@trymellon/js 1.7.6 → 2.0.0
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/README.MD +637 -458
- package/dist/angular.cjs +1 -1
- package/dist/angular.cjs.map +1 -1
- package/dist/angular.d.cts +1 -1
- package/dist/angular.d.ts +1 -1
- package/dist/angular.js +1 -1
- package/dist/angular.js.map +1 -1
- package/dist/index.cjs +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +42 -20
- package/dist/index.d.ts +42 -20
- package/dist/index.global.js +2 -2
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/react.d.cts +1 -1
- package/dist/react.d.ts +1 -1
- package/dist/{trymellon-NM6i2RKa.d.cts → trymellon-P7BPxIry.d.cts} +42 -20
- package/dist/{trymellon-NM6i2RKa.d.ts → trymellon-P7BPxIry.d.ts} +42 -20
- package/dist/ui/index.d.ts +514 -0
- package/dist/ui/index.js +489 -0
- package/dist/ui/index.js.map +1 -0
- package/dist/vue.d.cts +1 -1
- package/dist/vue.d.ts +1 -1
- package/package.json +8 -2
package/dist/angular.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { InjectionToken, Provider } from '@angular/core';
|
|
2
|
-
import { T as TryMellon, e as TryMellonConfig } from './trymellon-
|
|
2
|
+
import { T as TryMellon, e as TryMellonConfig } from './trymellon-P7BPxIry.cjs';
|
|
3
3
|
|
|
4
4
|
declare const TRYMELLON_CONFIG: InjectionToken<TryMellonConfig>;
|
|
5
5
|
declare class TryMellonService {
|
package/dist/angular.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { InjectionToken, Provider } from '@angular/core';
|
|
2
|
-
import { T as TryMellon, e as TryMellonConfig } from './trymellon-
|
|
2
|
+
import { T as TryMellon, e as TryMellonConfig } from './trymellon-P7BPxIry.js';
|
|
3
3
|
|
|
4
4
|
declare const TRYMELLON_CONFIG: InjectionToken<TryMellonConfig>;
|
|
5
5
|
declare class TryMellonService {
|
package/dist/angular.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
var ir=Object.create;var ne=Object.defineProperty;var or=Object.getOwnPropertyDescriptor;var Pe=(e,r)=>(r=Symbol[e])?r:Symbol.for("Symbol."+e),L=e=>{throw TypeError(e)};var ar=(e,r,t)=>r in e?ne(e,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[r]=t;var ke=(e,r)=>ne(e,"name",{value:r,configurable:!0});var Me=e=>[,,,ir(e?.[Pe("metadata")]??null)],De=["class","method","getter","setter","accessor","field","value","get","set"],F=e=>e!==void 0&&typeof e!="function"?L("Function expected"):e,lr=(e,r,t,n,s)=>({kind:De[e],name:r,metadata:n,addInitializer:i=>t._?L("Already initialized"):s.push(F(i||null))}),ur=(e,r)=>ar(r,Pe("metadata"),e[3]),we=(e,r,t,n)=>{for(var s=0,i=e[r>>1],o=i&&i.length;s<o;s++)r&1?i[s].call(t):n=i[s].call(t,n);return n},Ne=(e,r,t,n,s,i)=>{var o,c,f,v,R,m=r&7,b=!!(r&8),_=!!(r&16),O=m>3?e.length+1:m?b?1:2:0,A=De[m+5],q=m>3&&(e[O-1]=[]),V=e[O]||(e[O]=[]),T=m&&(!_&&!b&&(s=s.prototype),m<5&&(m>3||!_)&&or(m<4?s:{get[t](){return Se(this,i)},set[t](I){return xe(this,i,I)}},t));m?_&&m<4&&ke(i,(m>2?"set ":m>1?"get ":"")+t):ke(s,t);for(var re=n.length-1;re>=0;re--)v=lr(m,t,f={},e[3],V),m&&(v.static=b,v.private=_,R=v.access={has:_?I=>cr(s,I):I=>t in I},m^3&&(R.get=_?I=>(m^1?Se:pr)(I,s,m^4?i:T.get):I=>I[t]),m>2&&(R.set=_?(I,te)=>xe(I,s,te,m^4?i:T.set):(I,te)=>I[t]=te)),c=(0,n[re])(m?m<4?_?i:T[A]:m>4?void 0:{get:T.get,set:T.set}:s,v),f._=1,m^4||c===void 0?F(c)&&(m>4?q.unshift(c):m?_?i=c:T[A]=c:s=c):typeof c!="object"||c===null?L("Object expected"):(F(o=c.get)&&(T.get=o),F(o=c.set)&&(T.set=o),F(o=c.init)&&q.unshift(o));return m||ur(e,s),T&&ne(s,t,T),_?m^4?i:T:s};var se=(e,r,t)=>r.has(e)||L("Cannot "+t),cr=(e,r)=>Object(r)!==r?L('Cannot use the "in" operator on this value'):e.has(r),Se=(e,r,t)=>(se(e,r,"read from private field"),t?t.call(e):r.get(e));var xe=(e,r,t,n)=>(se(e,r,"write to private field"),n?n.call(e,t):r.set(e,t),t),pr=(e,r,t)=>(se(e,r,"access private method"),t);import{Injectable as Dr,InjectionToken as wr,inject as Nr}from"@angular/core";var d=e=>({ok:!0,value:e}),u=e=>({ok:!1,error:e});var B=class e extends Error{code;details;isTryMellonError=!0;constructor(r,t,n){super(t),this.name="TryMellonError",this.code=r,this.details=n,Error.captureStackTrace&&Error.captureStackTrace(this,e)}},dr={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 y(e,r,t){return new B(e,r??dr[e],t)}function ie(e){return e instanceof B||typeof e=="object"&&e!==null&&"isTryMellonError"in e&&e.isTryMellonError===!0}function Ue(){return y("NOT_SUPPORTED")}function h(e,r){return y("INVALID_ARGUMENT",`Invalid argument: ${e} - ${r}`,{field:e,reason:r})}function Fe(e){return y("UNKNOWN_ERROR",`Failed to ${e} credential`,{operation:e})}function oe(e){return y("NOT_SUPPORTED",`No base64 ${e==="encode"?"encoding":"decoding"} available`,{type:e})}function ae(e,r){try{let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")throw h(r,"must use http or https protocol")}catch(t){throw ie(t)?t:h(r,"must be a valid URL")}}function x(e,r,t,n){if(!Number.isFinite(e))throw h(r,"must be a finite number");if(e<t||e>n)throw h(r,`must be between ${t} and ${n}`)}function W(e,r){if(typeof e!="string"||e.length===0)throw h(r,"must be a non-empty string");if(!/^[A-Za-z0-9_-]+$/.test(e))throw h(r,"must be a valid base64url string")}var gr={NotAllowedError:"USER_CANCELLED",AbortError:"ABORTED",NotSupportedError:"NOT_SUPPORTED",SecurityError:"NOT_SUPPORTED",InvalidStateError:"UNKNOWN_ERROR",UnknownError:"UNKNOWN_ERROR"};function K(e){if(typeof e!="string")return"UNKNOWN_ERROR";let r=e.toLowerCase().trim();return{challenge_mismatch:"CHALLENGE_MISMATCH",session_expired:"SESSION_EXPIRED",unauthorized:"SESSION_EXPIRED",validation_error:"INVALID_ARGUMENT",invalid_argument:"INVALID_ARGUMENT",user_not_found:"SESSION_EXPIRED",passkey_not_found:"PASSKEY_NOT_FOUND"}[r]??"UNKNOWN_ERROR"}function E(e){if(e instanceof DOMException){let r=e.name,t=e.message||"WebAuthn operation failed",n=gr[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 g(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function l(e){return typeof e=="string"}function k(e){return typeof e=="number"&&Number.isFinite(e)}function H(e){return typeof e=="boolean"}function D(e){return Array.isArray(e)}function a(e,r){return u(y("UNKNOWN_ERROR",e,{...r,originalData:r?.originalData}))}function p(e,r){return e[r]}function Le(e,r){return!g(e)||!l(e.name)||!l(e.id)?a("Invalid API response: challenge.rp must have name and id strings",{originalData:r}):d(!0)}function Ke(e,r){return!g(e)||!l(e.id)||!l(e.name)||!l(e.displayName)?a("Invalid API response: challenge.user must have id, name, displayName strings",{originalData:r}):d(!0)}function je(e,r){if(!D(e))return a("Invalid API response: challenge.pubKeyCredParams must be array",{originalData:r});for(let t of e)if(!g(t)||t.type!=="public-key"||!k(t.alg))return a("Invalid API response: pubKeyCredParams items must have type and alg",{originalData:r});return d(!0)}function le(e,r){if(!g(e))return a("Invalid API response: user must be object",{field:"user",originalData:r});let t=p(e,"user_id"),n=p(e,"external_user_id");if(!l(t)||!l(n))return a("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)?a("Invalid API response: user.email must be string",{originalData:r}):i!==void 0&&(typeof i!="object"||i===null)?a("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 ue(e){if(!g(e))return a("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id");if(!l(r))return a("Invalid API response: session_id must be string",{field:"session_id",originalData:e});let t=p(e,"challenge");if(!g(t))return a("Invalid API response: challenge must be object",{field:"challenge",originalData:e});let n=Le(p(t,"rp"),e);if(!n.ok)return n;let s=Ke(p(t,"user"),e);if(!s.ok)return s;let i=p(t,"challenge");if(!l(i))return a("Invalid API response: challenge.challenge must be string",{originalData:e});let o=je(p(t,"pubKeyCredParams"),e);if(!o.ok)return o;let c=t.timeout;if(c!==void 0&&!k(c))return a("Invalid API response: challenge.timeout must be number",{originalData:e});let f=t.excludeCredentials;if(f!==void 0){if(!D(f))return a("Invalid API response: excludeCredentials must be array",{originalData:e});for(let R of f)if(!g(R)||R.type!=="public-key"||!l(R.id))return a("Invalid API response: excludeCredentials items must have id and type",{originalData:e})}let v=t.authenticatorSelection;return v!==void 0&&!g(v)?a("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},...f!==void 0&&{excludeCredentials:f},...v!==void 0&&{authenticatorSelection:v}}})}function ce(e){if(!g(e))return a("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id");if(!l(r))return a("Invalid API response: session_id must be string",{field:"session_id",originalData:e});let t=p(e,"challenge");if(!g(t))return a("Invalid API response: challenge must be object",{field:"challenge",originalData:e});let n=p(t,"challenge"),s=p(t,"rpId"),i=t.allowCredentials;if(!l(n))return a("Invalid API response: challenge.challenge must be string",{originalData:e});if(!l(s))return a("Invalid API response: challenge.rpId must be string",{originalData:e});if(i!==void 0&&!D(i))return a("Invalid API response: allowCredentials must be array",{originalData:e});if(i){for(let f of i)if(!g(f)||f.type!=="public-key"||!l(f.id))return a("Invalid API response: allowCredentials items must have id and type",{originalData:e})}let o=t.timeout;if(o!==void 0&&!k(o))return a("Invalid API response: challenge.timeout must be number",{originalData:e});let c=t.userVerification;return c!==void 0&&!["required","preferred","discouraged"].includes(String(c))?a("Invalid API response: userVerification must be required|preferred|discouraged",{originalData:e}):d({session_id:r,challenge:{challenge:n,rpId:s,allowCredentials:i??[],...o!==void 0&&{timeout:o},...c!==void 0&&{userVerification:c}}})}function pe(e){if(!g(e))return a("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(!l(r))return a("Invalid API response: credential_id must be string",{field:"credential_id",originalData:e});if(!l(t))return a("Invalid API response: status must be string",{field:"status",originalData:e});if(!l(n))return a("Invalid API response: session_token must be string",{field:"session_token",originalData:e});let i=le(s,e);if(!i.ok)return a(i.error.message,{originalData:e});let o=e.redirect_url;return o!==void 0&&!l(o)?a("Invalid API response: redirect_url must be string",{originalData:e}):d({credential_id:r,status:t,session_token:n,user:i.value,...o!==void 0&&{redirect_url:o}})}function de(e){if(!g(e))return a("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(!H(r))return a("Invalid API response: authenticated must be boolean",{field:"authenticated",originalData:e});if(!l(t))return a("Invalid API response: session_token must be string",{field:"session_token",originalData:e});let i=le(n,e);if(!i.ok)return a(i.error.message,{originalData:e});if(s!==void 0&&!g(s))return a("Invalid API response: signals must be object",{originalData:e});let o=e.redirect_url;return o!==void 0&&!l(o)?a("Invalid API response: redirect_url must be string",{originalData:e}):d({authenticated:r,session_token:t,user:i.value,signals:s,...o!==void 0&&{redirect_url:o}})}function ge(e){if(!g(e))return a("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 H(r)?l(t)?l(n)?l(s)?l(i)?d({valid:r,user_id:t,external_user_id:n,tenant_id:s,app_id:i}):a("Invalid API response: app_id must be string",{field:"app_id",originalData:e}):a("Invalid API response: tenant_id must be string",{field:"tenant_id",originalData:e}):a("Invalid API response: external_user_id must be string",{field:"external_user_id",originalData:e}):a("Invalid API response: user_id must be string",{field:"user_id",originalData:e}):a("Invalid API response: valid must be boolean",{field:"valid",originalData:e})}function me(e){if(!g(e))return a("Invalid API response: expected object",{originalData:e});let r=e.session_token??e.sessionToken;if(!l(r))return a("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)?a("Invalid API response: redirect_url must be string",{originalData:e}):d({sessionToken:r,...t!==void 0&&{redirectUrl:t}})}var mr=["pending_passkey","pending_data","completed"],fr=["pending_data","completed"];function fe(e){if(!g(e))return a("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id"),t=p(e,"onboarding_url"),n=p(e,"expires_in");return l(r)?l(t)?k(n)?d({session_id:r,onboarding_url:t,expires_in:n}):a("Invalid API response: expires_in must be number",{field:"expires_in",originalData:e}):a("Invalid API response: onboarding_url must be string",{field:"onboarding_url",originalData:e}):a("Invalid API response: session_id must be string",{field:"session_id",originalData:e})}function Re(e){if(!g(e))return a("Invalid API response: expected object",{originalData:e});let r=p(e,"status"),t=p(e,"onboarding_url"),n=p(e,"expires_in");return!l(r)||!mr.includes(r)?a("Invalid API response: status must be pending_passkey|pending_data|completed",{field:"status",originalData:e}):l(t)?k(n)?d({status:r,onboarding_url:t,expires_in:n}):a("Invalid API response: expires_in must be number",{originalData:e}):a("Invalid API response: onboarding_url must be string",{originalData:e})}function ye(e){if(!g(e))return a("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id"),t=p(e,"status"),n=p(e,"onboarding_url");if(!l(r))return a("Invalid API response: session_id must be string",{field:"session_id",originalData:e});if(t!=="pending_passkey")return a("Invalid API response: status must be pending_passkey",{field:"status",originalData:e});if(!l(n))return a("Invalid API response: onboarding_url must be string",{originalData:e});let s=e.challenge,i;if(s!==void 0){let o=Rr(s);if(!o.ok)return o;i=o.value}return d({session_id:r,status:"pending_passkey",onboarding_url:n,...i!==void 0&&{challenge:i}})}function Rr(e){if(!g(e))return a("Invalid API response: challenge must be object",{originalData:e});let r=p(e,"rp"),t=p(e,"user"),n=p(e,"challenge"),s=p(e,"pubKeyCredParams");if(!g(r)||!l(r.name)||!l(r.id))return a("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 a("Invalid API response: challenge.user must have id, name, displayName",{originalData:e});if(!l(n))return a("Invalid API response: challenge.challenge must be string",{originalData:e});if(!D(s))return a("Invalid API response: challenge.pubKeyCredParams must be array",{originalData:e});for(let i of s)if(!g(i)||i.type!=="public-key"||!k(i.alg))return a("Invalid API response: pubKeyCredParams items must have type and alg",{originalData:e});return d({rp:r,user:t,challenge:n,pubKeyCredParams:s})}function ve(e){if(!g(e))return a("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 l(r)?!l(t)||!fr.includes(t)?a("Invalid API response: status must be pending_data|completed",{originalData:e}):l(n)?l(s)?d({session_id:r,status:t,user_id:n,tenant_id:s}):a("Invalid API response: tenant_id must be string",{originalData:e}):a("Invalid API response: user_id must be string",{originalData:e}):a("Invalid API response: session_id must be string",{originalData:e})}function he(e){if(!g(e))return a("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 l(r)?t!=="completed"?a("Invalid API response: status must be completed",{originalData:e}):!l(n)||!l(s)||!l(i)?a("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}):a("Invalid API response: session_id must be string",{originalData:e})}function yr(e){if(!e||typeof e!="object")return!1;let r=e;return typeof r.challenge=="string"&&r.rp!=null&&typeof r.rp=="object"&&r.user!=null&&typeof r.user=="object"&&Array.isArray(r.pubKeyCredParams)}function vr(e){if(!e||typeof e!="object")return!1;let r=e;return typeof r.challenge=="string"&&typeof r.rpId=="string"}function G(e){if(!g(e))return a("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)?a("Invalid API response: missing required fields",{originalData:e}):d({session_id:t,qr_url:n,expires_at:s,polling_token:i})}function Ee(e){if(!g(e))return a("Invalid API response: expected object",{originalData:e});let r=e.status;return!l(r)||!["pending","authenticated","completed"].includes(r)?a("Invalid API response: invalid status",{originalData:e}):d({status:r,user_id:e.user_id,session_token:e.session_token})}function be(e){if(!g(e))return a("Invalid API response: expected object",{originalData:e});let r=e.type,t=r==="registration"?"registration":"auth",n=e.options;if(!g(n))return a("Invalid API response: options are required",{originalData:e});let s=200,i=qe(e.approval_context,s),o=qe(e.application_name,s);if(i===!1||o===!1)return a("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 o=="string"&&(c.application_name=o),t==="registration"?yr(n)?d({type:"registration",options:n,...c}):a("Invalid API response: registration options must have challenge, rp, user, pubKeyCredParams",{originalData:e}):vr(n)?d({type:"auth",options:n,...c}):a("Invalid API response: auth options must have challenge and rpId",{originalData:e})}function qe(e,r){if(e!=null)return typeof e!="string"||e.length>r?!1:e}function _e(e){if(!g(e))return a("Invalid API response: expected object",{originalData:e});let r=p(e,"challenge"),t=p(e,"recovery_session_id");return g(r)?l(t)?d({challenge:r,recovery_session_id:t}):a("Invalid API response: recovery_session_id must be string",{field:"recovery_session_id",originalData:e}):a("Invalid API response: challenge must be object",{field:"challenge",originalData:e})}function Te(e){if(!g(e))return a("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(!l(r))return a("Invalid API response: status must be string",{field:"status",originalData:e});if(!l(t))return a("Invalid API response: session_token must be string",{field:"session_token",originalData:e});if(!l(s))return a("Invalid API response: credential_id must be string",{field:"credential_id",originalData:e});if(!g(n))return a("Invalid API response: user must be object",{field:"user",originalData:e});let i=p(n,"user_id");if(!l(i))return a("Invalid API response: user.user_id must be string",{field:"user.user_id",originalData:e});let o=n;return d({status:r,session_token:t,credential_id:s,user:{user_id:i,external_user_id:l(o.external_user_id)?o.external_user_id:void 0,email:l(o.email)?o.email:void 0,metadata:g(o.metadata)?o.metadata:void 0}})}var X=class{constructor(r,t,n={}){this.httpClient=r;this.baseUrl=t;this.defaultHeaders=n}mergeHeaders(r){return{...this.defaultHeaders,...r}}async post(r,t,n){let s=`${this.baseUrl}${r}`,i=await this.httpClient.post(s,t,this.mergeHeaders());return i.ok?n(i.value):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,ue)}async startAuth(r){return this.post("/v1/passkeys/auth/start",r,ce)}async finishRegister(r){return this.post("/v1/passkeys/register/finish",r,pe)}async finishAuthentication(r){return this.post("/v1/passkeys/auth/finish",r,de)}async validateSession(r){return this.get("/v1/sessions/validate",ge,{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):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,me)}async startOnboarding(r){return this.post("/v1/onboarding/start",r,fe)}async getOnboardingStatus(r){return this.get(`/v1/onboarding/${r}/status`,Re)}async getOnboardingRegister(r){return this.get(`/v1/onboarding/${r}/register`,ye)}async registerOnboardingPasskey(r,t){return this.post(`/v1/onboarding/${r}/register-passkey`,t,ve)}async completeOnboarding(r,t){return this.post(`/v1/onboarding/${r}/complete`,t,he)}async initCrossDeviceAuth(){return this.post("/v1/auth/cross-device/init",{},G)}async initCrossDeviceRegistration(r){return this.post("/v1/auth/cross-device/init-registration",{external_user_id:r.externalUserId},G)}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}`,Ee,Object.keys(n).length>0?n:void 0)}async getCrossDeviceContext(r){return this.get(`/v1/auth/cross-device/context/${r}`,be)}async verifyCrossDeviceAuth(r){let t=`${this.baseUrl}/v1/auth/cross-device/verify`,n=await this.httpClient.post(t,r,this.mergeHeaders());return n.ok?d(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?d(void 0):u(n.error)}async verifyAccountRecoveryOtp(r,t){return this.post("/v1/users/recovery/verify",{external_id:r,otp:t},_e)}async completeAccountRecovery(r,t){return this.post("/v1/users/recovery/complete",{recovery_session_id:r,credential:t},Te)}};function hr(e){return typeof e=="object"&&e!==null&&e.ok===!0&&"resultado"in e}function Er(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 br(e,r){if(Er(e))return{message:e.error.message,code:K(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:K(n.code)};let s=t?.message??r,i=t?.error,o=typeof i=="string"?K(i):i===void 0?"NETWORK_FAILURE":K(String(i));return{message:s,code:o}}var _r=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 Ve(e,r){let t=r*Math.pow(2,e);return Math.min(t,_r)}function Ir(e,r){return e!=="GET"?!1:r>=500||r===429}var Y=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 o;for(let c=0;c<=this.maxRetries;c++)try{let f=new AbortController,v=setTimeout(()=>f.abort(),this.timeoutMs);try{let R=await fetch(r,{...t,headers:i,signal:f.signal});if(!R.ok){let O;try{O=await R.json()}catch{}let{message:A,code:q}=br(O,R.statusText),V=y(q,A,{requestId:s,status:R.status,statusText:R.statusText,data:O});if(Ir(n,R.status)&&c<this.maxRetries){o=V,clearTimeout(v),await new Promise(T=>setTimeout(T,Ve(c,this.retryDelayMs)));continue}return u(V)}if(R.status===204)return d(void 0);if(R.headers.get("content-length")==="0")return d(void 0);let b=await R.json();if(hr(b))return d(b.resultado);let _=b;return typeof b=="object"&&b!==null&&_.ok===!0&&!("resultado"in _)?d(void 0):d(b)}finally{clearTimeout(v)}}catch(f){if(o=f,n==="GET"&&c<this.maxRetries)await new Promise(R=>setTimeout(R,Ve(c,this.retryDelayMs)));else break}return o instanceof Error&&o.name==="AbortError"?u(y("TIMEOUT","Request timed out",{requestId:s})):u(y("NETWORK_FAILURE",o instanceof Error?o.message:"Request failed",{requestId:s,cause:o}))}};function C(e){let r=new Uint8Array(e),t=Array.from(r,s=>String.fromCharCode(s)).join("");if(typeof globalThis.btoa>"u")throw oe("encode");return globalThis.btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Ar(e){if(typeof globalThis.atob>"u")throw oe("decode");let r=e.replace(/-/g,"+").replace(/_/g,"/"),t=r.length%4,n=t===0?r:r+"=".repeat(4-t),s=globalThis.atob(n);return Uint8Array.from(s,i=>i.charCodeAt(0))}function w(e){let r=Ar(e),t=new ArrayBuffer(r.length);return new Uint8Array(t).set(r),t}function Be(e){return e!==null&&typeof e=="object"&&"clientDataJSON"in e&&e.clientDataJSON instanceof ArrayBuffer}function S(e){if(!e.response)throw y("UNKNOWN_ERROR","Credential response is missing",{credential:e});let r=e.response;if(!Be(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:C(e.rawId),response:{clientDataJSON:C(t),attestationObject:C(n)},type:"public-key"}}function $(e){if(!e.response)throw y("UNKNOWN_ERROR","Credential response is missing",{credential:e});let r=e.response;if(!Be(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:C(e.rawId),response:{authenticatorData:C(n),clientDataJSON:C(t),signature:C(s),...i&&{userHandle:C(i)}},type:"public-key"}}function N(){try{return!(typeof navigator>"u"||!navigator.credentials||typeof PublicKeyCredential>"u")}catch{return!1}}async function Cr(){try{return!N()||typeof PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable!="function"?!1:await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}async function We(){let e=N(),r=await Cr();return{isPasskeySupported:e,platformAuthenticatorAvailable:r,recommendedFlow:e?"passkey":"fallback"}}function P(e,r="create"){if(!e||typeof e!="object"||!("id"in e)||!("rawId"in e)||!("response"in e))throw Fe(r)}async function j(e){let{operation:r,eventEmitter:t,start:n,createOptions:s,invoke:i,finish:o}=e;try{if(t.emit("start",{type:"start",operation:r}),!N()){let m=Ue();return t.emit("error",{type:"error",error:m}),u(m)}let c=await n();if(!c.ok)return t.emit("error",{type:"error",error:c.error}),u(c.error);let f=s(c.value);if(!f.ok)return t.emit("error",{type:"error",error:f.error}),u(f.error);let v=await i(f.value);if(!v){let m=h("credential",`${r==="register"?"creation":"retrieval"} failed`);return t.emit("error",{type:"error",error:m}),u(m)}try{P(v)}catch(m){let b=E(m);return t.emit("error",{type:"error",error:b}),u(b)}let R=await o(c.value,v);return R.ok?(t.emit("success",{type:"success",operation:r}),d(R.value)):(t.emit("error",{type:"error",error:R.error}),u(R.error))}catch(c){let f=E(c);return t.emit("error",{type:"error",error:f}),u(f)}}function M(e,r){try{W(e.challenge,"challenge"),W(e.user.id,"user.id");let t=w(e.challenge),n=w(e.user.id),s={userVerification:"preferred"};e.authenticatorSelection&&(s={...e.authenticatorSelection}),r&&(s={...s,authenticatorAttachment:r});let i={rp:{id:e.rp.id,name:e.rp.name},user:{id:n,name:e.user.name,displayName:e.user.displayName},challenge:t,pubKeyCredParams:e.pubKeyCredParams,...e.timeout!==void 0&&{timeout:e.timeout},attestation:"none",authenticatorSelection:s,...e.excludeCredentials&&{excludeCredentials:e.excludeCredentials.map(o=>({id:w(o.id),type:o.type,...o.transports&&{transports:o.transports}}))}};return d({publicKey:i})}catch(t){return u(E(t))}}function Ie(e,r){try{W(e.challenge,"challenge");let t=w(e.challenge);return d({publicKey:{challenge:t,rpId:e.rpId,...e.timeout!==void 0&&{timeout:e.timeout},userVerification:e.userVerification??"preferred",...e.allowCredentials&&{allowCredentials:e.allowCredentials.map(n=>({id:w(n.id),type:n.type,...n.transports&&{transports:n.transports}}))}},...r!==void 0&&{mediation:r}})}catch(t){return u(E(t))}}async function He(e,r,t){let n=e.externalUserId??e.external_user_id;if(!n||typeof n!="string"||n.trim()===""){let s=h("externalUserId","must be a non-empty string");return t.emit("error",{type:"error",error:s}),u(s)}return j({operation:"register",eventEmitter:t,start:()=>r.startRegister({external_user_id:n}),createOptions:s=>M(s.challenge,e.authenticatorType),invoke:async s=>{let i={...s,...e.signal&&{signal:e.signal}};return navigator.credentials.create(i)},finish:async(s,i)=>{let o=await r.finishRegister({session_id:s.session_id,credential:S(i),...e.successUrl&&{success_url:e.successUrl}});return o.ok?d({success:!0,credentialId:o.value.credential_id,credential_id:o.value.credential_id,status:o.value.status,sessionToken:o.value.session_token,user:{userId:o.value.user.user_id,externalUserId:o.value.user.external_user_id,email:o.value.user.email,metadata:o.value.user.metadata},...o.value.redirect_url&&{redirectUrl:o.value.redirect_url}}):u(o.error)}})}async function Ge(e,r,t){let n=e.externalUserId??e.external_user_id,s=n!==void 0&&typeof n=="string"&&n.trim()!=="";return j({operation:"authenticate",eventEmitter:t,start:()=>r.startAuth(s?{external_user_id:n.trim()}:{}),createOptions:i=>Ie(i.challenge,e.mediation),invoke:async i=>{let o={...i,...e.signal&&{signal:e.signal}};return navigator.credentials.get(o)},finish:async(i,o)=>{let c=await r.finishAuthentication({session_id:i.session_id,credential:$(o),...e.successUrl&&{success_url:e.successUrl}});return c.ok?d({authenticated:c.value.authenticated,sessionToken:c.value.session_token,user:{userId:c.value.user.user_id,externalUserId:c.value.user.external_user_id,email:c.value.user.email,metadata:c.value.user.metadata},signals:c.value.signals,...c.value.redirect_url&&{redirectUrl:c.value.redirect_url}}):u(c.error)}})}var Or=2e3,kr=60,z=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<kr;s++){await new Promise(f=>setTimeout(f,Or));let i=await this.apiClient.getOnboardingStatus(n);if(!i.ok)return u(i.error);let o=i.value.status,c=i.value.onboarding_url;if(o==="pending_passkey"){let f=await this.apiClient.getOnboardingRegister(n);if(!f.ok)return u(f.error);let v=f.value;if(!v.challenge)return u(y("NOT_SUPPORTED","Onboarding requires user action - complete passkey registration at the provided onboarding_url",{onboarding_url:c}));let R=M(v.challenge);if(!R.ok)return u(R.error);let m;try{m=await navigator.credentials.create(R.value)}catch(A){return u(E(A))}try{P(m,"create")}catch(A){return u(E(A))}let b;try{b=S(m)}catch(A){return u(E(A))}let _=await this.apiClient.registerOnboardingPasskey(n,{credential:b,challenge:v.challenge.challenge});return _.ok?await this.apiClient.completeOnboarding(n,{company_name:r.company_name}):u(_.error)}if(o==="completed")return await this.apiClient.completeOnboarding(n,{company_name:r.company_name})}return u(y("TIMEOUT","Onboarding timed out"))}};var Sr=2e3,xr=60,J=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<xr;s++){if(t?.aborted)return u(y("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(y("UNKNOWN_ERROR","Missing data in completed session")):d({session_token:i.value.session_token,user_id:i.value.user_id});if(t?.aborted)return u(y("ABORT_ERROR","Operation aborted by user or timeout"));if(await new Promise(o=>{let c=setTimeout(()=>{o(null),t?.removeEventListener("abort",f)},Sr),f=()=>{clearTimeout(c),o(null)};t?.addEventListener("abort",f)}),t?.aborted)return u(y("ABORT_ERROR","Operation aborted by user or timeout"))}return u(y("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=M(t.options);if(!n.ok)return u(n.error);let s;try{s=await navigator.credentials.create(n.value)}catch(o){return u(E(o))}try{P(s,"create")}catch(o){return u(E(o))}let i;try{i=S(s)}catch(o){return u(E(o))}return this.apiClient.verifyCrossDeviceRegistration({session_id:r,credential:i})}async executeAuthApproval(r,t){let n=Ie(t.options);if(!n.ok)return u(n.error);let s;try{s=await navigator.credentials.get(n.value)}catch(o){return u(E(o))}try{P(s,"get")}catch(o){return u(E(o))}let i;try{i=$(s)}catch(o){return u(E(o))}return this.apiClient.verifyCrossDeviceAuth({session_id:r,credential:i})}};var Z=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 Xe(e,r,t){let n=e.externalUserId??e.external_user_id;if(!n||typeof n!="string"||n.trim()===""){let s=h("externalUserId","must be a non-empty string");return t.emit("error",{type:"error",error:s}),u(s)}if(!e.otp||typeof e.otp!="string"||e.otp.trim().length!==6){let s=h("otp","must be a 6-digit string");return t.emit("error",{type:"error",error:s}),u(s)}return j({operation:"register",eventEmitter:t,start:()=>r.verifyAccountRecoveryOtp(n,e.otp),createOptions:s=>M(s.challenge),invoke:async s=>navigator.credentials.create(s),finish:async(s,i)=>{let o=await r.completeAccountRecovery(s.recovery_session_id,S(i));return o.ok?d({success:!0,credentialId:o.value.credential_id,status:o.value.status,sessionToken:o.value.session_token,user:{userId:o.value.user.user_id,externalUserId:o.value.user.external_user_id,email:o.value.user.email,metadata:o.value.user.metadata}}):u(o.error)}})}var Ae="https://api.trymellonauth.com",Ye="https://api.trymellonauth.com/v1/telemetry";var $e="trymellon_sandbox_session_token_v1";function ze(e){return{async send(r){let t=JSON.stringify(r);if(typeof navigator<"u"&&typeof navigator.sendBeacon=="function"){navigator.sendBeacon(e,t);return}typeof fetch<"u"&&await fetch(e,{method:"POST",body:t,headers:{"Content-Type":"application/json"},keepalive:!0})}}}function Ce(e,r){return{event:e,latencyMs:r,ok:!0}}var Q=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(h("appId","must be a non-empty string"));if(!n||typeof n!="string"||n.trim()==="")return u(h("publishableKey","must be a non-empty string"));let s=r.apiBaseUrl??Ae;ae(s,"apiBaseUrl");let i=r.timeoutMs??3e4;return x(i,"timeoutMs",1e3,3e5),r.maxRetries!==void 0&&x(r.maxRetries,"maxRetries",0,10),r.retryDelayMs!==void 0&&x(r.retryDelayMs,"retryDelayMs",100,1e4),d(new e(r))}catch(t){return ie(t)?u(t):u(h("config",t.message))}}constructor(r){this.sandbox=r.sandbox===!0,this.sandboxToken=this.sandbox&&r.sandboxToken!=null&&r.sandboxToken!==""?r.sandboxToken:$e;let t=r.appId,n=r.publishableKey;if(!t||typeof t!="string"||t.trim()==="")throw h("appId","must be a non-empty string");if(!n||typeof n!="string"||n.trim()==="")throw h("publishableKey","must be a non-empty string");let s=r.apiBaseUrl??Ae;ae(s,"apiBaseUrl");let i=r.timeoutMs??3e4;x(i,"timeoutMs",1e3,3e5),r.maxRetries!==void 0&&x(r.maxRetries,"maxRetries",0,10),r.retryDelayMs!==void 0&&x(r.retryDelayMs,"retryDelayMs",100,1e4);let o=r.maxRetries??3,c=r.retryDelayMs??1e3,f=new Y(i,o,c,r.logger),v=r.origin??(typeof window<"u"&&window?.location?.origin?window.location.origin:void 0),R={"X-App-Id":t.trim(),Authorization:`Bearer ${n.trim()}`,...v&&{Origin:v}};this.apiClient=new X(f,s,R),this.onboarding=new z(this.apiClient),this.crossDeviceManager=new J(this.apiClient),this.eventEmitter=new Z,r.enableTelemetry&&(this.telemetrySender=r.telemetrySender??ze(r.telemetryEndpoint??Ye))}static isSupported(){return N()}sandboxAuthResult(r,t){let n=t.externalUserId??t.external_user_id??"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)return this.sandboxAuthResult("register",r);let t=Date.now(),n=await He(r,this.apiClient,this.eventEmitter);return n.ok&&this.telemetrySender&&this.telemetrySender.send(Ce("register",Date.now()-t)).catch(()=>{}),n}async authenticate(r){if(this.sandbox)return this.sandboxAuthResult("authenticate",r);let t=Date.now(),n=await Ge(r,this.apiClient,this.eventEmitter);return n.ok&&this.telemetrySender&&this.telemetrySender.send(Ce("authenticate",Date.now()-t)).catch(()=>{}),n}async validateSession(r){return this.sandbox&&r===this.sandboxToken?Promise.resolve(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 We()}on(r,t){return this.eventEmitter.on(r,t)}version(){return"1.7.6"}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:async r=>Xe(r,this.apiClient,this.eventEmitter)}};var ee=new wr("TRYMELLON_CONFIG"),sr,Oe;sr=[Dr({providedIn:"root"})];var U=class{config=Nr(ee,{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 Q(this.config)}return this._client}};Oe=Me(null),U=Ne(Oe,0,"TryMellonService",sr,U),we(Oe,1,U);function On(e){return{provide:ee,useValue:e}}export{ee as TRYMELLON_CONFIG,U as TryMellonService,On as provideTryMellonConfig};
|
|
2
|
+
var pr=Object.create;var ae=Object.defineProperty;var dr=Object.getOwnPropertyDescriptor;var Ne=(e,r)=>(r=Symbol[e])?r:Symbol.for("Symbol."+e),j=e=>{throw TypeError(e)};var mr=(e,r,t)=>r in e?ae(e,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[r]=t;var Me=(e,r)=>ae(e,"name",{value:r,configurable:!0});var Ue=e=>[,,,pr(e?.[Ne("metadata")]??null)],Fe=["class","method","getter","setter","accessor","field","value","get","set"],K=e=>e!==void 0&&typeof e!="function"?j("Function expected"):e,gr=(e,r,t,n,s)=>({kind:Fe[e],name:r,metadata:n,addInitializer:i=>t._?j("Already initialized"):s.push(K(i||null))}),fr=(e,r)=>mr(r,Ne("metadata"),e[3]),Le=(e,r,t,n)=>{for(var s=0,i=e[r>>1],a=i&&i.length;s<a;s++)r&1?i[s].call(t):n=i[s].call(t,n);return n},Ke=(e,r,t,n,s,i)=>{var a,l,m,v,R,g=r&7,h=!!(r&8),b=!!(r&16),I=g>3?e.length+1:g?h?1:2:0,O=Fe[g+5],L=g>3&&(e[I-1]=[]),C=e[I]||(e[I]=[]),T=g&&(!b&&!h&&(s=s.prototype),g<5&&(g>3||!b)&&dr(g<4?s:{get[t](){return De(this,i)},set[t](A){return we(this,i,A)}},t));g?b&&g<4&&Me(i,(g>2?"set ":g>1?"get ":"")+t):Me(s,t);for(var ie=n.length-1;ie>=0;ie--)v=gr(g,t,m={},e[3],C),g&&(v.static=h,v.private=b,R=v.access={has:b?A=>Rr(s,A):A=>t in A},g^3&&(R.get=b?A=>(g^1?De:yr)(A,s,g^4?i:T.get):A=>A[t]),g>2&&(R.set=b?(A,oe)=>we(A,s,oe,g^4?i:T.set):(A,oe)=>A[t]=oe)),l=(0,n[ie])(g?g<4?b?i:T[O]:g>4?void 0:{get:T.get,set:T.set}:s,v),m._=1,g^4||l===void 0?K(l)&&(g>4?L.unshift(l):g?b?i=l:T[O]=l:s=l):typeof l!="object"||l===null?j("Object expected"):(K(a=l.get)&&(T.get=a),K(a=l.set)&&(T.set=a),K(a=l.init)&&L.unshift(a));return g||fr(e,s),T&&ae(s,t,T),b?g^4?i:T:s};var le=(e,r,t)=>r.has(e)||j("Cannot "+t),Rr=(e,r)=>Object(r)!==r?j('Cannot use the "in" operator on this value'):e.has(r),De=(e,r,t)=>(le(e,r,"read from private field"),t?t.call(e):r.get(e));var we=(e,r,t,n)=>(le(e,r,"write to private field"),n?n.call(e,t):r.set(e,t),t),yr=(e,r,t)=>(le(e,r,"access private method"),t);import{Injectable as Fr,InjectionToken as Lr,inject as Kr}from"@angular/core";var d=e=>({ok:!0,value:e}),c=e=>({ok:!1,error:e});var W=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)}},vr={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 y(e,r,t){return new W(e,r??vr[e],t)}function ue(e){return e instanceof W||typeof e=="object"&&e!==null&&"isTryMellonError"in e&&e.isTryMellonError===!0}function je(){return y("NOT_SUPPORTED")}function E(e,r){return y("INVALID_ARGUMENT",`Invalid argument: ${e} - ${r}`,{field:e,reason:r})}function qe(e){return y("UNKNOWN_ERROR",`Failed to ${e} credential`,{operation:e})}function ce(e){return y("NOT_SUPPORTED",`No base64 ${e==="encode"?"encoding":"decoding"} available`,{type:e})}function pe(e,r){try{let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")throw E(r,"must use http or https protocol")}catch(t){throw ue(t)?t:E(r,"must be a valid URL")}}function P(e,r,t,n){if(!Number.isFinite(e))throw E(r,"must be a finite number");if(e<t||e>n)throw E(r,`must be between ${t} and ${n}`)}function B(e,r){if(typeof e!="string"||e.length===0)throw E(r,"must be a non-empty string");if(!/^[A-Za-z0-9_-]+$/.test(e))throw E(r,"must be a valid base64url string")}var hr={NotAllowedError:"USER_CANCELLED",AbortError:"ABORTED",NotSupportedError:"NOT_SUPPORTED",SecurityError:"NOT_SUPPORTED",InvalidStateError:"UNKNOWN_ERROR",UnknownError:"UNKNOWN_ERROR"};function q(e){if(typeof e!="string")return"UNKNOWN_ERROR";let r=e.toLowerCase().trim();return{challenge_mismatch:"CHALLENGE_MISMATCH",session_expired:"SESSION_EXPIRED",unauthorized:"SESSION_EXPIRED",validation_error:"INVALID_ARGUMENT",invalid_argument:"INVALID_ARGUMENT",user_not_found:"SESSION_EXPIRED",passkey_not_found:"PASSKEY_NOT_FOUND"}[r]??"UNKNOWN_ERROR"}function _(e){if(e instanceof DOMException){let r=e.name,t=e.message||"WebAuthn operation failed",n=hr[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 f(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function u(e){return typeof e=="string"}function S(e){return typeof e=="number"&&Number.isFinite(e)}function H(e){return typeof e=="boolean"}function w(e){return Array.isArray(e)}function o(e,r){return c(y("UNKNOWN_ERROR",e,{...r,originalData:r?.originalData}))}function p(e,r){return e[r]}function Ve(e,r){return!f(e)||!u(e.name)||!u(e.id)?o("Invalid API response: challenge.rp must have name and id strings",{originalData:r}):d(!0)}function We(e,r){return!f(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 Be(e,r){if(!w(e))return o("Invalid API response: challenge.pubKeyCredParams must be array",{originalData:r});for(let t of e)if(!f(t)||t.type!=="public-key"||!S(t.alg))return o("Invalid API response: pubKeyCredParams items must have type and alg",{originalData:r});return d(!0)}function de(e,r){if(!f(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 me(e){if(!f(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id");if(!u(r))return o("Invalid API response: session_id must be string",{field:"session_id",originalData:e});let t=p(e,"challenge");if(!f(t))return o("Invalid API response: challenge must be object",{field:"challenge",originalData:e});let n=Ve(p(t,"rp"),e);if(!n.ok)return n;let s=We(p(t,"user"),e);if(!s.ok)return s;let i=p(t,"challenge");if(!u(i))return o("Invalid API response: challenge.challenge must be string",{originalData:e});let a=Be(p(t,"pubKeyCredParams"),e);if(!a.ok)return a;let l=t.timeout;if(l!==void 0&&!S(l))return o("Invalid API response: challenge.timeout must be number",{originalData:e});let m=t.excludeCredentials;if(m!==void 0){if(!w(m))return o("Invalid API response: excludeCredentials must be array",{originalData:e});for(let R of m)if(!f(R)||R.type!=="public-key"||!u(R.id))return o("Invalid API response: excludeCredentials items must have id and type",{originalData:e})}let v=t.authenticatorSelection;return v!==void 0&&!f(v)?o("Invalid API response: authenticatorSelection must be object",{originalData:e}):d({session_id:r,challenge:{rp:t.rp,user:t.user,challenge:i,pubKeyCredParams:t.pubKeyCredParams,...l!==void 0&&{timeout:l},...m!==void 0&&{excludeCredentials:m},...v!==void 0&&{authenticatorSelection:v}}})}function ge(e){if(!f(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id");if(!u(r))return o("Invalid API response: session_id must be string",{field:"session_id",originalData:e});let t=p(e,"challenge");if(!f(t))return o("Invalid API response: challenge must be object",{field:"challenge",originalData:e});let n=p(t,"challenge"),s=p(t,"rpId"),i=t.allowCredentials;if(!u(n))return o("Invalid API response: challenge.challenge must be string",{originalData:e});if(!u(s))return o("Invalid API response: challenge.rpId must be string",{originalData:e});if(i!==void 0&&!w(i))return o("Invalid API response: allowCredentials must be array",{originalData:e});if(i){for(let m of i)if(!f(m)||m.type!=="public-key"||!u(m.id))return o("Invalid API response: allowCredentials items must have id and type",{originalData:e})}let a=t.timeout;if(a!==void 0&&!S(a))return o("Invalid API response: challenge.timeout must be number",{originalData:e});let l=t.userVerification;return l!==void 0&&!["required","preferred","discouraged"].includes(String(l))?o("Invalid API response: userVerification must be required|preferred|discouraged",{originalData:e}):d({session_id:r,challenge:{challenge:n,rpId:s,allowCredentials:i??[],...a!==void 0&&{timeout:a},...l!==void 0&&{userVerification:l}}})}function fe(e){if(!f(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"credential_id"),t=p(e,"status"),n=p(e,"session_token"),s=p(e,"user");if(!u(r))return o("Invalid API response: credential_id must be string",{field:"credential_id",originalData:e});if(!u(t))return o("Invalid API response: status must be string",{field:"status",originalData:e});if(!u(n))return o("Invalid API response: session_token must be string",{field:"session_token",originalData:e});let i=de(s,e);if(!i.ok)return o(i.error.message,{originalData:e});let a=e.redirect_url;return a!==void 0&&!u(a)?o("Invalid API response: redirect_url must be string",{originalData:e}):d({credential_id:r,status:t,session_token:n,user:i.value,...a!==void 0&&{redirect_url:a}})}function Re(e){if(!f(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"authenticated"),t=p(e,"session_token"),n=p(e,"user"),s=p(e,"signals");if(!H(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=de(n,e);if(!i.ok)return o(i.error.message,{originalData:e});if(s!==void 0&&!f(s))return o("Invalid API response: signals must be object",{originalData:e});let a=e.redirect_url;return a!==void 0&&!u(a)?o("Invalid API response: redirect_url must be string",{originalData:e}):d({authenticated:r,session_token:t,user:i.value,signals:s,...a!==void 0&&{redirect_url:a}})}function ye(e){if(!f(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"valid"),t=p(e,"user_id"),n=p(e,"external_user_id"),s=p(e,"tenant_id"),i=p(e,"app_id");return H(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 ve(e){if(!f(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 Er=["pending_passkey","pending_data","completed"],br=["pending_data","completed"];function he(e){if(!f(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id"),t=p(e,"onboarding_url"),n=p(e,"expires_in");return u(r)?u(t)?S(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 Ee(e){if(!f(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"status"),t=p(e,"onboarding_url"),n=p(e,"expires_in");return!u(r)||!Er.includes(r)?o("Invalid API response: status must be pending_passkey|pending_data|completed",{field:"status",originalData:e}):u(t)?S(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 be(e){if(!f(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id"),t=p(e,"status"),n=p(e,"onboarding_url");if(!u(r))return o("Invalid API response: session_id must be string",{field:"session_id",originalData:e});if(t!=="pending_passkey")return o("Invalid API response: status must be pending_passkey",{field:"status",originalData:e});if(!u(n))return o("Invalid API response: onboarding_url must be string",{originalData:e});let s=e.challenge,i;if(s!==void 0){let a=_r(s);if(!a.ok)return a;i=a.value}return d({session_id:r,status:"pending_passkey",onboarding_url:n,...i!==void 0&&{challenge:i}})}function _r(e){if(!f(e))return o("Invalid API response: challenge must be object",{originalData:e});let r=p(e,"rp"),t=p(e,"user"),n=p(e,"challenge"),s=p(e,"pubKeyCredParams");if(!f(r)||!u(r.name)||!u(r.id))return o("Invalid API response: challenge.rp must have name and id",{originalData:e});if(!f(t)||!u(t.id)||!u(t.name)||!u(t.displayName))return o("Invalid API response: challenge.user must have id, name, displayName",{originalData:e});if(!u(n))return o("Invalid API response: challenge.challenge must be string",{originalData:e});if(!w(s))return o("Invalid API response: challenge.pubKeyCredParams must be array",{originalData:e});for(let i of s)if(!f(i)||i.type!=="public-key"||!S(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 _e(e){if(!f(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id"),t=p(e,"status"),n=p(e,"user_id"),s=p(e,"tenant_id");return u(r)?!u(t)||!br.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 Te(e){if(!f(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id"),t=p(e,"status"),n=p(e,"user_id"),s=p(e,"tenant_id"),i=p(e,"session_token");return u(r)?t!=="completed"?o("Invalid API response: status must be completed",{originalData:e}):!u(n)||!u(s)||!u(i)?o("Invalid API response: user_id, tenant_id, session_token must be strings",{originalData:e}):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 G(e){return e==null?d(void 0):f(e)&&Object.keys(e).length===0?d(void 0):o("Invalid API response: expected empty body (204)",{originalData:e})}function Tr(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 Ar(e){if(!e||typeof e!="object")return!1;let r=e;return typeof r.challenge=="string"&&typeof r.rpId=="string"}function X(e){if(!f(e))return o("Invalid API response: expected object",{originalData:e});let r="resultado"in e&&f(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 a={session_id:t,qr_url:n,expires_at:s,polling_token:i};return r.external_user_id!==void 0&&u(r.external_user_id)&&(a.external_user_id=r.external_user_id),d(a)}function Ae(e){if(!f(e))return o("Invalid API response: expected object",{originalData:e});let r="resultado"in e&&f(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 Ie(e){if(!f(e))return o("Invalid API response: expected object",{originalData:e});let r=e.type,t=r==="registration"?"registration":"auth",n=e.options;if(!f(n))return o("Invalid API response: options are required",{originalData:e});let s=200,i=He(e.approval_context,s),a=He(e.application_name,s);if(i===!1||a===!1)return o("Invalid API response: approval_context/application_name must be string max 200 chars",{originalData:e});let l={};return typeof i=="string"&&(l.approval_context=i),typeof a=="string"&&(l.application_name=a),t==="registration"?Tr(n)?d({type:"registration",options:n,...l}):o("Invalid API response: registration options must have challenge, rp, user, pubKeyCredParams",{originalData:e}):Ar(n)?d({type:"auth",options:n,...l}):o("Invalid API response: auth options must have challenge and rpId",{originalData:e})}function He(e,r){if(e!=null)return typeof e!="string"||e.length>r?!1:e}function Ce(e){if(!f(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"challenge"),t=p(e,"recovery_session_id");return f(r)?u(t)?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 Oe(e){if(!f(e))return o("Invalid API response: expected object",{originalData:e});let r=p(e,"status"),t=p(e,"session_token"),n=p(e,"user"),s=p(e,"credential_id");if(!u(r))return o("Invalid API response: status must be string",{field:"status",originalData:e});if(!u(t))return o("Invalid API response: session_token must be string",{field:"session_token",originalData:e});if(!u(s))return o("Invalid API response: credential_id must be string",{field:"credential_id",originalData:e});if(!f(n))return o("Invalid API response: user must be object",{field:"user",originalData:e});let i=p(n,"user_id");if(!u(i))return o("Invalid API response: user.user_id must be string",{field:"user.user_id",originalData:e});let l=e.redirect_url;if(l!==void 0&&!u(l))return o("Invalid API response: redirect_url must be string",{field:"redirect_url",originalData:e});let m=n;return d({status:r,session_token:t,credential_id:s,user:{user_id:i,external_user_id:u(m.external_user_id)?m.external_user_id:void 0,email:u(m.email)?m.email:void 0,metadata:f(m.metadata)?m.metadata:void 0},...l!==void 0&&{redirect_url:l}})}var Y=class{constructor(r,t,n={}){this.httpClient=r;this.baseUrl=t;this.defaultHeaders=n}mergeHeaders(r){return{...this.defaultHeaders,...r}}async post(r,t,n){let s=`${this.baseUrl}${r}`,i=await this.httpClient.post(s,t,this.mergeHeaders());return i.ok?n(i.value):c(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):c(i.error)}async startRegister(r){return this.post("/v1/passkeys/register/start",r,me)}async startAuth(r){return this.post("/v1/passkeys/auth/start",r,ge)}async finishRegister(r){return this.post("/v1/passkeys/register/finish",r,fe)}async finishAuthentication(r){return this.post("/v1/passkeys/auth/finish",r,Re)}async validateSession(r){return this.get("/v1/sessions/validate",ye,{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):c(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,ve)}async startOnboarding(r){return this.post("/v1/onboarding/start",r,he)}async getOnboardingStatus(r){return this.get(`/v1/onboarding/${r}/status`,Ee)}async getOnboardingRegister(r){return this.get(`/v1/onboarding/${r}/register`,be)}async registerOnboardingPasskey(r,t){return this.post(`/v1/onboarding/${r}/register-passkey`,t,_e)}async completeOnboarding(r,t){return this.post(`/v1/onboarding/${r}/complete`,t,Te)}async initCrossDeviceAuth(){return this.post("/v1/auth/cross-device/init",{},X)}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,X)}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}`,Ae,Object.keys(n).length>0?n:void 0)}async getCrossDeviceContext(r){return this.get(`/v1/auth/cross-device/context/${r}`,Ie)}async verifyCrossDeviceAuth(r){return this.post("/v1/auth/cross-device/verify",r,G)}async verifyCrossDeviceRegistration(r){return this.post("/v1/auth/cross-device/verify-registration",r,G)}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},Oe)}};function Ir(e){return typeof e=="object"&&e!==null&&e.ok===!0&&"resultado"in e}function Ye(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 Ge(e,r){if(Ye(e))return{message:e.error.message,code:q(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:q(n.code)};let s=t?.message??r,i=t?.error,a=typeof i=="string"?q(i):i===void 0?"NETWORK_FAILURE":q(String(i));return{message:s,code:a}}var Cr=3e4;function Or(){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 Xe(e,r){let t=r*Math.pow(2,e);return Math.min(t,Cr)}function kr(e,r){return e!=="GET"?!1:r>=500||r===429}var z=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=Or(),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 l=0;l<=this.maxRetries;l++)try{let m=new AbortController,v=setTimeout(()=>m.abort(),this.timeoutMs);try{let R=await fetch(r,{...t,headers:i,signal:m.signal});if(!R.ok){let I;try{I=await R.json()}catch{}let{message:O,code:L}=Ge(I,R.statusText),C=y(L,O,{requestId:s,status:R.status,statusText:R.statusText,data:I});if(kr(n,R.status)&&l<this.maxRetries){a=C,clearTimeout(v),await new Promise(T=>setTimeout(T,Xe(l,this.retryDelayMs)));continue}return c(C)}if(R.status===204)return d(void 0);if(R.headers.get("content-length")==="0")return d(void 0);let h=await R.json();if(Ir(h))return d(h.resultado);let b=h;if(typeof h=="object"&&h!==null&&b.ok===!0&&!("resultado"in b))return d(void 0);if(Ye(h)){let{message:I,code:O}=Ge(h,R.statusText);return c(y(O,I,{requestId:s,status:R.status,statusText:R.statusText,data:h}))}return d(h)}finally{clearTimeout(v)}}catch(m){if(a=m,n==="GET"&&l<this.maxRetries)await new Promise(R=>setTimeout(R,Xe(l,this.retryDelayMs)));else break}return a instanceof Error&&a.name==="AbortError"?c(y("TIMEOUT","Request timed out",{requestId:s})):c(y("NETWORK_FAILURE",a instanceof Error?a.message:"Request failed",{requestId:s,cause:a}))}};function k(e){let r=new Uint8Array(e),t=Array.from(r,s=>String.fromCharCode(s)).join("");if(typeof globalThis.btoa>"u")throw ce("encode");return globalThis.btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Sr(e){if(typeof globalThis.atob>"u")throw ce("decode");let r=e.replace(/-/g,"+").replace(/_/g,"/"),t=r.length%4,n=t===0?r:r+"=".repeat(4-t),s=globalThis.atob(n);return Uint8Array.from(s,i=>i.charCodeAt(0))}function N(e){let r=Sr(e),t=new ArrayBuffer(r.length);return new Uint8Array(t).set(r),t}function ze(e){return e!==null&&typeof e=="object"&&"clientDataJSON"in e&&e.clientDataJSON instanceof ArrayBuffer}function x(e){if(!e.response)throw y("UNKNOWN_ERROR","Credential response is missing",{credential:e});let r=e.response;if(!ze(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:k(e.rawId),response:{clientDataJSON:k(t),attestationObject:k(n)},type:"public-key"}}function $(e){if(!e.response)throw y("UNKNOWN_ERROR","Credential response is missing",{credential:e});let r=e.response;if(!ze(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:k(e.rawId),response:{authenticatorData:k(n),clientDataJSON:k(t),signature:k(s),...i&&{userHandle:k(i)}},type:"public-key"}}function U(){try{return!(typeof navigator>"u"||!navigator.credentials||typeof PublicKeyCredential>"u")}catch{return!1}}async function xr(){try{return!U()||typeof PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable!="function"?!1:await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}async function $e(){let e=U(),r=await xr();return{isPasskeySupported:e,platformAuthenticatorAvailable:r,recommendedFlow:e?"passkey":"fallback"}}function M(e,r="create"){if(!e||typeof e!="object"||!("id"in e)||!("rawId"in e)||!("response"in e))throw qe(r)}async function V(e){let{operation:r,eventEmitter:t,start:n,createOptions:s,invoke:i,finish:a}=e;try{if(t.emit("start",{type:"start",operation:r}),!U()){let g=je();return t.emit("error",{type:"error",error:g}),c(g)}let l=await n();if(!l.ok)return t.emit("error",{type:"error",error:l.error}),c(l.error);let m=s(l.value);if(!m.ok)return t.emit("error",{type:"error",error:m.error}),c(m.error);let v=await i(m.value);if(!v){let g=E("credential",`${r==="register"?"creation":"retrieval"} failed`);return t.emit("error",{type:"error",error:g}),c(g)}try{M(v)}catch(g){let h=_(g);return t.emit("error",{type:"error",error:h}),c(h)}let R=await a(l.value,v);return R.ok?d(R.value):(t.emit("error",{type:"error",error:R.error}),c(R.error))}catch(l){let m=_(l);return t.emit("error",{type:"error",error:m}),c(m)}}function D(e,r){try{B(e.challenge,"challenge"),B(e.user.id,"user.id");let t=N(e.challenge),n=N(e.user.id),s={userVerification:"preferred"};e.authenticatorSelection&&(s={...e.authenticatorSelection}),r&&(s={...s,authenticatorAttachment:r});let i={rp:{id:e.rp.id,name:e.rp.name},user:{id:n,name:e.user.name,displayName:e.user.displayName},challenge:t,pubKeyCredParams:e.pubKeyCredParams,...e.timeout!==void 0&&{timeout:e.timeout},attestation:"none",authenticatorSelection:s,...e.excludeCredentials&&{excludeCredentials:e.excludeCredentials.map(a=>({id:N(a.id),type:a.type,...a.transports&&{transports:a.transports}}))}};return d({publicKey:i})}catch(t){return c(_(t))}}function ke(e,r){try{B(e.challenge,"challenge");let t=N(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:N(n.id),type:n.type,...n.transports&&{transports:n.transports}}))}},...r!==void 0&&{mediation:r}})}catch(t){return c(_(t))}}async function Je(e,r,t){let n=e.externalUserId??e.external_user_id;if(!n||typeof n!="string"||n.trim()===""){let i=E("externalUserId","must be a non-empty string");return t.emit("error",{type:"error",error:i}),c(i)}let s=await V({operation:"register",eventEmitter:t,start:()=>r.startRegister({external_user_id:n}),createOptions:i=>D(i.challenge,e.authenticatorType),invoke:async i=>{let a={...i,...e.signal&&{signal:e.signal}};return navigator.credentials.create(a)},finish:async(i,a)=>{let l=await r.finishRegister({session_id:i.session_id,credential:x(a),...e.successUrl&&{success_url:e.successUrl}});return l.ok?d({success:!0,credentialId:l.value.credential_id,credential_id:l.value.credential_id,status:l.value.status,sessionToken:l.value.session_token,user:{userId:l.value.user.user_id,externalUserId:l.value.user.external_user_id,email:l.value.user.email,metadata:l.value.user.metadata},...l.value.redirect_url&&{redirectUrl:l.value.redirect_url}}):c(l.error)}});return s.ok&&t.emit("success",{type:"success",operation:"register",token:s.value.sessionToken,user:s.value.user}),s}async function Ze(e,r,t){let n=e.externalUserId??e.external_user_id,s=n!==void 0&&typeof n=="string"&&n.trim()!=="",i=await V({operation:"authenticate",eventEmitter:t,start:()=>r.startAuth(s?{external_user_id:n.trim()}:{}),createOptions:a=>ke(a.challenge,e.mediation),invoke:async a=>{let l={...a,...e.signal&&{signal:e.signal}};return navigator.credentials.get(l)},finish:async(a,l)=>{let m=await r.finishAuthentication({session_id:a.session_id,credential:$(l),...e.successUrl&&{success_url:e.successUrl}});return m.ok?d({authenticated:m.value.authenticated,sessionToken:m.value.session_token,user:{userId:m.value.user.user_id,externalUserId:m.value.user.external_user_id,email:m.value.user.email,metadata:m.value.user.metadata},signals:m.value.signals,...m.value.redirect_url&&{redirectUrl:m.value.redirect_url}}):c(m.error)}});return i.ok&&t.emit("success",{type:"success",operation:"authenticate",token:i.value.sessionToken,user:i.value.user}),i}async function J(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 Pr=2e3,Mr=60,Z=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 c(n.error);let{session_id:s}=n.value;for(let i=0;i<Mr;i++){if(t?.aborted)return c(y("ABORT_ERROR","Operation aborted by user or timeout"));if(await J(Pr,t)==="aborted")return c(y("ABORT_ERROR","Operation aborted by user or timeout"));let l=await this.apiClient.getOnboardingStatus(s);if(!l.ok)return c(l.error);let m=l.value.status,v=l.value.onboarding_url;if(m==="pending_passkey"){let R=await this.apiClient.getOnboardingRegister(s);if(!R.ok)return c(R.error);let g=R.value;if(!g.challenge)return c(y("NOT_SUPPORTED","Onboarding requires user action - complete passkey registration at the provided onboarding_url",{onboarding_url:v}));let h=D(g.challenge);if(!h.ok)return c(h.error);let b;try{b=await navigator.credentials.create(h.value)}catch(C){return c(_(C))}try{M(b,"create")}catch(C){return c(_(C))}let I;try{I=x(b)}catch(C){return c(_(C))}let O=await this.apiClient.registerOnboardingPasskey(s,{credential:I,challenge:g.challenge.challenge});return O.ok?await this.apiClient.completeOnboarding(s,{company_name:r.company_name}):c(O.error)}if(m==="completed")return await this.apiClient.completeOnboarding(s,{company_name:r.company_name})}return c(y("TIMEOUT","Onboarding timed out"))}};var Dr=2e3,wr=60,Q=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 c(y("ABORT_ERROR","Operation aborted by user or timeout"));for(let s=0;s<wr;s++){let i=await this.apiClient.getCrossDeviceStatus(r,n);if(!i.ok)return c(i.error);if(i.value.status==="completed"){if(!i.value.session_token||!i.value.user_id)return c(y("UNKNOWN_ERROR","Missing data in completed session"));let l=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,...l!==void 0&&{redirectUrl:l}})}if(await J(Dr,t)==="aborted")return c(y("ABORT_ERROR","Operation aborted by user or timeout"))}return c(y("TIMEOUT","Cross-device authentication timed out"))}async approve(r){let t=await this.apiClient.getCrossDeviceContext(r);if(!t.ok)return c(t.error);let n=t.value;return n.type==="registration"?this.executeRegistrationApproval(r,n):this.executeAuthApproval(r,n)}async executeRegistrationApproval(r,t){let n=D(t.options);if(!n.ok)return c(n.error);let s;try{s=await navigator.credentials.create(n.value)}catch(a){return c(_(a))}try{M(s,"create")}catch(a){return c(_(a))}let i;try{i=x(s)}catch(a){return c(_(a))}return this.apiClient.verifyCrossDeviceRegistration({session_id:r,credential:i})}async executeAuthApproval(r,t){let n=ke(t.options);if(!n.ok)return c(n.error);let s;try{s=await navigator.credentials.get(n.value)}catch(a){return c(_(a))}try{M(s,"get")}catch(a){return c(_(a))}let i;try{i=$(s)}catch(a){return c(_(a))}return this.apiClient.verifyCrossDeviceAuth({session_id:r,credential:i})}};var ee=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()}};var Se="https://api.trymellonauth.com",Qe="https://api.trymellonauth.com/v1/telemetry";var er="trymellon_sandbox_session_token_v1";function rr(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 xe(e,r){return{event:e,latencyMs:r,ok:!0}}var re=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 Je(r,this.apiClient,this.eventEmitter);return n.ok&&this.telemetrySender&&this.telemetrySender.send(xe("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 Ze(r,this.apiClient,this.eventEmitter);return n.ok&&this.telemetrySender&&this.telemetrySender.send(xe("authenticate",Date.now()-t)).catch(()=>{}),n}};async function tr(e,r,t){let n=e.externalUserId??e.external_user_id;if(!n||typeof n!="string"||n.trim()===""){let i=E("externalUserId","must be a non-empty string");return t.emit("error",{type:"error",error:i}),c(i)}if(!e.otp||typeof e.otp!="string"||e.otp.trim().length!==6){let i=E("otp","must be a 6-digit string");return t.emit("error",{type:"error",error:i}),c(i)}let s=await V({operation:"register",eventEmitter:t,start:()=>r.verifyAccountRecoveryOtp(n,e.otp),createOptions:i=>D(i.challenge),invoke:async i=>navigator.credentials.create(i),finish:async(i,a)=>{let l=await r.completeAccountRecovery(i.recovery_session_id,x(a));if(!l.ok)return c(l.error);let{credential_id:m,status:v,session_token:R,user:g,redirect_url:h}=l.value;return d({success:!0,credentialId:m,status:v,sessionToken:R,user:{userId:g.user_id,externalUserId:g.external_user_id,email:g.email,metadata:g.metadata},...h!==void 0&&{redirectUrl:h}})}});return s.ok&&t.emit("success",{type:"success",operation:"register",token:s.value.sessionToken,user:s.value.user}),s}var te=class{constructor(r,t){this.apiClient=r;this.eventEmitter=t}recover(r){return tr(r,this.apiClient,this.eventEmitter)}};var ne=class e{sandbox;sandboxToken;apiClient;eventEmitter;telemetrySender;crossDeviceManager;authService;recoveryService;onboarding;static create(r){try{let t=r.appId,n=r.publishableKey;if(!t||typeof t!="string"||t.trim()==="")return c(E("appId","must be a non-empty string"));if(!n||typeof n!="string"||n.trim()==="")return c(E("publishableKey","must be a non-empty string"));let s=r.apiBaseUrl??Se;pe(s,"apiBaseUrl");let i=r.timeoutMs??3e4;return P(i,"timeoutMs",1e3,3e5),r.maxRetries!==void 0&&P(r.maxRetries,"maxRetries",0,10),r.retryDelayMs!==void 0&&P(r.retryDelayMs,"retryDelayMs",100,1e4),d(new e(r))}catch(t){return ue(t)?c(t):c(E("config",t.message))}}constructor(r){this.sandbox=r.sandbox===!0,this.sandboxToken=this.sandbox&&r.sandboxToken!=null&&r.sandboxToken!==""?r.sandboxToken:er;let t=r.appId,n=r.publishableKey;if(!t||typeof t!="string"||t.trim()==="")throw E("appId","must be a non-empty string");if(!n||typeof n!="string"||n.trim()==="")throw E("publishableKey","must be a non-empty string");let s=r.apiBaseUrl??Se;pe(s,"apiBaseUrl");let i=r.timeoutMs??3e4;P(i,"timeoutMs",1e3,3e5),r.maxRetries!==void 0&&P(r.maxRetries,"maxRetries",0,10),r.retryDelayMs!==void 0&&P(r.retryDelayMs,"retryDelayMs",100,1e4);let a=r.maxRetries??3,l=r.retryDelayMs??1e3,m=new z(i,a,l,r.logger),v=r.origin??(typeof window<"u"&&window?.location?.origin?window.location.origin:void 0),R={"X-App-Id":t.trim(),Authorization:`Bearer ${n.trim()}`,...v&&{Origin:v}};this.apiClient=new Y(m,s,R),this.eventEmitter=new ee,r.enableTelemetry&&(this.telemetrySender=r.telemetrySender??rr(r.telemetryEndpoint??Qe)),this.authService=new re(this.apiClient,this.eventEmitter,this.sandbox,this.sandboxToken,this.telemetrySender),this.recoveryService=new te(this.apiClient,this.eventEmitter),this.onboarding=new Z(this.apiClient),this.crossDeviceManager=new Q(this.apiClient)}static isSupported(){return U()}async register(r){return this.authService.register(r)}async authenticate(r){return this.authService.authenticate(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 $e()}on(r,t){return this.eventEmitter.on(r,t)}version(){return"2.0.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 se=new Lr("TRYMELLON_CONFIG"),cr,Pe;cr=[Fr({providedIn:"root"})];var F=class{config=Kr(se,{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 ne(this.config)}return this._client}};Pe=Ue(null),F=Ke(Pe,0,"TryMellonService",cr,F),Le(Pe,1,F);function Kn(e){return{provide:se,useValue:e}}export{se as TRYMELLON_CONFIG,F as TryMellonService,Kn as provideTryMellonConfig};
|
|
3
3
|
//# sourceMappingURL=angular.js.map
|