@corbado/observe 1.1.4 → 1.1.5
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/cdn/script.global.js +1 -1
- package/dist/index.d.mts +16 -2
- package/dist/index.d.ts +16 -2
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -16,6 +16,7 @@ type SetFlowTagsOptions = {
|
|
|
16
16
|
/** Whether following sibling flows inherit the tags (default `true`). */
|
|
17
17
|
expandToFollowing?: boolean;
|
|
18
18
|
};
|
|
19
|
+
type ProvideIdentifierSpecType = "email" | "phone" | "username";
|
|
19
20
|
type SocialLoginProviderType = "google" | "apple" | "facebook" | "github" | "microsoft" | "line" | "kakao" | "singpass" | "other";
|
|
20
21
|
declare enum AuthEventName {
|
|
21
22
|
FlowStarted = "flow_started",
|
|
@@ -190,6 +191,20 @@ type StepOptions = {
|
|
|
190
191
|
explicitTimestamp?: number;
|
|
191
192
|
/** Per-call experiment override (experiment key → variant), merged over the persistent assignments. */
|
|
192
193
|
experiments?: Record<string, string>;
|
|
194
|
+
/**
|
|
195
|
+
* Identifier the user submitted with this step (e.g. on `pi-post-response`). Sent by step start,
|
|
196
|
+
* finished and error only. Makes the attempt searchable by identifier, including failed attempts;
|
|
197
|
+
* unlike `setUser`, it never identifies the user of the flow.
|
|
198
|
+
*/
|
|
199
|
+
identifier?: StepIdentifier;
|
|
200
|
+
};
|
|
201
|
+
/**
|
|
202
|
+
* Sent exactly as given: apply your normalization (e.g. trim and lowercase an email) and, if your data
|
|
203
|
+
* policy requires it, hash the value before passing it. Search must use the same representation.
|
|
204
|
+
*/
|
|
205
|
+
type StepIdentifier = {
|
|
206
|
+
value: string;
|
|
207
|
+
type?: ProvideIdentifierSpecType;
|
|
193
208
|
};
|
|
194
209
|
type SubflowTrigger = {
|
|
195
210
|
actor: "system" | "user";
|
|
@@ -1241,7 +1256,6 @@ type PasskeyLoginCUITypedError = {
|
|
|
1241
1256
|
code: PasskeyLoginCUITypedErrorCode;
|
|
1242
1257
|
};
|
|
1243
1258
|
type PasskeyLoginCUITypedErrorCode = "cancel_detected";
|
|
1244
|
-
type ProvideIdentifierSpecType = "email" | "phone" | "username";
|
|
1245
1259
|
type ProvideIdentifierPostResponseStart = {
|
|
1246
1260
|
explicitSpecType?: ProvideIdentifierSpecType;
|
|
1247
1261
|
};
|
|
@@ -2650,4 +2664,4 @@ declare function logInfo(message: string): void;
|
|
|
2650
2664
|
declare function logError(message: string): void;
|
|
2651
2665
|
declare function destroy(): Promise<void>;
|
|
2652
2666
|
|
|
2653
|
-
export { type AppConfirmationOperationCeremonyTypedError, type AppConfirmationOperationConfig, AppConfirmationOperationFull, type AppConfirmationOperationRetryReason, type AppConfirmationOperationSpecType, type AppConfirmationOperationStart, type AuthDecisionFinished, type AuthDecisionStarted, AuthEventName, type AuthMethodDecisionFinished, type AuthMethodDecisionStarted, type AuthMethodType, type BaseEvent, CEREMONY_LOW_EVENT_TAIL_MS, CONFIG_BOUNDS, CONFIG_REQUEST_HEADER, CONFIG_STORAGE_KEY, type CaptchaOperationConfig, CaptchaOperationFull, type CaptchaOperationSpecType, type ClientCapabilities, type ClientEnvHandleMeta, type ClientEnvHandleMetaSource, type Conversion, CookieStorage, CorbadoTracker, type CreateLoggerOptions, type CustomEvent, DEFAULT_DEVICE_INFO_COLLECTOR_TIMEOUT_MS, DEFAULT_FLUSH_INTERVAL_MS, DEFAULT_MAX_ENTRIES, DEFAULT_MAX_SERIALIZED_LENGTH, DEFAULT_RELIABILITY_CONFIG, DEFAULT_SEQ_LOCK_TIMEOUT_MS, DEFAULT_SESSION_INACTIVITY_MS, type DeviceInfo, type DeviceInfoCollectionError, type DeviceInfoDataWeb, type DeviceType, type EmailLinkContinuationConfig, EmailLinkContinuationOperation, type EmailLinkOperationConfig, EmailLinkOperationFull, type EmailLinkOperationPostResponseStart, type EmailLinkOperationSendStart, type EmailLinkOperationSpecType, type EmailOTPOperationConfig, type EmailOTPOperationPostResponseStart, type EmailOTPOperationSendOTPStart, type EmailOTPOperationSpecType, EmailOtpOperationFull, type ErrorStepOptions, type Event, type EventBatch, type EventBatchMeta, type EventMeta, EventStore, type EventType, type FlowAutoFinished, type FlowDecided, type FlowFinished, type FlowHandle, type FlowReset, type FlowStarted, type FlowType, type FlushReason, type JavaScriptHighEntropy, type KeyOperationConfig, KeyRegistrationOperationFull, KeySigningOperationFull, LocalStorage, type Logger, type LowEvent, type LowEventFieldRole, type LowEventInitiator, type LowEventInputEffect, type LowEventSourceKind, type MultiFlowReset, type MultiFlowStarted, NamespacedStorage, type NormalizedError, OUTBOX_LOCK_NAME, OUTBOX_STORAGE_KEY, type ObserveSdkConfigSnapshot, OperationFull, OperationFullProvideIdentifierWithCUI, type OperationFullProvideIdentifierWithCUIConfig, type OutboxEntry, type PasskeyEnrollmentCeremonyFinished, type PasskeyEnrollmentCeremonyStart, type PasskeyEnrollmentGetOptionsFinished, type PasskeyEnrollmentGetOptionsStart, type PasskeyEnrollmentOperationConfig, PasskeyEnrollmentOperationFull, type PasskeyEnrollmentPostResponseStart, type PasskeyLoginCUIGetOptionsFinished, type PasskeyLoginCUIGetOptionsStart, type PasskeyLoginCUISpecType, type PasskeyLoginCeremonyFinished, type PasskeyLoginCeremonyStart, type PasskeyLoginClientError, type PasskeyLoginFinish, type PasskeyLoginGetOptionsFinished, type PasskeyLoginGetOptionsStart, type PasskeyLoginOperationConfig, PasskeyLoginOperationFull, type PasskeyLoginPostResponseStart, type PasskeyLoginStartable, type PasskeyLoginSubmitted, type PasskeyOperationEnrollmentExplicitSpecType, type PasskeyOperationLoginExplicitSpecType, type PasswordEnrollmentConfig, PasswordEnrollmentOperationFull, type PasswordEnrollmentTypedError, type PasswordLoginCUICeremonyStart, type PasswordLoginCUIGetOptionsFinished, type PasswordLoginCUIGetOptionsStart, type PasswordLoginCUISpecType, type PasswordLoginCUITypedError, type PasswordLoginConfig, type PasswordLoginExplicitSpecType, PasswordLoginOperationFull, type PasswordLoginTypedError, type PredefinedEvent, type ProvideDataOperationConfig, ProvideDataOperationFull, type ProvideDataOperationPostResponseStart, type ProvideDataOperationSpecType, type ProvideDataOperationStart, type ProvideIdentifierError, type ProvideIdentifierFinish, type ProvideIdentifierPostResponseStart, type ProvideIdentifierSpecType, type ProvideIdentifierStart, type QueueOptions, RAW_ERROR_BOUNDS, type RawErrorEnvelope, RequestQueue, SDK_NAME, SDK_VERSION, type SdkInfo, type SdkReliabilityConfig, type SdkReliabilityConfigOverrides, type SdkRetryConfig, type SerializeRawErrorOptions, SessionStorage, type SetFlowTagsOptions, type SmsOTPOperationConfig, type SmsOTPOperationPostResponseStart, type SmsOTPOperationSpecType, SmsOtpOperationFull, type SocialLoginExchangeCodeFinished, type SocialLoginExchangeCodeStart, type SocialLoginGetRedirectUrlFinished, type SocialLoginGetRedirectUrlStart, type SocialLoginOperationConfig, SocialLoginOperationFull, type SocialLoginProviderType, type SocialLoginSpecType, type SourcePathQueryMode, type SsoLoginExchangeCodeFinished, type SsoLoginExchangeCodeStart, type SsoLoginGetRedirectUrlFinished, type SsoLoginGetRedirectUrlStart, type SsoLoginOperationConfig, SsoLoginOperationFull, type SsoLoginSpecType, type StepHelper, type StepOptions, type StorageEngine, type SubflowTrigger, type SubflowType, type TelemetryEntry, type TelemetryLevel, type TelemetrySink, type TotpOperationConfig, TotpOperationFull, type TotpOperationPostResponseStart, type TotpOperationSpecType, type TrackerOptions, type Transport, type TransportMakeRequestResponse, type TransportOptions, type TrustedDeviceBindingMetadata, type TrustedDeviceCheckConfig, TrustedDeviceCheckOperationFull, type TrustedDeviceCheckResult, type TrustedDeviceCheckStepResult, type TrustedDeviceCheckTypedError, TrustedDeviceEnrollmentOperationFull, type TrustedDeviceEnrollmentResult, type TrustedDeviceOperationConfig, type TrustedDevicePurpose, type TrustedDeviceStorage, type UserReference, cacheConfig, clearExperiment, clearExperiments, createLogger, destroy, getExperiments, getSessionId, getTracker, init, loadCachedConfig, logError, logInfo, namespacedKey, parseReliabilityConfig, resetSession, resolveRawErrorLimits, resolveReliabilityConfig, sanitizeAssertionResponse, sanitizeCreationOptions, sanitizeCreationResponse, sanitizeRequestOptions, serializeRawError, setExperiment, setExperiments, setFlowTags, setUser, telemetry };
|
|
2667
|
+
export { type AppConfirmationOperationCeremonyTypedError, type AppConfirmationOperationConfig, AppConfirmationOperationFull, type AppConfirmationOperationRetryReason, type AppConfirmationOperationSpecType, type AppConfirmationOperationStart, type AuthDecisionFinished, type AuthDecisionStarted, AuthEventName, type AuthMethodDecisionFinished, type AuthMethodDecisionStarted, type AuthMethodType, type BaseEvent, CEREMONY_LOW_EVENT_TAIL_MS, CONFIG_BOUNDS, CONFIG_REQUEST_HEADER, CONFIG_STORAGE_KEY, type CaptchaOperationConfig, CaptchaOperationFull, type CaptchaOperationSpecType, type ClientCapabilities, type ClientEnvHandleMeta, type ClientEnvHandleMetaSource, type Conversion, CookieStorage, CorbadoTracker, type CreateLoggerOptions, type CustomEvent, DEFAULT_DEVICE_INFO_COLLECTOR_TIMEOUT_MS, DEFAULT_FLUSH_INTERVAL_MS, DEFAULT_MAX_ENTRIES, DEFAULT_MAX_SERIALIZED_LENGTH, DEFAULT_RELIABILITY_CONFIG, DEFAULT_SEQ_LOCK_TIMEOUT_MS, DEFAULT_SESSION_INACTIVITY_MS, type DeviceInfo, type DeviceInfoCollectionError, type DeviceInfoDataWeb, type DeviceType, type EmailLinkContinuationConfig, EmailLinkContinuationOperation, type EmailLinkOperationConfig, EmailLinkOperationFull, type EmailLinkOperationPostResponseStart, type EmailLinkOperationSendStart, type EmailLinkOperationSpecType, type EmailOTPOperationConfig, type EmailOTPOperationPostResponseStart, type EmailOTPOperationSendOTPStart, type EmailOTPOperationSpecType, EmailOtpOperationFull, type ErrorStepOptions, type Event, type EventBatch, type EventBatchMeta, type EventMeta, EventStore, type EventType, type FlowAutoFinished, type FlowDecided, type FlowFinished, type FlowHandle, type FlowReset, type FlowStarted, type FlowType, type FlushReason, type JavaScriptHighEntropy, type KeyOperationConfig, KeyRegistrationOperationFull, KeySigningOperationFull, LocalStorage, type Logger, type LowEvent, type LowEventFieldRole, type LowEventInitiator, type LowEventInputEffect, type LowEventSourceKind, type MultiFlowReset, type MultiFlowStarted, NamespacedStorage, type NormalizedError, OUTBOX_LOCK_NAME, OUTBOX_STORAGE_KEY, type ObserveSdkConfigSnapshot, OperationFull, OperationFullProvideIdentifierWithCUI, type OperationFullProvideIdentifierWithCUIConfig, type OutboxEntry, type PasskeyEnrollmentCeremonyFinished, type PasskeyEnrollmentCeremonyStart, type PasskeyEnrollmentGetOptionsFinished, type PasskeyEnrollmentGetOptionsStart, type PasskeyEnrollmentOperationConfig, PasskeyEnrollmentOperationFull, type PasskeyEnrollmentPostResponseStart, type PasskeyLoginCUIGetOptionsFinished, type PasskeyLoginCUIGetOptionsStart, type PasskeyLoginCUISpecType, type PasskeyLoginCeremonyFinished, type PasskeyLoginCeremonyStart, type PasskeyLoginClientError, type PasskeyLoginFinish, type PasskeyLoginGetOptionsFinished, type PasskeyLoginGetOptionsStart, type PasskeyLoginOperationConfig, PasskeyLoginOperationFull, type PasskeyLoginPostResponseStart, type PasskeyLoginStartable, type PasskeyLoginSubmitted, type PasskeyOperationEnrollmentExplicitSpecType, type PasskeyOperationLoginExplicitSpecType, type PasswordEnrollmentConfig, PasswordEnrollmentOperationFull, type PasswordEnrollmentTypedError, type PasswordLoginCUICeremonyStart, type PasswordLoginCUIGetOptionsFinished, type PasswordLoginCUIGetOptionsStart, type PasswordLoginCUISpecType, type PasswordLoginCUITypedError, type PasswordLoginConfig, type PasswordLoginExplicitSpecType, PasswordLoginOperationFull, type PasswordLoginTypedError, type PredefinedEvent, type ProvideDataOperationConfig, ProvideDataOperationFull, type ProvideDataOperationPostResponseStart, type ProvideDataOperationSpecType, type ProvideDataOperationStart, type ProvideIdentifierError, type ProvideIdentifierFinish, type ProvideIdentifierPostResponseStart, type ProvideIdentifierSpecType, type ProvideIdentifierStart, type QueueOptions, RAW_ERROR_BOUNDS, type RawErrorEnvelope, RequestQueue, SDK_NAME, SDK_VERSION, type SdkInfo, type SdkReliabilityConfig, type SdkReliabilityConfigOverrides, type SdkRetryConfig, type SerializeRawErrorOptions, SessionStorage, type SetFlowTagsOptions, type SmsOTPOperationConfig, type SmsOTPOperationPostResponseStart, type SmsOTPOperationSpecType, SmsOtpOperationFull, type SocialLoginExchangeCodeFinished, type SocialLoginExchangeCodeStart, type SocialLoginGetRedirectUrlFinished, type SocialLoginGetRedirectUrlStart, type SocialLoginOperationConfig, SocialLoginOperationFull, type SocialLoginProviderType, type SocialLoginSpecType, type SourcePathQueryMode, type SsoLoginExchangeCodeFinished, type SsoLoginExchangeCodeStart, type SsoLoginGetRedirectUrlFinished, type SsoLoginGetRedirectUrlStart, type SsoLoginOperationConfig, SsoLoginOperationFull, type SsoLoginSpecType, type StepHelper, type StepIdentifier, type StepOptions, type StorageEngine, type SubflowTrigger, type SubflowType, type TelemetryEntry, type TelemetryLevel, type TelemetrySink, type TotpOperationConfig, TotpOperationFull, type TotpOperationPostResponseStart, type TotpOperationSpecType, type TrackerOptions, type Transport, type TransportMakeRequestResponse, type TransportOptions, type TrustedDeviceBindingMetadata, type TrustedDeviceCheckConfig, TrustedDeviceCheckOperationFull, type TrustedDeviceCheckResult, type TrustedDeviceCheckStepResult, type TrustedDeviceCheckTypedError, TrustedDeviceEnrollmentOperationFull, type TrustedDeviceEnrollmentResult, type TrustedDeviceOperationConfig, type TrustedDevicePurpose, type TrustedDeviceStorage, type UserReference, cacheConfig, clearExperiment, clearExperiments, createLogger, destroy, getExperiments, getSessionId, getTracker, init, loadCachedConfig, logError, logInfo, namespacedKey, parseReliabilityConfig, resetSession, resolveRawErrorLimits, resolveReliabilityConfig, sanitizeAssertionResponse, sanitizeCreationOptions, sanitizeCreationResponse, sanitizeRequestOptions, serializeRawError, setExperiment, setExperiments, setFlowTags, setUser, telemetry };
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
"use strict";var Ut=Object.create;var he=Object.defineProperty;var Bt=Object.getOwnPropertyDescriptor;var qt=Object.getOwnPropertyNames;var Kt=Object.getPrototypeOf,Vt=Object.prototype.hasOwnProperty;var $t=(n,e)=>{for(var t in e)he(n,t,{get:e[t],enumerable:!0})},Ze=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of qt(e))!Vt.call(n,r)&&r!==t&&he(n,r,{get:()=>e[r],enumerable:!(i=Bt(e,r))||i.enumerable});return n};var Gt=(n,e,t)=>(t=n!=null?Ut(Kt(n)):{},Ze(e||!n||!n.__esModule?he(t,"default",{value:n,enumerable:!0}):t,n)),zt=n=>Ze(he({},"__esModule",{value:!0}),n);var Zi={};$t(Zi,{AppConfirmationOperationFull:()=>le,AuthEventName:()=>ve,CEREMONY_LOW_EVENT_TAIL_MS:()=>st,CONFIG_BOUNDS:()=>S,CONFIG_REQUEST_HEADER:()=>Ne,CONFIG_STORAGE_KEY:()=>He,CaptchaOperationFull:()=>pe,CookieStorage:()=>Q,CorbadoTracker:()=>fe,DEFAULT_DEVICE_INFO_COLLECTOR_TIMEOUT_MS:()=>ut,DEFAULT_FLUSH_INTERVAL_MS:()=>vr,DEFAULT_MAX_ENTRIES:()=>gt,DEFAULT_MAX_SERIALIZED_LENGTH:()=>mt,DEFAULT_RELIABILITY_CONFIG:()=>y,DEFAULT_SEQ_LOCK_TIMEOUT_MS:()=>Sr,DEFAULT_SESSION_INACTIVITY_MS:()=>ct,EmailLinkContinuationOperation:()=>ee,EmailLinkOperationFull:()=>Z,EmailOtpOperationFull:()=>J,EventStore:()=>P,KeyRegistrationOperationFull:()=>V,KeySigningOperationFull:()=>K,LocalStorage:()=>W,NamespacedStorage:()=>z,OUTBOX_LOCK_NAME:()=>we,OUTBOX_STORAGE_KEY:()=>ht,OperationFull:()=>h,OperationFullProvideIdentifierWithCUI:()=>ne,PasskeyEnrollmentOperationFull:()=>te,PasskeyLoginOperationFull:()=>Y,PasswordEnrollmentOperationFull:()=>re,PasswordLoginOperationFull:()=>ie,ProvideDataOperationFull:()=>ce,RAW_ERROR_BOUNDS:()=>rt,RequestQueue:()=>$,SDK_NAME:()=>Pe,SDK_VERSION:()=>Re,SessionStorage:()=>j,SmsOtpOperationFull:()=>X,SocialLoginOperationFull:()=>oe,SsoLoginOperationFull:()=>se,TotpOperationFull:()=>ae,TrustedDeviceCheckOperationFull:()=>de,TrustedDeviceEnrollmentOperationFull:()=>ue,cacheConfig:()=>Be,clearExperiment:()=>zi,clearExperiments:()=>Wi,createLogger:()=>Ye,destroy:()=>Xi,getExperiments:()=>Qi,getSessionId:()=>qi,getTracker:()=>Ui,init:()=>Ni,loadCachedConfig:()=>Ue,logError:()=>Ji,logInfo:()=>Yi,namespacedKey:()=>w,parseReliabilityConfig:()=>H,resetSession:()=>Bi,resolveRawErrorLimits:()=>De,resolveReliabilityConfig:()=>Se,sanitizeAssertionResponse:()=>Nt,sanitizeCreationOptions:()=>_t,sanitizeCreationResponse:()=>Mt,sanitizeRequestOptions:()=>Ht,serializeRawError:()=>_e,setExperiment:()=>$i,setExperiments:()=>Gi,setFlowTags:()=>Vi,setUser:()=>Ki,telemetry:()=>ji});module.exports=zt(Zi);var et=0;function x(){if(et===4294967295)throw new Error("Low-event capture sequence exhausted");return++et}function tt(n,e){if(n==="passkey-login")switch(e){case"passkey-known-identifier":case"passkey-no-identifier":return"passkey-button";case"passkey-known-identifier-auto":case"passkey-no-identifier-auto":case"passkey-immediate":return"automatic"}else if(n==="passkey-enrollment")switch(e){case"manual":return"passkey-button";case"auto":case"conditional":return"automatic"}}var ot=require("uuid");function F(n){if(n!=null){if(n instanceof Error)return{name:n.name,message:n.message};if(typeof n=="string")return{message:n};if(typeof n=="object"){let e=n;if(typeof e.message=="string"||typeof e.code=="string")return{name:typeof e.name=="string"?e.name:void 0,message:typeof e.message=="string"?e.message:void 0,code:typeof e.code=="string"?e.code:void 0}}return{message:String(n)}}}var rt={maxStackFrames:{min:1,max:100,default:50},depth:{min:0,max:10,default:3},maxBreadth:{min:1,max:1e3,default:30},maxValueLength:{min:1,max:1e4,default:1024},maxCauseDepth:{min:0,max:10,default:3},maxBytes:{min:0,max:65536,default:32768}},Wt=1024,D=class extends Error{},Qt=["name","message","code","errors","stack"],jt=/[^\x20-\x7E]/,_=n=>Object.prototype.toString.call(n).slice(8,-1),Yt=n=>n===null?"null":typeof n=="object"?_(n):typeof n,Jt=n=>n instanceof Error||_(n)==="Error"||_(n)==="DOMException";function nt(n){return jt.test(n)?new TextEncoder().encode(n).byteLength:n.length}function A(n,e){let t=rt[n];return typeof e!="number"||!Number.isFinite(e)?t.default:Math.min(t.max,Math.max(t.min,Math.floor(e)))}function De(n={}){return{stack:n.stack===!0,maxStackFrames:A("maxStackFrames",n.maxStackFrames),depth:A("depth",n.depth),maxBreadth:A("maxBreadth",n.maxBreadth),maxValueLength:A("maxValueLength",n.maxValueLength),maxCauseDepth:A("maxCauseDepth",n.maxCauseDepth),maxBytes:A("maxBytes",n.maxBytes)}}function _e(n,e={}){if(n===void 0)return;let t=De(),i=r=>{let o=JSON.stringify(r);return o===void 0||nt(o)<=t.maxBytes};try{if(t=De(e),t.maxBytes===0)return;let r=C(Yt(n),1024);for(let s=t.depth;s>=0;s--){let a={limits:t,causeBudget:t.maxCauseDepth,seen:new Set,nodes:0,textBytes:0};try{let l={type:r,value:ge(n,s,a)};if(i(l))return l}catch(l){if(!(l instanceof D))throw l}}let o={type:r,truncated:!0};return i(o)?o:void 0}catch{let r={type:"unserializable"};return i(r)?r:void 0}}function q(n,e){if(n.length>e.limits.maxBytes)throw new D;if(e.textBytes+=nt(JSON.stringify(n)),e.textBytes>e.limits.maxBytes)throw new D;return n}function ge(n,e,t){if(++t.nodes>Wt)throw new D;let i=Xt(n,e,t);return typeof i=="string"?q(i,t):i}function Xt(n,e,t){switch(typeof n){case"string":return C(n,t.limits.maxValueLength);case"number":return Number.isFinite(n)?n:String(n);case"boolean":case"undefined":return n;case"bigint":case"symbol":return C(String(n),t.limits.maxValueLength);case"function":return`[Function: ${n.name||"anonymous"}]`}if(n===null)return null;let i=n;if(t.seen.has(i))return"[Circular]";if(e<0)return`[${_(i)}]`;t.seen.add(i);try{return Zt(i,e,t)}finally{t.seen.delete(i)}}function C(n,e){return n.length>e?n.slice(0,e)+"\u2026":n}function it(n,e,t){let i=n.length>t;n=C(n,t);let r=n.split(`
|
|
2
2
|
`);if(r.length<=e+1)return C(n,t);let o=r.slice(0,e+1).join(`
|
|
3
3
|
`),s=i?"[truncated]":`[+${r.length-e-1} frames]`;return C(`${o}
|
|
4
|
-
${s}`,t)}function Zt(n,e,t){let{limits:i}=t,r=_(n),o=d=>ge(d,e-1,t);if(r==="Date")return Number.isNaN(n.getTime())?"[Invalid Date]":n.toISOString();if(r==="RegExp")return C(String(n),i.maxValueLength);if(r==="ArrayBuffer")return`[ArrayBuffer(${n.byteLength})]`;if(ArrayBuffer.isView(n))return`[${r}(${n.byteLength})]`;if(r==="Map"||r==="Set"){let d=n,c=[];for(let f of d){if(c.length===i.maxBreadth)break;c.push(o(f))}return d.size>c.length&&c.push(`[+${d.size-c.length} more]`),c}if(r==="Promise"||r==="WeakMap"||r==="WeakSet"||r==="Window")return`[${r}]`;if(typeof Node<"u"&&n instanceof Node)return`[${r}]`;if(Array.isArray(n)){let d=n.slice(0,i.maxBreadth).map(o);return n.length>i.maxBreadth&&d.push(`[+${n.length-i.maxBreadth} more]`),d}if(typeof Response<"u"&&n instanceof Response)return{status:o(n.status),statusText:o(n.statusText),url:o(n.url),redirected:o(n.redirected)};if(typeof Event<"u"&&n instanceof Event){let d=n,c={type:o(d.type)};for(let f of["message","filename","lineno","colno"])f in d&&(c[f]=o(d[f]));return"error"in d&&d.error!=null&&(c.error=o(d.error)),c}let s=Object.create(null),a=n,l=Jt(n);if(l){for(let c of Qt){if(c==="stack"&&!i.stack)continue;let f=a[c];if(!(f==null||typeof f=="function")){if(c==="stack"){i.stack&&typeof f=="string"&&(s.stack=q(it(f,i.maxStackFrames,i.maxValueLength),t));continue}s[c]=o(f)}}let d=a.cause;d!=null&&typeof d!="function"&&(s.cause=ei(d,e-1,t))}let p=0,u=Object.keys(a);for(let d of u){if(d in s||d==="stack"&&!i.stack||l&&d==="cause")continue;if(++p>i.maxBreadth){s["\u2026"]=`[+${u.length-i.maxBreadth} keys]`;break}let c=a[d];typeof c!="function"&&(s[q(d,t)]=d==="stack"&&typeof c=="string"?q(it(c,i.maxStackFrames,i.maxValueLength),t):o(c))}return!l&&r!=="Object"&&p===0?`[${r}]`:s}function ei(n,e,t){if(typeof n!="object"||n===null)return ge(n,e,t);if(t.causeBudget<=0)return q(`[${_(n)}]`,t);t.causeBudget--;try{return ge(n,e,t)}finally{t.causeBudget++}}var st=1500,h=class{constructor(e,t){this.tracker=e;this.operationName=t}startReference;captureSpecType;captureSessionId;lowFlushers=[];lowPrefillCapturers=[];lowEventSink(e,t){return{reserveCaptureSeq:x,enqueueLowEvent:i=>this.tracker.enqueueLowEvent({...i,captureSeq:i.captureSeq??x(),subflowStartEventId:this.startReference,sourceKind:e,fieldRole:t,initiator:i.initiator??(t?`input-${t}`:"unknown")},this.captureSessionId),flushKeepalive:()=>this.tracker.lowEventFlushKeepalive(),registerInputs:(i,r)=>this.tracker.getWindowObserver().registerInputs(i,()=>({subflowStartEventId:this.startReference,fieldRole:t,initiator:t?`input-${t}`:"unknown",sessionId:this.captureSessionId}),r),beginCeremony:i=>this.tracker.getWindowObserver().beginCeremony({subflowStartEventId:this.startReference,initiator:i??"unknown",sessionId:this.captureSessionId})}}createLowCollector(e){try{let t=e();return this.lowPrefillCapturers.push(i=>t.capturePrefill(i)),t}catch(t){this.tracker.getLogger().error("Failed to attach low-event collector",t);return}}registerLowFlusher(e){this.lowFlushers.push(e)}captureOptions(e,t=this.startReference,i=this.captureSessionId,r){if(!t&&!r)return e;let o={};return t&&(o.subflowStartEventId=e?.subflowStartEventId??t,o.captureSessionId=e?.captureSessionId??i),r&&(o.initiator=e?.initiator??r),Object.defineProperties({},{...Object.getOwnPropertyDescriptors(e??{}),...Object.getOwnPropertyDescriptors(o)})}get captureReference(){return this.startReference}get captureSession(){return this.captureSessionId}adoptCapture(e,t,i){this.startReference=e,this.captureSessionId=t,this.captureSpecType=i}subflowStart(e,t){try{for(let i of this.lowFlushers)try{i()}catch(r){this.tracker.getLogger().error("Failed to flush previous low-event context",r)}this.captureSpecType=e?.explicitSpecType,this.startReference=(0,ot.v7)(),this.captureSessionId=this.tracker.getSessionId(),this.tracker.trackSubflowStarted(this.operationName,e,this.captureOptions(t),this.startReference),this.captureInputPrefills(!0)}catch(i){this.tracker.getLogger().error("Failed to start low-event capture context",i)}}capturePrefill(){this.captureInputPrefills(!1)}captureInputPrefills(e){for(let t of this.lowPrefillCapturers)try{t(e)}catch(i){this.tracker.getLogger().error("Failed to capture input prefill",i)}}trigger(e,t){this.tracker.trackSubflowTrigger(this.operationName,e,this.captureOptions(t))}customStep(e){return this.defineStep(e)}subflowStepStarted(e,t,i,r){this.captureSpecType=t?.explicitSpecType??this.captureSpecType,this.tracker.trackSubflowStepStarted(this.operationName,e,t,this.captureOptions(i),r)}subflowStepFinished(e,t,i){(!i?.subflowStartEventId||i.subflowStartEventId===this.startReference)&&(this.captureSpecType=t?.explicitSpecType??this.captureSpecType),this.tracker.trackSubflowStepFinished(this.operationName,e,t,this.captureOptions(i))}subflowStepError(e,t,i){let r=t;try{let o=this.tracker.getSdkConfig().rawErrors?i?.rawError:void 0;o!==void 0&&(r={...t,rawError:_e(o,i?.rawErrorLimits)})}catch{}this.tracker.trackSubflowStepError(this.operationName,e,r,this.captureOptions(i))}withWindowLowEvents(e,t){let i,r=s=>{s?.subflowStartEventId&&s.subflowStartEventId!==i||t.scheduleDisarm(st)},o=e;return{...e,start:(s,a)=>{i=a?.subflowStartEventId??this.startReference;let l=s?.explicitSpecType??this.captureSpecType,p=a?.initiator??tt(this.operationName,l);t.arm(p,l==="passkey-cui"),o.start(s,p?{...a,initiator:p}:a)},finished:(s,a)=>{o.finished(s,a),r(a)},error:(s,a)=>{o.error(s,a),r(a)},errorTyped:(s,a)=>{o.errorTyped?.(s,a),r(a)}}}defineStep(e,t){let i,r,o,s=l=>this.captureOptions(l,i,r,o);return{start:(l,p)=>{i=this.startReference,r=this.captureSessionId,o=p?.initiator,this.subflowStepStarted(e,l,s(p),t)},finished:(l,p)=>{this.subflowStepFinished(e,l,s(p))},error:(l,p)=>{this.subflowStepError(e,{error:F(l)},s(p))},errorTyped:(l,p)=>{this.subflowStepError(e,l,s(p))}}}};function at(n,e){if(e.explicitSpecType!==void 0)try{n.getLogger().warn("Unsupported key operation spec type; omitting it")}catch{}}var K=class extends h{prepare;sign;constructor(e,t={}){super(e,"key-signing"),this.prepare=this.defineStep("prepare"),this.sign=this.defineStep("sign"),this.subflowStart({actor:"system",explicitSpecType:at(e,t)})}},V=class extends h{prepare;postResponse;constructor(e,t={}){super(e,"key-registration"),this.prepare=this.defineStep("prepare"),this.postResponse=this.defineStep("post-response"),this.subflowStart({actor:"system",explicitSpecType:at(e,t)})}};function ti(n){try{return decodeURIComponent(n.replace(/\+/g," "))}catch{return n}}function ii(n,e){let t=n.toLowerCase();return e.some(i=>{let r=i.toLowerCase();return r.endsWith("*")?t.startsWith(r.slice(0,-1)):t===r})}function lt(n,e,t){return e!=="allowlist"||n===""||n==="?"?n:`?${(n.startsWith("?")?n.slice(1):n).split("&").map(o=>{let s=o.indexOf("=");if(s===-1)return o;let a=o.slice(0,s);return o.slice(s+1)===""||ii(ti(a),t)?o:`${a}=*`}).join("&")}`}var pt=require("uuid");var Me=(n,e,t)=>{let i=!1,r,o=null,s=null,a=()=>{s!==null&&(window.clearTimeout(s),s=null);let p=o;i=!1,o=null,p!==null&&n({...r===void 0?{}:{captureSeq:r},lowType:e,ts:p,durationMs:Date.now()-p})};return{extend:()=>{if(!i){let p=t?.();i=!0,o=Date.now(),r=p}s!==null&&window.clearTimeout(s),s=window.setTimeout(a,150)},flush:a}};var ri,ye=()=>ri??=(0,pt.v7)(),me=class{constructor(e,t,i){this.logger=e;this.enqueue=t;this.flushKeepalive=i;typeof window>"u"||typeof document>"u"||(this.listen(window,"blur",()=>{this.flushInputs(),this.bracket=this.context(),this.emit({lowType:"window-blur",ts:Date.now()},this.bracket)}),this.listen(window,"focus",()=>{this.flushInputs(),this.emit({lowType:"window-focus",ts:Date.now()},this.bracket??this.context()),this.bracket=void 0}),this.listen(document,"visibilitychange",()=>{this.flushInputs(),this.emit({lowType:`document-visibilitychange-${document.visibilityState==="hidden"?"hidden":"visible"}`,ts:Date.now()})}),this.listen(document,"focusout",r=>{let o=this.findInput(r.target);this.lastBlur=o&&!r.relatedTarget&&Date.now()-this.unrelatedPointerAt>250?{registration:o,ts:Date.now()}:void 0}),this.listen(document,"focusin",()=>{this.lastBlur=void 0}),this.listen(document,"pointerdown",r=>{this.findInput(r.target)?this.unrelatedPointerAt=-1/0:(this.lastBlur=void 0,this.unrelatedPointerAt=Date.now())}),window.visualViewport&&(this.listen(window.visualViewport,"resize",()=>this.extendViewport("resize")),this.listen(window.visualViewport,"scroll",()=>this.extendViewport("scroll"))),this.listen(window,"pagehide",()=>{this.flushInputs(),this.resize.flush(),this.scroll.flush(),this.flushKeepalive()}),this.observeNavigation())}inputs=new Set;ceremonies=new Set;removers=[];lastBlur;bracket;unrelatedPointerAt=-1/0;destroyed=!1;viewportContext={};resize=Me(e=>this.emit(e,this.viewportContext.resize),"visualviewport-resize",x);scroll=Me(e=>this.emit(e,this.viewportContext.scroll),"visualviewport-scroll",x);registerInputs(e,t,i){if(this.destroyed)return()=>{};let r={fields:e,context:t,flush:i};return this.inputs.add(r),()=>{this.inputs.delete(r),this.lastBlur?.registration===r&&(this.lastBlur=void 0)}}beginCeremony(e){let t={context:e,settled:!1};this.destroyed||(this.flushInputs(),this.ceremonies.add(t));let i=()=>{t.timer&&clearTimeout(t.timer),this.ceremonies.delete(t),this.bracket===t.context&&(this.bracket=void 0)};return{settle:r=>{t.settled=!0,t.timer&&clearTimeout(t.timer),t.timer=setTimeout(i,r)},destroy:i}}context(){let e=[...this.ceremonies].filter(r=>!r.settled);if(e.length===1)return e[0].context;if(e.length>1)return;let t=this.findInput(document.activeElement);if(t)return t.context();let i=this.lastBlur;if(i&&Date.now()-i.ts<=250&&(document.activeElement===document.body||!document.activeElement))return i.registration.context()}findInput(e){return[...this.inputs].find(t=>t.fields.some(i=>i===e))}flushInputs(){for(let e of this.inputs)try{e.flush()}catch(t){this.logger.error("Failed to flush window input context",t)}}emit(e,t){if(this.destroyed)return;let{sessionId:i,...r}=t??{};this.enqueue({...e,...r,captureSeq:e.captureSeq??x(),sourceKind:"window",captureVersion:1,pageId:ye()},i)}listen(e,t,i){let r=o=>{try{i(o)}catch(s){this.logger.error(`Failed to observe window ${t}`,s)}};e.addEventListener(t,r),this.removers.push(()=>e.removeEventListener(t,r))}extendViewport(e){let t=this.context(),i=this.viewportContext[e];(i?.subflowStartEventId!==t?.subflowStartEventId||i?.fieldRole!==t?.fieldRole||i?.sessionId!==t?.sessionId)&&this[e].flush(),this.viewportContext[e]=t,this[e].extend()}observeNavigation(){let e=window.navigation;e&&this.listen(e,"currententrychange",t=>{let i=t,r=i.from?.index,o=e.currentEntry?.index;i.navigationType==="traverse"&&typeof r=="number"&&typeof o=="number"&&r>=0&&o>=0&&o<r&&(this.flushInputs(),this.emit({lowType:"window-navigate-back",ts:Date.now()}))})}destroy(){if(!this.destroyed){this.flushInputs(),this.resize.flush(),this.scroll.flush(),this.destroyed=!0;for(let e of this.removers)e();for(let e of this.ceremonies)e.timer&&clearTimeout(e.timer);this.ceremonies.clear(),this.inputs.clear()}}};var ve=(v=>(v.FlowStarted="flow_started",v.FlowDecided="flow_decided",v.FlowFinished="flow_finished",v.FlowReset="flow_reset",v.AuthMethodDecisionStarted="auth_method_decision_started",v.AuthMethodDecisionFinished="auth_method_decision_finished",v.FlowAutoFinished="flow_auto_finished",v.AuthDecisionStarted="auth_decision_started",v.AuthDecisionFinished="auth_decision_finished",v.SubflowStepStarted="subflow_step_started",v.SubflowStepFinished="subflow_step_finished",v.SubflowStepError="subflow_step_error",v.SubflowTrigger="subflow_trigger",v.SubflowError="subflow_error",v.SubflowStarted="subflow_started",v.SubflowFinished="subflow_finished",v.FlowEnriched="flow_enriched",v.Conversion="conversion",v))(ve||{});var He="cbo_sdk_config",Ne="X-Corbado-Observe-Config",vr=500,Sr=50,ut=1e3,S={flushIntervalMs:{min:100,max:6e4},retryMaxAttempts:{min:1,max:10},retryDelayMs:{min:50,max:12e4},sessionInactivityMs:{min:6e4,max:864e5},seqLockTimeoutMs:{min:0,max:250},deviceInfoCollectorTimeoutMs:{min:10,max:1e4},flushOnFlowTypeFinished:{maxEntries:20,maxNameLength:100},sourcePathQueryAllow:{maxEntries:50,maxKeyLength:64}},ct=1800*1e3,y={version:"",flushIntervalMs:500,durableOutbox:!1,durableLowOutbox:!1,beaconKeepalive:!1,sessionContinuity:!1,sessionInactivityMs:ct,seqLockTimeoutMs:50,tvc:!0,tph:!0,td:!0,tlf:!0,telemetry:!0,flushOnTelemetry:!1,flushOnFlowTypeFinished:[],deviceInfoCollectorTimeoutMs:1e3,deviceInfoTiming:!1,rawErrors:!0,retry:{maxAttempts:1,baseDelayMs:0,maxDelayMs:0},aap:"",sourcePathQuery:"allowlist",sourcePathQueryAllow:[]};function O(n,e,t){return Math.min(Math.max(n,e),t)}function L(n,e){return typeof n=="number"&&Number.isFinite(n)?n:e}function M(n,e){return typeof n=="boolean"?n:e}function dt(n,e){return typeof n=="string"?n:e}function ni(n){return Array.isArray(n)?n.filter(e=>typeof e=="string"&&e.length>0&&e.length<=S.flushOnFlowTypeFinished.maxNameLength).slice(0,S.flushOnFlowTypeFinished.maxEntries):[]}function oi(n){return typeof n=="string"&&n.trim().toLowerCase()==="all"?"all":"allowlist"}function si(n){return Array.isArray(n)?n.filter(e=>typeof e=="string").map(e=>e.trim()).filter(e=>e.length>0&&e.length<=S.sourcePathQueryAllow.maxKeyLength).slice(0,S.sourcePathQueryAllow.maxEntries):[]}function H(n){if(!n||typeof n!="object")return null;let e=n;return typeof e.version!="string"||e.version===""?null:ft(e)}function ft(n){let e=n.retry&&typeof n.retry=="object"?n.retry:{},t=O(L(e.baseDelayMs,y.retry.baseDelayMs),S.retryDelayMs.min,S.retryDelayMs.max);return{version:dt(n.version,""),flushIntervalMs:O(L(n.flushIntervalMs,y.flushIntervalMs),S.flushIntervalMs.min,S.flushIntervalMs.max),durableOutbox:n.durableOutbox===!0,durableLowOutbox:n.durableLowOutbox===!0,beaconKeepalive:n.beaconKeepalive===!0,sessionContinuity:n.sessionContinuity===!0,sessionInactivityMs:O(L(n.sessionInactivityMs,y.sessionInactivityMs),S.sessionInactivityMs.min,S.sessionInactivityMs.max),seqLockTimeoutMs:O(L(n.seqLockTimeoutMs,y.seqLockTimeoutMs),S.seqLockTimeoutMs.min,S.seqLockTimeoutMs.max),tvc:M(n.tvc,y.tvc),tph:M(n.tph,y.tph),td:M(n.td,y.td),tlf:M(n.tlf,y.tlf),telemetry:M(n.telemetry,y.telemetry),flushOnTelemetry:n.flushOnTelemetry===!0,flushOnFlowTypeFinished:ni(n.flushOnFlowTypeFinished),deviceInfoCollectorTimeoutMs:O(L(n.deviceInfoCollectorTimeoutMs,y.deviceInfoCollectorTimeoutMs),S.deviceInfoCollectorTimeoutMs.min,S.deviceInfoCollectorTimeoutMs.max),deviceInfoTiming:n.deviceInfoTiming===!0,rawErrors:M(n.rawErrors,y.rawErrors),aap:dt(n.aap,""),sourcePathQuery:oi(n.sourcePathQuery),sourcePathQueryAllow:si(n.sourcePathQueryAllow),retry:{maxAttempts:O(L(e.maxAttempts,y.retry.maxAttempts),S.retryMaxAttempts.min,S.retryMaxAttempts.max),baseDelayMs:t,maxDelayMs:O(L(e.maxDelayMs,y.retry.maxDelayMs),t,S.retryDelayMs.max)}}}function Se(n,e={}){let t=n??y,i=Object.fromEntries(Object.entries(e).filter(([,s])=>s!==void 0)),r=Object.fromEntries(Object.entries(e.retry??{}).filter(([,s])=>s!==void 0)),o=ft({...t,...i,retry:{...t.retry,...r}});return o.retry={...t.retry,...Object.fromEntries(Object.keys(r).map(s=>[s,o.retry[s]]))},o.retry.maxDelayMs=Math.max(o.retry.baseDelayMs,o.retry.maxDelayMs),o}function Ue(n){return H(n.getItem(He))}function Be(n,e){n.setItem(He,e)}var ai=6e4,li=6e4,Te=class{constructor(e){this.options=e}async send(e,t){try{e.meta={...e.meta,sent:Date.now(),transport:"fetch"};let i=JSON.stringify(e),r=typeof AbortController<"u"?new AbortController:void 0,o=r?setTimeout(()=>r.abort(),li):void 0;try{let s={method:"POST",headers:{"Content-Type":"application/json",...this.options.headers,...t},body:i,keepalive:new Blob([i]).size<=ai,...r?{signal:r.signal}:{}},a=await fetch(this.options.url,s),l={statusCode:a.status,headers:{"retry-after":a.headers.get("Retry-After")}};if(a.headers.get("X-Corbado-Observe-Accepted")==="1"&&(l.deliveryAccepted=!0),a.status===200)try{let p=H(await a.json());p&&(l.config=p)}catch(p){this.options.logger.error("Failed to parse SDK config response",p),this.options.logger.reportTelemetry?.("error","failed to parse SDK config response")}return l}finally{o&&clearTimeout(o)}}catch(i){return this.options.logger.error("Failed to send event",i),{}}}sendBeacon(e){try{if(this.options.logger.debug(`Sending ${e.events.length} events via beacon`),typeof navigator?.sendBeacon!="function")return!1;e.meta={...e.meta,sent:Date.now(),transport:"beacon"};let t=new Blob([JSON.stringify(e)],{type:"text/plain"});return navigator.sendBeacon(this.options.url,t)}catch(t){return this.options.logger.error("Failed to send event via beacon",t),!1}}flush(e){return Promise.resolve(!0)}};var yt=require("uuid");function be(n,e,t={}){let i=typeof navigator<"u"?navigator.locks:void 0;if(i?.request){let r=t.timeoutMs,o=r!==void 0&&typeof AbortController<"u"?new AbortController:null;if(r!==void 0&&!o)return Promise.resolve().then(e);try{let s=!1,a,l=()=>{a!==void 0&&(clearTimeout(a),a=void 0)},p=()=>(s=!0,l(),e()),u=o?i.request(n,{signal:o.signal},p):i.request(n,p);return o&&r!==void 0&&!s&&(a=setTimeout(()=>{a=void 0,o.abort();try{t.onTimeout?.()}catch{}},r)),u.catch(d=>{if(s)throw d;return e()}).finally(l)}catch{}}try{return Promise.resolve(e())}catch(r){return Promise.reject(r)}}var ht="cbo_outbox",we="cbo_outbox",gt=500,mt=512*1024;function pi(n){if(!n||typeof n!="object")return!1;let e=n;return typeof e.id=="string"&&e.id!==""&&typeof e.sessionId=="string"&&typeof e.flushAfter=="number"&&Number.isFinite(e.flushAfter)&&typeof e.attempts=="number"&&Number.isFinite(e.attempts)&&typeof e.event=="object"&&e.event!==null}var P=class{constructor(e,t,i=gt,r=mt,o=we,s=ht){this.storage=e;this.logger=t;this.maxEntries=i;this.maxSerializedLength=r;this.lockName=o;this.storageKey=s;this.entries=this.read()}entries=[];reportedMalformed=!1;read(){let e=this.storage.getItem(this.storageKey);if(!Array.isArray(e))return[];let t=e.filter(pi);return t.length<e.length&&!this.reportedMalformed&&(this.reportedMalformed=!0,this.logger.error(`EventStore dropped ${e.length-t.length} malformed outbox entries`),this.logger.reportTelemetry?.("error","event store dropped malformed outbox entries")),t}mutate(e){return be(this.lockName,()=>{try{let t=e(this.read());if(t.length>this.maxEntries){let i=t.length-this.maxEntries;t=t.slice(t.length-this.maxEntries),this.logger.error(`EventStore evicted ${i} oldest entries (cap ${this.maxEntries})`),this.logger.reportTelemetry?.("error","event store evicted entries (cap)")}t=this.enforceSizeBudget(t),this.entries=t,this.storage.setItem(this.storageKey,t)}catch(t){this.logger.error("Failed to mutate event store",t),this.logger.reportTelemetry?.("error","failed to mutate event store")}})}enforceSizeBudget(e){let t=e.map(o=>JSON.stringify(o).length),i=t.reduce((o,s)=>o+s,e.length+1),r=0;for(;i>this.maxSerializedLength&&r<e.length;)i-=t[r]+1,r++;return r===0?e:(this.logger.error(`EventStore evicted ${r} oldest entries (size budget ${this.maxSerializedLength})`),this.logger.reportTelemetry?.("error","event store evicted entries (size budget)"),e.slice(r))}add(e){return this.mutate(t=>t.some(i=>i.id===e.id)?t:[...t,e])}all(){return this.entries=this.read(),this.entries}getDue(e){return this.all().filter(t=>t.flushAfter<=e)}remove(e){if(e.length===0)return Promise.resolve();let t=new Set(e);return this.mutate(i=>i.filter(r=>!t.has(r.id)))}update(e){if(e.length===0)return Promise.resolve();let t=new Map(e.map(i=>[i.id,i]));return this.mutate(i=>i.map(r=>t.get(r.id)??r))}size(){return this.all().length}};var $=class{constructor(e,t,i,r,o={},s){this.logger=e;this.transport=t;this.sessionId=i;this.sdk=r;this.storage=s;if(this.batchSize=o.batchSize||50,this.flushIntervalOverride=o.flushInterval,this.debug=o.debug??!1,this.requestConfig=o.requestConfig??!0,this.onConfigReceived=o.onConfigReceived,this.getDataPolicy=o.getDataPolicy,this.config=o.config??y,this.priorityFlowTypes=new Set(this.config.flushOnFlowTypeFinished),this.outboxLockName=o.outboxLockName,this.config.durableOutbox&&this.storage&&(this.store=new P(this.storage,this.logger,void 0,void 0,this.outboxLockName),this.pending=this.store.all()),this.storage){this.lowStore=new P(this.storage,this.logger,1e3,256*1024,`${this.outboxLockName??"cbo_outbox"}:lows`,"cbo_low_outbox_v1");let a=this.lowStore.all();this.lowPending=a.filter(l=>this.validPendingLow(l)),this.lowStore.remove(a.filter(l=>!this.validPendingLow(l)).map(l=>l.id))}this.setupLifecycleHooks(),(this.pending.length>0||this.lowPending.length>0)&&(this.dirtySinceSyncFlush=!0,this.scheduleFlush(0,"recovery"))}pending=[];lowsQueue=[];lowPending=[];lowStore;telemetryQueue=[];timer=null;isFlushing=!1;flushingDone;destroyed=!1;dirtySinceSyncFlush=!1;onVisibilityChange=null;onPageHide=null;batchSize;flushIntervalOverride;debug;requestConfig;onConfigReceived;getDataPolicy;config;priorityFlowTypes;outboxLockName;store;configResolved=!1;setSessionId(e){this.sessionId=e}flushInterval(){return this.flushIntervalOverride??this.config.flushIntervalMs}enqueue(e,t=this.sessionId){try{let i={id:e.id,sessionId:t,flushAfter:0,attempts:0,event:e};this.pending.push(i),this.store?.add(i),this.scheduleAfterEnqueue(e)}catch(i){this.logger.error("Failed to enqueue event",i)}}enqueueLow(e,t=this.sessionId){try{let i={...e,id:e.id??(0,yt.v7)()};if(this.config.durableLowOutbox){let r={id:i.id,sessionId:t,event:i,attempts:0,flushAfter:0};this.lowPending.push(r),this.lowPending=this.lowPending.slice(-1e3),this.lowStore?.add(r)}else this.lowsQueue.push({sessionId:t,event:i});this.scheduleAfterEnqueue()}catch(i){this.logger.error("Failed to enqueue low event",i)}}enqueueTelemetry(e){try{if(!this.config.telemetry)return;this.telemetryQueue.push(e),this.dirtySinceSyncFlush=!0,this.config.flushOnTelemetry&&this.flush("telemetry")}catch(t){this.logger.error("Failed to enqueue telemetry",t)}}scheduleAfterEnqueue(e){if(this.dirtySinceSyncFlush=!0,e!==void 0&&this.isPriorityEvent(e)){this.flush("flow-finished");return}this.scheduleFlush(this.flushInterval(),"timer")}isPriorityEvent(e){if(e.type!=="predefined"||e.name!=="flow_finished"&&e.name!=="flow_auto_finished")return!1;let t=e.data?.flowName;return typeof t=="string"&&this.priorityFlowTypes.has(t)}scheduleFlush(e,t){this.destroyed||this.timer||(this.timer=setTimeout(()=>{this.timer=null,this.flush(t)},e))}clearTimer(){this.timer&&(clearTimeout(this.timer),this.timer=null)}async flush(e="timer"){if(this.destroyed)return;if(this.isFlushing){e==="destroy"&&await this.flushingDone;return}this.isFlushing=!0;let t;this.flushingDone=new Promise(i=>{t=i});try{for(this.clearTimer();;){let i=Date.now(),r=this.getDuePending(i),o=this.lowPending.filter(m=>m.flushAfter<=i);if(r.length===0&&o.length===0&&this.lowsQueue.length===0&&this.telemetryQueue.length===0)return;let s=r[0]?.sessionId??o[0]?.sessionId??this.lowsQueue[0]?.sessionId??this.sessionId,a=r.filter(m=>m.sessionId===s).slice(0,this.batchSize),l=o.filter(m=>m.sessionId===s).slice(0,100),p=[...l.map(m=>m.event),...this.takeLows(s,100-l.length)],u=s===this.sessionId?this.takeTelemetry():[],d={sessionId:s,events:a.map(m=>m.event),sdk:this.sdk};p.length>0&&(d.lows=p),u.length>0&&(d.telemetry=u),this.attachBatchMeta(d,[...a,...l],e),l.length&&(d.deliveryAck=!0);let c=this.shouldRequestConfig()?{[Ne]:this.config.version||"1"}:void 0,f=await this.transport.send(d,c).catch(m=>(this.logger.error("Unexpected error in queue flush",m),{}));if(d.deliveryAck&&f.statusCode&&f.statusCode>=200&&f.statusCode<300&&!f.deliveryAccepted&&(f={...f,statusCode:503}),this.requestConfig&&this.handleConfigResponse(f),this.handleLowSendResult(f,l,i),!this.handleSendResult(f,a,i))return}}catch(i){this.logger.error("Unexpected error in queue flush",i)}finally{this.isFlushing=!1,t(),this.flushingDone=void 0,this.rescheduleIfPending()}}attachBatchMeta(e,t,i){e.meta={...e.meta,flushReason:i};let r=this.readDataPolicy();r!==void 0&&(e.meta={...e.meta,dataPolicy:r}),this.config.version&&(e.meta={...e.meta,configVersion:this.config.version});let o=t.reduce((s,a)=>Math.max(s,a.attempts),0);o>0&&(e.meta={...e.meta,retryCount:o})}readDataPolicy(){try{return this.getDataPolicy?.()}catch(e){this.logger.debug("Failed to read data policy for batch meta",e);return}}getDuePending(e){return this.pending.filter(t=>t.flushAfter<=e)}takeLows(e=this.sessionId,t=100){let i=this.lowsQueue.filter(o=>o.sessionId===e).slice(0,t),r=new Set(i);return this.lowsQueue=this.lowsQueue.filter(o=>!r.has(o)),i.map(o=>o.event)}validPendingLow(e){return typeof e.event?.lowType=="string"&&e.event.id===e.id&&Number.isFinite(e.event.ts)&&e.event.ts>Date.now()-7*864e5}removeLowEntries(e){let t=new Set(e);this.lowPending=this.lowPending.filter(i=>!t.has(i.id)),this.lowStore?.remove(e)}handleLowSendResult(e,t,i){let r=e.statusCode;if(r!==void 0&&r>=200&&r<300){e.deliveryAccepted?this.removeLowEntries(t.map(o=>o.id)):this.deferLowEntries(t,i);return}if(!this.isRetryable(r)){this.removeLowEntries(t.map(o=>o.id)),this.logger.reportTelemetry?.("error","low events rejected by ingestion");return}this.deferLowEntries(t,i,this.parseRetryAfter(e))}deferLowEntries(e,t,i=null){let r=[];for(let o of e){if(!this.validPendingLow(o)){r.push(o.id);continue}o.attempts=Math.min(o.attempts+1,16),o.flushAfter=t+Math.max(Math.min(6e4,1e3*2**Math.min(o.attempts,6)),this.backoffForAttempt(o.attempts,i))}this.removeLowEntries(r),this.lowStore?.update(e.filter(o=>!r.includes(o.id)))}takeTelemetry(){let e=this.telemetryQueue;return this.telemetryQueue=[],e}shouldRequestConfig(){return this.requestConfig&&!this.configResolved}handleConfigResponse(e){let t=e.statusCode;typeof t=="number"&&t>=200&&t<300&&(this.configResolved=!0),e.config&&(this.config.version||this.updateConfig(e.config),this.onConfigReceived?.(e.config))}updateConfig(e){if(this.destroyed)return;let t=this.config.flushIntervalMs!==e.flushIntervalMs;if(this.config={...e,durableOutbox:this.config.durableOutbox||e.durableOutbox},this.priorityFlowTypes=new Set(e.flushOnFlowTypeFinished),e.durableLowOutbox&&this.lowsQueue.length){let r=this.lowsQueue;this.lowsQueue=[];for(let{event:o,sessionId:s}of r)this.enqueueLow(o,s)}let i=!1;if(this.config.durableOutbox&&this.storage&&!this.store){this.store=new P(this.storage,this.logger,void 0,void 0,this.outboxLockName);let r=new Set(this.pending.map(s=>s.id)),o=this.store.all().filter(s=>!r.has(s.id));for(let s of this.pending)this.store.add(s);this.pending=[...o,...this.pending],i=o.length>0}i?(this.dirtySinceSyncFlush=!0,this.clearTimer(),this.scheduleFlush(0,"recovery")):t&&(this.clearTimer(),this.rescheduleIfPending())}handleSendResult(e,t,i){let r=e.statusCode,o=typeof r=="number"&&r>=200&&r<300;if(t.length===0)return o;if(o)return this.removeEntries(t.map(u=>u.id)),!0;if(!this.isRetryable(r))return this.removeEntries(t.map(u=>u.id)),!1;let s=Math.max(1,this.config.retry.maxAttempts),a=this.parseRetryAfter(e),l=[],p=[];for(let u of t)u.attempts+=1,u.attempts>=s?l.push(u.id):(u.flushAfter=i+this.backoffForAttempt(u.attempts,a),p.push(u));return this.removeEntries(l),this.store?.update(p),!1}isRetryable(e){return e===void 0||e===408||e===429?!0:e>=500}backoffForAttempt(e,t){let i=this.config.retry,r=i.baseDelayMs*Math.pow(2,Math.max(0,e-1));i.maxDelayMs>0&&(r=Math.min(r,i.maxDelayMs));let o=Math.round(r/2+Math.random()*(r/2));return t!==null&&(o=Math.max(o,t)),o}parseRetryAfter(e){let t=e.headers?.["retry-after"];if(!t)return null;let i=Number(t);if(!Number.isNaN(i))return i*1e3;let r=Date.parse(t);return Number.isNaN(r)?null:Math.max(0,r-Date.now())}removeEntries(e){if(e.length===0)return;let t=new Set(e);this.pending=this.pending.filter(i=>!t.has(i.id)),this.store?.remove(e)}rescheduleIfPending(){try{if(this.destroyed||this.timer||this.pending.length===0&&this.lowPending.length===0&&this.lowsQueue.length===0)return;let e=Date.now();if(this.getDuePending(e).length>0||this.lowPending.some(i=>i.flushAfter<=e)||this.lowsQueue.length>0){this.scheduleFlush(this.flushInterval(),"timer");return}let t=Math.min(...[...this.pending,...this.lowPending].map(i=>i.flushAfter));this.scheduleFlush(Math.max(0,t-e),"backoff")}catch(e){this.logger.error("Failed to reschedule queue flush",e)}}setupLifecycleHooks(){typeof window>"u"||(this.onVisibilityChange=()=>{try{this.writeLifecycleDebugOutput("cbo_visibility_change_debug"),document.visibilityState==="hidden"&&this.config.tvc&&this.flushSync("visibility-change")}catch(e){this.logger.error("Unexpected error in queue flushSync",e)}},this.onPageHide=()=>{try{this.writeLifecycleDebugOutput("cbo_pagehide_debug"),this.config.tph&&this.flushSync("pagehide")}catch(e){this.logger.error("Unexpected error in queue flushSync",e)}},window.addEventListener("visibilitychange",this.onVisibilityChange),window.addEventListener("pagehide",this.onPageHide))}writeLifecycleDebugOutput(e){if(!this.debug||!this.storage)return;let t={last_executed:Date.now(),url:window.location.href};this.storage.setItem(e,t)}flushKeepalive(e="manual"){this.flushSync(e)}flushSync(e){if(!this.dirtySinceSyncFlush)return;let t=this.sessionId,i=this.pending.filter(p=>p.sessionId===t),r=i.slice(0,this.batchSize),o=this.lowPending.filter(p=>p.sessionId===t).slice(0,100),s=[...o.map(p=>p.event),...this.takeLows(t,100-o.length)],a=this.takeTelemetry();if(r.length===0&&s.length===0&&a.length===0){this.dirtySinceSyncFlush=!1;return}let l={sessionId:t,events:r.map(p=>p.event),sdk:this.sdk};s.length>0&&(l.lows=s),a.length>0&&(l.telemetry=a),this.attachBatchMeta(l,[...r,...o],e),o.length&&(l.deliveryAck=!0),this.config.beaconKeepalive&&this.transport.sendBeacon?this.transport.sendBeacon(l)||this.transport.send(l):this.transport.send(l),this.config.durableOutbox||this.removeEntries(r.map(p=>p.id)),this.dirtySinceSyncFlush=!this.config.durableOutbox&&i.length>r.length}destroy(){try{this.destroyed=!0,this.clearTimer(),typeof window<"u"&&(this.onVisibilityChange&&window.removeEventListener("visibilitychange",this.onVisibilityChange),this.onPageHide&&window.removeEventListener("pagehide",this.onPageHide))}catch(e){this.logger.error("Failed to destroy queue lifecycle hooks",e)}}};var Ve=require("uuid"),vt=Gt(require("detectincognitojs")),qe={collectorTimeoutMs:1e3,timing:!1},Ke="cbo_tab_id",di={bluetoothAvailable:"bt",clientCapabilities:"cc",userVerifyingPlatformAuthenticatorAvailable:"uvpaa",conditionalMediationAvailable:"cm",javaScriptHighEntropy:"he",privateMode:"pm",webdriver:"wd",maxTouchPoints:"mtp"};function G(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var Ee=class{constructor(e,t,i="localstorage",r,o=()=>qe,s){this.logger=e;this.storage=t;this.storageSource=i;this.sessionStorage=r;this.settings=o;this.emitTelemetry=s}async getInfo(){try{let e=this.resolveSettings(),t=G(),i=this.getClientEnvHandle(),r=await Promise.all([this.collectField("bluetoothAvailable","navigator.bluetooth.getAvailability",()=>this.isBluetoothAvailable(),e.collectorTimeoutMs),this.collectField("clientCapabilities","PublicKeyCredential.getClientCapabilities",()=>this.getClientCapabilities(),e.collectorTimeoutMs),this.collectField("userVerifyingPlatformAuthenticatorAvailable","PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable",()=>this.getUserVerifyingPlatformAuthenticatorAvailable(),e.collectorTimeoutMs),this.collectField("conditionalMediationAvailable","PublicKeyCredential.isConditionalMediationAvailable",()=>this.isConditionalMediationAvailable(),e.collectorTimeoutMs),this.collectField("javaScriptHighEntropy","navigator.userAgentData.getHighEntropyValues",()=>this.getJavaScriptHighEntropy(),e.collectorTimeoutMs),this.collectField("privateMode","detectIncognito",()=>this.isPrivateMode(),e.collectorTimeoutMs),this.collectField("webdriver","navigator.webdriver",()=>this.getWebdriver(),e.collectorTimeoutMs),this.collectField("maxTouchPoints","navigator.maxTouchPoints",()=>this.getMaxTouchPoints(),e.collectorTimeoutMs)]),o=G()-t;e.timing&&this.reportTiming(o,r);let[s,a,l,p,u,d,c,f]=r,m=r.flatMap(E=>E.error?[E.error]:[]),g={type:"web",clientEnvHandle:i.value,clientEnvHandleMeta:{timestamp:i.timestamp,source:i.source},tabId:this.getTabId(),data:{bluetoothAvailable:s.value,javaScriptHighEntropy:u.value,privateMode:d.value,webdriver:c.value,conditionalMediationAvailable:p.value,userVerifyingPlatformAuthenticatorAvailable:l.value,clientCapabilities:a.value,maxTouchPoints:f.value}};return m.length>0&&(g.collectionErrors=m),g}catch(e){return this.logger.error("Failed to collect device info",e),{}}}async collectField(e,t,i,r){let o,s=G();try{let a=await Promise.race([Promise.resolve().then(i),new Promise((l,p)=>{o=setTimeout(()=>{let u=new Error(`Device info collection timed out after ${r}ms`);u.name="TimeoutError",p(u)},r)})]);return{field:e,value:a,durationMs:G()-s}}catch(a){return this.logger.error(`Failed to collect device info field "${e}"`,a),{field:e,durationMs:G()-s,error:{field:e,source:t,error:F(a)??{message:"Unknown error"}}}}finally{o&&clearTimeout(o)}}resolveSettings(){try{let e=this.settings(),t=e?.collectorTimeoutMs;return{collectorTimeoutMs:typeof t=="number"&&Number.isFinite(t)&&t>0?t:qe.collectorTimeoutMs,timing:e?.timing===!0}}catch(e){return this.logger.error("Failed to resolve device info collector settings",e),qe}}reportTiming(e,t){if(this.emitTelemetry)try{let i=t.map(r=>`${di[r.field]??r.field}=${Math.round(r.durationMs)}`).join(",");this.emitTelemetry("info",`device info collected in ${Math.round(e)}ms (${i})`)}catch(i){this.logger.error("Failed to report device info timing",i)}}static getOsAndBrowserInfo(){return{osName:this.getOsName(),browserName:this.getBrowserName()}}static getUserAgent(){return typeof navigator>"u"?"":navigator.userAgent??""}static getOsName(){let e=this.getUserAgent();return e.includes("iOS")?"iOS":e.includes("Android")?"Android":e.includes("Windows")?"Windows":e.includes("Macintosh")?"macOS":e.includes("Linux")?"Linux":e.includes("ChromeOS")?"ChromeOS":"other"}static getBrowserName(){let e=this.getUserAgent();return e.includes("Chrome")?"Chrome":e.includes("Firefox")?"Firefox":e.includes("Safari")?"Safari":e.includes("Edge")?"Edge":e.includes("Opera")?"Opera":e.includes("IE")?"IE":"other"}async isBluetoothAvailable(){if(!(typeof navigator>"u"||!navigator.bluetooth))return await navigator.bluetooth.getAvailability()}async getUserVerifyingPlatformAuthenticatorAvailable(){if(!(typeof PublicKeyCredential>"u"||!PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable))return await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}async isConditionalMediationAvailable(){if(!(typeof PublicKeyCredential>"u"||!PublicKeyCredential.isConditionalMediationAvailable))return await PublicKeyCredential.isConditionalMediationAvailable()}async getClientCapabilities(){if(typeof PublicKeyCredential>"u"||!PublicKeyCredential.getClientCapabilities)return;let e=await PublicKeyCredential.getClientCapabilities();return Object.fromEntries(Object.entries(e).map(([t,i])=>[t,i.toString()]))}getClientEnvHandle(){let e=this.storage.getItem("cbo_client_env_handle");if(e)return e;let t=(0,Ve.v7)(),i={timestamp:Date.now(),source:this.storageSource,value:t};return this.storage.setItem("cbo_client_env_handle",i),i}getTabId(){if(!this.sessionStorage)return;let e=this.sessionStorage.getItem(Ke);if(e)return e;let t=(0,Ve.v7)();if(this.sessionStorage.setItem(Ke,t),this.sessionStorage.getItem(Ke)===t)return t}async getJavaScriptHighEntropy(){if(typeof navigator>"u"||!navigator.userAgentData)return;let e=await navigator.userAgentData.getHighEntropyValues(["platformVersion","model"]),t=e.platform,i=e.mobile,r=e.platformVersion,o=e.model||void 0;if(!(!t||i===void 0||!r))return{platform:t,mobile:i,platformVersion:r,model:o}}async isPrivateMode(){return(await(0,vt.default)()).isPrivate}getWebdriver(){if(!(typeof navigator>"u"))return navigator.webdriver}getMaxTouchPoints(){if(!(typeof navigator>"u"||typeof navigator.maxTouchPoints!="number"))return navigator.maxTouchPoints}};var xe=class{constructor(e,t,i,r){this.logger=e;this.source=t;this.refreshInterval=i;this.attachInterval=r}snapshot;refreshedAt=0;lastAttachedAt=null;refreshPromise;timer;destroyed=!1;start(){this.refresh()}getForEvent(){if(Date.now()-this.refreshedAt>=this.refreshInterval&&this.refresh(),!!this.snapshot&&!(this.lastAttachedAt!==null&&Date.now()-this.lastAttachedAt<this.attachInterval))return this.lastAttachedAt=Date.now(),this.snapshot}destroy(){this.destroyed=!0,this.timer&&(clearTimeout(this.timer),this.timer=void 0)}refresh(){return this.refreshPromise?this.refreshPromise:(this.timer&&(clearTimeout(this.timer),this.timer=void 0),this.refreshPromise=Promise.resolve().then(()=>this.source.getInfo()).then(e=>{this.snapshot=e,this.refreshedAt=Date.now()}).catch(e=>this.logger.error("Failed to refresh device info",e)).finally(()=>{this.refreshPromise=void 0,this.destroyed||(this.timer=setTimeout(()=>{this.refresh()},this.refreshInterval))}),this.refreshPromise)}};function w(n,e){return`${n}_${e}`}var z=class{constructor(e,t){this.engine=e;this.namespace=t}getItem(e){return this.engine.getItem(w(e,this.namespace))}setItem(e,t){this.engine.setItem(w(e,this.namespace),t)}removeItem(e){this.engine.removeItem(w(e,this.namespace))}},W=class{constructor(e){this.logger=e}getItem(e){try{if(typeof localStorage>"u")return null;let t=localStorage.getItem(e);return t?JSON.parse(t):null}catch(t){return this.logger.error(`LocalStorage.getItem failed for key "${e}"`,t),null}}setItem(e,t){try{if(typeof localStorage>"u")return;localStorage.setItem(e,JSON.stringify(t))}catch(i){this.logger.error(`LocalStorage.setItem failed for key "${e}"`,i),this.logger.reportTelemetry?.("error",`localStorage.setItem failed: ${e}`)}}removeItem(e){try{if(typeof localStorage>"u")return;localStorage.removeItem(e)}catch(t){this.logger.error(`LocalStorage.removeItem failed for key "${e}"`,t)}}},Q=class{constructor(e,t){this.logger=e;this.domain=t}getItem(e){try{if(typeof document>"u")return null;let t=e+"=",i=document.cookie.split(";");for(let r=0;r<i.length;r++){let o=i[r].trim();if(o.indexOf(t)===0){let s=o.substring(t.length);return JSON.parse(decodeURIComponent(s))}}return null}catch(t){return this.logger.error(`CookieStorage.getItem failed for key "${e}"`,t),null}}setItem(e,t){try{if(typeof document>"u")return;let i=`${e}=${encodeURIComponent(JSON.stringify(t))}; path=/; SameSite=Lax`;this.domain&&(i+=`; domain=${this.domain}`),document.cookie=i}catch(i){this.logger.error(`CookieStorage.setItem failed for key "${e}"`,i),this.logger.reportTelemetry?.("error",`cookie.setItem failed: ${e}`)}}removeItem(e){try{if(typeof document>"u")return;let t=`${e}=; Max-Age=-99999999; path=/`;this.domain&&(t+=`; domain=${this.domain}`),document.cookie=t}catch(t){this.logger.error(`CookieStorage.removeItem failed for key "${e}"`,t)}}},j=class{constructor(e){this.logger=e}getItem(e){try{if(typeof sessionStorage>"u")return null;let t=sessionStorage.getItem(e);return t?JSON.parse(t):null}catch(t){return this.logger.error(`SessionStorage.getItem failed for key "${e}"`,t),null}}setItem(e,t){try{if(typeof sessionStorage>"u")return;sessionStorage.setItem(e,JSON.stringify(t))}catch(i){this.logger.error(`SessionStorage.setItem failed for key "${e}"`,i),this.logger.reportTelemetry?.("error",`sessionStorage.setItem failed: ${e}`)}}removeItem(e){try{if(typeof sessionStorage>"u")return;sessionStorage.removeItem(e)}catch(t){this.logger.error(`SessionStorage.removeItem failed for key "${e}"`,t)}}};var Ie=1,ke="cbo_storage_schema",ui=["cbo_seq","cbo_sdk_config","cbo_experiments","cbo_client_env_handle","cbo_outbox","cbo_visibility_change_debug","cbo_pagehide_debug","cbo_session"],ci=["cbo_session_id","cbo_tab_id"],fi=["cbo_client_env_handle"];function Ce(n,e,t){return n.setItem(e,t),JSON.stringify(n.getItem(e))===JSON.stringify(t)}function $e(n,e,t){let i=n.getItem(ke);if(i!==null){if(i.version!==Ie||i.projectId!==e)return!1;if(i.complete===!0)return!0;if(i.complete!==!1)return!1}else{if(t.some(r=>n.getItem(w(r,e))!==null))return Ce(n,ke,{version:Ie,projectId:e,complete:!0});if(!Ce(n,ke,{version:Ie,projectId:e,complete:!1}))return!1}for(let r of t){let o=w(r,e);if(n.getItem(o)!==null)continue;let s=n.getItem(r);if(s!==null&&!Ce(n,o,s))return!1}return Ce(n,ke,{version:Ie,projectId:e,complete:!0})}function St(n,e,t,i,r){try{if(!$e(e,n,ui))return;$e(t,n,ci),i&&$e(i,n,fi)}catch(o){r.error("Failed to migrate legacy Observe storage",o)}}var hi=10*1e3,gi=600*1e3,mi=[1e3,3e3],Oe=class{constructor(e,t,i){this.url=e;this.storage=t;this.logger=i;this.initialConfig=Ue(t)??void 0}initialConfig;refreshTimer;requestTimer;retryTimer;controller;fetching=!1;stopped=!1;onConfig;start(e){this.stopped||this.onConfig||(this.onConfig=e,this.fetchConfig())}async fetchConfig(e=0){if(this.stopped||this.fetching)return;e===0&&(clearTimeout(this.refreshTimer),clearTimeout(this.retryTimer),this.refreshTimer=setTimeout(()=>{this.fetchConfig()},gi)),this.fetching=!0;let t=typeof AbortController<"u"?new AbortController:void 0;this.controller=t,this.requestTimer=t?setTimeout(()=>t.abort(),hi):void 0;let i=!0;try{let r=await fetch(this.url,{method:"GET",cache:"no-store",...t?{signal:t.signal}:{}});if(!r.ok)throw i=(r.status===408||r.status===429||r.status>=500)&&!r.headers.has("Retry-After"),new Error(`SDK config request failed (${r.status})`);let o=await r.json();i=!1;let s=H(o);if(!s)throw new Error("Invalid SDK config response");if(this.stopped||t?.signal.aborted)return;Be(this.storage,s),this.onConfig?.(s)}catch(r){if(!this.stopped){this.logger.error("Failed to fetch SDK config",r);let o=mi[e];(i&&!(r instanceof SyntaxError)||t?.signal.aborted)&&o!==void 0&&(this.retryTimer=setTimeout(()=>{this.fetchConfig(e+1)},o))}}finally{clearTimeout(this.requestTimer),this.requestTimer=void 0,this.controller=void 0,this.fetching=!1}}destroy(){this.stopped=!0,clearTimeout(this.refreshTimer),clearTimeout(this.requestTimer),clearTimeout(this.retryTimer),this.controller?.abort(),this.onConfig=void 0}};var I=require("uuid");var N=class{constructor(e,t){this.logger=e;this.sink=t}lease;destroyed=!1;arm(e,t=!1){if(this.disarm(),!(this.destroyed||t))try{this.lease=this.sink.beginCeremony?.(e)}catch(i){this.logger.error("Failed to register ceremony low-event context",i)}}scheduleDisarm(e){try{this.lease?.settle(e)}catch(t){this.logger.error("Failed to settle ceremony low-event context",t)}}disarm(){try{this.lease?.destroy()}catch(e){this.logger.error("Failed to release ceremony low-event context",e)}this.lease=void 0}destroy(){this.disarm(),this.destroyed=!0}};var Y=class extends h{getOptions;ceremony;postResponse;lowEventTracker;constructor(e,t){super(e,"passkey-login"),this.lowEventTracker=new N(e.getLogger(),this.lowEventSink("ceremony")),this.registerLowFlusher(()=>this.lowEventTracker.disarm()),this.getOptions=this.defineStep("get-options"),this.ceremony=this.withWindowLowEvents(this.defineStep("ceremony"),this.lowEventTracker),this.postResponse=this.defineStep("post-response"),this.subflowStart({explicitSpecType:t?.explicitSpecType})}trigger(e,t){super.trigger(e,t)}destroy(){this.lowEventTracker.destroy()}};var U=class{constructor(e,t,i,r){this.previousLength=e;this.pushLow=t;this.logger=i;this.reserveCaptureSeq=r}prefillSettled=!1;inputBatch=null;currentEffect="modify";ringEffect="modify";autofillTimestamps=[];autofillStreak=null;idleTimer=null;markInputObserved(){this.prefillSettled=!0}capturePrefill(e,t=!1){t&&(this.prefillSettled=!1),!this.prefillSettled&&(this.previousLength=e,e!==0&&(this.prefillSettled=!0,this.pushLow({lowType:"input-prefill",ts:Date.now(),initiator:"unknown"})))}flush(){this.cancelIdle(),this.flushInputBatch(),this.flushAutofillStreak()}cancelIdle(){this.idleTimer!==null&&clearTimeout(this.idleTimer),this.idleTimer=null}scheduleIdle(){this.cancelIdle(),this.idleTimer=setTimeout(()=>{this.idleTimer=null;try{this.flushInputBatch(!0),this.flushAutofillStreak()}catch(e){this.logger.error("Failed to flush idle input",e)}},3e3)}extendInputBatch(e,t=this.currentEffect,i){let r=this.inputBatch;if(!r){this.inputBatch={firstTimestamp:e,lastTimestamp:e,effect:t,captureSeq:i};return}r.lastTimestamp=e}drainAutofillRingToBatch(){for(let e of this.autofillTimestamps)this.extendInputBatch(e.ts,this.ringEffect,e.captureSeq);this.autofillTimestamps.length=0}flushInputBatch(e=!1){this.drainAutofillRingToBatch();let t=this.inputBatch;t&&(this.pushLow({...t.captureSeq===void 0?{}:{captureSeq:t.captureSeq},lowType:e?"input-idle":"input",ts:t.firstTimestamp,durationMs:t.lastTimestamp-t.firstTimestamp,inputEffect:t.effect}),this.inputBatch=null)}flushAutofillStreak(){let e=this.autofillStreak;e&&(this.pushLow({...e.captureSeq===void 0?{}:{captureSeq:e.captureSeq},lowType:"big-input-add",ts:e.firstTimestamp,durationMs:e.lastTimestamp-e.firstTimestamp,inputEffect:e.effect}),this.autofillStreak=null)}detectAutofillStreak(){let e=this.autofillTimestamps;if(e.length<5)return!1;let t=1/0,i=-1/0;for(let r=1;r<e.length;r++){let o=e[r].ts-e[r-1].ts;if(o>80)return!1;o<t&&(t=o),o>i&&(i=o)}return i-t<=25}record(e,t=Date.now(),i=!1,r=this.reserveCaptureSeq?.()){this.markInputObserved(),this.scheduleIdle();let o=this.previousLength;this.currentEffect=e===0?"clear":o===0?"fill":"modify";let s=e-o;if(this.previousLength=e,e===0&&o>0){this.flush(),this.pushLow({...r===void 0?{}:{captureSeq:r},lowType:"input-clear",ts:t,inputEffect:"clear"});return}if(i){this.flushAutofillStreak(),this.drainAutofillRingToBatch(),this.extendInputBatch(t,this.currentEffect,r);return}if(s>=3){this.flushInputBatch(),this.flushAutofillStreak(),this.pushLow({...r===void 0?{}:{captureSeq:r},lowType:"big-input-add",ts:t,inputEffect:this.currentEffect});return}if(s<=-3){this.flushInputBatch(),this.flushAutofillStreak(),this.pushLow({...r===void 0?{}:{captureSeq:r},lowType:"big-input-rem",ts:t,inputEffect:this.currentEffect});return}let a=this.autofillStreak;if(a){if(s===1&&t-a.lastTimestamp<=80){a.lastTimestamp=t;return}this.flushAutofillStreak()}if(s!==1){this.drainAutofillRingToBatch(),this.extendInputBatch(t,this.currentEffect,r);return}let l=this.autofillTimestamps;if(l.length===0&&(this.ringEffect=this.currentEffect),l.push({ts:t,captureSeq:r}),l.length>5){let d=l.shift();this.extendInputBatch(d.ts,this.ringEffect,d.captureSeq),this.ringEffect="modify"}if(!this.detectAutofillStreak())return;let p=l[0],u=l[l.length-1];l.length=0,this.flushInputBatch(),this.autofillStreak={firstTimestamp:p.ts,captureSeq:p.captureSeq,lastTimestamp:u.ts,effect:this.ringEffect}}};var B=class{constructor(e,t,i,r){this.inputs=e;this.logger=t;this.changed=i;this.reserveCaptureSeq=r;for(let o of e)o.addEventListener("paste",this.onPaste,!0),o.addEventListener("beforeinput",this.onBeforeInput,!0)}before=null;timestamp=0;captureSeq;pasteEvent;timer=null;onPaste=e=>this.begin(e);onBeforeInput=e=>{e.inputType==="insertFromPaste"?this.begin(e):this.flush()};handlesInput(e){if(!this.before)return!1;let t=this.pasteEvent?.type==="paste"&&(this.pasteEvent.eventPhase??0)>0;return e.inputType==="insertFromPaste"||t?!0:(this.clear(),!1)}get pending(){return this.before!==null}begin(e){if(!(!e.isTrusted||this.before))try{this.before=this.inputs.map(t=>t.value),this.pasteEvent=e,this.timestamp=Date.now(),this.captureSeq=this.reserveCaptureSeq?.(),this.timer=setTimeout(()=>this.flush(),0)}catch(t){this.logger.error("Failed to observe paste",t),this.clear()}}flush(){let e=this.before;if(!e)return;let t=this.timestamp,i=this.captureSeq;this.clear();try{let r=0,o=!1;this.inputs.forEach((s,a)=>{let l=e[a],p=s.value;if(l===p)return;o=!0;let u=0;for(;u<l.length&&u<p.length&&l[u]===p[u];)u++;let d=0;for(;d<l.length-u&&d<p.length-u&&l[l.length-d-1]===p[p.length-d-1];)d++;r+=p.length-u-d}),o&&this.changed(t,r,i)}catch(r){this.logger.error("Failed to finish paste observation",r)}}clear(){this.timer!==null&&clearTimeout(this.timer),this.timer=null,this.before=null,this.pasteEvent=void 0}destroy(){this.flush();for(let e of this.inputs)e.removeEventListener("paste",this.onPaste,!0),e.removeEventListener("beforeinput",this.onBeforeInput,!0)}};var yi=[{query:"com-1password-button",eventType:"pa-1"},{query:"com-1password-menu",eventType:"pa-2"},{query:"com-1password-notification",eventType:"pa-3"}],vi="[data-lastpass-root], [data-lp], [data-lpignore], [data-lpfieldtype]",Tt="pa-4",Si='[popover="manual"]',Ti=400,bi=20,Ge="pa-5",ze="pa-6",We=(n,e)=>{try{return Array.from(n.querySelectorAll(e))}catch{return[]}},bt=n=>{if(n.getAttribute("popover")!=="manual")return!1;let e=n.getAttribute("style")??"";return!(e.length<Ti||!/z-index:\s*2147483647\b/i.test(e)||!/position:\s*fixed\b/i.test(e)||!/display:\s*block\b/i.test(e)||(e.match(/initial\s*!important/gi)?.length??0)<bi)},wi=n=>{if(bt(n)||n.getAttribute("popover")!=="manual")return!1;let e=n.getAttribute("style")??"";return!(!/z-index:\s*2147483647\b/i.test(e)||!/position:\s*fixed\b/i.test(e)||!/backdrop-filter:\s*[^;]*blur\(\s*20px\s*\)/i.test(e)||!/background-color:\s*rgba\(\s*35\s*,\s*35\s*,\s*35\s*,/i.test(e))},Ei=n=>{n(document);for(let e of Array.from(document.querySelectorAll("*"))){let t=e.shadowRoot;t&&n(t)}},wt=()=>{let n=new Set;return typeof document>"u"||Ei(e=>{for(let t of yi)n.has(t.eventType)||We(e,t.query).length>0&&n.add(t.eventType);if(!n.has(Tt)&&We(e,vi).length>0&&n.add(Tt),!n.has(Ge)||!n.has(ze))for(let t of We(e,Si)){if(!n.has(Ge)&&bt(t)){n.add(Ge);continue}!n.has(ze)&&wi(t)&&n.add(ze)}}),n};var xi=500,Ii=250,b=class{constructor(e,t,i){this.logger=e;this.inputField=t;this.sink=i;this.changes=new U(t.value.length,this.pushLow,e,i.reserveCaptureSeq),this.pasteObserver=new B([t],e,(r,o,s)=>{this.changes.flush(),this.changes.markInputObserved();let a=this.changes.previousLength;this.changes.previousLength=t.value.length,this.pushLow({...s===void 0?{}:{captureSeq:s},lowType:"input-paste",ts:r,inputEffect:t.value.length===0?"clear":a===0?"fill":"modify"})},i.reserveCaptureSeq),this.boundHandlers={focus:this.wrapHandler("focus",()=>this.handleFocus()),blur:this.wrapHandler("blur",()=>this.handleBlur()),pointerdown:this.wrapHandler("pointerdown",()=>this.enqueueNonInputEvent("pointerdown")),pointerup:this.wrapHandler("pointerup",()=>this.enqueueNonInputEvent("pointerup")),click:this.wrapHandler("click",()=>this.enqueueNonInputEvent("click")),input:r=>{try{this.handleInput(r)}catch(o){this.logger.error("Failed to observe input",o)}},keyup:this.wrapKeyboardHandler("keyup",r=>this.handleKeyUp(r)),pageHide:this.wrapHandler("pagehide",()=>this.flushForTeardown())},this.unregisterInputs=i.registerInputs?.([t],()=>this.flushPending()),this.capturePrefill(),this.attach()}unregisterInputs;changes;pasteObserver;emittedSignals=new Set;firstFocusHandled=!1;mountProbeTimer=null;focusProbeTimer=null;destroyed=!1;boundHandlers;destroy(){if(!this.destroyed){this.destroyed=!0;try{this.mountProbeTimer!==null&&(clearTimeout(this.mountProbeTimer),this.mountProbeTimer=null),this.focusProbeTimer!==null&&(clearTimeout(this.focusProbeTimer),this.focusProbeTimer=null),this.changes.flush(),this.unregisterInputs?.(),this.pasteObserver.destroy(),this.detach()}catch(e){this.logger.error("Failed to destroy LowEventInputTracker",e)}}}attach(){let e=this.inputField;e.addEventListener("focus",this.boundHandlers.focus),e.addEventListener("blur",this.boundHandlers.blur),e.addEventListener("pointerdown",this.boundHandlers.pointerdown),e.addEventListener("pointerup",this.boundHandlers.pointerup),e.addEventListener("click",this.boundHandlers.click),e.addEventListener("input",this.boundHandlers.input),e.addEventListener("keyup",this.boundHandlers.keyup),typeof window<"u"&&window.addEventListener("pagehide",this.boundHandlers.pageHide),typeof document<"u"&&document.activeElement===e&&this.handleFocus(),typeof window<"u"&&(this.mountProbeTimer=setTimeout(()=>this.runEnvProbe(),xi))}detach(){let e=this.inputField;e.removeEventListener("focus",this.boundHandlers.focus),e.removeEventListener("blur",this.boundHandlers.blur),e.removeEventListener("pointerdown",this.boundHandlers.pointerdown),e.removeEventListener("pointerup",this.boundHandlers.pointerup),e.removeEventListener("click",this.boundHandlers.click),e.removeEventListener("input",this.boundHandlers.input),e.removeEventListener("keyup",this.boundHandlers.keyup),typeof window<"u"&&window.removeEventListener("pagehide",this.boundHandlers.pageHide)}pushLow=e=>{this.sink.enqueueLowEvent(e)};runEnvProbe(){try{let e=wt(),t=Date.now();for(let i of e)this.emittedSignals.has(i)||(this.emittedSignals.add(i),this.pushLow({lowType:i,ts:t}))}catch(e){this.logger.error("Failed to run input env probe",e)}}scheduleFocusProbe(){this.firstFocusHandled||(this.firstFocusHandled=!0,this.focusProbeTimer=setTimeout(()=>this.runEnvProbe(),Ii))}capturePrefill(e=!1){this.destroyed||(this.flushPending(),this.changes.capturePrefill(this.inputField.value.length,e))}flushPending(){this.pasteObserver.flush(),this.changes.flush()}enqueueNonInputEvent(e){this.changes.flush(),this.pushLow({lowType:e,ts:Date.now()})}handleFocus(){this.scheduleFocusProbe(),this.enqueueNonInputEvent("focus")}handleBlur(){this.pasteObserver.flush(),this.enqueueNonInputEvent("blur")}handleInput(e){this.pasteObserver.handlesInput(e)||this.changes.record(this.inputField.value.length,Date.now(),e.isComposing||e.inputType==="insertCompositionText")}handleKeyUp(e){e.key==="Escape"&&this.enqueueNonInputEvent("keyup-escape")}flushForTeardown(){this.pasteObserver.flush(),this.changes.flush(),this.sink.flushKeepalive()}wrapHandler(e,t){return()=>{try{t()}catch(i){this.logger.error(`Failed to handle low event "${e}"`,i)}}}wrapKeyboardHandler(e,t){return i=>{try{t(i)}catch(r){this.logger.error(`Failed to handle low event "${e}"`,r)}}}};var Le=class{constructor(e,t,i){this.logger=e;this.sink=i;this.inputs=[...new Set(t)],this.changes=new U(this.length(),r=>i.enqueueLowEvent(r),e,i.reserveCaptureSeq),this.paste=new B(this.inputs,e,(r,o,s)=>{this.cancelChange(),this.changes.flush(),this.changes.markInputObserved();let a=this.changes.previousLength;this.changes.previousLength=this.length(),i.enqueueLowEvent({...s===void 0?{}:{captureSeq:s},lowType:"input-paste",ts:r,inputEffect:this.length()===0?"clear":a===0?"fill":"modify"})},i.reserveCaptureSeq),this.unregisterInputs=i.registerInputs?.(this.inputs,()=>this.flushPending()),this.capturePrefill();for(let r of this.inputs){this.listen(r,"input",o=>{this.paste.handlesInput(o)||(this.composing||=o.isComposing||o.inputType==="insertCompositionText",this.changeTimer===null&&(this.changeTime=Date.now(),this.changeSeq=i.reserveCaptureSeq?.(),this.changeTimer=setTimeout(()=>this.safe(()=>this.flushChanges()),0)))}),this.listen(r,"focus",o=>{this.contains(o.relatedTarget)||this.emit("focus")}),this.listen(r,"blur",o=>{this.contains(o.relatedTarget)||(this.flushPending(),this.emit("blur"))});for(let o of["click","pointerdown","pointerup"])this.listen(r,o,()=>this.emit(o));this.listen(r,"keyup",o=>{o.key==="Escape"&&this.emit("keyup-escape")})}typeof window<"u"&&this.listen(window,"pagehide",()=>{this.flushPending(),i.flushKeepalive()}),typeof document<"u"&&this.contains(document.activeElement)&&this.emit("focus")}inputs;changes;paste;unregisterInputs;listeners=[];changeTimer=null;changeTime=0;changeSeq;composing=!1;destroyed=!1;contains(e){return this.inputs.some(t=>t===e)}length(){return this.inputs.reduce((e,t)=>e+t.value.length,0)}safe(e){try{e()}catch(t){this.logger.error("Failed to observe grouped input",t)}}listen(e,t,i){let r=o=>this.safe(()=>i(o));e.addEventListener(t,r),this.listeners.push(()=>e.removeEventListener(t,r))}cancelChange(){this.changeTimer!==null&&clearTimeout(this.changeTimer),this.changeTimer=null}flushChanges(){this.changeTimer!==null&&(this.cancelChange(),this.paste.pending||this.changes.record(this.length(),this.changeTime,this.composing,this.changeSeq),this.composing=!1)}emit(e){this.flushChanges(),this.changes.flush(),this.sink.enqueueLowEvent({lowType:e,ts:Date.now()})}capturePrefill(e=!1){this.destroyed||(this.flushPending(),this.changes.capturePrefill(this.length(),e))}flushPending(){this.paste.flush(),this.flushChanges(),this.changes.flush()}destroy(){this.destroyed||(this.destroyed=!0,this.safe(()=>{this.flushPending(),this.paste.destroy(),this.unregisterInputs?.();for(let e of this.listeners)e()}))}};var k=class{constructor(e,t,i){this.logger=e;this.inputSink=t;this.groupSink=i}collector;fields=[];grouped=!1;destroyed=!1;prefillClaimed=!1;setFields(e,t=!0){try{if(this.destroyed)return;let i=[...new Set(e)];if(t===this.grouped&&i.length===this.fields.length&&i.every((s,a)=>s===this.fields[a])||(this.collector?.destroy(),this.collector=void 0,this.fields=[],this.grouped=t,i.length===0))return;let r=t?this.groupSink:this.inputSink,o={...r,enqueueLowEvent:s=>this.enqueue(r,s)};this.collector=t?new Le(this.logger,i,o):new b(this.logger,i[0],o),this.fields=i}catch(i){this.logger.error("Failed to bind OTP inputs",i)}}enqueue(e,t){if(t.lowType==="input-prefill"){if(this.prefillClaimed)return;this.prefillClaimed=!0}else["input","input-idle","input-clear","input-paste","big-input-paste","big-input-add","big-input-rem"].includes(t.lowType)&&(this.prefillClaimed=!0);e.enqueueLowEvent(t)}capturePrefill(e=!1){e&&(this.prefillClaimed=!1),this.collector?.capturePrefill(e)}flushPending(){this.collector?.flushPending()}destroy(){this.destroyed=!0,this.collector?.destroy(),this.collector=void 0,this.fields=[]}};var J=class extends h{lowEventTracker;send;postResponse;resend;constructor(e,t={}){super(e,"email-otp"),this.send=this.defineStep("send"),this.postResponse=this.defineStep("post-response"),this.resend=this.defineStep("resend"),this.subflowStart({explicitSpecType:t.explicitSpecType,emailDomain:t.emailDomain}),this.lowEventTracker=this.createLowCollector(()=>new k(e.getLogger(),this.lowEventSink("input","otp"),this.lowEventSink("input-group","otp"))),t.inputHtmlFields?.length?this.setInputFields(t.inputHtmlFields):t.inputHtmlField&&this.lowEventTracker?.setFields([t.inputHtmlField],!1),this.registerLowFlusher(()=>this.lowEventTracker?.flushPending())}setInputFields(e){this.lowEventTracker?.setFields(e)}destroy(){this.lowEventTracker?.destroy()}};var X=class extends h{lowEventTracker;send;postResponse;resend;constructor(e,t={}){super(e,"sms-otp"),this.send=this.defineStep("send"),this.postResponse=this.defineStep("post-response"),this.resend=this.defineStep("resend"),this.subflowStart({explicitSpecType:t.explicitSpecType}),this.lowEventTracker=this.createLowCollector(()=>new k(e.getLogger(),this.lowEventSink("input","otp"),this.lowEventSink("input-group","otp"))),t.inputHtmlFields?.length?this.setInputFields(t.inputHtmlFields):t.inputHtmlField&&this.lowEventTracker?.setFields([t.inputHtmlField],!1),this.registerLowFlusher(()=>this.lowEventTracker?.flushPending())}setInputFields(e){this.lowEventTracker?.setFields(e)}destroy(){this.lowEventTracker?.destroy()}};var ki=["ahrefsbot","ahrefssiteaudit","amazonbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","facebookexternal","petalbot","pinterest","screaming frog","yahoo! slurp","yandex","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleweblight","mediapartners-google","storebot-google"];function Et(n){if(!n)return!1;let e=n.toLowerCase();return ki.some(t=>e.includes(t))}var Pe="@corbado/observe",Re="1.1.4";var Ct=require("uuid");var Qe="cbo_email_link_starts";function je(n,e){let t=n.getItem(Qe);return Array.isArray(t)?t.filter(i=>!!i&&typeof i=="object"&&typeof i.transactionId=="string"&&typeof i.anchor=="string"&&typeof i.sessionId=="string"&&typeof i.startedAt=="number"&&e-i.startedAt<864e5):[]}function xt(n,e){if(n)try{let t=je(n,e.startedAt).filter(i=>i.transactionId!==e.transactionId);t.push(e),n.setItem(Qe,t.slice(-10))}catch{}}function It(n,e,t=Date.now()){if(n)try{let i=je(n,t);if(e.transactionId)return i.find(o=>o.transactionId===e.transactionId);let r=i.filter(o=>!o.continued&&(!e.specType||!o.specType||o.specType===e.specType));return r[r.length-1]}catch{return}}function kt(n,e){if(n)try{let t=je(n,Date.now()).map(i=>i.transactionId===e?{...i,continued:!0}:i);n.setItem(Qe,t)}catch{}}var Z=class extends h{send;postResponse;resend;transactionId;constructor(e,t={}){super(e,"email-link"),this.send=this.defineStep("send"),this.postResponse=this.defineStep("post-response"),this.resend=this.defineStep("resend"),this.transactionId=t.transactionId||(0,Ct.v7)(),this.subflowStart({explicitSpecType:t.explicitSpecType},{userReference:{crossEnvironmentTransactionIDStart:this.transactionId}});let i=this.captureReference,r=this.captureSession;i&&r&&xt(e.getPersistentStorage(),{transactionId:this.transactionId,anchor:i,sessionId:r,specType:t.explicitSpecType,startedAt:Date.now()})}},ee=class extends h{postResponse;resend;mode;continuationTracker;specType;createdAt=Date.now();transaction;started=!1;deferred=[];onPageHide=()=>this.flush();constructor(e,t={}){super(e,"email-link"),this.continuationTracker=e,this.specType=t.explicitSpecType,this.transaction=t.transactionId,this.postResponse=this.deferrable(this.defineStep("post-response"),!0),this.resend=this.deferrable(this.defineStep("resend"));let i=e.getPersistentStorage(),r=It(i,{transactionId:t.transactionId,specType:t.explicitSpecType});if(r&&r.sessionId===e.getSessionId()){this.mode="attached",this.transaction=t.transactionId??r.transactionId,this.adoptCapture(r.anchor,r.sessionId,r.specType??t.explicitSpecType),this.started=!0;return}this.mode="detached",this.transaction?this.startDetached(this.createdAt):typeof window<"u"&&window.addEventListener("pagehide",this.onPageHide)}get transactionId(){return this.transaction}setTransactionId(e){!e||this.transaction||(this.transaction=e,this.mode==="detached"&&!this.started&&this.startDetached(this.firstDeferredAt()))}flush(){this.mode==="detached"&&!this.started&&this.startDetached(this.firstDeferredAt())}destroy(){this.flush(),this.removePageHideListener()}firstDeferredAt(){return this.deferred[0]?.at??this.createdAt}startDetached(e){this.started=!0,this.removePageHideListener(),this.subflowStart({explicitSpecType:this.specType,continuation:!0},{explicitTimestamp:e,...this.transaction?{userReference:{crossEnvironmentTransactionIDFinish:this.transaction}}:{}});let t=this.deferred;this.deferred=[];for(let i of t)i.run(i.at);try{this.continuationTracker.flushKeepalive()}catch{}}removePageHideListener(){typeof window<"u"&&window.removeEventListener("pagehide",this.onPageHide)}deferrable(e,t=!1){let i=(r,o)=>{if(this.started){r(o?.explicitTimestamp??Date.now());return}this.deferred.push({at:o?.explicitTimestamp??Date.now(),run:r})};return{start:(r,o)=>i(s=>e.start(r,{...o,explicitTimestamp:s}),o),finished:(r,o)=>{i(s=>e.finished(r,{...o,explicitTimestamp:s}),o),t&&this.transaction&&kt(this.continuationTracker.getPersistentStorage(),this.transaction)},error:(r,o)=>i(s=>e.error(r,{...o,explicitTimestamp:s}),o)}}};var te=class extends h{getOptions;ceremony;postResponse;lowEventTracker;constructor(e,t){super(e,"passkey-enrollment"),this.lowEventTracker=new N(e.getLogger(),this.lowEventSink("ceremony")),this.registerLowFlusher(()=>this.lowEventTracker.disarm()),this.getOptions=this.defineStep("get-options"),this.ceremony=this.withWindowLowEvents(this.defineStep("ceremony"),this.lowEventTracker),this.postResponse=this.defineStep("post-response"),this.subflowStart({explicitSpecType:t?.explicitSpecType,...t?.ignoreAsInteraction?{ignoreAsInteraction:!0}:{}})}destroy(){this.lowEventTracker.destroy()}};function Ye(n){let e=n.debug,t,i=(r,o)=>`[Corbado Observe SDK ${r}] ${o}`;return{reportTelemetry(r,o){if(t)try{t(r,o)}catch{}},setTelemetrySink(r){t=r},debug(r,...o){e&&console.log(i("DEBUG",r),...o)},info(r,...o){e&&console.log(i("INFO",r),...o)},warn(r,...o){e&&console.warn(i("WARN",r),...o)},error(r,...o){e&&console.error(i("ERROR",r),...o)},critical(r,...o){console.error(i("CRITICAL",r),...o)}}}var ie=class extends h{clientValidation;postResponse;cui;lowEventTracker;identifierLowEventTracker;constructor(e,t){super(e,"password-login"),this.clientValidation=this.defineStep("client-validation"),this.postResponse=this.defineStep("post-response"),this.cui={getOptions:this.defineStep("cui-get-options",!0),ceremony:this.defineStep("cui-ceremony"),postResponse:this.defineStep("cui-post-response")},this.subflowStart({explicitSpecType:t?.explicitSpecType}),t?.identifierInputHtmlField&&(this.identifierLowEventTracker=this.createLowCollector(()=>new b(e.getLogger(),t.identifierInputHtmlField,this.lowEventSink("input","identifier"))),this.registerLowFlusher(()=>this.identifierLowEventTracker?.flushPending())),t?.inputHtmlField&&(this.lowEventTracker=this.createLowCollector(()=>new b(e.getLogger(),t.inputHtmlField,this.lowEventSink("input","password"))),this.registerLowFlusher(()=>this.lowEventTracker?.flushPending()))}trigger(e,t){super.trigger(e,t)}destroy(){this.lowEventTracker?.destroy(),this.identifierLowEventTracker?.destroy()}};var re=class extends h{clientValidation;postResponse;lowEventTracker;constructor(e,t){super(e,"password-enrollment"),this.clientValidation=this.defineStep("client-validation"),this.postResponse=this.defineStep("post-response"),this.subflowStart({explicitSpecType:t?.explicitSpecType}),t?.inputHtmlField&&(this.lowEventTracker=this.createLowCollector(()=>new b(e.getLogger(),t.inputHtmlField,this.lowEventSink("input","password"))),this.registerLowFlusher(()=>this.lowEventTracker?.flushPending()))}destroy(){this.lowEventTracker?.destroy()}};var ne=class extends h{lowEventTracker;cui;provideIdentifier;constructor(e,t){super(e,"provide-identifier"),this.cui={trigger:(i,r)=>{this.trigger(i,r)},getOptions:this.defineStep("cui-get-options",!0),ceremony:this.defineStep("cui-ceremony"),postResponse:this.defineStep("cui-post-response")},this.provideIdentifier={trigger:(i,r)=>{this.trigger(i,r)},clientValidation:this.defineStep("pi-client-validation"),postResponse:this.defineStep("pi-post-response")},this.subflowStart({explicitSpecType:t?.explicitSpecType}),t?.inputHtmlField&&(this.lowEventTracker=this.createLowCollector(()=>new b(e.getLogger(),t.inputHtmlField,this.lowEventSink("input","identifier"))),this.registerLowFlusher(()=>this.lowEventTracker?.flushPending()))}destroy(){this.lowEventTracker?.destroy()}};var oe=class extends h{getRedirectUrl;exchangeCode;constructor(e,t={}){super(e,"social-login"),this.getRedirectUrl=this.defineStep("get-redirect-url"),this.exchangeCode=this.defineStep("exchange-code"),this.subflowStart({explicitSpecType:t.explicitSpecType})}};var se=class extends h{getRedirectUrl;exchangeCode;constructor(e,t={}){super(e,"sso-login"),this.getRedirectUrl=this.defineStep("get-redirect-url"),this.exchangeCode=this.defineStep("exchange-code");let{explicitSpecType:i,organizationDomain:r,actor:o}=Ci(t??{},e);this.subflowStart({explicitSpecType:i,organizationDomain:r,actor:o})}};function Ci(n,e){let t={...n},i=o=>{try{e.getLogger().warn(`SSO login: unsupported ${o}; omitted from telemetry`)}catch{}},r=t.organizationDomain;return r!==void 0&&(typeof r!="string"||r.includes("@")||r.length>253)&&(delete t.organizationDomain,i("organizationDomain")),t.actor!==void 0&&t.actor!=="user"&&t.actor!=="system"&&(delete t.actor,i("actor")),t}var ae=class extends h{lowEventTracker;postResponse;constructor(e,t={}){super(e,"totp"),this.postResponse=this.defineStep("post-response"),this.subflowStart({explicitSpecType:t.explicitSpecType}),this.lowEventTracker=this.createLowCollector(()=>new k(e.getLogger(),this.lowEventSink("input","otp"),this.lowEventSink("input-group","otp"))),t.inputHtmlFields?.length?this.setInputFields(t.inputHtmlFields):t.inputHtmlField&&this.lowEventTracker?.setFields([t.inputHtmlField],!1),this.registerLowFlusher(()=>this.lowEventTracker?.flushPending())}setInputFields(e){this.lowEventTracker?.setFields(e)}destroy(){this.lowEventTracker?.destroy()}};var le=class extends h{ceremony;retry;postResponse;constructor(e,t={}){super(e,"app-confirmation"),this.ceremony=this.defineStep("ceremony"),this.retry=this.defineStep("retry"),this.postResponse=this.defineStep("post-response"),this.subflowStart({explicitSpecType:t.explicitSpecType})}};var pe=class extends h{ceremony;postResponse;constructor(e,t={}){super(e,"captcha"),this.ceremony=this.defineStep("ceremony"),this.postResponse=this.defineStep("post-response"),this.subflowStart({explicitSpecType:t.explicitSpecType})}};function Je(n,e,t){if(n===null||typeof n!="object")return n;try{let i={...n};i.purpose===void 0&&e.purpose!==void 0&&(i.purpose=e.purpose),i.storage===void 0&&e.storage!==void 0&&(i.storage=e.storage),i.trustName===void 0&&e.trustName!==void 0&&(i.trustName=e.trustName);for(let[r,o]of[["bindingReference",255],["trustName",128]])if(typeof i[r]=="string"&&[...i[r]].length>o){delete i[r];try{t.getLogger().debug(`Trusted device: omitted ${r} exceeding ${o} characters`)}catch{}}return i}catch{return n}}function Fe(n,e,t){return{...n,start:(i,r)=>n.start(Je(i,e,t),r),finished:(i,r)=>n.finished(Je(i,e,t),r)}}var de=class extends h{getOptions;ceremony;postResponse;constructor(e,t){super(e,"trusted-device-check"),t=Ot(t,e);let i={purpose:t.purpose,storage:t.storage,trustName:t.trustName};this.getOptions=this.checkStep("get-options",i,e),this.ceremony=this.checkStep("ceremony",i,e),this.postResponse=this.checkStep("post-response",i,e),this.subflowStart({explicitSpecType:t.explicitSpecType,actor:"system",ignoreAsInteraction:!0})}checkStep(e,t,i){let r=this.defineStep(e,!0);return{...Fe(r,t,i),errorTyped:(o,s)=>{r.errorTyped(Je({code:o?.code,error:F(o?.error)},t,i),s)}}}},ue=class extends h{getOptions;ceremony;postResponse;constructor(e,t){super(e,"trusted-device-enrollment"),t=Ot(t,e);let i={purpose:t.purpose,storage:t.storage,trustName:t.trustName};this.getOptions=Fe(this.defineStep("get-options"),i,e),this.ceremony=Fe(this.defineStep("ceremony"),i,e),this.postResponse=Fe(this.defineStep("post-response"),i,e),this.subflowStart({explicitSpecType:t.explicitSpecType})}};function Ot(n,e){let t={...n},i=r=>{try{e.getLogger().warn(`Trusted device: missing or unsupported ${r}; omitted from telemetry`)}catch{}};return t.purpose!=="additional-verification"&&t.purpose!=="mfa-exemption"&&(delete t.purpose,i("purpose")),["cookie","indexeddb","localstore","sessionstore"].includes(t.storage)||(delete t.storage,i("storage")),t}var ce=class extends h{clientValidation;postResponse;lowEventTracker;constructor(e,t={}){super(e,"provide-data"),this.clientValidation=this.defineStep("client-validation"),this.postResponse=this.defineStep("post-response");let{inputHtmlField:i,...r}=t;this.subflowStart(r),i&&(this.lowEventTracker=this.createLowCollector(()=>new b(e.getLogger(),i,this.lowEventSink("input","data"))),this.registerLowFlusher(()=>this.lowEventTracker?.flushPending()))}destroy(){this.lowEventTracker?.destroy()}};var Oi={name:Pe,version:Re},Lt="cbo_session_id",Xe="cbo_session",R="cbo_seq",Pt="cbo_experiments",Rt="cbo_data_policy",Li=255,Pi=/^[A-Za-z0-9_-]+$/,Ri=128,Fi=256,Ft=1e3,Ai=50,Di="cbo_seq",At=1e3,Dt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,fe=class n{constructor(e){this.options=e;this.options.debug=e.debug??!1,this.logger=e.logger??Ye({debug:this.options.debug});let t=new W(this.logger),i=new j(this.logger),r=e.storage==="cookie",o=r?new Q(this.logger,e.cookieDomain):void 0;St(e.projectId,t,i,o,this.logger);let s=e.projectId,a=g=>new z(g,s);this.seqLockName=w(Di,s),this.sessionStorage=a(i),this.persistentStorage=a(t),this.storage=a(o??t),this.configOverrides={...e.sdkConfig,...e.sdkConfig?.retry&&{retry:{...e.sdkConfig.retry}},...e.sdkConfig?.flushOnFlowTypeFinished&&{flushOnFlowTypeFinished:[...e.sdkConfig.flushOnFlowTypeFinished]},...e.sdkConfig?.sourcePathQueryAllow&&{sourcePathQueryAllow:[...e.sdkConfig.sourcePathQueryAllow]}};let l=Object.keys(y).every(g=>this.configOverrides[g]!==void 0)&&Object.keys(y.retry).every(g=>this.configOverrides.retry?.[g]!==void 0);l||(this.configManager=new Oe(e.apiBaseUrl+(e.apiConfigPath??"/v1/observe/config")+"/"+e.projectId,this.persistentStorage,this.logger));let p=this.configManager?.initialConfig;this.config=Se(p,this.configOverrides),!l&&!p&&e.flushInterval!=null&&this.configOverrides.flushIntervalMs===void 0&&(this.config={...this.config,flushIntervalMs:e.flushInterval}),!l&&!p&&e.deviceInfoCollectorTimeout!=null&&this.configOverrides.deviceInfoCollectorTimeoutMs===void 0&&(this.config={...this.config,deviceInfoCollectorTimeoutMs:e.deviceInfoCollectorTimeout}),e.apiBaseUrl!==""&&(/^https?:\/\//.test(e.apiBaseUrl)||(this.logger.critical(`Invalid apiBaseUrl: URL must start with http:// or https:// (got: "${e.apiBaseUrl}")`),this.reportTelemetry("error","invalid apiBaseUrl: missing http(s) scheme")),e.apiBaseUrl.endsWith("/")&&(this.logger.critical(`Invalid apiBaseUrl: URL must not have a trailing slash (got: "${e.apiBaseUrl}")`),this.reportTelemetry("error","invalid apiBaseUrl: trailing slash")));let u=e.apiBaseUrl+(e.apiEventPath??"/v1/observe/events")+"/"+e.projectId;this.logger.debug(`Using API endpoint: ${u}`);let d=new Te({logger:this.logger,url:u});this.sessionId=this.resolveSessionId(),this.queue=new $(this.logger,d,this.sessionId,Oi,{debug:this.options.debug,config:this.config,requestConfig:!1,outboxLockName:w(we,s),getDataPolicy:()=>this.dataPolicy},this.persistentStorage),this.telemetryReady=!0,this.logger.setTelemetrySink?.((g,E)=>this.reportTelemetry(g,E));try{this.getWindowObserver()}catch(g){this.logger.error("Failed to attach page low-event observer",g)}let c=this.pendingSelfTelemetry;this.pendingSelfTelemetry=[];for(let g of c)this.telemetry(g.level,g.message);let f=new Ee(this.logger,this.storage,r?"cookie":"localstorage",this.sessionStorage,()=>({collectorTimeoutMs:this.config.deviceInfoCollectorTimeoutMs,timing:this.config.deviceInfoTiming}),(g,E)=>this.telemetry(g,E));this.deviceCollector=f;let m=e.deviceInfoDebounceTime??3e4;this.deviceInfoManager=new xe(this.logger,f,Math.max(1,m),m),this.deviceInfoManager.start(),this.experiments=this.loadPersistedExperiments(),e.experiments&&this.setExperiments(e.experiments),this.dataPolicy=this.loadPersistedDataPolicy(),e.dataPolicy!==void 0&&this.setDataPolicy(e.dataPolicy),this.configManager?.start(g=>this.handleConfig(g))}logger;queue;sessionId;storage;sessionStorage;persistentStorage;seqLockName;config;configManager;configOverrides;deviceInfoManager;deviceCollector;eventTabId;seq=0;lastActivityWriteAt=0;experiments={};dataPolicy;telemetryReporting=!1;telemetryReady=!1;reportedTelemetryKeys=new Set;pendingSelfTelemetry=[];windowObserver;getWindowObserver(){return this.windowObserver??=new me(this.logger,(e,t)=>this.enqueueLowEvent(e,t),()=>this.lowEventFlushKeepalive())}handleConfig(e){let t=Se(e,this.configOverrides);t.sessionContinuity||=this.config.sessionContinuity,t.durableOutbox||=this.config.durableOutbox,this.config=t,this.queue.updateConfig(this.config)}getLogger(){return this.logger}applicationTag(){return this.options.applicationId?{applicationId:this.options.applicationId.toLowerCase()}:{}}setExperiment(e,t){this.setExperiments({[e]:t})}setExperiments(e){try{if(!e||typeof e!="object")return;let t=!1;for(let[i,r]of Object.entries(e)){if(!n.isValidExperimentKey(i)||!n.isValidExperimentVariant(r)){this.logger.debug(`Ignoring invalid experiment assignment "${String(i)}"`);continue}this.experiments[i]!==r&&(this.experiments[i]=r,t=!0)}t&&this.persistExperiments()}catch(t){this.logger.error("Failed to set experiments",t)}}clearExperiment(e){try{Object.prototype.hasOwnProperty.call(this.experiments,e)&&(delete this.experiments[e],this.persistExperiments())}catch(t){this.logger.error("Failed to clear experiment",t)}}clearExperiments(){try{if(Object.keys(this.experiments).length===0)return;this.experiments={},this.persistExperiments()}catch(e){this.logger.error("Failed to clear experiments",e)}}getExperiments(){return{...this.experiments}}getPersistentStorage(){return this.persistentStorage}getSdkConfig(){return Object.freeze({version:this.config.version,aap:this.config.aap,rawErrors:this.config.rawErrors})}setDataPolicy(e){try{if(!n.isValidDataPolicy(e)){this.logger.debug(`Ignoring invalid data policy code "${String(e)}"`);return}this.dataPolicy!==e&&(this.dataPolicy=e,this.persistDataPolicy())}catch(t){this.logger.error("Failed to set data policy",t)}}getDataPolicy(){return this.dataPolicy}static isValidDataPolicy(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=Li}loadPersistedDataPolicy(){try{let e=this.persistentStorage.getItem(Rt);return n.isValidDataPolicy(e)?e:void 0}catch(e){this.logger.debug("Failed to load persisted data policy",e);return}}persistDataPolicy(){try{if(this.dataPolicy===void 0)return;this.persistentStorage.setItem(Rt,this.dataPolicy)}catch(e){this.logger.debug("Failed to persist data policy",e)}}static isValidExperimentKey(e){return typeof e=="string"&&e.length>0&&e.length<=Ri&&Pi.test(e)}static isValidExperimentVariant(e){return typeof e=="string"&&e.length>0&&e.length<=Fi}loadPersistedExperiments(){try{let e=this.persistentStorage.getItem(Pt);if(!e||typeof e!="object")return{};let t={};for(let[i,r]of Object.entries(e))n.isValidExperimentKey(i)&&n.isValidExperimentVariant(r)&&(t[i]=r);return t}catch(e){return this.logger.debug("Failed to load persisted experiments",e),{}}}persistExperiments(){try{this.persistentStorage.setItem(Pt,this.experiments)}catch(e){this.logger.debug("Failed to persist experiments",e)}}resolveExperiments(e){let t={...this.experiments};if(e&&typeof e=="object")for(let[i,r]of Object.entries(e))n.isValidExperimentKey(i)&&n.isValidExperimentVariant(r)&&(t[i]=r);return Object.keys(t).length>0?t:void 0}isTrackingBlocked(){return typeof navigator>"u"?!1:Et(navigator.userAgent)}resolveSessionId(){try{if(this.config.sessionContinuity)return this.getContinuitySessionId();let e=Date.now(),t=this.readPerTabSession();if(t&&e-t.lastActiveAt<this.perTabInactivityMs(t))return this.persistPerTabSession(t.id,e),this.seq=0,t.id;let i=(0,I.v7)();return this.persistPerTabSession(i,e),this.seq=0,this.logger.debug("Created session id",i),i}catch(e){return this.logger.error("Failed to get session id",e),this.reportTelemetry("error","failed to get session id"),""}}getContinuitySessionId(){let e=Date.now(),t=this.persistentStorage.getItem(Xe);if(t?.id&&e-t.lastActiveAt<this.config.sessionInactivityMs)return this.persistContinuitySession(t.id,e),this.seq=this.persistentStorage.getItem(R)??0,t.id;if(!t?.id){let r=this.readPerTabSession();if(r&&e-r.lastActiveAt<this.config.sessionInactivityMs)return this.persistContinuitySession(r.id,e),this.persistentStorage.setItem(R,0),this.seq=0,this.logger.debug("Adopted per-tab session id as continuity session",r.id),r.id}let i=(0,I.v7)();return this.persistContinuitySession(i,e),this.persistentStorage.setItem(R,0),this.seq=0,this.logger.debug("Created continuity session id",i),i}persistContinuitySession(e,t){this.lastActivityWriteAt=t,this.persistentStorage.setItem(Xe,{id:e,lastActiveAt:t})}readPerTabSession(){let e=this.sessionStorage.getItem(Lt);if(e){if(typeof e=="string")return Dt.test(e)?{id:e,lastActiveAt:Date.now()}:void 0;if(typeof e.lastActiveAt=="number")return Dt.test(e.id)?e:void 0}}persistPerTabSession(e,t){this.lastActivityWriteAt=t;let i=this.configOverrides.sessionInactivityMs!==void 0||this.config.version?this.config.sessionInactivityMs:this.readPerTabSession()?.inactivityMs;this.sessionStorage.setItem(Lt,{id:e,lastActiveAt:t,...i===void 0?{}:{inactivityMs:i}})}perTabInactivityMs(e){return this.configOverrides.sessionInactivityMs!==void 0?this.config.sessionInactivityMs:e.inactivityMs??this.config.sessionInactivityMs}nextSeq(){if(!this.config.sessionContinuity){let i=Date.now();return this.sessionId&&i-this.lastActivityWriteAt>=At&&this.persistPerTabSession(this.sessionId,i),this.seq++}let e=()=>{let i=Date.now(),r=this.persistentStorage.getItem(Xe),o=!1;if(!r?.id&&this.sessionId)this.persistContinuitySession(this.sessionId,i);else if(r?.id)i-this.lastActivityWriteAt>=At&&this.persistContinuitySession(r.id,i),r.id!==this.sessionId&&(this.sessionId=r.id,this.queue.setSessionId(r.id),o=!0);else{let l=(0,I.v7)();this.persistContinuitySession(l,i),this.persistentStorage.setItem(R,0),this.sessionId=l,this.queue.setSessionId(l),this.seq=0,o=!0}let s=this.persistentStorage.getItem(R);o&&(this.seq=typeof s=="number"?s:0);let a=typeof s=="number"&&s>this.seq?s:this.seq;return this.seq=a+1,this.persistentStorage.setItem(R,this.seq),a},t=this.config.seqLockTimeoutMs;return t===0||typeof navigator>"u"||!navigator.locks?.request?e():be(this.seqLockName,e,{timeoutMs:t,onTimeout:()=>{this.logger.warn(`Sequence Web Lock acquisition timed out after ${t}ms; using fallback`),this.reportTelemetry("info",`seq web lock timeout; using fallback, ${t}ms`)}})}resolveTrackingSourcePath(){if(typeof window>"u")return;let e=lt(window.location.search,this.config.sourcePathQuery,this.config.sourcePathQueryAllow);return`${window.location.pathname}${e}`}resolveEventTabId(){return this.eventTabId===void 0&&(this.eventTabId=this.deviceCollector.getTabId()),this.eventTabId}trackSubflowStarted(e,t,i,r){let o={subflowType:e,...t};this.track("subflow_started",o,i?.userReference,void 0,void 0,i?.explicitTimestamp,i?.experiments,{id:r,subflowStartEventId:i?.subflowStartEventId,sessionId:i?.captureSessionId,initiator:i?.initiator})}trackSubflowTrigger(e,t,i){let r={subflowType:e,...t};this.track("subflow_trigger",r,i?.userReference,void 0,void 0,i?.explicitTimestamp,i?.experiments,{subflowStartEventId:i?.subflowStartEventId,sessionId:i?.captureSessionId,initiator:i?.initiator})}trackSubflowStepStarted(e,t,i,r,o){let s={subflowType:e,stepName:t,stepData:i,ignoreAsInteraction:o};this.track("subflow_step_started",s,r?.userReference,void 0,void 0,r?.explicitTimestamp,r?.experiments,{subflowStartEventId:r?.subflowStartEventId,sessionId:r?.captureSessionId,initiator:r?.initiator})}trackSubflowStepFinished(e,t,i,r){let o={subflowType:e,stepName:t,stepData:i};this.track("subflow_step_finished",o,r?.userReference,void 0,void 0,r?.explicitTimestamp,r?.experiments,{subflowStartEventId:r?.subflowStartEventId,sessionId:r?.captureSessionId,initiator:r?.initiator})}trackSubflowStepError(e,t,i,r){let o={subflowType:e,stepName:t,stepData:i};this.track("subflow_step_error",o,r?.userReference,void 0,void 0,r?.explicitTimestamp,r?.experiments,{subflowStartEventId:r?.subflowStartEventId,sessionId:r?.captureSessionId,initiator:r?.initiator})}trackSubflowError(e,t,i){let r={subflowType:e,stepData:t};this.track("subflow_error",r,i?.userReference,void 0,void 0,i?.explicitTimestamp,i?.experiments,{subflowStartEventId:i?.subflowStartEventId,sessionId:i?.captureSessionId,initiator:i?.initiator})}async track(e,t,i,r,o,s,a,l){try{if(this.isTrackingBlocked()){this.logger.debug(`Skipping event "${e}" for blocked user agent.`);return}(e==="flow_finished"||e==="flow_auto_finished"||e==="flow_reset")&&this.windowObserver?.flushInputs();let p=s??Date.now(),u=l?.id??(0,I.v7)(),d=l?.sessionId??this.sessionId,c=this.nextSeq(),f=typeof c=="number"?c:await c,m=this.resolveTrackingSourcePath(),g={type:"predefined",name:e,id:u,timestamp:p,seq:f,data:t,user:i,contexts:o,tags:r,experiments:this.resolveExperiments(a),meta:{captureVersion:1,pageId:ye(),initiator:l?.initiator,trackingSourcePath:m??"",subflowStartEventId:l?.subflowStartEventId,tabId:this.resolveEventTabId()}},E=this.deviceInfoManager.getForEvent();E&&(g.deviceInfo=E),this.logger.debug(`Track: ${e}`,JSON.stringify(g,null,2)),this.queue.enqueue(g,d)}catch(p){this.logger.error(`Failed to process event "${e}" before enqueue`,p),this.reportTelemetry("error",`failed to process event "${e}" before enqueue`)}}flowStarted(e,t,i,r){try{let o=(0,I.v7)(),s=this.sessionId,a={...this.options.defaultTags,...this.applicationTag(),...t};return this.track("flow_started",e,void 0,a,r,void 0,i,{id:o,sessionId:s}),this.flowHandle(o,s)}catch(o){return this.logger.warn("Failed to start flow",o),{enrich:async()=>{}}}}flowDecided(e,t,i){this.track("flow_decided",e,void 0,t,void 0,void 0,i)}conversion(e,t,i){let{userId:r,identifier:o,crossEnvironmentTransactionID:s,...a}=e,l={userId:r,identifier:o,crossEnvironmentTransactionID:s},p={...this.options.defaultTags,...this.applicationTag(),...t};this.track("conversion",a,l,p,void 0,void 0,i)}flowFinished(e,t,i){try{let{userId:r,identifier:o,...s}=e,a={userId:r,identifier:o},l=(0,I.v7)(),p=this.sessionId;return this.track("flow_finished",s,a,t,void 0,void 0,i,{id:l,sessionId:p}),this.flowHandle(l,p)}catch(r){return this.logger.warn("Failed to finish flow",r),{enrich:async()=>{}}}}flowHandle(e,t){return{enrich:async i=>{try{await this.track("flow_enriched",{targetEventId:e},{...i},void 0,void 0,void 0,void 0,{sessionId:t})}catch(r){this.logger.warn("Failed to enrich flow",r)}}}}flowReset(e,t,i){this.track("flow_reset",e,void 0,t,void 0,void 0,i)}flowAutoFinished(e,t,i){let{userId:r,identifier:o,...s}=e,a={userId:r,identifier:o};this.track("flow_auto_finished",s,a,t,void 0,void 0,i)}setUser(e){this.track("flow_enriched",{match:{flowType:"*",at:"during"},expFol:!0},{...e})}setFlowTags(e,t){try{if(!e||typeof e!="object"){this.logger.warn("setFlowTags: ignoring non-object tags");return}let i={};for(let[o,s]of Object.entries(e)){if(o===""||typeof s!="string"){this.logger.warn(`setFlowTags: ignoring invalid tag "${o}"`);continue}i[o]=s}if(Object.keys(i).length===0)return;let r={match:{flowType:t?.flowType??"*",at:"during"}};t?.expandToChildren!==void 0&&(r.expCh=t.expandToChildren),t?.expandToFollowing!==void 0&&(r.expFol=t.expandToFollowing),this.track("flow_enriched",r,void 0,i)}catch(i){this.logger.warn("Failed to set flow tags",i)}}authMethodsDecisionStarted(e,t,i,r){this.track("auth_method_decision_started",e,void 0,t,void 0,r?.explicitTimestamp,i)}authMethodsDecisionFinished(e,t,i){this.track("auth_method_decision_finished",e,void 0,t,void 0,void 0,i)}authDecisionStarted(e,t,i){this.track("auth_decision_started",e,void 0,t,void 0,void 0,i)}authDecisionFinished(e,t,i){this.track("auth_decision_finished",e,void 0,t,void 0,void 0,i)}enqueueLowEvent(e,t){try{if(this.isTrackingBlocked()){this.logger.debug(`Skipping low event "${e.lowType}" for blocked user agent.`);return}this.queue.enqueueLow({...e,captureSeq:e.captureSeq??x(),captureVersion:1,pageId:e.pageId??ye()},t)}catch(i){this.logger.error(`Failed to process low event "${e.lowType}" before enqueue`,i)}}telemetry(e,t){try{if(this.isTrackingBlocked()){this.logger.debug("Skipping telemetry for blocked user agent.");return}let i=typeof t=="string"?t:String(t);if(i.length===0)return;let r={id:(0,I.v7)(),level:e,message:i.length>Ft?i.slice(0,Ft):i,ts:Date.now()};this.queue.enqueueTelemetry(r)}catch(i){this.logger.error("Failed to process telemetry before enqueue",i)}}logInfo(e){this.telemetry("info",e)}logError(e){this.telemetry("error",e)}reportTelemetry(e,t){if(!this.telemetryReporting){this.telemetryReporting=!0;try{if(this.reportedTelemetryKeys.has(t)||this.reportedTelemetryKeys.size>=Ai)return;if(this.reportedTelemetryKeys.add(t),!this.telemetryReady){this.pendingSelfTelemetry.push({level:e,message:t});return}this.telemetry(e,t)}catch{}finally{this.telemetryReporting=!1}}}flushKeepalive(e="manual"){try{this.queue.flushKeepalive(e)}catch(t){this.logger.error("Failed to flush queue keepalive",t)}}lowEventFlushKeepalive(){this.config.tlf&&this.flushKeepalive("low-event-teardown")}passkeyLoginFullOperation(e){return new Y(this,e)}passkeyEnrollmentFullOperation(e){return new te(this,e)}passwordLoginFullOperation(e){return new ie(this,e)}passwordEnrollmentFullOperation(e){return new re(this,e)}emailLinkOperationFull(e){return new Z(this,e)}continueEmailLinkOperation(e){return new ee(this,e)}emailOtpOperationFull(e){return new J(this,e)}smsOtpOperationFull(e){return new X(this,e)}totpOperationFull(e){return new ae(this,e)}provideIdentifierOperationFull(e){return new ne(this,e)}provideDataOperationFull(e){return new ce(this,e)}socialLoginOperationFull(e){return new oe(this,e)}ssoLoginOperationFull(e){return new se(this,e)}appConfirmationOperationFull(e){return new le(this,e)}keySigningOperationFull(e){return new K(this,e)}keyRegistrationOperationFull(e){return new V(this,e)}captchaOperationFull(e){return new pe(this,e)}trustedDeviceCheckOperationFull(e){return new de(this,e)}trustedDeviceEnrollmentOperationFull(e){return new ue(this,e)}async destroy(){if(this.configManager?.destroy(),this.windowObserver?.destroy(),this.deviceInfoManager.destroy(),this.config.td)try{await this.queue.flush("destroy")}catch(e){this.logger.error("Failed to flush queue during destroy",e)}this.queue.destroy()}getSessionId(){if(!this.sessionId){let e=this.resolveSessionId();e&&(this.sessionId=e,this.queue.setSessionId(e))}return this.sessionId||void 0}resetSession(){let e=(0,I.v7)();return this.config.sessionContinuity?(this.persistContinuitySession(e,Date.now()),this.persistentStorage.setItem(R,0)):this.persistPerTabSession(e,Date.now()),this.sessionId=e,this.seq=0,this.queue.setSessionId(e),this.logger.debug(`Session reset: ${e}`),e}};var _i={creationOptions:["/user/name","/user/displayName"],creationResponse:["/clientExtensionResults/prf/results"],requestOptions:[],assertionResponse:["/response/signature","/clientExtensionResults/prf/results"]};function _t(n){return Ae(n,"creationOptions")}function Mt(n){return Ae(n,"creationResponse")}function Ht(n){return Ae(n,"requestOptions")}function Nt(n){return Ae(n,"assertionResponse")}function Ae(n,e){try{let t=typeof n=="string"?JSON.parse(n):n;if(!Mi(t))return;let i=new Set(_i[e]),r=new Set,o=(s,a,l=0)=>{if(!i.has(a)){if(s===null||typeof s=="string"||typeof s=="boolean")return s;if(typeof s=="number")return Number.isFinite(s)?s:null;if(typeof s=="object"){if(s instanceof ArrayBuffer||ArrayBuffer.isView(s))return Hi(s);if(l>64||r.has(s))throw new TypeError("Invalid telemetry payload");r.add(s);try{if(Array.isArray(s))return s.map((c,f)=>o(c,`${a}/${f}`,l+1));let p=Object.create(null);for(let c in s){let f=`${a}/${c.replace(/~/g,"~0").replace(/\//g,"~1")}`;if(i.has(f)||c==="toJSON")continue;let m=o(s[c],f,l+1);m!==void 0&&(p[c]=m)}let u=s,d=(c,f)=>{if(p[f]!==void 0||typeof u[c]!="function")return;let m=`${a}/${f}`,g=o(Reflect.apply(u[c],s,[]),m,l+1);g!==void 0&&(p[f]=g)};return a===""&&(e==="creationResponse"||e==="assertionResponse")&&d("getClientExtensionResults","clientExtensionResults"),a==="/response"&&e==="creationResponse"&&(d("getTransports","transports"),d("getAuthenticatorData","authenticatorData"),d("getPublicKey","publicKey"),d("getPublicKeyAlgorithm","publicKeyAlgorithm")),p}finally{r.delete(s)}}}};return JSON.stringify(o(t,""))}catch{return}}function Mi(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)&&!(n instanceof ArrayBuffer)&&!ArrayBuffer.isView(n)}function Hi(n){let e=n instanceof ArrayBuffer?new Uint8Array(n):new Uint8Array(n.buffer,n.byteOffset,n.byteLength),t="";for(let i of e)t+=String.fromCharCode(i);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}var T;function Ni(n){let e=new fe(n);return T=e,e}function Ui(){return T}function Bi(){return T?.resetSession()}function qi(){return T?.getSessionId()}function Ki(n){T?.setUser(n)}function Vi(n,e){T?.setFlowTags(n,e)}function $i(n,e){T?.setExperiment(n,e)}function Gi(n){T?.setExperiments(n)}function zi(n){T?.clearExperiment(n)}function Wi(){T?.clearExperiments()}function Qi(){return T?.getExperiments()??{}}function ji(n,e){T?.telemetry(n,e)}function Yi(n){T?.logInfo(n)}function Ji(n){T?.logError(n)}async function Xi(){T&&(await T.destroy(),T=void 0)}0&&(module.exports={AppConfirmationOperationFull,AuthEventName,CEREMONY_LOW_EVENT_TAIL_MS,CONFIG_BOUNDS,CONFIG_REQUEST_HEADER,CONFIG_STORAGE_KEY,CaptchaOperationFull,CookieStorage,CorbadoTracker,DEFAULT_DEVICE_INFO_COLLECTOR_TIMEOUT_MS,DEFAULT_FLUSH_INTERVAL_MS,DEFAULT_MAX_ENTRIES,DEFAULT_MAX_SERIALIZED_LENGTH,DEFAULT_RELIABILITY_CONFIG,DEFAULT_SEQ_LOCK_TIMEOUT_MS,DEFAULT_SESSION_INACTIVITY_MS,EmailLinkContinuationOperation,EmailLinkOperationFull,EmailOtpOperationFull,EventStore,KeyRegistrationOperationFull,KeySigningOperationFull,LocalStorage,NamespacedStorage,OUTBOX_LOCK_NAME,OUTBOX_STORAGE_KEY,OperationFull,OperationFullProvideIdentifierWithCUI,PasskeyEnrollmentOperationFull,PasskeyLoginOperationFull,PasswordEnrollmentOperationFull,PasswordLoginOperationFull,ProvideDataOperationFull,RAW_ERROR_BOUNDS,RequestQueue,SDK_NAME,SDK_VERSION,SessionStorage,SmsOtpOperationFull,SocialLoginOperationFull,SsoLoginOperationFull,TotpOperationFull,TrustedDeviceCheckOperationFull,TrustedDeviceEnrollmentOperationFull,cacheConfig,clearExperiment,clearExperiments,createLogger,destroy,getExperiments,getSessionId,getTracker,init,loadCachedConfig,logError,logInfo,namespacedKey,parseReliabilityConfig,resetSession,resolveRawErrorLimits,resolveReliabilityConfig,sanitizeAssertionResponse,sanitizeCreationOptions,sanitizeCreationResponse,sanitizeRequestOptions,serializeRawError,setExperiment,setExperiments,setFlowTags,setUser,telemetry});
|
|
4
|
+
${s}`,t)}function Zt(n,e,t){let{limits:i}=t,r=_(n),o=d=>ge(d,e-1,t);if(r==="Date")return Number.isNaN(n.getTime())?"[Invalid Date]":n.toISOString();if(r==="RegExp")return C(String(n),i.maxValueLength);if(r==="ArrayBuffer")return`[ArrayBuffer(${n.byteLength})]`;if(ArrayBuffer.isView(n))return`[${r}(${n.byteLength})]`;if(r==="Map"||r==="Set"){let d=n,c=[];for(let f of d){if(c.length===i.maxBreadth)break;c.push(o(f))}return d.size>c.length&&c.push(`[+${d.size-c.length} more]`),c}if(r==="Promise"||r==="WeakMap"||r==="WeakSet"||r==="Window")return`[${r}]`;if(typeof Node<"u"&&n instanceof Node)return`[${r}]`;if(Array.isArray(n)){let d=n.slice(0,i.maxBreadth).map(o);return n.length>i.maxBreadth&&d.push(`[+${n.length-i.maxBreadth} more]`),d}if(typeof Response<"u"&&n instanceof Response)return{status:o(n.status),statusText:o(n.statusText),url:o(n.url),redirected:o(n.redirected)};if(typeof Event<"u"&&n instanceof Event){let d=n,c={type:o(d.type)};for(let f of["message","filename","lineno","colno"])f in d&&(c[f]=o(d[f]));return"error"in d&&d.error!=null&&(c.error=o(d.error)),c}let s=Object.create(null),a=n,l=Jt(n);if(l){for(let c of Qt){if(c==="stack"&&!i.stack)continue;let f=a[c];if(!(f==null||typeof f=="function")){if(c==="stack"){i.stack&&typeof f=="string"&&(s.stack=q(it(f,i.maxStackFrames,i.maxValueLength),t));continue}s[c]=o(f)}}let d=a.cause;d!=null&&typeof d!="function"&&(s.cause=ei(d,e-1,t))}let p=0,u=Object.keys(a);for(let d of u){if(d in s||d==="stack"&&!i.stack||l&&d==="cause")continue;if(++p>i.maxBreadth){s["\u2026"]=`[+${u.length-i.maxBreadth} keys]`;break}let c=a[d];typeof c!="function"&&(s[q(d,t)]=d==="stack"&&typeof c=="string"?q(it(c,i.maxStackFrames,i.maxValueLength),t):o(c))}return!l&&r!=="Object"&&p===0?`[${r}]`:s}function ei(n,e,t){if(typeof n!="object"||n===null)return ge(n,e,t);if(t.causeBudget<=0)return q(`[${_(n)}]`,t);t.causeBudget--;try{return ge(n,e,t)}finally{t.causeBudget++}}var st=1500,h=class{constructor(e,t){this.tracker=e;this.operationName=t}startReference;captureSpecType;captureSessionId;lowFlushers=[];lowPrefillCapturers=[];lowEventSink(e,t){return{reserveCaptureSeq:x,enqueueLowEvent:i=>this.tracker.enqueueLowEvent({...i,captureSeq:i.captureSeq??x(),subflowStartEventId:this.startReference,sourceKind:e,fieldRole:t,initiator:i.initiator??(t?`input-${t}`:"unknown")},this.captureSessionId),flushKeepalive:()=>this.tracker.lowEventFlushKeepalive(),registerInputs:(i,r)=>this.tracker.getWindowObserver().registerInputs(i,()=>({subflowStartEventId:this.startReference,fieldRole:t,initiator:t?`input-${t}`:"unknown",sessionId:this.captureSessionId}),r),beginCeremony:i=>this.tracker.getWindowObserver().beginCeremony({subflowStartEventId:this.startReference,initiator:i??"unknown",sessionId:this.captureSessionId})}}createLowCollector(e){try{let t=e();return this.lowPrefillCapturers.push(i=>t.capturePrefill(i)),t}catch(t){this.tracker.getLogger().error("Failed to attach low-event collector",t);return}}registerLowFlusher(e){this.lowFlushers.push(e)}captureOptions(e,t=this.startReference,i=this.captureSessionId,r){if(!t&&!r)return e;let o={};return t&&(o.subflowStartEventId=e?.subflowStartEventId??t,o.captureSessionId=e?.captureSessionId??i),r&&(o.initiator=e?.initiator??r),Object.defineProperties({},{...Object.getOwnPropertyDescriptors(e??{}),...Object.getOwnPropertyDescriptors(o)})}get captureReference(){return this.startReference}get captureSession(){return this.captureSessionId}adoptCapture(e,t,i){this.startReference=e,this.captureSessionId=t,this.captureSpecType=i}subflowStart(e,t){try{for(let i of this.lowFlushers)try{i()}catch(r){this.tracker.getLogger().error("Failed to flush previous low-event context",r)}this.captureSpecType=e?.explicitSpecType,this.startReference=(0,ot.v7)(),this.captureSessionId=this.tracker.getSessionId(),this.tracker.trackSubflowStarted(this.operationName,e,this.captureOptions(t),this.startReference),this.captureInputPrefills(!0)}catch(i){this.tracker.getLogger().error("Failed to start low-event capture context",i)}}capturePrefill(){this.captureInputPrefills(!1)}captureInputPrefills(e){for(let t of this.lowPrefillCapturers)try{t(e)}catch(i){this.tracker.getLogger().error("Failed to capture input prefill",i)}}trigger(e,t){this.tracker.trackSubflowTrigger(this.operationName,e,this.captureOptions(t))}customStep(e){return this.defineStep(e)}subflowStepStarted(e,t,i,r){this.captureSpecType=t?.explicitSpecType??this.captureSpecType,this.tracker.trackSubflowStepStarted(this.operationName,e,t,this.captureOptions(i),r)}subflowStepFinished(e,t,i){(!i?.subflowStartEventId||i.subflowStartEventId===this.startReference)&&(this.captureSpecType=t?.explicitSpecType??this.captureSpecType),this.tracker.trackSubflowStepFinished(this.operationName,e,t,this.captureOptions(i))}subflowStepError(e,t,i){let r=t;try{let o=this.tracker.getSdkConfig().rawErrors?i?.rawError:void 0;o!==void 0&&(r={...t,rawError:_e(o,i?.rawErrorLimits)})}catch{}this.tracker.trackSubflowStepError(this.operationName,e,r,this.captureOptions(i))}withWindowLowEvents(e,t){let i,r=s=>{s?.subflowStartEventId&&s.subflowStartEventId!==i||t.scheduleDisarm(st)},o=e;return{...e,start:(s,a)=>{i=a?.subflowStartEventId??this.startReference;let l=s?.explicitSpecType??this.captureSpecType,p=a?.initiator??tt(this.operationName,l);t.arm(p,l==="passkey-cui"),o.start(s,p?{...a,initiator:p}:a)},finished:(s,a)=>{o.finished(s,a),r(a)},error:(s,a)=>{o.error(s,a),r(a)},errorTyped:(s,a)=>{o.errorTyped?.(s,a),r(a)}}}defineStep(e,t){let i,r,o,s=l=>this.captureOptions(l,i,r,o);return{start:(l,p)=>{i=this.startReference,r=this.captureSessionId,o=p?.initiator,this.subflowStepStarted(e,l,s(p),t)},finished:(l,p)=>{this.subflowStepFinished(e,l,s(p))},error:(l,p)=>{this.subflowStepError(e,{error:F(l)},s(p))},errorTyped:(l,p)=>{this.subflowStepError(e,l,s(p))}}}};function at(n,e){if(e.explicitSpecType!==void 0)try{n.getLogger().warn("Unsupported key operation spec type; omitting it")}catch{}}var K=class extends h{prepare;sign;constructor(e,t={}){super(e,"key-signing"),this.prepare=this.defineStep("prepare"),this.sign=this.defineStep("sign"),this.subflowStart({actor:"system",explicitSpecType:at(e,t)})}},V=class extends h{prepare;postResponse;constructor(e,t={}){super(e,"key-registration"),this.prepare=this.defineStep("prepare"),this.postResponse=this.defineStep("post-response"),this.subflowStart({actor:"system",explicitSpecType:at(e,t)})}};function ti(n){try{return decodeURIComponent(n.replace(/\+/g," "))}catch{return n}}function ii(n,e){let t=n.toLowerCase();return e.some(i=>{let r=i.toLowerCase();return r.endsWith("*")?t.startsWith(r.slice(0,-1)):t===r})}function lt(n,e,t){return e!=="allowlist"||n===""||n==="?"?n:`?${(n.startsWith("?")?n.slice(1):n).split("&").map(o=>{let s=o.indexOf("=");if(s===-1)return o;let a=o.slice(0,s);return o.slice(s+1)===""||ii(ti(a),t)?o:`${a}=*`}).join("&")}`}var pt=require("uuid");var Me=(n,e,t)=>{let i=!1,r,o=null,s=null,a=()=>{s!==null&&(window.clearTimeout(s),s=null);let p=o;i=!1,o=null,p!==null&&n({...r===void 0?{}:{captureSeq:r},lowType:e,ts:p,durationMs:Date.now()-p})};return{extend:()=>{if(!i){let p=t?.();i=!0,o=Date.now(),r=p}s!==null&&window.clearTimeout(s),s=window.setTimeout(a,150)},flush:a}};var ri,ye=()=>ri??=(0,pt.v7)(),me=class{constructor(e,t,i){this.logger=e;this.enqueue=t;this.flushKeepalive=i;typeof window>"u"||typeof document>"u"||(this.listen(window,"blur",()=>{this.flushInputs(),this.bracket=this.context(),this.emit({lowType:"window-blur",ts:Date.now()},this.bracket)}),this.listen(window,"focus",()=>{this.flushInputs(),this.emit({lowType:"window-focus",ts:Date.now()},this.bracket??this.context()),this.bracket=void 0}),this.listen(document,"visibilitychange",()=>{this.flushInputs(),this.emit({lowType:`document-visibilitychange-${document.visibilityState==="hidden"?"hidden":"visible"}`,ts:Date.now()})}),this.listen(document,"focusout",r=>{let o=this.findInput(r.target);this.lastBlur=o&&!r.relatedTarget&&Date.now()-this.unrelatedPointerAt>250?{registration:o,ts:Date.now()}:void 0}),this.listen(document,"focusin",()=>{this.lastBlur=void 0}),this.listen(document,"pointerdown",r=>{this.findInput(r.target)?this.unrelatedPointerAt=-1/0:(this.lastBlur=void 0,this.unrelatedPointerAt=Date.now())}),window.visualViewport&&(this.listen(window.visualViewport,"resize",()=>this.extendViewport("resize")),this.listen(window.visualViewport,"scroll",()=>this.extendViewport("scroll"))),this.listen(window,"pagehide",()=>{this.flushInputs(),this.resize.flush(),this.scroll.flush(),this.flushKeepalive()}),this.observeNavigation())}inputs=new Set;ceremonies=new Set;removers=[];lastBlur;bracket;unrelatedPointerAt=-1/0;destroyed=!1;viewportContext={};resize=Me(e=>this.emit(e,this.viewportContext.resize),"visualviewport-resize",x);scroll=Me(e=>this.emit(e,this.viewportContext.scroll),"visualviewport-scroll",x);registerInputs(e,t,i){if(this.destroyed)return()=>{};let r={fields:e,context:t,flush:i};return this.inputs.add(r),()=>{this.inputs.delete(r),this.lastBlur?.registration===r&&(this.lastBlur=void 0)}}beginCeremony(e){let t={context:e,settled:!1};this.destroyed||(this.flushInputs(),this.ceremonies.add(t));let i=()=>{t.timer&&clearTimeout(t.timer),this.ceremonies.delete(t),this.bracket===t.context&&(this.bracket=void 0)};return{settle:r=>{t.settled=!0,t.timer&&clearTimeout(t.timer),t.timer=setTimeout(i,r)},destroy:i}}context(){let e=[...this.ceremonies].filter(r=>!r.settled);if(e.length===1)return e[0].context;if(e.length>1)return;let t=this.findInput(document.activeElement);if(t)return t.context();let i=this.lastBlur;if(i&&Date.now()-i.ts<=250&&(document.activeElement===document.body||!document.activeElement))return i.registration.context()}findInput(e){return[...this.inputs].find(t=>t.fields.some(i=>i===e))}flushInputs(){for(let e of this.inputs)try{e.flush()}catch(t){this.logger.error("Failed to flush window input context",t)}}emit(e,t){if(this.destroyed)return;let{sessionId:i,...r}=t??{};this.enqueue({...e,...r,captureSeq:e.captureSeq??x(),sourceKind:"window",captureVersion:1,pageId:ye()},i)}listen(e,t,i){let r=o=>{try{i(o)}catch(s){this.logger.error(`Failed to observe window ${t}`,s)}};e.addEventListener(t,r),this.removers.push(()=>e.removeEventListener(t,r))}extendViewport(e){let t=this.context(),i=this.viewportContext[e];(i?.subflowStartEventId!==t?.subflowStartEventId||i?.fieldRole!==t?.fieldRole||i?.sessionId!==t?.sessionId)&&this[e].flush(),this.viewportContext[e]=t,this[e].extend()}observeNavigation(){let e=window.navigation;e&&this.listen(e,"currententrychange",t=>{let i=t,r=i.from?.index,o=e.currentEntry?.index;i.navigationType==="traverse"&&typeof r=="number"&&typeof o=="number"&&r>=0&&o>=0&&o<r&&(this.flushInputs(),this.emit({lowType:"window-navigate-back",ts:Date.now()}))})}destroy(){if(!this.destroyed){this.flushInputs(),this.resize.flush(),this.scroll.flush(),this.destroyed=!0;for(let e of this.removers)e();for(let e of this.ceremonies)e.timer&&clearTimeout(e.timer);this.ceremonies.clear(),this.inputs.clear()}}};var ve=(v=>(v.FlowStarted="flow_started",v.FlowDecided="flow_decided",v.FlowFinished="flow_finished",v.FlowReset="flow_reset",v.AuthMethodDecisionStarted="auth_method_decision_started",v.AuthMethodDecisionFinished="auth_method_decision_finished",v.FlowAutoFinished="flow_auto_finished",v.AuthDecisionStarted="auth_decision_started",v.AuthDecisionFinished="auth_decision_finished",v.SubflowStepStarted="subflow_step_started",v.SubflowStepFinished="subflow_step_finished",v.SubflowStepError="subflow_step_error",v.SubflowTrigger="subflow_trigger",v.SubflowError="subflow_error",v.SubflowStarted="subflow_started",v.SubflowFinished="subflow_finished",v.FlowEnriched="flow_enriched",v.Conversion="conversion",v))(ve||{});var He="cbo_sdk_config",Ne="X-Corbado-Observe-Config",vr=500,Sr=50,ut=1e3,S={flushIntervalMs:{min:100,max:6e4},retryMaxAttempts:{min:1,max:10},retryDelayMs:{min:50,max:12e4},sessionInactivityMs:{min:6e4,max:864e5},seqLockTimeoutMs:{min:0,max:250},deviceInfoCollectorTimeoutMs:{min:10,max:1e4},flushOnFlowTypeFinished:{maxEntries:20,maxNameLength:100},sourcePathQueryAllow:{maxEntries:50,maxKeyLength:64}},ct=1800*1e3,y={version:"",flushIntervalMs:500,durableOutbox:!1,durableLowOutbox:!1,beaconKeepalive:!1,sessionContinuity:!1,sessionInactivityMs:ct,seqLockTimeoutMs:50,tvc:!0,tph:!0,td:!0,tlf:!0,telemetry:!0,flushOnTelemetry:!1,flushOnFlowTypeFinished:[],deviceInfoCollectorTimeoutMs:1e3,deviceInfoTiming:!1,rawErrors:!0,retry:{maxAttempts:1,baseDelayMs:0,maxDelayMs:0},aap:"",sourcePathQuery:"allowlist",sourcePathQueryAllow:[]};function O(n,e,t){return Math.min(Math.max(n,e),t)}function L(n,e){return typeof n=="number"&&Number.isFinite(n)?n:e}function M(n,e){return typeof n=="boolean"?n:e}function dt(n,e){return typeof n=="string"?n:e}function ni(n){return Array.isArray(n)?n.filter(e=>typeof e=="string"&&e.length>0&&e.length<=S.flushOnFlowTypeFinished.maxNameLength).slice(0,S.flushOnFlowTypeFinished.maxEntries):[]}function oi(n){return typeof n=="string"&&n.trim().toLowerCase()==="all"?"all":"allowlist"}function si(n){return Array.isArray(n)?n.filter(e=>typeof e=="string").map(e=>e.trim()).filter(e=>e.length>0&&e.length<=S.sourcePathQueryAllow.maxKeyLength).slice(0,S.sourcePathQueryAllow.maxEntries):[]}function H(n){if(!n||typeof n!="object")return null;let e=n;return typeof e.version!="string"||e.version===""?null:ft(e)}function ft(n){let e=n.retry&&typeof n.retry=="object"?n.retry:{},t=O(L(e.baseDelayMs,y.retry.baseDelayMs),S.retryDelayMs.min,S.retryDelayMs.max);return{version:dt(n.version,""),flushIntervalMs:O(L(n.flushIntervalMs,y.flushIntervalMs),S.flushIntervalMs.min,S.flushIntervalMs.max),durableOutbox:n.durableOutbox===!0,durableLowOutbox:n.durableLowOutbox===!0,beaconKeepalive:n.beaconKeepalive===!0,sessionContinuity:n.sessionContinuity===!0,sessionInactivityMs:O(L(n.sessionInactivityMs,y.sessionInactivityMs),S.sessionInactivityMs.min,S.sessionInactivityMs.max),seqLockTimeoutMs:O(L(n.seqLockTimeoutMs,y.seqLockTimeoutMs),S.seqLockTimeoutMs.min,S.seqLockTimeoutMs.max),tvc:M(n.tvc,y.tvc),tph:M(n.tph,y.tph),td:M(n.td,y.td),tlf:M(n.tlf,y.tlf),telemetry:M(n.telemetry,y.telemetry),flushOnTelemetry:n.flushOnTelemetry===!0,flushOnFlowTypeFinished:ni(n.flushOnFlowTypeFinished),deviceInfoCollectorTimeoutMs:O(L(n.deviceInfoCollectorTimeoutMs,y.deviceInfoCollectorTimeoutMs),S.deviceInfoCollectorTimeoutMs.min,S.deviceInfoCollectorTimeoutMs.max),deviceInfoTiming:n.deviceInfoTiming===!0,rawErrors:M(n.rawErrors,y.rawErrors),aap:dt(n.aap,""),sourcePathQuery:oi(n.sourcePathQuery),sourcePathQueryAllow:si(n.sourcePathQueryAllow),retry:{maxAttempts:O(L(e.maxAttempts,y.retry.maxAttempts),S.retryMaxAttempts.min,S.retryMaxAttempts.max),baseDelayMs:t,maxDelayMs:O(L(e.maxDelayMs,y.retry.maxDelayMs),t,S.retryDelayMs.max)}}}function Se(n,e={}){let t=n??y,i=Object.fromEntries(Object.entries(e).filter(([,s])=>s!==void 0)),r=Object.fromEntries(Object.entries(e.retry??{}).filter(([,s])=>s!==void 0)),o=ft({...t,...i,retry:{...t.retry,...r}});return o.retry={...t.retry,...Object.fromEntries(Object.keys(r).map(s=>[s,o.retry[s]]))},o.retry.maxDelayMs=Math.max(o.retry.baseDelayMs,o.retry.maxDelayMs),o}function Ue(n){return H(n.getItem(He))}function Be(n,e){n.setItem(He,e)}var ai=6e4,li=6e4,Te=class{constructor(e){this.options=e}async send(e,t){try{e.meta={...e.meta,sent:Date.now(),transport:"fetch"};let i=JSON.stringify(e),r=typeof AbortController<"u"?new AbortController:void 0,o=r?setTimeout(()=>r.abort(),li):void 0;try{let s={method:"POST",headers:{"Content-Type":"application/json",...this.options.headers,...t},body:i,keepalive:new Blob([i]).size<=ai,...r?{signal:r.signal}:{}},a=await fetch(this.options.url,s),l={statusCode:a.status,headers:{"retry-after":a.headers.get("Retry-After")}};if(a.headers.get("X-Corbado-Observe-Accepted")==="1"&&(l.deliveryAccepted=!0),a.status===200)try{let p=H(await a.json());p&&(l.config=p)}catch(p){this.options.logger.error("Failed to parse SDK config response",p),this.options.logger.reportTelemetry?.("error","failed to parse SDK config response")}return l}finally{o&&clearTimeout(o)}}catch(i){return this.options.logger.error("Failed to send event",i),{}}}sendBeacon(e){try{if(this.options.logger.debug(`Sending ${e.events.length} events via beacon`),typeof navigator?.sendBeacon!="function")return!1;e.meta={...e.meta,sent:Date.now(),transport:"beacon"};let t=new Blob([JSON.stringify(e)],{type:"text/plain"});return navigator.sendBeacon(this.options.url,t)}catch(t){return this.options.logger.error("Failed to send event via beacon",t),!1}}flush(e){return Promise.resolve(!0)}};var yt=require("uuid");function be(n,e,t={}){let i=typeof navigator<"u"?navigator.locks:void 0;if(i?.request){let r=t.timeoutMs,o=r!==void 0&&typeof AbortController<"u"?new AbortController:null;if(r!==void 0&&!o)return Promise.resolve().then(e);try{let s=!1,a,l=()=>{a!==void 0&&(clearTimeout(a),a=void 0)},p=()=>(s=!0,l(),e()),u=o?i.request(n,{signal:o.signal},p):i.request(n,p);return o&&r!==void 0&&!s&&(a=setTimeout(()=>{a=void 0,o.abort();try{t.onTimeout?.()}catch{}},r)),u.catch(d=>{if(s)throw d;return e()}).finally(l)}catch{}}try{return Promise.resolve(e())}catch(r){return Promise.reject(r)}}var ht="cbo_outbox",we="cbo_outbox",gt=500,mt=512*1024;function pi(n){if(!n||typeof n!="object")return!1;let e=n;return typeof e.id=="string"&&e.id!==""&&typeof e.sessionId=="string"&&typeof e.flushAfter=="number"&&Number.isFinite(e.flushAfter)&&typeof e.attempts=="number"&&Number.isFinite(e.attempts)&&typeof e.event=="object"&&e.event!==null}var P=class{constructor(e,t,i=gt,r=mt,o=we,s=ht){this.storage=e;this.logger=t;this.maxEntries=i;this.maxSerializedLength=r;this.lockName=o;this.storageKey=s;this.entries=this.read()}entries=[];reportedMalformed=!1;read(){let e=this.storage.getItem(this.storageKey);if(!Array.isArray(e))return[];let t=e.filter(pi);return t.length<e.length&&!this.reportedMalformed&&(this.reportedMalformed=!0,this.logger.error(`EventStore dropped ${e.length-t.length} malformed outbox entries`),this.logger.reportTelemetry?.("error","event store dropped malformed outbox entries")),t}mutate(e){return be(this.lockName,()=>{try{let t=e(this.read());if(t.length>this.maxEntries){let i=t.length-this.maxEntries;t=t.slice(t.length-this.maxEntries),this.logger.error(`EventStore evicted ${i} oldest entries (cap ${this.maxEntries})`),this.logger.reportTelemetry?.("error","event store evicted entries (cap)")}t=this.enforceSizeBudget(t),this.entries=t,this.storage.setItem(this.storageKey,t)}catch(t){this.logger.error("Failed to mutate event store",t),this.logger.reportTelemetry?.("error","failed to mutate event store")}})}enforceSizeBudget(e){let t=e.map(o=>JSON.stringify(o).length),i=t.reduce((o,s)=>o+s,e.length+1),r=0;for(;i>this.maxSerializedLength&&r<e.length;)i-=t[r]+1,r++;return r===0?e:(this.logger.error(`EventStore evicted ${r} oldest entries (size budget ${this.maxSerializedLength})`),this.logger.reportTelemetry?.("error","event store evicted entries (size budget)"),e.slice(r))}add(e){return this.mutate(t=>t.some(i=>i.id===e.id)?t:[...t,e])}all(){return this.entries=this.read(),this.entries}getDue(e){return this.all().filter(t=>t.flushAfter<=e)}remove(e){if(e.length===0)return Promise.resolve();let t=new Set(e);return this.mutate(i=>i.filter(r=>!t.has(r.id)))}update(e){if(e.length===0)return Promise.resolve();let t=new Map(e.map(i=>[i.id,i]));return this.mutate(i=>i.map(r=>t.get(r.id)??r))}size(){return this.all().length}};var $=class{constructor(e,t,i,r,o={},s){this.logger=e;this.transport=t;this.sessionId=i;this.sdk=r;this.storage=s;if(this.batchSize=o.batchSize||50,this.flushIntervalOverride=o.flushInterval,this.debug=o.debug??!1,this.requestConfig=o.requestConfig??!0,this.onConfigReceived=o.onConfigReceived,this.getDataPolicy=o.getDataPolicy,this.config=o.config??y,this.priorityFlowTypes=new Set(this.config.flushOnFlowTypeFinished),this.outboxLockName=o.outboxLockName,this.config.durableOutbox&&this.storage&&(this.store=new P(this.storage,this.logger,void 0,void 0,this.outboxLockName),this.pending=this.store.all()),this.storage){this.lowStore=new P(this.storage,this.logger,1e3,256*1024,`${this.outboxLockName??"cbo_outbox"}:lows`,"cbo_low_outbox_v1");let a=this.lowStore.all();this.lowPending=a.filter(l=>this.validPendingLow(l)),this.lowStore.remove(a.filter(l=>!this.validPendingLow(l)).map(l=>l.id))}this.setupLifecycleHooks(),(this.pending.length>0||this.lowPending.length>0)&&(this.dirtySinceSyncFlush=!0,this.scheduleFlush(0,"recovery"))}pending=[];lowsQueue=[];lowPending=[];lowStore;telemetryQueue=[];timer=null;isFlushing=!1;flushingDone;destroyed=!1;dirtySinceSyncFlush=!1;onVisibilityChange=null;onPageHide=null;batchSize;flushIntervalOverride;debug;requestConfig;onConfigReceived;getDataPolicy;config;priorityFlowTypes;outboxLockName;store;configResolved=!1;setSessionId(e){this.sessionId=e}flushInterval(){return this.flushIntervalOverride??this.config.flushIntervalMs}enqueue(e,t=this.sessionId){try{let i={id:e.id,sessionId:t,flushAfter:0,attempts:0,event:e};this.pending.push(i),this.store?.add(i),this.scheduleAfterEnqueue(e)}catch(i){this.logger.error("Failed to enqueue event",i)}}enqueueLow(e,t=this.sessionId){try{let i={...e,id:e.id??(0,yt.v7)()};if(this.config.durableLowOutbox){let r={id:i.id,sessionId:t,event:i,attempts:0,flushAfter:0};this.lowPending.push(r),this.lowPending=this.lowPending.slice(-1e3),this.lowStore?.add(r)}else this.lowsQueue.push({sessionId:t,event:i});this.scheduleAfterEnqueue()}catch(i){this.logger.error("Failed to enqueue low event",i)}}enqueueTelemetry(e){try{if(!this.config.telemetry)return;this.telemetryQueue.push(e),this.dirtySinceSyncFlush=!0,this.config.flushOnTelemetry&&this.flush("telemetry")}catch(t){this.logger.error("Failed to enqueue telemetry",t)}}scheduleAfterEnqueue(e){if(this.dirtySinceSyncFlush=!0,e!==void 0&&this.isPriorityEvent(e)){this.flush("flow-finished");return}this.scheduleFlush(this.flushInterval(),"timer")}isPriorityEvent(e){if(e.type!=="predefined"||e.name!=="flow_finished"&&e.name!=="flow_auto_finished")return!1;let t=e.data?.flowName;return typeof t=="string"&&this.priorityFlowTypes.has(t)}scheduleFlush(e,t){this.destroyed||this.timer||(this.timer=setTimeout(()=>{this.timer=null,this.flush(t)},e))}clearTimer(){this.timer&&(clearTimeout(this.timer),this.timer=null)}async flush(e="timer"){if(this.destroyed)return;if(this.isFlushing){e==="destroy"&&await this.flushingDone;return}this.isFlushing=!0;let t;this.flushingDone=new Promise(i=>{t=i});try{for(this.clearTimer();;){let i=Date.now(),r=this.getDuePending(i),o=this.lowPending.filter(m=>m.flushAfter<=i);if(r.length===0&&o.length===0&&this.lowsQueue.length===0&&this.telemetryQueue.length===0)return;let s=r[0]?.sessionId??o[0]?.sessionId??this.lowsQueue[0]?.sessionId??this.sessionId,a=r.filter(m=>m.sessionId===s).slice(0,this.batchSize),l=o.filter(m=>m.sessionId===s).slice(0,100),p=[...l.map(m=>m.event),...this.takeLows(s,100-l.length)],u=s===this.sessionId?this.takeTelemetry():[],d={sessionId:s,events:a.map(m=>m.event),sdk:this.sdk};p.length>0&&(d.lows=p),u.length>0&&(d.telemetry=u),this.attachBatchMeta(d,[...a,...l],e),l.length&&(d.deliveryAck=!0);let c=this.shouldRequestConfig()?{[Ne]:this.config.version||"1"}:void 0,f=await this.transport.send(d,c).catch(m=>(this.logger.error("Unexpected error in queue flush",m),{}));if(d.deliveryAck&&f.statusCode&&f.statusCode>=200&&f.statusCode<300&&!f.deliveryAccepted&&(f={...f,statusCode:503}),this.requestConfig&&this.handleConfigResponse(f),this.handleLowSendResult(f,l,i),!this.handleSendResult(f,a,i))return}}catch(i){this.logger.error("Unexpected error in queue flush",i)}finally{this.isFlushing=!1,t(),this.flushingDone=void 0,this.rescheduleIfPending()}}attachBatchMeta(e,t,i){e.meta={...e.meta,flushReason:i};let r=this.readDataPolicy();r!==void 0&&(e.meta={...e.meta,dataPolicy:r}),this.config.version&&(e.meta={...e.meta,configVersion:this.config.version});let o=t.reduce((s,a)=>Math.max(s,a.attempts),0);o>0&&(e.meta={...e.meta,retryCount:o})}readDataPolicy(){try{return this.getDataPolicy?.()}catch(e){this.logger.debug("Failed to read data policy for batch meta",e);return}}getDuePending(e){return this.pending.filter(t=>t.flushAfter<=e)}takeLows(e=this.sessionId,t=100){let i=this.lowsQueue.filter(o=>o.sessionId===e).slice(0,t),r=new Set(i);return this.lowsQueue=this.lowsQueue.filter(o=>!r.has(o)),i.map(o=>o.event)}validPendingLow(e){return typeof e.event?.lowType=="string"&&e.event.id===e.id&&Number.isFinite(e.event.ts)&&e.event.ts>Date.now()-7*864e5}removeLowEntries(e){let t=new Set(e);this.lowPending=this.lowPending.filter(i=>!t.has(i.id)),this.lowStore?.remove(e)}handleLowSendResult(e,t,i){let r=e.statusCode;if(r!==void 0&&r>=200&&r<300){e.deliveryAccepted?this.removeLowEntries(t.map(o=>o.id)):this.deferLowEntries(t,i);return}if(!this.isRetryable(r)){this.removeLowEntries(t.map(o=>o.id)),this.logger.reportTelemetry?.("error","low events rejected by ingestion");return}this.deferLowEntries(t,i,this.parseRetryAfter(e))}deferLowEntries(e,t,i=null){let r=[];for(let o of e){if(!this.validPendingLow(o)){r.push(o.id);continue}o.attempts=Math.min(o.attempts+1,16),o.flushAfter=t+Math.max(Math.min(6e4,1e3*2**Math.min(o.attempts,6)),this.backoffForAttempt(o.attempts,i))}this.removeLowEntries(r),this.lowStore?.update(e.filter(o=>!r.includes(o.id)))}takeTelemetry(){let e=this.telemetryQueue;return this.telemetryQueue=[],e}shouldRequestConfig(){return this.requestConfig&&!this.configResolved}handleConfigResponse(e){let t=e.statusCode;typeof t=="number"&&t>=200&&t<300&&(this.configResolved=!0),e.config&&(this.config.version||this.updateConfig(e.config),this.onConfigReceived?.(e.config))}updateConfig(e){if(this.destroyed)return;let t=this.config.flushIntervalMs!==e.flushIntervalMs;if(this.config={...e,durableOutbox:this.config.durableOutbox||e.durableOutbox},this.priorityFlowTypes=new Set(e.flushOnFlowTypeFinished),e.durableLowOutbox&&this.lowsQueue.length){let r=this.lowsQueue;this.lowsQueue=[];for(let{event:o,sessionId:s}of r)this.enqueueLow(o,s)}let i=!1;if(this.config.durableOutbox&&this.storage&&!this.store){this.store=new P(this.storage,this.logger,void 0,void 0,this.outboxLockName);let r=new Set(this.pending.map(s=>s.id)),o=this.store.all().filter(s=>!r.has(s.id));for(let s of this.pending)this.store.add(s);this.pending=[...o,...this.pending],i=o.length>0}i?(this.dirtySinceSyncFlush=!0,this.clearTimer(),this.scheduleFlush(0,"recovery")):t&&(this.clearTimer(),this.rescheduleIfPending())}handleSendResult(e,t,i){let r=e.statusCode,o=typeof r=="number"&&r>=200&&r<300;if(t.length===0)return o;if(o)return this.removeEntries(t.map(u=>u.id)),!0;if(!this.isRetryable(r))return this.removeEntries(t.map(u=>u.id)),!1;let s=Math.max(1,this.config.retry.maxAttempts),a=this.parseRetryAfter(e),l=[],p=[];for(let u of t)u.attempts+=1,u.attempts>=s?l.push(u.id):(u.flushAfter=i+this.backoffForAttempt(u.attempts,a),p.push(u));return this.removeEntries(l),this.store?.update(p),!1}isRetryable(e){return e===void 0||e===408||e===429?!0:e>=500}backoffForAttempt(e,t){let i=this.config.retry,r=i.baseDelayMs*Math.pow(2,Math.max(0,e-1));i.maxDelayMs>0&&(r=Math.min(r,i.maxDelayMs));let o=Math.round(r/2+Math.random()*(r/2));return t!==null&&(o=Math.max(o,t)),o}parseRetryAfter(e){let t=e.headers?.["retry-after"];if(!t)return null;let i=Number(t);if(!Number.isNaN(i))return i*1e3;let r=Date.parse(t);return Number.isNaN(r)?null:Math.max(0,r-Date.now())}removeEntries(e){if(e.length===0)return;let t=new Set(e);this.pending=this.pending.filter(i=>!t.has(i.id)),this.store?.remove(e)}rescheduleIfPending(){try{if(this.destroyed||this.timer||this.pending.length===0&&this.lowPending.length===0&&this.lowsQueue.length===0)return;let e=Date.now();if(this.getDuePending(e).length>0||this.lowPending.some(i=>i.flushAfter<=e)||this.lowsQueue.length>0){this.scheduleFlush(this.flushInterval(),"timer");return}let t=Math.min(...[...this.pending,...this.lowPending].map(i=>i.flushAfter));this.scheduleFlush(Math.max(0,t-e),"backoff")}catch(e){this.logger.error("Failed to reschedule queue flush",e)}}setupLifecycleHooks(){typeof window>"u"||(this.onVisibilityChange=()=>{try{this.writeLifecycleDebugOutput("cbo_visibility_change_debug"),document.visibilityState==="hidden"&&this.config.tvc&&this.flushSync("visibility-change")}catch(e){this.logger.error("Unexpected error in queue flushSync",e)}},this.onPageHide=()=>{try{this.writeLifecycleDebugOutput("cbo_pagehide_debug"),this.config.tph&&this.flushSync("pagehide")}catch(e){this.logger.error("Unexpected error in queue flushSync",e)}},window.addEventListener("visibilitychange",this.onVisibilityChange),window.addEventListener("pagehide",this.onPageHide))}writeLifecycleDebugOutput(e){if(!this.debug||!this.storage)return;let t={last_executed:Date.now(),url:window.location.href};this.storage.setItem(e,t)}flushKeepalive(e="manual"){this.flushSync(e)}flushSync(e){if(!this.dirtySinceSyncFlush)return;let t=this.sessionId,i=this.pending.filter(p=>p.sessionId===t),r=i.slice(0,this.batchSize),o=this.lowPending.filter(p=>p.sessionId===t).slice(0,100),s=[...o.map(p=>p.event),...this.takeLows(t,100-o.length)],a=this.takeTelemetry();if(r.length===0&&s.length===0&&a.length===0){this.dirtySinceSyncFlush=!1;return}let l={sessionId:t,events:r.map(p=>p.event),sdk:this.sdk};s.length>0&&(l.lows=s),a.length>0&&(l.telemetry=a),this.attachBatchMeta(l,[...r,...o],e),o.length&&(l.deliveryAck=!0),this.config.beaconKeepalive&&this.transport.sendBeacon?this.transport.sendBeacon(l)||this.transport.send(l):this.transport.send(l),this.config.durableOutbox||this.removeEntries(r.map(p=>p.id)),this.dirtySinceSyncFlush=!this.config.durableOutbox&&i.length>r.length}destroy(){try{this.destroyed=!0,this.clearTimer(),typeof window<"u"&&(this.onVisibilityChange&&window.removeEventListener("visibilitychange",this.onVisibilityChange),this.onPageHide&&window.removeEventListener("pagehide",this.onPageHide))}catch(e){this.logger.error("Failed to destroy queue lifecycle hooks",e)}}};var Ve=require("uuid"),vt=Gt(require("detectincognitojs")),qe={collectorTimeoutMs:1e3,timing:!1},Ke="cbo_tab_id",di={bluetoothAvailable:"bt",clientCapabilities:"cc",userVerifyingPlatformAuthenticatorAvailable:"uvpaa",conditionalMediationAvailable:"cm",javaScriptHighEntropy:"he",privateMode:"pm",webdriver:"wd",maxTouchPoints:"mtp"};function G(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var Ee=class{constructor(e,t,i="localstorage",r,o=()=>qe,s){this.logger=e;this.storage=t;this.storageSource=i;this.sessionStorage=r;this.settings=o;this.emitTelemetry=s}async getInfo(){try{let e=this.resolveSettings(),t=G(),i=this.getClientEnvHandle(),r=await Promise.all([this.collectField("bluetoothAvailable","navigator.bluetooth.getAvailability",()=>this.isBluetoothAvailable(),e.collectorTimeoutMs),this.collectField("clientCapabilities","PublicKeyCredential.getClientCapabilities",()=>this.getClientCapabilities(),e.collectorTimeoutMs),this.collectField("userVerifyingPlatformAuthenticatorAvailable","PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable",()=>this.getUserVerifyingPlatformAuthenticatorAvailable(),e.collectorTimeoutMs),this.collectField("conditionalMediationAvailable","PublicKeyCredential.isConditionalMediationAvailable",()=>this.isConditionalMediationAvailable(),e.collectorTimeoutMs),this.collectField("javaScriptHighEntropy","navigator.userAgentData.getHighEntropyValues",()=>this.getJavaScriptHighEntropy(),e.collectorTimeoutMs),this.collectField("privateMode","detectIncognito",()=>this.isPrivateMode(),e.collectorTimeoutMs),this.collectField("webdriver","navigator.webdriver",()=>this.getWebdriver(),e.collectorTimeoutMs),this.collectField("maxTouchPoints","navigator.maxTouchPoints",()=>this.getMaxTouchPoints(),e.collectorTimeoutMs)]),o=G()-t;e.timing&&this.reportTiming(o,r);let[s,a,l,p,u,d,c,f]=r,m=r.flatMap(E=>E.error?[E.error]:[]),g={type:"web",clientEnvHandle:i.value,clientEnvHandleMeta:{timestamp:i.timestamp,source:i.source},tabId:this.getTabId(),data:{bluetoothAvailable:s.value,javaScriptHighEntropy:u.value,privateMode:d.value,webdriver:c.value,conditionalMediationAvailable:p.value,userVerifyingPlatformAuthenticatorAvailable:l.value,clientCapabilities:a.value,maxTouchPoints:f.value}};return m.length>0&&(g.collectionErrors=m),g}catch(e){return this.logger.error("Failed to collect device info",e),{}}}async collectField(e,t,i,r){let o,s=G();try{let a=await Promise.race([Promise.resolve().then(i),new Promise((l,p)=>{o=setTimeout(()=>{let u=new Error(`Device info collection timed out after ${r}ms`);u.name="TimeoutError",p(u)},r)})]);return{field:e,value:a,durationMs:G()-s}}catch(a){return this.logger.error(`Failed to collect device info field "${e}"`,a),{field:e,durationMs:G()-s,error:{field:e,source:t,error:F(a)??{message:"Unknown error"}}}}finally{o&&clearTimeout(o)}}resolveSettings(){try{let e=this.settings(),t=e?.collectorTimeoutMs;return{collectorTimeoutMs:typeof t=="number"&&Number.isFinite(t)&&t>0?t:qe.collectorTimeoutMs,timing:e?.timing===!0}}catch(e){return this.logger.error("Failed to resolve device info collector settings",e),qe}}reportTiming(e,t){if(this.emitTelemetry)try{let i=t.map(r=>`${di[r.field]??r.field}=${Math.round(r.durationMs)}`).join(",");this.emitTelemetry("info",`device info collected in ${Math.round(e)}ms (${i})`)}catch(i){this.logger.error("Failed to report device info timing",i)}}static getOsAndBrowserInfo(){return{osName:this.getOsName(),browserName:this.getBrowserName()}}static getUserAgent(){return typeof navigator>"u"?"":navigator.userAgent??""}static getOsName(){let e=this.getUserAgent();return e.includes("iOS")?"iOS":e.includes("Android")?"Android":e.includes("Windows")?"Windows":e.includes("Macintosh")?"macOS":e.includes("Linux")?"Linux":e.includes("ChromeOS")?"ChromeOS":"other"}static getBrowserName(){let e=this.getUserAgent();return e.includes("Chrome")?"Chrome":e.includes("Firefox")?"Firefox":e.includes("Safari")?"Safari":e.includes("Edge")?"Edge":e.includes("Opera")?"Opera":e.includes("IE")?"IE":"other"}async isBluetoothAvailable(){if(!(typeof navigator>"u"||!navigator.bluetooth))return await navigator.bluetooth.getAvailability()}async getUserVerifyingPlatformAuthenticatorAvailable(){if(!(typeof PublicKeyCredential>"u"||!PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable))return await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}async isConditionalMediationAvailable(){if(!(typeof PublicKeyCredential>"u"||!PublicKeyCredential.isConditionalMediationAvailable))return await PublicKeyCredential.isConditionalMediationAvailable()}async getClientCapabilities(){if(typeof PublicKeyCredential>"u"||!PublicKeyCredential.getClientCapabilities)return;let e=await PublicKeyCredential.getClientCapabilities();return Object.fromEntries(Object.entries(e).map(([t,i])=>[t,i.toString()]))}getClientEnvHandle(){let e=this.storage.getItem("cbo_client_env_handle");if(e)return e;let t=(0,Ve.v7)(),i={timestamp:Date.now(),source:this.storageSource,value:t};return this.storage.setItem("cbo_client_env_handle",i),i}getTabId(){if(!this.sessionStorage)return;let e=this.sessionStorage.getItem(Ke);if(e)return e;let t=(0,Ve.v7)();if(this.sessionStorage.setItem(Ke,t),this.sessionStorage.getItem(Ke)===t)return t}async getJavaScriptHighEntropy(){if(typeof navigator>"u"||!navigator.userAgentData)return;let e=await navigator.userAgentData.getHighEntropyValues(["platformVersion","model"]),t=e.platform,i=e.mobile,r=e.platformVersion,o=e.model||void 0;if(!(!t||i===void 0||!r))return{platform:t,mobile:i,platformVersion:r,model:o}}async isPrivateMode(){return(await(0,vt.default)()).isPrivate}getWebdriver(){if(!(typeof navigator>"u"))return navigator.webdriver}getMaxTouchPoints(){if(!(typeof navigator>"u"||typeof navigator.maxTouchPoints!="number"))return navigator.maxTouchPoints}};var xe=class{constructor(e,t,i,r){this.logger=e;this.source=t;this.refreshInterval=i;this.attachInterval=r}snapshot;refreshedAt=0;lastAttachedAt=null;refreshPromise;timer;destroyed=!1;start(){this.refresh()}getForEvent(){if(Date.now()-this.refreshedAt>=this.refreshInterval&&this.refresh(),!!this.snapshot&&!(this.lastAttachedAt!==null&&Date.now()-this.lastAttachedAt<this.attachInterval))return this.lastAttachedAt=Date.now(),this.snapshot}destroy(){this.destroyed=!0,this.timer&&(clearTimeout(this.timer),this.timer=void 0)}refresh(){return this.refreshPromise?this.refreshPromise:(this.timer&&(clearTimeout(this.timer),this.timer=void 0),this.refreshPromise=Promise.resolve().then(()=>this.source.getInfo()).then(e=>{this.snapshot=e,this.refreshedAt=Date.now()}).catch(e=>this.logger.error("Failed to refresh device info",e)).finally(()=>{this.refreshPromise=void 0,this.destroyed||(this.timer=setTimeout(()=>{this.refresh()},this.refreshInterval))}),this.refreshPromise)}};function w(n,e){return`${n}_${e}`}var z=class{constructor(e,t){this.engine=e;this.namespace=t}getItem(e){return this.engine.getItem(w(e,this.namespace))}setItem(e,t){this.engine.setItem(w(e,this.namespace),t)}removeItem(e){this.engine.removeItem(w(e,this.namespace))}},W=class{constructor(e){this.logger=e}getItem(e){try{if(typeof localStorage>"u")return null;let t=localStorage.getItem(e);return t?JSON.parse(t):null}catch(t){return this.logger.error(`LocalStorage.getItem failed for key "${e}"`,t),null}}setItem(e,t){try{if(typeof localStorage>"u")return;localStorage.setItem(e,JSON.stringify(t))}catch(i){this.logger.error(`LocalStorage.setItem failed for key "${e}"`,i),this.logger.reportTelemetry?.("error",`localStorage.setItem failed: ${e}`)}}removeItem(e){try{if(typeof localStorage>"u")return;localStorage.removeItem(e)}catch(t){this.logger.error(`LocalStorage.removeItem failed for key "${e}"`,t)}}},Q=class{constructor(e,t){this.logger=e;this.domain=t}getItem(e){try{if(typeof document>"u")return null;let t=e+"=",i=document.cookie.split(";");for(let r=0;r<i.length;r++){let o=i[r].trim();if(o.indexOf(t)===0){let s=o.substring(t.length);return JSON.parse(decodeURIComponent(s))}}return null}catch(t){return this.logger.error(`CookieStorage.getItem failed for key "${e}"`,t),null}}setItem(e,t){try{if(typeof document>"u")return;let i=`${e}=${encodeURIComponent(JSON.stringify(t))}; path=/; SameSite=Lax`;this.domain&&(i+=`; domain=${this.domain}`),document.cookie=i}catch(i){this.logger.error(`CookieStorage.setItem failed for key "${e}"`,i),this.logger.reportTelemetry?.("error",`cookie.setItem failed: ${e}`)}}removeItem(e){try{if(typeof document>"u")return;let t=`${e}=; Max-Age=-99999999; path=/`;this.domain&&(t+=`; domain=${this.domain}`),document.cookie=t}catch(t){this.logger.error(`CookieStorage.removeItem failed for key "${e}"`,t)}}},j=class{constructor(e){this.logger=e}getItem(e){try{if(typeof sessionStorage>"u")return null;let t=sessionStorage.getItem(e);return t?JSON.parse(t):null}catch(t){return this.logger.error(`SessionStorage.getItem failed for key "${e}"`,t),null}}setItem(e,t){try{if(typeof sessionStorage>"u")return;sessionStorage.setItem(e,JSON.stringify(t))}catch(i){this.logger.error(`SessionStorage.setItem failed for key "${e}"`,i),this.logger.reportTelemetry?.("error",`sessionStorage.setItem failed: ${e}`)}}removeItem(e){try{if(typeof sessionStorage>"u")return;sessionStorage.removeItem(e)}catch(t){this.logger.error(`SessionStorage.removeItem failed for key "${e}"`,t)}}};var Ie=1,ke="cbo_storage_schema",ui=["cbo_seq","cbo_sdk_config","cbo_experiments","cbo_client_env_handle","cbo_outbox","cbo_visibility_change_debug","cbo_pagehide_debug","cbo_session"],ci=["cbo_session_id","cbo_tab_id"],fi=["cbo_client_env_handle"];function Ce(n,e,t){return n.setItem(e,t),JSON.stringify(n.getItem(e))===JSON.stringify(t)}function $e(n,e,t){let i=n.getItem(ke);if(i!==null){if(i.version!==Ie||i.projectId!==e)return!1;if(i.complete===!0)return!0;if(i.complete!==!1)return!1}else{if(t.some(r=>n.getItem(w(r,e))!==null))return Ce(n,ke,{version:Ie,projectId:e,complete:!0});if(!Ce(n,ke,{version:Ie,projectId:e,complete:!1}))return!1}for(let r of t){let o=w(r,e);if(n.getItem(o)!==null)continue;let s=n.getItem(r);if(s!==null&&!Ce(n,o,s))return!1}return Ce(n,ke,{version:Ie,projectId:e,complete:!0})}function St(n,e,t,i,r){try{if(!$e(e,n,ui))return;$e(t,n,ci),i&&$e(i,n,fi)}catch(o){r.error("Failed to migrate legacy Observe storage",o)}}var hi=10*1e3,gi=600*1e3,mi=[1e3,3e3],Oe=class{constructor(e,t,i){this.url=e;this.storage=t;this.logger=i;this.initialConfig=Ue(t)??void 0}initialConfig;refreshTimer;requestTimer;retryTimer;controller;fetching=!1;stopped=!1;onConfig;start(e){this.stopped||this.onConfig||(this.onConfig=e,this.fetchConfig())}async fetchConfig(e=0){if(this.stopped||this.fetching)return;e===0&&(clearTimeout(this.refreshTimer),clearTimeout(this.retryTimer),this.refreshTimer=setTimeout(()=>{this.fetchConfig()},gi)),this.fetching=!0;let t=typeof AbortController<"u"?new AbortController:void 0;this.controller=t,this.requestTimer=t?setTimeout(()=>t.abort(),hi):void 0;let i=!0;try{let r=await fetch(this.url,{method:"GET",cache:"no-store",...t?{signal:t.signal}:{}});if(!r.ok)throw i=(r.status===408||r.status===429||r.status>=500)&&!r.headers.has("Retry-After"),new Error(`SDK config request failed (${r.status})`);let o=await r.json();i=!1;let s=H(o);if(!s)throw new Error("Invalid SDK config response");if(this.stopped||t?.signal.aborted)return;Be(this.storage,s),this.onConfig?.(s)}catch(r){if(!this.stopped){this.logger.error("Failed to fetch SDK config",r);let o=mi[e];(i&&!(r instanceof SyntaxError)||t?.signal.aborted)&&o!==void 0&&(this.retryTimer=setTimeout(()=>{this.fetchConfig(e+1)},o))}}finally{clearTimeout(this.requestTimer),this.requestTimer=void 0,this.controller=void 0,this.fetching=!1}}destroy(){this.stopped=!0,clearTimeout(this.refreshTimer),clearTimeout(this.requestTimer),clearTimeout(this.retryTimer),this.controller?.abort(),this.onConfig=void 0}};var I=require("uuid");var N=class{constructor(e,t){this.logger=e;this.sink=t}lease;destroyed=!1;arm(e,t=!1){if(this.disarm(),!(this.destroyed||t))try{this.lease=this.sink.beginCeremony?.(e)}catch(i){this.logger.error("Failed to register ceremony low-event context",i)}}scheduleDisarm(e){try{this.lease?.settle(e)}catch(t){this.logger.error("Failed to settle ceremony low-event context",t)}}disarm(){try{this.lease?.destroy()}catch(e){this.logger.error("Failed to release ceremony low-event context",e)}this.lease=void 0}destroy(){this.disarm(),this.destroyed=!0}};var Y=class extends h{getOptions;ceremony;postResponse;lowEventTracker;constructor(e,t){super(e,"passkey-login"),this.lowEventTracker=new N(e.getLogger(),this.lowEventSink("ceremony")),this.registerLowFlusher(()=>this.lowEventTracker.disarm()),this.getOptions=this.defineStep("get-options"),this.ceremony=this.withWindowLowEvents(this.defineStep("ceremony"),this.lowEventTracker),this.postResponse=this.defineStep("post-response"),this.subflowStart({explicitSpecType:t?.explicitSpecType})}trigger(e,t){super.trigger(e,t)}destroy(){this.lowEventTracker.destroy()}};var U=class{constructor(e,t,i,r){this.previousLength=e;this.pushLow=t;this.logger=i;this.reserveCaptureSeq=r}prefillSettled=!1;inputBatch=null;currentEffect="modify";ringEffect="modify";autofillTimestamps=[];autofillStreak=null;idleTimer=null;markInputObserved(){this.prefillSettled=!0}capturePrefill(e,t=!1){t&&(this.prefillSettled=!1),!this.prefillSettled&&(this.previousLength=e,e!==0&&(this.prefillSettled=!0,this.pushLow({lowType:"input-prefill",ts:Date.now(),initiator:"unknown"})))}flush(){this.cancelIdle(),this.flushInputBatch(),this.flushAutofillStreak()}cancelIdle(){this.idleTimer!==null&&clearTimeout(this.idleTimer),this.idleTimer=null}scheduleIdle(){this.cancelIdle(),this.idleTimer=setTimeout(()=>{this.idleTimer=null;try{this.flushInputBatch(!0),this.flushAutofillStreak()}catch(e){this.logger.error("Failed to flush idle input",e)}},3e3)}extendInputBatch(e,t=this.currentEffect,i){let r=this.inputBatch;if(!r){this.inputBatch={firstTimestamp:e,lastTimestamp:e,effect:t,captureSeq:i};return}r.lastTimestamp=e}drainAutofillRingToBatch(){for(let e of this.autofillTimestamps)this.extendInputBatch(e.ts,this.ringEffect,e.captureSeq);this.autofillTimestamps.length=0}flushInputBatch(e=!1){this.drainAutofillRingToBatch();let t=this.inputBatch;t&&(this.pushLow({...t.captureSeq===void 0?{}:{captureSeq:t.captureSeq},lowType:e?"input-idle":"input",ts:t.firstTimestamp,durationMs:t.lastTimestamp-t.firstTimestamp,inputEffect:t.effect}),this.inputBatch=null)}flushAutofillStreak(){let e=this.autofillStreak;e&&(this.pushLow({...e.captureSeq===void 0?{}:{captureSeq:e.captureSeq},lowType:"big-input-add",ts:e.firstTimestamp,durationMs:e.lastTimestamp-e.firstTimestamp,inputEffect:e.effect}),this.autofillStreak=null)}detectAutofillStreak(){let e=this.autofillTimestamps;if(e.length<5)return!1;let t=1/0,i=-1/0;for(let r=1;r<e.length;r++){let o=e[r].ts-e[r-1].ts;if(o>80)return!1;o<t&&(t=o),o>i&&(i=o)}return i-t<=25}record(e,t=Date.now(),i=!1,r=this.reserveCaptureSeq?.()){this.markInputObserved(),this.scheduleIdle();let o=this.previousLength;this.currentEffect=e===0?"clear":o===0?"fill":"modify";let s=e-o;if(this.previousLength=e,e===0&&o>0){this.flush(),this.pushLow({...r===void 0?{}:{captureSeq:r},lowType:"input-clear",ts:t,inputEffect:"clear"});return}if(i){this.flushAutofillStreak(),this.drainAutofillRingToBatch(),this.extendInputBatch(t,this.currentEffect,r);return}if(s>=3){this.flushInputBatch(),this.flushAutofillStreak(),this.pushLow({...r===void 0?{}:{captureSeq:r},lowType:"big-input-add",ts:t,inputEffect:this.currentEffect});return}if(s<=-3){this.flushInputBatch(),this.flushAutofillStreak(),this.pushLow({...r===void 0?{}:{captureSeq:r},lowType:"big-input-rem",ts:t,inputEffect:this.currentEffect});return}let a=this.autofillStreak;if(a){if(s===1&&t-a.lastTimestamp<=80){a.lastTimestamp=t;return}this.flushAutofillStreak()}if(s!==1){this.drainAutofillRingToBatch(),this.extendInputBatch(t,this.currentEffect,r);return}let l=this.autofillTimestamps;if(l.length===0&&(this.ringEffect=this.currentEffect),l.push({ts:t,captureSeq:r}),l.length>5){let d=l.shift();this.extendInputBatch(d.ts,this.ringEffect,d.captureSeq),this.ringEffect="modify"}if(!this.detectAutofillStreak())return;let p=l[0],u=l[l.length-1];l.length=0,this.flushInputBatch(),this.autofillStreak={firstTimestamp:p.ts,captureSeq:p.captureSeq,lastTimestamp:u.ts,effect:this.ringEffect}}};var B=class{constructor(e,t,i,r){this.inputs=e;this.logger=t;this.changed=i;this.reserveCaptureSeq=r;for(let o of e)o.addEventListener("paste",this.onPaste,!0),o.addEventListener("beforeinput",this.onBeforeInput,!0)}before=null;timestamp=0;captureSeq;pasteEvent;timer=null;onPaste=e=>this.begin(e);onBeforeInput=e=>{e.inputType==="insertFromPaste"?this.begin(e):this.flush()};handlesInput(e){if(!this.before)return!1;let t=this.pasteEvent?.type==="paste"&&(this.pasteEvent.eventPhase??0)>0;return e.inputType==="insertFromPaste"||t?!0:(this.clear(),!1)}get pending(){return this.before!==null}begin(e){if(!(!e.isTrusted||this.before))try{this.before=this.inputs.map(t=>t.value),this.pasteEvent=e,this.timestamp=Date.now(),this.captureSeq=this.reserveCaptureSeq?.(),this.timer=setTimeout(()=>this.flush(),0)}catch(t){this.logger.error("Failed to observe paste",t),this.clear()}}flush(){let e=this.before;if(!e)return;let t=this.timestamp,i=this.captureSeq;this.clear();try{let r=0,o=!1;this.inputs.forEach((s,a)=>{let l=e[a],p=s.value;if(l===p)return;o=!0;let u=0;for(;u<l.length&&u<p.length&&l[u]===p[u];)u++;let d=0;for(;d<l.length-u&&d<p.length-u&&l[l.length-d-1]===p[p.length-d-1];)d++;r+=p.length-u-d}),o&&this.changed(t,r,i)}catch(r){this.logger.error("Failed to finish paste observation",r)}}clear(){this.timer!==null&&clearTimeout(this.timer),this.timer=null,this.before=null,this.pasteEvent=void 0}destroy(){this.flush();for(let e of this.inputs)e.removeEventListener("paste",this.onPaste,!0),e.removeEventListener("beforeinput",this.onBeforeInput,!0)}};var yi=[{query:"com-1password-button",eventType:"pa-1"},{query:"com-1password-menu",eventType:"pa-2"},{query:"com-1password-notification",eventType:"pa-3"}],vi="[data-lastpass-root], [data-lp], [data-lpignore], [data-lpfieldtype]",Tt="pa-4",Si='[popover="manual"]',Ti=400,bi=20,Ge="pa-5",ze="pa-6",We=(n,e)=>{try{return Array.from(n.querySelectorAll(e))}catch{return[]}},bt=n=>{if(n.getAttribute("popover")!=="manual")return!1;let e=n.getAttribute("style")??"";return!(e.length<Ti||!/z-index:\s*2147483647\b/i.test(e)||!/position:\s*fixed\b/i.test(e)||!/display:\s*block\b/i.test(e)||(e.match(/initial\s*!important/gi)?.length??0)<bi)},wi=n=>{if(bt(n)||n.getAttribute("popover")!=="manual")return!1;let e=n.getAttribute("style")??"";return!(!/z-index:\s*2147483647\b/i.test(e)||!/position:\s*fixed\b/i.test(e)||!/backdrop-filter:\s*[^;]*blur\(\s*20px\s*\)/i.test(e)||!/background-color:\s*rgba\(\s*35\s*,\s*35\s*,\s*35\s*,/i.test(e))},Ei=n=>{n(document);for(let e of Array.from(document.querySelectorAll("*"))){let t=e.shadowRoot;t&&n(t)}},wt=()=>{let n=new Set;return typeof document>"u"||Ei(e=>{for(let t of yi)n.has(t.eventType)||We(e,t.query).length>0&&n.add(t.eventType);if(!n.has(Tt)&&We(e,vi).length>0&&n.add(Tt),!n.has(Ge)||!n.has(ze))for(let t of We(e,Si)){if(!n.has(Ge)&&bt(t)){n.add(Ge);continue}!n.has(ze)&&wi(t)&&n.add(ze)}}),n};var xi=500,Ii=250,b=class{constructor(e,t,i){this.logger=e;this.inputField=t;this.sink=i;this.changes=new U(t.value.length,this.pushLow,e,i.reserveCaptureSeq),this.pasteObserver=new B([t],e,(r,o,s)=>{this.changes.flush(),this.changes.markInputObserved();let a=this.changes.previousLength;this.changes.previousLength=t.value.length,this.pushLow({...s===void 0?{}:{captureSeq:s},lowType:"input-paste",ts:r,inputEffect:t.value.length===0?"clear":a===0?"fill":"modify"})},i.reserveCaptureSeq),this.boundHandlers={focus:this.wrapHandler("focus",()=>this.handleFocus()),blur:this.wrapHandler("blur",()=>this.handleBlur()),pointerdown:this.wrapHandler("pointerdown",()=>this.enqueueNonInputEvent("pointerdown")),pointerup:this.wrapHandler("pointerup",()=>this.enqueueNonInputEvent("pointerup")),click:this.wrapHandler("click",()=>this.enqueueNonInputEvent("click")),input:r=>{try{this.handleInput(r)}catch(o){this.logger.error("Failed to observe input",o)}},keyup:this.wrapKeyboardHandler("keyup",r=>this.handleKeyUp(r)),pageHide:this.wrapHandler("pagehide",()=>this.flushForTeardown())},this.unregisterInputs=i.registerInputs?.([t],()=>this.flushPending()),this.capturePrefill(),this.attach()}unregisterInputs;changes;pasteObserver;emittedSignals=new Set;firstFocusHandled=!1;mountProbeTimer=null;focusProbeTimer=null;destroyed=!1;boundHandlers;destroy(){if(!this.destroyed){this.destroyed=!0;try{this.mountProbeTimer!==null&&(clearTimeout(this.mountProbeTimer),this.mountProbeTimer=null),this.focusProbeTimer!==null&&(clearTimeout(this.focusProbeTimer),this.focusProbeTimer=null),this.changes.flush(),this.unregisterInputs?.(),this.pasteObserver.destroy(),this.detach()}catch(e){this.logger.error("Failed to destroy LowEventInputTracker",e)}}}attach(){let e=this.inputField;e.addEventListener("focus",this.boundHandlers.focus),e.addEventListener("blur",this.boundHandlers.blur),e.addEventListener("pointerdown",this.boundHandlers.pointerdown),e.addEventListener("pointerup",this.boundHandlers.pointerup),e.addEventListener("click",this.boundHandlers.click),e.addEventListener("input",this.boundHandlers.input),e.addEventListener("keyup",this.boundHandlers.keyup),typeof window<"u"&&window.addEventListener("pagehide",this.boundHandlers.pageHide),typeof document<"u"&&document.activeElement===e&&this.handleFocus(),typeof window<"u"&&(this.mountProbeTimer=setTimeout(()=>this.runEnvProbe(),xi))}detach(){let e=this.inputField;e.removeEventListener("focus",this.boundHandlers.focus),e.removeEventListener("blur",this.boundHandlers.blur),e.removeEventListener("pointerdown",this.boundHandlers.pointerdown),e.removeEventListener("pointerup",this.boundHandlers.pointerup),e.removeEventListener("click",this.boundHandlers.click),e.removeEventListener("input",this.boundHandlers.input),e.removeEventListener("keyup",this.boundHandlers.keyup),typeof window<"u"&&window.removeEventListener("pagehide",this.boundHandlers.pageHide)}pushLow=e=>{this.sink.enqueueLowEvent(e)};runEnvProbe(){try{let e=wt(),t=Date.now();for(let i of e)this.emittedSignals.has(i)||(this.emittedSignals.add(i),this.pushLow({lowType:i,ts:t}))}catch(e){this.logger.error("Failed to run input env probe",e)}}scheduleFocusProbe(){this.firstFocusHandled||(this.firstFocusHandled=!0,this.focusProbeTimer=setTimeout(()=>this.runEnvProbe(),Ii))}capturePrefill(e=!1){this.destroyed||(this.flushPending(),this.changes.capturePrefill(this.inputField.value.length,e))}flushPending(){this.pasteObserver.flush(),this.changes.flush()}enqueueNonInputEvent(e){this.changes.flush(),this.pushLow({lowType:e,ts:Date.now()})}handleFocus(){this.scheduleFocusProbe(),this.enqueueNonInputEvent("focus")}handleBlur(){this.pasteObserver.flush(),this.enqueueNonInputEvent("blur")}handleInput(e){this.pasteObserver.handlesInput(e)||this.changes.record(this.inputField.value.length,Date.now(),e.isComposing||e.inputType==="insertCompositionText")}handleKeyUp(e){e.key==="Escape"&&this.enqueueNonInputEvent("keyup-escape")}flushForTeardown(){this.pasteObserver.flush(),this.changes.flush(),this.sink.flushKeepalive()}wrapHandler(e,t){return()=>{try{t()}catch(i){this.logger.error(`Failed to handle low event "${e}"`,i)}}}wrapKeyboardHandler(e,t){return i=>{try{t(i)}catch(r){this.logger.error(`Failed to handle low event "${e}"`,r)}}}};var Le=class{constructor(e,t,i){this.logger=e;this.sink=i;this.inputs=[...new Set(t)],this.changes=new U(this.length(),r=>i.enqueueLowEvent(r),e,i.reserveCaptureSeq),this.paste=new B(this.inputs,e,(r,o,s)=>{this.cancelChange(),this.changes.flush(),this.changes.markInputObserved();let a=this.changes.previousLength;this.changes.previousLength=this.length(),i.enqueueLowEvent({...s===void 0?{}:{captureSeq:s},lowType:"input-paste",ts:r,inputEffect:this.length()===0?"clear":a===0?"fill":"modify"})},i.reserveCaptureSeq),this.unregisterInputs=i.registerInputs?.(this.inputs,()=>this.flushPending()),this.capturePrefill();for(let r of this.inputs){this.listen(r,"input",o=>{this.paste.handlesInput(o)||(this.composing||=o.isComposing||o.inputType==="insertCompositionText",this.changeTimer===null&&(this.changeTime=Date.now(),this.changeSeq=i.reserveCaptureSeq?.(),this.changeTimer=setTimeout(()=>this.safe(()=>this.flushChanges()),0)))}),this.listen(r,"focus",o=>{this.contains(o.relatedTarget)||this.emit("focus")}),this.listen(r,"blur",o=>{this.contains(o.relatedTarget)||(this.flushPending(),this.emit("blur"))});for(let o of["click","pointerdown","pointerup"])this.listen(r,o,()=>this.emit(o));this.listen(r,"keyup",o=>{o.key==="Escape"&&this.emit("keyup-escape")})}typeof window<"u"&&this.listen(window,"pagehide",()=>{this.flushPending(),i.flushKeepalive()}),typeof document<"u"&&this.contains(document.activeElement)&&this.emit("focus")}inputs;changes;paste;unregisterInputs;listeners=[];changeTimer=null;changeTime=0;changeSeq;composing=!1;destroyed=!1;contains(e){return this.inputs.some(t=>t===e)}length(){return this.inputs.reduce((e,t)=>e+t.value.length,0)}safe(e){try{e()}catch(t){this.logger.error("Failed to observe grouped input",t)}}listen(e,t,i){let r=o=>this.safe(()=>i(o));e.addEventListener(t,r),this.listeners.push(()=>e.removeEventListener(t,r))}cancelChange(){this.changeTimer!==null&&clearTimeout(this.changeTimer),this.changeTimer=null}flushChanges(){this.changeTimer!==null&&(this.cancelChange(),this.paste.pending||this.changes.record(this.length(),this.changeTime,this.composing,this.changeSeq),this.composing=!1)}emit(e){this.flushChanges(),this.changes.flush(),this.sink.enqueueLowEvent({lowType:e,ts:Date.now()})}capturePrefill(e=!1){this.destroyed||(this.flushPending(),this.changes.capturePrefill(this.length(),e))}flushPending(){this.paste.flush(),this.flushChanges(),this.changes.flush()}destroy(){this.destroyed||(this.destroyed=!0,this.safe(()=>{this.flushPending(),this.paste.destroy(),this.unregisterInputs?.();for(let e of this.listeners)e()}))}};var k=class{constructor(e,t,i){this.logger=e;this.inputSink=t;this.groupSink=i}collector;fields=[];grouped=!1;destroyed=!1;prefillClaimed=!1;setFields(e,t=!0){try{if(this.destroyed)return;let i=[...new Set(e)];if(t===this.grouped&&i.length===this.fields.length&&i.every((s,a)=>s===this.fields[a])||(this.collector?.destroy(),this.collector=void 0,this.fields=[],this.grouped=t,i.length===0))return;let r=t?this.groupSink:this.inputSink,o={...r,enqueueLowEvent:s=>this.enqueue(r,s)};this.collector=t?new Le(this.logger,i,o):new b(this.logger,i[0],o),this.fields=i}catch(i){this.logger.error("Failed to bind OTP inputs",i)}}enqueue(e,t){if(t.lowType==="input-prefill"){if(this.prefillClaimed)return;this.prefillClaimed=!0}else["input","input-idle","input-clear","input-paste","big-input-paste","big-input-add","big-input-rem"].includes(t.lowType)&&(this.prefillClaimed=!0);e.enqueueLowEvent(t)}capturePrefill(e=!1){e&&(this.prefillClaimed=!1),this.collector?.capturePrefill(e)}flushPending(){this.collector?.flushPending()}destroy(){this.destroyed=!0,this.collector?.destroy(),this.collector=void 0,this.fields=[]}};var J=class extends h{lowEventTracker;send;postResponse;resend;constructor(e,t={}){super(e,"email-otp"),this.send=this.defineStep("send"),this.postResponse=this.defineStep("post-response"),this.resend=this.defineStep("resend"),this.subflowStart({explicitSpecType:t.explicitSpecType,emailDomain:t.emailDomain}),this.lowEventTracker=this.createLowCollector(()=>new k(e.getLogger(),this.lowEventSink("input","otp"),this.lowEventSink("input-group","otp"))),t.inputHtmlFields?.length?this.setInputFields(t.inputHtmlFields):t.inputHtmlField&&this.lowEventTracker?.setFields([t.inputHtmlField],!1),this.registerLowFlusher(()=>this.lowEventTracker?.flushPending())}setInputFields(e){this.lowEventTracker?.setFields(e)}destroy(){this.lowEventTracker?.destroy()}};var X=class extends h{lowEventTracker;send;postResponse;resend;constructor(e,t={}){super(e,"sms-otp"),this.send=this.defineStep("send"),this.postResponse=this.defineStep("post-response"),this.resend=this.defineStep("resend"),this.subflowStart({explicitSpecType:t.explicitSpecType}),this.lowEventTracker=this.createLowCollector(()=>new k(e.getLogger(),this.lowEventSink("input","otp"),this.lowEventSink("input-group","otp"))),t.inputHtmlFields?.length?this.setInputFields(t.inputHtmlFields):t.inputHtmlField&&this.lowEventTracker?.setFields([t.inputHtmlField],!1),this.registerLowFlusher(()=>this.lowEventTracker?.flushPending())}setInputFields(e){this.lowEventTracker?.setFields(e)}destroy(){this.lowEventTracker?.destroy()}};var ki=["ahrefsbot","ahrefssiteaudit","amazonbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","facebookexternal","petalbot","pinterest","screaming frog","yahoo! slurp","yandex","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleweblight","mediapartners-google","storebot-google"];function Et(n){if(!n)return!1;let e=n.toLowerCase();return ki.some(t=>e.includes(t))}var Pe="@corbado/observe",Re="1.1.5";var Ct=require("uuid");var Qe="cbo_email_link_starts";function je(n,e){let t=n.getItem(Qe);return Array.isArray(t)?t.filter(i=>!!i&&typeof i=="object"&&typeof i.transactionId=="string"&&typeof i.anchor=="string"&&typeof i.sessionId=="string"&&typeof i.startedAt=="number"&&e-i.startedAt<864e5):[]}function xt(n,e){if(n)try{let t=je(n,e.startedAt).filter(i=>i.transactionId!==e.transactionId);t.push(e),n.setItem(Qe,t.slice(-10))}catch{}}function It(n,e,t=Date.now()){if(n)try{let i=je(n,t);if(e.transactionId)return i.find(o=>o.transactionId===e.transactionId);let r=i.filter(o=>!o.continued&&(!e.specType||!o.specType||o.specType===e.specType));return r[r.length-1]}catch{return}}function kt(n,e){if(n)try{let t=je(n,Date.now()).map(i=>i.transactionId===e?{...i,continued:!0}:i);n.setItem(Qe,t)}catch{}}var Z=class extends h{send;postResponse;resend;transactionId;constructor(e,t={}){super(e,"email-link"),this.send=this.defineStep("send"),this.postResponse=this.defineStep("post-response"),this.resend=this.defineStep("resend"),this.transactionId=t.transactionId||(0,Ct.v7)(),this.subflowStart({explicitSpecType:t.explicitSpecType},{userReference:{crossEnvironmentTransactionIDStart:this.transactionId}});let i=this.captureReference,r=this.captureSession;i&&r&&xt(e.getPersistentStorage(),{transactionId:this.transactionId,anchor:i,sessionId:r,specType:t.explicitSpecType,startedAt:Date.now()})}},ee=class extends h{postResponse;resend;mode;continuationTracker;specType;createdAt=Date.now();transaction;started=!1;deferred=[];onPageHide=()=>this.flush();constructor(e,t={}){super(e,"email-link"),this.continuationTracker=e,this.specType=t.explicitSpecType,this.transaction=t.transactionId,this.postResponse=this.deferrable(this.defineStep("post-response"),!0),this.resend=this.deferrable(this.defineStep("resend"));let i=e.getPersistentStorage(),r=It(i,{transactionId:t.transactionId,specType:t.explicitSpecType});if(r&&r.sessionId===e.getSessionId()){this.mode="attached",this.transaction=t.transactionId??r.transactionId,this.adoptCapture(r.anchor,r.sessionId,r.specType??t.explicitSpecType),this.started=!0;return}this.mode="detached",this.transaction?this.startDetached(this.createdAt):typeof window<"u"&&window.addEventListener("pagehide",this.onPageHide)}get transactionId(){return this.transaction}setTransactionId(e){!e||this.transaction||(this.transaction=e,this.mode==="detached"&&!this.started&&this.startDetached(this.firstDeferredAt()))}flush(){this.mode==="detached"&&!this.started&&this.startDetached(this.firstDeferredAt())}destroy(){this.flush(),this.removePageHideListener()}firstDeferredAt(){return this.deferred[0]?.at??this.createdAt}startDetached(e){this.started=!0,this.removePageHideListener(),this.subflowStart({explicitSpecType:this.specType,continuation:!0},{explicitTimestamp:e,...this.transaction?{userReference:{crossEnvironmentTransactionIDFinish:this.transaction}}:{}});let t=this.deferred;this.deferred=[];for(let i of t)i.run(i.at);try{this.continuationTracker.flushKeepalive()}catch{}}removePageHideListener(){typeof window<"u"&&window.removeEventListener("pagehide",this.onPageHide)}deferrable(e,t=!1){let i=(r,o)=>{if(this.started){r(o?.explicitTimestamp??Date.now());return}this.deferred.push({at:o?.explicitTimestamp??Date.now(),run:r})};return{start:(r,o)=>i(s=>e.start(r,{...o,explicitTimestamp:s}),o),finished:(r,o)=>{i(s=>e.finished(r,{...o,explicitTimestamp:s}),o),t&&this.transaction&&kt(this.continuationTracker.getPersistentStorage(),this.transaction)},error:(r,o)=>i(s=>e.error(r,{...o,explicitTimestamp:s}),o)}}};var te=class extends h{getOptions;ceremony;postResponse;lowEventTracker;constructor(e,t){super(e,"passkey-enrollment"),this.lowEventTracker=new N(e.getLogger(),this.lowEventSink("ceremony")),this.registerLowFlusher(()=>this.lowEventTracker.disarm()),this.getOptions=this.defineStep("get-options"),this.ceremony=this.withWindowLowEvents(this.defineStep("ceremony"),this.lowEventTracker),this.postResponse=this.defineStep("post-response"),this.subflowStart({explicitSpecType:t?.explicitSpecType,...t?.ignoreAsInteraction?{ignoreAsInteraction:!0}:{}})}destroy(){this.lowEventTracker.destroy()}};function Ye(n){let e=n.debug,t,i=(r,o)=>`[Corbado Observe SDK ${r}] ${o}`;return{reportTelemetry(r,o){if(t)try{t(r,o)}catch{}},setTelemetrySink(r){t=r},debug(r,...o){e&&console.log(i("DEBUG",r),...o)},info(r,...o){e&&console.log(i("INFO",r),...o)},warn(r,...o){e&&console.warn(i("WARN",r),...o)},error(r,...o){e&&console.error(i("ERROR",r),...o)},critical(r,...o){console.error(i("CRITICAL",r),...o)}}}var ie=class extends h{clientValidation;postResponse;cui;lowEventTracker;identifierLowEventTracker;constructor(e,t){super(e,"password-login"),this.clientValidation=this.defineStep("client-validation"),this.postResponse=this.defineStep("post-response"),this.cui={getOptions:this.defineStep("cui-get-options",!0),ceremony:this.defineStep("cui-ceremony"),postResponse:this.defineStep("cui-post-response")},this.subflowStart({explicitSpecType:t?.explicitSpecType}),t?.identifierInputHtmlField&&(this.identifierLowEventTracker=this.createLowCollector(()=>new b(e.getLogger(),t.identifierInputHtmlField,this.lowEventSink("input","identifier"))),this.registerLowFlusher(()=>this.identifierLowEventTracker?.flushPending())),t?.inputHtmlField&&(this.lowEventTracker=this.createLowCollector(()=>new b(e.getLogger(),t.inputHtmlField,this.lowEventSink("input","password"))),this.registerLowFlusher(()=>this.lowEventTracker?.flushPending()))}trigger(e,t){super.trigger(e,t)}destroy(){this.lowEventTracker?.destroy(),this.identifierLowEventTracker?.destroy()}};var re=class extends h{clientValidation;postResponse;lowEventTracker;constructor(e,t){super(e,"password-enrollment"),this.clientValidation=this.defineStep("client-validation"),this.postResponse=this.defineStep("post-response"),this.subflowStart({explicitSpecType:t?.explicitSpecType}),t?.inputHtmlField&&(this.lowEventTracker=this.createLowCollector(()=>new b(e.getLogger(),t.inputHtmlField,this.lowEventSink("input","password"))),this.registerLowFlusher(()=>this.lowEventTracker?.flushPending()))}destroy(){this.lowEventTracker?.destroy()}};var ne=class extends h{lowEventTracker;cui;provideIdentifier;constructor(e,t){super(e,"provide-identifier"),this.cui={trigger:(i,r)=>{this.trigger(i,r)},getOptions:this.defineStep("cui-get-options",!0),ceremony:this.defineStep("cui-ceremony"),postResponse:this.defineStep("cui-post-response")},this.provideIdentifier={trigger:(i,r)=>{this.trigger(i,r)},clientValidation:this.defineStep("pi-client-validation"),postResponse:this.defineStep("pi-post-response")},this.subflowStart({explicitSpecType:t?.explicitSpecType}),t?.inputHtmlField&&(this.lowEventTracker=this.createLowCollector(()=>new b(e.getLogger(),t.inputHtmlField,this.lowEventSink("input","identifier"))),this.registerLowFlusher(()=>this.lowEventTracker?.flushPending()))}destroy(){this.lowEventTracker?.destroy()}};var oe=class extends h{getRedirectUrl;exchangeCode;constructor(e,t={}){super(e,"social-login"),this.getRedirectUrl=this.defineStep("get-redirect-url"),this.exchangeCode=this.defineStep("exchange-code"),this.subflowStart({explicitSpecType:t.explicitSpecType})}};var se=class extends h{getRedirectUrl;exchangeCode;constructor(e,t={}){super(e,"sso-login"),this.getRedirectUrl=this.defineStep("get-redirect-url"),this.exchangeCode=this.defineStep("exchange-code");let{explicitSpecType:i,organizationDomain:r,actor:o}=Ci(t??{},e);this.subflowStart({explicitSpecType:i,organizationDomain:r,actor:o})}};function Ci(n,e){let t={...n},i=o=>{try{e.getLogger().warn(`SSO login: unsupported ${o}; omitted from telemetry`)}catch{}},r=t.organizationDomain;return r!==void 0&&(typeof r!="string"||r.includes("@")||r.length>253)&&(delete t.organizationDomain,i("organizationDomain")),t.actor!==void 0&&t.actor!=="user"&&t.actor!=="system"&&(delete t.actor,i("actor")),t}var ae=class extends h{lowEventTracker;postResponse;constructor(e,t={}){super(e,"totp"),this.postResponse=this.defineStep("post-response"),this.subflowStart({explicitSpecType:t.explicitSpecType}),this.lowEventTracker=this.createLowCollector(()=>new k(e.getLogger(),this.lowEventSink("input","otp"),this.lowEventSink("input-group","otp"))),t.inputHtmlFields?.length?this.setInputFields(t.inputHtmlFields):t.inputHtmlField&&this.lowEventTracker?.setFields([t.inputHtmlField],!1),this.registerLowFlusher(()=>this.lowEventTracker?.flushPending())}setInputFields(e){this.lowEventTracker?.setFields(e)}destroy(){this.lowEventTracker?.destroy()}};var le=class extends h{ceremony;retry;postResponse;constructor(e,t={}){super(e,"app-confirmation"),this.ceremony=this.defineStep("ceremony"),this.retry=this.defineStep("retry"),this.postResponse=this.defineStep("post-response"),this.subflowStart({explicitSpecType:t.explicitSpecType})}};var pe=class extends h{ceremony;postResponse;constructor(e,t={}){super(e,"captcha"),this.ceremony=this.defineStep("ceremony"),this.postResponse=this.defineStep("post-response"),this.subflowStart({explicitSpecType:t.explicitSpecType})}};function Je(n,e,t){if(n===null||typeof n!="object")return n;try{let i={...n};i.purpose===void 0&&e.purpose!==void 0&&(i.purpose=e.purpose),i.storage===void 0&&e.storage!==void 0&&(i.storage=e.storage),i.trustName===void 0&&e.trustName!==void 0&&(i.trustName=e.trustName);for(let[r,o]of[["bindingReference",255],["trustName",128]])if(typeof i[r]=="string"&&[...i[r]].length>o){delete i[r];try{t.getLogger().debug(`Trusted device: omitted ${r} exceeding ${o} characters`)}catch{}}return i}catch{return n}}function Fe(n,e,t){return{...n,start:(i,r)=>n.start(Je(i,e,t),r),finished:(i,r)=>n.finished(Je(i,e,t),r)}}var de=class extends h{getOptions;ceremony;postResponse;constructor(e,t){super(e,"trusted-device-check"),t=Ot(t,e);let i={purpose:t.purpose,storage:t.storage,trustName:t.trustName};this.getOptions=this.checkStep("get-options",i,e),this.ceremony=this.checkStep("ceremony",i,e),this.postResponse=this.checkStep("post-response",i,e),this.subflowStart({explicitSpecType:t.explicitSpecType,actor:"system",ignoreAsInteraction:!0})}checkStep(e,t,i){let r=this.defineStep(e,!0);return{...Fe(r,t,i),errorTyped:(o,s)=>{r.errorTyped(Je({code:o?.code,error:F(o?.error)},t,i),s)}}}},ue=class extends h{getOptions;ceremony;postResponse;constructor(e,t){super(e,"trusted-device-enrollment"),t=Ot(t,e);let i={purpose:t.purpose,storage:t.storage,trustName:t.trustName};this.getOptions=Fe(this.defineStep("get-options"),i,e),this.ceremony=Fe(this.defineStep("ceremony"),i,e),this.postResponse=Fe(this.defineStep("post-response"),i,e),this.subflowStart({explicitSpecType:t.explicitSpecType})}};function Ot(n,e){let t={...n},i=r=>{try{e.getLogger().warn(`Trusted device: missing or unsupported ${r}; omitted from telemetry`)}catch{}};return t.purpose!=="additional-verification"&&t.purpose!=="mfa-exemption"&&(delete t.purpose,i("purpose")),["cookie","indexeddb","localstore","sessionstore"].includes(t.storage)||(delete t.storage,i("storage")),t}var ce=class extends h{clientValidation;postResponse;lowEventTracker;constructor(e,t={}){super(e,"provide-data"),this.clientValidation=this.defineStep("client-validation"),this.postResponse=this.defineStep("post-response");let{inputHtmlField:i,...r}=t;this.subflowStart(r),i&&(this.lowEventTracker=this.createLowCollector(()=>new b(e.getLogger(),i,this.lowEventSink("input","data"))),this.registerLowFlusher(()=>this.lowEventTracker?.flushPending()))}destroy(){this.lowEventTracker?.destroy()}};var Oi={name:Pe,version:Re},Lt="cbo_session_id",Xe="cbo_session",R="cbo_seq",Pt="cbo_experiments",Rt="cbo_data_policy",Li=255,Pi=/^[A-Za-z0-9_-]+$/,Ri=128,Fi=256,Ft=1e3,Ai=50,Di="cbo_seq",At=1e3,Dt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,fe=class n{constructor(e){this.options=e;this.options.debug=e.debug??!1,this.logger=e.logger??Ye({debug:this.options.debug});let t=new W(this.logger),i=new j(this.logger),r=e.storage==="cookie",o=r?new Q(this.logger,e.cookieDomain):void 0;St(e.projectId,t,i,o,this.logger);let s=e.projectId,a=g=>new z(g,s);this.seqLockName=w(Di,s),this.sessionStorage=a(i),this.persistentStorage=a(t),this.storage=a(o??t),this.configOverrides={...e.sdkConfig,...e.sdkConfig?.retry&&{retry:{...e.sdkConfig.retry}},...e.sdkConfig?.flushOnFlowTypeFinished&&{flushOnFlowTypeFinished:[...e.sdkConfig.flushOnFlowTypeFinished]},...e.sdkConfig?.sourcePathQueryAllow&&{sourcePathQueryAllow:[...e.sdkConfig.sourcePathQueryAllow]}};let l=Object.keys(y).every(g=>this.configOverrides[g]!==void 0)&&Object.keys(y.retry).every(g=>this.configOverrides.retry?.[g]!==void 0);l||(this.configManager=new Oe(e.apiBaseUrl+(e.apiConfigPath??"/v1/observe/config")+"/"+e.projectId,this.persistentStorage,this.logger));let p=this.configManager?.initialConfig;this.config=Se(p,this.configOverrides),!l&&!p&&e.flushInterval!=null&&this.configOverrides.flushIntervalMs===void 0&&(this.config={...this.config,flushIntervalMs:e.flushInterval}),!l&&!p&&e.deviceInfoCollectorTimeout!=null&&this.configOverrides.deviceInfoCollectorTimeoutMs===void 0&&(this.config={...this.config,deviceInfoCollectorTimeoutMs:e.deviceInfoCollectorTimeout}),e.apiBaseUrl!==""&&(/^https?:\/\//.test(e.apiBaseUrl)||(this.logger.critical(`Invalid apiBaseUrl: URL must start with http:// or https:// (got: "${e.apiBaseUrl}")`),this.reportTelemetry("error","invalid apiBaseUrl: missing http(s) scheme")),e.apiBaseUrl.endsWith("/")&&(this.logger.critical(`Invalid apiBaseUrl: URL must not have a trailing slash (got: "${e.apiBaseUrl}")`),this.reportTelemetry("error","invalid apiBaseUrl: trailing slash")));let u=e.apiBaseUrl+(e.apiEventPath??"/v1/observe/events")+"/"+e.projectId;this.logger.debug(`Using API endpoint: ${u}`);let d=new Te({logger:this.logger,url:u});this.sessionId=this.resolveSessionId(),this.queue=new $(this.logger,d,this.sessionId,Oi,{debug:this.options.debug,config:this.config,requestConfig:!1,outboxLockName:w(we,s),getDataPolicy:()=>this.dataPolicy},this.persistentStorage),this.telemetryReady=!0,this.logger.setTelemetrySink?.((g,E)=>this.reportTelemetry(g,E));try{this.getWindowObserver()}catch(g){this.logger.error("Failed to attach page low-event observer",g)}let c=this.pendingSelfTelemetry;this.pendingSelfTelemetry=[];for(let g of c)this.telemetry(g.level,g.message);let f=new Ee(this.logger,this.storage,r?"cookie":"localstorage",this.sessionStorage,()=>({collectorTimeoutMs:this.config.deviceInfoCollectorTimeoutMs,timing:this.config.deviceInfoTiming}),(g,E)=>this.telemetry(g,E));this.deviceCollector=f;let m=e.deviceInfoDebounceTime??3e4;this.deviceInfoManager=new xe(this.logger,f,Math.max(1,m),m),this.deviceInfoManager.start(),this.experiments=this.loadPersistedExperiments(),e.experiments&&this.setExperiments(e.experiments),this.dataPolicy=this.loadPersistedDataPolicy(),e.dataPolicy!==void 0&&this.setDataPolicy(e.dataPolicy),this.configManager?.start(g=>this.handleConfig(g))}logger;queue;sessionId;storage;sessionStorage;persistentStorage;seqLockName;config;configManager;configOverrides;deviceInfoManager;deviceCollector;eventTabId;seq=0;lastActivityWriteAt=0;experiments={};dataPolicy;telemetryReporting=!1;telemetryReady=!1;reportedTelemetryKeys=new Set;pendingSelfTelemetry=[];windowObserver;getWindowObserver(){return this.windowObserver??=new me(this.logger,(e,t)=>this.enqueueLowEvent(e,t),()=>this.lowEventFlushKeepalive())}handleConfig(e){let t=Se(e,this.configOverrides);t.sessionContinuity||=this.config.sessionContinuity,t.durableOutbox||=this.config.durableOutbox,this.config=t,this.queue.updateConfig(this.config)}getLogger(){return this.logger}applicationTag(){return this.options.applicationId?{applicationId:this.options.applicationId.toLowerCase()}:{}}setExperiment(e,t){this.setExperiments({[e]:t})}setExperiments(e){try{if(!e||typeof e!="object")return;let t=!1;for(let[i,r]of Object.entries(e)){if(!n.isValidExperimentKey(i)||!n.isValidExperimentVariant(r)){this.logger.debug(`Ignoring invalid experiment assignment "${String(i)}"`);continue}this.experiments[i]!==r&&(this.experiments[i]=r,t=!0)}t&&this.persistExperiments()}catch(t){this.logger.error("Failed to set experiments",t)}}clearExperiment(e){try{Object.prototype.hasOwnProperty.call(this.experiments,e)&&(delete this.experiments[e],this.persistExperiments())}catch(t){this.logger.error("Failed to clear experiment",t)}}clearExperiments(){try{if(Object.keys(this.experiments).length===0)return;this.experiments={},this.persistExperiments()}catch(e){this.logger.error("Failed to clear experiments",e)}}getExperiments(){return{...this.experiments}}getPersistentStorage(){return this.persistentStorage}getSdkConfig(){return Object.freeze({version:this.config.version,aap:this.config.aap,rawErrors:this.config.rawErrors})}setDataPolicy(e){try{if(!n.isValidDataPolicy(e)){this.logger.debug(`Ignoring invalid data policy code "${String(e)}"`);return}this.dataPolicy!==e&&(this.dataPolicy=e,this.persistDataPolicy())}catch(t){this.logger.error("Failed to set data policy",t)}}getDataPolicy(){return this.dataPolicy}static isValidDataPolicy(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=Li}loadPersistedDataPolicy(){try{let e=this.persistentStorage.getItem(Rt);return n.isValidDataPolicy(e)?e:void 0}catch(e){this.logger.debug("Failed to load persisted data policy",e);return}}persistDataPolicy(){try{if(this.dataPolicy===void 0)return;this.persistentStorage.setItem(Rt,this.dataPolicy)}catch(e){this.logger.debug("Failed to persist data policy",e)}}static isValidExperimentKey(e){return typeof e=="string"&&e.length>0&&e.length<=Ri&&Pi.test(e)}static isValidExperimentVariant(e){return typeof e=="string"&&e.length>0&&e.length<=Fi}loadPersistedExperiments(){try{let e=this.persistentStorage.getItem(Pt);if(!e||typeof e!="object")return{};let t={};for(let[i,r]of Object.entries(e))n.isValidExperimentKey(i)&&n.isValidExperimentVariant(r)&&(t[i]=r);return t}catch(e){return this.logger.debug("Failed to load persisted experiments",e),{}}}persistExperiments(){try{this.persistentStorage.setItem(Pt,this.experiments)}catch(e){this.logger.debug("Failed to persist experiments",e)}}resolveExperiments(e){let t={...this.experiments};if(e&&typeof e=="object")for(let[i,r]of Object.entries(e))n.isValidExperimentKey(i)&&n.isValidExperimentVariant(r)&&(t[i]=r);return Object.keys(t).length>0?t:void 0}isTrackingBlocked(){return typeof navigator>"u"?!1:Et(navigator.userAgent)}resolveSessionId(){try{if(this.config.sessionContinuity)return this.getContinuitySessionId();let e=Date.now(),t=this.readPerTabSession();if(t&&e-t.lastActiveAt<this.perTabInactivityMs(t))return this.persistPerTabSession(t.id,e),this.seq=0,t.id;let i=(0,I.v7)();return this.persistPerTabSession(i,e),this.seq=0,this.logger.debug("Created session id",i),i}catch(e){return this.logger.error("Failed to get session id",e),this.reportTelemetry("error","failed to get session id"),""}}getContinuitySessionId(){let e=Date.now(),t=this.persistentStorage.getItem(Xe);if(t?.id&&e-t.lastActiveAt<this.config.sessionInactivityMs)return this.persistContinuitySession(t.id,e),this.seq=this.persistentStorage.getItem(R)??0,t.id;if(!t?.id){let r=this.readPerTabSession();if(r&&e-r.lastActiveAt<this.config.sessionInactivityMs)return this.persistContinuitySession(r.id,e),this.persistentStorage.setItem(R,0),this.seq=0,this.logger.debug("Adopted per-tab session id as continuity session",r.id),r.id}let i=(0,I.v7)();return this.persistContinuitySession(i,e),this.persistentStorage.setItem(R,0),this.seq=0,this.logger.debug("Created continuity session id",i),i}persistContinuitySession(e,t){this.lastActivityWriteAt=t,this.persistentStorage.setItem(Xe,{id:e,lastActiveAt:t})}readPerTabSession(){let e=this.sessionStorage.getItem(Lt);if(e){if(typeof e=="string")return Dt.test(e)?{id:e,lastActiveAt:Date.now()}:void 0;if(typeof e.lastActiveAt=="number")return Dt.test(e.id)?e:void 0}}persistPerTabSession(e,t){this.lastActivityWriteAt=t;let i=this.configOverrides.sessionInactivityMs!==void 0||this.config.version?this.config.sessionInactivityMs:this.readPerTabSession()?.inactivityMs;this.sessionStorage.setItem(Lt,{id:e,lastActiveAt:t,...i===void 0?{}:{inactivityMs:i}})}perTabInactivityMs(e){return this.configOverrides.sessionInactivityMs!==void 0?this.config.sessionInactivityMs:e.inactivityMs??this.config.sessionInactivityMs}nextSeq(){if(!this.config.sessionContinuity){let i=Date.now();return this.sessionId&&i-this.lastActivityWriteAt>=At&&this.persistPerTabSession(this.sessionId,i),this.seq++}let e=()=>{let i=Date.now(),r=this.persistentStorage.getItem(Xe),o=!1;if(!r?.id&&this.sessionId)this.persistContinuitySession(this.sessionId,i);else if(r?.id)i-this.lastActivityWriteAt>=At&&this.persistContinuitySession(r.id,i),r.id!==this.sessionId&&(this.sessionId=r.id,this.queue.setSessionId(r.id),o=!0);else{let l=(0,I.v7)();this.persistContinuitySession(l,i),this.persistentStorage.setItem(R,0),this.sessionId=l,this.queue.setSessionId(l),this.seq=0,o=!0}let s=this.persistentStorage.getItem(R);o&&(this.seq=typeof s=="number"?s:0);let a=typeof s=="number"&&s>this.seq?s:this.seq;return this.seq=a+1,this.persistentStorage.setItem(R,this.seq),a},t=this.config.seqLockTimeoutMs;return t===0||typeof navigator>"u"||!navigator.locks?.request?e():be(this.seqLockName,e,{timeoutMs:t,onTimeout:()=>{this.logger.warn(`Sequence Web Lock acquisition timed out after ${t}ms; using fallback`),this.reportTelemetry("info",`seq web lock timeout; using fallback, ${t}ms`)}})}resolveTrackingSourcePath(){if(typeof window>"u")return;let e=lt(window.location.search,this.config.sourcePathQuery,this.config.sourcePathQueryAllow);return`${window.location.pathname}${e}`}resolveEventTabId(){return this.eventTabId===void 0&&(this.eventTabId=this.deviceCollector.getTabId()),this.eventTabId}trackSubflowStarted(e,t,i,r){let o={subflowType:e,...t};this.track("subflow_started",o,i?.userReference,void 0,void 0,i?.explicitTimestamp,i?.experiments,{id:r,subflowStartEventId:i?.subflowStartEventId,sessionId:i?.captureSessionId,initiator:i?.initiator})}trackSubflowTrigger(e,t,i){let r={subflowType:e,...t};this.track("subflow_trigger",r,i?.userReference,void 0,void 0,i?.explicitTimestamp,i?.experiments,{subflowStartEventId:i?.subflowStartEventId,sessionId:i?.captureSessionId,initiator:i?.initiator})}trackSubflowStepStarted(e,t,i,r,o){let s={subflowType:e,stepName:t,stepData:i,identifier:r?.identifier,ignoreAsInteraction:o};this.track("subflow_step_started",s,r?.userReference,void 0,void 0,r?.explicitTimestamp,r?.experiments,{subflowStartEventId:r?.subflowStartEventId,sessionId:r?.captureSessionId,initiator:r?.initiator})}trackSubflowStepFinished(e,t,i,r){let o={subflowType:e,stepName:t,stepData:i,identifier:r?.identifier};this.track("subflow_step_finished",o,r?.userReference,void 0,void 0,r?.explicitTimestamp,r?.experiments,{subflowStartEventId:r?.subflowStartEventId,sessionId:r?.captureSessionId,initiator:r?.initiator})}trackSubflowStepError(e,t,i,r){let o={subflowType:e,stepName:t,stepData:i,identifier:r?.identifier};this.track("subflow_step_error",o,r?.userReference,void 0,void 0,r?.explicitTimestamp,r?.experiments,{subflowStartEventId:r?.subflowStartEventId,sessionId:r?.captureSessionId,initiator:r?.initiator})}trackSubflowError(e,t,i){let r={subflowType:e,stepData:t};this.track("subflow_error",r,i?.userReference,void 0,void 0,i?.explicitTimestamp,i?.experiments,{subflowStartEventId:i?.subflowStartEventId,sessionId:i?.captureSessionId,initiator:i?.initiator})}async track(e,t,i,r,o,s,a,l){try{if(this.isTrackingBlocked()){this.logger.debug(`Skipping event "${e}" for blocked user agent.`);return}(e==="flow_finished"||e==="flow_auto_finished"||e==="flow_reset")&&this.windowObserver?.flushInputs();let p=s??Date.now(),u=l?.id??(0,I.v7)(),d=l?.sessionId??this.sessionId,c=this.nextSeq(),f=typeof c=="number"?c:await c,m=this.resolveTrackingSourcePath(),g={type:"predefined",name:e,id:u,timestamp:p,seq:f,data:t,user:i,contexts:o,tags:r,experiments:this.resolveExperiments(a),meta:{captureVersion:1,pageId:ye(),initiator:l?.initiator,trackingSourcePath:m??"",subflowStartEventId:l?.subflowStartEventId,tabId:this.resolveEventTabId()}},E=this.deviceInfoManager.getForEvent();E&&(g.deviceInfo=E),this.logger.debug(`Track: ${e}`,JSON.stringify(g,null,2)),this.queue.enqueue(g,d)}catch(p){this.logger.error(`Failed to process event "${e}" before enqueue`,p),this.reportTelemetry("error",`failed to process event "${e}" before enqueue`)}}flowStarted(e,t,i,r){try{let o=(0,I.v7)(),s=this.sessionId,a={...this.options.defaultTags,...this.applicationTag(),...t};return this.track("flow_started",e,void 0,a,r,void 0,i,{id:o,sessionId:s}),this.flowHandle(o,s)}catch(o){return this.logger.warn("Failed to start flow",o),{enrich:async()=>{}}}}flowDecided(e,t,i){this.track("flow_decided",e,void 0,t,void 0,void 0,i)}conversion(e,t,i){let{userId:r,identifier:o,crossEnvironmentTransactionID:s,...a}=e,l={userId:r,identifier:o,crossEnvironmentTransactionID:s},p={...this.options.defaultTags,...this.applicationTag(),...t};this.track("conversion",a,l,p,void 0,void 0,i)}flowFinished(e,t,i){try{let{userId:r,identifier:o,...s}=e,a={userId:r,identifier:o},l=(0,I.v7)(),p=this.sessionId;return this.track("flow_finished",s,a,t,void 0,void 0,i,{id:l,sessionId:p}),this.flowHandle(l,p)}catch(r){return this.logger.warn("Failed to finish flow",r),{enrich:async()=>{}}}}flowHandle(e,t){return{enrich:async i=>{try{await this.track("flow_enriched",{targetEventId:e},{...i},void 0,void 0,void 0,void 0,{sessionId:t})}catch(r){this.logger.warn("Failed to enrich flow",r)}}}}flowReset(e,t,i){this.track("flow_reset",e,void 0,t,void 0,void 0,i)}flowAutoFinished(e,t,i){let{userId:r,identifier:o,...s}=e,a={userId:r,identifier:o};this.track("flow_auto_finished",s,a,t,void 0,void 0,i)}setUser(e){this.track("flow_enriched",{match:{flowType:"*",at:"during"},expFol:!0},{...e})}setFlowTags(e,t){try{if(!e||typeof e!="object"){this.logger.warn("setFlowTags: ignoring non-object tags");return}let i={};for(let[o,s]of Object.entries(e)){if(o===""||typeof s!="string"){this.logger.warn(`setFlowTags: ignoring invalid tag "${o}"`);continue}i[o]=s}if(Object.keys(i).length===0)return;let r={match:{flowType:t?.flowType??"*",at:"during"}};t?.expandToChildren!==void 0&&(r.expCh=t.expandToChildren),t?.expandToFollowing!==void 0&&(r.expFol=t.expandToFollowing),this.track("flow_enriched",r,void 0,i)}catch(i){this.logger.warn("Failed to set flow tags",i)}}authMethodsDecisionStarted(e,t,i,r){this.track("auth_method_decision_started",e,void 0,t,void 0,r?.explicitTimestamp,i)}authMethodsDecisionFinished(e,t,i){this.track("auth_method_decision_finished",e,void 0,t,void 0,void 0,i)}authDecisionStarted(e,t,i){this.track("auth_decision_started",e,void 0,t,void 0,void 0,i)}authDecisionFinished(e,t,i){this.track("auth_decision_finished",e,void 0,t,void 0,void 0,i)}enqueueLowEvent(e,t){try{if(this.isTrackingBlocked()){this.logger.debug(`Skipping low event "${e.lowType}" for blocked user agent.`);return}this.queue.enqueueLow({...e,captureSeq:e.captureSeq??x(),captureVersion:1,pageId:e.pageId??ye()},t)}catch(i){this.logger.error(`Failed to process low event "${e.lowType}" before enqueue`,i)}}telemetry(e,t){try{if(this.isTrackingBlocked()){this.logger.debug("Skipping telemetry for blocked user agent.");return}let i=typeof t=="string"?t:String(t);if(i.length===0)return;let r={id:(0,I.v7)(),level:e,message:i.length>Ft?i.slice(0,Ft):i,ts:Date.now()};this.queue.enqueueTelemetry(r)}catch(i){this.logger.error("Failed to process telemetry before enqueue",i)}}logInfo(e){this.telemetry("info",e)}logError(e){this.telemetry("error",e)}reportTelemetry(e,t){if(!this.telemetryReporting){this.telemetryReporting=!0;try{if(this.reportedTelemetryKeys.has(t)||this.reportedTelemetryKeys.size>=Ai)return;if(this.reportedTelemetryKeys.add(t),!this.telemetryReady){this.pendingSelfTelemetry.push({level:e,message:t});return}this.telemetry(e,t)}catch{}finally{this.telemetryReporting=!1}}}flushKeepalive(e="manual"){try{this.queue.flushKeepalive(e)}catch(t){this.logger.error("Failed to flush queue keepalive",t)}}lowEventFlushKeepalive(){this.config.tlf&&this.flushKeepalive("low-event-teardown")}passkeyLoginFullOperation(e){return new Y(this,e)}passkeyEnrollmentFullOperation(e){return new te(this,e)}passwordLoginFullOperation(e){return new ie(this,e)}passwordEnrollmentFullOperation(e){return new re(this,e)}emailLinkOperationFull(e){return new Z(this,e)}continueEmailLinkOperation(e){return new ee(this,e)}emailOtpOperationFull(e){return new J(this,e)}smsOtpOperationFull(e){return new X(this,e)}totpOperationFull(e){return new ae(this,e)}provideIdentifierOperationFull(e){return new ne(this,e)}provideDataOperationFull(e){return new ce(this,e)}socialLoginOperationFull(e){return new oe(this,e)}ssoLoginOperationFull(e){return new se(this,e)}appConfirmationOperationFull(e){return new le(this,e)}keySigningOperationFull(e){return new K(this,e)}keyRegistrationOperationFull(e){return new V(this,e)}captchaOperationFull(e){return new pe(this,e)}trustedDeviceCheckOperationFull(e){return new de(this,e)}trustedDeviceEnrollmentOperationFull(e){return new ue(this,e)}async destroy(){if(this.configManager?.destroy(),this.windowObserver?.destroy(),this.deviceInfoManager.destroy(),this.config.td)try{await this.queue.flush("destroy")}catch(e){this.logger.error("Failed to flush queue during destroy",e)}this.queue.destroy()}getSessionId(){if(!this.sessionId){let e=this.resolveSessionId();e&&(this.sessionId=e,this.queue.setSessionId(e))}return this.sessionId||void 0}resetSession(){let e=(0,I.v7)();return this.config.sessionContinuity?(this.persistContinuitySession(e,Date.now()),this.persistentStorage.setItem(R,0)):this.persistPerTabSession(e,Date.now()),this.sessionId=e,this.seq=0,this.queue.setSessionId(e),this.logger.debug(`Session reset: ${e}`),e}};var _i={creationOptions:["/user/name","/user/displayName"],creationResponse:["/clientExtensionResults/prf/results"],requestOptions:[],assertionResponse:["/response/signature","/clientExtensionResults/prf/results"]};function _t(n){return Ae(n,"creationOptions")}function Mt(n){return Ae(n,"creationResponse")}function Ht(n){return Ae(n,"requestOptions")}function Nt(n){return Ae(n,"assertionResponse")}function Ae(n,e){try{let t=typeof n=="string"?JSON.parse(n):n;if(!Mi(t))return;let i=new Set(_i[e]),r=new Set,o=(s,a,l=0)=>{if(!i.has(a)){if(s===null||typeof s=="string"||typeof s=="boolean")return s;if(typeof s=="number")return Number.isFinite(s)?s:null;if(typeof s=="object"){if(s instanceof ArrayBuffer||ArrayBuffer.isView(s))return Hi(s);if(l>64||r.has(s))throw new TypeError("Invalid telemetry payload");r.add(s);try{if(Array.isArray(s))return s.map((c,f)=>o(c,`${a}/${f}`,l+1));let p=Object.create(null);for(let c in s){let f=`${a}/${c.replace(/~/g,"~0").replace(/\//g,"~1")}`;if(i.has(f)||c==="toJSON")continue;let m=o(s[c],f,l+1);m!==void 0&&(p[c]=m)}let u=s,d=(c,f)=>{if(p[f]!==void 0||typeof u[c]!="function")return;let m=`${a}/${f}`,g=o(Reflect.apply(u[c],s,[]),m,l+1);g!==void 0&&(p[f]=g)};return a===""&&(e==="creationResponse"||e==="assertionResponse")&&d("getClientExtensionResults","clientExtensionResults"),a==="/response"&&e==="creationResponse"&&(d("getTransports","transports"),d("getAuthenticatorData","authenticatorData"),d("getPublicKey","publicKey"),d("getPublicKeyAlgorithm","publicKeyAlgorithm")),p}finally{r.delete(s)}}}};return JSON.stringify(o(t,""))}catch{return}}function Mi(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)&&!(n instanceof ArrayBuffer)&&!ArrayBuffer.isView(n)}function Hi(n){let e=n instanceof ArrayBuffer?new Uint8Array(n):new Uint8Array(n.buffer,n.byteOffset,n.byteLength),t="";for(let i of e)t+=String.fromCharCode(i);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}var T;function Ni(n){let e=new fe(n);return T=e,e}function Ui(){return T}function Bi(){return T?.resetSession()}function qi(){return T?.getSessionId()}function Ki(n){T?.setUser(n)}function Vi(n,e){T?.setFlowTags(n,e)}function $i(n,e){T?.setExperiment(n,e)}function Gi(n){T?.setExperiments(n)}function zi(n){T?.clearExperiment(n)}function Wi(){T?.clearExperiments()}function Qi(){return T?.getExperiments()??{}}function ji(n,e){T?.telemetry(n,e)}function Yi(n){T?.logInfo(n)}function Ji(n){T?.logError(n)}async function Xi(){T&&(await T.destroy(),T=void 0)}0&&(module.exports={AppConfirmationOperationFull,AuthEventName,CEREMONY_LOW_EVENT_TAIL_MS,CONFIG_BOUNDS,CONFIG_REQUEST_HEADER,CONFIG_STORAGE_KEY,CaptchaOperationFull,CookieStorage,CorbadoTracker,DEFAULT_DEVICE_INFO_COLLECTOR_TIMEOUT_MS,DEFAULT_FLUSH_INTERVAL_MS,DEFAULT_MAX_ENTRIES,DEFAULT_MAX_SERIALIZED_LENGTH,DEFAULT_RELIABILITY_CONFIG,DEFAULT_SEQ_LOCK_TIMEOUT_MS,DEFAULT_SESSION_INACTIVITY_MS,EmailLinkContinuationOperation,EmailLinkOperationFull,EmailOtpOperationFull,EventStore,KeyRegistrationOperationFull,KeySigningOperationFull,LocalStorage,NamespacedStorage,OUTBOX_LOCK_NAME,OUTBOX_STORAGE_KEY,OperationFull,OperationFullProvideIdentifierWithCUI,PasskeyEnrollmentOperationFull,PasskeyLoginOperationFull,PasswordEnrollmentOperationFull,PasswordLoginOperationFull,ProvideDataOperationFull,RAW_ERROR_BOUNDS,RequestQueue,SDK_NAME,SDK_VERSION,SessionStorage,SmsOtpOperationFull,SocialLoginOperationFull,SsoLoginOperationFull,TotpOperationFull,TrustedDeviceCheckOperationFull,TrustedDeviceEnrollmentOperationFull,cacheConfig,clearExperiment,clearExperiments,createLogger,destroy,getExperiments,getSessionId,getTracker,init,loadCachedConfig,logError,logInfo,namespacedKey,parseReliabilityConfig,resetSession,resolveRawErrorLimits,resolveReliabilityConfig,sanitizeAssertionResponse,sanitizeCreationOptions,sanitizeCreationResponse,sanitizeRequestOptions,serializeRawError,setExperiment,setExperiments,setFlowTags,setUser,telemetry});
|