@primer-io/primer-js 1.4.0 → 1.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/dist/custom-elements.json +29 -29
- package/dist/primer-loader.js +6 -6
- package/dist/web-types.json +1 -1
- package/package.json +1 -1
package/dist/primer-loader.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as jr,b as q,c as bi,d,e as S}from"./chunks/chunk.QNO3CTH5.js";var nc=q((Bw,ic)=>{"use strict";var pg={visa:{niceType:"Visa",type:"visa",patterns:[4],gaps:[4,8,12],lengths:[16,18,19],code:{name:"CVV",size:3}},mastercard:{niceType:"Mastercard",type:"mastercard",patterns:[[51,55],[2221,2229],[223,229],[23,26],[270,271],2720],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}},"american-express":{niceType:"American Express",type:"american-express",patterns:[34,37],gaps:[4,10],lengths:[15],code:{name:"CID",size:4}},"diners-club":{niceType:"Diners Club",type:"diners-club",patterns:[[300,305],36,38,39],gaps:[4,10],lengths:[14,16,19],code:{name:"CVV",size:3}},discover:{niceType:"Discover",type:"discover",patterns:[6011,[644,649],65],gaps:[4,8,12],lengths:[16,19],code:{name:"CID",size:3}},jcb:{niceType:"JCB",type:"jcb",patterns:[2131,1800,[3528,3589]],gaps:[4,8,12],lengths:[16,17,18,19],code:{name:"CVV",size:3}},unionpay:{niceType:"UnionPay",type:"unionpay",patterns:[620,[62100,62182],[62184,62187],[62185,62197],[62200,62205],[622010,622999],622018,[62207,62209],[623,626],6270,6272,6276,[627700,627779],[627781,627799],[6282,6289],6291,6292,810,[8110,8131],[8132,8151],[8152,8163],[8164,8171]],gaps:[4,8,12],lengths:[14,15,16,17,18,19],code:{name:"CVN",size:3}},maestro:{niceType:"Maestro",type:"maestro",patterns:[493698,[5e5,504174],[504176,506698],[506779,508999],[56,59],63,67,6],gaps:[4,8,12],lengths:[12,13,14,15,16,17,18,19],code:{name:"CVC",size:3}},elo:{niceType:"Elo",type:"elo",patterns:[401178,401179,438935,457631,457632,431274,451416,457393,504175,[506699,506778],[509e3,509999],627780,636297,636368,[650031,650033],[650035,650051],[650405,650439],[650485,650538],[650541,650598],[650700,650718],[650720,650727],[650901,650978],[651652,651679],[655e3,655019],[655021,655058]],gaps:[4,8,12],lengths:[16],code:{name:"CVE",size:3}},mir:{niceType:"Mir",type:"mir",patterns:[[2200,2204]],gaps:[4,8,12],lengths:[16,17,18,19],code:{name:"CVP2",size:3}},hiper:{niceType:"Hiper",type:"hiper",patterns:[637095,63737423,63743358,637568,637599,637609,637612],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}},hipercard:{niceType:"Hipercard",type:"hipercard",patterns:[606282],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}}};ic.exports=pg});var Yn=q(ai=>{"use strict";Object.defineProperty(ai,"__esModule",{value:!0});ai.clone=void 0;function mg(a){return a?JSON.parse(JSON.stringify(a)):null}ai.clone=mg});var oc=q(ii=>{"use strict";Object.defineProperty(ii,"__esModule",{value:!0});ii.matches=void 0;function hg(a,t,e){var r=String(t).length,i=a.substr(0,r),n=parseInt(i,10);return t=parseInt(String(t).substr(0,i.length),10),e=parseInt(String(e).substr(0,i.length),10),n>=t&&n<=e}function gg(a,t){return t=String(t),t.substring(0,a.length)===a.substring(0,t.length)}function yg(a,t){return Array.isArray(t)?hg(a,t[0],t[1]):gg(a,t)}ii.matches=yg});var sc=q(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:!0});ni.addMatchingCardsToResults=void 0;var fg=Yn(),vg=oc();function bg(a,t,e){var r,i;for(r=0;r<t.patterns.length;r++){var n=t.patterns[r];if((0,vg.matches)(a,n)){var o=(0,fg.clone)(t);Array.isArray(n)?i=String(n[0]).length:i=String(n).length,a.length>=i&&(o.matchStrength=i),e.push(o);break}}}ni.addMatchingCardsToResults=bg});var lc=q(oi=>{"use strict";Object.defineProperty(oi,"__esModule",{value:!0});oi.isValidInputType=void 0;function Cg(a){return typeof a=="string"||a instanceof String}oi.isValidInputType=Cg});var dc=q(si=>{"use strict";Object.defineProperty(si,"__esModule",{value:!0});si.findBestMatch=void 0;function Sg(a){var t=a.filter(function(e){return e.matchStrength}).length;return t>0&&t===a.length}function Ag(a){return Sg(a)?a.reduce(function(t,e){return!t||Number(t.matchStrength)<Number(e.matchStrength)?e:t}):null}si.findBestMatch=Ag});var Hr=q(($n,pc)=>{"use strict";var li=$n&&$n.__assign||function(){return li=Object.assign||function(a){for(var t,e=1,r=arguments.length;e<r;e++){t=arguments[e];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(a[i]=t[i])}return a},li.apply(this,arguments)},cc=nc(),Eg=sc(),Mg=lc(),Pg=dc(),Vr=Yn(),Ur={},Ae={VISA:"visa",MASTERCARD:"mastercard",AMERICAN_EXPRESS:"american-express",DINERS_CLUB:"diners-club",DISCOVER:"discover",JCB:"jcb",UNIONPAY:"unionpay",MAESTRO:"maestro",ELO:"elo",MIR:"mir",HIPER:"hiper",HIPERCARD:"hipercard"},uc=[Ae.VISA,Ae.MASTERCARD,Ae.AMERICAN_EXPRESS,Ae.DINERS_CLUB,Ae.DISCOVER,Ae.JCB,Ae.UNIONPAY,Ae.MAESTRO,Ae.ELO,Ae.MIR,Ae.HIPER,Ae.HIPERCARD],Tt=(0,Vr.clone)(uc);function zn(a){return Ur[a]||cc[a]}function Tg(){return Tt.map(function(a){return(0,Vr.clone)(zn(a))})}function jn(a,t){t===void 0&&(t=!1);var e=Tt.indexOf(a);if(!t&&e===-1)throw new Error('"'+a+'" is not a supported card type.');return e}function Nt(a){var t=[];if(!(0,Mg.isValidInputType)(a))return t;if(a.length===0)return Tg();Tt.forEach(function(r){var i=zn(r);(0,Eg.addMatchingCardsToResults)(a,i,t)});var e=(0,Pg.findBestMatch)(t);return e?[e]:t}Nt.getTypeInfo=function(a){return(0,Vr.clone)(zn(a))};Nt.removeCard=function(a){var t=jn(a);Tt.splice(t,1)};Nt.addCard=function(a){var t=jn(a.type,!0);Ur[a.type]=a,t===-1&&Tt.push(a.type)};Nt.updateCard=function(a,t){var e=Ur[a]||cc[a];if(!e)throw new Error('"'.concat(a,"\" is not a recognized type. Use `addCard` instead.'"));if(t.type&&e.type!==t.type)throw new Error("Cannot overwrite type parameter.");var r=(0,Vr.clone)(e);r=li(li({},r),t),Ur[r.type]=r};Nt.changeOrder=function(a,t){var e=jn(a);Tt.splice(e,1),Tt.splice(t,0,a)};Nt.resetModifications=function(){Tt=(0,Vr.clone)(uc),Ur={}};Nt.types=Ae;pc.exports=Nt});var mc=q(di=>{"use strict";Object.defineProperty(di,"__esModule",{value:!0});di.cardholderName=void 0;var Ng=/^[\d\s-]*$/,Ig=255;function Yr(a,t){return{isValid:a,isPotentiallyValid:t}}function kg(a){return typeof a!="string"?Yr(!1,!1):a.length===0?Yr(!1,!0):a.length>Ig?Yr(!1,!1):Ng.test(a)?Yr(!1,!0):Yr(!0,!0)}di.cardholderName=kg});var gc=q((Yw,hc)=>{"use strict";function Lg(a){for(var t=0,e=!1,r=a.length-1,i;r>=0;)i=parseInt(a.charAt(r),10),e&&(i*=2,i>9&&(i=i%10+1)),e=!e,t+=i,r--;return t%10===0}hc.exports=Lg});var fc=q(ci=>{"use strict";Object.defineProperty(ci,"__esModule",{value:!0});ci.cardNumber=void 0;var Rg=gc(),yc=Hr();function Yt(a,t,e){return{card:a,isPotentiallyValid:t,isValid:e}}function wg(a,t){t===void 0&&(t={});var e,r,i;if(typeof a!="string"&&typeof a!="number")return Yt(null,!1,!1);var n=String(a).replace(/-|\s/g,"");if(!/^\d*$/.test(n))return Yt(null,!1,!1);var o=yc(n);if(o.length===0)return Yt(null,!1,!1);if(o.length!==1)return Yt(null,!0,!1);var s=o[0];if(t.maxLength&&n.length>t.maxLength)return Yt(s,!1,!1);t.skipLuhnValidation===!0||s.type===yc.types.UNIONPAY&&t.luhnValidateUnionPay!==!0?r=!0:r=Rg(n),i=Math.max.apply(null,s.lengths),t.maxLength&&(i=Math.min(t.maxLength,i));for(var l=0;l<s.lengths.length;l++)if(s.lengths[l]===n.length)return e=n.length<i||r,Yt(s,e,r);return Yt(s,n.length<i,!1)}ci.cardNumber=wg});var pi=q(ui=>{"use strict";Object.defineProperty(ui,"__esModule",{value:!0});ui.expirationYear=void 0;var xg=19;function It(a,t,e){return{isValid:a,isPotentiallyValid:t,isCurrentYear:e||!1}}function _g(a,t){t===void 0&&(t=xg);var e;if(typeof a!="string")return It(!1,!1);if(a.replace(/\s/g,"")==="")return It(!1,!0);if(!/^\d*$/.test(a))return It(!1,!1);var r=a.length;if(r<2)return It(!1,!0);var i=new Date().getFullYear();if(r===3){var n=a.slice(0,2),o=String(i).slice(0,2);return It(!1,n===o)}if(r>4)return It(!1,!1);var s=parseInt(a,10),l=Number(String(i).substr(2,2)),c=!1;if(r===2){if(String(i).substr(0,2)===a)return It(!1,!0);e=l===s,c=s>=l&&s<=l+t}else r===4&&(e=i===s,c=s>=i&&s<=i+t);return It(c,c,e)}ui.expirationYear=_g});var vc=q(mi=>{"use strict";Object.defineProperty(mi,"__esModule",{value:!0});mi.isArray=void 0;mi.isArray=Array.isArray||function(a){return Object.prototype.toString.call(a)==="[object Array]"}});var bc=q(hi=>{"use strict";Object.defineProperty(hi,"__esModule",{value:!0});hi.parseDate=void 0;var Og=pi(),Dg=vc();function Bg(a){var t=Number(a[0]),e;return t===0?2:t>1||t===1&&Number(a[1])>2?1:t===1?(e=a.substr(1),(0,Og.expirationYear)(e).isPotentiallyValid?1:2):a.length===5?1:a.length>5?2:1}function Gg(a){var t;if(/^\d{4}-\d{1,2}$/.test(a)?t=a.split("-").reverse():/\//.test(a)?t=a.split(/\s*\/\s*/g):/\s/.test(a)&&(t=a.split(/ +/g)),(0,Dg.isArray)(t))return{month:t[0]||"",year:t.slice(1).join()};var e=Bg(a),r=a.substr(0,e);return{month:r,year:a.substr(r.length)}}hi.parseDate=Gg});var Wn=q(gi=>{"use strict";Object.defineProperty(gi,"__esModule",{value:!0});gi.expirationMonth=void 0;function $r(a,t,e){return{isValid:a,isPotentiallyValid:t,isValidForThisYear:e||!1}}function Kg(a){var t=new Date().getMonth()+1;if(typeof a!="string")return $r(!1,!1);if(a.replace(/\s/g,"")===""||a==="0")return $r(!1,!0);if(!/^\d*$/.test(a))return $r(!1,!1);var e=parseInt(a,10);if(isNaN(Number(a)))return $r(!1,!1);var r=e>0&&e<13;return $r(r,r,r&&e>=t)}gi.expirationMonth=Kg});var Cc=q(cr=>{"use strict";var Zn=cr&&cr.__assign||function(){return Zn=Object.assign||function(a){for(var t,e=1,r=arguments.length;e<r;e++){t=arguments[e];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(a[i]=t[i])}return a},Zn.apply(this,arguments)};Object.defineProperty(cr,"__esModule",{value:!0});cr.expirationDate=void 0;var Fg=bc(),Ug=Wn(),Vg=pi();function zr(a,t,e,r){return{isValid:a,isPotentiallyValid:t,month:e,year:r}}function Hg(a,t){var e;if(typeof a=="string")a=a.replace(/^(\d\d) (\d\d(\d\d)?)$/,"$1/$2"),e=(0,Fg.parseDate)(String(a));else if(a!==null&&typeof a=="object"){var r=Zn({},a);e={month:String(r.month),year:String(r.year)}}else return zr(!1,!1,null,null);var i=(0,Ug.expirationMonth)(e.month),n=(0,Vg.expirationYear)(e.year,t);if(i.isValid){if(n.isCurrentYear){var o=i.isValidForThisYear;return zr(o,o,e.month,e.year)}if(n.isValid)return zr(!0,!0,e.month,e.year)}return i.isPotentiallyValid&&n.isPotentiallyValid?zr(!1,!0,null,null):zr(!1,!1,null,null)}cr.expirationDate=Hg});var Ac=q(yi=>{"use strict";Object.defineProperty(yi,"__esModule",{value:!0});yi.cvv=void 0;var Sc=3;function Yg(a,t){for(var e=0;e<a.length;e++)if(t===a[e])return!0;return!1}function $g(a){for(var t=Sc,e=0;e<a.length;e++)t=a[e]>t?a[e]:t;return t}function ur(a,t){return{isValid:a,isPotentiallyValid:t}}function zg(a,t){return t===void 0&&(t=Sc),t=t instanceof Array?t:[t],typeof a!="string"||!/^\d*$/.test(a)?ur(!1,!1):Yg(t,a.length)?ur(!0,!0):a.length<Math.min.apply(null,t)?ur(!1,!0):a.length>$g(t)?ur(!1,!1):ur(!0,!0)}yi.cvv=zg});var Ec=q(vi=>{"use strict";Object.defineProperty(vi,"__esModule",{value:!0});vi.postalCode=void 0;var jg=3,Wg=new RegExp(/^[a-z0-9]+$/i);function fi(a,t){return{isValid:a,isPotentiallyValid:t}}function Zg(a,t){t===void 0&&(t={});var e=t.minLength||jg;return typeof a!="string"?fi(!1,!1):a.length<e?fi(!1,!0):Wg.test(a.trim().slice(0,e))?fi(!0,!0):fi(!1,!0)}vi.postalCode=Zg});var Pc=q(($t,Mc)=>{"use strict";var Jg=$t&&$t.__createBinding||(Object.create?(function(a,t,e,r){r===void 0&&(r=e);var i=Object.getOwnPropertyDescriptor(t,e);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[e]}}),Object.defineProperty(a,r,i)}):(function(a,t,e,r){r===void 0&&(r=e),a[r]=t[e]})),qg=$t&&$t.__setModuleDefault||(Object.create?(function(a,t){Object.defineProperty(a,"default",{enumerable:!0,value:t})}):function(a,t){a.default=t}),Qg=$t&&$t.__importStar||function(a){if(a&&a.__esModule)return a;var t={};if(a!=null)for(var e in a)e!=="default"&&Object.prototype.hasOwnProperty.call(a,e)&&Jg(t,a,e);return qg(t,a),t},Xg=Qg(Hr()),ey=mc(),ty=fc(),ry=Cc(),ay=Wn(),iy=pi(),ny=Ac(),oy=Ec(),sy={creditCardType:Xg,cardholderName:ey.cardholderName,number:ty.cardNumber,expirationDate:ry.expirationDate,expirationMonth:ay.expirationMonth,expirationYear:iy.expirationYear,cvv:ny.cvv,postalCode:oy.postalCode};Mc.exports=sy});var Ci=class{constructor(){S(this,"context",null)}initialize(t){this.context=t,P.debug("Session context initialized:",{checkoutSessionId:t.checkoutSessionId,clientSessionId:t.clientSessionId,primerAccountId:t.primerAccountId,environment:t.environment})}getContext(){return this.context}clear(){P.debug("Session context cleared"),this.context=null}isInitialized(){return this.context!==null}setSdkInitStartTime(t){this.context&&(this.context.sdkInitStartTime=t)}getSdkInitStartTime(){return this.context?.sdkInitStartTime}},De=new Ci;var Dc={LOCAL:"https://analytics.dev.data.primer.io/v1/sdk-logs",DEV:"https://analytics.dev.data.primer.io/v1/sdk-logs",STAGING:"https://analytics.staging.data.primer.io/v1/sdk-logs",SANDBOX:"https://analytics.sandbox.data.primer.io/v1/sdk-logs",PRODUCTION:"https://analytics.production.data.primer.io/v1/sdk-logs"};function Jn(a,t={}){let e=De.getContext();if(!e&&!t?.environment)return;let i={message:a instanceof Error?a.message:typeof a=="string"?a:JSON.stringify(a)};a instanceof Error&&a.stack&&(i.stack=a.stack),e?Object.assign(i,{primer:{checkout_session_id:e.checkoutSessionId,client_session_id:e.clientSessionId,primer_account_id:e.primerAccountId},user_agent:e.userAgent}):(t?.checkoutSessionId&&Object.assign(i,{primer:{checkout_session_id:t.checkoutSessionId}}),t?.clientSessionId&&Object.assign(i,{primer:{client_session_id:t.clientSessionId}}),t?.primerAccountId&&Object.assign(i,{primer:{primer_account_id:t.primerAccountId}}),t?.userAgent&&Object.assign(i,{user_agent:t.userAgent})),t?.metadata&&Object.assign(i,t.metadata),t.status&&(i.status=t.status);let n={message:JSON.stringify(i),hostname:typeof window<"u"?window.location.hostname:"unknown",service:"web-sdk",ddsource:"lambda",ddtags:`env:${e?.environment||t?.environment},version:${e?.sdkVersion||t?.sdkVersion}`};Bc(n,{environment:e?.environment||t?.environment,clientSessionToken:e?.clientSessionToken||t?.clientSessionToken})}var qn=(a,t={})=>Jn(a,{...t,status:"error"});function Qn(a){let t={event:"CHECKOUT_INITIALIZED"};a!==void 0&&(t.init_duration_ms=a),Jn("Checkout initialized",{status:"info",metadata:t})}function Bc(a,{environment:t,clientSessionToken:e}){if(t==="LOCAL"||a.hostname==="localhost"){P.debug("\u{1F436}\u{1F436}\u{1F436} [Datadog Log] \u{1F436}\u{1F436}\u{1F436}",a);return}let r=Dc[t||"LOCAL"];if(!r){P.warn("No logging endpoint configured for current environment");return}fetch(r,{method:"POST",headers:{"Content-Type":"application/json",...e&&{Authorization:`Bearer ${e}`}},body:JSON.stringify(a),keepalive:!0,priority:"low"}).catch(i=>{P.error("Failed to send log event:",i)})}var V=class V{static _log(t,e,...r){V.enabled.includes(t)&&(console[t](`%c${V.brandTag}%c ${e}`,V.brandStyle,V.styles[t],...r),r.forEach(i=>{if(i instanceof Error){let n=i;typeof n.toJSON=="function"&&console[t]("Error details:",n.toJSON())}}))}static log(t,...e){V._log("log",t,...e)}static info(t,...e){V._log("info",t,...e)}static warn(t,...e){V._log("warn",t,...e)}static error(t,...e){V._log("error",t,...e)}static debug(t,...e){this._log("debug",t,...e)}static errorWithDatadog(t,e){let{error:r,status:i="error"}=e||{};if(V.enabled.includes("error")){if(console.error(`%c${V.brandTag}%c ${t}`,V.brandStyle,V.styles.error,r||""),r instanceof Error){let n=r;typeof n.toJSON=="function"&&console.error("Error details:",n.toJSON())}try{let n={status:i,metadata:{sdkOptions:V.sdkOptions,clientToken:V.clientToken,error:r}};qn(t,n)}catch(n){this.debug("Failed to send error to remote logging:",n)}}}static setSdkOptions(t){V.sdkOptions=t}static setClientToken(t){V.clientToken=t}};S(V,"enabled",["warn","error"]),S(V,"sdkOptions"),S(V,"clientToken"),S(V,"defaultFont","font-family: Consolas, monospace; font-size: 12px;"),S(V,"brandTag","[PRIMER]"),S(V,"brandStyle",`background: #24292e; color: #ffffff; padding: 2px 6px; border-radius: 3px; font-weight: bold; margin-right: 4px; ${V.defaultFont}`),S(V,"styles",{log:`color: #4CAF50; ${V.defaultFont}`,info:`color: #2196F3; ${V.defaultFont}`,warn:`color: #FF9800; ${V.defaultFont}`,error:`color: #F44336; ${V.defaultFont}`,debug:`color: #9C27B0; ${V.defaultFont}`});var P=V;var Gc={"../../node_modules/card-validator/dist/card-number.js":function(a,t,e){Object.defineProperty(t,"__esModule",{value:!0}),t.cardNumber=void 0;var r=e("../../node_modules/card-validator/dist/luhn-10.js"),i=e("../../node_modules/credit-card-type/dist/index.js");function n(s,l,c){return{card:s,isPotentiallyValid:l,isValid:c}}function o(s,l){l===void 0&&(l={});var c,p,m;if(typeof s!="string"&&typeof s!="number")return n(null,!1,!1);var g=String(s).replace(/-|\s/g,"");if(!/^\d*$/.test(g))return n(null,!1,!1);var A=i(g);if(A.length===0)return n(null,!1,!1);if(A.length!==1)return n(null,!0,!1);var M=A[0];if(l.maxLength&&g.length>l.maxLength)return n(M,!1,!1);p=l.skipLuhnValidation===!0||M.type===i.types.UNIONPAY&&l.luhnValidateUnionPay!==!0?!0:r(g),m=Math.max.apply(null,M.lengths),l.maxLength&&(m=Math.min(l.maxLength,m));for(var w=0;w<M.lengths.length;w++)if(M.lengths[w]===g.length)return c=g.length<m||p,n(M,c,p);return n(M,g.length<m,!1)}t.cardNumber=o},"../../node_modules/card-validator/dist/cardholder-name.js":function(a,t){Object.defineProperty(t,"__esModule",{value:!0}),t.cardholderName=void 0;var e=/^[\d\s-]*$/,r=255;function i(o,s){return{isValid:o,isPotentiallyValid:s}}function n(o){return typeof o!="string"?i(!1,!1):o.length===0?i(!1,!0):o.length>r?i(!1,!1):e.test(o)?i(!1,!0):i(!0,!0)}t.cardholderName=n},"../../node_modules/card-validator/dist/cvv.js":function(a,t){Object.defineProperty(t,"__esModule",{value:!0}),t.cvv=void 0;var e=3;function r(s,l){for(var c=0;c<s.length;c++)if(l===s[c])return!0;return!1}function i(s){for(var l=e,c=0;c<s.length;c++)l=s[c]>l?s[c]:l;return l}function n(s,l){return{isValid:s,isPotentiallyValid:l}}function o(s,l){return l===void 0&&(l=e),l=l instanceof Array?l:[l],typeof s!="string"||!/^\d*$/.test(s)?n(!1,!1):r(l,s.length)?n(!0,!0):s.length<Math.min.apply(null,l)?n(!1,!0):s.length>i(l)?n(!1,!1):n(!0,!0)}t.cvv=o},"../../node_modules/card-validator/dist/expiration-date.js":function(a,t,e){var r=this&&this.__assign||function(){return r=Object.assign||function(c){for(var p,m=1,g=arguments.length;m<g;m++){p=arguments[m];for(var A in p)Object.prototype.hasOwnProperty.call(p,A)&&(c[A]=p[A])}return c},r.apply(this,arguments)};Object.defineProperty(t,"__esModule",{value:!0}),t.expirationDate=void 0;var i=e("../../node_modules/card-validator/dist/lib/parse-date.js"),n=e("../../node_modules/card-validator/dist/expiration-month.js"),o=e("../../node_modules/card-validator/dist/expiration-year.js");function s(c,p,m,g){return{isValid:c,isPotentiallyValid:p,month:m,year:g}}function l(c,p){var m;if(typeof c=="string")c=c.replace(/^(\d\d) (\d\d(\d\d)?)$/,"$1/$2"),m=(0,i.parseDate)(String(c));else{if(c===null||typeof c!="object")return s(!1,!1,null,null);var g=r({},c);m={month:String(g.month),year:String(g.year)}}var A=(0,n.expirationMonth)(m.month),M=(0,o.expirationYear)(m.year,p);if(A.isValid){if(M.isCurrentYear){var w=A.isValidForThisYear;return s(w,w,m.month,m.year)}if(M.isValid)return s(!0,!0,m.month,m.year)}return A.isPotentiallyValid&&M.isPotentiallyValid?s(!1,!0,null,null):s(!1,!1,null,null)}t.expirationDate=l},"../../node_modules/card-validator/dist/expiration-month.js":function(a,t){Object.defineProperty(t,"__esModule",{value:!0}),t.expirationMonth=void 0;function e(i,n,o){return{isValid:i,isPotentiallyValid:n,isValidForThisYear:o||!1}}function r(i){var n=new Date().getMonth()+1;if(typeof i!="string")return e(!1,!1);if(i.replace(/\s/g,"")===""||i==="0")return e(!1,!0);if(!/^\d*$/.test(i))return e(!1,!1);var o=parseInt(i,10);if(isNaN(Number(i)))return e(!1,!1);var s=o>0&&o<13;return e(s,s,s&&o>=n)}t.expirationMonth=r},"../../node_modules/card-validator/dist/expiration-year.js":function(a,t){Object.defineProperty(t,"__esModule",{value:!0}),t.expirationYear=void 0;var e=19;function r(n,o,s){return{isValid:n,isPotentiallyValid:o,isCurrentYear:s||!1}}function i(n,o){o===void 0&&(o=e);var s;if(typeof n!="string")return r(!1,!1);if(n.replace(/\s/g,"")==="")return r(!1,!0);if(!/^\d*$/.test(n))return r(!1,!1);var l=n.length;if(l<2)return r(!1,!0);var c=new Date().getFullYear();if(l===3){var p=n.slice(0,2),m=String(c).slice(0,2);return r(!1,p===m)}if(l>4)return r(!1,!1);var g=parseInt(n,10),A=Number(String(c).substr(2,2)),M=!1;if(l===2){if(String(c).substr(0,2)===n)return r(!1,!0);s=A===g,M=g>=A&&g<=A+o}else l===4&&(s=c===g,M=g>=c&&g<=c+o);return r(M,M,s)}t.expirationYear=i},"../../node_modules/card-validator/dist/index.js":function(a,t,e){var r=this&&this.__createBinding||(Object.create?function(w,L,I,x){x===void 0&&(x=I);var _=Object.getOwnPropertyDescriptor(L,I);(!_||("get"in _?!L.__esModule:_.writable||_.configurable))&&(_={enumerable:!0,get:function(){return L[I]}}),Object.defineProperty(w,x,_)}:function(w,L,I,x){x===void 0&&(x=I),w[x]=L[I]}),i=this&&this.__setModuleDefault||(Object.create?function(w,L){Object.defineProperty(w,"default",{enumerable:!0,value:L})}:function(w,L){w.default=L}),n=this&&this.__importStar||function(w){if(w&&w.__esModule)return w;var L={};if(w!=null)for(var I in w)I!=="default"&&Object.prototype.hasOwnProperty.call(w,I)&&r(L,w,I);return i(L,w),L},o=n(e("../../node_modules/credit-card-type/dist/index.js")),s=e("../../node_modules/card-validator/dist/cardholder-name.js"),l=e("../../node_modules/card-validator/dist/card-number.js"),c=e("../../node_modules/card-validator/dist/expiration-date.js"),p=e("../../node_modules/card-validator/dist/expiration-month.js"),m=e("../../node_modules/card-validator/dist/expiration-year.js"),g=e("../../node_modules/card-validator/dist/cvv.js"),A=e("../../node_modules/card-validator/dist/postal-code.js"),M={creditCardType:o,cardholderName:s.cardholderName,number:l.cardNumber,expirationDate:c.expirationDate,expirationMonth:p.expirationMonth,expirationYear:m.expirationYear,cvv:g.cvv,postalCode:A.postalCode};a.exports=M},"../../node_modules/card-validator/dist/lib/is-array.js":function(a,t){Object.defineProperty(t,"__esModule",{value:!0}),t.isArray=void 0,t.isArray=Array.isArray||function(e){return Object.prototype.toString.call(e)==="[object Array]"}},"../../node_modules/card-validator/dist/lib/parse-date.js":function(a,t,e){Object.defineProperty(t,"__esModule",{value:!0}),t.parseDate=void 0;var r=e("../../node_modules/card-validator/dist/expiration-year.js"),i=e("../../node_modules/card-validator/dist/lib/is-array.js");function n(s){var l=Number(s[0]),c;return l===0?2:l>1||l===1&&Number(s[1])>2?1:l===1?(c=s.substr(1),(0,r.expirationYear)(c).isPotentiallyValid?1:2):s.length===5?1:s.length>5?2:1}function o(s){var l;if(/^\d{4}-\d{1,2}$/.test(s)?l=s.split("-").reverse():/\//.test(s)?l=s.split(/\s*\/\s*/g):/\s/.test(s)&&(l=s.split(/ +/g)),(0,i.isArray)(l))return{month:l[0]||"",year:l.slice(1).join()};var c=n(s),p=s.substr(0,c);return{month:p,year:s.substr(p.length)}}t.parseDate=o},"../../node_modules/card-validator/dist/luhn-10.js":function(a){function t(e){for(var r=0,i=!1,n=e.length-1,o;n>=0;)o=parseInt(e.charAt(n),10),i&&(o*=2,o>9&&(o=o%10+1)),i=!i,r+=o,n--;return r%10===0}a.exports=t},"../../node_modules/card-validator/dist/postal-code.js":function(a,t){Object.defineProperty(t,"__esModule",{value:!0}),t.postalCode=void 0;var e=3,r=new RegExp(/^[a-z0-9]+$/i);function i(o,s){return{isValid:o,isPotentiallyValid:s}}function n(o,s){s===void 0&&(s={});var l=s.minLength||e;return typeof o!="string"?i(!1,!1):o.length<l||!r.test(o.trim().slice(0,l))?i(!1,!0):i(!0,!0)}t.postalCode=n},"../../node_modules/credit-card-type/dist/index.js":function(a,t,e){var r=this&&this.__assign||function(){return r=Object.assign||function(I){for(var x,_=1,z=arguments.length;_<z;_++){x=arguments[_];for(var Z in x)Object.prototype.hasOwnProperty.call(x,Z)&&(I[Z]=x[Z])}return I},r.apply(this,arguments)},i=e("../../node_modules/credit-card-type/dist/lib/card-types.js"),n=e("../../node_modules/credit-card-type/dist/lib/add-matching-cards-to-results.js"),o=e("../../node_modules/credit-card-type/dist/lib/is-valid-input-type.js"),s=e("../../node_modules/credit-card-type/dist/lib/find-best-match.js"),l=e("../../node_modules/credit-card-type/dist/lib/clone.js"),c={},p={VISA:"visa",MASTERCARD:"mastercard",AMERICAN_EXPRESS:"american-express",DINERS_CLUB:"diners-club",DISCOVER:"discover",JCB:"jcb",UNIONPAY:"unionpay",MAESTRO:"maestro",ELO:"elo",MIR:"mir",HIPER:"hiper",HIPERCARD:"hipercard"},m=[p.VISA,p.MASTERCARD,p.AMERICAN_EXPRESS,p.DINERS_CLUB,p.DISCOVER,p.JCB,p.UNIONPAY,p.MAESTRO,p.ELO,p.MIR,p.HIPER,p.HIPERCARD],g=(0,l.clone)(m);function A(I){return c[I]||i[I]}function M(){return g.map(function(I){return(0,l.clone)(A(I))})}function w(I,x){x===void 0&&(x=!1);var _=g.indexOf(I);if(!x&&_===-1)throw new Error('"'+I+'" is not a supported card type.');return _}function L(I){var x=[];if(!(0,o.isValidInputType)(I))return x;if(I.length===0)return M();g.forEach(function(z){var Z=A(z);(0,n.addMatchingCardsToResults)(I,Z,x)});var _=(0,s.findBestMatch)(x);return _?[_]:x}L.getTypeInfo=function(I){return(0,l.clone)(A(I))},L.removeCard=function(I){var x=w(I);g.splice(x,1)},L.addCard=function(I){var x=w(I.type,!0);c[I.type]=I,x===-1&&g.push(I.type)},L.updateCard=function(I,x){var _=c[I]||i[I];if(!_)throw new Error('"'.concat(I,"\" is not a recognized type. Use `addCard` instead.'"));if(x.type&&_.type!==x.type)throw new Error("Cannot overwrite type parameter.");var z=(0,l.clone)(_);z=r(r({},z),x),c[z.type]=z},L.changeOrder=function(I,x){var _=w(I);g.splice(_,1),g.splice(x,0,I)},L.resetModifications=function(){g=(0,l.clone)(m),c={}},L.types=p,a.exports=L},"../../node_modules/credit-card-type/dist/lib/add-matching-cards-to-results.js":function(a,t,e){Object.defineProperty(t,"__esModule",{value:!0}),t.addMatchingCardsToResults=void 0;var r=e("../../node_modules/credit-card-type/dist/lib/clone.js"),i=e("../../node_modules/credit-card-type/dist/lib/matches.js");function n(o,s,l){var c,p;for(c=0;c<s.patterns.length;c++){var m=s.patterns[c];if((0,i.matches)(o,m)){var g=(0,r.clone)(s);p=Array.isArray(m)?String(m[0]).length:String(m).length,o.length>=p&&(g.matchStrength=p),l.push(g);break}}}t.addMatchingCardsToResults=n},"../../node_modules/credit-card-type/dist/lib/card-types.js":function(a){var t={visa:{niceType:"Visa",type:"visa",patterns:[4],gaps:[4,8,12],lengths:[16,18,19],code:{name:"CVV",size:3}},mastercard:{niceType:"Mastercard",type:"mastercard",patterns:[[51,55],[2221,2229],[223,229],[23,26],[270,271],2720],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}},"american-express":{niceType:"American Express",type:"american-express",patterns:[34,37],gaps:[4,10],lengths:[15],code:{name:"CID",size:4}},"diners-club":{niceType:"Diners Club",type:"diners-club",patterns:[[300,305],36,38,39],gaps:[4,10],lengths:[14,16,19],code:{name:"CVV",size:3}},discover:{niceType:"Discover",type:"discover",patterns:[6011,[644,649],65],gaps:[4,8,12],lengths:[16,19],code:{name:"CID",size:3}},jcb:{niceType:"JCB",type:"jcb",patterns:[2131,1800,[3528,3589]],gaps:[4,8,12],lengths:[16,17,18,19],code:{name:"CVV",size:3}},unionpay:{niceType:"UnionPay",type:"unionpay",patterns:[620,[62100,62182],[62184,62187],[62185,62197],[62200,62205],[622010,622999],622018,[62207,62209],[623,626],6270,6272,6276,[627700,627779],[627781,627799],[6282,6289],6291,6292,810,[8110,8131],[8132,8151],[8152,8163],[8164,8171]],gaps:[4,8,12],lengths:[14,15,16,17,18,19],code:{name:"CVN",size:3}},maestro:{niceType:"Maestro",type:"maestro",patterns:[493698,[5e5,504174],[504176,506698],[506779,508999],[56,59],63,67,6],gaps:[4,8,12],lengths:[12,13,14,15,16,17,18,19],code:{name:"CVC",size:3}},elo:{niceType:"Elo",type:"elo",patterns:[401178,401179,438935,457631,457632,431274,451416,457393,504175,[506699,506778],[509e3,509999],627780,636297,636368,[650031,650033],[650035,650051],[650405,650439],[650485,650538],[650541,650598],[650700,650718],[650720,650727],[650901,650978],[651652,651679],[655e3,655019],[655021,655058]],gaps:[4,8,12],lengths:[16],code:{name:"CVE",size:3}},mir:{niceType:"Mir",type:"mir",patterns:[[2200,2204]],gaps:[4,8,12],lengths:[16,17,18,19],code:{name:"CVP2",size:3}},hiper:{niceType:"Hiper",type:"hiper",patterns:[637095,63737423,63743358,637568,637599,637609,637612],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}},hipercard:{niceType:"Hipercard",type:"hipercard",patterns:[606282],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}}};a.exports=t},"../../node_modules/credit-card-type/dist/lib/clone.js":function(a,t){Object.defineProperty(t,"__esModule",{value:!0}),t.clone=void 0;function e(r){return r?JSON.parse(JSON.stringify(r)):null}t.clone=e},"../../node_modules/credit-card-type/dist/lib/find-best-match.js":function(a,t){Object.defineProperty(t,"__esModule",{value:!0}),t.findBestMatch=void 0;function e(i){var n=i.filter(function(o){return o.matchStrength}).length;return n>0&&n===i.length}function r(i){return e(i)?i.reduce(function(n,o){return!n||Number(n.matchStrength)<Number(o.matchStrength)?o:n}):null}t.findBestMatch=r},"../../node_modules/credit-card-type/dist/lib/is-valid-input-type.js":function(a,t){Object.defineProperty(t,"__esModule",{value:!0}),t.isValidInputType=void 0;function e(r){return typeof r=="string"||r instanceof String}t.isValidInputType=e},"../../node_modules/credit-card-type/dist/lib/matches.js":function(a,t){Object.defineProperty(t,"__esModule",{value:!0}),t.matches=void 0;function e(n,o,s){var l=String(o).length,c=n.substr(0,l),p=parseInt(c,10);return o=parseInt(String(o).substr(0,c.length),10),s=parseInt(String(s).substr(0,c.length),10),p>=o&&p<=s}function r(n,o){return o=String(o),o.substring(0,n.length)===n.substring(0,o.length)}function i(n,o){return Array.isArray(o)?e(n,o[0],o[1]):r(n,o)}t.matches=i}},Xn={};function Wi(a){var t=Xn[a];if(t!==void 0)return t.exports;var e=Xn[a]={exports:{}};return Gc[a].call(e.exports,e,e.exports,Wi),e.exports}var he=()=>Lo.randomUUID?.()||Kc(),Kc=()=>"10000000-1000-4000-8000-100000000000".replace(/[018]/g,a=>(a^Fc()>>a/4).toString(16)),Fc=()=>(Lo.getRandomValues?.(new Uint8Array(1))[0]??16*Math.random())&15,Lo=typeof crypto<"u"?crypto:{},Ni=class{constructor(){S(this,"context",null)}initialize(t){this.context=t,C.debug("Session context initialized:",{checkoutSessionId:t.checkoutSessionId,clientSessionId:t.clientSessionId,primerAccountId:t.primerAccountId,environment:t.environment})}getContext(){return this.context}clear(){C.debug("Session context cleared"),this.context=null}isInitialized(){return this.context!==null}setSdkInitStartTime(t){this.context&&(this.context.sdkInitStartTime=t)}getSdkInitStartTime(){return this.context?.sdkInitStartTime}},ma=new Ni,Uc={LOCAL:"https://analytics.dev.data.primer.io/v1/sdk-logs",DEV:"https://analytics.dev.data.primer.io/v1/sdk-logs",STAGING:"https://analytics.staging.data.primer.io/v1/sdk-logs",SANDBOX:"https://analytics.sandbox.data.primer.io/v1/sdk-logs",PRODUCTION:"https://analytics.production.data.primer.io/v1/sdk-logs"};function Ro(a,t={}){let e=ma.getContext();if(!e&&!t?.environment)return;let i={message:a instanceof Error?a.message:typeof a=="string"?a:JSON.stringify(a)};a instanceof Error&&a.stack&&(i.stack=a.stack),e?Object.assign(i,{primer:{checkout_session_id:e.checkoutSessionId,client_session_id:e.clientSessionId,primer_account_id:e.primerAccountId},user_agent:e.userAgent}):(t?.checkoutSessionId&&Object.assign(i,{primer:{checkout_session_id:t.checkoutSessionId}}),t?.clientSessionId&&Object.assign(i,{primer:{client_session_id:t.clientSessionId}}),t?.primerAccountId&&Object.assign(i,{primer:{primer_account_id:t.primerAccountId}}),t?.userAgent&&Object.assign(i,{user_agent:t.userAgent})),t?.metadata&&Object.assign(i,t.metadata),t.status&&(i.status=t.status);let n={message:JSON.stringify(i),hostname:typeof window<"u"?window.location.hostname:"unknown",service:"web-sdk",ddsource:"lambda",ddtags:`env:${e?.environment||t?.environment},version:${e?.sdkVersion||t?.sdkVersion}`};Hc(n,{environment:e?.environment||t?.environment,clientSessionToken:e?.clientSessionToken||t?.clientSessionToken})}var Vc=(a,t={})=>Ro(a,{...t,status:"error"});function Hc(a,{environment:t,clientSessionToken:e}){if(t==="LOCAL"||a.hostname==="localhost")return void C.debug("\u{1F436}\u{1F436}\u{1F436} [Datadog Log] \u{1F436}\u{1F436}\u{1F436}",a);let r=Uc[t||"LOCAL"];if(!r)return void C.warn("No logging endpoint configured for current environment");fetch(r,{method:"POST",headers:{"Content-Type":"application/json",...e&&{Authorization:`Bearer ${e}`}},body:JSON.stringify(a),keepalive:!0,priority:"low"}).catch(i=>{C.error("Failed to send log event:",i)})}var H=class H{static _log(t,e,...r){H.enabled.includes(t)&&(console[t](`%c${H.brandTag}%c ${e}`,H.brandStyle,H.styles[t],...r),r.forEach(i=>{if(i instanceof Error){let n=i;typeof n.toJSON=="function"&&console[t]("Error details:",n.toJSON())}}))}static log(t,...e){H._log("log",t,...e)}static info(t,...e){H._log("info",t,...e)}static warn(t,...e){H._log("warn",t,...e)}static error(t,...e){H._log("error",t,...e)}static debug(t,...e){this._log("debug",t,...e)}static errorWithDatadog(t,e){let{error:r,status:i="error"}=e||{};if(H.enabled.includes("error")){if(console.error(`%c${H.brandTag}%c ${t}`,H.brandStyle,H.styles.error,r||""),r instanceof Error){let n=r;typeof n.toJSON=="function"&&console.error("Error details:",n.toJSON())}try{let n={status:i,metadata:{sdkOptions:H.sdkOptions,clientToken:H.clientToken,error:r}};Vc(t,n)}catch(n){this.debug("Failed to send error to remote logging:",n)}}}static setSdkOptions(t){H.sdkOptions=t}static setClientToken(t){H.clientToken=t}};S(H,"enabled",["warn","error"]),S(H,"sdkOptions"),S(H,"clientToken"),S(H,"defaultFont","font-family: Consolas, monospace; font-size: 12px;"),S(H,"brandTag","[PRIMER]"),S(H,"brandStyle",`background: #24292e; color: #ffffff; padding: 2px 6px; border-radius: 3px; font-weight: bold; margin-right: 4px; ${H.defaultFont}`),S(H,"styles",{log:`color: #4CAF50; ${H.defaultFont}`,info:`color: #2196F3; ${H.defaultFont}`,warn:`color: #FF9800; ${H.defaultFont}`,error:`color: #F44336; ${H.defaultFont}`,debug:`color: #9C27B0; ${H.defaultFont}`});var C=H,Yc={LOCAL:"https://analytics.sandbox.data.primer.io/v1/sdk-analytic-events",DEV:"https://analytics.dev.data.primer.io/v1/sdk-analytic-events",STAGING:"https://analytics.staging.data.primer.io/v1/sdk-analytic-events",SANDBOX:"https://analytics.sandbox.data.primer.io/v1/sdk-analytic-events",PRODUCTION:"https://analytics.production.data.primer.io/v1/sdk-analytic-events"},Ii=class{sendEvent(t){let e=ma.getContext();if(!e)return;let r={...t,id:he(),timestamp:Math.floor(Date.now()/1e3),sdkType:"WEB",eventName:t.eventName,checkoutSessionId:e.checkoutSessionId,clientSessionId:e.clientSessionId,primerAccountId:e.primerAccountId,sdkVersion:e.sdkVersion,userAgent:e.userAgent,eventType:t.eventType,userLocale:t.userLocale,paymentMethod:t.paymentMethod,paymentId:t.paymentId,redirectDestinationUrl:t.redirectDestinationUrl,threedsProvider:t.threedsProvider,threedsResponse:t.threedsResponse};jc(r,e)}},$c=new Ii;function zc(a){let t={...a,userAgent:a.userAgent||(typeof navigator<"u"?navigator.userAgent:"")};ma.initialize(t)}function Le(a){$c.sendEvent(a)}async function jc(a,{environment:t,clientSessionToken:e}){if(t==="LOCAL")return void C.debug(`Analytics event ${a.eventName}:`,a);let r=Yc[t];return fetch(r,{method:"POST",headers:{"Content-Type":"application/json",...e&&{Authorization:`Bearer ${e}`}},body:JSON.stringify(a),keepalive:!0,priority:"low"}).catch(i=>{C.error("Failed to send analytics event:",i)})}var jt=(function(a){return a.CARD="CARD",a.NATIVE="NATIVE",a.REDIRECT="REDIRECT",a.KLARNA="KLARNA",a.ADYEN_KLARNA="ADYEN_KLARNA",a.ACH="ACH",a.MBWAY="MBWAY",a})({}),eo=Wi("../../node_modules/credit-card-type/dist/index.js");function Zi(a){return a.replace(/[-_]/g," ").replace(/[^\s\w]/g,"").replace(/([A-Z][a-z]+|[0-9]+)/g," $1").replace(/([A-Z]{2,})/g," $1").trim().split(/\s+/g)}function Wc(a){return Zi(a).filter(Boolean).map(t=>t[0].toUpperCase()+t.slice(1).toLowerCase()).join(" ")}function to(a){return Zi(a).join("-").toLowerCase()}function ro(a){return Zi(a).join("_").toUpperCase()}var wo=[["AMEX","american-express"],["CARTES_BANCAIRES"],["DANKORT"],["DINERS_CLUB","diners-club"],["DISCOVER","discover"],["ENROUTE"],["ELO","elo"],["EFTPOS"],["HIPER","hiper","hiper-pay"],["HIPERCARD","hipercard"],["INTERAC"],["JCB","jcb"],["MAESTRO","maestro"],["MASTERCARD","mastercard"],["MIR","mir","mir-pay"],["OTHER",void 0,"payment-card"],["UNIONPAY","unionpay"],["VISA","visa"]],ao=new Map(wo.map(a=>[a[0],a])),Zc=new Map(wo.filter(a=>a[1]).map(a=>[a[1],a]));function Zt(a){let{niceType:t,type:e}=(0,eo.getTypeInfo)(to(a))||(0,eo.getTypeInfo)(ao.get(ro(a))?.[1]||"")||{},[r,i,n]=Zc.get(e)||ao.get(ro(a))||[];return{asset:n||to(i||a),backend:r,display:t||Wc(a),library:i}}var B={WORLDPAY_IDEAL:"WORLDPAY_IDEAL",STRIPE_ACH:"STRIPE_ACH",STRIPE_IDEAL:"STRIPE_IDEAL",ADYEN_KLARNA:"ADYEN_KLARNA",ADYEN_BANCONTACT_CARD:"ADYEN_BANCONTACT_CARD",PAY_NL_KAARTDIRECT:"PAY_NL_KAARTDIRECT",ADYEN_EPS:"ADYEN_EPS",ADYEN_BANCONTACT_PAYCONIQ:"ADYEN_BANCONTACT_PAYCONIQ",OMISE_PROMPTPAY:"OMISE_PROMPTPAY",OMISE_TRUEMONEY:"OMISE_TRUEMONEY",ADYEN_MULTIBANCO:"ADYEN_MULTIBANCO",PACYPAY_WECHAT:"PACYPAY_WECHAT",PACYPAY_ALIPAY:"PACYPAY_ALIPAY",ADYEN_MBWAY:"ADYEN_MBWAY",XENDIT_DANA:"XENDIT_DANA",XENDIT_SHOPEEPAY:"XENDIT_SHOPEEPAY",ADYEN_PAYSHOP:"ADYEN_PAYSHOP",ADYEN_PAYTRAIL:"ADYEN_PAYTRAIL",CLEARPAY:"CLEARPAY",RAPYD_FAST:"RAPYD_FAST",RAPYD_PROMPTPAY:"RAPYD_PROMPTPAY",RAPYD_GCASH:"RAPYD_GCASH",RAPYD_POLI:"RAPYD_POLI",RAPYD_GRABPAY:"RAPYD_GRABPAY",PRIMER_PAYPAL:"PRIMER_PAYPAL",TWOC2P:"TWOC2P",NETS:"NETS",STRIPE_GIROPAY:"STRIPE_GIROPAY",MOLLIE_GIROPAY:"MOLLIE_GIROPAY",MOLLIE_EPS:"MOLLIE_EPS",PAY_NL_EPS:"PAY_NL_EPS",PAY_NL_P24:"PAY_NL_P24",MOLLIE_P24:"MOLLIE_P24",MOLLIE_SOFORT:"MOLLIE_SOFORT",COINBASE:"COINBASE",OPENNODE:"OPENNODE",MOLLIE_GIFT_CARD:"MOLLIE_GIFTCARD",XFERS_PAYNOW:"XFERS_PAYNOW",PAYMENT_CARD:"PAYMENT_CARD",APPLE_PAY:"APPLE_PAY",GOOGLE_PAY:"GOOGLE_PAY",PAYPAL:"PAYPAL",GO_CARDLESS:"GOCARDLESS",KLARNA:"KLARNA",PAY_NL_IDEAL:"PAY_NL_IDEAL",PAY_NL_SOFORT_BANKING:"PAY_NL_SOFORT_BANKING",PAY_NL_BANCONTACT:"PAY_NL_BANCONTACT",PAY_NL_PAYPAL:"PAY_NL_PAYPAL",PAY_NL_CREDIT_TRANSFER:"PAY_NL_CREDIT_TRANSFER",PAY_NL_DIRECT_DEBIT:"PAY_NL_DIRECT_DEBIT",PAY_NL_GIROPAY:"PAY_NL_GIROPAY",PAY_NL_PAYCONIQ:"PAY_NL_PAYCONIQ",PAY_NL_RIVERTY:"PAY_NL_RIVERTY",HOOLAH:"HOOLAH",ADYEN_BLIK:"ADYEN_BLIK",ADYEN_MOBILEPAY:"ADYEN_MOBILEPAY",ADYEN_VIPPS:"ADYEN_VIPPS",ADYEN_GIROPAY:"ADYEN_GIROPAY",ADYEN_SOFORT:"ADYEN_SOFORT",ADYEN_IDEAL:"ADYEN_IDEAL",ADYEN_TRUSTLY:"ADYEN_TRUSTLY",ADYEN_ALIPAY:"ADYEN_ALIPAY",ADYEN_TWINT:"ADYEN_TWINT",ADYEN_BANK_TRANSFER:"ADYEN_BANK_TRANSFER",ADYEN_CASHAPP:"ADYEN_CASHAPP",ADYEN_AFFIRM:"ADYEN_AFFIRM",MOLLIE_BANCONTACT:"MOLLIE_BANCONTACT",MOLLIE_IDEAL:"MOLLIE_IDEAL",BUCKAROO_GIROPAY:"BUCKAROO_GIROPAY",BUCKAROO_EPS:"BUCKAROO_EPS",BUCKAROO_SOFORT:"BUCKAROO_SOFORT",BUCKAROO_BANCONTACT:"BUCKAROO_BANCONTACT",BUCKAROO_IDEAL:"BUCKAROO_IDEAL",ATOME:"ATOME",DLOCAL_PIX:"DLOCAL_PIX",ALMA:"ALMA"},Jc={WORLDPAY_IDEAL:"WORLDPAY_IDEAL",AUTOMATED_CLEARING_HOUSE:"AUTOMATED_CLEARING_HOUSE",ADYEN_KLARNA:"ADYEN_KLARNA",ADYEN_BANCONTACT_CARD:"ADYEN_BANCONTACT_CARD",PAY_NL_KAARTDIRECT:"PAY_NL_KAARTDIRECT",ADYEN_EPS:"ADYEN_EPS",ADYEN_BANCONTACT_PAYCONIQ:"ADYEN_BANCONTACT_PAYCONIQ",OMISE_PROMPTPAY:"OMISE_PROMPTPAY",OMISE_TRUEMONEY:"OMISE_TRUEMONEY",ADYEN_MULTIBANCO:"ADYEN_MULTIBANCO",PACYPAY_WECHAT:"PACYPAY_WECHAT",PACYPAY_ALIPAY:"PACYPAY_ALIPAY",ADYEN_MBWAY:"ADYEN_MBWAY",XENDIT_DANA:"XENDIT_DANA",XENDIT_SHOPEEPAY:"XENDIT_SHOPEEPAY",ADYEN_PAYSHOP:"ADYEN_PAYSHOP",ADYEN_PAYTRAIL:"ADYEN_PAYTRAIL",CLEARPAY:"CLEARPAY",RAPYD_FAST:"RAPYD_FAST",RAPYD_PROMPTPAY:"RAPYD_PROMPTPAY",RAPYD_GCASH:"RAPYD_GCASH",RAPYD_POLI:"RAPYD_POLI",RAPYD_GRABPAY:"RAPYD_GRABPAY",PRIMER_PAYPAL:"PRIMER_PAYPAL",TWOC2P:"TWOC2P",NETS:"NETS",STRIPE_ACH:"STRIPE_ACH",STRIPE_GIROPAY:"STRIPE_GIROPAY",MOLLIE_GIROPAY:"MOLLIE_GIROPAY",MOLLIE_EPS:"MOLLIE_EPS",PAY_NL_EPS:"PAY_NL_EPS",PAY_NL_P24:"PAY_NL_P24",MOLLIE_P24:"MOLLIE_P24",MOLLIE_SOFORT:"MOLLIE_SOFORT",COINBASE:"COINBASE",OPENNODE:"OPENNODE",MOLLIE_GIFT_CARD:"MOLLIE_GIFTCARD",XFERS_PAYNOW:"XFERS_PAYNOW",CARD:"PAYMENT_CARD",APPLE_PAY:"APPLE_PAY",GOOGLE_PAY:"GOOGLE_PAY",PAYPAL:"PAYPAL_ORDER",PAYPAL_VAULTED:"PAYPAL_BILLING_AGREEMENT",GO_CARDLESS:"GOCARDLESS",PAY_NL_IDEAL:"PAY_NL_IDEAL",PAY_NL_SOFORT_BANKING:"PAY_NL_SOFORT_BANKING",PAY_NL_BANCONTACT:"PAY_NL_BANCONTACT",PAY_NL_PAYPAL:"PAY_NL_PAYPAL",PAY_NL_CREDIT_TRANSFER:"PAY_NL_CREDIT_TRANSFER",PAY_NL_DIRECT_DEBIT:"PAY_NL_DIRECT_DEBIT",PAY_NL_GIROPAY:"PAY_NL_GIROPAY",PAY_NL_PAYCONIQ:"PAY_NL_PAYCONIQ",PAY_NL_RIVERTY:"PAY_NL_RIVERTY",HOOLAH:"HOOLAH",ADYEN_BLIK:"ADYEN_BLIK",ADYEN_VIPPS:"ADYEN_VIPPS",ADYEN_GIROPAY:"ADYEN_GIROPAY",ADYEN_SOFORT:"ADYEN_SOFORT",ADYEN_IDEAL:"ADYEN_IDEAL",ADYEN_TRUSTLY:"ADYEN_TRUSTLY",ADYEN_ALIPAY:"ADYEN_ALIPAY",ADYEN_TWINT:"ADYEN_TWINT",ADYEN_MOBILEPAY:"ADYEN_MOBILEPAY",MOLLIE_BANCONTACT:"MOLLIE_BANCONTACT",MOLLIE_IDEAL:"MOLLIE_IDEAL",BUCKAROO_GIROPAY:"BUCKAROO_GIROPAY",BUCKAROO_EPS:"BUCKAROO_EPS",BUCKAROO_SOFORT:"BUCKAROO_SOFORT",BUCKAROO_BANCONTACT:"BUCKAROO_BANCONTACT",BUCKAROO_IDEAL:"BUCKAROO_IDEAL",ATOME:"ATOME",KLARNA_CUSTOMER_TOKEN:"KLARNA_CUSTOMER_TOKEN",DLOCAL_PIX:"DLOCAL_PIX",ALMA:"ALMA",ADYEN_CASHAPP:"ADYEN_CASHAPP",ADYEN_AFFIRM:"ADYEN_AFFIRM"},xo="3.7.7",qc=xo,Qt=typeof Buffer=="function",io=typeof TextDecoder=="function"?new TextDecoder:void 0,no=typeof TextEncoder=="function"?new TextEncoder:void 0,Qc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",gr=Array.prototype.slice.call(Qc),Wr=(a=>{let t={};return a.forEach((e,r)=>t[e]=r),t})(gr),Xc=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,ee=String.fromCharCode.bind(String),oo=typeof Uint8Array.from=="function"?Uint8Array.from.bind(Uint8Array):a=>new Uint8Array(Array.prototype.slice.call(a,0)),_o=a=>a.replace(/=/g,"").replace(/[+\/]/g,t=>t=="+"?"-":"_"),Oo=a=>a.replace(/[^A-Za-z0-9\+\/]/g,""),Do=a=>{let t,e,r,i,n="",o=a.length%3;for(let s=0;s<a.length;){if((e=a.charCodeAt(s++))>255||(r=a.charCodeAt(s++))>255||(i=a.charCodeAt(s++))>255)throw new TypeError("invalid character found");t=e<<16|r<<8|i,n+=gr[t>>18&63]+gr[t>>12&63]+gr[t>>6&63]+gr[63&t]}return o?n.slice(0,o-3)+"===".substring(o):n},Ji=typeof btoa=="function"?a=>btoa(a):Qt?a=>Buffer.from(a,"binary").toString("base64"):Do,ki=Qt?a=>Buffer.from(a).toString("base64"):a=>{let e=[];for(let r=0,i=a.length;r<i;r+=4096)e.push(ee.apply(null,a.subarray(r,r+4096)));return Ji(e.join(""))},ea=(a,t=!1)=>t?_o(ki(a)):ki(a),eu=a=>{if(a.length<2){var t=a.charCodeAt(0);return t<128?a:t<2048?ee(192|t>>>6)+ee(128|63&t):ee(224|t>>>12&15)+ee(128|t>>>6&63)+ee(128|63&t)}var t=65536+(a.charCodeAt(0)-55296)*1024+(a.charCodeAt(1)-56320);return ee(240|t>>>18&7)+ee(128|t>>>12&63)+ee(128|t>>>6&63)+ee(128|63&t)},tu=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,Bo=a=>a.replace(tu,eu),so=Qt?a=>Buffer.from(a,"utf8").toString("base64"):no?a=>ki(no.encode(a)):a=>Ji(Bo(a)),Wt=(a,t=!1)=>t?_o(so(a)):so(a),lo=a=>Wt(a,!0),ru=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,au=a=>{switch(a.length){case 4:var t=(7&a.charCodeAt(0))<<18|(63&a.charCodeAt(1))<<12|(63&a.charCodeAt(2))<<6|63&a.charCodeAt(3),e=t-65536;return ee((e>>>10)+55296)+ee((1023&e)+56320);case 3:return ee((15&a.charCodeAt(0))<<12|(63&a.charCodeAt(1))<<6|63&a.charCodeAt(2));default:return ee((31&a.charCodeAt(0))<<6|63&a.charCodeAt(1))}},Go=a=>a.replace(ru,au),Ko=a=>{if(a=a.replace(/\s+/g,""),!Xc.test(a))throw new TypeError("malformed base64.");a+="==".slice(2-(3&a.length));let t,e="",r,i;for(let n=0;n<a.length;)t=Wr[a.charAt(n++)]<<18|Wr[a.charAt(n++)]<<12|(r=Wr[a.charAt(n++)])<<6|(i=Wr[a.charAt(n++)]),e+=r===64?ee(t>>16&255):i===64?ee(t>>16&255,t>>8&255):ee(t>>16&255,t>>8&255,255&t);return e},qi=typeof atob=="function"?a=>atob(Oo(a)):Qt?a=>Buffer.from(a,"base64").toString("binary"):Ko,Fo=Qt?a=>oo(Buffer.from(a,"base64")):a=>oo(qi(a).split("").map(t=>t.charCodeAt(0))),Uo=a=>Fo(Vo(a)),iu=Qt?a=>Buffer.from(a,"base64").toString("utf8"):io?a=>io.decode(Fo(a)):a=>Go(qi(a)),Vo=a=>Oo(a.replace(/[-_]/g,t=>t=="-"?"+":"/")),Li=a=>iu(Vo(a)),nu=a=>{if(typeof a!="string")return!1;let t=a.replace(/\s+/g,"").replace(/={0,2}$/,"");return!/[^\s0-9a-zA-Z\+/]/.test(t)||!/[^\s0-9a-zA-Z\-_]/.test(t)},Ho=a=>({value:a,enumerable:!1,writable:!0,configurable:!0}),Yo=function(){let a=(t,e)=>Object.defineProperty(String.prototype,t,Ho(e));a("fromBase64",function(){return Li(this)}),a("toBase64",function(t){return Wt(this,t)}),a("toBase64URI",function(){return Wt(this,!0)}),a("toBase64URL",function(){return Wt(this,!0)}),a("toUint8Array",function(){return Uo(this)})},$o=function(){let a=(t,e)=>Object.defineProperty(Uint8Array.prototype,t,Ho(e));a("toBase64",function(t){return ea(this,t)}),a("toBase64URI",function(){return ea(this,!0)}),a("toBase64URL",function(){return ea(this,!0)})},ou=()=>{Yo(),$o()},zo={version:xo,VERSION:qc,atob:qi,atobPolyfill:Ko,btoa:Ji,btoaPolyfill:Do,fromBase64:Li,toBase64:Wt,encode:Wt,encodeURI:lo,encodeURL:lo,utob:Bo,btou:Go,decode:Li,isValid:nu,fromUint8Array:ea,toUint8Array:Uo,extendString:Yo,extendUint8Array:$o,extendBuiltins:ou},Cr={encode:su,decode:zo.decode};function su(a,t={}){let{urlSafe:e=!1}=t;return zo.encode(a,e)}function jo(a,t){return!(a.intent!==`${t}_REDIRECTION`||!("statusUrl"in a)||!("redirectUrl"in a)||!a.redirectUrl||!a.statusUrl)}function ht(a){let t=cu(a),e=1e3*t.exp;if(Date.now()>e)throw new Error(`${lu}. Expiration date: ${new Date(e).toISOString()}`);return t}var Wo="The provided `clientToken`",lu=`${Wo} has expired`,du=`${Wo} is malformed`;function cu(a){try{let[t,e]=a.split("."),r=e||t;return JSON.parse(Cr.decode(r))}catch{throw new Error(du)}}var ta=class{constructor(t){S(this,"context");this.context=t}},ra=navigator.userAgent||navigator.vendor||window.opera||"";function Rt(){return{javaEnabled:typeof window.navigator.javaEnabled=="function"?window.navigator.javaEnabled():!1,language:window.navigator.language,colorDepth:window.screen.colorDepth,screenHeight:window.screen.height,screenWidth:window.screen.width,timezoneOffset:new Date().getTimezoneOffset(),userAgent:ra}}var Ar=()=>/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(ra)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw-(n|u)|c55\/|capi|ccwa|cdm-|cell|chtm|cldc|cmd-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc-s|devi|dica|dmob|do(c|p)o|ds(12|-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(-|_)|g1 u|g560|gene|gf-5|g-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd-(m|p|t)|hei-|hi(pt|ta)|hp( i|ip)|hs-c|ht(c(-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i-(20|go|ma)|i230|iac( |-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|-[a-w])|libw|lynx|m1-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|-([1-8]|c))|phil|pire|pl(ay|uc)|pn-2|po(ck|rt|se)|prox|psio|pt-g|qa-a|qc(07|12|21|32|60|-[2-7]|i-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h-|oo|p-)|sdk\/|se(c(-|0|1)|47|mc|nd|ri)|sgh-|shar|sie(-|m)|sk-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h-|v-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl-|tdg-|tel(i|m)|tim-|t-mo|to(pl|sh)|ts(70|m-|m3|m5)|tx-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas-|your|zeto|zte-/i.test(ra.slice(0,4)),Qi=()=>/(WebView|(iPhone|iPod|iPad)(?!.*Safari\/)|Android.*(wv))/gi.test(ra),Ri=class extends ta{async handleRequiredAction(t){let e=t.requiredAction?.clientToken;if(!e)throw new Error("No client token provided");let r=ht(e);if(!("intent"in r)||r.intent!=="3DS_AUTHENTICATION")throw new Error("Invalid client token");let{error:i,data:n}=await this.context.pciApi.post3dsAuth(r.tokenId,{device:Rt()});if(i||!n||!n.authentication)throw i??new Error("Unable to authenticate");let o=n.authentication,s=n;o.responseCode==="METHOD"&&(s=await this.handleMethod(r.tokenId,o),o=s.authentication),o.responseCode==="CHALLENGE"&&(s=await this.handleChallenge(r.tokenId,o));let l=await this.context.pciApi.postResumePayment(t.id,s.resumeToken);if(l.error||!l.data)throw l.error??new Error("Unable to resume payment");return l.data}async handleMethod(t,e){let r="primer-3ds-method-box",i="primer-3ds-method-iframe",n="primer-3ds-method-form",o="threeDSMethodData",s=document.createElement("div");s.id=r,s.style.position="absolute",s.style.width="2px",s.style.height="2px",s.style.left="-10000px";let l=document.createElement("iframe");l.style.display="none",l.id=i,l.name=i,s.appendChild(l);let c=document.createElement("form"),p=document.createElement("input");p.type="hidden",p.id=o,p.name=o,p.value=Cr.encode(JSON.stringify({threeDSServerTransID:e.transactionId,threeDSMethodNotificationURL:e.notificationUrl}),{urlSafe:!0}).replace(/=+$/g,""),c.appendChild(p),c.id=n,c.name=n,c.action=e.acsMethodUrl,c.target=i,c.method="post",s.appendChild(c),document.body.appendChild(s),c.submit();let{data:m,error:g}=await this.context.pciApi.poll3dsAuth(e.statusUrl,{timeout:13e3,isComplete:A=>!!A.error||A.data?.authentication.responseCode!=="METHOD"});return s.remove(),g||!m?this.continueAuth(t):m}async continueAuth(t){let{data:e,error:r}=await this.context.pciApi.post3dsContinue(t);return r||!e?{resumeToken:he(),authentication:{responseCode:"SKIPPED",skippedReasonCode:"NEGOTIATION_ERROR",skippedReasonText:"Failed to negotiate with 3DS server"}}:e}async handleChallenge(t,e){let{container:r,formId:i}=this.createChallengeElements(e),n=()=>{let l=document.getElementById(i);l?l.submit():requestAnimationFrame(()=>{let c=document.getElementById(i);c&&c.submit()})},o=new AbortController,s=this.context.pciApi.poll3dsAuth(e.statusUrl,{signal:o.signal,interval:2500,timeout:66e4,isComplete:l=>!!l.error||l.data?.authentication.responseCode!=="CHALLENGE"});try{let l=this.context.dialogProvider.show({htmlContent:r,onContentReady:n});Le({eventName:"PAYMENT_THREEDS",threedsResponse:JSON.stringify(e)});let c=await Promise.race([s,l.then(()=>null,p=>{throw o.abort(),p})]);return c&&c.data?(this.context.dialogProvider.close(),c.data):(this.context.dialogProvider.close(),this.continueAuth(t))}catch{return o.abort(),this.continueAuth(t)}}createChallengeElements(t){let e=`3ds-challenge-iframe-${he()}`,r=`3ds-challenge-form-${he()}`,i=/^1/.test(t.protocolVersion),n=document.createElement("div");n.className="challenge-container",n.setAttribute("style",`
|
|
1
|
+
import{a as jr,b as q,c as bi,d,e as S}from"./chunks/chunk.QNO3CTH5.js";var nc=q((Bw,ic)=>{"use strict";var pg={visa:{niceType:"Visa",type:"visa",patterns:[4],gaps:[4,8,12],lengths:[16,18,19],code:{name:"CVV",size:3}},mastercard:{niceType:"Mastercard",type:"mastercard",patterns:[[51,55],[2221,2229],[223,229],[23,26],[270,271],2720],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}},"american-express":{niceType:"American Express",type:"american-express",patterns:[34,37],gaps:[4,10],lengths:[15],code:{name:"CID",size:4}},"diners-club":{niceType:"Diners Club",type:"diners-club",patterns:[[300,305],36,38,39],gaps:[4,10],lengths:[14,16,19],code:{name:"CVV",size:3}},discover:{niceType:"Discover",type:"discover",patterns:[6011,[644,649],65],gaps:[4,8,12],lengths:[16,19],code:{name:"CID",size:3}},jcb:{niceType:"JCB",type:"jcb",patterns:[2131,1800,[3528,3589]],gaps:[4,8,12],lengths:[16,17,18,19],code:{name:"CVV",size:3}},unionpay:{niceType:"UnionPay",type:"unionpay",patterns:[620,[62100,62182],[62184,62187],[62185,62197],[62200,62205],[622010,622999],622018,[62207,62209],[623,626],6270,6272,6276,[627700,627779],[627781,627799],[6282,6289],6291,6292,810,[8110,8131],[8132,8151],[8152,8163],[8164,8171]],gaps:[4,8,12],lengths:[14,15,16,17,18,19],code:{name:"CVN",size:3}},maestro:{niceType:"Maestro",type:"maestro",patterns:[493698,[5e5,504174],[504176,506698],[506779,508999],[56,59],63,67,6],gaps:[4,8,12],lengths:[12,13,14,15,16,17,18,19],code:{name:"CVC",size:3}},elo:{niceType:"Elo",type:"elo",patterns:[401178,401179,438935,457631,457632,431274,451416,457393,504175,[506699,506778],[509e3,509999],627780,636297,636368,[650031,650033],[650035,650051],[650405,650439],[650485,650538],[650541,650598],[650700,650718],[650720,650727],[650901,650978],[651652,651679],[655e3,655019],[655021,655058]],gaps:[4,8,12],lengths:[16],code:{name:"CVE",size:3}},mir:{niceType:"Mir",type:"mir",patterns:[[2200,2204]],gaps:[4,8,12],lengths:[16,17,18,19],code:{name:"CVP2",size:3}},hiper:{niceType:"Hiper",type:"hiper",patterns:[637095,63737423,63743358,637568,637599,637609,637612],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}},hipercard:{niceType:"Hipercard",type:"hipercard",patterns:[606282],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}}};ic.exports=pg});var Yn=q(ai=>{"use strict";Object.defineProperty(ai,"__esModule",{value:!0});ai.clone=void 0;function mg(a){return a?JSON.parse(JSON.stringify(a)):null}ai.clone=mg});var oc=q(ii=>{"use strict";Object.defineProperty(ii,"__esModule",{value:!0});ii.matches=void 0;function hg(a,t,e){var r=String(t).length,i=a.substr(0,r),n=parseInt(i,10);return t=parseInt(String(t).substr(0,i.length),10),e=parseInt(String(e).substr(0,i.length),10),n>=t&&n<=e}function gg(a,t){return t=String(t),t.substring(0,a.length)===a.substring(0,t.length)}function yg(a,t){return Array.isArray(t)?hg(a,t[0],t[1]):gg(a,t)}ii.matches=yg});var sc=q(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:!0});ni.addMatchingCardsToResults=void 0;var fg=Yn(),vg=oc();function bg(a,t,e){var r,i;for(r=0;r<t.patterns.length;r++){var n=t.patterns[r];if((0,vg.matches)(a,n)){var o=(0,fg.clone)(t);Array.isArray(n)?i=String(n[0]).length:i=String(n).length,a.length>=i&&(o.matchStrength=i),e.push(o);break}}}ni.addMatchingCardsToResults=bg});var lc=q(oi=>{"use strict";Object.defineProperty(oi,"__esModule",{value:!0});oi.isValidInputType=void 0;function Cg(a){return typeof a=="string"||a instanceof String}oi.isValidInputType=Cg});var dc=q(si=>{"use strict";Object.defineProperty(si,"__esModule",{value:!0});si.findBestMatch=void 0;function Sg(a){var t=a.filter(function(e){return e.matchStrength}).length;return t>0&&t===a.length}function Ag(a){return Sg(a)?a.reduce(function(t,e){return!t||Number(t.matchStrength)<Number(e.matchStrength)?e:t}):null}si.findBestMatch=Ag});var Hr=q(($n,pc)=>{"use strict";var li=$n&&$n.__assign||function(){return li=Object.assign||function(a){for(var t,e=1,r=arguments.length;e<r;e++){t=arguments[e];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(a[i]=t[i])}return a},li.apply(this,arguments)},cc=nc(),Eg=sc(),Mg=lc(),Pg=dc(),Vr=Yn(),Ur={},Ae={VISA:"visa",MASTERCARD:"mastercard",AMERICAN_EXPRESS:"american-express",DINERS_CLUB:"diners-club",DISCOVER:"discover",JCB:"jcb",UNIONPAY:"unionpay",MAESTRO:"maestro",ELO:"elo",MIR:"mir",HIPER:"hiper",HIPERCARD:"hipercard"},uc=[Ae.VISA,Ae.MASTERCARD,Ae.AMERICAN_EXPRESS,Ae.DINERS_CLUB,Ae.DISCOVER,Ae.JCB,Ae.UNIONPAY,Ae.MAESTRO,Ae.ELO,Ae.MIR,Ae.HIPER,Ae.HIPERCARD],Tt=(0,Vr.clone)(uc);function zn(a){return Ur[a]||cc[a]}function Tg(){return Tt.map(function(a){return(0,Vr.clone)(zn(a))})}function jn(a,t){t===void 0&&(t=!1);var e=Tt.indexOf(a);if(!t&&e===-1)throw new Error('"'+a+'" is not a supported card type.');return e}function Nt(a){var t=[];if(!(0,Mg.isValidInputType)(a))return t;if(a.length===0)return Tg();Tt.forEach(function(r){var i=zn(r);(0,Eg.addMatchingCardsToResults)(a,i,t)});var e=(0,Pg.findBestMatch)(t);return e?[e]:t}Nt.getTypeInfo=function(a){return(0,Vr.clone)(zn(a))};Nt.removeCard=function(a){var t=jn(a);Tt.splice(t,1)};Nt.addCard=function(a){var t=jn(a.type,!0);Ur[a.type]=a,t===-1&&Tt.push(a.type)};Nt.updateCard=function(a,t){var e=Ur[a]||cc[a];if(!e)throw new Error('"'.concat(a,"\" is not a recognized type. Use `addCard` instead.'"));if(t.type&&e.type!==t.type)throw new Error("Cannot overwrite type parameter.");var r=(0,Vr.clone)(e);r=li(li({},r),t),Ur[r.type]=r};Nt.changeOrder=function(a,t){var e=jn(a);Tt.splice(e,1),Tt.splice(t,0,a)};Nt.resetModifications=function(){Tt=(0,Vr.clone)(uc),Ur={}};Nt.types=Ae;pc.exports=Nt});var mc=q(di=>{"use strict";Object.defineProperty(di,"__esModule",{value:!0});di.cardholderName=void 0;var Ng=/^[\d\s-]*$/,Ig=255;function Yr(a,t){return{isValid:a,isPotentiallyValid:t}}function kg(a){return typeof a!="string"?Yr(!1,!1):a.length===0?Yr(!1,!0):a.length>Ig?Yr(!1,!1):Ng.test(a)?Yr(!1,!0):Yr(!0,!0)}di.cardholderName=kg});var gc=q((Yw,hc)=>{"use strict";function Lg(a){for(var t=0,e=!1,r=a.length-1,i;r>=0;)i=parseInt(a.charAt(r),10),e&&(i*=2,i>9&&(i=i%10+1)),e=!e,t+=i,r--;return t%10===0}hc.exports=Lg});var fc=q(ci=>{"use strict";Object.defineProperty(ci,"__esModule",{value:!0});ci.cardNumber=void 0;var Rg=gc(),yc=Hr();function Yt(a,t,e){return{card:a,isPotentiallyValid:t,isValid:e}}function wg(a,t){t===void 0&&(t={});var e,r,i;if(typeof a!="string"&&typeof a!="number")return Yt(null,!1,!1);var n=String(a).replace(/-|\s/g,"");if(!/^\d*$/.test(n))return Yt(null,!1,!1);var o=yc(n);if(o.length===0)return Yt(null,!1,!1);if(o.length!==1)return Yt(null,!0,!1);var s=o[0];if(t.maxLength&&n.length>t.maxLength)return Yt(s,!1,!1);t.skipLuhnValidation===!0||s.type===yc.types.UNIONPAY&&t.luhnValidateUnionPay!==!0?r=!0:r=Rg(n),i=Math.max.apply(null,s.lengths),t.maxLength&&(i=Math.min(t.maxLength,i));for(var l=0;l<s.lengths.length;l++)if(s.lengths[l]===n.length)return e=n.length<i||r,Yt(s,e,r);return Yt(s,n.length<i,!1)}ci.cardNumber=wg});var pi=q(ui=>{"use strict";Object.defineProperty(ui,"__esModule",{value:!0});ui.expirationYear=void 0;var xg=19;function It(a,t,e){return{isValid:a,isPotentiallyValid:t,isCurrentYear:e||!1}}function _g(a,t){t===void 0&&(t=xg);var e;if(typeof a!="string")return It(!1,!1);if(a.replace(/\s/g,"")==="")return It(!1,!0);if(!/^\d*$/.test(a))return It(!1,!1);var r=a.length;if(r<2)return It(!1,!0);var i=new Date().getFullYear();if(r===3){var n=a.slice(0,2),o=String(i).slice(0,2);return It(!1,n===o)}if(r>4)return It(!1,!1);var s=parseInt(a,10),l=Number(String(i).substr(2,2)),c=!1;if(r===2){if(String(i).substr(0,2)===a)return It(!1,!0);e=l===s,c=s>=l&&s<=l+t}else r===4&&(e=i===s,c=s>=i&&s<=i+t);return It(c,c,e)}ui.expirationYear=_g});var vc=q(mi=>{"use strict";Object.defineProperty(mi,"__esModule",{value:!0});mi.isArray=void 0;mi.isArray=Array.isArray||function(a){return Object.prototype.toString.call(a)==="[object Array]"}});var bc=q(hi=>{"use strict";Object.defineProperty(hi,"__esModule",{value:!0});hi.parseDate=void 0;var Og=pi(),Dg=vc();function Bg(a){var t=Number(a[0]),e;return t===0?2:t>1||t===1&&Number(a[1])>2?1:t===1?(e=a.substr(1),(0,Og.expirationYear)(e).isPotentiallyValid?1:2):a.length===5?1:a.length>5?2:1}function Gg(a){var t;if(/^\d{4}-\d{1,2}$/.test(a)?t=a.split("-").reverse():/\//.test(a)?t=a.split(/\s*\/\s*/g):/\s/.test(a)&&(t=a.split(/ +/g)),(0,Dg.isArray)(t))return{month:t[0]||"",year:t.slice(1).join()};var e=Bg(a),r=a.substr(0,e);return{month:r,year:a.substr(r.length)}}hi.parseDate=Gg});var Wn=q(gi=>{"use strict";Object.defineProperty(gi,"__esModule",{value:!0});gi.expirationMonth=void 0;function $r(a,t,e){return{isValid:a,isPotentiallyValid:t,isValidForThisYear:e||!1}}function Kg(a){var t=new Date().getMonth()+1;if(typeof a!="string")return $r(!1,!1);if(a.replace(/\s/g,"")===""||a==="0")return $r(!1,!0);if(!/^\d*$/.test(a))return $r(!1,!1);var e=parseInt(a,10);if(isNaN(Number(a)))return $r(!1,!1);var r=e>0&&e<13;return $r(r,r,r&&e>=t)}gi.expirationMonth=Kg});var Cc=q(cr=>{"use strict";var Zn=cr&&cr.__assign||function(){return Zn=Object.assign||function(a){for(var t,e=1,r=arguments.length;e<r;e++){t=arguments[e];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(a[i]=t[i])}return a},Zn.apply(this,arguments)};Object.defineProperty(cr,"__esModule",{value:!0});cr.expirationDate=void 0;var Fg=bc(),Ug=Wn(),Vg=pi();function zr(a,t,e,r){return{isValid:a,isPotentiallyValid:t,month:e,year:r}}function Hg(a,t){var e;if(typeof a=="string")a=a.replace(/^(\d\d) (\d\d(\d\d)?)$/,"$1/$2"),e=(0,Fg.parseDate)(String(a));else if(a!==null&&typeof a=="object"){var r=Zn({},a);e={month:String(r.month),year:String(r.year)}}else return zr(!1,!1,null,null);var i=(0,Ug.expirationMonth)(e.month),n=(0,Vg.expirationYear)(e.year,t);if(i.isValid){if(n.isCurrentYear){var o=i.isValidForThisYear;return zr(o,o,e.month,e.year)}if(n.isValid)return zr(!0,!0,e.month,e.year)}return i.isPotentiallyValid&&n.isPotentiallyValid?zr(!1,!0,null,null):zr(!1,!1,null,null)}cr.expirationDate=Hg});var Ac=q(yi=>{"use strict";Object.defineProperty(yi,"__esModule",{value:!0});yi.cvv=void 0;var Sc=3;function Yg(a,t){for(var e=0;e<a.length;e++)if(t===a[e])return!0;return!1}function $g(a){for(var t=Sc,e=0;e<a.length;e++)t=a[e]>t?a[e]:t;return t}function ur(a,t){return{isValid:a,isPotentiallyValid:t}}function zg(a,t){return t===void 0&&(t=Sc),t=t instanceof Array?t:[t],typeof a!="string"||!/^\d*$/.test(a)?ur(!1,!1):Yg(t,a.length)?ur(!0,!0):a.length<Math.min.apply(null,t)?ur(!1,!0):a.length>$g(t)?ur(!1,!1):ur(!0,!0)}yi.cvv=zg});var Ec=q(vi=>{"use strict";Object.defineProperty(vi,"__esModule",{value:!0});vi.postalCode=void 0;var jg=3,Wg=new RegExp(/^[a-z0-9]+$/i);function fi(a,t){return{isValid:a,isPotentiallyValid:t}}function Zg(a,t){t===void 0&&(t={});var e=t.minLength||jg;return typeof a!="string"?fi(!1,!1):a.length<e?fi(!1,!0):Wg.test(a.trim().slice(0,e))?fi(!0,!0):fi(!1,!0)}vi.postalCode=Zg});var Pc=q(($t,Mc)=>{"use strict";var Jg=$t&&$t.__createBinding||(Object.create?(function(a,t,e,r){r===void 0&&(r=e);var i=Object.getOwnPropertyDescriptor(t,e);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[e]}}),Object.defineProperty(a,r,i)}):(function(a,t,e,r){r===void 0&&(r=e),a[r]=t[e]})),qg=$t&&$t.__setModuleDefault||(Object.create?(function(a,t){Object.defineProperty(a,"default",{enumerable:!0,value:t})}):function(a,t){a.default=t}),Qg=$t&&$t.__importStar||function(a){if(a&&a.__esModule)return a;var t={};if(a!=null)for(var e in a)e!=="default"&&Object.prototype.hasOwnProperty.call(a,e)&&Jg(t,a,e);return qg(t,a),t},Xg=Qg(Hr()),ey=mc(),ty=fc(),ry=Cc(),ay=Wn(),iy=pi(),ny=Ac(),oy=Ec(),sy={creditCardType:Xg,cardholderName:ey.cardholderName,number:ty.cardNumber,expirationDate:ry.expirationDate,expirationMonth:ay.expirationMonth,expirationYear:iy.expirationYear,cvv:ny.cvv,postalCode:oy.postalCode};Mc.exports=sy});var Ci=class{constructor(){S(this,"context",null)}initialize(t){this.context=t,P.debug("Session context initialized:",{checkoutSessionId:t.checkoutSessionId,clientSessionId:t.clientSessionId,primerAccountId:t.primerAccountId,environment:t.environment})}getContext(){return this.context}clear(){P.debug("Session context cleared"),this.context=null}isInitialized(){return this.context!==null}setSdkInitStartTime(t){this.context&&(this.context.sdkInitStartTime=t)}getSdkInitStartTime(){return this.context?.sdkInitStartTime}},De=new Ci;var Dc={LOCAL:"https://analytics.dev.data.primer.io/v1/sdk-logs",DEV:"https://analytics.dev.data.primer.io/v1/sdk-logs",STAGING:"https://analytics.staging.data.primer.io/v1/sdk-logs",SANDBOX:"https://analytics.sandbox.data.primer.io/v1/sdk-logs",PRODUCTION:"https://analytics.production.data.primer.io/v1/sdk-logs"};function Jn(a,t={}){let e=De.getContext();if(!e&&!t?.environment)return;let i={message:a instanceof Error?a.message:typeof a=="string"?a:JSON.stringify(a)};a instanceof Error&&a.stack&&(i.stack=a.stack),e?Object.assign(i,{primer:{checkout_session_id:e.checkoutSessionId,client_session_id:e.clientSessionId,primer_account_id:e.primerAccountId},user_agent:e.userAgent}):(t?.checkoutSessionId&&Object.assign(i,{primer:{checkout_session_id:t.checkoutSessionId}}),t?.clientSessionId&&Object.assign(i,{primer:{client_session_id:t.clientSessionId}}),t?.primerAccountId&&Object.assign(i,{primer:{primer_account_id:t.primerAccountId}}),t?.userAgent&&Object.assign(i,{user_agent:t.userAgent})),t?.metadata&&Object.assign(i,t.metadata),t.status&&(i.status=t.status);let n={message:JSON.stringify(i),hostname:typeof window<"u"?window.location.hostname:"unknown",service:"web-sdk",ddsource:"lambda",ddtags:`env:${e?.environment||t?.environment},version:${e?.sdkVersion||t?.sdkVersion}`};Bc(n,{environment:e?.environment||t?.environment,clientSessionToken:e?.clientSessionToken||t?.clientSessionToken})}var qn=(a,t={})=>Jn(a,{...t,status:"error"});function Qn(a){let t={event:"CHECKOUT_INITIALIZED"};a!==void 0&&(t.init_duration_ms=a),Jn("Checkout initialized",{status:"info",metadata:t})}function Bc(a,{environment:t,clientSessionToken:e}){if(t==="LOCAL"||a.hostname==="localhost"){P.debug("\u{1F436}\u{1F436}\u{1F436} [Datadog Log] \u{1F436}\u{1F436}\u{1F436}",a);return}let r=Dc[t||"LOCAL"];if(!r){P.warn("No logging endpoint configured for current environment");return}fetch(r,{method:"POST",headers:{"Content-Type":"application/json",...e&&{Authorization:`Bearer ${e}`}},body:JSON.stringify(a),keepalive:!0,priority:"low"}).catch(i=>{P.error("Failed to send log event:",i)})}var V=class V{static _log(t,e,...r){V.enabled.includes(t)&&(console[t](`%c${V.brandTag}%c ${e}`,V.brandStyle,V.styles[t],...r),r.forEach(i=>{if(i instanceof Error){let n=i;typeof n.toJSON=="function"&&console[t]("Error details:",n.toJSON())}}))}static log(t,...e){V._log("log",t,...e)}static info(t,...e){V._log("info",t,...e)}static warn(t,...e){V._log("warn",t,...e)}static error(t,...e){V._log("error",t,...e)}static debug(t,...e){this._log("debug",t,...e)}static errorWithDatadog(t,e){let{error:r,status:i="error"}=e||{};if(V.enabled.includes("error")){if(console.error(`%c${V.brandTag}%c ${t}`,V.brandStyle,V.styles.error,r||""),r instanceof Error){let n=r;typeof n.toJSON=="function"&&console.error("Error details:",n.toJSON())}try{let n={status:i,metadata:{sdkOptions:V.sdkOptions,clientToken:V.clientToken,error:r}};qn(t,n)}catch(n){this.debug("Failed to send error to remote logging:",n)}}}static setSdkOptions(t){V.sdkOptions=t}static setClientToken(t){V.clientToken=t}};S(V,"enabled",["warn","error"]),S(V,"sdkOptions"),S(V,"clientToken"),S(V,"defaultFont","font-family: Consolas, monospace; font-size: 12px;"),S(V,"brandTag","[PRIMER]"),S(V,"brandStyle",`background: #24292e; color: #ffffff; padding: 2px 6px; border-radius: 3px; font-weight: bold; margin-right: 4px; ${V.defaultFont}`),S(V,"styles",{log:`color: #4CAF50; ${V.defaultFont}`,info:`color: #2196F3; ${V.defaultFont}`,warn:`color: #FF9800; ${V.defaultFont}`,error:`color: #F44336; ${V.defaultFont}`,debug:`color: #9C27B0; ${V.defaultFont}`});var P=V;var Gc={"../../node_modules/card-validator/dist/card-number.js":function(a,t,e){Object.defineProperty(t,"__esModule",{value:!0}),t.cardNumber=void 0;var r=e("../../node_modules/card-validator/dist/luhn-10.js"),i=e("../../node_modules/credit-card-type/dist/index.js");function n(s,l,c){return{card:s,isPotentiallyValid:l,isValid:c}}function o(s,l){l===void 0&&(l={});var c,p,m;if(typeof s!="string"&&typeof s!="number")return n(null,!1,!1);var g=String(s).replace(/-|\s/g,"");if(!/^\d*$/.test(g))return n(null,!1,!1);var A=i(g);if(A.length===0)return n(null,!1,!1);if(A.length!==1)return n(null,!0,!1);var M=A[0];if(l.maxLength&&g.length>l.maxLength)return n(M,!1,!1);p=l.skipLuhnValidation===!0||M.type===i.types.UNIONPAY&&l.luhnValidateUnionPay!==!0?!0:r(g),m=Math.max.apply(null,M.lengths),l.maxLength&&(m=Math.min(l.maxLength,m));for(var w=0;w<M.lengths.length;w++)if(M.lengths[w]===g.length)return c=g.length<m||p,n(M,c,p);return n(M,g.length<m,!1)}t.cardNumber=o},"../../node_modules/card-validator/dist/cardholder-name.js":function(a,t){Object.defineProperty(t,"__esModule",{value:!0}),t.cardholderName=void 0;var e=/^[\d\s-]*$/,r=255;function i(o,s){return{isValid:o,isPotentiallyValid:s}}function n(o){return typeof o!="string"?i(!1,!1):o.length===0?i(!1,!0):o.length>r?i(!1,!1):e.test(o)?i(!1,!0):i(!0,!0)}t.cardholderName=n},"../../node_modules/card-validator/dist/cvv.js":function(a,t){Object.defineProperty(t,"__esModule",{value:!0}),t.cvv=void 0;var e=3;function r(s,l){for(var c=0;c<s.length;c++)if(l===s[c])return!0;return!1}function i(s){for(var l=e,c=0;c<s.length;c++)l=s[c]>l?s[c]:l;return l}function n(s,l){return{isValid:s,isPotentiallyValid:l}}function o(s,l){return l===void 0&&(l=e),l=l instanceof Array?l:[l],typeof s!="string"||!/^\d*$/.test(s)?n(!1,!1):r(l,s.length)?n(!0,!0):s.length<Math.min.apply(null,l)?n(!1,!0):s.length>i(l)?n(!1,!1):n(!0,!0)}t.cvv=o},"../../node_modules/card-validator/dist/expiration-date.js":function(a,t,e){var r=this&&this.__assign||function(){return r=Object.assign||function(c){for(var p,m=1,g=arguments.length;m<g;m++){p=arguments[m];for(var A in p)Object.prototype.hasOwnProperty.call(p,A)&&(c[A]=p[A])}return c},r.apply(this,arguments)};Object.defineProperty(t,"__esModule",{value:!0}),t.expirationDate=void 0;var i=e("../../node_modules/card-validator/dist/lib/parse-date.js"),n=e("../../node_modules/card-validator/dist/expiration-month.js"),o=e("../../node_modules/card-validator/dist/expiration-year.js");function s(c,p,m,g){return{isValid:c,isPotentiallyValid:p,month:m,year:g}}function l(c,p){var m;if(typeof c=="string")c=c.replace(/^(\d\d) (\d\d(\d\d)?)$/,"$1/$2"),m=(0,i.parseDate)(String(c));else{if(c===null||typeof c!="object")return s(!1,!1,null,null);var g=r({},c);m={month:String(g.month),year:String(g.year)}}var A=(0,n.expirationMonth)(m.month),M=(0,o.expirationYear)(m.year,p);if(A.isValid){if(M.isCurrentYear){var w=A.isValidForThisYear;return s(w,w,m.month,m.year)}if(M.isValid)return s(!0,!0,m.month,m.year)}return A.isPotentiallyValid&&M.isPotentiallyValid?s(!1,!0,null,null):s(!1,!1,null,null)}t.expirationDate=l},"../../node_modules/card-validator/dist/expiration-month.js":function(a,t){Object.defineProperty(t,"__esModule",{value:!0}),t.expirationMonth=void 0;function e(i,n,o){return{isValid:i,isPotentiallyValid:n,isValidForThisYear:o||!1}}function r(i){var n=new Date().getMonth()+1;if(typeof i!="string")return e(!1,!1);if(i.replace(/\s/g,"")===""||i==="0")return e(!1,!0);if(!/^\d*$/.test(i))return e(!1,!1);var o=parseInt(i,10);if(isNaN(Number(i)))return e(!1,!1);var s=o>0&&o<13;return e(s,s,s&&o>=n)}t.expirationMonth=r},"../../node_modules/card-validator/dist/expiration-year.js":function(a,t){Object.defineProperty(t,"__esModule",{value:!0}),t.expirationYear=void 0;var e=19;function r(n,o,s){return{isValid:n,isPotentiallyValid:o,isCurrentYear:s||!1}}function i(n,o){o===void 0&&(o=e);var s;if(typeof n!="string")return r(!1,!1);if(n.replace(/\s/g,"")==="")return r(!1,!0);if(!/^\d*$/.test(n))return r(!1,!1);var l=n.length;if(l<2)return r(!1,!0);var c=new Date().getFullYear();if(l===3){var p=n.slice(0,2),m=String(c).slice(0,2);return r(!1,p===m)}if(l>4)return r(!1,!1);var g=parseInt(n,10),A=Number(String(c).substr(2,2)),M=!1;if(l===2){if(String(c).substr(0,2)===n)return r(!1,!0);s=A===g,M=g>=A&&g<=A+o}else l===4&&(s=c===g,M=g>=c&&g<=c+o);return r(M,M,s)}t.expirationYear=i},"../../node_modules/card-validator/dist/index.js":function(a,t,e){var r=this&&this.__createBinding||(Object.create?function(w,L,I,_){_===void 0&&(_=I);var O=Object.getOwnPropertyDescriptor(L,I);(!O||("get"in O?!L.__esModule:O.writable||O.configurable))&&(O={enumerable:!0,get:function(){return L[I]}}),Object.defineProperty(w,_,O)}:function(w,L,I,_){_===void 0&&(_=I),w[_]=L[I]}),i=this&&this.__setModuleDefault||(Object.create?function(w,L){Object.defineProperty(w,"default",{enumerable:!0,value:L})}:function(w,L){w.default=L}),n=this&&this.__importStar||function(w){if(w&&w.__esModule)return w;var L={};if(w!=null)for(var I in w)I!=="default"&&Object.prototype.hasOwnProperty.call(w,I)&&r(L,w,I);return i(L,w),L},o=n(e("../../node_modules/credit-card-type/dist/index.js")),s=e("../../node_modules/card-validator/dist/cardholder-name.js"),l=e("../../node_modules/card-validator/dist/card-number.js"),c=e("../../node_modules/card-validator/dist/expiration-date.js"),p=e("../../node_modules/card-validator/dist/expiration-month.js"),m=e("../../node_modules/card-validator/dist/expiration-year.js"),g=e("../../node_modules/card-validator/dist/cvv.js"),A=e("../../node_modules/card-validator/dist/postal-code.js"),M={creditCardType:o,cardholderName:s.cardholderName,number:l.cardNumber,expirationDate:c.expirationDate,expirationMonth:p.expirationMonth,expirationYear:m.expirationYear,cvv:g.cvv,postalCode:A.postalCode};a.exports=M},"../../node_modules/card-validator/dist/lib/is-array.js":function(a,t){Object.defineProperty(t,"__esModule",{value:!0}),t.isArray=void 0,t.isArray=Array.isArray||function(e){return Object.prototype.toString.call(e)==="[object Array]"}},"../../node_modules/card-validator/dist/lib/parse-date.js":function(a,t,e){Object.defineProperty(t,"__esModule",{value:!0}),t.parseDate=void 0;var r=e("../../node_modules/card-validator/dist/expiration-year.js"),i=e("../../node_modules/card-validator/dist/lib/is-array.js");function n(s){var l=Number(s[0]),c;return l===0?2:l>1||l===1&&Number(s[1])>2?1:l===1?(c=s.substr(1),(0,r.expirationYear)(c).isPotentiallyValid?1:2):s.length===5?1:s.length>5?2:1}function o(s){var l;if(/^\d{4}-\d{1,2}$/.test(s)?l=s.split("-").reverse():/\//.test(s)?l=s.split(/\s*\/\s*/g):/\s/.test(s)&&(l=s.split(/ +/g)),(0,i.isArray)(l))return{month:l[0]||"",year:l.slice(1).join()};var c=n(s),p=s.substr(0,c);return{month:p,year:s.substr(p.length)}}t.parseDate=o},"../../node_modules/card-validator/dist/luhn-10.js":function(a){function t(e){for(var r=0,i=!1,n=e.length-1,o;n>=0;)o=parseInt(e.charAt(n),10),i&&(o*=2,o>9&&(o=o%10+1)),i=!i,r+=o,n--;return r%10===0}a.exports=t},"../../node_modules/card-validator/dist/postal-code.js":function(a,t){Object.defineProperty(t,"__esModule",{value:!0}),t.postalCode=void 0;var e=3,r=new RegExp(/^[a-z0-9]+$/i);function i(o,s){return{isValid:o,isPotentiallyValid:s}}function n(o,s){s===void 0&&(s={});var l=s.minLength||e;return typeof o!="string"?i(!1,!1):o.length<l||!r.test(o.trim().slice(0,l))?i(!1,!0):i(!0,!0)}t.postalCode=n},"../../node_modules/credit-card-type/dist/index.js":function(a,t,e){var r=this&&this.__assign||function(){return r=Object.assign||function(I){for(var _,O=1,z=arguments.length;O<z;O++){_=arguments[O];for(var Z in _)Object.prototype.hasOwnProperty.call(_,Z)&&(I[Z]=_[Z])}return I},r.apply(this,arguments)},i=e("../../node_modules/credit-card-type/dist/lib/card-types.js"),n=e("../../node_modules/credit-card-type/dist/lib/add-matching-cards-to-results.js"),o=e("../../node_modules/credit-card-type/dist/lib/is-valid-input-type.js"),s=e("../../node_modules/credit-card-type/dist/lib/find-best-match.js"),l=e("../../node_modules/credit-card-type/dist/lib/clone.js"),c={},p={VISA:"visa",MASTERCARD:"mastercard",AMERICAN_EXPRESS:"american-express",DINERS_CLUB:"diners-club",DISCOVER:"discover",JCB:"jcb",UNIONPAY:"unionpay",MAESTRO:"maestro",ELO:"elo",MIR:"mir",HIPER:"hiper",HIPERCARD:"hipercard"},m=[p.VISA,p.MASTERCARD,p.AMERICAN_EXPRESS,p.DINERS_CLUB,p.DISCOVER,p.JCB,p.UNIONPAY,p.MAESTRO,p.ELO,p.MIR,p.HIPER,p.HIPERCARD],g=(0,l.clone)(m);function A(I){return c[I]||i[I]}function M(){return g.map(function(I){return(0,l.clone)(A(I))})}function w(I,_){_===void 0&&(_=!1);var O=g.indexOf(I);if(!_&&O===-1)throw new Error('"'+I+'" is not a supported card type.');return O}function L(I){var _=[];if(!(0,o.isValidInputType)(I))return _;if(I.length===0)return M();g.forEach(function(z){var Z=A(z);(0,n.addMatchingCardsToResults)(I,Z,_)});var O=(0,s.findBestMatch)(_);return O?[O]:_}L.getTypeInfo=function(I){return(0,l.clone)(A(I))},L.removeCard=function(I){var _=w(I);g.splice(_,1)},L.addCard=function(I){var _=w(I.type,!0);c[I.type]=I,_===-1&&g.push(I.type)},L.updateCard=function(I,_){var O=c[I]||i[I];if(!O)throw new Error('"'.concat(I,"\" is not a recognized type. Use `addCard` instead.'"));if(_.type&&O.type!==_.type)throw new Error("Cannot overwrite type parameter.");var z=(0,l.clone)(O);z=r(r({},z),_),c[z.type]=z},L.changeOrder=function(I,_){var O=w(I);g.splice(O,1),g.splice(_,0,I)},L.resetModifications=function(){g=(0,l.clone)(m),c={}},L.types=p,a.exports=L},"../../node_modules/credit-card-type/dist/lib/add-matching-cards-to-results.js":function(a,t,e){Object.defineProperty(t,"__esModule",{value:!0}),t.addMatchingCardsToResults=void 0;var r=e("../../node_modules/credit-card-type/dist/lib/clone.js"),i=e("../../node_modules/credit-card-type/dist/lib/matches.js");function n(o,s,l){var c,p;for(c=0;c<s.patterns.length;c++){var m=s.patterns[c];if((0,i.matches)(o,m)){var g=(0,r.clone)(s);p=Array.isArray(m)?String(m[0]).length:String(m).length,o.length>=p&&(g.matchStrength=p),l.push(g);break}}}t.addMatchingCardsToResults=n},"../../node_modules/credit-card-type/dist/lib/card-types.js":function(a){var t={visa:{niceType:"Visa",type:"visa",patterns:[4],gaps:[4,8,12],lengths:[16,18,19],code:{name:"CVV",size:3}},mastercard:{niceType:"Mastercard",type:"mastercard",patterns:[[51,55],[2221,2229],[223,229],[23,26],[270,271],2720],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}},"american-express":{niceType:"American Express",type:"american-express",patterns:[34,37],gaps:[4,10],lengths:[15],code:{name:"CID",size:4}},"diners-club":{niceType:"Diners Club",type:"diners-club",patterns:[[300,305],36,38,39],gaps:[4,10],lengths:[14,16,19],code:{name:"CVV",size:3}},discover:{niceType:"Discover",type:"discover",patterns:[6011,[644,649],65],gaps:[4,8,12],lengths:[16,19],code:{name:"CID",size:3}},jcb:{niceType:"JCB",type:"jcb",patterns:[2131,1800,[3528,3589]],gaps:[4,8,12],lengths:[16,17,18,19],code:{name:"CVV",size:3}},unionpay:{niceType:"UnionPay",type:"unionpay",patterns:[620,[62100,62182],[62184,62187],[62185,62197],[62200,62205],[622010,622999],622018,[62207,62209],[623,626],6270,6272,6276,[627700,627779],[627781,627799],[6282,6289],6291,6292,810,[8110,8131],[8132,8151],[8152,8163],[8164,8171]],gaps:[4,8,12],lengths:[14,15,16,17,18,19],code:{name:"CVN",size:3}},maestro:{niceType:"Maestro",type:"maestro",patterns:[493698,[5e5,504174],[504176,506698],[506779,508999],[56,59],63,67,6],gaps:[4,8,12],lengths:[12,13,14,15,16,17,18,19],code:{name:"CVC",size:3}},elo:{niceType:"Elo",type:"elo",patterns:[401178,401179,438935,457631,457632,431274,451416,457393,504175,[506699,506778],[509e3,509999],627780,636297,636368,[650031,650033],[650035,650051],[650405,650439],[650485,650538],[650541,650598],[650700,650718],[650720,650727],[650901,650978],[651652,651679],[655e3,655019],[655021,655058]],gaps:[4,8,12],lengths:[16],code:{name:"CVE",size:3}},mir:{niceType:"Mir",type:"mir",patterns:[[2200,2204]],gaps:[4,8,12],lengths:[16,17,18,19],code:{name:"CVP2",size:3}},hiper:{niceType:"Hiper",type:"hiper",patterns:[637095,63737423,63743358,637568,637599,637609,637612],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}},hipercard:{niceType:"Hipercard",type:"hipercard",patterns:[606282],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}}};a.exports=t},"../../node_modules/credit-card-type/dist/lib/clone.js":function(a,t){Object.defineProperty(t,"__esModule",{value:!0}),t.clone=void 0;function e(r){return r?JSON.parse(JSON.stringify(r)):null}t.clone=e},"../../node_modules/credit-card-type/dist/lib/find-best-match.js":function(a,t){Object.defineProperty(t,"__esModule",{value:!0}),t.findBestMatch=void 0;function e(i){var n=i.filter(function(o){return o.matchStrength}).length;return n>0&&n===i.length}function r(i){return e(i)?i.reduce(function(n,o){return!n||Number(n.matchStrength)<Number(o.matchStrength)?o:n}):null}t.findBestMatch=r},"../../node_modules/credit-card-type/dist/lib/is-valid-input-type.js":function(a,t){Object.defineProperty(t,"__esModule",{value:!0}),t.isValidInputType=void 0;function e(r){return typeof r=="string"||r instanceof String}t.isValidInputType=e},"../../node_modules/credit-card-type/dist/lib/matches.js":function(a,t){Object.defineProperty(t,"__esModule",{value:!0}),t.matches=void 0;function e(n,o,s){var l=String(o).length,c=n.substr(0,l),p=parseInt(c,10);return o=parseInt(String(o).substr(0,c.length),10),s=parseInt(String(s).substr(0,c.length),10),p>=o&&p<=s}function r(n,o){return o=String(o),o.substring(0,n.length)===n.substring(0,o.length)}function i(n,o){return Array.isArray(o)?e(n,o[0],o[1]):r(n,o)}t.matches=i}},Xn={};function Wi(a){var t=Xn[a];if(t!==void 0)return t.exports;var e=Xn[a]={exports:{}};return Gc[a].call(e.exports,e,e.exports,Wi),e.exports}var he=()=>Lo.randomUUID?.()||Kc(),Kc=()=>"10000000-1000-4000-8000-100000000000".replace(/[018]/g,a=>(a^Fc()>>a/4).toString(16)),Fc=()=>(Lo.getRandomValues?.(new Uint8Array(1))[0]??16*Math.random())&15,Lo=typeof crypto<"u"?crypto:{},Ni=class{constructor(){S(this,"context",null)}initialize(t){this.context=t,C.debug("Session context initialized:",{checkoutSessionId:t.checkoutSessionId,clientSessionId:t.clientSessionId,primerAccountId:t.primerAccountId,environment:t.environment})}getContext(){return this.context}clear(){C.debug("Session context cleared"),this.context=null}isInitialized(){return this.context!==null}setSdkInitStartTime(t){this.context&&(this.context.sdkInitStartTime=t)}getSdkInitStartTime(){return this.context?.sdkInitStartTime}},ma=new Ni,Uc={LOCAL:"https://analytics.dev.data.primer.io/v1/sdk-logs",DEV:"https://analytics.dev.data.primer.io/v1/sdk-logs",STAGING:"https://analytics.staging.data.primer.io/v1/sdk-logs",SANDBOX:"https://analytics.sandbox.data.primer.io/v1/sdk-logs",PRODUCTION:"https://analytics.production.data.primer.io/v1/sdk-logs"};function Ro(a,t={}){let e=ma.getContext();if(!e&&!t?.environment)return;let i={message:a instanceof Error?a.message:typeof a=="string"?a:JSON.stringify(a)};a instanceof Error&&a.stack&&(i.stack=a.stack),e?Object.assign(i,{primer:{checkout_session_id:e.checkoutSessionId,client_session_id:e.clientSessionId,primer_account_id:e.primerAccountId},user_agent:e.userAgent}):(t?.checkoutSessionId&&Object.assign(i,{primer:{checkout_session_id:t.checkoutSessionId}}),t?.clientSessionId&&Object.assign(i,{primer:{client_session_id:t.clientSessionId}}),t?.primerAccountId&&Object.assign(i,{primer:{primer_account_id:t.primerAccountId}}),t?.userAgent&&Object.assign(i,{user_agent:t.userAgent})),t?.metadata&&Object.assign(i,t.metadata),t.status&&(i.status=t.status);let n={message:JSON.stringify(i),hostname:typeof window<"u"?window.location.hostname:"unknown",service:"web-sdk",ddsource:"lambda",ddtags:`env:${e?.environment||t?.environment},version:${e?.sdkVersion||t?.sdkVersion}`};Hc(n,{environment:e?.environment||t?.environment,clientSessionToken:e?.clientSessionToken||t?.clientSessionToken})}var Vc=(a,t={})=>Ro(a,{...t,status:"error"});function Hc(a,{environment:t,clientSessionToken:e}){if(t==="LOCAL"||a.hostname==="localhost")return void C.debug("\u{1F436}\u{1F436}\u{1F436} [Datadog Log] \u{1F436}\u{1F436}\u{1F436}",a);let r=Uc[t||"LOCAL"];if(!r)return void C.warn("No logging endpoint configured for current environment");fetch(r,{method:"POST",headers:{"Content-Type":"application/json",...e&&{Authorization:`Bearer ${e}`}},body:JSON.stringify(a),keepalive:!0,priority:"low"}).catch(i=>{C.error("Failed to send log event:",i)})}var H=class H{static _log(t,e,...r){H.enabled.includes(t)&&(console[t](`%c${H.brandTag}%c ${e}`,H.brandStyle,H.styles[t],...r),r.forEach(i=>{if(i instanceof Error){let n=i;typeof n.toJSON=="function"&&console[t]("Error details:",n.toJSON())}}))}static log(t,...e){H._log("log",t,...e)}static info(t,...e){H._log("info",t,...e)}static warn(t,...e){H._log("warn",t,...e)}static error(t,...e){H._log("error",t,...e)}static debug(t,...e){this._log("debug",t,...e)}static errorWithDatadog(t,e){let{error:r,status:i="error"}=e||{};if(H.enabled.includes("error")){if(console.error(`%c${H.brandTag}%c ${t}`,H.brandStyle,H.styles.error,r||""),r instanceof Error){let n=r;typeof n.toJSON=="function"&&console.error("Error details:",n.toJSON())}try{let n={status:i,metadata:{sdkOptions:H.sdkOptions,clientToken:H.clientToken,error:r}};Vc(t,n)}catch(n){this.debug("Failed to send error to remote logging:",n)}}}static setSdkOptions(t){H.sdkOptions=t}static setClientToken(t){H.clientToken=t}};S(H,"enabled",["warn","error"]),S(H,"sdkOptions"),S(H,"clientToken"),S(H,"defaultFont","font-family: Consolas, monospace; font-size: 12px;"),S(H,"brandTag","[PRIMER]"),S(H,"brandStyle",`background: #24292e; color: #ffffff; padding: 2px 6px; border-radius: 3px; font-weight: bold; margin-right: 4px; ${H.defaultFont}`),S(H,"styles",{log:`color: #4CAF50; ${H.defaultFont}`,info:`color: #2196F3; ${H.defaultFont}`,warn:`color: #FF9800; ${H.defaultFont}`,error:`color: #F44336; ${H.defaultFont}`,debug:`color: #9C27B0; ${H.defaultFont}`});var C=H,Yc={LOCAL:"https://analytics.sandbox.data.primer.io/v1/sdk-analytic-events",DEV:"https://analytics.dev.data.primer.io/v1/sdk-analytic-events",STAGING:"https://analytics.staging.data.primer.io/v1/sdk-analytic-events",SANDBOX:"https://analytics.sandbox.data.primer.io/v1/sdk-analytic-events",PRODUCTION:"https://analytics.production.data.primer.io/v1/sdk-analytic-events"},Ii=class{sendEvent(t){let e=ma.getContext();if(!e)return;let r={...t,id:he(),timestamp:Math.floor(Date.now()/1e3),sdkType:"WEB",eventName:t.eventName,checkoutSessionId:e.checkoutSessionId,clientSessionId:e.clientSessionId,primerAccountId:e.primerAccountId,sdkVersion:e.sdkVersion,userAgent:e.userAgent,eventType:t.eventType,userLocale:t.userLocale,paymentMethod:t.paymentMethod,paymentId:t.paymentId,redirectDestinationUrl:t.redirectDestinationUrl,threedsProvider:t.threedsProvider,threedsResponse:t.threedsResponse};jc(r,e)}},$c=new Ii;function zc(a){let t={...a,userAgent:a.userAgent||(typeof navigator<"u"?navigator.userAgent:"")};ma.initialize(t)}function Le(a){$c.sendEvent(a)}async function jc(a,{environment:t,clientSessionToken:e}){if(t==="LOCAL")return void C.debug(`Analytics event ${a.eventName}:`,a);let r=Yc[t];return fetch(r,{method:"POST",headers:{"Content-Type":"application/json",...e&&{Authorization:`Bearer ${e}`}},body:JSON.stringify(a),keepalive:!0,priority:"low"}).catch(i=>{C.error("Failed to send analytics event:",i)})}var jt=(function(a){return a.CARD="CARD",a.NATIVE="NATIVE",a.REDIRECT="REDIRECT",a.KLARNA="KLARNA",a.ADYEN_KLARNA="ADYEN_KLARNA",a.ACH="ACH",a.MBWAY="MBWAY",a})({}),eo=Wi("../../node_modules/credit-card-type/dist/index.js");function Zi(a){return a.replace(/[-_]/g," ").replace(/[^\s\w]/g,"").replace(/([A-Z][a-z]+|[0-9]+)/g," $1").replace(/([A-Z]{2,})/g," $1").trim().split(/\s+/g)}function Wc(a){return Zi(a).filter(Boolean).map(t=>t[0].toUpperCase()+t.slice(1).toLowerCase()).join(" ")}function to(a){return Zi(a).join("-").toLowerCase()}function ro(a){return Zi(a).join("_").toUpperCase()}var wo=[["AMEX","american-express"],["CARTES_BANCAIRES"],["DANKORT"],["DINERS_CLUB","diners-club"],["DISCOVER","discover"],["ENROUTE"],["ELO","elo"],["EFTPOS"],["HIPER","hiper","hiper-pay"],["HIPERCARD","hipercard"],["INTERAC"],["JCB","jcb"],["MAESTRO","maestro"],["MASTERCARD","mastercard"],["MIR","mir","mir-pay"],["OTHER",void 0,"payment-card"],["UNIONPAY","unionpay"],["VISA","visa"]],ao=new Map(wo.map(a=>[a[0],a])),Zc=new Map(wo.filter(a=>a[1]).map(a=>[a[1],a]));function Zt(a){let{niceType:t,type:e}=(0,eo.getTypeInfo)(to(a))||(0,eo.getTypeInfo)(ao.get(ro(a))?.[1]||"")||{},[r,i,n]=Zc.get(e)||ao.get(ro(a))||[];return{asset:n||to(i||a),backend:r,display:t||Wc(a),library:i}}var B={WORLDPAY_IDEAL:"WORLDPAY_IDEAL",STRIPE_ACH:"STRIPE_ACH",STRIPE_IDEAL:"STRIPE_IDEAL",ADYEN_KLARNA:"ADYEN_KLARNA",ADYEN_BANCONTACT_CARD:"ADYEN_BANCONTACT_CARD",PAY_NL_KAARTDIRECT:"PAY_NL_KAARTDIRECT",ADYEN_EPS:"ADYEN_EPS",ADYEN_BANCONTACT_PAYCONIQ:"ADYEN_BANCONTACT_PAYCONIQ",OMISE_PROMPTPAY:"OMISE_PROMPTPAY",OMISE_TRUEMONEY:"OMISE_TRUEMONEY",ADYEN_MULTIBANCO:"ADYEN_MULTIBANCO",PACYPAY_WECHAT:"PACYPAY_WECHAT",PACYPAY_ALIPAY:"PACYPAY_ALIPAY",ADYEN_MBWAY:"ADYEN_MBWAY",XENDIT_DANA:"XENDIT_DANA",XENDIT_SHOPEEPAY:"XENDIT_SHOPEEPAY",ADYEN_PAYSHOP:"ADYEN_PAYSHOP",ADYEN_PAYTRAIL:"ADYEN_PAYTRAIL",CLEARPAY:"CLEARPAY",RAPYD_FAST:"RAPYD_FAST",RAPYD_PROMPTPAY:"RAPYD_PROMPTPAY",RAPYD_GCASH:"RAPYD_GCASH",RAPYD_POLI:"RAPYD_POLI",RAPYD_GRABPAY:"RAPYD_GRABPAY",PRIMER_PAYPAL:"PRIMER_PAYPAL",TWOC2P:"TWOC2P",NETS:"NETS",STRIPE_GIROPAY:"STRIPE_GIROPAY",MOLLIE_GIROPAY:"MOLLIE_GIROPAY",MOLLIE_EPS:"MOLLIE_EPS",PAY_NL_EPS:"PAY_NL_EPS",PAY_NL_P24:"PAY_NL_P24",MOLLIE_P24:"MOLLIE_P24",MOLLIE_SOFORT:"MOLLIE_SOFORT",COINBASE:"COINBASE",OPENNODE:"OPENNODE",MOLLIE_GIFT_CARD:"MOLLIE_GIFTCARD",XFERS_PAYNOW:"XFERS_PAYNOW",PAYMENT_CARD:"PAYMENT_CARD",APPLE_PAY:"APPLE_PAY",GOOGLE_PAY:"GOOGLE_PAY",PAYPAL:"PAYPAL",GO_CARDLESS:"GOCARDLESS",KLARNA:"KLARNA",PAY_NL_IDEAL:"PAY_NL_IDEAL",PAY_NL_SOFORT_BANKING:"PAY_NL_SOFORT_BANKING",PAY_NL_BANCONTACT:"PAY_NL_BANCONTACT",PAY_NL_PAYPAL:"PAY_NL_PAYPAL",PAY_NL_CREDIT_TRANSFER:"PAY_NL_CREDIT_TRANSFER",PAY_NL_DIRECT_DEBIT:"PAY_NL_DIRECT_DEBIT",PAY_NL_GIROPAY:"PAY_NL_GIROPAY",PAY_NL_PAYCONIQ:"PAY_NL_PAYCONIQ",PAY_NL_RIVERTY:"PAY_NL_RIVERTY",HOOLAH:"HOOLAH",ADYEN_BLIK:"ADYEN_BLIK",ADYEN_MOBILEPAY:"ADYEN_MOBILEPAY",ADYEN_VIPPS:"ADYEN_VIPPS",ADYEN_GIROPAY:"ADYEN_GIROPAY",ADYEN_SOFORT:"ADYEN_SOFORT",ADYEN_IDEAL:"ADYEN_IDEAL",ADYEN_TRUSTLY:"ADYEN_TRUSTLY",ADYEN_ALIPAY:"ADYEN_ALIPAY",ADYEN_TWINT:"ADYEN_TWINT",ADYEN_BANK_TRANSFER:"ADYEN_BANK_TRANSFER",ADYEN_CASHAPP:"ADYEN_CASHAPP",ADYEN_AFFIRM:"ADYEN_AFFIRM",MOLLIE_BANCONTACT:"MOLLIE_BANCONTACT",MOLLIE_IDEAL:"MOLLIE_IDEAL",BUCKAROO_GIROPAY:"BUCKAROO_GIROPAY",BUCKAROO_EPS:"BUCKAROO_EPS",BUCKAROO_SOFORT:"BUCKAROO_SOFORT",BUCKAROO_BANCONTACT:"BUCKAROO_BANCONTACT",BUCKAROO_IDEAL:"BUCKAROO_IDEAL",ATOME:"ATOME",DLOCAL_PIX:"DLOCAL_PIX",ALMA:"ALMA"},Jc={WORLDPAY_IDEAL:"WORLDPAY_IDEAL",AUTOMATED_CLEARING_HOUSE:"AUTOMATED_CLEARING_HOUSE",ADYEN_KLARNA:"ADYEN_KLARNA",ADYEN_BANCONTACT_CARD:"ADYEN_BANCONTACT_CARD",PAY_NL_KAARTDIRECT:"PAY_NL_KAARTDIRECT",ADYEN_EPS:"ADYEN_EPS",ADYEN_BANCONTACT_PAYCONIQ:"ADYEN_BANCONTACT_PAYCONIQ",OMISE_PROMPTPAY:"OMISE_PROMPTPAY",OMISE_TRUEMONEY:"OMISE_TRUEMONEY",ADYEN_MULTIBANCO:"ADYEN_MULTIBANCO",PACYPAY_WECHAT:"PACYPAY_WECHAT",PACYPAY_ALIPAY:"PACYPAY_ALIPAY",ADYEN_MBWAY:"ADYEN_MBWAY",XENDIT_DANA:"XENDIT_DANA",XENDIT_SHOPEEPAY:"XENDIT_SHOPEEPAY",ADYEN_PAYSHOP:"ADYEN_PAYSHOP",ADYEN_PAYTRAIL:"ADYEN_PAYTRAIL",CLEARPAY:"CLEARPAY",RAPYD_FAST:"RAPYD_FAST",RAPYD_PROMPTPAY:"RAPYD_PROMPTPAY",RAPYD_GCASH:"RAPYD_GCASH",RAPYD_POLI:"RAPYD_POLI",RAPYD_GRABPAY:"RAPYD_GRABPAY",PRIMER_PAYPAL:"PRIMER_PAYPAL",TWOC2P:"TWOC2P",NETS:"NETS",STRIPE_ACH:"STRIPE_ACH",STRIPE_GIROPAY:"STRIPE_GIROPAY",MOLLIE_GIROPAY:"MOLLIE_GIROPAY",MOLLIE_EPS:"MOLLIE_EPS",PAY_NL_EPS:"PAY_NL_EPS",PAY_NL_P24:"PAY_NL_P24",MOLLIE_P24:"MOLLIE_P24",MOLLIE_SOFORT:"MOLLIE_SOFORT",COINBASE:"COINBASE",OPENNODE:"OPENNODE",MOLLIE_GIFT_CARD:"MOLLIE_GIFTCARD",XFERS_PAYNOW:"XFERS_PAYNOW",CARD:"PAYMENT_CARD",APPLE_PAY:"APPLE_PAY",GOOGLE_PAY:"GOOGLE_PAY",PAYPAL:"PAYPAL_ORDER",PAYPAL_VAULTED:"PAYPAL_BILLING_AGREEMENT",GO_CARDLESS:"GOCARDLESS",PAY_NL_IDEAL:"PAY_NL_IDEAL",PAY_NL_SOFORT_BANKING:"PAY_NL_SOFORT_BANKING",PAY_NL_BANCONTACT:"PAY_NL_BANCONTACT",PAY_NL_PAYPAL:"PAY_NL_PAYPAL",PAY_NL_CREDIT_TRANSFER:"PAY_NL_CREDIT_TRANSFER",PAY_NL_DIRECT_DEBIT:"PAY_NL_DIRECT_DEBIT",PAY_NL_GIROPAY:"PAY_NL_GIROPAY",PAY_NL_PAYCONIQ:"PAY_NL_PAYCONIQ",PAY_NL_RIVERTY:"PAY_NL_RIVERTY",HOOLAH:"HOOLAH",ADYEN_BLIK:"ADYEN_BLIK",ADYEN_VIPPS:"ADYEN_VIPPS",ADYEN_GIROPAY:"ADYEN_GIROPAY",ADYEN_SOFORT:"ADYEN_SOFORT",ADYEN_IDEAL:"ADYEN_IDEAL",ADYEN_TRUSTLY:"ADYEN_TRUSTLY",ADYEN_ALIPAY:"ADYEN_ALIPAY",ADYEN_TWINT:"ADYEN_TWINT",ADYEN_MOBILEPAY:"ADYEN_MOBILEPAY",MOLLIE_BANCONTACT:"MOLLIE_BANCONTACT",MOLLIE_IDEAL:"MOLLIE_IDEAL",BUCKAROO_GIROPAY:"BUCKAROO_GIROPAY",BUCKAROO_EPS:"BUCKAROO_EPS",BUCKAROO_SOFORT:"BUCKAROO_SOFORT",BUCKAROO_BANCONTACT:"BUCKAROO_BANCONTACT",BUCKAROO_IDEAL:"BUCKAROO_IDEAL",ATOME:"ATOME",KLARNA_CUSTOMER_TOKEN:"KLARNA_CUSTOMER_TOKEN",DLOCAL_PIX:"DLOCAL_PIX",ALMA:"ALMA",ADYEN_CASHAPP:"ADYEN_CASHAPP",ADYEN_AFFIRM:"ADYEN_AFFIRM"},xo="3.7.7",qc=xo,Qt=typeof Buffer=="function",io=typeof TextDecoder=="function"?new TextDecoder:void 0,no=typeof TextEncoder=="function"?new TextEncoder:void 0,Qc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",gr=Array.prototype.slice.call(Qc),Wr=(a=>{let t={};return a.forEach((e,r)=>t[e]=r),t})(gr),Xc=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,ee=String.fromCharCode.bind(String),oo=typeof Uint8Array.from=="function"?Uint8Array.from.bind(Uint8Array):a=>new Uint8Array(Array.prototype.slice.call(a,0)),_o=a=>a.replace(/=/g,"").replace(/[+\/]/g,t=>t=="+"?"-":"_"),Oo=a=>a.replace(/[^A-Za-z0-9\+\/]/g,""),Do=a=>{let t,e,r,i,n="",o=a.length%3;for(let s=0;s<a.length;){if((e=a.charCodeAt(s++))>255||(r=a.charCodeAt(s++))>255||(i=a.charCodeAt(s++))>255)throw new TypeError("invalid character found");t=e<<16|r<<8|i,n+=gr[t>>18&63]+gr[t>>12&63]+gr[t>>6&63]+gr[63&t]}return o?n.slice(0,o-3)+"===".substring(o):n},Ji=typeof btoa=="function"?a=>btoa(a):Qt?a=>Buffer.from(a,"binary").toString("base64"):Do,ki=Qt?a=>Buffer.from(a).toString("base64"):a=>{let e=[];for(let r=0,i=a.length;r<i;r+=4096)e.push(ee.apply(null,a.subarray(r,r+4096)));return Ji(e.join(""))},ea=(a,t=!1)=>t?_o(ki(a)):ki(a),eu=a=>{if(a.length<2){var t=a.charCodeAt(0);return t<128?a:t<2048?ee(192|t>>>6)+ee(128|63&t):ee(224|t>>>12&15)+ee(128|t>>>6&63)+ee(128|63&t)}var t=65536+(a.charCodeAt(0)-55296)*1024+(a.charCodeAt(1)-56320);return ee(240|t>>>18&7)+ee(128|t>>>12&63)+ee(128|t>>>6&63)+ee(128|63&t)},tu=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,Bo=a=>a.replace(tu,eu),so=Qt?a=>Buffer.from(a,"utf8").toString("base64"):no?a=>ki(no.encode(a)):a=>Ji(Bo(a)),Wt=(a,t=!1)=>t?_o(so(a)):so(a),lo=a=>Wt(a,!0),ru=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,au=a=>{switch(a.length){case 4:var t=(7&a.charCodeAt(0))<<18|(63&a.charCodeAt(1))<<12|(63&a.charCodeAt(2))<<6|63&a.charCodeAt(3),e=t-65536;return ee((e>>>10)+55296)+ee((1023&e)+56320);case 3:return ee((15&a.charCodeAt(0))<<12|(63&a.charCodeAt(1))<<6|63&a.charCodeAt(2));default:return ee((31&a.charCodeAt(0))<<6|63&a.charCodeAt(1))}},Go=a=>a.replace(ru,au),Ko=a=>{if(a=a.replace(/\s+/g,""),!Xc.test(a))throw new TypeError("malformed base64.");a+="==".slice(2-(3&a.length));let t,e="",r,i;for(let n=0;n<a.length;)t=Wr[a.charAt(n++)]<<18|Wr[a.charAt(n++)]<<12|(r=Wr[a.charAt(n++)])<<6|(i=Wr[a.charAt(n++)]),e+=r===64?ee(t>>16&255):i===64?ee(t>>16&255,t>>8&255):ee(t>>16&255,t>>8&255,255&t);return e},qi=typeof atob=="function"?a=>atob(Oo(a)):Qt?a=>Buffer.from(a,"base64").toString("binary"):Ko,Fo=Qt?a=>oo(Buffer.from(a,"base64")):a=>oo(qi(a).split("").map(t=>t.charCodeAt(0))),Uo=a=>Fo(Vo(a)),iu=Qt?a=>Buffer.from(a,"base64").toString("utf8"):io?a=>io.decode(Fo(a)):a=>Go(qi(a)),Vo=a=>Oo(a.replace(/[-_]/g,t=>t=="-"?"+":"/")),Li=a=>iu(Vo(a)),nu=a=>{if(typeof a!="string")return!1;let t=a.replace(/\s+/g,"").replace(/={0,2}$/,"");return!/[^\s0-9a-zA-Z\+/]/.test(t)||!/[^\s0-9a-zA-Z\-_]/.test(t)},Ho=a=>({value:a,enumerable:!1,writable:!0,configurable:!0}),Yo=function(){let a=(t,e)=>Object.defineProperty(String.prototype,t,Ho(e));a("fromBase64",function(){return Li(this)}),a("toBase64",function(t){return Wt(this,t)}),a("toBase64URI",function(){return Wt(this,!0)}),a("toBase64URL",function(){return Wt(this,!0)}),a("toUint8Array",function(){return Uo(this)})},$o=function(){let a=(t,e)=>Object.defineProperty(Uint8Array.prototype,t,Ho(e));a("toBase64",function(t){return ea(this,t)}),a("toBase64URI",function(){return ea(this,!0)}),a("toBase64URL",function(){return ea(this,!0)})},ou=()=>{Yo(),$o()},zo={version:xo,VERSION:qc,atob:qi,atobPolyfill:Ko,btoa:Ji,btoaPolyfill:Do,fromBase64:Li,toBase64:Wt,encode:Wt,encodeURI:lo,encodeURL:lo,utob:Bo,btou:Go,decode:Li,isValid:nu,fromUint8Array:ea,toUint8Array:Uo,extendString:Yo,extendUint8Array:$o,extendBuiltins:ou},Cr={encode:su,decode:zo.decode};function su(a,t={}){let{urlSafe:e=!1}=t;return zo.encode(a,e)}function jo(a,t){return!(a.intent!==`${t}_REDIRECTION`||!("statusUrl"in a)||!("redirectUrl"in a)||!a.redirectUrl||!a.statusUrl)}function ht(a){let t=cu(a),e=1e3*t.exp;if(Date.now()>e)throw new Error(`${lu}. Expiration date: ${new Date(e).toISOString()}`);return t}var Wo="The provided `clientToken`",lu=`${Wo} has expired`,du=`${Wo} is malformed`;function cu(a){try{let[t,e]=a.split("."),r=e||t;return JSON.parse(Cr.decode(r))}catch{throw new Error(du)}}var ta=class{constructor(t){S(this,"context");this.context=t}},ra=navigator.userAgent||navigator.vendor||window.opera||"";function Rt(){return{javaEnabled:typeof window.navigator.javaEnabled=="function"?window.navigator.javaEnabled():!1,language:window.navigator.language,colorDepth:window.screen.colorDepth,screenHeight:window.screen.height,screenWidth:window.screen.width,timezoneOffset:new Date().getTimezoneOffset(),userAgent:ra}}var Ar=()=>/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(ra)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw-(n|u)|c55\/|capi|ccwa|cdm-|cell|chtm|cldc|cmd-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc-s|devi|dica|dmob|do(c|p)o|ds(12|-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(-|_)|g1 u|g560|gene|gf-5|g-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd-(m|p|t)|hei-|hi(pt|ta)|hp( i|ip)|hs-c|ht(c(-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i-(20|go|ma)|i230|iac( |-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|-[a-w])|libw|lynx|m1-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|-([1-8]|c))|phil|pire|pl(ay|uc)|pn-2|po(ck|rt|se)|prox|psio|pt-g|qa-a|qc(07|12|21|32|60|-[2-7]|i-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h-|oo|p-)|sdk\/|se(c(-|0|1)|47|mc|nd|ri)|sgh-|shar|sie(-|m)|sk-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h-|v-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl-|tdg-|tel(i|m)|tim-|t-mo|to(pl|sh)|ts(70|m-|m3|m5)|tx-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas-|your|zeto|zte-/i.test(ra.slice(0,4)),Qi=()=>/(WebView|(iPhone|iPod|iPad)(?!.*Safari\/)|Android.*(wv))/gi.test(ra),Ri=class extends ta{async handleRequiredAction(t){let e=t.requiredAction?.clientToken;if(!e)throw new Error("No client token provided");let r=ht(e);if(!("intent"in r)||r.intent!=="3DS_AUTHENTICATION")throw new Error("Invalid client token");let{error:i,data:n}=await this.context.pciApi.post3dsAuth(r.tokenId,{device:Rt()});if(i||!n||!n.authentication)throw i??new Error("Unable to authenticate");let o=n.authentication,s=n;o.responseCode==="METHOD"&&(s=await this.handleMethod(r.tokenId,o),o=s.authentication),o.responseCode==="CHALLENGE"&&(s=await this.handleChallenge(r.tokenId,o));let l=await this.context.pciApi.postResumePayment(t.id,s.resumeToken);if(l.error||!l.data)throw l.error??new Error("Unable to resume payment");return l.data}async handleMethod(t,e){let r="primer-3ds-method-box",i="primer-3ds-method-iframe",n="primer-3ds-method-form",o="threeDSMethodData",s=document.createElement("div");s.id=r,s.style.position="absolute",s.style.width="2px",s.style.height="2px",s.style.left="-10000px";let l=document.createElement("iframe");l.style.display="none",l.id=i,l.name=i,s.appendChild(l);let c=document.createElement("form"),p=document.createElement("input");p.type="hidden",p.id=o,p.name=o,p.value=Cr.encode(JSON.stringify({threeDSServerTransID:e.transactionId,threeDSMethodNotificationURL:e.notificationUrl}),{urlSafe:!0}).replace(/=+$/g,""),c.appendChild(p),c.id=n,c.name=n,c.action=e.acsMethodUrl,c.target=i,c.method="post",s.appendChild(c),document.body.appendChild(s),c.submit();let{data:m,error:g}=await this.context.pciApi.poll3dsAuth(e.statusUrl,{timeout:13e3,isComplete:A=>!!A.error||A.data?.authentication.responseCode!=="METHOD"});return s.remove(),g||!m?this.continueAuth(t):m}async continueAuth(t){let{data:e,error:r}=await this.context.pciApi.post3dsContinue(t);return r||!e?{resumeToken:he(),authentication:{responseCode:"SKIPPED",skippedReasonCode:"NEGOTIATION_ERROR",skippedReasonText:"Failed to negotiate with 3DS server"}}:e}async handleChallenge(t,e){let{container:r,formId:i}=this.createChallengeElements(e),n=()=>{let l=document.getElementById(i);l?l.submit():requestAnimationFrame(()=>{let c=document.getElementById(i);c&&c.submit()})},o=new AbortController,s=this.context.pciApi.poll3dsAuth(e.statusUrl,{signal:o.signal,interval:2500,timeout:66e4,isComplete:l=>!!l.error||l.data?.authentication.responseCode!=="CHALLENGE"});try{let l=this.context.dialogProvider.show({htmlContent:r,onContentReady:n});Le({eventName:"PAYMENT_THREEDS",threedsResponse:JSON.stringify(e)});let c=await Promise.race([s,l.then(()=>null,p=>{throw o.abort(),p})]);return c&&c.data?(this.context.dialogProvider.close(),c.data):(this.context.dialogProvider.close(),this.continueAuth(t))}catch{return o.abort(),this.continueAuth(t)}}createChallengeElements(t){let e=`3ds-challenge-iframe-${he()}`,r=`3ds-challenge-form-${he()}`,i=/^1/.test(t.protocolVersion),n=document.createElement("div");n.className="challenge-container",n.setAttribute("style",`
|
|
2
2
|
margin-top: 24px;
|
|
3
3
|
width: 100%;
|
|
4
4
|
height: 100%;
|
|
@@ -28,12 +28,12 @@ import{a as jr,b as q,c as bi,d,e as S}from"./chunks/chunk.QNO3CTH5.js";var nc=q
|
|
|
28
28
|
border: none;
|
|
29
29
|
background-color: #ffffff;
|
|
30
30
|
flex: 1;
|
|
31
|
-
`),e.appendChild(i),{container:e,setIframeSrc:()=>{i.src=t}}}},uu={CONTAINER_NOT_FOUND:"CONTAINER_NOT_FOUND"},wt={MISSING_PARAMETER:"MISSING_PARAMETER",INVALID_PARAMETER:"INVALID_PARAMETER",INVALID_USAGE:"INVALID_USAGE"},J={UNAUTHORIZED:"UNAUTHORIZED",FORBIDDEN:"FORBIDDEN",NOT_FOUND:"NOT_FOUND",CONFLICT:"CONFLICT",REQUEST_TIMEOUT:"REQUEST_TIMEOUT",VALIDATION_ERROR:"REQUEST_VALIDATION_ERROR",SERVER_ERROR:"SERVER_ERROR",BAD_REQUEST:"BAD_REQUEST",REQUEST_ERROR:"REQUEST_ERROR",POLLING_ABORTED:"POLLING_ABORTED",UNEXPECTED:"UNEXPECTED"},O={PAYMENT_CREATION_ABORTED:"PAYMENT_CREATION_ABORTED",PAYMENT_FAILED:"PAYMENT_FAILED",RESUME_FAILED:"RESUME_FAILED",TOKENIZATION_ERROR:"TOKENIZATION_ERROR",IDEMPOTENCY_KEY_ALREADY_EXISTS:"IDEMPOTENCY_KEY_ALREADY_EXISTS"},aa={MISSING_CLIENT_TOKEN:"MISSING_CLIENT_TOKEN",INVALID_CLIENT_TOKEN:"INVALID_CLIENT_TOKEN"},Zr={VAULT_ERROR:"VAULT_ERROR",TOKENIZATION_ERROR:"TOKENIZATION_ERROR"},ha=(function(a){return a.REQUEST_ERROR="RequestError",a.TOKENIZATION_ERROR="TokenizationError",a.CLIENT_ERROR="ClientError",a.REQUEST_VALIDATION_ERROR="RequestValidationError",a.CONFIGURATION_ERROR="ConfigurationError",a.PCI_ERROR="PciError",a})({}),Jt=class a extends Error{constructor(e,r,i,n){super(r);S(this,"code");S(this,"error");this.name=e,this.code=i,this.error=n}toJSON(){return{name:this.name,message:this.message,code:this.code,stack:this.stack,...this.error?{error:JSON.parse(JSON.stringify(this.error,this.error instanceof a?void 0:Object.getOwnPropertyNames(this.error)))}:void 0}}},le=class extends Jt{constructor({message:e,error:r,response:i,code:n=J.REQUEST_ERROR}){super(ha.REQUEST_ERROR,e,n,r);S(this,"response");this.response=i}toJSON(){return{name:this.name,message:this.message,response:this.response,code:this.code,stack:this.stack}}},xi=class extends Jt{constructor({message:e,error:r,code:i=J.UNEXPECTED,suggestion:n}){super(ha.CONFIGURATION_ERROR,e,i,r);S(this,"suggestion");this.suggestion=n}toJSON(){return{name:this.name,message:this.message,suggestion:this.suggestion,code:this.code,stack:this.stack}}},F=class extends Jt{constructor({message:e,error:r,code:i=J.UNEXPECTED,suggestion:n,paymentMethod:o}){super(ha.TOKENIZATION_ERROR,e,i,r);S(this,"suggestion");S(this,"paymentMethod");this.suggestion=n,this.paymentMethod=o}toJSON(){return{name:this.name,message:this.message,code:this.code,paymentMethod:this.paymentMethod,suggestion:this.suggestion,stack:this.stack}}},R=class extends Jt{constructor({message:e,error:r,code:i=J.UNEXPECTED,suggestion:n,paymentMethod:o}){super(ha.CLIENT_ERROR,e,i,r);S(this,"suggestion");S(this,"paymentMethod");this.suggestion=n,this.paymentMethod=o}toJSON(){return{name:this.name,message:this.message,code:this.code,paymentMethod:this.paymentMethod,suggestion:this.suggestion,stack:this.stack}}},Ee=class{constructor(t,e){S(this,"config");S(this,"context");S(this,"callbacks",{onStart:()=>Promise.resolve({action:"continue"}),onFinish:()=>{}});S(this,"idempotencyKey",null);this.config=Object.freeze(t),this.context=e}setCallbacks(t){this.callbacks=t}setIdempotencyKey(t){this.idempotencyKey=t}async tokenizeVaulted(t){let{error:e,data:r}=await this.context.pciApi.postPaymentInstrumentsExchange(t);if(e||!r)throw e??new R({code:O.TOKENIZATION_ERROR,message:"Unable to tokenize vaulted payment method",paymentMethod:this.config.type});return r}async setup(){return!0}async start(){C.debug(`Start not implemented for ${this.config.type}`)}async render(t,e){C.warn(`Render not implemented for ${this.config.type}`)}async handleRequiredAction(t){return t.requiredAction?.name==="3DS_AUTHENTICATION"?new Ri(this.context).handleRequiredAction(t):t.requiredAction?.name==="PROCESSOR_3DS"?new wi(this.context).handleRequiredAction(t):t}async createPayment(t){let{error:e,data:r}=await this.context.pciApi.postCreatePayment(t.token,this.idempotencyKey);if(e||!r)throw e??new R({code:O.PAYMENT_FAILED,message:"Unable to create payment"});return r.requiredAction?.clientToken&&this.context.updateClientToken(r.requiredAction.clientToken),r}async resumePayment(t,e){let{error:r,data:i}=await this.context.pciApi.postResumePayment(t,e);if(r||!i)throw r??new R({code:O.RESUME_FAILED,message:"Unable to resume payment"});return i}};function Xi(a,t={}){return new Promise((e,r)=>{if(document.querySelector(`script[src="${a}"]`))return void e();let i=document.createElement("script");i.src=a,Object.entries(t).forEach(([n,o])=>{i.setAttribute(n,o)}),i.onload=()=>{e()},i.onerror=()=>{r(new Error(`Failed to load script: ${a}`))},document.head.appendChild(i)})}var co=5,pu="https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js",mu=["supports3DS"],fr={SHIPPING:"shipping",SHIPPING_ADDRESS_UNSUPPORTED:"shipping_address_unsupported_error",UNKNOWN_ERROR:"something_went_wrong_error",MISSING_FIRST_OR_LAST_NAME:"applePayMissingFirstNameOrLastName",FAILED_TO_TOKENIZE:"applePayFailedToTokenize"},vr={SHIPPING:"Shipping",SHIPPING_ADDRESS_UNSUPPORTED:"We do not ship to this address",UNKNOWN_ERROR:"Something went wrong. Please try again.",MISSING_FIRST_OR_LAST_NAME:"Missing first name or last name",FAILED_TO_TOKENIZE:"Failed to tokenize"};function hu(a){return a&&a.includes("_")?a.split("_").join("-"):a}var gu=JSON.parse('{"USD":{"b":2},"CAD":{"b":2},"EUR":{"b":2},"AED":{"b":2},"AFN":{"b":0},"ALL":{"b":0},"AMD":{"b":0},"ARS":{"b":2},"AUD":{"b":2},"AZN":{"b":2},"BAM":{"b":2},"BDT":{"b":2},"BGN":{"b":2},"BHD":{"b":3},"BIF":{"b":0},"BND":{"b":2},"BOB":{"b":2},"BRL":{"b":2},"BWP":{"b":2},"BYN":{"b":2},"BZD":{"b":2},"CDF":{"b":2},"CHF":{"b":2},"CLP":{"b":0},"CNY":{"b":2},"COP":{"b":2},"CRC":{"b":2},"CVE":{"b":2},"CZK":{"b":2},"DJF":{"b":0},"DKK":{"b":2},"DOP":{"b":2},"DZD":{"b":2},"EEK":{"b":2},"EGP":{"b":2},"ERN":{"b":2},"ETB":{"b":2},"GBP":{"b":2},"GEL":{"b":2},"GHS":{"b":2},"GNF":{"b":0},"GTQ":{"b":2},"HKD":{"b":2},"HNL":{"b":2},"HRK":{"b":2},"HUF":{"b":2},"IDR":{"b":2},"ILS":{"b":2},"INR":{"b":2},"IQD":{"b":0},"IRR":{"b":0},"ISK":{"b":0},"JMD":{"b":2},"JOD":{"b":3},"JPY":{"b":0},"KES":{"b":2},"KHR":{"b":2},"KMF":{"b":0},"KRW":{"b":0},"KWD":{"b":3},"KZT":{"b":2},"LBP":{"b":0},"LKR":{"b":2},"LTL":{"b":2},"LVL":{"b":2},"LYD":{"b":3},"MAD":{"b":2},"MDL":{"b":2},"MGA":{"b":0},"MKD":{"b":2},"MMK":{"b":0},"MOP":{"b":2},"MUR":{"b":0},"MXN":{"b":2},"MYR":{"b":2},"MZN":{"b":2},"NAD":{"b":2},"NGN":{"b":2},"NIO":{"b":2},"NOK":{"b":2},"NPR":{"b":2},"NZD":{"b":2},"OMR":{"b":3},"PAB":{"b":2},"PEN":{"b":2},"PHP":{"b":2},"PKR":{"b":0},"PLN":{"b":2},"PYG":{"b":0},"QAR":{"b":2},"RON":{"b":2},"RSD":{"b":2},"RUB":{"b":2},"RWF":{"b":0},"SAR":{"b":2},"SDG":{"b":2},"SEK":{"b":2},"SGD":{"b":2},"SOS":{"b":0},"SYP":{"b":0},"THB":{"b":2},"TND":{"b":3},"TOP":{"b":2},"TRY":{"b":2},"TTD":{"b":2},"TWD":{"b":2},"TZS":{"b":0},"UAH":{"b":2},"UGX":{"b":0},"UYU":{"b":2},"UZS":{"b":0},"VEF":{"b":2},"VND":{"b":0},"XAF":{"b":0},"XOF":{"b":0},"YER":{"b":0},"ZAR":{"b":2},"ZMK":{"b":0},"ZWL":{"b":0}}'),yu=2,fu=gu;function vu(a){if(!a)return null;let t=fu[a];return t?{decimalDigits:t.b}:null}function Zo(a,t,e){let r=hu(a),i=vu(e)?.decimalDigits??yu;function n(o){return new Intl.NumberFormat(r,{style:"currency",currency:e,currencyDisplay:o}).format(t/10**i)}try{return n("narrowSymbol")}catch{return n("symbol")}}function Me(a,t){return Zo("en",a,t).replace(/[^0-9.]/g,"").replace(/(\..*)\./g,"$1")}function bu(a,t){let e=10**t,r=a*e;return Math.abs(r-Math.round(r))<1e-9?a:Math.ceil((a+Number.EPSILON)*e)/e}function hr(a,t){let e=Number(Me(a,t));return bu(e,2).toFixed(2)}var uo={AMEX:"amex",CARTES_BANCAIRES:"cartesBancaires",DANKORT:"dankort",DISCOVER:"discover",ELO:"elo",EFTPOS:"eftpos",INTERAC:"interac",JCB:"jcb",MAESTRO:"maestro",MASTERCARD:"masterCard",MIR:"mir",OTHER:"privateLabel",UNIONPAY:"chinaUnionPay",VISA:"visa"};function Cu(a){return a?a.map(Zt).map(t=>uo[t.backend]).filter(Boolean):Object.values(uo)}function Su(a,t){return t.map(e=>({label:e.name,detail:e.description,amount:Me(e.amount,a),identifier:e.id}))}function Jo(a,t,e){let{paymentDescription:r,billingAgreement:i,managementUrl:n,regularBilling:o}=a,s={paymentDescription:r,billingAgreement:i,managementURL:n,regularBilling:{label:o.label,amount:o.amount?Me(o.amount,t):e,paymentTiming:"recurring",recurringPaymentIntervalUnit:o.recurringIntervalUnit||"month",recurringPaymentIntervalCount:o.recurringIntervalCount,recurringPaymentStartDate:new Date(1e3*o.recurringStartDate)}};return a.regularBilling.recurringEndDate&&(s.regularBilling.recurringPaymentEndDate=new Date(1e3*a.regularBilling.recurringEndDate)),a.trialBilling&&(s.trialBilling={label:a.trialBilling.label,amount:a.trialBilling.amount?Me(a.trialBilling.amount,t):"0.00",paymentTiming:"recurring"},a.trialBilling.recurringEndDate&&(s.trialBilling.recurringPaymentEndDate=new Date(1e3*a.trialBilling.recurringEndDate))),s}function Au(a,t,e){let{paymentDescription:r,billingAgreement:i,managementUrl:n,freeCancellationDate:o,freeCancellationTimeZone:s,deferredBilling:l}=a,c={paymentDescription:r,billingAgreement:i,managementURL:n||"",deferredBilling:{label:l.label,amount:l.amount?Me(l.amount,t):e,paymentTiming:"deferred",type:"final",deferredPaymentDate:new Date(1e3*l.deferredPaymentDate)}};return o&&s?{...c,freeCancellationDate:new Date(1e3*o),freeCancellationDateTimeZone:s}:c}function qo(a,t,e){let{paymentDescription:r,billingAgreement:i,managementUrl:n,automaticReloadBilling:o}=a;return{paymentDescription:r,billingAgreement:i,managementURL:n,automaticReloadBilling:{label:o.label,amount:o.amount?Me(o.amount,t):e,paymentTiming:"automaticReload",automaticReloadPaymentThresholdAmount:Me(o.automaticReloadThresholdAmount,t)}}}function Eu(a){return!!(a&&a.firstName&&a.lastName&&a.addressLine1&&a.city&&a.state&&a.countryCode&&a.postalCode)}function Si(a){if(!a)return;let[t,e]=a?.addressLines??[];return{firstName:a.givenName||null,lastName:a.familyName||null,addressLine1:t||null,addressLine2:e||null,city:a.locality||null,postalCode:a.postalCode||null,countryCode:a.countryCode?.toUpperCase()||null,state:a.administrativeArea||null}}function Mu(a){return{phoneNumber:"",emailAddress:"",givenName:"",familyName:"",phoneticGivenName:"",phoneticFamilyName:"",addressLines:[a?.addressLine1||"",a?.addressLine2||""],subLocality:"",locality:"",postalCode:a?.postalCode||"",subAdministrativeArea:"",administrativeArea:a?.city||"",country:"",countryCode:a?.state||""}}function Qo(a,t){let{lineItems:e,fees:r}=t.configuration.clientSession.order,i=[];return e?.forEach(n=>{i.push({label:n.description??n.name??t.translate("item_label_fallback","Item"),amount:Me(n.amount,a)})}),r?.forEach(n=>{i.push({label:n.type??t.translate("fee_label_fallback","Fee"),amount:Me(n.amount,a)})}),i}function Ai(a,t){let{merchantAmount:e,totalOrderAmount:r,currencyCode:i,shipping:n}=a.configuration.clientSession.order;if(!i)throw new Error("Currency code is required");let o=Me(e??r,i),s=[],l=Qo(i,a),c=[];if(t.options.recurringPaymentRequest){let{regularBilling:m,trialBilling:g}=Jo(t.options.recurringPaymentRequest,i,o);m&&l.push(m),g&&l.push(g)}else if(t.options.automaticReloadRequest){let{automaticReloadBilling:m}=qo(t.options.automaticReloadRequest,i,o);m&&l.push(m)}let p=a.configuration.checkoutModules?.find(m=>m.type==="SHIPPING")?.options;if(a.clientOptions?.applePay?.shippingOptions&&p){let m=Su(i,p.shippingMethods);m.length||s.push(new ApplePayError("addressUnserviceable","postalAddress",a.translate(fr.SHIPPING_ADDRESS_UNSUPPORTED,vr.SHIPPING_ADDRESS_UNSUPPORTED))),a.clientOptions.applePay.shippingOptions.requireShippingMethod&&(c=m,p.selectedShippingMethod&&c.sort(g=>g.identifier===p.selectedShippingMethod?-1:0)),n?.amount&&l.push({label:a.translate(fr.SHIPPING,vr.SHIPPING),amount:Me(n.amount,i)})}return{newTotal:{label:t.options.merchantName,amount:o,type:"final"},errors:s,newLineItems:l,newShippingMethods:c}}function Pu(a,t){let{countryCode:e,currencyCode:r,merchantAmount:i,totalOrderAmount:n}=a.configuration.clientSession.order;if(!e||!r)throw new Error("Country code and currency code are required");let o=Cu(a.configuration.clientSession.paymentMethod?.orderedAllowedCardNetworks),s=Me(i??n,r),l=a.clientOptions?.applePay?.billingOptions?.requiredBillingContactFields,c=a.clientOptions?.applePay?.shippingOptions?.requiredShippingContactFields,p={countryCode:e,currencyCode:r,merchantCapabilities:mu,supportedNetworks:o,total:{amount:s,label:t.options.merchantName,type:"pending"},requiredBillingContactFields:l,requiredShippingContactFields:c,lineItems:Qo(r,a)};return l?.includes("postalAddress")&&Eu(a.configuration.clientSession?.customer?.billingAddress)&&(p.billingContact=Mu(a.configuration.clientSession?.customer?.billingAddress)),t.options.recurringPaymentRequest&&(p.recurringPaymentRequest=Jo(t.options.recurringPaymentRequest,p.currencyCode,p.total.amount)),t.options.deferredPaymentRequest&&(p.deferredPaymentRequest=Au(t.options.deferredPaymentRequest,p.currencyCode,p.total.amount)),t.options.automaticReloadRequest&&(p.automaticReloadPaymentRequest=qo(t.options.automaticReloadRequest,p.currencyCode,p.total.amount)),p}var Tu=(a,t)=>{a&&(t?(a.setAttribute("disabled","true"),a.setAttribute("tabindex","-1"),a.style.pointerEvents="none"):(a.removeAttribute("disabled"),a.setAttribute("tabindex","0"),a.style.pointerEvents="all"))},ia=class extends Ee{constructor(){super(...arguments);S(this,"applePaySession",null);S(this,"onStartPromise",Promise.resolve({action:"continue"}));S(this,"container",null);S(this,"disabled",!1)}async setDisabled(e){this.disabled=e,Tu(this.container,e)}get clientOptions(){return this.context.clientOptions.applePay}async tokenize(){throw new F({message:"Apple Pay does not support direct tokenization",code:O.TOKENIZATION_ERROR,paymentMethod:B.APPLE_PAY})}async setup(){try{if(await Xi(pu,{crossorigin:""}),!("ApplePaySession"in window))return C.warn("Apple Pay is not available in this browser context"),!1;if(!ApplePaySession.supportsVersion(co))return C.warn("Apple Pay version not supported by this device"),!1;if(!ApplePaySession.canMakePayments())return C.warn("This device cannot make Apple Pay payments"),!1;if(!this.isMerchantDomainValid())return!1}catch(e){return C.errorWithDatadog("Failed to initialize Apple Pay",{error:e}),!1}return!0}isMerchantDomainValid(){if(this.context.clientOptions?.merchantDomain)return!0;let e=window.location.hostname;if(!(this.config.options.merchantDomains||[]).includes(e)){let i=new xi({message:`Apple Pay has not been configured for domain "${e}"`,code:wt.INVALID_USAGE,suggestion:"Add the current domain to Apple Pay merchantDomains configuration or provide merchantDomain in clientOptions"});return C.warn(`Apple Pay has not been configured for domain "${e}"`,i),!1}return!0}async render(e,{style:{buttonHeight:r}}={style:{buttonHeight:"44px"}}){this.container=e;let i=document.createElement("style");i.textContent=`
|
|
31
|
+
`),e.appendChild(i),{container:e,setIframeSrc:()=>{i.src=t}}}},uu={CONTAINER_NOT_FOUND:"CONTAINER_NOT_FOUND"},wt={MISSING_PARAMETER:"MISSING_PARAMETER",INVALID_PARAMETER:"INVALID_PARAMETER",INVALID_USAGE:"INVALID_USAGE"},J={UNAUTHORIZED:"UNAUTHORIZED",FORBIDDEN:"FORBIDDEN",NOT_FOUND:"NOT_FOUND",CONFLICT:"CONFLICT",REQUEST_TIMEOUT:"REQUEST_TIMEOUT",VALIDATION_ERROR:"REQUEST_VALIDATION_ERROR",SERVER_ERROR:"SERVER_ERROR",BAD_REQUEST:"BAD_REQUEST",REQUEST_ERROR:"REQUEST_ERROR",POLLING_ABORTED:"POLLING_ABORTED",UNEXPECTED:"UNEXPECTED"},x={PAYMENT_CREATION_ABORTED:"PAYMENT_CREATION_ABORTED",PAYMENT_FAILED:"PAYMENT_FAILED",RESUME_FAILED:"RESUME_FAILED",TOKENIZATION_ERROR:"TOKENIZATION_ERROR",IDEMPOTENCY_KEY_ALREADY_EXISTS:"IDEMPOTENCY_KEY_ALREADY_EXISTS"},aa={MISSING_CLIENT_TOKEN:"MISSING_CLIENT_TOKEN",INVALID_CLIENT_TOKEN:"INVALID_CLIENT_TOKEN"},Zr={VAULT_ERROR:"VAULT_ERROR",TOKENIZATION_ERROR:"TOKENIZATION_ERROR"},ha=(function(a){return a.REQUEST_ERROR="RequestError",a.TOKENIZATION_ERROR="TokenizationError",a.CLIENT_ERROR="ClientError",a.REQUEST_VALIDATION_ERROR="RequestValidationError",a.CONFIGURATION_ERROR="ConfigurationError",a.PCI_ERROR="PciError",a})({}),Jt=class a extends Error{constructor(e,r,i,n){super(r);S(this,"code");S(this,"error");this.name=e,this.code=i,this.error=n}toJSON(){return{name:this.name,message:this.message,code:this.code,stack:this.stack,...this.error?{error:JSON.parse(JSON.stringify(this.error,this.error instanceof a?void 0:Object.getOwnPropertyNames(this.error)))}:void 0}}},le=class extends Jt{constructor({message:e,error:r,response:i,code:n=J.REQUEST_ERROR}){super(ha.REQUEST_ERROR,e,n,r);S(this,"response");this.response=i}toJSON(){return{name:this.name,message:this.message,response:this.response,code:this.code,stack:this.stack}}},xi=class extends Jt{constructor({message:e,error:r,code:i=J.UNEXPECTED,suggestion:n}){super(ha.CONFIGURATION_ERROR,e,i,r);S(this,"suggestion");this.suggestion=n}toJSON(){return{name:this.name,message:this.message,suggestion:this.suggestion,code:this.code,stack:this.stack}}},F=class extends Jt{constructor({message:e,error:r,code:i=J.UNEXPECTED,suggestion:n,paymentMethod:o}){super(ha.TOKENIZATION_ERROR,e,i,r);S(this,"suggestion");S(this,"paymentMethod");this.suggestion=n,this.paymentMethod=o}toJSON(){return{name:this.name,message:this.message,code:this.code,paymentMethod:this.paymentMethod,suggestion:this.suggestion,stack:this.stack}}},R=class extends Jt{constructor({message:e,error:r,code:i=J.UNEXPECTED,suggestion:n,paymentMethod:o}){super(ha.CLIENT_ERROR,e,i,r);S(this,"suggestion");S(this,"paymentMethod");this.suggestion=n,this.paymentMethod=o}toJSON(){return{name:this.name,message:this.message,code:this.code,paymentMethod:this.paymentMethod,suggestion:this.suggestion,stack:this.stack}}},Ee=class{constructor(t,e){S(this,"config");S(this,"context");S(this,"callbacks",{onStart:()=>Promise.resolve({action:"continue"}),onFinish:()=>{}});S(this,"idempotencyKey",null);this.config=Object.freeze(t),this.context=e}setCallbacks(t){this.callbacks=t}setIdempotencyKey(t){this.idempotencyKey=t}async tokenizeVaulted(t){let{error:e,data:r}=await this.context.pciApi.postPaymentInstrumentsExchange(t);if(e||!r)throw e??new R({code:x.TOKENIZATION_ERROR,message:"Unable to tokenize vaulted payment method",paymentMethod:this.config.type});return r}async setup(){return!0}async start(){C.debug(`Start not implemented for ${this.config.type}`)}async render(t,e){C.warn(`Render not implemented for ${this.config.type}`)}async handleRequiredAction(t){return t.requiredAction?.name==="3DS_AUTHENTICATION"?new Ri(this.context).handleRequiredAction(t):t.requiredAction?.name==="PROCESSOR_3DS"?new wi(this.context).handleRequiredAction(t):t}async createPayment(t){let{error:e,data:r}=await this.context.pciApi.postCreatePayment(t.token,this.idempotencyKey);if(e||!r)throw e??new R({code:x.PAYMENT_FAILED,message:"Unable to create payment"});return r.requiredAction?.clientToken&&this.context.updateClientToken(r.requiredAction.clientToken),r}async resumePayment(t,e){let{error:r,data:i}=await this.context.pciApi.postResumePayment(t,e);if(r||!i)throw r??new R({code:x.RESUME_FAILED,message:"Unable to resume payment"});return i}};function Xi(a,t={}){return new Promise((e,r)=>{if(document.querySelector(`script[src="${a}"]`))return void e();let i=document.createElement("script");i.src=a,Object.entries(t).forEach(([n,o])=>{i.setAttribute(n,o)}),i.onload=()=>{e()},i.onerror=()=>{r(new Error(`Failed to load script: ${a}`))},document.head.appendChild(i)})}var co=5,pu="https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js",mu=["supports3DS"],fr={SHIPPING:"shipping",SHIPPING_ADDRESS_UNSUPPORTED:"shipping_address_unsupported_error",UNKNOWN_ERROR:"something_went_wrong_error",MISSING_FIRST_OR_LAST_NAME:"applePayMissingFirstNameOrLastName",FAILED_TO_TOKENIZE:"applePayFailedToTokenize"},vr={SHIPPING:"Shipping",SHIPPING_ADDRESS_UNSUPPORTED:"We do not ship to this address",UNKNOWN_ERROR:"Something went wrong. Please try again.",MISSING_FIRST_OR_LAST_NAME:"Missing first name or last name",FAILED_TO_TOKENIZE:"Failed to tokenize"};function hu(a){return a&&a.includes("_")?a.split("_").join("-"):a}var gu=JSON.parse('{"USD":{"b":2},"CAD":{"b":2},"EUR":{"b":2},"AED":{"b":2},"AFN":{"b":0},"ALL":{"b":0},"AMD":{"b":0},"ARS":{"b":2},"AUD":{"b":2},"AZN":{"b":2},"BAM":{"b":2},"BDT":{"b":2},"BGN":{"b":2},"BHD":{"b":3},"BIF":{"b":0},"BND":{"b":2},"BOB":{"b":2},"BRL":{"b":2},"BWP":{"b":2},"BYN":{"b":2},"BZD":{"b":2},"CDF":{"b":2},"CHF":{"b":2},"CLP":{"b":0},"CNY":{"b":2},"COP":{"b":2},"CRC":{"b":2},"CVE":{"b":2},"CZK":{"b":2},"DJF":{"b":0},"DKK":{"b":2},"DOP":{"b":2},"DZD":{"b":2},"EEK":{"b":2},"EGP":{"b":2},"ERN":{"b":2},"ETB":{"b":2},"GBP":{"b":2},"GEL":{"b":2},"GHS":{"b":2},"GNF":{"b":0},"GTQ":{"b":2},"HKD":{"b":2},"HNL":{"b":2},"HRK":{"b":2},"HUF":{"b":2},"IDR":{"b":2},"ILS":{"b":2},"INR":{"b":2},"IQD":{"b":0},"IRR":{"b":0},"ISK":{"b":0},"JMD":{"b":2},"JOD":{"b":3},"JPY":{"b":0},"KES":{"b":2},"KHR":{"b":2},"KMF":{"b":0},"KRW":{"b":0},"KWD":{"b":3},"KZT":{"b":2},"LBP":{"b":0},"LKR":{"b":2},"LTL":{"b":2},"LVL":{"b":2},"LYD":{"b":3},"MAD":{"b":2},"MDL":{"b":2},"MGA":{"b":0},"MKD":{"b":2},"MMK":{"b":0},"MOP":{"b":2},"MUR":{"b":0},"MXN":{"b":2},"MYR":{"b":2},"MZN":{"b":2},"NAD":{"b":2},"NGN":{"b":2},"NIO":{"b":2},"NOK":{"b":2},"NPR":{"b":2},"NZD":{"b":2},"OMR":{"b":3},"PAB":{"b":2},"PEN":{"b":2},"PHP":{"b":2},"PKR":{"b":0},"PLN":{"b":2},"PYG":{"b":0},"QAR":{"b":2},"RON":{"b":2},"RSD":{"b":2},"RUB":{"b":2},"RWF":{"b":0},"SAR":{"b":2},"SDG":{"b":2},"SEK":{"b":2},"SGD":{"b":2},"SOS":{"b":0},"SYP":{"b":0},"THB":{"b":2},"TND":{"b":3},"TOP":{"b":2},"TRY":{"b":2},"TTD":{"b":2},"TWD":{"b":2},"TZS":{"b":0},"UAH":{"b":2},"UGX":{"b":0},"UYU":{"b":2},"UZS":{"b":0},"VEF":{"b":2},"VND":{"b":0},"XAF":{"b":0},"XOF":{"b":0},"YER":{"b":0},"ZAR":{"b":2},"ZMK":{"b":0},"ZWL":{"b":0}}'),yu=2,fu=gu;function vu(a){if(!a)return null;let t=fu[a];return t?{decimalDigits:t.b}:null}function Zo(a,t,e){let r=hu(a),i=vu(e)?.decimalDigits??yu;function n(o){return new Intl.NumberFormat(r,{style:"currency",currency:e,currencyDisplay:o}).format(t/10**i)}try{return n("narrowSymbol")}catch{return n("symbol")}}function Me(a,t){return Zo("en",a,t).replace(/[^0-9.]/g,"").replace(/(\..*)\./g,"$1")}function bu(a,t){let e=10**t,r=a*e;return Math.abs(r-Math.round(r))<1e-9?a:Math.ceil((a+Number.EPSILON)*e)/e}function hr(a,t){let e=Number(Me(a,t));return bu(e,2).toFixed(2)}var uo={AMEX:"amex",CARTES_BANCAIRES:"cartesBancaires",DANKORT:"dankort",DISCOVER:"discover",ELO:"elo",EFTPOS:"eftpos",INTERAC:"interac",JCB:"jcb",MAESTRO:"maestro",MASTERCARD:"masterCard",MIR:"mir",OTHER:"privateLabel",UNIONPAY:"chinaUnionPay",VISA:"visa"};function Cu(a){return a?a.map(Zt).map(t=>uo[t.backend]).filter(Boolean):Object.values(uo)}function Su(a,t){return t.map(e=>({label:e.name,detail:e.description,amount:Me(e.amount,a),identifier:e.id}))}function Jo(a,t,e){let{paymentDescription:r,billingAgreement:i,managementUrl:n,regularBilling:o}=a,s={paymentDescription:r,billingAgreement:i,managementURL:n,regularBilling:{label:o.label,amount:o.amount?Me(o.amount,t):e,paymentTiming:"recurring",recurringPaymentIntervalUnit:o.recurringIntervalUnit||"month",recurringPaymentIntervalCount:o.recurringIntervalCount,recurringPaymentStartDate:new Date(1e3*o.recurringStartDate)}};return a.regularBilling.recurringEndDate&&(s.regularBilling.recurringPaymentEndDate=new Date(1e3*a.regularBilling.recurringEndDate)),a.trialBilling&&(s.trialBilling={label:a.trialBilling.label,amount:a.trialBilling.amount?Me(a.trialBilling.amount,t):"0.00",paymentTiming:"recurring"},a.trialBilling.recurringEndDate&&(s.trialBilling.recurringPaymentEndDate=new Date(1e3*a.trialBilling.recurringEndDate))),s}function Au(a,t,e){let{paymentDescription:r,billingAgreement:i,managementUrl:n,freeCancellationDate:o,freeCancellationTimeZone:s,deferredBilling:l}=a,c={paymentDescription:r,billingAgreement:i,managementURL:n||"",deferredBilling:{label:l.label,amount:l.amount?Me(l.amount,t):e,paymentTiming:"deferred",type:"final",deferredPaymentDate:new Date(1e3*l.deferredPaymentDate)}};return o&&s?{...c,freeCancellationDate:new Date(1e3*o),freeCancellationDateTimeZone:s}:c}function qo(a,t,e){let{paymentDescription:r,billingAgreement:i,managementUrl:n,automaticReloadBilling:o}=a;return{paymentDescription:r,billingAgreement:i,managementURL:n,automaticReloadBilling:{label:o.label,amount:o.amount?Me(o.amount,t):e,paymentTiming:"automaticReload",automaticReloadPaymentThresholdAmount:Me(o.automaticReloadThresholdAmount,t)}}}function Eu(a){return!!(a&&a.firstName&&a.lastName&&a.addressLine1&&a.city&&a.state&&a.countryCode&&a.postalCode)}function Si(a){if(!a)return;let[t,e]=a?.addressLines??[];return{firstName:a.givenName||null,lastName:a.familyName||null,addressLine1:t||null,addressLine2:e||null,city:a.locality||null,postalCode:a.postalCode||null,countryCode:a.countryCode?.toUpperCase()||null,state:a.administrativeArea||null}}function Mu(a){return{phoneNumber:"",emailAddress:"",givenName:"",familyName:"",phoneticGivenName:"",phoneticFamilyName:"",addressLines:[a?.addressLine1||"",a?.addressLine2||""],subLocality:"",locality:"",postalCode:a?.postalCode||"",subAdministrativeArea:"",administrativeArea:a?.city||"",country:"",countryCode:a?.state||""}}function Qo(a,t){let{lineItems:e,fees:r}=t.configuration.clientSession.order,i=[];return e?.forEach(n=>{i.push({label:n.description??n.name??t.translate("item_label_fallback","Item"),amount:Me(n.amount,a)})}),r?.forEach(n=>{i.push({label:n.type??t.translate("fee_label_fallback","Fee"),amount:Me(n.amount,a)})}),i}function Ai(a,t){let{merchantAmount:e,totalOrderAmount:r,currencyCode:i,shipping:n}=a.configuration.clientSession.order;if(!i)throw new Error("Currency code is required");let o=Me(e??r,i),s=[],l=Qo(i,a),c=[];if(t.options.recurringPaymentRequest){let{regularBilling:m,trialBilling:g}=Jo(t.options.recurringPaymentRequest,i,o);m&&l.push(m),g&&l.push(g)}else if(t.options.automaticReloadRequest){let{automaticReloadBilling:m}=qo(t.options.automaticReloadRequest,i,o);m&&l.push(m)}let p=a.configuration.checkoutModules?.find(m=>m.type==="SHIPPING")?.options;if(a.clientOptions?.applePay?.shippingOptions&&p){let m=Su(i,p.shippingMethods);m.length||s.push(new ApplePayError("addressUnserviceable","postalAddress",a.translate(fr.SHIPPING_ADDRESS_UNSUPPORTED,vr.SHIPPING_ADDRESS_UNSUPPORTED))),a.clientOptions.applePay.shippingOptions.requireShippingMethod&&(c=m,p.selectedShippingMethod&&c.sort(g=>g.identifier===p.selectedShippingMethod?-1:0)),n?.amount&&l.push({label:a.translate(fr.SHIPPING,vr.SHIPPING),amount:Me(n.amount,i)})}return{newTotal:{label:t.options.merchantName,amount:o,type:"final"},errors:s,newLineItems:l,newShippingMethods:c}}function Pu(a,t){let{countryCode:e,currencyCode:r,merchantAmount:i,totalOrderAmount:n}=a.configuration.clientSession.order;if(!e||!r)throw new Error("Country code and currency code are required");let o=Cu(a.configuration.clientSession.paymentMethod?.orderedAllowedCardNetworks),s=Me(i??n,r),l=a.clientOptions?.applePay?.billingOptions?.requiredBillingContactFields,c=a.clientOptions?.applePay?.shippingOptions?.requiredShippingContactFields,p={countryCode:e,currencyCode:r,merchantCapabilities:mu,supportedNetworks:o,total:{amount:s,label:t.options.merchantName,type:"pending"},requiredBillingContactFields:l,requiredShippingContactFields:c,lineItems:Qo(r,a)};return l?.includes("postalAddress")&&Eu(a.configuration.clientSession?.customer?.billingAddress)&&(p.billingContact=Mu(a.configuration.clientSession?.customer?.billingAddress)),t.options.recurringPaymentRequest&&(p.recurringPaymentRequest=Jo(t.options.recurringPaymentRequest,p.currencyCode,p.total.amount)),t.options.deferredPaymentRequest&&(p.deferredPaymentRequest=Au(t.options.deferredPaymentRequest,p.currencyCode,p.total.amount)),t.options.automaticReloadRequest&&(p.automaticReloadPaymentRequest=qo(t.options.automaticReloadRequest,p.currencyCode,p.total.amount)),p}var Tu=(a,t)=>{a&&(t?(a.setAttribute("disabled","true"),a.setAttribute("tabindex","-1"),a.style.pointerEvents="none"):(a.removeAttribute("disabled"),a.setAttribute("tabindex","0"),a.style.pointerEvents="all"))},ia=class extends Ee{constructor(){super(...arguments);S(this,"applePaySession",null);S(this,"onStartPromise",Promise.resolve({action:"continue"}));S(this,"container",null);S(this,"disabled",!1)}async setDisabled(e){this.disabled=e,Tu(this.container,e)}get clientOptions(){return this.context.clientOptions.applePay}async tokenize(){throw new F({message:"Apple Pay does not support direct tokenization",code:x.TOKENIZATION_ERROR,paymentMethod:B.APPLE_PAY})}async setup(){try{if(await Xi(pu,{crossorigin:""}),!("ApplePaySession"in window))return C.warn("Apple Pay is not available in this browser context"),!1;if(!ApplePaySession.supportsVersion(co))return C.warn("Apple Pay version not supported by this device"),!1;if(!ApplePaySession.canMakePayments())return C.warn("This device cannot make Apple Pay payments"),!1;if(!this.isMerchantDomainValid())return!1}catch(e){return C.errorWithDatadog("Failed to initialize Apple Pay",{error:e}),!1}return!0}isMerchantDomainValid(){if(this.context.clientOptions?.merchantDomain)return!0;let e=window.location.hostname;if(!(this.config.options.merchantDomains||[]).includes(e)){let i=new xi({message:`Apple Pay has not been configured for domain "${e}"`,code:wt.INVALID_USAGE,suggestion:"Add the current domain to Apple Pay merchantDomains configuration or provide merchantDomain in clientOptions"});return C.warn(`Apple Pay has not been configured for domain "${e}"`,i),!1}return!0}async render(e,{style:{buttonHeight:r}}={style:{buttonHeight:"44px"}}){this.container=e;let i=document.createElement("style");i.textContent=`
|
|
32
32
|
apple-pay-button {
|
|
33
33
|
--apple-pay-button-width: 100%;
|
|
34
34
|
--apple-pay-button-height: ${r}px;
|
|
35
35
|
}
|
|
36
|
-
`,e.appendChild(i);let n=document.createElement("apple-pay-button"),o=this.clientOptions?.buttonStyle??this.clientOptions?.buttonOptions?.buttonStyle;o&&n.setAttribute("buttonstyle",o);let s=this.clientOptions?.buttonType??this.clientOptions?.buttonOptions?.type??"plain";s&&n.setAttribute("type",s),n.setAttribute("locale",this.context.locale),n.addEventListener("click",this.handleClick.bind(this)),document.body.appendChild(n),setTimeout(()=>{e.appendChild(n)},0)}async handleClick(){if(!this.disabled)try{this.onStartPromise=this.callbacks.onStart(),Le({eventName:"PAYMENT_METHOD_SELECTION",paymentMethod:B.APPLE_PAY}),this.applePaySession=new ApplePaySession(co,Pu(this.context,this.config)),this.applePaySession.onvalidatemerchant=this.handleValidateMerchant.bind(this),this.applePaySession.onpaymentauthorized=this.handlePaymentAuthorized.bind(this),this.applePaySession.onpaymentmethodselected=this.handlePaymentMethodSelected.bind(this),this.applePaySession.onshippingcontactselected=this.handleShippingContactSelected.bind(this),this.applePaySession.onshippingmethodselected=this.handleShippingMethodSelected.bind(this),this.applePaySession.oncancel=this.handleCancel.bind(this),this.applePaySession.begin()}catch(e){C.errorWithDatadog("Error initiating Apple Pay session",{error:e})}}async handleValidateMerchant(e){if(this.applePaySession)try{let{action:r}=await this.onStartPromise;if(r==="abort")return void this.abort(new R({message:"Payment creation aborted",code:O.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type}));let{data:i,error:n}=await this.context.coreApi.createApplePaySession({validationUrl:e.validationURL,paymentMethodConfigId:this.config.id,merchantDomain:this.context.clientOptions.merchantDomain??window.location.hostname});if(!this.applePaySession)return;if(n||!i)throw n??new R({message:"Failed to validate merchant",code:J.REQUEST_ERROR,paymentMethod:B.APPLE_PAY});this.applePaySession.completeMerchantValidation(i)}catch(r){C.warn("Apple Pay merchant validation failed:",r),this.abort()}}async handlePaymentMethodSelected(e){if(this.applePaySession)try{this.applePaySession.completePaymentMethodSelection(Ai(this.context,this.config))}catch(r){C.errorWithDatadog("Error handling payment method selection",{error:r}),this.abort()}}async handlePaymentAuthorized(e){if(!this.applePaySession)return;let r=[new ApplePayError("unknown",void 0,this.context.translate(fr.UNKNOWN_ERROR,vr.UNKNOWN_ERROR))];try{if(this.clientOptions?.billingOptions?.requiredBillingContactFields?.includes("postalAddress")){let s=Si(e.payment.billingContact);if(s){if(!s.firstName||!s.lastName)throw r=[new ApplePayError("billingContactInvalid","name",this.context.translate(fr.MISSING_FIRST_OR_LAST_NAME,vr.MISSING_FIRST_OR_LAST_NAME))],new R({message:"Billing contact must include first and last name",code:wt.MISSING_PARAMETER,paymentMethod:B.APPLE_PAY,suggestion:"Ensure Apple Pay requiredBillingContactFields includes name fields"});let{error:l}=await this.context.clientSessionApi.setBillingAddress(s);l&&C.errorWithDatadog("Error setting billing address from Apple Pay",{error:l})}}let i=Si(e.payment.shippingContact);if(i){let{error:s}=await this.context.clientSessionApi.setShippingAddress(i,e.payment.shippingContact?.phoneNumber,e.payment.shippingContact?.emailAddress);if(s)throw s}let{data:n,error:o}=await this.context.pciApi.postApplePayPaymentInstruments({paymentMethodConfigId:this.config.id,token:e.payment.token});if(o||!n)throw r=[new ApplePayError("unknown",void 0,this.context.translate(fr.FAILED_TO_TOKENIZE,vr.FAILED_TO_TOKENIZE))],o??new Error("Failed to tokenize Apple Pay payment");this.applePaySession.completePayment(ApplePaySession.STATUS_SUCCESS),this.callbacks.onFinish(n),this.applePaySession=null}catch(i){let n=i instanceof R||i instanceof F?i:new R({message:"Error handling payment authorization",code:O.PAYMENT_FAILED,paymentMethod:B.APPLE_PAY,error:i instanceof Error?i:new Error(String(i))});C.errorWithDatadog("Apple Pay payment authorization failed",{error:n}),this.applePaySession&&(this.applePaySession.completePayment({status:ApplePaySession.STATUS_FAILURE,errors:r}),this.applePaySession=null),this.callbacks.onFinish(void 0,n)}}async handleShippingContactSelected(e){if(this.applePaySession)try{let{data:r,error:i}=await this.context.clientSessionApi.setShippingAddress(Si(e.shippingContact),e.shippingContact?.phoneNumber,e.shippingContact?.emailAddress);if(!this.applePaySession)return;if(!r||i)throw i??new R({message:"Failed to set shipping address",code:J.REQUEST_ERROR,paymentMethod:B.APPLE_PAY});this.applePaySession.completeShippingContactSelection(Ai(this.context,this.config))}catch(r){C.errorWithDatadog("Error handling shipping contact selection",{error:r}),this.abort()}}async handleShippingMethodSelected(e){if(!this.applePaySession)return;let r=this.context.configuration.checkoutModules?.find(i=>i.type==="SHIPPING")?.options;try{if(this.clientOptions?.shippingOptions?.requireShippingMethod&&r){let{data:i,error:n}=await this.context.clientSessionApi.selectShippingMethod(e.shippingMethod.identifier);if(!i||n)throw n??new R({message:"Failed to select shipping method",code:J.REQUEST_ERROR,paymentMethod:B.APPLE_PAY})}if(!this.applePaySession)return;this.applePaySession.completeShippingMethodSelection(Ai(this.context,this.config))}catch(i){C.errorWithDatadog("Error handling shipping method selection",{error:i}),this.abort();return}}handleCancel(){this.applePaySession=null,this.context.clientSessionApi.unselectPaymentMethod(),C.info("Apple Pay payment was cancelled by the user")}abort(e){this.applePaySession?.abort(),this.applePaySession=null,this.callbacks.onFinish(void 0,e??new Error("Apple Pay payment aborted"))}},na=class extends Ee{constructor(){super(...arguments);S(this,"blikCode","")}setBlikCode(e){this.blikCode=e}getBlikCode(){return this.blikCode}clearBlikCode(){this.blikCode=""}async start(){try{let{action:e}=await this.callbacks.onStart();if(e==="abort")return this.callbacks.onFinish(void 0,new R({message:"Payment creation aborted",code:O.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type}));let r=await this.tokenize();this.callbacks.onFinish(r)}catch(e){this.callbacks.onFinish(void 0,e)}}async tokenize(){if(!/^\d{6}$/.test(this.blikCode))throw new F({message:"BLIK code must be exactly 6 digits",code:O.TOKENIZATION_ERROR,paymentMethod:this.config.type});let e={type:"OFF_SESSION_PAYMENT",paymentMethodType:this.config.type,paymentMethodConfigId:this.config.id,sessionInfo:{locale:this.context.locale,platform:Ar()?"MOBILE_WEB":"WEB",browserInfo:Rt(),blikCode:this.blikCode}};try{let{error:r,data:i}=await this.context.pciApi.postBlikPaymentInstruments(e);if(this.clearBlikCode(),r||!i)throw r??new F({message:"Unable to tokenize BLIK payment method",code:O.TOKENIZATION_ERROR,paymentMethod:this.config.type});return i}catch(r){throw this.clearBlikCode(),r}}async createPayment(e){let r=await super.createPayment(e),i=r.requiredAction?.clientToken;if(!i)throw new le({message:"No client token provided for BLIK payment",code:aa.MISSING_CLIENT_TOKEN,response:{id:r.id,data:r}});let n=ht(i);if(!this.isValidBlikClientToken(n))throw new le({message:"Invalid BLIK client token: missing statusUrl or incorrect intent",code:aa.INVALID_CLIENT_TOKEN,response:{id:r.id,data:r}});let o=await this.context.pciApi.pollResumeStatus(n.statusUrl,{timeout:864e5,isComplete:l=>!!l.error||l.data?.status==="COMPLETE"});if(o.error)throw o.error;let s=o.data?.id;if(!s){let l=await this.context.pciApi.getResumeStatus(n.statusUrl);if(l.error||!l.data?.id)throw l.error??new Error("Unable to get resume token");s=l.data.id}return await this.resumePayment(r.id,s)}isValidBlikClientToken(e){if(typeof e!="object"||e===null)return!1;let r=e;return!(r.intent!=="ADYEN_BLIK_REDIRECTION"||!("statusUrl"in r)||typeof r.statusUrl!="string"||!r.statusUrl)}},Xo="https://sdk.primer.io/web/hosted-pages/v0.0.30",_i=!1,Nu=`${Xo}/api-controller.html`,Iu=`${Xo}/hosted-input.html`,es="https://goat-assets.production.core.primer.io",ku="primer-js-1.4.0_sdk-core-0.12.0";function ts(a,t,e){let r={checkoutSessionId:a,name:t};e!==void 0&&(r.defaultValue=e);try{return btoa(JSON.stringify(r))}catch{let{defaultValue:n,...o}=r;return btoa(JSON.stringify(o))}}Wi("../../node_modules/card-validator/dist/index.js");var ie={cardNumber:"cardNumber",cardSecurityCode:"cardSecurityCode",cardExpiryDate:"cardExpiryDate",cardholderName:"cardholderName"},po="cardSecurityCodeRecapture";Object.values(ie);function Lu({networks:a,source:t},e){let r=e,i=new Set(r.map(p=>Zt(p).backend)),n=a.map(p=>({...p,allowed:i.has(p.network)})).sort((p,m)=>p.allowed?r.indexOf(p.network)-r.indexOf(m.network):1),o=n.filter(p=>p.allowed),s=t==="REMOTE"&&o.length>1,[l,...c]=n;return{cardNetworkChangeEventData:{detectedCardNetworks:{items:n.map(Jr),preferred:o.length?Jr(o[0]):void 0},...s&&{selectableCardNetworks:{items:o.map(Jr),preferred:o.length?Jr(o[0]):void 0}},source:t},binDataAvailableEventData:{preferred:l,alternatives:c,status:t==="REMOTE"?"complete":"partial"}}}function Jr({network:a,displayName:t,allowed:e}){return{network:a,displayName:t,allowed:e}}function Ru(a,t){return{cardNumber:yr(a,ie.cardNumber),cardSecurityCode:yr(a,ie.cardSecurityCode),cardExpiryDate:yr(a,ie.cardExpiryDate),cardholderName:yr(a,ie.cardholderName,t?.cardholderName)}}function yr(a,t,e){let r=document.createElement("iframe"),i=ts(a,t,e);return r.src=`${Iu}#${i}`,r.setAttribute("tabindex","0"),r.setAttribute("frameBorder","0"),r.style.border="none",r.style.boxSizing="border-box",r.style.height="20px",r.style.width="100%",r.style.colorScheme="auto",r}var oa=class extends Ee{constructor(e,r){super(e,r);S(this,"iframes");this.iframes=Ru(r.checkoutSessionId,{cardholderName:r.clientOptions.card?.cardholderName?.defaultValue})}async start(){try{let{action:e}=await this.callbacks.onStart();if(e==="abort")return this.callbacks.onFinish(void 0,new R({message:"Payment creation aborted",code:O.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type}));let r=await this.tokenize();this.callbacks.onFinish(r)}catch(e){this.callbacks.onFinish(void 0,e)}}async tokenize(){let{error:e,data:r}=await this.context.pciApi.postCardPaymentInstruments();if(e||!r)throw e??new F({code:O.TOKENIZATION_ERROR,message:"Unable to tokenize payment method",paymentMethod:B.PAYMENT_CARD});return r}};function wu(a){if(!a)return{};let t=a.indexOf(" ");return t===-1?{firstName:a}:{firstName:a.substring(0,t),lastName:a.substring(t+1)}}function Ei(a){let{firstName:t,lastName:e}=wu(a.name);return{firstName:t||null,lastName:e||null,addressLine1:a.address1||null,addressLine2:a.address2||null,city:a.locality||null,state:a.administrativeArea||null,postalCode:a.postalCode||null,countryCode:a.countryCode||null}}function mo(a){return a.map(t=>({id:t.id,label:t.name,description:t.description||""}))}var ho=2,go=0,xu="https://pay.google.com/gp/p/js/pay.js",_u={AMEX:"AMEX",DISCOVER:"DISCOVER",INTERAC:"INTERAC",JCB:"JCB",MASTERCARD:"MASTERCARD",VISA:"VISA"},yo=["AMEX","DISCOVER","INTERAC","JCB","MASTERCARD","VISA"],qr={FEE:"fee_label_fallback",ITEM:"item_label_fallback",SHIPPING:"shipping",SUBTOTAL:"subtotal"},Qr={FEE:"Fee",ITEM:"Item",SHIPPING:"Shipping",SUBTOTAL:"Subtotal"},Ou="buy",Du="black",Bu="fill",sa=class extends Ee{constructor(){super(...arguments);S(this,"disabled",!1);S(this,"client",null)}async setDisabled(e){this.disabled=e}translate(e,r){return this.context.translate?.(e,r)??r}async tokenize(){throw new F({code:O.TOKENIZATION_ERROR,message:"Google Pay does not support direct tokenization",paymentMethod:B.GOOGLE_PAY})}async loadGooglePayScript(){if(typeof google<"u"&&google.payments?.api?.PaymentsClient)return!0;try{return await Xi(xu),!0}catch{return C.error("Failed to load Google Pay script"),!1}}async setup(){let{countryCode:e,currencyCode:r}=this.context.configuration.clientSession.order;if(!e)throw new R({code:wt.MISSING_PARAMETER,message:"Cannot initialize Google Pay: missing country code",paymentMethod:B.GOOGLE_PAY});if(!r)throw new R({code:wt.MISSING_PARAMETER,message:"Cannot initialize Google Pay: missing currency code",paymentMethod:B.GOOGLE_PAY});if(!await this.loadGooglePayScript())return C.error("Google Pay script failed to load"),!1;let n=this.context.configuration.env==="PRODUCTION"?"PRODUCTION":"TEST";this.client=new google.payments.api.PaymentsClient({environment:n,...this.needsPaymentDataCallbacks()&&{paymentDataCallbacks:{onPaymentDataChanged:s=>this.handlePaymentDataChanged(s)}}});try{let{result:s,paymentMethodPresent:l}=await this.client.isReadyToPay(this.buildIsReadyToPayRequest());if(!s)return C.info("Google Pay is not available in this browser/device"),!1;if(this.clientOptions?.existingPaymentMethodRequired&&l===!1)return C.info("Google Pay: existingPaymentMethodRequired is true but no existing payment method is available"),!1}catch(s){return C.error("Google Pay isReadyToPay check failed",{error:s}),!1}let o=this.context.onClientConfigurationUpdate(s=>{let l=s.clientSession?.order;(!l||!l.totalOrderAmount||!l.currencyCode)&&C.warn("Google Pay: Order details are missing or incomplete after client session update. Ensure order details (totalOrderAmount, currencyCode, countryCode) are always provided.")});return this.context.subscribeToTeardown(o),!0}needsPaymentDataCallbacks(){return!!(this.clientOptions?.requireShippingMethod||this.shouldCaptureShippingAddress)}buildIsReadyToPayRequest(){return{apiVersion:ho,apiVersionMinor:go,allowedPaymentMethods:[this.allowedPaymentMethod],existingPaymentMethodRequired:this.clientOptions?.existingPaymentMethodRequired}}async render(e){if(!this.client)return void C.error("Google Pay client not initialized. Call setup() first.");let r=this.client.createButton({buttonType:this.clientOptions?.buttonType??Ou,buttonColor:this.clientOptions?.buttonColor??Du,buttonSizeMode:this.clientOptions?.buttonSizeMode??Bu,buttonRadius:this.clientOptions?.buttonRadius,buttonLocale:this.clientOptions?.buttonLocale,buttonBorderType:this.clientOptions?.buttonBorderType,onClick:i=>this.handleClick(i),buttonRootNode:e instanceof ShadowRoot?e:void 0});e.appendChild(r)}async handleClick(e){if(this.disabled)return;if(!this.client)return void C.error("Google Pay client not available");let r=this.callbacks.onStart();Le({eventName:"PAYMENT_METHOD_SELECTION",paymentMethod:B.GOOGLE_PAY});try{let i=await this.client.loadPaymentData(this.buildPaymentDataRequest()),{action:n}=await r;if(n==="abort")throw new R({message:"Payment creation aborted",code:O.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type});await this.processPaymentData(i)}catch(i){if(i.statusCode==="CANCELED")return void this.context.clientSessionApi.unselectPaymentMethod();C.errorWithDatadog("Google Pay error",{error:i}),this.callbacks.onFinish(void 0,i)}}get clientOptions(){return this.context.clientOptions.googlePay}get shouldCaptureShippingAddress(){return!!(this.clientOptions?.captureShippingAddress||this.clientOptions?.shippingAddressParameters)}async processPaymentData(e){if(this.clientOptions?.captureBillingAddress&&await this.updateBillingAddress(e),(this.shouldCaptureShippingAddress||this.clientOptions?.requireShippingMethod||this.clientOptions?.emailRequired)&&await this.updateShippingDetails(e),this.clientOptions?.requireShippingMethod){let n=e.shippingOptionData?.id;n&&await this.context.clientSessionApi.selectShippingMethod(n)}let{data:r,error:i}=await this.context.pciApi.postGooglePayPaymentInstruments({flow:"GATEWAY",network:e.paymentMethodData.info?.cardNetwork??"OTHER",merchant_id:this.config.options.merchantId,encrypted_payload:Cr.encode(e.paymentMethodData.tokenizationData.token)});if(i||!r)throw this.callbacks.onFinish(void 0,i),i??new F({code:O.TOKENIZATION_ERROR,message:"Failed to tokenize payment data",paymentMethod:B.GOOGLE_PAY});this.callbacks.onFinish(r)}async updateBillingAddress(e){let r=e.paymentMethodData.info?.billingAddress;if(r){let i=Ei(r);await this.context.clientSessionApi.setBillingAddress(i)}else C.warn("Google Pay: Could not retrieve billing address from payment data")}async updateShippingDetails(e){let r=e.shippingAddress,i=e.email,n=r?.phoneNumber;if(r||n||i){let o=r?Ei(r):void 0;await this.context.clientSessionApi.setShippingAddress(o,n,i)}else C.warn("Google Pay: No shipping address, phone number, or email found in payment data")}async handlePaymentDataChanged(e){let r=e.callbackTrigger;try{if(r==="SHIPPING_OPTION"){let i=e.shippingOptionData?.id;return i&&await this.context.clientSessionApi.selectShippingMethod(i),{newTransactionInfo:this.getCurrentTransactionInfo()}}if(r==="SHIPPING_ADDRESS"||r==="INITIALIZE"){let i=e.shippingAddress;if(i){let s=Ei(i);await this.context.clientSessionApi.setShippingAddress(s)}let n=this.getShippingModule(),o=n?.shippingMethods||[];return{...this.clientOptions?.requireShippingMethod&&o.length>0&&{newShippingOptionParameters:{shippingOptions:mo(o),defaultSelectedOptionId:n?.selectedShippingMethod||o[0]?.id}},newTransactionInfo:this.getCurrentTransactionInfo()}}return{newTransactionInfo:this.getCurrentTransactionInfo()}}catch(i){return C.errorWithDatadog("Google Pay: Error handling payment data change",{error:i}),{error:{reason:"OTHER_ERROR",message:"An error occurred while processing your request",intent:r==="SHIPPING_OPTION"?"SHIPPING_OPTION":"SHIPPING_ADDRESS"}}}}getShippingModule(){return this.context.configuration.checkoutModules?.find(i=>i.type==="SHIPPING")?.options}getCurrentTransactionInfo(){let{countryCode:e,currencyCode:r,merchantAmount:i,totalOrderAmount:n}=this.context.configuration.clientSession.order;return{countryCode:e,currencyCode:r,displayItems:this.getDisplayItems(),totalPriceStatus:"FINAL",totalPrice:hr(i??n,r),totalPriceLabel:"Total"}}getDisplayItems(){let e=this.context.configuration.clientSession.order,{currencyCode:r,merchantAmount:i,lineItems:n,fees:o,shipping:s}=e,l=this.clientOptions?.requireShippingMethod,c=[];return i?(c.push({label:this.translate(qr.SUBTOTAL,Qr.SUBTOTAL),type:"SUBTOTAL",price:hr(i,r)}),c):(n&&n.length>0&&n.forEach(p=>{c.push({label:p.description||this.translate(qr.ITEM,Qr.ITEM),type:"LINE_ITEM",price:hr(p.amount,r)})}),o&&o.length>0&&o.filter(p=>p.amount!==0).forEach(p=>{c.push({label:p.type||p.description||this.translate(qr.FEE,Qr.FEE),type:"LINE_ITEM",price:hr(p.amount,r)})}),l&&s&&s.amount!==0&&c.push({label:s.methodName||this.translate(qr.SHIPPING,Qr.SHIPPING),type:"LINE_ITEM",price:hr(s.amount,r)}),c)}get allowedCardNetworks(){let e=this.context.configuration.clientSession.paymentMethod?.orderedAllowedCardNetworks;if(!e||e.length===0)return yo;let r=e.map(i=>_u[i]).filter(i=>!!i);return r.length>0?r:yo}get allowedPaymentMethod(){let e=this.clientOptions?.captureBillingAddress;return{type:"CARD",parameters:{allowedAuthMethods:["PAN_ONLY","CRYPTOGRAM_3DS"],allowedCardNetworks:this.allowedCardNetworks,...e&&{billingAddressRequired:!0,billingAddressParameters:{format:"FULL"}}}}}buildPaymentDataRequest(){let e=this.clientOptions?.shippingAddressParameters,r=this.clientOptions?.emailRequired,i=this.clientOptions?.requireShippingMethod,n=this.getShippingModule(),o=n?.shippingMethods,s=n?.selectedShippingMethod;return{apiVersion:ho,apiVersionMinor:go,...r&&{emailRequired:!0},...(this.shouldCaptureShippingAddress||i)&&{shippingAddressRequired:!0,...e&&{shippingAddressParameters:{...e.allowedCountryCodes&&{allowedCountryCodes:e.allowedCountryCodes},...e.phoneNumberRequired&&{phoneNumberRequired:!0}}}},...i&&{shippingOptionRequired:!0,...o&&o.length>0&&{shippingOptionParameters:{shippingOptions:mo(o),defaultSelectedOptionId:s||o[0]?.id}}},...this.needsPaymentDataCallbacks()&&{callbackIntents:[...i?["SHIPPING_ADDRESS","SHIPPING_OPTION"]:["SHIPPING_ADDRESS"]]},transactionInfo:this.getCurrentTransactionInfo(),merchantInfo:{merchantId:this.config.options.merchantId,merchantName:this.config.options.merchantName},allowedPaymentMethods:[{...this.allowedPaymentMethod,tokenizationSpecification:{type:"PAYMENT_GATEWAY",parameters:{gateway:"primer",gatewayMerchantId:this.config.options.merchantId}}}]}}},Gu="https://x.klarnacdn.net/kp/lib/v1/api.js",la=class extends Error{constructor(){super("Klarna authorization cancelled by user"),this.name="KlarnaUserCancelledError"}},da=class extends Ee{constructor(){super(...arguments);S(this,"session",null);S(this,"selectedCategoryId",null)}getCategories(){let e=this.session?.categories??[],r=this.context.clientOptions.klarna?.allowedPaymentCategories;return r?r.map(i=>e.find(n=>n.identifier===i)).filter(i=>i!=null):e}setSelectedCategory(e){this.selectedCategoryId=e}async setup(){try{return await Xi(Gu,{crossorigin:""}),window.Klarna?.Payments?(this.session=await this.createSession(),this.session?this.getCategories().length===0?(C.warn("No Klarna payment categories available"),!1):(window.Klarna.Payments.init({client_token:this.session.clientToken}),!0):!1):(C.error("Klarna SDK failed to load"),!1)}catch(e){return C.error("Klarna setup failed",e),!1}}get isRecurring(){return this.context.clientOptions.klarna?.paymentFlow==="PREFER_VAULT"}async createSession(){let{clientSession:e}=this.context.configuration,r=e.order,i={localeCode:this.context.locale,countryCode:r?.countryCode??"",currencyCode:r?.currencyCode??""},n;if(this.isRecurring)n={sessionType:"RECURRING_PAYMENT",paymentMethodConfigId:this.config.id,localeData:i,description:this.context.clientOptions.klarna?.recurringPaymentDescription};else{if(!r?.lineItems||r.lineItems.length===0)return C.error("Klarna requires order.lineItems to be provided"),null;let l=r.lineItems.map(p=>({name:p.name||p.description||"",unitAmount:p.amount,reference:p.itemId,quantity:p.quantity,discountAmount:p.discountAmount,taxCode:p.taxCode,taxAmount:p.taxAmount,productType:p.productType})),c=r.merchantAmount??r.totalOrderAmount??0;n={sessionType:"ONE_OFF_PAYMENT",paymentMethodConfigId:this.config.id,localeData:i,totalAmount:c,orderItems:l}}let{data:o,error:s}=await this.context.coreApi.createKlarnaSession(n);return s||!o?(C.error("Failed to create Klarna session",s),null):o}async renderCategory(e){if(!window.Klarna?.Payments)throw new F({message:"Klarna SDK not loaded",code:O.TOKENIZATION_ERROR,paymentMethod:this.config.type});let{Payments:r}=window.Klarna,i=(typeof e.containerId=="string",e.containerId);return e.onHeightChange&&r.on("heightChanged",e.onHeightChange),new Promise((n,o)=>{r.load({container:i,payment_method_category:e.paymentMethodCategoryId},s=>{s.error?o(new F({message:`Klarna load failed: ${s.error.invalid_fields?.join(", ")}`,code:O.TOKENIZATION_ERROR,paymentMethod:this.config.type})):(this.selectedCategoryId=e.paymentMethodCategoryId,n())})})}async authorize(e){if(!window.Klarna?.Payments)throw new F({message:"Klarna SDK not loaded",code:O.TOKENIZATION_ERROR,paymentMethod:this.config.type});let{Payments:r}=window.Klarna;return new Promise(i=>{r.authorize({payment_method_category:e},void 0,i)})}async finalizeSession(){if(!this.session)return null;let{data:e,error:r}=await this.context.coreApi.finalizeKlarnaSession({sessionId:this.session.sessionId,paymentMethodConfigId:this.config.id});return r||!e?(C.error("Failed to finalize Klarna session",r),null):e}async createCustomerToken(e){if(!this.session)return null;let r=this.context.clientOptions.klarna?.recurringPaymentDescription;if(!r)return C.error("klarna.recurringPaymentDescription must be provided for PREFER_VAULT flow"),null;let{clientSession:i}=this.context.configuration,n=i.order,{data:o,error:s}=await this.context.coreApi.createKlarnaCustomerToken({paymentMethodConfigId:this.config.id,sessionId:this.session.sessionId,authorizationToken:e,description:r,localeData:{localeCode:this.context.locale,countryCode:n?.countryCode??"",currencyCode:n?.currencyCode??""}});return s||!o?(C.error("Failed to create Klarna customer token",s),null):o}async tokenize(){if(!this.selectedCategoryId)throw new F({message:"No Klarna payment category selected",code:O.TOKENIZATION_ERROR,paymentMethod:this.config.type});let e=await this.authorize(this.selectedCategoryId);if(!e.approved&&!e.error)throw C.debug("Klarna authorization cancelled by user"),new la;if(!e.approved||!e.authorization_token){let r=e.error?.invalid_fields?.join(", ")||"Authorization failed";throw new F({message:`Klarna authorization failed: ${r}`,code:O.TOKENIZATION_ERROR,paymentMethod:this.config.type})}return this.isRecurring?this.tokenizeWithCustomerToken(e.authorization_token):this.tokenizeWithAuthToken(e.authorization_token)}async tokenizeWithAuthToken(e){let r=await this.finalizeSession();if(!r)throw new F({message:"Failed to finalize Klarna session",code:O.TOKENIZATION_ERROR,paymentMethod:this.config.type});let{data:i,error:n}=await this.context.pciApi.postKlarnaPaymentInstruments({klarnaAuthorizationToken:e,sessionData:r.sessionData});if(n||!i)throw n??new F({message:"Failed to tokenize Klarna payment",code:O.TOKENIZATION_ERROR,paymentMethod:this.config.type});return i}async tokenizeWithCustomerToken(e){let r=await this.createCustomerToken(e);if(!r)throw new F({message:"Failed to create Klarna customer token",code:O.TOKENIZATION_ERROR,paymentMethod:this.config.type});let{data:i,error:n}=await this.context.pciApi.postKlarnaCustomerTokenInstruments({klarnaCustomerToken:r.customerTokenId,sessionData:r.sessionData});if(n||!i)throw n??new F({message:"Failed to tokenize Klarna payment",code:O.TOKENIZATION_ERROR,paymentMethod:this.config.type});return i}async start(){try{let{action:e}=await this.callbacks.onStart();if(e==="abort")return this.callbacks.onFinish(void 0,new Error("Payment aborted"));let r=await this.tokenize();this.callbacks.onFinish(r)}catch(e){if(e instanceof la)return void this.context.clientSessionApi.unselectPaymentMethod();this.callbacks.onFinish(void 0,e)}}async startWithCategory(e){return this.selectedCategoryId=e,this.start()}},Ku=100;function en({height:a,name:t,url:e="",width:r}){let i=new Set,n=window.open(e,t,Uu({height:a,width:r}));if(!n)return;function o(){n?.close(),s()}function s(){i.forEach(l=>l()),i.clear(),window.removeEventListener("beforeunload",o)}return window.addEventListener("beforeunload",o),Fu(n).then(s),{close:o,focus(){n.focus()},get isOpen(){return n?.closed===!1},onClose(l){return i.add(l),()=>{i.delete(l)}},setContent(l){n.document.write(l)},setUrl(l){n.location.replace(l)}}}var Fu=a=>new Promise(t=>{let e=setInterval(()=>{a.closed&&(clearInterval(e),t())},Ku)});function Uu(a){let t=Vu({parent:{left:window.screenLeft,top:window.screenTop,height:window.outerHeight,width:window.outerWidth},popup:a});return Hu(t)}var Vu=({parent:a,popup:t})=>({left:a.left+(a.width-t.width)/2,top:a.top+(a.height-t.height)/2,height:t.height,width:t.width}),Hu=a=>Object.entries(a).map(t=>t.join("=")).join(",");function xt(a){return a?new Promise(t=>{setTimeout(t,a)}):Promise.resolve()}function tn(a,t){return a?.redirect?.returnUrl?!0:(C.warn(`[Primer SDK] ${t} is enabled in your client session but \`options.redirect.returnUrl\` is missing. This payment method may redirect the customer to an external page; without a return URL the customer cannot be brought back. The payment method will not be available in this checkout. Set \`options.redirect.returnUrl\` to a page that re-initializes the SDK with the \`?clientToken=...\` query parameter Primer appends on return.`),!1)}function Yu(a,t){if(a?.redirect?.returnUrl)return;let e=typeof window<"u"&&window.location?window.location.href:"";C.warn(`[Primer SDK] Initiating ${t} which may redirect the customer to an external page, but no \`options.redirect.returnUrl\` is configured. The customer will be returned to the current page (${e}). Set \`options.redirect.returnUrl\` to control the return destination.`),Le({eventName:"REDIRECT_RETURN_URL_NOT_CONFIGURED",paymentMethod:t})}function rn(a,t,e){let r="";try{r=new URL(a).origin}catch{r=""}C.info(`[Primer SDK] Redirecting to ${t} payment page at ${r} (${e})`),Le({eventName:"PAYMENT_REDIRECT_TO_THIRD_PARTY",paymentMethod:t,redirectDestinationUrl:r,redirectReason:e})}function fo(a,t={}){C.info(`[Primer SDK] Returned from third-party payment page (${a})`),Le({eventName:"PAYMENT_RETURNED_FROM_THIRD_PARTY",intent:a,...t})}var Mi="Adyen Klarna",ca=class extends Ee{constructor(){super(...arguments);S(this,"paymentTypes",[]);S(this,"popup");S(this,"shouldRedirect",!1);S(this,"redirectReason","force_redirect");S(this,"dialogPromise");S(this,"selectedOptionId",null)}get assets(){let{displayMetadata:e,name:r}=this.config;return{icon:e?.button?.iconUrl??{},logo:e?.overlay?.logo??e?.button?.iconUrl??{},backgroundColor:e?.button?.backgroundColor??e?.overlay?.backgroundColor??{},name:r}}get logoSrc(){return this.assets.logo.colored||this.assets.logo.light||this.assets.icon.colored||this.assets.icon.light||""}async setup(){if(!tn(this.context.clientOptions,this.config.type))return!1;try{let{data:e,error:r}=await this.context.coreApi.getPaymentMethodOptions(this.config.id);return r?(C.error("Failed to fetch Adyen Klarna payment types",r),!1):e?.result?.length?(this.paymentTypes=e.result,this.paymentTypes.length===1&&(this.selectedOptionId=this.paymentTypes[0].name),!0):(C.warn("No Adyen Klarna payment types available for this currency/country combination"),!1)}catch(e){return C.error("Adyen Klarna setup failed",e),!1}}getOptions(){return this.paymentTypes.map(e=>({id:e.name,label:e.id}))}selectOption(e){this.selectedOptionId=e}async tokenize(){if(!this.selectedOptionId)throw new F({message:"No Adyen Klarna payment type selected",code:O.TOKENIZATION_ERROR,paymentMethod:this.config.type});let{error:e,data:r}=await this.context.pciApi.postAdyenKlarnaPaymentInstruments({type:"OFF_SESSION_PAYMENT",paymentMethodType:this.config.type,paymentMethodConfigId:this.config.id,sessionInfo:{locale:this.context.locale,platform:Ar()?"MOBILE_WEB":"WEB",browserInfo:Rt(),paymentMethodType:this.selectedOptionId,merchantRedirectUrl:this.context.clientOptions.redirect?.returnUrl}});if(e||!r)throw e??new F({message:"Unable to tokenize Adyen Klarna payment",code:O.TOKENIZATION_ERROR,paymentMethod:this.config.type});return r}async createPayment(e){try{let r=await super.createPayment(e),i=this.validateAndDecodeClientToken(r);if(this.shouldRedirect&&(rn(i.redirectUrl,this.config.type,this.redirectReason),window.location.assign(i.redirectUrl),await new Promise(()=>{})),!this.popup?.isOpen)return this.cancelPayment(r);this.popup.setUrl(i.redirectUrl);let n=await this.waitForPaymentCompletion(i.statusUrl);if(this.cleanup(),"error"in n)throw n.error;if(this.wasPopupClosedWithoutCompletion(n))return this.cancelPayment(r);let o=await this.getResumeToken(n,i.statusUrl);return await this.resumePayment(r.id,o)}catch(r){throw this.cleanup(),r}}async start(){try{this.config.forceRedirect||!!this.context.clientOptions.redirect?.forceRedirect?(this.shouldRedirect=!0,this.redirectReason="force_redirect"):Qi()&&(this.shouldRedirect=!0,this.redirectReason="in_app_browser"),this.showOverlayDialog(),this.shouldRedirect||(this.openPopup(),this.popup&&await xt(300),this.popup?.isOpen||(this.shouldRedirect=!0,this.redirectReason="popup_blocked"));let{action:r}=await this.callbacks.onStart();if(r==="abort")throw this.cleanup(),new R({message:"Payment creation aborted",code:O.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type});let i=await this.tokenize();this.callbacks.onFinish(i)}catch(e){this.cleanup(),this.callbacks.onFinish(void 0,e)}}cleanup(){this.popup?.close(),this.context.dialogProvider.close()}cancelPayment(e){return this.context.clientSessionApi.unselectPaymentMethod(e),this.cleanup(),{...e,cancelled:!0}}validateAndDecodeClientToken(e){let r=e.requiredAction?.clientToken;if(!r)throw new F({message:"No client token provided for Adyen Klarna redirect"});let i=ht(r);if(!jo(i,this.config.type))throw new F({message:"Invalid Adyen Klarna client token"});return i}async waitForPaymentCompletion(e){let r=this.dialogPromise?.then(()=>({id:"",popupClosed:!0}))??Promise.resolve({id:"",popupClosed:!0}),i=new Promise(l=>{this.popup?.onClose(()=>l({id:"",popupClosed:!0}))}),{promise:n,abort:o}=this.pollStatus(e),s=await Promise.race([r,i,n]);return o(),s}wasPopupClosedWithoutCompletion(e){return"popupClosed"in e&&!!e.popupClosed&&!this.context.clientOptions.redirect?.resumePaymentOnPopupClosure}async getResumeToken(e,r){if(e.id)return e.id;let{data:i,error:n}=await this.context.pciApi.getResumeStatus(r);if(n||!i?.id)throw n??new Error("Unable to get resume token");return i.id}showOverlayDialog(){let e=this.assets.backgroundColor.colored||this.assets.backgroundColor.light||"#FFB3C7",r=document.createElement("div");r.setAttribute("style","display: flex; flex-direction: column; gap: var(--primer-size-xlarge);");let i=document.createElement("div");if(i.setAttribute("style",`display: flex;margin:auto;padding:calc(var(--primer-size-small)*0.5);height: var(--primer-size-xlarge);background-color: ${e};border-radius:var(--primer-radius-small);`),this.logoSrc){let o=document.createElement("img");o.src=this.logoSrc,o.setAttribute("style","height:100%;"),i.appendChild(o)}r.appendChild(i);let n=document.createElement("p");n.setAttribute("style","max-width: 300px;text-align: center;"),n.innerText=this.context.translate("paymentMethodPopupOverlayDescription","Having trouble viewing the {paymentMethodName} payment page? We'll help you find it!").replace("{paymentMethodName}",this.assets.name),r.appendChild(n),this.dialogPromise=this.context.dialogProvider.show({htmlContent:r,showCloseButton:!0,size:"flex",cta:{label:this.context.translate("paymentMethodPopupOverlayBringBackThePaymentPage","Bring back the payment page"),icon:"chevron-left",onClick:()=>this.popup?.focus()}}).then(()=>{})}openPopup(){let{name:e,displayMetadata:{popup:r}}=this.config;this.popup=en({name:e,height:r?.height??1e3,width:r?.width??1200}),this.popup?.setContent(this.createPopupLoadingContent())}createPopupLoadingContent(){let e=this.context.translate("paymentMethodPopupLoadingScreenText","Hold on! {paymentMethodName} is loading.").replace("{paymentMethodName}",Mi);return`
|
|
36
|
+
`,e.appendChild(i);let n=document.createElement("apple-pay-button"),o=this.clientOptions?.buttonStyle??this.clientOptions?.buttonOptions?.buttonStyle;o&&n.setAttribute("buttonstyle",o);let s=this.clientOptions?.buttonType??this.clientOptions?.buttonOptions?.type??"plain";s&&n.setAttribute("type",s),n.setAttribute("locale",this.context.locale),n.addEventListener("click",this.handleClick.bind(this)),document.body.appendChild(n),setTimeout(()=>{e.appendChild(n)},0)}async handleClick(){if(!this.disabled)try{this.onStartPromise=this.callbacks.onStart(),Le({eventName:"PAYMENT_METHOD_SELECTION",paymentMethod:B.APPLE_PAY}),this.applePaySession=new ApplePaySession(co,Pu(this.context,this.config)),this.applePaySession.onvalidatemerchant=this.handleValidateMerchant.bind(this),this.applePaySession.onpaymentauthorized=this.handlePaymentAuthorized.bind(this),this.applePaySession.onpaymentmethodselected=this.handlePaymentMethodSelected.bind(this),this.applePaySession.onshippingcontactselected=this.handleShippingContactSelected.bind(this),this.applePaySession.onshippingmethodselected=this.handleShippingMethodSelected.bind(this),this.applePaySession.oncancel=this.handleCancel.bind(this),this.applePaySession.begin()}catch(e){C.errorWithDatadog("Error initiating Apple Pay session",{error:e})}}async handleValidateMerchant(e){if(this.applePaySession)try{let{action:r}=await this.onStartPromise;if(r==="abort")return void this.abort(new R({message:"Payment creation aborted",code:x.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type}));let{data:i,error:n}=await this.context.coreApi.createApplePaySession({validationUrl:e.validationURL,paymentMethodConfigId:this.config.id,merchantDomain:this.context.clientOptions.merchantDomain??window.location.hostname});if(!this.applePaySession)return;if(n||!i)throw n??new R({message:"Failed to validate merchant",code:J.REQUEST_ERROR,paymentMethod:B.APPLE_PAY});this.applePaySession.completeMerchantValidation(i)}catch(r){C.warn("Apple Pay merchant validation failed:",r),this.abort()}}async handlePaymentMethodSelected(e){if(this.applePaySession)try{this.applePaySession.completePaymentMethodSelection(Ai(this.context,this.config))}catch(r){C.errorWithDatadog("Error handling payment method selection",{error:r}),this.abort()}}async handlePaymentAuthorized(e){if(!this.applePaySession)return;let r=[new ApplePayError("unknown",void 0,this.context.translate(fr.UNKNOWN_ERROR,vr.UNKNOWN_ERROR))];try{if(this.clientOptions?.billingOptions?.requiredBillingContactFields?.includes("postalAddress")){let s=Si(e.payment.billingContact);if(s){if(!s.firstName||!s.lastName)throw r=[new ApplePayError("billingContactInvalid","name",this.context.translate(fr.MISSING_FIRST_OR_LAST_NAME,vr.MISSING_FIRST_OR_LAST_NAME))],new R({message:"Billing contact must include first and last name",code:wt.MISSING_PARAMETER,paymentMethod:B.APPLE_PAY,suggestion:"Ensure Apple Pay requiredBillingContactFields includes name fields"});let{error:l}=await this.context.clientSessionApi.setBillingAddress(s);l&&C.errorWithDatadog("Error setting billing address from Apple Pay",{error:l})}}let i=Si(e.payment.shippingContact);if(i){let{error:s}=await this.context.clientSessionApi.setShippingAddress(i,e.payment.shippingContact?.phoneNumber,e.payment.shippingContact?.emailAddress);if(s)throw s}let{data:n,error:o}=await this.context.pciApi.postApplePayPaymentInstruments({paymentMethodConfigId:this.config.id,token:e.payment.token});if(o||!n)throw r=[new ApplePayError("unknown",void 0,this.context.translate(fr.FAILED_TO_TOKENIZE,vr.FAILED_TO_TOKENIZE))],o??new Error("Failed to tokenize Apple Pay payment");this.applePaySession.completePayment(ApplePaySession.STATUS_SUCCESS),this.callbacks.onFinish(n),this.applePaySession=null}catch(i){let n=i instanceof R||i instanceof F?i:new R({message:"Error handling payment authorization",code:x.PAYMENT_FAILED,paymentMethod:B.APPLE_PAY,error:i instanceof Error?i:new Error(String(i))});C.errorWithDatadog("Apple Pay payment authorization failed",{error:n}),this.applePaySession&&(this.applePaySession.completePayment({status:ApplePaySession.STATUS_FAILURE,errors:r}),this.applePaySession=null),this.callbacks.onFinish(void 0,n)}}async handleShippingContactSelected(e){if(this.applePaySession)try{let{data:r,error:i}=await this.context.clientSessionApi.setShippingAddress(Si(e.shippingContact),e.shippingContact?.phoneNumber,e.shippingContact?.emailAddress);if(!this.applePaySession)return;if(!r||i)throw i??new R({message:"Failed to set shipping address",code:J.REQUEST_ERROR,paymentMethod:B.APPLE_PAY});this.applePaySession.completeShippingContactSelection(Ai(this.context,this.config))}catch(r){C.errorWithDatadog("Error handling shipping contact selection",{error:r}),this.abort()}}async handleShippingMethodSelected(e){if(!this.applePaySession)return;let r=this.context.configuration.checkoutModules?.find(i=>i.type==="SHIPPING")?.options;try{if(this.clientOptions?.shippingOptions?.requireShippingMethod&&r){let{data:i,error:n}=await this.context.clientSessionApi.selectShippingMethod(e.shippingMethod.identifier);if(!i||n)throw n??new R({message:"Failed to select shipping method",code:J.REQUEST_ERROR,paymentMethod:B.APPLE_PAY})}if(!this.applePaySession)return;this.applePaySession.completeShippingMethodSelection(Ai(this.context,this.config))}catch(i){C.errorWithDatadog("Error handling shipping method selection",{error:i}),this.abort();return}}handleCancel(){this.applePaySession=null,this.context.clientSessionApi.unselectPaymentMethod(),C.info("Apple Pay payment was cancelled by the user")}abort(e){this.applePaySession?.abort(),this.applePaySession=null,this.callbacks.onFinish(void 0,e??new Error("Apple Pay payment aborted"))}},na=class extends Ee{constructor(){super(...arguments);S(this,"blikCode","")}setBlikCode(e){this.blikCode=e}getBlikCode(){return this.blikCode}clearBlikCode(){this.blikCode=""}async start(){try{let{action:e}=await this.callbacks.onStart();if(e==="abort")return this.callbacks.onFinish(void 0,new R({message:"Payment creation aborted",code:x.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type}));let r=await this.tokenize();this.callbacks.onFinish(r)}catch(e){this.callbacks.onFinish(void 0,e)}}async tokenize(){if(!/^\d{6}$/.test(this.blikCode))throw new F({message:"BLIK code must be exactly 6 digits",code:x.TOKENIZATION_ERROR,paymentMethod:this.config.type});let e={type:"OFF_SESSION_PAYMENT",paymentMethodType:this.config.type,paymentMethodConfigId:this.config.id,sessionInfo:{locale:this.context.locale,platform:Ar()?"MOBILE_WEB":"WEB",browserInfo:Rt(),blikCode:this.blikCode}};try{let{error:r,data:i}=await this.context.pciApi.postBlikPaymentInstruments(e);if(this.clearBlikCode(),r||!i)throw r??new F({message:"Unable to tokenize BLIK payment method",code:x.TOKENIZATION_ERROR,paymentMethod:this.config.type});return i}catch(r){throw this.clearBlikCode(),r}}async createPayment(e){let r=await super.createPayment(e),i=r.requiredAction?.clientToken;if(!i)throw new le({message:"No client token provided for BLIK payment",code:aa.MISSING_CLIENT_TOKEN,response:{id:r.id,data:r}});let n=ht(i);if(!this.isValidBlikClientToken(n))throw new le({message:"Invalid BLIK client token: missing statusUrl or incorrect intent",code:aa.INVALID_CLIENT_TOKEN,response:{id:r.id,data:r}});let o=await this.context.pciApi.pollResumeStatus(n.statusUrl,{timeout:864e5,isComplete:l=>!!l.error||l.data?.status==="COMPLETE"});if(o.error)throw o.error;let s=o.data?.id;if(!s){let l=await this.context.pciApi.getResumeStatus(n.statusUrl);if(l.error||!l.data?.id)throw l.error??new Error("Unable to get resume token");s=l.data.id}return await this.resumePayment(r.id,s)}isValidBlikClientToken(e){if(typeof e!="object"||e===null)return!1;let r=e;return!(r.intent!=="ADYEN_BLIK_REDIRECTION"||!("statusUrl"in r)||typeof r.statusUrl!="string"||!r.statusUrl)}},Xo="https://sdk.primer.io/web/hosted-pages/v0.0.30",_i=!1,Nu=`${Xo}/api-controller.html`,Iu=`${Xo}/hosted-input.html`,es="https://goat-assets.production.core.primer.io",ku="primer-js-1.4.1_sdk-core-0.12.1";function ts(a,t,e){let r={checkoutSessionId:a,name:t};e!==void 0&&(r.defaultValue=e);try{return btoa(JSON.stringify(r))}catch{let{defaultValue:n,...o}=r;return btoa(JSON.stringify(o))}}Wi("../../node_modules/card-validator/dist/index.js");var ie={cardNumber:"cardNumber",cardSecurityCode:"cardSecurityCode",cardExpiryDate:"cardExpiryDate",cardholderName:"cardholderName"},po="cardSecurityCodeRecapture";Object.values(ie);function Lu({networks:a,source:t},e){let r=e,i=new Set(r.map(p=>Zt(p).backend)),n=a.map(p=>({...p,allowed:i.has(p.network)})).sort((p,m)=>p.allowed?r.indexOf(p.network)-r.indexOf(m.network):1),o=n.filter(p=>p.allowed),s=t==="REMOTE"&&o.length>1,[l,...c]=n;return{cardNetworkChangeEventData:{detectedCardNetworks:{items:n.map(Jr),preferred:o.length?Jr(o[0]):void 0},...s&&{selectableCardNetworks:{items:o.map(Jr),preferred:o.length?Jr(o[0]):void 0}},source:t},binDataAvailableEventData:{preferred:l,alternatives:c,status:t==="REMOTE"?"complete":"partial"}}}function Jr({network:a,displayName:t,allowed:e}){return{network:a,displayName:t,allowed:e}}function Ru(a,t){return{cardNumber:yr(a,ie.cardNumber),cardSecurityCode:yr(a,ie.cardSecurityCode),cardExpiryDate:yr(a,ie.cardExpiryDate),cardholderName:yr(a,ie.cardholderName,t?.cardholderName)}}function yr(a,t,e){let r=document.createElement("iframe"),i=ts(a,t,e);return r.src=`${Iu}#${i}`,r.setAttribute("tabindex","0"),r.setAttribute("frameBorder","0"),r.style.border="none",r.style.boxSizing="border-box",r.style.height="20px",r.style.width="100%",r.style.colorScheme="auto",r}var oa=class extends Ee{constructor(e,r){super(e,r);S(this,"iframes");this.iframes=Ru(r.checkoutSessionId,{cardholderName:r.clientOptions.card?.cardholderName?.defaultValue})}async start(){try{let{action:e}=await this.callbacks.onStart();if(e==="abort")return this.callbacks.onFinish(void 0,new R({message:"Payment creation aborted",code:x.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type}));let r=await this.tokenize();this.callbacks.onFinish(r)}catch(e){this.callbacks.onFinish(void 0,e)}}async tokenize(){let{error:e,data:r}=await this.context.pciApi.postCardPaymentInstruments();if(e||!r)throw e??new F({code:x.TOKENIZATION_ERROR,message:"Unable to tokenize payment method",paymentMethod:B.PAYMENT_CARD});return r}};function wu(a){if(!a)return{};let t=a.indexOf(" ");return t===-1?{firstName:a}:{firstName:a.substring(0,t),lastName:a.substring(t+1)}}function Ei(a){let{firstName:t,lastName:e}=wu(a.name);return{firstName:t||null,lastName:e||null,addressLine1:a.address1||null,addressLine2:a.address2||null,city:a.locality||null,state:a.administrativeArea||null,postalCode:a.postalCode||null,countryCode:a.countryCode||null}}function mo(a){return a.map(t=>({id:t.id,label:t.name,description:t.description||""}))}var ho=2,go=0,xu="https://pay.google.com/gp/p/js/pay.js",_u={AMEX:"AMEX",DISCOVER:"DISCOVER",INTERAC:"INTERAC",JCB:"JCB",MASTERCARD:"MASTERCARD",VISA:"VISA"},yo=["AMEX","DISCOVER","INTERAC","JCB","MASTERCARD","VISA"],qr={FEE:"fee_label_fallback",ITEM:"item_label_fallback",SHIPPING:"shipping",SUBTOTAL:"subtotal"},Qr={FEE:"Fee",ITEM:"Item",SHIPPING:"Shipping",SUBTOTAL:"Subtotal"},Ou="buy",Du="black",Bu="fill",sa=class extends Ee{constructor(){super(...arguments);S(this,"disabled",!1);S(this,"client",null)}async setDisabled(e){this.disabled=e}translate(e,r){return this.context.translate?.(e,r)??r}async tokenize(){throw new F({code:x.TOKENIZATION_ERROR,message:"Google Pay does not support direct tokenization",paymentMethod:B.GOOGLE_PAY})}async loadGooglePayScript(){if(typeof google<"u"&&google.payments?.api?.PaymentsClient)return!0;try{return await Xi(xu),!0}catch{return C.error("Failed to load Google Pay script"),!1}}async setup(){let{countryCode:e,currencyCode:r}=this.context.configuration.clientSession.order;if(!e)throw new R({code:wt.MISSING_PARAMETER,message:"Cannot initialize Google Pay: missing country code",paymentMethod:B.GOOGLE_PAY});if(!r)throw new R({code:wt.MISSING_PARAMETER,message:"Cannot initialize Google Pay: missing currency code",paymentMethod:B.GOOGLE_PAY});if(!await this.loadGooglePayScript())return C.error("Google Pay script failed to load"),!1;let n=this.context.configuration.env==="PRODUCTION"?"PRODUCTION":"TEST";this.client=new google.payments.api.PaymentsClient({environment:n,...this.needsPaymentDataCallbacks()&&{paymentDataCallbacks:{onPaymentDataChanged:s=>this.handlePaymentDataChanged(s)}}});try{let{result:s,paymentMethodPresent:l}=await this.client.isReadyToPay(this.buildIsReadyToPayRequest());if(!s)return C.info("Google Pay is not available in this browser/device"),!1;if(this.clientOptions?.existingPaymentMethodRequired&&l===!1)return C.info("Google Pay: existingPaymentMethodRequired is true but no existing payment method is available"),!1}catch(s){return C.error("Google Pay isReadyToPay check failed",{error:s}),!1}let o=this.context.onClientConfigurationUpdate(s=>{let l=s.clientSession?.order;(!l||!l.totalOrderAmount||!l.currencyCode)&&C.warn("Google Pay: Order details are missing or incomplete after client session update. Ensure order details (totalOrderAmount, currencyCode, countryCode) are always provided.")});return this.context.subscribeToTeardown(o),!0}needsPaymentDataCallbacks(){return!!(this.clientOptions?.requireShippingMethod||this.shouldCaptureShippingAddress)}buildIsReadyToPayRequest(){return{apiVersion:ho,apiVersionMinor:go,allowedPaymentMethods:[this.allowedPaymentMethod],existingPaymentMethodRequired:this.clientOptions?.existingPaymentMethodRequired}}async render(e){if(!this.client)return void C.error("Google Pay client not initialized. Call setup() first.");let r=this.client.createButton({buttonType:this.clientOptions?.buttonType??Ou,buttonColor:this.clientOptions?.buttonColor??Du,buttonSizeMode:this.clientOptions?.buttonSizeMode??Bu,buttonRadius:this.clientOptions?.buttonRadius,buttonLocale:this.clientOptions?.buttonLocale,buttonBorderType:this.clientOptions?.buttonBorderType,onClick:i=>this.handleClick(i),buttonRootNode:e instanceof ShadowRoot?e:void 0});e.appendChild(r)}async handleClick(e){if(this.disabled)return;if(!this.client)return void C.error("Google Pay client not available");let r=this.callbacks.onStart();Le({eventName:"PAYMENT_METHOD_SELECTION",paymentMethod:B.GOOGLE_PAY});try{let i=await this.client.loadPaymentData(this.buildPaymentDataRequest()),{action:n}=await r;if(n==="abort")throw new R({message:"Payment creation aborted",code:x.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type});await this.processPaymentData(i)}catch(i){if(i.statusCode==="CANCELED")return void this.context.clientSessionApi.unselectPaymentMethod();C.errorWithDatadog("Google Pay error",{error:i}),this.callbacks.onFinish(void 0,i)}}get clientOptions(){return this.context.clientOptions.googlePay}get shouldCaptureShippingAddress(){return!!(this.clientOptions?.captureShippingAddress||this.clientOptions?.shippingAddressParameters)}async processPaymentData(e){if(this.clientOptions?.captureBillingAddress&&await this.updateBillingAddress(e),(this.shouldCaptureShippingAddress||this.clientOptions?.requireShippingMethod||this.clientOptions?.emailRequired)&&await this.updateShippingDetails(e),this.clientOptions?.requireShippingMethod){let n=e.shippingOptionData?.id;n&&await this.context.clientSessionApi.selectShippingMethod(n)}let{data:r,error:i}=await this.context.pciApi.postGooglePayPaymentInstruments({flow:"GATEWAY",network:e.paymentMethodData.info?.cardNetwork??"OTHER",merchant_id:this.config.options.merchantId,encrypted_payload:Cr.encode(e.paymentMethodData.tokenizationData.token)});if(i||!r)throw this.callbacks.onFinish(void 0,i),i??new F({code:x.TOKENIZATION_ERROR,message:"Failed to tokenize payment data",paymentMethod:B.GOOGLE_PAY});this.callbacks.onFinish(r)}async updateBillingAddress(e){let r=e.paymentMethodData.info?.billingAddress;if(r){let i=Ei(r);await this.context.clientSessionApi.setBillingAddress(i)}else C.warn("Google Pay: Could not retrieve billing address from payment data")}async updateShippingDetails(e){let r=e.shippingAddress,i=e.email,n=r?.phoneNumber;if(r||n||i){let o=r?Ei(r):void 0;await this.context.clientSessionApi.setShippingAddress(o,n,i)}else C.warn("Google Pay: No shipping address, phone number, or email found in payment data")}async handlePaymentDataChanged(e){let r=e.callbackTrigger;try{if(r==="SHIPPING_OPTION"){let i=e.shippingOptionData?.id;return i&&await this.context.clientSessionApi.selectShippingMethod(i),{newTransactionInfo:this.getCurrentTransactionInfo()}}if(r==="SHIPPING_ADDRESS"||r==="INITIALIZE"){let i=e.shippingAddress;if(i){let s=Ei(i);await this.context.clientSessionApi.setShippingAddress(s)}let n=this.getShippingModule(),o=n?.shippingMethods||[];return{...this.clientOptions?.requireShippingMethod&&o.length>0&&{newShippingOptionParameters:{shippingOptions:mo(o),defaultSelectedOptionId:n?.selectedShippingMethod||o[0]?.id}},newTransactionInfo:this.getCurrentTransactionInfo()}}return{newTransactionInfo:this.getCurrentTransactionInfo()}}catch(i){return C.errorWithDatadog("Google Pay: Error handling payment data change",{error:i}),{error:{reason:"OTHER_ERROR",message:"An error occurred while processing your request",intent:r==="SHIPPING_OPTION"?"SHIPPING_OPTION":"SHIPPING_ADDRESS"}}}}getShippingModule(){return this.context.configuration.checkoutModules?.find(i=>i.type==="SHIPPING")?.options}getCurrentTransactionInfo(){let{countryCode:e,currencyCode:r,merchantAmount:i,totalOrderAmount:n}=this.context.configuration.clientSession.order;return{countryCode:e,currencyCode:r,displayItems:this.getDisplayItems(),totalPriceStatus:"FINAL",totalPrice:hr(i??n,r),totalPriceLabel:"Total"}}getDisplayItems(){let e=this.context.configuration.clientSession.order,{currencyCode:r,merchantAmount:i,lineItems:n,fees:o,shipping:s}=e,l=this.clientOptions?.requireShippingMethod,c=[];return i?(c.push({label:this.translate(qr.SUBTOTAL,Qr.SUBTOTAL),type:"SUBTOTAL",price:hr(i,r)}),c):(n&&n.length>0&&n.forEach(p=>{c.push({label:p.description||this.translate(qr.ITEM,Qr.ITEM),type:"LINE_ITEM",price:hr(p.amount,r)})}),o&&o.length>0&&o.filter(p=>p.amount!==0).forEach(p=>{c.push({label:p.type||p.description||this.translate(qr.FEE,Qr.FEE),type:"LINE_ITEM",price:hr(p.amount,r)})}),l&&s&&s.amount!==0&&c.push({label:s.methodName||this.translate(qr.SHIPPING,Qr.SHIPPING),type:"LINE_ITEM",price:hr(s.amount,r)}),c)}get allowedCardNetworks(){let e=this.context.configuration.clientSession.paymentMethod?.orderedAllowedCardNetworks;if(!e||e.length===0)return yo;let r=e.map(i=>_u[i]).filter(i=>!!i);return r.length>0?r:yo}get allowedPaymentMethod(){let e=this.clientOptions?.captureBillingAddress;return{type:"CARD",parameters:{allowedAuthMethods:["PAN_ONLY","CRYPTOGRAM_3DS"],allowedCardNetworks:this.allowedCardNetworks,...e&&{billingAddressRequired:!0,billingAddressParameters:{format:"FULL"}}}}}buildPaymentDataRequest(){let e=this.clientOptions?.shippingAddressParameters,r=this.clientOptions?.emailRequired,i=this.clientOptions?.requireShippingMethod,n=this.getShippingModule(),o=n?.shippingMethods,s=n?.selectedShippingMethod;return{apiVersion:ho,apiVersionMinor:go,...r&&{emailRequired:!0},...(this.shouldCaptureShippingAddress||i)&&{shippingAddressRequired:!0,...e&&{shippingAddressParameters:{...e.allowedCountryCodes&&{allowedCountryCodes:e.allowedCountryCodes},...e.phoneNumberRequired&&{phoneNumberRequired:!0}}}},...i&&{shippingOptionRequired:!0,...o&&o.length>0&&{shippingOptionParameters:{shippingOptions:mo(o),defaultSelectedOptionId:s||o[0]?.id}}},...this.needsPaymentDataCallbacks()&&{callbackIntents:[...i?["SHIPPING_ADDRESS","SHIPPING_OPTION"]:["SHIPPING_ADDRESS"]]},transactionInfo:this.getCurrentTransactionInfo(),merchantInfo:{merchantId:this.config.options.merchantId,merchantName:this.config.options.merchantName},allowedPaymentMethods:[{...this.allowedPaymentMethod,tokenizationSpecification:{type:"PAYMENT_GATEWAY",parameters:{gateway:"primer",gatewayMerchantId:this.config.options.merchantId}}}]}}},Gu="https://x.klarnacdn.net/kp/lib/v1/api.js",la=class extends Error{constructor(){super("Klarna authorization cancelled by user"),this.name="KlarnaUserCancelledError"}},da=class extends Ee{constructor(){super(...arguments);S(this,"session",null);S(this,"selectedCategoryId",null)}getCategories(){let e=this.session?.categories??[],r=this.context.clientOptions.klarna?.allowedPaymentCategories;return r?r.map(i=>e.find(n=>n.identifier===i)).filter(i=>i!=null):e}setSelectedCategory(e){this.selectedCategoryId=e}async setup(){try{return await Xi(Gu,{crossorigin:""}),window.Klarna?.Payments?(this.session=await this.createSession(),this.session?this.getCategories().length===0?(C.warn("No Klarna payment categories available"),!1):(window.Klarna.Payments.init({client_token:this.session.clientToken}),!0):!1):(C.error("Klarna SDK failed to load"),!1)}catch(e){return C.error("Klarna setup failed",e),!1}}get isRecurring(){return this.context.clientOptions.klarna?.paymentFlow==="PREFER_VAULT"}async createSession(){let{clientSession:e}=this.context.configuration,r=e.order,i={localeCode:this.context.locale,countryCode:r?.countryCode??"",currencyCode:r?.currencyCode??""},n;if(this.isRecurring)n={sessionType:"RECURRING_PAYMENT",paymentMethodConfigId:this.config.id,localeData:i,description:this.context.clientOptions.klarna?.recurringPaymentDescription};else{if(!r?.lineItems||r.lineItems.length===0)return C.error("Klarna requires order.lineItems to be provided"),null;let l=r.lineItems.map(p=>({name:p.name||p.description||"",unitAmount:p.amount,reference:p.itemId,quantity:p.quantity,discountAmount:p.discountAmount,taxCode:p.taxCode,taxAmount:p.taxAmount,productType:p.productType})),c=r.merchantAmount??r.totalOrderAmount??0;n={sessionType:"ONE_OFF_PAYMENT",paymentMethodConfigId:this.config.id,localeData:i,totalAmount:c,orderItems:l}}let{data:o,error:s}=await this.context.coreApi.createKlarnaSession(n);return s||!o?(C.error("Failed to create Klarna session",s),null):o}async renderCategory(e){if(!window.Klarna?.Payments)throw new F({message:"Klarna SDK not loaded",code:x.TOKENIZATION_ERROR,paymentMethod:this.config.type});let{Payments:r}=window.Klarna,i=(typeof e.containerId=="string",e.containerId);return e.onHeightChange&&r.on("heightChanged",e.onHeightChange),new Promise((n,o)=>{r.load({container:i,payment_method_category:e.paymentMethodCategoryId},s=>{s.error?o(new F({message:`Klarna load failed: ${s.error.invalid_fields?.join(", ")}`,code:x.TOKENIZATION_ERROR,paymentMethod:this.config.type})):(this.selectedCategoryId=e.paymentMethodCategoryId,n())})})}async authorize(e){if(!window.Klarna?.Payments)throw new F({message:"Klarna SDK not loaded",code:x.TOKENIZATION_ERROR,paymentMethod:this.config.type});let{Payments:r}=window.Klarna;return new Promise(i=>{r.authorize({payment_method_category:e},void 0,i)})}async finalizeSession(){if(!this.session)return null;let{data:e,error:r}=await this.context.coreApi.finalizeKlarnaSession({sessionId:this.session.sessionId,paymentMethodConfigId:this.config.id});return r||!e?(C.error("Failed to finalize Klarna session",r),null):e}async createCustomerToken(e){if(!this.session)return null;let r=this.context.clientOptions.klarna?.recurringPaymentDescription;if(!r)return C.error("klarna.recurringPaymentDescription must be provided for PREFER_VAULT flow"),null;let{clientSession:i}=this.context.configuration,n=i.order,{data:o,error:s}=await this.context.coreApi.createKlarnaCustomerToken({paymentMethodConfigId:this.config.id,sessionId:this.session.sessionId,authorizationToken:e,description:r,localeData:{localeCode:this.context.locale,countryCode:n?.countryCode??"",currencyCode:n?.currencyCode??""}});return s||!o?(C.error("Failed to create Klarna customer token",s),null):o}async tokenize(){if(!this.selectedCategoryId)throw new F({message:"No Klarna payment category selected",code:x.TOKENIZATION_ERROR,paymentMethod:this.config.type});let e=await this.authorize(this.selectedCategoryId);if(!e.approved&&!e.error)throw C.debug("Klarna authorization cancelled by user"),new la;if(!e.approved||!e.authorization_token){let r=e.error?.invalid_fields?.join(", ")||"Authorization failed";throw new F({message:`Klarna authorization failed: ${r}`,code:x.TOKENIZATION_ERROR,paymentMethod:this.config.type})}return this.isRecurring?this.tokenizeWithCustomerToken(e.authorization_token):this.tokenizeWithAuthToken(e.authorization_token)}async tokenizeWithAuthToken(e){let r=await this.finalizeSession();if(!r)throw new F({message:"Failed to finalize Klarna session",code:x.TOKENIZATION_ERROR,paymentMethod:this.config.type});let{data:i,error:n}=await this.context.pciApi.postKlarnaPaymentInstruments({klarnaAuthorizationToken:e,sessionData:r.sessionData});if(n||!i)throw n??new F({message:"Failed to tokenize Klarna payment",code:x.TOKENIZATION_ERROR,paymentMethod:this.config.type});return i}async tokenizeWithCustomerToken(e){let r=await this.createCustomerToken(e);if(!r)throw new F({message:"Failed to create Klarna customer token",code:x.TOKENIZATION_ERROR,paymentMethod:this.config.type});let{data:i,error:n}=await this.context.pciApi.postKlarnaCustomerTokenInstruments({klarnaCustomerToken:r.customerTokenId,sessionData:r.sessionData});if(n||!i)throw n??new F({message:"Failed to tokenize Klarna payment",code:x.TOKENIZATION_ERROR,paymentMethod:this.config.type});return i}async start(){try{let{action:e}=await this.callbacks.onStart();if(e==="abort")return this.callbacks.onFinish(void 0,new Error("Payment aborted"));let r=await this.tokenize();this.callbacks.onFinish(r)}catch(e){if(e instanceof la)return void this.context.clientSessionApi.unselectPaymentMethod();this.callbacks.onFinish(void 0,e)}}async startWithCategory(e){return this.selectedCategoryId=e,this.start()}},Ku=100;function en({height:a,name:t,url:e="",width:r}){let i=new Set,n=window.open(e,t,Uu({height:a,width:r}));if(!n)return;function o(){n?.close(),s()}function s(){i.forEach(l=>l()),i.clear(),window.removeEventListener("beforeunload",o)}return window.addEventListener("beforeunload",o),Fu(n).then(s),{close:o,focus(){n.focus()},get isOpen(){return n?.closed===!1},onClose(l){return i.add(l),()=>{i.delete(l)}},setContent(l){n.document.write(l)},setUrl(l){n.location.replace(l)}}}var Fu=a=>new Promise(t=>{let e=setInterval(()=>{a.closed&&(clearInterval(e),t())},Ku)});function Uu(a){let t=Vu({parent:{left:window.screenLeft,top:window.screenTop,height:window.outerHeight,width:window.outerWidth},popup:a});return Hu(t)}var Vu=({parent:a,popup:t})=>({left:a.left+(a.width-t.width)/2,top:a.top+(a.height-t.height)/2,height:t.height,width:t.width}),Hu=a=>Object.entries(a).map(t=>t.join("=")).join(",");function xt(a){return a?new Promise(t=>{setTimeout(t,a)}):Promise.resolve()}function tn(a,t){return a?.redirect?.returnUrl?!0:(C.warn(`[Primer SDK] ${t} is enabled in your client session but \`options.redirect.returnUrl\` is missing. This payment method may redirect the customer to an external page; without a return URL the customer cannot be brought back. The payment method will not be available in this checkout. Set \`options.redirect.returnUrl\` to a page that re-initializes the SDK with the \`?clientToken=...\` query parameter Primer appends on return.`),!1)}function Yu(a,t){if(a?.redirect?.returnUrl)return;let e=typeof window<"u"&&window.location?window.location.href:"";C.warn(`[Primer SDK] Initiating ${t} which may redirect the customer to an external page, but no \`options.redirect.returnUrl\` is configured. The customer will be returned to the current page (${e}). Set \`options.redirect.returnUrl\` to control the return destination.`),Le({eventName:"REDIRECT_RETURN_URL_NOT_CONFIGURED",paymentMethod:t})}function rn(a,t,e){let r="";try{r=new URL(a).origin}catch{r=""}C.info(`[Primer SDK] Redirecting to ${t} payment page at ${r} (${e})`),Le({eventName:"PAYMENT_REDIRECT_TO_THIRD_PARTY",paymentMethod:t,redirectDestinationUrl:r,redirectReason:e})}function fo(a,t={}){C.info(`[Primer SDK] Returned from third-party payment page (${a})`),Le({eventName:"PAYMENT_RETURNED_FROM_THIRD_PARTY",intent:a,...t})}var Mi="Adyen Klarna",ca=class extends Ee{constructor(){super(...arguments);S(this,"paymentTypes",[]);S(this,"popup");S(this,"shouldRedirect",!1);S(this,"redirectReason","force_redirect");S(this,"dialogPromise");S(this,"selectedOptionId",null)}get assets(){let{displayMetadata:e,name:r}=this.config;return{icon:e?.button?.iconUrl??{},logo:e?.overlay?.logo??e?.button?.iconUrl??{},backgroundColor:e?.button?.backgroundColor??e?.overlay?.backgroundColor??{},name:r}}get logoSrc(){return this.assets.logo.colored||this.assets.logo.light||this.assets.icon.colored||this.assets.icon.light||""}async setup(){if(!tn(this.context.clientOptions,this.config.type))return!1;try{let{data:e,error:r}=await this.context.coreApi.getPaymentMethodOptions(this.config.id);return r?(C.error("Failed to fetch Adyen Klarna payment types",r),!1):e?.result?.length?(this.paymentTypes=e.result,this.paymentTypes.length===1&&(this.selectedOptionId=this.paymentTypes[0].name),!0):(C.warn("No Adyen Klarna payment types available for this currency/country combination"),!1)}catch(e){return C.error("Adyen Klarna setup failed",e),!1}}getOptions(){return this.paymentTypes.map(e=>({id:e.name,label:e.id}))}selectOption(e){this.selectedOptionId=e}async tokenize(){if(!this.selectedOptionId)throw new F({message:"No Adyen Klarna payment type selected",code:x.TOKENIZATION_ERROR,paymentMethod:this.config.type});let{error:e,data:r}=await this.context.pciApi.postAdyenKlarnaPaymentInstruments({type:"OFF_SESSION_PAYMENT",paymentMethodType:this.config.type,paymentMethodConfigId:this.config.id,sessionInfo:{locale:this.context.locale,platform:Ar()?"MOBILE_WEB":"WEB",browserInfo:Rt(),paymentMethodType:this.selectedOptionId,merchantRedirectUrl:this.context.clientOptions.redirect?.returnUrl}});if(e||!r)throw e??new F({message:"Unable to tokenize Adyen Klarna payment",code:x.TOKENIZATION_ERROR,paymentMethod:this.config.type});return r}async createPayment(e){try{let r=await super.createPayment(e),i=this.validateAndDecodeClientToken(r);if(this.shouldRedirect&&(rn(i.redirectUrl,this.config.type,this.redirectReason),window.location.assign(i.redirectUrl),await new Promise(()=>{})),!this.popup?.isOpen)return this.cancelPayment(r);this.popup.setUrl(i.redirectUrl);let n=await this.waitForPaymentCompletion(i.statusUrl);if(this.cleanup(),"error"in n)throw n.error;if(this.wasPopupClosedWithoutCompletion(n))return this.cancelPayment(r);let o=await this.getResumeToken(n,i.statusUrl);return await this.resumePayment(r.id,o)}catch(r){throw this.cleanup(),r}}async start(){try{this.config.forceRedirect||!!this.context.clientOptions.redirect?.forceRedirect?(this.shouldRedirect=!0,this.redirectReason="force_redirect"):Qi()&&(this.shouldRedirect=!0,this.redirectReason="in_app_browser"),this.showOverlayDialog(),this.shouldRedirect||(this.openPopup(),this.popup&&await xt(300),this.popup?.isOpen||(this.shouldRedirect=!0,this.redirectReason="popup_blocked"));let{action:r}=await this.callbacks.onStart();if(r==="abort")throw this.cleanup(),new R({message:"Payment creation aborted",code:x.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type});let i=await this.tokenize();this.callbacks.onFinish(i)}catch(e){this.cleanup(),this.callbacks.onFinish(void 0,e)}}cleanup(){this.popup?.close(),this.context.dialogProvider.close()}cancelPayment(e){return this.context.clientSessionApi.unselectPaymentMethod(e),this.cleanup(),{...e,cancelled:!0}}validateAndDecodeClientToken(e){let r=e.requiredAction?.clientToken;if(!r)throw new F({message:"No client token provided for Adyen Klarna redirect"});let i=ht(r);if(!jo(i,this.config.type))throw new F({message:"Invalid Adyen Klarna client token"});return i}async waitForPaymentCompletion(e){let r=this.dialogPromise?.then(()=>({id:"",popupClosed:!0}))??Promise.resolve({id:"",popupClosed:!0}),i=new Promise(l=>{this.popup?.onClose(()=>l({id:"",popupClosed:!0}))}),{promise:n,abort:o}=this.pollStatus(e),s=await Promise.race([r,i,n]);return o(),s}wasPopupClosedWithoutCompletion(e){return"popupClosed"in e&&!!e.popupClosed&&!this.context.clientOptions.redirect?.resumePaymentOnPopupClosure}async getResumeToken(e,r){if(e.id)return e.id;let{data:i,error:n}=await this.context.pciApi.getResumeStatus(r);if(n||!i?.id)throw n??new Error("Unable to get resume token");return i.id}showOverlayDialog(){let e=this.assets.backgroundColor.colored||this.assets.backgroundColor.light||"#FFB3C7",r=document.createElement("div");r.setAttribute("style","display: flex; flex-direction: column; gap: var(--primer-size-xlarge);");let i=document.createElement("div");if(i.setAttribute("style",`display: flex;margin:auto;padding:calc(var(--primer-size-small)*0.5);height: var(--primer-size-xlarge);background-color: ${e};border-radius:var(--primer-radius-small);`),this.logoSrc){let o=document.createElement("img");o.src=this.logoSrc,o.setAttribute("style","height:100%;"),i.appendChild(o)}r.appendChild(i);let n=document.createElement("p");n.setAttribute("style","max-width: 300px;text-align: center;"),n.innerText=this.context.translate("paymentMethodPopupOverlayDescription","Having trouble viewing the {paymentMethodName} payment page? We'll help you find it!").replace("{paymentMethodName}",this.assets.name),r.appendChild(n),this.dialogPromise=this.context.dialogProvider.show({htmlContent:r,showCloseButton:!0,size:"flex",cta:{label:this.context.translate("paymentMethodPopupOverlayBringBackThePaymentPage","Bring back the payment page"),icon:"chevron-left",onClick:()=>this.popup?.focus()}}).then(()=>{})}openPopup(){let{name:e,displayMetadata:{popup:r}}=this.config;this.popup=en({name:e,height:r?.height??1e3,width:r?.width??1200}),this.popup?.setContent(this.createPopupLoadingContent())}createPopupLoadingContent(){let e=this.context.translate("paymentMethodPopupLoadingScreenText","Hold on! {paymentMethodName} is loading.").replace("{paymentMethodName}",Mi);return`
|
|
37
37
|
<!DOCTYPE html>
|
|
38
38
|
<html>
|
|
39
39
|
<head>
|
|
@@ -67,7 +67,7 @@ import{a as jr,b as q,c as bi,d,e as S}from"./chunks/chunk.QNO3CTH5.js";var nc=q
|
|
|
67
67
|
<div class="message">${e}</div>
|
|
68
68
|
</body>
|
|
69
69
|
</html>
|
|
70
|
-
`}pollStatus(e){let r=!0;return{promise:(async()=>{for(;r;){let{data:n,error:o}=await this.context.pciApi.getResumeStatus(e);if(o)return{error:o instanceof Error?o:new Error(String(o))};if(n?.status==="COMPLETE")return{id:n.id};await xt(1e3)}return{id:""}})(),abort:()=>{r=!1}}}},ua=class extends Ee{constructor(){super(...arguments);S(this,"phoneNumber","")}setPhoneNumber(e){this.phoneNumber=e}getPhoneNumber(){return this.phoneNumber}clearPhoneNumber(){this.phoneNumber=""}async start(){try{let{action:e}=await this.callbacks.onStart();if(e==="abort")return this.callbacks.onFinish(void 0,new R({message:"Payment creation aborted",code:O.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type}));let r=await this.tokenize();this.callbacks.onFinish(r)}catch(e){this.callbacks.onFinish(void 0,e)}}async tokenize(){if(!/^\+\d{10,15}$/.test(this.phoneNumber))throw new F({message:"Phone number must include country prefix and 10\u201315 digits",code:O.TOKENIZATION_ERROR,paymentMethod:this.config.type});let e={type:"OFF_SESSION_PAYMENT",paymentMethodType:this.config.type,paymentMethodConfigId:this.config.id,sessionInfo:{locale:this.context.locale,platform:Ar()?"MOBILE_WEB":"WEB",browserInfo:Rt(),phoneNumber:this.phoneNumber}};try{let{error:r,data:i}=await this.context.pciApi.postMbwayPaymentInstruments(e);if(this.clearPhoneNumber(),r||!i)throw r??new F({message:"Unable to tokenize MB WAY payment method",code:O.TOKENIZATION_ERROR,paymentMethod:this.config.type});return i}catch(r){throw this.clearPhoneNumber(),r}}async createPayment(e){let r=await super.createPayment(e);if(r.status==="FAILED"||!r.requiredAction)return r;let i=r.requiredAction.clientToken;if(!i)throw new le({message:"No client token provided for MB WAY payment",code:aa.MISSING_CLIENT_TOKEN,response:{id:r.id,data:r}});let n=ht(i);if(!this.isValidMbwayClientToken(n))throw new le({message:"Invalid MB WAY client token: missing statusUrl or incorrect intent",code:aa.INVALID_CLIENT_TOKEN,response:{id:r.id,data:r}});let o=await this.context.pciApi.pollResumeStatus(n.statusUrl,{timeout:864e5,isComplete:l=>!!l.error||l.data?.status==="COMPLETE"});if(o.error)throw o.error;let s=o.data?.id;if(!s){let l=await this.context.pciApi.getResumeStatus(n.statusUrl);if(l.error||!l.data?.id)throw l.error??new Error("Unable to get resume token");s=l.data.id}return await this.resumePayment(r.id,s)}isValidMbwayClientToken(e){if(typeof e!="object"||e===null)return!1;let r=e;return!(r.intent!=="ADYEN_MBWAY_REDIRECTION"||!("statusUrl"in r)||typeof r.statusUrl!="string"||!r.statusUrl)}};function $u(a,t){var e={};for(var r in a)Object.prototype.hasOwnProperty.call(a,r)&&t.indexOf(r)<0&&(e[r]=a[r]);if(a!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(a);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(a,r[i])&&(e[r[i]]=a[r[i]]);return e}function zu(a,t){var e=document.querySelector('script[src="'.concat(a,'"]'));if(e===null)return null;var r=rs(a,t),i=e.cloneNode();if(delete i.dataset.uidAuto,Object.keys(i.dataset).length!==Object.keys(r.dataset).length)return null;var n=!0;return Object.keys(i.dataset).forEach(function(o){i.dataset[o]!==r.dataset[o]&&(n=!1)}),n?e:null}function ju(a){var t=a.url,e=a.attributes,r=a.onSuccess,i=a.onError,n=rs(t,e);n.onerror=i,n.onload=r,document.head.insertBefore(n,document.head.firstElementChild)}function Wu(a){var t=a.sdkBaseUrl,e=a.environment,r=$u(a,["sdkBaseUrl","environment"]),i=t||qu(e),n=r,o=Object.keys(n).filter(function(c){return n[c]!==void 0&&n[c]!==null&&n[c]!==""}).reduce(function(c,p){var m=n[p].toString();return p=Zu(p),p.substring(0,4)==="data"||p==="crossorigin"?c.attributes[p]=m:c.queryParams[p]=m,c},{queryParams:{},attributes:{}}),s=o.queryParams,l=o.attributes;return s["merchant-id"]&&s["merchant-id"].indexOf(",")!==-1&&(l["data-merchant-id"]=s["merchant-id"],s["merchant-id"]="*"),{url:"".concat(i,"?").concat(Ju(s)),attributes:l}}function Zu(a){var t=function(e,r){return(r?"-":"")+e.toLowerCase()};return a.replace(/[A-Z]+(?![a-z])|[A-Z]/g,t)}function Ju(a){var t="";return Object.keys(a).forEach(function(e){t.length!==0&&(t+="&"),t+=e+"="+a[e]}),t}function qu(a){return a==="sandbox"?"https://www.sandbox.paypal.com/sdk/js":"https://www.paypal.com/sdk/js"}function rs(a,t){t===void 0&&(t={});var e=document.createElement("script");return e.src=a,Object.keys(t).forEach(function(r){e.setAttribute(r,t[r]),r==="data-csp-nonce"&&e.setAttribute("nonce",t["data-csp-nonce"])}),e}function Qu(a,t){if(t===void 0&&(t=Promise),as(a,t),typeof document>"u")return t.resolve(null);var e=Wu(a),r=e.url,i=e.attributes,n=i["data-namespace"]||"paypal",o=vo(n);return i["data-js-sdk-library"]||(i["data-js-sdk-library"]="paypal-js"),zu(r,i)&&o?t.resolve(o):Xu({url:r,attributes:i},t).then(function(){var s=vo(n);if(s)return s;throw new Error("The window.".concat(n," global variable is not available."))})}function Xu(a,t){t===void 0&&(t=Promise),as(a,t);var e=a.url,r=a.attributes;if(typeof e!="string"||e.length===0)throw new Error("Invalid url.");if(r!==void 0&&typeof r!="object")throw new Error("Expected attributes to be an object.");return new t(function(i,n){if(typeof document>"u")return i();ju({url:e,attributes:r,onSuccess:function(){return i()},onError:function(){var o=new Error('The script "'.concat(e,'" failed to load. Check the HTTP status code and response body in DevTools to learn more.'));return n(o)}})})}function vo(a){return window[a]}function as(a,t){if(typeof a!="object"||a===null)throw new Error("Expected an options object.");var e=a.environment;if(e&&e!=="production"&&e!=="sandbox")throw new Error('The `environment` option must be either "production" or "sandbox".');if(t!==void 0&&typeof t!="function")throw new Error("Expected PromisePonyfill to be a function.")}var Xr=new Map,bo={getOrCreateNamespace(a){let t=Xr.get(a);return t?t.namespace:he()},getInstance(a){return Xr.get(a)?.instance??null},storeInstance(a,t,e){Xr.set(a,{instance:t,namespace:e})},hasInstance(a){return Xr.has(a)}};async function ep({context:a,configId:t,paymentMethodType:e,callbacks:r}){try{let{action:i}=await r.onStart();if(i==="abort")throw new R({message:"Payment creation aborted",code:O.PAYMENT_CREATION_ABORTED,paymentMethod:e});let{data:n,error:o}=await a.coreApi.createPaypalBillingAgreement({paymentMethodConfigId:t});if(o||!n){let s=o?.message??"Failed to create billing agreement";throw new R({message:s,code:O.PAYMENT_FAILED,paymentMethod:e})}return n.tokenId}catch(i){throw C.errorWithDatadog("PayPal billing agreement creation failed:",{error:i}),r.onFinish(void 0,i),i instanceof R||i instanceof F?i:new R({message:"Failed to create billing agreement",code:O.PAYMENT_FAILED,paymentMethod:e})}}async function tp({context:a,configId:t,paymentMethodType:e,callbacks:r,data:i}){try{let n=i.billingToken;if(!n)throw new F({message:"Billing token not provided",code:O.TOKENIZATION_ERROR,paymentMethod:e});let{data:o,error:s}=await a.coreApi.confirmPaypalBillingAgreement({paymentMethodConfigId:t,tokenId:n});if(s||!o){let g=s?.message??"Failed to confirm billing agreement";throw new F({message:g,code:O.TOKENIZATION_ERROR,paymentMethod:e})}let l=o,c={paypalBillingAgreementId:l.billingAgreementId,shippingAddress:l.shippingAddress,externalPayerInfo:l.externalPayerInfo},{error:p,data:m}=await a.pciApi.postPaypalPaymentInstruments(c,{tokenType:"MULTI_USE",paymentFlow:"VAULT"});if(p||!m){let g=p?.message??"Unable to vault PayPal payment method";throw new F({message:g,code:O.TOKENIZATION_ERROR,paymentMethod:e})}r.onFinish(m)}catch(n){throw C.errorWithDatadog("PayPal billing agreement approval failed:",{error:n}),r.onFinish(void 0,n),n instanceof F||n instanceof R?n:new F({message:"Failed to approve billing agreement",code:O.TOKENIZATION_ERROR,paymentMethod:e})}}var rp="gold",ap="black",ip="rect",np="paypal",op="vertical",is="horizontal",Co=2,So=["paypal","paylater"],ns={default:{color:rp},card:{validColors:["black","white"],defaultColor:ap}};function sp(a){if(!a)return;let t=ns[a];if(t&&"validColors"in t)return t}function lp(a,t){let e=sp(t);if(!e)return a??ns.default.color;let r=a??e.defaultColor;return e.validColors.includes(r)?r:(C.warn(`PayPal: Invalid color "${r}" for ${t} button. Only supports: ${e.validColors.join(", ")}. Falling back to "${e.defaultColor}".`),e.defaultColor)}var dp=25,cp=55;function up(a){return parseFloat(a)||0}function pp(a){let t=up(a);return Math.max(dp,Math.min(cp,t))}function mp(a,t,e){let r=t?a?.[t]:void 0,i=r?.tagline??a?.tagline??!1,n=i?is:op,o,s=r?.height??a?.height;s!=null?o=s:e!=null&&(o=pp(String(e)));let l=r?.borderRadius??a?.borderRadius,c=r?.disableMaxWidth??a?.disableMaxWidth,p=r?.color??a?.color;return{color:lp(p,t),shape:r?.shape??a?.shape??ip,label:r?.label??a?.label??np,layout:r?.layout??a?.layout??n,tagline:i,...o!=null&&{height:o},...l!=null&&{borderRadius:l},...c!=null&&{disableMaxWidth:c}}}function hp(a,t,e,r){let i={style:a,onInit:e.onInit,onClick:e.onClick,onCancel:e.onCancel,onError:e.onError};return t&&r?(i.createBillingAgreement=r.createBillingAgreement,i.onApprove=r.onApprove):i.onApprove=e.onApprove,i}function gp(a){if(!a)return;let t={first_name:a.firstName,last_name:a.lastName,address_line_1:a.addressLine1??"",address_line_2:a.addressLine2,city:a.city??"",state:a.state,postal_code:a.postalCode??"",country_code:a.countryCode??""},{address_line_1:e,city:r,postal_code:i,country_code:n}=t;if(!(!e||!r||!i||!n))return t}function yp(a){if(!a)return null;let t=a.purchase_units?.[0]?.shipping;if(!t?.address)return null;let e=t.address,r=t.name;return{firstName:r?.given_name,lastName:r?.surname,addressLine1:e.address_line_1,addressLine2:e.address_line_2,city:e.admin_area_2,state:e.admin_area_1,postalCode:e.postal_code,countryCode:e.country_code}}function fp(a,t,e){let{order:{currencyCode:r,merchantAmount:i,totalOrderAmount:n,shipping:o,lineItems:s=[],fees:l=[]},customer:c}=a;if(!r)throw new R({message:"Currency code is not provided",code:wt.MISSING_PARAMETER,paymentMethod:e});let p={amount:i??n,currencyCode:r,paymentMethodConfigId:t,amountBreakdown:{}},m=c?.shippingAddress,g=gp(m);g&&(p.shipping_address=g);let A=!s.some(M=>!M.name&&!M.description);if(A&&(p.items=s.map(M=>{let{name:w,description:L,taxAmount:I,amount:x,quantity:_}=M,z=I?Math.floor(I/_):0;return{name:L||w||"",unit_amount:{value:x,currency_code:r},quantity:_.toString(),tax:{value:z,currency_code:r}}})),A&&s.length){let M=s.reduce((Z,{amount:U,quantity:ke})=>Z+U*ke,0),w=l?.reduce?.((Z,{amount:U})=>Z+(U??0),0),L=s?.reduce((Z,{discountAmount:U})=>Z+(U??0),0),I=s?.reduce((Z,{taxAmount:U})=>Z+(U??0),0),x=o?.amount??0,_=w??0,z=M+I+x+_-L;p.amountBreakdown={item_total:{value:M,currency_code:r},tax_total:{value:I,currency_code:r},handling:{value:_,currency_code:r},shipping:{value:x,currency_code:r},discount:{value:L,currency_code:r}},p.amount=z}return p}async function vp({context:a,configId:t,paymentMethodType:e,callbacks:r,skipOnStartCallback:i=!1}){try{if(!i){let{action:s}=await r.onStart();if(s==="abort")throw new R({message:"Payment creation aborted",code:O.PAYMENT_CREATION_ABORTED,paymentMethod:e})}let{data:n,error:o}=await a.coreApi.createPaypalOrder(fp(a.configuration.clientSession,t,e));if(o||!n){let s=o?.message??"Unable to create PayPal order";throw new R({message:s,code:O.PAYMENT_FAILED,paymentMethod:e})}return n.orderId}catch(n){throw r.onFinish(void 0,n),n}}async function bp({context:a,paymentMethodType:t,callbacks:e,data:r,actions:i,deferredOnStartCallback:n=!1}){if(n){let{action:m}=await e.onStart();if(m==="abort")throw new R({message:"Payment creation aborted",code:O.PAYMENT_CREATION_ABORTED,paymentMethod:t})}let o=null;try{o=await i?.order?.get()??null}catch(m){C.warn("Failed to get PayPal order details",m)}let s=yp(o),l={external_payer_info:{email:o?.payer?.email_address,external_payer_id:r.payerID??void 0,first_name:o?.payer?.name?.given_name,last_name:o?.payer?.name?.surname},paypal_order_id:r.orderID,paypal_status:o?.status};s&&(l.shipping_address=s);let{error:c,data:p}=await a.pciApi.postPaypalPaymentInstruments(l);if(c||!p){let m=c?.message??"Unable to create payment instrument";throw new F({message:m,code:O.TOKENIZATION_ERROR,paymentMethod:t})}e.onFinish(p)}var Cp=["buttons","funding-eligibility"],Ao=[],Eo="paypal";function os(a){if(!a?.length)return;a.includes(Eo)&&C.warn("PayPal: Cannot disable paypal funding source");let t=a.filter(e=>e!==Eo);return t.length>0?t:void 0}var Sp="authorize";function Ap(a,t,e){return(a??t==="PREFER_VAULT")&&e}function Mo({isVaultFlow:a,configIntent:t}){return a?"tokenize":t??Sp}function Ep(a,t,e,r){let{clientId:i,intent:n}=t.options,o=a.configuration.clientSession.order.currencyCode,s=a.clientOptions.paypal?.disableFunding??(Ao.length>0?Ao:void 0),l=os(s),c=a.clientOptions?.paypal?.enableFunding,p={dataNamespace:e,clientId:i,currency:o,components:Cp,...l&&l.length>0?{disableFunding:l}:{},...c&&c.length>0?{enableFunding:c}:{},integrationDate:a.clientOptions.paypal?.integrationDate,debug:a.clientOptions.paypal?.debug};return(_i||a.decodedClientToken.env==="SANDBOX"||a.decodedClientToken.env==="STAGING")&&(p.buyerCountry=a.clientOptions?.paypal?.buyerCountry),r?(p.vault="true",p.intent=Mo({isVaultFlow:!0,configIntent:n})):(p.vault="false",p.intent=Mo({isVaultFlow:!1,configIntent:n})),p}var pa=class extends Ee{constructor(e,r){super(e,r);S(this,"paypalInstance");S(this,"dataNamespace");S(this,"isVaultFlow",!1);S(this,"isSetupComplete",!1);S(this,"setupPromise");S(this,"eligibleFundingSources",[]);S(this,"currentFundingSource",null);S(this,"onStartDeferred",!1);S(this,"disabled",!1);this.dataNamespace=bo.getOrCreateNamespace(e.id),this.context.onClientConfigurationUpdate(async()=>{C.info("PayPal: Client session updated, refreshing PayPal buttons");try{await this.setup()}catch(i){C.warn("PayPal: Failed to refresh on client session update:",i)}})}async setDisabled(e){this.disabled=e}async tokenize(){throw new F({message:"PayPal does not support direct tokenization",code:O.TOKENIZATION_ERROR,paymentMethod:B.PAYPAL})}async setup(){let{clientId:e}=this.config.options;return this.setupPromise?(C.info("PayPal setup already in progress, waiting..."),this.setupPromise):this.isSetupComplete&&this.paypalInstance?.Buttons?(C.info("PayPal setup already completed, skipping"),!0):e?(this.setupPromise=(async()=>{try{let r=this.context.clientOptions.paypal?.vault,i=this.context.clientOptions.paypal?.paymentFlow,n=this.context.configuration.clientSession.paymentMethod?.vaultOnSuccess??!1;this.isVaultFlow=Ap(r,i,n);let o=Ep(this.context,this.config,this.dataNamespace,this.isVaultFlow);C.debug("%c PAYPAL %c Script Configuration ","background: #0070BA; color: #ffffff; font-weight: bold; padding: 4px 12px; border-radius: 3px 0 0 3px; font-size: 14px;","background: #003087; color: #ffffff; padding: 4px 12px; border-radius: 0 3px 3px 0; font-size: 14px;",o);let s=await Qu(o);if(!s)return C.warn("Failed to load PayPal SDK"),!1;this.paypalInstance=s,bo.storeInstance(this.config.id,s,this.dataNamespace);let l=this.context.clientOptions.paypal?.enableFunding,c=os(this.context.clientOptions.paypal?.disableFunding),m=(s.getFundingSources?.()??[]).filter(g=>s?.isFundingEligible?.(g));return C.debug("PayPal: Eligible funding sources from PayPal SDK:",m),this.eligibleFundingSources=this.filterFundingSources(m,l,c),(l?.length||c?.length)&&(C.debug("PayPal: Primer SDK options:",{enableFunding:l??[],disableFunding:c??[]}),C.debug("PayPal: Funding sources after Primer SDK filter:",this.eligibleFundingSources)),this.eligibleFundingSources.length===0?(C.warn("PayPal: No funding sources are eligible with current configuration"),!1):!0}catch(r){return C.warn("PayPal setup failed:",{error:r}),this.setupPromise=void 0,!1}})(),this.setupPromise):(C.warn("PayPal clientId is required"),!1)}async render(e,r){let{Buttons:i}=this.paypalInstance;if(!i)throw new R({message:"PayPal Buttons component not available",code:wt.INVALID_USAGE,paymentMethod:B.PAYPAL});let n=this.context.clientOptions.paypal?.style,o=r?.style?.buttonHeight,s=n?.layout===is,l={onInit:this.handleInit.bind(this),onClick:this.handleClick.bind(this),onApprove:this.handleApprove.bind(this),onCancel:this.handleCancel.bind(this),onError:this.handleError.bind(this)},c=this.isVaultFlow?{createBillingAgreement:()=>ep({context:this.context,configId:this.config.id,paymentMethodType:this.config.type,callbacks:this.callbacks}),onApprove:M=>tp({context:this.context,configId:this.config.id,paymentMethodType:this.config.type,callbacks:this.callbacks,data:M})}:void 0,p=this.eligibleFundingSources,m=[];for(let M of p){let w=mp(n,M,o),L=hp(w,this.isVaultFlow,l,c);this.isVaultFlow||(L.createOrder=this.handleCreateOrder.bind(this));let I=i({...L,fundingSource:M});I.isEligible()?m.push({button:I,fundingSource:M}):C.debug(`PayPal: Button for "${M}" is not eligible with current config`)}if(m.length===0)throw C.warn("PayPal: No buttons were eligible to render with current configuration"),new R({message:"No PayPal buttons eligible to render",code:wt.INVALID_USAGE,paymentMethod:B.PAYPAL});let g=s&&m.length>Co?this.selectButtonsForHorizontalLayout(m):m;s&&this.applyHorizontalLayoutStyles(e,g.length);let A=g.map(({button:M})=>M.render(e));await Promise.all(A)}selectButtonsForHorizontalLayout(e){let r=new Set(So),i=So.map(o=>e.find(s=>s.fundingSource===o)).filter(o=>o!==void 0),n=e.filter(o=>!r.has(o.fundingSource));return[...i,...n].slice(0,Co)}applyHorizontalLayoutStyles(e,r){e.style.display="grid",e.style.gridTemplateColumns=`repeat(${r}, 1fr)`,e.style.gap="10px"}handleInit(e,r){let{clientSession:i}=this.context.configuration,n=!!i.order.currencyCode,o=!!i.order.totalOrderAmount||!!i.order.merchantAmount;if(!n||!o){C.warn("PayPal button disabled: missing currency or amount"),r.disable();return}r.enable()}handleClick(e,r){return this.currentFundingSource=e.fundingSource??null,Le({eventName:"PAYMENT_METHOD_SELECTION",paymentMethod:"PAYPAL"}),r.resolve()}async handleCreateOrder(){let e=this.currentFundingSource==="card";return this.onStartDeferred=e,vp({context:this.context,configId:this.config.id,paymentMethodType:this.config.type,callbacks:this.callbacks,skipOnStartCallback:e})}async handleApprove(e,r){let i=this.onStartDeferred;return this.onStartDeferred=!1,bp({context:this.context,paymentMethodType:this.config.type,callbacks:this.callbacks,data:e,actions:r,deferredOnStartCallback:i})}handleCancel(){this.context.clientSessionApi.unselectPaymentMethod(),this.callbacks.onFinish(void 0,new R({message:"The PayPal payment was cancelled by the user.",paymentMethod:B.PAYPAL}))}handleError(e){C.errorWithDatadog("PayPal error:",e),this.callbacks.onFinish(void 0,e)}filterFundingSources(e,r,i){return e.filter(n=>!(r?.length&&!r.includes(n)||i?.includes(n)))}};function Oi(a,t,e){if(!a)return null;let r={id:a.id,orderId:a.orderId};return t?.paymentInstrumentData&&e&&(r.paymentMethodData={paymentMethodType:e,...t.paymentInstrumentData}),r}var br=(a,t,e,r,i)=>{let n=e;if(t?.status==="FAILED"&&(n=new R({code:O.PAYMENT_FAILED,message:`The payment "${t.id}" was created but failed to be processed. Check the payment id ${t.id} using the Payments API or search for the payment on your Dashboard for further explanations.`})),t?.checkoutOutcome==="CHECKOUT_FAILURE"&&(n=new R({code:O.PAYMENT_FAILED,message:`The payment "${t.id}" was created but failed to be processed. Check the payment id ${t.id} using the Payments API or search for the payment on your Dashboard for further explanations.`})),t?.status==="PENDING"&&!t.requiredAction?.clientToken&&(n=new R({code:O.PAYMENT_FAILED,message:`The payment "${t.id}" ended up in a "PENDING" state without any required action. The SDK does not know how to handle this state. Check the payment id ${t.id} using the Payments API or search for the payment on your Dashboard for further explanations.`})),t?.status==="SUCCESS"&&t.checkoutOutcome!=="CHECKOUT_FAILURE"||t?.status==="PENDING"&&t.showSuccessCheckoutOnPendingPayment||t?.checkoutOutcome==="CHECKOUT_COMPLETE")return void a.onCheckoutComplete?.({payment:Oi(t,r,i)});a.onCheckoutFail?.(n||new R({code:O.PAYMENT_FAILED,message:`The payment${t?.id?` "${t.id}"`:""} is in an inconsistent state without any required action. The SDK does not know how to handle this state. Please contact Primer.`}),{payment:Oi(t,r,i)??void 0})};async function Po(a,t){let e=t.config.type,r=a.onBeforePaymentCreate?new Promise(i=>{let n=setTimeout(()=>{C.warn("onBeforePaymentCreate did not resolve within 10 seconds. Primer SDK will remain in a loading state until `continuePaymentCreation` or `abortPaymentCreation` is called.")},1e4);a.onBeforePaymentCreate?.({paymentMethodType:e},{continuePaymentCreation:o=>{clearTimeout(n),C.log(`Continuing payment creation for ${e}`),o?.idempotencyKey&&t.setIdempotencyKey(o.idempotencyKey),a.onPaymentCreationStart?.(),i({action:"continue"})},abortPaymentCreation:()=>{clearTimeout(n),C.log(`Aborting payment creation for ${e}`),i({action:"abort"})}})}):Promise.resolve({action:"continue"});return await t.context.clientSessionApi.selectPaymentMethod(e),Le({eventName:"PAYMENT_PROCESSING_STARTED",paymentMethod:e}),r}async function We(a,t,e){if(t.setCallbacks({onStart:()=>Po(a,t),onFinish:(r,i)=>{To(a,t,r,i)}}),!e)return t.start();{let r,i;try{let{action:n}=await Po(a,t);if(n==="abort")throw new R({message:"Payment creation aborted",code:O.PAYMENT_CREATION_ABORTED,paymentMethod:t.config.type});i=await t.tokenizeVaulted(e.id)}catch(n){r=n}return To(a,t,i,r)}}async function To(a,t,e,r){let i;if(e&&!r)try{if(i=await t.createPayment(e),i.cancelled)return;i.status!=="FAILED"&&(i=await t.handleRequiredAction(i))}catch(n){r=n}br(a,i,r,e,t.config.type)}var No=Symbol("PROXY_MARKER");function an({namespace:a,onMessage:t,sendMessage:e}){function r(i,n){return new Proxy(i,{get(o,s,l){if(s==="then")return null;if(o[No])return Reflect.get(o,s,l);let c=()=>{};return c[No]=!0,r(c,[...n,s])},apply(o,s,l){return new Promise((c,p)=>{try{let m=[],g=l.map(L=>{if(typeof L!="function")return L;{let I=he();return m.push(I),t(x=>{x.namespace===a&&x.sender===Ti.PROVIDER&&x.type===Pi.CALLBACK&&x.id===I&&L(...x.data)}),I}}),A=he(),M=t(L=>{L.namespace===a&&L.sender===Ti.PROVIDER&&L.type===Pi.APPLY&&L.id===A&&(L.error?p(new Error(L.error)):c(L.data),M?.())}),w={type:Pi.APPLY,sender:Ti.INJECTOR,id:A,path:n,args:g,callbackIds:m,timeStamp:Date.now(),namespace:a};e(w)}catch(m){p(m)}})}})}return r({},[])}var Pi={APPLY:"apply",CALLBACK:"callback"},Ti={PROVIDER:"provider",INJECTOR:"injector"};function Di(a,t){let e=t?.input?.base?.height;e&&(a.style.height=typeof e=="number"?`${e}px`:e)}function Mp(a,t,e,r={}){let i=[],n="LOCAL",o={[ie.cardNumber]:void 0,[ie.cardExpiryDate]:void 0,[ie.cardSecurityCode]:void 0,[ie.cardholderName]:void 0},s=!1,l=()=>{s=!0,e.iframes.cardNumber.remove(),e.iframes.cardSecurityCode.remove(),e.iframes.cardExpiryDate.remove(),e.iframes.cardholderName.remove()};t.subscribeToTeardown(()=>{l()});let c={createHostedInputs:()=>{let p=m=>{let g=new Map,A={};return{getOptions:()=>({placeholder:A.placeholder??"",ariaLabel:A.ariaLabel??"",style:A.style}),setOptions:M=>{A={...A,...M},Di(e.iframes[m],M.style),e.iframes[m].setAttribute("title",M.ariaLabel||""),o[m]?.setOptions(M)},render:(M,w)=>{A={...A,...w};let L=e.iframes[m];if(!L)return C.errorWithDatadog(`No iframe found for ${m}`),Promise.resolve();let I;return I=typeof M=="string"?document.getElementById(M):M,I?(Di(L,w.style),I.appendChild(L),new Promise(x=>{L.onload=()=>{if(s){C.warn(`Teardown was already called, aborting render for ${m}`),L.remove(),x();return}o[m]=an({namespace:`${t.checkoutSessionId}-${m}`,onMessage:U=>{let ke=mr=>U(mr.data);return window.addEventListener("message",ke),()=>window.removeEventListener("message",ke)},sendMessage:U=>{L.contentWindow?.postMessage(U,"*")}}),e.iframes[m].setAttribute("title",w.ariaLabel||"");let _=a.cardholderName??a.card?.cardholderName,{defaultValue:z,...Z}=_??{};o[m].setOptions({...w,orderedAllowedCardNetworks:t.configuration.clientSession.paymentMethod.orderedAllowedCardNetworks,cardholderName:Z}),o[m].setBinDataLoadingChange(U=>{U&&r.onCardNetworksLoading?.(),r.onBinDataLoadingChange?.(U)}),o[m].setOnBlur(()=>{try{g.get("blur")?.()}catch(U){C.errorWithDatadog(`Blur listener error for ${m}`,{error:U})}}),o[m].setOnFocus(()=>{try{g.get("focus")?.()}catch(U){C.errorWithDatadog(`Focus listener error for ${m}`,{error:U})}}),o[m].setOnInput(U=>{let ke={...U,errorCode:U.error,active:U.focused};try{g.get("input")?.(ke),g.get("change")?.(ke)}catch(mr){C.errorWithDatadog(`Input listener error for ${m}`,{error:mr})}}),o[m].setOnEnter(()=>{try{g.get("enter")?.()}catch(U){C.errorWithDatadog(`Enter listener error for ${m}`,{error:U})}}),m===ie.cardNumber&&(o[m].setBinDataApiConfig(t.configuration.binDataUrl,t.decodedClientToken.accessToken),o[m].setOnCardNetworksChange((U,ke,mr)=>{if(ke!==n||Pp(i,U)){i=U,n=ke;let{cardNetworkChangeEventData:_c,binDataAvailableEventData:Oc}=Lu({networks:i,source:n},t.configuration.clientSession.paymentMethod.orderedAllowedCardNetworks);r.onCardNetworksChange?.(_c),r.onBinDataAvailable?.({...Oc,firstDigits:mr})}}))},x()})):(C.error(`Container not found for ${m}:`,M),Promise.resolve())},addEventListener:(M,w)=>{g.set(M,w)},focus:()=>{let M=e.iframes[m];if(M&&M.contentWindow)try{o[m]?.focus()}catch(w){C.errorWithDatadog(`Focus send error for ${m}`,{error:w})}else C.warn(`Focus failed for ${m} - iframe not available`)},blur:()=>{let M=e.iframes[m];if(M&&M.contentWindow)try{o[m]?.blur()}catch(w){C.errorWithDatadog(`Blur send error for ${m}`,{error:w})}},setDisabled:M=>{o[m]?.setDisabled(M)}}};return{cardNumberInput:p(ie.cardNumber),cardholderNameInput:p(ie.cardholderName),expiryInput:p(ie.cardExpiryDate),cvvInput:p(ie.cardSecurityCode)}},removeHostedInputs:l,submit:async p=>{if((await c.validate()).valid)return await t.apiController.setPreferredNetwork(p?.cardNetwork),We(a,e)},validate:async()=>{let p=(await Promise.all(Object.entries(o).filter(g=>g[1]!=null).map(([g,A])=>A.getFieldState().then(M=>[g,M]).catch(()=>{})))).filter(g=>g!==void 0),m=[];for(let[g,A]of p)!A.valid&&A.error&&m.push({field:g,name:g,error:A.error,message:A.error});return{valid:m.length===0,validationErrors:m}},reset:()=>{Object.values(o).forEach(p=>{p?.reset()}),t.apiController.setPreferredNetwork(void 0)},setCardholderName:p=>{try{o[ie.cardholderName]?.setCardholderName(p)}catch(m){C.errorWithDatadog("SetCardholderName error",{error:m})}}};return c}function Pp(a,t){if(a.length!==t.length)return!0;let e=t.map(({network:r})=>r);return!a.every(({network:r})=>e.includes(r))}function Tp(a,t,e){return{createButton:()=>({render:async(r,i)=>{await We(a,e);let n=typeof r=="string"?document.getElementById(r):r;if(!n)throw new R({code:uu.CONTAINER_NOT_FOUND,message:`Container with id "${typeof r=="string"?r:"element"}" not found in the DOM.`});await e.render(n,i)},setDisabled:r=>e.setDisabled(r)})}}function Np(a,t,e){return{start:()=>We(a,e)}}function Ip(a,t,e){return{start:async r=>(r?.blikCode&&e.setBlikCode(r.blikCode),We(a,e))}}async function kp(a,t,e,r){if(r?.onPaymentMethodCategoriesChange){let i=e.getCategories();i.length>0&&r.onPaymentMethodCategoriesChange(i.map(n=>({id:n.identifier,name:n.name,descriptiveAssetUrl:n.descriptiveAssetUrl,standardAssetUrl:n.standardAssetUrl})))}return{renderCategory:async i=>e.renderCategory(i),start:async i=>(e.setSelectedCategory(i.paymentMethodCategoryId),We(a,e))}}function Lp(a,t,e,r){if(r?.onPaymentOptionsChange){let i=e.getOptions();i.length>0&&r.onPaymentOptionsChange(i)}return{getPaymentOptions:()=>e.getOptions(),selectOption:i=>{e.selectOption(i)},start:async()=>We(a,e)}}function Rp(a,t,e){return{start:async r=>(r?.phoneNumber&&e.setPhoneNumber(r.phoneNumber),We(a,e))}}function wp(a,t){return{"Content-Type":"application/json","primer-client-token":a,"primer-sdk-client":"WEB","primer-sdk-version":ku,"primer-sdk-checkout-session-id":t,"x-api-version":"2.4"}}var Bi=({backendErrorId:a,status:t})=>a==="TransactionRequestIdempotencyKeyAlreadyExists"?O.IDEMPOTENCY_KEY_ALREADY_EXISTS:t?t>=500?J.SERVER_ERROR:{400:J.BAD_REQUEST,401:J.UNAUTHORIZED,403:J.FORBIDDEN,404:J.NOT_FOUND,408:J.REQUEST_TIMEOUT,409:J.CONFLICT,422:J.VALIDATION_ERROR}[t]??J.REQUEST_ERROR:J.UNEXPECTED;function xp(a,t,e){if(e?.status&&e.status>=400&&e.status<500)return!1;if(e?.status&&e.status>=500)return!0;if(a instanceof Error){let r=a.message.toLowerCase();return r.includes("network")||r.includes("timeout")||r.includes("connection")}return!1}function _p(a){let n=1e3*Math.pow(1.1,a),o=.1*n*(Math.random()-.5);return n=Math.max(0,n+o),Math.min(n,3e4)}var Op={attempts:3,retryCondition:xp,delayCalculator:_p,totalTimeout:3e5};async function Dp(a,t,e){let r={...Op,...t.retry},i=[],n=Date.now(),o=t.id??he();for(let l=0;l<=r.attempts;l++)try{let c=await a();if(!c.error)return{...c,retryHistory:i.length>0?i:void 0};if(l===r.attempts||!r.retryCondition(c.error,l,c))return{...c,retryHistory:i};let p=r.delayCalculator(l);if(i.push({attempt:l+1,delay:p,error:c.error,timestamp:Date.now()}),Date.now()-n+p>r.totalTimeout)return{...c,error:new le({message:`Retry total timeout exceeded for ${t.method} ${e}`,code:Bi({status:408}),response:c}),retryHistory:i};await xt(p)}catch(c){i.push({attempt:l+1,delay:0,error:new le({message:`Request failed for ${t.method} ${e}`,code:J.UNEXPECTED,error:c,response:{id:o}}),timestamp:Date.now()})}let s=i[i.length-1]?.error;return{id:o,error:s,retryHistory:i}}var Bp=1e3;async function Gp(a,t){let e=he(),r=t.interval??Bp,i=!1,n=t.timeout!=null?setTimeout(()=>{i=!0},t.timeout):void 0,o=()=>t.signal?.aborted||i,s;try{for(;!o();){let l=await a();if(t.isComplete(l))return l;if(o())break;await xt(r)}}catch(l){s=l}finally{n!=null&&clearTimeout(n)}return s?{id:e,error:new le({message:"Poll operation failed",code:J.UNEXPECTED,response:{id:e},error:s})}:i?{id:e,status:408,error:new le({message:"Poll operation timed out",code:J.REQUEST_TIMEOUT,response:{id:e}})}:{id:e,error:new le({message:"Poll operation aborted",code:J.POLLING_ABORTED,response:{id:e}})}}var qt=class{constructor(t,e="",r={}){S(this,"fetch");S(this,"baseUrl");S(this,"defaultHeaders");this.fetch=t,this.baseUrl=e,this.defaultHeaders=Object.freeze({...r})}setDefaultHeader(t,e){this.defaultHeaders={...this.defaultHeaders,[t]:e}}async executeFetch(t,e){let r={...e,headers:{...this.defaultHeaders,...e?.headers},id:he()};return e?.retry?Dp(()=>this.fetch(t,{...r,retry:void 0}),r,t):this.fetch(t,r)}async get(t,e){return this.executeFetch(t,{...e,method:"GET"})}async post(t,e,r){return this.executeFetch(t,{...r,method:"POST",body:JSON.stringify(e)})}async delete(t,e){return this.executeFetch(t,{...e,method:"DELETE"})}async poll(t,e,r){return Gp(()=>this.get(t,r),e)}};async function Kp(a,t){let e=t.id??he(),r={id:e};t.headers??(t.headers={}),t.headers["X-Request-Id"]=e;try{let i=await fetch(a,t);if(r.data=await i.json(),r.status=i.status,r.headers=Object.fromEntries(i.headers.entries()),!i.ok){let n=new le({message:`Request failed for ${t.method} ${a}`,code:Bi({backendErrorId:r.data?.error?.errorId,status:r.status}),response:{...r}});r.error=n}}catch(i){let n=new le({message:`Request failed for ${t.method} ${a}`,code:Bi({status:r.status}),response:{...r},error:i});r.error=n}return r}var Fp="https://goat-assets.production.core.primer.io/icon/gift/medium.svg",Up=["PAY_NL_KAARTDIRECT","MOLLIE_GIFTCARD"],Vp=["PAY_NL_PAYPAL"],Hp="https://goat-assets.production.core.primer.io/brand/logo/paypal/inverted.svg";function Yp(a){let e={PAY_NL_PAYPAL:Hp}[a.type];return e?{...a,implementationType:"WEB_REDIRECT",displayMetadata:{...a.displayMetadata,button:{...a.displayMetadata.button,iconUrl:{...a.displayMetadata.button.iconUrl,colored:e}}}}:{...a,implementationType:"WEB_REDIRECT"}}function $p(a){return{...a,implementationType:"WEB_REDIRECT",displayMetadata:{...a.displayMetadata,button:{...a.displayMetadata.button,iconUrl:{...a.displayMetadata.button.iconUrl,colored:Fp},text:"Gift card"}}}}function zp(a){return{...a,paymentMethods:(a.paymentMethods??[]).map(t=>Up.includes(t.type)?$p(t):Vp.includes(t.type)?Yp(t):t)}}var Gi=class extends qt{constructor(){super(...arguments);S(this,"configurationSubscribers",new Set);S(this,"_configuration")}async getConfiguration(){let e=await this.get(this.baseUrl);return e.data&&(this.configuration=e.data),e}subscribe(e){return this.configurationSubscribers.add(e),()=>{this.configurationSubscribers.delete(e)}}get configuration(){return this._configuration}set configuration(e){this._configuration=zp(e),this.configurationSubscribers.forEach(r=>r(this._configuration))}},Ki=class extends qt{async getPaymentInstruments(){return this.get(`${this.baseUrl}/payment-instruments`)}async postCardPaymentInstruments(){return this.post(`${this.baseUrl}/payment-instruments`,"pci-card-form-data")}async postPaypalPaymentInstruments(t,e){return this.post(`${this.baseUrl}/payment-instruments`,{paymentInstrument:t,...e})}async postPaymentInstruments(t){return this.post(`${this.baseUrl}/payment-instruments`,{paymentInstrument:t})}async postRedirectPaymentInstruments(t){return this.postPaymentInstruments(t)}async postApplePayPaymentInstruments(t){return this.postPaymentInstruments(t)}async postGooglePayPaymentInstruments(t){return this.postPaymentInstruments(t)}async postBlikPaymentInstruments(t){return this.postPaymentInstruments(t)}async postMbwayPaymentInstruments(t){return this.postPaymentInstruments(t)}async postKlarnaPaymentInstruments(t){return this.postPaymentInstruments(t)}async postKlarnaCustomerTokenInstruments(t){return this.post(`${this.baseUrl}/payment-instruments`,{paymentInstrument:t,tokenType:"MULTI_USE",paymentFlow:"VAULT"})}async postAdyenKlarnaPaymentInstruments(t){return this.postPaymentInstruments(t)}async postPaymentInstrumentsExchange(t){return this.post(`${this.baseUrl}/payment-instruments/${t}/exchange`,"payment-instrument-exchange")}async postCreatePayment(t,e){return this.post(`${this.baseUrl}/payments`,{paymentMethodToken:t},e?{headers:{"X-Idempotency-Key":e}}:void 0)}async postResumePayment(t,e){return this.post(`${this.baseUrl}/payments/${t}/resume`,{resumeToken:e})}async post3dsAuth(t,e){return this.post(`${this.baseUrl}/3ds/${t}/auth`,e,{retry:{attempts:15}})}async post3dsContinue(t){return this.post(`${this.baseUrl}/3ds/${t}/continue`,{platform:"WEB",status:"FAILURE"})}async get3dsResumeStatus(t){return this.get(t)}async deletePaymentInstrument(t){return this.delete(`${this.baseUrl}/payment-instruments/${t}/vault`)}async postClientSessionActions(t){return this.post(`${this.baseUrl}/client-session/actions`,{actions:t})}async getResumeStatus(t){return this.get(t)}pollResumeStatus(t,e){return this.poll(t,e)}poll3dsAuth(t,e){return this.poll(t,e)}async postClientSessionPay(t,e){return this.post(`${this.baseUrl}/client-session/${t}:pay`,e)}async getClientSessionInstruction(t){return this.get(`${this.baseUrl}/client-session/${t}?expand=clientInstruction`,{retry:{attempts:3}})}};async function jp(a){return new Promise((t,e)=>{let r=ts(a,"api"),i=`${Nu}#${r}`,n=document.querySelector(`iframe[src="${i}"]`)??document.createElement("iframe");n.parentElement?t(n):(n.style.display="none",n.onload=()=>t(n),n.onerror=o=>{e(new Error(`Failed to initialize Primer SDK: ${typeof o=="string"?o:"load error"}`))},n.src=i,document.body.appendChild(n))})}var Lt=class Lt extends qt{constructor(){super(...arguments);S(this,"onClientSessionUpdate");S(this,"onPaymentMethodAction");S(this,"selectedPaymentMethodType",null)}setOnClientSessionUpdate(e){this.onClientSessionUpdate=e}setOnPaymentMethodAction(e){this.onPaymentMethodAction=e}async postClientSessionActions(e){if(e.length===0)return Lt.noActionsResponse;let r=await this.post(`${this.baseUrl}/client-session/actions`,{actions:e}),{data:i}=r;return i&&this.onClientSessionUpdate?.(i),r}async selectPaymentMethod(e,r={}){return this.selectedPaymentMethodType===e||(this.selectedPaymentMethodType=e,this.onPaymentMethodAction?.("PAYMENT_METHOD_SELECTED",{paymentMethodType:e}),e==="PAYMENT_CARD"&&!r.binData)?Lt.noActionsResponse:this.postClientSessionActions([{type:"SELECT_PAYMENT_METHOD",params:{...r,paymentMethodType:e}}])}async unselectPaymentMethod(e,r){return this.onPaymentMethodAction?.("PAYMENT_METHOD_UNSELECTED",{paymentMethodType:this.selectedPaymentMethodType,payment:e,token:r}),this.selectedPaymentMethodType=null,this.postClientSessionActions([{type:"UNSELECT_PAYMENT_METHOD"}])}async selectCardNetwork(e){return this.selectPaymentMethod(B.PAYMENT_CARD,{binData:this.buildCardBinData(e)})}async setBillingAddress(e){let r=this.removeEmptyStringFromObject(e);return Object.values(r).length===0?Lt.noActionsResponse:this.postClientSessionActions([{type:"SET_BILLING_ADDRESS",params:{billingAddress:r}}])}async setShippingAddress(e,r,i){let n=[];return e&&Object.keys(e).some(s=>!!e[s])&&n.push({type:"SET_SHIPPING_ADDRESS",params:{shippingAddress:e}}),r&&n.push({type:"SET_MOBILE_NUMBER",params:{mobileNumber:r}}),i&&n.push({type:"SET_EMAIL_ADDRESS",params:{emailAddress:i}}),this.postClientSessionActions(n)}async selectShippingMethod(e){return this.postClientSessionActions([{type:"SELECT_SHIPPING_METHOD",params:{shippingMethodId:e}}])}async setCustomerDetails({emailAddress:e,firstName:r,lastName:i}){let n=[];return e&&n.push({type:"SET_EMAIL_ADDRESS",params:{emailAddress:e}}),r&&n.push({type:"SET_CUSTOMER_FIRST_NAME",params:{firstName:r}}),i&&n.push({type:"SET_CUSTOMER_LAST_NAME",params:{lastName:i}}),this.postClientSessionActions(n)}buildCardBinData(e){let{backend:r}=Zt(e);return{network:r,issuer_name:null,product_code:r,product_name:r,product_usage_type:"UNKNOWN",account_number_type:"UNKNOWN",issuer_country_code:null,account_funding_type:"UNKNOWN",issuer_currency_code:null,regional_restriction:"UNKNOWN",prepaid_reloadable_indicator:"NOT_APPLICABLE"}}removeEmptyStringFromObject(e){let r={...e};for(let i in r)r[i]===""?delete r[i]:typeof r[i]=="object"&&r[i]!==null&&!Array.isArray(r[i])&&(r[i]=this.removeEmptyStringFromObject(r[i]));return r}};S(Lt,"noActionsResponse",{data:{},error:void 0,headers:{},status:200,id:""});var Fi=Lt,Ui=class extends qt{async createPaypalOrder(t){return this.post(`${this.baseUrl}/paypal/orders/create`,t,{retry:{attempts:3}})}async createPaypalBillingAgreement(t){return this.post(`${this.baseUrl}/paypal/billing-agreements/create-agreement`,t,{retry:{attempts:3}})}async confirmPaypalBillingAgreement(t){return this.post(`${this.baseUrl}/paypal/billing-agreements/confirm-agreement`,t,{retry:{attempts:3}})}async createApplePaySession(t){return this.post(`${this.baseUrl}/apple-pay/sessions`,t)}async createKlarnaSession(t){return this.post(`${this.baseUrl}/klarna/payment-sessions`,t)}async finalizeKlarnaSession(t){return this.post(`${this.baseUrl}/klarna/payment-sessions/finalize`,t)}async createKlarnaCustomerToken(t){return this.post(`${this.baseUrl}/klarna/customer-tokens`,t)}async getPaymentMethodOptions(t){return this.get(`${this.baseUrl}/payment-method-options/${t}/payment-types`)}};async function Wp(a,{locale:t,dialogProvider:e,translate:r,clientOptions:i,integrationType:n="HEADLESS"}){let o=he(),s=ht(a),l=await jp(o),c=an({namespace:`api-controller-${o}`,onMessage:_=>{let z=Z=>{if(Z.data?.data?.error?.name==="RequestError"){let U=Object.assign(new le({...Z.data.data.error}),Z.data.data.error);typeof U.error=="object"&&"message"in U.error&&(U.error=Object.assign(new Error(U.error.message),{stack:U.error.stack})),Z.data.data.error=U}return _(Z.data)};return window.addEventListener("message",z),()=>window.removeEventListener("message",z)},sendMessage:_=>{l.contentWindow?.postMessage(_,"*")}}),p=wp(s.accessToken,o),m=new Gi(Kp,s.configurationUrl,p),g=Date.now(),{error:A}=await m.getConfiguration();if(A||!m.configuration)throw new Error(`Failed to fetch configuration: ${A}`);let M=c.fetch.bind(c),w=new Ki(M,m.configuration.pciUrl,p),L=new Ui(M,m.configuration.coreUrl,p),I=new Fi(M,m.configuration.pciUrl,p);I.setOnClientSessionUpdate(_=>{m.configuration=_});let x=new Set;return{get configuration(){return m.configuration},onClientConfigurationUpdate(_){return m.subscribe(_)},checkoutSessionId:o,integrationType:n,apiController:c,configurationApi:m,pciApi:w,coreApi:L,clientSessionApi:I,dialogProvider:e,decodedClientToken:s,locale:t||navigator.language||navigator.languages[0]||"en",configurationFetchStartTime:g,translate:r??((_,z)=>z),clientOptions:i,updateClientToken(_){try{let z=ht(_);m.setDefaultHeader("primer-client-token",z.accessToken),w.setDefaultHeader("primer-client-token",z.accessToken),L.setDefaultHeader("primer-client-token",z.accessToken),I.setDefaultHeader("primer-client-token",z.accessToken)}catch{}},async refreshClientConfiguration(){let{data:_,error:z}=await m.getConfiguration();return z||!_?(C.warn("Failed to refresh client configuration:",z),!1):(m.configuration=_,!0)},subscribeToTeardown(_){return x.add(_),()=>{x.delete(_)}},teardown(){l.remove(),x.forEach(_=>_())}}}var ss=({name:a,background:t,logoSrc:e,logoAlt:r,message:i})=>`<html>
|
|
70
|
+
`}pollStatus(e){let r=!0;return{promise:(async()=>{for(;r;){let{data:n,error:o}=await this.context.pciApi.getResumeStatus(e);if(o)return{error:o instanceof Error?o:new Error(String(o))};if(n?.status==="COMPLETE")return{id:n.id};await xt(1e3)}return{id:""}})(),abort:()=>{r=!1}}}},ua=class extends Ee{constructor(){super(...arguments);S(this,"phoneNumber","")}setPhoneNumber(e){this.phoneNumber=e}getPhoneNumber(){return this.phoneNumber}clearPhoneNumber(){this.phoneNumber=""}async start(){try{let{action:e}=await this.callbacks.onStart();if(e==="abort")return this.callbacks.onFinish(void 0,new R({message:"Payment creation aborted",code:x.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type}));let r=await this.tokenize();this.callbacks.onFinish(r)}catch(e){this.callbacks.onFinish(void 0,e)}}async tokenize(){if(!/^\+\d{10,15}$/.test(this.phoneNumber))throw new F({message:"Phone number must include country prefix and 10\u201315 digits",code:x.TOKENIZATION_ERROR,paymentMethod:this.config.type});let e={type:"OFF_SESSION_PAYMENT",paymentMethodType:this.config.type,paymentMethodConfigId:this.config.id,sessionInfo:{locale:this.context.locale,platform:Ar()?"MOBILE_WEB":"WEB",browserInfo:Rt(),phoneNumber:this.phoneNumber}};try{let{error:r,data:i}=await this.context.pciApi.postMbwayPaymentInstruments(e);if(this.clearPhoneNumber(),r||!i)throw r??new F({message:"Unable to tokenize MB WAY payment method",code:x.TOKENIZATION_ERROR,paymentMethod:this.config.type});return i}catch(r){throw this.clearPhoneNumber(),r}}async createPayment(e){let r=await super.createPayment(e);if(r.status==="FAILED"||!r.requiredAction)return r;let i=r.requiredAction.clientToken;if(!i)throw new le({message:"No client token provided for MB WAY payment",code:aa.MISSING_CLIENT_TOKEN,response:{id:r.id,data:r}});let n=ht(i);if(!this.isValidMbwayClientToken(n))throw new le({message:"Invalid MB WAY client token: missing statusUrl or incorrect intent",code:aa.INVALID_CLIENT_TOKEN,response:{id:r.id,data:r}});let o=await this.context.pciApi.pollResumeStatus(n.statusUrl,{timeout:864e5,isComplete:l=>!!l.error||l.data?.status==="COMPLETE"});if(o.error)throw o.error;let s=o.data?.id;if(!s){let l=await this.context.pciApi.getResumeStatus(n.statusUrl);if(l.error||!l.data?.id)throw l.error??new Error("Unable to get resume token");s=l.data.id}return await this.resumePayment(r.id,s)}isValidMbwayClientToken(e){if(typeof e!="object"||e===null)return!1;let r=e;return!(r.intent!=="ADYEN_MBWAY_REDIRECTION"||!("statusUrl"in r)||typeof r.statusUrl!="string"||!r.statusUrl)}};function $u(a,t){var e={};for(var r in a)Object.prototype.hasOwnProperty.call(a,r)&&t.indexOf(r)<0&&(e[r]=a[r]);if(a!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(a);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(a,r[i])&&(e[r[i]]=a[r[i]]);return e}function zu(a,t){var e=document.querySelector('script[src="'.concat(a,'"]'));if(e===null)return null;var r=rs(a,t),i=e.cloneNode();if(delete i.dataset.uidAuto,Object.keys(i.dataset).length!==Object.keys(r.dataset).length)return null;var n=!0;return Object.keys(i.dataset).forEach(function(o){i.dataset[o]!==r.dataset[o]&&(n=!1)}),n?e:null}function ju(a){var t=a.url,e=a.attributes,r=a.onSuccess,i=a.onError,n=rs(t,e);n.onerror=i,n.onload=r,document.head.insertBefore(n,document.head.firstElementChild)}function Wu(a){var t=a.sdkBaseUrl,e=a.environment,r=$u(a,["sdkBaseUrl","environment"]),i=t||qu(e),n=r,o=Object.keys(n).filter(function(c){return n[c]!==void 0&&n[c]!==null&&n[c]!==""}).reduce(function(c,p){var m=n[p].toString();return p=Zu(p),p.substring(0,4)==="data"||p==="crossorigin"?c.attributes[p]=m:c.queryParams[p]=m,c},{queryParams:{},attributes:{}}),s=o.queryParams,l=o.attributes;return s["merchant-id"]&&s["merchant-id"].indexOf(",")!==-1&&(l["data-merchant-id"]=s["merchant-id"],s["merchant-id"]="*"),{url:"".concat(i,"?").concat(Ju(s)),attributes:l}}function Zu(a){var t=function(e,r){return(r?"-":"")+e.toLowerCase()};return a.replace(/[A-Z]+(?![a-z])|[A-Z]/g,t)}function Ju(a){var t="";return Object.keys(a).forEach(function(e){t.length!==0&&(t+="&"),t+=e+"="+a[e]}),t}function qu(a){return a==="sandbox"?"https://www.sandbox.paypal.com/sdk/js":"https://www.paypal.com/sdk/js"}function rs(a,t){t===void 0&&(t={});var e=document.createElement("script");return e.src=a,Object.keys(t).forEach(function(r){e.setAttribute(r,t[r]),r==="data-csp-nonce"&&e.setAttribute("nonce",t["data-csp-nonce"])}),e}function Qu(a,t){if(t===void 0&&(t=Promise),as(a,t),typeof document>"u")return t.resolve(null);var e=Wu(a),r=e.url,i=e.attributes,n=i["data-namespace"]||"paypal",o=vo(n);return i["data-js-sdk-library"]||(i["data-js-sdk-library"]="paypal-js"),zu(r,i)&&o?t.resolve(o):Xu({url:r,attributes:i},t).then(function(){var s=vo(n);if(s)return s;throw new Error("The window.".concat(n," global variable is not available."))})}function Xu(a,t){t===void 0&&(t=Promise),as(a,t);var e=a.url,r=a.attributes;if(typeof e!="string"||e.length===0)throw new Error("Invalid url.");if(r!==void 0&&typeof r!="object")throw new Error("Expected attributes to be an object.");return new t(function(i,n){if(typeof document>"u")return i();ju({url:e,attributes:r,onSuccess:function(){return i()},onError:function(){var o=new Error('The script "'.concat(e,'" failed to load. Check the HTTP status code and response body in DevTools to learn more.'));return n(o)}})})}function vo(a){return window[a]}function as(a,t){if(typeof a!="object"||a===null)throw new Error("Expected an options object.");var e=a.environment;if(e&&e!=="production"&&e!=="sandbox")throw new Error('The `environment` option must be either "production" or "sandbox".');if(t!==void 0&&typeof t!="function")throw new Error("Expected PromisePonyfill to be a function.")}var Xr=new Map,bo={getOrCreateNamespace(a){let t=Xr.get(a);return t?t.namespace:he()},getInstance(a){return Xr.get(a)?.instance??null},storeInstance(a,t,e){Xr.set(a,{instance:t,namespace:e})},hasInstance(a){return Xr.has(a)}};async function ep({context:a,configId:t,paymentMethodType:e,callbacks:r}){try{let{action:i}=await r.onStart();if(i==="abort")throw new R({message:"Payment creation aborted",code:x.PAYMENT_CREATION_ABORTED,paymentMethod:e});let{data:n,error:o}=await a.coreApi.createPaypalBillingAgreement({paymentMethodConfigId:t});if(o||!n){let s=o?.message??"Failed to create billing agreement";throw new R({message:s,code:x.PAYMENT_FAILED,paymentMethod:e})}return n.tokenId}catch(i){throw C.errorWithDatadog("PayPal billing agreement creation failed:",{error:i}),r.onFinish(void 0,i),i instanceof R||i instanceof F?i:new R({message:"Failed to create billing agreement",code:x.PAYMENT_FAILED,paymentMethod:e})}}async function tp({context:a,configId:t,paymentMethodType:e,callbacks:r,data:i}){try{let n=i.billingToken;if(!n)throw new F({message:"Billing token not provided",code:x.TOKENIZATION_ERROR,paymentMethod:e});let{data:o,error:s}=await a.coreApi.confirmPaypalBillingAgreement({paymentMethodConfigId:t,tokenId:n});if(s||!o){let g=s?.message??"Failed to confirm billing agreement";throw new F({message:g,code:x.TOKENIZATION_ERROR,paymentMethod:e})}let l=o,c={paypalBillingAgreementId:l.billingAgreementId,shippingAddress:l.shippingAddress,externalPayerInfo:l.externalPayerInfo},{error:p,data:m}=await a.pciApi.postPaypalPaymentInstruments(c,{tokenType:"MULTI_USE",paymentFlow:"VAULT"});if(p||!m){let g=p?.message??"Unable to vault PayPal payment method";throw new F({message:g,code:x.TOKENIZATION_ERROR,paymentMethod:e})}r.onFinish(m)}catch(n){throw C.errorWithDatadog("PayPal billing agreement approval failed:",{error:n}),r.onFinish(void 0,n),n instanceof F||n instanceof R?n:new F({message:"Failed to approve billing agreement",code:x.TOKENIZATION_ERROR,paymentMethod:e})}}var rp="gold",ap="black",ip="rect",np="paypal",op="vertical",is="horizontal",Co=2,So=["paypal","paylater"],ns={default:{color:rp},card:{validColors:["black","white"],defaultColor:ap}};function sp(a){if(!a)return;let t=ns[a];if(t&&"validColors"in t)return t}function lp(a,t){let e=sp(t);if(!e)return a??ns.default.color;let r=a??e.defaultColor;return e.validColors.includes(r)?r:(C.warn(`PayPal: Invalid color "${r}" for ${t} button. Only supports: ${e.validColors.join(", ")}. Falling back to "${e.defaultColor}".`),e.defaultColor)}var dp=25,cp=55;function up(a){return parseFloat(a)||0}function pp(a){let t=up(a);return Math.max(dp,Math.min(cp,t))}function mp(a,t,e){let r=t?a?.[t]:void 0,i=r?.tagline??a?.tagline??!1,n=i?is:op,o,s=r?.height??a?.height;s!=null?o=s:e!=null&&(o=pp(String(e)));let l=r?.borderRadius??a?.borderRadius,c=r?.disableMaxWidth??a?.disableMaxWidth,p=r?.color??a?.color;return{color:lp(p,t),shape:r?.shape??a?.shape??ip,label:r?.label??a?.label??np,layout:r?.layout??a?.layout??n,tagline:i,...o!=null&&{height:o},...l!=null&&{borderRadius:l},...c!=null&&{disableMaxWidth:c}}}function hp(a,t,e,r){let i={style:a,onInit:e.onInit,onClick:e.onClick,onCancel:e.onCancel,onError:e.onError};return t&&r?(i.createBillingAgreement=r.createBillingAgreement,i.onApprove=r.onApprove):i.onApprove=e.onApprove,i}function gp(a){if(!a)return;let t={first_name:a.firstName,last_name:a.lastName,address_line_1:a.addressLine1??"",address_line_2:a.addressLine2,city:a.city??"",state:a.state,postal_code:a.postalCode??"",country_code:a.countryCode??""},{address_line_1:e,city:r,postal_code:i,country_code:n}=t;if(!(!e||!r||!i||!n))return t}function yp(a){if(!a)return null;let t=a.purchase_units?.[0]?.shipping;if(!t?.address)return null;let e=t.address,r=t.name;return{firstName:r?.given_name,lastName:r?.surname,addressLine1:e.address_line_1,addressLine2:e.address_line_2,city:e.admin_area_2,state:e.admin_area_1,postalCode:e.postal_code,countryCode:e.country_code}}function fp(a,t,e){let{order:{currencyCode:r,merchantAmount:i,totalOrderAmount:n,shipping:o,lineItems:s=[],fees:l=[]},customer:c}=a;if(!r)throw new R({message:"Currency code is not provided",code:wt.MISSING_PARAMETER,paymentMethod:e});let p={amount:i??n,currencyCode:r,paymentMethodConfigId:t,amountBreakdown:{}},m=c?.shippingAddress,g=gp(m);g&&(p.shipping_address=g);let A=!s.some(M=>!M.name&&!M.description);if(A&&(p.items=s.map(M=>{let{name:w,description:L,taxAmount:I,amount:_,quantity:O}=M,z=I?Math.floor(I/O):0;return{name:L||w||"",unit_amount:{value:_,currency_code:r},quantity:O.toString(),tax:{value:z,currency_code:r}}})),A&&s.length){let M=s.reduce((Z,{amount:U,quantity:ke})=>Z+U*ke,0),w=l?.reduce?.((Z,{amount:U})=>Z+(U??0),0),L=s?.reduce((Z,{discountAmount:U})=>Z+(U??0),0),I=s?.reduce((Z,{taxAmount:U})=>Z+(U??0),0),_=o?.amount??0,O=w??0,z=M+I+_+O-L;p.amountBreakdown={item_total:{value:M,currency_code:r},tax_total:{value:I,currency_code:r},handling:{value:O,currency_code:r},shipping:{value:_,currency_code:r},discount:{value:L,currency_code:r}},p.amount=z}return p}async function vp({context:a,configId:t,paymentMethodType:e,callbacks:r,skipOnStartCallback:i=!1}){try{if(!i){let{action:s}=await r.onStart();if(s==="abort")throw new R({message:"Payment creation aborted",code:x.PAYMENT_CREATION_ABORTED,paymentMethod:e})}let{data:n,error:o}=await a.coreApi.createPaypalOrder(fp(a.configuration.clientSession,t,e));if(o||!n){let s=o?.message??"Unable to create PayPal order";throw new R({message:s,code:x.PAYMENT_FAILED,paymentMethod:e})}return n.orderId}catch(n){throw r.onFinish(void 0,n),n}}async function bp({context:a,paymentMethodType:t,callbacks:e,data:r,actions:i,deferredOnStartCallback:n=!1}){if(n){let{action:m}=await e.onStart();if(m==="abort")throw new R({message:"Payment creation aborted",code:x.PAYMENT_CREATION_ABORTED,paymentMethod:t})}let o=null;try{o=await i?.order?.get()??null}catch(m){C.warn("Failed to get PayPal order details",m)}let s=yp(o),l={external_payer_info:{email:o?.payer?.email_address,external_payer_id:r.payerID??void 0,first_name:o?.payer?.name?.given_name,last_name:o?.payer?.name?.surname},paypal_order_id:r.orderID,paypal_status:o?.status};s&&(l.shipping_address=s);let{error:c,data:p}=await a.pciApi.postPaypalPaymentInstruments(l);if(c||!p){let m=c?.message??"Unable to create payment instrument";throw new F({message:m,code:x.TOKENIZATION_ERROR,paymentMethod:t})}e.onFinish(p)}var Cp=["buttons","funding-eligibility"],Ao=[],Eo="paypal";function os(a){if(!a?.length)return;a.includes(Eo)&&C.warn("PayPal: Cannot disable paypal funding source");let t=a.filter(e=>e!==Eo);return t.length>0?t:void 0}var Sp="authorize";function Ap(a,t,e){return(a??t==="PREFER_VAULT")&&e}function Mo({isVaultFlow:a,configIntent:t}){return a?"tokenize":t??Sp}function Ep(a,t,e,r){let{clientId:i,intent:n}=t.options,o=a.configuration.clientSession.order.currencyCode,s=a.clientOptions.paypal?.disableFunding??(Ao.length>0?Ao:void 0),l=os(s),c=a.clientOptions?.paypal?.enableFunding,p={dataNamespace:e,clientId:i,currency:o,components:Cp,...l&&l.length>0?{disableFunding:l}:{},...c&&c.length>0?{enableFunding:c}:{},integrationDate:a.clientOptions.paypal?.integrationDate,debug:a.clientOptions.paypal?.debug};return(_i||a.decodedClientToken.env==="SANDBOX"||a.decodedClientToken.env==="STAGING")&&(p.buyerCountry=a.clientOptions?.paypal?.buyerCountry),r?(p.vault="true",p.intent=Mo({isVaultFlow:!0,configIntent:n})):(p.vault="false",p.intent=Mo({isVaultFlow:!1,configIntent:n})),p}var pa=class extends Ee{constructor(e,r){super(e,r);S(this,"paypalInstance");S(this,"dataNamespace");S(this,"isVaultFlow",!1);S(this,"isSetupComplete",!1);S(this,"setupPromise");S(this,"eligibleFundingSources",[]);S(this,"currentFundingSource",null);S(this,"onStartDeferred",!1);S(this,"disabled",!1);this.dataNamespace=bo.getOrCreateNamespace(e.id),this.context.onClientConfigurationUpdate(async()=>{C.info("PayPal: Client session updated, refreshing PayPal buttons");try{await this.setup()}catch(i){C.warn("PayPal: Failed to refresh on client session update:",i)}})}async setDisabled(e){this.disabled=e}async tokenize(){throw new F({message:"PayPal does not support direct tokenization",code:x.TOKENIZATION_ERROR,paymentMethod:B.PAYPAL})}async setup(){let{clientId:e}=this.config.options;return this.setupPromise?(C.info("PayPal setup already in progress, waiting..."),this.setupPromise):this.isSetupComplete&&this.paypalInstance?.Buttons?(C.info("PayPal setup already completed, skipping"),!0):e?(this.setupPromise=(async()=>{try{let r=this.context.clientOptions.paypal?.vault,i=this.context.clientOptions.paypal?.paymentFlow,n=this.context.configuration.clientSession.paymentMethod?.vaultOnSuccess??!1;this.isVaultFlow=Ap(r,i,n);let o=Ep(this.context,this.config,this.dataNamespace,this.isVaultFlow);C.debug("%c PAYPAL %c Script Configuration ","background: #0070BA; color: #ffffff; font-weight: bold; padding: 4px 12px; border-radius: 3px 0 0 3px; font-size: 14px;","background: #003087; color: #ffffff; padding: 4px 12px; border-radius: 0 3px 3px 0; font-size: 14px;",o);let s=await Qu(o);if(!s)return C.warn("Failed to load PayPal SDK"),!1;this.paypalInstance=s,bo.storeInstance(this.config.id,s,this.dataNamespace);let l=this.context.clientOptions.paypal?.enableFunding,c=os(this.context.clientOptions.paypal?.disableFunding),m=(s.getFundingSources?.()??[]).filter(g=>s?.isFundingEligible?.(g));return C.debug("PayPal: Eligible funding sources from PayPal SDK:",m),this.eligibleFundingSources=this.filterFundingSources(m,l,c),(l?.length||c?.length)&&(C.debug("PayPal: Primer SDK options:",{enableFunding:l??[],disableFunding:c??[]}),C.debug("PayPal: Funding sources after Primer SDK filter:",this.eligibleFundingSources)),this.eligibleFundingSources.length===0?(C.warn("PayPal: No funding sources are eligible with current configuration"),!1):!0}catch(r){return C.warn("PayPal setup failed:",{error:r}),this.setupPromise=void 0,!1}})(),this.setupPromise):(C.warn("PayPal clientId is required"),!1)}async render(e,r){let{Buttons:i}=this.paypalInstance;if(!i)throw new R({message:"PayPal Buttons component not available",code:wt.INVALID_USAGE,paymentMethod:B.PAYPAL});let n=this.context.clientOptions.paypal?.style,o=r?.style?.buttonHeight,s=n?.layout===is,l={onInit:this.handleInit.bind(this),onClick:this.handleClick.bind(this),onApprove:this.handleApprove.bind(this),onCancel:this.handleCancel.bind(this),onError:this.handleError.bind(this)},c=this.isVaultFlow?{createBillingAgreement:()=>ep({context:this.context,configId:this.config.id,paymentMethodType:this.config.type,callbacks:this.callbacks}),onApprove:M=>tp({context:this.context,configId:this.config.id,paymentMethodType:this.config.type,callbacks:this.callbacks,data:M})}:void 0,p=this.eligibleFundingSources,m=[];for(let M of p){let w=mp(n,M,o),L=hp(w,this.isVaultFlow,l,c);this.isVaultFlow||(L.createOrder=this.handleCreateOrder.bind(this));let I=i({...L,fundingSource:M});I.isEligible()?m.push({button:I,fundingSource:M}):C.debug(`PayPal: Button for "${M}" is not eligible with current config`)}if(m.length===0)throw C.warn("PayPal: No buttons were eligible to render with current configuration"),new R({message:"No PayPal buttons eligible to render",code:wt.INVALID_USAGE,paymentMethod:B.PAYPAL});let g=s&&m.length>Co?this.selectButtonsForHorizontalLayout(m):m;s&&this.applyHorizontalLayoutStyles(e,g.length);let A=g.map(({button:M})=>M.render(e));await Promise.all(A)}selectButtonsForHorizontalLayout(e){let r=new Set(So),i=So.map(o=>e.find(s=>s.fundingSource===o)).filter(o=>o!==void 0),n=e.filter(o=>!r.has(o.fundingSource));return[...i,...n].slice(0,Co)}applyHorizontalLayoutStyles(e,r){e.style.display="grid",e.style.gridTemplateColumns=`repeat(${r}, 1fr)`,e.style.gap="10px"}handleInit(e,r){let{clientSession:i}=this.context.configuration,n=!!i.order.currencyCode,o=!!i.order.totalOrderAmount||!!i.order.merchantAmount;if(!n||!o){C.warn("PayPal button disabled: missing currency or amount"),r.disable();return}r.enable()}handleClick(e,r){return this.currentFundingSource=e.fundingSource??null,Le({eventName:"PAYMENT_METHOD_SELECTION",paymentMethod:"PAYPAL"}),r.resolve()}async handleCreateOrder(){let e=this.currentFundingSource==="card";return this.onStartDeferred=e,vp({context:this.context,configId:this.config.id,paymentMethodType:this.config.type,callbacks:this.callbacks,skipOnStartCallback:e})}async handleApprove(e,r){let i=this.onStartDeferred;return this.onStartDeferred=!1,bp({context:this.context,paymentMethodType:this.config.type,callbacks:this.callbacks,data:e,actions:r,deferredOnStartCallback:i})}handleCancel(){this.context.clientSessionApi.unselectPaymentMethod(),this.callbacks.onFinish(void 0,new R({message:"The PayPal payment was cancelled by the user.",paymentMethod:B.PAYPAL}))}handleError(e){C.errorWithDatadog("PayPal error:",e),this.callbacks.onFinish(void 0,e)}filterFundingSources(e,r,i){return e.filter(n=>!(r?.length&&!r.includes(n)||i?.includes(n)))}};function Oi(a,t,e){if(!a)return null;let r={id:a.id,orderId:a.orderId};return t?.paymentInstrumentData&&e&&(r.paymentMethodData={paymentMethodType:e,...t.paymentInstrumentData}),r}var br=(a,t,e,r,i)=>{let n=e;if(t?.status==="FAILED"&&(n=new R({code:x.PAYMENT_FAILED,message:`The payment "${t.id}" was created but failed to be processed. Check the payment id ${t.id} using the Payments API or search for the payment on your Dashboard for further explanations.`})),t?.checkoutOutcome==="CHECKOUT_FAILURE"&&(n=new R({code:x.PAYMENT_FAILED,message:`The payment "${t.id}" was created but failed to be processed. Check the payment id ${t.id} using the Payments API or search for the payment on your Dashboard for further explanations.`})),t?.status==="PENDING"&&!t.requiredAction?.clientToken&&(n=new R({code:x.PAYMENT_FAILED,message:`The payment "${t.id}" ended up in a "PENDING" state without any required action. The SDK does not know how to handle this state. Check the payment id ${t.id} using the Payments API or search for the payment on your Dashboard for further explanations.`})),t?.status==="SUCCESS"&&t.checkoutOutcome!=="CHECKOUT_FAILURE"||t?.status==="PENDING"&&t.showSuccessCheckoutOnPendingPayment||t?.checkoutOutcome==="CHECKOUT_COMPLETE")return void a.onCheckoutComplete?.({payment:Oi(t,r,i)});a.onCheckoutFail?.(n||new R({code:x.PAYMENT_FAILED,message:`The payment${t?.id?` "${t.id}"`:""} is in an inconsistent state without any required action. The SDK does not know how to handle this state. Please contact Primer.`}),{payment:Oi(t,r,i)??void 0})};async function Po(a,t){let e=t.config.type,r=a.onBeforePaymentCreate?new Promise(i=>{let n=setTimeout(()=>{C.warn("onBeforePaymentCreate did not resolve within 10 seconds. Primer SDK will remain in a loading state until `continuePaymentCreation` or `abortPaymentCreation` is called.")},1e4);a.onBeforePaymentCreate?.({paymentMethodType:e},{continuePaymentCreation:o=>{clearTimeout(n),C.log(`Continuing payment creation for ${e}`),o?.idempotencyKey&&t.setIdempotencyKey(o.idempotencyKey),a.onPaymentCreationStart?.(),i({action:"continue"})},abortPaymentCreation:()=>{clearTimeout(n),C.log(`Aborting payment creation for ${e}`),i({action:"abort"})}})}):Promise.resolve({action:"continue"});return await t.context.clientSessionApi.selectPaymentMethod(e),Le({eventName:"PAYMENT_PROCESSING_STARTED",paymentMethod:e}),r}async function We(a,t,e){if(t.setCallbacks({onStart:()=>Po(a,t),onFinish:(r,i)=>{To(a,t,r,i)}}),!e)return t.start();{let r,i;try{let{action:n}=await Po(a,t);if(n==="abort")throw new R({message:"Payment creation aborted",code:x.PAYMENT_CREATION_ABORTED,paymentMethod:t.config.type});i=await t.tokenizeVaulted(e.id)}catch(n){r=n}return To(a,t,i,r)}}async function To(a,t,e,r){let i;if(e&&!r)try{if(i=await t.createPayment(e),i.cancelled)return;i.status!=="FAILED"&&(i=await t.handleRequiredAction(i))}catch(n){r=n}br(a,i,r,e,t.config.type)}var No=Symbol("PROXY_MARKER");function an({namespace:a,onMessage:t,sendMessage:e}){function r(i,n){return new Proxy(i,{get(o,s,l){if(s==="then")return null;if(o[No])return Reflect.get(o,s,l);let c=()=>{};return c[No]=!0,r(c,[...n,s])},apply(o,s,l){return new Promise((c,p)=>{try{let m=[],g=l.map(L=>{if(typeof L!="function")return L;{let I=he();return m.push(I),t(_=>{_.namespace===a&&_.sender===Ti.PROVIDER&&_.type===Pi.CALLBACK&&_.id===I&&L(..._.data)}),I}}),A=he(),M=t(L=>{L.namespace===a&&L.sender===Ti.PROVIDER&&L.type===Pi.APPLY&&L.id===A&&(L.error?p(new Error(L.error)):c(L.data),M?.())}),w={type:Pi.APPLY,sender:Ti.INJECTOR,id:A,path:n,args:g,callbackIds:m,timeStamp:Date.now(),namespace:a};e(w)}catch(m){p(m)}})}})}return r({},[])}var Pi={APPLY:"apply",CALLBACK:"callback"},Ti={PROVIDER:"provider",INJECTOR:"injector"};function Di(a,t){let e=t?.input?.base?.height;e&&(a.style.height=typeof e=="number"?`${e}px`:e)}function Mp(a,t,e,r={}){let i=[],n="LOCAL",o={[ie.cardNumber]:void 0,[ie.cardExpiryDate]:void 0,[ie.cardSecurityCode]:void 0,[ie.cardholderName]:void 0},s=!1,l=()=>{s=!0,e.iframes.cardNumber.remove(),e.iframes.cardSecurityCode.remove(),e.iframes.cardExpiryDate.remove(),e.iframes.cardholderName.remove()};t.subscribeToTeardown(()=>{l()});let c={createHostedInputs:()=>{let p=m=>{let g=new Map,A={};return{getOptions:()=>({placeholder:A.placeholder??"",ariaLabel:A.ariaLabel??"",style:A.style}),setOptions:M=>{A={...A,...M},Di(e.iframes[m],M.style),e.iframes[m].setAttribute("title",M.ariaLabel||""),o[m]?.setOptions(M)},render:(M,w)=>{A={...A,...w};let L=e.iframes[m];if(!L)return C.errorWithDatadog(`No iframe found for ${m}`),Promise.resolve();let I;return I=typeof M=="string"?document.getElementById(M):M,I?(Di(L,w.style),I.appendChild(L),new Promise(_=>{L.onload=()=>{if(s){C.warn(`Teardown was already called, aborting render for ${m}`),L.remove(),_();return}o[m]=an({namespace:`${t.checkoutSessionId}-${m}`,onMessage:U=>{let ke=mr=>U(mr.data);return window.addEventListener("message",ke),()=>window.removeEventListener("message",ke)},sendMessage:U=>{L.contentWindow?.postMessage(U,"*")}}),e.iframes[m].setAttribute("title",w.ariaLabel||"");let O=a.cardholderName??a.card?.cardholderName,{defaultValue:z,...Z}=O??{};o[m].setOptions({...w,orderedAllowedCardNetworks:t.configuration.clientSession.paymentMethod.orderedAllowedCardNetworks,cardholderName:Z}),o[m].setBinDataLoadingChange(U=>{U&&r.onCardNetworksLoading?.(),r.onBinDataLoadingChange?.(U)}),o[m].setOnBlur(()=>{try{g.get("blur")?.()}catch(U){C.errorWithDatadog(`Blur listener error for ${m}`,{error:U})}}),o[m].setOnFocus(()=>{try{g.get("focus")?.()}catch(U){C.errorWithDatadog(`Focus listener error for ${m}`,{error:U})}}),o[m].setOnInput(U=>{let ke={...U,errorCode:U.error,active:U.focused};try{g.get("input")?.(ke),g.get("change")?.(ke)}catch(mr){C.errorWithDatadog(`Input listener error for ${m}`,{error:mr})}}),o[m].setOnEnter(()=>{try{g.get("enter")?.()}catch(U){C.errorWithDatadog(`Enter listener error for ${m}`,{error:U})}}),m===ie.cardNumber&&(o[m].setBinDataApiConfig(t.configuration.binDataUrl,t.decodedClientToken.accessToken),o[m].setOnCardNetworksChange((U,ke,mr)=>{if(ke!==n||Pp(i,U)){i=U,n=ke;let{cardNetworkChangeEventData:_c,binDataAvailableEventData:Oc}=Lu({networks:i,source:n},t.configuration.clientSession.paymentMethod.orderedAllowedCardNetworks);r.onCardNetworksChange?.(_c),r.onBinDataAvailable?.({...Oc,firstDigits:mr})}}))},_()})):(C.error(`Container not found for ${m}:`,M),Promise.resolve())},addEventListener:(M,w)=>{g.set(M,w)},focus:()=>{let M=e.iframes[m];if(M&&M.contentWindow)try{o[m]?.focus()}catch(w){C.errorWithDatadog(`Focus send error for ${m}`,{error:w})}else C.warn(`Focus failed for ${m} - iframe not available`)},blur:()=>{let M=e.iframes[m];if(M&&M.contentWindow)try{o[m]?.blur()}catch(w){C.errorWithDatadog(`Blur send error for ${m}`,{error:w})}},setDisabled:M=>{o[m]?.setDisabled(M)}}};return{cardNumberInput:p(ie.cardNumber),cardholderNameInput:p(ie.cardholderName),expiryInput:p(ie.cardExpiryDate),cvvInput:p(ie.cardSecurityCode)}},removeHostedInputs:l,submit:async p=>{if((await c.validate()).valid)return await t.apiController.setPreferredNetwork(p?.cardNetwork),We(a,e)},validate:async()=>{let p=(await Promise.all(Object.entries(o).filter(g=>g[1]!=null).map(([g,A])=>A.getFieldState().then(M=>[g,M]).catch(()=>{})))).filter(g=>g!==void 0),m=[];for(let[g,A]of p)!A.valid&&A.error&&m.push({field:g,name:g,error:A.error,message:A.error});return{valid:m.length===0,validationErrors:m}},reset:()=>{Object.values(o).forEach(p=>{p?.reset()}),t.apiController.setPreferredNetwork(void 0)},setCardholderName:p=>{try{o[ie.cardholderName]?.setCardholderName(p)}catch(m){C.errorWithDatadog("SetCardholderName error",{error:m})}}};return c}function Pp(a,t){if(a.length!==t.length)return!0;let e=t.map(({network:r})=>r);return!a.every(({network:r})=>e.includes(r))}function Tp(a,t,e){return{createButton:()=>({render:async(r,i)=>{await We(a,e);let n=typeof r=="string"?document.getElementById(r):r;if(!n)throw new R({code:uu.CONTAINER_NOT_FOUND,message:`Container with id "${typeof r=="string"?r:"element"}" not found in the DOM.`});await e.render(n,i)},setDisabled:r=>e.setDisabled(r)})}}function Np(a,t,e){return{start:()=>We(a,e)}}function Ip(a,t,e){return{start:async r=>(r?.blikCode&&e.setBlikCode(r.blikCode),We(a,e))}}async function kp(a,t,e,r){if(r?.onPaymentMethodCategoriesChange){let i=e.getCategories();i.length>0&&r.onPaymentMethodCategoriesChange(i.map(n=>({id:n.identifier,name:n.name,descriptiveAssetUrl:n.descriptiveAssetUrl,standardAssetUrl:n.standardAssetUrl})))}return{renderCategory:async i=>e.renderCategory(i),start:async i=>(e.setSelectedCategory(i.paymentMethodCategoryId),We(a,e))}}function Lp(a,t,e,r){if(r?.onPaymentOptionsChange){let i=e.getOptions();i.length>0&&r.onPaymentOptionsChange(i)}return{getPaymentOptions:()=>e.getOptions(),selectOption:i=>{e.selectOption(i)},start:async()=>We(a,e)}}function Rp(a,t,e){return{start:async r=>(r?.phoneNumber&&e.setPhoneNumber(r.phoneNumber),We(a,e))}}function wp(a,t){return{"Content-Type":"application/json","primer-client-token":a,"primer-sdk-client":"WEB","primer-sdk-version":ku,"primer-sdk-checkout-session-id":t,"x-api-version":"2.4"}}var Bi=({backendErrorId:a,status:t})=>a==="TransactionRequestIdempotencyKeyAlreadyExists"?x.IDEMPOTENCY_KEY_ALREADY_EXISTS:t?t>=500?J.SERVER_ERROR:{400:J.BAD_REQUEST,401:J.UNAUTHORIZED,403:J.FORBIDDEN,404:J.NOT_FOUND,408:J.REQUEST_TIMEOUT,409:J.CONFLICT,422:J.VALIDATION_ERROR}[t]??J.REQUEST_ERROR:J.UNEXPECTED;function xp(a,t,e){if(e?.status&&e.status>=400&&e.status<500)return!1;if(e?.status&&e.status>=500)return!0;if(a instanceof Error){let r=a.message.toLowerCase();return r.includes("network")||r.includes("timeout")||r.includes("connection")}return!1}function _p(a){let n=1e3*Math.pow(1.1,a),o=.1*n*(Math.random()-.5);return n=Math.max(0,n+o),Math.min(n,3e4)}var Op={attempts:3,retryCondition:xp,delayCalculator:_p,totalTimeout:3e5};async function Dp(a,t,e){let r={...Op,...t.retry},i=[],n=Date.now(),o=t.id??he();for(let l=0;l<=r.attempts;l++)try{let c=await a();if(!c.error)return{...c,retryHistory:i.length>0?i:void 0};if(l===r.attempts||!r.retryCondition(c.error,l,c))return{...c,retryHistory:i};let p=r.delayCalculator(l);if(i.push({attempt:l+1,delay:p,error:c.error,timestamp:Date.now()}),Date.now()-n+p>r.totalTimeout)return{...c,error:new le({message:`Retry total timeout exceeded for ${t.method} ${e}`,code:Bi({status:408}),response:c}),retryHistory:i};await xt(p)}catch(c){i.push({attempt:l+1,delay:0,error:new le({message:`Request failed for ${t.method} ${e}`,code:J.UNEXPECTED,error:c,response:{id:o}}),timestamp:Date.now()})}let s=i[i.length-1]?.error;return{id:o,error:s,retryHistory:i}}var Bp=1e3;async function Gp(a,t){let e=he(),r=t.interval??Bp,i=!1,n=t.timeout!=null?setTimeout(()=>{i=!0},t.timeout):void 0,o=()=>t.signal?.aborted||i,s;try{for(;!o();){let l=await a();if(t.isComplete(l))return l;if(o())break;await xt(r)}}catch(l){s=l}finally{n!=null&&clearTimeout(n)}return s?{id:e,error:new le({message:"Poll operation failed",code:J.UNEXPECTED,response:{id:e},error:s})}:i?{id:e,status:408,error:new le({message:"Poll operation timed out",code:J.REQUEST_TIMEOUT,response:{id:e}})}:{id:e,error:new le({message:"Poll operation aborted",code:J.POLLING_ABORTED,response:{id:e}})}}var qt=class{constructor(t,e="",r={}){S(this,"fetch");S(this,"baseUrl");S(this,"defaultHeaders");this.fetch=t,this.baseUrl=e,this.defaultHeaders=Object.freeze({...r})}setDefaultHeader(t,e){this.defaultHeaders={...this.defaultHeaders,[t]:e}}async executeFetch(t,e){let r={...e,headers:{...this.defaultHeaders,...e?.headers},id:he()};return e?.retry?Dp(()=>this.fetch(t,{...r,retry:void 0}),r,t):this.fetch(t,r)}async get(t,e){return this.executeFetch(t,{...e,method:"GET"})}async post(t,e,r){return this.executeFetch(t,{...r,method:"POST",body:JSON.stringify(e)})}async delete(t,e){return this.executeFetch(t,{...e,method:"DELETE"})}async poll(t,e,r){return Gp(()=>this.get(t,r),e)}};async function Kp(a,t){let e=t.id??he(),r={id:e};t.headers??(t.headers={}),t.headers["X-Request-Id"]=e;try{let i=await fetch(a,t);if(r.data=await i.json(),r.status=i.status,r.headers=Object.fromEntries(i.headers.entries()),!i.ok){let n=new le({message:`Request failed for ${t.method} ${a}`,code:Bi({backendErrorId:r.data?.error?.errorId,status:r.status}),response:{...r}});r.error=n}}catch(i){let n=new le({message:`Request failed for ${t.method} ${a}`,code:Bi({status:r.status}),response:{...r},error:i});r.error=n}return r}var Fp="https://goat-assets.production.core.primer.io/icon/gift/medium.svg",Up=["PAY_NL_KAARTDIRECT","MOLLIE_GIFTCARD"],Vp=["PAY_NL_PAYPAL"],Hp="https://goat-assets.production.core.primer.io/brand/logo/paypal/inverted.svg";function Yp(a){let e={PAY_NL_PAYPAL:Hp}[a.type];return e?{...a,implementationType:"WEB_REDIRECT",displayMetadata:{...a.displayMetadata,button:{...a.displayMetadata.button,iconUrl:{...a.displayMetadata.button.iconUrl,colored:e}}}}:{...a,implementationType:"WEB_REDIRECT"}}function $p(a){return{...a,implementationType:"WEB_REDIRECT",displayMetadata:{...a.displayMetadata,button:{...a.displayMetadata.button,iconUrl:{...a.displayMetadata.button.iconUrl,colored:Fp},text:"Gift card"}}}}function zp(a){return{...a,paymentMethods:(a.paymentMethods??[]).map(t=>Up.includes(t.type)?$p(t):Vp.includes(t.type)?Yp(t):t)}}var Gi=class extends qt{constructor(){super(...arguments);S(this,"configurationSubscribers",new Set);S(this,"_configuration")}async getConfiguration(){let e=await this.get(this.baseUrl);return e.data&&(this.configuration=e.data),e}subscribe(e){return this.configurationSubscribers.add(e),()=>{this.configurationSubscribers.delete(e)}}get configuration(){return this._configuration}set configuration(e){this._configuration=zp(e),this.configurationSubscribers.forEach(r=>r(this._configuration))}},Ki=class extends qt{async getPaymentInstruments(){return this.get(`${this.baseUrl}/payment-instruments`)}async postCardPaymentInstruments(){return this.post(`${this.baseUrl}/payment-instruments`,"pci-card-form-data")}async postPaypalPaymentInstruments(t,e){return this.post(`${this.baseUrl}/payment-instruments`,{paymentInstrument:t,...e})}async postPaymentInstruments(t){return this.post(`${this.baseUrl}/payment-instruments`,{paymentInstrument:t})}async postRedirectPaymentInstruments(t){return this.postPaymentInstruments(t)}async postApplePayPaymentInstruments(t){return this.postPaymentInstruments(t)}async postGooglePayPaymentInstruments(t){return this.postPaymentInstruments(t)}async postBlikPaymentInstruments(t){return this.postPaymentInstruments(t)}async postMbwayPaymentInstruments(t){return this.postPaymentInstruments(t)}async postKlarnaPaymentInstruments(t){return this.postPaymentInstruments(t)}async postKlarnaCustomerTokenInstruments(t){return this.post(`${this.baseUrl}/payment-instruments`,{paymentInstrument:t,tokenType:"MULTI_USE",paymentFlow:"VAULT"})}async postAdyenKlarnaPaymentInstruments(t){return this.postPaymentInstruments(t)}async postPaymentInstrumentsExchange(t){return this.post(`${this.baseUrl}/payment-instruments/${t}/exchange`,"payment-instrument-exchange")}async postCreatePayment(t,e){return this.post(`${this.baseUrl}/payments`,{paymentMethodToken:t},e?{headers:{"X-Idempotency-Key":e}}:void 0)}async postResumePayment(t,e){return this.post(`${this.baseUrl}/payments/${t}/resume`,{resumeToken:e})}async post3dsAuth(t,e){return this.post(`${this.baseUrl}/3ds/${t}/auth`,e,{retry:{attempts:15}})}async post3dsContinue(t){return this.post(`${this.baseUrl}/3ds/${t}/continue`,{platform:"WEB",status:"FAILURE"})}async get3dsResumeStatus(t){return this.get(t)}async deletePaymentInstrument(t){return this.delete(`${this.baseUrl}/payment-instruments/${t}/vault`)}async postClientSessionActions(t){return this.post(`${this.baseUrl}/client-session/actions`,{actions:t})}async getResumeStatus(t){return this.get(t)}pollResumeStatus(t,e){return this.poll(t,e)}poll3dsAuth(t,e){return this.poll(t,e)}async postClientSessionPay(t,e){return this.post(`${this.baseUrl}/client-session/${t}:pay`,e)}async getClientSessionInstruction(t){return this.get(`${this.baseUrl}/client-session/${t}?expand=clientInstruction`,{retry:{attempts:3}})}};async function jp(a){return new Promise((t,e)=>{let r=ts(a,"api"),i=`${Nu}#${r}`,n=document.querySelector(`iframe[src="${i}"]`)??document.createElement("iframe");n.parentElement?t(n):(n.style.display="none",n.onload=()=>t(n),n.onerror=o=>{e(new Error(`Failed to initialize Primer SDK: ${typeof o=="string"?o:"load error"}`))},n.src=i,document.body.appendChild(n))})}var Lt=class Lt extends qt{constructor(){super(...arguments);S(this,"onClientSessionUpdate");S(this,"onPaymentMethodAction");S(this,"selectedPaymentMethodType",null)}setOnClientSessionUpdate(e){this.onClientSessionUpdate=e}setOnPaymentMethodAction(e){this.onPaymentMethodAction=e}async postClientSessionActions(e){if(e.length===0)return Lt.noActionsResponse;let r=await this.post(`${this.baseUrl}/client-session/actions`,{actions:e}),{data:i}=r;return i&&this.onClientSessionUpdate?.(i),r}async selectPaymentMethod(e,r={}){return this.selectedPaymentMethodType===e||(this.selectedPaymentMethodType=e,this.onPaymentMethodAction?.("PAYMENT_METHOD_SELECTED",{paymentMethodType:e}),e==="PAYMENT_CARD"&&!r.binData)?Lt.noActionsResponse:this.postClientSessionActions([{type:"SELECT_PAYMENT_METHOD",params:{...r,paymentMethodType:e}}])}async unselectPaymentMethod(e,r){return this.onPaymentMethodAction?.("PAYMENT_METHOD_UNSELECTED",{paymentMethodType:this.selectedPaymentMethodType,payment:e,token:r}),this.selectedPaymentMethodType=null,this.postClientSessionActions([{type:"UNSELECT_PAYMENT_METHOD"}])}async selectCardNetwork(e){return this.selectPaymentMethod(B.PAYMENT_CARD,{binData:this.buildCardBinData(e)})}async setBillingAddress(e){let r=this.removeEmptyStringFromObject(e);return Object.values(r).length===0?Lt.noActionsResponse:this.postClientSessionActions([{type:"SET_BILLING_ADDRESS",params:{billingAddress:r}}])}async setShippingAddress(e,r,i){let n=[];return e&&Object.keys(e).some(s=>!!e[s])&&n.push({type:"SET_SHIPPING_ADDRESS",params:{shippingAddress:e}}),r&&n.push({type:"SET_MOBILE_NUMBER",params:{mobileNumber:r}}),i&&n.push({type:"SET_EMAIL_ADDRESS",params:{emailAddress:i}}),this.postClientSessionActions(n)}async selectShippingMethod(e){return this.postClientSessionActions([{type:"SELECT_SHIPPING_METHOD",params:{shippingMethodId:e}}])}async setCustomerDetails({emailAddress:e,firstName:r,lastName:i}){let n=[];return e&&n.push({type:"SET_EMAIL_ADDRESS",params:{emailAddress:e}}),r&&n.push({type:"SET_CUSTOMER_FIRST_NAME",params:{firstName:r}}),i&&n.push({type:"SET_CUSTOMER_LAST_NAME",params:{lastName:i}}),this.postClientSessionActions(n)}buildCardBinData(e){let{backend:r}=Zt(e);return{network:r,issuer_name:null,product_code:r,product_name:r,product_usage_type:"UNKNOWN",account_number_type:"UNKNOWN",issuer_country_code:null,account_funding_type:"UNKNOWN",issuer_currency_code:null,regional_restriction:"UNKNOWN",prepaid_reloadable_indicator:"NOT_APPLICABLE"}}removeEmptyStringFromObject(e){let r={...e};for(let i in r)r[i]===""?delete r[i]:typeof r[i]=="object"&&r[i]!==null&&!Array.isArray(r[i])&&(r[i]=this.removeEmptyStringFromObject(r[i]));return r}};S(Lt,"noActionsResponse",{data:{},error:void 0,headers:{},status:200,id:""});var Fi=Lt,Ui=class extends qt{async createPaypalOrder(t){return this.post(`${this.baseUrl}/paypal/orders/create`,t,{retry:{attempts:3}})}async createPaypalBillingAgreement(t){return this.post(`${this.baseUrl}/paypal/billing-agreements/create-agreement`,t,{retry:{attempts:3}})}async confirmPaypalBillingAgreement(t){return this.post(`${this.baseUrl}/paypal/billing-agreements/confirm-agreement`,t,{retry:{attempts:3}})}async createApplePaySession(t){return this.post(`${this.baseUrl}/apple-pay/sessions`,t)}async createKlarnaSession(t){return this.post(`${this.baseUrl}/klarna/payment-sessions`,t)}async finalizeKlarnaSession(t){return this.post(`${this.baseUrl}/klarna/payment-sessions/finalize`,t)}async createKlarnaCustomerToken(t){return this.post(`${this.baseUrl}/klarna/customer-tokens`,t)}async getPaymentMethodOptions(t){return this.get(`${this.baseUrl}/payment-method-options/${t}/payment-types`)}};async function Wp(a,{locale:t,dialogProvider:e,translate:r,clientOptions:i,integrationType:n="HEADLESS"}){let o=he(),s=ht(a),l=await jp(o),c=an({namespace:`api-controller-${o}`,onMessage:O=>{let z=Z=>{if(Z.data?.data?.error?.name==="RequestError"){let U=Object.assign(new le({...Z.data.data.error}),Z.data.data.error);typeof U.error=="object"&&"message"in U.error&&(U.error=Object.assign(new Error(U.error.message),{stack:U.error.stack})),Z.data.data.error=U}return O(Z.data)};return window.addEventListener("message",z),()=>window.removeEventListener("message",z)},sendMessage:O=>{l.contentWindow?.postMessage(O,"*")}}),p=wp(s.accessToken,o),m=new Gi(Kp,s.configurationUrl,p),g=Date.now(),{error:A}=await m.getConfiguration();if(A||!m.configuration)throw new Error(`Failed to fetch configuration: ${A}`);let M=c.fetch.bind(c),w=new Ki(M,m.configuration.pciUrl,p),L=new Ui(M,m.configuration.coreUrl,p),I=new Fi(M,m.configuration.pciUrl,p);I.setOnClientSessionUpdate(O=>{m.configuration=O});let _=new Set;return{get configuration(){return m.configuration},onClientConfigurationUpdate(O){return m.subscribe(O)},checkoutSessionId:o,integrationType:n,apiController:c,configurationApi:m,pciApi:w,coreApi:L,clientSessionApi:I,dialogProvider:e,decodedClientToken:s,locale:t||navigator.language||navigator.languages[0]||"en",configurationFetchStartTime:g,translate:r??((O,z)=>z),clientOptions:i,updateClientToken(O){try{let z=ht(O);m.setDefaultHeader("primer-client-token",z.accessToken),w.setDefaultHeader("primer-client-token",z.accessToken),L.setDefaultHeader("primer-client-token",z.accessToken),I.setDefaultHeader("primer-client-token",z.accessToken)}catch{}},async refreshClientConfiguration(){let{data:O,error:z}=await m.getConfiguration();return z||!O?(C.warn("Failed to refresh client configuration:",z),!1):(m.configuration=O,!0)},subscribeToTeardown(O){return _.add(O),()=>{_.delete(O)}},teardown(){l.remove(),_.forEach(O=>O())}}}var ss=({name:a,background:t,logoSrc:e,logoAlt:r,message:i})=>`<html>
|
|
71
71
|
<head>
|
|
72
72
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
73
73
|
<style>
|
|
@@ -175,9 +175,9 @@ import{a as jr,b as q,c as bi,d,e as S}from"./chunks/chunk.QNO3CTH5.js";var nc=q
|
|
|
175
175
|
</div>
|
|
176
176
|
</body>
|
|
177
177
|
</html>
|
|
178
|
-
`,Vi=class extends Ee{constructor(){super(...arguments);S(this,"popup");S(this,"shouldRedirect",!1);S(this,"redirectReason","force_redirect");S(this,"dialogPromise")}async setup(){return tn(this.context.clientOptions,this.config.type)}async start(){try{let e=this.callbacks.onStart(),r=this.config.forceRedirect||!!this.context.clientOptions.redirect?.forceRedirect;(r||Qi())&&(this.shouldRedirect=!0,this.redirectReason=r?"force_redirect":"in_app_browser");let i=document.createElement("div");i.setAttribute("style","display: flex; flex-direction: column; gap: var(--primer-size-xlarge);");let n=document.createElement("div");n.setAttribute("style",`display: flex;margin:auto;padding:calc(var(--primer-size-small)*0.5);height: var(--primer-size-xlarge);background-color: ${this.backgroundColor};border-radius:var(--primer-radius-small);`);let o=document.createElement("img");o.src=this.logoSrc,n.appendChild(o),o.setAttribute("style","height:100%;"),i.appendChild(n);let s=document.createElement("p");s.setAttribute("style","max-width: 300px;text-align: center;"),s.innerText=this.context.translate("paymentMethodPopupOverlayDescription","Having trouble viewing the {paymentMethodName} payment page? We'll help you find it!").replace("{paymentMethodName}",this.config.name),i.appendChild(s),this.dialogPromise=this.context.dialogProvider.show({htmlContent:i,showCloseButton:!0,size:"flex",cta:{label:this.context.translate("paymentMethodPopupOverlayBringBackThePaymentPage","Bring back the payment page"),icon:"chevron-left",onClick:()=>{this.popup?.focus()}}}),this.shouldRedirect||(this.openPopup(),this.popup&&await xt(300),this.popup?.isOpen||(this.shouldRedirect=!0,this.redirectReason="popup_blocked"));let{action:l}=await e;if(l==="abort")throw new R({message:"Payment creation aborted",code:O.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type});let c=await this.tokenize();this.callbacks.onFinish(c)}catch(e){this.context.dialogProvider.close(),this.popup?.close(),this.callbacks.onFinish(void 0,e)}}async tokenize(){let{error:e,data:r}=await this.context.pciApi.postRedirectPaymentInstruments({type:"OFF_SESSION_PAYMENT",paymentMethodType:this.config.type,paymentMethodConfigId:this.config.id,sessionInfo:{locale:this.context.locale,platform:Ar()?"MOBILE_WEB":"WEB",browserInfo:Rt(),merchantRedirectUrl:this.context.clientOptions.redirect?.returnUrl}});if(e||!r)throw e??new F({message:"Unable to tokenize payment method",code:O.TOKENIZATION_ERROR});return r}async createPayment(e){try{let r=await super.createPayment(e),i=r.requiredAction?.clientToken;if(!i)throw new F({message:"No client token provided"});let n=ht(i);if(!jo(n,this.config.type))throw new F({message:"Invalid client token"});if(this.shouldRedirect&&(rn(n.redirectUrl,this.config.type,this.redirectReason),window.location.assign(n.redirectUrl),await new Promise(()=>{})),!this.popup?.isOpen)return this.unselect(r),this.context.dialogProvider.close(),{...r,cancelled:!0};this.popup?.setUrl(n.redirectUrl);let o=(this.dialogPromise??Promise.resolve()).then(()=>({id:"",popupClosed:!0})),s=new Promise(g=>{this.popup?.onClose(()=>{C.debug("Popup closed"),g({id:"",popupClosed:!0})})}),l=new AbortController,c=this.context.pciApi.pollResumeStatus(n.statusUrl,{signal:l.signal,isComplete:g=>!!g.error||g.data?.status==="COMPLETE"}),p=await Promise.race([o,s,c.then(g=>g.error?{error:g.error,id:"",popupClosed:!1}:{id:g.data?.id??"",popupClosed:!1})]);if(l.abort(),this.popup?.close(),this.context.dialogProvider.close(),"error"in p)throw p.error;if("popupClosed"in p&&p.popupClosed&&!this.context.clientOptions.redirect?.resumePaymentOnPopupClosure)return this.unselect(r),{...r,cancelled:!0};let m=p.id;if(!m){let g=await this.context.pciApi.getResumeStatus(n.statusUrl);if(g.error||!g.data?.id)throw g.error??new Error("Unable to get resume token");m=g.data.id}return await this.resumePayment(r.id,m)}catch(r){throw this.context.dialogProvider.close(),this.popup?.close(),r}}unselect(e){this.context.clientSessionApi.unselectPaymentMethod(e)}openPopup(){let{name:e,displayMetadata:{popup:r}}=this.config;this.popup=en({name:e,height:r?.height??500,width:r?.width??1e3}),this.popup?.setContent(ss({name:e,background:this.backgroundColor,logoSrc:this.logoSrc,logoAlt:e,message:`Loading ${e}...`}))}get backgroundColor(){let{displayMetadata:{button:e,overlay:r}}=this.config;return r?.backgroundColor.colored||e?.backgroundColor.colored||r?.backgroundColor.light||e?.backgroundColor.light||r?.backgroundColor.dark||e?.backgroundColor.dark||"#FFFFFF"}get logoSrc(){let{displayMetadata:{button:e,overlay:r}}=this.config;return r?.logo.colored||e?.iconUrl.colored||r?.logo.light||e?.iconUrl.light||r?.logo.dark||e?.iconUrl.dark}},Hi=class{constructor(t,e){S(this,"currentState");S(this,"stateProcessor");S(this,"handlerRegistry");this.stateProcessor=t,this.handlerRegistry=e}async run(t){let e=await this.stateProcessor.initialize(t??{});return this.handle(e)}async resume(t){let e=await this.stateProcessor.resume(t);return this.handle(e)}async handleEvent(t){if(!this.currentState)throw new Error("handleEvent() called before run()");C.debug("Orchestrator handling event",t);let e=await this.stateProcessor.applyEvent(this.currentState,t);return this.handle(e)}async handle(t){if(this.currentState=t.newState,t.error)throw new Error(t.error.message);if(t.terminal)return C.debug("Orchestrator reached terminal",t.terminal),t.terminal;if(!t.action)return C.debug("Orchestrator waiting for external event"),null;let e=t.action;C.debug(`Executing ${e.type}`,e.params);let r,i;try{let o=await this.handlerRegistry.execute(e.type,e);r=o.outcome,i=o.data??{}}catch(o){C.warn(`Handler failed for ${e.type}`,o),r="error",i={error:o instanceof Error?o.message:"Unknown error"}}let n=await this.stateProcessor.applyResult(this.currentState,e.id,r,i);return this.handle(n)}},Yi=class{constructor(){S(this,"handlers",new Map)}register(t,e){this.handlers.set(t,e)}get(t){return this.handlers.get(t)}async execute(t,e){let r=this.handlers.get(t);return r?r.execute(e):{outcome:"unsupported"}}finishAll(){this.handlers.forEach(t=>t.onFinish?.())}},Zp=["https://sdk.primer.io/web/","https://sdk.dev.primer.io/web/","https://sdk.sandbox.primer.io/web/","https://sdk.production.primer.io/web/","https://sdk.primer.io/state-processor/","https://sdk.dev.primer.io/state-processor/","https://sdk.primer.io/cel-wrapper/","https://sdk.dev.primer.io/cel-wrapper/","https://assets.primer.io/","https://x.klarnacdn.net/kp/lib/v","https://www.paypal.com/sdk/js","https://www.paypalobjects.com/","https://js.stripe.com/","https://pay.google.com/gp/p/js/"];function Jp(a){return Zp.some(t=>a.startsWith(t))}async function Io(a,t){if(!Jp(a))throw new Error(`Script source not authorized per PCI DSS 6.4.3: ${a}`);await new Promise((e,r)=>{let i=document.createElement("script");i.src=a,i.integrity=`sha256-${t}`,i.crossOrigin="anonymous",i.onload=()=>{i.remove(),e()},i.onerror=()=>{i.remove(),r(new Error(`SRI check or load failed for script: ${a}`))},document.head.appendChild(i)})}async function qp(a,t){let e=await fetch(a).then(n=>n.arrayBuffer()),r=await crypto.subtle.digest("SHA-256",e);if(btoa(String.fromCharCode(...new Uint8Array(r)))!==t)throw new Error(`Integrity check failed for ${a}`);return e}var ls=["MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEUM5exrePPsIdkWFL6IjKdYmEDoEHBZkoBvrApQpmDEhQ7IisLTCiP0byqN+5B5V60QjAj4I/Bw292h8gPGZyOg==","MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAERA0j68aAYtwMDagEx2FY+CBbm2+MAYviARSMxWHt1Qt8wGyVvLJ2FqIvg4m2pKfb7GqUwzuJRD/gaOrO2ZJulQ==","MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEp7v1KpNTWcI9yJSoZYGvRxsPtciT99P2YDpISVLyD6BDD8xqJ11A8v2/elOEPaSxx5hConszht1cOlPp9YdTsA=="];function Qp(a){let t=2;a[1]===129&&(t=3),t++;let e=a[t++],r=a.slice(t,t+e);t+=e,t++;let i=a[t++],n=a.slice(t,t+i),o=new Uint8Array(new ArrayBuffer(64));return o.set(r.slice(-32),32-Math.min(r.length,32)),o.set(n.slice(-32),64-Math.min(n.length,32)),o}async function Xp(a){let t=Uint8Array.from(atob(a),e=>e.charCodeAt(0));return crypto.subtle.importKey("spki",t,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"])}async function em(a,t){let e=Qp(Uint8Array.from(atob(t),i=>i.charCodeAt(0))),r=new TextEncoder().encode(a);for(let i of ls)try{let n=await Xp(i);if(await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},n,e,r))return!0}catch{}return!1}async function tm(a){let e;for(let r=0;r<3;r++){r>0&&await xt(300*r);try{let i=await fetch(a.manifestUrl);if(!i.ok)throw new Error(`Failed to fetch state processor manifest: ${i.status}`);let n=await i.json(),{signature:o,manifest:s}=n;if(typeof o!="string"||typeof s!="string")throw new Error("Invalid manifest response format");let l=Cr.decode(s);if(!await em(l,o))throw new Error("Manifest signature verification failed");return JSON.parse(l)}catch(i){e=i}}throw e}async function rm(){return Promise.all(ls.map(async a=>{let t=Uint8Array.from(atob(a),r=>r.charCodeAt(0)),e=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(e)).map(r=>r.toString(16).padStart(2,"0")).join("")}))}async function am(a,t,e){let r=await tm(a),i=r.cel.noModules,n=await qp(i.wasm.br,i.wasm.sha256);typeof window.primer_wasm_bindgen!="function"&&await Io(i.js.url,i.js.sha256);let o=window.primer_wasm_bindgen;if(typeof o!="function")throw new Error("Invalid CEL wrapper: window.primer_wasm_bindgen not set after script load");await o(n),window.StateProcessor?.createStateProcessor||await Io(r.stateProcessor.umd.url,r.stateProcessor.umd.sha256);let s=window.StateProcessor;if(!s?.createStateProcessor)throw new Error("createStateProcessor not found after loading state processor module");return s.createStateProcessor(t,e)}function im(a,t){return new Promise((e,r)=>{if(t.aborted)return void r(new DOMException("Aborted","AbortError"));let i=setTimeout(e,a);t.addEventListener("abort",()=>{clearTimeout(i),r(new DOMException("Aborted","AbortError"))},{once:!0})})}var $i=class{constructor(t,e,r){S(this,"popup");S(this,"shouldRedirect",!1);S(this,"resolveOutcome");S(this,"context");S(this,"config");S(this,"onBeforeRedirect");this.context=t,this.config=e,this.onBeforeRedirect=r}async execute(t){let{url:e}=t.params,r=!!this.config.forceRedirect||!!this.context.clientOptions.redirect?.forceRedirect,i=null;return r?(this.shouldRedirect=!0,i="force_redirect"):Qi()&&(this.shouldRedirect=!0,i="in_app_browser"),this.showDialogOverlay(),this.shouldRedirect||(this.openPopup(),this.popup&&await xt(300),this.popup?.isOpen||(this.shouldRedirect=!0,i="popup_blocked")),this.shouldRedirect&&i?(rn(e,this.config.type,i),this.onBeforeRedirect(),window.location.assign(e),new Promise(()=>{})):(this.popup?.setUrl(e),new Promise(n=>{this.resolveOutcome=n,this.popup?.onClose(()=>{this.context.dialogProvider.close(),n({outcome:"cancelled"})})}))}onFinish(){this.resolveOutcome?.({outcome:"success"}),this.context.dialogProvider.close(),this.popup?.close()}get isOpen(){return this.popup?.isOpen??!1}focus(){this.popup?.focus()}openPopup(){let{popup:t}=this.config.displayMetadata;this.popup=en({name:this.config.name,height:t.height,width:t.width}),this.popup?.setContent(ss({name:this.config.name,background:this.backgroundColor,logoSrc:this.logoSrc,logoAlt:this.config.name,message:`Loading ${this.config.name}...`}))}showDialogOverlay(){let t=document.createElement("div");t.setAttribute("style","display: flex; flex-direction: column; gap: var(--primer-size-xlarge);");let e=document.createElement("div");e.setAttribute("style",`display: flex;margin:auto;padding:calc(var(--primer-size-small)*0.5);height: var(--primer-size-xlarge);background-color: ${this.backgroundColor};border-radius:var(--primer-radius-small);`);let r=document.createElement("img");r.src=this.logoSrc,e.appendChild(r),t.appendChild(e);let i=document.createElement("p");i.setAttribute("style","max-width: 300px;text-align: center;"),i.innerText=this.context.translate("paymentMethodPopupOverlayDescription","Having trouble viewing the {paymentMethodName} payment page? We'll help you find it!").replace("{paymentMethodName}",this.config.name),t.appendChild(i),this.context.dialogProvider.show({htmlContent:t,showCloseButton:!0,size:"flex",cta:{label:this.context.translate("paymentMethodPopupOverlayBringBackThePaymentPage","Bring back the payment page"),icon:"chevron-left",onClick:()=>{this.popup?.focus()}}}).then(()=>{this.popup?.isOpen&&this.popup.close()})}get backgroundColor(){let{displayMetadata:{button:t,overlay:e}}=this.config;return e?.backgroundColor.colored||t?.backgroundColor.colored||e?.backgroundColor.light||t?.backgroundColor.light||e?.backgroundColor.dark||t?.backgroundColor.dark||"#FFFFFF"}get logoSrc(){let{displayMetadata:{button:t,overlay:e}}=this.config;return e?.logo.colored||t?.iconUrl.colored||e?.logo.light||t?.iconUrl.light||e?.logo.dark||t?.iconUrl.dark||""}},zi=class{async execute(t){let{message:e,severity:r,context:i}=t.params.properties;return Ro(e,{status:r,metadata:i}),{outcome:"success"}}},ji=class{async execute(t){return Le({...t.params,eventName:t.params.eventName}),{outcome:"success"}}},Sr=class extends Ee{constructor(e,r){super(e,r);S(this,"onFinishCallback");S(this,"stepHandlerRegistry");S(this,"abortController");S(this,"stateProcessorConfig");this.stepHandlerRegistry=new Yi;let i=r.decodedClientToken.env,n=null;i!=="PRODUCTION"&&(n=new URLSearchParams(window.location.search).get("manifestUrl")),this.stateProcessorConfig={manifestUrl:n??`https://sdk.primer.io/state-processor/v0/manifests/${i.toLowerCase()}.json`},r.subscribeToTeardown(()=>{this.abortController?.abort(),this.stepHandlerRegistry?.finishAll()})}async setup(){return tn(this.context.clientOptions,this.config.type)?super.setup():!1}setOnFinishCallback(e){this.onFinishCallback=e}async tokenize(){throw new R({message:"Tokenize is not supported for backend-driven payment methods"})}async start(){let{action:e}=await this.callbacks.onStart();if(e==="abort")return;this.abortController=new AbortController;let r=this.abortController.signal;try{let i=this.context.configuration.clientSession.clientSessionId,n=await this.initiatePayment(i),o=await this.runInstructionLoop(n,i,r);if(r.aborted)return this.finishCancel();if(o.type!=="END")throw new R({message:"Unexpected final instruction type"});this.handleEndInstruction(o)}catch(i){if(r.aborted)return this.finishCancel();this.stepHandlerRegistry?.finishAll(),this.onFinishCallback?.({result:"complete",error:this.normalizeError(i)})}}async resume(e){this.abortController=new AbortController;let r=this.abortController.signal;try{let i=await this.fetchNextInstruction(e),n=await this.runInstructionLoop(i,e,r);if(r.aborted)return this.finishCancel();if(n.type!=="END")throw new R({message:"Unexpected final instruction type"});this.handleEndInstruction(n)}catch(i){if(r.aborted)return this.finishCancel();this.stepHandlerRegistry?.finishAll(),this.onFinishCallback?.({result:"complete",error:this.normalizeError(i)})}}async runInstructionLoop(e,r,i){let n=e,o=null;for(;!i.aborted&&n.type!=="END";){n.type==="EXECUTE"&&!o&&(o=this.processExecute(n)),await im(n.pollDelayMilliseconds,i);let s=this.fetchNextInstruction(r);if(o){let l=await Promise.race([s.then(c=>({kind:"poll",value:c})),o.then(c=>({kind:"orch",value:c}))]);if(l.kind==="orch"){if(l.value?.outcome==="cancelled"){this.abortController?.abort();break}if(l.value?.outcome==="error")throw s.catch(()=>{}),new Error("Step handler failed");n=await s,o=null;continue}n=l.value;continue}n=await s}return n}async initiatePayment(e){Yu(this.context.clientOptions,this.config.type);let{data:r,error:i}=await this.context.pciApi.postClientSessionPay(e,{paymentMethodConfigId:this.config.id,processorMerchantAccountId:this.config.options?.merchantAccountId??null,paymentMethodType:this.config.type,clientInfo:{locale:this.context.locale,platform:Ar()?"MOBILE_WEB":"WEB",browserInfo:Rt(),returnUri:this.context.clientOptions.redirect?.returnUrl}});if(i||!r)throw i??new R({message:"Failed to initiate backend-driven payment"});return r.clientInstruction}async fetchNextInstruction(e){let{data:r,error:i}=await this.context.pciApi.getClientSessionInstruction(e);if(i||!r)throw i??new R({message:"Failed to fetch payment instruction"});return r.clientInstruction}async processExecute(e){let{schema:r,parameters:i}=e.payload;rm().then(s=>{Le({eventName:"BDC_FLOW_START",trustedKeyFingerprints:s})}).catch(()=>{});let n=await am(this.stateProcessorConfig,JSON.stringify(r),this.buildSdkContext()),o=new Hi(n,this.stepHandlerRegistry);return this.stepHandlerRegistry.register("url.open",new $i(this.context,this.config,()=>this.abortController?.abort())),this.stepHandlerRegistry.register("platform.log",new zi),this.stepHandlerRegistry.register("analytics.event",new ji),o.run(i)}buildSdkContext(){let e=Rt();return{sdk:{type:"WEB",version:ma.getContext()?.sdkVersion??"",integrationType:this.context.integrationType},device:{locale:e.language,userAgent:e.userAgent},session:{checkoutSessionId:this.context.checkoutSessionId,clientSessionId:this.context.configuration.clientSession.clientSessionId,customerId:this.context.configuration.clientSession.customer?.customerId},merchant:{primerAccountId:this.context.configuration.primerAccountId},payment:{paymentMethodType:this.config.type}}}handleEndInstruction(e){this.stepHandlerRegistry?.finishAll();let{checkoutOutcome:r,payment:i}=e.payload;if(i){let{paymentInstrumentToken:n,...o}=i;this.onFinishCallback?.({result:"complete",payment:{...o,checkoutOutcome:r},token:n})}else this.onFinishCallback?.({result:"complete"})}finishCancel(){this.stepHandlerRegistry?.finishAll(),this.onFinishCallback?.({result:"cancel"})}normalizeError(e){return e instanceof R?e:e instanceof Error?new R({message:e.message}):new R({message:String(e)})}},nm=[B.ADYEN_AFFIRM,B.ADYEN_BANCONTACT_CARD,B.ADYEN_BANCONTACT_PAYCONIQ,B.ADYEN_EPS,B.ADYEN_MULTIBANCO,B.GO_CARDLESS,B.OMISE_PROMPTPAY,B.RAPYD_FAST,B.RAPYD_PROMPTPAY,B.STRIPE_ACH,B.XFERS_PAYNOW,B.NETS];async function om(a,t){let r=a.configuration.paymentMethods.filter(({type:n})=>!t||t.includes(n)).map(n=>{if(nm.includes(n.type))return C.warn(`Payment method ${n.type} is not supported in sdk core.`),null;if(C.debug("Initializing payment method:",n.type),n.implementationType==="BACKEND_DRIVEN"||n.implementationType==="WEB_REDIRECT"&&n.capabilities?.includes("BACKEND_DRIVEN"))return new Sr(n,a);if(n.implementationType==="WEB_REDIRECT")return new Vi(n,a);if(n.type===B.PAYMENT_CARD)return new oa(n,a);if(n.type===B.PAYPAL)return new pa(n,a);if(n.type===B.APPLE_PAY)return new ia(n,a);if(n.type===B.GOOGLE_PAY)return new sa(n,a);if(n.type===B.ADYEN_BLIK)return new na(n,a);if(n.type===B.KLARNA)return new da(n,a);if(n.type===B.ADYEN_KLARNA)return new ca(n,a);if(n.type===B.ADYEN_MBWAY)return new ua(n,a)}).map(async n=>{if(!n)return null;try{return await n.setup()?n:null}catch(o){return C.warn(`Failed to initialize payment method ${n.config.type}:`,o),null}});return(await Promise.all(r)).filter(n=>!!n)}function sm(a,t,e){if(!t.configuration.clientSession.customer?.customerId)throw new R({message:"You must provide a `customerId` in the client session to use the Vault Manager."});let r=[];return{async fetchVaultedPaymentMethods(){let{data:i,error:n}=await t.pciApi.getPaymentInstruments();if(n)throw n;if(!i)throw new R({code:Zr.VAULT_ERROR,message:"Missing vaulted payment methods data"});return r=lm(i.data,t.configuration?.clientSession?.paymentMethod?.orderedAllowedCardNetworks),r},async deleteVaultedPaymentMethod(i){if(!r.find(s=>s.id===i))throw new R({code:Zr.VAULT_ERROR,message:"deleteVaultedPaymentMethod: the id provided doesn't match any vaulted payment method"});let{error:o}=await t.pciApi.deletePaymentInstrument(i);if(o)throw o;r=r.filter(s=>s.id!==i)},async startPaymentFlow(i){let n=r.find(s=>s.id===i);if(!n)throw new R({code:Zr.VAULT_ERROR,message:"startPaymentFlow: the id provided doesn't match any vaulted payment method"});let o=e.find(s=>s.config.type===n.paymentMethodType);if(!o)throw new F({code:Zr.TOKENIZATION_ERROR,message:`Payment instrument type ${n.paymentInstrumentType} is not recognized or not supported.`});await We(a,o,n)},async createCvvInput(i){let n={blur:new Set,change:new Set,focus:new Set},o,s=yr(t.checkoutSessionId,po);await new Promise(g=>{s.onload=()=>{g()},(typeof i.container=="string"?document.querySelector(i.container):i.container)?.appendChild(s)}),Di(s,i.style),s.setAttribute("title",i.ariaLabel||"");let l=an({namespace:`${t.checkoutSessionId}-${po}`,onMessage:g=>{let A=M=>g(M.data);return window.addEventListener("message",A),()=>window.removeEventListener("message",A)},sendMessage:g=>{s.contentWindow?.postMessage(g,"*")}});function c(g,A){g!=="metadata"&&n[g].add(A)}l.setOnFocus(()=>{n.focus.forEach(g=>g())}),l.setOnBlur(()=>{n.blur.forEach(g=>g())}),l.setOnInput(g=>{o=g,n.change.forEach(A=>A())}),l.setCardNetwork(i.cardNetwork??""),l.setOptions({placeholder:i.placeholder??"123",ariaLabel:i.ariaLabel??"CVV",style:i.style});function p(){s.parentNode&&s.remove()}let m=t.subscribeToTeardown(p);return{frame:s,remove:()=>{m(),p()},get metadata(){return{error:o?.error??"cvvRequired",errorCode:o?.error??"cvvRequired",valid:o?.valid??!1,active:o?.focused??!1,dirty:o?.dirty??!1,touched:o?.touched??!1,submitted:!0}},addEventListener:c,addListener:c,removeListener(g,A){g!=="metadata"&&n[g].delete(A)},blur(){l.blur()},focus(){l.focus()},validate(){l.getFieldState().then(g=>{o=g,n.change.forEach(A=>A(o))})}}}}}function lm(a,t){if(!t||t.length===0)return a;let e=new Set(t.map(r=>Zt(r).backend));return a.filter(r=>{if(r.paymentInstrumentType!==Jc.CARD)return!0;let i=r.paymentInstrumentData?.network;return typeof i!="string"||!i?!0:e.has(Zt(i).backend)})}function dm(a,t,e){return e.setOnFinishCallback(r=>{r.result==="cancel"?t.clientSessionApi.unselectPaymentMethod():br(a,r.payment,r.error,r.token,e.config.type)}),{start:()=>We(a,e)}}async function ds(a,t){C.debug("createHeadless",t);let e=await Wp(a,{locale:t.locale,dialogProvider:t.dialogProvider,translate:t.translate,integrationType:t.integrationType,clientOptions:{paypal:t.paypal,applePay:t.applePay,googlePay:t.googlePay,klarna:t.klarna,merchantDomain:t.merchantDomain,redirect:t.redirect,card:t.card}}),r=await om(e,t.enabledPaymentMethods);t.onClientSessionUpdate?.(e.configuration.clientSession),e.onClientConfigurationUpdate(async n=>{t.onClientSessionUpdate?.(n.clientSession)}),t.onPaymentMethodAction&&e.clientSessionApi.setOnPaymentMethodAction((n,o)=>t.onPaymentMethodAction?.(n,{...o,payment:Oi(o.payment,o.token)??void 0}));let i={environment:_i?"LOCAL":e.decodedClientToken.env,primerAccountId:e.configuration.primerAccountId,checkoutSessionId:e.checkoutSessionId,clientSessionId:e.configuration.clientSession?.clientSessionId,clientSessionToken:a,sdkVersion:t.sdkVersion,configurationFetchStartTime:e.configurationFetchStartTime};return zc({environment:_i?"LOCAL":e.decodedClientToken.env,primerAccountId:i.primerAccountId||"",checkoutSessionId:i.checkoutSessionId,clientSessionId:i.clientSessionId||"",clientSessionToken:i.clientSessionToken,sdkVersion:i.sdkVersion||"",userAgent:typeof navigator<"u"?navigator.userAgent:"unknown"}),t.onAvailablePaymentMethodsLoad?.(r.map(n=>({type:n.config.type,managerType:cm(n)}))),{start:async()=>{if(e.decodedClientToken.intent==="REDIRECTION_END"){fo(e.decodedClientToken.intent,{paymentId:e.decodedClientToken.paymentId});let{data:n,error:o}=await e.pciApi.postResumePayment(e.decodedClientToken.paymentId,e.decodedClientToken.resumeToken);br(t,n,o);return}if(e.decodedClientToken.intent==="AWAIT_CLIENT_INSTRUCTION"){let{clientSessionId:n,paymentMethodType:o,intent:s}=e.decodedClientToken;fo(s,{paymentMethod:o});let l=r.find(c=>c instanceof Sr&&c.config.type===o);if(!l)return void br(t,void 0,new R({message:"No backend-driven payment method found for resume"}));l.setOnFinishCallback(({result:c,payment:p,error:m,token:g})=>{c!=="cancel"&&br(t,p,m,g,l.config.type)}),await l.resume(n);return}},createPaymentMethodManager:async(n,o)=>{let s=r.find(({config:l})=>l.type===n);return s?s instanceof oa?Mp(t,e,s,o):s instanceof pa||s instanceof ia||s instanceof sa?Tp(t,e,s):s instanceof na?Ip(t,e,s):s instanceof Sr?dm(t,e,s):s instanceof da?kp(t,e,s,o):s instanceof ca?Lp(t,e,s,o):s instanceof ua?Rp(t,e,s):Np(t,e,s):(C.warn(`Payment method ${n} not found`),null)},getSDKUtilities:()=>({getCardNetworkAsset:ko,getUIOrderAmount:()=>{let{merchantAmount:n,totalOrderAmount:o,currencyCode:s}=e.configuration.clientSession.order;return Zo(e.locale,n??o,s)},getCDNAssets:async n=>{let o=r.find(({config:c})=>c.type===n);if(!o)return;let{backgroundColor:s}=o.config.displayMetadata?.button||{};return{assets:{icon:n?`brand/icon/${n.toLowerCase().replace(/_/g,"-")}.svg`:""},colors:{background:s?.colored||"",main:s?.colored||""},description:o.config.name||null,is_primer_app:!1,name:o.config.name,website:null,goatCdnUrl:es}},getPaymentMethodConfiguration:n=>r.find(({config:o})=>o.type===n)?.config,setBillingAddress:async n=>{let{error:o,data:s}=await e.clientSessionApi.setBillingAddress(n);if(o||!s)throw o||new R({message:"Failed to set billing address"})}}),getAnalyticsUtils:()=>i,createVaultManager(){return sm(t,e,r)},getAssetsManager:()=>({getCardNetworkAsset:ko,getPaymentMethodAsset:async n=>{let o=r.find(({config:p})=>p.type===n);if(!o)return null;let{backgroundColor:s,iconUrl:l,text:c}=o.config.displayMetadata?.button||{};return{backgroundColor:s,iconUrl:l,paymentMethodName:c,buttonText:c,displayName:o.config.name}}}),refreshClientSession:e.refreshClientConfiguration,getConfiguration:()=>e.configuration,teardown:()=>e.teardown()}}function cm(a){switch(a.config.type){case B.PAYMENT_CARD:return jt.CARD;case B.KLARNA:return jt.KLARNA;case B.ADYEN_KLARNA:return jt.ADYEN_KLARNA;case B.ADYEN_MBWAY:return jt.MBWAY;default:return a.config.implementationType==="NATIVE_SDK"?jt.NATIVE:jt.REDIRECT}}var ko=a=>{let{asset:t,display:e}=Zt(a);return{cardUrl:`${es}/brand/card/${t}.svg`,displayName:e}},um=new Set(["paymentMethodType","last4Digits","network","accountNumberLastFourDigits","bankName"]);function Xt(a){let{id:t,orderId:e,paymentMethodData:r}=a,i={id:t,orderId:e};if(!r||typeof r!="object")return i;let n={};for(let[o,s]of Object.entries(r))um.has(o)&&(n[o]=s);return i.paymentMethodData=n,i}var pm={PAYMENT_CARD:{fields:["last4Digits","network","cardholderName","expirationMonth","expirationYear"]},PAYPAL_BILLING_AGREEMENT:{path:"externalPayerInfo",fields:["externalPayerId","email","firstName","lastName"]},KLARNA_CUSTOMER_TOKEN:{path:"sessionData.billingAddress",fields:["email","firstName","lastName","phoneNumber"]},AUTOMATED_CLEARING_HOUSE:{fields:["accountNumberLastFourDigits","bankName","accountType"]}};function mm(a,t){let e=a;for(let r of t.split(".")){if(!e||typeof e!="object")return;e=e[r]}return e&&typeof e=="object"?e:void 0}function hm(a,t){if(!a)return;let e={};for(let r of t)a[r]!==void 0&&(e[r]=a[r]);return Object.keys(e).length>0?e:void 0}function cs(a){let{id:t,analyticsId:e,paymentMethodType:r,paymentInstrumentType:i,paymentInstrumentData:n,userDescription:o}=a,s=pm[i],l;if(s&&n&&typeof n=="object"){let c=s.path?mm(n,s.path):n;l=hm(c,s.fields)}return{id:t,analyticsId:e,paymentMethodType:r,paymentInstrumentType:i,...o&&{userDescription:o},...l&&{paymentInstrumentData:l}}}var er=class{constructor(t){this.host=t}dispatchEvent(t,e){this.host.dispatchEvent(new CustomEvent(t,{detail:e,bubbles:!0,composed:!0}))}dispatchSdkState(t){this.dispatchEvent("primer:state-change",t)}dispatchPaymentMethods(t){this.dispatchEvent("primer:methods-update",t)}dispatchCheckoutInitialized(t){this.dispatchEvent("primer:ready",t)}dispatchCardNetworkChange(t){this.dispatchEvent("primer:card-network-change",t)}dispatchBinDataAvailable(t){this.dispatchEvent("primer:bin-data-available",t)}dispatchBinDataLoadingChange(t){this.dispatchEvent("primer:bin-data-loading-change",{loading:t})}dispatchCardSubmit(t){this.dispatchEvent("primer:card-submit",{source:t})}dispatchFormSubmitSuccess(t){this.dispatchEvent("primer:card-success",{result:t})}dispatchFormSubmitErrors(t){this.dispatchEvent("primer:card-error",{errors:t})}dispatchPaymentCancel(t){let e=Math.floor(Date.now()/1e3);this.dispatchEvent("primer:payment-cancel",{...t,timestamp:e})}handleExternalCardSubmit(t){this.dispatchCardSubmit(t.source)}dispatchPaymentStart(t,e){let r=Math.floor(Date.now()/1e3),i=!1,n=new CustomEvent("primer:payment-start",{detail:{paymentMethodType:t,abortPaymentCreation:()=>{i=!0,e.abortPaymentCreation()},continuePaymentCreation:o=>{i=!0,e.continuePaymentCreation(o)},timestamp:r},bubbles:!0,composed:!0,cancelable:!0});return this.host.dispatchEvent(n),n.defaultPrevented?!0:i}dispatchPaymentSuccess(t,e){let r=Xt(t),i=Math.floor(Date.now()/1e3);this.dispatchEvent("primer:payment-success",{payment:r,paymentMethodType:e,timestamp:i})}dispatchPaymentFailure(t,e,r){let i=Math.floor(Date.now()/1e3),n=r?Xt(r):void 0;this.dispatchEvent("primer:payment-failure",{error:t,payment:n,paymentMethodType:e,timestamp:i})}dispatchVaultMethodsUpdate(t,e){let r=Math.floor(Date.now()/1e3);this.dispatchEvent("primer:vault-methods-update",{vaultedPayments:t,cvvRecapture:e,timestamp:r})}dispatchVaultSelectionChange(t){let e=Math.floor(Date.now()/1e3);this.dispatchEvent("primer:vault-selection-change",{paymentMethodId:t,timestamp:e})}dispatchVaultSubmit(t){this.dispatchEvent("primer:vault-submit",{source:t})}handleExternalVaultSubmit(t){this.dispatchVaultSubmit(t.source)}dispatchShowOtherPaymentsToggle(t,e){this.dispatchEvent("primer:show-other-payments-toggle",{action:t,source:e})}handleExternalShowOtherPaymentsToggle(t){this.dispatchShowOtherPaymentsToggle(t.action,t.source)}dispatchShowOtherPaymentsToggled(t){this.dispatchEvent("primer:show-other-payments-toggled",{expanded:t})}};var gt=class extends Event{constructor(t,e,r,i){super("context-request",{bubbles:!0,composed:!0}),this.context=t,this.contextTarget=e,this.callback=r,this.subscribe=i??!1}};var tr=class{constructor(t,e,r,i){if(this.subscribe=!1,this.provided=!1,this.value=void 0,this.t=(n,o)=>{this.unsubscribe&&(this.unsubscribe!==o&&(this.provided=!1,this.unsubscribe()),this.subscribe||this.unsubscribe()),this.value=n,this.host.requestUpdate(),this.provided&&!this.subscribe||(this.provided=!0,this.callback&&this.callback(n,o)),this.unsubscribe=o},this.host=t,e.context!==void 0){let n=e;this.context=n.context,this.callback=n.callback,this.subscribe=n.subscribe??!1}else this.context=e,this.callback=r,this.subscribe=i??!1;this.host.addController(this)}hostConnected(){this.dispatchRequest()}hostDisconnected(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=void 0)}dispatchRequest(){this.host.dispatchEvent(new gt(this.context,this.host,this.t,this.subscribe))}};var ga=class{get value(){return this.o}set value(t){this.setValue(t)}setValue(t,e=!1){let r=e||!Object.is(t,this.o);this.o=t,r&&this.updateObservers()}constructor(t){this.subscriptions=new Map,this.updateObservers=()=>{for(let[e,{disposer:r}]of this.subscriptions)e(this.o,r)},t!==void 0&&(this.value=t)}addCallback(t,e,r){if(!r)return void t(this.value);this.subscriptions.has(t)||this.subscriptions.set(t,{disposer:()=>{this.subscriptions.delete(t)},consumerHost:e});let{disposer:i}=this.subscriptions.get(t);t(this.value,i)}clearCallbacks(){this.subscriptions.clear()}};var nn=class extends Event{constructor(t,e){super("context-provider",{bubbles:!0,composed:!0}),this.context=t,this.contextTarget=e}},yt=class extends ga{constructor(t,e,r){super(e.context!==void 0?e.initialValue:r),this.onContextRequest=i=>{if(i.context!==this.context)return;let n=i.contextTarget??i.composedPath()[0];n!==this.host&&(i.stopPropagation(),this.addCallback(i.callback,n,i.subscribe))},this.onProviderRequest=i=>{if(i.context!==this.context||(i.contextTarget??i.composedPath()[0])===this.host)return;let n=new Set;for(let[o,{consumerHost:s}]of this.subscriptions)n.has(o)||(n.add(o),s.dispatchEvent(new gt(this.context,s,o,!0)));i.stopPropagation()},this.host=t,e.context!==void 0?this.context=e.context:this.context=e,this.attachListeners(),this.host.addController?.(this)}attachListeners(){this.host.addEventListener("context-request",this.onContextRequest),this.host.addEventListener("context-provider",this.onProviderRequest)}hostConnected(){this.host.dispatchEvent(new nn(this.context,this.host))}};function G({context:a,subscribe:t}){return(e,r)=>{typeof r=="object"?r.addInitializer((function(){new tr(this,{context:a,callback:i=>{e.set.call(this,i)},subscribe:t})})):e.constructor.addInitializer((i=>{new tr(i,{context:a,callback:n=>{i[r]=n},subscribe:t})}))}}var K=Symbol("primer-context");function ft(a,t,e=0,r=10){if(e>r)return a===t;if(a===t)return!0;if(a==null||t==null||typeof a!="object"||typeof t!="object")return!1;let i=Object.keys(a);if(i.length!==Object.keys(t).length)return!1;for(let n of i){if(!(n in t))return!1;let o=a[n],s=t[n];if(typeof o=="object"&&o!==null&&(typeof s=="object"&&s!==null)){if(!ft(o,s,e+1,r))return!1}else if(o!==s)return!1}return!0}var ps={klarnaCategories:{categories:[],isLoading:!0},sdkState:{isSuccessful:!1,isProcessing:!1,isLoading:!1,primerJsError:null,paymentFailure:null},paymentMethods:[]},ya=class{constructor(t){(this.host=t).addController(this),this.contextProvider=new yt(t,{context:K,initialValue:structuredClone(ps)})}hostConnected(){}setContext(t){this.contextProvider?.setValue({...this.contextProvider.value,...t})}setSdkState(t){let e=this.contextProvider.value.sdkState,r={...e,...t};ft(e,r)||(this.host.primerEventsController.dispatchSdkState(r),this.setContext({sdkState:r}))}resetSdkState(){this.setContext(structuredClone(ps))}setCardNetworks(t){this.setContext({cardNetworks:t})}setCardNetworksLoadingFalse(){this.setContext({cardNetworks:{detectedCardNetwork:this.contextProvider.value.cardNetworks?.detectedCardNetwork??null,selectableCardNetworks:this.contextProvider.value.cardNetworks?.selectableCardNetworks??[],isLoading:!1}})}setVaultManager(t){this.setContext({vaultManager:t})}setKlarnaCategories(t){this.setContext({klarnaCategories:t})}setAdyenKlarnaOptions(t){this.setContext({adyenKlarnaOptions:t})}setComputedStyles(t){this.setContext({computedStyles:t})}setVaultManagerCvv(t){this.setContext({vaultItem:t})}setEventsController(t){this.setContext({events:t})}};var _t=class _t{constructor(t){(this.host=t).addController(this)}processCustomStyles(t){try{let e=JSON.parse(t);this.applyStyles(e)}catch(e){P.error("Error parsing customStyles property.",e instanceof Error?e:new Error(String(e)))}}isValidCssProperty(t){return/^[a-zA-Z][a-zA-Z0-9]*$/.test(t)}isValidCssValue(t){let r=/^[\w\s#.,%()\-+/!]+$/.test(t);return r||P.warn(`Rejected potentially unsafe CSS value: ${t}`),r}getCssVarName(t){let e=_t.cssVarCache.get(t);return e||(e=`--${t.replace(/([A-Z])/g,(r,i)=>`-${i.toLowerCase()}`)}`,_t.cssVarCache.set(t,e)),e}applyStyles(t){let e=[];for(let r of Object.keys(t)){let i=t[r];if(!i)continue;if(!this.isValidCssProperty(r)){P.warn(`Skipping invalid CSS property name: ${r}`);continue}if(!this.isValidCssValue(i))continue;let n=this.getCssVarName(r);e.push([n,i])}if(e.length>0)for(let[r,i]of e)this.host.style.setProperty(r,i)}removeStyle(t){let e=this.getCssVarName(t);this.host.style.removeProperty(e)}clearAllStyles(){for(let t of _t.cssVarCache.keys()){let e=_t.cssVarCache.get(t);e&&this.host.style.removeProperty(e)}}hostDisconnected(){}};_t.cssVarCache=new Map;var fa=_t;var va=globalThis,Ca=va.ShadowRoot&&(va.ShadyCSS===void 0||va.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,hs=Symbol(),ms=new WeakMap,ba=class{constructor(t,e,r){if(this._$cssResult$=!0,r!==hs)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=e}get styleSheet(){let t=this.o,e=this.t;if(Ca&&t===void 0){let r=e!==void 0&&e.length===1;r&&(t=ms.get(e)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),r&&ms.set(e,t))}return t}toString(){return this.cssText}},gs=a=>new ba(typeof a=="string"?a:a+"",void 0,hs);var on=(a,t)=>{if(Ca)a.adoptedStyleSheets=t.map((e=>e instanceof CSSStyleSheet?e:e.styleSheet));else for(let e of t){let r=document.createElement("style"),i=va.litNonce;i!==void 0&&r.setAttribute("nonce",i),r.textContent=e.cssText,a.appendChild(r)}},Sa=Ca?a=>a:a=>a instanceof CSSStyleSheet?(t=>{let e="";for(let r of t.cssRules)e+=r.cssText;return gs(e)})(a):a;var{is:gm,defineProperty:ym,getOwnPropertyDescriptor:fm,getOwnPropertyNames:vm,getOwnPropertySymbols:bm,getPrototypeOf:Cm}=Object,vt=globalThis,ys=vt.trustedTypes,Sm=ys?ys.emptyScript:"",Am=vt.reactiveElementPolyfillSupport,Er=(a,t)=>a,sn={toAttribute(a,t){switch(t){case Boolean:a=a?Sm:null;break;case Object:case Array:a=a==null?a:JSON.stringify(a)}return a},fromAttribute(a,t){let e=a;switch(t){case Boolean:e=a!==null;break;case Number:e=a===null?null:Number(a);break;case Object:case Array:try{e=JSON.parse(a)}catch{e=null}}return e}},Aa=(a,t)=>!gm(a,t),fs={attribute:!0,type:String,converter:sn,reflect:!1,hasChanged:Aa};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),vt.litPropertyMetadata??(vt.litPropertyMetadata=new WeakMap);var Ot=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??(this.l=[])).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,e=fs){if(e.state&&(e.attribute=!1),this._$Ei(),this.elementProperties.set(t,e),!e.noAccessor){let r=Symbol(),i=this.getPropertyDescriptor(t,r,e);i!==void 0&&ym(this.prototype,t,i)}}static getPropertyDescriptor(t,e,r){let{get:i,set:n}=fm(this.prototype,t)??{get(){return this[e]},set(o){this[e]=o}};return{get(){return i?.call(this)},set(o){let s=i?.call(this);n.call(this,o),this.requestUpdate(t,s,r)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??fs}static _$Ei(){if(this.hasOwnProperty(Er("elementProperties")))return;let t=Cm(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(Er("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Er("properties"))){let e=this.properties,r=[...vm(e),...bm(e)];for(let i of r)this.createProperty(i,e[i])}let t=this[Symbol.metadata];if(t!==null){let e=litPropertyMetadata.get(t);if(e!==void 0)for(let[r,i]of e)this.elementProperties.set(r,i)}this._$Eh=new Map;for(let[e,r]of this.elementProperties){let i=this._$Eu(e,r);i!==void 0&&this._$Eh.set(i,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){let e=[];if(Array.isArray(t)){let r=new Set(t.flat(1/0).reverse());for(let i of r)e.unshift(Sa(i))}else t!==void 0&&e.push(Sa(t));return e}static _$Eu(t,e){let r=e.attribute;return r===!1?void 0:typeof r=="string"?r:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise((t=>this.enableUpdating=t)),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach((t=>t(this)))}addController(t){(this._$EO??(this._$EO=new Set)).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){let t=new Map,e=this.constructor.elementProperties;for(let r of e.keys())this.hasOwnProperty(r)&&(t.set(r,this[r]),delete this[r]);t.size>0&&(this._$Ep=t)}createRenderRoot(){let t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return on(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),this._$EO?.forEach((t=>t.hostConnected?.()))}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach((t=>t.hostDisconnected?.()))}attributeChangedCallback(t,e,r){this._$AK(t,r)}_$EC(t,e){let r=this.constructor.elementProperties.get(t),i=this.constructor._$Eu(t,r);if(i!==void 0&&r.reflect===!0){let n=(r.converter?.toAttribute!==void 0?r.converter:sn).toAttribute(e,r.type);this._$Em=t,n==null?this.removeAttribute(i):this.setAttribute(i,n),this._$Em=null}}_$AK(t,e){let r=this.constructor,i=r._$Eh.get(t);if(i!==void 0&&this._$Em!==i){let n=r.getPropertyOptions(i),o=typeof n.converter=="function"?{fromAttribute:n.converter}:n.converter?.fromAttribute!==void 0?n.converter:sn;this._$Em=i,this[i]=o.fromAttribute(e,n.type),this._$Em=null}}requestUpdate(t,e,r){if(t!==void 0){if(r??(r=this.constructor.getPropertyOptions(t)),!(r.hasChanged??Aa)(this[t],e))return;this.P(t,e,r)}this.isUpdatePending===!1&&(this._$ES=this._$ET())}P(t,e,r){this._$AL.has(t)||this._$AL.set(t,e),r.reflect===!0&&this._$Em!==t&&(this._$Ej??(this._$Ej=new Set)).add(t)}async _$ET(){this.isUpdatePending=!0;try{await this._$ES}catch(e){Promise.reject(e)}let t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(let[i,n]of this._$Ep)this[i]=n;this._$Ep=void 0}let r=this.constructor.elementProperties;if(r.size>0)for(let[i,n]of r)n.wrapped!==!0||this._$AL.has(i)||this[i]===void 0||this.P(i,this[i],n)}let t=!1,e=this._$AL;try{t=this.shouldUpdate(e),t?(this.willUpdate(e),this._$EO?.forEach((r=>r.hostUpdate?.())),this.update(e)):this._$EU()}catch(r){throw t=!1,this._$EU(),r}t&&this._$AE(e)}willUpdate(t){}_$AE(t){this._$EO?.forEach((e=>e.hostUpdated?.())),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EU(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Ej&&(this._$Ej=this._$Ej.forEach((e=>this._$EC(e,this[e])))),this._$EU()}updated(t){}firstUpdated(t){}};Ot.elementStyles=[],Ot.shadowRootOptions={mode:"open"},Ot[Er("elementProperties")]=new Map,Ot[Er("finalized")]=new Map,Am?.({ReactiveElement:Ot}),(vt.reactiveElementVersions??(vt.reactiveElementVersions=[])).push("2.0.4");var bt={INITIAL:0,PENDING:1,COMPLETE:2,ERROR:3},Y=Symbol(),$=class{get taskComplete(){return this.t||(this.i===1?this.t=new Promise(((t,e)=>{this.o=t,this.h=e})):this.i===3?this.t=Promise.reject(this.l):this.t=Promise.resolve(this.u)),this.t}constructor(t,e,r){this.p=0,this.i=0,(this._=t).addController(this);let i=typeof e=="object"?e:{task:e,args:r};this.v=i.task,this.j=i.args,this.m=i.argsEqual??vs,this.k=i.onComplete,this.A=i.onError,this.autoRun=i.autoRun??!0,"initialValue"in i&&(this.u=i.initialValue,this.i=2,this.O=this.T?.())}hostUpdate(){this.autoRun===!0&&this.S()}hostUpdated(){this.autoRun==="afterUpdate"&&this.S()}T(){if(this.j===void 0)return;let t=this.j();if(!Array.isArray(t))throw Error("The args function must return an array");return t}async S(){let t=this.T(),e=this.O;this.O=t,t===e||t===void 0||e!==void 0&&this.m(e,t)||await this.run(t)}async run(t){let e,r;t??(t=this.T()),this.O=t,this.i===1?this.q?.abort():(this.t=void 0,this.o=void 0,this.h=void 0),this.i=1,this.autoRun==="afterUpdate"?queueMicrotask((()=>this._.requestUpdate())):this._.requestUpdate();let i=++this.p;this.q=new AbortController;let n=!1;try{e=await this.v(t,{signal:this.q.signal})}catch(o){n=!0,r=o}if(this.p===i){if(e===Y)this.i=0;else{if(n===!1){try{this.k?.(e)}catch{}this.i=2,this.o?.(e)}else{try{this.A?.(r)}catch{}this.i=3,this.h?.(r)}this.u=e,this.l=r}this._.requestUpdate()}}abort(t){this.i===1&&this.q?.abort(t)}get value(){return this.u}get error(){return this.l}get status(){return this.i}render(t){switch(this.i){case 0:return t.initial?.();case 1:return t.pending?.();case 2:return t.complete?.(this.value);case 3:return t.error?.(this.error);default:throw Error("Unexpected status: "+this.i)}}},vs=(a,t)=>a===t||a.length===t.length&&a.every(((e,r)=>!Aa(e,t[r])));var Ea={enabled:!1,isLoading:!1,isUpdating:!1,cvvRecapture:!1,showEmptyState:!1,headless:!1,vaultedPaymentMethods:[],createCvvInput:null,deleteVaultedPaymentMethod:()=>Promise.resolve(),startVaultedPaymentFlow:()=>Promise.resolve()},bs={cvvInput:null,formIsDirty:!1,setCvvInput:()=>{},selectedVaultedPaymentMethod:null,setSelectedVaultedPaymentMethod:()=>{}},Mr=class{constructor(t){this.host=t;this._coreState={...Ea};this._itemState={...bs};this._vaultManager=null;this._options=null;this.createVaultManagerFn=null;this.createCvvInput=t=>{if(!this._vaultManager)throw new Error("Vault manager not initialized");return this._vaultManager.createCvvInput(t)};this.deleteVaultedPaymentMethod=async t=>{if(!this._vaultManager)throw new Error("Vault manager not initialized");try{this.updateCoreState({vaultedPaymentMethods:this._coreState.vaultedPaymentMethods}),await this._vaultManager.deleteVaultedPaymentMethod(t),await this.fetchVaultedPaymentMethods()}catch(e){let r=e instanceof Error?e:new Error("Failed to delete payment method");throw this.updateCoreState({isLoading:!1,isUpdating:!1}),this.host.sdkContextController.setSdkState({primerJsError:r}),e}};this.setCvvInput=t=>{this.updateItemState({cvvInput:t})};this.startVaultedPaymentFlow=async()=>{if(!this._vaultManager)throw new Error("Vault manager not initialized");let t=this._itemState.selectedVaultedPaymentMethod,e=this._coreState.cvvRecapture,r=this._itemState.cvvInput;if(!t||e&&(!r||r.metadata.error)){this.updateItemState({formIsDirty:!0});return}this.host.sdkContextController.setSdkState({isProcessing:!0,paymentFailure:null,primerJsError:null});try{await this._vaultManager.startPaymentFlow(t.id,e?{cvv:r?.valueToken}:void 0)}catch(i){P.errorWithDatadog("VaultManagerController: Error starting vaulted payment flow",{error:i});let n=i instanceof Error?i:new Error("Failed to start vaulted payment flow");this.updateCoreState({isLoading:!1,isUpdating:!1}),this.host.sdkContextController.setSdkState({isProcessing:!1,primerJsError:n})}};this.setSelectedVaultedPaymentMethod=t=>{this.updateItemState({selectedVaultedPaymentMethod:t,formIsDirty:!1}),this.host.primerEventsController.dispatchVaultSelectionChange(t?.id??null)};this.startVaultPaymentById=async(t,e)=>{if(!this._vaultManager)throw new Error("Vault manager not initialized");let r=this._coreState.vaultedPaymentMethods.find(i=>i.id===t);if(!r)throw new Error(`Payment method not found: ${t}`);this.setSelectedVaultedPaymentMethod(r),this.host.sdkContextController.setSdkState({isProcessing:!0,paymentFailure:null,primerJsError:null});try{await this._vaultManager.startPaymentFlow(t,e?.cvv?{cvv:e.cvv}:void 0)}catch(i){P.errorWithDatadog("VaultManagerController: Error starting vaulted payment flow",{error:i});let n=i instanceof Error?i:new Error("Failed to start vaulted payment flow");throw this.updateCoreState({isLoading:!1,isUpdating:!1}),this.host.sdkContextController.setSdkState({isProcessing:!1,primerJsError:n}),i}};this.host.addController(this),this._coreState={...this._coreState,deleteVaultedPaymentMethod:this.deleteVaultedPaymentMethod.bind(this),startVaultedPaymentFlow:this.startVaultedPaymentFlow.bind(this),createCvvInput:this.createCvvInput},this._itemState={...this._itemState,setCvvInput:this.setCvvInput.bind(this),setSelectedVaultedPaymentMethod:this.setSelectedVaultedPaymentMethod.bind(this)},new $(this.host,{task:async([e,r])=>{if(!e||!r?.vaultEnabled)return this.updateCoreState({...Ea,enabled:!1}),Y;this.updateCoreState({isLoading:!0});try{let i=e();this._vaultManager=i,this.updateCoreState({enabled:r.vaultEnabled,cvvRecapture:!!r.captureVaultedCardCvv,showEmptyState:r.showEmptyState??!1,headless:r.headless??!1,deleteVaultedPaymentMethod:this.deleteVaultedPaymentMethod.bind(this),startVaultedPaymentFlow:this.startVaultedPaymentFlow.bind(this),createCvvInput:this.createCvvInput}),this.host.sdkContextController.setVaultManagerCvv(this._itemState),await this.fetchVaultedPaymentMethods(!0),P.log("VaultManagerController: Vault initialized successfully",{coreState:this.vaultManagerState,cvvState:this.vaultItemState})}catch(i){P.errorWithDatadog("VaultManagerController: Failed to initialize vault",{error:i});let n=i instanceof Error?i:new Error("Unknown error");this.updateCoreState({isLoading:!1,isUpdating:!1}),this.host.sdkContextController.setSdkState({primerJsError:n})}return this._vaultManager},args:()=>[this.createVaultManagerFn,this.options]})}updateCoreState(t){let e={...this._coreState,...t};ft(this._coreState,e)?this._coreState=e:(this._coreState=e,this.host.sdkContextController.setVaultManager(e))}updateItemState(t){let e={...this._itemState,...t};ft(this._itemState,e)?this._itemState=e:(this._itemState=e,this.host.sdkContextController.setVaultManagerCvv(e))}initializeVaultManager(t,e){this.createVaultManagerFn=t,this.options=e??null}get vaultManager(){return this._vaultManager}set vaultManager(t){this._vaultManager=t,this.host.requestUpdate()}get options(){return this._options}set options(t){this._options=t,this.host.requestUpdate()}get vaultManagerState(){return Object.freeze({...this._coreState})}get vaultItemState(){return Object.freeze({...this._itemState})}hostConnected(){}hostDisconnected(){this.vaultManager=null,this.updateCoreState({...Ea})}createVaultedPaymentsArray(t){return t.map(e=>cs(e))}updatePaymentMethodsWithEvents(t){this.updateCoreState({vaultedPaymentMethods:t,isLoading:!1,isUpdating:!1});let e=this.createVaultedPaymentsArray(t);this.host.primerEventsController.dispatchVaultMethodsUpdate(e,this.vaultManagerState.cvvRecapture),this.host.primerJS?.handleVaultedMethodsUpdate(e,this.vaultManagerState.cvvRecapture),P.log("VaultManagerController: Dispatched vault methods update",{methodCount:t.length,filteredMethodCount:e.length})}async fetchVaultedPaymentMethods(t){if(!this._vaultManager)throw new Error("Vault manager not initialized");try{t||this.updateCoreState({isUpdating:!0});let e=await this._vaultManager.fetchVaultedPaymentMethods();return P.log("VaultManagerController: Fetched payment methods",e),this.updatePaymentMethodsWithEvents(e),e}catch(e){let r=e instanceof Error?e:new Error("Failed to fetch payment methods");throw this.updateCoreState({isLoading:!1,isUpdating:!1}),this.host.sdkContextController.setSdkState({primerJsError:r}),e}}};var Cs=()=>Ss.randomUUID?.()||Em(),Em=()=>("10000000-1000-4000-8000"+-1e11).replace(/[018]/g,a=>(a^Mm()>>a/4).toString(16)),Mm=()=>(Ss.getRandomValues?.(new Uint8Array(1))[0]??Math.random()*16)&15,Ss=typeof crypto<"u"?crypto:{};var Pm={LOCAL:"https://analytics.sandbox.data.primer.io/v1/sdk-analytic-events",DEV:"https://analytics.dev.data.primer.io/v1/sdk-analytic-events",STAGING:"https://analytics.staging.data.primer.io/v1/sdk-analytic-events",SANDBOX:"https://analytics.sandbox.data.primer.io/v1/sdk-analytic-events",PRODUCTION:"https://analytics.production.data.primer.io/v1/sdk-analytic-events"},ln=class{sendEvent(t){let e=De.getContext();if(!e)return;let r={...t,id:Cs(),timestamp:Math.floor(Date.now()/1e3),sdkType:"WEB",eventName:t.eventName,checkoutSessionId:e.checkoutSessionId,clientSessionId:e.clientSessionId,primerAccountId:e.primerAccountId,sdkVersion:e.sdkVersion,userAgent:e.userAgent,eventType:t.eventType,userLocale:t.userLocale,paymentMethod:t.paymentMethod,paymentId:t.paymentId,redirectDestinationUrl:t.redirectDestinationUrl,threedsProvider:t.threedsProvider,threedsResponse:t.threedsResponse};Nm(r,e)}},Tm=new ln;function As(a){let t={...a,userAgent:a.userAgent||(typeof navigator<"u"?navigator.userAgent:"")};De.initialize(t)}function Q(a){Tm.sendEvent(a)}function Es(){De.clear()}async function Nm(a,{environment:t,clientSessionToken:e}){if(t==="LOCAL"){P.debug(`Analytics event ${a.eventName}:`,a);return}let r=Pm[t];return fetch(r,{method:"POST",headers:{"Content-Type":"application/json",...e&&{Authorization:`Bearer ${e}`}},body:JSON.stringify(a),keepalive:!0,priority:"low"}).catch(i=>{P.error("Failed to send analytics event:",i)})}var Pr="lit-localize-status";var Ms=a=>typeof a!="string"&&"strTag"in a,Ma=(a,t,e)=>{let r=a[0];for(let i=1;i<a.length;i++)r+=t[e?e[i-1]:i-1],r+=a[i];return r};var Tr=(a=>Ms(a)?Ma(a.strings,a.values):a);var E=Tr,Ps=!1;function dn(a){if(Ps)throw new Error("lit-localize can only be configured once");E=a,Ps=!0}var cn=class{constructor(t){this.__litLocalizeEventHandler=e=>{e.detail.status==="ready"&&this.host.requestUpdate()},this.host=t}hostConnected(){window.addEventListener(Pr,this.__litLocalizeEventHandler)}hostDisconnected(){window.removeEventListener(Pr,this.__litLocalizeEventHandler)}},Im=a=>a.addController(new cn(a)),Ts=Im;var D=()=>(a,t)=>(a.addInitializer(Ts),a);var Nr=class{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._resolve=t,this._reject=e})}resolve(t){this.settled=!0,this._resolve(t)}reject(t){this.settled=!0,this._reject(t)}};var Ze=[];for(let a=0;a<256;a++)Ze[a]=(a>>4&15).toString(16)+(a&15).toString(16);function Ns(a){let t=0,e=8997,r=0,i=33826,n=0,o=40164,s=0,l=52210;for(let c=0;c<a.length;c++)e^=a.charCodeAt(c),t=e*435,r=i*435,n=o*435,s=l*435,n+=e<<8,s+=i<<8,r+=t>>>16,e=t&65535,n+=r>>>16,i=r&65535,l=s+(n>>>16)&65535,o=n&65535;return Ze[l>>8]+Ze[l&255]+Ze[o>>8]+Ze[o&255]+Ze[i>>8]+Ze[i&255]+Ze[e>>8]+Ze[e&255]}var km="",Lm="h",Rm="s";function Is(a,t){return(t?Lm:Rm)+Ns(typeof a=="string"?a:a.join(km))}var ks=new WeakMap,Ls=new Map;function Rs(a,t,e){if(a){let r=e?.id??wm(t),i=a[r];if(i){if(typeof i=="string")return i;if("strTag"in i)return Ma(i.strings,t.values,i.values);{let n=ks.get(i);return n===void 0&&(n=i.values,ks.set(i,n)),{...i,values:n.map(o=>t.values[o])}}}}return Tr(t)}function wm(a){let t=typeof a=="string"?a:a.strings,e=Ls.get(t);return e===void 0&&(e=Is(t,typeof a!="string"&&!("strTag"in a)),Ls.set(t,e)),e}function un(a){window.dispatchEvent(new CustomEvent(Pr,{detail:a}))}var Ta="",pn,ws,Na,mn,xs,Dt=new Nr;Dt.resolve();var Pa=0,_s=a=>(dn(((t,e)=>Rs(xs,t,e))),Ta=ws=a.sourceLocale,Na=new Set(a.targetLocales),Na.add(a.sourceLocale),mn=a.loadLocale,{getLocale:xm,setLocale:_m}),xm=()=>Ta,_m=a=>{if(a===(pn??Ta))return Dt.promise;if(!Na||!mn)throw new Error("Internal error");if(!Na.has(a))throw new Error("Invalid locale code");Pa++;let t=Pa;return pn=a,Dt.settled&&(Dt=new Nr),un({status:"loading",loadingLocale:a}),(a===ws?Promise.resolve({templates:void 0}):mn(a)).then(r=>{Pa===t&&(Ta=a,pn=void 0,xs=r.templates,un({status:"ready",readyLocale:a}),Dt.resolve())},r=>{Pa===t&&(un({status:"error",errorLocale:a,errorMessage:r.toString()}),Dt.reject(r))}),Dt.promise};var hn="en",gn=["ar","bg","ca","cs","da","de","el","en-GB","es","es-AR","es-MX","et-EE","fi-FI","fr","he","hr","hu","id","it","ja","ko","lt","lt-LT","lv","lv-LV","ms","nb","nl","nl_NL","pl","pt","pt-BR","ro","ru","sk","sl","sr-RS","sv","th","tr","uk-UA","vi","zf","zh-CN","zh-HK","zh-TW"],yn="You must call `loadLocale` first to set up the localized template.",Ia,ka,Os=a=>{let t=_s({sourceLocale:hn,targetLocales:gn,loadLocale:a});Ia=t.getLocale,ka=t.setLocale};var fn=a=>{Os(a)},vn=a=>{if(!ka)throw new Error(yn);return ka(a)},bn=()=>{if(!Ia)throw new Error(yn);return Ia()};var Ir=new Set(gn);Ir.add(hn);var Cn=a=>{if(typeof a!="string")return!1;if(a==="en")return!0;let t=a.replace("_","-");if(Ir.has(t))return!0;let e=t.split("-")[0];return!!Ir.has(e)},La=()=>navigator.language||navigator.languages[0]||"en",rr=a=>{let t=a.replace("_","-"),e=t.split("-")[0];return e==="en"?"en-GB":Ir.has(t)?t:Ir.has(e)?e:"en-GB"};var Ra=globalThis,wa=Ra.ShadowRoot&&(Ra.ShadyCSS===void 0||Ra.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Sn=Symbol(),Ds=new WeakMap,kr=class{constructor(t,e,r){if(this._$cssResult$=!0,r!==Sn)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=e}get styleSheet(){let t=this.o,e=this.t;if(wa&&t===void 0){let r=e!==void 0&&e.length===1;r&&(t=Ds.get(e)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),r&&Ds.set(e,t))}return t}toString(){return this.cssText}},Je=a=>new kr(typeof a=="string"?a:a+"",void 0,Sn),f=(a,...t)=>{let e=a.length===1?a[0]:t.reduce(((r,i,n)=>r+(o=>{if(o._$cssResult$===!0)return o.cssText;if(typeof o=="number")return o;throw Error("Value passed to 'css' function must be a 'css' function result: "+o+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(i)+a[n+1]),a[0]);return new kr(e,a,Sn)},Bs=(a,t)=>{if(wa)a.adoptedStyleSheets=t.map((e=>e instanceof CSSStyleSheet?e:e.styleSheet));else for(let e of t){let r=document.createElement("style"),i=Ra.litNonce;i!==void 0&&r.setAttribute("nonce",i),r.textContent=e.cssText,a.appendChild(r)}},An=wa?a=>a:a=>a instanceof CSSStyleSheet?(t=>{let e="";for(let r of t.cssRules)e+=r.cssText;return Je(e)})(a):a;var{is:Om,defineProperty:Dm,getOwnPropertyDescriptor:Bm,getOwnPropertyNames:Gm,getOwnPropertySymbols:Km,getPrototypeOf:Fm}=Object,Ct=globalThis,Gs=Ct.trustedTypes,Um=Gs?Gs.emptyScript:"",Vm=Ct.reactiveElementPolyfillSupport,Lr=(a,t)=>a,Rr={toAttribute(a,t){switch(t){case Boolean:a=a?Um:null;break;case Object:case Array:a=a==null?a:JSON.stringify(a)}return a},fromAttribute(a,t){let e=a;switch(t){case Boolean:e=a!==null;break;case Number:e=a===null?null:Number(a);break;case Object:case Array:try{e=JSON.parse(a)}catch{e=null}}return e}},xa=(a,t)=>!Om(a,t),Ks={attribute:!0,type:String,converter:Rr,reflect:!1,useDefault:!1,hasChanged:xa};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),Ct.litPropertyMetadata??(Ct.litPropertyMetadata=new WeakMap);var qe=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??(this.l=[])).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,e=Ks){if(e.state&&(e.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((e=Object.create(e)).wrapped=!0),this.elementProperties.set(t,e),!e.noAccessor){let r=Symbol(),i=this.getPropertyDescriptor(t,r,e);i!==void 0&&Dm(this.prototype,t,i)}}static getPropertyDescriptor(t,e,r){let{get:i,set:n}=Bm(this.prototype,t)??{get(){return this[e]},set(o){this[e]=o}};return{get:i,set(o){let s=i?.call(this);n?.call(this,o),this.requestUpdate(t,s,r)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??Ks}static _$Ei(){if(this.hasOwnProperty(Lr("elementProperties")))return;let t=Fm(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(Lr("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Lr("properties"))){let e=this.properties,r=[...Gm(e),...Km(e)];for(let i of r)this.createProperty(i,e[i])}let t=this[Symbol.metadata];if(t!==null){let e=litPropertyMetadata.get(t);if(e!==void 0)for(let[r,i]of e)this.elementProperties.set(r,i)}this._$Eh=new Map;for(let[e,r]of this.elementProperties){let i=this._$Eu(e,r);i!==void 0&&this._$Eh.set(i,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){let e=[];if(Array.isArray(t)){let r=new Set(t.flat(1/0).reverse());for(let i of r)e.unshift(An(i))}else t!==void 0&&e.push(An(t));return e}static _$Eu(t,e){let r=e.attribute;return r===!1?void 0:typeof r=="string"?r:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise((t=>this.enableUpdating=t)),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach((t=>t(this)))}addController(t){(this._$EO??(this._$EO=new Set)).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){let t=new Map,e=this.constructor.elementProperties;for(let r of e.keys())this.hasOwnProperty(r)&&(t.set(r,this[r]),delete this[r]);t.size>0&&(this._$Ep=t)}createRenderRoot(){let t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return Bs(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),this._$EO?.forEach((t=>t.hostConnected?.()))}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach((t=>t.hostDisconnected?.()))}attributeChangedCallback(t,e,r){this._$AK(t,r)}_$ET(t,e){let r=this.constructor.elementProperties.get(t),i=this.constructor._$Eu(t,r);if(i!==void 0&&r.reflect===!0){let n=(r.converter?.toAttribute!==void 0?r.converter:Rr).toAttribute(e,r.type);this._$Em=t,n==null?this.removeAttribute(i):this.setAttribute(i,n),this._$Em=null}}_$AK(t,e){let r=this.constructor,i=r._$Eh.get(t);if(i!==void 0&&this._$Em!==i){let n=r.getPropertyOptions(i),o=typeof n.converter=="function"?{fromAttribute:n.converter}:n.converter?.fromAttribute!==void 0?n.converter:Rr;this._$Em=i,this[i]=o.fromAttribute(e,n.type)??this._$Ej?.get(i)??null,this._$Em=null}}requestUpdate(t,e,r){if(t!==void 0){let i=this.constructor,n=this[t];if(r??(r=i.getPropertyOptions(t)),!((r.hasChanged??xa)(n,e)||r.useDefault&&r.reflect&&n===this._$Ej?.get(t)&&!this.hasAttribute(i._$Eu(t,r))))return;this.C(t,e,r)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(t,e,{useDefault:r,reflect:i,wrapped:n},o){r&&!(this._$Ej??(this._$Ej=new Map)).has(t)&&(this._$Ej.set(t,o??e??this[t]),n!==!0||o!==void 0)||(this._$AL.has(t)||(this.hasUpdated||r||(e=void 0),this._$AL.set(t,e)),i===!0&&this._$Em!==t&&(this._$Eq??(this._$Eq=new Set)).add(t))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(e){Promise.reject(e)}let t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(let[i,n]of this._$Ep)this[i]=n;this._$Ep=void 0}let r=this.constructor.elementProperties;if(r.size>0)for(let[i,n]of r){let{wrapped:o}=n,s=this[i];o!==!0||this._$AL.has(i)||s===void 0||this.C(i,void 0,n,s)}}let t=!1,e=this._$AL;try{t=this.shouldUpdate(e),t?(this.willUpdate(e),this._$EO?.forEach((r=>r.hostUpdate?.())),this.update(e)):this._$EM()}catch(r){throw t=!1,this._$EM(),r}t&&this._$AE(e)}willUpdate(t){}_$AE(t){this._$EO?.forEach((e=>e.hostUpdated?.())),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Eq&&(this._$Eq=this._$Eq.forEach((e=>this._$ET(e,this[e])))),this._$EM()}updated(t){}firstUpdated(t){}};qe.elementStyles=[],qe.shadowRootOptions={mode:"open"},qe[Lr("elementProperties")]=new Map,qe[Lr("finalized")]=new Map,Vm?.({ReactiveElement:qe}),(Ct.reactiveElementVersions??(Ct.reactiveElementVersions=[])).push("2.1.0");var xr=globalThis,_a=xr.trustedTypes,Fs=_a?_a.createPolicy("lit-html",{createHTML:a=>a}):void 0,Mn="$lit$",Qe=`lit$${Math.random().toFixed(9).slice(2)}$`,Pn="?"+Qe,Hm=`<${Pn}>`,Kt=document,_r=()=>Kt.createComment(""),Or=a=>a===null||typeof a!="object"&&typeof a!="function",Tn=Array.isArray,zs=a=>Tn(a)||typeof a?.[Symbol.iterator]=="function",En=`[
|
|
178
|
+
`,Vi=class extends Ee{constructor(){super(...arguments);S(this,"popup");S(this,"shouldRedirect",!1);S(this,"redirectReason","force_redirect");S(this,"dialogPromise")}async setup(){return tn(this.context.clientOptions,this.config.type)}async start(){try{let e=this.callbacks.onStart(),r=this.config.forceRedirect||!!this.context.clientOptions.redirect?.forceRedirect;(r||Qi())&&(this.shouldRedirect=!0,this.redirectReason=r?"force_redirect":"in_app_browser");let i=document.createElement("div");i.setAttribute("style","display: flex; flex-direction: column; gap: var(--primer-size-xlarge);");let n=document.createElement("div");n.setAttribute("style",`display: flex;margin:auto;padding:calc(var(--primer-size-small)*0.5);height: var(--primer-size-xlarge);background-color: ${this.backgroundColor};border-radius:var(--primer-radius-small);`);let o=document.createElement("img");o.src=this.logoSrc,n.appendChild(o),o.setAttribute("style","height:100%;"),i.appendChild(n);let s=document.createElement("p");s.setAttribute("style","max-width: 300px;text-align: center;"),s.innerText=this.context.translate("paymentMethodPopupOverlayDescription","Having trouble viewing the {paymentMethodName} payment page? We'll help you find it!").replace("{paymentMethodName}",this.config.name),i.appendChild(s),this.dialogPromise=this.context.dialogProvider.show({htmlContent:i,showCloseButton:!0,size:"flex",cta:{label:this.context.translate("paymentMethodPopupOverlayBringBackThePaymentPage","Bring back the payment page"),icon:"chevron-left",onClick:()=>{this.popup?.focus()}}}),this.shouldRedirect||(this.openPopup(),this.popup&&await xt(300),this.popup?.isOpen||(this.shouldRedirect=!0,this.redirectReason="popup_blocked"));let{action:l}=await e;if(l==="abort")throw new R({message:"Payment creation aborted",code:x.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type});let c=await this.tokenize();this.callbacks.onFinish(c)}catch(e){this.context.dialogProvider.close(),this.popup?.close(),this.callbacks.onFinish(void 0,e)}}async tokenize(){let{error:e,data:r}=await this.context.pciApi.postRedirectPaymentInstruments({type:"OFF_SESSION_PAYMENT",paymentMethodType:this.config.type,paymentMethodConfigId:this.config.id,sessionInfo:{locale:this.context.locale,platform:Ar()?"MOBILE_WEB":"WEB",browserInfo:Rt(),merchantRedirectUrl:this.context.clientOptions.redirect?.returnUrl}});if(e||!r)throw e??new F({message:"Unable to tokenize payment method",code:x.TOKENIZATION_ERROR});return r}async createPayment(e){try{let r=await super.createPayment(e),i=r.requiredAction?.clientToken;if(!i)throw new F({message:"No client token provided"});let n=ht(i);if(!jo(n,this.config.type))throw new F({message:"Invalid client token"});if(this.shouldRedirect&&(rn(n.redirectUrl,this.config.type,this.redirectReason),window.location.assign(n.redirectUrl),await new Promise(()=>{})),!this.popup?.isOpen)return this.unselect(r),this.context.dialogProvider.close(),{...r,cancelled:!0};this.popup?.setUrl(n.redirectUrl);let o=(this.dialogPromise??Promise.resolve()).then(()=>({id:"",popupClosed:!0})),s=new Promise(g=>{this.popup?.onClose(()=>{C.debug("Popup closed"),g({id:"",popupClosed:!0})})}),l=new AbortController,c=this.context.pciApi.pollResumeStatus(n.statusUrl,{signal:l.signal,isComplete:g=>!!g.error||g.data?.status==="COMPLETE"}),p=await Promise.race([o,s,c.then(g=>g.error?{error:g.error,id:"",popupClosed:!1}:{id:g.data?.id??"",popupClosed:!1})]);if(l.abort(),this.popup?.close(),this.context.dialogProvider.close(),"error"in p)throw p.error;if("popupClosed"in p&&p.popupClosed&&!this.context.clientOptions.redirect?.resumePaymentOnPopupClosure)return this.unselect(r),{...r,cancelled:!0};let m=p.id;if(!m){let g=await this.context.pciApi.getResumeStatus(n.statusUrl);if(g.error||!g.data?.id)throw g.error??new Error("Unable to get resume token");m=g.data.id}return await this.resumePayment(r.id,m)}catch(r){throw this.context.dialogProvider.close(),this.popup?.close(),r}}unselect(e){this.context.clientSessionApi.unselectPaymentMethod(e)}openPopup(){let{name:e,displayMetadata:{popup:r}}=this.config;this.popup=en({name:e,height:r?.height??500,width:r?.width??1e3}),this.popup?.setContent(ss({name:e,background:this.backgroundColor,logoSrc:this.logoSrc,logoAlt:e,message:`Loading ${e}...`}))}get backgroundColor(){let{displayMetadata:{button:e,overlay:r}}=this.config;return r?.backgroundColor.colored||e?.backgroundColor.colored||r?.backgroundColor.light||e?.backgroundColor.light||r?.backgroundColor.dark||e?.backgroundColor.dark||"#FFFFFF"}get logoSrc(){let{displayMetadata:{button:e,overlay:r}}=this.config;return r?.logo.colored||e?.iconUrl.colored||r?.logo.light||e?.iconUrl.light||r?.logo.dark||e?.iconUrl.dark}},Hi=class{constructor(t,e){S(this,"currentState");S(this,"stateProcessor");S(this,"handlerRegistry");this.stateProcessor=t,this.handlerRegistry=e}async run(t){let e=await this.stateProcessor.initialize(t??{});return this.handle(e)}async resume(t){let e=await this.stateProcessor.resume(t);return this.handle(e)}async handleEvent(t){if(!this.currentState)throw new Error("handleEvent() called before run()");C.debug("Orchestrator handling event",t);let e=await this.stateProcessor.applyEvent(this.currentState,t);return this.handle(e)}async handle(t){if(this.currentState=t.newState,t.error)throw new Error(t.error.message);if(t.terminal)return C.debug("Orchestrator reached terminal",t.terminal),t.terminal;if(!t.action)return C.debug("Orchestrator waiting for external event"),null;let e=t.action;C.debug(`Executing ${e.type}`,e.params);let r,i;try{let o=await this.handlerRegistry.execute(e.type,e);r=o.outcome,i=o.data??{}}catch(o){C.warn(`Handler failed for ${e.type}`,o),r="error",i={error:o instanceof Error?o.message:"Unknown error"}}let n=await this.stateProcessor.applyResult(this.currentState,e.id,r,i);return this.handle(n)}},Yi=class{constructor(){S(this,"handlers",new Map)}register(t,e){this.handlers.set(t,e)}get(t){return this.handlers.get(t)}async execute(t,e){let r=this.handlers.get(t);return r?r.execute(e):{outcome:"unsupported"}}finishAll(){this.handlers.forEach(t=>t.onFinish?.())}},Zp=["https://sdk.primer.io/web/","https://sdk.dev.primer.io/web/","https://sdk.sandbox.primer.io/web/","https://sdk.production.primer.io/web/","https://sdk.primer.io/state-processor/","https://sdk.dev.primer.io/state-processor/","https://sdk.primer.io/cel-wrapper/","https://sdk.dev.primer.io/cel-wrapper/","https://assets.primer.io/","https://x.klarnacdn.net/kp/lib/v","https://www.paypal.com/sdk/js","https://www.paypalobjects.com/","https://js.stripe.com/","https://pay.google.com/gp/p/js/"];function Jp(a){return Zp.some(t=>a.startsWith(t))}async function Io(a,t){if(!Jp(a))throw new Error(`Script source not authorized per PCI DSS 6.4.3: ${a}`);await new Promise((e,r)=>{let i=document.createElement("script");i.src=a,i.integrity=`sha256-${t}`,i.crossOrigin="anonymous",i.onload=()=>{i.remove(),e()},i.onerror=()=>{i.remove(),r(new Error(`SRI check or load failed for script: ${a}`))},document.head.appendChild(i)})}async function qp(a,t){let e=await fetch(a).then(n=>n.arrayBuffer()),r=await crypto.subtle.digest("SHA-256",e);if(btoa(String.fromCharCode(...new Uint8Array(r)))!==t)throw new Error(`Integrity check failed for ${a}`);return e}var ls=["MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEUM5exrePPsIdkWFL6IjKdYmEDoEHBZkoBvrApQpmDEhQ7IisLTCiP0byqN+5B5V60QjAj4I/Bw292h8gPGZyOg==","MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAERA0j68aAYtwMDagEx2FY+CBbm2+MAYviARSMxWHt1Qt8wGyVvLJ2FqIvg4m2pKfb7GqUwzuJRD/gaOrO2ZJulQ==","MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEp7v1KpNTWcI9yJSoZYGvRxsPtciT99P2YDpISVLyD6BDD8xqJ11A8v2/elOEPaSxx5hConszht1cOlPp9YdTsA=="];function Qp(a){let t=2;a[1]===129&&(t=3),t++;let e=a[t++],r=a.slice(t,t+e);t+=e,t++;let i=a[t++],n=a.slice(t,t+i),o=new Uint8Array(new ArrayBuffer(64));return o.set(r.slice(-32),32-Math.min(r.length,32)),o.set(n.slice(-32),64-Math.min(n.length,32)),o}async function Xp(a){let t=Uint8Array.from(atob(a),e=>e.charCodeAt(0));return crypto.subtle.importKey("spki",t,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"])}async function em(a,t){let e=Qp(Uint8Array.from(atob(t),i=>i.charCodeAt(0))),r=new TextEncoder().encode(a);for(let i of ls)try{let n=await Xp(i);if(await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},n,e,r))return!0}catch{}return!1}async function tm(a){let e;for(let r=0;r<3;r++){r>0&&await xt(300*r);try{let i=await fetch(a.manifestUrl);if(!i.ok)throw new Error(`Failed to fetch state processor manifest: ${i.status}`);let n=await i.json(),{signature:o,manifest:s}=n;if(typeof o!="string"||typeof s!="string")throw new Error("Invalid manifest response format");let l=Cr.decode(s);if(!await em(l,o))throw new Error("Manifest signature verification failed");return JSON.parse(l)}catch(i){e=i}}throw e}async function rm(){return Promise.all(ls.map(async a=>{let t=Uint8Array.from(atob(a),r=>r.charCodeAt(0)),e=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(e)).map(r=>r.toString(16).padStart(2,"0")).join("")}))}async function am(a,t,e){let r=await tm(a),i=r.cel.noModules,n=await qp(i.wasm.br,i.wasm.sha256);typeof window.primer_wasm_bindgen!="function"&&await Io(i.js.url,i.js.sha256);let o=window.primer_wasm_bindgen;if(typeof o!="function")throw new Error("Invalid CEL wrapper: window.primer_wasm_bindgen not set after script load");await o(n),window.StateProcessor?.createStateProcessor||await Io(r.stateProcessor.umd.url,r.stateProcessor.umd.sha256);let s=window.StateProcessor;if(!s?.createStateProcessor)throw new Error("createStateProcessor not found after loading state processor module");return s.createStateProcessor(t,e)}function im(a,t){return new Promise((e,r)=>{if(t.aborted)return void r(new DOMException("Aborted","AbortError"));let i=setTimeout(e,a);t.addEventListener("abort",()=>{clearTimeout(i),r(new DOMException("Aborted","AbortError"))},{once:!0})})}var $i=class{constructor(t,e,r){S(this,"popup");S(this,"shouldRedirect",!1);S(this,"resolveOutcome");S(this,"context");S(this,"config");S(this,"onBeforeRedirect");this.context=t,this.config=e,this.onBeforeRedirect=r}async execute(t){let{url:e}=t.params,r=!!this.config.forceRedirect||!!this.context.clientOptions.redirect?.forceRedirect,i=null;return r?(this.shouldRedirect=!0,i="force_redirect"):Qi()&&(this.shouldRedirect=!0,i="in_app_browser"),this.showDialogOverlay(),this.shouldRedirect||(this.openPopup(),this.popup&&await xt(300),this.popup?.isOpen||(this.shouldRedirect=!0,i="popup_blocked")),this.shouldRedirect&&i?(rn(e,this.config.type,i),this.onBeforeRedirect(),window.location.assign(e),new Promise(()=>{})):(this.popup?.setUrl(e),new Promise(n=>{this.resolveOutcome=n,this.popup?.onClose(()=>{this.context.dialogProvider.close(),n({outcome:"cancelled"})})}))}onFinish(){this.resolveOutcome?.({outcome:"success"}),this.context.dialogProvider.close(),this.popup?.close()}get isOpen(){return this.popup?.isOpen??!1}focus(){this.popup?.focus()}openPopup(){let{popup:t}=this.config.displayMetadata;this.popup=en({name:this.config.name,height:t.height,width:t.width}),this.popup?.setContent(ss({name:this.config.name,background:this.backgroundColor,logoSrc:this.logoSrc,logoAlt:this.config.name,message:`Loading ${this.config.name}...`}))}showDialogOverlay(){let t=document.createElement("div");t.setAttribute("style","display: flex; flex-direction: column; gap: var(--primer-size-xlarge);");let e=document.createElement("div");e.setAttribute("style",`display: flex;margin:auto;padding:calc(var(--primer-size-small)*0.5);height: var(--primer-size-xlarge);background-color: ${this.backgroundColor};border-radius:var(--primer-radius-small);`);let r=document.createElement("img");r.src=this.logoSrc,e.appendChild(r),t.appendChild(e);let i=document.createElement("p");i.setAttribute("style","max-width: 300px;text-align: center;"),i.innerText=this.context.translate("paymentMethodPopupOverlayDescription","Having trouble viewing the {paymentMethodName} payment page? We'll help you find it!").replace("{paymentMethodName}",this.config.name),t.appendChild(i),this.context.dialogProvider.show({htmlContent:t,showCloseButton:!0,size:"flex",cta:{label:this.context.translate("paymentMethodPopupOverlayBringBackThePaymentPage","Bring back the payment page"),icon:"chevron-left",onClick:()=>{this.popup?.focus()}}}).then(()=>{this.popup?.isOpen&&this.popup.close()})}get backgroundColor(){let{displayMetadata:{button:t,overlay:e}}=this.config;return e?.backgroundColor.colored||t?.backgroundColor.colored||e?.backgroundColor.light||t?.backgroundColor.light||e?.backgroundColor.dark||t?.backgroundColor.dark||"#FFFFFF"}get logoSrc(){let{displayMetadata:{button:t,overlay:e}}=this.config;return e?.logo.colored||t?.iconUrl.colored||e?.logo.light||t?.iconUrl.light||e?.logo.dark||t?.iconUrl.dark||""}},zi=class{async execute(t){let{message:e,severity:r,context:i}=t.params.properties;return Ro(e,{status:r,metadata:i}),{outcome:"success"}}},ji=class{async execute(t){return Le({...t.params,eventName:t.params.eventName}),{outcome:"success"}}},Sr=class extends Ee{constructor(e,r){super(e,r);S(this,"onFinishCallback");S(this,"stepHandlerRegistry");S(this,"abortController");S(this,"stateProcessorConfig");this.stepHandlerRegistry=new Yi;let i=r.decodedClientToken.env,n=null;i!=="PRODUCTION"&&(n=new URLSearchParams(window.location.search).get("manifestUrl")),this.stateProcessorConfig={manifestUrl:n??`https://sdk.primer.io/state-processor/v0/manifests/${i.toLowerCase()}.json`},r.subscribeToTeardown(()=>{this.abortController?.abort(),this.stepHandlerRegistry?.finishAll()})}async setup(){return tn(this.context.clientOptions,this.config.type)?super.setup():!1}setOnFinishCallback(e){this.onFinishCallback=e}async tokenize(){throw new R({message:"Tokenize is not supported for backend-driven payment methods"})}async start(){let{action:e}=await this.callbacks.onStart();if(e==="abort")return this.callbacks.onFinish(void 0,new R({message:"Payment creation aborted",code:x.PAYMENT_CREATION_ABORTED,paymentMethod:this.config.type}));this.abortController=new AbortController;let r=this.abortController.signal;try{let i=this.context.configuration.clientSession.clientSessionId,n=await this.initiatePayment(i),o=await this.runInstructionLoop(n,i,r);if(r.aborted)return this.finishCancel();if(o.type!=="END")throw new R({message:"Unexpected final instruction type"});this.handleEndInstruction(o)}catch(i){if(r.aborted)return this.finishCancel();this.stepHandlerRegistry?.finishAll(),this.onFinishCallback?.({result:"complete",error:this.normalizeError(i)})}}async resume(e){this.abortController=new AbortController;let r=this.abortController.signal;try{let i=await this.fetchNextInstruction(e),n=await this.runInstructionLoop(i,e,r);if(r.aborted)return this.finishCancel();if(n.type!=="END")throw new R({message:"Unexpected final instruction type"});this.handleEndInstruction(n)}catch(i){if(r.aborted)return this.finishCancel();this.stepHandlerRegistry?.finishAll(),this.onFinishCallback?.({result:"complete",error:this.normalizeError(i)})}}async runInstructionLoop(e,r,i){let n=e,o=null;for(;!i.aborted&&n.type!=="END";){n.type==="EXECUTE"&&!o&&(o=this.processExecute(n)),await im(n.pollDelayMilliseconds,i);let s=this.fetchNextInstruction(r);if(o){let l=await Promise.race([s.then(c=>({kind:"poll",value:c})),o.then(c=>({kind:"orch",value:c}))]);if(l.kind==="orch"){if(l.value?.outcome==="cancelled"){this.abortController?.abort();break}if(l.value?.outcome==="error")throw s.catch(()=>{}),new Error("Step handler failed");n=await s,o=null;continue}n=l.value;continue}n=await s}return n}async initiatePayment(e){Yu(this.context.clientOptions,this.config.type);let{data:r,error:i}=await this.context.pciApi.postClientSessionPay(e,{paymentMethodConfigId:this.config.id,processorMerchantAccountId:this.config.options?.merchantAccountId??null,paymentMethodType:this.config.type,clientInfo:{locale:this.context.locale,platform:Ar()?"MOBILE_WEB":"WEB",browserInfo:Rt(),returnUri:this.context.clientOptions.redirect?.returnUrl}});if(i||!r)throw i??new R({message:"Failed to initiate backend-driven payment"});return r.clientInstruction}async fetchNextInstruction(e){let{data:r,error:i}=await this.context.pciApi.getClientSessionInstruction(e);if(i||!r)throw i??new R({message:"Failed to fetch payment instruction"});return r.clientInstruction}async processExecute(e){let{schema:r,parameters:i}=e.payload;rm().then(s=>{Le({eventName:"BDC_FLOW_START",trustedKeyFingerprints:s})}).catch(()=>{});let n=await am(this.stateProcessorConfig,JSON.stringify(r),this.buildSdkContext()),o=new Hi(n,this.stepHandlerRegistry);return this.stepHandlerRegistry.register("url.open",new $i(this.context,this.config,()=>this.abortController?.abort())),this.stepHandlerRegistry.register("platform.log",new zi),this.stepHandlerRegistry.register("analytics.event",new ji),o.run(i)}buildSdkContext(){let e=Rt();return{sdk:{type:"WEB",version:ma.getContext()?.sdkVersion??"",integrationType:this.context.integrationType},device:{locale:e.language,userAgent:e.userAgent},session:{checkoutSessionId:this.context.checkoutSessionId,clientSessionId:this.context.configuration.clientSession.clientSessionId,customerId:this.context.configuration.clientSession.customer?.customerId},merchant:{primerAccountId:this.context.configuration.primerAccountId},payment:{paymentMethodType:this.config.type}}}handleEndInstruction(e){this.stepHandlerRegistry?.finishAll();let{checkoutOutcome:r,payment:i}=e.payload;if(i){let{paymentInstrumentToken:n,...o}=i;this.onFinishCallback?.({result:"complete",payment:{...o,checkoutOutcome:r},token:n})}else this.onFinishCallback?.({result:"complete"})}finishCancel(){this.stepHandlerRegistry?.finishAll(),this.onFinishCallback?.({result:"cancel"})}normalizeError(e){return e instanceof R?e:e instanceof Error?new R({message:e.message}):new R({message:String(e)})}},nm=[B.ADYEN_AFFIRM,B.ADYEN_BANCONTACT_CARD,B.ADYEN_BANCONTACT_PAYCONIQ,B.ADYEN_EPS,B.ADYEN_MULTIBANCO,B.GO_CARDLESS,B.OMISE_PROMPTPAY,B.RAPYD_FAST,B.RAPYD_PROMPTPAY,B.STRIPE_ACH,B.XFERS_PAYNOW,B.NETS];async function om(a,t){let r=a.configuration.paymentMethods.filter(({type:n})=>!t||t.includes(n)).map(n=>{if(nm.includes(n.type))return C.warn(`Payment method ${n.type} is not supported in sdk core.`),null;if(C.debug("Initializing payment method:",n.type),n.implementationType==="BACKEND_DRIVEN"||n.implementationType==="WEB_REDIRECT"&&n.capabilities?.includes("BACKEND_DRIVEN"))return new Sr(n,a);if(n.implementationType==="WEB_REDIRECT")return new Vi(n,a);if(n.type===B.PAYMENT_CARD)return new oa(n,a);if(n.type===B.PAYPAL)return new pa(n,a);if(n.type===B.APPLE_PAY)return new ia(n,a);if(n.type===B.GOOGLE_PAY)return new sa(n,a);if(n.type===B.ADYEN_BLIK)return new na(n,a);if(n.type===B.KLARNA)return new da(n,a);if(n.type===B.ADYEN_KLARNA)return new ca(n,a);if(n.type===B.ADYEN_MBWAY)return new ua(n,a)}).map(async n=>{if(!n)return null;try{return await n.setup()?n:null}catch(o){return C.warn(`Failed to initialize payment method ${n.config.type}:`,o),null}});return(await Promise.all(r)).filter(n=>!!n)}function sm(a,t,e){if(!t.configuration.clientSession.customer?.customerId)throw new R({message:"You must provide a `customerId` in the client session to use the Vault Manager."});let r=[];return{async fetchVaultedPaymentMethods(){let{data:i,error:n}=await t.pciApi.getPaymentInstruments();if(n)throw n;if(!i)throw new R({code:Zr.VAULT_ERROR,message:"Missing vaulted payment methods data"});return r=lm(i.data,t.configuration?.clientSession?.paymentMethod?.orderedAllowedCardNetworks),r},async deleteVaultedPaymentMethod(i){if(!r.find(s=>s.id===i))throw new R({code:Zr.VAULT_ERROR,message:"deleteVaultedPaymentMethod: the id provided doesn't match any vaulted payment method"});let{error:o}=await t.pciApi.deletePaymentInstrument(i);if(o)throw o;r=r.filter(s=>s.id!==i)},async startPaymentFlow(i){let n=r.find(s=>s.id===i);if(!n)throw new R({code:Zr.VAULT_ERROR,message:"startPaymentFlow: the id provided doesn't match any vaulted payment method"});let o=e.find(s=>s.config.type===n.paymentMethodType);if(!o)throw new F({code:Zr.TOKENIZATION_ERROR,message:`Payment instrument type ${n.paymentInstrumentType} is not recognized or not supported.`});await We(a,o,n)},async createCvvInput(i){let n={blur:new Set,change:new Set,focus:new Set},o,s=yr(t.checkoutSessionId,po);await new Promise(g=>{s.onload=()=>{g()},(typeof i.container=="string"?document.querySelector(i.container):i.container)?.appendChild(s)}),Di(s,i.style),s.setAttribute("title",i.ariaLabel||"");let l=an({namespace:`${t.checkoutSessionId}-${po}`,onMessage:g=>{let A=M=>g(M.data);return window.addEventListener("message",A),()=>window.removeEventListener("message",A)},sendMessage:g=>{s.contentWindow?.postMessage(g,"*")}});function c(g,A){g!=="metadata"&&n[g].add(A)}l.setOnFocus(()=>{n.focus.forEach(g=>g())}),l.setOnBlur(()=>{n.blur.forEach(g=>g())}),l.setOnInput(g=>{o=g,n.change.forEach(A=>A())}),l.setCardNetwork(i.cardNetwork??""),l.setOptions({placeholder:i.placeholder??"123",ariaLabel:i.ariaLabel??"CVV",style:i.style});function p(){s.parentNode&&s.remove()}let m=t.subscribeToTeardown(p);return{frame:s,remove:()=>{m(),p()},get metadata(){return{error:o?.error??"cvvRequired",errorCode:o?.error??"cvvRequired",valid:o?.valid??!1,active:o?.focused??!1,dirty:o?.dirty??!1,touched:o?.touched??!1,submitted:!0}},addEventListener:c,addListener:c,removeListener(g,A){g!=="metadata"&&n[g].delete(A)},blur(){l.blur()},focus(){l.focus()},validate(){l.getFieldState().then(g=>{o=g,n.change.forEach(A=>A(o))})}}}}}function lm(a,t){if(!t||t.length===0)return a;let e=new Set(t.map(r=>Zt(r).backend));return a.filter(r=>{if(r.paymentInstrumentType!==Jc.CARD)return!0;let i=r.paymentInstrumentData?.network;return typeof i!="string"||!i?!0:e.has(Zt(i).backend)})}function dm(a,t,e){return e.setOnFinishCallback(r=>{r.result==="cancel"?t.clientSessionApi.unselectPaymentMethod():br(a,r.payment,r.error,r.token,e.config.type)}),{start:()=>We(a,e)}}async function ds(a,t){C.debug("createHeadless",t);let e=await Wp(a,{locale:t.locale,dialogProvider:t.dialogProvider,translate:t.translate,integrationType:t.integrationType,clientOptions:{paypal:t.paypal,applePay:t.applePay,googlePay:t.googlePay,klarna:t.klarna,merchantDomain:t.merchantDomain,redirect:t.redirect,card:t.card}}),r=await om(e,t.enabledPaymentMethods);t.onClientSessionUpdate?.(e.configuration.clientSession),e.onClientConfigurationUpdate(async n=>{t.onClientSessionUpdate?.(n.clientSession)}),t.onPaymentMethodAction&&e.clientSessionApi.setOnPaymentMethodAction((n,o)=>t.onPaymentMethodAction?.(n,{...o,payment:Oi(o.payment,o.token)??void 0}));let i={environment:_i?"LOCAL":e.decodedClientToken.env,primerAccountId:e.configuration.primerAccountId,checkoutSessionId:e.checkoutSessionId,clientSessionId:e.configuration.clientSession?.clientSessionId,clientSessionToken:a,sdkVersion:t.sdkVersion,configurationFetchStartTime:e.configurationFetchStartTime};return zc({environment:_i?"LOCAL":e.decodedClientToken.env,primerAccountId:i.primerAccountId||"",checkoutSessionId:i.checkoutSessionId,clientSessionId:i.clientSessionId||"",clientSessionToken:i.clientSessionToken,sdkVersion:i.sdkVersion||"",userAgent:typeof navigator<"u"?navigator.userAgent:"unknown"}),t.onAvailablePaymentMethodsLoad?.(r.map(n=>({type:n.config.type,managerType:cm(n)}))),{start:async()=>{if(e.decodedClientToken.intent==="REDIRECTION_END"){fo(e.decodedClientToken.intent,{paymentId:e.decodedClientToken.paymentId});let{data:n,error:o}=await e.pciApi.postResumePayment(e.decodedClientToken.paymentId,e.decodedClientToken.resumeToken);br(t,n,o);return}if(e.decodedClientToken.intent==="AWAIT_CLIENT_INSTRUCTION"){let{clientSessionId:n,paymentMethodType:o,intent:s}=e.decodedClientToken;fo(s,{paymentMethod:o});let l=r.find(c=>c instanceof Sr&&c.config.type===o);if(!l)return void br(t,void 0,new R({message:"No backend-driven payment method found for resume"}));l.setOnFinishCallback(({result:c,payment:p,error:m,token:g})=>{c!=="cancel"&&br(t,p,m,g,l.config.type)}),await l.resume(n);return}},createPaymentMethodManager:async(n,o)=>{let s=r.find(({config:l})=>l.type===n);return s?s instanceof oa?Mp(t,e,s,o):s instanceof pa||s instanceof ia||s instanceof sa?Tp(t,e,s):s instanceof na?Ip(t,e,s):s instanceof Sr?dm(t,e,s):s instanceof da?kp(t,e,s,o):s instanceof ca?Lp(t,e,s,o):s instanceof ua?Rp(t,e,s):Np(t,e,s):(C.warn(`Payment method ${n} not found`),null)},getSDKUtilities:()=>({getCardNetworkAsset:ko,getUIOrderAmount:()=>{let{merchantAmount:n,totalOrderAmount:o,currencyCode:s}=e.configuration.clientSession.order;return Zo(e.locale,n??o,s)},getCDNAssets:async n=>{let o=r.find(({config:c})=>c.type===n);if(!o)return;let{backgroundColor:s}=o.config.displayMetadata?.button||{};return{assets:{icon:n?`brand/icon/${n.toLowerCase().replace(/_/g,"-")}.svg`:""},colors:{background:s?.colored||"",main:s?.colored||""},description:o.config.name||null,is_primer_app:!1,name:o.config.name,website:null,goatCdnUrl:es}},getPaymentMethodConfiguration:n=>r.find(({config:o})=>o.type===n)?.config,setBillingAddress:async n=>{let{error:o,data:s}=await e.clientSessionApi.setBillingAddress(n);if(o||!s)throw o||new R({message:"Failed to set billing address"})}}),getAnalyticsUtils:()=>i,createVaultManager(){return sm(t,e,r)},getAssetsManager:()=>({getCardNetworkAsset:ko,getPaymentMethodAsset:async n=>{let o=r.find(({config:p})=>p.type===n);if(!o)return null;let{backgroundColor:s,iconUrl:l,text:c}=o.config.displayMetadata?.button||{};return{backgroundColor:s,iconUrl:l,paymentMethodName:c,buttonText:c,displayName:o.config.name}}}),refreshClientSession:e.refreshClientConfiguration,getConfiguration:()=>e.configuration,teardown:()=>e.teardown()}}function cm(a){switch(a.config.type){case B.PAYMENT_CARD:return jt.CARD;case B.KLARNA:return jt.KLARNA;case B.ADYEN_KLARNA:return jt.ADYEN_KLARNA;case B.ADYEN_MBWAY:return jt.MBWAY;default:return a.config.implementationType==="NATIVE_SDK"?jt.NATIVE:jt.REDIRECT}}var ko=a=>{let{asset:t,display:e}=Zt(a);return{cardUrl:`${es}/brand/card/${t}.svg`,displayName:e}},um=new Set(["paymentMethodType","last4Digits","network","accountNumberLastFourDigits","bankName"]);function Xt(a){let{id:t,orderId:e,paymentMethodData:r}=a,i={id:t,orderId:e};if(!r||typeof r!="object")return i;let n={};for(let[o,s]of Object.entries(r))um.has(o)&&(n[o]=s);return i.paymentMethodData=n,i}var pm={PAYMENT_CARD:{fields:["last4Digits","network","cardholderName","expirationMonth","expirationYear"]},PAYPAL_BILLING_AGREEMENT:{path:"externalPayerInfo",fields:["externalPayerId","email","firstName","lastName"]},KLARNA_CUSTOMER_TOKEN:{path:"sessionData.billingAddress",fields:["email","firstName","lastName","phoneNumber"]},AUTOMATED_CLEARING_HOUSE:{fields:["accountNumberLastFourDigits","bankName","accountType"]}};function mm(a,t){let e=a;for(let r of t.split(".")){if(!e||typeof e!="object")return;e=e[r]}return e&&typeof e=="object"?e:void 0}function hm(a,t){if(!a)return;let e={};for(let r of t)a[r]!==void 0&&(e[r]=a[r]);return Object.keys(e).length>0?e:void 0}function cs(a){let{id:t,analyticsId:e,paymentMethodType:r,paymentInstrumentType:i,paymentInstrumentData:n,userDescription:o}=a,s=pm[i],l;if(s&&n&&typeof n=="object"){let c=s.path?mm(n,s.path):n;l=hm(c,s.fields)}return{id:t,analyticsId:e,paymentMethodType:r,paymentInstrumentType:i,...o&&{userDescription:o},...l&&{paymentInstrumentData:l}}}var er=class{constructor(t){this.host=t}dispatchEvent(t,e){this.host.dispatchEvent(new CustomEvent(t,{detail:e,bubbles:!0,composed:!0}))}dispatchSdkState(t){this.dispatchEvent("primer:state-change",t)}dispatchPaymentMethods(t){this.dispatchEvent("primer:methods-update",t)}dispatchCheckoutInitialized(t){this.dispatchEvent("primer:ready",t)}dispatchCardNetworkChange(t){this.dispatchEvent("primer:card-network-change",t)}dispatchBinDataAvailable(t){this.dispatchEvent("primer:bin-data-available",t)}dispatchBinDataLoadingChange(t){this.dispatchEvent("primer:bin-data-loading-change",{loading:t})}dispatchCardSubmit(t){this.dispatchEvent("primer:card-submit",{source:t})}dispatchFormSubmitSuccess(t){this.dispatchEvent("primer:card-success",{result:t})}dispatchFormSubmitErrors(t){this.dispatchEvent("primer:card-error",{errors:t})}dispatchPaymentCancel(t){let e=Math.floor(Date.now()/1e3);this.dispatchEvent("primer:payment-cancel",{...t,timestamp:e})}handleExternalCardSubmit(t){this.dispatchCardSubmit(t.source)}dispatchPaymentStart(t,e){let r=Math.floor(Date.now()/1e3),i=!1,n=new CustomEvent("primer:payment-start",{detail:{paymentMethodType:t,abortPaymentCreation:()=>{i=!0,e.abortPaymentCreation()},continuePaymentCreation:o=>{i=!0,e.continuePaymentCreation(o)},timestamp:r},bubbles:!0,composed:!0,cancelable:!0});return this.host.dispatchEvent(n),n.defaultPrevented?!0:i}dispatchPaymentSuccess(t,e){let r=Xt(t),i=Math.floor(Date.now()/1e3);this.dispatchEvent("primer:payment-success",{payment:r,paymentMethodType:e,timestamp:i})}dispatchPaymentFailure(t,e,r){let i=Math.floor(Date.now()/1e3),n=r?Xt(r):void 0;this.dispatchEvent("primer:payment-failure",{error:t,payment:n,paymentMethodType:e,timestamp:i})}dispatchVaultMethodsUpdate(t,e){let r=Math.floor(Date.now()/1e3);this.dispatchEvent("primer:vault-methods-update",{vaultedPayments:t,cvvRecapture:e,timestamp:r})}dispatchVaultSelectionChange(t){let e=Math.floor(Date.now()/1e3);this.dispatchEvent("primer:vault-selection-change",{paymentMethodId:t,timestamp:e})}dispatchVaultSubmit(t){this.dispatchEvent("primer:vault-submit",{source:t})}handleExternalVaultSubmit(t){this.dispatchVaultSubmit(t.source)}dispatchShowOtherPaymentsToggle(t,e){this.dispatchEvent("primer:show-other-payments-toggle",{action:t,source:e})}handleExternalShowOtherPaymentsToggle(t){this.dispatchShowOtherPaymentsToggle(t.action,t.source)}dispatchShowOtherPaymentsToggled(t){this.dispatchEvent("primer:show-other-payments-toggled",{expanded:t})}};var gt=class extends Event{constructor(t,e,r,i){super("context-request",{bubbles:!0,composed:!0}),this.context=t,this.contextTarget=e,this.callback=r,this.subscribe=i??!1}};var tr=class{constructor(t,e,r,i){if(this.subscribe=!1,this.provided=!1,this.value=void 0,this.t=(n,o)=>{this.unsubscribe&&(this.unsubscribe!==o&&(this.provided=!1,this.unsubscribe()),this.subscribe||this.unsubscribe()),this.value=n,this.host.requestUpdate(),this.provided&&!this.subscribe||(this.provided=!0,this.callback&&this.callback(n,o)),this.unsubscribe=o},this.host=t,e.context!==void 0){let n=e;this.context=n.context,this.callback=n.callback,this.subscribe=n.subscribe??!1}else this.context=e,this.callback=r,this.subscribe=i??!1;this.host.addController(this)}hostConnected(){this.dispatchRequest()}hostDisconnected(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=void 0)}dispatchRequest(){this.host.dispatchEvent(new gt(this.context,this.host,this.t,this.subscribe))}};var ga=class{get value(){return this.o}set value(t){this.setValue(t)}setValue(t,e=!1){let r=e||!Object.is(t,this.o);this.o=t,r&&this.updateObservers()}constructor(t){this.subscriptions=new Map,this.updateObservers=()=>{for(let[e,{disposer:r}]of this.subscriptions)e(this.o,r)},t!==void 0&&(this.value=t)}addCallback(t,e,r){if(!r)return void t(this.value);this.subscriptions.has(t)||this.subscriptions.set(t,{disposer:()=>{this.subscriptions.delete(t)},consumerHost:e});let{disposer:i}=this.subscriptions.get(t);t(this.value,i)}clearCallbacks(){this.subscriptions.clear()}};var nn=class extends Event{constructor(t,e){super("context-provider",{bubbles:!0,composed:!0}),this.context=t,this.contextTarget=e}},yt=class extends ga{constructor(t,e,r){super(e.context!==void 0?e.initialValue:r),this.onContextRequest=i=>{if(i.context!==this.context)return;let n=i.contextTarget??i.composedPath()[0];n!==this.host&&(i.stopPropagation(),this.addCallback(i.callback,n,i.subscribe))},this.onProviderRequest=i=>{if(i.context!==this.context||(i.contextTarget??i.composedPath()[0])===this.host)return;let n=new Set;for(let[o,{consumerHost:s}]of this.subscriptions)n.has(o)||(n.add(o),s.dispatchEvent(new gt(this.context,s,o,!0)));i.stopPropagation()},this.host=t,e.context!==void 0?this.context=e.context:this.context=e,this.attachListeners(),this.host.addController?.(this)}attachListeners(){this.host.addEventListener("context-request",this.onContextRequest),this.host.addEventListener("context-provider",this.onProviderRequest)}hostConnected(){this.host.dispatchEvent(new nn(this.context,this.host))}};function G({context:a,subscribe:t}){return(e,r)=>{typeof r=="object"?r.addInitializer((function(){new tr(this,{context:a,callback:i=>{e.set.call(this,i)},subscribe:t})})):e.constructor.addInitializer((i=>{new tr(i,{context:a,callback:n=>{i[r]=n},subscribe:t})}))}}var K=Symbol("primer-context");function ft(a,t,e=0,r=10){if(e>r)return a===t;if(a===t)return!0;if(a==null||t==null||typeof a!="object"||typeof t!="object")return!1;let i=Object.keys(a);if(i.length!==Object.keys(t).length)return!1;for(let n of i){if(!(n in t))return!1;let o=a[n],s=t[n];if(typeof o=="object"&&o!==null&&(typeof s=="object"&&s!==null)){if(!ft(o,s,e+1,r))return!1}else if(o!==s)return!1}return!0}var ps={klarnaCategories:{categories:[],isLoading:!0},sdkState:{isSuccessful:!1,isProcessing:!1,isLoading:!1,primerJsError:null,paymentFailure:null},paymentMethods:[]},ya=class{constructor(t){(this.host=t).addController(this),this.contextProvider=new yt(t,{context:K,initialValue:structuredClone(ps)})}hostConnected(){}setContext(t){this.contextProvider?.setValue({...this.contextProvider.value,...t})}setSdkState(t){let e=this.contextProvider.value.sdkState,r={...e,...t};ft(e,r)||(this.host.primerEventsController.dispatchSdkState(r),this.setContext({sdkState:r}))}resetSdkState(){this.setContext(structuredClone(ps))}setCardNetworks(t){this.setContext({cardNetworks:t})}setCardNetworksLoadingFalse(){this.setContext({cardNetworks:{detectedCardNetwork:this.contextProvider.value.cardNetworks?.detectedCardNetwork??null,selectableCardNetworks:this.contextProvider.value.cardNetworks?.selectableCardNetworks??[],isLoading:!1}})}setVaultManager(t){this.setContext({vaultManager:t})}setKlarnaCategories(t){this.setContext({klarnaCategories:t})}setAdyenKlarnaOptions(t){this.setContext({adyenKlarnaOptions:t})}setComputedStyles(t){this.setContext({computedStyles:t})}setVaultManagerCvv(t){this.setContext({vaultItem:t})}setEventsController(t){this.setContext({events:t})}};var _t=class _t{constructor(t){(this.host=t).addController(this)}processCustomStyles(t){try{let e=JSON.parse(t);this.applyStyles(e)}catch(e){P.error("Error parsing customStyles property.",e instanceof Error?e:new Error(String(e)))}}isValidCssProperty(t){return/^[a-zA-Z][a-zA-Z0-9]*$/.test(t)}isValidCssValue(t){let r=/^[\w\s#.,%()\-+/!]+$/.test(t);return r||P.warn(`Rejected potentially unsafe CSS value: ${t}`),r}getCssVarName(t){let e=_t.cssVarCache.get(t);return e||(e=`--${t.replace(/([A-Z])/g,(r,i)=>`-${i.toLowerCase()}`)}`,_t.cssVarCache.set(t,e)),e}applyStyles(t){let e=[];for(let r of Object.keys(t)){let i=t[r];if(!i)continue;if(!this.isValidCssProperty(r)){P.warn(`Skipping invalid CSS property name: ${r}`);continue}if(!this.isValidCssValue(i))continue;let n=this.getCssVarName(r);e.push([n,i])}if(e.length>0)for(let[r,i]of e)this.host.style.setProperty(r,i)}removeStyle(t){let e=this.getCssVarName(t);this.host.style.removeProperty(e)}clearAllStyles(){for(let t of _t.cssVarCache.keys()){let e=_t.cssVarCache.get(t);e&&this.host.style.removeProperty(e)}}hostDisconnected(){}};_t.cssVarCache=new Map;var fa=_t;var va=globalThis,Ca=va.ShadowRoot&&(va.ShadyCSS===void 0||va.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,hs=Symbol(),ms=new WeakMap,ba=class{constructor(t,e,r){if(this._$cssResult$=!0,r!==hs)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=e}get styleSheet(){let t=this.o,e=this.t;if(Ca&&t===void 0){let r=e!==void 0&&e.length===1;r&&(t=ms.get(e)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),r&&ms.set(e,t))}return t}toString(){return this.cssText}},gs=a=>new ba(typeof a=="string"?a:a+"",void 0,hs);var on=(a,t)=>{if(Ca)a.adoptedStyleSheets=t.map((e=>e instanceof CSSStyleSheet?e:e.styleSheet));else for(let e of t){let r=document.createElement("style"),i=va.litNonce;i!==void 0&&r.setAttribute("nonce",i),r.textContent=e.cssText,a.appendChild(r)}},Sa=Ca?a=>a:a=>a instanceof CSSStyleSheet?(t=>{let e="";for(let r of t.cssRules)e+=r.cssText;return gs(e)})(a):a;var{is:gm,defineProperty:ym,getOwnPropertyDescriptor:fm,getOwnPropertyNames:vm,getOwnPropertySymbols:bm,getPrototypeOf:Cm}=Object,vt=globalThis,ys=vt.trustedTypes,Sm=ys?ys.emptyScript:"",Am=vt.reactiveElementPolyfillSupport,Er=(a,t)=>a,sn={toAttribute(a,t){switch(t){case Boolean:a=a?Sm:null;break;case Object:case Array:a=a==null?a:JSON.stringify(a)}return a},fromAttribute(a,t){let e=a;switch(t){case Boolean:e=a!==null;break;case Number:e=a===null?null:Number(a);break;case Object:case Array:try{e=JSON.parse(a)}catch{e=null}}return e}},Aa=(a,t)=>!gm(a,t),fs={attribute:!0,type:String,converter:sn,reflect:!1,hasChanged:Aa};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),vt.litPropertyMetadata??(vt.litPropertyMetadata=new WeakMap);var Ot=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??(this.l=[])).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,e=fs){if(e.state&&(e.attribute=!1),this._$Ei(),this.elementProperties.set(t,e),!e.noAccessor){let r=Symbol(),i=this.getPropertyDescriptor(t,r,e);i!==void 0&&ym(this.prototype,t,i)}}static getPropertyDescriptor(t,e,r){let{get:i,set:n}=fm(this.prototype,t)??{get(){return this[e]},set(o){this[e]=o}};return{get(){return i?.call(this)},set(o){let s=i?.call(this);n.call(this,o),this.requestUpdate(t,s,r)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??fs}static _$Ei(){if(this.hasOwnProperty(Er("elementProperties")))return;let t=Cm(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(Er("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Er("properties"))){let e=this.properties,r=[...vm(e),...bm(e)];for(let i of r)this.createProperty(i,e[i])}let t=this[Symbol.metadata];if(t!==null){let e=litPropertyMetadata.get(t);if(e!==void 0)for(let[r,i]of e)this.elementProperties.set(r,i)}this._$Eh=new Map;for(let[e,r]of this.elementProperties){let i=this._$Eu(e,r);i!==void 0&&this._$Eh.set(i,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){let e=[];if(Array.isArray(t)){let r=new Set(t.flat(1/0).reverse());for(let i of r)e.unshift(Sa(i))}else t!==void 0&&e.push(Sa(t));return e}static _$Eu(t,e){let r=e.attribute;return r===!1?void 0:typeof r=="string"?r:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise((t=>this.enableUpdating=t)),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach((t=>t(this)))}addController(t){(this._$EO??(this._$EO=new Set)).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){let t=new Map,e=this.constructor.elementProperties;for(let r of e.keys())this.hasOwnProperty(r)&&(t.set(r,this[r]),delete this[r]);t.size>0&&(this._$Ep=t)}createRenderRoot(){let t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return on(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),this._$EO?.forEach((t=>t.hostConnected?.()))}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach((t=>t.hostDisconnected?.()))}attributeChangedCallback(t,e,r){this._$AK(t,r)}_$EC(t,e){let r=this.constructor.elementProperties.get(t),i=this.constructor._$Eu(t,r);if(i!==void 0&&r.reflect===!0){let n=(r.converter?.toAttribute!==void 0?r.converter:sn).toAttribute(e,r.type);this._$Em=t,n==null?this.removeAttribute(i):this.setAttribute(i,n),this._$Em=null}}_$AK(t,e){let r=this.constructor,i=r._$Eh.get(t);if(i!==void 0&&this._$Em!==i){let n=r.getPropertyOptions(i),o=typeof n.converter=="function"?{fromAttribute:n.converter}:n.converter?.fromAttribute!==void 0?n.converter:sn;this._$Em=i,this[i]=o.fromAttribute(e,n.type),this._$Em=null}}requestUpdate(t,e,r){if(t!==void 0){if(r??(r=this.constructor.getPropertyOptions(t)),!(r.hasChanged??Aa)(this[t],e))return;this.P(t,e,r)}this.isUpdatePending===!1&&(this._$ES=this._$ET())}P(t,e,r){this._$AL.has(t)||this._$AL.set(t,e),r.reflect===!0&&this._$Em!==t&&(this._$Ej??(this._$Ej=new Set)).add(t)}async _$ET(){this.isUpdatePending=!0;try{await this._$ES}catch(e){Promise.reject(e)}let t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(let[i,n]of this._$Ep)this[i]=n;this._$Ep=void 0}let r=this.constructor.elementProperties;if(r.size>0)for(let[i,n]of r)n.wrapped!==!0||this._$AL.has(i)||this[i]===void 0||this.P(i,this[i],n)}let t=!1,e=this._$AL;try{t=this.shouldUpdate(e),t?(this.willUpdate(e),this._$EO?.forEach((r=>r.hostUpdate?.())),this.update(e)):this._$EU()}catch(r){throw t=!1,this._$EU(),r}t&&this._$AE(e)}willUpdate(t){}_$AE(t){this._$EO?.forEach((e=>e.hostUpdated?.())),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EU(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Ej&&(this._$Ej=this._$Ej.forEach((e=>this._$EC(e,this[e])))),this._$EU()}updated(t){}firstUpdated(t){}};Ot.elementStyles=[],Ot.shadowRootOptions={mode:"open"},Ot[Er("elementProperties")]=new Map,Ot[Er("finalized")]=new Map,Am?.({ReactiveElement:Ot}),(vt.reactiveElementVersions??(vt.reactiveElementVersions=[])).push("2.0.4");var bt={INITIAL:0,PENDING:1,COMPLETE:2,ERROR:3},Y=Symbol(),$=class{get taskComplete(){return this.t||(this.i===1?this.t=new Promise(((t,e)=>{this.o=t,this.h=e})):this.i===3?this.t=Promise.reject(this.l):this.t=Promise.resolve(this.u)),this.t}constructor(t,e,r){this.p=0,this.i=0,(this._=t).addController(this);let i=typeof e=="object"?e:{task:e,args:r};this.v=i.task,this.j=i.args,this.m=i.argsEqual??vs,this.k=i.onComplete,this.A=i.onError,this.autoRun=i.autoRun??!0,"initialValue"in i&&(this.u=i.initialValue,this.i=2,this.O=this.T?.())}hostUpdate(){this.autoRun===!0&&this.S()}hostUpdated(){this.autoRun==="afterUpdate"&&this.S()}T(){if(this.j===void 0)return;let t=this.j();if(!Array.isArray(t))throw Error("The args function must return an array");return t}async S(){let t=this.T(),e=this.O;this.O=t,t===e||t===void 0||e!==void 0&&this.m(e,t)||await this.run(t)}async run(t){let e,r;t??(t=this.T()),this.O=t,this.i===1?this.q?.abort():(this.t=void 0,this.o=void 0,this.h=void 0),this.i=1,this.autoRun==="afterUpdate"?queueMicrotask((()=>this._.requestUpdate())):this._.requestUpdate();let i=++this.p;this.q=new AbortController;let n=!1;try{e=await this.v(t,{signal:this.q.signal})}catch(o){n=!0,r=o}if(this.p===i){if(e===Y)this.i=0;else{if(n===!1){try{this.k?.(e)}catch{}this.i=2,this.o?.(e)}else{try{this.A?.(r)}catch{}this.i=3,this.h?.(r)}this.u=e,this.l=r}this._.requestUpdate()}}abort(t){this.i===1&&this.q?.abort(t)}get value(){return this.u}get error(){return this.l}get status(){return this.i}render(t){switch(this.i){case 0:return t.initial?.();case 1:return t.pending?.();case 2:return t.complete?.(this.value);case 3:return t.error?.(this.error);default:throw Error("Unexpected status: "+this.i)}}},vs=(a,t)=>a===t||a.length===t.length&&a.every(((e,r)=>!Aa(e,t[r])));var Ea={enabled:!1,isLoading:!1,isUpdating:!1,cvvRecapture:!1,showEmptyState:!1,headless:!1,vaultedPaymentMethods:[],createCvvInput:null,deleteVaultedPaymentMethod:()=>Promise.resolve(),startVaultedPaymentFlow:()=>Promise.resolve()},bs={cvvInput:null,formIsDirty:!1,setCvvInput:()=>{},selectedVaultedPaymentMethod:null,setSelectedVaultedPaymentMethod:()=>{}},Mr=class{constructor(t){this.host=t;this._coreState={...Ea};this._itemState={...bs};this._vaultManager=null;this._options=null;this.createVaultManagerFn=null;this.createCvvInput=t=>{if(!this._vaultManager)throw new Error("Vault manager not initialized");return this._vaultManager.createCvvInput(t)};this.deleteVaultedPaymentMethod=async t=>{if(!this._vaultManager)throw new Error("Vault manager not initialized");try{this.updateCoreState({vaultedPaymentMethods:this._coreState.vaultedPaymentMethods}),await this._vaultManager.deleteVaultedPaymentMethod(t),await this.fetchVaultedPaymentMethods()}catch(e){let r=e instanceof Error?e:new Error("Failed to delete payment method");throw this.updateCoreState({isLoading:!1,isUpdating:!1}),this.host.sdkContextController.setSdkState({primerJsError:r}),e}};this.setCvvInput=t=>{this.updateItemState({cvvInput:t})};this.startVaultedPaymentFlow=async()=>{if(!this._vaultManager)throw new Error("Vault manager not initialized");let t=this._itemState.selectedVaultedPaymentMethod,e=this._coreState.cvvRecapture,r=this._itemState.cvvInput;if(!t||e&&(!r||r.metadata.error)){this.updateItemState({formIsDirty:!0});return}this.host.sdkContextController.setSdkState({isProcessing:!0,paymentFailure:null,primerJsError:null});try{await this._vaultManager.startPaymentFlow(t.id,e?{cvv:r?.valueToken}:void 0)}catch(i){P.errorWithDatadog("VaultManagerController: Error starting vaulted payment flow",{error:i});let n=i instanceof Error?i:new Error("Failed to start vaulted payment flow");this.updateCoreState({isLoading:!1,isUpdating:!1}),this.host.sdkContextController.setSdkState({isProcessing:!1,primerJsError:n})}};this.setSelectedVaultedPaymentMethod=t=>{this.updateItemState({selectedVaultedPaymentMethod:t,formIsDirty:!1}),this.host.primerEventsController.dispatchVaultSelectionChange(t?.id??null)};this.startVaultPaymentById=async(t,e)=>{if(!this._vaultManager)throw new Error("Vault manager not initialized");let r=this._coreState.vaultedPaymentMethods.find(i=>i.id===t);if(!r)throw new Error(`Payment method not found: ${t}`);this.setSelectedVaultedPaymentMethod(r),this.host.sdkContextController.setSdkState({isProcessing:!0,paymentFailure:null,primerJsError:null});try{await this._vaultManager.startPaymentFlow(t,e?.cvv?{cvv:e.cvv}:void 0)}catch(i){P.errorWithDatadog("VaultManagerController: Error starting vaulted payment flow",{error:i});let n=i instanceof Error?i:new Error("Failed to start vaulted payment flow");throw this.updateCoreState({isLoading:!1,isUpdating:!1}),this.host.sdkContextController.setSdkState({isProcessing:!1,primerJsError:n}),i}};this.host.addController(this),this._coreState={...this._coreState,deleteVaultedPaymentMethod:this.deleteVaultedPaymentMethod.bind(this),startVaultedPaymentFlow:this.startVaultedPaymentFlow.bind(this),createCvvInput:this.createCvvInput},this._itemState={...this._itemState,setCvvInput:this.setCvvInput.bind(this),setSelectedVaultedPaymentMethod:this.setSelectedVaultedPaymentMethod.bind(this)},new $(this.host,{task:async([e,r])=>{if(!e||!r?.vaultEnabled)return this.updateCoreState({...Ea,enabled:!1}),Y;this.updateCoreState({isLoading:!0});try{let i=e();this._vaultManager=i,this.updateCoreState({enabled:r.vaultEnabled,cvvRecapture:!!r.captureVaultedCardCvv,showEmptyState:r.showEmptyState??!1,headless:r.headless??!1,deleteVaultedPaymentMethod:this.deleteVaultedPaymentMethod.bind(this),startVaultedPaymentFlow:this.startVaultedPaymentFlow.bind(this),createCvvInput:this.createCvvInput}),this.host.sdkContextController.setVaultManagerCvv(this._itemState),await this.fetchVaultedPaymentMethods(!0),P.log("VaultManagerController: Vault initialized successfully",{coreState:this.vaultManagerState,cvvState:this.vaultItemState})}catch(i){P.errorWithDatadog("VaultManagerController: Failed to initialize vault",{error:i});let n=i instanceof Error?i:new Error("Unknown error");this.updateCoreState({isLoading:!1,isUpdating:!1}),this.host.sdkContextController.setSdkState({primerJsError:n})}return this._vaultManager},args:()=>[this.createVaultManagerFn,this.options]})}updateCoreState(t){let e={...this._coreState,...t};ft(this._coreState,e)?this._coreState=e:(this._coreState=e,this.host.sdkContextController.setVaultManager(e))}updateItemState(t){let e={...this._itemState,...t};ft(this._itemState,e)?this._itemState=e:(this._itemState=e,this.host.sdkContextController.setVaultManagerCvv(e))}initializeVaultManager(t,e){this.createVaultManagerFn=t,this.options=e??null}get vaultManager(){return this._vaultManager}set vaultManager(t){this._vaultManager=t,this.host.requestUpdate()}get options(){return this._options}set options(t){this._options=t,this.host.requestUpdate()}get vaultManagerState(){return Object.freeze({...this._coreState})}get vaultItemState(){return Object.freeze({...this._itemState})}hostConnected(){}hostDisconnected(){this.vaultManager=null,this.updateCoreState({...Ea})}createVaultedPaymentsArray(t){return t.map(e=>cs(e))}updatePaymentMethodsWithEvents(t){this.updateCoreState({vaultedPaymentMethods:t,isLoading:!1,isUpdating:!1});let e=this.createVaultedPaymentsArray(t);this.host.primerEventsController.dispatchVaultMethodsUpdate(e,this.vaultManagerState.cvvRecapture),this.host.primerJS?.handleVaultedMethodsUpdate(e,this.vaultManagerState.cvvRecapture),P.log("VaultManagerController: Dispatched vault methods update",{methodCount:t.length,filteredMethodCount:e.length})}async fetchVaultedPaymentMethods(t){if(!this._vaultManager)throw new Error("Vault manager not initialized");try{t||this.updateCoreState({isUpdating:!0});let e=await this._vaultManager.fetchVaultedPaymentMethods();return P.log("VaultManagerController: Fetched payment methods",e),this.updatePaymentMethodsWithEvents(e),e}catch(e){let r=e instanceof Error?e:new Error("Failed to fetch payment methods");throw this.updateCoreState({isLoading:!1,isUpdating:!1}),this.host.sdkContextController.setSdkState({primerJsError:r}),e}}};var Cs=()=>Ss.randomUUID?.()||Em(),Em=()=>("10000000-1000-4000-8000"+-1e11).replace(/[018]/g,a=>(a^Mm()>>a/4).toString(16)),Mm=()=>(Ss.getRandomValues?.(new Uint8Array(1))[0]??Math.random()*16)&15,Ss=typeof crypto<"u"?crypto:{};var Pm={LOCAL:"https://analytics.sandbox.data.primer.io/v1/sdk-analytic-events",DEV:"https://analytics.dev.data.primer.io/v1/sdk-analytic-events",STAGING:"https://analytics.staging.data.primer.io/v1/sdk-analytic-events",SANDBOX:"https://analytics.sandbox.data.primer.io/v1/sdk-analytic-events",PRODUCTION:"https://analytics.production.data.primer.io/v1/sdk-analytic-events"},ln=class{sendEvent(t){let e=De.getContext();if(!e)return;let r={...t,id:Cs(),timestamp:Math.floor(Date.now()/1e3),sdkType:"WEB",eventName:t.eventName,checkoutSessionId:e.checkoutSessionId,clientSessionId:e.clientSessionId,primerAccountId:e.primerAccountId,sdkVersion:e.sdkVersion,userAgent:e.userAgent,eventType:t.eventType,userLocale:t.userLocale,paymentMethod:t.paymentMethod,paymentId:t.paymentId,redirectDestinationUrl:t.redirectDestinationUrl,threedsProvider:t.threedsProvider,threedsResponse:t.threedsResponse};Nm(r,e)}},Tm=new ln;function As(a){let t={...a,userAgent:a.userAgent||(typeof navigator<"u"?navigator.userAgent:"")};De.initialize(t)}function Q(a){Tm.sendEvent(a)}function Es(){De.clear()}async function Nm(a,{environment:t,clientSessionToken:e}){if(t==="LOCAL"){P.debug(`Analytics event ${a.eventName}:`,a);return}let r=Pm[t];return fetch(r,{method:"POST",headers:{"Content-Type":"application/json",...e&&{Authorization:`Bearer ${e}`}},body:JSON.stringify(a),keepalive:!0,priority:"low"}).catch(i=>{P.error("Failed to send analytics event:",i)})}var Pr="lit-localize-status";var Ms=a=>typeof a!="string"&&"strTag"in a,Ma=(a,t,e)=>{let r=a[0];for(let i=1;i<a.length;i++)r+=t[e?e[i-1]:i-1],r+=a[i];return r};var Tr=(a=>Ms(a)?Ma(a.strings,a.values):a);var E=Tr,Ps=!1;function dn(a){if(Ps)throw new Error("lit-localize can only be configured once");E=a,Ps=!0}var cn=class{constructor(t){this.__litLocalizeEventHandler=e=>{e.detail.status==="ready"&&this.host.requestUpdate()},this.host=t}hostConnected(){window.addEventListener(Pr,this.__litLocalizeEventHandler)}hostDisconnected(){window.removeEventListener(Pr,this.__litLocalizeEventHandler)}},Im=a=>a.addController(new cn(a)),Ts=Im;var D=()=>(a,t)=>(a.addInitializer(Ts),a);var Nr=class{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._resolve=t,this._reject=e})}resolve(t){this.settled=!0,this._resolve(t)}reject(t){this.settled=!0,this._reject(t)}};var Ze=[];for(let a=0;a<256;a++)Ze[a]=(a>>4&15).toString(16)+(a&15).toString(16);function Ns(a){let t=0,e=8997,r=0,i=33826,n=0,o=40164,s=0,l=52210;for(let c=0;c<a.length;c++)e^=a.charCodeAt(c),t=e*435,r=i*435,n=o*435,s=l*435,n+=e<<8,s+=i<<8,r+=t>>>16,e=t&65535,n+=r>>>16,i=r&65535,l=s+(n>>>16)&65535,o=n&65535;return Ze[l>>8]+Ze[l&255]+Ze[o>>8]+Ze[o&255]+Ze[i>>8]+Ze[i&255]+Ze[e>>8]+Ze[e&255]}var km="",Lm="h",Rm="s";function Is(a,t){return(t?Lm:Rm)+Ns(typeof a=="string"?a:a.join(km))}var ks=new WeakMap,Ls=new Map;function Rs(a,t,e){if(a){let r=e?.id??wm(t),i=a[r];if(i){if(typeof i=="string")return i;if("strTag"in i)return Ma(i.strings,t.values,i.values);{let n=ks.get(i);return n===void 0&&(n=i.values,ks.set(i,n)),{...i,values:n.map(o=>t.values[o])}}}}return Tr(t)}function wm(a){let t=typeof a=="string"?a:a.strings,e=Ls.get(t);return e===void 0&&(e=Is(t,typeof a!="string"&&!("strTag"in a)),Ls.set(t,e)),e}function un(a){window.dispatchEvent(new CustomEvent(Pr,{detail:a}))}var Ta="",pn,ws,Na,mn,xs,Dt=new Nr;Dt.resolve();var Pa=0,_s=a=>(dn(((t,e)=>Rs(xs,t,e))),Ta=ws=a.sourceLocale,Na=new Set(a.targetLocales),Na.add(a.sourceLocale),mn=a.loadLocale,{getLocale:xm,setLocale:_m}),xm=()=>Ta,_m=a=>{if(a===(pn??Ta))return Dt.promise;if(!Na||!mn)throw new Error("Internal error");if(!Na.has(a))throw new Error("Invalid locale code");Pa++;let t=Pa;return pn=a,Dt.settled&&(Dt=new Nr),un({status:"loading",loadingLocale:a}),(a===ws?Promise.resolve({templates:void 0}):mn(a)).then(r=>{Pa===t&&(Ta=a,pn=void 0,xs=r.templates,un({status:"ready",readyLocale:a}),Dt.resolve())},r=>{Pa===t&&(un({status:"error",errorLocale:a,errorMessage:r.toString()}),Dt.reject(r))}),Dt.promise};var hn="en",gn=["ar","bg","ca","cs","da","de","el","en-GB","es","es-AR","es-MX","et-EE","fi-FI","fr","he","hr","hu","id","it","ja","ko","lt","lt-LT","lv","lv-LV","ms","nb","nl","nl_NL","pl","pt","pt-BR","ro","ru","sk","sl","sr-RS","sv","th","tr","uk-UA","vi","zf","zh-CN","zh-HK","zh-TW"],yn="You must call `loadLocale` first to set up the localized template.",Ia,ka,Os=a=>{let t=_s({sourceLocale:hn,targetLocales:gn,loadLocale:a});Ia=t.getLocale,ka=t.setLocale};var fn=a=>{Os(a)},vn=a=>{if(!ka)throw new Error(yn);return ka(a)},bn=()=>{if(!Ia)throw new Error(yn);return Ia()};var Ir=new Set(gn);Ir.add(hn);var Cn=a=>{if(typeof a!="string")return!1;if(a==="en")return!0;let t=a.replace("_","-");if(Ir.has(t))return!0;let e=t.split("-")[0];return!!Ir.has(e)},La=()=>navigator.language||navigator.languages[0]||"en",rr=a=>{let t=a.replace("_","-"),e=t.split("-")[0];return e==="en"?"en-GB":Ir.has(t)?t:Ir.has(e)?e:"en-GB"};var Ra=globalThis,wa=Ra.ShadowRoot&&(Ra.ShadyCSS===void 0||Ra.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Sn=Symbol(),Ds=new WeakMap,kr=class{constructor(t,e,r){if(this._$cssResult$=!0,r!==Sn)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=e}get styleSheet(){let t=this.o,e=this.t;if(wa&&t===void 0){let r=e!==void 0&&e.length===1;r&&(t=Ds.get(e)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),r&&Ds.set(e,t))}return t}toString(){return this.cssText}},Je=a=>new kr(typeof a=="string"?a:a+"",void 0,Sn),f=(a,...t)=>{let e=a.length===1?a[0]:t.reduce(((r,i,n)=>r+(o=>{if(o._$cssResult$===!0)return o.cssText;if(typeof o=="number")return o;throw Error("Value passed to 'css' function must be a 'css' function result: "+o+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(i)+a[n+1]),a[0]);return new kr(e,a,Sn)},Bs=(a,t)=>{if(wa)a.adoptedStyleSheets=t.map((e=>e instanceof CSSStyleSheet?e:e.styleSheet));else for(let e of t){let r=document.createElement("style"),i=Ra.litNonce;i!==void 0&&r.setAttribute("nonce",i),r.textContent=e.cssText,a.appendChild(r)}},An=wa?a=>a:a=>a instanceof CSSStyleSheet?(t=>{let e="";for(let r of t.cssRules)e+=r.cssText;return Je(e)})(a):a;var{is:Om,defineProperty:Dm,getOwnPropertyDescriptor:Bm,getOwnPropertyNames:Gm,getOwnPropertySymbols:Km,getPrototypeOf:Fm}=Object,Ct=globalThis,Gs=Ct.trustedTypes,Um=Gs?Gs.emptyScript:"",Vm=Ct.reactiveElementPolyfillSupport,Lr=(a,t)=>a,Rr={toAttribute(a,t){switch(t){case Boolean:a=a?Um:null;break;case Object:case Array:a=a==null?a:JSON.stringify(a)}return a},fromAttribute(a,t){let e=a;switch(t){case Boolean:e=a!==null;break;case Number:e=a===null?null:Number(a);break;case Object:case Array:try{e=JSON.parse(a)}catch{e=null}}return e}},xa=(a,t)=>!Om(a,t),Ks={attribute:!0,type:String,converter:Rr,reflect:!1,useDefault:!1,hasChanged:xa};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),Ct.litPropertyMetadata??(Ct.litPropertyMetadata=new WeakMap);var qe=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??(this.l=[])).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,e=Ks){if(e.state&&(e.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((e=Object.create(e)).wrapped=!0),this.elementProperties.set(t,e),!e.noAccessor){let r=Symbol(),i=this.getPropertyDescriptor(t,r,e);i!==void 0&&Dm(this.prototype,t,i)}}static getPropertyDescriptor(t,e,r){let{get:i,set:n}=Bm(this.prototype,t)??{get(){return this[e]},set(o){this[e]=o}};return{get:i,set(o){let s=i?.call(this);n?.call(this,o),this.requestUpdate(t,s,r)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??Ks}static _$Ei(){if(this.hasOwnProperty(Lr("elementProperties")))return;let t=Fm(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(Lr("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Lr("properties"))){let e=this.properties,r=[...Gm(e),...Km(e)];for(let i of r)this.createProperty(i,e[i])}let t=this[Symbol.metadata];if(t!==null){let e=litPropertyMetadata.get(t);if(e!==void 0)for(let[r,i]of e)this.elementProperties.set(r,i)}this._$Eh=new Map;for(let[e,r]of this.elementProperties){let i=this._$Eu(e,r);i!==void 0&&this._$Eh.set(i,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){let e=[];if(Array.isArray(t)){let r=new Set(t.flat(1/0).reverse());for(let i of r)e.unshift(An(i))}else t!==void 0&&e.push(An(t));return e}static _$Eu(t,e){let r=e.attribute;return r===!1?void 0:typeof r=="string"?r:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise((t=>this.enableUpdating=t)),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach((t=>t(this)))}addController(t){(this._$EO??(this._$EO=new Set)).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){let t=new Map,e=this.constructor.elementProperties;for(let r of e.keys())this.hasOwnProperty(r)&&(t.set(r,this[r]),delete this[r]);t.size>0&&(this._$Ep=t)}createRenderRoot(){let t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return Bs(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),this._$EO?.forEach((t=>t.hostConnected?.()))}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach((t=>t.hostDisconnected?.()))}attributeChangedCallback(t,e,r){this._$AK(t,r)}_$ET(t,e){let r=this.constructor.elementProperties.get(t),i=this.constructor._$Eu(t,r);if(i!==void 0&&r.reflect===!0){let n=(r.converter?.toAttribute!==void 0?r.converter:Rr).toAttribute(e,r.type);this._$Em=t,n==null?this.removeAttribute(i):this.setAttribute(i,n),this._$Em=null}}_$AK(t,e){let r=this.constructor,i=r._$Eh.get(t);if(i!==void 0&&this._$Em!==i){let n=r.getPropertyOptions(i),o=typeof n.converter=="function"?{fromAttribute:n.converter}:n.converter?.fromAttribute!==void 0?n.converter:Rr;this._$Em=i,this[i]=o.fromAttribute(e,n.type)??this._$Ej?.get(i)??null,this._$Em=null}}requestUpdate(t,e,r){if(t!==void 0){let i=this.constructor,n=this[t];if(r??(r=i.getPropertyOptions(t)),!((r.hasChanged??xa)(n,e)||r.useDefault&&r.reflect&&n===this._$Ej?.get(t)&&!this.hasAttribute(i._$Eu(t,r))))return;this.C(t,e,r)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(t,e,{useDefault:r,reflect:i,wrapped:n},o){r&&!(this._$Ej??(this._$Ej=new Map)).has(t)&&(this._$Ej.set(t,o??e??this[t]),n!==!0||o!==void 0)||(this._$AL.has(t)||(this.hasUpdated||r||(e=void 0),this._$AL.set(t,e)),i===!0&&this._$Em!==t&&(this._$Eq??(this._$Eq=new Set)).add(t))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(e){Promise.reject(e)}let t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(let[i,n]of this._$Ep)this[i]=n;this._$Ep=void 0}let r=this.constructor.elementProperties;if(r.size>0)for(let[i,n]of r){let{wrapped:o}=n,s=this[i];o!==!0||this._$AL.has(i)||s===void 0||this.C(i,void 0,n,s)}}let t=!1,e=this._$AL;try{t=this.shouldUpdate(e),t?(this.willUpdate(e),this._$EO?.forEach((r=>r.hostUpdate?.())),this.update(e)):this._$EM()}catch(r){throw t=!1,this._$EM(),r}t&&this._$AE(e)}willUpdate(t){}_$AE(t){this._$EO?.forEach((e=>e.hostUpdated?.())),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Eq&&(this._$Eq=this._$Eq.forEach((e=>this._$ET(e,this[e])))),this._$EM()}updated(t){}firstUpdated(t){}};qe.elementStyles=[],qe.shadowRootOptions={mode:"open"},qe[Lr("elementProperties")]=new Map,qe[Lr("finalized")]=new Map,Vm?.({ReactiveElement:qe}),(Ct.reactiveElementVersions??(Ct.reactiveElementVersions=[])).push("2.1.0");var xr=globalThis,_a=xr.trustedTypes,Fs=_a?_a.createPolicy("lit-html",{createHTML:a=>a}):void 0,Mn="$lit$",Qe=`lit$${Math.random().toFixed(9).slice(2)}$`,Pn="?"+Qe,Hm=`<${Pn}>`,Kt=document,_r=()=>Kt.createComment(""),Or=a=>a===null||typeof a!="object"&&typeof a!="function",Tn=Array.isArray,zs=a=>Tn(a)||typeof a?.[Symbol.iterator]=="function",En=`[
|
|
179
179
|
\f\r]`,wr=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Us=/-->/g,Vs=/>/g,Bt=RegExp(`>|${En}(?:([^\\s"'>=/]+)(${En}*=${En}*(?:[^
|
|
180
|
-
\f\r"'\`<>=]|("|')|))|$)`,"g"),Hs=/'/g,Ys=/"/g,js=/^(?:script|style|textarea|title)$/i,Nn=a=>(t,...e)=>({_$litType$:a,strings:t,values:e}),u=Nn(1),ge=Nn(2),wv=Nn(3),Xe=Symbol.for("lit-noChange"),y=Symbol.for("lit-nothing"),$s=new WeakMap,Gt=Kt.createTreeWalker(Kt,129);function Ws(a,t){if(!Tn(a)||!a.hasOwnProperty("raw"))throw Error("invalid template strings array");return Fs!==void 0?Fs.createHTML(t):t}var Zs=(a,t)=>{let e=a.length-1,r=[],i,n=t===2?"<svg>":t===3?"<math>":"",o=wr;for(let s=0;s<e;s++){let l=a[s],c,p,m=-1,g=0;for(;g<l.length&&(o.lastIndex=g,p=o.exec(l),p!==null);)g=o.lastIndex,o===wr?p[1]==="!--"?o=Us:p[1]!==void 0?o=Vs:p[2]!==void 0?(js.test(p[2])&&(i=RegExp("</"+p[2],"g")),o=Bt):p[3]!==void 0&&(o=Bt):o===Bt?p[0]===">"?(o=i??wr,m=-1):p[1]===void 0?m=-2:(m=o.lastIndex-p[2].length,c=p[1],o=p[3]===void 0?Bt:p[3]==='"'?Ys:Hs):o===Ys||o===Hs?o=Bt:o===Us||o===Vs?o=wr:(o=Bt,i=void 0);let A=o===Bt&&a[s+1].startsWith("/>")?" ":"";n+=o===wr?l+Hm:m>=0?(r.push(c),l.slice(0,m)+Mn+l.slice(m)+Qe+A):l+Qe+(m===-2?s:A)}return[Ws(a,n+(a[e]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),r]},Dr=class a{constructor({strings:t,_$litType$:e},r){let i;this.parts=[];let n=0,o=0,s=t.length-1,l=this.parts,[c,p]=Zs(t,e);if(this.el=a.createElement(c,r),Gt.currentNode=this.el.content,e===2||e===3){let m=this.el.content.firstChild;m.replaceWith(...m.childNodes)}for(;(i=Gt.nextNode())!==null&&l.length<s;){if(i.nodeType===1){if(i.hasAttributes())for(let m of i.getAttributeNames())if(m.endsWith(Mn)){let g=p[o++],A=i.getAttribute(m).split(Qe),M=/([.?@])?(.*)/.exec(g);l.push({type:1,index:n,name:M[2],strings:A,ctor:M[1]==="."?Da:M[1]==="?"?Ba:M[1]==="@"?Ga:Ut}),i.removeAttribute(m)}else m.startsWith(Qe)&&(l.push({type:6,index:n}),i.removeAttribute(m));if(js.test(i.tagName)){let m=i.textContent.split(Qe),g=m.length-1;if(g>0){i.textContent=_a?_a.emptyScript:"";for(let A=0;A<g;A++)i.append(m[A],_r()),Gt.nextNode(),l.push({type:2,index:++n});i.append(m[g],_r())}}}else if(i.nodeType===8)if(i.data===Pn)l.push({type:2,index:n});else{let m=-1;for(;(m=i.data.indexOf(Qe,m+1))!==-1;)l.push({type:7,index:n}),m+=Qe.length-1}n++}}static createElement(t,e){let r=Kt.createElement("template");return r.innerHTML=t,r}};function Ft(a,t,e=a,r){if(t===Xe)return t;let i=r!==void 0?e._$Co?.[r]:e._$Cl,n=Or(t)?void 0:t._$litDirective$;return i?.constructor!==n&&(i?._$AO?.(!1),n===void 0?i=void 0:(i=new n(a),i._$AT(a,e,r)),r!==void 0?(e._$Co??(e._$Co=[]))[r]=i:e._$Cl=i),i!==void 0&&(t=Ft(a,i._$AS(a,t.values),i,r)),t}var Oa=class{constructor(t,e){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=e}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){let{el:{content:e},parts:r}=this._$AD,i=(t?.creationScope??Kt).importNode(e,!0);Gt.currentNode=i;let n=Gt.nextNode(),o=0,s=0,l=r[0];for(;l!==void 0;){if(o===l.index){let c;l.type===2?c=new ar(n,n.nextSibling,this,t):l.type===1?c=new l.ctor(n,l.name,l.strings,this,t):l.type===6&&(c=new Ka(n,this,t)),this._$AV.push(c),l=r[++s]}o!==l?.index&&(n=Gt.nextNode(),o++)}return Gt.currentNode=Kt,i}p(t){let e=0;for(let r of this._$AV)r!==void 0&&(r.strings!==void 0?(r._$AI(t,r,e),e+=r.strings.length-2):r._$AI(t[e])),e++}},ar=class a{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,e,r,i){this.type=2,this._$AH=y,this._$AN=void 0,this._$AA=t,this._$AB=e,this._$AM=r,this.options=i,this._$Cv=i?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode,e=this._$AM;return e!==void 0&&t?.nodeType===11&&(t=e.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,e=this){t=Ft(this,t,e),Or(t)?t===y||t==null||t===""?(this._$AH!==y&&this._$AR(),this._$AH=y):t!==this._$AH&&t!==Xe&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):zs(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==y&&Or(this._$AH)?this._$AA.nextSibling.data=t:this.T(Kt.createTextNode(t)),this._$AH=t}$(t){let{values:e,_$litType$:r}=t,i=typeof r=="number"?this._$AC(t):(r.el===void 0&&(r.el=Dr.createElement(Ws(r.h,r.h[0]),this.options)),r);if(this._$AH?._$AD===i)this._$AH.p(e);else{let n=new Oa(i,this),o=n.u(this.options);n.p(e),this.T(o),this._$AH=n}}_$AC(t){let e=$s.get(t.strings);return e===void 0&&$s.set(t.strings,e=new Dr(t)),e}k(t){Tn(this._$AH)||(this._$AH=[],this._$AR());let e=this._$AH,r,i=0;for(let n of t)i===e.length?e.push(r=new a(this.O(_r()),this.O(_r()),this,this.options)):r=e[i],r._$AI(n),i++;i<e.length&&(this._$AR(r&&r._$AB.nextSibling,i),e.length=i)}_$AR(t=this._$AA.nextSibling,e){for(this._$AP?.(!1,!0,e);t&&t!==this._$AB;){let r=t.nextSibling;t.remove(),t=r}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}},Ut=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,e,r,i,n){this.type=1,this._$AH=y,this._$AN=void 0,this.element=t,this.name=e,this._$AM=i,this.options=n,r.length>2||r[0]!==""||r[1]!==""?(this._$AH=Array(r.length-1).fill(new String),this.strings=r):this._$AH=y}_$AI(t,e=this,r,i){let n=this.strings,o=!1;if(n===void 0)t=Ft(this,t,e,0),o=!Or(t)||t!==this._$AH&&t!==Xe,o&&(this._$AH=t);else{let s=t,l,c;for(t=n[0],l=0;l<n.length-1;l++)c=Ft(this,s[r+l],e,l),c===Xe&&(c=this._$AH[l]),o||(o=!Or(c)||c!==this._$AH[l]),c===y?t=y:t!==y&&(t+=(c??"")+n[l+1]),this._$AH[l]=c}o&&!i&&this.j(t)}j(t){t===y?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},Da=class extends Ut{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===y?void 0:t}},Ba=class extends Ut{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==y)}},Ga=class extends Ut{constructor(t,e,r,i,n){super(t,e,r,i,n),this.type=5}_$AI(t,e=this){if((t=Ft(this,t,e,0)??y)===Xe)return;let r=this._$AH,i=t===y&&r!==y||t.capture!==r.capture||t.once!==r.once||t.passive!==r.passive,n=t!==y&&(r===y||i);i&&this.element.removeEventListener(this.name,this,r),n&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,t):this._$AH.handleEvent(t)}},Ka=class{constructor(t,e,r){this.element=t,this.type=6,this._$AN=void 0,this._$AM=e,this.options=r}get _$AU(){return this._$AM._$AU}_$AI(t){Ft(this,t)}},Js={M:Mn,P:Qe,A:Pn,C:1,L:Zs,R:Oa,D:zs,V:Ft,I:ar,H:Ut,N:Ba,U:Ga,B:Da,F:Ka},Ym=xr.litHtmlPolyfillSupport;Ym?.(Dr,ar),(xr.litHtmlVersions??(xr.litHtmlVersions=[])).push("3.3.0");var qs=(a,t,e)=>{let r=e?.renderBefore??t,i=r._$litPart$;if(i===void 0){let n=e?.renderBefore??null;r._$litPart$=i=new ar(t.insertBefore(_r(),n),n,void 0,e??{})}return i._$AI(a),i};var Br=globalThis,v=class extends qe{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){var e;let t=super.createRenderRoot();return(e=this.renderOptions).renderBefore??(e.renderBefore=t.firstChild),t}update(t){let e=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=qs(e,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Xe}};v._$litElement$=!0,v.finalized=!0,Br.litElementHydrateSupport?.({LitElement:v});var $m=Br.litElementPolyfillSupport;$m?.({LitElement:v});(Br.litElementVersions??(Br.litElementVersions=[])).push("4.2.0");var b=a=>(t,e)=>{e!==void 0?e.addInitializer((()=>{customElements.define(a,t)})):customElements.define(a,t)};var zm={attribute:!0,type:String,converter:Rr,reflect:!1,hasChanged:xa},jm=(a=zm,t,e)=>{let{kind:r,metadata:i}=e,n=globalThis.litPropertyMetadata.get(i);if(n===void 0&&globalThis.litPropertyMetadata.set(i,n=new Map),r==="setter"&&((a=Object.create(a)).wrapped=!0),n.set(e.name,a),r==="accessor"){let{name:o}=e;return{set(s){let l=t.get.call(this);t.set.call(this,s),this.requestUpdate(o,l,a)},init(s){return s!==void 0&&this.C(o,void 0,a,s),s}}}if(r==="setter"){let{name:o}=e;return function(s){let l=this[o];t.call(this,s),this.requestUpdate(o,l,a)}}throw Error("Unsupported decorator location: "+r)};function h(a){return(t,e)=>typeof e=="object"?jm(a,t,e):((r,i,n)=>{let o=i.hasOwnProperty(n);return i.constructor.createProperty(n,r),o?Object.getOwnPropertyDescriptor(i,n):void 0})(a,t,e)}function N(a){return h({...a,state:!0,attribute:!1})}var Vt=(a,t,e)=>(e.configurable=!0,e.enumerable=!0,Reflect.decorate&&typeof t!="object"&&Object.defineProperty(a,t,e),e);function de(a,t){return(e,r,i)=>{let n=o=>o.renderRoot?.querySelector(a)??null;if(t){let{get:o,set:s}=typeof r=="object"?e:i??(()=>{let l=Symbol();return{get(){return this[l]},set(c){this[l]=c}}})();return Vt(e,r,{get(){let l=o.call(this);return l===void 0&&(l=n(this),(l!==null||this.hasUpdated)&&s.call(this,l)),l}})}return Vt(e,r,{get(){return n(this)}})}}function k(a,t,e){return a?t(a):e?.(a)}var T=f` * { box-sizing: border-box; } `,Qs=f` :host { display: block; isolation: isolate; position: relative; width: 100%; //Keep the CSS loader in the same position - check css-loader-inline.ts min-height: 64px; } `;var Xs="https://sdk.primer.io/web/v2-latest/Primer.min.js";var et="20px";var tt={WORLDPAY_IDEAL:"WORLDPAY_IDEAL",AUTOMATED_CLEARING_HOUSE:"AUTOMATED_CLEARING_HOUSE",ADYEN_KLARNA:"ADYEN_KLARNA",ADYEN_BANCONTACT_CARD:"ADYEN_BANCONTACT_CARD",PAY_NL_KAARTDIRECT:"PAY_NL_KAARTDIRECT",ADYEN_EPS:"ADYEN_EPS",ADYEN_BANCONTACT_PAYCONIQ:"ADYEN_BANCONTACT_PAYCONIQ",OMISE_PROMPTPAY:"OMISE_PROMPTPAY",OMISE_TRUEMONEY:"OMISE_TRUEMONEY",ADYEN_MULTIBANCO:"ADYEN_MULTIBANCO",PACYPAY_WECHAT:"PACYPAY_WECHAT",PACYPAY_ALIPAY:"PACYPAY_ALIPAY",ADYEN_MBWAY:"ADYEN_MBWAY",XENDIT_DANA:"XENDIT_DANA",XENDIT_SHOPEEPAY:"XENDIT_SHOPEEPAY",ADYEN_PAYSHOP:"ADYEN_PAYSHOP",ADYEN_PAYTRAIL:"ADYEN_PAYTRAIL",CLEARPAY:"CLEARPAY",RAPYD_FAST:"RAPYD_FAST",RAPYD_PROMPTPAY:"RAPYD_PROMPTPAY",RAPYD_GCASH:"RAPYD_GCASH",RAPYD_POLI:"RAPYD_POLI",RAPYD_GRABPAY:"RAPYD_GRABPAY",PRIMER_PAYPAL:"PRIMER_PAYPAL",TWOC2P:"TWOC2P",NETS:"NETS",STRIPE_ACH:"STRIPE_ACH",STRIPE_GIROPAY:"STRIPE_GIROPAY",MOLLIE_GIROPAY:"MOLLIE_GIROPAY",MOLLIE_EPS:"MOLLIE_EPS",PAY_NL_EPS:"PAY_NL_EPS",PAY_NL_P24:"PAY_NL_P24",MOLLIE_P24:"MOLLIE_P24",MOLLIE_SOFORT:"MOLLIE_SOFORT",COINBASE:"COINBASE",OPENNODE:"OPENNODE",MOLLIE_GIFT_CARD:"MOLLIE_GIFTCARD",XFERS_PAYNOW:"XFERS_PAYNOW",CARD:"PAYMENT_CARD",APPLE_PAY:"APPLE_PAY",GOOGLE_PAY:"GOOGLE_PAY",PAYPAL:"PAYPAL_ORDER",PAYPAL_VAULTED:"PAYPAL_BILLING_AGREEMENT",GO_CARDLESS:"GOCARDLESS",PAY_NL_IDEAL:"PAY_NL_IDEAL",PAY_NL_SOFORT_BANKING:"PAY_NL_SOFORT_BANKING",PAY_NL_BANCONTACT:"PAY_NL_BANCONTACT",PAY_NL_PAYPAL:"PAY_NL_PAYPAL",PAY_NL_CREDIT_TRANSFER:"PAY_NL_CREDIT_TRANSFER",PAY_NL_DIRECT_DEBIT:"PAY_NL_DIRECT_DEBIT",PAY_NL_GIROPAY:"PAY_NL_GIROPAY",PAY_NL_PAYCONIQ:"PAY_NL_PAYCONIQ",PAY_NL_RIVERTY:"PAY_NL_RIVERTY",HOOLAH:"HOOLAH",ADYEN_BLIK:"ADYEN_BLIK",ADYEN_VIPPS:"ADYEN_VIPPS",ADYEN_GIROPAY:"ADYEN_GIROPAY",ADYEN_SOFORT:"ADYEN_SOFORT",ADYEN_IDEAL:"ADYEN_IDEAL",ADYEN_TRUSTLY:"ADYEN_TRUSTLY",ADYEN_ALIPAY:"ADYEN_ALIPAY",ADYEN_TWINT:"ADYEN_TWINT",ADYEN_MOBILEPAY:"ADYEN_MOBILEPAY",MOLLIE_BANCONTACT:"MOLLIE_BANCONTACT",MOLLIE_IDEAL:"MOLLIE_IDEAL",BUCKAROO_GIROPAY:"BUCKAROO_GIROPAY",BUCKAROO_EPS:"BUCKAROO_EPS",BUCKAROO_SOFORT:"BUCKAROO_SOFORT",BUCKAROO_BANCONTACT:"BUCKAROO_BANCONTACT",BUCKAROO_IDEAL:"BUCKAROO_IDEAL",ATOME:"ATOME",KLARNA_CUSTOMER_TOKEN:"KLARNA_CUSTOMER_TOKEN",DLOCAL_PIX:"DLOCAL_PIX",ALMA:"ALMA",ADYEN_CASHAPP:"ADYEN_CASHAPP",ADYEN_AFFIRM:"ADYEN_AFFIRM"},W={WORLDPAY_IDEAL:"WORLDPAY_IDEAL",STRIPE_ACH:"STRIPE_ACH",STRIPE_IDEAL:"STRIPE_IDEAL",ADYEN_KLARNA:"ADYEN_KLARNA",ADYEN_BANCONTACT_CARD:"ADYEN_BANCONTACT_CARD",PAY_NL_KAARTDIRECT:"PAY_NL_KAARTDIRECT",ADYEN_EPS:"ADYEN_EPS",ADYEN_BANCONTACT_PAYCONIQ:"ADYEN_BANCONTACT_PAYCONIQ",OMISE_PROMPTPAY:"OMISE_PROMPTPAY",OMISE_TRUEMONEY:"OMISE_TRUEMONEY",ADYEN_MULTIBANCO:"ADYEN_MULTIBANCO",PACYPAY_WECHAT:"PACYPAY_WECHAT",PACYPAY_ALIPAY:"PACYPAY_ALIPAY",ADYEN_MBWAY:"ADYEN_MBWAY",XENDIT_DANA:"XENDIT_DANA",XENDIT_SHOPEEPAY:"XENDIT_SHOPEEPAY",ADYEN_PAYSHOP:"ADYEN_PAYSHOP",ADYEN_PAYTRAIL:"ADYEN_PAYTRAIL",CLEARPAY:"CLEARPAY",RAPYD_FAST:"RAPYD_FAST",RAPYD_PROMPTPAY:"RAPYD_PROMPTPAY",RAPYD_GCASH:"RAPYD_GCASH",RAPYD_POLI:"RAPYD_POLI",RAPYD_GRABPAY:"RAPYD_GRABPAY",PRIMER_PAYPAL:"PRIMER_PAYPAL",TWOC2P:"TWOC2P",NETS:"NETS",STRIPE_GIROPAY:"STRIPE_GIROPAY",MOLLIE_GIROPAY:"MOLLIE_GIROPAY",MOLLIE_EPS:"MOLLIE_EPS",PAY_NL_EPS:"PAY_NL_EPS",PAY_NL_P24:"PAY_NL_P24",MOLLIE_P24:"MOLLIE_P24",MOLLIE_SOFORT:"MOLLIE_SOFORT",COINBASE:"COINBASE",OPENNODE:"OPENNODE",MOLLIE_GIFT_CARD:"MOLLIE_GIFTCARD",XFERS_PAYNOW:"XFERS_PAYNOW",PAYMENT_CARD:"PAYMENT_CARD",APPLE_PAY:"APPLE_PAY",GOOGLE_PAY:"GOOGLE_PAY",PAYPAL:"PAYPAL",GO_CARDLESS:"GOCARDLESS",KLARNA:"KLARNA",PAY_NL_IDEAL:"PAY_NL_IDEAL",PAY_NL_SOFORT_BANKING:"PAY_NL_SOFORT_BANKING",PAY_NL_BANCONTACT:"PAY_NL_BANCONTACT",PAY_NL_PAYPAL:"PAY_NL_PAYPAL",PAY_NL_CREDIT_TRANSFER:"PAY_NL_CREDIT_TRANSFER",PAY_NL_DIRECT_DEBIT:"PAY_NL_DIRECT_DEBIT",PAY_NL_GIROPAY:"PAY_NL_GIROPAY",PAY_NL_PAYCONIQ:"PAY_NL_PAYCONIQ",PAY_NL_RIVERTY:"PAY_NL_RIVERTY",HOOLAH:"HOOLAH",ADYEN_BLIK:"ADYEN_BLIK",ADYEN_MOBILEPAY:"ADYEN_MOBILEPAY",ADYEN_VIPPS:"ADYEN_VIPPS",ADYEN_GIROPAY:"ADYEN_GIROPAY",ADYEN_SOFORT:"ADYEN_SOFORT",ADYEN_IDEAL:"ADYEN_IDEAL",ADYEN_TRUSTLY:"ADYEN_TRUSTLY",ADYEN_ALIPAY:"ADYEN_ALIPAY",ADYEN_TWINT:"ADYEN_TWINT",ADYEN_BANK_TRANSFER:"ADYEN_BANK_TRANSFER",MOLLIE_BANCONTACT:"MOLLIE_BANCONTACT",MOLLIE_IDEAL:"MOLLIE_IDEAL",BUCKAROO_GIROPAY:"BUCKAROO_GIROPAY",BUCKAROO_EPS:"BUCKAROO_EPS",BUCKAROO_SOFORT:"BUCKAROO_SOFORT",BUCKAROO_BANCONTACT:"BUCKAROO_BANCONTACT",BUCKAROO_IDEAL:"BUCKAROO_IDEAL",ATOME:"ATOME",DLOCAL_PIX:"DLOCAL_PIX",ALMA:"ALMA",ADYEN_CASHAPP:"ADYEN_CASHAPP",ADYEN_AFFIRM:"ADYEN_AFFIRM"};var Fa=class{constructor(t){this.paymentMethods=null;this.vaultController=null;this.headlessInstance=t,this.vault={createCvvInput:e=>this.createCvvInputInternal(e),startPayment:(e,r)=>this.startVaultPaymentInternal(e,r),delete:e=>this.deleteVaultPaymentMethod(e)}}setPaymentMethods(t){this.paymentMethods=t}setVaultController(t){this.vaultController=t}async createCvvInputInternal(t){return this.vaultController?this.vaultController.createCvvInput(t):(P.warn("PrimerJS: Vault not available - createCvvInput cannot be called"),null)}async startVaultPaymentInternal(t,e){if(!this.vaultController)throw new Error("Vault manager not initialized");return this.vaultController.startVaultPaymentById(t,e)}async deleteVaultPaymentMethod(t){if(!this.vaultController)throw new Error("Vault manager not initialized");return this.vaultController.deleteVaultedPaymentMethod(t)}async createCvvInput(t){return this.vault.createCvvInput(t)}async startVaultPayment(t,e){return this.vault.startPayment(t,e)}async refreshSession(){if(!this.headlessInstance){P.errorWithDatadog("PrimerJS: Cannot refresh session: Headless instance not available");return}try{await this.headlessInstance.refreshClientSession()}catch(t){throw P.errorWithDatadog("PrimerJS: Error refreshing client session",{error:t}),t}}getPaymentMethods(){return this.paymentMethods?this.paymentMethods:(P.warn("PrimerJS: Payment methods not available"),[])}handlePaymentStart(){this.onPaymentStart&&this.onPaymentStart()}handleVaultedMethodsUpdate(t,e){if(this.onVaultedMethodsUpdate){let r=Math.floor(Date.now()/1e3);this.onVaultedMethodsUpdate({vaultedPayments:t,cvvRecapture:e,timestamp:r})}}setCardholderName(t){let e=this.paymentMethods?.find(r=>r.type===W.PAYMENT_CARD)?.manager;if(!e){P.warn("PrimerJS: Card payment manager not available - setCardholderName cannot be called yet");return}try{e.setCardholderName(t)}catch(r){P.errorWithDatadog("PrimerJS: Error setting cardholder name",{error:r})}}};var Ua=typeof window<"u"&&typeof window.document<"u";function Wm(a){return document.querySelector(`script[src^="${a}"]`)}function Zm(a,t){let e=document.createElement("script");return e.setAttribute("src",a),e.setAttribute("async",""),e.setAttribute("crossorigin","anonymous"),t&&e.setAttribute("type","module"),e}function el(a,t=!1){if(!Ua)throw new Error("Cannot load script in server environment");let e=Wm(a)??Zm(a,t);return new Promise((r,i)=>{e.onload=()=>{r()},e.onerror=()=>{i(new Error(`Failed to load script: ${a}`))},e.parentNode||document.head.appendChild(e)})}var tl=f` :host { display: contents; } .cta-button { display: block; margin: auto; } `;var te=class extends v{constructor(){super(...arguments);this.size="large";this.showCloseButton=!1;this.darkMode=!1;this.open=!1}openDialog(){this.open=!0}closeDialog(){let e=()=>{this.open=!1,this.removeEventListener("primer:dialog-close",e)};this.addEventListener("primer:dialog-close",e),this.dialog.startExitAnimation()}connectedCallback(){super.connectedCallback(),this.darkMode&&this.classList.add("primer-dark-theme"),this.open||this.openDialog()}updated(e){super.updated(e),e.has("darkMode")&&(this.darkMode?this.classList.add("primer-dark-theme"):this.classList.remove("primer-dark-theme")),e.has("open")&&this.open&&this.onOpen&&this.onOpen(),e.has("open")&&this.open&&this.onContentRendered&&this.updateComplete.then(()=>{requestAnimationFrame(()=>{this.onContentRendered?.()})})}render(){return this.open?u`<primer-dialog class="${this.darkMode?"primer-dark-theme":""}" .open=${this.open} size=${this.size} .showCloseButton=${this.showCloseButton} @primer:dialog-close="${()=>{this.open=!1}}" ><slot></slot>${this.cta?u`<primer-button @click=${this.cta.onClick} class="cta-button">${this.cta.icon?u`<primer-icon name="${this.cta.icon}" size="sm" color="var(--primer-color-background-outlined-default)" ></primer-icon>`:y} ${this.cta.label}</primer-button>`:y}</primer-dialog>`:y}};te.styles=[T,tl],d([h({type:String})],te.prototype,"size",2),d([h({type:Boolean})],te.prototype,"showCloseButton",2),d([h({type:Boolean})],te.prototype,"darkMode",2),d([h({type:Object})],te.prototype,"onOpen",2),d([h({type:Object})],te.prototype,"onContentRendered",2),d([h({type:Object})],te.prototype,"cta",2),d([N()],te.prototype,"open",2),d([de("primer-dialog")],te.prototype,"dialog",2),te=d([b("primer-portal-dialog"),D()],te);var Va=class{constructor(){this.currentDialog=null;this.currentResolver=null}async show(t){return new Promise(e=>{let r=new te;r.size=t.size??"large",r.showCloseButton=t.showCloseButton??!1;let i=document.querySelector("primer-checkout");r.darkMode=i?.classList.contains("primer-dark-theme")??!1,r.onContentRendered=t.onContentReady,r.cta=t.cta;let n=()=>{r.remove(),this.currentDialog=null,this.currentResolver=null,e({success:!1})};r.addEventListener("primer:dialog-close",n),this.currentDialog=r,this.currentResolver=e,document.body.appendChild(r),r.appendChild(t.htmlContent)})}close(){this.currentDialog&&this.currentResolver&&(this.currentDialog.closeDialog(),this.currentResolver({success:!0}),this.currentDialog.remove(),this.currentDialog=null,this.currentResolver=null)}};var Jm=jr({"../../../localization/lit-localize/locales/ar.ts":()=>import("./chunks/ar.4ZFBST5B.js"),"../../../localization/lit-localize/locales/bg.ts":()=>import("./chunks/bg.A6DFGUKU.js"),"../../../localization/lit-localize/locales/ca.ts":()=>import("./chunks/ca.3MVWILFG.js"),"../../../localization/lit-localize/locales/cs.ts":()=>import("./chunks/cs.INYY7XZR.js"),"../../../localization/lit-localize/locales/da.ts":()=>import("./chunks/da.Y5IIDRC3.js"),"../../../localization/lit-localize/locales/de.ts":()=>import("./chunks/de.JZT46DAB.js"),"../../../localization/lit-localize/locales/el.ts":()=>import("./chunks/el.FJQOSK4N.js"),"../../../localization/lit-localize/locales/en-GB.ts":()=>import("./chunks/en-GB.TL522NMU.js"),"../../../localization/lit-localize/locales/en.ts":()=>import("./chunks/en.JFPWSECQ.js"),"../../../localization/lit-localize/locales/es-AR.ts":()=>import("./chunks/es-AR.GBZW2HPG.js"),"../../../localization/lit-localize/locales/es-MX.ts":()=>import("./chunks/es-MX.NFJ7HXSV.js"),"../../../localization/lit-localize/locales/es.ts":()=>import("./chunks/es.FX4YBDVU.js"),"../../../localization/lit-localize/locales/et-EE.ts":()=>import("./chunks/et-EE.JZD334EI.js"),"../../../localization/lit-localize/locales/fi-FI.ts":()=>import("./chunks/fi-FI.SHTM3UQK.js"),"../../../localization/lit-localize/locales/fr.ts":()=>import("./chunks/fr.MZYBSJWU.js"),"../../../localization/lit-localize/locales/he.ts":()=>import("./chunks/he.BQXGQQ4P.js"),"../../../localization/lit-localize/locales/hr.ts":()=>import("./chunks/hr.EK5WNO4N.js"),"../../../localization/lit-localize/locales/hu.ts":()=>import("./chunks/hu.N2BVXVWY.js"),"../../../localization/lit-localize/locales/id.ts":()=>import("./chunks/id.IJ37WK5P.js"),"../../../localization/lit-localize/locales/it.ts":()=>import("./chunks/it.2ZUPJDRP.js"),"../../../localization/lit-localize/locales/ja.ts":()=>import("./chunks/ja.BNLF6BZT.js"),"../../../localization/lit-localize/locales/ko.ts":()=>import("./chunks/ko.YJAZTBEF.js"),"../../../localization/lit-localize/locales/lt-LT.ts":()=>import("./chunks/lt-LT.GOVUI3KD.js"),"../../../localization/lit-localize/locales/lt.ts":()=>import("./chunks/lt.IPLRYI7A.js"),"../../../localization/lit-localize/locales/lv-LV.ts":()=>import("./chunks/lv-LV.EA76F4DL.js"),"../../../localization/lit-localize/locales/lv.ts":()=>import("./chunks/lv.I7E6LMWA.js"),"../../../localization/lit-localize/locales/ms.ts":()=>import("./chunks/ms.6I2BVK63.js"),"../../../localization/lit-localize/locales/nb.ts":()=>import("./chunks/nb.BYMLE7EQ.js"),"../../../localization/lit-localize/locales/nl.ts":()=>import("./chunks/nl.QOSIJQZE.js"),"../../../localization/lit-localize/locales/nl_NL.ts":()=>import("./chunks/nl_NL.DVZWMQJN.js"),"../../../localization/lit-localize/locales/pl.ts":()=>import("./chunks/pl.VK5CNTV3.js"),"../../../localization/lit-localize/locales/pt-BR.ts":()=>import("./chunks/pt-BR.22GYWGY5.js"),"../../../localization/lit-localize/locales/pt.ts":()=>import("./chunks/pt.L2PBSEBD.js"),"../../../localization/lit-localize/locales/ro.ts":()=>import("./chunks/ro.VFIM4IS3.js"),"../../../localization/lit-localize/locales/ru.ts":()=>import("./chunks/ru.VLLE4DKK.js"),"../../../localization/lit-localize/locales/sk.ts":()=>import("./chunks/sk.JALTDVLO.js"),"../../../localization/lit-localize/locales/sl.ts":()=>import("./chunks/sl.PQOCETM2.js"),"../../../localization/lit-localize/locales/sr-RS.ts":()=>import("./chunks/sr-RS.RGO57OCW.js"),"../../../localization/lit-localize/locales/sv.ts":()=>import("./chunks/sv.FQJP73FF.js"),"../../../localization/lit-localize/locales/th.ts":()=>import("./chunks/th.QYA26J2E.js"),"../../../localization/lit-localize/locales/tr.ts":()=>import("./chunks/tr.5ZDAANBV.js"),"../../../localization/lit-localize/locales/uk-UA.ts":()=>import("./chunks/uk-UA.FWQ7KVBB.js"),"../../../localization/lit-localize/locales/vi.ts":()=>import("./chunks/vi.GB6QZAMD.js"),"../../../localization/lit-localize/locales/zf.ts":()=>import("./chunks/zf.LNP32XVM.js"),"../../../localization/lit-localize/locales/zh-CN.ts":()=>import("./chunks/zh-CN.OEA7I6ZA.js"),"../../../localization/lit-localize/locales/zh-HK.ts":()=>import("./chunks/zh-HK.OUXNL5ZM.js"),"../../../localization/lit-localize/locales/zh-TW.ts":()=>import("./chunks/zh-TW.C5STTOCA.js")});var ir=null,In=null;async function rl(a){if(In===a&&ir)return ir;try{return ir=(await Jm(`../../../localization/lit-localize/locales/${a}.ts`)).templates,In=a,ir}catch{return a!=="en-GB"?rl("en-GB"):(ir={},In=a,ir)}}async function al(a){let t=await rl(a);return(e,r)=>t[e]??r}var Ha=class a extends Error{constructor(t,e){super(e.message),this.name="PrimerClientError",this.code=t,this.diagnosticsId=e.diagnosticsId||null,this.data=e.data,this.isFromDeveloper=e.isFromDeveloper||!1}static fromErrorCode(t,e){return new a(t,e)}};function il(a,t,e){return a.isDisconnected?!1:(a.host.sdkContextController.contextProvider.value.sdkState.paymentFailure!==null&&Q({eventName:"PAYMENT_REATTEMPTED",paymentMethod:t}),a.host.sdkContextController.setSdkState({isProcessing:!0,paymentFailure:null,primerJsError:null}),a.host.primerEventsController.dispatchPaymentStart(t,e))}function nl(a,t,e){if(!a.isDisconnected&&(P.info("Payment completed:",t),a.host.sdkContextController.setSdkState({isProcessing:!1,isSuccessful:!0}),a.host.primerEventsController.dispatchPaymentSuccess(t,e),Q({eventName:"PAYMENT_SUCCESS",paymentId:t?.id,paymentMethod:e}),a.primerJS?.onPaymentSuccess)){let r=Math.floor(Date.now()/1e3);a.primerJS.onPaymentSuccess({payment:Xt(t),paymentMethodType:e,timestamp:r})}}function ol(a,t,e,r){if(a.isDisconnected)return;(s=>typeof s=="object"&&s!==null&&"response"in s&&typeof s.response=="object"&&s.response!==null&&"status"in s.response&&typeof s.response.status=="number")(t)&&t.response.status>=500?P.errorWithDatadog("Payment failed with server error",{error:t}):P.error("Payment failed:",t);let o=t instanceof Ha?{code:t.code||"UNKNOWN_ERROR",message:t.message||"Unknown error occurred",diagnosticsId:t.diagnosticsId,data:t.data}:(()=>{let s=t,l=s instanceof Error&&"code"in s&&typeof s.code=="string"?s.code:"UNKNOWN_ERROR",c=s instanceof Error?s.message:"Unknown error occurred";return{code:l,message:c,data:{error:t}}})();if(a.host.sdkContextController.setSdkState({isProcessing:!1,paymentFailure:o}),a.host.primerEventsController.dispatchPaymentFailure({code:o.code,message:o.message,diagnosticsId:"diagnosticsId"in o?o.diagnosticsId??void 0:void 0,data:o.data},e,r),Q({eventName:"PAYMENT_FAILURE",paymentId:r?.id,paymentMethod:e}),a.primerJS?.onPaymentFailure){let s=Math.floor(Date.now()/1e3);a.primerJS.onPaymentFailure({error:{code:o.code,message:o.message,diagnosticsId:"diagnosticsId"in o?o.diagnosticsId??void 0:void 0,data:o.data},payment:r?Xt(r):void 0,paymentMethodType:e,timestamp:s})}}var sl="1.4.0",Ya=class{constructor(t){this.currentSdkInstance=null;this.primerJS=null;this.loadingTimeout=null;this.isDisconnected=!1;(this.host=t).addController(this),this.isDisconnected=!1,new $(t,{args:()=>[this.host.clientToken,this.host.options],task:this.initializeHeadless()})}get primerJSInstance(){return this.primerJS}hostConnected(){this.isDisconnected=!1,this.host.sdkContextController.setSdkState({isLoading:!0}),this.setupLoadingTimeout()}hostDisconnected(){if(this.isDisconnected=!0,this.host.sdkContextController.contextProvider?.value?.analytics){let e=this.host.sdkContextController.contextProvider.value.sdkState;(e.isProcessing||e.isLoading||this.currentSdkInstance)&&Q({eventName:"PAYMENT_FLOW_EXITED"})}this.cleanupResources()}normalizeOptionsForLegacySdk(t){if(t.sdkCore!==!1)return{...t,sdkCore:!0};let e={...t};if(e.card?.cardholderName){let r={...e.card.cardholderName};r.visible===!1&&(r.required=!1),e.card={...e.card,cardholderName:r}}return e}setupLoadingTimeout(){this.clearLoadingTimeout(),this.loadingTimeout=setTimeout(()=>{this.host.sdkContextController.contextProvider.value.sdkState.isLoading&&(P.warn("Loading timeout reached, resetting SDK state"),Q({eventName:"PAYMENT_FLOW_EXITED",eventType:"timeout"}),this.cleanupResources(),this.host.sdkContextController.setSdkState({isLoading:!1}))},1e4)}clearLoadingTimeout(){this.loadingTimeout!==null&&(clearTimeout(this.loadingTimeout),this.loadingTimeout=null)}cleanupResources(){if(this.clearLoadingTimeout(),this.currentSdkInstance)try{this.host.sdkContextController.resetSdkState(),this.currentSdkInstance.teardown?.(),P.info("SDK instance cleaned up")}catch(t){P.errorWithDatadog("Error cleaning up SDK instance",{error:t})}Es(),P.setClientToken(void 0),P.setSdkOptions(void 0),this.currentSdkInstance=null,this.primerJS=null}async _loadV2Sdk(t=Xs){let e=window;if(e.Primer&&typeof e.Primer.preloadPrimer=="function"){P.info("SDK already loaded, skipping load script"),await e.Primer.preloadPrimer();return}await el(t),await e.Primer?.preloadPrimer()}initializeHeadless(){return async([t,e])=>{if(this.isDisconnected)return P.warn("Component disconnected, aborting SDK initialization"),Y;if(!t||!e)return Y;this.cleanupResources();let r;try{let i;if(e.sdkCore!==!1){let m=new Va,g=rr(e.locale||La()),A=await al(g);i={createHeadless:(w,L)=>ds(w,{...L,dialogProvider:m,translate:A,sdkVersion:sl,locale:g})}}else await this._loadV2Sdk(),i=window.Primer;this.primerJS=new Fa(null),this.primerJS.setVaultController(this.host.vaultManagerController);let n=this.normalizeOptionsForLegacySdk(e);P.setClientToken(t),P.setSdkOptions(n);let o=[],s=await i.createHeadless(t,{...n,onAvailablePaymentMethodsLoad:m=>{this.isDisconnected||(P.info("Configuration payment methods:",m),o=m)},onCheckoutComplete:({payment:m})=>{let g=m?.paymentMethodData?.paymentMethodType;nl({isDisconnected:this.isDisconnected,host:this.host,primerJS:this.primerJS},m,g)},onCheckoutFail:(m,g)=>{let A=g.payment?.paymentMethodData?.paymentMethodType;ol({isDisconnected:this.isDisconnected,host:this.host,primerJS:this.primerJS},m,A,g.payment)},onBeforePaymentCreate:(m,g)=>{if(!m.paymentMethodType){P.error("Payment creation started without payment method type"),g?.abortPaymentCreation();return}if(!(il({isDisconnected:this.isDisconnected,host:this.host,primerJS:this.primerJS},m.paymentMethodType,g)||this.isDisconnected)){if(this.primerJS?.onPaymentPrepare){this.primerJS.onPaymentPrepare({paymentMethodType:m.paymentMethodType},g);return}g?.continuePaymentCreation()}},onPaymentMethodAction:(m,g)=>{this.isDisconnected||m==="PAYMENT_METHOD_UNSELECTED"&&(this.host.primerEventsController.dispatchPaymentCancel(g),this.host.sdkContextController.setSdkState({isProcessing:!1}))},onPaymentCreationStart:()=>{this.isDisconnected||this.primerJS&&this.primerJS.handlePaymentStart()}});if(this.currentSdkInstance=s,this.primerJS&&Object.defineProperty(this.primerJS,"headlessInstance",{value:s,writable:!1}),await s.start(),this.isDisconnected)return this.cleanupResources(),Y;let l=s.getSDKUtilities();r=s.getAnalyticsUtils?.(),r&&(As({environment:r.environment,checkoutSessionId:r.checkoutSessionId,clientSessionId:r.clientSessionId||"",primerAccountId:r.primerAccountId||"",sdkVersion:sl,clientSessionToken:r.clientSessionToken,userAgent:typeof navigator<"u"?navigator.userAgent:""}),r.configurationFetchStartTime&&De.setSdkInitStartTime(r.configurationFetchStartTime),Q({eventName:"SDK_INIT_START"})),this.host.vaultManagerController.initializeVaultManager(s.createVaultManager.bind(s),{vaultEnabled:e.vault?.enabled,captureVaultedCardCvv:!!l.getPaymentMethodConfiguration("PAYMENT_CARD")?.options?.captureVaultedCardCvv,showEmptyState:e.vault?.showEmptyState,headless:e.vault?.headless??!1});let c=(await Promise.all(o.map(async m=>{let g=await this.createManager(m,s);return g?{...m,manager:g}:null}))).filter(m=>!!m),p={clientOptions:e,analytics:r,headlessUtils:l,configuration:e.sdkCore!==!1?s.getConfiguration?.():void 0,paymentMethods:c};return this.host.sdkContextController.setContext(p),this.primerJS&&(this.host.primerEventsController.dispatchCheckoutInitialized(this.primerJS),this.primerJS.setPaymentMethods(c)),this.host.primerEventsController.dispatchPaymentMethods(c),P.info("Initialized payment methods:",c),this.host.sdkContextController.setSdkState({isLoading:!1}),Q({eventName:"SDK_INIT_END"}),s}catch(i){throw i instanceof Error&&(P.errorWithDatadog("SDK initialization error",{error:i,status:"error"}),this.host.sdkContextController.setSdkState({primerJsError:i})),this.cleanupResources(),i}}}async createManager(t,e){try{if(t.managerType==="KLARNA")return await e.createPaymentMethodManager("KLARNA",{onPaymentMethodCategoriesChange:r=>{this.isDisconnected||this.host.sdkContextController.setKlarnaCategories({categories:r,isLoading:!1})}});if(t.managerType==="ADYEN_KLARNA"){let r=await e.createPaymentMethodManager("ADYEN_KLARNA",{onPaymentOptionsChange:i=>{this.isDisconnected||this.host.sdkContextController.setAdyenKlarnaOptions({options:i,isLoading:!1})}});if(r&&"getPaymentOptions"in r){let i=r.getPaymentOptions();i.length>0&&this.host.sdkContextController.setAdyenKlarnaOptions({options:i,isLoading:!1})}return r}return t.managerType==="CARD"?await e.createPaymentMethodManager("PAYMENT_CARD",{onBinDataAvailable:r=>{this.isDisconnected||this.host.primerEventsController.dispatchBinDataAvailable(r)},onCardNetworksChange:r=>{if(this.isDisconnected)return;let{detectedCardNetworks:i,selectableCardNetworks:n}=r;this.updateCardNetworksState({detectedCardNetwork:i.preferred??i.items[0],selectableCardNetworks:n?.items??[],isLoading:!1})},onBinDataLoadingChange:r=>{this.isDisconnected||(r?this.updateCardNetworksState({detectedCardNetwork:null,selectableCardNetworks:[],isLoading:!0}):this.host.sdkContextController.setCardNetworksLoadingFalse(),this.host.primerEventsController.dispatchBinDataLoadingChange(r))}}):await e.createPaymentMethodManager(t.type)}catch(r){P.errorWithDatadog(`Failed to initialize manager for ${t.type}`,{error:r})}}updateCardNetworksState(t){this.host.primerEventsController.dispatchCardNetworkChange(t),this.host.sdkContextController.setCardNetworks(t)}};var qm=jr({"../../localization/lit-localize/locales/ar.ts":()=>import("./chunks/ar.4ZFBST5B.js"),"../../localization/lit-localize/locales/bg.ts":()=>import("./chunks/bg.A6DFGUKU.js"),"../../localization/lit-localize/locales/ca.ts":()=>import("./chunks/ca.3MVWILFG.js"),"../../localization/lit-localize/locales/cs.ts":()=>import("./chunks/cs.INYY7XZR.js"),"../../localization/lit-localize/locales/da.ts":()=>import("./chunks/da.Y5IIDRC3.js"),"../../localization/lit-localize/locales/de.ts":()=>import("./chunks/de.JZT46DAB.js"),"../../localization/lit-localize/locales/el.ts":()=>import("./chunks/el.FJQOSK4N.js"),"../../localization/lit-localize/locales/en-GB.ts":()=>import("./chunks/en-GB.TL522NMU.js"),"../../localization/lit-localize/locales/en.ts":()=>import("./chunks/en.JFPWSECQ.js"),"../../localization/lit-localize/locales/es-AR.ts":()=>import("./chunks/es-AR.GBZW2HPG.js"),"../../localization/lit-localize/locales/es-MX.ts":()=>import("./chunks/es-MX.NFJ7HXSV.js"),"../../localization/lit-localize/locales/es.ts":()=>import("./chunks/es.FX4YBDVU.js"),"../../localization/lit-localize/locales/et-EE.ts":()=>import("./chunks/et-EE.JZD334EI.js"),"../../localization/lit-localize/locales/fi-FI.ts":()=>import("./chunks/fi-FI.SHTM3UQK.js"),"../../localization/lit-localize/locales/fr.ts":()=>import("./chunks/fr.MZYBSJWU.js"),"../../localization/lit-localize/locales/he.ts":()=>import("./chunks/he.BQXGQQ4P.js"),"../../localization/lit-localize/locales/hr.ts":()=>import("./chunks/hr.EK5WNO4N.js"),"../../localization/lit-localize/locales/hu.ts":()=>import("./chunks/hu.N2BVXVWY.js"),"../../localization/lit-localize/locales/id.ts":()=>import("./chunks/id.IJ37WK5P.js"),"../../localization/lit-localize/locales/it.ts":()=>import("./chunks/it.2ZUPJDRP.js"),"../../localization/lit-localize/locales/ja.ts":()=>import("./chunks/ja.BNLF6BZT.js"),"../../localization/lit-localize/locales/ko.ts":()=>import("./chunks/ko.YJAZTBEF.js"),"../../localization/lit-localize/locales/lt-LT.ts":()=>import("./chunks/lt-LT.GOVUI3KD.js"),"../../localization/lit-localize/locales/lt.ts":()=>import("./chunks/lt.IPLRYI7A.js"),"../../localization/lit-localize/locales/lv-LV.ts":()=>import("./chunks/lv-LV.EA76F4DL.js"),"../../localization/lit-localize/locales/lv.ts":()=>import("./chunks/lv.I7E6LMWA.js"),"../../localization/lit-localize/locales/ms.ts":()=>import("./chunks/ms.6I2BVK63.js"),"../../localization/lit-localize/locales/nb.ts":()=>import("./chunks/nb.BYMLE7EQ.js"),"../../localization/lit-localize/locales/nl.ts":()=>import("./chunks/nl.QOSIJQZE.js"),"../../localization/lit-localize/locales/nl_NL.ts":()=>import("./chunks/nl_NL.DVZWMQJN.js"),"../../localization/lit-localize/locales/pl.ts":()=>import("./chunks/pl.VK5CNTV3.js"),"../../localization/lit-localize/locales/pt-BR.ts":()=>import("./chunks/pt-BR.22GYWGY5.js"),"../../localization/lit-localize/locales/pt.ts":()=>import("./chunks/pt.L2PBSEBD.js"),"../../localization/lit-localize/locales/ro.ts":()=>import("./chunks/ro.VFIM4IS3.js"),"../../localization/lit-localize/locales/ru.ts":()=>import("./chunks/ru.VLLE4DKK.js"),"../../localization/lit-localize/locales/sk.ts":()=>import("./chunks/sk.JALTDVLO.js"),"../../localization/lit-localize/locales/sl.ts":()=>import("./chunks/sl.PQOCETM2.js"),"../../localization/lit-localize/locales/sr-RS.ts":()=>import("./chunks/sr-RS.RGO57OCW.js"),"../../localization/lit-localize/locales/sv.ts":()=>import("./chunks/sv.FQJP73FF.js"),"../../localization/lit-localize/locales/th.ts":()=>import("./chunks/th.QYA26J2E.js"),"../../localization/lit-localize/locales/tr.ts":()=>import("./chunks/tr.5ZDAANBV.js"),"../../localization/lit-localize/locales/uk-UA.ts":()=>import("./chunks/uk-UA.FWQ7KVBB.js"),"../../localization/lit-localize/locales/vi.ts":()=>import("./chunks/vi.GB6QZAMD.js"),"../../localization/lit-localize/locales/zf.ts":()=>import("./chunks/zf.LNP32XVM.js"),"../../localization/lit-localize/locales/zh-CN.ts":()=>import("./chunks/zh-CN.OEA7I6ZA.js"),"../../localization/lit-localize/locales/zh-HK.ts":()=>import("./chunks/zh-HK.OUXNL5ZM.js"),"../../localization/lit-localize/locales/zh-TW.ts":()=>import("./chunks/zh-TW.C5STTOCA.js")});fn(a=>qm(`../../localization/lit-localize/locales/${a}.ts`));var Qm={LOADER_DISABLED:"loader-disabled",CUSTOM_STYLES:"custom-styles",CLIENT_TOKEN:"client-token",JS_INIT:"js-initialized"},ye=class extends v{constructor(){super();this.customStyles="";this.clientToken="";this.options={};this.disableLoader=!1;this._jsInitialized=!1;this.previousLoadingState=!0;this.hasAssignedContent=!1;this._loadingTimeoutId=null;this._eventListenerController=null;this._classObserver=null;this.locale=rr(La());this.onSlotChange=e=>{let i=e.target.assignedNodes({flatten:!0});this.hasAssignedContent=i.length>0,this.requestUpdate()};this.sdkContextController=new ya(this),this.primerEventsController=new er(this),this.styleProcessingController=new fa(this),this.vaultManagerController=new Mr(this),this.headlessSdkController=new Ya(this)}set jsInitialized(e){this.requestUpdate(),this._jsInitialized=e}get jsInitialized(){return this._jsInitialized}get primerJS(){return this.headlessSdkController?.primerJSInstance??void 0}connectedCallback(){super.connectedCallback(),this.sdkContextController.setEventsController(this.primerEventsController),this._eventListenerController=new AbortController,document.addEventListener("primer:card-submit",this.handleExternalCardSubmit.bind(this),{signal:this._eventListenerController.signal}),document.addEventListener("primer:vault-submit",this.handleExternalVaultSubmit.bind(this),{signal:this._eventListenerController.signal}),document.addEventListener("primer:show-other-payments-toggle",this.handleExternalShowOtherPaymentsToggle.bind(this),{signal:this._eventListenerController.signal}),this._classObserver=new MutationObserver(()=>{this.requestUpdate()}),this._classObserver.observe(this,{attributes:!0,attributeFilter:["class"]})}attributeChangedCallback(e,r,i){e===Qm.CUSTOM_STYLES?this.styleProcessingController.processCustomStyles(i):super.attributeChangedCallback(e,r,i)}disconnectedCallback(){this._loadingTimeoutId&&(window.clearTimeout(this._loadingTimeoutId),this._loadingTimeoutId=null),this.sdkContextController.contextProvider.value.sdkState?.isLoading&&this.sdkContextController.setSdkState({isLoading:!1}),this._eventListenerController&&(this._eventListenerController.abort(),this._eventListenerController=null),this._classObserver&&(this._classObserver.disconnect(),this._classObserver=null),super.disconnectedCallback()}willUpdate(e){e.has("options")&&(this.options?.locale&&(Cn(this.options?.locale)?this.locale=rr(this.options?.locale):P.warn("\u{1F30E}\u2757 Unsupported locale provided:",this.options?.locale,"- Falling back to system locale")),vn(this.locale))}updated(){let e=getComputedStyle(this);this.sdkContextController.setComputedStyles(e),this.checkLoadingStateChange()}handleExternalCardSubmit(e){this._eventListenerController?.signal.aborted||e.target!==this&&this.primerEventsController.dispatchEvent("primer:card-submit",e.detail)}handleExternalVaultSubmit(e){this._eventListenerController?.signal.aborted||e.target!==this&&this.primerEventsController.dispatchEvent("primer:vault-submit",e.detail)}handleExternalShowOtherPaymentsToggle(e){this._eventListenerController?.signal.aborted||e.target!==this&&this.primerEventsController.dispatchEvent("primer:show-other-payments-toggle",e.detail)}checkLoadingStateChange(){let e=this.sdkContextController.contextProvider.value.sdkState.isLoading||!1;if(this.previousLoadingState&&!e){this.jsInitialized=!0,Q({eventName:"CHECKOUT_FLOW_STARTED"});let r=De.getSdkInitStartTime(),i=r?Date.now()-r:void 0;Qn(i)}this.previousLoadingState=e,e&&!this._loadingTimeoutId?this._loadingTimeoutId=window.setTimeout(()=>{this.sdkContextController.contextProvider.value.sdkState.isLoading&&(P.warn("Loading timeout in component, forcing completion"),this.sdkContextController.setSdkState({isLoading:!1}),this.jsInitialized=!0),this._loadingTimeoutId=null},1e4):!e&&this._loadingTimeoutId&&(window.clearTimeout(this._loadingTimeoutId),this._loadingTimeoutId=null)}render(){let e=this.sdkContextController.contextProvider.value.sdkState,r=e.isLoading,i=e.primerJsError,n=!r&&!i;return u` ${k(r,()=>y)} ${k(i,()=>u`<primer-checkout-error></primer-checkout-error>`)} ${k(n,()=>u`<slot name="main" @slotchange=${this.onSlotChange}></slot>${k(this.hasAssignedContent,()=>y,()=>u`<primer-main></primer-main>`)} `,()=>y)} `}addEventListener(e,r,i){super.addEventListener(e,r,i)}removeEventListener(e,r,i){super.removeEventListener(e,r,i)}};ye.styles=[T,Qs],d([h({type:String,attribute:"custom-styles"})],ye.prototype,"customStyles",2),d([h({type:String,attribute:"client-token"})],ye.prototype,"clientToken",2),d([h({type:Object,attribute:!1,hasChanged:(e,r)=>!ft(e,r)})],ye.prototype,"options",2),d([h({type:Boolean,attribute:"loader-disabled"})],ye.prototype,"disableLoader",2),d([h({type:Boolean,reflect:!0,attribute:"js-initialized"})],ye.prototype,"_jsInitialized",2),d([de("slot")],ye.prototype,"defaultSlot",2),d([N()],ye.prototype,"previousLoadingState",2),ye=d([D(),b("primer-checkout")],ye);function Xm(a){return document.querySelector(`#${a}`)}function eh(a,t){let e=document.createElement("style");return e.textContent=a,e.id=t,e}function Gr(a,t,e=!0){if(!Ua||Xm(t))return;let i=eh(a,t);e&&document.head.firstChild?document.head.insertBefore(i,document.head.firstChild):document.head.appendChild(i)}var ll=`
|
|
180
|
+
\f\r"'\`<>=]|("|')|))|$)`,"g"),Hs=/'/g,Ys=/"/g,js=/^(?:script|style|textarea|title)$/i,Nn=a=>(t,...e)=>({_$litType$:a,strings:t,values:e}),u=Nn(1),ge=Nn(2),wv=Nn(3),Xe=Symbol.for("lit-noChange"),y=Symbol.for("lit-nothing"),$s=new WeakMap,Gt=Kt.createTreeWalker(Kt,129);function Ws(a,t){if(!Tn(a)||!a.hasOwnProperty("raw"))throw Error("invalid template strings array");return Fs!==void 0?Fs.createHTML(t):t}var Zs=(a,t)=>{let e=a.length-1,r=[],i,n=t===2?"<svg>":t===3?"<math>":"",o=wr;for(let s=0;s<e;s++){let l=a[s],c,p,m=-1,g=0;for(;g<l.length&&(o.lastIndex=g,p=o.exec(l),p!==null);)g=o.lastIndex,o===wr?p[1]==="!--"?o=Us:p[1]!==void 0?o=Vs:p[2]!==void 0?(js.test(p[2])&&(i=RegExp("</"+p[2],"g")),o=Bt):p[3]!==void 0&&(o=Bt):o===Bt?p[0]===">"?(o=i??wr,m=-1):p[1]===void 0?m=-2:(m=o.lastIndex-p[2].length,c=p[1],o=p[3]===void 0?Bt:p[3]==='"'?Ys:Hs):o===Ys||o===Hs?o=Bt:o===Us||o===Vs?o=wr:(o=Bt,i=void 0);let A=o===Bt&&a[s+1].startsWith("/>")?" ":"";n+=o===wr?l+Hm:m>=0?(r.push(c),l.slice(0,m)+Mn+l.slice(m)+Qe+A):l+Qe+(m===-2?s:A)}return[Ws(a,n+(a[e]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),r]},Dr=class a{constructor({strings:t,_$litType$:e},r){let i;this.parts=[];let n=0,o=0,s=t.length-1,l=this.parts,[c,p]=Zs(t,e);if(this.el=a.createElement(c,r),Gt.currentNode=this.el.content,e===2||e===3){let m=this.el.content.firstChild;m.replaceWith(...m.childNodes)}for(;(i=Gt.nextNode())!==null&&l.length<s;){if(i.nodeType===1){if(i.hasAttributes())for(let m of i.getAttributeNames())if(m.endsWith(Mn)){let g=p[o++],A=i.getAttribute(m).split(Qe),M=/([.?@])?(.*)/.exec(g);l.push({type:1,index:n,name:M[2],strings:A,ctor:M[1]==="."?Da:M[1]==="?"?Ba:M[1]==="@"?Ga:Ut}),i.removeAttribute(m)}else m.startsWith(Qe)&&(l.push({type:6,index:n}),i.removeAttribute(m));if(js.test(i.tagName)){let m=i.textContent.split(Qe),g=m.length-1;if(g>0){i.textContent=_a?_a.emptyScript:"";for(let A=0;A<g;A++)i.append(m[A],_r()),Gt.nextNode(),l.push({type:2,index:++n});i.append(m[g],_r())}}}else if(i.nodeType===8)if(i.data===Pn)l.push({type:2,index:n});else{let m=-1;for(;(m=i.data.indexOf(Qe,m+1))!==-1;)l.push({type:7,index:n}),m+=Qe.length-1}n++}}static createElement(t,e){let r=Kt.createElement("template");return r.innerHTML=t,r}};function Ft(a,t,e=a,r){if(t===Xe)return t;let i=r!==void 0?e._$Co?.[r]:e._$Cl,n=Or(t)?void 0:t._$litDirective$;return i?.constructor!==n&&(i?._$AO?.(!1),n===void 0?i=void 0:(i=new n(a),i._$AT(a,e,r)),r!==void 0?(e._$Co??(e._$Co=[]))[r]=i:e._$Cl=i),i!==void 0&&(t=Ft(a,i._$AS(a,t.values),i,r)),t}var Oa=class{constructor(t,e){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=e}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){let{el:{content:e},parts:r}=this._$AD,i=(t?.creationScope??Kt).importNode(e,!0);Gt.currentNode=i;let n=Gt.nextNode(),o=0,s=0,l=r[0];for(;l!==void 0;){if(o===l.index){let c;l.type===2?c=new ar(n,n.nextSibling,this,t):l.type===1?c=new l.ctor(n,l.name,l.strings,this,t):l.type===6&&(c=new Ka(n,this,t)),this._$AV.push(c),l=r[++s]}o!==l?.index&&(n=Gt.nextNode(),o++)}return Gt.currentNode=Kt,i}p(t){let e=0;for(let r of this._$AV)r!==void 0&&(r.strings!==void 0?(r._$AI(t,r,e),e+=r.strings.length-2):r._$AI(t[e])),e++}},ar=class a{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,e,r,i){this.type=2,this._$AH=y,this._$AN=void 0,this._$AA=t,this._$AB=e,this._$AM=r,this.options=i,this._$Cv=i?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode,e=this._$AM;return e!==void 0&&t?.nodeType===11&&(t=e.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,e=this){t=Ft(this,t,e),Or(t)?t===y||t==null||t===""?(this._$AH!==y&&this._$AR(),this._$AH=y):t!==this._$AH&&t!==Xe&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):zs(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==y&&Or(this._$AH)?this._$AA.nextSibling.data=t:this.T(Kt.createTextNode(t)),this._$AH=t}$(t){let{values:e,_$litType$:r}=t,i=typeof r=="number"?this._$AC(t):(r.el===void 0&&(r.el=Dr.createElement(Ws(r.h,r.h[0]),this.options)),r);if(this._$AH?._$AD===i)this._$AH.p(e);else{let n=new Oa(i,this),o=n.u(this.options);n.p(e),this.T(o),this._$AH=n}}_$AC(t){let e=$s.get(t.strings);return e===void 0&&$s.set(t.strings,e=new Dr(t)),e}k(t){Tn(this._$AH)||(this._$AH=[],this._$AR());let e=this._$AH,r,i=0;for(let n of t)i===e.length?e.push(r=new a(this.O(_r()),this.O(_r()),this,this.options)):r=e[i],r._$AI(n),i++;i<e.length&&(this._$AR(r&&r._$AB.nextSibling,i),e.length=i)}_$AR(t=this._$AA.nextSibling,e){for(this._$AP?.(!1,!0,e);t&&t!==this._$AB;){let r=t.nextSibling;t.remove(),t=r}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}},Ut=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,e,r,i,n){this.type=1,this._$AH=y,this._$AN=void 0,this.element=t,this.name=e,this._$AM=i,this.options=n,r.length>2||r[0]!==""||r[1]!==""?(this._$AH=Array(r.length-1).fill(new String),this.strings=r):this._$AH=y}_$AI(t,e=this,r,i){let n=this.strings,o=!1;if(n===void 0)t=Ft(this,t,e,0),o=!Or(t)||t!==this._$AH&&t!==Xe,o&&(this._$AH=t);else{let s=t,l,c;for(t=n[0],l=0;l<n.length-1;l++)c=Ft(this,s[r+l],e,l),c===Xe&&(c=this._$AH[l]),o||(o=!Or(c)||c!==this._$AH[l]),c===y?t=y:t!==y&&(t+=(c??"")+n[l+1]),this._$AH[l]=c}o&&!i&&this.j(t)}j(t){t===y?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},Da=class extends Ut{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===y?void 0:t}},Ba=class extends Ut{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==y)}},Ga=class extends Ut{constructor(t,e,r,i,n){super(t,e,r,i,n),this.type=5}_$AI(t,e=this){if((t=Ft(this,t,e,0)??y)===Xe)return;let r=this._$AH,i=t===y&&r!==y||t.capture!==r.capture||t.once!==r.once||t.passive!==r.passive,n=t!==y&&(r===y||i);i&&this.element.removeEventListener(this.name,this,r),n&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,t):this._$AH.handleEvent(t)}},Ka=class{constructor(t,e,r){this.element=t,this.type=6,this._$AN=void 0,this._$AM=e,this.options=r}get _$AU(){return this._$AM._$AU}_$AI(t){Ft(this,t)}},Js={M:Mn,P:Qe,A:Pn,C:1,L:Zs,R:Oa,D:zs,V:Ft,I:ar,H:Ut,N:Ba,U:Ga,B:Da,F:Ka},Ym=xr.litHtmlPolyfillSupport;Ym?.(Dr,ar),(xr.litHtmlVersions??(xr.litHtmlVersions=[])).push("3.3.0");var qs=(a,t,e)=>{let r=e?.renderBefore??t,i=r._$litPart$;if(i===void 0){let n=e?.renderBefore??null;r._$litPart$=i=new ar(t.insertBefore(_r(),n),n,void 0,e??{})}return i._$AI(a),i};var Br=globalThis,v=class extends qe{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){var e;let t=super.createRenderRoot();return(e=this.renderOptions).renderBefore??(e.renderBefore=t.firstChild),t}update(t){let e=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=qs(e,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Xe}};v._$litElement$=!0,v.finalized=!0,Br.litElementHydrateSupport?.({LitElement:v});var $m=Br.litElementPolyfillSupport;$m?.({LitElement:v});(Br.litElementVersions??(Br.litElementVersions=[])).push("4.2.0");var b=a=>(t,e)=>{e!==void 0?e.addInitializer((()=>{customElements.define(a,t)})):customElements.define(a,t)};var zm={attribute:!0,type:String,converter:Rr,reflect:!1,hasChanged:xa},jm=(a=zm,t,e)=>{let{kind:r,metadata:i}=e,n=globalThis.litPropertyMetadata.get(i);if(n===void 0&&globalThis.litPropertyMetadata.set(i,n=new Map),r==="setter"&&((a=Object.create(a)).wrapped=!0),n.set(e.name,a),r==="accessor"){let{name:o}=e;return{set(s){let l=t.get.call(this);t.set.call(this,s),this.requestUpdate(o,l,a)},init(s){return s!==void 0&&this.C(o,void 0,a,s),s}}}if(r==="setter"){let{name:o}=e;return function(s){let l=this[o];t.call(this,s),this.requestUpdate(o,l,a)}}throw Error("Unsupported decorator location: "+r)};function h(a){return(t,e)=>typeof e=="object"?jm(a,t,e):((r,i,n)=>{let o=i.hasOwnProperty(n);return i.constructor.createProperty(n,r),o?Object.getOwnPropertyDescriptor(i,n):void 0})(a,t,e)}function N(a){return h({...a,state:!0,attribute:!1})}var Vt=(a,t,e)=>(e.configurable=!0,e.enumerable=!0,Reflect.decorate&&typeof t!="object"&&Object.defineProperty(a,t,e),e);function de(a,t){return(e,r,i)=>{let n=o=>o.renderRoot?.querySelector(a)??null;if(t){let{get:o,set:s}=typeof r=="object"?e:i??(()=>{let l=Symbol();return{get(){return this[l]},set(c){this[l]=c}}})();return Vt(e,r,{get(){let l=o.call(this);return l===void 0&&(l=n(this),(l!==null||this.hasUpdated)&&s.call(this,l)),l}})}return Vt(e,r,{get(){return n(this)}})}}function k(a,t,e){return a?t(a):e?.(a)}var T=f` * { box-sizing: border-box; } `,Qs=f` :host { display: block; isolation: isolate; position: relative; width: 100%; //Keep the CSS loader in the same position - check css-loader-inline.ts min-height: 64px; } `;var Xs="https://sdk.primer.io/web/v2-latest/Primer.min.js";var et="20px";var tt={WORLDPAY_IDEAL:"WORLDPAY_IDEAL",AUTOMATED_CLEARING_HOUSE:"AUTOMATED_CLEARING_HOUSE",ADYEN_KLARNA:"ADYEN_KLARNA",ADYEN_BANCONTACT_CARD:"ADYEN_BANCONTACT_CARD",PAY_NL_KAARTDIRECT:"PAY_NL_KAARTDIRECT",ADYEN_EPS:"ADYEN_EPS",ADYEN_BANCONTACT_PAYCONIQ:"ADYEN_BANCONTACT_PAYCONIQ",OMISE_PROMPTPAY:"OMISE_PROMPTPAY",OMISE_TRUEMONEY:"OMISE_TRUEMONEY",ADYEN_MULTIBANCO:"ADYEN_MULTIBANCO",PACYPAY_WECHAT:"PACYPAY_WECHAT",PACYPAY_ALIPAY:"PACYPAY_ALIPAY",ADYEN_MBWAY:"ADYEN_MBWAY",XENDIT_DANA:"XENDIT_DANA",XENDIT_SHOPEEPAY:"XENDIT_SHOPEEPAY",ADYEN_PAYSHOP:"ADYEN_PAYSHOP",ADYEN_PAYTRAIL:"ADYEN_PAYTRAIL",CLEARPAY:"CLEARPAY",RAPYD_FAST:"RAPYD_FAST",RAPYD_PROMPTPAY:"RAPYD_PROMPTPAY",RAPYD_GCASH:"RAPYD_GCASH",RAPYD_POLI:"RAPYD_POLI",RAPYD_GRABPAY:"RAPYD_GRABPAY",PRIMER_PAYPAL:"PRIMER_PAYPAL",TWOC2P:"TWOC2P",NETS:"NETS",STRIPE_ACH:"STRIPE_ACH",STRIPE_GIROPAY:"STRIPE_GIROPAY",MOLLIE_GIROPAY:"MOLLIE_GIROPAY",MOLLIE_EPS:"MOLLIE_EPS",PAY_NL_EPS:"PAY_NL_EPS",PAY_NL_P24:"PAY_NL_P24",MOLLIE_P24:"MOLLIE_P24",MOLLIE_SOFORT:"MOLLIE_SOFORT",COINBASE:"COINBASE",OPENNODE:"OPENNODE",MOLLIE_GIFT_CARD:"MOLLIE_GIFTCARD",XFERS_PAYNOW:"XFERS_PAYNOW",CARD:"PAYMENT_CARD",APPLE_PAY:"APPLE_PAY",GOOGLE_PAY:"GOOGLE_PAY",PAYPAL:"PAYPAL_ORDER",PAYPAL_VAULTED:"PAYPAL_BILLING_AGREEMENT",GO_CARDLESS:"GOCARDLESS",PAY_NL_IDEAL:"PAY_NL_IDEAL",PAY_NL_SOFORT_BANKING:"PAY_NL_SOFORT_BANKING",PAY_NL_BANCONTACT:"PAY_NL_BANCONTACT",PAY_NL_PAYPAL:"PAY_NL_PAYPAL",PAY_NL_CREDIT_TRANSFER:"PAY_NL_CREDIT_TRANSFER",PAY_NL_DIRECT_DEBIT:"PAY_NL_DIRECT_DEBIT",PAY_NL_GIROPAY:"PAY_NL_GIROPAY",PAY_NL_PAYCONIQ:"PAY_NL_PAYCONIQ",PAY_NL_RIVERTY:"PAY_NL_RIVERTY",HOOLAH:"HOOLAH",ADYEN_BLIK:"ADYEN_BLIK",ADYEN_VIPPS:"ADYEN_VIPPS",ADYEN_GIROPAY:"ADYEN_GIROPAY",ADYEN_SOFORT:"ADYEN_SOFORT",ADYEN_IDEAL:"ADYEN_IDEAL",ADYEN_TRUSTLY:"ADYEN_TRUSTLY",ADYEN_ALIPAY:"ADYEN_ALIPAY",ADYEN_TWINT:"ADYEN_TWINT",ADYEN_MOBILEPAY:"ADYEN_MOBILEPAY",MOLLIE_BANCONTACT:"MOLLIE_BANCONTACT",MOLLIE_IDEAL:"MOLLIE_IDEAL",BUCKAROO_GIROPAY:"BUCKAROO_GIROPAY",BUCKAROO_EPS:"BUCKAROO_EPS",BUCKAROO_SOFORT:"BUCKAROO_SOFORT",BUCKAROO_BANCONTACT:"BUCKAROO_BANCONTACT",BUCKAROO_IDEAL:"BUCKAROO_IDEAL",ATOME:"ATOME",KLARNA_CUSTOMER_TOKEN:"KLARNA_CUSTOMER_TOKEN",DLOCAL_PIX:"DLOCAL_PIX",ALMA:"ALMA",ADYEN_CASHAPP:"ADYEN_CASHAPP",ADYEN_AFFIRM:"ADYEN_AFFIRM"},W={WORLDPAY_IDEAL:"WORLDPAY_IDEAL",STRIPE_ACH:"STRIPE_ACH",STRIPE_IDEAL:"STRIPE_IDEAL",ADYEN_KLARNA:"ADYEN_KLARNA",ADYEN_BANCONTACT_CARD:"ADYEN_BANCONTACT_CARD",PAY_NL_KAARTDIRECT:"PAY_NL_KAARTDIRECT",ADYEN_EPS:"ADYEN_EPS",ADYEN_BANCONTACT_PAYCONIQ:"ADYEN_BANCONTACT_PAYCONIQ",OMISE_PROMPTPAY:"OMISE_PROMPTPAY",OMISE_TRUEMONEY:"OMISE_TRUEMONEY",ADYEN_MULTIBANCO:"ADYEN_MULTIBANCO",PACYPAY_WECHAT:"PACYPAY_WECHAT",PACYPAY_ALIPAY:"PACYPAY_ALIPAY",ADYEN_MBWAY:"ADYEN_MBWAY",XENDIT_DANA:"XENDIT_DANA",XENDIT_SHOPEEPAY:"XENDIT_SHOPEEPAY",ADYEN_PAYSHOP:"ADYEN_PAYSHOP",ADYEN_PAYTRAIL:"ADYEN_PAYTRAIL",CLEARPAY:"CLEARPAY",RAPYD_FAST:"RAPYD_FAST",RAPYD_PROMPTPAY:"RAPYD_PROMPTPAY",RAPYD_GCASH:"RAPYD_GCASH",RAPYD_POLI:"RAPYD_POLI",RAPYD_GRABPAY:"RAPYD_GRABPAY",PRIMER_PAYPAL:"PRIMER_PAYPAL",TWOC2P:"TWOC2P",NETS:"NETS",STRIPE_GIROPAY:"STRIPE_GIROPAY",MOLLIE_GIROPAY:"MOLLIE_GIROPAY",MOLLIE_EPS:"MOLLIE_EPS",PAY_NL_EPS:"PAY_NL_EPS",PAY_NL_P24:"PAY_NL_P24",MOLLIE_P24:"MOLLIE_P24",MOLLIE_SOFORT:"MOLLIE_SOFORT",COINBASE:"COINBASE",OPENNODE:"OPENNODE",MOLLIE_GIFT_CARD:"MOLLIE_GIFTCARD",XFERS_PAYNOW:"XFERS_PAYNOW",PAYMENT_CARD:"PAYMENT_CARD",APPLE_PAY:"APPLE_PAY",GOOGLE_PAY:"GOOGLE_PAY",PAYPAL:"PAYPAL",GO_CARDLESS:"GOCARDLESS",KLARNA:"KLARNA",PAY_NL_IDEAL:"PAY_NL_IDEAL",PAY_NL_SOFORT_BANKING:"PAY_NL_SOFORT_BANKING",PAY_NL_BANCONTACT:"PAY_NL_BANCONTACT",PAY_NL_PAYPAL:"PAY_NL_PAYPAL",PAY_NL_CREDIT_TRANSFER:"PAY_NL_CREDIT_TRANSFER",PAY_NL_DIRECT_DEBIT:"PAY_NL_DIRECT_DEBIT",PAY_NL_GIROPAY:"PAY_NL_GIROPAY",PAY_NL_PAYCONIQ:"PAY_NL_PAYCONIQ",PAY_NL_RIVERTY:"PAY_NL_RIVERTY",HOOLAH:"HOOLAH",ADYEN_BLIK:"ADYEN_BLIK",ADYEN_MOBILEPAY:"ADYEN_MOBILEPAY",ADYEN_VIPPS:"ADYEN_VIPPS",ADYEN_GIROPAY:"ADYEN_GIROPAY",ADYEN_SOFORT:"ADYEN_SOFORT",ADYEN_IDEAL:"ADYEN_IDEAL",ADYEN_TRUSTLY:"ADYEN_TRUSTLY",ADYEN_ALIPAY:"ADYEN_ALIPAY",ADYEN_TWINT:"ADYEN_TWINT",ADYEN_BANK_TRANSFER:"ADYEN_BANK_TRANSFER",MOLLIE_BANCONTACT:"MOLLIE_BANCONTACT",MOLLIE_IDEAL:"MOLLIE_IDEAL",BUCKAROO_GIROPAY:"BUCKAROO_GIROPAY",BUCKAROO_EPS:"BUCKAROO_EPS",BUCKAROO_SOFORT:"BUCKAROO_SOFORT",BUCKAROO_BANCONTACT:"BUCKAROO_BANCONTACT",BUCKAROO_IDEAL:"BUCKAROO_IDEAL",ATOME:"ATOME",DLOCAL_PIX:"DLOCAL_PIX",ALMA:"ALMA",ADYEN_CASHAPP:"ADYEN_CASHAPP",ADYEN_AFFIRM:"ADYEN_AFFIRM"};var Fa=class{constructor(t){this.paymentMethods=null;this.vaultController=null;this.headlessInstance=t,this.vault={createCvvInput:e=>this.createCvvInputInternal(e),startPayment:(e,r)=>this.startVaultPaymentInternal(e,r),delete:e=>this.deleteVaultPaymentMethod(e)}}setPaymentMethods(t){this.paymentMethods=t}setVaultController(t){this.vaultController=t}async createCvvInputInternal(t){return this.vaultController?this.vaultController.createCvvInput(t):(P.warn("PrimerJS: Vault not available - createCvvInput cannot be called"),null)}async startVaultPaymentInternal(t,e){if(!this.vaultController)throw new Error("Vault manager not initialized");return this.vaultController.startVaultPaymentById(t,e)}async deleteVaultPaymentMethod(t){if(!this.vaultController)throw new Error("Vault manager not initialized");return this.vaultController.deleteVaultedPaymentMethod(t)}async createCvvInput(t){return this.vault.createCvvInput(t)}async startVaultPayment(t,e){return this.vault.startPayment(t,e)}async refreshSession(){if(!this.headlessInstance){P.errorWithDatadog("PrimerJS: Cannot refresh session: Headless instance not available");return}try{await this.headlessInstance.refreshClientSession()}catch(t){throw P.errorWithDatadog("PrimerJS: Error refreshing client session",{error:t}),t}}getPaymentMethods(){return this.paymentMethods?this.paymentMethods:(P.warn("PrimerJS: Payment methods not available"),[])}handlePaymentStart(){this.onPaymentStart&&this.onPaymentStart()}handleVaultedMethodsUpdate(t,e){if(this.onVaultedMethodsUpdate){let r=Math.floor(Date.now()/1e3);this.onVaultedMethodsUpdate({vaultedPayments:t,cvvRecapture:e,timestamp:r})}}setCardholderName(t){let e=this.paymentMethods?.find(r=>r.type===W.PAYMENT_CARD)?.manager;if(!e){P.warn("PrimerJS: Card payment manager not available - setCardholderName cannot be called yet");return}try{e.setCardholderName(t)}catch(r){P.errorWithDatadog("PrimerJS: Error setting cardholder name",{error:r})}}};var Ua=typeof window<"u"&&typeof window.document<"u";function Wm(a){return document.querySelector(`script[src^="${a}"]`)}function Zm(a,t){let e=document.createElement("script");return e.setAttribute("src",a),e.setAttribute("async",""),e.setAttribute("crossorigin","anonymous"),t&&e.setAttribute("type","module"),e}function el(a,t=!1){if(!Ua)throw new Error("Cannot load script in server environment");let e=Wm(a)??Zm(a,t);return new Promise((r,i)=>{e.onload=()=>{r()},e.onerror=()=>{i(new Error(`Failed to load script: ${a}`))},e.parentNode||document.head.appendChild(e)})}var tl=f` :host { display: contents; } .cta-button { display: block; margin: auto; } `;var te=class extends v{constructor(){super(...arguments);this.size="large";this.showCloseButton=!1;this.darkMode=!1;this.open=!1}openDialog(){this.open=!0}closeDialog(){let e=()=>{this.open=!1,this.removeEventListener("primer:dialog-close",e)};this.addEventListener("primer:dialog-close",e),this.dialog.startExitAnimation()}connectedCallback(){super.connectedCallback(),this.darkMode&&this.classList.add("primer-dark-theme"),this.open||this.openDialog()}updated(e){super.updated(e),e.has("darkMode")&&(this.darkMode?this.classList.add("primer-dark-theme"):this.classList.remove("primer-dark-theme")),e.has("open")&&this.open&&this.onOpen&&this.onOpen(),e.has("open")&&this.open&&this.onContentRendered&&this.updateComplete.then(()=>{requestAnimationFrame(()=>{this.onContentRendered?.()})})}render(){return this.open?u`<primer-dialog class="${this.darkMode?"primer-dark-theme":""}" .open=${this.open} size=${this.size} .showCloseButton=${this.showCloseButton} @primer:dialog-close="${()=>{this.open=!1}}" ><slot></slot>${this.cta?u`<primer-button @click=${this.cta.onClick} class="cta-button">${this.cta.icon?u`<primer-icon name="${this.cta.icon}" size="sm" color="var(--primer-color-background-outlined-default)" ></primer-icon>`:y} ${this.cta.label}</primer-button>`:y}</primer-dialog>`:y}};te.styles=[T,tl],d([h({type:String})],te.prototype,"size",2),d([h({type:Boolean})],te.prototype,"showCloseButton",2),d([h({type:Boolean})],te.prototype,"darkMode",2),d([h({type:Object})],te.prototype,"onOpen",2),d([h({type:Object})],te.prototype,"onContentRendered",2),d([h({type:Object})],te.prototype,"cta",2),d([N()],te.prototype,"open",2),d([de("primer-dialog")],te.prototype,"dialog",2),te=d([b("primer-portal-dialog"),D()],te);var Va=class{constructor(){this.currentDialog=null;this.currentResolver=null}async show(t){return new Promise(e=>{let r=new te;r.size=t.size??"large",r.showCloseButton=t.showCloseButton??!1;let i=document.querySelector("primer-checkout");r.darkMode=i?.classList.contains("primer-dark-theme")??!1,r.onContentRendered=t.onContentReady,r.cta=t.cta;let n=()=>{r.remove(),this.currentDialog=null,this.currentResolver=null,e({success:!1})};r.addEventListener("primer:dialog-close",n),this.currentDialog=r,this.currentResolver=e,document.body.appendChild(r),r.appendChild(t.htmlContent)})}close(){this.currentDialog&&this.currentResolver&&(this.currentDialog.closeDialog(),this.currentResolver({success:!0}),this.currentDialog.remove(),this.currentDialog=null,this.currentResolver=null)}};var Jm=jr({"../../../localization/lit-localize/locales/ar.ts":()=>import("./chunks/ar.4ZFBST5B.js"),"../../../localization/lit-localize/locales/bg.ts":()=>import("./chunks/bg.A6DFGUKU.js"),"../../../localization/lit-localize/locales/ca.ts":()=>import("./chunks/ca.3MVWILFG.js"),"../../../localization/lit-localize/locales/cs.ts":()=>import("./chunks/cs.INYY7XZR.js"),"../../../localization/lit-localize/locales/da.ts":()=>import("./chunks/da.Y5IIDRC3.js"),"../../../localization/lit-localize/locales/de.ts":()=>import("./chunks/de.JZT46DAB.js"),"../../../localization/lit-localize/locales/el.ts":()=>import("./chunks/el.FJQOSK4N.js"),"../../../localization/lit-localize/locales/en-GB.ts":()=>import("./chunks/en-GB.TL522NMU.js"),"../../../localization/lit-localize/locales/en.ts":()=>import("./chunks/en.JFPWSECQ.js"),"../../../localization/lit-localize/locales/es-AR.ts":()=>import("./chunks/es-AR.GBZW2HPG.js"),"../../../localization/lit-localize/locales/es-MX.ts":()=>import("./chunks/es-MX.NFJ7HXSV.js"),"../../../localization/lit-localize/locales/es.ts":()=>import("./chunks/es.FX4YBDVU.js"),"../../../localization/lit-localize/locales/et-EE.ts":()=>import("./chunks/et-EE.JZD334EI.js"),"../../../localization/lit-localize/locales/fi-FI.ts":()=>import("./chunks/fi-FI.SHTM3UQK.js"),"../../../localization/lit-localize/locales/fr.ts":()=>import("./chunks/fr.MZYBSJWU.js"),"../../../localization/lit-localize/locales/he.ts":()=>import("./chunks/he.BQXGQQ4P.js"),"../../../localization/lit-localize/locales/hr.ts":()=>import("./chunks/hr.EK5WNO4N.js"),"../../../localization/lit-localize/locales/hu.ts":()=>import("./chunks/hu.N2BVXVWY.js"),"../../../localization/lit-localize/locales/id.ts":()=>import("./chunks/id.IJ37WK5P.js"),"../../../localization/lit-localize/locales/it.ts":()=>import("./chunks/it.2ZUPJDRP.js"),"../../../localization/lit-localize/locales/ja.ts":()=>import("./chunks/ja.BNLF6BZT.js"),"../../../localization/lit-localize/locales/ko.ts":()=>import("./chunks/ko.YJAZTBEF.js"),"../../../localization/lit-localize/locales/lt-LT.ts":()=>import("./chunks/lt-LT.GOVUI3KD.js"),"../../../localization/lit-localize/locales/lt.ts":()=>import("./chunks/lt.IPLRYI7A.js"),"../../../localization/lit-localize/locales/lv-LV.ts":()=>import("./chunks/lv-LV.EA76F4DL.js"),"../../../localization/lit-localize/locales/lv.ts":()=>import("./chunks/lv.I7E6LMWA.js"),"../../../localization/lit-localize/locales/ms.ts":()=>import("./chunks/ms.6I2BVK63.js"),"../../../localization/lit-localize/locales/nb.ts":()=>import("./chunks/nb.BYMLE7EQ.js"),"../../../localization/lit-localize/locales/nl.ts":()=>import("./chunks/nl.QOSIJQZE.js"),"../../../localization/lit-localize/locales/nl_NL.ts":()=>import("./chunks/nl_NL.DVZWMQJN.js"),"../../../localization/lit-localize/locales/pl.ts":()=>import("./chunks/pl.VK5CNTV3.js"),"../../../localization/lit-localize/locales/pt-BR.ts":()=>import("./chunks/pt-BR.22GYWGY5.js"),"../../../localization/lit-localize/locales/pt.ts":()=>import("./chunks/pt.L2PBSEBD.js"),"../../../localization/lit-localize/locales/ro.ts":()=>import("./chunks/ro.VFIM4IS3.js"),"../../../localization/lit-localize/locales/ru.ts":()=>import("./chunks/ru.VLLE4DKK.js"),"../../../localization/lit-localize/locales/sk.ts":()=>import("./chunks/sk.JALTDVLO.js"),"../../../localization/lit-localize/locales/sl.ts":()=>import("./chunks/sl.PQOCETM2.js"),"../../../localization/lit-localize/locales/sr-RS.ts":()=>import("./chunks/sr-RS.RGO57OCW.js"),"../../../localization/lit-localize/locales/sv.ts":()=>import("./chunks/sv.FQJP73FF.js"),"../../../localization/lit-localize/locales/th.ts":()=>import("./chunks/th.QYA26J2E.js"),"../../../localization/lit-localize/locales/tr.ts":()=>import("./chunks/tr.5ZDAANBV.js"),"../../../localization/lit-localize/locales/uk-UA.ts":()=>import("./chunks/uk-UA.FWQ7KVBB.js"),"../../../localization/lit-localize/locales/vi.ts":()=>import("./chunks/vi.GB6QZAMD.js"),"../../../localization/lit-localize/locales/zf.ts":()=>import("./chunks/zf.LNP32XVM.js"),"../../../localization/lit-localize/locales/zh-CN.ts":()=>import("./chunks/zh-CN.OEA7I6ZA.js"),"../../../localization/lit-localize/locales/zh-HK.ts":()=>import("./chunks/zh-HK.OUXNL5ZM.js"),"../../../localization/lit-localize/locales/zh-TW.ts":()=>import("./chunks/zh-TW.C5STTOCA.js")});var ir=null,In=null;async function rl(a){if(In===a&&ir)return ir;try{return ir=(await Jm(`../../../localization/lit-localize/locales/${a}.ts`)).templates,In=a,ir}catch{return a!=="en-GB"?rl("en-GB"):(ir={},In=a,ir)}}async function al(a){let t=await rl(a);return(e,r)=>t[e]??r}var Ha=class a extends Error{constructor(t,e){super(e.message),this.name="PrimerClientError",this.code=t,this.diagnosticsId=e.diagnosticsId||null,this.data=e.data,this.isFromDeveloper=e.isFromDeveloper||!1}static fromErrorCode(t,e){return new a(t,e)}};function il(a,t,e){return a.isDisconnected?!1:(a.host.sdkContextController.contextProvider.value.sdkState.paymentFailure!==null&&Q({eventName:"PAYMENT_REATTEMPTED",paymentMethod:t}),a.host.sdkContextController.setSdkState({isProcessing:!0,paymentFailure:null,primerJsError:null}),a.host.primerEventsController.dispatchPaymentStart(t,e))}function nl(a,t,e){if(!a.isDisconnected&&(P.info("Payment completed:",t),a.host.sdkContextController.setSdkState({isProcessing:!1,isSuccessful:!0}),a.host.primerEventsController.dispatchPaymentSuccess(t,e),Q({eventName:"PAYMENT_SUCCESS",paymentId:t?.id,paymentMethod:e}),a.primerJS?.onPaymentSuccess)){let r=Math.floor(Date.now()/1e3);a.primerJS.onPaymentSuccess({payment:Xt(t),paymentMethodType:e,timestamp:r})}}function ol(a,t,e,r){if(a.isDisconnected)return;(s=>typeof s=="object"&&s!==null&&"response"in s&&typeof s.response=="object"&&s.response!==null&&"status"in s.response&&typeof s.response.status=="number")(t)&&t.response.status>=500?P.errorWithDatadog("Payment failed with server error",{error:t}):P.error("Payment failed:",t);let o=t instanceof Ha?{code:t.code||"UNKNOWN_ERROR",message:t.message||"Unknown error occurred",diagnosticsId:t.diagnosticsId,data:t.data}:(()=>{let s=t,l=s instanceof Error&&"code"in s&&typeof s.code=="string"?s.code:"UNKNOWN_ERROR",c=s instanceof Error?s.message:"Unknown error occurred";return{code:l,message:c,data:{error:t}}})();if(a.host.sdkContextController.setSdkState({isProcessing:!1,paymentFailure:o}),a.host.primerEventsController.dispatchPaymentFailure({code:o.code,message:o.message,diagnosticsId:"diagnosticsId"in o?o.diagnosticsId??void 0:void 0,data:o.data},e,r),Q({eventName:"PAYMENT_FAILURE",paymentId:r?.id,paymentMethod:e}),a.primerJS?.onPaymentFailure){let s=Math.floor(Date.now()/1e3);a.primerJS.onPaymentFailure({error:{code:o.code,message:o.message,diagnosticsId:"diagnosticsId"in o?o.diagnosticsId??void 0:void 0,data:o.data},payment:r?Xt(r):void 0,paymentMethodType:e,timestamp:s})}}var sl="1.4.1",Ya=class{constructor(t){this.currentSdkInstance=null;this.primerJS=null;this.loadingTimeout=null;this.isDisconnected=!1;(this.host=t).addController(this),this.isDisconnected=!1,new $(t,{args:()=>[this.host.clientToken,this.host.options],task:this.initializeHeadless()})}get primerJSInstance(){return this.primerJS}hostConnected(){this.isDisconnected=!1,this.host.sdkContextController.setSdkState({isLoading:!0}),this.setupLoadingTimeout()}hostDisconnected(){if(this.isDisconnected=!0,this.host.sdkContextController.contextProvider?.value?.analytics){let e=this.host.sdkContextController.contextProvider.value.sdkState;(e.isProcessing||e.isLoading||this.currentSdkInstance)&&Q({eventName:"PAYMENT_FLOW_EXITED"})}this.cleanupResources()}normalizeOptionsForLegacySdk(t){if(t.sdkCore!==!1)return{...t,sdkCore:!0};let e={...t};if(e.card?.cardholderName){let r={...e.card.cardholderName};r.visible===!1&&(r.required=!1),e.card={...e.card,cardholderName:r}}return e}setupLoadingTimeout(){this.clearLoadingTimeout(),this.loadingTimeout=setTimeout(()=>{this.host.sdkContextController.contextProvider.value.sdkState.isLoading&&(P.warn("Loading timeout reached, resetting SDK state"),Q({eventName:"PAYMENT_FLOW_EXITED",eventType:"timeout"}),this.cleanupResources(),this.host.sdkContextController.setSdkState({isLoading:!1}))},1e4)}clearLoadingTimeout(){this.loadingTimeout!==null&&(clearTimeout(this.loadingTimeout),this.loadingTimeout=null)}cleanupResources(){if(this.clearLoadingTimeout(),this.currentSdkInstance)try{this.host.sdkContextController.resetSdkState(),this.currentSdkInstance.teardown?.(),P.info("SDK instance cleaned up")}catch(t){P.errorWithDatadog("Error cleaning up SDK instance",{error:t})}Es(),P.setClientToken(void 0),P.setSdkOptions(void 0),this.currentSdkInstance=null,this.primerJS=null}async _loadV2Sdk(t=Xs){let e=window;if(e.Primer&&typeof e.Primer.preloadPrimer=="function"){P.info("SDK already loaded, skipping load script"),await e.Primer.preloadPrimer();return}await el(t),await e.Primer?.preloadPrimer()}initializeHeadless(){return async([t,e])=>{if(this.isDisconnected)return P.warn("Component disconnected, aborting SDK initialization"),Y;if(!t||!e)return Y;this.cleanupResources();let r;try{let i;if(e.sdkCore!==!1){let m=new Va,g=rr(e.locale||La()),A=await al(g);i={createHeadless:(w,L)=>ds(w,{...L,dialogProvider:m,translate:A,sdkVersion:sl,locale:g})}}else await this._loadV2Sdk(),i=window.Primer;this.primerJS=new Fa(null),this.primerJS.setVaultController(this.host.vaultManagerController);let n=this.normalizeOptionsForLegacySdk(e);P.setClientToken(t),P.setSdkOptions(n);let o=[],s=await i.createHeadless(t,{...n,onAvailablePaymentMethodsLoad:m=>{this.isDisconnected||(P.info("Configuration payment methods:",m),o=m)},onCheckoutComplete:({payment:m})=>{let g=m?.paymentMethodData?.paymentMethodType;nl({isDisconnected:this.isDisconnected,host:this.host,primerJS:this.primerJS},m,g)},onCheckoutFail:(m,g)=>{let A=g.payment?.paymentMethodData?.paymentMethodType;ol({isDisconnected:this.isDisconnected,host:this.host,primerJS:this.primerJS},m,A,g.payment)},onBeforePaymentCreate:(m,g)=>{if(!m.paymentMethodType){P.error("Payment creation started without payment method type"),g?.abortPaymentCreation();return}if(!(il({isDisconnected:this.isDisconnected,host:this.host,primerJS:this.primerJS},m.paymentMethodType,g)||this.isDisconnected)){if(this.primerJS?.onPaymentPrepare){this.primerJS.onPaymentPrepare({paymentMethodType:m.paymentMethodType},g);return}g?.continuePaymentCreation()}},onPaymentMethodAction:(m,g)=>{this.isDisconnected||m==="PAYMENT_METHOD_UNSELECTED"&&(this.host.primerEventsController.dispatchPaymentCancel(g),this.host.sdkContextController.setSdkState({isProcessing:!1}))},onPaymentCreationStart:()=>{this.isDisconnected||this.primerJS&&this.primerJS.handlePaymentStart()}});if(this.currentSdkInstance=s,this.primerJS&&Object.defineProperty(this.primerJS,"headlessInstance",{value:s,writable:!1}),await s.start(),this.isDisconnected)return this.cleanupResources(),Y;let l=s.getSDKUtilities();r=s.getAnalyticsUtils?.(),r&&(As({environment:r.environment,checkoutSessionId:r.checkoutSessionId,clientSessionId:r.clientSessionId||"",primerAccountId:r.primerAccountId||"",sdkVersion:sl,clientSessionToken:r.clientSessionToken,userAgent:typeof navigator<"u"?navigator.userAgent:""}),r.configurationFetchStartTime&&De.setSdkInitStartTime(r.configurationFetchStartTime),Q({eventName:"SDK_INIT_START"})),this.host.vaultManagerController.initializeVaultManager(s.createVaultManager.bind(s),{vaultEnabled:e.vault?.enabled,captureVaultedCardCvv:!!l.getPaymentMethodConfiguration("PAYMENT_CARD")?.options?.captureVaultedCardCvv,showEmptyState:e.vault?.showEmptyState,headless:e.vault?.headless??!1});let c=(await Promise.all(o.map(async m=>{let g=await this.createManager(m,s);return g?{...m,manager:g}:null}))).filter(m=>!!m),p={clientOptions:e,analytics:r,headlessUtils:l,configuration:e.sdkCore!==!1?s.getConfiguration?.():void 0,paymentMethods:c};return this.host.sdkContextController.setContext(p),this.primerJS&&(this.host.primerEventsController.dispatchCheckoutInitialized(this.primerJS),this.primerJS.setPaymentMethods(c)),this.host.primerEventsController.dispatchPaymentMethods(c),P.info("Initialized payment methods:",c),this.host.sdkContextController.setSdkState({isLoading:!1}),Q({eventName:"SDK_INIT_END"}),s}catch(i){throw i instanceof Error&&(P.errorWithDatadog("SDK initialization error",{error:i,status:"error"}),this.host.sdkContextController.setSdkState({primerJsError:i})),this.cleanupResources(),i}}}async createManager(t,e){try{if(t.managerType==="KLARNA")return await e.createPaymentMethodManager("KLARNA",{onPaymentMethodCategoriesChange:r=>{this.isDisconnected||this.host.sdkContextController.setKlarnaCategories({categories:r,isLoading:!1})}});if(t.managerType==="ADYEN_KLARNA"){let r=await e.createPaymentMethodManager("ADYEN_KLARNA",{onPaymentOptionsChange:i=>{this.isDisconnected||this.host.sdkContextController.setAdyenKlarnaOptions({options:i,isLoading:!1})}});if(r&&"getPaymentOptions"in r){let i=r.getPaymentOptions();i.length>0&&this.host.sdkContextController.setAdyenKlarnaOptions({options:i,isLoading:!1})}return r}return t.managerType==="CARD"?await e.createPaymentMethodManager("PAYMENT_CARD",{onBinDataAvailable:r=>{this.isDisconnected||this.host.primerEventsController.dispatchBinDataAvailable(r)},onCardNetworksChange:r=>{if(this.isDisconnected)return;let{detectedCardNetworks:i,selectableCardNetworks:n}=r;this.updateCardNetworksState({detectedCardNetwork:i.preferred??i.items[0],selectableCardNetworks:n?.items??[],isLoading:!1})},onBinDataLoadingChange:r=>{this.isDisconnected||(r?this.updateCardNetworksState({detectedCardNetwork:null,selectableCardNetworks:[],isLoading:!0}):this.host.sdkContextController.setCardNetworksLoadingFalse(),this.host.primerEventsController.dispatchBinDataLoadingChange(r))}}):await e.createPaymentMethodManager(t.type)}catch(r){P.errorWithDatadog(`Failed to initialize manager for ${t.type}`,{error:r})}}updateCardNetworksState(t){this.host.primerEventsController.dispatchCardNetworkChange(t),this.host.sdkContextController.setCardNetworks(t)}};var qm=jr({"../../localization/lit-localize/locales/ar.ts":()=>import("./chunks/ar.4ZFBST5B.js"),"../../localization/lit-localize/locales/bg.ts":()=>import("./chunks/bg.A6DFGUKU.js"),"../../localization/lit-localize/locales/ca.ts":()=>import("./chunks/ca.3MVWILFG.js"),"../../localization/lit-localize/locales/cs.ts":()=>import("./chunks/cs.INYY7XZR.js"),"../../localization/lit-localize/locales/da.ts":()=>import("./chunks/da.Y5IIDRC3.js"),"../../localization/lit-localize/locales/de.ts":()=>import("./chunks/de.JZT46DAB.js"),"../../localization/lit-localize/locales/el.ts":()=>import("./chunks/el.FJQOSK4N.js"),"../../localization/lit-localize/locales/en-GB.ts":()=>import("./chunks/en-GB.TL522NMU.js"),"../../localization/lit-localize/locales/en.ts":()=>import("./chunks/en.JFPWSECQ.js"),"../../localization/lit-localize/locales/es-AR.ts":()=>import("./chunks/es-AR.GBZW2HPG.js"),"../../localization/lit-localize/locales/es-MX.ts":()=>import("./chunks/es-MX.NFJ7HXSV.js"),"../../localization/lit-localize/locales/es.ts":()=>import("./chunks/es.FX4YBDVU.js"),"../../localization/lit-localize/locales/et-EE.ts":()=>import("./chunks/et-EE.JZD334EI.js"),"../../localization/lit-localize/locales/fi-FI.ts":()=>import("./chunks/fi-FI.SHTM3UQK.js"),"../../localization/lit-localize/locales/fr.ts":()=>import("./chunks/fr.MZYBSJWU.js"),"../../localization/lit-localize/locales/he.ts":()=>import("./chunks/he.BQXGQQ4P.js"),"../../localization/lit-localize/locales/hr.ts":()=>import("./chunks/hr.EK5WNO4N.js"),"../../localization/lit-localize/locales/hu.ts":()=>import("./chunks/hu.N2BVXVWY.js"),"../../localization/lit-localize/locales/id.ts":()=>import("./chunks/id.IJ37WK5P.js"),"../../localization/lit-localize/locales/it.ts":()=>import("./chunks/it.2ZUPJDRP.js"),"../../localization/lit-localize/locales/ja.ts":()=>import("./chunks/ja.BNLF6BZT.js"),"../../localization/lit-localize/locales/ko.ts":()=>import("./chunks/ko.YJAZTBEF.js"),"../../localization/lit-localize/locales/lt-LT.ts":()=>import("./chunks/lt-LT.GOVUI3KD.js"),"../../localization/lit-localize/locales/lt.ts":()=>import("./chunks/lt.IPLRYI7A.js"),"../../localization/lit-localize/locales/lv-LV.ts":()=>import("./chunks/lv-LV.EA76F4DL.js"),"../../localization/lit-localize/locales/lv.ts":()=>import("./chunks/lv.I7E6LMWA.js"),"../../localization/lit-localize/locales/ms.ts":()=>import("./chunks/ms.6I2BVK63.js"),"../../localization/lit-localize/locales/nb.ts":()=>import("./chunks/nb.BYMLE7EQ.js"),"../../localization/lit-localize/locales/nl.ts":()=>import("./chunks/nl.QOSIJQZE.js"),"../../localization/lit-localize/locales/nl_NL.ts":()=>import("./chunks/nl_NL.DVZWMQJN.js"),"../../localization/lit-localize/locales/pl.ts":()=>import("./chunks/pl.VK5CNTV3.js"),"../../localization/lit-localize/locales/pt-BR.ts":()=>import("./chunks/pt-BR.22GYWGY5.js"),"../../localization/lit-localize/locales/pt.ts":()=>import("./chunks/pt.L2PBSEBD.js"),"../../localization/lit-localize/locales/ro.ts":()=>import("./chunks/ro.VFIM4IS3.js"),"../../localization/lit-localize/locales/ru.ts":()=>import("./chunks/ru.VLLE4DKK.js"),"../../localization/lit-localize/locales/sk.ts":()=>import("./chunks/sk.JALTDVLO.js"),"../../localization/lit-localize/locales/sl.ts":()=>import("./chunks/sl.PQOCETM2.js"),"../../localization/lit-localize/locales/sr-RS.ts":()=>import("./chunks/sr-RS.RGO57OCW.js"),"../../localization/lit-localize/locales/sv.ts":()=>import("./chunks/sv.FQJP73FF.js"),"../../localization/lit-localize/locales/th.ts":()=>import("./chunks/th.QYA26J2E.js"),"../../localization/lit-localize/locales/tr.ts":()=>import("./chunks/tr.5ZDAANBV.js"),"../../localization/lit-localize/locales/uk-UA.ts":()=>import("./chunks/uk-UA.FWQ7KVBB.js"),"../../localization/lit-localize/locales/vi.ts":()=>import("./chunks/vi.GB6QZAMD.js"),"../../localization/lit-localize/locales/zf.ts":()=>import("./chunks/zf.LNP32XVM.js"),"../../localization/lit-localize/locales/zh-CN.ts":()=>import("./chunks/zh-CN.OEA7I6ZA.js"),"../../localization/lit-localize/locales/zh-HK.ts":()=>import("./chunks/zh-HK.OUXNL5ZM.js"),"../../localization/lit-localize/locales/zh-TW.ts":()=>import("./chunks/zh-TW.C5STTOCA.js")});fn(a=>qm(`../../localization/lit-localize/locales/${a}.ts`));var Qm={LOADER_DISABLED:"loader-disabled",CUSTOM_STYLES:"custom-styles",CLIENT_TOKEN:"client-token",JS_INIT:"js-initialized"},ye=class extends v{constructor(){super();this.customStyles="";this.clientToken="";this.options={};this.disableLoader=!1;this._jsInitialized=!1;this.previousLoadingState=!0;this.hasAssignedContent=!1;this._loadingTimeoutId=null;this._eventListenerController=null;this._classObserver=null;this.locale=rr(La());this.onSlotChange=e=>{let i=e.target.assignedNodes({flatten:!0});this.hasAssignedContent=i.length>0,this.requestUpdate()};this.sdkContextController=new ya(this),this.primerEventsController=new er(this),this.styleProcessingController=new fa(this),this.vaultManagerController=new Mr(this),this.headlessSdkController=new Ya(this)}set jsInitialized(e){this.requestUpdate(),this._jsInitialized=e}get jsInitialized(){return this._jsInitialized}get primerJS(){return this.headlessSdkController?.primerJSInstance??void 0}connectedCallback(){super.connectedCallback(),this.sdkContextController.setEventsController(this.primerEventsController),this._eventListenerController=new AbortController,document.addEventListener("primer:card-submit",this.handleExternalCardSubmit.bind(this),{signal:this._eventListenerController.signal}),document.addEventListener("primer:vault-submit",this.handleExternalVaultSubmit.bind(this),{signal:this._eventListenerController.signal}),document.addEventListener("primer:show-other-payments-toggle",this.handleExternalShowOtherPaymentsToggle.bind(this),{signal:this._eventListenerController.signal}),this._classObserver=new MutationObserver(()=>{this.requestUpdate()}),this._classObserver.observe(this,{attributes:!0,attributeFilter:["class"]})}attributeChangedCallback(e,r,i){e===Qm.CUSTOM_STYLES?this.styleProcessingController.processCustomStyles(i):super.attributeChangedCallback(e,r,i)}disconnectedCallback(){this._loadingTimeoutId&&(window.clearTimeout(this._loadingTimeoutId),this._loadingTimeoutId=null),this.sdkContextController.contextProvider.value.sdkState?.isLoading&&this.sdkContextController.setSdkState({isLoading:!1}),this._eventListenerController&&(this._eventListenerController.abort(),this._eventListenerController=null),this._classObserver&&(this._classObserver.disconnect(),this._classObserver=null),super.disconnectedCallback()}willUpdate(e){e.has("options")&&(this.options?.locale&&(Cn(this.options?.locale)?this.locale=rr(this.options?.locale):P.warn("\u{1F30E}\u2757 Unsupported locale provided:",this.options?.locale,"- Falling back to system locale")),vn(this.locale))}updated(){let e=getComputedStyle(this);this.sdkContextController.setComputedStyles(e),this.checkLoadingStateChange()}handleExternalCardSubmit(e){this._eventListenerController?.signal.aborted||e.target!==this&&this.primerEventsController.dispatchEvent("primer:card-submit",e.detail)}handleExternalVaultSubmit(e){this._eventListenerController?.signal.aborted||e.target!==this&&this.primerEventsController.dispatchEvent("primer:vault-submit",e.detail)}handleExternalShowOtherPaymentsToggle(e){this._eventListenerController?.signal.aborted||e.target!==this&&this.primerEventsController.dispatchEvent("primer:show-other-payments-toggle",e.detail)}checkLoadingStateChange(){let e=this.sdkContextController.contextProvider.value.sdkState.isLoading||!1;if(this.previousLoadingState&&!e){this.jsInitialized=!0,Q({eventName:"CHECKOUT_FLOW_STARTED"});let r=De.getSdkInitStartTime(),i=r?Date.now()-r:void 0;Qn(i)}this.previousLoadingState=e,e&&!this._loadingTimeoutId?this._loadingTimeoutId=window.setTimeout(()=>{this.sdkContextController.contextProvider.value.sdkState.isLoading&&(P.warn("Loading timeout in component, forcing completion"),this.sdkContextController.setSdkState({isLoading:!1}),this.jsInitialized=!0),this._loadingTimeoutId=null},1e4):!e&&this._loadingTimeoutId&&(window.clearTimeout(this._loadingTimeoutId),this._loadingTimeoutId=null)}render(){let e=this.sdkContextController.contextProvider.value.sdkState,r=e.isLoading,i=e.primerJsError,n=!r&&!i;return u` ${k(r,()=>y)} ${k(i,()=>u`<primer-checkout-error></primer-checkout-error>`)} ${k(n,()=>u`<slot name="main" @slotchange=${this.onSlotChange}></slot>${k(this.hasAssignedContent,()=>y,()=>u`<primer-main></primer-main>`)} `,()=>y)} `}addEventListener(e,r,i){super.addEventListener(e,r,i)}removeEventListener(e,r,i){super.removeEventListener(e,r,i)}};ye.styles=[T,Qs],d([h({type:String,attribute:"custom-styles"})],ye.prototype,"customStyles",2),d([h({type:String,attribute:"client-token"})],ye.prototype,"clientToken",2),d([h({type:Object,attribute:!1,hasChanged:(e,r)=>!ft(e,r)})],ye.prototype,"options",2),d([h({type:Boolean,attribute:"loader-disabled"})],ye.prototype,"disableLoader",2),d([h({type:Boolean,reflect:!0,attribute:"js-initialized"})],ye.prototype,"_jsInitialized",2),d([de("slot")],ye.prototype,"defaultSlot",2),d([N()],ye.prototype,"previousLoadingState",2),ye=d([D(),b("primer-checkout")],ye);function Xm(a){return document.querySelector(`#${a}`)}function eh(a,t){let e=document.createElement("style");return e.textContent=a,e.id=t,e}function Gr(a,t,e=!0){if(!Ua||Xm(t))return;let i=eh(a,t);e&&document.head.firstChild?document.head.insertBefore(i,document.head.firstChild):document.head.appendChild(i)}var ll=`
|
|
181
181
|
@keyframes primer-css-spinner-rotate {
|
|
182
182
|
0% {
|
|
183
183
|
transform: rotate(0deg);
|