@tagadapay/headless-sdk 1.20.1 → 1.21.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.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @tagadapay/headless-sdk v1.20.1
2
+ * @tagadapay/headless-sdk v1.21.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.20.1";
145
+ var SDK_VERSION = "1.21.0";
146
146
 
147
147
  // src/core/http.ts
148
148
  var BASE_URLS = {
@@ -724,7 +724,8 @@ var TagadaHeadlessBundle = (() => {
724
724
  shippingAddress: this.normalizeAddress(cs.shippingAddress),
725
725
  billingAddress: this.normalizeAddress(cs.billingAddress),
726
726
  selectedShippingRateId: cs.shippingRateId ?? null,
727
- metadata: cs.metadata
727
+ metadata: cs.metadata,
728
+ ...typeof cs.draft === "boolean" ? { draft: cs.draft } : {}
728
729
  };
729
730
  }
730
731
  /**
@@ -804,7 +805,7 @@ var TagadaHeadlessBundle = (() => {
804
805
  }
805
806
 
806
807
  // src/core/modules/track.ts
807
- var CDN_URL = false ? "" : "https://cdn.jsdelivr.net/npm/@tagadapay/headless-sdk@1.20.1/dist/tagada-pixels.min.js";
808
+ var CDN_URL = false ? "" : "https://cdn.jsdelivr.net/npm/@tagadapay/headless-sdk@1.21.0/dist/tagada-pixels.min.js";
808
809
  function loadScript(src, isReady) {
809
810
  if (isReady())
810
811
  return Promise.resolve();
@@ -1430,6 +1431,42 @@ var TagadaHeadlessBundle = (() => {
1430
1431
  return error instanceof Error && error.message ? error.message : UNAVAILABLE;
1431
1432
  }
1432
1433
 
1434
+ // src/core/helpers/paymentsApiAnswer.ts
1435
+ function readStartedPayment(answer) {
1436
+ if (!answer || typeof answer !== "object" || Array.isArray(answer))
1437
+ return null;
1438
+ const { payment, order, paymentId, clientSecret, amount, currency, checkoutSessionId } = answer;
1439
+ if (payment !== void 0 || order !== void 0)
1440
+ return null;
1441
+ if (typeof paymentId !== "string" || !paymentId || typeof clientSecret !== "string" || !clientSecret)
1442
+ return null;
1443
+ return {
1444
+ paymentId,
1445
+ clientSecret,
1446
+ ...typeof amount === "number" ? { amount } : {},
1447
+ ...typeof currency === "string" ? { currency } : {},
1448
+ ...typeof checkoutSessionId === "string" ? { checkoutSessionId } : {}
1449
+ };
1450
+ }
1451
+ var PENDING_KEY = "tgd_payments_api_return";
1452
+ var PENDING_TTL_MS = 60 * 6e4;
1453
+ function takeParkedPaymentsApiReturn(paymentId) {
1454
+ try {
1455
+ const raw = sessionStorage.getItem(PENDING_KEY);
1456
+ if (!raw)
1457
+ return null;
1458
+ const parked = JSON.parse(raw);
1459
+ if (parked.paymentId !== paymentId)
1460
+ return null;
1461
+ sessionStorage.removeItem(PENDING_KEY);
1462
+ if (!parked.checkoutSessionId || !parked.at || Date.now() - parked.at > PENDING_TTL_MS)
1463
+ return null;
1464
+ return { checkoutSessionId: parked.checkoutSessionId };
1465
+ } catch {
1466
+ return null;
1467
+ }
1468
+ }
1469
+
1433
1470
  // src/core/helpers/oceanpayment.ts
1434
1471
  var OCEAN_SDK_URL = "https://secure.oceanpayment.com/pages/js/oceanpayment.js";
1435
1472
  var OCEAN_CONTAINER_ID = "oceanpayment-element";
@@ -1512,6 +1549,16 @@ var TagadaHeadlessBundle = (() => {
1512
1549
  }
1513
1550
 
1514
1551
  // src/core/modules/payment.ts
1552
+ function loadPaymentsApiFlow() {
1553
+ if (true) {
1554
+ return Promise.reject(
1555
+ new Error(
1556
+ "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."
1557
+ )
1558
+ );
1559
+ }
1560
+ return import("../helpers/paymentsApi.js");
1561
+ }
1515
1562
  var FAILED_PAYMENT_STATUSES = /* @__PURE__ */ new Set(["failed", "declined", "rejected", "error"]);
1516
1563
  var oceanSlot = null;
1517
1564
  var oceanSlotTaken = () => !!oceanSlot && (!oceanSlot.attached || oceanSlot.element.isConnected);
@@ -1575,6 +1622,11 @@ var TagadaHeadlessBundle = (() => {
1575
1622
  * without a second network round-trip inside Apple's authorization window.
1576
1623
  */
1577
1624
  this.lastPaymentSetup = null;
1625
+ /**
1626
+ * Payments API (V3) store: what the pay call knew about each payment it started (the session it
1627
+ * pays, the shopper's method), so `finalize()` can confirm it from the bare pay answer.
1628
+ */
1629
+ this.paymentsApiStarts = /* @__PURE__ */ new Map();
1578
1630
  }
1579
1631
  // ---------------------------------------------------------------------------
1580
1632
  // Discovery: what payment methods are available?
@@ -1785,7 +1837,7 @@ var TagadaHeadlessBundle = (() => {
1785
1837
  */
1786
1838
  async pay(opts) {
1787
1839
  if (opts.tagadaToken && !opts.paymentInstrumentId) {
1788
- return this.http.post("/api/v1/payment/pay-with-token", {
1840
+ return this.rememberPaymentsApiStart(await this.http.post("/api/v1/payment/pay-with-token", {
1789
1841
  tagadaToken: opts.tagadaToken,
1790
1842
  checkoutSessionId: opts.checkoutSessionId,
1791
1843
  returnUrl: opts.returnUrl,
@@ -1794,9 +1846,9 @@ var TagadaHeadlessBundle = (() => {
1794
1846
  paymentMethod: opts.paymentMethod,
1795
1847
  isExpress: opts.isExpress,
1796
1848
  metadata: opts.metadata
1797
- });
1849
+ }), opts);
1798
1850
  }
1799
- return this.http.post("/api/public/v1/checkout/pay-v2", {
1851
+ return this.rememberPaymentsApiStart(await this.http.post("/api/public/v1/checkout/pay-v2", {
1800
1852
  checkoutSessionId: opts.checkoutSessionId,
1801
1853
  paymentInstrumentId: opts.paymentInstrumentId,
1802
1854
  storeId: this.storeId,
@@ -1807,14 +1859,14 @@ var TagadaHeadlessBundle = (() => {
1807
1859
  isExpress: opts.isExpress,
1808
1860
  metadata: opts.metadata,
1809
1861
  returnUrl: opts.returnUrl
1810
- });
1862
+ }), opts);
1811
1863
  }
1812
1864
  /**
1813
1865
  * Low-level pay: process payment with an existing instrument or for APM/express flows
1814
1866
  * where no instrument is needed (redirect-based methods).
1815
1867
  */
1816
1868
  async payDirect(opts) {
1817
- return this.http.post("/api/public/v1/checkout/pay-v2", {
1869
+ return this.rememberPaymentsApiStart(await this.http.post("/api/public/v1/checkout/pay-v2", {
1818
1870
  checkoutSessionId: opts.checkoutSessionId,
1819
1871
  paymentInstrumentId: opts.paymentInstrumentId ?? "",
1820
1872
  storeId: this.storeId,
@@ -1824,7 +1876,7 @@ var TagadaHeadlessBundle = (() => {
1824
1876
  isExpress: opts.isExpress,
1825
1877
  threedsSessionId: opts.threedsSessionId,
1826
1878
  returnUrl: opts.returnUrl
1827
- });
1879
+ }), opts);
1828
1880
  }
1829
1881
  /**
1830
1882
  * Persist a wallet contact onto the session before the charge.
@@ -2307,6 +2359,11 @@ var TagadaHeadlessBundle = (() => {
2307
2359
  var _a, _b, _c;
2308
2360
  const payment = input.payment;
2309
2361
  const returnUrl = (opts == null ? void 0 : opts.returnUrl) ?? (typeof window !== "undefined" ? window.location.href : void 0);
2362
+ if (!payment) {
2363
+ const started = readStartedPayment(input);
2364
+ if (started)
2365
+ return this.finalizeOnPaymentsApi(started, returnUrl);
2366
+ }
2310
2367
  if (payment.status === "succeeded") {
2311
2368
  this.emitPaid((_a = input.order) == null ? void 0 : _a.id, payment);
2312
2369
  return { status: "succeeded", payment, order: input.order };
@@ -2327,6 +2384,11 @@ var TagadaHeadlessBundle = (() => {
2327
2384
  * You can also call it manually in non-React apps.
2328
2385
  */
2329
2386
  async resumeAfterRedirect(paymentId) {
2387
+ const parked = takeParkedPaymentsApiReturn(paymentId);
2388
+ if (parked) {
2389
+ const url2 = typeof window !== "undefined" ? window.location.href : void 0;
2390
+ return this.onPaymentsApi((flow, host) => flow.resumeOnPaymentsApi(host, paymentId, parked.checkoutSessionId, url2));
2391
+ }
2330
2392
  return this.pollUntilDone(paymentId);
2331
2393
  }
2332
2394
  /**
@@ -2616,6 +2678,48 @@ var TagadaHeadlessBundle = (() => {
2616
2678
  return { status: "pending", paymentId };
2617
2679
  }
2618
2680
  // ---------------------------------------------------------------------------
2681
+ // Internal: Payments API (V3) stores
2682
+ // ---------------------------------------------------------------------------
2683
+ /** Keeps what a V3 pay answer does not say (its session, the method); returns the answer as is. */
2684
+ rememberPaymentsApiStart(answer, opts) {
2685
+ const started = answer && !answer.payment ? readStartedPayment(answer) : null;
2686
+ if (started) {
2687
+ this.paymentsApiStarts.set(started.paymentId, {
2688
+ checkoutSessionId: started.checkoutSessionId ?? opts.checkoutSessionId,
2689
+ ...opts.paymentMethod ? { paymentMethod: opts.paymentMethod } : {}
2690
+ });
2691
+ }
2692
+ return answer;
2693
+ }
2694
+ /** Confirms a started V3 payment with payments-js and runs it to the V2-shaped result. */
2695
+ finalizeOnPaymentsApi(started, returnUrl) {
2696
+ const known = this.paymentsApiStarts.get(started.paymentId);
2697
+ this.paymentsApiStarts.delete(started.paymentId);
2698
+ return this.onPaymentsApi(
2699
+ (flow, host) => flow.finalizeOnPaymentsApi(host, started, {
2700
+ checkoutSessionId: known == null ? void 0 : known.checkoutSessionId,
2701
+ paymentMethod: known == null ? void 0 : known.paymentMethod,
2702
+ returnUrl
2703
+ })
2704
+ );
2705
+ }
2706
+ /** Runs `run` with the lazily imported V3 flow; a flow that cannot load is a failed payment. */
2707
+ async onPaymentsApi(run) {
2708
+ let flow;
2709
+ try {
2710
+ flow = await loadPaymentsApiFlow();
2711
+ } catch (error) {
2712
+ return { status: "failed", error: error instanceof Error ? error.message : String(error) };
2713
+ }
2714
+ return run(flow, {
2715
+ http: this.http,
2716
+ storeId: this.storeId,
2717
+ checkout: this.checkout,
2718
+ stepConfig: this.readInjectedStepConfigRaw(),
2719
+ onPaid: (orderId, payment) => this.emitPaid(orderId, payment)
2720
+ });
2721
+ }
2722
+ // ---------------------------------------------------------------------------
2619
2723
  // Internal helpers
2620
2724
  // ---------------------------------------------------------------------------
2621
2725
  /**
@@ -2635,6 +2739,19 @@ var TagadaHeadlessBundle = (() => {
2635
2739
  return null;
2636
2740
  }
2637
2741
  }
2742
+ /** The whole injected step config (Tagada-hosted pages), or null. */
2743
+ readInjectedStepConfigRaw() {
2744
+ if (typeof window === "undefined")
2745
+ return null;
2746
+ const raw = window.__TGD_STEP_CONFIG__;
2747
+ if (!raw)
2748
+ return null;
2749
+ try {
2750
+ return typeof raw === "string" ? JSON.parse(raw) : raw;
2751
+ } catch {
2752
+ return null;
2753
+ }
2754
+ }
2638
2755
  /** Tracking hook. Never throws, never awaits: a pixel must not be able to break a payment. */
2639
2756
  emitPaid(orderId, payment) {
2640
2757
  var _a;
@@ -2667,7 +2784,7 @@ var TagadaHeadlessBundle = (() => {
2667
2784
 
2668
2785
  // src/core/modules/lazyCommerce.ts
2669
2786
  var script = typeof document === "undefined" ? null : document.currentScript;
2670
- 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.20.1/dist/tagada-headless-commerce.min.js";
2787
+ 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.21.0/dist/tagada-headless-commerce.min.js";
2671
2788
  var loading;
2672
2789
  function loadCommerce() {
2673
2790
  if (window.TagadaHeadlessCommerce)
@@ -1,8 +1,8 @@
1
1
  /**
2
- * @tagadapay/headless-sdk v1.20.1
2
+ * @tagadapay/headless-sdk v1.21.0
3
3
  * Headless checkout, payments, offers, and CRM
4
4
  * @license MIT
5
5
  */
6
- "use strict";var TagadaHeadlessBundle=(()=>{var ot=Object.create;var re=Object.defineProperty;var at=Object.getOwnPropertyDescriptor;var dt=Object.getOwnPropertyNames;var ct=Object.getPrototypeOf,ut=Object.prototype.hasOwnProperty;var ge=(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 lt=(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 dt(e))!ut.call(s,r)&&r!==t&&re(s,r,{get:()=>e[r],enumerable:!(n=at(e,r))||n.enumerable});return s};var he=(s,e,t)=>(t=s!=null?ot(ct(s)):{},Ee(e||!s||!s.__esModule?re(t,"default",{value:s,enumerable:!0}):t,s)),pt=s=>Ee(re({},"__esModule",{value:!0}),s);var Kt={};lt(Kt,{AVAILABLE_LANGUAGES:()=>Z,CRYPTO_ONCHAIN_FINAL_PHASES:()=>de,CRYPTO_ONCHAIN_PAYMENT_METHOD:()=>Ce,CRYPTO_ONCHAIN_STATUS_POLL_MS:()=>je,CatalogModule:()=>K,CheckoutModule:()=>O,CryptoOnchainCheckout:()=>F,CurrencyUtils:()=>N,CustomerModule:()=>_,CustomerPortalModule:()=>E,ExperimentsModule:()=>B,FunnelModule:()=>j,GoogleAutocompleteCore:()=>Q,HeadlessClient:()=>Y,HttpClient:()=>A,ISODataCore:()=>ne,OffersModule:()=>T,PaymentModule:()=>$,RxModule:()=>G,TagadaAuthError:()=>L,TagadaError:()=>P,TagadaNetworkError:()=>R,TagadaNotFoundError:()=>v,TagadaPaymentError:()=>se,TagadaRateLimitError:()=>D,TagadaValidationError:()=>M,TrackModule:()=>U,createHeadlessClient:()=>et,cryptoOnchainPhase:()=>ke,cryptoOnchainSecondsLeft:()=>ce,defaultCryptoOnchainSelection:()=>Se,ensureGeoDataLoaded:()=>X,formatCryptoOnchainCountdown:()=>Be,formatMoney:()=>Te,getCountries:()=>V,getStatesForCountry:()=>ee,isCryptoOnchainMethod:()=>Ge,isLanguageLoaded:()=>te,isQuestionActive:()=>be,loadGoogleMapsScript:()=>Re,parseTokensFromUrl:()=>Le,selectCryptoOnchainNetwork:()=>we,toIntakeAnswers:()=>Xe});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}},v=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}},se=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 fe="headless",z="1.20.1";var Ne={production:"https://api.tagada.io",development:"https://api.tagada.dev",local:"http://localhost:3000"},A=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??Ne[e]??Ne.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 f=new URLSearchParams;for(let[C,w]of Object.entries(o))w!==void 0&&f.set(C,String(w));let h=f.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 f=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),f.ok){let h=await f.text();return h?JSON.parse(h):{}}throw await this.handleErrorResponse(f,e),new P("Unexpected error","unknown",f.status)}catch(f){throw clearTimeout(l),f instanceof P?f:f instanceof DOMException&&f.name==="AbortError"?new R(`Request to ${e} timed out after ${this.timeout}ms.`):new R(f instanceof Error?f.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=mt(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 v(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 mt(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 gt({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??{},f=(p==null?void 0:p.currencyOptions)??{},h=(a?f[a]:void 0)??f[Object.keys(f)[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}}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}},Le=O.parseTokensFromUrl;function gt(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 ie(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 Me(e)?e:void 0}function oe(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 Me(n)?n:void 0}function Me(s){var e,t;return!!((e=s.line1)!=null&&e.trim()&&((t=s.country)!=null&&t.trim()))}var De="https://cdn.jsdelivr.net/npm/@tagadapay/headless-sdk@1.20.1/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 ht(){if(typeof window>"u")return null;if(De){let s=window;return s.TagadaPixels?s.TagadaPixels:(await He(De,()=>!!s.TagadaPixels),s.TagadaPixels??null)}return await import("../../pixels/index.js")}var Ue="__tgd_track",ft="__tgd_aid",yt="__tgd_sid",Fe=50,Pt=2e3,qe=1e3,Ct=64;function ae(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 St={lead:"Lead",product_viewed:"ViewContent",added_to_cart:"AddToCart"};function ye(){try{return crypto.randomUUID()}catch{return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}}function wt(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(Ue)??"").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(Ue,`${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<qe||(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=St[e],i=`${r??e}_${ye()}`;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>=qe&&this.lastStep.delete(n);for(;this.lastStep.size>=Ct;){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:fe,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 ht();if(n===null)return null;let r=n.createPixelEngine({pixels:wt(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>=Fe){this.flush();return}this.flushTimer===null&&(this.flushTimer=setTimeout(()=>this.flush(),Pt))}}identifier(e,t){try{let n=e==="local"?localStorage:sessionStorage,r=n.getItem(t);if(r)return r;let i=ye();return n.setItem(t,i),i}catch{return ye()}}flush(){if(this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.records.length===0)return;let e=this.records.splice(0,Fe),t={storeId:this.storeId,funnelKey:this.flagFunnelKey(),sdk:{name:fe,version:z},anonymousId:this.identifier("local",ft),sessionId:this.identifier("session",yt),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",je=5e3,de=["paid","underpaid","failed","expired"];function Ge(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 ce(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 Be(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"&&ce(t.expiresAt,e)===0?"expired":r}getSecondsLeft(e=Date.now()){var t;return ce(((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||de.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&&!de.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}var kt="https://secure.oceanpayment.com/pages/js/oceanpayment.js",Ie="oceanpayment-element";var vt={fi:"en"};function Ve(s){var t;let e=(t=s==null?void 0:s.split(/[-_]/)[0])==null?void 0:t.toLowerCase();return e?vt[e]??e:"en"}var It=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"),It);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=kt,document.head.appendChild(n)}),J)}var ve="tgd:headless:oceanpayment:pending",bt=30*60*1e3;function Je(s){try{sessionStorage.setItem(ve,JSON.stringify({paymentId:s,at:Date.now()}))}catch{}}function xt(){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>bt?void 0:e}catch{return}}function Ye(){if(typeof window>"u")return;let s=xt();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{}}var Qe=new Set(["failed","declined","rejected","error"]),q=null,At=()=>!!q&&(!q.attached||q.element.isConnected),We=Symbol("ocean-timed-out"),Ze=Symbol("ocean-unmounted"),Ot=new Set(["apple_pay","google_pay","paypal","klarna","klarna_express","link"]);function Tt(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:Ot.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}}function _t(){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 $=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}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 v))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(Tt):(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[f,h]of Object.entries(n)){if(!h.enabled)continue;if(f.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 y=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:!!y}}(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.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}):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})}async payDirect(e){return 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})}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,f;await this.syncWalletContact(e.checkoutSessionId,{shippingAddress:ie(e.shippingContact),billingAddress:ie(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??((f=await this.resolveApplePayRegistration(e.checkoutSessionId))==null?void 0:f.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:oe(e.shippingAddress),billingAddress:oe(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})}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(At()||document.getElementById(Ie))throw new Error("An Ocean Payment card form is already mounted on this page");let o=window,a=document.createElement("div");a.id=Ie;let d={element:a,attached:!1};q=d;let u=()=>{q===d&&(q=null)},g=!0,c=null,p=y=>{let k=c;c=null,k==null||k(y)},l=()=>{g&&(g=!1,o.oceanpaymentCallBack===p&&delete o.oceanpaymentCallBack,a.remove(),u(),p(Ze))};n==null||n.addEventListener("abort",l,{once:!0});let m,f;try{if(m=e.mode==="redirect"?{embedded:!1,sandboxed:!1}:await this.getOceanPaymentConfig(t),n!=null&&n.aborted||m.embedded&&(f=await ze(),n!=null&&n.aborted))throw r()}catch(y){throw l(),y}let h=!1;if(!f)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 y=await this.http.post(`/api/v1/checkout-sessions/${t}/oceanpayment-link`,{returnUrl:e.returnUrl??window.location.href});return!(y!=null&&y.url)||!y.paymentId?{status:"failed",error:"Ocean Payment is not available for this store"}:{status:"requires_redirect",redirectUrl:y.url,method:"GET",paymentId:y.paymentId}}catch(y){return{status:"failed",error:y instanceof Error?y.message:String(y)}}finally{h=!1}},unmount:l};let C=f;i.appendChild(a),d.attached=!0,o.oceanpaymentCallBack=p;let w=window.location.href;return C.init(m.sandboxed,"",Ve(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 y=await this.http.post(`/api/v1/checkout-sessions/${t}/oceanpayment-embedded-payment`,{backUrl:w});if(!(y!=null&&y.paymentId)||!y.params)return{status:"failed",error:"Failed to start the payment"};let k=y.paymentId,x=await new Promise(_e=>{let st=setTimeout(()=>{c=null,_e(We)},12e4);c=it=>{clearTimeout(st),_e(it)},C.checkout(y.params)});if(x===We||x===Ze)return this.pollUntilDone(k);if(x&&typeof x=="object"&&"msg"in x)return{status:"failed",error:String(x.msg||"Please check your card details.")};let S=await this.http.post(`/api/v1/checkout-sessions/${t}/oceanpayment-embedded-result`,{paymentId:k,response:String(x)});return(S==null?void 0:S.status)==="requires_action"&&S.payUrl?(Je(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(y){return{status:"failed",error:y instanceof Error?y.message:String(y)}}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);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){return this.pollUntilDone(e)}async maybeResumeFromUrl(e){if(typeof window>"u"&&!(e!=null&&e.url))return null;e!=null&&e.url||Ye();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"||Qe.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 _t(),{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(Qe.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}}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}}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:ae(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 I=typeof document>"u"?null:document.currentScript,Et=I!=null&&I.src?new URL("tagada-headless-commerce.min.js",I.src).href:"https://cdn.jsdelivr.net/npm/@tagadapay/headless-sdk@1.20.1/dist/tagada-headless-commerce.min.js",ue;function H(){return window.TagadaHeadlessCommerce?Promise.resolve(window.TagadaHeadlessCommerce):(ue||(ue=new Promise((s,e)=>{let t=document.createElement("script");t.src=Et,t.async=!0,I!=null&&I.nonce&&(t.nonce=I.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 ue=void 0,s})),ue)}var T=class{constructor(...e){this.args=e}load(){return this.instance||(this.instance=H().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=H().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 E=class{constructor(...e){this.args=e}load(){return this.instance||(this.instance=H().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"])E.prototype[s]=function(...e){return this.load().then(t=>t[s](...e))};var K=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 j=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)??Nt(),userAgent:Lt(),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(f=>({variantId:f.variantId,priceId:f.priceId,quantity:f.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 Nt(){return typeof navigator<"u"&&navigator.language?navigator.language:"en-US"}function Lt(){return typeof navigator<"u"&&navigator.userAgent?navigator.userAgent:"tagadapay-headless-sdk"}var le=(s,e)=>e!==null&&String(s).trim().toLowerCase()===e.trim().toLowerCase();function be(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 le(t.state??"",o.answer);if(o.basedOn==="other"&&o.questionId==="patient_sex")return le(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=>le(d,o.answer)):le(a,o.answer)}return!1};return r.op==="and"?r.requirements.every(i):r.requirements.some(i)})}function Xe(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(!be(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=A.resolveBaseUrl(t,e.baseUrl);this.config={...e,environment:t,baseUrl:n,timeout:e.timeout??3e4},this.http=new A({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:ae(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 E(this.http,this.config.storeId,r),this.catalog=new K(this.http,this.config.storeId),this.funnel=new j(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 et(s){return new Y(s)}var tt=!1,nt=!1,pe=[];function xe(){nt=!0;for(let s of pe)s();pe.length=0}function Re(s,e={}){var t,n;return nt||(n=(t=window.google)==null?void 0:t.maps)!=null&&n.places?(xe(),Promise.resolve()):tt?new Promise(r=>pe.push(r)):(tt=!0,new Promise((r,i)=>{if(pe.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?xe():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=()=>xe(),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 rt="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,me=new Map,Ae=new Map,Oe=new Map;async function Mt(s){let e=W.get(s);if(e)return e;let t=Ae.get(s);return t||(t=(async()=>{let n=`${rt}/${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),Ae.delete(s),i})(),Ae.set(s,t),t)}async function Dt(s){let e=me.get(s);if(e)return e;let t=Oe.get(s);return t||(t=(async()=>{let n=`${rt}/${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 me.set(s,i),Oe.delete(s),i})(),Oe.set(s,t),t)}function Ut(s){return W.get(s)||W.get("en")||{}}function Ft(s){return me.get(s)||me.get("en")||{}}async function X(s="en"){await Promise.all([Mt(s),Dt(s)])}var V=(s="en")=>{let e=Ut(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=Ft(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 qt={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"},$t={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"},Ht=new Set(["JPY","KRW","VND","IDR","LAK","KHR","MMK","PYG"]),N=class s{static getSymbol(e){return qt[e]??e}static getName(e){return $t[e]??e}static getDecimalPlaces(e){return Ht.has(e)?0:2}static getCurrency(e){return{code:e,symbol:s.getSymbol(e),name:s.getName(e),decimalPlaces:s.getDecimalPlaces(e)}}};function Te(s,e="USD",t="en-US"){let n=N.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`${N.getSymbol(e)}${r.toFixed(n)}`}}return pt(Kt);})();
6
+ "use strict";var TagadaHeadlessBundle=(()=>{var ct=Object.create;var re=Object.defineProperty;var ut=Object.getOwnPropertyDescriptor;var lt=Object.getOwnPropertyNames;var pt=Object.getPrototypeOf,mt=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 gt=(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 lt(e))!mt.call(s,r)&&r!==t&&re(s,r,{get:()=>e[r],enumerable:!(n=ut(e,r))||n.enumerable});return s};var ie=(s,e,t)=>(t=s!=null?ct(pt(s)):{},Ee(e||!s||!s.__esModule?re(t,"default",{value:s,enumerable:!0}):t,s)),ht=s=>Ee(re({},"__esModule",{value:!0}),s);var zt={};gt(zt,{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:()=>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:()=>rt,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:()=>nt});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.21.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=yt(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 yt(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 ft({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 ft(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.21.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 Pt(){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",Ct="__tgd_aid",St="__tgd_sid",qe=50,wt=2e3,$e=1e3,kt=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 He(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 It={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 vt(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=It[e],i=`${r??e}_${fe()}`;this.push({kind:"event",stepId:n,name:e,at:Date.now(),eventId:i,props:He(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,{...He(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>=kt;){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 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 Pt();if(n===null)return null;let r=n.createPixelEngine({pixels:vt(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(),wt))}}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",Ct),sessionId:this.identifier("session",St),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}=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}:{}}}var ze="tgd_payments_api_return",bt=60*6e4;function Je(s){try{let e=sessionStorage.getItem(ze);if(!e)return null;let t=JSON.parse(e);return t.paymentId!==s||(sessionStorage.removeItem(ze),!t.checkoutSessionId||!t.at||Date.now()-t.at>bt)?null:{checkoutSessionId:t.checkoutSessionId}}catch{return null}}var At="https://secure.oceanpayment.com/pages/js/oceanpayment.js",be="oceanpayment-element";var Rt={fi:"en"};function Ye(s){var t;let e=(t=s==null?void 0:s.split(/[-_]/)[0])==null?void 0:t.toLowerCase();return e?Rt[e]??e:"en"}var xt=3e4,J=null;function Qe(){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"),xt);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=At,document.head.appendChild(n)}),J)}var ve="tgd:headless:oceanpayment:pending",Ot=30*60*1e3;function We(s){try{sessionStorage.setItem(ve,JSON.stringify({paymentId:s,at:Date.now()}))}catch{}}function Tt(){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>Ot?void 0:e}catch{return}}function Ze(){if(typeof window>"u")return;let s=Tt();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 Nt(){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 Xe=new Set(["failed","declined","rejected","error"]),q=null,Et=()=>!!q&&(!q.attached||q.element.isConnected),et=Symbol("ocean-timed-out"),tt=Symbol("ocean-unmounted"),Lt=new Set(["apple_pay","google_pay","paypal","klarna","klarna_express","link"]);function Mt(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:Lt.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}}function Dt(){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 $=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(Mt):(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})}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(Et()||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(tt))};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 Qe(),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,"",Ye(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 at=setTimeout(()=>{c=null,Ne(et)},12e4);c=dt=>{clearTimeout(at),Ne(dt)},C.checkout(f.params)});if(A===et||A===tt)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?(We(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=Je(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||Ze();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"||Xe.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 Dt(),{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(Xe.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 Nt()}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,Ut=v!=null&&v.src?new URL("tagada-headless-commerce.min.js",v.src).href:"https://cdn.jsdelivr.net/npm/@tagadapay/headless-sdk@1.21.0/dist/tagada-headless-commerce.min.js",pe;function H(){return window.TagadaHeadlessCommerce?Promise.resolve(window.TagadaHeadlessCommerce):(pe||(pe=new Promise((s,e)=>{let t=document.createElement("script");t.src=Ut,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=H().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=H().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=H().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 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)??Ft(),userAgent:qt(),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 Ft(){return typeof navigator<"u"&&navigator.language?navigator.language:"en-US"}function qt(){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 nt(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 j(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 rt(s){return new Y(s)}var st=!1,it=!1,ge=[];function Re(){it=!0;for(let s of ge)s();ge.length=0}function xe(s,e={}){var t,n;return it||(n=(t=window.google)==null?void 0:t.maps)!=null&&n.places?(Re(),Promise.resolve()):st?new Promise(r=>ge.push(r)):(st=!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 ot="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=`${ot}/${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=`${ot}/${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 jt(s){return W.get(s)||W.get("en")||{}}function Kt(s){return he.get(s)||he.get("en")||{}}async function X(s="en"){await Promise.all([$t(s),Ht(s)])}var V=(s="en")=>{let e=jt(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=Kt(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 Gt={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"},Bt={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"},Vt=new Set(["JPY","KRW","VND","IDR","LAK","KHR","MMK","PYG"]),E=class s{static getSymbol(e){return Gt[e]??e}static getName(e){return Bt[e]??e}static getDecimalPlaces(e){return Vt.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 ht(zt);})();
7
7
  if(typeof window!=="undefined"&&TagadaHeadlessBundle){ window.TagadaHeadless=TagadaHeadlessBundle; window.TagadaHeadless.create=TagadaHeadlessBundle.createHeadlessClient;}
8
8
  //# sourceMappingURL=tagada-headless.min.js.map