@tagadapay/headless-sdk 1.22.0 → 1.23.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/dist/core/helpers/paymentsApi.d.ts +5 -0
- package/dist/core/helpers/paymentsApi.d.ts.map +1 -1
- package/dist/core/helpers/paymentsApi.js +30 -0
- package/dist/core/helpers/paymentsApi.js.map +1 -1
- package/dist/core/modules/track.d.ts.map +1 -1
- package/dist/core/modules/track.js +7 -1
- package/dist/core/modules/track.js.map +1 -1
- package/dist/core/version.d.ts +1 -1
- package/dist/core/version.js +1 -1
- package/dist/pixels/engine.d.ts +3 -3
- package/dist/pixels/engine.d.ts.map +1 -1
- package/dist/pixels/engine.js +12 -8
- package/dist/pixels/engine.js.map +1 -1
- package/dist/pixels/pixelMapping.d.ts +37 -6
- package/dist/pixels/pixelMapping.d.ts.map +1 -1
- package/dist/pixels/pixelMapping.js +194 -3
- package/dist/pixels/pixelMapping.js.map +1 -1
- package/dist/pixels/pixelTracker.d.ts +10 -4
- package/dist/pixels/pixelTracker.d.ts.map +1 -1
- package/dist/pixels/pixelTracker.js +164 -7
- package/dist/pixels/pixelTracker.js.map +1 -1
- package/dist/pixels/types.d.ts +18 -2
- package/dist/pixels/types.d.ts.map +1 -1
- package/dist/pixels/types.js +1 -0
- package/dist/pixels/types.js.map +1 -1
- package/dist/tagada-headless-commerce.min.js +1 -1
- package/dist/tagada-headless-react.min.js +2 -2
- package/dist/tagada-headless-react.min.js.map +2 -2
- package/dist/tagada-headless.js +11 -5
- package/dist/tagada-headless.min.js +2 -2
- package/dist/tagada-headless.min.js.map +2 -2
- package/dist/tagada-pixels.min.js +2 -2
- package/dist/tagada-pixels.min.js.map +3 -3
- package/package.json +1 -1
package/dist/tagada-headless.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @tagadapay/headless-sdk v1.
|
|
2
|
+
* @tagadapay/headless-sdk v1.23.0
|
|
3
3
|
* Headless checkout, payments, offers, and CRM
|
|
4
4
|
* @license MIT
|
|
5
5
|
*/
|
|
@@ -142,7 +142,7 @@ var TagadaHeadlessBundle = (() => {
|
|
|
142
142
|
|
|
143
143
|
// src/core/version.ts
|
|
144
144
|
var SDK_NAME = "headless";
|
|
145
|
-
var SDK_VERSION = "1.
|
|
145
|
+
var SDK_VERSION = "1.23.0";
|
|
146
146
|
|
|
147
147
|
// src/core/http.ts
|
|
148
148
|
var BASE_URLS = {
|
|
@@ -805,7 +805,7 @@ var TagadaHeadlessBundle = (() => {
|
|
|
805
805
|
}
|
|
806
806
|
|
|
807
807
|
// src/core/modules/track.ts
|
|
808
|
-
var CDN_URL = false ? "" : "https://cdn.jsdelivr.net/npm/@tagadapay/headless-sdk@1.
|
|
808
|
+
var CDN_URL = false ? "" : "https://cdn.jsdelivr.net/npm/@tagadapay/headless-sdk@1.23.0/dist/tagada-pixels.min.js";
|
|
809
809
|
function loadScript(src, isReady) {
|
|
810
810
|
if (isReady())
|
|
811
811
|
return Promise.resolve();
|
|
@@ -1002,7 +1002,13 @@ var TagadaHeadlessBundle = (() => {
|
|
|
1002
1002
|
var _a;
|
|
1003
1003
|
return engine == null ? void 0 : engine.track(
|
|
1004
1004
|
event,
|
|
1005
|
-
{
|
|
1005
|
+
{
|
|
1006
|
+
value: input.amount,
|
|
1007
|
+
currency: input.currency,
|
|
1008
|
+
contents: input.items,
|
|
1009
|
+
num_items: (_a = input.items) == null ? void 0 : _a.length,
|
|
1010
|
+
...event === "Purchase" ? { transaction_id: id } : {}
|
|
1011
|
+
},
|
|
1006
1012
|
{ eventId: `${event}_${id}` }
|
|
1007
1013
|
);
|
|
1008
1014
|
}
|
|
@@ -2796,7 +2802,7 @@ var TagadaHeadlessBundle = (() => {
|
|
|
2796
2802
|
|
|
2797
2803
|
// src/core/modules/lazyCommerce.ts
|
|
2798
2804
|
var script = typeof document === "undefined" ? null : document.currentScript;
|
|
2799
|
-
var url = (script == null ? void 0 : script.src) ? new URL("tagada-headless-commerce.min.js", script.src).href : "https://cdn.jsdelivr.net/npm/@tagadapay/headless-sdk@1.
|
|
2805
|
+
var url = (script == null ? void 0 : script.src) ? new URL("tagada-headless-commerce.min.js", script.src).href : "https://cdn.jsdelivr.net/npm/@tagadapay/headless-sdk@1.23.0/dist/tagada-headless-commerce.min.js";
|
|
2800
2806
|
var loading;
|
|
2801
2807
|
function loadCommerce() {
|
|
2802
2808
|
if (window.TagadaHeadlessCommerce)
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @tagadapay/headless-sdk v1.
|
|
2
|
+
* @tagadapay/headless-sdk v1.23.0
|
|
3
3
|
* Headless checkout, payments, offers, and CRM
|
|
4
4
|
* @license MIT
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var TagadaHeadlessBundle=(()=>{var lt=Object.create;var re=Object.defineProperty;var pt=Object.getOwnPropertyDescriptor;var mt=Object.getOwnPropertyNames;var gt=Object.getPrototypeOf,ht=Object.prototype.hasOwnProperty;var se=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var yt=(s,e)=>{for(var t in e)re(s,t,{get:e[t],enumerable:!0})},Ee=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of mt(e))!ht.call(s,r)&&r!==t&&re(s,r,{get:()=>e[r],enumerable:!(n=pt(e,r))||n.enumerable});return s};var ie=(s,e,t)=>(t=s!=null?lt(gt(s)):{},Ee(e||!s||!s.__esModule?re(t,"default",{value:s,enumerable:!0}):t,s)),ft=s=>Ee(re({},"__esModule",{value:!0}),s);var Jt={};yt(Jt,{AVAILABLE_LANGUAGES:()=>Z,CRYPTO_ONCHAIN_FINAL_PHASES:()=>ue,CRYPTO_ONCHAIN_PAYMENT_METHOD:()=>Ce,CRYPTO_ONCHAIN_STATUS_POLL_MS:()=>Ge,CatalogModule:()=>H,CheckoutModule:()=>O,CryptoOnchainCheckout:()=>F,CurrencyUtils:()=>E,CustomerModule:()=>_,CustomerPortalModule:()=>N,ExperimentsModule:()=>B,FunnelModule:()=>K,GoogleAutocompleteCore:()=>Q,HeadlessClient:()=>Y,HttpClient:()=>x,ISODataCore:()=>ne,OffersModule:()=>T,PaymentModule:()=>$,RxModule:()=>G,TagadaAuthError:()=>L,TagadaError:()=>P,TagadaNetworkError:()=>R,TagadaNotFoundError:()=>I,TagadaPaymentError:()=>oe,TagadaRateLimitError:()=>D,TagadaValidationError:()=>M,TrackModule:()=>U,createHeadlessClient:()=>it,cryptoOnchainPhase:()=>ke,cryptoOnchainSecondsLeft:()=>le,defaultCryptoOnchainSelection:()=>Se,ensureGeoDataLoaded:()=>X,formatCryptoOnchainCountdown:()=>Ve,formatMoney:()=>_e,getCountries:()=>V,getStatesForCountry:()=>ee,isCryptoOnchainMethod:()=>Be,isLanguageLoaded:()=>te,isQuestionActive:()=>Ae,loadGoogleMapsScript:()=>xe,parseTokensFromUrl:()=>Me,selectCryptoOnchainNetwork:()=>we,toIntakeAnswers:()=>st});var P=class extends Error{constructor(e,t,n,r){super(e),this.name="TagadaError",this.code=t,this.statusCode=n,this.details=r}},L=class extends P{constructor(e="Authentication failed. Check your API key or checkout token."){super(e,"auth_error",401),this.name="TagadaAuthError"}},M=class extends P{constructor(e,t=[],n,r){super(e,"validation_error",422,{errors:t,...r}),this.name="TagadaValidationError",this.errors=t,this.appCode=n}},I=class extends P{constructor(e,t){super(`${e} "${t}" not found.`,"not_found",404),this.name="TagadaNotFoundError"}},D=class extends P{constructor(e=1e3){super(`Rate limited. Retry after ${e}ms.`,"rate_limit",429),this.name="TagadaRateLimitError",this.retryAfterMs=e}},oe=class extends P{constructor(e,t){super(e,"payment_error",void 0,t==null?void 0:t.details),this.name="TagadaPaymentError",this.paymentId=t==null?void 0:t.paymentId,this.requireAction=t==null?void 0:t.requireAction}},R=class extends P{constructor(e="Network request failed. Check your connection."){super(e,"network_error"),this.name="TagadaNetworkError"}};var ye="headless",z="1.22.0";var Le={production:"https://api.tagada.io",development:"https://api.tagada.dev",local:"http://localhost:3000"},x=class{constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.timeout=e.timeout,this.apiKey=e.apiKey,this.getToken=e.getToken,this.redirect=e.redirect}static resolveBaseUrl(e,t){return t??Le[e]??Le.production}async request(e,t={}){var m;let{method:n="GET",body:r,headers:i={},params:o,token:a,signal:d}=t,u=`${this.baseUrl}${e}`;if(o){let y=new URLSearchParams;for(let[C,w]of Object.entries(o))w!==void 0&&y.set(C,String(w));let h=y.toString();h&&(u+=`?${h}`)}let g={"Content-Type":"application/json","X-Tagada-SDK":`headless-sdk/${z}`,...i},c=a??this.apiKey??((m=this.getToken)==null?void 0:m.call(this));c&&(g["x-cms-token"]=c);let p=new AbortController,l=setTimeout(()=>p.abort(),this.timeout);try{let y=await fetch(u,{method:n,headers:g,body:r!=null?JSON.stringify(r):void 0,signal:d??p.signal,...this.redirect&&{redirect:this.redirect}});if(clearTimeout(l),y.ok){let h=await y.text();return h?JSON.parse(h):{}}throw await this.handleErrorResponse(y,e),new P("Unexpected error","unknown",y.status)}catch(y){throw clearTimeout(l),y instanceof P?y:y instanceof DOMException&&y.name==="AbortError"?new R(`Request to ${e} timed out after ${this.timeout}ms.`):new R(y instanceof Error?y.message:"Network request failed.")}}get(e,t){return this.request(e,{...t,method:"GET"})}post(e,t,n){return this.request(e,{...n,method:"POST",body:t})}patch(e,t,n){return this.request(e,{...n,method:"PATCH",body:t})}put(e,t,n){return this.request(e,{...n,method:"PUT",body:t})}delete(e,t){return this.request(e,{...t,method:"DELETE"})}async handleErrorResponse(e,t){let n={};try{n=await e.json()}catch{}let r=Pt(n.data),i=n.message||n.error||(typeof r.message=="string"?r.message:void 0)||(typeof n.data=="string"&&Object.keys(r).length===0?n.data:void 0)||`Request failed: ${e.status} ${e.statusText} on ${t}`,o=typeof r.code=="string"?r.code:void 0;switch(e.status){case 401:case 403:throw new L(i);case 404:throw new I(t,"");case 422:{let a=Array.isArray(n.errors)?n.errors:[];throw new M(i,a,o,n)}case 429:{let a=Number(e.headers.get("Retry-After")??"1")*1e3;throw new D(a)}default:throw new P(i,"api_error",e.status,n)}}};function Pt(s){if(s&&typeof s=="object")return s;if(typeof s!="string")return{};try{let e=JSON.parse(s);return e&&typeof e=="object"?e:{}}catch{return{}}}var O=class s{constructor(e,t,n,r){this.http=e;this.storeId=t;this.onTokenChange=n;this.onSession=r}getCurrentSession(){return this._currentSession}async loadSession(e,t,n){var a,d;t&&(this.sessionToken=t,(a=this.onTokenChange)==null||a.call(this,t));let r={skipAsyncWait:"false"};n!=null&&n.currency&&(r.currency=n.currency);let i=await this.http.get(`/api/v1/checkout-sessions/${e}/v2`,{params:r,token:this.sessionToken}),o=this.normalizeSession(i);this._currentSession=o;try{(d=this.onSession)==null||d.call(this,o)}catch{}return o}async createSession(e){var d,u,g;let t=e.items.map(c=>({variantId:c.variantId,priceId:c.priceId,...c.sellingPlanId!==void 0?{sellingPlanId:c.sellingPlanId}:{},...c.trialDays!==void 0?{trialDays:c.trialDays}:{},...c.trialPrice!==void 0?{trialPrice:c.trialPrice}:{},quantity:c.quantity})),n={storeId:this.storeId,lineItems:t};e.returnUrl&&(n.returnUrl=e.returnUrl),e.funnelSessionId&&(n.funnelSessionId=e.funnelSessionId),(d=e.discountCodes)!=null&&d.length&&(n.discountCodes=e.discountCodes),e.metadata&&Object.keys(e.metadata).length>0&&(n.metadata=e.metadata),e.customerMetadata&&Object.keys(e.customerMetadata).length>0&&(n.customerMetadata=e.customerMetadata),(u=e.customerTags)!=null&&u.length&&(n.customerTags=e.customerTags);let r={};e.currency&&(r.currency=e.currency),e.customerEmail&&(r.email=e.customerEmail,r.firstName=e.customerFirstName,r.lastName=e.customerLastName),Object.keys(r).length>0&&(n.customer=r);let i=await this.http.post("/api/v1/checkout/session/init",n),a=new URL(i.checkoutUrl).searchParams.get("token")??"";return this.sessionToken=a,a&&((g=this.onTokenChange)==null||g.call(this,a)),{checkoutUrl:i.checkoutUrl,checkoutToken:i.checkoutToken,sessionToken:a,customerId:i.customerId}}async createSessionUrl(e){let{checkoutPath:t="/checkout",origin:n,...r}=e,i=await this.createSession(r),o=n??(typeof window<"u"?window.location.origin:""),a=new URLSearchParams({checkoutToken:i.checkoutToken,sessionToken:i.sessionToken}),d=`${o}${t}?${a.toString()}`;return{...i,url:d}}static parseTokensFromUrl(e){if(typeof e>"u"&&typeof window>"u")return null;let t=e??window.location.href,n;try{n=new URL(t)}catch{return null}let r=n.searchParams.get("checkoutToken");if(!r)return null;let i=n.searchParams.get("sessionToken")??n.searchParams.get("token")??"";return{checkoutToken:r,sessionToken:i}}parseTokensFromUrl(e){return s.parseTokensFromUrl(e)}async updateCart(e,t){let n=t.map(r=>({variantId:r.variantId,priceId:r.priceId,...r.sellingPlanId!==void 0?{sellingPlanId:r.sellingPlanId}:{},quantity:r.quantity}));return this.http.post(`/api/v1/checkout-sessions/${e}/line-items`,{lineItems:n},{token:this.sessionToken})}async updateCustomer(e,t){t.email&&(this.customerEmail=t.email),t.firstName&&(this.customerFirstName=t.firstName),t.lastName&&(this.customerLastName=t.lastName),t.phone&&(this.customerPhone=t.phone)}async updateAddress(e,t){let n=this.mapAddress(t.shippingAddress),r=this.mapAddress(t.billingAddress),i=n??r??{},o=r??n,a=!!(t.billingAddress&&t.shippingAddress);await this.http.post(`/api/v1/checkout-sessions/${e}/customer-and-session-info`,{checkoutSessionId:e,customerData:{email:this.customerEmail},shippingAddress:i,billingAddress:o??{},differentBillingAddress:a},{token:this.sessionToken})}async updateCustomerAndAddress(e,t){t.customer.email&&(this.customerEmail=t.customer.email),t.customer.firstName&&(this.customerFirstName=t.customer.firstName),t.customer.lastName&&(this.customerLastName=t.customer.lastName),t.customer.phone&&(this.customerPhone=t.customer.phone);let n=this.mapAddress(t.shippingAddress),r=this.mapAddress(t.billingAddress),i=n??r??{},o=r??n,a=!!(t.billingAddress&&t.shippingAddress);await this.http.post(`/api/v1/checkout-sessions/${e}/customer-and-session-info`,{checkoutSessionId:e,customerData:{email:this.customerEmail},shippingAddress:i,billingAddress:o??{},differentBillingAddress:a},{token:this.sessionToken})}mapAddress(e){if(e)return Ct({firstName:e.firstName??this.customerFirstName,lastName:e.lastName??this.customerLastName,phone:e.phone??this.customerPhone,address1:e.line1,address2:e.line2,city:e.city,state:e.state,postal:e.postalCode,country:e.country})}async applyPromoCode(e,t){await this.http.post(`/api/v1/checkout-sessions/${e}/promotions/apply`,{checkoutSessionId:e,code:t},{token:this.sessionToken})}async removePromoCode(e,t){let n=t??"default";await this.http.delete(`/api/v1/checkout-sessions/${e}/promotions/${n}`,{token:this.sessionToken})}async getShippingRates(e){return((await this.http.get(`/api/v1/checkout-sessions/${e}/shipping-rates`,{token:this.sessionToken})).rates??[]).map(n=>this.normalizeShippingRate(n))}normalizeShippingRate(e){return{id:e.id,name:e.name??e.shippingRateName??"",description:e.description??void 0,amount:e.amount??0,currency:e.currency??"USD",estimatedDays:e.estimatedDays??e.estimatedDeliveryTime??void 0}}async selectShippingRate(e,t){await this.http.post(`/api/v1/checkout-sessions/${e}/shipping-rate`,{checkoutSessionId:e,shippingRateId:t},{token:this.sessionToken})}normalizeSession(e){var g;let t=e.checkoutSession,n=t.orderSummaries??[],r=e.summary??t.summary??n[0]??{},i=t.sessionLineItems??[],o=t.customer,a=(g=r.currency??t.selectedPresentmentCurrency)==null?void 0:g.toUpperCase(),d=i.map(c=>{let p=c.price,l=c.variant??(p==null?void 0:p.variant)??{},m=c.product??l.product??{},y=(p==null?void 0:p.currencyOptions)??{},h=(a?y[a]:void 0)??y[Object.keys(y)[0]],C=(h==null?void 0:h.amount)??0;return{id:c.id,variantId:c.variantId,priceId:c.priceId,productName:m.name??"",variantName:l.name??"",quantity:c.quantity??1,unitAmount:C,totalAmount:C*(c.quantity??1),currency:a??"USD",imageUrl:l.imageUrl??m.imageUrl??"",...p!=null&&p.recurring?{recurring:{interval:p.interval??"month",intervalCount:p.intervalCount??1}}:{}}}),u=r.items??[];return{id:t.id,storeId:t.storeId,checkoutToken:t.checkoutToken,currency:a??"USD",items:d,totals:{subtotal:r.subtotalAmount??0,discount:r.totalPromotionAmount??0,shipping:r.shippingCost??0,tax:r.totalTaxAmount??0,total:r.totalAdjustedAmount??r.totalAmount??u.reduce((c,p)=>c+(p.amount??0),0),currency:a??"USD"},customer:o?{id:o.id,email:o.email,firstName:o.firstName,lastName:o.lastName,phone:o.phone}:void 0,shippingAddress:this.normalizeAddress(t.shippingAddress),billingAddress:this.normalizeAddress(t.billingAddress),selectedShippingRateId:t.shippingRateId??null,metadata:t.metadata,...typeof t.draft=="boolean"?{draft:t.draft}:{}}}normalizeAddress(e){if(!e||typeof e!="object")return;let t=e,n={firstName:t.firstName,lastName:t.lastName,line1:t.line1??t.address1,line2:t.line2??t.address2,city:t.city,state:t.state,postalCode:t.postalCode??t.postal,country:t.country,phone:t.phone};return Object.values(n).some(r=>r!==void 0&&r!=="")?n:void 0}},Me=O.parseTokensFromUrl;function Ct(s){let e={};for(let[t,n]of Object.entries(s))n!=null&&n!==""&&(e[t]=n);return Object.keys(e).length>0?e:void 0}function ae(s){var t,n;if(!s)return;let e={firstName:s.givenName,lastName:s.familyName,line1:(t=s.addressLines)==null?void 0:t[0],line2:(n=s.addressLines)==null?void 0:n[1],city:s.locality,state:s.administrativeArea,postalCode:s.postalCode,country:s.countryCode,phone:s.phoneNumber};return De(e)?e:void 0}function de(s){if(!s)return;let[e,...t]=(s.name??"").trim().split(/\s+/),n={firstName:e||void 0,lastName:t.length?t.join(" "):void 0,line1:s.address1,line2:[s.address2,s.address3].filter(Boolean).join(" ")||void 0,city:s.locality,state:s.administrativeArea,postalCode:s.postalCode,country:s.countryCode,phone:s.phoneNumber};return De(n)?n:void 0}function De(s){var e,t;return!!((e=s.line1)!=null&&e.trim()&&((t=s.country)!=null&&t.trim()))}var Ue="https://cdn.jsdelivr.net/npm/@tagadapay/headless-sdk@1.22.0/dist/tagada-pixels.min.js";function He(s,e){return e()?Promise.resolve():new Promise((t,n)=>{let r=document.createElement("script");r.src=s,r.async=!0,r.onload=()=>t(),r.onerror=()=>n(new Error("runtime script failed to load")),document.head.appendChild(r)})}async function St(){if(typeof window>"u")return null;if(Ue){let s=window;return s.TagadaPixels?s.TagadaPixels:(await He(Ue,()=>!!s.TagadaPixels),s.TagadaPixels??null)}return await import("../../pixels/index.js")}var Fe="__tgd_track",wt="__tgd_aid",kt="__tgd_sid",qe=50,It=2e3,$e=1e3,vt=64;function ce(s){if(!(!Array.isArray(s)||s.length===0))return s.map(e=>({id:e.variantId,quantity:e.quantity,item_price:e.unitAmount}))}function je(s){if(!s)return;let e={};for(let[t,n]of Object.entries(s))(typeof n=="string"||typeof n=="number"||typeof n=="boolean")&&(e[t]=n);return Object.keys(e).length>0?e:void 0}var bt={lead:"Lead",product_viewed:"ViewContent",added_to_cart:"AddToCart"};function fe(){try{return crypto.randomUUID()}catch{return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}}function At(s){let e={};for(let t of s){let{provider:n,id:r,idKey:i,...o}=t;(e[n]??(e[n]=[])).push({...o,enabled:!0,[i]:r,events:t.events??{}})}return e}var U=class{constructor(e,t,n){this.baseUrl=e;this.storeId=t;this.funnelKey=n;this.records=[];this.lastStep=new Map;this.signals=[];this.currentStepId=null;this.manifestHash=null;this.loadedProviders=[];this.configPromise=null;this.corePromise=null;this.enginePromise=null;this.flushTimer=null;this.listening=!1}flag(){try{return(localStorage.getItem(Fe)??"").split(":")}catch{return[]}}enabled(){return this.flag()[0]===this.storeId}flagFunnelKey(){return this.flag()[1]||this.funnelKey}off(){return typeof window>"u"||!this.enabled()}arm(){try{localStorage.setItem(Fe,`${this.storeId}:${this.funnelKey}`)}catch{}}step(e,t){if(typeof window>"u")return;this.arm();let n=(t==null?void 0:t.path)??window.location.pathname,r=`${e}|${n}`,i=Date.now(),o=this.lastStep.get(r);o!==void 0&&i-o<$e||(this.remember(r,i),this.currentStepId=e,this.listen(),this.push({kind:"step",stepId:e,at:i,path:n}),this.pixels().then(a=>a==null?void 0:a.pageView(n,{stepId:e})),this.core().then(a=>a==null?void 0:a.page({step_id:e})).catch(()=>{}))}event(e,t){if(this.off())return;let n=this.currentStepId;if(n===null)return;let r=bt[e],i=`${r??e}_${fe()}`;this.push({kind:"event",stepId:n,name:e,at:Date.now(),eventId:i,props:je(t)}),this.pixels().then(o=>r?o==null?void 0:o.track(r,t,{stepId:n,eventId:i}):o==null?void 0:o.trackCustom(e,t,{stepId:n})),this.core().then(o=>o==null?void 0:o.track(e,{...je(t)??{},step_id:n,pixel_event_id:i})).catch(()=>{})}remember(e,t){for(let[n,r]of this.lastStep)t-r>=$e&&this.lastStep.delete(n);for(;this.lastStep.size>=vt;){let n=this.lastStep.keys().next();if(n.done===!0)break;this.lastStep.delete(n.value)}this.lastStep.set(e,t)}identify(e){this.off()||(this.pixels().then(t=>t==null?void 0:t.identify({email:e.email,phone:e.phone,externalId:e.customerId})),this.core().then(t=>t==null?void 0:t.identify(e.customerId??null,{email:e.email,phone:e.phone,customerId:e.customerId})).catch(()=>{}))}consent(e){this.off()||this.pixels().then(t=>t==null?void 0:t.consent(e))}async health(){return typeof window>"u"?this.snapshot():(this.enabled()&&await this.config(),this.snapshot())}noteCheckout(e){this.notePixel("InitiateCheckout",e.checkoutSessionId,e)}notePaid(e){this.notePixel("Purchase",e.orderId,e)}notePixel(e,t,n){this.off()||this.pixels().then(r=>{var i;return r==null?void 0:r.track(e,{value:n.amount,currency:n.currency,contents:n.items,num_items:(i=n.items)==null?void 0:i.length},{eventId:`${e}_${t}`})})}noteSignal(e,t,n){this.off()||(this.signals.push({signal:e,value:t,detail:n}),this.listen(),this.push({kind:"signal",signal:e,value:t,detail:n}))}snapshot(){return{enabled:typeof window>"u"?!1:this.enabled(),storeId:this.storeId,funnelKey:this.flagFunnelKey(),sdk:{name:ye,version:z},manifestHash:this.manifestHash,pixels:{loaded:this.loadedProviders.length>0,providers:[...this.loadedProviders]},signals:[...this.signals]}}config(){if(this.configPromise!==null)return this.configPromise;let e=`${this.baseUrl}/api/public/v1/sdk/config?storeId=${encodeURIComponent(this.storeId)}&funnel=${encodeURIComponent(this.flagFunnelKey())}`;return this.configPromise=(async()=>{try{let t=await fetch(e);if(!t.ok)return null;let n=await t.json();return this.manifestHash=n.manifestHash||null,n}catch{return null}})(),this.configPromise}core(){return typeof window>"u"?Promise.resolve(null):(this.corePromise??(this.corePromise=(async()=>{var e,t;try{let n=await this.config();if(!n||!n.collect&&!n.experiments)return null;let r=this.baseUrl.replace(/\/+$/,""),i=window;return typeof((e=i.tgd)==null?void 0:e.init)!="function"&&await He(r+"/assets/js/tgd.js",()=>{var o;return typeof((o=i.tgd)==null?void 0:o.init)=="function"}),typeof((t=i.tgd)==null?void 0:t.init)!="function"?null:(i.tgd.init({storeId:this.storeId,apiHost:n.collect?new URL(n.collect.url).origin:r,bootstrap:this.bootstrap,_source:"headless",_manualPages:!0}),i.tgd)}catch{return null}})()),this.corePromise)}noteFunnelSession(e){this.off()||this.core().then(t=>t==null?void 0:t._link(e)).catch(()=>{})}pixels(){return this.enabled()?(this.enginePromise??(this.enginePromise=this.startEngine()),this.enginePromise):Promise.resolve(null)}async startEngine(){var e;try{let t=await this.config();if(t===null)return null;let n=await St();if(n===null)return null;let r=n.createPixelEngine({pixels:At(t.pixels??[]),steps:t.steps,checkout:t.checkout,requireConsent:((e=t.consent)==null?void 0:e.required)===!0,onSignal:i=>this.onPixelSignal(i)});return await r.init(),this.loadedProviders=[...new Set((t.pixels??[]).map(i=>i.provider))],r}catch{return null}}onPixelSignal(e){let t=e.detail??{};this.signals.push({signal:e.kind,value:e.provider,detail:t}),this.push({kind:"signal",signal:e.kind,value:e.provider,detail:t})}listen(){if(this.listening||typeof window>"u")return;this.listening=!0;let e=t=>{t.type==="visibilitychange"&&document.visibilityState!=="hidden"||this.flush()};window.addEventListener("pagehide",e),window.addEventListener("visibilitychange",e)}push(e){if(this.enabled()){if(this.records.push(e),this.records.length>=qe){this.flush();return}this.flushTimer===null&&(this.flushTimer=setTimeout(()=>this.flush(),It))}}identifier(e,t){try{let n=e==="local"?localStorage:sessionStorage,r=n.getItem(t);if(r)return r;let i=fe();return n.setItem(t,i),i}catch{return fe()}}flush(){if(this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.records.length===0)return;let e=this.records.splice(0,qe),t={storeId:this.storeId,funnelKey:this.flagFunnelKey(),sdk:{name:ye,version:z},anonymousId:this.identifier("local",wt),sessionId:this.identifier("session",kt),records:e};this.manifestHash!==null&&(t.manifestHash=this.manifestHash);let n=JSON.stringify(t),r=`${this.baseUrl}/api/public/v1/sdk/events`;try{if(typeof navigator<"u"&&typeof navigator.sendBeacon=="function"&&navigator.sendBeacon(r,new Blob([n],{type:"text/plain;charset=UTF-8"})))return}catch{}try{fetch(r,{method:"POST",body:n,keepalive:!0,headers:{"content-type":"text/plain;charset=UTF-8"}}).catch(()=>{})}catch{}}};var Ce="crypto_onchain",Ge=5e3,ue=["paid","underpaid","failed","expired"];function Be(s){return s?s.trim().toLowerCase().replace(/-/g,"_").split(":")[0]===Ce:!1}function Se(s){let e=s.filter(r=>r.assets.length>0),t=e.find(r=>!r.testnet)??e[0];if(!t)return null;let n=t.assets.find(r=>r.stable)??t.assets[0];return{chainId:t.chainId,asset:n.symbol}}function we(s,e,t){var o,a;let n=((o=s.find(d=>d.chainId===e))==null?void 0:o.assets)??[],r=n.find(d=>d.symbol===t),i=n.find(d=>d.stable)??n[0];return{chainId:e,asset:((a=r??i)==null?void 0:a.symbol)??t}}function ke(s){if(!s)return"waiting";if(s.paid)return"paid";switch(s.status){case"detected":case"overpaid":return"confirming";case"underpaid":return"underpaid";case"failed":return"failed";case"expired":return"expired";default:return s.expired?"expired":"waiting"}}function le(s,e){if(!s)return 0;let t=Date.parse(s);return Number.isNaN(t)?0:Math.max(0,Math.floor((t-e)/1e3))}function Ve(s){let e=Math.max(0,Math.floor(s)),t=Math.floor(e/3600),n=Math.floor(e%3600/60),r=String(e%60).padStart(2,"0");return t>0?`${t}:${String(n).padStart(2,"0")}:${r}`:`${n}:${r}`}var Pe="Crypto payments are not available right now. Choose another payment method.",F=class{constructor(e,t){this.api=e;this.options=t;this.state={options:"idle",networks:[],selection:null,payment:null,paymentStatus:null,isCreating:!1,error:null};this.listeners=new Set;this.pollTimer=null;this.stopped=!1;this.paidNotified=!1;this.subscribe=this.subscribe.bind(this),this.getState=this.getState.bind(this)}getState(){return this.state}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getPhase(e=Date.now()){let{payment:t,paymentStatus:n}=this.state,r=ke(n??(t?{status:t.status,paid:!1,expired:!1}:null));return t!==null&&r==="waiting"&&le(t.expiresAt,e)===0?"expired":r}getSecondsLeft(e=Date.now()){var t;return le(((t=this.state.payment)==null?void 0:t.expiresAt)??null,e)}async loadOptions(){this.setState({options:"loading",error:null});try{let e=await this.api.getCryptoOnchainOptions(this.options.checkoutSessionId);if(!e.ok)return this.setState({options:"unavailable",networks:[],selection:null,error:e.message||Pe}),this.state;let t=this.state.selection??Se(e.networks);this.setState(t?{options:"ready",networks:e.networks,selection:t}:{options:"unavailable",networks:e.networks,selection:null,error:Pe})}catch(e){this.setState({options:"unavailable",error:Ke(e)})}return this.state}select(e){let t=this.state.selection;if(e.chainId!==void 0&&e.chainId!==(t==null?void 0:t.chainId)){this.setState({selection:we(this.state.networks,e.chainId,e.asset??(t==null?void 0:t.asset)??"")});return}e.asset!==void 0&&t&&this.setState({selection:{...t,asset:e.asset}})}async pay(e){let t=e??this.state.selection;if(!t)return{ok:!1,code:"ASSET_NOT_AVAILABLE",message:"Choose a network and a coin"};if(this.state.isCreating)return{ok:!1,code:"CHECKOUT_FAILED",message:"A payment is already being created"};this.setState({isCreating:!0,error:null,selection:t});try{let n=await this.api.createCryptoOnchainPayment({checkoutSessionId:this.options.checkoutSessionId,chainId:t.chainId,asset:t.asset});return n.ok?(this.stopped=!1,this.setState({isCreating:!1,payment:n.payment,paymentStatus:null}),this.schedulePoll(),n):(this.setState({isCreating:!1,error:n.message}),n)}catch(n){let r=Ke(n);return this.setState({isCreating:!1,error:r}),{ok:!1,code:"CHECKOUT_FAILED",message:r}}}async refreshStatus(){var t,n,r;let e=this.state.payment;if(!e)return null;try{let i=await this.api.getCryptoOnchainStatus({checkoutSessionId:this.options.checkoutSessionId,cryptoOnchainPaymentId:e.cryptoOnchainPaymentId});if(!i.ok||((t=this.state.payment)==null?void 0:t.cryptoOnchainPaymentId)!==e.cryptoOnchainPaymentId)return null;let o={status:i.status,paymentId:i.paymentId,orderId:i.orderId,confirmations:i.confirmations,requiredConfirmations:i.requiredConfirmations,txHash:i.txHash,explorerTxUrl:i.explorerTxUrl,paid:i.paid,expired:i.expired,redirectUrl:i.redirectUrl};return this.setState({paymentStatus:o}),o.paid&&!this.paidNotified&&(this.paidNotified=!0,(r=(n=this.options).onPaid)==null||r.call(n,o)),o}catch{return null}}resume(){!this.state.payment||ue.includes(this.getPhase())||(this.stopped=!1,this.schedulePoll())}stop(){this.stopped=!0,this.pollTimer&&clearTimeout(this.pollTimer),this.pollTimer=null}schedulePoll(){this.pollTimer&&clearTimeout(this.pollTimer),this.pollTimer=setTimeout(async()=>{this.pollTimer=null,await this.refreshStatus(),!this.stopped&&!ue.includes(this.getPhase())&&this.schedulePoll()},this.options.pollIntervalMs??5e3)}setState(e){var t,n;this.state={...this.state,...e},(n=(t=this.options).onChange)==null||n.call(t,this.state),this.listeners.forEach(r=>r(this.state))}};function Ke(s){return s instanceof Error&&s.message?s.message:Pe}function Ie(s){if(!s||typeof s!="object"||Array.isArray(s))return null;let{payment:e,order:t,paymentId:n,clientSecret:r,amount:i,currency:o,checkoutSessionId:a,radar:d}=s;return e!==void 0||t!==void 0||typeof n!="string"||!n||typeof r!="string"||!r?null:{paymentId:n,clientSecret:r,...typeof i=="number"?{amount:i}:{},...typeof o=="string"?{currency:o}:{},...typeof a=="string"?{checkoutSessionId:a}:{},...ze(d)?{radar:{publishableKey:ze(d)}}:{}}}function ze(s){let e=s&&typeof s=="object"?s.publishableKey:null;return typeof e=="string"&&e.startsWith("pk_")?e:null}var Je="tgd_payments_api_return",Rt=60*6e4;function Ye(s){try{let e=sessionStorage.getItem(Je);if(!e)return null;let t=JSON.parse(e);return t.paymentId!==s||(sessionStorage.removeItem(Je),!t.checkoutSessionId||!t.at||Date.now()-t.at>Rt)?null:{checkoutSessionId:t.checkoutSessionId}}catch{return null}}function Qe(){if(typeof window>"u")return Promise.reject(new Error("Stripe Radar needs a browser"));let s=()=>window.Stripe,e=s();return e?Promise.resolve(e):new Promise((t,n)=>{let r=document.createElement("script");r.src="https://js.stripe.com/v3/",r.async=!0,r.onload=()=>{let i=s();i?t(i):n(new Error("Stripe.js loaded without window.Stripe"))},r.onerror=()=>n(new Error("Failed to load Stripe.js")),document.head.appendChild(r)})}var xt="https://secure.oceanpayment.com/pages/js/oceanpayment.js",be="oceanpayment-element";var Ot={fi:"en"};function We(s){var t;let e=(t=s==null?void 0:s.split(/[-_]/)[0])==null?void 0:t.toLowerCase();return e?Ot[e]??e:"en"}var Tt=3e4,J=null;function Ze(){let s=window;return s.Oceanpayment?Promise.resolve(s.Oceanpayment):J||(J=new Promise((e,t)=>{let n=document.createElement("script"),r=o=>{clearTimeout(i),n.remove(),J=null,t(new Error(o))},i=setTimeout(()=>r("The Ocean Payment card form took too long to load"),Tt);n.addEventListener("load",()=>{if(!s.Oceanpayment)return r("Ocean Payment script loaded without window.Oceanpayment");clearTimeout(i),e(s.Oceanpayment)}),n.addEventListener("error",()=>r("Failed to load the Ocean Payment card form")),n.src=xt,document.head.appendChild(n)}),J)}var ve="tgd:headless:oceanpayment:pending",_t=30*60*1e3;function Xe(s){try{sessionStorage.setItem(ve,JSON.stringify({paymentId:s,at:Date.now()}))}catch{}}function Nt(){try{let s=sessionStorage.getItem(ve);if(!s)return;sessionStorage.removeItem(ve);let{paymentId:e,at:t}=JSON.parse(s);return!e||!t||Date.now()-t>_t?void 0:e}catch{return}}function et(){if(typeof window>"u")return;let s=Nt();if(s)try{let e=new URL(window.location.href);if(e.searchParams.get("paymentId"))return;e.searchParams.set("paymentId",s),e.searchParams.set("paymentAction","requireAction"),e.searchParams.set("paymentActionStatus","completed"),window.history.replaceState(window.history.state,"",e.toString())}catch{}}function Lt(){return Promise.reject(new Error("This store takes payments through the Payments API, which the CDN build does not support yet: install @tagadapay/headless-sdk and @tagadapay/core-js 3.7.0 or later from npm."))}var tt=new Set(["failed","declined","rejected","error"]),q=null,Mt=()=>!!q&&(!q.attached||q.element.isConnected),nt=Symbol("ocean-timed-out"),rt=Symbol("ocean-unmounted"),Dt=new Set(["apple_pay","google_pay","paypal","klarna","klarna_express","link"]);function Ut(s){var o;let e=s.type==="credit-card",t=e?"card":s.type,n=s.settings??{},r=n.processors,i=n.publishableKey;return{enabled:!0,method:t,provider:e?void 0:s.type,type:e?"card":s.type,label:s.title,logoUrl:s.iconUrl,express:Dt.has(t),integrationId:e?void 0:s.id,processorId:(o=r==null?void 0:r[0])==null?void 0:o.processorId,publishableKey:typeof i=="string"?i:void 0,metadata:s.metadata??void 0}}var $=class{constructor(e,t,n,r,i,o){this.http=e;this.storeId=t;this.environment=n;this.checkout=r;this.onPaid=i;this.onSignal=o;this.lastPaymentSetup=null;this.paymentsApiStarts=new Map}async getPaymentSetup(e,t){if(t!=null&&t.paymentSetupConfig)return this.lastPaymentSetup=t.paymentSetupConfig,t.paymentSetupConfig;let n=this.readInjectedStepConfig();if(n)return this.lastPaymentSetup=n,n;try{let i=await this.http.get(`/api/v1/checkout-sessions/${e}/payment-setup`),o={...(i==null?void 0:i.config)??{}};return this.lastPaymentSetup=o,o}catch(i){if(!(i instanceof I))throw i}let r=await this.getPaymentSetupFromPickerList(e);return this.lastPaymentSetup=r,r}async getPaymentSetupFromPickerList(e){let t=await this.http.get("/api/v1/payment-methods",{params:{checkoutSessionId:e}}),n=Array.isArray(t)?t.map(Ut):(t==null?void 0:t.methods)??[],r={};for(let i of n){let o=i.provider&&i.provider!==i.method?`${i.method}:${i.provider}`:i.method;r[o]=i}return r}async getExpressMethods(e,t){var i,o,a,d,u,g,c,p,l,m;let n=await this.getPaymentSetup(e,t),r={};for(let[y,h]of Object.entries(n)){if(!h.enabled)continue;if(y.startsWith("express_checkout:")&&h.methods){let b={available:!0,processorId:h.processorId,publishableKey:h.publishableKey,metadata:h.metadata};if((i=h.methods.apple_pay)!=null&&i.enabled){let f=typeof window<"u"&&"ApplePaySession"in window&&((a=(o=window.ApplePaySession)==null?void 0:o.canMakePayments)==null?void 0:a.call(o));r.applePay={...b,type:"apple_pay",available:!!f}}(d=h.methods.google_pay)!=null&&d.enabled&&(typeof window<"u"&&!("PaymentRequest"in window)&&((u=this.onSignal)==null||u.call(this,"googlePay",{reason:"no-payment-request-api"})),r.googlePay={...b,type:"google_pay"}),(g=h.methods.link)!=null&&g.enabled&&(r.link={...b,type:"link"}),(c=h.methods.klarna_express)!=null&&c.enabled&&(r.klarna={...b,type:"klarna_express"});continue}if(!h.express)continue;let C=h.method,w={type:C,available:!0,processorId:h.processorId,publishableKey:h.publishableKey,metadata:h.metadata};if(C==="apple_pay"||h.type==="apple_pay"){let b=typeof window<"u"&&"ApplePaySession"in window&&((l=(p=window.ApplePaySession)==null?void 0:p.canMakePayments)==null?void 0:l.call(p));r.applePay={...w,available:!!b}}else C==="google_pay"||h.type==="google_pay"?(typeof window<"u"&&!("PaymentRequest"in window)&&((m=this.onSignal)==null||m.call(this,"googlePay",{reason:"no-payment-request-api"})),r.googlePay=w):C==="paypal"?r.paypal=w:C==="klarna"||C==="klarna_express"?r.klarna=w:C==="link"&&(r.link=w)}return r}async getStoreConfig(){let e=await this.http.get("/api/v1/checkout/config",{params:{storeId:this.storeId}});return e.config??e}async getEnabledMethods(e,t){let n=await this.getPaymentSetup(e,t);return Object.entries(n).filter(([,r])=>r.enabled).map(([r])=>r)}async tokenizeCard(e){let t=await this.loadCoreJs(),n=new t.Tokenizer({environment:this.environment});await n.initialize();let r={cardNumber:e.cardNumber,expiryDate:e.expiryDate,cvc:e.cvc};e.cardholderName&&(r.cardholderName=e.cardholderName);let i=await n.tokenizeCardRaw(r);return{tagadaToken:t.createTagadaToken(i,n.getProvider().getProviderName()),rawToken:i}}async createInstrument(e){return this.http.post("/api/v1/payment/create-instrument-from-token",{tagadaToken:e.tagadaToken})}async create3dsSession(e){return this.http.post("/api/public/v1/threeds/create-session",{provider:e.provider??"basis_theory",storeId:this.storeId,paymentInstrumentId:e.paymentInstrumentId,sessionData:e.sessionData})}async pay(e){return e.tagadaToken&&!e.paymentInstrumentId?this.rememberPaymentsApiStart(await this.http.post("/api/v1/payment/pay-with-token",{tagadaToken:e.tagadaToken,checkoutSessionId:e.checkoutSessionId,returnUrl:e.returnUrl,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:e.isExpress,metadata:e.metadata}),e):this.rememberPaymentsApiStart(await this.http.post("/api/public/v1/checkout/pay-v2",{checkoutSessionId:e.checkoutSessionId,paymentInstrumentId:e.paymentInstrumentId,storeId:this.storeId,paymentFlowId:e.paymentFlowId,threedsSessionId:e.threedsSessionId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:e.isExpress,metadata:e.metadata,returnUrl:e.returnUrl}),e)}async payDirect(e){return this.rememberPaymentsApiStart(await this.http.post("/api/public/v1/checkout/pay-v2",{checkoutSessionId:e.checkoutSessionId,paymentInstrumentId:e.paymentInstrumentId??"",storeId:this.storeId,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:e.isExpress,threedsSessionId:e.threedsSessionId,returnUrl:e.returnUrl}),e)}async syncWalletContact(e,t){let{shippingAddress:n,billingAddress:r}=t;if(!n&&!r)return;if(!this.checkout)throw new Error("PaymentModule cannot persist the wallet contact: no CheckoutModule was provided. Build the SDK through createTagadaClient() rather than constructing PaymentModule directly.");let i={};t.email&&(i.email=t.email),t.phone&&(i.phone=t.phone),t.firstName&&(i.firstName=t.firstName),t.lastName&&(i.lastName=t.lastName),await this.checkout.updateCustomerAndAddress(e,{customer:i,shippingAddress:n,billingAddress:r})}async processApplePay(e){var a,d,u,g,c,p,l,m,y;await this.syncWalletContact(e.checkoutSessionId,{shippingAddress:ae(e.shippingContact),billingAddress:ae(e.billingContact),email:((a=e.shippingContact)==null?void 0:a.emailAddress)??((d=e.billingContact)==null?void 0:d.emailAddress),phone:((u=e.shippingContact)==null?void 0:u.phoneNumber)??((g=e.billingContact)==null?void 0:g.phoneNumber),firstName:((c=e.shippingContact)==null?void 0:c.givenName)??((p=e.billingContact)==null?void 0:p.givenName),lastName:((l=e.shippingContact)==null?void 0:l.familyName)??((m=e.billingContact)==null?void 0:m.familyName)});let t=e.merchantRegistrationId??((y=await this.resolveApplePayRegistration(e.checkoutSessionId))==null?void 0:y.merchantRegistrationId),n=await this.loadCoreJs(),r=new n.Tokenizer({environment:this.environment});await r.initialize();let i=await r.tokenizeApplePay(e.applePayToken,t),o=btoa(JSON.stringify(n.createTagadaDigitalWalletToken(i,"apple_pay")));return this.pay({checkoutSessionId:e.checkoutSessionId,tagadaToken:o,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:"apple_pay",isExpress:!0})}async resolveApplePayRegistration(e){if(typeof window>"u")return null;let t=window.location.hostname.toLowerCase().split(":")[0];t.startsWith("www.")&&(t=t.slice(4));let n=i=>{var o;for(let a of Object.values(i??{})){let d=(o=a==null?void 0:a.metadata)==null?void 0:o.applePayByok;if(!d||typeof d!="object")continue;let u=d[t];if(u!=null&&u.merchantRegistrationId)return{merchantRegistrationId:u.merchantRegistrationId,displayName:u.displayName}}return null},r=n(this.readInjectedStepConfig())??n(this.lastPaymentSetup);if(r)return r;if(this.lastPaymentSetup||this.readInjectedStepConfig()||!e)return null;try{return n(await this.getPaymentSetup(e))}catch{return null}}async processGooglePay(e){var o,a,d,u;await this.syncWalletContact(e.checkoutSessionId,{shippingAddress:de(e.shippingAddress),billingAddress:de(e.billingAddress),email:e.email??((o=e.shippingAddress)==null?void 0:o.emailAddress)??((a=e.billingAddress)==null?void 0:a.emailAddress),phone:((d=e.shippingAddress)==null?void 0:d.phoneNumber)??((u=e.billingAddress)==null?void 0:u.phoneNumber)});let t=await this.loadCoreJs(),n=new t.Tokenizer({environment:this.environment});await n.initialize();let r=await n.tokenizeGooglePay(e.googlePayToken),i=btoa(JSON.stringify(t.createTagadaDigitalWalletToken(r,"google_pay")));return this.pay({checkoutSessionId:e.checkoutSessionId,tagadaToken:i,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:"google_pay",isExpress:!0})}async processApm(e){return this.payDirect({checkoutSessionId:e.checkoutSessionId,paymentMethod:e.paymentMethod,processorId:e.processorId,paymentFlowId:e.paymentFlowId,returnUrl:e.returnUrl??(typeof window<"u"?window.location.href:void 0)})}async processStripeExpress(e){return this.payDirect({checkoutSessionId:e.checkoutSessionId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:!0})}async getCryptoOnchainOptions(e){return this.http.get(`/api/v1/checkout-sessions/${encodeURIComponent(e)}/crypto-onchain/options`)}async createCryptoOnchainPayment(e){return this.http.post(`/api/v1/checkout-sessions/${encodeURIComponent(e.checkoutSessionId)}/crypto-onchain/session`,{chainId:e.chainId,asset:e.asset})}async getCryptoOnchainStatus(e){return this.http.get(`/api/v1/checkout-sessions/${encodeURIComponent(e.checkoutSessionId)}/crypto-onchain/status`,{params:{cryptoOnchainPaymentId:e.cryptoOnchainPaymentId}})}createCryptoOnchainCheckout(e){return new F(this,e)}async getOceanPaymentConfig(e){let t=await this.http.post(`/api/v1/checkout-sessions/${e}/oceanpayment-embedded-config`,{});return{embedded:!!(t!=null&&t.embedded),sandboxed:!!(t!=null&&t.sandboxed)}}async mountOceanPayment(e){if(typeof window>"u")throw new Error("Ocean Payment needs a browser");let{checkoutSessionId:t,signal:n}=e,r=()=>Object.assign(new Error("Ocean Payment mount aborted"),{name:"AbortError"});if(n!=null&&n.aborted)throw r();let i=typeof e.container=="string"?document.querySelector(e.container):e.container;if(!i&&e.mode!=="redirect")throw new Error(`Ocean Payment container not found: ${String(e.container)}`);if(Mt()||document.getElementById(be))throw new Error("An Ocean Payment card form is already mounted on this page");let o=window,a=document.createElement("div");a.id=be;let d={element:a,attached:!1};q=d;let u=()=>{q===d&&(q=null)},g=!0,c=null,p=f=>{let k=c;c=null,k==null||k(f)},l=()=>{g&&(g=!1,o.oceanpaymentCallBack===p&&delete o.oceanpaymentCallBack,a.remove(),u(),p(rt))};n==null||n.addEventListener("abort",l,{once:!0});let m,y;try{if(m=e.mode==="redirect"?{embedded:!1,sandboxed:!1}:await this.getOceanPaymentConfig(t),n!=null&&n.aborted||m.embedded&&(y=await Ze(),n!=null&&n.aborted))throw r()}catch(f){throw l(),f}let h=!1;if(!y)return u(),{mode:"redirect",pay:async()=>{if(!g)return{status:"failed",error:"The Ocean Payment form was removed"};if(h)return{status:"failed",error:"Payment already in progress"};h=!0;try{let f=await this.http.post(`/api/v1/checkout-sessions/${t}/oceanpayment-link`,{returnUrl:e.returnUrl??window.location.href});return!(f!=null&&f.url)||!f.paymentId?{status:"failed",error:"Ocean Payment is not available for this store"}:{status:"requires_redirect",redirectUrl:f.url,method:"GET",paymentId:f.paymentId}}catch(f){return{status:"failed",error:f instanceof Error?f.message:String(f)}}finally{h=!1}},unmount:l};let C=y;i.appendChild(a),d.attached=!0,o.oceanpaymentCallBack=p;let w=window.location.href;return C.init(m.sandboxed,"",We(e.locale),{showCardName:!1}),{mode:"embedded",pay:async()=>{if(!g)return{status:"failed",error:"The Ocean Payment card form was removed"};if(h)return{status:"failed",error:"Payment already in progress"};h=!0;try{let f=await this.http.post(`/api/v1/checkout-sessions/${t}/oceanpayment-embedded-payment`,{backUrl:w});if(!(f!=null&&f.paymentId)||!f.params)return{status:"failed",error:"Failed to start the payment"};let k=f.paymentId,A=await new Promise(Ne=>{let ct=setTimeout(()=>{c=null,Ne(nt)},12e4);c=ut=>{clearTimeout(ct),Ne(ut)},C.checkout(f.params)});if(A===nt||A===rt)return this.pollUntilDone(k);if(A&&typeof A=="object"&&"msg"in A)return{status:"failed",error:String(A.msg||"Please check your card details.")};let S=await this.http.post(`/api/v1/checkout-sessions/${t}/oceanpayment-embedded-result`,{paymentId:k,response:String(A)});return(S==null?void 0:S.status)==="requires_action"&&S.payUrl?(Xe(k),{status:"requires_redirect",redirectUrl:S.payUrl,method:"GET",paymentId:k}):(S==null?void 0:S.status)==="succeeded"||(S==null?void 0:S.status)==="pending"?this.pollUntilDone(k):{status:"failed",error:(S==null?void 0:S.message)||"Payment declined"}}catch(f){return{status:"failed",error:f instanceof Error?f.message:String(f)}}finally{h=!1}},unmount:l}}async processPayment(e){!e.returnUrl&&typeof window<"u"&&(e={...e,returnUrl:window.location.href});let t=await this.pay(e);return this.finalize(t,{returnUrl:e.returnUrl})}async finalize(e,t){var i,o,a;let n=e.payment,r=(t==null?void 0:t.returnUrl)??(typeof window<"u"?window.location.href:void 0);if(!n){let d=Ie(e);if(d)return this.finalizeOnPaymentsApi(d,r)}return n.status==="succeeded"?(this.emitPaid((i=e.order)==null?void 0:i.id,n),{status:"succeeded",payment:n,order:e.order}):n.status==="failed"||n.status==="declined"?{status:"failed",error:((o=n.requireActionData)==null?void 0:o.message)||((a=n.requireActionData)==null?void 0:a.errorCode)||`Payment ${n.status}`,payment:n}:n.requireAction&&n.requireAction!=="none"&&n.requireActionData?this.handlePaymentAction(n,{returnUrl:r}):this.pollUntilDone(n.id)}async resumeAfterRedirect(e){let t=Ye(e);if(t){let n=typeof window<"u"?window.location.href:void 0;return this.onPaymentsApi((r,i)=>r.resumeOnPaymentsApi(i,e,t.checkoutSessionId,n))}return this.pollUntilDone(e)}async maybeResumeFromUrl(e){if(typeof window>"u"&&!(e!=null&&e.url))return null;e!=null&&e.url||et();let t=(e==null?void 0:e.url)??window.location.href,n;try{n=new URL(t)}catch{return null}let r=n.searchParams.get("paymentAction"),i=n.searchParams.get("paymentActionStatus"),o=n.searchParams.get("paymentId");if(r!=="requireAction"||i!=="completed"||!o)return null;let a=await this.resumeAfterRedirect(o);if((e==null?void 0:e.cleanUrl)!==!1&&typeof window<"u"&&!(e!=null&&e.url)){let d=new URLSearchParams(window.location.search);["paymentAction","paymentActionStatus","paymentId","payment_intent","payment_intent_client_secret","source_type","redirect_status","sessionId"].forEach(g=>d.delete(g));let u=d.toString();try{window.history.replaceState({},document.title,window.location.pathname+(u?"?"+u:""))}catch{}}return a}async getPaymentStatus(e){return this.http.get(`/api/v1/payments/${e}`)}async pollPaymentStatus(e,t){let n=(t==null?void 0:t.intervalMs)??1500,r=(t==null?void 0:t.timeoutMs)??6e4,i=Date.now();for(;Date.now()-i<r;){let o=await this.getPaymentStatus(e);if(o.status==="succeeded"||tt.has(o.status))return o;await new Promise(a=>setTimeout(a,n))}throw new Error(`Payment ${e} did not reach terminal status within ${r}ms.`)}async completeAfter3ds(e){return this.http.post("/api/v1/payments/complete-after-3ds",{paymentId:e})}async markActionProcessed(e){try{await this.http.post("/api/v1/payments/require-action/processed",{paymentId:e})}catch{}}async handlePaymentAction(e,t){let n=e.requireActionData;switch(await this.markActionProcessed(e.id),n.type){case"threeds_auth":return this.handleThreedsAuth(e,t);case"processor_auth":case"redirect_to_payment":return this.extractRedirect(e,n);case"redirect":return this.extractRedirect(e,n);case"stripe_radar":return this.handleStripeRadar(e);case"error":return{status:"failed",error:n.message||n.errorCode||"Payment failed",payment:e};default:return this.extractRedirect(e,n)}}extractRedirect(e,t){var i,o;let n=(i=t.metadata)==null?void 0:i.redirect,r=(n==null?void 0:n.redirectUrl)||t.redirectUrl;return r?{status:"requires_redirect",redirectUrl:r,method:((o=n==null?void 0:n.method)==null?void 0:o.toUpperCase())||"GET",postData:n==null?void 0:n.data,paymentId:e.id}:{status:"failed",error:`Payment requires action (${t.type}) but no redirect URL was provided`,payment:e}}async handleThreedsAuth(e,t){var i,o;let n=(o=(i=e.requireActionData)==null?void 0:i.metadata)==null?void 0:o.threedsSession;if(!(n!=null&&n.externalSessionId))return this.extractRedirect(e,e.requireActionData);let r;try{r=await import("@tagadapay/core-js")}catch{return n.acsChallengeUrl?{status:"requires_redirect",redirectUrl:n.acsChallengeUrl,paymentId:e.id}:this.extractRedirect(e,e.requireActionData)}try{let a=new r.ThreedsManager({provider:"basis_theory"});return await a.initialize({apiKey:void 0}),await a.startChallenge({sessionId:n.externalSessionId,acsChallengeUrl:n.acsChallengeUrl,acsTransactionId:n.acsTransID,threeDSVersion:n.messageVersion}),await this.completeAfter3ds(e.id),this.pollUntilDone(e.id)}catch{return n.acsChallengeUrl?{status:"requires_redirect",redirectUrl:n.acsChallengeUrl,paymentId:e.id}:{status:"failed",error:"3D Secure authentication failed",payment:e}}}async handleStripeRadar(e){var n,r;let t=(r=(n=e.requireActionData)==null?void 0:n.metadata)==null?void 0:r.radar;if(!(t!=null&&t.publishableKey))return{status:"failed",error:"Stripe Radar configuration missing",payment:e};try{let i=await Qe(),{radarSession:o,error:a}=await i(t.publishableKey).createRadarSession();if(a||!o)throw new Error((a==null?void 0:a.message)||"No Radar session returned by Stripe");return await this.http.post("/api/v1/radar-sessions",{orderId:t.orderId,paymentId:e.id,stripeRadarSessionId:o.id,stripeRadarSessionData:o}),await this.completeAfter3ds(e.id),this.pollUntilDone(e.id)}catch(i){return{status:"failed",error:i instanceof Error?i.message:"Stripe Radar failed",payment:e}}}async pollUntilDone(e,t){var a;let n=(t==null?void 0:t.intervalMs)??1500,r=(t==null?void 0:t.timeoutMs)??6e4,i=Date.now(),o=0;for(;Date.now()-i<r;){let d;try{d=await this.getPaymentStatus(e),o=0}catch{if(o++,o>=3)return{status:"failed",error:"Payment verification failed due to network errors"};await new Promise(u=>setTimeout(u,n));continue}if(d.status==="succeeded"||d.status==="pending"&&d.subStatus==="authorized")return d.status==="succeeded"&&this.emitPaid((a=d.order)==null?void 0:a.id,d),{status:"succeeded",payment:d,order:d.order};if(tt.has(d.status))return{status:"failed",error:d.status,payment:d};if(d.requireAction&&d.requireAction!=="none"&&d.requireActionData&&!d.requireActionData.processed)return this.handlePaymentAction(d,{});await new Promise(u=>setTimeout(u,n))}return{status:"pending",paymentId:e}}rememberPaymentsApiStart(e,t){let n=e&&!e.payment?Ie(e):null;return n&&this.paymentsApiStarts.set(n.paymentId,{checkoutSessionId:n.checkoutSessionId??t.checkoutSessionId,...t.paymentMethod?{paymentMethod:t.paymentMethod}:{}}),e}finalizeOnPaymentsApi(e,t){let n=this.paymentsApiStarts.get(e.paymentId);return this.paymentsApiStarts.delete(e.paymentId),this.onPaymentsApi((r,i)=>r.finalizeOnPaymentsApi(i,e,{checkoutSessionId:n==null?void 0:n.checkoutSessionId,paymentMethod:n==null?void 0:n.paymentMethod,returnUrl:t}))}async onPaymentsApi(e){let t;try{t=await Lt()}catch(n){return{status:"failed",error:n instanceof Error?n.message:String(n)}}return e(t,{http:this.http,storeId:this.storeId,checkout:this.checkout,stepConfig:this.readInjectedStepConfigRaw(),onPaid:(n,r)=>this.emitPaid(n,r)})}readInjectedStepConfig(){if(typeof window>"u")return null;let e=window.__TGD_STEP_CONFIG__;if(!e)return null;try{let t=typeof e=="string"?JSON.parse(e):e;return(t==null?void 0:t.paymentSetupConfig)??null}catch{return null}}readInjectedStepConfigRaw(){if(typeof window>"u")return null;let e=window.__TGD_STEP_CONFIG__;if(!e)return null;try{return typeof e=="string"?JSON.parse(e):e}catch{return null}}emitPaid(e,t){var n;if(!(!e||!this.onPaid))try{let r=(n=this.checkout)==null?void 0:n.getCurrentSession();this.onPaid({orderId:e,amount:t.amount,currency:t.currency,items:ce(r==null?void 0:r.items)})}catch{}}async loadCoreJs(){try{return await import("@tagadapay/core-js")}catch(e){let t=new Error("This method requires @tagadapay/core-js. Install it: npm install @tagadapay/core-js");throw t.cause=e,t}}};var v=typeof document>"u"?null:document.currentScript,Ft=v!=null&&v.src?new URL("tagada-headless-commerce.min.js",v.src).href:"https://cdn.jsdelivr.net/npm/@tagadapay/headless-sdk@1.22.0/dist/tagada-headless-commerce.min.js",pe;function j(){return window.TagadaHeadlessCommerce?Promise.resolve(window.TagadaHeadlessCommerce):(pe||(pe=new Promise((s,e)=>{let t=document.createElement("script");t.src=Ft,t.async=!0,v!=null&&v.nonce&&(t.nonce=v.nonce),t.addEventListener("load",()=>window.TagadaHeadlessCommerce?s(window.TagadaHeadlessCommerce):e(new Error("Commerce bundle did not initialize"))),t.addEventListener("error",()=>{t.remove(),e(new Error("Unable to load commerce bundle"))}),document.head.appendChild(t)}).catch(s=>{throw pe=void 0,s})),pe)}var T=class{constructor(...e){this.args=e}load(){return this.instance||(this.instance=j().then(e=>new e.OffersModule(...this.args)).catch(e=>{throw this.instance=void 0,e}))}};for(let s of["getOffer","listOffers","previewOffer","enterFunnelStep","payPreviewedOffer","processOfferPayment","toggleOrderBump","listPostPurchaseOffers","acceptPostPurchaseOffer","declinePostPurchaseOffer"])T.prototype[s]=function(...e){return this.load().then(t=>t[s](...e))};var _=class{constructor(...e){this.args=e}load(){return this.instance||(this.instance=j().then(e=>new e.CustomerModule(...this.args)).catch(e=>{throw this.instance=void 0,e}))}};for(let s of["getProfile","getByEmail","updateProfile","getOrders","getOrder","getSubscriptions","getSubscription","pauseSubscription","resumeSubscription","skipSubscription","rescheduleSubscription","updateSubscriptionQuantity","changeSubscriptionFrequency","swapSubscriptionProduct","updateSubscriptionPaymentMethod","cancelSubscription"])_.prototype[s]=function(...e){return this.load().then(t=>t[s](...e))};var N=class{constructor(...e){this.args=e}load(){return this.instance||(this.instance=j().then(e=>new e.CustomerPortalModule(...this.args)).catch(e=>{throw this.instance=void 0,e}))}};for(let s of["requestCode","verifyCode","getConfig","getMe","cancelFlow","acceptCancelOffer","switchOption","getOffer","acceptOffer","addToNextOrder","getCredits","redeemCredits","buyCreditPack","requestEmailChangeCode","updateProfile","saveAddress","removeAddress","setDefaultAddress","addCard","removeCard","setDefaultPaymentMethod","retryPayment","buyAgain","joinMembership","buyNow","sendNow","reactivateSubscription","setSubscriptionCard","setSubscriptionAddress","skipDate","unskipDate"])N.prototype[s]=function(...e){return this.load().then(t=>t[s](...e))};var H=class{constructor(e,t){this.http=e;this.storeId=t}async getProducts(e){var r,i;let t={storeId:this.storeId,includeVariants:!0,includePrices:!0};return(r=e==null?void 0:e.productIds)!=null&&r.length&&(t.productIds=e.productIds),(i=e==null?void 0:e.variantIds)!=null&&i.length&&(t.variantIds=e.variantIds),(await this.http.post("/api/v1/products",t)).items??[]}async getProduct(e){return(await this.getProducts({productIds:[e]}))[0]??null}};var K=class{constructor(e,t,n,r,i){this.http=e;this.storeId=t;this.checkout=n;this.accountId=r;this.onFunnelSession=i}async navigate(e){var a,d;let t=this.checkout.getCurrentSession();if(!t)throw new P("No checkout session loaded. Call sdk.checkout.loadSession(...) before sdk.funnel.navigate(...).","no_cart_loaded");let n=e.accountId??this.accountId;if(!n)throw new P("accountId is required for funnel.navigate(). Set it on createHeadlessClient({ accountId }) or pass it per call.","missing_account_id");let r=e.currentUrl??(typeof globalThis<"u"?(a=globalThis.location)==null?void 0:a.href:void 0);await this.ensureCmsSession(t,n,e);let i=await this.initializeFunnel({funnelId:e.funnelId,stepId:e.stepId,accountId:n,currentUrl:r});try{(d=this.onFunnelSession)==null||d.call(this,i)}catch{}return{url:await this.runNavigate({funnelSessionId:i,stepId:e.stepId,session:t,input:e,currentUrl:r}),funnelSessionId:i}}async ensureCmsSession(e,t,n){var o,a,d;if(this._cmsToken&&this._cmsSessionId&&this._cmsCustomerId)return;let r=await this.http.post("/api/v1/cms/session/anonymous",{storeId:this.storeId,role:"anonymous",draft:!1});this._cmsToken=r.token,this._cmsSessionId=r.sessionId;let i=await this.http.post("/api/v1/cms/session/v2/init",{storeId:this.storeId,accountId:t,customerId:"anon_placeholder",browserLocale:((o=n.customer)==null?void 0:o.locale)??qt(),userAgent:$t(),queryCurrency:((a=n.customer)==null?void 0:a.currency)??e.currency,queryLocale:(d=n.customer)==null?void 0:d.locale},{token:this._cmsToken});this._cmsCustomerId=i.customer.id}async initializeFunnel(e){return(await this.http.post("/api/v1/funnel/initialize",{cmsSession:{customerId:this._cmsCustomerId,sessionId:this._cmsSessionId,storeId:this.storeId,accountId:e.accountId},funnelId:e.funnelId,entryStepId:e.stepId,funnelStepId:e.stepId,currentUrl:e.currentUrl,draft:!1},{token:this._cmsToken})).context.sessionId}async runNavigate(e){var c,p,l,m;let{funnelSessionId:t,stepId:n,session:r,input:i,currentUrl:o}=e,a=r.items.map(y=>({variantId:y.variantId,priceId:y.priceId,quantity:y.quantity})),d=i.discountCodes??(r.promotionCode?[r.promotionCode]:void 0),u={email:((c=i.customer)==null?void 0:c.email)??((p=r.customer)==null?void 0:p.email),currency:((l=i.customer)==null?void 0:l.currency)??r.currency,locale:(m=i.customer)==null?void 0:m.locale};return(await this.http.post("/api/v1/funnel/navigate",{sessionId:t,currentUrl:o,funnelStepId:n,fireAndForget:!1,event:{type:"INIT_CHECKOUT",data:{checkoutInit:{cartToken:r.id,lineItems:a,customer:u,returnUrl:i.returnUrl,storeId:this.storeId,metadata:i.metadata,discountCodes:d,externalShipping:i.externalShipping}}}},{token:this._cmsToken})).result.url}};function qt(){return typeof navigator<"u"&&navigator.language?navigator.language:"en-US"}function $t(){return typeof navigator<"u"&&navigator.userAgent?navigator.userAgent:"tagadapay-headless-sdk"}var me=(s,e)=>e!==null&&String(s).trim().toLowerCase()===e.trim().toLowerCase();function Ae(s,e,t={}){if(s.visible===!1||s.type==="file")return!1;let n=s.rules??[];return n.length===0?!0:n.some(r=>{let i=o=>{if(o.basedOn==="state")return me(t.state??"",o.answer);if(o.basedOn==="other"&&o.questionId==="patient_sex")return me(t.sexAtBirth??"",o.answer);if(o.basedOn==="question"&&o.questionId){let a=e[o.questionId];return a===void 0?!1:Array.isArray(a)?a.some(d=>me(d,o.answer)):me(a,o.answer)}return!1};return r.op==="and"?r.requirements.every(i):r.requirements.some(i)})}function st(s,e,t={}){let n=[];for(let r of s){if(r.visible===!1){r.defaultValue&&n.push({questionId:r.title,question:r.title,value:r.defaultValue,type:"string"});continue}if(!Ae(r,e,t))continue;let i=e[r.externalQuestionId];i===void 0||typeof i=="string"&&i.trim()===""||n.push({questionId:r.title,question:r.title,value:i,type:r.type==="number"?"number":r.type==="boolean"?"boolean":"string",...r.options.length>0?{displayedOptions:r.options.map(o=>o.label)}:{}})}return n}var G=class{constructor(e,t){this.http=e;this.storeId=t}async getActivationStatus(e){let t=e??this.storeId;if(!t)throw new Error("rx.getActivationStatus: storeId is required");return this.http.get("/api/public/v1/rx/activation-status",{params:{storeId:t}})}async isRequiredForProduct(e,t){return this.http.get("/api/public/v1/rx/required-for-product",{params:{productId:e,clinicalNetworkId:t==null?void 0:t.clinicalNetworkId}})}async getCasesForOrder(e){return this.http.post("/api/public/v1/rx/cases/lookup",e)}async getIntakeContext(e){return this.http.post("/api/public/v1/rx/intake/context",e)}async submitCase(e){return this.http.post("/api/public/v1/rx/cases/submit",e)}async validateIntake(e){return this.http.post("/api/public/v1/rx/intake/validate",e)}async getQuestionsForProduct(e,t){return this.http.get("/api/public/v1/rx/questions-for-product",{params:t?{productId:e,variantId:t}:{productId:e}})}};var B=class{constructor(e,t){this.core=e;this.bootstrap=t;this.runtime=null;this.loading=null;this.settled=!1;this.reads=new Set;this.subscribers=[]}variant(e){var t,n,r,i;return((n=(t=this.bootstrap)==null?void 0:t.experiments[e])==null?void 0:n.arm)??((i=(r=this.bootstrap)==null?void 0:r.flags[e])==null?void 0:i.variant)??null}start(){return typeof window>"u"?Promise.resolve():(this.loading??(this.loading=(async()=>{try{this.runtime=await this.core()}catch{}this.settled=!0;let e=this.runtime;for(let t of this.reads)try{e==null||e.getVariant(t)}catch{}this.reads.clear();for(let{key:t,cb:n}of this.subscribers.splice(0))try{e?e.onVariant(t,n):n(this.variant(t))}catch{}try{await(e==null?void 0:e.ready())}catch{}})()),this.loading)}read(e){this.settled||this.reads.add(e),this.start()}getVariant(e){return this.runtime?this.runtime.getVariant(e):(this.read(e),this.variant(e))}getPayload(e){var t,n,r,i;return this.runtime?this.runtime.getPayload(e):(this.read(e),((n=(t=this.bootstrap)==null?void 0:t.experiments[e])==null?void 0:n.payload)??((i=(r=this.bootstrap)==null?void 0:r.flags[e])==null?void 0:i.payload)??null)}isEnabled(e){var t,n;return this.runtime?this.runtime.isEnabled(e):(this.read(e),((n=(t=this.bootstrap)==null?void 0:t.flags[e])==null?void 0:n.enabled)??!1)}onVariant(e,t){if(this.runtime){this.runtime.onVariant(e,t);return}if(this.settled){t(this.variant(e));return}this.subscribers.push({key:e,cb:t}),this.start()}ready(){return this.start()}};var Y=class{constructor(e){let t=e.environment??"production",n=x.resolveBaseUrl(t,e.baseUrl);this.config={...e,environment:t,baseUrl:n,timeout:e.timeout??3e4},this.http=new x({baseUrl:n,timeout:this.config.timeout,apiKey:e.apiKey,getToken:()=>this._sessionToken}),this.track=new U(n,this.config.storeId,this.config.funnel??"main"),this.track.bootstrap=this.config.bootstrap,this.experiments=new B(()=>this.track.core(),this.config.bootstrap);let r=i=>{this._sessionToken=i};this.checkout=new O(this.http,this.config.storeId,r,i=>this.track.noteCheckout({checkoutSessionId:i.id,amount:i.totals.total,currency:i.totals.currency,items:ce(i.items)})),this.payment=new $(this.http,this.config.storeId,t,this.checkout,i=>this.track.notePaid(i),(i,o)=>this.track.noteSignal("wallet_unavailable",i,o)),this.offers=new T(this.http,this.config.storeId,this.payment),this.customer=new _(this.http,this.config.storeId),this.portal=new N(this.http,this.config.storeId,r),this.catalog=new H(this.http,this.config.storeId),this.funnel=new K(this.http,this.config.storeId,this.checkout,this.config.accountId,i=>this.track.noteFunnelSession(i)),this.rx=new G(this.http,this.config.storeId)}setSessionToken(e){this._sessionToken=e}};function it(s){return new Y(s)}var ot=!1,at=!1,ge=[];function Re(){at=!0;for(let s of ge)s();ge.length=0}function xe(s,e={}){var t,n;return at||(n=(t=window.google)==null?void 0:t.maps)!=null&&n.places?(Re(),Promise.resolve()):ot?new Promise(r=>ge.push(r)):(ot=!0,new Promise((r,i)=>{if(ge.push(r),document.querySelector('script[src*="maps.googleapis.com"]')){let u=()=>{var g,c;(c=(g=window.google)==null?void 0:g.maps)!=null&&c.places?Re():setTimeout(u,100)};u();return}let a=new URLSearchParams({key:s,libraries:"places",v:e.version??"weekly"});e.language&&a.set("language",e.language),e.region&&a.set("region",e.region);let d=document.createElement("script");d.src=`https://maps.googleapis.com/maps/api/js?${a}`,d.async=!0,d.defer=!0,d.onload=()=>Re(),d.onerror=()=>i(new Error("Failed to load Google Maps script")),document.head.appendChild(d)}))}var Q=class s{static async searchPlaces(e,t={}){var r,i;if(!((i=(r=window.google)==null?void 0:r.maps)!=null&&i.places)||!e.trim())return[];let n=new window.google.maps.places.AutocompleteService;return new Promise(o=>{n.getPlacePredictions({input:e,types:t.types??["address"],componentRestrictions:t.componentRestrictions},(a,d)=>{var u,g,c;o(d===((c=(g=(u=window.google)==null?void 0:u.maps)==null?void 0:g.places)==null?void 0:c.PlacesServiceStatus.OK)&&a?a:[])})})}static async getPlaceDetails(e){var n,r;if(!((r=(n=window.google)==null?void 0:n.maps)!=null&&r.places))return null;let t=new window.google.maps.places.PlacesService(document.createElement("div"));return new Promise(i=>{t.getDetails({placeId:e,fields:["place_id","formatted_address","address_components","geometry"]},(o,a)=>{var d,u,g;i(a===((g=(u=(d=window.google)==null?void 0:d.maps)==null?void 0:u.places)==null?void 0:g.PlacesServiceStatus.OK)&&o?o:null)})})}static extractAddressComponents(e){let t={subpremise:"",streetNumber:"",route:"",locality:"",administrativeAreaLevel1:"",administrativeAreaLevel1Long:"",administrativeAreaLevel2:"",administrativeAreaLevel2Long:"",country:"",postalCode:"",fullStreetAddress:""},n="",r="",i="",o="",a="",d="",u="",g="";for(let l of e.address_components??[]){let m=l.types;m.includes("subpremise")&&(t.subpremise=l.long_name),m.includes("street_number")&&(t.streetNumber=l.long_name),m.includes("premise")&&(n=l.long_name),m.includes("route")&&(t.route=l.long_name),m.includes("neighborhood")&&(r=l.long_name),m.includes("sublocality_level_5")&&(i=l.long_name),m.includes("sublocality_level_4")&&(o=l.long_name),m.includes("sublocality_level_3")&&(a=l.long_name),m.includes("sublocality_level_2")&&(d=l.long_name),m.includes("sublocality_level_1")&&(u=l.long_name),m.includes("locality")&&(t.locality=l.long_name),m.includes("postal_town")&&(g=l.long_name),m.includes("administrative_area_level_2")&&(t.administrativeAreaLevel2=l.short_name,t.administrativeAreaLevel2Long=l.long_name),m.includes("administrative_area_level_1")&&(t.administrativeAreaLevel1=l.short_name,t.administrativeAreaLevel1Long=l.long_name),m.includes("country")&&(t.country=l.short_name),m.includes("postal_code")&&(t.postalCode=l.long_name)}t.locality||(t.locality=g||d||u||""),!t.administrativeAreaLevel1&&t.administrativeAreaLevel2&&(t.administrativeAreaLevel1=t.administrativeAreaLevel2Long||t.administrativeAreaLevel2,t.administrativeAreaLevel1Long=t.administrativeAreaLevel2Long);let c=t.streetNumber||n,p=t.route||i||o||a||r;if(t.subpremise&&c&&p)t.fullStreetAddress=`${t.subpremise}/${c} ${p}`;else if(c&&p)if(n&&o&&a){let l=`${a}-${o}-${n}`;d&&(l=`${l} ${d}`),t.fullStreetAddress=l}else t.fullStreetAddress=`${c} ${p}`;else p?t.fullStreetAddress=p:c&&(t.fullStreetAddress=c);return t.fullStreetAddress=t.fullStreetAddress.trim(),t}static extractFormattedAddress(e){let t=s.extractAddressComponents(e);return{address1:t.fullStreetAddress,city:t.locality,country:t.country,state:t.administrativeAreaLevel1,postal:t.postalCode}}};var dt="https://cvwnizdbugpz6jwk.public.blob.vercel-storage.com/geodata/v1",Z=["en","ru","de","da","fr","es","zh","hi","pt","ja","ar","it","he"],W=new Map,he=new Map,Oe=new Map,Te=new Map;async function jt(s){let e=W.get(s);if(e)return e;let t=Oe.get(s);return t||(t=(async()=>{let n=`${dt}/${s}/countries.json`,r=await fetch(n);if(!r.ok)throw new Error(`Geodata fetch failed: ${n} (${r.status})`);let i=await r.json();return W.set(s,i),Oe.delete(s),i})(),Oe.set(s,t),t)}async function Ht(s){let e=he.get(s);if(e)return e;let t=Te.get(s);return t||(t=(async()=>{let n=`${dt}/${s}/regions.json`,r=await fetch(n);if(!r.ok)throw new Error(`Geodata fetch failed: ${n} (${r.status})`);let i=await r.json();return he.set(s,i),Te.delete(s),i})(),Te.set(s,t),t)}function Kt(s){return W.get(s)||W.get("en")||{}}function Gt(s){return he.get(s)||he.get("en")||{}}async function X(s="en"){await Promise.all([jt(s),Ht(s)])}var V=(s="en")=>{let e=Kt(s);return Object.entries(e).map(([t,n])=>({code:t,name:n.n,iso3:n.i3,numeric:n.nu})).sort((t,n)=>t.name.localeCompare(n.name))},ee=(s,e="en")=>{let n=Gt(e)[s];return n?n.map(([r,i])=>({code:r,name:i,countryCode:s})).sort((r,i)=>r.name.localeCompare(i.name)):[]};function te(s){return W.has(s)}var ne=class s{static ensureLoaded(e="en"){return X(e)}static getCountries(e="en"){let t=V(e),n={};for(let r of t)n[r.code]={iso:r.code,iso3:r.iso3??"",numeric:r.numeric??0,name:r.name};return n}static getCountryOptions(e="en"){return V(e).map(t=>({value:t.code,label:t.name}))}static getRegions(e,t="en"){return ee(e,t).map(n=>({iso:n.code,name:n.name}))}static getRegionOptions(e,t="en"){return s.getRegions(e,t).map(n=>({value:n.iso,label:n.name}))}static findRegion(e,t,n="en"){return s.getRegions(e,n).find(r=>r.iso===t)??null}static mapGoogleToISO(e,t,n,r="en"){let i=s.getRegions(n,r);if(i.length===0)return null;let o=i.find(a=>a.iso===e);return o||(o=i.find(a=>a.name.toLowerCase()===e.toLowerCase()),o)||(o=i.find(a=>a.name.toLowerCase()===t.toLowerCase()),o)?o:(o=i.find(a=>a.name.toLowerCase().includes(t.toLowerCase())||t.toLowerCase().includes(a.name.toLowerCase())),o??null)}static isLanguageLoaded(e){return te(e)}static getAvailableLanguages(){return Z}};var Bt={USD:"$",EUR:"\u20AC",GBP:"\xA3",JPY:"\xA5",CAD:"C$",AUD:"A$",CHF:"CHF",CNY:"\xA5",SEK:"kr",NOK:"kr",DKK:"kr",PLN:"z\u0142",CZK:"K\u010D",HUF:"Ft",RON:"lei",BGN:"\u043B\u0432",HRK:"kn",RUB:"\u20BD",UAH:"\u20B4",TRY:"\u20BA",BRL:"R$",MXN:"$",ZAR:"R",INR:"\u20B9",KRW:"\u20A9",THB:"\u0E3F",VND:"\u20AB",IDR:"Rp",MYR:"RM",SGD:"S$",PHP:"\u20B1",TWD:"NT$",HKD:"HK$",ILS:"\u20AA",AED:"\u062F.\u0625",SAR:"\u0631.\u0633",QAR:"\u0631.\u0642",KWD:"\u062F.\u0643",BHD:"\u062F.\u0628",OMR:"\u0631.\u0639.",EGP:"\xA3",NGN:"\u20A6",KES:"KSh",GHS:"\u20B5",COP:"$",ARS:"$",CLP:"$",PEN:"S/",CRC:"\u20A1",DOP:"RD$",JMD:"J$",BOB:"Bs",PYG:"\u20B2",GTQ:"Q",NIO:"C$",PAB:"B/.",PKR:"\u20A8",BDT:"\u09F3",LKR:"\u20A8",NPR:"\u20A8",GEL:"\u20BE",AMD:"\u058F",AZN:"\u20BC",KZT:"\u20B8"},Vt={USD:"US Dollar",EUR:"Euro",GBP:"British Pound",JPY:"Japanese Yen",CAD:"Canadian Dollar",AUD:"Australian Dollar",CHF:"Swiss Franc",CNY:"Chinese Yuan",SEK:"Swedish Krona",NOK:"Norwegian Krone",DKK:"Danish Krone",PLN:"Polish Zloty",CZK:"Czech Koruna",HUF:"Hungarian Forint",BRL:"Brazilian Real",MXN:"Mexican Peso",INR:"Indian Rupee",KRW:"South Korean Won",THB:"Thai Baht",SGD:"Singapore Dollar",HKD:"Hong Kong Dollar",TWD:"Taiwan Dollar",ILS:"Israeli Shekel",AED:"UAE Dirham",SAR:"Saudi Riyal",ZAR:"South African Rand",TRY:"Turkish Lira",RUB:"Russian Ruble",NGN:"Nigerian Naira"},zt=new Set(["JPY","KRW","VND","IDR","LAK","KHR","MMK","PYG"]),E=class s{static getSymbol(e){return Bt[e]??e}static getName(e){return Vt[e]??e}static getDecimalPlaces(e){return zt.has(e)?0:2}static getCurrency(e){return{code:e,symbol:s.getSymbol(e),name:s.getName(e),decimalPlaces:s.getDecimalPlaces(e)}}};function _e(s,e="USD",t="en-US"){let n=E.getDecimalPlaces(e),r=s/(n===0?100:Math.pow(10,n));try{return new Intl.NumberFormat(t,{style:"currency",currency:e,minimumFractionDigits:n,maximumFractionDigits:n}).format(r)}catch{return`${E.getSymbol(e)}${r.toFixed(n)}`}}return ft(Jt);})();
|
|
6
|
+
"use strict";var TagadaHeadlessBundle=(()=>{var lt=Object.create;var re=Object.defineProperty;var pt=Object.getOwnPropertyDescriptor;var mt=Object.getOwnPropertyNames;var gt=Object.getPrototypeOf,ht=Object.prototype.hasOwnProperty;var se=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var yt=(s,e)=>{for(var t in e)re(s,t,{get:e[t],enumerable:!0})},Ee=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of mt(e))!ht.call(s,r)&&r!==t&&re(s,r,{get:()=>e[r],enumerable:!(n=pt(e,r))||n.enumerable});return s};var ie=(s,e,t)=>(t=s!=null?lt(gt(s)):{},Ee(e||!s||!s.__esModule?re(t,"default",{value:s,enumerable:!0}):t,s)),ft=s=>Ee(re({},"__esModule",{value:!0}),s);var Jt={};yt(Jt,{AVAILABLE_LANGUAGES:()=>Z,CRYPTO_ONCHAIN_FINAL_PHASES:()=>ue,CRYPTO_ONCHAIN_PAYMENT_METHOD:()=>Ce,CRYPTO_ONCHAIN_STATUS_POLL_MS:()=>Ge,CatalogModule:()=>j,CheckoutModule:()=>O,CryptoOnchainCheckout:()=>F,CurrencyUtils:()=>E,CustomerModule:()=>_,CustomerPortalModule:()=>N,ExperimentsModule:()=>B,FunnelModule:()=>H,GoogleAutocompleteCore:()=>Q,HeadlessClient:()=>Y,HttpClient:()=>x,ISODataCore:()=>ne,OffersModule:()=>T,PaymentModule:()=>K,RxModule:()=>G,TagadaAuthError:()=>L,TagadaError:()=>P,TagadaNetworkError:()=>R,TagadaNotFoundError:()=>I,TagadaPaymentError:()=>oe,TagadaRateLimitError:()=>D,TagadaValidationError:()=>M,TrackModule:()=>U,createHeadlessClient:()=>it,cryptoOnchainPhase:()=>ke,cryptoOnchainSecondsLeft:()=>le,defaultCryptoOnchainSelection:()=>Se,ensureGeoDataLoaded:()=>X,formatCryptoOnchainCountdown:()=>Ve,formatMoney:()=>_e,getCountries:()=>V,getStatesForCountry:()=>ee,isCryptoOnchainMethod:()=>Be,isLanguageLoaded:()=>te,isQuestionActive:()=>Ae,loadGoogleMapsScript:()=>xe,parseTokensFromUrl:()=>Me,selectCryptoOnchainNetwork:()=>we,toIntakeAnswers:()=>st});var P=class extends Error{constructor(e,t,n,r){super(e),this.name="TagadaError",this.code=t,this.statusCode=n,this.details=r}},L=class extends P{constructor(e="Authentication failed. Check your API key or checkout token."){super(e,"auth_error",401),this.name="TagadaAuthError"}},M=class extends P{constructor(e,t=[],n,r){super(e,"validation_error",422,{errors:t,...r}),this.name="TagadaValidationError",this.errors=t,this.appCode=n}},I=class extends P{constructor(e,t){super(`${e} "${t}" not found.`,"not_found",404),this.name="TagadaNotFoundError"}},D=class extends P{constructor(e=1e3){super(`Rate limited. Retry after ${e}ms.`,"rate_limit",429),this.name="TagadaRateLimitError",this.retryAfterMs=e}},oe=class extends P{constructor(e,t){super(e,"payment_error",void 0,t==null?void 0:t.details),this.name="TagadaPaymentError",this.paymentId=t==null?void 0:t.paymentId,this.requireAction=t==null?void 0:t.requireAction}},R=class extends P{constructor(e="Network request failed. Check your connection."){super(e,"network_error"),this.name="TagadaNetworkError"}};var ye="headless",z="1.23.0";var Le={production:"https://api.tagada.io",development:"https://api.tagada.dev",local:"http://localhost:3000"},x=class{constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.timeout=e.timeout,this.apiKey=e.apiKey,this.getToken=e.getToken,this.redirect=e.redirect}static resolveBaseUrl(e,t){return t??Le[e]??Le.production}async request(e,t={}){var m;let{method:n="GET",body:r,headers:i={},params:o,token:a,signal:d}=t,u=`${this.baseUrl}${e}`;if(o){let y=new URLSearchParams;for(let[C,w]of Object.entries(o))w!==void 0&&y.set(C,String(w));let h=y.toString();h&&(u+=`?${h}`)}let g={"Content-Type":"application/json","X-Tagada-SDK":`headless-sdk/${z}`,...i},c=a??this.apiKey??((m=this.getToken)==null?void 0:m.call(this));c&&(g["x-cms-token"]=c);let p=new AbortController,l=setTimeout(()=>p.abort(),this.timeout);try{let y=await fetch(u,{method:n,headers:g,body:r!=null?JSON.stringify(r):void 0,signal:d??p.signal,...this.redirect&&{redirect:this.redirect}});if(clearTimeout(l),y.ok){let h=await y.text();return h?JSON.parse(h):{}}throw await this.handleErrorResponse(y,e),new P("Unexpected error","unknown",y.status)}catch(y){throw clearTimeout(l),y instanceof P?y:y instanceof DOMException&&y.name==="AbortError"?new R(`Request to ${e} timed out after ${this.timeout}ms.`):new R(y instanceof Error?y.message:"Network request failed.")}}get(e,t){return this.request(e,{...t,method:"GET"})}post(e,t,n){return this.request(e,{...n,method:"POST",body:t})}patch(e,t,n){return this.request(e,{...n,method:"PATCH",body:t})}put(e,t,n){return this.request(e,{...n,method:"PUT",body:t})}delete(e,t){return this.request(e,{...t,method:"DELETE"})}async handleErrorResponse(e,t){let n={};try{n=await e.json()}catch{}let r=Pt(n.data),i=n.message||n.error||(typeof r.message=="string"?r.message:void 0)||(typeof n.data=="string"&&Object.keys(r).length===0?n.data:void 0)||`Request failed: ${e.status} ${e.statusText} on ${t}`,o=typeof r.code=="string"?r.code:void 0;switch(e.status){case 401:case 403:throw new L(i);case 404:throw new I(t,"");case 422:{let a=Array.isArray(n.errors)?n.errors:[];throw new M(i,a,o,n)}case 429:{let a=Number(e.headers.get("Retry-After")??"1")*1e3;throw new D(a)}default:throw new P(i,"api_error",e.status,n)}}};function Pt(s){if(s&&typeof s=="object")return s;if(typeof s!="string")return{};try{let e=JSON.parse(s);return e&&typeof e=="object"?e:{}}catch{return{}}}var O=class s{constructor(e,t,n,r){this.http=e;this.storeId=t;this.onTokenChange=n;this.onSession=r}getCurrentSession(){return this._currentSession}async loadSession(e,t,n){var a,d;t&&(this.sessionToken=t,(a=this.onTokenChange)==null||a.call(this,t));let r={skipAsyncWait:"false"};n!=null&&n.currency&&(r.currency=n.currency);let i=await this.http.get(`/api/v1/checkout-sessions/${e}/v2`,{params:r,token:this.sessionToken}),o=this.normalizeSession(i);this._currentSession=o;try{(d=this.onSession)==null||d.call(this,o)}catch{}return o}async createSession(e){var d,u,g;let t=e.items.map(c=>({variantId:c.variantId,priceId:c.priceId,...c.sellingPlanId!==void 0?{sellingPlanId:c.sellingPlanId}:{},...c.trialDays!==void 0?{trialDays:c.trialDays}:{},...c.trialPrice!==void 0?{trialPrice:c.trialPrice}:{},quantity:c.quantity})),n={storeId:this.storeId,lineItems:t};e.returnUrl&&(n.returnUrl=e.returnUrl),e.funnelSessionId&&(n.funnelSessionId=e.funnelSessionId),(d=e.discountCodes)!=null&&d.length&&(n.discountCodes=e.discountCodes),e.metadata&&Object.keys(e.metadata).length>0&&(n.metadata=e.metadata),e.customerMetadata&&Object.keys(e.customerMetadata).length>0&&(n.customerMetadata=e.customerMetadata),(u=e.customerTags)!=null&&u.length&&(n.customerTags=e.customerTags);let r={};e.currency&&(r.currency=e.currency),e.customerEmail&&(r.email=e.customerEmail,r.firstName=e.customerFirstName,r.lastName=e.customerLastName),Object.keys(r).length>0&&(n.customer=r);let i=await this.http.post("/api/v1/checkout/session/init",n),a=new URL(i.checkoutUrl).searchParams.get("token")??"";return this.sessionToken=a,a&&((g=this.onTokenChange)==null||g.call(this,a)),{checkoutUrl:i.checkoutUrl,checkoutToken:i.checkoutToken,sessionToken:a,customerId:i.customerId}}async createSessionUrl(e){let{checkoutPath:t="/checkout",origin:n,...r}=e,i=await this.createSession(r),o=n??(typeof window<"u"?window.location.origin:""),a=new URLSearchParams({checkoutToken:i.checkoutToken,sessionToken:i.sessionToken}),d=`${o}${t}?${a.toString()}`;return{...i,url:d}}static parseTokensFromUrl(e){if(typeof e>"u"&&typeof window>"u")return null;let t=e??window.location.href,n;try{n=new URL(t)}catch{return null}let r=n.searchParams.get("checkoutToken");if(!r)return null;let i=n.searchParams.get("sessionToken")??n.searchParams.get("token")??"";return{checkoutToken:r,sessionToken:i}}parseTokensFromUrl(e){return s.parseTokensFromUrl(e)}async updateCart(e,t){let n=t.map(r=>({variantId:r.variantId,priceId:r.priceId,...r.sellingPlanId!==void 0?{sellingPlanId:r.sellingPlanId}:{},quantity:r.quantity}));return this.http.post(`/api/v1/checkout-sessions/${e}/line-items`,{lineItems:n},{token:this.sessionToken})}async updateCustomer(e,t){t.email&&(this.customerEmail=t.email),t.firstName&&(this.customerFirstName=t.firstName),t.lastName&&(this.customerLastName=t.lastName),t.phone&&(this.customerPhone=t.phone)}async updateAddress(e,t){let n=this.mapAddress(t.shippingAddress),r=this.mapAddress(t.billingAddress),i=n??r??{},o=r??n,a=!!(t.billingAddress&&t.shippingAddress);await this.http.post(`/api/v1/checkout-sessions/${e}/customer-and-session-info`,{checkoutSessionId:e,customerData:{email:this.customerEmail},shippingAddress:i,billingAddress:o??{},differentBillingAddress:a},{token:this.sessionToken})}async updateCustomerAndAddress(e,t){t.customer.email&&(this.customerEmail=t.customer.email),t.customer.firstName&&(this.customerFirstName=t.customer.firstName),t.customer.lastName&&(this.customerLastName=t.customer.lastName),t.customer.phone&&(this.customerPhone=t.customer.phone);let n=this.mapAddress(t.shippingAddress),r=this.mapAddress(t.billingAddress),i=n??r??{},o=r??n,a=!!(t.billingAddress&&t.shippingAddress);await this.http.post(`/api/v1/checkout-sessions/${e}/customer-and-session-info`,{checkoutSessionId:e,customerData:{email:this.customerEmail},shippingAddress:i,billingAddress:o??{},differentBillingAddress:a},{token:this.sessionToken})}mapAddress(e){if(e)return Ct({firstName:e.firstName??this.customerFirstName,lastName:e.lastName??this.customerLastName,phone:e.phone??this.customerPhone,address1:e.line1,address2:e.line2,city:e.city,state:e.state,postal:e.postalCode,country:e.country})}async applyPromoCode(e,t){await this.http.post(`/api/v1/checkout-sessions/${e}/promotions/apply`,{checkoutSessionId:e,code:t},{token:this.sessionToken})}async removePromoCode(e,t){let n=t??"default";await this.http.delete(`/api/v1/checkout-sessions/${e}/promotions/${n}`,{token:this.sessionToken})}async getShippingRates(e){return((await this.http.get(`/api/v1/checkout-sessions/${e}/shipping-rates`,{token:this.sessionToken})).rates??[]).map(n=>this.normalizeShippingRate(n))}normalizeShippingRate(e){return{id:e.id,name:e.name??e.shippingRateName??"",description:e.description??void 0,amount:e.amount??0,currency:e.currency??"USD",estimatedDays:e.estimatedDays??e.estimatedDeliveryTime??void 0}}async selectShippingRate(e,t){await this.http.post(`/api/v1/checkout-sessions/${e}/shipping-rate`,{checkoutSessionId:e,shippingRateId:t},{token:this.sessionToken})}normalizeSession(e){var g;let t=e.checkoutSession,n=t.orderSummaries??[],r=e.summary??t.summary??n[0]??{},i=t.sessionLineItems??[],o=t.customer,a=(g=r.currency??t.selectedPresentmentCurrency)==null?void 0:g.toUpperCase(),d=i.map(c=>{let p=c.price,l=c.variant??(p==null?void 0:p.variant)??{},m=c.product??l.product??{},y=(p==null?void 0:p.currencyOptions)??{},h=(a?y[a]:void 0)??y[Object.keys(y)[0]],C=(h==null?void 0:h.amount)??0;return{id:c.id,variantId:c.variantId,priceId:c.priceId,productName:m.name??"",variantName:l.name??"",quantity:c.quantity??1,unitAmount:C,totalAmount:C*(c.quantity??1),currency:a??"USD",imageUrl:l.imageUrl??m.imageUrl??"",...p!=null&&p.recurring?{recurring:{interval:p.interval??"month",intervalCount:p.intervalCount??1}}:{}}}),u=r.items??[];return{id:t.id,storeId:t.storeId,checkoutToken:t.checkoutToken,currency:a??"USD",items:d,totals:{subtotal:r.subtotalAmount??0,discount:r.totalPromotionAmount??0,shipping:r.shippingCost??0,tax:r.totalTaxAmount??0,total:r.totalAdjustedAmount??r.totalAmount??u.reduce((c,p)=>c+(p.amount??0),0),currency:a??"USD"},customer:o?{id:o.id,email:o.email,firstName:o.firstName,lastName:o.lastName,phone:o.phone}:void 0,shippingAddress:this.normalizeAddress(t.shippingAddress),billingAddress:this.normalizeAddress(t.billingAddress),selectedShippingRateId:t.shippingRateId??null,metadata:t.metadata,...typeof t.draft=="boolean"?{draft:t.draft}:{}}}normalizeAddress(e){if(!e||typeof e!="object")return;let t=e,n={firstName:t.firstName,lastName:t.lastName,line1:t.line1??t.address1,line2:t.line2??t.address2,city:t.city,state:t.state,postalCode:t.postalCode??t.postal,country:t.country,phone:t.phone};return Object.values(n).some(r=>r!==void 0&&r!=="")?n:void 0}},Me=O.parseTokensFromUrl;function Ct(s){let e={};for(let[t,n]of Object.entries(s))n!=null&&n!==""&&(e[t]=n);return Object.keys(e).length>0?e:void 0}function ae(s){var t,n;if(!s)return;let e={firstName:s.givenName,lastName:s.familyName,line1:(t=s.addressLines)==null?void 0:t[0],line2:(n=s.addressLines)==null?void 0:n[1],city:s.locality,state:s.administrativeArea,postalCode:s.postalCode,country:s.countryCode,phone:s.phoneNumber};return De(e)?e:void 0}function de(s){if(!s)return;let[e,...t]=(s.name??"").trim().split(/\s+/),n={firstName:e||void 0,lastName:t.length?t.join(" "):void 0,line1:s.address1,line2:[s.address2,s.address3].filter(Boolean).join(" ")||void 0,city:s.locality,state:s.administrativeArea,postalCode:s.postalCode,country:s.countryCode,phone:s.phoneNumber};return De(n)?n:void 0}function De(s){var e,t;return!!((e=s.line1)!=null&&e.trim()&&((t=s.country)!=null&&t.trim()))}var Ue="https://cdn.jsdelivr.net/npm/@tagadapay/headless-sdk@1.23.0/dist/tagada-pixels.min.js";function je(s,e){return e()?Promise.resolve():new Promise((t,n)=>{let r=document.createElement("script");r.src=s,r.async=!0,r.onload=()=>t(),r.onerror=()=>n(new Error("runtime script failed to load")),document.head.appendChild(r)})}async function St(){if(typeof window>"u")return null;if(Ue){let s=window;return s.TagadaPixels?s.TagadaPixels:(await je(Ue,()=>!!s.TagadaPixels),s.TagadaPixels??null)}return await import("../../pixels/index.js")}var Fe="__tgd_track",wt="__tgd_aid",kt="__tgd_sid",qe=50,It=2e3,Ke=1e3,vt=64;function ce(s){if(!(!Array.isArray(s)||s.length===0))return s.map(e=>({id:e.variantId,quantity:e.quantity,item_price:e.unitAmount}))}function $e(s){if(!s)return;let e={};for(let[t,n]of Object.entries(s))(typeof n=="string"||typeof n=="number"||typeof n=="boolean")&&(e[t]=n);return Object.keys(e).length>0?e:void 0}var bt={lead:"Lead",product_viewed:"ViewContent",added_to_cart:"AddToCart"};function fe(){try{return crypto.randomUUID()}catch{return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}}function At(s){let e={};for(let t of s){let{provider:n,id:r,idKey:i,...o}=t;(e[n]??(e[n]=[])).push({...o,enabled:!0,[i]:r,events:t.events??{}})}return e}var U=class{constructor(e,t,n){this.baseUrl=e;this.storeId=t;this.funnelKey=n;this.records=[];this.lastStep=new Map;this.signals=[];this.currentStepId=null;this.manifestHash=null;this.loadedProviders=[];this.configPromise=null;this.corePromise=null;this.enginePromise=null;this.flushTimer=null;this.listening=!1}flag(){try{return(localStorage.getItem(Fe)??"").split(":")}catch{return[]}}enabled(){return this.flag()[0]===this.storeId}flagFunnelKey(){return this.flag()[1]||this.funnelKey}off(){return typeof window>"u"||!this.enabled()}arm(){try{localStorage.setItem(Fe,`${this.storeId}:${this.funnelKey}`)}catch{}}step(e,t){if(typeof window>"u")return;this.arm();let n=(t==null?void 0:t.path)??window.location.pathname,r=`${e}|${n}`,i=Date.now(),o=this.lastStep.get(r);o!==void 0&&i-o<Ke||(this.remember(r,i),this.currentStepId=e,this.listen(),this.push({kind:"step",stepId:e,at:i,path:n}),this.pixels().then(a=>a==null?void 0:a.pageView(n,{stepId:e})),this.core().then(a=>a==null?void 0:a.page({step_id:e})).catch(()=>{}))}event(e,t){if(this.off())return;let n=this.currentStepId;if(n===null)return;let r=bt[e],i=`${r??e}_${fe()}`;this.push({kind:"event",stepId:n,name:e,at:Date.now(),eventId:i,props:$e(t)}),this.pixels().then(o=>r?o==null?void 0:o.track(r,t,{stepId:n,eventId:i}):o==null?void 0:o.trackCustom(e,t,{stepId:n})),this.core().then(o=>o==null?void 0:o.track(e,{...$e(t)??{},step_id:n,pixel_event_id:i})).catch(()=>{})}remember(e,t){for(let[n,r]of this.lastStep)t-r>=Ke&&this.lastStep.delete(n);for(;this.lastStep.size>=vt;){let n=this.lastStep.keys().next();if(n.done===!0)break;this.lastStep.delete(n.value)}this.lastStep.set(e,t)}identify(e){this.off()||(this.pixels().then(t=>t==null?void 0:t.identify({email:e.email,phone:e.phone,externalId:e.customerId})),this.core().then(t=>t==null?void 0:t.identify(e.customerId??null,{email:e.email,phone:e.phone,customerId:e.customerId})).catch(()=>{}))}consent(e){this.off()||this.pixels().then(t=>t==null?void 0:t.consent(e))}async health(){return typeof window>"u"?this.snapshot():(this.enabled()&&await this.config(),this.snapshot())}noteCheckout(e){this.notePixel("InitiateCheckout",e.checkoutSessionId,e)}notePaid(e){this.notePixel("Purchase",e.orderId,e)}notePixel(e,t,n){this.off()||this.pixels().then(r=>{var i;return r==null?void 0:r.track(e,{value:n.amount,currency:n.currency,contents:n.items,num_items:(i=n.items)==null?void 0:i.length,...e==="Purchase"?{transaction_id:t}:{}},{eventId:`${e}_${t}`})})}noteSignal(e,t,n){this.off()||(this.signals.push({signal:e,value:t,detail:n}),this.listen(),this.push({kind:"signal",signal:e,value:t,detail:n}))}snapshot(){return{enabled:typeof window>"u"?!1:this.enabled(),storeId:this.storeId,funnelKey:this.flagFunnelKey(),sdk:{name:ye,version:z},manifestHash:this.manifestHash,pixels:{loaded:this.loadedProviders.length>0,providers:[...this.loadedProviders]},signals:[...this.signals]}}config(){if(this.configPromise!==null)return this.configPromise;let e=`${this.baseUrl}/api/public/v1/sdk/config?storeId=${encodeURIComponent(this.storeId)}&funnel=${encodeURIComponent(this.flagFunnelKey())}`;return this.configPromise=(async()=>{try{let t=await fetch(e);if(!t.ok)return null;let n=await t.json();return this.manifestHash=n.manifestHash||null,n}catch{return null}})(),this.configPromise}core(){return typeof window>"u"?Promise.resolve(null):(this.corePromise??(this.corePromise=(async()=>{var e,t;try{let n=await this.config();if(!n||!n.collect&&!n.experiments)return null;let r=this.baseUrl.replace(/\/+$/,""),i=window;return typeof((e=i.tgd)==null?void 0:e.init)!="function"&&await je(r+"/assets/js/tgd.js",()=>{var o;return typeof((o=i.tgd)==null?void 0:o.init)=="function"}),typeof((t=i.tgd)==null?void 0:t.init)!="function"?null:(i.tgd.init({storeId:this.storeId,apiHost:n.collect?new URL(n.collect.url).origin:r,bootstrap:this.bootstrap,_source:"headless",_manualPages:!0}),i.tgd)}catch{return null}})()),this.corePromise)}noteFunnelSession(e){this.off()||this.core().then(t=>t==null?void 0:t._link(e)).catch(()=>{})}pixels(){return this.enabled()?(this.enginePromise??(this.enginePromise=this.startEngine()),this.enginePromise):Promise.resolve(null)}async startEngine(){var e;try{let t=await this.config();if(t===null)return null;let n=await St();if(n===null)return null;let r=n.createPixelEngine({pixels:At(t.pixels??[]),steps:t.steps,checkout:t.checkout,requireConsent:((e=t.consent)==null?void 0:e.required)===!0,onSignal:i=>this.onPixelSignal(i)});return await r.init(),this.loadedProviders=[...new Set((t.pixels??[]).map(i=>i.provider))],r}catch{return null}}onPixelSignal(e){let t=e.detail??{};this.signals.push({signal:e.kind,value:e.provider,detail:t}),this.push({kind:"signal",signal:e.kind,value:e.provider,detail:t})}listen(){if(this.listening||typeof window>"u")return;this.listening=!0;let e=t=>{t.type==="visibilitychange"&&document.visibilityState!=="hidden"||this.flush()};window.addEventListener("pagehide",e),window.addEventListener("visibilitychange",e)}push(e){if(this.enabled()){if(this.records.push(e),this.records.length>=qe){this.flush();return}this.flushTimer===null&&(this.flushTimer=setTimeout(()=>this.flush(),It))}}identifier(e,t){try{let n=e==="local"?localStorage:sessionStorage,r=n.getItem(t);if(r)return r;let i=fe();return n.setItem(t,i),i}catch{return fe()}}flush(){if(this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.records.length===0)return;let e=this.records.splice(0,qe),t={storeId:this.storeId,funnelKey:this.flagFunnelKey(),sdk:{name:ye,version:z},anonymousId:this.identifier("local",wt),sessionId:this.identifier("session",kt),records:e};this.manifestHash!==null&&(t.manifestHash=this.manifestHash);let n=JSON.stringify(t),r=`${this.baseUrl}/api/public/v1/sdk/events`;try{if(typeof navigator<"u"&&typeof navigator.sendBeacon=="function"&&navigator.sendBeacon(r,new Blob([n],{type:"text/plain;charset=UTF-8"})))return}catch{}try{fetch(r,{method:"POST",body:n,keepalive:!0,headers:{"content-type":"text/plain;charset=UTF-8"}}).catch(()=>{})}catch{}}};var Ce="crypto_onchain",Ge=5e3,ue=["paid","underpaid","failed","expired"];function Be(s){return s?s.trim().toLowerCase().replace(/-/g,"_").split(":")[0]===Ce:!1}function Se(s){let e=s.filter(r=>r.assets.length>0),t=e.find(r=>!r.testnet)??e[0];if(!t)return null;let n=t.assets.find(r=>r.stable)??t.assets[0];return{chainId:t.chainId,asset:n.symbol}}function we(s,e,t){var o,a;let n=((o=s.find(d=>d.chainId===e))==null?void 0:o.assets)??[],r=n.find(d=>d.symbol===t),i=n.find(d=>d.stable)??n[0];return{chainId:e,asset:((a=r??i)==null?void 0:a.symbol)??t}}function ke(s){if(!s)return"waiting";if(s.paid)return"paid";switch(s.status){case"detected":case"overpaid":return"confirming";case"underpaid":return"underpaid";case"failed":return"failed";case"expired":return"expired";default:return s.expired?"expired":"waiting"}}function le(s,e){if(!s)return 0;let t=Date.parse(s);return Number.isNaN(t)?0:Math.max(0,Math.floor((t-e)/1e3))}function Ve(s){let e=Math.max(0,Math.floor(s)),t=Math.floor(e/3600),n=Math.floor(e%3600/60),r=String(e%60).padStart(2,"0");return t>0?`${t}:${String(n).padStart(2,"0")}:${r}`:`${n}:${r}`}var Pe="Crypto payments are not available right now. Choose another payment method.",F=class{constructor(e,t){this.api=e;this.options=t;this.state={options:"idle",networks:[],selection:null,payment:null,paymentStatus:null,isCreating:!1,error:null};this.listeners=new Set;this.pollTimer=null;this.stopped=!1;this.paidNotified=!1;this.subscribe=this.subscribe.bind(this),this.getState=this.getState.bind(this)}getState(){return this.state}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getPhase(e=Date.now()){let{payment:t,paymentStatus:n}=this.state,r=ke(n??(t?{status:t.status,paid:!1,expired:!1}:null));return t!==null&&r==="waiting"&&le(t.expiresAt,e)===0?"expired":r}getSecondsLeft(e=Date.now()){var t;return le(((t=this.state.payment)==null?void 0:t.expiresAt)??null,e)}async loadOptions(){this.setState({options:"loading",error:null});try{let e=await this.api.getCryptoOnchainOptions(this.options.checkoutSessionId);if(!e.ok)return this.setState({options:"unavailable",networks:[],selection:null,error:e.message||Pe}),this.state;let t=this.state.selection??Se(e.networks);this.setState(t?{options:"ready",networks:e.networks,selection:t}:{options:"unavailable",networks:e.networks,selection:null,error:Pe})}catch(e){this.setState({options:"unavailable",error:He(e)})}return this.state}select(e){let t=this.state.selection;if(e.chainId!==void 0&&e.chainId!==(t==null?void 0:t.chainId)){this.setState({selection:we(this.state.networks,e.chainId,e.asset??(t==null?void 0:t.asset)??"")});return}e.asset!==void 0&&t&&this.setState({selection:{...t,asset:e.asset}})}async pay(e){let t=e??this.state.selection;if(!t)return{ok:!1,code:"ASSET_NOT_AVAILABLE",message:"Choose a network and a coin"};if(this.state.isCreating)return{ok:!1,code:"CHECKOUT_FAILED",message:"A payment is already being created"};this.setState({isCreating:!0,error:null,selection:t});try{let n=await this.api.createCryptoOnchainPayment({checkoutSessionId:this.options.checkoutSessionId,chainId:t.chainId,asset:t.asset});return n.ok?(this.stopped=!1,this.setState({isCreating:!1,payment:n.payment,paymentStatus:null}),this.schedulePoll(),n):(this.setState({isCreating:!1,error:n.message}),n)}catch(n){let r=He(n);return this.setState({isCreating:!1,error:r}),{ok:!1,code:"CHECKOUT_FAILED",message:r}}}async refreshStatus(){var t,n,r;let e=this.state.payment;if(!e)return null;try{let i=await this.api.getCryptoOnchainStatus({checkoutSessionId:this.options.checkoutSessionId,cryptoOnchainPaymentId:e.cryptoOnchainPaymentId});if(!i.ok||((t=this.state.payment)==null?void 0:t.cryptoOnchainPaymentId)!==e.cryptoOnchainPaymentId)return null;let o={status:i.status,paymentId:i.paymentId,orderId:i.orderId,confirmations:i.confirmations,requiredConfirmations:i.requiredConfirmations,txHash:i.txHash,explorerTxUrl:i.explorerTxUrl,paid:i.paid,expired:i.expired,redirectUrl:i.redirectUrl};return this.setState({paymentStatus:o}),o.paid&&!this.paidNotified&&(this.paidNotified=!0,(r=(n=this.options).onPaid)==null||r.call(n,o)),o}catch{return null}}resume(){!this.state.payment||ue.includes(this.getPhase())||(this.stopped=!1,this.schedulePoll())}stop(){this.stopped=!0,this.pollTimer&&clearTimeout(this.pollTimer),this.pollTimer=null}schedulePoll(){this.pollTimer&&clearTimeout(this.pollTimer),this.pollTimer=setTimeout(async()=>{this.pollTimer=null,await this.refreshStatus(),!this.stopped&&!ue.includes(this.getPhase())&&this.schedulePoll()},this.options.pollIntervalMs??5e3)}setState(e){var t,n;this.state={...this.state,...e},(n=(t=this.options).onChange)==null||n.call(t,this.state),this.listeners.forEach(r=>r(this.state))}};function He(s){return s instanceof Error&&s.message?s.message:Pe}function Ie(s){if(!s||typeof s!="object"||Array.isArray(s))return null;let{payment:e,order:t,paymentId:n,clientSecret:r,amount:i,currency:o,checkoutSessionId:a,radar:d}=s;return e!==void 0||t!==void 0||typeof n!="string"||!n||typeof r!="string"||!r?null:{paymentId:n,clientSecret:r,...typeof i=="number"?{amount:i}:{},...typeof o=="string"?{currency:o}:{},...typeof a=="string"?{checkoutSessionId:a}:{},...ze(d)?{radar:{publishableKey:ze(d)}}:{}}}function ze(s){let e=s&&typeof s=="object"?s.publishableKey:null;return typeof e=="string"&&e.startsWith("pk_")?e:null}var Je="tgd_payments_api_return",Rt=60*6e4;function Ye(s){try{let e=sessionStorage.getItem(Je);if(!e)return null;let t=JSON.parse(e);return t.paymentId!==s||(sessionStorage.removeItem(Je),!t.checkoutSessionId||!t.at||Date.now()-t.at>Rt)?null:{checkoutSessionId:t.checkoutSessionId}}catch{return null}}function Qe(){if(typeof window>"u")return Promise.reject(new Error("Stripe Radar needs a browser"));let s=()=>window.Stripe,e=s();return e?Promise.resolve(e):new Promise((t,n)=>{let r=document.createElement("script");r.src="https://js.stripe.com/v3/",r.async=!0,r.onload=()=>{let i=s();i?t(i):n(new Error("Stripe.js loaded without window.Stripe"))},r.onerror=()=>n(new Error("Failed to load Stripe.js")),document.head.appendChild(r)})}var xt="https://secure.oceanpayment.com/pages/js/oceanpayment.js",be="oceanpayment-element";var Ot={fi:"en"};function We(s){var t;let e=(t=s==null?void 0:s.split(/[-_]/)[0])==null?void 0:t.toLowerCase();return e?Ot[e]??e:"en"}var Tt=3e4,J=null;function Ze(){let s=window;return s.Oceanpayment?Promise.resolve(s.Oceanpayment):J||(J=new Promise((e,t)=>{let n=document.createElement("script"),r=o=>{clearTimeout(i),n.remove(),J=null,t(new Error(o))},i=setTimeout(()=>r("The Ocean Payment card form took too long to load"),Tt);n.addEventListener("load",()=>{if(!s.Oceanpayment)return r("Ocean Payment script loaded without window.Oceanpayment");clearTimeout(i),e(s.Oceanpayment)}),n.addEventListener("error",()=>r("Failed to load the Ocean Payment card form")),n.src=xt,document.head.appendChild(n)}),J)}var ve="tgd:headless:oceanpayment:pending",_t=30*60*1e3;function Xe(s){try{sessionStorage.setItem(ve,JSON.stringify({paymentId:s,at:Date.now()}))}catch{}}function Nt(){try{let s=sessionStorage.getItem(ve);if(!s)return;sessionStorage.removeItem(ve);let{paymentId:e,at:t}=JSON.parse(s);return!e||!t||Date.now()-t>_t?void 0:e}catch{return}}function et(){if(typeof window>"u")return;let s=Nt();if(s)try{let e=new URL(window.location.href);if(e.searchParams.get("paymentId"))return;e.searchParams.set("paymentId",s),e.searchParams.set("paymentAction","requireAction"),e.searchParams.set("paymentActionStatus","completed"),window.history.replaceState(window.history.state,"",e.toString())}catch{}}function Lt(){return Promise.reject(new Error("This store takes payments through the Payments API, which the CDN build does not support yet: install @tagadapay/headless-sdk and @tagadapay/core-js 3.7.0 or later from npm."))}var tt=new Set(["failed","declined","rejected","error"]),q=null,Mt=()=>!!q&&(!q.attached||q.element.isConnected),nt=Symbol("ocean-timed-out"),rt=Symbol("ocean-unmounted"),Dt=new Set(["apple_pay","google_pay","paypal","klarna","klarna_express","link"]);function Ut(s){var o;let e=s.type==="credit-card",t=e?"card":s.type,n=s.settings??{},r=n.processors,i=n.publishableKey;return{enabled:!0,method:t,provider:e?void 0:s.type,type:e?"card":s.type,label:s.title,logoUrl:s.iconUrl,express:Dt.has(t),integrationId:e?void 0:s.id,processorId:(o=r==null?void 0:r[0])==null?void 0:o.processorId,publishableKey:typeof i=="string"?i:void 0,metadata:s.metadata??void 0}}var K=class{constructor(e,t,n,r,i,o){this.http=e;this.storeId=t;this.environment=n;this.checkout=r;this.onPaid=i;this.onSignal=o;this.lastPaymentSetup=null;this.paymentsApiStarts=new Map}async getPaymentSetup(e,t){if(t!=null&&t.paymentSetupConfig)return this.lastPaymentSetup=t.paymentSetupConfig,t.paymentSetupConfig;let n=this.readInjectedStepConfig();if(n)return this.lastPaymentSetup=n,n;try{let i=await this.http.get(`/api/v1/checkout-sessions/${e}/payment-setup`),o={...(i==null?void 0:i.config)??{}};return this.lastPaymentSetup=o,o}catch(i){if(!(i instanceof I))throw i}let r=await this.getPaymentSetupFromPickerList(e);return this.lastPaymentSetup=r,r}async getPaymentSetupFromPickerList(e){let t=await this.http.get("/api/v1/payment-methods",{params:{checkoutSessionId:e}}),n=Array.isArray(t)?t.map(Ut):(t==null?void 0:t.methods)??[],r={};for(let i of n){let o=i.provider&&i.provider!==i.method?`${i.method}:${i.provider}`:i.method;r[o]=i}return r}async getExpressMethods(e,t){var i,o,a,d,u,g,c,p,l,m;let n=await this.getPaymentSetup(e,t),r={};for(let[y,h]of Object.entries(n)){if(!h.enabled)continue;if(y.startsWith("express_checkout:")&&h.methods){let b={available:!0,processorId:h.processorId,publishableKey:h.publishableKey,metadata:h.metadata};if((i=h.methods.apple_pay)!=null&&i.enabled){let f=typeof window<"u"&&"ApplePaySession"in window&&((a=(o=window.ApplePaySession)==null?void 0:o.canMakePayments)==null?void 0:a.call(o));r.applePay={...b,type:"apple_pay",available:!!f}}(d=h.methods.google_pay)!=null&&d.enabled&&(typeof window<"u"&&!("PaymentRequest"in window)&&((u=this.onSignal)==null||u.call(this,"googlePay",{reason:"no-payment-request-api"})),r.googlePay={...b,type:"google_pay"}),(g=h.methods.link)!=null&&g.enabled&&(r.link={...b,type:"link"}),(c=h.methods.klarna_express)!=null&&c.enabled&&(r.klarna={...b,type:"klarna_express"});continue}if(!h.express)continue;let C=h.method,w={type:C,available:!0,processorId:h.processorId,publishableKey:h.publishableKey,metadata:h.metadata};if(C==="apple_pay"||h.type==="apple_pay"){let b=typeof window<"u"&&"ApplePaySession"in window&&((l=(p=window.ApplePaySession)==null?void 0:p.canMakePayments)==null?void 0:l.call(p));r.applePay={...w,available:!!b}}else C==="google_pay"||h.type==="google_pay"?(typeof window<"u"&&!("PaymentRequest"in window)&&((m=this.onSignal)==null||m.call(this,"googlePay",{reason:"no-payment-request-api"})),r.googlePay=w):C==="paypal"?r.paypal=w:C==="klarna"||C==="klarna_express"?r.klarna=w:C==="link"&&(r.link=w)}return r}async getStoreConfig(){let e=await this.http.get("/api/v1/checkout/config",{params:{storeId:this.storeId}});return e.config??e}async getEnabledMethods(e,t){let n=await this.getPaymentSetup(e,t);return Object.entries(n).filter(([,r])=>r.enabled).map(([r])=>r)}async tokenizeCard(e){let t=await this.loadCoreJs(),n=new t.Tokenizer({environment:this.environment});await n.initialize();let r={cardNumber:e.cardNumber,expiryDate:e.expiryDate,cvc:e.cvc};e.cardholderName&&(r.cardholderName=e.cardholderName);let i=await n.tokenizeCardRaw(r);return{tagadaToken:t.createTagadaToken(i,n.getProvider().getProviderName()),rawToken:i}}async createInstrument(e){return this.http.post("/api/v1/payment/create-instrument-from-token",{tagadaToken:e.tagadaToken})}async create3dsSession(e){return this.http.post("/api/public/v1/threeds/create-session",{provider:e.provider??"basis_theory",storeId:this.storeId,paymentInstrumentId:e.paymentInstrumentId,sessionData:e.sessionData})}async pay(e){return e.tagadaToken&&!e.paymentInstrumentId?this.rememberPaymentsApiStart(await this.http.post("/api/v1/payment/pay-with-token",{tagadaToken:e.tagadaToken,checkoutSessionId:e.checkoutSessionId,returnUrl:e.returnUrl,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:e.isExpress,metadata:e.metadata}),e):this.rememberPaymentsApiStart(await this.http.post("/api/public/v1/checkout/pay-v2",{checkoutSessionId:e.checkoutSessionId,paymentInstrumentId:e.paymentInstrumentId,storeId:this.storeId,paymentFlowId:e.paymentFlowId,threedsSessionId:e.threedsSessionId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:e.isExpress,metadata:e.metadata,returnUrl:e.returnUrl}),e)}async payDirect(e){return this.rememberPaymentsApiStart(await this.http.post("/api/public/v1/checkout/pay-v2",{checkoutSessionId:e.checkoutSessionId,paymentInstrumentId:e.paymentInstrumentId??"",storeId:this.storeId,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:e.isExpress,threedsSessionId:e.threedsSessionId,returnUrl:e.returnUrl}),e)}async syncWalletContact(e,t){let{shippingAddress:n,billingAddress:r}=t;if(!n&&!r)return;if(!this.checkout)throw new Error("PaymentModule cannot persist the wallet contact: no CheckoutModule was provided. Build the SDK through createTagadaClient() rather than constructing PaymentModule directly.");let i={};t.email&&(i.email=t.email),t.phone&&(i.phone=t.phone),t.firstName&&(i.firstName=t.firstName),t.lastName&&(i.lastName=t.lastName),await this.checkout.updateCustomerAndAddress(e,{customer:i,shippingAddress:n,billingAddress:r})}async processApplePay(e){var a,d,u,g,c,p,l,m,y;await this.syncWalletContact(e.checkoutSessionId,{shippingAddress:ae(e.shippingContact),billingAddress:ae(e.billingContact),email:((a=e.shippingContact)==null?void 0:a.emailAddress)??((d=e.billingContact)==null?void 0:d.emailAddress),phone:((u=e.shippingContact)==null?void 0:u.phoneNumber)??((g=e.billingContact)==null?void 0:g.phoneNumber),firstName:((c=e.shippingContact)==null?void 0:c.givenName)??((p=e.billingContact)==null?void 0:p.givenName),lastName:((l=e.shippingContact)==null?void 0:l.familyName)??((m=e.billingContact)==null?void 0:m.familyName)});let t=e.merchantRegistrationId??((y=await this.resolveApplePayRegistration(e.checkoutSessionId))==null?void 0:y.merchantRegistrationId),n=await this.loadCoreJs(),r=new n.Tokenizer({environment:this.environment});await r.initialize();let i=await r.tokenizeApplePay(e.applePayToken,t),o=btoa(JSON.stringify(n.createTagadaDigitalWalletToken(i,"apple_pay")));return this.pay({checkoutSessionId:e.checkoutSessionId,tagadaToken:o,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:"apple_pay",isExpress:!0})}async resolveApplePayRegistration(e){if(typeof window>"u")return null;let t=window.location.hostname.toLowerCase().split(":")[0];t.startsWith("www.")&&(t=t.slice(4));let n=i=>{var o;for(let a of Object.values(i??{})){let d=(o=a==null?void 0:a.metadata)==null?void 0:o.applePayByok;if(!d||typeof d!="object")continue;let u=d[t];if(u!=null&&u.merchantRegistrationId)return{merchantRegistrationId:u.merchantRegistrationId,displayName:u.displayName}}return null},r=n(this.readInjectedStepConfig())??n(this.lastPaymentSetup);if(r)return r;if(this.lastPaymentSetup||this.readInjectedStepConfig()||!e)return null;try{return n(await this.getPaymentSetup(e))}catch{return null}}async processGooglePay(e){var o,a,d,u;await this.syncWalletContact(e.checkoutSessionId,{shippingAddress:de(e.shippingAddress),billingAddress:de(e.billingAddress),email:e.email??((o=e.shippingAddress)==null?void 0:o.emailAddress)??((a=e.billingAddress)==null?void 0:a.emailAddress),phone:((d=e.shippingAddress)==null?void 0:d.phoneNumber)??((u=e.billingAddress)==null?void 0:u.phoneNumber)});let t=await this.loadCoreJs(),n=new t.Tokenizer({environment:this.environment});await n.initialize();let r=await n.tokenizeGooglePay(e.googlePayToken),i=btoa(JSON.stringify(t.createTagadaDigitalWalletToken(r,"google_pay")));return this.pay({checkoutSessionId:e.checkoutSessionId,tagadaToken:i,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:"google_pay",isExpress:!0})}async processApm(e){return this.payDirect({checkoutSessionId:e.checkoutSessionId,paymentMethod:e.paymentMethod,processorId:e.processorId,paymentFlowId:e.paymentFlowId,returnUrl:e.returnUrl??(typeof window<"u"?window.location.href:void 0)})}async processStripeExpress(e){return this.payDirect({checkoutSessionId:e.checkoutSessionId,processorId:e.processorId,paymentMethod:e.paymentMethod,isExpress:!0})}async getCryptoOnchainOptions(e){return this.http.get(`/api/v1/checkout-sessions/${encodeURIComponent(e)}/crypto-onchain/options`)}async createCryptoOnchainPayment(e){return this.http.post(`/api/v1/checkout-sessions/${encodeURIComponent(e.checkoutSessionId)}/crypto-onchain/session`,{chainId:e.chainId,asset:e.asset})}async getCryptoOnchainStatus(e){return this.http.get(`/api/v1/checkout-sessions/${encodeURIComponent(e.checkoutSessionId)}/crypto-onchain/status`,{params:{cryptoOnchainPaymentId:e.cryptoOnchainPaymentId}})}createCryptoOnchainCheckout(e){return new F(this,e)}async getOceanPaymentConfig(e){let t=await this.http.post(`/api/v1/checkout-sessions/${e}/oceanpayment-embedded-config`,{});return{embedded:!!(t!=null&&t.embedded),sandboxed:!!(t!=null&&t.sandboxed)}}async mountOceanPayment(e){if(typeof window>"u")throw new Error("Ocean Payment needs a browser");let{checkoutSessionId:t,signal:n}=e,r=()=>Object.assign(new Error("Ocean Payment mount aborted"),{name:"AbortError"});if(n!=null&&n.aborted)throw r();let i=typeof e.container=="string"?document.querySelector(e.container):e.container;if(!i&&e.mode!=="redirect")throw new Error(`Ocean Payment container not found: ${String(e.container)}`);if(Mt()||document.getElementById(be))throw new Error("An Ocean Payment card form is already mounted on this page");let o=window,a=document.createElement("div");a.id=be;let d={element:a,attached:!1};q=d;let u=()=>{q===d&&(q=null)},g=!0,c=null,p=f=>{let k=c;c=null,k==null||k(f)},l=()=>{g&&(g=!1,o.oceanpaymentCallBack===p&&delete o.oceanpaymentCallBack,a.remove(),u(),p(rt))};n==null||n.addEventListener("abort",l,{once:!0});let m,y;try{if(m=e.mode==="redirect"?{embedded:!1,sandboxed:!1}:await this.getOceanPaymentConfig(t),n!=null&&n.aborted||m.embedded&&(y=await Ze(),n!=null&&n.aborted))throw r()}catch(f){throw l(),f}let h=!1;if(!y)return u(),{mode:"redirect",pay:async()=>{if(!g)return{status:"failed",error:"The Ocean Payment form was removed"};if(h)return{status:"failed",error:"Payment already in progress"};h=!0;try{let f=await this.http.post(`/api/v1/checkout-sessions/${t}/oceanpayment-link`,{returnUrl:e.returnUrl??window.location.href});return!(f!=null&&f.url)||!f.paymentId?{status:"failed",error:"Ocean Payment is not available for this store"}:{status:"requires_redirect",redirectUrl:f.url,method:"GET",paymentId:f.paymentId}}catch(f){return{status:"failed",error:f instanceof Error?f.message:String(f)}}finally{h=!1}},unmount:l};let C=y;i.appendChild(a),d.attached=!0,o.oceanpaymentCallBack=p;let w=window.location.href;return C.init(m.sandboxed,"",We(e.locale),{showCardName:!1}),{mode:"embedded",pay:async()=>{if(!g)return{status:"failed",error:"The Ocean Payment card form was removed"};if(h)return{status:"failed",error:"Payment already in progress"};h=!0;try{let f=await this.http.post(`/api/v1/checkout-sessions/${t}/oceanpayment-embedded-payment`,{backUrl:w});if(!(f!=null&&f.paymentId)||!f.params)return{status:"failed",error:"Failed to start the payment"};let k=f.paymentId,A=await new Promise(Ne=>{let ct=setTimeout(()=>{c=null,Ne(nt)},12e4);c=ut=>{clearTimeout(ct),Ne(ut)},C.checkout(f.params)});if(A===nt||A===rt)return this.pollUntilDone(k);if(A&&typeof A=="object"&&"msg"in A)return{status:"failed",error:String(A.msg||"Please check your card details.")};let S=await this.http.post(`/api/v1/checkout-sessions/${t}/oceanpayment-embedded-result`,{paymentId:k,response:String(A)});return(S==null?void 0:S.status)==="requires_action"&&S.payUrl?(Xe(k),{status:"requires_redirect",redirectUrl:S.payUrl,method:"GET",paymentId:k}):(S==null?void 0:S.status)==="succeeded"||(S==null?void 0:S.status)==="pending"?this.pollUntilDone(k):{status:"failed",error:(S==null?void 0:S.message)||"Payment declined"}}catch(f){return{status:"failed",error:f instanceof Error?f.message:String(f)}}finally{h=!1}},unmount:l}}async processPayment(e){!e.returnUrl&&typeof window<"u"&&(e={...e,returnUrl:window.location.href});let t=await this.pay(e);return this.finalize(t,{returnUrl:e.returnUrl})}async finalize(e,t){var i,o,a;let n=e.payment,r=(t==null?void 0:t.returnUrl)??(typeof window<"u"?window.location.href:void 0);if(!n){let d=Ie(e);if(d)return this.finalizeOnPaymentsApi(d,r)}return n.status==="succeeded"?(this.emitPaid((i=e.order)==null?void 0:i.id,n),{status:"succeeded",payment:n,order:e.order}):n.status==="failed"||n.status==="declined"?{status:"failed",error:((o=n.requireActionData)==null?void 0:o.message)||((a=n.requireActionData)==null?void 0:a.errorCode)||`Payment ${n.status}`,payment:n}:n.requireAction&&n.requireAction!=="none"&&n.requireActionData?this.handlePaymentAction(n,{returnUrl:r}):this.pollUntilDone(n.id)}async resumeAfterRedirect(e){let t=Ye(e);if(t){let n=typeof window<"u"?window.location.href:void 0;return this.onPaymentsApi((r,i)=>r.resumeOnPaymentsApi(i,e,t.checkoutSessionId,n))}return this.pollUntilDone(e)}async maybeResumeFromUrl(e){if(typeof window>"u"&&!(e!=null&&e.url))return null;e!=null&&e.url||et();let t=(e==null?void 0:e.url)??window.location.href,n;try{n=new URL(t)}catch{return null}let r=n.searchParams.get("paymentAction"),i=n.searchParams.get("paymentActionStatus"),o=n.searchParams.get("paymentId");if(r!=="requireAction"||i!=="completed"||!o)return null;let a=await this.resumeAfterRedirect(o);if((e==null?void 0:e.cleanUrl)!==!1&&typeof window<"u"&&!(e!=null&&e.url)){let d=new URLSearchParams(window.location.search);["paymentAction","paymentActionStatus","paymentId","payment_intent","payment_intent_client_secret","source_type","redirect_status","sessionId"].forEach(g=>d.delete(g));let u=d.toString();try{window.history.replaceState({},document.title,window.location.pathname+(u?"?"+u:""))}catch{}}return a}async getPaymentStatus(e){return this.http.get(`/api/v1/payments/${e}`)}async pollPaymentStatus(e,t){let n=(t==null?void 0:t.intervalMs)??1500,r=(t==null?void 0:t.timeoutMs)??6e4,i=Date.now();for(;Date.now()-i<r;){let o=await this.getPaymentStatus(e);if(o.status==="succeeded"||tt.has(o.status))return o;await new Promise(a=>setTimeout(a,n))}throw new Error(`Payment ${e} did not reach terminal status within ${r}ms.`)}async completeAfter3ds(e){return this.http.post("/api/v1/payments/complete-after-3ds",{paymentId:e})}async markActionProcessed(e){try{await this.http.post("/api/v1/payments/require-action/processed",{paymentId:e})}catch{}}async handlePaymentAction(e,t){let n=e.requireActionData;switch(await this.markActionProcessed(e.id),n.type){case"threeds_auth":return this.handleThreedsAuth(e,t);case"processor_auth":case"redirect_to_payment":return this.extractRedirect(e,n);case"redirect":return this.extractRedirect(e,n);case"stripe_radar":return this.handleStripeRadar(e);case"error":return{status:"failed",error:n.message||n.errorCode||"Payment failed",payment:e};default:return this.extractRedirect(e,n)}}extractRedirect(e,t){var i,o;let n=(i=t.metadata)==null?void 0:i.redirect,r=(n==null?void 0:n.redirectUrl)||t.redirectUrl;return r?{status:"requires_redirect",redirectUrl:r,method:((o=n==null?void 0:n.method)==null?void 0:o.toUpperCase())||"GET",postData:n==null?void 0:n.data,paymentId:e.id}:{status:"failed",error:`Payment requires action (${t.type}) but no redirect URL was provided`,payment:e}}async handleThreedsAuth(e,t){var i,o;let n=(o=(i=e.requireActionData)==null?void 0:i.metadata)==null?void 0:o.threedsSession;if(!(n!=null&&n.externalSessionId))return this.extractRedirect(e,e.requireActionData);let r;try{r=await import("@tagadapay/core-js")}catch{return n.acsChallengeUrl?{status:"requires_redirect",redirectUrl:n.acsChallengeUrl,paymentId:e.id}:this.extractRedirect(e,e.requireActionData)}try{let a=new r.ThreedsManager({provider:"basis_theory"});return await a.initialize({apiKey:void 0}),await a.startChallenge({sessionId:n.externalSessionId,acsChallengeUrl:n.acsChallengeUrl,acsTransactionId:n.acsTransID,threeDSVersion:n.messageVersion}),await this.completeAfter3ds(e.id),this.pollUntilDone(e.id)}catch{return n.acsChallengeUrl?{status:"requires_redirect",redirectUrl:n.acsChallengeUrl,paymentId:e.id}:{status:"failed",error:"3D Secure authentication failed",payment:e}}}async handleStripeRadar(e){var n,r;let t=(r=(n=e.requireActionData)==null?void 0:n.metadata)==null?void 0:r.radar;if(!(t!=null&&t.publishableKey))return{status:"failed",error:"Stripe Radar configuration missing",payment:e};try{let i=await Qe(),{radarSession:o,error:a}=await i(t.publishableKey).createRadarSession();if(a||!o)throw new Error((a==null?void 0:a.message)||"No Radar session returned by Stripe");return await this.http.post("/api/v1/radar-sessions",{orderId:t.orderId,paymentId:e.id,stripeRadarSessionId:o.id,stripeRadarSessionData:o}),await this.completeAfter3ds(e.id),this.pollUntilDone(e.id)}catch(i){return{status:"failed",error:i instanceof Error?i.message:"Stripe Radar failed",payment:e}}}async pollUntilDone(e,t){var a;let n=(t==null?void 0:t.intervalMs)??1500,r=(t==null?void 0:t.timeoutMs)??6e4,i=Date.now(),o=0;for(;Date.now()-i<r;){let d;try{d=await this.getPaymentStatus(e),o=0}catch{if(o++,o>=3)return{status:"failed",error:"Payment verification failed due to network errors"};await new Promise(u=>setTimeout(u,n));continue}if(d.status==="succeeded"||d.status==="pending"&&d.subStatus==="authorized")return d.status==="succeeded"&&this.emitPaid((a=d.order)==null?void 0:a.id,d),{status:"succeeded",payment:d,order:d.order};if(tt.has(d.status))return{status:"failed",error:d.status,payment:d};if(d.requireAction&&d.requireAction!=="none"&&d.requireActionData&&!d.requireActionData.processed)return this.handlePaymentAction(d,{});await new Promise(u=>setTimeout(u,n))}return{status:"pending",paymentId:e}}rememberPaymentsApiStart(e,t){let n=e&&!e.payment?Ie(e):null;return n&&this.paymentsApiStarts.set(n.paymentId,{checkoutSessionId:n.checkoutSessionId??t.checkoutSessionId,...t.paymentMethod?{paymentMethod:t.paymentMethod}:{}}),e}finalizeOnPaymentsApi(e,t){let n=this.paymentsApiStarts.get(e.paymentId);return this.paymentsApiStarts.delete(e.paymentId),this.onPaymentsApi((r,i)=>r.finalizeOnPaymentsApi(i,e,{checkoutSessionId:n==null?void 0:n.checkoutSessionId,paymentMethod:n==null?void 0:n.paymentMethod,returnUrl:t}))}async onPaymentsApi(e){let t;try{t=await Lt()}catch(n){return{status:"failed",error:n instanceof Error?n.message:String(n)}}return e(t,{http:this.http,storeId:this.storeId,checkout:this.checkout,stepConfig:this.readInjectedStepConfigRaw(),onPaid:(n,r)=>this.emitPaid(n,r)})}readInjectedStepConfig(){if(typeof window>"u")return null;let e=window.__TGD_STEP_CONFIG__;if(!e)return null;try{let t=typeof e=="string"?JSON.parse(e):e;return(t==null?void 0:t.paymentSetupConfig)??null}catch{return null}}readInjectedStepConfigRaw(){if(typeof window>"u")return null;let e=window.__TGD_STEP_CONFIG__;if(!e)return null;try{return typeof e=="string"?JSON.parse(e):e}catch{return null}}emitPaid(e,t){var n;if(!(!e||!this.onPaid))try{let r=(n=this.checkout)==null?void 0:n.getCurrentSession();this.onPaid({orderId:e,amount:t.amount,currency:t.currency,items:ce(r==null?void 0:r.items)})}catch{}}async loadCoreJs(){try{return await import("@tagadapay/core-js")}catch(e){let t=new Error("This method requires @tagadapay/core-js. Install it: npm install @tagadapay/core-js");throw t.cause=e,t}}};var v=typeof document>"u"?null:document.currentScript,Ft=v!=null&&v.src?new URL("tagada-headless-commerce.min.js",v.src).href:"https://cdn.jsdelivr.net/npm/@tagadapay/headless-sdk@1.23.0/dist/tagada-headless-commerce.min.js",pe;function $(){return window.TagadaHeadlessCommerce?Promise.resolve(window.TagadaHeadlessCommerce):(pe||(pe=new Promise((s,e)=>{let t=document.createElement("script");t.src=Ft,t.async=!0,v!=null&&v.nonce&&(t.nonce=v.nonce),t.addEventListener("load",()=>window.TagadaHeadlessCommerce?s(window.TagadaHeadlessCommerce):e(new Error("Commerce bundle did not initialize"))),t.addEventListener("error",()=>{t.remove(),e(new Error("Unable to load commerce bundle"))}),document.head.appendChild(t)}).catch(s=>{throw pe=void 0,s})),pe)}var T=class{constructor(...e){this.args=e}load(){return this.instance||(this.instance=$().then(e=>new e.OffersModule(...this.args)).catch(e=>{throw this.instance=void 0,e}))}};for(let s of["getOffer","listOffers","previewOffer","enterFunnelStep","payPreviewedOffer","processOfferPayment","toggleOrderBump","listPostPurchaseOffers","acceptPostPurchaseOffer","declinePostPurchaseOffer"])T.prototype[s]=function(...e){return this.load().then(t=>t[s](...e))};var _=class{constructor(...e){this.args=e}load(){return this.instance||(this.instance=$().then(e=>new e.CustomerModule(...this.args)).catch(e=>{throw this.instance=void 0,e}))}};for(let s of["getProfile","getByEmail","updateProfile","getOrders","getOrder","getSubscriptions","getSubscription","pauseSubscription","resumeSubscription","skipSubscription","rescheduleSubscription","updateSubscriptionQuantity","changeSubscriptionFrequency","swapSubscriptionProduct","updateSubscriptionPaymentMethod","cancelSubscription"])_.prototype[s]=function(...e){return this.load().then(t=>t[s](...e))};var N=class{constructor(...e){this.args=e}load(){return this.instance||(this.instance=$().then(e=>new e.CustomerPortalModule(...this.args)).catch(e=>{throw this.instance=void 0,e}))}};for(let s of["requestCode","verifyCode","getConfig","getMe","cancelFlow","acceptCancelOffer","switchOption","getOffer","acceptOffer","addToNextOrder","getCredits","redeemCredits","buyCreditPack","requestEmailChangeCode","updateProfile","saveAddress","removeAddress","setDefaultAddress","addCard","removeCard","setDefaultPaymentMethod","retryPayment","buyAgain","joinMembership","buyNow","sendNow","reactivateSubscription","setSubscriptionCard","setSubscriptionAddress","skipDate","unskipDate"])N.prototype[s]=function(...e){return this.load().then(t=>t[s](...e))};var j=class{constructor(e,t){this.http=e;this.storeId=t}async getProducts(e){var r,i;let t={storeId:this.storeId,includeVariants:!0,includePrices:!0};return(r=e==null?void 0:e.productIds)!=null&&r.length&&(t.productIds=e.productIds),(i=e==null?void 0:e.variantIds)!=null&&i.length&&(t.variantIds=e.variantIds),(await this.http.post("/api/v1/products",t)).items??[]}async getProduct(e){return(await this.getProducts({productIds:[e]}))[0]??null}};var H=class{constructor(e,t,n,r,i){this.http=e;this.storeId=t;this.checkout=n;this.accountId=r;this.onFunnelSession=i}async navigate(e){var a,d;let t=this.checkout.getCurrentSession();if(!t)throw new P("No checkout session loaded. Call sdk.checkout.loadSession(...) before sdk.funnel.navigate(...).","no_cart_loaded");let n=e.accountId??this.accountId;if(!n)throw new P("accountId is required for funnel.navigate(). Set it on createHeadlessClient({ accountId }) or pass it per call.","missing_account_id");let r=e.currentUrl??(typeof globalThis<"u"?(a=globalThis.location)==null?void 0:a.href:void 0);await this.ensureCmsSession(t,n,e);let i=await this.initializeFunnel({funnelId:e.funnelId,stepId:e.stepId,accountId:n,currentUrl:r});try{(d=this.onFunnelSession)==null||d.call(this,i)}catch{}return{url:await this.runNavigate({funnelSessionId:i,stepId:e.stepId,session:t,input:e,currentUrl:r}),funnelSessionId:i}}async ensureCmsSession(e,t,n){var o,a,d;if(this._cmsToken&&this._cmsSessionId&&this._cmsCustomerId)return;let r=await this.http.post("/api/v1/cms/session/anonymous",{storeId:this.storeId,role:"anonymous",draft:!1});this._cmsToken=r.token,this._cmsSessionId=r.sessionId;let i=await this.http.post("/api/v1/cms/session/v2/init",{storeId:this.storeId,accountId:t,customerId:"anon_placeholder",browserLocale:((o=n.customer)==null?void 0:o.locale)??qt(),userAgent:Kt(),queryCurrency:((a=n.customer)==null?void 0:a.currency)??e.currency,queryLocale:(d=n.customer)==null?void 0:d.locale},{token:this._cmsToken});this._cmsCustomerId=i.customer.id}async initializeFunnel(e){return(await this.http.post("/api/v1/funnel/initialize",{cmsSession:{customerId:this._cmsCustomerId,sessionId:this._cmsSessionId,storeId:this.storeId,accountId:e.accountId},funnelId:e.funnelId,entryStepId:e.stepId,funnelStepId:e.stepId,currentUrl:e.currentUrl,draft:!1},{token:this._cmsToken})).context.sessionId}async runNavigate(e){var c,p,l,m;let{funnelSessionId:t,stepId:n,session:r,input:i,currentUrl:o}=e,a=r.items.map(y=>({variantId:y.variantId,priceId:y.priceId,quantity:y.quantity})),d=i.discountCodes??(r.promotionCode?[r.promotionCode]:void 0),u={email:((c=i.customer)==null?void 0:c.email)??((p=r.customer)==null?void 0:p.email),currency:((l=i.customer)==null?void 0:l.currency)??r.currency,locale:(m=i.customer)==null?void 0:m.locale};return(await this.http.post("/api/v1/funnel/navigate",{sessionId:t,currentUrl:o,funnelStepId:n,fireAndForget:!1,event:{type:"INIT_CHECKOUT",data:{checkoutInit:{cartToken:r.id,lineItems:a,customer:u,returnUrl:i.returnUrl,storeId:this.storeId,metadata:i.metadata,discountCodes:d,externalShipping:i.externalShipping}}}},{token:this._cmsToken})).result.url}};function qt(){return typeof navigator<"u"&&navigator.language?navigator.language:"en-US"}function Kt(){return typeof navigator<"u"&&navigator.userAgent?navigator.userAgent:"tagadapay-headless-sdk"}var me=(s,e)=>e!==null&&String(s).trim().toLowerCase()===e.trim().toLowerCase();function Ae(s,e,t={}){if(s.visible===!1||s.type==="file")return!1;let n=s.rules??[];return n.length===0?!0:n.some(r=>{let i=o=>{if(o.basedOn==="state")return me(t.state??"",o.answer);if(o.basedOn==="other"&&o.questionId==="patient_sex")return me(t.sexAtBirth??"",o.answer);if(o.basedOn==="question"&&o.questionId){let a=e[o.questionId];return a===void 0?!1:Array.isArray(a)?a.some(d=>me(d,o.answer)):me(a,o.answer)}return!1};return r.op==="and"?r.requirements.every(i):r.requirements.some(i)})}function st(s,e,t={}){let n=[];for(let r of s){if(r.visible===!1){r.defaultValue&&n.push({questionId:r.title,question:r.title,value:r.defaultValue,type:"string"});continue}if(!Ae(r,e,t))continue;let i=e[r.externalQuestionId];i===void 0||typeof i=="string"&&i.trim()===""||n.push({questionId:r.title,question:r.title,value:i,type:r.type==="number"?"number":r.type==="boolean"?"boolean":"string",...r.options.length>0?{displayedOptions:r.options.map(o=>o.label)}:{}})}return n}var G=class{constructor(e,t){this.http=e;this.storeId=t}async getActivationStatus(e){let t=e??this.storeId;if(!t)throw new Error("rx.getActivationStatus: storeId is required");return this.http.get("/api/public/v1/rx/activation-status",{params:{storeId:t}})}async isRequiredForProduct(e,t){return this.http.get("/api/public/v1/rx/required-for-product",{params:{productId:e,clinicalNetworkId:t==null?void 0:t.clinicalNetworkId}})}async getCasesForOrder(e){return this.http.post("/api/public/v1/rx/cases/lookup",e)}async getIntakeContext(e){return this.http.post("/api/public/v1/rx/intake/context",e)}async submitCase(e){return this.http.post("/api/public/v1/rx/cases/submit",e)}async validateIntake(e){return this.http.post("/api/public/v1/rx/intake/validate",e)}async getQuestionsForProduct(e,t){return this.http.get("/api/public/v1/rx/questions-for-product",{params:t?{productId:e,variantId:t}:{productId:e}})}};var B=class{constructor(e,t){this.core=e;this.bootstrap=t;this.runtime=null;this.loading=null;this.settled=!1;this.reads=new Set;this.subscribers=[]}variant(e){var t,n,r,i;return((n=(t=this.bootstrap)==null?void 0:t.experiments[e])==null?void 0:n.arm)??((i=(r=this.bootstrap)==null?void 0:r.flags[e])==null?void 0:i.variant)??null}start(){return typeof window>"u"?Promise.resolve():(this.loading??(this.loading=(async()=>{try{this.runtime=await this.core()}catch{}this.settled=!0;let e=this.runtime;for(let t of this.reads)try{e==null||e.getVariant(t)}catch{}this.reads.clear();for(let{key:t,cb:n}of this.subscribers.splice(0))try{e?e.onVariant(t,n):n(this.variant(t))}catch{}try{await(e==null?void 0:e.ready())}catch{}})()),this.loading)}read(e){this.settled||this.reads.add(e),this.start()}getVariant(e){return this.runtime?this.runtime.getVariant(e):(this.read(e),this.variant(e))}getPayload(e){var t,n,r,i;return this.runtime?this.runtime.getPayload(e):(this.read(e),((n=(t=this.bootstrap)==null?void 0:t.experiments[e])==null?void 0:n.payload)??((i=(r=this.bootstrap)==null?void 0:r.flags[e])==null?void 0:i.payload)??null)}isEnabled(e){var t,n;return this.runtime?this.runtime.isEnabled(e):(this.read(e),((n=(t=this.bootstrap)==null?void 0:t.flags[e])==null?void 0:n.enabled)??!1)}onVariant(e,t){if(this.runtime){this.runtime.onVariant(e,t);return}if(this.settled){t(this.variant(e));return}this.subscribers.push({key:e,cb:t}),this.start()}ready(){return this.start()}};var Y=class{constructor(e){let t=e.environment??"production",n=x.resolveBaseUrl(t,e.baseUrl);this.config={...e,environment:t,baseUrl:n,timeout:e.timeout??3e4},this.http=new x({baseUrl:n,timeout:this.config.timeout,apiKey:e.apiKey,getToken:()=>this._sessionToken}),this.track=new U(n,this.config.storeId,this.config.funnel??"main"),this.track.bootstrap=this.config.bootstrap,this.experiments=new B(()=>this.track.core(),this.config.bootstrap);let r=i=>{this._sessionToken=i};this.checkout=new O(this.http,this.config.storeId,r,i=>this.track.noteCheckout({checkoutSessionId:i.id,amount:i.totals.total,currency:i.totals.currency,items:ce(i.items)})),this.payment=new K(this.http,this.config.storeId,t,this.checkout,i=>this.track.notePaid(i),(i,o)=>this.track.noteSignal("wallet_unavailable",i,o)),this.offers=new T(this.http,this.config.storeId,this.payment),this.customer=new _(this.http,this.config.storeId),this.portal=new N(this.http,this.config.storeId,r),this.catalog=new j(this.http,this.config.storeId),this.funnel=new H(this.http,this.config.storeId,this.checkout,this.config.accountId,i=>this.track.noteFunnelSession(i)),this.rx=new G(this.http,this.config.storeId)}setSessionToken(e){this._sessionToken=e}};function it(s){return new Y(s)}var ot=!1,at=!1,ge=[];function Re(){at=!0;for(let s of ge)s();ge.length=0}function xe(s,e={}){var t,n;return at||(n=(t=window.google)==null?void 0:t.maps)!=null&&n.places?(Re(),Promise.resolve()):ot?new Promise(r=>ge.push(r)):(ot=!0,new Promise((r,i)=>{if(ge.push(r),document.querySelector('script[src*="maps.googleapis.com"]')){let u=()=>{var g,c;(c=(g=window.google)==null?void 0:g.maps)!=null&&c.places?Re():setTimeout(u,100)};u();return}let a=new URLSearchParams({key:s,libraries:"places",v:e.version??"weekly"});e.language&&a.set("language",e.language),e.region&&a.set("region",e.region);let d=document.createElement("script");d.src=`https://maps.googleapis.com/maps/api/js?${a}`,d.async=!0,d.defer=!0,d.onload=()=>Re(),d.onerror=()=>i(new Error("Failed to load Google Maps script")),document.head.appendChild(d)}))}var Q=class s{static async searchPlaces(e,t={}){var r,i;if(!((i=(r=window.google)==null?void 0:r.maps)!=null&&i.places)||!e.trim())return[];let n=new window.google.maps.places.AutocompleteService;return new Promise(o=>{n.getPlacePredictions({input:e,types:t.types??["address"],componentRestrictions:t.componentRestrictions},(a,d)=>{var u,g,c;o(d===((c=(g=(u=window.google)==null?void 0:u.maps)==null?void 0:g.places)==null?void 0:c.PlacesServiceStatus.OK)&&a?a:[])})})}static async getPlaceDetails(e){var n,r;if(!((r=(n=window.google)==null?void 0:n.maps)!=null&&r.places))return null;let t=new window.google.maps.places.PlacesService(document.createElement("div"));return new Promise(i=>{t.getDetails({placeId:e,fields:["place_id","formatted_address","address_components","geometry"]},(o,a)=>{var d,u,g;i(a===((g=(u=(d=window.google)==null?void 0:d.maps)==null?void 0:u.places)==null?void 0:g.PlacesServiceStatus.OK)&&o?o:null)})})}static extractAddressComponents(e){let t={subpremise:"",streetNumber:"",route:"",locality:"",administrativeAreaLevel1:"",administrativeAreaLevel1Long:"",administrativeAreaLevel2:"",administrativeAreaLevel2Long:"",country:"",postalCode:"",fullStreetAddress:""},n="",r="",i="",o="",a="",d="",u="",g="";for(let l of e.address_components??[]){let m=l.types;m.includes("subpremise")&&(t.subpremise=l.long_name),m.includes("street_number")&&(t.streetNumber=l.long_name),m.includes("premise")&&(n=l.long_name),m.includes("route")&&(t.route=l.long_name),m.includes("neighborhood")&&(r=l.long_name),m.includes("sublocality_level_5")&&(i=l.long_name),m.includes("sublocality_level_4")&&(o=l.long_name),m.includes("sublocality_level_3")&&(a=l.long_name),m.includes("sublocality_level_2")&&(d=l.long_name),m.includes("sublocality_level_1")&&(u=l.long_name),m.includes("locality")&&(t.locality=l.long_name),m.includes("postal_town")&&(g=l.long_name),m.includes("administrative_area_level_2")&&(t.administrativeAreaLevel2=l.short_name,t.administrativeAreaLevel2Long=l.long_name),m.includes("administrative_area_level_1")&&(t.administrativeAreaLevel1=l.short_name,t.administrativeAreaLevel1Long=l.long_name),m.includes("country")&&(t.country=l.short_name),m.includes("postal_code")&&(t.postalCode=l.long_name)}t.locality||(t.locality=g||d||u||""),!t.administrativeAreaLevel1&&t.administrativeAreaLevel2&&(t.administrativeAreaLevel1=t.administrativeAreaLevel2Long||t.administrativeAreaLevel2,t.administrativeAreaLevel1Long=t.administrativeAreaLevel2Long);let c=t.streetNumber||n,p=t.route||i||o||a||r;if(t.subpremise&&c&&p)t.fullStreetAddress=`${t.subpremise}/${c} ${p}`;else if(c&&p)if(n&&o&&a){let l=`${a}-${o}-${n}`;d&&(l=`${l} ${d}`),t.fullStreetAddress=l}else t.fullStreetAddress=`${c} ${p}`;else p?t.fullStreetAddress=p:c&&(t.fullStreetAddress=c);return t.fullStreetAddress=t.fullStreetAddress.trim(),t}static extractFormattedAddress(e){let t=s.extractAddressComponents(e);return{address1:t.fullStreetAddress,city:t.locality,country:t.country,state:t.administrativeAreaLevel1,postal:t.postalCode}}};var dt="https://cvwnizdbugpz6jwk.public.blob.vercel-storage.com/geodata/v1",Z=["en","ru","de","da","fr","es","zh","hi","pt","ja","ar","it","he"],W=new Map,he=new Map,Oe=new Map,Te=new Map;async function $t(s){let e=W.get(s);if(e)return e;let t=Oe.get(s);return t||(t=(async()=>{let n=`${dt}/${s}/countries.json`,r=await fetch(n);if(!r.ok)throw new Error(`Geodata fetch failed: ${n} (${r.status})`);let i=await r.json();return W.set(s,i),Oe.delete(s),i})(),Oe.set(s,t),t)}async function jt(s){let e=he.get(s);if(e)return e;let t=Te.get(s);return t||(t=(async()=>{let n=`${dt}/${s}/regions.json`,r=await fetch(n);if(!r.ok)throw new Error(`Geodata fetch failed: ${n} (${r.status})`);let i=await r.json();return he.set(s,i),Te.delete(s),i})(),Te.set(s,t),t)}function Ht(s){return W.get(s)||W.get("en")||{}}function Gt(s){return he.get(s)||he.get("en")||{}}async function X(s="en"){await Promise.all([$t(s),jt(s)])}var V=(s="en")=>{let e=Ht(s);return Object.entries(e).map(([t,n])=>({code:t,name:n.n,iso3:n.i3,numeric:n.nu})).sort((t,n)=>t.name.localeCompare(n.name))},ee=(s,e="en")=>{let n=Gt(e)[s];return n?n.map(([r,i])=>({code:r,name:i,countryCode:s})).sort((r,i)=>r.name.localeCompare(i.name)):[]};function te(s){return W.has(s)}var ne=class s{static ensureLoaded(e="en"){return X(e)}static getCountries(e="en"){let t=V(e),n={};for(let r of t)n[r.code]={iso:r.code,iso3:r.iso3??"",numeric:r.numeric??0,name:r.name};return n}static getCountryOptions(e="en"){return V(e).map(t=>({value:t.code,label:t.name}))}static getRegions(e,t="en"){return ee(e,t).map(n=>({iso:n.code,name:n.name}))}static getRegionOptions(e,t="en"){return s.getRegions(e,t).map(n=>({value:n.iso,label:n.name}))}static findRegion(e,t,n="en"){return s.getRegions(e,n).find(r=>r.iso===t)??null}static mapGoogleToISO(e,t,n,r="en"){let i=s.getRegions(n,r);if(i.length===0)return null;let o=i.find(a=>a.iso===e);return o||(o=i.find(a=>a.name.toLowerCase()===e.toLowerCase()),o)||(o=i.find(a=>a.name.toLowerCase()===t.toLowerCase()),o)?o:(o=i.find(a=>a.name.toLowerCase().includes(t.toLowerCase())||t.toLowerCase().includes(a.name.toLowerCase())),o??null)}static isLanguageLoaded(e){return te(e)}static getAvailableLanguages(){return Z}};var Bt={USD:"$",EUR:"\u20AC",GBP:"\xA3",JPY:"\xA5",CAD:"C$",AUD:"A$",CHF:"CHF",CNY:"\xA5",SEK:"kr",NOK:"kr",DKK:"kr",PLN:"z\u0142",CZK:"K\u010D",HUF:"Ft",RON:"lei",BGN:"\u043B\u0432",HRK:"kn",RUB:"\u20BD",UAH:"\u20B4",TRY:"\u20BA",BRL:"R$",MXN:"$",ZAR:"R",INR:"\u20B9",KRW:"\u20A9",THB:"\u0E3F",VND:"\u20AB",IDR:"Rp",MYR:"RM",SGD:"S$",PHP:"\u20B1",TWD:"NT$",HKD:"HK$",ILS:"\u20AA",AED:"\u062F.\u0625",SAR:"\u0631.\u0633",QAR:"\u0631.\u0642",KWD:"\u062F.\u0643",BHD:"\u062F.\u0628",OMR:"\u0631.\u0639.",EGP:"\xA3",NGN:"\u20A6",KES:"KSh",GHS:"\u20B5",COP:"$",ARS:"$",CLP:"$",PEN:"S/",CRC:"\u20A1",DOP:"RD$",JMD:"J$",BOB:"Bs",PYG:"\u20B2",GTQ:"Q",NIO:"C$",PAB:"B/.",PKR:"\u20A8",BDT:"\u09F3",LKR:"\u20A8",NPR:"\u20A8",GEL:"\u20BE",AMD:"\u058F",AZN:"\u20BC",KZT:"\u20B8"},Vt={USD:"US Dollar",EUR:"Euro",GBP:"British Pound",JPY:"Japanese Yen",CAD:"Canadian Dollar",AUD:"Australian Dollar",CHF:"Swiss Franc",CNY:"Chinese Yuan",SEK:"Swedish Krona",NOK:"Norwegian Krone",DKK:"Danish Krone",PLN:"Polish Zloty",CZK:"Czech Koruna",HUF:"Hungarian Forint",BRL:"Brazilian Real",MXN:"Mexican Peso",INR:"Indian Rupee",KRW:"South Korean Won",THB:"Thai Baht",SGD:"Singapore Dollar",HKD:"Hong Kong Dollar",TWD:"Taiwan Dollar",ILS:"Israeli Shekel",AED:"UAE Dirham",SAR:"Saudi Riyal",ZAR:"South African Rand",TRY:"Turkish Lira",RUB:"Russian Ruble",NGN:"Nigerian Naira"},zt=new Set(["JPY","KRW","VND","IDR","LAK","KHR","MMK","PYG"]),E=class s{static getSymbol(e){return Bt[e]??e}static getName(e){return Vt[e]??e}static getDecimalPlaces(e){return zt.has(e)?0:2}static getCurrency(e){return{code:e,symbol:s.getSymbol(e),name:s.getName(e),decimalPlaces:s.getDecimalPlaces(e)}}};function _e(s,e="USD",t="en-US"){let n=E.getDecimalPlaces(e),r=s/(n===0?100:Math.pow(10,n));try{return new Intl.NumberFormat(t,{style:"currency",currency:e,minimumFractionDigits:n,maximumFractionDigits:n}).format(r)}catch{return`${E.getSymbol(e)}${r.toFixed(n)}`}}return ft(Jt);})();
|
|
7
7
|
if(typeof window!=="undefined"&&TagadaHeadlessBundle){ window.TagadaHeadless=TagadaHeadlessBundle; window.TagadaHeadless.create=TagadaHeadlessBundle.createHeadlessClient;}
|
|
8
8
|
//# sourceMappingURL=tagada-headless.min.js.map
|