@trymellon/js 1.6.1 → 1.6.2

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 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};
2
+ var sr=Object.create;var ne=Object.defineProperty;var ir=Object.getOwnPropertyDescriptor;var Pe=(e,r)=>(r=Symbol[e])?r:Symbol.for("Symbol."+e),j=e=>{throw TypeError(e)};var or=(e,r,t)=>r in e?ne(e,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[r]=t;var Se=(e,r)=>ne(e,"name",{value:r,configurable:!0});var Me=e=>[,,,sr(e?.[Pe("metadata")]??null)],De=["class","method","getter","setter","accessor","field","value","get","set"],K=e=>e!==void 0&&typeof e!="function"?j("Function expected"):e,ar=(e,r,t,n,s)=>({kind:De[e],name:r,metadata:n,addInitializer:i=>t._?j("Already initialized"):s.push(K(i||null))}),lr=(e,r)=>or(r,Pe("metadata"),e[3]),we=(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},Ne=(e,r,t,n,s,i)=>{var a,d,R,v,y,g=r&7,T=!!(r&8),I=!!(r&16),C=g>3?e.length+1:g?T?1:2:0,A=De[g+5],P=g>3&&(e[C-1]=[]),W=e[C]||(e[C]=[]),E=g&&(!I&&!T&&(s=s.prototype),g<5&&(g>3||!I)&&ir(g<4?s:{get[t](){return ke(this,i)},set[t](b){return xe(this,i,b)}},t));g?I&&g<4&&Se(i,(g>2?"set ":g>1?"get ":"")+t):Se(s,t);for(var O=n.length-1;O>=0;O--)v=ar(g,t,R={},e[3],W),g&&(v.static=T,v.private=I,y=v.access={has:I?b=>ur(s,b):b=>t in b},g^3&&(y.get=I?b=>(g^1?ke:pr)(b,s,g^4?i:E.get):b=>b[t]),g>2&&(y.set=I?(b,te)=>xe(b,s,te,g^4?i:E.set):(b,te)=>b[t]=te)),d=(0,n[O])(g?g<4?I?i:E[A]:g>4?void 0:{get:E.get,set:E.set}:s,v),R._=1,g^4||d===void 0?K(d)&&(g>4?P.unshift(d):g?I?i=d:E[A]=d:s=d):typeof d!="object"||d===null?j("Object expected"):(K(a=d.get)&&(E.get=a),K(a=d.set)&&(E.set=a),K(a=d.init)&&P.unshift(a));return g||lr(e,s),E&&ne(s,t,E),I?g^4?i:E:s};var se=(e,r,t)=>r.has(e)||j("Cannot "+t),ur=(e,r)=>Object(r)!==r?j('Cannot use the "in" operator on this value'):e.has(r),ke=(e,r,t)=>(se(e,r,"read from private field"),t?t.call(e):r.get(e));var xe=(e,r,t,n)=>(se(e,r,"write to private field"),n?n.call(e,t):r.set(e,t),t),pr=(e,r,t)=>(se(e,r,"access private method"),t);import{Injectable as Pr,InjectionToken as Mr,inject as Dr}from"@angular/core";var c=e=>({ok:!0,value:e}),l=e=>({ok:!1,error:e});var B=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)}},cr={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 B(e,r??cr[e],t)}function ie(e){return e instanceof B||typeof e=="object"&&e!==null&&"isTryMellonError"in e&&e.isTryMellonError===!0}function Ue(){return f("NOT_SUPPORTED")}function h(e,r){return f("INVALID_ARGUMENT",`Invalid argument: ${e} - ${r}`,{field:e,reason:r})}function Fe(e){return f("UNKNOWN_ERROR",`Failed to ${e} credential`,{operation:e})}function oe(e){return f("NOT_SUPPORTED",`No base64 ${e==="encode"?"encoding":"decoding"} available`,{type:e})}function ae(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 ie(t)?t:h(r,"must be a valid URL")}}function M(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 H(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 dr={NotAllowedError:"USER_CANCELLED",AbortError:"ABORTED",NotSupportedError:"NOT_SUPPORTED",SecurityError:"NOT_SUPPORTED",InvalidStateError:"UNKNOWN_ERROR",UnknownError:"UNKNOWN_ERROR"};function q(e){if(typeof e!="string")return"UNKNOWN_ERROR";let r=e.toLowerCase().trim();return{challenge_mismatch:"CHALLENGE_MISMATCH",session_expired:"SESSION_EXPIRED",unauthorized:"SESSION_EXPIRED",validation_error:"INVALID_ARGUMENT",invalid_argument:"INVALID_ARGUMENT",user_not_found:"SESSION_EXPIRED",passkey_not_found:"PASSKEY_NOT_FOUND"}[r]??"UNKNOWN_ERROR"}function _(e){if(e instanceof DOMException){let r=e.name,t=e.message||"WebAuthn operation failed",n=dr[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 m(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function u(e){return typeof e=="string"}function k(e){return typeof e=="number"&&Number.isFinite(e)}function G(e){return typeof e=="boolean"}function N(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 Le(e,r){return!m(e)||!u(e.name)||!u(e.id)?o("Invalid API response: challenge.rp must have name and id strings",{originalData:r}):c(!0)}function Ke(e,r){return!m(e)||!u(e.id)||!u(e.name)||!u(e.displayName)?o("Invalid API response: challenge.user must have id, name, displayName strings",{originalData:r}):c(!0)}function je(e,r){if(!N(e))return o("Invalid API response: challenge.pubKeyCredParams must be array",{originalData:r});for(let t of e)if(!m(t)||t.type!=="public-key"||!k(t.alg))return o("Invalid API response: pubKeyCredParams items must have type and alg",{originalData:r});return c(!0)}function le(e,r){if(!m(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}):c({user_id:t,external_user_id:n,...s!==void 0&&{email:s},...i!==void 0&&{metadata:i}})}function ue(e){if(!m(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(!m(t))return o("Invalid API response: challenge must be object",{field:"challenge",originalData:e});let n=Le(p(t,"rp"),e);if(!n.ok)return n;let s=Ke(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=je(p(t,"pubKeyCredParams"),e);if(!a.ok)return a;let d=t.timeout;if(d!==void 0&&!k(d))return o("Invalid API response: challenge.timeout must be number",{originalData:e});let R=t.excludeCredentials;if(R!==void 0){if(!N(R))return o("Invalid API response: excludeCredentials must be array",{originalData:e});for(let y of R)if(!m(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&&!m(v)?o("Invalid API response: authenticatorSelection must be object",{originalData:e}):c({session_id:r,challenge:{rp:t.rp,user:t.user,challenge:i,pubKeyCredParams:t.pubKeyCredParams,...d!==void 0&&{timeout:d},...R!==void 0&&{excludeCredentials:R},...v!==void 0&&{authenticatorSelection:v}}})}function pe(e){if(!m(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(!m(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&&!N(i))return o("Invalid API response: allowCredentials must be array",{originalData:e});if(i){for(let R of i)if(!m(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&&!k(a))return o("Invalid API response: challenge.timeout must be number",{originalData:e});let d=t.userVerification;return d!==void 0&&!["required","preferred","discouraged"].includes(String(d))?o("Invalid API response: userVerification must be required|preferred|discouraged",{originalData:e}):c({session_id:r,challenge:{challenge:n,rpId:s,allowCredentials:i??[],...a!==void 0&&{timeout:a},...d!==void 0&&{userVerification:d}}})}function ce(e){if(!m(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=le(s,e);return i.ok?c({credential_id:r,status:t,session_token:n,user:i.value}):o(i.error.message,{originalData:e})}function de(e){if(!m(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(!G(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=le(n,e);return i.ok?s!==void 0&&!m(s)?o("Invalid API response: signals must be object",{originalData:e}):c({authenticated:r,session_token:t,user:i.value,signals:s}):o(i.error.message,{originalData:e})}function me(e){if(!m(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 G(r)?u(t)?u(n)?u(s)?u(i)?c({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 ge(e){if(!m(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"sessionToken");return u(r)?c({sessionToken:r}):o("Invalid API response: sessionToken must be string",{field:"sessionToken",originalData:e})}var mr=["pending_passkey","pending_data","completed"],gr=["pending_data","completed"];function Re(e){if(!m(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)?k(n)?c({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 ye(e){if(!m(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)||!mr.includes(r)?o("Invalid API response: status must be pending_passkey|pending_data|completed",{field:"status",originalData:e}):u(t)?k(n)?c({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 fe(e){if(!m(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=Rr(s);if(!a.ok)return a;i=a.value}return c({session_id:r,status:"pending_passkey",onboarding_url:n,...i!==void 0&&{challenge:i}})}function Rr(e){if(!m(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(!m(r)||!u(r.name)||!u(r.id))return o("Invalid API response: challenge.rp must have name and id",{originalData:e});if(!m(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(!N(s))return o("Invalid API response: challenge.pubKeyCredParams must be array",{originalData:e});for(let i of s)if(!m(i)||i.type!=="public-key"||!k(i.alg))return o("Invalid API response: pubKeyCredParams items must have type and alg",{originalData:e});return c({rp:r,user:t,challenge:n,pubKeyCredParams:s})}function ve(e){if(!m(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)||!gr.includes(t)?o("Invalid API response: status must be pending_data|completed",{originalData:e}):u(n)?u(s)?c({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 he(e){if(!m(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}):c({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 yr(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 fr(e){if(!e||typeof e!="object")return!1;let r=e;return typeof r.challenge=="string"&&typeof r.rpId=="string"}function Y(e){if(!m(e))return o("Invalid API response: expected object",{originalData:e});let r="resultado"in e&&m(e.resultado)?e.resultado:e,t=r.session_id,n=r.qr_url,s=r.expires_at;return!u(t)||!u(n)||!u(s)?o("Invalid API response: missing required fields",{originalData:e}):c({session_id:t,qr_url:n,expires_at:s})}function Ee(e){if(!m(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}):c({status:r,user_id:e.user_id,session_token:e.session_token})}function be(e){if(!m(e))return o("Invalid API response: expected object",{originalData:e});let r=e.type,t=r==="registration"?"registration":"auth",n=e.options;return m(n)?t==="registration"?yr(n)?c({type:"registration",options:n}):o("Invalid API response: registration options must have challenge, rp, user, pubKeyCredParams",{originalData:e}):fr(n)?c({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 _e(e){if(!m(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"challenge"),t=p(e,"recovery_session_id");return m(r)?u(t)?c({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 Te(e){if(!m(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(!m(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 c({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:m(a.metadata)?a.metadata:void 0}})}var X=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,ue)}async startAuth(r){return this.post("/v1/passkeys/auth/start",r,pe)}async finishRegister(r){return this.post("/v1/passkeys/register/finish",r,ce)}async finishAuthentication(r){return this.post("/v1/passkeys/auth/finish",r,de)}async validateSession(r){return this.get("/v1/sessions/validate",me,{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?c(void 0):l(n.error)}async verifyEmailCode(r,t){return this.post("/v1/fallback/email/verify",{userId:r,code:t},ge)}async startOnboarding(r){return this.post("/onboarding/start",r,Re)}async getOnboardingStatus(r){return this.get(`/onboarding/${r}/status`,ye)}async getOnboardingRegister(r){return this.get(`/onboarding/${r}/register`,fe)}async registerOnboardingPasskey(r,t){return this.post(`/onboarding/${r}/register-passkey`,t,ve)}async completeOnboarding(r,t){return this.post(`/onboarding/${r}/complete`,t,he)}async initCrossDeviceAuth(){return this.post("/v1/auth/cross-device/init",{},Y)}async initCrossDeviceRegistration(r){return this.post("/v1/auth/cross-device/init-registration",{external_user_id:r.externalUserId},Y)}async getCrossDeviceStatus(r){return this.get(`/v1/auth/cross-device/status/${r}`,Ee)}async getCrossDeviceContext(r){return this.get(`/v1/auth/cross-device/context/${r}`,be)}async verifyCrossDeviceAuth(r){let t=`${this.baseUrl}/v1/auth/cross-device/verify`,n=await this.httpClient.post(t,r,this.mergeHeaders());return n.ok?c(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?c(void 0):l(n.error)}async verifyAccountRecoveryOtp(r,t){return this.post("/v1/users/recovery/verify",{external_id:r,otp:t},_e)}async completeAccountRecovery(r,t){return this.post("/v1/users/recovery/complete",{recovery_session_id:r,credential:t},Te)}};function vr(e){return typeof e=="object"&&e!==null&&e.ok===!0&&"resultado"in e}function hr(e){if(typeof e!="object"||e===null)return!1;let r=e;if(r.ok!==!1||!r.error||typeof r.error!="object")return!1;let t=r.error;return typeof t.code=="string"&&typeof t.message=="string"}var Er=3e4;function br(){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 qe(e,r){let t=r*Math.pow(2,e);return Math.min(t,Er)}function _r(e,r){return e!=="GET"?!1:r>=500||r===429}var $=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=br(),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 d=0;d<=this.maxRetries;d++)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 C;try{C=await y.json()}catch{}let A,P;if(hr(C))A=C.error.message,P=q(C.error.code);else{let E=C,O=E?.error;if(typeof O=="object"&&O!==null&&"code"in O&&typeof O.code=="string")A=O.message??E?.message??y.statusText,P=q(O.code);else{A=E?.message??y.statusText;let b=E?.error;P=typeof b=="string"?q(b):b===void 0?"NETWORK_FAILURE":q(String(b))}}let W=f(P,A,{requestId:s,status:y.status,statusText:y.statusText,data:C});if(_r(n,y.status)&&d<this.maxRetries){a=W,await new Promise(E=>setTimeout(E,qe(d,this.retryDelayMs)));continue}return l(W)}if(y.status===204)return c(void 0);if(y.headers.get("content-length")==="0")return c(void 0);let T=await y.json();if(vr(T))return c(T.resultado);let I=T;return typeof T=="object"&&T!==null&&I.ok===!0&&!("resultado"in I)?c(void 0):c(T)}finally{clearTimeout(v)}}catch(R){if(a=R,n==="GET"&&d<this.maxRetries)await new Promise(y=>setTimeout(y,qe(d,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 S(e){let r=new Uint8Array(e),t=Array.from(r,s=>String.fromCharCode(s)).join("");if(typeof globalThis.btoa>"u")throw oe("encode");return globalThis.btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Tr(e){if(typeof globalThis.atob>"u")throw oe("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 U(e){let r=Tr(e),t=new ArrayBuffer(r.length);return new Uint8Array(t).set(r),t}function Ve(e){return e!==null&&typeof e=="object"&&"clientDataJSON"in e&&e.clientDataJSON instanceof ArrayBuffer}function x(e){if(!e.response)throw f("UNKNOWN_ERROR","Credential response is missing",{credential:e});let r=e.response;if(!Ve(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:S(e.rawId),response:{clientDataJSON:S(t),attestationObject:S(n)},type:"public-key"}}function z(e){if(!e.response)throw f("UNKNOWN_ERROR","Credential response is missing",{credential:e});let r=e.response;if(!Ve(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:S(e.rawId),response:{authenticatorData:S(n),clientDataJSON:S(t),signature:S(s),...i&&{userHandle:S(i)}},type:"public-key"}}function F(){try{return!(typeof navigator>"u"||!navigator.credentials||typeof PublicKeyCredential>"u")}catch{return!1}}async function Ir(){try{return!F()||typeof PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable!="function"?!1:await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}async function We(){let e=F(),r=await Ir();return{isPasskeySupported:e,platformAuthenticatorAvailable:r,recommendedFlow:e?"passkey":"fallback"}}function D(e,r="create"){if(!e||typeof e!="object"||!("id"in e)||!("rawId"in e)||!("response"in e))throw Fe(r)}async function V(e){let{operation:r,eventEmitter:t,start:n,createOptions:s,invoke:i,finish:a}=e;try{if(t.emit("start",{type:"start",operation:r}),!F()){let g=Ue();return t.emit("error",{type:"error",error:g}),l(g)}let d=await n();if(!d.ok)return t.emit("error",{type:"error",error:d.error}),l(d.error);let R=s(d.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 g=h("credential",`${r==="register"?"creation":"retrieval"} failed`);return t.emit("error",{type:"error",error:g}),l(g)}try{D(v)}catch(g){let T=_(g);return t.emit("error",{type:"error",error:T}),l(T)}let y=await a(d.value,v);return y.ok?(t.emit("success",{type:"success",operation:r}),c(y.value)):(t.emit("error",{type:"error",error:y.error}),l(y.error))}catch(d){let R=_(d);return t.emit("error",{type:"error",error:R}),l(R)}}function w(e,r){try{H(e.challenge,"challenge"),H(e.user.id,"user.id");let t=U(e.challenge),n=U(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:U(a.id),type:a.type,...a.transports&&{transports:a.transports}}))}};return c({publicKey:i})}catch(t){return l(_(t))}}function Ie(e,r){try{H(e.challenge,"challenge");let t=U(e.challenge);return c({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:U(n.id),type:n.type,...n.transports&&{transports:n.transports}}))}},...r!==void 0&&{mediation:r}})}catch(t){return l(_(t))}}async function Be(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 V({operation:"register",eventEmitter:t,start:()=>r.startRegister({external_user_id:n}),createOptions:s=>w(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:x(i)});return a.ok?c({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 He(e,r,t){let n=e.externalUserId??e.external_user_id,s=n!==void 0&&typeof n=="string"&&n.trim()!=="";return V({operation:"authenticate",eventEmitter:t,start:()=>r.startAuth(s?{external_user_id:n.trim()}:{}),createOptions:i=>Ie(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 d=await r.finishAuthentication({session_id:i.session_id,credential:z(a)});return d.ok?c({authenticated:d.value.authenticated,sessionToken:d.value.session_token,user:{userId:d.value.user.user_id,externalUserId:d.value.user.external_user_id,email:d.value.user.email,metadata:d.value.user.metadata},signals:d.value.signals}):l(d.error)}})}var Ar=2e3,Cr=60,J=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<Cr;s++){await new Promise(R=>setTimeout(R,Ar));let i=await this.apiClient.getOnboardingStatus(n);if(!i.ok)return l(i.error);let a=i.value.status,d=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:d}));let y=w(v.challenge);if(!y.ok)return l(y.error);let g;try{g=await navigator.credentials.create(y.value)}catch(A){return l(_(A))}try{D(g,"create")}catch(A){return l(_(A))}let T;try{T=x(g)}catch(A){return l(_(A))}let I=await this.apiClient.registerOnboardingPasskey(n,{credential:T,challenge:v.challenge.challenge});return I.ok?await this.apiClient.completeOnboarding(n,{company_name:r.company_name}):l(I.error)}if(a==="completed")return await this.apiClient.completeOnboarding(n,{company_name:r.company_name})}return l(f("TIMEOUT","Onboarding timed out"))}};var Or=2e3,Sr=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<Sr;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")):c({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",d)},Or),d=()=>{clearTimeout(a),i(null)};t?.addEventListener("abort",d)}),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=w(t.options);if(!n.ok)return l(n.error);let s;try{s=await navigator.credentials.create(n.value)}catch(a){return l(_(a))}try{D(s,"create")}catch(a){return l(_(a))}let i;try{i=x(s)}catch(a){return l(_(a))}return this.apiClient.verifyCrossDeviceRegistration({session_id:r,credential:i})}async executeAuthApproval(r,t){let n=Ie(t.options);if(!n.ok)return l(n.error);let s;try{s=await navigator.credentials.get(n.value)}catch(a){return l(_(a))}try{D(s,"get")}catch(a){return l(_(a))}let i;try{i=z(s)}catch(a){return l(_(a))}return this.apiClient.verifyCrossDeviceAuth({session_id:r,credential:i})}};var Q=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);if(n)for(let s of n)try{s(t)}catch{}}removeAllListeners(){this.handlers.clear()}};async function Ge(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 V({operation:"register",eventEmitter:t,start:()=>r.verifyAccountRecoveryOtp(n,e.otp),createOptions:s=>w(s.challenge),invoke:async s=>navigator.credentials.create(s),finish:async(s,i)=>{let a=await r.completeAccountRecovery(s.recovery_session_id,x(i));return a.ok?c({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 Ae="https://api.trymellonauth.com",Ye="https://api.trymellonauth.com/v1/telemetry";var Xe="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 Ce(e,r){return{event:e,latencyMs:r,ok:!0}}var ee=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??Ae;ae(s,"apiBaseUrl");let i=r.timeoutMs??3e4;return M(i,"timeoutMs",1e3,3e5),r.maxRetries!==void 0&&M(r.maxRetries,"maxRetries",0,10),r.retryDelayMs!==void 0&&M(r.retryDelayMs,"retryDelayMs",100,1e4),c(new e(r))}catch(t){return ie(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:Xe;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??Ae;ae(s,"apiBaseUrl");let i=r.timeoutMs??3e4;M(i,"timeoutMs",1e3,3e5),r.maxRetries!==void 0&&M(r.maxRetries,"maxRetries",0,10),r.retryDelayMs!==void 0&&M(r.retryDelayMs,"retryDelayMs",100,1e4);let a=r.maxRetries??3,d=r.retryDelayMs??1e3,R=new $(i,a,d,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 X(R,s,y),this.onboarding=new J(this.apiClient),this.crossDeviceManager=new Z(this.apiClient),this.eventEmitter=new Q,r.enableTelemetry&&(this.telemetrySender=r.telemetrySender??$e(r.telemetryEndpoint??Ye))}static isSupported(){return F()}async register(r){if(this.sandbox){let s=r.externalUserId??r.external_user_id??"sandbox";return Promise.resolve(c({success:!0,credentialId:"",status:"sandbox",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(Ce("register",Date.now()-t)).catch(()=>{}),n}async authenticate(r){if(this.sandbox){let s=r.externalUserId??r.external_user_id??"sandbox";return Promise.resolve(c({authenticated:!0,sessionToken:this.sandboxToken,user:{userId:"sandbox-user",externalUserId:typeof s=="string"?s:"sandbox"}}))}let t=Date.now(),n=await He(r,this.apiClient,this.eventEmitter);return n.ok&&this.telemetrySender&&this.telemetrySender.send(Ce("authenticate",Date.now()-t)).catch(()=>{}),n}async validateSession(r){return this.sandbox&&r===this.sandboxToken?Promise.resolve(c({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 We()}on(r,t){return this.eventEmitter.on(r,t)}version(){return"1.6.2"}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=>Ge(r,this.apiClient,this.eventEmitter)}};var re=new Mr("TRYMELLON_CONFIG"),nr,Oe;nr=[Pr({providedIn:"root"})];var L=class{config=Dr(re,{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 ee(this.config)}return this._client}};Oe=Me(null),L=Ne(Oe,0,"TryMellonService",nr,L),we(Oe,1,L);function An(e){return{provide:re,useValue:e}}export{re as TRYMELLON_CONFIG,L as TryMellonService,An as provideTryMellonConfig};
3
3
  //# sourceMappingURL=angular.js.map