@trymellon/js 1.5.0 → 1.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/angular.js CHANGED
@@ -1,3 +1,3 @@
1
1
  "use client";
2
- var Ze=Object.create;var re=Object.defineProperty;var Qe=Object.getOwnPropertyDescriptor;var xe=(e,r)=>(r=Symbol[e])?r:Symbol.for("Symbol."+e),j=e=>{throw TypeError(e)};var er=(e,r,t)=>r in e?re(e,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[r]=t;var Ce=(e,r)=>re(e,"name",{value:r,configurable:!0});var Pe=e=>[,,,Ze(e?.[xe("metadata")]??null)],ke=["class","method","getter","setter","accessor","field","value","get","set"],K=e=>e!==void 0&&typeof e!="function"?j("Function expected"):e,rr=(e,r,t,n,s)=>({kind:ke[e],name:r,metadata:n,addInitializer:i=>t._?j("Already initialized"):s.push(K(i||null))}),tr=(e,r)=>er(r,xe("metadata"),e[3]),De=(e,r,t,n)=>{for(var s=0,i=e[r>>1],a=i&&i.length;s<a;s++)r&1?i[s].call(t):n=i[s].call(t,n);return n},Me=(e,r,t,n,s,i)=>{var a,m,c,R,d,g=r&7,I=!!(r&8),_=!!(r&16),k=g>3?e.length+1:g?I?1:2:0,A=ke[g+5],F=g>3&&(e[k-1]=[]),Ae=e[k]||(e[k]=[]),E=g&&(!_&&!I&&(s=s.prototype),g<5&&(g>3||!_)&&Qe(g<4?s:{get[t](){return Oe(this,i)},set[t](T){return Se(this,i,T)}},t));g?_&&g<4&&Ce(i,(g>2?"set ":g>1?"get ":"")+t):Ce(s,t);for(var L=n.length-1;L>=0;L--)R=rr(g,t,c={},e[3],Ae),g&&(R.static=I,R.private=_,d=R.access={has:_?T=>nr(s,T):T=>t in T},g^3&&(d.get=_?T=>(g^1?Oe:sr)(T,s,g^4?i:E.get):T=>T[t]),g>2&&(d.set=_?(T,ee)=>Se(T,s,ee,g^4?i:E.set):(T,ee)=>T[t]=ee)),m=(0,n[L])(g?g<4?_?i:E[A]:g>4?void 0:{get:E.get,set:E.set}:s,R),c._=1,g^4||m===void 0?K(m)&&(g>4?F.unshift(m):g?_?i=m:E[A]=m:s=m):typeof m!="object"||m===null?j("Object expected"):(K(a=m.get)&&(E.get=a),K(a=m.set)&&(E.set=a),K(a=m.init)&&F.unshift(a));return g||tr(e,s),E&&re(s,t,E),_?g^4?i:E:s};var te=(e,r,t)=>r.has(e)||j("Cannot "+t),nr=(e,r)=>Object(r)!==r?j('Cannot use the "in" operator on this value'):e.has(r),Oe=(e,r,t)=>(te(e,r,"read from private field"),t?t.call(e):r.get(e));var Se=(e,r,t,n)=>(te(e,r,"write to private field"),n?n.call(e,t):r.set(e,t),t),sr=(e,r,t)=>(te(e,r,"access private method"),t);import{Injectable as Tr,InjectionToken as Ir,inject as Ar}from"@angular/core";var y=e=>({ok:!0,value:e}),l=e=>({ok:!1,error:e});var V=class e extends Error{code;details;isTryMellonError=!0;constructor(r,t,n){super(t),this.name="TryMellonError",this.code=r,this.details=n,Error.captureStackTrace&&Error.captureStackTrace(this,e)}},ir={NOT_SUPPORTED:"WebAuthn is not supported in this environment",USER_CANCELLED:"User cancelled the operation",PASSKEY_NOT_FOUND:"Passkey not found",SESSION_EXPIRED:"Session has expired",NETWORK_FAILURE:"Network request failed",INVALID_ARGUMENT:"Invalid argument provided",TIMEOUT:"Operation timed out",ABORTED:"Operation was aborted",ABORT_ERROR:"Operation aborted by user or timeout",CHALLENGE_MISMATCH:"This link was already used or expired. Please try again from your computer.",UNKNOWN_ERROR:"An unknown error occurred"};function h(e,r,t){return new V(e,r??ir[e],t)}function ne(e){return e instanceof V||typeof e=="object"&&e!==null&&"isTryMellonError"in e&&e.isTryMellonError===!0}function q(){return h("NOT_SUPPORTED")}function b(e,r){return h("INVALID_ARGUMENT",`Invalid argument: ${e} - ${r}`,{field:e,reason:r})}function we(e){return h("UNKNOWN_ERROR",`Failed to ${e} credential`,{operation:e})}function se(e){return h("NOT_SUPPORTED",`No base64 ${e==="encode"?"encoding":"decoding"} available`,{type:e})}function ie(e,r){try{let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")throw b(r,"must use http or https protocol")}catch(t){throw ne(t)?t:b(r,"must be a valid URL")}}function D(e,r,t,n){if(!Number.isFinite(e))throw b(r,"must be a finite number");if(e<t||e>n)throw b(r,`must be between ${t} and ${n}`)}function W(e,r){if(typeof e!="string"||e.length===0)throw b(r,"must be a non-empty string");if(!/^[A-Za-z0-9_-]+$/.test(e))throw b(r,"must be a valid base64url string")}var or={NotAllowedError:"USER_CANCELLED",AbortError:"ABORTED",NotSupportedError:"NOT_SUPPORTED",SecurityError:"NOT_SUPPORTED",InvalidStateError:"UNKNOWN_ERROR",UnknownError:"UNKNOWN_ERROR"};function v(e){if(e instanceof DOMException){let r=e.name,t=e.message||"WebAuthn operation failed",n=or[r]??"UNKNOWN_ERROR";return h(n,t,{originalError:e})}return e instanceof Error?h("UNKNOWN_ERROR",e.message,{originalError:e}):h("UNKNOWN_ERROR","An unknown error occurred",{originalError:e})}function f(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function u(e){return typeof e=="string"}function x(e){return typeof e=="number"&&Number.isFinite(e)}function B(e){return typeof e=="boolean"}function w(e){return Array.isArray(e)}function o(e,r){return l(h("UNKNOWN_ERROR",e,{...r,originalData:r?.originalData}))}function p(e,r){return e[r]}function oe(e){if(!f(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id");if(!u(r))return o("Invalid API response: session_id must be string",{field:"session_id",originalData:e});let t=p(e,"challenge");if(!f(t))return o("Invalid API response: challenge must be object",{field:"challenge",originalData:e});let n=p(t,"rp");if(!f(n)||!u(n.name)||!u(n.id))return o("Invalid API response: challenge.rp must have name and id strings",{originalData:e});let s=p(t,"user");if(!f(s)||!u(s.id)||!u(s.name)||!u(s.displayName))return o("Invalid API response: challenge.user must have id, name, displayName strings",{originalData:e});let i=p(t,"challenge");if(!u(i))return o("Invalid API response: challenge.challenge must be string",{originalData:e});let a=p(t,"pubKeyCredParams");if(!w(a))return o("Invalid API response: challenge.pubKeyCredParams must be array",{originalData:e});for(let d of a)if(!f(d)||d.type!=="public-key"||!x(d.alg))return o("Invalid API response: pubKeyCredParams items must have type and alg",{originalData:e});let m=t.timeout;if(m!==void 0&&!x(m))return o("Invalid API response: challenge.timeout must be number",{originalData:e});let c=t.excludeCredentials;if(c!==void 0){if(!w(c))return o("Invalid API response: excludeCredentials must be array",{originalData:e});for(let d of c)if(!f(d)||d.type!=="public-key"||!u(d.id))return o("Invalid API response: excludeCredentials items must have id and type",{originalData:e})}let R=t.authenticatorSelection;return R!==void 0&&!f(R)?o("Invalid API response: authenticatorSelection must be object",{originalData:e}):y({session_id:r,challenge:{rp:n,user:s,challenge:i,pubKeyCredParams:a,...m!==void 0&&{timeout:m},...c!==void 0&&{excludeCredentials:c},...R!==void 0&&{authenticatorSelection:R}}})}function ae(e){if(!f(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id");if(!u(r))return o("Invalid API response: session_id must be string",{field:"session_id",originalData:e});let t=p(e,"challenge");if(!f(t))return o("Invalid API response: challenge must be object",{field:"challenge",originalData:e});let n=p(t,"challenge"),s=p(t,"rpId"),i=t.allowCredentials;if(!u(n))return o("Invalid API response: challenge.challenge must be string",{originalData:e});if(!u(s))return o("Invalid API response: challenge.rpId must be string",{originalData:e});if(i!==void 0&&!w(i))return o("Invalid API response: allowCredentials must be array",{originalData:e});if(i){for(let c of i)if(!f(c)||c.type!=="public-key"||!u(c.id))return o("Invalid API response: allowCredentials items must have id and type",{originalData:e})}let a=t.timeout;if(a!==void 0&&!x(a))return o("Invalid API response: challenge.timeout must be number",{originalData:e});let m=t.userVerification;return m!==void 0&&!["required","preferred","discouraged"].includes(String(m))?o("Invalid API response: userVerification must be required|preferred|discouraged",{originalData:e}):y({session_id:r,challenge:{challenge:n,rpId:s,allowCredentials:i??[],...a!==void 0&&{timeout:a},...m!==void 0&&{userVerification:m}}})}function le(e){if(!f(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"credential_id"),t=p(e,"status"),n=p(e,"session_token"),s=p(e,"user");if(!u(r))return o("Invalid API response: credential_id must be string",{field:"credential_id",originalData:e});if(!u(t))return o("Invalid API response: status must be string",{field:"status",originalData:e});if(!u(n))return o("Invalid API response: session_token must be string",{field:"session_token",originalData:e});if(!f(s))return o("Invalid API response: user must be object",{field:"user",originalData:e});let i=p(s,"user_id"),a=p(s,"external_user_id");if(!u(i)||!u(a))return o("Invalid API response: user must have user_id and external_user_id strings",{originalData:e});let m=s.email,c=s.metadata;return m!==void 0&&!u(m)?o("Invalid API response: user.email must be string",{originalData:e}):c!==void 0&&(typeof c!="object"||c===null)?o("Invalid API response: user.metadata must be object",{originalData:e}):y({credential_id:r,status:t,session_token:n,user:{user_id:i,external_user_id:a,...m!==void 0&&{email:m},...c!==void 0&&{metadata:c}}})}function ue(e){if(!f(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"authenticated"),t=p(e,"session_token"),n=p(e,"user"),s=p(e,"signals");if(!B(r))return o("Invalid API response: authenticated must be boolean",{field:"authenticated",originalData:e});if(!u(t))return o("Invalid API response: session_token must be string",{field:"session_token",originalData:e});if(!f(n))return o("Invalid API response: user must be object",{field:"user",originalData:e});let i=p(n,"user_id"),a=p(n,"external_user_id");return!u(i)||!u(a)?o("Invalid API response: user must have user_id and external_user_id strings",{originalData:e}):s!==void 0&&!f(s)?o("Invalid API response: signals must be object",{originalData:e}):y({authenticated:r,session_token:t,user:{user_id:i,external_user_id:a,...n.email!==void 0&&{email:n.email},...n.metadata!==void 0&&{metadata:n.metadata}},signals:s})}function pe(e){if(!f(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"valid"),t=p(e,"user_id"),n=p(e,"external_user_id"),s=p(e,"tenant_id"),i=p(e,"app_id");return B(r)?u(t)?u(n)?u(s)?u(i)?y({valid:r,user_id:t,external_user_id:n,tenant_id:s,app_id:i}):o("Invalid API response: app_id must be string",{field:"app_id",originalData:e}):o("Invalid API response: tenant_id must be string",{field:"tenant_id",originalData:e}):o("Invalid API response: external_user_id must be string",{field:"external_user_id",originalData:e}):o("Invalid API response: user_id must be string",{field:"user_id",originalData:e}):o("Invalid API response: valid must be boolean",{field:"valid",originalData:e})}function ce(e){if(!f(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"sessionToken");return u(r)?y({sessionToken:r}):o("Invalid API response: sessionToken must be string",{field:"sessionToken",originalData:e})}var ar=["pending_passkey","pending_data","completed"],lr=["pending_data","completed"];function de(e){if(!f(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id"),t=p(e,"onboarding_url"),n=p(e,"expires_in");return u(r)?u(t)?x(n)?y({session_id:r,onboarding_url:t,expires_in:n}):o("Invalid API response: expires_in must be number",{field:"expires_in",originalData:e}):o("Invalid API response: onboarding_url must be string",{field:"onboarding_url",originalData:e}):o("Invalid API response: session_id must be string",{field:"session_id",originalData:e})}function me(e){if(!f(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"status"),t=p(e,"onboarding_url"),n=p(e,"expires_in");return!u(r)||!ar.includes(r)?o("Invalid API response: status must be pending_passkey|pending_data|completed",{field:"status",originalData:e}):u(t)?x(n)?y({status:r,onboarding_url:t,expires_in:n}):o("Invalid API response: expires_in must be number",{originalData:e}):o("Invalid API response: onboarding_url must be string",{originalData:e})}function ge(e){if(!f(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id"),t=p(e,"status"),n=p(e,"onboarding_url");if(!u(r))return o("Invalid API response: session_id must be string",{field:"session_id",originalData:e});if(t!=="pending_passkey")return o("Invalid API response: status must be pending_passkey",{field:"status",originalData:e});if(!u(n))return o("Invalid API response: onboarding_url must be string",{originalData:e});let s=e.challenge,i;if(s!==void 0){let a=ur(s);if(!a.ok)return a;i=a.value}return y({session_id:r,status:"pending_passkey",onboarding_url:n,...i!==void 0&&{challenge:i}})}function ur(e){if(!f(e))return o("Invalid API response: challenge must be object",{originalData:e});let r=p(e,"rp"),t=p(e,"user"),n=p(e,"challenge"),s=p(e,"pubKeyCredParams");if(!f(r)||!u(r.name)||!u(r.id))return o("Invalid API response: challenge.rp must have name and id",{originalData:e});if(!f(t)||!u(t.id)||!u(t.name)||!u(t.displayName))return o("Invalid API response: challenge.user must have id, name, displayName",{originalData:e});if(!u(n))return o("Invalid API response: challenge.challenge must be string",{originalData:e});if(!w(s))return o("Invalid API response: challenge.pubKeyCredParams must be array",{originalData:e});for(let i of s)if(!f(i)||i.type!=="public-key"||!x(i.alg))return o("Invalid API response: pubKeyCredParams items must have type and alg",{originalData:e});return y({rp:r,user:t,challenge:n,pubKeyCredParams:s})}function ye(e){if(!f(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id"),t=p(e,"status"),n=p(e,"user_id"),s=p(e,"tenant_id");return u(r)?!u(t)||!lr.includes(t)?o("Invalid API response: status must be pending_data|completed",{originalData:e}):u(n)?u(s)?y({session_id:r,status:t,user_id:n,tenant_id:s}):o("Invalid API response: tenant_id must be string",{originalData:e}):o("Invalid API response: user_id must be string",{originalData:e}):o("Invalid API response: session_id must be string",{originalData:e})}function fe(e){if(!f(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id"),t=p(e,"status"),n=p(e,"user_id"),s=p(e,"tenant_id"),i=p(e,"session_token");return u(r)?t!=="completed"?o("Invalid API response: status must be completed",{originalData:e}):!u(n)||!u(s)||!u(i)?o("Invalid API response: user_id, tenant_id, session_token must be strings",{originalData:e}):y({session_id:r,status:"completed",user_id:n,tenant_id:s,session_token:i}):o("Invalid API response: session_id must be string",{originalData:e})}function pr(e){if(!e||typeof e!="object")return!1;let r=e;return typeof r.challenge=="string"&&r.rp!=null&&typeof r.rp=="object"&&r.user!=null&&typeof r.user=="object"&&Array.isArray(r.pubKeyCredParams)}function cr(e){if(!e||typeof e!="object")return!1;let r=e;return typeof r.challenge=="string"&&typeof r.rpId=="string"}function H(e){if(!f(e))return o("Invalid API response: expected object",{originalData:e});let r=e.session_id,t=e.qr_url,n=e.expires_at;return!u(r)||!u(t)||!u(n)?o("Invalid API response: missing required fields",{originalData:e}):y({session_id:r,qr_url:t,expires_at:n})}function Re(e){if(!f(e))return o("Invalid API response: expected object",{originalData:e});let r=e.status;return!u(r)||!["pending","authenticated","completed"].includes(r)?o("Invalid API response: invalid status",{originalData:e}):y({status:r,user_id:e.user_id,session_token:e.session_token})}function he(e){if(!f(e))return o("Invalid API response: expected object",{originalData:e});let r=e.type,t=r==="registration"?"registration":"auth",n=e.options;return f(n)?t==="registration"?pr(n)?y({type:"registration",options:n}):o("Invalid API response: registration options must have challenge, rp, user, pubKeyCredParams",{originalData:e}):cr(n)?y({type:"auth",options:n}):o("Invalid API response: auth options must have challenge and rpId",{originalData:e}):o("Invalid API response: options are required",{originalData:e})}function ve(e){if(!f(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"challenge"),t=p(e,"recovery_session_id");return f(r)?u(t)?y({challenge:r,recovery_session_id:t}):o("Invalid API response: recovery_session_id must be string",{field:"recovery_session_id",originalData:e}):o("Invalid API response: challenge must be object",{field:"challenge",originalData:e})}function be(e){if(!f(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"status"),t=p(e,"session_token"),n=p(e,"user"),s=p(e,"credential_id");if(!u(r))return o("Invalid API response: status must be string",{field:"status",originalData:e});if(!u(t))return o("Invalid API response: session_token must be string",{field:"session_token",originalData:e});if(!u(s))return o("Invalid API response: credential_id must be string",{field:"credential_id",originalData:e});if(!f(n))return o("Invalid API response: user must be object",{field:"user",originalData:e});let i=p(n,"user_id");if(!u(i))return o("Invalid API response: user.user_id must be string",{field:"user.user_id",originalData:e});let a=n;return y({status:r,session_token:t,credential_id:s,user:{user_id:i,external_user_id:u(a.external_user_id)?a.external_user_id:void 0,email:u(a.email)?a.email:void 0,metadata:f(a.metadata)?a.metadata:void 0}})}var Y=class{constructor(r,t,n={}){this.httpClient=r;this.baseUrl=t;this.defaultHeaders=n}mergeHeaders(r){return{...this.defaultHeaders,...r}}async post(r,t,n){let s=`${this.baseUrl}${r}`,i=await this.httpClient.post(s,t,this.mergeHeaders());return i.ok?n(i.value):l(i.error)}async get(r,t,n){let s=`${this.baseUrl}${r}`,i=await this.httpClient.get(s,this.mergeHeaders(n));return i.ok?t(i.value):l(i.error)}async startRegister(r){return this.post("/v1/passkeys/register/start",r,oe)}async startAuth(r){return this.post("/v1/passkeys/auth/start",r,ae)}async finishRegister(r){return this.post("/v1/passkeys/register/finish",r,le)}async finishAuthentication(r){return this.post("/v1/passkeys/auth/finish",r,ue)}async validateSession(r){return this.get("/v1/sessions/validate",pe,{Authorization:`Bearer ${r}`})}async startEmailFallback(r){let t=`${this.baseUrl}/v1/fallback/email/start`,n=await this.httpClient.post(t,{userId:r.userId,email:r.email},this.mergeHeaders());return n.ok?y(void 0):l(n.error)}async verifyEmailCode(r,t){return this.post("/v1/fallback/email/verify",{userId:r,code:t},ce)}async startOnboarding(r){return this.post("/onboarding/start",r,de)}async getOnboardingStatus(r){return this.get(`/onboarding/${r}/status`,me)}async getOnboardingRegister(r){return this.get(`/onboarding/${r}/register`,ge)}async registerOnboardingPasskey(r,t){return this.post(`/onboarding/${r}/register-passkey`,t,ye)}async completeOnboarding(r,t){return this.post(`/onboarding/${r}/complete`,t,fe)}async initCrossDeviceAuth(){return this.post("/v1/auth/cross-device/init",{},H)}async initCrossDeviceRegistration(r){return this.post("/v1/auth/cross-device/init-registration",{external_user_id:r.externalUserId},H)}async getCrossDeviceStatus(r){return this.get(`/v1/auth/cross-device/status/${r}`,Re)}async getCrossDeviceContext(r){return this.get(`/v1/auth/cross-device/context/${r}`,he)}async verifyCrossDeviceAuth(r){let t=`${this.baseUrl}/v1/auth/cross-device/verify`,n=await this.httpClient.post(t,r,this.mergeHeaders());return n.ok?y(void 0):l(n.error)}async verifyCrossDeviceRegistration(r){let t=`${this.baseUrl}/v1/auth/cross-device/verify-registration`,n=await this.httpClient.post(t,r,this.mergeHeaders());return n.ok?y(void 0):l(n.error)}async verifyAccountRecoveryOtp(r,t){return this.post("/v1/users/recovery/verify",{external_id:r,otp:t},ve)}async completeAccountRecovery(r,t){return this.post("/v1/users/recovery/complete",{recovery_session_id:r,credential:t},be)}};var dr=3e4;function mr(){if(typeof globalThis.crypto<"u"&&typeof globalThis.crypto.randomUUID=="function")return globalThis.crypto.randomUUID();throw new Error("Web Crypto API is required but not available.")}function Ne(e,r){let t=r*Math.pow(2,e);return Math.min(t,dr)}function gr(e,r){return e!=="GET"?!1:r>=500||r===429}var G=class{constructor(r,t=0,n=1e3,s){this.timeoutMs=r;this.maxRetries=t;this.retryDelayMs=n;this.logger=s}async get(r,t){return this.request(r,{method:"GET",headers:t})}async post(r,t,n){return this.request(r,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",...n}})}async request(r,t){let n=(t.method??"GET").toUpperCase(),s=mr(),i=new Headers(t.headers);i.set("X-Request-Id",s),this.logger&&this.logger.debug("request",{requestId:s,url:r,method:n});let a;for(let m=0;m<=this.maxRetries;m++)try{let c=new AbortController,R=setTimeout(()=>c.abort(),this.timeoutMs);try{let d=await fetch(r,{...t,headers:i,signal:c.signal});if(!d.ok){let _;try{_=await d.json()}catch{}let k=_,A=k?.message??d.statusText,F=k?.error,E=h(F==="challenge_mismatch"?"CHALLENGE_MISMATCH":F??"NETWORK_FAILURE",A,{requestId:s,status:d.status,statusText:d.statusText,data:_});if(gr(n,d.status)&&m<this.maxRetries){a=E,await new Promise(L=>setTimeout(L,Ne(m,this.retryDelayMs)));continue}return l(E)}if(d.status===204)return y(void 0);if(d.headers.get("content-length")==="0")return y(void 0);let I=await d.json();return y(I)}finally{clearTimeout(R)}}catch(c){if(a=c,n==="GET"&&m<this.maxRetries)await new Promise(d=>setTimeout(d,Ne(m,this.retryDelayMs)));else break}return a instanceof Error&&a.name==="AbortError"?l(h("TIMEOUT","Request timed out",{requestId:s})):l(h("NETWORK_FAILURE",a instanceof Error?a.message:"Request failed",{requestId:s,cause:a}))}};function O(){try{return!(typeof navigator>"u"||!navigator.credentials||typeof PublicKeyCredential>"u")}catch{return!1}}async function yr(){try{return!O()||typeof PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable!="function"?!1:await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}async function Ue(){let e=O(),r=await yr();return{isPasskeySupported:e,platformAuthenticatorAvailable:r,recommendedFlow:e?"passkey":"fallback"}}function S(e){let r=new Uint8Array(e),t=Array.from(r,s=>String.fromCharCode(s)).join("");if(typeof globalThis.btoa>"u")throw se("encode");return globalThis.btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function fr(e){if(typeof globalThis.atob>"u")throw se("decode");let r=e.replace(/-/g,"+").replace(/_/g,"/"),t=r.length%4,n=t===0?r:r+"=".repeat(4-t),s=globalThis.atob(n);return Uint8Array.from(s,i=>i.charCodeAt(0))}function N(e){let r=fr(e),t=new ArrayBuffer(r.length);return new Uint8Array(t).set(r),t}function C(e,r="create"){if(!e||typeof e!="object"||!("id"in e)||!("rawId"in e)||!("response"in e))throw we(r)}function Fe(e){return e!==null&&typeof e=="object"&&"clientDataJSON"in e&&e.clientDataJSON instanceof ArrayBuffer}function P(e){if(!e.response)throw h("UNKNOWN_ERROR","Credential response is missing",{credential:e});let r=e.response;if(!Fe(r))throw h("UNKNOWN_ERROR","Invalid credential response structure",{response:r});if(!("attestationObject"in r))throw h("UNKNOWN_ERROR","Invalid credential response structure for register: attestationObject is missing",{response:r});let t=r.clientDataJSON,n=r.attestationObject;return{id:e.id,rawId:S(e.rawId),response:{clientDataJSON:S(t),attestationObject:S(n)},type:"public-key"}}function $(e){if(!e.response)throw h("UNKNOWN_ERROR","Credential response is missing",{credential:e});let r=e.response;if(!Fe(r))throw h("UNKNOWN_ERROR","Invalid credential response structure",{response:r});if(!("authenticatorData"in r)||!("signature"in r))throw h("UNKNOWN_ERROR","Invalid credential response structure for auth: authenticatorData or signature is missing",{response:r});let t=r.clientDataJSON,n=r.authenticatorData,s=r.signature,i=r.userHandle;return{id:e.id,rawId:S(e.rawId),response:{authenticatorData:S(n),clientDataJSON:S(t),signature:S(s),...i&&{userHandle:S(i)}},type:"public-key"}}function M(e,r){try{W(e.challenge,"challenge"),W(e.user.id,"user.id");let t=N(e.challenge),n=N(e.user.id),s={userVerification:"preferred"};e.authenticatorSelection&&(s={...e.authenticatorSelection}),r&&(s={...s,authenticatorAttachment:r});let i={rp:{id:e.rp.id,name:e.rp.name},user:{id:n,name:e.user.name,displayName:e.user.displayName},challenge:t,pubKeyCredParams:e.pubKeyCredParams,...e.timeout!==void 0&&{timeout:e.timeout},attestation:"none",authenticatorSelection:s,...e.excludeCredentials&&{excludeCredentials:e.excludeCredentials.map(a=>({id:N(a.id),type:a.type,...a.transports&&{transports:a.transports}}))}};return y({publicKey:i})}catch(t){return l(v(t))}}function _e(e,r){try{W(e.challenge,"challenge");let t=N(e.challenge);return y({publicKey:{challenge:t,rpId:e.rpId,...e.timeout!==void 0&&{timeout:e.timeout},userVerification:e.userVerification??"preferred",...e.allowCredentials&&{allowCredentials:e.allowCredentials.map(n=>({id:N(n.id),type:n.type,...n.transports&&{transports:n.transports}}))}},...r!==void 0&&{mediation:r}})}catch(t){return l(v(t))}}async function Le(e,r,t){try{if(t.emit("start",{type:"start",operation:"register"}),!O()){let d=q();return t.emit("error",{type:"error",error:d}),l(d)}let n=e.externalUserId??e.external_user_id;if(!n||typeof n!="string"||n.trim()===""){let d=b("externalUserId","must be a non-empty string");return t.emit("error",{type:"error",error:d}),l(d)}let s=await r.startRegister({external_user_id:n});if(!s.ok)return t.emit("error",{type:"error",error:s.error}),l(s.error);let i=M(s.value.challenge,e.authenticatorType);if(!i.ok)return t.emit("error",{type:"error",error:i.error}),l(i.error);let a={...i.value,...e.signal&&{signal:e.signal}},m=await navigator.credentials.create(a);if(!m){let d=b("credential","creation failed");return t.emit("error",{type:"error",error:d}),l(d)}try{C(m)}catch(d){let g=v(d);return t.emit("error",{type:"error",error:g}),l(g)}let c=await r.finishRegister({session_id:s.value.session_id,credential:P(m)});if(!c.ok)return t.emit("error",{type:"error",error:c.error}),l(c.error);let R={success:!0,credentialId:c.value.credential_id,credential_id:c.value.credential_id,status:c.value.status,sessionToken:c.value.session_token,user:{userId:c.value.user.user_id,externalUserId:c.value.user.external_user_id,email:c.value.user.email,metadata:c.value.user.metadata}};return t.emit("success",{type:"success",operation:"register"}),y(R)}catch(n){let s=v(n);return t.emit("error",{type:"error",error:s}),l(s)}}async function Ke(e,r,t){try{if(t.emit("start",{type:"start",operation:"authenticate"}),!O()){let g=q();return t.emit("error",{type:"error",error:g}),l(g)}let n=e.externalUserId??e.external_user_id,s=n!==void 0&&typeof n=="string"&&n.trim()!=="",i=await r.startAuth(s?{external_user_id:n.trim()}:{});if(!i.ok)return t.emit("error",{type:"error",error:i.error}),l(i.error);let a=_e(i.value.challenge,e.mediation);if(!a.ok)return t.emit("error",{type:"error",error:a.error}),l(a.error);let m={...a.value,...e.signal&&{signal:e.signal}},c=await navigator.credentials.get(m);if(!c){let g=b("credential","retrieval failed");return t.emit("error",{type:"error",error:g}),l(g)}try{C(c)}catch(g){let I=v(g);return t.emit("error",{type:"error",error:I}),l(I)}let R=await r.finishAuthentication({session_id:i.value.session_id,credential:$(c)});if(!R.ok)return t.emit("error",{type:"error",error:R.error}),l(R.error);let d={authenticated:R.value.authenticated,sessionToken:R.value.session_token,user:{userId:R.value.user.user_id,externalUserId:R.value.user.external_user_id,email:R.value.user.email,metadata:R.value.user.metadata},signals:R.value.signals};return t.emit("success",{type:"success",operation:"authenticate"}),y(d)}catch(n){let s=v(n);return t.emit("error",{type:"error",error:s}),l(s)}}var Rr=2e3,hr=60,X=class{constructor(r){this.apiClient=r}async startFlow(r){let t=await this.apiClient.startOnboarding({user_role:r.user_role});if(!t.ok)return l(t.error);let{session_id:n}=t.value;for(let s=0;s<hr;s++){await new Promise(c=>setTimeout(c,Rr));let i=await this.apiClient.getOnboardingStatus(n);if(!i.ok)return l(i.error);let a=i.value.status,m=i.value.onboarding_url;if(a==="pending_passkey"){let c=await this.apiClient.getOnboardingRegister(n);if(!c.ok)return l(c.error);let R=c.value;if(!R.challenge)return l(h("NOT_SUPPORTED","Onboarding requires user action - complete passkey registration at the provided onboarding_url",{onboarding_url:m}));let d=M(R.challenge);if(!d.ok)return l(d.error);let g;try{g=await navigator.credentials.create(d.value)}catch(A){return l(v(A))}try{C(g,"create")}catch(A){return l(v(A))}let I;try{I=P(g)}catch(A){return l(v(A))}let _=await this.apiClient.registerOnboardingPasskey(n,{credential:I,challenge:R.challenge.challenge});return _.ok?await this.apiClient.completeOnboarding(n,{company_name:r.company_name}):l(_.error)}if(a==="completed")return await this.apiClient.completeOnboarding(n,{company_name:r.company_name})}return l(h("TIMEOUT","Onboarding timed out"))}};var vr=2e3,br=60,z=class{constructor(r){this.apiClient=r}async init(){return this.apiClient.initCrossDeviceAuth()}async initRegistration(r){return this.apiClient.initCrossDeviceRegistration(r)}async waitForSession(r,t){for(let n=0;n<br;n++){if(t?.aborted)return l(h("ABORT_ERROR","Operation aborted by user or timeout"));let s=await this.apiClient.getCrossDeviceStatus(r);if(!s.ok)return l(s.error);if(s.value.status==="completed")return!s.value.session_token||!s.value.user_id?l(h("UNKNOWN_ERROR","Missing data in completed session")):y({session_token:s.value.session_token,user_id:s.value.user_id});if(t?.aborted)return l(h("ABORT_ERROR","Operation aborted by user or timeout"));if(await new Promise(i=>{let a=setTimeout(()=>{i(null),t?.removeEventListener("abort",m)},vr),m=()=>{clearTimeout(a),i(null)};t?.addEventListener("abort",m)}),t?.aborted)return l(h("ABORT_ERROR","Operation aborted by user or timeout"))}return l(h("TIMEOUT","Cross-device authentication timed out"))}async approve(r){let t=await this.apiClient.getCrossDeviceContext(r);if(!t.ok)return l(t.error);let n=t.value;return n.type==="registration"?this.executeRegistrationApproval(r,n):this.executeAuthApproval(r,n)}async executeRegistrationApproval(r,t){let n=M(t.options);if(!n.ok)return l(n.error);let s;try{s=await navigator.credentials.create(n.value)}catch(a){return l(v(a))}try{C(s,"create")}catch(a){return l(v(a))}let i;try{i=P(s)}catch(a){return l(v(a))}return this.apiClient.verifyCrossDeviceRegistration({session_id:r,credential:i})}async executeAuthApproval(r,t){let n=_e(t.options);if(!n.ok)return l(n.error);let s;try{s=await navigator.credentials.get(n.value)}catch(a){return l(v(a))}try{C(s,"get")}catch(a){return l(v(a))}let i;try{i=$(s)}catch(a){return l(v(a))}return this.apiClient.verifyCrossDeviceAuth({session_id:r,credential:i})}};var J=class{handlers;constructor(){this.handlers=new Map}on(r,t){let n=this.handlers.get(r);return n||(n=new Set,this.handlers.set(r,n)),n.add(t),()=>{this.off(r,t)}}off(r,t){let n=this.handlers.get(r);n&&(n.delete(t),n.size===0&&this.handlers.delete(r))}emit(r,t){let n=this.handlers.get(r);n&&n.forEach(s=>{try{s(t)}catch{}})}removeAllListeners(){this.handlers.clear()}};async function je(e,r,t){try{if(t.emit("start",{type:"start",operation:"register"}),!O()){let d=q();return t.emit("error",{type:"error",error:d}),l(d)}let n=e.externalUserId??e.external_user_id;if(!n||typeof n!="string"||n.trim()===""){let d=b("externalUserId","must be a non-empty string");return t.emit("error",{type:"error",error:d}),l(d)}if(!e.otp||typeof e.otp!="string"||e.otp.trim().length!==6){let d=b("otp","must be a 6-digit string");return t.emit("error",{type:"error",error:d}),l(d)}let s=await r.verifyAccountRecoveryOtp(n,e.otp);if(!s.ok)return t.emit("error",{type:"error",error:s.error}),l(s.error);let i=M(s.value.challenge);if(!i.ok)return t.emit("error",{type:"error",error:i.error}),l(i.error);let a={...i.value},m=await navigator.credentials.create(a);if(!m){let d=b("credential","creation failed");return t.emit("error",{type:"error",error:d}),l(d)}try{C(m)}catch(d){let g=v(d);return t.emit("error",{type:"error",error:g}),l(g)}let c=await r.completeAccountRecovery(s.value.recovery_session_id,P(m));if(!c.ok)return t.emit("error",{type:"error",error:c.error}),l(c.error);let R={success:!0,credentialId:c.value.credential_id,status:c.value.status,sessionToken:c.value.session_token,user:{userId:c.value.user.user_id,externalUserId:c.value.user.external_user_id,email:c.value.user.email,metadata:c.value.user.metadata}};return t.emit("success",{type:"success",operation:"register"}),y(R)}catch(n){let s=v(n);return t.emit("error",{type:"error",error:s}),l(s)}}var Ee="https://api.trymellonauth.com",qe="https://api.trymellonauth.com/v1/telemetry";var Ve="trymellon_sandbox_session_token_v1";function We(e){return{async send(r){let t=JSON.stringify(r);if(typeof navigator<"u"&&typeof navigator.sendBeacon=="function"){navigator.sendBeacon(e,t);return}typeof fetch<"u"&&await fetch(e,{method:"POST",body:t,headers:{"Content-Type":"application/json"},keepalive:!0})}}}function Te(e,r){return{event:e,latencyMs:r,ok:!0}}var Z=class e{sandbox;sandboxToken;apiClient;eventEmitter;telemetrySender;crossDeviceManager;onboarding;static create(r){try{let t=r.appId,n=r.publishableKey;if(!t||typeof t!="string"||t.trim()==="")return l(b("appId","must be a non-empty string"));if(!n||typeof n!="string"||n.trim()==="")return l(b("publishableKey","must be a non-empty string"));let s=r.apiBaseUrl??Ee;ie(s,"apiBaseUrl");let i=r.timeoutMs??3e4;return D(i,"timeoutMs",1e3,3e5),r.maxRetries!==void 0&&D(r.maxRetries,"maxRetries",0,10),r.retryDelayMs!==void 0&&D(r.retryDelayMs,"retryDelayMs",100,1e4),y(new e(r))}catch(t){return ne(t)?l(t):l(b("config",t.message))}}constructor(r){this.sandbox=r.sandbox===!0,this.sandboxToken=this.sandbox&&r.sandboxToken!=null&&r.sandboxToken!==""?r.sandboxToken:Ve;let t=r.appId,n=r.publishableKey;if(!t||typeof t!="string"||t.trim()==="")throw b("appId","must be a non-empty string");if(!n||typeof n!="string"||n.trim()==="")throw b("publishableKey","must be a non-empty string");let s=r.apiBaseUrl??Ee;ie(s,"apiBaseUrl");let i=r.timeoutMs??3e4;D(i,"timeoutMs",1e3,3e5),r.maxRetries!==void 0&&D(r.maxRetries,"maxRetries",0,10),r.retryDelayMs!==void 0&&D(r.retryDelayMs,"retryDelayMs",100,1e4);let a=r.maxRetries??3,m=r.retryDelayMs??1e3,c=new G(i,a,m,r.logger),R=r.origin??(typeof window<"u"&&window?.location?.origin?window.location.origin:void 0),d={"X-App-Id":t.trim(),Authorization:`Bearer ${n.trim()}`,...R&&{Origin:R}};this.apiClient=new Y(c,s,d),this.onboarding=new X(this.apiClient),this.crossDeviceManager=new z(this.apiClient),this.eventEmitter=new J,r.enableTelemetry&&(this.telemetrySender=r.telemetrySender??We(r.telemetryEndpoint??qe))}static isSupported(){return O()}async register(r){if(this.sandbox){let s=r.externalUserId??r.external_user_id??"sandbox";return Promise.resolve(y({success:!0,credentialId:"",status:"sandbox",sessionToken:this.sandboxToken,user:{userId:"sandbox-user",externalUserId:typeof s=="string"?s:"sandbox"}}))}let t=Date.now(),n=await Le(r,this.apiClient,this.eventEmitter);return n.ok&&this.telemetrySender&&this.telemetrySender.send(Te("register",Date.now()-t)).catch(()=>{}),n}async authenticate(r){if(this.sandbox){let s=r.externalUserId??r.external_user_id??"sandbox";return Promise.resolve(y({authenticated:!0,sessionToken:this.sandboxToken,user:{userId:"sandbox-user",externalUserId:typeof s=="string"?s:"sandbox"}}))}let t=Date.now(),n=await Ke(r,this.apiClient,this.eventEmitter);return n.ok&&this.telemetrySender&&this.telemetrySender.send(Te("authenticate",Date.now()-t)).catch(()=>{}),n}async validateSession(r){return this.sandbox&&r===this.sandboxToken?Promise.resolve(y({valid:!0,user_id:"sandbox-user",external_user_id:"sandbox",tenant_id:"sandbox-tenant",app_id:"sandbox-app"})):this.apiClient.validateSession(r)}async getStatus(){return Ue()}on(r,t){return this.eventEmitter.on(r,t)}version(){return"1.5.0"}fallback={email:{start:async r=>this.apiClient.startEmailFallback(r),verify:async r=>this.apiClient.verifyEmailCode(r.userId,r.code)}};auth={crossDevice:{init:()=>this.crossDeviceManager.init(),initRegistration:r=>this.crossDeviceManager.initRegistration(r),waitForSession:(r,t)=>this.crossDeviceManager.waitForSession(r,t),approve:r=>this.crossDeviceManager.approve(r)},recoverAccount:async r=>je(r,this.apiClient,this.eventEmitter)}};var Q=new Ir("TRYMELLON_CONFIG"),Je,Ie;Je=[Tr({providedIn:"root"})];var U=class{config=Ar(Q,{optional:!0});_client=null;get client(){if(this._client==null){if(this.config==null)throw new Error("TryMellonService: provide TRYMELLON_CONFIG (e.g. via provideTryMellonConfig(config))");this._client=new Z(this.config)}return this._client}};Ie=Pe(null),U=Me(Ie,0,"TryMellonService",Je,U),De(Ie,1,U);function gn(e){return{provide:Q,useValue:e}}export{Q as TRYMELLON_CONFIG,U as TryMellonService,gn as provideTryMellonConfig};
2
+ var nr=Object.create;var re=Object.defineProperty;var sr=Object.getOwnPropertyDescriptor;var Pe=(e,r)=>(r=Symbol[e])?r:Symbol.for("Symbol."+e),j=e=>{throw TypeError(e)};var ir=(e,r,t)=>r in e?re(e,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[r]=t;var Oe=(e,r)=>re(e,"name",{value:r,configurable:!0});var ke=e=>[,,,nr(e?.[Pe("metadata")]??null)],Me=["class","method","getter","setter","accessor","field","value","get","set"],K=e=>e!==void 0&&typeof e!="function"?j("Function expected"):e,or=(e,r,t,n,s)=>({kind:Me[e],name:r,metadata:n,addInitializer:i=>t._?j("Already initialized"):s.push(K(i||null))}),ar=(e,r)=>ir(r,Pe("metadata"),e[3]),De=(e,r,t,n)=>{for(var s=0,i=e[r>>1],a=i&&i.length;s<a;s++)r&1?i[s].call(t):n=i[s].call(t,n);return n},we=(e,r,t,n,s,i)=>{var a,c,R,v,y,m=r&7,A=!!(r&8),E=!!(r&16),x=m>3?e.length+1:m?A?1:2:0,I=Me[m+5],F=m>3&&(e[x-1]=[]),Ce=e[x]||(e[x]=[]),_=m&&(!E&&!A&&(s=s.prototype),m<5&&(m>3||!E)&&sr(m<4?s:{get[t](){return Se(this,i)},set[t](T){return xe(this,i,T)}},t));m?E&&m<4&&Oe(i,(m>2?"set ":m>1?"get ":"")+t):Oe(s,t);for(var L=n.length-1;L>=0;L--)v=or(m,t,R={},e[3],Ce),m&&(v.static=A,v.private=E,y=v.access={has:E?T=>lr(s,T):T=>t in T},m^3&&(y.get=E?T=>(m^1?Se:ur)(T,s,m^4?i:_.get):T=>T[t]),m>2&&(y.set=E?(T,ee)=>xe(T,s,ee,m^4?i:_.set):(T,ee)=>T[t]=ee)),c=(0,n[L])(m?m<4?E?i:_[I]:m>4?void 0:{get:_.get,set:_.set}:s,v),R._=1,m^4||c===void 0?K(c)&&(m>4?F.unshift(c):m?E?i=c:_[I]=c:s=c):typeof c!="object"||c===null?j("Object expected"):(K(a=c.get)&&(_.get=a),K(a=c.set)&&(_.set=a),K(a=c.init)&&F.unshift(a));return m||ar(e,s),_&&re(s,t,_),E?m^4?i:_:s};var te=(e,r,t)=>r.has(e)||j("Cannot "+t),lr=(e,r)=>Object(r)!==r?j('Cannot use the "in" operator on this value'):e.has(r),Se=(e,r,t)=>(te(e,r,"read from private field"),t?t.call(e):r.get(e));var xe=(e,r,t,n)=>(te(e,r,"write to private field"),n?n.call(e,t):r.set(e,t),t),ur=(e,r,t)=>(te(e,r,"access private method"),t);import{Injectable as Sr,InjectionToken as xr,inject as Pr}from"@angular/core";var d=e=>({ok:!0,value:e}),l=e=>({ok:!1,error:e});var V=class e extends Error{code;details;isTryMellonError=!0;constructor(r,t,n){super(t),this.name="TryMellonError",this.code=r,this.details=n,Error.captureStackTrace&&Error.captureStackTrace(this,e)}},pr={NOT_SUPPORTED:"WebAuthn is not supported in this environment",USER_CANCELLED:"User cancelled the operation",PASSKEY_NOT_FOUND:"Passkey not found",SESSION_EXPIRED:"Session has expired",NETWORK_FAILURE:"Network request failed",INVALID_ARGUMENT:"Invalid argument provided",TIMEOUT:"Operation timed out",ABORTED:"Operation was aborted",ABORT_ERROR:"Operation aborted by user or timeout",CHALLENGE_MISMATCH:"This link was already used or expired. Please try again from your computer.",UNKNOWN_ERROR:"An unknown error occurred"};function f(e,r,t){return new V(e,r??pr[e],t)}function ne(e){return e instanceof V||typeof e=="object"&&e!==null&&"isTryMellonError"in e&&e.isTryMellonError===!0}function Ne(){return f("NOT_SUPPORTED")}function h(e,r){return f("INVALID_ARGUMENT",`Invalid argument: ${e} - ${r}`,{field:e,reason:r})}function Ue(e){return f("UNKNOWN_ERROR",`Failed to ${e} credential`,{operation:e})}function se(e){return f("NOT_SUPPORTED",`No base64 ${e==="encode"?"encoding":"decoding"} available`,{type:e})}function ie(e,r){try{let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")throw h(r,"must use http or https protocol")}catch(t){throw ne(t)?t:h(r,"must be a valid URL")}}function P(e,r,t,n){if(!Number.isFinite(e))throw h(r,"must be a finite number");if(e<t||e>n)throw h(r,`must be between ${t} and ${n}`)}function W(e,r){if(typeof e!="string"||e.length===0)throw h(r,"must be a non-empty string");if(!/^[A-Za-z0-9_-]+$/.test(e))throw h(r,"must be a valid base64url string")}var cr={NotAllowedError:"USER_CANCELLED",AbortError:"ABORTED",NotSupportedError:"NOT_SUPPORTED",SecurityError:"NOT_SUPPORTED",InvalidStateError:"UNKNOWN_ERROR",UnknownError:"UNKNOWN_ERROR"};function b(e){if(e instanceof DOMException){let r=e.name,t=e.message||"WebAuthn operation failed",n=cr[r]??"UNKNOWN_ERROR";return f(n,t,{originalError:e})}return e instanceof Error?f("UNKNOWN_ERROR",e.message,{originalError:e}):f("UNKNOWN_ERROR","An unknown error occurred",{originalError:e})}function g(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function u(e){return typeof e=="string"}function O(e){return typeof e=="number"&&Number.isFinite(e)}function B(e){return typeof e=="boolean"}function D(e){return Array.isArray(e)}function o(e,r){return l(f("UNKNOWN_ERROR",e,{...r,originalData:r?.originalData}))}function p(e,r){return e[r]}function Fe(e,r){return!g(e)||!u(e.name)||!u(e.id)?o("Invalid API response: challenge.rp must have name and id strings",{originalData:r}):d(!0)}function Le(e,r){return!g(e)||!u(e.id)||!u(e.name)||!u(e.displayName)?o("Invalid API response: challenge.user must have id, name, displayName strings",{originalData:r}):d(!0)}function Ke(e,r){if(!D(e))return o("Invalid API response: challenge.pubKeyCredParams must be array",{originalData:r});for(let t of e)if(!g(t)||t.type!=="public-key"||!O(t.alg))return o("Invalid API response: pubKeyCredParams items must have type and alg",{originalData:r});return d(!0)}function oe(e,r){if(!g(e))return o("Invalid API response: user must be object",{field:"user",originalData:r});let t=p(e,"user_id"),n=p(e,"external_user_id");if(!u(t)||!u(n))return o("Invalid API response: user must have user_id and external_user_id strings",{originalData:r});let s=e.email,i=e.metadata;return s!==void 0&&!u(s)?o("Invalid API response: user.email must be string",{originalData:r}):i!==void 0&&(typeof i!="object"||i===null)?o("Invalid API response: user.metadata must be object",{originalData:r}):d({user_id:t,external_user_id:n,...s!==void 0&&{email:s},...i!==void 0&&{metadata:i}})}function ae(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id");if(!u(r))return o("Invalid API response: session_id must be string",{field:"session_id",originalData:e});let t=p(e,"challenge");if(!g(t))return o("Invalid API response: challenge must be object",{field:"challenge",originalData:e});let n=Fe(p(t,"rp"),e);if(!n.ok)return n;let s=Le(p(t,"user"),e);if(!s.ok)return s;let i=p(t,"challenge");if(!u(i))return o("Invalid API response: challenge.challenge must be string",{originalData:e});let a=Ke(p(t,"pubKeyCredParams"),e);if(!a.ok)return a;let c=t.timeout;if(c!==void 0&&!O(c))return o("Invalid API response: challenge.timeout must be number",{originalData:e});let R=t.excludeCredentials;if(R!==void 0){if(!D(R))return o("Invalid API response: excludeCredentials must be array",{originalData:e});for(let y of R)if(!g(y)||y.type!=="public-key"||!u(y.id))return o("Invalid API response: excludeCredentials items must have id and type",{originalData:e})}let v=t.authenticatorSelection;return v!==void 0&&!g(v)?o("Invalid API response: authenticatorSelection must be object",{originalData:e}):d({session_id:r,challenge:{rp:t.rp,user:t.user,challenge:i,pubKeyCredParams:t.pubKeyCredParams,...c!==void 0&&{timeout:c},...R!==void 0&&{excludeCredentials:R},...v!==void 0&&{authenticatorSelection:v}}})}function le(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id");if(!u(r))return o("Invalid API response: session_id must be string",{field:"session_id",originalData:e});let t=p(e,"challenge");if(!g(t))return o("Invalid API response: challenge must be object",{field:"challenge",originalData:e});let n=p(t,"challenge"),s=p(t,"rpId"),i=t.allowCredentials;if(!u(n))return o("Invalid API response: challenge.challenge must be string",{originalData:e});if(!u(s))return o("Invalid API response: challenge.rpId must be string",{originalData:e});if(i!==void 0&&!D(i))return o("Invalid API response: allowCredentials must be array",{originalData:e});if(i){for(let R of i)if(!g(R)||R.type!=="public-key"||!u(R.id))return o("Invalid API response: allowCredentials items must have id and type",{originalData:e})}let a=t.timeout;if(a!==void 0&&!O(a))return o("Invalid API response: challenge.timeout must be number",{originalData:e});let c=t.userVerification;return c!==void 0&&!["required","preferred","discouraged"].includes(String(c))?o("Invalid API response: userVerification must be required|preferred|discouraged",{originalData:e}):d({session_id:r,challenge:{challenge:n,rpId:s,allowCredentials:i??[],...a!==void 0&&{timeout:a},...c!==void 0&&{userVerification:c}}})}function ue(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"credential_id"),t=p(e,"status"),n=p(e,"session_token"),s=p(e,"user");if(!u(r))return o("Invalid API response: credential_id must be string",{field:"credential_id",originalData:e});if(!u(t))return o("Invalid API response: status must be string",{field:"status",originalData:e});if(!u(n))return o("Invalid API response: session_token must be string",{field:"session_token",originalData:e});let i=oe(s,e);return i.ok?d({credential_id:r,status:t,session_token:n,user:i.value}):o(i.error.message,{originalData:e})}function pe(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"authenticated"),t=p(e,"session_token"),n=p(e,"user"),s=p(e,"signals");if(!B(r))return o("Invalid API response: authenticated must be boolean",{field:"authenticated",originalData:e});if(!u(t))return o("Invalid API response: session_token must be string",{field:"session_token",originalData:e});let i=oe(n,e);return i.ok?s!==void 0&&!g(s)?o("Invalid API response: signals must be object",{originalData:e}):d({authenticated:r,session_token:t,user:i.value,signals:s}):o(i.error.message,{originalData:e})}function ce(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"valid"),t=p(e,"user_id"),n=p(e,"external_user_id"),s=p(e,"tenant_id"),i=p(e,"app_id");return B(r)?u(t)?u(n)?u(s)?u(i)?d({valid:r,user_id:t,external_user_id:n,tenant_id:s,app_id:i}):o("Invalid API response: app_id must be string",{field:"app_id",originalData:e}):o("Invalid API response: tenant_id must be string",{field:"tenant_id",originalData:e}):o("Invalid API response: external_user_id must be string",{field:"external_user_id",originalData:e}):o("Invalid API response: user_id must be string",{field:"user_id",originalData:e}):o("Invalid API response: valid must be boolean",{field:"valid",originalData:e})}function de(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"sessionToken");return u(r)?d({sessionToken:r}):o("Invalid API response: sessionToken must be string",{field:"sessionToken",originalData:e})}var dr=["pending_passkey","pending_data","completed"],mr=["pending_data","completed"];function me(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id"),t=p(e,"onboarding_url"),n=p(e,"expires_in");return u(r)?u(t)?O(n)?d({session_id:r,onboarding_url:t,expires_in:n}):o("Invalid API response: expires_in must be number",{field:"expires_in",originalData:e}):o("Invalid API response: onboarding_url must be string",{field:"onboarding_url",originalData:e}):o("Invalid API response: session_id must be string",{field:"session_id",originalData:e})}function ge(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"status"),t=p(e,"onboarding_url"),n=p(e,"expires_in");return!u(r)||!dr.includes(r)?o("Invalid API response: status must be pending_passkey|pending_data|completed",{field:"status",originalData:e}):u(t)?O(n)?d({status:r,onboarding_url:t,expires_in:n}):o("Invalid API response: expires_in must be number",{originalData:e}):o("Invalid API response: onboarding_url must be string",{originalData:e})}function Re(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id"),t=p(e,"status"),n=p(e,"onboarding_url");if(!u(r))return o("Invalid API response: session_id must be string",{field:"session_id",originalData:e});if(t!=="pending_passkey")return o("Invalid API response: status must be pending_passkey",{field:"status",originalData:e});if(!u(n))return o("Invalid API response: onboarding_url must be string",{originalData:e});let s=e.challenge,i;if(s!==void 0){let a=gr(s);if(!a.ok)return a;i=a.value}return d({session_id:r,status:"pending_passkey",onboarding_url:n,...i!==void 0&&{challenge:i}})}function gr(e){if(!g(e))return o("Invalid API response: challenge must be object",{originalData:e});let r=p(e,"rp"),t=p(e,"user"),n=p(e,"challenge"),s=p(e,"pubKeyCredParams");if(!g(r)||!u(r.name)||!u(r.id))return o("Invalid API response: challenge.rp must have name and id",{originalData:e});if(!g(t)||!u(t.id)||!u(t.name)||!u(t.displayName))return o("Invalid API response: challenge.user must have id, name, displayName",{originalData:e});if(!u(n))return o("Invalid API response: challenge.challenge must be string",{originalData:e});if(!D(s))return o("Invalid API response: challenge.pubKeyCredParams must be array",{originalData:e});for(let i of s)if(!g(i)||i.type!=="public-key"||!O(i.alg))return o("Invalid API response: pubKeyCredParams items must have type and alg",{originalData:e});return d({rp:r,user:t,challenge:n,pubKeyCredParams:s})}function ye(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id"),t=p(e,"status"),n=p(e,"user_id"),s=p(e,"tenant_id");return u(r)?!u(t)||!mr.includes(t)?o("Invalid API response: status must be pending_data|completed",{originalData:e}):u(n)?u(s)?d({session_id:r,status:t,user_id:n,tenant_id:s}):o("Invalid API response: tenant_id must be string",{originalData:e}):o("Invalid API response: user_id must be string",{originalData:e}):o("Invalid API response: session_id must be string",{originalData:e})}function fe(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id"),t=p(e,"status"),n=p(e,"user_id"),s=p(e,"tenant_id"),i=p(e,"session_token");return u(r)?t!=="completed"?o("Invalid API response: status must be completed",{originalData:e}):!u(n)||!u(s)||!u(i)?o("Invalid API response: user_id, tenant_id, session_token must be strings",{originalData:e}):d({session_id:r,status:"completed",user_id:n,tenant_id:s,session_token:i}):o("Invalid API response: session_id must be string",{originalData:e})}function Rr(e){if(!e||typeof e!="object")return!1;let r=e;return typeof r.challenge=="string"&&r.rp!=null&&typeof r.rp=="object"&&r.user!=null&&typeof r.user=="object"&&Array.isArray(r.pubKeyCredParams)}function yr(e){if(!e||typeof e!="object")return!1;let r=e;return typeof r.challenge=="string"&&typeof r.rpId=="string"}function H(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=e.session_id,t=e.qr_url,n=e.expires_at;return!u(r)||!u(t)||!u(n)?o("Invalid API response: missing required fields",{originalData:e}):d({session_id:r,qr_url:t,expires_at:n})}function ve(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=e.status;return!u(r)||!["pending","authenticated","completed"].includes(r)?o("Invalid API response: invalid status",{originalData:e}):d({status:r,user_id:e.user_id,session_token:e.session_token})}function he(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=e.type,t=r==="registration"?"registration":"auth",n=e.options;return g(n)?t==="registration"?Rr(n)?d({type:"registration",options:n}):o("Invalid API response: registration options must have challenge, rp, user, pubKeyCredParams",{originalData:e}):yr(n)?d({type:"auth",options:n}):o("Invalid API response: auth options must have challenge and rpId",{originalData:e}):o("Invalid API response: options are required",{originalData:e})}function Ee(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"challenge"),t=p(e,"recovery_session_id");return g(r)?u(t)?d({challenge:r,recovery_session_id:t}):o("Invalid API response: recovery_session_id must be string",{field:"recovery_session_id",originalData:e}):o("Invalid API response: challenge must be object",{field:"challenge",originalData:e})}function be(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"status"),t=p(e,"session_token"),n=p(e,"user"),s=p(e,"credential_id");if(!u(r))return o("Invalid API response: status must be string",{field:"status",originalData:e});if(!u(t))return o("Invalid API response: session_token must be string",{field:"session_token",originalData:e});if(!u(s))return o("Invalid API response: credential_id must be string",{field:"credential_id",originalData:e});if(!g(n))return o("Invalid API response: user must be object",{field:"user",originalData:e});let i=p(n,"user_id");if(!u(i))return o("Invalid API response: user.user_id must be string",{field:"user.user_id",originalData:e});let a=n;return d({status:r,session_token:t,credential_id:s,user:{user_id:i,external_user_id:u(a.external_user_id)?a.external_user_id:void 0,email:u(a.email)?a.email:void 0,metadata:g(a.metadata)?a.metadata:void 0}})}var Y=class{constructor(r,t,n={}){this.httpClient=r;this.baseUrl=t;this.defaultHeaders=n}mergeHeaders(r){return{...this.defaultHeaders,...r}}async post(r,t,n){let s=`${this.baseUrl}${r}`,i=await this.httpClient.post(s,t,this.mergeHeaders());return i.ok?n(i.value):l(i.error)}async get(r,t,n){let s=`${this.baseUrl}${r}`,i=await this.httpClient.get(s,this.mergeHeaders(n));return i.ok?t(i.value):l(i.error)}async startRegister(r){return this.post("/v1/passkeys/register/start",r,ae)}async startAuth(r){return this.post("/v1/passkeys/auth/start",r,le)}async finishRegister(r){return this.post("/v1/passkeys/register/finish",r,ue)}async finishAuthentication(r){return this.post("/v1/passkeys/auth/finish",r,pe)}async validateSession(r){return this.get("/v1/sessions/validate",ce,{Authorization:`Bearer ${r}`})}async startEmailFallback(r){let t=`${this.baseUrl}/v1/fallback/email/start`,n=await this.httpClient.post(t,{userId:r.userId,email:r.email},this.mergeHeaders());return n.ok?d(void 0):l(n.error)}async verifyEmailCode(r,t){return this.post("/v1/fallback/email/verify",{userId:r,code:t},de)}async startOnboarding(r){return this.post("/onboarding/start",r,me)}async getOnboardingStatus(r){return this.get(`/onboarding/${r}/status`,ge)}async getOnboardingRegister(r){return this.get(`/onboarding/${r}/register`,Re)}async registerOnboardingPasskey(r,t){return this.post(`/onboarding/${r}/register-passkey`,t,ye)}async completeOnboarding(r,t){return this.post(`/onboarding/${r}/complete`,t,fe)}async initCrossDeviceAuth(){return this.post("/v1/auth/cross-device/init",{},H)}async initCrossDeviceRegistration(r){return this.post("/v1/auth/cross-device/init-registration",{external_user_id:r.externalUserId},H)}async getCrossDeviceStatus(r){return this.get(`/v1/auth/cross-device/status/${r}`,ve)}async getCrossDeviceContext(r){return this.get(`/v1/auth/cross-device/context/${r}`,he)}async verifyCrossDeviceAuth(r){let t=`${this.baseUrl}/v1/auth/cross-device/verify`,n=await this.httpClient.post(t,r,this.mergeHeaders());return n.ok?d(void 0):l(n.error)}async verifyCrossDeviceRegistration(r){let t=`${this.baseUrl}/v1/auth/cross-device/verify-registration`,n=await this.httpClient.post(t,r,this.mergeHeaders());return n.ok?d(void 0):l(n.error)}async verifyAccountRecoveryOtp(r,t){return this.post("/v1/users/recovery/verify",{external_id:r,otp:t},Ee)}async completeAccountRecovery(r,t){return this.post("/v1/users/recovery/complete",{recovery_session_id:r,credential:t},be)}};var fr=3e4;function vr(){if(typeof globalThis.crypto<"u"&&typeof globalThis.crypto.randomUUID=="function")return globalThis.crypto.randomUUID();throw new Error("Web Crypto API is required but not available.")}function je(e,r){let t=r*Math.pow(2,e);return Math.min(t,fr)}function hr(e,r){return e!=="GET"?!1:r>=500||r===429}var G=class{constructor(r,t=0,n=1e3,s){this.timeoutMs=r;this.maxRetries=t;this.retryDelayMs=n;this.logger=s}async get(r,t){return this.request(r,{method:"GET",headers:t})}async post(r,t,n){return this.request(r,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",...n}})}async request(r,t){let n=(t.method??"GET").toUpperCase(),s=vr(),i=new Headers(t.headers);i.set("X-Request-Id",s),this.logger&&this.logger.debug("request",{requestId:s,url:r,method:n});let a;for(let c=0;c<=this.maxRetries;c++)try{let R=new AbortController,v=setTimeout(()=>R.abort(),this.timeoutMs);try{let y=await fetch(r,{...t,headers:i,signal:R.signal});if(!y.ok){let E;try{E=await y.json()}catch{}let x=E,I=x?.message??y.statusText,F=x?.error,_=f(F==="challenge_mismatch"?"CHALLENGE_MISMATCH":F??"NETWORK_FAILURE",I,{requestId:s,status:y.status,statusText:y.statusText,data:E});if(hr(n,y.status)&&c<this.maxRetries){a=_,await new Promise(L=>setTimeout(L,je(c,this.retryDelayMs)));continue}return l(_)}if(y.status===204)return d(void 0);if(y.headers.get("content-length")==="0")return d(void 0);let A=await y.json();return d(A)}finally{clearTimeout(v)}}catch(R){if(a=R,n==="GET"&&c<this.maxRetries)await new Promise(y=>setTimeout(y,je(c,this.retryDelayMs)));else break}return a instanceof Error&&a.name==="AbortError"?l(f("TIMEOUT","Request timed out",{requestId:s})):l(f("NETWORK_FAILURE",a instanceof Error?a.message:"Request failed",{requestId:s,cause:a}))}};function C(e){let r=new Uint8Array(e),t=Array.from(r,s=>String.fromCharCode(s)).join("");if(typeof globalThis.btoa>"u")throw se("encode");return globalThis.btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Er(e){if(typeof globalThis.atob>"u")throw se("decode");let r=e.replace(/-/g,"+").replace(/_/g,"/"),t=r.length%4,n=t===0?r:r+"=".repeat(4-t),s=globalThis.atob(n);return Uint8Array.from(s,i=>i.charCodeAt(0))}function w(e){let r=Er(e),t=new ArrayBuffer(r.length);return new Uint8Array(t).set(r),t}function qe(e){return e!==null&&typeof e=="object"&&"clientDataJSON"in e&&e.clientDataJSON instanceof ArrayBuffer}function S(e){if(!e.response)throw f("UNKNOWN_ERROR","Credential response is missing",{credential:e});let r=e.response;if(!qe(r))throw f("UNKNOWN_ERROR","Invalid credential response structure",{response:r});if(!("attestationObject"in r))throw f("UNKNOWN_ERROR","Invalid credential response structure for register: attestationObject is missing",{response:r});let t=r.clientDataJSON,n=r.attestationObject;return{id:e.id,rawId:C(e.rawId),response:{clientDataJSON:C(t),attestationObject:C(n)},type:"public-key"}}function $(e){if(!e.response)throw f("UNKNOWN_ERROR","Credential response is missing",{credential:e});let r=e.response;if(!qe(r))throw f("UNKNOWN_ERROR","Invalid credential response structure",{response:r});if(!("authenticatorData"in r)||!("signature"in r))throw f("UNKNOWN_ERROR","Invalid credential response structure for auth: authenticatorData or signature is missing",{response:r});let t=r.clientDataJSON,n=r.authenticatorData,s=r.signature,i=r.userHandle;return{id:e.id,rawId:C(e.rawId),response:{authenticatorData:C(n),clientDataJSON:C(t),signature:C(s),...i&&{userHandle:C(i)}},type:"public-key"}}function N(){try{return!(typeof navigator>"u"||!navigator.credentials||typeof PublicKeyCredential>"u")}catch{return!1}}async function br(){try{return!N()||typeof PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable!="function"?!1:await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}async function Ve(){let e=N(),r=await br();return{isPasskeySupported:e,platformAuthenticatorAvailable:r,recommendedFlow:e?"passkey":"fallback"}}function k(e,r="create"){if(!e||typeof e!="object"||!("id"in e)||!("rawId"in e)||!("response"in e))throw Ue(r)}async function q(e){let{operation:r,eventEmitter:t,start:n,createOptions:s,invoke:i,finish:a}=e;try{if(t.emit("start",{type:"start",operation:r}),!N()){let m=Ne();return t.emit("error",{type:"error",error:m}),l(m)}let c=await n();if(!c.ok)return t.emit("error",{type:"error",error:c.error}),l(c.error);let R=s(c.value);if(!R.ok)return t.emit("error",{type:"error",error:R.error}),l(R.error);let v=await i(R.value);if(!v){let m=h("credential",`${r==="register"?"creation":"retrieval"} failed`);return t.emit("error",{type:"error",error:m}),l(m)}try{k(v)}catch(m){let A=b(m);return t.emit("error",{type:"error",error:A}),l(A)}let y=await a(c.value,v);return y.ok?(t.emit("success",{type:"success",operation:r}),d(y.value)):(t.emit("error",{type:"error",error:y.error}),l(y.error))}catch(c){let R=b(c);return t.emit("error",{type:"error",error:R}),l(R)}}function M(e,r){try{W(e.challenge,"challenge"),W(e.user.id,"user.id");let t=w(e.challenge),n=w(e.user.id),s={userVerification:"preferred"};e.authenticatorSelection&&(s={...e.authenticatorSelection}),r&&(s={...s,authenticatorAttachment:r});let i={rp:{id:e.rp.id,name:e.rp.name},user:{id:n,name:e.user.name,displayName:e.user.displayName},challenge:t,pubKeyCredParams:e.pubKeyCredParams,...e.timeout!==void 0&&{timeout:e.timeout},attestation:"none",authenticatorSelection:s,...e.excludeCredentials&&{excludeCredentials:e.excludeCredentials.map(a=>({id:w(a.id),type:a.type,...a.transports&&{transports:a.transports}}))}};return d({publicKey:i})}catch(t){return l(b(t))}}function _e(e,r){try{W(e.challenge,"challenge");let t=w(e.challenge);return d({publicKey:{challenge:t,rpId:e.rpId,...e.timeout!==void 0&&{timeout:e.timeout},userVerification:e.userVerification??"preferred",...e.allowCredentials&&{allowCredentials:e.allowCredentials.map(n=>({id:w(n.id),type:n.type,...n.transports&&{transports:n.transports}}))}},...r!==void 0&&{mediation:r}})}catch(t){return l(b(t))}}async function We(e,r,t){let n=e.externalUserId??e.external_user_id;if(!n||typeof n!="string"||n.trim()===""){let s=h("externalUserId","must be a non-empty string");return t.emit("error",{type:"error",error:s}),l(s)}return q({operation:"register",eventEmitter:t,start:()=>r.startRegister({external_user_id:n}),createOptions:s=>M(s.challenge,e.authenticatorType),invoke:async s=>{let i={...s,...e.signal&&{signal:e.signal}};return navigator.credentials.create(i)},finish:async(s,i)=>{let a=await r.finishRegister({session_id:s.session_id,credential:S(i)});return a.ok?d({success:!0,credentialId:a.value.credential_id,credential_id:a.value.credential_id,status:a.value.status,sessionToken:a.value.session_token,user:{userId:a.value.user.user_id,externalUserId:a.value.user.external_user_id,email:a.value.user.email,metadata:a.value.user.metadata}}):l(a.error)}})}async function Be(e,r,t){let n=e.externalUserId??e.external_user_id,s=n!==void 0&&typeof n=="string"&&n.trim()!=="";return q({operation:"authenticate",eventEmitter:t,start:()=>r.startAuth(s?{external_user_id:n.trim()}:{}),createOptions:i=>_e(i.challenge,e.mediation),invoke:async i=>{let a={...i,...e.signal&&{signal:e.signal}};return navigator.credentials.get(a)},finish:async(i,a)=>{let c=await r.finishAuthentication({session_id:i.session_id,credential:$(a)});return c.ok?d({authenticated:c.value.authenticated,sessionToken:c.value.session_token,user:{userId:c.value.user.user_id,externalUserId:c.value.user.external_user_id,email:c.value.user.email,metadata:c.value.user.metadata},signals:c.value.signals}):l(c.error)}})}var _r=2e3,Tr=60,X=class{constructor(r){this.apiClient=r}async startFlow(r){let t=await this.apiClient.startOnboarding({user_role:r.user_role});if(!t.ok)return l(t.error);let{session_id:n}=t.value;for(let s=0;s<Tr;s++){await new Promise(R=>setTimeout(R,_r));let i=await this.apiClient.getOnboardingStatus(n);if(!i.ok)return l(i.error);let a=i.value.status,c=i.value.onboarding_url;if(a==="pending_passkey"){let R=await this.apiClient.getOnboardingRegister(n);if(!R.ok)return l(R.error);let v=R.value;if(!v.challenge)return l(f("NOT_SUPPORTED","Onboarding requires user action - complete passkey registration at the provided onboarding_url",{onboarding_url:c}));let y=M(v.challenge);if(!y.ok)return l(y.error);let m;try{m=await navigator.credentials.create(y.value)}catch(I){return l(b(I))}try{k(m,"create")}catch(I){return l(b(I))}let A;try{A=S(m)}catch(I){return l(b(I))}let E=await this.apiClient.registerOnboardingPasskey(n,{credential:A,challenge:v.challenge.challenge});return E.ok?await this.apiClient.completeOnboarding(n,{company_name:r.company_name}):l(E.error)}if(a==="completed")return await this.apiClient.completeOnboarding(n,{company_name:r.company_name})}return l(f("TIMEOUT","Onboarding timed out"))}};var Ar=2e3,Ir=60,z=class{constructor(r){this.apiClient=r}async init(){return this.apiClient.initCrossDeviceAuth()}async initRegistration(r){return this.apiClient.initCrossDeviceRegistration(r)}async waitForSession(r,t){for(let n=0;n<Ir;n++){if(t?.aborted)return l(f("ABORT_ERROR","Operation aborted by user or timeout"));let s=await this.apiClient.getCrossDeviceStatus(r);if(!s.ok)return l(s.error);if(s.value.status==="completed")return!s.value.session_token||!s.value.user_id?l(f("UNKNOWN_ERROR","Missing data in completed session")):d({session_token:s.value.session_token,user_id:s.value.user_id});if(t?.aborted)return l(f("ABORT_ERROR","Operation aborted by user or timeout"));if(await new Promise(i=>{let a=setTimeout(()=>{i(null),t?.removeEventListener("abort",c)},Ar),c=()=>{clearTimeout(a),i(null)};t?.addEventListener("abort",c)}),t?.aborted)return l(f("ABORT_ERROR","Operation aborted by user or timeout"))}return l(f("TIMEOUT","Cross-device authentication timed out"))}async approve(r){let t=await this.apiClient.getCrossDeviceContext(r);if(!t.ok)return l(t.error);let n=t.value;return n.type==="registration"?this.executeRegistrationApproval(r,n):this.executeAuthApproval(r,n)}async executeRegistrationApproval(r,t){let n=M(t.options);if(!n.ok)return l(n.error);let s;try{s=await navigator.credentials.create(n.value)}catch(a){return l(b(a))}try{k(s,"create")}catch(a){return l(b(a))}let i;try{i=S(s)}catch(a){return l(b(a))}return this.apiClient.verifyCrossDeviceRegistration({session_id:r,credential:i})}async executeAuthApproval(r,t){let n=_e(t.options);if(!n.ok)return l(n.error);let s;try{s=await navigator.credentials.get(n.value)}catch(a){return l(b(a))}try{k(s,"get")}catch(a){return l(b(a))}let i;try{i=$(s)}catch(a){return l(b(a))}return this.apiClient.verifyCrossDeviceAuth({session_id:r,credential:i})}};var J=class{handlers;constructor(){this.handlers=new Map}on(r,t){let n=this.handlers.get(r);return n||(n=new Set,this.handlers.set(r,n)),n.add(t),()=>{this.off(r,t)}}off(r,t){let n=this.handlers.get(r);n&&(n.delete(t),n.size===0&&this.handlers.delete(r))}emit(r,t){let n=this.handlers.get(r);n&&n.forEach(s=>{try{s(t)}catch{}})}removeAllListeners(){this.handlers.clear()}};async function He(e,r,t){let n=e.externalUserId??e.external_user_id;if(!n||typeof n!="string"||n.trim()===""){let s=h("externalUserId","must be a non-empty string");return t.emit("error",{type:"error",error:s}),l(s)}if(!e.otp||typeof e.otp!="string"||e.otp.trim().length!==6){let s=h("otp","must be a 6-digit string");return t.emit("error",{type:"error",error:s}),l(s)}return q({operation:"register",eventEmitter:t,start:()=>r.verifyAccountRecoveryOtp(n,e.otp),createOptions:s=>M(s.challenge),invoke:async s=>navigator.credentials.create(s),finish:async(s,i)=>{let a=await r.completeAccountRecovery(s.recovery_session_id,S(i));return a.ok?d({success:!0,credentialId:a.value.credential_id,status:a.value.status,sessionToken:a.value.session_token,user:{userId:a.value.user.user_id,externalUserId:a.value.user.external_user_id,email:a.value.user.email,metadata:a.value.user.metadata}}):l(a.error)}})}var Te="https://api.trymellonauth.com",Ye="https://api.trymellonauth.com/v1/telemetry";var Ge="trymellon_sandbox_session_token_v1";function $e(e){return{async send(r){let t=JSON.stringify(r);if(typeof navigator<"u"&&typeof navigator.sendBeacon=="function"){navigator.sendBeacon(e,t);return}typeof fetch<"u"&&await fetch(e,{method:"POST",body:t,headers:{"Content-Type":"application/json"},keepalive:!0})}}}function Ae(e,r){return{event:e,latencyMs:r,ok:!0}}var Z=class e{sandbox;sandboxToken;apiClient;eventEmitter;telemetrySender;crossDeviceManager;onboarding;static create(r){try{let t=r.appId,n=r.publishableKey;if(!t||typeof t!="string"||t.trim()==="")return l(h("appId","must be a non-empty string"));if(!n||typeof n!="string"||n.trim()==="")return l(h("publishableKey","must be a non-empty string"));let s=r.apiBaseUrl??Te;ie(s,"apiBaseUrl");let i=r.timeoutMs??3e4;return P(i,"timeoutMs",1e3,3e5),r.maxRetries!==void 0&&P(r.maxRetries,"maxRetries",0,10),r.retryDelayMs!==void 0&&P(r.retryDelayMs,"retryDelayMs",100,1e4),d(new e(r))}catch(t){return ne(t)?l(t):l(h("config",t.message))}}constructor(r){this.sandbox=r.sandbox===!0,this.sandboxToken=this.sandbox&&r.sandboxToken!=null&&r.sandboxToken!==""?r.sandboxToken:Ge;let t=r.appId,n=r.publishableKey;if(!t||typeof t!="string"||t.trim()==="")throw h("appId","must be a non-empty string");if(!n||typeof n!="string"||n.trim()==="")throw h("publishableKey","must be a non-empty string");let s=r.apiBaseUrl??Te;ie(s,"apiBaseUrl");let i=r.timeoutMs??3e4;P(i,"timeoutMs",1e3,3e5),r.maxRetries!==void 0&&P(r.maxRetries,"maxRetries",0,10),r.retryDelayMs!==void 0&&P(r.retryDelayMs,"retryDelayMs",100,1e4);let a=r.maxRetries??3,c=r.retryDelayMs??1e3,R=new G(i,a,c,r.logger),v=r.origin??(typeof window<"u"&&window?.location?.origin?window.location.origin:void 0),y={"X-App-Id":t.trim(),Authorization:`Bearer ${n.trim()}`,...v&&{Origin:v}};this.apiClient=new Y(R,s,y),this.onboarding=new X(this.apiClient),this.crossDeviceManager=new z(this.apiClient),this.eventEmitter=new J,r.enableTelemetry&&(this.telemetrySender=r.telemetrySender??$e(r.telemetryEndpoint??Ye))}static isSupported(){return N()}async register(r){if(this.sandbox){let s=r.externalUserId??r.external_user_id??"sandbox";return Promise.resolve(d({success:!0,credentialId:"",status:"sandbox",sessionToken:this.sandboxToken,user:{userId:"sandbox-user",externalUserId:typeof s=="string"?s:"sandbox"}}))}let t=Date.now(),n=await We(r,this.apiClient,this.eventEmitter);return n.ok&&this.telemetrySender&&this.telemetrySender.send(Ae("register",Date.now()-t)).catch(()=>{}),n}async authenticate(r){if(this.sandbox){let s=r.externalUserId??r.external_user_id??"sandbox";return Promise.resolve(d({authenticated:!0,sessionToken:this.sandboxToken,user:{userId:"sandbox-user",externalUserId:typeof s=="string"?s:"sandbox"}}))}let t=Date.now(),n=await Be(r,this.apiClient,this.eventEmitter);return n.ok&&this.telemetrySender&&this.telemetrySender.send(Ae("authenticate",Date.now()-t)).catch(()=>{}),n}async validateSession(r){return this.sandbox&&r===this.sandboxToken?Promise.resolve(d({valid:!0,user_id:"sandbox-user",external_user_id:"sandbox",tenant_id:"sandbox-tenant",app_id:"sandbox-app"})):this.apiClient.validateSession(r)}async getStatus(){return Ve()}on(r,t){return this.eventEmitter.on(r,t)}version(){return"1.6.1"}fallback={email:{start:async r=>this.apiClient.startEmailFallback(r),verify:async r=>this.apiClient.verifyEmailCode(r.userId,r.code)}};auth={crossDevice:{init:()=>this.crossDeviceManager.init(),initRegistration:r=>this.crossDeviceManager.initRegistration(r),waitForSession:(r,t)=>this.crossDeviceManager.waitForSession(r,t),approve:r=>this.crossDeviceManager.approve(r)},recoverAccount:async r=>He(r,this.apiClient,this.eventEmitter)}};var Q=new xr("TRYMELLON_CONFIG"),tr,Ie;tr=[Sr({providedIn:"root"})];var U=class{config=Pr(Q,{optional:!0});_client=null;get client(){if(this._client==null){if(this.config==null)throw new Error("TryMellonService: provide TRYMELLON_CONFIG (e.g. via provideTryMellonConfig(config))");this._client=new Z(this.config)}return this._client}};Ie=ke(null),U=we(Ie,0,"TryMellonService",tr,U),De(Ie,1,U);function _n(e){return{provide:Q,useValue:e}}export{Q as TRYMELLON_CONFIG,U as TryMellonService,_n as provideTryMellonConfig};
3
3
  //# sourceMappingURL=angular.js.map