@payment-kit-js/vanilla 0.3.0-alpha.0 → 0.3.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.
@@ -0,0 +1,10 @@
1
+ /**
2
+ * PaymentKit.js v0.3.0
3
+ * https://paymentkit.com
4
+ *
5
+ * @license MIT
6
+ */
7
+
8
+ "use strict";var PaymentKit=(()=>{var W=Object.defineProperty;var Ze=Object.getOwnPropertyDescriptor;var Ye=Object.getOwnPropertyNames;var Qe=Object.prototype.hasOwnProperty;var ve=e=>{throw TypeError(e)};var en=(e,n,t)=>n in e?W(e,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[n]=t;var nn=(e,n)=>{for(var t in n)W(e,t,{get:n[t],enumerable:!0})},tn=(e,n,t,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let s of Ye(n))!Qe.call(e,s)&&s!==t&&W(e,s,{get:()=>n[s],enumerable:!(r=Ze(n,s))||r.enumerable});return e};var rn=e=>tn(W({},"__esModule",{value:!0}),e);var d=(e,n,t)=>en(e,typeof n!="symbol"?n+"":n,t),ge=(e,n,t)=>n.has(e)||ve("Cannot "+t);var f=(e,n,t)=>(ge(e,n,"read from private field"),t?t.call(e):n.get(e)),g=(e,n,t)=>n.has(e)?ve("Cannot add the same private member more than once"):n instanceof WeakSet?n.add(e):n.set(e,t),_=(e,n,t,r)=>(ge(e,n,"write to private field"),r?r.call(e,t):n.set(e,t),t);var gt={};nn(gt,{PaymentMethods:()=>vt,default:()=>dt});var ke="0.3.0";var on=class extends Error{constructor(n,t){super(t);d(this,"code");this.name="PenpalError",this.code=n}},E=on,un=e=>({name:e.name,message:e.message,stack:e.stack,penpalCode:e instanceof E?e.code:void 0}),an=({name:e,message:n,stack:t,penpalCode:r})=>{let s=r?new E(r,n):new Error(n);return s.name=e,s.stack=t,s},ln=Symbol("Reply"),oe,Ee,cn=(Ee=class{constructor(e,n){d(this,"value");d(this,"transferables");g(this,oe,ln);this.value=e,this.transferables=n?.transferables}},oe=new WeakMap,Ee),pn=cn,x="penpal",Y=e=>typeof e=="object"&&e!==null,Ce=e=>typeof e=="function",fn=e=>Y(e)&&e.namespace===x,B=e=>e.type==="SYN",ae=e=>e.type==="ACK1",se=e=>e.type==="ACK2",Se=e=>e.type==="CALL",Me=e=>e.type==="REPLY",yn=e=>e.type==="DESTROY",Ae=(e,n=[])=>{let t=[];for(let r of Object.keys(e)){let s=e[r];Ce(s)?t.push([...n,r]):Y(s)&&t.push(...Ae(s,[...n,r]))}return t},hn=(e,n)=>{let t=e.reduce((r,s)=>Y(r)?r[s]:void 0,n);return Ce(t)?t:void 0},A=e=>e.join("."),be=(e,n,t)=>({namespace:x,channel:e,type:"REPLY",callId:n,isError:!0,...t instanceof Error?{value:un(t),isSerializedErrorInstance:!0}:{value:t}}),mn=(e,n,t,r)=>{let s=!1,i=async o=>{if(s||!Se(o))return;r?.(`Received ${A(o.methodPath)}() call`,o);let{methodPath:p,args:u,id:l}=o,c,y;try{let a=hn(p,n);if(!a)throw new E("METHOD_NOT_FOUND",`Method \`${A(p)}\` is not found.`);let h=await a(...u);h instanceof pn&&(y=h.transferables,h=await h.value),c={namespace:x,channel:t,type:"REPLY",callId:l,value:h}}catch(a){c=be(t,l,a)}if(!s)try{r?.(`Sending ${A(p)}() reply`,c),e.sendMessage(c,y)}catch(a){throw a.name==="DataCloneError"&&(c=be(t,l,a),r?.(`Sending ${A(p)}() reply`,c),e.sendMessage(c)),a}};return e.addMessageHandler(i),()=>{s=!0,e.removeMessageHandler(i)}},dn=mn,Re=crypto.randomUUID?.bind(crypto)??(()=>new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")),vn=Symbol("CallOptions"),ue,_e,gn=(_e=class{constructor(e){d(this,"transferables");d(this,"timeout");g(this,ue,vn);this.transferables=e?.transferables,this.timeout=e?.timeout}},ue=new WeakMap,_e),kn=gn,bn=new Set(["apply","call","bind"]),Te=(e,n,t=[])=>new Proxy(t.length?()=>{}:Object.create(null),{get(r,s){if(s!=="then")return t.length&&bn.has(s)?Reflect.get(r,s):Te(e,n,[...t,s])},apply(r,s,i){return e(t,i)}}),Pe=e=>new E("CONNECTION_DESTROYED",`Method call ${A(e)}() failed due to destroyed connection`),Pn=(e,n,t)=>{let r=!1,s=new Map,i=u=>{if(!Me(u))return;let{callId:l,value:c,isError:y,isSerializedErrorInstance:a}=u,h=s.get(l);h&&(s.delete(l),t?.(`Received ${A(h.methodPath)}() call`,u),y?h.reject(a?an(c):c):h.resolve(c))};return e.addMessageHandler(i),{remoteProxy:Te((u,l)=>{if(r)throw Pe(u);let c=Re(),y=l[l.length-1],a=y instanceof kn,{timeout:h,transferables:v}=a?y:{},b=a?l.slice(0,-1):l;return new Promise((k,C)=>{let P=h!==void 0?window.setTimeout(()=>{s.delete(c),C(new E("METHOD_CALL_TIMEOUT",`Method call ${A(u)}() timed out after ${h}ms`))},h):void 0;s.set(c,{methodPath:u,resolve:k,reject:C,timeoutId:P});try{let I={namespace:x,channel:n,type:"CALL",id:c,methodPath:u,args:b};t?.(`Sending ${A(u)}() call`,I),e.sendMessage(I,v)}catch(I){C(new E("TRANSMISSION_FAILED",I.message))}})},t),destroy:()=>{r=!0,e.removeMessageHandler(i);for(let{methodPath:u,reject:l,timeoutId:c}of s.values())clearTimeout(c),l(Pe(u));s.clear()}}},wn=Pn,xn=()=>{let e,n;return{promise:new Promise((r,s)=>{e=r,n=s}),resolve:e,reject:n}},En=xn,_n=class extends Error{constructor(e){super(`You've hit a bug in Penpal. Please file an issue with the following information: ${e}`)}},J=_n,ie="deprecated-penpal",In=e=>Y(e)&&"penpal"in e,Cn=e=>e.split("."),we=e=>e.join("."),De=e=>new J(`Unexpected message to translate: ${JSON.stringify(e)}`),Sn=e=>{if(e.penpal==="syn")return{namespace:x,channel:void 0,type:"SYN",participantId:ie};if(e.penpal==="ack")return{namespace:x,channel:void 0,type:"ACK2"};if(e.penpal==="call")return{namespace:x,channel:void 0,type:"CALL",id:e.id,methodPath:Cn(e.methodName),args:e.args};if(e.penpal==="reply")return e.resolution==="fulfilled"?{namespace:x,channel:void 0,type:"REPLY",callId:e.id,value:e.returnValue}:{namespace:x,channel:void 0,type:"REPLY",callId:e.id,isError:!0,...e.returnValueIsError?{value:e.returnValue,isSerializedErrorInstance:!0}:{value:e.returnValue}};throw De(e)},Mn=e=>{if(ae(e))return{penpal:"synAck",methodNames:e.methodPaths.map(we)};if(Se(e))return{penpal:"call",id:e.id,methodName:we(e.methodPath),args:e.args};if(Me(e))return e.isError?{penpal:"reply",id:e.callId,resolution:"rejected",...e.isSerializedErrorInstance?{returnValue:e.value,returnValueIsError:!0}:{returnValue:e.value}}:{penpal:"reply",id:e.callId,resolution:"fulfilled",returnValue:e.value};throw De(e)},An=({messenger:e,methods:n,timeout:t,channel:r,log:s})=>{let i=Re(),o,p=[],u=!1,l=Ae(n),{promise:c,resolve:y,reject:a}=En(),h=t!==void 0?setTimeout(()=>{a(new E("CONNECTION_TIMEOUT",`Connection timed out after ${t}ms`))},t):void 0,v=()=>{for(let m of p)m()},b=()=>{if(u)return;p.push(dn(e,n,r,s));let{remoteProxy:m,destroy:R}=wn(e,r,s);p.push(R),clearTimeout(h),u=!0,y({remoteProxy:m,destroy:v})},k=()=>{let m={namespace:x,type:"SYN",channel:r,participantId:i};s?.("Sending handshake SYN",m);try{e.sendMessage(m)}catch(R){a(new E("TRANSMISSION_FAILED",R.message))}},C=m=>{if(s?.("Received handshake SYN",m),m.participantId===o&&o!==ie||(o=m.participantId,k(),!(i>o||o===ie)))return;let H={namespace:x,channel:r,type:"ACK1",methodPaths:l};s?.("Sending handshake ACK1",H);try{e.sendMessage(H)}catch(Je){a(new E("TRANSMISSION_FAILED",Je.message));return}},P=m=>{s?.("Received handshake ACK1",m);let R={namespace:x,channel:r,type:"ACK2"};s?.("Sending handshake ACK2",R);try{e.sendMessage(R)}catch(H){a(new E("TRANSMISSION_FAILED",H.message));return}b()},I=m=>{s?.("Received handshake ACK2",m),b()},de=m=>{B(m)&&C(m),ae(m)&&P(m),se(m)&&I(m)};return e.addMessageHandler(de),p.push(()=>e.removeMessageHandler(de)),k(),c},Rn=An,Tn=e=>{let n=!1,t;return(...r)=>(n||(n=!0,t=e(...r)),t)},Dn=Tn,xe=new WeakSet,On=({messenger:e,methods:n={},timeout:t,channel:r,log:s})=>{if(!e)throw new E("INVALID_ARGUMENT","messenger must be defined");if(xe.has(e))throw new E("INVALID_ARGUMENT","A messenger can only be used for a single connection");xe.add(e);let i=[e.destroy],o=Dn(l=>{if(l){let c={namespace:x,channel:r,type:"DESTROY"};try{e.sendMessage(c)}catch{}}for(let c of i)c();s?.("Connection destroyed")}),p=l=>fn(l)&&l.channel===r;return{promise:(async()=>{try{e.initialize({log:s,validateReceivedMessage:p}),e.addMessageHandler(y=>{yn(y)&&o(!1)});let{remoteProxy:l,destroy:c}=await Rn({messenger:e,methods:n,timeout:t,channel:r,log:s});return i.push(c),l}catch(l){throw o(!0),l}})(),destroy:()=>{o(!0)}}},Oe=On,S,T,N,q,D,M,w,O,Z,G,U,V,$,Ie,Fn=(Ie=class{constructor({remoteWindow:e,allowedOrigins:n}){g(this,S);g(this,T);g(this,N);g(this,q);g(this,D);g(this,M,new Set);g(this,w);g(this,O,!1);d(this,"initialize",({log:e,validateReceivedMessage:n})=>{_(this,N,e),_(this,q,n),window.addEventListener("message",f(this,V))});d(this,"sendMessage",(e,n)=>{if(B(e)){let t=f(this,G).call(this,e);f(this,S).postMessage(e,{targetOrigin:t,transfer:n});return}if(ae(e)||f(this,O)){let t=f(this,O)?Mn(e):e,r=f(this,G).call(this,e);f(this,S).postMessage(t,{targetOrigin:r,transfer:n});return}if(se(e)){let{port1:t,port2:r}=new MessageChannel;_(this,w,t),t.addEventListener("message",f(this,$)),t.start();let s=[r,...n||[]],i=f(this,G).call(this,e);f(this,S).postMessage(e,{targetOrigin:i,transfer:s});return}if(f(this,w)){f(this,w).postMessage(e,{transfer:n});return}throw new J("Port is undefined")});d(this,"addMessageHandler",e=>{f(this,M).add(e)});d(this,"removeMessageHandler",e=>{f(this,M).delete(e)});d(this,"destroy",()=>{window.removeEventListener("message",f(this,V)),f(this,U).call(this),f(this,M).clear()});g(this,Z,e=>f(this,T).some(n=>n instanceof RegExp?n.test(e):n===e||n==="*"));g(this,G,e=>{if(B(e))return"*";if(!f(this,D))throw new J("Concrete remote origin not set");return f(this,D)==="null"&&f(this,T).includes("*")?"*":f(this,D)});g(this,U,()=>{f(this,w)?.removeEventListener("message",f(this,$)),f(this,w)?.close(),_(this,w,void 0)});g(this,V,({source:e,origin:n,ports:t,data:r})=>{var s,i,o;if(e===f(this,S)&&(In(r)&&((s=f(this,N))==null||s.call(this,"Please upgrade the child window to the latest version of Penpal."),_(this,O,!0),r=Sn(r)),!!((i=f(this,q))!=null&&i.call(this,r)))){if(!f(this,Z).call(this,n)){(o=f(this,N))==null||o.call(this,`Received a message from origin \`${n}\` which did not match allowed origins \`[${f(this,T).join(", ")}]\``);return}if(B(r)&&(f(this,U).call(this),_(this,D,n)),se(r)&&!f(this,O)){if(_(this,w,t[0]),!f(this,w))throw new J("No port received on ACK2");f(this,w).addEventListener("message",f(this,$)),f(this,w).start()}for(let p of f(this,M))p(r)}});g(this,$,({data:e})=>{var n;if((n=f(this,q))!=null&&n.call(this,e))for(let t of f(this,M))t(e)});if(!e)throw new E("INVALID_ARGUMENT","remoteWindow must be defined");_(this,S,e),_(this,T,n?.length?n:[window.origin])}},S=new WeakMap,T=new WeakMap,N=new WeakMap,q=new WeakMap,D=new WeakMap,M=new WeakMap,w=new WeakMap,O=new WeakMap,Z=new WeakMap,G=new WeakMap,U=new WeakMap,V=new WeakMap,$=new WeakMap,Ie),Fe=Fn;var Q=({window:e,methods:n})=>{let t=new Fe({remoteWindow:e,allowedOrigins:["*"]});return Oe({methods:n,messenger:t})};var je=(e,n)=>Q({window:e.contentWindow,methods:n});var ne=class ne{constructor(n,t){d(this,"penpalConn");d(this,"_methods");this.penpalConn=n,this._methods=t}get publicEndpoints(){let n={get:(t,r)=>async(...s)=>await this._methods.queryPublicEndpoint(r,s[0],s[1])};return new Proxy({},n)}destroy(){this.penpalConn.destroy()}};d(ne,"createFromPenpalConnection",async n=>{let t=await n.promise;return new ne(n,t)});var ee=ne;var jn={local:{baseUrl:"http://localhost:9101",apiBaseUrl:"http://localhost:9000"},sandbox:{baseUrl:"https://staging.paymentkit.com/customer",apiBaseUrl:"https://staging.paymentkit.com"},production:{baseUrl:"https://paymentkit.com/customer",apiBaseUrl:"https://paymentkit.com"}};function Ne(e){let t=jn[e];if(!t)throw new Error(`Invalid environment: ${e}. Must be one of: local, sandbox, production`);return t}var le;function qe(e){return{lang:e?.lang??le?.lang,message:e?.message,abortEarly:e?.abortEarly??le?.abortEarly,abortPipeEarly:e?.abortPipeEarly??le?.abortPipeEarly}}var Nn;function qn(e){return Nn?.get(e)}var Gn;function $n(e){return Gn?.get(e)}var Kn;function zn(e,n){return Kn?.get(e)?.get(n)}function Ln(e){let n=typeof e;return n==="string"?`"${e}"`:n==="number"||n==="bigint"||n==="boolean"?`${e}`:n==="object"||n==="function"?(e&&Object.getPrototypeOf(e)?.constructor?.name)??"null":n}function F(e,n,t,r,s){let i=s&&"input"in s?s.input:t.value,o=s?.expected??e.expects??null,p=s?.received??Ln(i),u={kind:e.kind,type:e.type,input:i,expected:o,received:p,message:`Invalid ${n}: ${o?`Expected ${o} but r`:"R"}eceived ${p}`,requirement:e.requirement,path:s?.path,issues:s?.issues,lang:r.lang,abortEarly:r.abortEarly,abortPipeEarly:r.abortPipeEarly},l=e.kind==="schema",c=s?.message??e.message??zn(e.reference,u.lang)??(l?$n(u.lang):null)??r.message??qn(u.lang);c!==void 0&&(u.message=typeof c=="function"?c(u):c),l&&(t.typed=!1),t.issues?t.issues.push(u):t.issues=[u]}function ce(e){return{version:1,vendor:"valibot",validate(n){return e["~run"]({value:n},qe())}}}function Ge(e){if(e.path){let n="";for(let t of e.path)if(typeof t.key=="string"||typeof t.key=="number")n?n+=`.${t.key}`:n+=t.key;else return null;return n}return null}var Xn=/^[\w+-]+(?:\.[\w+-]+)*@[\da-z]+(?:[.-][\da-z]+)*\.[a-z]{2,}$/iu;function pe(e){return{kind:"validation",type:"email",reference:pe,expects:null,async:!1,requirement:Xn,message:e,"~run"(n,t){return n.typed&&!this.requirement.test(n.value)&&F(this,"email",n,t),n}}}function fe(e,n){return{kind:"validation",type:"max_length",reference:fe,async:!1,expects:`<=${e}`,requirement:e,message:n,"~run"(t,r){return t.typed&&t.value.length>this.requirement&&F(this,"length",t,r,{received:`${t.value.length}`}),t}}}function ye(e,n){return{kind:"validation",type:"min_length",reference:ye,async:!1,expects:`>=${e}`,requirement:e,message:n,"~run"(t,r){return t.typed&&t.value.length<this.requirement&&F(this,"length",t,r,{received:`${t.value.length}`}),t}}}function K(e){return{kind:"validation",type:"non_empty",reference:K,async:!1,expects:"!0",message:e,"~run"(n,t){return n.typed&&n.value.length===0&&F(this,"length",n,t,{received:"0"}),n}}}function Un(e,n,t){return typeof e.fallback=="function"?e.fallback(n,t):e.fallback}function Vn(e,n,t){return typeof e.default=="function"?e.default(n,t):e.default}function he(e,n){return{kind:"schema",type:"object",reference:he,expects:"Object",async:!1,entries:e,message:n,get"~standard"(){return ce(this)},"~run"(t,r){let s=t.value;if(s&&typeof s=="object"){t.typed=!0,t.value={};for(let i in this.entries){let o=this.entries[i];if(i in s||(o.type==="exact_optional"||o.type==="optional"||o.type==="nullish")&&o.default!==void 0){let p=i in s?s[i]:Vn(o),u=o["~run"]({value:p},r);if(u.issues){let l={type:"object",origin:"value",input:s,key:i,value:p};for(let c of u.issues)c.path?c.path.unshift(l):c.path=[l],t.issues?.push(c);if(t.issues||(t.issues=u.issues),r.abortEarly){t.typed=!1;break}}u.typed||(t.typed=!1),t.value[i]=u.value}else if(o.fallback!==void 0)t.value[i]=Un(o);else if(o.type!=="exact_optional"&&o.type!=="optional"&&o.type!=="nullish"&&(F(this,"key",t,r,{input:void 0,expected:`"${i}"`,path:[{type:"object",origin:"key",input:s,key:i,value:s[i]}]}),r.abortEarly))break}}else F(this,"type",t,r);return t}}}function j(e){return{kind:"schema",type:"string",reference:j,expects:"string",async:!1,message:e,get"~standard"(){return ce(this)},"~run"(n,t){return typeof n.value=="string"?n.typed=!0:F(this,"type",n,t),n}}}function z(...e){return{...e[0],pipe:e,get"~standard"(){return ce(this)},"~run"(n,t){for(let r of e)if(r.kind!=="metadata"){if(n.issues&&(r.kind==="schema"||r.kind==="transformation")){n.typed=!1;break}(!n.issues||!t.abortEarly&&!t.abortPipeEarly)&&(n=r["~run"](n,t))}return n}}}function $e(e,n,t){let r=e["~run"]({value:n},qe(t));return{typed:r.typed,success:!r.issues,output:r.value,issues:r.issues}}var me=async(e,n={})=>{let t=he({customer_name:z(j("required"),K("required"),ye(4,"invalid"),fe(40,"invalid")),customer_email:z(j("required"),K("required"),pe("invalid")),customer_country:z(j("required"),K("required")),customer_zip_code:n.optionalZipCode?z(j("required")):z(j("required"),K("required"))}),r=$e(t,e);return r.issues?{isSuccess:!1,errors:r.issues.reduce((i,o)=>{let p=Ge(o);return i[p]=o.kind==="schema"?"required":o.message,i},{})}:{isSuccess:!0}};var Ke=e=>{let n=document.querySelector(e);if(!n)throw new Error(`Cannot find element with selector: ${e}`);return n},L=e=>e,te=(e,n,t)=>{let r=document.createElement("iframe"),i=new URLSearchParams(t).toString();return r.src=`${n}/embeds/v1/${e}${i?`?${i}`:""}`,Object.assign(r.style,{width:"100%",height:"100%",border:"none"}),r};function X(){return{ipAddress:void 0,browserInfo:{userAgent:navigator.userAgent,language:navigator.language,screenHeight:window.screen.height,screenWidth:window.screen.width,colorDepth:window.screen.colorDepth,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone},processorFraudInfo:void 0}}var Wn=(e,n,t)=>{let r=te("tunnel-x",e,{checkout_token:t,api_base_url:n});document.body.appendChild(r);let s=je(r,{});return{unmount:()=>{s.destroy(),document.body.removeChild(r)},connection:s}},Bn=({environment:e,secureToken:n,paymentMethods:t})=>{let{baseUrl:r,apiBaseUrl:s}=Ne(e);console.log(`[PaymentKit] v${ke} initialized (env: ${e})`);let{connection:i,unmount:o}=Wn(r,s,n),p={baseUrl:r,apiBaseUrl:s,secureToken:n,tunnelXConnection:i},u=t.map(a=>a(p)),l=u.reduce((a,{name:h,externalFuncs:v})=>(a[h]=v,a),{});return{submit:({paymentMethod:a,fields:h,options:v,onSuccess:b,onError:k})=>{let C=u.find(({name:P})=>P===a);if(!C){k({root:"payment_method_not_found"});return}C.internalFuncs.submitPayment(h,v).then(({data:P,errors:I})=>{I?k(I):b(P)}).catch(P=>{console.error("PaymentKit:submit:catch",P),P?.response?.data?k(P.response.data):P?.message?k({root:P.message}):k({root:"unknown_error"})})},cleanup:()=>{for(let a of u)a.internalFuncs.cleanup&&a.internalFuncs.cleanup();o()},...l}},ze=Bn;var Le=(e,n)=>Q({window:e.contentWindow,methods:n});var Jn=e=>new Promise(n=>setTimeout(n,e)),Xe=()=>"Stripe"in window,Zn=async e=>{for(let t=0;t<10&&!Xe();t++)await Jn(500);if(!Xe())throw new Error(`Stripe.js not loaded. Add this script tag to your HTML <head>:
9
+ <script src="https://js.stripe.com/v3/"><\/script>`);return new window.Stripe(e)},Yn=async e=>{console.log("3DS authentication required, loading Stripe...");let{clientSecret:n,stripePk:t}=e,r=await Zn(t),{error:s}=await r.confirmCardPayment(n);return s?(console.error("3DS authentication failed:",s),{success:!1,error:s.message||"3DS authentication failed"}):(console.log("3DS authentication completed"),{success:!0})},Ue=async e=>{switch(e.type){case"stripe_3ds":return Yn(e);default:return{success:!1,error:`Unknown next action type: ${e.type}`}}};var Qn=e=>{let n=e.trim(),t=n.indexOf(" ");return t===-1?{firstName:n}:{firstName:n.substring(0,t),lastName:n.substring(t+1).trim()||void 0}},et=e=>{let{firstName:n,lastName:t}=Qn(e.customer_name);return{email:e.customer_email||void 0,firstName:n,lastName:t,billingAddress:e.customer_country||e.customer_zip_code?{country:e.customer_country||void 0,zipCode:e.customer_zip_code||void 0}:void 0}},nt=e=>{let{baseUrl:n,apiBaseUrl:t,cardInputConnections:r,secureToken:s}=e;return(i,o)=>{let{style:p,onLoaded:u,onFocusChange:l}=o;return{mount:y=>{let a=Ke(y),h={checkout_token:s,api_base_url:t};p&&(h.style=JSON.stringify(p));let v=te(i.replace("_","-"),n,h);return a.appendChild(v),v.onload=()=>{let k=Le(v,{onLoaded:u||(()=>{}),onFocusChange:l||(()=>{})});e.cardInputConnections[i]=k},{unmount:()=>{r[i]?.destroy(),a.removeChild(v),e.cardInputConnections[i]=void 0}}}}}},tt=e=>async t=>{let r=await ee.createFromPenpalConnection(e.tunnelXConnection),s=await st(e),i=await me(t);if(!(s.isSuccess&&i.isSuccess))return{errors:{...s.errors,...i.errors}};if(!e.cardSetupIntentId){let y=await r.publicEndpoints.createCardSetupIntent({checkoutToken:e.secureToken});e.cardSetupIntentId=y.cardSetupIntentId}let o=await rt(e);if(!o.isSuccess)return{errors:o.errors};let p=await r.publicEndpoints.getCardSetupIntent({cardSetupIntentId:e.cardSetupIntentId,checkoutToken:e.secureToken});if(!p.isCardAllSet){let y={};return p.isCardPanSet||(y.card_pan="required"),p.isCardExpSet||(y.card_exp="required"),p.isCardCvcSet||(y.card_cvc="required"),{errors:y}}console.log("Card setup intent is set \u2705",p),console.log("Fields",t);let u=await r.publicEndpoints.cardCheckout({checkoutToken:e.secureToken,publicCardCheckoutRequest:{cardSetupIntentId:e.cardSetupIntentId,customerInfo:et(t),fraudMetadata:X()}});console.log("Card checkout result:",u);let l=5,c=0;for(;u.nextAction&&c<l;){c++,console.log(`Handling user action ${c}/${l}...`);let y=await Ue(u.nextAction);console.log("User action completed, verifying checkout...");let a=await r.publicEndpoints.cardCheckoutVerify({checkoutToken:e.secureToken});if(a.nextAction){y.success?console.log("Another user action required, continuing loop..."):console.log("3DS failed but cascade triggered new action, continuing loop..."),u=a;continue}return y.success?(console.log("Card checkout verified \u2705",a),{data:a}):(console.log("3DS authentication failed, checkout concluded:",a),{errors:{root:y.error}})}return c>=l?(console.error("Max user actions exceeded"),{errors:{root:"Too many authentication attempts. Please try again."}}):(console.log("Card checkout completed \u2705",u),{data:u})},rt=async e=>{let n={},{cardSetupIntentId:t,cardInputConnections:r}=e,s=Object.entries(r).map(async([i,o])=>{let p=i,l=await(await o.promise).onSubmit(t||"");"error"in l&&(n[p]=l.error)});return await Promise.allSettled(s),{errors:n,isSuccess:Object.keys(n).length===0}},st=async e=>{let n={},{cardInputConnections:t}=e,r=Object.entries(t).map(async([s,i])=>{let o=s;if(!i){n[o]="penpal_not_connected";return}let u=await(await i.promise).onValidate();u&&(n[o]=u)});return await Promise.allSettled(r),{errors:n,isSuccess:Object.keys(n).length===0}},it=L(e=>{let n={...e,cardInputConnections:{}};return{name:"card",externalFuncs:{createElement:nt(n)},internalFuncs:{submitPayment:tt(n),cleanup:()=>{for(let t of Object.values(n.cardInputConnections))t?.destroy();n.cardInputConnections={}}}}}),Ve=it;var re=class{constructor(n){d(this,"stripe",null);d(this,"paymentRequest",null);d(this,"mockScenario");this.mockScenario=n??"none"}initialize(n){switch(this.mockScenario){case"none":{if(console.log("[GooglePay] initialize called"),!window.Stripe)return console.log("[GooglePay] Stripe.js not loaded"),!1;this.stripe=window.Stripe(n);let t=this.stripe!==null;return console.log("[GooglePay] initialize result:",t),t}case"success":case"cancelled":return console.log("[MockGooglePay] initialize called"),console.log("[MockGooglePay] initialize result:",!0),!0}}createPaymentRequest(n){switch(this.mockScenario){case"none":{if(console.log("[GooglePay] createPaymentRequest called",n),!this.stripe)throw new Error("Stripe not initialized");this.paymentRequest=this.stripe.paymentRequest(n),console.log("[GooglePay] paymentRequest created");return}case"success":case"cancelled":{console.log("[MockGooglePay] createPaymentRequest called",n);return}}}async canMakePayment(){switch(this.mockScenario){case"none":{if(console.log("[GooglePay] canMakePayment called"),!this.paymentRequest)return console.log("[GooglePay] canMakePayment: no paymentRequest"),!1;let n=await this.paymentRequest.canMakePayment(),t=n?.googlePay??!1;return console.log("[GooglePay] canMakePayment result:",{result:n,isAvailable:t}),t}case"success":case"cancelled":return console.log("[MockGooglePay] canMakePayment called"),console.log("[MockGooglePay] canMakePayment result:",{result:{googlePay:!0},isAvailable:!0}),!0}}async showPaymentSheet(){switch(this.mockScenario){case"none":return console.log("[GooglePay] showPaymentSheet called"),this.paymentRequest?new Promise(n=>{this.paymentRequest.on("paymentmethod",t=>{console.log("[GooglePay] showPaymentSheet: paymentmethod event",{paymentMethodId:t.paymentMethod.id}),n({success:!0,paymentMethodId:t.paymentMethod.id,complete:r=>{console.log("[GooglePay] complete called:",r),t.complete(r)}})}),this.paymentRequest.on("cancel",()=>{console.log("[GooglePay] showPaymentSheet: cancelled by user"),n({success:!1,cancelled:!0})}),console.log("[GooglePay] showing payment sheet..."),this.paymentRequest.show()}):(console.log("[GooglePay] showPaymentSheet: no paymentRequest"),{success:!1,error:"Payment request not created"});case"success":return console.log("[MockGooglePay] showPaymentSheet: success"),await new Promise(n=>setTimeout(n,500)),{success:!0,paymentMethodId:"pm_mock_123456789",complete:n=>console.log(`[MockGooglePay] complete: ${n}`)};case"cancelled":return console.log("[MockGooglePay] showPaymentSheet: cancelled"),await new Promise(n=>setTimeout(n,500)),{success:!1,cancelled:!0}}}async confirmCardSetup(n,t){switch(this.mockScenario){case"none":{if(console.log("[GooglePay] confirmCardSetup called",{clientSecret:`${n.slice(0,20)}...`,paymentMethodId:t}),!this.stripe)return console.log("[GooglePay] confirmCardSetup: Stripe not initialized"),{success:!1,error:"Stripe not initialized"};let{error:r}=await this.stripe.confirmCardSetup(n,{payment_method:t});return r?(console.log("[GooglePay] confirmCardSetup error:",r),{success:!1,error:r.message??"Card setup failed"}):(console.log("[GooglePay] confirmCardSetup success"),{success:!0})}case"success":return console.log("[MockGooglePay] confirmCardSetup called",{clientSecret:n,paymentMethodId:t}),{success:!0};case"cancelled":throw new Error("confirmCardSetup should not be called when scenario is Cancelled")}}};async function He(e,n){let t=await fetch(e,n);if(!t.ok){let r=`Request failed (${t.status})`;try{r=(await t.json()).detail||r}catch{r=t.statusText||r}return{error:r}}return{data:await t.json()}}function ot(e){return e?.processorId?!e?.customerInfo?.first_name||!e?.customerInfo?.last_name?{customer_name:"Customer first and last name are required"}:null:{processor_id:"Processor ID is required"}}function ut(e){return e&&e!=="none"?e:void 0}async function at(e,n,t,r){return He(`${e}/api/checkout/${n}/google-pay/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({processor_id:t.processorId,customer_info:t.customerInfo,fraud_metadata:X(),mock_scenario:r})})}function lt(e,n,t){let r=new re(t);if(!r.initialize(e))return{error:'Stripe.js not loaded. Add <script src="https://js.stripe.com/v3/"><\/script> to your page.'};let s={country:n.country,currency:n.currency.toLowerCase(),total:{label:"Total",amount:n.amount},requestPayerName:!0,requestPayerEmail:!0};return console.log("[GooglePay] PaymentRequest config:",s),r.createPaymentRequest(s),{adapter:r}}async function ct(e,n){let t=await e.canMakePayment();if(console.log("[GooglePay] canMakePayment result:",t),!t)return{success:!1,error:"Google Pay not available on this device"};let r=await e.showPaymentSheet();if(!r.success)return"cancelled"in r&&r.cancelled?{success:!1,error:"Google Pay cancelled by user"}:{success:!1,error:"error"in r?r.error:"Unknown error"};let s=await e.confirmCardSetup(n,r.paymentMethodId);return s.success?(r.complete("success"),{success:!0}):(r.complete("fail"),{success:!1,error:s.error})}async function pt(e,n,t){let r=await He(`${e}/api/checkout/${n}/google-pay/confirm`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mock_scenario:t})});if(r.error||!r.data)return{errors:{google_pay:r.error||"Failed to confirm payment"}};let s=r.data;return s.charge_status==="success"?{data:{id:s.transaction_id,checkoutAttemptId:s.checkout_attempt_id,checkoutSessionId:n,state:"checkout_succeeded"}}:{errors:{google_pay:s.error_message||"Payment failed"}}}var ft=e=>async(t,r)=>{let{apiBaseUrl:s,secureToken:i}=e,o=r,p=ot(o);if(p)return{errors:p};try{let u=ut(o.mockScenario),l=await at(s,i,o,u);if(l.error||!l.data)return{errors:{google_pay:l.error||"Failed to start Google Pay"}};let{adapter:c,error:y}=lt(l.data.stripe_pk,l.data,o.mockScenario);if(!c)return{errors:{google_pay:y}};let a=await ct(c,l.data.client_secret);return a.success?await pt(s,i,u):{errors:{google_pay:a.error}}}catch(u){return{errors:{google_pay:`Google Pay error: ${u}`}}}},yt=L(e=>({name:"google_pay",externalFuncs:{},internalFuncs:{submitPayment:ft(e),cleanup:()=>{}}}));var We=yt;var ht=e=>async(t,r)=>{let{apiBaseUrl:s,secureToken:i}=e,o=r;if(!o?.processorId)return{errors:{processor_id:"Processor ID is required"}};if(!o?.customerInfo?.first_name||!o?.customerInfo?.last_name)return{errors:{customer_name:"Customer first and last name are required"}};try{let p=await fetch(`${s}/api/checkout/${i}/paypal/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({processor_id:o.processorId,customer_info:o.customerInfo,fraud_metadata:X()})});if(!p.ok){let a=`Failed to start PayPal checkout (${p.status})`;try{a=(await p.json()).detail||a}catch{a=p.statusText||a}return{errors:{paypal:a}}}let{approval_url:u,popup_token:l,checkout_attempt_id:c}=await p.json(),y=window.open(u,"PayPal","width=600,height=700");return y?(e.popup=y,new Promise(a=>{let h=setInterval(async()=>{try{let v=await fetch(`${s}/api/checkout/${i}/popup/status?popup_token=${l}`);if(!v.ok){clearInterval(h),y.close(),a({errors:{paypal:"Failed to check PayPal status"}});return}let b=await v.json();if(b.completed){if(clearInterval(h),y.close(),b.status==="success"){let k=b.result||{id:c,checkoutAttemptId:c,checkoutSessionId:i,state:"checkout_succeeded"};a({data:k})}else a({errors:{paypal:b.error||`PayPal checkout ${b.status}`}});return}if(y.closed){clearInterval(h),a({errors:{paypal:"PayPal popup closed by user"}});return}}catch(v){clearInterval(h),y.close(),a({errors:{paypal:`Polling error: ${v}`}})}},2e3);e.pollInterval=h})):{errors:{paypal:"Failed to open PayPal popup. Please allow popups for this site."}}}catch(p){return{errors:{paypal:`PayPal checkout error: ${p}`}}}},mt=L(e=>{let n={...e};return{name:"paypal",externalFuncs:{},internalFuncs:{submitPayment:ht(n),cleanup:()=>{n.pollInterval&&clearInterval(n.pollInterval),n.popup&&!n.popup.closed&&n.popup.close()}}}}),Be=mt;var dt=ze,vt={card:Ve,googlePay:We,paypal:Be};return rn(gt);})();
10
+ //# sourceMappingURL=paymentkit.min.js.map