@trymellon/js 1.7.5 → 1.7.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -150,6 +150,8 @@ type RecoveryCompleteResponse = {
150
150
  metadata?: Record<string, unknown>;
151
151
  };
152
152
  credential_id: string;
153
+ /** Set when successUrl was passed and allowed by application allowlist. */
154
+ redirect_url?: string;
153
155
  };
154
156
  type RecoverAccountOptions = {
155
157
  /** The external user ID of the account being recovered. */
@@ -172,6 +174,8 @@ interface RecoverAccountResult {
172
174
  email?: string;
173
175
  metadata?: Record<string, unknown>;
174
176
  };
177
+ /** Set when successUrl was passed and allowed by application allowlist. */
178
+ redirectUrl?: string;
175
179
  }
176
180
  type OnboardingStartOptions = {
177
181
  user_role: 'maintainer' | 'app_user';
@@ -233,6 +237,8 @@ type CrossDeviceStatusResult = {
233
237
  status: 'pending' | 'authenticated' | 'completed';
234
238
  user_id?: string;
235
239
  session_token?: string;
240
+ /** Set when backend allows redirect; returned in GET cross-device/status when status=completed. */
241
+ redirect_url?: string;
236
242
  };
237
243
  /** Context for auth: request options (get). */
238
244
  type CrossDeviceContextAuth = {
@@ -364,7 +370,7 @@ interface AuthFinishResponse {
364
370
  email?: string;
365
371
  metadata?: Record<string, unknown>;
366
372
  };
367
- signals: {
373
+ signals?: {
368
374
  userVerification?: boolean;
369
375
  backupEligible?: boolean;
370
376
  backupStatus?: boolean;
@@ -593,6 +599,7 @@ declare class TryMellon {
593
599
  waitForSession: (sessionId: string, signal?: AbortSignal, pollingToken?: string | null) => Promise<Result<{
594
600
  session_token: string;
595
601
  user_id: string;
602
+ redirectUrl?: string;
596
603
  }, TryMellonError>>;
597
604
  getContext: (sessionId: string) => Promise<Result<CrossDeviceContextResult, TryMellonError>>;
598
605
  approve: (sessionId: string) => Promise<Result<void, TryMellonError>>;
package/dist/index.d.ts CHANGED
@@ -150,6 +150,8 @@ type RecoveryCompleteResponse = {
150
150
  metadata?: Record<string, unknown>;
151
151
  };
152
152
  credential_id: string;
153
+ /** Set when successUrl was passed and allowed by application allowlist. */
154
+ redirect_url?: string;
153
155
  };
154
156
  type RecoverAccountOptions = {
155
157
  /** The external user ID of the account being recovered. */
@@ -172,6 +174,8 @@ interface RecoverAccountResult {
172
174
  email?: string;
173
175
  metadata?: Record<string, unknown>;
174
176
  };
177
+ /** Set when successUrl was passed and allowed by application allowlist. */
178
+ redirectUrl?: string;
175
179
  }
176
180
  type OnboardingStartOptions = {
177
181
  user_role: 'maintainer' | 'app_user';
@@ -233,6 +237,8 @@ type CrossDeviceStatusResult = {
233
237
  status: 'pending' | 'authenticated' | 'completed';
234
238
  user_id?: string;
235
239
  session_token?: string;
240
+ /** Set when backend allows redirect; returned in GET cross-device/status when status=completed. */
241
+ redirect_url?: string;
236
242
  };
237
243
  /** Context for auth: request options (get). */
238
244
  type CrossDeviceContextAuth = {
@@ -364,7 +370,7 @@ interface AuthFinishResponse {
364
370
  email?: string;
365
371
  metadata?: Record<string, unknown>;
366
372
  };
367
- signals: {
373
+ signals?: {
368
374
  userVerification?: boolean;
369
375
  backupEligible?: boolean;
370
376
  backupStatus?: boolean;
@@ -593,6 +599,7 @@ declare class TryMellon {
593
599
  waitForSession: (sessionId: string, signal?: AbortSignal, pollingToken?: string | null) => Promise<Result<{
594
600
  session_token: string;
595
601
  user_id: string;
602
+ redirectUrl?: string;
596
603
  }, TryMellonError>>;
597
604
  getContext: (sessionId: string) => Promise<Result<CrossDeviceContextResult, TryMellonError>>;
598
605
  approve: (sessionId: string) => Promise<Result<void, TryMellonError>>;
@@ -1,3 +1,3 @@
1
- var TryMellon=(function(exports){'use strict';var p=e=>({ok:true,value:e}),u=e=>({ok:false,error:e});var D=class e extends Error{code;details;isTryMellonError=true;constructor(r,t,n){super(t),this.name="TryMellonError",this.code=r,this.details=n,Error.captureStackTrace&&Error.captureStackTrace(this,e);}},qe={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 R(e,r,t){return new D(e,r??qe[e],t)}function F(e){return e instanceof D||typeof e=="object"&&e!==null&&"isTryMellonError"in e&&e.isTryMellonError===true}function X(){return R("NOT_SUPPORTED")}function Ve(){return R("USER_CANCELLED")}function Be(e){return R("NETWORK_FAILURE",void 0,{cause:e?.message,originalError:e})}function We(){return R("TIMEOUT")}function y(e,r){return R("INVALID_ARGUMENT",`Invalid argument: ${e} - ${r}`,{field:e,reason:r})}function he(e){return R("UNKNOWN_ERROR",`Failed to ${e} credential`,{operation:e})}function G(e){return R("NOT_SUPPORTED",`No base64 ${e==="encode"?"encoding":"decoding"} available`,{type:e})}function z(e,r){try{let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")throw y(r,"must use http or https protocol")}catch(t){throw F(t)?t:y(r,"must be a valid URL")}}function O(e,r,t,n){if(!Number.isFinite(e))throw y(r,"must be a finite number");if(e<t||e>n)throw y(r,`must be between ${t} and ${n}`)}function L(e,r){if(typeof e!="string"||e.length===0)throw y(r,"must be a non-empty string");if(!/^[A-Za-z0-9_-]+$/.test(e))throw y(r,"must be a valid base64url string")}var He={NotAllowedError:"USER_CANCELLED",AbortError:"ABORTED",NotSupportedError:"NOT_SUPPORTED",SecurityError:"NOT_SUPPORTED",InvalidStateError:"UNKNOWN_ERROR",UnknownError:"UNKNOWN_ERROR"};function w(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 h(e){if(e instanceof DOMException){let r=e.name,t=e.message||"WebAuthn operation failed",n=He[r]??"UNKNOWN_ERROR";return R(n,t,{originalError:e})}return e instanceof Error?R("UNKNOWN_ERROR",e.message,{originalError:e}):R("UNKNOWN_ERROR","An unknown error occurred",{originalError:e})}function g(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function l(e){return typeof e=="string"}function T(e){return typeof e=="number"&&Number.isFinite(e)}function K(e){return typeof e=="boolean"}function S(e){return Array.isArray(e)}function o(e,r){return u(R("UNKNOWN_ERROR",e,{...r,originalData:r?.originalData}))}function c(e,r){return e[r]}function Ee(e,r){return !g(e)||!l(e.name)||!l(e.id)?o("Invalid API response: challenge.rp must have name and id strings",{originalData:r}):p(true)}function be(e,r){return !g(e)||!l(e.id)||!l(e.name)||!l(e.displayName)?o("Invalid API response: challenge.user must have id, name, displayName strings",{originalData:r}):p(true)}function _e(e,r){if(!S(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"||!T(t.alg))return o("Invalid API response: pubKeyCredParams items must have type and alg",{originalData:r});return p(true)}function Y(e,r){if(!g(e))return o("Invalid API response: user must be object",{field:"user",originalData:r});let t=c(e,"user_id"),n=c(e,"external_user_id");if(!l(t)||!l(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&&!l(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}):p({user_id:t,external_user_id:n,...s!==void 0&&{email:s},...i!==void 0&&{metadata:i}})}function J(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=c(e,"session_id");if(!l(r))return o("Invalid API response: session_id must be string",{field:"session_id",originalData:e});let t=c(e,"challenge");if(!g(t))return o("Invalid API response: challenge must be object",{field:"challenge",originalData:e});let n=Ee(c(t,"rp"),e);if(!n.ok)return n;let s=be(c(t,"user"),e);if(!s.ok)return s;let i=c(t,"challenge");if(!l(i))return o("Invalid API response: challenge.challenge must be string",{originalData:e});let a=_e(c(t,"pubKeyCredParams"),e);if(!a.ok)return a;let d=t.timeout;if(d!==void 0&&!T(d))return o("Invalid API response: challenge.timeout must be number",{originalData:e});let m=t.excludeCredentials;if(m!==void 0){if(!S(m))return o("Invalid API response: excludeCredentials must be array",{originalData:e});for(let f of m)if(!g(f)||f.type!=="public-key"||!l(f.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}):p({session_id:r,challenge:{rp:t.rp,user:t.user,challenge:i,pubKeyCredParams:t.pubKeyCredParams,...d!==void 0&&{timeout:d},...m!==void 0&&{excludeCredentials:m},...v!==void 0&&{authenticatorSelection:v}}})}function Z(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=c(e,"session_id");if(!l(r))return o("Invalid API response: session_id must be string",{field:"session_id",originalData:e});let t=c(e,"challenge");if(!g(t))return o("Invalid API response: challenge must be object",{field:"challenge",originalData:e});let n=c(t,"challenge"),s=c(t,"rpId"),i=t.allowCredentials;if(!l(n))return o("Invalid API response: challenge.challenge must be string",{originalData:e});if(!l(s))return o("Invalid API response: challenge.rpId must be string",{originalData:e});if(i!==void 0&&!S(i))return o("Invalid API response: allowCredentials must be array",{originalData:e});if(i){for(let m of i)if(!g(m)||m.type!=="public-key"||!l(m.id))return o("Invalid API response: allowCredentials items must have id and type",{originalData:e})}let a=t.timeout;if(a!==void 0&&!T(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}):p({session_id:r,challenge:{challenge:n,rpId:s,allowCredentials:i??[],...a!==void 0&&{timeout:a},...d!==void 0&&{userVerification:d}}})}function Q(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=c(e,"credential_id"),t=c(e,"status"),n=c(e,"session_token"),s=c(e,"user");if(!l(r))return o("Invalid API response: credential_id must be string",{field:"credential_id",originalData:e});if(!l(t))return o("Invalid API response: status must be string",{field:"status",originalData:e});if(!l(n))return o("Invalid API response: session_token must be string",{field:"session_token",originalData:e});let i=Y(s,e);if(!i.ok)return o(i.error.message,{originalData:e});let a=e.redirect_url;return a!==void 0&&!l(a)?o("Invalid API response: redirect_url must be string",{originalData:e}):p({credential_id:r,status:t,session_token:n,user:i.value,...a!==void 0&&{redirect_url:a}})}function ee(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=c(e,"authenticated"),t=c(e,"session_token"),n=c(e,"user"),s=c(e,"signals");if(!K(r))return o("Invalid API response: authenticated must be boolean",{field:"authenticated",originalData:e});if(!l(t))return o("Invalid API response: session_token must be string",{field:"session_token",originalData:e});let i=Y(n,e);if(!i.ok)return o(i.error.message,{originalData:e});if(s!==void 0&&!g(s))return o("Invalid API response: signals must be object",{originalData:e});let a=e.redirect_url;return a!==void 0&&!l(a)?o("Invalid API response: redirect_url must be string",{originalData:e}):p({authenticated:r,session_token:t,user:i.value,signals:s,...a!==void 0&&{redirect_url:a}})}function re(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=c(e,"valid"),t=c(e,"user_id"),n=c(e,"external_user_id"),s=c(e,"tenant_id"),i=c(e,"app_id");return K(r)?l(t)?l(n)?l(s)?l(i)?p({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 te(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=e.session_token??e.sessionToken;if(!l(r))return o("Invalid API response: session_token/sessionToken must be string",{field:"session_token",originalData:e});let t=e.redirect_url;return t!==void 0&&!l(t)?o("Invalid API response: redirect_url must be string",{originalData:e}):p({sessionToken:r,...t!==void 0&&{redirectUrl:t}})}var $e=["pending_passkey","pending_data","completed"],Xe=["pending_data","completed"];function ne(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=c(e,"session_id"),t=c(e,"onboarding_url"),n=c(e,"expires_in");return l(r)?l(t)?T(n)?p({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 se(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=c(e,"status"),t=c(e,"onboarding_url"),n=c(e,"expires_in");return !l(r)||!$e.includes(r)?o("Invalid API response: status must be pending_passkey|pending_data|completed",{field:"status",originalData:e}):l(t)?T(n)?p({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 ie(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=c(e,"session_id"),t=c(e,"status"),n=c(e,"onboarding_url");if(!l(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(!l(n))return o("Invalid API response: onboarding_url must be string",{originalData:e});let s=e.challenge,i;if(s!==void 0){let a=Ge(s);if(!a.ok)return a;i=a.value;}return p({session_id:r,status:"pending_passkey",onboarding_url:n,...i!==void 0&&{challenge:i}})}function Ge(e){if(!g(e))return o("Invalid API response: challenge must be object",{originalData:e});let r=c(e,"rp"),t=c(e,"user"),n=c(e,"challenge"),s=c(e,"pubKeyCredParams");if(!g(r)||!l(r.name)||!l(r.id))return o("Invalid API response: challenge.rp must have name and id",{originalData:e});if(!g(t)||!l(t.id)||!l(t.name)||!l(t.displayName))return o("Invalid API response: challenge.user must have id, name, displayName",{originalData:e});if(!l(n))return o("Invalid API response: challenge.challenge must be string",{originalData:e});if(!S(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"||!T(i.alg))return o("Invalid API response: pubKeyCredParams items must have type and alg",{originalData:e});return p({rp:r,user:t,challenge:n,pubKeyCredParams:s})}function oe(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=c(e,"session_id"),t=c(e,"status"),n=c(e,"user_id"),s=c(e,"tenant_id");return l(r)?!l(t)||!Xe.includes(t)?o("Invalid API response: status must be pending_data|completed",{originalData:e}):l(n)?l(s)?p({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 ae(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=c(e,"session_id"),t=c(e,"status"),n=c(e,"user_id"),s=c(e,"tenant_id"),i=c(e,"session_token");return l(r)?t!=="completed"?o("Invalid API response: status must be completed",{originalData:e}):!l(n)||!l(s)||!l(i)?o("Invalid API response: user_id, tenant_id, session_token must be strings",{originalData:e}):p({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 ze(e){if(!e||typeof e!="object")return false;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 Ye(e){if(!e||typeof e!="object")return false;let r=e;return typeof r.challenge=="string"&&typeof r.rpId=="string"}function j(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r="resultado"in e&&g(e.resultado)?e.resultado:e,t=r.session_id,n=r.qr_url,s=r.expires_at,i=r.polling_token;return !l(t)||!l(n)||!l(s)||!l(i)?o("Invalid API response: missing required fields",{originalData:e}):p({session_id:t,qr_url:n,expires_at:s,polling_token:i})}function le(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=e.status;return !l(r)||!["pending","authenticated","completed"].includes(r)?o("Invalid API response: invalid status",{originalData:e}):p({status:r,user_id:e.user_id,session_token:e.session_token})}function ue(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;if(!g(n))return o("Invalid API response: options are required",{originalData:e});let s=200,i=Te(e.approval_context,s),a=Te(e.application_name,s);if(i===false||a===false)return o("Invalid API response: approval_context/application_name must be string max 200 chars",{originalData:e});let d={};return typeof i=="string"&&(d.approval_context=i),typeof a=="string"&&(d.application_name=a),t==="registration"?ze(n)?p({type:"registration",options:n,...d}):o("Invalid API response: registration options must have challenge, rp, user, pubKeyCredParams",{originalData:e}):Ye(n)?p({type:"auth",options:n,...d}):o("Invalid API response: auth options must have challenge and rpId",{originalData:e})}function Te(e,r){if(e!=null)return typeof e!="string"||e.length>r?false:e}function ce(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=c(e,"challenge"),t=c(e,"recovery_session_id");return g(r)?l(t)?p({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 pe(e){if(!g(e))return o("Invalid API response: expected object",{originalData:e});let r=c(e,"status"),t=c(e,"session_token"),n=c(e,"user"),s=c(e,"credential_id");if(!l(r))return o("Invalid API response: status must be string",{field:"status",originalData:e});if(!l(t))return o("Invalid API response: session_token must be string",{field:"session_token",originalData:e});if(!l(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=c(n,"user_id");if(!l(i))return o("Invalid API response: user.user_id must be string",{field:"user.user_id",originalData:e});let a=n;return p({status:r,session_token:t,credential_id:s,user:{user_id:i,external_user_id:l(a.external_user_id)?a.external_user_id:void 0,email:l(a.email)?a.email:void 0,metadata:g(a.metadata)?a.metadata:void 0}})}var q=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):u(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):u(i.error)}async startRegister(r){return this.post("/v1/passkeys/register/start",r,J)}async startAuth(r){return this.post("/v1/passkeys/auth/start",r,Z)}async finishRegister(r){return this.post("/v1/passkeys/register/finish",r,Q)}async finishAuthentication(r){return this.post("/v1/passkeys/auth/finish",r,ee)}async validateSession(r){return this.get("/v1/sessions/validate",re,{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?p(void 0):u(n.error)}async verifyEmailCode(r){let t={userId:r.userId,code:r.code};return r.successUrl&&(t.success_url=r.successUrl),this.post("/v1/fallback/email/verify",t,te)}async startOnboarding(r){return this.post("/v1/onboarding/start",r,ne)}async getOnboardingStatus(r){return this.get(`/v1/onboarding/${r}/status`,se)}async getOnboardingRegister(r){return this.get(`/v1/onboarding/${r}/register`,ie)}async registerOnboardingPasskey(r,t){return this.post(`/v1/onboarding/${r}/register-passkey`,t,oe)}async completeOnboarding(r,t){return this.post(`/v1/onboarding/${r}/complete`,t,ae)}async initCrossDeviceAuth(){return this.post("/v1/auth/cross-device/init",{},j)}async initCrossDeviceRegistration(r){return this.post("/v1/auth/cross-device/init-registration",{external_user_id:r.externalUserId},j)}async getCrossDeviceStatus(r,t){let n={};return typeof t=="string"&&t.length>0&&(n["X-Polling-Token"]=t),this.get(`/v1/auth/cross-device/status/${r}`,le,Object.keys(n).length>0?n:void 0)}async getCrossDeviceContext(r){return this.get(`/v1/auth/cross-device/context/${r}`,ue)}async verifyCrossDeviceAuth(r){let t=`${this.baseUrl}/v1/auth/cross-device/verify`,n=await this.httpClient.post(t,r,this.mergeHeaders());return n.ok?p(void 0):u(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?p(void 0):u(n.error)}async verifyAccountRecoveryOtp(r,t){return this.post("/v1/users/recovery/verify",{external_id:r,otp:t},ce)}async completeAccountRecovery(r,t){return this.post("/v1/users/recovery/complete",{recovery_session_id:r,credential:t},pe)}};function Je(e){return typeof e=="object"&&e!==null&&e.ok===true&&"resultado"in e}function Ze(e){if(typeof e!="object"||e===null)return false;let r=e;if(r.ok!==false||!r.error||typeof r.error!="object")return false;let t=r.error;return typeof t.code=="string"&&typeof t.message=="string"}function Qe(e,r){if(Ze(e))return {message:e.error.message,code:w(e.error.code)};let t=e,n=t?.error;if(typeof n=="object"&&n!==null&&"code"in n&&typeof n.code=="string")return {message:n.message??t?.message??r,code:w(n.code)};let s=t?.message??r,i=t?.error,a=typeof i=="string"?w(i):i===void 0?"NETWORK_FAILURE":w(String(i));return {message:s,code:a}}var er=3e4;function rr(){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 Ae(e,r){let t=r*Math.pow(2,e);return Math.min(t,er)}function tr(e,r){return e!=="GET"?false:r>=500||r===429}var V=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=rr(),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 m=new AbortController,v=setTimeout(()=>m.abort(),this.timeoutMs);try{let f=await fetch(r,{...t,headers:i,signal:m.signal});if(!f.ok){let U;try{U=await f.json();}catch{}let{message:I,code:Ke}=Qe(U,f.statusText),ve=R(Ke,I,{requestId:s,status:f.status,statusText:f.statusText,data:U});if(tr(n,f.status)&&d<this.maxRetries){a=ve,clearTimeout(v),await new Promise(je=>setTimeout(je,Ae(d,this.retryDelayMs)));continue}return u(ve)}if(f.status===204)return p(void 0);if(f.headers.get("content-length")==="0")return p(void 0);let b=await f.json();if(Je(b))return p(b.resultado);let P=b;return typeof b=="object"&&b!==null&&P.ok===true&&!("resultado"in P)?p(void 0):p(b)}finally{clearTimeout(v);}}catch(m){if(a=m,n==="GET"&&d<this.maxRetries)await new Promise(f=>setTimeout(f,Ae(d,this.retryDelayMs)));else break}return a instanceof Error&&a.name==="AbortError"?u(R("TIMEOUT","Request timed out",{requestId:s})):u(R("NETWORK_FAILURE",a instanceof Error?a.message:"Request failed",{requestId:s,cause:a}))}};function _(e){let r=new Uint8Array(e),t=Array.from(r,s=>String.fromCharCode(s)).join("");if(typeof globalThis.btoa>"u")throw G("encode");return globalThis.btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function nr(e){if(typeof globalThis.atob>"u")throw G("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 x(e){let r=nr(e),t=new ArrayBuffer(r.length);return new Uint8Array(t).set(r),t}function Ie(e){return e!==null&&typeof e=="object"&&"clientDataJSON"in e&&e.clientDataJSON instanceof ArrayBuffer}function A(e){if(!e.response)throw R("UNKNOWN_ERROR","Credential response is missing",{credential:e});let r=e.response;if(!Ie(r))throw R("UNKNOWN_ERROR","Invalid credential response structure",{response:r});if(!("attestationObject"in r))throw R("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:_(e.rawId),response:{clientDataJSON:_(t),attestationObject:_(n)},type:"public-key"}}function B(e){if(!e.response)throw R("UNKNOWN_ERROR","Credential response is missing",{credential:e});let r=e.response;if(!Ie(r))throw R("UNKNOWN_ERROR","Invalid credential response structure",{response:r});if(!("authenticatorData"in r)||!("signature"in r))throw R("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:_(e.rawId),response:{authenticatorData:_(n),clientDataJSON:_(t),signature:_(s),...i&&{userHandle:_(i)}},type:"public-key"}}function M(){try{return !(typeof navigator>"u"||!navigator.credentials||typeof PublicKeyCredential>"u")}catch{return false}}async function sr(){try{return !M()||typeof PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable!="function"?false:await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return false}}async function Oe(){let e=M(),r=await sr();return {isPasskeySupported:e,platformAuthenticatorAvailable:r,recommendedFlow:e?"passkey":"fallback"}}function C(e,r="create"){if(!e||typeof e!="object"||!("id"in e)||!("rawId"in e)||!("response"in e))throw he(r)}async function N(e){let{operation:r,eventEmitter:t,start:n,createOptions:s,invoke:i,finish:a}=e;try{if(t.emit("start",{type:"start",operation:r}),!M()){let E=X();return t.emit("error",{type:"error",error:E}),u(E)}let d=await n();if(!d.ok)return t.emit("error",{type:"error",error:d.error}),u(d.error);let m=s(d.value);if(!m.ok)return t.emit("error",{type:"error",error:m.error}),u(m.error);let v=await i(m.value);if(!v){let E=y("credential",`${r==="register"?"creation":"retrieval"} failed`);return t.emit("error",{type:"error",error:E}),u(E)}try{C(v);}catch(E){let b=h(E);return t.emit("error",{type:"error",error:b}),u(b)}let f=await a(d.value,v);return f.ok?(t.emit("success",{type:"success",operation:r}),p(f.value)):(t.emit("error",{type:"error",error:f.error}),u(f.error))}catch(d){let m=h(d);return t.emit("error",{type:"error",error:m}),u(m)}}function k(e,r){try{L(e.challenge,"challenge"),L(e.user.id,"user.id");let t=x(e.challenge),n=x(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:x(a.id),type:a.type,...a.transports&&{transports:a.transports}}))}};return p({publicKey:i})}catch(t){return u(h(t))}}function de(e,r){try{L(e.challenge,"challenge");let t=x(e.challenge);return p({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:x(n.id),type:n.type,...n.transports&&{transports:n.transports}}))}},...r!==void 0&&{mediation:r}})}catch(t){return u(h(t))}}async function Ce(e,r,t){let n=e.externalUserId??e.external_user_id;if(!n||typeof n!="string"||n.trim()===""){let s=y("externalUserId","must be a non-empty string");return t.emit("error",{type:"error",error:s}),u(s)}return N({operation:"register",eventEmitter:t,start:()=>r.startRegister({external_user_id:n}),createOptions:s=>k(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:A(i),...e.successUrl&&{success_url:e.successUrl}});return a.ok?p({success:true,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},...a.value.redirect_url&&{redirectUrl:a.value.redirect_url}}):u(a.error)}})}async function ke(e,r,t){let n=e.externalUserId??e.external_user_id,s=n!==void 0&&typeof n=="string"&&n.trim()!=="";return N({operation:"authenticate",eventEmitter:t,start:()=>r.startAuth(s?{external_user_id:n.trim()}:{}),createOptions:i=>de(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:B(a),...e.successUrl&&{success_url:e.successUrl}});return d.ok?p({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,...d.value.redirect_url&&{redirectUrl:d.value.redirect_url}}):u(d.error)}})}var ir=2e3,or=60,W=class{constructor(r){this.apiClient=r;}async startFlow(r){let t=await this.apiClient.startOnboarding({user_role:r.user_role});if(!t.ok)return u(t.error);let{session_id:n}=t.value;for(let s=0;s<or;s++){await new Promise(m=>setTimeout(m,ir));let i=await this.apiClient.getOnboardingStatus(n);if(!i.ok)return u(i.error);let a=i.value.status,d=i.value.onboarding_url;if(a==="pending_passkey"){let m=await this.apiClient.getOnboardingRegister(n);if(!m.ok)return u(m.error);let v=m.value;if(!v.challenge)return u(R("NOT_SUPPORTED","Onboarding requires user action - complete passkey registration at the provided onboarding_url",{onboarding_url:d}));let f=k(v.challenge);if(!f.ok)return u(f.error);let E;try{E=await navigator.credentials.create(f.value);}catch(I){return u(h(I))}try{C(E,"create");}catch(I){return u(h(I))}let b;try{b=A(E);}catch(I){return u(h(I))}let P=await this.apiClient.registerOnboardingPasskey(n,{credential:b,challenge:v.challenge.challenge});return P.ok?await this.apiClient.completeOnboarding(n,{company_name:r.company_name}):u(P.error)}if(a==="completed")return await this.apiClient.completeOnboarding(n,{company_name:r.company_name})}return u(R("TIMEOUT","Onboarding timed out"))}};var ar=2e3,lr=60,H=class{constructor(r){this.apiClient=r;}async init(){return this.apiClient.initCrossDeviceAuth()}async initRegistration(r){return this.apiClient.initCrossDeviceRegistration(r)}async waitForSession(r,t,n){for(let s=0;s<lr;s++){if(t?.aborted)return u(R("ABORT_ERROR","Operation aborted by user or timeout"));let i=await this.apiClient.getCrossDeviceStatus(r,n);if(!i.ok)return u(i.error);if(i.value.status==="completed")return !i.value.session_token||!i.value.user_id?u(R("UNKNOWN_ERROR","Missing data in completed session")):p({session_token:i.value.session_token,user_id:i.value.user_id});if(t?.aborted)return u(R("ABORT_ERROR","Operation aborted by user or timeout"));if(await new Promise(a=>{let d=setTimeout(()=>{a(null),t?.removeEventListener("abort",m);},ar),m=()=>{clearTimeout(d),a(null);};t?.addEventListener("abort",m);}),t?.aborted)return u(R("ABORT_ERROR","Operation aborted by user or timeout"))}return u(R("TIMEOUT","Cross-device authentication timed out"))}async approve(r){let t=await this.apiClient.getCrossDeviceContext(r);if(!t.ok)return u(t.error);let n=t.value;return n.type==="registration"?this.executeRegistrationApproval(r,n):this.executeAuthApproval(r,n)}async executeRegistrationApproval(r,t){let n=k(t.options);if(!n.ok)return u(n.error);let s;try{s=await navigator.credentials.create(n.value);}catch(a){return u(h(a))}try{C(s,"create");}catch(a){return u(h(a))}let i;try{i=A(s);}catch(a){return u(h(a))}return this.apiClient.verifyCrossDeviceRegistration({session_id:r,credential:i})}async executeAuthApproval(r,t){let n=de(t.options);if(!n.ok)return u(n.error);let s;try{s=await navigator.credentials.get(n.value);}catch(a){return u(h(a))}try{C(s,"get");}catch(a){return u(h(a))}let i;try{i=B(s);}catch(a){return u(h(a))}return this.apiClient.verifyCrossDeviceAuth({session_id:r,credential:i})}};var $=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 Se(e,r,t){let n=e.externalUserId??e.external_user_id;if(!n||typeof n!="string"||n.trim()===""){let s=y("externalUserId","must be a non-empty string");return t.emit("error",{type:"error",error:s}),u(s)}if(!e.otp||typeof e.otp!="string"||e.otp.trim().length!==6){let s=y("otp","must be a 6-digit string");return t.emit("error",{type:"error",error:s}),u(s)}return N({operation:"register",eventEmitter:t,start:()=>r.verifyAccountRecoveryOtp(n,e.otp),createOptions:s=>k(s.challenge),invoke:async s=>navigator.credentials.create(s),finish:async(s,i)=>{let a=await r.completeAccountRecovery(s.recovery_session_id,A(i));return a.ok?p({success:true,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}}):u(a.error)}})}var ge="https://api.trymellonauth.com",xe="https://api.trymellonauth.com/v1/telemetry";var me="trymellon_sandbox_session_token_v1";function Me(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:true});}}}function Re(e,r){return {event:e,latencyMs:r,ok:true}}var fe=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 u(y("appId","must be a non-empty string"));if(!n||typeof n!="string"||n.trim()==="")return u(y("publishableKey","must be a non-empty string"));let s=r.apiBaseUrl??ge;z(s,"apiBaseUrl");let i=r.timeoutMs??3e4;return O(i,"timeoutMs",1e3,3e5),r.maxRetries!==void 0&&O(r.maxRetries,"maxRetries",0,10),r.retryDelayMs!==void 0&&O(r.retryDelayMs,"retryDelayMs",100,1e4),p(new e(r))}catch(t){return F(t)?u(t):u(y("config",t.message))}}constructor(r){this.sandbox=r.sandbox===true,this.sandboxToken=this.sandbox&&r.sandboxToken!=null&&r.sandboxToken!==""?r.sandboxToken:me;let t=r.appId,n=r.publishableKey;if(!t||typeof t!="string"||t.trim()==="")throw y("appId","must be a non-empty string");if(!n||typeof n!="string"||n.trim()==="")throw y("publishableKey","must be a non-empty string");let s=r.apiBaseUrl??ge;z(s,"apiBaseUrl");let i=r.timeoutMs??3e4;O(i,"timeoutMs",1e3,3e5),r.maxRetries!==void 0&&O(r.maxRetries,"maxRetries",0,10),r.retryDelayMs!==void 0&&O(r.retryDelayMs,"retryDelayMs",100,1e4);let a=r.maxRetries??3,d=r.retryDelayMs??1e3,m=new V(i,a,d,r.logger),v=r.origin??(typeof window<"u"&&window?.location?.origin?window.location.origin:void 0),f={"X-App-Id":t.trim(),Authorization:`Bearer ${n.trim()}`,...v&&{Origin:v}};this.apiClient=new q(m,s,f),this.onboarding=new W(this.apiClient),this.crossDeviceManager=new H(this.apiClient),this.eventEmitter=new $,r.enableTelemetry&&(this.telemetrySender=r.telemetrySender??Me(r.telemetryEndpoint??xe));}static isSupported(){return M()}sandboxAuthResult(r,t){let n=t.externalUserId??t.external_user_id??"sandbox",s=typeof n=="string"?n:"sandbox";return r==="register"?Promise.resolve(p({success:true,credentialId:"",status:"sandbox",sessionToken:this.sandboxToken,user:{userId:"sandbox-user",externalUserId:s}})):Promise.resolve(p({authenticated:true,sessionToken:this.sandboxToken,user:{userId:"sandbox-user",externalUserId:s}}))}async register(r){if(this.sandbox)return this.sandboxAuthResult("register",r);let t=Date.now(),n=await Ce(r,this.apiClient,this.eventEmitter);return n.ok&&this.telemetrySender&&this.telemetrySender.send(Re("register",Date.now()-t)).catch(()=>{}),n}async authenticate(r){if(this.sandbox)return this.sandboxAuthResult("authenticate",r);let t=Date.now(),n=await ke(r,this.apiClient,this.eventEmitter);return n.ok&&this.telemetrySender&&this.telemetrySender.send(Re("authenticate",Date.now()-t)).catch(()=>{}),n}async validateSession(r){return this.sandbox&&r===this.sandboxToken?Promise.resolve(p({valid:true,user_id:"sandbox-user",external_user_id:"sandbox",tenant_id:"sandbox-tenant",app_id:"sandbox-app"})):this.apiClient.validateSession(r)}async getStatus(){return Oe()}on(r,t){return this.eventEmitter.on(r,t)}version(){return "1.7.5"}fallback={email:{start:async r=>this.apiClient.startEmailFallback(r),verify:async r=>{let t=await this.apiClient.verifyEmailCode({userId:r.userId,code:r.code,...r.successUrl&&{successUrl:r.successUrl}});return t.ok?p({sessionToken:t.value.sessionToken,...t.value.redirectUrl&&{redirectUrl:t.value.redirectUrl}}):t}}};auth={crossDevice:{init:()=>this.crossDeviceManager.init(),initRegistration:r=>this.crossDeviceManager.initRegistration(r),waitForSession:(r,t,n)=>this.crossDeviceManager.waitForSession(r,t,n),getContext:r=>this.apiClient.getCrossDeviceContext(r),approve:r=>this.crossDeviceManager.approve(r)},recoverAccount:async r=>Se(r,this.apiClient,this.eventEmitter)}};var ye=class{debug(r,t){t&&Object.keys(t).length>0?console.debug(`[TryMellon] ${r}`,t):console.debug(`[TryMellon] ${r}`);}info(r,t){t&&Object.keys(t).length>0?console.info(`[TryMellon] ${r}`,t):console.info(`[TryMellon] ${r}`);}warn(r,t){t&&Object.keys(t).length>0?console.warn(`[TryMellon] ${r}`,t):console.warn(`[TryMellon] ${r}`);}error(r,t){t&&Object.keys(t).length>0?console.error(`[TryMellon] ${r}`,t):console.error(`[TryMellon] ${r}`);}};
2
- exports.ConsoleLogger=ye;exports.SANDBOX_SESSION_TOKEN=me;exports.TryMellon=fe;exports.TryMellonError=D;exports.createError=R;exports.createInvalidArgumentError=y;exports.createNetworkError=Be;exports.createNotSupportedError=X;exports.createTimeoutError=We;exports.createUserCancelledError=Ve;exports.err=u;exports.isTryMellonError=F;exports.mapWebAuthnError=h;exports.ok=p;return exports;})({});//# sourceMappingURL=index.global.js.map
1
+ var TryMellon=(function(exports){'use strict';var p=e=>({ok:true,value:e}),u=e=>({ok:false,error:e});var w=class e extends Error{code;details;isTryMellonError=true;constructor(r,t,n){super(t),this.name="TryMellonError",this.code=r,this.details=n,Error.captureStackTrace&&Error.captureStackTrace(this,e);}},We={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 R(e,r,t){return new w(e,r??We[e],t)}function F(e){return e instanceof w||typeof e=="object"&&e!==null&&"isTryMellonError"in e&&e.isTryMellonError===true}function G(){return R("NOT_SUPPORTED")}function He(){return R("USER_CANCELLED")}function $e(e){return R("NETWORK_FAILURE",void 0,{cause:e?.message,originalError:e})}function Xe(){return R("TIMEOUT")}function v(e,r){return R("INVALID_ARGUMENT",`Invalid argument: ${e} - ${r}`,{field:e,reason:r})}function Ee(e){return R("UNKNOWN_ERROR",`Failed to ${e} credential`,{operation:e})}function z(e){return R("NOT_SUPPORTED",`No base64 ${e==="encode"?"encoding":"decoding"} available`,{type:e})}function Y(e,r){try{let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")throw v(r,"must use http or https protocol")}catch(t){throw F(t)?t:v(r,"must be a valid URL")}}function O(e,r,t,n){if(!Number.isFinite(e))throw v(r,"must be a finite number");if(e<t||e>n)throw v(r,`must be between ${t} and ${n}`)}function L(e,r){if(typeof e!="string"||e.length===0)throw v(r,"must be a non-empty string");if(!/^[A-Za-z0-9_-]+$/.test(e))throw v(r,"must be a valid base64url string")}var Ge={NotAllowedError:"USER_CANCELLED",AbortError:"ABORTED",NotSupportedError:"NOT_SUPPORTED",SecurityError:"NOT_SUPPORTED",InvalidStateError:"UNKNOWN_ERROR",UnknownError:"UNKNOWN_ERROR"};function N(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 h(e){if(e instanceof DOMException){let r=e.name,t=e.message||"WebAuthn operation failed",n=Ge[r]??"UNKNOWN_ERROR";return R(n,t,{originalError:e})}return e instanceof Error?R("UNKNOWN_ERROR",e.message,{originalError:e}):R("UNKNOWN_ERROR","An unknown error occurred",{originalError:e})}function m(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function l(e){return typeof e=="string"}function A(e){return typeof e=="number"&&Number.isFinite(e)}function K(e){return typeof e=="boolean"}function x(e){return Array.isArray(e)}function o(e,r){return u(R("UNKNOWN_ERROR",e,{...r,originalData:r?.originalData}))}function c(e,r){return e[r]}function be(e,r){return !m(e)||!l(e.name)||!l(e.id)?o("Invalid API response: challenge.rp must have name and id strings",{originalData:r}):p(true)}function _e(e,r){return !m(e)||!l(e.id)||!l(e.name)||!l(e.displayName)?o("Invalid API response: challenge.user must have id, name, displayName strings",{originalData:r}):p(true)}function Te(e,r){if(!x(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"||!A(t.alg))return o("Invalid API response: pubKeyCredParams items must have type and alg",{originalData:r});return p(true)}function J(e,r){if(!m(e))return o("Invalid API response: user must be object",{field:"user",originalData:r});let t=c(e,"user_id"),n=c(e,"external_user_id");if(!l(t)||!l(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&&!l(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}):p({user_id:t,external_user_id:n,...s!==void 0&&{email:s},...i!==void 0&&{metadata:i}})}function Z(e){if(!m(e))return o("Invalid API response: expected object",{originalData:e});let r=c(e,"session_id");if(!l(r))return o("Invalid API response: session_id must be string",{field:"session_id",originalData:e});let t=c(e,"challenge");if(!m(t))return o("Invalid API response: challenge must be object",{field:"challenge",originalData:e});let n=be(c(t,"rp"),e);if(!n.ok)return n;let s=_e(c(t,"user"),e);if(!s.ok)return s;let i=c(t,"challenge");if(!l(i))return o("Invalid API response: challenge.challenge must be string",{originalData:e});let a=Te(c(t,"pubKeyCredParams"),e);if(!a.ok)return a;let d=t.timeout;if(d!==void 0&&!A(d))return o("Invalid API response: challenge.timeout must be number",{originalData:e});let g=t.excludeCredentials;if(g!==void 0){if(!x(g))return o("Invalid API response: excludeCredentials must be array",{originalData:e});for(let f of g)if(!m(f)||f.type!=="public-key"||!l(f.id))return o("Invalid API response: excludeCredentials items must have id and type",{originalData:e})}let y=t.authenticatorSelection;return y!==void 0&&!m(y)?o("Invalid API response: authenticatorSelection must be object",{originalData:e}):p({session_id:r,challenge:{rp:t.rp,user:t.user,challenge:i,pubKeyCredParams:t.pubKeyCredParams,...d!==void 0&&{timeout:d},...g!==void 0&&{excludeCredentials:g},...y!==void 0&&{authenticatorSelection:y}}})}function Q(e){if(!m(e))return o("Invalid API response: expected object",{originalData:e});let r=c(e,"session_id");if(!l(r))return o("Invalid API response: session_id must be string",{field:"session_id",originalData:e});let t=c(e,"challenge");if(!m(t))return o("Invalid API response: challenge must be object",{field:"challenge",originalData:e});let n=c(t,"challenge"),s=c(t,"rpId"),i=t.allowCredentials;if(!l(n))return o("Invalid API response: challenge.challenge must be string",{originalData:e});if(!l(s))return o("Invalid API response: challenge.rpId must be string",{originalData:e});if(i!==void 0&&!x(i))return o("Invalid API response: allowCredentials must be array",{originalData:e});if(i){for(let g of i)if(!m(g)||g.type!=="public-key"||!l(g.id))return o("Invalid API response: allowCredentials items must have id and type",{originalData:e})}let a=t.timeout;if(a!==void 0&&!A(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}):p({session_id:r,challenge:{challenge:n,rpId:s,allowCredentials:i??[],...a!==void 0&&{timeout:a},...d!==void 0&&{userVerification:d}}})}function ee(e){if(!m(e))return o("Invalid API response: expected object",{originalData:e});let r=c(e,"credential_id"),t=c(e,"status"),n=c(e,"session_token"),s=c(e,"user");if(!l(r))return o("Invalid API response: credential_id must be string",{field:"credential_id",originalData:e});if(!l(t))return o("Invalid API response: status must be string",{field:"status",originalData:e});if(!l(n))return o("Invalid API response: session_token must be string",{field:"session_token",originalData:e});let i=J(s,e);if(!i.ok)return o(i.error.message,{originalData:e});let a=e.redirect_url;return a!==void 0&&!l(a)?o("Invalid API response: redirect_url must be string",{originalData:e}):p({credential_id:r,status:t,session_token:n,user:i.value,...a!==void 0&&{redirect_url:a}})}function re(e){if(!m(e))return o("Invalid API response: expected object",{originalData:e});let r=c(e,"authenticated"),t=c(e,"session_token"),n=c(e,"user"),s=c(e,"signals");if(!K(r))return o("Invalid API response: authenticated must be boolean",{field:"authenticated",originalData:e});if(!l(t))return o("Invalid API response: session_token must be string",{field:"session_token",originalData:e});let i=J(n,e);if(!i.ok)return o(i.error.message,{originalData:e});if(s!==void 0&&!m(s))return o("Invalid API response: signals must be object",{originalData:e});let a=e.redirect_url;return a!==void 0&&!l(a)?o("Invalid API response: redirect_url must be string",{originalData:e}):p({authenticated:r,session_token:t,user:i.value,signals:s,...a!==void 0&&{redirect_url:a}})}function te(e){if(!m(e))return o("Invalid API response: expected object",{originalData:e});let r=c(e,"valid"),t=c(e,"user_id"),n=c(e,"external_user_id"),s=c(e,"tenant_id"),i=c(e,"app_id");return K(r)?l(t)?l(n)?l(s)?l(i)?p({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 ne(e){if(!m(e))return o("Invalid API response: expected object",{originalData:e});let r=e.session_token??e.sessionToken;if(!l(r))return o("Invalid API response: session_token/sessionToken must be string",{field:"session_token",originalData:e});let t=e.redirect_url;return t!==void 0&&!l(t)?o("Invalid API response: redirect_url must be string",{originalData:e}):p({sessionToken:r,...t!==void 0&&{redirectUrl:t}})}var ze=["pending_passkey","pending_data","completed"],Ye=["pending_data","completed"];function se(e){if(!m(e))return o("Invalid API response: expected object",{originalData:e});let r=c(e,"session_id"),t=c(e,"onboarding_url"),n=c(e,"expires_in");return l(r)?l(t)?A(n)?p({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 ie(e){if(!m(e))return o("Invalid API response: expected object",{originalData:e});let r=c(e,"status"),t=c(e,"onboarding_url"),n=c(e,"expires_in");return !l(r)||!ze.includes(r)?o("Invalid API response: status must be pending_passkey|pending_data|completed",{field:"status",originalData:e}):l(t)?A(n)?p({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 oe(e){if(!m(e))return o("Invalid API response: expected object",{originalData:e});let r=c(e,"session_id"),t=c(e,"status"),n=c(e,"onboarding_url");if(!l(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(!l(n))return o("Invalid API response: onboarding_url must be string",{originalData:e});let s=e.challenge,i;if(s!==void 0){let a=Je(s);if(!a.ok)return a;i=a.value;}return p({session_id:r,status:"pending_passkey",onboarding_url:n,...i!==void 0&&{challenge:i}})}function Je(e){if(!m(e))return o("Invalid API response: challenge must be object",{originalData:e});let r=c(e,"rp"),t=c(e,"user"),n=c(e,"challenge"),s=c(e,"pubKeyCredParams");if(!m(r)||!l(r.name)||!l(r.id))return o("Invalid API response: challenge.rp must have name and id",{originalData:e});if(!m(t)||!l(t.id)||!l(t.name)||!l(t.displayName))return o("Invalid API response: challenge.user must have id, name, displayName",{originalData:e});if(!l(n))return o("Invalid API response: challenge.challenge must be string",{originalData:e});if(!x(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"||!A(i.alg))return o("Invalid API response: pubKeyCredParams items must have type and alg",{originalData:e});return p({rp:r,user:t,challenge:n,pubKeyCredParams:s})}function ae(e){if(!m(e))return o("Invalid API response: expected object",{originalData:e});let r=c(e,"session_id"),t=c(e,"status"),n=c(e,"user_id"),s=c(e,"tenant_id");return l(r)?!l(t)||!Ye.includes(t)?o("Invalid API response: status must be pending_data|completed",{originalData:e}):l(n)?l(s)?p({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 le(e){if(!m(e))return o("Invalid API response: expected object",{originalData:e});let r=c(e,"session_id"),t=c(e,"status"),n=c(e,"user_id"),s=c(e,"tenant_id"),i=c(e,"session_token");return l(r)?t!=="completed"?o("Invalid API response: status must be completed",{originalData:e}):!l(n)||!l(s)||!l(i)?o("Invalid API response: user_id, tenant_id, session_token must be strings",{originalData:e}):p({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 j(e){return e==null?p(void 0):m(e)&&Object.keys(e).length===0?p(void 0):o("Invalid API response: expected empty body (204)",{originalData:e})}function Ze(e){if(!e||typeof e!="object")return false;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 Qe(e){if(!e||typeof e!="object")return false;let r=e;return typeof r.challenge=="string"&&typeof r.rpId=="string"}function V(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,i=r.polling_token;return !l(t)||!l(n)||!l(s)||!l(i)?o("Invalid API response: missing required fields",{originalData:e}):p({session_id:t,qr_url:n,expires_at:s,polling_token:i})}function ue(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.status;if(!l(t)||!["pending","authenticated","completed"].includes(t))return o("Invalid API response: invalid status",{originalData:e});let n=r.user_id,s=r.session_token,i=r.redirect_url;return n!==void 0&&!l(n)?o("Invalid API response: user_id must be a string when present",{originalData:e}):s!==void 0&&!l(s)?o("Invalid API response: session_token must be a string when present",{originalData:e}):i!==void 0&&!l(i)?o("Invalid API response: redirect_url must be a string when present",{originalData:e}):p({status:t,user_id:n,session_token:s,redirect_url:i})}function ce(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;if(!m(n))return o("Invalid API response: options are required",{originalData:e});let s=200,i=Ae(e.approval_context,s),a=Ae(e.application_name,s);if(i===false||a===false)return o("Invalid API response: approval_context/application_name must be string max 200 chars",{originalData:e});let d={};return typeof i=="string"&&(d.approval_context=i),typeof a=="string"&&(d.application_name=a),t==="registration"?Ze(n)?p({type:"registration",options:n,...d}):o("Invalid API response: registration options must have challenge, rp, user, pubKeyCredParams",{originalData:e}):Qe(n)?p({type:"auth",options:n,...d}):o("Invalid API response: auth options must have challenge and rpId",{originalData:e})}function Ae(e,r){if(e!=null)return typeof e!="string"||e.length>r?false:e}function pe(e){if(!m(e))return o("Invalid API response: expected object",{originalData:e});let r=c(e,"challenge"),t=c(e,"recovery_session_id");return m(r)?l(t)?p({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 de(e){if(!m(e))return o("Invalid API response: expected object",{originalData:e});let r=c(e,"status"),t=c(e,"session_token"),n=c(e,"user"),s=c(e,"credential_id");if(!l(r))return o("Invalid API response: status must be string",{field:"status",originalData:e});if(!l(t))return o("Invalid API response: session_token must be string",{field:"session_token",originalData:e});if(!l(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=c(n,"user_id");if(!l(i))return o("Invalid API response: user.user_id must be string",{field:"user.user_id",originalData:e});let d=e.redirect_url;if(d!==void 0&&!l(d))return o("Invalid API response: redirect_url must be string",{field:"redirect_url",originalData:e});let g=n;return p({status:r,session_token:t,credential_id:s,user:{user_id:i,external_user_id:l(g.external_user_id)?g.external_user_id:void 0,email:l(g.email)?g.email:void 0,metadata:m(g.metadata)?g.metadata:void 0},...d!==void 0&&{redirect_url:d}})}var q=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):u(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):u(i.error)}async startRegister(r){return this.post("/v1/passkeys/register/start",r,Z)}async startAuth(r){return this.post("/v1/passkeys/auth/start",r,Q)}async finishRegister(r){return this.post("/v1/passkeys/register/finish",r,ee)}async finishAuthentication(r){return this.post("/v1/passkeys/auth/finish",r,re)}async validateSession(r){return this.get("/v1/sessions/validate",te,{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?p(void 0):u(n.error)}async verifyEmailCode(r){let t={userId:r.userId,code:r.code};return r.successUrl&&(t.success_url=r.successUrl),this.post("/v1/fallback/email/verify",t,ne)}async startOnboarding(r){return this.post("/v1/onboarding/start",r,se)}async getOnboardingStatus(r){return this.get(`/v1/onboarding/${r}/status`,ie)}async getOnboardingRegister(r){return this.get(`/v1/onboarding/${r}/register`,oe)}async registerOnboardingPasskey(r,t){return this.post(`/v1/onboarding/${r}/register-passkey`,t,ae)}async completeOnboarding(r,t){return this.post(`/v1/onboarding/${r}/complete`,t,le)}async initCrossDeviceAuth(){return this.post("/v1/auth/cross-device/init",{},V)}async initCrossDeviceRegistration(r){return this.post("/v1/auth/cross-device/init-registration",{external_user_id:r.externalUserId},V)}async getCrossDeviceStatus(r,t){let n={};return typeof t=="string"&&t.length>0&&(n["X-Polling-Token"]=t),this.get(`/v1/auth/cross-device/status/${r}`,ue,Object.keys(n).length>0?n:void 0)}async getCrossDeviceContext(r){return this.get(`/v1/auth/cross-device/context/${r}`,ce)}async verifyCrossDeviceAuth(r){return this.post("/v1/auth/cross-device/verify",r,j)}async verifyCrossDeviceRegistration(r){return this.post("/v1/auth/cross-device/verify-registration",r,j)}async verifyAccountRecoveryOtp(r,t){return this.post("/v1/users/recovery/verify",{external_id:r,otp:t},pe)}async completeAccountRecovery(r,t){return this.post("/v1/users/recovery/complete",{recovery_session_id:r,credential:t},de)}};function er(e){return typeof e=="object"&&e!==null&&e.ok===true&&"resultado"in e}function Ce(e){if(typeof e!="object"||e===null)return false;let r=e;if(r.ok!==false||!r.error||typeof r.error!="object")return false;let t=r.error;return typeof t.code=="string"&&typeof t.message=="string"}function Ie(e,r){if(Ce(e))return {message:e.error.message,code:N(e.error.code)};let t=e,n=t?.error;if(typeof n=="object"&&n!==null&&"code"in n&&typeof n.code=="string")return {message:n.message??t?.message??r,code:N(n.code)};let s=t?.message??r,i=t?.error,a=typeof i=="string"?N(i):i===void 0?"NETWORK_FAILURE":N(String(i));return {message:s,code:a}}var rr=3e4;function tr(){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 Oe(e,r){let t=r*Math.pow(2,e);return Math.min(t,rr)}function nr(e,r){return e!=="GET"?false:r>=500||r===429}var B=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=tr(),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 g=new AbortController,y=setTimeout(()=>g.abort(),this.timeoutMs);try{let f=await fetch(r,{...t,headers:i,signal:g.signal});if(!f.ok){let S;try{S=await f.json();}catch{}let{message:_,code:qe}=Ie(S,f.statusText),he=R(qe,_,{requestId:s,status:f.status,statusText:f.statusText,data:S});if(nr(n,f.status)&&d<this.maxRetries){a=he,clearTimeout(y),await new Promise(Be=>setTimeout(Be,Oe(d,this.retryDelayMs)));continue}return u(he)}if(f.status===204)return p(void 0);if(f.headers.get("content-length")==="0")return p(void 0);let b=await f.json();if(er(b))return p(b.resultado);let M=b;if(typeof b=="object"&&b!==null&&M.ok===true&&!("resultado"in M))return p(void 0);if(Ce(b)){let{message:S,code:_}=Ie(b,f.statusText);return u(R(_,S,{requestId:s,status:f.status,statusText:f.statusText,data:b}))}return p(b)}finally{clearTimeout(y);}}catch(g){if(a=g,n==="GET"&&d<this.maxRetries)await new Promise(f=>setTimeout(f,Oe(d,this.retryDelayMs)));else break}return a instanceof Error&&a.name==="AbortError"?u(R("TIMEOUT","Request timed out",{requestId:s})):u(R("NETWORK_FAILURE",a instanceof Error?a.message:"Request failed",{requestId:s,cause:a}))}};function T(e){let r=new Uint8Array(e),t=Array.from(r,s=>String.fromCharCode(s)).join("");if(typeof globalThis.btoa>"u")throw z("encode");return globalThis.btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function sr(e){if(typeof globalThis.atob>"u")throw z("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 P(e){let r=sr(e),t=new ArrayBuffer(r.length);return new Uint8Array(t).set(r),t}function ke(e){return e!==null&&typeof e=="object"&&"clientDataJSON"in e&&e.clientDataJSON instanceof ArrayBuffer}function I(e){if(!e.response)throw R("UNKNOWN_ERROR","Credential response is missing",{credential:e});let r=e.response;if(!ke(r))throw R("UNKNOWN_ERROR","Invalid credential response structure",{response:r});if(!("attestationObject"in r))throw R("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:T(e.rawId),response:{clientDataJSON:T(t),attestationObject:T(n)},type:"public-key"}}function W(e){if(!e.response)throw R("UNKNOWN_ERROR","Credential response is missing",{credential:e});let r=e.response;if(!ke(r))throw R("UNKNOWN_ERROR","Invalid credential response structure",{response:r});if(!("authenticatorData"in r)||!("signature"in r))throw R("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:T(e.rawId),response:{authenticatorData:T(n),clientDataJSON:T(t),signature:T(s),...i&&{userHandle:T(i)}},type:"public-key"}}function D(){try{return !(typeof navigator>"u"||!navigator.credentials||typeof PublicKeyCredential>"u")}catch{return false}}async function ir(){try{return !D()||typeof PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable!="function"?false:await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return false}}async function Se(){let e=D(),r=await ir();return {isPasskeySupported:e,platformAuthenticatorAvailable:r,recommendedFlow:e?"passkey":"fallback"}}function C(e,r="create"){if(!e||typeof e!="object"||!("id"in e)||!("rawId"in e)||!("response"in e))throw Ee(r)}async function U(e){let{operation:r,eventEmitter:t,start:n,createOptions:s,invoke:i,finish:a}=e;try{if(t.emit("start",{type:"start",operation:r}),!D()){let E=G();return t.emit("error",{type:"error",error:E}),u(E)}let d=await n();if(!d.ok)return t.emit("error",{type:"error",error:d.error}),u(d.error);let g=s(d.value);if(!g.ok)return t.emit("error",{type:"error",error:g.error}),u(g.error);let y=await i(g.value);if(!y){let E=v("credential",`${r==="register"?"creation":"retrieval"} failed`);return t.emit("error",{type:"error",error:E}),u(E)}try{C(y);}catch(E){let b=h(E);return t.emit("error",{type:"error",error:b}),u(b)}let f=await a(d.value,y);return f.ok?(t.emit("success",{type:"success",operation:r}),p(f.value)):(t.emit("error",{type:"error",error:f.error}),u(f.error))}catch(d){let g=h(d);return t.emit("error",{type:"error",error:g}),u(g)}}function k(e,r){try{L(e.challenge,"challenge"),L(e.user.id,"user.id");let t=P(e.challenge),n=P(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:P(a.id),type:a.type,...a.transports&&{transports:a.transports}}))}};return p({publicKey:i})}catch(t){return u(h(t))}}function ge(e,r){try{L(e.challenge,"challenge");let t=P(e.challenge);return p({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:P(n.id),type:n.type,...n.transports&&{transports:n.transports}}))}},...r!==void 0&&{mediation:r}})}catch(t){return u(h(t))}}async function xe(e,r,t){let n=e.externalUserId??e.external_user_id;if(!n||typeof n!="string"||n.trim()===""){let s=v("externalUserId","must be a non-empty string");return t.emit("error",{type:"error",error:s}),u(s)}return U({operation:"register",eventEmitter:t,start:()=>r.startRegister({external_user_id:n}),createOptions:s=>k(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:I(i),...e.successUrl&&{success_url:e.successUrl}});return a.ok?p({success:true,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},...a.value.redirect_url&&{redirectUrl:a.value.redirect_url}}):u(a.error)}})}async function Pe(e,r,t){let n=e.externalUserId??e.external_user_id,s=n!==void 0&&typeof n=="string"&&n.trim()!=="";return U({operation:"authenticate",eventEmitter:t,start:()=>r.startAuth(s?{external_user_id:n.trim()}:{}),createOptions:i=>ge(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:W(a),...e.successUrl&&{success_url:e.successUrl}});return d.ok?p({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,...d.value.redirect_url&&{redirectUrl:d.value.redirect_url}}):u(d.error)}})}var or=2e3,ar=60,H=class{constructor(r){this.apiClient=r;}async startFlow(r){let t=await this.apiClient.startOnboarding({user_role:r.user_role});if(!t.ok)return u(t.error);let{session_id:n}=t.value;for(let s=0;s<ar;s++){await new Promise(g=>setTimeout(g,or));let i=await this.apiClient.getOnboardingStatus(n);if(!i.ok)return u(i.error);let a=i.value.status,d=i.value.onboarding_url;if(a==="pending_passkey"){let g=await this.apiClient.getOnboardingRegister(n);if(!g.ok)return u(g.error);let y=g.value;if(!y.challenge)return u(R("NOT_SUPPORTED","Onboarding requires user action - complete passkey registration at the provided onboarding_url",{onboarding_url:d}));let f=k(y.challenge);if(!f.ok)return u(f.error);let E;try{E=await navigator.credentials.create(f.value);}catch(_){return u(h(_))}try{C(E,"create");}catch(_){return u(h(_))}let b;try{b=I(E);}catch(_){return u(h(_))}let M=await this.apiClient.registerOnboardingPasskey(n,{credential:b,challenge:y.challenge.challenge});return M.ok?await this.apiClient.completeOnboarding(n,{company_name:r.company_name}):u(M.error)}if(a==="completed")return await this.apiClient.completeOnboarding(n,{company_name:r.company_name})}return u(R("TIMEOUT","Onboarding timed out"))}};var lr=2e3,ur=60,$=class{constructor(r){this.apiClient=r;}async init(){return this.apiClient.initCrossDeviceAuth()}async initRegistration(r){return this.apiClient.initCrossDeviceRegistration(r)}async waitForSession(r,t,n){for(let s=0;s<ur;s++){if(t?.aborted)return u(R("ABORT_ERROR","Operation aborted by user or timeout"));let i=await this.apiClient.getCrossDeviceStatus(r,n);if(!i.ok)return u(i.error);if(i.value.status==="completed"){if(!i.value.session_token||!i.value.user_id)return u(R("UNKNOWN_ERROR","Missing data in completed session"));let a=i.value.redirect_url!=null&&i.value.redirect_url!==""?i.value.redirect_url:void 0;return p({session_token:i.value.session_token,user_id:i.value.user_id,...a!==void 0&&{redirectUrl:a}})}if(t?.aborted)return u(R("ABORT_ERROR","Operation aborted by user or timeout"));if(await new Promise(a=>{let d=setTimeout(()=>{a(null),t?.removeEventListener("abort",g);},lr),g=()=>{clearTimeout(d),a(null);};t?.addEventListener("abort",g);}),t?.aborted)return u(R("ABORT_ERROR","Operation aborted by user or timeout"))}return u(R("TIMEOUT","Cross-device authentication timed out"))}async approve(r){let t=await this.apiClient.getCrossDeviceContext(r);if(!t.ok)return u(t.error);let n=t.value;return n.type==="registration"?this.executeRegistrationApproval(r,n):this.executeAuthApproval(r,n)}async executeRegistrationApproval(r,t){let n=k(t.options);if(!n.ok)return u(n.error);let s;try{s=await navigator.credentials.create(n.value);}catch(a){return u(h(a))}try{C(s,"create");}catch(a){return u(h(a))}let i;try{i=I(s);}catch(a){return u(h(a))}return this.apiClient.verifyCrossDeviceRegistration({session_id:r,credential:i})}async executeAuthApproval(r,t){let n=ge(t.options);if(!n.ok)return u(n.error);let s;try{s=await navigator.credentials.get(n.value);}catch(a){return u(h(a))}try{C(s,"get");}catch(a){return u(h(a))}let i;try{i=W(s);}catch(a){return u(h(a))}return this.apiClient.verifyCrossDeviceAuth({session_id:r,credential:i})}};var X=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 De(e,r,t){let n=e.externalUserId??e.external_user_id;if(!n||typeof n!="string"||n.trim()===""){let s=v("externalUserId","must be a non-empty string");return t.emit("error",{type:"error",error:s}),u(s)}if(!e.otp||typeof e.otp!="string"||e.otp.trim().length!==6){let s=v("otp","must be a 6-digit string");return t.emit("error",{type:"error",error:s}),u(s)}return U({operation:"register",eventEmitter:t,start:()=>r.verifyAccountRecoveryOtp(n,e.otp),createOptions:s=>k(s.challenge),invoke:async s=>navigator.credentials.create(s),finish:async(s,i)=>{let a=await r.completeAccountRecovery(s.recovery_session_id,I(i));if(!a.ok)return u(a.error);let{credential_id:d,status:g,session_token:y,user:f,redirect_url:E}=a.value;return p({success:true,credentialId:d,status:g,sessionToken:y,user:{userId:f.user_id,externalUserId:f.external_user_id,email:f.email,metadata:f.metadata},...E!==void 0&&{redirectUrl:E}})}})}var me="https://api.trymellonauth.com",Me="https://api.trymellonauth.com/v1/telemetry";var fe="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:true});}}}function Re(e,r){return {event:e,latencyMs:r,ok:true}}var ye=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 u(v("appId","must be a non-empty string"));if(!n||typeof n!="string"||n.trim()==="")return u(v("publishableKey","must be a non-empty string"));let s=r.apiBaseUrl??me;Y(s,"apiBaseUrl");let i=r.timeoutMs??3e4;return O(i,"timeoutMs",1e3,3e5),r.maxRetries!==void 0&&O(r.maxRetries,"maxRetries",0,10),r.retryDelayMs!==void 0&&O(r.retryDelayMs,"retryDelayMs",100,1e4),p(new e(r))}catch(t){return F(t)?u(t):u(v("config",t.message))}}constructor(r){this.sandbox=r.sandbox===true,this.sandboxToken=this.sandbox&&r.sandboxToken!=null&&r.sandboxToken!==""?r.sandboxToken:fe;let t=r.appId,n=r.publishableKey;if(!t||typeof t!="string"||t.trim()==="")throw v("appId","must be a non-empty string");if(!n||typeof n!="string"||n.trim()==="")throw v("publishableKey","must be a non-empty string");let s=r.apiBaseUrl??me;Y(s,"apiBaseUrl");let i=r.timeoutMs??3e4;O(i,"timeoutMs",1e3,3e5),r.maxRetries!==void 0&&O(r.maxRetries,"maxRetries",0,10),r.retryDelayMs!==void 0&&O(r.retryDelayMs,"retryDelayMs",100,1e4);let a=r.maxRetries??3,d=r.retryDelayMs??1e3,g=new B(i,a,d,r.logger),y=r.origin??(typeof window<"u"&&window?.location?.origin?window.location.origin:void 0),f={"X-App-Id":t.trim(),Authorization:`Bearer ${n.trim()}`,...y&&{Origin:y}};this.apiClient=new q(g,s,f),this.onboarding=new H(this.apiClient),this.crossDeviceManager=new $(this.apiClient),this.eventEmitter=new X,r.enableTelemetry&&(this.telemetrySender=r.telemetrySender??we(r.telemetryEndpoint??Me));}static isSupported(){return D()}sandboxAuthResult(r,t){let n=t.externalUserId??t.external_user_id??"sandbox",s=typeof n=="string"?n:"sandbox";return r==="register"?Promise.resolve(p({success:true,credentialId:"",status:"sandbox",sessionToken:this.sandboxToken,user:{userId:"sandbox-user",externalUserId:s}})):Promise.resolve(p({authenticated:true,sessionToken:this.sandboxToken,user:{userId:"sandbox-user",externalUserId:s}}))}async register(r){if(this.sandbox)return this.sandboxAuthResult("register",r);let t=Date.now(),n=await xe(r,this.apiClient,this.eventEmitter);return n.ok&&this.telemetrySender&&this.telemetrySender.send(Re("register",Date.now()-t)).catch(()=>{}),n}async authenticate(r){if(this.sandbox)return this.sandboxAuthResult("authenticate",r);let t=Date.now(),n=await Pe(r,this.apiClient,this.eventEmitter);return n.ok&&this.telemetrySender&&this.telemetrySender.send(Re("authenticate",Date.now()-t)).catch(()=>{}),n}async validateSession(r){return this.sandbox&&r===this.sandboxToken?Promise.resolve(p({valid:true,user_id:"sandbox-user",external_user_id:"sandbox",tenant_id:"sandbox-tenant",app_id:"sandbox-app"})):this.apiClient.validateSession(r)}async getStatus(){return Se()}on(r,t){return this.eventEmitter.on(r,t)}version(){return "1.7.7"}fallback={email:{start:async r=>this.apiClient.startEmailFallback(r),verify:async r=>{let t=await this.apiClient.verifyEmailCode({userId:r.userId,code:r.code,...r.successUrl&&{successUrl:r.successUrl}});return t.ok?p({sessionToken:t.value.sessionToken,...t.value.redirectUrl&&{redirectUrl:t.value.redirectUrl}}):t}}};auth={crossDevice:{init:()=>this.crossDeviceManager.init(),initRegistration:r=>this.crossDeviceManager.initRegistration(r),waitForSession:(r,t,n)=>this.crossDeviceManager.waitForSession(r,t,n),getContext:r=>this.apiClient.getCrossDeviceContext(r),approve:r=>this.crossDeviceManager.approve(r)},recoverAccount:async r=>De(r,this.apiClient,this.eventEmitter)}};var ve=class{debug(r,t){t&&Object.keys(t).length>0?console.debug(`[TryMellon] ${r}`,t):console.debug(`[TryMellon] ${r}`);}info(r,t){t&&Object.keys(t).length>0?console.info(`[TryMellon] ${r}`,t):console.info(`[TryMellon] ${r}`);}warn(r,t){t&&Object.keys(t).length>0?console.warn(`[TryMellon] ${r}`,t):console.warn(`[TryMellon] ${r}`);}error(r,t){t&&Object.keys(t).length>0?console.error(`[TryMellon] ${r}`,t):console.error(`[TryMellon] ${r}`);}};
2
+ exports.ConsoleLogger=ve;exports.SANDBOX_SESSION_TOKEN=fe;exports.TryMellon=ye;exports.TryMellonError=w;exports.createError=R;exports.createInvalidArgumentError=v;exports.createNetworkError=$e;exports.createNotSupportedError=G;exports.createTimeoutError=Xe;exports.createUserCancelledError=He;exports.err=u;exports.isTryMellonError=F;exports.mapWebAuthnError=h;exports.ok=p;return exports;})({});//# sourceMappingURL=index.global.js.map
3
3
  //# sourceMappingURL=index.global.js.map