@stitch-money/client 3.13.0 → 3.14.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/build/index.d.ts CHANGED
@@ -37,9 +37,9 @@ interface ApplePaySession {
37
37
  domainName: string;
38
38
  displayName: string;
39
39
  signature: string;
40
- operationalAnalyticsIdentifier: string;
41
- retries: number;
42
- pspId: string;
40
+ operationalAnalyticsIdentifier?: string;
41
+ retries?: number;
42
+ pspId?: string;
43
43
  }
44
44
  interface SamsungPayPaymentResult {
45
45
  status: 'CHARGED' | 'REJECTED' | 'CANCELED' | 'ERRED';
package/build/index.js CHANGED
@@ -23,5 +23,5 @@ ${n}`:t}function Gi(e){return Re(e,[]).join(`
23
23
  ${n}`);return r.name="Decoding error",r}else return n}function I(e){function t(c){return e(c,kn,u=>Tn(xn(u)?u:W(c,u)))}function n(c,u=Vi){let m=t(c);if(m.ok)return m.value;throw $i(m.error,u)}function r(c){return t(c).value}function o(c){return i(Wi(c))}function a(c,u){return l(m=>c(m)?null:u)}function i(c){return I((u,m,g)=>{let d=t(u);if(!d.ok)return d;let p=vn(c)?c:c(d.value,m,g);return vn(p)?p.decode(d.value):p})}function s(c){return i(c)}function l(c){return i((u,m,g)=>{let d=c(u);return d===null?m(u):g(typeof d=="string"?W(u,d):d)})}function f(c){return I((u,m,g)=>{let d=t(u);return d.ok?d:g(W(d.error,c))})}return Ui({verify:n,value:r,decode:t,transform:o,refine:a,reject:l,describe:f,then:i,pipe:s})}var Nn=new WeakSet;function Ui(e){return Nn.add(e),e}function vn(e){return Nn.has(e)}var Zi=I((e,t,n)=>Array.isArray(e)?t(e):n("Must be an array"));function Hi(e,t,n,r){let o=[];for(let a=0;a<e.length;++a){let i=e[a];if(i.ok)o.push(i.value);else{let s=i.error,l=t.slice();return l.splice(a,1,W(s,s.text?`${s.text} (at index ${a})`:`index ${a}`)),r(W(l))}}return n(o)}function st(e){let t=e.decode;return Zi.then((n,r,o)=>{let a=n.map(t);return Hi(a,n,r,o)})}function Yi(e){return I((t,n,r)=>t instanceof e?n(t):r(`Must be ${e.name} instance`))}function Mn(e){return I(t=>e().decode(t))}function zi(e,t){let n=new Set;for(let r of e)t.has(r)||n.add(r);return n}var Ln=I((e,t,n)=>Rn(e)?t(e):n("Must be an object"));function J(e){let t=new Set(Object.keys(e));return Ln.then((n,r,o)=>{let a=new Set(Object.keys(n)),i=zi(t,a),s={},l=null;for(let f of Object.keys(e)){let c=e[f],u=n[f],m=c.decode(u);if(m.ok){let g=m.value;g!==void 0&&(s[f]=g),i.delete(f)}else{let g=m.error;u===void 0?i.add(f):(l===null&&(l=new Map),l.set(f,g))}}if(l||i.size>0){let f=An(n);if(l&&(f=In(f,l)),i.size>0){let c=Array.from(i).map(U).join(", "),u=i.size>1?"keys":"key";f=_n(f,`Missing ${u}: ${c}`)}return o(f)}return r(s)})}var rt=`Either:
24
24
  `;function Bi(e){return`-${it(e).substring(1)}`}function Ji(e){return e.startsWith(rt)?e.substring(rt.length):Bi(e)}function ie(...e){if(e.length===0)throw new Error("Pass at least one decoder to either()");return I((t,n,r)=>{let o=[];for(let i=0;i<e.length;i++){let s=e[i].decode(t);if(s.ok)return s;o.push(s.error)}let a=rt+o.map(i=>Ji(Re(i).join(`
25
25
  `))).join(`
26
- `);return r(a)})}function Fn(e){return I((t,n,r)=>{let o=e.find(a=>a===t);return o!==void 0?n(o):r(`Must be one of ${e.map(a=>U(a)).join(", ")}`)})}function Dn(e){return typeof e=="function"?e():e}var Xi=jn(null),Ki=jn(void 0),qi=I((e,t,n)=>e==null?t(e):n("Must be undefined or null"));function Pe(e,t){let n=ie(Ki,e);return arguments.length>=2?n.transform(r=>r!=null?r:Dn(t)):n}function ct(e,t){let n=ie(qi,e);return arguments.length>=2?n.transform(r=>r!=null?r:Dn(t)):n}function jn(e){return I((t,n,r)=>t===e?n(e):r(`Must be ${typeof e=="symbol"?String(e):U(e)}`))}var Ba=I((e,t,n)=>t(e));var ae=I((e,t,n)=>typeof e=="boolean"?t(e):n("Must be boolean")),Ja=I((e,t,n)=>t(!!e));function Qi(e,t){let n=t!==void 0?e:void 0,r=t!==void 0?t:e;return Ln.then((o,a,i)=>{var f;let s={},l=new Map;for(let c of Object.keys(o)){let u=o[c],m=n==null?void 0:n.decode(c);if((m==null?void 0:m.ok)===!1)return i(W(o,`Invalid key ${U(c)}: ${Gi(m.error)}`));let g=(f=m==null?void 0:m.value)!=null?f:c,d=r.decode(u);d.ok?l.size===0&&(s[g]=d.value):(l.set(c,d.error),s={})}return l.size>0?i(In(An(o),l)):a(s)})}var ea=/^([A-Za-z]{3,9}(?:[+][A-Za-z]{3,9})?):\/\/(?:([-;:&=+$,\w]+)@)?(?:([A-Za-z0-9.-]+)(?::([0-9]{2,5}))?)(\/(?:[-+~%/.,\w]*)?(?:\?[-+=&;%@.,/\w]*)?(?:#[.,!/\w]*)?)?$/,Vn=I((e,t,n)=>Oi(e)?t(e):n("Must be string")),j=V(/\S/,"Must be non-empty string");function V(e,t){return Vn.refine(n=>e.test(n),t)}var Xa=V(/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,"Must be email"),ta=ie(V(ea,"Must be URL").transform(e=>new URL(e)),Yi(URL)),Ka=ta.refine(e=>e.protocol==="https:","Must be an HTTPS URL"),qa=V(/^[a-z_][a-z0-9_]*$/i,"Must be valid identifier");var Gn=V(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,"Must be uuid"),Qa=Gn.refine(e=>e[14]==="1","Must be uuidv1"),es=Gn.refine(e=>e[14]==="4","Must be uuidv4"),na=V(/^[0-9]+$/,"Must only contain digits"),ts=V(/^[0-9a-f]+$/i,"Must only contain hexadecimal digits"),ns=na.transform(Number),ra=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:[.]\d+)?(?:Z|[+-]\d{2}:?\d{2})$/,oa=I((e,t,n)=>Sn(e)?t(e):n("Must be a Date")),ia=V(ra,"Must be ISO8601 format").transform(e=>{let t=new Date(e);if(isNaN(t.getTime()))throw new Error("Must be valid date/time value");return t}),rs=ie(oa,ia).describe("Must be a Date or date string"),aa=I((e,t,n)=>Ai(e)?t(e):n("Must be number")),se=aa.refine(e=>Number.isFinite(e),"Number must be finite"),sa=se.refine(e=>Number.isInteger(e),"Number must be an integer"),Wn=se.refine(e=>e>=0&&!Object.is(e,-0),"Number must be positive"),os=sa.refine(e=>e>=0&&!Object.is(e,-0),"Number must be positive"),is=I((e,t,n)=>ki(e)?t(e):n("Must be bigint")),ca=Mn(()=>Qi($n)),ua=Mn(()=>st($n)),$n=ie(Xi,Vn,se,ae,ca,ua).describe("Must be valid JSON value");var Ee=3,Un=500,Hn={prod:"https://public-config.stitch.money",staging:"https://public-config-staging.stitch.money",preprod:"https://public-config-pre-prod.stitch.money"},la=Fn(["visa","mastercard","amex"]),_e=ct(J({allowedNetworks:ct(st(la))})),fa=J({analytics:J({changeEventDebounceDelayMs:Wn}),evervault:J({teamId:j,appId:j}),ipAddress:Pe(j),ipAddressProof:Pe(j),fingerprint:J({disabled:ae,useEmulation:ae,ossEnabled:Pe(ae),publicKey:j,endpoint:j,scriptUrlPattern:j,cacheDurationInSeconds:se}),card:_e,applePay:_e,googlePay:_e,samsungPay:_e});function Zn(e){return e!=null&&typeof e=="object"&&"aborted"in e&&"addEventListener"in e}function da(e){return typeof e=="string"&&Object.prototype.hasOwnProperty.call(Hn,e)}function pa(e){let t=da(e==null?void 0:e.environment)?e.environment:"prod";return Hn[t]}function ma(e,t){return`${pa(t)}/config/${e}`}function ce(e,t,n){return h(this,null,function*(){let r=Zn(t)?t:void 0,o=Zn(t)?n:t,a=ma(e,o);try{let i=0;for(;i<Ee;)try{let s=yield fetch(a,{signal:r});if(s.ok)return{type:"success",runtimeConfig:fa.verify(yield s.json())};if(i++,i===Ee)return{type:"error",error:new Error(`[${ce.name}] Failed to retrieve runtime config after ${Ee} attempts. Runtime config endpoint returned ${s.status} response`)};yield new Promise(l=>setTimeout(l,Un))}catch(s){if(i++,i===Ee)throw s;yield new Promise(l=>setTimeout(l,Un))}return{type:"error",error:new Error(`[${ce.name}] Failed to retrieve runtime config`)}}catch(i){return i instanceof Error?{type:"error",error:i}:typeof i=="string"?{type:"error",error:new Error(i)}:{type:"error",error:new Error(`[${ce.name}] Failed to retrieve runtime config. Unknown error thrown`)}}})}import{v4 as ha}from"uuid";var ga="9ba67dd8d5b247cfb3f76e";function Ie(e){return{version:"2",serviceId:ga,protocol:"PROTOCOL_3DS",allowedBrands:q(e==null?void 0:e.samsungPay).map(t=>ht(t))}}function Yn(e){return{apiVersion:2,apiVersionMinor:0,allowedPaymentMethods:[{type:"CARD",parameters:{allowedAuthMethods:["CRYPTOGRAM_3DS"],allowedCardNetworks:q(e==null?void 0:e.googlePay).map(t=>yt(t))}}]}}function zn(e){return h(this,null,function*(){if(!window.ApplePaySession)return!1;let t=ApplePaySession;if(t.applePayCapabilities&&e)try{return(yield t.applePayCapabilities(e)).paymentCredentialStatus!=="applePayUnsupported"}catch(n){E("[determineApplePaySupport] failed to get applePayCapabilities, falling back to canMakePayments",n,{merchantIdentifier:e})}return t.canMakePayments()})}function Bn(){if(!window.ApplePaySession)return-1;let t=n=>n===0?-1:ApplePaySession.supportsVersion(n)?n:t(n-1);return t(14)}function Jn(e,t){return h(this,null,function*(){if(!e)return!1;try{return(yield e.isReadyToPay(Yn(t))).result}catch(n){return!1}})}function Xn(e,t){return h(this,null,function*(){if(!e)return!1;try{return(yield e.isReadyToPay(Ie(t))).result}catch(n){return!1}})}var M=class extends Error{constructor(t){super(t),this.name="SessionError"}};var ue=e=>e instanceof Error?e.toString():JSON.stringify(e);var ut="3.12.1";var ba="[onvalidatemerchant]",Kn="[onpaymentauthorized]",X="[onClickSamsungPaySessionHandler]",lt="[onClickGooglePaySessionHandler]",qn=class{constructor(t){O(this,"onCancelPayment");O(this,"clientId");O(this,"gatewayMerchantId");O(this,"runtimeConfigEnvironment");O(this,"applePayIsSupported",!1);O(this,"samsungPayIsSupported",!1);O(this,"googlePayIsSupported",!1);O(this,"runtimeConfig");O(this,"fingerprintAgent");O(this,"googlePayClient");O(this,"samsungPayClient");var s,l,f;Ve({source:"wallets-client",version:ut});let{onCancelPayment:n,clientId:r,gatewayMerchantId:o,runtimeConfigEnvironment:a}=t,i=(f=(l=(s=globalThis.google)==null?void 0:s.payments)==null?void 0:l.api)==null?void 0:f.PaymentsClient;this.googlePayClient=i?new i({environment:r!=null&&r.startsWith("test-")?"TEST":"PRODUCTION"}):void 0,this.samsungPayClient=window.SamsungPay?new window.SamsungPay.PaymentClient({environment:r!=null&&r.startsWith("test-")?"STAGE":"PRODUCTION",nonce:ha()}):void 0,this.onCancelPayment=n!=null?n:()=>{},this.clientId=r,this.gatewayMerchantId=o,this.runtimeConfigEnvironment=a,this.loadFingerprintAgent()}loadRuntimeConfig(){return h(this,null,function*(){var t,n;if(this.runtimeConfig===void 0&&this.clientId){let r=yield ce(this.clientId,{environment:this.runtimeConfigEnvironment});if(r.type==="error"){let o=(n=(t=r.error)==null?void 0:t.message)!=null?n:"Failed to load runtime configuration";throw E(o,r.error,{clientId:this.clientId}),r.error?r.error:new Error(o)}this.runtimeConfig=r.runtimeConfig}})}loadFingerprintAgent(){return h(this,null,function*(){this.fingerprintAgent===void 0&&(this.runtimeConfig===void 0&&(yield this.loadRuntimeConfig()),this.runtimeConfig!==void 0&&!this.runtimeConfig.fingerprint.disabled&&(this.fingerprintAgent=yield bn({config:this.runtimeConfig.fingerprint})))})}fingerprint(){return h(this,null,function*(){var n,r,o;let t=yield wn({config:(n=this.runtimeConfig)==null?void 0:n.fingerprint,agent:this.fingerprintAgent,clientId:this.clientId,sdkVersion:ut,ipAddress:(r=this.runtimeConfig)==null?void 0:r.ipAddress,ipAddressProof:(o=this.runtimeConfig)==null?void 0:o.ipAddressProof});return Ve({fingerprint:t}),t})}supportedPaymentMethods(){return h(this,null,function*(){let t=[];try{yield this.loadRuntimeConfig()}catch(n){}return this.applePayIsSupported=yield zn(this.gatewayMerchantId),this.applePayIsSupported&&t.push("APPLE_PAY"),this.samsungPayIsSupported=yield Xn(this.samsungPayClient,this.runtimeConfig),this.samsungPayIsSupported&&t.push("SAMSUNG_PAY"),this.googlePayIsSupported=yield Jn(this.googlePayClient,this.runtimeConfig),this.googlePayIsSupported&&t.push("GOOGLE_PAY"),t})}onClickApplePaySessionHandler(t,n,r,o,a,i){let s=Bn();return()=>{var u,m,g;let l=q((u=this.runtimeConfig)==null?void 0:u.applePay).map(d=>gt(d)),f={countryCode:"ZA",currencyCode:t,supportedNetworks:l,merchantCapabilities:["supports3DS"],total:{label:r,amount:n.toString()}};i&&(f.recurringPaymentRequest={paymentDescription:r,billingAgreement:i.billingAgreement,regularBilling:{label:r,amount:((m=i.recurringAmount)!=null?m:n).toString(),paymentTiming:"recurring",recurringPaymentIntervalUnit:i.recurringIntervalUnit,recurringPaymentIntervalCount:(g=i.recurringIntervalCount)!=null?g:1},managementURL:i.managementUrl});let c;try{c=new ApplePaySession(s,f)}catch(d){E("Failed to create Apple Pay session",d,{clientId:this.clientId});return}c.onvalidatemerchant=d=>h(this,null,function*(){try{let p=yield o(d.validationURL);if(!c)throw new Error("ApplePaySession is missing");if(p==null||typeof p!="object")throw new Error(`verifyCallbackResponse is not an object: ${JSON.stringify(p)}`);if(Object.keys(p).length===0)throw new Error(`verifyCallbackResponse is an empty object: ${JSON.stringify(p)}`);c.completeMerchantValidation(p)}catch(p){throw E(`${ba} Failed to complete merchant validation`,p,{clientId:this.clientId}),new M(`Failed to complete merchant validation: ${ue(p)}`)}}),c.onpaymentauthorized=d=>h(this,null,function*(){try{let p=d.payment.token,y=yield this.fingerprint(),b=yield a(p,y);switch(b.status){case"TransactionPending":case"TransactionSuccess":{c==null||c.completePayment(ApplePaySession.STATUS_SUCCESS);break}case"TransactionFailure":{c==null||c.completePayment(ApplePaySession.STATUS_FAILURE);break}default:{let P="Invalid transaction status",x=new M(`${P} ${b.status}`);throw E(`${Kn} Invalid transaction status`,x,{clientId:this.clientId}),x}}}catch(p){throw c==null||c.completePayment(ApplePaySession.STATUS_FAILURE),E(`${Kn} Failed to create payment`,p,{clientId:this.clientId}),new M(`Failed to create payment: ${ue(p)}`)}}),c.oncancel=()=>{this.onCancelPayment()},c.begin()}}onClickSamsungPaySessionHandler(t,n,r,o,a,i,s){return()=>h(this,null,function*(){if(!this.samsungPayClient){let l="Samsung Pay client not initialized",f=new Error(l);throw E(`${X} ${l}`,f,{clientId:this.clientId}),f}try{let l={orderNumber:o,merchant:{name:r,url:a,id:i,countryCode:"ZA"},amount:{option:"FORMAT_TOTAL_PRICE_ONLY",currency:t,total:n}},f=yield this.fingerprint(),c=Ie(this.runtimeConfig);Ge(`${X} Loading payment sheet`,{clientId:this.clientId,type:"SAMSUNG_PAY",samsungPay:{paymentMethods:c,transactionDetail:l}});let u=yield this.samsungPayClient.loadPaymentSheet(c,l);Ge(`${X} Received payment credential`,{clientId:this.clientId,type:"SAMSUNG_PAY",samsungPay:{paymentCredential:u}});let m=yield s(u,f);switch(m.status){case"TransactionPending":break;case"TransactionFailure":{this.samsungPayClient.notify({status:"REJECTED"});break}case"TransactionSuccess":{this.samsungPayClient.notify({status:"CHARGED"});break}default:{this.samsungPayClient.notify({status:"ERRED"});let g=`${X} Invalid transaction status: ${m.status}`,d=new M(g);throw E(g,d,{clientId:this.clientId,type:"SAMSUNG_PAY"}),d}}}catch(l){throw E(`${X} Failed to create payment`,l,{clientId:this.clientId,type:"SAMSUNG_PAY"}),new M(`${X} Failed to create payment: ${ue(l)}`)}})}onClickGooglePaySessionHandler(t){return n=>h(this,null,function*(){try{let r=yield this.fingerprint(),o=yield t(n.paymentMethodData.tokenizationData.token,r);switch(o.status){case"TransactionPending":case"TransactionFailure":case"TransactionSuccess":break;default:{let a=`${lt} Invalid transaction status: ${o.status}`,i=new M(a);throw E(a,i,{clientId:this.clientId}),i}}}catch(r){throw E(`${lt} Failed to create payment`,r,{clientId:this.clientId}),new M(`${lt} Failed to create payment: ${ue(r)}`)}})}};export{qn as StitchWalletClientSdk,mt as WalletType};
26
+ `);return r(a)})}function Fn(e){return I((t,n,r)=>{let o=e.find(a=>a===t);return o!==void 0?n(o):r(`Must be one of ${e.map(a=>U(a)).join(", ")}`)})}function Dn(e){return typeof e=="function"?e():e}var Xi=jn(null),Ki=jn(void 0),qi=I((e,t,n)=>e==null?t(e):n("Must be undefined or null"));function Pe(e,t){let n=ie(Ki,e);return arguments.length>=2?n.transform(r=>r!=null?r:Dn(t)):n}function ct(e,t){let n=ie(qi,e);return arguments.length>=2?n.transform(r=>r!=null?r:Dn(t)):n}function jn(e){return I((t,n,r)=>t===e?n(e):r(`Must be ${typeof e=="symbol"?String(e):U(e)}`))}var Ba=I((e,t,n)=>t(e));var ae=I((e,t,n)=>typeof e=="boolean"?t(e):n("Must be boolean")),Ja=I((e,t,n)=>t(!!e));function Qi(e,t){let n=t!==void 0?e:void 0,r=t!==void 0?t:e;return Ln.then((o,a,i)=>{var f;let s={},l=new Map;for(let c of Object.keys(o)){let u=o[c],m=n==null?void 0:n.decode(c);if((m==null?void 0:m.ok)===!1)return i(W(o,`Invalid key ${U(c)}: ${Gi(m.error)}`));let g=(f=m==null?void 0:m.value)!=null?f:c,d=r.decode(u);d.ok?l.size===0&&(s[g]=d.value):(l.set(c,d.error),s={})}return l.size>0?i(In(An(o),l)):a(s)})}var ea=/^([A-Za-z]{3,9}(?:[+][A-Za-z]{3,9})?):\/\/(?:([-;:&=+$,\w]+)@)?(?:([A-Za-z0-9.-]+)(?::([0-9]{2,5}))?)(\/(?:[-+~%/.,\w]*)?(?:\?[-+=&;%@.,/\w]*)?(?:#[.,!/\w]*)?)?$/,Vn=I((e,t,n)=>Oi(e)?t(e):n("Must be string")),j=V(/\S/,"Must be non-empty string");function V(e,t){return Vn.refine(n=>e.test(n),t)}var Xa=V(/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,"Must be email"),ta=ie(V(ea,"Must be URL").transform(e=>new URL(e)),Yi(URL)),Ka=ta.refine(e=>e.protocol==="https:","Must be an HTTPS URL"),qa=V(/^[a-z_][a-z0-9_]*$/i,"Must be valid identifier");var Gn=V(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,"Must be uuid"),Qa=Gn.refine(e=>e[14]==="1","Must be uuidv1"),es=Gn.refine(e=>e[14]==="4","Must be uuidv4"),na=V(/^[0-9]+$/,"Must only contain digits"),ts=V(/^[0-9a-f]+$/i,"Must only contain hexadecimal digits"),ns=na.transform(Number),ra=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:[.]\d+)?(?:Z|[+-]\d{2}:?\d{2})$/,oa=I((e,t,n)=>Sn(e)?t(e):n("Must be a Date")),ia=V(ra,"Must be ISO8601 format").transform(e=>{let t=new Date(e);if(isNaN(t.getTime()))throw new Error("Must be valid date/time value");return t}),rs=ie(oa,ia).describe("Must be a Date or date string"),aa=I((e,t,n)=>Ai(e)?t(e):n("Must be number")),se=aa.refine(e=>Number.isFinite(e),"Number must be finite"),sa=se.refine(e=>Number.isInteger(e),"Number must be an integer"),Wn=se.refine(e=>e>=0&&!Object.is(e,-0),"Number must be positive"),os=sa.refine(e=>e>=0&&!Object.is(e,-0),"Number must be positive"),is=I((e,t,n)=>ki(e)?t(e):n("Must be bigint")),ca=Mn(()=>Qi($n)),ua=Mn(()=>st($n)),$n=ie(Xi,Vn,se,ae,ca,ua).describe("Must be valid JSON value");var Ee=3,Un=500,Hn={prod:"https://public-config.stitch.money",staging:"https://public-config-staging.stitch.money",preprod:"https://public-config-pre-prod.stitch.money"},la=Fn(["visa","mastercard","amex"]),_e=ct(J({allowedNetworks:ct(st(la))})),fa=J({analytics:J({changeEventDebounceDelayMs:Wn}),evervault:J({teamId:j,appId:j}),ipAddress:Pe(j),ipAddressProof:Pe(j),fingerprint:J({disabled:ae,useEmulation:ae,ossEnabled:Pe(ae),publicKey:j,endpoint:j,scriptUrlPattern:j,cacheDurationInSeconds:se}),card:_e,applePay:_e,googlePay:_e,samsungPay:_e});function Zn(e){return e!=null&&typeof e=="object"&&"aborted"in e&&"addEventListener"in e}function da(e){return typeof e=="string"&&Object.prototype.hasOwnProperty.call(Hn,e)}function pa(e){let t=da(e==null?void 0:e.environment)?e.environment:"prod";return Hn[t]}function ma(e,t){return`${pa(t)}/config/${e}`}function ce(e,t,n){return h(this,null,function*(){let r=Zn(t)?t:void 0,o=Zn(t)?n:t,a=ma(e,o);try{let i=0;for(;i<Ee;)try{let s=yield fetch(a,{signal:r});if(s.ok)return{type:"success",runtimeConfig:fa.verify(yield s.json())};if(i++,i===Ee)return{type:"error",error:new Error(`[${ce.name}] Failed to retrieve runtime config after ${Ee} attempts. Runtime config endpoint returned ${s.status} response`)};yield new Promise(l=>setTimeout(l,Un))}catch(s){if(i++,i===Ee)throw s;yield new Promise(l=>setTimeout(l,Un))}return{type:"error",error:new Error(`[${ce.name}] Failed to retrieve runtime config`)}}catch(i){return i instanceof Error?{type:"error",error:i}:typeof i=="string"?{type:"error",error:new Error(i)}:{type:"error",error:new Error(`[${ce.name}] Failed to retrieve runtime config. Unknown error thrown`)}}})}import{v4 as ha}from"uuid";var ga="9ba67dd8d5b247cfb3f76e";function Ie(e){return{version:"2",serviceId:ga,protocol:"PROTOCOL_3DS",allowedBrands:q(e==null?void 0:e.samsungPay).map(t=>ht(t))}}function Yn(e){return{apiVersion:2,apiVersionMinor:0,allowedPaymentMethods:[{type:"CARD",parameters:{allowedAuthMethods:["CRYPTOGRAM_3DS"],allowedCardNetworks:q(e==null?void 0:e.googlePay).map(t=>yt(t))}}]}}function zn(e){return h(this,null,function*(){if(!window.ApplePaySession)return!1;let t=ApplePaySession;if(t.applePayCapabilities&&e)try{return(yield t.applePayCapabilities(e)).paymentCredentialStatus!=="applePayUnsupported"}catch(n){E("[determineApplePaySupport] failed to get applePayCapabilities, falling back to canMakePayments",n,{merchantIdentifier:e})}return t.canMakePayments()})}function Bn(){if(!window.ApplePaySession)return-1;let t=n=>n===0?-1:ApplePaySession.supportsVersion(n)?n:t(n-1);return t(14)}function Jn(e,t){return h(this,null,function*(){if(!e)return!1;try{return(yield e.isReadyToPay(Yn(t))).result}catch(n){return!1}})}function Xn(e,t){return h(this,null,function*(){if(!e)return!1;try{return(yield e.isReadyToPay(Ie(t))).result}catch(n){return!1}})}var M=class extends Error{constructor(t){super(t),this.name="SessionError"}};var ue=e=>e instanceof Error?e.toString():JSON.stringify(e);var ut="3.13.0";var ba="[onvalidatemerchant]",Kn="[onpaymentauthorized]",X="[onClickSamsungPaySessionHandler]",lt="[onClickGooglePaySessionHandler]",qn=class{constructor(t){O(this,"onCancelPayment");O(this,"clientId");O(this,"gatewayMerchantId");O(this,"runtimeConfigEnvironment");O(this,"applePayIsSupported",!1);O(this,"samsungPayIsSupported",!1);O(this,"googlePayIsSupported",!1);O(this,"runtimeConfig");O(this,"fingerprintAgent");O(this,"googlePayClient");O(this,"samsungPayClient");var s,l,f;Ve({source:"wallets-client",version:ut});let{onCancelPayment:n,clientId:r,gatewayMerchantId:o,runtimeConfigEnvironment:a}=t,i=(f=(l=(s=globalThis.google)==null?void 0:s.payments)==null?void 0:l.api)==null?void 0:f.PaymentsClient;this.googlePayClient=i?new i({environment:r!=null&&r.startsWith("test-")?"TEST":"PRODUCTION"}):void 0,this.samsungPayClient=window.SamsungPay?new window.SamsungPay.PaymentClient({environment:r!=null&&r.startsWith("test-")?"STAGE":"PRODUCTION",nonce:ha()}):void 0,this.onCancelPayment=n!=null?n:()=>{},this.clientId=r,this.gatewayMerchantId=o,this.runtimeConfigEnvironment=a,this.loadFingerprintAgent()}loadRuntimeConfig(){return h(this,null,function*(){var t,n;if(this.runtimeConfig===void 0&&this.clientId){let r=yield ce(this.clientId,{environment:this.runtimeConfigEnvironment});if(r.type==="error"){let o=(n=(t=r.error)==null?void 0:t.message)!=null?n:"Failed to load runtime configuration";throw E(o,r.error,{clientId:this.clientId}),r.error?r.error:new Error(o)}this.runtimeConfig=r.runtimeConfig}})}loadFingerprintAgent(){return h(this,null,function*(){this.fingerprintAgent===void 0&&(this.runtimeConfig===void 0&&(yield this.loadRuntimeConfig()),this.runtimeConfig!==void 0&&!this.runtimeConfig.fingerprint.disabled&&(this.fingerprintAgent=yield bn({config:this.runtimeConfig.fingerprint})))})}fingerprint(){return h(this,null,function*(){var n,r,o;let t=yield wn({config:(n=this.runtimeConfig)==null?void 0:n.fingerprint,agent:this.fingerprintAgent,clientId:this.clientId,sdkVersion:ut,ipAddress:(r=this.runtimeConfig)==null?void 0:r.ipAddress,ipAddressProof:(o=this.runtimeConfig)==null?void 0:o.ipAddressProof});return Ve({fingerprint:t}),t})}supportedPaymentMethods(){return h(this,null,function*(){let t=[];try{yield this.loadRuntimeConfig()}catch(n){}return this.applePayIsSupported=yield zn(this.gatewayMerchantId),this.applePayIsSupported&&t.push("APPLE_PAY"),this.samsungPayIsSupported=yield Xn(this.samsungPayClient,this.runtimeConfig),this.samsungPayIsSupported&&t.push("SAMSUNG_PAY"),this.googlePayIsSupported=yield Jn(this.googlePayClient,this.runtimeConfig),this.googlePayIsSupported&&t.push("GOOGLE_PAY"),t})}onClickApplePaySessionHandler(t,n,r,o,a,i){let s=Bn();return()=>{var u,m,g;let l=q((u=this.runtimeConfig)==null?void 0:u.applePay).map(d=>gt(d)),f={countryCode:"ZA",currencyCode:t,supportedNetworks:l,merchantCapabilities:["supports3DS"],total:{label:r,amount:n.toString()}};i&&(f.recurringPaymentRequest={paymentDescription:r,billingAgreement:i.billingAgreement,regularBilling:{label:r,amount:((m=i.recurringAmount)!=null?m:n).toString(),paymentTiming:"recurring",recurringPaymentIntervalUnit:i.recurringIntervalUnit,recurringPaymentIntervalCount:(g=i.recurringIntervalCount)!=null?g:1},managementURL:i.managementUrl});let c;try{c=new ApplePaySession(s,f)}catch(d){E("Failed to create Apple Pay session",d,{clientId:this.clientId});return}c.onvalidatemerchant=d=>h(this,null,function*(){try{let p=yield o(d.validationURL);if(!c)throw new Error("ApplePaySession is missing");if(p==null||typeof p!="object")throw new Error(`verifyCallbackResponse is not an object: ${JSON.stringify(p)}`);if(Object.keys(p).length===0)throw new Error(`verifyCallbackResponse is an empty object: ${JSON.stringify(p)}`);c.completeMerchantValidation(p)}catch(p){throw E(`${ba} Failed to complete merchant validation`,p,{clientId:this.clientId}),new M(`Failed to complete merchant validation: ${ue(p)}`)}}),c.onpaymentauthorized=d=>h(this,null,function*(){try{let p=d.payment.token,y=yield this.fingerprint(),b=yield a(p,y);switch(b.status){case"TransactionPending":case"TransactionSuccess":{c==null||c.completePayment(ApplePaySession.STATUS_SUCCESS);break}case"TransactionFailure":{c==null||c.completePayment(ApplePaySession.STATUS_FAILURE);break}default:{let P="Invalid transaction status",x=new M(`${P} ${b.status}`);throw E(`${Kn} Invalid transaction status`,x,{clientId:this.clientId}),x}}}catch(p){throw c==null||c.completePayment(ApplePaySession.STATUS_FAILURE),E(`${Kn} Failed to create payment`,p,{clientId:this.clientId}),new M(`Failed to create payment: ${ue(p)}`)}}),c.oncancel=()=>{this.onCancelPayment()},c.begin()}}onClickSamsungPaySessionHandler(t,n,r,o,a,i,s){return()=>h(this,null,function*(){if(!this.samsungPayClient){let l="Samsung Pay client not initialized",f=new Error(l);throw E(`${X} ${l}`,f,{clientId:this.clientId}),f}try{let l={orderNumber:o,merchant:{name:r,url:a,id:i,countryCode:"ZA"},amount:{option:"FORMAT_TOTAL_PRICE_ONLY",currency:t,total:n}},f=yield this.fingerprint(),c=Ie(this.runtimeConfig);Ge(`${X} Loading payment sheet`,{clientId:this.clientId,type:"SAMSUNG_PAY",samsungPay:{paymentMethods:c,transactionDetail:l}});let u=yield this.samsungPayClient.loadPaymentSheet(c,l);Ge(`${X} Received payment credential`,{clientId:this.clientId,type:"SAMSUNG_PAY",samsungPay:{paymentCredential:u}});let m=yield s(u,f);switch(m.status){case"TransactionPending":break;case"TransactionFailure":{this.samsungPayClient.notify({status:"REJECTED"});break}case"TransactionSuccess":{this.samsungPayClient.notify({status:"CHARGED"});break}default:{this.samsungPayClient.notify({status:"ERRED"});let g=`${X} Invalid transaction status: ${m.status}`,d=new M(g);throw E(g,d,{clientId:this.clientId,type:"SAMSUNG_PAY"}),d}}}catch(l){throw E(`${X} Failed to create payment`,l,{clientId:this.clientId,type:"SAMSUNG_PAY"}),new M(`${X} Failed to create payment: ${ue(l)}`)}})}onClickGooglePaySessionHandler(t){return n=>h(this,null,function*(){try{let r=yield this.fingerprint(),o=yield t(n.paymentMethodData.tokenizationData.token,r);switch(o.status){case"TransactionPending":case"TransactionFailure":case"TransactionSuccess":break;default:{let a=`${lt} Invalid transaction status: ${o.status}`,i=new M(a);throw E(a,i,{clientId:this.clientId}),i}}}catch(r){throw E(`${lt} Failed to create payment`,r,{clientId:this.clientId}),new M(`${lt} Failed to create payment: ${ue(r)}`)}})}};export{qn as StitchWalletClientSdk,mt as WalletType};
27
27
  //# sourceMappingURL=index.js.map