@sparkvault/sdk-js 13.0.6 → 13.0.7

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.
@@ -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).SparkVault={})}(this,function(e){"use strict";const t=/^tus_[0-9a-f]{32}$/;const n=Object.freeze({UPLOAD_CONTRACT_MISMATCH:"UPLOAD_CONTRACT_MISMATCH",UPLOAD_PROTOCOL_RETIRED:"UPLOAD_PROTOCOL_RETIRED",UPLOAD_SUPERSEDED:"UPLOAD_SUPERSEDED",UPLOAD_POOL_FULL:"UPLOAD_POOL_FULL"}),i=Object.freeze([n.UPLOAD_POOL_FULL,n.UPLOAD_SUPERSEDED]),s=Object.freeze({status:"revoked",reasons:Object.freeze({UPLOAD_SUPERSEDED:n.UPLOAD_SUPERSEDED,INGOT_DELETED:"INGOT_DELETED"})});Object.values(s.reasons);const o="VAULT_DELETION_SCHEDULED",r="upload_received_publishing",a=Object.freeze({OK:"ok",RETRY:"retry",RESYNC:"resync",DEFERRED:"deferred",GONE:"gone",REFUSED:"refused"}),l=new Set([a.RETRY,a.RESYNC]),d=new Set([404,410,412]),c=/^[A-Z][A-Z0-9_]{0,63}$/;function u({status:e,headers:t=null,details:n=null,receipt:i=!1,now:s=Date.now()}){if(!Number.isSafeInteger(e)||e<0)throw new TypeError(`A transfer answer's status is a whole number (0 for no answer), not ${e}`);if(null!==t&&"function"!=typeof t)throw new TypeError("A transfer answer's headers are read through a function from a header name to its value");if("boolean"!=typeof i)throw new TypeError(`Whether a transfer request was the receipt is a boolean, not ${i}`);if(0===e)return{verdict:a.RETRY,retryAfterMs:null,offset:null,coreCode:null};const o=e=>null===t?null:t(e),r=m(o("Upload-Offset")),l=function(e,t){return d.has(e)||409===e&&null===t}(e,r)?function(e){return e&&"object"==typeof e?p(e.coreCode):null}(n)??p(o("X-Upload-Refusal")):null,c=function(e,t){const n=m(e);if(null!==n){const e=1e3*n;return Number.isSafeInteger(e)?e:null}const i="string"==typeof e?function(e,t){let n=b.exec(e);if(n){const[,e,t,i,s,o,r]=n;return x(Number(i),t,Number(e),s,o,r)}if(n=w.exec(e),n){const[,e,i,s,o,r,a]=n;return x(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),o,r,a)}if(n=k.exec(e),n){const[,e,t,i,s,o,r]=n;return x(Number(r),e,Number(t.trim()),i,s,o)}return null}(e.trim(),t):null;return null===i?null:Math.max(0,i-t)}(o("Retry-After"),s);return{verdict:h(e,{offset:r,coreCode:l,deferral:i&&null!==c}),retryAfterMs:c,offset:r,coreCode:l}}function h(e,{offset:t,coreCode:n,deferral:s}){return e>=200&&e<300?a.OK:409===e?null!==t?a.RESYNC:null===n?a.RETRY:a.REFUSED:null!==n?i.includes(n)?a.REFUSED:a.GONE:404===e||410===e?a.GONE:s&&503===e?a.DEFERRED:425===e||function(e){return 408===e||429===e||e>=500}(e)?a.RETRY:a.REFUSED}function p(e){if("string"!=typeof e)return null;const t=e.trim();return c.test(t)?t:null}function m(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}const f=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],v="(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)",g=`(${f.join("|")})`,y="(\\d{2}):(\\d{2}):(\\d{2})",b=new RegExp(`^${v}, (\\d{2}) ${g} (\\d{4}) ${y} GMT$`),w=new RegExp(`^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\\d{2})-${g}-(\\d{2}) ${y} GMT$`),k=new RegExp(`^${v} ${g} ( \\d|\\d{2}) ${y} (\\d{4})$`);function x(e,t,n,i,s,o){const r=f.indexOf(t),[a,l,d]=[Number(i),Number(s),Number(o)];if(a>23||l>59||d>60)return null;const c=new Date(0);return c.setUTCFullYear(e,r,n),c.getUTCFullYear()!==e||c.getUTCMonth()!==r||c.getUTCDate()!==n?null:c.getTime()+1e3*(60*(60*a+l)+d)}let C=0;function S(e){if("string"!=typeof e||0===e.length)throw new TypeError("A transfer jitter key needs the scope its transfer runs in");return C+=1,`${e}#${Date.now()}-${C}`}function E({attempt:e,retryAfterMs:t=null,baseMs:n=1e3,capMs:i=32e3,jitterKey:s}){if(!Number.isSafeInteger(e)||e<1)throw new TypeError(`A retry's attempt is a whole number from 1, not ${e}`);if("string"!=typeof s||0===s.length)throw new TypeError("A retry delay needs the key its transfer spreads by");if(!_(n)||0===n||!_(i)||i<n)throw new TypeError("A retry backs off from a positive base up to a cap no smaller");if(null!==t&&!_(t))throw new TypeError(`A Retry-After floor is a non-negative number of ms, not ${t}`);const o=Math.min(i,n*2**(e-1)),r=Math.floor(function(e){if("string"!=typeof e)throw new TypeError("fnv1a32 hashes a string, not "+typeof e);let t=2166136261;const n=e=>{t=Math.imul(t^e,16777619)>>>0};for(const t of e){let e=t.codePointAt(0);e>=55296&&e<=57343&&(e=65533),e<128?n(e):e<2048?(n(192|e>>6),n(128|63&e)):e<65536?(n(224|e>>12),n(128|e>>6&63),n(128|63&e)):(n(240|e>>18),n(128|e>>12&63),n(128|e>>6&63),n(128|63&e))}return t}(`${s}|${e}`)/2**32*1e3);return Math.max(o+r,t??0)}function _(e){return Number.isFinite(e)&&e>=0}function T({idleLimitMs:e=6e5,maxConsecutiveFailures:t=8,now:n=()=>Date.now()}={}){if(!_(e)||0===e)throw new TypeError(`A transfer's idle limit is a positive number of ms, not ${e}`);if(!Number.isSafeInteger(t)||t<1)throw new TypeError(`A transfer's failure limit is a whole number from 1, not ${t}`);if("function"!=typeof n)throw new TypeError("A transfer budget reads time from a clock function");let i=0,s=0,o=n();const r=()=>n()-o,a=t=>{if(null!==t&&!_(t))throw new TypeError(`A Retry-After floor is a non-negative number of ms, not ${t}`);return r()+(t??0)<e};return Object.freeze({progressed(){i=0,s=0,o=n()},alive(){o=n()},failed(e,n=null){if(!l.has(e))throw new TypeError("A transfer budget records retryable answers only");const s=a(n);return i+=1,s&&i<t},deferred(e=null){const t=a(e);return s+=1,t},get consecutiveFailures(){return i},get attempt(){return i+s},get msSinceProgress(){return r()}})}const A=Object.freeze({INVALID:"invalid",BEYOND_TOTAL:"beyond_total",MISALIGNED:"misaligned"});class I extends Error{constructor(e,t,n,i,s=null,o){super(e),this.name="SparkVaultError",this.code=t,this.statusCode=n,this.details=i,this.retryAfterMs=s,this.serviceCode=o,Object.setPrototypeOf(this,I.prototype)}}class $ extends I{constructor(e,t,n=null,i){super(e,"authentication_error",401,t,n,i),this.name="AuthenticationError",Object.setPrototypeOf(this,$.prototype)}}class L extends I{constructor(e,t,n=null,i){super(e,"UNAUTHORIZED",401,t,n,i),this.name="UnauthorizedError",Object.setPrototypeOf(this,L.prototype)}}class B extends I{constructor(e,t,n=null,i){super(e,"authorization_error",403,t,n,i),this.name="AuthorizationError",Object.setPrototypeOf(this,B.prototype)}}class M extends I{constructor(e,t,n=null,i){super(e,"validation_error",400,t,n,i),this.name="ValidationError",Object.setPrototypeOf(this,M.prototype)}}class P extends I{constructor(e,t,n=null,i){super(e,"PLAN_REQUIRED",402,t,n,i),this.name="PlanRequiredError",Object.setPrototypeOf(this,P.prototype)}}class R extends I{constructor(e,t,n=null,i){super(e,"QUOTA_EXCEEDED",402,t,n,i),this.name="QuotaExceededError";const s=t?.resource;this.resource="storage"===s||"bandwidth"===s?s:void 0,Object.setPrototypeOf(this,R.prototype)}}class N extends I{constructor(e,t,n=null,i){super(e,"NOTIFY_SUBSCRIPTION_REQUIRED",403,t,n,i),this.name="NotifySubscriptionRequiredError",Object.setPrototypeOf(this,N.prototype)}}class O extends I{constructor(e,t){super(e,"network_error",void 0,t),this.name="NetworkError",Object.setPrototypeOf(this,O.prototype)}}class z extends I{constructor(e="Request timed out"){super(e,"timeout_error"),this.name="TimeoutError",Object.setPrototypeOf(this,z.prototype)}}class D extends I{constructor(e="User cancelled the operation"){super(e,"user_cancelled"),this.name="UserCancelledError",Object.setPrototypeOf(this,D.prototype)}}class U extends I{constructor(e){super("The identity provider could not complete the sign-in.",e||"identity_provider_error"),this.name="IdentityProviderError",Object.setPrototypeOf(this,U.prototype)}}class H extends I{constructor(){super("Popup was blocked. Please allow popups for this site.","popup_blocked"),this.name="PopupBlockedError",Object.setPrototypeOf(this,H.prototype)}}class F extends I{constructor(){super("The sign-in window could not communicate with this page.","popup_severed"),this.name="PopupSeveredError",Object.setPrototypeOf(this,F.prototype)}}function V(e){return"string"==typeof e&&e?e:null}function j(e){return"object"!=typeof e||null===e||Array.isArray(e)?void 0:e}function q(e,t,n){const i=j(t)??{},s=j(i.error);return{status:e,message:V(s?.message)??V(i.message)??V(i.error)??"Request failed",code:V(s?.code)??V(i.code)??"api_error",details:j(s?.details)??j(i.details),retryAfterMs:u({status:e,headers:n}).retryAfterMs}}function W(e){return q(e.status,function(e){try{return JSON.parse(e)}catch{return null}}(e.body),e.header)}async function K(e){return q(e.status,await e.json().catch(()=>null),t=>e.headers.get(t))}const G=Object.freeze({account:"acc",attachment:"hda",folder:"fld",helpDeskJob:"hdj",knowledgeBaseArticle:"hdkba",knowledgeBaseCategory:"hdkbc",knowledgeBaseRevision:"hdkbr",knowledgeBaseAsset:"hdkbm",ingot:"ing",invite:"inv",notification:"ntf",requester:"hrq",routingRule:"hdr",savedReply:"hds",spark:"spk",team:"team",ticket:"tkt",ticketEvent:"hdev",user:"usr",vault:"vlt"});function Y(e){if(!Object.hasOwn(G,e))throw new TypeError(`No resource kind '${e}'`);return`^${G[e]}_[A-Za-z0-9_-]+$`}const X=Object.freeze(Object.fromEntries(Object.keys(G).map(e=>[e,new RegExp(Y(e))])));function J(e,t){if(!Object.hasOwn(G,e))throw new TypeError(`No resource kind '${e}'`);return"string"==typeof t&&t.length<=128&&X[e].test(t)}const Q=Object.freeze(Object.keys(G));function Z(e){return Q.some(t=>J(t,e))}const ee="sparkvault.com",te="auth.sv",ne=Object.freeze([te,"x.sv","files.sv","file.sv","spark.sv","by.sv","at.sv","db.sv"]);function ie(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const se=Object.freeze([new RegExp(`(^|\\.)${ie(ee)}$`,"i"),new RegExp(`^(${ne.map(ie).join("|")})$`,"i")]);function oe(e){return"string"!=typeof e?"":e.trim().toLowerCase().replace(/\.$/,"")}function re(e){return function(e){const t=oe(e);return t===ee||t.endsWith(`.${ee}`)}(e)||function(e){return ne.includes(oe(e))}(e)}const ae=`https://${te}`;function le(e){const t=e.replace(/\/+$/,"");return t.endsWith("/v1")?t.slice(0,-3):t}function de(e){return e.replace(/\/+$/,"")}function ce(e,t){return e.allowedDownloadHostPatterns.some(e=>e.test(t))}async function ue(e){try{return await e.json()}catch(e){if(e instanceof SyntaxError)return null;throw e}}async function he(e,t,n){const{timeoutMs:i,closeSignal:s,read:o,fail:r}=n;if(s?.aborted)throw r("cancelled",null);const{signal:a,dispose:l}=function(e,t){const n=new AbortController,i=setTimeout(()=>n.abort(),e);let s=n.signal,o=null;return t&&"any"in AbortSignal?s=AbortSignal.any([n.signal,t]):t&&(o=()=>n.abort(),t.addEventListener("abort",o)),{signal:s,dispose:()=>{clearTimeout(i),t&&o&&t.removeEventListener("abort",o)}}}(i,s);try{return await o(await fetch(e,{...t,signal:a}))}catch(e){if(e instanceof I)throw e;if(function(e){return null!=e&&"object"==typeof e&&"name"in e&&"AbortError"===e.name}(e))throw r(s?.aborted?"cancelled":"timeout",e);if(e instanceof TypeError)throw r("network",e);throw r("unknown",e)}finally{l()}}class pe{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 he(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:o}=await K(e);throw this.makeError(n,i,t,s,o)}return{data:await ue(e),status:e.status}})}}function me(e){if("string"!=typeof e||""===e||"."===e||".."===e)return null;try{return encodeURIComponent(e)}catch{return null}}function fe(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}`:""}class ve{constructor(e){this.config=e}async getDefaultHeaders(e,t,n){const i={Accept:"application/json",...e};if(t&&(i["Content-Type"]="application/json"),n&&(i["X-Vault-Access-Token"]=n),!i.Authorization){const e=await this.getAccessToken();e&&(i.Authorization=`Bearer ${e}`)}return this.config.apiKey&&!i["X-API-Key"]&&(i["X-API-Key"]=this.config.apiKey),i}async getAccessToken(){return this.config.getAccessToken?this.config.getAccessToken():this.config.accessToken??null}async request(e,t={}){const{method:n="GET",headers:i={},body:s,query:o,vat:r,timeout:a=this.config.timeout}=t;return he(`${this.config.apiBaseUrl}${e}${fe(o)}`,{method:n,headers:await this.getDefaultHeaders(i,void 0!==s,r),body:s?JSON.stringify(s):void 0},{timeoutMs:a,read:async e=>{if(!e.ok)throw this.createErrorFromResponse(await K(e));return{data:this.unwrapApiResponse(await this.parseResponse(e))}},fail:(e,t)=>{switch(e){case"timeout":return new z;case"network":return new O("Network request failed. Please check your connection.");default:return new I(t instanceof Error?t.message:"Unknown error","unknown_error")}}})}async parseResponse(e){const t=e.headers.get("content-length");if(204===e.status||"0"===t)return null;const n=e.headers.get("content-type");if(n?.includes("application/json")){return await e.json()}const i=await e.text();throw new I(`Unexpected response format: expected JSON but received ${n??"unknown content type"}`,"invalid_response_format",e.status,{body:i.slice(0,500)})}createErrorFromResponse({status:e,message:t,code:n,details:i,retryAfterMs:s}){switch(e){case 400:return new M(t,i,s,n);case 401:return"UNAUTHORIZED"===n?new L(t,i,s,n):new $(t,i,s,n);case 402:return"QUOTA_EXCEEDED"===n?new R(t,i,s,n):new P(t,i,s,n);case 403:return"NOTIFY_SUBSCRIPTION_REQUIRED"===n?new N(t,i,s,n):new B(t,i,s,n);default:return new I(t,n,e,i,s,n)}}unwrapApiResponse(e){if("object"==typeof e&&null!==e){if("data"in e&&("meta"in e||"error"in e))return e.data}return e}get(e,t){return this.request(e,{...t,method:"GET"})}post(e,t,n){return this.request(e,{...n,method:"POST",body:t})}put(e,t,n){return this.request(e,{...n,method:"PUT",body:t})}patch(e,t,n){return this.request(e,{...n,method:"PATCH",body:t})}delete(e,t){return this.request(e,{...t,method:"DELETE"})}}class ge{constructor(e){this.config=e}async check(e={}){const t=Math.floor(Date.now()/1e3),n=new AbortController,i=setTimeout(()=>n.abort(),e.timeout??this.config.timeout);try{const e=await fetch(`${this.config.apiBaseUrl}/health`,{method:"GET",headers:{Accept:"application/json"},signal:n.signal});return{online:e.ok,status:e.ok?await this.readStatus(e):"unhealthy",httpStatus:e.status,checkedAt:t}}catch(e){return{online:!1,status:"unreachable",checkedAt:t,error:e instanceof Error?e.message:String(e)}}finally{clearTimeout(i)}}async isOnline(e={}){return(await this.check(e)).online}async readStatus(e){try{const t=await e.json(),n="object"==typeof t&&null!==t&&"data"in t?t.data:t;if("object"==typeof n&&null!==n){const e=n.status;if("string"==typeof e&&e)return e}}catch{return e.ok?"healthy":"unhealthy"}return e.ok?"healthy":"unhealthy"}}function ye(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}}const be=ye("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",!0),we=ye("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",!1);function ke(e){return 9===e||10===e||12===e||13===e||32===e}function xe(e){return ArrayBuffer.isView(e)&&"[object Uint8Array]"===Object.prototype.toString.call(e)}function Ce(e,t){if(!xe(e))throw new TypeError("Base64 encoding takes a Uint8Array");const{codes:n}=t,i=e.length%3,s=e.length-i;let o=0;i>0&&(o=t.padded?4:i+1);const r=new Uint8Array(s/3*4+o);let a=0;for(let t=0;t<s;t+=3){const i=e[t]<<16|e[t+1]<<8|e[t+2];r[a++]=n[i>>18],r[a++]=n[i>>12&63],r[a++]=n[i>>6&63],r[a++]=n[63&i]}if(i>0){const t=e[s]<<16|(2===i?e[s+1]<<8:0);r[a++]=n[t>>18],r[a++]=n[t>>12&63],2===i&&(r[a++]=n[t>>6&63]),r.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}(r)}function Se(e){return Ce(e,we)}function Ee(e,{canonical:t=!1}={}){return function(e,t,n){if("string"!=typeof e)return null;const{values:i}=t;let s=0,o=0;for(let t=0;t<e.length;t+=1){const r=e.charCodeAt(t);if(ke(r)){if(n)return null}else if(61===r)o+=1;else{if(o>0||r>127||i[r]<0)return null;s+=1}}const r=s%4;if(1===r)return null;if(o>0&&(o>2||(s+o)%4!=0))return null;if(n&&o!==(t.padded?(4-r)%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;ke(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,we,t)}function _e(e){return Ce((new TextEncoder).encode(e),be)}const Te=Object.freeze(["hex","base64","base64url","alphanumeric","alphanumeric-mixed","password","numeric","uuid","bytes"]),Ae=1024,Ie=Object.freeze(["alphanumeric","alphanumeric-mixed","password"]);const $e=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>Ae)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 Le(e){const{codeVerifier:t,state:n,nonce:i}=function(e,t){if(!xe(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,o]of t.fields)n[s]=e.subarray(i,i+o),i+=o;return n}(e,$e);return{codeVerifier:Se(t),state:Se(n),nonce:Se(i)}}function Be(e,...t){const n=function(e,t){let n=e[0];for(let i=0;i<t.length;i+=1){const s=me(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===me(e))});return n}function Me(e,t){if("string"!=typeof e||!Z(e))throw new M(`${t} must be a SparkVault resource id`,{field:t,received:e});return e}function Pe(e){return Me(e?.id,"vault.id")}$e.bytes;class Re{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 Ne{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 Oe(e){return Se(new Uint8Array(e))}function ze(){return`${window.location.origin}${window.location.pathname}${window.location.search}`}function De(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"),n&&(i.set("redirect_uri",n.redirectUri),i.set("state",n.state),i.set("code_challenge",n.codeChallenge)),`${e.identityBaseUrl}/${e.accountId}/signin?${i}`}class Ue extends pe{constructor(e,t){super(t),this.configCache=null,this.config=e}get baseUrl(){return`${this.config.identityBaseUrl}${Be`/${this.config.accountId}`}`}makeError(e,t,n,i,s=null){return new je(e,t,n,i,s)}async request(e,t,n,i){const{data:s}=await this.rawRequest(`${this.baseUrl}${t}${fe(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",Be`/config`));try{return await this.configCache}catch(e){throw this.configCache=null,e}}preloadConfig(){if(this.configCache)return;const e=this.request("GET",Be`/config`);this.configCache=e,e.catch(()=>{})}isConfigPreloaded(){return null!==this.configCache}async drawAuthorizationValues(){return Le(function(e,t){const n=Ee(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}(await this.request("POST",Be`/entropy`,{num_bytes:$e.bytes}),$e.bytes))}async checkPasskey(e,t="email",n){const i="phone"===t?{phone:e}:{email:e};return this.request("POST",Be`/passkey/check`,{...i,...He(n)})}async redeemHandoffCode(e,t){return this.request("POST",Be`/signin/redeem`,{code:e,code_verifier:t})}buildAuthContextParams(e){return{...e?.authRequestId?{auth_request_id:e.authRequestId}:{},...He(e)}}async sendOtp(e){return this.request("POST",Be`/otp/send`,{recipient:e.recipient,method:e.method,...this.buildAuthContextParams(e.authContext)})}async verifyOtp(e){return this.request("POST",Be`/otp/verify`,{kindling:e.kindling,pin:e.pin,recipient:e.recipient,...this.buildAuthContextParams(e.authContext)})}async submitSecondFactor(e){return this.request("POST",Be`/second-factor/verify`,{ticket:e.ticket,code:e.code})}async startPasskeyVerify(e,t="email",n){const i=e?{[t]:e}:{},s=await this.request("POST",Be`/passkey/verify`,{...i,...He(n)});return{challenge:s.options.challenge,rpId:s.options.rpId,timeout:s.options.timeout,...s.options.allowCredentials?{allowCredentials:s.options.allowCredentials}:{},session:s.session}}async completePasskeyVerify(e){const t=e.credential.response;return this.request("POST",Be`/passkey/verify/complete`,{session:e.session,...this.buildAuthContextParams(e.authContext),credential:{id:e.credential.id,rawId:Oe(e.credential.rawId),type:e.credential.type,response:{clientDataJSON:Oe(t.clientDataJSON),authenticatorData:Oe(t.authenticatorData),signature:Oe(t.signature),userHandle:t.userHandle?Oe(t.userHandle):null}}})}async sendBackupVerification(e){return this.request("POST",Be`/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",Be`/backup-verification/verify`,{session_id:e.sessionId,code:e.code})}async dismissRecommendation(e){await this.request("POST",Be`/recommendations/dismiss`,{verification_token:e.verificationToken,key:e.key})}getSocialAuthUrl(e,t,n,i){const s=new URLSearchParams({redirect_uri:t,state:n});i?.authRequestId&&s.set("auth_request_id",i.authRequestId);const{simple_mode:o}=He(i);return o&&s.set("simple_mode",JSON.stringify(o)),`${this.baseUrl}/social/${e}?${s}`}async sendSparkLink(e,t,n){return this.request("POST",Be`/sparklink/send`,{email:e,connection_id:t,...this.buildAuthContextParams(n)})}async consumeSparkLinkResult(e){return Fe(await this.request("GET",Be`/sparklink/result`,void 0,{kindling:e}))}}function He(e){return e?.simpleMode?{simple_mode:{session_id:e.simpleMode.sessionId}}:{}}function Fe(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:Ve(t.recommendations)}}:null}function Ve(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 je extends I{constructor(e,t,n,i,s=null){super(e,t,n,i,s),this.name="IdentityApiError",Object.setPrototypeOf(this,je.prototype)}}const qe=/^\D*\+/,We=/^[1-9]\d{7,14}$/,Ke=/\p{Cf}/gu,Ge=/^[\s().\p{Pd}]*\+?[\d\s().\p{Pd}]*$/u,Ye=/^[+(\d]/;function Xe(e){return e.replace(Ke,"")}function Je(e){if("string"!=typeof e)return null;const t=Xe(e);if(!Ge.test(t))return null;const n=t.replace(/\D/g,"");return qe.test(t)?We.test(n)?`+${n}`:null:10===n.length?`+1${n}`:11===n.length&&n.startsWith("1")?`+${n}`:null}function Qe(e){if("string"!=typeof e)return"email";const t=Xe(e).trim();return Ye.test(t)&&Ge.test(t)?"phone":"email"}function Ze(e){const t=Xe(e);if(!Ge.test(t))return e;const n=t.replace(/\D/g,"");if(qe.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 et={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"}};function tt(e){return e.map(e=>et[e]).filter(e=>void 0!==e)}class nt{constructor(){this._sdkConfig=null,this._viewState={view:"loading"},this._recipient="",this._identityType="email",this._authContext=void 0,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 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 it{openPopup(e){const t=e.width??480,n=e.height??640,i=e.timeoutMs??18e5;return new Promise((s,o)=>{const r=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=${r},top=${a},popup=1`);if(!l)return void o(new H);e.onOpen?.(l);const d=Date.now();let c=!1,u=!1;const h=()=>{window.removeEventListener("message",p),clearTimeout(m),clearInterval(f)},p=t=>{if(t.origin!==e.trustedOrigin)return;const n=t.data;if(e.readyType&&n?.type===e.readyType)return u=!0,void e.onReady?.();n?.type===e.resultType&&(c=!0,h(),s(n))};window.addEventListener("message",p);const m=setTimeout(()=>{c||(c=!0,h(),l.close(),o(new z("Popup operation timed out. Please try again.")))},i),f=setInterval(()=>{if(l.closed&&!c){if(c=!0,h(),!u&&Date.now()-d<=2500)return void o(new F);o(new D("Authentication was cancelled."))}},500)})}}function st(e){const t=Ee(e);if(null===t)throw new je("The passkey options are not valid base64url","invalid_response",0);return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}class ot{constructor(e,t){this.api=e,this.state=t,this.popupLauncher=new it;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),i=await navigator.credentials.get({...e?{signal:e}:{},publicKey:{challenge:st(n.challenge),rpId:n.rpId,timeout:n.timeout,userVerification:"required",...n.allowCredentials?{allowCredentials:n.allowCredentials.map(e=>({type:e.type,id:st(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});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 je?"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}=He(i);s&&n.set("simple_mode",JSON.stringify(s));const o="register"===e&&t?`#${new URLSearchParams({registration_token:t}).toString()}`:"",r=`${this.baseUrl}/${this.accountId}/passkey/popup?${n}${o}`;let a;try{a=await this.popupLauncher.openPopup({url:r,windowName:"sparkvault-passkey",width:450,height:500,resultType:"sparkvault-passkey-result",trustedOrigin:this.trustedOrigin})}catch(e){return e instanceof H?{success:!1,error:e.message,errorType:"popup_blocked"}:e instanceof D?{success:!1,error:e.message,errorType:"cancelled"}:{success:!1,error:e instanceof Error?e.message:"Passkey operation failed. Please try again.",errorType:"unknown"}}return a.success&&a.data?{success:!0,result:{token:a.data.token||"",identity:a.data.identity||this.state.recipient,identityType:a.data.identity_type||"email",svid:a.data.svid,sessionId:a.data.session_id,refreshToken:a.data.refresh_token,redirect:a.data.redirect}}:this.handlePopupError(a.error,a.message,a.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 rt{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});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 I?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});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 I?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});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:Ve(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 I?e.code:void 0}}}}class at{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);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 I?e.code:void 0}}}}const lt=new RegExp("^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$"),dt=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,ct=Object.freeze({ADDRESS:320,LOCAL_PART:64,DOMAIN:255}),ut=Object.freeze({FORMAT:"format",TOO_LONG:"too_long",LOCAL_PART_TOO_LONG:"local_part_too_long",DOMAIN_TOO_LONG:"domain_too_long"});function ht(e){if("string"!=typeof e)throw new TypeError("An email address is a string");return e.trim().toLowerCase()}function pt(e){return null===function(e){if("string"!=typeof e)return ut.FORMAT;const t=ht(e),n=t.indexOf("@");if(n<=0||n!==t.lastIndexOf("@"))return ut.FORMAT;const i=t.slice(0,n),s=t.slice(n+1),o=s.split(".");return!lt.test(i)||o.length<2||!o.every(e=>dt.test(e))?ut.FORMAT:t.length>ct.ADDRESS?ut.TOO_LONG:i.length>ct.LOCAL_PART?ut.LOCAL_PART_TOO_LONG:s.length>ct.DOMAIN?ut.DOMAIN_TOO_LONG:null}(e)}function mt(e,t){const n=document.createElement("div");return e&&(n.className=e),n}function ft(e){for(;e.firstChild;)e.removeChild(e.firstChild)}function vt(e){const t=document.createElement("div");return t.className="sv-error",t.setAttribute("role","alert"),t.textContent=e,t}function gt(e){return pt(e)?ht(e):null}class yt{constructor(e={}){this.message=e.message??"Loading..."}render(){const e=mt("sv-loading"),t=document.createElement("div");t.className="sv-spinner",t.setAttribute("role","status"),t.setAttribute("aria-label","Loading");const n=document.createElement("p");return n.className="sv-loading-text",n.textContent=this.message,e.appendChild(t),e.appendChild(n),e}destroy(){}}class bt{constructor(e){this.inputElement=null,this.labelElement=null,this.submitButton=null,this.passkeyLink=null,this.errorContainer=null,this.focusTimeoutId=null,this.detectedType="email",this.props=e,this.boundHandleInput=()=>this.handleInput(),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=mt("sv-email-view"),t=mt("sv-email-header"),n=document.createElement("p");n.className="sv-email-subtitle",n.textContent=this.getSubtitleText(),t.appendChild(n),e.appendChild(t),this.errorContainer=mt("sv-email-error-container"),this.props.error&&this.errorContainer.appendChild(vt(this.props.error)),e.appendChild(this.errorContainer);const i=mt("sv-email-form"),s=mt("sv-email-input-wrapper");return 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=ct.ADDRESS,this.props.initialValue&&(this.inputElement.value=this.props.initialValue,this.detectAndUpdateType(this.props.initialValue)),this.inputElement.addEventListener("input",this.boundHandleInput),this.inputElement.addEventListener("keydown",this.boundHandleKeyDown),s.appendChild(this.labelElement),s.appendChild(this.inputElement),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}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.detectedType?"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"}handleInput(){if(this.clearError(),!this.inputElement)return;const e=this.inputElement.value;if(this.allowsBoth){const t="phone"===this.detectedType;this.detectAndUpdateType(e),t!==("phone"===this.detectedType)&&this.labelElement&&(this.labelElement.textContent=this.getLabelText())}else if(this.allowsPhone){const t=this.inputElement.selectionStart??e.length,n=Ze(e);if(n!==e){this.inputElement.value=n;const i=Math.min(t+(n.length-e.length),n.length);this.inputElement.setSelectionRange(i,i)}}}detectAndUpdateType(e){this.detectedType=Qe(e)}clearError(){this.errorContainer&&ft(this.errorContainer),this.inputElement?.classList.remove("sv-email-input-error")}showError(e){this.errorContainer&&(ft(this.errorContainer),this.errorContainer.appendChild(vt(e))),this.inputElement?.classList.add("sv-email-input-error"),this.inputElement?.focus()}handleSubmit(){if(!this.inputElement||!this.submitButton)return;const e=this.inputElement.value;if(this.allowsBoth)if("phone"===this.detectedType){const t=Je(e);if(!t)return void this.showError("Please enter a valid phone number");this.submitButton.disabled=!0,this.submitButton.textContent="Please wait...",this.props.onSubmit({value:t,type:"phone"})}else{const t=gt(e);if(!t)return void this.showError("Please enter a valid email address");this.submitButton.disabled=!0,this.submitButton.textContent="Please wait...",this.props.onSubmit({value:t,type:"email"})}else if(this.allowsPhone){const t=Je(e);if(!t)return void this.showError("Please enter a valid phone number");this.submitButton.disabled=!0,this.submitButton.textContent="Please wait...",this.props.onSubmit({value:t,type:"phone"})}else{const t=gt(e);if(!t)return void this.showError("Please enter a valid email address");this.submitButton.disabled=!0,this.submitButton.textContent="Please wait...",this.props.onSubmit({value:t,type:"email"})}}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.passkeyLink&&this.boundHandlePasskey&&this.passkeyLink.removeEventListener("click",this.boundHandlePasskey)}}function wt(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 kt(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 xt(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 Ct(){const e=wt("0 0 16 16");return e.appendChild(kt("M13.25 4.75L6 12 2.75 8.75",{stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"})),e}function St(){const e=wt("0 0 16 16");return e.appendChild(kt("M10 12L6 8L10 4",{stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"})),e}function Et(){const e=wt("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(xt(-9.5,-9.5,9.5,n)),t.appendChild(kt("M-2.8 -2.8L16 16",n)),t.appendChild(kt("M9.5 9.5L9.5 15.5",n)),t.appendChild(kt("M16 16L16 22",n)),e.appendChild(t),e}function _t(e){const t=wt("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(kt("M24 9L5.5 39h37L24 9z",n)),t.appendChild(kt("M24 20v8",n)),t.appendChild(xt(24,33.5,1.5,{fill:"currentColor"})),t}function Tt(e){const t=function(e){switch(e){case"email":return function(){const e=wt("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(kt("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(kt("M18 5l-8 5.5L2 5")),e}();case"sms":return function(){const e=wt("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(kt("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(xt(7,8,.75,{fill:"currentColor",stroke:"none"})),e.appendChild(xt(10,8,.75,{fill:"currentColor",stroke:"none"})),e.appendChild(xt(13,8,.75,{fill:"currentColor",stroke:"none"})),e}();case"phone":return function(){const e=wt("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(kt("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=wt("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(kt("M2 10c0-4.42 3.58-8 8-8 2.65 0 5 1.29 6.47 3.28")),e.appendChild(kt("M4 16.58c.42-.35.79-.76 1.1-1.22")),e.appendChild(kt("M14.41 17.51c.09-.45.32-1.73.38-2.26")),e.appendChild(kt("M10 8.33a1.5 1.5 0 00-1.5 1.5c0 .77-.08 1.88-.2 3")),e.appendChild(kt("M7.21 18.33c.16-.5.34-1 .43-1.5")),e.appendChild(kt("M11.67 10.93c0 1.79 0 4.79-.75 6.65")),e.appendChild(kt("M17.33 13.33c.15-1.5.1-4.02 0-4.5")),e.appendChild(kt("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=wt("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(kt("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(kt("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":return function(){const e=wt("0 0 20 20",20,20);return e.appendChild(kt("M18.8 10.21c0-.65-.06-1.28-.17-1.88H10v3.55h4.93c-.21 1.14-.87 2.11-1.84 2.76v2.3h2.98c1.73-1.6 2.73-3.96 2.73-6.73z",{fill:"#4285F4"})),e.appendChild(kt("M10 19.17c2.48 0 4.55-.82 6.07-2.23l-2.98-2.3c-.82.55-1.86.88-3.09.88-2.38 0-4.4-1.6-5.13-3.77H1.82v2.37c1.52 3.02 4.6 5.05 8.18 5.05z",{fill:"#34A853"})),e.appendChild(kt("M4.87 11.74c-.18-.55-.29-1.14-.29-1.74s.1-1.19.29-1.74V5.89H1.82c-.6 1.23-.94 2.6-.94 4.11s.34 2.88.94 4.11l3.05-2.37z",{fill:"#FBBC05"})),e.appendChild(kt("M10 4.48c1.35 0 2.55.47 3.5 1.37l2.63-2.63C14.53 1.74 12.47.83 10 .83c-3.58 0-6.66 2.03-8.18 5.05l3.05 2.37c.72-2.17 2.75-3.77 5.13-3.77z",{fill:"#EA4335"})),e}();case"apple":return function(){const e=wt("0 0 20 20",20,20);return e.setAttribute("fill","currentColor"),e.appendChild(kt("M14.21 16.9c-.82.79-1.71.67-2.57.29-.91-.38-1.74-.4-2.7 0-1.2.51-1.83.37-2.55-.29C2.7 12.71 3.3 6.33 7.54 6.09c1.13.06 1.91.61 2.57.66.98-.2 1.92-.78 2.97-.7 1.26.1 2.21.6 2.83 1.5-2.6 1.56-1.98 4.99.4 5.94-.48 1.25-1.09 2.49-2.11 3.41h.01zM10.02 6.04c-.12-1.86 1.38-3.39 3.11-3.54.24 2.15-1.95 3.75-3.11 3.54z")),e}();case"microsoft":return function(){const e=wt("0 0 20 20",20,20);return e.appendChild(kt("M1 1h8.33v8.33H1z",{fill:"#F25022"})),e.appendChild(kt("M1 10.67h8.33V19H1z",{fill:"#00A4EF"})),e.appendChild(kt("M10.67 1H19v8.33h-8.33z",{fill:"#7FBA00"})),e.appendChild(kt("M10.67 10.67H19V19h-8.33z",{fill:"#FFB900"})),e}();case"github":return function(){const e=wt("0 0 20 20",20,20);return e.setAttribute("fill","currentColor"),e.appendChild(kt("M10 0C4.48 0 0 4.48 0 10c0 4.42 2.86 8.17 6.84 9.49.5.09.68-.22.68-.48 0-.24-.01-1.02-.01-1.86-2.51.46-3.16-.61-3.36-1.18-.11-.29-.6-1.18-1.02-1.41-.35-.19-.85-.65-.01-.66.79-.01 1.35.72 1.54 1.02.9 1.51 2.34 1.09 2.91.83.09-.65.35-1.09.64-1.34-2.22-.25-4.55-1.11-4.55-4.94 0-1.09.39-1.99 1.02-2.69-.1-.25-.45-1.27.1-2.65 0 0 .84-.27 2.75 1.02.8-.22 1.65-.33 2.5-.33s1.7.11 2.5.33c1.91-1.3 2.75-1.02 2.75-1.02.55 1.38.2 2.4.1 2.65.64.7 1.02 1.59 1.02 2.69 0 3.84-2.34 4.69-4.57 4.94.36.31.67.91.67 1.85 0 1.34-.01 2.41-.01 2.75 0 .27.18.58.69.48C17.14 18.16 20 14.42 20 10c0-5.52-4.48-10-10-10z")),e}();case"facebook":return function(){const e=wt("0 0 20 20",20,20);return e.appendChild(kt("M20 10.06c0-5.52-4.48-10-10-10S0 4.53 0 10.06c0 4.99 3.66 9.13 8.44 9.88v-6.99H5.9v-2.89h2.54V7.85c0-2.51 1.49-3.89 3.78-3.89 1.09 0 2.24.2 2.24.2v2.46h-1.26c-1.24 0-1.63.77-1.63 1.56v1.88h2.77l-.44 2.89h-2.33v6.99c4.78-.75 8.44-4.89 8.44-9.88z",{fill:"#1877F2"})),e}();case"linkedin":return function(){const e=wt("0 0 20 20",20,20);return e.appendChild(kt("M17.04 17.04h-2.96v-4.64c0-1.11-.02-2.53-1.54-2.53-1.55 0-1.78 1.2-1.78 2.45v4.73H7.8V7.5h2.84v1.3h.04c.4-.75 1.36-1.54 2.81-1.54 3 0 3.56 1.98 3.56 4.55v5.24zM4.45 6.19c-.95 0-1.72-.77-1.72-1.72s.77-1.72 1.72-1.72 1.72.77 1.72 1.72-.77 1.72-1.72 1.72zm1.48 10.85H2.96V7.5h2.97v9.54zM18.52 0H1.47C.66 0 0 .65 0 1.44v17.12c0 .79.66 1.44 1.48 1.44h17.04c.82 0 1.48-.65 1.48-1.44V1.44c0-.79-.66-1.44-1.48-1.44z",{fill:"#0A66C2"})),e}();case"building":return function(){const e=wt("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(kt("M2.5 17.5h15")),e.appendChild(kt("M4.17 17.5V5.83L10.83 2.5v15")),e.appendChild(kt("M15.83 17.5V9.17l-5-3.33")),e.appendChild(kt("M7.5 7.5v.01")),e.appendChild(kt("M7.5 10v.01")),e.appendChild(kt("M7.5 12.5v.01")),e.appendChild(kt("M7.5 15v.01")),e}();case"users":return function(){const e=wt("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(kt("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(xt(7.5,5.83,3.33,{stroke:"currentColor","stroke-width":"1.5",fill:"none"})),e.appendChild(kt("M19.17 17.5v-1.67a3.33 3.33 0 00-2.5-3.22")),e.appendChild(kt("M13.33 2.6a3.33 3.33 0 010 6.46")),e}();default:return function(){const e=wt("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(kt("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(xt(10,10,1.25,{fill:"currentColor",stroke:"none"})),e}()}}(e);return t.setAttribute("data-sv-method-icon",e),t}class At{constructor(e){this.backLink=null,this.methodButtons=[],this.methodClickHandlers=new Map,this.props=e,this.boundHandleBack=()=>this.props.onBack?.()}render(){const e=mt();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=mt();for(const e of this.props.methods){const t=this.createMethodButton(e);this.methodButtons.push(t),s.appendChild(t)}return this.backLink&&e.appendChild(this.backLink),e.appendChild(t),i&&e.appendChild(i),e.appendChild(s),e}createBackLink(){const e=document.createElement("button");e.className="sv-back-link",e.appendChild(St());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=document.createElement("button");t.className="sv-btn sv-btn-method";const n=mt("sv-method-content"),i=this.getMethodIcon(e);n.appendChild(i);const s=mt("sv-method-text"),o=document.createElement("div");o.className="sv-method-name",o.textContent=e.name;const r=document.createElement("div");r.className="sv-method-description",r.textContent=e.description,s.appendChild(o),s.appendChild(r),n.appendChild(s),t.appendChild(n);const a=()=>this.props.onSelectMethod(e);return this.methodClickHandlers.set(t,a),t.addEventListener("click",a),t}getMethodIcon(e){const t=mt("sv-method-icon");return t.appendChild(Tt(e.icon)),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 It(e){return function(e,t){return e?String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,t):""}(e,"&#39;")}class $t{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=mt();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>${It(this.props.email)}</strong>`,this.errorContainer=mt(),this.props.error&&this.errorContainer.appendChild(vt(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 o=mt("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),o.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(o),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(St()),e.appendChild(document.createTextNode(" Choose another method")),e.addEventListener("click",this.boundHandleBack),e}createInputGroup(){const e=mt("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&&ft(this.errorContainer),this.inputElements.forEach(e=>e.classList.remove("sv-input-error"))}showError(e){this.errorContainer&&(ft(this.errorContainer),this.errorContainer.appendChild(vt(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 Ne({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 Re({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 Lt{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=mt();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=mt(),this.props.error&&this.errorContainer.appendChild(vt(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&&ft(this.errorContainer),this.input?.classList.remove("sv-input-error")}showError(e){this.errorContainer&&(ft(this.errorContainer),this.errorContainer.appendChild(vt(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 Bt{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=mt();this.backLink=this.props.onBack?this.createBackLink():null;const t=mt();t.appendChild(Et());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>${It(this.props.identityLabel)}</strong><br>to sign in faster next time`:i.innerHTML="Use a passkey linked to your SparkVault Identity",this.errorContainer=mt(),this.props.error&&this.errorContainer.appendChild(vt(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 o="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=o,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(St()),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&&(ft(this.errorContainer),this.errorContainer.appendChild(vt(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 Mt{constructor(e){this.fallbackLink=null,this.props=e,this.boundHandleFallback=()=>this.props.onUseAnotherMethod()}render(){const e=mt(),t=mt();t.appendChild(Et());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 o=mt("sv-loading");return o.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(o),e.appendChild(this.fallbackLink),e}destroy(){this.fallbackLink&&this.fallbackLink.removeEventListener("click",this.boundHandleFallback)}}class Pt{constructor(e){this.addButton=null,this.skipLink=null,this.props=e,this.boundHandleAdd=()=>this.props.onAddPasskey(),this.boundHandleSkip=()=>this.props.onSkip()}render(){const e=mt(),t=mt();t.appendChild(Et());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>${It(this.props.identityLabel)}</strong>`;const s=mt();this.props.error&&s.appendChild(vt(this.props.error));const o=document.createElement("div");o.className="sv-passkey-prompt-benefits";const r=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(Ct()),t.appendChild(document.createTextNode(e)),r.appendChild(t)}return o.appendChild(r),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(o),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 Rt{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=mt("sv-email-view"),t=mt("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=mt("sv-email-error-container"),this.props.error&&this.errorContainer.appendChild(vt(this.props.error)),e.appendChild(this.errorContainer);const s=mt("sv-email-form"),o=mt("sv-email-input-wrapper"),r=document.createElement("label");return r.className="sv-email-label",r.htmlFor="sv-backup-input",r.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=ct.ADDRESS,this.inputElement.addEventListener("input",this.boundHandleInput),this.inputElement.addEventListener("keydown",this.boundHandleKeyDown),o.appendChild(r),o.appendChild(this.inputElement),s.appendChild(o),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=Ze(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&&ft(this.errorContainer),this.inputElement?.classList.remove("sv-email-input-error")}showError(e){this.errorContainer&&(ft(this.errorContainer),this.errorContainer.appendChild(vt(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?Je(e):gt(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 Nt{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=mt();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>${It(this.props.email)}</strong>`,this.waitingSection=mt("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=mt("sv-sparklink-countdown");const o=document.createElement("span");o.textContent="Link expires in ",this.countdownElement=document.createElement("span"),this.countdownElement.className="sv-sparklink-countdown-time",this.startExpirationTimer(),this.countdownSection.appendChild(o),this.countdownSection.appendChild(this.countdownElement);const r=mt("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),r.appendChild(this.resendButton);const a=mt("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(r),e.appendChild(a),e}createBackLink(){const e=document.createElement("button");return e.className="sv-back-link",e.appendChild(St()),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 Ne({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=mt("sv-sparklink-expired-icon");e.appendChild(_t("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 Re({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 Ot=["identity_trial_exhausted","identity_trial_expired","identity_capacity_blocked"];const zt="stronger_verification_required";function Dt(e){return"identity_locked"===e?"This SparkVault Identity is locked":function(e){return Ot.includes(e)}(e)?"Sign-in unavailable":e===zt?"This request needs your passkey":null}class Ut{constructor(e){this.retryButton=null,this.closeButton=null,this.props=e,this.boundHandleRetry=()=>this.props.onRetry(),this.boundHandleClose=()=>this.props.onClose()}render(){const e=mt();e.className="sv-error-view";const t=mt();t.className="sv-error-icon-container",t.appendChild(_t("sv-error-icon"));const n=mt();n.className="sv-error-content";const i=Dt(this.props.code),s=null!==i,o=document.createElement("h3");o.className="sv-error-title",o.textContent=i??"Something went wrong";const r=document.createElement("p");if(r.className="sv-error-message",r.textContent=this.props.message,n.appendChild(o),n.appendChild(r),!s){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 a=mt();return a.className="sv-error-actions",s||(this.retryButton=document.createElement("button"),this.retryButton.className="sv-btn sv-btn-error-primary",this.retryButton.textContent="Try Again",this.retryButton.addEventListener("click",this.boundHandleRetry),a.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),a.appendChild(this.closeButton),e.appendChild(t),e.appendChild(n),e.appendChild(a),e}destroy(){this.retryButton&&this.retryButton.removeEventListener("click",this.boundHandleRetry),this.closeButton&&this.closeButton.removeEventListener("click",this.boundHandleClose)}}const Ht=Object.freeze({white:"#ffffff",slate50:"#f8fafc",slate100:"#f1f5f9",slate200:"#e2e8f0",slate300:"#cbd5e1",slate500:"#64748b",slate600:"#475569",slate900:"#0f172a",slate950:"#030712",action:"#216bde",actionHover:"#0d5bcd",actionBg:"#eef4fe",btnDanger:"#b02b27",btnDangerHover:"#9a221f",success:"#006d42",success500:"#2ec26b",error:"#b02b27",error500:"#e6443d",errorBg:"#fee2e2",errorText:"#991b1b",warning:"#8a5600",warning500:"#e6ad00",infoBg:"#dbeafe",info500:"#4383eb",modalOverlay:"rgba(15, 23, 42, 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(15, 23, 42, 0.12)"});function Ft(e,t){const n=Number.parseInt(e.slice(1),16);return`rgba(${n>>16}, ${n>>8&255}, ${255&n}, ${t})`}class Vt{constructor(e){this.retryButton=null,this.closeButton=null,this.props=e,this.boundHandleRetry=()=>this.props.onRetry(),this.boundHandleClose=()=>this.props.onClose()}render(){const e=mt("sv-unavailable-view"),t=mt("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",Ht.actionBg),t.setAttribute("stroke",Ht.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",Ht.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",Ht.white),n.appendChild(s);const o=document.createElementNS("http://www.w3.org/2000/svg","rect");return o.setAttribute("x","12.5"),o.setAttribute("y","9"),o.setAttribute("width","2.5"),o.setAttribute("height","8"),o.setAttribute("rx","1"),o.setAttribute("fill",Ht.white),n.appendChild(o),e.appendChild(n),e}()),e.appendChild(t);const n=mt("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 o=mt("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),o.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),o.appendChild(this.closeButton),e.appendChild(o),e}destroy(){this.retryButton&&this.retryButton.removeEventListener("click",this.boundHandleRetry),this.closeButton&&this.closeButton.removeEventListener("click",this.boundHandleClose)}}class jt{constructor(e){this.dismissButton=null,this.props=e,this.boundHandleClose=()=>this.props.onClose()}render(){const e=mt("sv-not-activated-view"),t=mt("sv-not-activated-eyebrow");t.appendChild(function(){const e=mt("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=mt("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",Ht.slate50),n.setAttribute("stroke",Ht.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",Ht.white),i.setAttribute("stroke",Ht.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",Ht.slate600),i.setAttribute("stroke-width","2"),i.setAttribute("stroke-linecap","round"),t.appendChild(i)};s("26","40"),s("32","40"),s("38","35");const o=(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",Ht.action),i.setAttribute("stroke",Ht.white),i.setAttribute("stroke-width","1.5"),t.appendChild(i)};return o("30","26"),o("36","32"),o("28","38"),e.appendChild(t),e}();e.appendChild(s);const o=document.createElement("h2");o.className="sv-not-activated-title",o.id="sv-modal-title",o.textContent="Identity Product not configured",e.appendChild(o);const r=document.createElement("p");r.className="sv-not-activated-message",r.textContent="Sign-in is unavailable because the site owner has not configured SparkVault Identity for this account.",e.appendChild(r);const a=mt("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=mt("sv-not-activated-actions"),u=document.createElement("a");u.className="sv-btn sv-btn-primary sv-not-activated-cta",u.href="https://app.sparkvault.com/products/identity",u.target="_blank",u.rel="noopener noreferrer";const h=document.createElement("span");return h.textContent="Configure in SparkVault",u.appendChild(h),u.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(u),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 qt{constructor(e){this.dismissButton=null,this.props=e,this.boundHandleClose=()=>this.props.onClose()}render(){const e=mt("sv-not-activated-view"),t=mt("sv-not-activated-eyebrow");t.appendChild(function(){const e=mt("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=mt("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",Ht.slate50),n.setAttribute("stroke",Ht.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",Ht.white),i.setAttribute("stroke",Ht.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",Ht.slate300),s.setAttribute("stroke-width","2"),t.appendChild(s);const o=document.createElementNS("http://www.w3.org/2000/svg","path");o.setAttribute("d","M19 32H45"),o.setAttribute("stroke",Ht.slate300),o.setAttribute("stroke-width","2"),o.setAttribute("stroke-linecap","round"),t.appendChild(o);const r=document.createElementNS("http://www.w3.org/2000/svg","path");return r.setAttribute("d","M23 23L41 41"),r.setAttribute("stroke",Ht.action),r.setAttribute("stroke-width","2.5"),r.setAttribute("stroke-linecap","round"),t.appendChild(r),e.appendChild(t),e}();e.appendChild(s);const o=document.createElement("h2");o.className="sv-not-activated-title",o.id="sv-modal-title",o.textContent="This domain isn’t allowed",e.appendChild(o);const r=document.createElement("p");r.className="sv-not-activated-message",r.textContent="Sign-in is blocked because this website’s domain is not on the SparkVault Identity allowlist for this account.",e.appendChild(r);const a=mt("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=mt("sv-not-activated-actions"),u=document.createElement("a");u.className="sv-btn sv-btn-primary sv-not-activated-cta",u.href="https://app.sparkvault.com/company/domains",u.target="_blank",u.rel="noopener noreferrer";const h=document.createElement("span");return h.textContent="Manage domains in SparkVault",u.appendChild(h),u.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(u),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 Wt(){if("undefined"==typeof window)return null;const e=window.__sparkvaultProgress;return e&&"function"==typeof e.start?e:null}function Kt(){Wt()?.start()}function Gt(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 Yt=new Set(Ot),Xt={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){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.container=e,this.api=t,this.options=n,this.callbacks=i,this.verificationState=new nt,this.passkeyHandler=new ot(t,this.verificationState),this.otpHandler=new rt(t,this.verificationState),this.sparkLinkHandler=new at(t,this.verificationState),this.applyInitialIdentity(),n.authContext&&this.verificationState.setAuthContext(n.authContext)}applyInitialIdentity(){const e="string"==typeof this.options.phone&&this.options.phone.length>0,t=e?this.options.phone:this.options.email;t&&(e||"phone"===Qe(t)?this.verificationState.setIdentity(Je(t)??t,"phone"):this.verificationState.setIdentity(gt(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(){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());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.setState(this.viewStateForConfigError(e))}viewStateForConfigError(e){if(e instanceof je){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 je&&"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.discoverableVerifyAbort?.abort(),this.discoverableVerifyAbort=null,null!==this.focusTimeoutId&&(clearTimeout(this.focusTimeoutId),this.focusTimeoutId=null),null!==this.morphTimer&&(clearTimeout(this.morphTimer),this.morphTimer=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(){this.recipient||0===this.getAllowedIdentityTypes().length?await this.showMethodSelect():this.canDiscoverableVerify()?this.launchDiscoverableVerify():this.showIdentityInput()}canDiscoverableVerify(){if(!this.passkeyHandler.canAutoVerify())return!1;return tt(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;const n=t.render();n.classList.add("sv-step-enter"),this.morphSwap(e,n),"loading"===this.viewState.view?Kt():Wt()?.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))}destroyCurrentView(){this.currentView?.destroy&&this.currentView.destroy(),this.currentView=null}morphSwap(e,t){const n=e.getBoundingClientRect().height;ft(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 o=()=>{null!==this.morphTimer&&(clearTimeout(this.morphTimer),this.morphTimer=null),e.removeEventListener("transitionend",r),e.style.height="",e.style.overflow="",e.style.transition="",e.style.boxSizing=""},r=t=>{const n=t.propertyName;t.target===e&&"height"===n&&o()};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",r),null!==this.morphTimer&&clearTimeout(this.morphTimer),this.morphTimer=setTimeout(o,550)}createViewForState(e){switch(e.view){case"loading":return new yt({message:"Loading..."});case"identity-input":return new bt({allowedTypes:this.getAllowedIdentityTypes(),initialValue:this.recipient,error:e.error,onSubmit:e=>this.handleIdentitySubmit(e),onPasskey:this.canDiscoverableVerify()?()=>{this.launchDiscoverableVerify()}:void 0});case"method-select":return new At({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 $t({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 Lt({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 Bt({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 Mt({onUseAnotherMethod:()=>this.cancelDiscoverableVerify()});case"passkey-prompt":return new Pt({identityLabel:e.recipient,onAddPasskey:()=>this.handlePasskeyPromptAdd(e.pendingResult),onSkip:()=>this.handlePasskeyPromptSkip(e.pendingResult),error:e.error});case"backup-verify":return new Rt({missingType:e.missingType,error:e.error,onSubmit:e=>this.handleBackupSubmit(e),onSkip:()=>this.handleBackupSkip()});case"backup-code":return new $t({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 Nt({email:e.email,expiresAt:e.expiresAt,onResend:()=>this.handleSparkLinkResend(),onFallback:()=>this.handleSparkLinkFallback(),onBack:()=>this.showMethodSelect(),onExpired:()=>this.cleanupSparkLink()});case"oauth-pending":return new yt({message:`Connecting to ${e.provider}...`});case"error":return new Ut({message:e.message,code:e.code,onRetry:()=>this.showIdentityInput(),onClose:()=>this.handleClose()});case"service-unavailable":return new Vt({onRetry:()=>this.retryConfigLoad(),onClose:()=>this.handleClose()});case"product-not-configured":return new jt({onClose:()=>this.handleClose()});case"origin-not-allowed":return new qt({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"});let i=tt(n);if(this.recipient){i=i.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&&i.some(e=>"passkey"===e.type)&&await this.passkeyHandler.checkPasskey(),!1===this.verificationState.passkey.hasPasskey&&(i=i.filter(e=>"passkey"!==e.type))}else i=i.filter(e=>"passkey"===e.type||"social"===e.type);this.verificationState.passkey.isFallbackMode&&(i=i.filter(e=>"passkey"!==e.type)),0!==i.length?t&&!0===this.verificationState.passkey.hasPasskey&&!this.verificationState.passkey.isFallbackMode&&i.some(e=>"passkey"===e.type)?this.launchPasskeyVerify(!0):1!==i.length||this.isIdentityFixed()?this.setState({view:"method-select",email:this.recipient,methods:i}):this.handleMethodSelect(i[0]):this.setState(this.noMethodState())}noMethodState(){return this.verificationState.passkeyRequired&&!1===this.verificationState.passkey.hasPasskey?{view:"error",code:zt,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.`)}:{view:"error",message:"No authentication methods available",code:"no_methods"};var e,t}handleIdentitySubmit(e){this.verificationState.setIdentity(e.value,e.type),this.identityPrefilled=!1,this.showMethodSelect()}getAllowedIdentityTypes(){return this.verificationState.getAllowedIdentityTypes()}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;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",...Xt}):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;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;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||!Yt.has(e))&&(this.setState({view:"error",code:e,message:Gt(this.verificationState.sdkConfig?.branding?.companyName)}),!0)}async handleOtpSubmit(e){if("otp-verify"!==this.viewState.view)return;const t=this.verificationState.otp.method??"email";Kt();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("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.";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)||"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=tt(this.verificationState.methodIds);return this.recipient?e.some(e=>"passkey"!==e.type&&("phone"===this.identityType?"phone"===e.identityType:"email"===e.identityType)):e.some(e=>"social"===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,ze(),t,this.verificationState.authContext);window.location.href=n}normalizeError(e){return e instanceof je?new I(e.message,e.code):e instanceof Error?e:new Error(String(e))}isSessionExpiredError(e){const t=e.message.toLowerCase(),n=e instanceof I?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);this.isSessionExpiredError(n)?this.showIdentityInput("Your session has expired. Please try again."):this.setState({view:"error",message:n.message,code:n instanceof I?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:o}=this.viewState;try{await this.api.verifyBackupVerification({sessionId:s,code:e}),this.advancePostLogin()}catch(e){if("backup_conflict"===(e instanceof je?e.code:""))return void this.setState({view:"backup-verify",missingType:t,pendingResult:o,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:o,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 o=t=>{"connect-src"===t.violatedDirective&&t.blockedURI.includes(e)&&(s=!0)};document.addEventListener("securitypolicyviolation",o);const r=()=>{document.removeEventListener("securitypolicyviolation",o)},a=new WebSocket(t);this.sparkLinkWs=a;const l=setTimeout(()=>{i||(i=!0,r(),a.close(),n({error:s?"csp":"connection"}))},1e4);a.onopen=()=>{try{a.send(JSON.stringify({action:"init"}))}catch{i||(i=!0,r(),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,r(),clearTimeout(l),this.setupSparkLinkWsHandler(a),void n({connectionId:t.connectionId})},a.onerror=()=>{i||(i=!0,r(),clearTimeout(l),n({error:s?"csp":"connection"}))},a.onclose=()=>{i||(i=!0,r(),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=Fe(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",...Xt}):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);t.success?(this.sparkLinkKindling=t.kindling??null,this.armSparkLinkRefocusClaim(),this.setState({view:"sparklink-waiting",email:this.recipient,expiresAt:t.expiresAt})):(this.cleanupSparkLink(),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;this.setState({view:"error",message:e.error??"Failed to send code",code:"otp_send_failed"})}}}const Qt="sparkvault-identity-styles";function Zt(e){if(document.getElementById(Qt))return en(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=Qt,t.dataset.svTheme=tn(e.branding),t.textContent=nn(e),document.head.appendChild(t)}function en(e){const t=document.getElementById(Qt);if(!t)return;const n=tn(e);t.dataset.svTheme!==n&&(t.dataset.svTheme=n,t.textContent=nn({branding:e??{companyName:"",logoLight:null,logoDark:null}}))}function tn(e){return e?.themeMode??"light"}function nn(e){const{branding:t,backdropBlur:n}=e,i="dark"===tn(t),s=!1!==n,o=`var(--sv-primary, ${Ht.action})`,r=i?Ht.slate950:Ht.white,a=`color-mix(in srgb, ${o} 80%, white)`,l=o,d=`var(--sv-primary-hover, ${Ht.actionHover})`,c=`color-mix(in srgb, ${o} ${i?"20%":"9%"}, transparent)`,u=i?Ht.error500:Ht.error,h=i?Ft(Ht.error500,.12):Ht.errorBg,p=Ft(Ht.error500,.35),m=Ht.btnDanger,f=Ht.btnDangerHover,v=i?Ht.warning500:Ht.warning,g=r,y=i?Ht.darkCard:Ht.slate50,b=i?Ft(Ht.white,.08):Ht.slate100,w=i?Ft(Ht.white,.04):Ht.white,k=i?Ht.darkHairline:Ht.slate200,x=i?Ft(Ht.white,.18):Ht.slate300,C=o,S=i?Ft(Ht.white,.35):Ht.slate300,E=i?Ht.darkText:Ht.slate900,_=i?Ht.darkTextMuted:Ht.slate600,T=i?Ft(Ht.white,.45):Ht.slate500,A=Ht.white,I=`0 0 0 2px ${r}, 0 0 0 4px ${a}`,$=i?"0 1px 2px rgba(0, 0, 0, 0.4)":Ht.shadowSm,L=(i||Ht.shadowMd,i?`0 8px 24px rgba(0, 0, 0, 0.5), 0 0 0 1px ${Ht.darkHairline}`:Ht.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)":Ht.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: ${L};\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 ${k};\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: ${_};\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: ${_};\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 ${k};\n border-radius: 8px;\n background: ${w};\n color: ${E};\n box-sizing: border-box;\n box-shadow: ${$};\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: ${T};\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: ${u};\n }\n\n .sv-input.sv-input-error:focus,\n .sv-input.sv-email-input-error:focus {\n box-shadow: 0 0 0 3px ${h};\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 rgba(15, 23, 42, 0.2);\n }\n\n /* Primary Button */\n .sv-btn-primary,\n .sv-btn-email-primary {\n background: ${l};\n color: ${A};\n box-shadow: ${$};\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 ${k};\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 ${k};\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: ${A};\n box-shadow: ${$};\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: ${_};\n border: 1px solid ${k};\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: ${T};\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: ${T};\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 ${k};\n border-radius: 8px;\n background: ${w};\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: ${_};\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: ${h};\n border: 1px solid ${p};\n color: ${u};\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 ${k};\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: ${_};\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: ${T};\n letter-spacing: 0.02em;\n }\n\n .sv-footer-link {\n color: ${_};\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: ${_};\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 ${k};\n border-radius: 8px;\n background: ${w};\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: ${T};\n }\n\n .sv-email-input-error {\n border-color: ${u};\n }\n\n .sv-email-input-error:focus {\n box-shadow: 0 0 0 3px ${h};\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: ${_};\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: ${h};\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?Ht.error500:Ht.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: ${u};\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: ${_};\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: ${T};\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: ${_};\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: ${T};\n opacity: 0.6;\n }\n\n .sv-not-activated-eyebrow-label {\n color: ${_};\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 rgba(15, 23, 42, 0.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: ${_};\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 ${k};\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: ${_};\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: ${T};\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: ${T};\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: ${_};\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: ${_};\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: ${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 transition: color var(--sv-dur-fast) var(--sv-ease-standard);\n }\n\n .sv-skip-link:hover {\n color: ${_};\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: ${_};\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 ${k};\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: ${_};\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: ${T};\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 ${k};\n }\n\n .sv-sparklink-fallback .sv-back-link {\n margin-bottom: 0;\n font-size: 12px;\n color: ${T};\n }\n\n .sv-sparklink-fallback .sv-back-link:hover:not(:disabled) {\n color: ${_};\n }\n\n /* SparkLink Expired State */\n .sv-sparklink-expired {\n flex-direction: column;\n gap: 12px;\n background: ${y};\n border: 1px solid ${k};\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: ${_};\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: ${k};\n }\n\n .sv-divider-text {\n padding: 0 12px;\n font-size: 12px;\n color: ${T};\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 ${k};\n }\n\n .sv-inline-header {\n border-bottom: 1px solid ${k};\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 ${k};\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: ${_}; }\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 `}let sn=0,on="";class rn{constructor(e){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.onOverlayClick=t=>{t.target===this.overlay&&e.onDismiss()},this.onKeydown=t=>{"Escape"===t.key&&e.onDismiss()},this.overlay.addEventListener("click",this.onOverlayClick),document.addEventListener("keydown",this.onKeydown),document.body.appendChild(this.overlay),0===sn&&(on=document.body.style.overflow,document.body.style.overflow="hidden"),sn+=1,this.modal.focus({preventScroll:!0})}destroy(){this.open&&(this.open=!1,document.removeEventListener("keydown",this.onKeydown),this.overlay.removeEventListener("click",this.onOverlayClick),this.overlay.remove(),sn-=1,0===sn&&(document.body.style.overflow=on),this.opener?.isConnected&&this.opener.focus({preventScroll:!0}))}}function an(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}function ln(e,t,n){return e?n||t:t||n}const dn="sv-modal-title",cn={companyName:"",logoLight:null,logoDark:null};class un{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=tn(cn),Zt({branding:cn,backdropBlur:e.backdropBlur}),this.shell=new rn({overlayId:"sparkvault-identity-overlay",modalId:"sparkvault-identity-modal",classPrefix:"sv",titleId:dn,backdropBlur:!1!==e.backdropBlur,onDismiss:()=>this.handleClose()}),this.header=this.createHeader(cn),this.body=document.createElement("div"),this.body.className="sv-body",this.shell.modal.append(this.header,this.body,an("sv")))}updateBranding(e){if(!this.shell||!this.header)return;this.effectiveTheme=tn(e),en(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=hn("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=ln("dark"===this.effectiveTheme,e.logoLight,e.logoDark);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=dn,s.textContent=e.companyName,n.appendChild(s)}else{const t=document.createElement("h2");t.className="sv-company-name",t.id=dn,t.textContent=e.companyName,n.appendChild(t)}return t.append(n,hn("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 hn(e,t){const n=document.createElement("button");return n.className=e,n.type="button",n.setAttribute("aria-label","Close"),n.appendChild(function(){const e=wt("0 0 20 20",20,20);return e.appendChild(kt("M15 5L5 15M5 5L15 15",{stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round"})),e}()),n.addEventListener("click",t),n}const pn="http://www.w3.org/2000/svg";function mn(e,t,n){const i=document.createElement(e);return t&&(i.className=t),null!=n&&(i.textContent=n),i}class fn{constructor(e,t,n,i){this.config=e,this.api=t,this.options=n,this.callbacks=i,this.popupLauncher=new it,this.modal=null,this.alertEl=null,this.popupWindow=null,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}openPopup(){const e=++this.generation;this.popupLauncher.openPopup({url:De(this.config,this.options),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()}}).then(t=>{e===this.generation&&this.handleResult(t)}).catch(t=>{e===this.generation&&this.handleError(t)})}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 I(e.message||e.error||"Verification failed",e.errorCode||e.error||"verification_failed"))):this.finishCancel()}}handleError(e){if(!this.settled)if(e instanceof F&&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 H||e instanceof D||e instanceof F)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 un,this.modal.createLoading({backdropBlur:this.options.backdropBlur},()=>this.abort()));const e=this.modal.getBody();if(!e)return;ft(e);const t=mn("div","sv-bridge"),n=mn("div","sv-bridge-alert");n.appendChild(function(){const e=document.createElementNS(pn,"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(pn,"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(pn,"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=mn("div","sv-bridge-alert-body");i.appendChild(mn("span","sv-bridge-alert-text","The sign-in window may not have opened."));const s=mn("button","sv-bridge-retry","Try again");s.type="button",s.addEventListener("click",()=>this.retry()),i.appendChild(s),n.appendChild(i),this.alertEl=n;const o=mn("div","sv-bridge-dots");o.append(mn("span"),mn("span"),mn("span")),t.append(n,o,mn("h3","sv-title","Continue in the secure window"),mn("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.callbacks.onPopupReopened?.(),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 vn{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 gn{constructor(e,t={}){this.shell=null,this.targetElement=e,this.bare=!0===t.bare}createLoading(e,t){this.shell||(Zt({branding:{companyName:"",logoLight:null,logoDark:null},backdropBlur:!1}),this.shell=new vn(this.targetElement,{containerClassName:this.bare?"sv-inline-container sv-inline-bare":"sv-inline-container",bodyClassName:"sv-body sv-inline-body",footer:this.bare?null:an("sv")}))}updateBranding(e){this.shell&&en(e)}setMinimalChrome(e){}getBody(){return this.shell?.body??null}isOpen(){return null!==this.shell}destroy(){this.shell?.destroy(),this.shell=null}}function yn(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")}function bn(e,t){let n=null,i=!1;const s=new Map,o=e=>{s.has(e)||(e.addEventListener("click",t),s.set(e,()=>e.removeEventListener("click",t)))};var r;return r=()=>{i||(document.querySelectorAll(e).forEach(o),n=new MutationObserver(t=>{t.forEach(t=>{t.addedNodes.forEach(t=>{t instanceof Element&&(t.matches(e)&&o(t),t.querySelectorAll(e).forEach(o))})})}),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",r,{once:!0}):r(),()=>{i=!0,n?.disconnect(),s.forEach(e=>e()),s.clear()}}const wn=["home","identity","security","sessions","sites"],kn=["EdDSA","RS256"],xn="sv_signin_pending";function Cn(){let e=null;try{e=sessionStorage.getItem(xn)}catch{return null}if(!e)return null;let t=NaN,n=null;try{const i=JSON.parse(e);if("object"==typeof i&&null!==i){const e=i;"number"==typeof e.at&&(t=e.at),"string"==typeof e.hint&&e.hint&&(n=e.hint)}else"number"==typeof i&&(t=i)}catch{t=Number(e)}return Number.isFinite(t)?{at:t,hint:n}:null}function Sn(e){return null!==e&&Date.now()-e.at<6e5}function En(){return"undefined"!=typeof window&&(!!/[#&](sv_code|sv_error|sso)=/.test(window.location.hash||"")||Sn(Cn()))}function _n(e,t){const n=Ee(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 Tn{constructor(e){this.renderer=null,this.launcher=null,this.config=e,this.api=new Ue(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(!wn.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={}){if(!Tn.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 t=e.nonce??(await this.api.drawAuthorizationValues()).nonce,n={identity:{providers:[{configURL:`${this.config.identityBaseUrl}/${this.config.accountId}/fedcm/config.json`,clientId:this.config.clientId,nonce:t}]},...e.mediation?{mediation:e.mediation}:{}};let i;try{const e=navigator.credentials.get.bind(navigator.credentials);i=await e(n)}catch(e){throw function(e){if("object"!=typeof e||null===e)return null;const{name:t,error:n}=e;return"IdentityCredentialError"!==t?null:new U("string"==typeof n?n:"")}(e)??new D(e instanceof Error?e.message:void 0)}const s=i?.token;if(!s)throw new M("FedCM did not return a token");const o=this.decodeToken(s);return{token:s,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={}){return this.runFlow(e)}async runFlow(e={}){this.launcher&&(this.launcher.close(),this.launcher=null),this.renderer&&this.renderer.close(),this.api.resetSession();const t={...e,backdropBlur:e.backdropBlur??this.config.backdropBlur},n=!!e.target,i="local"===e.renderMode||n;let s,o;const r=new Promise((e,t)=>{s=e,o=t}),a={onSuccess:t=>{e.onSuccess?.(t),s(t)},onError:t=>{e.onError?.(t),o(t)},onCancel:()=>{const t=new D;e.onCancel?.(),o(t)}},l=e=>{this.renderer=new Jt(e,this.api,t,a),this.renderer.start().catch(e=>{this.renderer?.showStartupError(e)})};if(!i){if(await this.preloadedConfigPermanentlyFailed())return l(new un),r;if("redirect"===t.flow){try{await this.startRedirectFlow(t)||a.onError(new M("Sign-in requires browser session storage. Enable site data for this site and try again."))}catch(e){a.onError(e instanceof Error?e:new Error(String(e)))}return r}const e=t.email||t.phone||null;return this.markSignInPending(e),this.launcher=new fn(this.config,this.api,t,{onSuccess:e=>{this.clearSignInPending(),a.onSuccess(e)},onError:e=>{this.clearSignInPending(),a.onError(e)},onCancel:()=>{this.clearSignInPending(),a.onCancel()},onPopupClosedUnresolved:()=>this.clearSignInPending(),onPopupReopened:()=>this.markSignInPending(e),onPopupSevered:()=>this.startRedirectFlow(t)}),this.launcher.start(),r}return l(n?this.createInlineContainer(e.target,"bare"===e.chrome):new un),r}attach(e,t={}){return bn(e,async e=>{e.preventDefault();try{await this.signIn({email:t.email,phone:t.phone,authContext:t.authContext,prompt:t.prompt,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=_n(n,"Invalid token header");if("object"!=typeof s||null===s)throw new M("Invalid token header");const o=s.alg;if("string"!=typeof o||!kn.includes(o))throw new M("Unsupported token algorithm");const r=_n(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}(r))throw new M("Invalid token payload structure");const a=Math.floor(Date.now()/1e3);if(r.exp<a)throw new M("Token has expired");const l=`${this.config.identityBaseUrl}/${this.config.accountId}`;if(r.iss!==l)throw new M("Invalid token issuer");if(r.aud!==this.config.accountId)throw new M("Invalid token audience");return r}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.fresh&&await this.startRecoveryBounce(n.hint),null}async consumeHandoffFragment(e,t){const n=e.get("sv_code"),i=e.get("sv_error");this.clearSignInPending();let s=null,o=null;try{s=sessionStorage.getItem("sv_oauth_state"),o=sessionStorage.getItem("sv_pkce_verifier"),this.clearOneShotAuthState()}catch{}this.clearUrlFragment();try{if(i){if("cancelled"===i)return t.onCancel?.(),null;throw new I("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(!o)throw new M("Sign-in session was lost — please sign in again.");const r=await this.api.redeemHandoffCode(n,o),a={token:r.token,identity:r.identity,identityType:r.identity_type,svid:r.svid??void 0,sessionId:r.session_id??void 0,refreshToken:r.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=new URL(`${this.config.identityBaseUrl}/${this.config.accountId}/sso`);e&&t.searchParams.set("login_hint",e);const n=await this.prepareHandoffNavigation(t.toString());n&&window.location.assign(n)}async startRedirectFlow(e){const t=e.authContext;if(t?.authRequestId||t?.simpleMode?.sessionId)return window.location.assign(De(this.config,e)),!0;const n=await this.prepareHandoffNavigation(De(this.config,e),t=>De(this.config,e,t));return!!n&&(window.location.assign(n),!0)}async prepareHandoffNavigation(e,t){const{state:n,codeVerifier:i}=await this.api.drawAuthorizationValues();let s;try{s=await async function(e){const t=await crypto.subtle.digest("SHA-256",(new TextEncoder).encode(e));return Se(new Uint8Array(t))}(i)}catch{return null}try{sessionStorage.setItem("sv_oauth_state",n),sessionStorage.setItem("sv_pkce_verifier",i)}catch{return null}const o=ze();if(t)return t({redirectUri:o,state:n,codeChallenge:s});const r=new URL(e);return r.searchParams.set("redirect_uri",o),r.searchParams.set("state",n),r.searchParams.set("code_challenge",s),r.toString()}markSignInPending(e){try{sessionStorage.setItem(xn,JSON.stringify({at:Date.now(),hint:e}))}catch{}}clearSignInPending(){try{sessionStorage.removeItem(xn)}catch{}}consumeSignInPending(){const e=Cn(),t=Sn(e);return this.clearSignInPending(),{fresh:t,hint:t?e.hint: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("token");if(!t)return null;try{let n=null;try{n=sessionStorage.getItem("sv_oauth_state")}catch{}if(!n||e.get("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{}}}close(){this.launcher&&(this.launcher.close(),this.launcher=null),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 je&&("ORIGIN_NOT_ALLOWED"===e.code||"product_not_configured"===e.code)}}createInlineContainer(e,t=!1){return new gn(yn(e),{bare:t})}async render(e){const t=await this.consumeRedirectResult();return t?(e.onSuccess?.(t),t):this.runFlow(e)}}const An=/^[A-Za-z0-9_.:-]+$/,In=Object.freeze(["seen","read","archived"]),$n=Object.freeze(["seen","read"]),Ln=Object.freeze({alert:Object.freeze({category:"alert",delivery:"plaintext",policy:Object.freeze({verification_level:"none",interaction:"view"})}),secureMessage:Object.freeze({category:"secure",channels:Object.freeze(["email"]),policy:Object.freeze({verification_level:"identifier",interaction:"view"})}),conversation:Object.freeze({category:"conversation",channels:Object.freeze(["in_app","email"]),policy:Object.freeze({verification_level:"identifier",interaction:"reply"})}),approval:Object.freeze({category:"approval",channels:Object.freeze(["in_app","email"]),policy:Object.freeze({verification_level:"identifier",interaction:"approve"})}),signatureRequest:Object.freeze({category:"signature",channels:Object.freeze(["in_app","email"]),policy:Object.freeze({verification_level:"identifier",interaction:"sign"})})});Object.freeze([...new Set(Object.values(Ln).map(e=>e.category))]);const Bn=In,Mn=$n,Pn=Object.freeze(Object.fromEntries(Object.keys(Ln).map(e=>{const{category:t,delivery:n,channels:i,policy:s}=Ln[e],o={category:t,...n?{delivery:n}:{},...i?{channels:i}:{},policy:Object.freeze({verificationLevel:s.verification_level,interaction:s.interaction})};return[e,Object.freeze(o)]})));function Rn(e,t){const n=Pn[e];if(!n)throw new M(`Unknown notify preset "${e}" (valid: ${Object.keys(Pn).join(", ")})`,{field:"preset",received:e});return function(e,t){const n={...t,category:t.category||e.category,delivery:t.delivery??e.delivery,policy:{...e.policy}};for(const[e,i]of Object.entries(t.policy??{}))null!=i&&(n.policy[e]=i);const i=t.channels||e.channels;return i&&(n.channels=[...i]),n}(n,t)}class Nn{constructor(e){this.http=e}async send(e){if(void 0!==e?.sendId&&!("string"==typeof(t=e.sendId)&&t.length>0&&t.length<=128&&An.test(t)))throw new M("sendId must be 1-128 characters of letters, digits, and _ . : -",{field:"sendId",received:e.sendId});var t;if(!Array.isArray(e?.recipients)||0===e.recipients.length)throw new M("recipients is required and must be non-empty",{field:"recipients"});if(Boolean(e.content)===Boolean(e.ingot))throw new M("Provide exactly one content source: content OR ingot");if(e.ingot&&(!e.ingot.vault?.id||!e.ingot.vault.vatToken))throw new M("An ingot send requires its vault unsealed with sv.vaults.unseal (ingot.vault): only a key holder may send a vault file",{field:"ingot.vault"});return(await this.http.post(Be`/v1/products/notify/send`,function(e){return{send_id:e.sendId,recipients:e.recipients,content:e.content?{payload:e.content.payload,content_type:e.content.contentType,filename:e.content.filename,ttl_minutes:e.content.ttlMinutes}:void 0,ingot:e.ingot?{ingot_id:e.ingot.ingotId,vault_id:e.ingot.vault.id}:void 0,delivery:e.delivery,policy:e.policy?{verification_level:e.policy.verificationLevel,interaction:e.policy.interaction,reveal_freshness_minutes:e.policy.revealFreshnessMinutes,action_hash:e.policy.actionHash}:void 0,channels:e.channels,escalation:e.escalation,title:e.title,category:e.category,type:e.type,instructions:e.instructions,history_ttl_days:e.historyTtlDays}}(e),{vat:e.ingot?.vault.vatToken})).data}async sendAlert(e){return this.send(Rn("alert",e))}async sendSecureMessage(e){return this.send(Rn("secureMessage",e))}async sendConversation(e){return this.send(Rn("conversation",e))}async sendApproval(e){return this.send(Rn("approval",e))}async sendSignatureRequest(e){return this.send(Rn("signatureRequest",e))}async getInbox(e){On(e?.recipientId);return(await this.http.get(Be`/v1/products/notify/inbox`,{query:{recipient_id:e.recipientId,state:e.state,limit:e.limit,cursor:e.cursor}})).data}async markInboxState(e,t){const n=Me(e,"notificationId");if(On(t?.recipientId),!Number.isInteger(t?.createdAt))throw new M("createdAt (the row's created_at) is required",{field:"createdAt",received:t?.createdAt});if(!Bn.includes(t.state))throw new M(`state must be one of ${Bn.join(", ")}`,{field:"state",received:t.state});return(await this.http.post(Be`/v1/products/notify/inbox/${n}/state`,{recipient_id:t.recipientId,created_at:t.createdAt,state:t.state})).data}async markInboxAll(e){if(On(e?.recipientId),!Mn.includes(e.state))throw new M(`state must be one of ${Mn.join(", ")} (archive per-row instead)`,{field:"state",received:e.state});return(await this.http.post(Be`/v1/products/notify/inbox/state`,{recipient_id:e.recipientId,state:e.state,cursor:e.cursor})).data}async listSends(e={}){return(await this.http.get(Be`/v1/products/notify/sends`,{query:{limit:e.limit,cursor:e.cursor}})).data}async recallSend(e,t={}){if(zn(e),void 0!==t.recipientIds&&(!Array.isArray(t.recipientIds)||0===t.recipientIds.length))throw new M("recipientIds must be a non-empty array; omit it entirely to recall the whole audience",{field:"recipientIds",received:t.recipientIds});if(void 0!==t.mode&&"grant"!==t.mode&&"content"!==t.mode)throw new M("mode must be 'grant' or 'content'",{field:"mode",received:t.mode});return(await this.http.post(Be`/v1/products/notify/sends/${e}/recall`,{recipient_ids:t.recipientIds,mode:t.mode})).data}async getSendStatus(e){zn(e);return(await this.http.get(Be`/v1/products/notify/sends/${e}/status`)).data}async listReceipts(e={}){return(await this.http.get(Be`/v1/products/notify/receipts`,{query:{limit:e.limit,cursor:e.cursor,interaction:e.interaction}})).data}async getSendReceipts(e,t={}){zn(e);return(await this.http.get(Be`/v1/products/notify/sends/${e}/receipts`,{query:{cursor:t.cursor}})).data}async getConfig(){return(await this.http.get(Be`/v1/products/notify/config`)).data}async updateConfig(e){if(!e||"object"!=typeof e||Array.isArray(e))throw new M("config patch must be an object");return(await this.http.put(Be`/v1/products/notify/config`,e)).data}async getEmailSender(){return(await this.http.get(Be`/v1/products/notify/email-sender`)).data}}function On(e){if(!e||"string"!=typeof e)throw new M("recipientId is required",{field:"recipientId"})}function zn(e){if(!e||"string"!=typeof e)throw new M("sendId is required",{field:"sendId"})}class Dn{constructor(e,t=new ve(e)){this.identity=new Tn(e),this.notify=new Nn(t)}}const Un=Object.freeze({min:12,max:32});new RegExp(`^[A-Za-z0-9]{${Un.min},${Un.max}}$`);const Hn=Object.freeze({INVALID:"invalid_url",NOT_HTTPS:"not_https",UNSAFE_PARTS:"unsafe_parts",HOST:"host_not_allowed",OPERATION:"wrong_operation",ISTK:"bad_istk"}),Fn=/^[A-Za-z0-9_-]+$/,Vn=/^[A-Za-z0-9_-]+$/,jn=/^[\x21-\x7e]+$/,qn=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)([^?#]*)(?:\?([^#]*))?(#.*)?$/,Wn=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*$/;function Kn(e){return"forge.sparkvault.com"===e}function Gn(e,{operation:t,isAllowedHost:n=Kn}){const i=Xn(e);if(!i.ok)return i;if(!n(i.hostname))return Qn(Hn.HOST);if(i.path!==`/${t}`)return Qn(Hn.OPERATION);const s=function(e,t){const n=[];for(const i of(e??"").split("&")){if(!i)continue;const e=i.indexOf("=");Jn(-1===e?i:i.slice(0,e))===t&&n.push(-1===e?"":Jn(i.slice(e+1)))}return n}(i.query,"istk");if(1!==s.length||!Fn.test(s[0]))return Qn(Hn.ISTK);const o=`https://${i.hostname}`;return{ok:!0,origin:o,endpoint:`${o}/${t}`,istk:s[0]}}function Yn(e,t){const n=Xn(t);if(!n.ok||void 0!==n.query||"string"!=typeof e||!jn.test(e))return null;const i=`https://${n.hostname}`;let s=null;if(e.startsWith(`${i}/`)?s=e.slice(i.length):e.startsWith("/")&&!e.startsWith("//")&&(s=e),null===s||!s.startsWith(`${n.path}/`))return null;const o=s.slice(n.path.length+1);return Vn.test(o)?`${i}${n.path}/${o}`:null}function Xn(e){if("string"!=typeof e||!jn.test(e))return Qn(Hn.INVALID);const t=qn.exec(e);if(!t)return Qn(Hn.INVALID);const[,n,i,s,o,r]=t;if("https"!==n.toLowerCase())return Qn(Hn.NOT_HTTPS);if(i.includes("@")||/:[0-9]*$/.test(i)||void 0!==r)return Qn(Hn.UNSAFE_PARTS);const a=i.toLowerCase();return Wn.test(a)?{ok:!0,hostname:a,path:s,query:o}:Qn(Hn.HOST)}function Jn(e){const t=e.replace(/\+/g," ");try{return decodeURIComponent(t)}catch{return t}}function Qn(e){return{ok:!1,reason:e}}class Zn extends I{constructor(e,t,n,i,s){super(e,t,n,i,s?.retryAfterMs??null),this.name="UploadApiError",this.verdict=s?.verdict??a.REFUSED,this.serverOffset=s?.offset??null,Object.setPrototypeOf(this,Zn.prototype)}}const ei="1.0.0";function ti(e){if(null===e||!/^\d+$/.test(e.trim()))return null;const t=Number(e);return Number.isSafeInteger(t)&&t>0?t:null}function ni(e){if(null===e||!/^\d+$/.test(e.trim()))return null;const t=Number(e);return Number.isSafeInteger(t)?t:null}const ii=new Map([[n.UPLOAD_POOL_FULL,"This upload could not be saved: the owner's storage cannot take the file."],[n.UPLOAD_SUPERSEDED,"This upload was not saved: a newer upload of this file replaced it."],[o,"This vault is scheduled for deletion. Cancel its deletion in vault settings before accessing its contents."]]);function si(e,t,n,i){return new Zn(t??ii.get(e)??"This upload could not be saved: the server refused it.","upload_refused",n,{status:n,coreCode:e},i)}function oi(e,t,n,s){return i.includes(e)?si(e,t,n,{verdict:a.REFUSED,retryAfterMs:s,offset:null,coreCode:e}):null}function ri(e){return!(e instanceof I)||e instanceof Zn||void 0===e.statusCode?e:oi(e.code,e.message,e.statusCode,e.retryAfterMs)??e}function ai(){return new Zn("Upload cancelled","cancelled",0)}function li(){if("undefined"==typeof XMLHttpRequest)throw new Zn("XMLHttpRequest is required for browser uploads","environment_unsupported",0)}function di(){return"undefined"!=typeof navigator&&!1===navigator.onLine}const ci=new WeakSet,ui=new Set(["session_gone","upload_refused","cancelled"]);function hi(e){return e instanceof Zn&&!ui.has(e.code)&&e.verdict!==a.RESYNC&&ci.add(e),e}function pi(e){return e instanceof Zn&&ci.has(e)}function mi(e){if(e instanceof Zn)return e;throw e}function fi(e){return new Zn("Upload could not be finished: the server has ended this upload session. Please upload the file again.","session_gone",e.statusCode??0,{status:e.statusCode,...e.details},{verdict:a.GONE,retryAfterMs:null,offset:null,coreCode:null})}async function vi(e,t,n,i){const{verdict:s,retryAfterMs:o}=t;if(s===a.DEFERRED){if(!e.deferred(o))throw t}else{if(s!==a.RETRY)throw t;if(di())return await(r=i,new Promise((e,t)=>{if(r.aborted)return void t(ai());const n=e=>{globalThis.removeEventListener("online",i),r.removeEventListener("abort",s),e()},i=()=>n(e),s=()=>n(()=>t(ai()));globalThis.addEventListener("online",i),r.addEventListener("abort",s,{once:!0}),di()||n(e)})),void e.alive();if(!e.failed(s,o))throw t}var r;const l=E({attempt:e.attempt,retryAfterMs:o,jitterKey:n});await function(e,t){return new Promise((n,i)=>{if(t.aborted)return void i(ai());const s=()=>{clearTimeout(o),i(ai())},o=setTimeout(()=>{t.removeEventListener("abort",s),n()},e);t.addEventListener("abort",s,{once:!0})})}(l,i)}function gi(e,t){const n=e.body?W(e):null,i=u({status:e.status,headers:e.header,details:n?.details??null,receipt:t.receipt});if(i.verdict===a.OK)return{outcome:i,failure:null};const{status:s}=e;if(i.verdict===a.REFUSED&&null!==i.coreCode)return{outcome:i,failure:si(i.coreCode,n?.message??null,s,i)};if(i.verdict===a.DEFERRED)return{outcome:i,failure:new Zn("The server received every byte of this file and is still saving it. It finishes on its own.",r,s,{status:s},i)};const o=e.body.replace(/\s+/g," ").trim().slice(0,200);return{outcome:i,failure:new Zn(t.failureMessage,t.code,s,{status:s,...o?{serverDetail:o}:{},...null!==i.coreCode?{coreCode:i.coreCode}:{}},i)}}const yi={name:"Upload session creation",code:"tus_create_failed",failureMessage:"The upload could not be started: the server did not open an upload session.",networkMessage:"Unable to start the upload. Please check your connection and try again.",receipt:!1},bi={name:"Upload resume check",code:"resume_check_failed",failureMessage:"Upload could not be resumed: the server no longer recognizes this upload session.",networkMessage:"Unable to resume upload. Please check your connection and try again.",receipt:!1,timeoutMs:6e4},wi={name:"Upload finalization check",code:"finalization_check_failed",failureMessage:"Upload could not be confirmed: the server did not finalize the file.",networkMessage:"Unable to confirm upload. Please check your connection and try again.",receipt:!0,timeoutMs:6e4};class ki extends pe{constructor(e){super(e.timeout),this.vaultInfoMemo=new Map,this.config=e}makeError(e,t,n,i,s=null){const o=n>0?oi(t,e,n,s):null;if(o)return o;return new Zn(e,t,n,i,0===n&&"cancelled"!==t?u({status:0}):{verdict:a.REFUSED,retryAfterMs:s,offset:null,coreCode:null})}async request(e,t){const{data:n,status:i}=await this.rawRequest(`${this.config.apiBaseUrl}${e}`,t),s="object"==typeof n&&null!==n?n:null;return{data:s&&"data"in s?s.data:n,status:i,requestId:s?.meta?.request_id}}requireVaultId(e){if(!Z(e))throw new Zn("Invalid vault ID","invalid_vault_id",0,{field:"vaultId",received:e});return e}async getVaultUploadInfo(e){const t=this.vaultInfoMemo.get(e);if(t&&!t.pendingSignal?.aborted)return t.promise;const n={pendingSignal:this.getAbortSignal(),promise:this.fetchVaultUploadInfo(e)};this.vaultInfoMemo.set(e,n);try{const e=await n.promise;return n.pendingSignal=null,e}catch(t){throw this.vaultInfoMemo.get(e)===n&&this.vaultInfoMemo.delete(e),t}}async fetchVaultUploadInfo(e){const t=await this.request(Be`/v1/files/in/${this.requireVaultId(e)}`,{method:"GET"});if(!function(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.vault_id&&"string"==typeof t.vault_name&&"number"==typeof t.max_size_bytes&&"object"==typeof t.branding&&null!==t.branding&&"string"==typeof t.branding.organization_name&&"object"==typeof t.encryption&&null!==t.encryption&&"string"==typeof t.encryption.algorithm&&("active"===t.forge_status||"inactive"===t.forge_status)}(t.data))throw new Zn("Invalid vault upload info response from server","invalid_response",t.status);return{vaultId:(n=t.data).vault_id,vaultName:n.vault_name,maxSizeBytes:n.max_size_bytes,branding:{organizationName:n.branding.organization_name,logoLightUrl:n.branding.logo_light_url,logoDarkUrl:n.branding.logo_dark_url},encryption:{algorithm:n.encryption.algorithm,keyDerivation:n.encryption.key_derivation,postQuantum:n.encryption.post_quantum},forgeStatus:n.forge_status};var n}async initiateUpload(e,t,n,i,s,o){const r=Be`/v1/files/in/${this.requireVaultId(e)}/upload`,a={filename:t,size_bytes:n,content_type:i};o&&(a.folder_path=o);const l=await this.request(r,{method:"POST",body:JSON.stringify(a),headers:s?{"X-Vault-Access-Token":s}:void 0});if(!function(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.forge_url&&"string"==typeof t.ingot_id}(l.data))throw new Zn("Invalid initiate upload response from server","invalid_response",l.status);return{forgeUrl:l.data.forge_url,ingotId:l.data.ingot_id,requestId:"string"==typeof l.requestId&&l.requestId.length>0?l.requestId:null}}async uploadFileToForge(e,t,n,i){li();const s=Gn(t,{operation:"encrypt",isAllowedHost:e=>ce(this.config,e)});if(!s.ok)throw new Zn("Forge upload URL was refused","invalid_forge_url",0,{reason:s.reason});const o=this.getAbortSignal(),r=T(),a=await this.createTusSession(s.endpoint,s.istk,e.size,r,o),l=Yn(a.location,s.endpoint);if(!l)throw new Zn("Upload session is outside the upload endpoint","tus_create_failed",0);i?.(l),await this.sendFile(e,{uploadUrl:l,totalSize:e.size,chunkSize:a.chunkSize,budget:r,sessionSignal:o},0,n)}async resumeUploadToForge(e,t,n){li();const i=function(e,{operation:t,isAllowedHost:n=Kn}){const i=Xn(e);if(!i.ok)return i;if(!n(i.hostname))return Qn(Hn.HOST);const s=Yn(e,`https://${i.hostname}/${t}`);return null===s?Qn(Hn.OPERATION):{ok:!0,url:s}}(t,{operation:"encrypt",isAllowedHost:e=>ce(this.config,e)});if(!i.ok)throw new Zn("Forge upload session URL was refused","invalid_forge_url",0,{reason:i.reason});const s=this.getAbortSignal(),o=T(),r=await this.readSessionStanding(i.url,o,s);if(r.length!==e.size)throw new Zn("The upload session is for a file of another length","session_mismatch",0,{sessionLength:r.length,fileSize:e.size});const a={uploadUrl:i.url,totalSize:e.size,chunkSize:r.chunkSize,budget:o,sessionSignal:s};await this.sendFile(e,a,this.checkResumeOffset(r.offset,a),n)}async sendFile(e,t,n,i){let s=0;const o=i?(e,t)=>{e>s&&(s=e,i(e,t))}:void 0;for(o?.(n,e.size);;){if(t.sessionSignal.aborted)throw ai();if(n===e.size){const e=await this.confirmServerFinalized(t).catch(e=>{throw hi(e)});if(e.published)return;n=e.resumeAt;continue}const i=Math.min(n+t.chunkSize,e.size);try{n=await this.patchChunk(t,e.slice(n,i),n,o),t.budget.progressed()}catch(e){n=await this.offsetAfterFailure(t,e,n)}}}async offsetAfterFailure(e,t,n){let i=mi(t);for(;;){if(i.verdict===a.RESYNC)return this.resyncedOffset(e,i,n);await this.backOff(e,i);try{const t=await this.readResumeOffset(e);return t>n&&e.budget.progressed(),t}catch(e){i=mi(e)}}}resyncedOffset(e,t,n){const i=this.checkResumeOffset(t.serverOffset,e);if(i>n)e.budget.progressed();else if(!e.budget.failed(a.RESYNC))throw t;return i}async backOff(e,t){if(t.verdict===a.GONE)throw fi(t);await vi(e.budget,t,e.uploadUrl,e.sessionSignal)}async confirmServerFinalized(e){let t=0;for(;;)try{return await this.tusRequest(e.uploadUrl,{method:"PATCH",headers:{"Tus-Resumable":ei,"Upload-Offset":String(e.totalSize),"Content-Type":"application/offset+octet-stream"}},wi),{published:!0}}catch(n){const i=mi(n);if(t="timeout"===i.code?t+1:0,t>=2)throw i;if(i.verdict===a.RESYNC){const t=this.resyncedOffset(e,i,e.totalSize);if(t<e.totalSize)return{published:!1,resumeAt:t};continue}await this.backOff(e,i)}}async readSessionStanding(e,t,n){for(;;)try{const{response:n,outcome:i}=await this.tusRequest(e,{method:"HEAD",headers:{"Tus-Resumable":ei}},bi),s=n.headers.get("X-Chunk-Size"),o=ti(s);if(null===o)throw new Zn("Server did not return a valid X-Chunk-Size",bi.code,n.status,{header:"X-Chunk-Size",received:s});return t.progressed(),{offset:i.offset,length:ni(n.headers.get("Upload-Length")),chunkSize:o}}catch(i){const s=mi(i);if(s.verdict===a.GONE)throw fi(s);await vi(t,s,e,n)}}async readResumeOffset(e){return this.checkResumeOffset(await this.headUploadOffset(e.uploadUrl,bi),e)}checkResumeOffset(e,t){const n=function(e,{totalSize:t,chunkSize:n}){if(!Number.isSafeInteger(t)||t<0||!Number.isSafeInteger(n)||n<1)throw new TypeError("An upload's geometry is a whole length and a positive chunk size");return!Number.isSafeInteger(e)||e<0?A.INVALID:e>t?A.BEYOND_TOTAL:e!==t&&e%n!==0?A.MISALIGNED:null}(e,t);if(null===e||null!==n){const t=n===A.MISALIGNED?"misaligned":"invalid";throw new Zn(`Server returned ${t} upload offset (${e})`,"invalid_offset",0)}return e}async createTusSession(e,t,n,i,s){const o=S(e);let r;for(;;)try{({response:r}=await this.tusRequest(e,{method:"POST",headers:{"Tus-Resumable":ei,"Upload-Length":String(n),"X-ISTK":t}},yi));break}catch(e){const t=mi(e);if(t.verdict!==a.RETRY)throw t;await vi(i,t,o,s)}const l=r.headers.get("Location");if(!l)throw new Zn("Server did not return upload location","tus_create_failed",r.status);const d=r.headers.get("X-Chunk-Size"),c=ti(d);if(null===c)throw new Zn("Server did not return a valid X-Chunk-Size","tus_create_failed",r.status,{header:"X-Chunk-Size",received:d});return i.progressed(),{location:l,chunkSize:c}}patchChunk(e,t,n,i){const{uploadUrl:s,totalSize:o,budget:r}=e;return new Promise((a,l)=>{const d=e.sessionSignal;if(d.aborted)return void l(ai());const c=new XMLHttpRequest;let h=!1,p=!1,m=null;const f=()=>c.abort(),v=e=>{h||(h=!0,null!==m&&clearTimeout(m),d.removeEventListener("abort",f),e())},g=()=>{h||(null!==m&&clearTimeout(m),m=setTimeout(()=>{p=!0,c.abort()},6e4))};d.addEventListener("abort",f),c.upload.onprogress=e=>{g(),r.alive(),e.lengthComputable&&i?.(n+e.loaded,o)},c.onload=()=>{const{status:e}=c,{outcome:t,failure:i}=gi({status:e,header:e=>c.getResponseHeader(e),body:e>=200&&e<300?"":c.responseText},{receipt:!1,code:"chunk_upload_failed",failureMessage:`Chunk upload failed with status ${e}`});if(i)return void v(()=>l(i));const s=t.offset;v(null===s||s<=n||s>o?()=>l(new Zn(`Server returned invalid upload offset (${c.getResponseHeader("Upload-Offset")})`,"invalid_offset",c.status)):()=>a(s))},c.onerror=()=>v(()=>l(new Zn("Chunk upload failed","network_error",0,void 0,u({status:0})))),c.onabort=()=>v(()=>l(p?new Zn("Chunk upload timed out after 60000ms of inactivity","timeout",0,void 0,u({status:0})):ai())),c.open("PATCH",s),c.setRequestHeader("Tus-Resumable",ei),c.setRequestHeader("Upload-Offset",String(n)),c.setRequestHeader("Content-Type","application/offset+octet-stream"),g(),c.send(t)})}async headUploadOffset(e,t){const{response:n,outcome:i}=await this.tusRequest(e,{method:"HEAD",headers:{"Tus-Resumable":ei}},t);if(null===i.offset)throw new Zn(`${t.name} returned an invalid offset`,t.code,n.status);return i.offset}tusRequest(e,t,n){const i=n.timeoutMs??this.timeoutMs;return this.send(e,{method:t.method,headers:t.headers},{cancelled:"Upload cancelled",timeout:`${n.name} timed out after ${i}ms`,network:n.networkMessage},async e=>{const{outcome:t,failure:i}=gi({status:e.status,header:t=>e.headers.get(t),body:e.ok?"":await e.text().catch(()=>"")},n);if(i)throw i;return{response:e,outcome:t}},i)}}const xi="sparkvault-upload-styles";function Ci(){if(document.getElementById(xi))return;const e=document.createElement("style");e.id=xi,e.textContent=function(){const e={primary:Ht.action,primaryHover:Ht.actionHover,primaryLight:Ht.actionBg,error:Ht.error,errorLight:Ht.errorBg,errorBorder:Ft(Ht.error500,.35),errorText:Ht.errorText,success:Ht.success,successOnDark:Ht.success500,bg:Ht.white,bgSubtle:Ht.slate50,bgHover:Ht.slate100,bgDark:Ht.slate950,bgDarkSubtle:Ht.darkCard,overlay:Ht.modalOverlay,border:Ht.slate200,borderHover:Ht.slate300,borderDark:Ht.darkHairline,textPrimary:Ht.slate900,textSecondary:Ht.slate600,textMuted:Ht.slate500,textOnPrimary:Ht.white,textOnDark:Ht.darkText,textMutedOnDark:Ht.darkTextMuted,shadowSm:Ht.shadowSm,shadowLg:Ht.shadowPopover};return`\n /* ========================================\n OVERLAY & MODAL CONTAINER\n ======================================== */\n\n .svu-overlay {\n /* Force full-screen overlay regardless of page styles */\n position: fixed !important;\n top: 0 !important;\n left: 0 !important;\n right: 0 !important;\n bottom: 0 !important;\n width: 100vw !important;\n height: 100vh !important;\n max-width: none !important;\n max-height: none !important;\n margin: 0 !important;\n background: ${e.overlay};\n display: flex !important;\n align-items: center;\n justify-content: center;\n z-index: 999999 !important;\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 /* Break out of any containing block that could affect fixed positioning */\n transform: none !important;\n filter: none !important;\n contain: none !important;\n isolation: isolate;\n }\n\n .svu-overlay.svu-blur {\n backdrop-filter: blur(8px);\n -webkit-backdrop-filter: blur(8px);\n }\n\n .svu-modal {\n background: ${e.bg};\n border-radius: 16px;\n box-shadow: ${e.shadowLg};\n width: 100%;\n max-width: 480px;\n max-height: calc(100vh - 32px);\n display: flex;\n flex-direction: column;\n color: ${e.textPrimary};\n overflow: hidden;\n }\n\n .svu-modal.svu-with-sidebar {\n max-width: 900px;\n flex-direction: row;\n }\n\n .svu-modal-main {\n flex: 1;\n display: flex;\n flex-direction: column;\n min-width: 0;\n }\n\n /* Dark card variant for uploading/ceremony states */\n .svu-modal.svu-dark {\n background: ${e.bgDark};\n color: ${e.textOnDark};\n }\n\n /* ========================================\n HEADER\n ======================================== */\n\n .svu-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 14px 20px;\n border-bottom: 1px solid ${e.border};\n background: ${e.bg};\n flex-shrink: 0;\n }\n\n .svu-dark .svu-header {\n border-bottom-color: ${e.borderDark};\n background: ${e.bgDark};\n }\n\n .svu-header-title {\n display: flex;\n align-items: center;\n gap: 12px;\n min-width: 0;\n }\n\n .svu-logo {\n height: 28px;\n width: auto;\n max-width: 140px;\n object-fit: contain;\n flex-shrink: 0;\n }\n\n .svu-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 .svu-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: transparent;\n border: none;\n border-radius: 8px;\n cursor: pointer;\n color: ${e.textMuted};\n transition: background 0.15s ease, color 0.15s ease;\n }\n\n .svu-close-btn:hover {\n background: ${e.bgHover};\n color: ${e.textPrimary};\n }\n\n .svu-dark .svu-close-btn {\n color: ${e.textMutedOnDark};\n }\n\n .svu-dark .svu-close-btn:hover {\n background: ${e.bgDarkSubtle};\n color: ${e.textOnDark};\n }\n\n /* ========================================\n BODY\n ======================================== */\n\n .svu-body {\n padding: 24px 28px;\n overflow-y: auto;\n flex: 1;\n }\n\n /* ========================================\n FOOTER\n ======================================== */\n\n .svu-footer {\n padding: 10px 20px;\n border-top: 1px solid ${e.border};\n text-align: center;\n background: ${e.bgSubtle};\n flex-shrink: 0;\n }\n\n .svu-dark .svu-footer {\n border-top-color: ${e.borderDark};\n background: ${e.bgDarkSubtle};\n }\n\n .svu-footer-text {\n font-size: 10px;\n color: ${e.textMuted};\n letter-spacing: 0.02em;\n }\n\n .svu-dark .svu-footer-text {\n color: ${e.textMutedOnDark};\n }\n\n .svu-footer-link {\n color: ${e.textSecondary};\n text-decoration: none;\n font-weight: 500;\n transition: color 0.15s ease;\n }\n\n .svu-footer-link:hover {\n color: ${e.primary};\n }\n\n /* ========================================\n LOADING STATE\n ======================================== */\n\n .svu-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 .svu-spinner {\n width: 28px;\n height: 28px;\n border: 2.5px solid ${e.border};\n border-top-color: ${e.primary};\n border-radius: 50%;\n animation: svu-spin 0.7s linear infinite;\n }\n\n .svu-loading-text {\n font-size: 14px;\n color: ${e.textSecondary};\n margin: 0;\n }\n\n @keyframes svu-spin {\n to { transform: rotate(360deg); }\n }\n\n /* ========================================\n FORM VIEW\n ======================================== */\n\n .svu-form-view {\n display: flex;\n flex-direction: column;\n align-items: center;\n }\n\n .svu-title {\n font-size: 18px;\n font-weight: 600;\n letter-spacing: -0.02em;\n line-height: 1.3;\n margin: 0 0 6px 0;\n text-align: center;\n color: ${e.textPrimary};\n }\n\n .svu-dark .svu-title {\n color: ${e.textOnDark};\n }\n\n .svu-subtitle {\n font-size: 14px;\n font-weight: 400;\n line-height: 1.5;\n color: ${e.textSecondary};\n margin: 0 0 20px 0;\n text-align: center;\n }\n\n .svu-subtitle strong {\n color: ${e.textPrimary};\n font-weight: 500;\n }\n\n /* Drop Zone */\n .svu-drop-zone {\n width: 100%;\n border: 2px dashed ${e.border};\n border-radius: 12px;\n padding: 32px 24px;\n text-align: center;\n cursor: pointer;\n transition: border-color 0.15s ease, background 0.15s ease;\n margin-bottom: 16px;\n }\n\n .svu-drop-zone:hover {\n border-color: ${e.borderHover};\n background: ${e.bgSubtle};\n }\n\n .svu-drop-zone.svu-dragging {\n border-color: ${e.primary};\n background: ${e.primaryLight};\n }\n\n .svu-drop-zone.svu-has-file {\n border-style: solid;\n border-color: ${e.primary};\n background: ${e.primaryLight};\n cursor: default;\n }\n\n .svu-drop-icon {\n color: ${e.textMuted};\n margin-bottom: 12px;\n display: flex;\n justify-content: center;\n }\n\n .svu-drop-text {\n font-size: 14px;\n font-weight: 500;\n color: ${e.textPrimary};\n margin: 0 0 4px 0;\n }\n\n .svu-drop-subtext {\n font-size: 13px;\n color: ${e.textSecondary};\n margin: 0 0 8px 0;\n }\n\n .svu-drop-hint {\n font-size: 12px;\n color: ${e.textMuted};\n margin: 0;\n }\n\n /* Selected File */\n .svu-selected-file {\n display: flex;\n align-items: center;\n gap: 12px;\n width: 100%;\n }\n\n .svu-file-icon {\n color: ${e.primary};\n flex-shrink: 0;\n }\n\n .svu-file-info {\n flex: 1;\n min-width: 0;\n text-align: left;\n }\n\n .svu-file-name {\n display: block;\n font-size: 14px;\n font-weight: 500;\n color: ${e.textPrimary};\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n }\n\n .svu-file-size {\n display: block;\n font-size: 12px;\n color: ${e.textSecondary};\n }\n\n .svu-remove-file {\n flex-shrink: 0;\n width: 24px;\n height: 24px;\n display: flex;\n align-items: center;\n justify-content: center;\n background: transparent;\n border: none;\n border-radius: 50%;\n cursor: pointer;\n font-size: 18px;\n color: ${e.textMuted};\n transition: background 0.15s ease, color 0.15s ease;\n }\n\n .svu-remove-file:hover {\n background: ${e.bgHover};\n color: ${e.error};\n }\n\n /* Max Size */\n .svu-max-size {\n font-size: 12px;\n color: ${e.textMuted};\n margin: 0 0 16px 0;\n }\n\n /* Upload Button */\n .svu-btn {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n gap: 8px;\n width: 100%;\n padding: 12px 20px;\n font-size: 14px;\n font-weight: 500;\n letter-spacing: -0.005em;\n line-height: 1.4;\n border: none;\n border-radius: 8px;\n cursor: pointer;\n transition: background 0.15s ease, transform 0.1s ease;\n box-sizing: border-box;\n }\n\n .svu-btn:disabled {\n opacity: 0.5;\n cursor: not-allowed;\n }\n\n .svu-btn:active:not(:disabled) {\n transform: scale(0.98);\n }\n\n .svu-btn-primary {\n background: ${e.primary};\n color: ${e.textOnPrimary};\n box-shadow: ${e.shadowSm};\n }\n\n .svu-btn-primary:hover:not(:disabled) {\n background: ${e.primaryHover};\n }\n\n .svu-btn-secondary {\n background: ${e.bgSubtle};\n color: ${e.textPrimary};\n border: 1px solid ${e.border};\n }\n\n .svu-btn-secondary:hover:not(:disabled) {\n background: ${e.bgHover};\n }\n\n /* Error Alert */\n .svu-error-alert {\n background: ${e.errorLight};\n border: 1px solid ${e.errorBorder};\n color: ${e.error};\n padding: 10px 12px;\n border-radius: 8px;\n font-size: 13px;\n font-weight: 450;\n margin-bottom: 16px;\n width: 100%;\n }\n\n /* Metadata Grid */\n .svu-metadata {\n width: 100%;\n margin-top: 20px;\n padding-top: 20px;\n border-top: 1px solid ${e.border};\n }\n\n .svu-metadata h4 {\n font-size: 12px;\n font-weight: 600;\n color: ${e.textSecondary};\n text-transform: uppercase;\n letter-spacing: 0.05em;\n margin: 0 0 12px 0;\n }\n\n .svu-metadata-grid {\n display: grid;\n grid-template-columns: 1fr 1fr;\n gap: 8px;\n }\n\n .svu-metadata-item {\n font-size: 12px;\n }\n\n .svu-metadata-item.svu-full-width {\n grid-column: span 2;\n }\n\n .svu-metadata-label {\n display: block;\n color: ${e.textMuted};\n margin-bottom: 2px;\n }\n\n .svu-metadata-value {\n display: block;\n color: ${e.textPrimary};\n font-weight: 500;\n }\n\n .svu-metadata-value.svu-status-active {\n color: ${e.success};\n }\n\n /* ========================================\n UPLOADING VIEW\n ======================================== */\n\n .svu-uploading-view {\n display: flex;\n flex-direction: column;\n align-items: center;\n }\n\n .svu-stages {\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 12px;\n margin: 24px 0;\n width: 100%;\n }\n\n .svu-stage {\n display: flex;\n flex-direction: column;\n align-items: center;\n gap: 8px;\n opacity: 0.5;\n transition: opacity 0.3s ease;\n }\n\n .svu-stage.svu-active {\n opacity: 1;\n }\n\n .svu-stage span {\n font-size: 11px;\n color: ${e.textMutedOnDark};\n }\n\n .svu-stage-sub {\n font-size: 10px !important;\n color: ${e.primary} !important;\n }\n\n .svu-stage-arrow {\n width: 24px;\n height: 2px;\n background: ${e.borderDark};\n position: relative;\n }\n\n .svu-stage-arrow.svu-active::after {\n content: '';\n position: absolute;\n left: 0;\n top: 0;\n height: 100%;\n background: ${e.primary};\n animation: svu-arrow-flow 1s ease-in-out infinite;\n }\n\n @keyframes svu-arrow-flow {\n 0% { width: 0; }\n 50% { width: 100%; }\n 100% { width: 100%; }\n }\n\n /* Progress Bar */\n .svu-progress {\n width: 100%;\n margin: 20px 0;\n }\n\n .svu-progress-bar {\n width: 100%;\n height: 6px;\n background: ${e.borderDark};\n border-radius: 3px;\n overflow: hidden;\n }\n\n .svu-progress-fill {\n height: 100%;\n background: ${e.primary};\n border-radius: 3px;\n transition: width 0.3s ease;\n }\n\n .svu-progress-text {\n display: flex;\n justify-content: space-between;\n margin-top: 8px;\n font-size: 12px;\n color: ${e.textMutedOnDark};\n }\n\n /* Forging Info */\n .svu-forging-info {\n width: 100%;\n margin-top: 20px;\n padding: 16px;\n background: ${e.bgDarkSubtle};\n border-radius: 8px;\n }\n\n .svu-forging-line {\n font-size: 12px;\n color: ${e.textMutedOnDark};\n margin: 0 0 8px 0;\n }\n\n .svu-forging-line:last-child {\n margin-bottom: 0;\n }\n\n .svu-mono {\n font-family: ui-monospace, SFMono-Regular, 'SF Mono', Menlo, Monaco, monospace;\n color: ${e.textOnDark};\n }\n\n /* ========================================\n CEREMONY VIEW\n ======================================== */\n\n .svu-ceremony-view {\n display: flex;\n flex-direction: column;\n align-items: center;\n }\n\n .svu-ceremony-steps {\n width: 100%;\n margin: 20px 0;\n }\n\n .svu-ceremony-step {\n display: flex;\n align-items: center;\n gap: 12px;\n padding: 10px 0;\n opacity: 0.4;\n transition: opacity 0.3s ease;\n }\n\n .svu-ceremony-step.svu-active {\n opacity: 1;\n }\n\n .svu-ceremony-step.svu-complete {\n opacity: 0.7;\n }\n\n .svu-step-icon {\n width: 20px;\n height: 20px;\n display: flex;\n align-items: center;\n justify-content: center;\n color: ${e.primary};\n }\n\n .svu-step-text {\n font-size: 13px;\n color: ${e.textOnDark};\n }\n\n /* Spinning loader */\n .svu-step-icon .svu-spin {\n animation: svu-spin 0.7s linear infinite;\n }\n\n /* ========================================\n COMPLETE VIEW\n ======================================== */\n\n .svu-complete-view {\n display: flex;\n flex-direction: column;\n align-items: center;\n animation: svu-scale-in 0.3s ease;\n }\n\n @keyframes svu-scale-in {\n from {\n opacity: 0;\n transform: scale(0.95);\n }\n to {\n opacity: 1;\n transform: scale(1);\n }\n }\n\n .svu-success-icon {\n color: ${e.success};\n margin-bottom: 16px;\n }\n\n .svu-success-title {\n font-size: 20px;\n font-weight: 600;\n color: ${e.textPrimary};\n margin: 0 0 24px 0;\n text-align: center;\n }\n\n .svu-success-details {\n width: 100%;\n background: ${e.bgSubtle};\n border-radius: 8px;\n padding: 16px;\n margin-bottom: 16px;\n }\n\n .svu-success-row {\n display: flex;\n justify-content: space-between;\n align-items: center;\n padding: 8px 0;\n font-size: 13px;\n border-bottom: 1px solid ${e.border};\n }\n\n .svu-success-row:last-child {\n border-bottom: none;\n }\n\n .svu-success-label {\n color: ${e.textSecondary};\n }\n\n .svu-success-value {\n color: ${e.textPrimary};\n font-weight: 500;\n display: flex;\n align-items: center;\n gap: 8px;\n }\n\n .svu-copy-btn {\n width: 24px;\n height: 24px;\n display: flex;\n align-items: center;\n justify-content: center;\n background: transparent;\n border: none;\n border-radius: 4px;\n cursor: pointer;\n color: ${e.textMuted};\n transition: background 0.15s ease, color 0.15s ease;\n }\n\n .svu-copy-btn:hover {\n background: ${e.bgHover};\n color: ${e.primary};\n }\n\n .svu-success-guidance {\n font-size: 13px;\n color: ${e.textSecondary};\n text-align: center;\n margin: 0 0 20px 0;\n line-height: 1.5;\n }\n\n /* ========================================\n ERROR VIEW\n ======================================== */\n\n .svu-error-view {\n display: flex;\n flex-direction: column;\n align-items: center;\n text-align: center;\n }\n\n .svu-error-icon {\n color: ${e.error};\n margin-bottom: 16px;\n }\n\n .svu-error-title {\n font-size: 18px;\n font-weight: 600;\n color: ${e.textPrimary};\n margin: 0 0 8px 0;\n }\n\n .svu-error-message {\n font-size: 14px;\n color: ${e.textSecondary};\n margin: 0 0 16px 0;\n line-height: 1.5;\n }\n\n .svu-error-code {\n display: inline-flex;\n align-items: center;\n gap: 6px;\n padding: 6px 10px;\n background: ${e.errorLight};\n border: 1px solid ${e.errorBorder};\n border-radius: 6px;\n margin-bottom: 20px;\n }\n\n .svu-error-code-label {\n font-size: 10px;\n font-weight: 600;\n color: ${e.errorText};\n text-transform: uppercase;\n letter-spacing: 0.05em;\n }\n\n .svu-error-code-value {\n font-size: 11px;\n font-family: ui-monospace, SFMono-Regular, 'SF Mono', Menlo, Monaco, monospace;\n color: ${e.error};\n font-weight: 500;\n }\n\n /* ========================================\n SECURITY SIDEBAR\n ======================================== */\n\n .svu-sidebar {\n width: 320px;\n background: ${e.bgDark};\n border-left: 1px solid ${e.borderDark};\n color: ${e.textOnDark};\n padding: 20px;\n overflow-y: auto;\n flex-shrink: 0;\n }\n\n .svu-sidebar-logo {\n margin-bottom: 20px;\n }\n\n .svu-sidebar-logo img {\n height: 24px;\n width: auto;\n }\n\n .svu-sidebar-intro h3 {\n font-size: 14px;\n font-weight: 600;\n margin: 0 0 8px 0;\n }\n\n .svu-sidebar-intro p {\n font-size: 12px;\n color: ${e.textMutedOnDark};\n line-height: 1.5;\n margin: 0 0 20px 0;\n }\n\n .svu-sidebar-security h4 {\n display: flex;\n align-items: center;\n gap: 8px;\n font-size: 12px;\n font-weight: 600;\n margin: 0 0 12px 0;\n }\n\n .svu-security-intro {\n font-size: 11px;\n color: ${e.textMutedOnDark};\n line-height: 1.5;\n margin: 0 0 16px 0;\n }\n\n .svu-security-intro strong {\n color: ${e.textOnDark};\n }\n\n .svu-key-chain {\n display: flex;\n flex-direction: column;\n gap: 8px;\n margin-bottom: 16px;\n }\n\n .svu-key-item {\n display: flex;\n gap: 12px;\n padding: 10px;\n background: ${e.bgDarkSubtle};\n border-radius: 6px;\n }\n\n .svu-key-number {\n width: 20px;\n height: 20px;\n background: ${e.primary};\n color: ${e.textOnPrimary};\n border-radius: 50%;\n font-size: 11px;\n font-weight: 600;\n display: flex;\n align-items: center;\n justify-content: center;\n flex-shrink: 0;\n }\n\n .svu-key-info {\n flex: 1;\n }\n\n .svu-key-name {\n display: block;\n font-size: 11px;\n font-weight: 600;\n color: ${e.textOnDark};\n margin-bottom: 2px;\n }\n\n .svu-key-algo {\n display: block;\n font-size: 10px;\n color: ${e.primary};\n margin-bottom: 4px;\n }\n\n .svu-key-desc {\n display: block;\n font-size: 10px;\n color: ${e.textMutedOnDark};\n line-height: 1.4;\n }\n\n .svu-key-connector {\n display: flex;\n justify-content: center;\n color: ${e.textMutedOnDark};\n }\n\n .svu-encryption-result {\n display: flex;\n gap: 8px;\n font-size: 10px;\n color: ${e.textMutedOnDark};\n line-height: 1.5;\n padding: 10px;\n background: ${e.bgDarkSubtle};\n border-radius: 6px;\n margin-bottom: 16px;\n }\n\n .svu-encryption-result svg {\n color: ${e.successOnDark};\n flex-shrink: 0;\n }\n\n .svu-encryption-result strong {\n color: ${e.textOnDark};\n }\n\n .svu-security-badges {\n display: flex;\n flex-wrap: wrap;\n gap: 6px;\n }\n\n .svu-tls-badge {\n font-size: 9px;\n font-weight: 500;\n padding: 4px 8px;\n background: ${e.bgDarkSubtle};\n border-radius: 4px;\n color: ${e.textMutedOnDark};\n }\n\n /* ========================================\n INLINE CONTAINER\n ======================================== */\n\n .svu-inline-container {\n display: flex;\n flex-direction: column;\n width: 100%;\n height: 100%;\n box-sizing: border-box;\n background: ${e.bg};\n color: ${e.textPrimary};\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 ${e.border};\n overflow: hidden;\n }\n\n /* ========================================\n RESPONSIVE\n ======================================== */\n\n @media (max-width: 768px) {\n .svu-modal.svu-with-sidebar {\n flex-direction: column;\n max-width: 480px;\n }\n\n .svu-sidebar {\n width: 100%;\n border-left: none;\n border-top: 1px solid ${e.borderDark};\n max-height: 300px;\n }\n }\n\n @media (max-width: 480px) {\n .svu-modal {\n max-width: 100%;\n max-height: 100%;\n border-radius: 0;\n }\n\n .svu-overlay {\n padding: 0;\n }\n\n .svu-body {\n padding: 20px;\n }\n }\n\n /* ========================================\n ACCESSIBILITY\n ======================================== */\n\n .svu-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 `}(),document.head.appendChild(e)}const Si="svu-modal-title",Ei={organizationName:"",logoLightUrl:null,logoDarkUrl:null};class _i{constructor(){this.shell=null,this.header=null,this.body=null,this.sidebar=null,this.onCloseCallback=null,this.isDarkMode=!1,this.branding=Ei}createLoading(e,t){if(this.shell)return;this.onCloseCallback=t,this.branding=Ei,Ci(),this.shell=new rn({overlayId:"sparkvault-upload-overlay",modalId:"sparkvault-upload-modal",classPrefix:"svu",titleId:Si,backdropBlur:!1!==e.backdropBlur,onDismiss:()=>this.handleClose()});const n=document.createElement("div");n.className="svu-modal-main",this.header=this.createHeader(),this.body=document.createElement("div"),this.body.className="svu-body",n.append(this.header,this.body,an("svu")),this.shell.modal.appendChild(n)}createHeader(){return function(e){const{branding:t,isDarkMode:n,titleId:i,onClose:s}=e,o=document.createElement("div");o.className="svu-header";const r=document.createElement("div");r.className="svu-header-title";const a=ln(n,t.logoLightUrl,t.logoDarkUrl);if(a){const e=document.createElement("img");e.className="svu-logo",e.src=a,e.alt=t.organizationName,r.appendChild(e);const n=document.createElement("span");n.className="svu-sr-only",n.id=i,n.textContent=t.organizationName,r.appendChild(n)}else if(t.organizationName){const e=document.createElement("h2");e.className="svu-company-name",e.id=i,e.textContent=t.organizationName,r.appendChild(e)}const l=document.createElement("button");return l.className="svu-close-btn",l.type="button",l.setAttribute("aria-label","Close"),l.innerHTML='\n <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">\n <path d="M18 6L6 18M6 6l12 12"/>\n </svg>\n ',l.addEventListener("click",s),o.append(r,l),o}({branding:this.branding,isDarkMode:this.isDarkMode,titleId:Si,onClose:()=>this.handleClose()})}refreshHeader(){if(!this.header)return;const e=this.createHeader();e.style.display=this.header.style.display,this.header.replaceWith(e),this.header=e}updateBranding(e){this.shell&&(this.branding=e,this.refreshHeader())}setDarkMode(e){this.shell&&this.isDarkMode!==e&&(this.isDarkMode=e,this.shell.modal.classList.toggle("svu-dark",e),this.refreshHeader())}toggleSidebar(e){this.shell&&(e&&!this.sidebar?(this.sidebar=function(e){const t=document.createElement("div");t.className="svu-sidebar";const n=document.createElement("div");if(n.className="svu-sidebar-logo",e.logoDarkUrl){const t=document.createElement("img");t.src=e.logoDarkUrl,t.alt=e.organizationName,n.appendChild(t)}t.appendChild(n);const i=document.createElement("div");i.className="svu-sidebar-intro",i.innerHTML="\n <h3>Secure File Transfer</h3>\n <p>This file is secured with SparkVault's advanced multi-key cryptography and end-to-end encryption.</p>\n ",t.appendChild(i);const s=document.createElement("div");return s.className="svu-sidebar-security",s.innerHTML='\n <h4>\n <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">\n <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>\n </svg>\n SparkVault\'s Triple Zero-Trust\n </h4>\n <p class="svu-security-intro">\n Decryption requires <strong>three independent Master Keys</strong>, held in three different physical locations, by three separate companies, all cryptographically combined in real-time.\n </p>\n <div class="svu-key-chain">\n <div class="svu-key-item">\n <div class="svu-key-number">1</div>\n <div class="svu-key-info">\n <span class="svu-key-name">Kyber-1024 Post-Quantum Key</span>\n <span class="svu-key-algo">ML-KEM lattice-based encapsulation</span>\n <span class="svu-key-desc">Quantum-resistant key exchange</span>\n </div>\n </div>\n <div class="svu-key-connector">\n <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">\n <path d="M12 5v14M5 12h14"/>\n </svg>\n </div>\n <div class="svu-key-item">\n <div class="svu-key-number">2</div>\n <div class="svu-key-info">\n <span class="svu-key-name">X25519 Ephemeral Key</span>\n <span class="svu-key-algo">Elliptic-curve Diffie-Hellman</span>\n <span class="svu-key-desc">Perfect forward secrecy</span>\n </div>\n </div>\n <div class="svu-key-connector">\n <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">\n <path d="M12 5v14M5 12h14"/>\n </svg>\n </div>\n <div class="svu-key-item">\n <div class="svu-key-number">3</div>\n <div class="svu-key-info">\n <span class="svu-key-name">HKDF-SHA512 Derived Key</span>\n <span class="svu-key-algo">Hardware-bound key derivation</span>\n <span class="svu-key-desc">Vault master key in secure enclave</span>\n </div>\n </div>\n </div>\n <div class="svu-encryption-result">\n <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">\n <path d="M20 6L9 17l-5-5"/>\n </svg>\n <span>Combined via <strong>HKDF</strong> producing <strong>AES-256-GCM</strong> authenticated cipher</span>\n </div>\n <div class="svu-security-badges">\n <span class="svu-tls-badge">TLS 1.3 In Transit</span>\n <span class="svu-tls-badge">Encrypted At Rest</span>\n <span class="svu-tls-badge">Zero Trust</span>\n </div>\n ',t.appendChild(s),t}(this.branding),this.shell.modal.classList.add("svu-with-sidebar"),this.shell.modal.appendChild(this.sidebar),this.header&&(this.header.style.display="none")):!e&&this.sidebar&&(this.shell.modal.classList.remove("svu-with-sidebar"),this.sidebar.remove(),this.sidebar=null,this.header&&(this.header.style.display="")))}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.sidebar=null,this.onCloseCallback=null}}class Ti{constructor(e){this.shell=null,this.targetElement=e}createLoading(e,t){this.shell||(Ci(),this.shell=new vn(this.targetElement,{containerClassName:"svu-inline-container",bodyClassName:"svu-body",footer:an("svu")}))}updateBranding(e){}getBody(){return this.shell?.body??null}isOpen(){return null!==this.shell}destroy(){this.shell?.destroy(),this.shell=null}}const Ai=Object.freeze(["B","KB","MB","GB","TB"]);function Ii(e,t=1){if("number"!=typeof e||!Number.isFinite(e)||e<=0)return`0 ${Ai[0]}`;const n=Math.min(Math.max(Math.floor(Math.log(e)/Math.log(1024)),0),Ai.length-1);return`${parseFloat((e/1024**n).toFixed(t))} ${Ai[n]}`}const $i=[{text:"File received by Forge",duration:600},{text:"Deriving Triple Zero-Trust encryption keys",duration:800},{text:"Encrypting with AES-256-GCM",duration:900},{text:"Generating cryptographic signatures",duration:700},{text:"Storing in post-quantum protected vault",duration:600},{text:"Verifying integrity",duration:400}];function Li(e){return Se(new Uint8Array(e.match(/.{2}/g).map(e=>parseInt(e,16))))}function Bi(e){return null===e?"":`<p class="svu-forging-line">Secure Transfer Channel: <span class="svu-mono">${It(e)}</span></p>`}function Mi(e){if(!(e instanceof Zn))return{label:"Try Again",keepFile:!0};if(function(e){return e.code===o||e.details?.coreCode===o||"UPLOAD_SOURCE_DISABLED"===e.code||402===e.statusCode||404===e.statusCode&&"session_gone"!==e.code}(e))return null;if(e.code===r)return{label:"Upload Another File",keepFile:!1};const t=e.statusCode??0;return 0===t||429===t||t>=500?{label:"Try Again",keepFile:!0}:{label:"Choose Another File",keepFile:!1}}class Pi{constructor(e,t,n,i){this.viewState={view:"loading"},this.config=null,this.selectedFile=null,this.fileInputElement=null,this.uploadModal=null,this.isInlineMode=!1,this.hybridModalInitialized=!1,this.closed=!1,this.cancelled=!1,this.pasteHandler=null,this.container=e,this.api=t,this.options=n,this.callbacks=i,this.isInlineMode=!!n.target}async start(){this.container.createLoading({backdropBlur:this.options.backdropBlur},()=>this.handleClose()),this.setState({view:"loading"});try{const[e]=await Promise.all([this.api.getVaultUploadInfo(this.options.vaultId),new Promise(e=>setTimeout(e,1e3))]);if(this.config=e,this.container.updateBranding(e.branding),this.options.file)return this.selectedFile=this.options.file,this.callbacks.onReady?.(),void await this.startUpload(e);this.setState({view:"form",config:e}),this.callbacks.onReady?.()}catch(e){this.handleApiError(e)}}close(){this.closed=!0,this.api.abort(),this.cleanupFileInput(),this.cleanupPasteHandler(),this.uploadModal&&(this.uploadModal.destroy(),this.uploadModal=null,this.hybridModalInitialized=!1),this.container.destroy()}cancel(){this.cancelled||(this.cancelled=!0,this.close(),this.callbacks.onCancel())}handleClose(){this.cancel()}setState(e){if(this.closed)return;const t=this.viewState.view;this.viewState=e,"uploading"===t&&"uploading"===e.view&&this.updateUploadProgress(e)||this.render()}updateUploadProgress(e){const t=this.isInlineMode&&this.uploadModal?this.uploadModal.getBody():this.container.getBody(),n=t?.querySelector(".svu-progress-fill");if(!t||!n)return!1;n.style.width=`${e.progress}%`;const[i,s]=t.querySelectorAll(".svu-progress-text span");return i&&(i.textContent=`${e.progress}%`),s&&(s.textContent=`${Ii(e.bytesUploaded)} / ${Ii(e.file.size)}`),!0}render(){const e="uploading"===this.viewState.view||"ceremony"===this.viewState.view;if(this.isInlineMode&&e)return void this.renderInModal();if(this.uploadModal){this.uploadModal.destroy(),this.uploadModal=null,this.hybridModalInitialized=!1;const e=this.container.getBody();e?.parentElement&&(e.parentElement.style.display="")}const t=this.container.getBody();if(t)switch(t.innerHTML="",this.container instanceof _i&&(this.container.setDarkMode(e),this.container.toggleSidebar(e)),this.viewState.view){case"loading":t.appendChild(this.renderLoading());break;case"form":t.appendChild(this.renderForm(this.viewState.config,this.viewState.error));break;case"uploading":t.appendChild(this.renderUploading(this.viewState));break;case"ceremony":t.appendChild(this.renderCeremony(this.viewState));break;case"complete":t.appendChild(this.renderComplete(this.viewState.result,this.viewState.config));break;case"error":t.appendChild(this.renderError(this.viewState))}}renderInModal(){this.uploadModal||(this.uploadModal=new _i,this.uploadModal.createLoading({backdropBlur:this.options.backdropBlur??!0},()=>{}),this.config&&this.uploadModal.updateBranding(this.config.branding),this.hybridModalInitialized=!1);const e=this.uploadModal.getBody();if(e){if(!this.hybridModalInitialized){const e=this.container.getBody();e?.parentElement&&(e.parentElement.style.display="none"),this.uploadModal.setDarkMode(!0),this.uploadModal.toggleSidebar(!0),this.hybridModalInitialized=!0}e.innerHTML="","uploading"===this.viewState.view?e.appendChild(this.renderUploading(this.viewState)):"ceremony"===this.viewState.view&&e.appendChild(this.renderCeremony(this.viewState))}}renderLoading(){const e=document.createElement("div");return e.className="svu-loading",e.innerHTML='\n <div class="svu-spinner"></div>\n <p class="svu-loading-text">Establishing secure connection...</p>\n ',e}renderForm(e,t){const n=document.createElement("div");n.className="svu-form-view";const i=document.createElement("h2");i.className="svu-title",i.textContent="Cryptographically Secure File Transfer",n.appendChild(i);const s=document.createElement("p");if(s.className="svu-subtitle",s.innerHTML=`Destination Vault: <strong>${It(e.vaultName)}</strong>`,n.appendChild(s),t){const e=document.createElement("div");e.className="svu-error-alert",e.textContent=t,n.appendChild(e)}const o=document.createElement("div");if(o.className="svu-drop-zone"+(this.selectedFile?" svu-has-file":""),this.selectedFile){o.innerHTML=`\n <div class="svu-selected-file">\n <div class="svu-file-icon">\n <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">\n <path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/>\n <path d="M14 2v6h6"/>\n </svg>\n </div>\n <div class="svu-file-info">\n <span class="svu-file-name">${It(this.selectedFile.name)}</span>\n <span class="svu-file-size">${Ii(this.selectedFile.size)}</span>\n </div>\n <button class="svu-remove-file" aria-label="Remove file">&times;</button>\n </div>\n `;const e=o.querySelector(".svu-remove-file");e&&e.addEventListener("click",e=>{e.stopPropagation(),this.selectedFile=null,this.render()})}else o.innerHTML='\n <div class="svu-drop-icon">\n <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">\n <path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/>\n <path d="M17 8l-5-5-5 5"/>\n <path d="M12 3v12"/>\n </svg>\n </div>\n <p class="svu-drop-text">Drag & drop a file here</p>\n <p class="svu-drop-subtext">or click to select</p>\n <p class="svu-drop-hint">Paste from clipboard also supported (Ctrl+V)</p>\n ';o.addEventListener("dragover",e=>{e.preventDefault(),o.classList.add("svu-dragging")}),o.addEventListener("dragleave",e=>{e.preventDefault(),o.classList.remove("svu-dragging")}),o.addEventListener("drop",t=>{t.preventDefault(),o.classList.remove("svu-dragging");const n=t.dataTransfer?.files[0];n&&this.handleFileSelect(n,e)}),o.addEventListener("click",()=>{this.selectedFile||this.openFileSelector(e)}),n.appendChild(o);const r=document.createElement("p");if(r.className="svu-max-size",r.textContent=`Max upload size: ${Ii(e.maxSizeBytes)}`,n.appendChild(r),this.selectedFile){const t=document.createElement("button");t.className="svu-btn svu-btn-primary",t.textContent="Upload Securely",t.onclick=()=>this.startUpload(e),n.appendChild(t)}const a=document.createElement("div");return a.className="svu-metadata",a.innerHTML=`\n <h4>Transfer Details</h4>\n <div class="svu-metadata-grid">\n <div class="svu-metadata-item">\n <span class="svu-metadata-label">Recipient</span>\n <span class="svu-metadata-value">${It(e.branding.organizationName)}</span>\n </div>\n <div class="svu-metadata-item">\n <span class="svu-metadata-label">Vault</span>\n <span class="svu-metadata-value">${It(e.vaultName)}</span>\n </div>\n <div class="svu-metadata-item svu-full-width">\n <span class="svu-metadata-label">Vault ID</span>\n <span class="svu-metadata-value">${It(e.vaultId)}</span>\n </div>\n <div class="svu-metadata-item">\n <span class="svu-metadata-label">Encryption</span>\n <span class="svu-metadata-value">${It(e.encryption.algorithm)}</span>\n </div>\n <div class="svu-metadata-item">\n <span class="svu-metadata-label">Key Derivation</span>\n <span class="svu-metadata-value">${It(e.encryption.keyDerivation)}</span>\n </div>\n <div class="svu-metadata-item">\n <span class="svu-metadata-label">Post-Quantum</span>\n <span class="svu-metadata-value">${It(e.encryption.postQuantum)}</span>\n </div>\n <div class="svu-metadata-item">\n <span class="svu-metadata-label">Forge Status</span>\n <span class="svu-metadata-value ${"active"===e.forgeStatus?"svu-status-active":""}">\n ${"active"===e.forgeStatus?"● Active":"○ Inactive"}\n </span>\n </div>\n </div>\n `,n.appendChild(a),this.setupPasteHandler(e),n}renderUploading(e){const t=document.createElement("div");t.className="svu-uploading-view";const n=Li(e.ingotId.replace("ing_",""));return t.innerHTML=`\n <h2 class="svu-title">Streaming & Encrypting</h2>\n\n <div class="svu-stages">\n <div class="svu-stage svu-active">\n <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">\n <rect x="2" y="3" width="20" height="18" rx="2"/>\n <path d="M2 9h20"/>\n <circle cx="6" cy="6" r="1" fill="currentColor"/>\n <circle cx="10" cy="6" r="1" fill="currentColor"/>\n </svg>\n <span>Your Browser</span>\n </div>\n <div class="svu-stage-arrow svu-active"></div>\n <div class="svu-stage svu-active">\n <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">\n <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>\n </svg>\n <span>SparkVault</span>\n <span class="svu-stage-sub">Encrypting</span>\n </div>\n <div class="svu-stage-arrow"></div>\n <div class="svu-stage">\n <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">\n <rect x="3" y="3" width="18" height="18" rx="2"/>\n <circle cx="12" cy="12" r="3"/>\n <path d="M12 9V6M12 18v-3M9 12H6M18 12h-3"/>\n </svg>\n <span>${It(this.config?.branding.organizationName||"")}</span>\n </div>\n </div>\n\n <div class="svu-progress">\n <div class="svu-progress-bar">\n <div class="svu-progress-fill" style="width: ${e.progress}%"></div>\n </div>\n <div class="svu-progress-text">\n <span>${e.progress}%</span>\n <span>${Ii(e.bytesUploaded)} / ${Ii(e.file.size)}</span>\n </div>\n </div>\n\n <div class="svu-forging-info">\n <p class="svu-forging-line">Forging Ingot ID: <span class="svu-mono">${n}</span></p>\n ${Bi(e.requestId)}\n </div>\n `,t}renderCeremony(e){const t=document.createElement("div");t.className="svu-ceremony-view";const n=Li(e.ingotId.replace("ing_",""));let i="";return $i.forEach((t,n)=>{const s=n<e.step,o=n===e.step;i+=`\n <div class="svu-ceremony-step ${s?"svu-complete":""} ${o?"svu-active":""}">\n <span class="svu-step-icon">\n ${s?'<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M20 6L9 17l-5-5"/></svg>':o?'<svg class="svu-spin" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4M4.93 19.07l2.83-2.83M16.24 7.76l2.83-2.83"/></svg>':""}\n </span>\n <span class="svu-step-text">${t.text}</span>\n </div>\n `}),t.innerHTML=`\n <h2 class="svu-title">Securing Your File</h2>\n\n <div class="svu-ceremony-steps">\n ${i}\n </div>\n\n <div class="svu-forging-info">\n <p class="svu-forging-line">Forging Ingot ID: <span class="svu-mono">${n}</span></p>\n ${Bi(e.requestId)}\n </div>\n `,t}renderComplete(e,t){const n=document.createElement("div");n.className="svu-complete-view",n.innerHTML=`\n <div class="svu-success-icon">\n <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">\n <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/>\n <path d="M22 4L12 14.01l-3-3"/>\n </svg>\n </div>\n\n <h2 class="svu-success-title">Your file has been securely sent!</h2>\n\n <div class="svu-success-details">\n <div class="svu-success-row">\n <span class="svu-success-label">Ingot ID</span>\n <span class="svu-success-value svu-mono">\n ${It(e.ingotId)}\n <button class="svu-copy-btn" aria-label="Copy Ingot ID">\n <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">\n <rect x="9" y="9" width="13" height="13" rx="2" ry="2"/>\n <path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"/>\n </svg>\n </button>\n </span>\n </div>\n <div class="svu-success-row">\n <span class="svu-success-label">File</span>\n <span class="svu-success-value">${It(e.filename)}</span>\n </div>\n <div class="svu-success-row">\n <span class="svu-success-label">Size</span>\n <span class="svu-success-value">${Ii(e.sizeBytes)}</span>\n </div>\n <div class="svu-success-row">\n <span class="svu-success-label">Timestamp</span>\n <span class="svu-success-value svu-mono">${It(e.uploadTime)}</span>\n </div>\n <div class="svu-success-row">\n <span class="svu-success-label">Encryption</span>\n <span class="svu-success-value">AES-256-GCM</span>\n </div>\n </div>\n\n <p class="svu-success-guidance">\n ${It(t.branding.organizationName)} has been notified and can access this file\n from their SparkVault dashboard. Save the Ingot ID above for your records.\n </p>\n\n ${this.options.hideUploadAnother?"":'\n <button class="svu-btn svu-btn-secondary">\n <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">\n <path d="M1 4v6h6M23 20v-6h-6"/>\n <path d="M20.49 9A9 9 0 005.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 013.51 15"/>\n </svg>\n Upload Another File\n </button>\n '}\n `;const i=n.querySelector(".svu-copy-btn");i&&i.addEventListener("click",()=>{navigator.clipboard.writeText(e.ingotId)});const s=n.querySelector(".svu-btn-secondary");return s&&s.addEventListener("click",()=>{this.selectedFile=null,this.setState({view:"form",config:t})}),n}renderError(e){const t=document.createElement("div");t.className="svu-error-view",t.innerHTML=`\n <div class="svu-error-icon">\n <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">\n <circle cx="12" cy="12" r="10"/>\n <path d="M12 8v4M12 16h.01"/>\n </svg>\n </div>\n\n <h2 class="svu-error-title">${It(e.title)}</h2>\n\n <p class="svu-error-message">${It(e.message)}</p>\n\n <div class="svu-error-code">\n <span class="svu-error-code-label">Code</span>\n <span class="svu-error-code-value">${It(e.code)}</span>\n </div>\n `;const{action:n}=e;if(n&&this.config){const e=this.config,i=document.createElement("button");i.className="svu-btn svu-btn-primary",i.textContent=n.label,i.addEventListener("click",()=>{n.keepFile||(this.selectedFile=null),this.setState({view:"form",config:e})}),t.appendChild(i)}return t}handleFileSelect(e,t){0!==e.size?e.size>t.maxSizeBytes?this.setState({view:"form",config:t,error:`File size exceeds maximum allowed (${Ii(t.maxSizeBytes)})`}):(this.selectedFile=e,this.setState({view:"form",config:t})):this.setState({view:"form",config:t,error:"This file is empty, so there is nothing to upload. Choose another file."})}openFileSelector(e){this.cleanupFileInput(),this.fileInputElement=document.createElement("input"),this.fileInputElement.type="file",this.fileInputElement.style.display="none",this.fileInputElement.onchange=()=>{const t=this.fileInputElement?.files?.[0];t&&this.handleFileSelect(t,e)},document.body.appendChild(this.fileInputElement),this.fileInputElement.click()}cleanupFileInput(){this.fileInputElement&&(this.fileInputElement.remove(),this.fileInputElement=null)}setupPasteHandler(e){this.cleanupPasteHandler(),this.pasteHandler=t=>{const n=t.clipboardData?.items;if(n)for(const t of n)if("file"===t.kind){const n=t.getAsFile();if(n){this.handleFileSelect(n,e);break}}},document.addEventListener("paste",this.pasteHandler)}cleanupPasteHandler(){this.pasteHandler&&(document.removeEventListener("paste",this.pasteHandler),this.pasteHandler=null)}async startUpload(e){if(!this.selectedFile)return;const t=this.selectedFile;try{const{forgeUrl:n,ingotId:i,requestId:s}=await this.api.initiateUpload(e.vaultId,t.name,t.size,t.type||"application/octet-stream",this.options.token,this.options.folder);this.setState({view:"uploading",file:t,ingotId:i,requestId:s,progress:0,bytesUploaded:0}),await this.api.uploadFileToForge(t,n,(e,n)=>{const o=Math.round(e/n*100);this.setState({view:"uploading",file:t,ingotId:i,requestId:s,progress:o,bytesUploaded:e}),this.callbacks.onProgress?.({bytesUploaded:e,bytesTotal:n,percentage:o,phase:"uploading"})}),await this.runCeremony(t,i,s);const o=new Date,r=`${o.getUTCFullYear()}-${String(o.getUTCMonth()+1).padStart(2,"0")}-${String(o.getUTCDate()).padStart(2,"0")} ${String(o.getUTCHours()).padStart(2,"0")}:${String(o.getUTCMinutes()).padStart(2,"0")}:${String(o.getUTCSeconds()).padStart(2,"0")} UTC`,a={ingotId:i,vaultId:e.vaultId,filename:t.name,sizeBytes:t.size,uploadTime:r};if(this.callbacks.onProgress?.({bytesUploaded:t.size,bytesTotal:t.size,percentage:100,phase:"complete"}),this.options.hideSuccessScreen)return this.callbacks.onSuccess(a),void this.close();this.setState({view:"complete",result:a,config:e}),this.callbacks.onSuccess(a)}catch(e){this.handleApiError(e,this.options.file?null:Mi(e))}}async runCeremony(e,t,n){for(let i=0;i<$i.length;i++)this.setState({view:"ceremony",file:e,ingotId:t,requestId:n,step:i,complete:!1}),this.callbacks.onProgress?.({bytesUploaded:e.size,bytesTotal:e.size,percentage:100,phase:"ceremony"}),await new Promise(e=>setTimeout(e,$i[i].duration));this.setState({view:"ceremony",file:e,ingotId:t,requestId:n,step:$i.length,complete:!0}),await new Promise(e=>setTimeout(e,500))}handleApiError(e,t=null){if(!this.closed&&!function(e){return e instanceof D||e instanceof I&&"cancelled"===e.code}(e))if(e instanceof Zn)"UPLOAD_SOURCE_DISABLED"===e.code?this.setState({view:"error",action:t,title:"Upload Widget Not Enabled",message:"This vault has not enabled the embedded upload widget. Enable it on the vault's settings page in the SparkVault dashboard to start accepting uploads here.",code:"UPLOAD_SOURCE_DISABLED",statusCode:e.statusCode}):e.code===r?this.setState({view:"error",action:t,title:"Upload Received",message:e.message,code:e.code,statusCode:e.statusCode}):e.code===o||e.details?.coreCode===o?this.setState({view:"error",action:t,title:"Uploads Paused",message:"This vault isn't accepting files right now, so your file was not saved. Please contact the person who shared this upload page with you.",code:e.code,statusCode:e.statusCode}):"upload_refused"===e.code?this.setState({view:"error",action:t,title:"Upload Not Saved",message:e.message,code:e.code,statusCode:e.statusCode}):404===e.statusCode&&"session_gone"!==e.code?this.setState({view:"error",action:t,title:"Upload Page Not Found",message:"The requested upload endpoint could not be located. This may occur if the upload link has expired or was entered incorrectly.",code:"NOT_FOUND",statusCode:404}):402===e.statusCode?this.setState({view:"error",action:t,title:"Service Unavailable",message:"This upload endpoint has been temporarily disabled due to an account billing issue. Please contact the organization's administrator.",code:"PAYMENT_REQUIRED",statusCode:402}):this.setState({view:"error",action:t,title:"Upload Failed",message:e.message,code:e.code,statusCode:e.statusCode}),this.callbacks.onError(e);else if(e instanceof Error)this.setState({view:"error",action:t,title:"Upload Failed",message:e.message,code:"UNKNOWN_ERROR"}),this.callbacks.onError(e);else{const e=new Error("An unexpected error occurred");this.setState({view:"error",action:t,title:"Upload Failed",message:e.message,code:"UNKNOWN_ERROR"}),this.callbacks.onError(e)}}}class Ri{constructor(e){this.renderer=null,this.config=e,this.api=new ki(e)}async upload(e){if(!e.vaultId)throw new M("vaultId is required");this.renderer&&this.renderer.cancel();const t=!!e.target?this.createInlineContainer(e.target):new _i,n={...e,backdropBlur:e.backdropBlur??this.config.backdropBlur};return this.api.resetSession(),new Promise((i,s)=>{this.renderer=new Pi(t,this.api,n,{onSuccess:t=>{e.onSuccess?.(t),i(t)},onError:t=>{e.onError?.(t),s(t)},onCancel:()=>{const t=new D;e.onCancel?.(),s(t)},onProgress:e.onProgress,onReady:e.onReady}),this.renderer.start().catch(t=>{e.onError?.(t),s(t)})})}attach(e,t){if(!t.vaultId)throw new M("vaultId is required");return bn(e,async e=>{e.preventDefault();try{await this.upload({vaultId:t.vaultId,onSuccess:t.onSuccess,onError:t.onError,onCancel:t.onCancel,onProgress:t.onProgress})}catch{}})}close(){this.renderer&&(this.renderer.cancel(),this.renderer=null)}createInlineContainer(e){return new Ti(yn(e))}async pop(e){return this.upload(e)}async render(e){return this.upload(e)}}class Ni{constructor(e,t){this.http=t,this.uploadModule=new Ri(e);const n=e=>this.uploadModule.upload(e);n.attach=(e,t)=>this.uploadModule.attach(e,t),n.close=()=>this.uploadModule.close(),n.pop=e=>this.uploadModule.pop(e),n.render=e=>this.uploadModule.render(e),this.upload=n}async create(e){this.validateCreateOptions(e);const t=await this.http.post(Be`/v1/vaults`,{name:e.name});return{id:t.data.vault_id,name:t.data.name,vmk:t.data.vmk,createdAt:t.data.created_at}}async unseal(e,t){const n=Me(e,"vaultId");if("string"!=typeof t||!t.trim())throw new M("A VMK or DVAK token is required");const i=await this.http.post(Be`/v1/vaults/${n}/unseal`,function(e,t){const n="string"==typeof e?e.trim():"";if(!n)throw new TypeError("unsealRequestBody requires a non-empty key");const i=n.startsWith("dvak_")?"dvak_token":"vmk";return void 0===t?{[i]:n}:{[i]:n,ttl_seconds:t}}(t));if(!i.data.vat)throw new M("Unseal response did not include a vault access token");return{id:i.data.vault_id,vatToken:i.data.vat,issuedAt:i.data.issued_at,expiresAt:i.data.expires_at,ttlSeconds:i.data.ttl_seconds}}async list(e={}){const t=await this.http.get(Be`/v1/vaults`,{query:{limit:e.limit,cursor:e.cursor}});return{vaults:t.data.vaults.map(e=>({id:e.vault_id,name:e.name,createdAt:e.created_at,ingotCount:e.ingot_count,storageBytes:e.storage_bytes,...Oi(e)})),nextCursor:t.data.next_cursor}}async get(e){const t=Me(e,"vaultId");return zi((await this.http.get(Be`/v1/vaults/${t}`)).data)}async update(e,t){const n=Me(e,"vaultId");if(!t.name?.trim())throw new M("Vault name is required");const i=(await this.http.put(Be`/v1/vaults/${n}`,{name:t.name})).data;return{id:i.vault_id,name:i.name,description:i.description??null,updatedAt:i.updated_at}}async seal(e){const t=Me(e,"vaultId");await this.http.post(Be`/v1/vaults/${t}/seal`)}async delete(e,t){const n=Me(e,"vaultId");if(!t)throw new M("Vault name is required to confirm deletion");const i=(await this.http.delete(Be`/v1/vaults/${n}`,{headers:{"X-Confirm-Name-B64":_e(t),"X-Vault-Deletion-Mode":"schedule"}})).data;return{id:i.vault_id,status:i.status,deletionRequestedAt:i.deletion_requested_at,deletionScheduledFor:i.deletion_scheduled_for,deletionRequestedBy:i.deletion_requested_by,deletionScheduleId:i.deletion_schedule_id}}async cancelDeletion(e,t){const n=Me(e,"vaultId");if(!t?.trim())throw new M("Deletion schedule is required to cancel deletion");return zi((await this.http.post(Be`/v1/vaults/${n}/deletion/cancel`,{deletion_schedule_id:t})).data)}async getSharingConfig(e){const t=Me(e,"vaultId");return Di((await this.http.get(Be`/v1/vaults/${t}/sharing`)).data)}async enableSharing(e,t,n={}){const i=Me(e,"vaultId");if(!t)throw new M("VMK is required");return Di((await this.http.post(Be`/v1/vaults/${i}/sharing/enable`,{vmk:t,all_ingots_public:n.allIngotsPublic,session_length_seconds:n.sessionLengthSeconds})).data)}async disableSharing(e){const t=Me(e,"vaultId");return Di((await this.http.post(Be`/v1/vaults/${t}/sharing/disable`)).data)}async updateSharingConfig(e,t,n){const i=Me(e,"vaultId");return Di((await this.http.put(Be`/v1/vaults/${i}/sharing`,{all_ingots_public:t.allIngotsPublic,session_length_seconds:t.sessionLengthSeconds},{vat:n?.vatToken})).data)}async getAccessLogRetention(e){const t=Me(e,"vaultId"),n=await this.http.get(Be`/v1/vaults/${t}/access-log-retention`);return{vaultId:n.data.vault_id,retentionSeconds:n.data.access_log_retention_seconds}}async updateAccessLogRetention(e,t){const n=Me(e,"vaultId"),i=await this.http.put(Be`/v1/vaults/${n}/access-log-retention`,{access_log_retention_seconds:t});return{vaultId:i.data.vault_id,retentionSeconds:i.data.access_log_retention_seconds}}async getUploadConfig(e){const t=Me(e,"vaultId");return Ui((await this.http.get(Be`/v1/vaults/${t}/upload`)).data)}async enableUploadPortal(e,t){return this.toggleUploadChannel(e,"portal","enable",t)}async disableUploadPortal(e){return this.toggleUploadChannel(e,"portal","disable")}async enableUploadWidget(e,t){return this.toggleUploadChannel(e,"widget","enable",t)}async disableUploadWidget(e){return this.toggleUploadChannel(e,"widget","disable")}async updateUploadConfig(e,t){const n=Me(e,"vaultId"),i={};void 0!==t.maxSizeBytes&&(i.max_size_bytes=t.maxSizeBytes),void 0!==t.notificationEmail&&(i.notification_email=t.notificationEmail);return Ui((await this.http.put(Be`/v1/vaults/${n}/upload`,i)).data)}async toggleUploadChannel(e,t,n,i){const s=Me(e,"vaultId");if("enable"===n&&!i)throw new M("VMK is required");return Ui((await this.http.post(Be`/v1/vaults/${s}/upload/${t}/${n}`,"enable"===n?{vmk:i}:void 0)).data)}validateCreateOptions(e){if(!e.name?.trim())throw new M("Vault name is required")}}function Oi(e){return{status:e.status,deletionRequestedAt:e.deletion_requested_at,deletionScheduledFor:e.deletion_scheduled_for,deletionRequestedBy:e.deletion_requested_by,deletionScheduleId:e.deletion_schedule_id}}function zi(e){return{id:e.vault_id,name:e.name,description:e.description??null,...Oi(e),ingotCount:e.ingot_count??0,storageBytes:e.storage_bytes??0,createdAt:e.created_at,lastUnsealedAt:e.last_unsealed_at??null,unsealCount:e.unseal_count??0}}function Di(e){return{vaultId:e.vault_id,publicSharingEnabled:e.public_sharing_enabled,allIngotsPublic:e.all_ingots_public,sessionLengthSeconds:e.session_length_seconds??null,enabledAt:e.enabled_at??null}}function Ui(e){return{vaultId:e.vault_id,uploadPortalEnabled:e.upload_portal_enabled,uploadPortalEnabledAt:e.upload_portal_enabled_at??null,uploadWidgetEnabled:e.upload_widget_enabled,uploadWidgetEnabledAt:e.upload_widget_enabled_at??null,maxSizeBytes:e.max_size_bytes??null,notificationEmail:e.notification_email??null,portalUrl:e.portal_url}}const Hi=new Map([["ingot_downloaded","download"]]),Fi=Object.freeze([...Hi.keys()]);function Vi(e){const t=Hi.get(e.event_type);return void 0===t?null:{timestamp:e.timestamp,action:t,identity:e.actor_display||e.metadata?.identity||e.actor_id||"Unknown",ip_address:e.ip_address??"",user_agent:e.user_agent??""}}let ji=!1;function qi(e){ji=e,e&&Wi("info","Debug mode enabled")}function Wi(e,t,...n){const i=`[SparkVault] ${(new Date).toISOString().split("T")[1].slice(0,-1)} ${t}`;switch(e){case"debug":ji&&console.debug(i,...n);break;case"info":ji&&console.log(i,...n);break;case"warn":ji&&console.warn(i,...n);break;case"error":console.error(i,...n)}}const Ki={debug:(e,...t)=>Wi("debug",e,...t),info:(e,...t)=>Wi("info",e,...t),warn:(e,...t)=>Wi("warn",e,...t),error:(e,...t)=>Wi("error",e,...t)},Gi=6e4,Yi=3e5;function Xi(e,t,n,i){return new Promise((s,o)=>{const r=setTimeout(()=>{n.abort(),o(new z(i))},t);e.then(e=>{clearTimeout(r),s(e)},e=>{clearTimeout(r),o(e)})})}function Ji(e,t=re){const n=Gn(e,{operation:"decrypt",isAllowedHost:t});if(!n.ok)throw new M("Invalid download URL",{reason:n.reason})}const Qi=u({status:0}),Zi={verdict:a.REFUSED,retryAfterMs:null,offset:null,coreCode:null},es=/^bytes (\d+)-(\d+)\/(\d+)$/,ts=/^"[^"]*"$/,ns="The file changed while it was downloading. Please try again.";async function is(e,t){const{signal:n,remint:i}=t,s={received:new ps,budget:T(),held:null,furthest:0},o=S("download");for(let r=e;;){const e=await ss(r,s,t);if(e.ok)return e.download;if(n?.aborted)throw n.reason;const{error:l,outcome:d}=e;if(!i||d.verdict!==a.RETRY||!s.budget.failed(a.RETRY,d.retryAfterMs))throw l;await hs(E({attempt:s.budget.attempt,retryAfterMs:d.retryAfterMs,jitterKey:o}),n),r=i}}async function ss(e,t,n){let i;try{i=await e(),Ji(i,n.isAllowedHost)}catch(e){if(!(e instanceof I)||"number"!=typeof e.statusCode)return{ok:!1,error:e,outcome:Qi};const t=function(e,t){const n=e.code===o?{coreCode:e.code}:null;return{...u({status:t,details:n}),retryAfterMs:e.retryAfterMs}}(e,e.statusCode);return{ok:!1,error:null===t.coreCode?e:os(e,t.coreCode),outcome:t}}return async function(e,t,n){const{signal:i,onProgress:s,expectedContentVersion:o}=n,{received:r}=t,a=function(e){const{held:t,received:n}=e;return null===t||null===t.validator||0===n.loaded?null:{held:t,validator:t.validator,at:n.loaded}}(t);a||r.discard();const l=new AbortController,d=()=>l.abort(i?.reason);i?.aborted?d():i?.addEventListener("abort",d,{once:!0});const c=e=>({ok:!0,download:{blob:r.toBlob(e.contentType),contentVersion:e.contentVersion}});let h=null,p=!1;try{const n=await Xi(fetch(e,a?{signal:l.signal,headers:{Range:`bytes=${a.at}-`,"If-Range":a.validator}}:{signal:l.signal}),3e4,l,"Download timed out waiting for response headers");if(!n.ok){const e=u({status:n.status,headers:e=>n.headers.get(e)});return{ok:!1,error:await rs(n,e,l),outcome:e}}if(a&&206===n.status){const e=function(e,t){const n=e.headers.get("etag");if(null!==n&&n.replace(/^W\//,"")!==t.validator)return new I(ns,"content_changed");const i=es.exec(e.headers.get("content-range")??""),[s,o,r]=i?i.slice(1).map(Number):[NaN,NaN,NaN],{total:a}=t.held;if(s!==t.at||o!==r-1||a>0&&r!==a)return new I("The resumed download did not continue where it stopped","download_failed",e.status,{reason:"range_mismatch"});return{...t.held,total:r}}(n,a);if(e instanceof I)return{ok:!1,error:e,outcome:Zi};h=e}else{r.discard();const e=n.headers.get("x-content-version")||null;if(o&&e&&e!==o)return{ok:!1,error:new I(ns,"content_changed"),outcome:Zi};h={contentType:n.headers.get("content-type")??"",contentVersion:e,total:Number(n.headers.get("content-length"))||0,validator:ls(n.headers)}}return t.held=h,await async function(e,t,n,i,s){const{received:o}=n;if(!e.body)return o.appendBlob(await Xi(e.blob(),Yi,t,"Download timed out")),us(n),void cs(s,o.loaded,i);const r=e.body.getReader();for(;;){const{done:e,value:a}=await Xi(r.read(),Gi,t,"Download stalled: no data received");if(e)return;o.append(a),us(n),cs(s,o.loaded,i)}}(n,l,t,h.total,s),h.total>0&&r.loaded!==h.total?(r.loaded>h.total&&r.discard(),{ok:!1,error:as(r.loaded,h.total),outcome:Qi}):(p=!0,c(h))}catch(e){return e instanceof ds?{ok:!1,error:e.failure,outcome:Zi}:null!==h&&h.total>0&&r.loaded===h.total&&!i?.aborted?c(h):{ok:!1,error:e,outcome:Qi}}finally{p||l.abort(),i?.removeEventListener("abort",d)}}(i,t,n)}function os(e,t){return new I(e.message,e.code,e.statusCode,{...e.details,coreCode:t},e.retryAfterMs)}async function rs(e,t,n){const i=`Download failed with status ${e.status}`,{coreCode:s}=t;if(t.verdict!==a.REFUSED||null===s)return new I(i,"download_failed",e.status);const o=await Xi(K(e),Gi,n,"Download timed out reading the refusal"),r=o.code===s?o.message:i;return new I(r,"download_failed",e.status,{coreCode:s})}function as(e,t){return new I(`The download ended after ${e} of ${t} bytes`,"download_failed",void 0,{reason:"length_mismatch",received:e,total:t})}function ls(e){const t=e.get("etag"),n=(e.get("accept-ranges")??"").split(",").some(e=>"bytes"===e.trim().toLowerCase());return null!==t&&ts.test(t)&&n?t:null}class ds extends Error{constructor(e){super("onProgress threw"),this.failure=e}}function cs(e,t,n){if(e)try{e(t,n)}catch(e){throw new ds(e)}}function us(e){e.received.loaded>e.furthest?(e.furthest=e.received.loaded,e.budget.progressed()):e.budget.alive()}function hs(e,t){return new Promise((n,i)=>{if(t?.aborted)return void i(t.reason);const s=()=>{clearTimeout(o),i(t?.reason)},o=setTimeout(()=>{t?.removeEventListener("abort",s),n()},e);t?.addEventListener("abort",s,{once:!0})})}class ps{constructor(){this.parts=[],this.pending=[],this.pendingBytes=0,this.count=0}get loaded(){return this.count}append(e){this.pending.push(e),this.pendingBytes+=e.byteLength,this.count+=e.byteLength,this.pendingBytes>=8388608&&this.fold()}appendBlob(e){this.fold(),this.parts.push(e),this.count+=e.size}discard(){this.parts=[],this.pending=[],this.pendingBytes=0,this.count=0}toBlob(e){return this.fold(),new Blob(this.parts,{type:e})}fold(){0!==this.pending.length&&(this.parts.push(new Blob(this.pending)),this.pending=[],this.pendingBytes=0)}}class ms{constructor(e){this.http=e}async list(e,t={}){const n=Pe(e),i=await this.http.get(Be`/v1/vaults/${n}/folders`,{vat:e.vatToken,query:{limit:t.limit,page_token:t.pageToken}});return{folders:(i.data.folders??[]).map(fs),nextPageToken:i.data.next_page_token??null}}async findByPath(e,t){const n=Pe(e);if("string"!=typeof t||""===t.trim())throw new M("path must be a non-empty string",{field:"path"});const i=await this.http.get(Be`/v1/vaults/${n}/folders`,{vat:e.vatToken,query:{path:t}}),s=i.data?.folders;if(!Array.isArray(s)||s.length>1)throw new I("A folder path lookup answered neither one folder nor none","invalid_response",void 0,{count:Array.isArray(s)?s.length:null});return 1===s.length?fs(s[0]):null}async get(e,t){const n=Pe(e),i=Me(t,"folderId");return fs((await this.http.get(Be`/v1/vaults/${n}/folders/${i}`,{vat:e.vatToken})).data)}async getBreadcrumb(e,t){const n=Pe(e),i=Me(t,"folderId");return((await this.http.get(Be`/v1/vaults/${n}/folders/${i}`,{vat:e.vatToken})).data.breadcrumb??[]).map(e=>({id:e.folder_id,name:e.name}))}async create(e,t){if(!t.name?.trim())throw new M("Folder name is required");const n=Pe(e);return fs((await this.http.post(Be`/v1/vaults/${n}/folders`,{name:t.name,parent_id:t.parentId??null},{vat:e.vatToken})).data)}async update(e,t,n){const i=Pe(e),s=Me(t,"folderId"),o={};void 0!==n.name&&(o.name=n.name),void 0!==n.parentId&&(o.parent_id=n.parentId),void 0!==n.pinned&&(o.pinned=n.pinned);return fs((await this.http.put(Be`/v1/vaults/${i}/folders/${s}`,o,{vat:e.vatToken})).data)}move(e,t,n){return this.update(e,t,{parentId:n})}togglePin(e,t,n){return this.update(e,t,{pinned:n})}async delete(e,t){const n=Pe(e),i=Me(t,"folderId");await this.http.delete(Be`/v1/vaults/${n}/folders/${i}`,{vat:e.vatToken})}async moveIngot(e,t,n){const i=Pe(e),s=Me(t,"ingotId");await this.http.patch(Be`/v1/vaults/${i}/ingots/${s}`,{folder_id:n},{vat:e.vatToken})}}function fs(e){return{id:e.folder_id,name:e.name,parentId:e.parent_id??null,pinned:e.pinned??!1,createdAt:e.created_at??0,updatedAt:e.updated_at??0}}class vs{constructor(e,t){this.allowsTransferHost=e=>ce(this.config,e),this.config=e,this.http=t}async createUpload(e){if(!e.name?.trim())throw new M("Ingot name is required");if(!Number.isFinite(e.sizeBytes)||e.sizeBytes<1)throw new M("sizeBytes must be a positive number");if(e.folder&&e.folderId)throw new M("Provide folder or folderId, not both");const t=await this.requestUploadSession(e.vault,{name:e.name,content_type:e.contentType,size_bytes:e.sizeBytes,contentHmac:e.contentHmac,folder:e.folder,folderId:e.folderId,onNameConflict:e.onNameConflict});return{...gs(t),name:t.name,contentType:t.content_type,size:t.size_bytes,uploadUrl:t.forge_url,expiresAt:t.expires_at}}async endUpload(e,n){const i=Pe(e),s=Me(n.id,"ingotId"),o=function({created:e,uploadId:n}){return!0===e&&"string"==typeof n&&t.test(n)?n:null}(n);if(null===o)return"kept";try{return await this.http.delete(Be`/v1/vaults/${i}/ingots/${s}`,{vat:e.vatToken,query:{upload_id:o}}),"deleted"}catch(e){if(e instanceof I&&404===e.statusCode)return"deleted";if(e instanceof I&&412===e.statusCode)return"kept";throw e}}async sendUpload(e,t,n={}){this.validateFile(t);const{onProgress:i,onSessionCreated:s}=n;await this.runTransfer(n.signal,n=>n.uploadFileToForge(t,e,i,s&&(e=>s({sessionUrl:e}))))}async resumeUpload(e,t,n={}){this.validateFile(t);const{onProgress:i}=n;await this.runTransfer(n.signal,n=>n.resumeUploadToForge(t,e.sessionUrl,i))}async runTransfer(e,t){if(e?.aborted)throw new Zn("Upload cancelled","cancelled",0);const n=new ki(this.config),i=()=>n.abort();e?.addEventListener("abort",i,{once:!0});try{await t(n)}finally{e?.removeEventListener("abort",i)}}async upload(e,t){if(this.validateFile(t.file),t.folder&&t.folderId)throw new M("Provide folder or folderId, not both");const n=t.name??ys(t.file);li();const i=await this.requestUploadSession(e,{name:n,content_type:bs(t),size_bytes:t.file.size,contentHmac:t.contentHmac,folder:t.folder,folderId:t.folderId,onNameConflict:t.onNameConflict});try{return await this.transferAndFinalize(i,i.created,t.file,t.onProgress)}catch(t){throw pi(t)||this.endGivenUp(e,gs(i)),t}}endGivenUp(e,t){this.endUpload(e,t).catch(e=>{Ki.warn("A given-up upload could not be ended with its file; the server expires it",{ingotId:t.id,code:e instanceof I?e.code:void 0})})}async replace(e,t,n){this.validateFile(n.file);const i=Pe(e),s=Me(t,"ingotId"),o=n.name??ys(n.file),r=bs(n);li();const a=await this.http.put(Be`/v1/vaults/${i}/ingots/${s}`,{name:o,...void 0!==r&&{content_type:r},size_bytes:n.file.size,...n.contentHmac&&{content_hmac:n.contentHmac}},{vat:e.vatToken}).catch(e=>{throw ri(e)});if(!a.data.forge_url)throw new M("Replace endpoint did not return a Forge upload URL");return this.transferAndFinalize(a.data,!1,n.file,n.onProgress)}async rename(e,t,n){if(!n?.trim())throw new M("Ingot name is required");const i=Pe(e),s=Me(t,"ingotId");return ws((await this.http.patch(Be`/v1/vaults/${i}/ingots/${s}`,{name:n},{vat:e.vatToken})).data)}async move(e,t,n){const i=Pe(e),s=Me(t,"ingotId");return ws((await this.http.patch(Be`/v1/vaults/${i}/ingots/${s}`,{folder_id:n},{vat:e.vatToken})).data)}async delete(e,t){const n=Pe(e),i=Me(t,"ingotId");await this.http.delete(Be`/v1/vaults/${n}/ingots/${i}`,{vat:e.vatToken})}async get(e,t){const n=Pe(e),i=Me(t,"ingotId");return ws((await this.http.get(Be`/v1/vaults/${n}/ingots/${i}`,{vat:e.vatToken})).data)}async list(e,t={}){const n=Pe(e);return ks((await this.http.get(Be`/v1/vaults/${n}/ingots`,{vat:e.vatToken,query:{limit:t.limit,cursor:t.cursor,sort_by:t.sortBy,sort_order:t.sortOrder}})).data)}async search(e,t={}){const n=Pe(e);return ks((await this.http.get(Be`/v1/vaults/${n}/ingots/search`,{vat:e.vatToken,query:{q:t.q,file_type:t.fileType,folder_id:t.folderId,min_size:t.minSize,max_size:t.maxSize,limit:t.limit,cursor:t.cursor,sort_order:t.sortOrder}})).data)}async listContents(e,t={}){const n=Pe(e),i=await this.http.get(Be`/v1/vaults/${n}/contents`,{vat:e.vatToken,query:{folder_id:t.folderId,limit:t.limit,page_token:t.pageToken,sort_order:t.sortOrder}});return{folder:(s=i.data).folder?{id:s.folder.folder_id,name:s.folder.name,parentId:s.folder.parent_id??null}:null,breadcrumb:(s.breadcrumb??[]).map(e=>({id:e.folder_id,name:e.name})),folders:(s.folders??[]).map(fs),ingots:(s.ingots??[]).map(ws),nextPageToken:s.next_page_token??null};var s}async createDownloadLink(e,t){const n=Pe(e),i=Me(t,"ingotId"),s=await this.http.post(Be`/v1/vaults/${n}/ingots/${i}/download`,void 0,{vat:e.vatToken});if(!s.data.download_url)throw new M("Download endpoint did not return a download URL");return Ji(s.data.download_url,this.allowsTransferHost),{downloadUrl:s.data.download_url,contentVersion:s.data.content_version??null,id:s.data.ingot_id,name:s.data.name,size:s.data.size_bytes,contentType:s.data.content_type}}async download(e,t){return(await function(e,t={}){return is(e,{...t,remint:e})}(async()=>(await this.createDownloadLink(e,t)).downloadUrl,{isAllowedHost:this.allowsTransferHost})).blob}async getSharingConfig(e,t){const n=Pe(e),i=Me(t,"ingotId");return xs((await this.http.get(Be`/v1/vaults/${n}/ingots/${i}/sharing`,{vat:e.vatToken})).data)}async updateSharingConfig(e,t,n){const i=Pe(e),s=Me(t,"ingotId");return xs((await this.http.put(Be`/v1/vaults/${i}/ingots/${s}/sharing`,{shared:n.shared,visibility:n.visibility},{vat:e.vatToken})).data)}async addInvite(e,t,n){if(!n?.trim())throw new M("Invite identity is required");const i=Pe(e),s=Me(t,"ingotId"),o=await this.http.post(Be`/v1/vaults/${i}/ingots/${s}/sharing/invite`,{identity:n},{vat:e.vatToken});return{...Cs(r=o.data),shareUrl:r.share_url,delivered:r.delivered};var r}async revokeInvite(e,t,n){const i=Pe(e),s=Me(t,"ingotId"),o=Me(n,"inviteId");await this.http.delete(Be`/v1/vaults/${i}/ingots/${s}/sharing/invite/${o}`,{vat:e.vatToken})}async checkContentHmacs(e,t){const n=Pe(e);return(await this.http.post(Be`/v1/vaults/${n}/ingots/hash-check`,{hashes:t},{vat:e.vatToken})).data}async getAccessLogs(e,t,n={}){const i=Pe(e),s=Me(t,"ingotId"),o=await this.http.get(Be`/v1/vaults/${i}/ingots/${s}/audit-logs`,{vat:e.vatToken,query:{limit:n.limit,cursor:n.cursor,event_types:Fi.join(",")}}),r=[];for(const e of o.data.entries??[]){const t=Vi(e);t&&r.push({id:String(t.timestamp),action:t.action,identity:t.identity,ipAddress:t.ip_address,userAgent:t.user_agent,timestamp:t.timestamp})}return{logs:r,nextCursor:o.data.next_cursor}}async requestUploadSession(e,t){const n={name:t.name,...void 0!==t.content_type&&{content_type:t.content_type},size_bytes:t.size_bytes};t.folder?n.folder_path=t.folder:t.folderId&&(n.folder_id=t.folderId),t.contentHmac&&(n.content_hmac=t.contentHmac),t.onNameConflict&&(n.on_name_conflict=t.onNameConflict);const i=Pe(e),s=await this.http.post(Be`/v1/vaults/${i}/ingots`,n,{vat:e.vatToken}).catch(e=>{throw ri(e)});if(!s.data.forge_url)throw this.endGivenUp(e,gs(s.data)),new M("Upload endpoint did not return a Forge upload URL");return s.data}async transferAndFinalize(e,t,n,i){return await this.sendUpload(e.forge_url,n,{onProgress:i}),{id:e.ingot_id,name:e.name,contentType:e.content_type,size:e.size_bytes,created:t}}validateFile(e){if(!e)throw new M("File is required");if(0===e.size)throw new M("File cannot be empty")}}function gs(e){return{id:e.ingot_id,created:e.created,uploadId:e.upload_id??null}}function ys(e){return"undefined"!=typeof File&&e instanceof File&&e.name?e.name:"unnamed"}function bs(e){return e.contentType??(e.file.type||void 0)}function ws(e){return{id:e.ingot_id,name:e.name,downloadFilename:e.download_filename,contentType:e.content_type,size:e.size_bytes,status:e.status??"active",createdAt:e.created_at??0,folderId:e.folder_id??null,contentHmac:e.content_hmac??null,contentVersion:e.content_version??null}}function ks(e){return{ingots:(e.ingots??[]).map(ws),nextCursor:e.next_cursor}}function xs(e){return{shared:e.shared,visibility:e.visibility??void 0,publicUrl:e.public_url,linkCode:e.link_code,sharingEnabled:e.sharing_enabled,vaultAllIngotsPublic:e.vault_all_ingots_public,sessionLengthSeconds:e.session_length_seconds,invites:e.invites?.map(Cs)}}function Cs(e){return{id:e.invite_id,identity:e.identity,identityType:e.identity_type,invitedAt:e.created_at}}class Ss{constructor(e){this.http=e}async list(e={}){const t=await this.http.get(Be`/v1/sparks`,{query:{kindling:e.kindling,status:e.status,limit:e.limit,cursor:e.cursor}});return{sparks:(t.data.sparks??[]).map(Es),nextCursor:t.data.next_cursor}}async get(e){const t=Me(e,"sparkId"),n=(await this.http.get(Be`/v1/sparks/${t}`)).data;return{id:n.spark_id,payload:n.payload,contentType:n.content_type??"text/plain",size:n.size_bytes,status:n.status,createdAt:n.created_at,burnedAt:n.burned_at,filename:n.filename,downloadFilename:n.download_filename}}async create(e){if("string"!=typeof e.payload||0===e.payload.length)throw new M("Spark payload is required");const t={payload:e.payload,content_type:e.contentType,ttl_minutes:e.ttlMinutes,kindling:e.kindling,filename:e.filename};e.withKindling&&(t.with_kindling=!0);const n=(await this.http.post(Be`/v1/sparks`,t)).data;return{id:n.spark_id,size:n.size_bytes,status:n.status,createdAt:n.created_at,expiresAt:n.expires_at,ttlMinutes:n.ttl_minutes,filename:n.filename,kindling:n.kindling,linkUrl:n.link_url,linkCode:n.link_code}}async delete(e){const t=Me(e,"sparkId");await this.http.delete(Be`/v1/sparks/${t}`)}async share(e,t={}){const n=Me(e,"sparkId");return _s((await this.http.patch(Be`/v1/sparks/${n}/share`,{visibility:t.visibility,invites:t.invites,expires_in_seconds:t.expiresInSeconds})).data)}async resendInvite(e){const t=Me(e,"sparkId"),n=(await this.http.post(Be`/v1/sparks/${t}/share/resend`)).data;return{sparkId:n.spark_id,identity:n.identity,identityType:n.identity_type,sentAt:n.sent_at}}async getShare(e){const t=Me(e,"sparkId");return _s((await this.http.get(Be`/v1/sparks/${t}/share`)).data)}async unshare(e){const t=Me(e,"sparkId");return _s((await this.http.delete(Be`/v1/sparks/${t}/share`)).data)}}function Es(e){return{id:e.spark_id,contentType:e.content_type??"text/plain",size:e.size_bytes,status:e.status,createdAt:e.created_at,expiresAt:e.expires_at,burnedAt:e.burned_at??null,timeRemaining:e.time_remaining??0,filename:e.filename,kindling:e.kindling,linkUrl:e.link_url}}function _s(e){return{shared:e.shared,shareUrl:e.share_url,linkCode:e.link_code,visibility:e.visibility,invites:e.invites,expiresAt:e.expires_at,createdAt:e.created_at,deliveredTo:e.delivered_to}}class Ts{constructor(e){this.http=e}async generate(e){const t=e.format??"hex";!function(e,t){if(!function(e){return Te.includes(e)}(t))throw new M(`Entropy format must be one of: ${Te.join(", ")}`,{field:"format",received:t});const n=function(e){return Ie.includes(e)?512:Ae}(t);if(!Number.isInteger(e)||e<1||e>n)throw new M(`Entropy byte count must be an integer from 1 to ${n} for the ${t} format`,{field:"bytes",received:e})}(e.bytes,t);const n=(await this.http.post(Be`/v1/entropy/generate`,{num_bytes:e.bytes,format:t})).data;return{value:n.value,numBytes:n.num_bytes,format:n.format,referenceId:n.reference_id}}async generateBytes(e){const t=await this.generate({bytes:e,format:"base64url"});if("string"!=typeof t.value||0===t.value.length)throw new I("Entropy endpoint returned no value","invalid_response");const n=Ee(t.value);if(null===n)throw new I("Entropy endpoint returned a value that is not base64url","invalid_response");if(n.length!==e)throw new I(`Entropy length mismatch: expected ${e}, got ${n.length}`,"invalid_response");return n}}const As=In,Is=$n;function $s(e,t){const n=e.options?.applicationServerKey;if(!n)return!1;const i=new Uint8Array(n);return i.length===t.length&&i.every((e,n)=>e===t[n])}class Ls{constructor(e){this.http=e}async getInbox(e={}){return(await this.http.get(Be`/v1/me/notifications`,{query:{state:e.state,limit:e.limit||void 0,cursor:e.cursor}})).data}async getUnreadCount(){return(await this.http.get(Be`/v1/me/notifications/unread-count`)).data}async markState(e,t){const n=Me(e,"notificationId");if(!Number.isFinite(t?.createdAt))throw new M("createdAt (the row's created_at) is required",{field:"createdAt",received:t?.createdAt});if(!As.includes(t.state))throw new M(`state must be one of ${As.join(", ")}`,{field:"state",received:t.state});return(await this.http.post(Be`/v1/me/notifications/${n}/state`,{created_at:t.createdAt,state:t.state})).data}async markAllState(e){if(!Is.includes(e?.state))throw new M(`state must be one of ${Is.join(", ")}`,{field:"state",received:e?.state});if(void 0!==e.cursor&&"string"!=typeof e.cursor)throw new M("cursor must be the string cursor from a prior response",{field:"cursor",received:e.cursor});const t={state:e.state};e.cursor&&(t.cursor=e.cursor);return(await this.http.post(Be`/v1/me/notifications/state`,t)).data}async markAllRead(){let e,t=0;for(let n=0;n<100;n+=1){const n=await this.markAllState(e?{state:"read",cursor:e}:{state:"read"});if(t+=n?.updated??0,!n?.cursor)return{updated:t,complete:!0};e=n.cursor}return{updated:t,complete:!1}}isWebPushSupported(){return"undefined"!=typeof window&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window}async getWebPushKey(){return(await this.http.get(Be`/v1/me/notifications/web-push/key`)).data}async serverKey(){const e=await this.getWebPushKey();if(!e.configured||!e.vapid_public_key)return null;const t=Ee(e.vapid_public_key);if(null===t)throw new I("The server returned a Web Push key that is not base64url","invalid_response");return t}async getWebPushStatus(e={}){if(!this.isWebPushSupported())return{status:"not_supported"};const t=await this.serverKey();if(null===t)return{status:"not_configured"};const n=e.serviceWorkerRegistration?await e.serviceWorkerRegistration.pushManager.getSubscription():null;return n&&$s(n,t)?{status:"subscribed",subscription:n}:{status:"not_subscribed"}}async registerWebPushSubscription(e){const t=function(e){const t="function"==typeof e.toJSON?e.toJSON():e,n=t.endpoint,i=t.keys?.p256dh,s=t.keys?.auth;if(!n||!i||!s)throw new M("A web push subscription requires endpoint and keys.p256dh/auth");return{endpoint:n,keys:{p256dh:i,auth:s}}}(e);return(await this.http.post(Be`/v1/me/notifications/web-push`,t)).data}async unsubscribeWebPushEndpoint(e){if(!e||"string"!=typeof e)throw new M("endpoint is required");return(await this.http.post(Be`/v1/me/notifications/web-push/unsubscribe`,{endpoint:e})).data}async subscribeWebPush(e){if(!this.isWebPushSupported())return{status:"not_supported"};const t=e?.serviceWorkerRegistration;if(!t||"function"!=typeof t.pushManager?.subscribe)throw new M("serviceWorkerRegistration with a pushManager is required");const n=await this.serverKey();if(null===n)return{status:"not_configured"};if("denied"===Notification.permission)return{status:"permission_denied"};if("default"===Notification.permission){if("granted"!==await Notification.requestPermission())return{status:"permission_denied"}}const i=await t.pushManager.getSubscription(),s=i&&$s(i,n)?i:null;i&&!s&&await this.dropDeadSubscription(i);const o=s??await t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:n});return await this.registerWebPushSubscription(o),{status:s?"already_subscribed":"subscribed",subscription:o}}async dropDeadSubscription(e){await this.unsubscribeWebPushEndpoint(e.endpoint),await e.unsubscribe()}async unsubscribeWebPush(e){const t=e?.serviceWorkerRegistration;if(!t||"function"!=typeof t.pushManager?.getSubscription)return!1;const n=await t.pushManager.getSubscription();return!!n&&(await this.unsubscribeWebPushEndpoint(n.endpoint).catch(()=>{}),n.unsubscribe())}}class Bs{constructor(e){!function(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(!J("account",e.accountId))throw new M("accountId must be a SparkVault account id (acc_...)",{field:"accountId",received:e.accountId})}(e),this.config=function(e){return{accountId:e.accountId,timeout:e.timeout??3e4,apiBaseUrl:le(e.apiBaseUrl??"https://api.sparkvault.com"),identityBaseUrl:de(e.identityBaseUrl??"https://auth.sparkvault.com"),portalBaseUrl:de(e.portalBaseUrl??ae),accessToken:e.accessToken,getAccessToken:e.getAccessToken,apiKey:e.apiKey,clientId:e.clientId,preloadConfig:e.preloadConfig??"undefined"!=typeof window,backdropBlur:!1!==e.backdropBlur,allowedDownloadHostPatterns:e.allowedDownloadHostPatterns??[...se]}}(e);const t=new ve(this.config);this.products=new Dn(this.config,t),this.vaults=new Ni(this.config,t),this.ingots=new vs(this.config,t),this.folders=new ms(t),this.sparks=new Ss(t),this.entropy=new Ts(t),this.notify=new Ls(t),this.health=new ge(this.config)}static init(e){return new Bs(e)}static isRecoveryPending(){return En()}static get version(){return"13.0.6"}}if("undefined"!=typeof window){const e=function(e){if("undefined"==typeof window||"undefined"==typeof document)return null;const t=document.currentScript;if(!t)return null;const n=t.dataset.accountId;if("true"===t.dataset.debug&&qi(!0),!n)return Ki.debug("No data-account-id attribute, skipping auto-init"),null;Ki.info("Auto-initializing SDK...");try{const t=e.init({accountId:n});return Ki.info("SDK initialized successfully"),t}catch(e){return Ki.error("Failed to initialize SDK:",e),null}}(Bs);window.SparkVault=e??Bs}e.AuthenticationError=$,e.AuthorizationError=B,e.EntropyModule=Ts,e.FoldersModule=ms,e.IdentityModule=Tn,e.IdentityProviderError=U,e.IngotsModule=vs,e.NAME_CONFLICT_POLICIES=["upsert","complete_pending","refuse","new_name"],e.NOTIFY_PRESETS=Pn,e.NetworkError=O,e.NotifyModule=Ls,e.NotifyProductModule=Nn,e.NotifySubscriptionRequiredError=N,e.PlanRequiredError=P,e.PopupBlockedError=H,e.ProductsModule=Dn,e.QuotaExceededError=R,e.SparkVault=Bs,e.SparkVaultError=I,e.SparksModule=Ss,e.TimeoutError=z,e.UnauthorizedError=L,e.UserCancelledError=D,e.ValidationError=M,e.VaultsModule=Ni,e.buildNotifyPresetSend=Rn,e.default=Bs,e.fetchDownload=function(e,t={}){return is(()=>Promise.resolve(e),t)},e.isReceivedUploadFailure=pi,e.logger=Ki,e.setDebugMode=qi,Object.defineProperty(e,"__esModule",{value:!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).SparkVault={})}(this,function(e){"use strict";const t=/^tus_[0-9a-f]{32}$/;const n=Object.freeze({UPLOAD_CONTRACT_MISMATCH:"UPLOAD_CONTRACT_MISMATCH",UPLOAD_PROTOCOL_RETIRED:"UPLOAD_PROTOCOL_RETIRED",UPLOAD_SUPERSEDED:"UPLOAD_SUPERSEDED",UPLOAD_POOL_FULL:"UPLOAD_POOL_FULL"}),i=Object.freeze([n.UPLOAD_POOL_FULL,n.UPLOAD_SUPERSEDED]),s=Object.freeze({status:"revoked",reasons:Object.freeze({UPLOAD_SUPERSEDED:n.UPLOAD_SUPERSEDED,INGOT_DELETED:"INGOT_DELETED"})});Object.values(s.reasons);const o="VAULT_DELETION_SCHEDULED",r="upload_received_publishing",a=Object.freeze({OK:"ok",RETRY:"retry",RESYNC:"resync",DEFERRED:"deferred",GONE:"gone",REFUSED:"refused"}),l=new Set([a.RETRY,a.RESYNC]),d=new Set([404,410,412]),c=/^[A-Z][A-Z0-9_]{0,63}$/;function u({status:e,headers:t=null,details:n=null,receipt:i=!1,now:s=Date.now()}){if(!Number.isSafeInteger(e)||e<0)throw new TypeError(`A transfer answer's status is a whole number (0 for no answer), not ${e}`);if(null!==t&&"function"!=typeof t)throw new TypeError("A transfer answer's headers are read through a function from a header name to its value");if("boolean"!=typeof i)throw new TypeError(`Whether a transfer request was the receipt is a boolean, not ${i}`);if(0===e)return{verdict:a.RETRY,retryAfterMs:null,offset:null,coreCode:null};const o=e=>null===t?null:t(e),r=m(o("Upload-Offset")),l=function(e,t){return d.has(e)||409===e&&null===t}(e,r)?function(e){return e&&"object"==typeof e?p(e.coreCode):null}(n)??p(o("X-Upload-Refusal")):null,c=function(e,t){const n=m(e);if(null!==n){const e=1e3*n;return Number.isSafeInteger(e)?e:null}const i="string"==typeof e?function(e,t){let n=b.exec(e);if(n){const[,e,t,i,s,o,r]=n;return x(Number(i),t,Number(e),s,o,r)}if(n=w.exec(e),n){const[,e,i,s,o,r,a]=n;return x(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),o,r,a)}if(n=k.exec(e),n){const[,e,t,i,s,o,r]=n;return x(Number(r),e,Number(t.trim()),i,s,o)}return null}(e.trim(),t):null;return null===i?null:Math.max(0,i-t)}(o("Retry-After"),s);return{verdict:h(e,{offset:r,coreCode:l,deferral:i&&null!==c}),retryAfterMs:c,offset:r,coreCode:l}}function h(e,{offset:t,coreCode:n,deferral:s}){return e>=200&&e<300?a.OK:409===e?null!==t?a.RESYNC:null===n?a.RETRY:a.REFUSED:null!==n?i.includes(n)?a.REFUSED:a.GONE:404===e||410===e?a.GONE:s&&503===e?a.DEFERRED:425===e||function(e){return 408===e||429===e||e>=500}(e)?a.RETRY:a.REFUSED}function p(e){if("string"!=typeof e)return null;const t=e.trim();return c.test(t)?t:null}function m(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}const f=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],v="(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)",g=`(${f.join("|")})`,y="(\\d{2}):(\\d{2}):(\\d{2})",b=new RegExp(`^${v}, (\\d{2}) ${g} (\\d{4}) ${y} GMT$`),w=new RegExp(`^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\\d{2})-${g}-(\\d{2}) ${y} GMT$`),k=new RegExp(`^${v} ${g} ( \\d|\\d{2}) ${y} (\\d{4})$`);function x(e,t,n,i,s,o){const r=f.indexOf(t),[a,l,d]=[Number(i),Number(s),Number(o)];if(a>23||l>59||d>60)return null;const c=new Date(0);return c.setUTCFullYear(e,r,n),c.getUTCFullYear()!==e||c.getUTCMonth()!==r||c.getUTCDate()!==n?null:c.getTime()+1e3*(60*(60*a+l)+d)}let C=0;function S(e){if("string"!=typeof e||0===e.length)throw new TypeError("A transfer jitter key needs the scope its transfer runs in");return C+=1,`${e}#${Date.now()}-${C}`}function E({attempt:e,retryAfterMs:t=null,baseMs:n=1e3,capMs:i=32e3,jitterKey:s}){if(!Number.isSafeInteger(e)||e<1)throw new TypeError(`A retry's attempt is a whole number from 1, not ${e}`);if("string"!=typeof s||0===s.length)throw new TypeError("A retry delay needs the key its transfer spreads by");if(!_(n)||0===n||!_(i)||i<n)throw new TypeError("A retry backs off from a positive base up to a cap no smaller");if(null!==t&&!_(t))throw new TypeError(`A Retry-After floor is a non-negative number of ms, not ${t}`);const o=Math.min(i,n*2**(e-1)),r=Math.floor(function(e){if("string"!=typeof e)throw new TypeError("fnv1a32 hashes a string, not "+typeof e);let t=2166136261;const n=e=>{t=Math.imul(t^e,16777619)>>>0};for(const t of e){let e=t.codePointAt(0);e>=55296&&e<=57343&&(e=65533),e<128?n(e):e<2048?(n(192|e>>6),n(128|63&e)):e<65536?(n(224|e>>12),n(128|e>>6&63),n(128|63&e)):(n(240|e>>18),n(128|e>>12&63),n(128|e>>6&63),n(128|63&e))}return t}(`${s}|${e}`)/2**32*1e3);return Math.max(o+r,t??0)}function _(e){return Number.isFinite(e)&&e>=0}function T({idleLimitMs:e=6e5,maxConsecutiveFailures:t=8,now:n=()=>Date.now()}={}){if(!_(e)||0===e)throw new TypeError(`A transfer's idle limit is a positive number of ms, not ${e}`);if(!Number.isSafeInteger(t)||t<1)throw new TypeError(`A transfer's failure limit is a whole number from 1, not ${t}`);if("function"!=typeof n)throw new TypeError("A transfer budget reads time from a clock function");let i=0,s=0,o=n();const r=()=>n()-o,a=t=>{if(null!==t&&!_(t))throw new TypeError(`A Retry-After floor is a non-negative number of ms, not ${t}`);return r()+(t??0)<e};return Object.freeze({progressed(){i=0,s=0,o=n()},alive(){o=n()},failed(e,n=null){if(!l.has(e))throw new TypeError("A transfer budget records retryable answers only");const s=a(n);return i+=1,s&&i<t},deferred(e=null){const t=a(e);return s+=1,t},get consecutiveFailures(){return i},get attempt(){return i+s},get msSinceProgress(){return r()}})}const A=Object.freeze({INVALID:"invalid",BEYOND_TOTAL:"beyond_total",MISALIGNED:"misaligned"});class I extends Error{constructor(e,t,n,i,s=null,o){super(e),this.name="SparkVaultError",this.code=t,this.statusCode=n,this.details=i,this.retryAfterMs=s,this.serviceCode=o,Object.setPrototypeOf(this,I.prototype)}}class $ extends I{constructor(e,t,n=null,i){super(e,"authentication_error",401,t,n,i),this.name="AuthenticationError",Object.setPrototypeOf(this,$.prototype)}}class L extends I{constructor(e,t,n=null,i){super(e,"UNAUTHORIZED",401,t,n,i),this.name="UnauthorizedError",Object.setPrototypeOf(this,L.prototype)}}class B extends I{constructor(e,t,n=null,i){super(e,"authorization_error",403,t,n,i),this.name="AuthorizationError",Object.setPrototypeOf(this,B.prototype)}}class M extends I{constructor(e,t,n=null,i){super(e,"validation_error",400,t,n,i),this.name="ValidationError",Object.setPrototypeOf(this,M.prototype)}}class P extends I{constructor(e,t,n=null,i){super(e,"PLAN_REQUIRED",402,t,n,i),this.name="PlanRequiredError",Object.setPrototypeOf(this,P.prototype)}}class R extends I{constructor(e,t,n=null,i){super(e,"QUOTA_EXCEEDED",402,t,n,i),this.name="QuotaExceededError";const s=t?.resource;this.resource="storage"===s||"bandwidth"===s?s:void 0,Object.setPrototypeOf(this,R.prototype)}}class N extends I{constructor(e,t,n=null,i){super(e,"NOTIFY_SUBSCRIPTION_REQUIRED",403,t,n,i),this.name="NotifySubscriptionRequiredError",Object.setPrototypeOf(this,N.prototype)}}class O extends I{constructor(e,t){super(e,"network_error",void 0,t),this.name="NetworkError",Object.setPrototypeOf(this,O.prototype)}}class z extends I{constructor(e="Request timed out"){super(e,"timeout_error"),this.name="TimeoutError",Object.setPrototypeOf(this,z.prototype)}}class D extends I{constructor(e="User cancelled the operation"){super(e,"user_cancelled"),this.name="UserCancelledError",Object.setPrototypeOf(this,D.prototype)}}class U extends I{constructor(e){super("The identity provider could not complete the sign-in.",e||"identity_provider_error"),this.name="IdentityProviderError",Object.setPrototypeOf(this,U.prototype)}}class H extends I{constructor(){super("Popup was blocked. Please allow popups for this site.","popup_blocked"),this.name="PopupBlockedError",Object.setPrototypeOf(this,H.prototype)}}class F extends I{constructor(){super("The sign-in window could not communicate with this page.","popup_severed"),this.name="PopupSeveredError",Object.setPrototypeOf(this,F.prototype)}}function V(e){return"string"==typeof e&&e?e:null}function j(e){return"object"!=typeof e||null===e||Array.isArray(e)?void 0:e}function q(e,t,n){const i=j(t)??{},s=j(i.error);return{status:e,message:V(s?.message)??V(i.message)??V(i.error)??"Request failed",code:V(s?.code)??V(i.code)??"api_error",details:j(s?.details)??j(i.details),retryAfterMs:u({status:e,headers:n}).retryAfterMs}}function W(e){return q(e.status,function(e){try{return JSON.parse(e)}catch{return null}}(e.body),e.header)}async function K(e){return q(e.status,await e.json().catch(()=>null),t=>e.headers.get(t))}const G=Object.freeze({account:"acc",attachment:"hda",folder:"fld",helpDeskJob:"hdj",knowledgeBaseArticle:"hdkba",knowledgeBaseCategory:"hdkbc",knowledgeBaseRevision:"hdkbr",knowledgeBaseAsset:"hdkbm",ingot:"ing",invite:"inv",notification:"ntf",requester:"hrq",routingRule:"hdr",savedReply:"hds",spark:"spk",team:"team",ticket:"tkt",ticketEvent:"hdev",user:"usr",vault:"vlt"});function Y(e){if(!Object.hasOwn(G,e))throw new TypeError(`No resource kind '${e}'`);return`^${G[e]}_[A-Za-z0-9_-]+$`}const X=Object.freeze(Object.fromEntries(Object.keys(G).map(e=>[e,new RegExp(Y(e))])));function J(e,t){if(!Object.hasOwn(G,e))throw new TypeError(`No resource kind '${e}'`);return"string"==typeof t&&t.length<=128&&X[e].test(t)}const Q=Object.freeze(Object.keys(G));function Z(e){return Q.some(t=>J(t,e))}const ee="sparkvault.com",te="auth.sv",ne=Object.freeze([te,"x.sv","files.sv","file.sv","spark.sv","by.sv","at.sv","db.sv"]);function ie(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const se=Object.freeze([new RegExp(`(^|\\.)${ie(ee)}$`,"i"),new RegExp(`^(${ne.map(ie).join("|")})$`,"i")]);function oe(e){return"string"!=typeof e?"":e.trim().toLowerCase().replace(/\.$/,"")}function re(e){return function(e){const t=oe(e);return t===ee||t.endsWith(`.${ee}`)}(e)||function(e){return ne.includes(oe(e))}(e)}const ae=`https://${te}`;function le(e){const t=e.replace(/\/+$/,"");return t.endsWith("/v1")?t.slice(0,-3):t}function de(e){return e.replace(/\/+$/,"")}function ce(e,t){return e.allowedDownloadHostPatterns.some(e=>e.test(t))}async function ue(e){try{return await e.json()}catch(e){if(e instanceof SyntaxError)return null;throw e}}async function he(e,t,n){const{timeoutMs:i,closeSignal:s,read:o,fail:r}=n;if(s?.aborted)throw r("cancelled",null);const{signal:a,dispose:l}=function(e,t){const n=new AbortController,i=setTimeout(()=>n.abort(),e);let s=n.signal,o=null;return t&&"any"in AbortSignal?s=AbortSignal.any([n.signal,t]):t&&(o=()=>n.abort(),t.addEventListener("abort",o)),{signal:s,dispose:()=>{clearTimeout(i),t&&o&&t.removeEventListener("abort",o)}}}(i,s);try{return await o(await fetch(e,{...t,signal:a}))}catch(e){if(e instanceof I)throw e;if(function(e){return null!=e&&"object"==typeof e&&"name"in e&&"AbortError"===e.name}(e))throw r(s?.aborted?"cancelled":"timeout",e);if(e instanceof TypeError)throw r("network",e);throw r("unknown",e)}finally{l()}}class pe{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 he(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:o}=await K(e);throw this.makeError(n,i,t,s,o)}return{data:await ue(e),status:e.status}})}}function me(e){if("string"!=typeof e||""===e||"."===e||".."===e)return null;try{return encodeURIComponent(e)}catch{return null}}function fe(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}`:""}class ve{constructor(e){this.config=e}async getDefaultHeaders(e,t,n){const i={Accept:"application/json",...e};if(t&&(i["Content-Type"]="application/json"),n&&(i["X-Vault-Access-Token"]=n),!i.Authorization){const e=await this.getAccessToken();e&&(i.Authorization=`Bearer ${e}`)}return this.config.apiKey&&!i["X-API-Key"]&&(i["X-API-Key"]=this.config.apiKey),i}async getAccessToken(){return this.config.getAccessToken?this.config.getAccessToken():this.config.accessToken??null}async request(e,t={}){const{method:n="GET",headers:i={},body:s,query:o,vat:r,timeout:a=this.config.timeout}=t;return he(`${this.config.apiBaseUrl}${e}${fe(o)}`,{method:n,headers:await this.getDefaultHeaders(i,void 0!==s,r),body:s?JSON.stringify(s):void 0},{timeoutMs:a,read:async e=>{if(!e.ok)throw this.createErrorFromResponse(await K(e));return{data:this.unwrapApiResponse(await this.parseResponse(e))}},fail:(e,t)=>{switch(e){case"timeout":return new z;case"network":return new O("Network request failed. Please check your connection.");default:return new I(t instanceof Error?t.message:"Unknown error","unknown_error")}}})}async parseResponse(e){const t=e.headers.get("content-length");if(204===e.status||"0"===t)return null;const n=e.headers.get("content-type");if(n?.includes("application/json")){return await e.json()}const i=await e.text();throw new I(`Unexpected response format: expected JSON but received ${n??"unknown content type"}`,"invalid_response_format",e.status,{body:i.slice(0,500)})}createErrorFromResponse({status:e,message:t,code:n,details:i,retryAfterMs:s}){switch(e){case 400:return new M(t,i,s,n);case 401:return"UNAUTHORIZED"===n?new L(t,i,s,n):new $(t,i,s,n);case 402:return"QUOTA_EXCEEDED"===n?new R(t,i,s,n):new P(t,i,s,n);case 403:return"NOTIFY_SUBSCRIPTION_REQUIRED"===n?new N(t,i,s,n):new B(t,i,s,n);default:return new I(t,n,e,i,s,n)}}unwrapApiResponse(e){if("object"==typeof e&&null!==e){if("data"in e&&("meta"in e||"error"in e))return e.data}return e}get(e,t){return this.request(e,{...t,method:"GET"})}post(e,t,n){return this.request(e,{...n,method:"POST",body:t})}put(e,t,n){return this.request(e,{...n,method:"PUT",body:t})}patch(e,t,n){return this.request(e,{...n,method:"PATCH",body:t})}delete(e,t){return this.request(e,{...t,method:"DELETE"})}}class ge{constructor(e){this.config=e}async check(e={}){const t=Math.floor(Date.now()/1e3),n=new AbortController,i=setTimeout(()=>n.abort(),e.timeout??this.config.timeout);try{const e=await fetch(`${this.config.apiBaseUrl}/health`,{method:"GET",headers:{Accept:"application/json"},signal:n.signal});return{online:e.ok,status:e.ok?await this.readStatus(e):"unhealthy",httpStatus:e.status,checkedAt:t}}catch(e){return{online:!1,status:"unreachable",checkedAt:t,error:e instanceof Error?e.message:String(e)}}finally{clearTimeout(i)}}async isOnline(e={}){return(await this.check(e)).online}async readStatus(e){try{const t=await e.json(),n="object"==typeof t&&null!==t&&"data"in t?t.data:t;if("object"==typeof n&&null!==n){const e=n.status;if("string"==typeof e&&e)return e}}catch{return e.ok?"healthy":"unhealthy"}return e.ok?"healthy":"unhealthy"}}function ye(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}}const be=ye("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",!0),we=ye("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",!1);function ke(e){return 9===e||10===e||12===e||13===e||32===e}function xe(e){return ArrayBuffer.isView(e)&&"[object Uint8Array]"===Object.prototype.toString.call(e)}function Ce(e,t){if(!xe(e))throw new TypeError("Base64 encoding takes a Uint8Array");const{codes:n}=t,i=e.length%3,s=e.length-i;let o=0;i>0&&(o=t.padded?4:i+1);const r=new Uint8Array(s/3*4+o);let a=0;for(let t=0;t<s;t+=3){const i=e[t]<<16|e[t+1]<<8|e[t+2];r[a++]=n[i>>18],r[a++]=n[i>>12&63],r[a++]=n[i>>6&63],r[a++]=n[63&i]}if(i>0){const t=e[s]<<16|(2===i?e[s+1]<<8:0);r[a++]=n[t>>18],r[a++]=n[t>>12&63],2===i&&(r[a++]=n[t>>6&63]),r.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}(r)}function Se(e){return Ce(e,we)}function Ee(e,{canonical:t=!1}={}){return function(e,t,n){if("string"!=typeof e)return null;const{values:i}=t;let s=0,o=0;for(let t=0;t<e.length;t+=1){const r=e.charCodeAt(t);if(ke(r)){if(n)return null}else if(61===r)o+=1;else{if(o>0||r>127||i[r]<0)return null;s+=1}}const r=s%4;if(1===r)return null;if(o>0&&(o>2||(s+o)%4!=0))return null;if(n&&o!==(t.padded?(4-r)%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;ke(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,we,t)}function _e(e){return Ce((new TextEncoder).encode(e),be)}const Te=Object.freeze(["hex","base64","base64url","alphanumeric","alphanumeric-mixed","password","numeric","uuid","bytes"]),Ae=1024,Ie=Object.freeze(["alphanumeric","alphanumeric-mixed","password"]);const $e=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>Ae)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 Le(e){const{codeVerifier:t,state:n,nonce:i}=function(e,t){if(!xe(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,o]of t.fields)n[s]=e.subarray(i,i+o),i+=o;return n}(e,$e);return{codeVerifier:Se(t),state:Se(n),nonce:Se(i)}}function Be(e,...t){const n=function(e,t){let n=e[0];for(let i=0;i<t.length;i+=1){const s=me(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===me(e))});return n}function Me(e,t){if("string"!=typeof e||!Z(e))throw new M(`${t} must be a SparkVault resource id`,{field:t,received:e});return e}function Pe(e){return Me(e?.id,"vault.id")}$e.bytes;class Re{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 Ne{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 Oe(e){return Se(new Uint8Array(e))}function ze(){return`${window.location.origin}${window.location.pathname}${window.location.search}`}function De(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"),n&&(i.set("redirect_uri",n.redirectUri),i.set("state",n.state),i.set("code_challenge",n.codeChallenge)),`${e.identityBaseUrl}/${e.accountId}/signin?${i}`}class Ue extends pe{constructor(e,t){super(t),this.configCache=null,this.config=e}get baseUrl(){return`${this.config.identityBaseUrl}${Be`/${this.config.accountId}`}`}makeError(e,t,n,i,s=null){return new je(e,t,n,i,s)}async request(e,t,n,i){const{data:s}=await this.rawRequest(`${this.baseUrl}${t}${fe(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",Be`/config`));try{return await this.configCache}catch(e){throw this.configCache=null,e}}preloadConfig(){if(this.configCache)return;const e=this.request("GET",Be`/config`);this.configCache=e,e.catch(()=>{})}isConfigPreloaded(){return null!==this.configCache}async drawAuthorizationValues(){return Le(function(e,t){const n=Ee(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}(await this.request("POST",Be`/entropy`,{num_bytes:$e.bytes}),$e.bytes))}async checkPasskey(e,t="email",n){const i="phone"===t?{phone:e}:{email:e};return this.request("POST",Be`/passkey/check`,{...i,...He(n)})}async redeemHandoffCode(e,t){return this.request("POST",Be`/signin/redeem`,{code:e,code_verifier:t})}buildAuthContextParams(e){return{...e?.authRequestId?{auth_request_id:e.authRequestId}:{},...He(e)}}async sendOtp(e){return this.request("POST",Be`/otp/send`,{recipient:e.recipient,method:e.method,...this.buildAuthContextParams(e.authContext)})}async verifyOtp(e){return this.request("POST",Be`/otp/verify`,{kindling:e.kindling,pin:e.pin,recipient:e.recipient,...this.buildAuthContextParams(e.authContext)})}async submitSecondFactor(e){return this.request("POST",Be`/second-factor/verify`,{ticket:e.ticket,code:e.code})}async startPasskeyVerify(e,t="email",n){const i=e?{[t]:e}:{},s=await this.request("POST",Be`/passkey/verify`,{...i,...He(n)});return{challenge:s.options.challenge,rpId:s.options.rpId,timeout:s.options.timeout,...s.options.allowCredentials?{allowCredentials:s.options.allowCredentials}:{},session:s.session}}async completePasskeyVerify(e){const t=e.credential.response;return this.request("POST",Be`/passkey/verify/complete`,{session:e.session,...this.buildAuthContextParams(e.authContext),credential:{id:e.credential.id,rawId:Oe(e.credential.rawId),type:e.credential.type,response:{clientDataJSON:Oe(t.clientDataJSON),authenticatorData:Oe(t.authenticatorData),signature:Oe(t.signature),userHandle:t.userHandle?Oe(t.userHandle):null}}})}async sendBackupVerification(e){return this.request("POST",Be`/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",Be`/backup-verification/verify`,{session_id:e.sessionId,code:e.code})}async dismissRecommendation(e){await this.request("POST",Be`/recommendations/dismiss`,{verification_token:e.verificationToken,key:e.key})}getSocialAuthUrl(e,t,n,i){const s=new URLSearchParams({redirect_uri:t,state:n});i?.authRequestId&&s.set("auth_request_id",i.authRequestId);const{simple_mode:o}=He(i);return o&&s.set("simple_mode",JSON.stringify(o)),`${this.baseUrl}/social/${e}?${s}`}async sendSparkLink(e,t,n){return this.request("POST",Be`/sparklink/send`,{email:e,connection_id:t,...this.buildAuthContextParams(n)})}async consumeSparkLinkResult(e){return Fe(await this.request("GET",Be`/sparklink/result`,void 0,{kindling:e}))}}function He(e){return e?.simpleMode?{simple_mode:{session_id:e.simpleMode.sessionId}}:{}}function Fe(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:Ve(t.recommendations)}}:null}function Ve(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 je extends I{constructor(e,t,n,i,s=null){super(e,t,n,i,s),this.name="IdentityApiError",Object.setPrototypeOf(this,je.prototype)}}const qe=/^\D*\+/,We=/^[1-9]\d{7,14}$/,Ke=/\p{Cf}/gu,Ge=/^[\s().\p{Pd}]*\+?[\d\s().\p{Pd}]*$/u,Ye=/^[+(\d]/;function Xe(e){return e.replace(Ke,"")}function Je(e){if("string"!=typeof e)return null;const t=Xe(e);if(!Ge.test(t))return null;const n=t.replace(/\D/g,"");return qe.test(t)?We.test(n)?`+${n}`:null:10===n.length?`+1${n}`:11===n.length&&n.startsWith("1")?`+${n}`:null}function Qe(e){if("string"!=typeof e)return"email";const t=Xe(e).trim();return Ye.test(t)&&Ge.test(t)?"phone":"email"}function Ze(e){const t=Xe(e);if(!Ge.test(t))return e;const n=t.replace(/\D/g,"");if(qe.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 et={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"}};function tt(e){return e.map(e=>et[e]).filter(e=>void 0!==e)}class nt{constructor(){this._sdkConfig=null,this._viewState={view:"loading"},this._recipient="",this._identityType="email",this._authContext=void 0,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 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 it{openPopup(e){const t=e.width??480,n=e.height??640,i=e.timeoutMs??18e5;return new Promise((s,o)=>{const r=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=${r},top=${a},popup=1`);if(!l)return void o(new H);e.onOpen?.(l);const d=Date.now();let c=!1,u=!1;const h=()=>{window.removeEventListener("message",p),clearTimeout(m),clearInterval(f)},p=t=>{if(t.origin!==e.trustedOrigin)return;const n=t.data;if(e.readyType&&n?.type===e.readyType)return u=!0,void e.onReady?.();n?.type===e.resultType&&(c=!0,h(),s(n))};window.addEventListener("message",p);const m=setTimeout(()=>{c||(c=!0,h(),l.close(),o(new z("Popup operation timed out. Please try again.")))},i),f=setInterval(()=>{if(l.closed&&!c){if(c=!0,h(),!u&&Date.now()-d<=2500)return void o(new F);o(new D("Authentication was cancelled."))}},500)})}}function st(e){const t=Ee(e);if(null===t)throw new je("The passkey options are not valid base64url","invalid_response",0);return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}class ot{constructor(e,t){this.api=e,this.state=t,this.popupLauncher=new it;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),i=await navigator.credentials.get({...e?{signal:e}:{},publicKey:{challenge:st(n.challenge),rpId:n.rpId,timeout:n.timeout,userVerification:"required",...n.allowCredentials?{allowCredentials:n.allowCredentials.map(e=>({type:e.type,id:st(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});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 je?"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}=He(i);s&&n.set("simple_mode",JSON.stringify(s));const o="register"===e&&t?`#${new URLSearchParams({registration_token:t}).toString()}`:"",r=`${this.baseUrl}/${this.accountId}/passkey/popup?${n}${o}`;let a;try{a=await this.popupLauncher.openPopup({url:r,windowName:"sparkvault-passkey",width:450,height:500,resultType:"sparkvault-passkey-result",trustedOrigin:this.trustedOrigin})}catch(e){return e instanceof H?{success:!1,error:e.message,errorType:"popup_blocked"}:e instanceof D?{success:!1,error:e.message,errorType:"cancelled"}:{success:!1,error:e instanceof Error?e.message:"Passkey operation failed. Please try again.",errorType:"unknown"}}return a.success&&a.data?{success:!0,result:{token:a.data.token||"",identity:a.data.identity||this.state.recipient,identityType:a.data.identity_type||"email",svid:a.data.svid,sessionId:a.data.session_id,refreshToken:a.data.refresh_token,redirect:a.data.redirect}}:this.handlePopupError(a.error,a.message,a.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 rt{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});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 I?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});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 I?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});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:Ve(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 I?e.code:void 0}}}}class at{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);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 I?e.code:void 0}}}}const lt=new RegExp("^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$"),dt=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,ct=Object.freeze({ADDRESS:320,LOCAL_PART:64,DOMAIN:255}),ut=Object.freeze({FORMAT:"format",TOO_LONG:"too_long",LOCAL_PART_TOO_LONG:"local_part_too_long",DOMAIN_TOO_LONG:"domain_too_long"});function ht(e){if("string"!=typeof e)throw new TypeError("An email address is a string");return e.trim().toLowerCase()}function pt(e){return null===function(e){if("string"!=typeof e)return ut.FORMAT;const t=ht(e),n=t.indexOf("@");if(n<=0||n!==t.lastIndexOf("@"))return ut.FORMAT;const i=t.slice(0,n),s=t.slice(n+1),o=s.split(".");return!lt.test(i)||o.length<2||!o.every(e=>dt.test(e))?ut.FORMAT:t.length>ct.ADDRESS?ut.TOO_LONG:i.length>ct.LOCAL_PART?ut.LOCAL_PART_TOO_LONG:s.length>ct.DOMAIN?ut.DOMAIN_TOO_LONG:null}(e)}function mt(e,t){const n=document.createElement("div");return e&&(n.className=e),n}function ft(e){for(;e.firstChild;)e.removeChild(e.firstChild)}function vt(e){const t=document.createElement("div");return t.className="sv-error",t.setAttribute("role","alert"),t.textContent=e,t}function gt(e){return pt(e)?ht(e):null}class yt{constructor(e={}){this.message=e.message??"Loading..."}render(){const e=mt("sv-loading"),t=document.createElement("div");t.className="sv-spinner",t.setAttribute("role","status"),t.setAttribute("aria-label","Loading");const n=document.createElement("p");return n.className="sv-loading-text",n.textContent=this.message,e.appendChild(t),e.appendChild(n),e}destroy(){}}class bt{constructor(e){this.inputElement=null,this.labelElement=null,this.submitButton=null,this.passkeyLink=null,this.errorContainer=null,this.focusTimeoutId=null,this.detectedType="email",this.props=e,this.boundHandleInput=()=>this.handleInput(),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=mt("sv-email-view"),t=mt("sv-email-header"),n=document.createElement("p");n.className="sv-email-subtitle",n.textContent=this.getSubtitleText(),t.appendChild(n),e.appendChild(t),this.errorContainer=mt("sv-email-error-container"),this.props.error&&this.errorContainer.appendChild(vt(this.props.error)),e.appendChild(this.errorContainer);const i=mt("sv-email-form"),s=mt("sv-email-input-wrapper");return 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=ct.ADDRESS,this.props.initialValue&&(this.inputElement.value=this.props.initialValue,this.detectAndUpdateType(this.props.initialValue)),this.inputElement.addEventListener("input",this.boundHandleInput),this.inputElement.addEventListener("keydown",this.boundHandleKeyDown),s.appendChild(this.labelElement),s.appendChild(this.inputElement),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}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.detectedType?"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"}handleInput(){if(this.clearError(),!this.inputElement)return;const e=this.inputElement.value;if(this.allowsBoth){const t="phone"===this.detectedType;this.detectAndUpdateType(e),t!==("phone"===this.detectedType)&&this.labelElement&&(this.labelElement.textContent=this.getLabelText())}else if(this.allowsPhone){const t=this.inputElement.selectionStart??e.length,n=Ze(e);if(n!==e){this.inputElement.value=n;const i=Math.min(t+(n.length-e.length),n.length);this.inputElement.setSelectionRange(i,i)}}}detectAndUpdateType(e){this.detectedType=Qe(e)}clearError(){this.errorContainer&&ft(this.errorContainer),this.inputElement?.classList.remove("sv-email-input-error")}showError(e){this.errorContainer&&(ft(this.errorContainer),this.errorContainer.appendChild(vt(e))),this.inputElement?.classList.add("sv-email-input-error"),this.inputElement?.focus()}handleSubmit(){if(!this.inputElement||!this.submitButton)return;const e=this.inputElement.value;if(this.allowsBoth)if("phone"===this.detectedType){const t=Je(e);if(!t)return void this.showError("Please enter a valid phone number");this.submitButton.disabled=!0,this.submitButton.textContent="Please wait...",this.props.onSubmit({value:t,type:"phone"})}else{const t=gt(e);if(!t)return void this.showError("Please enter a valid email address");this.submitButton.disabled=!0,this.submitButton.textContent="Please wait...",this.props.onSubmit({value:t,type:"email"})}else if(this.allowsPhone){const t=Je(e);if(!t)return void this.showError("Please enter a valid phone number");this.submitButton.disabled=!0,this.submitButton.textContent="Please wait...",this.props.onSubmit({value:t,type:"phone"})}else{const t=gt(e);if(!t)return void this.showError("Please enter a valid email address");this.submitButton.disabled=!0,this.submitButton.textContent="Please wait...",this.props.onSubmit({value:t,type:"email"})}}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.passkeyLink&&this.boundHandlePasskey&&this.passkeyLink.removeEventListener("click",this.boundHandlePasskey)}}function wt(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 kt(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 xt(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 Ct(){const e=wt("0 0 16 16");return e.appendChild(kt("M13.25 4.75L6 12 2.75 8.75",{stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"})),e}function St(){const e=wt("0 0 16 16");return e.appendChild(kt("M10 12L6 8L10 4",{stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"})),e}function Et(){const e=wt("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(xt(-9.5,-9.5,9.5,n)),t.appendChild(kt("M-2.8 -2.8L16 16",n)),t.appendChild(kt("M9.5 9.5L9.5 15.5",n)),t.appendChild(kt("M16 16L16 22",n)),e.appendChild(t),e}function _t(e){const t=wt("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(kt("M24 9L5.5 39h37L24 9z",n)),t.appendChild(kt("M24 20v8",n)),t.appendChild(xt(24,33.5,1.5,{fill:"currentColor"})),t}function Tt(e){const t=function(e){switch(e){case"email":return function(){const e=wt("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(kt("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(kt("M18 5l-8 5.5L2 5")),e}();case"sms":return function(){const e=wt("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(kt("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(xt(7,8,.75,{fill:"currentColor",stroke:"none"})),e.appendChild(xt(10,8,.75,{fill:"currentColor",stroke:"none"})),e.appendChild(xt(13,8,.75,{fill:"currentColor",stroke:"none"})),e}();case"phone":return function(){const e=wt("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(kt("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=wt("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(kt("M2 10c0-4.42 3.58-8 8-8 2.65 0 5 1.29 6.47 3.28")),e.appendChild(kt("M4 16.58c.42-.35.79-.76 1.1-1.22")),e.appendChild(kt("M14.41 17.51c.09-.45.32-1.73.38-2.26")),e.appendChild(kt("M10 8.33a1.5 1.5 0 00-1.5 1.5c0 .77-.08 1.88-.2 3")),e.appendChild(kt("M7.21 18.33c.16-.5.34-1 .43-1.5")),e.appendChild(kt("M11.67 10.93c0 1.79 0 4.79-.75 6.65")),e.appendChild(kt("M17.33 13.33c.15-1.5.1-4.02 0-4.5")),e.appendChild(kt("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=wt("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(kt("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(kt("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":return function(){const e=wt("0 0 20 20",20,20);return e.appendChild(kt("M18.8 10.21c0-.65-.06-1.28-.17-1.88H10v3.55h4.93c-.21 1.14-.87 2.11-1.84 2.76v2.3h2.98c1.73-1.6 2.73-3.96 2.73-6.73z",{fill:"#4285F4"})),e.appendChild(kt("M10 19.17c2.48 0 4.55-.82 6.07-2.23l-2.98-2.3c-.82.55-1.86.88-3.09.88-2.38 0-4.4-1.6-5.13-3.77H1.82v2.37c1.52 3.02 4.6 5.05 8.18 5.05z",{fill:"#34A853"})),e.appendChild(kt("M4.87 11.74c-.18-.55-.29-1.14-.29-1.74s.1-1.19.29-1.74V5.89H1.82c-.6 1.23-.94 2.6-.94 4.11s.34 2.88.94 4.11l3.05-2.37z",{fill:"#FBBC05"})),e.appendChild(kt("M10 4.48c1.35 0 2.55.47 3.5 1.37l2.63-2.63C14.53 1.74 12.47.83 10 .83c-3.58 0-6.66 2.03-8.18 5.05l3.05 2.37c.72-2.17 2.75-3.77 5.13-3.77z",{fill:"#EA4335"})),e}();case"apple":return function(){const e=wt("0 0 20 20",20,20);return e.setAttribute("fill","currentColor"),e.appendChild(kt("M14.21 16.9c-.82.79-1.71.67-2.57.29-.91-.38-1.74-.4-2.7 0-1.2.51-1.83.37-2.55-.29C2.7 12.71 3.3 6.33 7.54 6.09c1.13.06 1.91.61 2.57.66.98-.2 1.92-.78 2.97-.7 1.26.1 2.21.6 2.83 1.5-2.6 1.56-1.98 4.99.4 5.94-.48 1.25-1.09 2.49-2.11 3.41h.01zM10.02 6.04c-.12-1.86 1.38-3.39 3.11-3.54.24 2.15-1.95 3.75-3.11 3.54z")),e}();case"microsoft":return function(){const e=wt("0 0 20 20",20,20);return e.appendChild(kt("M1 1h8.33v8.33H1z",{fill:"#F25022"})),e.appendChild(kt("M1 10.67h8.33V19H1z",{fill:"#00A4EF"})),e.appendChild(kt("M10.67 1H19v8.33h-8.33z",{fill:"#7FBA00"})),e.appendChild(kt("M10.67 10.67H19V19h-8.33z",{fill:"#FFB900"})),e}();case"github":return function(){const e=wt("0 0 20 20",20,20);return e.setAttribute("fill","currentColor"),e.appendChild(kt("M10 0C4.48 0 0 4.48 0 10c0 4.42 2.86 8.17 6.84 9.49.5.09.68-.22.68-.48 0-.24-.01-1.02-.01-1.86-2.51.46-3.16-.61-3.36-1.18-.11-.29-.6-1.18-1.02-1.41-.35-.19-.85-.65-.01-.66.79-.01 1.35.72 1.54 1.02.9 1.51 2.34 1.09 2.91.83.09-.65.35-1.09.64-1.34-2.22-.25-4.55-1.11-4.55-4.94 0-1.09.39-1.99 1.02-2.69-.1-.25-.45-1.27.1-2.65 0 0 .84-.27 2.75 1.02.8-.22 1.65-.33 2.5-.33s1.7.11 2.5.33c1.91-1.3 2.75-1.02 2.75-1.02.55 1.38.2 2.4.1 2.65.64.7 1.02 1.59 1.02 2.69 0 3.84-2.34 4.69-4.57 4.94.36.31.67.91.67 1.85 0 1.34-.01 2.41-.01 2.75 0 .27.18.58.69.48C17.14 18.16 20 14.42 20 10c0-5.52-4.48-10-10-10z")),e}();case"facebook":return function(){const e=wt("0 0 20 20",20,20);return e.appendChild(kt("M20 10.06c0-5.52-4.48-10-10-10S0 4.53 0 10.06c0 4.99 3.66 9.13 8.44 9.88v-6.99H5.9v-2.89h2.54V7.85c0-2.51 1.49-3.89 3.78-3.89 1.09 0 2.24.2 2.24.2v2.46h-1.26c-1.24 0-1.63.77-1.63 1.56v1.88h2.77l-.44 2.89h-2.33v6.99c4.78-.75 8.44-4.89 8.44-9.88z",{fill:"#1877F2"})),e}();case"linkedin":return function(){const e=wt("0 0 20 20",20,20);return e.appendChild(kt("M17.04 17.04h-2.96v-4.64c0-1.11-.02-2.53-1.54-2.53-1.55 0-1.78 1.2-1.78 2.45v4.73H7.8V7.5h2.84v1.3h.04c.4-.75 1.36-1.54 2.81-1.54 3 0 3.56 1.98 3.56 4.55v5.24zM4.45 6.19c-.95 0-1.72-.77-1.72-1.72s.77-1.72 1.72-1.72 1.72.77 1.72 1.72-.77 1.72-1.72 1.72zm1.48 10.85H2.96V7.5h2.97v9.54zM18.52 0H1.47C.66 0 0 .65 0 1.44v17.12c0 .79.66 1.44 1.48 1.44h17.04c.82 0 1.48-.65 1.48-1.44V1.44c0-.79-.66-1.44-1.48-1.44z",{fill:"#0A66C2"})),e}();case"building":return function(){const e=wt("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(kt("M2.5 17.5h15")),e.appendChild(kt("M4.17 17.5V5.83L10.83 2.5v15")),e.appendChild(kt("M15.83 17.5V9.17l-5-3.33")),e.appendChild(kt("M7.5 7.5v.01")),e.appendChild(kt("M7.5 10v.01")),e.appendChild(kt("M7.5 12.5v.01")),e.appendChild(kt("M7.5 15v.01")),e}();case"users":return function(){const e=wt("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(kt("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(xt(7.5,5.83,3.33,{stroke:"currentColor","stroke-width":"1.5",fill:"none"})),e.appendChild(kt("M19.17 17.5v-1.67a3.33 3.33 0 00-2.5-3.22")),e.appendChild(kt("M13.33 2.6a3.33 3.33 0 010 6.46")),e}();default:return function(){const e=wt("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(kt("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(xt(10,10,1.25,{fill:"currentColor",stroke:"none"})),e}()}}(e);return t.setAttribute("data-sv-method-icon",e),t}class At{constructor(e){this.backLink=null,this.methodButtons=[],this.methodClickHandlers=new Map,this.props=e,this.boundHandleBack=()=>this.props.onBack?.()}render(){const e=mt();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=mt();for(const e of this.props.methods){const t=this.createMethodButton(e);this.methodButtons.push(t),s.appendChild(t)}return this.backLink&&e.appendChild(this.backLink),e.appendChild(t),i&&e.appendChild(i),e.appendChild(s),e}createBackLink(){const e=document.createElement("button");e.className="sv-back-link",e.appendChild(St());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=document.createElement("button");t.className="sv-btn sv-btn-method";const n=mt("sv-method-content"),i=this.getMethodIcon(e);n.appendChild(i);const s=mt("sv-method-text"),o=document.createElement("div");o.className="sv-method-name",o.textContent=e.name;const r=document.createElement("div");r.className="sv-method-description",r.textContent=e.description,s.appendChild(o),s.appendChild(r),n.appendChild(s),t.appendChild(n);const a=()=>this.props.onSelectMethod(e);return this.methodClickHandlers.set(t,a),t.addEventListener("click",a),t}getMethodIcon(e){const t=mt("sv-method-icon");return t.appendChild(Tt(e.icon)),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 It(e){return function(e,t){return e?String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,t):""}(e,"&#39;")}class $t{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=mt();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>${It(this.props.email)}</strong>`,this.errorContainer=mt(),this.props.error&&this.errorContainer.appendChild(vt(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 o=mt("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),o.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(o),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(St()),e.appendChild(document.createTextNode(" Choose another method")),e.addEventListener("click",this.boundHandleBack),e}createInputGroup(){const e=mt("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&&ft(this.errorContainer),this.inputElements.forEach(e=>e.classList.remove("sv-input-error"))}showError(e){this.errorContainer&&(ft(this.errorContainer),this.errorContainer.appendChild(vt(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 Ne({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 Re({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 Lt{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=mt();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=mt(),this.props.error&&this.errorContainer.appendChild(vt(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&&ft(this.errorContainer),this.input?.classList.remove("sv-input-error")}showError(e){this.errorContainer&&(ft(this.errorContainer),this.errorContainer.appendChild(vt(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 Bt{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=mt();this.backLink=this.props.onBack?this.createBackLink():null;const t=mt();t.appendChild(Et());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>${It(this.props.identityLabel)}</strong><br>to sign in faster next time`:i.innerHTML="Use a passkey linked to your SparkVault Identity",this.errorContainer=mt(),this.props.error&&this.errorContainer.appendChild(vt(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 o="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=o,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(St()),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&&(ft(this.errorContainer),this.errorContainer.appendChild(vt(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 Mt{constructor(e){this.fallbackLink=null,this.props=e,this.boundHandleFallback=()=>this.props.onUseAnotherMethod()}render(){const e=mt(),t=mt();t.appendChild(Et());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 o=mt("sv-loading");return o.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(o),e.appendChild(this.fallbackLink),e}destroy(){this.fallbackLink&&this.fallbackLink.removeEventListener("click",this.boundHandleFallback)}}class Pt{constructor(e){this.addButton=null,this.skipLink=null,this.props=e,this.boundHandleAdd=()=>this.props.onAddPasskey(),this.boundHandleSkip=()=>this.props.onSkip()}render(){const e=mt(),t=mt();t.appendChild(Et());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>${It(this.props.identityLabel)}</strong>`;const s=mt();this.props.error&&s.appendChild(vt(this.props.error));const o=document.createElement("div");o.className="sv-passkey-prompt-benefits";const r=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(Ct()),t.appendChild(document.createTextNode(e)),r.appendChild(t)}return o.appendChild(r),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(o),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 Rt{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=mt("sv-email-view"),t=mt("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=mt("sv-email-error-container"),this.props.error&&this.errorContainer.appendChild(vt(this.props.error)),e.appendChild(this.errorContainer);const s=mt("sv-email-form"),o=mt("sv-email-input-wrapper"),r=document.createElement("label");return r.className="sv-email-label",r.htmlFor="sv-backup-input",r.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=ct.ADDRESS,this.inputElement.addEventListener("input",this.boundHandleInput),this.inputElement.addEventListener("keydown",this.boundHandleKeyDown),o.appendChild(r),o.appendChild(this.inputElement),s.appendChild(o),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=Ze(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&&ft(this.errorContainer),this.inputElement?.classList.remove("sv-email-input-error")}showError(e){this.errorContainer&&(ft(this.errorContainer),this.errorContainer.appendChild(vt(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?Je(e):gt(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 Nt{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=mt();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>${It(this.props.email)}</strong>`,this.waitingSection=mt("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=mt("sv-sparklink-countdown");const o=document.createElement("span");o.textContent="Link expires in ",this.countdownElement=document.createElement("span"),this.countdownElement.className="sv-sparklink-countdown-time",this.startExpirationTimer(),this.countdownSection.appendChild(o),this.countdownSection.appendChild(this.countdownElement);const r=mt("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),r.appendChild(this.resendButton);const a=mt("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(r),e.appendChild(a),e}createBackLink(){const e=document.createElement("button");return e.className="sv-back-link",e.appendChild(St()),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 Ne({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=mt("sv-sparklink-expired-icon");e.appendChild(_t("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 Re({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 Ot=["identity_trial_exhausted","identity_trial_expired","identity_capacity_blocked"];const zt="stronger_verification_required";function Dt(e){return"identity_locked"===e?"This SparkVault Identity is locked":function(e){return Ot.includes(e)}(e)?"Sign-in unavailable":e===zt?"This request needs your passkey":null}class Ut{constructor(e){this.retryButton=null,this.closeButton=null,this.props=e,this.boundHandleRetry=()=>this.props.onRetry(),this.boundHandleClose=()=>this.props.onClose()}render(){const e=mt();e.className="sv-error-view";const t=mt();t.className="sv-error-icon-container",t.appendChild(_t("sv-error-icon"));const n=mt();n.className="sv-error-content";const i=Dt(this.props.code),s=null!==i,o=document.createElement("h3");o.className="sv-error-title",o.textContent=i??"Something went wrong";const r=document.createElement("p");if(r.className="sv-error-message",r.textContent=this.props.message,n.appendChild(o),n.appendChild(r),!s){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 a=mt();return a.className="sv-error-actions",s||(this.retryButton=document.createElement("button"),this.retryButton.className="sv-btn sv-btn-error-primary",this.retryButton.textContent="Try Again",this.retryButton.addEventListener("click",this.boundHandleRetry),a.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),a.appendChild(this.closeButton),e.appendChild(t),e.appendChild(n),e.appendChild(a),e}destroy(){this.retryButton&&this.retryButton.removeEventListener("click",this.boundHandleRetry),this.closeButton&&this.closeButton.removeEventListener("click",this.boundHandleClose)}}const Ht=Object.freeze({white:"#ffffff",slate50:"#f8fafc",slate100:"#f1f5f9",slate200:"#e2e8f0",slate300:"#cbd5e1",slate500:"#64748b",slate600:"#475569",slate900:"#0f172a",slate950:"#030712",action:"#216bde",actionHover:"#0d5bcd",actionBg:"#eef4fe",btnDanger:"#b02b27",btnDangerHover:"#9a221f",success:"#006d42",success500:"#2ec26b",error:"#b02b27",error500:"#e6443d",errorBg:"#fee2e2",errorText:"#991b1b",warning:"#8a5600",warning500:"#e6ad00",infoBg:"#dbeafe",info500:"#4383eb",modalOverlay:"rgba(15, 23, 42, 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(15, 23, 42, 0.12)"});function Ft(e,t){const n=Number.parseInt(e.slice(1),16);return`rgba(${n>>16}, ${n>>8&255}, ${255&n}, ${t})`}class Vt{constructor(e){this.retryButton=null,this.closeButton=null,this.props=e,this.boundHandleRetry=()=>this.props.onRetry(),this.boundHandleClose=()=>this.props.onClose()}render(){const e=mt("sv-unavailable-view"),t=mt("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",Ht.actionBg),t.setAttribute("stroke",Ht.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",Ht.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",Ht.white),n.appendChild(s);const o=document.createElementNS("http://www.w3.org/2000/svg","rect");return o.setAttribute("x","12.5"),o.setAttribute("y","9"),o.setAttribute("width","2.5"),o.setAttribute("height","8"),o.setAttribute("rx","1"),o.setAttribute("fill",Ht.white),n.appendChild(o),e.appendChild(n),e}()),e.appendChild(t);const n=mt("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 o=mt("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),o.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),o.appendChild(this.closeButton),e.appendChild(o),e}destroy(){this.retryButton&&this.retryButton.removeEventListener("click",this.boundHandleRetry),this.closeButton&&this.closeButton.removeEventListener("click",this.boundHandleClose)}}class jt{constructor(e){this.dismissButton=null,this.props=e,this.boundHandleClose=()=>this.props.onClose()}render(){const e=mt("sv-not-activated-view"),t=mt("sv-not-activated-eyebrow");t.appendChild(function(){const e=mt("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=mt("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",Ht.slate50),n.setAttribute("stroke",Ht.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",Ht.white),i.setAttribute("stroke",Ht.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",Ht.slate600),i.setAttribute("stroke-width","2"),i.setAttribute("stroke-linecap","round"),t.appendChild(i)};s("26","40"),s("32","40"),s("38","35");const o=(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",Ht.action),i.setAttribute("stroke",Ht.white),i.setAttribute("stroke-width","1.5"),t.appendChild(i)};return o("30","26"),o("36","32"),o("28","38"),e.appendChild(t),e}();e.appendChild(s);const o=document.createElement("h2");o.className="sv-not-activated-title",o.id="sv-modal-title",o.textContent="Identity Product not configured",e.appendChild(o);const r=document.createElement("p");r.className="sv-not-activated-message",r.textContent="Sign-in is unavailable because the site owner has not configured SparkVault Identity for this account.",e.appendChild(r);const a=mt("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=mt("sv-not-activated-actions"),u=document.createElement("a");u.className="sv-btn sv-btn-primary sv-not-activated-cta",u.href="https://app.sparkvault.com/products/identity",u.target="_blank",u.rel="noopener noreferrer";const h=document.createElement("span");return h.textContent="Configure in SparkVault",u.appendChild(h),u.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(u),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 qt{constructor(e){this.dismissButton=null,this.props=e,this.boundHandleClose=()=>this.props.onClose()}render(){const e=mt("sv-not-activated-view"),t=mt("sv-not-activated-eyebrow");t.appendChild(function(){const e=mt("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=mt("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",Ht.slate50),n.setAttribute("stroke",Ht.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",Ht.white),i.setAttribute("stroke",Ht.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",Ht.slate300),s.setAttribute("stroke-width","2"),t.appendChild(s);const o=document.createElementNS("http://www.w3.org/2000/svg","path");o.setAttribute("d","M19 32H45"),o.setAttribute("stroke",Ht.slate300),o.setAttribute("stroke-width","2"),o.setAttribute("stroke-linecap","round"),t.appendChild(o);const r=document.createElementNS("http://www.w3.org/2000/svg","path");return r.setAttribute("d","M23 23L41 41"),r.setAttribute("stroke",Ht.action),r.setAttribute("stroke-width","2.5"),r.setAttribute("stroke-linecap","round"),t.appendChild(r),e.appendChild(t),e}();e.appendChild(s);const o=document.createElement("h2");o.className="sv-not-activated-title",o.id="sv-modal-title",o.textContent="This domain isn’t allowed",e.appendChild(o);const r=document.createElement("p");r.className="sv-not-activated-message",r.textContent="Sign-in is blocked because this website’s domain is not on the SparkVault Identity allowlist for this account.",e.appendChild(r);const a=mt("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=mt("sv-not-activated-actions"),u=document.createElement("a");u.className="sv-btn sv-btn-primary sv-not-activated-cta",u.href="https://app.sparkvault.com/company/domains",u.target="_blank",u.rel="noopener noreferrer";const h=document.createElement("span");return h.textContent="Manage domains in SparkVault",u.appendChild(h),u.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(u),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 Wt(){if("undefined"==typeof window)return null;const e=window.__sparkvaultProgress;return e&&"function"==typeof e.start?e:null}function Kt(){Wt()?.start()}function Gt(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 Yt=new Set(Ot),Xt={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){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.container=e,this.api=t,this.options=n,this.callbacks=i,this.verificationState=new nt,this.passkeyHandler=new ot(t,this.verificationState),this.otpHandler=new rt(t,this.verificationState),this.sparkLinkHandler=new at(t,this.verificationState),this.applyInitialIdentity(),n.authContext&&this.verificationState.setAuthContext(n.authContext)}applyInitialIdentity(){const e="string"==typeof this.options.phone&&this.options.phone.length>0,t=e?this.options.phone:this.options.email;t&&(e||"phone"===Qe(t)?this.verificationState.setIdentity(Je(t)??t,"phone"):this.verificationState.setIdentity(gt(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(){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());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.setState(this.viewStateForConfigError(e))}viewStateForConfigError(e){if(e instanceof je){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 je&&"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.discoverableVerifyAbort?.abort(),this.discoverableVerifyAbort=null,null!==this.focusTimeoutId&&(clearTimeout(this.focusTimeoutId),this.focusTimeoutId=null),null!==this.morphTimer&&(clearTimeout(this.morphTimer),this.morphTimer=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(){this.recipient||0===this.getAllowedIdentityTypes().length?await this.showMethodSelect():this.canDiscoverableVerify()?this.launchDiscoverableVerify():this.showIdentityInput()}canDiscoverableVerify(){if(!this.passkeyHandler.canAutoVerify())return!1;return tt(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;const n=t.render();n.classList.add("sv-step-enter"),this.morphSwap(e,n),"loading"===this.viewState.view?Kt():Wt()?.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))}destroyCurrentView(){this.currentView?.destroy&&this.currentView.destroy(),this.currentView=null}morphSwap(e,t){const n=e.getBoundingClientRect().height;ft(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 o=()=>{null!==this.morphTimer&&(clearTimeout(this.morphTimer),this.morphTimer=null),e.removeEventListener("transitionend",r),e.style.height="",e.style.overflow="",e.style.transition="",e.style.boxSizing=""},r=t=>{const n=t.propertyName;t.target===e&&"height"===n&&o()};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",r),null!==this.morphTimer&&clearTimeout(this.morphTimer),this.morphTimer=setTimeout(o,550)}createViewForState(e){switch(e.view){case"loading":return new yt({message:"Loading..."});case"identity-input":return new bt({allowedTypes:this.getAllowedIdentityTypes(),initialValue:this.recipient,error:e.error,onSubmit:e=>this.handleIdentitySubmit(e),onPasskey:this.canDiscoverableVerify()?()=>{this.launchDiscoverableVerify()}:void 0});case"method-select":return new At({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 $t({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 Lt({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 Bt({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 Mt({onUseAnotherMethod:()=>this.cancelDiscoverableVerify()});case"passkey-prompt":return new Pt({identityLabel:e.recipient,onAddPasskey:()=>this.handlePasskeyPromptAdd(e.pendingResult),onSkip:()=>this.handlePasskeyPromptSkip(e.pendingResult),error:e.error});case"backup-verify":return new Rt({missingType:e.missingType,error:e.error,onSubmit:e=>this.handleBackupSubmit(e),onSkip:()=>this.handleBackupSkip()});case"backup-code":return new $t({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 Nt({email:e.email,expiresAt:e.expiresAt,onResend:()=>this.handleSparkLinkResend(),onFallback:()=>this.handleSparkLinkFallback(),onBack:()=>this.showMethodSelect(),onExpired:()=>this.cleanupSparkLink()});case"oauth-pending":return new yt({message:`Connecting to ${e.provider}...`});case"error":return new Ut({message:e.message,code:e.code,onRetry:()=>this.showIdentityInput(),onClose:()=>this.handleClose()});case"service-unavailable":return new Vt({onRetry:()=>this.retryConfigLoad(),onClose:()=>this.handleClose()});case"product-not-configured":return new jt({onClose:()=>this.handleClose()});case"origin-not-allowed":return new qt({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"});let i=tt(n);if(this.recipient){i=i.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&&i.some(e=>"passkey"===e.type)&&await this.passkeyHandler.checkPasskey(),!1===this.verificationState.passkey.hasPasskey&&(i=i.filter(e=>"passkey"!==e.type))}else i=i.filter(e=>"passkey"===e.type||"social"===e.type);this.verificationState.passkey.isFallbackMode&&(i=i.filter(e=>"passkey"!==e.type)),0!==i.length?t&&!0===this.verificationState.passkey.hasPasskey&&!this.verificationState.passkey.isFallbackMode&&i.some(e=>"passkey"===e.type)?this.launchPasskeyVerify(!0):1!==i.length||this.isIdentityFixed()?this.setState({view:"method-select",email:this.recipient,methods:i}):this.handleMethodSelect(i[0]):this.setState(this.noMethodState())}noMethodState(){return this.verificationState.passkeyRequired&&!1===this.verificationState.passkey.hasPasskey?{view:"error",code:zt,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.`)}:{view:"error",message:"No authentication methods available",code:"no_methods"};var e,t}handleIdentitySubmit(e){this.verificationState.setIdentity(e.value,e.type),this.identityPrefilled=!1,this.showMethodSelect()}getAllowedIdentityTypes(){return this.verificationState.getAllowedIdentityTypes()}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;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",...Xt}):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;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;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||!Yt.has(e))&&(this.setState({view:"error",code:e,message:Gt(this.verificationState.sdkConfig?.branding?.companyName)}),!0)}async handleOtpSubmit(e){if("otp-verify"!==this.viewState.view)return;const t=this.verificationState.otp.method??"email";Kt();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("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.";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)||"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=tt(this.verificationState.methodIds);return this.recipient?e.some(e=>"passkey"!==e.type&&("phone"===this.identityType?"phone"===e.identityType:"email"===e.identityType)):e.some(e=>"social"===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,ze(),t,this.verificationState.authContext);window.location.href=n}normalizeError(e){return e instanceof je?new I(e.message,e.code):e instanceof Error?e:new Error(String(e))}isSessionExpiredError(e){const t=e.message.toLowerCase(),n=e instanceof I?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);this.isSessionExpiredError(n)?this.showIdentityInput("Your session has expired. Please try again."):this.setState({view:"error",message:n.message,code:n instanceof I?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:o}=this.viewState;try{await this.api.verifyBackupVerification({sessionId:s,code:e}),this.advancePostLogin()}catch(e){if("backup_conflict"===(e instanceof je?e.code:""))return void this.setState({view:"backup-verify",missingType:t,pendingResult:o,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:o,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 o=t=>{"connect-src"===t.violatedDirective&&t.blockedURI.includes(e)&&(s=!0)};document.addEventListener("securitypolicyviolation",o);const r=()=>{document.removeEventListener("securitypolicyviolation",o)},a=new WebSocket(t);this.sparkLinkWs=a;const l=setTimeout(()=>{i||(i=!0,r(),a.close(),n({error:s?"csp":"connection"}))},1e4);a.onopen=()=>{try{a.send(JSON.stringify({action:"init"}))}catch{i||(i=!0,r(),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,r(),clearTimeout(l),this.setupSparkLinkWsHandler(a),void n({connectionId:t.connectionId})},a.onerror=()=>{i||(i=!0,r(),clearTimeout(l),n({error:s?"csp":"connection"}))},a.onclose=()=>{i||(i=!0,r(),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=Fe(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",...Xt}):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);t.success?(this.sparkLinkKindling=t.kindling??null,this.armSparkLinkRefocusClaim(),this.setState({view:"sparklink-waiting",email:this.recipient,expiresAt:t.expiresAt})):(this.cleanupSparkLink(),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;this.setState({view:"error",message:e.error??"Failed to send code",code:"otp_send_failed"})}}}const Qt="sparkvault-identity-styles";function Zt(e){if(document.getElementById(Qt))return en(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=Qt,t.dataset.svTheme=tn(e.branding),t.textContent=nn(e),document.head.appendChild(t)}function en(e){const t=document.getElementById(Qt);if(!t)return;const n=tn(e);t.dataset.svTheme!==n&&(t.dataset.svTheme=n,t.textContent=nn({branding:e??{companyName:"",logoLight:null,logoDark:null}}))}function tn(e){return e?.themeMode??"light"}function nn(e){const{branding:t,backdropBlur:n}=e,i="dark"===tn(t),s=!1!==n,o=`var(--sv-primary, ${Ht.action})`,r=i?Ht.slate950:Ht.white,a=`color-mix(in srgb, ${o} 80%, white)`,l=o,d=`var(--sv-primary-hover, ${Ht.actionHover})`,c=`color-mix(in srgb, ${o} ${i?"20%":"9%"}, transparent)`,u=i?Ht.error500:Ht.error,h=i?Ft(Ht.error500,.12):Ht.errorBg,p=Ft(Ht.error500,.35),m=Ht.btnDanger,f=Ht.btnDangerHover,v=i?Ht.warning500:Ht.warning,g=r,y=i?Ht.darkCard:Ht.slate50,b=i?Ft(Ht.white,.08):Ht.slate100,w=i?Ft(Ht.white,.04):Ht.white,k=i?Ht.darkHairline:Ht.slate200,x=i?Ft(Ht.white,.18):Ht.slate300,C=o,S=i?Ft(Ht.white,.35):Ht.slate300,E=i?Ht.darkText:Ht.slate900,_=i?Ht.darkTextMuted:Ht.slate600,T=i?Ft(Ht.white,.45):Ht.slate500,A=Ht.white,I=`0 0 0 2px ${r}, 0 0 0 4px ${a}`,$=i?"0 1px 2px rgba(0, 0, 0, 0.4)":Ht.shadowSm,L=(i||Ht.shadowMd,i?`0 8px 24px rgba(0, 0, 0, 0.5), 0 0 0 1px ${Ht.darkHairline}`:Ht.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)":Ht.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: ${L};\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 ${k};\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: ${_};\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: ${_};\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 ${k};\n border-radius: 8px;\n background: ${w};\n color: ${E};\n box-sizing: border-box;\n box-shadow: ${$};\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: ${T};\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: ${u};\n }\n\n .sv-input.sv-input-error:focus,\n .sv-input.sv-email-input-error:focus {\n box-shadow: 0 0 0 3px ${h};\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 rgba(15, 23, 42, 0.2);\n }\n\n /* Primary Button */\n .sv-btn-primary,\n .sv-btn-email-primary {\n background: ${l};\n color: ${A};\n box-shadow: ${$};\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 ${k};\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 ${k};\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: ${A};\n box-shadow: ${$};\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: ${_};\n border: 1px solid ${k};\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: ${T};\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: ${T};\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 ${k};\n border-radius: 8px;\n background: ${w};\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: ${_};\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: ${h};\n border: 1px solid ${p};\n color: ${u};\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 ${k};\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: ${_};\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: ${T};\n letter-spacing: 0.02em;\n }\n\n .sv-footer-link {\n color: ${_};\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: ${_};\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 ${k};\n border-radius: 8px;\n background: ${w};\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: ${T};\n }\n\n .sv-email-input-error {\n border-color: ${u};\n }\n\n .sv-email-input-error:focus {\n box-shadow: 0 0 0 3px ${h};\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: ${_};\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: ${h};\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?Ht.error500:Ht.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: ${u};\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: ${_};\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: ${T};\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: ${_};\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: ${T};\n opacity: 0.6;\n }\n\n .sv-not-activated-eyebrow-label {\n color: ${_};\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 rgba(15, 23, 42, 0.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: ${_};\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 ${k};\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: ${_};\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: ${T};\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: ${T};\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: ${_};\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: ${_};\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: ${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 transition: color var(--sv-dur-fast) var(--sv-ease-standard);\n }\n\n .sv-skip-link:hover {\n color: ${_};\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: ${_};\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 ${k};\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: ${_};\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: ${T};\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 ${k};\n }\n\n .sv-sparklink-fallback .sv-back-link {\n margin-bottom: 0;\n font-size: 12px;\n color: ${T};\n }\n\n .sv-sparklink-fallback .sv-back-link:hover:not(:disabled) {\n color: ${_};\n }\n\n /* SparkLink Expired State */\n .sv-sparklink-expired {\n flex-direction: column;\n gap: 12px;\n background: ${y};\n border: 1px solid ${k};\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: ${_};\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: ${k};\n }\n\n .sv-divider-text {\n padding: 0 12px;\n font-size: 12px;\n color: ${T};\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 ${k};\n }\n\n .sv-inline-header {\n border-bottom: 1px solid ${k};\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 ${k};\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: ${_}; }\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 `}let sn=0,on="";class rn{constructor(e){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.onOverlayClick=t=>{t.target===this.overlay&&e.onDismiss()},this.onKeydown=t=>{"Escape"===t.key&&e.onDismiss()},this.overlay.addEventListener("click",this.onOverlayClick),document.addEventListener("keydown",this.onKeydown),document.body.appendChild(this.overlay),0===sn&&(on=document.body.style.overflow,document.body.style.overflow="hidden"),sn+=1,this.modal.focus({preventScroll:!0})}destroy(){this.open&&(this.open=!1,document.removeEventListener("keydown",this.onKeydown),this.overlay.removeEventListener("click",this.onOverlayClick),this.overlay.remove(),sn-=1,0===sn&&(document.body.style.overflow=on),this.opener?.isConnected&&this.opener.focus({preventScroll:!0}))}}function an(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}function ln(e,t,n){return e?n||t:t||n}const dn="sv-modal-title",cn={companyName:"",logoLight:null,logoDark:null};class un{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=tn(cn),Zt({branding:cn,backdropBlur:e.backdropBlur}),this.shell=new rn({overlayId:"sparkvault-identity-overlay",modalId:"sparkvault-identity-modal",classPrefix:"sv",titleId:dn,backdropBlur:!1!==e.backdropBlur,onDismiss:()=>this.handleClose()}),this.header=this.createHeader(cn),this.body=document.createElement("div"),this.body.className="sv-body",this.shell.modal.append(this.header,this.body,an("sv")))}updateBranding(e){if(!this.shell||!this.header)return;this.effectiveTheme=tn(e),en(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=hn("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=ln("dark"===this.effectiveTheme,e.logoLight,e.logoDark);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=dn,s.textContent=e.companyName,n.appendChild(s)}else{const t=document.createElement("h2");t.className="sv-company-name",t.id=dn,t.textContent=e.companyName,n.appendChild(t)}return t.append(n,hn("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 hn(e,t){const n=document.createElement("button");return n.className=e,n.type="button",n.setAttribute("aria-label","Close"),n.appendChild(function(){const e=wt("0 0 20 20",20,20);return e.appendChild(kt("M15 5L5 15M5 5L15 15",{stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round"})),e}()),n.addEventListener("click",t),n}const pn="http://www.w3.org/2000/svg";function mn(e,t,n){const i=document.createElement(e);return t&&(i.className=t),null!=n&&(i.textContent=n),i}class fn{constructor(e,t,n,i){this.config=e,this.api=t,this.options=n,this.callbacks=i,this.popupLauncher=new it,this.modal=null,this.alertEl=null,this.popupWindow=null,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}openPopup(){const e=++this.generation;this.popupLauncher.openPopup({url:De(this.config,this.options),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()}}).then(t=>{e===this.generation&&this.handleResult(t)}).catch(t=>{e===this.generation&&this.handleError(t)})}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 I(e.message||e.error||"Verification failed",e.errorCode||e.error||"verification_failed"))):this.finishCancel()}}handleError(e){if(!this.settled)if(e instanceof F&&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 H||e instanceof D||e instanceof F)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 un,this.modal.createLoading({backdropBlur:this.options.backdropBlur},()=>this.abort()));const e=this.modal.getBody();if(!e)return;ft(e);const t=mn("div","sv-bridge"),n=mn("div","sv-bridge-alert");n.appendChild(function(){const e=document.createElementNS(pn,"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(pn,"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(pn,"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=mn("div","sv-bridge-alert-body");i.appendChild(mn("span","sv-bridge-alert-text","The sign-in window may not have opened."));const s=mn("button","sv-bridge-retry","Try again");s.type="button",s.addEventListener("click",()=>this.retry()),i.appendChild(s),n.appendChild(i),this.alertEl=n;const o=mn("div","sv-bridge-dots");o.append(mn("span"),mn("span"),mn("span")),t.append(n,o,mn("h3","sv-title","Continue in the secure window"),mn("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.callbacks.onPopupReopened?.(),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 vn{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 gn{constructor(e,t={}){this.shell=null,this.targetElement=e,this.bare=!0===t.bare}createLoading(e,t){this.shell||(Zt({branding:{companyName:"",logoLight:null,logoDark:null},backdropBlur:!1}),this.shell=new vn(this.targetElement,{containerClassName:this.bare?"sv-inline-container sv-inline-bare":"sv-inline-container",bodyClassName:"sv-body sv-inline-body",footer:this.bare?null:an("sv")}))}updateBranding(e){this.shell&&en(e)}setMinimalChrome(e){}getBody(){return this.shell?.body??null}isOpen(){return null!==this.shell}destroy(){this.shell?.destroy(),this.shell=null}}function yn(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")}function bn(e,t){let n=null,i=!1;const s=new Map,o=e=>{s.has(e)||(e.addEventListener("click",t),s.set(e,()=>e.removeEventListener("click",t)))};var r;return r=()=>{i||(document.querySelectorAll(e).forEach(o),n=new MutationObserver(t=>{t.forEach(t=>{t.addedNodes.forEach(t=>{t instanceof Element&&(t.matches(e)&&o(t),t.querySelectorAll(e).forEach(o))})})}),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",r,{once:!0}):r(),()=>{i=!0,n?.disconnect(),s.forEach(e=>e()),s.clear()}}const wn=["home","identity","security","sessions","sites"],kn=["EdDSA","RS256"],xn="sv_signin_pending";function Cn(){let e=null;try{e=sessionStorage.getItem(xn)}catch{return null}if(!e)return null;let t=NaN,n=null;try{const i=JSON.parse(e);if("object"==typeof i&&null!==i){const e=i;"number"==typeof e.at&&(t=e.at),"string"==typeof e.hint&&e.hint&&(n=e.hint)}else"number"==typeof i&&(t=i)}catch{t=Number(e)}return Number.isFinite(t)?{at:t,hint:n}:null}function Sn(e){return null!==e&&Date.now()-e.at<6e5}function En(){return"undefined"!=typeof window&&(!!/[#&](sv_code|sv_error|sso)=/.test(window.location.hash||"")||Sn(Cn()))}function _n(e,t){const n=Ee(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 Tn{constructor(e){this.renderer=null,this.launcher=null,this.config=e,this.api=new Ue(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(!wn.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={}){if(!Tn.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 t=e.nonce??(await this.api.drawAuthorizationValues()).nonce,n={identity:{providers:[{configURL:`${this.config.identityBaseUrl}/${this.config.accountId}/fedcm/config.json`,clientId:this.config.clientId,nonce:t}]},...e.mediation?{mediation:e.mediation}:{}};let i;try{const e=navigator.credentials.get.bind(navigator.credentials);i=await e(n)}catch(e){throw function(e){if("object"!=typeof e||null===e)return null;const{name:t,error:n}=e;return"IdentityCredentialError"!==t?null:new U("string"==typeof n?n:"")}(e)??new D(e instanceof Error?e.message:void 0)}const s=i?.token;if(!s)throw new M("FedCM did not return a token");const o=this.decodeToken(s);return{token:s,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={}){return this.runFlow(e)}async runFlow(e={}){this.launcher&&(this.launcher.close(),this.launcher=null),this.renderer&&this.renderer.close(),this.api.resetSession();const t={...e,backdropBlur:e.backdropBlur??this.config.backdropBlur},n=!!e.target,i="local"===e.renderMode||n;let s,o;const r=new Promise((e,t)=>{s=e,o=t}),a={onSuccess:t=>{e.onSuccess?.(t),s(t)},onError:t=>{e.onError?.(t),o(t)},onCancel:()=>{const t=new D;e.onCancel?.(),o(t)}},l=e=>{this.renderer=new Jt(e,this.api,t,a),this.renderer.start().catch(e=>{this.renderer?.showStartupError(e)})};if(!i){if(await this.preloadedConfigPermanentlyFailed())return l(new un),r;if("redirect"===t.flow){try{await this.startRedirectFlow(t)||a.onError(new M("Sign-in requires browser session storage. Enable site data for this site and try again."))}catch(e){a.onError(e instanceof Error?e:new Error(String(e)))}return r}const e=t.email||t.phone||null;return this.markSignInPending(e),this.launcher=new fn(this.config,this.api,t,{onSuccess:e=>{this.clearSignInPending(),a.onSuccess(e)},onError:e=>{this.clearSignInPending(),a.onError(e)},onCancel:()=>{this.clearSignInPending(),a.onCancel()},onPopupClosedUnresolved:()=>this.clearSignInPending(),onPopupReopened:()=>this.markSignInPending(e),onPopupSevered:()=>this.startRedirectFlow(t)}),this.launcher.start(),r}return l(n?this.createInlineContainer(e.target,"bare"===e.chrome):new un),r}attach(e,t={}){return bn(e,async e=>{e.preventDefault();try{await this.signIn({email:t.email,phone:t.phone,authContext:t.authContext,prompt:t.prompt,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=_n(n,"Invalid token header");if("object"!=typeof s||null===s)throw new M("Invalid token header");const o=s.alg;if("string"!=typeof o||!kn.includes(o))throw new M("Unsupported token algorithm");const r=_n(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}(r))throw new M("Invalid token payload structure");const a=Math.floor(Date.now()/1e3);if(r.exp<a)throw new M("Token has expired");const l=`${this.config.identityBaseUrl}/${this.config.accountId}`;if(r.iss!==l)throw new M("Invalid token issuer");if(r.aud!==this.config.accountId)throw new M("Invalid token audience");return r}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.fresh&&await this.startRecoveryBounce(n.hint),null}async consumeHandoffFragment(e,t){const n=e.get("sv_code"),i=e.get("sv_error");this.clearSignInPending();let s=null,o=null;try{s=sessionStorage.getItem("sv_oauth_state"),o=sessionStorage.getItem("sv_pkce_verifier"),this.clearOneShotAuthState()}catch{}this.clearUrlFragment();try{if(i){if("cancelled"===i)return t.onCancel?.(),null;throw new I("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(!o)throw new M("Sign-in session was lost — please sign in again.");const r=await this.api.redeemHandoffCode(n,o),a={token:r.token,identity:r.identity,identityType:r.identity_type,svid:r.svid??void 0,sessionId:r.session_id??void 0,refreshToken:r.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=new URL(`${this.config.identityBaseUrl}/${this.config.accountId}/sso`);e&&t.searchParams.set("login_hint",e);const n=await this.prepareHandoffNavigation(t.toString());n&&window.location.assign(n)}async startRedirectFlow(e){const t=e.authContext;if(t?.authRequestId||t?.simpleMode?.sessionId)return window.location.assign(De(this.config,e)),!0;const n=await this.prepareHandoffNavigation(De(this.config,e),t=>De(this.config,e,t));return!!n&&(window.location.assign(n),!0)}async prepareHandoffNavigation(e,t){const{state:n,codeVerifier:i}=await this.api.drawAuthorizationValues();let s;try{s=await async function(e){const t=await crypto.subtle.digest("SHA-256",(new TextEncoder).encode(e));return Se(new Uint8Array(t))}(i)}catch{return null}try{sessionStorage.setItem("sv_oauth_state",n),sessionStorage.setItem("sv_pkce_verifier",i)}catch{return null}const o=ze();if(t)return t({redirectUri:o,state:n,codeChallenge:s});const r=new URL(e);return r.searchParams.set("redirect_uri",o),r.searchParams.set("state",n),r.searchParams.set("code_challenge",s),r.toString()}markSignInPending(e){try{sessionStorage.setItem(xn,JSON.stringify({at:Date.now(),hint:e}))}catch{}}clearSignInPending(){try{sessionStorage.removeItem(xn)}catch{}}consumeSignInPending(){const e=Cn(),t=Sn(e);return this.clearSignInPending(),{fresh:t,hint:t?e.hint: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("token");if(!t)return null;try{let n=null;try{n=sessionStorage.getItem("sv_oauth_state")}catch{}if(!n||e.get("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{}}}close(){this.launcher&&(this.launcher.close(),this.launcher=null),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 je&&("ORIGIN_NOT_ALLOWED"===e.code||"product_not_configured"===e.code)}}createInlineContainer(e,t=!1){return new gn(yn(e),{bare:t})}async render(e){const t=await this.consumeRedirectResult();return t?(e.onSuccess?.(t),t):this.runFlow(e)}}const An=/^[A-Za-z0-9_.:-]+$/,In=Object.freeze(["seen","read","archived"]),$n=Object.freeze(["seen","read"]),Ln=Object.freeze({alert:Object.freeze({category:"alert",delivery:"plaintext",policy:Object.freeze({verification_level:"none",interaction:"view"})}),secureMessage:Object.freeze({category:"secure",channels:Object.freeze(["email"]),policy:Object.freeze({verification_level:"identifier",interaction:"view"})}),conversation:Object.freeze({category:"conversation",channels:Object.freeze(["in_app","email"]),policy:Object.freeze({verification_level:"identifier",interaction:"reply"})}),approval:Object.freeze({category:"approval",channels:Object.freeze(["in_app","email"]),policy:Object.freeze({verification_level:"identifier",interaction:"approve"})}),signatureRequest:Object.freeze({category:"signature",channels:Object.freeze(["in_app","email"]),policy:Object.freeze({verification_level:"identifier",interaction:"sign"})})});Object.freeze([...new Set(Object.values(Ln).map(e=>e.category))]);const Bn=In,Mn=$n,Pn=Object.freeze(Object.fromEntries(Object.keys(Ln).map(e=>{const{category:t,delivery:n,channels:i,policy:s}=Ln[e],o={category:t,...n?{delivery:n}:{},...i?{channels:i}:{},policy:Object.freeze({verificationLevel:s.verification_level,interaction:s.interaction})};return[e,Object.freeze(o)]})));function Rn(e,t){const n=Pn[e];if(!n)throw new M(`Unknown notify preset "${e}" (valid: ${Object.keys(Pn).join(", ")})`,{field:"preset",received:e});return function(e,t){const n={...t,category:t.category||e.category,delivery:t.delivery??e.delivery,policy:{...e.policy}};for(const[e,i]of Object.entries(t.policy??{}))null!=i&&(n.policy[e]=i);const i=t.channels||e.channels;return i&&(n.channels=[...i]),n}(n,t)}class Nn{constructor(e){this.http=e}async send(e){if(void 0!==e?.sendId&&!("string"==typeof(t=e.sendId)&&t.length>0&&t.length<=128&&An.test(t)))throw new M("sendId must be 1-128 characters of letters, digits, and _ . : -",{field:"sendId",received:e.sendId});var t;if(!Array.isArray(e?.recipients)||0===e.recipients.length)throw new M("recipients is required and must be non-empty",{field:"recipients"});if(Boolean(e.content)===Boolean(e.ingot))throw new M("Provide exactly one content source: content OR ingot");if(e.ingot&&(!e.ingot.vault?.id||!e.ingot.vault.vatToken))throw new M("An ingot send requires its vault unsealed with sv.vaults.unseal (ingot.vault): only a key holder may send a vault file",{field:"ingot.vault"});return(await this.http.post(Be`/v1/products/notify/send`,function(e){return{send_id:e.sendId,recipients:e.recipients,content:e.content?{payload:e.content.payload,content_type:e.content.contentType,filename:e.content.filename,ttl_minutes:e.content.ttlMinutes}:void 0,ingot:e.ingot?{ingot_id:e.ingot.ingotId,vault_id:e.ingot.vault.id}:void 0,delivery:e.delivery,policy:e.policy?{verification_level:e.policy.verificationLevel,interaction:e.policy.interaction,reveal_freshness_minutes:e.policy.revealFreshnessMinutes,action_hash:e.policy.actionHash}:void 0,channels:e.channels,escalation:e.escalation,title:e.title,category:e.category,type:e.type,instructions:e.instructions,history_ttl_days:e.historyTtlDays}}(e),{vat:e.ingot?.vault.vatToken})).data}async sendAlert(e){return this.send(Rn("alert",e))}async sendSecureMessage(e){return this.send(Rn("secureMessage",e))}async sendConversation(e){return this.send(Rn("conversation",e))}async sendApproval(e){return this.send(Rn("approval",e))}async sendSignatureRequest(e){return this.send(Rn("signatureRequest",e))}async getInbox(e){On(e?.recipientId);return(await this.http.get(Be`/v1/products/notify/inbox`,{query:{recipient_id:e.recipientId,state:e.state,limit:e.limit,cursor:e.cursor}})).data}async markInboxState(e,t){const n=Me(e,"notificationId");if(On(t?.recipientId),!Number.isInteger(t?.createdAt))throw new M("createdAt (the row's created_at) is required",{field:"createdAt",received:t?.createdAt});if(!Bn.includes(t.state))throw new M(`state must be one of ${Bn.join(", ")}`,{field:"state",received:t.state});return(await this.http.post(Be`/v1/products/notify/inbox/${n}/state`,{recipient_id:t.recipientId,created_at:t.createdAt,state:t.state})).data}async markInboxAll(e){if(On(e?.recipientId),!Mn.includes(e.state))throw new M(`state must be one of ${Mn.join(", ")} (archive per-row instead)`,{field:"state",received:e.state});return(await this.http.post(Be`/v1/products/notify/inbox/state`,{recipient_id:e.recipientId,state:e.state,cursor:e.cursor})).data}async listSends(e={}){return(await this.http.get(Be`/v1/products/notify/sends`,{query:{limit:e.limit,cursor:e.cursor}})).data}async recallSend(e,t={}){if(zn(e),void 0!==t.recipientIds&&(!Array.isArray(t.recipientIds)||0===t.recipientIds.length))throw new M("recipientIds must be a non-empty array; omit it entirely to recall the whole audience",{field:"recipientIds",received:t.recipientIds});if(void 0!==t.mode&&"grant"!==t.mode&&"content"!==t.mode)throw new M("mode must be 'grant' or 'content'",{field:"mode",received:t.mode});return(await this.http.post(Be`/v1/products/notify/sends/${e}/recall`,{recipient_ids:t.recipientIds,mode:t.mode})).data}async getSendStatus(e){zn(e);return(await this.http.get(Be`/v1/products/notify/sends/${e}/status`)).data}async listReceipts(e={}){return(await this.http.get(Be`/v1/products/notify/receipts`,{query:{limit:e.limit,cursor:e.cursor,interaction:e.interaction}})).data}async getSendReceipts(e,t={}){zn(e);return(await this.http.get(Be`/v1/products/notify/sends/${e}/receipts`,{query:{cursor:t.cursor}})).data}async getConfig(){return(await this.http.get(Be`/v1/products/notify/config`)).data}async updateConfig(e){if(!e||"object"!=typeof e||Array.isArray(e))throw new M("config patch must be an object");return(await this.http.put(Be`/v1/products/notify/config`,e)).data}async getEmailSender(){return(await this.http.get(Be`/v1/products/notify/email-sender`)).data}}function On(e){if(!e||"string"!=typeof e)throw new M("recipientId is required",{field:"recipientId"})}function zn(e){if(!e||"string"!=typeof e)throw new M("sendId is required",{field:"sendId"})}class Dn{constructor(e,t=new ve(e)){this.identity=new Tn(e),this.notify=new Nn(t)}}const Un=Object.freeze({min:12,max:32});new RegExp(`^[A-Za-z0-9]{${Un.min},${Un.max}}$`);const Hn=Object.freeze({INVALID:"invalid_url",NOT_HTTPS:"not_https",UNSAFE_PARTS:"unsafe_parts",HOST:"host_not_allowed",OPERATION:"wrong_operation",ISTK:"bad_istk"}),Fn=/^[A-Za-z0-9_-]+$/,Vn=/^[A-Za-z0-9_-]+$/,jn=/^[\x21-\x7e]+$/,qn=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)([^?#]*)(?:\?([^#]*))?(#.*)?$/,Wn=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*$/;function Kn(e){return"forge.sparkvault.com"===e}function Gn(e,{operation:t,isAllowedHost:n=Kn}){const i=Xn(e);if(!i.ok)return i;if(!n(i.hostname))return Qn(Hn.HOST);if(i.path!==`/${t}`)return Qn(Hn.OPERATION);const s=function(e,t){const n=[];for(const i of(e??"").split("&")){if(!i)continue;const e=i.indexOf("=");Jn(-1===e?i:i.slice(0,e))===t&&n.push(-1===e?"":Jn(i.slice(e+1)))}return n}(i.query,"istk");if(1!==s.length||!Fn.test(s[0]))return Qn(Hn.ISTK);const o=`https://${i.hostname}`;return{ok:!0,origin:o,endpoint:`${o}/${t}`,istk:s[0]}}function Yn(e,t){const n=Xn(t);if(!n.ok||void 0!==n.query||"string"!=typeof e||!jn.test(e))return null;const i=`https://${n.hostname}`;let s=null;if(e.startsWith(`${i}/`)?s=e.slice(i.length):e.startsWith("/")&&!e.startsWith("//")&&(s=e),null===s||!s.startsWith(`${n.path}/`))return null;const o=s.slice(n.path.length+1);return Vn.test(o)?`${i}${n.path}/${o}`:null}function Xn(e){if("string"!=typeof e||!jn.test(e))return Qn(Hn.INVALID);const t=qn.exec(e);if(!t)return Qn(Hn.INVALID);const[,n,i,s,o,r]=t;if("https"!==n.toLowerCase())return Qn(Hn.NOT_HTTPS);if(i.includes("@")||/:[0-9]*$/.test(i)||void 0!==r)return Qn(Hn.UNSAFE_PARTS);const a=i.toLowerCase();return Wn.test(a)?{ok:!0,hostname:a,path:s,query:o}:Qn(Hn.HOST)}function Jn(e){const t=e.replace(/\+/g," ");try{return decodeURIComponent(t)}catch{return t}}function Qn(e){return{ok:!1,reason:e}}class Zn extends I{constructor(e,t,n,i,s){super(e,t,n,i,s?.retryAfterMs??null),this.name="UploadApiError",this.verdict=s?.verdict??a.REFUSED,this.serverOffset=s?.offset??null,Object.setPrototypeOf(this,Zn.prototype)}}const ei="1.0.0";function ti(e){if(null===e||!/^\d+$/.test(e.trim()))return null;const t=Number(e);return Number.isSafeInteger(t)&&t>0?t:null}function ni(e){if(null===e||!/^\d+$/.test(e.trim()))return null;const t=Number(e);return Number.isSafeInteger(t)?t:null}const ii=new Map([[n.UPLOAD_POOL_FULL,"This upload could not be saved: the owner's storage cannot take the file."],[n.UPLOAD_SUPERSEDED,"This upload was not saved: a newer upload of this file replaced it."],[o,"This vault is scheduled for deletion. Cancel its deletion in vault settings before accessing its contents."]]);function si(e,t,n,i){return new Zn(t??ii.get(e)??"This upload could not be saved: the server refused it.","upload_refused",n,{status:n,coreCode:e},i)}function oi(e,t,n,s){return i.includes(e)?si(e,t,n,{verdict:a.REFUSED,retryAfterMs:s,offset:null,coreCode:e}):null}function ri(e){return!(e instanceof I)||e instanceof Zn||void 0===e.statusCode?e:oi(e.code,e.message,e.statusCode,e.retryAfterMs)??e}function ai(){return new Zn("Upload cancelled","cancelled",0)}function li(){if("undefined"==typeof XMLHttpRequest)throw new Zn("XMLHttpRequest is required for browser uploads","environment_unsupported",0)}function di(){return"undefined"!=typeof navigator&&!1===navigator.onLine}const ci=new WeakSet,ui=new Set(["session_gone","upload_refused","cancelled"]);function hi(e){return e instanceof Zn&&!ui.has(e.code)&&e.verdict!==a.RESYNC&&ci.add(e),e}function pi(e){return e instanceof Zn&&ci.has(e)}function mi(e){if(e instanceof Zn)return e;throw e}function fi(e){return new Zn("Upload could not be finished: the server has ended this upload session. Please upload the file again.","session_gone",e.statusCode??0,{status:e.statusCode,...e.details},{verdict:a.GONE,retryAfterMs:null,offset:null,coreCode:null})}async function vi(e,t,n,i){const{verdict:s,retryAfterMs:o}=t;if(s===a.DEFERRED){if(!e.deferred(o))throw t}else{if(s!==a.RETRY)throw t;if(di())return await(r=i,new Promise((e,t)=>{if(r.aborted)return void t(ai());const n=e=>{globalThis.removeEventListener("online",i),r.removeEventListener("abort",s),e()},i=()=>n(e),s=()=>n(()=>t(ai()));globalThis.addEventListener("online",i),r.addEventListener("abort",s,{once:!0}),di()||n(e)})),void e.alive();if(!e.failed(s,o))throw t}var r;const l=E({attempt:e.attempt,retryAfterMs:o,jitterKey:n});await function(e,t){return new Promise((n,i)=>{if(t.aborted)return void i(ai());const s=()=>{clearTimeout(o),i(ai())},o=setTimeout(()=>{t.removeEventListener("abort",s),n()},e);t.addEventListener("abort",s,{once:!0})})}(l,i)}function gi(e,t){const n=e.body?W(e):null,i=u({status:e.status,headers:e.header,details:n?.details??null,receipt:t.receipt});if(i.verdict===a.OK)return{outcome:i,failure:null};const{status:s}=e;if(i.verdict===a.REFUSED&&null!==i.coreCode)return{outcome:i,failure:si(i.coreCode,n?.message??null,s,i)};if(i.verdict===a.DEFERRED)return{outcome:i,failure:new Zn("The server received every byte of this file and is still saving it. It finishes on its own.",r,s,{status:s},i)};const o=e.body.replace(/\s+/g," ").trim().slice(0,200);return{outcome:i,failure:new Zn(t.failureMessage,t.code,s,{status:s,...o?{serverDetail:o}:{},...null!==i.coreCode?{coreCode:i.coreCode}:{}},i)}}const yi={name:"Upload session creation",code:"tus_create_failed",failureMessage:"The upload could not be started: the server did not open an upload session.",networkMessage:"Unable to start the upload. Please check your connection and try again.",receipt:!1},bi={name:"Upload resume check",code:"resume_check_failed",failureMessage:"Upload could not be resumed: the server no longer recognizes this upload session.",networkMessage:"Unable to resume upload. Please check your connection and try again.",receipt:!1,timeoutMs:6e4},wi={name:"Upload finalization check",code:"finalization_check_failed",failureMessage:"Upload could not be confirmed: the server did not finalize the file.",networkMessage:"Unable to confirm upload. Please check your connection and try again.",receipt:!0,timeoutMs:6e4};class ki extends pe{constructor(e){super(e.timeout),this.vaultInfoMemo=new Map,this.config=e}makeError(e,t,n,i,s=null){const o=n>0?oi(t,e,n,s):null;if(o)return o;return new Zn(e,t,n,i,0===n&&"cancelled"!==t?u({status:0}):{verdict:a.REFUSED,retryAfterMs:s,offset:null,coreCode:null})}async request(e,t){const{data:n,status:i}=await this.rawRequest(`${this.config.apiBaseUrl}${e}`,t),s="object"==typeof n&&null!==n?n:null;return{data:s&&"data"in s?s.data:n,status:i,requestId:s?.meta?.request_id}}requireVaultId(e){if(!Z(e))throw new Zn("Invalid vault ID","invalid_vault_id",0,{field:"vaultId",received:e});return e}async getVaultUploadInfo(e){const t=this.vaultInfoMemo.get(e);if(t&&!t.pendingSignal?.aborted)return t.promise;const n={pendingSignal:this.getAbortSignal(),promise:this.fetchVaultUploadInfo(e)};this.vaultInfoMemo.set(e,n);try{const e=await n.promise;return n.pendingSignal=null,e}catch(t){throw this.vaultInfoMemo.get(e)===n&&this.vaultInfoMemo.delete(e),t}}async fetchVaultUploadInfo(e){const t=await this.request(Be`/v1/files/in/${this.requireVaultId(e)}`,{method:"GET"});if(!function(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.vault_id&&"string"==typeof t.vault_name&&"number"==typeof t.max_size_bytes&&"object"==typeof t.branding&&null!==t.branding&&"string"==typeof t.branding.organization_name&&"object"==typeof t.encryption&&null!==t.encryption&&"string"==typeof t.encryption.algorithm&&("active"===t.forge_status||"inactive"===t.forge_status)}(t.data))throw new Zn("Invalid vault upload info response from server","invalid_response",t.status);return{vaultId:(n=t.data).vault_id,vaultName:n.vault_name,maxSizeBytes:n.max_size_bytes,branding:{organizationName:n.branding.organization_name,logoLightUrl:n.branding.logo_light_url,logoDarkUrl:n.branding.logo_dark_url},encryption:{algorithm:n.encryption.algorithm,keyDerivation:n.encryption.key_derivation,postQuantum:n.encryption.post_quantum},forgeStatus:n.forge_status};var n}async initiateUpload(e,t,n,i,s,o){const r=Be`/v1/files/in/${this.requireVaultId(e)}/upload`,a={filename:t,size_bytes:n,content_type:i};o&&(a.folder_path=o);const l=await this.request(r,{method:"POST",body:JSON.stringify(a),headers:s?{"X-Vault-Access-Token":s}:void 0});if(!function(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.forge_url&&"string"==typeof t.ingot_id}(l.data))throw new Zn("Invalid initiate upload response from server","invalid_response",l.status);return{forgeUrl:l.data.forge_url,ingotId:l.data.ingot_id,requestId:"string"==typeof l.requestId&&l.requestId.length>0?l.requestId:null}}async uploadFileToForge(e,t,n,i){li();const s=Gn(t,{operation:"encrypt",isAllowedHost:e=>ce(this.config,e)});if(!s.ok)throw new Zn("Forge upload URL was refused","invalid_forge_url",0,{reason:s.reason});const o=this.getAbortSignal(),r=T(),a=await this.createTusSession(s.endpoint,s.istk,e.size,r,o),l=Yn(a.location,s.endpoint);if(!l)throw new Zn("Upload session is outside the upload endpoint","tus_create_failed",0);i?.(l),await this.sendFile(e,{uploadUrl:l,totalSize:e.size,chunkSize:a.chunkSize,budget:r,sessionSignal:o},0,n)}async resumeUploadToForge(e,t,n){li();const i=function(e,{operation:t,isAllowedHost:n=Kn}){const i=Xn(e);if(!i.ok)return i;if(!n(i.hostname))return Qn(Hn.HOST);const s=Yn(e,`https://${i.hostname}/${t}`);return null===s?Qn(Hn.OPERATION):{ok:!0,url:s}}(t,{operation:"encrypt",isAllowedHost:e=>ce(this.config,e)});if(!i.ok)throw new Zn("Forge upload session URL was refused","invalid_forge_url",0,{reason:i.reason});const s=this.getAbortSignal(),o=T(),r=await this.readSessionStanding(i.url,o,s);if(r.length!==e.size)throw new Zn("The upload session is for a file of another length","session_mismatch",0,{sessionLength:r.length,fileSize:e.size});const a={uploadUrl:i.url,totalSize:e.size,chunkSize:r.chunkSize,budget:o,sessionSignal:s};await this.sendFile(e,a,this.checkResumeOffset(r.offset,a),n)}async sendFile(e,t,n,i){let s=0;const o=i?(e,t)=>{e>s&&(s=e,i(e,t))}:void 0;for(o?.(n,e.size);;){if(t.sessionSignal.aborted)throw ai();if(n===e.size){const e=await this.confirmServerFinalized(t).catch(e=>{throw hi(e)});if(e.published)return;n=e.resumeAt;continue}const i=Math.min(n+t.chunkSize,e.size);try{n=await this.patchChunk(t,e.slice(n,i),n,o),t.budget.progressed()}catch(e){n=await this.offsetAfterFailure(t,e,n)}}}async offsetAfterFailure(e,t,n){let i=mi(t);for(;;){if(i.verdict===a.RESYNC)return this.resyncedOffset(e,i,n);await this.backOff(e,i);try{const t=await this.readResumeOffset(e);return t>n&&e.budget.progressed(),t}catch(e){i=mi(e)}}}resyncedOffset(e,t,n){const i=this.checkResumeOffset(t.serverOffset,e);if(i>n)e.budget.progressed();else if(!e.budget.failed(a.RESYNC))throw t;return i}async backOff(e,t){if(t.verdict===a.GONE)throw fi(t);await vi(e.budget,t,e.uploadUrl,e.sessionSignal)}async confirmServerFinalized(e){let t=0;for(;;)try{return await this.tusRequest(e.uploadUrl,{method:"PATCH",headers:{"Tus-Resumable":ei,"Upload-Offset":String(e.totalSize),"Content-Type":"application/offset+octet-stream"}},wi),{published:!0}}catch(n){const i=mi(n);if(t="timeout"===i.code?t+1:0,t>=2)throw i;if(i.verdict===a.RESYNC){const t=this.resyncedOffset(e,i,e.totalSize);if(t<e.totalSize)return{published:!1,resumeAt:t};continue}await this.backOff(e,i)}}async readSessionStanding(e,t,n){for(;;)try{const{response:n,outcome:i}=await this.tusRequest(e,{method:"HEAD",headers:{"Tus-Resumable":ei}},bi),s=n.headers.get("X-Chunk-Size"),o=ti(s);if(null===o)throw new Zn("Server did not return a valid X-Chunk-Size",bi.code,n.status,{header:"X-Chunk-Size",received:s});return t.progressed(),{offset:i.offset,length:ni(n.headers.get("Upload-Length")),chunkSize:o}}catch(i){const s=mi(i);if(s.verdict===a.GONE)throw fi(s);await vi(t,s,e,n)}}async readResumeOffset(e){return this.checkResumeOffset(await this.headUploadOffset(e.uploadUrl,bi),e)}checkResumeOffset(e,t){const n=function(e,{totalSize:t,chunkSize:n}){if(!Number.isSafeInteger(t)||t<0||!Number.isSafeInteger(n)||n<1)throw new TypeError("An upload's geometry is a whole length and a positive chunk size");return!Number.isSafeInteger(e)||e<0?A.INVALID:e>t?A.BEYOND_TOTAL:e!==t&&e%n!==0?A.MISALIGNED:null}(e,t);if(null===e||null!==n){const t=n===A.MISALIGNED?"misaligned":"invalid";throw new Zn(`Server returned ${t} upload offset (${e})`,"invalid_offset",0)}return e}async createTusSession(e,t,n,i,s){const o=S(e);let r;for(;;)try{({response:r}=await this.tusRequest(e,{method:"POST",headers:{"Tus-Resumable":ei,"Upload-Length":String(n),"X-ISTK":t}},yi));break}catch(e){const t=mi(e);if(t.verdict!==a.RETRY)throw t;await vi(i,t,o,s)}const l=r.headers.get("Location");if(!l)throw new Zn("Server did not return upload location","tus_create_failed",r.status);const d=r.headers.get("X-Chunk-Size"),c=ti(d);if(null===c)throw new Zn("Server did not return a valid X-Chunk-Size","tus_create_failed",r.status,{header:"X-Chunk-Size",received:d});return i.progressed(),{location:l,chunkSize:c}}patchChunk(e,t,n,i){const{uploadUrl:s,totalSize:o,budget:r}=e;return new Promise((a,l)=>{const d=e.sessionSignal;if(d.aborted)return void l(ai());const c=new XMLHttpRequest;let h=!1,p=!1,m=null;const f=()=>c.abort(),v=e=>{h||(h=!0,null!==m&&clearTimeout(m),d.removeEventListener("abort",f),e())},g=()=>{h||(null!==m&&clearTimeout(m),m=setTimeout(()=>{p=!0,c.abort()},6e4))};d.addEventListener("abort",f),c.upload.onprogress=e=>{g(),r.alive(),e.lengthComputable&&i?.(n+e.loaded,o)},c.onload=()=>{const{status:e}=c,{outcome:t,failure:i}=gi({status:e,header:e=>c.getResponseHeader(e),body:e>=200&&e<300?"":c.responseText},{receipt:!1,code:"chunk_upload_failed",failureMessage:`Chunk upload failed with status ${e}`});if(i)return void v(()=>l(i));const s=t.offset;v(null===s||s<=n||s>o?()=>l(new Zn(`Server returned invalid upload offset (${c.getResponseHeader("Upload-Offset")})`,"invalid_offset",c.status)):()=>a(s))},c.onerror=()=>v(()=>l(new Zn("Chunk upload failed","network_error",0,void 0,u({status:0})))),c.onabort=()=>v(()=>l(p?new Zn("Chunk upload timed out after 60000ms of inactivity","timeout",0,void 0,u({status:0})):ai())),c.open("PATCH",s),c.setRequestHeader("Tus-Resumable",ei),c.setRequestHeader("Upload-Offset",String(n)),c.setRequestHeader("Content-Type","application/offset+octet-stream"),g(),c.send(t)})}async headUploadOffset(e,t){const{response:n,outcome:i}=await this.tusRequest(e,{method:"HEAD",headers:{"Tus-Resumable":ei}},t);if(null===i.offset)throw new Zn(`${t.name} returned an invalid offset`,t.code,n.status);return i.offset}tusRequest(e,t,n){const i=n.timeoutMs??this.timeoutMs;return this.send(e,{method:t.method,headers:t.headers},{cancelled:"Upload cancelled",timeout:`${n.name} timed out after ${i}ms`,network:n.networkMessage},async e=>{const{outcome:t,failure:i}=gi({status:e.status,header:t=>e.headers.get(t),body:e.ok?"":await e.text().catch(()=>"")},n);if(i)throw i;return{response:e,outcome:t}},i)}}const xi="sparkvault-upload-styles";function Ci(){if(document.getElementById(xi))return;const e=document.createElement("style");e.id=xi,e.textContent=function(){const e={primary:Ht.action,primaryHover:Ht.actionHover,primaryLight:Ht.actionBg,error:Ht.error,errorLight:Ht.errorBg,errorBorder:Ft(Ht.error500,.35),errorText:Ht.errorText,success:Ht.success,successOnDark:Ht.success500,bg:Ht.white,bgSubtle:Ht.slate50,bgHover:Ht.slate100,bgDark:Ht.slate950,bgDarkSubtle:Ht.darkCard,overlay:Ht.modalOverlay,border:Ht.slate200,borderHover:Ht.slate300,borderDark:Ht.darkHairline,textPrimary:Ht.slate900,textSecondary:Ht.slate600,textMuted:Ht.slate500,textOnPrimary:Ht.white,textOnDark:Ht.darkText,textMutedOnDark:Ht.darkTextMuted,shadowSm:Ht.shadowSm,shadowLg:Ht.shadowPopover};return`\n /* ========================================\n OVERLAY & MODAL CONTAINER\n ======================================== */\n\n .svu-overlay {\n /* Force full-screen overlay regardless of page styles */\n position: fixed !important;\n top: 0 !important;\n left: 0 !important;\n right: 0 !important;\n bottom: 0 !important;\n width: 100vw !important;\n height: 100vh !important;\n max-width: none !important;\n max-height: none !important;\n margin: 0 !important;\n background: ${e.overlay};\n display: flex !important;\n align-items: center;\n justify-content: center;\n z-index: 999999 !important;\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 /* Break out of any containing block that could affect fixed positioning */\n transform: none !important;\n filter: none !important;\n contain: none !important;\n isolation: isolate;\n }\n\n .svu-overlay.svu-blur {\n backdrop-filter: blur(8px);\n -webkit-backdrop-filter: blur(8px);\n }\n\n .svu-modal {\n background: ${e.bg};\n border-radius: 16px;\n box-shadow: ${e.shadowLg};\n width: 100%;\n max-width: 480px;\n max-height: calc(100vh - 32px);\n display: flex;\n flex-direction: column;\n color: ${e.textPrimary};\n overflow: hidden;\n }\n\n .svu-modal.svu-with-sidebar {\n max-width: 900px;\n flex-direction: row;\n }\n\n .svu-modal-main {\n flex: 1;\n display: flex;\n flex-direction: column;\n min-width: 0;\n }\n\n /* Dark card variant for uploading/ceremony states */\n .svu-modal.svu-dark {\n background: ${e.bgDark};\n color: ${e.textOnDark};\n }\n\n /* ========================================\n HEADER\n ======================================== */\n\n .svu-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 14px 20px;\n border-bottom: 1px solid ${e.border};\n background: ${e.bg};\n flex-shrink: 0;\n }\n\n .svu-dark .svu-header {\n border-bottom-color: ${e.borderDark};\n background: ${e.bgDark};\n }\n\n .svu-header-title {\n display: flex;\n align-items: center;\n gap: 12px;\n min-width: 0;\n }\n\n .svu-logo {\n height: 28px;\n width: auto;\n max-width: 140px;\n object-fit: contain;\n flex-shrink: 0;\n }\n\n .svu-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 .svu-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: transparent;\n border: none;\n border-radius: 8px;\n cursor: pointer;\n color: ${e.textMuted};\n transition: background 0.15s ease, color 0.15s ease;\n }\n\n .svu-close-btn:hover {\n background: ${e.bgHover};\n color: ${e.textPrimary};\n }\n\n .svu-dark .svu-close-btn {\n color: ${e.textMutedOnDark};\n }\n\n .svu-dark .svu-close-btn:hover {\n background: ${e.bgDarkSubtle};\n color: ${e.textOnDark};\n }\n\n /* ========================================\n BODY\n ======================================== */\n\n .svu-body {\n padding: 24px 28px;\n overflow-y: auto;\n flex: 1;\n }\n\n /* ========================================\n FOOTER\n ======================================== */\n\n .svu-footer {\n padding: 10px 20px;\n border-top: 1px solid ${e.border};\n text-align: center;\n background: ${e.bgSubtle};\n flex-shrink: 0;\n }\n\n .svu-dark .svu-footer {\n border-top-color: ${e.borderDark};\n background: ${e.bgDarkSubtle};\n }\n\n .svu-footer-text {\n font-size: 10px;\n color: ${e.textMuted};\n letter-spacing: 0.02em;\n }\n\n .svu-dark .svu-footer-text {\n color: ${e.textMutedOnDark};\n }\n\n .svu-footer-link {\n color: ${e.textSecondary};\n text-decoration: none;\n font-weight: 500;\n transition: color 0.15s ease;\n }\n\n .svu-footer-link:hover {\n color: ${e.primary};\n }\n\n /* ========================================\n LOADING STATE\n ======================================== */\n\n .svu-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 .svu-spinner {\n width: 28px;\n height: 28px;\n border: 2.5px solid ${e.border};\n border-top-color: ${e.primary};\n border-radius: 50%;\n animation: svu-spin 0.7s linear infinite;\n }\n\n .svu-loading-text {\n font-size: 14px;\n color: ${e.textSecondary};\n margin: 0;\n }\n\n @keyframes svu-spin {\n to { transform: rotate(360deg); }\n }\n\n /* ========================================\n FORM VIEW\n ======================================== */\n\n .svu-form-view {\n display: flex;\n flex-direction: column;\n align-items: center;\n }\n\n .svu-title {\n font-size: 18px;\n font-weight: 600;\n letter-spacing: -0.02em;\n line-height: 1.3;\n margin: 0 0 6px 0;\n text-align: center;\n color: ${e.textPrimary};\n }\n\n .svu-dark .svu-title {\n color: ${e.textOnDark};\n }\n\n .svu-subtitle {\n font-size: 14px;\n font-weight: 400;\n line-height: 1.5;\n color: ${e.textSecondary};\n margin: 0 0 20px 0;\n text-align: center;\n }\n\n .svu-subtitle strong {\n color: ${e.textPrimary};\n font-weight: 500;\n }\n\n /* Drop Zone */\n .svu-drop-zone {\n width: 100%;\n border: 2px dashed ${e.border};\n border-radius: 12px;\n padding: 32px 24px;\n text-align: center;\n cursor: pointer;\n transition: border-color 0.15s ease, background 0.15s ease;\n margin-bottom: 16px;\n }\n\n .svu-drop-zone:hover {\n border-color: ${e.borderHover};\n background: ${e.bgSubtle};\n }\n\n .svu-drop-zone.svu-dragging {\n border-color: ${e.primary};\n background: ${e.primaryLight};\n }\n\n .svu-drop-zone.svu-has-file {\n border-style: solid;\n border-color: ${e.primary};\n background: ${e.primaryLight};\n cursor: default;\n }\n\n .svu-drop-icon {\n color: ${e.textMuted};\n margin-bottom: 12px;\n display: flex;\n justify-content: center;\n }\n\n .svu-drop-text {\n font-size: 14px;\n font-weight: 500;\n color: ${e.textPrimary};\n margin: 0 0 4px 0;\n }\n\n .svu-drop-subtext {\n font-size: 13px;\n color: ${e.textSecondary};\n margin: 0 0 8px 0;\n }\n\n .svu-drop-hint {\n font-size: 12px;\n color: ${e.textMuted};\n margin: 0;\n }\n\n /* Selected File */\n .svu-selected-file {\n display: flex;\n align-items: center;\n gap: 12px;\n width: 100%;\n }\n\n .svu-file-icon {\n color: ${e.primary};\n flex-shrink: 0;\n }\n\n .svu-file-info {\n flex: 1;\n min-width: 0;\n text-align: left;\n }\n\n .svu-file-name {\n display: block;\n font-size: 14px;\n font-weight: 500;\n color: ${e.textPrimary};\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n }\n\n .svu-file-size {\n display: block;\n font-size: 12px;\n color: ${e.textSecondary};\n }\n\n .svu-remove-file {\n flex-shrink: 0;\n width: 24px;\n height: 24px;\n display: flex;\n align-items: center;\n justify-content: center;\n background: transparent;\n border: none;\n border-radius: 50%;\n cursor: pointer;\n font-size: 18px;\n color: ${e.textMuted};\n transition: background 0.15s ease, color 0.15s ease;\n }\n\n .svu-remove-file:hover {\n background: ${e.bgHover};\n color: ${e.error};\n }\n\n /* Max Size */\n .svu-max-size {\n font-size: 12px;\n color: ${e.textMuted};\n margin: 0 0 16px 0;\n }\n\n /* Upload Button */\n .svu-btn {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n gap: 8px;\n width: 100%;\n padding: 12px 20px;\n font-size: 14px;\n font-weight: 500;\n letter-spacing: -0.005em;\n line-height: 1.4;\n border: none;\n border-radius: 8px;\n cursor: pointer;\n transition: background 0.15s ease, transform 0.1s ease;\n box-sizing: border-box;\n }\n\n .svu-btn:disabled {\n opacity: 0.5;\n cursor: not-allowed;\n }\n\n .svu-btn:active:not(:disabled) {\n transform: scale(0.98);\n }\n\n .svu-btn-primary {\n background: ${e.primary};\n color: ${e.textOnPrimary};\n box-shadow: ${e.shadowSm};\n }\n\n .svu-btn-primary:hover:not(:disabled) {\n background: ${e.primaryHover};\n }\n\n .svu-btn-secondary {\n background: ${e.bgSubtle};\n color: ${e.textPrimary};\n border: 1px solid ${e.border};\n }\n\n .svu-btn-secondary:hover:not(:disabled) {\n background: ${e.bgHover};\n }\n\n /* Error Alert */\n .svu-error-alert {\n background: ${e.errorLight};\n border: 1px solid ${e.errorBorder};\n color: ${e.error};\n padding: 10px 12px;\n border-radius: 8px;\n font-size: 13px;\n font-weight: 450;\n margin-bottom: 16px;\n width: 100%;\n }\n\n /* Metadata Grid */\n .svu-metadata {\n width: 100%;\n margin-top: 20px;\n padding-top: 20px;\n border-top: 1px solid ${e.border};\n }\n\n .svu-metadata h4 {\n font-size: 12px;\n font-weight: 600;\n color: ${e.textSecondary};\n text-transform: uppercase;\n letter-spacing: 0.05em;\n margin: 0 0 12px 0;\n }\n\n .svu-metadata-grid {\n display: grid;\n grid-template-columns: 1fr 1fr;\n gap: 8px;\n }\n\n .svu-metadata-item {\n font-size: 12px;\n }\n\n .svu-metadata-item.svu-full-width {\n grid-column: span 2;\n }\n\n .svu-metadata-label {\n display: block;\n color: ${e.textMuted};\n margin-bottom: 2px;\n }\n\n .svu-metadata-value {\n display: block;\n color: ${e.textPrimary};\n font-weight: 500;\n }\n\n .svu-metadata-value.svu-status-active {\n color: ${e.success};\n }\n\n /* ========================================\n UPLOADING VIEW\n ======================================== */\n\n .svu-uploading-view {\n display: flex;\n flex-direction: column;\n align-items: center;\n }\n\n .svu-stages {\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 12px;\n margin: 24px 0;\n width: 100%;\n }\n\n .svu-stage {\n display: flex;\n flex-direction: column;\n align-items: center;\n gap: 8px;\n opacity: 0.5;\n transition: opacity 0.3s ease;\n }\n\n .svu-stage.svu-active {\n opacity: 1;\n }\n\n .svu-stage span {\n font-size: 11px;\n color: ${e.textMutedOnDark};\n }\n\n .svu-stage-sub {\n font-size: 10px !important;\n color: ${e.primary} !important;\n }\n\n .svu-stage-arrow {\n width: 24px;\n height: 2px;\n background: ${e.borderDark};\n position: relative;\n }\n\n .svu-stage-arrow.svu-active::after {\n content: '';\n position: absolute;\n left: 0;\n top: 0;\n height: 100%;\n background: ${e.primary};\n animation: svu-arrow-flow 1s ease-in-out infinite;\n }\n\n @keyframes svu-arrow-flow {\n 0% { width: 0; }\n 50% { width: 100%; }\n 100% { width: 100%; }\n }\n\n /* Progress Bar */\n .svu-progress {\n width: 100%;\n margin: 20px 0;\n }\n\n .svu-progress-bar {\n width: 100%;\n height: 6px;\n background: ${e.borderDark};\n border-radius: 3px;\n overflow: hidden;\n }\n\n .svu-progress-fill {\n height: 100%;\n background: ${e.primary};\n border-radius: 3px;\n transition: width 0.3s ease;\n }\n\n .svu-progress-text {\n display: flex;\n justify-content: space-between;\n margin-top: 8px;\n font-size: 12px;\n color: ${e.textMutedOnDark};\n }\n\n /* Forging Info */\n .svu-forging-info {\n width: 100%;\n margin-top: 20px;\n padding: 16px;\n background: ${e.bgDarkSubtle};\n border-radius: 8px;\n }\n\n .svu-forging-line {\n font-size: 12px;\n color: ${e.textMutedOnDark};\n margin: 0 0 8px 0;\n }\n\n .svu-forging-line:last-child {\n margin-bottom: 0;\n }\n\n .svu-mono {\n font-family: ui-monospace, SFMono-Regular, 'SF Mono', Menlo, Monaco, monospace;\n color: ${e.textOnDark};\n }\n\n /* ========================================\n CEREMONY VIEW\n ======================================== */\n\n .svu-ceremony-view {\n display: flex;\n flex-direction: column;\n align-items: center;\n }\n\n .svu-ceremony-steps {\n width: 100%;\n margin: 20px 0;\n }\n\n .svu-ceremony-step {\n display: flex;\n align-items: center;\n gap: 12px;\n padding: 10px 0;\n opacity: 0.4;\n transition: opacity 0.3s ease;\n }\n\n .svu-ceremony-step.svu-active {\n opacity: 1;\n }\n\n .svu-ceremony-step.svu-complete {\n opacity: 0.7;\n }\n\n .svu-step-icon {\n width: 20px;\n height: 20px;\n display: flex;\n align-items: center;\n justify-content: center;\n color: ${e.primary};\n }\n\n .svu-step-text {\n font-size: 13px;\n color: ${e.textOnDark};\n }\n\n /* Spinning loader */\n .svu-step-icon .svu-spin {\n animation: svu-spin 0.7s linear infinite;\n }\n\n /* ========================================\n COMPLETE VIEW\n ======================================== */\n\n .svu-complete-view {\n display: flex;\n flex-direction: column;\n align-items: center;\n animation: svu-scale-in 0.3s ease;\n }\n\n @keyframes svu-scale-in {\n from {\n opacity: 0;\n transform: scale(0.95);\n }\n to {\n opacity: 1;\n transform: scale(1);\n }\n }\n\n .svu-success-icon {\n color: ${e.success};\n margin-bottom: 16px;\n }\n\n .svu-success-title {\n font-size: 20px;\n font-weight: 600;\n color: ${e.textPrimary};\n margin: 0 0 24px 0;\n text-align: center;\n }\n\n .svu-success-details {\n width: 100%;\n background: ${e.bgSubtle};\n border-radius: 8px;\n padding: 16px;\n margin-bottom: 16px;\n }\n\n .svu-success-row {\n display: flex;\n justify-content: space-between;\n align-items: center;\n padding: 8px 0;\n font-size: 13px;\n border-bottom: 1px solid ${e.border};\n }\n\n .svu-success-row:last-child {\n border-bottom: none;\n }\n\n .svu-success-label {\n color: ${e.textSecondary};\n }\n\n .svu-success-value {\n color: ${e.textPrimary};\n font-weight: 500;\n display: flex;\n align-items: center;\n gap: 8px;\n }\n\n .svu-copy-btn {\n width: 24px;\n height: 24px;\n display: flex;\n align-items: center;\n justify-content: center;\n background: transparent;\n border: none;\n border-radius: 4px;\n cursor: pointer;\n color: ${e.textMuted};\n transition: background 0.15s ease, color 0.15s ease;\n }\n\n .svu-copy-btn:hover {\n background: ${e.bgHover};\n color: ${e.primary};\n }\n\n .svu-success-guidance {\n font-size: 13px;\n color: ${e.textSecondary};\n text-align: center;\n margin: 0 0 20px 0;\n line-height: 1.5;\n }\n\n /* ========================================\n ERROR VIEW\n ======================================== */\n\n .svu-error-view {\n display: flex;\n flex-direction: column;\n align-items: center;\n text-align: center;\n }\n\n .svu-error-icon {\n color: ${e.error};\n margin-bottom: 16px;\n }\n\n .svu-error-title {\n font-size: 18px;\n font-weight: 600;\n color: ${e.textPrimary};\n margin: 0 0 8px 0;\n }\n\n .svu-error-message {\n font-size: 14px;\n color: ${e.textSecondary};\n margin: 0 0 16px 0;\n line-height: 1.5;\n }\n\n .svu-error-code {\n display: inline-flex;\n align-items: center;\n gap: 6px;\n padding: 6px 10px;\n background: ${e.errorLight};\n border: 1px solid ${e.errorBorder};\n border-radius: 6px;\n margin-bottom: 20px;\n }\n\n .svu-error-code-label {\n font-size: 10px;\n font-weight: 600;\n color: ${e.errorText};\n text-transform: uppercase;\n letter-spacing: 0.05em;\n }\n\n .svu-error-code-value {\n font-size: 11px;\n font-family: ui-monospace, SFMono-Regular, 'SF Mono', Menlo, Monaco, monospace;\n color: ${e.error};\n font-weight: 500;\n }\n\n /* ========================================\n SECURITY SIDEBAR\n ======================================== */\n\n .svu-sidebar {\n width: 320px;\n background: ${e.bgDark};\n border-left: 1px solid ${e.borderDark};\n color: ${e.textOnDark};\n padding: 20px;\n overflow-y: auto;\n flex-shrink: 0;\n }\n\n .svu-sidebar-logo {\n margin-bottom: 20px;\n }\n\n .svu-sidebar-logo img {\n height: 24px;\n width: auto;\n }\n\n .svu-sidebar-intro h3 {\n font-size: 14px;\n font-weight: 600;\n margin: 0 0 8px 0;\n }\n\n .svu-sidebar-intro p {\n font-size: 12px;\n color: ${e.textMutedOnDark};\n line-height: 1.5;\n margin: 0 0 20px 0;\n }\n\n .svu-sidebar-security h4 {\n display: flex;\n align-items: center;\n gap: 8px;\n font-size: 12px;\n font-weight: 600;\n margin: 0 0 12px 0;\n }\n\n .svu-security-intro {\n font-size: 11px;\n color: ${e.textMutedOnDark};\n line-height: 1.5;\n margin: 0 0 16px 0;\n }\n\n .svu-security-intro strong {\n color: ${e.textOnDark};\n }\n\n .svu-key-chain {\n display: flex;\n flex-direction: column;\n gap: 8px;\n margin-bottom: 16px;\n }\n\n .svu-key-item {\n display: flex;\n gap: 12px;\n padding: 10px;\n background: ${e.bgDarkSubtle};\n border-radius: 6px;\n }\n\n .svu-key-number {\n width: 20px;\n height: 20px;\n background: ${e.primary};\n color: ${e.textOnPrimary};\n border-radius: 50%;\n font-size: 11px;\n font-weight: 600;\n display: flex;\n align-items: center;\n justify-content: center;\n flex-shrink: 0;\n }\n\n .svu-key-info {\n flex: 1;\n }\n\n .svu-key-name {\n display: block;\n font-size: 11px;\n font-weight: 600;\n color: ${e.textOnDark};\n margin-bottom: 2px;\n }\n\n .svu-key-algo {\n display: block;\n font-size: 10px;\n color: ${e.primary};\n margin-bottom: 4px;\n }\n\n .svu-key-desc {\n display: block;\n font-size: 10px;\n color: ${e.textMutedOnDark};\n line-height: 1.4;\n }\n\n .svu-key-connector {\n display: flex;\n justify-content: center;\n color: ${e.textMutedOnDark};\n }\n\n .svu-encryption-result {\n display: flex;\n gap: 8px;\n font-size: 10px;\n color: ${e.textMutedOnDark};\n line-height: 1.5;\n padding: 10px;\n background: ${e.bgDarkSubtle};\n border-radius: 6px;\n margin-bottom: 16px;\n }\n\n .svu-encryption-result svg {\n color: ${e.successOnDark};\n flex-shrink: 0;\n }\n\n .svu-encryption-result strong {\n color: ${e.textOnDark};\n }\n\n .svu-security-badges {\n display: flex;\n flex-wrap: wrap;\n gap: 6px;\n }\n\n .svu-tls-badge {\n font-size: 9px;\n font-weight: 500;\n padding: 4px 8px;\n background: ${e.bgDarkSubtle};\n border-radius: 4px;\n color: ${e.textMutedOnDark};\n }\n\n /* ========================================\n INLINE CONTAINER\n ======================================== */\n\n .svu-inline-container {\n display: flex;\n flex-direction: column;\n width: 100%;\n height: 100%;\n box-sizing: border-box;\n background: ${e.bg};\n color: ${e.textPrimary};\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 ${e.border};\n overflow: hidden;\n }\n\n /* ========================================\n RESPONSIVE\n ======================================== */\n\n @media (max-width: 768px) {\n .svu-modal.svu-with-sidebar {\n flex-direction: column;\n max-width: 480px;\n }\n\n .svu-sidebar {\n width: 100%;\n border-left: none;\n border-top: 1px solid ${e.borderDark};\n max-height: 300px;\n }\n }\n\n @media (max-width: 480px) {\n .svu-modal {\n max-width: 100%;\n max-height: 100%;\n border-radius: 0;\n }\n\n .svu-overlay {\n padding: 0;\n }\n\n .svu-body {\n padding: 20px;\n }\n }\n\n /* ========================================\n ACCESSIBILITY\n ======================================== */\n\n .svu-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 `}(),document.head.appendChild(e)}const Si="svu-modal-title",Ei={organizationName:"",logoLightUrl:null,logoDarkUrl:null};class _i{constructor(){this.shell=null,this.header=null,this.body=null,this.sidebar=null,this.onCloseCallback=null,this.isDarkMode=!1,this.branding=Ei}createLoading(e,t){if(this.shell)return;this.onCloseCallback=t,this.branding=Ei,Ci(),this.shell=new rn({overlayId:"sparkvault-upload-overlay",modalId:"sparkvault-upload-modal",classPrefix:"svu",titleId:Si,backdropBlur:!1!==e.backdropBlur,onDismiss:()=>this.handleClose()});const n=document.createElement("div");n.className="svu-modal-main",this.header=this.createHeader(),this.body=document.createElement("div"),this.body.className="svu-body",n.append(this.header,this.body,an("svu")),this.shell.modal.appendChild(n)}createHeader(){return function(e){const{branding:t,isDarkMode:n,titleId:i,onClose:s}=e,o=document.createElement("div");o.className="svu-header";const r=document.createElement("div");r.className="svu-header-title";const a=ln(n,t.logoLightUrl,t.logoDarkUrl);if(a){const e=document.createElement("img");e.className="svu-logo",e.src=a,e.alt=t.organizationName,r.appendChild(e);const n=document.createElement("span");n.className="svu-sr-only",n.id=i,n.textContent=t.organizationName,r.appendChild(n)}else if(t.organizationName){const e=document.createElement("h2");e.className="svu-company-name",e.id=i,e.textContent=t.organizationName,r.appendChild(e)}const l=document.createElement("button");return l.className="svu-close-btn",l.type="button",l.setAttribute("aria-label","Close"),l.innerHTML='\n <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">\n <path d="M18 6L6 18M6 6l12 12"/>\n </svg>\n ',l.addEventListener("click",s),o.append(r,l),o}({branding:this.branding,isDarkMode:this.isDarkMode,titleId:Si,onClose:()=>this.handleClose()})}refreshHeader(){if(!this.header)return;const e=this.createHeader();e.style.display=this.header.style.display,this.header.replaceWith(e),this.header=e}updateBranding(e){this.shell&&(this.branding=e,this.refreshHeader())}setDarkMode(e){this.shell&&this.isDarkMode!==e&&(this.isDarkMode=e,this.shell.modal.classList.toggle("svu-dark",e),this.refreshHeader())}toggleSidebar(e){this.shell&&(e&&!this.sidebar?(this.sidebar=function(e){const t=document.createElement("div");t.className="svu-sidebar";const n=document.createElement("div");if(n.className="svu-sidebar-logo",e.logoDarkUrl){const t=document.createElement("img");t.src=e.logoDarkUrl,t.alt=e.organizationName,n.appendChild(t)}t.appendChild(n);const i=document.createElement("div");i.className="svu-sidebar-intro",i.innerHTML="\n <h3>Secure File Transfer</h3>\n <p>This file is secured with SparkVault's advanced multi-key cryptography and end-to-end encryption.</p>\n ",t.appendChild(i);const s=document.createElement("div");return s.className="svu-sidebar-security",s.innerHTML='\n <h4>\n <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">\n <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>\n </svg>\n SparkVault\'s Triple Zero-Trust\n </h4>\n <p class="svu-security-intro">\n Decryption requires <strong>three independent Master Keys</strong>, held in three different physical locations, by three separate companies, all cryptographically combined in real-time.\n </p>\n <div class="svu-key-chain">\n <div class="svu-key-item">\n <div class="svu-key-number">1</div>\n <div class="svu-key-info">\n <span class="svu-key-name">Kyber-1024 Post-Quantum Key</span>\n <span class="svu-key-algo">ML-KEM lattice-based encapsulation</span>\n <span class="svu-key-desc">Quantum-resistant key exchange</span>\n </div>\n </div>\n <div class="svu-key-connector">\n <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">\n <path d="M12 5v14M5 12h14"/>\n </svg>\n </div>\n <div class="svu-key-item">\n <div class="svu-key-number">2</div>\n <div class="svu-key-info">\n <span class="svu-key-name">X25519 Ephemeral Key</span>\n <span class="svu-key-algo">Elliptic-curve Diffie-Hellman</span>\n <span class="svu-key-desc">Perfect forward secrecy</span>\n </div>\n </div>\n <div class="svu-key-connector">\n <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">\n <path d="M12 5v14M5 12h14"/>\n </svg>\n </div>\n <div class="svu-key-item">\n <div class="svu-key-number">3</div>\n <div class="svu-key-info">\n <span class="svu-key-name">HKDF-SHA512 Derived Key</span>\n <span class="svu-key-algo">Hardware-bound key derivation</span>\n <span class="svu-key-desc">Vault master key in secure enclave</span>\n </div>\n </div>\n </div>\n <div class="svu-encryption-result">\n <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">\n <path d="M20 6L9 17l-5-5"/>\n </svg>\n <span>Combined via <strong>HKDF</strong> producing <strong>AES-256-GCM</strong> authenticated cipher</span>\n </div>\n <div class="svu-security-badges">\n <span class="svu-tls-badge">TLS 1.3 In Transit</span>\n <span class="svu-tls-badge">Encrypted At Rest</span>\n <span class="svu-tls-badge">Zero Trust</span>\n </div>\n ',t.appendChild(s),t}(this.branding),this.shell.modal.classList.add("svu-with-sidebar"),this.shell.modal.appendChild(this.sidebar),this.header&&(this.header.style.display="none")):!e&&this.sidebar&&(this.shell.modal.classList.remove("svu-with-sidebar"),this.sidebar.remove(),this.sidebar=null,this.header&&(this.header.style.display="")))}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.sidebar=null,this.onCloseCallback=null}}class Ti{constructor(e){this.shell=null,this.targetElement=e}createLoading(e,t){this.shell||(Ci(),this.shell=new vn(this.targetElement,{containerClassName:"svu-inline-container",bodyClassName:"svu-body",footer:an("svu")}))}updateBranding(e){}getBody(){return this.shell?.body??null}isOpen(){return null!==this.shell}destroy(){this.shell?.destroy(),this.shell=null}}const Ai=Object.freeze(["B","KB","MB","GB","TB"]);function Ii(e,t=1){if("number"!=typeof e||!Number.isFinite(e)||e<=0)return`0 ${Ai[0]}`;const n=Math.min(Math.max(Math.floor(Math.log(e)/Math.log(1024)),0),Ai.length-1);return`${parseFloat((e/1024**n).toFixed(t))} ${Ai[n]}`}const $i=[{text:"File received by Forge",duration:600},{text:"Deriving Triple Zero-Trust encryption keys",duration:800},{text:"Encrypting with AES-256-GCM",duration:900},{text:"Generating cryptographic signatures",duration:700},{text:"Storing in post-quantum protected vault",duration:600},{text:"Verifying integrity",duration:400}];function Li(e){return Se(new Uint8Array(e.match(/.{2}/g).map(e=>parseInt(e,16))))}function Bi(e){return null===e?"":`<p class="svu-forging-line">Secure Transfer Channel: <span class="svu-mono">${It(e)}</span></p>`}function Mi(e){if(!(e instanceof Zn))return{label:"Try Again",keepFile:!0};if(function(e){return e.code===o||e.details?.coreCode===o||"UPLOAD_SOURCE_DISABLED"===e.code||402===e.statusCode||404===e.statusCode&&"session_gone"!==e.code}(e))return null;if(e.code===r)return{label:"Upload Another File",keepFile:!1};const t=e.statusCode??0;return 0===t||429===t||t>=500?{label:"Try Again",keepFile:!0}:{label:"Choose Another File",keepFile:!1}}class Pi{constructor(e,t,n,i){this.viewState={view:"loading"},this.config=null,this.selectedFile=null,this.fileInputElement=null,this.uploadModal=null,this.isInlineMode=!1,this.hybridModalInitialized=!1,this.closed=!1,this.cancelled=!1,this.pasteHandler=null,this.container=e,this.api=t,this.options=n,this.callbacks=i,this.isInlineMode=!!n.target}async start(){this.container.createLoading({backdropBlur:this.options.backdropBlur},()=>this.handleClose()),this.setState({view:"loading"});try{const[e]=await Promise.all([this.api.getVaultUploadInfo(this.options.vaultId),new Promise(e=>setTimeout(e,1e3))]);if(this.config=e,this.container.updateBranding(e.branding),this.options.file)return this.selectedFile=this.options.file,this.callbacks.onReady?.(),void await this.startUpload(e);this.setState({view:"form",config:e}),this.callbacks.onReady?.()}catch(e){this.handleApiError(e)}}close(){this.closed=!0,this.api.abort(),this.cleanupFileInput(),this.cleanupPasteHandler(),this.uploadModal&&(this.uploadModal.destroy(),this.uploadModal=null,this.hybridModalInitialized=!1),this.container.destroy()}cancel(){this.cancelled||(this.cancelled=!0,this.close(),this.callbacks.onCancel())}handleClose(){this.cancel()}setState(e){if(this.closed)return;const t=this.viewState.view;this.viewState=e,"uploading"===t&&"uploading"===e.view&&this.updateUploadProgress(e)||this.render()}updateUploadProgress(e){const t=this.isInlineMode&&this.uploadModal?this.uploadModal.getBody():this.container.getBody(),n=t?.querySelector(".svu-progress-fill");if(!t||!n)return!1;n.style.width=`${e.progress}%`;const[i,s]=t.querySelectorAll(".svu-progress-text span");return i&&(i.textContent=`${e.progress}%`),s&&(s.textContent=`${Ii(e.bytesUploaded)} / ${Ii(e.file.size)}`),!0}render(){const e="uploading"===this.viewState.view||"ceremony"===this.viewState.view;if(this.isInlineMode&&e)return void this.renderInModal();if(this.uploadModal){this.uploadModal.destroy(),this.uploadModal=null,this.hybridModalInitialized=!1;const e=this.container.getBody();e?.parentElement&&(e.parentElement.style.display="")}const t=this.container.getBody();if(t)switch(t.innerHTML="",this.container instanceof _i&&(this.container.setDarkMode(e),this.container.toggleSidebar(e)),this.viewState.view){case"loading":t.appendChild(this.renderLoading());break;case"form":t.appendChild(this.renderForm(this.viewState.config,this.viewState.error));break;case"uploading":t.appendChild(this.renderUploading(this.viewState));break;case"ceremony":t.appendChild(this.renderCeremony(this.viewState));break;case"complete":t.appendChild(this.renderComplete(this.viewState.result,this.viewState.config));break;case"error":t.appendChild(this.renderError(this.viewState))}}renderInModal(){this.uploadModal||(this.uploadModal=new _i,this.uploadModal.createLoading({backdropBlur:this.options.backdropBlur??!0},()=>{}),this.config&&this.uploadModal.updateBranding(this.config.branding),this.hybridModalInitialized=!1);const e=this.uploadModal.getBody();if(e){if(!this.hybridModalInitialized){const e=this.container.getBody();e?.parentElement&&(e.parentElement.style.display="none"),this.uploadModal.setDarkMode(!0),this.uploadModal.toggleSidebar(!0),this.hybridModalInitialized=!0}e.innerHTML="","uploading"===this.viewState.view?e.appendChild(this.renderUploading(this.viewState)):"ceremony"===this.viewState.view&&e.appendChild(this.renderCeremony(this.viewState))}}renderLoading(){const e=document.createElement("div");return e.className="svu-loading",e.innerHTML='\n <div class="svu-spinner"></div>\n <p class="svu-loading-text">Establishing secure connection...</p>\n ',e}renderForm(e,t){const n=document.createElement("div");n.className="svu-form-view";const i=document.createElement("h2");i.className="svu-title",i.textContent="Cryptographically Secure File Transfer",n.appendChild(i);const s=document.createElement("p");if(s.className="svu-subtitle",s.innerHTML=`Destination Vault: <strong>${It(e.vaultName)}</strong>`,n.appendChild(s),t){const e=document.createElement("div");e.className="svu-error-alert",e.textContent=t,n.appendChild(e)}const o=document.createElement("div");if(o.className="svu-drop-zone"+(this.selectedFile?" svu-has-file":""),this.selectedFile){o.innerHTML=`\n <div class="svu-selected-file">\n <div class="svu-file-icon">\n <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">\n <path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/>\n <path d="M14 2v6h6"/>\n </svg>\n </div>\n <div class="svu-file-info">\n <span class="svu-file-name">${It(this.selectedFile.name)}</span>\n <span class="svu-file-size">${Ii(this.selectedFile.size)}</span>\n </div>\n <button class="svu-remove-file" aria-label="Remove file">&times;</button>\n </div>\n `;const e=o.querySelector(".svu-remove-file");e&&e.addEventListener("click",e=>{e.stopPropagation(),this.selectedFile=null,this.render()})}else o.innerHTML='\n <div class="svu-drop-icon">\n <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">\n <path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/>\n <path d="M17 8l-5-5-5 5"/>\n <path d="M12 3v12"/>\n </svg>\n </div>\n <p class="svu-drop-text">Drag & drop a file here</p>\n <p class="svu-drop-subtext">or click to select</p>\n <p class="svu-drop-hint">Paste from clipboard also supported (Ctrl+V)</p>\n ';o.addEventListener("dragover",e=>{e.preventDefault(),o.classList.add("svu-dragging")}),o.addEventListener("dragleave",e=>{e.preventDefault(),o.classList.remove("svu-dragging")}),o.addEventListener("drop",t=>{t.preventDefault(),o.classList.remove("svu-dragging");const n=t.dataTransfer?.files[0];n&&this.handleFileSelect(n,e)}),o.addEventListener("click",()=>{this.selectedFile||this.openFileSelector(e)}),n.appendChild(o);const r=document.createElement("p");if(r.className="svu-max-size",r.textContent=`Max upload size: ${Ii(e.maxSizeBytes)}`,n.appendChild(r),this.selectedFile){const t=document.createElement("button");t.className="svu-btn svu-btn-primary",t.textContent="Upload Securely",t.onclick=()=>this.startUpload(e),n.appendChild(t)}const a=document.createElement("div");return a.className="svu-metadata",a.innerHTML=`\n <h4>Transfer Details</h4>\n <div class="svu-metadata-grid">\n <div class="svu-metadata-item">\n <span class="svu-metadata-label">Recipient</span>\n <span class="svu-metadata-value">${It(e.branding.organizationName)}</span>\n </div>\n <div class="svu-metadata-item">\n <span class="svu-metadata-label">Vault</span>\n <span class="svu-metadata-value">${It(e.vaultName)}</span>\n </div>\n <div class="svu-metadata-item svu-full-width">\n <span class="svu-metadata-label">Vault ID</span>\n <span class="svu-metadata-value">${It(e.vaultId)}</span>\n </div>\n <div class="svu-metadata-item">\n <span class="svu-metadata-label">Encryption</span>\n <span class="svu-metadata-value">${It(e.encryption.algorithm)}</span>\n </div>\n <div class="svu-metadata-item">\n <span class="svu-metadata-label">Key Derivation</span>\n <span class="svu-metadata-value">${It(e.encryption.keyDerivation)}</span>\n </div>\n <div class="svu-metadata-item">\n <span class="svu-metadata-label">Post-Quantum</span>\n <span class="svu-metadata-value">${It(e.encryption.postQuantum)}</span>\n </div>\n <div class="svu-metadata-item">\n <span class="svu-metadata-label">Forge Status</span>\n <span class="svu-metadata-value ${"active"===e.forgeStatus?"svu-status-active":""}">\n ${"active"===e.forgeStatus?"● Active":"○ Inactive"}\n </span>\n </div>\n </div>\n `,n.appendChild(a),this.setupPasteHandler(e),n}renderUploading(e){const t=document.createElement("div");t.className="svu-uploading-view";const n=Li(e.ingotId.replace("ing_",""));return t.innerHTML=`\n <h2 class="svu-title">Streaming & Encrypting</h2>\n\n <div class="svu-stages">\n <div class="svu-stage svu-active">\n <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">\n <rect x="2" y="3" width="20" height="18" rx="2"/>\n <path d="M2 9h20"/>\n <circle cx="6" cy="6" r="1" fill="currentColor"/>\n <circle cx="10" cy="6" r="1" fill="currentColor"/>\n </svg>\n <span>Your Browser</span>\n </div>\n <div class="svu-stage-arrow svu-active"></div>\n <div class="svu-stage svu-active">\n <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">\n <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>\n </svg>\n <span>SparkVault</span>\n <span class="svu-stage-sub">Encrypting</span>\n </div>\n <div class="svu-stage-arrow"></div>\n <div class="svu-stage">\n <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">\n <rect x="3" y="3" width="18" height="18" rx="2"/>\n <circle cx="12" cy="12" r="3"/>\n <path d="M12 9V6M12 18v-3M9 12H6M18 12h-3"/>\n </svg>\n <span>${It(this.config?.branding.organizationName||"")}</span>\n </div>\n </div>\n\n <div class="svu-progress">\n <div class="svu-progress-bar">\n <div class="svu-progress-fill" style="width: ${e.progress}%"></div>\n </div>\n <div class="svu-progress-text">\n <span>${e.progress}%</span>\n <span>${Ii(e.bytesUploaded)} / ${Ii(e.file.size)}</span>\n </div>\n </div>\n\n <div class="svu-forging-info">\n <p class="svu-forging-line">Forging Ingot ID: <span class="svu-mono">${n}</span></p>\n ${Bi(e.requestId)}\n </div>\n `,t}renderCeremony(e){const t=document.createElement("div");t.className="svu-ceremony-view";const n=Li(e.ingotId.replace("ing_",""));let i="";return $i.forEach((t,n)=>{const s=n<e.step,o=n===e.step;i+=`\n <div class="svu-ceremony-step ${s?"svu-complete":""} ${o?"svu-active":""}">\n <span class="svu-step-icon">\n ${s?'<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M20 6L9 17l-5-5"/></svg>':o?'<svg class="svu-spin" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4M4.93 19.07l2.83-2.83M16.24 7.76l2.83-2.83"/></svg>':""}\n </span>\n <span class="svu-step-text">${t.text}</span>\n </div>\n `}),t.innerHTML=`\n <h2 class="svu-title">Securing Your File</h2>\n\n <div class="svu-ceremony-steps">\n ${i}\n </div>\n\n <div class="svu-forging-info">\n <p class="svu-forging-line">Forging Ingot ID: <span class="svu-mono">${n}</span></p>\n ${Bi(e.requestId)}\n </div>\n `,t}renderComplete(e,t){const n=document.createElement("div");n.className="svu-complete-view",n.innerHTML=`\n <div class="svu-success-icon">\n <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">\n <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/>\n <path d="M22 4L12 14.01l-3-3"/>\n </svg>\n </div>\n\n <h2 class="svu-success-title">Your file has been securely sent!</h2>\n\n <div class="svu-success-details">\n <div class="svu-success-row">\n <span class="svu-success-label">Ingot ID</span>\n <span class="svu-success-value svu-mono">\n ${It(e.ingotId)}\n <button class="svu-copy-btn" aria-label="Copy Ingot ID">\n <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">\n <rect x="9" y="9" width="13" height="13" rx="2" ry="2"/>\n <path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"/>\n </svg>\n </button>\n </span>\n </div>\n <div class="svu-success-row">\n <span class="svu-success-label">File</span>\n <span class="svu-success-value">${It(e.filename)}</span>\n </div>\n <div class="svu-success-row">\n <span class="svu-success-label">Size</span>\n <span class="svu-success-value">${Ii(e.sizeBytes)}</span>\n </div>\n <div class="svu-success-row">\n <span class="svu-success-label">Timestamp</span>\n <span class="svu-success-value svu-mono">${It(e.uploadTime)}</span>\n </div>\n <div class="svu-success-row">\n <span class="svu-success-label">Encryption</span>\n <span class="svu-success-value">AES-256-GCM</span>\n </div>\n </div>\n\n <p class="svu-success-guidance">\n ${It(t.branding.organizationName)} has been notified and can access this file\n from their SparkVault dashboard. Save the Ingot ID above for your records.\n </p>\n\n ${this.options.hideUploadAnother?"":'\n <button class="svu-btn svu-btn-secondary">\n <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">\n <path d="M1 4v6h6M23 20v-6h-6"/>\n <path d="M20.49 9A9 9 0 005.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 013.51 15"/>\n </svg>\n Upload Another File\n </button>\n '}\n `;const i=n.querySelector(".svu-copy-btn");i&&i.addEventListener("click",()=>{navigator.clipboard.writeText(e.ingotId)});const s=n.querySelector(".svu-btn-secondary");return s&&s.addEventListener("click",()=>{this.selectedFile=null,this.setState({view:"form",config:t})}),n}renderError(e){const t=document.createElement("div");t.className="svu-error-view",t.innerHTML=`\n <div class="svu-error-icon">\n <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">\n <circle cx="12" cy="12" r="10"/>\n <path d="M12 8v4M12 16h.01"/>\n </svg>\n </div>\n\n <h2 class="svu-error-title">${It(e.title)}</h2>\n\n <p class="svu-error-message">${It(e.message)}</p>\n\n <div class="svu-error-code">\n <span class="svu-error-code-label">Code</span>\n <span class="svu-error-code-value">${It(e.code)}</span>\n </div>\n `;const{action:n}=e;if(n&&this.config){const e=this.config,i=document.createElement("button");i.className="svu-btn svu-btn-primary",i.textContent=n.label,i.addEventListener("click",()=>{n.keepFile||(this.selectedFile=null),this.setState({view:"form",config:e})}),t.appendChild(i)}return t}handleFileSelect(e,t){0!==e.size?e.size>t.maxSizeBytes?this.setState({view:"form",config:t,error:`File size exceeds maximum allowed (${Ii(t.maxSizeBytes)})`}):(this.selectedFile=e,this.setState({view:"form",config:t})):this.setState({view:"form",config:t,error:"This file is empty, so there is nothing to upload. Choose another file."})}openFileSelector(e){this.cleanupFileInput(),this.fileInputElement=document.createElement("input"),this.fileInputElement.type="file",this.fileInputElement.style.display="none",this.fileInputElement.onchange=()=>{const t=this.fileInputElement?.files?.[0];t&&this.handleFileSelect(t,e)},document.body.appendChild(this.fileInputElement),this.fileInputElement.click()}cleanupFileInput(){this.fileInputElement&&(this.fileInputElement.remove(),this.fileInputElement=null)}setupPasteHandler(e){this.cleanupPasteHandler(),this.pasteHandler=t=>{const n=t.clipboardData?.items;if(n)for(const t of n)if("file"===t.kind){const n=t.getAsFile();if(n){this.handleFileSelect(n,e);break}}},document.addEventListener("paste",this.pasteHandler)}cleanupPasteHandler(){this.pasteHandler&&(document.removeEventListener("paste",this.pasteHandler),this.pasteHandler=null)}async startUpload(e){if(!this.selectedFile)return;const t=this.selectedFile;try{const{forgeUrl:n,ingotId:i,requestId:s}=await this.api.initiateUpload(e.vaultId,t.name,t.size,t.type||"application/octet-stream",this.options.token,this.options.folder);this.setState({view:"uploading",file:t,ingotId:i,requestId:s,progress:0,bytesUploaded:0}),await this.api.uploadFileToForge(t,n,(e,n)=>{const o=Math.round(e/n*100);this.setState({view:"uploading",file:t,ingotId:i,requestId:s,progress:o,bytesUploaded:e}),this.callbacks.onProgress?.({bytesUploaded:e,bytesTotal:n,percentage:o,phase:"uploading"})}),await this.runCeremony(t,i,s);const o=new Date,r=`${o.getUTCFullYear()}-${String(o.getUTCMonth()+1).padStart(2,"0")}-${String(o.getUTCDate()).padStart(2,"0")} ${String(o.getUTCHours()).padStart(2,"0")}:${String(o.getUTCMinutes()).padStart(2,"0")}:${String(o.getUTCSeconds()).padStart(2,"0")} UTC`,a={ingotId:i,vaultId:e.vaultId,filename:t.name,sizeBytes:t.size,uploadTime:r};if(this.callbacks.onProgress?.({bytesUploaded:t.size,bytesTotal:t.size,percentage:100,phase:"complete"}),this.options.hideSuccessScreen)return this.callbacks.onSuccess(a),void this.close();this.setState({view:"complete",result:a,config:e}),this.callbacks.onSuccess(a)}catch(e){this.handleApiError(e,this.options.file?null:Mi(e))}}async runCeremony(e,t,n){for(let i=0;i<$i.length;i++)this.setState({view:"ceremony",file:e,ingotId:t,requestId:n,step:i,complete:!1}),this.callbacks.onProgress?.({bytesUploaded:e.size,bytesTotal:e.size,percentage:100,phase:"ceremony"}),await new Promise(e=>setTimeout(e,$i[i].duration));this.setState({view:"ceremony",file:e,ingotId:t,requestId:n,step:$i.length,complete:!0}),await new Promise(e=>setTimeout(e,500))}handleApiError(e,t=null){if(!this.closed&&!function(e){return e instanceof D||e instanceof I&&"cancelled"===e.code}(e))if(e instanceof Zn)"UPLOAD_SOURCE_DISABLED"===e.code?this.setState({view:"error",action:t,title:"Upload Widget Not Enabled",message:"This vault has not enabled the embedded upload widget. Enable it on the vault's settings page in the SparkVault dashboard to start accepting uploads here.",code:"UPLOAD_SOURCE_DISABLED",statusCode:e.statusCode}):e.code===r?this.setState({view:"error",action:t,title:"Upload Received",message:e.message,code:e.code,statusCode:e.statusCode}):e.code===o||e.details?.coreCode===o?this.setState({view:"error",action:t,title:"Uploads Paused",message:"This vault isn't accepting files right now, so your file was not saved. Please contact the person who shared this upload page with you.",code:e.code,statusCode:e.statusCode}):"upload_refused"===e.code?this.setState({view:"error",action:t,title:"Upload Not Saved",message:e.message,code:e.code,statusCode:e.statusCode}):404===e.statusCode&&"session_gone"!==e.code?this.setState({view:"error",action:t,title:"Upload Page Not Found",message:"The requested upload endpoint could not be located. This may occur if the upload link has expired or was entered incorrectly.",code:"NOT_FOUND",statusCode:404}):402===e.statusCode?this.setState({view:"error",action:t,title:"Service Unavailable",message:"This upload endpoint has been temporarily disabled due to an account billing issue. Please contact the organization's administrator.",code:"PAYMENT_REQUIRED",statusCode:402}):this.setState({view:"error",action:t,title:"Upload Failed",message:e.message,code:e.code,statusCode:e.statusCode}),this.callbacks.onError(e);else if(e instanceof Error)this.setState({view:"error",action:t,title:"Upload Failed",message:e.message,code:"UNKNOWN_ERROR"}),this.callbacks.onError(e);else{const e=new Error("An unexpected error occurred");this.setState({view:"error",action:t,title:"Upload Failed",message:e.message,code:"UNKNOWN_ERROR"}),this.callbacks.onError(e)}}}class Ri{constructor(e){this.renderer=null,this.config=e,this.api=new ki(e)}async upload(e){if(!e.vaultId)throw new M("vaultId is required");this.renderer&&this.renderer.cancel();const t=!!e.target?this.createInlineContainer(e.target):new _i,n={...e,backdropBlur:e.backdropBlur??this.config.backdropBlur};return this.api.resetSession(),new Promise((i,s)=>{this.renderer=new Pi(t,this.api,n,{onSuccess:t=>{e.onSuccess?.(t),i(t)},onError:t=>{e.onError?.(t),s(t)},onCancel:()=>{const t=new D;e.onCancel?.(),s(t)},onProgress:e.onProgress,onReady:e.onReady}),this.renderer.start().catch(t=>{e.onError?.(t),s(t)})})}attach(e,t){if(!t.vaultId)throw new M("vaultId is required");return bn(e,async e=>{e.preventDefault();try{await this.upload({vaultId:t.vaultId,onSuccess:t.onSuccess,onError:t.onError,onCancel:t.onCancel,onProgress:t.onProgress})}catch{}})}close(){this.renderer&&(this.renderer.cancel(),this.renderer=null)}createInlineContainer(e){return new Ti(yn(e))}async pop(e){return this.upload(e)}async render(e){return this.upload(e)}}class Ni{constructor(e,t){this.http=t,this.uploadModule=new Ri(e);const n=e=>this.uploadModule.upload(e);n.attach=(e,t)=>this.uploadModule.attach(e,t),n.close=()=>this.uploadModule.close(),n.pop=e=>this.uploadModule.pop(e),n.render=e=>this.uploadModule.render(e),this.upload=n}async create(e){this.validateCreateOptions(e);const t=await this.http.post(Be`/v1/vaults`,{name:e.name});return{id:t.data.vault_id,name:t.data.name,vmk:t.data.vmk,createdAt:t.data.created_at}}async unseal(e,t){const n=Me(e,"vaultId");if("string"!=typeof t||!t.trim())throw new M("A VMK or DVAK token is required");const i=await this.http.post(Be`/v1/vaults/${n}/unseal`,function(e,t){const n="string"==typeof e?e.trim():"";if(!n)throw new TypeError("unsealRequestBody requires a non-empty key");const i=n.startsWith("dvak_")?"dvak_token":"vmk";return void 0===t?{[i]:n}:{[i]:n,ttl_seconds:t}}(t));if(!i.data.vat)throw new M("Unseal response did not include a vault access token");return{id:i.data.vault_id,vatToken:i.data.vat,issuedAt:i.data.issued_at,expiresAt:i.data.expires_at,ttlSeconds:i.data.ttl_seconds}}async list(e={}){const t=await this.http.get(Be`/v1/vaults`,{query:{limit:e.limit,cursor:e.cursor}});return{vaults:t.data.vaults.map(e=>({id:e.vault_id,name:e.name,createdAt:e.created_at,ingotCount:e.ingot_count,storageBytes:e.storage_bytes,...Oi(e)})),nextCursor:t.data.next_cursor}}async get(e){const t=Me(e,"vaultId");return zi((await this.http.get(Be`/v1/vaults/${t}`)).data)}async update(e,t){const n=Me(e,"vaultId");if(!t.name?.trim())throw new M("Vault name is required");const i=(await this.http.put(Be`/v1/vaults/${n}`,{name:t.name})).data;return{id:i.vault_id,name:i.name,description:i.description??null,updatedAt:i.updated_at}}async seal(e){const t=Me(e,"vaultId");await this.http.post(Be`/v1/vaults/${t}/seal`)}async delete(e,t){const n=Me(e,"vaultId");if(!t)throw new M("Vault name is required to confirm deletion");const i=(await this.http.delete(Be`/v1/vaults/${n}`,{headers:{"X-Confirm-Name-B64":_e(t),"X-Vault-Deletion-Mode":"schedule"}})).data;return{id:i.vault_id,status:i.status,deletionRequestedAt:i.deletion_requested_at,deletionScheduledFor:i.deletion_scheduled_for,deletionRequestedBy:i.deletion_requested_by,deletionScheduleId:i.deletion_schedule_id}}async cancelDeletion(e,t){const n=Me(e,"vaultId");if(!t?.trim())throw new M("Deletion schedule is required to cancel deletion");return zi((await this.http.post(Be`/v1/vaults/${n}/deletion/cancel`,{deletion_schedule_id:t})).data)}async getSharingConfig(e){const t=Me(e,"vaultId");return Di((await this.http.get(Be`/v1/vaults/${t}/sharing`)).data)}async enableSharing(e,t,n={}){const i=Me(e,"vaultId");if(!t)throw new M("VMK is required");return Di((await this.http.post(Be`/v1/vaults/${i}/sharing/enable`,{vmk:t,all_ingots_public:n.allIngotsPublic,session_length_seconds:n.sessionLengthSeconds})).data)}async disableSharing(e){const t=Me(e,"vaultId");return Di((await this.http.post(Be`/v1/vaults/${t}/sharing/disable`)).data)}async updateSharingConfig(e,t,n){const i=Me(e,"vaultId");return Di((await this.http.put(Be`/v1/vaults/${i}/sharing`,{all_ingots_public:t.allIngotsPublic,session_length_seconds:t.sessionLengthSeconds},{vat:n?.vatToken})).data)}async getAccessLogRetention(e){const t=Me(e,"vaultId"),n=await this.http.get(Be`/v1/vaults/${t}/access-log-retention`);return{vaultId:n.data.vault_id,retentionSeconds:n.data.access_log_retention_seconds}}async updateAccessLogRetention(e,t){const n=Me(e,"vaultId"),i=await this.http.put(Be`/v1/vaults/${n}/access-log-retention`,{access_log_retention_seconds:t});return{vaultId:i.data.vault_id,retentionSeconds:i.data.access_log_retention_seconds}}async getUploadConfig(e){const t=Me(e,"vaultId");return Ui((await this.http.get(Be`/v1/vaults/${t}/upload`)).data)}async enableUploadPortal(e,t){return this.toggleUploadChannel(e,"portal","enable",t)}async disableUploadPortal(e){return this.toggleUploadChannel(e,"portal","disable")}async enableUploadWidget(e,t){return this.toggleUploadChannel(e,"widget","enable",t)}async disableUploadWidget(e){return this.toggleUploadChannel(e,"widget","disable")}async updateUploadConfig(e,t){const n=Me(e,"vaultId"),i={};void 0!==t.maxSizeBytes&&(i.max_size_bytes=t.maxSizeBytes),void 0!==t.notificationEmail&&(i.notification_email=t.notificationEmail);return Ui((await this.http.put(Be`/v1/vaults/${n}/upload`,i)).data)}async toggleUploadChannel(e,t,n,i){const s=Me(e,"vaultId");if("enable"===n&&!i)throw new M("VMK is required");return Ui((await this.http.post(Be`/v1/vaults/${s}/upload/${t}/${n}`,"enable"===n?{vmk:i}:void 0)).data)}validateCreateOptions(e){if(!e.name?.trim())throw new M("Vault name is required")}}function Oi(e){return{status:e.status,deletionRequestedAt:e.deletion_requested_at,deletionScheduledFor:e.deletion_scheduled_for,deletionRequestedBy:e.deletion_requested_by,deletionScheduleId:e.deletion_schedule_id}}function zi(e){return{id:e.vault_id,name:e.name,description:e.description??null,...Oi(e),ingotCount:e.ingot_count??0,storageBytes:e.storage_bytes??0,createdAt:e.created_at,lastUnsealedAt:e.last_unsealed_at??null,unsealCount:e.unseal_count??0}}function Di(e){return{vaultId:e.vault_id,publicSharingEnabled:e.public_sharing_enabled,allIngotsPublic:e.all_ingots_public,sessionLengthSeconds:e.session_length_seconds??null,enabledAt:e.enabled_at??null}}function Ui(e){return{vaultId:e.vault_id,uploadPortalEnabled:e.upload_portal_enabled,uploadPortalEnabledAt:e.upload_portal_enabled_at??null,uploadWidgetEnabled:e.upload_widget_enabled,uploadWidgetEnabledAt:e.upload_widget_enabled_at??null,maxSizeBytes:e.max_size_bytes??null,notificationEmail:e.notification_email??null,portalUrl:e.portal_url}}const Hi=new Map([["ingot_downloaded","download"]]),Fi=Object.freeze([...Hi.keys()]);function Vi(e){const t=Hi.get(e.event_type);return void 0===t?null:{timestamp:e.timestamp,action:t,identity:e.actor_display||e.metadata?.identity||e.actor_id||"Unknown",ip_address:e.ip_address??"",user_agent:e.user_agent??""}}let ji=!1;function qi(e){ji=e,e&&Wi("info","Debug mode enabled")}function Wi(e,t,...n){const i=`[SparkVault] ${(new Date).toISOString().split("T")[1].slice(0,-1)} ${t}`;switch(e){case"debug":ji&&console.debug(i,...n);break;case"info":ji&&console.log(i,...n);break;case"warn":ji&&console.warn(i,...n);break;case"error":console.error(i,...n)}}const Ki={debug:(e,...t)=>Wi("debug",e,...t),info:(e,...t)=>Wi("info",e,...t),warn:(e,...t)=>Wi("warn",e,...t),error:(e,...t)=>Wi("error",e,...t)},Gi=6e4,Yi=3e5;function Xi(e,t,n,i){return new Promise((s,o)=>{const r=setTimeout(()=>{n.abort(),o(new z(i))},t);e.then(e=>{clearTimeout(r),s(e)},e=>{clearTimeout(r),o(e)})})}function Ji(e,t=re){const n=Gn(e,{operation:"decrypt",isAllowedHost:t});if(!n.ok)throw new M("Invalid download URL",{reason:n.reason})}const Qi=u({status:0}),Zi={verdict:a.REFUSED,retryAfterMs:null,offset:null,coreCode:null},es=/^bytes (\d+)-(\d+)\/(\d+)$/,ts=/^"[^"]*"$/,ns="The file changed while it was downloading. Please try again.";async function is(e,t){const{signal:n,remint:i}=t,s={received:new ps,budget:T(),held:null,furthest:0},o=S("download");for(let r=e;;){const e=await ss(r,s,t);if(e.ok)return e.download;if(n?.aborted)throw n.reason;const{error:l,outcome:d}=e;if(!i||d.verdict!==a.RETRY||!s.budget.failed(a.RETRY,d.retryAfterMs))throw l;await hs(E({attempt:s.budget.attempt,retryAfterMs:d.retryAfterMs,jitterKey:o}),n),r=i}}async function ss(e,t,n){let i;try{i=await e(),Ji(i,n.isAllowedHost)}catch(e){if(!(e instanceof I)||"number"!=typeof e.statusCode)return{ok:!1,error:e,outcome:Qi};const t=function(e,t){const n=e.code===o?{coreCode:e.code}:null;return{...u({status:t,details:n}),retryAfterMs:e.retryAfterMs}}(e,e.statusCode);return{ok:!1,error:null===t.coreCode?e:os(e,t.coreCode),outcome:t}}return async function(e,t,n){const{signal:i,onProgress:s,expectedContentVersion:o}=n,{received:r}=t,a=function(e){const{held:t,received:n}=e;return null===t||null===t.validator||0===n.loaded?null:{held:t,validator:t.validator,at:n.loaded}}(t);a||r.discard();const l=new AbortController,d=()=>l.abort(i?.reason);i?.aborted?d():i?.addEventListener("abort",d,{once:!0});const c=e=>({ok:!0,download:{blob:r.toBlob(e.contentType),contentVersion:e.contentVersion}});let h=null,p=!1;try{const n=await Xi(fetch(e,a?{signal:l.signal,headers:{Range:`bytes=${a.at}-`,"If-Range":a.validator}}:{signal:l.signal}),3e4,l,"Download timed out waiting for response headers");if(!n.ok){const e=u({status:n.status,headers:e=>n.headers.get(e)});return{ok:!1,error:await rs(n,e,l),outcome:e}}if(a&&206===n.status){const e=function(e,t){const n=e.headers.get("etag");if(null!==n&&n.replace(/^W\//,"")!==t.validator)return new I(ns,"content_changed");const i=es.exec(e.headers.get("content-range")??""),[s,o,r]=i?i.slice(1).map(Number):[NaN,NaN,NaN],{total:a}=t.held;if(s!==t.at||o!==r-1||a>0&&r!==a)return new I("The resumed download did not continue where it stopped","download_failed",e.status,{reason:"range_mismatch"});return{...t.held,total:r}}(n,a);if(e instanceof I)return{ok:!1,error:e,outcome:Zi};h=e}else{r.discard();const e=n.headers.get("x-content-version")||null;if(o&&e&&e!==o)return{ok:!1,error:new I(ns,"content_changed"),outcome:Zi};h={contentType:n.headers.get("content-type")??"",contentVersion:e,total:Number(n.headers.get("content-length"))||0,validator:ls(n.headers)}}return t.held=h,await async function(e,t,n,i,s){const{received:o}=n;if(!e.body)return o.appendBlob(await Xi(e.blob(),Yi,t,"Download timed out")),us(n),void cs(s,o.loaded,i);const r=e.body.getReader();for(;;){const{done:e,value:a}=await Xi(r.read(),Gi,t,"Download stalled: no data received");if(e)return;o.append(a),us(n),cs(s,o.loaded,i)}}(n,l,t,h.total,s),h.total>0&&r.loaded!==h.total?(r.loaded>h.total&&r.discard(),{ok:!1,error:as(r.loaded,h.total),outcome:Qi}):(p=!0,c(h))}catch(e){return e instanceof ds?{ok:!1,error:e.failure,outcome:Zi}:null!==h&&h.total>0&&r.loaded===h.total&&!i?.aborted?c(h):{ok:!1,error:e,outcome:Qi}}finally{p||l.abort(),i?.removeEventListener("abort",d)}}(i,t,n)}function os(e,t){return new I(e.message,e.code,e.statusCode,{...e.details,coreCode:t},e.retryAfterMs)}async function rs(e,t,n){const i=`Download failed with status ${e.status}`,{coreCode:s}=t;if(t.verdict!==a.REFUSED||null===s)return new I(i,"download_failed",e.status);const o=await Xi(K(e),Gi,n,"Download timed out reading the refusal"),r=o.code===s?o.message:i;return new I(r,"download_failed",e.status,{coreCode:s})}function as(e,t){return new I(`The download ended after ${e} of ${t} bytes`,"download_failed",void 0,{reason:"length_mismatch",received:e,total:t})}function ls(e){const t=e.get("etag"),n=(e.get("accept-ranges")??"").split(",").some(e=>"bytes"===e.trim().toLowerCase());return null!==t&&ts.test(t)&&n?t:null}class ds extends Error{constructor(e){super("onProgress threw"),this.failure=e}}function cs(e,t,n){if(e)try{e(t,n)}catch(e){throw new ds(e)}}function us(e){e.received.loaded>e.furthest?(e.furthest=e.received.loaded,e.budget.progressed()):e.budget.alive()}function hs(e,t){return new Promise((n,i)=>{if(t?.aborted)return void i(t.reason);const s=()=>{clearTimeout(o),i(t?.reason)},o=setTimeout(()=>{t?.removeEventListener("abort",s),n()},e);t?.addEventListener("abort",s,{once:!0})})}class ps{constructor(){this.parts=[],this.pending=[],this.pendingBytes=0,this.count=0}get loaded(){return this.count}append(e){this.pending.push(e),this.pendingBytes+=e.byteLength,this.count+=e.byteLength,this.pendingBytes>=8388608&&this.fold()}appendBlob(e){this.fold(),this.parts.push(e),this.count+=e.size}discard(){this.parts=[],this.pending=[],this.pendingBytes=0,this.count=0}toBlob(e){return this.fold(),new Blob(this.parts,{type:e})}fold(){0!==this.pending.length&&(this.parts.push(new Blob(this.pending)),this.pending=[],this.pendingBytes=0)}}class ms{constructor(e){this.http=e}async list(e,t={}){const n=Pe(e),i=await this.http.get(Be`/v1/vaults/${n}/folders`,{vat:e.vatToken,query:{limit:t.limit,page_token:t.pageToken}});return{folders:(i.data.folders??[]).map(fs),nextPageToken:i.data.next_page_token??null}}async findByPath(e,t){const n=Pe(e);if("string"!=typeof t||""===t.trim())throw new M("path must be a non-empty string",{field:"path"});const i=await this.http.get(Be`/v1/vaults/${n}/folders`,{vat:e.vatToken,query:{path:t}}),s=i.data?.folders;if(!Array.isArray(s)||s.length>1)throw new I("A folder path lookup answered neither one folder nor none","invalid_response",void 0,{count:Array.isArray(s)?s.length:null});return 1===s.length?fs(s[0]):null}async get(e,t){const n=Pe(e),i=Me(t,"folderId");return fs((await this.http.get(Be`/v1/vaults/${n}/folders/${i}`,{vat:e.vatToken})).data)}async getBreadcrumb(e,t){const n=Pe(e),i=Me(t,"folderId");return((await this.http.get(Be`/v1/vaults/${n}/folders/${i}`,{vat:e.vatToken})).data.breadcrumb??[]).map(e=>({id:e.folder_id,name:e.name}))}async create(e,t){if(!t.name?.trim())throw new M("Folder name is required");const n=Pe(e);return fs((await this.http.post(Be`/v1/vaults/${n}/folders`,{name:t.name,parent_id:t.parentId??null},{vat:e.vatToken})).data)}async update(e,t,n){const i=Pe(e),s=Me(t,"folderId"),o={};void 0!==n.name&&(o.name=n.name),void 0!==n.parentId&&(o.parent_id=n.parentId),void 0!==n.pinned&&(o.pinned=n.pinned);return fs((await this.http.put(Be`/v1/vaults/${i}/folders/${s}`,o,{vat:e.vatToken})).data)}move(e,t,n){return this.update(e,t,{parentId:n})}togglePin(e,t,n){return this.update(e,t,{pinned:n})}async delete(e,t){const n=Pe(e),i=Me(t,"folderId");await this.http.delete(Be`/v1/vaults/${n}/folders/${i}`,{vat:e.vatToken})}async moveIngot(e,t,n){const i=Pe(e),s=Me(t,"ingotId");await this.http.patch(Be`/v1/vaults/${i}/ingots/${s}`,{folder_id:n},{vat:e.vatToken})}}function fs(e){return{id:e.folder_id,name:e.name,parentId:e.parent_id??null,pinned:e.pinned??!1,createdAt:e.created_at??0,updatedAt:e.updated_at??0}}class vs{constructor(e,t){this.allowsTransferHost=e=>ce(this.config,e),this.config=e,this.http=t}async createUpload(e){if(!e.name?.trim())throw new M("Ingot name is required");if(!Number.isFinite(e.sizeBytes)||e.sizeBytes<1)throw new M("sizeBytes must be a positive number");if(e.folder&&e.folderId)throw new M("Provide folder or folderId, not both");const t=await this.requestUploadSession(e.vault,{name:e.name,content_type:e.contentType,size_bytes:e.sizeBytes,contentHmac:e.contentHmac,folder:e.folder,folderId:e.folderId,onNameConflict:e.onNameConflict});return{...gs(t),name:t.name,contentType:t.content_type,size:t.size_bytes,uploadUrl:t.forge_url,expiresAt:t.expires_at}}async endUpload(e,n){const i=Pe(e),s=Me(n.id,"ingotId"),o=function({created:e,uploadId:n}){return!0===e&&"string"==typeof n&&t.test(n)?n:null}(n);if(null===o)return"kept";try{return await this.http.delete(Be`/v1/vaults/${i}/ingots/${s}`,{vat:e.vatToken,query:{upload_id:o}}),"deleted"}catch(e){if(e instanceof I&&404===e.statusCode)return"deleted";if(e instanceof I&&412===e.statusCode)return"kept";throw e}}async sendUpload(e,t,n={}){this.validateFile(t);const{onProgress:i,onSessionCreated:s}=n;await this.runTransfer(n.signal,n=>n.uploadFileToForge(t,e,i,s&&(e=>s({sessionUrl:e}))))}async resumeUpload(e,t,n={}){this.validateFile(t);const{onProgress:i}=n;await this.runTransfer(n.signal,n=>n.resumeUploadToForge(t,e.sessionUrl,i))}async runTransfer(e,t){if(e?.aborted)throw new Zn("Upload cancelled","cancelled",0);const n=new ki(this.config),i=()=>n.abort();e?.addEventListener("abort",i,{once:!0});try{await t(n)}finally{e?.removeEventListener("abort",i)}}async upload(e,t){if(this.validateFile(t.file),t.folder&&t.folderId)throw new M("Provide folder or folderId, not both");const n=t.name??ys(t.file);li();const i=await this.requestUploadSession(e,{name:n,content_type:bs(t),size_bytes:t.file.size,contentHmac:t.contentHmac,folder:t.folder,folderId:t.folderId,onNameConflict:t.onNameConflict});try{return await this.transferAndFinalize(i,i.created,t.file,t.onProgress)}catch(t){throw pi(t)||this.endGivenUp(e,gs(i)),t}}endGivenUp(e,t){this.endUpload(e,t).catch(e=>{Ki.warn("A given-up upload could not be ended with its file; the server expires it",{ingotId:t.id,code:e instanceof I?e.code:void 0})})}async replace(e,t,n){this.validateFile(n.file);const i=Pe(e),s=Me(t,"ingotId"),o=n.name??ys(n.file),r=bs(n);li();const a=await this.http.put(Be`/v1/vaults/${i}/ingots/${s}`,{name:o,...void 0!==r&&{content_type:r},size_bytes:n.file.size,...n.contentHmac&&{content_hmac:n.contentHmac}},{vat:e.vatToken}).catch(e=>{throw ri(e)});if(!a.data.forge_url)throw new M("Replace endpoint did not return a Forge upload URL");return this.transferAndFinalize(a.data,!1,n.file,n.onProgress)}async rename(e,t,n){if(!n?.trim())throw new M("Ingot name is required");const i=Pe(e),s=Me(t,"ingotId");return ws((await this.http.patch(Be`/v1/vaults/${i}/ingots/${s}`,{name:n},{vat:e.vatToken})).data)}async move(e,t,n){const i=Pe(e),s=Me(t,"ingotId");return ws((await this.http.patch(Be`/v1/vaults/${i}/ingots/${s}`,{folder_id:n},{vat:e.vatToken})).data)}async delete(e,t){const n=Pe(e),i=Me(t,"ingotId");await this.http.delete(Be`/v1/vaults/${n}/ingots/${i}`,{vat:e.vatToken})}async get(e,t){const n=Pe(e),i=Me(t,"ingotId");return ws((await this.http.get(Be`/v1/vaults/${n}/ingots/${i}`,{vat:e.vatToken})).data)}async list(e,t={}){const n=Pe(e);return ks((await this.http.get(Be`/v1/vaults/${n}/ingots`,{vat:e.vatToken,query:{limit:t.limit,cursor:t.cursor,sort_by:t.sortBy,sort_order:t.sortOrder}})).data)}async search(e,t={}){const n=Pe(e);return ks((await this.http.get(Be`/v1/vaults/${n}/ingots/search`,{vat:e.vatToken,query:{q:t.q,file_type:t.fileType,folder_id:t.folderId,min_size:t.minSize,max_size:t.maxSize,limit:t.limit,cursor:t.cursor,sort_order:t.sortOrder}})).data)}async listContents(e,t={}){const n=Pe(e),i=await this.http.get(Be`/v1/vaults/${n}/contents`,{vat:e.vatToken,query:{folder_id:t.folderId,limit:t.limit,page_token:t.pageToken,sort_order:t.sortOrder}});return{folder:(s=i.data).folder?{id:s.folder.folder_id,name:s.folder.name,parentId:s.folder.parent_id??null}:null,breadcrumb:(s.breadcrumb??[]).map(e=>({id:e.folder_id,name:e.name})),folders:(s.folders??[]).map(fs),ingots:(s.ingots??[]).map(ws),nextPageToken:s.next_page_token??null};var s}async createDownloadLink(e,t){const n=Pe(e),i=Me(t,"ingotId"),s=await this.http.post(Be`/v1/vaults/${n}/ingots/${i}/download`,void 0,{vat:e.vatToken});if(!s.data.download_url)throw new M("Download endpoint did not return a download URL");return Ji(s.data.download_url,this.allowsTransferHost),{downloadUrl:s.data.download_url,contentVersion:s.data.content_version??null,id:s.data.ingot_id,name:s.data.name,size:s.data.size_bytes,contentType:s.data.content_type}}async download(e,t){return(await function(e,t={}){return is(e,{...t,remint:e})}(async()=>(await this.createDownloadLink(e,t)).downloadUrl,{isAllowedHost:this.allowsTransferHost})).blob}async getSharingConfig(e,t){const n=Pe(e),i=Me(t,"ingotId");return xs((await this.http.get(Be`/v1/vaults/${n}/ingots/${i}/sharing`,{vat:e.vatToken})).data)}async updateSharingConfig(e,t,n){const i=Pe(e),s=Me(t,"ingotId");return xs((await this.http.put(Be`/v1/vaults/${i}/ingots/${s}/sharing`,{shared:n.shared,visibility:n.visibility},{vat:e.vatToken})).data)}async addInvite(e,t,n){if(!n?.trim())throw new M("Invite identity is required");const i=Pe(e),s=Me(t,"ingotId"),o=await this.http.post(Be`/v1/vaults/${i}/ingots/${s}/sharing/invite`,{identity:n},{vat:e.vatToken});return{...Cs(r=o.data),shareUrl:r.share_url,delivered:r.delivered};var r}async revokeInvite(e,t,n){const i=Pe(e),s=Me(t,"ingotId"),o=Me(n,"inviteId");await this.http.delete(Be`/v1/vaults/${i}/ingots/${s}/sharing/invite/${o}`,{vat:e.vatToken})}async checkContentHmacs(e,t){const n=Pe(e);return(await this.http.post(Be`/v1/vaults/${n}/ingots/hash-check`,{hashes:t},{vat:e.vatToken})).data}async getAccessLogs(e,t,n={}){const i=Pe(e),s=Me(t,"ingotId"),o=await this.http.get(Be`/v1/vaults/${i}/ingots/${s}/audit-logs`,{vat:e.vatToken,query:{limit:n.limit,cursor:n.cursor,event_types:Fi.join(",")}}),r=[];for(const e of o.data.entries??[]){const t=Vi(e);t&&r.push({id:String(t.timestamp),action:t.action,identity:t.identity,ipAddress:t.ip_address,userAgent:t.user_agent,timestamp:t.timestamp})}return{logs:r,nextCursor:o.data.next_cursor}}async requestUploadSession(e,t){const n={name:t.name,...void 0!==t.content_type&&{content_type:t.content_type},size_bytes:t.size_bytes};t.folder?n.folder_path=t.folder:t.folderId&&(n.folder_id=t.folderId),t.contentHmac&&(n.content_hmac=t.contentHmac),t.onNameConflict&&(n.on_name_conflict=t.onNameConflict);const i=Pe(e),s=await this.http.post(Be`/v1/vaults/${i}/ingots`,n,{vat:e.vatToken}).catch(e=>{throw ri(e)});if(!s.data.forge_url)throw this.endGivenUp(e,gs(s.data)),new M("Upload endpoint did not return a Forge upload URL");return s.data}async transferAndFinalize(e,t,n,i){return await this.sendUpload(e.forge_url,n,{onProgress:i}),{id:e.ingot_id,name:e.name,contentType:e.content_type,size:e.size_bytes,created:t}}validateFile(e){if(!e)throw new M("File is required");if(0===e.size)throw new M("File cannot be empty")}}function gs(e){return{id:e.ingot_id,created:e.created,uploadId:e.upload_id??null}}function ys(e){return"undefined"!=typeof File&&e instanceof File&&e.name?e.name:"unnamed"}function bs(e){return e.contentType??(e.file.type||void 0)}function ws(e){return{id:e.ingot_id,name:e.name,downloadFilename:e.download_filename,contentType:e.content_type,size:e.size_bytes,status:e.status??"active",createdAt:e.created_at??0,folderId:e.folder_id??null,contentHmac:e.content_hmac??null,contentVersion:e.content_version??null}}function ks(e){return{ingots:(e.ingots??[]).map(ws),nextCursor:e.next_cursor}}function xs(e){return{shared:e.shared,visibility:e.visibility??void 0,publicUrl:e.public_url,linkCode:e.link_code,sharingEnabled:e.sharing_enabled,vaultAllIngotsPublic:e.vault_all_ingots_public,sessionLengthSeconds:e.session_length_seconds,invites:e.invites?.map(Cs)}}function Cs(e){return{id:e.invite_id,identity:e.identity,identityType:e.identity_type,invitedAt:e.created_at}}class Ss{constructor(e){this.http=e}async list(e={}){const t=await this.http.get(Be`/v1/sparks`,{query:{kindling:e.kindling,status:e.status,limit:e.limit,cursor:e.cursor}});return{sparks:(t.data.sparks??[]).map(Es),nextCursor:t.data.next_cursor}}async get(e){const t=Me(e,"sparkId"),n=(await this.http.get(Be`/v1/sparks/${t}`)).data;return{id:n.spark_id,payload:n.payload,contentType:n.content_type??"text/plain",size:n.size_bytes,status:n.status,createdAt:n.created_at,burnedAt:n.burned_at,filename:n.filename,downloadFilename:n.download_filename}}async create(e){if("string"!=typeof e.payload||0===e.payload.length)throw new M("Spark payload is required");const t={payload:e.payload,content_type:e.contentType,ttl_minutes:e.ttlMinutes,kindling:e.kindling,filename:e.filename};e.withKindling&&(t.with_kindling=!0);const n=(await this.http.post(Be`/v1/sparks`,t)).data;return{id:n.spark_id,size:n.size_bytes,status:n.status,createdAt:n.created_at,expiresAt:n.expires_at,ttlMinutes:n.ttl_minutes,filename:n.filename,kindling:n.kindling,linkUrl:n.link_url,linkCode:n.link_code}}async delete(e){const t=Me(e,"sparkId");await this.http.delete(Be`/v1/sparks/${t}`)}async share(e,t={}){const n=Me(e,"sparkId");return _s((await this.http.patch(Be`/v1/sparks/${n}/share`,{visibility:t.visibility,invites:t.invites,expires_in_seconds:t.expiresInSeconds})).data)}async resendInvite(e){const t=Me(e,"sparkId"),n=(await this.http.post(Be`/v1/sparks/${t}/share/resend`)).data;return{sparkId:n.spark_id,identity:n.identity,identityType:n.identity_type,sentAt:n.sent_at}}async getShare(e){const t=Me(e,"sparkId");return _s((await this.http.get(Be`/v1/sparks/${t}/share`)).data)}async unshare(e){const t=Me(e,"sparkId");return _s((await this.http.delete(Be`/v1/sparks/${t}/share`)).data)}}function Es(e){return{id:e.spark_id,contentType:e.content_type??"text/plain",size:e.size_bytes,status:e.status,createdAt:e.created_at,expiresAt:e.expires_at,burnedAt:e.burned_at??null,timeRemaining:e.time_remaining??0,filename:e.filename,kindling:e.kindling,linkUrl:e.link_url}}function _s(e){return{shared:e.shared,shareUrl:e.share_url,linkCode:e.link_code,visibility:e.visibility,invites:e.invites,expiresAt:e.expires_at,createdAt:e.created_at,deliveredTo:e.delivered_to}}class Ts{constructor(e){this.http=e}async generate(e){const t=e.format??"hex";!function(e,t){if(!function(e){return Te.includes(e)}(t))throw new M(`Entropy format must be one of: ${Te.join(", ")}`,{field:"format",received:t});const n=function(e){return Ie.includes(e)?512:Ae}(t);if(!Number.isInteger(e)||e<1||e>n)throw new M(`Entropy byte count must be an integer from 1 to ${n} for the ${t} format`,{field:"bytes",received:e})}(e.bytes,t);const n=(await this.http.post(Be`/v1/entropy/generate`,{num_bytes:e.bytes,format:t})).data;return{value:n.value,numBytes:n.num_bytes,format:n.format,referenceId:n.reference_id}}async generateBytes(e){const t=await this.generate({bytes:e,format:"base64url"});if("string"!=typeof t.value||0===t.value.length)throw new I("Entropy endpoint returned no value","invalid_response");const n=Ee(t.value);if(null===n)throw new I("Entropy endpoint returned a value that is not base64url","invalid_response");if(n.length!==e)throw new I(`Entropy length mismatch: expected ${e}, got ${n.length}`,"invalid_response");return n}}const As=In,Is=$n;function $s(e,t){const n=e.options?.applicationServerKey;if(!n)return!1;const i=new Uint8Array(n);return i.length===t.length&&i.every((e,n)=>e===t[n])}class Ls{constructor(e){this.http=e}async getInbox(e={}){return(await this.http.get(Be`/v1/me/notifications`,{query:{state:e.state,limit:e.limit||void 0,cursor:e.cursor}})).data}async getUnreadCount(){return(await this.http.get(Be`/v1/me/notifications/unread-count`)).data}async markState(e,t){const n=Me(e,"notificationId");if(!Number.isFinite(t?.createdAt))throw new M("createdAt (the row's created_at) is required",{field:"createdAt",received:t?.createdAt});if(!As.includes(t.state))throw new M(`state must be one of ${As.join(", ")}`,{field:"state",received:t.state});return(await this.http.post(Be`/v1/me/notifications/${n}/state`,{created_at:t.createdAt,state:t.state})).data}async markAllState(e){if(!Is.includes(e?.state))throw new M(`state must be one of ${Is.join(", ")}`,{field:"state",received:e?.state});if(void 0!==e.cursor&&"string"!=typeof e.cursor)throw new M("cursor must be the string cursor from a prior response",{field:"cursor",received:e.cursor});const t={state:e.state};e.cursor&&(t.cursor=e.cursor);return(await this.http.post(Be`/v1/me/notifications/state`,t)).data}async markAllRead(){let e,t=0;for(let n=0;n<100;n+=1){const n=await this.markAllState(e?{state:"read",cursor:e}:{state:"read"});if(t+=n?.updated??0,!n?.cursor)return{updated:t,complete:!0};e=n.cursor}return{updated:t,complete:!1}}isWebPushSupported(){return"undefined"!=typeof window&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window}async getWebPushKey(){return(await this.http.get(Be`/v1/me/notifications/web-push/key`)).data}async serverKey(){const e=await this.getWebPushKey();if(!e.configured||!e.vapid_public_key)return null;const t=Ee(e.vapid_public_key);if(null===t)throw new I("The server returned a Web Push key that is not base64url","invalid_response");return t}async getWebPushStatus(e={}){if(!this.isWebPushSupported())return{status:"not_supported"};const t=await this.serverKey();if(null===t)return{status:"not_configured"};const n=e.serviceWorkerRegistration?await e.serviceWorkerRegistration.pushManager.getSubscription():null;return n&&$s(n,t)?{status:"subscribed",subscription:n}:{status:"not_subscribed"}}async registerWebPushSubscription(e){const t=function(e){const t="function"==typeof e.toJSON?e.toJSON():e,n=t.endpoint,i=t.keys?.p256dh,s=t.keys?.auth;if(!n||!i||!s)throw new M("A web push subscription requires endpoint and keys.p256dh/auth");return{endpoint:n,keys:{p256dh:i,auth:s}}}(e);return(await this.http.post(Be`/v1/me/notifications/web-push`,t)).data}async unsubscribeWebPushEndpoint(e){if(!e||"string"!=typeof e)throw new M("endpoint is required");return(await this.http.post(Be`/v1/me/notifications/web-push/unsubscribe`,{endpoint:e})).data}async subscribeWebPush(e){if(!this.isWebPushSupported())return{status:"not_supported"};const t=e?.serviceWorkerRegistration;if(!t||"function"!=typeof t.pushManager?.subscribe)throw new M("serviceWorkerRegistration with a pushManager is required");const n=await this.serverKey();if(null===n)return{status:"not_configured"};if("denied"===Notification.permission)return{status:"permission_denied"};if("default"===Notification.permission){if("granted"!==await Notification.requestPermission())return{status:"permission_denied"}}const i=await t.pushManager.getSubscription(),s=i&&$s(i,n)?i:null;i&&!s&&await this.dropDeadSubscription(i);const o=s??await t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:n});return await this.registerWebPushSubscription(o),{status:s?"already_subscribed":"subscribed",subscription:o}}async dropDeadSubscription(e){await this.unsubscribeWebPushEndpoint(e.endpoint),await e.unsubscribe()}async unsubscribeWebPush(e){const t=e?.serviceWorkerRegistration;if(!t||"function"!=typeof t.pushManager?.getSubscription)return!1;const n=await t.pushManager.getSubscription();return!!n&&(await this.unsubscribeWebPushEndpoint(n.endpoint).catch(()=>{}),n.unsubscribe())}}class Bs{constructor(e){!function(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(!J("account",e.accountId))throw new M("accountId must be a SparkVault account id (acc_...)",{field:"accountId",received:e.accountId})}(e),this.config=function(e){return{accountId:e.accountId,timeout:e.timeout??3e4,apiBaseUrl:le(e.apiBaseUrl??"https://api.sparkvault.com"),identityBaseUrl:de(e.identityBaseUrl??"https://auth.sparkvault.com"),portalBaseUrl:de(e.portalBaseUrl??ae),accessToken:e.accessToken,getAccessToken:e.getAccessToken,apiKey:e.apiKey,clientId:e.clientId,preloadConfig:e.preloadConfig??"undefined"!=typeof window,backdropBlur:!1!==e.backdropBlur,allowedDownloadHostPatterns:e.allowedDownloadHostPatterns??[...se]}}(e);const t=new ve(this.config);this.products=new Dn(this.config,t),this.vaults=new Ni(this.config,t),this.ingots=new vs(this.config,t),this.folders=new ms(t),this.sparks=new Ss(t),this.entropy=new Ts(t),this.notify=new Ls(t),this.health=new ge(this.config)}static init(e){return new Bs(e)}static isRecoveryPending(){return En()}static get version(){return"13.0.7"}}if("undefined"!=typeof window){const e=function(e){if("undefined"==typeof window||"undefined"==typeof document)return null;const t=document.currentScript;if(!t)return null;const n=t.dataset.accountId;if("true"===t.dataset.debug&&qi(!0),!n)return Ki.debug("No data-account-id attribute, skipping auto-init"),null;Ki.info("Auto-initializing SDK...");try{const t=e.init({accountId:n});return Ki.info("SDK initialized successfully"),t}catch(e){return Ki.error("Failed to initialize SDK:",e),null}}(Bs);window.SparkVault=e??Bs}e.AuthenticationError=$,e.AuthorizationError=B,e.EntropyModule=Ts,e.FoldersModule=ms,e.IdentityModule=Tn,e.IdentityProviderError=U,e.IngotsModule=vs,e.NAME_CONFLICT_POLICIES=["upsert","complete_pending","refuse","new_name"],e.NOTIFY_PRESETS=Pn,e.NetworkError=O,e.NotifyModule=Ls,e.NotifyProductModule=Nn,e.NotifySubscriptionRequiredError=N,e.PlanRequiredError=P,e.PopupBlockedError=H,e.ProductsModule=Dn,e.QuotaExceededError=R,e.SparkVault=Bs,e.SparkVaultError=I,e.SparksModule=Ss,e.TimeoutError=z,e.UnauthorizedError=L,e.UserCancelledError=D,e.ValidationError=M,e.VaultsModule=Ni,e.buildNotifyPresetSend=Rn,e.default=Bs,e.fetchDownload=function(e,t={}){return is(()=>Promise.resolve(e),t)},e.isReceivedUploadFailure=pi,e.logger=Ki,e.setDebugMode=qi,Object.defineProperty(e,"__esModule",{value:!0})});
2
2
  //# sourceMappingURL=sparkvault.js.map