@brightnkhoma/bright-auth-client 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/components/auth-wrapper.d.ts +6 -0
- package/dist/components/auth-wrapper.d.ts.map +1 -0
- package/dist/components/client-auth.d.ts +9 -0
- package/dist/components/client-auth.d.ts.map +1 -0
- package/dist/components/continue-with-google-button.d.ts +14 -0
- package/dist/components/continue-with-google-button.d.ts.map +1 -0
- package/dist/components/form.d.ts +5 -0
- package/dist/components/form.d.ts.map +1 -0
- package/dist/components/login-form.d.ts +40 -0
- package/dist/components/login-form.d.ts.map +1 -0
- package/dist/components/otp.d.ts +38 -0
- package/dist/components/otp.d.ts.map +1 -0
- package/dist/components/signup-form.d.ts +43 -0
- package/dist/components/signup-form.d.ts.map +1 -0
- package/dist/components/ui/button.d.ts +9 -0
- package/dist/components/ui/button.d.ts.map +1 -0
- package/dist/components/ui/card.d.ts +12 -0
- package/dist/components/ui/card.d.ts.map +1 -0
- package/dist/components/ui/field.d.ts +25 -0
- package/dist/components/ui/field.d.ts.map +1 -0
- package/dist/components/ui/input-otp.d.ts +12 -0
- package/dist/components/ui/input-otp.d.ts.map +1 -0
- package/dist/components/ui/input.d.ts +4 -0
- package/dist/components/ui/input.d.ts.map +1 -0
- package/dist/components/ui/label.d.ts +4 -0
- package/dist/components/ui/label.d.ts.map +1 -0
- package/dist/components/ui/separator.d.ts +4 -0
- package/dist/components/ui/separator.d.ts.map +1 -0
- package/dist/context/auth-context.d.ts +29 -0
- package/dist/context/auth-context.d.ts.map +1 -0
- package/dist/context/context.d.ts +2 -0
- package/dist/context/context.d.ts.map +1 -0
- package/dist/index.cjs +24 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.css +3 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +5714 -0
- package/dist/index.js.map +1 -0
- package/dist/lib/utils.d.ts +2 -0
- package/dist/lib/utils.d.ts.map +1 -0
- package/package.json +54 -4
- package/README.md +0 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["U","Z","h","OTPInput","React","OTPInputContext","React","React","React","_formatErrorMessage","React","noop","React","React","_formatErrorMessage","React","ownerWindow","React","Button","ButtonPrimitive","defaultLabels","_Fragment","FieldControlDataAttributes.valid","FieldControlDataAttributes.invalid","React","_formatErrorMessage","React","React","React","React","React","React","React","REASONS.none","Input","Field.Control","InputPrimitive","name","version","DB_NAME","DB_VERSION","_Fragment","defaultLabels","_Fragment","_Fragment","_Fragment","createAppContext","context","createContext","initialState","useContext","AuthContext","useTagAuth","TagAuthProvider","user","setUser","useState","form","setForm","confirmPassword","setConfirmPassword","loading","setLoading","error","setError","success","setSuccess","router","useRouter","isLogingIn","setIsLoggingIn","isResendingOtp","setIsResendingOtp","resendOtp","params","data","err","handleChange","prev","loginWithGoogle","token","refresh","login","props","me","t","setOtp","verififyOTP","onSignUp","otp","f","rest","P","U$1","out","s","i","o","PS","counts","DZ","a","z","GROUP_COUNT","customValidatorNames","edgeStart","labelStart","labelText","edgeTarget","N","sizes","c","k","e","nodeGroup","vlistPat","vlistOps","vlistRef","vlistGroup","nodeVlist","A","V","SETS","tails","prefix","AA","AG","AS","litAnchor","litGroup","litPool","poolText","poolOffsets","tailRef","nextRef","tail","r","adjGid","adjStart","adjTgt","patGid","patTgt","postfixLookupGroups","tables_generated_default","IS_JSC","EXTERNAL","DEAD","fnv","h","p","str","spanHash","len","q","m","createEngine","T","adjRow","maxAdj","n","CLAIM_PER_TOKEN","vgStart","l","postfixLookupSet","nodeCount","nodeHasLit","litMaxLen","litNoArb","c0","LIT_SIZE","litTable","off","idx","litProbe","input","anchor","entry","ok","cacheSize","options","RAW_PREFIX","FULL_PREFIX","FPL","vCustom","fn","validatorImpls","name","lengthUnitRegex","colorFunctionRegex","shadowRegex","imageRegex","aKind","aLabelS","aLabelE","aValS","aValE","isWordCode","isUniWS","analyzeArb","cl","spanEq","fractionRegex","tshirtRegex","isNumStr","v","spanIsNamedContainerQuery","c11","VKIND","VLABELS","VFALL","runValidator","op","L","orderSensitive","orderSensitiveModifiers","internSpan","imp","bucket","map","b","en","id","make","ctxByHash","ctxByCanon","nextCtxId","MAX_CTX","canonicalizeContext","mods","dB","dP","start","raw","canonical","result","segment","mod","key","important","dynByHash","nextDynId","MAX_DYN","newDynId","ID_LIMIT","TOKEN_TABLE","memoHash","memoStr","memoGid","memoCtx","memoFlags","memoTick","memoPut","slot","way0","ts","te","gid","ctxId","flags","memoReset","cap","tokI32","tokStart","tokEnd","tokGid","tokCtx","tokFlags","keep","growTokens","nf","ckptCap","ckptNode","ckptTail","claim0","CLAIM_TABLE","claimShift","claimKeys","claimEpochs","epoch","claimTest","ctx","resolveAt","endPos","bs","colon","nodeAt","ckptAt","tailStart","nodeId","tlen","g","vl","pat","vs","ve","g0","mergeClassList","tokenCount","totalTokenChars","sawNonSpaceWS","th","hitAt","pts","depthB","depthP","lastColon","lastSlash","pc","modStart","be","prefixShift","postfixEnd","feedStart","node","lp","le","pending","ckptTop","slashNode","slashCkpt","cc","arrived","es","ee","next","ls","nv","nt","endNode","hasPostfix","gidFull","didDrop","runStart","runEnd","u","DOOR_SIZE","door","doorBase","doorEpoch","cache","prevCache","cacheMap","prevCacheMap","cacheCount","doorMarks","rotateDoor","mergeCached","merged","hash","wasSeen","mergeCachedMap","seenBefore","mergeString","twJoin","resolveValue","arr","item","clsxMode","joinArgs","args","BUCKET_CAP","BUCKET_MISS_CAP","BUCKET_SKIP","CHURN_SIZE","wrapClsx","fresh","mergeUncached","argCache","prevArgCache","argCount","lastHit","churnKey","churnOwn","churnVal","churnTick","churnLookup","own","join","match3","v0","v1","v2","matchN","ea","vals","resolveArgs","nArgs","pred","probed","first","firstIdx","truthy","hasResolvedValue","hit","joined","entries","mergeSingleValue","value","lh","pa","la","instance","cn","Card","size","className","CardHeader","CardTitle","CardDescription","CardContent","CardFooter","kt","xt","Gt","U","ht","St","Et","bt","Pt","wt","_t","Tt","Ot","Lt","Ct","jt","Mt","w","x","M","I","y","S","R","G","ot","X","Nt","$t","Ft","rt","at","D","O","d","K","J","Y","$","B","_","E","C","Bt","Wt","W","et","At","vt","gt","Ht","Q","F","ct","it","H","j","st","lt","ut","It","dt","yt","tt","Dt","InputOTP","containerClassName","InputOTPGroup","InputOTPSlot","index","isActive","char","hasFakeCaret","InputOTPSeparator","MinusIcon","clsx","falsyToString","cx","cva","config","base","getVariantClassNames","variants","variantProp","variant","defaultVariantProp","defaultVariants","variantKey","propsWithoutUndefined","param","acc","cvClass","cvClassName","compoundVariantOptions","Label","createFormatErrorMessage","url","baseUrl","code","arg","formatErrorMessage","UNINITIALIZED","useRefWithInit","ref","init","initArg","useMergedRefs","forkRef","createForkRef","didChange","update","useMergedRefsN","didChangeN","refs","newRefs","cleanupCallbacks","refCleanup","cleanupCallback","majorVersion","isReactVersionAtLeast","reactVersionToCheck","getReactElementRef","element","reactElement","propsWithRef","mergeObjects","loggedMessages","createLogOnce","messages","message","output","severity","warn","NOOP","EMPTY_ARRAY","EMPTY_OBJECT","getStateAttributesProps","state","customMapping","customProps","resolveClassName","resolveStyle","style","EMPTY_PROPS","mergeProps","createInitialMergedProps","mergeInto","mergePropsN","isPropsGetter","inputProps","resolvePropsGetter","copyInitialProps","mutablyMergeInto","copiedProps","propName","propValue","isEventHandler","wrapEventHandler","externalProps","mergedProps","externalPropValue","mergeClassNames","mergeEventHandlers","code0","code1","code2","previousProps","theirHandler","ourHandler","event","isSyntheticEvent","baseUIEvent","handler","makeEventPreventable","theirClassName","ourClassName","useRenderElement","renderProp","componentProps","unwrapLazyRenderProp","outProps","useRenderElementProps","evaluateRenderProp","classNameProp","styleProp","enabled","stateProps","stateAttributesMapping","resolvedProps","resolveRenderFunctionProps","REACT_LAZY_TYPE","COMPONENT_IDENTIFIER_PATTERN","LOWERCASE_CHARACTER_PATTERN","render","unwrapped","warnIfRenderPropLooksLikeComponent","renderTag","functionName","renderFn","Tag","FieldGroup","fieldVariants","Field","orientation","FieldLabel","FieldDescription","hasWindow","getWindow","_node$ownerDocument","isHTMLElement","SafeReact","useInsertionEffect","useSafeInsertionEffect","useStableCallback","stable","createStableCallback","callback","assertNotCalled","useIsoLayoutEffect","CompositeRootContext","useCompositeRootContext","optional","useFocusableWhenDisabled","tabIndexProp","parameters","isFocusableComposite","composite","focusableWhenDisabled","isNonFocusableComposite","additionalProps","disabled","isNativeButton","ownerDocument","dispatchClickWithModifiers","target","sourceEvent","useButton","compositeProp","elementRef","compositeRootContext","isCompositeItem","focusableWhenDisabledProps","isButtonTag","isButtonElement","updateDisabled","externalOnClick","externalOnMouseDown","externalOnKeyUp","externalOnKeyDown","externalOnPointerDown","otherExternalProps","isCurrentTarget","currentTarget","isButton","isLink","isValidLinkElement","shouldClick","isEnterKey","isSpaceKey","role","isTextNavigationRole","elem","Button$1","elementProps","nativeButton","forwardedRef","buttonRef","getButtonProps","buttonVariants","Button","defaultLabels$2","Fragment","email","InputOTPForm","labelsProp","resending","labels","onSetOTP","onVerify","onResend","successMessage","otpGroupClasses","classNames","RefreshCwIcon","children","valid","invalid","DEFAULT_VALIDITY_STATE","DEFAULT_FIELD_ROOT_STATE","fieldValidityMapping","DEFAULT_FIELD_ROOT_CONTEXT","FieldRootContext","useFieldRootContext","FormContext","useFormContext","globalId","useGlobalId","defaultId","setDefaultId","idOverride","maybeReactUseId","useId","reactId","useBaseUiId","LabelableContext","useLabelableContext","useLabelableId","controlSourceRef","hasRegisteredRef","hadExplicitIdRef","unregisterControlId","registerControlId","nextId","resetControlId","controlId","activeElement","doc","useOnMount","EMPTY","Timeout","delay","useTimeout","timeout","useControlled","defaultProp","isControlled","controlled","valueState","setValue","defaultValue","serializeToDevModeString","newValue","seen","useRegisterFieldControl","sourceRef","source","getFormValueOverride","controlRef","registerFieldControl","useValueChanged","valueRef","onChangeCallback","onChange","none","createChangeEventDetails","canceled","allowPropagation","custom","customProperties","FieldControl","idProp","nameProp","valueProp","disabledProp","fieldState","fieldName","fieldDisabled","formElementRef","valueUnwrapped","serializedValue","getValueFromInput","validation","currentValue","setFilled","clearErrors","setDirty","validityData","inputRef","enterValidationTimeout","autoFocus","setFocused","labelId","inputValue","details","onValueChange","setTouched","validationMode","nextValue","submitCount","submitCountRef","Input$1","Input","getDefaultsFromPostinstall","stringToByteArray$1","byteArrayToString","pos","bytes","c1","c2","c3","c4","base64","byteToCharMap","webSafe","byte1","haveByte2","byte2","haveByte3","byte3","outByte1","outByte2","outByte3","outByte4","charToByteMap","byte4","DecodeBase64StringError","base64Encode","utf8Bytes","base64urlEncodeWithoutPadding","base64Decode","getGlobal","getDefaultsFromGlobal","getDefaultsFromEnvVariable","defaultsJsonString","getDefaultsFromCookie","match","decoded","getDefaults","getExperimentalSetting","getUA","\"userAgent\"","isMobileCordova","\"cordova\"","\"phonegap\"","\"PhoneGap\"","isCloudflareWorker","isBrowserExtension","runtime","isReactNative","\"product\"","isIE","ua","isIndexedDBAvailable","validateIndexedDBOpenable","preExist","DB_CHECK_NAME","request","resolve","ERROR_NAME","FirebaseError","customData","ErrorFactory","service","serviceName","errors","fullCode","template","replaceTemplate","ptr","end","isEmpty","obj","querystring","querystringParams","arrayVal","createSubscribe","proxy","ObserverProxy","executor","onNoObservers","observer","nextOrObserver","complete","implementsAnyMethods","noop","unsub","method","methods","getModularInstance","isCloudWorkstation","Component","instanceFactory","type","mode","multipleInstances","instances","LogLevel","\"DEBUG\"","\"VERBOSE\"","\"INFO\"","\"WARN\"","\"ERROR\"","\"SILENT\"","levelStringToEnum","\"debug\"","\"verbose\"","\"info\"","\"warn\"","\"error\"","\"silent\"","defaultLogLevel","ConsoleMethod","defaultLogHandler","logType","now","Logger","val","instanceOfAny","constructors","object","idbProxyableTypes","cursorAdvanceMethods","getIdbProxyableTypes","getCursorAdvanceMethods","cursorRequestMap","transactionDoneMap","transactionStoreNamesMap","transformCache","reverseTransformCache","promisifyRequest","promise","unlisten","wrap","reject","cacheDonePromiseForTransaction","tx","done","idbProxyTraps","prop","receiver","replaceTraps","wrapFunction","func","unwrap","storeNames","transformCachableValue","openDB","version","openPromise","upgrade","blocked","terminated","db","blocking","readMethods","writeMethods","cachedMethods","getMethod","targetFuncName","useIndex","isWrite","storeName","oldTraps","PlatformLoggerServiceImpl","container","isVersionServiceProvider","provider","logString","name$q","version$1","logger","name$p","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","name$10","version$2","PLATFORM_LOG_STRING","_apps","_serverApps","_components","_addComponent","component","app","_registerComponent","componentName","serverApp","_isFirebaseServerApp","ERROR_FACTORY","SDK_VERSION","registerVersion","library","libraryKeyOrName","libraryMismatch","versionMismatch","warning","DB_NAME$1","DB_VERSION$1","STORE_NAME","dbPromise","getDbPromise","oldVersion","readHeartbeatsFromIndexedDB","computeKey","idbGetError","writeHeartbeatsToIndexedDB","heartbeatObject","MAX_HEADER_BYTES","MAX_NUM_STORED_HEARTBEATS","HeartbeatServiceImpl","HeartbeatStorageImpl","agent","date","getUTCDateString","singleDateHeartbeat","earliestHeartbeatIdx","getEarliestHeartbeatIdx","extractHeartbeatsForHeader","headerString","heartbeatsToSend","unsentEntries","heartbeatsCache","heartbeatEntry","hb","countBytes","maxSize","idbHeartbeatObject","existingHeartbeatsObject","heartbeatsObject","heartbeats","earliestHeartbeatDate","registerCoreComponents","_prodErrorMap","prodErrorMap","_DEFAULT_AUTH_ERROR_FACTORY","logClient","_logWarn","msg","_logError","_fail","createErrorInternal","authOrCode","_createError","_errorWithCustomMessage","auth","_serverAppCurrentUserOperationNotSupportedError","_assertInstanceOf","constructorInstance","fullParams","_assert","assertion","debugFail","failure","debugAssert","_getCurrentUrl","_isHttpOrHttps","_getCurrentScheme","_isOnline","_getUserLanguage","navigatorLanguage","Delay","shortDelay","longDelay","_emulatorUrl","path","FetchProvider","fetchImpl","headersImpl","responseImpl","SERVER_ERROR_MAP","\"CREDENTIAL_MISMATCH\"","\"MISSING_CUSTOM_TOKEN\"","\"INVALID_IDENTIFIER\"","\"MISSING_CONTINUE_URI\"","\"INVALID_PASSWORD\"","\"MISSING_PASSWORD\"","\"INVALID_LOGIN_CREDENTIALS\"","\"EMAIL_EXISTS\"","\"PASSWORD_LOGIN_DISABLED\"","\"INVALID_IDP_RESPONSE\"","\"INVALID_PENDING_TOKEN\"","\"FEDERATED_USER_ID_ALREADY_LINKED\"","\"MISSING_REQ_TYPE\"","\"EMAIL_NOT_FOUND\"","\"RESET_PASSWORD_EXCEED_LIMIT\"","\"EXPIRED_OOB_CODE\"","\"INVALID_OOB_CODE\"","\"MISSING_OOB_CODE\"","\"CREDENTIAL_TOO_OLD_LOGIN_AGAIN\"","\"INVALID_ID_TOKEN\"","\"TOKEN_EXPIRED\"","\"USER_NOT_FOUND\"","\"TOO_MANY_ATTEMPTS_TRY_LATER\"","\"PASSWORD_DOES_NOT_MEET_REQUIREMENTS\"","\"INVALID_CODE\"","\"INVALID_SESSION_INFO\"","\"INVALID_TEMPORARY_PROOF\"","\"MISSING_SESSION_INFO\"","\"SESSION_EXPIRED\"","\"MISSING_ANDROID_PACKAGE_NAME\"","\"UNAUTHORIZED_DOMAIN\"","\"INVALID_OAUTH_CLIENT_ID\"","\"ADMIN_ONLY_OPERATION\"","\"INVALID_MFA_PENDING_CREDENTIAL\"","\"MFA_ENROLLMENT_NOT_FOUND\"","\"MISSING_MFA_ENROLLMENT_ID\"","\"MISSING_MFA_PENDING_CREDENTIAL\"","\"SECOND_FACTOR_EXISTS\"","\"SECOND_FACTOR_LIMIT_EXCEEDED\"","\"BLOCKING_FUNCTION_ERROR_RESPONSE\"","\"RECAPTCHA_NOT_ENABLED\"","\"MISSING_RECAPTCHA_TOKEN\"","\"INVALID_RECAPTCHA_TOKEN\"","\"INVALID_RECAPTCHA_ACTION\"","\"MISSING_CLIENT_TYPE\"","\"MISSING_RECAPTCHA_VERSION\"","\"INVALID_RECAPTCHA_VERSION\"","\"INVALID_REQ_TYPE\"","CookieAuthProxiedEndpoints","DEFAULT_API_TIMEOUT_MS","_addTidIfNecessary","_performApiRequest","_performFetchWithErrorHandling","customErrorMap","body","query","headers","fetchArgs","_getFinalTarget","errorMap","networkTimeout","NetworkTimeout","response","fetchFn","json","_makeTaggedError","serverErrorCode","serverErrorMessage","authError","\"message\"","_performSignInRequest","serverResponse","host","authInternal","finalTarget","errorParams","deleteAccount","getAccountInfo","utcTimestampToDateString","utcTimestamp","getIdTokenResult","userInternal","forceRefresh","claims","_parseToken","firebase","signInProvider","\"sign_in_provider\"","secondsStringToMilliseconds","\"sign_in_second_factor\"","seconds","algorithm","payload","signature","_tokenExpiresIn","parsedToken","_logoutIfInvalidated","bypassAuthState","isUserInvalidated","ProactiveRefresh","wasError","interval","UserMetadata","createdAt","lastLoginAt","metadata","_reloadWithoutSaving","coreAccount","newProviderData","extractProviderData","providerData","mergeProviderData","oldIsAnonymous","newIsAnonymous","isAnonymous","updates","reload","original","newData","providers","requestStsToken","\"grant_type\"","\"refresh_token\"","refreshToken","tokenApiHost","apiKey","revokeToken","StsTokenManager","expiresIn","idToken","oldToken","accessToken","expiresInSec","manager","expirationTime","stsTokenManager","assertStringOrUndefined","UserImpl","opt","uid","userInfo","newUser","tokensRefreshed","displayName","phoneNumber","photoURL","tenantId","_redirectEventId","plainObjectTokenManager","emailVerified","idTokenResponse","instanceCache","_getInstance","cls","InMemoryPersistence","inMemoryPersistence","_persistenceKeyName","appName","PersistenceUserManager","persistence","userKey","blob","newPersistence","currentUser","persistenceHierarchy","availablePersistences","selectedPersistence","userToMigrate","migrationHierarchy","_getBrowserName","userAgent","_isIEMobile","_isFirefox","_isBlackBerry","_isWebOS","_isSafari","_isChromeIOS","_isAndroid","matches","_isIOS","_isIOSStandalone","_isIE10","_isMobileBrowser","_getClientVersion","reportedPlatform","clientPlatform","reportedFrameworks","frameworks","AuthMiddlewareQueue","wrappedCallback","onAbort","nextUser","onAbortStack","beforeStateCallback","_getPasswordPolicy","MINIMUM_MIN_PASSWORD_LENGTH","PasswordPolicyImpl","responseOptions","status","password","minPasswordLength","maxPasswordLength","passwordChar","containsLowercaseCharacter","containsUppercaseCharacter","containsNumericCharacter","containsNonAlphanumericCharacter","AuthImpl","heartbeatServiceProvider","appCheckServiceProvider","Subscription","popupRedirectResolver","previouslyStoredUser","futureCurrentUser","needsTocheckMiddleware","redirectUserEventId","storedUserEventId","redirectResolver","userExtern","skipBeforeStateCallbacks","passwordPolicy","completed","unsubscribe","redirectManager","resolver","currentUid","cb","isUnsubscribed","subscription","originalMessage","action","framework","heartbeatsHeader","appCheckToken","appCheckTokenResult","_castAuth","externalJSProvider","_setExternalJSProvider","_loadJS","_gapiScriptUrl","_generateCallbackName","_initializeAuthInstance","deps","hierarchy","AuthCredential","providerId","signInMethod","signInWithIdp","IDP_REQUEST_URI$1","OAuthCredential","cred","postBody","\"id_token\"","\"access_token\"","\"oauth_token_secret\"","\"providerId\"","\"nonce\"","FederatedAuthProvider","languageCode","customOAuthParameters","BaseOAuthProvider","scope","FacebookAuthProvider","userCredential","tokenResponse","GoogleAuthProvider","oauthIdToken","oauthAccessToken","GithubAuthProvider","TwitterAuthProvider","secret","oauthTokenSecret","UserCredentialImpl","providerIdForResponse","MultiFactorError","operationType","_processCredentialSavingMfaContextIfNecessary","credential","_link$1","_reauthenticate","parsed","localId","_signInWithCredential","STORAGE_AVAILABLE_KEY","BrowserPersistenceClass","storageRetriever","_POLLING_INTERVAL_MS$1","IE10_LOCAL_STORAGE_SYNC_DELAY","BrowserLocalPersistence","poll","oldValue","triggerListeners","storedValue","listeners","listener","BrowserSessionPersistence","browserSessionPersistence","_generateEventId","random","digits","_window","_setWindowLocation","_withDefaultResolver","resolverOverride","IdpCredential","_signIn","_reauth","_link","AbstractPopupRedirectOperation","filter","urlResponse","_POLL_WINDOW_CLOSE_TIMEOUT","signInWithPopup","PopupOperation","eventId","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","domain","authorizedDomains","matchDomain","currentUrl","expected","ceUrl","hostname","protocol","escapedDomainPattern","NETWORK_TIMEOUT","resetUnloadedGapiModules","beacon","hint","loadGapi","loadGapiIframe","cbName","cachedGApiLoader","_loadGapi","PING_TIMEOUT","IFRAME_PATH","EMULATED_IFRAME_PATH","IFRAME_ATTRIBUTES","EID_FROM_APIHOST","getIframeUrl","eid","_openIframe","gapi","iframe","networkError","networkErrorTimer","clearTimerAndResolve","BASE_POPUP_OPTIONS","DEFAULT_WIDTH","DEFAULT_HEIGHT","TARGET_BLANK","FIREFOX_EMPTY_URL","AuthPopup","window","_open","top","height","left","width","optionsString","accum","openAsNewWindowIOS","newWin","el","click","WIDGET_PATH","EMULATOR_WIDGET_PATH","FIREBASE_APP_CHECK_FRAGMENT_ID","_getRedirectUrl","additionalParams","scopes","paramsDict","appCheckTokenFragment","getHandlerBase","WEB_STORAGE_SUPPORT_KEY","browserPopupRedirectResolver","authType","iframeEvent","AuthInterop","getVersionForPlatform","registerAuth","authInstance","getScriptParentElement","ContinueWithGoogleButton","useMemo","signIn","useCallback","Spinner","loadingLabel","hideIcon","GoogleIcon","label","defaultLabels$1","LoginForm","logprops","setProps","onLogin","defaultLabels","SignupForm","cardProps","AUTH_VIEWS","DEFAULT_VIEW","resolveView","normalized","AuthClient","useParams","searchParams","useSearchParams","view","redirectTo","initialEmail","isAuthenticated","timer","_auth","ForgotPasswordPlaceholder","ResetPasswordPlaceholder"],"sources":["../src/context/context.ts","../src/context/auth-context.ts","../src/components/auth-wrapper.tsx","../node_modules/cn/dist/tables.js","../node_modules/cn/dist/engine.js","../node_modules/cn/dist/index.js","../src/components/ui/card.tsx","../node_modules/input-otp/dist/index.mjs","../src/components/ui/input-otp.tsx","../node_modules/clsx/dist/clsx.mjs","../node_modules/class-variance-authority/dist/index.mjs","../src/components/ui/label.tsx","../node_modules/@base-ui/utils/formatErrorMessage.mjs","../node_modules/@base-ui/utils/useRefWithInit.mjs","../node_modules/@base-ui/utils/useMergedRefs.mjs","../node_modules/@base-ui/utils/reactVersion.mjs","../node_modules/@base-ui/utils/getReactElementRef.mjs","../node_modules/@base-ui/utils/mergeObjects.mjs","../node_modules/@base-ui/utils/createLogOnce.mjs","../node_modules/@base-ui/utils/warn.mjs","../node_modules/@base-ui/utils/empty.mjs","../node_modules/@base-ui/react/internals/getStateAttributesProps.mjs","../node_modules/@base-ui/react/utils/resolveClassName.mjs","../node_modules/@base-ui/react/utils/resolveStyle.mjs","../node_modules/@base-ui/react/merge-props/mergeProps.mjs","../node_modules/@base-ui/react/internals/useRenderElement.mjs","../src/components/ui/field.tsx","../node_modules/@floating-ui/utils/dist/floating-ui.utils.dom.mjs","../node_modules/@base-ui/utils/safeReact.mjs","../node_modules/@base-ui/utils/useStableCallback.mjs","../node_modules/@base-ui/utils/error.mjs","../node_modules/@base-ui/utils/useIsoLayoutEffect.mjs","../node_modules/@base-ui/react/internals/composite/root/CompositeRootContext.mjs","../node_modules/@base-ui/react/utils/useFocusableWhenDisabled.mjs","../node_modules/@base-ui/utils/owner.mjs","../node_modules/@base-ui/react/utils/dispatchClickWithModifiers.mjs","../node_modules/@base-ui/react/internals/use-button/useButton.mjs","../node_modules/@base-ui/react/button/Button.mjs","../src/components/ui/button.tsx","../src/components/otp.tsx","../node_modules/@base-ui/react/field/control/FieldControlDataAttributes.mjs","../node_modules/@base-ui/react/internals/field-constants/constants.mjs","../node_modules/@base-ui/react/internals/field-root-context/FieldRootContext.mjs","../node_modules/@base-ui/react/internals/form-context/FormContext.mjs","../node_modules/@base-ui/utils/useId.mjs","../node_modules/@base-ui/react/internals/useBaseUiId.mjs","../node_modules/@base-ui/react/internals/labelable-provider/LabelableContext.mjs","../node_modules/@base-ui/react/internals/labelable-provider/useLabelableId.mjs","../node_modules/@base-ui/utils/shadowDom.mjs","../node_modules/@base-ui/utils/useOnMount.mjs","../node_modules/@base-ui/utils/useTimeout.mjs","../node_modules/@base-ui/utils/useControlled.mjs","../node_modules/@base-ui/react/internals/field-register-control/useRegisterFieldControl.mjs","../node_modules/@base-ui/react/internals/useValueChanged.mjs","../node_modules/@base-ui/react/internals/reason-parts.mjs","../node_modules/@base-ui/react/internals/createBaseUIEventDetails.mjs","../node_modules/@base-ui/react/field/control/FieldControl.mjs","../node_modules/@base-ui/react/input/Input.mjs","../src/components/ui/input.tsx","../node_modules/@firebase/util/dist/postinstall.mjs","../node_modules/@firebase/util/dist/index.esm.js","../node_modules/@firebase/component/dist/esm/index.esm.js","../node_modules/@firebase/logger/dist/esm/index.esm.js","../node_modules/idb/build/wrap-idb-value.js","../node_modules/idb/build/index.js","../node_modules/@firebase/app/dist/esm/index.esm.js","../node_modules/@firebase/auth/dist/esm/index-LY22yodV.js","../src/components/continue-with-google-button.tsx","../src/components/login-form.tsx","../src/components/signup-form.tsx","../src/components/client-auth.tsx"],"sourcesContent":["import { createContext, useContext } from \"react\"\r\nexport const createAppContext = <T>(initialState : T)=>{\r\n const context = createContext(initialState);\r\n const hook = ()=> useContext(context);\r\n return [context,hook] as const;\r\n}","import { ChangeEvent, Dispatch, FormEvent, SetStateAction } from \"react\";\r\n import { LoginProps, User } from \"@brightnkhoma/tag-auth\";\r\nimport { createAppContext } from \"./context.js\";\r\n\r\ninterface Props{\r\n confirmPassword: string;\r\n setConfirmPassword: Dispatch<SetStateAction<string>>;\r\n form: any;\r\n setForm: Dispatch<any>;\r\n loading: boolean;\r\n setLoading: Dispatch<SetStateAction<boolean>>;\r\n error: string | null;\r\n setError: Dispatch<SetStateAction<string | null>>;\r\n success: boolean;\r\n setSuccess: Dispatch<SetStateAction<boolean>>;\r\n handleChange: (e: ChangeEvent<HTMLInputElement, Element>) => void;\r\n onSignUp: (e: FormEvent<Element>) => Promise<void>;\r\n setOtp: (otp: string) => void;\r\n verififyOTP: () => Promise<void>;\r\n isLogingIn: boolean;\r\n setIsLoggingIn: Dispatch<SetStateAction<boolean>>;\r\n login: (props: LoginProps) => Promise<void>;\r\n refresh: () => Promise<void>;\r\n user: User | null;\r\n isResendingOtp: boolean;\r\n resendOtp: () => Promise<void>;\r\n loginWithGoogle: (token: string) => Promise<void>\r\n\r\n};\r\n\r\nconst initialState : Props = {\r\n confirmPassword: \"\",\r\n setConfirmPassword: function (value: SetStateAction<string>): void {\r\n throw new Error(\"Function not implemented.\");\r\n },\r\n form: undefined,\r\n setForm: function (value: any): void {\r\n throw new Error(\"Function not implemented.\");\r\n },\r\n loading: false,\r\n setLoading: function (value: SetStateAction<boolean>): void {\r\n throw new Error(\"Function not implemented.\");\r\n },\r\n error: null,\r\n setError: function (value: SetStateAction<string | null>): void {\r\n throw new Error(\"Function not implemented.\");\r\n },\r\n success: false,\r\n setSuccess: function (value: SetStateAction<boolean>): void {\r\n throw new Error(\"Function not implemented.\");\r\n },\r\n handleChange: function (e: ChangeEvent<HTMLInputElement, Element>): void {\r\n throw new Error(\"Function not implemented.\");\r\n },\r\n onSignUp: function (e: FormEvent<Element>): Promise<void> {\r\n throw new Error(\"Function not implemented.\");\r\n },\r\n setOtp: function (otp: string): void {\r\n throw new Error(\"Function not implemented.\");\r\n },\r\n verififyOTP: function (): Promise<void> {\r\n throw new Error(\"Function not implemented.\");\r\n },\r\n isLogingIn: false,\r\n setIsLoggingIn: function (value: SetStateAction<boolean>): void {\r\n throw new Error(\"Function not implemented.\");\r\n },\r\n login: function (props: LoginProps): Promise<void> {\r\n throw new Error(\"Function not implemented.\");\r\n },\r\n refresh: function (): Promise<void> {\r\n throw new Error(\"Function not implemented.\");\r\n },\r\n user: null,\r\n isResendingOtp: false,\r\n resendOtp: function (): Promise<void> {\r\n throw new Error(\"Function not implemented.\");\r\n },\r\n loginWithGoogle: function (token: string): Promise<void> {\r\n throw new Error(\"Function not implemented.\");\r\n }\r\n};\r\n\r\nexport const [AuthContext, useTagAuth]= createAppContext(initialState);","\"use client\";\r\n\r\nimport { AuthContext } from \"../context/auth-context.js\";\r\nimport { useState } from \"react\";\r\nimport { LoginProps, SignUpProps, User } from \"@brightnkhoma/tag-auth\";\r\nimport { AppRouterInstance } from \"next/dist/shared/lib/app-router-context.shared-runtime.js\";\r\n\r\n\r\nexport const TagAuthProvider = ({children,useRouter} : {children : React.ReactNode, useRouter(): AppRouterInstance})=>{\r\n const [user, setUser] = useState<User | null>(null);\r\n\r\nconst [form, setForm] = useState<SignUpProps>({\r\n email: \"\",\r\n name: \"\",\r\n password: \"\",userName : \"\",\r\n otp : \"\"\r\n })\r\n const [confirmPassword, setConfirmPassword] = useState(\"\")\r\n const [loading, setLoading] = useState(false)\r\n const [error, setError] = useState<string | null>(null)\r\n const [success, setSuccess] = useState(false)\r\n const router = useRouter();\r\n const [isLogingIn, setIsLoggingIn] = useState<boolean>(false);\r\n const [isResendingOtp, setIsResendingOtp] = useState<boolean>(false);\r\n\r\n\r\n const resendOtp = async()=>{\r\n try {\r\n setIsResendingOtp(true);\r\n const params = new URLSearchParams({\r\n type : \"resend_otp\"\r\n })\r\n const res = await fetch(`/api/auth?${params.toString()}`);\r\n const data = await res.json();\r\n if(!data.success){\r\n throw new Error(data.message)\r\n }\r\n \r\n } catch (err) {\r\n setError(\r\n err instanceof Error ? err.message : \"Something went wrong. Try again.\"\r\n ) \r\n }finally{\r\n setIsResendingOtp(false)\r\n }\r\n }\r\n \r\n\r\n const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {\r\n setForm((prev: any) => ({ ...prev, [e.target.id]: e.target.value }))\r\n }\r\n\r\n const loginWithGoogle = async(token : string)=>{\r\n try {\r\n if(!token) return;\r\n setIsLoggingIn(true);\r\n const params = new URLSearchParams({\r\n type: \"google\",\r\n google : token\r\n });\r\n\r\n const res = await fetch(`/api/auth?${params.toString()}`);\r\n const data = await res.json();\r\n\r\n if (!data.success) {\r\n throw new Error(\r\n data.message ?? \"Login failed, please try again later\"\r\n );\r\n }\r\n\r\n setSuccess(true);\r\n await refresh(true);\r\n router.replace(\"/\");\r\n } catch (err) {\r\n console.log(err);\r\n setError(\r\n err instanceof Error\r\n ? err.message\r\n : \"Something went wrong. Try again.\"\r\n );\r\n }finally{\r\n setIsLoggingIn(false)\r\n }\r\n }\r\n\r\nconst login = async (props: LoginProps) => {\r\n try {\r\n setIsLoggingIn(true);\r\n\r\n const params = new URLSearchParams({\r\n ...props,\r\n type: \"login\",\r\n });\r\n\r\n const res = await fetch(`/api/auth?${params.toString()}`);\r\n\r\n const data = await res.json();\r\n\r\n if (!data.success) {\r\n throw new Error(\r\n data.message ?? \"Login failed, please try again later\"\r\n );\r\n }\r\n\r\n setSuccess(true);\r\n await refresh(true);\r\n router.replace(\"/\");\r\n } catch (err) {\r\n setError(\r\n err instanceof Error\r\n ? err.message\r\n : \"Something went wrong. Try again.\"\r\n );\r\n } finally {\r\n setIsLoggingIn(false);\r\n }\r\n};\r\n\r\n \r\n const me = async(t : boolean = false)=>{\r\n try {\r\n const params = new URLSearchParams({\r\n type : \"me\"\r\n })\r\n const res = await fetch(`/api/auth?${params.toString()}`);\r\n const data = await res.json();\r\n \r\n if(!data.success){\r\n throw new Error(data.message)\r\n }\r\n setUser(data.item ?? null)\r\n \r\n \r\n console.log(\"user\",{user : data.item,_tokens : []});\r\n \r\n } catch (err) {\r\n setError(\r\n err instanceof Error ? err.message : \"Something went wrong. Try again.\"\r\n )\r\n if(t)throw new Error( err instanceof Error ? err.message : \"Something went wrong. Try again.\" )\r\n \r\n }\r\n }\r\n\r\n const refresh = (t : boolean = false)=>me(t);\r\n\r\n const setOtp = (otp : string) => {\r\n setForm((prev: any) => ({ ...prev, otp }))\r\n }\r\n\r\n const verififyOTP = async()=>{\r\n if(!form.otp) return;\r\n return await onSignUp(undefined,true)\r\n }\r\n\r\n const onSignUp = async (e?: React.FormEvent, otp?: boolean) => { if (e) e.preventDefault(); setError(null); setSuccess(false); if (!otp) { if (form.password.length < 8) { setError(\"Password must be at least 8 characters long.\"); return; } if (form.password !== confirmPassword) { setError(\"Passwords do not match.\"); return; } } try { setLoading(true); let f = { ...form }; if (!otp) { const { otp, ...rest } = f; f = rest; } const res = await fetch(\"/api/auth\", { method: \"POST\", headers: { \"Content-Type\": \"application/json\", }, body: JSON.stringify(f), }); const data = await res.json(); if (!data.success) { throw new Error(data.message); } setSuccess(true); setForm({ email: \"\", name: \"\", password: \"\", userName: \"\", otp: \"\", }); setConfirmPassword(\"\"); router.push(otp ? \"/auth/login\" : \"/auth/verify\"); } catch (err) { setError( err instanceof Error ? err.message : \"Something went wrong. Try again.\" ); } finally { setLoading(false); } };\r\n\r\n\r\n return(\r\n <AuthContext.Provider value={{confirmPassword,error,form,handleChange,loading,onSignUp,setConfirmPassword,setError,setForm,setLoading,setSuccess,success,setOtp,verififyOTP,isLogingIn,login,setIsLoggingIn,refresh,isResendingOtp,user,resendOtp,loginWithGoogle}}>\r\n {children}\r\n </AuthContext.Provider>\r\n )\r\n}","//#region src/tables.generated.ts\nconst P = 48;\nconst U = (s, o = 0) => {\n\tconst out = new Int32Array(s.length);\n\tfor (let i = 0; i < s.length; i++) out[i] = s.charCodeAt(i) - P - o;\n\treturn out;\n};\nconst PS = (counts) => {\n\tconst out = new Int32Array(counts.length + 1);\n\tfor (let i = 0; i < counts.length; i++) out[i + 1] = out[i] + counts[i];\n\treturn out;\n};\nconst DZ = (s) => {\n\tconst out = new Int32Array(s.length);\n\tlet a = 0;\n\tfor (let i = 0; i < s.length; i++) {\n\t\tconst z = s.charCodeAt(i) - P;\n\t\ta += z >>> 1 ^ -(z & 1);\n\t\tout[i] = a;\n\t}\n\treturn out;\n};\nconst GROUP_COUNT = 384;\nconst customValidatorNames = [];\nconst edgeStart = PS(U(\"E0500002005282000000002000150000020021820000011200000003022202000300004200120000200420001200021200301200010400162000010000220021010:2192001200220012000220012000200200200400010200040000000000400200108200110100000022010313000162002000020020012020080213000228200000000082000000000120002000120020020040101020300130001001010\"));\nconst labelStart = PS(U(\":11111111211111119311546544411119731869:671397415686432441111111111161114151214313433415:78311132233313187211117221449443411141111151152226611131111112212518142224214215421421542142424242516171151615616347111111111197911327451111111111111111111113134714133513411111311111111111111111111112444411111342312715245411117:3\"));\nconst labelText = \"@containerabcdefghinlmoprstunderlineviawzccentlignnimatespectuto-colsrowsaglorightnessckdrop-sisbcontrastfiltergrayscalehue-rotateinvertopacityslurrightnessaturateepia-coniclinearpositionradialsizeockurrderttom-belrstxyespacing-xyaretoursorlnt-umnsendspantartainentrasteividerop-shadowurationcorationlay-xyasendillexontromlter-featuresstretchapr-xyayscaleidow-colsrowsue-rotatedentlinesetvert-beringsxyeshadoweiadingftnest-clamp-imageabein-lrstxyskx--b-coniclpositionrsizet-x-y-fromto-fromto-inearfromto-fromto-adialfromto-fromtofromtofromtofromtoblockhinlinew-screenesblockhinlinewbjectpacityrutlinederigin-offsetbelrstxyesrspective-originaceholderioghtng-offsettateundedw-xyz-belrstlreseslr-endspantartaturatecepiahizekewpace-taleroll-xyz-barmpbelrstxyesbelrstxyes-thumbrackadowrink-xyxyartrokeabextora-shadowpckingnsformitionlate-xyz-offsetill-changeoom\";\nconst edgeTarget = (() => {\n\tconst N = edgeStart.length - 1;\n\tconst sizes = new Int32Array(N);\n\tfor (let i = N - 1; i >= 0; i--) {\n\t\tlet s = 1;\n\t\tlet c = i + 1;\n\t\tfor (let k = edgeStart[i]; k < edgeStart[i + 1]; k++) {\n\t\t\ts += sizes[c];\n\t\t\tc += sizes[c];\n\t\t}\n\t\tsizes[i] = s;\n\t}\n\tconst out = new Int32Array(edgeStart[N]);\n\tlet e = 0;\n\tfor (let i = 0; i < N; i++) {\n\t\tlet c = i + 1;\n\t\tfor (let k = edgeStart[i]; k < edgeStart[i + 1]; k++) {\n\t\t\tout[e++] = c;\n\t\t\tc += sizes[c];\n\t\t}\n\t}\n\treturn out;\n})();\nconst nodeGroup = U(\"02000000000000900<=0?000B000F00F00ŏI0J0LNPRTVX0000]_a00000000000000000000000rst0000000zŏ00000000000
ŏ0000000ŏ00000000000000000000000000000000000000000000000000000000000000Ë000000000000000000000Þ000000000000000000ð0000000ø0ùúûüýþÿĀāĂ㥹Ć000000000000000000000000000000000000000000ħ0ĨĪ00000000000000000000ļĽ00000Ŭ000000\", 1);\nconst vlistPat = PS(U(\"123333359346463635126536711576\"));\nconst vlistOps = U(\"93203242332583253248325D>E?F@03263243255B:032523853:0325B:8GA032542H<C=12727B:0328432553;D>E?3257D>032585:0325B:;0328B:032\");\nconst vlistRef = U(\"012113445661666666789111:5;;;;;;;;444;;;:62999<1161=62>>?61:21@ABCD4446996:64E:::;:?::64:F114GHHIHHHHIHH1HH1HH1HHHHHH::EEJ4444::EE4444441691;644444114244444:;K6666555555555555555999666664444444444444444444444226?6:66644L9M?D:111::::6DE199\");\nconst vlistGroup = DZ(\"020200202020020020020020020020200200200200200200200002020202001003040106000200200200200200200200200200200200200200200200200200200200200200200200200200200200020020020020020020002020200202002002002002002002002002002020002002020020200220200200200200200200200200200200020020020000200020002000200200200020020020002000200200200020020202002020202000200200020022000200200020020002002000200220002002000200W0Z00020020002002020002002000200g0j0002002000200200020020002002000200200020020002000200002000002002002002002000200020000200002002002002002002002020020020200200200200200200200200202020020020020020020020020002002002020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020020002002002002002002000200200200200200200200200200020202020002000200020002002002002000020200200\");\nconst nodeVlist = (() => {\n\tconst out = (/* @__PURE__ */ new Int32Array(319)).fill(-1);\n\tconst A = DZ(\"02422242:222222242224222242442222222422222244442242226224222426222422442462222422622222222626222462242622422622422424242422222222422222222242422222222222222222622442224222222222222224424442262222222222222222222226224222424242422224422422422222\");\n\tconst V = DZ(\"02222222222222222222202222222222222222222222221422222222222222222222222222222222222Y\\\\222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222221422222222222222222222222222222222222222Ŀł222222222222222222\");\n\tfor (let i = 0; i < A.length; i++) out[A[i]] = V[i];\n\treturn out;\n})();\nconst SETS = \"container |break-after- all auto avoid avoid-page column left page right|break-before- all auto avoid avoid-page column left page right|break-inside-a uto void void-column void-page|box-decoration- clone slice|box- border content| contents flow-root hidden table table-caption table-cell table-column table-column-group table-footer-group table-header-group table-row table-row-group| not-sr-only sr-only|float- end left none right start|clear- both end left none right start|isolat e ion-auto|overflow- auto clip hidden scroll visible|overflow-x- auto clip hidden scroll visible|overflow-y- auto clip hidden scroll visible|overscroll- auto contain none|overscroll-x- auto contain none|overscroll-y- auto contain none| absolute fixed relative static sticky| collapse invisible visible|justify- around baseline between center center-safe end end-safe evenly normal start stretch|justify-items- center center-safe end end-safe normal start stretch|justify-self- auto center center-safe end end-safe start stretch|items- baseline baseline-last center center-safe end end-safe start stretch|self- auto baseline baseline-last center center-safe end end-safe start stretch|place-content- around baseline between center center-safe end end-safe evenly start stretch|place-items- baseline center center-safe end end-safe start stretch|place-self- auto center center-safe end end-safe start stretch| antialiased subpixel-antialiased| italic not-italic|normal-nums |ordinal |slashed-zero | lining-nums oldstyle-nums| proportional-nums tabular-nums| diagonal-fractions stacked-fractions| no-underline overline| capitalize lowercase normal-case uppercase|truncate |whitespace- break-spaces normal nowrap pre pre-line pre-wrap|break- all keep normal words|wrap- anywhere break-word normal|hyphens- auto manual none|mix-blend- color color-burn color-dodge darken difference exclusion hard-light hue lighten luminosity multiply normal overlay plus-darker plus-lighter saturation screen soft-light|table- auto fixed|caption- bottom top|backface- hidden visible|appearance- auto none|scheme- dark light light-dark normal only-dark only-light|field-sizing- content fixed|pointer-events- auto none|resize -none -x -y|snap- align-none center end start|snap- always normal|snap- both none x y|snap- mandatory proximity|touch- auto manipulation none|touch-pan- left right x|touch-pan- down up y|touch-pinch-zoom |select- all auto none text|forced-color-adjust- auto none| normal size| baseline bottom middle sub super text-bottom text-top top| bounce none ping pulse spin| auto square video| auto fr max min px|none | auto full px| fixed local scroll|clip- border content padding text|origin- border content padding| bottom bottom-left bottom-right center left left-bottom left-top right right-bottom right-top top top-left top-right| no-repeat repeat repeat-round repeat-space repeat-x repeat-y| auto contain cover| gradient-to-b gradient-to-bl gradient-to-br gradient-to-l gradient-to-r gradient-to-t gradient-to-tl gradient-to-tr none|blend- color color-burn color-dodge darken difference exclusion hard-light hue lighten luminosity multiply normal overlay saturation screen soft-light|to- b bl br l r t tl tr| auto dvh fit full lh lvh max min px screen svh| dashed dotted double hidden none solid| collapse separate|px |auto |full | content none strict| inline-size size|layout |paint |style | around baseline between center center-safe end end-safe evenly normal start stretch| alias all-scroll auto cell col-resize context-menu copy crosshair default e-resize ew-resize grab grabbing help move n-resize ne-resize nesw-resize no-drop none not-allowed ns-resize nw-resize nwse-resize pointer progress row-resize s-resize se-resize sw-resize text vertical-text w-resize wait zoom-in zoom-out| dashed dotted double solid wavy| auto from-font|reverse |initial | in in-out initial linear out| col col-reverse row row-reverse| nowrap wrap wrap-reverse| auto initial none| black bold extrabold extralight light medium normal semibold thin| condensed expanded extra-condensed extra-expanded normal semi-condensed semi-expanded ultra-condensed ultra-expanded|flow- col col-dense dense row row-dense| none subgrid| auto dvh dvw fit full lh lvh lvw max min px screen svh svw| block flex grid table| auto dvw fit full lvw max min px screen svw| loose none normal px relaxed snug tight|through |item | inside outside| decimal disc none| auto px| clip-border clip-content clip-fill clip-padding clip-stroke clip-view no-clip| add exclude intersect subtract| alpha luminance match|origin- border content fill padding stroke view|type- alpha luminance| circle ellipse| closest-corner closest-side farthest-corner farthest-side|at- bottom bottom-left bottom-right center left left-bottom left-top right right-bottom right-top top top-left top-right| dvh fit full lh lvh max min none px screen svh| auto dvh dvw fit full lh lvh lvw max min none px screen svh svw| dvw fit full lvw max min none px screen svw| auto dvh dvw fit full lvh lvw max min none prose px svh svw| auto dvh dvw fit full lvh lvw max min none px screen svh svw| contain cover fill none scale-down| first last none| distant dramatic midrange near none normal|inset | full none|3d | auto smooth|gutter- auto both stable| auto none thin| inner none| auto dvh dvw fit full lvh lvw max min px svh svw|base | center end justify left right start| clip ellipsis| balance nowrap pretty wrap| normal tight tighter wide wider widest| cpu gpu none| 3d flat| all colors none opacity shadow transform| discrete normal| full px| auto dvh dvw fit full lvh lvw max min px screen svh svw| auto contents scroll transform\".split(\"|\").map((s) => {\n\tconst tails = s.split(\" \");\n\tconst prefix = tails.shift();\n\tfor (let i = 0; i < tails.length; i++) tails[i] = prefix + tails[i];\n\treturn tails;\n});\nconst AA = DZ(\"0000000000000000000000000000000000000000000000000000000000000262242:6@200000006:240B428:4422400002046044222426220026642642462026224222824220022400000000\\\\00N222422242222222224062242222222422226264222422222222222222442804222422222222222222222222220<4<0204260002444020204224422\");\nconst AG = DZ(\"ɠ222222222222222222222222222222222222222222222222222222222222˕4222226>ʶ22ʷʺʷ2ʸʷ42ʴ2ʓ22>621422ɶ222ɹɼɷɺɷɺ22ɱ42222ɨ2ɧ26622ɘɓ244ƸƵ222]d24242ǖǓƚÄȫ2263ȨȥȨ2222222ǣ222222222222222222ǂƽ2ƾƵ2222222422222ƜƑ22222222222222222222144Ŧţ22Ţş222222222222222222222ĸ2ı68ĦģĦɡŰ4Ġ«®ĝ822ĔđĔ2ē2222622\");\nconst AS = DZ(\"02222222222222222222222222222222222222222222222222222222222222222202022222222222EH2200IL021042222Y\\\\222IL0cf2e10j2222U00X202[^2y0000120|{~22
:22|22222222222G000qOVI00000}2>40000B00000I¨©000¬00000000000000021M®00°000000000000000000000222HGHa1º222¿2À2222ÉÌ000°2±\");\nconst litAnchor = /* @__PURE__ */ new Int32Array(995);\nconst litGroup = /* @__PURE__ */ new Int32Array(995);\nconst litPool = /* @__PURE__ */ new Int32Array(995);\nlet poolText = \"\";\nconst poolOffsets = /* @__PURE__ */ new Int32Array(1038);\n{\n\tconst tailRef = /* @__PURE__ */ new Map();\n\tlet nextRef = 0;\n\tlet e = 0;\n\tfor (let i = 0; i < AA.length; i++) for (const tail of SETS[AS[i]]) {\n\t\tlet r = tailRef.get(tail);\n\t\tif (r === void 0) {\n\t\t\tr = nextRef++;\n\t\t\ttailRef.set(tail, r);\n\t\t\tpoolOffsets[r * 2] = poolText.length;\n\t\t\tpoolOffsets[r * 2 + 1] = tail.length;\n\t\t\tpoolText += tail;\n\t\t}\n\t\tlitAnchor[e] = AA[i];\n\t\tlitGroup[e] = AG[i];\n\t\tlitPool[e] = r;\n\t\te++;\n\t}\n}\nconst adjGid = DZ(\"0b2N:222@R>F@286¦2@H2D266226FB22B2>BD\\\\6N22222Z222D222p\");\nconst adjStart = PS(U(\"1::24444432:442:44:44>222222:44:4421322511111311111114\"));\nconst adjTgt = DZ(\"24A;33N=C@H4A;33N=C@<27;83:;8393NQ:3NQʰ222ˉºŴŽ2R2=18cƴÅŇ=cĞÛC1ƈǝȈ:ħ25=11D3A@4=<1;1DEr25;11B3?<6;:371BCn9@7=<8192>2E121@9@EHE@9>2T25511<398454131<=V25511<398454131<=ƧNž2Đå242L222290000f22500ɛ000ǘ222\");\nconst patGid = U(\"ij\");\nconst patTgt = U(\"\");\nconst postfixLookupGroups = U(\"1\");\nconst orderSensitiveModifiers = \"* ** after backdrop before details-content file first-letter first-line marker placeholder selection\";\nvar tables_generated_default = {\n\tGROUP_COUNT,\n\tcustomValidatorNames,\n\tedgeStart,\n\tlabelStart,\n\tlabelText,\n\tedgeTarget,\n\tnodeGroup,\n\tnodeVlist,\n\tvlistPat,\n\tvlistOps,\n\tvlistRef,\n\tvlistGroup,\n\tlitAnchor,\n\tlitGroup,\n\tlitPool,\n\tpoolOffsets,\n\tpoolText,\n\tadjGid,\n\tadjStart,\n\tadjTgt,\n\tpatGid,\n\tpatTgt,\n\tpostfixLookupGroups,\n\torderSensitiveModifiers\n};\n\n//#endregion\nexport { tables_generated_default as default };","//#region src/engine.ts\nconst IS_JSC = \"line\" in /* @__PURE__ */ new Error();\nconst EXTERNAL = -1;\nconst DEAD = -1;\nconst fnv = (str, s, e) => {\n\tlet h = 2166136261;\n\tfor (let p = s; p < e; p++) h = Math.imul(h ^ str.charCodeAt(p), 16777619);\n\treturn h;\n};\nconst spanHash = (str, s, e) => {\n\tconst len = e - s;\n\tlet h = Math.imul(len, 2654435761) ^ str.charCodeAt(s);\n\tif (len > 3) {\n\t\tconst q = len >> 2;\n\t\tconst m = len >> 1;\n\t\th = Math.imul(h ^ str.charCodeAt(s + 1) << 8 ^ str.charCodeAt(s + 2) << 16 ^ str.charCodeAt(s + q), 2246822507);\n\t\th = Math.imul(h ^ str.charCodeAt(s + m) << 8 ^ str.charCodeAt(s + m + q) << 16 ^ str.charCodeAt(e - 3), 3266489909);\n\t\th ^= str.charCodeAt(e - 2) << 8 ^ str.charCodeAt(e - 1) << 16;\n\t\tfor (let p = s + 3, q = e - 4; p < s + 8 && p < q; p++, q--) h = Math.imul(h ^ str.charCodeAt(p) ^ str.charCodeAt(q) << 8, 16777619);\n\t}\n\treturn h ^ h >>> 15 | 0;\n};\nconst createEngine = (T, validatorImpls, options = {}) => {\n\tconst { GROUP_COUNT, edgeStart, labelStart, labelText, edgeTarget, nodeGroup, nodeVlist, vlistPat, vlistOps, vlistRef, vlistGroup, litAnchor, litGroup, litPool, poolOffsets, poolText, adjGid, adjStart, adjTgt, patGid, patTgt, postfixLookupGroups, customValidatorNames, orderSensitiveModifiers } = T;\n\tconst adjRow = new Int32Array(GROUP_COUNT).fill(-1);\n\tfor (let i = 0; i < adjGid.length; i++) adjRow[adjGid[i]] = i;\n\tlet maxAdj = 0;\n\tfor (let r = 0; r + 1 < adjStart.length; r++) {\n\t\tconst n = adjStart[r + 1] - adjStart[r];\n\t\tif (n > maxAdj) maxAdj = n;\n\t}\n\tlet CLAIM_PER_TOKEN = 32;\n\twhile (CLAIM_PER_TOKEN < 2 * (1 + maxAdj + patGid.length)) CLAIM_PER_TOKEN <<= 1;\n\tconst vgStart = new Int32Array(vlistRef.length + 1);\n\tfor (let l = 0; l < vlistRef.length; l++) vgStart[l + 1] = vgStart[l] + vlistPat[vlistRef[l] + 1] - vlistPat[vlistRef[l]];\n\tconst postfixLookupSet = new Uint8Array(GROUP_COUNT);\n\tfor (let i = 0; i < postfixLookupGroups.length; i++) postfixLookupSet[postfixLookupGroups[i]] = 1;\n\tconst nodeCount = edgeStart.length - 1;\n\tconst nodeHasLit = new Uint8Array(nodeCount);\n\tlet litMaxLen = 0;\n\tlet litNoArb = true;\n\tfor (let i = 0; i < litAnchor.length; i++) {\n\t\tnodeHasLit[litAnchor[i]] = 1;\n\t\tconst len = poolOffsets[litPool[i] * 2 + 1];\n\t\tif (len > litMaxLen) litMaxLen = len;\n\t\tconst c0 = poolText.charCodeAt(poolOffsets[litPool[i] * 2]);\n\t\tif (c0 === 91 || c0 === 40) litNoArb = false;\n\t}\n\tlet LIT_SIZE = 1;\n\twhile (LIT_SIZE < litAnchor.length * 2) LIT_SIZE <<= 1;\n\tconst litTable = new Int32Array(LIT_SIZE).fill(-1);\n\tfor (let i = 0; i < litAnchor.length; i++) {\n\t\tconst off = poolOffsets[litPool[i] * 2];\n\t\tlet idx = (fnv(poolText, off, off + poolOffsets[litPool[i] * 2 + 1]) ^ Math.imul(litAnchor[i], 2654435761) | 0) & LIT_SIZE - 1;\n\t\twhile (litTable[idx] !== -1) idx = idx + 1 & LIT_SIZE - 1;\n\t\tlitTable[idx] = i;\n\t}\n\tconst litProbe = (anchor, input, s, e) => {\n\t\tlet idx = (fnv(input, s, e) ^ Math.imul(anchor, 2654435761) | 0) & LIT_SIZE - 1;\n\t\tconst len = e - s;\n\t\tfor (;;) {\n\t\t\tconst entry = litTable[idx];\n\t\t\tif (entry === -1) return -1;\n\t\t\tif (litAnchor[entry] === anchor && poolOffsets[litPool[entry] * 2 + 1] === len) {\n\t\t\t\tconst off = poolOffsets[litPool[entry] * 2];\n\t\t\t\tlet ok = true;\n\t\t\t\tfor (let k = 0; k < len; k++) if (poolText.charCodeAt(off + k) !== input.charCodeAt(s + k)) {\n\t\t\t\t\tok = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (ok) return litGroup[entry];\n\t\t\t}\n\t\t\tidx = idx + 1 & LIT_SIZE - 1;\n\t\t}\n\t};\n\tconst cacheSize = options.cacheSize ?? 8192;\n\tconst RAW_PREFIX = options.prefix ?? T.prefix ?? \"\";\n\tconst FULL_PREFIX = RAW_PREFIX === \"\" ? \"\" : RAW_PREFIX + \":\";\n\tconst FPL = FULL_PREFIX.length;\n\tconst vCustom = (customValidatorNames ?? []).map((name) => {\n\t\tconst fn = validatorImpls && validatorImpls[name];\n\t\tif (!fn) throw new Error(\"cn: missing validator \" + name);\n\t\treturn fn;\n\t});\n\tconst lengthUnitRegex = /\\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\\b(calc|min|max|clamp)\\(.+\\)|^0$/;\n\tconst colorFunctionRegex = /^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\\(.+\\)$/;\n\tconst shadowRegex = /^(inset_)?-?((\\d+)?\\.?(\\d+)[a-z]+|0)_-?((\\d+)?\\.?(\\d+)[a-z]+|0)/;\n\tconst imageRegex = /^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\\(.+\\)$/;\n\tlet aKind = 0;\n\tlet aLabelS = -1;\n\tlet aLabelE = -1;\n\tlet aValS = -1;\n\tlet aValE = -1;\n\tconst isWordCode = (c) => c >= 97 && c <= 122 || c >= 65 && c <= 90 || c >= 48 && c <= 57 || c === 95;\n\tconst isUniWS = (c) => /\\s/.test(String.fromCharCode(c));\n\tconst analyzeArb = (input, s, e) => {\n\t\taKind = 0;\n\t\taLabelS = -1;\n\t\tif (e - s < 3) return;\n\t\tconst c0 = input.charCodeAt(s);\n\t\tconst cl = input.charCodeAt(e - 1);\n\t\tif (c0 === 91 && cl === 93) aKind = 1;\n\t\telse if (c0 === 40 && cl === 41) aKind = 2;\n\t\telse return;\n\t\taValS = s + 1;\n\t\taValE = e - 1;\n\t\tlet p = s + 1;\n\t\tif (isWordCode(input.charCodeAt(p))) {\n\t\t\tp++;\n\t\t\twhile (p < e - 1) {\n\t\t\t\tconst c = input.charCodeAt(p);\n\t\t\t\tif (!isWordCode(c) && c !== 45) break;\n\t\t\t\tp++;\n\t\t\t}\n\t\t\tif (p < e - 2 && input.charCodeAt(p) === 58) {\n\t\t\t\taLabelS = s + 1;\n\t\t\t\taLabelE = p;\n\t\t\t\taValS = p + 1;\n\t\t\t}\n\t\t}\n\t};\n\tconst spanEq = (input, s, e, str) => {\n\t\tif (e - s !== str.length) return false;\n\t\tfor (let i = 0; i < str.length; i++) if (input.charCodeAt(s + i) !== str.charCodeAt(i)) return false;\n\t\treturn true;\n\t};\n\tconst fractionRegex = /^\\d+(?:\\.\\d+)?\\/\\d+(?:\\.\\d+)?$/;\n\tconst tshirtRegex = /^(\\d+(\\.\\d+)?)?(xs|sm|md|lg|xl)$/;\n\tconst isNumStr = (v) => !!v && !Number.isNaN(Number(v));\n\tconst spanIsNamedContainerQuery = (input, s, e) => {\n\t\tif (e - s < 11 || !spanEq(input, s, s + 10, \"@container\")) return false;\n\t\tif (input.charCodeAt(s + 10) === 47) return e - s >= 12;\n\t\tconst c11 = input.charCodeAt(s + 11);\n\t\treturn c11 === 115 && e - s >= 17 && spanEq(input, s + 10, s + 16, \"-size/\") || c11 === 110 && e - s >= 19 && spanEq(input, s + 10, s + 18, \"-normal/\");\n\t};\n\tconst VKIND = [\n\t\t1,\n\t\t1,\n\t\t1,\n\t\t1,\n\t\t1,\n\t\t1,\n\t\t1,\n\t\t1,\n\t\t2,\n\t\t2,\n\t\t2,\n\t\t2,\n\t\t2,\n\t\t2,\n\t\t2\n\t];\n\tconst VLABELS = \"length|number|number weight|family-name|position percentage|length size bg-size|image url|shadow|length|family-name|position percentage|length size bg-size|image url|shadow|number weight\".split(\"|\").map((s) => s.split(\" \"));\n\tconst VFALL = [\n\t\t2,\n\t\t3,\n\t\t1,\n\t\t0,\n\t\t0,\n\t\t0,\n\t\t4,\n\t\t5,\n\t\t0,\n\t\t0,\n\t\t0,\n\t\t0,\n\t\t0,\n\t\t1,\n\t\t1\n\t];\n\tconst runValidator = (op, input, s, e) => {\n\t\tif (op >= 10) {\n\t\t\tif (op >= 25) return vCustom[op - 25](input.slice(s, e));\n\t\t\tconst i = op - 10;\n\t\t\tif (aKind !== VKIND[i]) return false;\n\t\t\tif (aLabelS >= 0) {\n\t\t\t\tfor (const L of VLABELS[i]) if (spanEq(input, aLabelS, aLabelE, L)) return true;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tswitch (VFALL[i]) {\n\t\t\t\tcase 0: return false;\n\t\t\t\tcase 1: return true;\n\t\t\t\tcase 2: {\n\t\t\t\t\tconst v = input.slice(aValS, aValE);\n\t\t\t\t\treturn lengthUnitRegex.test(v) && !colorFunctionRegex.test(v);\n\t\t\t\t}\n\t\t\t\tcase 3: return isNumStr(input.slice(aValS, aValE));\n\t\t\t\tcase 4: return imageRegex.test(input.slice(aValS, aValE));\n\t\t\t\tdefault: return shadowRegex.test(input.slice(aValS, aValE));\n\t\t\t}\n\t\t}\n\t\tswitch (op) {\n\t\t\tcase 0: return true;\n\t\t\tcase 1: return aKind === 0;\n\t\t\tcase 2: return aKind === 1;\n\t\t\tcase 3: return aKind === 2;\n\t\t\tcase 4: return fractionRegex.test(input.slice(s, e));\n\t\t\tcase 5: return isNumStr(input.slice(s, e));\n\t\t\tcase 6: {\n\t\t\t\tconst v = input.slice(s, e);\n\t\t\t\treturn !!v && Number.isInteger(Number(v));\n\t\t\t}\n\t\t\tcase 7: return e > s && input.charCodeAt(e - 1) === 37 && isNumStr(input.slice(s, e - 1));\n\t\t\tcase 8: return tshirtRegex.test(input.slice(s, e));\n\t\t\tdefault: return spanIsNamedContainerQuery(input, s, e);\n\t\t}\n\t};\n\tconst orderSensitive = new Set(typeof orderSensitiveModifiers === \"string\" ? orderSensitiveModifiers.split(\" \") : orderSensitiveModifiers);\n\tconst internSpan = (map, input, s, e, imp, make) => {\n\t\tconst h = fnv(input, s, e) ^ (imp ? 2654435769 : 0) | 0;\n\t\tlet bucket = map.get(h);\n\t\tif (bucket !== void 0) outer: for (let b = 0; b < bucket.length; b++) {\n\t\t\tconst en = bucket[b];\n\t\t\tif (en.imp !== imp || en.k.length !== e - s) continue;\n\t\t\tfor (let i = 0; i < en.k.length; i++) if (en.k.charCodeAt(i) !== input.charCodeAt(s + i)) continue outer;\n\t\t\treturn en.id;\n\t\t}\n\t\telse map.set(h, bucket = []);\n\t\tconst k = input.slice(s, e);\n\t\tconst id = make(k);\n\t\tbucket.push({\n\t\t\tk,\n\t\t\timp,\n\t\t\tid\n\t\t});\n\t\treturn id;\n\t};\n\tlet ctxByHash = /* @__PURE__ */ new Map();\n\tlet ctxByCanon = /* @__PURE__ */ new Map();\n\tlet nextCtxId = 2;\n\tconst MAX_CTX = 4096;\n\tconst canonicalizeContext = (raw, important) => {\n\t\tconst mods = [];\n\t\tlet dB = 0, dP = 0, start = 0;\n\t\tfor (let i = 0; i < raw.length; i++) {\n\t\t\tconst c = raw.charCodeAt(i);\n\t\t\tif (dB === 0 && dP === 0 && c === 58) {\n\t\t\t\tmods.push(raw.slice(start, i));\n\t\t\t\tstart = i + 1;\n\t\t\t} else if (c === 91) dB++;\n\t\t\telse if (c === 93) dB--;\n\t\t\telse if (c === 40) dP++;\n\t\t\telse if (c === 41) dP--;\n\t\t}\n\t\tmods.push(raw.slice(start));\n\t\tlet canonical = mods[0];\n\t\tif (mods.length > 1) {\n\t\t\tconst result = [];\n\t\t\tlet segment = [];\n\t\t\tfor (const mod of mods) if (mod.charCodeAt(0) === 91 || orderSensitive.has(mod)) {\n\t\t\t\tif (segment.length) {\n\t\t\t\t\tresult.push(...segment.sort());\n\t\t\t\t\tsegment = [];\n\t\t\t\t}\n\t\t\t\tresult.push(mod);\n\t\t\t} else segment.push(mod);\n\t\t\tif (segment.length) result.push(...segment.sort());\n\t\t\tcanonical = result.join(\":\");\n\t\t}\n\t\tconst key = important ? canonical + \" !\" : canonical;\n\t\tlet id = ctxByCanon.get(key);\n\t\tif (id === void 0) ctxByCanon.set(key, id = nextCtxId++);\n\t\treturn id;\n\t};\n\tlet dynByHash = /* @__PURE__ */ new Map();\n\tlet nextDynId = GROUP_COUNT;\n\tconst MAX_DYN = GROUP_COUNT + 4096;\n\tconst newDynId = () => nextDynId++;\n\tconst ID_LIMIT = 2097152;\n\tconst TOKEN_TABLE = 8192;\n\tconst memoHash = new Int32Array(TOKEN_TABLE);\n\tconst memoStr = new Array(TOKEN_TABLE).fill(null);\n\tconst memoGid = new Int32Array(TOKEN_TABLE);\n\tconst memoCtx = new Int32Array(TOKEN_TABLE);\n\tconst memoFlags = new Uint8Array(TOKEN_TABLE);\n\tlet memoTick = 0;\n\tconst memoPut = (way0, input, ts, te, h, gid, ctxId, flags) => {\n\t\tlet slot = way0;\n\t\tif (memoStr[way0] !== null) {\n\t\t\tif (memoStr[way0 | 1] === null) slot = way0 | 1;\n\t\t\telse if ((memoTick++ & 3) === 0) slot = way0 | memoTick >> 2 & 1;\n\t\t\telse return;\n\t\t}\n\t\tmemoStr[slot] = input.slice(ts, te);\n\t\tmemoHash[slot] = h;\n\t\tmemoGid[slot] = gid;\n\t\tmemoCtx[slot] = ctxId;\n\t\tmemoFlags[slot] = flags;\n\t};\n\tconst memoReset = () => memoStr.fill(null);\n\tlet cap = 256;\n\tlet tokI32 = [\n\t\tnew Int32Array(cap),\n\t\tnew Int32Array(cap),\n\t\tnew Int32Array(cap),\n\t\tnew Int32Array(cap)\n\t];\n\tlet [tokStart, tokEnd, tokGid, tokCtx] = tokI32;\n\tlet tokFlags = new Uint8Array(cap);\n\tlet keep = new Uint8Array(cap);\n\tconst growTokens = () => {\n\t\tcap *= 2;\n\t\ttokI32 = tokI32.map((a) => {\n\t\t\tconst n = new Int32Array(cap);\n\t\t\tn.set(a);\n\t\t\treturn n;\n\t\t});\n\t\t[tokStart, tokEnd, tokGid, tokCtx] = tokI32;\n\t\tconst nf = new Uint8Array(cap);\n\t\tnf.set(tokFlags);\n\t\ttokFlags = nf;\n\t\tkeep = new Uint8Array(cap);\n\t};\n\tlet ckptCap = 64;\n\tlet ckptNode = new Int32Array(ckptCap);\n\tlet ckptTail = new Int32Array(ckptCap);\n\tconst claim0 = new Int32Array(GROUP_COUNT);\n\tlet CLAIM_TABLE = 2048;\n\tlet claimShift = 21;\n\tlet claimKeys = new Float64Array(CLAIM_TABLE);\n\tlet claimEpochs = new Int32Array(CLAIM_TABLE);\n\tlet epoch = 0;\n\tconst claimTest = (ctx, gid) => {\n\t\tif (ctx === 0 && gid < GROUP_COUNT) {\n\t\t\tif (claim0[gid] === epoch) return 1;\n\t\t\tclaim0[gid] = epoch;\n\t\t\treturn 0;\n\t\t}\n\t\tconst key = ctx * 2097152 + gid + 1;\n\t\tlet idx = Math.imul(key, 2654435761) >>> claimShift;\n\t\tfor (;;) {\n\t\t\tif (claimEpochs[idx] !== epoch) break;\n\t\t\tif (claimKeys[idx] === key) return 1;\n\t\t\tidx = idx + 1 & CLAIM_TABLE - 1;\n\t\t}\n\t\tclaimKeys[idx] = key;\n\t\tclaimEpochs[idx] = epoch;\n\t\treturn 0;\n\t};\n\tconst resolveAt = (input, bs, endPos, nodeAt, ckptAt) => {\n\t\tif (endPos - bs >= 2 && input.charCodeAt(bs) === 91 && input.charCodeAt(endPos - 1) === 93) {\n\t\t\tlet colon = -1;\n\t\t\tfor (let p = bs + 1; p < endPos - 1; p++) if (input.charCodeAt(p) === 58) {\n\t\t\t\tcolon = p;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (colon === -1 || colon === bs + 1) return EXTERNAL;\n\t\t\treturn internSpan(dynByHash, input, bs + 1, colon, 0, newDynId);\n\t\t}\n\t\tif (nodeAt >= 0 && nodeGroup[nodeAt] >= 0) return nodeGroup[nodeAt];\n\t\tfor (let k = ckptAt - 1; k >= 0; k--) {\n\t\t\tconst tailStart = ckptTail[k];\n\t\t\tif (tailStart > endPos) continue;\n\t\t\tconst nodeId = ckptNode[k];\n\t\t\tconst tlen = endPos - tailStart;\n\t\t\tif (nodeHasLit[nodeId] === 1 && tlen > 0 && tlen <= litMaxLen) {\n\t\t\t\tconst c0 = input.charCodeAt(tailStart);\n\t\t\t\tif (litNoArb === false || c0 !== 91 && c0 !== 40) {\n\t\t\t\t\tconst g = litProbe(nodeId, input, tailStart, endPos);\n\t\t\t\t\tif (g >= 0) return g;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst vl = nodeVlist[nodeId];\n\t\t\tif (vl < 0) continue;\n\t\t\tconst pat = vlistRef[vl];\n\t\t\tconst vs = vlistPat[pat];\n\t\t\tconst ve = vlistPat[pat + 1];\n\t\t\tif (vs === ve) continue;\n\t\t\tanalyzeArb(input, tailStart, endPos);\n\t\t\tconst g0 = vgStart[vl] - vs;\n\t\t\tfor (let v = vs; v < ve; v++) if (runValidator(vlistOps[v], input, tailStart, endPos)) return vlistGroup[g0 + v];\n\t\t}\n\t\treturn EXTERNAL;\n\t};\n\tconst mergeClassList = (input) => {\n\t\tconst n = input.length;\n\t\tlet tokenCount = 0;\n\t\tlet totalTokenChars = 0;\n\t\tlet sawNonSpaceWS = false;\n\t\tif (nextCtxId > MAX_CTX || ctxByHash.size > MAX_CTX) {\n\t\t\tctxByHash = /* @__PURE__ */ new Map();\n\t\t\tctxByCanon = /* @__PURE__ */ new Map();\n\t\t\tnextCtxId = 2;\n\t\t\tmemoReset();\n\t\t}\n\t\tif (nextDynId > MAX_DYN) {\n\t\t\tdynByHash = /* @__PURE__ */ new Map();\n\t\t\tnextDynId = GROUP_COUNT;\n\t\t\tmemoReset();\n\t\t}\n\t\tlet i = 0;\n\t\twhile (i < n) {\n\t\t\tlet c = input.charCodeAt(i);\n\t\t\tif (c === 32 || c >= 9 && c <= 13 || c >= 160 && isUniWS(c)) {\n\t\t\t\tif (c !== 32) sawNonSpaceWS = true;\n\t\t\t\ti++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst ts = i;\n\t\t\tlet th = 0;\n\t\t\twhile (i < n) {\n\t\t\t\tc = input.charCodeAt(i);\n\t\t\t\tif (c <= 32) {\n\t\t\t\t\tif (c === 32) break;\n\t\t\t\t\tif (c >= 9 && c <= 13) {\n\t\t\t\t\t\tsawNonSpaceWS = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t} else if (c >= 160 && isUniWS(c)) {\n\t\t\t\t\tsawNonSpaceWS = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tth = Math.imul(th ^ c, 16777619);\n\t\t\t\ti++;\n\t\t\t}\n\t\t\tconst te = i;\n\t\t\tconst len = te - ts;\n\t\t\tif (tokenCount === cap) growTokens();\n\t\t\tconst t = tokenCount++;\n\t\t\ttokStart[t] = ts;\n\t\t\ttokEnd[t] = te;\n\t\t\ttotalTokenChars += len;\n\t\t\tth ^= Math.imul(len, 2654435761);\n\t\t\tconst h = th ^ th >>> 15 | 0;\n\t\t\tconst way0 = h & 8190;\n\t\t\t{\n\t\t\t\tlet hitAt = -1;\n\t\t\t\tif (memoHash[way0] === h && memoStr[way0] !== null && memoStr[way0].length === len) hitAt = way0;\n\t\t\t\telse if (memoHash[way0 | 1] === h && memoStr[way0 | 1] !== null && memoStr[way0 | 1].length === len) hitAt = way0 | 1;\n\t\t\t\tif (hitAt >= 0) {\n\t\t\t\t\tconst s = memoStr[hitAt];\n\t\t\t\t\tlet ok = true;\n\t\t\t\t\tfor (let k = 0; k < len; k++) if (s.charCodeAt(k) !== input.charCodeAt(ts + k)) {\n\t\t\t\t\t\tok = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tif (ok) {\n\t\t\t\t\t\ttokGid[t] = memoGid[hitAt];\n\t\t\t\t\t\ttokCtx[t] = memoCtx[hitAt];\n\t\t\t\t\t\ttokFlags[t] = memoFlags[hitAt];\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tlet pts = ts;\n\t\t\tif (FPL !== 0) {\n\t\t\t\tif (te - ts <= FPL || !input.startsWith(FULL_PREFIX, ts)) {\n\t\t\t\t\ttokGid[t] = EXTERNAL;\n\t\t\t\t\tmemoPut(way0, input, ts, te, h, EXTERNAL, 0, 0);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tpts = ts + FPL;\n\t\t\t}\n\t\t\tlet depthB = 0, depthP = 0;\n\t\t\tlet lastColon = -1, lastSlash = -1;\n\t\t\tfor (let p = pts; p < te; p++) {\n\t\t\t\tconst pc = input.charCodeAt(p);\n\t\t\t\tif (depthB === 0 && depthP === 0) {\n\t\t\t\t\tif (pc === 58) {\n\t\t\t\t\t\tlastColon = p;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (pc === 47) {\n\t\t\t\t\t\tlastSlash = p;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (pc === 91) depthB++;\n\t\t\t\telse if (pc === 93) depthB--;\n\t\t\t\telse if (pc === 40) depthP++;\n\t\t\t\telse if (pc === 41) depthP--;\n\t\t\t}\n\t\t\tconst modStart = lastColon >= pts ? lastColon + 1 : pts;\n\t\t\tlet bs = modStart;\n\t\t\tlet be = te;\n\t\t\tlet important = false;\n\t\t\tlet prefixShift = 0;\n\t\t\tif (be > bs && input.charCodeAt(be - 1) === 33) {\n\t\t\t\timportant = true;\n\t\t\t\tbe--;\n\t\t\t} else if (be > bs && input.charCodeAt(bs) === 33) {\n\t\t\t\timportant = true;\n\t\t\t\tbs++;\n\t\t\t\tprefixShift = 1;\n\t\t\t}\n\t\t\tlet postfixEnd = -1;\n\t\t\tif (lastSlash > modStart) {\n\t\t\t\tpostfixEnd = lastSlash + prefixShift;\n\t\t\t\tif (postfixEnd >= be) postfixEnd = -1;\n\t\t\t}\n\t\t\tlet feedStart = bs;\n\t\t\tif (be - bs > 1 && input.charCodeAt(bs) === 45) feedStart = bs + 1;\n\t\t\tlet node = 0;\n\t\t\tlet lp = 0;\n\t\t\tlet le = 0;\n\t\t\tlet pending = -1;\n\t\t\tlet ckptTop = 0;\n\t\t\tif (nodeVlist[0] >= 0 || nodeHasLit[0] === 1) {\n\t\t\t\tckptNode[0] = 0;\n\t\t\t\tckptTail[0] = feedStart;\n\t\t\t\tckptTop = 1;\n\t\t\t}\n\t\t\tlet slashNode = DEAD;\n\t\t\tlet slashCkpt = 0;\n\t\t\tfor (let p = feedStart; p < be; p++) {\n\t\t\t\tif (p === postfixEnd) {\n\t\t\t\t\tslashNode = lp < le ? DEAD : node;\n\t\t\t\t\tslashCkpt = ckptTop;\n\t\t\t\t}\n\t\t\t\tif (node !== DEAD) {\n\t\t\t\t\tconst cc = input.charCodeAt(p);\n\t\t\t\t\tlet arrived = -1;\n\t\t\t\t\tif (lp < le) {\n\t\t\t\t\t\tif (labelText.charCodeAt(lp) === cc) {\n\t\t\t\t\t\t\tlp++;\n\t\t\t\t\t\t\tif (lp === le) arrived = node = pending;\n\t\t\t\t\t\t} else node = DEAD;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst es = edgeStart[node];\n\t\t\t\t\t\tconst ee = edgeStart[node + 1];\n\t\t\t\t\t\tlet next = DEAD;\n\t\t\t\t\t\tfor (let e = es; e < ee; e++) {\n\t\t\t\t\t\t\tconst ls = labelStart[e];\n\t\t\t\t\t\t\tif (labelText.charCodeAt(ls) === cc) {\n\t\t\t\t\t\t\t\tif (labelStart[e + 1] - ls === 1) arrived = next = edgeTarget[e];\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\tlp = ls + 1;\n\t\t\t\t\t\t\t\t\tle = labelStart[e + 1];\n\t\t\t\t\t\t\t\t\tpending = edgeTarget[e];\n\t\t\t\t\t\t\t\t\tnext = node;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tnode = next;\n\t\t\t\t\t}\n\t\t\t\t\tif (arrived >= 0 && (nodeVlist[arrived] >= 0 || nodeHasLit[arrived] === 1) && p + 1 < be && input.charCodeAt(p + 1) === 45) {\n\t\t\t\t\t\tif (ckptTop === ckptCap) {\n\t\t\t\t\t\t\tckptCap *= 2;\n\t\t\t\t\t\t\tconst nv = new Int32Array(ckptCap);\n\t\t\t\t\t\t\tnv.set(ckptNode);\n\t\t\t\t\t\t\tckptNode = nv;\n\t\t\t\t\t\t\tconst nt = new Int32Array(ckptCap);\n\t\t\t\t\t\t\tnt.set(ckptTail);\n\t\t\t\t\t\t\tckptTail = nt;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tckptNode[ckptTop] = arrived;\n\t\t\t\t\t\tckptTail[ckptTop] = p + 2;\n\t\t\t\t\t\tckptTop++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (postfixEnd === be) {\n\t\t\t\tslashNode = lp < le ? DEAD : node;\n\t\t\t\tslashCkpt = ckptTop;\n\t\t\t}\n\t\t\tconst endNode = lp < le ? DEAD : node;\n\t\t\tlet gid;\n\t\t\tlet hasPostfix = false;\n\t\t\tif (postfixEnd >= 0) {\n\t\t\t\thasPostfix = true;\n\t\t\t\tgid = resolveAt(input, bs, postfixEnd, slashNode, slashCkpt);\n\t\t\t\tif (gid !== EXTERNAL && gid < GROUP_COUNT && postfixLookupSet[gid]) {\n\t\t\t\t\tconst gidFull = resolveAt(input, bs, be, endNode, ckptTop);\n\t\t\t\t\tif (gidFull !== EXTERNAL && gidFull !== gid) {\n\t\t\t\t\t\tgid = gidFull;\n\t\t\t\t\t\thasPostfix = false;\n\t\t\t\t\t}\n\t\t\t\t} else if (gid === EXTERNAL) {\n\t\t\t\t\tgid = resolveAt(input, bs, be, endNode, ckptTop);\n\t\t\t\t\thasPostfix = false;\n\t\t\t\t}\n\t\t\t} else gid = resolveAt(input, bs, be, endNode, ckptTop);\n\t\t\tlet ctxId = 0;\n\t\t\tlet flags = 0;\n\t\t\tif (gid === EXTERNAL) tokGid[t] = EXTERNAL;\n\t\t\telse {\n\t\t\t\tflags = hasPostfix ? 1 : 0;\n\t\t\t\tctxId = pts >= lastColon ? important ? 1 : 0 : internSpan(ctxByHash, input, pts, lastColon, important ? 1 : 0, (k) => canonicalizeContext(k, important));\n\t\t\t\ttokGid[t] = gid;\n\t\t\t\ttokFlags[t] = flags;\n\t\t\t\ttokCtx[t] = ctxId;\n\t\t\t}\n\t\t\tmemoPut(way0, input, ts, te, h, gid, ctxId, flags);\n\t\t}\n\t\tif (tokenCount === 0) return \"\";\n\t\tif (tokenCount === 1) return tokStart[0] === 0 && tokEnd[0] === n ? input : input.slice(tokStart[0], tokEnd[0]);\n\t\tif (tokenCount * CLAIM_PER_TOKEN > CLAIM_TABLE) {\n\t\t\twhile (tokenCount * CLAIM_PER_TOKEN > CLAIM_TABLE) {\n\t\t\t\tCLAIM_TABLE <<= 1;\n\t\t\t\tclaimShift--;\n\t\t\t}\n\t\t\tclaimKeys = new Float64Array(CLAIM_TABLE);\n\t\t\tclaimEpochs = new Int32Array(CLAIM_TABLE);\n\t\t}\n\t\tif (nextCtxId >= ID_LIMIT || nextDynId >= ID_LIMIT) throw new Error(\"cn: too many distinct classes in one merge\");\n\t\tepoch = epoch + 1 | 0;\n\t\tif (epoch === 0) {\n\t\t\tclaim0.fill(0);\n\t\t\tclaimEpochs.fill(0);\n\t\t\tepoch = 1;\n\t\t}\n\t\tlet didDrop = false;\n\t\tfor (let t = tokenCount - 1; t >= 0; t--) {\n\t\t\tconst gid = tokGid[t];\n\t\t\tif (gid === EXTERNAL) {\n\t\t\t\tkeep[t] = 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst ctxId = tokCtx[t];\n\t\t\tif (claimTest(ctxId, gid) === 1) {\n\t\t\t\tkeep[t] = 0;\n\t\t\t\tdidDrop = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tkeep[t] = 1;\n\t\t\tif (gid < GROUP_COUNT) {\n\t\t\t\tconst r = adjRow[gid];\n\t\t\t\tif (r >= 0) for (let k = adjStart[r]; k < adjStart[r + 1]; k++) claimTest(ctxId, adjTgt[k]);\n\t\t\t\tif (tokFlags[t] & 1) {\n\t\t\t\t\tfor (let k = 0; k < patGid.length; k++) if (patGid[k] === gid) claimTest(ctxId, patTgt[k]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (!didDrop && !sawNonSpaceWS && n === totalTokenChars + tokenCount - 1) return input;\n\t\tlet out = \"\";\n\t\tlet t = 0;\n\t\twhile (t < tokenCount) {\n\t\t\tif (!keep[t]) {\n\t\t\t\tt++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst runStart = tokStart[t];\n\t\t\tlet runEnd = tokEnd[t];\n\t\t\tlet u = t + 1;\n\t\t\twhile (u < tokenCount && keep[u] && tokStart[u] === runEnd + 1 && input.charCodeAt(runEnd) === 32) {\n\t\t\t\trunEnd = tokEnd[u];\n\t\t\t\tu++;\n\t\t\t}\n\t\t\tif (out.length > 0) out += \" \";\n\t\t\tout += input.slice(runStart, runEnd);\n\t\t\tt = u;\n\t\t}\n\t\treturn out;\n\t};\n\tconst DOOR_SIZE = 16384;\n\tconst door = new Int32Array(DOOR_SIZE * 2);\n\tlet doorBase = 0;\n\tlet doorEpoch = 1;\n\tlet cache = Object.create(null);\n\tlet prevCache = Object.create(null);\n\tlet cacheMap = /* @__PURE__ */ new Map();\n\tlet prevCacheMap = /* @__PURE__ */ new Map();\n\tlet cacheCount = 0;\n\tlet doorMarks = 0;\n\tconst rotateDoor = () => {\n\t\tdoorBase ^= DOOR_SIZE;\n\t\tdoorEpoch = doorEpoch + 1 | 0;\n\t\tdoorMarks = 0;\n\t};\n\tconst mergeCached = (input) => {\n\t\tlet merged = cache[input];\n\t\tif (merged !== void 0) return merged;\n\t\tconst hash = spanHash(input, 0, input.length);\n\t\tconst slot = (hash & 16383) + doorBase;\n\t\tconst wasSeen = door[slot] === (hash ^ doorEpoch) || door[slot ^ DOOR_SIZE] === (hash ^ doorEpoch - 1);\n\t\tif (wasSeen) {\n\t\t\tmerged = prevCache[input];\n\t\t\tif (merged !== void 0) {\n\t\t\t\tcache[input] = merged;\n\t\t\t\treturn merged;\n\t\t\t}\n\t\t}\n\t\tmerged = mergeClassList(input);\n\t\tif (wasSeen) {\n\t\t\tcache[input] = merged;\n\t\t\tif (++cacheCount > cacheSize) {\n\t\t\t\tcacheCount = 0;\n\t\t\t\tprevCache = cache;\n\t\t\t\tcache = Object.create(null);\n\t\t\t\trotateDoor();\n\t\t\t}\n\t\t} else {\n\t\t\tdoor[slot] = hash ^ doorEpoch;\n\t\t\tif (++doorMarks > DOOR_SIZE) rotateDoor();\n\t\t}\n\t\treturn merged;\n\t};\n\tconst mergeCachedMap = (input) => {\n\t\tlet merged = cacheMap.get(input);\n\t\tif (merged !== void 0) return merged;\n\t\tconst hash = spanHash(input, 0, input.length);\n\t\tconst slot = (hash & 16383) + doorBase;\n\t\tconst wasSeen = door[slot] === (hash ^ doorEpoch) || door[slot ^ DOOR_SIZE] === (hash ^ doorEpoch - 1);\n\t\tif (wasSeen) {\n\t\t\tmerged = prevCacheMap.get(input);\n\t\t\tif (merged !== void 0) {\n\t\t\t\tcacheMap.set(input, merged);\n\t\t\t\treturn merged;\n\t\t\t}\n\t\t}\n\t\tmerged = mergeClassList(input);\n\t\tif (wasSeen) {\n\t\t\tcacheMap.set(input, merged);\n\t\t\tif (++cacheCount > cacheSize) {\n\t\t\t\tcacheCount = 0;\n\t\t\t\tprevCacheMap = cacheMap;\n\t\t\t\tcacheMap = /* @__PURE__ */ new Map();\n\t\t\t\trotateDoor();\n\t\t\t}\n\t\t} else {\n\t\t\tdoor[slot] = hash ^ doorEpoch;\n\t\t\tif (++doorMarks > DOOR_SIZE) rotateDoor();\n\t\t}\n\t\treturn merged;\n\t};\n\tconst seenBefore = (input) => {\n\t\tconst hash = spanHash(input, 0, input.length);\n\t\tconst slot = (hash & 16383) + doorBase;\n\t\tif (door[slot] === (hash ^ doorEpoch) || door[slot ^ DOOR_SIZE] === (hash ^ doorEpoch - 1)) return true;\n\t\tdoor[slot] = hash ^ doorEpoch;\n\t\tif (++doorMarks > DOOR_SIZE) rotateDoor();\n\t\treturn false;\n\t};\n\tconst mergeString = cacheSize === 0 ? mergeClassList : IS_JSC ? (input) => {\n\t\tconst merged = cacheMap.get(input);\n\t\treturn merged !== void 0 ? merged : mergeCachedMap(input);\n\t} : mergeCached;\n\tconst merge = function() {\n\t\treturn arguments.length === 1 && typeof arguments[0] === \"string\" ? mergeString(arguments[0]) : mergeString(twJoin.apply(null, arguments));\n\t};\n\treturn {\n\t\tmerge,\n\t\tmergeString,\n\t\tseenBefore: cacheSize === 0 ? () => false : seenBefore,\n\t\tmergeUncached: mergeClassList\n\t};\n};\nconst resolveValue = (v, clsxMode) => {\n\tif (!v) return \"\";\n\tif (typeof v === \"string\") return v;\n\tlet out = \"\";\n\tif (typeof v.length === \"number\" && (clsxMode ? Array.isArray(v) : true)) {\n\t\tconst arr = v;\n\t\tfor (let i = 0; i < arr.length; i++) {\n\t\t\tconst item = arr[i];\n\t\t\tif (!item) continue;\n\t\t\tconst r = typeof item === \"string\" ? item : resolveValue(item, clsxMode);\n\t\t\tif (r) {\n\t\t\t\tif (out) out += \" \";\n\t\t\t\tout += r;\n\t\t\t}\n\t\t}\n\t\treturn out;\n\t}\n\tif (clsxMode) {\n\t\tif (typeof v === \"number\") return \"\" + v;\n\t\tif (typeof v === \"object\") {\n\t\t\tfor (const k in v) if (v[k]) {\n\t\t\t\tif (out) out += \" \";\n\t\t\t\tout += k;\n\t\t\t}\n\t\t}\n\t}\n\treturn out;\n};\nconst joinArgs = (args, clsxMode) => {\n\tlet s = \"\";\n\tfor (let i = 0; i < args.length; i++) {\n\t\tconst a = args[i];\n\t\tif (!a) continue;\n\t\tconst r = typeof a === \"string\" ? a : resolveValue(a, clsxMode);\n\t\tif (r) {\n\t\t\tif (s) s += \" \";\n\t\t\ts += r;\n\t\t}\n\t}\n\treturn s;\n};\n/** join-only, `twJoin`-compatible (strings + nested arrays, falsy skipped) */\nconst twJoin = function() {\n\treturn joinArgs(arguments, false);\n};\n/** join-only, `clsx`-compatible (no merging) */\nconst clsx = function() {\n\treturn joinArgs(arguments, true);\n};\nconst BUCKET_CAP = 256;\nconst BUCKET_MISS_CAP = 16;\nconst BUCKET_SKIP = 1024;\nconst CHURN_SIZE = 4096;\nconst wrapClsx = (mergeString, fresh) => {\n\tconst seenBefore = fresh === void 0 ? () => true : fresh.seenBefore;\n\tconst mergeUncached = fresh === void 0 ? mergeString : fresh.mergeUncached;\n\tlet argCache = /* @__PURE__ */ new Map();\n\tlet prevArgCache = /* @__PURE__ */ new Map();\n\tlet argCount = 0;\n\tlet lastHit = null;\n\tlet churnKey = null;\n\tlet churnOwn = [];\n\tlet churnVal = [];\n\tlet churnTick = 0;\n\tconst churnLookup = (key, own, join) => {\n\t\tif (churnKey === null) {\n\t\t\tchurnKey = new Array(CHURN_SIZE).fill(\"\");\n\t\t\tchurnOwn = new Array(CHURN_SIZE).fill(\"\");\n\t\t\tchurnVal = new Array(CHURN_SIZE).fill(\"\");\n\t\t}\n\t\tconst way0 = spanHash(key, 0, key.length) & 4094;\n\t\tif (churnKey[way0] === key && churnOwn[way0] === own) return churnVal[way0];\n\t\tif (churnKey[way0 | 1] === key && churnOwn[way0 | 1] === own) return churnVal[way0 | 1];\n\t\tconst merged = mergeString(join ? own + \" \" + key : key);\n\t\tconst slot = churnKey[way0] === \"\" ? way0 : way0 | (churnKey[way0 | 1] === \"\" ? 1 : churnTick++ & 1);\n\t\tchurnKey[slot] = key;\n\t\tchurnOwn[slot] = own;\n\t\tchurnVal[slot] = merged;\n\t\treturn merged;\n\t};\n\tconst match3 = (e, v0, v1, v2) => {\n\t\tlet k = 0;\n\t\tif (v0) {\n\t\t\tif (v0 !== e.a0) return false;\n\t\t\tk = 1;\n\t\t}\n\t\tif (v1) {\n\t\t\tif (v1 !== (k === 0 ? e.a0 : e.a1)) return false;\n\t\t\tk++;\n\t\t}\n\t\tif (v2) {\n\t\t\tif (v2 !== (k === 0 ? e.a0 : k === 1 ? e.a1 : e.a2)) return false;\n\t\t\tk++;\n\t\t}\n\t\treturn k === e.t;\n\t};\n\tconst matchN = (e, vals) => {\n\t\tconst ea = e.a;\n\t\tlet k = 0;\n\t\tfor (let i = 0; i < vals.length; i++) {\n\t\t\tconst v = vals[i];\n\t\t\tif (!v) continue;\n\t\t\tif (v !== ea[k]) return false;\n\t\t\tk++;\n\t\t}\n\t\treturn k === e.t;\n\t};\n\tconst resolveArgs = (vals, probed) => {\n\t\tconst nArgs = vals.length;\n\t\tconst pred = lastHit === null ? null : lastHit.n;\n\t\tif (!probed) {\n\t\t\tif (pred !== null && matchN(pred, vals)) {\n\t\t\t\tlastHit = pred;\n\t\t\t\treturn pred.r;\n\t\t\t}\n\t\t\tif (lastHit !== null && lastHit !== pred && matchN(lastHit, vals)) return lastHit.r;\n\t\t}\n\t\tlet first = \"\";\n\t\tlet firstIdx = -1;\n\t\tlet truthy = 0;\n\t\tlet hasResolvedValue = false;\n\t\tfor (let i = 0; i < nArgs; i++) {\n\t\t\tlet v = vals[i];\n\t\t\tif (!v) continue;\n\t\t\tif (typeof v !== \"string\") {\n\t\t\t\tv = vals[i] = resolveValue(v, true);\n\t\t\t\tif (!v) continue;\n\t\t\t\thasResolvedValue = true;\n\t\t\t}\n\t\t\tif (firstIdx < 0) {\n\t\t\t\tfirst = v;\n\t\t\t\tfirstIdx = i;\n\t\t\t}\n\t\t\ttruthy++;\n\t\t}\n\t\tif (truthy === 0) return \"\";\n\t\tif (truthy === 1) return mergeString(first);\n\t\tif (hasResolvedValue) {\n\t\t\tif (pred !== null && matchN(pred, vals)) {\n\t\t\t\tlastHit = pred;\n\t\t\t\treturn pred.r;\n\t\t\t}\n\t\t\tif (lastHit !== null && lastHit !== pred && matchN(lastHit, vals)) return lastHit.r;\n\t\t}\n\t\tlet bucket = argCache.get(first);\n\t\tif (bucket === void 0) {\n\t\t\tbucket = prevArgCache.get(first);\n\t\t\tif (bucket !== void 0) argCache.set(first, bucket);\n\t\t}\n\t\tlet hit = null;\n\t\tif (bucket !== void 0) {\n\t\t\tif (bucket.skip > 0) {\n\t\t\t\tbucket.skip--;\n\t\t\t\tlastHit = null;\n\t\t\t\tlet joined = first;\n\t\t\t\tfor (let i = firstIdx + 1; i < nArgs; i++) {\n\t\t\t\t\tconst v = vals[i];\n\t\t\t\t\tif (v) joined += \" \" + v;\n\t\t\t\t}\n\t\t\t\treturn churnLookup(joined, \"\", false);\n\t\t\t}\n\t\t\tconst entries = bucket.e;\n\t\t\touter: for (let b = 0; b < entries.length; b++) {\n\t\t\t\tconst e = entries[b];\n\t\t\t\tif (e.t !== truthy) continue;\n\t\t\t\tconst ea = e.a;\n\t\t\t\tlet k = 1;\n\t\t\t\tfor (let i = firstIdx + 1; i < nArgs; i++) {\n\t\t\t\t\tconst v = vals[i];\n\t\t\t\t\tif (v && v !== ea[k++]) continue outer;\n\t\t\t\t}\n\t\t\t\thit = e;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (hit !== null) bucket.miss = 0;\n\t\t}\n\t\tif (hit === null) {\n\t\t\tlet joined = first;\n\t\t\tconst a = [first];\n\t\t\tfor (let i = firstIdx + 1; i < nArgs; i++) {\n\t\t\t\tconst v = vals[i];\n\t\t\t\tif (!v) continue;\n\t\t\t\tjoined += \" \" + v;\n\t\t\t\ta.push(v);\n\t\t\t}\n\t\t\tif (!seenBefore(joined)) return mergeUncached(joined);\n\t\t\thit = {\n\t\t\t\tr: mergeString(joined),\n\t\t\t\tt: a.length,\n\t\t\t\ta0: a[0],\n\t\t\t\ta1: a[1],\n\t\t\t\ta2: a[2] ?? \"\",\n\t\t\t\ta,\n\t\t\t\tn: null\n\t\t\t};\n\t\t\tif (bucket === void 0) argCache.set(first, bucket = {\n\t\t\t\te: [],\n\t\t\t\tmiss: 0,\n\t\t\t\tskip: 0,\n\t\t\t\tat: 0\n\t\t\t});\n\t\t\telse if (++bucket.miss > BUCKET_MISS_CAP) {\n\t\t\t\tbucket.miss = BUCKET_MISS_CAP;\n\t\t\t\tbucket.skip = BUCKET_SKIP;\n\t\t\t\tbucket.e.length = 0;\n\t\t\t\tbucket.at = 0;\n\t\t\t}\n\t\t\tconst entries = bucket.e;\n\t\t\tif (entries.length < BUCKET_CAP) entries.push(hit);\n\t\t\telse {\n\t\t\t\tentries[bucket.at] = hit;\n\t\t\t\tbucket.at = bucket.at + 1 & 255;\n\t\t\t}\n\t\t\tif (++argCount > 1e3) {\n\t\t\t\targCount = 0;\n\t\t\t\tprevArgCache = argCache;\n\t\t\t\targCache = /* @__PURE__ */ new Map();\n\t\t\t}\n\t\t}\n\t\tif (lastHit !== null && lastHit !== hit) lastHit.n = hit;\n\t\tlastHit = hit;\n\t\treturn hit.r;\n\t};\n\tconst mergeSingleValue = (value) => Array.isArray(value) ? resolveArgs(value.slice(), false) : mergeString(resolveValue(value, true));\n\treturn function(v0, v1, v2) {\n\t\tconst nArgs = arguments.length;\n\t\tif ((nArgs | 1) === 3) {\n\t\t\tconst lh = lastHit;\n\t\t\tif (lh !== null) {\n\t\t\t\tconst pred = lh.n;\n\t\t\t\tif (pred !== null && match3(pred, v0, v1, v2)) {\n\t\t\t\t\tlastHit = pred;\n\t\t\t\t\treturn pred.r;\n\t\t\t\t}\n\t\t\t\tif (lh !== pred && match3(lh, v0, v1, v2)) return lh.r;\n\t\t\t}\n\t\t\tif (nArgs === 2 && typeof v1 === \"string\" && v1 !== \"\") {\n\t\t\t\tconst bucket = argCache.get(v0);\n\t\t\t\tif (bucket !== void 0 && bucket.skip > 0) {\n\t\t\t\t\tbucket.skip--;\n\t\t\t\t\tlastHit = null;\n\t\t\t\t\treturn churnLookup(v1, v0, true);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn resolveArgs([\n\t\t\t\tv0,\n\t\t\t\tv1,\n\t\t\t\tv2\n\t\t\t], true);\n\t\t}\n\t\tif (nArgs === 1) return typeof v0 === \"string\" ? mergeString(v0) : mergeSingleValue(v0);\n\t\tconst lh = lastHit;\n\t\tif (lh !== null) {\n\t\t\tconst pred = lh.n;\n\t\t\tif (pred !== null) {\n\t\t\t\tconst pa = pred.a;\n\t\t\t\tlet k = 0;\n\t\t\t\tlet ok = true;\n\t\t\t\tfor (let i = 0; i < nArgs; i++) {\n\t\t\t\t\tconst v = arguments[i];\n\t\t\t\t\tif (!v) continue;\n\t\t\t\t\tif (v !== pa[k]) {\n\t\t\t\t\t\tok = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tk++;\n\t\t\t\t}\n\t\t\t\tif (ok && k === pred.t) {\n\t\t\t\t\tlastHit = pred;\n\t\t\t\t\treturn pred.r;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (lh !== pred) {\n\t\t\t\tconst la = lh.a;\n\t\t\t\tlet k = 0;\n\t\t\t\tlet ok = true;\n\t\t\t\tfor (let i = 0; i < nArgs; i++) {\n\t\t\t\t\tconst v = arguments[i];\n\t\t\t\t\tif (!v) continue;\n\t\t\t\t\tif (v !== la[k]) {\n\t\t\t\t\t\tok = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tk++;\n\t\t\t\t}\n\t\t\t\tif (ok && k === lh.t) return lh.r;\n\t\t\t}\n\t\t}\n\t\tconst vals = [];\n\t\tfor (let i = 0; i < nArgs; i++) vals.push(arguments[i]);\n\t\treturn resolveArgs(vals, true);\n\t};\n};\n/**\n* Create a `cn` function bound to compiled tables — the entry point for\n* project-compiled (`cn build`) tables:\n*\n* ```ts\n* import tables from \"./cn-tables.js\"\n* import { createCn } from \"cn/engine\"\n* export const cn = createCn(tables)\n* ```\n*/\nconst createCn = (tables, validatorImpls, options) => {\n\tconst engine = createEngine(tables, validatorImpls, options);\n\treturn wrapClsx(engine.mergeString, engine);\n};\n\n//#endregion\nexport { clsx, createCn, createEngine, twJoin, wrapClsx };","import tables_generated_default from \"./tables.js\";\nimport { clsx, createEngine, twJoin, wrapClsx } from \"./engine.js\";\n\n//#region src/index.ts\nconst instance = /* @__PURE__ */ createEngine(tables_generated_default);\n/**\n* Merge Tailwind CSS classes with clsx-style arguments (strings, arrays,\n* objects, conditionals). Drop-in replacement for `twMerge(clsx(...))`.\n*/\nconst cn = /* @__PURE__ */ wrapClsx(instance.mergeString, instance);\n/** tailwind-merge–compatible variadic merge (strings + nested arrays). */\nconst twMerge = instance.merge;\n\n//#endregion\nexport { clsx, cn, createEngine, twJoin, twMerge };","import * as React from \"react\"\nimport { cn } from \"cn\"\n\nfunction Card({\n className,\n size = \"default\",\n ...props\n}: React.ComponentProps<\"div\"> & { size?: \"default\" | \"sm\" }) {\n return (\n <div\n data-slot=\"card\"\n data-size={size}\n className={cn(\n \"group/card flex flex-col gap-(--card-spacing) overflow-hidden rounded-xl bg-card py-(--card-spacing) text-sm text-card-foreground ring-1 ring-foreground/10 [--card-spacing:--spacing(4)] has-data-[slot=card-footer]:pb-0 has-[>img:first-child]:pt-0 data-[size=sm]:[--card-spacing:--spacing(3)] data-[size=sm]:has-data-[slot=card-footer]:pb-0 *:[img:first-child]:rounded-t-xl *:[img:last-child]:rounded-b-xl\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction CardHeader({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-header\"\n className={cn(\n \"group/card-header @container/card-header grid auto-rows-min items-start gap-1 rounded-t-xl px-(--card-spacing) has-data-[slot=card-action]:grid-cols-[1fr_auto] has-data-[slot=card-description]:grid-rows-[auto_auto] [.border-b]:pb-(--card-spacing)\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction CardTitle({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-title\"\n className={cn(\n \"font-heading text-base leading-snug font-medium group-data-[size=sm]/card:text-sm\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction CardDescription({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-description\"\n className={cn(\"text-sm text-muted-foreground\", className)}\n {...props}\n />\n )\n}\n\nfunction CardAction({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-action\"\n className={cn(\n \"col-start-2 row-span-2 row-start-1 self-start justify-self-end\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction CardContent({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-content\"\n className={cn(\"px-(--card-spacing)\", className)}\n {...props}\n />\n )\n}\n\nfunction CardFooter({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-footer\"\n className={cn(\n \"flex items-center rounded-b-xl border-t bg-muted/50 p-(--card-spacing)\",\n className\n )}\n {...props}\n />\n )\n}\n\nexport {\n Card,\n CardHeader,\n CardFooter,\n CardTitle,\n CardAction,\n CardDescription,\n CardContent,\n}\n","var kt=Object.defineProperty,xt=Object.defineProperties;var Gt=Object.getOwnPropertyDescriptors;var U=Object.getOwnPropertySymbols;var ht=Object.prototype.hasOwnProperty,St=Object.prototype.propertyIsEnumerable;var Et=(o,r,t)=>r in o?kt(o,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[r]=t,bt=(o,r)=>{for(var t in r||(r={}))ht.call(r,t)&&Et(o,t,r[t]);if(U)for(var t of U(r))St.call(r,t)&&Et(o,t,r[t]);return o},Pt=(o,r)=>xt(o,Gt(r));var wt=(o,r)=>{var t={};for(var u in o)ht.call(o,u)&&r.indexOf(u)<0&&(t[u]=o[u]);if(o!=null&&U)for(var u of U(o))r.indexOf(u)<0&&St.call(o,u)&&(t[u]=o[u]);return t};import*as e from\"react\";function _t(o){let r=setTimeout(o,0),t=setTimeout(o,10),u=setTimeout(o,50);return[r,t,u]}import*as Z from\"react\";function Tt(o){let r=Z.useRef();return Z.useEffect(()=>{r.current=o}),r.current}import*as h from\"react\";var Ot=18,nt=40,Lt=`${nt}px`;function Ct(o){let r=o.getBoundingClientRect().right,t=o;for(;t;){if(getComputedStyle(t).overflowX!==\"visible\")return t.getBoundingClientRect().left+t.clientLeft+t.clientWidth-r;t=t.parentElement}return document.documentElement.clientWidth-r}var jt=[\"[data-lastpass-icon-root]\",\"com-1password-button\",\"[data-dashlanecreated]\",'[style$=\"2147483647 !important;\"]'].join(\",\");function Mt({containerRef:o,inputRef:r,pushPasswordManagerStrategy:t,isFocused:u}){let[w,T]=h.useState(!1),[x,M]=h.useState(!1),[V,I]=h.useState(!1),q=h.useMemo(()=>t===\"none\"?!1:(t===\"increase-width\"||t===\"experimental-no-flickering\")&&w&&x,[w,x,t]),y=h.useCallback(()=>{let m=o.current,S=r.current;if(!m||!S||V||t===\"none\")return;let R=m,i=R.getBoundingClientRect().left+R.offsetWidth,G=R.getBoundingClientRect().top+R.offsetHeight/2,ot=i-Ot,X=G;document.querySelectorAll(jt).length===0&&document.elementFromPoint(ot,X)===m||(M(Ct(m)>=nt),T(!0),I(!0))},[o,r,V,t]);return h.useEffect(()=>{let m=o.current;if(!m||t===\"none\")return;function S(){M(Ct(m)>=nt)}S();let R=setInterval(S,1e3);return()=>{clearInterval(R)}},[o,t]),h.useEffect(()=>{let m=u||document.activeElement===r.current;if(t===\"none\"||!m)return;let S=setTimeout(y,0),R=setTimeout(y,2e3),i=setTimeout(y,5e3),G=setTimeout(()=>{I(!0)},6e3);return()=>{clearTimeout(S),clearTimeout(R),clearTimeout(i),clearTimeout(G)}},[r,u,t,y]),{hasPWMBadge:w,willPushPWMBadge:q,PWM_BADGE_SPACE_WIDTH:Lt}}var Nt=e.createContext({}),$t=e.forwardRef((ot,G)=>{var X=ot,{value:o,onChange:r,maxLength:t,textAlign:u=\"left\",pattern:w,placeholder:T,inputMode:x=\"numeric\",onComplete:M,pushPasswordManagerStrategy:V=\"increase-width\",pasteTransformer:I,containerClassName:q,noScriptCSSFallback:y=Ft,nonce:m,render:S,children:R}=X,i=wt(X,[\"value\",\"onChange\",\"maxLength\",\"textAlign\",\"pattern\",\"placeholder\",\"inputMode\",\"onComplete\",\"pushPasswordManagerStrategy\",\"pasteTransformer\",\"containerClassName\",\"noScriptCSSFallback\",\"nonce\",\"render\",\"children\"]);var z,ft,mt,pt,Rt;let[rt,at]=e.useState(typeof i.defaultValue==\"string\"?i.defaultValue:\"\"),l=o!=null?o:rt,D=Tt(l),O=e.useCallback(a=>{r==null||r(a),at(a)},[r]),p=e.useMemo(()=>w?typeof w==\"string\"?new RegExp(w):w:null,[w]),d=e.useRef(null),K=e.useRef(null),J=e.useRef({value:l,onChange:O,isIOS:typeof window!=\"undefined\"&&((ft=(z=window==null?void 0:window.CSS)==null?void 0:z.supports)==null?void 0:ft.call(z,\"-webkit-touch-callout\",\"none\"))}),Y=e.useRef({prev:[(mt=d.current)==null?void 0:mt.selectionStart,(pt=d.current)==null?void 0:pt.selectionEnd,(Rt=d.current)==null?void 0:Rt.selectionDirection]});e.useImperativeHandle(G,()=>d.current,[]),e.useEffect(()=>{let a=d.current,n=K.current;if(!a||!n)return;J.current.value!==a.value&&J.current.onChange(a.value),Y.current.prev=[a.selectionStart,a.selectionEnd,a.selectionDirection];function c(){if(document.activeElement!==a){j(null),N(null);return}let s=a.selectionStart,P=a.selectionEnd,$=a.selectionDirection,v=a.maxLength,B=a.value,_=Y.current.prev,g=-1,E=-1,C;if(B.length!==0&&s!==null&&P!==null){let Bt=s===P,Wt=s===B.length&&B.length<v;if(Bt&&!Wt){let W=s;if(W===0)g=0,E=1,C=\"forward\";else if(W===v)g=W-1,E=W,C=\"backward\";else if(v>1&&B.length>1){let et=0;if(_[0]!==null&&_[1]!==null){C=W<_[1]?\"backward\":\"forward\";let At=_[0]===_[1]&&_[0]<v;C===\"backward\"&&!At&&(et=-1)}g=et+W,E=et+W+1}}g!==-1&&E!==-1&&g!==E&&a.setSelectionRange(g,E,C)}let vt=g!==-1?g:s,gt=E!==-1?E:P,Ht=C!=null?C:$;j(vt),N(gt),Y.current.prev=[vt,gt,Ht]}if(document.addEventListener(\"selectionchange\",c,{capture:!0}),c(),document.activeElement===a&&Q(!0),!document.getElementById(\"input-otp-style\")){let s=document.createElement(\"style\");if(s.id=\"input-otp-style\",m&&s.setAttribute(\"nonce\",m),document.head.appendChild(s),s.sheet){let P=\"background: transparent !important; color: transparent !important; border-color: transparent !important; opacity: 0 !important; box-shadow: none !important; -webkit-box-shadow: none !important; -webkit-text-fill-color: transparent !important;\";F(s.sheet,\"[data-input-otp]::selection { background: transparent !important; color: transparent !important; }\"),F(s.sheet,`[data-input-otp]:autofill { ${P} }`),F(s.sheet,`[data-input-otp]:-webkit-autofill { ${P} }`),F(s.sheet,\"@supports (-webkit-touch-callout: none) { [data-input-otp] { letter-spacing: -.6em !important; font-weight: 100 !important; font-stretch: ultra-condensed; font-optical-sizing: none !important; left: -1px !important; right: 1px !important; } }\"),F(s.sheet,\"[data-input-otp] + * { pointer-events: all !important; }\")}}let b=()=>{n&&n.style.setProperty(\"--root-height\",`${a.clientHeight}px`)};b();let f=typeof ResizeObserver==\"undefined\"?null:new ResizeObserver(b);return f==null||f.observe(a),()=>{document.removeEventListener(\"selectionchange\",c,{capture:!0}),f==null||f.disconnect()}},[]);let[ct,it]=e.useState(!1),[L,Q]=e.useState(!1),[H,j]=e.useState(null),[A,N]=e.useState(null);e.useEffect(()=>{let a=_t(()=>{var f,s,P,$;(f=d.current)==null||f.dispatchEvent(new Event(\"input\"));let n=(s=d.current)==null?void 0:s.selectionStart,c=(P=d.current)==null?void 0:P.selectionEnd,b=($=d.current)==null?void 0:$.selectionDirection;n!==null&&c!==null&&(j(n),N(c),Y.current.prev=[n,c,b])});return()=>{a.forEach(n=>clearTimeout(n))}},[l,L]),e.useEffect(()=>{D!==void 0&&l!==D&&D.length<t&&l.length===t&&(M==null||M(l))},[t,M,D,l]);let k=Mt({containerRef:K,inputRef:d,pushPasswordManagerStrategy:V,isFocused:L}),st=e.useCallback(a=>{let n=a.currentTarget.value.slice(0,t);if(n.length>0&&p&&!p.test(n)){a.preventDefault();return}typeof D==\"string\"&&n.length<D.length&&document.dispatchEvent(new Event(\"selectionchange\")),O(n)},[t,O,D,p]),lt=e.useCallback(()=>{var a;if(d.current){let n=Math.min(d.current.value.length,t-1),c=d.current.value.length;(a=d.current)==null||a.setSelectionRange(n,c),j(n),N(c)}Q(!0)},[t]),ut=e.useCallback(a=>{var g,E;let n=d.current;if(!I&&(!J.current.isIOS||!a.clipboardData||!n))return;let c=a.clipboardData.getData(\"text/plain\"),b=I?I(c):c;a.preventDefault();let f=(g=d.current)==null?void 0:g.selectionStart,s=(E=d.current)==null?void 0:E.selectionEnd,v=(f!==s?l.slice(0,f)+b+l.slice(s):l.slice(0,f)+b+l.slice(f)).slice(0,t);if(v.length>0&&p&&!p.test(v))return;n.value=v,O(v);let B=Math.min(v.length,t-1),_=v.length;n.setSelectionRange(B,_),j(B),N(_)},[t,O,I,p,l]),It=e.useMemo(()=>({position:\"relative\",cursor:i.disabled?\"default\":\"text\",userSelect:\"none\",WebkitUserSelect:\"none\",pointerEvents:\"none\"}),[i.disabled]),dt=e.useMemo(()=>({position:\"absolute\",inset:0,width:k.willPushPWMBadge?`calc(100% + ${k.PWM_BADGE_SPACE_WIDTH})`:\"100%\",clipPath:k.willPushPWMBadge?`inset(0 ${k.PWM_BADGE_SPACE_WIDTH} 0 0)`:void 0,height:\"100%\",display:\"flex\",textAlign:u,opacity:\"1\",color:\"transparent\",pointerEvents:\"all\",background:\"transparent\",caretColor:\"transparent\",border:\"0 solid transparent\",outline:\"0 solid transparent\",boxShadow:\"none\",lineHeight:\"1\",letterSpacing:\"-.5em\",fontSize:\"var(--root-height, 16px)\",fontFamily:\"monospace\",fontVariantNumeric:\"tabular-nums\"}),[k.PWM_BADGE_SPACE_WIDTH,k.willPushPWMBadge,u]),yt=e.useMemo(()=>{var a;return e.createElement(\"input\",Pt(bt({autoComplete:i.autoComplete||\"one-time-code\"},i),{\"data-input-otp\":!0,\"data-input-otp-placeholder-shown\":l.length===0||void 0,\"data-input-otp-mss\":H,\"data-input-otp-mse\":A,inputMode:x,pattern:p==null?void 0:p.source,\"aria-placeholder\":T,style:dt,maxLength:t,value:l,ref:d,spellCheck:(a=i.spellCheck)!=null?a:!1,onPaste:n=>{var c;ut(n),(c=i.onPaste)==null||c.call(i,n)},onChange:st,onMouseOver:n=>{var c;it(!0),(c=i.onMouseOver)==null||c.call(i,n)},onMouseLeave:n=>{var c;it(!1),(c=i.onMouseLeave)==null||c.call(i,n)},onFocus:n=>{var c;lt(),(c=i.onFocus)==null||c.call(i,n)},onBlur:n=>{var c;Q(!1),(c=i.onBlur)==null||c.call(i,n)}}))},[st,lt,ut,x,dt,t,A,H,T,i,p==null?void 0:p.source,l]),tt=e.useMemo(()=>({slots:Array.from({length:t}).map((a,n)=>{var s;let c=L&&H!==null&&A!==null&&(H===A&&n===H||n>=H&&n<A),b=l[n]!==void 0?l[n]:null,f=l[0]!==void 0?null:(s=T==null?void 0:T[n])!=null?s:null;return{char:b,placeholderChar:f,isActive:c,hasFakeCaret:c&&b===null}}),isFocused:L,isHovering:!i.disabled&&ct}),[L,ct,t,A,H,T,i.disabled,l]),Dt=e.useMemo(()=>S?S(tt):e.createElement(Nt.Provider,{value:tt},R),[R,tt,S]);return e.createElement(e.Fragment,null,y!==null&&e.createElement(\"noscript\",null,e.createElement(\"style\",null,y)),e.createElement(\"div\",{ref:K,\"data-input-otp-container\":!0,translate:\"no\",style:It,className:q},Dt,e.createElement(\"div\",{style:{position:\"absolute\",inset:0,pointerEvents:\"none\"}},yt)))});$t.displayName=\"Input\";function F(o,r){try{o.insertRule(r)}catch(t){console.warn(\"input-otp could not insert CSS rule:\",r)}}var Ft=`\n[data-input-otp] {\n --nojs-bg: white !important;\n --nojs-fg: black !important;\n\n background-color: var(--nojs-bg) !important;\n color: var(--nojs-fg) !important;\n caret-color: var(--nojs-fg) !important;\n letter-spacing: .25em !important;\n text-align: center !important;\n border: 1px solid var(--nojs-fg) !important;\n border-radius: 4px !important;\n width: 100% !important;\n}\n@media (prefers-color-scheme: dark) {\n [data-input-otp] {\n --nojs-bg: black !important;\n --nojs-fg: white !important;\n }\n}`;var Qt=\"^\\\\d+$\",te=\"^[a-zA-Z]+$\",ee=\"^[a-zA-Z0-9]+$\";export{$t as OTPInput,Nt as OTPInputContext,te as REGEXP_ONLY_CHARS,Qt as REGEXP_ONLY_DIGITS,ee as REGEXP_ONLY_DIGITS_AND_CHARS};\n//# sourceMappingURL=index.mjs.map","import * as React from \"react\"\nimport { cn } from \"cn\"\nimport { OTPInput, OTPInputContext } from \"input-otp\"\nimport { MinusIcon } from \"lucide-react\"\n\nfunction InputOTP({\n className,\n containerClassName,\n ...props\n}: React.ComponentProps<typeof OTPInput> & {\n containerClassName?: string\n}) {\n return (\n <OTPInput\n data-slot=\"input-otp\"\n containerClassName={cn(\n \"cn-input-otp flex items-center has-disabled:opacity-50\",\n containerClassName\n )}\n spellCheck={false}\n className={cn(\"disabled:cursor-not-allowed\", className)}\n {...props}\n />\n )\n}\n\nfunction InputOTPGroup({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"input-otp-group\"\n className={cn(\n \"flex items-center rounded-lg has-aria-invalid:border-destructive has-aria-invalid:ring-3 has-aria-invalid:ring-destructive/20 dark:has-aria-invalid:ring-destructive/40\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction InputOTPSlot({\n index,\n className,\n ...props\n}: React.ComponentProps<\"div\"> & {\n index: number\n}) {\n const inputOTPContext = React.useContext(OTPInputContext)\n const { char, hasFakeCaret, isActive } = inputOTPContext?.slots[index] ?? {}\n\n return (\n <div\n data-slot=\"input-otp-slot\"\n data-active={isActive}\n className={cn(\n \"relative flex size-8 items-center justify-center border-y border-r border-input text-sm transition-all outline-none first:rounded-l-lg first:border-l last:rounded-r-lg aria-invalid:border-destructive data-[active=true]:z-10 data-[active=true]:border-ring data-[active=true]:ring-3 data-[active=true]:ring-ring/50 data-[active=true]:aria-invalid:border-destructive data-[active=true]:aria-invalid:ring-destructive/20 dark:bg-input/30 dark:data-[active=true]:aria-invalid:ring-destructive/40\",\n className\n )}\n {...props}\n >\n {char}\n {hasFakeCaret && (\n <div className=\"pointer-events-none absolute inset-0 flex items-center justify-center\">\n <div className=\"h-4 w-px animate-caret-blink bg-foreground duration-1000\" />\n </div>\n )}\n </div>\n )\n}\n\nfunction InputOTPSeparator({ ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"input-otp-separator\"\n className=\"flex items-center [&_svg:not([class*='size-'])]:size-4\"\n role=\"separator\"\n {...props}\n >\n <MinusIcon\n />\n </div>\n )\n}\n\nexport { InputOTP, InputOTPGroup, InputOTPSlot, InputOTPSeparator }\n","function r(e){var t,f,n=\"\";if(\"string\"==typeof e||\"number\"==typeof e)n+=e;else if(\"object\"==typeof e)if(Array.isArray(e)){var o=e.length;for(t=0;t<o;t++)e[t]&&(f=r(e[t]))&&(n&&(n+=\" \"),n+=f)}else for(f in e)e[f]&&(n&&(n+=\" \"),n+=f);return n}export function clsx(){for(var e,t,f=0,n=\"\",o=arguments.length;f<o;f++)(e=arguments[f])&&(t=r(e))&&(n&&(n+=\" \"),n+=t);return n}export default clsx;","/**\n * Copyright 2022 Joe Bell. All rights reserved.\n *\n * This file is licensed to you under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with the\n * License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations under\n * the License.\n */ import { clsx } from \"clsx\";\nconst falsyToString = (value)=>typeof value === \"boolean\" ? `${value}` : value === 0 ? \"0\" : value;\nexport const cx = clsx;\nexport const cva = (base, config)=>(props)=>{\n var _config_compoundVariants;\n if ((config === null || config === void 0 ? void 0 : config.variants) == null) return cx(base, props === null || props === void 0 ? void 0 : props.class, props === null || props === void 0 ? void 0 : props.className);\n const { variants, defaultVariants } = config;\n const getVariantClassNames = Object.keys(variants).map((variant)=>{\n const variantProp = props === null || props === void 0 ? void 0 : props[variant];\n const defaultVariantProp = defaultVariants === null || defaultVariants === void 0 ? void 0 : defaultVariants[variant];\n if (variantProp === null) return null;\n const variantKey = falsyToString(variantProp) || falsyToString(defaultVariantProp);\n return variants[variant][variantKey];\n });\n const propsWithoutUndefined = props && Object.entries(props).reduce((acc, param)=>{\n let [key, value] = param;\n if (value === undefined) {\n return acc;\n }\n acc[key] = value;\n return acc;\n }, {});\n const getCompoundVariantClassNames = config === null || config === void 0 ? void 0 : (_config_compoundVariants = config.compoundVariants) === null || _config_compoundVariants === void 0 ? void 0 : _config_compoundVariants.reduce((acc, param)=>{\n let { class: cvClass, className: cvClassName, ...compoundVariantOptions } = param;\n return Object.entries(compoundVariantOptions).every((param)=>{\n let [key, value] = param;\n return Array.isArray(value) ? value.includes({\n ...defaultVariants,\n ...propsWithoutUndefined\n }[key]) : ({\n ...defaultVariants,\n ...propsWithoutUndefined\n })[key] === value;\n }) ? [\n ...acc,\n cvClass,\n cvClassName\n ] : acc;\n }, []);\n return cx(base, getVariantClassNames, getCompoundVariantClassNames, props === null || props === void 0 ? void 0 : props.class, props === null || props === void 0 ? void 0 : props.className);\n };\n\n","\"use client\"\n\nimport * as React from \"react\"\nimport { cn } from \"cn\"\n\nfunction Label({ className, ...props }: React.ComponentProps<\"label\">) {\n return (\n <label\n data-slot=\"label\"\n className={cn(\n \"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50\",\n className\n )}\n {...props}\n />\n )\n}\n\nexport { Label }\n","/**\n * Creates a formatErrorMessage function with a custom URL and prefix.\n * @param baseUrl - The base URL for the error page (e.g., 'https://base-ui.com/production-error')\n * @param prefix - The prefix for the error message (e.g., 'Base UI')\n * @returns A function that formats error messages with the given URL and prefix\n */\nexport function createFormatErrorMessage(baseUrl, prefix) {\n return function formatErrorMessage(code, ...args) {\n const url = new URL(baseUrl);\n url.searchParams.set('code', code.toString());\n args.forEach(arg => url.searchParams.append('args[]', arg));\n return `${prefix} error #${code}; visit ${url} for the full message.`;\n };\n}\n\n/**\n * WARNING: Don't import this directly. It's imported by the code generated by\n * `@mui/internal-babel-plugin-minify-errors`. Make sure to always use string literals in `Error`\n * constructors to ensure the plugin works as expected. Supported patterns include:\n * throw new Error('My message');\n * throw new Error(`My message: ${foo}`);\n * throw new Error(`My message: ${foo}` + 'another string');\n * ...\n */\nconst formatErrorMessage = createFormatErrorMessage('https://base-ui.com/production-error', 'Base UI');\nexport default formatErrorMessage;","'use client';\n\nimport * as React from 'react';\nconst UNINITIALIZED = {};\n\n/**\n * A React.useRef() that is initialized with a function. Note that it accepts an optional\n * initialization argument, so the initialization function doesn't need to be an inline closure.\n *\n * @usage\n * const ref = useRefWithInit(sortColumns, columns)\n */\n\nexport function useRefWithInit(init, initArg) {\n const ref = React.useRef(UNINITIALIZED);\n if (ref.current === UNINITIALIZED) {\n ref.current = init(initArg);\n }\n return ref;\n}","import { useRefWithInit } from \"./useRefWithInit.mjs\";\n\n/**\n * Merges refs into a single memoized callback ref or `null`.\n * This makes sure multiple refs are updated together and have the same value.\n *\n * This function accepts up to four refs. If you need to merge more, or have an unspecified number of refs to merge,\n * use `useMergedRefsN` instead.\n */\n\nexport function useMergedRefs(a, b, c, d) {\n const forkRef = useRefWithInit(createForkRef).current;\n if (didChange(forkRef, a, b, c, d)) {\n update(forkRef, [a, b, c, d]);\n }\n return forkRef.callback;\n}\n\n/**\n * Merges an array of refs into a single memoized callback ref or `null`.\n *\n * If you need to merge a fixed number (up to four) of refs, use `useMergedRefs` instead for better performance.\n */\nexport function useMergedRefsN(refs) {\n const forkRef = useRefWithInit(createForkRef).current;\n if (didChangeN(forkRef, refs)) {\n update(forkRef, refs);\n }\n return forkRef.callback;\n}\nfunction createForkRef() {\n return {\n callback: null,\n cleanup: null,\n refs: []\n };\n}\nfunction didChange(forkRef, a, b, c, d) {\n // prettier-ignore\n return forkRef.refs[0] !== a || forkRef.refs[1] !== b || forkRef.refs[2] !== c || forkRef.refs[3] !== d;\n}\nfunction didChangeN(forkRef, newRefs) {\n return forkRef.refs.length !== newRefs.length || forkRef.refs.some((ref, index) => ref !== newRefs[index]);\n}\nfunction update(forkRef, refs) {\n forkRef.refs = refs;\n if (refs.every(ref => ref == null)) {\n forkRef.callback = null;\n return;\n }\n forkRef.callback = instance => {\n if (forkRef.cleanup) {\n forkRef.cleanup();\n forkRef.cleanup = null;\n }\n if (instance != null) {\n const cleanupCallbacks = Array(refs.length).fill(null);\n for (let i = 0; i < refs.length; i += 1) {\n const ref = refs[i];\n if (ref == null) {\n continue;\n }\n switch (typeof ref) {\n case 'function':\n {\n const refCleanup = ref(instance);\n if (typeof refCleanup === 'function') {\n cleanupCallbacks[i] = refCleanup;\n }\n break;\n }\n case 'object':\n {\n ref.current = instance;\n break;\n }\n default:\n }\n }\n forkRef.cleanup = () => {\n for (let i = 0; i < refs.length; i += 1) {\n const ref = refs[i];\n if (ref == null) {\n continue;\n }\n switch (typeof ref) {\n case 'function':\n {\n const cleanupCallback = cleanupCallbacks[i];\n if (typeof cleanupCallback === 'function') {\n cleanupCallback();\n } else {\n // Legacy ref with no attach-time cleanup: detach by calling it with `null`.\n // It returns nothing; React 19 cleanups are handled in the branch above.\n void ref(null);\n }\n break;\n }\n case 'object':\n {\n ref.current = null;\n break;\n }\n default:\n }\n }\n };\n }\n };\n}","import * as React from 'react';\nconst majorVersion = parseInt(React.version, 10);\nexport function isReactVersionAtLeast(reactVersionToCheck) {\n return majorVersion >= reactVersionToCheck;\n}","import * as React from 'react';\nimport { isReactVersionAtLeast } from \"./reactVersion.mjs\";\n\n/**\n * Extracts the `ref` from a React element, handling different React versions.\n */\nexport function getReactElementRef(element) {\n if (! /*#__PURE__*/React.isValidElement(element)) {\n return null;\n }\n const reactElement = element;\n const propsWithRef = reactElement.props;\n return (isReactVersionAtLeast(19) ? propsWithRef?.ref : reactElement.ref) ?? null;\n}","export function mergeObjects(a, b) {\n if (a && !b) {\n return a;\n }\n if (!a && b) {\n return b;\n }\n if (a || b) {\n return {\n ...a,\n ...b\n };\n }\n return undefined;\n}","let loggedMessages;\nif (process.env.NODE_ENV !== 'production') {\n loggedMessages = new Set();\n}\n\n/** Creates a dev-only logger that writes each unique message to `console[severity]` once. */\nexport function createLogOnce(severity, prefix) {\n return function logOnce(...messages) {\n if (process.env.NODE_ENV !== 'production') {\n const message = messages.join(' ');\n const output = prefix ? `${prefix}: ${message}` : message;\n const key = `${severity}:${output}`;\n if (!loggedMessages.has(key)) {\n loggedMessages.add(key);\n if (severity === 'warn') {\n console.warn(output);\n } else {\n console.error(output);\n }\n }\n }\n };\n}\nexport function reset() {\n loggedMessages?.clear();\n}","import { createLogOnce } from \"./createLogOnce.mjs\";\nexport const warn = createLogOnce('warn', 'Base UI');\nexport { reset } from \"./createLogOnce.mjs\";","export function NOOP() {}\n\n// Typed as mutable `never[]` so it is assignable to any `T[]` fallback (for example\n// `defaultValue ?? EMPTY_ARRAY` in `useControlled` callers) without widening `T`.\n// Frozen so a write through a widened alias throws instead of mutating the shared singleton.\nexport const EMPTY_ARRAY = Object.freeze([]);\nexport const EMPTY_OBJECT = Object.freeze({});","export function getStateAttributesProps(state, customMapping) {\n const props = {};\n\n /* eslint-disable-next-line guard-for-in */\n for (const key in state) {\n const value = state[key];\n if (customMapping?.hasOwnProperty(key)) {\n const customProps = customMapping[key](value);\n if (customProps != null) {\n Object.assign(props, customProps);\n }\n continue;\n }\n if (value === true) {\n props[`data-${key.toLowerCase()}`] = '';\n } else if (value) {\n props[`data-${key.toLowerCase()}`] = value.toString();\n }\n }\n return props;\n}","/**\n * If the provided className is a string, it will be returned as is.\n * Otherwise, the function will call the className function with the state as the first argument.\n *\n * @param className\n * @param state\n */\nexport function resolveClassName(className, state) {\n return typeof className === 'function' ? className(state) : className;\n}","/**\n * If the provided style is an object, it will be returned as is.\n * Otherwise, the function will call the style function with the state as the first argument.\n *\n * @param style\n * @param state\n */\nexport function resolveStyle(style, state) {\n return typeof style === 'function' ? style(state) : style;\n}","import { mergeObjects } from '@base-ui/utils/mergeObjects';\nconst EMPTY_PROPS = {};\n\n/* eslint-disable id-denylist */\n/**\n * Merges multiple sets of React props. It follows the Object.assign pattern where the rightmost object's fields overwrite\n * the conflicting ones from others. This doesn't apply to event handlers, `className` and `style` props.\n *\n * Event handlers are merged and called in right-to-left order (rightmost handler executes first, leftmost last).\n * For React synthetic events, the rightmost handler can prevent prior (left-positioned) handlers from executing\n * by calling `event.preventBaseUIHandler()`. For non-synthetic events (custom events with primitive/object values),\n * all handlers always execute without prevention capability.\n *\n * The `className` prop is merged by concatenating classes in right-to-left order (rightmost class appears first in the string).\n * The `style` prop is merged with rightmost styles overwriting the prior ones.\n *\n * Props can either be provided as objects or as functions that take the previous props as an argument.\n * The function will receive the merged props up to that point (going from left to right):\n * so in the case of `(obj1, obj2, fn, obj3)`, `fn` will receive the merged props of `obj1` and `obj2`.\n * The function is responsible for chaining event handlers if needed (that is, we don't run the merge logic).\n *\n * Event handlers returned by the functions are not automatically prevented when `preventBaseUIHandler` is called.\n * They must check `event.baseUIHandlerPrevented` themselves and bail out if it's true.\n *\n * @important **`ref` is not merged.**\n * @param a Props object to merge.\n * @param b Props object to merge. The function will overwrite conflicting props from `a`.\n * @param c Props object to merge. The function will overwrite conflicting props from previous parameters.\n * @param d Props object to merge. The function will overwrite conflicting props from previous parameters.\n * @param e Props object to merge. The function will overwrite conflicting props from previous parameters.\n * @returns The merged props.\n * @public\n */\n\nexport function mergeProps(a, b, c, d, e) {\n if (!c && !d && !e && !a) {\n return createInitialMergedProps(b);\n }\n\n // We need to mutably own `merged`.\n let merged = createInitialMergedProps(a);\n if (b) {\n merged = mergeInto(merged, b);\n }\n if (c) {\n merged = mergeInto(merged, c);\n }\n if (d) {\n merged = mergeInto(merged, d);\n }\n if (e) {\n merged = mergeInto(merged, e);\n }\n return merged;\n}\n/* eslint-enable id-denylist */\n\n/**\n * Merges an arbitrary number of React props using the same logic as {@link mergeProps}.\n * This function accepts an array of props instead of individual arguments.\n *\n * This has slightly lower performance than {@link mergeProps} due to accepting an array\n * instead of a fixed number of arguments. Prefer {@link mergeProps} when merging 5 or\n * fewer prop sets for better performance.\n *\n * @param props Array of props to merge.\n * @returns The merged props.\n * @see mergeProps\n * @public\n */\nexport function mergePropsN(props) {\n if (props.length === 0) {\n return EMPTY_PROPS;\n }\n if (props.length === 1) {\n return createInitialMergedProps(props[0]);\n }\n\n // We need to mutably own `merged`.\n let merged = createInitialMergedProps(props[0]);\n for (let i = 1; i < props.length; i += 1) {\n merged = mergeInto(merged, props[i]);\n }\n return merged;\n}\nfunction createInitialMergedProps(inputProps) {\n if (isPropsGetter(inputProps)) {\n // Getter-returned handlers intentionally keep their existing semantics.\n return {\n ...resolvePropsGetter(inputProps, EMPTY_PROPS)\n };\n }\n return copyInitialProps(inputProps);\n}\nfunction mergeInto(merged, inputProps) {\n if (isPropsGetter(inputProps)) {\n return resolvePropsGetter(inputProps, merged);\n }\n return mutablyMergeInto(merged, inputProps);\n}\nfunction copyInitialProps(inputProps) {\n const copiedProps = {\n ...inputProps\n };\n\n // `copiedProps` is our fresh own-object copy, so iterating with `for...in` is safe here.\n // eslint-disable-next-line guard-for-in\n for (const propName in copiedProps) {\n const propValue = copiedProps[propName];\n if (isEventHandler(propName, propValue)) {\n copiedProps[propName] = wrapEventHandler(propValue);\n }\n }\n return copiedProps;\n}\n\n/**\n * Merges two sets of props. In case of conflicts, the external props take precedence.\n */\nfunction mutablyMergeInto(mergedProps, externalProps) {\n if (!externalProps) {\n return mergedProps;\n }\n\n // eslint-disable-next-line guard-for-in\n for (const propName in externalProps) {\n const externalPropValue = externalProps[propName];\n switch (propName) {\n case 'style':\n {\n mergedProps[propName] = mergeObjects(mergedProps.style, externalPropValue);\n break;\n }\n case 'className':\n {\n mergedProps[propName] = mergeClassNames(mergedProps.className, externalPropValue);\n break;\n }\n default:\n {\n if (isEventHandler(propName, externalPropValue)) {\n mergedProps[propName] = mergeEventHandlers(mergedProps[propName], externalPropValue);\n } else {\n mergedProps[propName] = externalPropValue;\n }\n }\n }\n }\n return mergedProps;\n}\nfunction isEventHandler(key, value) {\n // This approach is more efficient than using a regex.\n const code0 = key.charCodeAt(0);\n const code1 = key.charCodeAt(1);\n const code2 = key.charCodeAt(2);\n return code0 === 111 /* o */ && code1 === 110 /* n */ && code2 >= 65 /* A */ && code2 <= 90 /* Z */ && (typeof value === 'function' || typeof value === 'undefined');\n}\nfunction isPropsGetter(inputProps) {\n return typeof inputProps === 'function';\n}\nfunction resolvePropsGetter(inputProps, previousProps) {\n if (isPropsGetter(inputProps)) {\n return inputProps(previousProps);\n }\n return inputProps ?? EMPTY_PROPS;\n}\nfunction mergeEventHandlers(ourHandler, theirHandler) {\n if (!theirHandler) {\n return ourHandler;\n }\n if (!ourHandler) {\n return wrapEventHandler(theirHandler);\n }\n return (...args) => {\n const event = args[0];\n if (isSyntheticEvent(event)) {\n const baseUIEvent = event;\n makeEventPreventable(baseUIEvent);\n const result = theirHandler(...args);\n if (!baseUIEvent.baseUIHandlerPrevented) {\n ourHandler?.(...args);\n }\n return result;\n }\n const result = theirHandler(...args);\n ourHandler?.(...args);\n return result;\n };\n}\nfunction wrapEventHandler(handler) {\n if (!handler) {\n return handler;\n }\n return (...args) => {\n const event = args[0];\n if (isSyntheticEvent(event)) {\n makeEventPreventable(event);\n }\n return handler(...args);\n };\n}\nexport function makeEventPreventable(event) {\n event.preventBaseUIHandler = () => {\n event.baseUIHandlerPrevented = true;\n };\n return event;\n}\nexport function mergeClassNames(ourClassName, theirClassName) {\n if (theirClassName) {\n if (ourClassName) {\n // eslint-disable-next-line prefer-template\n return theirClassName + ' ' + ourClassName;\n }\n return theirClassName;\n }\n return ourClassName;\n}\nfunction isSyntheticEvent(event) {\n return event != null && typeof event === 'object' && 'nativeEvent' in event;\n}","import _formatErrorMessage from \"@base-ui/utils/formatErrorMessage\";\nimport * as React from 'react';\nimport { useMergedRefs, useMergedRefsN } from '@base-ui/utils/useMergedRefs';\nimport { getReactElementRef } from '@base-ui/utils/getReactElementRef';\nimport { mergeObjects } from '@base-ui/utils/mergeObjects';\nimport { warn } from '@base-ui/utils/warn';\nimport { EMPTY_OBJECT } from '@base-ui/utils/empty';\nimport { getStateAttributesProps } from \"./getStateAttributesProps.mjs\";\nimport { resolveClassName } from \"../utils/resolveClassName.mjs\";\nimport { resolveStyle } from \"../utils/resolveStyle.mjs\";\nimport { mergeProps, mergePropsN, mergeClassNames } from \"../merge-props/index.mjs\";\nimport { createElement as _createElement } from \"react\";\n/**\n * Renders a Base UI element.\n *\n * @param element The default HTML element to render. Can be overridden by the `render` prop.\n * @param componentProps An object containing the `render` and `className` props to be used for element customization. Other props are ignored.\n * @param params Additional parameters for rendering the element.\n */\nexport function useRenderElement(element, componentProps, params = {}) {\n let renderProp = componentProps.render;\n if (params.enabled !== false) {\n // A pending lazy element suspends when unwrapped, so leave it wrapped while disabled.\n renderProp = unwrapLazyRenderProp(renderProp);\n }\n const outProps = useRenderElementProps(componentProps, params, renderProp);\n if (params.enabled === false) {\n return null;\n }\n const state = params.state ?? EMPTY_OBJECT;\n return evaluateRenderProp(element, renderProp, outProps, state);\n}\n\n/**\n * Computes render element final props.\n */\nfunction useRenderElementProps(componentProps, params, renderProp) {\n const {\n className: classNameProp,\n style: styleProp\n } = componentProps;\n const {\n state = EMPTY_OBJECT,\n ref,\n props,\n stateAttributesMapping,\n enabled = true\n } = params;\n const className = enabled ? resolveClassName(classNameProp, state) : undefined;\n const style = enabled ? resolveStyle(styleProp, state) : undefined;\n const stateProps = enabled ? getStateAttributesProps(state, stateAttributesMapping) : EMPTY_OBJECT;\n const resolvedProps = enabled && props ? resolveRenderFunctionProps(props) : undefined;\n\n // Ensure outProps is always a new mutable object when enabled, never EMPTY_OBJECT.\n // This prevents potential TypeError when setting ref, className, or style properties,\n // since EMPTY_OBJECT is frozen and mutations would fail in strict mode.\n const outProps = enabled ? mergeObjects(stateProps, resolvedProps) ?? {} : EMPTY_OBJECT;\n\n // SAFETY: The `useMergedRefs` functions use a single hook to store the same value,\n // switching between them at runtime is safe. If this assertion fails, React will\n // throw at runtime anyway.\n // This also skips the `useMergedRefs` call on the server, which is fine because\n // refs are not used on the server side.\n /* eslint-disable react-hooks/rules-of-hooks */\n if (typeof document !== 'undefined') {\n if (!enabled) {\n // Called only to keep the hook order stable when disabled; the merged ref is unused.\n void useMergedRefs(null, null);\n } else if (Array.isArray(ref)) {\n outProps.ref = useMergedRefsN([outProps.ref, getReactElementRef(renderProp), ...ref]);\n } else {\n outProps.ref = useMergedRefs(outProps.ref, getReactElementRef(renderProp), ref);\n }\n }\n if (!enabled) {\n return EMPTY_OBJECT;\n }\n if (className !== undefined) {\n outProps.className = mergeClassNames(outProps.className, className);\n }\n if (style !== undefined) {\n outProps.style = mergeObjects(outProps.style, style);\n }\n return outProps;\n}\nfunction resolveRenderFunctionProps(props) {\n if (Array.isArray(props)) {\n return mergePropsN(props);\n }\n return mergeProps(undefined, props);\n}\n\n// The symbol React uses internally for lazy components\n// https://github.com/react/react/blob/a0566250b210499b4c5677f5ac2eedbd71d51a1b/packages/shared/ReactSymbols.js#L31\n//\n// TODO delete once https://github.com/react/react/issues/32392 is fixed\nconst REACT_LAZY_TYPE = Symbol.for('react.lazy');\nconst COMPONENT_IDENTIFIER_PATTERN = /^[A-Z][A-Za-z0-9$]*$/;\nconst LOWERCASE_CHARACTER_PATTERN = /[a-z]/;\n\n// Workaround for https://github.com/react/react/issues/32392\n// The Flight client hands over a lazy wrapper in place of a render element created in a\n// Server Component. The wrapper exposes no `.props` or `.ref`, so it must be unwrapped\n// before those are read. This works because the toArray() logic unwraps the lazy\n// element type in\n// https://github.com/react/react/blob/a0566250b210499b4c5677f5ac2eedbd71d51a1b/packages/react/src/ReactChildren.js#L186\nfunction unwrapLazyRenderProp(render) {\n // `$$typeof` is a React internal, absent from the public element types.\n if (render?.$$typeof !== REACT_LAZY_TYPE) {\n return render;\n }\n // Keep the wrapper unless it unwraps to an element, so an invalid render prop is still\n // reported as one instead of silently falling back to the default element.\n const unwrapped = React.Children.toArray(render)[0];\n return /*#__PURE__*/React.isValidElement(unwrapped) ? unwrapped : render;\n}\nfunction evaluateRenderProp(element, render, props, state) {\n if (render) {\n if (typeof render === 'function') {\n if (process.env.NODE_ENV !== 'production') {\n warnIfRenderPropLooksLikeComponent(render);\n }\n return render(props, state);\n }\n const mergedProps = mergeProps(props, render.props);\n mergedProps.ref = props.ref;\n\n // There is a high number of indirections, the error message thrown by React.cloneElement() is\n // hard to use for developers, this logic provides a better context.\n //\n // Our general guideline is to never change the control flow depending on the environment.\n // However, React.cloneElement() throws if React.isValidElement() is false,\n // so we can throw before with custom message.\n if (process.env.NODE_ENV !== 'production') {\n if (! /*#__PURE__*/React.isValidElement(render)) {\n // TODO: fix mui/no-guarded-throw\n // eslint-disable-next-line mui/no-guarded-throw\n throw new Error(['Base UI: The `render` prop was provided an invalid React element as `React.isValidElement(render)` is `false`.', 'A valid React element must be provided to the `render` prop because it is cloned with props to replace the default element.', 'https://base-ui.com/r/invalid-render-prop'].join('\\n'));\n }\n }\n return /*#__PURE__*/React.cloneElement(render, mergedProps);\n }\n if (element) {\n if (typeof element === 'string') {\n return renderTag(element, props);\n }\n }\n // Unreachable, but the typings on `useRenderElement` need to be reworked\n // to annotate it correctly.\n throw new Error(process.env.NODE_ENV !== \"production\" ? 'Base UI: Render element or function are not defined.' : _formatErrorMessage(8));\n}\nfunction warnIfRenderPropLooksLikeComponent(renderFn) {\n const functionName = renderFn.name;\n if (functionName.length === 0) {\n return;\n }\n if (!COMPONENT_IDENTIFIER_PATTERN.test(functionName)) {\n return;\n }\n if (!LOWERCASE_CHARACTER_PATTERN.test(functionName)) {\n return;\n }\n warn(`The \\`render\\` prop received a function named \\`${functionName}\\` that starts with an uppercase letter.`, 'This usually means a React component was passed directly as `render={Component}`.', 'Base UI calls `render` as a plain function, which can break the Rules of Hooks during reconciliation.', 'If this is an intentional render callback, rename it to start with a lowercase letter.', 'Use `render={<Component />}` or `render={(props) => <Component {...props} />}` instead.', 'https://base-ui.com/r/invalid-render-prop');\n}\nfunction renderTag(Tag, props) {\n if (Tag === 'button') {\n return /*#__PURE__*/_createElement(\"button\", {\n type: \"button\",\n ...props,\n key: props.key\n });\n }\n if (Tag === 'img') {\n return /*#__PURE__*/_createElement(\"img\", {\n alt: \"\",\n ...props,\n key: props.key\n });\n }\n return /*#__PURE__*/React.createElement(Tag, props);\n}","\"use client\"\n\nimport { useMemo } from \"react\"\nimport { cva, type VariantProps } from \"class-variance-authority\"\nimport { cn } from \"cn\"\n\nimport { Label } from \"@/components/ui/label.js\"\nimport { Separator } from \"@/components/ui/separator.js\"\n\nfunction FieldSet({ className, ...props }: React.ComponentProps<\"fieldset\">) {\n return (\n <fieldset\n data-slot=\"field-set\"\n className={cn(\n \"flex flex-col gap-4 has-[>[data-slot=checkbox-group]]:gap-3 has-[>[data-slot=radio-group]]:gap-3\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction FieldLegend({\n className,\n variant = \"legend\",\n ...props\n}: React.ComponentProps<\"legend\"> & { variant?: \"legend\" | \"label\" }) {\n return (\n <legend\n data-slot=\"field-legend\"\n data-variant={variant}\n className={cn(\n \"mb-1.5 font-medium data-[variant=label]:text-sm data-[variant=legend]:text-base\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction FieldGroup({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"field-group\"\n className={cn(\n \"group/field-group @container/field-group flex w-full flex-col gap-5 data-[slot=checkbox-group]:gap-3 *:data-[slot=field-group]:gap-4\",\n className\n )}\n {...props}\n />\n )\n}\n\nconst fieldVariants = cva(\n \"group/field flex w-full gap-2 data-[invalid=true]:text-destructive\",\n {\n variants: {\n orientation: {\n vertical: \"flex-col *:w-full [&>.sr-only]:w-auto\",\n horizontal:\n \"flex-row items-center has-[>[data-slot=field-content]]:items-start *:data-[slot=field-label]:flex-auto has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px\",\n responsive:\n \"flex-col *:w-full @md/field-group:flex-row @md/field-group:items-center @md/field-group:*:w-auto @md/field-group:has-[>[data-slot=field-content]]:items-start @md/field-group:*:data-[slot=field-label]:flex-auto [&>.sr-only]:w-auto @md/field-group:has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px\",\n },\n },\n defaultVariants: {\n orientation: \"vertical\",\n },\n }\n)\n\nfunction Field({\n className,\n orientation = \"vertical\",\n ...props\n}: React.ComponentProps<\"div\"> & VariantProps<typeof fieldVariants>) {\n return (\n <div\n role=\"group\"\n data-slot=\"field\"\n data-orientation={orientation}\n className={cn(fieldVariants({ orientation }), className)}\n {...props}\n />\n )\n}\n\nfunction FieldContent({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"field-content\"\n className={cn(\n \"group/field-content flex flex-1 flex-col gap-0.5 leading-snug\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction FieldLabel({\n className,\n ...props\n}: React.ComponentProps<typeof Label>) {\n return (\n <Label\n data-slot=\"field-label\"\n className={cn(\n \"group/field-label peer/field-label flex w-fit gap-2 leading-snug group-data-[disabled=true]/field:opacity-50 has-data-checked:border-primary/30 has-data-checked:bg-primary/5 has-[>[data-slot=field]]:rounded-lg has-[>[data-slot=field]]:border has-[>[data-slot=field]]:not-has-[:disabled,[data-disabled]]:hover:bg-muted/50 has-[>[data-slot=field]]:has-[:focus-visible]:border-ring has-[>[data-slot=field]]:has-[:focus-visible]:ring-3 has-[>[data-slot=field]]:has-[:focus-visible]:ring-ring/50 *:data-[slot=field]:p-2.5 dark:has-data-checked:border-primary/20 dark:has-data-checked:bg-primary/10\",\n \"has-[>[data-slot=field]]:w-full has-[>[data-slot=field]]:flex-col\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction FieldTitle({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"field-label\"\n className={cn(\n \"flex w-fit items-center gap-2 text-sm font-medium group-data-[disabled=true]/field:opacity-50\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction FieldDescription({ className, ...props }: React.ComponentProps<\"p\">) {\n return (\n <p\n data-slot=\"field-description\"\n className={cn(\n \"text-left text-sm leading-normal font-normal text-muted-foreground group-has-data-horizontal/field:text-balance [[data-variant=legend]+&]:-mt-1.5\",\n \"last:mt-0 nth-last-2:-mt-1\",\n \"[&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction FieldSeparator({\n children,\n className,\n ...props\n}: React.ComponentProps<\"div\"> & {\n children?: React.ReactNode\n}) {\n return (\n <div\n data-slot=\"field-separator\"\n data-content={!!children}\n className={cn(\n \"relative -my-2 h-5 text-sm group-data-[variant=outline]/field-group:-mb-2\",\n className\n )}\n {...props}\n >\n <Separator className=\"absolute inset-0 top-1/2\" />\n {children && (\n <span\n className=\"relative mx-auto block w-fit bg-background px-2 text-muted-foreground\"\n data-slot=\"field-separator-content\"\n >\n {children}\n </span>\n )}\n </div>\n )\n}\n\nfunction FieldError({\n className,\n children,\n errors,\n ...props\n}: React.ComponentProps<\"div\"> & {\n errors?: Array<{ message?: string } | undefined>\n}) {\n const content = useMemo(() => {\n if (children) {\n return children\n }\n\n if (!errors?.length) {\n return null\n }\n\n const uniqueErrors = [\n ...new Map(errors.map((error) => [error?.message, error])).values(),\n ]\n\n if (uniqueErrors?.length == 1) {\n return uniqueErrors[0]?.message\n }\n\n return (\n <ul className=\"ml-4 flex list-disc flex-col gap-1\">\n {uniqueErrors.map(\n (error, index) =>\n error?.message && <li key={index}>{error.message}</li>\n )}\n </ul>\n )\n }, [children, errors])\n\n if (!content) {\n return null\n }\n\n return (\n <div\n role=\"alert\"\n data-slot=\"field-error\"\n className={cn(\"text-sm font-normal text-destructive\", className)}\n {...props}\n >\n {content}\n </div>\n )\n}\n\nexport {\n Field,\n FieldLabel,\n FieldDescription,\n FieldError,\n FieldGroup,\n FieldLegend,\n FieldSeparator,\n FieldSet,\n FieldContent,\n FieldTitle,\n}\n","function hasWindow() {\n return typeof window !== 'undefined';\n}\nfunction getNodeName(node) {\n if (isNode(node)) {\n return (node.nodeName || '').toLowerCase();\n }\n // Mocked nodes in testing environments may not be instances of Node. By\n // returning `#document` an infinite loop won't occur.\n // https://github.com/floating-ui/floating-ui/issues/2317\n return '#document';\n}\nfunction getWindow(node) {\n var _node$ownerDocument;\n return (node == null || (_node$ownerDocument = node.ownerDocument) == null ? void 0 : _node$ownerDocument.defaultView) || window;\n}\nfunction getDocumentElement(node) {\n var _ref;\n return (_ref = (isNode(node) ? node.ownerDocument : node.document) || window.document) == null ? void 0 : _ref.documentElement;\n}\nfunction isNode(value) {\n if (!hasWindow()) {\n return false;\n }\n return value instanceof Node || value instanceof getWindow(value).Node;\n}\nfunction isElement(value) {\n if (!hasWindow()) {\n return false;\n }\n return value instanceof Element || value instanceof getWindow(value).Element;\n}\nfunction isHTMLElement(value) {\n if (!hasWindow()) {\n return false;\n }\n return value instanceof HTMLElement || value instanceof getWindow(value).HTMLElement;\n}\nfunction isShadowRoot(value) {\n if (!hasWindow() || typeof ShadowRoot === 'undefined') {\n return false;\n }\n return value instanceof ShadowRoot || value instanceof getWindow(value).ShadowRoot;\n}\nfunction isOverflowElement(element) {\n const {\n overflow,\n overflowX,\n overflowY,\n display\n } = getComputedStyle(element);\n return /auto|scroll|overlay|hidden|clip/.test(overflow + overflowY + overflowX) && display !== 'inline' && display !== 'contents';\n}\nfunction isTableElement(element) {\n return /^(table|td|th)$/.test(getNodeName(element));\n}\nfunction isTopLayer(element) {\n try {\n if (element.matches(':popover-open')) {\n return true;\n }\n } catch (_e) {\n // no-op\n }\n try {\n return element.matches(':modal');\n } catch (_e) {\n return false;\n }\n}\nconst willChangeRe = /transform|translate|scale|rotate|perspective|filter/;\nconst containRe = /paint|layout|strict|content/;\nconst isNotNone = value => !!value && value !== 'none';\nlet isWebKitValue;\nfunction isContainingBlock(elementOrCss) {\n const css = isElement(elementOrCss) ? getComputedStyle(elementOrCss) : elementOrCss;\n\n // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block\n // https://drafts.csswg.org/css-transforms-2/#individual-transforms\n return isNotNone(css.transform) || isNotNone(css.translate) || isNotNone(css.scale) || isNotNone(css.rotate) || isNotNone(css.perspective) || !isWebKit() && (isNotNone(css.backdropFilter) || isNotNone(css.filter)) || willChangeRe.test(css.willChange || '') || containRe.test(css.contain || '');\n}\nfunction getContainingBlock(element) {\n let currentNode = getParentNode(element);\n while (isHTMLElement(currentNode) && !isLastTraversableNode(currentNode)) {\n if (isContainingBlock(currentNode)) {\n return currentNode;\n } else if (isTopLayer(currentNode)) {\n return null;\n }\n currentNode = getParentNode(currentNode);\n }\n return null;\n}\nfunction isWebKit() {\n if (isWebKitValue == null) {\n isWebKitValue = typeof CSS !== 'undefined' && CSS.supports && CSS.supports('-webkit-backdrop-filter', 'none');\n }\n return isWebKitValue;\n}\nfunction isLastTraversableNode(node) {\n return /^(html|body|#document)$/.test(getNodeName(node));\n}\nfunction getComputedStyle(element) {\n return getWindow(element).getComputedStyle(element);\n}\nfunction getNodeScroll(element) {\n if (isElement(element)) {\n return {\n scrollLeft: element.scrollLeft,\n scrollTop: element.scrollTop\n };\n }\n return {\n scrollLeft: element.scrollX,\n scrollTop: element.scrollY\n };\n}\nfunction getParentNode(node) {\n if (getNodeName(node) === 'html') {\n return node;\n }\n const result =\n // Step into the shadow DOM of the parent of a slotted node.\n node.assignedSlot ||\n // DOM Element detected.\n node.parentNode ||\n // ShadowRoot detected.\n isShadowRoot(node) && node.host ||\n // Fallback.\n getDocumentElement(node);\n return isShadowRoot(result) ? result.host : result;\n}\nfunction getNearestOverflowAncestor(node) {\n const parentNode = getParentNode(node);\n if (isLastTraversableNode(parentNode)) {\n return (node.ownerDocument || node).body;\n }\n if (isHTMLElement(parentNode) && isOverflowElement(parentNode)) {\n return parentNode;\n }\n return getNearestOverflowAncestor(parentNode);\n}\nfunction getOverflowAncestors(node, list, traverseIframes) {\n var _node$ownerDocument2;\n if (list === void 0) {\n list = [];\n }\n if (traverseIframes === void 0) {\n traverseIframes = true;\n }\n const scrollableAncestor = getNearestOverflowAncestor(node);\n const isBody = scrollableAncestor === ((_node$ownerDocument2 = node.ownerDocument) == null ? void 0 : _node$ownerDocument2.body);\n const win = getWindow(scrollableAncestor);\n if (isBody) {\n const frameElement = getFrameElement(win);\n return list.concat(win, win.visualViewport || [], isOverflowElement(scrollableAncestor) ? scrollableAncestor : [], frameElement && traverseIframes ? getOverflowAncestors(frameElement) : []);\n } else {\n return list.concat(scrollableAncestor, getOverflowAncestors(scrollableAncestor, [], traverseIframes));\n }\n}\nfunction getFrameElement(win) {\n return win.parent && Object.getPrototypeOf(win.parent) ? win.frameElement : null;\n}\n\nexport { getComputedStyle, getContainingBlock, getDocumentElement, getFrameElement, getNearestOverflowAncestor, getNodeName, getNodeScroll, getOverflowAncestors, getParentNode, getWindow, isContainingBlock, isElement, isHTMLElement, isLastTraversableNode, isNode, isOverflowElement, isShadowRoot, isTableElement, isTopLayer, isWebKit };\n","import * as React from 'react';\n\n/**\n * A clone of the React namespace for reading APIs that may be missing in older\n * supported React versions. Bundlers can rewrite direct `React.someNewApi`\n * reads into named imports, which breaks React 17. Reading from this cloned\n * object keeps those lookups optional.\n *\n * @see https://github.com/mui/material-ui/issues/41190#issuecomment-2040873379\n */\nexport const SafeReact = {\n ...React\n};","'use client';\n\nimport { SafeReact } from \"./safeReact.mjs\";\nimport { useRefWithInit } from \"./useRefWithInit.mjs\";\nconst useInsertionEffect = SafeReact.useInsertionEffect;\nconst useSafeInsertionEffect =\n// React 17 doesn't have useInsertionEffect.\nuseInsertionEffect &&\n// Preact replaces useInsertionEffect with useLayoutEffect and fires too late.\nuseInsertionEffect !== SafeReact.useLayoutEffect ? useInsertionEffect : fn => fn();\n/**\n * Stabilizes the function passed so it's always the same between renders.\n *\n * The function becomes non-reactive to any values it captures.\n * It can safely be passed as a dependency of `React.useMemo` and `React.useEffect` without re-triggering them if its captured values change.\n *\n * The function must only be called inside effects and event handlers, never during render (which throws an error).\n *\n * This hook is a more permissive version of React 19.2's `React.useEffectEvent` in that it can be passed through contexts and called in event handler props, not just effects.\n */\nexport function useStableCallback(callback) {\n const stable = useRefWithInit(createStableCallback).current;\n stable.next = callback;\n useSafeInsertionEffect(stable.effect);\n return stable.trampoline;\n}\nfunction createStableCallback() {\n const stable = {\n next: undefined,\n callback: assertNotCalled,\n trampoline: (...args) => stable.callback?.(...args),\n effect: () => {\n stable.callback = stable.next;\n }\n };\n return stable;\n}\nfunction assertNotCalled() {\n if (process.env.NODE_ENV !== 'production') {\n // TODO: fix mui/no-guarded-throw\n // eslint-disable-next-line mui/no-guarded-throw\n throw /* minify-error-disabled */new Error('Base UI: Cannot call an event handler while rendering.');\n }\n}","import { createLogOnce } from \"./createLogOnce.mjs\";\nexport const error = createLogOnce('error', 'Base UI');\nexport { reset } from \"./createLogOnce.mjs\";","'use client';\n\nimport * as React from 'react';\nconst noop = () => {};\nexport const useIsoLayoutEffect = typeof document !== 'undefined' ? React.useLayoutEffect : noop;","'use client';\n\nimport _formatErrorMessage from \"@base-ui/utils/formatErrorMessage\";\nimport * as React from 'react';\nexport const CompositeRootContext = /*#__PURE__*/React.createContext(undefined);\nif (process.env.NODE_ENV !== \"production\") CompositeRootContext.displayName = \"CompositeRootContext\";\nexport function useCompositeRootContext(optional = false) {\n const context = React.useContext(CompositeRootContext);\n if (context === undefined && !optional) {\n throw new Error(process.env.NODE_ENV !== \"production\" ? 'Base UI: CompositeRootContext is missing. Composite parts must be placed within <Composite.Root>.' : _formatErrorMessage(16));\n }\n return context;\n}","'use client';\n\nimport * as React from 'react';\nexport function useFocusableWhenDisabled(parameters) {\n const {\n focusableWhenDisabled,\n disabled,\n composite = false,\n tabIndex: tabIndexProp = 0,\n isNativeButton\n } = parameters;\n const isFocusableComposite = composite && focusableWhenDisabled !== false;\n const isNonFocusableComposite = composite && focusableWhenDisabled === false;\n\n // we can't explicitly assign `undefined` to any of these props because it\n // would otherwise prevent subsequently merged props from setting them\n const props = React.useMemo(() => {\n const additionalProps = {\n // allow Tabbing away from focusableWhenDisabled elements\n onKeyDown(event) {\n if (disabled && focusableWhenDisabled && event.key !== 'Tab') {\n event.preventDefault();\n }\n }\n };\n if (!composite) {\n additionalProps.tabIndex = tabIndexProp;\n if (!isNativeButton && disabled) {\n additionalProps.tabIndex = focusableWhenDisabled ? tabIndexProp : -1;\n }\n }\n if (isNativeButton && (focusableWhenDisabled || isFocusableComposite) || !isNativeButton && disabled) {\n additionalProps['aria-disabled'] = disabled;\n }\n if (isNativeButton && (!focusableWhenDisabled || isNonFocusableComposite)) {\n additionalProps.disabled = disabled;\n }\n return additionalProps;\n }, [composite, disabled, focusableWhenDisabled, isFocusableComposite, isNonFocusableComposite, isNativeButton, tabIndexProp]);\n return {\n props\n };\n}","export { getWindow as ownerWindow } from '@floating-ui/utils/dom';\nexport function ownerDocument(node) {\n return node?.ownerDocument || document;\n}","import { ownerWindow } from '@base-ui/utils/owner';\n/**\n * Dispatches a constructed click on the target so it carries the source event's\n * modifier state, which `click()` always reports as unpressed. Like `click()`,\n * the untrusted click still runs native activation behavior (form submission,\n * link navigation).\n * `detail` defaults to 0 (the native convention for keyboard-generated clicks);\n * pass `detail: 1` when the click represents a mouse gesture so consumers keying\n * off `detail === 0` don't classify it as a keyboard activation.\n */\nexport function dispatchClickWithModifiers(target, sourceEvent, {\n detail = 0\n} = {}) {\n target.dispatchEvent(new (ownerWindow(target).PointerEvent)('click', {\n bubbles: true,\n cancelable: true,\n composed: true,\n detail,\n shiftKey: sourceEvent.shiftKey,\n ctrlKey: sourceEvent.ctrlKey,\n altKey: sourceEvent.altKey,\n metaKey: sourceEvent.metaKey\n }));\n}","'use client';\n\nimport * as React from 'react';\nimport { isHTMLElement } from '@floating-ui/utils/dom';\nimport { useStableCallback } from '@base-ui/utils/useStableCallback';\nimport { error } from '@base-ui/utils/error';\nimport { SafeReact } from '@base-ui/utils/safeReact';\nimport { useIsoLayoutEffect } from '@base-ui/utils/useIsoLayoutEffect';\nimport { makeEventPreventable, mergeProps } from \"../../merge-props/index.mjs\";\nimport { useCompositeRootContext } from \"../composite/root/CompositeRootContext.mjs\";\nimport { useFocusableWhenDisabled } from \"../../utils/useFocusableWhenDisabled.mjs\";\nimport { dispatchClickWithModifiers } from \"../../utils/dispatchClickWithModifiers.mjs\";\nexport function useButton(parameters = {}) {\n const {\n disabled = false,\n focusableWhenDisabled,\n tabIndex = 0,\n native: isNativeButton = true,\n composite: compositeProp\n } = parameters;\n const elementRef = React.useRef(null);\n const compositeRootContext = useCompositeRootContext(true);\n const isCompositeItem = compositeProp ?? compositeRootContext !== undefined;\n const {\n props: focusableWhenDisabledProps\n } = useFocusableWhenDisabled({\n focusableWhenDisabled,\n disabled,\n composite: isCompositeItem,\n tabIndex,\n isNativeButton\n });\n if (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useEffect(() => {\n if (!elementRef.current) {\n return;\n }\n const isButtonTag = isButtonElement(elementRef.current);\n if (isNativeButton) {\n if (!isButtonTag) {\n const ownerStackMessage = SafeReact.captureOwnerStack?.() || '';\n const message = 'A component that acts as a button expected a native <button> because the ' + '`nativeButton` prop is true. Rendering a non-<button> removes native button ' + 'semantics, which can impact forms and accessibility. Use a real <button> in the ' + '`render` prop, or set `nativeButton` to `false`.';\n error(`${message}${ownerStackMessage}`);\n }\n } else if (isButtonTag) {\n const ownerStackMessage = SafeReact.captureOwnerStack?.() || '';\n const message = 'A component that acts as a button expected a non-<button> because the `nativeButton` ' + 'prop is false. Rendering a <button> keeps native behavior while Base UI applies ' + 'non-native attributes and handlers, which can add unintended extra attributes (such ' + 'as `role` or `aria-disabled`). Use a non-<button> in the `render` prop, or set ' + '`nativeButton` to `true`.';\n error(`${message}${ownerStackMessage}`);\n }\n }, [isNativeButton]);\n }\n\n // handles a disabled composite button rendering another button, e.g.\n // <Toolbar.Button disabled render={<Menu.Trigger />} />\n // the `disabled` prop needs to pass through 2 `useButton`s then finally\n // delete the `disabled` attribute from DOM\n const updateDisabled = React.useCallback(() => {\n const element = elementRef.current;\n if (!isButtonElement(element)) {\n return;\n }\n if (isCompositeItem && disabled && focusableWhenDisabledProps.disabled === undefined && element.disabled) {\n element.disabled = false;\n }\n }, [disabled, focusableWhenDisabledProps.disabled, isCompositeItem]);\n useIsoLayoutEffect(updateDisabled, [updateDisabled]);\n const getButtonProps = React.useCallback((externalProps = {}) => {\n const {\n onClick: externalOnClick,\n onMouseDown: externalOnMouseDown,\n onKeyUp: externalOnKeyUp,\n onKeyDown: externalOnKeyDown,\n onPointerDown: externalOnPointerDown,\n ...otherExternalProps\n } = externalProps;\n return mergeProps({\n onClick(event) {\n if (disabled) {\n event.preventDefault();\n return;\n }\n externalOnClick?.(event);\n },\n onMouseDown(event) {\n if (!disabled) {\n externalOnMouseDown?.(event);\n }\n },\n onKeyDown(event) {\n if (disabled) {\n return;\n }\n makeEventPreventable(event);\n externalOnKeyDown?.(event);\n if (event.baseUIHandlerPrevented) {\n return;\n }\n const isCurrentTarget = event.target === event.currentTarget;\n const currentTarget = event.currentTarget;\n const isButton = isButtonElement(currentTarget);\n const isLink = !isNativeButton && isValidLinkElement(currentTarget);\n const shouldClick = isCurrentTarget && (isNativeButton ? isButton : !isLink);\n const isEnterKey = event.key === 'Enter';\n const isSpaceKey = event.key === ' ';\n const role = currentTarget.getAttribute('role');\n const isTextNavigationRole = role?.startsWith('menuitem') || role === 'option' || role === 'gridcell';\n if (isCurrentTarget && isCompositeItem && isSpaceKey) {\n if (event.defaultPrevented && isTextNavigationRole) {\n return;\n }\n event.preventDefault();\n\n // Only a native-mode item that isn't a real <button> is excluded.\n if (!isNativeButton || isButton) {\n event.preventBaseUIHandler();\n dispatchClickWithModifiers(currentTarget, event);\n }\n return;\n }\n\n // Keyboard accessibility for native and non-native elements.\n if (!shouldClick || isNativeButton || !isSpaceKey && !isEnterKey) {\n // Space activates links on keyup (`role=\"button\"` semantics, matching the\n // composite path); prevent the page scroll Space would otherwise trigger.\n // Enter is left to the browser's native link activation.\n if (isCurrentTarget && isLink && isSpaceKey) {\n event.preventDefault();\n }\n return;\n }\n\n // Match native buttons: preventing the keydown's default cancels activation.\n if (event.defaultPrevented) {\n return;\n }\n event.preventDefault();\n if (isEnterKey) {\n event.preventBaseUIHandler();\n dispatchClickWithModifiers(currentTarget, event);\n }\n },\n onKeyUp(event) {\n if (disabled) {\n return;\n }\n\n // calling preventDefault in keyUp on a <button> will not dispatch a click event if Space is pressed\n // https://codesandbox.io/p/sandbox/button-keyup-preventdefault-dn7f0\n makeEventPreventable(event);\n externalOnKeyUp?.(event);\n if (event.target === event.currentTarget && isNativeButton && isCompositeItem && isButtonElement(event.currentTarget) && event.key === ' ') {\n event.preventDefault();\n return;\n }\n if (event.baseUIHandlerPrevented) {\n return;\n }\n\n // Keyboard accessibility for non interactive elements.\n // Match native buttons: preventing the keyup's default cancels Space activation.\n // Limitation: unlike a native <button>, a prevented *keydown* cannot cancel the\n // activation — no state is kept between keydown and keyup, so we can't tell\n // whether the keydown was prevented or even happened on this element.\n if (event.target === event.currentTarget && !isNativeButton && !isCompositeItem && !event.defaultPrevented && event.key === ' ') {\n event.preventBaseUIHandler();\n dispatchClickWithModifiers(event.currentTarget, event);\n }\n },\n onPointerDown(event) {\n if (disabled) {\n event.preventDefault();\n return;\n }\n externalOnPointerDown?.(event);\n }\n }, isNativeButton ? {\n type: 'button'\n } : {\n role: 'button'\n }, focusableWhenDisabledProps, otherExternalProps);\n }, [disabled, focusableWhenDisabledProps, isCompositeItem, isNativeButton]);\n const buttonRef = useStableCallback(element => {\n elementRef.current = element;\n updateDisabled();\n });\n return {\n getButtonProps,\n buttonRef\n };\n}\nfunction isButtonElement(elem) {\n return isHTMLElement(elem) && elem.tagName === 'BUTTON';\n}\nfunction isValidLinkElement(elem) {\n return isHTMLElement(elem) && elem.tagName === 'A' && Boolean(elem.href);\n}","'use client';\n\nimport * as React from 'react';\nimport { useButton } from \"../internals/use-button/useButton.mjs\";\nimport { useRenderElement } from \"../internals/useRenderElement.mjs\";\n/**\n * A button component that can be used to trigger actions.\n * Renders a `<button>` element.\n *\n * Documentation: [Base UI Button](https://base-ui.com/react/components/button)\n */\nexport const Button = /*#__PURE__*/React.forwardRef(function Button(componentProps, forwardedRef) {\n const {\n render,\n className,\n disabled = false,\n focusableWhenDisabled = false,\n nativeButton = true,\n style,\n ...elementProps\n } = componentProps;\n const {\n getButtonProps,\n buttonRef\n } = useButton({\n disabled,\n focusableWhenDisabled,\n native: nativeButton\n });\n const state = {\n disabled\n };\n return useRenderElement('button', componentProps, {\n state,\n ref: [forwardedRef, buttonRef],\n props: [elementProps, getButtonProps]\n });\n});\nif (process.env.NODE_ENV !== \"production\") Button.displayName = \"Button\";","import { Button as ButtonPrimitive } from \"@base-ui/react/button\"\nimport { cva, type VariantProps } from \"class-variance-authority\"\nimport { cn } from \"cn\"\n\nconst buttonVariants = cva(\n \"group/button inline-flex shrink-0 items-center justify-center rounded-lg border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4\",\n {\n variants: {\n variant: {\n default: \"bg-primary text-primary-foreground hover:bg-primary/80\",\n outline:\n \"border-border bg-background hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50\",\n secondary:\n \"bg-secondary text-secondary-foreground hover:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)] aria-expanded:bg-secondary aria-expanded:text-secondary-foreground\",\n ghost:\n \"hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50\",\n destructive:\n \"bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40\",\n link: \"text-primary underline-offset-4 hover:underline\",\n },\n size: {\n default:\n \"h-8 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2\",\n xs: \"h-6 gap-1 rounded-[min(var(--radius-md),10px)] px-2 text-xs in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3\",\n sm: \"h-7 gap-1 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5\",\n lg: \"h-9 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2\",\n icon: \"size-8\",\n \"icon-xs\":\n \"size-6 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-lg [&_svg:not([class*='size-'])]:size-3\",\n \"icon-sm\":\n \"size-7 rounded-[min(var(--radius-md),12px)] in-data-[slot=button-group]:rounded-lg\",\n \"icon-lg\": \"size-9\",\n },\n },\n defaultVariants: {\n variant: \"default\",\n size: \"default\",\n },\n }\n)\n\nfunction Button({\n className,\n variant = \"default\",\n size = \"default\",\n ...props\n}: ButtonPrimitive.Props & VariantProps<typeof buttonVariants>) {\n return (\n <ButtonPrimitive\n data-slot=\"button\"\n className={cn(buttonVariants({ variant, size, className }))}\n {...props}\n />\n )\n}\n\nexport { Button, buttonVariants }\n","\"use client\"\r\n\r\nimport { useTagAuth } from \"../context/auth-context.js\"\r\nimport { RefreshCwIcon } from \"lucide-react\"\r\nimport {\r\n Card,\r\n CardHeader,\r\n CardTitle,\r\n CardDescription,\r\n CardContent,\r\n CardFooter,\r\n} from \"./ui/card.js\"\r\nimport {\r\n InputOTP,\r\n InputOTPGroup,\r\n InputOTPSlot,\r\n InputOTPSeparator,\r\n} from \"./ui/input-otp.js\"\r\nimport { Field, FieldDescription, FieldLabel } from \"./ui/field.js\"\r\nimport { Button } from \"./ui/button.js\"\r\n\r\n// ---- Types -----------------------------------------------------------------\r\n\r\nexport interface InputOTPFormLabels {\r\n title?: React.ReactNode\r\n /** Receives the email so callers can interpolate it */\r\n description?: (email?: string) => React.ReactNode\r\n codeLabel?: React.ReactNode\r\n resendIdle?: React.ReactNode\r\n resendLoading?: React.ReactNode\r\n verifyIdle?: React.ReactNode\r\n verifyLoading?: React.ReactNode\r\n successMessage?: React.ReactNode\r\n lostAccess?: React.ReactNode\r\n lostAccessHref?: string\r\n footer?: React.ReactNode\r\n}\r\n\r\nexport interface InputOTPFormProps {\r\n /** Override any of the default labels */\r\n labels?: InputOTPFormLabels\r\n /** Optional slot rendered inside the footer after the verify button */\r\n children?: React.ReactNode\r\n /** Optional className overrides for each slot */\r\n classNames?: {\r\n card?: string\r\n header?: string\r\n title?: string\r\n description?: string\r\n content?: string\r\n label?: string\r\n otpGroup?: string\r\n otpSeparator?: string\r\n error?: string\r\n success?: string\r\n submit?: string\r\n resend?: string\r\n footer?: string\r\n }\r\n}\r\n\r\n// ---- Defaults --------------------------------------------------------------\r\n\r\nconst defaultLabels: Required<InputOTPFormLabels> = {\r\n title: \"Verify your login\",\r\n description: (email) => (\r\n <>\r\n Enter the verification code we sent to your email address:{\" \"}\r\n <span className=\"font-medium\">{email}</span>.\r\n </>\r\n ),\r\n codeLabel: \"Verification code\",\r\n resendIdle: \"Resend Code\",\r\n resendLoading: \"Resending…\",\r\n verifyIdle: \"Verify\",\r\n verifyLoading: \"Verifying…\",\r\n successMessage: \"Code verified. Redirecting…\",\r\n lostAccess: \"I no longer have access to this email address.\",\r\n lostAccessHref: \"#\",\r\n footer: (\r\n <>\r\n Having trouble signing in?{\" \"}\r\n <a\r\n href=\"#\"\r\n className=\"font-medium underline underline-offset-4 hover:opacity-80\"\r\n >\r\n Contact support\r\n </a>\r\n </>\r\n ),\r\n}\r\n\r\n// ---- Component -------------------------------------------------------------\r\n\r\nexport function InputOTPForm({\r\n labels: labelsProp,\r\n children,\r\n classNames = {},\r\n}: InputOTPFormProps) {\r\n const {\r\n form,\r\n setOtp,\r\n verififyOTP,\r\n loading,\r\n success,\r\n setSuccess,\r\n error,\r\n setError,\r\n resendOtp,\r\n isResendingOtp: resending,\r\n } = useTagAuth()\r\n\r\n const otp = form?.otp\r\n const email = form?.email\r\n\r\n const labels = { ...defaultLabels, ...labelsProp }\r\n\r\n const onSetOTP = (value: string) => {\r\n setError(null)\r\n setSuccess(false)\r\n // 6 digit string, expires after 20 minutes\r\n setOtp(value)\r\n }\r\n\r\n const onVerify = async (e: React.FormEvent) => {\r\n e.preventDefault()\r\n setError(null)\r\n setSuccess(false)\r\n\r\n if (!otp || otp.length !== 6) {\r\n setError(\"Please enter the 6-digit verification code.\")\r\n return\r\n }\r\n\r\n try {\r\n await verififyOTP()\r\n } catch (err) {\r\n setError(err instanceof Error ? err.message : \"Invalid or expired code.\")\r\n }\r\n }\r\n\r\n const onResend = async () => {\r\n await resendOtp()\r\n }\r\n\r\n // Support both boolean and string success values\r\n const successMessage =\r\n typeof success === \"string\"\r\n ? success\r\n : success\r\n ? labels.successMessage\r\n : null\r\n\r\n const otpGroupClasses =\r\n \"*:data-[slot=input-otp-slot]:h-12 *:data-[slot=input-otp-slot]:w-11 *:data-[slot=input-otp-slot]:text-xl\"\r\n\r\n return (\r\n <Card\r\n className={[\r\n \"mx-auto w-full max-w-md border bg-card text-card-foreground shadow-lg\",\r\n classNames.card,\r\n ]\r\n .filter(Boolean)\r\n .join(\" \")}\r\n >\r\n <CardHeader\r\n className={[\"space-y-1\", classNames.header].filter(Boolean).join(\" \")}\r\n >\r\n <CardTitle\r\n className={[\"text-2xl font-semibold\", classNames.title]\r\n .filter(Boolean)\r\n .join(\" \")}\r\n >\r\n {labels.title}\r\n </CardTitle>\r\n <CardDescription className={classNames.description}>\r\n {typeof labels.description === \"function\"\r\n ? labels.description(email)\r\n : labels.description}\r\n </CardDescription>\r\n </CardHeader>\r\n\r\n <CardContent className={classNames.content}>\r\n <form onSubmit={onVerify} id=\"otp-form\">\r\n <Field>\r\n <div className=\"flex items-center justify-between\">\r\n <FieldLabel htmlFor=\"otp-verification\" className={classNames.label}>\r\n {labels.codeLabel}\r\n </FieldLabel>\r\n <Button\r\n variant=\"outline\"\r\n size=\"xs\"\r\n type=\"button\"\r\n onClick={onResend}\r\n disabled={resending}\r\n className={classNames.resend}\r\n >\r\n <RefreshCwIcon\r\n className={resending ? \"animate-spin\" : undefined}\r\n />\r\n {resending ? labels.resendLoading : labels.resendIdle}\r\n </Button>\r\n </div>\r\n\r\n <InputOTP\r\n maxLength={6}\r\n id=\"otp-verification\"\r\n required\r\n value={otp ?? \"\"}\r\n onChange={onSetOTP}\r\n containerClassName=\"justify-center\"\r\n >\r\n <InputOTPGroup\r\n className={[otpGroupClasses, classNames.otpGroup]\r\n .filter(Boolean)\r\n .join(\" \")}\r\n >\r\n <InputOTPSlot index={0} />\r\n <InputOTPSlot index={1} />\r\n <InputOTPSlot index={2} />\r\n </InputOTPGroup>\r\n <InputOTPSeparator\r\n className={[\"mx-2\", classNames.otpSeparator]\r\n .filter(Boolean)\r\n .join(\" \")}\r\n />\r\n <InputOTPGroup\r\n className={[otpGroupClasses, classNames.otpGroup]\r\n .filter(Boolean)\r\n .join(\" \")}\r\n >\r\n <InputOTPSlot index={3} />\r\n <InputOTPSlot index={4} />\r\n <InputOTPSlot index={5} />\r\n </InputOTPGroup>\r\n </InputOTP>\r\n\r\n {labels.lostAccess ? (\r\n <FieldDescription>\r\n <a\r\n href={labels.lostAccessHref}\r\n className=\"underline underline-offset-2 hover:opacity-80\"\r\n >\r\n {labels.lostAccess}\r\n </a>\r\n </FieldDescription>\r\n ) : null}\r\n\r\n {error ? (\r\n <p\r\n role=\"alert\"\r\n className={[\r\n \"mt-2 rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive\",\r\n classNames.error,\r\n ]\r\n .filter(Boolean)\r\n .join(\" \")}\r\n >\r\n {error}\r\n </p>\r\n ) : null}\r\n\r\n {successMessage ? (\r\n <p\r\n role=\"status\"\r\n className={[\r\n \"mt-2 rounded-md border border-emerald-500/30 bg-emerald-500/10 px-3 py-2 text-sm text-emerald-700 dark:text-emerald-300\",\r\n classNames.success,\r\n ]\r\n .filter(Boolean)\r\n .join(\" \")}\r\n >\r\n {successMessage}\r\n </p>\r\n ) : null}\r\n </Field>\r\n </form>\r\n </CardContent>\r\n\r\n <CardFooter className={classNames.footer}>\r\n <Field>\r\n <Button\r\n type=\"submit\"\r\n form=\"otp-form\"\r\n disabled={loading || (otp?.length ?? 0) !== 6}\r\n className={[\"w-full\", classNames.submit]\r\n .filter(Boolean)\r\n .join(\" \")}\r\n >\r\n {loading ? labels.verifyLoading : labels.verifyIdle}\r\n </Button>\r\n\r\n {children}\r\n\r\n {labels.footer ? (\r\n <div className=\"text-sm text-muted-foreground\">{labels.footer}</div>\r\n ) : null}\r\n </Field>\r\n </CardFooter>\r\n </Card>\r\n )\r\n}","/**\n * Present when the field is disabled.\n */\nexport const disabled = 'data-disabled';\n/**\n * Present when the field is in a valid state.\n */\nexport const valid = 'data-valid';\n/**\n * Present when the field is in an invalid state.\n */\nexport const invalid = 'data-invalid';\n/**\n * Present when the field has been touched.\n */\nexport const touched = 'data-touched';\n/**\n * Present when the field's value has changed.\n */\nexport const dirty = 'data-dirty';\n/**\n * Present when the field is filled.\n */\nexport const filled = 'data-filled';\n/**\n * Present when the field control is focused.\n */\nexport const focused = 'data-focused';","import * as FieldControlDataAttributes from \"../../field/control/FieldControlDataAttributes.mjs\";\nexport const DEFAULT_VALIDITY_STATE = {\n badInput: false,\n customError: false,\n patternMismatch: false,\n rangeOverflow: false,\n rangeUnderflow: false,\n stepMismatch: false,\n tooLong: false,\n tooShort: false,\n typeMismatch: false,\n valid: null,\n valueMissing: false\n};\nexport const DEFAULT_FIELD_STATE_ATTRIBUTES = {\n valid: null,\n touched: false,\n dirty: false,\n filled: false,\n focused: false\n};\nexport const DEFAULT_FIELD_ROOT_STATE = {\n disabled: false,\n ...DEFAULT_FIELD_STATE_ATTRIBUTES\n};\nexport const fieldValidityMapping = {\n valid(value) {\n if (value === null) {\n return null;\n }\n if (value) {\n return {\n [FieldControlDataAttributes.valid]: ''\n };\n }\n return {\n [FieldControlDataAttributes.invalid]: ''\n };\n }\n};","'use client';\n\nimport _formatErrorMessage from \"@base-ui/utils/formatErrorMessage\";\nimport * as React from 'react';\nimport { EMPTY_OBJECT } from '@base-ui/utils/empty';\nimport { NOOP } from \"../noop.mjs\";\nimport { DEFAULT_FIELD_ROOT_STATE, DEFAULT_VALIDITY_STATE } from \"../field-constants/constants.mjs\";\nexport const DEFAULT_FIELD_ROOT_CONTEXT = {\n invalid: undefined,\n name: undefined,\n validityData: {\n state: DEFAULT_VALIDITY_STATE,\n errors: [],\n error: '',\n value: '',\n initialValue: null\n },\n setValidityData: NOOP,\n disabled: undefined,\n setTouched: NOOP,\n setDirty: NOOP,\n setFilled: NOOP,\n setFocused: NOOP,\n validationMode: 'onSubmit',\n shouldValidateOnChange: () => false,\n state: DEFAULT_FIELD_ROOT_STATE,\n registerFieldControl: NOOP,\n validation: {\n getValidationProps: (_disabled, props = EMPTY_OBJECT) => props,\n inputRef: {\n current: null\n },\n registeredInputs: new Map(),\n registerInput: NOOP,\n getInputControl: () => null,\n commit: async () => {},\n change: NOOP\n }\n};\nexport const FieldRootContext = /*#__PURE__*/React.createContext(DEFAULT_FIELD_ROOT_CONTEXT);\nif (process.env.NODE_ENV !== \"production\") FieldRootContext.displayName = \"FieldRootContext\";\nexport function useFieldRootContext(optional = true) {\n const context = React.useContext(FieldRootContext);\n if (context.setValidityData === NOOP && !optional) {\n throw new Error(process.env.NODE_ENV !== \"production\" ? 'Base UI: FieldRootContext is missing. Field parts must be placed within <Field.Root>.' : _formatErrorMessage(28));\n }\n return context;\n}","'use client';\n\nimport * as React from 'react';\nimport { NOOP } from \"../noop.mjs\";\nexport const FormContext = /*#__PURE__*/React.createContext({\n elementRef: {\n current: null\n },\n formRef: {\n current: {\n fields: new Map()\n }\n },\n errors: {},\n clearErrors: NOOP,\n validationMode: 'onSubmit',\n submitCountRef: {\n current: 0\n }\n});\nif (process.env.NODE_ENV !== \"production\") FormContext.displayName = \"FormContext\";\nexport function useFormContext() {\n return React.useContext(FormContext);\n}","'use client';\n\nimport * as React from 'react';\nimport { SafeReact } from \"./safeReact.mjs\";\nlet globalId = 0;\n\n// TODO React 17: Remove `useGlobalId` once React 17 support is removed\nfunction useGlobalId(idOverride, prefix = 'mui') {\n const [defaultId, setDefaultId] = React.useState(idOverride);\n const id = idOverride || defaultId;\n React.useEffect(() => {\n if (defaultId == null) {\n // Fallback to this default id when possible.\n // Use the incrementing value for client-side rendering only.\n // We can't use it server-side.\n // If you want to use random values please consider the Birthday Problem: https://en.wikipedia.org/wiki/Birthday_problem\n globalId += 1;\n setDefaultId(`${prefix}-${globalId}`);\n }\n }, [defaultId, prefix]);\n return id;\n}\nconst maybeReactUseId = SafeReact.useId;\n\n/**\n *\n * @example <div id={useId()} />\n * @param idOverride\n * @returns {string}\n */\nexport function useId(idOverride, prefix) {\n // React.useId() is only available from React 17.0.0.\n if (maybeReactUseId !== undefined) {\n const reactId = maybeReactUseId();\n return idOverride ?? (prefix ? `${prefix}-${reactId}` : reactId);\n }\n\n // TODO: uncomment once we enable eslint-plugin-react-compiler // eslint-disable-next-line react-compiler/react-compiler\n // eslint-disable-next-line react-hooks/rules-of-hooks -- `React.useId` is invariant at runtime.\n return useGlobalId(idOverride, prefix);\n}","'use client';\n\nimport { useId } from '@base-ui/utils/useId';\n\n/**\n * Wraps `useId` and prefixes generated `id`s with `base-ui-`\n * @param {string | undefined} idOverride overrides the generated id when provided\n * @returns {string | undefined}\n */\nexport function useBaseUiId(idOverride) {\n return useId(idOverride, 'base-ui');\n}","'use client';\n\nimport * as React from 'react';\nimport { NOOP } from \"../noop.mjs\";\n/**\n * A context for providing [labelable elements](https://html.spec.whatwg.org/multipage/forms.html#category-label)\\\n * with an accessible name (label) and description.\n */\nexport const LabelableContext = /*#__PURE__*/React.createContext({\n controlId: undefined,\n registerControlId: NOOP,\n resetControlId: NOOP,\n labelId: undefined,\n setLabelId: NOOP,\n messageIds: [],\n setMessageIds: NOOP,\n getDescriptionProps: externalProps => externalProps\n});\nif (process.env.NODE_ENV !== \"production\") LabelableContext.displayName = \"LabelableContext\";\nexport function useLabelableContext() {\n return React.useContext(LabelableContext);\n}","'use client';\n\nimport * as React from 'react';\nimport { useIsoLayoutEffect } from '@base-ui/utils/useIsoLayoutEffect';\nimport { useStableCallback } from '@base-ui/utils/useStableCallback';\nimport { useRefWithInit } from '@base-ui/utils/useRefWithInit';\nimport { NOOP } from \"../noop.mjs\";\nimport { useBaseUiId } from \"../useBaseUiId.mjs\";\nimport { useLabelableContext } from \"./LabelableContext.mjs\";\nexport function useLabelableId(params = {}) {\n const {\n id,\n enabled = true\n } = params;\n const {\n controlId,\n registerControlId,\n resetControlId\n } = useLabelableContext();\n\n // Deliberately not seeded with `id`: on React 17 the seed would stick around after the\n // `id` prop is removed, leaving the control on a stale id forever.\n const defaultId = useBaseUiId();\n const controlSourceRef = useRefWithInit(() => Symbol());\n const hasRegisteredRef = React.useRef(false);\n const hadExplicitIdRef = React.useRef(false);\n const unregisterControlId = useStableCallback(() => {\n if (!hasRegisteredRef.current || registerControlId === NOOP) {\n return;\n }\n hasRegisteredRef.current = false;\n registerControlId(controlSourceRef.current, undefined);\n });\n useIsoLayoutEffect(() => {\n if (!enabled || registerControlId === NOOP) {\n unregisterControlId();\n return undefined;\n }\n let nextId;\n if (id !== undefined) {\n hadExplicitIdRef.current = true;\n nextId = id;\n } else if (hadExplicitIdRef.current) {\n nextId = defaultId;\n } else {\n // An id-less replacement must claim the provider's fallback so a previously registered\n // explicit id is not retained after its control unmounts.\n resetControlId();\n return undefined;\n }\n\n // Either the control never had an explicit `id`, or React 17 has not assigned the\n // fallback id yet. Neither is worth registering.\n if (nextId === undefined) {\n unregisterControlId();\n return undefined;\n }\n hasRegisteredRef.current = true;\n registerControlId(controlSourceRef.current, nextId);\n return undefined;\n }, [id, enabled, registerControlId, resetControlId, defaultId, controlSourceRef, unregisterControlId]);\n\n // Unregistering in the layout phase, not a passive effect: a replacement control's layout\n // effect would otherwise run first and still see the outgoing control's registration.\n useIsoLayoutEffect(() => {\n return unregisterControlId;\n }, [unregisterControlId]);\n\n // The provider's id wins until registration runs: the label renders `htmlFor` from the\n // provider's pre-registration state, so preempting it with an explicit `id` here would\n // leave the pair unassociated in server-rendered markup.\n return (enabled ? controlId : undefined) ?? id ?? defaultId;\n}","import { isShadowRoot } from '@floating-ui/utils/dom';\nexport function activeElement(doc) {\n let element = doc.activeElement;\n while (element?.shadowRoot?.activeElement != null) {\n element = element.shadowRoot.activeElement;\n }\n return element;\n}\nexport function contains(parent, child) {\n if (!parent || !child) {\n return false;\n }\n const rootNode = child.getRootNode?.();\n\n // First, attempt with the faster native method.\n if (parent.contains(child)) {\n return true;\n }\n\n // Then fall back to traversing out of shadow roots when needed.\n if (rootNode && isShadowRoot(rootNode)) {\n let next = child;\n while (next) {\n if (parent === next) {\n return true;\n }\n next = next.parentNode || next.host;\n }\n }\n return false;\n}\nexport function getTarget(event) {\n if ('composedPath' in event) {\n // The composed path is empty once the event is no longer being dispatched,\n // so fall back to `target` for handlers running after dispatch completes.\n return event.composedPath()[0] ?? event.target;\n }\n\n // TS assumes `composedPath()` always exists, but older browsers without\n // shadow DOM support still fall back to `target`.\n return event.target;\n}","'use client';\n\nimport * as React from 'react';\nimport { EMPTY_ARRAY } from \"./empty.mjs\";\n\n/**\n * A React.useEffect equivalent that runs once, when the component is mounted.\n */\nexport function useOnMount(fn) {\n // TODO: uncomment once we enable eslint-plugin-react-compiler // eslint-disable-next-line react-compiler/react-compiler -- no need to put `fn` in the dependency array\n /* eslint-disable react-hooks/exhaustive-deps */\n React.useEffect(fn, EMPTY_ARRAY);\n /* eslint-enable react-hooks/exhaustive-deps */\n}","'use client';\n\nimport { useRefWithInit } from \"./useRefWithInit.mjs\";\nimport { useOnMount } from \"./useOnMount.mjs\";\nconst EMPTY = 0;\nexport class Timeout {\n static create() {\n return new Timeout();\n }\n currentId = EMPTY;\n\n /**\n * Executes `fn` after `delay`, clearing any previously scheduled call.\n */\n start(delay, fn) {\n this.clear();\n this.currentId = setTimeout(() => {\n this.currentId = EMPTY;\n fn();\n }, delay); /* Node.js types are enabled in development */\n }\n isStarted() {\n return this.currentId !== EMPTY;\n }\n clear = () => {\n if (this.currentId !== EMPTY) {\n clearTimeout(this.currentId);\n this.currentId = EMPTY;\n }\n };\n disposeEffect = () => {\n return this.clear;\n };\n}\n\n/**\n * A `setTimeout` with automatic cleanup and guard.\n */\nexport function useTimeout() {\n const timeout = useRefWithInit(Timeout.create).current;\n useOnMount(timeout.disposeEffect);\n return timeout;\n}","'use client';\n\n// TODO: uncomment once we enable eslint-plugin-react-compiler // eslint-disable-next-line react-compiler/react-compiler -- process.env never changes, dependency arrays are intentionally ignored\n/* eslint-disable react-hooks/rules-of-hooks, react-hooks/exhaustive-deps */\nimport * as React from 'react';\nimport { error } from \"./error.mjs\";\n\n// A defined default guarantees a defined value. Otherwise, preserve `undefined`,\n// including when callers pass an explicit generic argument.\n\nexport function useControlled({\n controlled,\n default: defaultProp,\n name,\n state = 'value'\n}) {\n // isControlled is ignored in the hook dependency lists as it should never change.\n const {\n current: isControlled\n } = React.useRef(controlled !== undefined);\n const [valueState, setValue] = React.useState(defaultProp);\n // Keep the initial mode, but use the initial default if a controlled value disappears.\n // This preserves the defined-default overload while the mode-switch warning is emitted below.\n const value = isControlled && controlled !== undefined ? controlled : valueState;\n if (process.env.NODE_ENV !== 'production') {\n React.useEffect(() => {\n if (isControlled !== (controlled !== undefined)) {\n error([`A component is changing the ${isControlled ? '' : 'un'}controlled ${state} state of ${name} to be ${isControlled ? 'un' : ''}controlled.`, 'Elements should not switch from uncontrolled to controlled (or vice versa).', `Decide between using a controlled or uncontrolled ${name} ` + 'element for the lifetime of the component.', \"The nature of the state is determined during the first render. It's considered controlled if the value is not `undefined`.\", 'More info: https://fb.me/react-controlled-components'].join('\\n'));\n }\n }, [state, name, controlled]);\n const {\n current: defaultValue\n } = React.useRef(defaultProp);\n React.useEffect(() => {\n if (!isControlled && serializeToDevModeString(defaultValue) !== serializeToDevModeString(defaultProp)) {\n error([`A component is changing the default ${state} state of an uncontrolled ${name} after being initialized. ` + `To suppress this warning opt to use a controlled ${name}.`].join('\\n'));\n }\n }, [defaultProp]);\n }\n const setValueIfUncontrolled = React.useCallback(newValue => {\n if (!isControlled) {\n setValue(newValue);\n }\n }, []);\n return [value, setValueIfUncontrolled];\n}\nfunction serializeToDevModeString(input) {\n let nextId = 0;\n const seen = new WeakMap();\n try {\n const result = JSON.stringify(input, function replacer(key, value) {\n if (key === '_owner' && this != null && typeof this === 'object' && '$$typeof' in this) {\n return undefined;\n }\n if (typeof value === 'bigint') {\n return `__bigint__:${value}`;\n }\n if (value !== null && typeof value === 'object') {\n const id = seen.get(value);\n if (id !== undefined) {\n return `__object__:${id}`;\n }\n seen.set(value, nextId);\n nextId += 1;\n }\n return value;\n });\n return result ?? `__top__:${typeof input}`;\n } catch {\n return '__unserializable__';\n }\n}","'use client';\n\nimport { useIsoLayoutEffect } from '@base-ui/utils/useIsoLayoutEffect';\nimport { useRefWithInit } from '@base-ui/utils/useRefWithInit';\nimport { useFieldRootContext } from \"../field-root-context/FieldRootContext.mjs\";\nexport function useRegisterFieldControl(controlRef, id, value, getFormValueOverride, enabled = true, name) {\n const {\n registerFieldControl\n } = useFieldRootContext();\n const sourceRef = useRefWithInit(() => Symbol());\n\n // Re-register without unregistering first: re-registration with the same id updates the\n // form's fields Map entry in place, while a delete + re-add would move the field to the\n // end of the Map every time its value changes.\n useIsoLayoutEffect(() => {\n const source = sourceRef.current;\n if (!enabled) {\n registerFieldControl(source, undefined);\n return;\n }\n const registration = {\n controlRef,\n getValue: getFormValueOverride,\n id,\n name,\n value\n };\n registerFieldControl(source, registration);\n }, [controlRef, enabled, getFormValueOverride, id, name, registerFieldControl, sourceRef, value]);\n useIsoLayoutEffect(() => {\n const source = sourceRef.current;\n return () => {\n registerFieldControl(source, undefined);\n };\n }, [registerFieldControl, sourceRef]);\n}","'use client';\n\nimport * as React from 'react';\nimport { useIsoLayoutEffect } from '@base-ui/utils/useIsoLayoutEffect';\nimport { useStableCallback } from '@base-ui/utils/useStableCallback';\nexport function useValueChanged(value, onChange) {\n const valueRef = React.useRef(value);\n const onChangeCallback = useStableCallback(onChange);\n useIsoLayoutEffect(() => {\n if (valueRef.current !== value) {\n onChangeCallback(valueRef.current);\n }\n valueRef.current = value;\n }, [value, onChangeCallback]);\n}","export const none = 'none';\nexport const triggerPress = 'trigger-press';\nexport const triggerHover = 'trigger-hover';\nexport const triggerFocus = 'trigger-focus';\nexport const outsidePress = 'outside-press';\nexport const itemPress = 'item-press';\nexport const closePress = 'close-press';\nexport const linkPress = 'link-press';\nexport const clearPress = 'clear-press';\nexport const chipRemovePress = 'chip-remove-press';\nexport const trackPress = 'track-press';\nexport const incrementPress = 'increment-press';\nexport const decrementPress = 'decrement-press';\nexport const inputChange = 'input-change';\nexport const inputClear = 'input-clear';\nexport const inputBlur = 'input-blur';\nexport const inputPaste = 'input-paste';\nexport const inputPress = 'input-press';\nexport const focusOut = 'focus-out';\nexport const escapeKey = 'escape-key';\nexport const closeWatcher = 'close-watcher';\nexport const listNavigation = 'list-navigation';\nexport const keyboard = 'keyboard';\nexport const pointer = 'pointer';\nexport const drag = 'drag';\nexport const wheel = 'wheel';\nexport const scrub = 'scrub';\nexport const cancelOpen = 'cancel-open';\nexport const siblingOpen = 'sibling-open';\nexport const disabled = 'disabled';\nexport const missing = 'missing';\nexport const initial = 'initial';\nexport const imperativeAction = 'imperative-action';\nexport const swipe = 'swipe';\nexport const windowResize = 'window-resize';","import { EMPTY_OBJECT } from '@base-ui/utils/empty';\nimport { REASONS } from \"./reasons.mjs\";\n\n/**\n * Maps a change `reason` string to the corresponding native event type.\n */\n\n/**\n * Details of custom change events emitted by Base UI components.\n */\n\n/**\n * Details of custom generic events emitted by Base UI components.\n */\n\n/**\n * Creates a Base UI event details object with the given reason and utilities\n * for preventing Base UI's internal event handling.\n */\nexport function createChangeEventDetails(reason, event, trigger, customProperties) {\n let canceled = false;\n let allowPropagation = false;\n const custom = customProperties ?? EMPTY_OBJECT;\n const details = {\n reason,\n event: event ?? new Event('base-ui'),\n cancel() {\n canceled = true;\n },\n allowPropagation() {\n allowPropagation = true;\n },\n get isCanceled() {\n return canceled;\n },\n get isPropagationAllowed() {\n return allowPropagation;\n },\n trigger,\n ...custom\n };\n return details;\n}\nexport function createGenericEventDetails(reason, event, customProperties) {\n const custom = customProperties ?? EMPTY_OBJECT;\n const details = {\n reason,\n event: event ?? new Event('base-ui'),\n ...custom\n };\n return details;\n}","'use client';\n\nimport * as React from 'react';\nimport { useControlled } from '@base-ui/utils/useControlled';\nimport { useIsoLayoutEffect } from '@base-ui/utils/useIsoLayoutEffect';\nimport { ownerDocument } from '@base-ui/utils/owner';\nimport { useStableCallback } from '@base-ui/utils/useStableCallback';\nimport { useTimeout } from '@base-ui/utils/useTimeout';\nimport { useFieldRootContext } from \"../../internals/field-root-context/FieldRootContext.mjs\";\nimport { useRegisterFieldControl } from \"../../internals/field-register-control/useRegisterFieldControl.mjs\";\nimport { useFormContext } from \"../../internals/form-context/FormContext.mjs\";\nimport { useLabelableContext } from \"../../internals/labelable-provider/LabelableContext.mjs\";\nimport { useLabelableId } from \"../../internals/labelable-provider/useLabelableId.mjs\";\nimport { fieldValidityMapping } from \"../../internals/field-constants/constants.mjs\";\nimport { useRenderElement } from \"../../internals/useRenderElement.mjs\";\nimport { useValueChanged } from \"../../internals/useValueChanged.mjs\";\nimport { createChangeEventDetails } from \"../../internals/createBaseUIEventDetails.mjs\";\nimport { REASONS } from \"../../internals/reasons.mjs\";\nimport { activeElement } from \"../../floating-ui-react/utils.mjs\";\n\n/**\n * The form control to label and validate.\n * Renders an `<input>` element.\n *\n * You can omit this part and use any Base UI input component instead. For example,\n * [Input](https://base-ui.com/react/components/input), [Checkbox](https://base-ui.com/react/components/checkbox),\n * or [Select](https://base-ui.com/react/components/select), among others, will work with Field out of the box.\n *\n * Documentation: [Base UI Field](https://base-ui.com/react/components/field)\n */\nexport const FieldControl = /*#__PURE__*/React.forwardRef(function FieldControl(componentProps, forwardedRef) {\n const {\n render,\n className,\n id: idProp,\n name: nameProp,\n value: valueProp,\n disabled: disabledProp = false,\n onValueChange,\n defaultValue,\n autoFocus = false,\n style,\n ...elementProps\n } = componentProps;\n const {\n state: fieldState,\n name: fieldName,\n disabled: fieldDisabled,\n setTouched,\n setDirty,\n validityData,\n setFocused,\n setFilled,\n validationMode,\n validation\n } = useFieldRootContext();\n const {\n clearErrors,\n elementRef: formElementRef,\n submitCountRef\n } = useFormContext();\n const disabled = fieldDisabled || disabledProp;\n const name = fieldName ?? nameProp;\n const state = {\n ...fieldState,\n disabled\n };\n const {\n labelId\n } = useLabelableContext();\n const id = useLabelableId({\n id: idProp\n });\n const [valueUnwrapped] = useControlled({\n controlled: valueProp,\n default: defaultValue,\n name: 'FieldControl',\n state: 'value'\n });\n const isControlled = valueProp !== undefined;\n const value = isControlled ? valueUnwrapped : undefined;\n // The DOM value is always a string, so dirty comparisons must serialize the controlled value.\n const serializedValue = value == null ? undefined : String(value);\n const getValueFromInput = useStableCallback(() => validation.inputRef.current?.value);\n useRegisterFieldControl(validation.inputRef, id, serializedValue, getValueFromInput, !disabled, nameProp);\n useIsoLayoutEffect(() => {\n const currentValue = serializedValue ?? validation.inputRef.current?.value;\n if (currentValue !== undefined) {\n setFilled(currentValue !== '');\n }\n }, [serializedValue, validation.inputRef, setFilled]);\n useValueChanged(serializedValue, () => {\n if (serializedValue === undefined) {\n return;\n }\n clearErrors(name);\n setDirty(serializedValue !== (validityData.initialValue ?? ''));\n validation.change(serializedValue);\n });\n const inputRef = React.useRef(null);\n const enterValidationTimeout = useTimeout();\n useIsoLayoutEffect(() => {\n if (autoFocus && inputRef.current === activeElement(ownerDocument(inputRef.current))) {\n setFocused(true);\n }\n }, [autoFocus, setFocused]);\n const element = useRenderElement('input', componentProps, {\n ref: [forwardedRef, inputRef],\n state,\n props: [{\n id,\n disabled,\n name,\n ref: validation.inputRef,\n 'aria-labelledby': labelId,\n autoFocus,\n ...(isControlled ? {\n value\n } : {\n defaultValue\n }),\n onChange(event) {\n const inputValue = event.currentTarget.value;\n const details = createChangeEventDetails(REASONS.none, event.nativeEvent);\n onValueChange?.(inputValue, details);\n\n // Controlled values sync from the `value` prop instead, so that a value the consumer\n // rejects or rewrites never reaches the field state.\n if (isControlled) {\n return;\n }\n\n // `validation.change` reads `markedDirtyRef`, so update dirty before validating.\n setDirty(inputValue !== (validityData.initialValue ?? ''));\n setFilled(inputValue !== '');\n\n // Workaround for https://github.com/react/react/issues/9023\n if (!event.nativeEvent.defaultPrevented && !details.isCanceled) {\n clearErrors(name);\n validation.change(inputValue);\n }\n },\n onFocus() {\n setFocused(true);\n },\n onBlur(event) {\n setTouched(true);\n setFocused(false);\n if (validationMode === 'onBlur') {\n const inputValue = event.currentTarget.value;\n validation.commit(inputValue);\n if (isControlled) {\n // Controlled blur handlers can normalize the value before this microtask runs.\n // A rewrite back to the initial value is a programmatic reset: the field looks\n // pristine, so committing it would only surface `valueMissing` noise.\n queueMicrotask(() => {\n const nextValue = validation.inputRef.current?.value;\n if (nextValue !== undefined && nextValue !== inputValue && nextValue !== (validityData.initialValue ?? '')) {\n validation.commit(nextValue);\n }\n });\n }\n }\n },\n onKeyDown(event) {\n if (event.currentTarget.tagName === 'INPUT' && event.key === 'Enter') {\n setTouched(true);\n const value = event.currentTarget.value;\n const form = event.currentTarget.form;\n if (form && form === formElementRef.current && !event.defaultPrevented) {\n const input = event.currentTarget;\n const submitCount = submitCountRef.current;\n\n // Implicit submission runs after keydown. Fall back unless Form handles it first.\n enterValidationTimeout.start(0, () => {\n if (submitCountRef.current === submitCount) {\n validation.commit(input.value);\n }\n });\n } else {\n validation.commit(value);\n }\n }\n }\n }, elementProps, props => validation.getValidationProps(disabled, props)],\n stateAttributesMapping: fieldValidityMapping\n });\n return element;\n});\nif (process.env.NODE_ENV !== \"production\") FieldControl.displayName = \"FieldControl\";","'use client';\n\nimport * as React from 'react';\nimport { Field } from \"../field/index.mjs\";\n\n/**\n * A native input element that automatically works with [Field](https://base-ui.com/react/components/field).\n * Renders an `<input>` element.\n *\n * Documentation: [Base UI Input](https://base-ui.com/react/components/input)\n */\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport const Input = /*#__PURE__*/React.forwardRef(function Input(props, forwardedRef) {\n return /*#__PURE__*/_jsx(Field.Control, {\n ref: forwardedRef,\n ...props\n });\n});\nif (process.env.NODE_ENV !== \"production\") Input.displayName = \"Input\";","import * as React from \"react\"\nimport { Input as InputPrimitive } from \"@base-ui/react/input\"\nimport { cn } from \"cn\"\n\nfunction Input({ className, type, ...props }: React.ComponentProps<\"input\">) {\n return (\n <InputPrimitive\n type={type}\n data-slot=\"input\"\n className={cn(\n \"h-8 w-full min-w-0 rounded-lg border border-input bg-transparent px-2.5 py-1 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40\",\n className\n )}\n {...props}\n />\n )\n}\n\nexport { Input }\n","const getDefaultsFromPostinstall = () => (undefined);\nexport { getDefaultsFromPostinstall };","import { getDefaultsFromPostinstall } from './postinstall.mjs';\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @fileoverview Firebase constants. Some of these (@defines) can be overridden at compile-time.\n */\nconst CONSTANTS = {\n /**\n * @define {boolean} Whether this is the client Node.js SDK.\n */\n NODE_CLIENT: false,\n /**\n * @define {boolean} Whether this is the Admin Node.js SDK.\n */\n NODE_ADMIN: false,\n /**\n * Firebase SDK Version\n */\n SDK_VERSION: '${JSCORE_VERSION}'\n};\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Throws an error if the provided assertion is falsy\n */\nconst assert = function (assertion, message) {\n if (!assertion) {\n throw assertionError(message);\n }\n};\n/**\n * Returns an Error object suitable for throwing.\n */\nconst assertionError = function (message) {\n return new Error('Firebase Database (' +\n CONSTANTS.SDK_VERSION +\n ') INTERNAL ASSERT FAILED: ' +\n message);\n};\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst stringToByteArray$1 = function (str) {\n // TODO(user): Use native implementations if/when available\n const out = [];\n let p = 0;\n for (let i = 0; i < str.length; i++) {\n let c = str.charCodeAt(i);\n if (c < 128) {\n out[p++] = c;\n }\n else if (c < 2048) {\n out[p++] = (c >> 6) | 192;\n out[p++] = (c & 63) | 128;\n }\n else if ((c & 0xfc00) === 0xd800 &&\n i + 1 < str.length &&\n (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {\n // Surrogate Pair\n c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff);\n out[p++] = (c >> 18) | 240;\n out[p++] = ((c >> 12) & 63) | 128;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n }\n else {\n out[p++] = (c >> 12) | 224;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n }\n }\n return out;\n};\n/**\n * Turns an array of numbers into the string given by the concatenation of the\n * characters to which the numbers correspond.\n * @param bytes Array of numbers representing characters.\n * @return Stringification of the array.\n */\nconst byteArrayToString = function (bytes) {\n // TODO(user): Use native implementations if/when available\n const out = [];\n let pos = 0, c = 0;\n while (pos < bytes.length) {\n const c1 = bytes[pos++];\n if (c1 < 128) {\n out[c++] = String.fromCharCode(c1);\n }\n else if (c1 > 191 && c1 < 224) {\n const c2 = bytes[pos++];\n out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));\n }\n else if (c1 > 239 && c1 < 365) {\n // Surrogate Pair\n const c2 = bytes[pos++];\n const c3 = bytes[pos++];\n const c4 = bytes[pos++];\n const u = (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) -\n 0x10000;\n out[c++] = String.fromCharCode(0xd800 + (u >> 10));\n out[c++] = String.fromCharCode(0xdc00 + (u & 1023));\n }\n else {\n const c2 = bytes[pos++];\n const c3 = bytes[pos++];\n out[c++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));\n }\n }\n return out.join('');\n};\n// We define it as an object literal instead of a class because a class compiled down to es5 can't\n// be treeshaked. https://github.com/rollup/rollup/issues/1691\n// Static lookup maps, lazily populated by init_()\n// TODO(dlarocque): Define this as a class, since we no longer target ES5.\nconst base64 = {\n /**\n * Maps bytes to characters.\n */\n byteToCharMap_: null,\n /**\n * Maps characters to bytes.\n */\n charToByteMap_: null,\n /**\n * Maps bytes to websafe characters.\n * @private\n */\n byteToCharMapWebSafe_: null,\n /**\n * Maps websafe characters to bytes.\n * @private\n */\n charToByteMapWebSafe_: null,\n /**\n * Our default alphabet, shared between\n * ENCODED_VALS and ENCODED_VALS_WEBSAFE\n */\n ENCODED_VALS_BASE: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789',\n /**\n * Our default alphabet. Value 64 (=) is special; it means \"nothing.\"\n */\n get ENCODED_VALS() {\n return this.ENCODED_VALS_BASE + '+/=';\n },\n /**\n * Our websafe alphabet.\n */\n get ENCODED_VALS_WEBSAFE() {\n return this.ENCODED_VALS_BASE + '-_.';\n },\n /**\n * Whether this browser supports the atob and btoa functions. This extension\n * started at Mozilla but is now implemented by many browsers. We use the\n * ASSUME_* variables to avoid pulling in the full useragent detection library\n * but still allowing the standard per-browser compilations.\n *\n */\n HAS_NATIVE_SUPPORT: typeof atob === 'function',\n /**\n * Base64-encode an array of bytes.\n *\n * @param input An array of bytes (numbers with\n * value in [0, 255]) to encode.\n * @param webSafe Boolean indicating we should use the\n * alternative alphabet.\n * @return The base64 encoded string.\n */\n encodeByteArray(input, webSafe) {\n if (!Array.isArray(input)) {\n throw Error('encodeByteArray takes an array as a parameter');\n }\n this.init_();\n const byteToCharMap = webSafe\n ? this.byteToCharMapWebSafe_\n : this.byteToCharMap_;\n const output = [];\n for (let i = 0; i < input.length; i += 3) {\n const byte1 = input[i];\n const haveByte2 = i + 1 < input.length;\n const byte2 = haveByte2 ? input[i + 1] : 0;\n const haveByte3 = i + 2 < input.length;\n const byte3 = haveByte3 ? input[i + 2] : 0;\n const outByte1 = byte1 >> 2;\n const outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);\n let outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6);\n let outByte4 = byte3 & 0x3f;\n if (!haveByte3) {\n outByte4 = 64;\n if (!haveByte2) {\n outByte3 = 64;\n }\n }\n output.push(byteToCharMap[outByte1], byteToCharMap[outByte2], byteToCharMap[outByte3], byteToCharMap[outByte4]);\n }\n return output.join('');\n },\n /**\n * Base64-encode a string.\n *\n * @param input A string to encode.\n * @param webSafe If true, we should use the\n * alternative alphabet.\n * @return The base64 encoded string.\n */\n encodeString(input, webSafe) {\n // Shortcut for Mozilla browsers that implement\n // a native base64 encoder in the form of \"btoa/atob\"\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\n return btoa(input);\n }\n return this.encodeByteArray(stringToByteArray$1(input), webSafe);\n },\n /**\n * Base64-decode a string.\n *\n * @param input to decode.\n * @param webSafe True if we should use the\n * alternative alphabet.\n * @return string representing the decoded value.\n */\n decodeString(input, webSafe) {\n // Shortcut for Mozilla browsers that implement\n // a native base64 encoder in the form of \"btoa/atob\"\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\n return atob(input);\n }\n return byteArrayToString(this.decodeStringToByteArray(input, webSafe));\n },\n /**\n * Base64-decode a string.\n *\n * In base-64 decoding, groups of four characters are converted into three\n * bytes. If the encoder did not apply padding, the input length may not\n * be a multiple of 4.\n *\n * In this case, the last group will have fewer than 4 characters, and\n * padding will be inferred. If the group has one or two characters, it decodes\n * to one byte. If the group has three characters, it decodes to two bytes.\n *\n * @param input Input to decode.\n * @param webSafe True if we should use the web-safe alphabet.\n * @return bytes representing the decoded value.\n */\n decodeStringToByteArray(input, webSafe) {\n this.init_();\n const charToByteMap = webSafe\n ? this.charToByteMapWebSafe_\n : this.charToByteMap_;\n const output = [];\n for (let i = 0; i < input.length;) {\n const byte1 = charToByteMap[input.charAt(i++)];\n const haveByte2 = i < input.length;\n const byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0;\n ++i;\n const haveByte3 = i < input.length;\n const byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64;\n ++i;\n const haveByte4 = i < input.length;\n const byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64;\n ++i;\n if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) {\n throw new DecodeBase64StringError();\n }\n const outByte1 = (byte1 << 2) | (byte2 >> 4);\n output.push(outByte1);\n if (byte3 !== 64) {\n const outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2);\n output.push(outByte2);\n if (byte4 !== 64) {\n const outByte3 = ((byte3 << 6) & 0xc0) | byte4;\n output.push(outByte3);\n }\n }\n }\n return output;\n },\n /**\n * Lazy static initialization function. Called before\n * accessing any of the static map variables.\n * @private\n */\n init_() {\n if (!this.byteToCharMap_) {\n this.byteToCharMap_ = {};\n this.charToByteMap_ = {};\n this.byteToCharMapWebSafe_ = {};\n this.charToByteMapWebSafe_ = {};\n // We want quick mappings back and forth, so we precompute two maps.\n for (let i = 0; i < this.ENCODED_VALS.length; i++) {\n this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i);\n this.charToByteMap_[this.byteToCharMap_[i]] = i;\n this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i);\n this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i;\n // Be forgiving when decoding and correctly decode both encodings.\n if (i >= this.ENCODED_VALS_BASE.length) {\n this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i;\n this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i;\n }\n }\n }\n }\n};\n/**\n * An error encountered while decoding base64 string.\n */\nclass DecodeBase64StringError extends Error {\n constructor() {\n super(...arguments);\n this.name = 'DecodeBase64StringError';\n }\n}\n/**\n * URL-safe base64 encoding\n */\nconst base64Encode = function (str) {\n const utf8Bytes = stringToByteArray$1(str);\n return base64.encodeByteArray(utf8Bytes, true);\n};\n/**\n * URL-safe base64 encoding (without \".\" padding in the end).\n * e.g. Used in JSON Web Token (JWT) parts.\n */\nconst base64urlEncodeWithoutPadding = function (str) {\n // Use base64url encoding and remove padding in the end (dot characters).\n return base64Encode(str).replace(/\\./g, '');\n};\n/**\n * URL-safe base64 decoding\n *\n * NOTE: DO NOT use the global atob() function - it does NOT support the\n * base64Url variant encoding.\n *\n * @param str To be decoded\n * @return Decoded result, if possible\n */\nconst base64Decode = function (str) {\n try {\n return base64.decodeString(str, true);\n }\n catch (e) {\n console.error('base64Decode failed: ', e);\n }\n return null;\n};\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Do a deep-copy of basic JavaScript Objects or Arrays.\n */\nfunction deepCopy(value) {\n return deepExtend(undefined, value);\n}\n/**\n * Copy properties from source to target (recursively allows extension\n * of Objects and Arrays). Scalar values in the target are over-written.\n * If target is undefined, an object of the appropriate type will be created\n * (and returned).\n *\n * We recursively copy all child properties of plain Objects in the source- so\n * that namespace- like dictionaries are merged.\n *\n * Note that the target can be a function, in which case the properties in\n * the source Object are copied onto it as static properties of the Function.\n *\n * Note: we don't merge __proto__ to prevent prototype pollution\n */\nfunction deepExtend(target, source) {\n if (!(source instanceof Object)) {\n return source;\n }\n switch (source.constructor) {\n case Date:\n // Treat Dates like scalars; if the target date object had any child\n // properties - they will be lost!\n const dateValue = source;\n return new Date(dateValue.getTime());\n case Object:\n if (target === undefined) {\n target = {};\n }\n break;\n case Array:\n // Always copy the array source and overwrite the target.\n target = [];\n break;\n default:\n // Not a plain Object - treat it as a scalar.\n return source;\n }\n for (const prop in source) {\n // use isValidKey to guard against prototype pollution. See https://snyk.io/vuln/SNYK-JS-LODASH-450202\n if (!source.hasOwnProperty(prop) || !isValidKey(prop)) {\n continue;\n }\n target[prop] = deepExtend(target[prop], source[prop]);\n }\n return target;\n}\nfunction isValidKey(key) {\n return key !== '__proto__';\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Polyfill for `globalThis` object.\n * @returns the `globalThis` object for the given environment.\n * @public\n */\nfunction getGlobal() {\n if (typeof self !== 'undefined') {\n return self;\n }\n if (typeof window !== 'undefined') {\n return window;\n }\n if (typeof global !== 'undefined') {\n return global;\n }\n throw new Error('Unable to locate global object.');\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst getDefaultsFromGlobal = () => getGlobal().__FIREBASE_DEFAULTS__;\n/**\n * Attempt to read defaults from a JSON string provided to\n * process(.)env(.)__FIREBASE_DEFAULTS__ or a JSON file whose path is in\n * process(.)env(.)__FIREBASE_DEFAULTS_PATH__\n * The dots are in parens because certain compilers (Vite?) cannot\n * handle seeing that variable in comments.\n * See https://github.com/firebase/firebase-js-sdk/issues/6838\n */\nconst getDefaultsFromEnvVariable = () => {\n if (typeof process === 'undefined' || typeof process.env === 'undefined') {\n return;\n }\n const defaultsJsonString = process.env.__FIREBASE_DEFAULTS__;\n if (defaultsJsonString) {\n return JSON.parse(defaultsJsonString);\n }\n};\nconst getDefaultsFromCookie = () => {\n if (typeof document === 'undefined') {\n return;\n }\n let match;\n try {\n match = document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/);\n }\n catch (e) {\n // Some environments such as Angular Universal SSR have a\n // `document` object but error on accessing `document.cookie`.\n return;\n }\n const decoded = match && base64Decode(match[1]);\n return decoded && JSON.parse(decoded);\n};\n/**\n * Get the __FIREBASE_DEFAULTS__ object. It checks in order:\n * (1) if such an object exists as a property of `globalThis`\n * (2) if such an object was provided on a shell environment variable\n * (3) if such an object exists in a cookie\n * @public\n */\nconst getDefaults = () => {\n try {\n return (getDefaultsFromPostinstall() ||\n getDefaultsFromGlobal() ||\n getDefaultsFromEnvVariable() ||\n getDefaultsFromCookie());\n }\n catch (e) {\n /**\n * Catch-all for being unable to get __FIREBASE_DEFAULTS__ due\n * to any environment case we have not accounted for. Log to\n * info instead of swallowing so we can find these unknown cases\n * and add paths for them if needed.\n */\n console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`);\n return;\n }\n};\n/**\n * Returns emulator host stored in the __FIREBASE_DEFAULTS__ object\n * for the given product.\n * @returns a URL host formatted like `127.0.0.1:9999` or `[::1]:4000` if available\n * @public\n */\nconst getDefaultEmulatorHost = (productName) => getDefaults()?.emulatorHosts?.[productName];\n/**\n * Returns emulator hostname and port stored in the __FIREBASE_DEFAULTS__ object\n * for the given product.\n * @returns a pair of hostname and port like `[\"::1\", 4000]` if available\n * @public\n */\nconst getDefaultEmulatorHostnameAndPort = (productName) => {\n const host = getDefaultEmulatorHost(productName);\n if (!host) {\n return undefined;\n }\n const separatorIndex = host.lastIndexOf(':'); // Finding the last since IPv6 addr also has colons.\n if (separatorIndex <= 0 || separatorIndex + 1 === host.length) {\n throw new Error(`Invalid host ${host} with no separate hostname and port!`);\n }\n // eslint-disable-next-line no-restricted-globals\n const port = parseInt(host.substring(separatorIndex + 1), 10);\n if (host[0] === '[') {\n // Bracket-quoted `[ipv6addr]:port` => return \"ipv6addr\" (without brackets).\n return [host.substring(1, separatorIndex - 1), port];\n }\n else {\n return [host.substring(0, separatorIndex), port];\n }\n};\n/**\n * Returns Firebase app config stored in the __FIREBASE_DEFAULTS__ object.\n * @public\n */\nconst getDefaultAppConfig = () => getDefaults()?.config;\n/**\n * Returns an experimental setting on the __FIREBASE_DEFAULTS__ object (properties\n * prefixed by \"_\")\n * @public\n */\nconst getExperimentalSetting = (name) => getDefaults()?.[`_${name}`];\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass Deferred {\n constructor() {\n this.reject = () => { };\n this.resolve = () => { };\n this.promise = new Promise((resolve, reject) => {\n this.resolve = resolve;\n this.reject = reject;\n });\n }\n /**\n * Our API internals are not promisified and cannot because our callback APIs have subtle expectations around\n * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback\n * and returns a node-style callback which will resolve or reject the Deferred's promise.\n */\n wrapCallback(callback) {\n return (error, value) => {\n if (error) {\n this.reject(error);\n }\n else {\n this.resolve(value);\n }\n if (typeof callback === 'function') {\n // Attaching noop handler just in case developer wasn't expecting\n // promises\n this.promise.catch(() => { });\n // Some of our callbacks don't expect a value and our own tests\n // assert that the parameter length is 1\n if (callback.length === 1) {\n callback(error);\n }\n else {\n callback(error, value);\n }\n }\n };\n }\n}\n\n/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nfunction createMockUserToken(token, projectId) {\n if (token.uid) {\n throw new Error('The \"uid\" field is no longer supported by mockUserToken. Please use \"sub\" instead for Firebase Auth User ID.');\n }\n // Unsecured JWTs use \"none\" as the algorithm.\n const header = {\n alg: 'none',\n type: 'JWT'\n };\n const project = projectId || 'demo-project';\n const iat = token.iat || 0;\n const sub = token.sub || token.user_id;\n if (!sub) {\n throw new Error(\"mockUserToken must contain 'sub' or 'user_id' field!\");\n }\n const payload = {\n // Set all required fields to decent defaults\n iss: `https://securetoken.google.com/${project}`,\n aud: project,\n iat,\n exp: iat + 3600,\n auth_time: iat,\n sub,\n user_id: sub,\n firebase: {\n sign_in_provider: 'custom',\n identities: {}\n },\n // Override with user options\n ...token\n };\n // Unsecured JWTs use the empty string as a signature.\n const signature = '';\n return [\n base64urlEncodeWithoutPadding(JSON.stringify(header)),\n base64urlEncodeWithoutPadding(JSON.stringify(payload)),\n signature\n ].join('.');\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Returns navigator.userAgent string or '' if it's not defined.\n * @return user agent string\n */\nfunction getUA() {\n if (typeof navigator !== 'undefined' &&\n typeof navigator['userAgent'] === 'string') {\n return navigator['userAgent'];\n }\n else {\n return '';\n }\n}\n/**\n * Detect Cordova / PhoneGap / Ionic frameworks on a mobile device.\n *\n * Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap\n * in the Ripple emulator) nor Cordova `onDeviceReady`, which would normally\n * wait for a callback.\n */\nfunction isMobileCordova() {\n return (typeof window !== 'undefined' &&\n // @ts-ignore Setting up an broadly applicable index signature for Window\n // just to deal with this case would probably be a bad idea.\n !!(window['cordova'] || window['phonegap'] || window['PhoneGap']) &&\n /ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA()));\n}\n/**\n * Detect Node.js.\n *\n * @return true if Node.js environment is detected or specified.\n */\n// Node detection logic from: https://github.com/iliakan/detect-node/\nfunction isNode() {\n const forceEnvironment = getDefaults()?.forceEnvironment;\n if (forceEnvironment === 'node') {\n return true;\n }\n else if (forceEnvironment === 'browser') {\n return false;\n }\n try {\n return (Object.prototype.toString.call(global.process) === '[object process]');\n }\n catch (e) {\n return false;\n }\n}\n/**\n * Detect Browser Environment.\n * Note: This will return true for certain test frameworks that are incompletely\n * mimicking a browser, and should not lead to assuming all browser APIs are\n * available.\n */\nfunction isBrowser() {\n return typeof window !== 'undefined' || isWebWorker();\n}\n/**\n * Detect Web Worker context.\n */\nfunction isWebWorker() {\n return (typeof WorkerGlobalScope !== 'undefined' &&\n typeof self !== 'undefined' &&\n self instanceof WorkerGlobalScope);\n}\n/**\n * Detect Cloudflare Worker context.\n */\nfunction isCloudflareWorker() {\n return (typeof navigator !== 'undefined' &&\n navigator.userAgent === 'Cloudflare-Workers');\n}\nfunction isBrowserExtension() {\n const runtime = typeof chrome === 'object'\n ? chrome.runtime\n : typeof browser === 'object'\n ? browser.runtime\n : undefined;\n return typeof runtime === 'object' && runtime.id !== undefined;\n}\n/**\n * Detect React Native.\n *\n * @return true if ReactNative environment is detected.\n */\nfunction isReactNative() {\n return (typeof navigator === 'object' && navigator['product'] === 'ReactNative');\n}\n/** Detects Electron apps. */\nfunction isElectron() {\n return getUA().indexOf('Electron/') >= 0;\n}\n/** Detects Internet Explorer. */\nfunction isIE() {\n const ua = getUA();\n return ua.indexOf('MSIE ') >= 0 || ua.indexOf('Trident/') >= 0;\n}\n/** Detects Universal Windows Platform apps. */\nfunction isUWP() {\n return getUA().indexOf('MSAppHost/') >= 0;\n}\n/**\n * Detect whether the current SDK build is the Node version.\n *\n * @return true if it's the Node SDK build.\n */\nfunction isNodeSdk() {\n return CONSTANTS.NODE_CLIENT === true || CONSTANTS.NODE_ADMIN === true;\n}\n/** Returns true if we are running in Safari. */\nfunction isSafari() {\n return (!isNode() &&\n !!navigator.userAgent &&\n navigator.userAgent.includes('Safari') &&\n !navigator.userAgent.includes('Chrome'));\n}\n/** Returns true if we are running in Safari or WebKit */\nfunction isSafariOrWebkit() {\n return (!isNode() &&\n !!navigator.userAgent &&\n (navigator.userAgent.includes('Safari') ||\n navigator.userAgent.includes('WebKit')) &&\n !navigator.userAgent.includes('Chrome'));\n}\n/**\n * This method checks if indexedDB is supported by current browser/service worker context\n * @return true if indexedDB is supported by current browser/service worker context\n */\nfunction isIndexedDBAvailable() {\n try {\n return typeof indexedDB === 'object';\n }\n catch (e) {\n return false;\n }\n}\n/**\n * This method validates browser/sw context for indexedDB by opening a dummy indexedDB database and reject\n * if errors occur during the database open operation.\n *\n * @throws exception if current browser/sw context can't run idb.open (ex: Safari iframe, Firefox\n * private browsing)\n */\nfunction validateIndexedDBOpenable() {\n return new Promise((resolve, reject) => {\n try {\n let preExist = true;\n const DB_CHECK_NAME = 'validate-browser-context-for-indexeddb-analytics-module';\n const request = self.indexedDB.open(DB_CHECK_NAME);\n request.onsuccess = () => {\n request.result.close();\n // delete database only when it doesn't pre-exist\n if (!preExist) {\n self.indexedDB.deleteDatabase(DB_CHECK_NAME);\n }\n resolve(true);\n };\n request.onupgradeneeded = () => {\n preExist = false;\n };\n request.onerror = () => {\n reject(request.error?.message || '');\n };\n }\n catch (error) {\n reject(error);\n }\n });\n}\n/**\n *\n * This method checks whether cookie is enabled within current browser\n * @return true if cookie is enabled within current browser\n */\nfunction areCookiesEnabled() {\n if (typeof navigator === 'undefined' || !navigator.cookieEnabled) {\n return false;\n }\n return true;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @fileoverview Standardized Firebase Error.\n *\n * Usage:\n *\n * // TypeScript string literals for type-safe codes\n * type Err =\n * 'unknown' |\n * 'object-not-found'\n * ;\n *\n * // Closure enum for type-safe error codes\n * // at-enum {string}\n * var Err = {\n * UNKNOWN: 'unknown',\n * OBJECT_NOT_FOUND: 'object-not-found',\n * }\n *\n * let errors: Map<Err, string> = {\n * 'generic-error': \"Unknown error\",\n * 'file-not-found': \"Could not find file: {$file}\",\n * };\n *\n * // Type-safe function - must pass a valid error code as param.\n * let error = new ErrorFactory<Err>('service', 'Service', errors);\n *\n * ...\n * throw error.create(Err.GENERIC);\n * ...\n * throw error.create(Err.FILE_NOT_FOUND, {'file': fileName});\n * ...\n * // Service: Could not file file: foo.txt (service/file-not-found).\n *\n * catch (e) {\n * assert(e.message === \"Could not find file: foo.txt.\");\n * if ((e as FirebaseError)?.code === 'service/file-not-found') {\n * console.log(\"Could not read file: \" + e['file']);\n * }\n * }\n */\nconst ERROR_NAME = 'FirebaseError';\n// Based on code from:\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types\nclass FirebaseError extends Error {\n constructor(\n /** The error code for this error. */\n code, message, \n /** Custom data for this error. */\n customData) {\n super(message);\n this.code = code;\n this.customData = customData;\n /** The custom name for all FirebaseErrors. */\n this.name = ERROR_NAME;\n // Fix For ES5\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n // TODO(dlarocque): Replace this with `new.target`: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#support-for-newtarget\n // which we can now use since we no longer target ES5.\n Object.setPrototypeOf(this, FirebaseError.prototype);\n // Maintains proper stack trace for where our error was thrown.\n // Only available on V8.\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, ErrorFactory.prototype.create);\n }\n }\n}\nclass ErrorFactory {\n constructor(service, serviceName, errors) {\n this.service = service;\n this.serviceName = serviceName;\n this.errors = errors;\n }\n create(code, ...data) {\n const customData = data[0] || {};\n const fullCode = `${this.service}/${code}`;\n const template = this.errors[code];\n const message = template ? replaceTemplate(template, customData) : 'Error';\n // Service Name: Error message (service/code).\n const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`;\n const error = new FirebaseError(fullCode, fullMessage, customData);\n return error;\n }\n}\nfunction replaceTemplate(template, data) {\n try {\n let ptr = 0;\n let result = '';\n while (ptr < template.length) {\n const start = template.indexOf('{$', ptr);\n if (start === -1) {\n result += template.substring(ptr);\n break;\n }\n const end = template.indexOf('}', start + 2);\n if (end === -1) {\n result += template.substring(ptr);\n break;\n }\n const key = template.substring(start + 2, end);\n const value = data[key];\n result +=\n template.substring(ptr, start) +\n (value != null ? String(value) : `<${key}?>`);\n ptr = end + 1;\n }\n return result;\n }\n catch (e) {\n // Should never happen, but fallback just in case\n return template;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Evaluates a JSON string into a javascript object.\n *\n * @param {string} str A string containing JSON.\n * @return {*} The javascript object representing the specified JSON.\n */\nfunction jsonEval(str) {\n return JSON.parse(str);\n}\n/**\n * Returns JSON representing a javascript object.\n * @param {*} data JavaScript object to be stringified.\n * @return {string} The JSON contents of the object.\n */\nfunction stringify(data) {\n return JSON.stringify(data);\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Decodes a Firebase auth. token into constituent parts.\n *\n * Notes:\n * - May return with invalid / incomplete claims if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nconst decode = function (token) {\n let header = {}, claims = {}, data = {}, signature = '';\n try {\n const parts = token.split('.');\n header = jsonEval(base64Decode(parts[0]) || '');\n claims = jsonEval(base64Decode(parts[1]) || '');\n signature = parts[2];\n data = claims['d'] || {};\n delete claims['d'];\n }\n catch (e) { }\n return {\n header,\n claims,\n data,\n signature\n };\n};\n/**\n * Decodes a Firebase auth. token and checks the validity of its time-based claims. Will return true if the\n * token is within the time window authorized by the 'nbf' (not-before) and 'iat' (issued-at) claims.\n *\n * Notes:\n * - May return a false negative if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nconst isValidTimestamp = function (token) {\n const claims = decode(token).claims;\n const now = Math.floor(new Date().getTime() / 1000);\n let validSince = 0, validUntil = 0;\n if (typeof claims === 'object') {\n if (claims.hasOwnProperty('nbf')) {\n validSince = claims['nbf'];\n }\n else if (claims.hasOwnProperty('iat')) {\n validSince = claims['iat'];\n }\n if (claims.hasOwnProperty('exp')) {\n validUntil = claims['exp'];\n }\n else {\n // token will expire after 24h by default\n validUntil = validSince + 86400;\n }\n }\n return (!!now &&\n !!validSince &&\n !!validUntil &&\n now >= validSince &&\n now <= validUntil);\n};\n/**\n * Decodes a Firebase auth. token and returns its issued at time if valid, null otherwise.\n *\n * Notes:\n * - May return null if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nconst issuedAtTime = function (token) {\n const claims = decode(token).claims;\n if (typeof claims === 'object' && claims.hasOwnProperty('iat')) {\n return claims['iat'];\n }\n return null;\n};\n/**\n * Decodes a Firebase auth. token and checks the validity of its format. Expects a valid issued-at time.\n *\n * Notes:\n * - May return a false negative if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nconst isValidFormat = function (token) {\n const decoded = decode(token), claims = decoded.claims;\n return !!claims && typeof claims === 'object' && claims.hasOwnProperty('iat');\n};\n/**\n * Attempts to peer into an auth token and determine if it's an admin auth token by looking at the claims portion.\n *\n * Notes:\n * - May return a false negative if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nconst isAdmin = function (token) {\n const claims = decode(token).claims;\n return typeof claims === 'object' && claims['admin'] === true;\n};\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nfunction contains(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\nfunction safeGet(obj, key) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n return obj[key];\n }\n else {\n return undefined;\n }\n}\nfunction isEmpty(obj) {\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n return false;\n }\n }\n return true;\n}\nfunction map(obj, fn, contextObj) {\n const res = {};\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n res[key] = fn.call(contextObj, obj[key], key, obj);\n }\n }\n return res;\n}\n/**\n * Deep equal two objects. Support Arrays and Objects.\n */\nfunction deepEqual(a, b) {\n if (a === b) {\n return true;\n }\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n for (const k of aKeys) {\n if (!bKeys.includes(k)) {\n return false;\n }\n const aProp = a[k];\n const bProp = b[k];\n if (isObject(aProp) && isObject(bProp)) {\n if (!deepEqual(aProp, bProp)) {\n return false;\n }\n }\n else if (aProp !== bProp) {\n return false;\n }\n }\n for (const k of bKeys) {\n if (!aKeys.includes(k)) {\n return false;\n }\n }\n return true;\n}\nfunction isObject(thing) {\n return thing !== null && typeof thing === 'object';\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Rejects if the given promise doesn't resolve in timeInMS milliseconds.\n * @internal\n */\nfunction promiseWithTimeout(promise, timeInMS = 2000) {\n const deferredPromise = new Deferred();\n setTimeout(() => deferredPromise.reject('timeout!'), timeInMS);\n promise.then(deferredPromise.resolve, deferredPromise.reject);\n return deferredPromise.promise;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Returns a querystring-formatted string (e.g. &arg=val&arg2=val2) from a\n * params object (e.g. {arg: 'val', arg2: 'val2'})\n * Note: You must prepend it with ? when adding it to a URL.\n */\nfunction querystring(querystringParams) {\n const params = [];\n for (const [key, value] of Object.entries(querystringParams)) {\n if (Array.isArray(value)) {\n value.forEach(arrayVal => {\n params.push(encodeURIComponent(key) + '=' + encodeURIComponent(arrayVal));\n });\n }\n else {\n params.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));\n }\n }\n return params.length ? '&' + params.join('&') : '';\n}\n/**\n * Decodes a querystring (e.g. ?arg=val&arg2=val2) into a params object\n * (e.g. {arg: 'val', arg2: 'val2'})\n */\nfunction querystringDecode(querystring) {\n const obj = {};\n const tokens = querystring.replace(/^\\?/, '').split('&');\n tokens.forEach(token => {\n if (token) {\n const [key, value] = token.split('=');\n obj[decodeURIComponent(key)] = decodeURIComponent(value);\n }\n });\n return obj;\n}\n/**\n * Extract the query string part of a URL, including the leading question mark (if present).\n */\nfunction extractQuerystring(url) {\n const queryStart = url.indexOf('?');\n if (!queryStart) {\n return '';\n }\n const fragmentStart = url.indexOf('#', queryStart);\n return url.substring(queryStart, fragmentStart > 0 ? fragmentStart : undefined);\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @fileoverview SHA-1 cryptographic hash.\n * Variable names follow the notation in FIPS PUB 180-3:\n * http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf.\n *\n * Usage:\n * var sha1 = new sha1();\n * sha1.update(bytes);\n * var hash = sha1.digest();\n *\n * Performance:\n * Chrome 23: ~400 Mbit/s\n * Firefox 16: ~250 Mbit/s\n *\n */\n/**\n * SHA-1 cryptographic hash constructor.\n *\n * The properties declared here are discussed in the above algorithm document.\n * @constructor\n * @final\n * @struct\n */\nclass Sha1 {\n constructor() {\n /**\n * Holds the previous values of accumulated variables a-e in the compress_\n * function.\n * @private\n */\n this.chain_ = [];\n /**\n * A buffer holding the partially computed hash result.\n * @private\n */\n this.buf_ = [];\n /**\n * An array of 80 bytes, each a part of the message to be hashed. Referred to\n * as the message schedule in the docs.\n * @private\n */\n this.W_ = [];\n /**\n * Contains data needed to pad messages less than 64 bytes.\n * @private\n */\n this.pad_ = [];\n /**\n * @private {number}\n */\n this.inbuf_ = 0;\n /**\n * @private {number}\n */\n this.total_ = 0;\n this.blockSize = 512 / 8;\n this.pad_[0] = 128;\n for (let i = 1; i < this.blockSize; ++i) {\n this.pad_[i] = 0;\n }\n this.reset();\n }\n reset() {\n this.chain_[0] = 0x67452301;\n this.chain_[1] = 0xefcdab89;\n this.chain_[2] = 0x98badcfe;\n this.chain_[3] = 0x10325476;\n this.chain_[4] = 0xc3d2e1f0;\n this.inbuf_ = 0;\n this.total_ = 0;\n }\n /**\n * Internal compress helper function.\n * @param buf Block to compress.\n * @param offset Offset of the block in the buffer.\n * @private\n */\n compress_(buf, offset) {\n if (!offset) {\n offset = 0;\n }\n const W = this.W_;\n // get 16 big endian words\n if (typeof buf === 'string') {\n for (let i = 0; i < 16; i++) {\n // TODO(user): [bug 8140122] Recent versions of Safari for Mac OS and iOS\n // have a bug that turns the post-increment ++ operator into pre-increment\n // during JIT compilation. We have code that depends heavily on SHA-1 for\n // correctness and which is affected by this bug, so I've removed all uses\n // of post-increment ++ in which the result value is used. We can revert\n // this change once the Safari bug\n // (https://bugs.webkit.org/show_bug.cgi?id=109036) has been fixed and\n // most clients have been updated.\n W[i] =\n (buf.charCodeAt(offset) << 24) |\n (buf.charCodeAt(offset + 1) << 16) |\n (buf.charCodeAt(offset + 2) << 8) |\n buf.charCodeAt(offset + 3);\n offset += 4;\n }\n }\n else {\n for (let i = 0; i < 16; i++) {\n W[i] =\n (buf[offset] << 24) |\n (buf[offset + 1] << 16) |\n (buf[offset + 2] << 8) |\n buf[offset + 3];\n offset += 4;\n }\n }\n // expand to 80 words\n for (let i = 16; i < 80; i++) {\n const t = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];\n W[i] = ((t << 1) | (t >>> 31)) & 0xffffffff;\n }\n let a = this.chain_[0];\n let b = this.chain_[1];\n let c = this.chain_[2];\n let d = this.chain_[3];\n let e = this.chain_[4];\n let f, k;\n // TODO(user): Try to unroll this loop to speed up the computation.\n for (let i = 0; i < 80; i++) {\n if (i < 40) {\n if (i < 20) {\n f = d ^ (b & (c ^ d));\n k = 0x5a827999;\n }\n else {\n f = b ^ c ^ d;\n k = 0x6ed9eba1;\n }\n }\n else {\n if (i < 60) {\n f = (b & c) | (d & (b | c));\n k = 0x8f1bbcdc;\n }\n else {\n f = b ^ c ^ d;\n k = 0xca62c1d6;\n }\n }\n const t = (((a << 5) | (a >>> 27)) + f + e + k + W[i]) & 0xffffffff;\n e = d;\n d = c;\n c = ((b << 30) | (b >>> 2)) & 0xffffffff;\n b = a;\n a = t;\n }\n this.chain_[0] = (this.chain_[0] + a) & 0xffffffff;\n this.chain_[1] = (this.chain_[1] + b) & 0xffffffff;\n this.chain_[2] = (this.chain_[2] + c) & 0xffffffff;\n this.chain_[3] = (this.chain_[3] + d) & 0xffffffff;\n this.chain_[4] = (this.chain_[4] + e) & 0xffffffff;\n }\n update(bytes, length) {\n // TODO(johnlenz): tighten the function signature and remove this check\n if (bytes == null) {\n return;\n }\n if (length === undefined) {\n length = bytes.length;\n }\n const lengthMinusBlock = length - this.blockSize;\n let n = 0;\n // Using local instead of member variables gives ~5% speedup on Firefox 16.\n const buf = this.buf_;\n let inbuf = this.inbuf_;\n // The outer while loop should execute at most twice.\n while (n < length) {\n // When we have no data in the block to top up, we can directly process the\n // input buffer (assuming it contains sufficient data). This gives ~25%\n // speedup on Chrome 23 and ~15% speedup on Firefox 16, but requires that\n // the data is provided in large chunks (or in multiples of 64 bytes).\n if (inbuf === 0) {\n while (n <= lengthMinusBlock) {\n this.compress_(bytes, n);\n n += this.blockSize;\n }\n }\n if (typeof bytes === 'string') {\n while (n < length) {\n buf[inbuf] = bytes.charCodeAt(n);\n ++inbuf;\n ++n;\n if (inbuf === this.blockSize) {\n this.compress_(buf);\n inbuf = 0;\n // Jump to the outer loop so we use the full-block optimization.\n break;\n }\n }\n }\n else {\n while (n < length) {\n buf[inbuf] = bytes[n];\n ++inbuf;\n ++n;\n if (inbuf === this.blockSize) {\n this.compress_(buf);\n inbuf = 0;\n // Jump to the outer loop so we use the full-block optimization.\n break;\n }\n }\n }\n }\n this.inbuf_ = inbuf;\n this.total_ += length;\n }\n /** @override */\n digest() {\n const digest = [];\n let totalBits = this.total_ * 8;\n // Add pad 0x80 0x00*.\n if (this.inbuf_ < 56) {\n this.update(this.pad_, 56 - this.inbuf_);\n }\n else {\n this.update(this.pad_, this.blockSize - (this.inbuf_ - 56));\n }\n // Add # bits.\n for (let i = this.blockSize - 1; i >= 56; i--) {\n this.buf_[i] = totalBits & 255;\n totalBits /= 256; // Don't use bit-shifting here!\n }\n this.compress_(this.buf_);\n let n = 0;\n for (let i = 0; i < 5; i++) {\n for (let j = 24; j >= 0; j -= 8) {\n digest[n] = (this.chain_[i] >> j) & 255;\n ++n;\n }\n }\n return digest;\n }\n}\n\n/**\n * Helper to make a Subscribe function (just like Promise helps make a\n * Thenable).\n *\n * @param executor Function which can make calls to a single Observer\n * as a proxy.\n * @param onNoObservers Callback when count of Observers goes to zero.\n */\nfunction createSubscribe(executor, onNoObservers) {\n const proxy = new ObserverProxy(executor, onNoObservers);\n return proxy.subscribe.bind(proxy);\n}\n/**\n * Implement fan-out for any number of Observers attached via a subscribe\n * function.\n */\nclass ObserverProxy {\n /**\n * @param executor Function which can make calls to a single Observer\n * as a proxy.\n * @param onNoObservers Callback when count of Observers goes to zero.\n */\n constructor(executor, onNoObservers) {\n this.observers = [];\n this.unsubscribes = [];\n this.observerCount = 0;\n // Micro-task scheduling by calling task.then().\n this.task = Promise.resolve();\n this.finalized = false;\n this.onNoObservers = onNoObservers;\n // Call the executor asynchronously so subscribers that are called\n // synchronously after the creation of the subscribe function\n // can still receive the very first value generated in the executor.\n this.task\n .then(() => {\n executor(this);\n })\n .catch(e => {\n this.error(e);\n });\n }\n next(value) {\n this.forEachObserver((observer) => {\n observer.next(value);\n });\n }\n error(error) {\n this.forEachObserver((observer) => {\n observer.error(error);\n });\n this.close(error);\n }\n complete() {\n this.forEachObserver((observer) => {\n observer.complete();\n });\n this.close();\n }\n /**\n * Subscribe function that can be used to add an Observer to the fan-out list.\n *\n * - We require that no event is sent to a subscriber synchronously to their\n * call to subscribe().\n */\n subscribe(nextOrObserver, error, complete) {\n let observer;\n if (nextOrObserver === undefined &&\n error === undefined &&\n complete === undefined) {\n throw new Error('Missing Observer.');\n }\n // Assemble an Observer object when passed as callback functions.\n if (implementsAnyMethods(nextOrObserver, [\n 'next',\n 'error',\n 'complete'\n ])) {\n observer = nextOrObserver;\n }\n else {\n observer = {\n next: nextOrObserver,\n error,\n complete\n };\n }\n if (observer.next === undefined) {\n observer.next = noop;\n }\n if (observer.error === undefined) {\n observer.error = noop;\n }\n if (observer.complete === undefined) {\n observer.complete = noop;\n }\n const unsub = this.unsubscribeOne.bind(this, this.observers.length);\n // Attempt to subscribe to a terminated Observable - we\n // just respond to the Observer with the final error or complete\n // event.\n if (this.finalized) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.task.then(() => {\n try {\n if (this.finalError) {\n observer.error(this.finalError);\n }\n else {\n observer.complete();\n }\n }\n catch (e) {\n // nothing\n }\n return;\n });\n }\n this.observers.push(observer);\n return unsub;\n }\n // Unsubscribe is synchronous - we guarantee that no events are sent to\n // any unsubscribed Observer.\n unsubscribeOne(i) {\n if (this.observers === undefined || this.observers[i] === undefined) {\n return;\n }\n delete this.observers[i];\n this.observerCount -= 1;\n if (this.observerCount === 0 && this.onNoObservers !== undefined) {\n this.onNoObservers(this);\n }\n }\n forEachObserver(fn) {\n if (this.finalized) {\n // Already closed by previous event....just eat the additional values.\n return;\n }\n // Since sendOne calls asynchronously - there is no chance that\n // this.observers will become undefined.\n for (let i = 0; i < this.observers.length; i++) {\n this.sendOne(i, fn);\n }\n }\n // Call the Observer via one of it's callback function. We are careful to\n // confirm that the observe has not been unsubscribed since this asynchronous\n // function had been queued.\n sendOne(i, fn) {\n // Execute the callback asynchronously\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.task.then(() => {\n if (this.observers !== undefined && this.observers[i] !== undefined) {\n try {\n fn(this.observers[i]);\n }\n catch (e) {\n // Ignore exceptions raised in Observers or missing methods of an\n // Observer.\n // Log error to console. b/31404806\n if (typeof console !== 'undefined' && console.error) {\n console.error(e);\n }\n }\n }\n });\n }\n close(err) {\n if (this.finalized) {\n return;\n }\n this.finalized = true;\n if (err !== undefined) {\n this.finalError = err;\n }\n // Proxy is no longer needed - garbage collect references\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.task.then(() => {\n this.observers = undefined;\n this.onNoObservers = undefined;\n });\n }\n}\n/** Turn synchronous function into one called asynchronously. */\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction async(fn, onError) {\n return (...args) => {\n Promise.resolve(true)\n .then(() => {\n fn(...args);\n })\n .catch((error) => {\n if (onError) {\n onError(error);\n }\n });\n };\n}\n/**\n * Return true if the object passed in implements any of the named methods.\n */\nfunction implementsAnyMethods(obj, methods) {\n if (typeof obj !== 'object' || obj === null) {\n return false;\n }\n for (const method of methods) {\n if (method in obj && typeof obj[method] === 'function') {\n return true;\n }\n }\n return false;\n}\nfunction noop() {\n // do nothing\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Check to make sure the appropriate number of arguments are provided for a public function.\n * Throws an error if it fails.\n *\n * @param fnName The function name\n * @param minCount The minimum number of arguments to allow for the function call\n * @param maxCount The maximum number of argument to allow for the function call\n * @param argCount The actual number of arguments provided.\n */\nconst validateArgCount = function (fnName, minCount, maxCount, argCount) {\n let argError;\n if (argCount < minCount) {\n argError = 'at least ' + minCount;\n }\n else if (argCount > maxCount) {\n argError = maxCount === 0 ? 'none' : 'no more than ' + maxCount;\n }\n if (argError) {\n const error = fnName +\n ' failed: Was called with ' +\n argCount +\n (argCount === 1 ? ' argument.' : ' arguments.') +\n ' Expects ' +\n argError +\n '.';\n throw new Error(error);\n }\n};\n/**\n * Generates a string to prefix an error message about failed argument validation\n *\n * @param fnName The function name\n * @param argName The name of the argument\n * @return The prefix to add to the error thrown for validation.\n */\nfunction errorPrefix(fnName, argName) {\n return `${fnName} failed: ${argName} argument `;\n}\n/**\n * @param fnName\n * @param argumentNumber\n * @param namespace\n * @param optional\n */\nfunction validateNamespace(fnName, namespace, optional) {\n if (optional && !namespace) {\n return;\n }\n if (typeof namespace !== 'string') {\n //TODO: I should do more validation here. We only allow certain chars in namespaces.\n throw new Error(errorPrefix(fnName, 'namespace') + 'must be a valid firebase namespace.');\n }\n}\nfunction validateCallback(fnName, argumentName, \n// eslint-disable-next-line @typescript-eslint/ban-types\ncallback, optional) {\n if (optional && !callback) {\n return;\n }\n if (typeof callback !== 'function') {\n throw new Error(errorPrefix(fnName, argumentName) + 'must be a valid function.');\n }\n}\nfunction validateContextObject(fnName, argumentName, context, optional) {\n if (optional && !context) {\n return;\n }\n if (typeof context !== 'object' || context === null) {\n throw new Error(errorPrefix(fnName, argumentName) + 'must be a valid context object.');\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// Code originally came from goog.crypt.stringToUtf8ByteArray, but for some reason they\n// automatically replaced '\\r\\n' with '\\n', and they didn't handle surrogate pairs,\n// so it's been modified.\n// Note that not all Unicode characters appear as single characters in JavaScript strings.\n// fromCharCode returns the UTF-16 encoding of a character - so some Unicode characters\n// use 2 characters in JavaScript. All 4-byte UTF-8 characters begin with a first\n// character in the range 0xD800 - 0xDBFF (the first character of a so-called surrogate\n// pair).\n// See http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3\n/**\n * @param {string} str\n * @return {Array}\n */\nconst stringToByteArray = function (str) {\n const out = [];\n let p = 0;\n for (let i = 0; i < str.length; i++) {\n let c = str.charCodeAt(i);\n // Is this the lead surrogate in a surrogate pair?\n if (c >= 0xd800 && c <= 0xdbff) {\n const high = c - 0xd800; // the high 10 bits.\n i++;\n assert(i < str.length, 'Surrogate pair missing trail surrogate.');\n const low = str.charCodeAt(i) - 0xdc00; // the low 10 bits.\n c = 0x10000 + (high << 10) + low;\n }\n if (c < 128) {\n out[p++] = c;\n }\n else if (c < 2048) {\n out[p++] = (c >> 6) | 192;\n out[p++] = (c & 63) | 128;\n }\n else if (c < 65536) {\n out[p++] = (c >> 12) | 224;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n }\n else {\n out[p++] = (c >> 18) | 240;\n out[p++] = ((c >> 12) & 63) | 128;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n }\n }\n return out;\n};\n/**\n * Calculate length without actually converting; useful for doing cheaper validation.\n * @param {string} str\n * @return {number}\n */\nconst stringLength = function (str) {\n let p = 0;\n for (let i = 0; i < str.length; i++) {\n const c = str.charCodeAt(i);\n if (c < 128) {\n p++;\n }\n else if (c < 2048) {\n p += 2;\n }\n else if (c >= 0xd800 && c <= 0xdbff) {\n // Lead surrogate of a surrogate pair. The pair together will take 4 bytes to represent.\n p += 4;\n i++; // skip trail surrogate.\n }\n else {\n p += 3;\n }\n }\n return p;\n};\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * The amount of milliseconds to exponentially increase.\n */\nconst DEFAULT_INTERVAL_MILLIS = 1000;\n/**\n * The factor to backoff by.\n * Should be a number greater than 1.\n */\nconst DEFAULT_BACKOFF_FACTOR = 2;\n/**\n * The maximum milliseconds to increase to.\n *\n * <p>Visible for testing\n */\nconst MAX_VALUE_MILLIS = 4 * 60 * 60 * 1000; // Four hours, like iOS and Android.\n/**\n * The percentage of backoff time to randomize by.\n * See\n * http://go/safe-client-behavior#step-1-determine-the-appropriate-retry-interval-to-handle-spike-traffic\n * for context.\n *\n * <p>Visible for testing\n */\nconst RANDOM_FACTOR = 0.5;\n/**\n * Based on the backoff method from\n * https://github.com/google/closure-library/blob/master/closure/goog/math/exponentialbackoff.js.\n * Extracted here so we don't need to pass metadata and a stateful ExponentialBackoff object around.\n */\nfunction calculateBackoffMillis(backoffCount, intervalMillis = DEFAULT_INTERVAL_MILLIS, backoffFactor = DEFAULT_BACKOFF_FACTOR) {\n // Calculates an exponentially increasing value.\n // Deviation: calculates value from count and a constant interval, so we only need to save value\n // and count to restore state.\n const currBaseValue = intervalMillis * Math.pow(backoffFactor, backoffCount);\n // A random \"fuzz\" to avoid waves of retries.\n // Deviation: randomFactor is required.\n const randomWait = Math.round(\n // A fraction of the backoff value to add/subtract.\n // Deviation: changes multiplication order to improve readability.\n RANDOM_FACTOR *\n currBaseValue *\n // A random float (rounded to int by Math.round above) in the range [-1, 1]. Determines\n // if we add or subtract.\n (Math.random() - 0.5) *\n 2);\n // Limits backoff to max to avoid effectively permanent backoff.\n return Math.min(MAX_VALUE_MILLIS, currBaseValue + randomWait);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Provide English ordinal letters after a number\n */\nfunction ordinal(i) {\n if (!Number.isFinite(i)) {\n return `${i}`;\n }\n return i + indicator(i);\n}\nfunction indicator(i) {\n i = Math.abs(i);\n const cent = i % 100;\n if (cent >= 10 && cent <= 20) {\n return 'th';\n }\n const dec = i % 10;\n if (dec === 1) {\n return 'st';\n }\n if (dec === 2) {\n return 'nd';\n }\n if (dec === 3) {\n return 'rd';\n }\n return 'th';\n}\n\n/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nfunction getModularInstance(service) {\n if (service && service._delegate) {\n return service._delegate;\n }\n else {\n return service;\n }\n}\n\n/**\n * @license\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Checks whether host is a cloud workstation or not.\n * @public\n */\nfunction isCloudWorkstation(url) {\n // `isCloudWorkstation` is called without protocol in certain connect*Emulator functions\n // In HTTP request builders, it's called with the protocol.\n // If called with protocol prefix, it's a valid URL, so we extract the hostname\n // If called without, we assume the string is the hostname.\n try {\n const host = url.startsWith('http://') || url.startsWith('https://')\n ? new URL(url).hostname\n : url;\n return host.endsWith('.cloudworkstations.dev');\n }\n catch {\n return false;\n }\n}\n/**\n * Makes a fetch request to the given server.\n * Mostly used for forwarding cookies in Firebase Studio.\n * @public\n */\nasync function pingServer(endpoint) {\n const result = await fetch(endpoint, {\n credentials: 'include'\n });\n return result.ok;\n}\n\n/**\n * @license\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @public\n * Generates a SHA-256 hash for the given input string.\n *\n * @param input The string to hash.\n * @returns A promise that resolves to the SHA-256 hash as a hex string.\n */\nasync function generateSHA256Hash(input) {\n const textEncoder = new TextEncoder();\n const data = textEncoder.encode(input);\n const hashBuffer = await crypto.subtle.digest('SHA-256', data);\n // Convert ArrayBuffer to hex string\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n const hexHash = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');\n return hexHash;\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, generateSHA256Hash, getDefaultAppConfig, getDefaultEmulatorHost, getDefaultEmulatorHostnameAndPort, getDefaults, getExperimentalSetting, getGlobal, getModularInstance, getUA, isAdmin, isBrowser, isBrowserExtension, isCloudWorkstation, isCloudflareWorker, isElectron, isEmpty, isIE, isIndexedDBAvailable, isMobileCordova, isNode, isNodeSdk, isReactNative, isSafari, isSafariOrWebkit, isUWP, isValidFormat, isValidTimestamp, isWebWorker, issuedAtTime, jsonEval, map, ordinal, pingServer, promiseWithTimeout, querystring, querystringDecode, safeGet, stringLength, stringToByteArray, stringify, validateArgCount, validateCallback, validateContextObject, validateIndexedDBOpenable, validateNamespace };\n//# sourceMappingURL=index.esm.js.map\n","import { Deferred } from '@firebase/util';\n\n/**\n * Component for service name T, e.g. `auth`, `auth-internal`\n */\nclass Component {\n /**\n *\n * @param name The public service name, e.g. app, auth, firestore, database\n * @param instanceFactory Service factory responsible for creating the public interface\n * @param type whether the service provided by the component is public or private\n */\n constructor(name, instanceFactory, type) {\n this.name = name;\n this.instanceFactory = instanceFactory;\n this.type = type;\n this.multipleInstances = false;\n /**\n * Properties to be added to the service namespace\n */\n this.serviceProps = {};\n this.instantiationMode = \"LAZY\" /* InstantiationMode.LAZY */;\n this.onInstanceCreated = null;\n }\n setInstantiationMode(mode) {\n this.instantiationMode = mode;\n return this;\n }\n setMultipleInstances(multipleInstances) {\n this.multipleInstances = multipleInstances;\n return this;\n }\n setServiceProps(props) {\n this.serviceProps = props;\n return this;\n }\n setInstanceCreatedCallback(callback) {\n this.onInstanceCreated = callback;\n return this;\n }\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst DEFAULT_ENTRY_NAME = '[DEFAULT]';\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Provider for instance for service name T, e.g. 'auth', 'auth-internal'\n * NameServiceMapping[T] is an alias for the type of the instance\n */\nclass Provider {\n constructor(name, container) {\n this.name = name;\n this.container = container;\n this.component = null;\n this.instances = new Map();\n this.instancesDeferred = new Map();\n this.instancesOptions = new Map();\n this.onInitCallbacks = new Map();\n }\n /**\n * @param identifier A provider can provide multiple instances of a service\n * if this.component.multipleInstances is true.\n */\n get(identifier) {\n // if multipleInstances is not supported, use the default name\n const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);\n if (!this.instancesDeferred.has(normalizedIdentifier)) {\n const deferred = new Deferred();\n this.instancesDeferred.set(normalizedIdentifier, deferred);\n if (this.isInitialized(normalizedIdentifier) ||\n this.shouldAutoInitialize()) {\n // initialize the service if it can be auto-initialized\n try {\n const instance = this.getOrInitializeService({\n instanceIdentifier: normalizedIdentifier\n });\n if (instance) {\n deferred.resolve(instance);\n }\n }\n catch (e) {\n // when the instance factory throws an exception during get(), it should not cause\n // a fatal error. We just return the unresolved promise in this case.\n }\n }\n }\n return this.instancesDeferred.get(normalizedIdentifier).promise;\n }\n getImmediate(options) {\n // if multipleInstances is not supported, use the default name\n const normalizedIdentifier = this.normalizeInstanceIdentifier(options?.identifier);\n const optional = options?.optional ?? false;\n if (this.isInitialized(normalizedIdentifier) ||\n this.shouldAutoInitialize()) {\n try {\n return this.getOrInitializeService({\n instanceIdentifier: normalizedIdentifier\n });\n }\n catch (e) {\n if (optional) {\n return null;\n }\n else {\n throw e;\n }\n }\n }\n else {\n // In case a component is not initialized and should/cannot be auto-initialized at the moment, return null if the optional flag is set, or throw\n if (optional) {\n return null;\n }\n else {\n throw Error(`Service ${this.name} is not available`);\n }\n }\n }\n getComponent() {\n return this.component;\n }\n setComponent(component) {\n if (component.name !== this.name) {\n throw Error(`Mismatching Component ${component.name} for Provider ${this.name}.`);\n }\n if (this.component) {\n throw Error(`Component for ${this.name} has already been provided`);\n }\n this.component = component;\n // return early without attempting to initialize the component if the component requires explicit initialization (calling `Provider.initialize()`)\n if (!this.shouldAutoInitialize()) {\n return;\n }\n // if the service is eager, initialize the default instance\n if (isComponentEager(component)) {\n try {\n this.getOrInitializeService({ instanceIdentifier: DEFAULT_ENTRY_NAME });\n }\n catch (e) {\n // when the instance factory for an eager Component throws an exception during the eager\n // initialization, it should not cause a fatal error.\n // TODO: Investigate if we need to make it configurable, because some component may want to cause\n // a fatal error in this case?\n }\n }\n // Create service instances for the pending promises and resolve them\n // NOTE: if this.multipleInstances is false, only the default instance will be created\n // and all promises with resolve with it regardless of the identifier.\n for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) {\n const normalizedIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier);\n try {\n // `getOrInitializeService()` should always return a valid instance since a component is guaranteed. use ! to make typescript happy.\n const instance = this.getOrInitializeService({\n instanceIdentifier: normalizedIdentifier\n });\n instanceDeferred.resolve(instance);\n }\n catch (e) {\n // when the instance factory throws an exception, it should not cause\n // a fatal error. We just leave the promise unresolved.\n }\n }\n }\n clearInstance(identifier = DEFAULT_ENTRY_NAME) {\n this.instancesDeferred.delete(identifier);\n this.instancesOptions.delete(identifier);\n this.instances.delete(identifier);\n }\n // app.delete() will call this method on every provider to delete the services\n // TODO: should we mark the provider as deleted?\n async delete() {\n const services = Array.from(this.instances.values());\n await Promise.all([\n ...services\n .filter(service => 'INTERNAL' in service) // legacy services\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n .map(service => service.INTERNAL.delete()),\n ...services\n .filter(service => '_delete' in service) // modularized services\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n .map(service => service._delete())\n ]);\n }\n isComponentSet() {\n return this.component != null;\n }\n isInitialized(identifier = DEFAULT_ENTRY_NAME) {\n return this.instances.has(identifier);\n }\n getOptions(identifier = DEFAULT_ENTRY_NAME) {\n return this.instancesOptions.get(identifier) || {};\n }\n initialize(opts = {}) {\n const { options = {} } = opts;\n const normalizedIdentifier = this.normalizeInstanceIdentifier(opts.instanceIdentifier);\n if (this.isInitialized(normalizedIdentifier)) {\n throw Error(`${this.name}(${normalizedIdentifier}) has already been initialized`);\n }\n if (!this.isComponentSet()) {\n throw Error(`Component ${this.name} has not been registered yet`);\n }\n const instance = this.getOrInitializeService({\n instanceIdentifier: normalizedIdentifier,\n options\n });\n // resolve any pending promise waiting for the service instance\n for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) {\n const normalizedDeferredIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier);\n if (normalizedIdentifier === normalizedDeferredIdentifier) {\n instanceDeferred.resolve(instance);\n }\n }\n return instance;\n }\n /**\n *\n * @param callback - a function that will be invoked after the provider has been initialized by calling provider.initialize().\n * The function is invoked SYNCHRONOUSLY, so it should not execute any longrunning tasks in order to not block the program.\n *\n * @param identifier An optional instance identifier\n * @returns a function to unregister the callback\n */\n onInit(callback, identifier) {\n const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);\n const existingCallbacks = this.onInitCallbacks.get(normalizedIdentifier) ??\n new Set();\n existingCallbacks.add(callback);\n this.onInitCallbacks.set(normalizedIdentifier, existingCallbacks);\n const existingInstance = this.instances.get(normalizedIdentifier);\n if (existingInstance) {\n callback(existingInstance, normalizedIdentifier);\n }\n return () => {\n existingCallbacks.delete(callback);\n };\n }\n /**\n * Invoke onInit callbacks synchronously\n * @param instance the service instance`\n */\n invokeOnInitCallbacks(instance, identifier) {\n const callbacks = this.onInitCallbacks.get(identifier);\n if (!callbacks) {\n return;\n }\n for (const callback of callbacks) {\n try {\n callback(instance, identifier);\n }\n catch {\n // ignore errors in the onInit callback\n }\n }\n }\n getOrInitializeService({ instanceIdentifier, options = {} }) {\n let instance = this.instances.get(instanceIdentifier);\n if (!instance && this.component) {\n instance = this.component.instanceFactory(this.container, {\n instanceIdentifier: normalizeIdentifierForFactory(instanceIdentifier),\n options\n });\n this.instances.set(instanceIdentifier, instance);\n this.instancesOptions.set(instanceIdentifier, options);\n /**\n * Invoke onInit listeners.\n * Note this.component.onInstanceCreated is different, which is used by the component creator,\n * while onInit listeners are registered by consumers of the provider.\n */\n this.invokeOnInitCallbacks(instance, instanceIdentifier);\n /**\n * Order is important\n * onInstanceCreated() should be called after this.instances.set(instanceIdentifier, instance); which\n * makes `isInitialized()` return true.\n */\n if (this.component.onInstanceCreated) {\n try {\n this.component.onInstanceCreated(this.container, instanceIdentifier, instance);\n }\n catch {\n // ignore errors in the onInstanceCreatedCallback\n }\n }\n }\n return instance || null;\n }\n normalizeInstanceIdentifier(identifier = DEFAULT_ENTRY_NAME) {\n if (this.component) {\n return this.component.multipleInstances ? identifier : DEFAULT_ENTRY_NAME;\n }\n else {\n return identifier; // assume multiple instances are supported before the component is provided.\n }\n }\n shouldAutoInitialize() {\n return (!!this.component &&\n this.component.instantiationMode !== \"EXPLICIT\" /* InstantiationMode.EXPLICIT */);\n }\n}\n// undefined should be passed to the service factory for the default instance\nfunction normalizeIdentifierForFactory(identifier) {\n return identifier === DEFAULT_ENTRY_NAME ? undefined : identifier;\n}\nfunction isComponentEager(component) {\n return component.instantiationMode === \"EAGER\" /* InstantiationMode.EAGER */;\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * ComponentContainer that provides Providers for service name T, e.g. `auth`, `auth-internal`\n */\nclass ComponentContainer {\n constructor(name) {\n this.name = name;\n this.providers = new Map();\n }\n /**\n *\n * @param component Component being added\n * @param overwrite When a component with the same name has already been registered,\n * if overwrite is true: overwrite the existing component with the new component and create a new\n * provider with the new component. It can be useful in tests where you want to use different mocks\n * for different tests.\n * if overwrite is false: throw an exception\n */\n addComponent(component) {\n const provider = this.getProvider(component.name);\n if (provider.isComponentSet()) {\n throw new Error(`Component ${component.name} has already been registered with ${this.name}`);\n }\n provider.setComponent(component);\n }\n addOrOverwriteComponent(component) {\n const provider = this.getProvider(component.name);\n if (provider.isComponentSet()) {\n // delete the existing provider from the container, so we can register the new component\n this.providers.delete(component.name);\n }\n this.addComponent(component);\n }\n /**\n * getProvider provides a type safe interface where it can only be called with a field name\n * present in NameServiceMapping interface.\n *\n * Firebase SDKs providing services should extend NameServiceMapping interface to register\n * themselves.\n */\n getProvider(name) {\n if (this.providers.has(name)) {\n return this.providers.get(name);\n }\n // create a Provider for a service that hasn't registered with Firebase\n const provider = new Provider(name, this);\n this.providers.set(name, provider);\n return provider;\n }\n getProviders() {\n return Array.from(this.providers.values());\n }\n}\n\nexport { Component, ComponentContainer, Provider };\n//# sourceMappingURL=index.esm.js.map\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A container for all of the Logger instances\n */\nconst instances = [];\n/**\n * The JS SDK supports 5 log levels and also allows a user the ability to\n * silence the logs altogether.\n *\n * The order is a follows:\n * DEBUG < VERBOSE < INFO < WARN < ERROR\n *\n * All of the log types above the current log level will be captured (i.e. if\n * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and\n * `VERBOSE` logs will not)\n */\nvar LogLevel;\n(function (LogLevel) {\n LogLevel[LogLevel[\"DEBUG\"] = 0] = \"DEBUG\";\n LogLevel[LogLevel[\"VERBOSE\"] = 1] = \"VERBOSE\";\n LogLevel[LogLevel[\"INFO\"] = 2] = \"INFO\";\n LogLevel[LogLevel[\"WARN\"] = 3] = \"WARN\";\n LogLevel[LogLevel[\"ERROR\"] = 4] = \"ERROR\";\n LogLevel[LogLevel[\"SILENT\"] = 5] = \"SILENT\";\n})(LogLevel || (LogLevel = {}));\nconst levelStringToEnum = {\n 'debug': LogLevel.DEBUG,\n 'verbose': LogLevel.VERBOSE,\n 'info': LogLevel.INFO,\n 'warn': LogLevel.WARN,\n 'error': LogLevel.ERROR,\n 'silent': LogLevel.SILENT\n};\n/**\n * The default log level\n */\nconst defaultLogLevel = LogLevel.INFO;\n/**\n * By default, `console.debug` is not displayed in the developer console (in\n * chrome). To avoid forcing users to have to opt-in to these logs twice\n * (i.e. once for firebase, and once in the console), we are sending `DEBUG`\n * logs to the `console.log` function.\n */\nconst ConsoleMethod = {\n [LogLevel.DEBUG]: 'log',\n [LogLevel.VERBOSE]: 'log',\n [LogLevel.INFO]: 'info',\n [LogLevel.WARN]: 'warn',\n [LogLevel.ERROR]: 'error'\n};\n/**\n * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR\n * messages on to their corresponding console counterparts (if the log method\n * is supported by the current log level)\n */\nconst defaultLogHandler = (instance, logType, ...args) => {\n if (logType < instance.logLevel) {\n return;\n }\n const now = new Date().toISOString();\n const method = ConsoleMethod[logType];\n if (method) {\n console[method](`[${now}] ${instance.name}:`, ...args);\n }\n else {\n throw new Error(`Attempted to log a message with an invalid logType (value: ${logType})`);\n }\n};\nclass Logger {\n /**\n * Gives you an instance of a Logger to capture messages according to\n * Firebase's logging scheme.\n *\n * @param name The name that the logs will be associated with\n */\n constructor(name) {\n this.name = name;\n /**\n * The log level of the given Logger instance.\n */\n this._logLevel = defaultLogLevel;\n /**\n * The main (internal) log handler for the Logger instance.\n * Can be set to a new function in internal package code but not by user.\n */\n this._logHandler = defaultLogHandler;\n /**\n * The optional, additional, user-defined log handler for the Logger instance.\n */\n this._userLogHandler = null;\n /**\n * Capture the current instance for later use\n */\n instances.push(this);\n }\n get logLevel() {\n return this._logLevel;\n }\n set logLevel(val) {\n if (!(val in LogLevel)) {\n throw new TypeError(`Invalid value \"${val}\" assigned to \\`logLevel\\``);\n }\n this._logLevel = val;\n }\n // Workaround for setter/getter having to be the same type.\n setLogLevel(val) {\n this._logLevel = typeof val === 'string' ? levelStringToEnum[val] : val;\n }\n get logHandler() {\n return this._logHandler;\n }\n set logHandler(val) {\n if (typeof val !== 'function') {\n throw new TypeError('Value assigned to `logHandler` must be a function');\n }\n this._logHandler = val;\n }\n get userLogHandler() {\n return this._userLogHandler;\n }\n set userLogHandler(val) {\n this._userLogHandler = val;\n }\n /**\n * The functions below are all based on the `console` interface\n */\n debug(...args) {\n this._userLogHandler && this._userLogHandler(this, LogLevel.DEBUG, ...args);\n this._logHandler(this, LogLevel.DEBUG, ...args);\n }\n log(...args) {\n this._userLogHandler &&\n this._userLogHandler(this, LogLevel.VERBOSE, ...args);\n this._logHandler(this, LogLevel.VERBOSE, ...args);\n }\n info(...args) {\n this._userLogHandler && this._userLogHandler(this, LogLevel.INFO, ...args);\n this._logHandler(this, LogLevel.INFO, ...args);\n }\n warn(...args) {\n this._userLogHandler && this._userLogHandler(this, LogLevel.WARN, ...args);\n this._logHandler(this, LogLevel.WARN, ...args);\n }\n error(...args) {\n this._userLogHandler && this._userLogHandler(this, LogLevel.ERROR, ...args);\n this._logHandler(this, LogLevel.ERROR, ...args);\n }\n}\nfunction setLogLevel(level) {\n instances.forEach(inst => {\n inst.setLogLevel(level);\n });\n}\nfunction setUserLogHandler(logCallback, options) {\n for (const instance of instances) {\n let customLogLevel = null;\n if (options && options.level) {\n customLogLevel = levelStringToEnum[options.level];\n }\n if (logCallback === null) {\n instance.userLogHandler = null;\n }\n else {\n instance.userLogHandler = (instance, level, ...args) => {\n const message = args\n .map(arg => {\n if (arg == null) {\n return null;\n }\n else if (typeof arg === 'string') {\n return arg;\n }\n else if (typeof arg === 'number' || typeof arg === 'boolean') {\n return arg.toString();\n }\n else if (arg instanceof Error) {\n return arg.message;\n }\n else {\n try {\n return JSON.stringify(arg);\n }\n catch (ignored) {\n return null;\n }\n }\n })\n .filter(arg => arg)\n .join(' ');\n if (level >= (customLogLevel ?? instance.logLevel)) {\n logCallback({\n level: LogLevel[level].toLowerCase(),\n message,\n args,\n type: instance.name\n });\n }\n };\n }\n }\n}\n\nexport { LogLevel, Logger, setLogLevel, setUserLogHandler };\n//# sourceMappingURL=index.esm.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, base64Decode, getDefaultAppConfig, deepEqual, isBrowser, isWebWorker, FirebaseError, base64urlEncodeWithoutPadding, isIndexedDBAvailable, validateIndexedDBOpenable } from '@firebase/util';\nexport { FirebaseError } from '@firebase/util';\nimport { openDB } from 'idb';\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass PlatformLoggerServiceImpl {\n constructor(container) {\n this.container = container;\n }\n // In initial implementation, this will be called by installations on\n // auth token refresh, and installations will send this string.\n getPlatformInfoString() {\n const providers = this.container.getProviders();\n // Loop through providers and get library/version pairs from any that are\n // version components.\n return providers\n .map(provider => {\n if (isVersionServiceProvider(provider)) {\n const service = provider.getImmediate();\n return `${service.library}/${service.version}`;\n }\n else {\n return null;\n }\n })\n .filter(logString => logString)\n .join(' ');\n }\n}\n/**\n *\n * @param provider check if this provider provides a VersionService\n *\n * NOTE: Using Provider<'app-version'> is a hack to indicate that the provider\n * provides VersionService. The provider is not necessarily a 'app-version'\n * provider.\n */\nfunction isVersionServiceProvider(provider) {\n const component = provider.getComponent();\n return component?.type === \"VERSION\" /* ComponentType.VERSION */;\n}\n\nconst name$q = \"@firebase/app\";\nconst version$1 = \"0.16.3\";\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst logger = new Logger('@firebase/app');\n\nconst name$p = \"@firebase/app-compat\";\n\nconst name$o = \"@firebase/analytics-compat\";\n\nconst name$n = \"@firebase/analytics\";\n\nconst name$m = \"@firebase/app-check-compat\";\n\nconst name$l = \"@firebase/app-check\";\n\nconst name$k = \"@firebase/auth\";\n\nconst name$j = \"@firebase/auth-compat\";\n\nconst name$i = \"@firebase/database\";\n\nconst name$h = \"@firebase/data-connect\";\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/ai\";\n\nconst name$1 = \"@firebase/firestore-compat\";\n\nconst name = \"firebase\";\nconst version = \"13.0.0\";\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * The default app name\n *\n * @internal\n */\nconst DEFAULT_ENTRY_NAME = '[DEFAULT]';\nconst PLATFORM_LOG_STRING = {\n [name$q]: 'fire-core',\n [name$p]: 'fire-core-compat',\n [name$n]: 'fire-analytics',\n [name$o]: 'fire-analytics-compat',\n [name$l]: 'fire-app-check',\n [name$m]: 'fire-app-check-compat',\n [name$k]: 'fire-auth',\n [name$j]: 'fire-auth-compat',\n [name$i]: 'fire-rtdb',\n [name$h]: 'fire-data-connect',\n [name$g]: 'fire-rtdb-compat',\n [name$f]: 'fire-fn',\n [name$e]: 'fire-fn-compat',\n [name$d]: 'fire-iid',\n [name$c]: 'fire-iid-compat',\n [name$b]: 'fire-fcm',\n [name$a]: 'fire-fcm-compat',\n [name$9]: 'fire-perf',\n [name$8]: 'fire-perf-compat',\n [name$7]: 'fire-rc',\n [name$6]: 'fire-rc-compat',\n [name$5]: 'fire-gcs',\n [name$4]: 'fire-gcs-compat',\n [name$3]: 'fire-fst',\n [name$1]: 'fire-fst-compat',\n [name$2]: 'fire-vertex',\n 'fire-js': 'fire-js', // Platform identifier for JS SDK.\n [name]: 'fire-js-all'\n};\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @internal\n */\nconst _apps = new Map();\n/**\n * @internal\n */\nconst _serverApps = new Map();\n/**\n * Registered components.\n *\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst _components = new Map();\n/**\n * @param component - the component being added to this app's container\n *\n * @internal\n */\nfunction _addComponent(app, component) {\n try {\n app.container.addComponent(component);\n }\n catch (e) {\n logger.debug(`Component ${component.name} failed to register with FirebaseApp ${app.name}`, e);\n }\n}\n/**\n *\n * @internal\n */\nfunction _addOrOverwriteComponent(app, component) {\n app.container.addOrOverwriteComponent(component);\n}\n/**\n *\n * @param component - the component to register\n * @returns whether or not the component is registered successfully\n *\n * @internal\n */\nfunction _registerComponent(component) {\n const componentName = component.name;\n if (_components.has(componentName)) {\n logger.debug(`There were multiple attempts to register component ${componentName}.`);\n return false;\n }\n _components.set(componentName, component);\n // add the component to existing app instances\n for (const app of _apps.values()) {\n _addComponent(app, component);\n }\n for (const serverApp of _serverApps.values()) {\n _addComponent(serverApp, component);\n }\n return true;\n}\n/**\n *\n * @param app - FirebaseApp instance\n * @param name - service name\n *\n * @returns the provider for the service with the matching name\n *\n * @internal\n */\nfunction _getProvider(app, name) {\n const heartbeatController = app.container\n .getProvider('heartbeat')\n .getImmediate({ optional: true });\n if (heartbeatController) {\n void heartbeatController.triggerHeartbeat();\n }\n return app.container.getProvider(name);\n}\n/**\n *\n * @param app - FirebaseApp instance\n * @param name - service name\n * @param instanceIdentifier - service instance identifier in case the service supports multiple instances\n *\n * @internal\n */\nfunction _removeServiceInstance(app, name, instanceIdentifier = DEFAULT_ENTRY_NAME) {\n _getProvider(app, name).clearInstance(instanceIdentifier);\n}\n/**\n *\n * @param obj - an object of type FirebaseApp, FirebaseOptions or FirebaseAppSettings.\n *\n * @returns true if the provide object is of type FirebaseApp.\n *\n * @internal\n */\nfunction _isFirebaseApp(obj) {\n return obj.options !== undefined;\n}\n/**\n *\n * @param obj - an object of type FirebaseApp, FirebaseOptions or FirebaseAppSettings.\n *\n * @returns true if the provided object is of type FirebaseServerAppImpl.\n *\n * @internal\n */\nfunction _isFirebaseServerAppSettings(obj) {\n if (_isFirebaseApp(obj)) {\n return false;\n }\n return ('authIdToken' in obj ||\n 'appCheckToken' in obj ||\n 'releaseOnDeref' in obj ||\n 'automaticDataCollectionEnabled' in obj);\n}\n/**\n *\n * @param obj - an object of type FirebaseApp.\n *\n * @returns true if the provided object is of type FirebaseServerAppImpl.\n *\n * @internal\n */\nfunction _isFirebaseServerApp(obj) {\n if (obj === null || obj === undefined) {\n return false;\n }\n return obj.settings !== undefined;\n}\n/**\n * Test only\n *\n * @internal\n */\nfunction _clearComponents() {\n _components.clear();\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst ERRORS = {\n [\"no-app\" /* AppError.NO_APP */]: \"No Firebase App '{$appName}' has been created - \" +\n 'call initializeApp() first',\n [\"bad-app-name\" /* AppError.BAD_APP_NAME */]: \"Illegal App name: '{$appName}'\",\n [\"duplicate-app\" /* AppError.DUPLICATE_APP */]: \"Firebase App named '{$appName}' already exists with different {$mismatchedParam}.\" +\n \" Existing: '{$oldValue}'. New: '{$newValue}'.\",\n [\"app-deleted\" /* AppError.APP_DELETED */]: \"Firebase App named '{$appName}' already deleted\",\n [\"server-app-deleted\" /* AppError.SERVER_APP_DELETED */]: 'Firebase Server App has been deleted',\n [\"no-options\" /* AppError.NO_OPTIONS */]: 'Need to provide options, when not being deployed to hosting via source.',\n [\"invalid-app-argument\" /* AppError.INVALID_APP_ARGUMENT */]: 'firebase.{$appName}() takes either no argument or a ' +\n 'Firebase App instance.',\n [\"invalid-log-argument\" /* AppError.INVALID_LOG_ARGUMENT */]: 'First argument to `onLog` must be null or a function.',\n [\"idb-open\" /* AppError.IDB_OPEN */]: 'Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.',\n [\"idb-get\" /* AppError.IDB_GET */]: 'Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.',\n [\"idb-set\" /* AppError.IDB_WRITE */]: 'Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.',\n [\"idb-delete\" /* AppError.IDB_DELETE */]: 'Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.',\n [\"finalization-registry-not-supported\" /* AppError.FINALIZATION_REGISTRY_NOT_SUPPORTED */]: 'FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.',\n [\"invalid-server-app-environment\" /* AppError.INVALID_SERVER_APP_ENVIRONMENT */]: 'FirebaseServerApp is not for use in browser environments.'\n};\nconst ERROR_FACTORY = new ErrorFactory('app', 'Firebase', ERRORS);\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass FirebaseAppImpl {\n constructor(options, config, container) {\n this._isDeleted = false;\n this._options = { ...options };\n this._config = { ...config };\n this._name = config.name;\n this._automaticDataCollectionEnabled =\n config.automaticDataCollectionEnabled;\n this._container = container;\n this.container.addComponent(new Component('app', () => this, \"PUBLIC\" /* ComponentType.PUBLIC */));\n }\n get automaticDataCollectionEnabled() {\n this.checkDestroyed();\n return this._automaticDataCollectionEnabled;\n }\n set automaticDataCollectionEnabled(val) {\n this.checkDestroyed();\n this._automaticDataCollectionEnabled = val;\n }\n get name() {\n this.checkDestroyed();\n return this._name;\n }\n get options() {\n this.checkDestroyed();\n return this._options;\n }\n get config() {\n this.checkDestroyed();\n return this._config;\n }\n get container() {\n return this._container;\n }\n get isDeleted() {\n return this._isDeleted;\n }\n set isDeleted(val) {\n this._isDeleted = val;\n }\n /**\n * This function will throw an Error if the App has already been deleted -\n * use before performing API actions on the App.\n */\n checkDestroyed() {\n if (this.isDeleted) {\n throw ERROR_FACTORY.create(\"app-deleted\" /* AppError.APP_DELETED */, { appName: this._name });\n }\n }\n}\n\n/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// Parse the token and check to see if the `exp` claim is in the future.\n// Reports an error to the console if the token or claim could not be parsed, or if `exp` is in\n// the past.\nfunction validateTokenTTL(base64Token, tokenName) {\n const secondPart = base64Decode(base64Token.split('.')[1]);\n if (secondPart === null) {\n console.error(`FirebaseServerApp ${tokenName} is invalid: second part could not be parsed.`);\n return;\n }\n const expClaim = JSON.parse(secondPart).exp;\n if (expClaim === undefined) {\n console.error(`FirebaseServerApp ${tokenName} is invalid: expiration claim could not be parsed`);\n return;\n }\n const exp = JSON.parse(secondPart).exp * 1000;\n const now = new Date().getTime();\n const diff = exp - now;\n if (diff <= 0) {\n console.error(`FirebaseServerApp ${tokenName} is invalid: the token has expired.`);\n }\n}\nclass FirebaseServerAppImpl extends FirebaseAppImpl {\n constructor(options, serverConfig, name, container) {\n // Build configuration parameters for the FirebaseAppImpl base class.\n const automaticDataCollectionEnabled = serverConfig.automaticDataCollectionEnabled !== undefined\n ? serverConfig.automaticDataCollectionEnabled\n : true;\n // Create the FirebaseAppSettings object for the FirebaseAppImp constructor.\n const config = {\n name,\n automaticDataCollectionEnabled\n };\n if (options.apiKey !== undefined) {\n // Construct the parent FirebaseAppImp object.\n super(options, config, container);\n }\n else {\n const appImpl = options;\n super(appImpl.options, config, container);\n }\n // Now construct the data for the FirebaseServerAppImpl.\n this._serverConfig = {\n automaticDataCollectionEnabled,\n ...serverConfig\n };\n // Ensure that the current time is within the `authIdtoken` window of validity.\n if (this._serverConfig.authIdToken) {\n validateTokenTTL(this._serverConfig.authIdToken, 'authIdToken');\n }\n // Ensure that the current time is within the `appCheckToken` window of validity.\n if (this._serverConfig.appCheckToken) {\n validateTokenTTL(this._serverConfig.appCheckToken, 'appCheckToken');\n }\n this._finalizationRegistry = null;\n if (typeof FinalizationRegistry !== 'undefined') {\n this._finalizationRegistry = new FinalizationRegistry(() => {\n this.automaticCleanup();\n });\n }\n this._refCount = 0;\n this.incRefCount(this._serverConfig.releaseOnDeref);\n // Do not retain a hard reference to the dref object, otherwise the FinalizationRegistry\n // will never trigger.\n this._serverConfig.releaseOnDeref = undefined;\n serverConfig.releaseOnDeref = undefined;\n registerVersion(name$q, version$1, 'serverapp');\n }\n toJSON() {\n return undefined;\n }\n get refCount() {\n return this._refCount;\n }\n // Increment the reference count of this server app. If an object is provided, register it\n // with the finalization registry.\n incRefCount(obj) {\n if (this.isDeleted) {\n return;\n }\n this._refCount++;\n if (obj !== undefined && this._finalizationRegistry !== null) {\n this._finalizationRegistry.register(obj, this);\n }\n }\n // Decrement the reference count.\n decRefCount() {\n if (this.isDeleted) {\n return 0;\n }\n return --this._refCount;\n }\n // Invoked by the FinalizationRegistry callback to note that this app should go through its\n // reference counts and delete itself if no reference count remain. The coordinating logic that\n // handles this is in deleteApp(...).\n automaticCleanup() {\n void deleteApp(this);\n }\n get settings() {\n this.checkDestroyed();\n return this._serverConfig;\n }\n /**\n * This function will throw an Error if the App has already been deleted -\n * use before performing API actions on the App.\n */\n checkDestroyed() {\n if (this.isDeleted) {\n throw ERROR_FACTORY.create(\"server-app-deleted\" /* AppError.SERVER_APP_DELETED */);\n }\n }\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * The current SDK version.\n *\n * @public\n */\nconst SDK_VERSION = version;\nfunction initializeApp(_options, rawConfig = {}) {\n let options = _options;\n if (typeof rawConfig !== 'object') {\n const name = rawConfig;\n rawConfig = { name };\n }\n const config = {\n name: DEFAULT_ENTRY_NAME,\n automaticDataCollectionEnabled: true,\n ...rawConfig\n };\n const name = config.name;\n if (typeof name !== 'string' || !name) {\n throw ERROR_FACTORY.create(\"bad-app-name\" /* AppError.BAD_APP_NAME */, {\n appName: String(name)\n });\n }\n options || (options = getDefaultAppConfig());\n if (!options) {\n throw ERROR_FACTORY.create(\"no-options\" /* AppError.NO_OPTIONS */);\n }\n const existingApp = _apps.get(name);\n if (existingApp) {\n // return the existing app if options and config deep equal the ones in the existing app.\n if (!deepEqual(options, existingApp.options)) {\n throw ERROR_FACTORY.create(\"duplicate-app\" /* AppError.DUPLICATE_APP */, {\n appName: name,\n mismatchedParam: 'options',\n oldValue: JSON.stringify(existingApp.options),\n newValue: JSON.stringify(options)\n });\n }\n else if (!deepEqual(config, existingApp.config)) {\n throw ERROR_FACTORY.create(\"duplicate-app\" /* AppError.DUPLICATE_APP */, {\n appName: name,\n mismatchedParam: 'config',\n oldValue: JSON.stringify(existingApp.config),\n newValue: JSON.stringify(config)\n });\n }\n else {\n return existingApp;\n }\n }\n const container = new ComponentContainer(name);\n for (const component of _components.values()) {\n container.addComponent(component);\n }\n const newApp = new FirebaseAppImpl(options, config, container);\n _apps.set(name, newApp);\n return newApp;\n}\nfunction initializeServerApp(_options, _serverAppConfig = {}) {\n if (isBrowser() && !isWebWorker()) {\n // FirebaseServerApp isn't designed to be run in browsers.\n throw ERROR_FACTORY.create(\"invalid-server-app-environment\" /* AppError.INVALID_SERVER_APP_ENVIRONMENT */);\n }\n let firebaseOptions;\n let serverAppSettings = _serverAppConfig || {};\n if (_options) {\n if (_isFirebaseApp(_options)) {\n firebaseOptions = _options.options;\n }\n else if (_isFirebaseServerAppSettings(_options)) {\n serverAppSettings = _options;\n }\n else {\n firebaseOptions = _options;\n }\n }\n if (serverAppSettings.automaticDataCollectionEnabled === undefined) {\n serverAppSettings.automaticDataCollectionEnabled = true;\n }\n firebaseOptions || (firebaseOptions = getDefaultAppConfig());\n if (!firebaseOptions) {\n throw ERROR_FACTORY.create(\"no-options\" /* AppError.NO_OPTIONS */);\n }\n // Build an app name based on a hash of the configuration options.\n const nameObj = {\n ...serverAppSettings,\n ...firebaseOptions\n };\n // However, Do not mangle the name based on releaseOnDeref, since it will vary between the\n // construction of FirebaseServerApp instances. For example, if the object is the request headers.\n if (nameObj.releaseOnDeref !== undefined) {\n delete nameObj.releaseOnDeref;\n }\n const hashCode = (s) => {\n return [...s].reduce((hash, c) => (Math.imul(31, hash) + c.charCodeAt(0)) | 0, 0);\n };\n if (serverAppSettings.releaseOnDeref !== undefined) {\n if (typeof FinalizationRegistry === 'undefined') {\n throw ERROR_FACTORY.create(\"finalization-registry-not-supported\" /* AppError.FINALIZATION_REGISTRY_NOT_SUPPORTED */, {});\n }\n }\n const nameString = '' + hashCode(JSON.stringify(nameObj));\n const existingApp = _serverApps.get(nameString);\n if (existingApp) {\n existingApp.incRefCount(serverAppSettings.releaseOnDeref);\n return existingApp;\n }\n const container = new ComponentContainer(nameString);\n for (const component of _components.values()) {\n container.addComponent(component);\n }\n const newApp = new FirebaseServerAppImpl(firebaseOptions, serverAppSettings, nameString, container);\n _serverApps.set(nameString, newApp);\n return newApp;\n}\n/**\n * Retrieves a {@link @firebase/app#FirebaseApp} instance.\n *\n * When called with no arguments, the default app is returned. When an app name\n * is provided, the app corresponding to that name is returned.\n *\n * An exception is thrown if the app being retrieved has not yet been\n * initialized.\n *\n * @example\n * ```javascript\n * // Return the default app\n * const app = getApp();\n * ```\n *\n * @example\n * ```javascript\n * // Return a named app\n * const otherApp = getApp(\"otherApp\");\n * ```\n *\n * @param name - Optional name of the app to return. If no name is\n * provided, the default is `\"[DEFAULT]\"`.\n *\n * @returns The app corresponding to the provided app name.\n * If no app name is provided, the default app is returned.\n *\n * @public\n */\nfunction getApp(name = DEFAULT_ENTRY_NAME) {\n const app = _apps.get(name);\n if (!app && name === DEFAULT_ENTRY_NAME && getDefaultAppConfig()) {\n return initializeApp();\n }\n if (!app) {\n throw ERROR_FACTORY.create(\"no-app\" /* AppError.NO_APP */, { appName: name });\n }\n return app;\n}\n/**\n * A (read-only) array of all initialized apps.\n * @public\n */\nfunction getApps() {\n return Array.from(_apps.values());\n}\n/**\n * Renders this app unusable and frees the resources of all associated\n * services.\n *\n * @example\n * ```javascript\n * deleteApp(app)\n * .then(function() {\n * console.log(\"App deleted successfully\");\n * })\n * .catch(function(error) {\n * console.log(\"Error deleting app:\", error);\n * });\n * ```\n *\n * @public\n */\nasync function deleteApp(app) {\n let cleanupProviders = false;\n const name = app.name;\n if (_apps.has(name)) {\n cleanupProviders = true;\n _apps.delete(name);\n }\n else if (_serverApps.has(name)) {\n const firebaseServerApp = app;\n if (firebaseServerApp.decRefCount() <= 0) {\n _serverApps.delete(name);\n cleanupProviders = true;\n }\n }\n if (cleanupProviders) {\n await Promise.all(app.container\n .getProviders()\n .map(provider => provider.delete()));\n app.isDeleted = true;\n }\n}\n/**\n * Registers a library's name and version for platform logging purposes.\n * @param library - Name of 1p or 3p library (e.g. firestore, angularfire)\n * @param version - Current version of that library.\n * @param variant - Bundle variant, e.g., node, rn, etc.\n *\n * @public\n */\nfunction registerVersion(libraryKeyOrName, version, variant) {\n // TODO: We can use this check to whitelist strings when/if we set up\n // a good whitelist system.\n let library = PLATFORM_LOG_STRING[libraryKeyOrName] ?? libraryKeyOrName;\n if (variant) {\n library += `-${variant}`;\n }\n const libraryMismatch = library.match(/\\s|\\//);\n const versionMismatch = version.match(/\\s|\\//);\n if (libraryMismatch || versionMismatch) {\n const warning = [\n `Unable to register library \"${library}\" with version \"${version}\":`\n ];\n if (libraryMismatch) {\n warning.push(`library name \"${library}\" contains illegal characters (whitespace or \"/\")`);\n }\n if (libraryMismatch && versionMismatch) {\n warning.push('and');\n }\n if (versionMismatch) {\n warning.push(`version name \"${version}\" contains illegal characters (whitespace or \"/\")`);\n }\n logger.warn(warning.join(' '));\n return;\n }\n _registerComponent(new Component(`${library}-version`, () => ({ library, version }), \"VERSION\" /* ComponentType.VERSION */));\n}\n/**\n * Sets log handler for all Firebase SDKs.\n * @param logCallback - An optional custom log handler that executes user code whenever\n * the Firebase SDK makes a logging call.\n *\n * @public\n */\nfunction onLog(logCallback, options) {\n if (logCallback !== null && typeof logCallback !== 'function') {\n throw ERROR_FACTORY.create(\"invalid-log-argument\" /* AppError.INVALID_LOG_ARGUMENT */);\n }\n setUserLogHandler(logCallback, options);\n}\n/**\n * Sets log level for all Firebase SDKs.\n *\n * All of the log types above the current log level are captured (i.e. if\n * you set the log level to `info`, errors are logged, but `debug` and\n * `verbose` logs are not).\n *\n * @public\n */\nfunction setLogLevel(logLevel) {\n setLogLevel$1(logLevel);\n}\n\n/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst DB_NAME = 'firebase-heartbeat-database';\nconst DB_VERSION = 1;\nconst STORE_NAME = 'firebase-heartbeat-store';\nlet dbPromise = null;\nfunction getDbPromise() {\n if (!dbPromise) {\n dbPromise = openDB(DB_NAME, DB_VERSION, {\n upgrade: (db, oldVersion) => {\n // We don't use 'break' in this switch statement, the fall-through\n // behavior is what we want, because if there are multiple versions between\n // the old version and the current version, we want ALL the migrations\n // that correspond to those versions to run, not only the last one.\n // eslint-disable-next-line default-case\n switch (oldVersion) {\n case 0:\n try {\n db.createObjectStore(STORE_NAME);\n }\n catch (e) {\n // Safari/iOS browsers throw occasional exceptions on\n // db.createObjectStore() that may be a bug. Avoid blocking\n // the rest of the app functionality.\n console.warn(e);\n }\n }\n }\n }).catch(e => {\n throw ERROR_FACTORY.create(\"idb-open\" /* AppError.IDB_OPEN */, {\n originalErrorMessage: e.message\n });\n });\n }\n return dbPromise;\n}\nasync function readHeartbeatsFromIndexedDB(app) {\n try {\n const db = await getDbPromise();\n const tx = db.transaction(STORE_NAME);\n const result = await tx.objectStore(STORE_NAME).get(computeKey(app));\n // We already have the value but tx.done can throw,\n // so we need to await it here to catch errors\n await tx.done;\n return result;\n }\n catch (e) {\n if (e instanceof FirebaseError) {\n logger.warn(e.message);\n }\n else {\n const idbGetError = ERROR_FACTORY.create(\"idb-get\" /* AppError.IDB_GET */, {\n originalErrorMessage: e?.message\n });\n logger.warn(idbGetError.message);\n }\n }\n}\nasync function writeHeartbeatsToIndexedDB(app, heartbeatObject) {\n try {\n const db = await getDbPromise();\n const tx = db.transaction(STORE_NAME, 'readwrite');\n const objectStore = tx.objectStore(STORE_NAME);\n await objectStore.put(heartbeatObject, computeKey(app));\n await tx.done;\n }\n catch (e) {\n if (e instanceof FirebaseError) {\n logger.warn(e.message);\n }\n else {\n const idbGetError = ERROR_FACTORY.create(\"idb-set\" /* AppError.IDB_WRITE */, {\n originalErrorMessage: e?.message\n });\n logger.warn(idbGetError.message);\n }\n }\n}\nfunction computeKey(app) {\n return `${app.name}!${app.options.appId}`;\n}\n\n/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst MAX_HEADER_BYTES = 1024;\nconst MAX_NUM_STORED_HEARTBEATS = 30;\nclass HeartbeatServiceImpl {\n constructor(container) {\n this.container = container;\n /**\n * In-memory cache for heartbeats, used by getHeartbeatsHeader() to generate\n * the header string.\n * Stores one record per date. This will be consolidated into the standard\n * format of one record per user agent string before being sent as a header.\n * Populated from indexedDB when the controller is instantiated and should\n * be kept in sync with indexedDB.\n * Leave public for easier testing.\n */\n this._heartbeatsCache = null;\n const app = this.container.getProvider('app').getImmediate();\n this._storage = new HeartbeatStorageImpl(app);\n this._heartbeatsCachePromise = this._storage.read().then(result => {\n this._heartbeatsCache = result;\n return result;\n });\n }\n /**\n * Called to report a heartbeat. The function will generate\n * a HeartbeatsByUserAgent object, update heartbeatsCache, and persist it\n * to IndexedDB.\n * Note that we only store one heartbeat per day. So if a heartbeat for today is\n * already logged, subsequent calls to this function in the same day will be ignored.\n */\n async triggerHeartbeat() {\n try {\n const platformLogger = this.container\n .getProvider('platform-logger')\n .getImmediate();\n // This is the \"Firebase user agent\" string from the platform logger\n // service, not the browser user agent.\n const agent = platformLogger.getPlatformInfoString();\n const date = getUTCDateString();\n if (this._heartbeatsCache?.heartbeats == null) {\n this._heartbeatsCache = await this._heartbeatsCachePromise;\n // If we failed to construct a heartbeats cache, then return immediately.\n if (this._heartbeatsCache?.heartbeats == null) {\n return;\n }\n }\n // Do not store a heartbeat if one is already stored for this day\n // or if a header has already been sent today.\n if (this._heartbeatsCache.lastSentHeartbeatDate === date ||\n this._heartbeatsCache.heartbeats.some(singleDateHeartbeat => singleDateHeartbeat.date === date)) {\n return;\n }\n else {\n // There is no entry for this date. Create one.\n this._heartbeatsCache.heartbeats.push({ date, agent });\n // If the number of stored heartbeats exceeds the maximum number of stored heartbeats, remove the heartbeat with the earliest date.\n // Since this is executed each time a heartbeat is pushed, the limit can only be exceeded by one, so only one needs to be removed.\n if (this._heartbeatsCache.heartbeats.length > MAX_NUM_STORED_HEARTBEATS) {\n const earliestHeartbeatIdx = getEarliestHeartbeatIdx(this._heartbeatsCache.heartbeats);\n this._heartbeatsCache.heartbeats.splice(earliestHeartbeatIdx, 1);\n }\n }\n return this._storage.overwrite(this._heartbeatsCache);\n }\n catch (e) {\n logger.warn(e);\n }\n }\n /**\n * Returns a base64 encoded string which can be attached to the heartbeat-specific header directly.\n * It also clears all heartbeats from memory as well as in IndexedDB.\n *\n * NOTE: Consuming product SDKs should not send the header if this method\n * returns an empty string.\n */\n async getHeartbeatsHeader() {\n try {\n if (this._heartbeatsCache === null) {\n await this._heartbeatsCachePromise;\n }\n // If it's still null or the array is empty, there is no data to send.\n if (this._heartbeatsCache?.heartbeats == null ||\n this._heartbeatsCache.heartbeats.length === 0) {\n return '';\n }\n const date = getUTCDateString();\n // Extract as many heartbeats from the cache as will fit under the size limit.\n const { heartbeatsToSend, unsentEntries } = extractHeartbeatsForHeader(this._heartbeatsCache.heartbeats);\n const headerString = base64urlEncodeWithoutPadding(JSON.stringify({ version: 2, heartbeats: heartbeatsToSend }));\n // Store last sent date to prevent another being logged/sent for the same day.\n this._heartbeatsCache.lastSentHeartbeatDate = date;\n if (unsentEntries.length > 0) {\n // Store any unsent entries if they exist.\n this._heartbeatsCache.heartbeats = unsentEntries;\n // This seems more likely than emptying the array (below) to lead to some odd state\n // since the cache isn't empty and this will be called again on the next request,\n // and is probably safest if we await it.\n await this._storage.overwrite(this._heartbeatsCache);\n }\n else {\n this._heartbeatsCache.heartbeats = [];\n // Do not wait for this, to reduce latency.\n void this._storage.overwrite(this._heartbeatsCache);\n }\n return headerString;\n }\n catch (e) {\n logger.warn(e);\n return '';\n }\n }\n}\nfunction getUTCDateString() {\n const today = new Date();\n // Returns date format 'YYYY-MM-DD'\n return today.toISOString().substring(0, 10);\n}\nfunction extractHeartbeatsForHeader(heartbeatsCache, maxSize = MAX_HEADER_BYTES) {\n // Heartbeats grouped by user agent in the standard format to be sent in\n // the header.\n const heartbeatsToSend = [];\n // Single date format heartbeats that are not sent.\n let unsentEntries = heartbeatsCache.slice();\n for (const singleDateHeartbeat of heartbeatsCache) {\n // Look for an existing entry with the same user agent.\n const heartbeatEntry = heartbeatsToSend.find(hb => hb.agent === singleDateHeartbeat.agent);\n if (!heartbeatEntry) {\n // If no entry for this user agent exists, create one.\n heartbeatsToSend.push({\n agent: singleDateHeartbeat.agent,\n dates: [singleDateHeartbeat.date]\n });\n if (countBytes(heartbeatsToSend) > maxSize) {\n // If the header would exceed max size, remove the added heartbeat\n // entry and stop adding to the header.\n heartbeatsToSend.pop();\n break;\n }\n }\n else {\n heartbeatEntry.dates.push(singleDateHeartbeat.date);\n // If the header would exceed max size, remove the added date\n // and stop adding to the header.\n if (countBytes(heartbeatsToSend) > maxSize) {\n heartbeatEntry.dates.pop();\n break;\n }\n }\n // Pop unsent entry from queue. (Skipped if adding the entry exceeded\n // quota and the loop breaks early.)\n unsentEntries = unsentEntries.slice(1);\n }\n return {\n heartbeatsToSend,\n unsentEntries\n };\n}\nclass HeartbeatStorageImpl {\n constructor(app) {\n this.app = app;\n this._canUseIndexedDBPromise = this.runIndexedDBEnvironmentCheck();\n }\n async runIndexedDBEnvironmentCheck() {\n if (!isIndexedDBAvailable()) {\n return false;\n }\n else {\n return validateIndexedDBOpenable()\n .then(() => true)\n .catch(() => false);\n }\n }\n /**\n * Read all heartbeats.\n */\n async read() {\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\n if (!canUseIndexedDB) {\n return { heartbeats: [] };\n }\n else {\n const idbHeartbeatObject = await readHeartbeatsFromIndexedDB(this.app);\n if (idbHeartbeatObject?.heartbeats) {\n return idbHeartbeatObject;\n }\n else {\n return { heartbeats: [] };\n }\n }\n }\n // overwrite the storage with the provided heartbeats\n async overwrite(heartbeatsObject) {\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\n if (!canUseIndexedDB) {\n return;\n }\n else {\n const existingHeartbeatsObject = await this.read();\n return writeHeartbeatsToIndexedDB(this.app, {\n lastSentHeartbeatDate: heartbeatsObject.lastSentHeartbeatDate ??\n existingHeartbeatsObject.lastSentHeartbeatDate,\n heartbeats: heartbeatsObject.heartbeats\n });\n }\n }\n // add heartbeats\n async add(heartbeatsObject) {\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\n if (!canUseIndexedDB) {\n return;\n }\n else {\n const existingHeartbeatsObject = await this.read();\n return writeHeartbeatsToIndexedDB(this.app, {\n lastSentHeartbeatDate: heartbeatsObject.lastSentHeartbeatDate ??\n existingHeartbeatsObject.lastSentHeartbeatDate,\n heartbeats: [\n ...existingHeartbeatsObject.heartbeats,\n ...heartbeatsObject.heartbeats\n ]\n });\n }\n }\n}\n/**\n * Calculate bytes of a HeartbeatsByUserAgent array after being wrapped\n * in a platform logging header JSON object, stringified, and converted\n * to base 64.\n */\nfunction countBytes(heartbeatsCache) {\n // base64 has a restricted set of characters, all of which should be 1 byte.\n return base64urlEncodeWithoutPadding(\n // heartbeatsCache wrapper properties\n JSON.stringify({ version: 2, heartbeats: heartbeatsCache })).length;\n}\n/**\n * Returns the index of the heartbeat with the earliest date.\n * If the heartbeats array is empty, -1 is returned.\n */\nfunction getEarliestHeartbeatIdx(heartbeats) {\n if (heartbeats.length === 0) {\n return -1;\n }\n let earliestHeartbeatIdx = 0;\n let earliestHeartbeatDate = heartbeats[0].date;\n for (let i = 1; i < heartbeats.length; i++) {\n if (heartbeats[i].date < earliestHeartbeatDate) {\n earliestHeartbeatDate = heartbeats[i].date;\n earliestHeartbeatIdx = i;\n }\n }\n return earliestHeartbeatIdx;\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nfunction registerCoreComponents(variant) {\n _registerComponent(new Component('platform-logger', container => new PlatformLoggerServiceImpl(container), \"PRIVATE\" /* ComponentType.PRIVATE */));\n _registerComponent(new Component('heartbeat', container => new HeartbeatServiceImpl(container), \"PRIVATE\" /* ComponentType.PRIVATE */));\n // Register `app` package.\n registerVersion(name$q, version$1, variant);\n // BUILD_TARGET will be replaced by values like esm, cjs, etc during the compilation\n registerVersion(name$q, version$1, 'esm2020');\n // Register platform SDK identifier (no version).\n registerVersion('fire-js', '');\n}\n\n/**\n * Firebase App\n *\n * @remarks This package coordinates the communication between the different Firebase components\n * @packageDocumentation\n */\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nregisterCoreComponents('');\n\nexport { SDK_VERSION, DEFAULT_ENTRY_NAME as _DEFAULT_ENTRY_NAME, _addComponent, _addOrOverwriteComponent, _apps, _clearComponents, _components, _getProvider, _isFirebaseApp, _isFirebaseServerApp, _isFirebaseServerAppSettings, _registerComponent, _removeServiceInstance, _serverApps, deleteApp, getApp, getApps, initializeApp, initializeServerApp, onLog, registerVersion, setLogLevel };\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, isCloudflareWorker, isCloudWorkstation, getModularInstance, base64Decode, getUA, isIE, createSubscribe, Deferred, deepEqual, pingServer, querystringDecode, extractQuerystring, isEmpty, getExperimentalSetting, getDefaultEmulatorHost } from '@firebase/util';\nimport { Logger, LogLevel } from '@firebase/logger';\nimport { Component } from '@firebase/component';\n\n/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An enum of factors that may be used for multifactor authentication.\n *\n * @public\n */\nconst FactorId = {\n /** Phone as second factor */\n PHONE: 'phone',\n TOTP: 'totp'\n};\n/**\n * Enumeration of supported providers.\n *\n * @public\n */\nconst ProviderId = {\n /** Facebook provider ID */\n FACEBOOK: 'facebook.com',\n /** GitHub provider ID */\n GITHUB: 'github.com',\n /** Google provider ID */\n GOOGLE: 'google.com',\n /** Password provider */\n PASSWORD: 'password',\n /** Phone provider */\n PHONE: 'phone',\n /** Twitter provider ID */\n TWITTER: 'twitter.com'\n};\n/**\n * Enumeration of supported sign-in methods.\n *\n * @public\n */\nconst SignInMethod = {\n /** Email link sign in method */\n EMAIL_LINK: 'emailLink',\n /** Email/password sign in method */\n EMAIL_PASSWORD: 'password',\n /** Facebook sign in method */\n FACEBOOK: 'facebook.com',\n /** GitHub sign in method */\n GITHUB: 'github.com',\n /** Google sign in method */\n GOOGLE: 'google.com',\n /** Phone sign in method */\n PHONE: 'phone',\n /** Twitter sign in method */\n TWITTER: 'twitter.com'\n};\n/**\n * Enumeration of supported operation types.\n *\n * @public\n */\nconst OperationType = {\n /** Operation involving linking an additional provider to an already signed-in user. */\n LINK: 'link',\n /** Operation involving using a provider to reauthenticate an already signed-in user. */\n REAUTHENTICATE: 'reauthenticate',\n /** Operation involving signing in a user. */\n SIGN_IN: 'signIn'\n};\n/**\n * An enumeration of the possible email action types.\n *\n * @public\n */\nconst ActionCodeOperation = {\n /** The email link sign-in action. */\n EMAIL_SIGNIN: 'EMAIL_SIGNIN',\n /** The password reset action. */\n PASSWORD_RESET: 'PASSWORD_RESET',\n /** The email revocation action. */\n RECOVER_EMAIL: 'RECOVER_EMAIL',\n /** The revert second factor addition email action. */\n REVERT_SECOND_FACTOR_ADDITION: 'REVERT_SECOND_FACTOR_ADDITION',\n /** The revert second factor addition email action. */\n VERIFY_AND_CHANGE_EMAIL: 'VERIFY_AND_CHANGE_EMAIL',\n /** The email verification action. */\n VERIFY_EMAIL: 'VERIFY_EMAIL'\n};\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nfunction _debugErrorMap() {\n return {\n [\"admin-restricted-operation\" /* AuthErrorCode.ADMIN_ONLY_OPERATION */]: 'This operation is restricted to administrators only.',\n [\"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */]: '',\n [\"app-not-authorized\" /* AuthErrorCode.APP_NOT_AUTHORIZED */]: \"This app, identified by the domain where it's hosted, is not \" +\n 'authorized to use Firebase Authentication with the provided API key. ' +\n 'Review your key configuration in the Google API console.',\n [\"app-not-installed\" /* AuthErrorCode.APP_NOT_INSTALLED */]: 'The requested mobile application corresponding to the identifier (' +\n 'Android package name or iOS bundle ID) provided is not installed on ' +\n 'this device.',\n [\"captcha-check-failed\" /* AuthErrorCode.CAPTCHA_CHECK_FAILED */]: 'The reCAPTCHA response token provided is either invalid, expired, ' +\n 'already used or the domain associated with it does not match the list ' +\n 'of whitelisted domains.',\n [\"code-expired\" /* AuthErrorCode.CODE_EXPIRED */]: 'The SMS code has expired. Please re-send the verification code to try ' +\n 'again.',\n [\"cordova-not-ready\" /* AuthErrorCode.CORDOVA_NOT_READY */]: 'Cordova framework is not ready.',\n [\"cors-unsupported\" /* AuthErrorCode.CORS_UNSUPPORTED */]: 'This browser is not supported.',\n [\"credential-already-in-use\" /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */]: 'This credential is already associated with a different user account.',\n [\"custom-token-mismatch\" /* AuthErrorCode.CREDENTIAL_MISMATCH */]: 'The custom token corresponds to a different audience.',\n [\"requires-recent-login\" /* AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */]: 'This operation is sensitive and requires recent authentication. Log in ' +\n 'again before retrying this request.',\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 ' +\n 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +\n 'starting any other Firebase SDK.',\n [\"dynamic-link-not-activated\" /* AuthErrorCode.DYNAMIC_LINK_NOT_ACTIVATED */]: 'Please activate Dynamic Links in the Firebase Console and agree to the terms and ' +\n 'conditions.',\n [\"email-change-needs-verification\" /* AuthErrorCode.EMAIL_CHANGE_NEEDS_VERIFICATION */]: 'Multi-factor users must always have a verified email.',\n [\"email-already-in-use\" /* AuthErrorCode.EMAIL_EXISTS */]: 'The email address is already in use by another account.',\n [\"emulator-config-failed\" /* AuthErrorCode.EMULATOR_CONFIG_FAILED */]: 'Auth instance has already been used to make a network call. Auth can ' +\n 'no longer be configured to use the emulator. Try calling ' +\n '\"connectAuthEmulator()\" sooner.',\n [\"expired-action-code\" /* AuthErrorCode.EXPIRED_OOB_CODE */]: 'The action code has expired.',\n [\"cancelled-popup-request\" /* AuthErrorCode.EXPIRED_POPUP_REQUEST */]: 'This operation has been cancelled due to another conflicting popup being opened.',\n [\"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */]: 'An internal AuthError has occurred.',\n [\"invalid-app-credential\" /* AuthErrorCode.INVALID_APP_CREDENTIAL */]: 'The phone verification request contains an invalid application verifier.' +\n ' The reCAPTCHA token response is either invalid or expired.',\n [\"invalid-app-id\" /* AuthErrorCode.INVALID_APP_ID */]: 'The mobile app identifier is not registered for the current project.',\n [\"invalid-user-token\" /* AuthErrorCode.INVALID_AUTH */]: \"This user's credential isn't valid for this project. This can happen \" +\n \"if the user's token has been tampered with, or if the user isn't for \" +\n 'the project associated with this API key.',\n [\"invalid-auth-event\" /* AuthErrorCode.INVALID_AUTH_EVENT */]: 'An internal AuthError has occurred.',\n [\"invalid-verification-code\" /* AuthErrorCode.INVALID_CODE */]: 'The SMS verification code used to create the phone auth credential is ' +\n 'invalid. Please resend the verification code sms and be sure to use the ' +\n 'verification code provided by the user.',\n [\"invalid-continue-uri\" /* AuthErrorCode.INVALID_CONTINUE_URI */]: 'The continue URL provided in the request is invalid.',\n [\"invalid-cordova-configuration\" /* AuthErrorCode.INVALID_CORDOVA_CONFIGURATION */]: 'The following Cordova plugins must be installed to enable OAuth sign-in: ' +\n 'cordova-plugin-buildinfo, cordova-universal-links-plugin, ' +\n 'cordova-plugin-browsertab, cordova-plugin-inappbrowser and ' +\n 'cordova-plugin-customurlscheme.',\n [\"invalid-custom-token\" /* AuthErrorCode.INVALID_CUSTOM_TOKEN */]: 'The custom token format is incorrect. Please check the documentation.',\n [\"invalid-dynamic-link-domain\" /* AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN */]: 'The provided dynamic link domain is not configured or authorized for the current project.',\n [\"invalid-email\" /* AuthErrorCode.INVALID_EMAIL */]: 'The email address is badly formatted.',\n [\"invalid-emulator-scheme\" /* AuthErrorCode.INVALID_EMULATOR_SCHEME */]: 'Emulator URL must start with a valid scheme (http:// or https://).',\n [\"invalid-api-key\" /* AuthErrorCode.INVALID_API_KEY */]: 'Your API key is invalid, please check you have copied it correctly.',\n [\"invalid-cert-hash\" /* AuthErrorCode.INVALID_CERT_HASH */]: 'The SHA-1 certificate hash provided is invalid.',\n [\"invalid-credential\" /* AuthErrorCode.INVALID_CREDENTIAL */]: 'The supplied auth credential is incorrect, malformed or has expired.',\n [\"invalid-message-payload\" /* AuthErrorCode.INVALID_MESSAGE_PAYLOAD */]: 'The email template corresponding to this action contains invalid characters in its message. ' +\n 'Please fix by going to the Auth email templates section in the Firebase Console.',\n [\"invalid-multi-factor-session\" /* AuthErrorCode.INVALID_MFA_SESSION */]: 'The request does not contain a valid proof of first factor successful sign-in.',\n [\"invalid-oauth-provider\" /* AuthErrorCode.INVALID_OAUTH_PROVIDER */]: 'EmailAuthProvider is not supported for this operation. This operation ' +\n 'only supports OAuth providers.',\n [\"invalid-oauth-client-id\" /* AuthErrorCode.INVALID_OAUTH_CLIENT_ID */]: 'The OAuth client ID provided is either invalid or does not match the ' +\n 'specified API key.',\n [\"unauthorized-domain\" /* AuthErrorCode.INVALID_ORIGIN */]: 'This domain is not authorized for OAuth operations for your Firebase ' +\n 'project. Edit the list of authorized domains from the Firebase console.',\n [\"invalid-action-code\" /* AuthErrorCode.INVALID_OOB_CODE */]: 'The action code is invalid. This can happen if the code is malformed, ' +\n 'expired, or has already been used.',\n [\"wrong-password\" /* AuthErrorCode.INVALID_PASSWORD */]: 'The password is invalid or the user does not have a password.',\n [\"invalid-persistence-type\" /* AuthErrorCode.INVALID_PERSISTENCE */]: 'The specified persistence type is invalid. It can only be local, session or none.',\n [\"invalid-phone-number\" /* AuthErrorCode.INVALID_PHONE_NUMBER */]: 'The format of the phone number provided is incorrect. Please enter the ' +\n 'phone number in a format that can be parsed into E.164 format. E.164 ' +\n 'phone numbers are written in the format [+][country code][subscriber ' +\n 'number including area code].',\n [\"invalid-provider-id\" /* AuthErrorCode.INVALID_PROVIDER_ID */]: 'The specified provider ID is invalid.',\n [\"invalid-recipient-email\" /* AuthErrorCode.INVALID_RECIPIENT_EMAIL */]: 'The email corresponding to this action failed to send as the provided ' +\n 'recipient email address is invalid.',\n [\"invalid-sender\" /* AuthErrorCode.INVALID_SENDER */]: 'The email template corresponding to this action contains an invalid sender email or name. ' +\n 'Please fix by going to the Auth email templates section in the Firebase Console.',\n [\"invalid-verification-id\" /* AuthErrorCode.INVALID_SESSION_INFO */]: 'The verification ID used to create the phone auth credential is invalid.',\n [\"invalid-tenant-id\" /* AuthErrorCode.INVALID_TENANT_ID */]: \"The Auth instance's tenant ID is invalid.\",\n [\"login-blocked\" /* AuthErrorCode.LOGIN_BLOCKED */]: 'Login blocked by user-provided method: {$originalMessage}',\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.',\n [\"auth-domain-config-required\" /* AuthErrorCode.MISSING_AUTH_DOMAIN */]: 'Be sure to include authDomain when calling firebase.initializeApp(), ' +\n 'by following the instructions in the Firebase console.',\n [\"missing-app-credential\" /* AuthErrorCode.MISSING_APP_CREDENTIAL */]: 'The phone verification request is missing an application verifier ' +\n 'assertion. A reCAPTCHA response token needs to be provided.',\n [\"missing-verification-code\" /* AuthErrorCode.MISSING_CODE */]: 'The phone auth credential was created with an empty SMS verification code.',\n [\"missing-continue-uri\" /* AuthErrorCode.MISSING_CONTINUE_URI */]: 'A continue URL must be provided in the request.',\n [\"missing-iframe-start\" /* AuthErrorCode.MISSING_IFRAME_START */]: 'An internal AuthError has occurred.',\n [\"missing-ios-bundle-id\" /* AuthErrorCode.MISSING_IOS_BUNDLE_ID */]: 'An iOS Bundle ID must be provided if an App Store ID is provided.',\n [\"missing-or-invalid-nonce\" /* AuthErrorCode.MISSING_OR_INVALID_NONCE */]: 'The request does not contain a valid nonce. This can occur if the ' +\n 'SHA-256 hash of the provided raw nonce does not match the hashed nonce ' +\n 'in the ID token payload.',\n [\"missing-password\" /* AuthErrorCode.MISSING_PASSWORD */]: 'A non-empty password must be provided',\n [\"missing-multi-factor-info\" /* AuthErrorCode.MISSING_MFA_INFO */]: 'No second factor identifier is provided.',\n [\"missing-multi-factor-session\" /* AuthErrorCode.MISSING_MFA_SESSION */]: 'The request is missing proof of first factor successful sign-in.',\n [\"missing-phone-number\" /* AuthErrorCode.MISSING_PHONE_NUMBER */]: 'To send verification codes, provide a phone number for the recipient.',\n [\"missing-verification-id\" /* AuthErrorCode.MISSING_SESSION_INFO */]: 'The phone auth credential was created with an empty verification ID.',\n [\"app-deleted\" /* AuthErrorCode.MODULE_DESTROYED */]: 'This instance of FirebaseApp has been deleted.',\n [\"multi-factor-info-not-found\" /* AuthErrorCode.MFA_INFO_NOT_FOUND */]: 'The user does not have a second factor matching the identifier provided.',\n [\"multi-factor-auth-required\" /* AuthErrorCode.MFA_REQUIRED */]: 'Proof of ownership of a second factor is required to complete sign-in.',\n [\"account-exists-with-different-credential\" /* AuthErrorCode.NEED_CONFIRMATION */]: 'An account already exists with the same email address but different ' +\n 'sign-in credentials. Sign in using a provider associated with this ' +\n 'email address.',\n [\"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */]: 'A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred.',\n [\"no-auth-event\" /* AuthErrorCode.NO_AUTH_EVENT */]: 'An internal AuthError has occurred.',\n [\"no-such-provider\" /* AuthErrorCode.NO_SUCH_PROVIDER */]: 'User was not linked to an account with the given provider.',\n [\"null-user\" /* AuthErrorCode.NULL_USER */]: 'A null user object was provided as the argument for an operation which ' +\n 'requires a non-null user object.',\n [\"operation-not-allowed\" /* AuthErrorCode.OPERATION_NOT_ALLOWED */]: 'The given sign-in provider is disabled for this Firebase project. ' +\n 'Enable it in the Firebase console, under the sign-in method tab of the ' +\n 'Auth section.',\n [\"operation-not-supported-in-this-environment\" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */]: 'This operation is not supported in the environment this application is ' +\n 'running on. \"location.protocol\" must be http, https or chrome-extension' +\n ' and web storage must be enabled.',\n [\"popup-blocked\" /* AuthErrorCode.POPUP_BLOCKED */]: 'Unable to establish a connection with the popup. It may have been blocked by the browser.',\n [\"popup-closed-by-user\" /* AuthErrorCode.POPUP_CLOSED_BY_USER */]: 'The popup has been closed by the user before finalizing the operation.',\n [\"provider-already-linked\" /* AuthErrorCode.PROVIDER_ALREADY_LINKED */]: 'User can only be linked to one identity for the given provider.',\n [\"quota-exceeded\" /* AuthErrorCode.QUOTA_EXCEEDED */]: \"The project's quota for this operation has been exceeded.\",\n [\"redirect-cancelled-by-user\" /* AuthErrorCode.REDIRECT_CANCELLED_BY_USER */]: 'The redirect operation has been cancelled by the user before finalizing.',\n [\"redirect-operation-pending\" /* AuthErrorCode.REDIRECT_OPERATION_PENDING */]: 'A redirect sign-in operation is already pending.',\n [\"rejected-credential\" /* AuthErrorCode.REJECTED_CREDENTIAL */]: 'The request contains malformed or mismatching credentials.',\n [\"second-factor-already-in-use\" /* AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED */]: 'The second factor is already enrolled on this account.',\n [\"maximum-second-factor-count-exceeded\" /* AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED */]: 'The maximum allowed number of second factors on a user has been exceeded.',\n [\"tenant-id-mismatch\" /* AuthErrorCode.TENANT_ID_MISMATCH */]: \"The provided tenant ID does not match the Auth instance's tenant ID\",\n [\"timeout\" /* AuthErrorCode.TIMEOUT */]: 'The operation has timed out.',\n [\"user-token-expired\" /* AuthErrorCode.TOKEN_EXPIRED */]: \"The user's credential is no longer valid. The user must sign in again.\",\n [\"too-many-requests\" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */]: 'We have blocked all requests from this device due to unusual activity. ' +\n 'Try again later.',\n [\"unauthorized-continue-uri\" /* AuthErrorCode.UNAUTHORIZED_DOMAIN */]: 'The domain of the continue URL is not whitelisted. Please whitelist ' +\n 'the domain in the Firebase console.',\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.',\n [\"unsupported-persistence-type\" /* AuthErrorCode.UNSUPPORTED_PERSISTENCE */]: 'The current environment does not support the specified persistence type.',\n [\"unsupported-tenant-operation\" /* AuthErrorCode.UNSUPPORTED_TENANT_OPERATION */]: 'This operation is not supported in a multi-tenant context.',\n [\"unverified-email\" /* AuthErrorCode.UNVERIFIED_EMAIL */]: 'The operation requires a verified email.',\n [\"user-cancelled\" /* AuthErrorCode.USER_CANCELLED */]: 'The user did not grant your application the permissions it requested.',\n [\"user-not-found\" /* AuthErrorCode.USER_DELETED */]: 'There is no user record corresponding to this identifier. The user may ' +\n 'have been deleted.',\n [\"user-disabled\" /* AuthErrorCode.USER_DISABLED */]: 'The user account has been disabled by an administrator.',\n [\"user-mismatch\" /* AuthErrorCode.USER_MISMATCH */]: 'The supplied credentials do not correspond to the previously signed in user.',\n [\"user-signed-out\" /* AuthErrorCode.USER_SIGNED_OUT */]: '',\n [\"weak-password\" /* AuthErrorCode.WEAK_PASSWORD */]: 'The password must be 6 characters long or more.',\n [\"web-storage-unsupported\" /* AuthErrorCode.WEB_STORAGE_UNSUPPORTED */]: 'This browser is not supported or 3rd party cookies and data may be disabled.',\n [\"already-initialized\" /* AuthErrorCode.ALREADY_INITIALIZED */]: 'initializeAuth() has already been called with ' +\n 'different options. To avoid this error, call initializeAuth() with the ' +\n 'same options as when it was originally called, or call getAuth() to return the' +\n ' already initialized instance.',\n [\"missing-recaptcha-token\" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */]: 'The reCAPTCHA token is missing when sending request to the backend.',\n [\"invalid-recaptcha-token\" /* AuthErrorCode.INVALID_RECAPTCHA_TOKEN */]: 'The reCAPTCHA token is invalid when sending request to the backend.',\n [\"invalid-recaptcha-action\" /* AuthErrorCode.INVALID_RECAPTCHA_ACTION */]: 'The reCAPTCHA action is invalid when sending request to the backend.',\n [\"recaptcha-not-enabled\" /* AuthErrorCode.RECAPTCHA_NOT_ENABLED */]: 'reCAPTCHA Enterprise integration is not enabled for this project.',\n [\"missing-client-type\" /* AuthErrorCode.MISSING_CLIENT_TYPE */]: 'The reCAPTCHA client type is missing when sending request to the backend.',\n [\"missing-recaptcha-version\" /* AuthErrorCode.MISSING_RECAPTCHA_VERSION */]: 'The reCAPTCHA version is missing when sending request to the backend.',\n [\"invalid-req-type\" /* AuthErrorCode.INVALID_REQ_TYPE */]: 'Invalid request parameters.',\n [\"invalid-recaptcha-version\" /* AuthErrorCode.INVALID_RECAPTCHA_VERSION */]: 'The reCAPTCHA version is invalid when sending request to the backend.',\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.',\n [\"password-does-not-meet-requirements\" /* AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS */]: 'The password does not meet the requirements.',\n [\"invalid-hosting-link-domain\" /* AuthErrorCode.INVALID_HOSTING_LINK_DOMAIN */]: 'The provided Hosting link domain is not configured in Firebase Hosting or is not owned by ' +\n 'the current project. This cannot be a default Hosting domain (`web.app` or `firebaseapp.com`).'\n };\n}\nfunction _prodErrorMap() {\n // We will include this one message in the prod error map since by the very\n // nature of this error, developers will never be able to see the message\n // using the debugErrorMap (which is installed during auth initialization).\n return {\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 ' +\n 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +\n 'starting any other Firebase SDK.'\n };\n}\n/**\n * A verbose error map with detailed descriptions for most error codes.\n *\n * See discussion at {@link AuthErrorMap}\n *\n * @public\n */\nconst debugErrorMap = _debugErrorMap;\n/**\n * A minimal error map with all verbose error messages stripped.\n *\n * See discussion at {@link AuthErrorMap}\n *\n * @public\n */\nconst prodErrorMap = _prodErrorMap;\nconst _DEFAULT_AUTH_ERROR_FACTORY = new ErrorFactory('auth', 'Firebase', _prodErrorMap());\n/**\n * A map of potential `Auth` error codes, for easier comparison with errors\n * thrown by the SDK.\n *\n * @remarks\n * Note that you can't tree-shake individual keys\n * in the map, so by using the map you might substantially increase your\n * bundle size.\n *\n * @public\n */\nconst AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY = {\n ADMIN_ONLY_OPERATION: 'auth/admin-restricted-operation',\n ARGUMENT_ERROR: 'auth/argument-error',\n APP_NOT_AUTHORIZED: 'auth/app-not-authorized',\n APP_NOT_INSTALLED: 'auth/app-not-installed',\n CAPTCHA_CHECK_FAILED: 'auth/captcha-check-failed',\n CODE_EXPIRED: 'auth/code-expired',\n CORDOVA_NOT_READY: 'auth/cordova-not-ready',\n CORS_UNSUPPORTED: 'auth/cors-unsupported',\n CREDENTIAL_ALREADY_IN_USE: 'auth/credential-already-in-use',\n CREDENTIAL_MISMATCH: 'auth/custom-token-mismatch',\n CREDENTIAL_TOO_OLD_LOGIN_AGAIN: 'auth/requires-recent-login',\n DEPENDENT_SDK_INIT_BEFORE_AUTH: 'auth/dependent-sdk-initialized-before-auth',\n DYNAMIC_LINK_NOT_ACTIVATED: 'auth/dynamic-link-not-activated',\n EMAIL_CHANGE_NEEDS_VERIFICATION: 'auth/email-change-needs-verification',\n EMAIL_EXISTS: 'auth/email-already-in-use',\n EMULATOR_CONFIG_FAILED: 'auth/emulator-config-failed',\n EXPIRED_OOB_CODE: 'auth/expired-action-code',\n EXPIRED_POPUP_REQUEST: 'auth/cancelled-popup-request',\n INTERNAL_ERROR: 'auth/internal-error',\n INVALID_API_KEY: 'auth/invalid-api-key',\n INVALID_APP_CREDENTIAL: 'auth/invalid-app-credential',\n INVALID_APP_ID: 'auth/invalid-app-id',\n INVALID_AUTH: 'auth/invalid-user-token',\n INVALID_AUTH_EVENT: 'auth/invalid-auth-event',\n INVALID_CERT_HASH: 'auth/invalid-cert-hash',\n INVALID_CODE: 'auth/invalid-verification-code',\n INVALID_CONTINUE_URI: 'auth/invalid-continue-uri',\n INVALID_CORDOVA_CONFIGURATION: 'auth/invalid-cordova-configuration',\n INVALID_CUSTOM_TOKEN: 'auth/invalid-custom-token',\n INVALID_DYNAMIC_LINK_DOMAIN: 'auth/invalid-dynamic-link-domain',\n INVALID_EMAIL: 'auth/invalid-email',\n INVALID_EMULATOR_SCHEME: 'auth/invalid-emulator-scheme',\n INVALID_IDP_RESPONSE: 'auth/invalid-credential',\n INVALID_LOGIN_CREDENTIALS: 'auth/invalid-credential',\n INVALID_MESSAGE_PAYLOAD: 'auth/invalid-message-payload',\n INVALID_MFA_SESSION: 'auth/invalid-multi-factor-session',\n INVALID_OAUTH_CLIENT_ID: 'auth/invalid-oauth-client-id',\n INVALID_OAUTH_PROVIDER: 'auth/invalid-oauth-provider',\n INVALID_OOB_CODE: 'auth/invalid-action-code',\n INVALID_ORIGIN: 'auth/unauthorized-domain',\n INVALID_PASSWORD: 'auth/wrong-password',\n INVALID_PERSISTENCE: 'auth/invalid-persistence-type',\n INVALID_PHONE_NUMBER: 'auth/invalid-phone-number',\n INVALID_PROVIDER_ID: 'auth/invalid-provider-id',\n INVALID_RECIPIENT_EMAIL: 'auth/invalid-recipient-email',\n INVALID_SENDER: 'auth/invalid-sender',\n INVALID_SESSION_INFO: 'auth/invalid-verification-id',\n INVALID_TENANT_ID: 'auth/invalid-tenant-id',\n MFA_INFO_NOT_FOUND: 'auth/multi-factor-info-not-found',\n MFA_REQUIRED: 'auth/multi-factor-auth-required',\n MISSING_ANDROID_PACKAGE_NAME: 'auth/missing-android-pkg-name',\n MISSING_APP_CREDENTIAL: 'auth/missing-app-credential',\n MISSING_AUTH_DOMAIN: 'auth/auth-domain-config-required',\n MISSING_CODE: 'auth/missing-verification-code',\n MISSING_CONTINUE_URI: 'auth/missing-continue-uri',\n MISSING_IFRAME_START: 'auth/missing-iframe-start',\n MISSING_IOS_BUNDLE_ID: 'auth/missing-ios-bundle-id',\n MISSING_OR_INVALID_NONCE: 'auth/missing-or-invalid-nonce',\n MISSING_MFA_INFO: 'auth/missing-multi-factor-info',\n MISSING_MFA_SESSION: 'auth/missing-multi-factor-session',\n MISSING_PHONE_NUMBER: 'auth/missing-phone-number',\n MISSING_PASSWORD: 'auth/missing-password',\n MISSING_SESSION_INFO: 'auth/missing-verification-id',\n MODULE_DESTROYED: 'auth/app-deleted',\n NEED_CONFIRMATION: 'auth/account-exists-with-different-credential',\n NETWORK_REQUEST_FAILED: 'auth/network-request-failed',\n NULL_USER: 'auth/null-user',\n NO_AUTH_EVENT: 'auth/no-auth-event',\n NO_SUCH_PROVIDER: 'auth/no-such-provider',\n OPERATION_NOT_ALLOWED: 'auth/operation-not-allowed',\n OPERATION_NOT_SUPPORTED: 'auth/operation-not-supported-in-this-environment',\n POPUP_BLOCKED: 'auth/popup-blocked',\n POPUP_CLOSED_BY_USER: 'auth/popup-closed-by-user',\n PROVIDER_ALREADY_LINKED: 'auth/provider-already-linked',\n QUOTA_EXCEEDED: 'auth/quota-exceeded',\n REDIRECT_CANCELLED_BY_USER: 'auth/redirect-cancelled-by-user',\n REDIRECT_OPERATION_PENDING: 'auth/redirect-operation-pending',\n REJECTED_CREDENTIAL: 'auth/rejected-credential',\n SECOND_FACTOR_ALREADY_ENROLLED: 'auth/second-factor-already-in-use',\n SECOND_FACTOR_LIMIT_EXCEEDED: 'auth/maximum-second-factor-count-exceeded',\n TENANT_ID_MISMATCH: 'auth/tenant-id-mismatch',\n TIMEOUT: 'auth/timeout',\n TOKEN_EXPIRED: 'auth/user-token-expired',\n TOO_MANY_ATTEMPTS_TRY_LATER: 'auth/too-many-requests',\n UNAUTHORIZED_DOMAIN: 'auth/unauthorized-continue-uri',\n UNSUPPORTED_FIRST_FACTOR: 'auth/unsupported-first-factor',\n UNSUPPORTED_PERSISTENCE: 'auth/unsupported-persistence-type',\n UNSUPPORTED_TENANT_OPERATION: 'auth/unsupported-tenant-operation',\n UNVERIFIED_EMAIL: 'auth/unverified-email',\n USER_CANCELLED: 'auth/user-cancelled',\n USER_DELETED: 'auth/user-not-found',\n USER_DISABLED: 'auth/user-disabled',\n USER_MISMATCH: 'auth/user-mismatch',\n USER_SIGNED_OUT: 'auth/user-signed-out',\n WEAK_PASSWORD: 'auth/weak-password',\n WEB_STORAGE_UNSUPPORTED: 'auth/web-storage-unsupported',\n ALREADY_INITIALIZED: 'auth/already-initialized',\n RECAPTCHA_NOT_ENABLED: 'auth/recaptcha-not-enabled',\n MISSING_RECAPTCHA_TOKEN: 'auth/missing-recaptcha-token',\n INVALID_RECAPTCHA_TOKEN: 'auth/invalid-recaptcha-token',\n INVALID_RECAPTCHA_ACTION: 'auth/invalid-recaptcha-action',\n MISSING_CLIENT_TYPE: 'auth/missing-client-type',\n MISSING_RECAPTCHA_VERSION: 'auth/missing-recaptcha-version',\n INVALID_RECAPTCHA_VERSION: 'auth/invalid-recaptcha-version',\n INVALID_REQ_TYPE: 'auth/invalid-req-type',\n INVALID_HOSTING_LINK_DOMAIN: 'auth/invalid-hosting-link-domain'\n};\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst logClient = new Logger('@firebase/auth');\nfunction _logWarn(msg, ...args) {\n if (logClient.logLevel <= LogLevel.WARN) {\n logClient.warn(`Auth (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\nfunction _logError(msg, ...args) {\n if (logClient.logLevel <= LogLevel.ERROR) {\n logClient.error(`Auth (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nfunction _fail(authOrCode, ...rest) {\n throw createErrorInternal(authOrCode, ...rest);\n}\nfunction _createError(authOrCode, ...rest) {\n return createErrorInternal(authOrCode, ...rest);\n}\nfunction _errorWithCustomMessage(auth, code, message) {\n const errorMap = {\n ...prodErrorMap(),\n [code]: message\n };\n const factory = new ErrorFactory('auth', 'Firebase', errorMap);\n return factory.create(code, {\n appName: auth.name\n });\n}\nfunction _serverAppCurrentUserOperationNotSupportedError(auth) {\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');\n}\nfunction _assertInstanceOf(auth, object, instance) {\n const constructorInstance = instance;\n if (!(object instanceof constructorInstance)) {\n if (constructorInstance.name !== object.constructor.name) {\n _fail(auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\n }\n throw _errorWithCustomMessage(auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */, `Type of ${object.constructor.name} does not match expected instance.` +\n `Did you pass a reference from a different Auth SDK?`);\n }\n}\nfunction createErrorInternal(authOrCode, ...rest) {\n if (typeof authOrCode !== 'string') {\n const code = rest[0];\n const fullParams = [...rest.slice(1)];\n if (fullParams[0]) {\n fullParams[0].appName = authOrCode.name;\n }\n return authOrCode._errorFactory.create(code, ...fullParams);\n }\n return _DEFAULT_AUTH_ERROR_FACTORY.create(authOrCode, ...rest);\n}\nfunction _assert(assertion, authOrCode, ...rest) {\n if (!assertion) {\n throw createErrorInternal(authOrCode, ...rest);\n }\n}\n/**\n * Unconditionally fails, throwing an internal error with the given message.\n *\n * @param failure type of failure encountered\n * @throws Error\n */\nfunction debugFail(failure) {\n // Log the failure in addition to throw an exception, just in case the\n // exception is swallowed.\n const message = `INTERNAL ASSERTION FAILED: ` + failure;\n _logError(message);\n // NOTE: We don't use FirebaseError here because these are internal failures\n // that cannot be handled by the user. (Also it would create a circular\n // dependency between the error and assert modules which doesn't work.)\n throw new Error(message);\n}\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * @param assertion\n * @param message\n */\nfunction debugAssert(assertion, message) {\n if (!assertion) {\n debugFail(message);\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nfunction _getCurrentUrl() {\n return (typeof self !== 'undefined' && self.location?.href) || '';\n}\nfunction _isHttpOrHttps() {\n return _getCurrentScheme() === 'http:' || _getCurrentScheme() === 'https:';\n}\nfunction _getCurrentScheme() {\n return (typeof self !== 'undefined' && self.location?.protocol) || null;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Determine whether the browser is working online\n */\nfunction _isOnline() {\n if (typeof navigator !== 'undefined' &&\n navigator &&\n 'onLine' in navigator &&\n typeof navigator.onLine === 'boolean' &&\n // Apply only for traditional web apps and Chrome extensions.\n // This is especially true for Cordova apps which have unreliable\n // navigator.onLine behavior unless cordova-plugin-network-information is\n // installed which overwrites the native navigator.onLine value and\n // defines navigator.connection.\n (_isHttpOrHttps() || isBrowserExtension() || 'connection' in navigator)) {\n return navigator.onLine;\n }\n // If we can't determine the state, assume it is online.\n return true;\n}\nfunction _getUserLanguage() {\n if (typeof navigator === 'undefined') {\n return null;\n }\n const navigatorLanguage = navigator;\n return (\n // Most reliable, but only supported in Chrome/Firefox.\n (navigatorLanguage.languages && navigatorLanguage.languages[0]) ||\n // Supported in most browsers, but returns the language of the browser\n // UI, not the language set in browser settings.\n navigatorLanguage.language ||\n // Couldn't determine language.\n null);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A structure to help pick between a range of long and short delay durations\n * depending on the current environment. In general, the long delay is used for\n * mobile environments whereas short delays are used for desktop environments.\n */\nclass Delay {\n constructor(shortDelay, longDelay) {\n this.shortDelay = shortDelay;\n this.longDelay = longDelay;\n // Internal error when improperly initialized.\n debugAssert(longDelay > shortDelay, 'Short delay should be less than long delay!');\n this.isMobile = isMobileCordova() || isReactNative();\n }\n get() {\n if (!_isOnline()) {\n // Pick the shorter timeout.\n return Math.min(5000 /* DelayMin.OFFLINE */, this.shortDelay);\n }\n // If running in a mobile environment, return the long delay, otherwise\n // return the short delay.\n // This could be improved in the future to dynamically change based on other\n // variables instead of just reading the current environment.\n return this.isMobile ? this.longDelay : this.shortDelay;\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nfunction _emulatorUrl(config, path) {\n debugAssert(config.emulator, 'Emulator should always be set here');\n const { url } = config.emulator;\n if (!path) {\n return url;\n }\n return `${url}${path.startsWith('/') ? path.slice(1) : path}`;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass FetchProvider {\n static initialize(fetchImpl, headersImpl, responseImpl) {\n this.fetchImpl = fetchImpl;\n if (headersImpl) {\n this.headersImpl = headersImpl;\n }\n if (responseImpl) {\n this.responseImpl = responseImpl;\n }\n }\n static fetch() {\n if (this.fetchImpl) {\n return this.fetchImpl;\n }\n if (typeof self !== 'undefined' && 'fetch' in self) {\n return self.fetch;\n }\n if (typeof globalThis !== 'undefined' && globalThis.fetch) {\n return globalThis.fetch;\n }\n if (typeof fetch !== 'undefined') {\n return fetch;\n }\n debugFail('Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');\n }\n static headers() {\n if (this.headersImpl) {\n return this.headersImpl;\n }\n if (typeof self !== 'undefined' && 'Headers' in self) {\n return self.Headers;\n }\n if (typeof globalThis !== 'undefined' && globalThis.Headers) {\n return globalThis.Headers;\n }\n if (typeof Headers !== 'undefined') {\n return Headers;\n }\n debugFail('Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');\n }\n static response() {\n if (this.responseImpl) {\n return this.responseImpl;\n }\n if (typeof self !== 'undefined' && 'Response' in self) {\n return self.Response;\n }\n if (typeof globalThis !== 'undefined' && globalThis.Response) {\n return globalThis.Response;\n }\n if (typeof Response !== 'undefined') {\n return Response;\n }\n debugFail('Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Map from errors returned by the server to errors to developer visible errors\n */\nconst SERVER_ERROR_MAP = {\n // Custom token errors.\n [\"CREDENTIAL_MISMATCH\" /* ServerError.CREDENTIAL_MISMATCH */]: \"custom-token-mismatch\" /* AuthErrorCode.CREDENTIAL_MISMATCH */,\n // This can only happen if the SDK sends a bad request.\n [\"MISSING_CUSTOM_TOKEN\" /* ServerError.MISSING_CUSTOM_TOKEN */]: \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */,\n // Create Auth URI errors.\n [\"INVALID_IDENTIFIER\" /* ServerError.INVALID_IDENTIFIER */]: \"invalid-email\" /* AuthErrorCode.INVALID_EMAIL */,\n // This can only happen if the SDK sends a bad request.\n [\"MISSING_CONTINUE_URI\" /* ServerError.MISSING_CONTINUE_URI */]: \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */,\n // Sign in with email and password errors (some apply to sign up too).\n [\"INVALID_PASSWORD\" /* ServerError.INVALID_PASSWORD */]: \"wrong-password\" /* AuthErrorCode.INVALID_PASSWORD */,\n // This can only happen if the SDK sends a bad request.\n [\"MISSING_PASSWORD\" /* ServerError.MISSING_PASSWORD */]: \"missing-password\" /* AuthErrorCode.MISSING_PASSWORD */,\n // Thrown if Email Enumeration Protection is enabled in the project and the email or password is\n // invalid.\n [\"INVALID_LOGIN_CREDENTIALS\" /* ServerError.INVALID_LOGIN_CREDENTIALS */]: \"invalid-credential\" /* AuthErrorCode.INVALID_CREDENTIAL */,\n // Sign up with email and password errors.\n [\"EMAIL_EXISTS\" /* ServerError.EMAIL_EXISTS */]: \"email-already-in-use\" /* AuthErrorCode.EMAIL_EXISTS */,\n [\"PASSWORD_LOGIN_DISABLED\" /* ServerError.PASSWORD_LOGIN_DISABLED */]: \"operation-not-allowed\" /* AuthErrorCode.OPERATION_NOT_ALLOWED */,\n // Verify assertion for sign in with credential errors:\n [\"INVALID_IDP_RESPONSE\" /* ServerError.INVALID_IDP_RESPONSE */]: \"invalid-credential\" /* AuthErrorCode.INVALID_CREDENTIAL */,\n [\"INVALID_PENDING_TOKEN\" /* ServerError.INVALID_PENDING_TOKEN */]: \"invalid-credential\" /* AuthErrorCode.INVALID_CREDENTIAL */,\n [\"FEDERATED_USER_ID_ALREADY_LINKED\" /* ServerError.FEDERATED_USER_ID_ALREADY_LINKED */]: \"credential-already-in-use\" /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */,\n // This can only happen if the SDK sends a bad request.\n [\"MISSING_REQ_TYPE\" /* ServerError.MISSING_REQ_TYPE */]: \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */,\n // Send Password reset email errors:\n [\"EMAIL_NOT_FOUND\" /* ServerError.EMAIL_NOT_FOUND */]: \"user-not-found\" /* AuthErrorCode.USER_DELETED */,\n [\"RESET_PASSWORD_EXCEED_LIMIT\" /* ServerError.RESET_PASSWORD_EXCEED_LIMIT */]: \"too-many-requests\" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */,\n [\"EXPIRED_OOB_CODE\" /* ServerError.EXPIRED_OOB_CODE */]: \"expired-action-code\" /* AuthErrorCode.EXPIRED_OOB_CODE */,\n [\"INVALID_OOB_CODE\" /* ServerError.INVALID_OOB_CODE */]: \"invalid-action-code\" /* AuthErrorCode.INVALID_OOB_CODE */,\n // This can only happen if the SDK sends a bad request.\n [\"MISSING_OOB_CODE\" /* ServerError.MISSING_OOB_CODE */]: \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */,\n // Operations that require ID token in request:\n [\"CREDENTIAL_TOO_OLD_LOGIN_AGAIN\" /* ServerError.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */]: \"requires-recent-login\" /* AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */,\n [\"INVALID_ID_TOKEN\" /* ServerError.INVALID_ID_TOKEN */]: \"invalid-user-token\" /* AuthErrorCode.INVALID_AUTH */,\n [\"TOKEN_EXPIRED\" /* ServerError.TOKEN_EXPIRED */]: \"user-token-expired\" /* AuthErrorCode.TOKEN_EXPIRED */,\n [\"USER_NOT_FOUND\" /* ServerError.USER_NOT_FOUND */]: \"user-token-expired\" /* AuthErrorCode.TOKEN_EXPIRED */,\n // Other errors.\n [\"TOO_MANY_ATTEMPTS_TRY_LATER\" /* ServerError.TOO_MANY_ATTEMPTS_TRY_LATER */]: \"too-many-requests\" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */,\n [\"PASSWORD_DOES_NOT_MEET_REQUIREMENTS\" /* ServerError.PASSWORD_DOES_NOT_MEET_REQUIREMENTS */]: \"password-does-not-meet-requirements\" /* AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS */,\n // Phone Auth related errors.\n [\"INVALID_CODE\" /* ServerError.INVALID_CODE */]: \"invalid-verification-code\" /* AuthErrorCode.INVALID_CODE */,\n [\"INVALID_SESSION_INFO\" /* ServerError.INVALID_SESSION_INFO */]: \"invalid-verification-id\" /* AuthErrorCode.INVALID_SESSION_INFO */,\n [\"INVALID_TEMPORARY_PROOF\" /* ServerError.INVALID_TEMPORARY_PROOF */]: \"invalid-credential\" /* AuthErrorCode.INVALID_CREDENTIAL */,\n [\"MISSING_SESSION_INFO\" /* ServerError.MISSING_SESSION_INFO */]: \"missing-verification-id\" /* AuthErrorCode.MISSING_SESSION_INFO */,\n [\"SESSION_EXPIRED\" /* ServerError.SESSION_EXPIRED */]: \"code-expired\" /* AuthErrorCode.CODE_EXPIRED */,\n // Other action code errors when additional settings passed.\n // MISSING_CONTINUE_URI is getting mapped to INTERNAL_ERROR above.\n // This is OK as this error will be caught by client side validation.\n [\"MISSING_ANDROID_PACKAGE_NAME\" /* ServerError.MISSING_ANDROID_PACKAGE_NAME */]: \"missing-android-pkg-name\" /* AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME */,\n [\"UNAUTHORIZED_DOMAIN\" /* ServerError.UNAUTHORIZED_DOMAIN */]: \"unauthorized-continue-uri\" /* AuthErrorCode.UNAUTHORIZED_DOMAIN */,\n // getProjectConfig errors when clientId is passed.\n [\"INVALID_OAUTH_CLIENT_ID\" /* ServerError.INVALID_OAUTH_CLIENT_ID */]: \"invalid-oauth-client-id\" /* AuthErrorCode.INVALID_OAUTH_CLIENT_ID */,\n // User actions (sign-up or deletion) disabled errors.\n [\"ADMIN_ONLY_OPERATION\" /* ServerError.ADMIN_ONLY_OPERATION */]: \"admin-restricted-operation\" /* AuthErrorCode.ADMIN_ONLY_OPERATION */,\n // Multi factor related errors.\n [\"INVALID_MFA_PENDING_CREDENTIAL\" /* ServerError.INVALID_MFA_PENDING_CREDENTIAL */]: \"invalid-multi-factor-session\" /* AuthErrorCode.INVALID_MFA_SESSION */,\n [\"MFA_ENROLLMENT_NOT_FOUND\" /* ServerError.MFA_ENROLLMENT_NOT_FOUND */]: \"multi-factor-info-not-found\" /* AuthErrorCode.MFA_INFO_NOT_FOUND */,\n [\"MISSING_MFA_ENROLLMENT_ID\" /* ServerError.MISSING_MFA_ENROLLMENT_ID */]: \"missing-multi-factor-info\" /* AuthErrorCode.MISSING_MFA_INFO */,\n [\"MISSING_MFA_PENDING_CREDENTIAL\" /* ServerError.MISSING_MFA_PENDING_CREDENTIAL */]: \"missing-multi-factor-session\" /* AuthErrorCode.MISSING_MFA_SESSION */,\n [\"SECOND_FACTOR_EXISTS\" /* ServerError.SECOND_FACTOR_EXISTS */]: \"second-factor-already-in-use\" /* AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED */,\n [\"SECOND_FACTOR_LIMIT_EXCEEDED\" /* ServerError.SECOND_FACTOR_LIMIT_EXCEEDED */]: \"maximum-second-factor-count-exceeded\" /* AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED */,\n // Blocking functions related errors.\n [\"BLOCKING_FUNCTION_ERROR_RESPONSE\" /* ServerError.BLOCKING_FUNCTION_ERROR_RESPONSE */]: \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */,\n // Recaptcha related errors.\n [\"RECAPTCHA_NOT_ENABLED\" /* ServerError.RECAPTCHA_NOT_ENABLED */]: \"recaptcha-not-enabled\" /* AuthErrorCode.RECAPTCHA_NOT_ENABLED */,\n [\"MISSING_RECAPTCHA_TOKEN\" /* ServerError.MISSING_RECAPTCHA_TOKEN */]: \"missing-recaptcha-token\" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */,\n [\"INVALID_RECAPTCHA_TOKEN\" /* ServerError.INVALID_RECAPTCHA_TOKEN */]: \"invalid-recaptcha-token\" /* AuthErrorCode.INVALID_RECAPTCHA_TOKEN */,\n [\"INVALID_RECAPTCHA_ACTION\" /* ServerError.INVALID_RECAPTCHA_ACTION */]: \"invalid-recaptcha-action\" /* AuthErrorCode.INVALID_RECAPTCHA_ACTION */,\n [\"MISSING_CLIENT_TYPE\" /* ServerError.MISSING_CLIENT_TYPE */]: \"missing-client-type\" /* AuthErrorCode.MISSING_CLIENT_TYPE */,\n [\"MISSING_RECAPTCHA_VERSION\" /* ServerError.MISSING_RECAPTCHA_VERSION */]: \"missing-recaptcha-version\" /* AuthErrorCode.MISSING_RECAPTCHA_VERSION */,\n [\"INVALID_RECAPTCHA_VERSION\" /* ServerError.INVALID_RECAPTCHA_VERSION */]: \"invalid-recaptcha-version\" /* AuthErrorCode.INVALID_RECAPTCHA_VERSION */,\n [\"INVALID_REQ_TYPE\" /* ServerError.INVALID_REQ_TYPE */]: \"invalid-req-type\" /* AuthErrorCode.INVALID_REQ_TYPE */\n};\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst CookieAuthProxiedEndpoints = [\n \"/v1/accounts:signInWithCustomToken\" /* Endpoint.SIGN_IN_WITH_CUSTOM_TOKEN */,\n \"/v1/accounts:signInWithEmailLink\" /* Endpoint.SIGN_IN_WITH_EMAIL_LINK */,\n \"/v1/accounts:signInWithIdp\" /* Endpoint.SIGN_IN_WITH_IDP */,\n \"/v1/accounts:signInWithPassword\" /* Endpoint.SIGN_IN_WITH_PASSWORD */,\n \"/v1/accounts:signInWithPhoneNumber\" /* Endpoint.SIGN_IN_WITH_PHONE_NUMBER */,\n \"/v1/token\" /* Endpoint.TOKEN */\n];\nconst DEFAULT_API_TIMEOUT_MS = new Delay(30000, 60000);\nfunction _addTidIfNecessary(auth, request) {\n if (auth.tenantId && !request.tenantId) {\n return {\n ...request,\n tenantId: auth.tenantId\n };\n }\n return request;\n}\nasync function _performApiRequest(auth, method, path, request, customErrorMap = {}) {\n return _performFetchWithErrorHandling(auth, customErrorMap, async () => {\n let body = {};\n let params = {};\n if (request) {\n if (method === \"GET\" /* HttpMethod.GET */) {\n params = request;\n }\n else {\n body = {\n body: JSON.stringify(request)\n };\n }\n }\n const query = querystring({\n ...params,\n key: auth.config.apiKey\n }).slice(1);\n const headers = await auth._getAdditionalHeaders();\n headers[\"Content-Type\" /* HttpHeader.CONTENT_TYPE */] = 'application/json';\n if (auth.languageCode) {\n headers[\"X-Firebase-Locale\" /* HttpHeader.X_FIREBASE_LOCALE */] = auth.languageCode;\n }\n const fetchArgs = {\n method,\n headers,\n ...body\n };\n /* Security-conscious server-side frameworks tend to have built in mitigations for referrer\n problems\". See the Cloudflare GitHub issue #487: Error: The 'referrerPolicy' field on\n 'RequestInitializerDict' is not implemented.\"\n https://github.com/cloudflare/next-on-pages/issues/487 */\n if (!isCloudflareWorker()) {\n fetchArgs.referrerPolicy = 'strict-origin-when-cross-origin';\n }\n if (auth.emulatorConfig && isCloudWorkstation(auth.emulatorConfig.host)) {\n fetchArgs.credentials = 'include';\n }\n return FetchProvider.fetch()(await _getFinalTarget(auth, auth.config.apiHost, path, query), fetchArgs);\n });\n}\nasync function _performFetchWithErrorHandling(auth, customErrorMap, fetchFn) {\n auth._canInitEmulator = false;\n const errorMap = { ...SERVER_ERROR_MAP, ...customErrorMap };\n try {\n const networkTimeout = new NetworkTimeout(auth);\n const response = await Promise.race([\n fetchFn(),\n networkTimeout.promise\n ]);\n // If we've reached this point, the fetch succeeded and the networkTimeout\n // didn't throw; clear the network timeout delay so that Node won't hang\n networkTimeout.clearNetworkTimeout();\n const json = await response.json();\n if ('needConfirmation' in json) {\n throw _makeTaggedError(auth, \"account-exists-with-different-credential\" /* AuthErrorCode.NEED_CONFIRMATION */, json);\n }\n if (response.ok && !('errorMessage' in json)) {\n return json;\n }\n else {\n const errorMessage = response.ok ? json.errorMessage : json.error.message;\n const [serverErrorCode, serverErrorMessage] = errorMessage.split(' : ');\n if (serverErrorCode === \"FEDERATED_USER_ID_ALREADY_LINKED\" /* ServerError.FEDERATED_USER_ID_ALREADY_LINKED */) {\n throw _makeTaggedError(auth, \"credential-already-in-use\" /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */, json);\n }\n else if (serverErrorCode === \"EMAIL_EXISTS\" /* ServerError.EMAIL_EXISTS */) {\n throw _makeTaggedError(auth, \"email-already-in-use\" /* AuthErrorCode.EMAIL_EXISTS */, json);\n }\n else if (serverErrorCode === \"USER_DISABLED\" /* ServerError.USER_DISABLED */) {\n throw _makeTaggedError(auth, \"user-disabled\" /* AuthErrorCode.USER_DISABLED */, json);\n }\n const authError = errorMap[serverErrorCode] ||\n serverErrorCode\n .toLowerCase()\n .replace(/[_\\s]+/g, '-');\n if (serverErrorMessage) {\n throw _errorWithCustomMessage(auth, authError, serverErrorMessage);\n }\n else {\n _fail(auth, authError);\n }\n }\n }\n catch (e) {\n if (e instanceof FirebaseError) {\n throw e;\n }\n // Changing this to a different error code will log user out when there is a network error\n // because we treat any error other than NETWORK_REQUEST_FAILED as token is invalid.\n // https://github.com/firebase/firebase-js-sdk/blob/4fbc73610d70be4e0852e7de63a39cb7897e8546/packages/auth/src/core/auth/auth_impl.ts#L309-L316\n _fail(auth, \"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */, { 'message': String(e) });\n }\n}\nasync function _performSignInRequest(auth, method, path, request, customErrorMap = {}) {\n const serverResponse = await _performApiRequest(auth, method, path, request, customErrorMap);\n if ('mfaPendingCredential' in serverResponse) {\n _fail(auth, \"multi-factor-auth-required\" /* AuthErrorCode.MFA_REQUIRED */, {\n _serverResponse: serverResponse\n });\n }\n return serverResponse;\n}\nasync function _getFinalTarget(auth, host, path, query) {\n const base = `${host}${path}?${query}`;\n const authInternal = auth;\n const finalTarget = authInternal.config.emulator\n ? _emulatorUrl(auth.config, base)\n : `${auth.config.apiScheme}://${base}`;\n // Cookie auth works by MiTMing the signIn and token endpoints from the developer's backend,\n // saving the idToken and refreshToken into cookies, and then redacting the refreshToken\n // from the response\n if (CookieAuthProxiedEndpoints.includes(path)) {\n // Persistence manager is async, we need to await it. We can't just wait for auth initialized\n // here since auth initialization calls this function.\n await authInternal._persistenceManagerAvailable;\n if (authInternal._getPersistenceType() === \"COOKIE\" /* PersistenceType.COOKIE */) {\n const cookiePersistence = authInternal._getPersistence();\n return cookiePersistence._getFinalTarget(finalTarget).toString();\n }\n }\n return finalTarget;\n}\nfunction _parseEnforcementState(enforcementStateStr) {\n switch (enforcementStateStr) {\n case 'ENFORCE':\n return \"ENFORCE\" /* EnforcementState.ENFORCE */;\n case 'AUDIT':\n return \"AUDIT\" /* EnforcementState.AUDIT */;\n case 'OFF':\n return \"OFF\" /* EnforcementState.OFF */;\n default:\n return \"ENFORCEMENT_STATE_UNSPECIFIED\" /* EnforcementState.ENFORCEMENT_STATE_UNSPECIFIED */;\n }\n}\nclass NetworkTimeout {\n clearNetworkTimeout() {\n clearTimeout(this.timer);\n }\n constructor(auth) {\n this.auth = auth;\n // Node timers and browser timers are fundamentally incompatible, but we\n // don't care about the value here\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this.timer = null;\n this.promise = new Promise((_, reject) => {\n this.timer = setTimeout(() => {\n return reject(_createError(this.auth, \"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));\n }, DEFAULT_API_TIMEOUT_MS.get());\n });\n }\n}\nfunction _makeTaggedError(auth, code, response) {\n const errorParams = {\n appName: auth.name\n };\n if (response.email) {\n errorParams.email = response.email;\n }\n if (response.phoneNumber) {\n errorParams.phoneNumber = response.phoneNumber;\n }\n const error = _createError(auth, code, errorParams);\n // We know customData is defined on error because errorParams is defined\n error.customData._tokenResponse = response;\n return error;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nfunction isV2(grecaptcha) {\n return (grecaptcha !== undefined &&\n grecaptcha.getResponse !== undefined);\n}\nfunction isEnterprise(grecaptcha) {\n return (grecaptcha !== undefined &&\n grecaptcha.enterprise !== undefined);\n}\nclass RecaptchaConfig {\n constructor(response) {\n /**\n * The reCAPTCHA site key.\n */\n this.siteKey = '';\n /**\n * The list of providers and their enablement status for reCAPTCHA Enterprise.\n */\n this.recaptchaEnforcementState = [];\n if (response.recaptchaKey === undefined) {\n throw new Error('recaptchaKey undefined');\n }\n // Example response.recaptchaKey: \"projects/proj123/keys/sitekey123\"\n this.siteKey = response.recaptchaKey.split('/')[3];\n this.recaptchaEnforcementState = response.recaptchaEnforcementState;\n }\n /**\n * Returns the reCAPTCHA Enterprise enforcement state for the given provider.\n *\n * @param providerStr - The provider whose enforcement state is to be returned.\n * @returns The reCAPTCHA Enterprise enforcement state for the given provider.\n */\n getProviderEnforcementState(providerStr) {\n if (!this.recaptchaEnforcementState ||\n this.recaptchaEnforcementState.length === 0) {\n return null;\n }\n for (const recaptchaEnforcementState of this.recaptchaEnforcementState) {\n if (recaptchaEnforcementState.provider &&\n recaptchaEnforcementState.provider === providerStr) {\n return _parseEnforcementState(recaptchaEnforcementState.enforcementState);\n }\n }\n return null;\n }\n /**\n * Returns true if the reCAPTCHA Enterprise enforcement state for the provider is set to ENFORCE or AUDIT.\n *\n * @param providerStr - The provider whose enablement state is to be returned.\n * @returns Whether or not reCAPTCHA Enterprise protection is enabled for the given provider.\n */\n isProviderEnabled(providerStr) {\n return (this.getProviderEnforcementState(providerStr) ===\n \"ENFORCE\" /* EnforcementState.ENFORCE */ ||\n this.getProviderEnforcementState(providerStr) === \"AUDIT\" /* EnforcementState.AUDIT */);\n }\n /**\n * Returns true if reCAPTCHA Enterprise protection is enabled in at least one provider, otherwise\n * returns false.\n *\n * @returns Whether or not reCAPTCHA Enterprise protection is enabled for at least one provider.\n */\n isAnyProviderEnabled() {\n return (this.isProviderEnabled(\"EMAIL_PASSWORD_PROVIDER\" /* RecaptchaAuthProvider.EMAIL_PASSWORD_PROVIDER */) ||\n this.isProviderEnabled(\"PHONE_PROVIDER\" /* RecaptchaAuthProvider.PHONE_PROVIDER */));\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nasync function getRecaptchaParams(auth) {\n return ((await _performApiRequest(auth, \"GET\" /* HttpMethod.GET */, \"/v1/recaptchaParams\" /* Endpoint.GET_RECAPTCHA_PARAM */)).recaptchaSiteKey || '');\n}\nasync function getRecaptchaConfig(auth, request) {\n return _performApiRequest(auth, \"GET\" /* HttpMethod.GET */, \"/v2/recaptchaConfig\" /* Endpoint.GET_RECAPTCHA_CONFIG */, _addTidIfNecessary(auth, request));\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nasync function deleteAccount(auth, request) {\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:delete\" /* Endpoint.DELETE_ACCOUNT */, request);\n}\nasync function deleteLinkedAccounts(auth, request) {\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:update\" /* Endpoint.SET_ACCOUNT_INFO */, request);\n}\nasync function getAccountInfo(auth, request) {\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:lookup\" /* Endpoint.GET_ACCOUNT_INFO */, request);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nfunction utcTimestampToDateString(utcTimestamp) {\n if (!utcTimestamp) {\n return undefined;\n }\n try {\n // Convert to date object.\n const date = new Date(Number(utcTimestamp));\n // Test date is valid.\n if (!isNaN(date.getTime())) {\n // Convert to UTC date string.\n return date.toUTCString();\n }\n }\n catch (e) {\n // Do nothing. undefined will be returned.\n }\n return undefined;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Returns a JSON Web Token (JWT) used to identify the user to a Firebase service.\n *\n * @remarks\n * Returns the current token if it has not expired or if it will not expire in the next five\n * minutes. Otherwise, this will refresh the token and return a new one.\n *\n * @param user - The user.\n * @param forceRefresh - Force refresh regardless of token expiration.\n *\n * @public\n */\nfunction getIdToken(user, forceRefresh = false) {\n return getModularInstance(user).getIdToken(forceRefresh);\n}\n/**\n * Returns a deserialized JSON Web Token (JWT) used to identify the user to a Firebase service.\n *\n * @remarks\n * Returns the current token if it has not expired or if it will not expire in the next five\n * minutes. Otherwise, this will refresh the token and return a new one.\n *\n * @param user - The user.\n * @param forceRefresh - Force refresh regardless of token expiration.\n *\n * @public\n */\nasync function getIdTokenResult(user, forceRefresh = false) {\n const userInternal = getModularInstance(user);\n const token = await userInternal.getIdToken(forceRefresh);\n const claims = _parseToken(token);\n _assert(claims && claims.exp && claims.auth_time && claims.iat, userInternal.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n const firebase = typeof claims.firebase === 'object' ? claims.firebase : undefined;\n const signInProvider = firebase?.['sign_in_provider'];\n return {\n claims,\n token,\n authTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.auth_time)),\n issuedAtTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.iat)),\n expirationTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.exp)),\n signInProvider: signInProvider || null,\n signInSecondFactor: firebase?.['sign_in_second_factor'] || null\n };\n}\nfunction secondsStringToMilliseconds(seconds) {\n return Number(seconds) * 1000;\n}\nfunction _parseToken(token) {\n const [algorithm, payload, signature] = token.split('.');\n if (algorithm === undefined ||\n payload === undefined ||\n signature === undefined) {\n _logError('JWT malformed, contained fewer than 3 sections');\n return null;\n }\n try {\n const decoded = base64Decode(payload);\n if (!decoded) {\n _logError('Failed to decode base64 JWT payload');\n return null;\n }\n return JSON.parse(decoded);\n }\n catch (e) {\n _logError('Caught error parsing JWT payload as JSON', e?.toString());\n return null;\n }\n}\n/**\n * Extract expiresIn TTL from a token by subtracting the expiration from the issuance.\n */\nfunction _tokenExpiresIn(token) {\n const parsedToken = _parseToken(token);\n _assert(parsedToken, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n _assert(typeof parsedToken.exp !== 'undefined', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n _assert(typeof parsedToken.iat !== 'undefined', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n return Number(parsedToken.exp) - Number(parsedToken.iat);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nasync function _logoutIfInvalidated(user, promise, bypassAuthState = false) {\n if (bypassAuthState) {\n return promise;\n }\n try {\n return await promise;\n }\n catch (e) {\n if (e instanceof FirebaseError && isUserInvalidated(e)) {\n if (user.auth.currentUser === user) {\n await user.auth.signOut();\n }\n }\n throw e;\n }\n}\nfunction isUserInvalidated({ code }) {\n return (code === `auth/${\"user-disabled\" /* AuthErrorCode.USER_DISABLED */}` ||\n code === `auth/${\"user-token-expired\" /* AuthErrorCode.TOKEN_EXPIRED */}`);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass ProactiveRefresh {\n constructor(user) {\n this.user = user;\n this.isRunning = false;\n // Node timers and browser timers return fundamentally different types.\n // We don't actually care what the value is but TS won't accept unknown and\n // we can't cast properly in both environments.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this.timerId = null;\n this.errorBackoff = 30000 /* Duration.RETRY_BACKOFF_MIN */;\n }\n _start() {\n if (this.isRunning) {\n return;\n }\n this.isRunning = true;\n this.schedule();\n }\n _stop() {\n if (!this.isRunning) {\n return;\n }\n this.isRunning = false;\n if (this.timerId !== null) {\n clearTimeout(this.timerId);\n }\n }\n getInterval(wasError) {\n if (wasError) {\n const interval = this.errorBackoff;\n this.errorBackoff = Math.min(this.errorBackoff * 2, 960000 /* Duration.RETRY_BACKOFF_MAX */);\n return interval;\n }\n else {\n // Reset the error backoff\n this.errorBackoff = 30000 /* Duration.RETRY_BACKOFF_MIN */;\n const expTime = this.user.stsTokenManager.expirationTime ?? 0;\n const interval = expTime - Date.now() - 300000 /* Duration.OFFSET */;\n return Math.max(0, interval);\n }\n }\n schedule(wasError = false) {\n if (!this.isRunning) {\n // Just in case...\n return;\n }\n const interval = this.getInterval(wasError);\n this.timerId = setTimeout(async () => {\n await this.iteration();\n }, interval);\n }\n async iteration() {\n try {\n await this.user.getIdToken(true);\n }\n catch (e) {\n // Only retry on network errors\n if (e?.code ===\n `auth/${\"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */}`) {\n this.schedule(/* wasError */ true);\n }\n return;\n }\n this.schedule();\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass UserMetadata {\n constructor(createdAt, lastLoginAt) {\n this.createdAt = createdAt;\n this.lastLoginAt = lastLoginAt;\n this._initializeTime();\n }\n _initializeTime() {\n this.lastSignInTime = utcTimestampToDateString(this.lastLoginAt);\n this.creationTime = utcTimestampToDateString(this.createdAt);\n }\n _copy(metadata) {\n this.createdAt = metadata.createdAt;\n this.lastLoginAt = metadata.lastLoginAt;\n this._initializeTime();\n }\n toJSON() {\n return {\n createdAt: this.createdAt,\n lastLoginAt: this.lastLoginAt\n };\n }\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nasync function _reloadWithoutSaving(user) {\n const auth = user.auth;\n const idToken = await user.getIdToken();\n const response = await _logoutIfInvalidated(user, getAccountInfo(auth, { idToken }));\n _assert(response?.users.length, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n const coreAccount = response.users[0];\n user._notifyReloadListener(coreAccount);\n const newProviderData = coreAccount.providerUserInfo?.length\n ? extractProviderData(coreAccount.providerUserInfo)\n : [];\n const providerData = mergeProviderData(user.providerData, newProviderData);\n // Preserves the non-nonymous status of the stored user, even if no more\n // credentials (federated or email/password) are linked to the user. If\n // the user was previously anonymous, then use provider data to update.\n // On the other hand, if it was not anonymous before, it should never be\n // considered anonymous now.\n const oldIsAnonymous = user.isAnonymous;\n const newIsAnonymous = !(user.email && coreAccount.passwordHash) && !providerData?.length;\n const isAnonymous = !oldIsAnonymous ? false : newIsAnonymous;\n const updates = {\n uid: coreAccount.localId,\n displayName: coreAccount.displayName || null,\n photoURL: coreAccount.photoUrl || null,\n email: coreAccount.email || null,\n emailVerified: coreAccount.emailVerified || false,\n phoneNumber: coreAccount.phoneNumber || null,\n tenantId: coreAccount.tenantId || null,\n providerData,\n metadata: new UserMetadata(coreAccount.createdAt, coreAccount.lastLoginAt),\n isAnonymous\n };\n Object.assign(user, updates);\n}\n/**\n * Reloads user account data, if signed in.\n *\n * @param user - The user.\n *\n * @public\n */\nasync function reload(user) {\n const userInternal = getModularInstance(user);\n await _reloadWithoutSaving(userInternal);\n // Even though the current user hasn't changed, update\n // current user will trigger a persistence update w/ the\n // new info.\n await userInternal.auth._persistUserIfCurrent(userInternal);\n userInternal.auth._notifyListenersIfCurrent(userInternal);\n}\nfunction mergeProviderData(original, newData) {\n const deduped = original.filter(o => !newData.some(n => n.providerId === o.providerId));\n return [...deduped, ...newData];\n}\nfunction extractProviderData(providers) {\n return providers.map(({ providerId, ...provider }) => {\n return {\n providerId,\n uid: provider.rawId || '',\n displayName: provider.displayName || null,\n email: provider.email || null,\n phoneNumber: provider.phoneNumber || null,\n photoURL: provider.photoUrl || null\n };\n });\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/* eslint-disable camelcase */\nasync function requestStsToken(auth, refreshToken) {\n const response = await _performFetchWithErrorHandling(auth, {}, async () => {\n const body = querystring({\n 'grant_type': 'refresh_token',\n 'refresh_token': refreshToken\n }).slice(1);\n const { tokenApiHost, apiKey } = auth.config;\n const url = await _getFinalTarget(auth, tokenApiHost, \"/v1/token\" /* Endpoint.TOKEN */, `key=${apiKey}`);\n const headers = await auth._getAdditionalHeaders();\n headers[\"Content-Type\" /* HttpHeader.CONTENT_TYPE */] = 'application/x-www-form-urlencoded';\n const options = {\n method: \"POST\" /* HttpMethod.POST */,\n headers,\n body\n };\n if (auth.emulatorConfig &&\n isCloudWorkstation(auth.emulatorConfig.host)) {\n options.credentials = 'include';\n }\n return FetchProvider.fetch()(url, options);\n });\n // The response comes back in snake_case. Convert to camel:\n return {\n accessToken: response.access_token,\n expiresIn: response.expires_in,\n refreshToken: response.refresh_token\n };\n}\nasync function revokeToken(auth, request) {\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts:revokeToken\" /* Endpoint.REVOKE_TOKEN */, _addTidIfNecessary(auth, request));\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * We need to mark this class as internal explicitly to exclude it in the public typings, because\n * it references AuthInternal which has a circular dependency with UserInternal.\n *\n * @internal\n */\nclass StsTokenManager {\n constructor() {\n this.refreshToken = null;\n this.accessToken = null;\n this.expirationTime = null;\n }\n get isExpired() {\n return (!this.expirationTime ||\n Date.now() > this.expirationTime - 30000 /* Buffer.TOKEN_REFRESH */);\n }\n updateFromServerResponse(response) {\n _assert(response.idToken, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n _assert(typeof response.idToken !== 'undefined', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n _assert(typeof response.refreshToken !== 'undefined', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n const expiresIn = 'expiresIn' in response && typeof response.expiresIn !== 'undefined'\n ? Number(response.expiresIn)\n : _tokenExpiresIn(response.idToken);\n this.updateTokensAndExpiration(response.idToken, response.refreshToken, expiresIn);\n }\n updateFromIdToken(idToken) {\n _assert(idToken.length !== 0, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n const expiresIn = _tokenExpiresIn(idToken);\n this.updateTokensAndExpiration(idToken, null, expiresIn);\n }\n async getToken(auth, forceRefresh = false) {\n if (!forceRefresh && this.accessToken && !this.isExpired) {\n return this.accessToken;\n }\n _assert(this.refreshToken, auth, \"user-token-expired\" /* AuthErrorCode.TOKEN_EXPIRED */);\n if (this.refreshToken) {\n await this.refresh(auth, this.refreshToken);\n return this.accessToken;\n }\n return null;\n }\n clearRefreshToken() {\n this.refreshToken = null;\n }\n async refresh(auth, oldToken) {\n const { accessToken, refreshToken, expiresIn } = await requestStsToken(auth, oldToken);\n this.updateTokensAndExpiration(accessToken, refreshToken, Number(expiresIn));\n }\n updateTokensAndExpiration(accessToken, refreshToken, expiresInSec) {\n this.refreshToken = refreshToken || null;\n this.accessToken = accessToken || null;\n this.expirationTime = Date.now() + expiresInSec * 1000;\n }\n static fromJSON(appName, object) {\n const { refreshToken, accessToken, expirationTime } = object;\n const manager = new StsTokenManager();\n if (refreshToken) {\n _assert(typeof refreshToken === 'string', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */, {\n appName\n });\n manager.refreshToken = refreshToken;\n }\n if (accessToken) {\n _assert(typeof accessToken === 'string', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */, {\n appName\n });\n manager.accessToken = accessToken;\n }\n if (expirationTime) {\n _assert(typeof expirationTime === 'number', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */, {\n appName\n });\n manager.expirationTime = expirationTime;\n }\n return manager;\n }\n toJSON() {\n return {\n refreshToken: this.refreshToken,\n accessToken: this.accessToken,\n expirationTime: this.expirationTime\n };\n }\n _assign(stsTokenManager) {\n this.accessToken = stsTokenManager.accessToken;\n this.refreshToken = stsTokenManager.refreshToken;\n this.expirationTime = stsTokenManager.expirationTime;\n }\n _clone() {\n return Object.assign(new StsTokenManager(), this.toJSON());\n }\n _performRefresh() {\n return debugFail('not implemented');\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nfunction assertStringOrUndefined(assertion, appName) {\n _assert(typeof assertion === 'string' || typeof assertion === 'undefined', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */, { appName });\n}\nclass UserImpl {\n constructor({ uid, auth, stsTokenManager, ...opt }) {\n // For the user object, provider is always Firebase.\n this.providerId = \"firebase\" /* ProviderId.FIREBASE */;\n this.proactiveRefresh = new ProactiveRefresh(this);\n this.reloadUserInfo = null;\n this.reloadListener = null;\n this.uid = uid;\n this.auth = auth;\n this.stsTokenManager = stsTokenManager;\n this.accessToken = stsTokenManager.accessToken;\n this.displayName = opt.displayName || null;\n this.email = opt.email || null;\n this.emailVerified = opt.emailVerified || false;\n this.phoneNumber = opt.phoneNumber || null;\n this.photoURL = opt.photoURL || null;\n this.isAnonymous = opt.isAnonymous || false;\n this.tenantId = opt.tenantId || null;\n this.providerData = opt.providerData ? [...opt.providerData] : [];\n this.metadata = new UserMetadata(opt.createdAt || undefined, opt.lastLoginAt || undefined);\n }\n async getIdToken(forceRefresh) {\n const accessToken = await _logoutIfInvalidated(this, this.stsTokenManager.getToken(this.auth, forceRefresh));\n _assert(accessToken, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n if (this.accessToken !== accessToken) {\n this.accessToken = accessToken;\n await this.auth._persistUserIfCurrent(this);\n this.auth._notifyListenersIfCurrent(this);\n }\n return accessToken;\n }\n getIdTokenResult(forceRefresh) {\n return getIdTokenResult(this, forceRefresh);\n }\n reload() {\n return reload(this);\n }\n _assign(user) {\n if (this === user) {\n return;\n }\n _assert(this.uid === user.uid, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n this.displayName = user.displayName;\n this.photoURL = user.photoURL;\n this.email = user.email;\n this.emailVerified = user.emailVerified;\n this.phoneNumber = user.phoneNumber;\n this.isAnonymous = user.isAnonymous;\n this.tenantId = user.tenantId;\n this.providerData = user.providerData.map(userInfo => ({ ...userInfo }));\n this.metadata._copy(user.metadata);\n this.stsTokenManager._assign(user.stsTokenManager);\n }\n _clone(auth) {\n const newUser = new UserImpl({\n ...this,\n auth,\n stsTokenManager: this.stsTokenManager._clone()\n });\n newUser.metadata._copy(this.metadata);\n return newUser;\n }\n _onReload(callback) {\n // There should only ever be one listener, and that is a single instance of MultiFactorUser\n _assert(!this.reloadListener, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n this.reloadListener = callback;\n if (this.reloadUserInfo) {\n this._notifyReloadListener(this.reloadUserInfo);\n this.reloadUserInfo = null;\n }\n }\n _notifyReloadListener(userInfo) {\n if (this.reloadListener) {\n this.reloadListener(userInfo);\n }\n else {\n // If no listener is subscribed yet, save the result so it's available when they do subscribe\n this.reloadUserInfo = userInfo;\n }\n }\n _startProactiveRefresh() {\n this.proactiveRefresh._start();\n }\n _stopProactiveRefresh() {\n this.proactiveRefresh._stop();\n }\n async _updateTokensIfNecessary(response, reload = false) {\n let tokensRefreshed = false;\n if (response.idToken &&\n response.idToken !== this.stsTokenManager.accessToken) {\n this.stsTokenManager.updateFromServerResponse(response);\n tokensRefreshed = true;\n }\n if (reload) {\n await _reloadWithoutSaving(this);\n }\n await this.auth._persistUserIfCurrent(this);\n if (tokensRefreshed) {\n this.auth._notifyListenersIfCurrent(this);\n }\n }\n async delete() {\n if (_isFirebaseServerApp(this.auth.app)) {\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this.auth));\n }\n const idToken = await this.getIdToken();\n await _logoutIfInvalidated(this, deleteAccount(this.auth, { idToken }));\n this.stsTokenManager.clearRefreshToken();\n // TODO: Determine if cancellable-promises are necessary to use in this class so that delete()\n // cancels pending actions...\n return this.auth.signOut();\n }\n toJSON() {\n return {\n uid: this.uid,\n email: this.email || undefined,\n emailVerified: this.emailVerified,\n displayName: this.displayName || undefined,\n isAnonymous: this.isAnonymous,\n photoURL: this.photoURL || undefined,\n phoneNumber: this.phoneNumber || undefined,\n tenantId: this.tenantId || undefined,\n providerData: this.providerData.map(userInfo => ({ ...userInfo })),\n stsTokenManager: this.stsTokenManager.toJSON(),\n // Redirect event ID must be maintained in case there is a pending\n // redirect event.\n _redirectEventId: this._redirectEventId,\n ...this.metadata.toJSON(),\n // Required for compatibility with the legacy SDK (go/firebase-auth-sdk-persistence-parsing):\n apiKey: this.auth.config.apiKey,\n appName: this.auth.name\n // Missing authDomain will be tolerated by the legacy SDK.\n // stsTokenManager.apiKey isn't actually required (despite the legacy SDK persisting it).\n };\n }\n get refreshToken() {\n return this.stsTokenManager.refreshToken || '';\n }\n static _fromJSON(auth, object) {\n const displayName = object.displayName ?? undefined;\n const email = object.email ?? undefined;\n const phoneNumber = object.phoneNumber ?? undefined;\n const photoURL = object.photoURL ?? undefined;\n const tenantId = object.tenantId ?? undefined;\n const _redirectEventId = object._redirectEventId ?? undefined;\n const createdAt = object.createdAt ?? undefined;\n const lastLoginAt = object.lastLoginAt ?? undefined;\n const { uid, emailVerified, isAnonymous, providerData, stsTokenManager: plainObjectTokenManager } = object;\n _assert(uid && plainObjectTokenManager, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n const stsTokenManager = StsTokenManager.fromJSON(this.name, plainObjectTokenManager);\n _assert(typeof uid === 'string', auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n assertStringOrUndefined(displayName, auth.name);\n assertStringOrUndefined(email, auth.name);\n _assert(typeof emailVerified === 'boolean', auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n _assert(typeof isAnonymous === 'boolean', auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n assertStringOrUndefined(phoneNumber, auth.name);\n assertStringOrUndefined(photoURL, auth.name);\n assertStringOrUndefined(tenantId, auth.name);\n assertStringOrUndefined(_redirectEventId, auth.name);\n assertStringOrUndefined(createdAt, auth.name);\n assertStringOrUndefined(lastLoginAt, auth.name);\n const user = new UserImpl({\n uid,\n auth,\n email,\n emailVerified,\n displayName,\n isAnonymous,\n photoURL,\n phoneNumber,\n tenantId,\n stsTokenManager,\n createdAt,\n lastLoginAt\n });\n if (providerData && Array.isArray(providerData)) {\n user.providerData = providerData.map(userInfo => ({ ...userInfo }));\n }\n if (_redirectEventId) {\n user._redirectEventId = _redirectEventId;\n }\n return user;\n }\n /**\n * Initialize a User from an idToken server response\n * @param auth\n * @param idTokenResponse\n */\n static async _fromIdTokenResponse(auth, idTokenResponse, isAnonymous = false) {\n const stsTokenManager = new StsTokenManager();\n stsTokenManager.updateFromServerResponse(idTokenResponse);\n // Initialize the Firebase Auth user.\n const user = new UserImpl({\n uid: idTokenResponse.localId,\n auth,\n stsTokenManager,\n isAnonymous\n });\n // Updates the user info and data and resolves with a user instance.\n await _reloadWithoutSaving(user);\n return user;\n }\n /**\n * Initialize a User from an idToken server response\n * @param auth\n * @param idTokenResponse\n */\n static async _fromGetAccountInfoResponse(auth, response, idToken) {\n const coreAccount = response.users[0];\n _assert(coreAccount.localId !== undefined, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n const providerData = coreAccount.providerUserInfo !== undefined\n ? extractProviderData(coreAccount.providerUserInfo)\n : [];\n const isAnonymous = !(coreAccount.email && coreAccount.passwordHash) && !providerData?.length;\n const stsTokenManager = new StsTokenManager();\n stsTokenManager.updateFromIdToken(idToken);\n // Initialize the Firebase Auth user.\n const user = new UserImpl({\n uid: coreAccount.localId,\n auth,\n stsTokenManager,\n isAnonymous\n });\n // update the user with data from the GetAccountInfo response.\n const updates = {\n uid: coreAccount.localId,\n displayName: coreAccount.displayName || null,\n photoURL: coreAccount.photoUrl || null,\n email: coreAccount.email || null,\n emailVerified: coreAccount.emailVerified || false,\n phoneNumber: coreAccount.phoneNumber || null,\n tenantId: coreAccount.tenantId || null,\n providerData,\n metadata: new UserMetadata(coreAccount.createdAt, coreAccount.lastLoginAt),\n isAnonymous: !(coreAccount.email && coreAccount.passwordHash) &&\n !providerData?.length\n };\n Object.assign(user, updates);\n return user;\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst instanceCache = new Map();\nfunction _getInstance(cls) {\n debugAssert(cls instanceof Function, 'Expected a class definition');\n let instance = instanceCache.get(cls);\n if (instance) {\n debugAssert(instance instanceof cls, 'Instance stored in cache mismatched with class');\n return instance;\n }\n instance = new cls();\n instanceCache.set(cls, instance);\n return instance;\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass InMemoryPersistence {\n constructor() {\n this.type = \"NONE\" /* PersistenceType.NONE */;\n this.storage = {};\n }\n async _isAvailable() {\n return true;\n }\n async _set(key, value) {\n this.storage[key] = value;\n }\n async _get(key) {\n const value = this.storage[key];\n return value === undefined ? null : value;\n }\n async _remove(key) {\n delete this.storage[key];\n }\n _addListener(_key, _listener) {\n // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers\n return;\n }\n _removeListener(_key, _listener) {\n // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers\n return;\n }\n}\nInMemoryPersistence.type = 'NONE';\n/**\n * An implementation of {@link Persistence} of type 'NONE'.\n *\n * @public\n */\nconst inMemoryPersistence = InMemoryPersistence;\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nfunction _persistenceKeyName(key, apiKey, appName) {\n return `${\"firebase\" /* Namespace.PERSISTENCE */}:${key}:${apiKey}:${appName}`;\n}\nclass PersistenceUserManager {\n constructor(persistence, auth, userKey) {\n this.persistence = persistence;\n this.auth = auth;\n this.userKey = userKey;\n const { config, name } = this.auth;\n this.fullUserKey = _persistenceKeyName(this.userKey, config.apiKey, name);\n this.fullPersistenceKey = _persistenceKeyName(\"persistence\" /* KeyName.PERSISTENCE_USER */, config.apiKey, name);\n this.boundEventHandler = auth._onStorageEvent.bind(auth);\n try {\n this.persistence._addListener(this.fullUserKey, this.boundEventHandler);\n }\n catch {\n // Best effort; ignore errors if addListener throws\n }\n }\n setCurrentUser(user) {\n return this.persistence._set(this.fullUserKey, user.toJSON());\n }\n async getCurrentUser() {\n const blob = await this.persistence._get(this.fullUserKey);\n if (!blob) {\n return null;\n }\n if (typeof blob === 'string') {\n const response = await getAccountInfo(this.auth, { idToken: blob }).catch(() => undefined);\n if (!response) {\n return null;\n }\n return UserImpl._fromGetAccountInfoResponse(this.auth, response, blob);\n }\n return UserImpl._fromJSON(this.auth, blob);\n }\n removeCurrentUser() {\n return this.persistence._remove(this.fullUserKey);\n }\n savePersistenceForRedirect() {\n return this.persistence._set(this.fullPersistenceKey, this.persistence.type);\n }\n async setPersistence(newPersistence) {\n if (this.persistence === newPersistence) {\n return;\n }\n const currentUser = await this.getCurrentUser();\n await this.removeCurrentUser();\n this.persistence = newPersistence;\n if (currentUser) {\n return this.setCurrentUser(currentUser);\n }\n }\n delete() {\n try {\n this.persistence._removeListener(this.fullUserKey, this.boundEventHandler);\n }\n catch { }\n }\n static async create(auth, persistenceHierarchy, userKey = \"authUser\" /* KeyName.AUTH_USER */) {\n if (!persistenceHierarchy.length) {\n return new PersistenceUserManager(_getInstance(inMemoryPersistence), auth, userKey);\n }\n // Eliminate any persistences that are not available\n const availablePersistences = (await Promise.all(persistenceHierarchy.map(async (persistence) => {\n try {\n if (await persistence._isAvailable()) {\n return persistence;\n }\n }\n catch {\n return undefined;\n }\n return undefined;\n }))).filter(persistence => persistence);\n // Fall back to the first persistence listed, or in memory if none available\n let selectedPersistence = availablePersistences[0] ||\n _getInstance(inMemoryPersistence);\n const key = _persistenceKeyName(userKey, auth.config.apiKey, auth.name);\n // Pull out the existing user, setting the chosen persistence to that\n // persistence if the user exists.\n let userToMigrate = null;\n // Note, here we check for a user in _all_ persistences, not just the\n // ones deemed available. If we can migrate a user out of a broken\n // persistence, we will (but only if that persistence supports migration).\n for (const persistence of persistenceHierarchy) {\n try {\n const blob = await persistence._get(key);\n if (blob) {\n let user;\n if (typeof blob === 'string') {\n const response = await getAccountInfo(auth, {\n idToken: blob\n }).catch(() => undefined);\n if (!response) {\n break;\n }\n user = await UserImpl._fromGetAccountInfoResponse(auth, response, blob);\n }\n else {\n user = UserImpl._fromJSON(auth, blob); // throws for unparsable blob (wrong format)\n }\n if (persistence !== selectedPersistence) {\n userToMigrate = user;\n }\n selectedPersistence = persistence;\n break;\n }\n }\n catch { }\n }\n // If we find the user in a persistence that does support migration, use\n // that migration path (of only persistences that support migration)\n const migrationHierarchy = availablePersistences.filter(p => p._shouldAllowMigration);\n // If the persistence does _not_ allow migration, just finish off here\n if (!selectedPersistence._shouldAllowMigration ||\n !migrationHierarchy.length) {\n return new PersistenceUserManager(selectedPersistence, auth, userKey);\n }\n selectedPersistence = migrationHierarchy[0];\n if (userToMigrate) {\n // This normally shouldn't throw since chosenPersistence.isAvailable() is true, but if it does\n // we'll just let it bubble to surface the error.\n await selectedPersistence._set(key, userToMigrate.toJSON());\n }\n // Attempt to clear the key in other persistences but ignore errors. This helps prevent issues\n // such as users getting stuck with a previous account after signing out and refreshing the tab.\n await Promise.all(persistenceHierarchy.map(async (persistence) => {\n if (persistence !== selectedPersistence) {\n try {\n await persistence._remove(key);\n }\n catch { }\n }\n }));\n return new PersistenceUserManager(selectedPersistence, auth, userKey);\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Determine the browser for the purposes of reporting usage to the API\n */\nfunction _getBrowserName(userAgent) {\n const ua = userAgent.toLowerCase();\n if (ua.includes('opera/') || ua.includes('opr/') || ua.includes('opios/')) {\n return \"Opera\" /* BrowserName.OPERA */;\n }\n else if (_isIEMobile(ua)) {\n // Windows phone IEMobile browser.\n return \"IEMobile\" /* BrowserName.IEMOBILE */;\n }\n else if (ua.includes('msie') || ua.includes('trident/')) {\n return \"IE\" /* BrowserName.IE */;\n }\n else if (ua.includes('edge/')) {\n return \"Edge\" /* BrowserName.EDGE */;\n }\n else if (_isFirefox(ua)) {\n return \"Firefox\" /* BrowserName.FIREFOX */;\n }\n else if (ua.includes('silk/')) {\n return \"Silk\" /* BrowserName.SILK */;\n }\n else if (_isBlackBerry(ua)) {\n // Blackberry browser.\n return \"Blackberry\" /* BrowserName.BLACKBERRY */;\n }\n else if (_isWebOS(ua)) {\n // WebOS default browser.\n return \"Webos\" /* BrowserName.WEBOS */;\n }\n else if (_isSafari(ua)) {\n return \"Safari\" /* BrowserName.SAFARI */;\n }\n else if ((ua.includes('chrome/') || _isChromeIOS(ua)) &&\n !ua.includes('edge/')) {\n return \"Chrome\" /* BrowserName.CHROME */;\n }\n else if (_isAndroid(ua)) {\n // Android stock browser.\n return \"Android\" /* BrowserName.ANDROID */;\n }\n else {\n // Most modern browsers have name/version at end of user agent string.\n const re = /([a-zA-Z\\d\\.]+)\\/[a-zA-Z\\d\\.]*$/;\n const matches = userAgent.match(re);\n if (matches?.length === 2) {\n return matches[1];\n }\n }\n return \"Other\" /* BrowserName.OTHER */;\n}\nfunction _isFirefox(ua = getUA()) {\n return /firefox\\//i.test(ua);\n}\nfunction _isSafari(userAgent = getUA()) {\n const ua = userAgent.toLowerCase();\n return (ua.includes('safari/') &&\n !ua.includes('chrome/') &&\n !ua.includes('crios/') &&\n !ua.includes('android'));\n}\nfunction _isChromeIOS(ua = getUA()) {\n return /crios\\//i.test(ua);\n}\nfunction _isIEMobile(ua = getUA()) {\n return /iemobile/i.test(ua);\n}\nfunction _isAndroid(ua = getUA()) {\n return /android/i.test(ua);\n}\nfunction _isBlackBerry(ua = getUA()) {\n return /blackberry/i.test(ua);\n}\nfunction _isWebOS(ua = getUA()) {\n return /webos/i.test(ua);\n}\nfunction _isIOS(ua = getUA()) {\n return (/iphone|ipad|ipod/i.test(ua) ||\n (/macintosh/i.test(ua) && /mobile/i.test(ua)));\n}\nfunction _isIOS7Or8(ua = getUA()) {\n return (/(iPad|iPhone|iPod).*OS 7_\\d/i.test(ua) ||\n /(iPad|iPhone|iPod).*OS 8_\\d/i.test(ua));\n}\nfunction _isIOSStandalone(ua = getUA()) {\n return _isIOS(ua) && !!window.navigator?.standalone;\n}\nfunction _isIE10() {\n return isIE() && document.documentMode === 10;\n}\nfunction _isMobileBrowser(ua = getUA()) {\n // TODO: implement getBrowserName equivalent for OS.\n return (_isIOS(ua) ||\n _isAndroid(ua) ||\n _isWebOS(ua) ||\n _isBlackBerry(ua) ||\n /windows phone/i.test(ua) ||\n _isIEMobile(ua));\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/*\n * Determine the SDK version string\n */\nfunction _getClientVersion(clientPlatform, frameworks = []) {\n let reportedPlatform;\n switch (clientPlatform) {\n case \"Browser\" /* ClientPlatform.BROWSER */:\n // In a browser environment, report the browser name.\n reportedPlatform = _getBrowserName(getUA());\n break;\n case \"Worker\" /* ClientPlatform.WORKER */:\n // Technically a worker runs from a browser but we need to differentiate a\n // worker from a browser.\n // For example: Chrome-Worker/JsCore/4.9.1/FirebaseCore-web.\n reportedPlatform = `${_getBrowserName(getUA())}-${clientPlatform}`;\n break;\n default:\n reportedPlatform = clientPlatform;\n }\n const reportedFrameworks = frameworks.length\n ? frameworks.join(',')\n : 'FirebaseCore-web'; /* default value if no other framework is used */\n return `${reportedPlatform}/${\"JsCore\" /* ClientImplementation.CORE */}/${SDK_VERSION}/${reportedFrameworks}`;\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass AuthMiddlewareQueue {\n constructor(auth) {\n this.auth = auth;\n this.queue = [];\n }\n pushCallback(callback, onAbort) {\n // The callback could be sync or async. Wrap it into a\n // function that is always async.\n const wrappedCallback = (user) => new Promise((resolve, reject) => {\n try {\n const result = callback(user);\n // Either resolve with existing promise or wrap a non-promise\n // return value into a promise.\n resolve(result);\n }\n catch (e) {\n // Sync callback throws.\n reject(e);\n }\n });\n // Attach the onAbort if present\n wrappedCallback.onAbort = onAbort;\n this.queue.push(wrappedCallback);\n const index = this.queue.length - 1;\n return () => {\n // Unsubscribe. Replace with no-op. Do not remove from array, or it will disturb\n // indexing of other elements.\n this.queue[index] = () => Promise.resolve();\n };\n }\n async runMiddleware(nextUser) {\n if (this.auth.currentUser === nextUser) {\n return;\n }\n // While running the middleware, build a temporary stack of onAbort\n // callbacks to call if one middleware callback rejects.\n const onAbortStack = [];\n try {\n for (const beforeStateCallback of this.queue) {\n await beforeStateCallback(nextUser);\n // Only push the onAbort if the callback succeeds\n if (beforeStateCallback.onAbort) {\n onAbortStack.push(beforeStateCallback.onAbort);\n }\n }\n }\n catch (e) {\n // Run all onAbort, with separate try/catch to ignore any errors and\n // continue\n onAbortStack.reverse();\n for (const onAbort of onAbortStack) {\n try {\n onAbort();\n }\n catch (_) {\n /* swallow error */\n }\n }\n throw this.auth._errorFactory.create(\"login-blocked\" /* AuthErrorCode.LOGIN_BLOCKED */, {\n originalMessage: e?.message\n });\n }\n }\n}\n\n/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Fetches the password policy for the currently set tenant or the project if no tenant is set.\n *\n * @param auth Auth object.\n * @param request Password policy request.\n * @returns Password policy response.\n */\nasync function _getPasswordPolicy(auth, request = {}) {\n return _performApiRequest(auth, \"GET\" /* HttpMethod.GET */, \"/v2/passwordPolicy\" /* Endpoint.GET_PASSWORD_POLICY */, _addTidIfNecessary(auth, request));\n}\n\n/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// Minimum min password length enforced by the backend, even if no minimum length is set.\nconst MINIMUM_MIN_PASSWORD_LENGTH = 6;\n/**\n * Stores password policy requirements and provides password validation against the policy.\n *\n * @internal\n */\nclass PasswordPolicyImpl {\n constructor(response) {\n // Only include custom strength options defined in the response.\n const responseOptions = response.customStrengthOptions;\n this.customStrengthOptions = {};\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.\n this.customStrengthOptions.minPasswordLength =\n responseOptions.minPasswordLength ?? MINIMUM_MIN_PASSWORD_LENGTH;\n if (responseOptions.maxPasswordLength) {\n this.customStrengthOptions.maxPasswordLength =\n responseOptions.maxPasswordLength;\n }\n if (responseOptions.containsLowercaseCharacter !== undefined) {\n this.customStrengthOptions.containsLowercaseLetter =\n responseOptions.containsLowercaseCharacter;\n }\n if (responseOptions.containsUppercaseCharacter !== undefined) {\n this.customStrengthOptions.containsUppercaseLetter =\n responseOptions.containsUppercaseCharacter;\n }\n if (responseOptions.containsNumericCharacter !== undefined) {\n this.customStrengthOptions.containsNumericCharacter =\n responseOptions.containsNumericCharacter;\n }\n if (responseOptions.containsNonAlphanumericCharacter !== undefined) {\n this.customStrengthOptions.containsNonAlphanumericCharacter =\n responseOptions.containsNonAlphanumericCharacter;\n }\n this.enforcementState = response.enforcementState;\n if (this.enforcementState === 'ENFORCEMENT_STATE_UNSPECIFIED') {\n this.enforcementState = 'OFF';\n }\n // Use an empty string if no non-alphanumeric characters are specified in the response.\n this.allowedNonAlphanumericCharacters =\n response.allowedNonAlphanumericCharacters?.join('') ?? '';\n this.forceUpgradeOnSignin = response.forceUpgradeOnSignin ?? false;\n this.schemaVersion = response.schemaVersion;\n }\n validatePassword(password) {\n const status = {\n isValid: true,\n passwordPolicy: this\n };\n // Check the password length and character options.\n this.validatePasswordLengthOptions(password, status);\n this.validatePasswordCharacterOptions(password, status);\n // Combine the status into single isValid property.\n status.isValid && (status.isValid = status.meetsMinPasswordLength ?? true);\n status.isValid && (status.isValid = status.meetsMaxPasswordLength ?? true);\n status.isValid && (status.isValid = status.containsLowercaseLetter ?? true);\n status.isValid && (status.isValid = status.containsUppercaseLetter ?? true);\n status.isValid && (status.isValid = status.containsNumericCharacter ?? true);\n status.isValid && (status.isValid = status.containsNonAlphanumericCharacter ?? true);\n return status;\n }\n /**\n * Validates that the password meets the length options for the policy.\n *\n * @param password Password to validate.\n * @param status Validation status.\n */\n validatePasswordLengthOptions(password, status) {\n const minPasswordLength = this.customStrengthOptions.minPasswordLength;\n const maxPasswordLength = this.customStrengthOptions.maxPasswordLength;\n if (minPasswordLength) {\n status.meetsMinPasswordLength = password.length >= minPasswordLength;\n }\n if (maxPasswordLength) {\n status.meetsMaxPasswordLength = password.length <= maxPasswordLength;\n }\n }\n /**\n * Validates that the password meets the character options for the policy.\n *\n * @param password Password to validate.\n * @param status Validation status.\n */\n validatePasswordCharacterOptions(password, status) {\n // Assign statuses for requirements even if the password is an empty string.\n this.updatePasswordCharacterOptionsStatuses(status, \n /* containsLowercaseCharacter= */ false, \n /* containsUppercaseCharacter= */ false, \n /* containsNumericCharacter= */ false, \n /* containsNonAlphanumericCharacter= */ false);\n let passwordChar;\n for (let i = 0; i < password.length; i++) {\n passwordChar = password.charAt(i);\n this.updatePasswordCharacterOptionsStatuses(status, \n /* containsLowercaseCharacter= */ passwordChar >= 'a' &&\n passwordChar <= 'z', \n /* containsUppercaseCharacter= */ passwordChar >= 'A' &&\n passwordChar <= 'Z', \n /* containsNumericCharacter= */ passwordChar >= '0' &&\n passwordChar <= '9', \n /* containsNonAlphanumericCharacter= */ this.allowedNonAlphanumericCharacters.includes(passwordChar));\n }\n }\n /**\n * Updates the running validation status with the statuses for the character options.\n * Expected to be called each time a character is processed to update each option status\n * based on the current character.\n *\n * @param status Validation status.\n * @param containsLowercaseCharacter Whether the character is a lowercase letter.\n * @param containsUppercaseCharacter Whether the character is an uppercase letter.\n * @param containsNumericCharacter Whether the character is a numeric character.\n * @param containsNonAlphanumericCharacter Whether the character is a non-alphanumeric character.\n */\n updatePasswordCharacterOptionsStatuses(status, containsLowercaseCharacter, containsUppercaseCharacter, containsNumericCharacter, containsNonAlphanumericCharacter) {\n if (this.customStrengthOptions.containsLowercaseLetter) {\n status.containsLowercaseLetter || (status.containsLowercaseLetter = containsLowercaseCharacter);\n }\n if (this.customStrengthOptions.containsUppercaseLetter) {\n status.containsUppercaseLetter || (status.containsUppercaseLetter = containsUppercaseCharacter);\n }\n if (this.customStrengthOptions.containsNumericCharacter) {\n status.containsNumericCharacter || (status.containsNumericCharacter = containsNumericCharacter);\n }\n if (this.customStrengthOptions.containsNonAlphanumericCharacter) {\n status.containsNonAlphanumericCharacter || (status.containsNonAlphanumericCharacter = containsNonAlphanumericCharacter);\n }\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass AuthImpl {\n constructor(app, heartbeatServiceProvider, appCheckServiceProvider, config) {\n this.app = app;\n this.heartbeatServiceProvider = heartbeatServiceProvider;\n this.appCheckServiceProvider = appCheckServiceProvider;\n this.config = config;\n this.currentUser = null;\n this.emulatorConfig = null;\n this.operations = Promise.resolve();\n this.authStateSubscription = new Subscription(this);\n this.idTokenSubscription = new Subscription(this);\n this.beforeStateQueue = new AuthMiddlewareQueue(this);\n this.redirectUser = null;\n this.isProactiveRefreshEnabled = false;\n this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION = 1;\n // Any network calls will set this to true and prevent subsequent emulator\n // initialization\n this._canInitEmulator = true;\n this._isInitialized = false;\n this._deleted = false;\n this._initializationPromise = null;\n this._popupRedirectResolver = null;\n this._errorFactory = _DEFAULT_AUTH_ERROR_FACTORY;\n this._agentRecaptchaConfig = null;\n this._tenantRecaptchaConfigs = {};\n this._projectPasswordPolicy = null;\n this._tenantPasswordPolicies = {};\n this._resolvePersistenceManagerAvailable = undefined;\n // Tracks the last notified UID for state change listeners to prevent\n // repeated calls to the callbacks. Undefined means it's never been\n // called, whereas null means it's been called with a signed out user\n this.lastNotifiedUid = undefined;\n this.languageCode = null;\n this.tenantId = null;\n this.settings = { appVerificationDisabledForTesting: false };\n this.frameworks = [];\n this.name = app.name;\n this.clientVersion = config.sdkClientVersion;\n // TODO(jamesdaniels) explore less hacky way to do this, cookie authentication needs\n // persistenceMananger to be available. see _getFinalTarget for more context\n this._persistenceManagerAvailable = new Promise(resolve => (this._resolvePersistenceManagerAvailable = resolve));\n }\n _initializeWithPersistence(persistenceHierarchy, popupRedirectResolver) {\n if (popupRedirectResolver) {\n this._popupRedirectResolver = _getInstance(popupRedirectResolver);\n }\n // Have to check for app deletion throughout initialization (after each\n // promise resolution)\n this._initializationPromise = this.queue(async () => {\n if (this._deleted) {\n return;\n }\n try {\n this.persistenceManager = await PersistenceUserManager.create(this, persistenceHierarchy);\n }\n catch (e) {\n _logWarn(`Failed to initialize persistence: ${e}`);\n this.persistenceManager = await PersistenceUserManager.create(this, []);\n }\n finally {\n this._resolvePersistenceManagerAvailable?.();\n }\n if (this._deleted) {\n return;\n }\n // Initialize the resolver early if necessary (only applicable to web:\n // this will cause the iframe to load immediately in certain cases)\n if (this._popupRedirectResolver?._shouldInitProactively) {\n // If this fails, don't halt auth loading\n try {\n await this._popupRedirectResolver._initialize(this);\n }\n catch (e) {\n /* Ignore the error */\n }\n }\n try {\n await this.initializeCurrentUser(popupRedirectResolver);\n }\n catch (e) {\n _logWarn(`Failed to initialize current user: ${e}`);\n await this.directlySetCurrentUser(null).catch(() => { });\n }\n this.lastNotifiedUid = this.currentUser?.uid || null;\n if (this._deleted) {\n return;\n }\n this._isInitialized = true;\n });\n return this._initializationPromise;\n }\n /**\n * If the persistence is changed in another window, the user manager will let us know\n */\n async _onStorageEvent() {\n if (this._deleted) {\n return;\n }\n const user = await this.assertedPersistence.getCurrentUser();\n if (!this.currentUser && !user) {\n // No change, do nothing (was signed out and remained signed out).\n return;\n }\n // If the same user is to be synchronized.\n if (this.currentUser && user && this.currentUser.uid === user.uid) {\n // Data update, simply copy data changes.\n this._currentUser._assign(user);\n // If tokens changed from previous user tokens, this will trigger\n // notifyAuthListeners_.\n await this.currentUser.getIdToken();\n return;\n }\n // Update current Auth state. Either a new login or logout.\n // Skip blocking callbacks, they should not apply to a change in another tab.\n await this._updateCurrentUser(user, /* skipBeforeStateCallbacks */ true);\n }\n async initializeCurrentUserFromIdToken(idToken) {\n try {\n const response = await getAccountInfo(this, { idToken });\n const user = await UserImpl._fromGetAccountInfoResponse(this, response, idToken);\n await this.directlySetCurrentUser(user);\n }\n catch (err) {\n console.warn('FirebaseServerApp could not login user with provided authIdToken: ', err);\n await this.directlySetCurrentUser(null);\n }\n }\n async initializeCurrentUser(popupRedirectResolver) {\n if (_isFirebaseServerApp(this.app)) {\n const idToken = this.app.settings.authIdToken;\n if (idToken) {\n // Start the auth operation in the next tick to allow a moment for the customer's app to\n // attach an emulator, if desired.\n return new Promise(resolve => {\n setTimeout(() => this.initializeCurrentUserFromIdToken(idToken).then(resolve, resolve));\n });\n }\n else {\n return this.directlySetCurrentUser(null);\n }\n }\n // First check to see if we have a pending redirect event.\n const previouslyStoredUser = (await this.assertedPersistence.getCurrentUser());\n let futureCurrentUser = previouslyStoredUser;\n let needsTocheckMiddleware = false;\n if (popupRedirectResolver && this.config.authDomain) {\n await this.getOrInitRedirectPersistenceManager();\n const redirectUserEventId = this.redirectUser?._redirectEventId;\n const storedUserEventId = futureCurrentUser?._redirectEventId;\n const result = await this.tryRedirectSignIn(popupRedirectResolver);\n // If the stored user (i.e. the old \"currentUser\") has a redirectId that\n // matches the redirect user, then we want to initially sign in with the\n // new user object from result.\n // TODO(samgho): More thoroughly test all of this\n if ((!redirectUserEventId || redirectUserEventId === storedUserEventId) &&\n result?.user) {\n futureCurrentUser = result.user;\n needsTocheckMiddleware = true;\n }\n }\n // If no user in persistence, there is no current user. Set to null.\n if (!futureCurrentUser) {\n return this.directlySetCurrentUser(null);\n }\n if (!futureCurrentUser._redirectEventId) {\n // This isn't a redirect link operation, we can reload and bail.\n // First though, ensure that we check the middleware is happy.\n if (needsTocheckMiddleware) {\n try {\n await this.beforeStateQueue.runMiddleware(futureCurrentUser);\n }\n catch (e) {\n futureCurrentUser = previouslyStoredUser;\n // We know this is available since the bit is only set when the\n // resolver is available\n this._popupRedirectResolver._overrideRedirectResult(this, () => Promise.reject(e));\n }\n }\n if (futureCurrentUser) {\n return this.reloadAndSetCurrentUserOrClear(futureCurrentUser);\n }\n else {\n return this.directlySetCurrentUser(null);\n }\n }\n _assert(this._popupRedirectResolver, this, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\n await this.getOrInitRedirectPersistenceManager();\n // If the redirect user's event ID matches the current user's event ID,\n // DO NOT reload the current user, otherwise they'll be cleared from storage.\n // This is important for the reauthenticateWithRedirect() flow.\n if (this.redirectUser &&\n this.redirectUser._redirectEventId === futureCurrentUser._redirectEventId) {\n return this.directlySetCurrentUser(futureCurrentUser);\n }\n return this.reloadAndSetCurrentUserOrClear(futureCurrentUser);\n }\n async tryRedirectSignIn(redirectResolver) {\n // The redirect user needs to be checked (and signed in if available)\n // during auth initialization. All of the normal sign in and link/reauth\n // flows call back into auth and push things onto the promise queue. We\n // need to await the result of the redirect sign in *inside the promise\n // queue*. This presents a problem: we run into deadlock. See:\n // ┌> [Initialization] ─────┐\n // ┌> [<other queue tasks>] │\n // └─ [getRedirectResult] <─┘\n // where [] are tasks on the queue and arrows denote awaits\n // Initialization will never complete because it's waiting on something\n // that's waiting for initialization to complete!\n //\n // Instead, this method calls getRedirectResult() (stored in\n // _completeRedirectFn) with an optional parameter that instructs all of\n // the underlying auth operations to skip anything that mutates auth state.\n let result = null;\n try {\n // We know this._popupRedirectResolver is set since redirectResolver\n // is passed in. The _completeRedirectFn expects the unwrapped extern.\n result = await this._popupRedirectResolver._completeRedirectFn(this, redirectResolver, true);\n }\n catch (e) {\n // Swallow any errors here; the code can retrieve them in\n // getRedirectResult().\n await this._setRedirectUser(null);\n }\n return result;\n }\n async reloadAndSetCurrentUserOrClear(user) {\n try {\n await _reloadWithoutSaving(user);\n }\n catch (e) {\n const code = e?.code;\n if (code !== `auth/${\"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */}` &&\n code !== `auth/${\"too-many-requests\" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */}` &&\n !code?.startsWith(`auth/${\"quota-exceeded\" /* AuthErrorCode.QUOTA_EXCEEDED */}`)) {\n // Something's wrong with the user's token. Log them out and remove\n // them from storage\n return this.directlySetCurrentUser(null);\n }\n }\n return this.directlySetCurrentUser(user);\n }\n useDeviceLanguage() {\n this.languageCode = _getUserLanguage();\n }\n async _delete() {\n this._deleted = true;\n }\n async updateCurrentUser(userExtern) {\n if (_isFirebaseServerApp(this.app)) {\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this));\n }\n // The public updateCurrentUser method needs to make a copy of the user,\n // and also check that the project matches\n const user = userExtern\n ? getModularInstance(userExtern)\n : null;\n if (user) {\n _assert(user.auth.config.apiKey === this.config.apiKey, this, \"invalid-user-token\" /* AuthErrorCode.INVALID_AUTH */);\n }\n return this._updateCurrentUser(user && user._clone(this));\n }\n async _updateCurrentUser(user, skipBeforeStateCallbacks = false) {\n if (this._deleted) {\n return;\n }\n if (user) {\n _assert(this.tenantId === user.tenantId, this, \"tenant-id-mismatch\" /* AuthErrorCode.TENANT_ID_MISMATCH */);\n }\n if (!skipBeforeStateCallbacks) {\n await this.beforeStateQueue.runMiddleware(user);\n }\n return this.queue(async () => {\n await this.directlySetCurrentUser(user);\n this.notifyAuthListeners();\n });\n }\n async signOut() {\n if (_isFirebaseServerApp(this.app)) {\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this));\n }\n // Run first, to block _setRedirectUser() if any callbacks fail.\n await this.beforeStateQueue.runMiddleware(null);\n // Clear the redirect user when signOut is called\n if (this.redirectPersistenceManager || this._popupRedirectResolver) {\n await this._setRedirectUser(null);\n }\n // Prevent callbacks from being called again in _updateCurrentUser, as\n // they were already called in the first line.\n return this._updateCurrentUser(null, /* skipBeforeStateCallbacks */ true);\n }\n setPersistence(persistence) {\n if (_isFirebaseServerApp(this.app)) {\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this));\n }\n return this.queue(async () => {\n await this.assertedPersistence.setPersistence(_getInstance(persistence));\n });\n }\n _getRecaptchaConfig() {\n if (this.tenantId == null) {\n return this._agentRecaptchaConfig;\n }\n else {\n return this._tenantRecaptchaConfigs[this.tenantId];\n }\n }\n async validatePassword(password) {\n if (!this._getPasswordPolicyInternal()) {\n await this._updatePasswordPolicy();\n }\n // Password policy will be defined after fetching.\n const passwordPolicy = this._getPasswordPolicyInternal();\n // Check that the policy schema version is supported by the SDK.\n // TODO: Update this logic to use a max supported policy schema version once we have multiple schema versions.\n if (passwordPolicy.schemaVersion !==\n this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION) {\n return Promise.reject(this._errorFactory.create(\"unsupported-password-policy-schema-version\" /* AuthErrorCode.UNSUPPORTED_PASSWORD_POLICY_SCHEMA_VERSION */, {}));\n }\n return passwordPolicy.validatePassword(password);\n }\n _getPasswordPolicyInternal() {\n if (this.tenantId === null) {\n return this._projectPasswordPolicy;\n }\n else {\n return this._tenantPasswordPolicies[this.tenantId];\n }\n }\n async _updatePasswordPolicy() {\n const response = await _getPasswordPolicy(this);\n const passwordPolicy = new PasswordPolicyImpl(response);\n if (this.tenantId === null) {\n this._projectPasswordPolicy = passwordPolicy;\n }\n else {\n this._tenantPasswordPolicies[this.tenantId] = passwordPolicy;\n }\n }\n _getPersistenceType() {\n return this.assertedPersistence.persistence.type;\n }\n _getPersistence() {\n return this.assertedPersistence.persistence;\n }\n _updateErrorMap(errorMap) {\n this._errorFactory = new ErrorFactory('auth', 'Firebase', errorMap());\n }\n onAuthStateChanged(nextOrObserver, error, completed) {\n return this.registerStateListener(this.authStateSubscription, nextOrObserver, error, completed);\n }\n beforeAuthStateChanged(callback, onAbort) {\n return this.beforeStateQueue.pushCallback(callback, onAbort);\n }\n onIdTokenChanged(nextOrObserver, error, completed) {\n return this.registerStateListener(this.idTokenSubscription, nextOrObserver, error, completed);\n }\n authStateReady() {\n return new Promise((resolve, reject) => {\n if (this.currentUser) {\n resolve();\n }\n else {\n const unsubscribe = this.onAuthStateChanged(() => {\n unsubscribe();\n resolve();\n }, reject);\n }\n });\n }\n /**\n * Revokes the given access token. Currently only supports Apple OAuth access tokens.\n */\n async revokeAccessToken(token) {\n if (this.currentUser) {\n const idToken = await this.currentUser.getIdToken();\n // Generalize this to accept other providers once supported.\n const request = {\n providerId: 'apple.com',\n tokenType: \"ACCESS_TOKEN\" /* TokenType.ACCESS_TOKEN */,\n token,\n idToken\n };\n if (this.tenantId != null) {\n request.tenantId = this.tenantId;\n }\n await revokeToken(this, request);\n }\n }\n toJSON() {\n return {\n apiKey: this.config.apiKey,\n authDomain: this.config.authDomain,\n appName: this.name,\n currentUser: this._currentUser?.toJSON()\n };\n }\n async _setRedirectUser(user, popupRedirectResolver) {\n const redirectManager = await this.getOrInitRedirectPersistenceManager(popupRedirectResolver);\n return user === null\n ? redirectManager.removeCurrentUser()\n : redirectManager.setCurrentUser(user);\n }\n async getOrInitRedirectPersistenceManager(popupRedirectResolver) {\n if (!this.redirectPersistenceManager) {\n const resolver = (popupRedirectResolver && _getInstance(popupRedirectResolver)) ||\n this._popupRedirectResolver;\n _assert(resolver, this, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\n this.redirectPersistenceManager = await PersistenceUserManager.create(this, [_getInstance(resolver._redirectPersistence)], \"redirectUser\" /* KeyName.REDIRECT_USER */);\n this.redirectUser =\n await this.redirectPersistenceManager.getCurrentUser();\n }\n return this.redirectPersistenceManager;\n }\n async _redirectUserForId(id) {\n // Make sure we've cleared any pending persistence actions if we're not in\n // the initializer\n if (this._isInitialized) {\n await this.queue(async () => { });\n }\n if (this._currentUser?._redirectEventId === id) {\n return this._currentUser;\n }\n if (this.redirectUser?._redirectEventId === id) {\n return this.redirectUser;\n }\n return null;\n }\n async _persistUserIfCurrent(user) {\n if (user === this.currentUser) {\n return this.queue(async () => this.directlySetCurrentUser(user));\n }\n }\n /** Notifies listeners only if the user is current */\n _notifyListenersIfCurrent(user) {\n if (user === this.currentUser) {\n this.notifyAuthListeners();\n }\n }\n _key() {\n return `${this.config.authDomain}:${this.config.apiKey}:${this.name}`;\n }\n _startProactiveRefresh() {\n this.isProactiveRefreshEnabled = true;\n if (this.currentUser) {\n this._currentUser._startProactiveRefresh();\n }\n }\n _stopProactiveRefresh() {\n this.isProactiveRefreshEnabled = false;\n if (this.currentUser) {\n this._currentUser._stopProactiveRefresh();\n }\n }\n /** Returns the current user cast as the internal type */\n get _currentUser() {\n return this.currentUser;\n }\n notifyAuthListeners() {\n if (!this._isInitialized) {\n return;\n }\n this.idTokenSubscription.next(this.currentUser);\n const currentUid = this.currentUser?.uid ?? null;\n if (this.lastNotifiedUid !== currentUid) {\n this.lastNotifiedUid = currentUid;\n this.authStateSubscription.next(this.currentUser);\n }\n }\n registerStateListener(subscription, nextOrObserver, error, completed) {\n if (this._deleted) {\n return () => { };\n }\n const cb = typeof nextOrObserver === 'function'\n ? nextOrObserver\n : nextOrObserver.next.bind(nextOrObserver);\n let isUnsubscribed = false;\n const promise = this._isInitialized\n ? Promise.resolve()\n : this._initializationPromise;\n _assert(promise, this, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n // The callback needs to be called asynchronously per the spec.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n promise\n .then(() => {\n if (isUnsubscribed) {\n return;\n }\n cb(this.currentUser);\n })\n .catch(err => {\n if (isUnsubscribed) {\n return;\n }\n if (typeof nextOrObserver !== 'function' && nextOrObserver.error) {\n nextOrObserver.error(err);\n }\n else if (error) {\n error(err);\n }\n else {\n throw err;\n }\n });\n if (typeof nextOrObserver === 'function') {\n const unsubscribe = subscription.addObserver(nextOrObserver, error, completed);\n return () => {\n isUnsubscribed = true;\n unsubscribe();\n };\n }\n else {\n const unsubscribe = subscription.addObserver(nextOrObserver);\n return () => {\n isUnsubscribed = true;\n unsubscribe();\n };\n }\n }\n /**\n * Unprotected (from race conditions) method to set the current user. This\n * should only be called from within a queued callback. This is necessary\n * because the queue shouldn't rely on another queued callback.\n */\n async directlySetCurrentUser(user) {\n if (this.currentUser && this.currentUser !== user) {\n this._currentUser._stopProactiveRefresh();\n }\n if (user && this.isProactiveRefreshEnabled) {\n user._startProactiveRefresh();\n }\n this.currentUser = user;\n if (this.persistenceManager) {\n try {\n if (user) {\n await this.persistenceManager.setCurrentUser(user);\n }\n else {\n await this.persistenceManager.removeCurrentUser();\n }\n }\n catch (e) {\n const originalMessage = e?.message || String(e);\n const error = _errorWithCustomMessage(this, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */, `An internal AuthError has occurred: ${originalMessage}`);\n error.customData = { originalError: e };\n throw error;\n }\n }\n }\n queue(action) {\n // In case something errors, the callback still should be called in order\n // to keep the promise chain alive\n this.operations = this.operations.then(action, action);\n return this.operations;\n }\n get assertedPersistence() {\n _assert(this.persistenceManager, this, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n return this.persistenceManager;\n }\n _logFramework(framework) {\n if (!framework || this.frameworks.includes(framework)) {\n return;\n }\n this.frameworks.push(framework);\n // Sort alphabetically so that \"FirebaseCore-web,FirebaseUI-web\" and\n // \"FirebaseUI-web,FirebaseCore-web\" aren't viewed as different.\n this.frameworks.sort();\n this.clientVersion = _getClientVersion(this.config.clientPlatform, this._getFrameworks());\n }\n _getFrameworks() {\n return this.frameworks;\n }\n async _getAdditionalHeaders() {\n // Additional headers on every request\n const headers = {\n [\"X-Client-Version\" /* HttpHeader.X_CLIENT_VERSION */]: this.clientVersion\n };\n if (this.app.options.appId) {\n headers[\"X-Firebase-gmpid\" /* HttpHeader.X_FIREBASE_GMPID */] = this.app.options.appId;\n }\n // If the heartbeat service exists, add the heartbeat string\n const heartbeatsHeader = await this.heartbeatServiceProvider\n .getImmediate({\n optional: true\n })\n ?.getHeartbeatsHeader();\n if (heartbeatsHeader) {\n headers[\"X-Firebase-Client\" /* HttpHeader.X_FIREBASE_CLIENT */] = heartbeatsHeader;\n }\n // If the App Check service exists, add the App Check token in the headers\n const appCheckToken = await this._getAppCheckToken();\n if (appCheckToken) {\n headers[\"X-Firebase-AppCheck\" /* HttpHeader.X_FIREBASE_APP_CHECK */] = appCheckToken;\n }\n return headers;\n }\n async _getAppCheckToken() {\n if (_isFirebaseServerApp(this.app) && this.app.settings.appCheckToken) {\n return this.app.settings.appCheckToken;\n }\n const appCheckTokenResult = await this.appCheckServiceProvider\n .getImmediate({ optional: true })\n ?.getToken();\n if (appCheckTokenResult?.error) {\n // Context: appCheck.getToken() will never throw even if an error happened.\n // In the error case, a dummy token will be returned along with an error field describing\n // the error. In general, we shouldn't care about the error condition and just use\n // the token (actual or dummy) to send requests.\n _logWarn(`Error while retrieving App Check token: ${appCheckTokenResult.error}`);\n }\n return appCheckTokenResult?.token;\n }\n}\n/**\n * Method to be used to cast down to our private implementation of Auth.\n * It will also handle unwrapping from the compat type if necessary\n *\n * @param auth Auth object passed in from developer\n */\nfunction _castAuth(auth) {\n return getModularInstance(auth);\n}\n/** Helper class to wrap subscriber logic */\nclass Subscription {\n constructor(auth) {\n this.auth = auth;\n this.observer = null;\n this.addObserver = createSubscribe(observer => (this.observer = observer));\n }\n get next() {\n _assert(this.observer, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n return this.observer.next.bind(this.observer);\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nlet externalJSProvider = {\n async loadJS() {\n throw new Error('Unable to load external scripts');\n },\n recaptchaV2Script: '',\n recaptchaEnterpriseScript: '',\n gapiScript: ''\n};\nfunction _setExternalJSProvider(p) {\n externalJSProvider = p;\n}\nfunction _loadJS(url) {\n return externalJSProvider.loadJS(url);\n}\nfunction _recaptchaV2ScriptUrl() {\n return externalJSProvider.recaptchaV2Script;\n}\nfunction _recaptchaEnterpriseScriptUrl() {\n return externalJSProvider.recaptchaEnterpriseScript;\n}\nfunction _gapiScriptUrl() {\n return externalJSProvider.gapiScript;\n}\nfunction _generateCallbackName(prefix) {\n return `__${prefix}${Math.floor(Math.random() * 1000000)}`;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst _SOLVE_TIME_MS = 500;\nconst _EXPIRATION_TIME_MS = 60000;\nconst _WIDGET_ID_START = 1000000000000;\nclass MockReCaptcha {\n constructor(auth) {\n this.auth = auth;\n this.counter = _WIDGET_ID_START;\n this._widgets = new Map();\n }\n render(container, parameters) {\n const id = this.counter;\n this._widgets.set(id, new MockWidget(container, this.auth.name, parameters || {}));\n this.counter++;\n return id;\n }\n reset(optWidgetId) {\n const id = optWidgetId || _WIDGET_ID_START;\n void this._widgets.get(id)?.delete();\n this._widgets.delete(id);\n }\n getResponse(optWidgetId) {\n const id = optWidgetId || _WIDGET_ID_START;\n return this._widgets.get(id)?.getResponse() || '';\n }\n async execute(optWidgetId) {\n const id = optWidgetId || _WIDGET_ID_START;\n void this._widgets.get(id)?.execute();\n return '';\n }\n}\nclass MockGreCAPTCHATopLevel {\n constructor() {\n this.enterprise = new MockGreCAPTCHA();\n }\n ready(callback) {\n callback();\n }\n execute(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _siteKey, _options) {\n return Promise.resolve('token');\n }\n render(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _container, _parameters) {\n return '';\n }\n}\nclass MockGreCAPTCHA {\n ready(callback) {\n callback();\n }\n execute(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _siteKey, _options) {\n return Promise.resolve('token');\n }\n render(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _container, _parameters) {\n return '';\n }\n}\nclass MockWidget {\n constructor(containerOrId, appName, params) {\n this.params = params;\n this.timerId = null;\n this.deleted = false;\n this.responseToken = null;\n this.clickHandler = () => {\n this.execute();\n };\n const container = typeof containerOrId === 'string'\n ? document.getElementById(containerOrId)\n : containerOrId;\n _assert(container, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */, { appName });\n this.container = container;\n this.isVisible = this.params.size !== 'invisible';\n if (this.isVisible) {\n this.execute();\n }\n else {\n this.container.addEventListener('click', this.clickHandler);\n }\n }\n getResponse() {\n this.checkIfDeleted();\n return this.responseToken;\n }\n delete() {\n this.checkIfDeleted();\n this.deleted = true;\n if (this.timerId) {\n clearTimeout(this.timerId);\n this.timerId = null;\n }\n this.container.removeEventListener('click', this.clickHandler);\n }\n execute() {\n this.checkIfDeleted();\n if (this.timerId) {\n return;\n }\n this.timerId = window.setTimeout(() => {\n this.responseToken = generateRandomAlphaNumericString(50);\n const { callback, 'expired-callback': expiredCallback } = this.params;\n if (callback) {\n try {\n callback(this.responseToken);\n }\n catch (e) { }\n }\n this.timerId = window.setTimeout(() => {\n this.timerId = null;\n this.responseToken = null;\n if (expiredCallback) {\n try {\n expiredCallback();\n }\n catch (e) { }\n }\n if (this.isVisible) {\n this.execute();\n }\n }, _EXPIRATION_TIME_MS);\n }, _SOLVE_TIME_MS);\n }\n checkIfDeleted() {\n if (this.deleted) {\n throw new Error('reCAPTCHA mock was already deleted!');\n }\n }\n}\nfunction generateRandomAlphaNumericString(len) {\n const chars = [];\n const allowedChars = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\n for (let i = 0; i < len; i++) {\n chars.push(allowedChars.charAt(Math.floor(Math.random() * allowedChars.length)));\n }\n return chars.join('');\n}\n\n/* eslint-disable @typescript-eslint/no-require-imports */\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst RECAPTCHA_ENTERPRISE_VERIFIER_TYPE = 'recaptcha-enterprise';\nconst FAKE_TOKEN = 'NO_RECAPTCHA';\nconst RECAPTCHA_ENTERPRISE_ONLOAD_CALLBACK_NAME = 'onFirebaseAuthREInstanceReady';\nclass RecaptchaEnterpriseVerifier {\n /**\n *\n * @param authExtern - The corresponding Firebase {@link Auth} instance.\n *\n */\n constructor(authExtern) {\n /**\n * Identifies the type of application verifier (e.g. \"recaptcha-enterprise\").\n */\n this.type = RECAPTCHA_ENTERPRISE_VERIFIER_TYPE;\n this.auth = _castAuth(authExtern);\n }\n /**\n * Executes the verification process.\n *\n * @returns A Promise for a token that can be used to assert the validity of a request.\n */\n async verify(action = 'verify', forceRefresh = false) {\n async function retrieveSiteKey(auth) {\n if (!forceRefresh) {\n if (auth.tenantId == null && auth._agentRecaptchaConfig != null) {\n return auth._agentRecaptchaConfig.siteKey;\n }\n if (auth.tenantId != null &&\n auth._tenantRecaptchaConfigs[auth.tenantId] !== undefined) {\n return auth._tenantRecaptchaConfigs[auth.tenantId].siteKey;\n }\n }\n return new Promise(async (resolve, reject) => {\n getRecaptchaConfig(auth, {\n clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */,\n version: \"RECAPTCHA_ENTERPRISE\" /* RecaptchaVersion.ENTERPRISE */\n })\n .then(response => {\n if (response.recaptchaKey === undefined) {\n reject(new Error('recaptcha Enterprise site key undefined'));\n }\n else {\n const config = new RecaptchaConfig(response);\n if (auth.tenantId == null) {\n auth._agentRecaptchaConfig = config;\n }\n else {\n auth._tenantRecaptchaConfigs[auth.tenantId] = config;\n }\n return resolve(config.siteKey);\n }\n })\n .catch(error => {\n reject(error);\n });\n });\n }\n function retrieveRecaptchaToken(siteKey, resolve, reject) {\n const grecaptcha = window.grecaptcha;\n if (isEnterprise(grecaptcha)) {\n grecaptcha.enterprise.ready(() => {\n grecaptcha.enterprise\n .execute(siteKey, { action })\n .then(token => {\n resolve(token);\n })\n .catch(() => {\n resolve(FAKE_TOKEN);\n });\n });\n }\n else {\n reject(Error('No reCAPTCHA enterprise script loaded.'));\n }\n }\n // Returns Promise for a mock token when appVerificationDisabledForTesting is true.\n if (this.auth.settings.appVerificationDisabledForTesting) {\n const mockRecaptcha = new MockGreCAPTCHATopLevel();\n return mockRecaptcha.execute('siteKey', { action: 'verify' });\n }\n return new Promise((resolve, reject) => {\n retrieveSiteKey(this.auth)\n .then(async (siteKey) => {\n if (!forceRefresh &&\n isEnterprise(window.grecaptcha) &&\n // If download has already been initiated, do not trigger another\n // download, await the promise here.\n RecaptchaEnterpriseVerifier.scriptInjectionDeferred) {\n await RecaptchaEnterpriseVerifier.scriptInjectionDeferred.promise;\n retrieveRecaptchaToken(siteKey, resolve, reject);\n }\n else {\n if (typeof window === 'undefined') {\n reject(new Error('RecaptchaVerifier is only supported in browser'));\n return;\n }\n let url = _recaptchaEnterpriseScriptUrl();\n if (url.length !== 0) {\n url +=\n siteKey +\n `&onload=${RECAPTCHA_ENTERPRISE_ONLOAD_CALLBACK_NAME}`;\n }\n // Existence of deferred indicates download has been initiated.\n RecaptchaEnterpriseVerifier.scriptInjectionDeferred =\n new Deferred();\n /**\n * Script attached to global window object that will be called\n * when the ReCAPTCHA Enterprise instance is ready.\n * grecaptcha.ready() is not reliable when there are multiple\n * scripts on the page, and script.onload only indicates the\n * script has downloaded, not that it has initialized.\n */\n window[RECAPTCHA_ENTERPRISE_ONLOAD_CALLBACK_NAME] = () => {\n RecaptchaEnterpriseVerifier.scriptInjectionDeferred?.resolve();\n };\n _loadJS(url)\n .then(() => RecaptchaEnterpriseVerifier.scriptInjectionDeferred?.promise)\n .then(() => {\n retrieveRecaptchaToken(siteKey, resolve, reject);\n })\n .catch(error => {\n reject(error);\n });\n }\n })\n .catch(error => {\n reject(error);\n });\n });\n }\n}\n/**\n * Deferred that resolves when script tag has been injected onto the page\n * and the script is ready (grecaptcha.ready() and script.onload are not\n * reliable indicators, so this resolves when the global\n * `window[RECAPTCHA_ENTERPRISE_ONLOAD_CALLBACK_NAME]()` callback provided to the recaptcha url param \"onload\"\n * is triggered).\n * As a static variable this is applied to all instances of the class.\n * This will cause an error if users try to create multiple RecaptchaVerifiers\n * with different Recaptcha Enterprise sitekeys, which should be an\n * unuspported use case.\n */\nRecaptchaEnterpriseVerifier.scriptInjectionDeferred = null;\nasync function injectRecaptchaFields(auth, request, action, isCaptchaResp = false, isFakeToken = false) {\n const verifier = new RecaptchaEnterpriseVerifier(auth);\n let captchaResponse;\n if (isFakeToken) {\n captchaResponse = FAKE_TOKEN;\n }\n else {\n try {\n captchaResponse = await verifier.verify(action);\n }\n catch (error) {\n captchaResponse = await verifier.verify(action, true);\n }\n }\n const newRequest = { ...request };\n if (action === \"mfaSmsEnrollment\" /* RecaptchaActionName.MFA_SMS_ENROLLMENT */ ||\n action === \"mfaSmsSignIn\" /* RecaptchaActionName.MFA_SMS_SIGNIN */) {\n if ('phoneEnrollmentInfo' in newRequest) {\n const phoneNumber = newRequest.phoneEnrollmentInfo.phoneNumber;\n const recaptchaToken = newRequest.phoneEnrollmentInfo.recaptchaToken;\n Object.assign(newRequest, {\n 'phoneEnrollmentInfo': {\n phoneNumber,\n recaptchaToken,\n captchaResponse,\n 'clientType': \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */,\n 'recaptchaVersion': \"RECAPTCHA_ENTERPRISE\" /* RecaptchaVersion.ENTERPRISE */\n }\n });\n }\n else if ('phoneSignInInfo' in newRequest) {\n const recaptchaToken = newRequest.phoneSignInInfo.recaptchaToken;\n Object.assign(newRequest, {\n 'phoneSignInInfo': {\n recaptchaToken,\n captchaResponse,\n 'clientType': \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */,\n 'recaptchaVersion': \"RECAPTCHA_ENTERPRISE\" /* RecaptchaVersion.ENTERPRISE */\n }\n });\n }\n return newRequest;\n }\n if (!isCaptchaResp) {\n Object.assign(newRequest, { captchaResponse });\n }\n else {\n Object.assign(newRequest, { 'captchaResp': captchaResponse });\n }\n Object.assign(newRequest, { 'clientType': \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */ });\n Object.assign(newRequest, {\n 'recaptchaVersion': \"RECAPTCHA_ENTERPRISE\" /* RecaptchaVersion.ENTERPRISE */\n });\n return newRequest;\n}\nasync function handleRecaptchaFlow(authInstance, request, actionName, actionMethod, recaptchaAuthProvider) {\n if (recaptchaAuthProvider === \"EMAIL_PASSWORD_PROVIDER\" /* RecaptchaAuthProvider.EMAIL_PASSWORD_PROVIDER */) {\n if (authInstance\n ._getRecaptchaConfig()\n ?.isProviderEnabled(\"EMAIL_PASSWORD_PROVIDER\" /* RecaptchaAuthProvider.EMAIL_PASSWORD_PROVIDER */)) {\n const requestWithRecaptcha = await injectRecaptchaFields(authInstance, request, actionName, actionName === \"getOobCode\" /* RecaptchaActionName.GET_OOB_CODE */);\n return actionMethod(authInstance, requestWithRecaptcha);\n }\n else {\n return actionMethod(authInstance, request).catch(async (error) => {\n if (error.code === `auth/${\"missing-recaptcha-token\" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */}`) {\n console.log(`${actionName} is protected by reCAPTCHA Enterprise for this project. Automatically triggering the reCAPTCHA flow and restarting the flow.`);\n const requestWithRecaptcha = await injectRecaptchaFields(authInstance, request, actionName, actionName === \"getOobCode\" /* RecaptchaActionName.GET_OOB_CODE */);\n return actionMethod(authInstance, requestWithRecaptcha);\n }\n else {\n return Promise.reject(error);\n }\n });\n }\n }\n else if (recaptchaAuthProvider === \"PHONE_PROVIDER\" /* RecaptchaAuthProvider.PHONE_PROVIDER */) {\n if (authInstance\n ._getRecaptchaConfig()\n ?.isProviderEnabled(\"PHONE_PROVIDER\" /* RecaptchaAuthProvider.PHONE_PROVIDER */)) {\n const requestWithRecaptcha = await injectRecaptchaFields(authInstance, request, actionName);\n return actionMethod(authInstance, requestWithRecaptcha).catch(async (error) => {\n if (authInstance\n ._getRecaptchaConfig()\n ?.getProviderEnforcementState(\"PHONE_PROVIDER\" /* RecaptchaAuthProvider.PHONE_PROVIDER */) === \"AUDIT\" /* EnforcementState.AUDIT */) {\n // AUDIT mode\n if (error.code === `auth/${\"missing-recaptcha-token\" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */}` ||\n error.code === `auth/${\"invalid-app-credential\" /* AuthErrorCode.INVALID_APP_CREDENTIAL */}`) {\n console.log(`Failed to verify with reCAPTCHA Enterprise. Automatically triggering the reCAPTCHA v2 flow to complete the ${actionName} flow.`);\n // reCAPTCHA Enterprise token is missing or reCAPTCHA Enterprise token\n // check fails.\n // Fallback to reCAPTCHA v2 flow.\n const requestWithRecaptchaFields = await injectRecaptchaFields(authInstance, request, actionName, false, // isCaptchaResp\n true // isFakeToken\n );\n // This will call the PhoneApiCaller to fetch and inject reCAPTCHA v2 token.\n return actionMethod(authInstance, requestWithRecaptchaFields);\n }\n }\n // ENFORCE mode or AUDIT mode with any other error.\n return Promise.reject(error);\n });\n }\n else {\n // Do reCAPTCHA v2 flow.\n const requestWithRecaptchaFields = await injectRecaptchaFields(authInstance, request, actionName, false, // isCaptchaResp\n true // isFakeToken\n );\n // This will call the PhoneApiCaller to fetch and inject v2 token.\n return actionMethod(authInstance, requestWithRecaptchaFields);\n }\n }\n else {\n return Promise.reject(recaptchaAuthProvider + ' provider is not supported.');\n }\n}\nasync function _initializeRecaptchaConfig(auth) {\n const authInternal = _castAuth(auth);\n const response = await getRecaptchaConfig(authInternal, {\n clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */,\n version: \"RECAPTCHA_ENTERPRISE\" /* RecaptchaVersion.ENTERPRISE */\n });\n const config = new RecaptchaConfig(response);\n if (authInternal.tenantId == null) {\n authInternal._agentRecaptchaConfig = config;\n }\n else {\n authInternal._tenantRecaptchaConfigs[authInternal.tenantId] = config;\n }\n if (config.isAnyProviderEnabled()) {\n const verifier = new RecaptchaEnterpriseVerifier(authInternal);\n void verifier.verify();\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Initializes an {@link Auth} instance with fine-grained control over\n * {@link Dependencies}.\n *\n * @remarks\n *\n * This function allows more control over the {@link Auth} instance than\n * {@link getAuth}. `getAuth` uses platform-specific defaults to supply\n * the {@link Dependencies}. In general, `getAuth` is the easiest way to\n * initialize Auth and works for most use cases. Use `initializeAuth` if you\n * need control over which persistence layer is used, or to minimize bundle\n * size if you're not using either `signInWithPopup` or `signInWithRedirect`.\n *\n * For example, if your app only uses anonymous accounts and you only want\n * accounts saved for the current session, initialize `Auth` with:\n *\n * ```js\n * const auth = initializeAuth(app, {\n * persistence: browserSessionPersistence,\n * popupRedirectResolver: undefined,\n * });\n * ```\n *\n * @public\n */\nfunction initializeAuth(app, deps) {\n const provider = _getProvider(app, 'auth');\n if (provider.isInitialized()) {\n const auth = provider.getImmediate();\n const initialOptions = provider.getOptions();\n if (deepEqual(initialOptions, deps ?? {})) {\n return auth;\n }\n else {\n _fail(auth, \"already-initialized\" /* AuthErrorCode.ALREADY_INITIALIZED */);\n }\n }\n const auth = provider.initialize({ options: deps });\n return auth;\n}\nfunction _initializeAuthInstance(auth, deps) {\n const persistence = deps?.persistence || [];\n const hierarchy = (Array.isArray(persistence) ? persistence : [persistence]).map(_getInstance);\n if (deps?.errorMap) {\n auth._updateErrorMap(deps.errorMap);\n }\n // This promise is intended to float; auth initialization happens in the\n // background, meanwhile the auth object may be used by the app.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n auth._initializeWithPersistence(hierarchy, deps?.popupRedirectResolver);\n}\n\n/**\n * Changes the {@link Auth} instance to communicate with the Firebase Auth Emulator, instead of production\n * Firebase Auth services.\n *\n * @remarks\n * This must be called synchronously immediately following the first call to\n * {@link initializeAuth}. Do not use with production credentials as emulator\n * traffic is not encrypted.\n *\n *\n * @example\n * ```javascript\n * connectAuthEmulator(auth, 'http://127.0.0.1:9099', { disableWarnings: true });\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param url - The URL at which the emulator is running (eg, 'http://localhost:9099').\n * @param options - Optional. `options.disableWarnings` defaults to `false`. Set it to\n * `true` to disable the warning banner attached to the DOM.\n *\n * @public\n */\nfunction connectAuthEmulator(auth, url, options) {\n const authInternal = _castAuth(auth);\n _assert(/^https?:\\/\\//.test(url), authInternal, \"invalid-emulator-scheme\" /* AuthErrorCode.INVALID_EMULATOR_SCHEME */);\n const disableWarnings = !!options?.disableWarnings;\n const protocol = extractProtocol(url);\n const { host, port } = extractHostAndPort(url);\n const portStr = port === null ? '' : `:${port}`;\n // Always replace path with \"/\" (even if input url had no path at all, or had a different one).\n const emulator = { url: `${protocol}//${host}${portStr}/` };\n const emulatorConfig = Object.freeze({\n host,\n port,\n protocol: protocol.replace(':', ''),\n options: Object.freeze({ disableWarnings })\n });\n // There are a few scenarios to guard against if the Auth instance has already started:\n if (!authInternal._canInitEmulator) {\n // Applications may not initialize the emulator for the first time if Auth has already started\n // to make network requests.\n _assert(authInternal.config.emulator && authInternal.emulatorConfig, authInternal, \"emulator-config-failed\" /* AuthErrorCode.EMULATOR_CONFIG_FAILED */);\n // Applications may not alter the configuration of the emulator (aka pass a different config)\n // once Auth has started to make network requests.\n _assert(deepEqual(emulator, authInternal.config.emulator) &&\n deepEqual(emulatorConfig, authInternal.emulatorConfig), authInternal, \"emulator-config-failed\" /* AuthErrorCode.EMULATOR_CONFIG_FAILED */);\n // It's valid, however, to invoke connectAuthEmulator() after Auth has started making\n // connections, so long as the config matches the existing config. This results in a no-op.\n return;\n }\n authInternal.config.emulator = emulator;\n authInternal.emulatorConfig = emulatorConfig;\n authInternal.settings.appVerificationDisabledForTesting = true;\n // Workaround to get cookies in Firebase Studio\n if (isCloudWorkstation(host)) {\n void pingServer(`${protocol}//${host}${portStr}`);\n }\n else if (!disableWarnings) {\n emitEmulatorWarning();\n }\n}\nfunction extractProtocol(url) {\n const protocolEnd = url.indexOf(':');\n return protocolEnd < 0 ? '' : url.substr(0, protocolEnd + 1);\n}\nfunction extractHostAndPort(url) {\n const protocol = extractProtocol(url);\n const authority = /(\\/\\/)?([^?#/]+)/.exec(url.substr(protocol.length)); // Between // and /, ? or #.\n if (!authority) {\n return { host: '', port: null };\n }\n const hostAndPort = authority[2].split('@').pop() || ''; // Strip out \"username:password@\".\n const bracketedIPv6 = /^(\\[[^\\]]+\\])(:|$)/.exec(hostAndPort);\n if (bracketedIPv6) {\n const host = bracketedIPv6[1];\n return { host, port: parsePort(hostAndPort.substr(host.length + 1)) };\n }\n else {\n const [host, port] = hostAndPort.split(':');\n return { host, port: parsePort(port) };\n }\n}\nfunction parsePort(portStr) {\n if (!portStr) {\n return null;\n }\n const port = Number(portStr);\n if (isNaN(port)) {\n return null;\n }\n return port;\n}\nfunction emitEmulatorWarning() {\n function attachBanner() {\n const el = document.createElement('p');\n const sty = el.style;\n el.innerText =\n 'Running in emulator mode. Do not use with production credentials.';\n sty.position = 'fixed';\n sty.width = '100%';\n sty.backgroundColor = '#ffffff';\n sty.border = '.1em solid #000000';\n sty.color = '#b50000';\n sty.bottom = '0px';\n sty.left = '0px';\n sty.margin = '0px';\n sty.zIndex = '10000';\n sty.textAlign = 'center';\n el.classList.add('firebase-emulator-warning');\n document.body.appendChild(el);\n }\n if (typeof console !== 'undefined' && typeof console.info === 'function') {\n console.info('WARNING: You are using the Auth Emulator,' +\n ' which is intended for local testing only. Do not use with' +\n ' production credentials.');\n }\n if (typeof window !== 'undefined' && typeof document !== 'undefined') {\n if (document.readyState === 'loading') {\n window.addEventListener('DOMContentLoaded', attachBanner);\n }\n else {\n attachBanner();\n }\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Interface that represents the credentials returned by an {@link AuthProvider}.\n *\n * @remarks\n * Implementations specify the details about each auth provider's credential requirements.\n *\n * @public\n */\nclass AuthCredential {\n /** @internal */\n constructor(\n /**\n * The authentication provider ID for the credential.\n *\n * @remarks\n * For example, 'facebook.com', or 'google.com'.\n */\n providerId, \n /**\n * The authentication sign in method for the credential.\n *\n * @remarks\n * For example, {@link SignInMethod}.EMAIL_PASSWORD, or\n * {@link SignInMethod}.EMAIL_LINK. This corresponds to the sign-in method\n * identifier as returned in {@link fetchSignInMethodsForEmail}.\n */\n signInMethod) {\n this.providerId = providerId;\n this.signInMethod = signInMethod;\n }\n /**\n * Returns a JSON-serializable representation of this object.\n *\n * @returns a JSON-serializable representation of this object.\n */\n toJSON() {\n return debugFail('not implemented');\n }\n /** @internal */\n _getIdTokenResponse(_auth) {\n return debugFail('not implemented');\n }\n /** @internal */\n _linkToIdToken(_auth, _idToken) {\n return debugFail('not implemented');\n }\n /** @internal */\n _getReauthenticationResolver(_auth) {\n return debugFail('not implemented');\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nasync function resetPassword(auth, request) {\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:resetPassword\" /* Endpoint.RESET_PASSWORD */, _addTidIfNecessary(auth, request));\n}\nasync function updateEmailPassword(auth, request) {\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:update\" /* Endpoint.SET_ACCOUNT_INFO */, request);\n}\n// Used for linking an email/password account to an existing idToken. Uses the same request/response\n// format as updateEmailPassword.\nasync function linkEmailPassword(auth, request) {\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signUp\" /* Endpoint.SIGN_UP */, request);\n}\nasync function applyActionCode$1(auth, request) {\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:update\" /* Endpoint.SET_ACCOUNT_INFO */, _addTidIfNecessary(auth, request));\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nasync function signInWithPassword(auth, request) {\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithPassword\" /* Endpoint.SIGN_IN_WITH_PASSWORD */, _addTidIfNecessary(auth, request));\n}\nasync function sendOobCode(auth, request) {\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:sendOobCode\" /* Endpoint.SEND_OOB_CODE */, _addTidIfNecessary(auth, request));\n}\nasync function sendEmailVerification$1(auth, request) {\n return sendOobCode(auth, request);\n}\nasync function sendPasswordResetEmail$1(auth, request) {\n return sendOobCode(auth, request);\n}\nasync function sendSignInLinkToEmail$1(auth, request) {\n return sendOobCode(auth, request);\n}\nasync function verifyAndChangeEmail(auth, request) {\n return sendOobCode(auth, request);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nasync function signInWithEmailLink$1(auth, request) {\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithEmailLink\" /* Endpoint.SIGN_IN_WITH_EMAIL_LINK */, _addTidIfNecessary(auth, request));\n}\nasync function signInWithEmailLinkForLinking(auth, request) {\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithEmailLink\" /* Endpoint.SIGN_IN_WITH_EMAIL_LINK */, _addTidIfNecessary(auth, request));\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Interface that represents the credentials returned by {@link EmailAuthProvider} for\n * {@link ProviderId}.PASSWORD\n *\n * @remarks\n * Covers both {@link SignInMethod}.EMAIL_PASSWORD and\n * {@link SignInMethod}.EMAIL_LINK.\n *\n * @public\n */\nclass EmailAuthCredential extends AuthCredential {\n /** @internal */\n constructor(\n /** @internal */\n _email, \n /** @internal */\n _password, signInMethod, \n /** @internal */\n _tenantId = null) {\n super(\"password\" /* ProviderId.PASSWORD */, signInMethod);\n this._email = _email;\n this._password = _password;\n this._tenantId = _tenantId;\n }\n /** @internal */\n static _fromEmailAndPassword(email, password) {\n return new EmailAuthCredential(email, password, \"password\" /* SignInMethod.EMAIL_PASSWORD */);\n }\n /** @internal */\n static _fromEmailAndCode(email, oobCode, tenantId = null) {\n return new EmailAuthCredential(email, oobCode, \"emailLink\" /* SignInMethod.EMAIL_LINK */, tenantId);\n }\n /** {@inheritdoc AuthCredential.toJSON} */\n toJSON() {\n return {\n email: this._email,\n password: this._password,\n signInMethod: this.signInMethod,\n tenantId: this._tenantId\n };\n }\n /**\n * Static method to deserialize a JSON representation of an object into an {@link AuthCredential}.\n *\n * @param json - Either `object` or the stringified representation of the object. When string is\n * provided, `JSON.parse` would be called first.\n *\n * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.\n */\n static fromJSON(json) {\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\n if (obj?.email && obj?.password) {\n if (obj.signInMethod === \"password\" /* SignInMethod.EMAIL_PASSWORD */) {\n return this._fromEmailAndPassword(obj.email, obj.password);\n }\n else if (obj.signInMethod === \"emailLink\" /* SignInMethod.EMAIL_LINK */) {\n return this._fromEmailAndCode(obj.email, obj.password, obj.tenantId);\n }\n }\n return null;\n }\n /** @internal */\n async _getIdTokenResponse(auth) {\n switch (this.signInMethod) {\n case \"password\" /* SignInMethod.EMAIL_PASSWORD */:\n const request = {\n returnSecureToken: true,\n email: this._email,\n password: this._password,\n clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */\n };\n return handleRecaptchaFlow(auth, request, \"signInWithPassword\" /* RecaptchaActionName.SIGN_IN_WITH_PASSWORD */, signInWithPassword, \"EMAIL_PASSWORD_PROVIDER\" /* RecaptchaAuthProvider.EMAIL_PASSWORD_PROVIDER */);\n case \"emailLink\" /* SignInMethod.EMAIL_LINK */:\n return signInWithEmailLink$1(auth, {\n email: this._email,\n oobCode: this._password\n });\n default:\n _fail(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n }\n }\n /** @internal */\n async _linkToIdToken(auth, idToken) {\n switch (this.signInMethod) {\n case \"password\" /* SignInMethod.EMAIL_PASSWORD */:\n const request = {\n idToken,\n returnSecureToken: true,\n email: this._email,\n password: this._password,\n clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */\n };\n return handleRecaptchaFlow(auth, request, \"signUpPassword\" /* RecaptchaActionName.SIGN_UP_PASSWORD */, linkEmailPassword, \"EMAIL_PASSWORD_PROVIDER\" /* RecaptchaAuthProvider.EMAIL_PASSWORD_PROVIDER */);\n case \"emailLink\" /* SignInMethod.EMAIL_LINK */:\n return signInWithEmailLinkForLinking(auth, {\n idToken,\n email: this._email,\n oobCode: this._password\n });\n default:\n _fail(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n }\n }\n /** @internal */\n _getReauthenticationResolver(auth) {\n return this._getIdTokenResponse(auth);\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nasync function signInWithIdp(auth, request) {\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithIdp\" /* Endpoint.SIGN_IN_WITH_IDP */, _addTidIfNecessary(auth, request));\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst IDP_REQUEST_URI$1 = 'http://localhost';\n/**\n * Represents the OAuth credentials returned by an {@link OAuthProvider}.\n *\n * @remarks\n * Implementations specify the details about each auth provider's credential requirements.\n *\n * @public\n */\nclass OAuthCredential extends AuthCredential {\n constructor() {\n super(...arguments);\n this.pendingToken = null;\n }\n /** @internal */\n static _fromParams(params) {\n const cred = new OAuthCredential(params.providerId, params.signInMethod);\n if (params.idToken || params.accessToken) {\n // OAuth 2 and either ID token or access token.\n if (params.idToken) {\n cred.idToken = params.idToken;\n }\n if (params.accessToken) {\n cred.accessToken = params.accessToken;\n }\n // Add nonce if available and no pendingToken is present.\n if (params.nonce && !params.pendingToken) {\n cred.nonce = params.nonce;\n }\n if (params.pendingToken) {\n cred.pendingToken = params.pendingToken;\n }\n }\n else if (params.oauthToken && params.oauthTokenSecret) {\n // OAuth 1 and OAuth token with token secret\n cred.accessToken = params.oauthToken;\n cred.secret = params.oauthTokenSecret;\n }\n else {\n _fail(\"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\n }\n return cred;\n }\n /** {@inheritdoc AuthCredential.toJSON} */\n toJSON() {\n return {\n idToken: this.idToken,\n accessToken: this.accessToken,\n secret: this.secret,\n nonce: this.nonce,\n pendingToken: this.pendingToken,\n providerId: this.providerId,\n signInMethod: this.signInMethod\n };\n }\n /**\n * Static method to deserialize a JSON representation of an object into an\n * {@link AuthCredential}.\n *\n * @param json - Input can be either Object or the stringified representation of the object.\n * When string is provided, JSON.parse would be called first.\n *\n * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.\n */\n static fromJSON(json) {\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\n const { providerId, signInMethod, ...rest } = obj;\n if (!providerId || !signInMethod) {\n return null;\n }\n const cred = new OAuthCredential(providerId, signInMethod);\n cred.idToken = rest.idToken || undefined;\n cred.accessToken = rest.accessToken || undefined;\n cred.secret = rest.secret;\n cred.nonce = rest.nonce;\n cred.pendingToken = rest.pendingToken || null;\n return cred;\n }\n /** @internal */\n _getIdTokenResponse(auth) {\n const request = this.buildRequest();\n return signInWithIdp(auth, request);\n }\n /** @internal */\n _linkToIdToken(auth, idToken) {\n const request = this.buildRequest();\n request.idToken = idToken;\n return signInWithIdp(auth, request);\n }\n /** @internal */\n _getReauthenticationResolver(auth) {\n const request = this.buildRequest();\n request.autoCreate = false;\n return signInWithIdp(auth, request);\n }\n buildRequest() {\n const request = {\n requestUri: IDP_REQUEST_URI$1,\n returnSecureToken: true\n };\n if (this.pendingToken) {\n request.pendingToken = this.pendingToken;\n }\n else {\n const postBody = {};\n if (this.idToken) {\n postBody['id_token'] = this.idToken;\n }\n if (this.accessToken) {\n postBody['access_token'] = this.accessToken;\n }\n if (this.secret) {\n postBody['oauth_token_secret'] = this.secret;\n }\n postBody['providerId'] = this.providerId;\n if (this.nonce && !this.pendingToken) {\n postBody['nonce'] = this.nonce;\n }\n request.postBody = querystring(postBody);\n }\n return request;\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nasync function sendPhoneVerificationCode(auth, request) {\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:sendVerificationCode\" /* Endpoint.SEND_VERIFICATION_CODE */, _addTidIfNecessary(auth, request));\n}\nasync function signInWithPhoneNumber$1(auth, request) {\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithPhoneNumber\" /* Endpoint.SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, request));\n}\nasync function linkWithPhoneNumber$1(auth, request) {\n const response = await _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithPhoneNumber\" /* Endpoint.SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, request));\n if (response.temporaryProof) {\n throw _makeTaggedError(auth, \"account-exists-with-different-credential\" /* AuthErrorCode.NEED_CONFIRMATION */, response);\n }\n return response;\n}\nconst VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_ = {\n [\"USER_NOT_FOUND\" /* ServerError.USER_NOT_FOUND */]: \"user-not-found\" /* AuthErrorCode.USER_DELETED */\n};\nasync function verifyPhoneNumberForExisting(auth, request) {\n const apiRequest = {\n ...request,\n operation: 'REAUTH'\n };\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_);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents the credentials returned by {@link PhoneAuthProvider}.\n *\n * @public\n */\nclass PhoneAuthCredential extends AuthCredential {\n constructor(params) {\n super(\"phone\" /* ProviderId.PHONE */, \"phone\" /* SignInMethod.PHONE */);\n this.params = params;\n }\n /** @internal */\n static _fromVerification(verificationId, verificationCode) {\n return new PhoneAuthCredential({ verificationId, verificationCode });\n }\n /** @internal */\n static _fromTokenResponse(phoneNumber, temporaryProof) {\n return new PhoneAuthCredential({ phoneNumber, temporaryProof });\n }\n /** @internal */\n _getIdTokenResponse(auth) {\n return signInWithPhoneNumber$1(auth, this._makeVerificationRequest());\n }\n /** @internal */\n _linkToIdToken(auth, idToken) {\n return linkWithPhoneNumber$1(auth, {\n idToken,\n ...this._makeVerificationRequest()\n });\n }\n /** @internal */\n _getReauthenticationResolver(auth) {\n return verifyPhoneNumberForExisting(auth, this._makeVerificationRequest());\n }\n /** @internal */\n _makeVerificationRequest() {\n const { temporaryProof, phoneNumber, verificationId, verificationCode } = this.params;\n if (temporaryProof && phoneNumber) {\n return { temporaryProof, phoneNumber };\n }\n return {\n sessionInfo: verificationId,\n code: verificationCode\n };\n }\n /** {@inheritdoc AuthCredential.toJSON} */\n toJSON() {\n const obj = {\n providerId: this.providerId\n };\n if (this.params.phoneNumber) {\n obj.phoneNumber = this.params.phoneNumber;\n }\n if (this.params.temporaryProof) {\n obj.temporaryProof = this.params.temporaryProof;\n }\n if (this.params.verificationCode) {\n obj.verificationCode = this.params.verificationCode;\n }\n if (this.params.verificationId) {\n obj.verificationId = this.params.verificationId;\n }\n return obj;\n }\n /** Generates a phone credential based on a plain object or a JSON string. */\n static fromJSON(json) {\n if (typeof json === 'string') {\n json = JSON.parse(json);\n }\n const { verificationId, verificationCode, phoneNumber, temporaryProof } = json;\n if (!verificationCode &&\n !verificationId &&\n !phoneNumber &&\n !temporaryProof) {\n return null;\n }\n return new PhoneAuthCredential({\n verificationId,\n verificationCode,\n phoneNumber,\n temporaryProof\n });\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Maps the mode string in action code URL to Action Code Info operation.\n *\n * @param mode\n */\nfunction parseMode(mode) {\n switch (mode) {\n case 'recoverEmail':\n return \"RECOVER_EMAIL\" /* ActionCodeOperation.RECOVER_EMAIL */;\n case 'resetPassword':\n return \"PASSWORD_RESET\" /* ActionCodeOperation.PASSWORD_RESET */;\n case 'signIn':\n return \"EMAIL_SIGNIN\" /* ActionCodeOperation.EMAIL_SIGNIN */;\n case 'verifyEmail':\n return \"VERIFY_EMAIL\" /* ActionCodeOperation.VERIFY_EMAIL */;\n case 'verifyAndChangeEmail':\n return \"VERIFY_AND_CHANGE_EMAIL\" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */;\n case 'revertSecondFactorAddition':\n return \"REVERT_SECOND_FACTOR_ADDITION\" /* ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION */;\n default:\n return null;\n }\n}\n/**\n * Helper to parse FDL links\n *\n * @param url\n */\nfunction parseDeepLink(url) {\n const link = querystringDecode(extractQuerystring(url))['link'];\n // Double link case (automatic redirect).\n const doubleDeepLink = link\n ? querystringDecode(extractQuerystring(link))['deep_link_id']\n : null;\n // iOS custom scheme links.\n const iOSDeepLink = querystringDecode(extractQuerystring(url))['deep_link_id'];\n const iOSDoubleDeepLink = iOSDeepLink\n ? querystringDecode(extractQuerystring(iOSDeepLink))['link']\n : null;\n return iOSDoubleDeepLink || iOSDeepLink || doubleDeepLink || link || url;\n}\n/**\n * A utility class to parse email action URLs such as password reset, email verification,\n * email link sign in, etc.\n *\n * @public\n */\nclass ActionCodeURL {\n /**\n * @param actionLink - The link from which to extract the URL.\n * @returns The {@link ActionCodeURL} object, or null if the link is invalid.\n *\n * @internal\n */\n constructor(actionLink) {\n const searchParams = querystringDecode(extractQuerystring(actionLink));\n const apiKey = searchParams[\"apiKey\" /* QueryField.API_KEY */] ?? null;\n const code = searchParams[\"oobCode\" /* QueryField.CODE */] ?? null;\n const operation = parseMode(searchParams[\"mode\" /* QueryField.MODE */] ?? null);\n // Validate API key, code and mode.\n _assert(apiKey && code && operation, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\n this.apiKey = apiKey;\n this.operation = operation;\n this.code = code;\n this.continueUrl = searchParams[\"continueUrl\" /* QueryField.CONTINUE_URL */] ?? null;\n this.languageCode = searchParams[\"lang\" /* QueryField.LANGUAGE_CODE */] ?? null;\n this.tenantId = searchParams[\"tenantId\" /* QueryField.TENANT_ID */] ?? null;\n }\n /**\n * Parses the email action link string and returns an {@link ActionCodeURL} if the link is valid,\n * otherwise returns null.\n *\n * @param link - The email action link string.\n * @returns The {@link ActionCodeURL} object, or null if the link is invalid.\n *\n * @public\n */\n static parseLink(link) {\n const actionLink = parseDeepLink(link);\n try {\n return new ActionCodeURL(actionLink);\n }\n catch {\n return null;\n }\n }\n}\n/**\n * Parses the email action link string and returns an {@link ActionCodeURL} if\n * the link is valid, otherwise returns null.\n *\n * @public\n */\nfunction parseActionCodeURL(link) {\n return ActionCodeURL.parseLink(link);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Provider for generating {@link EmailAuthCredential}.\n *\n * @public\n */\nclass EmailAuthProvider {\n constructor() {\n /**\n * Always set to {@link ProviderId}.PASSWORD, even for email link.\n */\n this.providerId = EmailAuthProvider.PROVIDER_ID;\n }\n /**\n * Initialize an {@link AuthCredential} using an email and password.\n *\n * @example\n * ```javascript\n * const authCredential = EmailAuthProvider.credential(email, password);\n * const userCredential = await signInWithCredential(auth, authCredential);\n * ```\n *\n * @example\n * ```javascript\n * const userCredential = await signInWithEmailAndPassword(auth, email, password);\n * ```\n *\n * @param email - Email address.\n * @param password - User account password.\n * @returns The auth provider credential.\n */\n static credential(email, password) {\n return EmailAuthCredential._fromEmailAndPassword(email, password);\n }\n /**\n * Initialize an {@link AuthCredential} using an email and an email link after a sign in with\n * email link operation.\n *\n * @example\n * ```javascript\n * const authCredential = EmailAuthProvider.credentialWithLink(auth, email, emailLink);\n * const userCredential = await signInWithCredential(auth, authCredential);\n * ```\n *\n * @example\n * ```javascript\n * await sendSignInLinkToEmail(auth, email);\n * // Obtain emailLink from user.\n * const userCredential = await signInWithEmailLink(auth, email, emailLink);\n * ```\n *\n * @param auth - The {@link Auth} instance used to verify the link.\n * @param email - Email address.\n * @param emailLink - Sign-in email link.\n * @returns - The auth provider credential.\n */\n static credentialWithLink(email, emailLink) {\n const actionCodeUrl = ActionCodeURL.parseLink(emailLink);\n _assert(actionCodeUrl, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\n return EmailAuthCredential._fromEmailAndCode(email, actionCodeUrl.code, actionCodeUrl.tenantId);\n }\n}\n/**\n * Always set to {@link ProviderId}.PASSWORD, even for email link.\n */\nEmailAuthProvider.PROVIDER_ID = \"password\" /* ProviderId.PASSWORD */;\n/**\n * Always set to {@link SignInMethod}.EMAIL_PASSWORD.\n */\nEmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD = \"password\" /* SignInMethod.EMAIL_PASSWORD */;\n/**\n * Always set to {@link SignInMethod}.EMAIL_LINK.\n */\nEmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD = \"emailLink\" /* SignInMethod.EMAIL_LINK */;\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * The base class for all Federated providers (OAuth (including OIDC), SAML).\n *\n * This class is not meant to be instantiated directly.\n *\n * @public\n */\nclass FederatedAuthProvider {\n /**\n * Constructor for generic OAuth providers.\n *\n * @param providerId - Provider for which credentials should be generated.\n */\n constructor(providerId) {\n this.providerId = providerId;\n /** @internal */\n this.defaultLanguageCode = null;\n /** @internal */\n this.customParameters = {};\n }\n /**\n * Set the language gode.\n *\n * @param languageCode - language code\n */\n setDefaultLanguage(languageCode) {\n this.defaultLanguageCode = languageCode;\n }\n /**\n * Sets the OAuth custom parameters to pass in an OAuth request for popup and redirect sign-in\n * operations.\n *\n * @remarks\n * For a detailed list, check the reserved required OAuth 2.0 parameters such as `client_id`,\n * `redirect_uri`, `scope`, `response_type`, and `state` are not allowed and will be ignored.\n *\n * @param customOAuthParameters - The custom OAuth parameters to pass in the OAuth request.\n */\n setCustomParameters(customOAuthParameters) {\n this.customParameters = customOAuthParameters;\n return this;\n }\n /**\n * Retrieve the current list of {@link CustomParameters}.\n */\n getCustomParameters() {\n return this.customParameters;\n }\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Common code to all OAuth providers. This is separate from the\n * {@link OAuthProvider} so that child providers (like\n * {@link GoogleAuthProvider}) don't inherit the `credential` instance method.\n * Instead, they rely on a static `credential` method.\n */\nclass BaseOAuthProvider extends FederatedAuthProvider {\n constructor() {\n super(...arguments);\n /** @internal */\n this.scopes = [];\n }\n /**\n * Add an OAuth scope to the credential.\n *\n * @param scope - Provider OAuth scope to add.\n */\n addScope(scope) {\n // If not already added, add scope to list.\n if (!this.scopes.includes(scope)) {\n this.scopes.push(scope);\n }\n return this;\n }\n /**\n * Retrieve the current list of OAuth scopes.\n */\n getScopes() {\n return [...this.scopes];\n }\n}\n/**\n * Provider for generating generic {@link OAuthCredential}.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new OAuthProvider('google.com');\n * // Start a sign in process for an unauthenticated user.\n * provider.addScope('profile');\n * provider.addScope('email');\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a OAuth Access Token for the provider.\n * const credential = provider.credentialFromResult(auth, result);\n * const token = credential.accessToken;\n * }\n * ```\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new OAuthProvider('google.com');\n * provider.addScope('profile');\n * provider.addScope('email');\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a OAuth Access Token for the provider.\n * const credential = provider.credentialFromResult(auth, result);\n * const token = credential.accessToken;\n * ```\n * @public\n */\nclass OAuthProvider extends BaseOAuthProvider {\n /**\n * Creates an {@link OAuthCredential} from a JSON string or a plain object.\n * @param json - A plain object or a JSON string\n */\n static credentialFromJSON(json) {\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\n _assert('providerId' in obj && 'signInMethod' in obj, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\n return OAuthCredential._fromParams(obj);\n }\n /**\n * Creates a {@link OAuthCredential} from a generic OAuth provider's access token or ID token.\n *\n * @remarks\n * The raw nonce is required when an ID token with a nonce field is provided. The SHA-256 hash of\n * the raw nonce must match the nonce field in the ID token.\n *\n * @example\n * ```javascript\n * // `googleUser` from the onsuccess Google Sign In callback.\n * // Initialize a generate OAuth provider with a `google.com` providerId.\n * const provider = new OAuthProvider('google.com');\n * const credential = provider.credential({\n * idToken: googleUser.getAuthResponse().id_token,\n * });\n * const result = await signInWithCredential(credential);\n * ```\n *\n * @param params - Either the options object containing the ID token, access token and raw nonce\n * or the ID token string.\n */\n credential(params) {\n return this._credential({ ...params, nonce: params.rawNonce });\n }\n /** An internal credential method that accepts more permissive options */\n _credential(params) {\n _assert(params.idToken || params.accessToken, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\n // For OAuthCredential, sign in method is same as providerId.\n return OAuthCredential._fromParams({\n ...params,\n providerId: this.providerId,\n signInMethod: this.providerId\n });\n }\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(userCredential) {\n return OAuthProvider.oauthCredentialFromTaggedObject(userCredential);\n }\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error) {\n return OAuthProvider.oauthCredentialFromTaggedObject((error.customData || {}));\n }\n static oauthCredentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\n if (!tokenResponse) {\n return null;\n }\n const { oauthIdToken, oauthAccessToken, oauthTokenSecret, pendingToken, nonce, providerId } = tokenResponse;\n if (!oauthAccessToken &&\n !oauthTokenSecret &&\n !oauthIdToken &&\n !pendingToken) {\n return null;\n }\n if (!providerId) {\n return null;\n }\n try {\n return new OAuthProvider(providerId)._credential({\n idToken: oauthIdToken,\n accessToken: oauthAccessToken,\n nonce,\n pendingToken\n });\n }\n catch (e) {\n return null;\n }\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.FACEBOOK.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new FacebookAuthProvider();\n * // Start a sign in process for an unauthenticated user.\n * provider.addScope('user_birthday');\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Facebook Access Token.\n * const credential = FacebookAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * }\n * ```\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new FacebookAuthProvider();\n * provider.addScope('user_birthday');\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a Facebook Access Token.\n * const credential = FacebookAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * ```\n *\n * @public\n */\nclass FacebookAuthProvider extends BaseOAuthProvider {\n constructor() {\n super(\"facebook.com\" /* ProviderId.FACEBOOK */);\n }\n /**\n * Creates a credential for Facebook.\n *\n * @example\n * ```javascript\n * // `event` from the Facebook auth.authResponseChange callback.\n * const credential = FacebookAuthProvider.credential(event.authResponse.accessToken);\n * const result = await signInWithCredential(credential);\n * ```\n *\n * @param accessToken - Facebook access token.\n */\n static credential(accessToken) {\n return OAuthCredential._fromParams({\n providerId: FacebookAuthProvider.PROVIDER_ID,\n signInMethod: FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD,\n accessToken\n });\n }\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(userCredential) {\n return FacebookAuthProvider.credentialFromTaggedObject(userCredential);\n }\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error) {\n return FacebookAuthProvider.credentialFromTaggedObject((error.customData || {}));\n }\n static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\n if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {\n return null;\n }\n if (!tokenResponse.oauthAccessToken) {\n return null;\n }\n try {\n return FacebookAuthProvider.credential(tokenResponse.oauthAccessToken);\n }\n catch {\n return null;\n }\n }\n}\n/** Always set to {@link SignInMethod}.FACEBOOK. */\nFacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD = \"facebook.com\" /* SignInMethod.FACEBOOK */;\n/** Always set to {@link ProviderId}.FACEBOOK. */\nFacebookAuthProvider.PROVIDER_ID = \"facebook.com\" /* ProviderId.FACEBOOK */;\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.GOOGLE.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new GoogleAuthProvider();\n * // Start a sign in process for an unauthenticated user.\n * provider.addScope('profile');\n * provider.addScope('email');\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Google Access Token.\n * const credential = GoogleAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * }\n * ```\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new GoogleAuthProvider();\n * provider.addScope('profile');\n * provider.addScope('email');\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a Google Access Token.\n * const credential = GoogleAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * ```\n *\n * @public\n */\nclass GoogleAuthProvider extends BaseOAuthProvider {\n constructor() {\n super(\"google.com\" /* ProviderId.GOOGLE */);\n this.addScope('profile');\n }\n /**\n * Creates a credential for Google. At least one of ID token and access token is required.\n *\n * @example\n * ```javascript\n * // \\`googleUser\\` from the onsuccess Google Sign In callback.\n * const credential = GoogleAuthProvider.credential(googleUser.getAuthResponse().id_token);\n * const result = await signInWithCredential(credential);\n * ```\n *\n * @param idToken - Google ID token.\n * @param accessToken - Google access token.\n */\n static credential(idToken, accessToken) {\n return OAuthCredential._fromParams({\n providerId: GoogleAuthProvider.PROVIDER_ID,\n signInMethod: GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD,\n idToken,\n accessToken\n });\n }\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(userCredential) {\n return GoogleAuthProvider.credentialFromTaggedObject(userCredential);\n }\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error) {\n return GoogleAuthProvider.credentialFromTaggedObject((error.customData || {}));\n }\n static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\n if (!tokenResponse) {\n return null;\n }\n const { oauthIdToken, oauthAccessToken } = tokenResponse;\n if (!oauthIdToken && !oauthAccessToken) {\n // This could be an oauth 1 credential or a phone credential\n return null;\n }\n try {\n return GoogleAuthProvider.credential(oauthIdToken, oauthAccessToken);\n }\n catch {\n return null;\n }\n }\n}\n/** Always set to {@link SignInMethod}.GOOGLE. */\nGoogleAuthProvider.GOOGLE_SIGN_IN_METHOD = \"google.com\" /* SignInMethod.GOOGLE */;\n/** Always set to {@link ProviderId}.GOOGLE. */\nGoogleAuthProvider.PROVIDER_ID = \"google.com\" /* ProviderId.GOOGLE */;\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.GITHUB.\n *\n * @remarks\n * GitHub requires an OAuth 2.0 redirect, so you can either handle the redirect directly, or use\n * the {@link signInWithPopup} handler:\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new GithubAuthProvider();\n * // Start a sign in process for an unauthenticated user.\n * provider.addScope('repo');\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a GitHub Access Token.\n * const credential = GithubAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * }\n * ```\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new GithubAuthProvider();\n * provider.addScope('repo');\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a GitHub Access Token.\n * const credential = GithubAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * ```\n * @public\n */\nclass GithubAuthProvider extends BaseOAuthProvider {\n constructor() {\n super(\"github.com\" /* ProviderId.GITHUB */);\n }\n /**\n * Creates a credential for GitHub.\n *\n * @param accessToken - GitHub access token.\n */\n static credential(accessToken) {\n return OAuthCredential._fromParams({\n providerId: GithubAuthProvider.PROVIDER_ID,\n signInMethod: GithubAuthProvider.GITHUB_SIGN_IN_METHOD,\n accessToken\n });\n }\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(userCredential) {\n return GithubAuthProvider.credentialFromTaggedObject(userCredential);\n }\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error) {\n return GithubAuthProvider.credentialFromTaggedObject((error.customData || {}));\n }\n static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\n if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {\n return null;\n }\n if (!tokenResponse.oauthAccessToken) {\n return null;\n }\n try {\n return GithubAuthProvider.credential(tokenResponse.oauthAccessToken);\n }\n catch {\n return null;\n }\n }\n}\n/** Always set to {@link SignInMethod}.GITHUB. */\nGithubAuthProvider.GITHUB_SIGN_IN_METHOD = \"github.com\" /* SignInMethod.GITHUB */;\n/** Always set to {@link ProviderId}.GITHUB. */\nGithubAuthProvider.PROVIDER_ID = \"github.com\" /* ProviderId.GITHUB */;\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents the SAML credentials returned by an {@link SAMLAuthProvider}.\n *\n * @public\n */\nconst IDP_REQUEST_URI = 'http://localhost';\n/**\n * @public\n */\nclass SAMLAuthCredential extends AuthCredential {\n /** @internal */\n constructor(providerId, pendingToken) {\n super(providerId, providerId);\n this.pendingToken = pendingToken;\n }\n /** @internal */\n _getIdTokenResponse(auth) {\n const request = this.buildRequest();\n return signInWithIdp(auth, request);\n }\n /** @internal */\n _linkToIdToken(auth, idToken) {\n const request = this.buildRequest();\n request.idToken = idToken;\n return signInWithIdp(auth, request);\n }\n /** @internal */\n _getReauthenticationResolver(auth) {\n const request = this.buildRequest();\n request.autoCreate = false;\n return signInWithIdp(auth, request);\n }\n /** {@inheritdoc AuthCredential.toJSON} */\n toJSON() {\n return {\n signInMethod: this.signInMethod,\n providerId: this.providerId,\n pendingToken: this.pendingToken\n };\n }\n /**\n * Static method to deserialize a JSON representation of an object into an\n * {@link AuthCredential}.\n *\n * @param json - Input can be either Object or the stringified representation of the object.\n * When string is provided, JSON.parse would be called first.\n *\n * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.\n */\n static fromJSON(json) {\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\n const { providerId, signInMethod, pendingToken } = obj;\n if (!providerId ||\n !signInMethod ||\n !pendingToken ||\n providerId !== signInMethod) {\n return null;\n }\n return new SAMLAuthCredential(providerId, pendingToken);\n }\n /**\n * Helper static method to avoid exposing the constructor to end users.\n *\n * @internal\n */\n static _create(providerId, pendingToken) {\n return new SAMLAuthCredential(providerId, pendingToken);\n }\n buildRequest() {\n return {\n requestUri: IDP_REQUEST_URI,\n returnSecureToken: true,\n pendingToken: this.pendingToken\n };\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst SAML_PROVIDER_PREFIX = 'saml.';\n/**\n * An {@link AuthProvider} for SAML.\n *\n * @public\n */\nclass SAMLAuthProvider extends FederatedAuthProvider {\n /**\n * Constructor. The providerId must start with \"saml.\"\n * @param providerId - SAML provider ID.\n */\n constructor(providerId) {\n _assert(providerId.startsWith(SAML_PROVIDER_PREFIX), \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\n super(providerId);\n }\n /**\n * Generates an {@link AuthCredential} from a {@link UserCredential} after a\n * successful SAML flow completes.\n *\n * @remarks\n *\n * For example, to get an {@link AuthCredential}, you could write the\n * following code:\n *\n * ```js\n * const userCredential = await signInWithPopup(auth, samlProvider);\n * const credential = SAMLAuthProvider.credentialFromResult(userCredential);\n * ```\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(userCredential) {\n return SAMLAuthProvider.samlCredentialFromTaggedObject(userCredential);\n }\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error) {\n return SAMLAuthProvider.samlCredentialFromTaggedObject((error.customData || {}));\n }\n /**\n * Creates an {@link AuthCredential} from a JSON string or a plain object.\n * @param json - A plain object or a JSON string\n */\n static credentialFromJSON(json) {\n const credential = SAMLAuthCredential.fromJSON(json);\n _assert(credential, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\n return credential;\n }\n static samlCredentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\n if (!tokenResponse) {\n return null;\n }\n const { pendingToken, providerId } = tokenResponse;\n if (!pendingToken || !providerId) {\n return null;\n }\n try {\n return SAMLAuthCredential._create(providerId, pendingToken);\n }\n catch (e) {\n return null;\n }\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.TWITTER.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new TwitterAuthProvider();\n * // Start a sign in process for an unauthenticated user.\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Twitter Access Token and Secret.\n * const credential = TwitterAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * const secret = credential.secret;\n * }\n * ```\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new TwitterAuthProvider();\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a Twitter Access Token and Secret.\n * const credential = TwitterAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * const secret = credential.secret;\n * ```\n *\n * @public\n */\nclass TwitterAuthProvider extends BaseOAuthProvider {\n constructor() {\n super(\"twitter.com\" /* ProviderId.TWITTER */);\n }\n /**\n * Creates a credential for Twitter.\n *\n * @param token - Twitter access token.\n * @param secret - Twitter secret.\n */\n static credential(token, secret) {\n return OAuthCredential._fromParams({\n providerId: TwitterAuthProvider.PROVIDER_ID,\n signInMethod: TwitterAuthProvider.TWITTER_SIGN_IN_METHOD,\n oauthToken: token,\n oauthTokenSecret: secret\n });\n }\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(userCredential) {\n return TwitterAuthProvider.credentialFromTaggedObject(userCredential);\n }\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error) {\n return TwitterAuthProvider.credentialFromTaggedObject((error.customData || {}));\n }\n static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\n if (!tokenResponse) {\n return null;\n }\n const { oauthAccessToken, oauthTokenSecret } = tokenResponse;\n if (!oauthAccessToken || !oauthTokenSecret) {\n return null;\n }\n try {\n return TwitterAuthProvider.credential(oauthAccessToken, oauthTokenSecret);\n }\n catch {\n return null;\n }\n }\n}\n/** Always set to {@link SignInMethod}.TWITTER. */\nTwitterAuthProvider.TWITTER_SIGN_IN_METHOD = \"twitter.com\" /* SignInMethod.TWITTER */;\n/** Always set to {@link ProviderId}.TWITTER. */\nTwitterAuthProvider.PROVIDER_ID = \"twitter.com\" /* ProviderId.TWITTER */;\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nasync function signUp(auth, request) {\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signUp\" /* Endpoint.SIGN_UP */, _addTidIfNecessary(auth, request));\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass UserCredentialImpl {\n constructor(params) {\n this.user = params.user;\n this.providerId = params.providerId;\n this._tokenResponse = params._tokenResponse;\n this.operationType = params.operationType;\n }\n static async _fromIdTokenResponse(auth, operationType, idTokenResponse, isAnonymous = false) {\n const user = await UserImpl._fromIdTokenResponse(auth, idTokenResponse, isAnonymous);\n const providerId = providerIdForResponse(idTokenResponse);\n const userCred = new UserCredentialImpl({\n user,\n providerId,\n _tokenResponse: idTokenResponse,\n operationType\n });\n return userCred;\n }\n static async _forOperation(user, operationType, response) {\n await user._updateTokensIfNecessary(response, /* reload */ true);\n const providerId = providerIdForResponse(response);\n return new UserCredentialImpl({\n user,\n providerId,\n _tokenResponse: response,\n operationType\n });\n }\n}\nfunction providerIdForResponse(response) {\n if (response.providerId) {\n return response.providerId;\n }\n if ('phoneNumber' in response) {\n return \"phone\" /* ProviderId.PHONE */;\n }\n return null;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Asynchronously signs in as an anonymous user.\n *\n * @remarks\n * If there is already an anonymous user signed in, that user will be returned; otherwise, a\n * new anonymous user identity will be created and returned.\n *\n * This method is not supported by {@link Auth} instances created with a\n * {@link @firebase/app#FirebaseServerApp}.\n *\n * @param auth - The {@link Auth} instance.\n *\n * @public\n */\nasync function signInAnonymously(auth) {\n if (_isFirebaseServerApp(auth.app)) {\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\n }\n const authInternal = _castAuth(auth);\n await authInternal._initializationPromise;\n if (authInternal.currentUser?.isAnonymous) {\n // If an anonymous user is already signed in, no need to sign them in again.\n return new UserCredentialImpl({\n user: authInternal.currentUser,\n providerId: null,\n operationType: \"signIn\" /* OperationType.SIGN_IN */\n });\n }\n const response = await signUp(authInternal, {\n returnSecureToken: true\n });\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(authInternal, \"signIn\" /* OperationType.SIGN_IN */, response, true);\n await authInternal._updateCurrentUser(userCredential.user);\n return userCredential;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass MultiFactorError extends FirebaseError {\n constructor(auth, error, operationType, user) {\n super(error.code, error.message);\n this.operationType = operationType;\n this.user = user;\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, MultiFactorError.prototype);\n this.customData = {\n appName: auth.name,\n tenantId: auth.tenantId ?? undefined,\n _serverResponse: error.customData._serverResponse,\n operationType\n };\n }\n static _fromErrorAndOperation(auth, error, operationType, user) {\n return new MultiFactorError(auth, error, operationType, user);\n }\n}\nfunction _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential, user) {\n const idTokenProvider = operationType === \"reauthenticate\" /* OperationType.REAUTHENTICATE */\n ? credential._getReauthenticationResolver(auth)\n : credential._getIdTokenResponse(auth);\n return idTokenProvider.catch(error => {\n if (error.code === `auth/${\"multi-factor-auth-required\" /* AuthErrorCode.MFA_REQUIRED */}`) {\n throw MultiFactorError._fromErrorAndOperation(auth, error, operationType, user);\n }\n throw error;\n });\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Takes a set of UserInfo provider data and converts it to a set of names\n */\nfunction providerDataAsNames(providerData) {\n return new Set(providerData\n .map(({ providerId }) => providerId)\n .filter(pid => !!pid));\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Unlinks a provider from a user account.\n *\n * @param user - The user.\n * @param providerId - The provider to unlink.\n *\n * @public\n */\nasync function unlink(user, providerId) {\n const userInternal = getModularInstance(user);\n await _assertLinkedStatus(true, userInternal, providerId);\n const { providerUserInfo } = await deleteLinkedAccounts(userInternal.auth, {\n idToken: await userInternal.getIdToken(),\n deleteProvider: [providerId]\n });\n const providersLeft = providerDataAsNames(providerUserInfo || []);\n userInternal.providerData = userInternal.providerData.filter(pd => providersLeft.has(pd.providerId));\n if (!providersLeft.has(\"phone\" /* ProviderId.PHONE */)) {\n userInternal.phoneNumber = null;\n }\n await userInternal.auth._persistUserIfCurrent(userInternal);\n return userInternal;\n}\nasync function _link$1(user, credential, bypassAuthState = false) {\n const response = await _logoutIfInvalidated(user, credential._linkToIdToken(user.auth, await user.getIdToken()), bypassAuthState);\n return UserCredentialImpl._forOperation(user, \"link\" /* OperationType.LINK */, response);\n}\nasync function _assertLinkedStatus(expected, user, provider) {\n await _reloadWithoutSaving(user);\n const providerIds = providerDataAsNames(user.providerData);\n const code = expected === false\n ? \"provider-already-linked\" /* AuthErrorCode.PROVIDER_ALREADY_LINKED */\n : \"no-such-provider\" /* AuthErrorCode.NO_SUCH_PROVIDER */;\n _assert(providerIds.has(provider) === expected, user.auth, code);\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nasync function _reauthenticate(user, credential, bypassAuthState = false) {\n const { auth } = user;\n if (_isFirebaseServerApp(auth.app)) {\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\n }\n const operationType = \"reauthenticate\" /* OperationType.REAUTHENTICATE */;\n try {\n const response = await _logoutIfInvalidated(user, _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential, user), bypassAuthState);\n _assert(response.idToken, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n const parsed = _parseToken(response.idToken);\n _assert(parsed, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n const { sub: localId } = parsed;\n _assert(user.uid === localId, auth, \"user-mismatch\" /* AuthErrorCode.USER_MISMATCH */);\n return UserCredentialImpl._forOperation(user, operationType, response);\n }\n catch (e) {\n // Convert user deleted error into user mismatch\n if (e?.code === `auth/${\"user-not-found\" /* AuthErrorCode.USER_DELETED */}`) {\n _fail(auth, \"user-mismatch\" /* AuthErrorCode.USER_MISMATCH */);\n }\n throw e;\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nasync function _signInWithCredential(auth, credential, bypassAuthState = false) {\n if (_isFirebaseServerApp(auth.app)) {\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\n }\n const operationType = \"signIn\" /* OperationType.SIGN_IN */;\n const response = await _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential);\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(auth, operationType, response);\n if (!bypassAuthState) {\n await auth._updateCurrentUser(userCredential.user);\n }\n return userCredential;\n}\n/**\n * Asynchronously signs in with the given credentials.\n *\n * @remarks\n * An {@link AuthProvider} can be used to generate the credential.\n *\n * This method is not supported by {@link Auth} instances created with a\n * {@link @firebase/app#FirebaseServerApp}.\n *\n * @param auth - The {@link Auth} instance.\n * @param credential - The auth credential.\n *\n * @public\n */\nasync function signInWithCredential(auth, credential) {\n return _signInWithCredential(_castAuth(auth), credential);\n}\n/**\n * Links the user account with the given credentials.\n *\n * @remarks\n * An {@link AuthProvider} can be used to generate the credential.\n *\n * @param user - The user.\n * @param credential - The auth credential.\n *\n * @public\n */\nasync function linkWithCredential(user, credential) {\n const userInternal = getModularInstance(user);\n await _assertLinkedStatus(false, userInternal, credential.providerId);\n return _link$1(userInternal, credential);\n}\n/**\n * Re-authenticates a user using a fresh credential.\n *\n * @remarks\n * Use before operations such as {@link updatePassword} that require tokens from recent sign-in\n * attempts. This method can be used to recover from a `CREDENTIAL_TOO_OLD_LOGIN_AGAIN` error\n * or a `TOKEN_EXPIRED` error.\n *\n * This method is not supported on any {@link User} signed in by {@link Auth} instances\n * created with a {@link @firebase/app#FirebaseServerApp}.\n *\n * @param user - The user.\n * @param credential - The auth credential.\n *\n * @public\n */\nasync function reauthenticateWithCredential(user, credential) {\n return _reauthenticate(getModularInstance(user), credential);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nasync function signInWithCustomToken$1(auth, request) {\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithCustomToken\" /* Endpoint.SIGN_IN_WITH_CUSTOM_TOKEN */, _addTidIfNecessary(auth, request));\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Asynchronously signs in using a custom token.\n *\n * @remarks\n * Custom tokens are used to integrate Firebase Auth with existing auth systems, and must\n * be generated by an auth backend using the\n * {@link https://firebase.google.com/docs/reference/admin/node/admin.auth.Auth#createcustomtoken | createCustomToken}\n * method in the {@link https://firebase.google.com/docs/auth/admin | Admin SDK} .\n *\n * Fails with an error if the token is invalid, expired, or not accepted by the Firebase Auth service.\n *\n * This method is not supported by {@link Auth} instances created with a\n * {@link @firebase/app#FirebaseServerApp}.\n *\n * @param auth - The {@link Auth} instance.\n * @param customToken - The custom token to sign in with.\n *\n * @public\n */\nasync function signInWithCustomToken(auth, customToken) {\n if (_isFirebaseServerApp(auth.app)) {\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\n }\n const authInternal = _castAuth(auth);\n const response = await signInWithCustomToken$1(authInternal, {\n token: customToken,\n returnSecureToken: true\n });\n const cred = await UserCredentialImpl._fromIdTokenResponse(authInternal, \"signIn\" /* OperationType.SIGN_IN */, response);\n await authInternal._updateCurrentUser(cred.user);\n return cred;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass MultiFactorInfoImpl {\n constructor(factorId, response) {\n this.factorId = factorId;\n this.uid = response.mfaEnrollmentId;\n this.enrollmentTime = new Date(response.enrolledAt).toUTCString();\n this.displayName = response.displayName;\n }\n static _fromServerResponse(auth, enrollment) {\n if ('phoneInfo' in enrollment) {\n return PhoneMultiFactorInfoImpl._fromServerResponse(auth, enrollment);\n }\n else if ('totpInfo' in enrollment) {\n return TotpMultiFactorInfoImpl._fromServerResponse(auth, enrollment);\n }\n return _fail(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n }\n}\nclass PhoneMultiFactorInfoImpl extends MultiFactorInfoImpl {\n constructor(response) {\n super(\"phone\" /* FactorId.PHONE */, response);\n this.phoneNumber = response.phoneInfo;\n }\n static _fromServerResponse(_auth, enrollment) {\n return new PhoneMultiFactorInfoImpl(enrollment);\n }\n}\nclass TotpMultiFactorInfoImpl extends MultiFactorInfoImpl {\n constructor(response) {\n super(\"totp\" /* FactorId.TOTP */, response);\n }\n static _fromServerResponse(_auth, enrollment) {\n return new TotpMultiFactorInfoImpl(enrollment);\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nfunction _setActionCodeSettingsOnRequest(auth, request, actionCodeSettings) {\n _assert(actionCodeSettings.url?.length > 0, auth, \"invalid-continue-uri\" /* AuthErrorCode.INVALID_CONTINUE_URI */);\n _assert(typeof actionCodeSettings.dynamicLinkDomain === 'undefined' ||\n actionCodeSettings.dynamicLinkDomain.length > 0, auth, \"invalid-dynamic-link-domain\" /* AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN */);\n _assert(typeof actionCodeSettings.linkDomain === 'undefined' ||\n actionCodeSettings.linkDomain.length > 0, auth, \"invalid-hosting-link-domain\" /* AuthErrorCode.INVALID_HOSTING_LINK_DOMAIN */);\n request.continueUrl = actionCodeSettings.url;\n request.dynamicLinkDomain = actionCodeSettings.dynamicLinkDomain;\n request.linkDomain = actionCodeSettings.linkDomain;\n request.canHandleCodeInApp = actionCodeSettings.handleCodeInApp;\n if (actionCodeSettings.iOS) {\n _assert(actionCodeSettings.iOS.bundleId.length > 0, auth, \"missing-ios-bundle-id\" /* AuthErrorCode.MISSING_IOS_BUNDLE_ID */);\n request.iOSBundleId = actionCodeSettings.iOS.bundleId;\n }\n if (actionCodeSettings.android) {\n _assert(actionCodeSettings.android.packageName.length > 0, auth, \"missing-android-pkg-name\" /* AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME */);\n request.androidInstallApp = actionCodeSettings.android.installApp;\n request.androidMinimumVersionCode =\n actionCodeSettings.android.minimumVersion;\n request.androidPackageName = actionCodeSettings.android.packageName;\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Updates the password policy cached in the {@link Auth} instance if a policy is already\n * cached for the project or tenant.\n *\n * @remarks\n * We only fetch the password policy if the password did not meet policy requirements and\n * there is an existing policy cached. A developer must call validatePassword at least\n * once for the cache to be automatically updated.\n *\n * @param auth - The {@link Auth} instance.\n *\n * @private\n */\nasync function recachePasswordPolicy(auth) {\n const authInternal = _castAuth(auth);\n if (authInternal._getPasswordPolicyInternal()) {\n await authInternal._updatePasswordPolicy();\n }\n}\n/**\n * Sends a password reset email to the given email address. This method does not throw an error when\n * there's no user account with the given email address and\n * {@link https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection | Email Enumeration Protection}\n * is enabled.\n *\n * @remarks\n * To complete the password reset, call {@link confirmPasswordReset} with the code supplied in\n * the email sent to the user, along with the new password specified by the user.\n *\n * @example\n * ```javascript\n * const actionCodeSettings = {\n * url: 'https://www.example.com/?email=user@example.com',\n * iOS: {\n * bundleId: 'com.example.ios'\n * },\n * android: {\n * packageName: 'com.example.android',\n * installApp: true,\n * minimumVersion: '12'\n * },\n * handleCodeInApp: true\n * };\n * await sendPasswordResetEmail(auth, 'user@example.com', actionCodeSettings);\n * // Obtain code from user.\n * await confirmPasswordReset('user@example.com', code);\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param email - The user's email address.\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\n *\n * @public\n */\nasync function sendPasswordResetEmail(auth, email, actionCodeSettings) {\n const authInternal = _castAuth(auth);\n const request = {\n requestType: \"PASSWORD_RESET\" /* ActionCodeOperation.PASSWORD_RESET */,\n email,\n clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */\n };\n if (actionCodeSettings) {\n _setActionCodeSettingsOnRequest(authInternal, request, actionCodeSettings);\n }\n await handleRecaptchaFlow(authInternal, request, \"getOobCode\" /* RecaptchaActionName.GET_OOB_CODE */, sendPasswordResetEmail$1, \"EMAIL_PASSWORD_PROVIDER\" /* RecaptchaAuthProvider.EMAIL_PASSWORD_PROVIDER */);\n}\n/**\n * Completes the password reset process, given a confirmation code and new password.\n *\n * @param auth - The {@link Auth} instance.\n * @param oobCode - A confirmation code sent to the user.\n * @param newPassword - The new password.\n *\n * @public\n */\nasync function confirmPasswordReset(auth, oobCode, newPassword) {\n await resetPassword(getModularInstance(auth), {\n oobCode,\n newPassword\n })\n .catch(async (error) => {\n if (error.code ===\n `auth/${\"password-does-not-meet-requirements\" /* AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS */}`) {\n void recachePasswordPolicy(auth);\n }\n throw error;\n });\n // Do not return the email.\n}\n/**\n * Applies a verification code sent to the user by email or other out-of-band mechanism.\n *\n * @param auth - The {@link Auth} instance.\n * @param oobCode - A verification code sent to the user.\n *\n * @public\n */\nasync function applyActionCode(auth, oobCode) {\n await applyActionCode$1(getModularInstance(auth), { oobCode });\n}\n/**\n * Checks a verification code sent to the user by email or other out-of-band mechanism.\n *\n * @returns metadata about the code.\n *\n * @param auth - The {@link Auth} instance.\n * @param oobCode - A verification code sent to the user.\n *\n * @public\n */\nasync function checkActionCode(auth, oobCode) {\n const authModular = getModularInstance(auth);\n const response = await resetPassword(authModular, { oobCode });\n // Email could be empty only if the request type is EMAIL_SIGNIN or\n // VERIFY_AND_CHANGE_EMAIL.\n // New email should not be empty if the request type is\n // VERIFY_AND_CHANGE_EMAIL.\n // Multi-factor info could not be empty if the request type is\n // REVERT_SECOND_FACTOR_ADDITION.\n const operation = response.requestType;\n _assert(operation, authModular, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n switch (operation) {\n case \"EMAIL_SIGNIN\" /* ActionCodeOperation.EMAIL_SIGNIN */:\n break;\n case \"VERIFY_AND_CHANGE_EMAIL\" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */:\n _assert(response.newEmail, authModular, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n break;\n case \"REVERT_SECOND_FACTOR_ADDITION\" /* ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION */:\n _assert(response.mfaInfo, authModular, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n // fall through\n default:\n _assert(response.email, authModular, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n }\n // The multi-factor info for revert second factor addition\n let multiFactorInfo = null;\n if (response.mfaInfo) {\n multiFactorInfo = MultiFactorInfoImpl._fromServerResponse(_castAuth(authModular), response.mfaInfo);\n }\n return {\n data: {\n email: (response.requestType === \"VERIFY_AND_CHANGE_EMAIL\" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */\n ? response.newEmail\n : response.email) || null,\n previousEmail: (response.requestType === \"VERIFY_AND_CHANGE_EMAIL\" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */\n ? response.email\n : response.newEmail) || null,\n multiFactorInfo\n },\n operation\n };\n}\n/**\n * Checks a password reset code sent to the user by email or other out-of-band mechanism.\n *\n * @returns the user's email address if valid.\n *\n * @param auth - The {@link Auth} instance.\n * @param code - A verification code sent to the user.\n *\n * @public\n */\nasync function verifyPasswordResetCode(auth, code) {\n const { data } = await checkActionCode(getModularInstance(auth), code);\n // Email should always be present since a code was sent to it\n return data.email;\n}\n/**\n * Creates a new user account associated with the specified email address and password.\n *\n * @remarks\n * On successful creation of the user account, this user will also be signed in to your application.\n *\n * User account creation can fail if the account already exists or the password is invalid.\n *\n * This method is not supported on {@link Auth} instances created with a\n * {@link @firebase/app#FirebaseServerApp}.\n *\n * Note: The email address acts as a unique identifier for the user and enables an email-based\n * password reset. This function will create a new user account and set the initial user password.\n *\n * @param auth - The {@link Auth} instance.\n * @param email - The user's email address.\n * @param password - The user's chosen password.\n *\n * @public\n */\nasync function createUserWithEmailAndPassword(auth, email, password) {\n if (_isFirebaseServerApp(auth.app)) {\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\n }\n const authInternal = _castAuth(auth);\n const request = {\n returnSecureToken: true,\n email,\n password,\n clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */\n };\n const signUpResponse = handleRecaptchaFlow(authInternal, request, \"signUpPassword\" /* RecaptchaActionName.SIGN_UP_PASSWORD */, signUp, \"EMAIL_PASSWORD_PROVIDER\" /* RecaptchaAuthProvider.EMAIL_PASSWORD_PROVIDER */);\n const response = await signUpResponse.catch(error => {\n if (error.code === `auth/${\"password-does-not-meet-requirements\" /* AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS */}`) {\n void recachePasswordPolicy(auth);\n }\n throw error;\n });\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(authInternal, \"signIn\" /* OperationType.SIGN_IN */, response);\n await authInternal._updateCurrentUser(userCredential.user);\n return userCredential;\n}\n/**\n * Asynchronously signs in using an email and password.\n *\n * @remarks\n * Fails with an error if the email address and password do not match. When\n * {@link https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection | Email Enumeration Protection}\n * is enabled, this method fails with \"auth/invalid-credential\" in case of an invalid\n * email/password.\n *\n * This method is not supported on {@link Auth} instances created with a\n * {@link @firebase/app#FirebaseServerApp}.\n *\n * Note: The user's password is NOT the password used to access the user's email account. The\n * email address serves as a unique identifier for the user, and the password is used to access\n * the user's account in your Firebase project. See also: {@link createUserWithEmailAndPassword}.\n *\n *\n * @param auth - The {@link Auth} instance.\n * @param email - The users email address.\n * @param password - The users password.\n *\n * @public\n */\nfunction signInWithEmailAndPassword(auth, email, password) {\n if (_isFirebaseServerApp(auth.app)) {\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\n }\n return signInWithCredential(getModularInstance(auth), EmailAuthProvider.credential(email, password)).catch(async (error) => {\n if (error.code === `auth/${\"password-does-not-meet-requirements\" /* AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS */}`) {\n void recachePasswordPolicy(auth);\n }\n throw error;\n });\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Sends a sign-in email link to the user with the specified email.\n *\n * @remarks\n * The sign-in operation has to always be completed in the app unlike other out of band email\n * actions (password reset and email verifications). This is because, at the end of the flow,\n * the user is expected to be signed in and their Auth state persisted within the app.\n *\n * To complete sign in with the email link, call {@link signInWithEmailLink} with the email\n * address and the email link supplied in the email sent to the user.\n *\n * @example\n * ```javascript\n * const actionCodeSettings = {\n * url: 'https://www.example.com/?email=user@example.com',\n * iOS: {\n * bundleId: 'com.example.ios'\n * },\n * android: {\n * packageName: 'com.example.android',\n * installApp: true,\n * minimumVersion: '12'\n * },\n * handleCodeInApp: true\n * };\n * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);\n * // Obtain emailLink from the user.\n * if(isSignInWithEmailLink(auth, emailLink)) {\n * await signInWithEmailLink(auth, 'user@example.com', emailLink);\n * }\n * ```\n *\n * @param authInternal - The {@link Auth} instance.\n * @param email - The user's email address.\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\n *\n * @public\n */\nasync function sendSignInLinkToEmail(auth, email, actionCodeSettings) {\n const authInternal = _castAuth(auth);\n const request = {\n requestType: \"EMAIL_SIGNIN\" /* ActionCodeOperation.EMAIL_SIGNIN */,\n email,\n clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */\n };\n function setActionCodeSettings(request, actionCodeSettings) {\n _assert(actionCodeSettings.handleCodeInApp, authInternal, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\n if (actionCodeSettings) {\n _setActionCodeSettingsOnRequest(authInternal, request, actionCodeSettings);\n }\n }\n setActionCodeSettings(request, actionCodeSettings);\n await handleRecaptchaFlow(authInternal, request, \"getOobCode\" /* RecaptchaActionName.GET_OOB_CODE */, sendSignInLinkToEmail$1, \"EMAIL_PASSWORD_PROVIDER\" /* RecaptchaAuthProvider.EMAIL_PASSWORD_PROVIDER */);\n}\n/**\n * Checks if an incoming link is a sign-in with email link suitable for {@link signInWithEmailLink}.\n *\n * @param auth - The {@link Auth} instance.\n * @param emailLink - The link sent to the user's email address.\n *\n * @public\n */\nfunction isSignInWithEmailLink(auth, emailLink) {\n const actionCodeUrl = ActionCodeURL.parseLink(emailLink);\n return actionCodeUrl?.operation === \"EMAIL_SIGNIN\" /* ActionCodeOperation.EMAIL_SIGNIN */;\n}\n/**\n * Asynchronously signs in using an email and sign-in email link.\n *\n * @remarks\n * If no link is passed, the link is inferred from the current URL.\n *\n * Fails with an error if the email address is invalid or OTP in email link expires.\n *\n * This method is not supported by {@link Auth} instances created with a\n * {@link @firebase/app#FirebaseServerApp}.\n *\n * Note: Confirm the link is a sign-in email link before calling this method firebase.auth.Auth.isSignInWithEmailLink.\n *\n * @example\n * ```javascript\n * const actionCodeSettings = {\n * url: 'https://www.example.com/?email=user@example.com',\n * iOS: {\n * bundleId: 'com.example.ios'\n * },\n * android: {\n * packageName: 'com.example.android',\n * installApp: true,\n * minimumVersion: '12'\n * },\n * handleCodeInApp: true\n * };\n * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);\n * // Obtain emailLink from the user.\n * if(isSignInWithEmailLink(auth, emailLink)) {\n * await signInWithEmailLink(auth, 'user@example.com', emailLink);\n * }\n * ```\n *\n *\n * @param auth - The {@link Auth} instance.\n * @param email - The user's email address.\n * @param emailLink - The link sent to the user's email address.\n *\n * @public\n */\nasync function signInWithEmailLink(auth, email, emailLink) {\n if (_isFirebaseServerApp(auth.app)) {\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\n }\n const authModular = getModularInstance(auth);\n const credential = EmailAuthProvider.credentialWithLink(email, emailLink || _getCurrentUrl());\n // Check if the tenant ID in the email link matches the tenant ID on Auth\n // instance.\n _assert(credential._tenantId === (authModular.tenantId || null), authModular, \"tenant-id-mismatch\" /* AuthErrorCode.TENANT_ID_MISMATCH */);\n return signInWithCredential(authModular, credential);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nasync function createAuthUri(auth, request) {\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:createAuthUri\" /* Endpoint.CREATE_AUTH_URI */, _addTidIfNecessary(auth, request));\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Gets the list of possible sign in methods for the given email address. This method returns an\n * empty list when\n * {@link https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection | Email Enumeration Protection}\n * is enabled, irrespective of the number of authentication methods available for the given email.\n *\n * @remarks\n * This is useful to differentiate methods of sign-in for the same provider, eg.\n * {@link EmailAuthProvider} which has 2 methods of sign-in,\n * {@link SignInMethod}.EMAIL_PASSWORD and\n * {@link SignInMethod}.EMAIL_LINK.\n *\n * @param auth - The {@link Auth} instance.\n * @param email - The user's email address.\n *\n * Deprecated. Migrating off of this method is recommended as a security best-practice.\n * Learn more in the Identity Platform documentation for\n * {@link https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection | Email Enumeration Protection}.\n * @public\n */\nasync function fetchSignInMethodsForEmail(auth, email) {\n // createAuthUri returns an error if continue URI is not http or https.\n // For environments like Cordova, Chrome extensions, native frameworks, file\n // systems, etc, use http://localhost as continue URL.\n const continueUri = _isHttpOrHttps() ? _getCurrentUrl() : 'http://localhost';\n const request = {\n identifier: email,\n continueUri\n };\n const { signinMethods } = await createAuthUri(getModularInstance(auth), request);\n return signinMethods || [];\n}\n/**\n * Sends a verification email to a user.\n *\n * @remarks\n * The verification process is completed by calling {@link applyActionCode}.\n *\n * @example\n * ```javascript\n * const actionCodeSettings = {\n * url: 'https://www.example.com/?email=user@example.com',\n * iOS: {\n * bundleId: 'com.example.ios'\n * },\n * android: {\n * packageName: 'com.example.android',\n * installApp: true,\n * minimumVersion: '12'\n * },\n * handleCodeInApp: true\n * };\n * await sendEmailVerification(user, actionCodeSettings);\n * // Obtain code from the user.\n * await applyActionCode(auth, code);\n * ```\n *\n * @param user - The user.\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\n *\n * @public\n */\nasync function sendEmailVerification(user, actionCodeSettings) {\n const userInternal = getModularInstance(user);\n const idToken = await user.getIdToken();\n const request = {\n requestType: \"VERIFY_EMAIL\" /* ActionCodeOperation.VERIFY_EMAIL */,\n idToken\n };\n if (actionCodeSettings) {\n _setActionCodeSettingsOnRequest(userInternal.auth, request, actionCodeSettings);\n }\n const { email } = await sendEmailVerification$1(userInternal.auth, request);\n if (email !== user.email) {\n await user.reload();\n }\n}\n/**\n * Sends a verification email to a new email address.\n *\n * @remarks\n * The user's email will be updated to the new one after being verified.\n *\n * If you have a custom email action handler, you can complete the verification process by calling\n * {@link applyActionCode}.\n *\n * @example\n * ```javascript\n * const actionCodeSettings = {\n * url: 'https://www.example.com/?email=user@example.com',\n * iOS: {\n * bundleId: 'com.example.ios'\n * },\n * android: {\n * packageName: 'com.example.android',\n * installApp: true,\n * minimumVersion: '12'\n * },\n * handleCodeInApp: true\n * };\n * await verifyBeforeUpdateEmail(user, 'newemail@example.com', actionCodeSettings);\n * // Obtain code from the user.\n * await applyActionCode(auth, code);\n * ```\n *\n * @param user - The user.\n * @param newEmail - The new email address to be verified before update.\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\n *\n * @public\n */\nasync function verifyBeforeUpdateEmail(user, newEmail, actionCodeSettings) {\n const userInternal = getModularInstance(user);\n const idToken = await user.getIdToken();\n const request = {\n requestType: \"VERIFY_AND_CHANGE_EMAIL\" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */,\n idToken,\n newEmail\n };\n if (actionCodeSettings) {\n _setActionCodeSettingsOnRequest(userInternal.auth, request, actionCodeSettings);\n }\n const { email } = await verifyAndChangeEmail(userInternal.auth, request);\n if (email !== user.email) {\n // If the local copy of the email on user is outdated, reload the\n // user.\n await user.reload();\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nasync function updateProfile$1(auth, request) {\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:update\" /* Endpoint.SET_ACCOUNT_INFO */, request);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Updates a user's profile data.\n *\n * @param user - The user.\n * @param profile - The profile's `displayName` and `photoURL` to update.\n *\n * @public\n */\nasync function updateProfile(user, profile) {\n const { displayName, photoURL: photoUrl } = profile;\n if (displayName === undefined && photoUrl === undefined) {\n return;\n }\n const userInternal = getModularInstance(user);\n const idToken = await userInternal.getIdToken();\n const profileRequest = {\n idToken,\n displayName,\n photoUrl,\n returnSecureToken: true\n };\n const response = await _logoutIfInvalidated(userInternal, updateProfile$1(userInternal.auth, profileRequest));\n userInternal.displayName = response.displayName || null;\n userInternal.photoURL = response.photoUrl || null;\n // Update the password provider as well\n const passwordProvider = userInternal.providerData.find(({ providerId }) => providerId === \"password\" /* ProviderId.PASSWORD */);\n if (passwordProvider) {\n passwordProvider.displayName = userInternal.displayName;\n passwordProvider.photoURL = userInternal.photoURL;\n }\n await userInternal._updateTokensIfNecessary(response);\n}\n/**\n * Updates the user's email address.\n *\n * @remarks\n * An email will be sent to the original email address (if it was set) that allows to revoke the\n * email address change, in order to protect them from account hijacking.\n *\n * This method is not supported on any {@link User} signed in by {@link Auth} instances\n * created with a {@link @firebase/app#FirebaseServerApp}.\n *\n * Important: this is a security sensitive operation that requires the user to have recently signed\n * in. If this requirement isn't met, ask the user to authenticate again and then call\n * {@link reauthenticateWithCredential}.\n *\n * @param user - The user.\n * @param newEmail - The new email address.\n *\n * Throws \"auth/operation-not-allowed\" error when\n * {@link https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection | Email Enumeration Protection}\n * is enabled.\n * Deprecated - Use {@link verifyBeforeUpdateEmail} instead.\n *\n * @public\n */\nfunction updateEmail(user, newEmail) {\n const userInternal = getModularInstance(user);\n if (_isFirebaseServerApp(userInternal.auth.app)) {\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(userInternal.auth));\n }\n return updateEmailOrPassword(userInternal, newEmail, null);\n}\n/**\n * Updates the user's password.\n *\n * @remarks\n * Important: this is a security sensitive operation that requires the user to have recently signed\n * in. If this requirement isn't met, ask the user to authenticate again and then call\n * {@link reauthenticateWithCredential}.\n *\n * @param user - The user.\n * @param newPassword - The new password.\n *\n * @public\n */\nfunction updatePassword(user, newPassword) {\n return updateEmailOrPassword(getModularInstance(user), null, newPassword);\n}\nasync function updateEmailOrPassword(user, email, password) {\n const { auth } = user;\n const idToken = await user.getIdToken();\n const request = {\n idToken,\n returnSecureToken: true\n };\n if (email) {\n request.email = email;\n }\n if (password) {\n request.password = password;\n }\n const response = await _logoutIfInvalidated(user, updateEmailPassword(auth, request));\n await user._updateTokensIfNecessary(response, /* reload */ true);\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Parse the `AdditionalUserInfo` from the ID token response.\n *\n */\nfunction _fromIdTokenResponse(idTokenResponse) {\n if (!idTokenResponse) {\n return null;\n }\n const { providerId } = idTokenResponse;\n const profile = idTokenResponse.rawUserInfo\n ? JSON.parse(idTokenResponse.rawUserInfo)\n : {};\n const isNewUser = idTokenResponse.isNewUser ||\n idTokenResponse.kind === \"identitytoolkit#SignupNewUserResponse\" /* IdTokenResponseKind.SignupNewUser */;\n if (!providerId && idTokenResponse?.idToken) {\n const signInProvider = _parseToken(idTokenResponse.idToken)?.firebase?.['sign_in_provider'];\n if (signInProvider) {\n const filteredProviderId = signInProvider !== \"anonymous\" /* ProviderId.ANONYMOUS */ &&\n signInProvider !== \"custom\" /* ProviderId.CUSTOM */\n ? signInProvider\n : null;\n // Uses generic class in accordance with the legacy SDK.\n return new GenericAdditionalUserInfo(isNewUser, filteredProviderId);\n }\n }\n if (!providerId) {\n return null;\n }\n switch (providerId) {\n case \"facebook.com\" /* ProviderId.FACEBOOK */:\n return new FacebookAdditionalUserInfo(isNewUser, profile);\n case \"github.com\" /* ProviderId.GITHUB */:\n return new GithubAdditionalUserInfo(isNewUser, profile);\n case \"google.com\" /* ProviderId.GOOGLE */:\n return new GoogleAdditionalUserInfo(isNewUser, profile);\n case \"twitter.com\" /* ProviderId.TWITTER */:\n return new TwitterAdditionalUserInfo(isNewUser, profile, idTokenResponse.screenName || null);\n case \"custom\" /* ProviderId.CUSTOM */:\n case \"anonymous\" /* ProviderId.ANONYMOUS */:\n return new GenericAdditionalUserInfo(isNewUser, null);\n default:\n return new GenericAdditionalUserInfo(isNewUser, providerId, profile);\n }\n}\nclass GenericAdditionalUserInfo {\n constructor(isNewUser, providerId, profile = {}) {\n this.isNewUser = isNewUser;\n this.providerId = providerId;\n this.profile = profile;\n }\n}\nclass FederatedAdditionalUserInfoWithUsername extends GenericAdditionalUserInfo {\n constructor(isNewUser, providerId, profile, username) {\n super(isNewUser, providerId, profile);\n this.username = username;\n }\n}\nclass FacebookAdditionalUserInfo extends GenericAdditionalUserInfo {\n constructor(isNewUser, profile) {\n super(isNewUser, \"facebook.com\" /* ProviderId.FACEBOOK */, profile);\n }\n}\nclass GithubAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername {\n constructor(isNewUser, profile) {\n super(isNewUser, \"github.com\" /* ProviderId.GITHUB */, profile, typeof profile?.login === 'string' ? profile?.login : null);\n }\n}\nclass GoogleAdditionalUserInfo extends GenericAdditionalUserInfo {\n constructor(isNewUser, profile) {\n super(isNewUser, \"google.com\" /* ProviderId.GOOGLE */, profile);\n }\n}\nclass TwitterAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername {\n constructor(isNewUser, profile, screenName) {\n super(isNewUser, \"twitter.com\" /* ProviderId.TWITTER */, profile, screenName);\n }\n}\n/**\n * Extracts provider specific {@link AdditionalUserInfo} for the given credential.\n *\n * @param userCredential - The user credential.\n *\n * @public\n */\nfunction getAdditionalUserInfo(userCredential) {\n const { user, _tokenResponse } = userCredential;\n if (user.isAnonymous && !_tokenResponse) {\n // Handle the special case where signInAnonymously() gets called twice.\n // No network call is made so there's nothing to actually fill this in\n return {\n providerId: null,\n isNewUser: false,\n profile: null\n };\n }\n return _fromIdTokenResponse(_tokenResponse);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// Non-optional auth methods.\n/**\n * Changes the type of persistence on the {@link Auth} instance for the currently saved\n * `Auth` session and applies this type of persistence for future sign-in requests, including\n * sign-in with redirect requests.\n *\n * @remarks\n * This makes it easy for a user signing in to specify whether their session should be\n * remembered or not. It also makes it easier to never persist the `Auth` state for applications\n * that are shared by other users or have sensitive data.\n *\n * This method does not work in a Node.js environment or with {@link Auth} instances created with a\n * {@link @firebase/app#FirebaseServerApp}.\n *\n * @example\n * ```javascript\n * setPersistence(auth, browserSessionPersistence);\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param persistence - The {@link Persistence} to use.\n * @returns A `Promise` that resolves once the persistence change has completed\n *\n * @public\n */\nfunction setPersistence(auth, persistence) {\n return getModularInstance(auth).setPersistence(persistence);\n}\n/**\n * Loads the reCAPTCHA configuration into the `Auth` instance.\n *\n * @remarks\n * This will load the reCAPTCHA config, which indicates whether the reCAPTCHA\n * verification flow should be triggered for each auth provider, into the\n * current Auth session.\n *\n * If initializeRecaptchaConfig() is not invoked, the auth flow will always start\n * without reCAPTCHA verification. If the provider is configured to require reCAPTCHA\n * verification, the SDK will transparently load the reCAPTCHA config and restart the\n * auth flows.\n *\n * Thus, by calling this optional method, you will reduce the latency of future auth flows.\n * Loading the reCAPTCHA config early will also enhance the signal collected by reCAPTCHA.\n *\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * initializeRecaptchaConfig(auth);\n * ```\n *\n * @param auth - The {@link Auth} instance.\n *\n * @public\n */\nfunction initializeRecaptchaConfig(auth) {\n return _initializeRecaptchaConfig(auth);\n}\n/**\n * Validates the password against the password policy configured for the project or tenant.\n *\n * @remarks\n * If no tenant ID is set on the `Auth` instance, then this method will use the password\n * policy configured for the project. Otherwise, this method will use the policy configured\n * for the tenant. If a password policy has not been configured, then the default policy\n * configured for all projects will be used.\n *\n * If an auth flow fails because a submitted password does not meet the password policy\n * requirements and this method has previously been called, then this method will use the\n * most recent policy available when called again.\n *\n * @example\n * ```javascript\n * validatePassword(auth, 'some-password');\n * ```\n *\n * @param auth The {@link Auth} instance.\n * @param password The password to validate.\n *\n * @public\n */\nasync function validatePassword(auth, password) {\n const authInternal = _castAuth(auth);\n return authInternal.validatePassword(password);\n}\n/**\n * Adds an observer for changes to the signed-in user's ID token.\n *\n * @remarks\n * This includes sign-in, sign-out, and token refresh events.\n * This will not be triggered automatically upon ID token expiration. Use {@link User.getIdToken} to refresh the ID token.\n *\n * @param auth - The {@link Auth} instance.\n * @param nextOrObserver - callback triggered on change.\n * @param error - Deprecated. This callback is never triggered. Errors\n * on signing in/out can be caught in promises returned from\n * sign-in/sign-out functions.\n * @param completed - Deprecated. This callback is never triggered.\n *\n * @public\n */\nfunction onIdTokenChanged(auth, nextOrObserver, error, completed) {\n return getModularInstance(auth).onIdTokenChanged(nextOrObserver, error, completed);\n}\n/**\n * Adds a blocking callback that runs before an auth state change\n * sets a new user.\n *\n * @param auth - The {@link Auth} instance.\n * @param callback - callback triggered before new user value is set.\n * If this throws, it blocks the user from being set.\n * @param onAbort - callback triggered if a later `beforeAuthStateChanged()`\n * callback throws, allowing you to undo any side effects.\n */\nfunction beforeAuthStateChanged(auth, callback, onAbort) {\n return getModularInstance(auth).beforeAuthStateChanged(callback, onAbort);\n}\n/**\n * Adds an observer for changes to the user's sign-in state.\n *\n * @remarks\n * To keep the old behavior, see {@link onIdTokenChanged}.\n *\n * @param auth - The {@link Auth} instance.\n * @param nextOrObserver - callback triggered on change.\n * @param error - Deprecated. This callback is never triggered. Errors\n * on signing in/out can be caught in promises returned from\n * sign-in/sign-out functions.\n * @param completed - Deprecated. This callback is never triggered.\n *\n * @public\n */\nfunction onAuthStateChanged(auth, nextOrObserver, error, completed) {\n return getModularInstance(auth).onAuthStateChanged(nextOrObserver, error, completed);\n}\n/**\n * Sets the current language to the default device/browser preference.\n *\n * @param auth - The {@link Auth} instance.\n *\n * @public\n */\nfunction useDeviceLanguage(auth) {\n getModularInstance(auth).useDeviceLanguage();\n}\n/**\n * Asynchronously sets the provided user as {@link Auth.currentUser} on the\n * {@link Auth} instance.\n *\n * @remarks\n * A new instance copy of the user provided will be made and set as currentUser.\n *\n * This will trigger {@link onAuthStateChanged} and {@link onIdTokenChanged} listeners\n * like other sign in methods.\n *\n * The operation fails with an error if the user to be updated belongs to a different Firebase\n * project.\n *\n * This method is not supported by {@link Auth} instances created with a\n * {@link @firebase/app#FirebaseServerApp}.\n *\n * @param auth - The {@link Auth} instance.\n * @param user - The new {@link User}.\n *\n * @public\n */\nfunction updateCurrentUser(auth, user) {\n return getModularInstance(auth).updateCurrentUser(user);\n}\n/**\n * Signs out the current user.\n *\n * @remarks\n * This method is not supported by {@link Auth} instances created with a\n * {@link @firebase/app#FirebaseServerApp}.\n *\n * @param auth - The {@link Auth} instance.\n *\n * @public\n */\nfunction signOut(auth) {\n return getModularInstance(auth).signOut();\n}\n/**\n * Revokes the given access token. Currently only supports Apple OAuth access tokens.\n *\n * @param auth - The {@link Auth} instance.\n * @param token - The Apple OAuth access token.\n *\n * @public\n */\nfunction revokeAccessToken(auth, token) {\n const authInternal = _castAuth(auth);\n return authInternal.revokeAccessToken(token);\n}\n/**\n * Deletes and signs out the user.\n *\n * @remarks\n * Important: this is a security-sensitive operation that requires the user to have recently\n * signed in. If this requirement isn't met, ask the user to authenticate again and then call\n * {@link reauthenticateWithCredential}.\n *\n * @param user - The user.\n *\n * @public\n */\nasync function deleteUser(user) {\n return getModularInstance(user).delete();\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass MultiFactorSessionImpl {\n constructor(type, credential, user) {\n this.type = type;\n this.credential = credential;\n this.user = user;\n }\n static _fromIdtoken(idToken, user) {\n return new MultiFactorSessionImpl(\"enroll\" /* MultiFactorSessionType.ENROLL */, idToken, user);\n }\n static _fromMfaPendingCredential(mfaPendingCredential) {\n return new MultiFactorSessionImpl(\"signin\" /* MultiFactorSessionType.SIGN_IN */, mfaPendingCredential);\n }\n toJSON() {\n const key = this.type === \"enroll\" /* MultiFactorSessionType.ENROLL */\n ? 'idToken'\n : 'pendingCredential';\n return {\n multiFactorSession: {\n [key]: this.credential\n }\n };\n }\n static fromJSON(obj) {\n if (obj?.multiFactorSession) {\n if (obj.multiFactorSession?.pendingCredential) {\n return MultiFactorSessionImpl._fromMfaPendingCredential(obj.multiFactorSession.pendingCredential);\n }\n else if (obj.multiFactorSession?.idToken) {\n return MultiFactorSessionImpl._fromIdtoken(obj.multiFactorSession.idToken);\n }\n }\n return null;\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass MultiFactorResolverImpl {\n constructor(session, hints, signInResolver) {\n this.session = session;\n this.hints = hints;\n this.signInResolver = signInResolver;\n }\n /** @internal */\n static _fromError(authExtern, error) {\n const auth = _castAuth(authExtern);\n const serverResponse = error.customData._serverResponse;\n const hints = (serverResponse.mfaInfo || []).map(enrollment => MultiFactorInfoImpl._fromServerResponse(auth, enrollment));\n _assert(serverResponse.mfaPendingCredential, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n const session = MultiFactorSessionImpl._fromMfaPendingCredential(serverResponse.mfaPendingCredential);\n return new MultiFactorResolverImpl(session, hints, async (assertion) => {\n const mfaResponse = await assertion._process(auth, session);\n // Clear out the unneeded fields from the old login response\n delete serverResponse.mfaInfo;\n delete serverResponse.mfaPendingCredential;\n // Use in the new token & refresh token in the old response\n const idTokenResponse = {\n ...serverResponse,\n idToken: mfaResponse.idToken,\n refreshToken: mfaResponse.refreshToken\n };\n // TODO: we should collapse this switch statement into UserCredentialImpl._forOperation and have it support the SIGN_IN case\n switch (error.operationType) {\n case \"signIn\" /* OperationType.SIGN_IN */:\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(auth, error.operationType, idTokenResponse);\n await auth._updateCurrentUser(userCredential.user);\n return userCredential;\n case \"reauthenticate\" /* OperationType.REAUTHENTICATE */:\n _assert(error.user, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n return UserCredentialImpl._forOperation(error.user, error.operationType, idTokenResponse);\n default:\n _fail(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n }\n });\n }\n async resolveSignIn(assertionExtern) {\n const assertion = assertionExtern;\n return this.signInResolver(assertion);\n }\n}\n/**\n * Provides a {@link MultiFactorResolver} suitable for completion of a\n * multi-factor flow.\n *\n * @param auth - The {@link Auth} instance.\n * @param error - The {@link MultiFactorError} raised during a sign-in, or\n * reauthentication operation.\n *\n * @public\n */\nfunction getMultiFactorResolver(auth, error) {\n const authModular = getModularInstance(auth);\n const errorInternal = error;\n _assert(error.customData.operationType, authModular, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\n _assert(errorInternal.customData._serverResponse?.mfaPendingCredential, authModular, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\n return MultiFactorResolverImpl._fromError(authModular, errorInternal);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nfunction startEnrollPhoneMfa(auth, request) {\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaEnrollment:start\" /* Endpoint.START_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));\n}\nfunction finalizeEnrollPhoneMfa(auth, request) {\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaEnrollment:finalize\" /* Endpoint.FINALIZE_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));\n}\nfunction startEnrollTotpMfa(auth, request) {\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaEnrollment:start\" /* Endpoint.START_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));\n}\nfunction finalizeEnrollTotpMfa(auth, request) {\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaEnrollment:finalize\" /* Endpoint.FINALIZE_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));\n}\nfunction withdrawMfa(auth, request) {\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaEnrollment:withdraw\" /* Endpoint.WITHDRAW_MFA */, _addTidIfNecessary(auth, request));\n}\n\nclass MultiFactorUserImpl {\n constructor(user) {\n this.user = user;\n this.enrolledFactors = [];\n user._onReload(userInfo => {\n if (userInfo.mfaInfo) {\n this.enrolledFactors = userInfo.mfaInfo.map(enrollment => MultiFactorInfoImpl._fromServerResponse(user.auth, enrollment));\n }\n });\n }\n static _fromUser(user) {\n return new MultiFactorUserImpl(user);\n }\n async getSession() {\n return MultiFactorSessionImpl._fromIdtoken(await this.user.getIdToken(), this.user);\n }\n async enroll(assertionExtern, displayName) {\n const assertion = assertionExtern;\n const session = (await this.getSession());\n const finalizeMfaResponse = await _logoutIfInvalidated(this.user, assertion._process(this.user.auth, session, displayName));\n // New tokens will be issued after enrollment of the new second factors.\n // They need to be updated on the user.\n await this.user._updateTokensIfNecessary(finalizeMfaResponse);\n // The user needs to be reloaded to get the new multi-factor information\n // from server. USER_RELOADED event will be triggered and `enrolledFactors`\n // will be updated.\n return this.user.reload();\n }\n async unenroll(infoOrUid) {\n const mfaEnrollmentId = typeof infoOrUid === 'string' ? infoOrUid : infoOrUid.uid;\n const idToken = await this.user.getIdToken();\n try {\n const idTokenResponse = await _logoutIfInvalidated(this.user, withdrawMfa(this.user.auth, {\n idToken,\n mfaEnrollmentId\n }));\n // Remove the second factor from the user's list.\n this.enrolledFactors = this.enrolledFactors.filter(({ uid }) => uid !== mfaEnrollmentId);\n // Depending on whether the backend decided to revoke the user's session,\n // the tokenResponse may be empty. If the tokens were not updated (and they\n // are now invalid), reloading the user will discover this and invalidate\n // the user's state accordingly.\n await this.user._updateTokensIfNecessary(idTokenResponse);\n await this.user.reload();\n }\n catch (e) {\n throw e;\n }\n }\n}\nconst multiFactorUserCache = new WeakMap();\n/**\n * The {@link MultiFactorUser} corresponding to the user.\n *\n * @remarks\n * This is used to access all multi-factor properties and operations related to the user.\n *\n * @param user - The user.\n *\n * @public\n */\nfunction multiFactor(user) {\n const userModular = getModularInstance(user);\n if (!multiFactorUserCache.has(userModular)) {\n multiFactorUserCache.set(userModular, MultiFactorUserImpl._fromUser(userModular));\n }\n return multiFactorUserCache.get(userModular);\n}\n\nconst STORAGE_AVAILABLE_KEY = '__sak';\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// There are two different browser persistence types: local and session.\n// Both have the same implementation but use a different underlying storage\n// object.\nclass BrowserPersistenceClass {\n constructor(storageRetriever, type) {\n this.storageRetriever = storageRetriever;\n this.type = type;\n }\n _isAvailable() {\n try {\n if (!this.storage) {\n return Promise.resolve(false);\n }\n this.storage.setItem(STORAGE_AVAILABLE_KEY, '1');\n this.storage.removeItem(STORAGE_AVAILABLE_KEY);\n return Promise.resolve(true);\n }\n catch {\n return Promise.resolve(false);\n }\n }\n _set(key, value) {\n this.storage.setItem(key, JSON.stringify(value));\n return Promise.resolve();\n }\n _get(key) {\n const json = this.storage.getItem(key);\n return Promise.resolve(json ? JSON.parse(json) : null);\n }\n _remove(key) {\n this.storage.removeItem(key);\n return Promise.resolve();\n }\n get storage() {\n return this.storageRetriever();\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// The polling period in case events are not supported\nconst _POLLING_INTERVAL_MS$1 = 1000;\n// The IE 10 localStorage cross tab synchronization delay in milliseconds\nconst IE10_LOCAL_STORAGE_SYNC_DELAY = 10;\nclass BrowserLocalPersistence extends BrowserPersistenceClass {\n constructor() {\n super(() => window.localStorage, \"LOCAL\" /* PersistenceType.LOCAL */);\n this.boundEventHandler = (event, poll) => this.onStorageEvent(event, poll);\n this.listeners = {};\n this.localCache = {};\n // setTimeout return value is platform specific\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this.pollTimer = null;\n // Whether to use polling instead of depending on window events\n this.fallbackToPolling = _isMobileBrowser();\n this._shouldAllowMigration = true;\n }\n forAllChangedKeys(cb) {\n // Check all keys with listeners on them.\n for (const key of Object.keys(this.listeners)) {\n // Get value from localStorage.\n const newValue = this.storage.getItem(key);\n const oldValue = this.localCache[key];\n // If local map value does not match, trigger listener with storage event.\n // Differentiate this simulated event from the real storage event.\n if (newValue !== oldValue) {\n cb(key, oldValue, newValue);\n }\n }\n }\n onStorageEvent(event, poll = false) {\n // Key would be null in some situations, like when localStorage is cleared\n if (!event.key) {\n this.forAllChangedKeys((key, _oldValue, newValue) => {\n this.notifyListeners(key, newValue);\n });\n return;\n }\n const key = event.key;\n // Check the mechanism how this event was detected.\n // The first event will dictate the mechanism to be used.\n if (poll) {\n // Environment detects storage changes via polling.\n // Remove storage event listener to prevent possible event duplication.\n this.detachListener();\n }\n else {\n // Environment detects storage changes via storage event listener.\n // Remove polling listener to prevent possible event duplication.\n this.stopPolling();\n }\n const triggerListeners = () => {\n // Keep local map up to date in case storage event is triggered before\n // poll.\n const storedValue = this.storage.getItem(key);\n if (!poll && this.localCache[key] === storedValue) {\n // Real storage event which has already been detected, do nothing.\n // This seems to trigger in some IE browsers for some reason.\n return;\n }\n this.notifyListeners(key, storedValue);\n };\n const storedValue = this.storage.getItem(key);\n if (_isIE10() &&\n storedValue !== event.newValue &&\n event.newValue !== event.oldValue) {\n // IE 10 has this weird bug where a storage event would trigger with the\n // correct key, oldValue and newValue but localStorage.getItem(key) does\n // not yield the updated value until a few milliseconds. This ensures\n // this recovers from that situation.\n setTimeout(triggerListeners, IE10_LOCAL_STORAGE_SYNC_DELAY);\n }\n else {\n triggerListeners();\n }\n }\n notifyListeners(key, value) {\n this.localCache[key] = value;\n const listeners = this.listeners[key];\n if (listeners) {\n for (const listener of Array.from(listeners)) {\n listener(value ? JSON.parse(value) : value);\n }\n }\n }\n startPolling() {\n this.stopPolling();\n this.pollTimer = setInterval(() => {\n this.forAllChangedKeys((key, oldValue, newValue) => {\n this.onStorageEvent(new StorageEvent('storage', {\n key,\n oldValue,\n newValue\n }), \n /* poll */ true);\n });\n }, _POLLING_INTERVAL_MS$1);\n }\n stopPolling() {\n if (this.pollTimer) {\n clearInterval(this.pollTimer);\n this.pollTimer = null;\n }\n }\n attachListener() {\n window.addEventListener('storage', this.boundEventHandler);\n }\n detachListener() {\n window.removeEventListener('storage', this.boundEventHandler);\n }\n _addListener(key, listener) {\n if (Object.keys(this.listeners).length === 0) {\n // Whether browser can detect storage event when it had already been pushed to the background.\n // This may happen in some mobile browsers. A localStorage change in the foreground window\n // will not be detected in the background window via the storage event.\n // This was detected in iOS 7.x mobile browsers\n if (this.fallbackToPolling) {\n this.startPolling();\n }\n else {\n this.attachListener();\n }\n }\n if (!this.listeners[key]) {\n this.listeners[key] = new Set();\n // Populate the cache to avoid spuriously triggering on first poll.\n this.localCache[key] = this.storage.getItem(key);\n }\n this.listeners[key].add(listener);\n }\n _removeListener(key, listener) {\n if (this.listeners[key]) {\n this.listeners[key].delete(listener);\n if (this.listeners[key].size === 0) {\n delete this.listeners[key];\n }\n }\n if (Object.keys(this.listeners).length === 0) {\n this.detachListener();\n this.stopPolling();\n }\n }\n // Update local cache on base operations:\n async _set(key, value) {\n await super._set(key, value);\n this.localCache[key] = JSON.stringify(value);\n }\n async _get(key) {\n const value = await super._get(key);\n this.localCache[key] = JSON.stringify(value);\n return value;\n }\n async _remove(key) {\n await super._remove(key);\n delete this.localCache[key];\n }\n}\nBrowserLocalPersistence.type = 'LOCAL';\n/**\n * An implementation of {@link Persistence} of type `LOCAL` using `localStorage`\n * for the underlying storage.\n *\n * @public\n */\nconst browserLocalPersistence = BrowserLocalPersistence;\n\n/**\n * @license\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst POLLING_INTERVAL_MS = 1000;\n// Pull a cookie value from document.cookie\nfunction getDocumentCookie(name) {\n const escapedName = name.replace(/[\\\\^$.*+?()[\\]{}|]/g, '\\\\$&');\n const matcher = RegExp(`${escapedName}=([^;]+)`);\n return document.cookie.match(matcher)?.[1] ?? null;\n}\n// Produce a sanitized cookie name from the persistence key\nfunction getCookieName(key) {\n // __HOST- doesn't work in localhost https://issues.chromium.org/issues/40196122 but it has\n // desirable security properties, so lets use a different cookie name while in dev-mode.\n // Already checked isSecureContext in _isAvailable, so if it's http we're hitting local.\n const isDevMode = window.location.protocol === 'http:';\n return `${isDevMode ? '__dev_' : '__HOST-'}FIREBASE_${key.split(':')[3]}`;\n}\nclass CookiePersistence {\n constructor() {\n this.type = \"COOKIE\" /* PersistenceType.COOKIE */;\n this.listenerUnsubscribes = new Map();\n }\n // used to get the URL to the backend to proxy to\n _getFinalTarget(originalUrl) {\n if (typeof window === undefined) {\n return originalUrl;\n }\n const url = new URL(`${window.location.origin}/__cookies__`);\n url.searchParams.set('finalTarget', originalUrl);\n return url;\n }\n // To be a usable persistence method in a chain browserCookiePersistence ensures that\n // prerequisites have been met, namely that we're in a secureContext, navigator and document are\n // available and cookies are enabled. Not all UAs support these method, so fallback accordingly.\n async _isAvailable() {\n if (typeof isSecureContext === 'boolean' && !isSecureContext) {\n return false;\n }\n if (typeof navigator === 'undefined' || typeof document === 'undefined') {\n return false;\n }\n return navigator.cookieEnabled ?? true;\n }\n // Set should be a noop as we expect middleware to handle this\n async _set(_key, _value) {\n return;\n }\n // Attempt to get the cookie from cookieStore, fallback to document.cookie\n async _get(key) {\n if (!this._isAvailable()) {\n return null;\n }\n const name = getCookieName(key);\n if (window.cookieStore) {\n const cookie = await window.cookieStore.get(name);\n return cookie?.value;\n }\n return getDocumentCookie(name);\n }\n // Log out by overriding the idToken with a sentinel value of \"\"\n async _remove(key) {\n if (!this._isAvailable()) {\n return;\n }\n // To make sure we don't hit signout over and over again, only do this operation if we need to\n // with the logout sentinel value of \"\" this can cause race conditions. Unnecessary set-cookie\n // headers will reduce CDN hit rates too.\n const existingValue = await this._get(key);\n if (!existingValue) {\n return;\n }\n const name = getCookieName(key);\n document.cookie = `${name}=;Max-Age=34560000;Partitioned;Secure;SameSite=Strict;Path=/;Priority=High`;\n await fetch(`/__cookies__`, { method: 'DELETE' }).catch(() => undefined);\n }\n // Listen for cookie changes, both cookieStore and fallback to polling document.cookie\n _addListener(key, listener) {\n if (!this._isAvailable()) {\n return;\n }\n const name = getCookieName(key);\n if (window.cookieStore) {\n const cb = ((event) => {\n const changedCookie = event.changed.find(change => change.name === name);\n if (changedCookie) {\n listener(changedCookie.value);\n }\n const deletedCookie = event.deleted.find(change => change.name === name);\n if (deletedCookie) {\n listener(null);\n }\n });\n const unsubscribe = () => window.cookieStore.removeEventListener('change', cb);\n this.listenerUnsubscribes.set(listener, unsubscribe);\n return window.cookieStore.addEventListener('change', cb);\n }\n let lastValue = getDocumentCookie(name);\n const interval = setInterval(() => {\n const currentValue = getDocumentCookie(name);\n if (currentValue !== lastValue) {\n listener(currentValue);\n lastValue = currentValue;\n }\n }, POLLING_INTERVAL_MS);\n const unsubscribe = () => clearInterval(interval);\n this.listenerUnsubscribes.set(listener, unsubscribe);\n }\n _removeListener(_key, listener) {\n const unsubscribe = this.listenerUnsubscribes.get(listener);\n if (!unsubscribe) {\n return;\n }\n unsubscribe();\n this.listenerUnsubscribes.delete(listener);\n }\n}\nCookiePersistence.type = 'COOKIE';\n/**\n * An implementation of {@link Persistence} of type `COOKIE`, for use on the client side in\n * applications leveraging hybrid rendering and middleware.\n *\n * @remarks This persistence method requires companion middleware to function, such as that provided\n * by {@link https://firebaseopensource.com/projects/firebaseextended/reactfire/ | ReactFire} for\n * NextJS.\n * @beta\n */\nconst browserCookiePersistence = CookiePersistence;\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass BrowserSessionPersistence extends BrowserPersistenceClass {\n constructor() {\n super(() => window.sessionStorage, \"SESSION\" /* PersistenceType.SESSION */);\n }\n _addListener(_key, _listener) {\n // Listeners are not supported for session storage since it cannot be shared across windows\n return;\n }\n _removeListener(_key, _listener) {\n // Listeners are not supported for session storage since it cannot be shared across windows\n return;\n }\n}\nBrowserSessionPersistence.type = 'SESSION';\n/**\n * An implementation of {@link Persistence} of `SESSION` using `sessionStorage`\n * for the underlying storage.\n *\n * @public\n */\nconst browserSessionPersistence = BrowserSessionPersistence;\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Shim for Promise.allSettled, note the slightly different format of `fulfilled` vs `status`.\n *\n * @param promises - Array of promises to wait on.\n */\nfunction _allSettled(promises) {\n return Promise.all(promises.map(async (promise) => {\n try {\n const value = await promise;\n return {\n fulfilled: true,\n value\n };\n }\n catch (reason) {\n return {\n fulfilled: false,\n reason\n };\n }\n }));\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Interface class for receiving messages.\n *\n */\nclass Receiver {\n constructor(eventTarget) {\n this.eventTarget = eventTarget;\n this.handlersMap = {};\n this.boundEventHandler = this.handleEvent.bind(this);\n }\n /**\n * Obtain an instance of a Receiver for a given event target, if none exists it will be created.\n *\n * @param eventTarget - An event target (such as window or self) through which the underlying\n * messages will be received.\n */\n static _getInstance(eventTarget) {\n // The results are stored in an array since objects can't be keys for other\n // objects. In addition, setting a unique property on an event target as a\n // hash map key may not be allowed due to CORS restrictions.\n const existingInstance = this.receivers.find(receiver => receiver.isListeningto(eventTarget));\n if (existingInstance) {\n return existingInstance;\n }\n const newInstance = new Receiver(eventTarget);\n this.receivers.push(newInstance);\n return newInstance;\n }\n isListeningto(eventTarget) {\n return this.eventTarget === eventTarget;\n }\n /**\n * Fans out a MessageEvent to the appropriate listeners.\n *\n * @remarks\n * Sends an {@link Status.ACK} upon receipt and a {@link Status.DONE} once all handlers have\n * finished processing.\n *\n * @param event - The MessageEvent.\n *\n */\n async handleEvent(event) {\n const messageEvent = event;\n const { eventId, eventType, data } = messageEvent.data;\n const handlers = this.handlersMap[eventType];\n if (!handlers?.size) {\n return;\n }\n messageEvent.ports[0].postMessage({\n status: \"ack\" /* _Status.ACK */,\n eventId,\n eventType\n });\n const promises = Array.from(handlers).map(async (handler) => handler(messageEvent.origin, data));\n const response = await _allSettled(promises);\n messageEvent.ports[0].postMessage({\n status: \"done\" /* _Status.DONE */,\n eventId,\n eventType,\n response\n });\n }\n /**\n * Subscribe an event handler for a particular event.\n *\n * @param eventType - Event name to subscribe to.\n * @param eventHandler - The event handler which should receive the events.\n *\n */\n _subscribe(eventType, eventHandler) {\n if (Object.keys(this.handlersMap).length === 0) {\n this.eventTarget.addEventListener('message', this.boundEventHandler);\n }\n if (!this.handlersMap[eventType]) {\n this.handlersMap[eventType] = new Set();\n }\n this.handlersMap[eventType].add(eventHandler);\n }\n /**\n * Unsubscribe an event handler from a particular event.\n *\n * @param eventType - Event name to unsubscribe from.\n * @param eventHandler - Optional event handler, if none provided, unsubscribe all handlers on this event.\n *\n */\n _unsubscribe(eventType, eventHandler) {\n if (this.handlersMap[eventType] && eventHandler) {\n this.handlersMap[eventType].delete(eventHandler);\n }\n if (!eventHandler || this.handlersMap[eventType].size === 0) {\n delete this.handlersMap[eventType];\n }\n if (Object.keys(this.handlersMap).length === 0) {\n this.eventTarget.removeEventListener('message', this.boundEventHandler);\n }\n }\n}\nReceiver.receivers = [];\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nfunction _generateEventId(prefix = '', digits = 10) {\n let random = '';\n for (let i = 0; i < digits; i++) {\n random += Math.floor(Math.random() * 10);\n }\n return prefix + random;\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Interface for sending messages and waiting for a completion response.\n *\n */\nclass Sender {\n constructor(target) {\n this.target = target;\n this.handlers = new Set();\n }\n /**\n * Unsubscribe the handler and remove it from our tracking Set.\n *\n * @param handler - The handler to unsubscribe.\n */\n removeMessageHandler(handler) {\n if (handler.messageChannel) {\n handler.messageChannel.port1.removeEventListener('message', handler.onMessage);\n handler.messageChannel.port1.close();\n }\n this.handlers.delete(handler);\n }\n /**\n * Send a message to the Receiver located at {@link target}.\n *\n * @remarks\n * We'll first wait a bit for an ACK , if we get one we will wait significantly longer until the\n * receiver has had a chance to fully process the event.\n *\n * @param eventType - Type of event to send.\n * @param data - The payload of the event.\n * @param timeout - Timeout for waiting on an ACK from the receiver.\n *\n * @returns An array of settled promises from all the handlers that were listening on the receiver.\n */\n async _send(eventType, data, timeout = 50 /* _TimeoutDuration.ACK */) {\n const messageChannel = typeof MessageChannel !== 'undefined' ? new MessageChannel() : null;\n if (!messageChannel) {\n throw new Error(\"connection_unavailable\" /* _MessageError.CONNECTION_UNAVAILABLE */);\n }\n // Node timers and browser timers return fundamentally different types.\n // We don't actually care what the value is but TS won't accept unknown and\n // we can't cast properly in both environments.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let completionTimer;\n let handler;\n return new Promise((resolve, reject) => {\n const eventId = _generateEventId('', 20);\n messageChannel.port1.start();\n const ackTimer = setTimeout(() => {\n reject(new Error(\"unsupported_event\" /* _MessageError.UNSUPPORTED_EVENT */));\n }, timeout);\n handler = {\n messageChannel,\n onMessage(event) {\n const messageEvent = event;\n if (messageEvent.data.eventId !== eventId) {\n return;\n }\n switch (messageEvent.data.status) {\n case \"ack\" /* _Status.ACK */:\n // The receiver should ACK first.\n clearTimeout(ackTimer);\n completionTimer = setTimeout(() => {\n reject(new Error(\"timeout\" /* _MessageError.TIMEOUT */));\n }, 3000 /* _TimeoutDuration.COMPLETION */);\n break;\n case \"done\" /* _Status.DONE */:\n // Once the receiver's handlers are finished we will get the results.\n clearTimeout(completionTimer);\n resolve(messageEvent.data.response);\n break;\n default:\n clearTimeout(ackTimer);\n clearTimeout(completionTimer);\n reject(new Error(\"invalid_response\" /* _MessageError.INVALID_RESPONSE */));\n break;\n }\n }\n };\n this.handlers.add(handler);\n messageChannel.port1.addEventListener('message', handler.onMessage);\n this.target.postMessage({\n eventType,\n eventId,\n data\n }, [messageChannel.port2]);\n }).finally(() => {\n if (handler) {\n this.removeMessageHandler(handler);\n }\n });\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Lazy accessor for window, since the compat layer won't tree shake this out,\n * we need to make sure not to mess with window unless we have to\n */\nfunction _window() {\n return window;\n}\nfunction _setWindowLocation(url) {\n _window().location.href = url;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nfunction _isWorker() {\n return (typeof _window()['WorkerGlobalScope'] !== 'undefined' &&\n typeof _window()['importScripts'] === 'function');\n}\nasync function _getActiveServiceWorker() {\n if (!navigator?.serviceWorker) {\n return null;\n }\n try {\n const registration = await navigator.serviceWorker.ready;\n return registration.active;\n }\n catch {\n return null;\n }\n}\nfunction _getServiceWorkerController() {\n return navigator?.serviceWorker?.controller || null;\n}\nfunction _getWorkerGlobalScope() {\n return _isWorker() ? self : null;\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst DB_NAME = 'firebaseLocalStorageDb';\nconst DB_VERSION = 1;\nconst DB_OBJECTSTORE_NAME = 'firebaseLocalStorage';\nconst DB_DATA_KEYPATH = 'fbase_key';\n/**\n * Promise wrapper for IDBRequest\n *\n * Unfortunately we can't cleanly extend Promise<T> since promises are not callable in ES6\n *\n */\nclass DBPromise {\n constructor(request) {\n this.request = request;\n }\n toPromise() {\n return new Promise((resolve, reject) => {\n this.request.addEventListener('success', () => {\n resolve(this.request.result);\n });\n this.request.addEventListener('error', () => {\n reject(this.request.error);\n });\n });\n }\n}\nfunction getObjectStore(db, isReadWrite) {\n return db\n .transaction([DB_OBJECTSTORE_NAME], isReadWrite ? 'readwrite' : 'readonly')\n .objectStore(DB_OBJECTSTORE_NAME);\n}\nfunction _deleteDatabase() {\n const request = indexedDB.deleteDatabase(DB_NAME);\n return new DBPromise(request).toPromise();\n}\nfunction _openDatabase() {\n const request = indexedDB.open(DB_NAME, DB_VERSION);\n return new Promise((resolve, reject) => {\n request.addEventListener('error', () => {\n reject(request.error);\n });\n request.addEventListener('upgradeneeded', () => {\n const db = request.result;\n try {\n db.createObjectStore(DB_OBJECTSTORE_NAME, { keyPath: DB_DATA_KEYPATH });\n }\n catch (e) {\n reject(e);\n }\n });\n request.addEventListener('success', async () => {\n const db = request.result;\n // Strange bug that occurs in Firefox when multiple tabs are opened at the\n // same time. The only way to recover seems to be deleting the database\n // and re-initializing it.\n // https://github.com/firebase/firebase-js-sdk/issues/634\n if (!db.objectStoreNames.contains(DB_OBJECTSTORE_NAME)) {\n // Need to close the database or else you get a `blocked` event\n db.close();\n await _deleteDatabase();\n resolve(await _openDatabase());\n }\n else {\n resolve(db);\n }\n });\n });\n}\nasync function _putObject(db, key, value) {\n const request = getObjectStore(db, true).put({\n [DB_DATA_KEYPATH]: key,\n value\n });\n return new DBPromise(request).toPromise();\n}\nasync function getObject(db, key) {\n const request = getObjectStore(db, false).get(key);\n const data = await new DBPromise(request).toPromise();\n return data === undefined ? null : data.value;\n}\nfunction _deleteObject(db, key) {\n const request = getObjectStore(db, true).delete(key);\n return new DBPromise(request).toPromise();\n}\nconst _POLLING_INTERVAL_MS = 800;\nconst _TRANSACTION_RETRY_COUNT = 3;\nclass IndexedDBLocalPersistence {\n registerLifecycleListeners() {\n if (typeof window !== 'undefined' &&\n typeof window.addEventListener === 'function') {\n window.addEventListener('pagehide', this.onPageHide);\n window.addEventListener('pageshow', this.onPageShow);\n }\n }\n unregisterLifecycleListeners() {\n if (typeof window !== 'undefined' &&\n typeof window.removeEventListener === 'function') {\n window.removeEventListener('pagehide', this.onPageHide);\n window.removeEventListener('pageshow', this.onPageShow);\n }\n }\n constructor() {\n this.type = \"LOCAL\" /* PersistenceType.LOCAL */;\n this.dbPromise = null;\n this._shouldAllowMigration = true;\n this.listeners = {};\n this.localCache = {};\n // setTimeout return value is platform specific\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this.pollTimer = null;\n this.isClosing = false;\n this.pendingWrites = 0;\n this.receiver = null;\n this.sender = null;\n this.serviceWorkerReceiverAvailable = false;\n this.activeServiceWorker = null;\n this.onPageHide = () => {\n this.isClosing = true;\n this.stopPolling();\n if (this.dbPromise) {\n this.dbPromise.then(db => db.close()).catch(() => { });\n this.dbPromise = null;\n }\n };\n this.onPageShow = () => {\n if (this.isClosing) {\n this.isClosing = false;\n if (Object.keys(this.listeners).length > 0) {\n this.startPolling();\n }\n }\n };\n // Fire & forget the service worker registration as it may never resolve\n this._workerInitializationPromise =\n this.initializeServiceWorkerMessaging().then(() => { }, () => { });\n }\n async _openDb() {\n if (this.dbPromise) {\n return this.dbPromise;\n }\n this.dbPromise = _openDatabase();\n this.dbPromise.catch(() => {\n this.dbPromise = null;\n });\n return this.dbPromise;\n }\n async _withRetries(op) {\n let numAttempts = 0;\n while (true) {\n try {\n const db = await this._openDb();\n return await op(db);\n }\n catch (e) {\n if (numAttempts++ > _TRANSACTION_RETRY_COUNT) {\n throw e;\n }\n if (this.dbPromise) {\n const dbPromise = this.dbPromise;\n this.dbPromise = null;\n try {\n const db = await dbPromise;\n db.close();\n }\n catch { }\n }\n // TODO: consider adding exponential backoff\n }\n }\n }\n /**\n * IndexedDB events do not propagate from the main window to the worker context. We rely on a\n * postMessage interface to send these events to the worker ourselves.\n */\n async initializeServiceWorkerMessaging() {\n return _isWorker() ? this.initializeReceiver() : this.initializeSender();\n }\n /**\n * As the worker we should listen to events from the main window.\n */\n async initializeReceiver() {\n this.receiver = Receiver._getInstance(_getWorkerGlobalScope());\n // Refresh from persistence if we receive a KeyChanged message.\n this.receiver._subscribe(\"keyChanged\" /* _EventType.KEY_CHANGED */, async (_origin, data) => {\n const keys = await this._poll();\n return {\n keyProcessed: keys.includes(data.key)\n };\n });\n // Let the sender know that we are listening so they give us more timeout.\n this.receiver._subscribe(\"ping\" /* _EventType.PING */, async (_origin, _data) => {\n return [\"keyChanged\" /* _EventType.KEY_CHANGED */];\n });\n }\n /**\n * As the main window, we should let the worker know when keys change (set and remove).\n *\n * @remarks\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/ready | ServiceWorkerContainer.ready}\n * may not resolve.\n */\n async initializeSender() {\n // Check to see if there's an active service worker.\n this.activeServiceWorker = await _getActiveServiceWorker();\n if (!this.activeServiceWorker) {\n return;\n }\n this.sender = new Sender(this.activeServiceWorker);\n // Ping the service worker to check what events they can handle.\n const results = await this.sender._send(\"ping\" /* _EventType.PING */, {}, 800 /* _TimeoutDuration.LONG_ACK */);\n if (!results) {\n return;\n }\n if (results[0]?.fulfilled &&\n results[0]?.value.includes(\"keyChanged\" /* _EventType.KEY_CHANGED */)) {\n this.serviceWorkerReceiverAvailable = true;\n }\n }\n /**\n * Let the worker know about a changed key, the exact key doesn't technically matter since the\n * worker will just trigger a full sync anyway.\n *\n * @remarks\n * For now, we only support one service worker per page.\n *\n * @param key - Storage key which changed.\n */\n async notifyServiceWorker(key) {\n if (!this.sender ||\n !this.activeServiceWorker ||\n _getServiceWorkerController() !== this.activeServiceWorker) {\n return;\n }\n try {\n await this.sender._send(\"keyChanged\" /* _EventType.KEY_CHANGED */, { key }, \n // Use long timeout if receiver has previously responded to a ping from us.\n this.serviceWorkerReceiverAvailable\n ? 800 /* _TimeoutDuration.LONG_ACK */\n : 50 /* _TimeoutDuration.ACK */);\n }\n catch {\n // This is a best effort approach. Ignore errors.\n }\n }\n async _isAvailable() {\n try {\n if (!indexedDB) {\n return false;\n }\n await this._withRetries(async (db) => {\n await _putObject(db, STORAGE_AVAILABLE_KEY, '1');\n await _deleteObject(db, STORAGE_AVAILABLE_KEY);\n });\n return true;\n }\n catch { }\n return false;\n }\n async _withPendingWrite(write) {\n this.pendingWrites++;\n try {\n await write();\n }\n finally {\n this.pendingWrites--;\n }\n }\n async _set(key, value) {\n return this._withPendingWrite(async () => {\n await this._withRetries((db) => _putObject(db, key, value));\n this.localCache[key] = value;\n return this.notifyServiceWorker(key);\n });\n }\n async _get(key) {\n const obj = (await this._withRetries((db) => getObject(db, key)));\n this.localCache[key] = obj;\n return obj;\n }\n async _remove(key) {\n return this._withPendingWrite(async () => {\n await this._withRetries((db) => _deleteObject(db, key));\n delete this.localCache[key];\n return this.notifyServiceWorker(key);\n });\n }\n async _poll() {\n if (this.isClosing) {\n return [];\n }\n try {\n // TODO: check if we need to fallback if getAll is not supported\n const result = await this._withRetries((db) => {\n const getAllRequest = getObjectStore(db, false).getAll();\n return new DBPromise(getAllRequest).toPromise();\n });\n if (this.isClosing) {\n return [];\n }\n if (!result) {\n return [];\n }\n // If we have pending writes in progress abort, we'll get picked up on the next poll\n if (this.pendingWrites !== 0) {\n return [];\n }\n const keys = [];\n const keysInResult = new Set();\n if (result.length !== 0) {\n for (const { fbase_key: key, value } of result) {\n keysInResult.add(key);\n if (JSON.stringify(this.localCache[key]) !== JSON.stringify(value)) {\n this.notifyListeners(key, value);\n keys.push(key);\n }\n }\n }\n for (const localKey of Object.keys(this.localCache)) {\n if (this.localCache[localKey] && !keysInResult.has(localKey)) {\n // Deleted\n this.notifyListeners(localKey, null);\n keys.push(localKey);\n }\n }\n return keys;\n }\n catch (e) {\n if (!this.isClosing) {\n _logWarn(`Firebase Auth cross-tab polling failed with error: ${e}`);\n }\n return [];\n }\n }\n notifyListeners(key, newValue) {\n this.localCache[key] = newValue;\n const listeners = this.listeners[key];\n if (listeners) {\n for (const listener of Array.from(listeners)) {\n listener(newValue);\n }\n }\n }\n startPolling() {\n this.stopPolling();\n this.pollTimer = setInterval(async () => this._poll(), _POLLING_INTERVAL_MS);\n }\n stopPolling() {\n if (this.pollTimer) {\n clearInterval(this.pollTimer);\n this.pollTimer = null;\n }\n }\n _addListener(key, listener) {\n if (Object.keys(this.listeners).length === 0) {\n this.startPolling();\n this.registerLifecycleListeners();\n }\n if (!this.listeners[key]) {\n this.listeners[key] = new Set();\n // Populate the cache to avoid spuriously triggering on first poll.\n void this._get(key); // This can happen in the background async and we can return immediately.\n }\n this.listeners[key].add(listener);\n }\n _removeListener(key, listener) {\n if (this.listeners[key]) {\n this.listeners[key].delete(listener);\n if (this.listeners[key].size === 0) {\n delete this.listeners[key];\n }\n }\n if (Object.keys(this.listeners).length === 0) {\n this.stopPolling();\n this.unregisterLifecycleListeners();\n }\n }\n}\nIndexedDBLocalPersistence.type = 'LOCAL';\n/**\n * An implementation of {@link Persistence} of type `LOCAL` using `indexedDB`\n * for the underlying storage.\n *\n * @public\n */\nconst indexedDBLocalPersistence = IndexedDBLocalPersistence;\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nfunction startSignInPhoneMfa(auth, request) {\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaSignIn:start\" /* Endpoint.START_MFA_SIGN_IN */, _addTidIfNecessary(auth, request));\n}\nfunction finalizeSignInPhoneMfa(auth, request) {\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaSignIn:finalize\" /* Endpoint.FINALIZE_MFA_SIGN_IN */, _addTidIfNecessary(auth, request));\n}\nfunction finalizeSignInTotpMfa(auth, request) {\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaSignIn:finalize\" /* Endpoint.FINALIZE_MFA_SIGN_IN */, _addTidIfNecessary(auth, request));\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// ReCaptcha will load using the same callback, so the callback function needs\n// to be kept around\nconst _JSLOAD_CALLBACK = _generateCallbackName('rcb');\nconst NETWORK_TIMEOUT_DELAY = new Delay(30000, 60000);\n/**\n * Loader for the GReCaptcha library. There should only ever be one of this.\n */\nclass ReCaptchaLoaderImpl {\n constructor() {\n this.hostLanguage = '';\n this.counter = 0;\n /**\n * Check for `render()` method. `window.grecaptcha` will exist if the Enterprise\n * version of the ReCAPTCHA script was loaded by someone else (e.g. App Check) but\n * `window.grecaptcha.render()` will not. Another load will add it.\n */\n this.librarySeparatelyLoaded = !!_window().grecaptcha?.render;\n }\n load(auth, hl = '') {\n _assert(isHostLanguageValid(hl), auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\n if (this.shouldResolveImmediately(hl) && isV2(_window().grecaptcha)) {\n return Promise.resolve(_window().grecaptcha);\n }\n return new Promise((resolve, reject) => {\n const networkTimeout = _window().setTimeout(() => {\n reject(_createError(auth, \"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));\n }, NETWORK_TIMEOUT_DELAY.get());\n _window()[_JSLOAD_CALLBACK] = () => {\n _window().clearTimeout(networkTimeout);\n delete _window()[_JSLOAD_CALLBACK];\n const recaptcha = _window().grecaptcha;\n if (!recaptcha || !isV2(recaptcha)) {\n reject(_createError(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */));\n return;\n }\n // Wrap the recaptcha render function so that we know if the developer has\n // called it separately\n const render = recaptcha.render;\n recaptcha.render = (container, params) => {\n const widgetId = render(container, params);\n this.counter++;\n return widgetId;\n };\n this.hostLanguage = hl;\n resolve(recaptcha);\n };\n const url = `${_recaptchaV2ScriptUrl()}?${querystring({\n onload: _JSLOAD_CALLBACK,\n render: 'explicit',\n hl\n })}`;\n _loadJS(url).catch(() => {\n clearTimeout(networkTimeout);\n reject(_createError(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */));\n });\n });\n }\n clearedOneInstance() {\n this.counter--;\n }\n shouldResolveImmediately(hl) {\n // We can resolve immediately if:\n // • grecaptcha is already defined AND (\n // 1. the requested language codes are the same OR\n // 2. there exists already a ReCaptcha on the page\n // 3. the library was already loaded by the app\n // In cases (2) and (3), we _can't_ reload as it would break the recaptchas\n // that are already in the page\n return (!!_window().grecaptcha?.render &&\n (hl === this.hostLanguage ||\n this.counter > 0 ||\n this.librarySeparatelyLoaded));\n }\n}\nfunction isHostLanguageValid(hl) {\n return hl.length <= 6 && /^\\s*[a-zA-Z0-9\\-]*\\s*$/.test(hl);\n}\nclass MockReCaptchaLoaderImpl {\n async load(auth) {\n return new MockReCaptcha(auth);\n }\n clearedOneInstance() { }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst RECAPTCHA_VERIFIER_TYPE = 'recaptcha';\nconst DEFAULT_PARAMS = {\n theme: 'light',\n type: 'image'\n};\n/**\n * An {@link https://www.google.com/recaptcha/ | reCAPTCHA}-based application verifier.\n *\n * @remarks\n * `RecaptchaVerifier` does not work in a Node.js environment.\n *\n * @public\n */\nclass RecaptchaVerifier {\n /**\n * @param authExtern - The corresponding Firebase {@link Auth} instance.\n *\n * @param containerOrId - The reCAPTCHA container parameter.\n *\n * @remarks\n * This has different meaning depending on whether the reCAPTCHA is hidden or visible. For a\n * visible reCAPTCHA the container must be empty. If a string is used, it has to correspond to\n * an element ID. The corresponding element must also must be in the DOM at the time of\n * initialization.\n *\n * @param parameters - The optional reCAPTCHA parameters.\n *\n * @remarks\n * Check the reCAPTCHA docs for a comprehensive list. All parameters are accepted except for\n * the sitekey. Firebase Auth backend provisions a reCAPTCHA for each project and will\n * configure this upon rendering. For an invisible reCAPTCHA, a size key must have the value\n * 'invisible'.\n */\n constructor(authExtern, containerOrId, parameters = {\n ...DEFAULT_PARAMS\n }) {\n this.parameters = parameters;\n /**\n * The application verifier type.\n *\n * @remarks\n * For a reCAPTCHA verifier, this is 'recaptcha'.\n */\n this.type = RECAPTCHA_VERIFIER_TYPE;\n this.destroyed = false;\n this.widgetId = null;\n this.tokenChangeListeners = new Set();\n this.renderPromise = null;\n this.recaptcha = null;\n this.auth = _castAuth(authExtern);\n this.isInvisible = this.parameters.size === 'invisible';\n _assert(typeof document !== 'undefined', this.auth, \"operation-not-supported-in-this-environment\" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */);\n const container = typeof containerOrId === 'string'\n ? document.getElementById(containerOrId)\n : containerOrId;\n _assert(container, this.auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\n this.container = container;\n this.parameters.callback = this.makeTokenCallback(this.parameters.callback);\n this._recaptchaLoader = this.auth.settings.appVerificationDisabledForTesting\n ? new MockReCaptchaLoaderImpl()\n : new ReCaptchaLoaderImpl();\n this.validateStartingState();\n // TODO: Figure out if sdk version is needed\n }\n /**\n * Waits for the user to solve the reCAPTCHA and resolves with the reCAPTCHA token.\n *\n * @returns A Promise for the reCAPTCHA token.\n */\n async verify() {\n this.assertNotDestroyed();\n const id = await this.render();\n const recaptcha = this.getAssertedRecaptcha();\n const response = recaptcha.getResponse(id);\n if (response) {\n return response;\n }\n return new Promise(resolve => {\n const tokenChange = (token) => {\n if (!token) {\n return; // Ignore token expirations.\n }\n this.tokenChangeListeners.delete(tokenChange);\n resolve(token);\n };\n this.tokenChangeListeners.add(tokenChange);\n if (this.isInvisible) {\n recaptcha.execute(id);\n }\n });\n }\n /**\n * Renders the reCAPTCHA widget on the page.\n *\n * @returns A Promise that resolves with the reCAPTCHA widget ID.\n */\n render() {\n try {\n this.assertNotDestroyed();\n }\n catch (e) {\n // This method returns a promise. Since it's not async (we want to return the\n // _same_ promise if rendering is still occurring), the API surface should\n // reject with the error rather than just throw\n return Promise.reject(e);\n }\n if (this.renderPromise) {\n return this.renderPromise;\n }\n this.renderPromise = this.makeRenderPromise().catch(e => {\n this.renderPromise = null;\n throw e;\n });\n return this.renderPromise;\n }\n /** @internal */\n _reset() {\n this.assertNotDestroyed();\n if (this.widgetId !== null) {\n this.getAssertedRecaptcha().reset(this.widgetId);\n }\n }\n /**\n * Clears the reCAPTCHA widget from the page and destroys the instance.\n */\n clear() {\n this.assertNotDestroyed();\n this.destroyed = true;\n this._recaptchaLoader.clearedOneInstance();\n if (!this.isInvisible) {\n this.container.childNodes.forEach(node => {\n this.container.removeChild(node);\n });\n }\n }\n validateStartingState() {\n _assert(!this.parameters.sitekey, this.auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\n _assert(this.isInvisible || !this.container.hasChildNodes(), this.auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\n _assert(typeof document !== 'undefined', this.auth, \"operation-not-supported-in-this-environment\" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */);\n }\n makeTokenCallback(existing) {\n return token => {\n this.tokenChangeListeners.forEach(listener => listener(token));\n if (typeof existing === 'function') {\n existing(token);\n }\n else if (typeof existing === 'string') {\n const globalFunc = _window()[existing];\n if (typeof globalFunc === 'function') {\n globalFunc(token);\n }\n }\n };\n }\n assertNotDestroyed() {\n _assert(!this.destroyed, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n }\n async makeRenderPromise() {\n await this.init();\n if (!this.widgetId) {\n let container = this.container;\n if (!this.isInvisible) {\n const guaranteedEmpty = document.createElement('div');\n container.appendChild(guaranteedEmpty);\n container = guaranteedEmpty;\n }\n this.widgetId = this.getAssertedRecaptcha().render(container, this.parameters);\n }\n return this.widgetId;\n }\n async init() {\n _assert(_isHttpOrHttps() && !_isWorker(), this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n await domReady();\n this.recaptcha = await this._recaptchaLoader.load(this.auth, this.auth.languageCode || undefined);\n const siteKey = await getRecaptchaParams(this.auth);\n _assert(siteKey, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n this.parameters.sitekey = siteKey;\n }\n getAssertedRecaptcha() {\n _assert(this.recaptcha, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n return this.recaptcha;\n }\n}\nfunction domReady() {\n let resolver = null;\n return new Promise(resolve => {\n if (document.readyState === 'complete') {\n resolve();\n return;\n }\n // Document not ready, wait for load before resolving.\n // Save resolver, so we can remove listener in case it was externally\n // cancelled.\n resolver = () => resolve();\n window.addEventListener('load', resolver);\n }).catch(e => {\n if (resolver) {\n window.removeEventListener('load', resolver);\n }\n throw e;\n });\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass ConfirmationResultImpl {\n constructor(verificationId, onConfirmation) {\n this.verificationId = verificationId;\n this.onConfirmation = onConfirmation;\n }\n confirm(verificationCode) {\n const authCredential = PhoneAuthCredential._fromVerification(this.verificationId, verificationCode);\n return this.onConfirmation(authCredential);\n }\n}\n/**\n * Asynchronously signs in using a phone number.\n *\n * @remarks\n * This method sends a code via SMS to the given\n * phone number, and returns a {@link ConfirmationResult}. After the user\n * provides the code sent to their phone, call {@link ConfirmationResult.confirm}\n * with the code to sign the user in.\n *\n * For abuse prevention, this method requires a {@link ApplicationVerifier}.\n * This SDK includes an implementation based on reCAPTCHA v2, {@link RecaptchaVerifier}.\n * This function can work on other platforms that do not support the\n * {@link RecaptchaVerifier} (like React Native), but you need to use a\n * third-party {@link ApplicationVerifier} implementation.\n *\n * If you've enabled project-level reCAPTCHA Enterprise bot protection in\n * Enforce mode, you can omit the {@link ApplicationVerifier}.\n *\n * This method does not work in a Node.js environment or with {@link Auth} instances created with a\n * {@link @firebase/app#FirebaseServerApp}.\n *\n * @example\n * ```javascript\n * // 'recaptcha-container' is the ID of an element in the DOM.\n * const applicationVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container');\n * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\n * // Obtain a verificationCode from the user.\n * const credential = await confirmationResult.confirm(verificationCode);\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\n * @param appVerifier - The {@link ApplicationVerifier}.\n *\n * @public\n */\nasync function signInWithPhoneNumber(auth, phoneNumber, appVerifier) {\n if (_isFirebaseServerApp(auth.app)) {\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\n }\n const authInternal = _castAuth(auth);\n const verificationId = await _verifyPhoneNumber(authInternal, phoneNumber, getModularInstance(appVerifier));\n return new ConfirmationResultImpl(verificationId, cred => signInWithCredential(authInternal, cred));\n}\n/**\n * Links the user account with the given phone number.\n *\n * @remarks\n * This method does not work in a Node.js environment.\n *\n * @param user - The user.\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\n * @param appVerifier - The {@link ApplicationVerifier}.\n *\n * @public\n */\nasync function linkWithPhoneNumber(user, phoneNumber, appVerifier) {\n const userInternal = getModularInstance(user);\n await _assertLinkedStatus(false, userInternal, \"phone\" /* ProviderId.PHONE */);\n const verificationId = await _verifyPhoneNumber(userInternal.auth, phoneNumber, getModularInstance(appVerifier));\n return new ConfirmationResultImpl(verificationId, cred => linkWithCredential(userInternal, cred));\n}\n/**\n * Re-authenticates a user using a fresh phone credential.\n *\n * @remarks\n * Use before operations such as {@link updatePassword} that require tokens from recent sign-in attempts.\n *\n * This method does not work in a Node.js environment or on any {@link User} signed in by\n * {@link Auth} instances created with a {@link @firebase/app#FirebaseServerApp}.\n *\n * @param user - The user.\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\n * @param appVerifier - The {@link ApplicationVerifier}.\n *\n * @public\n */\nasync function reauthenticateWithPhoneNumber(user, phoneNumber, appVerifier) {\n const userInternal = getModularInstance(user);\n if (_isFirebaseServerApp(userInternal.auth.app)) {\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(userInternal.auth));\n }\n const verificationId = await _verifyPhoneNumber(userInternal.auth, phoneNumber, getModularInstance(appVerifier));\n return new ConfirmationResultImpl(verificationId, cred => reauthenticateWithCredential(userInternal, cred));\n}\n/**\n * Returns a verification ID to be used in conjunction with the SMS code that is sent.\n *\n */\nasync function _verifyPhoneNumber(auth, options, verifier) {\n if (!auth._getRecaptchaConfig()) {\n try {\n await _initializeRecaptchaConfig(auth);\n }\n catch (error) {\n // If an error occurs while fetching the config, there is no way to know the enablement state\n // of Phone provider, so we proceed with recaptcha V2 verification.\n // The error is likely \"recaptchaKey undefined\", as reCAPTCHA Enterprise is not\n // enabled for any provider.\n console.log('Failed to initialize reCAPTCHA Enterprise config. Triggering the reCAPTCHA v2 verification.');\n }\n }\n try {\n let phoneInfoOptions;\n if (typeof options === 'string') {\n phoneInfoOptions = {\n phoneNumber: options\n };\n }\n else {\n phoneInfoOptions = options;\n }\n if ('session' in phoneInfoOptions) {\n const session = phoneInfoOptions.session;\n if ('phoneNumber' in phoneInfoOptions) {\n _assert(session.type === \"enroll\" /* MultiFactorSessionType.ENROLL */, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n const startPhoneMfaEnrollmentRequest = {\n idToken: session.credential,\n phoneEnrollmentInfo: {\n phoneNumber: phoneInfoOptions.phoneNumber,\n clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */\n }\n };\n const startEnrollPhoneMfaActionCallback = async (authInstance, request) => {\n // If reCAPTCHA Enterprise token is FAKE_TOKEN, fetch reCAPTCHA v2 token and inject into request.\n if (request.phoneEnrollmentInfo.captchaResponse === FAKE_TOKEN) {\n _assert(verifier?.type === RECAPTCHA_VERIFIER_TYPE, authInstance, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\n const requestWithRecaptchaV2 = await injectRecaptchaV2Token(authInstance, request, verifier);\n return startEnrollPhoneMfa(authInstance, requestWithRecaptchaV2);\n }\n return startEnrollPhoneMfa(authInstance, request);\n };\n const startPhoneMfaEnrollmentResponse = handleRecaptchaFlow(auth, startPhoneMfaEnrollmentRequest, \"mfaSmsEnrollment\" /* RecaptchaActionName.MFA_SMS_ENROLLMENT */, startEnrollPhoneMfaActionCallback, \"PHONE_PROVIDER\" /* RecaptchaAuthProvider.PHONE_PROVIDER */);\n const response = await startPhoneMfaEnrollmentResponse.catch(error => {\n return Promise.reject(error);\n });\n return response.phoneSessionInfo.sessionInfo;\n }\n else {\n _assert(session.type === \"signin\" /* MultiFactorSessionType.SIGN_IN */, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n const mfaEnrollmentId = phoneInfoOptions.multiFactorHint?.uid ||\n phoneInfoOptions.multiFactorUid;\n _assert(mfaEnrollmentId, auth, \"missing-multi-factor-info\" /* AuthErrorCode.MISSING_MFA_INFO */);\n const startPhoneMfaSignInRequest = {\n mfaPendingCredential: session.credential,\n mfaEnrollmentId,\n phoneSignInInfo: {\n clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */\n }\n };\n const startSignInPhoneMfaActionCallback = async (authInstance, request) => {\n // If reCAPTCHA Enterprise token is FAKE_TOKEN, fetch reCAPTCHA v2 token and inject into request.\n if (request.phoneSignInInfo.captchaResponse === FAKE_TOKEN) {\n _assert(verifier?.type === RECAPTCHA_VERIFIER_TYPE, authInstance, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\n const requestWithRecaptchaV2 = await injectRecaptchaV2Token(authInstance, request, verifier);\n return startSignInPhoneMfa(authInstance, requestWithRecaptchaV2);\n }\n return startSignInPhoneMfa(authInstance, request);\n };\n const startPhoneMfaSignInResponse = handleRecaptchaFlow(auth, startPhoneMfaSignInRequest, \"mfaSmsSignIn\" /* RecaptchaActionName.MFA_SMS_SIGNIN */, startSignInPhoneMfaActionCallback, \"PHONE_PROVIDER\" /* RecaptchaAuthProvider.PHONE_PROVIDER */);\n const response = await startPhoneMfaSignInResponse.catch(error => {\n return Promise.reject(error);\n });\n return response.phoneResponseInfo.sessionInfo;\n }\n }\n else {\n const sendPhoneVerificationCodeRequest = {\n phoneNumber: phoneInfoOptions.phoneNumber,\n clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */\n };\n const sendPhoneVerificationCodeActionCallback = async (authInstance, request) => {\n // If reCAPTCHA Enterprise token is FAKE_TOKEN, fetch reCAPTCHA v2 token and inject into request.\n if (request.captchaResponse === FAKE_TOKEN) {\n _assert(verifier?.type === RECAPTCHA_VERIFIER_TYPE, authInstance, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\n const requestWithRecaptchaV2 = await injectRecaptchaV2Token(authInstance, request, verifier);\n return sendPhoneVerificationCode(authInstance, requestWithRecaptchaV2);\n }\n return sendPhoneVerificationCode(authInstance, request);\n };\n const sendPhoneVerificationCodeResponse = handleRecaptchaFlow(auth, sendPhoneVerificationCodeRequest, \"sendVerificationCode\" /* RecaptchaActionName.SEND_VERIFICATION_CODE */, sendPhoneVerificationCodeActionCallback, \"PHONE_PROVIDER\" /* RecaptchaAuthProvider.PHONE_PROVIDER */);\n const response = await sendPhoneVerificationCodeResponse.catch(error => {\n return Promise.reject(error);\n });\n return response.sessionInfo;\n }\n }\n finally {\n verifier?._reset();\n }\n}\n/**\n * Updates the user's phone number.\n *\n * @remarks\n * This method does not work in a Node.js environment or on any {@link User} signed in by\n * {@link Auth} instances created with a {@link @firebase/app#FirebaseServerApp}.\n *\n * @example\n * ```\n * // 'recaptcha-container' is the ID of an element in the DOM.\n * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');\n * const provider = new PhoneAuthProvider(auth);\n * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);\n * // Obtain the verificationCode from the user.\n * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\n * await updatePhoneNumber(user, phoneCredential);\n * ```\n *\n * @param user - The user.\n * @param credential - A credential authenticating the new phone number.\n *\n * @public\n */\nasync function updatePhoneNumber(user, credential) {\n const userInternal = getModularInstance(user);\n if (_isFirebaseServerApp(userInternal.auth.app)) {\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(userInternal.auth));\n }\n await _link$1(userInternal, credential);\n}\n// Helper function that fetches and injects a reCAPTCHA v2 token into the request.\nasync function injectRecaptchaV2Token(auth, request, recaptchaV2Verifier) {\n _assert(recaptchaV2Verifier.type === RECAPTCHA_VERIFIER_TYPE, auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\n const recaptchaV2Token = await recaptchaV2Verifier.verify();\n _assert(typeof recaptchaV2Token === 'string', auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\n const newRequest = { ...request };\n if ('phoneEnrollmentInfo' in newRequest) {\n const phoneNumber = newRequest.phoneEnrollmentInfo.phoneNumber;\n const captchaResponse = newRequest.phoneEnrollmentInfo.captchaResponse;\n const clientType = newRequest\n .phoneEnrollmentInfo.clientType;\n const recaptchaVersion = newRequest.phoneEnrollmentInfo.recaptchaVersion;\n Object.assign(newRequest, {\n 'phoneEnrollmentInfo': {\n phoneNumber,\n recaptchaToken: recaptchaV2Token,\n captchaResponse,\n clientType,\n recaptchaVersion\n }\n });\n return newRequest;\n }\n else if ('phoneSignInInfo' in newRequest) {\n const captchaResponse = newRequest.phoneSignInInfo.captchaResponse;\n const clientType = newRequest\n .phoneSignInInfo.clientType;\n const recaptchaVersion = newRequest.phoneSignInInfo.recaptchaVersion;\n Object.assign(newRequest, {\n 'phoneSignInInfo': {\n recaptchaToken: recaptchaV2Token,\n captchaResponse,\n clientType,\n recaptchaVersion\n }\n });\n return newRequest;\n }\n else {\n Object.assign(newRequest, { 'recaptchaToken': recaptchaV2Token });\n return newRequest;\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Provider for generating an {@link PhoneAuthCredential}.\n *\n * @remarks\n * `PhoneAuthProvider` does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * // 'recaptcha-container' is the ID of an element in the DOM.\n * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');\n * const provider = new PhoneAuthProvider(auth);\n * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);\n * // Obtain the verificationCode from the user.\n * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\n * const userCredential = await signInWithCredential(auth, phoneCredential);\n * ```\n *\n * @public\n */\nclass PhoneAuthProvider {\n /**\n * @param auth - The Firebase {@link Auth} instance in which sign-ins should occur.\n *\n */\n constructor(auth) {\n /** Always set to {@link ProviderId}.PHONE. */\n this.providerId = PhoneAuthProvider.PROVIDER_ID;\n this.auth = _castAuth(auth);\n }\n /**\n *\n * Starts a phone number authentication flow by sending a verification code to the given phone\n * number.\n *\n * @example\n * ```javascript\n * const provider = new PhoneAuthProvider(auth);\n * const verificationId = await provider.verifyPhoneNumber(phoneNumber, applicationVerifier);\n * // Obtain verificationCode from the user.\n * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\n * const userCredential = await signInWithCredential(auth, authCredential);\n * ```\n *\n * @example\n * An alternative flow is provided using the `signInWithPhoneNumber` method.\n * ```javascript\n * const confirmationResult = signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\n * // Obtain verificationCode from the user.\n * const userCredential = confirmationResult.confirm(verificationCode);\n * ```\n *\n * @param phoneInfoOptions - The user's {@link PhoneInfoOptions}. The phone number should be in\n * E.164 format (e.g. +16505550101).\n * @param applicationVerifier - An {@link ApplicationVerifier}, which prevents\n * requests from unauthorized clients. This SDK includes an implementation\n * based on reCAPTCHA v2, {@link RecaptchaVerifier}. If you've enabled\n * reCAPTCHA Enterprise bot protection in Enforce mode, this parameter is\n * optional; in all other configurations, the parameter is required.\n *\n * @returns A Promise for a verification ID that can be passed to\n * {@link PhoneAuthProvider.credential} to identify this flow.\n */\n verifyPhoneNumber(phoneOptions, applicationVerifier) {\n return _verifyPhoneNumber(this.auth, phoneOptions, getModularInstance(applicationVerifier));\n }\n /**\n * Creates a phone auth credential, given the verification ID from\n * {@link PhoneAuthProvider.verifyPhoneNumber} and the code that was sent to the user's\n * mobile device.\n *\n * @example\n * ```javascript\n * const provider = new PhoneAuthProvider(auth);\n * const verificationId = provider.verifyPhoneNumber(phoneNumber, applicationVerifier);\n * // Obtain verificationCode from the user.\n * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\n * const userCredential = signInWithCredential(auth, authCredential);\n * ```\n *\n * @example\n * An alternative flow is provided using the `signInWithPhoneNumber` method.\n * ```javascript\n * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\n * // Obtain verificationCode from the user.\n * const userCredential = await confirmationResult.confirm(verificationCode);\n * ```\n *\n * @param verificationId - The verification ID returned from {@link PhoneAuthProvider.verifyPhoneNumber}.\n * @param verificationCode - The verification code sent to the user's mobile device.\n *\n * @returns The auth provider credential.\n */\n static credential(verificationId, verificationCode) {\n return PhoneAuthCredential._fromVerification(verificationId, verificationCode);\n }\n /**\n * Generates an {@link AuthCredential} from a {@link UserCredential}.\n * @param userCredential - The user credential.\n */\n static credentialFromResult(userCredential) {\n const credential = userCredential;\n return PhoneAuthProvider.credentialFromTaggedObject(credential);\n }\n /**\n * Returns an {@link AuthCredential} when passed an error.\n *\n * @remarks\n *\n * This method works for errors like\n * `auth/account-exists-with-different-credentials`. This is useful for\n * recovering when attempting to set a user's phone number but the number\n * in question is already tied to another account. For example, the following\n * code tries to update the current user's phone number, and if that\n * fails, links the user with the account associated with that number:\n *\n * ```js\n * const provider = new PhoneAuthProvider(auth);\n * const verificationId = await provider.verifyPhoneNumber(number, verifier);\n * try {\n * const code = ''; // Prompt the user for the verification code\n * await updatePhoneNumber(\n * auth.currentUser,\n * PhoneAuthProvider.credential(verificationId, code));\n * } catch (e) {\n * if ((e as FirebaseError)?.code === 'auth/account-exists-with-different-credential') {\n * const cred = PhoneAuthProvider.credentialFromError(e);\n * await linkWithCredential(auth.currentUser, cred);\n * }\n * }\n *\n * // At this point, auth.currentUser.phoneNumber === number.\n * ```\n *\n * @param error - The error to generate a credential from.\n */\n static credentialFromError(error) {\n return PhoneAuthProvider.credentialFromTaggedObject((error.customData || {}));\n }\n static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\n if (!tokenResponse) {\n return null;\n }\n const { phoneNumber, temporaryProof } = tokenResponse;\n if (phoneNumber && temporaryProof) {\n return PhoneAuthCredential._fromTokenResponse(phoneNumber, temporaryProof);\n }\n return null;\n }\n}\n/** Always set to {@link ProviderId}.PHONE. */\nPhoneAuthProvider.PROVIDER_ID = \"phone\" /* ProviderId.PHONE */;\n/** Always set to {@link SignInMethod}.PHONE. */\nPhoneAuthProvider.PHONE_SIGN_IN_METHOD = \"phone\" /* SignInMethod.PHONE */;\n\n/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Chooses a popup/redirect resolver to use. This prefers the override (which\n * is directly passed in), and falls back to the property set on the auth\n * object. If neither are available, this function errors w/ an argument error.\n */\nfunction _withDefaultResolver(auth, resolverOverride) {\n if (resolverOverride) {\n return _getInstance(resolverOverride);\n }\n _assert(auth._popupRedirectResolver, auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\n return auth._popupRedirectResolver;\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass IdpCredential extends AuthCredential {\n constructor(params) {\n super(\"custom\" /* ProviderId.CUSTOM */, \"custom\" /* ProviderId.CUSTOM */);\n this.params = params;\n }\n _getIdTokenResponse(auth) {\n return signInWithIdp(auth, this._buildIdpRequest());\n }\n _linkToIdToken(auth, idToken) {\n return signInWithIdp(auth, this._buildIdpRequest(idToken));\n }\n _getReauthenticationResolver(auth) {\n return signInWithIdp(auth, this._buildIdpRequest());\n }\n _buildIdpRequest(idToken) {\n const request = {\n requestUri: this.params.requestUri,\n sessionId: this.params.sessionId,\n postBody: this.params.postBody,\n tenantId: this.params.tenantId,\n pendingToken: this.params.pendingToken,\n returnSecureToken: true,\n returnIdpCredential: true\n };\n if (idToken) {\n request.idToken = idToken;\n }\n return request;\n }\n}\nfunction _signIn(params) {\n return _signInWithCredential(params.auth, new IdpCredential(params), params.bypassAuthState);\n}\nfunction _reauth(params) {\n const { auth, user } = params;\n _assert(user, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n return _reauthenticate(user, new IdpCredential(params), params.bypassAuthState);\n}\nasync function _link(params) {\n const { auth, user } = params;\n _assert(user, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n return _link$1(user, new IdpCredential(params), params.bypassAuthState);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Popup event manager. Handles the popup's entire lifecycle; listens to auth\n * events\n */\nclass AbstractPopupRedirectOperation {\n constructor(auth, filter, resolver, user, bypassAuthState = false) {\n this.auth = auth;\n this.resolver = resolver;\n this.user = user;\n this.bypassAuthState = bypassAuthState;\n this.pendingPromise = null;\n this.eventManager = null;\n this.filter = Array.isArray(filter) ? filter : [filter];\n }\n execute() {\n return new Promise(async (resolve, reject) => {\n this.pendingPromise = { resolve, reject };\n try {\n this.eventManager = await this.resolver._initialize(this.auth);\n await this.onExecution();\n this.eventManager.registerConsumer(this);\n }\n catch (e) {\n this.reject(e);\n }\n });\n }\n async onAuthEvent(event) {\n const { urlResponse, sessionId, postBody, tenantId, error, type } = event;\n if (error) {\n this.reject(error);\n return;\n }\n const params = {\n auth: this.auth,\n requestUri: urlResponse,\n sessionId: sessionId,\n tenantId: tenantId || undefined,\n postBody: postBody || undefined,\n user: this.user,\n bypassAuthState: this.bypassAuthState\n };\n try {\n this.resolve(await this.getIdpTask(type)(params));\n }\n catch (e) {\n this.reject(e);\n }\n }\n onError(error) {\n this.reject(error);\n }\n getIdpTask(type) {\n switch (type) {\n case \"signInViaPopup\" /* AuthEventType.SIGN_IN_VIA_POPUP */:\n case \"signInViaRedirect\" /* AuthEventType.SIGN_IN_VIA_REDIRECT */:\n return _signIn;\n case \"linkViaPopup\" /* AuthEventType.LINK_VIA_POPUP */:\n case \"linkViaRedirect\" /* AuthEventType.LINK_VIA_REDIRECT */:\n return _link;\n case \"reauthViaPopup\" /* AuthEventType.REAUTH_VIA_POPUP */:\n case \"reauthViaRedirect\" /* AuthEventType.REAUTH_VIA_REDIRECT */:\n return _reauth;\n default:\n _fail(this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n }\n }\n resolve(cred) {\n debugAssert(this.pendingPromise, 'Pending promise was never set');\n this.pendingPromise.resolve(cred);\n this.unregisterAndCleanUp();\n }\n reject(error) {\n debugAssert(this.pendingPromise, 'Pending promise was never set');\n this.pendingPromise.reject(error);\n this.unregisterAndCleanUp();\n }\n unregisterAndCleanUp() {\n if (this.eventManager) {\n this.eventManager.unregisterConsumer(this);\n }\n this.pendingPromise = null;\n this.cleanUp();\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst _POLL_WINDOW_CLOSE_TIMEOUT = new Delay(2000, 10000);\n/**\n * Authenticates a Firebase client using a popup-based OAuth authentication flow.\n *\n * @remarks\n * If succeeds, returns the signed in user along with the provider's credential. If sign in was\n * unsuccessful, returns an error object containing additional information about the error.\n *\n * This method does not work in a Node.js environment or with {@link Auth} instances created with a\n * {@link @firebase/app#FirebaseServerApp}.\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new FacebookAuthProvider();\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a Facebook Access Token.\n * const credential = provider.credentialFromResult(auth, result);\n * const token = credential.accessToken;\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nasync function signInWithPopup(auth, provider, resolver) {\n if (_isFirebaseServerApp(auth.app)) {\n return Promise.reject(_createError(auth, \"operation-not-supported-in-this-environment\" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */));\n }\n const authInternal = _castAuth(auth);\n _assertInstanceOf(auth, provider, FederatedAuthProvider);\n const resolverInternal = _withDefaultResolver(authInternal, resolver);\n const action = new PopupOperation(authInternal, \"signInViaPopup\" /* AuthEventType.SIGN_IN_VIA_POPUP */, provider, resolverInternal);\n return action.executeNotNull();\n}\n/**\n * Reauthenticates the current user with the specified {@link OAuthProvider} using a pop-up based\n * OAuth flow.\n *\n * @remarks\n * If the reauthentication is successful, the returned result will contain the user and the\n * provider's credential.\n *\n * This method does not work in a Node.js environment or on any {@link User} signed in by\n * {@link Auth} instances created with a {@link @firebase/app#FirebaseServerApp}.\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new FacebookAuthProvider();\n * const result = await signInWithPopup(auth, provider);\n * // Reauthenticate using a popup.\n * await reauthenticateWithPopup(result.user, provider);\n * ```\n *\n * @param user - The user.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nasync function reauthenticateWithPopup(user, provider, resolver) {\n const userInternal = getModularInstance(user);\n if (_isFirebaseServerApp(userInternal.auth.app)) {\n return Promise.reject(_createError(userInternal.auth, \"operation-not-supported-in-this-environment\" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */));\n }\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\n const action = new PopupOperation(userInternal.auth, \"reauthViaPopup\" /* AuthEventType.REAUTH_VIA_POPUP */, provider, resolverInternal, userInternal);\n return action.executeNotNull();\n}\n/**\n * Links the authenticated provider to the user account using a pop-up based OAuth flow.\n *\n * @remarks\n * If the linking is successful, the returned result will contain the user and the provider's credential.\n *\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * // Sign in using some other provider.\n * const result = await signInWithEmailAndPassword(auth, email, password);\n * // Link using a popup.\n * const provider = new FacebookAuthProvider();\n * await linkWithPopup(result.user, provider);\n * ```\n *\n * @param user - The user.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nasync function linkWithPopup(user, provider, resolver) {\n const userInternal = getModularInstance(user);\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\n const action = new PopupOperation(userInternal.auth, \"linkViaPopup\" /* AuthEventType.LINK_VIA_POPUP */, provider, resolverInternal, userInternal);\n return action.executeNotNull();\n}\n/**\n * Popup event manager. Handles the popup's entire lifecycle; listens to auth\n * events\n *\n */\nclass PopupOperation extends AbstractPopupRedirectOperation {\n constructor(auth, filter, provider, resolver, user) {\n super(auth, filter, resolver, user);\n this.provider = provider;\n this.authWindow = null;\n this.pollId = null;\n if (PopupOperation.currentPopupAction) {\n PopupOperation.currentPopupAction.cancel();\n }\n PopupOperation.currentPopupAction = this;\n }\n async executeNotNull() {\n const result = await this.execute();\n _assert(result, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n return result;\n }\n async onExecution() {\n debugAssert(this.filter.length === 1, 'Popup operations only handle one event');\n const eventId = _generateEventId();\n this.authWindow = await this.resolver._openPopup(this.auth, this.provider, this.filter[0], // There's always one, see constructor\n eventId);\n this.authWindow.associatedEvent = eventId;\n // Check for web storage support and origin validation _after_ the popup is\n // loaded. These operations are slow (~1 second or so) Rather than\n // waiting on them before opening the window, optimistically open the popup\n // and check for storage support at the same time. If storage support is\n // not available, this will cause the whole thing to reject properly. It\n // will also close the popup, but since the promise has already rejected,\n // the popup closed by user poll will reject into the void.\n this.resolver._originValidation(this.auth).catch(e => {\n this.reject(e);\n });\n this.resolver._isIframeWebStorageSupported(this.auth, isSupported => {\n if (!isSupported) {\n this.reject(_createError(this.auth, \"web-storage-unsupported\" /* AuthErrorCode.WEB_STORAGE_UNSUPPORTED */));\n }\n });\n // Handle user closure. Notice this does *not* use await\n this.pollUserCancellation();\n }\n get eventId() {\n return this.authWindow?.associatedEvent || null;\n }\n cancel() {\n this.reject(_createError(this.auth, \"cancelled-popup-request\" /* AuthErrorCode.EXPIRED_POPUP_REQUEST */));\n }\n cleanUp() {\n if (this.authWindow) {\n this.authWindow.close();\n }\n if (this.pollId) {\n window.clearTimeout(this.pollId);\n }\n this.authWindow = null;\n this.pollId = null;\n PopupOperation.currentPopupAction = null;\n }\n pollUserCancellation() {\n const poll = () => {\n if (this.authWindow?.window?.closed) {\n // Make sure that there is sufficient time for whatever action to\n // complete. The window could have closed but the sign in network\n // call could still be in flight. This is specifically true for\n // Firefox or if the opener is in an iframe, in which case the oauth\n // helper closes the popup.\n this.pollId = window.setTimeout(() => {\n this.pollId = null;\n this.reject(_createError(this.auth, \"popup-closed-by-user\" /* AuthErrorCode.POPUP_CLOSED_BY_USER */));\n }, 8000 /* _Timeout.AUTH_EVENT */);\n return;\n }\n this.pollId = window.setTimeout(poll, _POLL_WINDOW_CLOSE_TIMEOUT.get());\n };\n poll();\n }\n}\n// Only one popup is ever shown at once. The lifecycle of the current popup\n// can be managed / cancelled by the constructor.\nPopupOperation.currentPopupAction = null;\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst PENDING_REDIRECT_KEY = 'pendingRedirect';\n// We only get one redirect outcome for any one auth, so just store it\n// in here.\nconst redirectOutcomeMap = new Map();\nclass RedirectAction extends AbstractPopupRedirectOperation {\n constructor(auth, resolver, bypassAuthState = false) {\n super(auth, [\n \"signInViaRedirect\" /* AuthEventType.SIGN_IN_VIA_REDIRECT */,\n \"linkViaRedirect\" /* AuthEventType.LINK_VIA_REDIRECT */,\n \"reauthViaRedirect\" /* AuthEventType.REAUTH_VIA_REDIRECT */,\n \"unknown\" /* AuthEventType.UNKNOWN */\n ], resolver, undefined, bypassAuthState);\n this.eventId = null;\n }\n /**\n * Override the execute function; if we already have a redirect result, then\n * just return it.\n */\n async execute() {\n let readyOutcome = redirectOutcomeMap.get(this.auth._key());\n if (!readyOutcome) {\n try {\n const hasPendingRedirect = await _getAndClearPendingRedirectStatus(this.resolver, this.auth);\n const result = hasPendingRedirect ? await super.execute() : null;\n readyOutcome = () => Promise.resolve(result);\n }\n catch (e) {\n readyOutcome = () => Promise.reject(e);\n }\n redirectOutcomeMap.set(this.auth._key(), readyOutcome);\n }\n // If we're not bypassing auth state, the ready outcome should be set to\n // null.\n if (!this.bypassAuthState) {\n redirectOutcomeMap.set(this.auth._key(), () => Promise.resolve(null));\n }\n return readyOutcome();\n }\n async onAuthEvent(event) {\n if (event.type === \"signInViaRedirect\" /* AuthEventType.SIGN_IN_VIA_REDIRECT */) {\n return super.onAuthEvent(event);\n }\n else if (event.type === \"unknown\" /* AuthEventType.UNKNOWN */) {\n // This is a sentinel value indicating there's no pending redirect\n this.resolve(null);\n return;\n }\n if (event.eventId) {\n const user = await this.auth._redirectUserForId(event.eventId);\n if (user) {\n this.user = user;\n return super.onAuthEvent(event);\n }\n else {\n this.resolve(null);\n }\n }\n }\n async onExecution() { }\n cleanUp() { }\n}\nasync function _getAndClearPendingRedirectStatus(resolver, auth) {\n const key = pendingRedirectKey(auth);\n const persistence = resolverPersistence(resolver);\n if (!(await persistence._isAvailable())) {\n return false;\n }\n const hasPendingRedirect = (await persistence._get(key)) === 'true';\n await persistence._remove(key);\n return hasPendingRedirect;\n}\nasync function _setPendingRedirectStatus(resolver, auth) {\n return resolverPersistence(resolver)._set(pendingRedirectKey(auth), 'true');\n}\nfunction _clearRedirectOutcomes() {\n redirectOutcomeMap.clear();\n}\nfunction _overrideRedirectResult(auth, result) {\n redirectOutcomeMap.set(auth._key(), result);\n}\nfunction resolverPersistence(resolver) {\n return _getInstance(resolver._redirectPersistence);\n}\nfunction pendingRedirectKey(auth) {\n return _persistenceKeyName(PENDING_REDIRECT_KEY, auth.config.apiKey, auth.name);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Authenticates a Firebase client using a full-page redirect flow.\n *\n * @remarks\n * To handle the results and errors for this operation, refer to {@link getRedirectResult}.\n * Follow the {@link https://firebase.google.com/docs/auth/web/redirect-best-practices\n * | best practices} when using {@link signInWithRedirect}.\n *\n * This method does not work in a Node.js environment or with {@link Auth} instances created with a\n * {@link @firebase/app#FirebaseServerApp}.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new FacebookAuthProvider();\n * // You can add additional scopes to the provider:\n * provider.addScope('user_birthday');\n * // Start a sign in process for an unauthenticated user.\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Facebook Access Token.\n * const credential = provider.credentialFromResult(auth, result);\n * const token = credential.accessToken;\n * }\n * // As this API can be used for sign-in, linking and reauthentication,\n * // check the operationType to determine what triggered this redirect\n * // operation.\n * const operationType = result.operationType;\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nfunction signInWithRedirect(auth, provider, resolver) {\n return _signInWithRedirect(auth, provider, resolver);\n}\nasync function _signInWithRedirect(auth, provider, resolver) {\n if (_isFirebaseServerApp(auth.app)) {\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\n }\n const authInternal = _castAuth(auth);\n _assertInstanceOf(auth, provider, FederatedAuthProvider);\n // Wait for auth initialization to complete, this will process pending redirects and clear the\n // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new\n // redirect and creating a PENDING_REDIRECT_KEY entry.\n await authInternal._initializationPromise;\n const resolverInternal = _withDefaultResolver(authInternal, resolver);\n await _setPendingRedirectStatus(resolverInternal, authInternal);\n return resolverInternal._openRedirect(authInternal, provider, \"signInViaRedirect\" /* AuthEventType.SIGN_IN_VIA_REDIRECT */);\n}\n/**\n * Reauthenticates the current user with the specified {@link OAuthProvider} using a full-page redirect flow.\n * @remarks\n * To handle the results and errors for this operation, refer to {@link getRedirectResult}.\n * Follow the {@link https://firebase.google.com/docs/auth/web/redirect-best-practices\n * | best practices} when using {@link reauthenticateWithRedirect}.\n *\n * This method does not work in a Node.js environment or with {@link Auth} instances\n * created with a {@link @firebase/app#FirebaseServerApp}.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new FacebookAuthProvider();\n * const result = await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * // Reauthenticate using a redirect.\n * await reauthenticateWithRedirect(result.user, provider);\n * // This will again trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * ```\n *\n * @param user - The user.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nfunction reauthenticateWithRedirect(user, provider, resolver) {\n return _reauthenticateWithRedirect(user, provider, resolver);\n}\nasync function _reauthenticateWithRedirect(user, provider, resolver) {\n const userInternal = getModularInstance(user);\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\n if (_isFirebaseServerApp(userInternal.auth.app)) {\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(userInternal.auth));\n }\n // Wait for auth initialization to complete, this will process pending redirects and clear the\n // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new\n // redirect and creating a PENDING_REDIRECT_KEY entry.\n await userInternal.auth._initializationPromise;\n // Allow the resolver to error before persisting the redirect user\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\n await _setPendingRedirectStatus(resolverInternal, userInternal.auth);\n const eventId = await prepareUserForRedirect(userInternal);\n return resolverInternal._openRedirect(userInternal.auth, provider, \"reauthViaRedirect\" /* AuthEventType.REAUTH_VIA_REDIRECT */, eventId);\n}\n/**\n * Links the {@link OAuthProvider} to the user account using a full-page redirect flow.\n * @remarks\n * To handle the results and errors for this operation, refer to {@link getRedirectResult}.\n * Follow the {@link https://firebase.google.com/docs/auth/web/redirect-best-practices\n * | best practices} when using {@link linkWithRedirect}.\n *\n * This method does not work in a Node.js environment or with {@link Auth} instances\n * created with a {@link @firebase/app#FirebaseServerApp}.\n *\n * @example\n * ```javascript\n * // Sign in using some other provider.\n * const result = await signInWithEmailAndPassword(auth, email, password);\n * // Link using a redirect.\n * const provider = new FacebookAuthProvider();\n * await linkWithRedirect(result.user, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * ```\n *\n * @param user - The user.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nfunction linkWithRedirect(user, provider, resolver) {\n return _linkWithRedirect(user, provider, resolver);\n}\nasync function _linkWithRedirect(user, provider, resolver) {\n const userInternal = getModularInstance(user);\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\n // Wait for auth initialization to complete, this will process pending redirects and clear the\n // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new\n // redirect and creating a PENDING_REDIRECT_KEY entry.\n await userInternal.auth._initializationPromise;\n // Allow the resolver to error before persisting the redirect user\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\n await _assertLinkedStatus(false, userInternal, provider.providerId);\n await _setPendingRedirectStatus(resolverInternal, userInternal.auth);\n const eventId = await prepareUserForRedirect(userInternal);\n return resolverInternal._openRedirect(userInternal.auth, provider, \"linkViaRedirect\" /* AuthEventType.LINK_VIA_REDIRECT */, eventId);\n}\n/**\n * Returns a {@link UserCredential} from the redirect-based sign-in flow.\n *\n * @remarks\n * If sign-in succeeded, returns the signed in user. If sign-in was unsuccessful, fails with an\n * error. If no redirect operation was called, returns `null`.\n *\n * This method does not work in a Node.js environment or with {@link Auth} instances created with a\n * {@link @firebase/app#FirebaseServerApp}.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new FacebookAuthProvider();\n * // You can add additional scopes to the provider:\n * provider.addScope('user_birthday');\n * // Start a sign in process for an unauthenticated user.\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Facebook Access Token.\n * const credential = provider.credentialFromResult(auth, result);\n * const token = credential.accessToken;\n * }\n * // As this API can be used for sign-in, linking and reauthentication,\n * // check the operationType to determine what triggered this redirect\n * // operation.\n * const operationType = result.operationType;\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nasync function getRedirectResult(auth, resolver) {\n await _castAuth(auth)._initializationPromise;\n return _getRedirectResult(auth, resolver, false);\n}\nasync function _getRedirectResult(auth, resolverExtern, bypassAuthState = false) {\n if (_isFirebaseServerApp(auth.app)) {\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\n }\n const authInternal = _castAuth(auth);\n const resolver = _withDefaultResolver(authInternal, resolverExtern);\n const action = new RedirectAction(authInternal, resolver, bypassAuthState);\n const result = await action.execute();\n if (result && !bypassAuthState) {\n delete result.user._redirectEventId;\n await authInternal._persistUserIfCurrent(result.user);\n await authInternal._setRedirectUser(null, resolverExtern);\n }\n return result;\n}\nasync function prepareUserForRedirect(user) {\n const eventId = _generateEventId(`${user.uid}:::`);\n user._redirectEventId = eventId;\n await user.auth._setRedirectUser(user);\n await user.auth._persistUserIfCurrent(user);\n return eventId;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// The amount of time to store the UIDs of seen events; this is\n// set to 10 min by default\nconst EVENT_DUPLICATION_CACHE_DURATION_MS = 10 * 60 * 1000;\nclass AuthEventManager {\n constructor(auth) {\n this.auth = auth;\n this.cachedEventUids = new Set();\n this.consumers = new Set();\n this.queuedRedirectEvent = null;\n this.hasHandledPotentialRedirect = false;\n this.lastProcessedEventTime = Date.now();\n }\n registerConsumer(authEventConsumer) {\n this.consumers.add(authEventConsumer);\n if (this.queuedRedirectEvent &&\n this.isEventForConsumer(this.queuedRedirectEvent, authEventConsumer)) {\n this.sendToConsumer(this.queuedRedirectEvent, authEventConsumer);\n this.saveEventToCache(this.queuedRedirectEvent);\n this.queuedRedirectEvent = null;\n }\n }\n unregisterConsumer(authEventConsumer) {\n this.consumers.delete(authEventConsumer);\n }\n onEvent(event) {\n // Check if the event has already been handled\n if (this.hasEventBeenHandled(event)) {\n return false;\n }\n let handled = false;\n this.consumers.forEach(consumer => {\n if (this.isEventForConsumer(event, consumer)) {\n handled = true;\n this.sendToConsumer(event, consumer);\n this.saveEventToCache(event);\n }\n });\n if (this.hasHandledPotentialRedirect || !isRedirectEvent(event)) {\n // If we've already seen a redirect before, or this is a popup event,\n // bail now\n return handled;\n }\n this.hasHandledPotentialRedirect = true;\n // If the redirect wasn't handled, hang on to it\n if (!handled) {\n this.queuedRedirectEvent = event;\n handled = true;\n }\n return handled;\n }\n sendToConsumer(event, consumer) {\n if (event.error && !isNullRedirectEvent(event)) {\n const code = event.error.code?.split('auth/')[1] ||\n \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */;\n consumer.onError(_createError(this.auth, code));\n }\n else {\n consumer.onAuthEvent(event);\n }\n }\n isEventForConsumer(event, consumer) {\n const eventIdMatches = consumer.eventId === null ||\n (!!event.eventId && event.eventId === consumer.eventId);\n return consumer.filter.includes(event.type) && eventIdMatches;\n }\n hasEventBeenHandled(event) {\n if (Date.now() - this.lastProcessedEventTime >=\n EVENT_DUPLICATION_CACHE_DURATION_MS) {\n this.cachedEventUids.clear();\n }\n return this.cachedEventUids.has(eventUid(event));\n }\n saveEventToCache(event) {\n this.cachedEventUids.add(eventUid(event));\n this.lastProcessedEventTime = Date.now();\n }\n}\nfunction eventUid(e) {\n return [e.type, e.eventId, e.sessionId, e.tenantId].filter(v => v).join('-');\n}\nfunction isNullRedirectEvent({ type, error }) {\n return (type === \"unknown\" /* AuthEventType.UNKNOWN */ &&\n error?.code === `auth/${\"no-auth-event\" /* AuthErrorCode.NO_AUTH_EVENT */}`);\n}\nfunction isRedirectEvent(event) {\n switch (event.type) {\n case \"signInViaRedirect\" /* AuthEventType.SIGN_IN_VIA_REDIRECT */:\n case \"linkViaRedirect\" /* AuthEventType.LINK_VIA_REDIRECT */:\n case \"reauthViaRedirect\" /* AuthEventType.REAUTH_VIA_REDIRECT */:\n return true;\n case \"unknown\" /* AuthEventType.UNKNOWN */:\n return isNullRedirectEvent(event);\n default:\n return false;\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nasync function _getProjectConfig(auth, request = {}) {\n return _performApiRequest(auth, \"GET\" /* HttpMethod.GET */, \"/v1/projects\" /* Endpoint.GET_PROJECT_CONFIG */, request);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst IP_ADDRESS_REGEX = /^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/;\nconst HTTP_REGEX = /^https?/;\nasync function _validateOrigin(auth) {\n // Skip origin validation if we are in an emulated environment\n if (auth.config.emulator) {\n return;\n }\n const { authorizedDomains } = await _getProjectConfig(auth);\n for (const domain of authorizedDomains) {\n try {\n if (matchDomain(domain)) {\n return;\n }\n }\n catch {\n // Do nothing if there's a URL error; just continue searching\n }\n }\n // In the old SDK, this error also provides helpful messages.\n _fail(auth, \"unauthorized-domain\" /* AuthErrorCode.INVALID_ORIGIN */);\n}\nfunction matchDomain(expected) {\n const currentUrl = _getCurrentUrl();\n const { protocol, hostname } = new URL(currentUrl);\n if (expected.startsWith('chrome-extension://')) {\n const ceUrl = new URL(expected);\n if (ceUrl.hostname === '' && hostname === '') {\n // For some reason we're not parsing chrome URLs properly\n return (protocol === 'chrome-extension:' &&\n expected.replace('chrome-extension://', '') ===\n currentUrl.replace('chrome-extension://', ''));\n }\n return protocol === 'chrome-extension:' && ceUrl.hostname === hostname;\n }\n if (!HTTP_REGEX.test(protocol)) {\n return false;\n }\n if (IP_ADDRESS_REGEX.test(expected)) {\n // The domain has to be exactly equal to the pattern, as an IP domain will\n // only contain the IP, no extra character.\n return hostname === expected;\n }\n // Dots in pattern should be escaped.\n const escapedDomainPattern = expected.replace(/\\./g, '\\\\.');\n // Non ip address domains.\n // domain.com = *.domain.com OR domain.com\n const re = new RegExp('^(.+\\\\.' + escapedDomainPattern + '|' + escapedDomainPattern + ')$', 'i');\n return re.test(hostname);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst NETWORK_TIMEOUT = new Delay(30000, 60000);\n/**\n * Reset unloaded GApi modules. If gapi.load fails due to a network error,\n * it will stop working after a retrial. This is a hack to fix this issue.\n */\nfunction resetUnloadedGapiModules() {\n // Clear last failed gapi.load state to force next gapi.load to first\n // load the failed gapi.iframes module.\n // Get gapix.beacon context.\n const beacon = _window().___jsl;\n // Get current hint.\n if (beacon?.H) {\n // Get gapi hint.\n for (const hint of Object.keys(beacon.H)) {\n // Requested modules.\n beacon.H[hint].r = beacon.H[hint].r || [];\n // Loaded modules.\n beacon.H[hint].L = beacon.H[hint].L || [];\n // Set requested modules to a copy of the loaded modules.\n beacon.H[hint].r = [...beacon.H[hint].L];\n // Clear pending callbacks.\n if (beacon.CP) {\n for (let i = 0; i < beacon.CP.length; i++) {\n // Remove all failed pending callbacks.\n beacon.CP[i] = null;\n }\n }\n }\n }\n}\nfunction loadGapi(auth) {\n return new Promise((resolve, reject) => {\n // Function to run when gapi.load is ready.\n function loadGapiIframe() {\n // The developer may have tried to previously run gapi.load and failed.\n // Run this to fix that.\n resetUnloadedGapiModules();\n gapi.load('gapi.iframes', {\n callback: () => {\n resolve(gapi.iframes.getContext());\n },\n ontimeout: () => {\n // The above reset may be sufficient, but having this reset after\n // failure ensures that if the developer calls gapi.load after the\n // connection is re-established and before another attempt to embed\n // the iframe, it would work and would not be broken because of our\n // failed attempt.\n // Timeout when gapi.iframes.Iframe not loaded.\n resetUnloadedGapiModules();\n reject(_createError(auth, \"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));\n },\n timeout: NETWORK_TIMEOUT.get()\n });\n }\n if (_window().gapi?.iframes?.Iframe) {\n // If gapi.iframes.Iframe available, resolve.\n resolve(gapi.iframes.getContext());\n }\n else if (!!_window().gapi?.load) {\n // Gapi loader ready, load gapi.iframes.\n loadGapiIframe();\n }\n else {\n // Create a new iframe callback when this is called so as not to overwrite\n // any previous defined callback. This happens if this method is called\n // multiple times in parallel and could result in the later callback\n // overwriting the previous one. This would end up with a iframe\n // timeout.\n const cbName = _generateCallbackName('iframefcb');\n // GApi loader not available, dynamically load platform.js.\n _window()[cbName] = () => {\n // GApi loader should be ready.\n if (!!gapi.load) {\n loadGapiIframe();\n }\n else {\n // Gapi loader failed, throw error.\n reject(_createError(auth, \"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));\n }\n };\n // Load GApi loader.\n return _loadJS(`${_gapiScriptUrl()}?onload=${cbName}`)\n .catch(e => reject(e));\n }\n }).catch(error => {\n // Reset cached promise to allow for retrial.\n cachedGApiLoader = null;\n throw error;\n });\n}\nlet cachedGApiLoader = null;\nfunction _loadGapi(auth) {\n cachedGApiLoader = cachedGApiLoader || loadGapi(auth);\n return cachedGApiLoader;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst PING_TIMEOUT = new Delay(5000, 15000);\nconst IFRAME_PATH = '__/auth/iframe';\nconst EMULATED_IFRAME_PATH = 'emulator/auth/iframe';\nconst IFRAME_ATTRIBUTES = {\n style: {\n position: 'absolute',\n top: '-100px',\n width: '1px',\n height: '1px'\n },\n 'aria-hidden': 'true',\n tabindex: '-1'\n};\n// Map from apiHost to endpoint ID for passing into iframe. In current SDK, apiHost can be set to\n// anything (not from a list of endpoints with IDs as in legacy), so this is the closest we can get.\nconst EID_FROM_APIHOST = new Map([\n [\"identitytoolkit.googleapis.com\" /* DefaultConfig.API_HOST */, 'p'], // production\n ['staging-identitytoolkit.sandbox.googleapis.com', 's'], // staging\n ['test-identitytoolkit.sandbox.googleapis.com', 't'] // test\n]);\nfunction getIframeUrl(auth) {\n const config = auth.config;\n _assert(config.authDomain, auth, \"auth-domain-config-required\" /* AuthErrorCode.MISSING_AUTH_DOMAIN */);\n const url = config.emulator\n ? _emulatorUrl(config, EMULATED_IFRAME_PATH)\n : `https://${auth.config.authDomain}/${IFRAME_PATH}`;\n const params = {\n apiKey: config.apiKey,\n appName: auth.name,\n v: SDK_VERSION\n };\n const eid = EID_FROM_APIHOST.get(auth.config.apiHost);\n if (eid) {\n params.eid = eid;\n }\n const frameworks = auth._getFrameworks();\n if (frameworks.length) {\n params.fw = frameworks.join(',');\n }\n return `${url}?${querystring(params).slice(1)}`;\n}\nasync function _openIframe(auth) {\n const context = await _loadGapi(auth);\n const gapi = _window().gapi;\n _assert(gapi, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n return context.open({\n where: document.body,\n url: getIframeUrl(auth),\n messageHandlersFilter: gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER,\n attributes: IFRAME_ATTRIBUTES,\n dontclear: true\n }, (iframe) => new Promise(async (resolve, reject) => {\n await iframe.restyle({\n // Prevent iframe from closing on mouse out.\n setHideOnLeave: false\n });\n const networkError = _createError(auth, \"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */);\n // Confirm iframe is correctly loaded.\n // To fallback on failure, set a timeout.\n const networkErrorTimer = _window().setTimeout(() => {\n reject(networkError);\n }, PING_TIMEOUT.get());\n // Clear timer and resolve pending iframe ready promise.\n function clearTimerAndResolve() {\n _window().clearTimeout(networkErrorTimer);\n resolve(iframe);\n }\n // This returns an IThenable. However the reject part does not call\n // when the iframe is not loaded.\n iframe.ping(clearTimerAndResolve).then(clearTimerAndResolve, () => {\n reject(networkError);\n });\n }));\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst BASE_POPUP_OPTIONS = {\n location: 'yes',\n resizable: 'yes',\n statusbar: 'yes',\n toolbar: 'no'\n};\nconst DEFAULT_WIDTH = 500;\nconst DEFAULT_HEIGHT = 600;\nconst TARGET_BLANK = '_blank';\nconst FIREFOX_EMPTY_URL = 'http://localhost';\nclass AuthPopup {\n constructor(window) {\n this.window = window;\n this.associatedEvent = null;\n }\n close() {\n if (this.window) {\n try {\n this.window.close();\n }\n catch (e) { }\n }\n }\n}\nfunction _open(auth, url, name, width = DEFAULT_WIDTH, height = DEFAULT_HEIGHT) {\n const top = Math.max((window.screen.availHeight - height) / 2, 0).toString();\n const left = Math.max((window.screen.availWidth - width) / 2, 0).toString();\n let target = '';\n const options = {\n ...BASE_POPUP_OPTIONS,\n width: width.toString(),\n height: height.toString(),\n top,\n left\n };\n // Chrome iOS 7 and 8 is returning an undefined popup win when target is\n // specified, even though the popup is not necessarily blocked.\n const ua = getUA().toLowerCase();\n if (name) {\n target = _isChromeIOS(ua) ? TARGET_BLANK : name;\n }\n if (_isFirefox(ua)) {\n // Firefox complains when invalid URLs are popped out. Hacky way to bypass.\n url = url || FIREFOX_EMPTY_URL;\n // Firefox disables by default scrolling on popup windows, which can create\n // issues when the user has many Google accounts, for instance.\n options.scrollbars = 'yes';\n }\n const optionsString = Object.entries(options).reduce((accum, [key, value]) => `${accum}${key}=${value},`, '');\n if (_isIOSStandalone(ua) && target !== '_self') {\n openAsNewWindowIOS(url || '', target);\n return new AuthPopup(null);\n }\n // about:blank getting sanitized causing browsers like IE/Edge to display\n // brief error message before redirecting to handler.\n const newWin = window.open(url || '', target, optionsString);\n _assert(newWin, auth, \"popup-blocked\" /* AuthErrorCode.POPUP_BLOCKED */);\n // Flaky on IE edge, encapsulate with a try and catch.\n try {\n newWin.focus();\n }\n catch (e) { }\n return new AuthPopup(newWin);\n}\nfunction openAsNewWindowIOS(url, target) {\n const el = document.createElement('a');\n el.href = url;\n el.target = target;\n const click = document.createEvent('MouseEvent');\n click.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 1, null);\n el.dispatchEvent(click);\n}\n\n/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * URL for Authentication widget which will initiate the OAuth handshake\n *\n * @internal\n */\nconst WIDGET_PATH = '__/auth/handler';\n/**\n * URL for emulated environment\n *\n * @internal\n */\nconst EMULATOR_WIDGET_PATH = 'emulator/auth/handler';\n/**\n * Fragment name for the App Check token that gets passed to the widget\n *\n * @internal\n */\nconst FIREBASE_APP_CHECK_FRAGMENT_ID = encodeURIComponent('fac');\nasync function _getRedirectUrl(auth, provider, authType, redirectUrl, eventId, additionalParams) {\n _assert(auth.config.authDomain, auth, \"auth-domain-config-required\" /* AuthErrorCode.MISSING_AUTH_DOMAIN */);\n _assert(auth.config.apiKey, auth, \"invalid-api-key\" /* AuthErrorCode.INVALID_API_KEY */);\n const params = {\n apiKey: auth.config.apiKey,\n appName: auth.name,\n authType,\n redirectUrl,\n v: SDK_VERSION,\n eventId\n };\n if (provider instanceof FederatedAuthProvider) {\n provider.setDefaultLanguage(auth.languageCode);\n params.providerId = provider.providerId || '';\n if (!isEmpty(provider.getCustomParameters())) {\n params.customParameters = JSON.stringify(provider.getCustomParameters());\n }\n // TODO set additionalParams from the provider as well?\n for (const [key, value] of Object.entries(additionalParams || {})) {\n params[key] = value;\n }\n }\n if (provider instanceof BaseOAuthProvider) {\n const scopes = provider.getScopes().filter(scope => scope !== '');\n if (scopes.length > 0) {\n params.scopes = scopes.join(',');\n }\n }\n if (auth.tenantId) {\n params.tid = auth.tenantId;\n }\n // TODO: maybe set eid as endpointId\n // TODO: maybe set fw as Frameworks.join(\",\")\n const paramsDict = params;\n for (const key of Object.keys(paramsDict)) {\n if (paramsDict[key] === undefined) {\n delete paramsDict[key];\n }\n }\n // Sets the App Check token to pass to the widget\n const appCheckToken = await auth._getAppCheckToken();\n const appCheckTokenFragment = appCheckToken\n ? `#${FIREBASE_APP_CHECK_FRAGMENT_ID}=${encodeURIComponent(appCheckToken)}`\n : '';\n // Start at index 1 to skip the leading '&' in the query string\n return `${getHandlerBase(auth)}?${querystring(paramsDict).slice(1)}${appCheckTokenFragment}`;\n}\nfunction getHandlerBase({ config }) {\n if (!config.emulator) {\n return `https://${config.authDomain}/${WIDGET_PATH}`;\n }\n return _emulatorUrl(config, EMULATOR_WIDGET_PATH);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * The special web storage event\n *\n */\nconst WEB_STORAGE_SUPPORT_KEY = 'webStorageSupport';\nclass BrowserPopupRedirectResolver {\n constructor() {\n this.eventManagers = {};\n this.iframes = {};\n this.originValidationPromises = {};\n this._redirectPersistence = browserSessionPersistence;\n this._completeRedirectFn = _getRedirectResult;\n this._overrideRedirectResult = _overrideRedirectResult;\n }\n // Wrapping in async even though we don't await anywhere in order\n // to make sure errors are raised as promise rejections\n async _openPopup(auth, provider, authType, eventId) {\n debugAssert(this.eventManagers[auth._key()]?.manager, '_initialize() not called before _openPopup()');\n const url = await _getRedirectUrl(auth, provider, authType, _getCurrentUrl(), eventId);\n return _open(auth, url, _generateEventId());\n }\n async _openRedirect(auth, provider, authType, eventId) {\n await this._originValidation(auth);\n const url = await _getRedirectUrl(auth, provider, authType, _getCurrentUrl(), eventId);\n _setWindowLocation(url);\n return new Promise(() => { });\n }\n _initialize(auth) {\n const key = auth._key();\n if (this.eventManagers[key]) {\n const { manager, promise } = this.eventManagers[key];\n if (manager) {\n return Promise.resolve(manager);\n }\n else {\n debugAssert(promise, 'If manager is not set, promise should be');\n return promise;\n }\n }\n const promise = this.initAndGetManager(auth);\n this.eventManagers[key] = { promise };\n // If the promise is rejected, the key should be removed so that the\n // operation can be retried later.\n promise.catch(() => {\n delete this.eventManagers[key];\n });\n return promise;\n }\n async initAndGetManager(auth) {\n const iframe = await _openIframe(auth);\n const manager = new AuthEventManager(auth);\n iframe.register('authEvent', (iframeEvent) => {\n _assert(iframeEvent?.authEvent, auth, \"invalid-auth-event\" /* AuthErrorCode.INVALID_AUTH_EVENT */);\n // TODO: Consider splitting redirect and popup events earlier on\n const handled = manager.onEvent(iframeEvent.authEvent);\n return { status: handled ? \"ACK\" /* GapiOutcome.ACK */ : \"ERROR\" /* GapiOutcome.ERROR */ };\n }, gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER);\n this.eventManagers[auth._key()] = { manager };\n this.iframes[auth._key()] = iframe;\n return manager;\n }\n _isIframeWebStorageSupported(auth, cb) {\n const iframe = this.iframes[auth._key()];\n iframe.send(WEB_STORAGE_SUPPORT_KEY, { type: WEB_STORAGE_SUPPORT_KEY }, result => {\n const isSupported = result?.[0]?.[WEB_STORAGE_SUPPORT_KEY];\n if (isSupported !== undefined) {\n cb(!!isSupported);\n }\n _fail(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n }, gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER);\n }\n _originValidation(auth) {\n const key = auth._key();\n if (!this.originValidationPromises[key]) {\n this.originValidationPromises[key] = _validateOrigin(auth);\n }\n return this.originValidationPromises[key];\n }\n get _shouldInitProactively() {\n // Mobile browsers and Safari need to optimistically initialize\n return _isMobileBrowser() || _isSafari() || _isIOS();\n }\n}\n/**\n * An implementation of {@link PopupRedirectResolver} suitable for browser\n * based applications.\n *\n * @remarks\n * This method does not work in a Node.js environment.\n *\n * @public\n */\nconst browserPopupRedirectResolver = BrowserPopupRedirectResolver;\n\nclass MultiFactorAssertionImpl {\n constructor(factorId) {\n this.factorId = factorId;\n }\n _process(auth, session, displayName) {\n switch (session.type) {\n case \"enroll\" /* MultiFactorSessionType.ENROLL */:\n return this._finalizeEnroll(auth, session.credential, displayName);\n case \"signin\" /* MultiFactorSessionType.SIGN_IN */:\n return this._finalizeSignIn(auth, session.credential);\n default:\n return debugFail('unexpected MultiFactorSessionType');\n }\n }\n}\n\n/**\n * {@inheritdoc PhoneMultiFactorAssertion}\n *\n * @public\n */\nclass PhoneMultiFactorAssertionImpl extends MultiFactorAssertionImpl {\n constructor(credential) {\n super(\"phone\" /* FactorId.PHONE */);\n this.credential = credential;\n }\n /** @internal */\n static _fromCredential(credential) {\n return new PhoneMultiFactorAssertionImpl(credential);\n }\n /** @internal */\n _finalizeEnroll(auth, idToken, displayName) {\n return finalizeEnrollPhoneMfa(auth, {\n idToken,\n displayName,\n phoneVerificationInfo: this.credential._makeVerificationRequest()\n });\n }\n /** @internal */\n _finalizeSignIn(auth, mfaPendingCredential) {\n return finalizeSignInPhoneMfa(auth, {\n mfaPendingCredential,\n phoneVerificationInfo: this.credential._makeVerificationRequest()\n });\n }\n}\n/**\n * Provider for generating a {@link PhoneMultiFactorAssertion}.\n *\n * @public\n */\nclass PhoneMultiFactorGenerator {\n constructor() { }\n /**\n * Provides a {@link PhoneMultiFactorAssertion} to confirm ownership of the phone second factor.\n *\n * @remarks\n * This method does not work in a Node.js environment.\n *\n * @param phoneAuthCredential - A credential provided by {@link PhoneAuthProvider.credential}.\n * @returns A {@link PhoneMultiFactorAssertion} which can be used with\n * {@link MultiFactorResolver.resolveSignIn}\n */\n static assertion(credential) {\n return PhoneMultiFactorAssertionImpl._fromCredential(credential);\n }\n}\n/**\n * The identifier of the phone second factor: `phone`.\n */\nPhoneMultiFactorGenerator.FACTOR_ID = 'phone';\n\n/**\n * Provider for generating a {@link TotpMultiFactorAssertion}.\n *\n * @public\n */\nclass TotpMultiFactorGenerator {\n /**\n * Provides a {@link TotpMultiFactorAssertion} to confirm ownership of\n * the TOTP (time-based one-time password) second factor.\n * This assertion is used to complete enrollment in TOTP second factor.\n *\n * @param secret A {@link TotpSecret} containing the shared secret key and other TOTP parameters.\n * @param oneTimePassword One-time password from TOTP App.\n * @returns A {@link TotpMultiFactorAssertion} which can be used with\n * {@link MultiFactorUser.enroll}.\n */\n static assertionForEnrollment(secret, oneTimePassword) {\n return TotpMultiFactorAssertionImpl._fromSecret(secret, oneTimePassword);\n }\n /**\n * Provides a {@link TotpMultiFactorAssertion} to confirm ownership of the TOTP second factor.\n * This assertion is used to complete signIn with TOTP as the second factor.\n *\n * @param enrollmentId identifies the enrolled TOTP second factor.\n * @param oneTimePassword One-time password from TOTP App.\n * @returns A {@link TotpMultiFactorAssertion} which can be used with\n * {@link MultiFactorResolver.resolveSignIn}.\n */\n static assertionForSignIn(enrollmentId, oneTimePassword) {\n return TotpMultiFactorAssertionImpl._fromEnrollmentId(enrollmentId, oneTimePassword);\n }\n /**\n * Returns a promise to {@link TotpSecret} which contains the TOTP shared secret key and other parameters.\n * Creates a TOTP secret as part of enrolling a TOTP second factor.\n * Used for generating a QR code URL or inputting into a TOTP app.\n * This method uses the auth instance corresponding to the user in the multiFactorSession.\n *\n * @param session The {@link MultiFactorSession} that the user is part of.\n * @returns A promise to {@link TotpSecret}.\n */\n static async generateSecret(session) {\n const mfaSession = session;\n _assert(typeof mfaSession.user?.auth !== 'undefined', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n const response = await startEnrollTotpMfa(mfaSession.user.auth, {\n idToken: mfaSession.credential,\n totpEnrollmentInfo: {}\n });\n return TotpSecret._fromStartTotpMfaEnrollmentResponse(response, mfaSession.user.auth);\n }\n}\n/**\n * The identifier of the TOTP second factor: `totp`.\n */\nTotpMultiFactorGenerator.FACTOR_ID = \"totp\" /* FactorId.TOTP */;\nclass TotpMultiFactorAssertionImpl extends MultiFactorAssertionImpl {\n constructor(otp, enrollmentId, secret) {\n super(\"totp\" /* FactorId.TOTP */);\n this.otp = otp;\n this.enrollmentId = enrollmentId;\n this.secret = secret;\n }\n /** @internal */\n static _fromSecret(secret, otp) {\n return new TotpMultiFactorAssertionImpl(otp, undefined, secret);\n }\n /** @internal */\n static _fromEnrollmentId(enrollmentId, otp) {\n return new TotpMultiFactorAssertionImpl(otp, enrollmentId);\n }\n /** @internal */\n async _finalizeEnroll(auth, idToken, displayName) {\n _assert(typeof this.secret !== 'undefined', auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\n return finalizeEnrollTotpMfa(auth, {\n idToken,\n displayName,\n totpVerificationInfo: this.secret._makeTotpVerificationInfo(this.otp)\n });\n }\n /** @internal */\n async _finalizeSignIn(auth, mfaPendingCredential) {\n _assert(this.enrollmentId !== undefined && this.otp !== undefined, auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\n const totpVerificationInfo = { verificationCode: this.otp };\n return finalizeSignInTotpMfa(auth, {\n mfaPendingCredential,\n mfaEnrollmentId: this.enrollmentId,\n totpVerificationInfo\n });\n }\n}\n/**\n * Provider for generating a {@link TotpMultiFactorAssertion}.\n *\n * Stores the shared secret key and other parameters to generate time-based OTPs.\n * Implements methods to retrieve the shared secret key and generate a QR code URL.\n * @public\n */\nclass TotpSecret {\n // The public members are declared outside the constructor so the docs can be generated.\n constructor(secretKey, hashingAlgorithm, codeLength, codeIntervalSeconds, enrollmentCompletionDeadline, sessionInfo, auth) {\n this.sessionInfo = sessionInfo;\n this.auth = auth;\n this.secretKey = secretKey;\n this.hashingAlgorithm = hashingAlgorithm;\n this.codeLength = codeLength;\n this.codeIntervalSeconds = codeIntervalSeconds;\n this.enrollmentCompletionDeadline = enrollmentCompletionDeadline;\n }\n /** @internal */\n static _fromStartTotpMfaEnrollmentResponse(response, auth) {\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);\n }\n /** @internal */\n _makeTotpVerificationInfo(otp) {\n return { sessionInfo: this.sessionInfo, verificationCode: otp };\n }\n /**\n * Returns a QR code URL as described in\n * https://github.com/google/google-authenticator/wiki/Key-Uri-Format\n * This can be displayed to the user as a QR code to be scanned into a TOTP app like Google Authenticator.\n * If the optional parameters are unspecified, an accountName of <userEmail> and issuer of <firebaseAppName> are used.\n *\n * @param accountName the name of the account/app along with a user identifier.\n * @param issuer issuer of the TOTP (likely the app name).\n * @returns A QR code URL string.\n */\n generateQrCodeUrl(accountName, issuer) {\n let useDefaults = false;\n if (_isEmptyString(accountName) || _isEmptyString(issuer)) {\n useDefaults = true;\n }\n if (useDefaults) {\n if (_isEmptyString(accountName)) {\n accountName = this.auth.currentUser?.email || 'unknownuser';\n }\n if (_isEmptyString(issuer)) {\n issuer = this.auth.name;\n }\n }\n return `otpauth://totp/${issuer}:${accountName}?secret=${this.secretKey}&issuer=${issuer}&algorithm=${this.hashingAlgorithm}&digits=${this.codeLength}`;\n }\n}\n/** @internal */\nfunction _isEmptyString(input) {\n return typeof input === 'undefined' || input?.length === 0;\n}\n\nvar name = \"@firebase/auth\";\nvar version = \"1.13.7\";\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass AuthInterop {\n constructor(auth) {\n this.auth = auth;\n this.internalListeners = new Map();\n }\n getUid() {\n this.assertAuthConfigured();\n return this.auth.currentUser?.uid || null;\n }\n async getToken(forceRefresh) {\n this.assertAuthConfigured();\n await this.auth._initializationPromise;\n if (!this.auth.currentUser) {\n return null;\n }\n const accessToken = await this.auth.currentUser.getIdToken(forceRefresh);\n return { accessToken };\n }\n addAuthTokenListener(listener) {\n this.assertAuthConfigured();\n if (this.internalListeners.has(listener)) {\n return;\n }\n const unsubscribe = this.auth.onIdTokenChanged(user => {\n listener(user?.stsTokenManager.accessToken || null);\n });\n this.internalListeners.set(listener, unsubscribe);\n this.updateProactiveRefresh();\n }\n removeAuthTokenListener(listener) {\n this.assertAuthConfigured();\n const unsubscribe = this.internalListeners.get(listener);\n if (!unsubscribe) {\n return;\n }\n this.internalListeners.delete(listener);\n unsubscribe();\n this.updateProactiveRefresh();\n }\n assertAuthConfigured() {\n _assert(this.auth._initializationPromise, \"dependent-sdk-initialized-before-auth\" /* AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH */);\n }\n updateProactiveRefresh() {\n if (this.internalListeners.size > 0) {\n this.auth._startProactiveRefresh();\n }\n else {\n this.auth._stopProactiveRefresh();\n }\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nfunction getVersionForPlatform(clientPlatform) {\n switch (clientPlatform) {\n case \"Node\" /* ClientPlatform.NODE */:\n return 'node';\n case \"ReactNative\" /* ClientPlatform.REACT_NATIVE */:\n return 'rn';\n case \"Worker\" /* ClientPlatform.WORKER */:\n return 'webworker';\n case \"Cordova\" /* ClientPlatform.CORDOVA */:\n return 'cordova';\n case \"WebExtension\" /* ClientPlatform.WEB_EXTENSION */:\n return 'web-extension';\n default:\n return undefined;\n }\n}\n/** @internal */\nfunction registerAuth(clientPlatform) {\n _registerComponent(new Component(\"auth\" /* _ComponentName.AUTH */, (container, { options: deps }) => {\n const app = container.getProvider('app').getImmediate();\n const heartbeatServiceProvider = container.getProvider('heartbeat');\n const appCheckServiceProvider = container.getProvider('app-check-internal');\n const { apiKey, authDomain } = app.options;\n _assert(apiKey && !apiKey.includes(':'), \"invalid-api-key\" /* AuthErrorCode.INVALID_API_KEY */, { appName: app.name });\n const config = {\n apiKey,\n authDomain,\n clientPlatform,\n apiHost: \"identitytoolkit.googleapis.com\" /* DefaultConfig.API_HOST */,\n tokenApiHost: \"securetoken.googleapis.com\" /* DefaultConfig.TOKEN_API_HOST */,\n apiScheme: \"https\" /* DefaultConfig.API_SCHEME */,\n sdkClientVersion: _getClientVersion(clientPlatform)\n };\n const authInstance = new AuthImpl(app, heartbeatServiceProvider, appCheckServiceProvider, config);\n _initializeAuthInstance(authInstance, deps);\n return authInstance;\n }, \"PUBLIC\" /* ComponentType.PUBLIC */)\n /**\n * Auth can only be initialized by explicitly calling getAuth() or initializeAuth()\n * For why we do this, See go/firebase-next-auth-init\n */\n .setInstantiationMode(\"EXPLICIT\" /* InstantiationMode.EXPLICIT */)\n /**\n * Because all firebase products that depend on auth depend on auth-internal directly,\n * we need to initialize auth-internal after auth is initialized to make it available to other firebase products.\n */\n .setInstanceCreatedCallback((container, _instanceIdentifier, _instance) => {\n const authInternalProvider = container.getProvider(\"auth-internal\" /* _ComponentName.AUTH_INTERNAL */);\n authInternalProvider.initialize();\n }));\n _registerComponent(new Component(\"auth-internal\" /* _ComponentName.AUTH_INTERNAL */, container => {\n const auth = _castAuth(container.getProvider(\"auth\" /* _ComponentName.AUTH */).getImmediate());\n return (auth => new AuthInterop(auth))(auth);\n }, \"PRIVATE\" /* ComponentType.PRIVATE */).setInstantiationMode(\"EXPLICIT\" /* InstantiationMode.EXPLICIT */));\n registerVersion(name, version, getVersionForPlatform(clientPlatform));\n // BUILD_TARGET will be replaced by values like esm, cjs, etc during the compilation\n registerVersion(name, version, 'esm2020');\n}\n\n/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst DEFAULT_ID_TOKEN_MAX_AGE = 5 * 60;\nconst authIdTokenMaxAge = getExperimentalSetting('authIdTokenMaxAge') || DEFAULT_ID_TOKEN_MAX_AGE;\nlet lastPostedIdToken = null;\nconst mintCookieFactory = (url) => async (user) => {\n const idTokenResult = user && (await user.getIdTokenResult());\n const idTokenAge = idTokenResult &&\n (new Date().getTime() - Date.parse(idTokenResult.issuedAtTime)) / 1000;\n if (idTokenAge && idTokenAge > authIdTokenMaxAge) {\n return;\n }\n // Specifically trip null => undefined when logged out, to delete any existing cookie\n const idToken = idTokenResult?.token;\n if (lastPostedIdToken === idToken) {\n return;\n }\n lastPostedIdToken = idToken;\n await fetch(url, {\n method: idToken ? 'POST' : 'DELETE',\n headers: idToken\n ? {\n 'Authorization': `Bearer ${idToken}`\n }\n : {}\n });\n};\n/**\n * Returns the Auth instance associated with the provided {@link @firebase/app#FirebaseApp}.\n * If no instance exists, initializes an Auth instance with platform-specific default dependencies.\n *\n * @param app - The Firebase App.\n *\n * @public\n */\nfunction getAuth(app = getApp()) {\n const provider = _getProvider(app, 'auth');\n if (provider.isInitialized()) {\n return provider.getImmediate();\n }\n const auth = initializeAuth(app, {\n popupRedirectResolver: browserPopupRedirectResolver,\n persistence: [\n indexedDBLocalPersistence,\n browserLocalPersistence,\n browserSessionPersistence\n ]\n });\n const authTokenSyncPath = getExperimentalSetting('authTokenSyncURL');\n // Only do the Cookie exchange in a secure context\n if (authTokenSyncPath &&\n typeof isSecureContext === 'boolean' &&\n isSecureContext) {\n // Don't allow urls (XSS possibility), only paths on the same domain\n const authTokenSyncUrl = new URL(authTokenSyncPath, location.origin);\n if (location.origin === authTokenSyncUrl.origin) {\n const mintCookie = mintCookieFactory(authTokenSyncUrl.toString());\n beforeAuthStateChanged(auth, mintCookie, () => mintCookie(auth.currentUser));\n onIdTokenChanged(auth, user => mintCookie(user));\n }\n }\n const authEmulatorHost = getDefaultEmulatorHost('auth');\n if (authEmulatorHost) {\n connectAuthEmulator(auth, `http://${authEmulatorHost}`);\n }\n return auth;\n}\nfunction getScriptParentElement() {\n return document.getElementsByTagName('head')?.[0] ?? document;\n}\n_setExternalJSProvider({\n loadJS(url) {\n // TODO: consider adding timeout support & cancellation\n return new Promise((resolve, reject) => {\n const el = document.createElement('script');\n el.setAttribute('src', url);\n el.onload = resolve;\n el.onerror = e => {\n const error = _createError(\"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\n error.customData = e;\n reject(error);\n };\n el.type = 'text/javascript';\n el.charset = 'UTF-8';\n getScriptParentElement().appendChild(el);\n });\n },\n gapiScript: 'https://apis.google.com/js/api.js',\n recaptchaV2Script: 'https://www.google.com/recaptcha/api.js',\n recaptchaEnterpriseScript: 'https://www.google.com/recaptcha/enterprise.js?render='\n});\nregisterAuth(\"Browser\" /* ClientPlatform.BROWSER */);\n\nexport { onIdTokenChanged as $, ActionCodeOperation as A, fetchSignInMethodsForEmail as B, getAdditionalUserInfo as C, getAuth as D, EmailAuthCredential as E, FacebookAuthProvider as F, GithubAuthProvider as G, getIdToken as H, getIdTokenResult as I, getMultiFactorResolver as J, getRedirectResult as K, inMemoryPersistence as L, indexedDBLocalPersistence as M, initializeAuth as N, OAuthCredential as O, PhoneAuthCredential as P, initializeRecaptchaConfig as Q, RecaptchaVerifier as R, SAMLAuthProvider as S, TotpMultiFactorGenerator as T, isSignInWithEmailLink as U, linkWithCredential as V, linkWithPhoneNumber as W, linkWithPopup as X, linkWithRedirect as Y, multiFactor as Z, onAuthStateChanged as _, ActionCodeURL as a, parseActionCodeURL as a0, prodErrorMap as a1, reauthenticateWithCredential as a2, reauthenticateWithPhoneNumber as a3, reauthenticateWithPopup as a4, reauthenticateWithRedirect as a5, reload as a6, revokeAccessToken as a7, sendEmailVerification as a8, sendPasswordResetEmail as a9, _getRedirectUrl as aA, _isIOS7Or8 as aB, _createError as aC, _getProjectConfig as aD, AuthEventManager as aE, _getInstance as aF, _persistenceKeyName as aG, _getRedirectResult as aH, _overrideRedirectResult as aI, _clearRedirectOutcomes as aJ, _castAuth as aK, AuthImpl as aL, AuthPopup as aM, FetchProvider as aN, SAMLAuthCredential as aO, UserImpl as aP, _generateEventId as aQ, _getClientVersion as aR, sendSignInLinkToEmail as aa, setPersistence as ab, signInAnonymously as ac, signInWithCredential as ad, signInWithCustomToken as ae, signInWithEmailAndPassword as af, signInWithEmailLink as ag, signInWithPhoneNumber as ah, signInWithPopup as ai, signInWithRedirect as aj, signOut as ak, unlink as al, updateCurrentUser as am, updateEmail as an, updatePassword as ao, updatePhoneNumber as ap, updateProfile as aq, useDeviceLanguage as ar, validatePassword as as, verifyBeforeUpdateEmail as at, verifyPasswordResetCode as au, _assert as av, debugAssert as aw, _isIOS as ax, _isAndroid as ay, _fail as az, AuthCredential as b, AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY as c, EmailAuthProvider as d, FactorId as e, GoogleAuthProvider as f, OAuthProvider as g, OperationType as h, PhoneAuthProvider as i, PhoneMultiFactorGenerator as j, ProviderId as k, SignInMethod as l, TotpSecret as m, TwitterAuthProvider as n, applyActionCode as o, beforeAuthStateChanged as p, browserCookiePersistence as q, browserLocalPersistence as r, browserPopupRedirectResolver as s, browserSessionPersistence as t, checkActionCode as u, confirmPasswordReset as v, connectAuthEmulator as w, createUserWithEmailAndPassword as x, debugErrorMap as y, deleteUser as z };\n//# sourceMappingURL=index-LY22yodV.js.map\n","\"use client\"\r\n\r\nimport { useTagAuth } from \"../context/auth-context.js\"\r\nimport {\r\n signInWithPopup,\r\n GoogleAuthProvider,\r\n type Auth,\r\n browserPopupRedirectResolver\r\n} from \"firebase/auth\"\r\nimport { useCallback, useMemo } from \"react\"\r\nimport { cn } from \"cn\"\r\n\r\n// ---- Types -----------------------------------------------------------------\r\n\r\nexport interface ContinueWithGoogleButtonProps {\r\n auth: Auth\r\n /** Button label when idle */\r\n label?: React.ReactNode\r\n /** Button label while connecting */\r\n loadingLabel?: React.ReactNode\r\n /** Optional className override */\r\n className?: string\r\n /** Hide the Google logo */\r\n hideIcon?: boolean\r\n}\r\n\r\n// ---- Component -------------------------------------------------------------\r\n\r\nexport const ContinueWithGoogleButton = ({\r\n auth,\r\n label = \"Continue with Google\",\r\n loadingLabel = \"Connecting to Google…\",\r\n className,\r\n hideIcon = false,\r\n}: ContinueWithGoogleButtonProps) => {\r\n const provider = useMemo(() => new GoogleAuthProvider(), [])\r\n\r\n const { setIsLoggingIn, isLogingIn, setError,loginWithGoogle } = useTagAuth()\r\n\r\n const signIn = useCallback(async () => {\r\n if (isLogingIn) return\r\n\r\n try {\r\n setIsLoggingIn(true)\r\n setError(\"\")\r\n const res = await signInWithPopup(auth, provider,browserPopupRedirectResolver);\r\n const token =await res.user.getIdToken();\r\n await loginWithGoogle(token)\r\n\r\n } catch (error: unknown) {\r\n console.error(\"Google sign-in failed:\", error)\r\n setError(\r\n error instanceof Error\r\n ? error.message\r\n : \"Google login failed. Please try again.\",\r\n )\r\n } finally {\r\n setIsLoggingIn(false)\r\n }\r\n }, [auth, provider, isLogingIn, setIsLoggingIn, setError])\r\n\r\n return (\r\n <button\r\n type=\"button\"\r\n onClick={signIn}\r\n disabled={isLogingIn}\r\n aria-busy={isLogingIn}\r\n className={cn(\r\n // layout\r\n \"inline-flex w-full items-center justify-center gap-2\",\r\n // sizing\r\n \"h-9 px-4 py-2\",\r\n // shape\r\n \"rounded-md border\",\r\n // colors (theme-aware)\r\n \"border-input bg-background text-foreground\",\r\n \"hover:bg-accent hover:text-accent-foreground\",\r\n // focus\r\n \"outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background\",\r\n // text\r\n \"text-sm font-medium\",\r\n // motion\r\n \"transition-colors\",\r\n // disabled\r\n \"disabled:pointer-events-none disabled:opacity-50\",\r\n // allow caller overrides\r\n className,\r\n )}\r\n >\r\n {isLogingIn ? (\r\n <>\r\n <Spinner />\r\n <span>{loadingLabel}</span>\r\n </>\r\n ) : (\r\n <>\r\n {!hideIcon && <GoogleIcon />}\r\n <span>{label}</span>\r\n </>\r\n )}\r\n </button>\r\n )\r\n}\r\n\r\n// ---- Sub-components --------------------------------------------------------\r\n\r\nfunction GoogleIcon({ className }: { className?: string }) {\r\n return (\r\n <svg\r\n xmlns=\"http://www.w3.org/2000/svg\"\r\n width=\"18\"\r\n height=\"18\"\r\n viewBox=\"0 0 48 48\"\r\n aria-hidden=\"true\"\r\n className={cn(\"shrink-0\", className)}\r\n >\r\n <path\r\n fill=\"#EA4335\"\r\n d=\"M24 9.5c3.54 0 6.71 1.22 9.21 3.6l6.85-6.85C35.9 2.38 30.47 0 24 0 14.62 0 6.51 5.38 3.1 13.22l7.98 6.19C13 13.72 18.11 9.5 24 9.5Z\"\r\n />\r\n <path\r\n fill=\"#4285F4\"\r\n d=\"M46.98 24.55c0-1.57-.15-3.09-.38-4.55H24v9.02h12.94c-.58 2.96-2.26 5.48-4.77 7.18l7.73 6C44.4 37.95 46.98 31.78 46.98 24.55Z\"\r\n />\r\n <path\r\n fill=\"#FBBC05\"\r\n d=\"M10.08 28.59A14.4 14.4 0 0 1 9.3 24c0-1.59.27-3.13.76-4.59l-7.98-6.19A23.9 23.9 0 0 0 0 24c0 3.87.93 7.52 2.58 10.78l7.5-6.19Z\"\r\n />\r\n <path\r\n fill=\"#34A853\"\r\n d=\"M24 48c6.48 0 11.93-2.13 15.9-5.8l-7.73-6c-2.14 1.44-4.87 2.3-8.17 2.3-5.89 0-10.9-3.98-12.7-9.32l-7.5 6.19C7.22 43.4 15.02 48 24 48Z\"\r\n />\r\n </svg>\r\n )\r\n}\r\n\r\nfunction Spinner({ className }: { className?: string }) {\r\n return (\r\n <svg\r\n xmlns=\"http://www.w3.org/2000/svg\"\r\n width=\"16\"\r\n height=\"16\"\r\n viewBox=\"0 0 24 24\"\r\n fill=\"none\"\r\n aria-hidden=\"true\"\r\n className={cn(\"shrink-0 animate-spin\", className)}\r\n >\r\n <circle\r\n cx=\"12\"\r\n cy=\"12\"\r\n r=\"10\"\r\n stroke=\"currentColor\"\r\n strokeWidth=\"4\"\r\n className=\"opacity-25\"\r\n />\r\n <path\r\n fill=\"currentColor\"\r\n className=\"opacity-75\"\r\n d=\"M4 12a8 8 0 0 1 8-8v4a4 4 0 0 0-4 4H4z\"\r\n />\r\n </svg>\r\n )\r\n}","\"use client\"\n\nimport { cn } from \"cn\"\nimport { useEffect, useState } from \"react\"\nimport type { LoginProps } from \"@brightnkhoma/tag-auth\"\nimport {\n Card,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from \"./ui/card.js\"\nimport {\n FieldGroup,\n Field,\n FieldLabel,\n FieldDescription,\n} from \"./ui/field.js\"\nimport { Input } from \"./ui/input.js\"\nimport { Button } from \"./ui/button.js\"\nimport { useTagAuth } from \"../context/auth-context.js\"\nimport { Auth } from \"firebase/auth\"\nimport { ContinueWithGoogleButton } from \"./continue-with-google-button.js\"\n\n// ---- Types -----------------------------------------------------------------\n\nexport interface LoginFormLabels {\n title?: React.ReactNode\n description?: React.ReactNode\n emailLabel?: React.ReactNode\n emailPlaceholder?: string\n passwordLabel?: React.ReactNode\n forgotPassword?: React.ReactNode\n forgotPasswordHref?: string\n submitIdle?: React.ReactNode\n submitLoading?: React.ReactNode\n successMessage?: React.ReactNode\n footer?: React.ReactNode\n footerHref?: string\n}\n\nexport interface LoginFormProps extends React.ComponentProps<\"div\"> {\n /** Override any of the default labels */\n auth : Auth | undefined,\n labels?: LoginFormLabels\n /** Optional slot rendered after the submit button (e.g. social auth) */\n children?: React.ReactNode\n /** Optional className overrides for each slot */\n classNames?: {\n root?: string\n card?: string\n header?: string\n title?: string\n description?: string\n content?: string\n label?: string\n input?: string\n error?: string\n success?: string\n submit?: string\n forgotPassword?: string\n footer?: string\n\n }\n}\n\n// ---- Defaults --------------------------------------------------------------\n\nconst defaultLabels: Required<LoginFormLabels> = {\n title: \"Login to your account\",\n description: \"Enter your email below to login to your account\",\n emailLabel: \"Email\",\n emailPlaceholder: \"m@example.com\",\n passwordLabel: \"Password\",\n forgotPassword: \"Forgot your password?\",\n forgotPasswordHref: \"#\",\n submitIdle: \"Login\",\n submitLoading: \"Logging in…\",\n successMessage: \"Logged in successfully.\",\n footerHref: \"/auth/signup\",\n footer: (\n <>\n Don't have an account?{\" \"}\n <a\n href=\"/auth/signup\"\n className=\"font-medium underline underline-offset-4 hover:opacity-80\"\n >\n Sign up\n </a>\n </>\n ),\n}\n\n// ---- Component -------------------------------------------------------------\n\nexport function LoginForm({\n className,\n labels: labelsProp,\n children,\n classNames = {},\n auth,\n ...props\n}: LoginFormProps) {\n const [logprops, setProps] = useState<LoginProps>({\n email: \"\",\n password: \"\",\n })\n const { isLogingIn, login, error, success, setSuccess } = useTagAuth()\n\n const labels = { ...defaultLabels, ...labelsProp }\n\n const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n setProps((prev) => ({ ...prev, [e.target.id]: e.target.value }))\n }\n\n const onLogin = async (e: React.FormEvent) => {\n e.preventDefault()\n setSuccess(false)\n await login(logprops)\n }\n\n useEffect(() => {\n setSuccess(false)\n }, [setSuccess])\n\n // Support both boolean and string success values\n const successMessage =\n typeof success === \"string\"\n ? success\n : success\n ? labels.successMessage\n : null\n\n return (\n <div\n className={cn(\"flex flex-col gap-6\", className, classNames.root)}\n {...props}\n >\n <Card\n className={[\n \"w-full border bg-card text-card-foreground shadow-lg\",\n classNames.card,\n ]\n .filter(Boolean)\n .join(\" \")}\n >\n <CardHeader\n className={[\"space-y-1\", classNames.header].filter(Boolean).join(\" \")}\n >\n <CardTitle\n className={[\"text-2xl font-semibold\", classNames.title]\n .filter(Boolean)\n .join(\" \")}\n >\n {labels.title}\n </CardTitle>\n <CardDescription className={classNames.description}>\n {labels.description}\n </CardDescription>\n </CardHeader>\n\n <CardContent className={classNames.content}>\n <form onSubmit={onLogin} noValidate>\n <FieldGroup>\n <Field>\n <FieldLabel htmlFor=\"login-email\" className={classNames.label}>\n {labels.emailLabel}\n </FieldLabel>\n <Input\n id=\"email\"\n name=\"email\"\n type=\"email\"\n placeholder={labels.emailPlaceholder}\n required\n autoComplete=\"email\"\n value={logprops.email}\n onChange={handleChange}\n className={classNames.input}\n />\n </Field>\n\n <Field>\n <div className=\"flex items-center\">\n <FieldLabel\n htmlFor=\"password\"\n className={classNames.label}\n >\n {labels.passwordLabel}\n </FieldLabel>\n {labels.forgotPassword ? (\n <a\n href={labels.forgotPasswordHref}\n className={[\n \"ml-auto inline-block text-sm underline underline-offset-4 hover:opacity-80\",\n classNames.forgotPassword,\n ]\n .filter(Boolean)\n .join(\" \")}\n >\n {labels.forgotPassword}\n </a>\n ) : null}\n </div>\n <Input\n id=\"password\"\n name=\"password\"\n type=\"password\"\n required\n autoComplete=\"current-password\"\n value={logprops.password}\n onChange={handleChange}\n className={classNames.input}\n />\n </Field>\n\n {error ? (\n <p\n role=\"alert\"\n className={[\n \"rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive\",\n classNames.error,\n ]\n .filter(Boolean)\n .join(\" \")}\n >\n {error}\n </p>\n ) : null}\n\n {successMessage ? (\n <p\n role=\"status\"\n className={[\n \"rounded-md border border-emerald-500/30 bg-emerald-500/10 px-3 py-2 text-sm text-emerald-700 dark:text-emerald-300\",\n classNames.success,\n ]\n .filter(Boolean)\n .join(\" \")}\n >\n {successMessage}\n </p>\n ) : null}\n\n <Field>\n <Button\n type=\"submit\"\n disabled={isLogingIn}\n className={[\"w-full\", classNames.submit]\n .filter(Boolean)\n .join(\" \")}\n >\n {isLogingIn ? labels.submitLoading : labels.submitIdle}\n </Button>\n {auth && <ContinueWithGoogleButton auth={auth}/>}\n\n\n\n {children}\n\n {labels.footer ? (\n <FieldDescription\n className={[\"text-center\", classNames.footer]\n .filter(Boolean)\n .join(\" \")}\n >\n {labels.footer}\n </FieldDescription>\n ) : null}\n </Field>\n </FieldGroup>\n </form>\n </CardContent>\n </Card>\n </div>\n )\n}","\"use client\"\n\nimport * as React from \"react\"\nimport { Button } from \"./ui/button.js\"\nimport {\n Card,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from \"./ui/card.js\"\nimport {\n Field,\n FieldDescription,\n FieldGroup,\n FieldLabel,\n} from \"./ui/field.js\"\nimport { Input } from \"./ui/input.js\"\nimport { useTagAuth } from \"../context/auth-context.js\"\nimport { ContinueWithGoogleButton } from \"./continue-with-google-button.js\"\nimport { Auth } from \"firebase/auth\"\n\n// ---- Types -----------------------------------------------------------------\n\nexport interface SignupFormLabels {\n title?: React.ReactNode\n description?: React.ReactNode\n nameLabel?: React.ReactNode\n namePlaceholder?: string\n emailLabel?: React.ReactNode\n emailPlaceholder?: string\n emailHint?: React.ReactNode\n passwordLabel?: React.ReactNode\n passwordHint?: React.ReactNode\n confirmPasswordLabel?: React.ReactNode\n confirmPasswordHint?: React.ReactNode\n submitIdle?: React.ReactNode\n submitLoading?: React.ReactNode\n successMessage?: React.ReactNode\n footer?: React.ReactNode\n}\n\nexport interface SignupFormProps\n extends Omit<React.ComponentProps<typeof Card>, \"onSubmit\"> {\n /** Override any of the default labels */\n labels?: SignupFormLabels,\n auth : Auth | undefined,\n /** Optional slot rendered after the submit button (e.g. social auth) */\n children?: React.ReactNode\n /** Optional className overrides for each slot */\n classNames?: {\n root?: string\n header?: string\n title?: string\n description?: string\n content?: string\n label?: string\n input?: string\n error?: string\n success?: string\n submit?: string\n footer?: string\n }\n}\n\n// ---- Defaults --------------------------------------------------------------\n\nconst defaultLabels: Required<SignupFormLabels> = {\n title: \"Create an account\",\n description: \"Enter your information below to create your account\",\n nameLabel: \"Full Name\",\n namePlaceholder: \"Your name\",\n emailLabel: \"Email\",\n emailPlaceholder: \"m@example.com\",\n emailHint:\n \"We'll use this to contact you. We will not share your email with anyone else.\",\n passwordLabel: \"Password\",\n passwordHint: \"Must be at least 8 characters long.\",\n confirmPasswordLabel: \"Confirm Password\",\n confirmPasswordHint: \"Please confirm your password.\",\n submitIdle: \"Create Account\",\n submitLoading: \"Creating account…\",\n successMessage: \"Account created successfully. You can now sign in.\",\n footer: (\n <>\n Already have an account?{\" \"}\n <a\n href=\"/auth/login\"\n className=\"font-medium underline underline-offset-4 hover:opacity-80\"\n >\n Sign in\n </a>\n </>\n ),\n}\n\n// ---- Component -------------------------------------------------------------\n\nexport function SignupForm({\n labels: labelsProp,\n children,\n classNames = {},\n auth,\n ...cardProps\n}: SignupFormProps) {\n const {\n confirmPassword,\n error,\n form,\n handleChange,\n loading,\n onSignUp,\n setConfirmPassword,\n success,\n } = useTagAuth()\n\n const labels = { ...defaultLabels, ...labelsProp }\n\n // Support both boolean and string success values\n const successMessage =\n typeof success === \"string\"\n ? success\n : success\n ? labels.successMessage\n : null\n\n return (\n <Card\n className={[\n \"w-full max-w-md border bg-card text-card-foreground shadow-lg\",\n classNames.root,\n ]\n .filter(Boolean)\n .join(\" \")}\n {...cardProps}\n >\n <CardHeader\n className={[\"space-y-1\", classNames.header].filter(Boolean).join(\" \")}\n >\n <CardTitle\n className={[\"text-2xl font-semibold\", classNames.title]\n .filter(Boolean)\n .join(\" \")}\n >\n {labels.title}\n </CardTitle>\n <CardDescription className={classNames.description}>\n {labels.description}\n </CardDescription>\n </CardHeader>\n\n <CardContent className={classNames.content}>\n <form onSubmit={onSignUp} noValidate>\n <FieldGroup>\n <Field>\n <FieldLabel htmlFor=\"signup-name\" className={classNames.label}>\n {labels.nameLabel}\n </FieldLabel>\n <Input\n id=\"name\"\n name=\"name\"\n type=\"text\"\n placeholder={labels.namePlaceholder}\n required\n value={form.name}\n onChange={handleChange}\n autoComplete=\"name\"\n className={classNames.input}\n />\n </Field>\n\n <Field>\n <FieldLabel htmlFor=\"signup-email\" className={classNames.label}>\n {labels.emailLabel}\n </FieldLabel>\n <Input\n id=\"email\"\n name=\"email\"\n type=\"email\"\n placeholder={labels.emailPlaceholder}\n required\n value={form.email}\n onChange={handleChange}\n autoComplete=\"email\"\n className={classNames.input}\n />\n {labels.emailHint ? (\n <FieldDescription>{labels.emailHint}</FieldDescription>\n ) : null}\n </Field>\n\n <Field>\n <FieldLabel htmlFor=\"signup-password\" className={classNames.label}>\n {labels.passwordLabel}\n </FieldLabel>\n <Input\n id=\"password\"\n name=\"password\"\n type=\"password\"\n required\n value={form.password}\n onChange={handleChange}\n autoComplete=\"new-password\"\n className={classNames.input}\n />\n {labels.passwordHint ? (\n <FieldDescription>{labels.passwordHint}</FieldDescription>\n ) : null}\n </Field>\n\n <Field>\n <FieldLabel\n htmlFor=\"signup-confirm-password\"\n className={classNames.label}\n >\n {labels.confirmPasswordLabel}\n </FieldLabel>\n <Input\n id=\"signup-confirm-password\"\n name=\"confirmPassword\"\n type=\"password\"\n required\n value={confirmPassword}\n onChange={(e) => setConfirmPassword(e.target.value)}\n autoComplete=\"new-password\"\n className={classNames.input}\n />\n {labels.confirmPasswordHint ? (\n <FieldDescription>{labels.confirmPasswordHint}</FieldDescription>\n ) : null}\n </Field>\n\n {error ? (\n <p\n role=\"alert\"\n className={[\n \"rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive\",\n classNames.error,\n ]\n .filter(Boolean)\n .join(\" \")}\n >\n {error}\n </p>\n ) : null}\n\n {successMessage ? (\n <p\n role=\"status\"\n className={[\n \"rounded-md border border-emerald-500/30 bg-emerald-500/10 px-3 py-2 text-sm text-emerald-700 dark:text-emerald-300\",\n classNames.success,\n ]\n .filter(Boolean)\n .join(\" \")}\n >\n {successMessage}\n </p>\n ) : null}\n\n <FieldGroup>\n <Field>\n <Button\n type=\"submit\"\n disabled={loading}\n className={[\"w-full\", classNames.submit]\n .filter(Boolean)\n .join(\" \")}\n >\n {loading ? labels.submitLoading : labels.submitIdle}\n </Button>\n { auth && <ContinueWithGoogleButton auth={auth}/>}\n\n {children}\n\n {labels.footer ? (\n <FieldDescription\n className={[\"px-6 text-center\", classNames.footer]\n .filter(Boolean)\n .join(\" \")}\n >\n {labels.footer}\n </FieldDescription>\n ) : null}\n </Field>\n </FieldGroup>\n </FieldGroup>\n </form>\n </CardContent>\n </Card>\n )\n}"," \"use client\"\r\n\r\nimport { useTagAuth } from \"../context/auth-context.js\"\r\n import * as React from \"react\"\r\nimport { LoginForm } from \"./login-form.js\"\r\nimport { InputOTPForm } from \"./otp.js\"\r\nimport { SignupForm } from \"./signup-form.js\"\r\nimport { Auth } from \"firebase/auth\"\r\n \r\n\r\n// ---- Types -----------------------------------------------------------------\r\n\r\ntype AuthView = \"login\" | \"signup\" | \"verify\" | \"forgot\" | \"reset\"\r\n\r\nconst AUTH_VIEWS: readonly AuthView[] = [\r\n \"login\",\r\n \"signup\",\r\n \"verify\",\r\n \"forgot\",\r\n \"reset\",\r\n] as const\r\n\r\nconst DEFAULT_VIEW: AuthView = \"login\"\r\n\r\n/** Map URL segment → view (fallback to default for unknown segments) */\r\nfunction resolveView(segment?: string | string[]): AuthView {\r\n const raw = Array.isArray(segment) ? segment[0] : segment\r\n if (!raw) return DEFAULT_VIEW\r\n const normalized = raw.toLowerCase() as AuthView\r\n return AUTH_VIEWS.includes(normalized) ? normalized : DEFAULT_VIEW\r\n}\r\n\r\n// ---- Page ------------------------------------------------------------------\r\n\r\nexport function AuthClient({useSearchParams,useParams,useRouter,_auth} : {useParams :()=> any, useSearchParams :()=> any,useRouter : ()=>any,_auth ? : Auth}) {\r\n const params = useParams()\r\n const searchParams = useSearchParams()\r\n const router = useRouter()\r\n\r\n const view = resolveView(params?.auth)\r\n const redirectTo = searchParams?.get(\"redirect\") ?? \"/\"\r\n const initialEmail = searchParams?.get(\"email\") ?? undefined\r\n\r\n const auth = useTagAuth()\r\n const {\r\n success,\r\n setError,\r\n setSuccess,\r\n\r\n \r\n // signup\r\n form\r\n ,\r\n } = auth\r\n\r\n // -------- Post-auth redirect ---------------------------------------------\r\n // When login or OTP verification succeeds, push the user onward.\r\n const isAuthenticated = Boolean(success) && (view === \"login\" || view === \"verify\")\r\n\r\n React.useEffect(() => {\r\n if (!isAuthenticated) return\r\n const timer = setTimeout(() => {\r\n router.replace(redirectTo)\r\n }, 800) // let the success message breathe\r\n return () => clearTimeout(timer)\r\n }, [isAuthenticated, redirectTo, router])\r\n\r\n // -------- Reset transient state when switching views ---------------------\r\n React.useEffect(() => {\r\n setError?.(null)\r\n setSuccess?.(false)\r\n }, [view, setError, setSuccess])\r\n\r\n // -------- Render ---------------------------------------------------------\r\n return (\r\n <main className=\"flex min-h-svh w-full items-center justify-center bg-background p-4 sm:p-6\">\r\n <div className=\"w-full max-w-md\">\r\n {view === \"login\" && (\r\n <LoginForm\r\n auth={_auth}\r\n labels={{\r\n footer: (\r\n <>\r\n Don't have an account?{\" \"}\r\n <a\r\n href={`/auth/signup?redirect=${encodeURIComponent(redirectTo)}`}\r\n className=\"font-medium underline underline-offset-4 hover:opacity-80\"\r\n >\r\n Sign up\r\n </a>\r\n </>\r\n ),\r\n forgotPasswordHref: `/auth/forgot?email=${encodeURIComponent(\r\n form?.email ?? \"\",\r\n )}`,\r\n }}\r\n />\r\n )}\r\n\r\n {view === \"signup\" && (\r\n <SignupForm\r\n auth={_auth}\r\n labels={{\r\n footer: (\r\n <>\r\n Already have an account?{\" \"}\r\n <a\r\n href={`/auth/login?redirect=${encodeURIComponent(redirectTo)}`}\r\n className=\"font-medium underline underline-offset-4 hover:opacity-80\"\r\n >\r\n Sign in\r\n </a>\r\n </>\r\n ),\r\n }}\r\n />\r\n )}\r\n\r\n {view === \"verify\" && (\r\n <InputOTPForm\r\n labels={{\r\n description: (email) => (\r\n <>\r\n Enter the verification code we sent to{\" \"}\r\n <span className=\"font-medium\">\r\n {email ?? initialEmail ?? \"your email\"}\r\n </span>\r\n .\r\n </>\r\n ),\r\n }}\r\n />\r\n )}\r\n\r\n {view === \"forgot\" && <ForgotPasswordPlaceholder />}\r\n\r\n {view === \"reset\" && <ResetPasswordPlaceholder />}\r\n </div>\r\n </main>\r\n )\r\n}\r\n\r\n// ---- Placeholders for views you haven't built yet --------------------------\r\n// Replace these with real forms when ready — the routing already works.\r\n\r\nfunction ForgotPasswordPlaceholder() {\r\n return (\r\n <div className=\"rounded-lg border bg-card p-6 text-card-foreground shadow-lg\">\r\n <h1 className=\"text-2xl font-semibold\">Reset your password</h1>\r\n <p className=\"mt-1 text-sm text-muted-foreground\">\r\n Forgot-password flow coming soon.\r\n </p>\r\n </div>\r\n )\r\n}\r\n\r\nfunction ResetPasswordPlaceholder() {\r\n return (\r\n <div className=\"rounded-lg border bg-card p-6 text-card-foreground shadow-lg\">\r\n <h1 className=\"text-2xl font-semibold\">Set a new password</h1>\r\n <p className=\"mt-1 text-sm text-muted-foreground\">\r\n Reset-password flow coming soon.\r\n </p>\r\n </div>\r\n )\r\n}"],"ignoreList":[3,4,5,7,9,10,12,13,14,15,16,17,18,19,20,21,22,23,24,25,27,28,29,30,31,32,33,34,35,36,37,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,59,60,61,62,63,64,65,66],"mappings":";;;;;AACA,IAAa8C,KAAuB,MAAmB;CACnD,IAAMC,IAAUC,EAAcC,CAAY;CAE1C,OAAO,CAACF,SADUG,EAAWH,CAAO,CAChB;AACxB,GC8Ea,CAACI,GAAaC,KAAaN,EAAiB;CApDrD,iBAAiB;CACjB,oBAA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