@sparkvault/sdk-js 19.1.0 → 19.1.1
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/npm/chunks/{index-CgR08uMG.mjs → index-C97091lF.mjs} +3 -4
- package/dist/npm/chunks/index-C97091lF.mjs.map +1 -0
- package/dist/npm/chunks/{index-BnP-2w0t.cjs → index-D_p_8VO7.cjs} +3 -4
- package/dist/npm/chunks/index-D_p_8VO7.cjs.map +1 -0
- package/dist/npm/identity.cjs +2 -2
- package/dist/npm/identity.mjs +3 -3
- package/dist/npm/index.cjs +5 -6
- package/dist/npm/index.cjs.map +1 -1
- package/dist/npm/index.mjs +6 -7
- package/dist/npm/index.mjs.map +1 -1
- package/dist/sparkvault-identity.js +1 -1
- package/dist/sparkvault-identity.js.map +1 -1
- package/dist/sparkvault.js +1 -1
- package/dist/sparkvault.js.map +1 -1
- package/package.json +1 -1
- package/dist/npm/chunks/index-BnP-2w0t.cjs.map +0 -1
- package/dist/npm/chunks/index-CgR08uMG.mjs.map +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).SparkVaultIdentity={})}(this,function(e){"use strict";const t=Object.freeze({UPLOAD_CONTRACT_MISMATCH:"UPLOAD_CONTRACT_MISMATCH",UPLOAD_PROTOCOL_RETIRED:"UPLOAD_PROTOCOL_RETIRED",UPLOAD_SUPERSEDED:"UPLOAD_SUPERSEDED",UPLOAD_POOL_FULL:"UPLOAD_POOL_FULL"});Object.freeze([t.UPLOAD_POOL_FULL,t.UPLOAD_SUPERSEDED]);const n=Object.freeze({status:"revoked",reasons:Object.freeze({UPLOAD_SUPERSEDED:t.UPLOAD_SUPERSEDED,INGOT_DELETED:"INGOT_DELETED"})});Object.values(n.reasons);const i=Object.freeze({OK:"ok",RETRY:"retry",RESYNC:"resync",DEFERRED:"deferred",GONE:"gone",REFUSED:"refused"});new Set([i.RETRY,i.RESYNC]);function s(e,t=Date.now()){const n=function(e){if("string"!=typeof e)return null;const t=e.trim();if(!/^\d+$/.test(t))return null;const n=Number(t);return Number.isSafeInteger(n)?n:null}(e);if(null!==n){const e=1e3*n;return Number.isSafeInteger(e)?e:null}const i="string"==typeof e?function(e,t){let n=d.exec(e);if(n){const[,e,t,i,s,r,o]=n;return u(Number(i),t,Number(e),s,r,o)}if(n=c.exec(e),n){const[,e,i,s,r,o,a]=n;return u(function(e,t){const n=new Date(t).getUTCFullYear(),i=n-n%100+e;return i>n+50?i-100:i}(Number(s),t),i,Number(e),r,o,a)}if(n=h.exec(e),n){const[,e,t,i,s,r,o]=n;return u(Number(o),e,Number(t.trim()),i,s,r)}return null}(e.trim(),t):null;return null===i?null:Math.max(0,i-t)}const r=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],o="(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)",a=`(${r.join("|")})`,l="(\\d{2}):(\\d{2}):(\\d{2})",d=new RegExp(`^${o}, (\\d{2}) ${a} (\\d{4}) ${l} GMT$`),c=new RegExp(`^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\\d{2})-${a}-(\\d{2}) ${l} GMT$`),h=new RegExp(`^${o} ${a} ( \\d|\\d{2}) ${l} (\\d{4})$`);function u(e,t,n,i,s,o){const a=r.indexOf(t),[l,d,c]=[Number(i),Number(s),Number(o)];if(l>23||d>59||c>60)return null;const h=new Date(0);return h.setUTCFullYear(e,a,n),h.getUTCFullYear()!==e||h.getUTCMonth()!==a||h.getUTCDate()!==n?null:h.getTime()+1e3*(60*(60*l+d)+c)}class p extends Error{constructor(e,t,n,i,s=null,r){super(e),this.name="SparkVaultError",this.code=t,this.statusCode=n,this.details=i,this.retryAfterMs=s,this.serviceCode=r,Object.setPrototypeOf(this,p.prototype)}}class m extends p{constructor(e,t,n=null,i){super(e,"validation_error",400,t,n,i),this.name="ValidationError",Object.setPrototypeOf(this,m.prototype)}}class f extends p{constructor(e="Request timed out"){super(e,"timeout_error"),this.name="TimeoutError",Object.setPrototypeOf(this,f.prototype)}}class v extends p{constructor(e="User cancelled the operation"){super(e,"user_cancelled"),this.name="UserCancelledError",Object.setPrototypeOf(this,v.prototype)}}class g extends p{constructor(e){super("The identity provider could not complete the sign-in.",e||"identity_provider_error"),this.name="IdentityProviderError",Object.setPrototypeOf(this,g.prototype)}}class y extends p{constructor(){super("Popup was blocked. Please allow popups for this site.","popup_blocked"),this.name="PopupBlockedError",Object.setPrototypeOf(this,y.prototype)}}class b extends p{constructor(e="The sign-in window could not communicate with this page."){super(e,"popup_severed"),this.name="PopupSeveredError",Object.setPrototypeOf(this,b.prototype)}}function k(e){return"string"==typeof e&&e?e:null}function w(e){return"object"!=typeof e||null===e||Array.isArray(e)?void 0:e}async function x(e){return function(e,t,n){const i=w(t)??{},r=w(i.error);return{status:e,message:k(r?.message)??k(i.message)??k(i.error)??"Request failed",code:k(r?.code)??k(i.code)??"api_error",details:w(r?.details)??w(i.details),retryAfterMs:s(n("Retry-After"))}}(e.status,await e.json().catch(()=>null),t=>e.headers.get(t))}const C=Object.freeze({account:"acc",attachment:"hda",folder:"fld",helpDeskJob:"hdj",knowledgeBaseArticle:"hdkba",knowledgeBaseCategory:"hdkbc",knowledgeBaseRevision:"hdkbr",knowledgeBaseAsset:"hdkbm",knowledgeBaseFaq:"hdkbq",ingot:"ing",invite:"inv",notification:"ntf",notifyProject:"ntp",requester:"hrq",routingRule:"hdr",savedReply:"hds",spark:"spk",team:"team",ticket:"tkt",ticketEvent:"hdev",user:"usr",vault:"vlt"});function S(e){if(!Object.hasOwn(C,e))throw new TypeError(`No resource kind '${e}'`);return`^${C[e]}_[A-Za-z0-9_-]+$`}const E=Object.freeze(Object.fromEntries(Object.keys(C).map(e=>[e,new RegExp(S(e))])));Object.freeze(Object.keys(C));const T="auth.sv",A=Object.freeze([T,"x.sv","files.sv","file.sv","spark.sv","by.sv","at.sv","db.sv"]);function L(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const I=Object.freeze([new RegExp(`(^|\\.)${L("sparkvault.com")}$`,"i"),new RegExp(`^(${A.map(L).join("|")})$`,"i")]),R=`https://${T}`;function B(e){const t=e.replace(/\/+$/,"");return t.endsWith("/v1")?t.slice(0,-3):t}function _(e){return e.replace(/\/+$/,"")}function P(e){if(!e.accountId)throw new m("accountId is required",{field:"accountId"});if("string"!=typeof e.accountId)throw new m("accountId must be a string",{field:"accountId",received:typeof e.accountId});if(!function(e,t){if(!Object.hasOwn(C,e))throw new TypeError(`No resource kind '${e}'`);return"string"==typeof t&&t.length<=128&&E[e].test(t)}("account",e.accountId))throw new m("accountId must be a SparkVault account id (acc_...)",{field:"accountId",received:e.accountId})}async function $(e){try{return await e.json()}catch(e){if(e instanceof SyntaxError)return null;throw e}}async function O(e,t,n){const{timeoutMs:i,closeSignal:s,read:r,fail:o}=n;if(s?.aborted)throw o("cancelled",null);const{signal:a,dispose:l}=function(e,t){const n=new AbortController,i=setTimeout(()=>n.abort(),e);let s=n.signal,r=null;return t&&"any"in AbortSignal?s=AbortSignal.any([n.signal,t]):t&&(r=()=>n.abort(),t.addEventListener("abort",r)),{signal:s,dispose:()=>{clearTimeout(i),t&&r&&t.removeEventListener("abort",r)}}}(i,s);try{return await r(await fetch(e,{...t,signal:a}))}catch(e){if(e instanceof p)throw e;if(function(e){return null!=e&&"object"==typeof e&&"name"in e&&"AbortError"===e.name}(e))throw o(s?.aborted?"cancelled":"timeout",e);if(e instanceof TypeError)throw o("network",e);throw o("unknown",e)}finally{l()}}class M{constructor(e=3e4){this.closeController=new AbortController,this.timeoutMs=e}abort(){this.closeController.abort()}isAborted(){return this.closeController.signal.aborted}getAbortSignal(){return this.closeController.signal}resetSession(){this.closeController=new AbortController}send(e,t,n,i,s=this.timeoutMs){return O(e,t,{timeoutMs:s,closeSignal:this.closeController.signal,read:i,fail:(e,t)=>{switch(e){case"cancelled":return this.makeError(n.cancelled,"cancelled",0);case"timeout":return this.makeError(n.timeout,"timeout",0);case"network":return this.makeError(n.network,"network_error",0);default:return this.makeError(t instanceof Error?t.message:"An unexpected error occurred","unknown_error",0)}}})}rawRequest(e,t){const n={Accept:"application/json"};return void 0!==t.body&&(n["Content-Type"]="application/json"),t.headers&&Object.assign(n,t.headers),this.send(e,{method:t.method,headers:n,body:t.body},{cancelled:"Request cancelled",timeout:`Request timed out after ${this.timeoutMs}ms`,network:"Unable to connect. Please check your connection and try again."},async e=>{if(!e.ok){const{status:t,message:n,code:i,details:s,retryAfterMs:r}=await x(e);throw this.makeError(n,i,t,s,r)}return t.onResponse?.(e),{data:await $(e),status:e.status}})}}function N(e){if("string"!=typeof e||""===e||"."===e||".."===e)return null;try{return encodeURIComponent(e)}catch{return null}}function H(e,t){const n=new Uint8Array(64),i=new Int8Array(128).fill(-1);for(let t=0;t<64;t+=1)n[t]=e.charCodeAt(t),i[n[t]]=t;return{codes:n,values:i,padded:t}}H("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",!0);const F=H("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",!1);function D(e){return 9===e||10===e||12===e||13===e||32===e}function V(e){return ArrayBuffer.isView(e)&&"[object Uint8Array]"===Object.prototype.toString.call(e)}function z(e,t){if(!V(e))throw new TypeError("Base64 encoding takes a Uint8Array");const{codes:n}=t,i=e.length%3,s=e.length-i;let r=0;i>0&&(r=t.padded?4:i+1);const o=new Uint8Array(s/3*4+r);let a=0;for(let t=0;t<s;t+=3){const i=e[t]<<16|e[t+1]<<8|e[t+2];o[a++]=n[i>>18],o[a++]=n[i>>12&63],o[a++]=n[i>>6&63],o[a++]=n[63&i]}if(i>0){const t=e[s]<<16|(2===i?e[s+1]<<8:0);o[a++]=n[t>>18],o[a++]=n[t>>12&63],2===i&&(o[a++]=n[t>>6&63]),o.fill(61,a)}return function(e){let t="";for(let n=0;n<e.length;n+=8192)t+=String.fromCharCode.apply(null,e.subarray(n,n+8192));return t}(o)}function U(e){return z(e,F)}function j(e,{canonical:t=!1}={}){return function(e,t,n){if("string"!=typeof e)return null;const{values:i}=t;let s=0,r=0;for(let t=0;t<e.length;t+=1){const o=e.charCodeAt(t);if(D(o)){if(n)return null}else if(61===o)r+=1;else{if(r>0||o>127||i[o]<0)return null;s+=1}}const o=s%4;if(1===o)return null;if(r>0&&(r>2||(s+r)%4!=0))return null;if(n&&r!==(t.padded?(4-o)%4:0))return null;const a=new Uint8Array(3*s>>2);let l=0,d=0,c=0;for(let t=0;t<e.length;t+=1){const n=e.charCodeAt(t);if(61===n)break;D(n)||(l=4095&(l<<6|i[n]),d+=6,d>=8&&(d-=8,a[c++]=l>>d))}return n&&l&(1<<d)-1?null:a}(e,F,t)}const W=function(e){if(!Array.isArray(e)||0===e.length)throw new TypeError("An entropy layout names at least one field");const t=new Set;let n=0;for(const[i,s]of e){if("string"!=typeof i||0===i.length||t.has(i))throw new TypeError(`Entropy layout field names must be unique non-empty strings (${String(i)})`);if(!Number.isSafeInteger(s)||s<=0)throw new TypeError(`Entropy layout field ${i} must be a positive whole number of bytes`);t.add(i),n+=s}if(n>1024)throw new TypeError(`An entropy layout of ${n} bytes exceeds one 1024-byte draw`);return Object.freeze({bytes:n,fields:Object.freeze(e.map(([e,t])=>Object.freeze([e,t])))})}([["codeVerifier",32],["state",16],["nonce",16]]);function q(e){const{codeVerifier:t,state:n,nonce:i}=function(e,t){if(!V(e)||e.length!==t.bytes)throw new TypeError(`An entropy draw for this layout is exactly ${t.bytes} bytes`);const n={};let i=0;for(const[s,r]of t.fields)n[s]=e.subarray(i,i+r),i+=r;return n}(e,W);return{codeVerifier:U(t),state:U(n),nonce:U(i)}}function K(e,t){const n=j(e?.value,{canonical:!0});if(!n||n.length!==t||e.num_bytes!==t||/[^A-Za-z0-9_-]/.test(e.value))throw new Error(`The Identity origin answered a malformed draw for ${t} bytes`);return n}W.bytes;const G=Object.freeze({redirectUri:"redirect_uri",state:"state",authRequestId:"auth_request_id",prompt:"prompt"}),Y=Object.freeze({token:"token",state:"state"}),J="federation";const X=Object.freeze({pendingTtlMs:6e5}),Z=Object.freeze({param:"signin_ref",bytes:32,drawPurpose:"signin_reference",fromOpenerParam:"signin_ref_from",fromOpenerValue:"opener",noRecoveryValue:"none",message:"sparkvault-signin-ref",retryMessage:"sparkvault-signin-ref-retry",drawDeadlineMs:2500,openerWaitMs:4e3,redirectWaitMs:500});function Q(e){return"string"==typeof e&&/^[A-Za-z0-9_-]{43}$/.test(e)}const ee=Object.freeze({param:"identity_types",values:Object.freeze(["email","phone","social","federated"]),refusalCode:"IDENTITY_TYPE_NOT_ALLOWED"});function te(e){if(!Array.isArray(e)||0===e.length||!e.every(e=>ee.values.includes(e)))throw new TypeError(`identity types must name at least one of ${ee.values.join(", ")}`);return ee.values.filter(t=>e.includes(t)).join(",")}function ne(e){if(null==e)return{ok:!0,types:null};if("string"!=typeof e)return{ok:!1};const t=e.split(",");return t.every(e=>ee.values.includes(e))&&new Set(t).size===t.length?{ok:!0,types:ee.values.filter(e=>t.includes(e))}:{ok:!1}}function ie(e,t){return null===t||t.includes(e)}function se(e,t){return null===t||function(e){return"otp_email"===e||"sparklink"===e?["email"]:"otp_sms"===e||"otp_voice"===e?["phone"]:"passkey"===e?["email","phone","social"]:e===J?["federated"]:"string"==typeof e&&e.startsWith("social_")?["social"]:"string"==typeof e&&e.startsWith("enterprise_")?["email"]:[]}(e).some(e=>ie(e,t))}const re=Object.freeze({email:"an email address",phone:"a phone number",social:"a social account",federated:"your organization's sign-in"});function oe(e){return`This sign-in accepts only ${function(e){const t=e.map(e=>re[e]);return 1===t.length?t[0]:`${t.slice(0,-1).join(", ")} or ${t[t.length-1]}`}(e)}, and none of the ways to sign in here gives one. Contact the site you came from for help.`}function ae(e,...t){const n=function(e,t){let n=e[0];for(let i=0;i<t.length;i+=1){const s=N(t[i]);if(null===s)return null;n+=s+e[i+1]}return n}(e,t);if(null===n)throw new m("A path value must be exactly one path segment",{received:t.find(e=>null===N(e))});return n}class le{constructor(e){this.intervalId=null,this.secondsRemaining=e.duration,this.onTick=e.onTick,this.onComplete=e.onComplete}start(){this.stop(),this.onTick(this.secondsRemaining),this.intervalId=setInterval(()=>{this.secondsRemaining--,this.onTick(this.secondsRemaining),this.secondsRemaining<=0&&(this.stop(),this.onComplete())},1e3)}stop(){null!==this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null)}isRunning(){return null!==this.intervalId}getRemainingSeconds(){return this.secondsRemaining}}class de{constructor(e){this.intervalId=null,Number.isFinite(e.expiresAt)?this.expiresAt=e.expiresAt:(console.warn("[ExpirationTimer] Invalid expiresAt:",e.expiresAt),this.expiresAt=0),this.onTick=e.onTick,this.onExpired=e.onExpired}calculateRemaining(){const e=Math.floor(Date.now()/1e3),t=this.expiresAt-e;return!Number.isFinite(t)||t<0?0:Math.ceil(t)}start(){this.stop();const e=this.calculateRemaining();this.onTick(e),e<=0?this.onExpired():this.intervalId=setInterval(()=>{const e=this.calculateRemaining();this.onTick(e),e<=0&&(this.stop(),this.onExpired())},1e3)}stop(){null!==this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null)}isRunning(){return null!==this.intervalId}}function ce(e){return U(new Uint8Array(e))}function he(e){if(void 0===e)return null;const t=()=>new m(`identityTypes must name at least one of ${ee.values.join(", ")}`,{field:"identityTypes",received:e});let n;try{n=te(e)}catch{throw t()}const i=ne(n);if(!i.ok||null===i.types)throw t();return i.types}function ue(e){return e?{[ee.param]:te(e)}:{}}function pe(){return`${window.location.origin}${window.location.pathname}${window.location.search}`}function me(e,t,n){const i=new URLSearchParams({origin:window.location.origin});t.email?i.set("email",t.email):t.phone&&i.set("phone",t.phone);const s=t.authContext;return s?.authRequestId?i.set("auth_request",s.authRequestId):s?.simpleMode?.sessionId&&(i.set("mode","simple"),i.set("session",s.simpleMode.sessionId)),"select_account"===t.prompt&&i.set("prompt","select_account"),t.method===J&&i.set("method",J),t.identityTypes&&i.set(ee.param,te(t.identityTypes)),"popup"===n.kind?i.set(Z.fromOpenerParam,Z.fromOpenerValue):(n.signinRef?i.set(Z.param,n.signinRef):i.set(Z.fromOpenerParam,Z.noRecoveryValue),n.handoff&&(i.set("redirect_uri",n.handoff.redirectUri),i.set("state",n.handoff.state),i.set("code_challenge",n.handoff.codeChallenge))),`${e.identityBaseUrl}/${e.accountId}/signin?${i}`}class fe extends M{constructor(e,t){super(t),this.configCache=null,this.config=e}get accountId(){return this.config.accountId}get baseUrl(){return`${this.config.identityBaseUrl}${ae`/${this.config.accountId}`}`}makeError(e,t,n,i,s=null){return new ke(e,t,n,i,s)}async request(e,t,n,i){const{data:s}=await this.rawRequest(`${this.baseUrl}${t}${function(e){const t=new URLSearchParams;for(const[n,i]of Object.entries(e??{}))null!=i&&""!==i&&t.append(n,String(i));const n=t.toString().replace(/\+/g,"%20");return n?`?${n}`:""}(i)}`,{method:e,body:n?JSON.stringify(n):void 0});return"object"==typeof s&&null!==s&&"data"in s?s.data:s}async getConfig(){this.configCache||(this.configCache=this.request("GET",ae`/config`));try{return await this.configCache}catch(e){throw this.configCache=null,e}}preloadConfig(){if(this.configCache)return;const e=this.request("GET",ae`/config`);this.configCache=e,e.catch(()=>{})}isConfigPreloaded(){return null!==this.configCache}async drawAuthorizationValues(){return q(K(await this.request("POST",ae`/entropy`,{num_bytes:W.bytes}),W.bytes))}async drawSigninReference(){const e=U(K(await this.request("POST",ae`/entropy`,{num_bytes:Z.bytes,purpose:Z.drawPurpose}),Z.bytes));if(!Q(e))throw new p("The Identity origin answered a malformed sign-in reference","invalid_response");return e}async checkPasskey(e,t="email",n){const i="phone"===t?{phone:e}:{email:e};return this.request("POST",ae`/passkey/check`,{...i,...ve(n)})}async redeemHandoffCode(e,t){return this.request("POST",ae`/signin/redeem`,{code:e,code_verifier:t})}buildAuthContextParams(e){return{...e?.authRequestId?{auth_request_id:e.authRequestId}:{},...ve(e)}}async sendOtp(e){return this.request("POST",ae`/otp/send`,{recipient:e.recipient,method:e.method,...this.buildAuthContextParams(e.authContext),...ue(e.identityTypes??null)})}async verifyOtp(e){return this.request("POST",ae`/otp/verify`,{kindling:e.kindling,pin:e.pin,recipient:e.recipient,...this.buildAuthContextParams(e.authContext),...ge(e.signinRef)})}async submitSecondFactor(e){return this.request("POST",ae`/second-factor/verify`,{ticket:e.ticket,code:e.code})}async startPasskeyVerify(e,t="email",n,i=null){const s=e?{[t]:e}:{},r=await this.request("POST",ae`/passkey/verify`,{...s,...ve(n),...ue(i)});return{challenge:r.options.challenge,rpId:r.options.rpId,timeout:r.options.timeout,...r.options.allowCredentials?{allowCredentials:r.options.allowCredentials}:{},session:r.session}}async completePasskeyVerify(e){const t=e.credential.response;return this.request("POST",ae`/passkey/verify/complete`,{session:e.session,...this.buildAuthContextParams(e.authContext),...ge(e.signinRef),credential:{id:e.credential.id,rawId:ce(e.credential.rawId),type:e.credential.type,response:{clientDataJSON:ce(t.clientDataJSON),authenticatorData:ce(t.authenticatorData),signature:ce(t.signature),userHandle:t.userHandle?ce(t.userHandle):null}}})}async sendBackupVerification(e){return this.request("POST",ae`/backup-verification/send`,{verification_token:e.verificationToken,type:e.type,value:e.value,...e.method?{method:e.method}:{}})}async verifyBackupVerification(e){return this.request("POST",ae`/backup-verification/verify`,{session_id:e.sessionId,code:e.code})}async dismissRecommendation(e){await this.request("POST",ae`/recommendations/dismiss`,{verification_token:e.verificationToken,key:e.key})}getSocialAuthUrl(e,t,n,i,s={}){const r=new URLSearchParams({[G.redirectUri]:t,[G.state]:n,...ge(s.signinRef),...ue(s.identityTypes??null)});i?.authRequestId&&r.set(G.authRequestId,i.authRequestId);const{simple_mode:o}=ve(i);return o&&r.set("simple_mode",JSON.stringify(o)),`${this.baseUrl}/social/${e}?${r}`}getFederationAuthUrl(e,t,n,i={}){const s=new URLSearchParams({[G.redirectUri]:e,[G.state]:t,...ge(i.signinRef),...ue(i.identityTypes??null)});return n?.authRequestId&&s.set(G.authRequestId,n.authRequestId),i.silent&&s.set(G.prompt,"none"),`${this.baseUrl}/federation?${s}`}async sendSparkLink(e,t,n,i,s=null){return this.request("POST",ae`/sparklink/send`,{email:e,connection_id:t,...this.buildAuthContextParams(n),...ge(i),...ue(s)})}async consumeSparkLinkResult(e){return ye(await this.request("GET",ae`/sparklink/result`,void 0,{kindling:e}))}}function ve(e){return e?.simpleMode?{simple_mode:{session_id:e.simpleMode.sessionId}}:{}}function ge(e){return e?{[Z.param]:e}:{}}function ye(e){if(!e||"object"!=typeof e)return null;const t=e;if("sparklink_second_factor"===t.type){if("string"!=typeof t.ticket||!t.ticket)return null;const e=Array.isArray(t.methods)?t.methods.filter(e=>"string"==typeof e):[];return{kind:"second_factor",ticket:t.ticket,methods:e.length>0?e:["authenticator"]}}if("sparklink_verified"!==t.type)return null;const n="string"==typeof t.token&&t.token?t.token:void 0,i="string"==typeof t.redirect&&t.redirect?t.redirect:void 0;return n||i?{kind:"verified",result:{token:n??"",identity:"string"==typeof t.identity?t.identity:"",identityType:t.identityType||"email",svid:"string"==typeof t.svid?t.svid:void 0,sessionId:"string"==typeof t.session_id?t.session_id:void 0,refreshToken:"string"==typeof t.refresh_token?t.refresh_token:void 0,redirect:i,recommendations:be(t.recommendations)}}:null}function be(e){if(!Array.isArray(e))return;const t=[];for(const n of e){if(!n||"object"!=typeof n)continue;const e=n;"passkey"===e.type?t.push({type:"passkey"}):"backup_identifier"!==e.type||"email"!==e.missing_type&&"phone"!==e.missing_type||t.push({type:"backup_identifier",missingType:e.missing_type})}return t}class ke extends p{constructor(e,t,n,i,s=null){super(e,t,n,i,s),this.name="IdentityApiError",Object.setPrototypeOf(this,ke.prototype)}}const we=/^\D*\+/,xe=/^[1-9]\d{7,14}$/,Ce=/\p{Cf}/gu,Se=/^[\s().\p{Pd}]*\+?[\d\s().\p{Pd}]*$/u,Ee=/^[+(\d]/;function Te(e){return e.replace(Ce,"")}function Ae(e){if("string"!=typeof e)return null;const t=Te(e);if(!Se.test(t))return null;const n=t.replace(/\D/g,"");return we.test(t)?xe.test(n)?`+${n}`:null:10===n.length?`+1${n}`:11===n.length&&n.startsWith("1")?`+${n}`:null}function Le(e){if("string"!=typeof e)return"email";const t=Te(e).trim();return Ee.test(t)&&Se.test(t)?"phone":"email"}function Ie(e){const t=Te(e);if(!Se.test(t))return e;const n=t.replace(/\D/g,"");if(we.test(t)&&(!n.startsWith("1")||11!==n.length))return`+${n}`;if(n.length>11||11===n.length&&!n.startsWith("1"))return n;const i=11===n.length?n.slice(1):n;return 0===i.length?"":i.length<=3?`(${i}`:i.length<=6?`(${i.slice(0,3)}) ${i.slice(3)}`:`(${i.slice(0,3)}) ${i.slice(3,6)}-${i.slice(6,10)}`}const Re={otp_email:{id:"otp_email",type:"otp",identityType:"email",name:"Email code",description:"Get a one-time code via email",icon:"email"},otp_sms:{id:"otp_sms",type:"otp",identityType:"phone",name:"Text message",description:"Get a one-time code via SMS",icon:"sms"},otp_voice:{id:"otp_voice",type:"otp",identityType:"phone",name:"Voice call",description:"Get a one-time code via phone call",icon:"phone"},passkey:{id:"passkey",type:"passkey",name:"Passkey",description:"Use biometrics or security key",icon:"fingerprint"},sparklink:{id:"sparklink",type:"sparklink",identityType:"email",name:"SparkLink",description:"Get an instant sign-in link via email",icon:"link"},social_google:{id:"social_google",type:"social",identityType:"email",name:"Google",description:"Sign in with Google",icon:"google",provider:"google"},social_apple:{id:"social_apple",type:"social",identityType:"email",name:"Apple",description:"Sign in with Apple",icon:"apple",provider:"apple"},social_microsoft:{id:"social_microsoft",type:"social",identityType:"email",name:"Microsoft",description:"Sign in with Microsoft",icon:"microsoft",provider:"microsoft"},social_github:{id:"social_github",type:"social",identityType:"email",name:"GitHub",description:"Sign in with GitHub",icon:"github",provider:"github"},social_facebook:{id:"social_facebook",type:"social",identityType:"email",name:"Facebook",description:"Sign in with Facebook",icon:"facebook",provider:"facebook"},social_linkedin:{id:"social_linkedin",type:"social",identityType:"email",name:"LinkedIn",description:"Sign in with LinkedIn",icon:"linkedin",provider:"linkedin"},federation:{id:"federation",type:"federation",name:"Your organization",description:"",icon:"building"}};function Be(e,t){return e.map(e=>{return"federation"!==e?Re[e]:t?{...Re.federation,name:(n=t.display_name,`Continue with ${n}`)}:void 0;var n}).filter(e=>void 0!==e)}const _e="federation_failed",Pe="sv_federation_auto_start";function $e(e){let t;try{t=sessionStorage.getItem(Pe),sessionStorage.removeItem(Pe)}catch{return!1}if(null===t)return!1;try{const n=JSON.parse(t);if("object"!=typeof n||null===n)return!1;const{at:i,accountId:s}=n;return s===e&&"number"==typeof i&&Number.isFinite(i)&&Date.now()-i<9e5}catch{return!1}}class Oe{constructor(){this._sdkConfig=null,this._viewState={view:"loading"},this._recipient="",this._identityType="email",this._authContext=void 0,this._signinRef=null,this._identityTypes=null,this._passkey={hasPasskey:null,isFallbackMode:!1,pendingResult:null},this._otp={kindling:"",method:null}}get sdkConfig(){return this._sdkConfig}setConfig(e){this._sdkConfig=e}get accountId(){return this._sdkConfig?.accountId??""}get viewState(){return this._viewState}setViewState(e){this._viewState=e}get recipient(){return this._recipient}get identityType(){return this._identityType}setIdentity(e,t){this._recipient=e,this._identityType=t}get methodIds(){return this._authContext?.simpleMode?.methods??this._sdkConfig?.methods??[]}get passkeyRequired(){return!0===this._authContext?.simpleMode?.passkeyRequired}getAllowedIdentityTypes(){const e=this._authContext?.simpleMode?.allowedIdentityTypes;if(e)return e;if(!this._sdkConfig)return["email"];return this._sdkConfig.allowedIdentityTypes??["email"]}get authContext(){return this._authContext}setAuthContext(e){this._authContext=e}get signinRef(){return this._signinRef}setSigninRef(e){this._signinRef=e}get identityTypes(){return this._identityTypes}setIdentityTypes(e){this._identityTypes=e}get passkey(){return this._passkey}setPasskeyStatus(e){this._passkey.hasPasskey=e}enablePasskeyFallback(){this._passkey.isFallbackMode=!0}setPendingResult(e){this._passkey.pendingResult=e}get otp(){return this._otp}setKindling(e){this._otp.kindling=e}setOtpMethod(e){this._otp.method=e}}class Me{openPopup(e){const t=e.width??480,n=e.height??640,i=e.timeoutMs??18e5;return new Promise((s,r)=>{const o=Math.round((window.screen.width-t)/2),a=Math.round((window.screen.height-n)/2),l=window.open(e.url,e.windowName,`width=${t},height=${n},left=${o},top=${a},popup=1`);if(!l)return void r(new y);e.onOpen?.(l);const d=Date.now();let c=!1,h=!1;const u=()=>{window.removeEventListener("message",p),clearTimeout(m),clearInterval(g)},p=t=>{if(t.origin!==e.trustedOrigin)return;const n=t.data;if(e.readyType&&n?.type===e.readyType)return h=!0,void e.onReady?.();e.requestType&&n?.type===e.requestType?t.source===l&&e.onRequest?.():n?.type===e.resultType&&(c=!0,u(),s(n))};window.addEventListener("message",p);const m=setTimeout(()=>{c||(c=!0,u(),l.close(),r(new f("Popup operation timed out. Please try again.")))},i),g=setInterval(()=>{if(l.closed&&!c){if(c=!0,u(),!h&&Date.now()-d<=2500)return void r(new b);r(new v("Authentication was cancelled."))}},500)})}}function Ne(e){const t=j(e);if(null===t)throw new ke("The passkey options are not valid base64url","invalid_response",0);return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}class He{constructor(e,t){this.api=e,this.state=t,this.popupLauncher=new Me;const n=e.config;this.baseUrl=n.identityBaseUrl,this.accountId=n.accountId,this.trustedOrigin=new URL(this.baseUrl).origin}async checkPasskey(){try{const e=await this.api.checkPasskey(this.state.recipient,this.state.identityType,this.state.authContext);this.state.setPasskeyStatus(e.has_passkey)}catch(e){console.warn("Passkey check failed:",e),this.state.setPasskeyStatus(null)}}async register(e){const t=await this.openPasskeyPopup("register",e);return t.success&&this.state.setPasskeyStatus(!0),t}async verify(e){return this.canRunCeremonyInline()?this.verifyInline(e):this.openPasskeyPopup("verify")}canRunCeremonyInline(){return"undefined"!=typeof window&&"undefined"!=typeof navigator&&!!navigator.credentials&&window.location.origin===this.trustedOrigin}canAutoVerify(){return!!this.canRunCeremonyInline()&&document.cookie.split(";").some(e=>e.trim().startsWith("__Host-authsv_passkey=1"))}async verifyInline(e){try{const t="phone"===this.state.identityType?"phone":"email",n=await this.api.startPasskeyVerify(this.state.recipient,t,this.state.authContext,this.state.identityTypes),i=await navigator.credentials.get({...e?{signal:e}:{},publicKey:{challenge:Ne(n.challenge),rpId:n.rpId,timeout:n.timeout,userVerification:"required",...n.allowCredentials?{allowCredentials:n.allowCredentials.map(e=>({type:e.type,id:Ne(e.id)}))}:{}}});if(!i)return{success:!1,error:"Failed to get passkey",errorType:"unknown"};const s=await this.api.completePasskeyVerify({session:n.session,credential:i,authContext:this.state.authContext,signinRef:this.state.signinRef});return{success:!0,result:{token:s.token,identity:s.identity||this.state.recipient,identityType:s.identity_type||"email",svid:s.svid,sessionId:s.session_id,refreshToken:s.refresh_token,redirect:s.redirect}}}catch(e){return this.mapInlineCeremonyError(e)}}mapInlineCeremonyError(e){return e instanceof Error&&("NotAllowedError"===e.name||"AbortError"===e.name)?{success:!1,error:"Authentication was cancelled. Please try again.",errorType:"cancelled"}:e instanceof ke?"identity_locked"===e.code?{success:!1,error:"This SparkVault Identity is locked. Visit auth.sv to manage it.",errorType:"unknown",errorCode:"identity_locked"}:"passkey_not_registered"===e.code?{success:!1,error:"No passkey found. Create one to continue.",errorType:"not_found",errorCode:"passkey_not_registered"}:{success:!1,error:e.message||"Passkey authentication failed",errorType:"unknown",errorCode:e.code}:{success:!1,error:e instanceof Error?e.message:"Passkey authentication failed",errorType:"unknown"}}async openPasskeyPopup(e,t){const n=new URLSearchParams({mode:e,origin:window.location.origin});if(this.state.recipient){const e="phone"===this.state.identityType?"phone":"email";n.set(e,this.state.recipient)}const i=this.state.authContext;i?.authRequestId&&n.set("auth_request_id",i.authRequestId);const{simple_mode:s}=ve(i);s&&n.set("simple_mode",JSON.stringify(s));const{signinRef:r}=this.state;r&&n.set(Z.param,r);const{identityTypes:o}=this.state;o&&n.set(ee.param,te(o));const a="register"===e&&t?`#${new URLSearchParams({registration_token:t}).toString()}`:"",l=`${this.baseUrl}/${this.accountId}/passkey/popup?${n}${a}`;let d;try{d=await this.popupLauncher.openPopup({url:l,windowName:"sparkvault-passkey",width:450,height:500,resultType:"sparkvault-passkey-result",trustedOrigin:this.trustedOrigin})}catch(e){return e instanceof y?{success:!1,error:e.message,errorType:"popup_blocked"}:e instanceof v?{success:!1,error:e.message,errorType:"cancelled"}:{success:!1,error:e instanceof Error?e.message:"Passkey operation failed. Please try again.",errorType:"unknown"}}return d.success&&d.data?{success:!0,result:{token:d.data.token||"",identity:d.data.identity||this.state.recipient,identityType:d.data.identity_type||"email",svid:d.data.svid,sessionId:d.data.session_id,refreshToken:d.data.refresh_token,redirect:d.data.redirect}}:this.handlePopupError(d.error,d.message,d.errorCode)}handlePopupError(e,t,n){return"cancelled"===e?{success:!1,error:t||"Authentication was cancelled. Please try again.",errorType:"cancelled"}:"identity_locked"===n||"identity_locked"===e?{success:!1,error:t||"This SparkVault Identity is locked. Visit auth.sv to manage it.",errorType:"unknown",errorCode:"identity_locked"}:t?.includes("No passkey")||t?.includes("not found")?{success:!1,error:"No passkey found. Create one to continue.",errorType:"not_found"}:{success:!1,error:t||e||"Passkey authentication failed",errorType:"unknown",errorCode:n}}}class Fe{constructor(e,t){this.api=e,this.state=t}async send(e){try{const t=await this.api.sendOtp({recipient:this.state.recipient,method:e,authContext:this.state.authContext,identityTypes:this.state.identityTypes});return this.state.setKindling(t.kindling),this.state.setOtpMethod(e),{success:!0,kindling:t.kindling,expiresAt:t.expires_at}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Failed to send code",errorCode:e instanceof p?e.code:void 0}}}async resend(){const e=this.state.otp.method;if(!e)return{success:!1,error:"No OTP method set"};try{const t=await this.api.sendOtp({recipient:this.state.recipient,method:e,authContext:this.state.authContext,identityTypes:this.state.identityTypes});return this.state.setKindling(t.kindling),{success:!0,kindling:t.kindling,expiresAt:t.expires_at}}catch(e){return{success:!1,error:`Failed to resend: ${e instanceof Error?e.message:"Failed to resend code"}`,errorCode:e instanceof p?e.code:void 0}}}async verify(e){const t=this.state.otp.kindling;if(!t)return{success:!1,error:"No kindling available"};try{const n=await this.api.verifyOtp({kindling:t,pin:e,recipient:this.state.recipient,authContext:this.state.authContext,signinRef:this.state.signinRef});return n.second_factor_required&&n.ticket?{success:!1,secondFactor:{ticket:n.ticket,methods:n.methods??["authenticator"]}}:n.verified&&(n.token||n.redirect)?{success:!0,result:{token:n.token??"",identity:n.identity??this.state.recipient,identityType:n.identity_type??this.state.identityType,svid:n.svid,sessionId:n.session_id,refreshToken:n.refresh_token,redirect:n.redirect,recommendations:be(n.recommendations)}}:(n.kindling&&this.state.setKindling(n.kindling),{success:!1,newKindling:n.kindling,retryAfter:n.retry_after,backoffExpires:n.retry_after,error:"Invalid code. Please try again."})}catch(e){return{success:!1,error:e instanceof Error?e.message:"Verification failed",errorCode:e instanceof p?e.code:void 0}}}}class De{constructor(e,t){this.api=e,this.state=t}async send(e){try{const t=await this.api.sendSparkLink(this.state.recipient,e,this.state.authContext,this.state.signinRef,this.state.identityTypes);return{success:!0,expiresAt:t.expiresAt,kindling:t.kindling}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Failed to send SparkLink",errorCode:e instanceof p?e.code:void 0}}}}const Ve=new RegExp("^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$"),ze=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,Ue=Object.freeze({ADDRESS:320,LOCAL_PART:64,DOMAIN:255}),je=Object.freeze({FORMAT:"format",TOO_LONG:"too_long",LOCAL_PART_TOO_LONG:"local_part_too_long",DOMAIN_TOO_LONG:"domain_too_long"});function We(e){if("string"!=typeof e)throw new TypeError("An email address is a string");return e.trim().toLowerCase()}function qe(e){return null===function(e){if("string"!=typeof e)return je.FORMAT;const t=We(e),n=t.indexOf("@");if(n<=0||n!==t.lastIndexOf("@"))return je.FORMAT;const i=t.slice(0,n),s=t.slice(n+1),r=s.split(".");return!Ve.test(i)||r.length<2||!r.every(e=>ze.test(e))?je.FORMAT:t.length>Ue.ADDRESS?je.TOO_LONG:i.length>Ue.LOCAL_PART?je.LOCAL_PART_TOO_LONG:s.length>Ue.DOMAIN?je.DOMAIN_TOO_LONG:null}(e)}function Ke(e,t){const n=document.createElement("div");return e&&(n.className=e),n}function Ge(e){for(;e.firstChild;)e.removeChild(e.firstChild)}function Ye(e){const t=document.createElement("div");return t.className="sv-error",t.setAttribute("role","alert"),t.textContent=e,t}function Je(e){return qe(e)?We(e):null}class Xe{constructor(e={}){this.message=e.message??"Loading...",!0===e.announce&&(this.announcement=this.message)}render(){const e=Ke("sv-loading"),t=document.createElement("div");t.className="sv-spinner";const n=document.createElement("p");return n.className="sv-loading-text",n.textContent=this.message,void 0!==this.announcement?(t.setAttribute("aria-hidden","true"),n.setAttribute("aria-hidden","true")):(t.setAttribute("role","status"),t.setAttribute("aria-label","Loading")),e.appendChild(t),e.appendChild(n),e}destroy(){}}const Ze=/[+\d]/;const Qe="0 0 24 24",et="#FFFFFF";function tt(e){for(const t of Object.values(e))t&&"object"==typeof t&&tt(t);return Object.freeze(e)}const nt=tt({google:[{d:"M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z",fill:"#4285F4"},{d:"M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z",fill:"#34A853"},{d:"M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z",fill:"#FBBC05"},{d:"M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z",fill:"#EA4335"}],apple:[{d:"M18.71 19.5c-.83 1.24-1.71 2.45-3.05 2.47-1.34.03-1.77-.79-3.29-.79-1.53 0-2 .77-3.27.82-1.31.05-2.3-1.32-3.14-2.53C4.25 17 2.94 12.45 4.7 9.39c.87-1.52 2.43-2.48 4.12-2.51 1.28-.02 2.5.87 3.29.87.78 0 2.26-1.07 3.81-.91.65.03 2.47.26 3.64 1.98-.09.06-2.17 1.28-2.15 3.81.03 3.02 2.65 4.03 2.68 4.04-.03.07-.42 1.44-1.38 2.83M13 3.5c.73-.83 1.94-1.46 2.94-1.5.13 1.17-.34 2.35-1.04 3.19-.69.85-1.83 1.51-2.95 1.42-.15-1.15.41-2.35 1.05-3.11z",fill:"currentColor"}],microsoft:[{d:"M1 1h10v10H1z",fill:"#F25022"},{d:"M1 13h10v10H1z",fill:"#00A4EF"},{d:"M13 1h10v10H13z",fill:"#7FBA00"},{d:"M13 13h10v10H13z",fill:"#FFB900"}],github:[{d:"M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0024 12c0-6.63-5.37-12-12-12z",fill:"currentColor"}],facebook:[{d:"M24 12.044c0-6.627-5.373-12-12-12s-12 5.373-12 12 5.373 12 12 12 12-5.373 12-12Z",fill:"#0866FF"},{d:"M9.101 23.691v-7.98H6.627v-3.667h2.474v-1.58c0-4.085 1.848-5.978 5.858-5.978.401 0 .955.042 1.468.103a8.68 8.68 0 0 1 1.141.195v3.325a8.623 8.623 0 0 0-.653-.036 26.805 26.805 0 0 0-.733-.009c-.707 0-1.259.096-1.675.309a1.686 1.686 0 0 0-.679.622c-.258.42-.374.995-.374 1.752v1.297h3.919l-.386 2.103-.287 1.564h-3.246v8.245A12 12 0 0 1 9.101 23.691Z",fill:et}],linkedin:[{d:"M22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z",fill:"#0A66C2"},{d:"M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433c-1.144 0-2.063-.926-2.063-2.065 0-1.138.92-2.063 2.063-2.063 1.14 0 2.064.925 2.064 2.063 0 1.139-.925 2.065-2.064 2.065zm1.782 13.019H3.555V9h3.564v11.452z",fill:et}]});function it(e,t=16,n=16){const i=document.createElementNS("http://www.w3.org/2000/svg","svg");return i.setAttribute("viewBox",e),i.setAttribute("width",String(t)),i.setAttribute("height",String(n)),i.setAttribute("fill","none"),i.setAttribute("xmlns","http://www.w3.org/2000/svg"),i}function st(e,t={}){const n=document.createElementNS("http://www.w3.org/2000/svg","path");n.setAttribute("d",e);for(const[e,i]of Object.entries(t))n.setAttribute(e,i);return n}function rt(e,t,n,i={}){const s=document.createElementNS("http://www.w3.org/2000/svg","circle");s.setAttribute("cx",String(e)),s.setAttribute("cy",String(t)),s.setAttribute("r",String(n));for(const[e,t]of Object.entries(i))s.setAttribute(e,t);return s}function ot(){const e=it("0 0 16 16");return e.appendChild(st("M13.25 4.75L6 12 2.75 8.75",{stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"})),e}function at(){const e=it("0 0 16 16");return e.appendChild(st("M10 12L6 8L10 4",{stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"})),e}function lt(){const e=it("0 0 56 56",56,56);e.classList.add("sv-passkey-icon");const t=document.createElementNS("http://www.w3.org/2000/svg","g");t.setAttribute("transform","translate(29.5, 26.5)");const n={stroke:"currentColor","stroke-width":"3","stroke-linecap":"round","stroke-linejoin":"round",fill:"none"};return t.appendChild(rt(-9.5,-9.5,9.5,n)),t.appendChild(st("M-2.8 -2.8L16 16",n)),t.appendChild(st("M9.5 9.5L9.5 15.5",n)),t.appendChild(st("M16 16L16 22",n)),e.appendChild(t),e}function dt(e){const t=it("0 0 48 48",48,48);t.classList.add(e);const n={stroke:"currentColor","stroke-width":"2.5","stroke-linecap":"round","stroke-linejoin":"round",fill:"none"};return t.appendChild(st("M24 9L5.5 39h37L24 9z",n)),t.appendChild(st("M24 20v8",n)),t.appendChild(rt(24,33.5,1.5,{fill:"currentColor"})),t}function ct(e){const t=function(e){switch(e){case"email":return function(){const e=it("0 0 20 20",20,20);return e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","1.5"),e.setAttribute("stroke-linecap","round"),e.setAttribute("stroke-linejoin","round"),e.appendChild(st("M3 4h14c.55 0 1 .45 1 1v10c0 .55-.45 1-1 1H3c-.55 0-1-.45-1-1V5c0-.55.45-1 1-1z")),e.appendChild(st("M18 5l-8 5.5L2 5")),e}();case"sms":return function(){const e=it("0 0 20 20",20,20);return e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","1.5"),e.setAttribute("stroke-linecap","round"),e.setAttribute("stroke-linejoin","round"),e.appendChild(st("M4 3.75h12A1.75 1.75 0 0117.75 5.5v5A1.75 1.75 0 0116 12.25H8.5L5 15.25V12.25H4A1.75 1.75 0 012.25 10.5v-5A1.75 1.75 0 014 3.75z")),e.appendChild(rt(7,8,.75,{fill:"currentColor",stroke:"none"})),e.appendChild(rt(10,8,.75,{fill:"currentColor",stroke:"none"})),e.appendChild(rt(13,8,.75,{fill:"currentColor",stroke:"none"})),e}();case"phone":return function(){const e=it("0 0 20 20",20,20);return e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","1.5"),e.setAttribute("stroke-linecap","round"),e.setAttribute("stroke-linejoin","round"),e.appendChild(st("M18 14v2.5a1.5 1.5 0 01-1.64 1.5 14.85 14.85 0 01-6.47-2.3 14.63 14.63 0 01-4.5-4.5A14.85 14.85 0 013.1 4.64 1.5 1.5 0 014.59 3H7.1a1.5 1.5 0 011.5 1.29 9.63 9.63 0 00.52 2.11 1.5 1.5 0 01-.34 1.58l-.95.95a12 12 0 004.5 4.5l.95-.95a1.5 1.5 0 011.58-.34 9.63 9.63 0 002.11.52A1.5 1.5 0 0118 14z")),e}();case"fingerprint":return function(){const e=it("0 0 20 20",20,20);return e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","1.5"),e.setAttribute("stroke-linecap","round"),e.setAttribute("stroke-linejoin","round"),e.appendChild(st("M2 10c0-4.42 3.58-8 8-8 2.65 0 5 1.29 6.47 3.28")),e.appendChild(st("M4 16.58c.42-.35.79-.76 1.1-1.22")),e.appendChild(st("M14.41 17.51c.09-.45.32-1.73.38-2.26")),e.appendChild(st("M10 8.33a1.5 1.5 0 00-1.5 1.5c0 .77-.08 1.88-.2 3")),e.appendChild(st("M7.21 18.33c.16-.5.34-1 .43-1.5")),e.appendChild(st("M11.67 10.93c0 1.79 0 4.79-.75 6.65")),e.appendChild(st("M17.33 13.33c.15-1.5.1-4.02 0-4.5")),e.appendChild(st("M7.5 5.67a4.5 4.5 0 016.75 3.9c0 .35 0 .88-.02 1.5")),e}();case"link":return function(){const e=it("0 0 20 20",20,20);return e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","1.5"),e.setAttribute("stroke-linecap","round"),e.setAttribute("stroke-linejoin","round"),e.appendChild(st("M8.33 10.83a3.75 3.75 0 005.66.41l2.25-2.25a3.75 3.75 0 00-5.3-5.3l-1.29 1.28")),e.appendChild(st("M11.67 9.17a3.75 3.75 0 00-5.66-.41l-2.25 2.25a3.75 3.75 0 005.3 5.3l1.28-1.28")),e}();case"google":case"apple":case"microsoft":case"github":case"facebook":case"linkedin":return function(e){const t=it(Qe,20,20);for(const{d:n,fill:i}of nt[e])t.appendChild(st(n,{fill:i}));return t}(e);case"building":return function(){const e=it("0 0 20 20",20,20);return e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","1.5"),e.setAttribute("stroke-linecap","round"),e.setAttribute("stroke-linejoin","round"),e.appendChild(st("M2.5 17.5h15")),e.appendChild(st("M4.17 17.5V5.83L10.83 2.5v15")),e.appendChild(st("M15.83 17.5V9.17l-5-3.33")),e.appendChild(st("M7.5 7.5v.01")),e.appendChild(st("M7.5 10v.01")),e.appendChild(st("M7.5 12.5v.01")),e.appendChild(st("M7.5 15v.01")),e}();case"users":return function(){const e=it("0 0 20 20",20,20);return e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","1.5"),e.setAttribute("stroke-linecap","round"),e.setAttribute("stroke-linejoin","round"),e.appendChild(st("M14.17 17.5v-1.67a3.33 3.33 0 00-3.34-3.33H4.17a3.33 3.33 0 00-3.34 3.33v1.67")),e.appendChild(rt(7.5,5.83,3.33,{stroke:"currentColor","stroke-width":"1.5",fill:"none"})),e.appendChild(st("M19.17 17.5v-1.67a3.33 3.33 0 00-2.5-3.22")),e.appendChild(st("M13.33 2.6a3.33 3.33 0 010 6.46")),e}();default:return function(){const e=it("0 0 20 20",20,20);return e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","1.5"),e.setAttribute("stroke-linecap","round"),e.setAttribute("stroke-linejoin","round"),e.appendChild(st("M6 2.75h8A3.25 3.25 0 0117.25 6v8A3.25 3.25 0 0114 17.25H6A3.25 3.25 0 012.75 14V6A3.25 3.25 0 016 2.75z")),e.appendChild(rt(10,10,1.25,{fill:"currentColor",stroke:"none"})),e}()}}(e);return t.setAttribute("data-sv-method-icon",e),t}function ht(e){const t=document.createElement("button");t.className="sv-btn sv-btn-method";const n=Ke("sv-method-content"),i=Ke("sv-method-icon");i.setAttribute("aria-hidden","true"),i.appendChild(ct(e.icon)),n.appendChild(i);const s=Ke("sv-method-text"),r=document.createElement("div");if(r.className="sv-method-name",r.textContent=e.name,s.appendChild(r),e.description){const t=document.createElement("div");t.className="sv-method-description",t.textContent=e.description,s.appendChild(t)}return n.appendChild(s),t.appendChild(n),t}const ut=Object.freeze({beforeTerms:"By providing a phone number, you agree to receive texts from SparkVault with verification codes, security alerts and account notifications, and automated calls with verification codes, as its ",terms:"Terms",beforePrivacy:" and ",privacy:"Privacy Policy",afterPrivacy:" describe. Message frequency varies. Message and data rates may apply. Reply STOP to opt out or HELP for help."});function pt(e,t){const n=document.createElement("a");return n.className="sv-sms-consent-link",n.href=t,n.target="_blank",n.rel="noopener noreferrer",n.textContent=e,n}function mt(e){const t=document.createElement("p");return t.className="sv-sms-consent",t.id=e,t.append(ut.beforeTerms,pt(ut.terms,"https://sparkvault.com/terms/"),ut.beforePrivacy,pt(ut.privacy,"https://sparkvault.com/privacy/"),ut.afterPrivacy),t}class ft{constructor(e){this.container=null,this.inputElement=null,this.labelElement=null,this.submitButton=null,this.passkeyLink=null,this.leadingButton=null,this.leadingHandler=null,this.errorContainer=null,this.focusTimeoutId=null,this.identityInput=null,this.props=e,this.boundHandleKeyDown=e=>{"Enter"===e.key&&(e.preventDefault(),this.handleSubmit())},this.boundHandleSubmit=()=>this.handleSubmit(),this.boundHandlePasskey=e.onPasskey?()=>e.onPasskey():null}get allowsBoth(){return this.props.allowedTypes.includes("email")&&this.props.allowedTypes.includes("phone")}get allowsEmail(){return this.props.allowedTypes.includes("email")}get allowsPhone(){return this.props.allowedTypes.includes("phone")}render(){const e=Ke("sv-email-view");this.container=e,this.props.leadingMethod&&this.offerLeadingMethod(this.props.leadingMethod);const t=Ke("sv-email-header"),n=document.createElement("p");n.className="sv-email-subtitle",n.textContent=this.getSubtitleText(),t.appendChild(n),e.appendChild(t),this.errorContainer=Ke("sv-email-error-container"),this.props.error&&this.errorContainer.appendChild(Ye(this.props.error)),e.appendChild(this.errorContainer);const i=Ke("sv-email-form"),s=Ke("sv-email-input-wrapper");if(this.labelElement=document.createElement("label"),this.labelElement.className="sv-email-label",this.labelElement.htmlFor="sv-identity-input",this.labelElement.textContent=this.getLabelText(),this.inputElement=document.createElement("input"),this.inputElement.type=this.allowsPhone&&!this.allowsEmail?"tel":"text",this.inputElement.id="sv-identity-input",this.inputElement.className="sv-email-input",this.inputElement.placeholder=this.getPlaceholderText(),this.inputElement.autocomplete=this.allowsBoth?"on":this.allowsEmail?"email":"tel",this.inputElement.required=!0,this.inputElement.maxLength=Ue.ADDRESS,this.props.initialValue&&(this.inputElement.value=this.props.initialValue),this.identityInput=function(e,{allowedTypes:t=["email","phone"],onChange:n}={}){let i=e.value,s=i,r=[],o=!1,a=null,l=[{value:i,start:i.length,end:i.length}],d=0;const c=1===t.length&&"phone"===t[0],h=t.includes("phone"),u=()=>c?"phone":h?Le(i):"email";function p(e){return s===i||0===e?e:e>=s.length?i.length:r.find(t=>t.display>=e)?.value??i.length}function m(e){if(s===i)return e;if(e>=i.length)return s.length;for(let t=r.length-1;t>=0;t-=1)if(r[t].value<e)return r[t].display+1;return r[0]?.display??0}function f(t=null,n=t){s="phone"===u()?Ie(i):i,r=s===i?[]:function(e,t){const n=[...e.matchAll(/[+\d]/g)].map(e=>e.index),i=[...t.matchAll(/[+\d]/g)].map(e=>e.index);return i.map((e,t)=>({display:e,value:n[t+n.length-i.length]}))}(i,s),e.value=s,e.inputMode=c?"tel":"text",e.autocapitalize="none",e.spellcheck=!1,null!==t&&e.setSelectionRange(m(t),m(n))}function v(t){a=null;const s=Math.max(0,Math.min(l.length-1,d+t)),r=s!==d;d=s;const o=l[d];i=o.value,f(),e.setSelectionRange(o.start,o.end),r&&n?.(i,u())}function g(e){return"historyUndo"===e.inputType?-1:"historyRedo"===e.inputType?1:0}function y(e){if(o||e.isComposing||e.altKey||!e.metaKey&&!e.ctrlKey)return;const t=e.key.toLowerCase(),n="z"===t?e.shiftKey?1:-1:"y"===t&&e.ctrlKey?1:0;n&&(e.preventDefault(),v(n))}function b(){const t=e.selectionStart??s.length,n=e.selectionEnd??t;l[d]={value:i,start:t,end:n}}function k(t){if(o||t.isComposing)return;const n=g(t);if(n)return void(t.cancelable&&(t.preventDefault(),v(n)));b();let i=e.selectionStart??s.length,r=e.selectionEnd??i;i===r&&"deleteContentBackward"===t.inputType&&(i=Math.max(0,i-1)),i===r&&"deleteContentForward"===t.inputType&&(r=Math.min(s.length,r+1)),a={start:i,end:r,inputType:t.inputType,display:s}}function w(t){if(o||t.isComposing)return;const r=g(t);if(r)return void v(r);const c=e.value;if(c===s)return void(a=null);const h=e.selectionStart??c.length,m=e.selectionEnd??h;let y=0,b=s.length,k=c.length;const w=a;if(a=null,w?.display===s&&c.startsWith(s.slice(0,w.start))&&c.endsWith(s.slice(w.end)))y=w.start,b=w.end,k=c.length-(s.length-b);else{for(;y<s.length&&y<c.length&&s[y]===c[y];)y+=1;for(;b>y&&k>y&&s[b-1]===c[k-1];)b-=1,k-=1}let x=p(y),C=p(b);const S=c.slice(y,k);if(!S&&b>y&&x===C)if("deleteContentForward"===(w?.inputType||t.inputType)){for(;C<i.length&&!Ze.test(i[C]);)C+=1;C=Math.min(i.length,C+1)}else{for(;x>0&&!Ze.test(i[x-1]);)x-=1;x=Math.max(0,x-1)}const E=e=>e<y?p(e):e<=k?x+e-y:p(e-k+b)+S.length-(C-x),T=E(h),A=E(m);i=i.slice(0,x)+S+i.slice(C),f(T,A),l.splice(d+1),l.push({value:i,start:e.selectionStart,end:e.selectionEnd}),d=l.length-1,n?.(i,u())}function x(){b(),o=!0,a=null}function C(e){o=!1,w(e)}return e.addEventListener("keydown",y),e.addEventListener("beforeinput",k),e.addEventListener("input",w),e.addEventListener("change",w),e.addEventListener("compositionstart",x),e.addEventListener("compositionend",C),f(),b(),{get value(){return i},get type(){return u()},setValue(e){e!==i&&(i=e,l=[{value:i,start:i.length,end:i.length}],d=0,a=null,f(),b())},destroy(){e.removeEventListener("keydown",y),e.removeEventListener("beforeinput",k),e.removeEventListener("input",w),e.removeEventListener("change",w),e.removeEventListener("compositionstart",x),e.removeEventListener("compositionend",C)}}}(this.inputElement,{allowedTypes:this.props.allowedTypes,onChange:()=>{this.clearError(),this.labelElement&&(this.labelElement.textContent=this.getLabelText()),this.props.onType?.()}}),this.labelElement.textContent=this.getLabelText(),this.inputElement.addEventListener("keydown",this.boundHandleKeyDown),s.appendChild(this.labelElement),s.appendChild(this.inputElement),this.allowsPhone){const e=mt("sv-identity-sms-consent");this.inputElement.setAttribute("aria-describedby",e.id),s.appendChild(e)}return i.appendChild(s),this.submitButton=document.createElement("button"),this.submitButton.className="sv-btn sv-btn-email-primary",this.submitButton.textContent="Continue",this.submitButton.addEventListener("click",this.boundHandleSubmit),i.appendChild(this.submitButton),e.appendChild(i),this.boundHandlePasskey&&(this.passkeyLink=document.createElement("button"),this.passkeyLink.className="sv-fallback-link",this.passkeyLink.textContent="Sign in with a passkey",this.passkeyLink.addEventListener("click",this.boundHandlePasskey),e.appendChild(this.passkeyLink)),this.focusTimeoutId=setTimeout(()=>this.inputElement?.focus(),50),e}offerLeadingMethod(e){if(!this.container||this.leadingButton)return;this.leadingHandler=e.onSelect,this.leadingButton=ht(e.method),this.leadingButton.addEventListener("click",this.leadingHandler);const t=Ke("sv-divider"),n=document.createElement("span");n.className="sv-divider-text",n.textContent="or",t.appendChild(n),this.container.prepend(this.leadingButton,t)}getSubtitleText(){return this.allowsBoth?"Enter your email or phone to continue":this.allowsPhone?"Enter your phone number to continue":"Enter your email to continue"}getLabelText(){return this.allowsBoth?"phone"===this.identityInput?.type?"Phone number":"Email address":this.allowsPhone?"Phone number":"Email address"}getPlaceholderText(){return this.allowsBoth?"you@example.com or (555) 123-4567":this.allowsPhone?"(555) 123-4567":"you@example.com"}clearError(){this.errorContainer&&Ge(this.errorContainer),this.inputElement?.classList.remove("sv-email-input-error")}showError(e){this.errorContainer&&(Ge(this.errorContainer),this.errorContainer.appendChild(Ye(e))),this.inputElement?.classList.add("sv-email-input-error"),this.inputElement?.focus()}handleSubmit(){if(!this.identityInput||!this.submitButton)return;const e=this.identityInput.type,t="phone"===e?Ae(this.identityInput.value):Je(this.identityInput.value);t?(this.submitButton.disabled=!0,this.submitButton.textContent="Please wait...",this.props.onSubmit({value:t,type:e})):this.showError("phone"===e?"Please enter a valid phone number":"Please enter a valid email address")}destroy(){this.identityInput?.destroy(),null!==this.focusTimeoutId&&(clearTimeout(this.focusTimeoutId),this.focusTimeoutId=null),this.inputElement&&this.inputElement.removeEventListener("keydown",this.boundHandleKeyDown),this.submitButton&&this.submitButton.removeEventListener("click",this.boundHandleSubmit),this.passkeyLink&&this.boundHandlePasskey&&this.passkeyLink.removeEventListener("click",this.boundHandlePasskey),this.leadingButton&&this.leadingHandler&&this.leadingButton.removeEventListener("click",this.leadingHandler)}}const vt=e=>"phone"===e.identityType;class gt{constructor(e){this.backLink=null,this.methodsContainer=null,this.methodButtons=[],this.methodClickHandlers=new Map,this.props=e,this.boundHandleBack=()=>this.props.onBack?.()}render(){const e=Ke();this.backLink=this.props.onBack?this.createBackLink():null;const t=document.createElement("h3");t.className="sv-title",t.textContent="Choose how to sign in";const n=this.props.email,i=n?document.createElement("p"):null;i&&n&&(i.className="sv-subtitle",i.textContent=n);const s=this.props.methods.some(vt)?mt("sv-method-sms-consent"):null,r=Ke();this.methodsContainer=r;for(const e of this.props.methods){const t=this.createMethodButton(e);s&&vt(e)&&t.setAttribute("aria-describedby",s.id),this.methodButtons.push(t),r.appendChild(t)}return this.backLink&&e.appendChild(this.backLink),e.appendChild(t),i&&e.appendChild(i),e.appendChild(r),s&&e.appendChild(s),e}offerLeadingMethod(e){if(!this.methodsContainer)return;const t=this.createMethodButton(e);this.methodButtons.unshift(t),this.methodsContainer.prepend(t)}createBackLink(){const e=document.createElement("button");e.className="sv-back-link",e.appendChild(at());const t="phone"===this.props.identityType?" Change phone number":" Change email";return e.appendChild(document.createTextNode(t)),e.addEventListener("click",this.boundHandleBack),e}createMethodButton(e){const t=ht(e),n=()=>this.props.onSelectMethod(e);return this.methodClickHandlers.set(t,n),t.addEventListener("click",n),t}destroy(){this.backLink&&this.backLink.removeEventListener("click",this.boundHandleBack);for(const e of this.methodButtons){const t=this.methodClickHandlers.get(e);t&&e.removeEventListener("click",t)}this.methodClickHandlers.clear(),this.methodButtons=[]}}function yt(e){return function(e,t){return e?String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,t):""}(e,"'")}class bt{constructor(e){this.inputElements=[],this.submitButton=null,this.resendButton=null,this.backLink=null,this.errorContainer=null,this.resendTimer=null,this.backoffTimer=null,this.backoffSeconds=0,this.focusTimeoutId=null,this.autoSubmitTimeoutId=null,this.isSubmitting=!1,this.inputHandlers=new Map,this.props=e,this.boundHandleBack=()=>this.props.onBack(),this.boundHandleResend=()=>this.handleResend(),this.boundHandleSubmit=()=>this.handleSubmit()}render(){const e=Ke();this.backLink=this.createBackLink();const t=document.createElement("h3");t.className="sv-title",t.textContent="Enter verification code";const n="email"===this.props.method?"email":"phone",i=document.createElement("p");i.className="sv-subtitle",i.innerHTML=`We sent a 6-digit code to your ${n}<br><strong>${yt(this.props.email)}</strong>`,this.errorContainer=Ke(),this.props.error&&this.errorContainer.appendChild(Ye(this.props.error));const s=this.createInputGroup();if(this.submitButton=document.createElement("button"),this.submitButton.className="sv-btn sv-btn-primary",this.submitButton.textContent="Verify",this.submitButton.addEventListener("click",this.boundHandleSubmit),this.props.backoffExpires){Math.max(0,Math.ceil(this.props.backoffExpires-Date.now()/1e3))>0&&this.startBackoff(this.props.backoffExpires)}const r=Ke("sv-resend-container");return this.resendButton=document.createElement("button"),this.resendButton.className="sv-back-link",this.resendButton.textContent="Resend code",this.resendButton.addEventListener("click",this.boundHandleResend),r.appendChild(this.resendButton),e.style.display="flex",e.style.flexDirection="column",e.appendChild(t),e.appendChild(i),e.appendChild(this.errorContainer),e.appendChild(s),e.appendChild(this.submitButton),e.appendChild(r),e.appendChild(this.backLink),this.focusTimeoutId=setTimeout(()=>this.inputElements[0]?.focus(),50),e}createBackLink(){const e=document.createElement("button");return e.className="sv-back-link",e.style.order="-1",e.appendChild(at()),e.appendChild(document.createTextNode(" Choose another method")),e.addEventListener("click",this.boundHandleBack),e}createInputGroup(){const e=Ke("sv-otp-input-group");for(let t=0;t<6;t++){const n=document.createElement("input");n.type="text",n.inputMode="numeric",n.pattern="[0-9]*",n.maxLength=1,n.className="sv-otp-digit",n.autocomplete="one-time-code",n.setAttribute("aria-label",`Digit ${t+1} of 6`);const i={input:e=>this.handleInput(e,t),keydown:e=>this.handleKeyDown(e,t),paste:e=>this.handlePaste(e),focus:()=>n.select()};this.inputHandlers.set(n,i),n.addEventListener("input",i.input),n.addEventListener("keydown",i.keydown),n.addEventListener("paste",i.paste),n.addEventListener("focus",i.focus),this.inputElements.push(n),e.appendChild(n)}return e}handleInput(e,t){const n=e.target,i=n.value.replace(/\D/g,"");i.length>0?(n.value=i[0],this.clearError(),t<5?this.inputElements[t+1].focus():this.checkAutoSubmit()):n.value=""}handleKeyDown(e,t){const n=e.target;"Backspace"===e.key?""===n.value&&t>0&&(this.inputElements[t-1].focus(),this.inputElements[t-1].value=""):"ArrowLeft"===e.key&&t>0?this.inputElements[t-1].focus():"ArrowRight"===e.key&&t<5?this.inputElements[t+1].focus():"Enter"===e.key&&this.handleSubmit()}handlePaste(e){e.preventDefault();const t=(e.clipboardData?.getData("text")??"").replace(/\D/g,"").slice(0,6);for(let e=0;e<t.length;e++)this.inputElements[e]&&(this.inputElements[e].value=t[e]);if(t.length>0){this.clearError();const e=Math.min(t.length,5);this.inputElements[e].focus()}6===t.length&&this.checkAutoSubmit()}checkAutoSubmit(){6===this.getCode().length&&(this.autoSubmitTimeoutId=setTimeout(()=>this.handleSubmit(),100))}getCode(){return this.inputElements.map(e=>e.value).join("")}clearError(){this.errorContainer&&Ge(this.errorContainer),this.inputElements.forEach(e=>e.classList.remove("sv-input-error"))}showError(e){this.errorContainer&&(Ge(this.errorContainer),this.errorContainer.appendChild(Ye(e))),this.inputElements.forEach(e=>e.classList.add("sv-input-error")),this.inputElements[0]?.focus()}handleSubmit(){if(!this.submitButton)return;if(this.isSubmitting)return;if(this.backoffSeconds>0)return;const e=function(e){const t=e.replace(/\D/g,"");return 6===t.length?t:null}(this.getCode());e?(null!==this.autoSubmitTimeoutId&&(clearTimeout(this.autoSubmitTimeoutId),this.autoSubmitTimeoutId=null),this.isSubmitting=!0,this.submitButton.disabled=!0,this.submitButton.textContent="Verifying...",this.props.onSubmit(e)):this.showError("Please enter the complete 6-digit code")}startBackoff(e){this.disableInputs(!0),this.backoffTimer=new de({expiresAt:e,onTick:e=>{this.backoffSeconds=e,this.updateSubmitButton()},onExpired:()=>{this.backoffSeconds=0,this.updateSubmitButton(),this.disableInputs(!1),this.inputElements[0]?.focus()}}),this.backoffTimer.start()}updateSubmitButton(){this.submitButton&&(this.backoffSeconds>0?(this.submitButton.textContent=`Wait ${this.backoffSeconds}s`,this.submitButton.disabled=!0):(this.submitButton.textContent="Verify",this.submitButton.disabled=!1))}disableInputs(e){this.inputElements.forEach(t=>{t.disabled=e})}handleResend(){!this.resendTimer?.isRunning()&&this.resendButton&&(this.resendTimer=new le({duration:30,onTick:e=>{this.resendButton&&(this.resendButton.textContent=`Resend code (${e}s)`,this.resendButton.disabled=!0)},onComplete:()=>{this.resendButton&&(this.resendButton.textContent="Resend code",this.resendButton.disabled=!1)}}),this.resendTimer.start(),this.props.onResend())}destroy(){null!==this.focusTimeoutId&&(clearTimeout(this.focusTimeoutId),this.focusTimeoutId=null),null!==this.autoSubmitTimeoutId&&(clearTimeout(this.autoSubmitTimeoutId),this.autoSubmitTimeoutId=null),this.resendTimer?.stop(),this.resendTimer=null,this.backoffTimer?.stop(),this.backoffTimer=null;for(const e of this.inputElements){const t=this.inputHandlers.get(e);t&&(e.removeEventListener("input",t.input),e.removeEventListener("keydown",t.keydown),e.removeEventListener("paste",t.paste),e.removeEventListener("focus",t.focus))}this.inputHandlers.clear(),this.inputElements=[],this.submitButton&&this.submitButton.removeEventListener("click",this.boundHandleSubmit),this.resendButton&&this.resendButton.removeEventListener("click",this.boundHandleResend),this.backLink&&this.backLink.removeEventListener("click",this.boundHandleBack)}}class kt{constructor(e){this.input=null,this.submitButton=null,this.toggleButton=null,this.errorContainer=null,this.promptEl=null,this.recoveryMode=!1,this.isSubmitting=!1,this.focusTimeoutId=null,this.props=e,this.boundSubmit=()=>this.handleSubmit(),this.boundToggle=()=>this.toggleRecovery(),this.boundKeydown=e=>{"Enter"===e.key&&this.handleSubmit()},this.boundInput=()=>this.clearError()}render(){const e=Ke();e.style.display="flex",e.style.flexDirection="column";const t=document.createElement("h3");return t.className="sv-title",t.textContent="Two-step verification",this.promptEl=document.createElement("p"),this.promptEl.className="sv-subtitle",this.promptEl.innerHTML="Enter the 6-digit code from your authenticator app.",this.errorContainer=Ke(),this.props.error&&this.errorContainer.appendChild(Ye(this.props.error)),this.input=document.createElement("input"),this.input.type="text",this.input.inputMode="numeric",this.input.autocomplete="one-time-code",this.input.maxLength=6,this.input.className="sv-input",this.input.setAttribute("aria-label","Verification code"),this.input.placeholder="000000",this.input.addEventListener("keydown",this.boundKeydown),this.input.addEventListener("input",this.boundInput),this.submitButton=document.createElement("button"),this.submitButton.className="sv-btn sv-btn-primary",this.submitButton.textContent="Verify",this.submitButton.addEventListener("click",this.boundSubmit),e.appendChild(t),e.appendChild(this.promptEl),e.appendChild(this.errorContainer),e.appendChild(this.input),e.appendChild(this.submitButton),this.props.methods?.includes("recovery_code")&&(this.toggleButton=document.createElement("button"),this.toggleButton.className="sv-back-link",this.toggleButton.textContent="Use a recovery code instead",this.toggleButton.addEventListener("click",this.boundToggle),e.appendChild(this.toggleButton)),this.focusTimeoutId=setTimeout(()=>this.input?.focus(),50),e}toggleRecovery(){this.input&&this.promptEl&&this.toggleButton&&(this.recoveryMode=!this.recoveryMode,this.input.value="",this.clearError(),this.recoveryMode?(this.input.inputMode="text",this.input.removeAttribute("maxlength"),this.input.placeholder="XXXX-XXXX-XXXX-XXXX",this.promptEl.innerHTML="Enter one of your recovery codes.",this.toggleButton.textContent="Use your authenticator app instead"):(this.input.inputMode="numeric",this.input.maxLength=6,this.input.placeholder="000000",this.promptEl.innerHTML="Enter the 6-digit code from your authenticator app.",this.toggleButton.textContent="Use a recovery code instead"),this.input.focus())}clearError(){this.errorContainer&&Ge(this.errorContainer),this.input?.classList.remove("sv-input-error")}showError(e){this.errorContainer&&(Ge(this.errorContainer),this.errorContainer.appendChild(Ye(e))),this.input?.classList.add("sv-input-error"),this.isSubmitting=!1,this.submitButton&&(this.submitButton.disabled=!1,this.submitButton.textContent="Verify"),this.input?.focus(),this.input?.select()}handleSubmit(){if(this.isSubmitting||!this.submitButton||!this.input)return;const e=this.input.value.trim();e?this.recoveryMode||/^\d{6}$/.test(e)?(this.isSubmitting=!0,this.submitButton.disabled=!0,this.submitButton.textContent="Verifying...",this.props.onSubmit(e)):this.showError("Enter the complete 6-digit code"):this.showError(this.recoveryMode?"Enter a recovery code":"Enter the 6-digit code")}destroy(){null!==this.focusTimeoutId&&(clearTimeout(this.focusTimeoutId),this.focusTimeoutId=null),this.input?.removeEventListener("keydown",this.boundKeydown),this.input?.removeEventListener("input",this.boundInput),this.submitButton?.removeEventListener("click",this.boundSubmit),this.toggleButton?.removeEventListener("click",this.boundToggle)}}class wt{constructor(e){this.actionButton=null,this.errorContainer=null,this.backLink=null,this.fallbackLink=null,this.props=e,this.boundHandleBack=()=>this.props.onBack?.(),this.boundHandleStart=()=>this.handleStart(),this.boundHandleFallback=e.onFallback?()=>e.onFallback():null}render(){const e=Ke();this.backLink=this.props.onBack?this.createBackLink():null;const t=Ke();t.appendChild(lt());const n=document.createElement("h3");n.className="sv-title",n.textContent="register"===this.props.mode?"Set up a passkey":"Use your passkey";const i=document.createElement("p");i.className="sv-subtitle","register"===this.props.mode?i.innerHTML=`Create a passkey for<br><strong>${yt(this.props.identityLabel)}</strong><br>to sign in faster next time`:i.innerHTML="Use a passkey linked to your SparkVault Identity",this.errorContainer=Ke(),this.props.error&&this.errorContainer.appendChild(Ye(this.props.error));const s=document.createElement("p");s.className="sv-passkey-description",s.textContent="register"===this.props.mode?"Use Face ID, Touch ID, Windows Hello, or a security key.":"Your device will prompt you to verify your identity.";const r="register"===this.props.mode?"Create Passkey":"Continue with Passkey";return this.actionButton=document.createElement("button"),this.actionButton.className="sv-btn sv-btn-primary",this.actionButton.textContent=r,this.actionButton.addEventListener("click",this.boundHandleStart),this.backLink&&e.appendChild(this.backLink),e.appendChild(t),e.appendChild(n),e.appendChild(i),e.appendChild(this.errorContainer),e.appendChild(s),e.appendChild(this.actionButton),this.props.onFallback&&this.boundHandleFallback&&(this.fallbackLink=this.createFallbackLink(),e.appendChild(this.fallbackLink)),e}createFallbackLink(){const e=document.createElement("button");return e.className="sv-fallback-link",e.textContent="Having trouble? Use a code instead",this.boundHandleFallback&&e.addEventListener("click",this.boundHandleFallback),e}createBackLink(){const e=document.createElement("button");return e.className="sv-back-link",e.appendChild(at()),e.appendChild(document.createTextNode(" Choose another method")),e.addEventListener("click",this.boundHandleBack),e}handleStart(){this.actionButton&&(this.actionButton.disabled=!0,this.actionButton.textContent="Waiting for device...",this.props.onStart())}showError(e){this.errorContainer&&(Ge(this.errorContainer),this.errorContainer.appendChild(Ye(e))),this.actionButton&&(this.actionButton.disabled=!1,this.actionButton.textContent="Try Again")}destroy(){this.backLink&&this.backLink.removeEventListener("click",this.boundHandleBack),this.actionButton&&this.actionButton.removeEventListener("click",this.boundHandleStart),this.fallbackLink&&this.boundHandleFallback&&this.fallbackLink.removeEventListener("click",this.boundHandleFallback)}}class xt{constructor(e){this.fallbackLink=null,this.props=e,this.boundHandleFallback=()=>this.props.onUseAnotherMethod()}render(){const e=Ke(),t=Ke();t.appendChild(lt());const n=document.createElement("h3");n.className="sv-title",n.textContent="Signing you in";const i=document.createElement("p");i.className="sv-subtitle",i.textContent="Use your passkey to continue";const s=document.createElement("div");s.className="sv-spinner",s.setAttribute("role","status"),s.setAttribute("aria-label","Waiting for your passkey");const r=Ke("sv-loading");return r.appendChild(s),this.fallbackLink=document.createElement("button"),this.fallbackLink.className="sv-fallback-link",this.fallbackLink.textContent="Use another method",this.fallbackLink.addEventListener("click",this.boundHandleFallback),e.appendChild(t),e.appendChild(n),e.appendChild(i),e.appendChild(r),e.appendChild(this.fallbackLink),e}destroy(){this.fallbackLink&&this.fallbackLink.removeEventListener("click",this.boundHandleFallback)}}class Ct{constructor(e){this.addButton=null,this.skipLink=null,this.props=e,this.boundHandleAdd=()=>this.props.onAddPasskey(),this.boundHandleSkip=()=>this.props.onSkip()}render(){const e=Ke(),t=Ke();t.appendChild(lt());const n=document.createElement("h3");n.className="sv-title",n.textContent="Add a passkey for faster sign-in?";const i=document.createElement("p");i.className="sv-subtitle",i.innerHTML=`Next time, sign in instantly as<br><strong>${yt(this.props.identityLabel)}</strong>`;const s=Ke();this.props.error&&s.appendChild(Ye(this.props.error));const r=document.createElement("div");r.className="sv-passkey-prompt-benefits";const o=document.createElement("ul"),a=["No codes to type or wait for","Phishing-resistant security","Works with Face ID, Touch ID, or Windows Hello"];for(const e of a){const t=document.createElement("li");t.appendChild(ot()),t.appendChild(document.createTextNode(e)),o.appendChild(t)}return r.appendChild(o),this.addButton=document.createElement("button"),this.addButton.className="sv-btn sv-btn-primary",this.addButton.textContent=this.props.error?"Try Again":"Add Passkey",this.addButton.addEventListener("click",this.boundHandleAdd),this.skipLink=document.createElement("button"),this.skipLink.className="sv-skip-link",this.skipLink.textContent=this.props.error?"Skip for now":"Not now",this.skipLink.addEventListener("click",this.boundHandleSkip),e.appendChild(t),e.appendChild(n),e.appendChild(i),e.appendChild(s),e.appendChild(r),e.appendChild(this.addButton),e.appendChild(this.skipLink),e}destroy(){this.addButton&&this.addButton.removeEventListener("click",this.boundHandleAdd),this.skipLink&&this.skipLink.removeEventListener("click",this.boundHandleSkip)}}class St{constructor(e){this.inputElement=null,this.submitButton=null,this.skipLink=null,this.errorContainer=null,this.focusTimeoutId=null,this.props=e,this.boundHandleInput=()=>this.handleInput(),this.boundHandleKeyDown=e=>{"Enter"===e.key&&(e.preventDefault(),this.handleSubmit())},this.boundHandleSubmit=()=>this.handleSubmit(),this.boundHandleSkip=()=>this.props.onSkip()}get isPhone(){return"phone"===this.props.missingType}render(){const e=Ke("sv-email-view"),t=Ke("sv-email-header"),n=document.createElement("h3");n.className="sv-title",n.textContent=this.isPhone?"Add a backup phone number":"Add a backup email";const i=document.createElement("p");i.className="sv-email-subtitle",i.textContent=this.isPhone?"Add a phone number so you can always get back into your account.":"Add an email so you can always get back into your account.",t.appendChild(n),t.appendChild(i),e.appendChild(t),this.errorContainer=Ke("sv-email-error-container"),this.props.error&&this.errorContainer.appendChild(Ye(this.props.error)),e.appendChild(this.errorContainer);const s=Ke("sv-email-form"),r=Ke("sv-email-input-wrapper"),o=document.createElement("label");if(o.className="sv-email-label",o.htmlFor="sv-backup-input",o.textContent=this.isPhone?"Phone number":"Email address",this.inputElement=document.createElement("input"),this.inputElement.type=this.isPhone?"tel":"email",this.inputElement.id="sv-backup-input",this.inputElement.className="sv-email-input",this.inputElement.placeholder=this.isPhone?"(555) 123-4567":"you@example.com",this.inputElement.autocomplete=this.isPhone?"tel":"email",this.inputElement.required=!0,this.inputElement.maxLength=Ue.ADDRESS,this.inputElement.addEventListener("input",this.boundHandleInput),this.inputElement.addEventListener("keydown",this.boundHandleKeyDown),r.appendChild(o),r.appendChild(this.inputElement),this.isPhone){const e=mt("sv-backup-sms-consent");this.inputElement.setAttribute("aria-describedby",e.id),r.appendChild(e)}return s.appendChild(r),this.submitButton=document.createElement("button"),this.submitButton.className="sv-btn sv-btn-primary",this.submitButton.textContent="Send code",this.submitButton.addEventListener("click",this.boundHandleSubmit),s.appendChild(this.submitButton),this.skipLink=document.createElement("button"),this.skipLink.className="sv-skip-link",this.skipLink.textContent="Not now",this.skipLink.addEventListener("click",this.boundHandleSkip),s.appendChild(this.skipLink),e.appendChild(s),this.focusTimeoutId=setTimeout(()=>this.inputElement?.focus(),50),e}handleInput(){if(this.clearError(),!this.inputElement||!this.isPhone)return;const e=this.inputElement.value,t=this.inputElement.selectionStart??e.length,n=Ie(e);if(n!==e){this.inputElement.value=n;const i=Math.min(t+(n.length-e.length),n.length);this.inputElement.setSelectionRange(i,i)}}clearError(){this.errorContainer&&Ge(this.errorContainer),this.inputElement?.classList.remove("sv-email-input-error")}showError(e){this.errorContainer&&(Ge(this.errorContainer),this.errorContainer.appendChild(Ye(e))),this.inputElement?.classList.add("sv-email-input-error"),this.inputElement?.focus()}handleSubmit(){if(!this.inputElement||!this.submitButton)return;const e=this.inputElement.value,t=this.isPhone?Ae(e):Je(e);t?(this.submitButton.disabled=!0,this.submitButton.textContent="Please wait...",this.props.onSubmit(t)):this.showError(this.isPhone?"Please enter a valid phone number":"Please enter a valid email address")}destroy(){null!==this.focusTimeoutId&&(clearTimeout(this.focusTimeoutId),this.focusTimeoutId=null),this.inputElement&&(this.inputElement.removeEventListener("input",this.boundHandleInput),this.inputElement.removeEventListener("keydown",this.boundHandleKeyDown)),this.submitButton&&this.submitButton.removeEventListener("click",this.boundHandleSubmit),this.skipLink&&this.skipLink.removeEventListener("click",this.boundHandleSkip)}}class Et{constructor(e){this.expirationTimer=null,this.resendTimer=null,this.countdownElement=null,this.countdownSection=null,this.waitingSection=null,this.resendButton=null,this.backLink=null,this.fallbackButton=null,this.props=e,this.boundHandleBack=()=>this.props.onBack(),this.boundHandleResend=()=>this.handleResend(),this.boundHandleFallback=()=>this.props.onFallback()}render(){const e=Ke();this.backLink=this.createBackLink();const t=document.createElement("h3");t.className="sv-title",t.textContent="Check your email";const n=document.createElement("p");n.className="sv-subtitle",n.innerHTML=`We sent a secure link to<br><strong>${yt(this.props.email)}</strong>`,this.waitingSection=Ke("sv-sparklink-waiting");const i=document.createElement("div");i.className="sv-spinner sv-spinner-small",i.setAttribute("role","status"),i.setAttribute("aria-label","Waiting for verification");const s=document.createElement("span");s.className="sv-sparklink-waiting-text",s.textContent="Waiting for you to click the link...",this.waitingSection.appendChild(i),this.waitingSection.appendChild(s),this.countdownSection=Ke("sv-sparklink-countdown");const r=document.createElement("span");r.textContent="Link expires in ",this.countdownElement=document.createElement("span"),this.countdownElement.className="sv-sparklink-countdown-time",this.startExpirationTimer(),this.countdownSection.appendChild(r),this.countdownSection.appendChild(this.countdownElement);const o=Ke("sv-resend-container");this.resendButton=document.createElement("button"),this.resendButton.className="sv-btn sv-btn-secondary",this.resendButton.textContent="Resend link",this.resendButton.addEventListener("click",this.boundHandleResend),o.appendChild(this.resendButton);const a=Ke("sv-sparklink-fallback");return this.fallbackButton=document.createElement("button"),this.fallbackButton.className="sv-back-link",this.fallbackButton.textContent="Use verification code instead",this.fallbackButton.addEventListener("click",this.boundHandleFallback),a.appendChild(this.fallbackButton),e.appendChild(this.backLink),e.appendChild(t),e.appendChild(n),e.appendChild(this.waitingSection),e.appendChild(this.countdownSection),e.appendChild(o),e.appendChild(a),e}createBackLink(){const e=document.createElement("button");return e.className="sv-back-link",e.appendChild(at()),e.appendChild(document.createTextNode(" Choose another method")),e.addEventListener("click",this.boundHandleBack),e}formatTime(e){if(!Number.isFinite(e)||e<0)return"--:--";return`${Math.floor(e/60)}:${Math.floor(e%60).toString().padStart(2,"0")}`}startExpirationTimer(){if(!Number.isFinite(this.props.expiresAt)||this.props.expiresAt<=0)return this.countdownElement&&(this.countdownElement.textContent="--:--"),void console.warn("[SparkVault] Invalid expiresAt timestamp:",this.props.expiresAt);const e=Math.floor(this.props.expiresAt/1e3);this.expirationTimer=new de({expiresAt:e,onTick:e=>{this.countdownElement&&(this.countdownElement.textContent=this.formatTime(e))},onExpired:()=>{this.showExpiredState()}}),this.expirationTimer.start()}showExpiredState(){if(this.props.onExpired(),this.waitingSection){this.waitingSection.innerHTML="",this.waitingSection.classList.add("sv-sparklink-expired");const e=Ke("sv-sparklink-expired-icon");e.appendChild(dt("sv-expired-icon")),this.waitingSection.appendChild(e);const t=document.createElement("span");t.className="sv-sparklink-expired-text",t.textContent="This link has expired",this.waitingSection.appendChild(t)}this.countdownSection&&(this.countdownSection.style.display="none")}handleResend(){!this.resendTimer?.isRunning()&&this.resendButton&&(this.resendTimer=new le({duration:30,onTick:e=>{this.resendButton&&(this.resendButton.textContent=`Resend link (${e}s)`,this.resendButton.disabled=!0)},onComplete:()=>{this.resendButton&&(this.resendButton.textContent="Resend link",this.resendButton.disabled=!1)}}),this.resendTimer.start(),this.props.onResend())}destroy(){this.expirationTimer?.stop(),this.expirationTimer=null,this.resendTimer?.stop(),this.resendTimer=null,this.backLink&&this.backLink.removeEventListener("click",this.boundHandleBack),this.resendButton&&this.resendButton.removeEventListener("click",this.boundHandleResend),this.fallbackButton&&this.fallbackButton.removeEventListener("click",this.boundHandleFallback)}}const Tt=["identity_trial_exhausted","identity_trial_expired","identity_capacity_blocked"];const At="stronger_verification_required",Lt="federation_unavailable",It="signin_reference_unavailable",Rt="identity_types_unavailable",Bt="identity_types_unreadable";function _t(e){return"identity_locked"===e?"This SparkVault Identity is locked":function(e){return Tt.includes(e)}(e)||e===Lt||e===Rt||e===Bt?"Sign-in unavailable":e===At?"This request needs your passkey":null}class Pt{constructor(e){this.retryButton=null,this.closeButton=null,this.props=e,this.boundHandleRetry=()=>this.props.onRetry(),this.boundHandleClose=()=>this.props.onClose()}render(){const e=Ke();e.className="sv-error-view";const t=Ke();t.className="sv-error-icon-container",t.appendChild(dt("sv-error-icon"));const n=Ke();n.className="sv-error-content";const i=_t(this.props.code),s=this.props.code===ee.refusalCode?{title:"That sign-in is not accepted here",action:"Other ways to sign in"}:null;const r=null===i&&null===s,o=document.createElement("h3");o.className="sv-error-title",o.textContent=i??s?.title??"Something went wrong";const a=document.createElement("p");if(a.className="sv-error-message",a.textContent=this.props.message,n.appendChild(o),n.appendChild(a),r){const e=document.createElement("div");e.className="sv-error-code-badge";const t=document.createElement("span");t.className="sv-error-code-label",t.textContent="Error code";const i=document.createElement("code");i.className="sv-error-code-value",i.textContent=this.props.code,e.appendChild(t),e.appendChild(i),n.appendChild(e)}const l=Ke();return l.className="sv-error-actions",null===i&&(this.retryButton=document.createElement("button"),this.retryButton.className="sv-btn sv-btn-error-primary",this.retryButton.textContent=s?.action??"Try Again",this.retryButton.addEventListener("click",this.boundHandleRetry),l.appendChild(this.retryButton)),this.closeButton=document.createElement("button"),this.closeButton.className="sv-btn sv-btn-error-secondary",this.closeButton.textContent="Close",this.closeButton.addEventListener("click",this.boundHandleClose),l.appendChild(this.closeButton),e.appendChild(t),e.appendChild(n),e.appendChild(l),e}destroy(){this.retryButton&&this.retryButton.removeEventListener("click",this.boundHandleRetry),this.closeButton&&this.closeButton.removeEventListener("click",this.boundHandleClose)}}const $t=Object.freeze({white:"#ffffff",slate50:"#f7fafb",slate100:"#f0f5f7",slate200:"#e0e9ed",slate300:"#c9d6dc",slate500:"#5e757f",slate600:"#425761",slate900:"#0d1a20",slate950:"#030a0e",action:"#216bde",actionHover:"#0d5bcd",actionBg:"#eef4fe",btnDanger:"#b02b27",btnDangerHover:"#9a221f",success:"#006d42",success500:"#2ec26b",error:"#b02b27",error500:"#e6443d",errorBg:"#ffeae7",errorText:"#94221f",warning:"#8a5600",warning500:"#e6ad00",infoBg:"#e0f2ff",info500:"#4383eb",modalOverlay:"rgba(13, 26, 32, 0.6)",darkText:"rgba(255,255,255,0.92)",darkTextMuted:"rgba(255,255,255,0.62)",darkHairline:"rgba(255,255,255,0.10)",darkCard:"rgba(255,255,255,0.05)",shadowSm:"0 1px 2px 0 rgba(0, 0, 0, 0.05)",shadowMd:"0 4px 6px -1px rgba(0, 0, 0, 0.1)",shadowPopover:"0 8px 24px rgba(13, 26, 32, 0.12)"});function Ot(e,t){const n=Number.parseInt(e.slice(1),16);return`rgba(${n>>16}, ${n>>8&255}, ${255&n}, ${t})`}class Mt{constructor(e){this.retryButton=null,this.closeButton=null,this.props=e,this.boundHandleRetry=()=>this.props.onRetry(),this.boundHandleClose=()=>this.props.onClose()}render(){const e=Ke("sv-unavailable-view"),t=Ke("sv-unavailable-icon-container");t.appendChild(function(){const e=document.createElementNS("http://www.w3.org/2000/svg","svg");e.setAttribute("viewBox","0 0 48 48"),e.setAttribute("width","48"),e.setAttribute("height","48"),e.setAttribute("fill","none"),e.classList.add("sv-unavailable-icon");const t=document.createElementNS("http://www.w3.org/2000/svg","circle");t.setAttribute("cx","24"),t.setAttribute("cy","24"),t.setAttribute("r","22"),t.setAttribute("fill",$t.actionBg),t.setAttribute("stroke",$t.infoBg),t.setAttribute("stroke-width","1"),e.appendChild(t);const n=document.createElementNS("http://www.w3.org/2000/svg","g");n.setAttribute("transform","translate(12, 10)");const i=document.createElementNS("http://www.w3.org/2000/svg","path");i.setAttribute("d","M12 2L3 6v6c0 5.55 3.84 10.74 9 12 5.16-1.26 9-6.45 9-12V6l-9-4z"),i.setAttribute("fill",$t.info500),n.appendChild(i);const s=document.createElementNS("http://www.w3.org/2000/svg","rect");s.setAttribute("x","9"),s.setAttribute("y","9"),s.setAttribute("width","2.5"),s.setAttribute("height","8"),s.setAttribute("rx","1"),s.setAttribute("fill",$t.white),n.appendChild(s);const r=document.createElementNS("http://www.w3.org/2000/svg","rect");return r.setAttribute("x","12.5"),r.setAttribute("y","9"),r.setAttribute("width","2.5"),r.setAttribute("height","8"),r.setAttribute("rx","1"),r.setAttribute("fill",$t.white),n.appendChild(r),e.appendChild(n),e}()),e.appendChild(t);const n=Ke("sv-unavailable-content"),i=document.createElement("h3");i.className="sv-unavailable-title",i.textContent="Temporarily Unavailable",n.appendChild(i);const s=document.createElement("p");s.className="sv-unavailable-message",s.textContent="Authentication is experiencing a brief interruption. Please try again in a moment.",n.appendChild(s),e.appendChild(n);const r=Ke("sv-unavailable-actions");return this.retryButton=document.createElement("button"),this.retryButton.className="sv-btn sv-btn-primary",this.retryButton.textContent="Try Again",this.retryButton.addEventListener("click",this.boundHandleRetry),r.appendChild(this.retryButton),this.closeButton=document.createElement("button"),this.closeButton.className="sv-btn sv-btn-secondary",this.closeButton.textContent="Close",this.closeButton.addEventListener("click",this.boundHandleClose),r.appendChild(this.closeButton),e.appendChild(r),e}destroy(){this.retryButton&&this.retryButton.removeEventListener("click",this.boundHandleRetry),this.closeButton&&this.closeButton.removeEventListener("click",this.boundHandleClose)}}class Nt{constructor(e){this.dismissButton=null,this.props=e,this.boundHandleClose=()=>this.props.onClose()}render(){const e=Ke("sv-not-activated-view"),t=Ke("sv-not-activated-eyebrow");t.appendChild(function(){const e=Ke("sv-not-activated-mark"),t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("viewBox","0 0 16 16"),t.setAttribute("width","14"),t.setAttribute("height","14"),t.setAttribute("fill","none");const n=document.createElementNS("http://www.w3.org/2000/svg","path");n.setAttribute("d","M8 1.5c.6 1.8 2 2.7 2 4.4 0 .9-.5 1.6-1.2 1.6-.6 0-1-.4-1-.9 0-.4.2-.8.2-1.2 0-.7-.5-1.1-1-1.1-1.4 0-2.5 1.5-2.5 3.4 0 2.4 1.9 4.3 4.5 4.3s4.5-1.9 4.5-4.3c0-3.6-3-4.6-5.5-6.2z"),n.setAttribute("fill","currentColor"),t.appendChild(n);const i=document.createElement("span");return i.textContent="SparkVault",e.appendChild(t),e.appendChild(i),e}());const n=document.createElement("span");n.className="sv-not-activated-eyebrow-divider",n.textContent="•",t.appendChild(n);const i=document.createElement("span");i.className="sv-not-activated-eyebrow-label",i.textContent="Identity",t.appendChild(i),e.appendChild(t);const s=function(){const e=Ke("sv-not-activated-badge"),t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("viewBox","0 0 64 64"),t.setAttribute("width","72"),t.setAttribute("height","72"),t.setAttribute("fill","none"),t.setAttribute("aria-hidden","true"),t.classList.add("sv-not-activated-badge-svg");const n=document.createElementNS("http://www.w3.org/2000/svg","circle");n.setAttribute("cx","32"),n.setAttribute("cy","32"),n.setAttribute("r","29.5"),n.setAttribute("fill",$t.slate50),n.setAttribute("stroke",$t.slate200),n.setAttribute("stroke-width","1"),t.appendChild(n);const i=document.createElementNS("http://www.w3.org/2000/svg","rect");i.setAttribute("x","18.5"),i.setAttribute("y","18.5"),i.setAttribute("width","27"),i.setAttribute("height","27"),i.setAttribute("rx","7"),i.setAttribute("fill",$t.white),i.setAttribute("stroke",$t.slate300),i.setAttribute("stroke-width","1"),t.appendChild(i);const s=(e,n)=>{const i=document.createElementNS("http://www.w3.org/2000/svg","path");i.setAttribute("d",`M24 ${e}H${n}`),i.setAttribute("stroke",$t.slate600),i.setAttribute("stroke-width","2"),i.setAttribute("stroke-linecap","round"),t.appendChild(i)};s("26","40"),s("32","40"),s("38","35");const r=(e,n)=>{const i=document.createElementNS("http://www.w3.org/2000/svg","circle");i.setAttribute("cx",e),i.setAttribute("cy",n),i.setAttribute("r","2.5"),i.setAttribute("fill",$t.action),i.setAttribute("stroke",$t.white),i.setAttribute("stroke-width","1.5"),t.appendChild(i)};return r("30","26"),r("36","32"),r("28","38"),e.appendChild(t),e}();e.appendChild(s);const r=document.createElement("h2");r.className="sv-not-activated-title",r.id="sv-modal-title",r.textContent="Identity Product not configured",e.appendChild(r);const o=document.createElement("p");o.className="sv-not-activated-message",o.textContent="Sign-in is unavailable because the site owner has not configured SparkVault Identity for this account.",e.appendChild(o);const a=Ke("sv-not-activated-owner"),l=document.createElement("span");l.className="sv-not-activated-owner-label",l.textContent="Are you the site owner?";const d=document.createElement("span");d.className="sv-not-activated-owner-hint",d.textContent="Sign in to SparkVault and configure the Identity Product to start accepting sign-ins.",a.appendChild(l),a.appendChild(d),e.appendChild(a);const c=Ke("sv-not-activated-actions"),h=document.createElement("a");h.className="sv-btn sv-btn-primary sv-not-activated-cta",h.href="https://app.sparkvault.com/products/identity",h.target="_blank",h.rel="noopener noreferrer";const u=document.createElement("span");return u.textContent="Configure in SparkVault",h.appendChild(u),h.appendChild(function(){const e=document.createElementNS("http://www.w3.org/2000/svg","svg");e.setAttribute("viewBox","0 0 16 16"),e.setAttribute("width","14"),e.setAttribute("height","14"),e.setAttribute("fill","none"),e.classList.add("sv-not-activated-cta-icon");const t=document.createElementNS("http://www.w3.org/2000/svg","path");return t.setAttribute("d","M6 3h7v7M13 3l-8 8"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","2"),t.setAttribute("stroke-linecap","round"),t.setAttribute("stroke-linejoin","round"),e.appendChild(t),e}()),c.appendChild(h),this.dismissButton=document.createElement("button"),this.dismissButton.className="sv-not-activated-dismiss",this.dismissButton.type="button",this.dismissButton.textContent="Dismiss",this.dismissButton.addEventListener("click",this.boundHandleClose),c.appendChild(this.dismissButton),e.appendChild(c),e}destroy(){this.dismissButton&&this.dismissButton.removeEventListener("click",this.boundHandleClose)}}class Ht{constructor(e){this.dismissButton=null,this.props=e,this.boundHandleClose=()=>this.props.onClose()}render(){const e=Ke("sv-not-activated-view"),t=Ke("sv-not-activated-eyebrow");t.appendChild(function(){const e=Ke("sv-not-activated-mark"),t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("viewBox","0 0 16 16"),t.setAttribute("width","14"),t.setAttribute("height","14"),t.setAttribute("fill","none");const n=document.createElementNS("http://www.w3.org/2000/svg","path");n.setAttribute("d","M8 1.5c.6 1.8 2 2.7 2 4.4 0 .9-.5 1.6-1.2 1.6-.6 0-1-.4-1-.9 0-.4.2-.8.2-1.2 0-.7-.5-1.1-1-1.1-1.4 0-2.5 1.5-2.5 3.4 0 2.4 1.9 4.3 4.5 4.3s4.5-1.9 4.5-4.3c0-3.6-3-4.6-5.5-6.2z"),n.setAttribute("fill","currentColor"),t.appendChild(n);const i=document.createElement("span");return i.textContent="SparkVault",e.appendChild(t),e.appendChild(i),e}());const n=document.createElement("span");n.className="sv-not-activated-eyebrow-divider",n.textContent="•",t.appendChild(n);const i=document.createElement("span");i.className="sv-not-activated-eyebrow-label",i.textContent="Identity",t.appendChild(i),e.appendChild(t);const s=function(){const e=Ke("sv-not-activated-badge"),t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("viewBox","0 0 64 64"),t.setAttribute("width","72"),t.setAttribute("height","72"),t.setAttribute("fill","none"),t.setAttribute("aria-hidden","true"),t.classList.add("sv-not-activated-badge-svg");const n=document.createElementNS("http://www.w3.org/2000/svg","circle");n.setAttribute("cx","32"),n.setAttribute("cy","32"),n.setAttribute("r","29.5"),n.setAttribute("fill",$t.slate50),n.setAttribute("stroke",$t.slate200),n.setAttribute("stroke-width","1"),t.appendChild(n);const i=document.createElementNS("http://www.w3.org/2000/svg","circle");i.setAttribute("cx","32"),i.setAttribute("cy","32"),i.setAttribute("r","13"),i.setAttribute("fill",$t.white),i.setAttribute("stroke",$t.slate300),i.setAttribute("stroke-width","2"),t.appendChild(i);const s=document.createElementNS("http://www.w3.org/2000/svg","ellipse");s.setAttribute("cx","32"),s.setAttribute("cy","32"),s.setAttribute("rx","5.5"),s.setAttribute("ry","13"),s.setAttribute("fill","none"),s.setAttribute("stroke",$t.slate300),s.setAttribute("stroke-width","2"),t.appendChild(s);const r=document.createElementNS("http://www.w3.org/2000/svg","path");r.setAttribute("d","M19 32H45"),r.setAttribute("stroke",$t.slate300),r.setAttribute("stroke-width","2"),r.setAttribute("stroke-linecap","round"),t.appendChild(r);const o=document.createElementNS("http://www.w3.org/2000/svg","path");return o.setAttribute("d","M23 23L41 41"),o.setAttribute("stroke",$t.action),o.setAttribute("stroke-width","2.5"),o.setAttribute("stroke-linecap","round"),t.appendChild(o),e.appendChild(t),e}();e.appendChild(s);const r=document.createElement("h2");r.className="sv-not-activated-title",r.id="sv-modal-title",r.textContent="This domain isn't allowed",e.appendChild(r);const o=document.createElement("p");o.className="sv-not-activated-message",o.textContent="Sign-in is blocked because this website's domain is not on the SparkVault Identity allowlist for this account.",e.appendChild(o);const a=Ke("sv-not-activated-owner"),l=document.createElement("span");l.className="sv-not-activated-owner-label",l.textContent="Are you the site owner?";const d=document.createElement("span");d.className="sv-not-activated-owner-hint",d.textContent=this.props.origin?`Add ${this.props.origin} to your verified domains in SparkVault, then reload this page.`:"Add this website's domain to your verified domains in SparkVault, then reload this page.",a.appendChild(l),a.appendChild(d),e.appendChild(a);const c=Ke("sv-not-activated-actions"),h=document.createElement("a");h.className="sv-btn sv-btn-primary sv-not-activated-cta",h.href="https://app.sparkvault.com/company/domains",h.target="_blank",h.rel="noopener noreferrer";const u=document.createElement("span");return u.textContent="Manage domains in SparkVault",h.appendChild(u),h.appendChild(function(){const e=document.createElementNS("http://www.w3.org/2000/svg","svg");e.setAttribute("viewBox","0 0 16 16"),e.setAttribute("width","14"),e.setAttribute("height","14"),e.setAttribute("fill","none"),e.classList.add("sv-not-activated-cta-icon");const t=document.createElementNS("http://www.w3.org/2000/svg","path");return t.setAttribute("d","M6 3h7v7M13 3l-8 8"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","2"),t.setAttribute("stroke-linecap","round"),t.setAttribute("stroke-linejoin","round"),e.appendChild(t),e}()),c.appendChild(h),this.dismissButton=document.createElement("button"),this.dismissButton.className="sv-not-activated-dismiss",this.dismissButton.type="button",this.dismissButton.textContent="Dismiss",this.dismissButton.addEventListener("click",this.boundHandleClose),c.appendChild(this.dismissButton),e.appendChild(c),e}destroy(){this.dismissButton&&this.dismissButton.removeEventListener("click",this.boundHandleClose)}}function Ft(){if("undefined"==typeof window)return null;const e=window.__sparkvaultProgress;return e&&"function"==typeof e.start?e:null}function Dt(){Ft()?.start()}function Vt(e){const t=e?.trim();return t?`Sign-in for ${t} is temporarily unavailable. Please contact them for assistance.`:"Sign-in is temporarily unavailable. Please contact the site owner for assistance."}const zt=new Set(Tt),Ut={message:["Connection blocked by security policy.","Please contact the site administrator to add wss://ws.sparkvault.com","to the Content-Security-Policy connect-src directive."].join(" "),code:"sparklink_csp_blocked"};class jt{constructor(e,t,n,i,s=null,r={ok:!0,types:null}){this.identityPrefilled=!1,this.currentView=null,this.focusTimeoutId=null,this.morphTimer=null,this.discoverableVerifyAbort=null,this.postLoginResult=null,this.postLoginQueue=[],this.sparkLinkWs=null,this.sparkLinkKindling=null,this.sparkLinkVisibilityHandler=null,this.sparkLinkClaiming=!1,this.sparkLinkRetryTimer=null,this.pageRestoreHandler=null,this.referenceAsk=null,this.referenceAsks=0,this.untouchedStep=null,this.statusRegion=null,this.container=e,this.api=t,this.options=n,this.callbacks=i,this.federationReturn=s;const o=$e(this.api.accountId);this.federationMayAutoStart=null===s&&!o,this.verificationState=new Oe,this.passkeyHandler=new He(t,this.verificationState),this.otpHandler=new Fe(t,this.verificationState),this.sparkLinkHandler=new De(t,this.verificationState),this.identityTypesUnreadable=!r.ok,this.verificationState.setIdentityTypes(r.ok?r.types:null),this.applyInitialIdentity(),n.authContext&&this.verificationState.setAuthContext(n.authContext);const{signinRef:a,completesInWindow:l}=n;this.askReference="function"==typeof a?a:null,this.verificationState.setSigninRef(Q(a)?a:null),this.offeredWithoutReference=void 0===a&&!0===l}applyInitialIdentity(){const e="string"==typeof this.options.phone&&this.options.phone.length>0,t=e?this.options.phone:this.options.email;if(!t)return;const n=e||"phone"===Le(t)?"phone":"email";ie(n,this.verificationState.identityTypes)&&("phone"===n?this.verificationState.setIdentity(Ae(t)??t,"phone"):this.verificationState.setIdentity(Je(t)??t,"email"),this.identityPrefilled=!0)}isIdentityFixed(){return this.identityPrefilled&&void 0!==this.verificationState.authContext?.simpleMode}safeOnSuccess(e){try{this.callbacks.onSuccess(e)}catch(e){console.warn("[SparkVault SDK] onSuccess threw, continuing to redirect",e)}}get recipient(){return this.verificationState.recipient}get identityType(){return this.verificationState.identityType}get sdkConfig(){return this.verificationState.sdkConfig}async start(){this.requestReference();let e=null;if(this.api.isConfigPreloaded()){const t=new Promise(e=>setTimeout(()=>e(null),50));try{const n=await Promise.race([this.api.getConfig().then(e=>e),t]);null!==n&&(e=n)}catch{}}this.container.createLoading({backdropBlur:this.options.backdropBlur},()=>this.handleClose()),this.placeStatusRegion();try{e||(this.setState({view:"loading"}),e=await this.fetchConfigWithRetry()),this.verificationState.setConfig(e),e.branding&&this.container.updateBranding(e.branding),await this.showInitialAuthStep()}catch(e){this.setState(this.viewStateForConfigError(e))}}showStartupError(e){this.container.isOpen()||(this.container.createLoading({backdropBlur:this.options.backdropBlur},()=>this.handleClose()),this.placeStatusRegion()),this.setState(this.viewStateForConfigError(e))}viewStateForConfigError(e){if(e instanceof ke){if("product_not_configured"===e.code)return{view:"product-not-configured"};if("ORIGIN_NOT_ALLOWED"===e.code){return{view:"origin-not-allowed",origin:"string"==typeof e.details?.origin?e.details.origin:void 0}}}return{view:"service-unavailable"}}async fetchConfigWithRetry(){try{return await this.api.getConfig()}catch(e){if(!(e instanceof ke&&"network_error"===e.code))throw e;return await new Promise(e=>setTimeout(e,1e3)),this.api.getConfig()}}async retryConfigLoad(){this.setState({view:"loading"});try{const e=await this.fetchConfigWithRetry();this.verificationState.setConfig(e),e.branding&&this.container.updateBranding(e.branding),await this.showInitialAuthStep()}catch(e){this.setState(this.viewStateForConfigError(e))}}close(){this.api.abort(),this.referenceAsks+=1,this.discoverableVerifyAbort?.abort(),this.discoverableVerifyAbort=null,null!==this.focusTimeoutId&&(clearTimeout(this.focusTimeoutId),this.focusTimeoutId=null),null!==this.morphTimer&&(clearTimeout(this.morphTimer),this.morphTimer=null),this.pageRestoreHandler&&(window.removeEventListener("pageshow",this.pageRestoreHandler),this.pageRestoreHandler=null),this.statusRegion?.destroy(),this.statusRegion=null,this.cleanupSparkLink(),this.destroyCurrentView(),this.container.destroy()}handleClose(){this.close(),this.callbacks.onCancel()}get viewState(){return this.verificationState.viewState}setState(e){this.verificationState.setViewState(e),this.render()}async showInitialAuthStep(){if(this.identityTypesUnreadable)return void this.setState({view:"error",code:Bt,message:"This sign-in link is not valid. Contact the site you came from for help."});const e=this.verificationState.signinRef;this.startWithFederation()||(await this.showSignInStep(),this.untouchedStep=this.currentView,this.verificationState.signinRef!==e&&this.offerArrivedReference())}startWithFederation(){return"failed"===this.federationReturn?(this.federationReturn=null,this.setState(this.federationFailedState()),!0):this.startFederationAutomatically()}startFederationAutomatically(){const e=this.federation;return!!this.federationStartsOnItsOwn(e)&&(this.leaveForFederation({silent:e.silent,automatic:!0}).catch(e=>this.handleErrorWithRecovery(e,"unknown")),!0)}federationStartsOnItsOwn(e){return null!==e&&this.federationMayAutoStart&&(e.silent||"federation"===this.options.method)}federationAwaitingReference(e){return"pending"===this.referenceAsk&&this.offersFederationBeside(e)?this.accountFederation:null}requestReference(){const e=this.askReference;if(!e)return;const t=++this.referenceAsks;this.referenceAsk="pending",new Promise(t=>{t(e())}).catch(()=>null).then(e=>{t===this.referenceAsks&&(Q(e)?this.referenceArrived(e):this.referenceUnavailable())})}referenceArrived(e){this.referenceAsk=null,this.verificationState.setSigninRef(e),this.offerArrivedReference()}referenceUnavailable(){this.referenceAsk="unavailable","awaiting-reference"===this.viewState.view&&this.showMethodSelect()}retryReference(){this.requestReference(),this.showSignInStep()}offerArrivedReference(){const e=this.viewState;if(!("awaiting-reference"===e.view||"identity-input"===e.view||"method-select"===e.view&&this.offersFederationBeside(e.email)))return;if(null!==this.untouchedStep&&this.currentView===this.untouchedStep&&this.startFederationAutomatically())return;if("awaiting-reference"===e.view)return void this.showMethodSelect();const t=this.leadingFederationMethod();if(!t)return;const n=this.currentView;n instanceof ft?n.offerLeadingMethod(t):n instanceof gt&&"method-select"===e.view&&!e.methods.some(e=>"federation"===e.type)&&(n.offerLeadingMethod(t.method),this.verificationState.setViewState({...e,methods:[t.method,...e.methods]}))}async showSignInStep(){this.recipient||0===this.getAllowedIdentityTypes().length?await this.showMethodSelect():!this.canDiscoverableVerify()||this.federationStartsOnItsOwn(this.federationAwaitingReference(this.recipient))?this.showIdentityInput():this.launchDiscoverableVerify()}canDiscoverableVerify(){if(!this.passkeyHandler.canAutoVerify())return!1;return this.admittedMethods(Be(this.verificationState.methodIds)).some(e=>"passkey"===e.type)}async launchDiscoverableVerify(){this.discoverableVerifyAbort=new AbortController;const{signal:e}=this.discoverableVerifyAbort;this.setState({view:"passkey-auto"});const t=await this.passkeyHandler.verify(e);e.aborted||(this.discoverableVerifyAbort=null,this.applyTerminalPasskeyResult(t)||this.showIdentityInput())}cancelDiscoverableVerify(){this.discoverableVerifyAbort?.abort(),this.discoverableVerifyAbort=null,this.showIdentityInput()}render(){const e=this.container.getBody();if(!e)return;this.destroyCurrentView();this.container.setMinimalChrome(["product-not-configured","origin-not-allowed"].includes(this.viewState.view));const t=this.createViewForState(this.viewState);this.currentView=t,this.statusRegion?.announce(t.announcement??"");const n=t.render();n.classList.add("sv-step-enter"),this.morphSwap(e,n),"loading"===this.viewState.view||"awaiting-reference"===this.viewState.view?Dt():Ft()?.done();const i=e.querySelector("input:not([disabled]), button.sv-btn-primary:not([disabled]), button.sv-btn-email-primary:not([disabled]), button.sv-btn-method:not([disabled])");i&&(null!==this.focusTimeoutId&&clearTimeout(this.focusTimeoutId),this.focusTimeoutId=setTimeout(()=>i.focus(),50))}placeStatusRegion(){const e=this.container.getBody();e&&!this.statusRegion?.element.isConnected&&(this.statusRegion?.destroy(),this.statusRegion=function(e){const t=document.createElement("div");t.className=e,t.setAttribute("role","status"),t.setAttribute("aria-live","polite"),t.setAttribute("aria-atomic","true");let n=null;const i=()=>{null!==n&&clearTimeout(n),n=null};return{element:t,announce(e){i(),e?n=setTimeout(()=>{n=null,t.textContent=e},100):t.textContent=""},destroy(){i(),t.remove()}}}("sv-sr-only"),e.insertAdjacentElement("beforebegin",this.statusRegion.element))}destroyCurrentView(){this.currentView?.destroy&&this.currentView.destroy(),this.currentView=null}morphSwap(e,t){const n=e.getBoundingClientRect().height;Ge(e),e.appendChild(t);const i="undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,s=e.getBoundingClientRect().height;if(i||n<1||s<1||Math.abs(s-n)<1)return;const r=()=>{null!==this.morphTimer&&(clearTimeout(this.morphTimer),this.morphTimer=null),e.removeEventListener("transitionend",o),e.style.height="",e.style.overflow="",e.style.transition="",e.style.boxSizing=""},o=t=>{const n=t.propertyName;t.target===e&&"height"===n&&r()};e.style.boxSizing="border-box",e.style.overflow="hidden",e.style.height=`${n}px`,e.offsetHeight,e.style.transition="height var(--sv-dur-slow) var(--sv-ease-out)",e.style.height=`${s}px`,e.addEventListener("transitionend",o),null!==this.morphTimer&&clearTimeout(this.morphTimer),this.morphTimer=setTimeout(r,550)}createViewForState(e){switch(e.view){case"loading":case"awaiting-reference":return new Xe({message:"Loading..."});case"identity-input":return new ft({allowedTypes:this.getAllowedIdentityTypes(),initialValue:this.recipient,error:e.error,onSubmit:e=>this.handleIdentitySubmit(e),onPasskey:this.canDiscoverableVerify()?()=>{this.launchDiscoverableVerify()}:void 0,leadingMethod:this.leadingFederationMethod(),onType:()=>{this.untouchedStep=null}});case"method-select":return new gt({email:e.email,identityType:this.identityType,methods:e.methods,onSelectMethod:e=>this.handleMethodSelect(e,!0),onBack:e.email&&!this.isIdentityFixed()?()=>this.showIdentityInput():void 0});case"otp-verify":return new bt({email:e.email,method:e.method,error:e.error,backoffExpires:e.backoffExpires,onSubmit:e=>this.handleOtpSubmit(e),onResend:()=>this.handleOtpResend(),onBack:()=>this.showMethodSelect()});case"two-factor":return new kt({methods:e.methods,error:e.error,onSubmit:e=>this.handleSecondFactorSubmit(e)});case"passkey":{const{passkey:t}=this.verificationState,n="register"===e.mode&&null!==t.pendingResult;return new wt({identityLabel:e.recipient,mode:e.mode,error:e.error,onStart:()=>this.handlePasskeyStart(),onBack:n?()=>this.handlePasskeyRegistrationSkip():"verify"===e.mode?this.passkeyFallbackMethodsAvailable()?()=>this.showMethodSelect({autoRoute:!1}):this.recipient&&!this.isIdentityFixed()?()=>this.showIdentityInput():void 0:()=>this.showMethodSelect(),onFallback:t.hasPasskey&&!t.isFallbackMode&&this.passkeyFallbackMethodsAvailable()?()=>this.handlePasskeyFallback():void 0})}case"passkey-auto":return new xt({onUseAnotherMethod:()=>this.cancelDiscoverableVerify()});case"passkey-prompt":return new Ct({identityLabel:e.recipient,onAddPasskey:()=>this.handlePasskeyPromptAdd(e.pendingResult),onSkip:()=>this.handlePasskeyPromptSkip(e.pendingResult),error:e.error});case"backup-verify":return new St({missingType:e.missingType,error:e.error,onSubmit:e=>this.handleBackupSubmit(e),onSkip:()=>this.handleBackupSkip()});case"backup-code":return new bt({email:e.value,method:e.method,error:e.error,onSubmit:e=>this.handleBackupCodeSubmit(e),onResend:()=>this.handleBackupResend(),onBack:()=>this.setState({view:"backup-verify",missingType:e.missingType,pendingResult:e.pendingResult})});case"sparklink-waiting":return new Et({email:e.email,expiresAt:e.expiresAt,onResend:()=>this.handleSparkLinkResend(),onFallback:()=>this.handleSparkLinkFallback(),onBack:()=>this.showMethodSelect(),onExpired:()=>this.cleanupSparkLink()});case"oauth-pending":return new Xe({message:`Connecting to ${e.provider}...`});case"federation-checking":return new Xe({message:`Checking your ${e.displayName} sign-in…`,announce:!0});case"error":return new Pt({message:e.message,code:e.code,onRetry:e.code===_e?()=>{this.showSignInStep()}:e.code===It?()=>this.retryReference():e.code===ee.refusalCode?()=>this.chooseAnotherWay():()=>this.showIdentityInput(),onClose:()=>this.handleClose()});case"service-unavailable":return new Mt({onRetry:()=>this.retryConfigLoad(),onClose:()=>this.handleClose()});case"product-not-configured":return new Nt({onClose:()=>this.handleClose()});case"origin-not-allowed":return new Ht({origin:e.origin,onClose:()=>this.handleClose()})}}showIdentityInput(e){this.setState({view:"identity-input",error:e})}async showMethodSelect(e={}){this.cleanupSparkLink();const t=!1!==e.autoRoute;if(!this.sdkConfig)return;const n=this.verificationState.methodIds;if(!Array.isArray(n))return void this.setState({view:"error",message:"Invalid configuration",code:"invalid_config"});const i=this.federationAwaitingReference(this.recipient);let s=this.admittedMethods(Be(n));if(this.recipient){s=s.filter(e=>"phone"===this.identityType?"passkey"===e.type||"phone"===e.identityType:"email"===e.identityType||void 0===e.identityType);const{passkey:e}=this.verificationState;null===e.hasPasskey&&s.some(e=>"passkey"===e.type)&&await this.passkeyHandler.checkPasskey(),!1===this.verificationState.passkey.hasPasskey&&(s=s.filter(e=>"passkey"!==e.type))}else s=s.filter(e=>"passkey"===e.type||"social"===e.type);if(this.verificationState.passkey.isFallbackMode&&(s=s.filter(e=>"passkey"!==e.type)),this.offersFederationBeside(this.recipient)&&(s=[...Be(["federation"],this.federation),...s]),0===s.length)return void this.setState(this.noMethodState());if(t&&!this.federationStartsOnItsOwn(i)&&!0===this.verificationState.passkey.hasPasskey&&!this.verificationState.passkey.isFallbackMode&&s.some(e=>"passkey"===e.type))return void this.launchPasskeyVerify(!0);const r=this.identityPrefilled&&"phone"===s[0].identityType,o="federation"===s[0].type&&!this.federationMayAutoStart;1!==s.length||this.isIdentityFixed()||r||o||null!==i?this.setState({view:"method-select",email:this.recipient,methods:s}):this.handleMethodSelect(s[0])}noMethodState(){if(this.verificationState.passkeyRequired&&!1===this.verificationState.passkey.hasPasskey)return{view:"error",code:At,message:(e="request",t=this.sdkConfig?.branding?.companyName,`This ${e} requires a passkey already registered with SparkVault. Ask ${t||"the sender"} to resend it at a different verification level.`)};var e,t;if(this.accountFederation&&!this.federationOffered){if(!this.askReference){const e=this.sdkConfig?.federation?.display_name?.trim();return{view:"error",code:Lt,message:`This site needs to update its sign-in to use ${e||"your organization's sign-in"}.`}}return"unavailable"===this.referenceAsk?{view:"error",code:It,message:"We couldn't start sign-in. Try again."}:{view:"awaiting-reference"}}const n=this.verificationState.identityTypes;return n&&this.verificationState.methodIds.some(e=>!se(e,n))?{view:"error",code:Rt,message:oe(n)}:{view:"error",message:"No authentication methods available",code:"no_methods"}}admittedMethods(e){const t=this.verificationState.identityTypes;return e.filter(e=>se(e.id,t))}chooseAnotherWay(){this.recipient||0===this.getAllowedIdentityTypes().length?this.showMethodSelect({autoRoute:!1}):this.showIdentityInput()}renderIdentityTypeRefusal(e,t){return!(e!==ee.refusalCode||!t)&&(this.setState({view:"error",code:e,message:t}),!0)}handleIdentitySubmit(e){this.verificationState.setIdentity(e.value,e.type),this.identityPrefilled=!1,this.showMethodSelect()}getAllowedIdentityTypes(){const e=this.verificationState.getAllowedIdentityTypes(),t=this.verificationState.identityTypes;return t?e.filter(e=>t.includes(e)):e}async handleMethodSelect(e,t=!1){try{switch(e.type){case"otp":{const t="otp_sms"===e.id?"sms":"otp_voice"===e.id?"voice":"email";this.setState({view:"loading"});const n=await this.otpHandler.send(t);if(!n.success){if(this.renderBlockedInterstitial(n.errorCode))return;if(this.renderIdentityTypeRefusal(n.errorCode,n.error))return;return void this.setState({view:"error",message:n.error??"Failed to send code",code:"otp_send_failed"})}this.setState({view:"otp-verify",email:this.recipient,method:t,kindling:this.verificationState.otp.kindling});break}case"passkey":t?await this.launchPasskeyVerify():this.setState({view:"passkey",recipient:this.recipient,mode:"verify"});break;case"sparklink":{this.setState({view:"loading"});const e=await this.openSparkLinkWebSocket();if("error"in e)return this.cleanupSparkLink(),void("csp"===e.error?this.setState({view:"error",...Ut}):this.setState({view:"error",message:"Failed to establish connection",code:"sparklink_ws_failed"}));const t=await this.sparkLinkHandler.send(e.connectionId);if(!t.success){if(this.cleanupSparkLink(),this.renderBlockedInterstitial(t.errorCode))return;if(this.renderIdentityTypeRefusal(t.errorCode,t.error))return;return void this.setState({view:"error",message:t.error??"Failed to send SparkLink",code:"sparklink_send_failed"})}this.sparkLinkKindling=t.kindling??null,this.armSparkLinkRefocusClaim(),this.setState({view:"sparklink-waiting",email:this.recipient,expiresAt:t.expiresAt});break}case"social":e.provider&&await this.handleSocialLogin(e.provider);break;case"federation":await this.leaveForFederation({silent:!1,automatic:!t});break;default:this.setState({view:"error",message:`Authentication method not supported: ${e.type}`,code:"unsupported_method"})}}catch(e){this.handleErrorWithRecovery(e,"unknown")}}renderBlockedInterstitial(e){return!(!e||!zt.has(e))&&(this.setState({view:"error",code:e,message:Vt(this.verificationState.sdkConfig?.branding?.companyName)}),!0)}async handleOtpSubmit(e){if("otp-verify"!==this.viewState.view)return;const t=this.verificationState.otp.method??"email";Dt();const n=await this.otpHandler.verify(e);if(n.secondFactor)this.setState({view:"two-factor",ticket:n.secondFactor.ticket,methods:n.secondFactor.methods});else if(n.success&&n.result)this.runPostLogin(n.result);else if(this.renderBlockedInterstitial(n.errorCode));else if(this.renderIdentityTypeRefusal(n.errorCode,n.error));else if("identity_locked"===n.errorCode)this.setState({view:"error",code:"identity_locked",message:"This SparkVault Identity is locked. Visit auth.sv to manage it."});else{if((n.error?.toLowerCase()??"").includes("expired")){const e=await this.otpHandler.resend();return e.success?void this.setState({view:"otp-verify",email:this.recipient,method:t,kindling:this.verificationState.otp.kindling,error:"Code expired. We've sent a new one."}):void this.setState({view:"otp-verify",email:this.recipient,method:t,kindling:this.verificationState.otp.kindling,error:e.error??"Code expired and failed to resend."})}this.setState({view:"otp-verify",email:this.recipient,method:t,kindling:this.verificationState.otp.kindling,error:n.error??"Invalid code. Please try again.",backoffExpires:n.backoffExpires})}}async handleSecondFactorSubmit(e){if("two-factor"!==this.viewState.view)return;const{ticket:t,methods:n}=this.viewState;try{const n=await this.api.submitSecondFactor({ticket:t,code:e}),i={token:n.token??"",identity:n.identity??this.recipient,identityType:n.identity_type??this.identityType,svid:n.svid,sessionId:n.session_id,refreshToken:n.refresh_token,redirect:n.redirect};this.close(),this.safeOnSuccess(i),"string"==typeof i.redirect&&i.redirect&&(window.location.href=i.redirect)}catch(e){const i=e instanceof Error?e.message:"That code is not valid. Please try again.";if(e instanceof ke&&this.renderIdentityTypeRefusal(e.code,i))return;this.setState({view:"two-factor",ticket:t,methods:n,error:i})}}async handleOtpResend(){if("otp-verify"!==this.viewState.view)return;const e=this.verificationState.otp.method??"email",t=await this.otpHandler.resend();if(!t.success){if(this.renderBlockedInterstitial(t.errorCode))return;this.setState({view:"otp-verify",email:this.recipient,method:e,kindling:this.verificationState.otp.kindling,error:t.error??"Failed to resend code"})}}async handlePasskeyStart(){if("passkey"!==this.viewState.view)return;const e=this.viewState.mode,t="register"===e?await this.passkeyHandler.register():await this.passkeyHandler.verify();this.applyPasskeyResult(t,e)}async launchPasskeyVerify(e=!1){this.setState({view:"loading"});const t=await this.passkeyHandler.verify();this.applyPasskeyResult(t,"verify",e)}applyTerminalPasskeyResult(e){return e.success&&e.result?(this.close(),this.safeOnSuccess(e.result),"string"==typeof e.result.redirect&&e.result.redirect&&(window.location.href=e.result.redirect),!0):!!this.renderBlockedInterstitial(e.errorCode)||(!!this.renderIdentityTypeRefusal(e.errorCode,e.error)||"identity_locked"===e.errorCode&&(this.setState({view:"error",code:"identity_locked",message:"This SparkVault Identity is locked. Visit auth.sv to manage it."}),!0))}applyPasskeyResult(e,t,n=!1){this.applyTerminalPasskeyResult(e)||(n&&this.passkeyFallbackMethodsAvailable()?this.showMethodSelect({autoRoute:!1}):"not_found"===e.errorType?this.setState({view:"passkey",recipient:this.recipient,mode:"register",error:e.error}):this.setState({view:"passkey",recipient:this.recipient,mode:t,error:e.error}))}async handlePasskeyFallback(){this.verificationState.enablePasskeyFallback(),await this.showMethodSelect()}passkeyFallbackMethodsAvailable(){if(!this.sdkConfig)return!1;const e=this.admittedMethods(Be(this.verificationState.methodIds,this.federation));return this.recipient?e.some(e=>"passkey"!==e.type&&("federation"===e.type?this.offersFederationBeside(this.recipient):"phone"===this.identityType?"phone"===e.identityType:"email"===e.identityType)):e.some(e=>"social"===e.type||"federation"===e.type)}handlePasskeyRegistrationSkip(){this.verificationState.setPendingResult(null),this.dismissRecommendation("passkey"),this.advancePostLogin()}async handleSocialLogin(e){this.setState({view:"oauth-pending",provider:e});const{state:t}=await this.api.drawAuthorizationValues();sessionStorage.setItem("sv_oauth_state",t);const n=this.api.getSocialAuthUrl(e,pe(),t,this.verificationState.authContext,{signinRef:this.verificationState.signinRef,identityTypes:this.verificationState.identityTypes});window.location.href=n}get federation(){return this.federationOffered?this.accountFederation:null}get federationOffered(){return this.offeredWithoutReference||null!==this.verificationState.signinRef}get accountFederation(){const e=this.sdkConfig?.federation,t=this.verificationState.methodIds;return e&&Array.isArray(t)&&t.includes(J)&&se(J,this.verificationState.identityTypes)?e:null}offersFederationBeside(e){return!e||this.identityPrefilled}leadingFederationMethod(){const[e]=Be(["federation"],this.federation);if(e)return{method:e,onSelect:()=>{this.handleMethodSelect(e,!0)}}}async leaveForFederation({silent:e,automatic:t}){const n=this.federation;if(!n)return;t&&(this.federationMayAutoStart=!1),this.setState(e?{view:"federation-checking",displayName:n.display_name}:{view:"oauth-pending",provider:n.display_name});const{state:i}=await this.api.drawAuthorizationValues();sessionStorage.setItem("sv_oauth_state",i),t&&function(e){try{sessionStorage.setItem(Pe,JSON.stringify({at:Date.now(),accountId:e}))}catch{}}(this.api.accountId),this.watchForPageRestore(),window.location.href=this.api.getFederationAuthUrl(pe(),i,this.verificationState.authContext,{silent:e,signinRef:this.verificationState.signinRef,identityTypes:this.verificationState.identityTypes})}watchForPageRestore(){this.pageRestoreHandler||(this.pageRestoreHandler=e=>{e.persisted&&($e(this.api.accountId),this.federationMayAutoStart=!1,this.showSignInStep())},window.addEventListener("pageshow",this.pageRestoreHandler))}federationFailedState(){const e=this.sdkConfig?.federation?.display_name;return{view:"error",code:_e,message:e?`We couldn't sign you in with ${e}. Please try again.`:"We couldn't sign you in through your organization. Please try again."}}normalizeError(e){return e instanceof ke?new p(e.message,e.code):e instanceof Error?e:new Error(String(e))}isSessionExpiredError(e){const t=e.message.toLowerCase(),n=e instanceof p?e.code:"";return t.includes("expired")||t.includes("session")||t.includes("invalid token")||t.includes("token invalid")||"token_expired"===n||"session_expired"===n||"kindling_expired"===n}handleErrorWithRecovery(e,t){const n=this.normalizeError(e);n instanceof p&&this.renderIdentityTypeRefusal(n.code,n.message)||(this.isSessionExpiredError(n)?this.showIdentityInput("Your session has expired. Please try again."):this.setState({view:"error",message:n.message,code:n instanceof p?n.code:t}))}runPostLogin(e){e.redirect?this.finalizeLogin(e):(this.postLoginResult=e,this.postLoginQueue=[...e.recommendations??[]],this.advancePostLogin())}advancePostLogin(){const e=this.postLoginResult;if(!e)return;const t=this.postLoginQueue.shift();if(!t)return this.postLoginResult=null,void this.finalizeLogin(e);"passkey"===t.type?this.setState({view:"passkey-prompt",recipient:this.recipient,pendingResult:e}):"backup_identifier"===t.type?this.setState({view:"backup-verify",missingType:t.missingType,pendingResult:e}):this.advancePostLogin()}dismissRecommendation(e){const t=this.postLoginResult?.token;t&&this.api.dismissRecommendation({verificationToken:t,key:e}).catch(()=>{})}finalizeLogin(e){this.safeOnSuccess(e),this.close(),"string"==typeof e.redirect&&e.redirect&&(window.location.href=e.redirect)}async handleBackupSubmit(e){if("backup-verify"!==this.viewState.view)return;const{missingType:t,pendingResult:n}=this.viewState;this.setState({view:"loading"});try{const i=await this.api.sendBackupVerification({verificationToken:n.token,type:t,value:e});if(i.already_verified||!i.session_id)return void this.advancePostLogin();this.setState({view:"backup-code",missingType:t,value:e,method:i.method??("phone"===t?"sms":"email"),sessionId:i.session_id,pendingResult:n})}catch(e){this.setState({view:"backup-verify",missingType:t,pendingResult:n,error:e instanceof Error?e.message:"Could not send a code. Please try again."})}}async handleBackupCodeSubmit(e){if("backup-code"!==this.viewState.view)return;const{missingType:t,value:n,method:i,sessionId:s,pendingResult:r}=this.viewState;try{await this.api.verifyBackupVerification({sessionId:s,code:e}),this.advancePostLogin()}catch(e){if("backup_conflict"===(e instanceof ke?e.code:""))return void this.setState({view:"backup-verify",missingType:t,pendingResult:r,error:e instanceof Error?e.message:"That identifier is already linked to another account."});this.setState({view:"backup-code",missingType:t,value:n,method:i,sessionId:s,pendingResult:r,error:e instanceof Error?e.message:"That code is not valid. Please try again."})}}async handleBackupResend(){if("backup-code"!==this.viewState.view)return;const{missingType:e,value:t,method:n,pendingResult:i}=this.viewState;try{const s=await this.api.sendBackupVerification({verificationToken:i.token,type:e,value:t,method:n});s.session_id&&this.setState({view:"backup-code",missingType:e,value:t,method:s.method??n,sessionId:s.session_id,pendingResult:i})}catch{}}handleBackupSkip(){if("backup-verify"!==this.viewState.view)return;const{missingType:e}=this.viewState;this.dismissRecommendation("phone"===e?"backup_phone":"backup_email"),this.advancePostLogin()}async handlePasskeyPromptAdd(e){this.verificationState.setPendingResult(e),this.setState({view:"loading"});const t=await this.passkeyHandler.register(e.token);if(t.success&&t.result)this.postLoginResult=t.result,this.advancePostLogin();else if("cancelled"===t.errorType)this.setState({view:"passkey-prompt",recipient:this.recipient,pendingResult:e});else{const n=t.error||"Failed to create passkey. Please try again.";this.setState({view:"passkey-prompt",recipient:this.recipient,pendingResult:e,error:n})}}handlePasskeyPromptSkip(e){this.dismissRecommendation("passkey"),this.advancePostLogin()}openSparkLinkWebSocket(){this.cleanupSparkLink();const e=this.sdkConfig?.wsDomain||"ws.sparkvault.com",t=`wss://${e}`;return new Promise(n=>{let i=!1,s=!1;const r=t=>{"connect-src"===t.violatedDirective&&t.blockedURI.includes(e)&&(s=!0)};document.addEventListener("securitypolicyviolation",r);const o=()=>{document.removeEventListener("securitypolicyviolation",r)},a=new WebSocket(t);this.sparkLinkWs=a;const l=setTimeout(()=>{i||(i=!0,o(),a.close(),n({error:s?"csp":"connection"}))},1e4);a.onopen=()=>{try{a.send(JSON.stringify({action:"init"}))}catch{i||(i=!0,o(),clearTimeout(l),n({error:"connection"}))}},a.onmessage=e=>{let t;try{t=JSON.parse(e.data)}catch{return}if(!i&&"connection"===t.type&&"string"==typeof t.connectionId)return i=!0,o(),clearTimeout(l),this.setupSparkLinkWsHandler(a),void n({connectionId:t.connectionId})},a.onerror=()=>{i||(i=!0,o(),clearTimeout(l),n({error:s?"csp":"connection"}))},a.onclose=()=>{i||(i=!0,o(),clearTimeout(l),n({error:s?"csp":"connection"}))}})}setupSparkLinkWsHandler(e){e.onmessage=e=>{let t;try{t=JSON.parse(e.data)}catch{return}switch(t.type){case"sparklink_verified":case"sparklink_second_factor":{const e=ye(t);if(!e){this.failSparkLink();break}this.burnSparkLinkFallback(),this.applySparkLinkOutcome(e);break}case"sparklink_failed":this.failSparkLink();break;case"sparklink_resent":"number"==typeof t.expiresAt&&this.setState({view:"sparklink-waiting",email:this.recipient,expiresAt:t.expiresAt})}},e.onclose=()=>{this.sparkLinkWs=null}}applySparkLinkOutcome(e){this.cleanupSparkLink(),"second_factor"!==e.kind?this.runPostLogin(e.result):this.setState({view:"two-factor",ticket:e.ticket,methods:e.methods})}burnSparkLinkFallback(){const e=this.sparkLinkKindling;e&&this.api.consumeSparkLinkResult(e).catch(()=>{})}failSparkLink(){this.cleanupSparkLink(),this.setState({view:"error",message:"Verification failed. Please try again or choose a different method.",code:"sparklink_failed"})}armSparkLinkRefocusClaim(){if(this.sparkLinkVisibilityHandler||!this.sparkLinkKindling)return;if("undefined"==typeof document)return;const e=()=>{"undefined"!=typeof document&&"visible"!==document.visibilityState||this.sparkLinkWs&&this.sparkLinkWs.readyState===WebSocket.OPEN||this.claimSparkLinkResult(!0)};this.sparkLinkVisibilityHandler=e,document.addEventListener("visibilitychange",e),"undefined"!=typeof window&&window.addEventListener("pageshow",e)}async claimSparkLinkResult(e){const t=this.sparkLinkKindling;if(!t||this.sparkLinkClaiming)return;this.sparkLinkClaiming=!0;let n=null;try{n=await this.api.consumeSparkLinkResult(t)}catch{n=null}this.sparkLinkClaiming=!1,n?this.applySparkLinkOutcome(n):e&&this.sparkLinkKindling===t&&(this.sparkLinkRetryTimer=setTimeout(()=>{this.sparkLinkRetryTimer=null,this.sparkLinkKindling===t&&this.claimSparkLinkResult(!1)},2e3))}cleanupSparkLink(){this.sparkLinkWs&&(this.sparkLinkWs.onmessage=null,this.sparkLinkWs.onclose=null,this.sparkLinkWs.onerror=null,this.sparkLinkWs.close(),this.sparkLinkWs=null),this.sparkLinkVisibilityHandler&&("undefined"!=typeof document&&document.removeEventListener("visibilitychange",this.sparkLinkVisibilityHandler),"undefined"!=typeof window&&window.removeEventListener("pageshow",this.sparkLinkVisibilityHandler),this.sparkLinkVisibilityHandler=null),null!==this.sparkLinkRetryTimer&&(clearTimeout(this.sparkLinkRetryTimer),this.sparkLinkRetryTimer=null),this.sparkLinkKindling=null}async handleSparkLinkResend(){const e=await this.openSparkLinkWebSocket();if("error"in e)return this.cleanupSparkLink(),void("csp"===e.error?this.setState({view:"error",...Ut}):this.setState({view:"error",message:"Unable to establish a secure connection. Please try again or choose a different method.",code:"sparklink_ws_failed"}));const t=await this.sparkLinkHandler.send(e.connectionId);if(t.success)this.sparkLinkKindling=t.kindling??null,this.armSparkLinkRefocusClaim(),this.setState({view:"sparklink-waiting",email:this.recipient,expiresAt:t.expiresAt});else{if(this.cleanupSparkLink(),this.renderIdentityTypeRefusal(t.errorCode,t.error))return;this.setState({view:"error",message:t.error??"Failed to resend verification link. Please try again.",code:"sparklink_resend_failed"})}}async handleSparkLinkFallback(){this.cleanupSparkLink(),this.setState({view:"loading"});const e=await this.otpHandler.send("email");if(e.success)this.setState({view:"otp-verify",email:this.recipient,method:"email",kindling:this.verificationState.otp.kindling});else{if(this.renderBlockedInterstitial(e.errorCode))return;if(this.renderIdentityTypeRefusal(e.errorCode,e.error))return;this.setState({view:"error",message:e.error??"Failed to send code",code:"otp_send_failed"})}}}const Wt="sparkvault-identity-styles";function qt(e){if(document.getElementById(Wt))return Kt(e.branding),void function(e){const t=document.getElementById("sparkvault-identity-overlay");t&&(!1!==e?t.classList.add("sv-blur"):t.classList.remove("sv-blur"))}(e.backdropBlur);const t=document.createElement("style");t.id=Wt,t.dataset.svTheme=Gt(e.branding),t.textContent=Yt(e),document.head.appendChild(t)}function Kt(e){const t=document.getElementById(Wt);if(!t)return;const n=Gt(e);t.dataset.svTheme!==n&&(t.dataset.svTheme=n,t.textContent=Yt({branding:e??{companyName:"",logoLight:null,logoDark:null}}))}function Gt(e){return e?.themeMode??"light"}function Yt(e){const{branding:t,backdropBlur:n}=e,i="dark"===Gt(t),s=!1!==n,r=`var(--sv-primary, ${$t.action})`,o=i?$t.slate950:$t.white,a=`color-mix(in srgb, ${r} 80%, white)`,l=r,d=`var(--sv-primary-hover, ${$t.actionHover})`,c=`color-mix(in srgb, ${r} ${i?"20%":"9%"}, transparent)`,h=i?$t.error500:$t.error,u=i?Ot($t.error500,.12):$t.errorBg,p=Ot($t.error500,.35),m=$t.btnDanger,f=$t.btnDangerHover,v=i?$t.warning500:$t.warning,g=o,y=i?$t.darkCard:$t.slate50,b=i?Ot($t.white,.08):$t.slate100,k=i?Ot($t.white,.04):$t.white,w=i?$t.darkHairline:$t.slate200,x=i?Ot($t.white,.18):$t.slate300,C=r,S=i?Ot($t.white,.35):$t.slate300,E=i?$t.darkText:$t.slate900,T=i?$t.darkTextMuted:$t.slate600,A=i?Ot($t.white,.45):$t.slate500,L=$t.white,I=`0 0 0 2px ${o}, 0 0 0 4px ${a}`,R=i?"0 1px 2px rgba(0, 0, 0, 0.4)":$t.shadowSm,B=(i||$t.shadowMd,i?`0 8px 24px rgba(0, 0, 0, 0.5), 0 0 0 1px ${$t.darkHairline}`:$t.shadowPopover);return`\n /* ========================================\n MOTION SYSTEM: shared duration/easing tokens so every transition in\n the flow is consistent. 120/180/280ms tiers; standard and decelerate\n curves only, never overshoot.\n ======================================== */\n :root {\n --sv-dur-instant: 120ms;\n --sv-dur-fast: 120ms;\n --sv-dur-base: 180ms;\n --sv-dur-slow: 280ms;\n --sv-dur-slower: 280ms;\n --sv-ease-standard: cubic-bezier(0.2, 0, 0, 1);\n --sv-ease-out: cubic-bezier(0, 0, 0.2, 1);\n --sv-ease-accelerate: cubic-bezier(0.2, 0, 0, 1);\n --sv-ease-spring: cubic-bezier(0.2, 0, 0, 1);\n }\n\n /* Each mounted view enters with a calm fade + rise. Applied by the renderer\n on every step change; the brand lockup and footer never move. */\n @keyframes sv-step-in {\n from { opacity: 0; transform: translateY(8px); }\n to { opacity: 1; transform: none; }\n }\n .sv-step-enter { animation: sv-step-in var(--sv-dur-base) var(--sv-ease-out) both; }\n\n /* The top progress bar itself is owned and styled by the sign-in page\n (login-popup.js); the renderer only drives it via window.__sparkvaultProgress. */\n\n @media (prefers-reduced-motion: reduce) {\n .sv-step-enter { animation-duration: 1ms; }\n }\n\n /* ========================================\n OVERLAY & MODAL CONTAINER\n ======================================== */\n\n .sv-overlay {\n position: fixed;\n inset: 0;\n background: ${i?"rgba(0, 0, 0, 0.7)":$t.modalOverlay};\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: 999999;\n padding: 16px;\n box-sizing: border-box;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n }\n\n .sv-overlay.sv-blur {\n backdrop-filter: blur(${s?"8px":"0"});\n -webkit-backdrop-filter: blur(${s?"8px":"0"});\n }\n\n .sv-modal {\n background: ${g};\n border-radius: 12px;\n box-shadow: ${B};\n width: 100%;\n max-width: 400px;\n max-height: calc(100vh - 32px);\n display: flex;\n flex-direction: column;\n color: ${E};\n }\n\n /* ========================================\n HEADER\n ======================================== */\n\n .sv-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 14px 20px;\n border-bottom: 1px solid ${w};\n background: ${g};\n border-radius: 12px 12px 0 0;\n flex-shrink: 0;\n }\n\n .sv-header-title {\n display: flex;\n align-items: center;\n gap: 12px;\n min-width: 0;\n }\n\n .sv-logo {\n height: 28px;\n width: auto;\n max-width: 140px;\n object-fit: contain;\n flex-shrink: 0;\n }\n\n .sv-company-name {\n font-size: 15px;\n font-weight: 600;\n letter-spacing: -0.01em;\n margin: 0;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n }\n\n .sv-close-btn {\n flex-shrink: 0;\n width: 32px;\n height: 32px;\n display: flex;\n align-items: center;\n justify-content: center;\n background: ${y};\n border: none;\n border-radius: 6px;\n cursor: pointer;\n color: ${T};\n transition: background var(--sv-dur-fast) var(--sv-ease-standard), color var(--sv-dur-fast) var(--sv-ease-standard);\n }\n\n .sv-close-btn:hover {\n background: ${b};\n color: ${E};\n }\n\n .sv-close-btn:focus-visible {\n outline: none;\n box-shadow: ${I};\n }\n\n /* ========================================\n BODY\n ======================================== */\n\n .sv-body {\n padding: 24px 28px;\n overflow-y: auto;\n flex: 1;\n }\n\n /* ========================================\n TYPOGRAPHY\n ======================================== */\n\n .sv-title {\n font-size: 21px;\n font-weight: 600;\n letter-spacing: -0.02em;\n line-height: 1.22;\n margin: 0 0 7px 0;\n text-align: left;\n color: ${E};\n }\n\n .sv-subtitle {\n font-size: 14px;\n font-weight: 400;\n line-height: 1.5;\n color: ${T};\n margin: 0 0 16px 0;\n text-align: left;\n text-wrap: balance;\n }\n\n /* Icon-led ceremony screens (passkey set-up / sign-in) are a fully\n centered composition: the headline and subtitle follow the glyph. */\n div:has(> .sv-passkey-icon) ~ .sv-title,\n div:has(> .sv-passkey-icon) ~ .sv-subtitle {\n text-align: center;\n }\n\n .sv-subtitle strong {\n color: ${E};\n font-weight: 500;\n }\n\n /* ========================================\n FORM ELEMENTS\n ======================================== */\n\n .sv-form-group {\n margin-bottom: 16px;\n }\n\n .sv-label {\n display: block;\n font-size: 13px;\n font-weight: 500;\n letter-spacing: -0.005em;\n margin-bottom: 6px;\n color: ${E};\n }\n\n .sv-input {\n width: 100%;\n padding: 13px 14px;\n font-size: 15px;\n font-weight: 400;\n line-height: 1.4;\n border: 1px solid ${w};\n border-radius: 8px;\n background: ${k};\n color: ${E};\n box-sizing: border-box;\n box-shadow: ${R};\n transition: border-color var(--sv-dur-fast) var(--sv-ease-standard), box-shadow var(--sv-dur-fast) var(--sv-ease-standard);\n }\n\n .sv-input:hover:not(:focus):not(:disabled) {\n border-color: ${x};\n }\n\n .sv-input:focus {\n outline: none;\n border-color: ${C};\n box-shadow: 0 0 0 3px ${c};\n }\n\n .sv-input::placeholder {\n color: ${A};\n }\n\n .sv-input:disabled {\n opacity: 0.5;\n cursor: not-allowed;\n }\n\n .sv-input.sv-input-error,\n .sv-input.sv-email-input-error {\n border-color: ${h};\n }\n\n .sv-input.sv-input-error:focus,\n .sv-input.sv-email-input-error:focus {\n box-shadow: 0 0 0 3px ${u};\n }\n\n /* ========================================\n BUTTONS\n ======================================== */\n\n .sv-btn {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n gap: 8px;\n width: 100%;\n padding: 14px 16px;\n font-size: 15px;\n font-weight: 600;\n letter-spacing: -0.006em;\n line-height: 1.35;\n border: none;\n border-radius: 8px;\n cursor: pointer;\n transition: background var(--sv-dur-fast) var(--sv-ease-standard), box-shadow var(--sv-dur-fast) var(--sv-ease-standard);\n box-sizing: border-box;\n }\n\n .sv-btn:focus-visible {\n outline: none;\n box-shadow: ${I};\n }\n\n .sv-btn:disabled {\n opacity: 0.5;\n cursor: not-allowed;\n }\n\n /* Press = visual compression via an inset shadow, never scale. */\n .sv-btn:active:not(:disabled) {\n box-shadow: inset 0 1px 2px ${Ot($t.slate900,.2)};\n }\n\n /* Primary Button */\n .sv-btn-primary,\n .sv-btn-email-primary {\n background: ${l};\n color: ${L};\n box-shadow: ${R};\n }\n\n .sv-btn-primary:hover:not(:disabled),\n .sv-btn-email-primary:hover:not(:disabled) {\n background: ${d};\n }\n\n /* Secondary Button, quiet: subtle fill, hairline border */\n .sv-btn-secondary {\n background: ${y};\n color: ${E};\n border: 1px solid ${w};\n }\n\n .sv-btn-secondary:hover:not(:disabled) {\n background: ${b};\n border-color: ${x};\n }\n\n /* Method Button: a full-width row with a nudging chevron affordance\n (added via ::after so no DOM change is needed). The card itself stays\n planted: hover is a quiet fill + border shift, no translate. */\n .sv-btn-method {\n position: relative;\n background: ${g};\n border: 1px solid ${w};\n border-radius: 10px;\n color: ${E};\n text-align: left;\n padding: 15px 40px 15px 14px;\n margin-bottom: 9px;\n transition: background var(--sv-dur-fast) var(--sv-ease-standard), border-color var(--sv-dur-fast) var(--sv-ease-standard);\n }\n\n .sv-btn-method::after {\n content: "";\n position: absolute;\n right: 16px;\n top: 50%;\n width: 8px;\n height: 8px;\n border-right: 1.6px solid ${S};\n border-top: 1.6px solid ${S};\n transform: translateY(-50%) rotate(45deg);\n transition: transform var(--sv-dur-base) var(--sv-ease-out), border-color var(--sv-dur-fast) var(--sv-ease-standard);\n }\n\n .sv-btn-method:hover:not(:disabled)::after {\n transform: translateY(-50%) translateX(3px) rotate(45deg);\n border-color: ${l};\n }\n\n .sv-btn-method:focus-visible {\n outline: none;\n box-shadow: ${I};\n }\n\n .sv-btn-method:hover:not(:disabled) {\n background: ${y};\n border-color: ${x};\n }\n\n .sv-btn-method:last-child {\n margin-bottom: 0;\n }\n\n /* Error Buttons */\n .sv-btn-error-primary {\n background: ${m};\n color: ${L};\n box-shadow: ${R};\n }\n\n .sv-btn-error-primary:hover:not(:disabled) {\n background: ${f};\n }\n\n .sv-btn-error-secondary {\n background: ${y};\n color: ${T};\n border: 1px solid ${w};\n }\n\n .sv-btn-error-secondary:hover:not(:disabled) {\n background: ${b};\n color: ${E};\n }\n\n /* ========================================\n METHOD SELECTION\n ======================================== */\n\n .sv-method-content {\n display: flex;\n align-items: center;\n gap: 12px;\n width: 100%;\n }\n\n /* Bare glyph slot, no container chrome. Quiet slate stroke that takes\n the accent on row hover. */\n .sv-method-icon {\n width: 20px;\n height: 20px;\n flex-shrink: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n color: ${A};\n transition: color var(--sv-dur-fast) var(--sv-ease-standard);\n }\n\n .sv-btn-method:hover:not(:disabled) .sv-method-icon {\n color: ${l};\n }\n\n .sv-method-icon svg {\n width: 20px;\n height: 20px;\n }\n\n .sv-method-text {\n flex: 1;\n min-width: 0;\n }\n\n .sv-method-name {\n font-weight: 600;\n font-size: 15px;\n color: ${E};\n }\n\n .sv-method-description {\n font-size: 13px;\n color: ${A};\n margin-top: 1px;\n }\n\n /* ========================================\n OTP INPUT\n ======================================== */\n\n .sv-otp-input-group {\n display: flex;\n gap: 8px;\n justify-content: center;\n margin-bottom: 16px;\n }\n\n .sv-otp-digit {\n width: 46px;\n height: 56px;\n text-align: center;\n font-size: 22px;\n font-weight: 600;\n letter-spacing: 0;\n font-variant-numeric: tabular-nums;\n caret-color: transparent;\n border: 1px solid ${w};\n border-radius: 8px;\n background: ${k};\n color: ${E};\n box-sizing: border-box;\n transition: border-color var(--sv-dur-fast) var(--sv-ease-standard), box-shadow var(--sv-dur-fast) var(--sv-ease-standard);\n }\n\n .sv-otp-digit:hover:not(:focus):not(:disabled) {\n border-color: ${x};\n }\n\n .sv-otp-digit:focus {\n outline: none;\n border-color: ${C};\n box-shadow: 0 0 0 3px ${c};\n }\n\n .sv-otp-digit:disabled {\n opacity: 0.5;\n cursor: not-allowed;\n }\n\n /* ========================================\n BACK LINK\n ======================================== */\n\n .sv-back-link {\n display: inline-flex;\n align-items: center;\n gap: 4px;\n color: ${T};\n font-size: 13px;\n font-weight: 500;\n text-decoration: none;\n cursor: pointer;\n background: none;\n border: none;\n padding: 0;\n margin-bottom: 16px;\n transition: color var(--sv-dur-fast) var(--sv-ease-standard);\n }\n\n .sv-back-link:hover:not(:disabled) {\n color: ${l};\n }\n\n .sv-back-link:disabled {\n opacity: 0.5;\n cursor: not-allowed;\n }\n\n .sv-back-link svg {\n width: 14px;\n height: 14px;\n }\n\n /* ========================================\n ERROR MESSAGE\n ======================================== */\n\n .sv-error {\n background: ${u};\n border: 1px solid ${p};\n color: ${h};\n padding: 10px 12px;\n border-radius: 8px;\n font-size: 13px;\n font-weight: 500;\n margin-bottom: 16px;\n }\n\n /* ========================================\n LOADING STATE\n ======================================== */\n\n .sv-loading {\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n padding: 48px 24px;\n gap: 16px;\n }\n\n .sv-spinner {\n width: 28px;\n height: 28px;\n border: 2.5px solid ${w};\n border-top-color: ${l};\n border-radius: 50%;\n animation: sv-spin 0.7s linear infinite;\n }\n\n .sv-loading-text {\n font-size: 14px;\n color: ${T};\n margin: 0;\n }\n\n @keyframes sv-spin {\n to { transform: rotate(360deg); }\n }\n\n /* ========================================\n FOOTER\n ======================================== */\n\n .sv-footer {\n padding: 10px 20px;\n text-align: center;\n flex-shrink: 0;\n }\n\n .sv-footer-text {\n font-size: 10px;\n color: ${A};\n letter-spacing: 0.02em;\n }\n\n .sv-footer-link {\n color: ${T};\n text-decoration: none;\n font-weight: 500;\n transition: color var(--sv-dur-fast) var(--sv-ease-standard);\n }\n\n .sv-footer-link:hover {\n color: ${l};\n }\n\n /* ========================================\n IDENTITY INPUT VIEW\n ======================================== */\n\n .sv-email-view {\n display: flex;\n flex-direction: column;\n }\n\n .sv-email-header {\n margin-bottom: 16px;\n }\n\n .sv-email-subtitle {\n font-size: 14px;\n font-weight: 500;\n line-height: 1.4;\n color: ${T};\n margin: 0;\n }\n\n .sv-email-error-container {\n width: 100%;\n }\n\n .sv-email-form {\n width: 100%;\n }\n\n .sv-email-input-wrapper {\n margin-bottom: 14px;\n }\n\n .sv-email-label {\n display: block;\n font-size: 13px;\n font-weight: 500;\n letter-spacing: -0.005em;\n margin-bottom: 6px;\n color: ${E};\n }\n\n .sv-email-input {\n width: 100%;\n padding: 10px 12px;\n font-size: 15px;\n font-weight: 400;\n line-height: 1.4;\n border: 1px solid ${w};\n border-radius: 8px;\n background: ${k};\n color: ${E};\n box-sizing: border-box;\n transition: border-color var(--sv-dur-fast) var(--sv-ease-standard), box-shadow var(--sv-dur-fast) var(--sv-ease-standard);\n }\n\n .sv-email-input:hover:not(:focus):not(:disabled) {\n border-color: ${x};\n }\n\n .sv-email-input:focus {\n outline: none;\n border-color: ${C};\n box-shadow: 0 0 0 3px ${c};\n }\n\n .sv-email-input::placeholder {\n color: ${A};\n }\n\n .sv-email-input-error {\n border-color: ${h};\n }\n\n .sv-email-input-error:focus {\n box-shadow: 0 0 0 3px ${u};\n }\n\n /* The SMS and voice consent under a phone number field: fine print in the\n secondary ink, its links underlined in the same ink so each reads as a\n link without a second color. */\n .sv-sms-consent {\n margin: 8px 0 0;\n font-size: 12px;\n line-height: 1.5;\n color: ${T};\n }\n\n .sv-sms-consent-link {\n color: inherit;\n text-decoration: underline;\n text-underline-offset: 2px;\n border-radius: 2px;\n transition: color var(--sv-dur-fast) var(--sv-ease-standard);\n }\n\n .sv-sms-consent-link:hover {\n color: ${E};\n }\n\n .sv-sms-consent-link:focus-visible {\n outline: none;\n box-shadow: ${I};\n }\n\n /* ========================================\n ERROR VIEW\n ======================================== */\n\n .sv-error-view {\n display: flex;\n flex-direction: column;\n align-items: center;\n text-align: center;\n }\n\n .sv-error-icon-container {\n margin-bottom: 16px;\n }\n\n .sv-error-icon {\n width: 48px;\n height: 48px;\n }\n\n .sv-error-content {\n margin-bottom: 24px;\n }\n\n .sv-error-title {\n font-size: 18px;\n font-weight: 600;\n letter-spacing: -0.02em;\n margin: 0 0 8px 0;\n color: ${E};\n }\n\n .sv-error-message {\n font-size: 14px;\n line-height: 1.5;\n color: ${T};\n margin: 0 0 16px 0;\n }\n\n .sv-error-code-badge {\n display: inline-flex;\n align-items: center;\n gap: 6px;\n padding: 6px 10px;\n background: ${u};\n border: 1px solid ${p};\n border-radius: 6px;\n }\n\n .sv-error-code-label {\n font-size: 10px;\n font-weight: 600;\n color: ${i?$t.error500:$t.errorText};\n text-transform: uppercase;\n letter-spacing: 0.05em;\n }\n\n .sv-error-code-value {\n font-size: 11px;\n font-family: 'IBM Plex Mono', ui-monospace, SFMono-Regular, 'SF Mono', Menlo, Monaco, 'Cascadia Mono', monospace;\n color: ${h};\n font-weight: 500;\n }\n\n .sv-error-actions {\n display: flex;\n gap: 10px;\n width: 100%;\n }\n\n .sv-error-actions .sv-btn {\n flex: 1;\n }\n\n /* ========================================\n SERVICE UNAVAILABLE VIEW\n ======================================== */\n\n .sv-unavailable-view {\n display: flex;\n flex-direction: column;\n align-items: center;\n text-align: center;\n }\n\n .sv-unavailable-icon-container {\n margin-bottom: 16px;\n }\n\n .sv-unavailable-icon {\n width: 48px;\n height: 48px;\n }\n\n .sv-unavailable-content {\n margin-bottom: 24px;\n }\n\n .sv-unavailable-title {\n font-size: 18px;\n font-weight: 600;\n letter-spacing: -0.02em;\n margin: 0 0 8px 0;\n color: ${E};\n }\n\n .sv-unavailable-message {\n font-size: 14px;\n line-height: 1.5;\n color: ${T};\n margin: 0;\n }\n\n .sv-unavailable-actions {\n display: flex;\n gap: 10px;\n width: 100%;\n }\n\n .sv-unavailable-actions .sv-btn {\n flex: 1;\n }\n\n @media (max-width: 480px) {\n .sv-unavailable-actions {\n flex-direction: column;\n }\n }\n\n /* ========================================\n MINIMAL CHROME (full-dialog views)\n ======================================== */\n\n .sv-modal-minimal {\n position: relative;\n }\n\n .sv-modal-minimal > .sv-header {\n display: none;\n }\n\n .sv-modal-minimal > .sv-body {\n padding: 36px 32px 28px;\n }\n\n .sv-floating-close {\n position: absolute;\n top: 14px;\n right: 14px;\n width: 32px;\n height: 32px;\n display: flex;\n align-items: center;\n justify-content: center;\n background: transparent;\n border: none;\n border-radius: 6px;\n cursor: pointer;\n color: ${A};\n transition: background var(--sv-dur-fast) var(--sv-ease-standard), color var(--sv-dur-fast) var(--sv-ease-standard);\n z-index: 1;\n }\n\n .sv-floating-close:hover {\n background: ${b};\n color: ${E};\n }\n\n .sv-floating-close:focus-visible {\n outline: none;\n box-shadow: ${I};\n }\n\n /* ========================================\n APP NOT ACTIVATED VIEW\n ======================================== */\n\n .sv-not-activated-view {\n display: flex;\n flex-direction: column;\n align-items: center;\n text-align: center;\n }\n\n .sv-not-activated-eyebrow {\n display: inline-flex;\n align-items: center;\n gap: 8px;\n padding: 5px 10px;\n border-radius: 999px;\n background: ${b};\n color: ${T};\n font-size: 11px;\n font-weight: 600;\n letter-spacing: 0.04em;\n text-transform: uppercase;\n margin-bottom: 20px;\n }\n\n .sv-not-activated-mark {\n display: inline-flex;\n align-items: center;\n gap: 5px;\n color: ${E};\n font-weight: 700;\n letter-spacing: -0.01em;\n text-transform: none;\n font-size: 12px;\n }\n\n .sv-not-activated-eyebrow-divider {\n color: ${A};\n opacity: 0.6;\n }\n\n .sv-not-activated-eyebrow-label {\n color: ${T};\n }\n\n .sv-not-activated-badge {\n margin-bottom: 20px;\n }\n\n .sv-not-activated-badge-svg {\n display: block;\n filter: drop-shadow(0 8px 18px ${Ot($t.slate900,.08)});\n }\n\n .sv-not-activated-title {\n font-size: 22px;\n font-weight: 600;\n letter-spacing: -0.02em;\n line-height: 1.2;\n margin: 0 0 10px 0;\n color: ${E};\n }\n\n .sv-not-activated-message {\n font-size: 14px;\n line-height: 1.55;\n color: ${T};\n margin: 0 0 22px 0;\n max-width: 320px;\n }\n\n .sv-not-activated-owner {\n width: 100%;\n display: flex;\n flex-direction: column;\n gap: 4px;\n padding: 14px 16px;\n border: 1px solid ${w};\n border-radius: 10px;\n background: ${y};\n text-align: left;\n margin-bottom: 22px;\n }\n\n .sv-not-activated-owner-label {\n font-size: 13px;\n font-weight: 600;\n color: ${E};\n }\n\n .sv-not-activated-owner-hint {\n font-size: 12.5px;\n line-height: 1.5;\n color: ${T};\n }\n\n .sv-not-activated-actions {\n display: flex;\n flex-direction: column;\n align-items: stretch;\n gap: 10px;\n width: 100%;\n }\n\n .sv-not-activated-cta {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n gap: 8px;\n width: 100%;\n text-decoration: none;\n height: 44px;\n }\n\n .sv-not-activated-cta-icon {\n opacity: 0.85;\n }\n\n .sv-not-activated-dismiss {\n background: transparent;\n border: none;\n cursor: pointer;\n padding: 8px;\n font-size: 13px;\n font-weight: 500;\n color: ${A};\n transition: color var(--sv-dur-fast) var(--sv-ease-standard);\n align-self: center;\n }\n\n .sv-not-activated-dismiss:hover {\n color: ${E};\n }\n\n .sv-not-activated-dismiss:focus-visible {\n outline: none;\n box-shadow: ${I};\n border-radius: 6px;\n }\n\n /* ========================================\n OTP VIEW\n ======================================== */\n\n .sv-resend-container {\n text-align: center;\n margin-top: 16px;\n }\n\n /* ========================================\n PASSKEY VIEW\n ======================================== */\n\n .sv-passkey-icon {\n width: 48px;\n height: 48px;\n margin: 0 auto 12px;\n display: block;\n }\n\n .sv-passkey-description {\n font-size: 13px;\n color: ${A};\n text-align: center;\n margin: 0 0 16px 0;\n line-height: 1.4;\n }\n\n .sv-fallback-link {\n display: block;\n width: 100%;\n text-align: center;\n color: ${T};\n font-size: 13px;\n font-weight: 400;\n text-decoration: none;\n cursor: pointer;\n background: none;\n border: none;\n padding: 12px 0 0 0;\n margin-top: 8px;\n transition: color var(--sv-dur-fast) var(--sv-ease-standard);\n }\n\n .sv-fallback-link:hover {\n color: ${l};\n text-decoration: underline;\n }\n\n /* ========================================\n PASSKEY PROMPT VIEW\n ======================================== */\n\n .sv-passkey-prompt-icon {\n width: 48px;\n height: 48px;\n margin: 0 auto 12px;\n display: block;\n color: ${l};\n }\n\n .sv-passkey-prompt-benefits {\n background: ${y};\n border-radius: 8px;\n padding: 10px 14px;\n margin-bottom: 16px;\n }\n\n .sv-passkey-prompt-benefits ul {\n list-style: none;\n margin: 0;\n padding: 0;\n }\n\n .sv-passkey-prompt-benefits li {\n display: flex;\n align-items: center;\n gap: 10px;\n font-size: 13px;\n color: ${T};\n padding: 6px 0;\n }\n\n .sv-passkey-prompt-benefits li svg {\n width: 16px;\n height: 16px;\n color: ${l};\n flex-shrink: 0;\n }\n\n .sv-skip-link {\n display: block;\n width: 100%;\n text-align: center;\n color: ${A};\n font-size: 13px;\n font-weight: 400;\n text-decoration: none;\n cursor: pointer;\n background: none;\n border: none;\n padding: 12px 0 0 0;\n transition: color var(--sv-dur-fast) var(--sv-ease-standard);\n }\n\n .sv-skip-link:hover {\n color: ${T};\n text-decoration: underline;\n }\n\n /* ========================================\n SPARKLINK WAITING VIEW\n ======================================== */\n\n .sv-sparklink-icon-container {\n display: flex;\n justify-content: center;\n margin-bottom: 16px;\n }\n\n /* Bare glyph, no tinted circle container. */\n .sv-sparklink-icon {\n width: 48px;\n height: 48px;\n color: ${T};\n }\n\n .sv-sparklink-waiting {\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 12px;\n background: ${y};\n border-radius: 10px;\n padding: 14px 18px;\n margin: 16px 0;\n }\n\n .sv-spinner-small {\n width: 18px;\n height: 18px;\n border: 2px solid ${w};\n border-top-color: ${l};\n border-radius: 50%;\n animation: sv-spin 0.7s linear infinite;\n flex-shrink: 0;\n }\n\n .sv-sparklink-waiting-text {\n font-size: 13px;\n font-weight: 500;\n color: ${T};\n }\n\n .sv-sparklink-countdown {\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 6px;\n font-size: 13px;\n color: ${A};\n margin-bottom: 20px;\n }\n\n .sv-sparklink-countdown-time {\n font-family: 'IBM Plex Mono', ui-monospace, SFMono-Regular, 'SF Mono', Menlo, Monaco, 'Cascadia Mono', monospace;\n font-weight: 600;\n font-size: 14px;\n font-variant-numeric: tabular-nums;\n color: ${E};\n min-width: 40px;\n }\n\n .sv-sparklink-fallback {\n text-align: center;\n margin-top: 12px;\n padding-top: 16px;\n border-top: 1px solid ${w};\n }\n\n .sv-sparklink-fallback .sv-back-link {\n margin-bottom: 0;\n font-size: 12px;\n color: ${A};\n }\n\n .sv-sparklink-fallback .sv-back-link:hover:not(:disabled) {\n color: ${T};\n }\n\n /* SparkLink Expired State */\n .sv-sparklink-expired {\n flex-direction: column;\n gap: 12px;\n background: ${y};\n border: 1px solid ${w};\n }\n\n .sv-sparklink-expired-icon {\n display: flex;\n justify-content: center;\n }\n\n .sv-sparklink-expired-icon svg {\n width: 48px;\n height: 48px;\n }\n\n .sv-sparklink-expired-text {\n font-size: 14px;\n font-weight: 500;\n color: ${T};\n text-align: center;\n }\n\n .sv-expired-icon {\n width: 48px;\n height: 48px;\n }\n\n /* ========================================\n DIVIDER\n ======================================== */\n\n .sv-divider {\n display: flex;\n align-items: center;\n margin: 20px 0;\n }\n\n .sv-divider::before,\n .sv-divider::after {\n content: '';\n flex: 1;\n height: 1px;\n background: ${w};\n }\n\n .sv-divider-text {\n padding: 0 12px;\n font-size: 12px;\n color: ${A};\n }\n\n /* ========================================\n ACCESSIBILITY\n ======================================== */\n\n .sv-sr-only {\n position: absolute;\n width: 1px;\n height: 1px;\n padding: 0;\n margin: -1px;\n overflow: hidden;\n clip: rect(0, 0, 0, 0);\n white-space: nowrap;\n border: 0;\n }\n\n /* ========================================\n INLINE CONTAINER\n ======================================== */\n\n .sv-inline-container {\n display: flex;\n flex-direction: column;\n width: 100%;\n height: 100%;\n box-sizing: border-box;\n background: ${g};\n color: ${E};\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n border-radius: 12px;\n border: 1px solid ${w};\n }\n\n .sv-inline-header {\n border-bottom: 1px solid ${w};\n }\n\n .sv-inline-body {\n display: flex;\n flex-direction: column;\n justify-content: center;\n min-height: 200px;\n flex: 1;\n padding-left: 32px;\n padding-right: 32px;\n }\n\n /* Bare mode: the host page owns the surface and chrome, so the container\n is transparent and edge-free and the body hugs its content. */\n .sv-inline-bare {\n border: none;\n border-radius: 0;\n background: transparent;\n height: auto;\n }\n\n .sv-inline-bare > .sv-inline-body {\n min-height: 0;\n padding-left: 0;\n padding-right: 0;\n /* The host page owns the scroll and the surrounding padding in bare\n mode, so this body never scrolls internally. Keep overflow visible\n so a focused control's ring paints into the host padding instead of\n being clipped flat against this edgeless body's sides. */\n overflow: visible;\n }\n\n /* ========================================\n BRIDGE MODAL (host page, while the sign-in popup runs)\n ======================================== */\n\n .sv-bridge {\n text-align: center;\n padding: 4px 4px 6px;\n }\n\n .sv-bridge-dots {\n display: flex;\n gap: 6px;\n align-items: center;\n justify-content: center;\n margin-bottom: 20px;\n }\n\n .sv-bridge-dots span {\n width: 7px;\n height: 7px;\n border-radius: 50%;\n background: ${l};\n animation: sv-bridge-pulse 1.3s ease-in-out infinite;\n }\n\n .sv-bridge-dots span:nth-child(2) { animation-delay: 0.16s; }\n .sv-bridge-dots span:nth-child(3) { animation-delay: 0.32s; }\n\n @keyframes sv-bridge-pulse {\n 0%, 100% { opacity: 0.28; transform: translateY(0); }\n 50% { opacity: 1; transform: translateY(-3px); }\n }\n\n /* Warning shown under the logo only when the popup can't be confirmed -\n blocked, closed, or no result after a few seconds. Hidden on the happy\n path; appears with a gentle fade. */\n .sv-bridge-alert {\n display: flex;\n align-items: flex-start;\n gap: 10px;\n text-align: left;\n margin: 0 0 22px;\n padding: 11px 13px;\n border: 1px solid ${w};\n border-radius: 10px;\n background: ${y};\n font-size: 13px;\n line-height: 1.45;\n opacity: 0;\n max-height: 0;\n padding-top: 0;\n padding-bottom: 0;\n margin-bottom: 0;\n border-width: 0;\n overflow: hidden;\n transition: opacity var(--sv-dur-slow) var(--sv-ease-standard);\n }\n\n .sv-bridge-alert.sv-shown {\n opacity: 1;\n max-height: 120px;\n padding-top: 11px;\n padding-bottom: 11px;\n margin-bottom: 22px;\n border-width: 1px;\n }\n\n .sv-bridge-alert-icon {\n flex-shrink: 0;\n width: 17px;\n height: 17px;\n margin-top: 1px;\n color: ${v};\n }\n\n /* Text stacked over the action, so the message keeps the full width and\n never wraps to a lone word beside a right-aligned button. */\n .sv-bridge-alert-body {\n display: flex;\n flex-direction: column;\n align-items: flex-start;\n gap: 7px;\n flex: 1;\n min-width: 0;\n line-height: 1.35;\n }\n\n .sv-bridge-alert-text { color: ${T}; }\n\n .sv-bridge-retry {\n padding: 0;\n background: none;\n border: none;\n font-family: inherit;\n font-size: 13px;\n font-weight: 600;\n color: ${l};\n text-decoration: underline;\n text-underline-offset: 2px;\n cursor: pointer;\n }\n\n .sv-bridge-retry:hover { color: ${d}; }\n .sv-bridge-retry:focus-visible { outline: none; box-shadow: ${I}; border-radius: 4px; }\n\n @media (prefers-reduced-motion: reduce) {\n .sv-bridge-dots span { animation: none; opacity: 0.5; }\n }\n\n /* ========================================\n RESPONSIVE\n ======================================== */\n\n @media (max-width: 480px) {\n .sv-modal {\n max-width: 100%;\n max-height: 100%;\n border-radius: 0;\n }\n\n .sv-overlay {\n padding: 0;\n }\n\n .sv-body {\n padding: 24px 28px;\n }\n\n .sv-otp-digit {\n width: 40px;\n height: 48px;\n font-size: 18px;\n }\n\n .sv-error-actions {\n flex-direction: column;\n }\n }\n\n @media (max-width: 360px) {\n .sv-otp-input-group {\n gap: 6px;\n }\n\n .sv-otp-digit {\n width: 36px;\n height: 44px;\n font-size: 16px;\n }\n }\n `}const Jt=[];let Xt="";class Zt{constructor(e){var t;this.pressOnBackdrop=!1,this.open=!0,this.opener=document.activeElement instanceof HTMLElement?document.activeElement:null,this.overlay=document.createElement("div"),this.overlay.id=e.overlayId,this.overlay.className=`${e.classPrefix}-overlay`,this.overlay.classList.toggle(`${e.classPrefix}-blur`,e.backdropBlur),this.overlay.setAttribute("role","dialog"),this.overlay.setAttribute("aria-modal","true"),this.overlay.setAttribute("aria-labelledby",e.titleId),this.modal=document.createElement("div"),this.modal.id=e.modalId,this.modal.className=`${e.classPrefix}-modal`,this.modal.tabIndex=-1,this.overlay.appendChild(this.modal),this.onOverlayPointerDown=e=>{this.pressOnBackdrop=e.target===this.overlay},this.onOverlayClick=t=>{const n=t.target===this.overlay&&this.pressOnBackdrop;this.pressOnBackdrop=!1,n&&e.onDismiss()},this.onKeydown=t=>{if(this.ownsKeyboard())if("Escape"===t.key){if(function(e){return e.isComposing||229===e.keyCode}(t)||t.defaultPrevented)return;t.preventDefault(),e.onDismiss()}else"Tab"!==t.key||t.defaultPrevented||this.keepFocusInside(t)},this.overlay.addEventListener("pointerdown",this.onOverlayPointerDown),this.overlay.addEventListener("click",this.onOverlayClick),document.addEventListener("keydown",this.onKeydown),document.body.appendChild(this.overlay),t=this,0===Jt.length&&(Xt=document.body.style.overflow,document.body.style.overflow="hidden"),Jt.push(t),this.modal.focus({preventScroll:!0})}destroy(){var e;this.open&&(this.open=!1,document.removeEventListener("keydown",this.onKeydown),this.overlay.removeEventListener("pointerdown",this.onOverlayPointerDown),this.overlay.removeEventListener("click",this.onOverlayClick),this.overlay.remove(),e=this,Jt.splice(Jt.indexOf(e),1),0===Jt.length&&(document.body.style.overflow=Xt),this.opener?.isConnected&&this.opener.focus({preventScroll:!0}))}ownsKeyboard(){if(function(){for(let e=Jt.length-1;e>=0;e-=1)if(Jt[e].overlay.isConnected)return Jt[e]}()!==this)return!1;const e=document.activeElement?.closest('[aria-modal="true"], [role="dialog"], [role="alertdialog"], dialog[open]');return!e||Jt.some(t=>t.overlay.contains(e))}keepFocusInside(e){const t=Array.from(this.modal.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]):not([type=hidden]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter(e=>e.getClientRects().length>0),n=document.activeElement;if(0===t.length)return e.preventDefault(),void this.modal.focus({preventScroll:!0});const i=t[0],s=t[t.length-1];if(!n||!this.modal.contains(n))return e.preventDefault(),void i.focus();const r=n===i||0!==(i.compareDocumentPosition(n)&Node.DOCUMENT_POSITION_PRECEDING),o=n===s||0!==(s.compareDocumentPosition(n)&Node.DOCUMENT_POSITION_FOLLOWING)&&!s.contains(n);e.shiftKey&&r?(e.preventDefault(),s.focus()):!e.shiftKey&&o&&(e.preventDefault(),i.focus())}}function Qt(e){const t=document.createElement("div");t.className=`${e}-footer`;const n=document.createElement("span");n.className=`${e}-footer-text`,n.appendChild(document.createTextNode("Secured by "));const i=document.createElement("a");return i.href="https://sparkvault.com",i.target="_blank",i.rel="noopener noreferrer",i.className=`${e}-footer-link`,i.style.color="inherit",i.style.textDecoration="none",i.textContent="SparkVault",n.appendChild(i),t.appendChild(n),t}const en="sv-modal-title",tn={companyName:"",logoLight:null,logoDark:null};class nn{constructor(){this.shell=null,this.body=null,this.header=null,this.onCloseCallback=null,this.effectiveTheme="light",this.floatingCloseBtn=null}createLoading(e,t){this.shell||(this.onCloseCallback=t,this.effectiveTheme=Gt(tn),qt({branding:tn,backdropBlur:e.backdropBlur}),this.shell=new Zt({overlayId:"sparkvault-identity-overlay",modalId:"sparkvault-identity-modal",classPrefix:"sv",titleId:en,backdropBlur:!1!==e.backdropBlur,onDismiss:()=>this.handleClose()}),this.header=this.createHeader(tn),this.body=document.createElement("div"),this.body.className="sv-body",this.shell.modal.append(this.header,this.body,Qt("sv")))}updateBranding(e){if(!this.shell||!this.header)return;this.effectiveTheme=Gt(e),Kt(e);const t=this.createHeader(e);this.header.replaceWith(t),this.header=t}setMinimalChrome(e){if(!this.shell)return;const{modal:t}=this.shell;t.classList.toggle("sv-modal-minimal",e),e&&!this.floatingCloseBtn?(this.floatingCloseBtn=sn("sv-floating-close",()=>this.handleClose()),t.appendChild(this.floatingCloseBtn)):!e&&this.floatingCloseBtn&&(this.floatingCloseBtn.remove(),this.floatingCloseBtn=null)}createHeader(e){const t=document.createElement("div");t.className="sv-header";const n=document.createElement("div");n.className="sv-header-title";const i=(s="dark"===this.effectiveTheme,r=e.logoLight,o=e.logoDark,s?o||r:r||o);var s,r,o;if(i){const t=document.createElement("img");t.className="sv-logo",t.src=i,t.alt=e.companyName,n.appendChild(t);const s=document.createElement("span");s.className="sv-sr-only",s.id=en,s.textContent=e.companyName,n.appendChild(s)}else{const t=document.createElement("h2");t.className="sv-company-name",t.id=en,t.textContent=e.companyName,n.appendChild(t)}return t.append(n,sn("sv-close-btn",()=>this.handleClose())),t}handleClose(){this.onCloseCallback?.()}getBody(){return this.body}isOpen(){return null!==this.shell}destroy(){this.shell?.destroy(),this.shell=null,this.header=null,this.body=null,this.floatingCloseBtn=null,this.onCloseCallback=null}}function sn(e,t){const n=document.createElement("button");return n.className=e,n.type="button",n.setAttribute("aria-label","Close"),n.appendChild(function(){const e=it("0 0 20 20",20,20);return e.appendChild(st("M15 5L5 15M5 5L15 15",{stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round"})),e}()),n.addEventListener("click",t),n}const rn="http://www.w3.org/2000/svg";function on(e,t,n){const i=document.createElement(e);return t&&(i.className=t),null!=n&&(i.textContent=n),i}class an{constructor(e,t,n,i){this.config=e,this.api=t,this.options=n,this.callbacks=i,this.popupLauncher=new Me,this.modal=null,this.alertEl=null,this.popupWindow=null,this.popupReady=!1,this.openTimer=null,this.settled=!1,this.generation=0,this.trustedOrigin=new URL(this.config.identityBaseUrl).origin}start(){this.showBridge(),this.openPopup(),this.loadBranding()}close(){this.clearOpenTimer(),this.closePopup(),this.modal?.destroy(),this.modal=null,this.alertEl=null}signinReferenceDecided(){this.popupReady&&this.postSigninReference()}openPopup(){const e=++this.generation;this.popupReady=!1,this.popupLauncher.openPopup({url:me(this.config,this.options,{kind:"popup"}),windowName:"sparkvault-login",resultType:"sparkvault-login-result",readyType:"sparkvault-login-ready",trustedOrigin:this.trustedOrigin,onOpen:t=>{e===this.generation&&(this.popupWindow=t,this.scheduleOpenWarning())},onReady:()=>{e===this.generation&&(this.clearOpenTimer(),this.popupReady=!0,this.postSigninReference())},requestType:Z.retryMessage,onRequest:()=>{e===this.generation&&this.answerSigninReferenceRetry()}}).then(t=>{e===this.generation&&this.handleResult(t)}).catch(t=>{e===this.generation&&this.handleError(t)}),this.callbacks.drawSigninReference()}answerSigninReferenceRetry(){const e=this.callbacks.signinReference();null!==e?void 0!==e&&this.postSigninReference():this.callbacks.drawSigninReference()}postSigninReference(){const e=this.callbacks.signinReference();void 0!==e&&this.popupWindow&&this.popupWindow.postMessage({type:Z.message,[Z.param]:e},this.trustedOrigin)}handleResult(e){if(!this.settled){if(e.success&&e.data){const t={token:e.data.token||"",identity:e.data.identity||"",identityType:e.data.identity_type||"email",svid:e.data.svid,sessionId:e.data.session_id,refreshToken:e.data.refresh_token,redirect:e.data.redirect};return this.finish(),void this.callbacks.onSuccess(t)}"cancelled"!==e.error?(this.finish(),this.callbacks.onError(new p(e.message||e.error||"Verification failed",e.errorCode||e.error||"verification_failed"))):this.finishCancel()}}handleError(e){if(!this.settled)if(e instanceof b&&this.callbacks.onPopupSevered)this.callbacks.onPopupSevered().then(e=>{this.settled||e||(this.callbacks.onPopupClosedUnresolved?.(),this.showAlert())}).catch(()=>{this.settled||(this.callbacks.onPopupClosedUnresolved?.(),this.showAlert())});else{if(e instanceof y||e instanceof v||e instanceof b)return this.callbacks.onPopupClosedUnresolved?.(),void this.showAlert();this.finish(),this.callbacks.onError(e instanceof Error?e:new Error(String(e)))}}showBridge(){if(this.settled)return;this.modal||(this.modal=new nn,this.modal.createLoading({backdropBlur:this.options.backdropBlur},()=>this.abort()));const e=this.modal.getBody();if(!e)return;Ge(e);const t=on("div","sv-bridge"),n=on("div","sv-bridge-alert");n.appendChild(function(){const e=document.createElementNS(rn,"svg");e.setAttribute("viewBox","0 0 20 20"),e.setAttribute("fill","none"),e.classList.add("sv-bridge-alert-icon");const t=(e,t)=>{const n=document.createElementNS(rn,"path");n.setAttribute("d",e);for(const[e,i]of Object.entries(t))n.setAttribute(e,i);return n};e.appendChild(t("M10 2.75 18.25 17.25H1.75L10 2.75Z",{stroke:"currentColor","stroke-width":"1.5","stroke-linejoin":"round"})),e.appendChild(t("M10 8.25v3.25",{stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round"}));const n=document.createElementNS(rn,"circle");return n.setAttribute("cx","10"),n.setAttribute("cy","14.5"),n.setAttribute("r","0.95"),n.setAttribute("fill","currentColor"),e.appendChild(n),e}());const i=on("div","sv-bridge-alert-body");i.appendChild(on("span","sv-bridge-alert-text","The sign-in window may not have opened."));const s=on("button","sv-bridge-retry","Try again");s.type="button",s.addEventListener("click",()=>this.retry()),i.appendChild(s),n.appendChild(i),this.alertEl=n;const r=on("div","sv-bridge-dots");r.append(on("span"),on("span"),on("span")),t.append(n,r,on("h3","sv-title","Continue in the secure window"),on("p","sv-subtitle","Finish signing in there. This page updates on its own.")),e.appendChild(t)}showAlert(){this.clearOpenTimer(),this.alertEl?.classList.add("sv-shown")}hideAlert(){this.alertEl?.classList.remove("sv-shown")}scheduleOpenWarning(){this.clearOpenTimer(),this.openTimer=setTimeout(()=>this.showAlert(),8e3)}clearOpenTimer(){this.openTimer&&(clearTimeout(this.openTimer),this.openTimer=null)}retry(){this.hideAlert(),this.closePopup(),this.openPopup()}loadBranding(){this.api.getConfig().then(e=>{e.branding&&this.modal&&this.modal.updateBranding(e.branding)}).catch(()=>{})}closePopup(){if(this.popupWindow&&!this.popupWindow.closed)try{this.popupWindow.close()}catch{}this.popupWindow=null}abort(){this.finishCancel()}finish(){this.settled=!0,this.close()}finishCancel(){this.settled||(this.settled=!0,this.close(),this.callbacks.onCancel())}}class ln{constructor(e,t){this.container=document.createElement("div"),this.container.className=t.containerClassName,this.body=document.createElement("div"),this.body.className=t.bodyClassName,this.container.appendChild(this.body),t.footer&&this.container.appendChild(t.footer),e.textContent="",e.appendChild(this.container)}destroy(){this.container.remove()}}class dn{constructor(e,t={}){this.shell=null,this.targetElement=e,this.bare=!0===t.bare}createLoading(e,t){this.shell||(qt({branding:{companyName:"",logoLight:null,logoDark:null},backdropBlur:!1}),this.shell=new ln(this.targetElement,{containerClassName:this.bare?"sv-inline-container sv-inline-bare":"sv-inline-container",bodyClassName:"sv-body sv-inline-body",footer:this.bare?null:Qt("sv")}))}updateBranding(e){this.shell&&Kt(e)}setMinimalChrome(e){}getBody(){return this.shell?.body??null}isOpen(){return null!==this.shell}destroy(){this.shell?.destroy(),this.shell=null}}function cn(e,t){let n=null,i=!1;const s=new Map,r=e=>{s.has(e)||(e.addEventListener("click",t),s.set(e,()=>e.removeEventListener("click",t)))};var o;return o=()=>{i||(document.querySelectorAll(e).forEach(r),n=new MutationObserver(t=>{t.forEach(t=>{t.addedNodes.forEach(t=>{t instanceof Element&&(t.matches(e)&&r(t),t.querySelectorAll(e).forEach(r))})})}),function(e){if(document.body)e();else{const t=()=>{document.body?e():window.requestAnimationFrame(t)};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",t,{once:!0}):window.requestAnimationFrame(t)}}(()=>{n?.observe(document.body,{childList:!0,subtree:!0})}))},"loading"===document.readyState?document.addEventListener("DOMContentLoaded",o,{once:!0}):o(),()=>{i=!0,n?.disconnect(),s.forEach(e=>e()),s.clear()}}const hn="sv_signin_pending";function un(){let e,t=null;try{t=sessionStorage.getItem(hn)}catch{return null}if(!t)return null;try{e=JSON.parse(t)}catch{return null}if("object"!=typeof e||null===e)return null;const n=e;if("number"!=typeof n.at||!Number.isFinite(n.at))return null;const{ref:i}=n;if(void 0!==i&&!Q(i))return null;const s=n[ee.param];return ne(s).ok?{at:n.at,hint:"string"==typeof n.hint&&n.hint?n.hint:null,ref:"string"==typeof i?i:null,identityTypes:"string"==typeof s?s:null}:null}function pn(e){return null!==e&&Date.now()-e.at<X.pendingTtlMs}function mn(){try{sessionStorage.removeItem(hn)}catch{}}class fn{constructor(e,t){this.hint=e,this.identityTypes=t,this.at=0,this.ended=!1,this.opens=0,this.current=void 0,this.decided=Promise.resolve()}get reference(){return this.current}get live(){return!this.ended}open(e){if(this.ended)return Promise.resolve(!1);const t=++this.opens;this.at=Date.now(),this.current=void 0,this.write(null)||mn();const n=function(e){return new Promise(t=>{const n=setTimeout(()=>t(null),Z.drawDeadlineMs);e.then(e=>{clearTimeout(n),t(e)},()=>{clearTimeout(n),t(null)})})}(e()).then(e=>!this.ended&&t===this.opens&&(this.current=null!==e&&this.write(e)?e:null,!0));return this.decided=n,n}retire(){this.ended||(this.opens+=1,this.current=null,mn())}end(){this.retire(),this.ended=!0}referenceWithin(e){return void 0!==this.current?Promise.resolve(this.current):new Promise(t=>{const n=setTimeout(()=>t(this.current??null),e);this.decided.then(()=>{clearTimeout(n),t(this.current??null)})})}write(e){const t={at:this.at,hint:this.hint,...e?{ref:e}:{},...this.identityTypes?{[ee.param]:this.identityTypes}:{}};try{sessionStorage.setItem(hn,JSON.stringify(t))}catch{return!1}return!0}}const vn=["home","identity","security","sessions","sites"],gn=["EdDSA","RS256"];function yn(e,t){const n=j(e);if(null===n)throw new m(t);try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n))}catch{throw new m(t)}}class bn{constructor(e){this.renderer=null,this.launcher=null,this.pendingSignIn=null,this.config=e,this.api=new fe(e),e.preloadConfig&&this.api.preloadConfig(),function(e){if("undefined"==typeof document||"undefined"==typeof window||!document.head)return;let t;try{t=new URL(e).origin}catch{return}if(t!==window.location.origin)for(const e of[!1,!0]){const n=`link[rel="preconnect"][href="${t}"]${e?"[crossorigin]":":not([crossorigin])"}`;if(document.head.querySelector(n))continue;const i=document.createElement("link");i.rel="preconnect",i.href=t,e&&(i.crossOrigin="anonymous"),document.head.appendChild(i)}}(e.identityBaseUrl)}portalUrl(e={}){const t=e.section??"home";if(!vn.includes(t))throw new m(`Unknown portal section: ${t}`,{field:"section",received:t});let n;if("home"===t)n="/";else if("sites"===t){const t=(e.site??this.config.accountId).trim();n=t?`/sites/${encodeURIComponent(t)}`:"/sites"}else n=`/${t}`;return new URL(n,this.config.portalBaseUrl).toString()}async signInWithFedcm(e={}){const t=he(e.identityTypes);if(!bn.isFedcmAvailable())return null;if(!this.config.clientId)throw new m("clientId must be set in the SDK config to use FedCM sign-in",{field:"clientId"});const n=e.nonce??(await this.api.drawAuthorizationValues()).nonce,i={identity:{providers:[{configURL:`${this.config.identityBaseUrl}/${this.config.accountId}/fedcm/config.json`,clientId:this.config.clientId,nonce:n,...t?{params:ue(t)}:{}}]},...e.mediation?{mediation:e.mediation}:{}};let s;try{const e=navigator.credentials.get.bind(navigator.credentials);s=await e(i)}catch(e){throw function(e){if("object"!=typeof e||null===e)return null;const{name:t,error:n}=e;return"IdentityCredentialError"!==t?null:new g("string"==typeof n?n:"")}(e)??new v(e instanceof Error?e.message:void 0)}const r=s?.token;if(!r)throw new m("FedCM did not return a token");const o=this.decodeToken(r);return{token:r,identity:o.identity,identityType:o.identity_type,svid:o.svid,sessionId:o.session_id}}static isFedcmAvailable(){return"undefined"!=typeof window&&"IdentityCredential"in window&&"undefined"!=typeof navigator&&!!navigator.credentials&&"function"==typeof navigator.credentials.get}async signIn(e={}){let t;try{t=he(e.identityTypes)}catch(t){const n=t instanceof Error?t:new Error(String(t));throw e.onError?.(n),n}return this.runFlow(e,{ok:!0,types:t})}async runFlow(e,t,n=null){this.closeLauncher(),this.renderer&&this.renderer.close(),this.api.resetSession();const i={...e,backdropBlur:e.backdropBlur??this.config.backdropBlur},s=!!e.target,r="local"===e.renderMode||s;let o,a;const l=new Promise((e,t)=>{o=e,a=t}),d={onSuccess:t=>{e.onSuccess?.(t),o(t)},onError:t=>{e.onError?.(t),a(t)},onCancel:()=>{const t=new v;e.onCancel?.(),a(t)}},c=e=>{this.renderer=new jt(e,this.api,i,d,n,t),this.renderer.start().catch(e=>{this.renderer?.showStartupError(e)})};if(!r){if(await this.preloadedConfigPermanentlyFailed())return c(new nn),l;if("redirect"===i.flow){try{await this.startRedirectFlow(i,null)||d.onError(new m("Sign-in requires browser session storage. Enable site data for this site and try again."))}catch(e){d.onError(e instanceof Error?e:new Error(String(e)))}return l}const e=new fn(i.email||i.phone||null,i.identityTypes?te(i.identityTypes):null);this.pendingSignIn=e;const t=new an(this.config,this.api,i,{onSuccess:t=>{e.end(),d.onSuccess(t)},onError:t=>{e.end(),d.onError(t)},onCancel:()=>{e.end(),d.onCancel()},onPopupClosedUnresolved:()=>e.retire(),drawSigninReference:()=>{e.open(()=>this.api.drawSigninReference()).then(e=>{e&&t.signinReferenceDecided()})},onPopupSevered:async()=>{const t=await e.referenceWithin(Z.redirectWaitMs);return null===t&&e.retire(),this.startRedirectFlow(i,{signIn:e,signinRef:t})},signinReference:()=>e.reference});return this.launcher=t,t.start(),l}return c(s?this.createInlineContainer(e.target,"bare"===e.chrome):new nn),l}attach(e,t={}){return cn(e,async e=>{e.preventDefault();try{await this.signIn({email:t.email,phone:t.phone,authContext:t.authContext,prompt:t.prompt,method:t.method,identityTypes:t.identityTypes,onSuccess:t.onSuccess,onError:t.onError,onCancel:t.onCancel})}catch{}})}decodeToken(e){if(!e||"string"!=typeof e)throw new m("Token is required");const t=e.split(".");if(3!==t.length)throw new m("Invalid token format");const[n,i]=t,s=yn(n,"Invalid token header");if("object"!=typeof s||null===s)throw new m("Invalid token header");const r=s.alg;if("string"!=typeof r||!gn.includes(r))throw new m("Unsupported token algorithm");const o=yn(i,"Invalid token payload");if(!function(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.iss&&"string"==typeof t.sub&&"string"==typeof t.aud&&"number"==typeof t.exp&&"number"==typeof t.iat&&"string"==typeof t.identity&&"string"==typeof t.identity_type&&"number"==typeof t.verified_at&&"string"==typeof t.method}(o))throw new m("Invalid token payload structure");const a=Math.floor(Date.now()/1e3);if(o.exp<a)throw new m("Token has expired");const l=`${this.config.identityBaseUrl}/${this.config.accountId}`;if(o.iss!==l)throw new m("Invalid token issuer");if(o.aud!==this.config.accountId)throw new m("Invalid token audience");return o}async handleRedirectResult(e={}){if("undefined"==typeof window)return null;const t=new URLSearchParams((window.location.hash||"").slice(1));if(t.get("sv_code")||t.get("sv_error"))return this.consumeHandoffFragment(t,e);t.get("sso")&&(this.clearUrlFragment(),this.clearOneShotAuthState());const n=this.consumeSignInPending();return n&&await this.startRecoveryBounce(n),null}async consumeHandoffFragment(e,t){const n=e.get("sv_code"),i=e.get("sv_error");mn();let s=null,r=null;try{s=sessionStorage.getItem("sv_oauth_state"),r=sessionStorage.getItem("sv_pkce_verifier"),this.clearOneShotAuthState()}catch{}this.clearUrlFragment();try{if(i){if("cancelled"===i)return t.onCancel?.(),null;throw new p("Sign-in could not be completed. Please try again.","REDIRECT_SIGNIN_FAILED")}if(s&&e.get("state")!==s)throw new m("Invalid OAuth state");if(!r)throw new m("Sign-in session was lost. Please sign in again.");const o=await this.api.redeemHandoffCode(n,r),a={token:o.token,identity:o.identity,identityType:o.identity_type,svid:o.svid??void 0,sessionId:o.session_id??void 0,refreshToken:o.refresh_token??void 0};return t.onSuccess?.(a),a}catch(e){const n=e instanceof Error?e:new Error(String(e));throw t.onError?.(n),n}}async startRecoveryBounce(e){const t=await this.armHandoffReturn();if(!t)return;const n=new URL(`${this.config.identityBaseUrl}/${this.config.accountId}/sso`);e.hint&&n.searchParams.set("login_hint",e.hint),e.ref&&n.searchParams.set(Z.param,e.ref),e.identityTypes&&n.searchParams.set(ee.param,e.identityTypes),n.searchParams.set("redirect_uri",t.redirectUri),n.searchParams.set("state",t.state),n.searchParams.set("code_challenge",t.codeChallenge),window.location.assign(n.toString())}async startRedirectFlow(e,t){const n=t?.signinRef??null,i=e.authContext,s=i?.authRequestId||i?.simpleMode?.sessionId?void 0:await this.armHandoffReturn();return null!==s&&(!(t&&!t.signIn.live)&&(null===n&&mn(),window.location.assign(me(this.config,e,{kind:"redirect",signinRef:n,handoff:s})),!0))}async armHandoffReturn(){const{state:e,codeVerifier:t}=await this.api.drawAuthorizationValues();let n;try{n=await async function(e){const t=await crypto.subtle.digest("SHA-256",(new TextEncoder).encode(e));return U(new Uint8Array(t))}(t)}catch{return null}try{sessionStorage.setItem("sv_oauth_state",e),sessionStorage.setItem("sv_pkce_verifier",t)}catch{return null}return{redirectUri:pe(),state:e,codeChallenge:n}}consumeSignInPending(){const e=un();return mn(),pn(e)?e:null}closeLauncher(){this.launcher?.close(),this.launcher=null,this.pendingSignIn?.end(),this.pendingSignIn=null}clearUrlFragment(){"function"==typeof window.history?.replaceState&&window.history.replaceState(window.history.state,document.title,`${window.location.pathname}${window.location.search}`)}clearOneShotAuthState(){try{sessionStorage.removeItem("sv_oauth_state"),sessionStorage.removeItem("sv_pkce_verifier")}catch{}}async consumeRedirectResult(){if("undefined"==typeof window||!window.location.hash)return null;const e=new URLSearchParams(window.location.hash.slice(1)),t=e.get(Y.token);if(!t)return null;try{let n=null;try{n=sessionStorage.getItem("sv_oauth_state")}catch{}if(!n||e.get(Y.state)!==n)throw new m("Invalid OAuth state");const i=this.decodeToken(t);return{token:t,identity:i.identity,identityType:i.identity_type,svid:i.svid,sessionId:i.session_id}}finally{this.clearUrlFragment();try{sessionStorage.removeItem("sv_oauth_state")}catch{}$e(this.config.accountId)}}consumeFederationReturn(){if("undefined"==typeof window||!window.location.hash)return null;const e=new URLSearchParams(window.location.hash.slice(1)),t=function(e){const t=e.get("error");return"interaction_required"===t&&"federation"===e.get("method")?"interaction_required":"federation_failed"===t?"failed":null}(e);if(!t)return null;let n=null;try{n=sessionStorage.getItem("sv_oauth_state"),sessionStorage.removeItem("sv_oauth_state")}catch{}return this.clearUrlFragment(),n&&e.get(Y.state)===n?t:null}close(){this.closeLauncher(),this.renderer&&(this.renderer.close(),this.renderer=null)}async preloadedConfigPermanentlyFailed(){if(!this.api.isConfigPreloaded())return!1;const e=Symbol("pending");try{return await Promise.race([this.api.getConfig(),new Promise(t=>setTimeout(()=>t(e),50))]),!1}catch(e){return e instanceof ke&&("ORIGIN_NOT_ALLOWED"===e.code||"product_not_configured"===e.code)}}createInlineContainer(e,t=!1){return new dn(function(e){if("string"==typeof e){const t=document.querySelector(e);if(!(t instanceof HTMLElement))throw new m(`Target selector "${e}" did not match any element`);return t}if(e instanceof HTMLElement)return e;throw new m("Target must be a CSS selector string or HTMLElement")}(e),{bare:t})}async render(e){const t=await this.consumeRedirectResult();if(t)return e.onSuccess?.(t),t;const{identityTypes:n,...i}=e;return this.runFlow(i,ne(n),this.consumeFederationReturn())}}e.IdentityModule=bn,e.IdentityProviderError=g,e.PopupBlockedError=y,e.PopupSeveredError=b,e.SparkVaultError=p,e.TimeoutError=f,e.UserCancelledError=v,e.ValidationError=m,e.init=function(e){return P(e),new bn(function(e){return{accountId:e.accountId,timeout:e.timeout??3e4,apiBaseUrl:B(e.apiBaseUrl??"https://api.sparkvault.com"),identityBaseUrl:_(e.identityBaseUrl??"https://auth.sparkvault.com"),portalBaseUrl:_(e.portalBaseUrl??R),accessToken:e.accessToken,getAccessToken:e.getAccessToken,onVaultSessionTiming:e.onVaultSessionTiming,apiKey:e.apiKey,clientId:e.clientId,preloadConfig:e.preloadConfig??"undefined"!=typeof window,backdropBlur:!1!==e.backdropBlur,allowedDownloadHostPatterns:e.allowedDownloadHostPatterns??[...I]}}(e))},e.isRecoveryPending=function(){return"undefined"!=typeof window&&(!!/[#&](sv_code|sv_error|sso)=/.test(window.location.hash||"")||pn(un()))},e.version="19.1.0"});
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).SparkVaultIdentity={})}(this,function(e){"use strict";const t=Object.freeze({UPLOAD_CONTRACT_MISMATCH:"UPLOAD_CONTRACT_MISMATCH",UPLOAD_PROTOCOL_RETIRED:"UPLOAD_PROTOCOL_RETIRED",UPLOAD_SUPERSEDED:"UPLOAD_SUPERSEDED",UPLOAD_POOL_FULL:"UPLOAD_POOL_FULL"});Object.freeze([t.UPLOAD_POOL_FULL,t.UPLOAD_SUPERSEDED]);const n=Object.freeze({status:"revoked",reasons:Object.freeze({UPLOAD_SUPERSEDED:t.UPLOAD_SUPERSEDED,INGOT_DELETED:"INGOT_DELETED"})});Object.values(n.reasons);const i=Object.freeze({OK:"ok",RETRY:"retry",RESYNC:"resync",DEFERRED:"deferred",GONE:"gone",REFUSED:"refused"});new Set([i.RETRY,i.RESYNC]);function s(e,t=Date.now()){const n=function(e){if("string"!=typeof e)return null;const t=e.trim();if(!/^\d+$/.test(t))return null;const n=Number(t);return Number.isSafeInteger(n)?n:null}(e);if(null!==n){const e=1e3*n;return Number.isSafeInteger(e)?e:null}const i="string"==typeof e?function(e,t){let n=d.exec(e);if(n){const[,e,t,i,s,r,o]=n;return u(Number(i),t,Number(e),s,r,o)}if(n=c.exec(e),n){const[,e,i,s,r,o,a]=n;return u(function(e,t){const n=new Date(t).getUTCFullYear(),i=n-n%100+e;return i>n+50?i-100:i}(Number(s),t),i,Number(e),r,o,a)}if(n=h.exec(e),n){const[,e,t,i,s,r,o]=n;return u(Number(o),e,Number(t.trim()),i,s,r)}return null}(e.trim(),t):null;return null===i?null:Math.max(0,i-t)}const r=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],o="(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)",a=`(${r.join("|")})`,l="(\\d{2}):(\\d{2}):(\\d{2})",d=new RegExp(`^${o}, (\\d{2}) ${a} (\\d{4}) ${l} GMT$`),c=new RegExp(`^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\\d{2})-${a}-(\\d{2}) ${l} GMT$`),h=new RegExp(`^${o} ${a} ( \\d|\\d{2}) ${l} (\\d{4})$`);function u(e,t,n,i,s,o){const a=r.indexOf(t),[l,d,c]=[Number(i),Number(s),Number(o)];if(l>23||d>59||c>60)return null;const h=new Date(0);return h.setUTCFullYear(e,a,n),h.getUTCFullYear()!==e||h.getUTCMonth()!==a||h.getUTCDate()!==n?null:h.getTime()+1e3*(60*(60*l+d)+c)}class p extends Error{constructor(e,t,n,i,s=null,r){super(e),this.name="SparkVaultError",this.code=t,this.statusCode=n,this.details=i,this.retryAfterMs=s,this.serviceCode=r,Object.setPrototypeOf(this,p.prototype)}}class m extends p{constructor(e,t,n=null,i){super(e,"validation_error",400,t,n,i),this.name="ValidationError",Object.setPrototypeOf(this,m.prototype)}}class f extends p{constructor(e="Request timed out"){super(e,"timeout_error"),this.name="TimeoutError",Object.setPrototypeOf(this,f.prototype)}}class v extends p{constructor(e="User cancelled the operation"){super(e,"user_cancelled"),this.name="UserCancelledError",Object.setPrototypeOf(this,v.prototype)}}class g extends p{constructor(e){super("The identity provider could not complete the sign-in.",e||"identity_provider_error"),this.name="IdentityProviderError",Object.setPrototypeOf(this,g.prototype)}}class y extends p{constructor(){super("Popup was blocked. Please allow popups for this site.","popup_blocked"),this.name="PopupBlockedError",Object.setPrototypeOf(this,y.prototype)}}class b extends p{constructor(e="The sign-in window could not communicate with this page."){super(e,"popup_severed"),this.name="PopupSeveredError",Object.setPrototypeOf(this,b.prototype)}}function k(e){return"string"==typeof e&&e?e:null}function w(e){return"object"!=typeof e||null===e||Array.isArray(e)?void 0:e}async function x(e){return function(e,t,n){const i=w(t)??{},r=w(i.error);return{status:e,message:k(r?.message)??k(i.message)??k(i.error)??"Request failed",code:k(r?.code)??k(i.code)??"api_error",details:w(r?.details)??w(i.details),retryAfterMs:s(n("Retry-After"))}}(e.status,await e.json().catch(()=>null),t=>e.headers.get(t))}const C=Object.freeze({account:"acc",attachment:"hda",folder:"fld",helpDeskJob:"hdj",knowledgeBaseArticle:"hdkba",knowledgeBaseCategory:"hdkbc",knowledgeBaseRevision:"hdkbr",knowledgeBaseAsset:"hdkbm",knowledgeBaseFaq:"hdkbq",ingot:"ing",invite:"inv",notification:"ntf",notifyProject:"ntp",requester:"hrq",routingRule:"hdr",savedReply:"hds",spark:"spk",team:"team",ticket:"tkt",ticketEvent:"hdev",user:"usr",vault:"vlt"});function S(e){if(!Object.hasOwn(C,e))throw new TypeError(`No resource kind '${e}'`);return`^${C[e]}_[A-Za-z0-9_-]+$`}const E=Object.freeze(Object.fromEntries(Object.keys(C).map(e=>[e,new RegExp(S(e))])));Object.freeze(Object.keys(C));const T="auth.sv",A=Object.freeze([T,"x.sv","files.sv","file.sv","spark.sv","by.sv","at.sv","db.sv"]);function L(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const I=Object.freeze([new RegExp(`(^|\\.)${L("sparkvault.com")}$`,"i"),new RegExp(`^(${A.map(L).join("|")})$`,"i")]),R=`https://${T}`;function B(e){const t=e.replace(/\/+$/,"");return t.endsWith("/v1")?t.slice(0,-3):t}function _(e){return e.replace(/\/+$/,"")}function P(e){if(!e.accountId)throw new m("accountId is required",{field:"accountId"});if("string"!=typeof e.accountId)throw new m("accountId must be a string",{field:"accountId",received:typeof e.accountId});if(!function(e,t){if(!Object.hasOwn(C,e))throw new TypeError(`No resource kind '${e}'`);return"string"==typeof t&&t.length<=128&&E[e].test(t)}("account",e.accountId))throw new m("accountId must be a SparkVault account id (acc_...)",{field:"accountId",received:e.accountId})}async function $(e){try{return await e.json()}catch(e){if(e instanceof SyntaxError)return null;throw e}}async function O(e,t,n){const{timeoutMs:i,closeSignal:s,read:r,fail:o}=n;if(s?.aborted)throw o("cancelled",null);const{signal:a,dispose:l}=function(e,t){const n=new AbortController,i=setTimeout(()=>n.abort(),e);let s=n.signal,r=null;return t&&"any"in AbortSignal?s=AbortSignal.any([n.signal,t]):t&&(r=()=>n.abort(),t.addEventListener("abort",r)),{signal:s,dispose:()=>{clearTimeout(i),t&&r&&t.removeEventListener("abort",r)}}}(i,s);try{return await r(await fetch(e,{...t,signal:a}))}catch(e){if(e instanceof p)throw e;if(function(e){return null!=e&&"object"==typeof e&&"name"in e&&"AbortError"===e.name}(e))throw o(s?.aborted?"cancelled":"timeout",e);if(e instanceof TypeError)throw o("network",e);throw o("unknown",e)}finally{l()}}class M{constructor(e=3e4){this.closeController=new AbortController,this.timeoutMs=e}abort(){this.closeController.abort()}isAborted(){return this.closeController.signal.aborted}getAbortSignal(){return this.closeController.signal}resetSession(){this.closeController=new AbortController}send(e,t,n,i,s=this.timeoutMs){return O(e,t,{timeoutMs:s,closeSignal:this.closeController.signal,read:i,fail:(e,t)=>{switch(e){case"cancelled":return this.makeError(n.cancelled,"cancelled",0);case"timeout":return this.makeError(n.timeout,"timeout",0);case"network":return this.makeError(n.network,"network_error",0);default:return this.makeError(t instanceof Error?t.message:"An unexpected error occurred","unknown_error",0)}}})}rawRequest(e,t){const n={Accept:"application/json"};return void 0!==t.body&&(n["Content-Type"]="application/json"),t.headers&&Object.assign(n,t.headers),this.send(e,{method:t.method,headers:n,body:t.body},{cancelled:"Request cancelled",timeout:`Request timed out after ${this.timeoutMs}ms`,network:"Unable to connect. Please check your connection and try again."},async e=>{if(!e.ok){const{status:t,message:n,code:i,details:s,retryAfterMs:r}=await x(e);throw this.makeError(n,i,t,s,r)}return t.onResponse?.(e),{data:await $(e),status:e.status}})}}function N(e){if("string"!=typeof e||""===e||"."===e||".."===e)return null;try{return encodeURIComponent(e)}catch{return null}}function H(e,t){const n=new Uint8Array(64),i=new Int8Array(128).fill(-1);for(let t=0;t<64;t+=1)n[t]=e.charCodeAt(t),i[n[t]]=t;return{codes:n,values:i,padded:t}}H("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",!0);const F=H("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",!1);function D(e){return 9===e||10===e||12===e||13===e||32===e}function V(e){return ArrayBuffer.isView(e)&&"[object Uint8Array]"===Object.prototype.toString.call(e)}function z(e,t){if(!V(e))throw new TypeError("Base64 encoding takes a Uint8Array");const{codes:n}=t,i=e.length%3,s=e.length-i;let r=0;i>0&&(r=t.padded?4:i+1);const o=new Uint8Array(s/3*4+r);let a=0;for(let t=0;t<s;t+=3){const i=e[t]<<16|e[t+1]<<8|e[t+2];o[a++]=n[i>>18],o[a++]=n[i>>12&63],o[a++]=n[i>>6&63],o[a++]=n[63&i]}if(i>0){const t=e[s]<<16|(2===i?e[s+1]<<8:0);o[a++]=n[t>>18],o[a++]=n[t>>12&63],2===i&&(o[a++]=n[t>>6&63]),o.fill(61,a)}return function(e){let t="";for(let n=0;n<e.length;n+=8192)t+=String.fromCharCode.apply(null,e.subarray(n,n+8192));return t}(o)}function U(e){return z(e,F)}function j(e,{canonical:t=!1}={}){return function(e,t,n){if("string"!=typeof e)return null;const{values:i}=t;let s=0,r=0;for(let t=0;t<e.length;t+=1){const o=e.charCodeAt(t);if(D(o)){if(n)return null}else if(61===o)r+=1;else{if(r>0||o>127||i[o]<0)return null;s+=1}}const o=s%4;if(1===o)return null;if(r>0&&(r>2||(s+r)%4!=0))return null;if(n&&r!==(t.padded?(4-o)%4:0))return null;const a=new Uint8Array(3*s>>2);let l=0,d=0,c=0;for(let t=0;t<e.length;t+=1){const n=e.charCodeAt(t);if(61===n)break;D(n)||(l=4095&(l<<6|i[n]),d+=6,d>=8&&(d-=8,a[c++]=l>>d))}return n&&l&(1<<d)-1?null:a}(e,F,t)}const W=function(e){if(!Array.isArray(e)||0===e.length)throw new TypeError("An entropy layout names at least one field");const t=new Set;let n=0;for(const[i,s]of e){if("string"!=typeof i||0===i.length||t.has(i))throw new TypeError(`Entropy layout field names must be unique non-empty strings (${String(i)})`);if(!Number.isSafeInteger(s)||s<=0)throw new TypeError(`Entropy layout field ${i} must be a positive whole number of bytes`);t.add(i),n+=s}if(n>1024)throw new TypeError(`An entropy layout of ${n} bytes exceeds one 1024-byte draw`);return Object.freeze({bytes:n,fields:Object.freeze(e.map(([e,t])=>Object.freeze([e,t])))})}([["codeVerifier",32],["state",16],["nonce",16]]);function q(e){const{codeVerifier:t,state:n,nonce:i}=function(e,t){if(!V(e)||e.length!==t.bytes)throw new TypeError(`An entropy draw for this layout is exactly ${t.bytes} bytes`);const n={};let i=0;for(const[s,r]of t.fields)n[s]=e.subarray(i,i+r),i+=r;return n}(e,W);return{codeVerifier:U(t),state:U(n),nonce:U(i)}}function K(e,t){const n=j(e?.value,{canonical:!0});if(!n||n.length!==t||e.num_bytes!==t||/[^A-Za-z0-9_-]/.test(e.value))throw new Error(`The Identity origin answered a malformed draw for ${t} bytes`);return n}W.bytes;const G=Object.freeze({redirectUri:"redirect_uri",state:"state",authRequestId:"auth_request_id",prompt:"prompt"}),Y=Object.freeze({token:"token",state:"state"}),J="federation";const X=Object.freeze({pendingTtlMs:6e5}),Z=Object.freeze({param:"signin_ref",bytes:32,drawPurpose:"signin_reference",fromOpenerParam:"signin_ref_from",fromOpenerValue:"opener",noRecoveryValue:"none",message:"sparkvault-signin-ref",retryMessage:"sparkvault-signin-ref-retry",drawDeadlineMs:2500,openerWaitMs:4e3,redirectWaitMs:500});function Q(e){return"string"==typeof e&&/^[A-Za-z0-9_-]{43}$/.test(e)}const ee=Object.freeze({param:"identity_types",values:Object.freeze(["email","phone","social","federated"]),refusalCode:"IDENTITY_TYPE_NOT_ALLOWED"});function te(e){if(!Array.isArray(e)||0===e.length||!e.every(e=>ee.values.includes(e)))throw new TypeError(`identity types must name at least one of ${ee.values.join(", ")}`);return ee.values.filter(t=>e.includes(t)).join(",")}function ne(e){if(null==e)return{ok:!0,types:null};if("string"!=typeof e)return{ok:!1};const t=e.split(",");return t.every(e=>ee.values.includes(e))&&new Set(t).size===t.length?{ok:!0,types:ee.values.filter(e=>t.includes(e))}:{ok:!1}}function ie(e,t){return null===t||t.includes(e)}function se(e,t){return null===t||function(e){return"otp_email"===e||"sparklink"===e?["email"]:"otp_sms"===e||"otp_voice"===e?["phone"]:"passkey"===e?["email","phone","social"]:e===J?["federated"]:"string"==typeof e&&e.startsWith("social_")?["social"]:"string"==typeof e&&e.startsWith("enterprise_")?["email"]:[]}(e).some(e=>ie(e,t))}const re=Object.freeze({email:"an email address",phone:"a phone number",social:"a social account",federated:"your organization's sign-in"});function oe(e){return`This sign-in accepts only ${function(e){const t=e.map(e=>re[e]);return 1===t.length?t[0]:`${t.slice(0,-1).join(", ")} or ${t[t.length-1]}`}(e)}, and none of the ways to sign in here gives one. Contact the site you came from for help.`}function ae(e,...t){const n=function(e,t){let n=e[0];for(let i=0;i<t.length;i+=1){const s=N(t[i]);if(null===s)return null;n+=s+e[i+1]}return n}(e,t);if(null===n)throw new m("A path value must be exactly one path segment",{received:t.find(e=>null===N(e))});return n}class le{constructor(e){this.intervalId=null,this.secondsRemaining=e.duration,this.onTick=e.onTick,this.onComplete=e.onComplete}start(){this.stop(),this.onTick(this.secondsRemaining),this.intervalId=setInterval(()=>{this.secondsRemaining--,this.onTick(this.secondsRemaining),this.secondsRemaining<=0&&(this.stop(),this.onComplete())},1e3)}stop(){null!==this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null)}isRunning(){return null!==this.intervalId}getRemainingSeconds(){return this.secondsRemaining}}class de{constructor(e){this.intervalId=null,Number.isFinite(e.expiresAt)?this.expiresAt=e.expiresAt:(console.warn("[ExpirationTimer] Invalid expiresAt:",e.expiresAt),this.expiresAt=0),this.onTick=e.onTick,this.onExpired=e.onExpired}calculateRemaining(){const e=Math.floor(Date.now()/1e3),t=this.expiresAt-e;return!Number.isFinite(t)||t<0?0:Math.ceil(t)}start(){this.stop();const e=this.calculateRemaining();this.onTick(e),e<=0?this.onExpired():this.intervalId=setInterval(()=>{const e=this.calculateRemaining();this.onTick(e),e<=0&&(this.stop(),this.onExpired())},1e3)}stop(){null!==this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null)}isRunning(){return null!==this.intervalId}}function ce(e){return U(new Uint8Array(e))}function he(e){if(void 0===e)return null;const t=()=>new m(`identityTypes must name at least one of ${ee.values.join(", ")}`,{field:"identityTypes",received:e});let n;try{n=te(e)}catch{throw t()}const i=ne(n);if(!i.ok||null===i.types)throw t();return i.types}function ue(e){return e?{[ee.param]:te(e)}:{}}function pe(){return`${window.location.origin}${window.location.pathname}${window.location.search}`}function me(e,t,n){const i=new URLSearchParams({origin:window.location.origin});t.email?i.set("email",t.email):t.phone&&i.set("phone",t.phone);const s=t.authContext;return s?.authRequestId?i.set("auth_request",s.authRequestId):s?.simpleMode?.sessionId&&(i.set("mode","simple"),i.set("session",s.simpleMode.sessionId)),"select_account"===t.prompt&&i.set("prompt","select_account"),t.method===J&&i.set("method",J),t.identityTypes&&i.set(ee.param,te(t.identityTypes)),"popup"===n.kind?i.set(Z.fromOpenerParam,Z.fromOpenerValue):(n.signinRef?i.set(Z.param,n.signinRef):i.set(Z.fromOpenerParam,Z.noRecoveryValue),n.handoff&&(i.set("redirect_uri",n.handoff.redirectUri),i.set("state",n.handoff.state),i.set("code_challenge",n.handoff.codeChallenge))),`${e.identityBaseUrl}/${e.accountId}/signin?${i}`}class fe extends M{constructor(e,t){super(t),this.configCache=null,this.config=e}get accountId(){return this.config.accountId}get baseUrl(){return`${this.config.identityBaseUrl}${ae`/${this.config.accountId}`}`}makeError(e,t,n,i,s=null){return new ke(e,t,n,i,s)}async request(e,t,n,i){const{data:s}=await this.rawRequest(`${this.baseUrl}${t}${function(e){const t=new URLSearchParams;for(const[n,i]of Object.entries(e??{}))null!=i&&""!==i&&t.append(n,String(i));const n=t.toString().replace(/\+/g,"%20");return n?`?${n}`:""}(i)}`,{method:e,body:n?JSON.stringify(n):void 0});return"object"==typeof s&&null!==s&&"data"in s?s.data:s}async getConfig(){this.configCache||(this.configCache=this.request("GET",ae`/config`));try{return await this.configCache}catch(e){throw this.configCache=null,e}}preloadConfig(){if(this.configCache)return;const e=this.request("GET",ae`/config`);this.configCache=e,e.catch(()=>{})}isConfigPreloaded(){return null!==this.configCache}async drawAuthorizationValues(){return q(K(await this.request("POST",ae`/entropy`,{num_bytes:W.bytes}),W.bytes))}async drawSigninReference(){const e=U(K(await this.request("POST",ae`/entropy`,{num_bytes:Z.bytes,purpose:Z.drawPurpose}),Z.bytes));if(!Q(e))throw new p("The Identity origin answered a malformed sign-in reference","invalid_response");return e}async checkPasskey(e,t="email",n){const i="phone"===t?{phone:e}:{email:e};return this.request("POST",ae`/passkey/check`,{...i,...ve(n)})}async redeemHandoffCode(e,t){return this.request("POST",ae`/signin/redeem`,{code:e,code_verifier:t})}buildAuthContextParams(e){return{...e?.authRequestId?{auth_request_id:e.authRequestId}:{},...ve(e)}}async sendOtp(e){return this.request("POST",ae`/otp/send`,{recipient:e.recipient,method:e.method,...this.buildAuthContextParams(e.authContext),...ue(e.identityTypes??null)})}async verifyOtp(e){return this.request("POST",ae`/otp/verify`,{kindling:e.kindling,pin:e.pin,recipient:e.recipient,...this.buildAuthContextParams(e.authContext),...ge(e.signinRef)})}async submitSecondFactor(e){return this.request("POST",ae`/second-factor/verify`,{ticket:e.ticket,code:e.code})}async startPasskeyVerify(e,t="email",n,i=null){const s=e?{[t]:e}:{},r=await this.request("POST",ae`/passkey/verify`,{...s,...ve(n),...ue(i)});return{challenge:r.options.challenge,rpId:r.options.rpId,timeout:r.options.timeout,...r.options.allowCredentials?{allowCredentials:r.options.allowCredentials}:{},session:r.session}}async completePasskeyVerify(e){const t=e.credential.response;return this.request("POST",ae`/passkey/verify/complete`,{session:e.session,...this.buildAuthContextParams(e.authContext),...ge(e.signinRef),credential:{id:e.credential.id,rawId:ce(e.credential.rawId),type:e.credential.type,response:{clientDataJSON:ce(t.clientDataJSON),authenticatorData:ce(t.authenticatorData),signature:ce(t.signature),userHandle:t.userHandle?ce(t.userHandle):null}}})}async sendBackupVerification(e){return this.request("POST",ae`/backup-verification/send`,{verification_token:e.verificationToken,type:e.type,value:e.value,...e.method?{method:e.method}:{}})}async verifyBackupVerification(e){return this.request("POST",ae`/backup-verification/verify`,{session_id:e.sessionId,code:e.code})}async dismissRecommendation(e){await this.request("POST",ae`/recommendations/dismiss`,{verification_token:e.verificationToken,key:e.key})}getSocialAuthUrl(e,t,n,i,s={}){const r=new URLSearchParams({[G.redirectUri]:t,[G.state]:n,...ge(s.signinRef),...ue(s.identityTypes??null)});i?.authRequestId&&r.set(G.authRequestId,i.authRequestId);const{simple_mode:o}=ve(i);return o&&r.set("simple_mode",JSON.stringify(o)),`${this.baseUrl}/social/${e}?${r}`}getFederationAuthUrl(e,t,n,i={}){const s=new URLSearchParams({[G.redirectUri]:e,[G.state]:t,...ge(i.signinRef),...ue(i.identityTypes??null)});return n?.authRequestId&&s.set(G.authRequestId,n.authRequestId),i.silent&&s.set(G.prompt,"none"),`${this.baseUrl}/federation?${s}`}async sendSparkLink(e,t,n,i,s=null){return this.request("POST",ae`/sparklink/send`,{email:e,connection_id:t,...this.buildAuthContextParams(n),...ge(i),...ue(s)})}async consumeSparkLinkResult(e){return ye(await this.request("GET",ae`/sparklink/result`,void 0,{kindling:e}))}}function ve(e){return e?.simpleMode?{simple_mode:{session_id:e.simpleMode.sessionId}}:{}}function ge(e){return e?{[Z.param]:e}:{}}function ye(e){if(!e||"object"!=typeof e)return null;const t=e;if("sparklink_second_factor"===t.type){if("string"!=typeof t.ticket||!t.ticket)return null;const e=Array.isArray(t.methods)?t.methods.filter(e=>"string"==typeof e):[];return{kind:"second_factor",ticket:t.ticket,methods:e.length>0?e:["authenticator"]}}if("sparklink_verified"!==t.type)return null;const n="string"==typeof t.token&&t.token?t.token:void 0,i="string"==typeof t.redirect&&t.redirect?t.redirect:void 0;return n||i?{kind:"verified",result:{token:n??"",identity:"string"==typeof t.identity?t.identity:"",identityType:t.identityType||"email",svid:"string"==typeof t.svid?t.svid:void 0,sessionId:"string"==typeof t.session_id?t.session_id:void 0,refreshToken:"string"==typeof t.refresh_token?t.refresh_token:void 0,redirect:i,recommendations:be(t.recommendations)}}:null}function be(e){if(!Array.isArray(e))return;const t=[];for(const n of e){if(!n||"object"!=typeof n)continue;const e=n;"passkey"===e.type?t.push({type:"passkey"}):"backup_identifier"!==e.type||"email"!==e.missing_type&&"phone"!==e.missing_type||t.push({type:"backup_identifier",missingType:e.missing_type})}return t}class ke extends p{constructor(e,t,n,i,s=null){super(e,t,n,i,s),this.name="IdentityApiError",Object.setPrototypeOf(this,ke.prototype)}}const we=/^\D*\+/,xe=/^[1-9]\d{7,14}$/,Ce=/\p{Cf}/gu,Se=/^[\s().\p{Pd}]*\+?[\d\s().\p{Pd}]*$/u,Ee=/^[+(\d]/;function Te(e){return e.replace(Ce,"")}function Ae(e){if("string"!=typeof e)return null;const t=Te(e);if(!Se.test(t))return null;const n=t.replace(/\D/g,"");return we.test(t)?xe.test(n)?`+${n}`:null:10===n.length?`+1${n}`:11===n.length&&n.startsWith("1")?`+${n}`:null}function Le(e){if("string"!=typeof e)return"email";const t=Te(e).trim();return Ee.test(t)&&Se.test(t)?"phone":"email"}function Ie(e){const t=Te(e);if(!Se.test(t))return e;const n=t.replace(/\D/g,"");if(we.test(t)&&(!n.startsWith("1")||11!==n.length))return`+${n}`;if(n.length>11||11===n.length&&!n.startsWith("1"))return n;const i=11===n.length?n.slice(1):n;return 0===i.length?"":i.length<=3?`(${i}`:i.length<=6?`(${i.slice(0,3)}) ${i.slice(3)}`:`(${i.slice(0,3)}) ${i.slice(3,6)}-${i.slice(6,10)}`}const Re={otp_email:{id:"otp_email",type:"otp",identityType:"email",name:"Email code",description:"Get a one-time code via email",icon:"email"},otp_sms:{id:"otp_sms",type:"otp",identityType:"phone",name:"Text message",description:"Get a one-time code via SMS",icon:"sms"},otp_voice:{id:"otp_voice",type:"otp",identityType:"phone",name:"Voice call",description:"Get a one-time code via phone call",icon:"phone"},passkey:{id:"passkey",type:"passkey",name:"Passkey",description:"Use biometrics or security key",icon:"fingerprint"},sparklink:{id:"sparklink",type:"sparklink",identityType:"email",name:"SparkLink",description:"Get an instant sign-in link via email",icon:"link"},social_google:{id:"social_google",type:"social",identityType:"email",name:"Google",description:"Sign in with Google",icon:"google",provider:"google"},social_apple:{id:"social_apple",type:"social",identityType:"email",name:"Apple",description:"Sign in with Apple",icon:"apple",provider:"apple"},social_microsoft:{id:"social_microsoft",type:"social",identityType:"email",name:"Microsoft",description:"Sign in with Microsoft",icon:"microsoft",provider:"microsoft"},social_github:{id:"social_github",type:"social",identityType:"email",name:"GitHub",description:"Sign in with GitHub",icon:"github",provider:"github"},social_facebook:{id:"social_facebook",type:"social",identityType:"email",name:"Facebook",description:"Sign in with Facebook",icon:"facebook",provider:"facebook"},social_linkedin:{id:"social_linkedin",type:"social",identityType:"email",name:"LinkedIn",description:"Sign in with LinkedIn",icon:"linkedin",provider:"linkedin"},federation:{id:"federation",type:"federation",name:"Your organization",description:"",icon:"building"}};function Be(e,t){return e.map(e=>{return"federation"!==e?Re[e]:t?{...Re.federation,name:(n=t.display_name,`Continue with ${n}`)}:void 0;var n}).filter(e=>void 0!==e)}const _e="federation_failed",Pe="sv_federation_auto_start";function $e(e){let t;try{t=sessionStorage.getItem(Pe),sessionStorage.removeItem(Pe)}catch{return!1}if(null===t)return!1;try{const n=JSON.parse(t);if("object"!=typeof n||null===n)return!1;const{at:i,accountId:s}=n;return s===e&&"number"==typeof i&&Number.isFinite(i)&&Date.now()-i<9e5}catch{return!1}}class Oe{constructor(){this._sdkConfig=null,this._viewState={view:"loading"},this._recipient="",this._identityType="email",this._authContext=void 0,this._signinRef=null,this._identityTypes=null,this._passkey={hasPasskey:null,isFallbackMode:!1,pendingResult:null},this._otp={kindling:"",method:null}}get sdkConfig(){return this._sdkConfig}setConfig(e){this._sdkConfig=e}get accountId(){return this._sdkConfig?.accountId??""}get viewState(){return this._viewState}setViewState(e){this._viewState=e}get recipient(){return this._recipient}get identityType(){return this._identityType}setIdentity(e,t){this._recipient=e,this._identityType=t}get methodIds(){return this._authContext?.simpleMode?.methods??this._sdkConfig?.methods??[]}get passkeyRequired(){return!0===this._authContext?.simpleMode?.passkeyRequired}getAllowedIdentityTypes(){const e=this._authContext?.simpleMode?.allowedIdentityTypes;if(e)return e;if(!this._sdkConfig)return["email"];return this._sdkConfig.allowedIdentityTypes??["email"]}get authContext(){return this._authContext}setAuthContext(e){this._authContext=e}get signinRef(){return this._signinRef}setSigninRef(e){this._signinRef=e}get identityTypes(){return this._identityTypes}setIdentityTypes(e){this._identityTypes=e}get passkey(){return this._passkey}setPasskeyStatus(e){this._passkey.hasPasskey=e}enablePasskeyFallback(){this._passkey.isFallbackMode=!0}setPendingResult(e){this._passkey.pendingResult=e}get otp(){return this._otp}setKindling(e){this._otp.kindling=e}setOtpMethod(e){this._otp.method=e}}class Me{openPopup(e){const t=e.width??480,n=e.height??640,i=e.timeoutMs??18e5;return new Promise((s,r)=>{const o=Math.round((window.screen.width-t)/2),a=Math.round((window.screen.height-n)/2),l=window.open(e.url,e.windowName,`width=${t},height=${n},left=${o},top=${a},popup=1`);if(!l)return void r(new y);e.onOpen?.(l);const d=Date.now();let c=!1,h=!1;const u=()=>{window.removeEventListener("message",p),clearTimeout(m),clearInterval(g)},p=t=>{if(t.origin!==e.trustedOrigin)return;const n=t.data;if(e.readyType&&n?.type===e.readyType)return h=!0,void e.onReady?.();e.requestType&&n?.type===e.requestType?t.source===l&&e.onRequest?.():n?.type===e.resultType&&(c=!0,u(),s(n))};window.addEventListener("message",p);const m=setTimeout(()=>{c||(c=!0,u(),l.close(),r(new f("Popup operation timed out. Please try again.")))},i),g=setInterval(()=>{if(l.closed&&!c){if(c=!0,u(),!h&&Date.now()-d<=2500)return void r(new b);r(new v("Authentication was cancelled."))}},500)})}}function Ne(e){const t=j(e);if(null===t)throw new ke("The passkey options are not valid base64url","invalid_response",0);return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}class He{constructor(e,t){this.api=e,this.state=t,this.popupLauncher=new Me;const n=e.config;this.baseUrl=n.identityBaseUrl,this.accountId=n.accountId,this.trustedOrigin=new URL(this.baseUrl).origin}async checkPasskey(){try{const e=await this.api.checkPasskey(this.state.recipient,this.state.identityType,this.state.authContext);this.state.setPasskeyStatus(e.has_passkey)}catch(e){console.warn("Passkey check failed:",e),this.state.setPasskeyStatus(null)}}async register(e){const t=await this.openPasskeyPopup("register",e);return t.success&&this.state.setPasskeyStatus(!0),t}async verify(e){return this.canRunCeremonyInline()?this.verifyInline(e):this.openPasskeyPopup("verify")}canRunCeremonyInline(){return"undefined"!=typeof window&&"undefined"!=typeof navigator&&!!navigator.credentials&&window.location.origin===this.trustedOrigin}canAutoVerify(){return!!this.canRunCeremonyInline()&&document.cookie.split(";").some(e=>e.trim().startsWith("__Host-authsv_passkey=1"))}async verifyInline(e){try{const t="phone"===this.state.identityType?"phone":"email",n=await this.api.startPasskeyVerify(this.state.recipient,t,this.state.authContext,this.state.identityTypes),i=await navigator.credentials.get({...e?{signal:e}:{},publicKey:{challenge:Ne(n.challenge),rpId:n.rpId,timeout:n.timeout,userVerification:"required",...n.allowCredentials?{allowCredentials:n.allowCredentials.map(e=>({type:e.type,id:Ne(e.id)}))}:{}}});if(!i)return{success:!1,error:"Failed to get passkey",errorType:"unknown"};const s=await this.api.completePasskeyVerify({session:n.session,credential:i,authContext:this.state.authContext,signinRef:this.state.signinRef});return{success:!0,result:{token:s.token,identity:s.identity||this.state.recipient,identityType:s.identity_type||"email",svid:s.svid,sessionId:s.session_id,refreshToken:s.refresh_token,redirect:s.redirect}}}catch(e){return this.mapInlineCeremonyError(e)}}mapInlineCeremonyError(e){return e instanceof Error&&("NotAllowedError"===e.name||"AbortError"===e.name)?{success:!1,error:"Authentication was cancelled. Please try again.",errorType:"cancelled"}:e instanceof ke?"identity_locked"===e.code?{success:!1,error:"This SparkVault Identity is locked. Visit auth.sv to manage it.",errorType:"unknown",errorCode:"identity_locked"}:"passkey_not_registered"===e.code?{success:!1,error:"No passkey found. Create one to continue.",errorType:"not_found",errorCode:"passkey_not_registered"}:{success:!1,error:e.message||"Passkey authentication failed",errorType:"unknown",errorCode:e.code}:{success:!1,error:e instanceof Error?e.message:"Passkey authentication failed",errorType:"unknown"}}async openPasskeyPopup(e,t){const n=new URLSearchParams({mode:e,origin:window.location.origin});if(this.state.recipient){const e="phone"===this.state.identityType?"phone":"email";n.set(e,this.state.recipient)}const i=this.state.authContext;i?.authRequestId&&n.set("auth_request_id",i.authRequestId);const{simple_mode:s}=ve(i);s&&n.set("simple_mode",JSON.stringify(s));const{signinRef:r}=this.state;r&&n.set(Z.param,r);const{identityTypes:o}=this.state;o&&n.set(ee.param,te(o));const a="register"===e&&t?`#${new URLSearchParams({registration_token:t}).toString()}`:"",l=`${this.baseUrl}/${this.accountId}/passkey/popup?${n}${a}`;let d;try{d=await this.popupLauncher.openPopup({url:l,windowName:"sparkvault-passkey",width:450,height:500,resultType:"sparkvault-passkey-result",trustedOrigin:this.trustedOrigin})}catch(e){return e instanceof y?{success:!1,error:e.message,errorType:"popup_blocked"}:e instanceof v?{success:!1,error:e.message,errorType:"cancelled"}:{success:!1,error:e instanceof Error?e.message:"Passkey operation failed. Please try again.",errorType:"unknown"}}return d.success&&d.data?{success:!0,result:{token:d.data.token||"",identity:d.data.identity||this.state.recipient,identityType:d.data.identity_type||"email",svid:d.data.svid,sessionId:d.data.session_id,refreshToken:d.data.refresh_token,redirect:d.data.redirect}}:this.handlePopupError(d.error,d.message,d.errorCode)}handlePopupError(e,t,n){return"cancelled"===e?{success:!1,error:t||"Authentication was cancelled. Please try again.",errorType:"cancelled"}:"identity_locked"===n||"identity_locked"===e?{success:!1,error:t||"This SparkVault Identity is locked. Visit auth.sv to manage it.",errorType:"unknown",errorCode:"identity_locked"}:t?.includes("No passkey")||t?.includes("not found")?{success:!1,error:"No passkey found. Create one to continue.",errorType:"not_found"}:{success:!1,error:t||e||"Passkey authentication failed",errorType:"unknown",errorCode:n}}}class Fe{constructor(e,t){this.api=e,this.state=t}async send(e){try{const t=await this.api.sendOtp({recipient:this.state.recipient,method:e,authContext:this.state.authContext,identityTypes:this.state.identityTypes});return this.state.setKindling(t.kindling),this.state.setOtpMethod(e),{success:!0,kindling:t.kindling,expiresAt:t.expires_at}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Failed to send code",errorCode:e instanceof p?e.code:void 0}}}async resend(){const e=this.state.otp.method;if(!e)return{success:!1,error:"No OTP method set"};try{const t=await this.api.sendOtp({recipient:this.state.recipient,method:e,authContext:this.state.authContext,identityTypes:this.state.identityTypes});return this.state.setKindling(t.kindling),{success:!0,kindling:t.kindling,expiresAt:t.expires_at}}catch(e){return{success:!1,error:`Failed to resend: ${e instanceof Error?e.message:"Failed to resend code"}`,errorCode:e instanceof p?e.code:void 0}}}async verify(e){const t=this.state.otp.kindling;if(!t)return{success:!1,error:"No kindling available"};try{const n=await this.api.verifyOtp({kindling:t,pin:e,recipient:this.state.recipient,authContext:this.state.authContext,signinRef:this.state.signinRef});return n.second_factor_required&&n.ticket?{success:!1,secondFactor:{ticket:n.ticket,methods:n.methods??["authenticator"]}}:n.verified&&(n.token||n.redirect)?{success:!0,result:{token:n.token??"",identity:n.identity??this.state.recipient,identityType:n.identity_type??this.state.identityType,svid:n.svid,sessionId:n.session_id,refreshToken:n.refresh_token,redirect:n.redirect,recommendations:be(n.recommendations)}}:(n.kindling&&this.state.setKindling(n.kindling),{success:!1,newKindling:n.kindling,retryAfter:n.retry_after,backoffExpires:n.retry_after,error:"Invalid code. Please try again."})}catch(e){return{success:!1,error:e instanceof Error?e.message:"Verification failed",errorCode:e instanceof p?e.code:void 0}}}}class De{constructor(e,t){this.api=e,this.state=t}async send(e){try{const t=await this.api.sendSparkLink(this.state.recipient,e,this.state.authContext,this.state.signinRef,this.state.identityTypes);return{success:!0,expiresAt:t.expiresAt,kindling:t.kindling}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Failed to send SparkLink",errorCode:e instanceof p?e.code:void 0}}}}const Ve=new RegExp("^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$"),ze=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,Ue=Object.freeze({ADDRESS:320,LOCAL_PART:64,DOMAIN:255}),je=Object.freeze({FORMAT:"format",TOO_LONG:"too_long",LOCAL_PART_TOO_LONG:"local_part_too_long",DOMAIN_TOO_LONG:"domain_too_long"});function We(e){if("string"!=typeof e)throw new TypeError("An email address is a string");return e.trim().toLowerCase()}function qe(e){return null===function(e){if("string"!=typeof e)return je.FORMAT;const t=We(e),n=t.indexOf("@");if(n<=0||n!==t.lastIndexOf("@"))return je.FORMAT;const i=t.slice(0,n),s=t.slice(n+1),r=s.split(".");return!Ve.test(i)||r.length<2||!r.every(e=>ze.test(e))?je.FORMAT:t.length>Ue.ADDRESS?je.TOO_LONG:i.length>Ue.LOCAL_PART?je.LOCAL_PART_TOO_LONG:s.length>Ue.DOMAIN?je.DOMAIN_TOO_LONG:null}(e)}function Ke(e,t){const n=document.createElement("div");return e&&(n.className=e),n}function Ge(e){for(;e.firstChild;)e.removeChild(e.firstChild)}function Ye(e){const t=document.createElement("div");return t.className="sv-error",t.setAttribute("role","alert"),t.textContent=e,t}function Je(e){return qe(e)?We(e):null}class Xe{constructor(e={}){this.message=e.message??"Loading...",!0===e.announce&&(this.announcement=this.message)}render(){const e=Ke("sv-loading"),t=document.createElement("div");t.className="sv-spinner";const n=document.createElement("p");return n.className="sv-loading-text",n.textContent=this.message,void 0!==this.announcement?(t.setAttribute("aria-hidden","true"),n.setAttribute("aria-hidden","true")):(t.setAttribute("role","status"),t.setAttribute("aria-label","Loading")),e.appendChild(t),e.appendChild(n),e}destroy(){}}const Ze=/[+\d]/;const Qe="0 0 24 24",et="#FFFFFF";function tt(e){for(const t of Object.values(e))t&&"object"==typeof t&&tt(t);return Object.freeze(e)}const nt=tt({google:[{d:"M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z",fill:"#4285F4"},{d:"M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z",fill:"#34A853"},{d:"M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z",fill:"#FBBC05"},{d:"M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z",fill:"#EA4335"}],apple:[{d:"M18.71 19.5c-.83 1.24-1.71 2.45-3.05 2.47-1.34.03-1.77-.79-3.29-.79-1.53 0-2 .77-3.27.82-1.31.05-2.3-1.32-3.14-2.53C4.25 17 2.94 12.45 4.7 9.39c.87-1.52 2.43-2.48 4.12-2.51 1.28-.02 2.5.87 3.29.87.78 0 2.26-1.07 3.81-.91.65.03 2.47.26 3.64 1.98-.09.06-2.17 1.28-2.15 3.81.03 3.02 2.65 4.03 2.68 4.04-.03.07-.42 1.44-1.38 2.83M13 3.5c.73-.83 1.94-1.46 2.94-1.5.13 1.17-.34 2.35-1.04 3.19-.69.85-1.83 1.51-2.95 1.42-.15-1.15.41-2.35 1.05-3.11z",fill:"currentColor"}],microsoft:[{d:"M1 1h10v10H1z",fill:"#F25022"},{d:"M1 13h10v10H1z",fill:"#00A4EF"},{d:"M13 1h10v10H13z",fill:"#7FBA00"},{d:"M13 13h10v10H13z",fill:"#FFB900"}],github:[{d:"M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0024 12c0-6.63-5.37-12-12-12z",fill:"currentColor"}],facebook:[{d:"M24 12.044c0-6.627-5.373-12-12-12s-12 5.373-12 12 5.373 12 12 12 12-5.373 12-12Z",fill:"#0866FF"},{d:"M9.101 23.691v-7.98H6.627v-3.667h2.474v-1.58c0-4.085 1.848-5.978 5.858-5.978.401 0 .955.042 1.468.103a8.68 8.68 0 0 1 1.141.195v3.325a8.623 8.623 0 0 0-.653-.036 26.805 26.805 0 0 0-.733-.009c-.707 0-1.259.096-1.675.309a1.686 1.686 0 0 0-.679.622c-.258.42-.374.995-.374 1.752v1.297h3.919l-.386 2.103-.287 1.564h-3.246v8.245A12 12 0 0 1 9.101 23.691Z",fill:et}],linkedin:[{d:"M22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z",fill:"#0A66C2"},{d:"M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433c-1.144 0-2.063-.926-2.063-2.065 0-1.138.92-2.063 2.063-2.063 1.14 0 2.064.925 2.064 2.063 0 1.139-.925 2.065-2.064 2.065zm1.782 13.019H3.555V9h3.564v11.452z",fill:et}]});function it(e,t=16,n=16){const i=document.createElementNS("http://www.w3.org/2000/svg","svg");return i.setAttribute("viewBox",e),i.setAttribute("width",String(t)),i.setAttribute("height",String(n)),i.setAttribute("fill","none"),i.setAttribute("xmlns","http://www.w3.org/2000/svg"),i}function st(e,t={}){const n=document.createElementNS("http://www.w3.org/2000/svg","path");n.setAttribute("d",e);for(const[e,i]of Object.entries(t))n.setAttribute(e,i);return n}function rt(e,t,n,i={}){const s=document.createElementNS("http://www.w3.org/2000/svg","circle");s.setAttribute("cx",String(e)),s.setAttribute("cy",String(t)),s.setAttribute("r",String(n));for(const[e,t]of Object.entries(i))s.setAttribute(e,t);return s}function ot(){const e=it("0 0 16 16");return e.appendChild(st("M13.25 4.75L6 12 2.75 8.75",{stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"})),e}function at(){const e=it("0 0 16 16");return e.appendChild(st("M10 12L6 8L10 4",{stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"})),e}function lt(){const e=it("0 0 56 56",56,56);e.classList.add("sv-passkey-icon");const t=document.createElementNS("http://www.w3.org/2000/svg","g");t.setAttribute("transform","translate(29.5, 26.5)");const n={stroke:"currentColor","stroke-width":"3","stroke-linecap":"round","stroke-linejoin":"round",fill:"none"};return t.appendChild(rt(-9.5,-9.5,9.5,n)),t.appendChild(st("M-2.8 -2.8L16 16",n)),t.appendChild(st("M9.5 9.5L9.5 15.5",n)),t.appendChild(st("M16 16L16 22",n)),e.appendChild(t),e}function dt(e){const t=it("0 0 48 48",48,48);t.classList.add(e);const n={stroke:"currentColor","stroke-width":"2.5","stroke-linecap":"round","stroke-linejoin":"round",fill:"none"};return t.appendChild(st("M24 9L5.5 39h37L24 9z",n)),t.appendChild(st("M24 20v8",n)),t.appendChild(rt(24,33.5,1.5,{fill:"currentColor"})),t}function ct(e){const t=function(e){switch(e){case"email":return function(){const e=it("0 0 20 20",20,20);return e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","1.5"),e.setAttribute("stroke-linecap","round"),e.setAttribute("stroke-linejoin","round"),e.appendChild(st("M3 4h14c.55 0 1 .45 1 1v10c0 .55-.45 1-1 1H3c-.55 0-1-.45-1-1V5c0-.55.45-1 1-1z")),e.appendChild(st("M18 5l-8 5.5L2 5")),e}();case"sms":return function(){const e=it("0 0 20 20",20,20);return e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","1.5"),e.setAttribute("stroke-linecap","round"),e.setAttribute("stroke-linejoin","round"),e.appendChild(st("M4 3.75h12A1.75 1.75 0 0117.75 5.5v5A1.75 1.75 0 0116 12.25H8.5L5 15.25V12.25H4A1.75 1.75 0 012.25 10.5v-5A1.75 1.75 0 014 3.75z")),e.appendChild(rt(7,8,.75,{fill:"currentColor",stroke:"none"})),e.appendChild(rt(10,8,.75,{fill:"currentColor",stroke:"none"})),e.appendChild(rt(13,8,.75,{fill:"currentColor",stroke:"none"})),e}();case"phone":return function(){const e=it("0 0 20 20",20,20);return e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","1.5"),e.setAttribute("stroke-linecap","round"),e.setAttribute("stroke-linejoin","round"),e.appendChild(st("M18 14v2.5a1.5 1.5 0 01-1.64 1.5 14.85 14.85 0 01-6.47-2.3 14.63 14.63 0 01-4.5-4.5A14.85 14.85 0 013.1 4.64 1.5 1.5 0 014.59 3H7.1a1.5 1.5 0 011.5 1.29 9.63 9.63 0 00.52 2.11 1.5 1.5 0 01-.34 1.58l-.95.95a12 12 0 004.5 4.5l.95-.95a1.5 1.5 0 011.58-.34 9.63 9.63 0 002.11.52A1.5 1.5 0 0118 14z")),e}();case"fingerprint":return function(){const e=it("0 0 20 20",20,20);return e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","1.5"),e.setAttribute("stroke-linecap","round"),e.setAttribute("stroke-linejoin","round"),e.appendChild(st("M2 10c0-4.42 3.58-8 8-8 2.65 0 5 1.29 6.47 3.28")),e.appendChild(st("M4 16.58c.42-.35.79-.76 1.1-1.22")),e.appendChild(st("M14.41 17.51c.09-.45.32-1.73.38-2.26")),e.appendChild(st("M10 8.33a1.5 1.5 0 00-1.5 1.5c0 .77-.08 1.88-.2 3")),e.appendChild(st("M7.21 18.33c.16-.5.34-1 .43-1.5")),e.appendChild(st("M11.67 10.93c0 1.79 0 4.79-.75 6.65")),e.appendChild(st("M17.33 13.33c.15-1.5.1-4.02 0-4.5")),e.appendChild(st("M7.5 5.67a4.5 4.5 0 016.75 3.9c0 .35 0 .88-.02 1.5")),e}();case"link":return function(){const e=it("0 0 20 20",20,20);return e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","1.5"),e.setAttribute("stroke-linecap","round"),e.setAttribute("stroke-linejoin","round"),e.appendChild(st("M8.33 10.83a3.75 3.75 0 005.66.41l2.25-2.25a3.75 3.75 0 00-5.3-5.3l-1.29 1.28")),e.appendChild(st("M11.67 9.17a3.75 3.75 0 00-5.66-.41l-2.25 2.25a3.75 3.75 0 005.3 5.3l1.28-1.28")),e}();case"google":case"apple":case"microsoft":case"github":case"facebook":case"linkedin":return function(e){const t=it(Qe,20,20);for(const{d:n,fill:i}of nt[e])t.appendChild(st(n,{fill:i}));return t}(e);case"building":return function(){const e=it("0 0 20 20",20,20);return e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","1.5"),e.setAttribute("stroke-linecap","round"),e.setAttribute("stroke-linejoin","round"),e.appendChild(st("M2.5 17.5h15")),e.appendChild(st("M4.17 17.5V5.83L10.83 2.5v15")),e.appendChild(st("M15.83 17.5V9.17l-5-3.33")),e.appendChild(st("M7.5 7.5v.01")),e.appendChild(st("M7.5 10v.01")),e.appendChild(st("M7.5 12.5v.01")),e.appendChild(st("M7.5 15v.01")),e}();case"users":return function(){const e=it("0 0 20 20",20,20);return e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","1.5"),e.setAttribute("stroke-linecap","round"),e.setAttribute("stroke-linejoin","round"),e.appendChild(st("M14.17 17.5v-1.67a3.33 3.33 0 00-3.34-3.33H4.17a3.33 3.33 0 00-3.34 3.33v1.67")),e.appendChild(rt(7.5,5.83,3.33,{stroke:"currentColor","stroke-width":"1.5",fill:"none"})),e.appendChild(st("M19.17 17.5v-1.67a3.33 3.33 0 00-2.5-3.22")),e.appendChild(st("M13.33 2.6a3.33 3.33 0 010 6.46")),e}();default:return function(){const e=it("0 0 20 20",20,20);return e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","1.5"),e.setAttribute("stroke-linecap","round"),e.setAttribute("stroke-linejoin","round"),e.appendChild(st("M6 2.75h8A3.25 3.25 0 0117.25 6v8A3.25 3.25 0 0114 17.25H6A3.25 3.25 0 012.75 14V6A3.25 3.25 0 016 2.75z")),e.appendChild(rt(10,10,1.25,{fill:"currentColor",stroke:"none"})),e}()}}(e);return t.setAttribute("data-sv-method-icon",e),t}function ht(e){const t=document.createElement("button");t.className="sv-btn sv-btn-method";const n=Ke("sv-method-content"),i=Ke("sv-method-icon");i.setAttribute("aria-hidden","true"),i.appendChild(ct(e.icon)),n.appendChild(i);const s=Ke("sv-method-text"),r=document.createElement("div");if(r.className="sv-method-name",r.textContent=e.name,s.appendChild(r),e.description){const t=document.createElement("div");t.className="sv-method-description",t.textContent=e.description,s.appendChild(t)}return n.appendChild(s),t.appendChild(n),t}const ut=Object.freeze({beforeTerms:"By providing a phone number, you agree to receive texts from SparkVault with verification codes, security alerts and account notifications, and automated calls with verification codes, as its ",terms:"Terms",beforePrivacy:" and ",privacy:"Privacy Policy",afterPrivacy:" describe. Message frequency varies. Message and data rates may apply. Reply STOP to opt out or HELP for help."});function pt(e,t){const n=document.createElement("a");return n.className="sv-sms-consent-link",n.href=t,n.target="_blank",n.rel="noopener noreferrer",n.textContent=e,n}function mt(e){const t=document.createElement("p");return t.className="sv-sms-consent",t.id=e,t.append(ut.beforeTerms,pt(ut.terms,"https://sparkvault.com/terms/"),ut.beforePrivacy,pt(ut.privacy,"https://sparkvault.com/privacy/"),ut.afterPrivacy),t}class ft{constructor(e){this.container=null,this.inputElement=null,this.labelElement=null,this.submitButton=null,this.passkeyLink=null,this.leadingButton=null,this.leadingHandler=null,this.errorContainer=null,this.focusTimeoutId=null,this.identityInput=null,this.props=e,this.boundHandleKeyDown=e=>{"Enter"===e.key&&(e.preventDefault(),this.handleSubmit())},this.boundHandleSubmit=()=>this.handleSubmit(),this.boundHandlePasskey=e.onPasskey?()=>e.onPasskey():null}get allowsBoth(){return this.props.allowedTypes.includes("email")&&this.props.allowedTypes.includes("phone")}get allowsEmail(){return this.props.allowedTypes.includes("email")}get allowsPhone(){return this.props.allowedTypes.includes("phone")}render(){const e=Ke("sv-email-view");this.container=e,this.props.leadingMethod&&this.offerLeadingMethod(this.props.leadingMethod);const t=Ke("sv-email-header"),n=document.createElement("p");n.className="sv-email-subtitle",n.textContent=this.getSubtitleText(),t.appendChild(n),e.appendChild(t),this.errorContainer=Ke("sv-email-error-container"),this.props.error&&this.errorContainer.appendChild(Ye(this.props.error)),e.appendChild(this.errorContainer);const i=Ke("sv-email-form"),s=Ke("sv-email-input-wrapper");if(this.labelElement=document.createElement("label"),this.labelElement.className="sv-email-label",this.labelElement.htmlFor="sv-identity-input",this.labelElement.textContent=this.getLabelText(),this.inputElement=document.createElement("input"),this.inputElement.type=this.allowsPhone&&!this.allowsEmail?"tel":"text",this.inputElement.id="sv-identity-input",this.inputElement.className="sv-email-input",this.inputElement.placeholder=this.getPlaceholderText(),this.inputElement.autocomplete=this.allowsBoth?"on":this.allowsEmail?"email":"tel",this.inputElement.required=!0,this.inputElement.maxLength=Ue.ADDRESS,this.props.initialValue&&(this.inputElement.value=this.props.initialValue),this.identityInput=function(e,{allowedTypes:t=["email","phone"],onChange:n}={}){let i=e.value,s=i,r=[],o=!1,a=null,l=[{value:i,start:i.length,end:i.length}],d=0;const c=1===t.length&&"phone"===t[0],h=t.includes("phone"),u=()=>c?"phone":h?Le(i):"email";function p(e){return s===i||0===e?e:e>=s.length?i.length:r.find(t=>t.display>=e)?.value??i.length}function m(e){if(s===i)return e;if(e>=i.length)return s.length;for(let t=r.length-1;t>=0;t-=1)if(r[t].value<e)return r[t].display+1;return r[0]?.display??0}function f(t=null,n=t){s="phone"===u()?Ie(i):i,r=s===i?[]:function(e,t){const n=[...e.matchAll(/[+\d]/g)].map(e=>e.index),i=[...t.matchAll(/[+\d]/g)].map(e=>e.index);return i.map((e,t)=>({display:e,value:n[t+n.length-i.length]}))}(i,s),e.value=s,e.inputMode=c?"tel":"text",e.autocapitalize="none",e.spellcheck=!1,null!==t&&e.setSelectionRange(m(t),m(n))}function v(t){a=null;const s=Math.max(0,Math.min(l.length-1,d+t)),r=s!==d;d=s;const o=l[d];i=o.value,f(),e.setSelectionRange(o.start,o.end),r&&n?.(i,u())}function g(e){return"historyUndo"===e.inputType?-1:"historyRedo"===e.inputType?1:0}function y(e){if(o||e.isComposing||e.altKey||!e.metaKey&&!e.ctrlKey)return;const t=e.key.toLowerCase(),n="z"===t?e.shiftKey?1:-1:"y"===t&&e.ctrlKey?1:0;n&&(e.preventDefault(),v(n))}function b(){const t=e.selectionStart??s.length,n=e.selectionEnd??t;l[d]={value:i,start:t,end:n}}function k(t){if(o||t.isComposing)return;const n=g(t);if(n)return void(t.cancelable&&(t.preventDefault(),v(n)));b();let i=e.selectionStart??s.length,r=e.selectionEnd??i;i===r&&"deleteContentBackward"===t.inputType&&(i=Math.max(0,i-1)),i===r&&"deleteContentForward"===t.inputType&&(r=Math.min(s.length,r+1)),a={start:i,end:r,inputType:t.inputType,display:s}}function w(t){if(o||t.isComposing)return;const r=g(t);if(r)return void v(r);const c=e.value;if(c===s)return void(a=null);const h=e.selectionStart??c.length,m=e.selectionEnd??h;let y=0,b=s.length,k=c.length;const w=a;if(a=null,w?.display===s&&c.startsWith(s.slice(0,w.start))&&c.endsWith(s.slice(w.end)))y=w.start,b=w.end,k=c.length-(s.length-b);else{for(;y<s.length&&y<c.length&&s[y]===c[y];)y+=1;for(;b>y&&k>y&&s[b-1]===c[k-1];)b-=1,k-=1}let x=p(y),C=p(b);const S=c.slice(y,k);if(!S&&b>y&&x===C)if("deleteContentForward"===(w?.inputType||t.inputType)){for(;C<i.length&&!Ze.test(i[C]);)C+=1;C=Math.min(i.length,C+1)}else{for(;x>0&&!Ze.test(i[x-1]);)x-=1;x=Math.max(0,x-1)}const E=e=>e<y?p(e):e<=k?x+e-y:p(e-k+b)+S.length-(C-x),T=E(h),A=E(m);i=i.slice(0,x)+S+i.slice(C),f(T,A),l.splice(d+1),l.push({value:i,start:e.selectionStart,end:e.selectionEnd}),d=l.length-1,n?.(i,u())}function x(){b(),o=!0,a=null}function C(e){o=!1,w(e)}return e.addEventListener("keydown",y),e.addEventListener("beforeinput",k),e.addEventListener("input",w),e.addEventListener("change",w),e.addEventListener("compositionstart",x),e.addEventListener("compositionend",C),f(),b(),{get value(){return i},get type(){return u()},setValue(e){e!==i&&(i=e,l=[{value:i,start:i.length,end:i.length}],d=0,a=null,f(),b())},destroy(){e.removeEventListener("keydown",y),e.removeEventListener("beforeinput",k),e.removeEventListener("input",w),e.removeEventListener("change",w),e.removeEventListener("compositionstart",x),e.removeEventListener("compositionend",C)}}}(this.inputElement,{allowedTypes:this.props.allowedTypes,onChange:()=>{this.clearError(),this.labelElement&&(this.labelElement.textContent=this.getLabelText()),this.props.onType?.()}}),this.labelElement.textContent=this.getLabelText(),this.inputElement.addEventListener("keydown",this.boundHandleKeyDown),s.appendChild(this.labelElement),s.appendChild(this.inputElement),this.allowsPhone){const e=mt("sv-identity-sms-consent");this.inputElement.setAttribute("aria-describedby",e.id),s.appendChild(e)}return i.appendChild(s),this.submitButton=document.createElement("button"),this.submitButton.className="sv-btn sv-btn-email-primary",this.submitButton.textContent="Continue",this.submitButton.addEventListener("click",this.boundHandleSubmit),i.appendChild(this.submitButton),e.appendChild(i),this.boundHandlePasskey&&(this.passkeyLink=document.createElement("button"),this.passkeyLink.className="sv-fallback-link",this.passkeyLink.textContent="Sign in with a passkey",this.passkeyLink.addEventListener("click",this.boundHandlePasskey),e.appendChild(this.passkeyLink)),this.focusTimeoutId=setTimeout(()=>this.inputElement?.focus(),50),e}offerLeadingMethod(e){if(!this.container||this.leadingButton)return;this.leadingHandler=e.onSelect,this.leadingButton=ht(e.method),this.leadingButton.addEventListener("click",this.leadingHandler);const t=Ke("sv-divider"),n=document.createElement("span");n.className="sv-divider-text",n.textContent="or",t.appendChild(n),this.container.prepend(this.leadingButton,t)}getSubtitleText(){return this.allowsBoth?"Enter your email or phone to continue":this.allowsPhone?"Enter your phone number to continue":"Enter your email to continue"}getLabelText(){return this.allowsBoth?"phone"===this.identityInput?.type?"Phone number":"Email address":this.allowsPhone?"Phone number":"Email address"}getPlaceholderText(){return this.allowsBoth?"you@example.com or (555) 123-4567":this.allowsPhone?"(555) 123-4567":"you@example.com"}clearError(){this.errorContainer&&Ge(this.errorContainer),this.inputElement?.classList.remove("sv-email-input-error")}showError(e){this.errorContainer&&(Ge(this.errorContainer),this.errorContainer.appendChild(Ye(e))),this.inputElement?.classList.add("sv-email-input-error"),this.inputElement?.focus()}handleSubmit(){if(!this.identityInput||!this.submitButton)return;const e=this.identityInput.type,t="phone"===e?Ae(this.identityInput.value):Je(this.identityInput.value);t?(this.submitButton.disabled=!0,this.submitButton.textContent="Please wait...",this.props.onSubmit({value:t,type:e})):this.showError("phone"===e?"Please enter a valid phone number":"Please enter a valid email address")}destroy(){this.identityInput?.destroy(),null!==this.focusTimeoutId&&(clearTimeout(this.focusTimeoutId),this.focusTimeoutId=null),this.inputElement&&this.inputElement.removeEventListener("keydown",this.boundHandleKeyDown),this.submitButton&&this.submitButton.removeEventListener("click",this.boundHandleSubmit),this.passkeyLink&&this.boundHandlePasskey&&this.passkeyLink.removeEventListener("click",this.boundHandlePasskey),this.leadingButton&&this.leadingHandler&&this.leadingButton.removeEventListener("click",this.leadingHandler)}}const vt=e=>"phone"===e.identityType;class gt{constructor(e){this.backLink=null,this.methodsContainer=null,this.methodButtons=[],this.methodClickHandlers=new Map,this.props=e,this.boundHandleBack=()=>this.props.onBack?.()}render(){const e=Ke();this.backLink=this.props.onBack?this.createBackLink():null;const t=document.createElement("h3");t.className="sv-title",t.textContent="Choose how to sign in";const n=this.props.email,i=n?document.createElement("p"):null;i&&n&&(i.className="sv-subtitle",i.textContent=n);const s=this.props.methods.some(vt)?mt("sv-method-sms-consent"):null,r=Ke();this.methodsContainer=r;for(const e of this.props.methods){const t=this.createMethodButton(e);s&&vt(e)&&t.setAttribute("aria-describedby",s.id),this.methodButtons.push(t),r.appendChild(t)}return this.backLink&&e.appendChild(this.backLink),e.appendChild(t),i&&e.appendChild(i),e.appendChild(r),s&&e.appendChild(s),e}offerLeadingMethod(e){if(!this.methodsContainer)return;const t=this.createMethodButton(e);this.methodButtons.unshift(t),this.methodsContainer.prepend(t)}createBackLink(){const e=document.createElement("button");e.className="sv-back-link",e.appendChild(at());const t="phone"===this.props.identityType?" Change phone number":" Change email";return e.appendChild(document.createTextNode(t)),e.addEventListener("click",this.boundHandleBack),e}createMethodButton(e){const t=ht(e),n=()=>this.props.onSelectMethod(e);return this.methodClickHandlers.set(t,n),t.addEventListener("click",n),t}destroy(){this.backLink&&this.backLink.removeEventListener("click",this.boundHandleBack);for(const e of this.methodButtons){const t=this.methodClickHandlers.get(e);t&&e.removeEventListener("click",t)}this.methodClickHandlers.clear(),this.methodButtons=[]}}function yt(e){return function(e,t){return e?String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,t):""}(e,"'")}class bt{constructor(e){this.inputElements=[],this.submitButton=null,this.resendButton=null,this.backLink=null,this.errorContainer=null,this.resendTimer=null,this.backoffTimer=null,this.backoffSeconds=0,this.focusTimeoutId=null,this.autoSubmitTimeoutId=null,this.isSubmitting=!1,this.inputHandlers=new Map,this.props=e,this.boundHandleBack=()=>this.props.onBack(),this.boundHandleResend=()=>this.handleResend(),this.boundHandleSubmit=()=>this.handleSubmit()}render(){const e=Ke();this.backLink=this.createBackLink();const t=document.createElement("h3");t.className="sv-title",t.textContent="Enter verification code";const n="email"===this.props.method?"email":"phone",i=document.createElement("p");i.className="sv-subtitle",i.innerHTML=`We sent a 6-digit code to your ${n}<br><strong>${yt(this.props.email)}</strong>`,this.errorContainer=Ke(),this.props.error&&this.errorContainer.appendChild(Ye(this.props.error));const s=this.createInputGroup();if(this.submitButton=document.createElement("button"),this.submitButton.className="sv-btn sv-btn-primary",this.submitButton.textContent="Verify",this.submitButton.addEventListener("click",this.boundHandleSubmit),this.props.backoffExpires){Math.max(0,Math.ceil(this.props.backoffExpires-Date.now()/1e3))>0&&this.startBackoff(this.props.backoffExpires)}const r=Ke("sv-resend-container");return this.resendButton=document.createElement("button"),this.resendButton.className="sv-back-link",this.resendButton.textContent="Resend code",this.resendButton.addEventListener("click",this.boundHandleResend),r.appendChild(this.resendButton),e.style.display="flex",e.style.flexDirection="column",e.appendChild(t),e.appendChild(i),e.appendChild(this.errorContainer),e.appendChild(s),e.appendChild(this.submitButton),e.appendChild(r),e.appendChild(this.backLink),this.focusTimeoutId=setTimeout(()=>this.inputElements[0]?.focus(),50),e}createBackLink(){const e=document.createElement("button");return e.className="sv-back-link",e.style.order="-1",e.appendChild(at()),e.appendChild(document.createTextNode(" Choose another method")),e.addEventListener("click",this.boundHandleBack),e}createInputGroup(){const e=Ke("sv-otp-input-group");for(let t=0;t<6;t++){const n=document.createElement("input");n.type="text",n.inputMode="numeric",n.pattern="[0-9]*",n.maxLength=1,n.className="sv-otp-digit",n.autocomplete="one-time-code",n.setAttribute("aria-label",`Digit ${t+1} of 6`);const i={input:e=>this.handleInput(e,t),keydown:e=>this.handleKeyDown(e,t),paste:e=>this.handlePaste(e),focus:()=>n.select()};this.inputHandlers.set(n,i),n.addEventListener("input",i.input),n.addEventListener("keydown",i.keydown),n.addEventListener("paste",i.paste),n.addEventListener("focus",i.focus),this.inputElements.push(n),e.appendChild(n)}return e}handleInput(e,t){const n=e.target,i=n.value.replace(/\D/g,"");i.length>0?(n.value=i[0],this.clearError(),t<5?this.inputElements[t+1].focus():this.checkAutoSubmit()):n.value=""}handleKeyDown(e,t){const n=e.target;"Backspace"===e.key?""===n.value&&t>0&&(this.inputElements[t-1].focus(),this.inputElements[t-1].value=""):"ArrowLeft"===e.key&&t>0?this.inputElements[t-1].focus():"ArrowRight"===e.key&&t<5?this.inputElements[t+1].focus():"Enter"===e.key&&this.handleSubmit()}handlePaste(e){e.preventDefault();const t=(e.clipboardData?.getData("text")??"").replace(/\D/g,"").slice(0,6);for(let e=0;e<t.length;e++)this.inputElements[e]&&(this.inputElements[e].value=t[e]);if(t.length>0){this.clearError();const e=Math.min(t.length,5);this.inputElements[e].focus()}6===t.length&&this.checkAutoSubmit()}checkAutoSubmit(){6===this.getCode().length&&(this.autoSubmitTimeoutId=setTimeout(()=>this.handleSubmit(),100))}getCode(){return this.inputElements.map(e=>e.value).join("")}clearError(){this.errorContainer&&Ge(this.errorContainer),this.inputElements.forEach(e=>e.classList.remove("sv-input-error"))}showError(e){this.errorContainer&&(Ge(this.errorContainer),this.errorContainer.appendChild(Ye(e))),this.inputElements.forEach(e=>e.classList.add("sv-input-error")),this.inputElements[0]?.focus()}handleSubmit(){if(!this.submitButton)return;if(this.isSubmitting)return;if(this.backoffSeconds>0)return;const e=function(e){const t=e.replace(/\D/g,"");return 6===t.length?t:null}(this.getCode());e?(null!==this.autoSubmitTimeoutId&&(clearTimeout(this.autoSubmitTimeoutId),this.autoSubmitTimeoutId=null),this.isSubmitting=!0,this.submitButton.disabled=!0,this.submitButton.textContent="Verifying...",this.props.onSubmit(e)):this.showError("Please enter the complete 6-digit code")}startBackoff(e){this.disableInputs(!0),this.backoffTimer=new de({expiresAt:e,onTick:e=>{this.backoffSeconds=e,this.updateSubmitButton()},onExpired:()=>{this.backoffSeconds=0,this.updateSubmitButton(),this.disableInputs(!1),this.inputElements[0]?.focus()}}),this.backoffTimer.start()}updateSubmitButton(){this.submitButton&&(this.backoffSeconds>0?(this.submitButton.textContent=`Wait ${this.backoffSeconds}s`,this.submitButton.disabled=!0):(this.submitButton.textContent="Verify",this.submitButton.disabled=!1))}disableInputs(e){this.inputElements.forEach(t=>{t.disabled=e})}handleResend(){!this.resendTimer?.isRunning()&&this.resendButton&&(this.resendTimer=new le({duration:30,onTick:e=>{this.resendButton&&(this.resendButton.textContent=`Resend code (${e}s)`,this.resendButton.disabled=!0)},onComplete:()=>{this.resendButton&&(this.resendButton.textContent="Resend code",this.resendButton.disabled=!1)}}),this.resendTimer.start(),this.props.onResend())}destroy(){null!==this.focusTimeoutId&&(clearTimeout(this.focusTimeoutId),this.focusTimeoutId=null),null!==this.autoSubmitTimeoutId&&(clearTimeout(this.autoSubmitTimeoutId),this.autoSubmitTimeoutId=null),this.resendTimer?.stop(),this.resendTimer=null,this.backoffTimer?.stop(),this.backoffTimer=null;for(const e of this.inputElements){const t=this.inputHandlers.get(e);t&&(e.removeEventListener("input",t.input),e.removeEventListener("keydown",t.keydown),e.removeEventListener("paste",t.paste),e.removeEventListener("focus",t.focus))}this.inputHandlers.clear(),this.inputElements=[],this.submitButton&&this.submitButton.removeEventListener("click",this.boundHandleSubmit),this.resendButton&&this.resendButton.removeEventListener("click",this.boundHandleResend),this.backLink&&this.backLink.removeEventListener("click",this.boundHandleBack)}}class kt{constructor(e){this.input=null,this.submitButton=null,this.toggleButton=null,this.errorContainer=null,this.promptEl=null,this.recoveryMode=!1,this.isSubmitting=!1,this.focusTimeoutId=null,this.props=e,this.boundSubmit=()=>this.handleSubmit(),this.boundToggle=()=>this.toggleRecovery(),this.boundKeydown=e=>{"Enter"===e.key&&this.handleSubmit()},this.boundInput=()=>this.clearError()}render(){const e=Ke();e.style.display="flex",e.style.flexDirection="column";const t=document.createElement("h3");return t.className="sv-title",t.textContent="Two-step verification",this.promptEl=document.createElement("p"),this.promptEl.className="sv-subtitle",this.promptEl.innerHTML="Enter the 6-digit code from your authenticator app.",this.errorContainer=Ke(),this.props.error&&this.errorContainer.appendChild(Ye(this.props.error)),this.input=document.createElement("input"),this.input.type="text",this.input.inputMode="numeric",this.input.autocomplete="one-time-code",this.input.maxLength=6,this.input.className="sv-input",this.input.setAttribute("aria-label","Verification code"),this.input.placeholder="000000",this.input.addEventListener("keydown",this.boundKeydown),this.input.addEventListener("input",this.boundInput),this.submitButton=document.createElement("button"),this.submitButton.className="sv-btn sv-btn-primary",this.submitButton.textContent="Verify",this.submitButton.addEventListener("click",this.boundSubmit),e.appendChild(t),e.appendChild(this.promptEl),e.appendChild(this.errorContainer),e.appendChild(this.input),e.appendChild(this.submitButton),this.props.methods?.includes("recovery_code")&&(this.toggleButton=document.createElement("button"),this.toggleButton.className="sv-back-link",this.toggleButton.textContent="Use a recovery code instead",this.toggleButton.addEventListener("click",this.boundToggle),e.appendChild(this.toggleButton)),this.focusTimeoutId=setTimeout(()=>this.input?.focus(),50),e}toggleRecovery(){this.input&&this.promptEl&&this.toggleButton&&(this.recoveryMode=!this.recoveryMode,this.input.value="",this.clearError(),this.recoveryMode?(this.input.inputMode="text",this.input.removeAttribute("maxlength"),this.input.placeholder="XXXX-XXXX-XXXX-XXXX",this.promptEl.innerHTML="Enter one of your recovery codes.",this.toggleButton.textContent="Use your authenticator app instead"):(this.input.inputMode="numeric",this.input.maxLength=6,this.input.placeholder="000000",this.promptEl.innerHTML="Enter the 6-digit code from your authenticator app.",this.toggleButton.textContent="Use a recovery code instead"),this.input.focus())}clearError(){this.errorContainer&&Ge(this.errorContainer),this.input?.classList.remove("sv-input-error")}showError(e){this.errorContainer&&(Ge(this.errorContainer),this.errorContainer.appendChild(Ye(e))),this.input?.classList.add("sv-input-error"),this.isSubmitting=!1,this.submitButton&&(this.submitButton.disabled=!1,this.submitButton.textContent="Verify"),this.input?.focus(),this.input?.select()}handleSubmit(){if(this.isSubmitting||!this.submitButton||!this.input)return;const e=this.input.value.trim();e?this.recoveryMode||/^\d{6}$/.test(e)?(this.isSubmitting=!0,this.submitButton.disabled=!0,this.submitButton.textContent="Verifying...",this.props.onSubmit(e)):this.showError("Enter the complete 6-digit code"):this.showError(this.recoveryMode?"Enter a recovery code":"Enter the 6-digit code")}destroy(){null!==this.focusTimeoutId&&(clearTimeout(this.focusTimeoutId),this.focusTimeoutId=null),this.input?.removeEventListener("keydown",this.boundKeydown),this.input?.removeEventListener("input",this.boundInput),this.submitButton?.removeEventListener("click",this.boundSubmit),this.toggleButton?.removeEventListener("click",this.boundToggle)}}class wt{constructor(e){this.actionButton=null,this.errorContainer=null,this.backLink=null,this.fallbackLink=null,this.props=e,this.boundHandleBack=()=>this.props.onBack?.(),this.boundHandleStart=()=>this.handleStart(),this.boundHandleFallback=e.onFallback?()=>e.onFallback():null}render(){const e=Ke();this.backLink=this.props.onBack?this.createBackLink():null;const t=Ke();t.appendChild(lt());const n=document.createElement("h3");n.className="sv-title",n.textContent="register"===this.props.mode?"Set up a passkey":"Use your passkey";const i=document.createElement("p");i.className="sv-subtitle","register"===this.props.mode?i.innerHTML=`Create a passkey for<br><strong>${yt(this.props.identityLabel)}</strong><br>to sign in faster next time`:i.innerHTML="Use a passkey linked to your SparkVault Identity",this.errorContainer=Ke(),this.props.error&&this.errorContainer.appendChild(Ye(this.props.error));const s=document.createElement("p");s.className="sv-passkey-description",s.textContent="register"===this.props.mode?"Use Face ID, Touch ID, Windows Hello, or a security key.":"Your device will prompt you to verify your identity.";const r="register"===this.props.mode?"Create Passkey":"Continue with Passkey";return this.actionButton=document.createElement("button"),this.actionButton.className="sv-btn sv-btn-primary",this.actionButton.textContent=r,this.actionButton.addEventListener("click",this.boundHandleStart),this.backLink&&e.appendChild(this.backLink),e.appendChild(t),e.appendChild(n),e.appendChild(i),e.appendChild(this.errorContainer),e.appendChild(s),e.appendChild(this.actionButton),this.props.onFallback&&this.boundHandleFallback&&(this.fallbackLink=this.createFallbackLink(),e.appendChild(this.fallbackLink)),e}createFallbackLink(){const e=document.createElement("button");return e.className="sv-fallback-link",e.textContent="Having trouble? Use a code instead",this.boundHandleFallback&&e.addEventListener("click",this.boundHandleFallback),e}createBackLink(){const e=document.createElement("button");return e.className="sv-back-link",e.appendChild(at()),e.appendChild(document.createTextNode(" Choose another method")),e.addEventListener("click",this.boundHandleBack),e}handleStart(){this.actionButton&&(this.actionButton.disabled=!0,this.actionButton.textContent="Waiting for device...",this.props.onStart())}showError(e){this.errorContainer&&(Ge(this.errorContainer),this.errorContainer.appendChild(Ye(e))),this.actionButton&&(this.actionButton.disabled=!1,this.actionButton.textContent="Try Again")}destroy(){this.backLink&&this.backLink.removeEventListener("click",this.boundHandleBack),this.actionButton&&this.actionButton.removeEventListener("click",this.boundHandleStart),this.fallbackLink&&this.boundHandleFallback&&this.fallbackLink.removeEventListener("click",this.boundHandleFallback)}}class xt{constructor(e){this.fallbackLink=null,this.props=e,this.boundHandleFallback=()=>this.props.onUseAnotherMethod()}render(){const e=Ke(),t=Ke();t.appendChild(lt());const n=document.createElement("h3");n.className="sv-title",n.textContent="Signing you in";const i=document.createElement("p");i.className="sv-subtitle",i.textContent="Use your passkey to continue";const s=document.createElement("div");s.className="sv-spinner",s.setAttribute("role","status"),s.setAttribute("aria-label","Waiting for your passkey");const r=Ke("sv-loading");return r.appendChild(s),this.fallbackLink=document.createElement("button"),this.fallbackLink.className="sv-fallback-link",this.fallbackLink.textContent="Use another method",this.fallbackLink.addEventListener("click",this.boundHandleFallback),e.appendChild(t),e.appendChild(n),e.appendChild(i),e.appendChild(r),e.appendChild(this.fallbackLink),e}destroy(){this.fallbackLink&&this.fallbackLink.removeEventListener("click",this.boundHandleFallback)}}class Ct{constructor(e){this.addButton=null,this.skipLink=null,this.props=e,this.boundHandleAdd=()=>this.props.onAddPasskey(),this.boundHandleSkip=()=>this.props.onSkip()}render(){const e=Ke(),t=Ke();t.appendChild(lt());const n=document.createElement("h3");n.className="sv-title",n.textContent="Add a passkey for faster sign-in?";const i=document.createElement("p");i.className="sv-subtitle",i.innerHTML=`Next time, sign in instantly as<br><strong>${yt(this.props.identityLabel)}</strong>`;const s=Ke();this.props.error&&s.appendChild(Ye(this.props.error));const r=document.createElement("div");r.className="sv-passkey-prompt-benefits";const o=document.createElement("ul"),a=["No codes to type or wait for","Phishing-resistant security","Works with Face ID, Touch ID, or Windows Hello"];for(const e of a){const t=document.createElement("li");t.appendChild(ot()),t.appendChild(document.createTextNode(e)),o.appendChild(t)}return r.appendChild(o),this.addButton=document.createElement("button"),this.addButton.className="sv-btn sv-btn-primary",this.addButton.textContent=this.props.error?"Try Again":"Add Passkey",this.addButton.addEventListener("click",this.boundHandleAdd),this.skipLink=document.createElement("button"),this.skipLink.className="sv-skip-link",this.skipLink.textContent=this.props.error?"Skip for now":"Not now",this.skipLink.addEventListener("click",this.boundHandleSkip),e.appendChild(t),e.appendChild(n),e.appendChild(i),e.appendChild(s),e.appendChild(r),e.appendChild(this.addButton),e.appendChild(this.skipLink),e}destroy(){this.addButton&&this.addButton.removeEventListener("click",this.boundHandleAdd),this.skipLink&&this.skipLink.removeEventListener("click",this.boundHandleSkip)}}class St{constructor(e){this.inputElement=null,this.submitButton=null,this.skipLink=null,this.errorContainer=null,this.focusTimeoutId=null,this.props=e,this.boundHandleInput=()=>this.handleInput(),this.boundHandleKeyDown=e=>{"Enter"===e.key&&(e.preventDefault(),this.handleSubmit())},this.boundHandleSubmit=()=>this.handleSubmit(),this.boundHandleSkip=()=>this.props.onSkip()}get isPhone(){return"phone"===this.props.missingType}render(){const e=Ke("sv-email-view"),t=Ke("sv-email-header"),n=document.createElement("h3");n.className="sv-title",n.textContent=this.isPhone?"Add a backup phone number":"Add a backup email";const i=document.createElement("p");i.className="sv-email-subtitle",i.textContent=this.isPhone?"Add a phone number so you can always get back into your account.":"Add an email so you can always get back into your account.",t.appendChild(n),t.appendChild(i),e.appendChild(t),this.errorContainer=Ke("sv-email-error-container"),this.props.error&&this.errorContainer.appendChild(Ye(this.props.error)),e.appendChild(this.errorContainer);const s=Ke("sv-email-form"),r=Ke("sv-email-input-wrapper"),o=document.createElement("label");if(o.className="sv-email-label",o.htmlFor="sv-backup-input",o.textContent=this.isPhone?"Phone number":"Email address",this.inputElement=document.createElement("input"),this.inputElement.type=this.isPhone?"tel":"email",this.inputElement.id="sv-backup-input",this.inputElement.className="sv-email-input",this.inputElement.placeholder=this.isPhone?"(555) 123-4567":"you@example.com",this.inputElement.autocomplete=this.isPhone?"tel":"email",this.inputElement.required=!0,this.inputElement.maxLength=Ue.ADDRESS,this.inputElement.addEventListener("input",this.boundHandleInput),this.inputElement.addEventListener("keydown",this.boundHandleKeyDown),r.appendChild(o),r.appendChild(this.inputElement),this.isPhone){const e=mt("sv-backup-sms-consent");this.inputElement.setAttribute("aria-describedby",e.id),r.appendChild(e)}return s.appendChild(r),this.submitButton=document.createElement("button"),this.submitButton.className="sv-btn sv-btn-primary",this.submitButton.textContent="Send code",this.submitButton.addEventListener("click",this.boundHandleSubmit),s.appendChild(this.submitButton),this.skipLink=document.createElement("button"),this.skipLink.className="sv-skip-link",this.skipLink.textContent="Not now",this.skipLink.addEventListener("click",this.boundHandleSkip),s.appendChild(this.skipLink),e.appendChild(s),this.focusTimeoutId=setTimeout(()=>this.inputElement?.focus(),50),e}handleInput(){if(this.clearError(),!this.inputElement||!this.isPhone)return;const e=this.inputElement.value,t=this.inputElement.selectionStart??e.length,n=Ie(e);if(n!==e){this.inputElement.value=n;const i=Math.min(t+(n.length-e.length),n.length);this.inputElement.setSelectionRange(i,i)}}clearError(){this.errorContainer&&Ge(this.errorContainer),this.inputElement?.classList.remove("sv-email-input-error")}showError(e){this.errorContainer&&(Ge(this.errorContainer),this.errorContainer.appendChild(Ye(e))),this.inputElement?.classList.add("sv-email-input-error"),this.inputElement?.focus()}handleSubmit(){if(!this.inputElement||!this.submitButton)return;const e=this.inputElement.value,t=this.isPhone?Ae(e):Je(e);t?(this.submitButton.disabled=!0,this.submitButton.textContent="Please wait...",this.props.onSubmit(t)):this.showError(this.isPhone?"Please enter a valid phone number":"Please enter a valid email address")}destroy(){null!==this.focusTimeoutId&&(clearTimeout(this.focusTimeoutId),this.focusTimeoutId=null),this.inputElement&&(this.inputElement.removeEventListener("input",this.boundHandleInput),this.inputElement.removeEventListener("keydown",this.boundHandleKeyDown)),this.submitButton&&this.submitButton.removeEventListener("click",this.boundHandleSubmit),this.skipLink&&this.skipLink.removeEventListener("click",this.boundHandleSkip)}}class Et{constructor(e){this.expirationTimer=null,this.resendTimer=null,this.countdownElement=null,this.countdownSection=null,this.waitingSection=null,this.resendButton=null,this.backLink=null,this.fallbackButton=null,this.props=e,this.boundHandleBack=()=>this.props.onBack(),this.boundHandleResend=()=>this.handleResend(),this.boundHandleFallback=()=>this.props.onFallback()}render(){const e=Ke();this.backLink=this.createBackLink();const t=document.createElement("h3");t.className="sv-title",t.textContent="Check your email";const n=document.createElement("p");n.className="sv-subtitle",n.innerHTML=`We sent a secure link to<br><strong>${yt(this.props.email)}</strong>`,this.waitingSection=Ke("sv-sparklink-waiting");const i=document.createElement("div");i.className="sv-spinner sv-spinner-small",i.setAttribute("role","status"),i.setAttribute("aria-label","Waiting for verification");const s=document.createElement("span");s.className="sv-sparklink-waiting-text",s.textContent="Waiting for you to click the link...",this.waitingSection.appendChild(i),this.waitingSection.appendChild(s),this.countdownSection=Ke("sv-sparklink-countdown");const r=document.createElement("span");r.textContent="Link expires in ",this.countdownElement=document.createElement("span"),this.countdownElement.className="sv-sparklink-countdown-time",this.startExpirationTimer(),this.countdownSection.appendChild(r),this.countdownSection.appendChild(this.countdownElement);const o=Ke("sv-resend-container");this.resendButton=document.createElement("button"),this.resendButton.className="sv-btn sv-btn-secondary",this.resendButton.textContent="Resend link",this.resendButton.addEventListener("click",this.boundHandleResend),o.appendChild(this.resendButton);const a=Ke("sv-sparklink-fallback");return this.fallbackButton=document.createElement("button"),this.fallbackButton.className="sv-back-link",this.fallbackButton.textContent="Use verification code instead",this.fallbackButton.addEventListener("click",this.boundHandleFallback),a.appendChild(this.fallbackButton),e.appendChild(this.backLink),e.appendChild(t),e.appendChild(n),e.appendChild(this.waitingSection),e.appendChild(this.countdownSection),e.appendChild(o),e.appendChild(a),e}createBackLink(){const e=document.createElement("button");return e.className="sv-back-link",e.appendChild(at()),e.appendChild(document.createTextNode(" Choose another method")),e.addEventListener("click",this.boundHandleBack),e}formatTime(e){if(!Number.isFinite(e)||e<0)return"--:--";return`${Math.floor(e/60)}:${Math.floor(e%60).toString().padStart(2,"0")}`}startExpirationTimer(){if(!Number.isFinite(this.props.expiresAt)||this.props.expiresAt<=0)return this.countdownElement&&(this.countdownElement.textContent="--:--"),void console.warn("[SparkVault] Invalid expiresAt timestamp:",this.props.expiresAt);const e=Math.floor(this.props.expiresAt/1e3);this.expirationTimer=new de({expiresAt:e,onTick:e=>{this.countdownElement&&(this.countdownElement.textContent=this.formatTime(e))},onExpired:()=>{this.showExpiredState()}}),this.expirationTimer.start()}showExpiredState(){if(this.props.onExpired(),this.waitingSection){this.waitingSection.innerHTML="",this.waitingSection.classList.add("sv-sparklink-expired");const e=Ke("sv-sparklink-expired-icon");e.appendChild(dt("sv-expired-icon")),this.waitingSection.appendChild(e);const t=document.createElement("span");t.className="sv-sparklink-expired-text",t.textContent="This link has expired",this.waitingSection.appendChild(t)}this.countdownSection&&(this.countdownSection.style.display="none")}handleResend(){!this.resendTimer?.isRunning()&&this.resendButton&&(this.resendTimer=new le({duration:30,onTick:e=>{this.resendButton&&(this.resendButton.textContent=`Resend link (${e}s)`,this.resendButton.disabled=!0)},onComplete:()=>{this.resendButton&&(this.resendButton.textContent="Resend link",this.resendButton.disabled=!1)}}),this.resendTimer.start(),this.props.onResend())}destroy(){this.expirationTimer?.stop(),this.expirationTimer=null,this.resendTimer?.stop(),this.resendTimer=null,this.backLink&&this.backLink.removeEventListener("click",this.boundHandleBack),this.resendButton&&this.resendButton.removeEventListener("click",this.boundHandleResend),this.fallbackButton&&this.fallbackButton.removeEventListener("click",this.boundHandleFallback)}}const Tt=["identity_trial_exhausted","identity_trial_expired","identity_capacity_blocked"];const At="stronger_verification_required",Lt="federation_unavailable",It="signin_reference_unavailable",Rt="identity_types_unavailable",Bt="identity_types_unreadable";function _t(e){return"identity_locked"===e?"This SparkVault Identity is locked":function(e){return Tt.includes(e)}(e)||e===Lt||e===Rt||e===Bt?"Sign-in unavailable":e===At?"This request needs your passkey":null}class Pt{constructor(e){this.retryButton=null,this.closeButton=null,this.props=e,this.boundHandleRetry=()=>this.props.onRetry(),this.boundHandleClose=()=>this.props.onClose()}render(){const e=Ke();e.className="sv-error-view";const t=Ke();t.className="sv-error-icon-container",t.appendChild(dt("sv-error-icon"));const n=Ke();n.className="sv-error-content";const i=_t(this.props.code),s=this.props.code===ee.refusalCode?{title:"That sign-in is not accepted here",action:"Other ways to sign in"}:null;const r=null===i&&null===s,o=document.createElement("h3");o.className="sv-error-title",o.textContent=i??s?.title??"Something went wrong";const a=document.createElement("p");if(a.className="sv-error-message",a.textContent=this.props.message,n.appendChild(o),n.appendChild(a),r){const e=document.createElement("div");e.className="sv-error-code-badge";const t=document.createElement("span");t.className="sv-error-code-label",t.textContent="Error code";const i=document.createElement("code");i.className="sv-error-code-value",i.textContent=this.props.code,e.appendChild(t),e.appendChild(i),n.appendChild(e)}const l=Ke();return l.className="sv-error-actions",null===i&&(this.retryButton=document.createElement("button"),this.retryButton.className="sv-btn sv-btn-error-primary",this.retryButton.textContent=s?.action??"Try Again",this.retryButton.addEventListener("click",this.boundHandleRetry),l.appendChild(this.retryButton)),this.closeButton=document.createElement("button"),this.closeButton.className="sv-btn sv-btn-error-secondary",this.closeButton.textContent="Close",this.closeButton.addEventListener("click",this.boundHandleClose),l.appendChild(this.closeButton),e.appendChild(t),e.appendChild(n),e.appendChild(l),e}destroy(){this.retryButton&&this.retryButton.removeEventListener("click",this.boundHandleRetry),this.closeButton&&this.closeButton.removeEventListener("click",this.boundHandleClose)}}const $t=Object.freeze({white:"#ffffff",slate50:"#f7fafb",slate100:"#f0f5f7",slate200:"#e0e9ed",slate300:"#c9d6dc",slate500:"#5e757f",slate600:"#425761",slate900:"#0d1a20",slate950:"#030a0e",action:"#216bde",actionHover:"#0d5bcd",actionBg:"#eef4fe",btnDanger:"#b02b27",btnDangerHover:"#9a221f",success:"#006d42",success500:"#2ec26b",error:"#b02b27",error500:"#e6443d",errorBg:"#ffeae7",errorText:"#94221f",warning:"#8a5600",warning500:"#e6ad00",infoBg:"#e0f2ff",info500:"#4383eb",modalOverlay:"rgba(13, 26, 32, 0.6)",darkText:"rgba(255,255,255,0.92)",darkTextMuted:"rgba(255,255,255,0.62)",darkHairline:"rgba(255,255,255,0.10)",darkCard:"rgba(255,255,255,0.05)",shadowSm:"0 1px 2px 0 rgba(0, 0, 0, 0.05)",shadowMd:"0 4px 6px -1px rgba(0, 0, 0, 0.1)",shadowPopover:"0 8px 24px rgba(13, 26, 32, 0.12)"});function Ot(e,t){const n=Number.parseInt(e.slice(1),16);return`rgba(${n>>16}, ${n>>8&255}, ${255&n}, ${t})`}class Mt{constructor(e){this.retryButton=null,this.closeButton=null,this.props=e,this.boundHandleRetry=()=>this.props.onRetry(),this.boundHandleClose=()=>this.props.onClose()}render(){const e=Ke("sv-unavailable-view"),t=Ke("sv-unavailable-icon-container");t.appendChild(function(){const e=document.createElementNS("http://www.w3.org/2000/svg","svg");e.setAttribute("viewBox","0 0 48 48"),e.setAttribute("width","48"),e.setAttribute("height","48"),e.setAttribute("fill","none"),e.classList.add("sv-unavailable-icon");const t=document.createElementNS("http://www.w3.org/2000/svg","circle");t.setAttribute("cx","24"),t.setAttribute("cy","24"),t.setAttribute("r","22"),t.setAttribute("fill",$t.actionBg),t.setAttribute("stroke",$t.infoBg),t.setAttribute("stroke-width","1"),e.appendChild(t);const n=document.createElementNS("http://www.w3.org/2000/svg","g");n.setAttribute("transform","translate(12, 10)");const i=document.createElementNS("http://www.w3.org/2000/svg","path");i.setAttribute("d","M12 2L3 6v6c0 5.55 3.84 10.74 9 12 5.16-1.26 9-6.45 9-12V6l-9-4z"),i.setAttribute("fill",$t.info500),n.appendChild(i);const s=document.createElementNS("http://www.w3.org/2000/svg","rect");s.setAttribute("x","9"),s.setAttribute("y","9"),s.setAttribute("width","2.5"),s.setAttribute("height","8"),s.setAttribute("rx","1"),s.setAttribute("fill",$t.white),n.appendChild(s);const r=document.createElementNS("http://www.w3.org/2000/svg","rect");return r.setAttribute("x","12.5"),r.setAttribute("y","9"),r.setAttribute("width","2.5"),r.setAttribute("height","8"),r.setAttribute("rx","1"),r.setAttribute("fill",$t.white),n.appendChild(r),e.appendChild(n),e}()),e.appendChild(t);const n=Ke("sv-unavailable-content"),i=document.createElement("h3");i.className="sv-unavailable-title",i.textContent="Temporarily Unavailable",n.appendChild(i);const s=document.createElement("p");s.className="sv-unavailable-message",s.textContent="Authentication is experiencing a brief interruption. Please try again in a moment.",n.appendChild(s),e.appendChild(n);const r=Ke("sv-unavailable-actions");return this.retryButton=document.createElement("button"),this.retryButton.className="sv-btn sv-btn-primary",this.retryButton.textContent="Try Again",this.retryButton.addEventListener("click",this.boundHandleRetry),r.appendChild(this.retryButton),this.closeButton=document.createElement("button"),this.closeButton.className="sv-btn sv-btn-secondary",this.closeButton.textContent="Close",this.closeButton.addEventListener("click",this.boundHandleClose),r.appendChild(this.closeButton),e.appendChild(r),e}destroy(){this.retryButton&&this.retryButton.removeEventListener("click",this.boundHandleRetry),this.closeButton&&this.closeButton.removeEventListener("click",this.boundHandleClose)}}class Nt{constructor(e){this.dismissButton=null,this.props=e,this.boundHandleClose=()=>this.props.onClose()}render(){const e=Ke("sv-not-activated-view"),t=Ke("sv-not-activated-eyebrow");t.appendChild(function(){const e=Ke("sv-not-activated-mark"),t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("viewBox","0 0 16 16"),t.setAttribute("width","14"),t.setAttribute("height","14"),t.setAttribute("fill","none");const n=document.createElementNS("http://www.w3.org/2000/svg","path");n.setAttribute("d","M8 1.5c.6 1.8 2 2.7 2 4.4 0 .9-.5 1.6-1.2 1.6-.6 0-1-.4-1-.9 0-.4.2-.8.2-1.2 0-.7-.5-1.1-1-1.1-1.4 0-2.5 1.5-2.5 3.4 0 2.4 1.9 4.3 4.5 4.3s4.5-1.9 4.5-4.3c0-3.6-3-4.6-5.5-6.2z"),n.setAttribute("fill","currentColor"),t.appendChild(n);const i=document.createElement("span");return i.textContent="SparkVault",e.appendChild(t),e.appendChild(i),e}());const n=document.createElement("span");n.className="sv-not-activated-eyebrow-divider",n.textContent="•",t.appendChild(n);const i=document.createElement("span");i.className="sv-not-activated-eyebrow-label",i.textContent="Identity",t.appendChild(i),e.appendChild(t);const s=function(){const e=Ke("sv-not-activated-badge"),t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("viewBox","0 0 64 64"),t.setAttribute("width","72"),t.setAttribute("height","72"),t.setAttribute("fill","none"),t.setAttribute("aria-hidden","true"),t.classList.add("sv-not-activated-badge-svg");const n=document.createElementNS("http://www.w3.org/2000/svg","circle");n.setAttribute("cx","32"),n.setAttribute("cy","32"),n.setAttribute("r","29.5"),n.setAttribute("fill",$t.slate50),n.setAttribute("stroke",$t.slate200),n.setAttribute("stroke-width","1"),t.appendChild(n);const i=document.createElementNS("http://www.w3.org/2000/svg","rect");i.setAttribute("x","18.5"),i.setAttribute("y","18.5"),i.setAttribute("width","27"),i.setAttribute("height","27"),i.setAttribute("rx","7"),i.setAttribute("fill",$t.white),i.setAttribute("stroke",$t.slate300),i.setAttribute("stroke-width","1"),t.appendChild(i);const s=(e,n)=>{const i=document.createElementNS("http://www.w3.org/2000/svg","path");i.setAttribute("d",`M24 ${e}H${n}`),i.setAttribute("stroke",$t.slate600),i.setAttribute("stroke-width","2"),i.setAttribute("stroke-linecap","round"),t.appendChild(i)};s("26","40"),s("32","40"),s("38","35");const r=(e,n)=>{const i=document.createElementNS("http://www.w3.org/2000/svg","circle");i.setAttribute("cx",e),i.setAttribute("cy",n),i.setAttribute("r","2.5"),i.setAttribute("fill",$t.action),i.setAttribute("stroke",$t.white),i.setAttribute("stroke-width","1.5"),t.appendChild(i)};return r("30","26"),r("36","32"),r("28","38"),e.appendChild(t),e}();e.appendChild(s);const r=document.createElement("h2");r.className="sv-not-activated-title",r.id="sv-modal-title",r.textContent="Identity Product not configured",e.appendChild(r);const o=document.createElement("p");o.className="sv-not-activated-message",o.textContent="Sign-in is unavailable because the site owner has not configured SparkVault Identity for this account.",e.appendChild(o);const a=Ke("sv-not-activated-owner"),l=document.createElement("span");l.className="sv-not-activated-owner-label",l.textContent="Are you the site owner?";const d=document.createElement("span");d.className="sv-not-activated-owner-hint",d.textContent="Sign in to SparkVault and configure the Identity Product to start accepting sign-ins.",a.appendChild(l),a.appendChild(d),e.appendChild(a);const c=Ke("sv-not-activated-actions"),h=document.createElement("a");h.className="sv-btn sv-btn-primary sv-not-activated-cta",h.href="https://app.sparkvault.com/products/identity",h.target="_blank",h.rel="noopener noreferrer";const u=document.createElement("span");return u.textContent="Configure in SparkVault",h.appendChild(u),h.appendChild(function(){const e=document.createElementNS("http://www.w3.org/2000/svg","svg");e.setAttribute("viewBox","0 0 16 16"),e.setAttribute("width","14"),e.setAttribute("height","14"),e.setAttribute("fill","none"),e.classList.add("sv-not-activated-cta-icon");const t=document.createElementNS("http://www.w3.org/2000/svg","path");return t.setAttribute("d","M6 3h7v7M13 3l-8 8"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","2"),t.setAttribute("stroke-linecap","round"),t.setAttribute("stroke-linejoin","round"),e.appendChild(t),e}()),c.appendChild(h),this.dismissButton=document.createElement("button"),this.dismissButton.className="sv-not-activated-dismiss",this.dismissButton.type="button",this.dismissButton.textContent="Dismiss",this.dismissButton.addEventListener("click",this.boundHandleClose),c.appendChild(this.dismissButton),e.appendChild(c),e}destroy(){this.dismissButton&&this.dismissButton.removeEventListener("click",this.boundHandleClose)}}class Ht{constructor(e){this.dismissButton=null,this.props=e,this.boundHandleClose=()=>this.props.onClose()}render(){const e=Ke("sv-not-activated-view"),t=Ke("sv-not-activated-eyebrow");t.appendChild(function(){const e=Ke("sv-not-activated-mark"),t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("viewBox","0 0 16 16"),t.setAttribute("width","14"),t.setAttribute("height","14"),t.setAttribute("fill","none");const n=document.createElementNS("http://www.w3.org/2000/svg","path");n.setAttribute("d","M8 1.5c.6 1.8 2 2.7 2 4.4 0 .9-.5 1.6-1.2 1.6-.6 0-1-.4-1-.9 0-.4.2-.8.2-1.2 0-.7-.5-1.1-1-1.1-1.4 0-2.5 1.5-2.5 3.4 0 2.4 1.9 4.3 4.5 4.3s4.5-1.9 4.5-4.3c0-3.6-3-4.6-5.5-6.2z"),n.setAttribute("fill","currentColor"),t.appendChild(n);const i=document.createElement("span");return i.textContent="SparkVault",e.appendChild(t),e.appendChild(i),e}());const n=document.createElement("span");n.className="sv-not-activated-eyebrow-divider",n.textContent="•",t.appendChild(n);const i=document.createElement("span");i.className="sv-not-activated-eyebrow-label",i.textContent="Identity",t.appendChild(i),e.appendChild(t);const s=function(){const e=Ke("sv-not-activated-badge"),t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("viewBox","0 0 64 64"),t.setAttribute("width","72"),t.setAttribute("height","72"),t.setAttribute("fill","none"),t.setAttribute("aria-hidden","true"),t.classList.add("sv-not-activated-badge-svg");const n=document.createElementNS("http://www.w3.org/2000/svg","circle");n.setAttribute("cx","32"),n.setAttribute("cy","32"),n.setAttribute("r","29.5"),n.setAttribute("fill",$t.slate50),n.setAttribute("stroke",$t.slate200),n.setAttribute("stroke-width","1"),t.appendChild(n);const i=document.createElementNS("http://www.w3.org/2000/svg","circle");i.setAttribute("cx","32"),i.setAttribute("cy","32"),i.setAttribute("r","13"),i.setAttribute("fill",$t.white),i.setAttribute("stroke",$t.slate300),i.setAttribute("stroke-width","2"),t.appendChild(i);const s=document.createElementNS("http://www.w3.org/2000/svg","ellipse");s.setAttribute("cx","32"),s.setAttribute("cy","32"),s.setAttribute("rx","5.5"),s.setAttribute("ry","13"),s.setAttribute("fill","none"),s.setAttribute("stroke",$t.slate300),s.setAttribute("stroke-width","2"),t.appendChild(s);const r=document.createElementNS("http://www.w3.org/2000/svg","path");r.setAttribute("d","M19 32H45"),r.setAttribute("stroke",$t.slate300),r.setAttribute("stroke-width","2"),r.setAttribute("stroke-linecap","round"),t.appendChild(r);const o=document.createElementNS("http://www.w3.org/2000/svg","path");return o.setAttribute("d","M23 23L41 41"),o.setAttribute("stroke",$t.action),o.setAttribute("stroke-width","2.5"),o.setAttribute("stroke-linecap","round"),t.appendChild(o),e.appendChild(t),e}();e.appendChild(s);const r=document.createElement("h2");r.className="sv-not-activated-title",r.id="sv-modal-title",r.textContent="This domain isn't allowed",e.appendChild(r);const o=document.createElement("p");o.className="sv-not-activated-message",o.textContent="Sign-in is blocked because this website's domain is not on the SparkVault Identity allowlist for this account.",e.appendChild(o);const a=Ke("sv-not-activated-owner"),l=document.createElement("span");l.className="sv-not-activated-owner-label",l.textContent="Are you the site owner?";const d=document.createElement("span");d.className="sv-not-activated-owner-hint",d.textContent=this.props.origin?`Add ${this.props.origin} to your verified domains in SparkVault, then reload this page.`:"Add this website's domain to your verified domains in SparkVault, then reload this page.",a.appendChild(l),a.appendChild(d),e.appendChild(a);const c=Ke("sv-not-activated-actions"),h=document.createElement("a");h.className="sv-btn sv-btn-primary sv-not-activated-cta",h.href="https://app.sparkvault.com/company/domains",h.target="_blank",h.rel="noopener noreferrer";const u=document.createElement("span");return u.textContent="Manage domains in SparkVault",h.appendChild(u),h.appendChild(function(){const e=document.createElementNS("http://www.w3.org/2000/svg","svg");e.setAttribute("viewBox","0 0 16 16"),e.setAttribute("width","14"),e.setAttribute("height","14"),e.setAttribute("fill","none"),e.classList.add("sv-not-activated-cta-icon");const t=document.createElementNS("http://www.w3.org/2000/svg","path");return t.setAttribute("d","M6 3h7v7M13 3l-8 8"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","2"),t.setAttribute("stroke-linecap","round"),t.setAttribute("stroke-linejoin","round"),e.appendChild(t),e}()),c.appendChild(h),this.dismissButton=document.createElement("button"),this.dismissButton.className="sv-not-activated-dismiss",this.dismissButton.type="button",this.dismissButton.textContent="Dismiss",this.dismissButton.addEventListener("click",this.boundHandleClose),c.appendChild(this.dismissButton),e.appendChild(c),e}destroy(){this.dismissButton&&this.dismissButton.removeEventListener("click",this.boundHandleClose)}}function Ft(){if("undefined"==typeof window)return null;const e=window.__sparkvaultProgress;return e&&"function"==typeof e.start?e:null}function Dt(){Ft()?.start()}function Vt(e){const t=e?.trim();return t?`Sign-in for ${t} is temporarily unavailable. Please contact them for assistance.`:"Sign-in is temporarily unavailable. Please contact the site owner for assistance."}const zt=new Set(Tt),Ut={message:["Connection blocked by security policy.","Please contact the site administrator to add wss://ws.sparkvault.com","to the Content-Security-Policy connect-src directive."].join(" "),code:"sparklink_csp_blocked"};class jt{constructor(e,t,n,i,s=null,r={ok:!0,types:null}){this.identityPrefilled=!1,this.currentView=null,this.focusTimeoutId=null,this.morphTimer=null,this.discoverableVerifyAbort=null,this.postLoginResult=null,this.postLoginQueue=[],this.sparkLinkWs=null,this.sparkLinkKindling=null,this.sparkLinkVisibilityHandler=null,this.sparkLinkClaiming=!1,this.sparkLinkRetryTimer=null,this.pageRestoreHandler=null,this.referenceAsk=null,this.referenceAsks=0,this.untouchedStep=null,this.statusRegion=null,this.container=e,this.api=t,this.options=n,this.callbacks=i,this.federationReturn=s;const o=$e(this.api.accountId);this.federationMayAutoStart=null===s&&!o,this.verificationState=new Oe,this.passkeyHandler=new He(t,this.verificationState),this.otpHandler=new Fe(t,this.verificationState),this.sparkLinkHandler=new De(t,this.verificationState),this.identityTypesUnreadable=!r.ok,this.verificationState.setIdentityTypes(r.ok?r.types:null),this.applyInitialIdentity(),n.authContext&&this.verificationState.setAuthContext(n.authContext);const{signinRef:a,completesInWindow:l}=n;this.askReference="function"==typeof a?a:null,this.verificationState.setSigninRef(Q(a)?a:null),this.offeredWithoutReference=void 0===a&&!0===l}applyInitialIdentity(){const e="string"==typeof this.options.phone&&this.options.phone.length>0,t=e?this.options.phone:this.options.email;if(!t)return;const n=e||"phone"===Le(t)?"phone":"email";ie(n,this.verificationState.identityTypes)&&("phone"===n?this.verificationState.setIdentity(Ae(t)??t,"phone"):this.verificationState.setIdentity(Je(t)??t,"email"),this.identityPrefilled=!0)}isIdentityFixed(){return this.identityPrefilled&&void 0!==this.verificationState.authContext?.simpleMode}safeOnSuccess(e){try{this.callbacks.onSuccess(e)}catch(e){console.warn("[SparkVault SDK] onSuccess threw, continuing to redirect",e)}}get recipient(){return this.verificationState.recipient}get identityType(){return this.verificationState.identityType}get sdkConfig(){return this.verificationState.sdkConfig}async start(){this.requestReference();let e=null;if(this.api.isConfigPreloaded()){const t=new Promise(e=>setTimeout(()=>e(null),50));try{const n=await Promise.race([this.api.getConfig().then(e=>e),t]);null!==n&&(e=n)}catch{}}this.container.createLoading({backdropBlur:this.options.backdropBlur},()=>this.handleClose()),this.placeStatusRegion();try{e||(this.setState({view:"loading"}),e=await this.fetchConfigWithRetry()),this.verificationState.setConfig(e),e.branding&&this.container.updateBranding(e.branding),await this.showInitialAuthStep()}catch(e){this.setState(this.viewStateForConfigError(e))}}showStartupError(e){this.container.isOpen()||(this.container.createLoading({backdropBlur:this.options.backdropBlur},()=>this.handleClose()),this.placeStatusRegion()),this.setState(this.viewStateForConfigError(e))}viewStateForConfigError(e){if(e instanceof ke){if("product_not_configured"===e.code)return{view:"product-not-configured"};if("ORIGIN_NOT_ALLOWED"===e.code){return{view:"origin-not-allowed",origin:"string"==typeof e.details?.origin?e.details.origin:void 0}}}return{view:"service-unavailable"}}async fetchConfigWithRetry(){try{return await this.api.getConfig()}catch(e){if(!(e instanceof ke&&"network_error"===e.code))throw e;return await new Promise(e=>setTimeout(e,1e3)),this.api.getConfig()}}async retryConfigLoad(){this.setState({view:"loading"});try{const e=await this.fetchConfigWithRetry();this.verificationState.setConfig(e),e.branding&&this.container.updateBranding(e.branding),await this.showInitialAuthStep()}catch(e){this.setState(this.viewStateForConfigError(e))}}close(){this.api.abort(),this.referenceAsks+=1,this.discoverableVerifyAbort?.abort(),this.discoverableVerifyAbort=null,null!==this.focusTimeoutId&&(clearTimeout(this.focusTimeoutId),this.focusTimeoutId=null),null!==this.morphTimer&&(clearTimeout(this.morphTimer),this.morphTimer=null),this.pageRestoreHandler&&(window.removeEventListener("pageshow",this.pageRestoreHandler),this.pageRestoreHandler=null),this.statusRegion?.destroy(),this.statusRegion=null,this.cleanupSparkLink(),this.destroyCurrentView(),this.container.destroy()}handleClose(){this.close(),this.callbacks.onCancel()}get viewState(){return this.verificationState.viewState}setState(e){this.verificationState.setViewState(e),this.render()}async showInitialAuthStep(){if(this.identityTypesUnreadable)return void this.setState({view:"error",code:Bt,message:"This sign-in link is not valid. Contact the site you came from for help."});const e=this.verificationState.signinRef;this.startWithFederation()||(await this.showSignInStep(),this.untouchedStep=this.currentView,this.verificationState.signinRef!==e&&this.offerArrivedReference())}startWithFederation(){return"failed"===this.federationReturn?(this.federationReturn=null,this.setState(this.federationFailedState()),!0):this.startFederationAutomatically()}startFederationAutomatically(){const e=this.federation;return!!this.federationStartsOnItsOwn(e)&&(this.leaveForFederation({silent:e.silent,automatic:!0}).catch(e=>this.handleErrorWithRecovery(e,"unknown")),!0)}federationStartsOnItsOwn(e){return null!==e&&this.federationMayAutoStart&&(e.silent||"federation"===this.options.method)}federationAwaitingReference(e){return"pending"===this.referenceAsk&&this.offersFederationBeside(e)?this.accountFederation:null}requestReference(){const e=this.askReference;if(!e)return;const t=++this.referenceAsks;this.referenceAsk="pending",new Promise(t=>{t(e())}).catch(()=>null).then(e=>{t===this.referenceAsks&&(Q(e)?this.referenceArrived(e):this.referenceUnavailable())})}referenceArrived(e){this.referenceAsk=null,this.verificationState.setSigninRef(e),this.offerArrivedReference()}referenceUnavailable(){this.referenceAsk="unavailable","awaiting-reference"===this.viewState.view&&this.showMethodSelect()}retryReference(){this.requestReference(),this.showSignInStep()}offerArrivedReference(){const e=this.viewState;if(!("awaiting-reference"===e.view||"identity-input"===e.view||"method-select"===e.view&&this.offersFederationBeside(e.email)))return;if(null!==this.untouchedStep&&this.currentView===this.untouchedStep&&this.startFederationAutomatically())return;if("awaiting-reference"===e.view)return void this.showMethodSelect();const t=this.leadingFederationMethod();if(!t)return;const n=this.currentView;n instanceof ft?n.offerLeadingMethod(t):n instanceof gt&&"method-select"===e.view&&!e.methods.some(e=>"federation"===e.type)&&(n.offerLeadingMethod(t.method),this.verificationState.setViewState({...e,methods:[t.method,...e.methods]}))}async showSignInStep(){this.recipient||0===this.getAllowedIdentityTypes().length?await this.showMethodSelect():!this.canDiscoverableVerify()||this.federationStartsOnItsOwn(this.federationAwaitingReference(this.recipient))?this.showIdentityInput():this.launchDiscoverableVerify()}canDiscoverableVerify(){if(!this.passkeyHandler.canAutoVerify())return!1;return this.admittedMethods(Be(this.verificationState.methodIds)).some(e=>"passkey"===e.type)}async launchDiscoverableVerify(){this.discoverableVerifyAbort=new AbortController;const{signal:e}=this.discoverableVerifyAbort;this.setState({view:"passkey-auto"});const t=await this.passkeyHandler.verify(e);e.aborted||(this.discoverableVerifyAbort=null,this.applyTerminalPasskeyResult(t)||this.showIdentityInput())}cancelDiscoverableVerify(){this.discoverableVerifyAbort?.abort(),this.discoverableVerifyAbort=null,this.showIdentityInput()}render(){const e=this.container.getBody();if(!e)return;this.destroyCurrentView();this.container.setMinimalChrome(["product-not-configured","origin-not-allowed"].includes(this.viewState.view));const t=this.createViewForState(this.viewState);this.currentView=t,this.statusRegion?.announce(t.announcement??"");const n=t.render();n.classList.add("sv-step-enter"),this.morphSwap(e,n),"loading"===this.viewState.view||"awaiting-reference"===this.viewState.view?Dt():Ft()?.done();const i=e.querySelector("input:not([disabled]), button.sv-btn-primary:not([disabled]), button.sv-btn-email-primary:not([disabled]), button.sv-btn-method:not([disabled])");i&&(null!==this.focusTimeoutId&&clearTimeout(this.focusTimeoutId),this.focusTimeoutId=setTimeout(()=>i.focus(),50))}placeStatusRegion(){const e=this.container.getBody();e&&!this.statusRegion?.element.isConnected&&(this.statusRegion?.destroy(),this.statusRegion=function(e){const t=document.createElement("div");t.className=e,t.setAttribute("role","status"),t.setAttribute("aria-live","polite"),t.setAttribute("aria-atomic","true");let n=null;const i=()=>{null!==n&&clearTimeout(n),n=null};return{element:t,announce(e){i(),e?n=setTimeout(()=>{n=null,t.textContent=e},100):t.textContent=""},destroy(){i(),t.remove()}}}("sv-sr-only"),e.insertAdjacentElement("beforebegin",this.statusRegion.element))}destroyCurrentView(){this.currentView?.destroy&&this.currentView.destroy(),this.currentView=null}morphSwap(e,t){const n=e.getBoundingClientRect().height;Ge(e),e.appendChild(t);const i="undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,s=e.getBoundingClientRect().height;if(i||n<1||s<1||Math.abs(s-n)<1)return;const r=()=>{null!==this.morphTimer&&(clearTimeout(this.morphTimer),this.morphTimer=null),e.removeEventListener("transitionend",o),e.style.height="",e.style.overflow="",e.style.transition="",e.style.boxSizing=""},o=t=>{const n=t.propertyName;t.target===e&&"height"===n&&r()};e.style.boxSizing="border-box",e.style.overflow="hidden",e.style.height=`${n}px`,e.offsetHeight,e.style.transition="height var(--sv-dur-slow) var(--sv-ease-out)",e.style.height=`${s}px`,e.addEventListener("transitionend",o),null!==this.morphTimer&&clearTimeout(this.morphTimer),this.morphTimer=setTimeout(r,550)}createViewForState(e){switch(e.view){case"loading":case"awaiting-reference":return new Xe({message:"Loading..."});case"identity-input":return new ft({allowedTypes:this.getAllowedIdentityTypes(),initialValue:this.recipient,error:e.error,onSubmit:e=>this.handleIdentitySubmit(e),onPasskey:this.canDiscoverableVerify()?()=>{this.launchDiscoverableVerify()}:void 0,leadingMethod:this.leadingFederationMethod(),onType:()=>{this.untouchedStep=null}});case"method-select":return new gt({email:e.email,identityType:this.identityType,methods:e.methods,onSelectMethod:e=>this.handleMethodSelect(e,!0),onBack:e.email&&!this.isIdentityFixed()?()=>this.showIdentityInput():void 0});case"otp-verify":return new bt({email:e.email,method:e.method,error:e.error,backoffExpires:e.backoffExpires,onSubmit:e=>this.handleOtpSubmit(e),onResend:()=>this.handleOtpResend(),onBack:()=>this.showMethodSelect()});case"two-factor":return new kt({methods:e.methods,error:e.error,onSubmit:e=>this.handleSecondFactorSubmit(e)});case"passkey":{const{passkey:t}=this.verificationState,n="register"===e.mode&&null!==t.pendingResult;return new wt({identityLabel:e.recipient,mode:e.mode,error:e.error,onStart:()=>this.handlePasskeyStart(),onBack:n?()=>this.handlePasskeyRegistrationSkip():"verify"===e.mode?this.passkeyFallbackMethodsAvailable()?()=>this.showMethodSelect({autoRoute:!1}):this.recipient&&!this.isIdentityFixed()?()=>this.showIdentityInput():void 0:()=>this.showMethodSelect(),onFallback:t.hasPasskey&&!t.isFallbackMode&&this.passkeyFallbackMethodsAvailable()?()=>this.handlePasskeyFallback():void 0})}case"passkey-auto":return new xt({onUseAnotherMethod:()=>this.cancelDiscoverableVerify()});case"passkey-prompt":return new Ct({identityLabel:e.recipient,onAddPasskey:()=>this.handlePasskeyPromptAdd(e.pendingResult),onSkip:()=>this.handlePasskeyPromptSkip(e.pendingResult),error:e.error});case"backup-verify":return new St({missingType:e.missingType,error:e.error,onSubmit:e=>this.handleBackupSubmit(e),onSkip:()=>this.handleBackupSkip()});case"backup-code":return new bt({email:e.value,method:e.method,error:e.error,onSubmit:e=>this.handleBackupCodeSubmit(e),onResend:()=>this.handleBackupResend(),onBack:()=>this.setState({view:"backup-verify",missingType:e.missingType,pendingResult:e.pendingResult})});case"sparklink-waiting":return new Et({email:e.email,expiresAt:e.expiresAt,onResend:()=>this.handleSparkLinkResend(),onFallback:()=>this.handleSparkLinkFallback(),onBack:()=>this.showMethodSelect(),onExpired:()=>this.cleanupSparkLink()});case"oauth-pending":return new Xe({message:`Connecting to ${e.provider}...`});case"federation-checking":return new Xe({message:`Checking your ${e.displayName} sign-in…`,announce:!0});case"error":return new Pt({message:e.message,code:e.code,onRetry:e.code===_e?()=>{this.showSignInStep()}:e.code===It?()=>this.retryReference():e.code===ee.refusalCode?()=>this.chooseAnotherWay():()=>this.showIdentityInput(),onClose:()=>this.handleClose()});case"service-unavailable":return new Mt({onRetry:()=>this.retryConfigLoad(),onClose:()=>this.handleClose()});case"product-not-configured":return new Nt({onClose:()=>this.handleClose()});case"origin-not-allowed":return new Ht({origin:e.origin,onClose:()=>this.handleClose()})}}showIdentityInput(e){this.setState({view:"identity-input",error:e})}async showMethodSelect(e={}){this.cleanupSparkLink();const t=!1!==e.autoRoute;if(!this.sdkConfig)return;const n=this.verificationState.methodIds;if(!Array.isArray(n))return void this.setState({view:"error",message:"Invalid configuration",code:"invalid_config"});const i=this.federationAwaitingReference(this.recipient);let s=this.admittedMethods(Be(n));if(this.recipient){s=s.filter(e=>"phone"===this.identityType?"passkey"===e.type||"phone"===e.identityType:"email"===e.identityType||void 0===e.identityType);const{passkey:e}=this.verificationState;null===e.hasPasskey&&s.some(e=>"passkey"===e.type)&&await this.passkeyHandler.checkPasskey(),!1===this.verificationState.passkey.hasPasskey&&(s=s.filter(e=>"passkey"!==e.type))}else s=s.filter(e=>"passkey"===e.type||"social"===e.type);if(this.verificationState.passkey.isFallbackMode&&(s=s.filter(e=>"passkey"!==e.type)),this.offersFederationBeside(this.recipient)&&(s=[...Be(["federation"],this.federation),...s]),0===s.length)return void this.setState(this.noMethodState());if(t&&!this.federationStartsOnItsOwn(i)&&!0===this.verificationState.passkey.hasPasskey&&!this.verificationState.passkey.isFallbackMode&&s.some(e=>"passkey"===e.type))return void this.launchPasskeyVerify(!0);const r=this.identityPrefilled&&"phone"===s[0].identityType,o="federation"===s[0].type&&!this.federationMayAutoStart;1!==s.length||this.isIdentityFixed()||r||o||null!==i?this.setState({view:"method-select",email:this.recipient,methods:s}):this.handleMethodSelect(s[0])}noMethodState(){if(this.verificationState.passkeyRequired&&!1===this.verificationState.passkey.hasPasskey)return{view:"error",code:At,message:(e="request",t=this.sdkConfig?.branding?.companyName,`This ${e} requires a passkey already registered with SparkVault. Ask ${t||"the sender"} to resend it at a different verification level.`)};var e,t;if(this.accountFederation&&!this.federationOffered){if(!this.askReference){const e=this.sdkConfig?.federation?.display_name?.trim();return{view:"error",code:Lt,message:`This site needs to update its sign-in to use ${e||"your organization's sign-in"}.`}}return"unavailable"===this.referenceAsk?{view:"error",code:It,message:"We couldn't start sign-in. Try again."}:{view:"awaiting-reference"}}const n=this.verificationState.identityTypes;return n&&this.verificationState.methodIds.some(e=>!se(e,n))?{view:"error",code:Rt,message:oe(n)}:{view:"error",message:"No authentication methods available",code:"no_methods"}}admittedMethods(e){const t=this.verificationState.identityTypes;return e.filter(e=>se(e.id,t))}chooseAnotherWay(){this.recipient||0===this.getAllowedIdentityTypes().length?this.showMethodSelect({autoRoute:!1}):this.showIdentityInput()}renderIdentityTypeRefusal(e,t){return!(e!==ee.refusalCode||!t)&&(this.setState({view:"error",code:e,message:t}),!0)}handleIdentitySubmit(e){this.verificationState.setIdentity(e.value,e.type),this.identityPrefilled=!1,this.showMethodSelect()}getAllowedIdentityTypes(){const e=this.verificationState.getAllowedIdentityTypes(),t=this.verificationState.identityTypes;return t?e.filter(e=>t.includes(e)):e}async handleMethodSelect(e,t=!1){try{switch(e.type){case"otp":{const t="otp_sms"===e.id?"sms":"otp_voice"===e.id?"voice":"email";this.setState({view:"loading"});const n=await this.otpHandler.send(t);if(!n.success){if(this.renderBlockedInterstitial(n.errorCode))return;if(this.renderIdentityTypeRefusal(n.errorCode,n.error))return;return void this.setState({view:"error",message:n.error??"Failed to send code",code:"otp_send_failed"})}this.setState({view:"otp-verify",email:this.recipient,method:t,kindling:this.verificationState.otp.kindling});break}case"passkey":t?await this.launchPasskeyVerify():this.setState({view:"passkey",recipient:this.recipient,mode:"verify"});break;case"sparklink":{this.setState({view:"loading"});const e=await this.openSparkLinkWebSocket();if("error"in e)return this.cleanupSparkLink(),void("csp"===e.error?this.setState({view:"error",...Ut}):this.setState({view:"error",message:"Failed to establish connection",code:"sparklink_ws_failed"}));const t=await this.sparkLinkHandler.send(e.connectionId);if(!t.success){if(this.cleanupSparkLink(),this.renderBlockedInterstitial(t.errorCode))return;if(this.renderIdentityTypeRefusal(t.errorCode,t.error))return;return void this.setState({view:"error",message:t.error??"Failed to send SparkLink",code:"sparklink_send_failed"})}this.sparkLinkKindling=t.kindling??null,this.armSparkLinkRefocusClaim(),this.setState({view:"sparklink-waiting",email:this.recipient,expiresAt:t.expiresAt});break}case"social":e.provider&&await this.handleSocialLogin(e.provider);break;case"federation":await this.leaveForFederation({silent:!1,automatic:!t});break;default:this.setState({view:"error",message:`Authentication method not supported: ${e.type}`,code:"unsupported_method"})}}catch(e){this.handleErrorWithRecovery(e,"unknown")}}renderBlockedInterstitial(e){return!(!e||!zt.has(e))&&(this.setState({view:"error",code:e,message:Vt(this.verificationState.sdkConfig?.branding?.companyName)}),!0)}async handleOtpSubmit(e){if("otp-verify"!==this.viewState.view)return;const t=this.verificationState.otp.method??"email";Dt();const n=await this.otpHandler.verify(e);if(n.secondFactor)this.setState({view:"two-factor",ticket:n.secondFactor.ticket,methods:n.secondFactor.methods});else if(n.success&&n.result)this.runPostLogin(n.result);else if(this.renderBlockedInterstitial(n.errorCode));else if(this.renderIdentityTypeRefusal(n.errorCode,n.error));else if("identity_locked"===n.errorCode)this.setState({view:"error",code:"identity_locked",message:"This SparkVault Identity is locked. Visit auth.sv to manage it."});else{if((n.error?.toLowerCase()??"").includes("expired")){const e=await this.otpHandler.resend();return e.success?void this.setState({view:"otp-verify",email:this.recipient,method:t,kindling:this.verificationState.otp.kindling,error:"Code expired. We've sent a new one."}):void this.setState({view:"otp-verify",email:this.recipient,method:t,kindling:this.verificationState.otp.kindling,error:e.error??"Code expired and failed to resend."})}this.setState({view:"otp-verify",email:this.recipient,method:t,kindling:this.verificationState.otp.kindling,error:n.error??"Invalid code. Please try again.",backoffExpires:n.backoffExpires})}}async handleSecondFactorSubmit(e){if("two-factor"!==this.viewState.view)return;const{ticket:t,methods:n}=this.viewState;try{const n=await this.api.submitSecondFactor({ticket:t,code:e}),i={token:n.token??"",identity:n.identity??this.recipient,identityType:n.identity_type??this.identityType,svid:n.svid,sessionId:n.session_id,refreshToken:n.refresh_token,redirect:n.redirect};this.close(),this.safeOnSuccess(i),"string"==typeof i.redirect&&i.redirect&&(window.location.href=i.redirect)}catch(e){const i=e instanceof Error?e.message:"That code is not valid. Please try again.";if(e instanceof ke&&this.renderIdentityTypeRefusal(e.code,i))return;this.setState({view:"two-factor",ticket:t,methods:n,error:i})}}async handleOtpResend(){if("otp-verify"!==this.viewState.view)return;const e=this.verificationState.otp.method??"email",t=await this.otpHandler.resend();if(!t.success){if(this.renderBlockedInterstitial(t.errorCode))return;this.setState({view:"otp-verify",email:this.recipient,method:e,kindling:this.verificationState.otp.kindling,error:t.error??"Failed to resend code"})}}async handlePasskeyStart(){if("passkey"!==this.viewState.view)return;const e=this.viewState.mode,t="register"===e?await this.passkeyHandler.register():await this.passkeyHandler.verify();this.applyPasskeyResult(t,e)}async launchPasskeyVerify(e=!1){this.setState({view:"loading"});const t=await this.passkeyHandler.verify();this.applyPasskeyResult(t,"verify",e)}applyTerminalPasskeyResult(e){return e.success&&e.result?(this.close(),this.safeOnSuccess(e.result),"string"==typeof e.result.redirect&&e.result.redirect&&(window.location.href=e.result.redirect),!0):!!this.renderBlockedInterstitial(e.errorCode)||(!!this.renderIdentityTypeRefusal(e.errorCode,e.error)||"identity_locked"===e.errorCode&&(this.setState({view:"error",code:"identity_locked",message:"This SparkVault Identity is locked. Visit auth.sv to manage it."}),!0))}applyPasskeyResult(e,t,n=!1){this.applyTerminalPasskeyResult(e)||(n&&this.passkeyFallbackMethodsAvailable()?this.showMethodSelect({autoRoute:!1}):"not_found"===e.errorType?this.setState({view:"passkey",recipient:this.recipient,mode:"register",error:e.error}):this.setState({view:"passkey",recipient:this.recipient,mode:t,error:e.error}))}async handlePasskeyFallback(){this.verificationState.enablePasskeyFallback(),await this.showMethodSelect()}passkeyFallbackMethodsAvailable(){if(!this.sdkConfig)return!1;const e=this.admittedMethods(Be(this.verificationState.methodIds,this.federation));return this.recipient?e.some(e=>"passkey"!==e.type&&("federation"===e.type?this.offersFederationBeside(this.recipient):"phone"===this.identityType?"phone"===e.identityType:"email"===e.identityType)):e.some(e=>"social"===e.type||"federation"===e.type)}handlePasskeyRegistrationSkip(){this.verificationState.setPendingResult(null),this.dismissRecommendation("passkey"),this.advancePostLogin()}async handleSocialLogin(e){this.setState({view:"oauth-pending",provider:e});const{state:t}=await this.api.drawAuthorizationValues();sessionStorage.setItem("sv_oauth_state",t);const n=this.api.getSocialAuthUrl(e,pe(),t,this.verificationState.authContext,{signinRef:this.verificationState.signinRef,identityTypes:this.verificationState.identityTypes});window.location.href=n}get federation(){return this.federationOffered?this.accountFederation:null}get federationOffered(){return this.offeredWithoutReference||null!==this.verificationState.signinRef}get accountFederation(){const e=this.sdkConfig?.federation,t=this.verificationState.methodIds;return e&&Array.isArray(t)&&t.includes(J)&&se(J,this.verificationState.identityTypes)?e:null}offersFederationBeside(e){return!e||this.identityPrefilled}leadingFederationMethod(){const[e]=Be(["federation"],this.federation);if(e)return{method:e,onSelect:()=>{this.handleMethodSelect(e,!0)}}}async leaveForFederation({silent:e,automatic:t}){const n=this.federation;if(!n)return;t&&(this.federationMayAutoStart=!1),this.setState(e?{view:"federation-checking",displayName:n.display_name}:{view:"oauth-pending",provider:n.display_name});const{state:i}=await this.api.drawAuthorizationValues();sessionStorage.setItem("sv_oauth_state",i),t&&function(e){try{sessionStorage.setItem(Pe,JSON.stringify({at:Date.now(),accountId:e}))}catch{}}(this.api.accountId),this.watchForPageRestore(),window.location.href=this.api.getFederationAuthUrl(pe(),i,this.verificationState.authContext,{silent:e,signinRef:this.verificationState.signinRef,identityTypes:this.verificationState.identityTypes})}watchForPageRestore(){this.pageRestoreHandler||(this.pageRestoreHandler=e=>{e.persisted&&($e(this.api.accountId),this.federationMayAutoStart=!1,this.showSignInStep())},window.addEventListener("pageshow",this.pageRestoreHandler))}federationFailedState(){const e=this.sdkConfig?.federation?.display_name;return{view:"error",code:_e,message:e?`We couldn't sign you in with ${e}. Please try again.`:"We couldn't sign you in through your organization. Please try again."}}normalizeError(e){return e instanceof ke?new p(e.message,e.code):e instanceof Error?e:new Error(String(e))}isSessionExpiredError(e){const t=e.message.toLowerCase(),n=e instanceof p?e.code:"";return t.includes("expired")||t.includes("session")||t.includes("invalid token")||t.includes("token invalid")||"token_expired"===n||"session_expired"===n||"kindling_expired"===n}handleErrorWithRecovery(e,t){const n=this.normalizeError(e);n instanceof p&&this.renderIdentityTypeRefusal(n.code,n.message)||(this.isSessionExpiredError(n)?this.showIdentityInput("Your session has expired. Please try again."):this.setState({view:"error",message:n.message,code:n instanceof p?n.code:t}))}runPostLogin(e){e.redirect?this.finalizeLogin(e):(this.postLoginResult=e,this.postLoginQueue=[...e.recommendations??[]],this.advancePostLogin())}advancePostLogin(){const e=this.postLoginResult;if(!e)return;const t=this.postLoginQueue.shift();if(!t)return this.postLoginResult=null,void this.finalizeLogin(e);"passkey"===t.type?this.setState({view:"passkey-prompt",recipient:this.recipient,pendingResult:e}):"backup_identifier"===t.type?this.setState({view:"backup-verify",missingType:t.missingType,pendingResult:e}):this.advancePostLogin()}dismissRecommendation(e){const t=this.postLoginResult?.token;t&&this.api.dismissRecommendation({verificationToken:t,key:e}).catch(()=>{})}finalizeLogin(e){this.safeOnSuccess(e),this.close(),"string"==typeof e.redirect&&e.redirect&&(window.location.href=e.redirect)}async handleBackupSubmit(e){if("backup-verify"!==this.viewState.view)return;const{missingType:t,pendingResult:n}=this.viewState;this.setState({view:"loading"});try{const i=await this.api.sendBackupVerification({verificationToken:n.token,type:t,value:e});if(i.already_verified||!i.session_id)return void this.advancePostLogin();this.setState({view:"backup-code",missingType:t,value:e,method:i.method??("phone"===t?"sms":"email"),sessionId:i.session_id,pendingResult:n})}catch(e){this.setState({view:"backup-verify",missingType:t,pendingResult:n,error:e instanceof Error?e.message:"Could not send a code. Please try again."})}}async handleBackupCodeSubmit(e){if("backup-code"!==this.viewState.view)return;const{missingType:t,value:n,method:i,sessionId:s,pendingResult:r}=this.viewState;try{await this.api.verifyBackupVerification({sessionId:s,code:e}),this.advancePostLogin()}catch(e){if("backup_conflict"===(e instanceof ke?e.code:""))return void this.setState({view:"backup-verify",missingType:t,pendingResult:r,error:e instanceof Error?e.message:"That identifier is already linked to another account."});this.setState({view:"backup-code",missingType:t,value:n,method:i,sessionId:s,pendingResult:r,error:e instanceof Error?e.message:"That code is not valid. Please try again."})}}async handleBackupResend(){if("backup-code"!==this.viewState.view)return;const{missingType:e,value:t,method:n,pendingResult:i}=this.viewState;try{const s=await this.api.sendBackupVerification({verificationToken:i.token,type:e,value:t,method:n});s.session_id&&this.setState({view:"backup-code",missingType:e,value:t,method:s.method??n,sessionId:s.session_id,pendingResult:i})}catch{}}handleBackupSkip(){if("backup-verify"!==this.viewState.view)return;const{missingType:e}=this.viewState;this.dismissRecommendation("phone"===e?"backup_phone":"backup_email"),this.advancePostLogin()}async handlePasskeyPromptAdd(e){this.verificationState.setPendingResult(e),this.setState({view:"loading"});const t=await this.passkeyHandler.register(e.token);if(t.success&&t.result)this.postLoginResult=t.result,this.advancePostLogin();else if("cancelled"===t.errorType)this.setState({view:"passkey-prompt",recipient:this.recipient,pendingResult:e});else{const n=t.error||"Failed to create passkey. Please try again.";this.setState({view:"passkey-prompt",recipient:this.recipient,pendingResult:e,error:n})}}handlePasskeyPromptSkip(e){this.dismissRecommendation("passkey"),this.advancePostLogin()}openSparkLinkWebSocket(){this.cleanupSparkLink();const e=this.sdkConfig?.wsDomain||"ws.sparkvault.com",t=`wss://${e}`;return new Promise(n=>{let i=!1,s=!1;const r=t=>{"connect-src"===t.violatedDirective&&t.blockedURI.includes(e)&&(s=!0)};document.addEventListener("securitypolicyviolation",r);const o=()=>{document.removeEventListener("securitypolicyviolation",r)},a=new WebSocket(t);this.sparkLinkWs=a;const l=setTimeout(()=>{i||(i=!0,o(),a.close(),n({error:s?"csp":"connection"}))},1e4);a.onopen=()=>{try{a.send(JSON.stringify({action:"init"}))}catch{i||(i=!0,o(),clearTimeout(l),n({error:"connection"}))}},a.onmessage=e=>{let t;try{t=JSON.parse(e.data)}catch{return}if(!i&&"connection"===t.type&&"string"==typeof t.connectionId)return i=!0,o(),clearTimeout(l),this.setupSparkLinkWsHandler(a),void n({connectionId:t.connectionId})},a.onerror=()=>{i||(i=!0,o(),clearTimeout(l),n({error:s?"csp":"connection"}))},a.onclose=()=>{i||(i=!0,o(),clearTimeout(l),n({error:s?"csp":"connection"}))}})}setupSparkLinkWsHandler(e){e.onmessage=e=>{let t;try{t=JSON.parse(e.data)}catch{return}switch(t.type){case"sparklink_verified":case"sparklink_second_factor":{const e=ye(t);if(!e){this.failSparkLink();break}this.burnSparkLinkFallback(),this.applySparkLinkOutcome(e);break}case"sparklink_failed":this.failSparkLink();break;case"sparklink_resent":"number"==typeof t.expiresAt&&this.setState({view:"sparklink-waiting",email:this.recipient,expiresAt:t.expiresAt})}},e.onclose=()=>{this.sparkLinkWs=null}}applySparkLinkOutcome(e){this.cleanupSparkLink(),"second_factor"!==e.kind?this.runPostLogin(e.result):this.setState({view:"two-factor",ticket:e.ticket,methods:e.methods})}burnSparkLinkFallback(){const e=this.sparkLinkKindling;e&&this.api.consumeSparkLinkResult(e).catch(()=>{})}failSparkLink(){this.cleanupSparkLink(),this.setState({view:"error",message:"Verification failed. Please try again or choose a different method.",code:"sparklink_failed"})}armSparkLinkRefocusClaim(){if(this.sparkLinkVisibilityHandler||!this.sparkLinkKindling)return;if("undefined"==typeof document)return;const e=()=>{"undefined"!=typeof document&&"visible"!==document.visibilityState||this.sparkLinkWs&&this.sparkLinkWs.readyState===WebSocket.OPEN||this.claimSparkLinkResult(!0)};this.sparkLinkVisibilityHandler=e,document.addEventListener("visibilitychange",e),"undefined"!=typeof window&&window.addEventListener("pageshow",e)}async claimSparkLinkResult(e){const t=this.sparkLinkKindling;if(!t||this.sparkLinkClaiming)return;this.sparkLinkClaiming=!0;let n=null;try{n=await this.api.consumeSparkLinkResult(t)}catch{n=null}this.sparkLinkClaiming=!1,n?this.applySparkLinkOutcome(n):e&&this.sparkLinkKindling===t&&(this.sparkLinkRetryTimer=setTimeout(()=>{this.sparkLinkRetryTimer=null,this.sparkLinkKindling===t&&this.claimSparkLinkResult(!1)},2e3))}cleanupSparkLink(){this.sparkLinkWs&&(this.sparkLinkWs.onmessage=null,this.sparkLinkWs.onclose=null,this.sparkLinkWs.onerror=null,this.sparkLinkWs.close(),this.sparkLinkWs=null),this.sparkLinkVisibilityHandler&&("undefined"!=typeof document&&document.removeEventListener("visibilitychange",this.sparkLinkVisibilityHandler),"undefined"!=typeof window&&window.removeEventListener("pageshow",this.sparkLinkVisibilityHandler),this.sparkLinkVisibilityHandler=null),null!==this.sparkLinkRetryTimer&&(clearTimeout(this.sparkLinkRetryTimer),this.sparkLinkRetryTimer=null),this.sparkLinkKindling=null}async handleSparkLinkResend(){const e=await this.openSparkLinkWebSocket();if("error"in e)return this.cleanupSparkLink(),void("csp"===e.error?this.setState({view:"error",...Ut}):this.setState({view:"error",message:"Unable to establish a secure connection. Please try again or choose a different method.",code:"sparklink_ws_failed"}));const t=await this.sparkLinkHandler.send(e.connectionId);if(t.success)this.sparkLinkKindling=t.kindling??null,this.armSparkLinkRefocusClaim(),this.setState({view:"sparklink-waiting",email:this.recipient,expiresAt:t.expiresAt});else{if(this.cleanupSparkLink(),this.renderIdentityTypeRefusal(t.errorCode,t.error))return;this.setState({view:"error",message:t.error??"Failed to resend verification link. Please try again.",code:"sparklink_resend_failed"})}}async handleSparkLinkFallback(){this.cleanupSparkLink(),this.setState({view:"loading"});const e=await this.otpHandler.send("email");if(e.success)this.setState({view:"otp-verify",email:this.recipient,method:"email",kindling:this.verificationState.otp.kindling});else{if(this.renderBlockedInterstitial(e.errorCode))return;if(this.renderIdentityTypeRefusal(e.errorCode,e.error))return;this.setState({view:"error",message:e.error??"Failed to send code",code:"otp_send_failed"})}}}const Wt="sparkvault-identity-styles";function qt(e){if(document.getElementById(Wt))return Kt(e.branding),void function(e){const t=document.getElementById("sparkvault-identity-overlay");t&&(!1!==e?t.classList.add("sv-blur"):t.classList.remove("sv-blur"))}(e.backdropBlur);const t=document.createElement("style");t.id=Wt,t.dataset.svTheme=Gt(e.branding),t.textContent=Yt(e),document.head.appendChild(t)}function Kt(e){const t=document.getElementById(Wt);if(!t)return;const n=Gt(e);t.dataset.svTheme!==n&&(t.dataset.svTheme=n,t.textContent=Yt({branding:e??{companyName:"",logoLight:null,logoDark:null}}))}function Gt(e){return e?.themeMode??"light"}function Yt(e){const{branding:t,backdropBlur:n}=e,i="dark"===Gt(t),s=!1!==n,r=`var(--sv-primary, ${$t.action})`,o=i?$t.slate950:$t.white,a=`color-mix(in srgb, ${r} 80%, white)`,l=r,d=`var(--sv-primary-hover, ${$t.actionHover})`,c=`color-mix(in srgb, ${r} ${i?"20%":"9%"}, transparent)`,h=i?$t.error500:$t.error,u=i?Ot($t.error500,.12):$t.errorBg,p=Ot($t.error500,.35),m=$t.btnDanger,f=$t.btnDangerHover,v=i?$t.warning500:$t.warning,g=o,y=i?$t.darkCard:$t.slate50,b=i?Ot($t.white,.08):$t.slate100,k=i?Ot($t.white,.04):$t.white,w=i?$t.darkHairline:$t.slate200,x=i?Ot($t.white,.18):$t.slate300,C=r,S=i?Ot($t.white,.35):$t.slate300,E=i?$t.darkText:$t.slate900,T=i?$t.darkTextMuted:$t.slate600,A=i?Ot($t.white,.45):$t.slate500,L=$t.white,I=`0 0 0 2px ${o}, 0 0 0 4px ${a}`,R=i?"0 1px 2px rgba(0, 0, 0, 0.4)":$t.shadowSm,B=(i||$t.shadowMd,i?`0 8px 24px rgba(0, 0, 0, 0.5), 0 0 0 1px ${$t.darkHairline}`:$t.shadowPopover);return`\n /* ========================================\n MOTION SYSTEM: shared duration/easing tokens so every transition in\n the flow is consistent. 120/180/280ms tiers; standard and decelerate\n curves only, never overshoot.\n ======================================== */\n :root {\n --sv-dur-instant: 120ms;\n --sv-dur-fast: 120ms;\n --sv-dur-base: 180ms;\n --sv-dur-slow: 280ms;\n --sv-dur-slower: 280ms;\n --sv-ease-standard: cubic-bezier(0.2, 0, 0, 1);\n --sv-ease-out: cubic-bezier(0, 0, 0.2, 1);\n --sv-ease-accelerate: cubic-bezier(0.2, 0, 0, 1);\n --sv-ease-spring: cubic-bezier(0.2, 0, 0, 1);\n }\n\n /* Each mounted view enters with a calm fade + rise. Applied by the renderer\n on every step change; the brand lockup and footer never move. */\n @keyframes sv-step-in {\n from { opacity: 0; transform: translateY(8px); }\n to { opacity: 1; transform: none; }\n }\n .sv-step-enter { animation: sv-step-in var(--sv-dur-base) var(--sv-ease-out) both; }\n\n /* The top progress bar itself is owned and styled by the sign-in page\n (login-popup.js); the renderer only drives it via window.__sparkvaultProgress. */\n\n @media (prefers-reduced-motion: reduce) {\n .sv-step-enter { animation-duration: 1ms; }\n }\n\n /* ========================================\n OVERLAY & MODAL CONTAINER\n ======================================== */\n\n .sv-overlay {\n position: fixed;\n inset: 0;\n background: ${i?"rgba(0, 0, 0, 0.7)":$t.modalOverlay};\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: 999999;\n padding: 16px;\n box-sizing: border-box;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n }\n\n .sv-overlay.sv-blur {\n backdrop-filter: blur(${s?"8px":"0"});\n -webkit-backdrop-filter: blur(${s?"8px":"0"});\n }\n\n .sv-modal {\n background: ${g};\n border-radius: 12px;\n box-shadow: ${B};\n width: 100%;\n max-width: 400px;\n max-height: calc(100vh - 32px);\n display: flex;\n flex-direction: column;\n color: ${E};\n }\n\n /* ========================================\n HEADER\n ======================================== */\n\n .sv-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 14px 20px;\n border-bottom: 1px solid ${w};\n background: ${g};\n border-radius: 12px 12px 0 0;\n flex-shrink: 0;\n }\n\n .sv-header-title {\n display: flex;\n align-items: center;\n gap: 12px;\n min-width: 0;\n }\n\n .sv-logo {\n height: 28px;\n width: auto;\n max-width: 140px;\n object-fit: contain;\n flex-shrink: 0;\n }\n\n .sv-company-name {\n font-size: 15px;\n font-weight: 600;\n letter-spacing: -0.01em;\n margin: 0;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n }\n\n .sv-close-btn {\n flex-shrink: 0;\n width: 32px;\n height: 32px;\n display: flex;\n align-items: center;\n justify-content: center;\n background: ${y};\n border: none;\n border-radius: 6px;\n cursor: pointer;\n color: ${T};\n transition: background var(--sv-dur-fast) var(--sv-ease-standard), color var(--sv-dur-fast) var(--sv-ease-standard);\n }\n\n .sv-close-btn:hover {\n background: ${b};\n color: ${E};\n }\n\n .sv-close-btn:focus-visible {\n outline: none;\n box-shadow: ${I};\n }\n\n /* ========================================\n BODY\n ======================================== */\n\n .sv-body {\n padding: 24px 28px;\n overflow-y: auto;\n flex: 1;\n }\n\n /* ========================================\n TYPOGRAPHY\n ======================================== */\n\n .sv-title {\n font-size: 21px;\n font-weight: 600;\n letter-spacing: -0.02em;\n line-height: 1.22;\n margin: 0 0 7px 0;\n text-align: left;\n color: ${E};\n }\n\n .sv-subtitle {\n font-size: 14px;\n font-weight: 400;\n line-height: 1.5;\n color: ${T};\n margin: 0 0 16px 0;\n text-align: left;\n text-wrap: balance;\n }\n\n /* Icon-led ceremony screens (passkey set-up / sign-in) are a fully\n centered composition: the headline and subtitle follow the glyph. */\n div:has(> .sv-passkey-icon) ~ .sv-title,\n div:has(> .sv-passkey-icon) ~ .sv-subtitle {\n text-align: center;\n }\n\n .sv-subtitle strong {\n color: ${E};\n font-weight: 500;\n }\n\n /* ========================================\n FORM ELEMENTS\n ======================================== */\n\n .sv-form-group {\n margin-bottom: 16px;\n }\n\n .sv-label {\n display: block;\n font-size: 13px;\n font-weight: 500;\n letter-spacing: -0.005em;\n margin-bottom: 6px;\n color: ${E};\n }\n\n .sv-input {\n width: 100%;\n padding: 13px 14px;\n font-size: 15px;\n font-weight: 400;\n line-height: 1.4;\n border: 1px solid ${w};\n border-radius: 8px;\n background: ${k};\n color: ${E};\n box-sizing: border-box;\n box-shadow: ${R};\n transition: border-color var(--sv-dur-fast) var(--sv-ease-standard), box-shadow var(--sv-dur-fast) var(--sv-ease-standard);\n }\n\n .sv-input:hover:not(:focus):not(:disabled) {\n border-color: ${x};\n }\n\n .sv-input:focus {\n outline: none;\n border-color: ${C};\n box-shadow: 0 0 0 3px ${c};\n }\n\n .sv-input::placeholder {\n color: ${A};\n }\n\n .sv-input:disabled {\n opacity: 0.5;\n cursor: not-allowed;\n }\n\n .sv-input.sv-input-error,\n .sv-input.sv-email-input-error {\n border-color: ${h};\n }\n\n .sv-input.sv-input-error:focus,\n .sv-input.sv-email-input-error:focus {\n box-shadow: 0 0 0 3px ${u};\n }\n\n /* ========================================\n BUTTONS\n ======================================== */\n\n .sv-btn {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n gap: 8px;\n width: 100%;\n padding: 14px 16px;\n font-size: 15px;\n font-weight: 600;\n letter-spacing: -0.006em;\n line-height: 1.35;\n border: none;\n border-radius: 8px;\n cursor: pointer;\n transition: background var(--sv-dur-fast) var(--sv-ease-standard), box-shadow var(--sv-dur-fast) var(--sv-ease-standard);\n box-sizing: border-box;\n }\n\n .sv-btn:focus-visible {\n outline: none;\n box-shadow: ${I};\n }\n\n .sv-btn:disabled {\n opacity: 0.5;\n cursor: not-allowed;\n }\n\n /* Press = visual compression via an inset shadow, never scale. */\n .sv-btn:active:not(:disabled) {\n box-shadow: inset 0 1px 2px ${Ot($t.slate900,.2)};\n }\n\n /* Primary Button */\n .sv-btn-primary,\n .sv-btn-email-primary {\n background: ${l};\n color: ${L};\n box-shadow: ${R};\n }\n\n .sv-btn-primary:hover:not(:disabled),\n .sv-btn-email-primary:hover:not(:disabled) {\n background: ${d};\n }\n\n /* Secondary Button, quiet: subtle fill, hairline border */\n .sv-btn-secondary {\n background: ${y};\n color: ${E};\n border: 1px solid ${w};\n }\n\n .sv-btn-secondary:hover:not(:disabled) {\n background: ${b};\n border-color: ${x};\n }\n\n /* Method Button: a full-width row with a nudging chevron affordance\n (added via ::after so no DOM change is needed). The card itself stays\n planted: hover is a quiet fill + border shift, no translate. */\n .sv-btn-method {\n position: relative;\n background: ${g};\n border: 1px solid ${w};\n border-radius: 10px;\n color: ${E};\n text-align: left;\n padding: 15px 40px 15px 14px;\n margin-bottom: 9px;\n transition: background var(--sv-dur-fast) var(--sv-ease-standard), border-color var(--sv-dur-fast) var(--sv-ease-standard);\n }\n\n .sv-btn-method::after {\n content: "";\n position: absolute;\n right: 16px;\n top: 50%;\n width: 8px;\n height: 8px;\n border-right: 1.6px solid ${S};\n border-top: 1.6px solid ${S};\n transform: translateY(-50%) rotate(45deg);\n transition: transform var(--sv-dur-base) var(--sv-ease-out), border-color var(--sv-dur-fast) var(--sv-ease-standard);\n }\n\n .sv-btn-method:hover:not(:disabled)::after {\n transform: translateY(-50%) translateX(3px) rotate(45deg);\n border-color: ${l};\n }\n\n .sv-btn-method:focus-visible {\n outline: none;\n box-shadow: ${I};\n }\n\n .sv-btn-method:hover:not(:disabled) {\n background: ${y};\n border-color: ${x};\n }\n\n .sv-btn-method:last-child {\n margin-bottom: 0;\n }\n\n /* Error Buttons */\n .sv-btn-error-primary {\n background: ${m};\n color: ${L};\n box-shadow: ${R};\n }\n\n .sv-btn-error-primary:hover:not(:disabled) {\n background: ${f};\n }\n\n .sv-btn-error-secondary {\n background: ${y};\n color: ${T};\n border: 1px solid ${w};\n }\n\n .sv-btn-error-secondary:hover:not(:disabled) {\n background: ${b};\n color: ${E};\n }\n\n /* ========================================\n METHOD SELECTION\n ======================================== */\n\n .sv-method-content {\n display: flex;\n align-items: center;\n gap: 12px;\n width: 100%;\n }\n\n /* Bare glyph slot, no container chrome. Quiet slate stroke that takes\n the accent on row hover. */\n .sv-method-icon {\n width: 20px;\n height: 20px;\n flex-shrink: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n color: ${A};\n transition: color var(--sv-dur-fast) var(--sv-ease-standard);\n }\n\n .sv-btn-method:hover:not(:disabled) .sv-method-icon {\n color: ${l};\n }\n\n .sv-method-icon svg {\n width: 20px;\n height: 20px;\n }\n\n .sv-method-text {\n flex: 1;\n min-width: 0;\n }\n\n .sv-method-name {\n font-weight: 600;\n font-size: 15px;\n color: ${E};\n }\n\n .sv-method-description {\n font-size: 13px;\n color: ${A};\n margin-top: 1px;\n }\n\n /* ========================================\n OTP INPUT\n ======================================== */\n\n .sv-otp-input-group {\n display: flex;\n gap: 8px;\n justify-content: center;\n margin-bottom: 16px;\n }\n\n .sv-otp-digit {\n width: 46px;\n height: 56px;\n text-align: center;\n font-size: 22px;\n font-weight: 600;\n letter-spacing: 0;\n font-variant-numeric: tabular-nums;\n caret-color: transparent;\n border: 1px solid ${w};\n border-radius: 8px;\n background: ${k};\n color: ${E};\n box-sizing: border-box;\n transition: border-color var(--sv-dur-fast) var(--sv-ease-standard), box-shadow var(--sv-dur-fast) var(--sv-ease-standard);\n }\n\n .sv-otp-digit:hover:not(:focus):not(:disabled) {\n border-color: ${x};\n }\n\n .sv-otp-digit:focus {\n outline: none;\n border-color: ${C};\n box-shadow: 0 0 0 3px ${c};\n }\n\n .sv-otp-digit:disabled {\n opacity: 0.5;\n cursor: not-allowed;\n }\n\n /* ========================================\n BACK LINK\n ======================================== */\n\n .sv-back-link {\n display: inline-flex;\n align-items: center;\n gap: 4px;\n color: ${T};\n font-size: 13px;\n font-weight: 500;\n text-decoration: none;\n cursor: pointer;\n background: none;\n border: none;\n padding: 0;\n margin-bottom: 16px;\n transition: color var(--sv-dur-fast) var(--sv-ease-standard);\n }\n\n .sv-back-link:hover:not(:disabled) {\n color: ${l};\n }\n\n .sv-back-link:disabled {\n opacity: 0.5;\n cursor: not-allowed;\n }\n\n .sv-back-link svg {\n width: 14px;\n height: 14px;\n }\n\n /* ========================================\n ERROR MESSAGE\n ======================================== */\n\n .sv-error {\n background: ${u};\n border: 1px solid ${p};\n color: ${h};\n padding: 10px 12px;\n border-radius: 8px;\n font-size: 13px;\n font-weight: 500;\n margin-bottom: 16px;\n }\n\n /* ========================================\n LOADING STATE\n ======================================== */\n\n .sv-loading {\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n padding: 48px 24px;\n gap: 16px;\n }\n\n .sv-spinner {\n width: 28px;\n height: 28px;\n border: 2.5px solid ${w};\n border-top-color: ${l};\n border-radius: 50%;\n animation: sv-spin 0.7s linear infinite;\n }\n\n .sv-loading-text {\n font-size: 14px;\n color: ${T};\n margin: 0;\n }\n\n @keyframes sv-spin {\n to { transform: rotate(360deg); }\n }\n\n /* ========================================\n FOOTER\n ======================================== */\n\n .sv-footer {\n padding: 10px 20px;\n text-align: center;\n flex-shrink: 0;\n }\n\n .sv-footer-text {\n font-size: 10px;\n color: ${A};\n letter-spacing: 0.02em;\n }\n\n .sv-footer-link {\n color: ${T};\n text-decoration: none;\n font-weight: 500;\n transition: color var(--sv-dur-fast) var(--sv-ease-standard);\n }\n\n .sv-footer-link:hover {\n color: ${l};\n }\n\n /* ========================================\n IDENTITY INPUT VIEW\n ======================================== */\n\n .sv-email-view {\n display: flex;\n flex-direction: column;\n }\n\n .sv-email-header {\n margin-bottom: 16px;\n }\n\n .sv-email-subtitle {\n font-size: 14px;\n font-weight: 500;\n line-height: 1.4;\n color: ${T};\n margin: 0;\n }\n\n .sv-email-error-container {\n width: 100%;\n }\n\n .sv-email-form {\n width: 100%;\n }\n\n .sv-email-input-wrapper {\n margin-bottom: 14px;\n }\n\n .sv-email-label {\n display: block;\n font-size: 13px;\n font-weight: 500;\n letter-spacing: -0.005em;\n margin-bottom: 6px;\n color: ${E};\n }\n\n .sv-email-input {\n width: 100%;\n padding: 10px 12px;\n font-size: 15px;\n font-weight: 400;\n line-height: 1.4;\n border: 1px solid ${w};\n border-radius: 8px;\n background: ${k};\n color: ${E};\n box-sizing: border-box;\n transition: border-color var(--sv-dur-fast) var(--sv-ease-standard), box-shadow var(--sv-dur-fast) var(--sv-ease-standard);\n }\n\n .sv-email-input:hover:not(:focus):not(:disabled) {\n border-color: ${x};\n }\n\n .sv-email-input:focus {\n outline: none;\n border-color: ${C};\n box-shadow: 0 0 0 3px ${c};\n }\n\n .sv-email-input::placeholder {\n color: ${A};\n }\n\n .sv-email-input-error {\n border-color: ${h};\n }\n\n .sv-email-input-error:focus {\n box-shadow: 0 0 0 3px ${u};\n }\n\n /* The SMS and voice consent under a phone number field: fine print in the\n secondary ink, its links underlined in the same ink so each reads as a\n link without a second color. */\n .sv-sms-consent {\n margin: 8px 0 0;\n font-size: 12px;\n line-height: 1.5;\n color: ${T};\n }\n\n .sv-sms-consent-link {\n color: inherit;\n text-decoration: underline;\n text-underline-offset: 2px;\n border-radius: 2px;\n transition: color var(--sv-dur-fast) var(--sv-ease-standard);\n }\n\n .sv-sms-consent-link:hover {\n color: ${E};\n }\n\n .sv-sms-consent-link:focus-visible {\n outline: none;\n box-shadow: ${I};\n }\n\n /* ========================================\n ERROR VIEW\n ======================================== */\n\n .sv-error-view {\n display: flex;\n flex-direction: column;\n align-items: center;\n text-align: center;\n }\n\n .sv-error-icon-container {\n margin-bottom: 16px;\n }\n\n .sv-error-icon {\n width: 48px;\n height: 48px;\n }\n\n .sv-error-content {\n margin-bottom: 24px;\n }\n\n .sv-error-title {\n font-size: 18px;\n font-weight: 600;\n letter-spacing: -0.02em;\n margin: 0 0 8px 0;\n color: ${E};\n }\n\n .sv-error-message {\n font-size: 14px;\n line-height: 1.5;\n color: ${T};\n margin: 0 0 16px 0;\n }\n\n .sv-error-code-badge {\n display: inline-flex;\n align-items: center;\n gap: 6px;\n padding: 6px 10px;\n background: ${u};\n border: 1px solid ${p};\n border-radius: 6px;\n }\n\n .sv-error-code-label {\n font-size: 10px;\n font-weight: 600;\n color: ${i?$t.error500:$t.errorText};\n text-transform: uppercase;\n letter-spacing: 0.05em;\n }\n\n .sv-error-code-value {\n font-size: 11px;\n font-family: 'IBM Plex Mono', ui-monospace, SFMono-Regular, 'SF Mono', Menlo, Monaco, 'Cascadia Mono', monospace;\n color: ${h};\n font-weight: 500;\n }\n\n .sv-error-actions {\n display: flex;\n gap: 10px;\n width: 100%;\n }\n\n .sv-error-actions .sv-btn {\n flex: 1;\n }\n\n /* ========================================\n SERVICE UNAVAILABLE VIEW\n ======================================== */\n\n .sv-unavailable-view {\n display: flex;\n flex-direction: column;\n align-items: center;\n text-align: center;\n }\n\n .sv-unavailable-icon-container {\n margin-bottom: 16px;\n }\n\n .sv-unavailable-icon {\n width: 48px;\n height: 48px;\n }\n\n .sv-unavailable-content {\n margin-bottom: 24px;\n }\n\n .sv-unavailable-title {\n font-size: 18px;\n font-weight: 600;\n letter-spacing: -0.02em;\n margin: 0 0 8px 0;\n color: ${E};\n }\n\n .sv-unavailable-message {\n font-size: 14px;\n line-height: 1.5;\n color: ${T};\n margin: 0;\n }\n\n .sv-unavailable-actions {\n display: flex;\n gap: 10px;\n width: 100%;\n }\n\n .sv-unavailable-actions .sv-btn {\n flex: 1;\n }\n\n @media (max-width: 480px) {\n .sv-unavailable-actions {\n flex-direction: column;\n }\n }\n\n /* ========================================\n MINIMAL CHROME (full-dialog views)\n ======================================== */\n\n .sv-modal-minimal {\n position: relative;\n }\n\n .sv-modal-minimal > .sv-header {\n display: none;\n }\n\n .sv-modal-minimal > .sv-body {\n padding: 36px 32px 28px;\n }\n\n .sv-floating-close {\n position: absolute;\n top: 14px;\n right: 14px;\n width: 32px;\n height: 32px;\n display: flex;\n align-items: center;\n justify-content: center;\n background: transparent;\n border: none;\n border-radius: 6px;\n cursor: pointer;\n color: ${A};\n transition: background var(--sv-dur-fast) var(--sv-ease-standard), color var(--sv-dur-fast) var(--sv-ease-standard);\n z-index: 1;\n }\n\n .sv-floating-close:hover {\n background: ${b};\n color: ${E};\n }\n\n .sv-floating-close:focus-visible {\n outline: none;\n box-shadow: ${I};\n }\n\n /* ========================================\n APP NOT ACTIVATED VIEW\n ======================================== */\n\n .sv-not-activated-view {\n display: flex;\n flex-direction: column;\n align-items: center;\n text-align: center;\n }\n\n .sv-not-activated-eyebrow {\n display: inline-flex;\n align-items: center;\n gap: 8px;\n padding: 5px 10px;\n border-radius: 999px;\n background: ${b};\n color: ${T};\n font-size: 11px;\n font-weight: 600;\n letter-spacing: 0.04em;\n text-transform: uppercase;\n margin-bottom: 20px;\n }\n\n .sv-not-activated-mark {\n display: inline-flex;\n align-items: center;\n gap: 5px;\n color: ${E};\n font-weight: 700;\n letter-spacing: -0.01em;\n text-transform: none;\n font-size: 12px;\n }\n\n .sv-not-activated-eyebrow-divider {\n color: ${A};\n opacity: 0.6;\n }\n\n .sv-not-activated-eyebrow-label {\n color: ${T};\n }\n\n .sv-not-activated-badge {\n margin-bottom: 20px;\n }\n\n .sv-not-activated-badge-svg {\n display: block;\n filter: drop-shadow(0 8px 18px ${Ot($t.slate900,.08)});\n }\n\n .sv-not-activated-title {\n font-size: 22px;\n font-weight: 600;\n letter-spacing: -0.02em;\n line-height: 1.2;\n margin: 0 0 10px 0;\n color: ${E};\n }\n\n .sv-not-activated-message {\n font-size: 14px;\n line-height: 1.55;\n color: ${T};\n margin: 0 0 22px 0;\n max-width: 320px;\n }\n\n .sv-not-activated-owner {\n width: 100%;\n display: flex;\n flex-direction: column;\n gap: 4px;\n padding: 14px 16px;\n border: 1px solid ${w};\n border-radius: 10px;\n background: ${y};\n text-align: left;\n margin-bottom: 22px;\n }\n\n .sv-not-activated-owner-label {\n font-size: 13px;\n font-weight: 600;\n color: ${E};\n }\n\n .sv-not-activated-owner-hint {\n font-size: 12.5px;\n line-height: 1.5;\n color: ${T};\n }\n\n .sv-not-activated-actions {\n display: flex;\n flex-direction: column;\n align-items: stretch;\n gap: 10px;\n width: 100%;\n }\n\n .sv-not-activated-cta {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n gap: 8px;\n width: 100%;\n text-decoration: none;\n height: 44px;\n }\n\n .sv-not-activated-cta-icon {\n opacity: 0.85;\n }\n\n .sv-not-activated-dismiss {\n background: transparent;\n border: none;\n cursor: pointer;\n padding: 8px;\n font-size: 13px;\n font-weight: 500;\n color: ${A};\n transition: color var(--sv-dur-fast) var(--sv-ease-standard);\n align-self: center;\n }\n\n .sv-not-activated-dismiss:hover {\n color: ${E};\n }\n\n .sv-not-activated-dismiss:focus-visible {\n outline: none;\n box-shadow: ${I};\n border-radius: 6px;\n }\n\n /* ========================================\n OTP VIEW\n ======================================== */\n\n .sv-resend-container {\n text-align: center;\n margin-top: 16px;\n }\n\n /* ========================================\n PASSKEY VIEW\n ======================================== */\n\n .sv-passkey-icon {\n width: 48px;\n height: 48px;\n margin: 0 auto 12px;\n display: block;\n }\n\n .sv-passkey-description {\n font-size: 13px;\n color: ${A};\n text-align: center;\n margin: 0 0 16px 0;\n line-height: 1.4;\n }\n\n .sv-fallback-link {\n display: block;\n width: 100%;\n text-align: center;\n color: ${T};\n font-size: 13px;\n font-weight: 400;\n text-decoration: none;\n cursor: pointer;\n background: none;\n border: none;\n padding: 12px 0 0 0;\n margin-top: 8px;\n transition: color var(--sv-dur-fast) var(--sv-ease-standard);\n }\n\n .sv-fallback-link:hover {\n color: ${l};\n text-decoration: underline;\n }\n\n /* ========================================\n PASSKEY PROMPT VIEW\n ======================================== */\n\n .sv-passkey-prompt-icon {\n width: 48px;\n height: 48px;\n margin: 0 auto 12px;\n display: block;\n color: ${l};\n }\n\n .sv-passkey-prompt-benefits {\n background: ${y};\n border-radius: 8px;\n padding: 10px 14px;\n margin-bottom: 16px;\n }\n\n .sv-passkey-prompt-benefits ul {\n list-style: none;\n margin: 0;\n padding: 0;\n }\n\n .sv-passkey-prompt-benefits li {\n display: flex;\n align-items: center;\n gap: 10px;\n font-size: 13px;\n color: ${T};\n padding: 6px 0;\n }\n\n .sv-passkey-prompt-benefits li svg {\n width: 16px;\n height: 16px;\n color: ${l};\n flex-shrink: 0;\n }\n\n .sv-skip-link {\n display: block;\n width: 100%;\n text-align: center;\n color: ${A};\n font-size: 13px;\n font-weight: 400;\n text-decoration: none;\n cursor: pointer;\n background: none;\n border: none;\n padding: 12px 0 0 0;\n transition: color var(--sv-dur-fast) var(--sv-ease-standard);\n }\n\n .sv-skip-link:hover {\n color: ${T};\n text-decoration: underline;\n }\n\n /* ========================================\n SPARKLINK WAITING VIEW\n ======================================== */\n\n .sv-sparklink-icon-container {\n display: flex;\n justify-content: center;\n margin-bottom: 16px;\n }\n\n /* Bare glyph, no tinted circle container. */\n .sv-sparklink-icon {\n width: 48px;\n height: 48px;\n color: ${T};\n }\n\n .sv-sparklink-waiting {\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 12px;\n background: ${y};\n border-radius: 10px;\n padding: 14px 18px;\n margin: 16px 0;\n }\n\n .sv-spinner-small {\n width: 18px;\n height: 18px;\n border: 2px solid ${w};\n border-top-color: ${l};\n border-radius: 50%;\n animation: sv-spin 0.7s linear infinite;\n flex-shrink: 0;\n }\n\n .sv-sparklink-waiting-text {\n font-size: 13px;\n font-weight: 500;\n color: ${T};\n }\n\n .sv-sparklink-countdown {\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 6px;\n font-size: 13px;\n color: ${A};\n margin-bottom: 20px;\n }\n\n .sv-sparklink-countdown-time {\n font-family: 'IBM Plex Mono', ui-monospace, SFMono-Regular, 'SF Mono', Menlo, Monaco, 'Cascadia Mono', monospace;\n font-weight: 600;\n font-size: 14px;\n font-variant-numeric: tabular-nums;\n color: ${E};\n min-width: 40px;\n }\n\n .sv-sparklink-fallback {\n text-align: center;\n margin-top: 12px;\n padding-top: 16px;\n border-top: 1px solid ${w};\n }\n\n .sv-sparklink-fallback .sv-back-link {\n margin-bottom: 0;\n font-size: 12px;\n color: ${A};\n }\n\n .sv-sparklink-fallback .sv-back-link:hover:not(:disabled) {\n color: ${T};\n }\n\n /* SparkLink Expired State */\n .sv-sparklink-expired {\n flex-direction: column;\n gap: 12px;\n background: ${y};\n border: 1px solid ${w};\n }\n\n .sv-sparklink-expired-icon {\n display: flex;\n justify-content: center;\n }\n\n .sv-sparklink-expired-icon svg {\n width: 48px;\n height: 48px;\n }\n\n .sv-sparklink-expired-text {\n font-size: 14px;\n font-weight: 500;\n color: ${T};\n text-align: center;\n }\n\n .sv-expired-icon {\n width: 48px;\n height: 48px;\n }\n\n /* ========================================\n DIVIDER\n ======================================== */\n\n .sv-divider {\n display: flex;\n align-items: center;\n margin: 20px 0;\n }\n\n .sv-divider::before,\n .sv-divider::after {\n content: '';\n flex: 1;\n height: 1px;\n background: ${w};\n }\n\n .sv-divider-text {\n padding: 0 12px;\n font-size: 12px;\n color: ${A};\n }\n\n /* ========================================\n ACCESSIBILITY\n ======================================== */\n\n .sv-sr-only {\n position: absolute;\n width: 1px;\n height: 1px;\n padding: 0;\n margin: -1px;\n overflow: hidden;\n clip: rect(0, 0, 0, 0);\n white-space: nowrap;\n border: 0;\n }\n\n /* ========================================\n INLINE CONTAINER\n ======================================== */\n\n .sv-inline-container {\n display: flex;\n flex-direction: column;\n width: 100%;\n height: 100%;\n box-sizing: border-box;\n background: ${g};\n color: ${E};\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n border-radius: 12px;\n border: 1px solid ${w};\n }\n\n .sv-inline-header {\n border-bottom: 1px solid ${w};\n }\n\n .sv-inline-body {\n display: flex;\n flex-direction: column;\n justify-content: center;\n min-height: 200px;\n flex: 1;\n padding-left: 32px;\n padding-right: 32px;\n }\n\n /* Bare mode: the host page owns the surface and chrome, so the container\n is transparent and edge-free and the body hugs its content. */\n .sv-inline-bare {\n border: none;\n border-radius: 0;\n background: transparent;\n height: auto;\n }\n\n .sv-inline-bare > .sv-inline-body {\n min-height: 0;\n padding-left: 0;\n padding-right: 0;\n /* The host page owns the scroll and the surrounding padding in bare\n mode, so this body never scrolls internally. Keep overflow visible\n so a focused control's ring paints into the host padding instead of\n being clipped flat against this edgeless body's sides. */\n overflow: visible;\n }\n\n /* ========================================\n BRIDGE MODAL (host page, while the sign-in popup runs)\n ======================================== */\n\n .sv-bridge {\n text-align: center;\n padding: 4px 4px 6px;\n }\n\n .sv-bridge-dots {\n display: flex;\n gap: 6px;\n align-items: center;\n justify-content: center;\n margin-bottom: 20px;\n }\n\n .sv-bridge-dots span {\n width: 7px;\n height: 7px;\n border-radius: 50%;\n background: ${l};\n animation: sv-bridge-pulse 1.3s ease-in-out infinite;\n }\n\n .sv-bridge-dots span:nth-child(2) { animation-delay: 0.16s; }\n .sv-bridge-dots span:nth-child(3) { animation-delay: 0.32s; }\n\n @keyframes sv-bridge-pulse {\n 0%, 100% { opacity: 0.28; transform: translateY(0); }\n 50% { opacity: 1; transform: translateY(-3px); }\n }\n\n /* Warning shown under the logo only when the popup can't be confirmed -\n blocked, closed, or no result after a few seconds. Hidden on the happy\n path; appears with a gentle fade. */\n .sv-bridge-alert {\n display: flex;\n align-items: flex-start;\n gap: 10px;\n text-align: left;\n margin: 0 0 22px;\n padding: 11px 13px;\n border: 1px solid ${w};\n border-radius: 10px;\n background: ${y};\n font-size: 13px;\n line-height: 1.45;\n opacity: 0;\n max-height: 0;\n padding-top: 0;\n padding-bottom: 0;\n margin-bottom: 0;\n border-width: 0;\n overflow: hidden;\n transition: opacity var(--sv-dur-slow) var(--sv-ease-standard);\n }\n\n .sv-bridge-alert.sv-shown {\n opacity: 1;\n max-height: 120px;\n padding-top: 11px;\n padding-bottom: 11px;\n margin-bottom: 22px;\n border-width: 1px;\n }\n\n .sv-bridge-alert-icon {\n flex-shrink: 0;\n width: 17px;\n height: 17px;\n margin-top: 1px;\n color: ${v};\n }\n\n /* Text stacked over the action, so the message keeps the full width and\n never wraps to a lone word beside a right-aligned button. */\n .sv-bridge-alert-body {\n display: flex;\n flex-direction: column;\n align-items: flex-start;\n gap: 7px;\n flex: 1;\n min-width: 0;\n line-height: 1.35;\n }\n\n .sv-bridge-alert-text { color: ${T}; }\n\n .sv-bridge-retry {\n padding: 0;\n background: none;\n border: none;\n font-family: inherit;\n font-size: 13px;\n font-weight: 600;\n color: ${l};\n text-decoration: underline;\n text-underline-offset: 2px;\n cursor: pointer;\n }\n\n .sv-bridge-retry:hover { color: ${d}; }\n .sv-bridge-retry:focus-visible { outline: none; box-shadow: ${I}; border-radius: 4px; }\n\n @media (prefers-reduced-motion: reduce) {\n .sv-bridge-dots span { animation: none; opacity: 0.5; }\n }\n\n /* ========================================\n RESPONSIVE\n ======================================== */\n\n @media (max-width: 480px) {\n .sv-modal {\n max-width: 100%;\n max-height: 100%;\n border-radius: 0;\n }\n\n .sv-overlay {\n padding: 0;\n }\n\n .sv-body {\n padding: 24px 28px;\n }\n\n .sv-otp-digit {\n width: 40px;\n height: 48px;\n font-size: 18px;\n }\n\n .sv-error-actions {\n flex-direction: column;\n }\n }\n\n @media (max-width: 360px) {\n .sv-otp-input-group {\n gap: 6px;\n }\n\n .sv-otp-digit {\n width: 36px;\n height: 44px;\n font-size: 16px;\n }\n }\n `}const Jt=[];let Xt="";class Zt{constructor(e){var t;this.pressOnBackdrop=!1,this.open=!0,this.opener=document.activeElement instanceof HTMLElement?document.activeElement:null,this.overlay=document.createElement("div"),this.overlay.id=e.overlayId,this.overlay.className=`${e.classPrefix}-overlay`,this.overlay.classList.toggle(`${e.classPrefix}-blur`,e.backdropBlur),this.overlay.setAttribute("role","dialog"),this.overlay.setAttribute("aria-modal","true"),this.overlay.setAttribute("aria-labelledby",e.titleId),this.modal=document.createElement("div"),this.modal.id=e.modalId,this.modal.className=`${e.classPrefix}-modal`,this.modal.tabIndex=-1,this.overlay.appendChild(this.modal),this.onOverlayPointerDown=e=>{this.pressOnBackdrop=e.target===this.overlay},this.onOverlayClick=t=>{const n=t.target===this.overlay&&this.pressOnBackdrop;this.pressOnBackdrop=!1,n&&e.onDismiss()},this.onKeydown=t=>{if(this.ownsKeyboard())if("Escape"===t.key){if(function(e){return e.isComposing||229===e.keyCode}(t)||t.defaultPrevented)return;t.preventDefault(),e.onDismiss()}else"Tab"!==t.key||t.defaultPrevented||this.keepFocusInside(t)},this.overlay.addEventListener("pointerdown",this.onOverlayPointerDown),this.overlay.addEventListener("click",this.onOverlayClick),document.addEventListener("keydown",this.onKeydown),document.body.appendChild(this.overlay),t=this,0===Jt.length&&(Xt=document.body.style.overflow,document.body.style.overflow="hidden"),Jt.push(t),this.modal.focus({preventScroll:!0})}destroy(){var e;this.open&&(this.open=!1,document.removeEventListener("keydown",this.onKeydown),this.overlay.removeEventListener("pointerdown",this.onOverlayPointerDown),this.overlay.removeEventListener("click",this.onOverlayClick),this.overlay.remove(),e=this,Jt.splice(Jt.indexOf(e),1),0===Jt.length&&(document.body.style.overflow=Xt),this.opener?.isConnected&&this.opener.focus({preventScroll:!0}))}ownsKeyboard(){if(function(){for(let e=Jt.length-1;e>=0;e-=1)if(Jt[e].overlay.isConnected)return Jt[e]}()!==this)return!1;const e=document.activeElement?.closest('[aria-modal="true"], [role="dialog"], [role="alertdialog"], dialog[open]');return!e||Jt.some(t=>t.overlay.contains(e))}keepFocusInside(e){const t=Array.from(this.modal.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]):not([type=hidden]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter(e=>e.getClientRects().length>0),n=document.activeElement;if(0===t.length)return e.preventDefault(),void this.modal.focus({preventScroll:!0});const i=t[0],s=t[t.length-1];if(!n||!this.modal.contains(n))return e.preventDefault(),void i.focus();const r=n===i||0!==(i.compareDocumentPosition(n)&Node.DOCUMENT_POSITION_PRECEDING),o=n===s||0!==(s.compareDocumentPosition(n)&Node.DOCUMENT_POSITION_FOLLOWING)&&!s.contains(n);e.shiftKey&&r?(e.preventDefault(),s.focus()):!e.shiftKey&&o&&(e.preventDefault(),i.focus())}}function Qt(e){const t=document.createElement("div");t.className=`${e}-footer`;const n=document.createElement("span");n.className=`${e}-footer-text`,n.appendChild(document.createTextNode("Secured by "));const i=document.createElement("a");return i.href="https://sparkvault.com",i.target="_blank",i.rel="noopener noreferrer",i.className=`${e}-footer-link`,i.style.color="inherit",i.style.textDecoration="none",i.textContent="SparkVault",n.appendChild(i),t.appendChild(n),t}const en="sv-modal-title",tn={companyName:"",logoLight:null,logoDark:null};class nn{constructor(){this.shell=null,this.body=null,this.header=null,this.onCloseCallback=null,this.effectiveTheme="light",this.floatingCloseBtn=null}createLoading(e,t){this.shell||(this.onCloseCallback=t,this.effectiveTheme=Gt(tn),qt({branding:tn,backdropBlur:e.backdropBlur}),this.shell=new Zt({overlayId:"sparkvault-identity-overlay",modalId:"sparkvault-identity-modal",classPrefix:"sv",titleId:en,backdropBlur:!1!==e.backdropBlur,onDismiss:()=>this.handleClose()}),this.header=this.createHeader(tn),this.body=document.createElement("div"),this.body.className="sv-body",this.shell.modal.append(this.header,this.body,Qt("sv")))}updateBranding(e){if(!this.shell||!this.header)return;this.effectiveTheme=Gt(e),Kt(e);const t=this.createHeader(e);this.header.replaceWith(t),this.header=t}setMinimalChrome(e){if(!this.shell)return;const{modal:t}=this.shell;t.classList.toggle("sv-modal-minimal",e),e&&!this.floatingCloseBtn?(this.floatingCloseBtn=sn("sv-floating-close",()=>this.handleClose()),t.appendChild(this.floatingCloseBtn)):!e&&this.floatingCloseBtn&&(this.floatingCloseBtn.remove(),this.floatingCloseBtn=null)}createHeader(e){const t=document.createElement("div");t.className="sv-header";const n=document.createElement("div");n.className="sv-header-title";const i=(s="dark"===this.effectiveTheme,r=e.logoLight,o=e.logoDark,s?o||r:r||o);var s,r,o;if(i){const t=document.createElement("img");t.className="sv-logo",t.src=i,t.alt=e.companyName,n.appendChild(t);const s=document.createElement("span");s.className="sv-sr-only",s.id=en,s.textContent=e.companyName,n.appendChild(s)}else{const t=document.createElement("h2");t.className="sv-company-name",t.id=en,t.textContent=e.companyName,n.appendChild(t)}return t.append(n,sn("sv-close-btn",()=>this.handleClose())),t}handleClose(){this.onCloseCallback?.()}getBody(){return this.body}isOpen(){return null!==this.shell}destroy(){this.shell?.destroy(),this.shell=null,this.header=null,this.body=null,this.floatingCloseBtn=null,this.onCloseCallback=null}}function sn(e,t){const n=document.createElement("button");return n.className=e,n.type="button",n.setAttribute("aria-label","Close"),n.appendChild(function(){const e=it("0 0 20 20",20,20);return e.appendChild(st("M15 5L5 15M5 5L15 15",{stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round"})),e}()),n.addEventListener("click",t),n}const rn="http://www.w3.org/2000/svg";function on(e,t,n){const i=document.createElement(e);return t&&(i.className=t),null!=n&&(i.textContent=n),i}class an{constructor(e,t,n,i){this.config=e,this.api=t,this.options=n,this.callbacks=i,this.popupLauncher=new Me,this.modal=null,this.alertEl=null,this.popupWindow=null,this.popupReady=!1,this.openTimer=null,this.settled=!1,this.generation=0,this.trustedOrigin=new URL(this.config.identityBaseUrl).origin}start(){this.showBridge(),this.openPopup(),this.loadBranding()}close(){this.clearOpenTimer(),this.closePopup(),this.modal?.destroy(),this.modal=null,this.alertEl=null}signinReferenceDecided(){this.popupReady&&this.postSigninReference()}openPopup(){const e=++this.generation;this.popupReady=!1,this.popupLauncher.openPopup({url:me(this.config,this.options,{kind:"popup"}),windowName:"sparkvault-login",resultType:"sparkvault-login-result",readyType:"sparkvault-login-ready",trustedOrigin:this.trustedOrigin,onOpen:t=>{e===this.generation&&(this.popupWindow=t,this.scheduleOpenWarning())},onReady:()=>{e===this.generation&&(this.clearOpenTimer(),this.popupReady=!0,this.postSigninReference())},requestType:Z.retryMessage,onRequest:()=>{e===this.generation&&this.answerSigninReferenceRetry()}}).then(t=>{e===this.generation&&this.handleResult(t)}).catch(t=>{e===this.generation&&this.handleError(t)}),this.callbacks.drawSigninReference()}answerSigninReferenceRetry(){const e=this.callbacks.signinReference();null!==e?void 0!==e&&this.postSigninReference():this.callbacks.drawSigninReference()}postSigninReference(){const e=this.callbacks.signinReference();void 0!==e&&this.popupWindow&&this.popupWindow.postMessage({type:Z.message,[Z.param]:e},this.trustedOrigin)}handleResult(e){if(!this.settled){if(e.success&&e.data){const t={token:e.data.token||"",identity:e.data.identity||"",identityType:e.data.identity_type||"email",svid:e.data.svid,sessionId:e.data.session_id,refreshToken:e.data.refresh_token,redirect:e.data.redirect};return this.finish(),void this.callbacks.onSuccess(t)}"cancelled"!==e.error?(this.finish(),this.callbacks.onError(new p(e.message||e.error||"Verification failed",e.errorCode||e.error||"verification_failed"))):this.finishCancel()}}handleError(e){if(!this.settled)if(e instanceof b&&this.callbacks.onPopupSevered)this.callbacks.onPopupSevered().then(e=>{this.settled||e||(this.callbacks.onPopupClosedUnresolved?.(),this.showAlert())}).catch(()=>{this.settled||(this.callbacks.onPopupClosedUnresolved?.(),this.showAlert())});else{if(e instanceof y||e instanceof v||e instanceof b)return this.callbacks.onPopupClosedUnresolved?.(),void this.showAlert();this.finish(),this.callbacks.onError(e instanceof Error?e:new Error(String(e)))}}showBridge(){if(this.settled)return;this.modal||(this.modal=new nn,this.modal.createLoading({backdropBlur:this.options.backdropBlur},()=>this.abort()));const e=this.modal.getBody();if(!e)return;Ge(e);const t=on("div","sv-bridge"),n=on("div","sv-bridge-alert");n.appendChild(function(){const e=document.createElementNS(rn,"svg");e.setAttribute("viewBox","0 0 20 20"),e.setAttribute("fill","none"),e.classList.add("sv-bridge-alert-icon");const t=(e,t)=>{const n=document.createElementNS(rn,"path");n.setAttribute("d",e);for(const[e,i]of Object.entries(t))n.setAttribute(e,i);return n};e.appendChild(t("M10 2.75 18.25 17.25H1.75L10 2.75Z",{stroke:"currentColor","stroke-width":"1.5","stroke-linejoin":"round"})),e.appendChild(t("M10 8.25v3.25",{stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round"}));const n=document.createElementNS(rn,"circle");return n.setAttribute("cx","10"),n.setAttribute("cy","14.5"),n.setAttribute("r","0.95"),n.setAttribute("fill","currentColor"),e.appendChild(n),e}());const i=on("div","sv-bridge-alert-body");i.appendChild(on("span","sv-bridge-alert-text","The sign-in window may not have opened."));const s=on("button","sv-bridge-retry","Try again");s.type="button",s.addEventListener("click",()=>this.retry()),i.appendChild(s),n.appendChild(i),this.alertEl=n;const r=on("div","sv-bridge-dots");r.append(on("span"),on("span"),on("span")),t.append(n,r,on("h3","sv-title","Continue in the secure window"),on("p","sv-subtitle","Finish signing in there. This page updates on its own.")),e.appendChild(t)}showAlert(){this.clearOpenTimer(),this.alertEl?.classList.add("sv-shown")}hideAlert(){this.alertEl?.classList.remove("sv-shown")}scheduleOpenWarning(){this.clearOpenTimer(),this.openTimer=setTimeout(()=>this.showAlert(),8e3)}clearOpenTimer(){this.openTimer&&(clearTimeout(this.openTimer),this.openTimer=null)}retry(){this.hideAlert(),this.closePopup(),this.openPopup()}loadBranding(){this.api.getConfig().then(e=>{e.branding&&this.modal&&this.modal.updateBranding(e.branding)}).catch(()=>{})}closePopup(){if(this.popupWindow&&!this.popupWindow.closed)try{this.popupWindow.close()}catch{}this.popupWindow=null}abort(){this.finishCancel()}finish(){this.settled=!0,this.close()}finishCancel(){this.settled||(this.settled=!0,this.close(),this.callbacks.onCancel())}}class ln{constructor(e,t){this.container=document.createElement("div"),this.container.className=t.containerClassName,this.body=document.createElement("div"),this.body.className=t.bodyClassName,this.container.appendChild(this.body),t.footer&&this.container.appendChild(t.footer),e.textContent="",e.appendChild(this.container)}destroy(){this.container.remove()}}class dn{constructor(e,t={}){this.shell=null,this.targetElement=e,this.bare=!0===t.bare}createLoading(e,t){this.shell||(qt({branding:{companyName:"",logoLight:null,logoDark:null},backdropBlur:!1}),this.shell=new ln(this.targetElement,{containerClassName:this.bare?"sv-inline-container sv-inline-bare":"sv-inline-container",bodyClassName:"sv-body sv-inline-body",footer:this.bare?null:Qt("sv")}))}updateBranding(e){this.shell&&Kt(e)}setMinimalChrome(e){}getBody(){return this.shell?.body??null}isOpen(){return null!==this.shell}destroy(){this.shell?.destroy(),this.shell=null}}function cn(e,t){let n=null,i=!1;const s=new Map,r=e=>{s.has(e)||(e.addEventListener("click",t),s.set(e,()=>e.removeEventListener("click",t)))};var o;return o=()=>{i||(document.querySelectorAll(e).forEach(r),n=new MutationObserver(t=>{t.forEach(t=>{t.addedNodes.forEach(t=>{t instanceof Element&&(t.matches(e)&&r(t),t.querySelectorAll(e).forEach(r))})})}),function(e){if(document.body)e();else{const t=()=>{document.body?e():window.requestAnimationFrame(t)};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",t,{once:!0}):window.requestAnimationFrame(t)}}(()=>{n?.observe(document.body,{childList:!0,subtree:!0})}))},"loading"===document.readyState?document.addEventListener("DOMContentLoaded",o,{once:!0}):o(),()=>{i=!0,n?.disconnect(),s.forEach(e=>e()),s.clear()}}const hn="sv_signin_pending";function un(){let e,t=null;try{t=sessionStorage.getItem(hn)}catch{return null}if(!t)return null;try{e=JSON.parse(t)}catch{return null}if("object"!=typeof e||null===e)return null;const n=e;if("number"!=typeof n.at||!Number.isFinite(n.at))return null;const{ref:i}=n;if(void 0!==i&&!Q(i))return null;const s=n[ee.param];return ne(s).ok?{at:n.at,hint:"string"==typeof n.hint&&n.hint?n.hint:null,ref:"string"==typeof i?i:null,identityTypes:"string"==typeof s?s:null}:null}function pn(e){return null!==e&&Date.now()-e.at<X.pendingTtlMs}function mn(){try{sessionStorage.removeItem(hn)}catch{}}class fn{constructor(e,t){this.hint=e,this.identityTypes=t,this.at=0,this.ended=!1,this.opens=0,this.current=void 0,this.decided=Promise.resolve()}get reference(){return this.current}get live(){return!this.ended}open(e){if(this.ended)return Promise.resolve(!1);const t=++this.opens;this.at=Date.now(),this.current=void 0,this.write(null)||mn();const n=function(e){return new Promise(t=>{const n=setTimeout(()=>t(null),Z.drawDeadlineMs);e.then(e=>{clearTimeout(n),t(e)},()=>{clearTimeout(n),t(null)})})}(e()).then(e=>!this.ended&&t===this.opens&&(this.current=null!==e&&this.write(e)?e:null,!0));return this.decided=n,n}retire(){this.ended||(this.opens+=1,this.current=null,mn())}end(){this.retire(),this.ended=!0}referenceWithin(e){return void 0!==this.current?Promise.resolve(this.current):new Promise(t=>{const n=setTimeout(()=>t(this.current??null),e);this.decided.then(()=>{clearTimeout(n),t(this.current??null)})})}write(e){const t={at:this.at,hint:this.hint,...e?{ref:e}:{},...this.identityTypes?{[ee.param]:this.identityTypes}:{}};try{sessionStorage.setItem(hn,JSON.stringify(t))}catch{return!1}return!0}}const vn=["home","identity","security","sessions","sites"],gn=["EdDSA","RS256"];function yn(e,t){const n=j(e);if(null===n)throw new m(t);try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n))}catch{throw new m(t)}}class bn{constructor(e){this.renderer=null,this.launcher=null,this.pendingSignIn=null,this.config=e,this.api=new fe(e),e.preloadConfig&&this.api.preloadConfig(),function(e){if("undefined"==typeof document||"undefined"==typeof window||!document.head)return;let t;try{t=new URL(e).origin}catch{return}if(t!==window.location.origin)for(const e of[!1,!0]){const n=`link[rel="preconnect"][href="${t}"]${e?"[crossorigin]":":not([crossorigin])"}`;if(document.head.querySelector(n))continue;const i=document.createElement("link");i.rel="preconnect",i.href=t,e&&(i.crossOrigin="anonymous"),document.head.appendChild(i)}}(e.identityBaseUrl)}portalUrl(e={}){const t=e.section??"home";if(!vn.includes(t))throw new m(`Unknown portal section: ${t}`,{field:"section",received:t});let n;if("home"===t)n="/";else if("sites"===t){const t=(e.site??this.config.accountId).trim();n=t?`/sites/${encodeURIComponent(t)}`:"/sites"}else n=`/${t}`;return new URL(n,this.config.portalBaseUrl).toString()}async signInWithFedcm(e={}){const t=he(e.identityTypes);if(!bn.isFedcmAvailable())return null;if(!this.config.clientId)throw new m("clientId must be set in the SDK config to use FedCM sign-in",{field:"clientId"});const n=e.nonce??(await this.api.drawAuthorizationValues()).nonce,i={identity:{providers:[{configURL:`${this.config.identityBaseUrl}/${this.config.accountId}/fedcm/config.json`,clientId:this.config.clientId,nonce:n,...t?{params:ue(t)}:{}}]},...e.mediation?{mediation:e.mediation}:{}};let s;try{const e=navigator.credentials.get.bind(navigator.credentials);s=await e(i)}catch(e){throw function(e){if("object"!=typeof e||null===e)return null;const{name:t,error:n}=e;return"IdentityCredentialError"!==t?null:new g("string"==typeof n?n:"")}(e)??new v(e instanceof Error?e.message:void 0)}const r=s?.token;if(!r)throw new m("FedCM did not return a token");const o=this.decodeToken(r);return{token:r,identity:o.identity,identityType:o.identity_type,svid:o.svid,sessionId:o.session_id}}static isFedcmAvailable(){return"undefined"!=typeof window&&"IdentityCredential"in window&&"undefined"!=typeof navigator&&!!navigator.credentials&&"function"==typeof navigator.credentials.get}async signIn(e={}){let t;try{t=he(e.identityTypes)}catch(t){const n=t instanceof Error?t:new Error(String(t));throw e.onError?.(n),n}return this.runFlow(e,{ok:!0,types:t})}async runFlow(e,t,n=null){this.closeLauncher(),this.renderer&&this.renderer.close(),this.api.resetSession();const i={...e,backdropBlur:e.backdropBlur??this.config.backdropBlur},s=!!e.target,r="local"===e.renderMode||s;let o,a;const l=new Promise((e,t)=>{o=e,a=t}),d={onSuccess:t=>{e.onSuccess?.(t),o(t)},onError:t=>{e.onError?.(t),a(t)},onCancel:()=>{const t=new v;e.onCancel?.(),a(t)}},c=e=>{this.renderer=new jt(e,this.api,i,d,n,t),this.renderer.start().catch(e=>{this.renderer?.showStartupError(e)})};if(!r){if(await this.preloadedConfigPermanentlyFailed())return c(new nn),l;if("redirect"===i.flow){try{await this.startRedirectFlow(i,null)||d.onError(new m("Sign-in requires browser session storage. Enable site data for this site and try again."))}catch(e){d.onError(e instanceof Error?e:new Error(String(e)))}return l}const e=new fn(i.email||i.phone||null,i.identityTypes?te(i.identityTypes):null);this.pendingSignIn=e;const t=new an(this.config,this.api,i,{onSuccess:t=>{e.end(),d.onSuccess(t)},onError:t=>{e.end(),d.onError(t)},onCancel:()=>{e.end(),d.onCancel()},onPopupClosedUnresolved:()=>e.retire(),drawSigninReference:()=>{e.open(()=>this.api.drawSigninReference()).then(e=>{e&&t.signinReferenceDecided()})},onPopupSevered:async()=>{const t=await e.referenceWithin(Z.redirectWaitMs);return null===t&&e.retire(),this.startRedirectFlow(i,{signIn:e,signinRef:t})},signinReference:()=>e.reference});return this.launcher=t,t.start(),l}return c(s?this.createInlineContainer(e.target,"bare"===e.chrome):new nn),l}attach(e,t={}){return cn(e,async e=>{e.preventDefault();try{await this.signIn({email:t.email,phone:t.phone,authContext:t.authContext,prompt:t.prompt,method:t.method,identityTypes:t.identityTypes,onSuccess:t.onSuccess,onError:t.onError,onCancel:t.onCancel})}catch{}})}decodeToken(e){if(!e||"string"!=typeof e)throw new m("Token is required");const t=e.split(".");if(3!==t.length)throw new m("Invalid token format");const[n,i]=t,s=yn(n,"Invalid token header");if("object"!=typeof s||null===s)throw new m("Invalid token header");const r=s.alg;if("string"!=typeof r||!gn.includes(r))throw new m("Unsupported token algorithm");const o=yn(i,"Invalid token payload");if(!function(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.iss&&"string"==typeof t.sub&&"string"==typeof t.aud&&"number"==typeof t.exp&&"number"==typeof t.iat&&"string"==typeof t.identity&&"string"==typeof t.identity_type&&"number"==typeof t.verified_at&&"string"==typeof t.method}(o))throw new m("Invalid token payload structure");const a=Math.floor(Date.now()/1e3);if(o.exp<a)throw new m("Token has expired");const l=`${this.config.identityBaseUrl}/${this.config.accountId}`;if(o.iss!==l)throw new m("Invalid token issuer");if(o.aud!==this.config.accountId)throw new m("Invalid token audience");return o}async handleRedirectResult(e={}){if("undefined"==typeof window)return null;const t=new URLSearchParams((window.location.hash||"").slice(1));if(t.get("sv_code")||t.get("sv_error"))return this.consumeHandoffFragment(t,e);t.get("sso")&&(this.clearUrlFragment(),this.clearOneShotAuthState());const n=this.consumeSignInPending();return n&&await this.startRecoveryBounce(n),null}async consumeHandoffFragment(e,t){const n=e.get("sv_code"),i=e.get("sv_error");mn();let s=null,r=null;try{s=sessionStorage.getItem("sv_oauth_state"),r=sessionStorage.getItem("sv_pkce_verifier"),this.clearOneShotAuthState()}catch{}this.clearUrlFragment();try{if(i){if("cancelled"===i)return t.onCancel?.(),null;throw new p("Sign-in could not be completed. Please try again.","REDIRECT_SIGNIN_FAILED")}if(s&&e.get("state")!==s)throw new m("Invalid OAuth state");if(!r)throw new m("Sign-in session was lost. Please sign in again.");const o=await this.api.redeemHandoffCode(n,r),a={token:o.token,identity:o.identity,identityType:o.identity_type,svid:o.svid??void 0,sessionId:o.session_id??void 0,refreshToken:o.refresh_token??void 0};return t.onSuccess?.(a),a}catch(e){const n=e instanceof Error?e:new Error(String(e));throw t.onError?.(n),n}}async startRecoveryBounce(e){const t=await this.armHandoffReturn();if(!t)return;const n=new URL(`${this.config.identityBaseUrl}/${this.config.accountId}/sso`);e.hint&&n.searchParams.set("login_hint",e.hint),e.ref&&n.searchParams.set(Z.param,e.ref),e.identityTypes&&n.searchParams.set(ee.param,e.identityTypes),n.searchParams.set("redirect_uri",t.redirectUri),n.searchParams.set("state",t.state),n.searchParams.set("code_challenge",t.codeChallenge),window.location.assign(n.toString())}async startRedirectFlow(e,t){const n=t?.signinRef??null,i=e.authContext,s=i?.authRequestId||i?.simpleMode?.sessionId?void 0:await this.armHandoffReturn();return null!==s&&(!(t&&!t.signIn.live)&&(null===n&&mn(),window.location.assign(me(this.config,e,{kind:"redirect",signinRef:n,handoff:s})),!0))}async armHandoffReturn(){const{state:e,codeVerifier:t}=await this.api.drawAuthorizationValues();let n;try{n=await async function(e){const t=await crypto.subtle.digest("SHA-256",(new TextEncoder).encode(e));return U(new Uint8Array(t))}(t)}catch{return null}try{sessionStorage.setItem("sv_oauth_state",e),sessionStorage.setItem("sv_pkce_verifier",t)}catch{return null}return{redirectUri:pe(),state:e,codeChallenge:n}}consumeSignInPending(){const e=un();return mn(),pn(e)?e:null}closeLauncher(){this.launcher?.close(),this.launcher=null,this.pendingSignIn?.end(),this.pendingSignIn=null}clearUrlFragment(){"function"==typeof window.history?.replaceState&&window.history.replaceState(window.history.state,document.title,`${window.location.pathname}${window.location.search}`)}clearOneShotAuthState(){try{sessionStorage.removeItem("sv_oauth_state"),sessionStorage.removeItem("sv_pkce_verifier")}catch{}}async consumeRedirectResult(){if("undefined"==typeof window||!window.location.hash)return null;const e=new URLSearchParams(window.location.hash.slice(1)),t=e.get(Y.token);if(!t)return null;try{let n=null;try{n=sessionStorage.getItem("sv_oauth_state")}catch{}if(!n||e.get(Y.state)!==n)throw new m("Invalid OAuth state");const i=this.decodeToken(t);return{token:t,identity:i.identity,identityType:i.identity_type,svid:i.svid,sessionId:i.session_id}}finally{this.clearUrlFragment();try{sessionStorage.removeItem("sv_oauth_state")}catch{}$e(this.config.accountId)}}consumeFederationReturn(){if("undefined"==typeof window||!window.location.hash)return null;const e=new URLSearchParams(window.location.hash.slice(1)),t=function(e){const t=e.get("error");return"interaction_required"===t&&"federation"===e.get("method")?"interaction_required":"federation_failed"===t?"failed":null}(e);if(!t)return null;let n=null;try{n=sessionStorage.getItem("sv_oauth_state"),sessionStorage.removeItem("sv_oauth_state")}catch{}return this.clearUrlFragment(),n&&e.get(Y.state)===n?t:null}close(){this.closeLauncher(),this.renderer&&(this.renderer.close(),this.renderer=null)}async preloadedConfigPermanentlyFailed(){if(!this.api.isConfigPreloaded())return!1;const e=Symbol("pending");try{return await Promise.race([this.api.getConfig(),new Promise(t=>setTimeout(()=>t(e),50))]),!1}catch(e){return e instanceof ke&&("ORIGIN_NOT_ALLOWED"===e.code||"product_not_configured"===e.code)}}createInlineContainer(e,t=!1){return new dn(function(e){if("string"==typeof e){const t=document.querySelector(e);if(!(t instanceof HTMLElement))throw new m(`Target selector "${e}" did not match any element`);return t}if(e instanceof HTMLElement)return e;throw new m("Target must be a CSS selector string or HTMLElement")}(e),{bare:t})}async render(e){const t=await this.consumeRedirectResult();if(t)return e.onSuccess?.(t),t;const{identityTypes:n,...i}=e;return this.runFlow(i,ne(n),this.consumeFederationReturn())}}e.IdentityModule=bn,e.IdentityProviderError=g,e.PopupBlockedError=y,e.PopupSeveredError=b,e.SparkVaultError=p,e.TimeoutError=f,e.UserCancelledError=v,e.ValidationError=m,e.init=function(e){return P(e),new bn(function(e){return{accountId:e.accountId,timeout:e.timeout??3e4,apiBaseUrl:B(e.apiBaseUrl??"https://api.sparkvault.com"),identityBaseUrl:_(e.identityBaseUrl??"https://auth.sparkvault.com"),portalBaseUrl:_(e.portalBaseUrl??R),accessToken:e.accessToken,getAccessToken:e.getAccessToken,onVaultSessionTiming:e.onVaultSessionTiming,apiKey:e.apiKey,clientId:e.clientId,preloadConfig:e.preloadConfig??"undefined"!=typeof window,backdropBlur:!1!==e.backdropBlur,allowedDownloadHostPatterns:e.allowedDownloadHostPatterns??[...I]}}(e))},e.isRecoveryPending=function(){return"undefined"!=typeof window&&(!!/[#&](sv_code|sv_error|sso)=/.test(window.location.hash||"")||pn(un()))},e.version="19.1.1"});
|
|
2
2
|
//# sourceMappingURL=sparkvault-identity.js.map
|