@trymellon/js 2.3.0 → 2.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/angular.d.ts CHANGED
@@ -1,15 +1,14 @@
1
1
  import { InjectionToken, Provider } from '@angular/core';
2
- import { T as TryMellon, f as TryMellonConfig } from './trymellon-DItEFTiv.js';
2
+ import { T as TryMellon } from './trymellon-CO_2wLZz.js';
3
3
 
4
- declare const TRYMELLON_CONFIG: InjectionToken<TryMellonConfig>;
4
+ declare const TRYMELLON_CLIENT: InjectionToken<TryMellon>;
5
5
  declare class TryMellonService {
6
- private readonly config;
7
- private _client;
6
+ private readonly _client;
8
7
  get client(): TryMellon;
9
8
  enroll(options: Parameters<TryMellon['enroll']>[0]): ReturnType<TryMellon['enroll']>;
10
9
  getContextHash(): string;
11
10
  }
12
11
 
13
- declare function provideTryMellonConfig(config: TryMellonConfig): Provider;
12
+ declare function provideTryMellon(client: TryMellon): Provider;
14
13
 
15
- export { TRYMELLON_CONFIG, TryMellonService, provideTryMellonConfig };
14
+ export { TRYMELLON_CLIENT, TryMellonService, provideTryMellon };
package/dist/angular.js CHANGED
@@ -1,3 +1,3 @@
1
1
  "use client";
2
- var Or=Object.create;var fe=Object.defineProperty;var Pr=Object.getOwnPropertyDescriptor;var $e=(e,r)=>(r=Symbol[e])?r:Symbol.for("Symbol."+e),q=e=>{throw TypeError(e)};var Mr=(e,r,t)=>r in e?fe(e,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[r]=t;var We=(e,r)=>fe(e,"name",{value:r,configurable:!0});var ze=e=>[,,,Or(e?.[$e("metadata")]??null)],Je=["class","method","getter","setter","accessor","field","value","get","set"],V=e=>e!==void 0&&typeof e!="function"?q("Function expected"):e,Dr=(e,r,t,n,s)=>({kind:Je[e],name:r,metadata:n,addInitializer:i=>t._?q("Already initialized"):s.push(V(i||null))}),wr=(e,r)=>Mr(r,$e("metadata"),e[3]),Ze=(e,r,t,n)=>{for(var s=0,i=e[r>>1],l=i&&i.length;s<l;s++)r&1?i[s].call(t):n=i[s].call(t,n);return n},Qe=(e,r,t,n,s,i)=>{var l,c,g,h,R,f=r&7,v=!!(r&8),E=!!(r&16),I=f>3?e.length+1:f?v?1:2:0,T=Je[f+5],S=f>3&&(e[I-1]=[]),C=e[I]||(e[I]=[]),k=f&&(!E&&!v&&(s=s.prototype),f<5&&(f>3||!E)&&Pr(f<4?s:{get[t](){return Xe(this,i)},set[t](A){return Ye(this,i,A)}},t));f?E&&f<4&&We(i,(f>2?"set ":f>1?"get ":"")+t):We(s,t);for(var w=n.length-1;w>=0;w--)h=Dr(f,t,g={},e[3],C),f&&(h.static=v,h.private=E,R=h.access={has:E?A=>Nr(s,A):A=>t in A},f^3&&(R.get=E?A=>(f^1?Xe:Ur)(A,s,f^4?i:k.get):A=>A[t]),f>2&&(R.set=E?(A,H)=>Ye(A,s,H,f^4?i:k.set):(A,H)=>A[t]=H)),c=(0,n[w])(f?f<4?E?i:k[T]:f>4?void 0:{get:k.get,set:k.set}:s,h),g._=1,f^4||c===void 0?V(c)&&(f>4?S.unshift(c):f?E?i=c:k[T]=c:s=c):typeof c!="object"||c===null?q("Object expected"):(V(l=c.get)&&(k.get=l),V(l=c.set)&&(k.set=l),V(l=c.init)&&S.unshift(l));return f||wr(e,s),k&&fe(s,t,k),E?f^4?i:k:s};var Re=(e,r,t)=>r.has(e)||q("Cannot "+t),Nr=(e,r)=>Object(r)!==r?q('Cannot use the "in" operator on this value'):e.has(r),Xe=(e,r,t)=>(Re(e,r,"read from private field"),t?t.call(e):r.get(e));var Ye=(e,r,t,n)=>(Re(e,r,"write to private field"),n?n.call(e,t):r.set(e,t),t),Ur=(e,r,t)=>(Re(e,r,"access private method"),t);import{Injectable as Rt,InjectionToken as yt,inject as ht}from"@angular/core";var ye="https://api.trymellonauth.com",er="https://api.trymellonauth.com/v1/telemetry";var rr="trymellon_sandbox_session_token_v1",tr="/v1/enrollment-bridge",nr="/v1/auth-bridge";var d=e=>({ok:!0,value:e}),a=e=>({ok:!1,error:e});var Y=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)}},Br={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.",TICKET_NOT_FOUND:"Enrollment ticket not found or invalid",TICKET_EXPIRED:"Enrollment ticket has expired",TICKET_ALREADY_USED:"Enrollment ticket was already used",PIN_MISMATCH:"PIN does not match",PIN_LOCKED:"PIN is locked due to too many failed attempts",BRIDGE_SESSION_EXPIRED:"Bridge session has expired",UNKNOWN_ERROR:"An unknown error occurred"};function y(e,r,t){return new Y(e,r??Br[e],t)}function he(e){return e instanceof Y||typeof e=="object"&&e!==null&&"isTryMellonError"in e&&e.isTryMellonError===!0}function sr(){return y("NOT_SUPPORTED")}function b(e,r){return y("INVALID_ARGUMENT",`Invalid argument: ${e} - ${r}`,{field:e,reason:r})}function ir(e){return y("UNKNOWN_ERROR",`Failed to ${e} credential`,{operation:e})}function ve(e){return y("NOT_SUPPORTED",`No base64 ${e==="encode"?"encoding":"decoding"} available`,{type:e})}function Ee(e,r){try{let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")throw b(r,"must use http or https protocol")}catch(t){throw he(t)?t:b(r,"must be a valid URL")}}function N(e,r,t,n){if(!Number.isFinite(e))throw b(r,"must be a finite number");if(e<t||e>n)throw b(r,`must be between ${t} and ${n}`)}function $(e,r){if(typeof e!="string"||e.length===0)throw b(r,"must be a non-empty string");if(!/^[A-Za-z0-9_-]+$/.test(e))throw b(r,"must be a valid base64url string")}var Lr={NotAllowedError:"USER_CANCELLED",AbortError:"ABORTED",NotSupportedError:"NOT_SUPPORTED",SecurityError:"NOT_SUPPORTED",InvalidStateError:"UNKNOWN_ERROR",UnknownError:"UNKNOWN_ERROR"};function G(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",ticket_not_found:"TICKET_NOT_FOUND",ticket_expired:"TICKET_EXPIRED",ticket_already_consumed:"TICKET_ALREADY_USED",not_found:"TICKET_NOT_FOUND",expired:"TICKET_EXPIRED",already_consumed:"TICKET_ALREADY_USED",context_mismatch:"CHALLENGE_MISMATCH",challenge_not_found:"CHALLENGE_MISMATCH",invalid_ticket_id:"INVALID_ARGUMENT",invalid_context_hash:"INVALID_ARGUMENT",invalid_ticket_status:"INVALID_ARGUMENT",invalid_config:"INVALID_ARGUMENT",enrollment_not_enabled:"INVALID_ARGUMENT",pin_mismatch:"PIN_MISMATCH",pin_locked:"PIN_LOCKED",bridge_not_enabled:"UNKNOWN_ERROR",bridge_session_expired:"BRIDGE_SESSION_EXPIRED",session_not_found:"BRIDGE_SESSION_EXPIRED"}[r]??"UNKNOWN_ERROR"}function _(e){if(e instanceof DOMException){let r=e.name,t=e.message||"WebAuthn operation failed",n=Lr[r]??"UNKNOWN_ERROR";return y(n,t,{originalError:e})}return e instanceof Error?y("UNKNOWN_ERROR",e.message,{originalError:e}):y("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 D(e){return typeof e=="number"&&Number.isFinite(e)}function z(e){return typeof e=="boolean"}function U(e){return Array.isArray(e)}function o(e,r){return a(y("UNKNOWN_ERROR",e,{...r,originalData:r?.originalData}))}function p(e,r){return e[r]}function Fr(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}):d(!0)}function Kr(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}):d(!0)}function jr(e,r){if(!U(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"||!D(t.alg))return o("Invalid API response: pubKeyCredParams items must have type and alg",{originalData:r});return d(!0)}function J(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=Fr(p(t,"rp"),e);if(!n.ok)return n;let s=Kr(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 l=jr(p(t,"pubKeyCredParams"),e);if(!l.ok)return l;let c=t.timeout;if(c!==void 0&&!D(c))return o("Invalid API response: challenge.timeout must be number",{originalData:e});let g=t.excludeCredentials;if(g!==void 0){if(!U(g))return o("Invalid API response: excludeCredentials must be array",{originalData:e});for(let R of g)if(!m(R)||R.type!=="public-key"||!u(R.id))return o("Invalid API response: excludeCredentials items must have id and type",{originalData:e})}let h=t.authenticatorSelection;return h!==void 0&&!m(h)?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},...g!==void 0&&{excludeCredentials:g},...h!==void 0&&{authenticatorSelection:h}}})}function _e(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}):d({user_id:t,external_user_id:n,...s!==void 0&&{email:s},...i!==void 0&&{metadata:i}})}function be(e){let r=J(e);return r.ok?d({session_id:r.value.session_id,challenge:r.value.challenge}):r}function Te(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&&!U(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"||!u(g.id))return o("Invalid API response: allowCredentials items must have id and type",{originalData:e})}let l=t.timeout;if(l!==void 0&&!D(l))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??[],...l!==void 0&&{timeout:l},...c!==void 0&&{userVerification:c}}})}function Ie(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=_e(s,e);if(!i.ok)return a(i.error);let l=e.redirect_url;return l!==void 0&&!u(l)?o("Invalid API response: redirect_url must be string",{originalData:e}):d({credential_id:r,status:t,session_token:n,user:i.value,...l!==void 0&&{redirect_url:l}})}function Ae(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(!z(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=_e(n,e);if(!i.ok)return a(i.error);if(s!==void 0&&!m(s))return o("Invalid API response: signals must be object",{originalData:e});let l=e.redirect_url;return l!==void 0&&!u(l)?o("Invalid API response: redirect_url must be string",{originalData:e}):d({authenticated:r,session_token:t,user:i.value,signals:s,...l!==void 0&&{redirect_url:l}})}function Ce(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 z(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 Se(e){if(!m(e))return o("Invalid API response: expected object",{originalData:e});let r=e.session_token??e.sessionToken;if(!u(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&&!u(t)?o("Invalid API response: redirect_url must be string",{originalData:e}):d({sessionToken:r,...t!==void 0&&{redirectUrl:t}})}var Hr=["pending_passkey","pending_data","completed"],Vr=["pending_data","completed"];function ke(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)?D(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 xe(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)||!Hr.includes(r)?o("Invalid API response: status must be pending_passkey|pending_data|completed",{field:"status",originalData:e}):u(t)?D(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 Oe(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 l=qr(s);if(!l.ok)return l;i=l.value}return d({session_id:r,status:"pending_passkey",onboarding_url:n,...i!==void 0&&{challenge:i}})}function qr(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(!U(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"||!D(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 Pe(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)||!Vr.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 Me(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}):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 Z(e){return e==null?d(void 0):m(e)&&Object.keys(e).length===0?d(void 0):o("Invalid API response: expected empty body (204)",{originalData:e})}function Gr(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 Wr(e){if(!e||typeof e!="object")return!1;let r=e;return typeof r.challenge=="string"&&typeof r.rpId=="string"}function Q(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;if(!u(t)||!u(n)||!u(s)||!u(i))return o("Invalid API response: missing required fields",{originalData:e});let l={session_id:t,qr_url:n,expires_at:s,polling_token:i};return r.external_user_id!==void 0&&u(r.external_user_id)&&(l.external_user_id=r.external_user_id),d(l)}function De(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(!u(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&&!u(n)?o("Invalid API response: user_id must be a string when present",{originalData:e}):s!==void 0&&!u(s)?o("Invalid API response: session_token must be a string when present",{originalData:e}):i!==void 0&&!u(i)?o("Invalid API response: redirect_url must be a string when present",{originalData:e}):d({status:t,user_id:n,session_token:s,redirect_url:i})}function we(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=or(e.approval_context,s),l=or(e.application_name,s);if(i===!1||l===!1)return o("Invalid API response: approval_context/application_name must be string max 200 chars",{originalData:e});let c={};return typeof i=="string"&&(c.approval_context=i),typeof l=="string"&&(c.application_name=l),t==="registration"?Gr(n)?d({type:"registration",options:n,...c}):o("Invalid API response: registration options must have challenge, rp, user, pubKeyCredParams",{originalData:e}):Wr(n)?d({type:"auth",options:n,...c}):o("Invalid API response: auth options must have challenge and rpId",{originalData:e})}function or(e,r){if(e!=null)return typeof e!="string"||e.length>r?!1:e}function Ne(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)?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 Ue(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 c=e.redirect_url;if(c!==void 0&&!u(c))return o("Invalid API response: redirect_url must be string",{field:"redirect_url",originalData:e});let g=n;return d({status:r,session_token:t,credential_id:s,user:{user_id:i,external_user_id:u(g.external_user_id)?g.external_user_id:void 0,email:u(g.email)?g.email:void 0,metadata:m(g.metadata)?g.metadata:void 0},...c!==void 0&&{redirect_url:c}})}function Be(e){let r=J(e);return r.ok?d({session_id:r.value.session_id,challenge:r.value.challenge}):r}function Xr(e,r){if(!m(e))return o("Invalid API response: user must be object",{field:"user",originalData:r});let t=p(e,"user_id");if(!u(t))return o("Invalid API response: user.user_id must be string",{originalData:r});let n=e.external_user_id;if(n!==void 0&&!u(n))return o("Invalid API response: user.external_user_id must be string",{originalData:r});let s=e.email;if(s!==void 0&&!u(s))return o("Invalid API response: user.email must be string",{originalData:r});let i=e.metadata;return i!==void 0&&(typeof i!="object"||i===null)?o("Invalid API response: user.metadata must be object",{originalData:r}):d({user_id:t,...n!==void 0&&{external_user_id:n},...s!==void 0&&{email:s},...i!==void 0&&{metadata:i}})}function Le(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=Xr(s,e);return i.ok?d({credential_id:r,status:t,session_token:n,user:i.value}):i}var Yr=["pending","pin_verified","pin_locked","completed"];function Fe(e){if(!m(e))return o("Invalid bridge context response: expected object",{originalData:e});let r=p(e,"type");if(r!=="auth"&&r!=="registration")return o('Invalid bridge context response: type must be "auth" or "registration"',{field:"type",expected:"auth | registration",originalData:e});let t=p(e,"options");if(!m(t))return o("Invalid bridge context response: options must be object",{field:"options",originalData:e});let n=e.application_name;return n!==void 0&&!u(n)?o("Invalid bridge context response: application_name must be string",{field:"application_name",originalData:e}):d({type:r,options:t,...n!==void 0&&{application_name:n}})}function Ke(e){if(!m(e))return o("Invalid bridge verify response: expected object",{originalData:e});let r=p(e,"session_id");if(!u(r)||r.trim()==="")return o("Invalid bridge verify response: session_id must be non-empty string (UUID expected)",{field:"session_id",originalData:e});let t=e.challenge;if(t!==void 0&&!u(t))return o("Invalid bridge verify response: challenge must be string when present",{field:"challenge",originalData:e});let n=e.registration_options;if(n!==void 0&&!m(n))return o("Invalid bridge verify response: registration_options must be object when present",{field:"registration_options",originalData:e});let s=e.authentication_options;return s!==void 0&&!m(s)?o("Invalid bridge verify response: authentication_options must be object when present",{field:"authentication_options",originalData:e}):d({session_id:r,...t!==void 0&&{challenge:t},...n!==void 0&&{registration_options:n},...s!==void 0&&{authentication_options:s}})}function je(e){if(!m(e))return o("Invalid bridge complete enrollment response: expected object",{originalData:e});let r=p(e,"credential_id"),t=p(e,"entity_id"),n=p(e,"user_id"),s=p(e,"session_token");return u(r)?u(t)?u(n)?u(s)?d({credential_id:r,entity_id:t,user_id:n,session_token:s}):o("Invalid bridge complete enrollment response: session_token must be string",{field:"session_token",originalData:e}):o("Invalid bridge complete enrollment response: user_id must be string",{field:"user_id",originalData:e}):o("Invalid bridge complete enrollment response: entity_id must be string",{field:"entity_id",originalData:e}):o("Invalid bridge complete enrollment response: credential_id must be string",{field:"credential_id",originalData:e})}function He(e){if(!m(e))return o("Invalid bridge complete auth response: expected object",{originalData:e});let r=p(e,"session_token");return u(r)?d({session_token:r}):o("Invalid bridge complete auth response: session_token must be string",{field:"session_token",originalData:e})}function Ve(e){if(!m(e))return o("Invalid bridge status response: expected object",{originalData:e});let r=p(e,"status");if(typeof r!="string"||!Yr.includes(r))return o("Invalid bridge status response: status must be one of pending, pin_verified, pin_locked, completed",{field:"status",originalData:e});let t=e.ts;return t!==void 0&&!u(t)?o("Invalid bridge status response: ts must be string when present",{field:"ts",originalData:e}):d({status:r,...t!==void 0&&{ts:t}})}var ee=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,s){let i=`${this.baseUrl}${r}`,l=await this.httpClient.post(i,t,this.mergeHeaders(s));return l.ok?n(l.value):a(l.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):a(i.error)}async startRegister(r){return this.post("/v1/passkeys/register/start",r,be)}async startAuth(r){return this.post("/v1/passkeys/auth/start",r,Te)}async finishRegister(r){return this.post("/v1/passkeys/register/finish",r,Ie)}async finishAuthentication(r){return this.post("/v1/passkeys/auth/finish",r,Ae)}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):a(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,Se)}async startOnboarding(r){return this.post("/v1/onboarding/start",r,ke)}async getOnboardingStatus(r){return this.get(`/v1/onboarding/${r}/status`,xe)}async getOnboardingRegister(r){return this.get(`/v1/onboarding/${r}/register`,Oe)}async registerOnboardingPasskey(r,t){return this.post(`/v1/onboarding/${r}/register-passkey`,t,Pe)}async completeOnboarding(r,t){return this.post(`/v1/onboarding/${r}/complete`,t,Me)}async initCrossDeviceAuth(){return this.post("/v1/auth/cross-device/init",{},Q)}async initCrossDeviceRegistration(r){let t=typeof r?.externalUserId=="string"?r.externalUserId.trim():"",n=t.length>0?{external_user_id:t}:{};return this.post("/v1/auth/cross-device/init-registration",n,Q)}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}`,De,Object.keys(n).length>0?n:void 0)}async getCrossDeviceContext(r){return this.get(`/v1/auth/cross-device/context/${r}`,we)}async verifyCrossDeviceAuth(r){return this.post("/v1/auth/cross-device/verify",r,Z)}async verifyCrossDeviceRegistration(r){return this.post("/v1/auth/cross-device/verify-registration",r,Z)}async verifyAccountRecoveryOtp(r,t){return this.post("/v1/users/recovery/verify",{external_id:r,otp:t},Ne)}async completeAccountRecovery(r,t){return this.post("/v1/users/recovery/complete",{recovery_session_id:r,credential:t},Ue)}async startEnrollment(r,t,n){return this.post("/v1/enrollment/register/options",{ticket_id:r,context_hash:t},Be,n)}async finishEnrollment(r,t,n){return this.post("/v1/enrollment/register",{...t,ticket_id:r},Le,n)}bridgePrefix(r){return r==="enrollment"?tr:nr}async getBridgeContext(r,t,n){return this.get(`${this.bridgePrefix(t)}/context/${r}`,Fe,n)}async verifyBridgePin(r,t,n,s){return this.post(`${this.bridgePrefix(n)}/verify/${r}`,{pin:t},Ke,s)}async completeBridgeEnrollment(r,t){return this.post(`${this.bridgePrefix("enrollment")}/complete`,r,je,t)}async completeBridgeAuth(r,t){return this.post(`${this.bridgePrefix("auth")}/complete`,r,He,t)}getBridgeStatusUrl(r,t){return`${this.baseUrl}${this.bridgePrefix(t)}/status/${r}`}async getBridgeStatus(r,t,n){return this.get(`${this.bridgePrefix(t)}/status/${r}`,Ve,n)}};function $r(e){return typeof e=="object"&&e!==null&&e.ok===!0&&"resultado"in e}function ur(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"}function ar(e,r){if(ur(e))return{message:e.error.message,code:G(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:G(n.code)};let s=t?.message??r,i=t?.error,l=typeof i=="string"?G(i):i===void 0?"NETWORK_FAILURE":G(String(i));return{message:s,code:l}}function zr(){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 lr(e,r){let t=r*Math.pow(2,e);return Math.min(t,3e4)}function Jr(e,r){return e!=="GET"?!1:r>=500||r===429}var re=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=zr(),i=new Headers(t.headers);i.set("X-Request-Id",s),this.logger&&this.logger.debug("request",{requestId:s,url:r,method:n});let l;for(let c=0;c<=this.maxRetries;c++)try{let g=new AbortController,h=setTimeout(()=>g.abort(),this.timeoutMs);try{let R=await fetch(r,{...t,headers:i,signal:g.signal});if(!R.ok){let I;try{I=await R.json()}catch{}let{message:T,code:S}=ar(I,R.statusText),C=y(S,T,{requestId:s,status:R.status,statusText:R.statusText,data:I});if(Jr(n,R.status)&&c<this.maxRetries){l=C,clearTimeout(h),await new Promise(k=>setTimeout(k,lr(c,this.retryDelayMs)));continue}return a(C)}if(R.status===204)return d(void 0);if(R.headers.get("content-length")==="0")return d(void 0);let v=await R.json();if($r(v))return d(v.resultado);let E=v;if(typeof v=="object"&&v!==null&&E.ok===!0&&!("resultado"in E))return d(void 0);if(ur(v)){let{message:I,code:T}=ar(v,R.statusText);return a(y(T,I,{requestId:s,status:R.status,statusText:R.statusText,data:v}))}return d(v)}finally{clearTimeout(h)}}catch(g){if(l=g,n==="GET"&&c<this.maxRetries)await new Promise(R=>setTimeout(R,lr(c,this.retryDelayMs)));else break}return l instanceof Error&&l.name==="AbortError"?a(y("TIMEOUT","Request timed out",{requestId:s})):a(y("NETWORK_FAILURE",l instanceof Error?l.message:"Request failed",{requestId:s,cause:l}))}};function M(e){let r=new Uint8Array(e),t=Array.from(r,s=>String.fromCharCode(s)).join("");if(typeof globalThis.btoa>"u")throw ve("encode");return globalThis.btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Zr(e){if(typeof globalThis.atob>"u")throw ve("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 B(e){let r=Zr(e),t=new ArrayBuffer(r.length);return new Uint8Array(t).set(r),t}function cr(e){return e!==null&&typeof e=="object"&&"clientDataJSON"in e&&e.clientDataJSON instanceof ArrayBuffer}function O(e){if(!e.response)throw y("UNKNOWN_ERROR","Credential response is missing",{credential:e});let r=e.response;if(!cr(r))throw y("UNKNOWN_ERROR","Invalid credential response structure",{response:r});if(!("attestationObject"in r))throw y("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:M(e.rawId),response:{clientDataJSON:M(t),attestationObject:M(n)},type:"public-key"}}function L(e){if(!e.response)throw y("UNKNOWN_ERROR","Credential response is missing",{credential:e});let r=e.response;if(!cr(r))throw y("UNKNOWN_ERROR","Invalid credential response structure",{response:r});if(!("authenticatorData"in r)||!("signature"in r))throw y("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:M(e.rawId),response:{authenticatorData:M(n),clientDataJSON:M(t),signature:M(s),...i&&{userHandle:M(i)}},type:"public-key"}}function x(e,r="create"){if(!e||typeof e!="object"||!("id"in e)||!("rawId"in e)||!("response"in e))throw ir(r)}function F(){try{return!(typeof navigator>"u"||!navigator.credentials||typeof PublicKeyCredential>"u")}catch{return!1}}async function Qr(){try{return!F()||typeof PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable!="function"?!1:await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}async function dr(){let e=F(),r=await Qr();return{isPasskeySupported:e,platformAuthenticatorAvailable:r,recommendedFlow:e?"passkey":"fallback"}}async function W(e){let{operation:r,eventEmitter:t,start:n,createOptions:s,invoke:i,finish:l}=e;try{if(t.emit("start",{type:"start",operation:r}),!F()){let f=sr();return t.emit("error",{type:"error",error:f}),a(f)}let c=await n();if(!c.ok)return t.emit("error",{type:"error",error:c.error}),a(c.error);let g=s(c.value);if(!g.ok)return t.emit("error",{type:"error",error:g.error}),a(g.error);let h=await i(g.value);if(!h){let f=b("credential",`${r==="register"?"creation":"retrieval"} failed`);return t.emit("error",{type:"error",error:f}),a(f)}try{x(h)}catch(f){let v=_(f);return t.emit("error",{type:"error",error:v}),a(v)}let R=await l(c.value,h);return R.ok?d(R.value):(t.emit("error",{type:"error",error:R.error}),a(R.error))}catch(c){let g=_(c);return t.emit("error",{type:"error",error:g}),a(g)}}function P(e,r){try{$(e.challenge,"challenge"),$(e.user.id,"user.id");let t=B(e.challenge),n=B(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(l=>({id:B(l.id),type:l.type,...l.transports&&{transports:l.transports}}))}};return d({publicKey:i})}catch(t){return a(_(t))}}async function pr(e,r){let t=P(e);if(!t.ok)return a(t.error);let n={...t.value,...r!==void 0&&{signal:r}},s;try{s=await navigator.credentials.create(n)}catch(i){return a(_(i))}try{x(s,"create")}catch(i){return a(_(i))}try{return d(O(s))}catch(i){return a(_(i))}}function X(e,r){try{$(e.challenge,"challenge");let t=B(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:B(n.id),type:n.type,...n.transports&&{transports:n.transports}}))}},...r!==void 0&&{mediation:r}})}catch(t){return a(_(t))}}async function gr(e,r,t){let n=e.externalUserId??e.external_user_id;if(!n||typeof n!="string"||n.trim()===""){let i=b("externalUserId","must be a non-empty string");return t.emit("error",{type:"error",error:i}),a(i)}let s=await W({operation:"register",eventEmitter:t,start:()=>r.startRegister({external_user_id:n}),createOptions:i=>P(i.challenge,e.authenticatorType),invoke:async i=>{let l={...i,...e.signal&&{signal:e.signal}};return navigator.credentials.create(l)},finish:async(i,l)=>{let c=await r.finishRegister({session_id:i.session_id,credential:O(l),...e.successUrl&&{success_url:e.successUrl}});return c.ok?d({success:!0,credentialId:c.value.credential_id,credential_id:c.value.credential_id,status:c.value.status,sessionToken:c.value.session_token,user:{userId:c.value.user.user_id,externalUserId:c.value.user.external_user_id,email:c.value.user.email,metadata:c.value.user.metadata},...c.value.redirect_url&&{redirectUrl:c.value.redirect_url}}):a(c.error)}});return s.ok&&t.emit("success",{type:"success",operation:"register",token:s.value.sessionToken,user:s.value.user}),s}async function mr(e,r,t){let n=e.externalUserId??e.external_user_id,s=n!==void 0&&typeof n=="string"&&n.trim()!=="",i=await W({operation:"authenticate",eventEmitter:t,start:()=>r.startAuth(s?{external_user_id:n.trim()}:{}),createOptions:l=>X(l.challenge,e.mediation),invoke:async l=>{let c={...l,...e.signal&&{signal:e.signal}};return navigator.credentials.get(c)},finish:async(l,c)=>{let g=await r.finishAuthentication({session_id:l.session_id,credential:L(c),...e.successUrl&&{success_url:e.successUrl}});return g.ok?d({authenticated:g.value.authenticated,sessionToken:g.value.session_token,user:{userId:g.value.user.user_id,externalUserId:g.value.user.external_user_id,email:g.value.user.email,metadata:g.value.user.metadata},signals:g.value.signals,...g.value.redirect_url&&{redirectUrl:g.value.redirect_url}}):a(g.error)}});return i.ok&&t.emit("success",{type:"success",operation:"authenticate",token:i.value.sessionToken,user:i.value.user}),i}async function te(e,r){return r?r.aborted?"aborted":new Promise(t=>{let n=()=>{s(),t("aborted")},s=()=>{clearTimeout(i),r.removeEventListener("abort",n)},i=setTimeout(()=>{s(),t("completed")},e);r.addEventListener("abort",n)}):(await new Promise(t=>setTimeout(t,e)),"completed")}var et=2e3,rt=60,ne=class{constructor(r){this.apiClient=r}async startFlow(r,t){let n=await this.apiClient.startOnboarding({user_role:r.user_role});if(!n.ok)return a(n.error);let{session_id:s}=n.value;for(let i=0;i<rt;i++){if(t?.aborted)return a(y("ABORT_ERROR","Operation aborted by user or timeout"));if(await te(et,t)==="aborted")return a(y("ABORT_ERROR","Operation aborted by user or timeout"));let c=await this.apiClient.getOnboardingStatus(s);if(!c.ok)return a(c.error);let g=c.value.status,h=c.value.onboarding_url;if(g==="pending_passkey"){let R=await this.apiClient.getOnboardingRegister(s);if(!R.ok)return a(R.error);let f=R.value;if(!f.challenge)return a(y("NOT_SUPPORTED","Onboarding requires user action - complete passkey registration at the provided onboarding_url",{onboarding_url:h}));let v=P(f.challenge);if(!v.ok)return a(v.error);let E;try{E=await navigator.credentials.create(v.value)}catch(C){return a(_(C))}try{x(E,"create")}catch(C){return a(_(C))}let I;try{I=O(E)}catch(C){return a(_(C))}let T=await this.apiClient.registerOnboardingPasskey(s,{credential:I,challenge:f.challenge.challenge});return T.ok?await this.apiClient.completeOnboarding(s,{company_name:r.company_name}):a(T.error)}if(g==="completed")return await this.apiClient.completeOnboarding(s,{company_name:r.company_name})}return a(y("TIMEOUT","Onboarding timed out"))}};var fr="trymellon_context_hash";var tt=/^[a-f0-9]{64}$/;function nt(e){return typeof e=="string"&&tt.test(e)}function st(){let e=new Uint8Array(32);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(e);else throw new Error("crypto.getRandomValues is not available");return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}function it(){let e=null;return{getItem(){return e},setItem(r,t){e=t}}}var Rr=it();function yr(e){let r=e.getItem(fr);if(r&&nt(r))return r;let t=st();return e.setItem(fr,t),t}function K(e){let r=e??Rr;try{return yr(r)}catch{return yr(Rr)}}var se=class{constructor(r,t){this.apiClient=r;this.storage=t}async enroll(r){if(r.signal?.aborted)return a(y("ABORT_ERROR","Operation aborted by user or timeout"));let t=this.storage??(typeof sessionStorage<"u"?sessionStorage:void 0),n=K(t),s=await this.apiClient.startEnrollment(r.ticketId,n);if(!s.ok)return a(s.error);let i=await pr(s.value.challenge,r.signal);if(!i.ok)return a(i.error);let l=await this.apiClient.finishEnrollment(r.ticketId,{credential:i.value,context_hash:n});return l.ok?d({sessionToken:l.value.session_token}):a(l.error)}};var ot=2e3,at=60,ie=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){if(t?.aborted)return a(y("ABORT_ERROR","Operation aborted by user or timeout"));for(let s=0;s<at;s++){let i=await this.apiClient.getCrossDeviceStatus(r,n);if(!i.ok)return a(i.error);if(i.value.status==="completed"){if(!i.value.session_token||!i.value.user_id)return a(y("UNKNOWN_ERROR","Missing data in completed session"));let c=i.value.redirect_url!=null&&i.value.redirect_url!==""?i.value.redirect_url:void 0;return d({session_token:i.value.session_token,user_id:i.value.user_id,...c!==void 0&&{redirectUrl:c}})}if(await te(ot,t)==="aborted")return a(y("ABORT_ERROR","Operation aborted by user or timeout"))}return a(y("TIMEOUT","Cross-device authentication timed out"))}async approve(r){let t=await this.apiClient.getCrossDeviceContext(r);if(!t.ok)return a(t.error);let n=t.value;return n.type==="registration"?this.executeRegistrationApproval(r,n):this.executeAuthApproval(r,n)}async executeRegistrationApproval(r,t){let n=P(t.options);if(!n.ok)return a(n.error);let s;try{s=await navigator.credentials.create(n.value)}catch(l){return a(_(l))}try{x(s,"create")}catch(l){return a(_(l))}let i;try{i=O(s)}catch(l){return a(_(l))}return this.apiClient.verifyCrossDeviceRegistration({session_id:r,credential:i})}async executeAuthApproval(r,t){let n=X(t.options);if(!n.ok)return a(n.error);let s;try{s=await navigator.credentials.get(n.value)}catch(l){return a(_(l))}try{x(s,"get")}catch(l){return a(_(l))}let i;try{i=L(s)}catch(l){return a(_(l))}return this.apiClient.verifyCrossDeviceAuth({session_id:r,credential:i})}};var lt=new Set(["pin_verified","pin_locked","completed"]),ut=1500,ct=3e5;function hr(e){return lt.has(e)}function oe(e){return e==null||typeof e!="string"||e.trim()===""?a(b("sessionId","must be a non-empty string")):d(e.trim())}function dt(e){return{sessionToken:e.session_token,credentialId:e.credential_id,userId:e.user_id,entityId:e.entity_id}}function pt(e){return{sessionToken:e.session_token}}async function gt(e,r,t,n){let i=(n.presencePin!=null&&n.presencePin!==""?n.presencePin:null)??(typeof n.onPinRequired=="function"?await n.onPinRequired():null);return i==null||i===""?a(y("INVALID_ARGUMENT","Bridge requires PIN: provide presencePin or onPinRequired in options")):e.verifyBridgePin(r,i,t)}var ae=class{constructor(r,t){this.apiClient=r;this.storage=t}async waitForResult(r,t){let n=oe(r);if(!n.ok)return a(n.error);let s=t?.kind??"enrollment",i=t?.useSse!==!1,l=t?.timeoutMs??ct,c=async g=>{for(;;){let h=await this.apiClient.getBridgeStatus(n.value,s);if(!h.ok)return a(h.error);if(hr(h.value.status))return d(h.value);if(Date.now()-g>=l)return a(y("TIMEOUT","Bridge status wait timed out"));await new Promise(R=>setTimeout(R,ut))}};return i&&typeof EventSource<"u"?new Promise(g=>{let h=this.apiClient.getBridgeStatusUrl(n.value,s),R=!1,f=E=>{if(!R){R=!0;try{v.close()}catch{}g(E)}},v;try{v=new EventSource(h)}catch{c(Date.now()).then(f);return}v.onmessage=E=>{try{let I=typeof E.data=="string"?E.data:String(E.data),T=JSON.parse(I);if(T!==null&&typeof T=="object"&&"status"in T&&typeof T.status=="string"){let S=T.status;if(hr(S)){let C=T.ts;f(d({status:S,...typeof C=="string"&&{ts:C}}))}}}catch{}},v.onerror=()=>{if(!R){try{v.close()}catch{}c(Date.now()).then(f)}}}):c(Date.now())}async getContext(r,t){let n=oe(r);return n.ok?this.apiClient.getBridgeContext(n.value,t):a(n.error)}async verifyPin(r,t,n){let s=oe(r);return s.ok?t==null||typeof t!="string"||t===""?a(b("pin","must be a non-empty string")):this.apiClient.verifyBridgePin(s.value,t,n):a(s.error)}async complete(r,t){let n=oe(r);if(!n.ok)return a(n.error);let s=t?.kind??"enrollment",i=await this.apiClient.getBridgeContext(n.value,s);if(!i.ok)return a(i.error);let l=i.value,c=await gt(this.apiClient,n.value,s,t??{kind:s});if(!c.ok)return a(c.error);let g=c.value;if(t?.signal?.aborted)return a(y("ABORT_ERROR","Operation aborted by user or timeout"));let h=l.type==="registration"?"enrollment":"auth";if(s!==h)return a(y("INVALID_ARGUMENT",`Bridge context type "${l.type}" does not match kind "${s}"`));if(l.type==="registration"){if(!t?.ticketId?.trim()||!t?.entityId?.trim())return a(b("ticketId/entityId","required for enrollment bridge complete"));let S=g.registration_options;if(!S||typeof S!="object")return a(y("UNKNOWN_ERROR","Bridge verify response missing registration_options"));let C=P(S);if(!C.ok)return a(C.error);let k={...C.value,...t.signal!==void 0&&{signal:t.signal}},w;try{w=await navigator.credentials.create(k)}catch(me){return a(_(me))}try{x(w,"create")}catch(me){return a(_(me))}let A=O(w),H=this.storage??(typeof sessionStorage<"u"?sessionStorage:void 0),xr=K(H),ge=await this.apiClient.completeBridgeEnrollment({session_id:n.value,ticket_id:t.ticketId,entity_id:t.entityId,context_hash:xr,registration_response:{id:A.id,rawId:A.rawId,response:A.response,type:A.type}});return ge.ok?d(dt(ge.value)):a(ge.error)}let R=g.authentication_options;if(!R||typeof R!="object")return a(y("UNKNOWN_ERROR","Bridge verify response missing authentication_options"));let f=X(R);if(!f.ok)return a(f.error);let v={...f.value,...t?.signal!==void 0&&{signal:t.signal}},E;try{E=await navigator.credentials.get(v)}catch(S){return a(_(S))}try{x(E,"get")}catch(S){return a(_(S))}let I=L(E),T=await this.apiClient.completeBridgeAuth({session_id:n.value,credential:{id:I.id,rawId:I.rawId,response:I.response,type:I.type}});return T.ok?d(pt(T.value)):a(T.error)}};var le=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()}};function vr(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 qe(e,r){return{event:e,latencyMs:r,ok:!0}}var ue=class{constructor(r,t,n,s,i){this.apiClient=r;this.eventEmitter=t;this.sandbox=n;this.sandboxToken=s;this.telemetrySender=i}async sandboxAuthResult(r,t){let n="externalUserId"in t?t.externalUserId??t.external_user_id??"sandbox":t.external_user_id??t.externalUserId??"sandbox",s=typeof n=="string"?n:"sandbox";return r==="register"?Promise.resolve(d({success:!0,credentialId:"",status:"sandbox",sessionToken:this.sandboxToken,user:{userId:"sandbox-user",externalUserId:s}})):Promise.resolve(d({authenticated:!0,sessionToken:this.sandboxToken,user:{userId:"sandbox-user",externalUserId:s}}))}async register(r){if(this.sandbox){let s=await this.sandboxAuthResult("register",r);return s.ok&&this.eventEmitter.emit("success",{type:"success",operation:"register",token:s.value.sessionToken,user:s.value.user}),s}let t=Date.now(),n=await gr(r,this.apiClient,this.eventEmitter);return n.ok&&this.telemetrySender&&this.telemetrySender.send(qe("register",Date.now()-t)).catch(()=>{}),n}async authenticate(r){if(this.sandbox){let s=await this.sandboxAuthResult("authenticate",r);return s.ok&&this.eventEmitter.emit("success",{type:"success",operation:"authenticate",token:s.value.sessionToken,user:s.value.user}),s}let t=Date.now(),n=await mr(r,this.apiClient,this.eventEmitter);return n.ok&&this.telemetrySender&&this.telemetrySender.send(qe("authenticate",Date.now()-t)).catch(()=>{}),n}};async function Er(e,r,t){let n=e.externalUserId??e.external_user_id;if(!n||typeof n!="string"||n.trim()===""){let i=b("externalUserId","must be a non-empty string");return t.emit("error",{type:"error",error:i}),a(i)}if(!e.otp||typeof e.otp!="string"||e.otp.trim().length!==6){let i=b("otp","must be a 6-digit string");return t.emit("error",{type:"error",error:i}),a(i)}let s=await W({operation:"register",eventEmitter:t,start:()=>r.verifyAccountRecoveryOtp(n,e.otp),createOptions:i=>P(i.challenge),invoke:async i=>navigator.credentials.create(i),finish:async(i,l)=>{let c=await r.completeAccountRecovery(i.recovery_session_id,O(l));if(!c.ok)return a(c.error);let{credential_id:g,status:h,session_token:R,user:f,redirect_url:v}=c.value;return d({success:!0,credentialId:g,status:h,sessionToken:R,user:{userId:f.user_id,externalUserId:f.external_user_id,email:f.email,metadata:f.metadata},...v!==void 0&&{redirectUrl:v}})}});return s.ok&&t.emit("success",{type:"success",operation:"register",token:s.value.sessionToken,user:s.value.user}),s}var ce=class{constructor(r,t){this.apiClient=r;this.eventEmitter=t}recover(r){return Er(r,this.apiClient,this.eventEmitter)}};var de=class e{sandbox;sandboxToken;apiClient;eventEmitter;telemetrySender;crossDeviceManager;authService;recoveryService;onboarding;enrollmentManager;bridgeManager;contextHashStorage;static create(r){try{let t=r.appId,n=r.publishableKey;if(!t||typeof t!="string"||t.trim()==="")return a(b("appId","must be a non-empty string"));if(!n||typeof n!="string"||n.trim()==="")return a(b("publishableKey","must be a non-empty string"));let s=r.apiBaseUrl??ye;Ee(s,"apiBaseUrl");let i=r.timeoutMs??3e4;return N(i,"timeoutMs",1e3,3e5),r.maxRetries!==void 0&&N(r.maxRetries,"maxRetries",0,10),r.retryDelayMs!==void 0&&N(r.retryDelayMs,"retryDelayMs",100,1e4),d(new e(r))}catch(t){return he(t)?a(t):a(b("config",t.message))}}constructor(r){this.sandbox=r.sandbox===!0,this.sandboxToken=this.sandbox&&r.sandboxToken!=null&&r.sandboxToken!==""?r.sandboxToken:rr;let t=r.appId,n=r.publishableKey;if(!t||typeof t!="string"||t.trim()==="")throw b("appId","must be a non-empty string");if(!n||typeof n!="string"||n.trim()==="")throw b("publishableKey","must be a non-empty string");let s=r.apiBaseUrl??ye;Ee(s,"apiBaseUrl");let i=r.timeoutMs??3e4;N(i,"timeoutMs",1e3,3e5),r.maxRetries!==void 0&&N(r.maxRetries,"maxRetries",0,10),r.retryDelayMs!==void 0&&N(r.retryDelayMs,"retryDelayMs",100,1e4);let l=r.maxRetries??3,c=r.retryDelayMs??1e3,g=new re(i,l,c,r.logger),h=r.origin??(typeof window<"u"&&window?.location?.origin?window.location.origin:void 0),R={"X-App-Id":t.trim(),Authorization:`Bearer ${n.trim()}`,...h&&{Origin:h}};this.apiClient=new ee(g,s,R),this.eventEmitter=new le,r.enableTelemetry&&(this.telemetrySender=r.telemetrySender??vr(r.telemetryEndpoint??er)),this.authService=new ue(this.apiClient,this.eventEmitter,this.sandbox,this.sandboxToken,this.telemetrySender),this.recoveryService=new ce(this.apiClient,this.eventEmitter),this.contextHashStorage=r.contextHashStorage,this.onboarding=new ne(this.apiClient),this.enrollmentManager=new se(this.apiClient,this.contextHashStorage),this.crossDeviceManager=new ie(this.apiClient),this.bridgeManager=new ae(this.apiClient,this.contextHashStorage)}get bridge(){return{getContext:(r,t)=>this.bridgeManager.getContext(r,t),verifyPin:(r,t,n)=>this.bridgeManager.verifyPin(r,t,n),complete:(r,t)=>this.bridgeManager.complete(r,t),waitForResult:(r,t)=>this.bridgeManager.waitForResult(r,t)}}static isSupported(){return F()}async register(r){return this.authService.register(r)}async authenticate(r){return this.authService.authenticate(r)}async enroll(r){this.eventEmitter.emit("start",{type:"start",operation:"enroll"});let t=await this.enrollmentManager.enroll(r);return t.ok?this.eventEmitter.emit("success",{type:"success",operation:"enroll",token:t.value.sessionToken}):this.eventEmitter.emit("error",{type:"error",operation:"enroll",error:t.error}),t}getContextHash(){let r=this.contextHashStorage??(typeof sessionStorage<"u"?sessionStorage:void 0);return K(r)}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 dr()}on(r,t){return this.eventEmitter.on(r,t)}version(){return"2.3.0"}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?d({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:r=>this.recoveryService.recover(r)}};var pe=new yt("TRYMELLON_CONFIG"),kr,Ge;kr=[Rt({providedIn:"root"})];var j=class{config=ht(pe,{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 de(this.config)}return this._client}enroll(r){return this.client.enroll(r)}getContextHash(){return this.client.getContextHash()}};Ge=ze(null),j=Qe(Ge,0,"TryMellonService",kr,j),Ze(Ge,1,j);function Gs(e){return{provide:pe,useValue:e}}export{pe as TRYMELLON_CONFIG,j as TryMellonService,Gs as provideTryMellonConfig};
2
+ var q=Object.create;var I=Object.defineProperty;var z=Object.getOwnPropertyDescriptor;var P=(r,e)=>(e=Symbol[r])?e:Symbol.for("Symbol."+r),M=r=>{throw TypeError(r)};var A=(r,e,o)=>e in r?I(r,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):r[e]=o;var R=(r,e)=>I(r,"name",{value:e,configurable:!0});var j=r=>[,,,q(r?.[P("metadata")]??null)],w=["class","method","getter","setter","accessor","field","value","get","set"],s=r=>r!==void 0&&typeof r!="function"?M("Function expected"):r,B=(r,e,o,T,n)=>({kind:w[r],name:e,metadata:T,addInitializer:l=>o._?M("Already initialized"):n.push(s(l||null))}),D=(r,e)=>A(e,P("metadata"),r[3]),H=(r,e,o,T)=>{for(var n=0,l=r[e>>1],c=l&&l.length;n<c;n++)e&1?l[n].call(o):T=l[n].call(o,T);return T},b=(r,e,o,T,n,l)=>{var c,p,C,y,E,t=e&7,d=!!(e&8),a=!!(e&16),N=t>3?r.length+1:t?d?1:2:0,g=w[t+5],x=t>3&&(r[N-1]=[]),V=r[N]||(r[N]=[]),L=t&&(!a&&!d&&(n=n.prototype),t<5&&(t>3||!a)&&z(t<4?n:{get[o](){return O(this,l)},set[o](i){return Y(this,l,i)}},o));t?a&&t<4&&R(l,(t>2?"set ":t>1?"get ":"")+o):R(n,o);for(var f=T.length-1;f>=0;f--)y=B(t,o,C={},r[3],V),t&&(y.static=d,y.private=a,E=y.access={has:a?i=>F(n,i):i=>o in i},t^3&&(E.get=a?i=>(t^1?O:G)(i,n,t^4?l:L.get):i=>i[o]),t>2&&(E.set=a?(i,v)=>Y(i,n,v,t^4?l:L.set):(i,v)=>i[o]=v)),p=(0,T[f])(t?t<4?a?l:L[g]:t>4?void 0:{get:L.get,set:L.set}:n,y),C._=1,t^4||p===void 0?s(p)&&(t>4?x.unshift(p):t?a?l=p:L[g]=p:n=p):typeof p!="object"||p===null?M("Object expected"):(s(c=p.get)&&(L.get=c),s(c=p.set)&&(L.set=c),s(c=p.init)&&x.unshift(c));return t||D(r,n),L&&I(n,o,L),a?t^4?l:L:n};var _=(r,e,o)=>e.has(r)||M("Cannot "+o),F=(r,e)=>Object(e)!==e?M('Cannot use the "in" operator on this value'):r.has(e),O=(r,e,o)=>(_(r,e,"read from private field"),o?o.call(r):e.get(r));var Y=(r,e,o,T)=>(_(r,e,"write to private field"),T?T.call(r,o):e.set(r,o),o),G=(r,e,o)=>(_(r,e,"access private method"),o);import{Injectable as J,InjectionToken as K,inject as Q}from"@angular/core";var u=new K("TRYMELLON_CLIENT"),k,h;k=[J({providedIn:"root"})];var m=class{_client=Q(u,{optional:!0});get client(){if(this._client==null)throw new Error("TryMellonService: provide TRYMELLON_CLIENT (e.g. via provideTryMellon(client))");return this._client}enroll(e){return this.client.enroll(e)}getContextHash(){return this.client.getContextHash()}};h=j(null),m=b(h,0,"TryMellonService",k,m),H(h,1,m);function S(r){return{provide:u,useValue:r}}export{u as TRYMELLON_CLIENT,m as TryMellonService,S as provideTryMellon};
3
3
  //# sourceMappingURL=angular.js.map