@sendoracloud/sdk-web 3.20.0 → 3.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var ae=Object.defineProperty;var Oe=Object.getOwnPropertyDescriptor;var Me=Object.getOwnPropertyNames;var Fe=Object.prototype.hasOwnProperty;var He=(n,e)=>{for(var t in e)ae(n,t,{get:e[t],enumerable:!0})},Ke=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Me(e))!Fe.call(n,s)&&s!==t&&ae(n,s,{get:()=>e[s],enumerable:!(r=Oe(e,s))||r.enumerable});return n};var Ve=n=>Ke(ae({},"__esModule",{value:!0}),n);var It={};He(It,{AlreadyIdentifiedError:()=>K,Analytics:()=>N,Audiences:()=>W,Auth:()=>V,AuthError:()=>c,Chatbot:()=>F,Consent:()=>H,CredentialInUseError:()=>D,EmailAlreadyTakenError:()=>C,FeatureFlags:()=>x,InAppMessaging:()=>M,LinkError:()=>p,Links:()=>B,SendoraCloud:()=>te,Surveys:()=>O,ValidationError:()=>f,WebPush:()=>$,default:()=>St,extractShortcodeFromUrl:()=>Ue,safeUrl:()=>I,sanitizeHtml:()=>Q});module.exports=Ve(It);var ge=/^[a-zA-Z][a-zA-Z0-9._:-]{0,127}$/;var $e=new Set(["__proto__","constructor","prototype"]),f=class extends Error{constructor(e){super(`[SendoraCloud] ${e}`),this.name="SendoraValidationError"}};function fe(n){if(typeof n!="string"||!ge.test(n))throw new f(`Invalid event name: must match ${ge}, got "${String(n)}".`)}function me(n){if(n==null)return;if(typeof n!="object"||Array.isArray(n))throw new f("Properties must be a plain object, not an array or primitive.");let e=ye(n);if(e>5)throw new f(`Properties nested too deeply (${e} levels, max 5).`);ve(n);let t;try{t=JSON.stringify(n).length}catch{throw new f("Properties contain a circular reference or unserializable value.")}if(t>32768)throw new f(`Properties too large (${t} bytes, max 32768).`)}function ye(n,e=0){if(e>6||n==null||typeof n!="object")return e;let t=e;for(let r of Object.keys(n)){let s=ye(n[r],e+1);s>t&&(t=s)}return t}function ve(n){if(!(n==null||typeof n!="object"))for(let e of Object.keys(n)){if($e.has(e))throw new f(`Forbidden property key "${e}" (prototype pollution guard).`);ve(n[e])}}var We=/^pk_[A-Za-z0-9_-]{16,}$/;function we(n){if(!n||typeof n!="string")throw new f("apiKey is required.");if(n.startsWith("sk_")||n.startsWith("sendora_secret_"))throw new f("Secret keys must NEVER be used in browser SDK. Use a publishable key (pk_...).");if(!We.test(n))throw new f("Invalid publishable key format. Expected pk_... (17+ chars).")}function ke(n){let e=n.replace(/\/$/,"");if(!(e.startsWith("http://localhost")||e.startsWith("http://127.0.0.1"))&&!e.startsWith("https://"))throw new f("apiUrl must be https:// (only http://localhost is allowed for dev).")}var Ae={name:"@sendoracloud/sdk-web",version:"3.20.0",description:"Sendora Cloud Web SDK \u2014 analytics, feature flags, surveys, in-app messaging, chatbot, auth, deep links (Branch / Firebase parity). Zero dependencies, TypeScript, SSR-safe.",type:"module",main:"./dist/index.cjs",module:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"}},files:["dist","README.md","LICENSE"],keywords:["sendora","analytics","feature-flags","surveys","in-app-messaging","chatbot","tracking","customer-engagement"],homepage:"https://sendoracloud.com/sdks",repository:{type:"git",url:"git+https://github.com/sendoracloud/sdk-web.git"},bugs:{url:"https://github.com/sendoracloud/sdk-web/issues"},author:"Sendora Cloud <hello@sendoracloud.com>",license:"Apache-2.0",publishConfig:{access:"public"},sideEffects:!1,scripts:{build:"tsup src/index.ts --format cjs,esm --dts --clean --minify",typecheck:"tsc --noEmit",prepublishOnly:"npm run build"},devDependencies:{typescript:"^5.4.0",tsup:"^8.0.0"}};var E=Ae.version;var qe="https://api.sendoracloud.com",ze=1e4,je="@sendoracloud/sdk-web",Y=class{constructor(e){let t=(e.apiUrl??qe).replace(/\/$/,"");ke(t),this.apiKey=e.apiKey,this.baseUrl=t,this.debug=!!e.debug}get(e,t){return this.request("GET",e,void 0,t)}post(e,t,r){return this.request("POST",e,t,r)}patch(e,t,r){return this.request("PATCH",e,t,r)}delete(e,t){return this.request("DELETE",e,void 0,t)}async request(e,t,r,s){let i=`${this.baseUrl}/api/v1${t}`,o=typeof AbortController<"u"?new AbortController:null,a=o?setTimeout(()=>o.abort(),ze):null;try{let u=await fetch(i,{method:e,headers:{"Content-Type":"application/json","X-API-Key":this.apiKey,"X-Sendora-SDK-Name":je,"X-Sendora-SDK-Version":E,...s??{}},body:r?JSON.stringify(r):void 0,signal:o?o.signal:void 0});a&&clearTimeout(a);let l;try{l=await u.json()}catch{l={success:!1,error:{code:"PARSE_ERROR",message:`HTTP ${u.status}`}}}if(this.debug&&console.debug(`[SendoraCloud] ${e} ${t} \u2192 ${u.status}`),!u.ok){if(t.startsWith("/auth-service/")&&!this.debug)console.warn(`[SendoraCloud] ${e} ${t} \u2192 HTTP ${u.status}`);else{let v=l?.error?.code??"HTTP_ERROR",w=l?.error?.message??`HTTP ${u.status}`,k=l?.error?.details?.fieldErrors,L=k?` (${Object.entries(k).map(([A,ne])=>`${A}: ${(ne??[]).join(", ")}`).join("; ")})`:"";console.warn(`[SendoraCloud] ${e} ${t} \u2192 HTTP ${u.status} \u2014 ${v}: ${w}${L}`)}l&&l.error&&(l.error={...l.error,status:u.status})}return l}catch(u){a&&clearTimeout(a);let l=u instanceof Error&&u.name==="AbortError"?"timeout":"error";return console.warn(`[SendoraCloud] ${e} ${t} network ${l}`),{success:!1,error:{code:"NETWORK_ERROR",message:l}}}}};var Ge="sendora_",X=class{constructor(e){this.memoryStore=new Map;this.useLocalStorage=this.checkLocalStorage(),this.prefix=e??Ge}get(e){let t=this.prefix+e;if(this.useLocalStorage)try{return localStorage.getItem(t)}catch{return this.memoryStore.get(t)??null}return this.memoryStore.get(t)??null}set(e,t){let r=this.prefix+e;if(this.useLocalStorage)try{localStorage.setItem(r,t);return}catch{}this.memoryStore.set(r,t)}remove(e){let t=this.prefix+e;if(this.useLocalStorage)try{localStorage.removeItem(t)}catch{}this.memoryStore.delete(t)}clearPrefix(e){let t=this.prefix+e;if(this.useLocalStorage)try{for(let r=localStorage.length-1;r>=0;r--){let s=localStorage.key(r);s&&s.startsWith(t)&&localStorage.removeItem(s)}}catch{}for(let r of Array.from(this.memoryStore.keys()))r.startsWith(t)&&this.memoryStore.delete(r)}checkLocalStorage(){try{if(typeof localStorage>"u")return!1;let e="__sendora_test__";return localStorage.setItem(e,"1"),localStorage.removeItem(e),!0}catch{return!1}}};function U(n=""){let e=new Uint8Array(16),t=typeof globalThis<"u"&&"crypto"in globalThis?globalThis.crypto:void 0;if(!t||typeof t.getRandomValues!="function")throw new Error("[SendoraCloud] crypto.getRandomValues unavailable \u2014 refusing to mint IDs without a CSPRNG");t.getRandomValues(e);let r="";for(let s of e)r+=s.toString(16).padStart(2,"0");return n+r}var Se=500,ce=10,ue=6e4,N=class{constructor(e,t,r,s){this.queue=[];this.timer=null;this.userId=null;this.identityToken=null;this.consecutiveFailures=0;this.nextFlushAfter=0;this.breakerOpenAt=0;this.breakerWarned=!1;this.http=t,this.storage=r,this.consent=s,this.projectId=e.projectId,this.flushInterval=e.flushInterval??5e3,this.maxQueueSize=e.maxQueueSize??20,this.persistUserId=!!e.persistUserId,this.stripQueryParams=e.stripQueryParams!==!1,this.appVersion=e.appVersion,this.storage.get("schema_version")===null&&this.storage.set("schema_version","1");let i=this.storage.get("anonymous_id");if(i?this.anonymousId=i:(this.anonymousId=U("anon_"),this.storage.set("anonymous_id",this.anonymousId)),this.persistUserId){let o=this.storage.get("user_id");o&&(this.userId=o)}this.timer=setInterval(()=>this.flush(),this.flushInterval),typeof window<"u"&&window.addEventListener("beforeunload",()=>this.flush()),this.consent.subscribe(o=>{o&&this.flush()})}track(e,t){fe(e),t&&me(t),this.queue.length>=Se&&this.queue.shift(),this.queue.push({eventType:e,properties:t??{},userId:this.userId??void 0,anonymousId:this.anonymousId,timestamp:new Date().toISOString(),identityToken:this.identityToken??void 0}),this.queue.length>=this.maxQueueSize&&this.flush()}page(e){if(typeof window>"u")return;let t=this.stripQueryParams?window.location.origin+window.location.pathname:window.location.href;this.track("page.viewed",{url:t,path:window.location.pathname,title:document.title,referrer:document.referrer||void 0,...e})}identify(e,t,r){if(typeof e!="string"||e.length===0||e.length>256)throw new Error("[SendoraCloud] userId must be a 1-256 char string.");this.userId=e,this.identityToken=r?.identityToken??null,this.persistUserId&&this.storage.set("user_id",e),this.track("user.identified",{...t})}reset(){this.userId=null,this.identityToken=null,this.storage.remove("user_id"),this.anonymousId=U("anon_"),this.storage.set("anonymous_id",this.anonymousId),this.storage.clearPrefix("iam_shown_"),this.storage.clearPrefix("survey_shown_")}dropQueue(){this.queue=[]}async flush(){if(this.queue.length===0||!this.consent.isGranted()||Date.now()<this.nextFlushAfter)return;this.consecutiveFailures>ce&&Date.now()-this.breakerOpenAt>=ue&&(this.consecutiveFailures=0,this.breakerOpenAt=0,this.breakerWarned=!1);let e=this.queue.splice(0,100),t=this.getSessionId(),r=e.map(a=>({projectId:this.projectId,module:"custom",eventType:a.eventType,userId:a.userId,anonymousId:a.anonymousId,identityToken:a.identityToken,timestamp:a.timestamp??new Date().toISOString(),properties:a.properties??{},context:this.getContext(),...t?{sessionId:t}:{},consent:["analytics"]}));if((await this.http.post("/events/batch",{events:r})).success){this.consecutiveFailures=0,this.breakerOpenAt=0,this.breakerWarned=!1;return}if(this.consecutiveFailures++,this.consecutiveFailures>ce){this.breakerWarned||(this.breakerOpenAt=Date.now(),this.breakerWarned=!0,console.warn(`[SendoraCloud] Analytics circuit breaker open after ${ce} consecutive failed flushes \u2014 events will be dropped until a flush succeeds or ${ue}ms elapse.`));return}let i=Math.min(ue,1e3*2**this.consecutiveFailures);this.nextFlushAfter=Date.now()+i;let o=Math.max(0,Se-this.queue.length);o>0&&this.queue.unshift(...e.slice(0,o))}destroy(){this.timer&&clearInterval(this.timer),this.timer=null,this.flush()}getSessionId(){try{return typeof sessionStorage>"u"?void 0:sessionStorage.getItem("sendora_session_id")||void 0}catch{return}}getContext(){return typeof window>"u"?{sdk:{name:"@sendoracloud/sdk-web",version:E}}:{page:{url:this.stripQueryParams?window.location.origin+window.location.pathname:window.location.href,path:window.location.pathname,title:document.title},referrer:document.referrer||void 0,locale:typeof navigator<"u"?navigator.language:void 0,device:this.buildDevice(),sdk:{name:"@sendoracloud/sdk-web",version:E}}}buildDevice(){if(typeof navigator>"u")return;let e=navigator.userAgent||"",r=navigator.userAgentData?.mobile??/Mobi|Android|iPhone|iPod/i.test(e);return{type:/iPad|Tablet|(?:Android(?!.*Mobile))/i.test(e)?"tablet":r?"mobile":"desktop",os:"Web",osVersion:"",model:"",appVersion:this.resolveAppVersion(),browser:Ye(e)}}resolveAppVersion(){if(this.appVersion)return this.appVersion;if(typeof document<"u"){let r=document.querySelector('meta[name="sendora:app-version"]')?.getAttribute("content");if(r)return r}let e=globalThis.__SENDORA_APP_VERSION__;return typeof e=="string"?e:""}};function Ye(n){let e=[["Edge",/Edg\/(\d+)/],["Opera",/OPR\/(\d+)/],["Firefox",/Firefox\/(\d+)/],["Samsung Internet",/SamsungBrowser\/(\d+)/],["Chrome",/Chrome\/(\d+)/],["Safari",/Version\/(\d+)[^ ]* Safari/]];for(let[t,r]of e){let s=r.exec(n);if(s)return`${t} ${s[1]}`}return"Unknown"}var x=class{constructor(e,t,r){this.cache=new Map;this.refreshInterval=null;this.http=t,this.storage=r;let s=this.storage.get("flags");if(s)try{let i=JSON.parse(s);if(Array.isArray(i))for(let o of i)le(o)&&this.cache.set(o.key,o)}catch{}}setContext(e){this.userId=e.userId,this.entityId=e.entityId,this.environment=e.environment}async getFlag(e){if(typeof e!="string"||e.length===0||e.length>128)return null;let t=this.cache.get(e);if(t)return t.value;let r=await this.http.post("/feature-flags/evaluate",{key:e,userId:this.userId,entityId:this.entityId,environment:this.environment});return r.success&&r.data&&le(r.data)?(this.cache.set(e,r.data),this.persistCache(),r.data.value):null}async isEnabled(e,t=!1){let r=await this.getFlag(e);return typeof r=="boolean"?r:t}async refreshAll(){let e=await this.http.post("/feature-flags/evaluate-all",{userId:this.userId,entityId:this.entityId,environment:this.environment});if(e.success&&Array.isArray(e.data)){this.cache.clear();for(let t of e.data)le(t)&&this.cache.set(t.key,t);this.persistCache()}}startAutoRefresh(e=6e4){this.stopAutoRefresh(),this.refreshAll(),this.refreshInterval=setInterval(()=>this.refreshAll(),e)}stopAutoRefresh(){this.refreshInterval&&clearInterval(this.refreshInterval),this.refreshInterval=null}getAllFlags(){let e={};for(let[t,r]of this.cache)e[t]=r.value;return e}reset(){this.cache.clear(),this.storage.remove("flags"),this.userId=void 0,this.entityId=void 0,this.environment=void 0}destroy(){this.stopAutoRefresh()}persistCache(){this.storage.set("flags",JSON.stringify(Array.from(this.cache.values())))}};function le(n){if(n==null||typeof n!="object")return!1;let e=n;return Object.prototype.hasOwnProperty.call(e,"__proto__")||Object.prototype.hasOwnProperty.call(e,"constructor")?!1:typeof e.key=="string"&&"value"in e}var Xe=32*1024,O=class{constructor(e,t,r){this.activeSurvey=null;this.http=t,this.storage=r}onDisplay(e){this.onSurveyDisplay=e}async showSurvey(e){if(typeof e!="string"||!/^[A-Za-z0-9_-]{6,64}$/.test(e))return null;let t=`survey_shown_${e}`;if(this.storage.get(t))return null;let r=await this.http.get(`/surveys/${encodeURIComponent(e)}/config`);return!r.success||!r.data||!Qe(r.data)?null:(this.activeSurvey=r.data,this.storage.set(t,"1"),this.onSurveyDisplay&&this.onSurveyDisplay(r.data),r.data)}async submitResponse(e,t,r=!0){let s=0;try{s=JSON.stringify(t).length}catch{return!1}if(s>Xe)return!1;let i=await this.http.post("/surveys/responses",{surveyId:e,answers:t,completed:r});return i.success&&(this.activeSurvey=null),i.success}dismiss(){this.activeSurvey=null}getActiveSurvey(){return this.activeSurvey}};function Qe(n){if(n==null||typeof n!="object")return!1;let e=n;return typeof e.id!="string"||typeof e.name!="string"||!Array.isArray(e.questions)?!1:e.questions.every(Je)}function Je(n){if(n==null||typeof n!="object")return!1;let e=n;return typeof e.id=="string"&&typeof e.text=="string"}function I(n){if(!(!n||typeof n!="string"))try{let e=typeof window<"u"?window.location.href:"https://local/",t=new URL(n,e);return t.protocol==="http:"||t.protocol==="https:"?t.href:void 0}catch{return}}var Ze=new Set(["b","i","u","em","strong","a","p","br","span","ul","ol","li","h1","h2","h3","h4"]),et={a:new Set(["href","target","rel"])};function Q(n){if(typeof DOMParser>"u")return"";let t=new DOMParser().parseFromString(`<div>${n}</div>`,"text/html").body.firstElementChild;return t?(Ie(t),t.innerHTML):""}function Ie(n){let e=Array.from(n.children);for(let t of e){let r=t.tagName.toLowerCase();if(!Ze.has(r)){let i=document.createTextNode(t.textContent??"");t.replaceWith(i);continue}let s=et[r]??new Set;for(let i of Array.from(t.attributes)){if(!s.has(i.name.toLowerCase())){t.removeAttribute(i.name);continue}if(i.name.toLowerCase()==="href"){let o=I(i.value);o?t.setAttribute("href",o):t.removeAttribute(i.name)}}r==="a"&&(t.setAttribute("rel","noopener noreferrer"),t.setAttribute("target","_blank")),Ie(t)}}var M=class{constructor(e,t,r){this.messages=[];this.pollInterval=null;this.http=t,this.storage=r}onDisplay(e){this.onMessageDisplay=e}async checkMessages(){let e=await this.http.get("/in-app-messages/active");if(!e.success||!Array.isArray(e.data))return null;this.messages=e.data.map(tt);for(let t of this.messages){let r=`iam_shown_${t.id}`;if(!this.storage.get(r))return this.storage.set(r,"1"),this.onMessageDisplay&&this.onMessageDisplay(t),t}return null}async recordAction(e,t){await this.http.post("/in-app-messages/impressions",{messageId:e,action:t})}startPolling(e=3e5){this.stopPolling(),this.checkMessages(),this.pollInterval=setInterval(()=>this.checkMessages(),e)}stopPolling(){this.pollInterval&&clearInterval(this.pollInterval),this.pollInterval=null}getMessages(){return this.messages}destroy(){this.stopPolling()}};function tt(n){return{...n,content:{...n.content,ctaUrl:I(n.content.ctaUrl),imageUrl:I(n.content.imageUrl)}}}var rt=4e3,F=class{constructor(e,t,r){this.chatbotId=null;this.messages=[];this.http=t,this.storage=r;let s=this.storage.get("chat_session_id");this.sessionId=s??U("chat_"),s||this.storage.set("chat_session_id",this.sessionId)}init(e){if(typeof e!="string"||!/^[A-Za-z0-9_-]{6,64}$/.test(e))throw new Error("[SendoraCloud] Invalid chatbotId.");this.chatbotId=e}onNewMessage(e){this.onMessage=e}async sendMessage(e,t){if(!this.chatbotId||typeof e!="string"||e.length===0||e.length>rt)return null;let r={role:"user",content:e,timestamp:new Date().toISOString()};this.messages.push(r);let s=await this.http.post("/chatbot/message",{chatbotId:this.chatbotId,sessionId:this.sessionId,message:e,userId:t});if(s.success&&s.data&&typeof s.data.reply=="string"){let i={role:"assistant",content:s.data.reply,timestamp:new Date().toISOString()};return this.messages.push(i),this.onMessage&&this.onMessage(i),i}return null}getMessages(){return[...this.messages]}newSession(){this.messages=[],this.sessionId=U("chat_"),this.storage.set("chat_session_id",this.sessionId)}getSessionId(){return this.sessionId}};var H=class{constructor(e,t){this.listeners=new Set;this.granted=e,this.http=t}isGranted(){return this.granted}grant(){this.granted||(this.granted=!0,this.emit())}revoke(){this.granted&&(this.granted=!1,this.emit())}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async record(e){if(!this.http)throw new Error("consent.record requires SDK init (HttpClient unavailable)");let t=await this.http.post("/consent/record",e);if(!t.success||!t.data)throw new Error(t.error?.message??"consent.record failed");return t.data}async requestDeletion(e){if(!this.http)throw new Error("consent.requestDeletion requires SDK init (HttpClient unavailable)");let t=await this.http.post("/consent/deletion-request",e);if(!t.success||!t.data)throw new Error(t.error?.message??"consent.requestDeletion failed");return t.data}emit(){for(let e of this.listeners)try{e(this.granted)}catch{}}};var T="auth_access_token",R="auth_access_expires",m="auth_refresh_token",_="auth_user",be=3e4,nt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function y(n){if(!n||typeof n!="object")return!1;let e=n,t=e.user,r=e.tokens;return!(!t||typeof t.id!="string"||t.id.length===0||!r||typeof r.accessToken!="string"||r.accessToken.length===0||typeof r.refreshToken!="string"||r.refreshToken.length===0||typeof r.expiresIn!="number"||r.expiresIn<=0||t.isAnonymous!==void 0&&typeof t.isAnonymous!="boolean"||t.email!==void 0&&t.email!==null&&typeof t.email!="string"||t.emailVerified!==void 0&&typeof t.emailVerified!="boolean"||t.name!==void 0&&t.name!==null&&typeof t.name!="string"||t.signupMethod!==void 0&&t.signupMethod!==null&&typeof t.signupMethod!="string"||t.lastLoginMethod!==void 0&&t.lastLoginMethod!==null&&typeof t.lastLoginMethod!="string"||e.retiredAnonUserId!==void 0&&typeof e.retiredAnonUserId!="string")}var C=class extends Error{constructor(e="An account with this email already exists"){super(e),this.name="EmailAlreadyTakenError"}},K=class extends Error{constructor(e="Already signed in with an identity; use link*() to add a credential, or sign out first"){super(e),this.name="AlreadyIdentifiedError"}},D=class extends Error{constructor(t="This credential is already linked to a different account",r){super(t);this.code="CREDENTIAL_IN_USE";this.kind="credential_in_use";this.retryable=!1;this.name="CredentialInUseError",this.provider=r?.provider,this.collision=r?.collision,this.status=r?.status}};function Ee(n){let e=n?.error?.details;if(!e||typeof e!="object")return{};let t=e;return{provider:typeof t.provider=="string"?t.provider:void 0,collision:t.collision==="identity"||t.collision==="email"?t.collision:void 0}}var st=new Set(["network","server","rate_limited","account_locked"]);function it(n,e){switch(n){case"NETWORK_ERROR":case"NETWORK_TIMEOUT":return"network";case"PARSE_ERROR":return"server";case"RATE_LIMITED":case"RATE_LIMIT":case"RATE_LIMIT_EXCEEDED":case"QUOTA_EXCEEDED":return"rate_limited";case"ACCOUNT_LOCKED":return"account_locked";case"CREDENTIAL_IN_USE":return"credential_in_use";case"LAST_CREDENTIAL":return"last_credential";case"RECENT_AUTH_REQUIRED":return"recent_auth_required";case"NOT_ANONYMOUS":case"FORBIDDEN_NON_ANONYMOUS":return"already_identified";case"PASSKEY_USER_CANCELLED":case"GAME_CENTER_CANCELLED":case"PLAY_GAMES_CANCELLED":case"SSO_CANCELLED":return"cancelled";case"GAME_CENTER_UNAVAILABLE":case"PLAY_GAMES_UNAVAILABLE":case"ENTITLEMENT_ERROR":case"tier_required":return"config";case"UNAUTHORIZED":case"INVALID_CREDENTIALS":case"INVALID_REFRESH_TOKEN":case"EMAIL_OTP_INVALID":case"MAGIC_LINK_INVALID":case"PASSKEY_RP_MISMATCH":case"NOT_SIGNED_IN":return"invalid_credential";default:break}if(typeof e=="number"){if(e===429)return"rate_limited";if(e>=500)return"server";if(e>=400)return"invalid_credential"}return"unknown"}var c=class extends Error{constructor(e,t,r){super(t),this.name="AuthError",this.code=e,this.kind=r?.kind??it(e,r?.status),this.retryable=st.has(this.kind),this.retryAfterSeconds=r?.retryAfterSeconds,this.status=r?.status}};function ot(n){if(n instanceof c||n instanceof C||n instanceof K||n instanceof D)return n;let e=n?.name;return e==="AbortError"||e==="TimeoutError"||e==="NetworkTimeoutError"?new c("NETWORK_TIMEOUT",n instanceof Error?n.message:"timeout",{kind:"network"}):new c("UNKNOWN_ERROR",n instanceof Error?n.message:String(n),{kind:"unknown"})}function h(n){let e=n.error?.status,t=n.error?.details?.retryAfterSeconds;return{status:typeof e=="number"?e:void 0,retryAfterSeconds:typeof t=="number"&&Number.isFinite(t)&&t>0?t:void 0}}var V=class{constructor(e,t,r,s,i,o){this.user=null;this.accessToken=null;this.accessExpiresAt=0;this.clockSkewConfirmed=!1;this.inflight=Promise.resolve();this.refreshInflight=null;this.refreshFailureCount=0;this.refreshCooldownUntil=0;this.visibilityResetUnsub=null;this.proactiveRefreshTimer=null;this.proactiveRefreshCleanup=null;this.takeoverListeners=new Set;this.lastTakeover=null;this.deletionCancelledListeners=new Set;this.lastDeletionCancelled=null;this.lastAnonRetirement=null;this.authStateListeners=new Set;this.pendingAnonTakeover=null;this.hydrated=!1;this.http=t,this.storage=r,this.analytics=s,this.flags=i,this.chatbot=o;let a=this.storage.get(_),u=this.storage.get(T),l=this.storage.get(m),g=this.storage.get(R);if(a&&(u||l))try{let v=JSON.parse(a);if(typeof v.id!="string"||v.id.length===0)throw new Error("invalid cache");this.user=v,u?(this.accessToken=u,this.accessExpiresAt=g?Number(g):0):(this.accessToken=null,this.accessExpiresAt=0),this.analytics.identify(this.user.id)}catch{this.storage.remove(_),this.storage.remove(T),this.storage.remove(R)}this.hydrated=!0}getCurrentUser(){return this.user}onDeviceTakeover(e){return this.takeoverListeners.add(e),()=>{this.takeoverListeners.delete(e)}}getLastDeviceTakeover(){return this.lastTakeover}onAuthStateChanged(e){if(this.authStateListeners.add(e),this.hydrated&&this.user){let t=this.user;try{e({event:"signed_in",user:t})}catch{}}return()=>{this.authStateListeners.delete(e)}}emitAuthState(e){for(let t of this.authStateListeners)try{t(e)}catch{}}fireDeviceTakeover(e,t){if(!e||!nt.test(e))return;let r={retiredAnonUserId:e,identifiedUserId:t,at:new Date};this.lastTakeover=r;for(let s of this.takeoverListeners)try{s(r)}catch{}this.emitAuthState({event:"device_takeover",user:this.user,retiredAnonUserId:e})}onDeletionCancelled(e){return this.deletionCancelledListeners.add(e),()=>{this.deletionCancelledListeners.delete(e)}}getLastDeletionCancelled(){return this.lastDeletionCancelled}getLastAnonRetirement(){return this.lastAnonRetirement}fireDeletionCancelled(e){let t={userId:e,at:new Date};this.lastDeletionCancelled=t;for(let r of this.deletionCancelledListeners)try{r(t)}catch{}this.emitAuthState({event:"deletion_cancelled",user:this.user})}takeoverHint(){if(this.user?.isAnonymous)return this.storage.get(m)??void 0}canServeToken(e,t,r){return!e||!t||r>=t-be?!1:this.clockSkewConfirmed?!0:Re(e,r)}canServeCachedToken(e){return this.canServeToken(this.accessToken,this.accessExpiresAt,e)}trackedDeadlineAlive(e){return!!this.accessToken&&!!this.accessExpiresAt&&e<this.accessExpiresAt-be}deadlinesDisagree(e){return this.trackedDeadlineAlive(e)&&!this.canServeCachedToken(e)}learnClockSkewFrom(e,t){Re(e,t)||(this.clockSkewConfirmed=!0)}async refreshAndReconcile(e){let t=this.deadlinesDisagree(e),r=await this.refreshAccessToken();return t&&r&&this.learnClockSkewFrom(r,Date.now()),r}async getAccessToken(e){return!e?.forceRefresh&&this.canServeCachedToken(Date.now())?this.accessToken:this.storage.get(m)?this.refreshInflight?this.refreshInflight:Date.now()<this.refreshCooldownUntil?null:this.refreshAndReconcile(Date.now()):null}getAccessTokenSync(){return this.accessToken}signInAnonymously(e){return this.serialize(async()=>{let t=this.user;if(!e?.forceNew&&t?.isAnonymous&&this.storage.get(m))return t;let r=await this.http.post("/auth-service/anonymous",{name:e?.name,metadata:e?.metadata});if(!r.success||!y(r.data))throw new c(r.error?.code??"AUTH_ERROR",r.error?.message??"Anonymous signup failed",h(r));return this.persist(r.data),r.data.user})}signUp(e,t,r){return this.serialize(async()=>{let s=this.storage.get(m);if(s){let o=await this.http.post("/auth-service/upgrade",{refreshToken:s,email:e,password:t,name:r?.name});if(o.success&&y(o.data))return this.persist(o.data),o.data.user;let a=o.error?.code??"",u=h(o),l=u.status;if(a==="NOT_ANONYMOUS"||a==="FORBIDDEN_NON_ANONYMOUS")throw new K(o.error?.message);if(a==="CONFLICT"||a==="EMAIL_ALREADY_TAKEN"||l===409)throw new C(o.error?.message);if(a==="INVALID_REFRESH"||a==="UNAUTHORIZED"||a==="REFRESH_EXPIRED")await this.analytics.flush(),this.wipeLocalIdentity("session_expired");else throw new c(a||"AUTH_ERROR",o.error?.message??"Upgrade failed",u)}let i=await this.http.post("/auth-service/signup",{email:e,password:t,name:r?.name,metadata:r?.metadata});if(!i.success||!y(i.data)){let o=i.error?.code??"";throw o==="CONFLICT"?new C(i.error?.message):new c(o||"AUTH_ERROR",i.error?.message??"Signup failed",h(i))}return this.persist(i.data),i.data.user})}signIn(e,t){return this.serialize(async()=>{let r=this.takeoverHint(),s=await this.http.post("/auth-service/login",{email:e,password:t,...r?{prevAnonRefreshToken:r}:{}});if(!s.success||!s.data)throw new c(s.error?.code??"AUTH_ERROR",s.error?.message??"Login failed",h(s));let i=s.data;if(i.mfaRequired===!0&&typeof i.mfaChallengeToken=="string"){r&&(this.pendingAnonTakeover={challengeToken:i.mfaChallengeToken,prevAnonRefreshToken:r});let o=i.user;return{mfaRequired:!0,mfaChallengeToken:i.mfaChallengeToken,userId:o?.id??""}}if(!y(s.data))throw new c(s.error?.code??"AUTH_ERROR",s.error?.message??"Login failed",h(s));return await this.replaceLocalIdentity(),this.persist(s.data),s.data.user})}loginSocial(e){return this.serialize(async()=>{let t=this.takeoverHint(),{link:r,onCredentialInUse:s,...i}=e,o=await this.http.post("/auth-service/login/social",{...i,...t?{prevAnonRefreshToken:t}:{},...r?{linkAnonymous:!0}:{},...s?{onCredentialInUse:s}:{}});if(!o.success||!y(o.data))throw o.error?.code==="CREDENTIAL_IN_USE"?new D(o.error.message,{...Ee(o),status:h(o).status}):new c(o.error?.code??"SOCIAL_LOGIN_FAILED",o.error?.message??"Social login failed",h(o));return await this.replaceLocalIdentity(),this.persist(o.data),o.data.user})}signInWithGoogle(e,t,r){return this.loginSocial({provider:"google",code:e,redirectUri:t,link:r})}signInWithGitHub(e,t){return this.loginSocial({provider:"github",code:e,redirectUri:t})}signInWithApple(e){return this.loginSocial({provider:"apple",...e})}signInWithMicrosoft(e,t){return this.loginSocial({provider:"microsoft",code:e,redirectUri:t})}signInWithLinkedIn(e,t){return this.loginSocial({provider:"linkedin",code:e,redirectUri:t})}signInWithFacebook(e,t){return this.loginSocial({provider:"facebook",code:e,redirectUri:t})}linkEmailPassword(e,t){return this.linkCredential("/auth-service/me/link/email",{email:e,password:t})}linkSocial(e){return this.linkCredential("/auth-service/me/link/social",e)}linkGoogle(e){return this.linkSocial({provider:"google",...e})}linkApple(e){return this.linkSocial({provider:"apple",...e})}async linkCredential(e,t){let r=await this.getAccessToken();if(!r)throw new c("NOT_SIGNED_IN","Sign in before linking a credential");let s=await this.http.post(e,t,{Authorization:`Bearer ${r}`});if(!s.success||!s.data?.user){let i=s.error?.code??"LINK_FAILED";throw i==="CREDENTIAL_IN_USE"?new D(s.error?.message,{...Ee(s),status:h(s).status}):new c(i,s.error?.message??"Failed to link credential",h(s))}return s.data.upgraded&&y(s.data)?(this.persist(s.data),s.data.user):(this.updateLocalUser(s.data.user),s.data.user)}updateLocalUser(e){this.user=e,this.storage.set(_,JSON.stringify(e))}async listLinkedIdentities(){let e=await this.getAccessToken();if(!e)throw new c("NOT_SIGNED_IN","Sign in before listing linked identities");let t=await this.http.get("/auth-service/me/identities",{Authorization:`Bearer ${e}`});if(!t.success||!t.data)throw new c(t.error?.code??"IDENTITIES_FAILED",t.error?.message??"Failed to list linked identities",h(t));return{identities:t.data.identities??[],hasPassword:!!t.data.hasPassword}}async unlink(e){let t=await this.getAccessToken();if(!t)throw new c("NOT_SIGNED_IN","Sign in before unlinking an identity");let r=await this.http.delete(`/auth-service/me/identities/${encodeURIComponent(e)}`,{Authorization:`Bearer ${t}`});if(!r.success||!r.data)throw new c(r.error?.code??"UNLINK_FAILED",r.error?.message??"Failed to unlink identity",h(r));return{provider:r.data.provider??e,removed:Number(r.data.removed??0),remaining:Number(r.data.remaining??0)}}signInWithDiscord(e,t){return this.loginSocial({provider:"discord",code:e,redirectUri:t})}challengeMfa(e,t){return this.serialize(async()=>{let s=(this.pendingAnonTakeover?.challengeToken===e?this.pendingAnonTakeover.prevAnonRefreshToken:void 0)??this.takeoverHint(),i=await this.http.post("/auth-service/mfa/challenge",{challengeToken:e,code:t,...s?{prevAnonRefreshToken:s}:{}});if(!i.success||!y(i.data))throw new c(i.error?.code??"MFA_CHALLENGE_FAILED",i.error?.message??"Invalid MFA code",h(i));return await this.replaceLocalIdentity(),this.persist(i.data),i.data.user})}async sendMagicLink(e){let t=await this.http.post("/auth-service/magic-link/request",{email:e});if(!t.success)throw new c(t.error?.code??"MAGIC_LINK_REQUEST_FAILED",t.error?.message??"Failed to send link")}async sendEmailOtp(e){let t=await this.http.post("/auth-service/email-otp/request",{email:e});if(!t.success)throw new c(t.error?.code??"EMAIL_OTP_REQUEST_FAILED",t.error?.message??"Failed to send code")}verifyEmailOtp(e,t){return this.serialize(async()=>{let r=this.takeoverHint(),s=await this.http.post("/auth-service/email-otp/verify",{email:e,code:t,...r?{prevAnonRefreshToken:r}:{}});if(!s.success||!y(s.data))throw new c(s.error?.code??"EMAIL_OTP_INVALID",s.error?.message??"Wrong or expired code",h(s));return await this.replaceLocalIdentity(),this.persist(s.data),s.data.user})}async requestPasswordReset(e){let t=await this.http.post("/auth-service/password/forgot",{email:e});if(!t.success)throw new c(t.error?.code??"PASSWORD_RESET_REQUEST_FAILED",t.error?.message??"Failed to send reset email")}async resetPassword(e,t){let r=await this.http.post("/auth-service/password/reset",{token:e,newPassword:t});if(!r.success)throw new c(r.error?.code??"PASSWORD_RESET_FAILED",r.error?.message??"Reset failed")}async verifyEmail(e){let t=await this.http.post("/auth-service/email/verify",{token:e});if(!t.success)throw new c(t.error?.code??"EMAIL_VERIFICATION_FAILED",t.error?.message??"Verification failed")}async sendVerificationEmail(){let e=await this.getAccessToken();if(!e)throw new c("UNAUTHORIZED","Sign in before requesting a verification email");let t=await this.http.post("/auth-service/email/verify/resend",{},{Authorization:`Bearer ${e}`});if(!t.success)throw new c(t.error?.code??"VERIFICATION_RESEND_FAILED",t.error?.message??"Failed to send verification email")}verifyMagicLink(e){return this.serialize(async()=>{let t=this.takeoverHint(),r=await this.http.post("/auth-service/magic-link/verify",{token:e,...t?{prevAnonRefreshToken:t}:{}});if(!r.success||!y(r.data))throw new c(r.error?.code??"MAGIC_LINK_INVALID",r.error?.message??"Invalid or expired magic link",h(r));return await this.replaceLocalIdentity(),this.persist(r.data),r.data.user})}async enrollMfa(){let e=await this.http.post("/auth-service/mfa/enroll/start",{},await this.bearerHeaders());if(!e.success||!e.data)throw new c(e.error?.code??"MFA_ENROLL_FAILED",e.error?.message??"MFA enrollment failed");return e.data}async confirmMfa(e){let t=await this.http.post("/auth-service/mfa/enroll/confirm",{code:e},await this.bearerHeaders());return!!(t.success&&t.data?.confirmed)}async disableMfa(){let e=await this.http.post("/auth-service/mfa/disable",{},await this.bearerHeaders());if(!e.success)throw new c(e.error?.code??"MFA_DISABLE_FAILED",e.error?.message??"Failed to disable MFA",h(e))}async registerPasskey(e){if(typeof navigator>"u"||!navigator.credentials)throw new c("PASSKEY_UNSUPPORTED","WebAuthn not supported in this environment");let t=await this.http.post("/auth-service/passkeys/register/start",{},await this.bearerHeaders());if(!t.success||!t.data)throw new c(t.error?.code??"PASSKEY_START_FAILED",t.error?.message??"Passkey start failed");let r=ct(t.data),s;try{let a=await navigator.credentials.create({publicKey:r});if(!a)throw new Error("create returned null");s=a}catch(a){throw new c("PASSKEY_USER_CANCELLED",a instanceof Error?a.message:"User cancelled passkey registration")}let i=lt(s),o=await this.http.post("/auth-service/passkeys/register/finish",{response:i,name:e},await this.bearerHeaders());if(!o.success||!o.data)throw new c(o.error?.code??"PASSKEY_FINISH_FAILED",o.error?.message??"Passkey verification failed");return o.data}signInWithPasskey(e){return this.serialize(async()=>{if(typeof navigator>"u"||!navigator.credentials)throw new c("PASSKEY_UNSUPPORTED","WebAuthn not supported in this environment");let t=this.takeoverHint(),r=await this.http.post("/auth-service/passkeys/authenticate/start",{userId:e??null});if(!r.success||!r.data)throw new c(r.error?.code??"PASSKEY_START_FAILED",r.error?.message??"Passkey start failed",h(r));let s=ut(r.data),i;try{let u=await navigator.credentials.get({publicKey:s});if(!u)throw new Error("get returned null");i=u}catch(u){throw new c("PASSKEY_USER_CANCELLED",u instanceof Error?u.message:"User cancelled passkey signin")}let o=ht(i),a=await this.http.post("/auth-service/passkeys/authenticate/finish",{response:o,userId:e??null,...t?{prevAnonRefreshToken:t}:{}});if(!a.success||!y(a.data))throw new c(a.error?.code??"PASSKEY_AUTH_FAILED",a.error?.message??"Passkey signin failed",h(a));return await this.replaceLocalIdentity(),this.persist(a.data),a.data.user})}async listPasskeys(){let e=await this.http.get("/auth-service/passkeys",await this.bearerHeaders());return!e.success||!Array.isArray(e.data)?[]:e.data}async deletePasskey(e){let t=await this.http.delete(`/auth-service/passkeys/${encodeURIComponent(e)}`,await this.bearerHeaders());if(!t.success)throw new c(t.error?.code??"PASSKEY_DELETE_FAILED",t.error?.message??"Failed to delete passkey",h(t))}async listMySessions(){let e=await this.http.get("/auth-service/sessions/me",await this.bearerHeaders());return!e.success||!Array.isArray(e.data)?[]:e.data}async revokeSession(e){let t=await this.http.delete(`/auth-service/sessions/me/${encodeURIComponent(e)}`,await this.bearerHeaders());if(!t.success)throw new c(t.error?.code??"SESSION_REVOKE_FAILED",t.error?.message??"Failed to revoke session",h(t))}async revokeAllSessions(){let e=await this.http.delete("/auth-service/sessions/me",await this.bearerHeaders());if(!e.success)throw new c(e.error?.code??"SESSION_REVOKE_ALL_FAILED",e.error?.message??"Failed to sign out other devices",h(e))}async startSso(e){let t=this.takeoverHint(),r=await this.http.post("/auth-service/sso/oidc/start",{returnTo:e,...t?{prevAnonRefreshToken:t}:{}});if(!r.success||!r.data)throw new c(r.error?.code??"SSO_START_FAILED",r.error?.message??"SSO start failed");return r.data}async signInWithSso(e){let t=e??(typeof window<"u"?window.location.origin:"");if(!t)throw new c("SSO_NO_RETURN_TO","returnTo required outside browser context");let r=await this.startSso(t);typeof window<"u"&&(window.location.href=r.authorizationUrl)}async startSaml(e){let t=this.takeoverHint(),r=await this.http.post("/auth-service/sso/saml/start",{returnTo:e,...t?{prevAnonRefreshToken:t}:{}});if(!r.success||!r.data)throw new c(r.error?.code??"SAML_START_FAILED",r.error?.message??"SAML start failed");return r.data}async signInWithSaml(e){let t=e??(typeof window<"u"?window.location.origin:"");if(!t)throw new c("SAML_NO_RETURN_TO","returnTo required outside browser context");let r=await this.startSaml(t);typeof window<"u"&&(window.location.href=r.authorizationUrl)}consumeSsoTokenFromUrl(){return this.serialize(async()=>{if(typeof window>"u")return null;let e=window.location.hash.replace(/^#/,"");if(!e)return null;let t=new URLSearchParams(e),r=t.get("sendora_oidc_error")??t.get("sendora_saml_error");if(r)throw window.history.replaceState(null,"",window.location.pathname+window.location.search),new c("SSO_FAILED",decodeURIComponent(r));let s=t.get("sendora_oidc_token")??t.get("sendora_saml_token");if(!s)return null;let i=t.get("sendora_retired_anon");window.history.replaceState(null,"",window.location.pathname+window.location.search);let o=await this.http.post("/auth-service/token/refresh",{refreshToken:s}),a=o.success?Te(o.data):null;if(!a)throw new c(o.error?.code??"SSO_EXCHANGE_FAILED",o.error?.message??"Could not exchange SSO token",h(o));let u={...a,tokenType:"Bearer"};await this.replaceLocalIdentity(),this.accessToken=u.accessToken,this.accessExpiresAt=Date.now()+u.expiresIn*1e3,this.storage.set(T,u.accessToken),this.storage.set(R,String(this.accessExpiresAt)),this.storage.set(m,u.refreshToken);let l=_e(u.accessToken),g={id:l?.sub??"",email:l?.email??null,emailVerified:l?.email_verified??!0,name:l?.name??null,isAnonymous:!1};return this.user=g,this.storage.set(_,JSON.stringify(g)),this.analytics.identify(g.id),this.flags.setContext({userId:g.id}),this.emitAuthState({event:"signed_in",user:g}),i&&this.fireDeviceTakeover(i,g.id),g})}async bearerHeaders(){let e=await this.getAccessToken();if(!e)throw new c("NOT_SIGNED_IN","Not signed in");return{Authorization:`Bearer ${e}`}}signOut(){return this.serialize(async()=>{let e=this.storage.get(m);this.wipeLocalIdentity("user"),e&&this.http.post("/auth-service/token/revoke",{refreshToken:e}).catch(()=>{})})}serialize(e){let t=async()=>{try{return await e()}catch(s){throw ot(s)}},r=this.inflight.then(t,t);return this.inflight=r.catch(()=>{}),r}async refreshAccessToken(){if(this.refreshInflight)return this.refreshInflight;let e=this.storage.get(m);if(!e)return null;let t=typeof navigator<"u"&&"locks"in navigator,r=async()=>{let s=this.storage.get(m);if(s&&s!==e){let i=this.storage.get(T),o=this.storage.get(R);if(i&&o){let a=Number(o);if(Number.isFinite(a)&&this.canServeToken(i,a,Date.now()))return this.accessToken=i,this.accessExpiresAt=a,i}}try{let i=s??e,o=await this.http.post("/auth-service/token/refresh",{refreshToken:i});if(!o.success)return at(o.error?.code)&&this.tokenStillCurrent(i)?(this.wipeLocalIdentity("session_expired"),this.refreshFailureCount=0,this.refreshCooldownUntil=0,null):(this.armBackoff(),null);let a=Te(o.data);if(!a)return this.armBackoff(),null;if(!this.tokenStillCurrent(i))return null;if(this.accessToken=a.accessToken,this.accessExpiresAt=Date.now()+a.expiresIn*1e3,this.storage.set(T,a.accessToken),this.storage.set(R,String(this.accessExpiresAt)),this.storage.set(m,a.refreshToken),this.user===null){let u=dt(o.data);u&&(this.user=u,this.storage.set(_,JSON.stringify(u)),this.analytics.identify(u.id),this.emitAuthState({event:"signed_in",user:u}))}return this.refreshFailureCount=0,this.refreshCooldownUntil=0,a.accessToken}catch{return this.armBackoff(),null}};return this.refreshInflight=(async()=>{try{return t?await navigator.locks.request("sendora-authservice-refresh",{mode:"exclusive"},r):await r()}finally{this.refreshInflight=null}})(),this.refreshInflight}armBackoff(){this.refreshFailureCount+=1;let e=Math.min(3e4,1e3*Math.pow(2,this.refreshFailureCount-1));this.refreshCooldownUntil=Date.now()+e}resetRefreshState(){this.refreshFailureCount=0,this.refreshCooldownUntil=0}startVisibilityRefreshReset(){if(this.visibilityResetUnsub||typeof document>"u")return;let e=()=>{document.visibilityState==="visible"&&this.resetRefreshState()};document.addEventListener("visibilitychange",e),this.visibilityResetUnsub=()=>document.removeEventListener("visibilitychange",e)}stopVisibilityRefreshReset(){this.visibilityResetUnsub&&(this.visibilityResetUnsub(),this.visibilityResetUnsub=null)}startProactiveRefreshCron(){if(typeof window>"u"||this.proactiveRefreshTimer)return;let e=.8,t=6e4,r=3e4,s=async()=>{if(!this.accessToken||!this.accessExpiresAt)return;let o=Date.now();if(!this.canServeCachedToken(o)){await this.refreshAndReconcile(o);return}let a=this.accessExpiresAt-o;if(a<=0)return;let l=Math.max(a,5*6e4)*(1-e)+(Math.random()*r*2-r);a<=l&&await this.refreshAccessToken()};this.proactiveRefreshTimer=window.setInterval(()=>{s()},t);let i=()=>{document.visibilityState==="visible"&&s()};document.addEventListener("visibilitychange",i),this.proactiveRefreshCleanup=()=>{this.proactiveRefreshTimer&&(window.clearInterval(this.proactiveRefreshTimer),this.proactiveRefreshTimer=null),document.removeEventListener("visibilitychange",i)}}stopProactiveRefreshCron(){this.proactiveRefreshCleanup&&(this.proactiveRefreshCleanup(),this.proactiveRefreshCleanup=null)}persist(e){this.user=e.user,this.accessToken=e.tokens.accessToken,this.accessExpiresAt=Date.now()+e.tokens.expiresIn*1e3,this.storage.set(_,JSON.stringify(e.user)),this.storage.set(T,e.tokens.accessToken),this.storage.set(R,String(this.accessExpiresAt)),this.storage.set(m,e.tokens.refreshToken),this.analytics.identify(e.user.id),this.flags.setContext({userId:e.user.id}),this.startProactiveRefreshCron(),this.startVisibilityRefreshReset(),this.emitAuthState({event:"signed_in",user:e.user}),e.retiredAnonUserId&&this.fireDeviceTakeover(e.retiredAnonUserId,e.user.id),e.anonRetirement&&(this.lastAnonRetirement=e.anonRetirement),e.reactivatedFromDeletion&&this.fireDeletionCancelled(e.user.id)}async replaceLocalIdentity(){this.user!==null&&(await this.analytics.flush(),this.wipeLocalIdentity("replaced"))}tokenStillCurrent(e){return this.storage.get(m)===e}wipeLocalIdentity(e="replaced"){this.user=null,this.accessToken=null,this.accessExpiresAt=0,this.clockSkewConfirmed=!1,this.lastTakeover=null,this.lastDeletionCancelled=null,this.lastAnonRetirement=null,this.pendingAnonTakeover=null,this.storage.remove(_),this.storage.remove(T),this.storage.remove(R),this.storage.remove(m),this.analytics.reset(),this.analytics.dropQueue(),this.flags.reset(),this.chatbot.newSession(),this.stopProactiveRefreshCron(),this.stopVisibilityRefreshReset(),this.refreshFailureCount=0,this.refreshCooldownUntil=0,e!=="replaced"&&this.emitAuthState({event:"signed_out",user:null,reason:e})}};function at(n){return n?n==="INVALID_REFRESH_TOKEN":!1}function z(n){let e=(4-n.length%4)%4,t=(n+"===".slice(0,e)).replace(/-/g,"+").replace(/_/g,"/"),r=atob(t),s=new ArrayBuffer(r.length),i=new Uint8Array(s);for(let o=0;o<r.length;o++)i[o]=r.charCodeAt(o);return s}function b(n){let e=n instanceof Uint8Array?n:new Uint8Array(n),t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function ct(n){return{challenge:z(n.challenge),rp:n.rp,user:{id:z(n.user.id),name:n.user.name,displayName:n.user.displayName},pubKeyCredParams:n.pubKeyCredParams,timeout:n.timeout,attestation:n.attestation,excludeCredentials:n.excludeCredentials?.map(e=>({id:z(e.id),type:"public-key",transports:e.transports})),authenticatorSelection:n.authenticatorSelection}}function ut(n){return{challenge:z(n.challenge),timeout:n.timeout,rpId:n.rpId,allowCredentials:n.allowCredentials?.map(e=>({id:z(e.id),type:"public-key",transports:e.transports})),userVerification:n.userVerification}}function lt(n){let e=n.response;return{id:n.id,rawId:b(n.rawId),type:n.type,response:{clientDataJSON:b(e.clientDataJSON),attestationObject:b(e.attestationObject),transports:typeof e.getTransports=="function"?e.getTransports():void 0},clientExtensionResults:n.getClientExtensionResults()}}function Te(n){if(!n||typeof n!="object")return null;let e=n.tokens,t=e&&typeof e=="object"?e:n;return typeof t.accessToken!="string"||!t.accessToken||typeof t.refreshToken!="string"||!t.refreshToken||typeof t.expiresIn!="number"||t.expiresIn<=0?null:{accessToken:t.accessToken,refreshToken:t.refreshToken,expiresIn:t.expiresIn}}function dt(n){if(!n||typeof n!="object")return null;let e=n.user;if(!e||typeof e!="object")return null;let t=e.id;return typeof t!="string"||t.length===0?null:e}function Re(n,e){let t=_e(n);if(!t)return!0;let r=t.exp;return typeof r!="number"||!Number.isFinite(r)?!0:e<r*1e3}function _e(n){try{let e=n.split(".");if(e.length!==3)return null;let t=e[1].replace(/-/g,"+").replace(/_/g,"/"),r=atob(t+"===".slice(0,(4-t.length%4)%4));return JSON.parse(r)}catch{return null}}function ht(n){let e=n.response;return{id:n.id,rawId:b(n.rawId),type:n.type,response:{clientDataJSON:b(e.clientDataJSON),authenticatorData:b(e.authenticatorData),signature:b(e.signature),userHandle:e.userHandle?b(e.userHandle):null},clientExtensionResults:n.getClientExtensionResults()}}function pt(n){return n===!1?{pageViews:!1,sessionStart:!1,appOpen:!1,appBackground:!1,engagement:!1}:n===!0||n===void 0?{pageViews:!0,sessionStart:!0,appOpen:!0,appBackground:!0,engagement:!0}:{pageViews:n.pageViews??!0,sessionStart:n.sessionStart??!0,appOpen:n.appOpen??!0,appBackground:n.appBackground??!0,engagement:n.engagement??!0}}var gt=250,Ce=360*60*1e3;function Pe(n,e){if(typeof window>"u")return()=>{};let t=pt(e.autoTrack),r=e.sessionIdleMs??18e5,s=[],i="sendora_session_id",o="sendora_session_last_activity";function a(){return De(i)??""}function u(d){Le(i,d)}function l(){let d=De(o);return d&&Number(d)||0}function g(d){Le(o,String(d))}function v(){return`sess_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`}function w(d){let S=Date.now(),q=l();if(!a()||q&&S-q>r){let G=v();u(G),d&&t.sessionStart&&n.track("session.start",{sessionId:G})}g(S)}w(t.sessionStart),t.appOpen&&n.track("app.opened",{sessionId:a()||void 0,url:window.location.origin+window.location.pathname,referrer:document.referrer||void 0});let k=window.location.pathname,L=0,A=document.visibilityState==="visible"?Date.now():0;function ne(){A>0&&(L+=Date.now()-A,A=0)}function j(){if(!t.engagement)return;ne();let d=L;if(L=0,!(d<gt)){d>Ce&&(d=Ce);try{n.track("app.engagement",{durationMs:Math.round(d),screen:k,sessionId:a()||void 0})}catch{}}}function Ne(d){k=d,L=0,A=document.visibilityState==="visible"?Date.now():0}if(t.pageViews||t.engagement){t.pageViews&&n.page();let d=()=>{j(),w(!0),t.pageViews&&n.page(),Ne(window.location.pathname)},S=()=>d();window.addEventListener("popstate",S),s.push(()=>window.removeEventListener("popstate",S));let q=window;if(!q.__sendoraHistoryPatched){q.__sendoraHistoryPatched=!0;let G=history.pushState,xe=history.replaceState;history.pushState=function(...ie){let oe=G.apply(this,ie);return window.dispatchEvent(new Event("sendora:locationchange")),oe},history.replaceState=function(...ie){let oe=xe.apply(this,ie);return window.dispatchEvent(new Event("sendora:locationchange")),oe}}let se=()=>d();window.addEventListener("sendora:locationchange",se),s.push(()=>window.removeEventListener("sendora:locationchange",se))}if(t.appBackground||t.engagement){let d=()=>{if(document.visibilityState==="hidden"){j(),t.appBackground&&(w(!0),n.track("app.backgrounded",{sessionId:a()||void 0}));try{n.flush()}catch{}}else document.visibilityState==="visible"&&(t.appBackground&&(w(!0),n.track("app.foregrounded",{sessionId:a()||void 0})),t.engagement&&A===0&&(A=Date.now()))};if(document.addEventListener("visibilitychange",d),s.push(()=>document.removeEventListener("visibilitychange",d)),t.engagement){let S=()=>{j();try{n.flush()}catch{}};window.addEventListener("pagehide",S),s.push(()=>window.removeEventListener("pagehide",S))}}let pe=0,P=()=>{let d=Date.now();d-pe<5e3||(pe=d,w(!0))};return window.addEventListener("click",P,{passive:!0}),window.addEventListener("keydown",P,{passive:!0}),window.addEventListener("scroll",P,{passive:!0}),s.push(()=>{window.removeEventListener("click",P),window.removeEventListener("keydown",P),window.removeEventListener("scroll",P)}),()=>{j();for(let d of s)try{d()}catch{}}}function De(n){try{return window.sessionStorage?.getItem(n)??null}catch{return null}}function Le(n,e){try{window.sessionStorage?.setItem(n,e)}catch{}}var $=class n{constructor(e){this.http=e}static isSupported(){return typeof window>"u"?!1:"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window}static permission(){return typeof Notification>"u"?"denied":Notification.permission}async subscribe(e){if(!n.isSupported())throw new Error("[sendoracloud] Web Push not supported in this browser.");let t=Notification.permission;if(t==="default"&&(t=await Notification.requestPermission()),t!=="granted")throw new Error(`[sendoracloud] Notification permission ${t}.`);let r=await navigator.serviceWorker.getRegistration(e.scope??"/");r||(r=await navigator.serviceWorker.register(e.serviceWorkerPath,{scope:e.scope??"/"})),await navigator.serviceWorker.ready;let i=(await this.http.get("/push/vapid"))?.data?.publicKey;if(!i)throw new Error("[sendoracloud] backend returned no VAPID public key.");let a=await r.pushManager.getSubscription()??await r.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:ft(i)}),u=a.toJSON(),l=u.endpoint,g=u.keys?.p256dh??"",v=u.keys?.auth??"",w=await mt(l),k=await this.http.post("/push/tokens",{platform:"web",token:w,webEndpoint:l,webP256dh:g,webAuth:v,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,locale:typeof navigator<"u"?navigator.language:void 0,timezone:Intl?.DateTimeFormat?.().resolvedOptions?.().timeZone,...e.userId?{userId:e.userId}:{}});if(!k?.data?.tokenId)throw new Error("[sendoracloud] backend returned no tokenId on subscribe.");return{tokenId:k.data.tokenId,subscription:a}}async unsubscribe(e="/"){if(!n.isSupported())return!1;let t=await navigator.serviceWorker.getRegistration(e);if(!t)return!1;let r=await t.pushManager.getSubscription();return r?await r.unsubscribe():!1}async trackOpen(e,t){let r={sendId:e};t!==void 0&&(r.clickAction=t);let s=await this.http.post("/push/track-open",r);if(!s.success)throw new Error(s.error?.message??"push.trackOpen failed")}};function ft(n){let e="=".repeat((4-n.length%4)%4),t=(n+e).replace(/-/g,"+").replace(/_/g,"/"),r=atob(t),s=new Uint8Array(r.length);for(let i=0;i<r.length;i++)s[i]=r.charCodeAt(i);return s}async function mt(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}var W=class{constructor(e){}unsupported(){throw new Error("[SendoraCloud] sendora.audiences is not available in the browser SDK. Audiences require a secret (sk_*) key with the audiences:read/write scopes and must be managed from a trusted server, not the browser.")}list(){return this.unsupported()}get(e){return this.unsupported()}create(e){return this.unsupported()}update(e,t){return this.unsupported()}delete(e){return this.unsupported()}};var p=class extends Error{constructor(e,t,r){super(t),this.name="LinkError",this.code=e,this.statusCode=r}};function de(n,e){let t=(n??"").toUpperCase();return t==="NOT_FOUND"?new p("NOT_FOUND",e):t==="FORBIDDEN"||t==="UNAUTHORIZED"?new p("UNAUTHORIZED",e):t==="RATE_LIMITED"?new p("RATE_LIMITED",e):t==="ENTITLEMENT_ERROR"||/plan limit/i.test(e)?new p("PLAN_LIMIT",e):t==="VALIDATION_ERROR"?/iOS bundle|Android package/i.test(e)?new p("BUNDLE_MISMATCH",e):/2KB|10KB|linkData/i.test(e)?new p("DATA_TOO_LARGE",e):/fallbackUrl/i.test(e)&&/apps/i.test(e)?new p("FALLBACK_REQUIRED",e):new p("INVALID_INPUT",e):t==="PARSE_ERROR"||t==="HTTP_ERROR"||/HTTP \d{3}/.test(e)?new p("NETWORK",e):new p("UNKNOWN",e||`Unknown LinkError (code=${n??"none"})`)}var he=/^[a-z0-9-]{3,20}$/;function Ue(n){try{let t=new URL(n).pathname.split("/").filter(Boolean);if(t.length===0)return null;let r=t[t.length-1];return he.test(r)?r:null}catch{return null}}var yt=5*6e4,vt=50,wt=5,B=class{constructor(e){this.http=e;this.prewarmCache=new Map;this.prewarmInflight=0}cacheKey(e,t){if(t)return`k:${t}`;let r={},s=e;for(let i of Object.keys(s).sort())r[i]=s[i];return`s:${JSON.stringify(r)}`}evictExpired(){let e=Date.now();for(let[t,r]of this.prewarmCache)e-r.ts>yt&&this.prewarmCache.delete(t);for(;this.prewarmCache.size>vt;){let t=this.prewarmCache.keys().next().value;if(t===void 0)break;this.prewarmCache.delete(t)}}prewarm(e,t){this.evictExpired();let r=this.cacheKey(e,t?.key);if(this.prewarmCache.has(r)||this.prewarmInflight>=wt)return;this.prewarmInflight++;let s=this.doCreate(e).catch(i=>{throw this.prewarmCache.delete(r),i}).finally(()=>{this.prewarmInflight--});this.prewarmCache.set(r,{promise:s,ts:Date.now()})}async create(e,t){if(!e.title)throw new p("INVALID_INPUT","links.create: title is required");this.evictExpired();let r=this.cacheKey(e,t?.key),s=this.prewarmCache.get(r);return s?(this.prewarmCache.delete(r),s.promise):this.doCreate(e)}async doCreate(e){let t={title:e.title};e.fallbackUrl&&(t.fallbackUrl=e.fallbackUrl),e.iosDeepLinkPath&&(t.iosDeepLinkPath=e.iosDeepLinkPath),e.androidDeepLinkPath&&(t.androidDeepLinkPath=e.androidDeepLinkPath),e.linkData&&(t.linkData=e.linkData),e.ogTitle&&(t.ogTitle=e.ogTitle),e.ogDescription&&(t.ogDescription=e.ogDescription),e.ogImageUrl&&(t.ogImageUrl=e.ogImageUrl),e.campaign&&(t.campaign=e.campaign),e.source&&(t.source=e.source),e.medium&&(t.medium=e.medium),e.channel&&(t.channel=e.channel),e.tags&&(t.tags=e.tags),e.expiresAt&&(t.expiresAt=e.expiresAt),e.iosBundleId&&(t.iosBundleId=e.iosBundleId),e.androidPackageName&&(t.androidPackageName=e.androidPackageName);let r=await this.http.post("/sdk/links",t);if(!r.success||!r.data)throw de(r.error?.code,r.error?.message??"links.create failed");return r.data}async revoke(e){if(!he.test(e))throw new p("INVALID_INPUT",`links.revoke: '${e}' is not a valid shortcode`);let t=await this.http.post(`/sdk/links/${encodeURIComponent(e)}/revoke`,{});if(!t.success||!t.data)throw de(t.error?.code,t.error?.message??"links.revoke failed");return{shortcode:t.data.shortcode,revoked:!0}}async getStats(e){if(!he.test(e))throw new p("INVALID_INPUT",`links.getStats: '${e}' is not a valid shortcode`);let t=await this.http.get(`/sdk/links/${encodeURIComponent(e)}/stats`);if(!t.success||!t.data)throw de(t.error?.code,t.error?.message??"links.getStats failed");return t.data}};var J=class{constructor(e){this.http=e}async reportInstall(e={}){let t=await this.http.post("/attribution/install",e);if(!t.success||!t.data)throw new Error(t.error?.message??"attribution.reportInstall failed");return t.data}async checkDeferred(e={}){let t=await this.http.post("/attribution/deferred",e);if(!t.success)throw new Error(t.error?.message??"attribution.checkDeferred failed");return t.data??null}};var Z=class{constructor(e){this.http=e}async createTicket(e){let t=await this.http.post("/support/tickets",e);if(!t.success||!t.data)throw new Error(t.error?.message??"support.createTicket failed");return t.data}async submitCsat(e){let t=await this.http.post("/support/csat",e);if(!t.success||!t.data)throw new Error(t.error?.message??"support.submitCsat failed");return t.data}};var ee=class{constructor(e){this.http=e}async search(e){if(!e.query||e.query.trim().length===0)return[];let t=new URLSearchParams({query:e.query});e.limit&&t.set("limit",String(e.limit));let r=await this.http.get(`/kb/search?${t.toString()}`);if(!r.success||!Array.isArray(r.data))throw new Error(r.error?.message??"kb.search failed");return r.data}};var kt=/^[A-Za-z0-9_.-]{1,64}$/;function At(n){if(n!==void 0){if(typeof n!="string"||!kt.test(n))throw new Error(`[sendora] init: storagePrefix must be 1-64 chars of A-Z a-z 0-9 _ . - (got ${JSON.stringify(n)}). Changing it signs the browser out, so it is validated rather than ignored.`);return n}}var re=class re{constructor(e){this.autoTrackCleanup=null;this.http=new Y(e),this.storage=new X(At(e.storagePrefix)),this.consent=new H(e.defaultConsent===!0,this.http),this.analytics=new N(e,this.http,this.storage,this.consent),this.flags=new x(e,this.http,this.storage),this.surveys=new O(e,this.http,this.storage),this.messages=new M(e,this.http,this.storage),this.chatbot=new F(e,this.http,this.storage),this.auth=new V(e,this.http,this.storage,this.analytics,this.flags,this.chatbot),this.webPush=new $(this.http),this.audiences=new W(this.http),this.links=new B(this.http),this.attribution=new J(this.http),this.support=new Z(this.http),this.kb=new ee(this.http),e.autoTrack!==!1&&(this.autoTrackCleanup=Pe(this.analytics,e))}static init(e){return we(e.apiKey),new re(e)}static sanitizeHtml(e){return Q(e)}static safeUrl(e){return I(e)}track(e,t){this.analytics.track(e,t)}page(e){this.analytics.page(e)}identify(e,t,r){this.analytics.identify(e,t,r),this.flags.setContext({userId:e})}reset(){this.analytics.reset(),this.flags.reset(),this.chatbot.newSession()}async flush(){await this.analytics.flush()}destroy(){this.autoTrackCleanup&&(this.autoTrackCleanup(),this.autoTrackCleanup=null),this.analytics.destroy(),this.flags.destroy(),this.messages.destroy()}};re.version=E;var te=re,St=te;0&&(module.exports={AlreadyIdentifiedError,Analytics,Audiences,Auth,AuthError,Chatbot,Consent,CredentialInUseError,EmailAlreadyTakenError,FeatureFlags,InAppMessaging,LinkError,Links,SendoraCloud,Surveys,ValidationError,WebPush,extractShortcodeFromUrl,safeUrl,sanitizeHtml});
1
+ "use strict";var ae=Object.defineProperty;var Oe=Object.getOwnPropertyDescriptor;var Me=Object.getOwnPropertyNames;var Fe=Object.prototype.hasOwnProperty;var He=(n,e)=>{for(var t in e)ae(n,t,{get:e[t],enumerable:!0})},Ke=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Me(e))!Fe.call(n,s)&&s!==t&&ae(n,s,{get:()=>e[s],enumerable:!(r=Oe(e,s))||r.enumerable});return n};var Ve=n=>Ke(ae({},"__esModule",{value:!0}),n);var It={};He(It,{AlreadyIdentifiedError:()=>K,Analytics:()=>N,Audiences:()=>W,Auth:()=>V,AuthError:()=>c,Chatbot:()=>F,Consent:()=>H,CredentialInUseError:()=>D,EmailAlreadyTakenError:()=>C,FeatureFlags:()=>x,InAppMessaging:()=>M,LinkError:()=>p,Links:()=>B,SendoraCloud:()=>te,Surveys:()=>O,ValidationError:()=>f,WebPush:()=>$,default:()=>St,extractShortcodeFromUrl:()=>Ue,safeUrl:()=>I,sanitizeHtml:()=>Q});module.exports=Ve(It);var ge=/^[a-zA-Z][a-zA-Z0-9._:-]{0,127}$/;var $e=new Set(["__proto__","constructor","prototype"]),f=class extends Error{constructor(e){super(`[SendoraCloud] ${e}`),this.name="SendoraValidationError"}};function fe(n){if(typeof n!="string"||!ge.test(n))throw new f(`Invalid event name: must match ${ge}, got "${String(n)}".`)}function me(n){if(n==null)return;if(typeof n!="object"||Array.isArray(n))throw new f("Properties must be a plain object, not an array or primitive.");let e=ye(n);if(e>5)throw new f(`Properties nested too deeply (${e} levels, max 5).`);ve(n);let t;try{t=JSON.stringify(n).length}catch{throw new f("Properties contain a circular reference or unserializable value.")}if(t>32768)throw new f(`Properties too large (${t} bytes, max 32768).`)}function ye(n,e=0){if(e>6||n==null||typeof n!="object")return e;let t=e;for(let r of Object.keys(n)){let s=ye(n[r],e+1);s>t&&(t=s)}return t}function ve(n){if(!(n==null||typeof n!="object"))for(let e of Object.keys(n)){if($e.has(e))throw new f(`Forbidden property key "${e}" (prototype pollution guard).`);ve(n[e])}}var We=/^pk_[A-Za-z0-9_-]{16,}$/;function we(n){if(!n||typeof n!="string")throw new f("apiKey is required.");if(n.startsWith("sk_")||n.startsWith("sendora_secret_"))throw new f("Secret keys must NEVER be used in browser SDK. Use a publishable key (pk_...).");if(!We.test(n))throw new f("Invalid publishable key format. Expected pk_... (17+ chars).")}function ke(n){let e=n.replace(/\/$/,"");if(!(e.startsWith("http://localhost")||e.startsWith("http://127.0.0.1"))&&!e.startsWith("https://"))throw new f("apiUrl must be https:// (only http://localhost is allowed for dev).")}var Ae={name:"@sendoracloud/sdk-web",version:"3.22.0",description:"Sendora Cloud Web SDK \u2014 analytics, feature flags, surveys, in-app messaging, chatbot, auth, deep links (Branch / Firebase parity). Zero dependencies, TypeScript, SSR-safe.",type:"module",main:"./dist/index.cjs",module:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"}},files:["dist","README.md","LICENSE"],keywords:["sendora","analytics","feature-flags","surveys","in-app-messaging","chatbot","tracking","customer-engagement"],homepage:"https://sendoracloud.com/sdks",repository:{type:"git",url:"git+https://github.com/sendoracloud/sdk-web.git"},bugs:{url:"https://github.com/sendoracloud/sdk-web/issues"},author:"Sendora Cloud <hello@sendoracloud.com>",license:"Apache-2.0",publishConfig:{access:"public"},sideEffects:!1,scripts:{build:"tsup src/index.ts --format cjs,esm --dts --clean --minify",typecheck:"tsc --noEmit",prepublishOnly:"npm run build"},devDependencies:{typescript:"^5.4.0",tsup:"^8.0.0"}};var E=Ae.version;var qe="https://api.sendoracloud.com",ze=1e4,je="@sendoracloud/sdk-web",Y=class{constructor(e){let t=(e.apiUrl??qe).replace(/\/$/,"");ke(t),this.apiKey=e.apiKey,this.baseUrl=t,this.debug=!!e.debug}get(e,t){return this.request("GET",e,void 0,t)}post(e,t,r){return this.request("POST",e,t,r)}patch(e,t,r){return this.request("PATCH",e,t,r)}delete(e,t){return this.request("DELETE",e,void 0,t)}async request(e,t,r,s){let i=`${this.baseUrl}/api/v1${t}`,o=typeof AbortController<"u"?new AbortController:null,a=o?setTimeout(()=>o.abort(),ze):null;try{let u=await fetch(i,{method:e,headers:{"Content-Type":"application/json","X-API-Key":this.apiKey,"X-Sendora-SDK-Name":je,"X-Sendora-SDK-Version":E,...s??{}},body:r?JSON.stringify(r):void 0,signal:o?o.signal:void 0});a&&clearTimeout(a);let l;try{l=await u.json()}catch{l={success:!1,error:{code:"PARSE_ERROR",message:`HTTP ${u.status}`}}}if(this.debug&&console.debug(`[SendoraCloud] ${e} ${t} \u2192 ${u.status}`),!u.ok){if(t.startsWith("/auth-service/")&&!this.debug)console.warn(`[SendoraCloud] ${e} ${t} \u2192 HTTP ${u.status}`);else{let v=l?.error?.code??"HTTP_ERROR",w=l?.error?.message??`HTTP ${u.status}`,k=l?.error?.details?.fieldErrors,L=k?` (${Object.entries(k).map(([A,ne])=>`${A}: ${(ne??[]).join(", ")}`).join("; ")})`:"";console.warn(`[SendoraCloud] ${e} ${t} \u2192 HTTP ${u.status} \u2014 ${v}: ${w}${L}`)}l&&l.error&&(l.error={...l.error,status:u.status})}return l}catch(u){a&&clearTimeout(a);let l=u instanceof Error&&u.name==="AbortError"?"timeout":"error";return console.warn(`[SendoraCloud] ${e} ${t} network ${l}`),{success:!1,error:{code:"NETWORK_ERROR",message:l}}}}};var Ge="sendora_",X=class{constructor(e,t=!1){this.memoryStore=new Map;this.useLocalStorage=t?!1:this.checkLocalStorage(),this.prefix=e??Ge}get(e){let t=this.prefix+e;if(this.useLocalStorage)try{return localStorage.getItem(t)}catch{return this.memoryStore.get(t)??null}return this.memoryStore.get(t)??null}set(e,t){let r=this.prefix+e;if(this.useLocalStorage)try{localStorage.setItem(r,t);return}catch{}this.memoryStore.set(r,t)}remove(e){let t=this.prefix+e;if(this.useLocalStorage)try{localStorage.removeItem(t)}catch{}this.memoryStore.delete(t)}clearPrefix(e){let t=this.prefix+e;if(this.useLocalStorage)try{for(let r=localStorage.length-1;r>=0;r--){let s=localStorage.key(r);s&&s.startsWith(t)&&localStorage.removeItem(s)}}catch{}for(let r of Array.from(this.memoryStore.keys()))r.startsWith(t)&&this.memoryStore.delete(r)}checkLocalStorage(){try{if(typeof localStorage>"u")return!1;let e="__sendora_test__";return localStorage.setItem(e,"1"),localStorage.removeItem(e),!0}catch{return!1}}};function U(n=""){let e=new Uint8Array(16),t=typeof globalThis<"u"&&"crypto"in globalThis?globalThis.crypto:void 0;if(!t||typeof t.getRandomValues!="function")throw new Error("[SendoraCloud] crypto.getRandomValues unavailable \u2014 refusing to mint IDs without a CSPRNG");t.getRandomValues(e);let r="";for(let s of e)r+=s.toString(16).padStart(2,"0");return n+r}var Se=500,ce=10,ue=6e4,N=class{constructor(e,t,r,s){this.queue=[];this.timer=null;this.userId=null;this.identityToken=null;this.consecutiveFailures=0;this.nextFlushAfter=0;this.breakerOpenAt=0;this.breakerWarned=!1;this.http=t,this.storage=r,this.consent=s,this.projectId=e.projectId,this.flushInterval=e.flushInterval??5e3,this.maxQueueSize=e.maxQueueSize??20,this.persistUserId=!!e.persistUserId,this.stripQueryParams=e.stripQueryParams!==!1,this.appVersion=e.appVersion,this.storage.get("schema_version")===null&&this.storage.set("schema_version","1");let i=this.storage.get("anonymous_id");if(i?this.anonymousId=i:(this.anonymousId=U("anon_"),this.storage.set("anonymous_id",this.anonymousId)),this.persistUserId){let o=this.storage.get("user_id");o&&(this.userId=o)}this.timer=setInterval(()=>this.flush(),this.flushInterval),typeof window<"u"&&window.addEventListener("beforeunload",()=>this.flush()),this.consent.subscribe(o=>{o&&this.flush()})}track(e,t){fe(e),t&&me(t),this.queue.length>=Se&&this.queue.shift(),this.queue.push({eventType:e,properties:t??{},userId:this.userId??void 0,anonymousId:this.anonymousId,timestamp:new Date().toISOString(),identityToken:this.identityToken??void 0}),this.queue.length>=this.maxQueueSize&&this.flush()}page(e){if(typeof window>"u")return;let t=this.stripQueryParams?window.location.origin+window.location.pathname:window.location.href;this.track("page.viewed",{url:t,path:window.location.pathname,title:document.title,referrer:document.referrer||void 0,...e})}identify(e,t,r){if(typeof e!="string"||e.length===0||e.length>256)throw new Error("[SendoraCloud] userId must be a 1-256 char string.");this.userId=e,this.identityToken=r?.identityToken??null,this.persistUserId&&this.storage.set("user_id",e),this.track("user.identified",{...t})}reset(e=!0){this.userId=null,this.identityToken=null,this.storage.remove("user_id"),e&&(this.anonymousId=U("anon_"),this.storage.set("anonymous_id",this.anonymousId)),this.storage.clearPrefix("iam_shown_"),this.storage.clearPrefix("survey_shown_")}dropQueue(){this.queue=[]}async flush(){if(this.queue.length===0||!this.consent.isGranted()||Date.now()<this.nextFlushAfter)return;this.consecutiveFailures>ce&&Date.now()-this.breakerOpenAt>=ue&&(this.consecutiveFailures=0,this.breakerOpenAt=0,this.breakerWarned=!1);let e=this.queue.splice(0,100),t=this.getSessionId(),r=e.map(a=>({projectId:this.projectId,module:"custom",eventType:a.eventType,userId:a.userId,anonymousId:a.anonymousId,identityToken:a.identityToken,timestamp:a.timestamp??new Date().toISOString(),properties:a.properties??{},context:this.getContext(),...t?{sessionId:t}:{},consent:["analytics"]}));if((await this.http.post("/events/batch",{events:r})).success){this.consecutiveFailures=0,this.breakerOpenAt=0,this.breakerWarned=!1;return}if(this.consecutiveFailures++,this.consecutiveFailures>ce){this.breakerWarned||(this.breakerOpenAt=Date.now(),this.breakerWarned=!0,console.warn(`[SendoraCloud] Analytics circuit breaker open after ${ce} consecutive failed flushes \u2014 events will be dropped until a flush succeeds or ${ue}ms elapse.`));return}let i=Math.min(ue,1e3*2**this.consecutiveFailures);this.nextFlushAfter=Date.now()+i;let o=Math.max(0,Se-this.queue.length);o>0&&this.queue.unshift(...e.slice(0,o))}destroy(){this.timer&&clearInterval(this.timer),this.timer=null,this.flush()}getSessionId(){try{return typeof sessionStorage>"u"?void 0:sessionStorage.getItem("sendora_session_id")||void 0}catch{return}}getContext(){return typeof window>"u"?{sdk:{name:"@sendoracloud/sdk-web",version:E}}:{page:{url:this.stripQueryParams?window.location.origin+window.location.pathname:window.location.href,path:window.location.pathname,title:document.title},referrer:document.referrer||void 0,locale:typeof navigator<"u"?navigator.language:void 0,device:this.buildDevice(),sdk:{name:"@sendoracloud/sdk-web",version:E}}}buildDevice(){if(typeof navigator>"u")return;let e=navigator.userAgent||"",r=navigator.userAgentData?.mobile??/Mobi|Android|iPhone|iPod/i.test(e);return{type:/iPad|Tablet|(?:Android(?!.*Mobile))/i.test(e)?"tablet":r?"mobile":"desktop",os:"Web",osVersion:"",model:"",appVersion:this.resolveAppVersion(),browser:Ye(e)}}resolveAppVersion(){if(this.appVersion)return this.appVersion;if(typeof document<"u"){let r=document.querySelector('meta[name="sendora:app-version"]')?.getAttribute("content");if(r)return r}let e=globalThis.__SENDORA_APP_VERSION__;return typeof e=="string"?e:""}};function Ye(n){let e=[["Edge",/Edg\/(\d+)/],["Opera",/OPR\/(\d+)/],["Firefox",/Firefox\/(\d+)/],["Samsung Internet",/SamsungBrowser\/(\d+)/],["Chrome",/Chrome\/(\d+)/],["Safari",/Version\/(\d+)[^ ]* Safari/]];for(let[t,r]of e){let s=r.exec(n);if(s)return`${t} ${s[1]}`}return"Unknown"}var x=class{constructor(e,t,r){this.cache=new Map;this.refreshInterval=null;this.http=t,this.storage=r;let s=this.storage.get("flags");if(s)try{let i=JSON.parse(s);if(Array.isArray(i))for(let o of i)le(o)&&this.cache.set(o.key,o)}catch{}}setContext(e){this.userId=e.userId,this.entityId=e.entityId,this.environment=e.environment}async getFlag(e){if(typeof e!="string"||e.length===0||e.length>128)return null;let t=this.cache.get(e);if(t)return t.value;let r=await this.http.post("/feature-flags/evaluate",{key:e,userId:this.userId,entityId:this.entityId,environment:this.environment});return r.success&&r.data&&le(r.data)?(this.cache.set(e,r.data),this.persistCache(),r.data.value):null}async isEnabled(e,t=!1){let r=await this.getFlag(e);return typeof r=="boolean"?r:t}async refreshAll(){let e=await this.http.post("/feature-flags/evaluate-all",{userId:this.userId,entityId:this.entityId,environment:this.environment});if(e.success&&Array.isArray(e.data)){this.cache.clear();for(let t of e.data)le(t)&&this.cache.set(t.key,t);this.persistCache()}}startAutoRefresh(e=6e4){this.stopAutoRefresh(),this.refreshAll(),this.refreshInterval=setInterval(()=>this.refreshAll(),e)}stopAutoRefresh(){this.refreshInterval&&clearInterval(this.refreshInterval),this.refreshInterval=null}getAllFlags(){let e={};for(let[t,r]of this.cache)e[t]=r.value;return e}reset(){this.cache.clear(),this.storage.remove("flags"),this.userId=void 0,this.entityId=void 0,this.environment=void 0}destroy(){this.stopAutoRefresh()}persistCache(){this.storage.set("flags",JSON.stringify(Array.from(this.cache.values())))}};function le(n){if(n==null||typeof n!="object")return!1;let e=n;return Object.prototype.hasOwnProperty.call(e,"__proto__")||Object.prototype.hasOwnProperty.call(e,"constructor")?!1:typeof e.key=="string"&&"value"in e}var Xe=32*1024,O=class{constructor(e,t,r){this.activeSurvey=null;this.http=t,this.storage=r}onDisplay(e){this.onSurveyDisplay=e}async showSurvey(e){if(typeof e!="string"||!/^[A-Za-z0-9_-]{6,64}$/.test(e))return null;let t=`survey_shown_${e}`;if(this.storage.get(t))return null;let r=await this.http.get(`/surveys/${encodeURIComponent(e)}/config`);return!r.success||!r.data||!Qe(r.data)?null:(this.activeSurvey=r.data,this.storage.set(t,"1"),this.onSurveyDisplay&&this.onSurveyDisplay(r.data),r.data)}async submitResponse(e,t,r=!0){let s=0;try{s=JSON.stringify(t).length}catch{return!1}if(s>Xe)return!1;let i=await this.http.post("/surveys/responses",{surveyId:e,answers:t,completed:r});return i.success&&(this.activeSurvey=null),i.success}dismiss(){this.activeSurvey=null}getActiveSurvey(){return this.activeSurvey}};function Qe(n){if(n==null||typeof n!="object")return!1;let e=n;return typeof e.id!="string"||typeof e.name!="string"||!Array.isArray(e.questions)?!1:e.questions.every(Je)}function Je(n){if(n==null||typeof n!="object")return!1;let e=n;return typeof e.id=="string"&&typeof e.text=="string"}function I(n){if(!(!n||typeof n!="string"))try{let e=typeof window<"u"?window.location.href:"https://local/",t=new URL(n,e);return t.protocol==="http:"||t.protocol==="https:"?t.href:void 0}catch{return}}var Ze=new Set(["b","i","u","em","strong","a","p","br","span","ul","ol","li","h1","h2","h3","h4"]),et={a:new Set(["href","target","rel"])};function Q(n){if(typeof DOMParser>"u")return"";let t=new DOMParser().parseFromString(`<div>${n}</div>`,"text/html").body.firstElementChild;return t?(Ie(t),t.innerHTML):""}function Ie(n){let e=Array.from(n.children);for(let t of e){let r=t.tagName.toLowerCase();if(!Ze.has(r)){let i=document.createTextNode(t.textContent??"");t.replaceWith(i);continue}let s=et[r]??new Set;for(let i of Array.from(t.attributes)){if(!s.has(i.name.toLowerCase())){t.removeAttribute(i.name);continue}if(i.name.toLowerCase()==="href"){let o=I(i.value);o?t.setAttribute("href",o):t.removeAttribute(i.name)}}r==="a"&&(t.setAttribute("rel","noopener noreferrer"),t.setAttribute("target","_blank")),Ie(t)}}var M=class{constructor(e,t,r){this.messages=[];this.pollInterval=null;this.http=t,this.storage=r}onDisplay(e){this.onMessageDisplay=e}async checkMessages(){let e=await this.http.get("/in-app-messages/active");if(!e.success||!Array.isArray(e.data))return null;this.messages=e.data.map(tt);for(let t of this.messages){let r=`iam_shown_${t.id}`;if(!this.storage.get(r))return this.storage.set(r,"1"),this.onMessageDisplay&&this.onMessageDisplay(t),t}return null}async recordAction(e,t){await this.http.post("/in-app-messages/impressions",{messageId:e,action:t})}startPolling(e=3e5){this.stopPolling(),this.checkMessages(),this.pollInterval=setInterval(()=>this.checkMessages(),e)}stopPolling(){this.pollInterval&&clearInterval(this.pollInterval),this.pollInterval=null}getMessages(){return this.messages}destroy(){this.stopPolling()}};function tt(n){return{...n,content:{...n.content,ctaUrl:I(n.content.ctaUrl),imageUrl:I(n.content.imageUrl)}}}var rt=4e3,F=class{constructor(e,t,r){this.chatbotId=null;this.messages=[];this.http=t,this.storage=r;let s=this.storage.get("chat_session_id");this.sessionId=s??U("chat_"),s||this.storage.set("chat_session_id",this.sessionId)}init(e){if(typeof e!="string"||!/^[A-Za-z0-9_-]{6,64}$/.test(e))throw new Error("[SendoraCloud] Invalid chatbotId.");this.chatbotId=e}onNewMessage(e){this.onMessage=e}async sendMessage(e,t){if(!this.chatbotId||typeof e!="string"||e.length===0||e.length>rt)return null;let r={role:"user",content:e,timestamp:new Date().toISOString()};this.messages.push(r);let s=await this.http.post("/chatbot/message",{chatbotId:this.chatbotId,sessionId:this.sessionId,message:e,userId:t});if(s.success&&s.data&&typeof s.data.reply=="string"){let i={role:"assistant",content:s.data.reply,timestamp:new Date().toISOString()};return this.messages.push(i),this.onMessage&&this.onMessage(i),i}return null}getMessages(){return[...this.messages]}newSession(){this.messages=[],this.sessionId=U("chat_"),this.storage.set("chat_session_id",this.sessionId)}getSessionId(){return this.sessionId}};var H=class{constructor(e,t){this.listeners=new Set;this.granted=e,this.http=t}isGranted(){return this.granted}grant(){this.granted||(this.granted=!0,this.emit())}revoke(){this.granted&&(this.granted=!1,this.emit())}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async record(e){if(!this.http)throw new Error("consent.record requires SDK init (HttpClient unavailable)");let t=await this.http.post("/consent/record",e);if(!t.success||!t.data)throw new Error(t.error?.message??"consent.record failed");return t.data}async requestDeletion(e){if(!this.http)throw new Error("consent.requestDeletion requires SDK init (HttpClient unavailable)");let t=await this.http.post("/consent/deletion-request",e);if(!t.success||!t.data)throw new Error(t.error?.message??"consent.requestDeletion failed");return t.data}emit(){for(let e of this.listeners)try{e(this.granted)}catch{}}};var T="auth_access_token",R="auth_access_expires",m="auth_refresh_token",_="auth_user",be=3e4,nt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function y(n){if(!n||typeof n!="object")return!1;let e=n,t=e.user,r=e.tokens;return!(!t||typeof t.id!="string"||t.id.length===0||!r||typeof r.accessToken!="string"||r.accessToken.length===0||typeof r.refreshToken!="string"||r.refreshToken.length===0||typeof r.expiresIn!="number"||r.expiresIn<=0||t.isAnonymous!==void 0&&typeof t.isAnonymous!="boolean"||t.email!==void 0&&t.email!==null&&typeof t.email!="string"||t.emailVerified!==void 0&&typeof t.emailVerified!="boolean"||t.name!==void 0&&t.name!==null&&typeof t.name!="string"||t.signupMethod!==void 0&&t.signupMethod!==null&&typeof t.signupMethod!="string"||t.lastLoginMethod!==void 0&&t.lastLoginMethod!==null&&typeof t.lastLoginMethod!="string"||e.retiredAnonUserId!==void 0&&typeof e.retiredAnonUserId!="string")}var C=class extends Error{constructor(e="An account with this email already exists"){super(e),this.name="EmailAlreadyTakenError"}},K=class extends Error{constructor(e="Already signed in with an identity; use link*() to add a credential, or sign out first"){super(e),this.name="AlreadyIdentifiedError"}},D=class extends Error{constructor(t="This credential is already linked to a different account",r){super(t);this.code="CREDENTIAL_IN_USE";this.kind="credential_in_use";this.retryable=!1;this.name="CredentialInUseError",this.provider=r?.provider,this.collision=r?.collision,this.status=r?.status}};function Ee(n){let e=n?.error?.details;if(!e||typeof e!="object")return{};let t=e;return{provider:typeof t.provider=="string"?t.provider:void 0,collision:t.collision==="identity"||t.collision==="email"?t.collision:void 0}}var st=new Set(["network","server","rate_limited","account_locked"]);function it(n,e){switch(n){case"NETWORK_ERROR":case"NETWORK_TIMEOUT":return"network";case"PARSE_ERROR":return"server";case"RATE_LIMITED":case"RATE_LIMIT":case"RATE_LIMIT_EXCEEDED":case"QUOTA_EXCEEDED":return"rate_limited";case"ACCOUNT_LOCKED":return"account_locked";case"CREDENTIAL_IN_USE":return"credential_in_use";case"LAST_CREDENTIAL":return"last_credential";case"RECENT_AUTH_REQUIRED":return"recent_auth_required";case"NOT_ANONYMOUS":case"FORBIDDEN_NON_ANONYMOUS":return"already_identified";case"PASSKEY_USER_CANCELLED":case"GAME_CENTER_CANCELLED":case"PLAY_GAMES_CANCELLED":case"SSO_CANCELLED":return"cancelled";case"GAME_CENTER_UNAVAILABLE":case"PLAY_GAMES_UNAVAILABLE":case"ENTITLEMENT_ERROR":case"tier_required":return"config";case"UNAUTHORIZED":case"INVALID_CREDENTIALS":case"INVALID_REFRESH_TOKEN":case"EMAIL_OTP_INVALID":case"MAGIC_LINK_INVALID":case"PASSKEY_RP_MISMATCH":case"NOT_SIGNED_IN":return"invalid_credential";default:break}if(typeof e=="number"){if(e===429)return"rate_limited";if(e>=500)return"server";if(e>=400)return"invalid_credential"}return"unknown"}var c=class extends Error{constructor(e,t,r){super(t),this.name="AuthError",this.code=e,this.kind=r?.kind??it(e,r?.status),this.retryable=st.has(this.kind),this.retryAfterSeconds=r?.retryAfterSeconds,this.status=r?.status}};function ot(n){if(n instanceof c||n instanceof C||n instanceof K||n instanceof D)return n;let e=n?.name;return e==="AbortError"||e==="TimeoutError"||e==="NetworkTimeoutError"?new c("NETWORK_TIMEOUT",n instanceof Error?n.message:"timeout",{kind:"network"}):new c("UNKNOWN_ERROR",n instanceof Error?n.message:String(n),{kind:"unknown"})}function h(n){let e=n.error?.status,t=n.error?.details?.retryAfterSeconds;return{status:typeof e=="number"?e:void 0,retryAfterSeconds:typeof t=="number"&&Number.isFinite(t)&&t>0?t:void 0}}var V=class{constructor(e,t,r,s,i,o){this.user=null;this.accessToken=null;this.accessExpiresAt=0;this.clockSkewConfirmed=!1;this.inflight=Promise.resolve();this.refreshInflight=null;this.refreshFailureCount=0;this.refreshCooldownUntil=0;this.visibilityResetUnsub=null;this.proactiveRefreshTimer=null;this.proactiveRefreshCleanup=null;this.takeoverListeners=new Set;this.lastTakeover=null;this.deletionCancelledListeners=new Set;this.lastDeletionCancelled=null;this.lastAnonRetirement=null;this.authStateListeners=new Set;this.pendingAnonTakeover=null;this.hydrated=!1;this.http=t,this.storage=r,this.analytics=s,this.flags=i,this.chatbot=o;let a=this.storage.get(_),u=this.storage.get(T),l=this.storage.get(m),g=this.storage.get(R);if(a&&(u||l))try{let v=JSON.parse(a);if(typeof v.id!="string"||v.id.length===0)throw new Error("invalid cache");this.user=v,u?(this.accessToken=u,this.accessExpiresAt=g?Number(g):0):(this.accessToken=null,this.accessExpiresAt=0),this.analytics.identify(this.user.id)}catch{this.storage.remove(_),this.storage.remove(T),this.storage.remove(R)}this.hydrated=!0}getCurrentUser(){return this.user}onDeviceTakeover(e){return this.takeoverListeners.add(e),()=>{this.takeoverListeners.delete(e)}}getLastDeviceTakeover(){return this.lastTakeover}onAuthStateChanged(e){if(this.authStateListeners.add(e),this.hydrated&&this.user){let t=this.user;try{e({event:"signed_in",user:t})}catch{}}return()=>{this.authStateListeners.delete(e)}}emitAuthState(e){for(let t of this.authStateListeners)try{t(e)}catch{}}fireDeviceTakeover(e,t){if(!e||!nt.test(e))return;let r={retiredAnonUserId:e,identifiedUserId:t,at:new Date};this.lastTakeover=r;for(let s of this.takeoverListeners)try{s(r)}catch{}this.emitAuthState({event:"device_takeover",user:this.user,retiredAnonUserId:e})}onDeletionCancelled(e){return this.deletionCancelledListeners.add(e),()=>{this.deletionCancelledListeners.delete(e)}}getLastDeletionCancelled(){return this.lastDeletionCancelled}getLastAnonRetirement(){return this.lastAnonRetirement}fireDeletionCancelled(e){let t={userId:e,at:new Date};this.lastDeletionCancelled=t;for(let r of this.deletionCancelledListeners)try{r(t)}catch{}this.emitAuthState({event:"deletion_cancelled",user:this.user})}takeoverHint(){if(this.user?.isAnonymous)return this.storage.get(m)??void 0}canServeToken(e,t,r){return!e||!t||r>=t-be?!1:this.clockSkewConfirmed?!0:Re(e,r)}canServeCachedToken(e){return this.canServeToken(this.accessToken,this.accessExpiresAt,e)}trackedDeadlineAlive(e){return!!this.accessToken&&!!this.accessExpiresAt&&e<this.accessExpiresAt-be}deadlinesDisagree(e){return this.trackedDeadlineAlive(e)&&!this.canServeCachedToken(e)}learnClockSkewFrom(e,t){Re(e,t)||(this.clockSkewConfirmed=!0)}async refreshAndReconcile(e){let t=this.deadlinesDisagree(e),r=await this.refreshAccessToken();return t&&r&&this.learnClockSkewFrom(r,Date.now()),r}async getAccessToken(e){return!e?.forceRefresh&&this.canServeCachedToken(Date.now())?this.accessToken:this.storage.get(m)?this.refreshInflight?this.refreshInflight:Date.now()<this.refreshCooldownUntil?null:this.refreshAndReconcile(Date.now()):null}getAccessTokenSync(){return this.accessToken}signInAnonymously(e){return this.serialize(async()=>{let t=this.user;if(!e?.forceNew&&t?.isAnonymous&&this.storage.get(m))return t;let r=await this.http.post("/auth-service/anonymous",{name:e?.name,metadata:e?.metadata});if(!r.success||!y(r.data))throw new c(r.error?.code??"AUTH_ERROR",r.error?.message??"Anonymous signup failed",h(r));return this.persist(r.data),r.data.user})}signUp(e,t,r){return this.serialize(async()=>{let s=this.storage.get(m);if(s){let o=await this.http.post("/auth-service/upgrade",{refreshToken:s,email:e,password:t,name:r?.name});if(o.success&&y(o.data))return this.persist(o.data),o.data.user;let a=o.error?.code??"",u=h(o),l=u.status;if(a==="NOT_ANONYMOUS"||a==="FORBIDDEN_NON_ANONYMOUS")throw new K(o.error?.message);if(a==="CONFLICT"||a==="EMAIL_ALREADY_TAKEN"||l===409)throw new C(o.error?.message);if(a==="INVALID_REFRESH"||a==="UNAUTHORIZED"||a==="REFRESH_EXPIRED")await this.analytics.flush(),this.wipeLocalIdentity("session_expired");else throw new c(a||"AUTH_ERROR",o.error?.message??"Upgrade failed",u)}let i=await this.http.post("/auth-service/signup",{email:e,password:t,name:r?.name,metadata:r?.metadata});if(!i.success||!y(i.data)){let o=i.error?.code??"";throw o==="CONFLICT"?new C(i.error?.message):new c(o||"AUTH_ERROR",i.error?.message??"Signup failed",h(i))}return this.persist(i.data),i.data.user})}signIn(e,t){return this.serialize(async()=>{let r=this.takeoverHint(),s=await this.http.post("/auth-service/login",{email:e,password:t,...r?{prevAnonRefreshToken:r}:{}});if(!s.success||!s.data)throw new c(s.error?.code??"AUTH_ERROR",s.error?.message??"Login failed",h(s));let i=s.data;if(i.mfaRequired===!0&&typeof i.mfaChallengeToken=="string"){r&&(this.pendingAnonTakeover={challengeToken:i.mfaChallengeToken,prevAnonRefreshToken:r});let o=i.user;return{mfaRequired:!0,mfaChallengeToken:i.mfaChallengeToken,userId:o?.id??""}}if(!y(s.data))throw new c(s.error?.code??"AUTH_ERROR",s.error?.message??"Login failed",h(s));return await this.replaceLocalIdentity(),this.persist(s.data),s.data.user})}loginSocial(e){return this.serialize(async()=>{let t=this.takeoverHint(),{link:r,onCredentialInUse:s,...i}=e,o=await this.http.post("/auth-service/login/social",{...i,...t?{prevAnonRefreshToken:t}:{},...r?{linkAnonymous:!0}:{},...s?{onCredentialInUse:s}:{}});if(!o.success||!y(o.data))throw o.error?.code==="CREDENTIAL_IN_USE"?new D(o.error.message,{...Ee(o),status:h(o).status}):new c(o.error?.code??"SOCIAL_LOGIN_FAILED",o.error?.message??"Social login failed",h(o));return await this.replaceLocalIdentity(),this.persist(o.data),o.data.user})}signInWithGoogle(e,t,r){return this.loginSocial({provider:"google",code:e,redirectUri:t,link:r})}signInWithGitHub(e,t){return this.loginSocial({provider:"github",code:e,redirectUri:t})}signInWithApple(e){return this.loginSocial({provider:"apple",...e})}signInWithMicrosoft(e,t){return this.loginSocial({provider:"microsoft",code:e,redirectUri:t})}signInWithLinkedIn(e,t){return this.loginSocial({provider:"linkedin",code:e,redirectUri:t})}signInWithFacebook(e,t){return this.loginSocial({provider:"facebook",code:e,redirectUri:t})}linkEmailPassword(e,t){return this.linkCredential("/auth-service/me/link/email",{email:e,password:t})}linkSocial(e){return this.linkCredential("/auth-service/me/link/social",e)}linkGoogle(e){return this.linkSocial({provider:"google",...e})}linkApple(e){return this.linkSocial({provider:"apple",...e})}async linkCredential(e,t){let r=await this.getAccessToken();if(!r)throw new c("NOT_SIGNED_IN","Sign in before linking a credential");let s=await this.http.post(e,t,{Authorization:`Bearer ${r}`});if(!s.success||!s.data?.user){let i=s.error?.code??"LINK_FAILED";throw i==="CREDENTIAL_IN_USE"?new D(s.error?.message,{...Ee(s),status:h(s).status}):new c(i,s.error?.message??"Failed to link credential",h(s))}return s.data.upgraded&&y(s.data)?(this.persist(s.data),s.data.user):(this.updateLocalUser(s.data.user),s.data.user)}updateLocalUser(e){this.user=e,this.storage.set(_,JSON.stringify(e))}async listLinkedIdentities(){let e=await this.getAccessToken();if(!e)throw new c("NOT_SIGNED_IN","Sign in before listing linked identities");let t=await this.http.get("/auth-service/me/identities",{Authorization:`Bearer ${e}`});if(!t.success||!t.data)throw new c(t.error?.code??"IDENTITIES_FAILED",t.error?.message??"Failed to list linked identities",h(t));return{identities:t.data.identities??[],hasPassword:!!t.data.hasPassword}}async unlink(e){let t=await this.getAccessToken();if(!t)throw new c("NOT_SIGNED_IN","Sign in before unlinking an identity");let r=await this.http.delete(`/auth-service/me/identities/${encodeURIComponent(e)}`,{Authorization:`Bearer ${t}`});if(!r.success||!r.data)throw new c(r.error?.code??"UNLINK_FAILED",r.error?.message??"Failed to unlink identity",h(r));return{provider:r.data.provider??e,removed:Number(r.data.removed??0),remaining:Number(r.data.remaining??0)}}signInWithDiscord(e,t){return this.loginSocial({provider:"discord",code:e,redirectUri:t})}challengeMfa(e,t){return this.serialize(async()=>{let s=(this.pendingAnonTakeover?.challengeToken===e?this.pendingAnonTakeover.prevAnonRefreshToken:void 0)??this.takeoverHint(),i=await this.http.post("/auth-service/mfa/challenge",{challengeToken:e,code:t,...s?{prevAnonRefreshToken:s}:{}});if(!i.success||!y(i.data))throw new c(i.error?.code??"MFA_CHALLENGE_FAILED",i.error?.message??"Invalid MFA code",h(i));return await this.replaceLocalIdentity(),this.persist(i.data),i.data.user})}async sendMagicLink(e){let t=await this.http.post("/auth-service/magic-link/request",{email:e});if(!t.success)throw new c(t.error?.code??"MAGIC_LINK_REQUEST_FAILED",t.error?.message??"Failed to send link")}async sendEmailOtp(e){let t=await this.http.post("/auth-service/email-otp/request",{email:e});if(!t.success)throw new c(t.error?.code??"EMAIL_OTP_REQUEST_FAILED",t.error?.message??"Failed to send code")}verifyEmailOtp(e,t){return this.serialize(async()=>{let r=this.takeoverHint(),s=await this.http.post("/auth-service/email-otp/verify",{email:e,code:t,...r?{prevAnonRefreshToken:r}:{}});if(!s.success||!y(s.data))throw new c(s.error?.code??"EMAIL_OTP_INVALID",s.error?.message??"Wrong or expired code",h(s));return await this.replaceLocalIdentity(),this.persist(s.data),s.data.user})}async requestPasswordReset(e){let t=await this.http.post("/auth-service/password/forgot",{email:e});if(!t.success)throw new c(t.error?.code??"PASSWORD_RESET_REQUEST_FAILED",t.error?.message??"Failed to send reset email")}async resetPassword(e,t){let r=await this.http.post("/auth-service/password/reset",{token:e,newPassword:t});if(!r.success)throw new c(r.error?.code??"PASSWORD_RESET_FAILED",r.error?.message??"Reset failed")}async verifyEmail(e){let t=await this.http.post("/auth-service/email/verify",{token:e});if(!t.success)throw new c(t.error?.code??"EMAIL_VERIFICATION_FAILED",t.error?.message??"Verification failed")}async sendVerificationEmail(){let e=await this.getAccessToken();if(!e)throw new c("UNAUTHORIZED","Sign in before requesting a verification email");let t=await this.http.post("/auth-service/email/verify/resend",{},{Authorization:`Bearer ${e}`});if(!t.success)throw new c(t.error?.code??"VERIFICATION_RESEND_FAILED",t.error?.message??"Failed to send verification email")}verifyMagicLink(e){return this.serialize(async()=>{let t=this.takeoverHint(),r=await this.http.post("/auth-service/magic-link/verify",{token:e,...t?{prevAnonRefreshToken:t}:{}});if(!r.success||!y(r.data))throw new c(r.error?.code??"MAGIC_LINK_INVALID",r.error?.message??"Invalid or expired magic link",h(r));return await this.replaceLocalIdentity(),this.persist(r.data),r.data.user})}async enrollMfa(){let e=await this.http.post("/auth-service/mfa/enroll/start",{},await this.bearerHeaders());if(!e.success||!e.data)throw new c(e.error?.code??"MFA_ENROLL_FAILED",e.error?.message??"MFA enrollment failed");return e.data}async confirmMfa(e){let t=await this.http.post("/auth-service/mfa/enroll/confirm",{code:e},await this.bearerHeaders());return!!(t.success&&t.data?.confirmed)}async disableMfa(){let e=await this.http.post("/auth-service/mfa/disable",{},await this.bearerHeaders());if(!e.success)throw new c(e.error?.code??"MFA_DISABLE_FAILED",e.error?.message??"Failed to disable MFA",h(e))}async registerPasskey(e){if(typeof navigator>"u"||!navigator.credentials)throw new c("PASSKEY_UNSUPPORTED","WebAuthn not supported in this environment");let t=await this.http.post("/auth-service/passkeys/register/start",{},await this.bearerHeaders());if(!t.success||!t.data)throw new c(t.error?.code??"PASSKEY_START_FAILED",t.error?.message??"Passkey start failed");let r=ct(t.data),s;try{let a=await navigator.credentials.create({publicKey:r});if(!a)throw new Error("create returned null");s=a}catch(a){throw new c("PASSKEY_USER_CANCELLED",a instanceof Error?a.message:"User cancelled passkey registration")}let i=lt(s),o=await this.http.post("/auth-service/passkeys/register/finish",{response:i,name:e},await this.bearerHeaders());if(!o.success||!o.data)throw new c(o.error?.code??"PASSKEY_FINISH_FAILED",o.error?.message??"Passkey verification failed");return o.data}signInWithPasskey(e){return this.serialize(async()=>{if(typeof navigator>"u"||!navigator.credentials)throw new c("PASSKEY_UNSUPPORTED","WebAuthn not supported in this environment");let t=this.takeoverHint(),r=await this.http.post("/auth-service/passkeys/authenticate/start",{userId:e??null});if(!r.success||!r.data)throw new c(r.error?.code??"PASSKEY_START_FAILED",r.error?.message??"Passkey start failed",h(r));let s=ut(r.data),i;try{let u=await navigator.credentials.get({publicKey:s});if(!u)throw new Error("get returned null");i=u}catch(u){throw new c("PASSKEY_USER_CANCELLED",u instanceof Error?u.message:"User cancelled passkey signin")}let o=ht(i),a=await this.http.post("/auth-service/passkeys/authenticate/finish",{response:o,userId:e??null,...t?{prevAnonRefreshToken:t}:{}});if(!a.success||!y(a.data))throw new c(a.error?.code??"PASSKEY_AUTH_FAILED",a.error?.message??"Passkey signin failed",h(a));return await this.replaceLocalIdentity(),this.persist(a.data),a.data.user})}async listPasskeys(){let e=await this.http.get("/auth-service/passkeys",await this.bearerHeaders());return!e.success||!Array.isArray(e.data)?[]:e.data}async deletePasskey(e){let t=await this.http.delete(`/auth-service/passkeys/${encodeURIComponent(e)}`,await this.bearerHeaders());if(!t.success)throw new c(t.error?.code??"PASSKEY_DELETE_FAILED",t.error?.message??"Failed to delete passkey",h(t))}async listMySessions(){let e=await this.http.get("/auth-service/sessions/me",await this.bearerHeaders());return!e.success||!Array.isArray(e.data)?[]:e.data}async revokeSession(e){let t=await this.http.delete(`/auth-service/sessions/me/${encodeURIComponent(e)}`,await this.bearerHeaders());if(!t.success)throw new c(t.error?.code??"SESSION_REVOKE_FAILED",t.error?.message??"Failed to revoke session",h(t))}async revokeAllSessions(){let e=await this.http.delete("/auth-service/sessions/me",await this.bearerHeaders());if(!e.success)throw new c(e.error?.code??"SESSION_REVOKE_ALL_FAILED",e.error?.message??"Failed to sign out other devices",h(e))}async startSso(e){let t=this.takeoverHint(),r=await this.http.post("/auth-service/sso/oidc/start",{returnTo:e,...t?{prevAnonRefreshToken:t}:{}});if(!r.success||!r.data)throw new c(r.error?.code??"SSO_START_FAILED",r.error?.message??"SSO start failed");return r.data}async signInWithSso(e){let t=e??(typeof window<"u"?window.location.origin:"");if(!t)throw new c("SSO_NO_RETURN_TO","returnTo required outside browser context");let r=await this.startSso(t);typeof window<"u"&&(window.location.href=r.authorizationUrl)}async startSaml(e){let t=this.takeoverHint(),r=await this.http.post("/auth-service/sso/saml/start",{returnTo:e,...t?{prevAnonRefreshToken:t}:{}});if(!r.success||!r.data)throw new c(r.error?.code??"SAML_START_FAILED",r.error?.message??"SAML start failed");return r.data}async signInWithSaml(e){let t=e??(typeof window<"u"?window.location.origin:"");if(!t)throw new c("SAML_NO_RETURN_TO","returnTo required outside browser context");let r=await this.startSaml(t);typeof window<"u"&&(window.location.href=r.authorizationUrl)}consumeSsoTokenFromUrl(){return this.serialize(async()=>{if(typeof window>"u")return null;let e=window.location.hash.replace(/^#/,"");if(!e)return null;let t=new URLSearchParams(e),r=t.get("sendora_oidc_error")??t.get("sendora_saml_error");if(r)throw window.history.replaceState(null,"",window.location.pathname+window.location.search),new c("SSO_FAILED",decodeURIComponent(r));let s=t.get("sendora_oidc_token")??t.get("sendora_saml_token");if(!s)return null;let i=t.get("sendora_retired_anon");window.history.replaceState(null,"",window.location.pathname+window.location.search);let o=await this.http.post("/auth-service/token/refresh",{refreshToken:s}),a=o.success?Te(o.data):null;if(!a)throw new c(o.error?.code??"SSO_EXCHANGE_FAILED",o.error?.message??"Could not exchange SSO token",h(o));let u={...a,tokenType:"Bearer"};await this.replaceLocalIdentity(),this.accessToken=u.accessToken,this.accessExpiresAt=Date.now()+u.expiresIn*1e3,this.storage.set(T,u.accessToken),this.storage.set(R,String(this.accessExpiresAt)),this.storage.set(m,u.refreshToken);let l=_e(u.accessToken),g={id:l?.sub??"",email:l?.email??null,emailVerified:l?.email_verified??!0,name:l?.name??null,isAnonymous:!1};return this.user=g,this.storage.set(_,JSON.stringify(g)),this.analytics.identify(g.id),this.flags.setContext({userId:g.id}),this.emitAuthState({event:"signed_in",user:g}),i&&this.fireDeviceTakeover(i,g.id),g})}async bearerHeaders(){let e=await this.getAccessToken();if(!e)throw new c("NOT_SIGNED_IN","Not signed in");return{Authorization:`Bearer ${e}`}}signOut(){return this.serialize(async()=>{let e=this.storage.get(m);this.wipeLocalIdentity("user"),e&&this.http.post("/auth-service/token/revoke",{refreshToken:e}).catch(()=>{})})}serialize(e){let t=async()=>{try{return await e()}catch(s){throw ot(s)}},r=this.inflight.then(t,t);return this.inflight=r.catch(()=>{}),r}async refreshAccessToken(){if(this.refreshInflight)return this.refreshInflight;let e=this.storage.get(m);if(!e)return null;let t=typeof navigator<"u"&&"locks"in navigator,r=async()=>{let s=this.storage.get(m);if(s&&s!==e){let i=this.storage.get(T),o=this.storage.get(R);if(i&&o){let a=Number(o);if(Number.isFinite(a)&&this.canServeToken(i,a,Date.now()))return this.accessToken=i,this.accessExpiresAt=a,i}}try{let i=s??e,o=await this.http.post("/auth-service/token/refresh",{refreshToken:i});if(!o.success)return at(o.error?.code)&&this.tokenStillCurrent(i)?(this.wipeLocalIdentity("session_expired"),this.refreshFailureCount=0,this.refreshCooldownUntil=0,null):(this.armBackoff(),null);let a=Te(o.data);if(!a)return this.armBackoff(),null;if(!this.tokenStillCurrent(i))return null;if(this.accessToken=a.accessToken,this.accessExpiresAt=Date.now()+a.expiresIn*1e3,this.storage.set(T,a.accessToken),this.storage.set(R,String(this.accessExpiresAt)),this.storage.set(m,a.refreshToken),this.user===null){let u=dt(o.data);u&&(this.user=u,this.storage.set(_,JSON.stringify(u)),this.analytics.identify(u.id),this.emitAuthState({event:"signed_in",user:u}))}return this.refreshFailureCount=0,this.refreshCooldownUntil=0,a.accessToken}catch{return this.armBackoff(),null}};return this.refreshInflight=(async()=>{try{return t?await navigator.locks.request("sendora-authservice-refresh",{mode:"exclusive"},r):await r()}finally{this.refreshInflight=null}})(),this.refreshInflight}armBackoff(){this.refreshFailureCount+=1;let e=Math.min(3e4,1e3*Math.pow(2,this.refreshFailureCount-1));this.refreshCooldownUntil=Date.now()+e}resetRefreshState(){this.refreshFailureCount=0,this.refreshCooldownUntil=0}startVisibilityRefreshReset(){if(this.visibilityResetUnsub||typeof document>"u")return;let e=()=>{document.visibilityState==="visible"&&this.resetRefreshState()};document.addEventListener("visibilitychange",e),this.visibilityResetUnsub=()=>document.removeEventListener("visibilitychange",e)}stopVisibilityRefreshReset(){this.visibilityResetUnsub&&(this.visibilityResetUnsub(),this.visibilityResetUnsub=null)}startProactiveRefreshCron(){if(typeof window>"u"||this.proactiveRefreshTimer)return;let e=.8,t=6e4,r=3e4,s=async()=>{if(!this.accessToken||!this.accessExpiresAt)return;let o=Date.now();if(!this.canServeCachedToken(o)){await this.refreshAndReconcile(o);return}let a=this.accessExpiresAt-o;if(a<=0)return;let l=Math.max(a,5*6e4)*(1-e)+(Math.random()*r*2-r);a<=l&&await this.refreshAccessToken()};this.proactiveRefreshTimer=window.setInterval(()=>{s()},t);let i=()=>{document.visibilityState==="visible"&&s()};document.addEventListener("visibilitychange",i),this.proactiveRefreshCleanup=()=>{this.proactiveRefreshTimer&&(window.clearInterval(this.proactiveRefreshTimer),this.proactiveRefreshTimer=null),document.removeEventListener("visibilitychange",i)}}stopProactiveRefreshCron(){this.proactiveRefreshCleanup&&(this.proactiveRefreshCleanup(),this.proactiveRefreshCleanup=null)}persist(e){this.user=e.user,this.accessToken=e.tokens.accessToken,this.accessExpiresAt=Date.now()+e.tokens.expiresIn*1e3,this.storage.set(_,JSON.stringify(e.user)),this.storage.set(T,e.tokens.accessToken),this.storage.set(R,String(this.accessExpiresAt)),this.storage.set(m,e.tokens.refreshToken),this.analytics.identify(e.user.id),this.flags.setContext({userId:e.user.id}),this.startProactiveRefreshCron(),this.startVisibilityRefreshReset(),this.emitAuthState({event:"signed_in",user:e.user}),e.retiredAnonUserId&&this.fireDeviceTakeover(e.retiredAnonUserId,e.user.id),e.anonRetirement&&(this.lastAnonRetirement=e.anonRetirement),e.reactivatedFromDeletion&&this.fireDeletionCancelled(e.user.id)}async replaceLocalIdentity(){this.user!==null&&(await this.analytics.flush(),this.wipeLocalIdentity("replaced"))}tokenStillCurrent(e){return this.storage.get(m)===e}wipeLocalIdentity(e="replaced"){this.user=null,this.accessToken=null,this.accessExpiresAt=0,this.clockSkewConfirmed=!1,this.lastTakeover=null,this.lastDeletionCancelled=null,this.lastAnonRetirement=null,this.pendingAnonTakeover=null,this.storage.remove(_),this.storage.remove(T),this.storage.remove(R),this.storage.remove(m),this.analytics.reset(e==="user"||e==="account_deleted"),this.analytics.dropQueue(),this.flags.reset(),this.chatbot.newSession(),this.stopProactiveRefreshCron(),this.stopVisibilityRefreshReset(),this.refreshFailureCount=0,this.refreshCooldownUntil=0,e!=="replaced"&&this.emitAuthState({event:"signed_out",user:null,reason:e})}};function at(n){return n?n==="INVALID_REFRESH_TOKEN":!1}function z(n){let e=(4-n.length%4)%4,t=(n+"===".slice(0,e)).replace(/-/g,"+").replace(/_/g,"/"),r=atob(t),s=new ArrayBuffer(r.length),i=new Uint8Array(s);for(let o=0;o<r.length;o++)i[o]=r.charCodeAt(o);return s}function b(n){let e=n instanceof Uint8Array?n:new Uint8Array(n),t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function ct(n){return{challenge:z(n.challenge),rp:n.rp,user:{id:z(n.user.id),name:n.user.name,displayName:n.user.displayName},pubKeyCredParams:n.pubKeyCredParams,timeout:n.timeout,attestation:n.attestation,excludeCredentials:n.excludeCredentials?.map(e=>({id:z(e.id),type:"public-key",transports:e.transports})),authenticatorSelection:n.authenticatorSelection}}function ut(n){return{challenge:z(n.challenge),timeout:n.timeout,rpId:n.rpId,allowCredentials:n.allowCredentials?.map(e=>({id:z(e.id),type:"public-key",transports:e.transports})),userVerification:n.userVerification}}function lt(n){let e=n.response;return{id:n.id,rawId:b(n.rawId),type:n.type,response:{clientDataJSON:b(e.clientDataJSON),attestationObject:b(e.attestationObject),transports:typeof e.getTransports=="function"?e.getTransports():void 0},clientExtensionResults:n.getClientExtensionResults()}}function Te(n){if(!n||typeof n!="object")return null;let e=n.tokens,t=e&&typeof e=="object"?e:n;return typeof t.accessToken!="string"||!t.accessToken||typeof t.refreshToken!="string"||!t.refreshToken||typeof t.expiresIn!="number"||t.expiresIn<=0?null:{accessToken:t.accessToken,refreshToken:t.refreshToken,expiresIn:t.expiresIn}}function dt(n){if(!n||typeof n!="object")return null;let e=n.user;if(!e||typeof e!="object")return null;let t=e.id;return typeof t!="string"||t.length===0?null:e}function Re(n,e){let t=_e(n);if(!t)return!0;let r=t.exp;return typeof r!="number"||!Number.isFinite(r)?!0:e<r*1e3}function _e(n){try{let e=n.split(".");if(e.length!==3)return null;let t=e[1].replace(/-/g,"+").replace(/_/g,"/"),r=atob(t+"===".slice(0,(4-t.length%4)%4));return JSON.parse(r)}catch{return null}}function ht(n){let e=n.response;return{id:n.id,rawId:b(n.rawId),type:n.type,response:{clientDataJSON:b(e.clientDataJSON),authenticatorData:b(e.authenticatorData),signature:b(e.signature),userHandle:e.userHandle?b(e.userHandle):null},clientExtensionResults:n.getClientExtensionResults()}}function pt(n){return n===!1?{pageViews:!1,sessionStart:!1,appOpen:!1,appBackground:!1,engagement:!1}:n===!0||n===void 0?{pageViews:!0,sessionStart:!0,appOpen:!0,appBackground:!0,engagement:!0}:{pageViews:n.pageViews??!0,sessionStart:n.sessionStart??!0,appOpen:n.appOpen??!0,appBackground:n.appBackground??!0,engagement:n.engagement??!0}}var gt=250,Ce=360*60*1e3;function Pe(n,e){if(typeof window>"u")return()=>{};let t=pt(e.autoTrack),r=e.sessionIdleMs??18e5,s=[],i="sendora_session_id",o="sendora_session_last_activity";function a(){return De(i)??""}function u(d){Le(i,d)}function l(){let d=De(o);return d&&Number(d)||0}function g(d){Le(o,String(d))}function v(){return`sess_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`}function w(d){let S=Date.now(),q=l();if(!a()||q&&S-q>r){let G=v();u(G),d&&t.sessionStart&&n.track("session.start",{sessionId:G})}g(S)}w(t.sessionStart),t.appOpen&&n.track("app.opened",{sessionId:a()||void 0,url:window.location.origin+window.location.pathname,referrer:document.referrer||void 0});let k=window.location.pathname,L=0,A=document.visibilityState==="visible"?Date.now():0;function ne(){A>0&&(L+=Date.now()-A,A=0)}function j(){if(!t.engagement)return;ne();let d=L;if(L=0,!(d<gt)){d>Ce&&(d=Ce);try{n.track("app.engagement",{durationMs:Math.round(d),screen:k,sessionId:a()||void 0})}catch{}}}function Ne(d){k=d,L=0,A=document.visibilityState==="visible"?Date.now():0}if(t.pageViews||t.engagement){t.pageViews&&n.page();let d=()=>{j(),w(!0),t.pageViews&&n.page(),Ne(window.location.pathname)},S=()=>d();window.addEventListener("popstate",S),s.push(()=>window.removeEventListener("popstate",S));let q=window;if(!q.__sendoraHistoryPatched){q.__sendoraHistoryPatched=!0;let G=history.pushState,xe=history.replaceState;history.pushState=function(...ie){let oe=G.apply(this,ie);return window.dispatchEvent(new Event("sendora:locationchange")),oe},history.replaceState=function(...ie){let oe=xe.apply(this,ie);return window.dispatchEvent(new Event("sendora:locationchange")),oe}}let se=()=>d();window.addEventListener("sendora:locationchange",se),s.push(()=>window.removeEventListener("sendora:locationchange",se))}if(t.appBackground||t.engagement){let d=()=>{if(document.visibilityState==="hidden"){j(),t.appBackground&&(w(!0),n.track("app.backgrounded",{sessionId:a()||void 0}));try{n.flush()}catch{}}else document.visibilityState==="visible"&&(t.appBackground&&(w(!0),n.track("app.foregrounded",{sessionId:a()||void 0})),t.engagement&&A===0&&(A=Date.now()))};if(document.addEventListener("visibilitychange",d),s.push(()=>document.removeEventListener("visibilitychange",d)),t.engagement){let S=()=>{j();try{n.flush()}catch{}};window.addEventListener("pagehide",S),s.push(()=>window.removeEventListener("pagehide",S))}}let pe=0,P=()=>{let d=Date.now();d-pe<5e3||(pe=d,w(!0))};return window.addEventListener("click",P,{passive:!0}),window.addEventListener("keydown",P,{passive:!0}),window.addEventListener("scroll",P,{passive:!0}),s.push(()=>{window.removeEventListener("click",P),window.removeEventListener("keydown",P),window.removeEventListener("scroll",P)}),()=>{j();for(let d of s)try{d()}catch{}}}function De(n){try{return window.sessionStorage?.getItem(n)??null}catch{return null}}function Le(n,e){try{window.sessionStorage?.setItem(n,e)}catch{}}var $=class n{constructor(e){this.http=e}static isSupported(){return typeof window>"u"?!1:"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window}static permission(){return typeof Notification>"u"?"denied":Notification.permission}async subscribe(e){if(!n.isSupported())throw new Error("[sendoracloud] Web Push not supported in this browser.");let t=Notification.permission;if(t==="default"&&(t=await Notification.requestPermission()),t!=="granted")throw new Error(`[sendoracloud] Notification permission ${t}.`);let r=await navigator.serviceWorker.getRegistration(e.scope??"/");r||(r=await navigator.serviceWorker.register(e.serviceWorkerPath,{scope:e.scope??"/"})),await navigator.serviceWorker.ready;let i=(await this.http.get("/push/vapid"))?.data?.publicKey;if(!i)throw new Error("[sendoracloud] backend returned no VAPID public key.");let a=await r.pushManager.getSubscription()??await r.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:ft(i)}),u=a.toJSON(),l=u.endpoint,g=u.keys?.p256dh??"",v=u.keys?.auth??"",w=await mt(l),k=await this.http.post("/push/tokens",{platform:"web",token:w,webEndpoint:l,webP256dh:g,webAuth:v,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,locale:typeof navigator<"u"?navigator.language:void 0,timezone:Intl?.DateTimeFormat?.().resolvedOptions?.().timeZone,...e.userId?{userId:e.userId}:{}});if(!k?.data?.tokenId)throw new Error("[sendoracloud] backend returned no tokenId on subscribe.");return{tokenId:k.data.tokenId,subscription:a}}async unsubscribe(e="/"){if(!n.isSupported())return!1;let t=await navigator.serviceWorker.getRegistration(e);if(!t)return!1;let r=await t.pushManager.getSubscription();return r?await r.unsubscribe():!1}async trackOpen(e,t){let r={sendId:e};t!==void 0&&(r.clickAction=t);let s=await this.http.post("/push/track-open",r);if(!s.success)throw new Error(s.error?.message??"push.trackOpen failed")}};function ft(n){let e="=".repeat((4-n.length%4)%4),t=(n+e).replace(/-/g,"+").replace(/_/g,"/"),r=atob(t),s=new Uint8Array(r.length);for(let i=0;i<r.length;i++)s[i]=r.charCodeAt(i);return s}async function mt(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}var W=class{constructor(e){}unsupported(){throw new Error("[SendoraCloud] sendora.audiences is not available in the browser SDK. Audiences require a secret (sk_*) key with the audiences:read/write scopes and must be managed from a trusted server, not the browser.")}list(){return this.unsupported()}get(e){return this.unsupported()}create(e){return this.unsupported()}update(e,t){return this.unsupported()}delete(e){return this.unsupported()}};var p=class extends Error{constructor(e,t,r){super(t),this.name="LinkError",this.code=e,this.statusCode=r}};function de(n,e){let t=(n??"").toUpperCase();return t==="NOT_FOUND"?new p("NOT_FOUND",e):t==="FORBIDDEN"||t==="UNAUTHORIZED"?new p("UNAUTHORIZED",e):t==="RATE_LIMITED"?new p("RATE_LIMITED",e):t==="ENTITLEMENT_ERROR"||/plan limit/i.test(e)?new p("PLAN_LIMIT",e):t==="VALIDATION_ERROR"?/iOS bundle|Android package/i.test(e)?new p("BUNDLE_MISMATCH",e):/2KB|10KB|linkData/i.test(e)?new p("DATA_TOO_LARGE",e):/fallbackUrl/i.test(e)&&/apps/i.test(e)?new p("FALLBACK_REQUIRED",e):new p("INVALID_INPUT",e):t==="PARSE_ERROR"||t==="HTTP_ERROR"||/HTTP \d{3}/.test(e)?new p("NETWORK",e):new p("UNKNOWN",e||`Unknown LinkError (code=${n??"none"})`)}var he=/^[a-z0-9-]{3,20}$/;function Ue(n){try{let t=new URL(n).pathname.split("/").filter(Boolean);if(t.length===0)return null;let r=t[t.length-1];return he.test(r)?r:null}catch{return null}}var yt=5*6e4,vt=50,wt=5,B=class{constructor(e){this.http=e;this.prewarmCache=new Map;this.prewarmInflight=0}cacheKey(e,t){if(t)return`k:${t}`;let r={},s=e;for(let i of Object.keys(s).sort())r[i]=s[i];return`s:${JSON.stringify(r)}`}evictExpired(){let e=Date.now();for(let[t,r]of this.prewarmCache)e-r.ts>yt&&this.prewarmCache.delete(t);for(;this.prewarmCache.size>vt;){let t=this.prewarmCache.keys().next().value;if(t===void 0)break;this.prewarmCache.delete(t)}}prewarm(e,t){this.evictExpired();let r=this.cacheKey(e,t?.key);if(this.prewarmCache.has(r)||this.prewarmInflight>=wt)return;this.prewarmInflight++;let s=this.doCreate(e).catch(i=>{throw this.prewarmCache.delete(r),i}).finally(()=>{this.prewarmInflight--});this.prewarmCache.set(r,{promise:s,ts:Date.now()})}async create(e,t){if(!e.title)throw new p("INVALID_INPUT","links.create: title is required");this.evictExpired();let r=this.cacheKey(e,t?.key),s=this.prewarmCache.get(r);return s?(this.prewarmCache.delete(r),s.promise):this.doCreate(e)}async doCreate(e){let t={title:e.title};e.fallbackUrl&&(t.fallbackUrl=e.fallbackUrl),e.iosDeepLinkPath&&(t.iosDeepLinkPath=e.iosDeepLinkPath),e.androidDeepLinkPath&&(t.androidDeepLinkPath=e.androidDeepLinkPath),e.linkData&&(t.linkData=e.linkData),e.ogTitle&&(t.ogTitle=e.ogTitle),e.ogDescription&&(t.ogDescription=e.ogDescription),e.ogImageUrl&&(t.ogImageUrl=e.ogImageUrl),e.campaign&&(t.campaign=e.campaign),e.source&&(t.source=e.source),e.medium&&(t.medium=e.medium),e.channel&&(t.channel=e.channel),e.tags&&(t.tags=e.tags),e.expiresAt&&(t.expiresAt=e.expiresAt),e.iosBundleId&&(t.iosBundleId=e.iosBundleId),e.androidPackageName&&(t.androidPackageName=e.androidPackageName);let r=await this.http.post("/sdk/links",t);if(!r.success||!r.data)throw de(r.error?.code,r.error?.message??"links.create failed");return r.data}async revoke(e){if(!he.test(e))throw new p("INVALID_INPUT",`links.revoke: '${e}' is not a valid shortcode`);let t=await this.http.post(`/sdk/links/${encodeURIComponent(e)}/revoke`,{});if(!t.success||!t.data)throw de(t.error?.code,t.error?.message??"links.revoke failed");return{shortcode:t.data.shortcode,revoked:!0}}async getStats(e){if(!he.test(e))throw new p("INVALID_INPUT",`links.getStats: '${e}' is not a valid shortcode`);let t=await this.http.get(`/sdk/links/${encodeURIComponent(e)}/stats`);if(!t.success||!t.data)throw de(t.error?.code,t.error?.message??"links.getStats failed");return t.data}};var J=class{constructor(e){this.http=e}async reportInstall(e={}){let t=await this.http.post("/attribution/install",e);if(!t.success||!t.data)throw new Error(t.error?.message??"attribution.reportInstall failed");return t.data}async checkDeferred(e={}){let t=await this.http.post("/attribution/deferred",e);if(!t.success)throw new Error(t.error?.message??"attribution.checkDeferred failed");return t.data??null}};var Z=class{constructor(e){this.http=e}async createTicket(e){let t=await this.http.post("/support/tickets",e);if(!t.success||!t.data)throw new Error(t.error?.message??"support.createTicket failed");return t.data}async submitCsat(e){let t=await this.http.post("/support/csat",e);if(!t.success||!t.data)throw new Error(t.error?.message??"support.submitCsat failed");return t.data}};var ee=class{constructor(e){this.http=e}async search(e){if(!e.query||e.query.trim().length===0)return[];let t=new URLSearchParams({query:e.query});e.limit&&t.set("limit",String(e.limit));let r=await this.http.get(`/kb/search?${t.toString()}`);if(!r.success||!Array.isArray(r.data))throw new Error(r.error?.message??"kb.search failed");return r.data}};var kt=/^[A-Za-z0-9_.-]{1,64}$/;function At(n){if(n!==void 0){if(typeof n!="string"||!kt.test(n))throw new Error(`[sendora] init: storagePrefix must be 1-64 chars of A-Z a-z 0-9 _ . - (got ${JSON.stringify(n)}). Changing it signs the browser out, so it is validated rather than ignored.`);return n}}var re=class re{constructor(e){this.autoTrackCleanup=null;this.http=new Y(e),this.storage=new X(At(e.storagePrefix),e.tokenStore==="memory"),this.consent=new H(e.defaultConsent===!0,this.http),this.analytics=new N(e,this.http,this.storage,this.consent),this.flags=new x(e,this.http,this.storage),this.surveys=new O(e,this.http,this.storage),this.messages=new M(e,this.http,this.storage),this.chatbot=new F(e,this.http,this.storage),this.auth=new V(e,this.http,this.storage,this.analytics,this.flags,this.chatbot),this.webPush=new $(this.http),this.audiences=new W(this.http),this.links=new B(this.http),this.attribution=new J(this.http),this.support=new Z(this.http),this.kb=new ee(this.http),e.autoTrack!==!1&&(this.autoTrackCleanup=Pe(this.analytics,e))}static init(e){return we(e.apiKey),new re(e)}static sanitizeHtml(e){return Q(e)}static safeUrl(e){return I(e)}track(e,t){this.analytics.track(e,t)}page(e){this.analytics.page(e)}identify(e,t,r){this.analytics.identify(e,t,r),this.flags.setContext({userId:e})}reset(){this.analytics.reset(),this.flags.reset(),this.chatbot.newSession()}async flush(){await this.analytics.flush()}destroy(){this.autoTrackCleanup&&(this.autoTrackCleanup(),this.autoTrackCleanup=null),this.analytics.destroy(),this.flags.destroy(),this.messages.destroy()}};re.version=E;var te=re,St=te;0&&(module.exports={AlreadyIdentifiedError,Analytics,Audiences,Auth,AuthError,Chatbot,Consent,CredentialInUseError,EmailAlreadyTakenError,FeatureFlags,InAppMessaging,LinkError,Links,SendoraCloud,Surveys,ValidationError,WebPush,extractShortcodeFromUrl,safeUrl,sanitizeHtml});
package/dist/index.d.cts CHANGED
@@ -45,6 +45,22 @@ interface SendoraConfig {
45
45
  * user. Pick one per environment before shipping and never change it.
46
46
  */
47
47
  storagePrefix?: string;
48
+ /**
49
+ * Where auth tokens (and all SDK state) are kept.
50
+ *
51
+ * - `"local"` (default) — `localStorage`. Durable across reloads, and
52
+ * **XSS-readable**: any script that runs on your origin can read the
53
+ * long-lived refresh token.
54
+ * - `"memory"` — kept only in a JS `Map`, never written to disk. An XSS
55
+ * payload or a malicious extension cannot exfiltrate a token that outlives
56
+ * the tab, at the cost of the session not surviving a page reload. Use it
57
+ * when your threat model treats the refresh token as too sensitive to
58
+ * persist (compliance, shared kiosks, high-value accounts).
59
+ *
60
+ * ⚠ s58.345: this flag used to be DOCUMENTED but not implemented — setting it
61
+ * silently no-op'd and tokens still hit localStorage. It is now real.
62
+ */
63
+ tokenStore?: "local" | "memory";
48
64
  /** Idle threshold (ms) for session expiry; default 30 minutes. */
49
65
  sessionIdleMs?: number;
50
66
  /** Event queue flush interval in ms (default 5000) */
@@ -182,7 +198,14 @@ declare class Storage {
182
198
  * shipping and never change it. Same frozen-key rule as ADR-023, delegated
183
199
  * to the integrator.
184
200
  */
185
- constructor(prefix?: string);
201
+ /**
202
+ * `memoryOnly` (s58.345) forces the in-memory `Map` and NEVER touches
203
+ * localStorage — the real implementation of `tokenStore: "memory"`. It is a
204
+ * hard opt-out, not the SSR/privacy fallback: `checkLocalStorage` is not even
205
+ * consulted, so a token cannot leak to disk on a browser where localStorage
206
+ * happens to be available.
207
+ */
208
+ constructor(prefix?: string, memoryOnly?: boolean);
186
209
  get(key: string): string | null;
187
210
  set(key: string, value: string): void;
188
211
  remove(key: string): void;
@@ -294,7 +317,16 @@ declare class Analytics {
294
317
  track(eventType: string, properties?: Record<string, unknown>): void;
295
318
  page(properties?: Record<string, unknown>): void;
296
319
  identify(userId: string, traits?: UserTraits, opts?: IdentifyOptions): void;
297
- reset(): void;
320
+ /**
321
+ * Clear the identity. `rotateAnonymousId` (default true) also regenerates the
322
+ * anonymous id — the person-boundary behaviour used on an explicit logout. Auth
323
+ * passes FALSE on a sign-in/upgrade or an involuntary session death: those keep
324
+ * the same person, so the anonymous id must SURVIVE so pre-auth analytics link to
325
+ * the now-real user (Firebase-FID / Segment-anonymousId norm). See auth.ts
326
+ * wipeLocalIdentity + the RN 1.38.0 write-up. Default true = logout/reset()
327
+ * unchanged.
328
+ */
329
+ reset(rotateAnonymousId?: boolean): void;
298
330
  /**
299
331
  * Drop any pending events without flushing. Used by Auth on
300
332
  * cross-account signin to ensure the prior identity's queued
@@ -1314,12 +1346,14 @@ declare class Auth {
1314
1346
  */
1315
1347
  private replaceLocalIdentity;
1316
1348
  /**
1317
- * Wipe everything tied to the current user identity. Anonymous-id
1318
- * is regenerated by analytics.reset() so the next page-view doesn't
1319
- * collide with the prior anonymous user_id. Chat session is reset
1320
- * so cross-account chat history can't bleed on a shared device.
1321
- * Pending analytics events are dropped — they're tied to the prior
1322
- * identity and shouldn't surface under the next.
1349
+ * Wipe everything tied to the current user identity. The anonymous id is
1350
+ * regenerated by analytics.reset() ONLY at a person-boundary (reason "user" /
1351
+ * "account_deleted") so two people on a shared device don't merge; on a
1352
+ * sign-in/upgrade ("replaced") or session death ("session_expired") it SURVIVES
1353
+ * (same person — pre-auth analytics link to them). Chat session is reset so
1354
+ * cross-account chat history can't bleed on a shared device. Pending analytics
1355
+ * events are dropped — they're tied to the prior identity and shouldn't surface
1356
+ * under the next.
1323
1357
  *
1324
1358
  * `reason` drives the `onAuthStateChanged` emission: a real sign-out reason
1325
1359
  * emits `signed_out`, while `"replaced"` (the internal pre-`persist()` clear
package/dist/index.d.ts CHANGED
@@ -45,6 +45,22 @@ interface SendoraConfig {
45
45
  * user. Pick one per environment before shipping and never change it.
46
46
  */
47
47
  storagePrefix?: string;
48
+ /**
49
+ * Where auth tokens (and all SDK state) are kept.
50
+ *
51
+ * - `"local"` (default) — `localStorage`. Durable across reloads, and
52
+ * **XSS-readable**: any script that runs on your origin can read the
53
+ * long-lived refresh token.
54
+ * - `"memory"` — kept only in a JS `Map`, never written to disk. An XSS
55
+ * payload or a malicious extension cannot exfiltrate a token that outlives
56
+ * the tab, at the cost of the session not surviving a page reload. Use it
57
+ * when your threat model treats the refresh token as too sensitive to
58
+ * persist (compliance, shared kiosks, high-value accounts).
59
+ *
60
+ * ⚠ s58.345: this flag used to be DOCUMENTED but not implemented — setting it
61
+ * silently no-op'd and tokens still hit localStorage. It is now real.
62
+ */
63
+ tokenStore?: "local" | "memory";
48
64
  /** Idle threshold (ms) for session expiry; default 30 minutes. */
49
65
  sessionIdleMs?: number;
50
66
  /** Event queue flush interval in ms (default 5000) */
@@ -182,7 +198,14 @@ declare class Storage {
182
198
  * shipping and never change it. Same frozen-key rule as ADR-023, delegated
183
199
  * to the integrator.
184
200
  */
185
- constructor(prefix?: string);
201
+ /**
202
+ * `memoryOnly` (s58.345) forces the in-memory `Map` and NEVER touches
203
+ * localStorage — the real implementation of `tokenStore: "memory"`. It is a
204
+ * hard opt-out, not the SSR/privacy fallback: `checkLocalStorage` is not even
205
+ * consulted, so a token cannot leak to disk on a browser where localStorage
206
+ * happens to be available.
207
+ */
208
+ constructor(prefix?: string, memoryOnly?: boolean);
186
209
  get(key: string): string | null;
187
210
  set(key: string, value: string): void;
188
211
  remove(key: string): void;
@@ -294,7 +317,16 @@ declare class Analytics {
294
317
  track(eventType: string, properties?: Record<string, unknown>): void;
295
318
  page(properties?: Record<string, unknown>): void;
296
319
  identify(userId: string, traits?: UserTraits, opts?: IdentifyOptions): void;
297
- reset(): void;
320
+ /**
321
+ * Clear the identity. `rotateAnonymousId` (default true) also regenerates the
322
+ * anonymous id — the person-boundary behaviour used on an explicit logout. Auth
323
+ * passes FALSE on a sign-in/upgrade or an involuntary session death: those keep
324
+ * the same person, so the anonymous id must SURVIVE so pre-auth analytics link to
325
+ * the now-real user (Firebase-FID / Segment-anonymousId norm). See auth.ts
326
+ * wipeLocalIdentity + the RN 1.38.0 write-up. Default true = logout/reset()
327
+ * unchanged.
328
+ */
329
+ reset(rotateAnonymousId?: boolean): void;
298
330
  /**
299
331
  * Drop any pending events without flushing. Used by Auth on
300
332
  * cross-account signin to ensure the prior identity's queued
@@ -1314,12 +1346,14 @@ declare class Auth {
1314
1346
  */
1315
1347
  private replaceLocalIdentity;
1316
1348
  /**
1317
- * Wipe everything tied to the current user identity. Anonymous-id
1318
- * is regenerated by analytics.reset() so the next page-view doesn't
1319
- * collide with the prior anonymous user_id. Chat session is reset
1320
- * so cross-account chat history can't bleed on a shared device.
1321
- * Pending analytics events are dropped — they're tied to the prior
1322
- * identity and shouldn't surface under the next.
1349
+ * Wipe everything tied to the current user identity. The anonymous id is
1350
+ * regenerated by analytics.reset() ONLY at a person-boundary (reason "user" /
1351
+ * "account_deleted") so two people on a shared device don't merge; on a
1352
+ * sign-in/upgrade ("replaced") or session death ("session_expired") it SURVIVES
1353
+ * (same person — pre-auth analytics link to them). Chat session is reset so
1354
+ * cross-account chat history can't bleed on a shared device. Pending analytics
1355
+ * events are dropped — they're tied to the prior identity and shouldn't surface
1356
+ * under the next.
1323
1357
  *
1324
1358
  * `reason` drives the `onAuthStateChanged` emission: a real sign-out reason
1325
1359
  * emits `signed_out`, while `"replaced"` (the internal pre-`persist()` clear
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- var pe=/^[a-zA-Z][a-zA-Z0-9._:-]{0,127}$/;var Ne=new Set(["__proto__","constructor","prototype"]),f=class extends Error{constructor(e){super(`[SendoraCloud] ${e}`),this.name="SendoraValidationError"}};function ge(n){if(typeof n!="string"||!pe.test(n))throw new f(`Invalid event name: must match ${pe}, got "${String(n)}".`)}function fe(n){if(n==null)return;if(typeof n!="object"||Array.isArray(n))throw new f("Properties must be a plain object, not an array or primitive.");let e=me(n);if(e>5)throw new f(`Properties nested too deeply (${e} levels, max 5).`);ye(n);let t;try{t=JSON.stringify(n).length}catch{throw new f("Properties contain a circular reference or unserializable value.")}if(t>32768)throw new f(`Properties too large (${t} bytes, max 32768).`)}function me(n,e=0){if(e>6||n==null||typeof n!="object")return e;let t=e;for(let r of Object.keys(n)){let s=me(n[r],e+1);s>t&&(t=s)}return t}function ye(n){if(!(n==null||typeof n!="object"))for(let e of Object.keys(n)){if(Ne.has(e))throw new f(`Forbidden property key "${e}" (prototype pollution guard).`);ye(n[e])}}var xe=/^pk_[A-Za-z0-9_-]{16,}$/;function ve(n){if(!n||typeof n!="string")throw new f("apiKey is required.");if(n.startsWith("sk_")||n.startsWith("sendora_secret_"))throw new f("Secret keys must NEVER be used in browser SDK. Use a publishable key (pk_...).");if(!xe.test(n))throw new f("Invalid publishable key format. Expected pk_... (17+ chars).")}function we(n){let e=n.replace(/\/$/,"");if(!(e.startsWith("http://localhost")||e.startsWith("http://127.0.0.1"))&&!e.startsWith("https://"))throw new f("apiUrl must be https:// (only http://localhost is allowed for dev).")}var ke={name:"@sendoracloud/sdk-web",version:"3.20.0",description:"Sendora Cloud Web SDK \u2014 analytics, feature flags, surveys, in-app messaging, chatbot, auth, deep links (Branch / Firebase parity). Zero dependencies, TypeScript, SSR-safe.",type:"module",main:"./dist/index.cjs",module:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"}},files:["dist","README.md","LICENSE"],keywords:["sendora","analytics","feature-flags","surveys","in-app-messaging","chatbot","tracking","customer-engagement"],homepage:"https://sendoracloud.com/sdks",repository:{type:"git",url:"git+https://github.com/sendoracloud/sdk-web.git"},bugs:{url:"https://github.com/sendoracloud/sdk-web/issues"},author:"Sendora Cloud <hello@sendoracloud.com>",license:"Apache-2.0",publishConfig:{access:"public"},sideEffects:!1,scripts:{build:"tsup src/index.ts --format cjs,esm --dts --clean --minify",typecheck:"tsc --noEmit",prepublishOnly:"npm run build"},devDependencies:{typescript:"^5.4.0",tsup:"^8.0.0"}};var b=ke.version;var Me="https://api.sendoracloud.com",Fe=1e4,He="@sendoracloud/sdk-web",Y=class{constructor(e){let t=(e.apiUrl??Me).replace(/\/$/,"");we(t),this.apiKey=e.apiKey,this.baseUrl=t,this.debug=!!e.debug}get(e,t){return this.request("GET",e,void 0,t)}post(e,t,r){return this.request("POST",e,t,r)}patch(e,t,r){return this.request("PATCH",e,t,r)}delete(e,t){return this.request("DELETE",e,void 0,t)}async request(e,t,r,s){let i=`${this.baseUrl}/api/v1${t}`,o=typeof AbortController<"u"?new AbortController:null,a=o?setTimeout(()=>o.abort(),Fe):null;try{let u=await fetch(i,{method:e,headers:{"Content-Type":"application/json","X-API-Key":this.apiKey,"X-Sendora-SDK-Name":He,"X-Sendora-SDK-Version":b,...s??{}},body:r?JSON.stringify(r):void 0,signal:o?o.signal:void 0});a&&clearTimeout(a);let l;try{l=await u.json()}catch{l={success:!1,error:{code:"PARSE_ERROR",message:`HTTP ${u.status}`}}}if(this.debug&&console.debug(`[SendoraCloud] ${e} ${t} \u2192 ${u.status}`),!u.ok){if(t.startsWith("/auth-service/")&&!this.debug)console.warn(`[SendoraCloud] ${e} ${t} \u2192 HTTP ${u.status}`);else{let v=l?.error?.code??"HTTP_ERROR",w=l?.error?.message??`HTTP ${u.status}`,k=l?.error?.details?.fieldErrors,C=k?` (${Object.entries(k).map(([A,te])=>`${A}: ${(te??[]).join(", ")}`).join("; ")})`:"";console.warn(`[SendoraCloud] ${e} ${t} \u2192 HTTP ${u.status} \u2014 ${v}: ${w}${C}`)}l&&l.error&&(l.error={...l.error,status:u.status})}return l}catch(u){a&&clearTimeout(a);let l=u instanceof Error&&u.name==="AbortError"?"timeout":"error";return console.warn(`[SendoraCloud] ${e} ${t} network ${l}`),{success:!1,error:{code:"NETWORK_ERROR",message:l}}}}};var Ke="sendora_",X=class{constructor(e){this.memoryStore=new Map;this.useLocalStorage=this.checkLocalStorage(),this.prefix=e??Ke}get(e){let t=this.prefix+e;if(this.useLocalStorage)try{return localStorage.getItem(t)}catch{return this.memoryStore.get(t)??null}return this.memoryStore.get(t)??null}set(e,t){let r=this.prefix+e;if(this.useLocalStorage)try{localStorage.setItem(r,t);return}catch{}this.memoryStore.set(r,t)}remove(e){let t=this.prefix+e;if(this.useLocalStorage)try{localStorage.removeItem(t)}catch{}this.memoryStore.delete(t)}clearPrefix(e){let t=this.prefix+e;if(this.useLocalStorage)try{for(let r=localStorage.length-1;r>=0;r--){let s=localStorage.key(r);s&&s.startsWith(t)&&localStorage.removeItem(s)}}catch{}for(let r of Array.from(this.memoryStore.keys()))r.startsWith(t)&&this.memoryStore.delete(r)}checkLocalStorage(){try{if(typeof localStorage>"u")return!1;let e="__sendora_test__";return localStorage.setItem(e,"1"),localStorage.removeItem(e),!0}catch{return!1}}};function L(n=""){let e=new Uint8Array(16),t=typeof globalThis<"u"&&"crypto"in globalThis?globalThis.crypto:void 0;if(!t||typeof t.getRandomValues!="function")throw new Error("[SendoraCloud] crypto.getRandomValues unavailable \u2014 refusing to mint IDs without a CSPRNG");t.getRandomValues(e);let r="";for(let s of e)r+=s.toString(16).padStart(2,"0");return n+r}var Ae=500,ie=10,oe=6e4,x=class{constructor(e,t,r,s){this.queue=[];this.timer=null;this.userId=null;this.identityToken=null;this.consecutiveFailures=0;this.nextFlushAfter=0;this.breakerOpenAt=0;this.breakerWarned=!1;this.http=t,this.storage=r,this.consent=s,this.projectId=e.projectId,this.flushInterval=e.flushInterval??5e3,this.maxQueueSize=e.maxQueueSize??20,this.persistUserId=!!e.persistUserId,this.stripQueryParams=e.stripQueryParams!==!1,this.appVersion=e.appVersion,this.storage.get("schema_version")===null&&this.storage.set("schema_version","1");let i=this.storage.get("anonymous_id");if(i?this.anonymousId=i:(this.anonymousId=L("anon_"),this.storage.set("anonymous_id",this.anonymousId)),this.persistUserId){let o=this.storage.get("user_id");o&&(this.userId=o)}this.timer=setInterval(()=>this.flush(),this.flushInterval),typeof window<"u"&&window.addEventListener("beforeunload",()=>this.flush()),this.consent.subscribe(o=>{o&&this.flush()})}track(e,t){ge(e),t&&fe(t),this.queue.length>=Ae&&this.queue.shift(),this.queue.push({eventType:e,properties:t??{},userId:this.userId??void 0,anonymousId:this.anonymousId,timestamp:new Date().toISOString(),identityToken:this.identityToken??void 0}),this.queue.length>=this.maxQueueSize&&this.flush()}page(e){if(typeof window>"u")return;let t=this.stripQueryParams?window.location.origin+window.location.pathname:window.location.href;this.track("page.viewed",{url:t,path:window.location.pathname,title:document.title,referrer:document.referrer||void 0,...e})}identify(e,t,r){if(typeof e!="string"||e.length===0||e.length>256)throw new Error("[SendoraCloud] userId must be a 1-256 char string.");this.userId=e,this.identityToken=r?.identityToken??null,this.persistUserId&&this.storage.set("user_id",e),this.track("user.identified",{...t})}reset(){this.userId=null,this.identityToken=null,this.storage.remove("user_id"),this.anonymousId=L("anon_"),this.storage.set("anonymous_id",this.anonymousId),this.storage.clearPrefix("iam_shown_"),this.storage.clearPrefix("survey_shown_")}dropQueue(){this.queue=[]}async flush(){if(this.queue.length===0||!this.consent.isGranted()||Date.now()<this.nextFlushAfter)return;this.consecutiveFailures>ie&&Date.now()-this.breakerOpenAt>=oe&&(this.consecutiveFailures=0,this.breakerOpenAt=0,this.breakerWarned=!1);let e=this.queue.splice(0,100),t=this.getSessionId(),r=e.map(a=>({projectId:this.projectId,module:"custom",eventType:a.eventType,userId:a.userId,anonymousId:a.anonymousId,identityToken:a.identityToken,timestamp:a.timestamp??new Date().toISOString(),properties:a.properties??{},context:this.getContext(),...t?{sessionId:t}:{},consent:["analytics"]}));if((await this.http.post("/events/batch",{events:r})).success){this.consecutiveFailures=0,this.breakerOpenAt=0,this.breakerWarned=!1;return}if(this.consecutiveFailures++,this.consecutiveFailures>ie){this.breakerWarned||(this.breakerOpenAt=Date.now(),this.breakerWarned=!0,console.warn(`[SendoraCloud] Analytics circuit breaker open after ${ie} consecutive failed flushes \u2014 events will be dropped until a flush succeeds or ${oe}ms elapse.`));return}let i=Math.min(oe,1e3*2**this.consecutiveFailures);this.nextFlushAfter=Date.now()+i;let o=Math.max(0,Ae-this.queue.length);o>0&&this.queue.unshift(...e.slice(0,o))}destroy(){this.timer&&clearInterval(this.timer),this.timer=null,this.flush()}getSessionId(){try{return typeof sessionStorage>"u"?void 0:sessionStorage.getItem("sendora_session_id")||void 0}catch{return}}getContext(){return typeof window>"u"?{sdk:{name:"@sendoracloud/sdk-web",version:b}}:{page:{url:this.stripQueryParams?window.location.origin+window.location.pathname:window.location.href,path:window.location.pathname,title:document.title},referrer:document.referrer||void 0,locale:typeof navigator<"u"?navigator.language:void 0,device:this.buildDevice(),sdk:{name:"@sendoracloud/sdk-web",version:b}}}buildDevice(){if(typeof navigator>"u")return;let e=navigator.userAgent||"",r=navigator.userAgentData?.mobile??/Mobi|Android|iPhone|iPod/i.test(e);return{type:/iPad|Tablet|(?:Android(?!.*Mobile))/i.test(e)?"tablet":r?"mobile":"desktop",os:"Web",osVersion:"",model:"",appVersion:this.resolveAppVersion(),browser:Ve(e)}}resolveAppVersion(){if(this.appVersion)return this.appVersion;if(typeof document<"u"){let r=document.querySelector('meta[name="sendora:app-version"]')?.getAttribute("content");if(r)return r}let e=globalThis.__SENDORA_APP_VERSION__;return typeof e=="string"?e:""}};function Ve(n){let e=[["Edge",/Edg\/(\d+)/],["Opera",/OPR\/(\d+)/],["Firefox",/Firefox\/(\d+)/],["Samsung Internet",/SamsungBrowser\/(\d+)/],["Chrome",/Chrome\/(\d+)/],["Safari",/Version\/(\d+)[^ ]* Safari/]];for(let[t,r]of e){let s=r.exec(n);if(s)return`${t} ${s[1]}`}return"Unknown"}var O=class{constructor(e,t,r){this.cache=new Map;this.refreshInterval=null;this.http=t,this.storage=r;let s=this.storage.get("flags");if(s)try{let i=JSON.parse(s);if(Array.isArray(i))for(let o of i)ae(o)&&this.cache.set(o.key,o)}catch{}}setContext(e){this.userId=e.userId,this.entityId=e.entityId,this.environment=e.environment}async getFlag(e){if(typeof e!="string"||e.length===0||e.length>128)return null;let t=this.cache.get(e);if(t)return t.value;let r=await this.http.post("/feature-flags/evaluate",{key:e,userId:this.userId,entityId:this.entityId,environment:this.environment});return r.success&&r.data&&ae(r.data)?(this.cache.set(e,r.data),this.persistCache(),r.data.value):null}async isEnabled(e,t=!1){let r=await this.getFlag(e);return typeof r=="boolean"?r:t}async refreshAll(){let e=await this.http.post("/feature-flags/evaluate-all",{userId:this.userId,entityId:this.entityId,environment:this.environment});if(e.success&&Array.isArray(e.data)){this.cache.clear();for(let t of e.data)ae(t)&&this.cache.set(t.key,t);this.persistCache()}}startAutoRefresh(e=6e4){this.stopAutoRefresh(),this.refreshAll(),this.refreshInterval=setInterval(()=>this.refreshAll(),e)}stopAutoRefresh(){this.refreshInterval&&clearInterval(this.refreshInterval),this.refreshInterval=null}getAllFlags(){let e={};for(let[t,r]of this.cache)e[t]=r.value;return e}reset(){this.cache.clear(),this.storage.remove("flags"),this.userId=void 0,this.entityId=void 0,this.environment=void 0}destroy(){this.stopAutoRefresh()}persistCache(){this.storage.set("flags",JSON.stringify(Array.from(this.cache.values())))}};function ae(n){if(n==null||typeof n!="object")return!1;let e=n;return Object.prototype.hasOwnProperty.call(e,"__proto__")||Object.prototype.hasOwnProperty.call(e,"constructor")?!1:typeof e.key=="string"&&"value"in e}var $e=32*1024,M=class{constructor(e,t,r){this.activeSurvey=null;this.http=t,this.storage=r}onDisplay(e){this.onSurveyDisplay=e}async showSurvey(e){if(typeof e!="string"||!/^[A-Za-z0-9_-]{6,64}$/.test(e))return null;let t=`survey_shown_${e}`;if(this.storage.get(t))return null;let r=await this.http.get(`/surveys/${encodeURIComponent(e)}/config`);return!r.success||!r.data||!We(r.data)?null:(this.activeSurvey=r.data,this.storage.set(t,"1"),this.onSurveyDisplay&&this.onSurveyDisplay(r.data),r.data)}async submitResponse(e,t,r=!0){let s=0;try{s=JSON.stringify(t).length}catch{return!1}if(s>$e)return!1;let i=await this.http.post("/surveys/responses",{surveyId:e,answers:t,completed:r});return i.success&&(this.activeSurvey=null),i.success}dismiss(){this.activeSurvey=null}getActiveSurvey(){return this.activeSurvey}};function We(n){if(n==null||typeof n!="object")return!1;let e=n;return typeof e.id!="string"||typeof e.name!="string"||!Array.isArray(e.questions)?!1:e.questions.every(Be)}function Be(n){if(n==null||typeof n!="object")return!1;let e=n;return typeof e.id=="string"&&typeof e.text=="string"}function E(n){if(!(!n||typeof n!="string"))try{let e=typeof window<"u"?window.location.href:"https://local/",t=new URL(n,e);return t.protocol==="http:"||t.protocol==="https:"?t.href:void 0}catch{return}}var qe=new Set(["b","i","u","em","strong","a","p","br","span","ul","ol","li","h1","h2","h3","h4"]),ze={a:new Set(["href","target","rel"])};function ce(n){if(typeof DOMParser>"u")return"";let t=new DOMParser().parseFromString(`<div>${n}</div>`,"text/html").body.firstElementChild;return t?(Se(t),t.innerHTML):""}function Se(n){let e=Array.from(n.children);for(let t of e){let r=t.tagName.toLowerCase();if(!qe.has(r)){let i=document.createTextNode(t.textContent??"");t.replaceWith(i);continue}let s=ze[r]??new Set;for(let i of Array.from(t.attributes)){if(!s.has(i.name.toLowerCase())){t.removeAttribute(i.name);continue}if(i.name.toLowerCase()==="href"){let o=E(i.value);o?t.setAttribute("href",o):t.removeAttribute(i.name)}}r==="a"&&(t.setAttribute("rel","noopener noreferrer"),t.setAttribute("target","_blank")),Se(t)}}var F=class{constructor(e,t,r){this.messages=[];this.pollInterval=null;this.http=t,this.storage=r}onDisplay(e){this.onMessageDisplay=e}async checkMessages(){let e=await this.http.get("/in-app-messages/active");if(!e.success||!Array.isArray(e.data))return null;this.messages=e.data.map(je);for(let t of this.messages){let r=`iam_shown_${t.id}`;if(!this.storage.get(r))return this.storage.set(r,"1"),this.onMessageDisplay&&this.onMessageDisplay(t),t}return null}async recordAction(e,t){await this.http.post("/in-app-messages/impressions",{messageId:e,action:t})}startPolling(e=3e5){this.stopPolling(),this.checkMessages(),this.pollInterval=setInterval(()=>this.checkMessages(),e)}stopPolling(){this.pollInterval&&clearInterval(this.pollInterval),this.pollInterval=null}getMessages(){return this.messages}destroy(){this.stopPolling()}};function je(n){return{...n,content:{...n.content,ctaUrl:E(n.content.ctaUrl),imageUrl:E(n.content.imageUrl)}}}var Ge=4e3,H=class{constructor(e,t,r){this.chatbotId=null;this.messages=[];this.http=t,this.storage=r;let s=this.storage.get("chat_session_id");this.sessionId=s??L("chat_"),s||this.storage.set("chat_session_id",this.sessionId)}init(e){if(typeof e!="string"||!/^[A-Za-z0-9_-]{6,64}$/.test(e))throw new Error("[SendoraCloud] Invalid chatbotId.");this.chatbotId=e}onNewMessage(e){this.onMessage=e}async sendMessage(e,t){if(!this.chatbotId||typeof e!="string"||e.length===0||e.length>Ge)return null;let r={role:"user",content:e,timestamp:new Date().toISOString()};this.messages.push(r);let s=await this.http.post("/chatbot/message",{chatbotId:this.chatbotId,sessionId:this.sessionId,message:e,userId:t});if(s.success&&s.data&&typeof s.data.reply=="string"){let i={role:"assistant",content:s.data.reply,timestamp:new Date().toISOString()};return this.messages.push(i),this.onMessage&&this.onMessage(i),i}return null}getMessages(){return[...this.messages]}newSession(){this.messages=[],this.sessionId=L("chat_"),this.storage.set("chat_session_id",this.sessionId)}getSessionId(){return this.sessionId}};var K=class{constructor(e,t){this.listeners=new Set;this.granted=e,this.http=t}isGranted(){return this.granted}grant(){this.granted||(this.granted=!0,this.emit())}revoke(){this.granted&&(this.granted=!1,this.emit())}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async record(e){if(!this.http)throw new Error("consent.record requires SDK init (HttpClient unavailable)");let t=await this.http.post("/consent/record",e);if(!t.success||!t.data)throw new Error(t.error?.message??"consent.record failed");return t.data}async requestDeletion(e){if(!this.http)throw new Error("consent.requestDeletion requires SDK init (HttpClient unavailable)");let t=await this.http.post("/consent/deletion-request",e);if(!t.success||!t.data)throw new Error(t.error?.message??"consent.requestDeletion failed");return t.data}emit(){for(let e of this.listeners)try{e(this.granted)}catch{}}};var T="auth_access_token",R="auth_access_expires",m="auth_refresh_token",_="auth_user",Ie=3e4,Ye=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function y(n){if(!n||typeof n!="object")return!1;let e=n,t=e.user,r=e.tokens;return!(!t||typeof t.id!="string"||t.id.length===0||!r||typeof r.accessToken!="string"||r.accessToken.length===0||typeof r.refreshToken!="string"||r.refreshToken.length===0||typeof r.expiresIn!="number"||r.expiresIn<=0||t.isAnonymous!==void 0&&typeof t.isAnonymous!="boolean"||t.email!==void 0&&t.email!==null&&typeof t.email!="string"||t.emailVerified!==void 0&&typeof t.emailVerified!="boolean"||t.name!==void 0&&t.name!==null&&typeof t.name!="string"||t.signupMethod!==void 0&&t.signupMethod!==null&&typeof t.signupMethod!="string"||t.lastLoginMethod!==void 0&&t.lastLoginMethod!==null&&typeof t.lastLoginMethod!="string"||e.retiredAnonUserId!==void 0&&typeof e.retiredAnonUserId!="string")}var P=class extends Error{constructor(e="An account with this email already exists"){super(e),this.name="EmailAlreadyTakenError"}},$=class extends Error{constructor(e="Already signed in with an identity; use link*() to add a credential, or sign out first"){super(e),this.name="AlreadyIdentifiedError"}},U=class extends Error{constructor(t="This credential is already linked to a different account",r){super(t);this.code="CREDENTIAL_IN_USE";this.kind="credential_in_use";this.retryable=!1;this.name="CredentialInUseError",this.provider=r?.provider,this.collision=r?.collision,this.status=r?.status}};function be(n){let e=n?.error?.details;if(!e||typeof e!="object")return{};let t=e;return{provider:typeof t.provider=="string"?t.provider:void 0,collision:t.collision==="identity"||t.collision==="email"?t.collision:void 0}}var Xe=new Set(["network","server","rate_limited","account_locked"]);function Qe(n,e){switch(n){case"NETWORK_ERROR":case"NETWORK_TIMEOUT":return"network";case"PARSE_ERROR":return"server";case"RATE_LIMITED":case"RATE_LIMIT":case"RATE_LIMIT_EXCEEDED":case"QUOTA_EXCEEDED":return"rate_limited";case"ACCOUNT_LOCKED":return"account_locked";case"CREDENTIAL_IN_USE":return"credential_in_use";case"LAST_CREDENTIAL":return"last_credential";case"RECENT_AUTH_REQUIRED":return"recent_auth_required";case"NOT_ANONYMOUS":case"FORBIDDEN_NON_ANONYMOUS":return"already_identified";case"PASSKEY_USER_CANCELLED":case"GAME_CENTER_CANCELLED":case"PLAY_GAMES_CANCELLED":case"SSO_CANCELLED":return"cancelled";case"GAME_CENTER_UNAVAILABLE":case"PLAY_GAMES_UNAVAILABLE":case"ENTITLEMENT_ERROR":case"tier_required":return"config";case"UNAUTHORIZED":case"INVALID_CREDENTIALS":case"INVALID_REFRESH_TOKEN":case"EMAIL_OTP_INVALID":case"MAGIC_LINK_INVALID":case"PASSKEY_RP_MISMATCH":case"NOT_SIGNED_IN":return"invalid_credential";default:break}if(typeof e=="number"){if(e===429)return"rate_limited";if(e>=500)return"server";if(e>=400)return"invalid_credential"}return"unknown"}var c=class extends Error{constructor(e,t,r){super(t),this.name="AuthError",this.code=e,this.kind=r?.kind??Qe(e,r?.status),this.retryable=Xe.has(this.kind),this.retryAfterSeconds=r?.retryAfterSeconds,this.status=r?.status}};function Je(n){if(n instanceof c||n instanceof P||n instanceof $||n instanceof U)return n;let e=n?.name;return e==="AbortError"||e==="TimeoutError"||e==="NetworkTimeoutError"?new c("NETWORK_TIMEOUT",n instanceof Error?n.message:"timeout",{kind:"network"}):new c("UNKNOWN_ERROR",n instanceof Error?n.message:String(n),{kind:"unknown"})}function h(n){let e=n.error?.status,t=n.error?.details?.retryAfterSeconds;return{status:typeof e=="number"?e:void 0,retryAfterSeconds:typeof t=="number"&&Number.isFinite(t)&&t>0?t:void 0}}var W=class{constructor(e,t,r,s,i,o){this.user=null;this.accessToken=null;this.accessExpiresAt=0;this.clockSkewConfirmed=!1;this.inflight=Promise.resolve();this.refreshInflight=null;this.refreshFailureCount=0;this.refreshCooldownUntil=0;this.visibilityResetUnsub=null;this.proactiveRefreshTimer=null;this.proactiveRefreshCleanup=null;this.takeoverListeners=new Set;this.lastTakeover=null;this.deletionCancelledListeners=new Set;this.lastDeletionCancelled=null;this.lastAnonRetirement=null;this.authStateListeners=new Set;this.pendingAnonTakeover=null;this.hydrated=!1;this.http=t,this.storage=r,this.analytics=s,this.flags=i,this.chatbot=o;let a=this.storage.get(_),u=this.storage.get(T),l=this.storage.get(m),g=this.storage.get(R);if(a&&(u||l))try{let v=JSON.parse(a);if(typeof v.id!="string"||v.id.length===0)throw new Error("invalid cache");this.user=v,u?(this.accessToken=u,this.accessExpiresAt=g?Number(g):0):(this.accessToken=null,this.accessExpiresAt=0),this.analytics.identify(this.user.id)}catch{this.storage.remove(_),this.storage.remove(T),this.storage.remove(R)}this.hydrated=!0}getCurrentUser(){return this.user}onDeviceTakeover(e){return this.takeoverListeners.add(e),()=>{this.takeoverListeners.delete(e)}}getLastDeviceTakeover(){return this.lastTakeover}onAuthStateChanged(e){if(this.authStateListeners.add(e),this.hydrated&&this.user){let t=this.user;try{e({event:"signed_in",user:t})}catch{}}return()=>{this.authStateListeners.delete(e)}}emitAuthState(e){for(let t of this.authStateListeners)try{t(e)}catch{}}fireDeviceTakeover(e,t){if(!e||!Ye.test(e))return;let r={retiredAnonUserId:e,identifiedUserId:t,at:new Date};this.lastTakeover=r;for(let s of this.takeoverListeners)try{s(r)}catch{}this.emitAuthState({event:"device_takeover",user:this.user,retiredAnonUserId:e})}onDeletionCancelled(e){return this.deletionCancelledListeners.add(e),()=>{this.deletionCancelledListeners.delete(e)}}getLastDeletionCancelled(){return this.lastDeletionCancelled}getLastAnonRetirement(){return this.lastAnonRetirement}fireDeletionCancelled(e){let t={userId:e,at:new Date};this.lastDeletionCancelled=t;for(let r of this.deletionCancelledListeners)try{r(t)}catch{}this.emitAuthState({event:"deletion_cancelled",user:this.user})}takeoverHint(){if(this.user?.isAnonymous)return this.storage.get(m)??void 0}canServeToken(e,t,r){return!e||!t||r>=t-Ie?!1:this.clockSkewConfirmed?!0:Te(e,r)}canServeCachedToken(e){return this.canServeToken(this.accessToken,this.accessExpiresAt,e)}trackedDeadlineAlive(e){return!!this.accessToken&&!!this.accessExpiresAt&&e<this.accessExpiresAt-Ie}deadlinesDisagree(e){return this.trackedDeadlineAlive(e)&&!this.canServeCachedToken(e)}learnClockSkewFrom(e,t){Te(e,t)||(this.clockSkewConfirmed=!0)}async refreshAndReconcile(e){let t=this.deadlinesDisagree(e),r=await this.refreshAccessToken();return t&&r&&this.learnClockSkewFrom(r,Date.now()),r}async getAccessToken(e){return!e?.forceRefresh&&this.canServeCachedToken(Date.now())?this.accessToken:this.storage.get(m)?this.refreshInflight?this.refreshInflight:Date.now()<this.refreshCooldownUntil?null:this.refreshAndReconcile(Date.now()):null}getAccessTokenSync(){return this.accessToken}signInAnonymously(e){return this.serialize(async()=>{let t=this.user;if(!e?.forceNew&&t?.isAnonymous&&this.storage.get(m))return t;let r=await this.http.post("/auth-service/anonymous",{name:e?.name,metadata:e?.metadata});if(!r.success||!y(r.data))throw new c(r.error?.code??"AUTH_ERROR",r.error?.message??"Anonymous signup failed",h(r));return this.persist(r.data),r.data.user})}signUp(e,t,r){return this.serialize(async()=>{let s=this.storage.get(m);if(s){let o=await this.http.post("/auth-service/upgrade",{refreshToken:s,email:e,password:t,name:r?.name});if(o.success&&y(o.data))return this.persist(o.data),o.data.user;let a=o.error?.code??"",u=h(o),l=u.status;if(a==="NOT_ANONYMOUS"||a==="FORBIDDEN_NON_ANONYMOUS")throw new $(o.error?.message);if(a==="CONFLICT"||a==="EMAIL_ALREADY_TAKEN"||l===409)throw new P(o.error?.message);if(a==="INVALID_REFRESH"||a==="UNAUTHORIZED"||a==="REFRESH_EXPIRED")await this.analytics.flush(),this.wipeLocalIdentity("session_expired");else throw new c(a||"AUTH_ERROR",o.error?.message??"Upgrade failed",u)}let i=await this.http.post("/auth-service/signup",{email:e,password:t,name:r?.name,metadata:r?.metadata});if(!i.success||!y(i.data)){let o=i.error?.code??"";throw o==="CONFLICT"?new P(i.error?.message):new c(o||"AUTH_ERROR",i.error?.message??"Signup failed",h(i))}return this.persist(i.data),i.data.user})}signIn(e,t){return this.serialize(async()=>{let r=this.takeoverHint(),s=await this.http.post("/auth-service/login",{email:e,password:t,...r?{prevAnonRefreshToken:r}:{}});if(!s.success||!s.data)throw new c(s.error?.code??"AUTH_ERROR",s.error?.message??"Login failed",h(s));let i=s.data;if(i.mfaRequired===!0&&typeof i.mfaChallengeToken=="string"){r&&(this.pendingAnonTakeover={challengeToken:i.mfaChallengeToken,prevAnonRefreshToken:r});let o=i.user;return{mfaRequired:!0,mfaChallengeToken:i.mfaChallengeToken,userId:o?.id??""}}if(!y(s.data))throw new c(s.error?.code??"AUTH_ERROR",s.error?.message??"Login failed",h(s));return await this.replaceLocalIdentity(),this.persist(s.data),s.data.user})}loginSocial(e){return this.serialize(async()=>{let t=this.takeoverHint(),{link:r,onCredentialInUse:s,...i}=e,o=await this.http.post("/auth-service/login/social",{...i,...t?{prevAnonRefreshToken:t}:{},...r?{linkAnonymous:!0}:{},...s?{onCredentialInUse:s}:{}});if(!o.success||!y(o.data))throw o.error?.code==="CREDENTIAL_IN_USE"?new U(o.error.message,{...be(o),status:h(o).status}):new c(o.error?.code??"SOCIAL_LOGIN_FAILED",o.error?.message??"Social login failed",h(o));return await this.replaceLocalIdentity(),this.persist(o.data),o.data.user})}signInWithGoogle(e,t,r){return this.loginSocial({provider:"google",code:e,redirectUri:t,link:r})}signInWithGitHub(e,t){return this.loginSocial({provider:"github",code:e,redirectUri:t})}signInWithApple(e){return this.loginSocial({provider:"apple",...e})}signInWithMicrosoft(e,t){return this.loginSocial({provider:"microsoft",code:e,redirectUri:t})}signInWithLinkedIn(e,t){return this.loginSocial({provider:"linkedin",code:e,redirectUri:t})}signInWithFacebook(e,t){return this.loginSocial({provider:"facebook",code:e,redirectUri:t})}linkEmailPassword(e,t){return this.linkCredential("/auth-service/me/link/email",{email:e,password:t})}linkSocial(e){return this.linkCredential("/auth-service/me/link/social",e)}linkGoogle(e){return this.linkSocial({provider:"google",...e})}linkApple(e){return this.linkSocial({provider:"apple",...e})}async linkCredential(e,t){let r=await this.getAccessToken();if(!r)throw new c("NOT_SIGNED_IN","Sign in before linking a credential");let s=await this.http.post(e,t,{Authorization:`Bearer ${r}`});if(!s.success||!s.data?.user){let i=s.error?.code??"LINK_FAILED";throw i==="CREDENTIAL_IN_USE"?new U(s.error?.message,{...be(s),status:h(s).status}):new c(i,s.error?.message??"Failed to link credential",h(s))}return s.data.upgraded&&y(s.data)?(this.persist(s.data),s.data.user):(this.updateLocalUser(s.data.user),s.data.user)}updateLocalUser(e){this.user=e,this.storage.set(_,JSON.stringify(e))}async listLinkedIdentities(){let e=await this.getAccessToken();if(!e)throw new c("NOT_SIGNED_IN","Sign in before listing linked identities");let t=await this.http.get("/auth-service/me/identities",{Authorization:`Bearer ${e}`});if(!t.success||!t.data)throw new c(t.error?.code??"IDENTITIES_FAILED",t.error?.message??"Failed to list linked identities",h(t));return{identities:t.data.identities??[],hasPassword:!!t.data.hasPassword}}async unlink(e){let t=await this.getAccessToken();if(!t)throw new c("NOT_SIGNED_IN","Sign in before unlinking an identity");let r=await this.http.delete(`/auth-service/me/identities/${encodeURIComponent(e)}`,{Authorization:`Bearer ${t}`});if(!r.success||!r.data)throw new c(r.error?.code??"UNLINK_FAILED",r.error?.message??"Failed to unlink identity",h(r));return{provider:r.data.provider??e,removed:Number(r.data.removed??0),remaining:Number(r.data.remaining??0)}}signInWithDiscord(e,t){return this.loginSocial({provider:"discord",code:e,redirectUri:t})}challengeMfa(e,t){return this.serialize(async()=>{let s=(this.pendingAnonTakeover?.challengeToken===e?this.pendingAnonTakeover.prevAnonRefreshToken:void 0)??this.takeoverHint(),i=await this.http.post("/auth-service/mfa/challenge",{challengeToken:e,code:t,...s?{prevAnonRefreshToken:s}:{}});if(!i.success||!y(i.data))throw new c(i.error?.code??"MFA_CHALLENGE_FAILED",i.error?.message??"Invalid MFA code",h(i));return await this.replaceLocalIdentity(),this.persist(i.data),i.data.user})}async sendMagicLink(e){let t=await this.http.post("/auth-service/magic-link/request",{email:e});if(!t.success)throw new c(t.error?.code??"MAGIC_LINK_REQUEST_FAILED",t.error?.message??"Failed to send link")}async sendEmailOtp(e){let t=await this.http.post("/auth-service/email-otp/request",{email:e});if(!t.success)throw new c(t.error?.code??"EMAIL_OTP_REQUEST_FAILED",t.error?.message??"Failed to send code")}verifyEmailOtp(e,t){return this.serialize(async()=>{let r=this.takeoverHint(),s=await this.http.post("/auth-service/email-otp/verify",{email:e,code:t,...r?{prevAnonRefreshToken:r}:{}});if(!s.success||!y(s.data))throw new c(s.error?.code??"EMAIL_OTP_INVALID",s.error?.message??"Wrong or expired code",h(s));return await this.replaceLocalIdentity(),this.persist(s.data),s.data.user})}async requestPasswordReset(e){let t=await this.http.post("/auth-service/password/forgot",{email:e});if(!t.success)throw new c(t.error?.code??"PASSWORD_RESET_REQUEST_FAILED",t.error?.message??"Failed to send reset email")}async resetPassword(e,t){let r=await this.http.post("/auth-service/password/reset",{token:e,newPassword:t});if(!r.success)throw new c(r.error?.code??"PASSWORD_RESET_FAILED",r.error?.message??"Reset failed")}async verifyEmail(e){let t=await this.http.post("/auth-service/email/verify",{token:e});if(!t.success)throw new c(t.error?.code??"EMAIL_VERIFICATION_FAILED",t.error?.message??"Verification failed")}async sendVerificationEmail(){let e=await this.getAccessToken();if(!e)throw new c("UNAUTHORIZED","Sign in before requesting a verification email");let t=await this.http.post("/auth-service/email/verify/resend",{},{Authorization:`Bearer ${e}`});if(!t.success)throw new c(t.error?.code??"VERIFICATION_RESEND_FAILED",t.error?.message??"Failed to send verification email")}verifyMagicLink(e){return this.serialize(async()=>{let t=this.takeoverHint(),r=await this.http.post("/auth-service/magic-link/verify",{token:e,...t?{prevAnonRefreshToken:t}:{}});if(!r.success||!y(r.data))throw new c(r.error?.code??"MAGIC_LINK_INVALID",r.error?.message??"Invalid or expired magic link",h(r));return await this.replaceLocalIdentity(),this.persist(r.data),r.data.user})}async enrollMfa(){let e=await this.http.post("/auth-service/mfa/enroll/start",{},await this.bearerHeaders());if(!e.success||!e.data)throw new c(e.error?.code??"MFA_ENROLL_FAILED",e.error?.message??"MFA enrollment failed");return e.data}async confirmMfa(e){let t=await this.http.post("/auth-service/mfa/enroll/confirm",{code:e},await this.bearerHeaders());return!!(t.success&&t.data?.confirmed)}async disableMfa(){let e=await this.http.post("/auth-service/mfa/disable",{},await this.bearerHeaders());if(!e.success)throw new c(e.error?.code??"MFA_DISABLE_FAILED",e.error?.message??"Failed to disable MFA",h(e))}async registerPasskey(e){if(typeof navigator>"u"||!navigator.credentials)throw new c("PASSKEY_UNSUPPORTED","WebAuthn not supported in this environment");let t=await this.http.post("/auth-service/passkeys/register/start",{},await this.bearerHeaders());if(!t.success||!t.data)throw new c(t.error?.code??"PASSKEY_START_FAILED",t.error?.message??"Passkey start failed");let r=et(t.data),s;try{let a=await navigator.credentials.create({publicKey:r});if(!a)throw new Error("create returned null");s=a}catch(a){throw new c("PASSKEY_USER_CANCELLED",a instanceof Error?a.message:"User cancelled passkey registration")}let i=rt(s),o=await this.http.post("/auth-service/passkeys/register/finish",{response:i,name:e},await this.bearerHeaders());if(!o.success||!o.data)throw new c(o.error?.code??"PASSKEY_FINISH_FAILED",o.error?.message??"Passkey verification failed");return o.data}signInWithPasskey(e){return this.serialize(async()=>{if(typeof navigator>"u"||!navigator.credentials)throw new c("PASSKEY_UNSUPPORTED","WebAuthn not supported in this environment");let t=this.takeoverHint(),r=await this.http.post("/auth-service/passkeys/authenticate/start",{userId:e??null});if(!r.success||!r.data)throw new c(r.error?.code??"PASSKEY_START_FAILED",r.error?.message??"Passkey start failed",h(r));let s=tt(r.data),i;try{let u=await navigator.credentials.get({publicKey:s});if(!u)throw new Error("get returned null");i=u}catch(u){throw new c("PASSKEY_USER_CANCELLED",u instanceof Error?u.message:"User cancelled passkey signin")}let o=st(i),a=await this.http.post("/auth-service/passkeys/authenticate/finish",{response:o,userId:e??null,...t?{prevAnonRefreshToken:t}:{}});if(!a.success||!y(a.data))throw new c(a.error?.code??"PASSKEY_AUTH_FAILED",a.error?.message??"Passkey signin failed",h(a));return await this.replaceLocalIdentity(),this.persist(a.data),a.data.user})}async listPasskeys(){let e=await this.http.get("/auth-service/passkeys",await this.bearerHeaders());return!e.success||!Array.isArray(e.data)?[]:e.data}async deletePasskey(e){let t=await this.http.delete(`/auth-service/passkeys/${encodeURIComponent(e)}`,await this.bearerHeaders());if(!t.success)throw new c(t.error?.code??"PASSKEY_DELETE_FAILED",t.error?.message??"Failed to delete passkey",h(t))}async listMySessions(){let e=await this.http.get("/auth-service/sessions/me",await this.bearerHeaders());return!e.success||!Array.isArray(e.data)?[]:e.data}async revokeSession(e){let t=await this.http.delete(`/auth-service/sessions/me/${encodeURIComponent(e)}`,await this.bearerHeaders());if(!t.success)throw new c(t.error?.code??"SESSION_REVOKE_FAILED",t.error?.message??"Failed to revoke session",h(t))}async revokeAllSessions(){let e=await this.http.delete("/auth-service/sessions/me",await this.bearerHeaders());if(!e.success)throw new c(e.error?.code??"SESSION_REVOKE_ALL_FAILED",e.error?.message??"Failed to sign out other devices",h(e))}async startSso(e){let t=this.takeoverHint(),r=await this.http.post("/auth-service/sso/oidc/start",{returnTo:e,...t?{prevAnonRefreshToken:t}:{}});if(!r.success||!r.data)throw new c(r.error?.code??"SSO_START_FAILED",r.error?.message??"SSO start failed");return r.data}async signInWithSso(e){let t=e??(typeof window<"u"?window.location.origin:"");if(!t)throw new c("SSO_NO_RETURN_TO","returnTo required outside browser context");let r=await this.startSso(t);typeof window<"u"&&(window.location.href=r.authorizationUrl)}async startSaml(e){let t=this.takeoverHint(),r=await this.http.post("/auth-service/sso/saml/start",{returnTo:e,...t?{prevAnonRefreshToken:t}:{}});if(!r.success||!r.data)throw new c(r.error?.code??"SAML_START_FAILED",r.error?.message??"SAML start failed");return r.data}async signInWithSaml(e){let t=e??(typeof window<"u"?window.location.origin:"");if(!t)throw new c("SAML_NO_RETURN_TO","returnTo required outside browser context");let r=await this.startSaml(t);typeof window<"u"&&(window.location.href=r.authorizationUrl)}consumeSsoTokenFromUrl(){return this.serialize(async()=>{if(typeof window>"u")return null;let e=window.location.hash.replace(/^#/,"");if(!e)return null;let t=new URLSearchParams(e),r=t.get("sendora_oidc_error")??t.get("sendora_saml_error");if(r)throw window.history.replaceState(null,"",window.location.pathname+window.location.search),new c("SSO_FAILED",decodeURIComponent(r));let s=t.get("sendora_oidc_token")??t.get("sendora_saml_token");if(!s)return null;let i=t.get("sendora_retired_anon");window.history.replaceState(null,"",window.location.pathname+window.location.search);let o=await this.http.post("/auth-service/token/refresh",{refreshToken:s}),a=o.success?Ee(o.data):null;if(!a)throw new c(o.error?.code??"SSO_EXCHANGE_FAILED",o.error?.message??"Could not exchange SSO token",h(o));let u={...a,tokenType:"Bearer"};await this.replaceLocalIdentity(),this.accessToken=u.accessToken,this.accessExpiresAt=Date.now()+u.expiresIn*1e3,this.storage.set(T,u.accessToken),this.storage.set(R,String(this.accessExpiresAt)),this.storage.set(m,u.refreshToken);let l=Re(u.accessToken),g={id:l?.sub??"",email:l?.email??null,emailVerified:l?.email_verified??!0,name:l?.name??null,isAnonymous:!1};return this.user=g,this.storage.set(_,JSON.stringify(g)),this.analytics.identify(g.id),this.flags.setContext({userId:g.id}),this.emitAuthState({event:"signed_in",user:g}),i&&this.fireDeviceTakeover(i,g.id),g})}async bearerHeaders(){let e=await this.getAccessToken();if(!e)throw new c("NOT_SIGNED_IN","Not signed in");return{Authorization:`Bearer ${e}`}}signOut(){return this.serialize(async()=>{let e=this.storage.get(m);this.wipeLocalIdentity("user"),e&&this.http.post("/auth-service/token/revoke",{refreshToken:e}).catch(()=>{})})}serialize(e){let t=async()=>{try{return await e()}catch(s){throw Je(s)}},r=this.inflight.then(t,t);return this.inflight=r.catch(()=>{}),r}async refreshAccessToken(){if(this.refreshInflight)return this.refreshInflight;let e=this.storage.get(m);if(!e)return null;let t=typeof navigator<"u"&&"locks"in navigator,r=async()=>{let s=this.storage.get(m);if(s&&s!==e){let i=this.storage.get(T),o=this.storage.get(R);if(i&&o){let a=Number(o);if(Number.isFinite(a)&&this.canServeToken(i,a,Date.now()))return this.accessToken=i,this.accessExpiresAt=a,i}}try{let i=s??e,o=await this.http.post("/auth-service/token/refresh",{refreshToken:i});if(!o.success)return Ze(o.error?.code)&&this.tokenStillCurrent(i)?(this.wipeLocalIdentity("session_expired"),this.refreshFailureCount=0,this.refreshCooldownUntil=0,null):(this.armBackoff(),null);let a=Ee(o.data);if(!a)return this.armBackoff(),null;if(!this.tokenStillCurrent(i))return null;if(this.accessToken=a.accessToken,this.accessExpiresAt=Date.now()+a.expiresIn*1e3,this.storage.set(T,a.accessToken),this.storage.set(R,String(this.accessExpiresAt)),this.storage.set(m,a.refreshToken),this.user===null){let u=nt(o.data);u&&(this.user=u,this.storage.set(_,JSON.stringify(u)),this.analytics.identify(u.id),this.emitAuthState({event:"signed_in",user:u}))}return this.refreshFailureCount=0,this.refreshCooldownUntil=0,a.accessToken}catch{return this.armBackoff(),null}};return this.refreshInflight=(async()=>{try{return t?await navigator.locks.request("sendora-authservice-refresh",{mode:"exclusive"},r):await r()}finally{this.refreshInflight=null}})(),this.refreshInflight}armBackoff(){this.refreshFailureCount+=1;let e=Math.min(3e4,1e3*Math.pow(2,this.refreshFailureCount-1));this.refreshCooldownUntil=Date.now()+e}resetRefreshState(){this.refreshFailureCount=0,this.refreshCooldownUntil=0}startVisibilityRefreshReset(){if(this.visibilityResetUnsub||typeof document>"u")return;let e=()=>{document.visibilityState==="visible"&&this.resetRefreshState()};document.addEventListener("visibilitychange",e),this.visibilityResetUnsub=()=>document.removeEventListener("visibilitychange",e)}stopVisibilityRefreshReset(){this.visibilityResetUnsub&&(this.visibilityResetUnsub(),this.visibilityResetUnsub=null)}startProactiveRefreshCron(){if(typeof window>"u"||this.proactiveRefreshTimer)return;let e=.8,t=6e4,r=3e4,s=async()=>{if(!this.accessToken||!this.accessExpiresAt)return;let o=Date.now();if(!this.canServeCachedToken(o)){await this.refreshAndReconcile(o);return}let a=this.accessExpiresAt-o;if(a<=0)return;let l=Math.max(a,5*6e4)*(1-e)+(Math.random()*r*2-r);a<=l&&await this.refreshAccessToken()};this.proactiveRefreshTimer=window.setInterval(()=>{s()},t);let i=()=>{document.visibilityState==="visible"&&s()};document.addEventListener("visibilitychange",i),this.proactiveRefreshCleanup=()=>{this.proactiveRefreshTimer&&(window.clearInterval(this.proactiveRefreshTimer),this.proactiveRefreshTimer=null),document.removeEventListener("visibilitychange",i)}}stopProactiveRefreshCron(){this.proactiveRefreshCleanup&&(this.proactiveRefreshCleanup(),this.proactiveRefreshCleanup=null)}persist(e){this.user=e.user,this.accessToken=e.tokens.accessToken,this.accessExpiresAt=Date.now()+e.tokens.expiresIn*1e3,this.storage.set(_,JSON.stringify(e.user)),this.storage.set(T,e.tokens.accessToken),this.storage.set(R,String(this.accessExpiresAt)),this.storage.set(m,e.tokens.refreshToken),this.analytics.identify(e.user.id),this.flags.setContext({userId:e.user.id}),this.startProactiveRefreshCron(),this.startVisibilityRefreshReset(),this.emitAuthState({event:"signed_in",user:e.user}),e.retiredAnonUserId&&this.fireDeviceTakeover(e.retiredAnonUserId,e.user.id),e.anonRetirement&&(this.lastAnonRetirement=e.anonRetirement),e.reactivatedFromDeletion&&this.fireDeletionCancelled(e.user.id)}async replaceLocalIdentity(){this.user!==null&&(await this.analytics.flush(),this.wipeLocalIdentity("replaced"))}tokenStillCurrent(e){return this.storage.get(m)===e}wipeLocalIdentity(e="replaced"){this.user=null,this.accessToken=null,this.accessExpiresAt=0,this.clockSkewConfirmed=!1,this.lastTakeover=null,this.lastDeletionCancelled=null,this.lastAnonRetirement=null,this.pendingAnonTakeover=null,this.storage.remove(_),this.storage.remove(T),this.storage.remove(R),this.storage.remove(m),this.analytics.reset(),this.analytics.dropQueue(),this.flags.reset(),this.chatbot.newSession(),this.stopProactiveRefreshCron(),this.stopVisibilityRefreshReset(),this.refreshFailureCount=0,this.refreshCooldownUntil=0,e!=="replaced"&&this.emitAuthState({event:"signed_out",user:null,reason:e})}};function Ze(n){return n?n==="INVALID_REFRESH_TOKEN":!1}function V(n){let e=(4-n.length%4)%4,t=(n+"===".slice(0,e)).replace(/-/g,"+").replace(/_/g,"/"),r=atob(t),s=new ArrayBuffer(r.length),i=new Uint8Array(s);for(let o=0;o<r.length;o++)i[o]=r.charCodeAt(o);return s}function I(n){let e=n instanceof Uint8Array?n:new Uint8Array(n),t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function et(n){return{challenge:V(n.challenge),rp:n.rp,user:{id:V(n.user.id),name:n.user.name,displayName:n.user.displayName},pubKeyCredParams:n.pubKeyCredParams,timeout:n.timeout,attestation:n.attestation,excludeCredentials:n.excludeCredentials?.map(e=>({id:V(e.id),type:"public-key",transports:e.transports})),authenticatorSelection:n.authenticatorSelection}}function tt(n){return{challenge:V(n.challenge),timeout:n.timeout,rpId:n.rpId,allowCredentials:n.allowCredentials?.map(e=>({id:V(e.id),type:"public-key",transports:e.transports})),userVerification:n.userVerification}}function rt(n){let e=n.response;return{id:n.id,rawId:I(n.rawId),type:n.type,response:{clientDataJSON:I(e.clientDataJSON),attestationObject:I(e.attestationObject),transports:typeof e.getTransports=="function"?e.getTransports():void 0},clientExtensionResults:n.getClientExtensionResults()}}function Ee(n){if(!n||typeof n!="object")return null;let e=n.tokens,t=e&&typeof e=="object"?e:n;return typeof t.accessToken!="string"||!t.accessToken||typeof t.refreshToken!="string"||!t.refreshToken||typeof t.expiresIn!="number"||t.expiresIn<=0?null:{accessToken:t.accessToken,refreshToken:t.refreshToken,expiresIn:t.expiresIn}}function nt(n){if(!n||typeof n!="object")return null;let e=n.user;if(!e||typeof e!="object")return null;let t=e.id;return typeof t!="string"||t.length===0?null:e}function Te(n,e){let t=Re(n);if(!t)return!0;let r=t.exp;return typeof r!="number"||!Number.isFinite(r)?!0:e<r*1e3}function Re(n){try{let e=n.split(".");if(e.length!==3)return null;let t=e[1].replace(/-/g,"+").replace(/_/g,"/"),r=atob(t+"===".slice(0,(4-t.length%4)%4));return JSON.parse(r)}catch{return null}}function st(n){let e=n.response;return{id:n.id,rawId:I(n.rawId),type:n.type,response:{clientDataJSON:I(e.clientDataJSON),authenticatorData:I(e.authenticatorData),signature:I(e.signature),userHandle:e.userHandle?I(e.userHandle):null},clientExtensionResults:n.getClientExtensionResults()}}function it(n){return n===!1?{pageViews:!1,sessionStart:!1,appOpen:!1,appBackground:!1,engagement:!1}:n===!0||n===void 0?{pageViews:!0,sessionStart:!0,appOpen:!0,appBackground:!0,engagement:!0}:{pageViews:n.pageViews??!0,sessionStart:n.sessionStart??!0,appOpen:n.appOpen??!0,appBackground:n.appBackground??!0,engagement:n.engagement??!0}}var ot=250,_e=360*60*1e3;function Le(n,e){if(typeof window>"u")return()=>{};let t=it(e.autoTrack),r=e.sessionIdleMs??18e5,s=[],i="sendora_session_id",o="sendora_session_last_activity";function a(){return Ce(i)??""}function u(d){De(i,d)}function l(){let d=Ce(o);return d&&Number(d)||0}function g(d){De(o,String(d))}function v(){return`sess_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`}function w(d){let S=Date.now(),N=l();if(!a()||N&&S-N>r){let G=v();u(G),d&&t.sessionStart&&n.track("session.start",{sessionId:G})}g(S)}w(t.sessionStart),t.appOpen&&n.track("app.opened",{sessionId:a()||void 0,url:window.location.origin+window.location.pathname,referrer:document.referrer||void 0});let k=window.location.pathname,C=0,A=document.visibilityState==="visible"?Date.now():0;function te(){A>0&&(C+=Date.now()-A,A=0)}function j(){if(!t.engagement)return;te();let d=C;if(C=0,!(d<ot)){d>_e&&(d=_e);try{n.track("app.engagement",{durationMs:Math.round(d),screen:k,sessionId:a()||void 0})}catch{}}}function Pe(d){k=d,C=0,A=document.visibilityState==="visible"?Date.now():0}if(t.pageViews||t.engagement){t.pageViews&&n.page();let d=()=>{j(),w(!0),t.pageViews&&n.page(),Pe(window.location.pathname)},S=()=>d();window.addEventListener("popstate",S),s.push(()=>window.removeEventListener("popstate",S));let N=window;if(!N.__sendoraHistoryPatched){N.__sendoraHistoryPatched=!0;let G=history.pushState,Ue=history.replaceState;history.pushState=function(...ne){let se=G.apply(this,ne);return window.dispatchEvent(new Event("sendora:locationchange")),se},history.replaceState=function(...ne){let se=Ue.apply(this,ne);return window.dispatchEvent(new Event("sendora:locationchange")),se}}let re=()=>d();window.addEventListener("sendora:locationchange",re),s.push(()=>window.removeEventListener("sendora:locationchange",re))}if(t.appBackground||t.engagement){let d=()=>{if(document.visibilityState==="hidden"){j(),t.appBackground&&(w(!0),n.track("app.backgrounded",{sessionId:a()||void 0}));try{n.flush()}catch{}}else document.visibilityState==="visible"&&(t.appBackground&&(w(!0),n.track("app.foregrounded",{sessionId:a()||void 0})),t.engagement&&A===0&&(A=Date.now()))};if(document.addEventListener("visibilitychange",d),s.push(()=>document.removeEventListener("visibilitychange",d)),t.engagement){let S=()=>{j();try{n.flush()}catch{}};window.addEventListener("pagehide",S),s.push(()=>window.removeEventListener("pagehide",S))}}let he=0,D=()=>{let d=Date.now();d-he<5e3||(he=d,w(!0))};return window.addEventListener("click",D,{passive:!0}),window.addEventListener("keydown",D,{passive:!0}),window.addEventListener("scroll",D,{passive:!0}),s.push(()=>{window.removeEventListener("click",D),window.removeEventListener("keydown",D),window.removeEventListener("scroll",D)}),()=>{j();for(let d of s)try{d()}catch{}}}function Ce(n){try{return window.sessionStorage?.getItem(n)??null}catch{return null}}function De(n,e){try{window.sessionStorage?.setItem(n,e)}catch{}}var B=class n{constructor(e){this.http=e}static isSupported(){return typeof window>"u"?!1:"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window}static permission(){return typeof Notification>"u"?"denied":Notification.permission}async subscribe(e){if(!n.isSupported())throw new Error("[sendoracloud] Web Push not supported in this browser.");let t=Notification.permission;if(t==="default"&&(t=await Notification.requestPermission()),t!=="granted")throw new Error(`[sendoracloud] Notification permission ${t}.`);let r=await navigator.serviceWorker.getRegistration(e.scope??"/");r||(r=await navigator.serviceWorker.register(e.serviceWorkerPath,{scope:e.scope??"/"})),await navigator.serviceWorker.ready;let i=(await this.http.get("/push/vapid"))?.data?.publicKey;if(!i)throw new Error("[sendoracloud] backend returned no VAPID public key.");let a=await r.pushManager.getSubscription()??await r.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:at(i)}),u=a.toJSON(),l=u.endpoint,g=u.keys?.p256dh??"",v=u.keys?.auth??"",w=await ct(l),k=await this.http.post("/push/tokens",{platform:"web",token:w,webEndpoint:l,webP256dh:g,webAuth:v,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,locale:typeof navigator<"u"?navigator.language:void 0,timezone:Intl?.DateTimeFormat?.().resolvedOptions?.().timeZone,...e.userId?{userId:e.userId}:{}});if(!k?.data?.tokenId)throw new Error("[sendoracloud] backend returned no tokenId on subscribe.");return{tokenId:k.data.tokenId,subscription:a}}async unsubscribe(e="/"){if(!n.isSupported())return!1;let t=await navigator.serviceWorker.getRegistration(e);if(!t)return!1;let r=await t.pushManager.getSubscription();return r?await r.unsubscribe():!1}async trackOpen(e,t){let r={sendId:e};t!==void 0&&(r.clickAction=t);let s=await this.http.post("/push/track-open",r);if(!s.success)throw new Error(s.error?.message??"push.trackOpen failed")}};function at(n){let e="=".repeat((4-n.length%4)%4),t=(n+e).replace(/-/g,"+").replace(/_/g,"/"),r=atob(t),s=new Uint8Array(r.length);for(let i=0;i<r.length;i++)s[i]=r.charCodeAt(i);return s}async function ct(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}var q=class{constructor(e){}unsupported(){throw new Error("[SendoraCloud] sendora.audiences is not available in the browser SDK. Audiences require a secret (sk_*) key with the audiences:read/write scopes and must be managed from a trusted server, not the browser.")}list(){return this.unsupported()}get(e){return this.unsupported()}create(e){return this.unsupported()}update(e,t){return this.unsupported()}delete(e){return this.unsupported()}};var p=class extends Error{constructor(e,t,r){super(t),this.name="LinkError",this.code=e,this.statusCode=r}};function ue(n,e){let t=(n??"").toUpperCase();return t==="NOT_FOUND"?new p("NOT_FOUND",e):t==="FORBIDDEN"||t==="UNAUTHORIZED"?new p("UNAUTHORIZED",e):t==="RATE_LIMITED"?new p("RATE_LIMITED",e):t==="ENTITLEMENT_ERROR"||/plan limit/i.test(e)?new p("PLAN_LIMIT",e):t==="VALIDATION_ERROR"?/iOS bundle|Android package/i.test(e)?new p("BUNDLE_MISMATCH",e):/2KB|10KB|linkData/i.test(e)?new p("DATA_TOO_LARGE",e):/fallbackUrl/i.test(e)&&/apps/i.test(e)?new p("FALLBACK_REQUIRED",e):new p("INVALID_INPUT",e):t==="PARSE_ERROR"||t==="HTTP_ERROR"||/HTTP \d{3}/.test(e)?new p("NETWORK",e):new p("UNKNOWN",e||`Unknown LinkError (code=${n??"none"})`)}var le=/^[a-z0-9-]{3,20}$/;function ut(n){try{let t=new URL(n).pathname.split("/").filter(Boolean);if(t.length===0)return null;let r=t[t.length-1];return le.test(r)?r:null}catch{return null}}var lt=5*6e4,dt=50,ht=5,z=class{constructor(e){this.http=e;this.prewarmCache=new Map;this.prewarmInflight=0}cacheKey(e,t){if(t)return`k:${t}`;let r={},s=e;for(let i of Object.keys(s).sort())r[i]=s[i];return`s:${JSON.stringify(r)}`}evictExpired(){let e=Date.now();for(let[t,r]of this.prewarmCache)e-r.ts>lt&&this.prewarmCache.delete(t);for(;this.prewarmCache.size>dt;){let t=this.prewarmCache.keys().next().value;if(t===void 0)break;this.prewarmCache.delete(t)}}prewarm(e,t){this.evictExpired();let r=this.cacheKey(e,t?.key);if(this.prewarmCache.has(r)||this.prewarmInflight>=ht)return;this.prewarmInflight++;let s=this.doCreate(e).catch(i=>{throw this.prewarmCache.delete(r),i}).finally(()=>{this.prewarmInflight--});this.prewarmCache.set(r,{promise:s,ts:Date.now()})}async create(e,t){if(!e.title)throw new p("INVALID_INPUT","links.create: title is required");this.evictExpired();let r=this.cacheKey(e,t?.key),s=this.prewarmCache.get(r);return s?(this.prewarmCache.delete(r),s.promise):this.doCreate(e)}async doCreate(e){let t={title:e.title};e.fallbackUrl&&(t.fallbackUrl=e.fallbackUrl),e.iosDeepLinkPath&&(t.iosDeepLinkPath=e.iosDeepLinkPath),e.androidDeepLinkPath&&(t.androidDeepLinkPath=e.androidDeepLinkPath),e.linkData&&(t.linkData=e.linkData),e.ogTitle&&(t.ogTitle=e.ogTitle),e.ogDescription&&(t.ogDescription=e.ogDescription),e.ogImageUrl&&(t.ogImageUrl=e.ogImageUrl),e.campaign&&(t.campaign=e.campaign),e.source&&(t.source=e.source),e.medium&&(t.medium=e.medium),e.channel&&(t.channel=e.channel),e.tags&&(t.tags=e.tags),e.expiresAt&&(t.expiresAt=e.expiresAt),e.iosBundleId&&(t.iosBundleId=e.iosBundleId),e.androidPackageName&&(t.androidPackageName=e.androidPackageName);let r=await this.http.post("/sdk/links",t);if(!r.success||!r.data)throw ue(r.error?.code,r.error?.message??"links.create failed");return r.data}async revoke(e){if(!le.test(e))throw new p("INVALID_INPUT",`links.revoke: '${e}' is not a valid shortcode`);let t=await this.http.post(`/sdk/links/${encodeURIComponent(e)}/revoke`,{});if(!t.success||!t.data)throw ue(t.error?.code,t.error?.message??"links.revoke failed");return{shortcode:t.data.shortcode,revoked:!0}}async getStats(e){if(!le.test(e))throw new p("INVALID_INPUT",`links.getStats: '${e}' is not a valid shortcode`);let t=await this.http.get(`/sdk/links/${encodeURIComponent(e)}/stats`);if(!t.success||!t.data)throw ue(t.error?.code,t.error?.message??"links.getStats failed");return t.data}};var Q=class{constructor(e){this.http=e}async reportInstall(e={}){let t=await this.http.post("/attribution/install",e);if(!t.success||!t.data)throw new Error(t.error?.message??"attribution.reportInstall failed");return t.data}async checkDeferred(e={}){let t=await this.http.post("/attribution/deferred",e);if(!t.success)throw new Error(t.error?.message??"attribution.checkDeferred failed");return t.data??null}};var J=class{constructor(e){this.http=e}async createTicket(e){let t=await this.http.post("/support/tickets",e);if(!t.success||!t.data)throw new Error(t.error?.message??"support.createTicket failed");return t.data}async submitCsat(e){let t=await this.http.post("/support/csat",e);if(!t.success||!t.data)throw new Error(t.error?.message??"support.submitCsat failed");return t.data}};var Z=class{constructor(e){this.http=e}async search(e){if(!e.query||e.query.trim().length===0)return[];let t=new URLSearchParams({query:e.query});e.limit&&t.set("limit",String(e.limit));let r=await this.http.get(`/kb/search?${t.toString()}`);if(!r.success||!Array.isArray(r.data))throw new Error(r.error?.message??"kb.search failed");return r.data}};var pt=/^[A-Za-z0-9_.-]{1,64}$/;function gt(n){if(n!==void 0){if(typeof n!="string"||!pt.test(n))throw new Error(`[sendora] init: storagePrefix must be 1-64 chars of A-Z a-z 0-9 _ . - (got ${JSON.stringify(n)}). Changing it signs the browser out, so it is validated rather than ignored.`);return n}}var ee=class ee{constructor(e){this.autoTrackCleanup=null;this.http=new Y(e),this.storage=new X(gt(e.storagePrefix)),this.consent=new K(e.defaultConsent===!0,this.http),this.analytics=new x(e,this.http,this.storage,this.consent),this.flags=new O(e,this.http,this.storage),this.surveys=new M(e,this.http,this.storage),this.messages=new F(e,this.http,this.storage),this.chatbot=new H(e,this.http,this.storage),this.auth=new W(e,this.http,this.storage,this.analytics,this.flags,this.chatbot),this.webPush=new B(this.http),this.audiences=new q(this.http),this.links=new z(this.http),this.attribution=new Q(this.http),this.support=new J(this.http),this.kb=new Z(this.http),e.autoTrack!==!1&&(this.autoTrackCleanup=Le(this.analytics,e))}static init(e){return ve(e.apiKey),new ee(e)}static sanitizeHtml(e){return ce(e)}static safeUrl(e){return E(e)}track(e,t){this.analytics.track(e,t)}page(e){this.analytics.page(e)}identify(e,t,r){this.analytics.identify(e,t,r),this.flags.setContext({userId:e})}reset(){this.analytics.reset(),this.flags.reset(),this.chatbot.newSession()}async flush(){await this.analytics.flush()}destroy(){this.autoTrackCleanup&&(this.autoTrackCleanup(),this.autoTrackCleanup=null),this.analytics.destroy(),this.flags.destroy(),this.messages.destroy()}};ee.version=b;var de=ee,ur=de;export{$ as AlreadyIdentifiedError,x as Analytics,q as Audiences,W as Auth,c as AuthError,H as Chatbot,K as Consent,U as CredentialInUseError,P as EmailAlreadyTakenError,O as FeatureFlags,F as InAppMessaging,p as LinkError,z as Links,de as SendoraCloud,M as Surveys,f as ValidationError,B as WebPush,ur as default,ut as extractShortcodeFromUrl,E as safeUrl,ce as sanitizeHtml};
1
+ var pe=/^[a-zA-Z][a-zA-Z0-9._:-]{0,127}$/;var Ne=new Set(["__proto__","constructor","prototype"]),f=class extends Error{constructor(e){super(`[SendoraCloud] ${e}`),this.name="SendoraValidationError"}};function ge(n){if(typeof n!="string"||!pe.test(n))throw new f(`Invalid event name: must match ${pe}, got "${String(n)}".`)}function fe(n){if(n==null)return;if(typeof n!="object"||Array.isArray(n))throw new f("Properties must be a plain object, not an array or primitive.");let e=me(n);if(e>5)throw new f(`Properties nested too deeply (${e} levels, max 5).`);ye(n);let t;try{t=JSON.stringify(n).length}catch{throw new f("Properties contain a circular reference or unserializable value.")}if(t>32768)throw new f(`Properties too large (${t} bytes, max 32768).`)}function me(n,e=0){if(e>6||n==null||typeof n!="object")return e;let t=e;for(let r of Object.keys(n)){let s=me(n[r],e+1);s>t&&(t=s)}return t}function ye(n){if(!(n==null||typeof n!="object"))for(let e of Object.keys(n)){if(Ne.has(e))throw new f(`Forbidden property key "${e}" (prototype pollution guard).`);ye(n[e])}}var xe=/^pk_[A-Za-z0-9_-]{16,}$/;function ve(n){if(!n||typeof n!="string")throw new f("apiKey is required.");if(n.startsWith("sk_")||n.startsWith("sendora_secret_"))throw new f("Secret keys must NEVER be used in browser SDK. Use a publishable key (pk_...).");if(!xe.test(n))throw new f("Invalid publishable key format. Expected pk_... (17+ chars).")}function we(n){let e=n.replace(/\/$/,"");if(!(e.startsWith("http://localhost")||e.startsWith("http://127.0.0.1"))&&!e.startsWith("https://"))throw new f("apiUrl must be https:// (only http://localhost is allowed for dev).")}var ke={name:"@sendoracloud/sdk-web",version:"3.22.0",description:"Sendora Cloud Web SDK \u2014 analytics, feature flags, surveys, in-app messaging, chatbot, auth, deep links (Branch / Firebase parity). Zero dependencies, TypeScript, SSR-safe.",type:"module",main:"./dist/index.cjs",module:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"}},files:["dist","README.md","LICENSE"],keywords:["sendora","analytics","feature-flags","surveys","in-app-messaging","chatbot","tracking","customer-engagement"],homepage:"https://sendoracloud.com/sdks",repository:{type:"git",url:"git+https://github.com/sendoracloud/sdk-web.git"},bugs:{url:"https://github.com/sendoracloud/sdk-web/issues"},author:"Sendora Cloud <hello@sendoracloud.com>",license:"Apache-2.0",publishConfig:{access:"public"},sideEffects:!1,scripts:{build:"tsup src/index.ts --format cjs,esm --dts --clean --minify",typecheck:"tsc --noEmit",prepublishOnly:"npm run build"},devDependencies:{typescript:"^5.4.0",tsup:"^8.0.0"}};var b=ke.version;var Me="https://api.sendoracloud.com",Fe=1e4,He="@sendoracloud/sdk-web",Y=class{constructor(e){let t=(e.apiUrl??Me).replace(/\/$/,"");we(t),this.apiKey=e.apiKey,this.baseUrl=t,this.debug=!!e.debug}get(e,t){return this.request("GET",e,void 0,t)}post(e,t,r){return this.request("POST",e,t,r)}patch(e,t,r){return this.request("PATCH",e,t,r)}delete(e,t){return this.request("DELETE",e,void 0,t)}async request(e,t,r,s){let i=`${this.baseUrl}/api/v1${t}`,o=typeof AbortController<"u"?new AbortController:null,a=o?setTimeout(()=>o.abort(),Fe):null;try{let u=await fetch(i,{method:e,headers:{"Content-Type":"application/json","X-API-Key":this.apiKey,"X-Sendora-SDK-Name":He,"X-Sendora-SDK-Version":b,...s??{}},body:r?JSON.stringify(r):void 0,signal:o?o.signal:void 0});a&&clearTimeout(a);let l;try{l=await u.json()}catch{l={success:!1,error:{code:"PARSE_ERROR",message:`HTTP ${u.status}`}}}if(this.debug&&console.debug(`[SendoraCloud] ${e} ${t} \u2192 ${u.status}`),!u.ok){if(t.startsWith("/auth-service/")&&!this.debug)console.warn(`[SendoraCloud] ${e} ${t} \u2192 HTTP ${u.status}`);else{let v=l?.error?.code??"HTTP_ERROR",w=l?.error?.message??`HTTP ${u.status}`,k=l?.error?.details?.fieldErrors,C=k?` (${Object.entries(k).map(([A,te])=>`${A}: ${(te??[]).join(", ")}`).join("; ")})`:"";console.warn(`[SendoraCloud] ${e} ${t} \u2192 HTTP ${u.status} \u2014 ${v}: ${w}${C}`)}l&&l.error&&(l.error={...l.error,status:u.status})}return l}catch(u){a&&clearTimeout(a);let l=u instanceof Error&&u.name==="AbortError"?"timeout":"error";return console.warn(`[SendoraCloud] ${e} ${t} network ${l}`),{success:!1,error:{code:"NETWORK_ERROR",message:l}}}}};var Ke="sendora_",X=class{constructor(e,t=!1){this.memoryStore=new Map;this.useLocalStorage=t?!1:this.checkLocalStorage(),this.prefix=e??Ke}get(e){let t=this.prefix+e;if(this.useLocalStorage)try{return localStorage.getItem(t)}catch{return this.memoryStore.get(t)??null}return this.memoryStore.get(t)??null}set(e,t){let r=this.prefix+e;if(this.useLocalStorage)try{localStorage.setItem(r,t);return}catch{}this.memoryStore.set(r,t)}remove(e){let t=this.prefix+e;if(this.useLocalStorage)try{localStorage.removeItem(t)}catch{}this.memoryStore.delete(t)}clearPrefix(e){let t=this.prefix+e;if(this.useLocalStorage)try{for(let r=localStorage.length-1;r>=0;r--){let s=localStorage.key(r);s&&s.startsWith(t)&&localStorage.removeItem(s)}}catch{}for(let r of Array.from(this.memoryStore.keys()))r.startsWith(t)&&this.memoryStore.delete(r)}checkLocalStorage(){try{if(typeof localStorage>"u")return!1;let e="__sendora_test__";return localStorage.setItem(e,"1"),localStorage.removeItem(e),!0}catch{return!1}}};function L(n=""){let e=new Uint8Array(16),t=typeof globalThis<"u"&&"crypto"in globalThis?globalThis.crypto:void 0;if(!t||typeof t.getRandomValues!="function")throw new Error("[SendoraCloud] crypto.getRandomValues unavailable \u2014 refusing to mint IDs without a CSPRNG");t.getRandomValues(e);let r="";for(let s of e)r+=s.toString(16).padStart(2,"0");return n+r}var Ae=500,ie=10,oe=6e4,x=class{constructor(e,t,r,s){this.queue=[];this.timer=null;this.userId=null;this.identityToken=null;this.consecutiveFailures=0;this.nextFlushAfter=0;this.breakerOpenAt=0;this.breakerWarned=!1;this.http=t,this.storage=r,this.consent=s,this.projectId=e.projectId,this.flushInterval=e.flushInterval??5e3,this.maxQueueSize=e.maxQueueSize??20,this.persistUserId=!!e.persistUserId,this.stripQueryParams=e.stripQueryParams!==!1,this.appVersion=e.appVersion,this.storage.get("schema_version")===null&&this.storage.set("schema_version","1");let i=this.storage.get("anonymous_id");if(i?this.anonymousId=i:(this.anonymousId=L("anon_"),this.storage.set("anonymous_id",this.anonymousId)),this.persistUserId){let o=this.storage.get("user_id");o&&(this.userId=o)}this.timer=setInterval(()=>this.flush(),this.flushInterval),typeof window<"u"&&window.addEventListener("beforeunload",()=>this.flush()),this.consent.subscribe(o=>{o&&this.flush()})}track(e,t){ge(e),t&&fe(t),this.queue.length>=Ae&&this.queue.shift(),this.queue.push({eventType:e,properties:t??{},userId:this.userId??void 0,anonymousId:this.anonymousId,timestamp:new Date().toISOString(),identityToken:this.identityToken??void 0}),this.queue.length>=this.maxQueueSize&&this.flush()}page(e){if(typeof window>"u")return;let t=this.stripQueryParams?window.location.origin+window.location.pathname:window.location.href;this.track("page.viewed",{url:t,path:window.location.pathname,title:document.title,referrer:document.referrer||void 0,...e})}identify(e,t,r){if(typeof e!="string"||e.length===0||e.length>256)throw new Error("[SendoraCloud] userId must be a 1-256 char string.");this.userId=e,this.identityToken=r?.identityToken??null,this.persistUserId&&this.storage.set("user_id",e),this.track("user.identified",{...t})}reset(e=!0){this.userId=null,this.identityToken=null,this.storage.remove("user_id"),e&&(this.anonymousId=L("anon_"),this.storage.set("anonymous_id",this.anonymousId)),this.storage.clearPrefix("iam_shown_"),this.storage.clearPrefix("survey_shown_")}dropQueue(){this.queue=[]}async flush(){if(this.queue.length===0||!this.consent.isGranted()||Date.now()<this.nextFlushAfter)return;this.consecutiveFailures>ie&&Date.now()-this.breakerOpenAt>=oe&&(this.consecutiveFailures=0,this.breakerOpenAt=0,this.breakerWarned=!1);let e=this.queue.splice(0,100),t=this.getSessionId(),r=e.map(a=>({projectId:this.projectId,module:"custom",eventType:a.eventType,userId:a.userId,anonymousId:a.anonymousId,identityToken:a.identityToken,timestamp:a.timestamp??new Date().toISOString(),properties:a.properties??{},context:this.getContext(),...t?{sessionId:t}:{},consent:["analytics"]}));if((await this.http.post("/events/batch",{events:r})).success){this.consecutiveFailures=0,this.breakerOpenAt=0,this.breakerWarned=!1;return}if(this.consecutiveFailures++,this.consecutiveFailures>ie){this.breakerWarned||(this.breakerOpenAt=Date.now(),this.breakerWarned=!0,console.warn(`[SendoraCloud] Analytics circuit breaker open after ${ie} consecutive failed flushes \u2014 events will be dropped until a flush succeeds or ${oe}ms elapse.`));return}let i=Math.min(oe,1e3*2**this.consecutiveFailures);this.nextFlushAfter=Date.now()+i;let o=Math.max(0,Ae-this.queue.length);o>0&&this.queue.unshift(...e.slice(0,o))}destroy(){this.timer&&clearInterval(this.timer),this.timer=null,this.flush()}getSessionId(){try{return typeof sessionStorage>"u"?void 0:sessionStorage.getItem("sendora_session_id")||void 0}catch{return}}getContext(){return typeof window>"u"?{sdk:{name:"@sendoracloud/sdk-web",version:b}}:{page:{url:this.stripQueryParams?window.location.origin+window.location.pathname:window.location.href,path:window.location.pathname,title:document.title},referrer:document.referrer||void 0,locale:typeof navigator<"u"?navigator.language:void 0,device:this.buildDevice(),sdk:{name:"@sendoracloud/sdk-web",version:b}}}buildDevice(){if(typeof navigator>"u")return;let e=navigator.userAgent||"",r=navigator.userAgentData?.mobile??/Mobi|Android|iPhone|iPod/i.test(e);return{type:/iPad|Tablet|(?:Android(?!.*Mobile))/i.test(e)?"tablet":r?"mobile":"desktop",os:"Web",osVersion:"",model:"",appVersion:this.resolveAppVersion(),browser:Ve(e)}}resolveAppVersion(){if(this.appVersion)return this.appVersion;if(typeof document<"u"){let r=document.querySelector('meta[name="sendora:app-version"]')?.getAttribute("content");if(r)return r}let e=globalThis.__SENDORA_APP_VERSION__;return typeof e=="string"?e:""}};function Ve(n){let e=[["Edge",/Edg\/(\d+)/],["Opera",/OPR\/(\d+)/],["Firefox",/Firefox\/(\d+)/],["Samsung Internet",/SamsungBrowser\/(\d+)/],["Chrome",/Chrome\/(\d+)/],["Safari",/Version\/(\d+)[^ ]* Safari/]];for(let[t,r]of e){let s=r.exec(n);if(s)return`${t} ${s[1]}`}return"Unknown"}var O=class{constructor(e,t,r){this.cache=new Map;this.refreshInterval=null;this.http=t,this.storage=r;let s=this.storage.get("flags");if(s)try{let i=JSON.parse(s);if(Array.isArray(i))for(let o of i)ae(o)&&this.cache.set(o.key,o)}catch{}}setContext(e){this.userId=e.userId,this.entityId=e.entityId,this.environment=e.environment}async getFlag(e){if(typeof e!="string"||e.length===0||e.length>128)return null;let t=this.cache.get(e);if(t)return t.value;let r=await this.http.post("/feature-flags/evaluate",{key:e,userId:this.userId,entityId:this.entityId,environment:this.environment});return r.success&&r.data&&ae(r.data)?(this.cache.set(e,r.data),this.persistCache(),r.data.value):null}async isEnabled(e,t=!1){let r=await this.getFlag(e);return typeof r=="boolean"?r:t}async refreshAll(){let e=await this.http.post("/feature-flags/evaluate-all",{userId:this.userId,entityId:this.entityId,environment:this.environment});if(e.success&&Array.isArray(e.data)){this.cache.clear();for(let t of e.data)ae(t)&&this.cache.set(t.key,t);this.persistCache()}}startAutoRefresh(e=6e4){this.stopAutoRefresh(),this.refreshAll(),this.refreshInterval=setInterval(()=>this.refreshAll(),e)}stopAutoRefresh(){this.refreshInterval&&clearInterval(this.refreshInterval),this.refreshInterval=null}getAllFlags(){let e={};for(let[t,r]of this.cache)e[t]=r.value;return e}reset(){this.cache.clear(),this.storage.remove("flags"),this.userId=void 0,this.entityId=void 0,this.environment=void 0}destroy(){this.stopAutoRefresh()}persistCache(){this.storage.set("flags",JSON.stringify(Array.from(this.cache.values())))}};function ae(n){if(n==null||typeof n!="object")return!1;let e=n;return Object.prototype.hasOwnProperty.call(e,"__proto__")||Object.prototype.hasOwnProperty.call(e,"constructor")?!1:typeof e.key=="string"&&"value"in e}var $e=32*1024,M=class{constructor(e,t,r){this.activeSurvey=null;this.http=t,this.storage=r}onDisplay(e){this.onSurveyDisplay=e}async showSurvey(e){if(typeof e!="string"||!/^[A-Za-z0-9_-]{6,64}$/.test(e))return null;let t=`survey_shown_${e}`;if(this.storage.get(t))return null;let r=await this.http.get(`/surveys/${encodeURIComponent(e)}/config`);return!r.success||!r.data||!We(r.data)?null:(this.activeSurvey=r.data,this.storage.set(t,"1"),this.onSurveyDisplay&&this.onSurveyDisplay(r.data),r.data)}async submitResponse(e,t,r=!0){let s=0;try{s=JSON.stringify(t).length}catch{return!1}if(s>$e)return!1;let i=await this.http.post("/surveys/responses",{surveyId:e,answers:t,completed:r});return i.success&&(this.activeSurvey=null),i.success}dismiss(){this.activeSurvey=null}getActiveSurvey(){return this.activeSurvey}};function We(n){if(n==null||typeof n!="object")return!1;let e=n;return typeof e.id!="string"||typeof e.name!="string"||!Array.isArray(e.questions)?!1:e.questions.every(Be)}function Be(n){if(n==null||typeof n!="object")return!1;let e=n;return typeof e.id=="string"&&typeof e.text=="string"}function E(n){if(!(!n||typeof n!="string"))try{let e=typeof window<"u"?window.location.href:"https://local/",t=new URL(n,e);return t.protocol==="http:"||t.protocol==="https:"?t.href:void 0}catch{return}}var qe=new Set(["b","i","u","em","strong","a","p","br","span","ul","ol","li","h1","h2","h3","h4"]),ze={a:new Set(["href","target","rel"])};function ce(n){if(typeof DOMParser>"u")return"";let t=new DOMParser().parseFromString(`<div>${n}</div>`,"text/html").body.firstElementChild;return t?(Se(t),t.innerHTML):""}function Se(n){let e=Array.from(n.children);for(let t of e){let r=t.tagName.toLowerCase();if(!qe.has(r)){let i=document.createTextNode(t.textContent??"");t.replaceWith(i);continue}let s=ze[r]??new Set;for(let i of Array.from(t.attributes)){if(!s.has(i.name.toLowerCase())){t.removeAttribute(i.name);continue}if(i.name.toLowerCase()==="href"){let o=E(i.value);o?t.setAttribute("href",o):t.removeAttribute(i.name)}}r==="a"&&(t.setAttribute("rel","noopener noreferrer"),t.setAttribute("target","_blank")),Se(t)}}var F=class{constructor(e,t,r){this.messages=[];this.pollInterval=null;this.http=t,this.storage=r}onDisplay(e){this.onMessageDisplay=e}async checkMessages(){let e=await this.http.get("/in-app-messages/active");if(!e.success||!Array.isArray(e.data))return null;this.messages=e.data.map(je);for(let t of this.messages){let r=`iam_shown_${t.id}`;if(!this.storage.get(r))return this.storage.set(r,"1"),this.onMessageDisplay&&this.onMessageDisplay(t),t}return null}async recordAction(e,t){await this.http.post("/in-app-messages/impressions",{messageId:e,action:t})}startPolling(e=3e5){this.stopPolling(),this.checkMessages(),this.pollInterval=setInterval(()=>this.checkMessages(),e)}stopPolling(){this.pollInterval&&clearInterval(this.pollInterval),this.pollInterval=null}getMessages(){return this.messages}destroy(){this.stopPolling()}};function je(n){return{...n,content:{...n.content,ctaUrl:E(n.content.ctaUrl),imageUrl:E(n.content.imageUrl)}}}var Ge=4e3,H=class{constructor(e,t,r){this.chatbotId=null;this.messages=[];this.http=t,this.storage=r;let s=this.storage.get("chat_session_id");this.sessionId=s??L("chat_"),s||this.storage.set("chat_session_id",this.sessionId)}init(e){if(typeof e!="string"||!/^[A-Za-z0-9_-]{6,64}$/.test(e))throw new Error("[SendoraCloud] Invalid chatbotId.");this.chatbotId=e}onNewMessage(e){this.onMessage=e}async sendMessage(e,t){if(!this.chatbotId||typeof e!="string"||e.length===0||e.length>Ge)return null;let r={role:"user",content:e,timestamp:new Date().toISOString()};this.messages.push(r);let s=await this.http.post("/chatbot/message",{chatbotId:this.chatbotId,sessionId:this.sessionId,message:e,userId:t});if(s.success&&s.data&&typeof s.data.reply=="string"){let i={role:"assistant",content:s.data.reply,timestamp:new Date().toISOString()};return this.messages.push(i),this.onMessage&&this.onMessage(i),i}return null}getMessages(){return[...this.messages]}newSession(){this.messages=[],this.sessionId=L("chat_"),this.storage.set("chat_session_id",this.sessionId)}getSessionId(){return this.sessionId}};var K=class{constructor(e,t){this.listeners=new Set;this.granted=e,this.http=t}isGranted(){return this.granted}grant(){this.granted||(this.granted=!0,this.emit())}revoke(){this.granted&&(this.granted=!1,this.emit())}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async record(e){if(!this.http)throw new Error("consent.record requires SDK init (HttpClient unavailable)");let t=await this.http.post("/consent/record",e);if(!t.success||!t.data)throw new Error(t.error?.message??"consent.record failed");return t.data}async requestDeletion(e){if(!this.http)throw new Error("consent.requestDeletion requires SDK init (HttpClient unavailable)");let t=await this.http.post("/consent/deletion-request",e);if(!t.success||!t.data)throw new Error(t.error?.message??"consent.requestDeletion failed");return t.data}emit(){for(let e of this.listeners)try{e(this.granted)}catch{}}};var T="auth_access_token",R="auth_access_expires",m="auth_refresh_token",_="auth_user",Ie=3e4,Ye=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function y(n){if(!n||typeof n!="object")return!1;let e=n,t=e.user,r=e.tokens;return!(!t||typeof t.id!="string"||t.id.length===0||!r||typeof r.accessToken!="string"||r.accessToken.length===0||typeof r.refreshToken!="string"||r.refreshToken.length===0||typeof r.expiresIn!="number"||r.expiresIn<=0||t.isAnonymous!==void 0&&typeof t.isAnonymous!="boolean"||t.email!==void 0&&t.email!==null&&typeof t.email!="string"||t.emailVerified!==void 0&&typeof t.emailVerified!="boolean"||t.name!==void 0&&t.name!==null&&typeof t.name!="string"||t.signupMethod!==void 0&&t.signupMethod!==null&&typeof t.signupMethod!="string"||t.lastLoginMethod!==void 0&&t.lastLoginMethod!==null&&typeof t.lastLoginMethod!="string"||e.retiredAnonUserId!==void 0&&typeof e.retiredAnonUserId!="string")}var P=class extends Error{constructor(e="An account with this email already exists"){super(e),this.name="EmailAlreadyTakenError"}},$=class extends Error{constructor(e="Already signed in with an identity; use link*() to add a credential, or sign out first"){super(e),this.name="AlreadyIdentifiedError"}},U=class extends Error{constructor(t="This credential is already linked to a different account",r){super(t);this.code="CREDENTIAL_IN_USE";this.kind="credential_in_use";this.retryable=!1;this.name="CredentialInUseError",this.provider=r?.provider,this.collision=r?.collision,this.status=r?.status}};function be(n){let e=n?.error?.details;if(!e||typeof e!="object")return{};let t=e;return{provider:typeof t.provider=="string"?t.provider:void 0,collision:t.collision==="identity"||t.collision==="email"?t.collision:void 0}}var Xe=new Set(["network","server","rate_limited","account_locked"]);function Qe(n,e){switch(n){case"NETWORK_ERROR":case"NETWORK_TIMEOUT":return"network";case"PARSE_ERROR":return"server";case"RATE_LIMITED":case"RATE_LIMIT":case"RATE_LIMIT_EXCEEDED":case"QUOTA_EXCEEDED":return"rate_limited";case"ACCOUNT_LOCKED":return"account_locked";case"CREDENTIAL_IN_USE":return"credential_in_use";case"LAST_CREDENTIAL":return"last_credential";case"RECENT_AUTH_REQUIRED":return"recent_auth_required";case"NOT_ANONYMOUS":case"FORBIDDEN_NON_ANONYMOUS":return"already_identified";case"PASSKEY_USER_CANCELLED":case"GAME_CENTER_CANCELLED":case"PLAY_GAMES_CANCELLED":case"SSO_CANCELLED":return"cancelled";case"GAME_CENTER_UNAVAILABLE":case"PLAY_GAMES_UNAVAILABLE":case"ENTITLEMENT_ERROR":case"tier_required":return"config";case"UNAUTHORIZED":case"INVALID_CREDENTIALS":case"INVALID_REFRESH_TOKEN":case"EMAIL_OTP_INVALID":case"MAGIC_LINK_INVALID":case"PASSKEY_RP_MISMATCH":case"NOT_SIGNED_IN":return"invalid_credential";default:break}if(typeof e=="number"){if(e===429)return"rate_limited";if(e>=500)return"server";if(e>=400)return"invalid_credential"}return"unknown"}var c=class extends Error{constructor(e,t,r){super(t),this.name="AuthError",this.code=e,this.kind=r?.kind??Qe(e,r?.status),this.retryable=Xe.has(this.kind),this.retryAfterSeconds=r?.retryAfterSeconds,this.status=r?.status}};function Je(n){if(n instanceof c||n instanceof P||n instanceof $||n instanceof U)return n;let e=n?.name;return e==="AbortError"||e==="TimeoutError"||e==="NetworkTimeoutError"?new c("NETWORK_TIMEOUT",n instanceof Error?n.message:"timeout",{kind:"network"}):new c("UNKNOWN_ERROR",n instanceof Error?n.message:String(n),{kind:"unknown"})}function h(n){let e=n.error?.status,t=n.error?.details?.retryAfterSeconds;return{status:typeof e=="number"?e:void 0,retryAfterSeconds:typeof t=="number"&&Number.isFinite(t)&&t>0?t:void 0}}var W=class{constructor(e,t,r,s,i,o){this.user=null;this.accessToken=null;this.accessExpiresAt=0;this.clockSkewConfirmed=!1;this.inflight=Promise.resolve();this.refreshInflight=null;this.refreshFailureCount=0;this.refreshCooldownUntil=0;this.visibilityResetUnsub=null;this.proactiveRefreshTimer=null;this.proactiveRefreshCleanup=null;this.takeoverListeners=new Set;this.lastTakeover=null;this.deletionCancelledListeners=new Set;this.lastDeletionCancelled=null;this.lastAnonRetirement=null;this.authStateListeners=new Set;this.pendingAnonTakeover=null;this.hydrated=!1;this.http=t,this.storage=r,this.analytics=s,this.flags=i,this.chatbot=o;let a=this.storage.get(_),u=this.storage.get(T),l=this.storage.get(m),g=this.storage.get(R);if(a&&(u||l))try{let v=JSON.parse(a);if(typeof v.id!="string"||v.id.length===0)throw new Error("invalid cache");this.user=v,u?(this.accessToken=u,this.accessExpiresAt=g?Number(g):0):(this.accessToken=null,this.accessExpiresAt=0),this.analytics.identify(this.user.id)}catch{this.storage.remove(_),this.storage.remove(T),this.storage.remove(R)}this.hydrated=!0}getCurrentUser(){return this.user}onDeviceTakeover(e){return this.takeoverListeners.add(e),()=>{this.takeoverListeners.delete(e)}}getLastDeviceTakeover(){return this.lastTakeover}onAuthStateChanged(e){if(this.authStateListeners.add(e),this.hydrated&&this.user){let t=this.user;try{e({event:"signed_in",user:t})}catch{}}return()=>{this.authStateListeners.delete(e)}}emitAuthState(e){for(let t of this.authStateListeners)try{t(e)}catch{}}fireDeviceTakeover(e,t){if(!e||!Ye.test(e))return;let r={retiredAnonUserId:e,identifiedUserId:t,at:new Date};this.lastTakeover=r;for(let s of this.takeoverListeners)try{s(r)}catch{}this.emitAuthState({event:"device_takeover",user:this.user,retiredAnonUserId:e})}onDeletionCancelled(e){return this.deletionCancelledListeners.add(e),()=>{this.deletionCancelledListeners.delete(e)}}getLastDeletionCancelled(){return this.lastDeletionCancelled}getLastAnonRetirement(){return this.lastAnonRetirement}fireDeletionCancelled(e){let t={userId:e,at:new Date};this.lastDeletionCancelled=t;for(let r of this.deletionCancelledListeners)try{r(t)}catch{}this.emitAuthState({event:"deletion_cancelled",user:this.user})}takeoverHint(){if(this.user?.isAnonymous)return this.storage.get(m)??void 0}canServeToken(e,t,r){return!e||!t||r>=t-Ie?!1:this.clockSkewConfirmed?!0:Te(e,r)}canServeCachedToken(e){return this.canServeToken(this.accessToken,this.accessExpiresAt,e)}trackedDeadlineAlive(e){return!!this.accessToken&&!!this.accessExpiresAt&&e<this.accessExpiresAt-Ie}deadlinesDisagree(e){return this.trackedDeadlineAlive(e)&&!this.canServeCachedToken(e)}learnClockSkewFrom(e,t){Te(e,t)||(this.clockSkewConfirmed=!0)}async refreshAndReconcile(e){let t=this.deadlinesDisagree(e),r=await this.refreshAccessToken();return t&&r&&this.learnClockSkewFrom(r,Date.now()),r}async getAccessToken(e){return!e?.forceRefresh&&this.canServeCachedToken(Date.now())?this.accessToken:this.storage.get(m)?this.refreshInflight?this.refreshInflight:Date.now()<this.refreshCooldownUntil?null:this.refreshAndReconcile(Date.now()):null}getAccessTokenSync(){return this.accessToken}signInAnonymously(e){return this.serialize(async()=>{let t=this.user;if(!e?.forceNew&&t?.isAnonymous&&this.storage.get(m))return t;let r=await this.http.post("/auth-service/anonymous",{name:e?.name,metadata:e?.metadata});if(!r.success||!y(r.data))throw new c(r.error?.code??"AUTH_ERROR",r.error?.message??"Anonymous signup failed",h(r));return this.persist(r.data),r.data.user})}signUp(e,t,r){return this.serialize(async()=>{let s=this.storage.get(m);if(s){let o=await this.http.post("/auth-service/upgrade",{refreshToken:s,email:e,password:t,name:r?.name});if(o.success&&y(o.data))return this.persist(o.data),o.data.user;let a=o.error?.code??"",u=h(o),l=u.status;if(a==="NOT_ANONYMOUS"||a==="FORBIDDEN_NON_ANONYMOUS")throw new $(o.error?.message);if(a==="CONFLICT"||a==="EMAIL_ALREADY_TAKEN"||l===409)throw new P(o.error?.message);if(a==="INVALID_REFRESH"||a==="UNAUTHORIZED"||a==="REFRESH_EXPIRED")await this.analytics.flush(),this.wipeLocalIdentity("session_expired");else throw new c(a||"AUTH_ERROR",o.error?.message??"Upgrade failed",u)}let i=await this.http.post("/auth-service/signup",{email:e,password:t,name:r?.name,metadata:r?.metadata});if(!i.success||!y(i.data)){let o=i.error?.code??"";throw o==="CONFLICT"?new P(i.error?.message):new c(o||"AUTH_ERROR",i.error?.message??"Signup failed",h(i))}return this.persist(i.data),i.data.user})}signIn(e,t){return this.serialize(async()=>{let r=this.takeoverHint(),s=await this.http.post("/auth-service/login",{email:e,password:t,...r?{prevAnonRefreshToken:r}:{}});if(!s.success||!s.data)throw new c(s.error?.code??"AUTH_ERROR",s.error?.message??"Login failed",h(s));let i=s.data;if(i.mfaRequired===!0&&typeof i.mfaChallengeToken=="string"){r&&(this.pendingAnonTakeover={challengeToken:i.mfaChallengeToken,prevAnonRefreshToken:r});let o=i.user;return{mfaRequired:!0,mfaChallengeToken:i.mfaChallengeToken,userId:o?.id??""}}if(!y(s.data))throw new c(s.error?.code??"AUTH_ERROR",s.error?.message??"Login failed",h(s));return await this.replaceLocalIdentity(),this.persist(s.data),s.data.user})}loginSocial(e){return this.serialize(async()=>{let t=this.takeoverHint(),{link:r,onCredentialInUse:s,...i}=e,o=await this.http.post("/auth-service/login/social",{...i,...t?{prevAnonRefreshToken:t}:{},...r?{linkAnonymous:!0}:{},...s?{onCredentialInUse:s}:{}});if(!o.success||!y(o.data))throw o.error?.code==="CREDENTIAL_IN_USE"?new U(o.error.message,{...be(o),status:h(o).status}):new c(o.error?.code??"SOCIAL_LOGIN_FAILED",o.error?.message??"Social login failed",h(o));return await this.replaceLocalIdentity(),this.persist(o.data),o.data.user})}signInWithGoogle(e,t,r){return this.loginSocial({provider:"google",code:e,redirectUri:t,link:r})}signInWithGitHub(e,t){return this.loginSocial({provider:"github",code:e,redirectUri:t})}signInWithApple(e){return this.loginSocial({provider:"apple",...e})}signInWithMicrosoft(e,t){return this.loginSocial({provider:"microsoft",code:e,redirectUri:t})}signInWithLinkedIn(e,t){return this.loginSocial({provider:"linkedin",code:e,redirectUri:t})}signInWithFacebook(e,t){return this.loginSocial({provider:"facebook",code:e,redirectUri:t})}linkEmailPassword(e,t){return this.linkCredential("/auth-service/me/link/email",{email:e,password:t})}linkSocial(e){return this.linkCredential("/auth-service/me/link/social",e)}linkGoogle(e){return this.linkSocial({provider:"google",...e})}linkApple(e){return this.linkSocial({provider:"apple",...e})}async linkCredential(e,t){let r=await this.getAccessToken();if(!r)throw new c("NOT_SIGNED_IN","Sign in before linking a credential");let s=await this.http.post(e,t,{Authorization:`Bearer ${r}`});if(!s.success||!s.data?.user){let i=s.error?.code??"LINK_FAILED";throw i==="CREDENTIAL_IN_USE"?new U(s.error?.message,{...be(s),status:h(s).status}):new c(i,s.error?.message??"Failed to link credential",h(s))}return s.data.upgraded&&y(s.data)?(this.persist(s.data),s.data.user):(this.updateLocalUser(s.data.user),s.data.user)}updateLocalUser(e){this.user=e,this.storage.set(_,JSON.stringify(e))}async listLinkedIdentities(){let e=await this.getAccessToken();if(!e)throw new c("NOT_SIGNED_IN","Sign in before listing linked identities");let t=await this.http.get("/auth-service/me/identities",{Authorization:`Bearer ${e}`});if(!t.success||!t.data)throw new c(t.error?.code??"IDENTITIES_FAILED",t.error?.message??"Failed to list linked identities",h(t));return{identities:t.data.identities??[],hasPassword:!!t.data.hasPassword}}async unlink(e){let t=await this.getAccessToken();if(!t)throw new c("NOT_SIGNED_IN","Sign in before unlinking an identity");let r=await this.http.delete(`/auth-service/me/identities/${encodeURIComponent(e)}`,{Authorization:`Bearer ${t}`});if(!r.success||!r.data)throw new c(r.error?.code??"UNLINK_FAILED",r.error?.message??"Failed to unlink identity",h(r));return{provider:r.data.provider??e,removed:Number(r.data.removed??0),remaining:Number(r.data.remaining??0)}}signInWithDiscord(e,t){return this.loginSocial({provider:"discord",code:e,redirectUri:t})}challengeMfa(e,t){return this.serialize(async()=>{let s=(this.pendingAnonTakeover?.challengeToken===e?this.pendingAnonTakeover.prevAnonRefreshToken:void 0)??this.takeoverHint(),i=await this.http.post("/auth-service/mfa/challenge",{challengeToken:e,code:t,...s?{prevAnonRefreshToken:s}:{}});if(!i.success||!y(i.data))throw new c(i.error?.code??"MFA_CHALLENGE_FAILED",i.error?.message??"Invalid MFA code",h(i));return await this.replaceLocalIdentity(),this.persist(i.data),i.data.user})}async sendMagicLink(e){let t=await this.http.post("/auth-service/magic-link/request",{email:e});if(!t.success)throw new c(t.error?.code??"MAGIC_LINK_REQUEST_FAILED",t.error?.message??"Failed to send link")}async sendEmailOtp(e){let t=await this.http.post("/auth-service/email-otp/request",{email:e});if(!t.success)throw new c(t.error?.code??"EMAIL_OTP_REQUEST_FAILED",t.error?.message??"Failed to send code")}verifyEmailOtp(e,t){return this.serialize(async()=>{let r=this.takeoverHint(),s=await this.http.post("/auth-service/email-otp/verify",{email:e,code:t,...r?{prevAnonRefreshToken:r}:{}});if(!s.success||!y(s.data))throw new c(s.error?.code??"EMAIL_OTP_INVALID",s.error?.message??"Wrong or expired code",h(s));return await this.replaceLocalIdentity(),this.persist(s.data),s.data.user})}async requestPasswordReset(e){let t=await this.http.post("/auth-service/password/forgot",{email:e});if(!t.success)throw new c(t.error?.code??"PASSWORD_RESET_REQUEST_FAILED",t.error?.message??"Failed to send reset email")}async resetPassword(e,t){let r=await this.http.post("/auth-service/password/reset",{token:e,newPassword:t});if(!r.success)throw new c(r.error?.code??"PASSWORD_RESET_FAILED",r.error?.message??"Reset failed")}async verifyEmail(e){let t=await this.http.post("/auth-service/email/verify",{token:e});if(!t.success)throw new c(t.error?.code??"EMAIL_VERIFICATION_FAILED",t.error?.message??"Verification failed")}async sendVerificationEmail(){let e=await this.getAccessToken();if(!e)throw new c("UNAUTHORIZED","Sign in before requesting a verification email");let t=await this.http.post("/auth-service/email/verify/resend",{},{Authorization:`Bearer ${e}`});if(!t.success)throw new c(t.error?.code??"VERIFICATION_RESEND_FAILED",t.error?.message??"Failed to send verification email")}verifyMagicLink(e){return this.serialize(async()=>{let t=this.takeoverHint(),r=await this.http.post("/auth-service/magic-link/verify",{token:e,...t?{prevAnonRefreshToken:t}:{}});if(!r.success||!y(r.data))throw new c(r.error?.code??"MAGIC_LINK_INVALID",r.error?.message??"Invalid or expired magic link",h(r));return await this.replaceLocalIdentity(),this.persist(r.data),r.data.user})}async enrollMfa(){let e=await this.http.post("/auth-service/mfa/enroll/start",{},await this.bearerHeaders());if(!e.success||!e.data)throw new c(e.error?.code??"MFA_ENROLL_FAILED",e.error?.message??"MFA enrollment failed");return e.data}async confirmMfa(e){let t=await this.http.post("/auth-service/mfa/enroll/confirm",{code:e},await this.bearerHeaders());return!!(t.success&&t.data?.confirmed)}async disableMfa(){let e=await this.http.post("/auth-service/mfa/disable",{},await this.bearerHeaders());if(!e.success)throw new c(e.error?.code??"MFA_DISABLE_FAILED",e.error?.message??"Failed to disable MFA",h(e))}async registerPasskey(e){if(typeof navigator>"u"||!navigator.credentials)throw new c("PASSKEY_UNSUPPORTED","WebAuthn not supported in this environment");let t=await this.http.post("/auth-service/passkeys/register/start",{},await this.bearerHeaders());if(!t.success||!t.data)throw new c(t.error?.code??"PASSKEY_START_FAILED",t.error?.message??"Passkey start failed");let r=et(t.data),s;try{let a=await navigator.credentials.create({publicKey:r});if(!a)throw new Error("create returned null");s=a}catch(a){throw new c("PASSKEY_USER_CANCELLED",a instanceof Error?a.message:"User cancelled passkey registration")}let i=rt(s),o=await this.http.post("/auth-service/passkeys/register/finish",{response:i,name:e},await this.bearerHeaders());if(!o.success||!o.data)throw new c(o.error?.code??"PASSKEY_FINISH_FAILED",o.error?.message??"Passkey verification failed");return o.data}signInWithPasskey(e){return this.serialize(async()=>{if(typeof navigator>"u"||!navigator.credentials)throw new c("PASSKEY_UNSUPPORTED","WebAuthn not supported in this environment");let t=this.takeoverHint(),r=await this.http.post("/auth-service/passkeys/authenticate/start",{userId:e??null});if(!r.success||!r.data)throw new c(r.error?.code??"PASSKEY_START_FAILED",r.error?.message??"Passkey start failed",h(r));let s=tt(r.data),i;try{let u=await navigator.credentials.get({publicKey:s});if(!u)throw new Error("get returned null");i=u}catch(u){throw new c("PASSKEY_USER_CANCELLED",u instanceof Error?u.message:"User cancelled passkey signin")}let o=st(i),a=await this.http.post("/auth-service/passkeys/authenticate/finish",{response:o,userId:e??null,...t?{prevAnonRefreshToken:t}:{}});if(!a.success||!y(a.data))throw new c(a.error?.code??"PASSKEY_AUTH_FAILED",a.error?.message??"Passkey signin failed",h(a));return await this.replaceLocalIdentity(),this.persist(a.data),a.data.user})}async listPasskeys(){let e=await this.http.get("/auth-service/passkeys",await this.bearerHeaders());return!e.success||!Array.isArray(e.data)?[]:e.data}async deletePasskey(e){let t=await this.http.delete(`/auth-service/passkeys/${encodeURIComponent(e)}`,await this.bearerHeaders());if(!t.success)throw new c(t.error?.code??"PASSKEY_DELETE_FAILED",t.error?.message??"Failed to delete passkey",h(t))}async listMySessions(){let e=await this.http.get("/auth-service/sessions/me",await this.bearerHeaders());return!e.success||!Array.isArray(e.data)?[]:e.data}async revokeSession(e){let t=await this.http.delete(`/auth-service/sessions/me/${encodeURIComponent(e)}`,await this.bearerHeaders());if(!t.success)throw new c(t.error?.code??"SESSION_REVOKE_FAILED",t.error?.message??"Failed to revoke session",h(t))}async revokeAllSessions(){let e=await this.http.delete("/auth-service/sessions/me",await this.bearerHeaders());if(!e.success)throw new c(e.error?.code??"SESSION_REVOKE_ALL_FAILED",e.error?.message??"Failed to sign out other devices",h(e))}async startSso(e){let t=this.takeoverHint(),r=await this.http.post("/auth-service/sso/oidc/start",{returnTo:e,...t?{prevAnonRefreshToken:t}:{}});if(!r.success||!r.data)throw new c(r.error?.code??"SSO_START_FAILED",r.error?.message??"SSO start failed");return r.data}async signInWithSso(e){let t=e??(typeof window<"u"?window.location.origin:"");if(!t)throw new c("SSO_NO_RETURN_TO","returnTo required outside browser context");let r=await this.startSso(t);typeof window<"u"&&(window.location.href=r.authorizationUrl)}async startSaml(e){let t=this.takeoverHint(),r=await this.http.post("/auth-service/sso/saml/start",{returnTo:e,...t?{prevAnonRefreshToken:t}:{}});if(!r.success||!r.data)throw new c(r.error?.code??"SAML_START_FAILED",r.error?.message??"SAML start failed");return r.data}async signInWithSaml(e){let t=e??(typeof window<"u"?window.location.origin:"");if(!t)throw new c("SAML_NO_RETURN_TO","returnTo required outside browser context");let r=await this.startSaml(t);typeof window<"u"&&(window.location.href=r.authorizationUrl)}consumeSsoTokenFromUrl(){return this.serialize(async()=>{if(typeof window>"u")return null;let e=window.location.hash.replace(/^#/,"");if(!e)return null;let t=new URLSearchParams(e),r=t.get("sendora_oidc_error")??t.get("sendora_saml_error");if(r)throw window.history.replaceState(null,"",window.location.pathname+window.location.search),new c("SSO_FAILED",decodeURIComponent(r));let s=t.get("sendora_oidc_token")??t.get("sendora_saml_token");if(!s)return null;let i=t.get("sendora_retired_anon");window.history.replaceState(null,"",window.location.pathname+window.location.search);let o=await this.http.post("/auth-service/token/refresh",{refreshToken:s}),a=o.success?Ee(o.data):null;if(!a)throw new c(o.error?.code??"SSO_EXCHANGE_FAILED",o.error?.message??"Could not exchange SSO token",h(o));let u={...a,tokenType:"Bearer"};await this.replaceLocalIdentity(),this.accessToken=u.accessToken,this.accessExpiresAt=Date.now()+u.expiresIn*1e3,this.storage.set(T,u.accessToken),this.storage.set(R,String(this.accessExpiresAt)),this.storage.set(m,u.refreshToken);let l=Re(u.accessToken),g={id:l?.sub??"",email:l?.email??null,emailVerified:l?.email_verified??!0,name:l?.name??null,isAnonymous:!1};return this.user=g,this.storage.set(_,JSON.stringify(g)),this.analytics.identify(g.id),this.flags.setContext({userId:g.id}),this.emitAuthState({event:"signed_in",user:g}),i&&this.fireDeviceTakeover(i,g.id),g})}async bearerHeaders(){let e=await this.getAccessToken();if(!e)throw new c("NOT_SIGNED_IN","Not signed in");return{Authorization:`Bearer ${e}`}}signOut(){return this.serialize(async()=>{let e=this.storage.get(m);this.wipeLocalIdentity("user"),e&&this.http.post("/auth-service/token/revoke",{refreshToken:e}).catch(()=>{})})}serialize(e){let t=async()=>{try{return await e()}catch(s){throw Je(s)}},r=this.inflight.then(t,t);return this.inflight=r.catch(()=>{}),r}async refreshAccessToken(){if(this.refreshInflight)return this.refreshInflight;let e=this.storage.get(m);if(!e)return null;let t=typeof navigator<"u"&&"locks"in navigator,r=async()=>{let s=this.storage.get(m);if(s&&s!==e){let i=this.storage.get(T),o=this.storage.get(R);if(i&&o){let a=Number(o);if(Number.isFinite(a)&&this.canServeToken(i,a,Date.now()))return this.accessToken=i,this.accessExpiresAt=a,i}}try{let i=s??e,o=await this.http.post("/auth-service/token/refresh",{refreshToken:i});if(!o.success)return Ze(o.error?.code)&&this.tokenStillCurrent(i)?(this.wipeLocalIdentity("session_expired"),this.refreshFailureCount=0,this.refreshCooldownUntil=0,null):(this.armBackoff(),null);let a=Ee(o.data);if(!a)return this.armBackoff(),null;if(!this.tokenStillCurrent(i))return null;if(this.accessToken=a.accessToken,this.accessExpiresAt=Date.now()+a.expiresIn*1e3,this.storage.set(T,a.accessToken),this.storage.set(R,String(this.accessExpiresAt)),this.storage.set(m,a.refreshToken),this.user===null){let u=nt(o.data);u&&(this.user=u,this.storage.set(_,JSON.stringify(u)),this.analytics.identify(u.id),this.emitAuthState({event:"signed_in",user:u}))}return this.refreshFailureCount=0,this.refreshCooldownUntil=0,a.accessToken}catch{return this.armBackoff(),null}};return this.refreshInflight=(async()=>{try{return t?await navigator.locks.request("sendora-authservice-refresh",{mode:"exclusive"},r):await r()}finally{this.refreshInflight=null}})(),this.refreshInflight}armBackoff(){this.refreshFailureCount+=1;let e=Math.min(3e4,1e3*Math.pow(2,this.refreshFailureCount-1));this.refreshCooldownUntil=Date.now()+e}resetRefreshState(){this.refreshFailureCount=0,this.refreshCooldownUntil=0}startVisibilityRefreshReset(){if(this.visibilityResetUnsub||typeof document>"u")return;let e=()=>{document.visibilityState==="visible"&&this.resetRefreshState()};document.addEventListener("visibilitychange",e),this.visibilityResetUnsub=()=>document.removeEventListener("visibilitychange",e)}stopVisibilityRefreshReset(){this.visibilityResetUnsub&&(this.visibilityResetUnsub(),this.visibilityResetUnsub=null)}startProactiveRefreshCron(){if(typeof window>"u"||this.proactiveRefreshTimer)return;let e=.8,t=6e4,r=3e4,s=async()=>{if(!this.accessToken||!this.accessExpiresAt)return;let o=Date.now();if(!this.canServeCachedToken(o)){await this.refreshAndReconcile(o);return}let a=this.accessExpiresAt-o;if(a<=0)return;let l=Math.max(a,5*6e4)*(1-e)+(Math.random()*r*2-r);a<=l&&await this.refreshAccessToken()};this.proactiveRefreshTimer=window.setInterval(()=>{s()},t);let i=()=>{document.visibilityState==="visible"&&s()};document.addEventListener("visibilitychange",i),this.proactiveRefreshCleanup=()=>{this.proactiveRefreshTimer&&(window.clearInterval(this.proactiveRefreshTimer),this.proactiveRefreshTimer=null),document.removeEventListener("visibilitychange",i)}}stopProactiveRefreshCron(){this.proactiveRefreshCleanup&&(this.proactiveRefreshCleanup(),this.proactiveRefreshCleanup=null)}persist(e){this.user=e.user,this.accessToken=e.tokens.accessToken,this.accessExpiresAt=Date.now()+e.tokens.expiresIn*1e3,this.storage.set(_,JSON.stringify(e.user)),this.storage.set(T,e.tokens.accessToken),this.storage.set(R,String(this.accessExpiresAt)),this.storage.set(m,e.tokens.refreshToken),this.analytics.identify(e.user.id),this.flags.setContext({userId:e.user.id}),this.startProactiveRefreshCron(),this.startVisibilityRefreshReset(),this.emitAuthState({event:"signed_in",user:e.user}),e.retiredAnonUserId&&this.fireDeviceTakeover(e.retiredAnonUserId,e.user.id),e.anonRetirement&&(this.lastAnonRetirement=e.anonRetirement),e.reactivatedFromDeletion&&this.fireDeletionCancelled(e.user.id)}async replaceLocalIdentity(){this.user!==null&&(await this.analytics.flush(),this.wipeLocalIdentity("replaced"))}tokenStillCurrent(e){return this.storage.get(m)===e}wipeLocalIdentity(e="replaced"){this.user=null,this.accessToken=null,this.accessExpiresAt=0,this.clockSkewConfirmed=!1,this.lastTakeover=null,this.lastDeletionCancelled=null,this.lastAnonRetirement=null,this.pendingAnonTakeover=null,this.storage.remove(_),this.storage.remove(T),this.storage.remove(R),this.storage.remove(m),this.analytics.reset(e==="user"||e==="account_deleted"),this.analytics.dropQueue(),this.flags.reset(),this.chatbot.newSession(),this.stopProactiveRefreshCron(),this.stopVisibilityRefreshReset(),this.refreshFailureCount=0,this.refreshCooldownUntil=0,e!=="replaced"&&this.emitAuthState({event:"signed_out",user:null,reason:e})}};function Ze(n){return n?n==="INVALID_REFRESH_TOKEN":!1}function V(n){let e=(4-n.length%4)%4,t=(n+"===".slice(0,e)).replace(/-/g,"+").replace(/_/g,"/"),r=atob(t),s=new ArrayBuffer(r.length),i=new Uint8Array(s);for(let o=0;o<r.length;o++)i[o]=r.charCodeAt(o);return s}function I(n){let e=n instanceof Uint8Array?n:new Uint8Array(n),t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function et(n){return{challenge:V(n.challenge),rp:n.rp,user:{id:V(n.user.id),name:n.user.name,displayName:n.user.displayName},pubKeyCredParams:n.pubKeyCredParams,timeout:n.timeout,attestation:n.attestation,excludeCredentials:n.excludeCredentials?.map(e=>({id:V(e.id),type:"public-key",transports:e.transports})),authenticatorSelection:n.authenticatorSelection}}function tt(n){return{challenge:V(n.challenge),timeout:n.timeout,rpId:n.rpId,allowCredentials:n.allowCredentials?.map(e=>({id:V(e.id),type:"public-key",transports:e.transports})),userVerification:n.userVerification}}function rt(n){let e=n.response;return{id:n.id,rawId:I(n.rawId),type:n.type,response:{clientDataJSON:I(e.clientDataJSON),attestationObject:I(e.attestationObject),transports:typeof e.getTransports=="function"?e.getTransports():void 0},clientExtensionResults:n.getClientExtensionResults()}}function Ee(n){if(!n||typeof n!="object")return null;let e=n.tokens,t=e&&typeof e=="object"?e:n;return typeof t.accessToken!="string"||!t.accessToken||typeof t.refreshToken!="string"||!t.refreshToken||typeof t.expiresIn!="number"||t.expiresIn<=0?null:{accessToken:t.accessToken,refreshToken:t.refreshToken,expiresIn:t.expiresIn}}function nt(n){if(!n||typeof n!="object")return null;let e=n.user;if(!e||typeof e!="object")return null;let t=e.id;return typeof t!="string"||t.length===0?null:e}function Te(n,e){let t=Re(n);if(!t)return!0;let r=t.exp;return typeof r!="number"||!Number.isFinite(r)?!0:e<r*1e3}function Re(n){try{let e=n.split(".");if(e.length!==3)return null;let t=e[1].replace(/-/g,"+").replace(/_/g,"/"),r=atob(t+"===".slice(0,(4-t.length%4)%4));return JSON.parse(r)}catch{return null}}function st(n){let e=n.response;return{id:n.id,rawId:I(n.rawId),type:n.type,response:{clientDataJSON:I(e.clientDataJSON),authenticatorData:I(e.authenticatorData),signature:I(e.signature),userHandle:e.userHandle?I(e.userHandle):null},clientExtensionResults:n.getClientExtensionResults()}}function it(n){return n===!1?{pageViews:!1,sessionStart:!1,appOpen:!1,appBackground:!1,engagement:!1}:n===!0||n===void 0?{pageViews:!0,sessionStart:!0,appOpen:!0,appBackground:!0,engagement:!0}:{pageViews:n.pageViews??!0,sessionStart:n.sessionStart??!0,appOpen:n.appOpen??!0,appBackground:n.appBackground??!0,engagement:n.engagement??!0}}var ot=250,_e=360*60*1e3;function Le(n,e){if(typeof window>"u")return()=>{};let t=it(e.autoTrack),r=e.sessionIdleMs??18e5,s=[],i="sendora_session_id",o="sendora_session_last_activity";function a(){return Ce(i)??""}function u(d){De(i,d)}function l(){let d=Ce(o);return d&&Number(d)||0}function g(d){De(o,String(d))}function v(){return`sess_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`}function w(d){let S=Date.now(),N=l();if(!a()||N&&S-N>r){let G=v();u(G),d&&t.sessionStart&&n.track("session.start",{sessionId:G})}g(S)}w(t.sessionStart),t.appOpen&&n.track("app.opened",{sessionId:a()||void 0,url:window.location.origin+window.location.pathname,referrer:document.referrer||void 0});let k=window.location.pathname,C=0,A=document.visibilityState==="visible"?Date.now():0;function te(){A>0&&(C+=Date.now()-A,A=0)}function j(){if(!t.engagement)return;te();let d=C;if(C=0,!(d<ot)){d>_e&&(d=_e);try{n.track("app.engagement",{durationMs:Math.round(d),screen:k,sessionId:a()||void 0})}catch{}}}function Pe(d){k=d,C=0,A=document.visibilityState==="visible"?Date.now():0}if(t.pageViews||t.engagement){t.pageViews&&n.page();let d=()=>{j(),w(!0),t.pageViews&&n.page(),Pe(window.location.pathname)},S=()=>d();window.addEventListener("popstate",S),s.push(()=>window.removeEventListener("popstate",S));let N=window;if(!N.__sendoraHistoryPatched){N.__sendoraHistoryPatched=!0;let G=history.pushState,Ue=history.replaceState;history.pushState=function(...ne){let se=G.apply(this,ne);return window.dispatchEvent(new Event("sendora:locationchange")),se},history.replaceState=function(...ne){let se=Ue.apply(this,ne);return window.dispatchEvent(new Event("sendora:locationchange")),se}}let re=()=>d();window.addEventListener("sendora:locationchange",re),s.push(()=>window.removeEventListener("sendora:locationchange",re))}if(t.appBackground||t.engagement){let d=()=>{if(document.visibilityState==="hidden"){j(),t.appBackground&&(w(!0),n.track("app.backgrounded",{sessionId:a()||void 0}));try{n.flush()}catch{}}else document.visibilityState==="visible"&&(t.appBackground&&(w(!0),n.track("app.foregrounded",{sessionId:a()||void 0})),t.engagement&&A===0&&(A=Date.now()))};if(document.addEventListener("visibilitychange",d),s.push(()=>document.removeEventListener("visibilitychange",d)),t.engagement){let S=()=>{j();try{n.flush()}catch{}};window.addEventListener("pagehide",S),s.push(()=>window.removeEventListener("pagehide",S))}}let he=0,D=()=>{let d=Date.now();d-he<5e3||(he=d,w(!0))};return window.addEventListener("click",D,{passive:!0}),window.addEventListener("keydown",D,{passive:!0}),window.addEventListener("scroll",D,{passive:!0}),s.push(()=>{window.removeEventListener("click",D),window.removeEventListener("keydown",D),window.removeEventListener("scroll",D)}),()=>{j();for(let d of s)try{d()}catch{}}}function Ce(n){try{return window.sessionStorage?.getItem(n)??null}catch{return null}}function De(n,e){try{window.sessionStorage?.setItem(n,e)}catch{}}var B=class n{constructor(e){this.http=e}static isSupported(){return typeof window>"u"?!1:"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window}static permission(){return typeof Notification>"u"?"denied":Notification.permission}async subscribe(e){if(!n.isSupported())throw new Error("[sendoracloud] Web Push not supported in this browser.");let t=Notification.permission;if(t==="default"&&(t=await Notification.requestPermission()),t!=="granted")throw new Error(`[sendoracloud] Notification permission ${t}.`);let r=await navigator.serviceWorker.getRegistration(e.scope??"/");r||(r=await navigator.serviceWorker.register(e.serviceWorkerPath,{scope:e.scope??"/"})),await navigator.serviceWorker.ready;let i=(await this.http.get("/push/vapid"))?.data?.publicKey;if(!i)throw new Error("[sendoracloud] backend returned no VAPID public key.");let a=await r.pushManager.getSubscription()??await r.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:at(i)}),u=a.toJSON(),l=u.endpoint,g=u.keys?.p256dh??"",v=u.keys?.auth??"",w=await ct(l),k=await this.http.post("/push/tokens",{platform:"web",token:w,webEndpoint:l,webP256dh:g,webAuth:v,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,locale:typeof navigator<"u"?navigator.language:void 0,timezone:Intl?.DateTimeFormat?.().resolvedOptions?.().timeZone,...e.userId?{userId:e.userId}:{}});if(!k?.data?.tokenId)throw new Error("[sendoracloud] backend returned no tokenId on subscribe.");return{tokenId:k.data.tokenId,subscription:a}}async unsubscribe(e="/"){if(!n.isSupported())return!1;let t=await navigator.serviceWorker.getRegistration(e);if(!t)return!1;let r=await t.pushManager.getSubscription();return r?await r.unsubscribe():!1}async trackOpen(e,t){let r={sendId:e};t!==void 0&&(r.clickAction=t);let s=await this.http.post("/push/track-open",r);if(!s.success)throw new Error(s.error?.message??"push.trackOpen failed")}};function at(n){let e="=".repeat((4-n.length%4)%4),t=(n+e).replace(/-/g,"+").replace(/_/g,"/"),r=atob(t),s=new Uint8Array(r.length);for(let i=0;i<r.length;i++)s[i]=r.charCodeAt(i);return s}async function ct(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}var q=class{constructor(e){}unsupported(){throw new Error("[SendoraCloud] sendora.audiences is not available in the browser SDK. Audiences require a secret (sk_*) key with the audiences:read/write scopes and must be managed from a trusted server, not the browser.")}list(){return this.unsupported()}get(e){return this.unsupported()}create(e){return this.unsupported()}update(e,t){return this.unsupported()}delete(e){return this.unsupported()}};var p=class extends Error{constructor(e,t,r){super(t),this.name="LinkError",this.code=e,this.statusCode=r}};function ue(n,e){let t=(n??"").toUpperCase();return t==="NOT_FOUND"?new p("NOT_FOUND",e):t==="FORBIDDEN"||t==="UNAUTHORIZED"?new p("UNAUTHORIZED",e):t==="RATE_LIMITED"?new p("RATE_LIMITED",e):t==="ENTITLEMENT_ERROR"||/plan limit/i.test(e)?new p("PLAN_LIMIT",e):t==="VALIDATION_ERROR"?/iOS bundle|Android package/i.test(e)?new p("BUNDLE_MISMATCH",e):/2KB|10KB|linkData/i.test(e)?new p("DATA_TOO_LARGE",e):/fallbackUrl/i.test(e)&&/apps/i.test(e)?new p("FALLBACK_REQUIRED",e):new p("INVALID_INPUT",e):t==="PARSE_ERROR"||t==="HTTP_ERROR"||/HTTP \d{3}/.test(e)?new p("NETWORK",e):new p("UNKNOWN",e||`Unknown LinkError (code=${n??"none"})`)}var le=/^[a-z0-9-]{3,20}$/;function ut(n){try{let t=new URL(n).pathname.split("/").filter(Boolean);if(t.length===0)return null;let r=t[t.length-1];return le.test(r)?r:null}catch{return null}}var lt=5*6e4,dt=50,ht=5,z=class{constructor(e){this.http=e;this.prewarmCache=new Map;this.prewarmInflight=0}cacheKey(e,t){if(t)return`k:${t}`;let r={},s=e;for(let i of Object.keys(s).sort())r[i]=s[i];return`s:${JSON.stringify(r)}`}evictExpired(){let e=Date.now();for(let[t,r]of this.prewarmCache)e-r.ts>lt&&this.prewarmCache.delete(t);for(;this.prewarmCache.size>dt;){let t=this.prewarmCache.keys().next().value;if(t===void 0)break;this.prewarmCache.delete(t)}}prewarm(e,t){this.evictExpired();let r=this.cacheKey(e,t?.key);if(this.prewarmCache.has(r)||this.prewarmInflight>=ht)return;this.prewarmInflight++;let s=this.doCreate(e).catch(i=>{throw this.prewarmCache.delete(r),i}).finally(()=>{this.prewarmInflight--});this.prewarmCache.set(r,{promise:s,ts:Date.now()})}async create(e,t){if(!e.title)throw new p("INVALID_INPUT","links.create: title is required");this.evictExpired();let r=this.cacheKey(e,t?.key),s=this.prewarmCache.get(r);return s?(this.prewarmCache.delete(r),s.promise):this.doCreate(e)}async doCreate(e){let t={title:e.title};e.fallbackUrl&&(t.fallbackUrl=e.fallbackUrl),e.iosDeepLinkPath&&(t.iosDeepLinkPath=e.iosDeepLinkPath),e.androidDeepLinkPath&&(t.androidDeepLinkPath=e.androidDeepLinkPath),e.linkData&&(t.linkData=e.linkData),e.ogTitle&&(t.ogTitle=e.ogTitle),e.ogDescription&&(t.ogDescription=e.ogDescription),e.ogImageUrl&&(t.ogImageUrl=e.ogImageUrl),e.campaign&&(t.campaign=e.campaign),e.source&&(t.source=e.source),e.medium&&(t.medium=e.medium),e.channel&&(t.channel=e.channel),e.tags&&(t.tags=e.tags),e.expiresAt&&(t.expiresAt=e.expiresAt),e.iosBundleId&&(t.iosBundleId=e.iosBundleId),e.androidPackageName&&(t.androidPackageName=e.androidPackageName);let r=await this.http.post("/sdk/links",t);if(!r.success||!r.data)throw ue(r.error?.code,r.error?.message??"links.create failed");return r.data}async revoke(e){if(!le.test(e))throw new p("INVALID_INPUT",`links.revoke: '${e}' is not a valid shortcode`);let t=await this.http.post(`/sdk/links/${encodeURIComponent(e)}/revoke`,{});if(!t.success||!t.data)throw ue(t.error?.code,t.error?.message??"links.revoke failed");return{shortcode:t.data.shortcode,revoked:!0}}async getStats(e){if(!le.test(e))throw new p("INVALID_INPUT",`links.getStats: '${e}' is not a valid shortcode`);let t=await this.http.get(`/sdk/links/${encodeURIComponent(e)}/stats`);if(!t.success||!t.data)throw ue(t.error?.code,t.error?.message??"links.getStats failed");return t.data}};var Q=class{constructor(e){this.http=e}async reportInstall(e={}){let t=await this.http.post("/attribution/install",e);if(!t.success||!t.data)throw new Error(t.error?.message??"attribution.reportInstall failed");return t.data}async checkDeferred(e={}){let t=await this.http.post("/attribution/deferred",e);if(!t.success)throw new Error(t.error?.message??"attribution.checkDeferred failed");return t.data??null}};var J=class{constructor(e){this.http=e}async createTicket(e){let t=await this.http.post("/support/tickets",e);if(!t.success||!t.data)throw new Error(t.error?.message??"support.createTicket failed");return t.data}async submitCsat(e){let t=await this.http.post("/support/csat",e);if(!t.success||!t.data)throw new Error(t.error?.message??"support.submitCsat failed");return t.data}};var Z=class{constructor(e){this.http=e}async search(e){if(!e.query||e.query.trim().length===0)return[];let t=new URLSearchParams({query:e.query});e.limit&&t.set("limit",String(e.limit));let r=await this.http.get(`/kb/search?${t.toString()}`);if(!r.success||!Array.isArray(r.data))throw new Error(r.error?.message??"kb.search failed");return r.data}};var pt=/^[A-Za-z0-9_.-]{1,64}$/;function gt(n){if(n!==void 0){if(typeof n!="string"||!pt.test(n))throw new Error(`[sendora] init: storagePrefix must be 1-64 chars of A-Z a-z 0-9 _ . - (got ${JSON.stringify(n)}). Changing it signs the browser out, so it is validated rather than ignored.`);return n}}var ee=class ee{constructor(e){this.autoTrackCleanup=null;this.http=new Y(e),this.storage=new X(gt(e.storagePrefix),e.tokenStore==="memory"),this.consent=new K(e.defaultConsent===!0,this.http),this.analytics=new x(e,this.http,this.storage,this.consent),this.flags=new O(e,this.http,this.storage),this.surveys=new M(e,this.http,this.storage),this.messages=new F(e,this.http,this.storage),this.chatbot=new H(e,this.http,this.storage),this.auth=new W(e,this.http,this.storage,this.analytics,this.flags,this.chatbot),this.webPush=new B(this.http),this.audiences=new q(this.http),this.links=new z(this.http),this.attribution=new Q(this.http),this.support=new J(this.http),this.kb=new Z(this.http),e.autoTrack!==!1&&(this.autoTrackCleanup=Le(this.analytics,e))}static init(e){return ve(e.apiKey),new ee(e)}static sanitizeHtml(e){return ce(e)}static safeUrl(e){return E(e)}track(e,t){this.analytics.track(e,t)}page(e){this.analytics.page(e)}identify(e,t,r){this.analytics.identify(e,t,r),this.flags.setContext({userId:e})}reset(){this.analytics.reset(),this.flags.reset(),this.chatbot.newSession()}async flush(){await this.analytics.flush()}destroy(){this.autoTrackCleanup&&(this.autoTrackCleanup(),this.autoTrackCleanup=null),this.analytics.destroy(),this.flags.destroy(),this.messages.destroy()}};ee.version=b;var de=ee,ur=de;export{$ as AlreadyIdentifiedError,x as Analytics,q as Audiences,W as Auth,c as AuthError,H as Chatbot,K as Consent,U as CredentialInUseError,P as EmailAlreadyTakenError,O as FeatureFlags,F as InAppMessaging,p as LinkError,z as Links,de as SendoraCloud,M as Surveys,f as ValidationError,B as WebPush,ur as default,ut as extractShortcodeFromUrl,E as safeUrl,ce as sanitizeHtml};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sendoracloud/sdk-web",
3
- "version": "3.20.0",
3
+ "version": "3.22.0",
4
4
  "description": "Sendora Cloud Web SDK — analytics, feature flags, surveys, in-app messaging, chatbot, auth, deep links (Branch / Firebase parity). Zero dependencies, TypeScript, SSR-safe.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",