@tagadapay/headless-sdk 1.17.0 → 1.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -0
- package/dist/core/index.d.ts +2 -2
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js +1 -1
- package/dist/core/index.js.map +1 -1
- package/dist/core/modules/customer.d.ts +26 -4
- package/dist/core/modules/customer.d.ts.map +1 -1
- package/dist/core/modules/customer.js +50 -16
- package/dist/core/modules/customer.js.map +1 -1
- package/dist/core/modules/rx.d.ts +91 -4
- package/dist/core/modules/rx.d.ts.map +1 -1
- package/dist/core/modules/rx.js +74 -2
- package/dist/core/modules/rx.js.map +1 -1
- package/dist/core/version.d.ts +1 -1
- package/dist/core/version.js +1 -1
- package/dist/react/index.d.ts +1 -1
- package/dist/react/index.d.ts.map +1 -1
- package/dist/react/provider.d.ts +13 -2
- package/dist/react/provider.d.ts.map +1 -1
- package/dist/react/provider.js +35 -7
- package/dist/react/provider.js.map +1 -1
- package/dist/tagada-headless-commerce.min.js +2 -2
- package/dist/tagada-headless-commerce.min.js.map +4 -4
- package/dist/tagada-headless-react.min.js +2 -2
- package/dist/tagada-headless-react.min.js.map +3 -3
- package/dist/tagada-headless.js +68 -7
- package/dist/tagada-headless.min.js +2 -2
- package/dist/tagada-headless.min.js.map +3 -3
- package/dist/tagada-pixels.min.js +1 -1
- package/package.json +4 -1
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @tagadapay/headless-sdk v1.
|
|
2
|
+
* @tagadapay/headless-sdk v1.19.0
|
|
3
3
|
* Headless checkout, payments, offers, and CRM
|
|
4
4
|
* @license MIT
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var TagadaHeadlessReactBundle=(()=>{var wt=Object.create;var le=Object.defineProperty;var Ct=Object.getOwnPropertyDescriptor;var vt=Object.getOwnPropertyNames;var kt=Object.getPrototypeOf,It=Object.prototype.hasOwnProperty;var M=(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 bt=(s,e)=>{for(var t in e)le(s,t,{get:e[t],enumerable:!0})},je=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of vt(e))!It.call(s,n)&&n!==t&&le(s,n,{get:()=>e[n],enumerable:!(r=Ct(e,n))||r.enumerable});return s};var Oe=(s,e,t)=>(t=s!=null?wt(kt(s)):{},je(e||!s||!s.__esModule?le(t,"default",{value:s,enumerable:!0}):t,s)),Rt=s=>je(le({},"__esModule",{value:!0}),s);var Qt={};bt(Qt,{CurrencyUtils:()=>W,GoogleAutocompleteCore:()=>K,ISODataCore:()=>B,TagadaHeadlessProvider:()=>et,formatMoney:()=>He,loadGoogleMapsScript:()=>ae,parseTokensFromUrl:()=>Ke,useCatalog:()=>ct,useCheckout:()=>rt,useCountryOptions:()=>ht,useCustomer:()=>ot,useGoogleAutocomplete:()=>gt,useHeadlessClient:()=>O,useISOData:()=>Te,useOffers:()=>it,useOrder:()=>at,usePayment:()=>st,useRegionOptions:()=>yt,useRx:()=>ut,useStep:()=>lt});var Q=M("react");var q=class extends Error{constructor(e,t,r,n){super(e),this.name="TagadaError",this.code=t,this.statusCode=r,this.details=n}},pe=class extends q{constructor(e="Authentication failed. Check your API key or checkout token."){super(e,"auth_error",401),this.name="TagadaAuthError"}},me=class extends q{constructor(e,t=[],r,n){super(e,"validation_error",422,{errors:t,...n}),this.name="TagadaValidationError",this.errors=t,this.appCode=r}},X=class extends q{constructor(e,t){super(`${e} "${t}" not found.`,"not_found",404),this.name="TagadaNotFoundError"}},ge=class extends q{constructor(e=1e3){super(`Rate limited. Retry after ${e}ms.`,"rate_limit",429),this.name="TagadaRateLimitError",this.retryAfterMs=e}};var te=class extends q{constructor(e="Network request failed. Check your connection."){super(e,"network_error"),this.name="TagadaNetworkError"}};var $e={production:"https://api.tagada.io",development:"https://api.tagada.dev",local:"http://localhost:3000"},re=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??$e[e]??$e.production}async request(e,t={}){var h;let{method:r="GET",body:n,headers:i={},params:o,token:a,signal:c}=t,u=`${this.baseUrl}${e}`;if(o){let y=new URLSearchParams;for(let[m,C]of Object.entries(o))C!==void 0&&y.set(m,String(C));let l=y.toString();l&&(u+=`?${l}`)}let g={"Content-Type":"application/json",...i},d=a??this.apiKey??((h=this.getToken)==null?void 0:h.call(this));d&&(g["x-cms-token"]=d);let f=new AbortController,p=setTimeout(()=>f.abort(),this.timeout);try{let y=await fetch(u,{method:r,headers:g,body:n!=null?JSON.stringify(n):void 0,signal:c??f.signal,...this.redirect&&{redirect:this.redirect}});if(clearTimeout(p),y.ok){let l=await y.text();return l?JSON.parse(l):{}}throw await this.handleErrorResponse(y,e),new q("Unexpected error","unknown",y.status)}catch(y){throw clearTimeout(p),y instanceof q?y:y instanceof DOMException&&y.name==="AbortError"?new te(`Request to ${e} timed out after ${this.timeout}ms.`):new te(y instanceof Error?y.message:"Network request failed.")}}get(e,t){return this.request(e,{...t,method:"GET"})}post(e,t,r){return this.request(e,{...r,method:"POST",body:t})}patch(e,t,r){return this.request(e,{...r,method:"PATCH",body:t})}put(e,t,r){return this.request(e,{...r,method:"PUT",body:t})}delete(e,t){return this.request(e,{...t,method:"DELETE"})}async handleErrorResponse(e,t){let r={};try{r=await e.json()}catch{}let n=At(r.data),i=r.message||r.error||(typeof n.message=="string"?n.message:void 0)||(typeof r.data=="string"&&Object.keys(n).length===0?r.data:void 0)||`Request failed: ${e.status} ${e.statusText} on ${t}`,o=typeof n.code=="string"?n.code:void 0;switch(e.status){case 401:case 403:throw new pe(i);case 404:throw new X(t,"");case 422:{let a=Array.isArray(r.errors)?r.errors:[];throw new me(i,a,o,r)}case 429:{let a=Number(e.headers.get("Retry-After")??"1")*1e3;throw new ge(a)}default:throw new q(i,"api_error",e.status,r)}}};function At(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 ne=class s{constructor(e,t,r,n){this.http=e;this.storeId=t;this.onTokenChange=r;this.onSession=n}getCurrentSession(){return this._currentSession}async loadSession(e,t,r){var a,c;t&&(this.sessionToken=t,(a=this.onTokenChange)==null||a.call(this,t));let n={skipAsyncWait:"false"};r!=null&&r.currency&&(n.currency=r.currency);let i=await this.http.get(`/api/v1/checkout-sessions/${e}/v2`,{params:n,token:this.sessionToken}),o=this.normalizeSession(i);this._currentSession=o;try{(c=this.onSession)==null||c.call(this,o)}catch{}return o}async createSession(e){var c,u,g;let t=e.items.map(d=>({variantId:d.variantId,priceId:d.priceId,...d.sellingPlanId!==void 0?{sellingPlanId:d.sellingPlanId}:{},...d.trialDays!==void 0?{trialDays:d.trialDays}:{},...d.trialPrice!==void 0?{trialPrice:d.trialPrice}:{},quantity:d.quantity})),r={storeId:this.storeId,lineItems:t};e.returnUrl&&(r.returnUrl=e.returnUrl),e.funnelSessionId&&(r.funnelSessionId=e.funnelSessionId),(c=e.discountCodes)!=null&&c.length&&(r.discountCodes=e.discountCodes),e.metadata&&Object.keys(e.metadata).length>0&&(r.metadata=e.metadata),e.customerMetadata&&Object.keys(e.customerMetadata).length>0&&(r.customerMetadata=e.customerMetadata),(u=e.customerTags)!=null&&u.length&&(r.customerTags=e.customerTags);let n={};e.currency&&(n.currency=e.currency),e.customerEmail&&(n.email=e.customerEmail,n.firstName=e.customerFirstName,n.lastName=e.customerLastName),Object.keys(n).length>0&&(r.customer=n);let i=await this.http.post("/api/v1/checkout/session/init",r),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:r,...n}=e,i=await this.createSession(n),o=r??(typeof window<"u"?window.location.origin:""),a=new URLSearchParams({checkoutToken:i.checkoutToken,sessionToken:i.sessionToken}),c=`${o}${t}?${a.toString()}`;return{...i,url:c}}static parseTokensFromUrl(e){if(typeof e>"u"&&typeof window>"u")return null;let t=e??window.location.href,r;try{r=new URL(t)}catch{return null}let n=r.searchParams.get("checkoutToken");if(!n)return null;let i=r.searchParams.get("sessionToken")??r.searchParams.get("token")??"";return{checkoutToken:n,sessionToken:i}}parseTokensFromUrl(e){return s.parseTokensFromUrl(e)}async updateCart(e,t){let r=t.map(n=>({variantId:n.variantId,priceId:n.priceId,...n.sellingPlanId!==void 0?{sellingPlanId:n.sellingPlanId}:{},quantity:n.quantity}));return this.http.post(`/api/v1/checkout-sessions/${e}/line-items`,{lineItems:r},{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 r=this.mapAddress(t.shippingAddress),n=this.mapAddress(t.billingAddress),i=r??n??{},o=n??r,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 r=this.mapAddress(t.shippingAddress),n=this.mapAddress(t.billingAddress),i=r??n??{},o=n??r,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 xt({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 r=t??"default";await this.http.delete(`/api/v1/checkout-sessions/${e}/promotions/${r}`,{token:this.sessionToken})}async getShippingRates(e){return((await this.http.get(`/api/v1/checkout-sessions/${e}/shipping-rates`,{token:this.sessionToken})).rates??[]).map(r=>this.normalizeShippingRate(r))}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,r=t.orderSummaries??[],n=e.summary??t.summary??r[0]??{},i=t.sessionLineItems??[],o=t.customer,a=(g=n.currency??t.selectedPresentmentCurrency)==null?void 0:g.toUpperCase(),c=i.map(d=>{let f=d.price,p=d.variant??(f==null?void 0:f.variant)??{},h=d.product??p.product??{},y=(f==null?void 0:f.currencyOptions)??{},l=(a?y[a]:void 0)??y[Object.keys(y)[0]],m=(l==null?void 0:l.amount)??0;return{id:d.id,variantId:d.variantId,priceId:d.priceId,productName:h.name??"",variantName:p.name??"",quantity:d.quantity??1,unitAmount:m,totalAmount:m*(d.quantity??1),currency:a??"USD",imageUrl:p.imageUrl??h.imageUrl??"",...f!=null&&f.recurring?{recurring:{interval:f.interval??"month",intervalCount:f.intervalCount??1}}:{}}}),u=n.items??[];return{id:t.id,storeId:t.storeId,checkoutToken:t.checkoutToken,currency:a??"USD",items:c,totals:{subtotal:n.subtotalAmount??0,discount:n.totalPromotionAmount??0,shipping:n.shippingCost??0,tax:n.totalTaxAmount??0,total:n.totalAdjustedAmount??n.totalAmount??u.reduce((d,f)=>d+(f.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,r={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(r).some(n=>n!==void 0&&n!=="")?r:void 0}},Ke=ne.parseTokensFromUrl;function xt(s){let e={};for(let[t,r]of Object.entries(s))r!=null&&r!==""&&(e[t]=r);return Object.keys(e).length>0?e:void 0}function fe(s){var t,r;if(!s)return;let e={firstName:s.givenName,lastName:s.familyName,line1:(t=s.addressLines)==null?void 0:t[0],line2:(r=s.addressLines)==null?void 0:r[1],city:s.locality,state:s.administrativeArea,postalCode:s.postalCode,country:s.countryCode,phone:s.phoneNumber};return Be(e)?e:void 0}function he(s){if(!s)return;let[e,...t]=(s.name??"").trim().split(/\s+/),r={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 Be(r)?r:void 0}function Be(s){var e,t;return!!((e=s.line1)!=null&&e.trim()&&((t=s.country)!=null&&t.trim()))}var _e="headless",Le="1.17.0";var ze="https://cdn.jsdelivr.net/npm/@tagadapay/headless-sdk@1.17.0/dist/tagada-pixels.min.js";function We(s,e){return e()?Promise.resolve():new Promise((t,r)=>{let n=document.createElement("script");n.src=s,n.async=!0,n.onload=()=>t(),n.onerror=()=>r(new Error("runtime script failed to load")),document.head.appendChild(n)})}async function Tt(){if(typeof window>"u")return null;if(ze){let s=window;return s.TagadaPixels?s.TagadaPixels:(await We(ze,()=>!!s.TagadaPixels),s.TagadaPixels??null)}return await import("../../pixels/index.js")}var Ve="__tgd_track",Et="__tgd_aid",Ot="__tgd_sid",Je=50,_t=2e3,Qe=1e3,Lt=64;function Pe(s){if(!(!Array.isArray(s)||s.length===0))return s.map(e=>({id:e.variantId,quantity:e.quantity,item_price:e.unitAmount}))}function Ye(s){if(!s)return;let e={};for(let[t,r]of Object.entries(s))(typeof r=="string"||typeof r=="number"||typeof r=="boolean")&&(e[t]=r);return Object.keys(e).length>0?e:void 0}var Ut={lead:"Lead",product_viewed:"ViewContent",added_to_cart:"AddToCart"};function Ue(){try{return crypto.randomUUID()}catch{return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}}function Nt(s){let e={};for(let t of s){let{provider:r,id:n,idKey:i,...o}=t;(e[r]??(e[r]=[])).push({...o,enabled:!0,[i]:n,events:t.events??{}})}return e}var ye=class{constructor(e,t,r){this.baseUrl=e;this.storeId=t;this.funnelKey=r;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(Ve)??"").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(Ve,`${this.storeId}:${this.funnelKey}`)}catch{}}step(e,t){if(typeof window>"u")return;this.arm();let r=(t==null?void 0:t.path)??window.location.pathname,n=`${e}|${r}`,i=Date.now(),o=this.lastStep.get(n);o!==void 0&&i-o<Qe||(this.remember(n,i),this.currentStepId=e,this.listen(),this.push({kind:"step",stepId:e,at:i,path:r}),this.pixels().then(a=>a==null?void 0:a.pageView(r,{stepId:e})),this.core().then(a=>a==null?void 0:a.page({step_id:e})).catch(()=>{}))}event(e,t){if(this.off())return;let r=this.currentStepId;if(r===null)return;let n=Ut[e],i=`${n??e}_${Ue()}`;this.push({kind:"event",stepId:r,name:e,at:Date.now(),eventId:i,props:Ye(t)}),this.pixels().then(o=>n?o==null?void 0:o.track(n,t,{stepId:r,eventId:i}):o==null?void 0:o.trackCustom(e,t,{stepId:r})),this.core().then(o=>o==null?void 0:o.track(e,{...Ye(t)??{},step_id:r,pixel_event_id:i})).catch(()=>{})}remember(e,t){for(let[r,n]of this.lastStep)t-n>=Qe&&this.lastStep.delete(r);for(;this.lastStep.size>=Lt;){let r=this.lastStep.keys().next();if(r.done===!0)break;this.lastStep.delete(r.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,r){this.off()||this.pixels().then(n=>{var i;return n==null?void 0:n.track(e,{value:r.amount,currency:r.currency,contents:r.items,num_items:(i=r.items)==null?void 0:i.length},{eventId:`${e}_${t}`})})}noteSignal(e,t,r){this.off()||(this.signals.push({signal:e,value:t,detail:r}),this.listen(),this.push({kind:"signal",signal:e,value:t,detail:r}))}snapshot(){return{enabled:typeof window>"u"?!1:this.enabled(),storeId:this.storeId,funnelKey:this.flagFunnelKey(),sdk:{name:_e,version:Le},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 r=await t.json();return this.manifestHash=r.manifestHash||null,r}catch{return null}})(),this.configPromise}core(){return typeof window>"u"?Promise.resolve(null):(this.corePromise??(this.corePromise=(async()=>{var e,t;try{let r=await this.config();if(!r||!r.collect&&!r.experiments)return null;let n=this.baseUrl.replace(/\/+$/,""),i=window;return typeof((e=i.tgd)==null?void 0:e.init)!="function"&&await We(n+"/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:r.collect?new URL(r.collect.url).origin:n,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 r=await Tt();if(r===null)return null;let n=r.createPixelEngine({pixels:Nt(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 n.init(),this.loadedProviders=[...new Set((t.pixels??[]).map(i=>i.provider))],n}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>=Je){this.flush();return}this.flushTimer===null&&(this.flushTimer=setTimeout(()=>this.flush(),_t))}}identifier(e,t){try{let r=e==="local"?localStorage:sessionStorage,n=r.getItem(t);if(n)return n;let i=Ue();return r.setItem(t,i),i}catch{return Ue()}}flush(){if(this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.records.length===0)return;let e=this.records.splice(0,Je),t={storeId:this.storeId,funnelKey:this.flagFunnelKey(),sdk:{name:_e,version:Le},anonymousId:this.identifier("local",Et),sessionId:this.identifier("session",Ot),records:e};this.manifestHash!==null&&(t.manifestHash=this.manifestHash);let r=JSON.stringify(t),n=`${this.baseUrl}/api/public/v1/sdk/events`;try{if(typeof navigator<"u"&&typeof navigator.sendBeacon=="function"&&navigator.sendBeacon(n,new Blob([r],{type:"text/plain;charset=UTF-8"})))return}catch{}try{fetch(n,{method:"POST",body:r,keepalive:!0,headers:{"content-type":"text/plain;charset=UTF-8"}}).catch(()=>{})}catch{}}};var Dt=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,r=s.settings??{},n=r.processors,i=r.publishableKey;return{enabled:!0,method:t,provider:e?void 0:s.type,type:e?"card":s.type,label:s.title,logoUrl:s.iconUrl,express:Dt.has(t),integrationId:e?void 0:s.id,processorId:(o=n==null?void 0:n[0])==null?void 0:o.processorId,publishableKey:typeof i=="string"?i:void 0,metadata:s.metadata??void 0}}var Se=class{constructor(e,t,r,n,i,o){this.http=e;this.storeId=t;this.environment=r;this.checkout=n;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 r=this.readInjectedStepConfig();if(r)return this.lastPaymentSetup=r,r;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 X))throw i}let n=await this.getPaymentSetupFromPickerList(e);return this.lastPaymentSetup=n,n}async getPaymentSetupFromPickerList(e){let t=await this.http.get("/api/v1/payment-methods",{params:{checkoutSessionId:e}}),r=Array.isArray(t)?t.map(Mt):(t==null?void 0:t.methods)??[],n={};for(let i of r){let o=i.provider&&i.provider!==i.method?`${i.method}:${i.provider}`:i.method;n[o]=i}return n}async getExpressMethods(e,t){var i,o,a,c,u,g,d,f,p,h;let r=await this.getPaymentSetup(e,t),n={};for(let[y,l]of Object.entries(r)){if(!l.enabled)continue;if(y.startsWith("express_checkout:")&&l.methods){let R={available:!0,processorId:l.processorId,publishableKey:l.publishableKey,metadata:l.metadata};if((i=l.methods.apple_pay)!=null&&i.enabled){let w=typeof window<"u"&&"ApplePaySession"in window&&((a=(o=window.ApplePaySession)==null?void 0:o.canMakePayments)==null?void 0:a.call(o));n.applePay={...R,type:"apple_pay",available:!!w}}(c=l.methods.google_pay)!=null&&c.enabled&&(typeof window<"u"&&!("PaymentRequest"in window)&&((u=this.onSignal)==null||u.call(this,"googlePay",{reason:"no-payment-request-api"})),n.googlePay={...R,type:"google_pay"}),(g=l.methods.link)!=null&&g.enabled&&(n.link={...R,type:"link"}),(d=l.methods.klarna_express)!=null&&d.enabled&&(n.klarna={...R,type:"klarna_express"});continue}if(!l.express)continue;let m=l.method,C={type:m,available:!0,processorId:l.processorId,publishableKey:l.publishableKey,metadata:l.metadata};if(m==="apple_pay"||l.type==="apple_pay"){let R=typeof window<"u"&&"ApplePaySession"in window&&((p=(f=window.ApplePaySession)==null?void 0:f.canMakePayments)==null?void 0:p.call(f));n.applePay={...C,available:!!R}}else m==="google_pay"||l.type==="google_pay"?(typeof window<"u"&&!("PaymentRequest"in window)&&((h=this.onSignal)==null||h.call(this,"googlePay",{reason:"no-payment-request-api"})),n.googlePay=C):m==="paypal"?n.paypal=C:m==="klarna"||m==="klarna_express"?n.klarna=C:m==="link"&&(n.link=C)}return n}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 r=await this.getPaymentSetup(e,t);return Object.entries(r).filter(([,n])=>n.enabled).map(([n])=>n)}async tokenizeCard(e){let t=await this.loadCoreJs(),r=new t.Tokenizer({environment:this.environment});await r.initialize();let n={cardNumber:e.cardNumber,expiryDate:e.expiryDate,cvc:e.cvc};e.cardholderName&&(n.cardholderName=e.cardholderName);let i=await r.tokenizeCardRaw(n);return{tagadaToken:t.createTagadaToken(i,r.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:r,billingAddress:n}=t;if(!r&&!n)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:r,billingAddress:n})}async processApplePay(e){var a,c,u,g,d,f,p,h,y;await this.syncWalletContact(e.checkoutSessionId,{shippingAddress:fe(e.shippingContact),billingAddress:fe(e.billingContact),email:((a=e.shippingContact)==null?void 0:a.emailAddress)??((c=e.billingContact)==null?void 0:c.emailAddress),phone:((u=e.shippingContact)==null?void 0:u.phoneNumber)??((g=e.billingContact)==null?void 0:g.phoneNumber),firstName:((d=e.shippingContact)==null?void 0:d.givenName)??((f=e.billingContact)==null?void 0:f.givenName),lastName:((p=e.shippingContact)==null?void 0:p.familyName)??((h=e.billingContact)==null?void 0:h.familyName)});let t=e.merchantRegistrationId??((y=await this.resolveApplePayRegistration(e.checkoutSessionId))==null?void 0:y.merchantRegistrationId),r=await this.loadCoreJs(),n=new r.Tokenizer({environment:this.environment});await n.initialize();let i=await n.tokenizeApplePay(e.applePayToken,t),o=btoa(JSON.stringify(r.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 r=i=>{var o;for(let a of Object.values(i??{})){let c=(o=a==null?void 0:a.metadata)==null?void 0:o.applePayByok;if(!c||typeof c!="object")continue;let u=c[t];if(u!=null&&u.merchantRegistrationId)return{merchantRegistrationId:u.merchantRegistrationId,displayName:u.displayName}}return null},n=r(this.readInjectedStepConfig())??r(this.lastPaymentSetup);if(n)return n;if(this.lastPaymentSetup||this.readInjectedStepConfig()||!e)return null;try{return r(await this.getPaymentSetup(e))}catch{return null}}async processGooglePay(e){var o,a,c,u;await this.syncWalletContact(e.checkoutSessionId,{shippingAddress:he(e.shippingAddress),billingAddress:he(e.billingAddress),email:e.email??((o=e.shippingAddress)==null?void 0:o.emailAddress)??((a=e.billingAddress)==null?void 0:a.emailAddress),phone:((c=e.shippingAddress)==null?void 0:c.phoneNumber)??((u=e.billingAddress)==null?void 0:u.phoneNumber)});let t=await this.loadCoreJs(),r=new t.Tokenizer({environment:this.environment});await r.initialize();let n=await r.tokenizeGooglePay(e.googlePayToken),i=btoa(JSON.stringify(t.createTagadaDigitalWalletToken(n,"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 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 r=e.payment,n=(t==null?void 0:t.returnUrl)??(typeof window<"u"?window.location.href:void 0);return r.status==="succeeded"?(this.emitPaid((i=e.order)==null?void 0:i.id,r),{status:"succeeded",payment:r,order:e.order}):r.status==="failed"||r.status==="declined"?{status:"failed",error:((o=r.requireActionData)==null?void 0:o.message)||((a=r.requireActionData)==null?void 0:a.errorCode)||`Payment ${r.status}`,payment:r}:r.requireAction&&r.requireAction!=="none"&&r.requireActionData?this.handlePaymentAction(r,{returnUrl:n}):this.pollUntilDone(r.id)}async resumeAfterRedirect(e){return this.pollUntilDone(e)}async maybeResumeFromUrl(e){if(typeof window>"u"&&!(e!=null&&e.url))return null;let t=(e==null?void 0:e.url)??window.location.href,r;try{r=new URL(t)}catch{return null}let n=r.searchParams.get("paymentAction"),i=r.searchParams.get("paymentActionStatus"),o=r.searchParams.get("paymentId");if(n!=="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 c=new URLSearchParams(window.location.search);["paymentAction","paymentActionStatus","paymentId","payment_intent","payment_intent_client_secret","source_type","redirect_status","sessionId"].forEach(g=>c.delete(g));let u=c.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 r=(t==null?void 0:t.intervalMs)??1500,n=(t==null?void 0:t.timeoutMs)??6e4,i=Date.now();for(;Date.now()-i<n;){let o=await this.getPaymentStatus(e);if(o.status==="succeeded"||o.status==="failed"||o.status==="declined")return o;await new Promise(a=>setTimeout(a,r))}throw new Error(`Payment ${e} did not reach terminal status within ${n}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 r=e.requireActionData;switch(await this.markActionProcessed(e.id),r.type){case"threeds_auth":return this.handleThreedsAuth(e,t);case"processor_auth":case"redirect_to_payment":return this.extractRedirect(e,r);case"redirect":return this.extractRedirect(e,r);case"error":return{status:"failed",error:r.message||r.errorCode||"Payment failed",payment:e};default:return this.extractRedirect(e,r)}}extractRedirect(e,t){var i,o;let r=(i=t.metadata)==null?void 0:i.redirect,n=(r==null?void 0:r.redirectUrl)||t.redirectUrl;return n?{status:"requires_redirect",redirectUrl:n,method:((o=r==null?void 0:r.method)==null?void 0:o.toUpperCase())||"GET",postData:r==null?void 0:r.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 r=(o=(i=e.requireActionData)==null?void 0:i.metadata)==null?void 0:o.threedsSession;if(!(r!=null&&r.externalSessionId))return this.extractRedirect(e,e.requireActionData);let n;try{n=await import("@tagadapay/core-js")}catch{return r.acsChallengeUrl?{status:"requires_redirect",redirectUrl:r.acsChallengeUrl,paymentId:e.id}:this.extractRedirect(e,e.requireActionData)}try{let a=new n.ThreedsManager({provider:"basis_theory"});return await a.initialize({apiKey:void 0}),await a.startChallenge({sessionId:r.externalSessionId,acsChallengeUrl:r.acsChallengeUrl,acsTransactionId:r.acsTransID,threeDSVersion:r.messageVersion}),await this.completeAfter3ds(e.id),this.pollUntilDone(e.id)}catch{return r.acsChallengeUrl?{status:"requires_redirect",redirectUrl:r.acsChallengeUrl,paymentId:e.id}:{status:"failed",error:"3D Secure authentication failed",payment:e}}}async pollUntilDone(e,t){var a;let r=(t==null?void 0:t.intervalMs)??1500,n=(t==null?void 0:t.timeoutMs)??6e4,i=Date.now(),o=0;for(;Date.now()-i<n;){let c;try{c=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,r));continue}if(c.status==="succeeded"||c.status==="pending"&&c.subStatus==="authorized")return c.status==="succeeded"&&this.emitPaid((a=c.order)==null?void 0:a.id,c),{status:"succeeded",payment:c,order:c.order};if(c.status==="failed"||c.status==="declined")return{status:"failed",error:c.status,payment:c};if(c.requireAction&&c.requireAction!=="none"&&c.requireActionData&&!c.requireActionData.processed)return this.handlePaymentAction(c,{});await new Promise(u=>setTimeout(u,r))}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 r;if(!(!e||!this.onPaid))try{let n=(r=this.checkout)==null?void 0:r.getCurrentSession();this.onPaid({orderId:e,amount:t.amount,currency:t.currency,items:Pe(n==null?void 0:n.items)})}catch{}}async loadCoreJs(){try{return await import("@tagadapay/core-js")}catch(e){let t=new Error("This method requires @tagadapay/core-js. Install it: npm install @tagadapay/core-js");throw t.cause=e,t}}};var V=typeof document>"u"?null:document.currentScript,Ft=V!=null&&V.src?new URL("tagada-headless-commerce.min.js",V.src).href:"https://cdn.jsdelivr.net/npm/@tagadapay/headless-sdk@1.17.0/dist/tagada-headless-commerce.min.js",we;function ee(){return window.TagadaHeadlessCommerce?Promise.resolve(window.TagadaHeadlessCommerce):(we||(we=new Promise((s,e)=>{let t=document.createElement("script");t.src=Ft,t.async=!0,V!=null&&V.nonce&&(t.nonce=V.nonce),t.addEventListener("load",()=>window.TagadaHeadlessCommerce?s(window.TagadaHeadlessCommerce):e(new Error("Commerce bundle did not initialize"))),t.addEventListener("error",()=>{t.remove(),e(new Error("Unable to load commerce bundle"))}),document.head.appendChild(t)}).catch(s=>{throw we=void 0,s})),we)}var se=class{constructor(...e){this.args=e}load(){return this.instance||(this.instance=ee().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"])se.prototype[s]=function(...e){return this.load().then(t=>t[s](...e))};var ie=class{constructor(...e){this.args=e}load(){return this.instance||(this.instance=ee().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"])ie.prototype[s]=function(...e){return this.load().then(t=>t[s](...e))};var oe=class{constructor(...e){this.args=e}load(){return this.instance||(this.instance=ee().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"])oe.prototype[s]=function(...e){return this.load().then(t=>t[s](...e))};var Ce=class{constructor(e,t){this.http=e;this.storeId=t}async getProducts(e){var n,i;let t={storeId:this.storeId,includeVariants:!0,includePrices:!0};return(n=e==null?void 0:e.productIds)!=null&&n.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 ve=class{constructor(e,t,r,n,i){this.http=e;this.storeId=t;this.checkout=r;this.accountId=n;this.onFunnelSession=i}async navigate(e){var a,c;let t=this.checkout.getCurrentSession();if(!t)throw new q("No checkout session loaded. Call sdk.checkout.loadSession(...) before sdk.funnel.navigate(...).","no_cart_loaded");let r=e.accountId??this.accountId;if(!r)throw new q("accountId is required for funnel.navigate(). Set it on createHeadlessClient({ accountId }) or pass it per call.","missing_account_id");let n=e.currentUrl??(typeof globalThis<"u"?(a=globalThis.location)==null?void 0:a.href:void 0);await this.ensureCmsSession(t,r,e);let i=await this.initializeFunnel({funnelId:e.funnelId,stepId:e.stepId,accountId:r,currentUrl:n});try{(c=this.onFunnelSession)==null||c.call(this,i)}catch{}return{url:await this.runNavigate({funnelSessionId:i,stepId:e.stepId,session:t,input:e,currentUrl:n}),funnelSessionId:i}}async ensureCmsSession(e,t,r){var o,a,c;if(this._cmsToken&&this._cmsSessionId&&this._cmsCustomerId)return;let n=await this.http.post("/api/v1/cms/session/anonymous",{storeId:this.storeId,role:"anonymous",draft:!1});this._cmsToken=n.token,this._cmsSessionId=n.sessionId;let i=await this.http.post("/api/v1/cms/session/v2/init",{storeId:this.storeId,accountId:t,customerId:"anon_placeholder",browserLocale:((o=r.customer)==null?void 0:o.locale)??qt(),userAgent:Gt(),queryCurrency:((a=r.customer)==null?void 0:a.currency)??e.currency,queryLocale:(c=r.customer)==null?void 0:c.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 d,f,p,h;let{funnelSessionId:t,stepId:r,session:n,input:i,currentUrl:o}=e,a=n.items.map(y=>({variantId:y.variantId,priceId:y.priceId,quantity:y.quantity})),c=i.discountCodes??(n.promotionCode?[n.promotionCode]:void 0),u={email:((d=i.customer)==null?void 0:d.email)??((f=n.customer)==null?void 0:f.email),currency:((p=i.customer)==null?void 0:p.currency)??n.currency,locale:(h=i.customer)==null?void 0:h.locale};return(await this.http.post("/api/v1/funnel/navigate",{sessionId:t,currentUrl:o,funnelStepId:r,fireAndForget:!1,event:{type:"INIT_CHECKOUT",data:{checkoutInit:{cartToken:n.id,lineItems:a,customer:u,returnUrl:i.returnUrl,storeId:this.storeId,metadata:i.metadata,discountCodes:c,externalShipping:i.externalShipping}}}},{token:this._cmsToken})).result.url}};function qt(){return typeof navigator<"u"&&navigator.language?navigator.language:"en-US"}function Gt(){return typeof navigator<"u"&&navigator.userAgent?navigator.userAgent:"tagadapay-headless-sdk"}var ke=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 submitCase(e){return this.http.post("/api/public/v1/rx/cases/submit",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 Ie=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,r,n,i;return((r=(t=this.bootstrap)==null?void 0:t.experiments[e])==null?void 0:r.arm)??((i=(n=this.bootstrap)==null?void 0:n.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:r}of this.subscribers.splice(0))try{e?e.onVariant(t,r):r(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,r,n,i;return this.runtime?this.runtime.getPayload(e):(this.read(e),((r=(t=this.bootstrap)==null?void 0:t.experiments[e])==null?void 0:r.payload)??((i=(n=this.bootstrap)==null?void 0:n.flags[e])==null?void 0:i.payload)??null)}isEnabled(e){var t,r;return this.runtime?this.runtime.isEnabled(e):(this.read(e),((r=(t=this.bootstrap)==null?void 0:t.flags[e])==null?void 0:r.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 Ne=class{constructor(e){let t=e.environment??"production",r=re.resolveBaseUrl(t,e.baseUrl);this.config={...e,environment:t,baseUrl:r,timeout:e.timeout??3e4},this.http=new re({baseUrl:r,timeout:this.config.timeout,apiKey:e.apiKey,getToken:()=>this._sessionToken}),this.track=new ye(r,this.config.storeId,this.config.funnel??"main"),this.track.bootstrap=this.config.bootstrap,this.experiments=new Ie(()=>this.track.core(),this.config.bootstrap);let n=i=>{this._sessionToken=i};this.checkout=new ne(this.http,this.config.storeId,n,i=>this.track.noteCheckout({checkoutSessionId:i.id,amount:i.totals.total,currency:i.totals.currency,items:Pe(i.items)})),this.payment=new Se(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 se(this.http,this.config.storeId,this.payment),this.customer=new ie(this.http,this.config.storeId),this.portal=new oe(this.http,this.config.storeId,n),this.catalog=new Ce(this.http,this.config.storeId),this.funnel=new ve(this.http,this.config.storeId,this.checkout,this.config.accountId,i=>this.track.noteFunnelSession(i)),this.rx=new ke(this.http,this.config.storeId)}setSessionToken(e){this._sessionToken=e}};function Ze(s){return new Ne(s)}var tt=M("react/jsx-runtime"),Xe=(0,Q.createContext)(null);function et({storeId:s,environment:e,apiKey:t,baseUrl:r,config:n,children:i}){let o=(0,Q.useMemo)(()=>Ze(n??{storeId:s,environment:e,apiKey:t,baseUrl:r}),[s,e,t,r,n]),a=(0,Q.useMemo)(()=>({client:o}),[o]);return(0,tt.jsx)(Xe.Provider,{value:a,children:i})}function O(){let s=(0,Q.useContext)(Xe);if(!s)throw new Error("useHeadlessClient must be used within <TagadaHeadlessProvider>");return s.client}var _=M("react");function rt(s,e){let t=O(),[r,n]=(0,_.useState)(null),[i,o]=(0,_.useState)(!1),[a,c]=(0,_.useState)(null),u=(0,_.useCallback)(async()=>{if(s){o(!0),c(null);try{let w=await t.checkout.loadSession(s,e);n(w)}catch(w){c(w instanceof Error?w:new Error(String(w)))}finally{o(!1)}}},[t,s,e]);(0,_.useEffect)(()=>{u()},[u]);let g=(0,_.useCallback)(async w=>{o(!0),c(null);try{let P=await t.checkout.createSession(w),v=new URL(window.location.href);v.searchParams.set("checkoutToken",P.checkoutToken),v.searchParams.set("token",P.sessionToken),window.history.replaceState({},"",v.toString());let E=await t.checkout.loadSession(P.checkoutToken,P.sessionToken);n(E)}catch(P){c(P instanceof Error?P:new Error(String(P)))}finally{o(!1)}},[t]),d=(0,_.useCallback)(async w=>{c(null);try{return await t.checkout.createSessionUrl(w)}catch(P){let v=P instanceof Error?P:new Error(String(P));throw c(v),v}},[t]),f=(0,_.useCallback)(async w=>{if(r){o(!0);try{await t.checkout.updateCart(r.id,w),await u()}catch(P){c(P instanceof Error?P:new Error(String(P)))}finally{o(!1)}}},[t,r,u]),p=(0,_.useCallback)(async w=>{r&&await t.checkout.updateCustomer(r.id,w)},[t,r]),h=(0,_.useCallback)(async w=>{if(r){o(!0);try{await t.checkout.updateAddress(r.id,w),await u()}catch(P){c(P instanceof Error?P:new Error(String(P)))}finally{o(!1)}}},[t,r,u]),y=(0,_.useCallback)(async w=>{if(r){o(!0);try{await t.checkout.updateCustomerAndAddress(r.id,w),await u()}catch(P){c(P instanceof Error?P:new Error(String(P)))}finally{o(!1)}}},[t,r,u]),l=(0,_.useCallback)(async w=>{if(r){o(!0);try{await t.checkout.applyPromoCode(r.id,w),await u()}catch(P){c(P instanceof Error?P:new Error(String(P)))}finally{o(!1)}}},[t,r,u]),m=(0,_.useCallback)(async w=>{if(r){o(!0);try{await t.checkout.removePromoCode(r.id,w),await u()}catch(P){c(P instanceof Error?P:new Error(String(P)))}finally{o(!1)}}},[t,r,u]),C=(0,_.useCallback)(async()=>r?t.checkout.getShippingRates(r.id):[],[t,r]),R=(0,_.useCallback)(async w=>{if(r){o(!0);try{await t.checkout.selectShippingRate(r.id,w),await u()}catch(P){c(P instanceof Error?P:new Error(String(P)))}finally{o(!1)}}},[t,r,u]);return{session:r,isLoading:i,error:a,refresh:u,createSession:g,createSessionUrl:d,updateCart:f,updateCustomer:p,updateAddress:h,updateCustomerAndAddress:y,applyPromo:l,removePromo:m,getShippingRates:C,selectShippingRate:R}}var x=M("react");var nt=new Set;function be(s){return nt.has(s)?!1:(nt.add(s),!0)}function st(s){let e=O(),[t,r]=(0,x.useState)(null),[n,i]=(0,x.useState)(null),[o,a]=(0,x.useState)(null),[c,u]=(0,x.useState)(!1),[g,d]=(0,x.useState)(null),[f,p]=(0,x.useState)(null),h=(0,x.useRef)(!1),y=(0,x.useRef)(!1),l=(0,x.useRef)(s);l.current=s,(0,x.useEffect)(()=>{if(typeof window>"u"||y.current)return;let b=new URLSearchParams(window.location.search),S=b.get("paymentAction"),k=b.get("paymentActionStatus"),U=b.get("paymentId");if(S!=="requireAction"||k!=="completed"||!U||(y.current=!0,!be(U)))return;u(!0),p(null),(async()=>{var I,A,j,Z;try{let D=await e.payment.resumeAfterRedirect(U),Ee=new URLSearchParams(window.location.search);["paymentAction","paymentActionStatus","paymentId","payment_intent","payment_intent_client_secret","source_type","redirect_status"].forEach(St=>Ee.delete(St));let Pt=Ee.toString()?`${window.location.pathname}?${Ee.toString()}`:window.location.pathname;window.history.replaceState({},document.title,Pt),D.status==="succeeded"?(A=(I=l.current)==null?void 0:I.onPaymentSuccess)==null||A.call(I,D):D.status==="failed"&&(p(new Error(D.error)),(Z=(j=l.current)==null?void 0:j.onPaymentFailed)==null||Z.call(j,D))}catch(D){p(D instanceof Error?D:new Error(String(D)))}finally{u(!1)}})()},[e]);let m=(0,x.useCallback)(async(b,S)=>{var U;if(h.current)return;h.current=!0;let k=S!=null&&S.paymentSetupConfig?{paymentSetupConfig:S.paymentSetupConfig}:(U=l.current)!=null&&U.paymentSetupConfig?{paymentSetupConfig:l.current.paymentSetupConfig}:void 0;try{let[N,I,A]=await Promise.all([e.payment.getPaymentSetup(b,k),e.payment.getExpressMethods(b,k),e.payment.getStoreConfig()]);r(N),i(I),a(A)}catch(N){h.current=!1,p(N instanceof Error?N:new Error(String(N)))}},[e]),C=(0,x.useCallback)(async b=>{var S,k,U,N;u(!0),p(null);try{let I=await e.payment.processPayment(b);if(I.status==="requires_redirect"){if(I.method==="POST"&&I.postData){let A=document.createElement("form");A.method="POST",A.action=I.redirectUrl;for(let[j,Z]of Object.entries(I.postData)){let D=document.createElement("input");D.type="hidden",D.name=j,D.value=Z,A.appendChild(D)}document.body.appendChild(A),A.submit()}else window.location.href=I.redirectUrl;return I}return I.status==="succeeded"?(k=(S=l.current)==null?void 0:S.onPaymentSuccess)==null||k.call(S,I):I.status==="failed"&&(p(new Error(I.error)),(N=(U=l.current)==null?void 0:U.onPaymentFailed)==null||N.call(U,I)),I}catch(I){let A=I instanceof Error?I:new Error(String(I));return p(A),{status:"failed",error:A.message}}finally{u(!1)}},[e]),R=(0,x.useCallback)(b=>async()=>{u(!0),p(null);try{return await b()}catch(S){let k=S instanceof Error?S:new Error(String(S));throw p(k),k}finally{u(!1)}},[]),w=(0,x.useCallback)(async b=>{u(!0),p(null);try{let S=await e.payment.pay(b);return d(S),S}catch(S){let k=S instanceof Error?S:new Error(String(S));throw p(k),k}finally{u(!1)}},[e]),P=(0,x.useCallback)(b=>e.payment.tokenizeCard(b),[e]),v=(0,x.useCallback)(async b=>{let k=await R(()=>e.payment.processApplePay(b))();return d(k),k},[e,R]),E=(0,x.useCallback)(async b=>{let k=await R(()=>e.payment.processGooglePay(b))();return d(k),k},[e,R]),z=(0,x.useCallback)(async b=>{let k=await R(()=>e.payment.processApm(b))();return d(k),k},[e,R]),H=(0,x.useCallback)(b=>e.payment.pollPaymentStatus(b),[e]);return{paymentSetup:t,expressMethods:n,storeConfig:o,isProcessing:c,result:g,error:f,loadPaymentSetup:m,processPayment:C,pay:w,tokenizeCard:P,processApplePay:v,processGooglePay:E,processApm:z,pollStatus:H}}var T=M("react");function it(s){let e=O(),[t,r]=(0,T.useState)(null),[n,i]=(0,T.useState)(null),[o,a]=(0,T.useState)(!1),[c,u]=(0,T.useState)(null),g=(0,T.useRef)(s);g.current=s;let d=(0,T.useRef)(!1);(0,T.useEffect)(()=>{var S;if(typeof window>"u"||(S=g.current)!=null&&S.disableAutoResume||d.current)return;let v=new URLSearchParams(window.location.search),E=v.get("paymentAction"),z=v.get("paymentActionStatus"),H=v.get("paymentId");if(E!=="requireAction"||z!=="completed"||!H||(d.current=!0,!be(H)))return;a(!0),u(null),(async()=>{var k,U,N,I;try{let A=await e.payment.resumeAfterRedirect(H),j=new URLSearchParams(window.location.search);["paymentAction","paymentActionStatus","paymentId","payment_intent","payment_intent_client_secret","source_type","redirect_status"].forEach(D=>j.delete(D));let Z=j.toString()?`${window.location.pathname}?${j.toString()}`:window.location.pathname;window.history.replaceState({},document.title,Z),A.status==="succeeded"?(U=(k=g.current)==null?void 0:k.onOfferAccepted)==null||U.call(k,A):A.status==="failed"&&(u(new Error(A.error)),(I=(N=g.current)==null?void 0:N.onOfferDeclined)==null||I.call(N,A))}catch(A){u(A instanceof Error?A:new Error(String(A)))}finally{a(!1)}})()},[e]);let f=(0,T.useCallback)(async v=>{a(!0),u(null);try{return await v()}catch(E){let z=E instanceof Error?E:new Error(String(E));throw u(z),z}finally{a(!1)}},[]),p=(0,T.useCallback)(v=>f(async()=>{let E=await e.offers.getOffer(v);return r(E),E}),[e,f]),h=(0,T.useCallback)(v=>e.offers.listOffers(v),[e]),y=(0,T.useCallback)(v=>f(async()=>{let E=await e.offers.previewOffer(v);return i(E),E}),[e,f]),l=(0,T.useCallback)(v=>f(()=>e.offers.payPreviewedOffer(v)),[e,f]),m=(0,T.useCallback)(async v=>{var E,z,H,b;a(!0),u(null);try{let S=await e.offers.processOfferPayment(v);if(S.status==="requires_redirect"){if(S.method==="POST"&&S.postData){let k=document.createElement("form");k.method="POST",k.action=S.redirectUrl;for(let[U,N]of Object.entries(S.postData)){let I=document.createElement("input");I.type="hidden",I.name=U,I.value=N,k.appendChild(I)}document.body.appendChild(k),k.submit()}else window.location.href=S.redirectUrl;return S}return S.status==="succeeded"?(z=(E=g.current)==null?void 0:E.onOfferAccepted)==null||z.call(E,S):S.status==="failed"&&(u(new Error(S.error)),(b=(H=g.current)==null?void 0:H.onOfferDeclined)==null||b.call(H,S)),S}catch(S){let k=S instanceof Error?S:new Error(String(S));return u(k),{status:"failed",error:k.message}}finally{a(!1)}},[e]),C=(0,T.useCallback)(v=>e.offers.toggleOrderBump(v),[e]),R=(0,T.useCallback)(v=>e.offers.listPostPurchaseOffers(v),[e]),w=(0,T.useCallback)(v=>f(()=>e.offers.acceptPostPurchaseOffer(v)),[e,f]),P=(0,T.useCallback)(v=>f(()=>e.offers.declinePostPurchaseOffer(v)),[e,f]);return{offer:t,preview:n,isLoading:o,error:c,getOffer:p,listOffers:h,previewOffer:y,processOfferPayment:m,payPreviewedOffer:l,toggleOrderBump:C,listPostPurchaseOffers:R,acceptPostPurchaseOffer:w,declinePostPurchaseOffer:P}}var G=M("react");function ot(s){let e=O(),[t,r]=(0,G.useState)(null),[n,i]=(0,G.useState)([]),[o,a]=(0,G.useState)([]),[c,u]=(0,G.useState)(!1),[g,d]=(0,G.useState)(null),f=(0,G.useCallback)(async l=>{u(!0),d(null);try{let m=await e.customer.getProfile(l);r(m)}catch(m){d(m instanceof Error?m:new Error(String(m)))}finally{u(!1)}},[e]),p=(0,G.useCallback)(async l=>{try{let m=await e.customer.getOrders(l);i(m.orders)}catch(m){d(m instanceof Error?m:new Error(String(m)))}},[e]),h=(0,G.useCallback)(async l=>{try{let m=await e.customer.getSubscriptions(l);a(m)}catch(m){d(m instanceof Error?m:new Error(String(m)))}},[e]),y=(0,G.useCallback)(async(l,m)=>{try{let C=await e.customer.updateProfile(l,m);r(C)}catch(C){d(C instanceof Error?C:new Error(String(C)))}},[e]);return(0,G.useEffect)(()=>{s&&f(s)},[s,f]),{customer:t,orders:n,subscriptions:o,isLoading:c,error:g,loadCustomer:f,loadOrders:p,loadSubscriptions:h,updateProfile:y}}var $=M("react");function at(s,e){let t=O(),[r,n]=(0,$.useState)(null),[i,o]=(0,$.useState)(!1),[a,c]=(0,$.useState)(null),u=(e==null?void 0:e.watchRelatedOrders)??!0,g=(e==null?void 0:e.watchTimeoutMs)??8e3,d=(e==null?void 0:e.watchIntervalMs)??2e3,f=(0,$.useRef)(0),p=(0,$.useCallback)(async()=>{if(s)try{let h=await t.customer.getOrder(s);n(h)}catch(h){c(h instanceof Error?h:new Error(String(h)))}},[t,s]);return(0,$.useEffect)(()=>{if(!s)return;let h=++f.current,y=()=>f.current===h;return o(!0),c(null),(async()=>{var l,m;try{let C=await t.customer.getOrder(s);if(!y()||(n(C),o(!1),!u||(l=C.relatedOrders)!=null&&l.length))return;let R=Date.now()+g;for(;Date.now()<R&&y();){if(await new Promise(w=>setTimeout(w,d)),!y()||(C=await t.customer.getOrder(s),!y()))return;if((m=C.relatedOrders)!=null&&m.length){n(C);return}}}catch(C){if(!y())return;c(C instanceof Error?C:new Error(String(C))),o(!1)}})(),()=>{f.current++}},[t,s,u,g,d]),{order:r,relatedOrders:(r==null?void 0:r.relatedOrders)??[],isLoading:i,error:a,refresh:p}}var Y=M("react");function ct(){let s=O(),[e,t]=(0,Y.useState)([]),[r,n]=(0,Y.useState)(!1),[i,o]=(0,Y.useState)(null),a=(0,Y.useCallback)(async u=>{n(!0),o(null);try{let g=await s.catalog.getProducts(u);return t(g),g}catch(g){let d=g instanceof Error?g:new Error(String(g));throw o(d),d}finally{n(!1)}},[s]),c=(0,Y.useCallback)(async u=>{n(!0),o(null);try{return await s.catalog.getProduct(u)}catch(g){let d=g instanceof Error?g:new Error(String(g));throw o(d),d}finally{n(!1)}},[s]);return{products:e,isLoading:r,error:i,loadProducts:a,loadProduct:c}}var F=M("react");var Ht=new Set(["approved","shipped","delivered","declined","cancelled","error"]);function ut(){let s=O(),[e,t]=(0,F.useState)([]),[r,n]=(0,F.useState)(null),[i,o]=(0,F.useState)(!1),[a,c]=(0,F.useState)(null),u=(0,F.useRef)(null);(0,F.useEffect)(()=>()=>{u.current&&clearInterval(u.current)},[]);let g=(0,F.useCallback)(async(y,l)=>{o(!0),c(null);try{return await s.rx.isRequiredForProduct(y,l)}catch(m){let C=m instanceof Error?m:new Error(String(m));throw c(C),C}finally{o(!1)}},[s]),d=(0,F.useCallback)(async(y,l)=>{o(!0),c(null);try{return await s.rx.getQuestionsForProduct(y,l)}catch(m){let C=m instanceof Error?m:new Error(String(m));throw c(C),C}finally{o(!1)}},[s]),f=(0,F.useCallback)(async y=>{o(!0),c(null);try{let l=await s.rx.submitCase(y);return n(l),l}catch(l){let m=l instanceof Error?l:new Error(String(l));throw c(m),m}finally{o(!1)}},[s]),p=(0,F.useCallback)(async y=>{o(!0),c(null);try{let l=await s.rx.getCasesForOrder(y);return t(l.cases),l.cases}catch(l){let m=l instanceof Error?l:new Error(String(l));throw c(m),m}finally{o(!1)}},[s]),h=(0,F.useCallback)(({orderId:y,checkoutToken:l},m)=>{u.current&&clearInterval(u.current);let C=(m==null?void 0:m.intervalMs)??5e3,R=async()=>{var w;try{let P=await s.rx.getCasesForOrder({orderId:y,checkoutToken:l});t(P.cases),(w=m==null?void 0:m.onUpdate)==null||w.call(m,P.cases),P.cases.length>0&&P.cases.every(v=>Ht.has(v.status))&&(u.current&&clearInterval(u.current),u.current=null)}catch(P){let v=P instanceof Error?P:new Error(String(P));c(v)}};return R(),u.current=setInterval(R,C),()=>{u.current&&clearInterval(u.current),u.current=null}},[s]);return{cases:e,lastSubmission:r,isLoading:i,error:a,isRequiredForProduct:g,getQuestionsForProduct:d,submitCase:f,fetchCasesForOrder:p,pollOrder:h}}var dt=M("react");function lt(s,e){let t=O(),r=e?JSON.stringify(e):"";(0,dt.useEffect)(()=>{t.track.step(s,e)},[t,s,r])}var L=M("react");var pt=!1,mt=!1,Re=[];function De(){mt=!0;for(let s of Re)s();Re.length=0}function ae(s,e={}){var t,r;return mt||(r=(t=window.google)==null?void 0:t.maps)!=null&&r.places?(De(),Promise.resolve()):pt?new Promise(n=>Re.push(n)):(pt=!0,new Promise((n,i)=>{if(Re.push(n),document.querySelector('script[src*="maps.googleapis.com"]')){let u=()=>{var g,d;(d=(g=window.google)==null?void 0:g.maps)!=null&&d.places?De():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 c=document.createElement("script");c.src=`https://maps.googleapis.com/maps/api/js?${a}`,c.async=!0,c.defer=!0,c.onload=()=>De(),c.onerror=()=>i(new Error("Failed to load Google Maps script")),document.head.appendChild(c)}))}var K=class s{static async searchPlaces(e,t={}){var n,i;if(!((i=(n=window.google)==null?void 0:n.maps)!=null&&i.places)||!e.trim())return[];let r=new window.google.maps.places.AutocompleteService;return new Promise(o=>{r.getPlacePredictions({input:e,types:t.types??["address"],componentRestrictions:t.componentRestrictions},(a,c)=>{var u,g,d;o(c===((d=(g=(u=window.google)==null?void 0:u.maps)==null?void 0:g.places)==null?void 0:d.PlacesServiceStatus.OK)&&a?a:[])})})}static async getPlaceDetails(e){var r,n;if(!((n=(r=window.google)==null?void 0:r.maps)!=null&&n.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 c,u,g;i(a===((g=(u=(c=window.google)==null?void 0:c.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:""},r="",n="",i="",o="",a="",c="",u="",g="";for(let p of e.address_components??[]){let h=p.types;h.includes("subpremise")&&(t.subpremise=p.long_name),h.includes("street_number")&&(t.streetNumber=p.long_name),h.includes("premise")&&(r=p.long_name),h.includes("route")&&(t.route=p.long_name),h.includes("neighborhood")&&(n=p.long_name),h.includes("sublocality_level_5")&&(i=p.long_name),h.includes("sublocality_level_4")&&(o=p.long_name),h.includes("sublocality_level_3")&&(a=p.long_name),h.includes("sublocality_level_2")&&(c=p.long_name),h.includes("sublocality_level_1")&&(u=p.long_name),h.includes("locality")&&(t.locality=p.long_name),h.includes("postal_town")&&(g=p.long_name),h.includes("administrative_area_level_2")&&(t.administrativeAreaLevel2=p.short_name,t.administrativeAreaLevel2Long=p.long_name),h.includes("administrative_area_level_1")&&(t.administrativeAreaLevel1=p.short_name,t.administrativeAreaLevel1Long=p.long_name),h.includes("country")&&(t.country=p.short_name),h.includes("postal_code")&&(t.postalCode=p.long_name)}t.locality||(t.locality=g||c||u||""),!t.administrativeAreaLevel1&&t.administrativeAreaLevel2&&(t.administrativeAreaLevel1=t.administrativeAreaLevel2Long||t.administrativeAreaLevel2,t.administrativeAreaLevel1Long=t.administrativeAreaLevel2Long);let d=t.streetNumber||r,f=t.route||i||o||a||n;if(t.subpremise&&d&&f)t.fullStreetAddress=`${t.subpremise}/${d} ${f}`;else if(d&&f)if(r&&o&&a){let p=`${a}-${o}-${r}`;c&&(p=`${p} ${c}`),t.fullStreetAddress=p}else t.fullStreetAddress=`${d} ${f}`;else f?t.fullStreetAddress=f:d&&(t.fullStreetAddress=d);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}}};function gt(s){let{apiKey:e,language:t,region:r,version:n,defer:i=!1}=s,[o,a]=(0,L.useState)([]),[c,u]=(0,L.useState)(!1),[g,d]=(0,L.useState)(!1),f=(0,L.useRef)(null),p=(0,L.useRef)(null),h=(0,L.useCallback)(()=>{ae(e,{language:t,region:r,version:n}).then(()=>d(!0))},[e,t,r,n]);(0,L.useEffect)(()=>{!e||i||h()},[e,i,h]),(0,L.useEffect)(()=>{if(g&&p.current){let{input:w,country:P}=p.current;p.current=null,y(w,P)}},[g]);let y=(0,L.useCallback)((w,P)=>{if(!g){i&&(p.current={input:w,country:P},h());return}if(w.length<3){a([]);return}f.current&&clearTimeout(f.current),f.current=setTimeout(async()=>{u(!0);let v=await K.searchPlaces(w,{componentRestrictions:P?{country:P.toLowerCase()}:void 0});a(v),u(!1)},300)},[g,i,h]),l=(0,L.useCallback)(w=>K.getPlaceDetails(w),[]),m=(0,L.useCallback)(w=>K.extractAddressComponents(w),[]),C=(0,L.useCallback)(w=>K.extractFormattedAddress(w),[]),R=(0,L.useCallback)(()=>a([]),[]);return{predictions:o,isLoading:c,isScriptLoaded:g,searchPlaces:y,getPlaceDetails:l,extractAddressComponents:m,extractFormattedAddress:C,clearPredictions:R}}var J=M("react");var ft="https://cvwnizdbugpz6jwk.public.blob.vercel-storage.com/geodata/v1",qe=["en","ru","de","da","fr","es","zh","hi","pt","ja","ar","it","he"],ce=new Map,Ae=new Map,Me=new Map,Fe=new Map;async function jt(s){let e=ce.get(s);if(e)return e;let t=Me.get(s);return t||(t=(async()=>{let r=`${ft}/${s}/countries.json`,n=await fetch(r);if(!n.ok)throw new Error(`Geodata fetch failed: ${r} (${n.status})`);let i=await n.json();return ce.set(s,i),Me.delete(s),i})(),Me.set(s,t),t)}async function $t(s){let e=Ae.get(s);if(e)return e;let t=Fe.get(s);return t||(t=(async()=>{let r=`${ft}/${s}/regions.json`,n=await fetch(r);if(!n.ok)throw new Error(`Geodata fetch failed: ${r} (${n.status})`);let i=await n.json();return Ae.set(s,i),Fe.delete(s),i})(),Fe.set(s,t),t)}function Kt(s){return ce.get(s)||ce.get("en")||{}}function Bt(s){return Ae.get(s)||Ae.get("en")||{}}async function ue(s="en"){await Promise.all([jt(s),$t(s)])}var xe=(s="en")=>{let e=Kt(s);return Object.entries(e).map(([t,r])=>({code:t,name:r.n,iso3:r.i3,numeric:r.nu})).sort((t,r)=>t.name.localeCompare(r.name))},Ge=(s,e="en")=>{let r=Bt(e)[s];return r?r.map(([n,i])=>({code:n,name:i,countryCode:s})).sort((n,i)=>n.name.localeCompare(i.name)):[]};function de(s){return ce.has(s)}var B=class s{static ensureLoaded(e="en"){return ue(e)}static getCountries(e="en"){let t=xe(e),r={};for(let n of t)r[n.code]={iso:n.code,iso3:n.iso3??"",numeric:n.numeric??0,name:n.name};return r}static getCountryOptions(e="en"){return xe(e).map(t=>({value:t.code,label:t.name}))}static getRegions(e,t="en"){return Ge(e,t).map(r=>({iso:r.code,name:r.name}))}static getRegionOptions(e,t="en"){return s.getRegions(e,t).map(r=>({value:r.iso,label:r.name}))}static findRegion(e,t,r="en"){return s.getRegions(e,r).find(n=>n.iso===t)??null}static mapGoogleToISO(e,t,r,n="en"){let i=s.getRegions(r,n);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 de(e)}static getAvailableLanguages(){return qe}};function Te(s="en"){let[e,t]=(0,J.useState)(de(s));return(0,J.useEffect)(()=>{let r=!1;return ue(s).then(()=>{r||t(!0)}).catch(n=>console.error("[headless-sdk] Failed to load geodata:",n)),()=>{r=!0}},[s]),(0,J.useMemo)(()=>e?{countries:B.getCountries(s),getRegions:r=>B.getRegions(r,s),findRegion:(r,n)=>B.findRegion(r,n,s),mapGoogleToISO:(r,n,i)=>B.mapGoogleToISO(r,n,i,s),isLoaded:!0}:{countries:{},getRegions:()=>[],findRegion:()=>null,mapGoogleToISO:()=>null,isLoaded:!1},[s,e])}function ht(s="en"){let{countries:e,isLoaded:t}=Te(s);return(0,J.useMemo)(()=>t?Object.values(e).map(r=>({value:r.iso,label:r.name})).sort((r,n)=>r.label.localeCompare(n.label)):[],[e,t])}function yt(s,e="en"){let{getRegions:t,isLoaded:r}=Te(e);return(0,J.useMemo)(()=>!r||!s?[]:t(s).map(n=>({value:n.iso,label:n.name})).sort((n,i)=>n.label.localeCompare(i.label)),[s,t,r])}var zt={USD:"$",EUR:"\u20AC",GBP:"\xA3",JPY:"\xA5",CAD:"C$",AUD:"A$",CHF:"CHF",CNY:"\xA5",SEK:"kr",NOK:"kr",DKK:"kr",PLN:"z\u0142",CZK:"K\u010D",HUF:"Ft",RON:"lei",BGN:"\u043B\u0432",HRK:"kn",RUB:"\u20BD",UAH:"\u20B4",TRY:"\u20BA",BRL:"R$",MXN:"$",ZAR:"R",INR:"\u20B9",KRW:"\u20A9",THB:"\u0E3F",VND:"\u20AB",IDR:"Rp",MYR:"RM",SGD:"S$",PHP:"\u20B1",TWD:"NT$",HKD:"HK$",ILS:"\u20AA",AED:"\u062F.\u0625",SAR:"\u0631.\u0633",QAR:"\u0631.\u0642",KWD:"\u062F.\u0643",BHD:"\u062F.\u0628",OMR:"\u0631.\u0639.",EGP:"\xA3",NGN:"\u20A6",KES:"KSh",GHS:"\u20B5",COP:"$",ARS:"$",CLP:"$",PEN:"S/",CRC:"\u20A1",DOP:"RD$",JMD:"J$",BOB:"Bs",PYG:"\u20B2",GTQ:"Q",NIO:"C$",PAB:"B/.",PKR:"\u20A8",BDT:"\u09F3",LKR:"\u20A8",NPR:"\u20A8",GEL:"\u20BE",AMD:"\u058F",AZN:"\u20BC",KZT:"\u20B8"},Vt={USD:"US Dollar",EUR:"Euro",GBP:"British Pound",JPY:"Japanese Yen",CAD:"Canadian Dollar",AUD:"Australian Dollar",CHF:"Swiss Franc",CNY:"Chinese Yuan",SEK:"Swedish Krona",NOK:"Norwegian Krone",DKK:"Danish Krone",PLN:"Polish Zloty",CZK:"Czech Koruna",HUF:"Hungarian Forint",BRL:"Brazilian Real",MXN:"Mexican Peso",INR:"Indian Rupee",KRW:"South Korean Won",THB:"Thai Baht",SGD:"Singapore Dollar",HKD:"Hong Kong Dollar",TWD:"Taiwan Dollar",ILS:"Israeli Shekel",AED:"UAE Dirham",SAR:"Saudi Riyal",ZAR:"South African Rand",TRY:"Turkish Lira",RUB:"Russian Ruble",NGN:"Nigerian Naira"},Jt=new Set(["JPY","KRW","VND","IDR","LAK","KHR","MMK","PYG"]),W=class s{static getSymbol(e){return zt[e]??e}static getName(e){return Vt[e]??e}static getDecimalPlaces(e){return Jt.has(e)?0:2}static getCurrency(e){return{code:e,symbol:s.getSymbol(e),name:s.getName(e),decimalPlaces:s.getDecimalPlaces(e)}}};function He(s,e="USD",t="en-US"){let r=W.getDecimalPlaces(e),n=s/(r===0?100:Math.pow(10,r));try{return new Intl.NumberFormat(t,{style:"currency",currency:e,minimumFractionDigits:r,maximumFractionDigits:r}).format(n)}catch{return`${W.getSymbol(e)}${n.toFixed(r)}`}}return Rt(Qt);})();
|
|
6
|
+
"use strict";var TagadaHeadlessReactBundle=(()=>{var Ct=Object.create;var de=Object.defineProperty;var St=Object.getOwnPropertyDescriptor;var vt=Object.getOwnPropertyNames;var kt=Object.getPrototypeOf,It=Object.prototype.hasOwnProperty;var M=(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 bt=(s,e)=>{for(var t in e)de(s,t,{get:e[t],enumerable:!0})},je=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of vt(e))!It.call(s,n)&&n!==t&&de(s,n,{get:()=>e[n],enumerable:!(r=St(e,n))||r.enumerable});return s};var Ee=(s,e,t)=>(t=s!=null?Ct(kt(s)):{},je(e||!s||!s.__esModule?de(t,"default",{value:s,enumerable:!0}):t,s)),Rt=s=>je(de({},"__esModule",{value:!0}),s);var Wt={};bt(Wt,{CurrencyUtils:()=>W,GoogleAutocompleteCore:()=>K,ISODataCore:()=>B,TagadaHeadlessProvider:()=>et,formatMoney:()=>Ge,loadGoogleMapsScript:()=>ae,parseTokensFromUrl:()=>Ke,useCatalog:()=>ct,useCheckout:()=>rt,useCountryOptions:()=>ht,useCustomer:()=>ot,useGoogleAutocomplete:()=>gt,useHeadlessClient:()=>E,useISOData:()=>Te,useOffers:()=>it,useOrder:()=>at,usePayment:()=>st,useRegionOptions:()=>yt,useRx:()=>ut,useStep:()=>dt});var Q=M("react");var q=class extends Error{constructor(e,t,r,n){super(e),this.name="TagadaError",this.code=t,this.statusCode=r,this.details=n}},pe=class extends q{constructor(e="Authentication failed. Check your API key or checkout token."){super(e,"auth_error",401),this.name="TagadaAuthError"}},me=class extends q{constructor(e,t=[],r,n){super(e,"validation_error",422,{errors:t,...n}),this.name="TagadaValidationError",this.errors=t,this.appCode=r}},X=class extends q{constructor(e,t){super(`${e} "${t}" not found.`,"not_found",404),this.name="TagadaNotFoundError"}},ge=class extends q{constructor(e=1e3){super(`Rate limited. Retry after ${e}ms.`,"rate_limit",429),this.name="TagadaRateLimitError",this.retryAfterMs=e}};var te=class extends q{constructor(e="Network request failed. Check your connection."){super(e,"network_error"),this.name="TagadaNetworkError"}};var $e={production:"https://api.tagada.io",development:"https://api.tagada.dev",local:"http://localhost:3000"},re=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??$e[e]??$e.production}async request(e,t={}){var h;let{method:r="GET",body:n,headers:i={},params:o,token:a,signal:c}=t,u=`${this.baseUrl}${e}`;if(o){let y=new URLSearchParams;for(let[m,S]of Object.entries(o))S!==void 0&&y.set(m,String(S));let d=y.toString();d&&(u+=`?${d}`)}let g={"Content-Type":"application/json",...i},l=a??this.apiKey??((h=this.getToken)==null?void 0:h.call(this));l&&(g["x-cms-token"]=l);let f=new AbortController,p=setTimeout(()=>f.abort(),this.timeout);try{let y=await fetch(u,{method:r,headers:g,body:n!=null?JSON.stringify(n):void 0,signal:c??f.signal,...this.redirect&&{redirect:this.redirect}});if(clearTimeout(p),y.ok){let d=await y.text();return d?JSON.parse(d):{}}throw await this.handleErrorResponse(y,e),new q("Unexpected error","unknown",y.status)}catch(y){throw clearTimeout(p),y instanceof q?y:y instanceof DOMException&&y.name==="AbortError"?new te(`Request to ${e} timed out after ${this.timeout}ms.`):new te(y instanceof Error?y.message:"Network request failed.")}}get(e,t){return this.request(e,{...t,method:"GET"})}post(e,t,r){return this.request(e,{...r,method:"POST",body:t})}patch(e,t,r){return this.request(e,{...r,method:"PATCH",body:t})}put(e,t,r){return this.request(e,{...r,method:"PUT",body:t})}delete(e,t){return this.request(e,{...t,method:"DELETE"})}async handleErrorResponse(e,t){let r={};try{r=await e.json()}catch{}let n=xt(r.data),i=r.message||r.error||(typeof n.message=="string"?n.message:void 0)||(typeof r.data=="string"&&Object.keys(n).length===0?r.data:void 0)||`Request failed: ${e.status} ${e.statusText} on ${t}`,o=typeof n.code=="string"?n.code:void 0;switch(e.status){case 401:case 403:throw new pe(i);case 404:throw new X(t,"");case 422:{let a=Array.isArray(r.errors)?r.errors:[];throw new me(i,a,o,r)}case 429:{let a=Number(e.headers.get("Retry-After")??"1")*1e3;throw new ge(a)}default:throw new q(i,"api_error",e.status,r)}}};function xt(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 ne=class s{constructor(e,t,r,n){this.http=e;this.storeId=t;this.onTokenChange=r;this.onSession=n}getCurrentSession(){return this._currentSession}async loadSession(e,t,r){var a,c;t&&(this.sessionToken=t,(a=this.onTokenChange)==null||a.call(this,t));let n={skipAsyncWait:"false"};r!=null&&r.currency&&(n.currency=r.currency);let i=await this.http.get(`/api/v1/checkout-sessions/${e}/v2`,{params:n,token:this.sessionToken}),o=this.normalizeSession(i);this._currentSession=o;try{(c=this.onSession)==null||c.call(this,o)}catch{}return o}async createSession(e){var c,u,g;let t=e.items.map(l=>({variantId:l.variantId,priceId:l.priceId,...l.sellingPlanId!==void 0?{sellingPlanId:l.sellingPlanId}:{},...l.trialDays!==void 0?{trialDays:l.trialDays}:{},...l.trialPrice!==void 0?{trialPrice:l.trialPrice}:{},quantity:l.quantity})),r={storeId:this.storeId,lineItems:t};e.returnUrl&&(r.returnUrl=e.returnUrl),e.funnelSessionId&&(r.funnelSessionId=e.funnelSessionId),(c=e.discountCodes)!=null&&c.length&&(r.discountCodes=e.discountCodes),e.metadata&&Object.keys(e.metadata).length>0&&(r.metadata=e.metadata),e.customerMetadata&&Object.keys(e.customerMetadata).length>0&&(r.customerMetadata=e.customerMetadata),(u=e.customerTags)!=null&&u.length&&(r.customerTags=e.customerTags);let n={};e.currency&&(n.currency=e.currency),e.customerEmail&&(n.email=e.customerEmail,n.firstName=e.customerFirstName,n.lastName=e.customerLastName),Object.keys(n).length>0&&(r.customer=n);let i=await this.http.post("/api/v1/checkout/session/init",r),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:r,...n}=e,i=await this.createSession(n),o=r??(typeof window<"u"?window.location.origin:""),a=new URLSearchParams({checkoutToken:i.checkoutToken,sessionToken:i.sessionToken}),c=`${o}${t}?${a.toString()}`;return{...i,url:c}}static parseTokensFromUrl(e){if(typeof e>"u"&&typeof window>"u")return null;let t=e??window.location.href,r;try{r=new URL(t)}catch{return null}let n=r.searchParams.get("checkoutToken");if(!n)return null;let i=r.searchParams.get("sessionToken")??r.searchParams.get("token")??"";return{checkoutToken:n,sessionToken:i}}parseTokensFromUrl(e){return s.parseTokensFromUrl(e)}async updateCart(e,t){let r=t.map(n=>({variantId:n.variantId,priceId:n.priceId,...n.sellingPlanId!==void 0?{sellingPlanId:n.sellingPlanId}:{},quantity:n.quantity}));return this.http.post(`/api/v1/checkout-sessions/${e}/line-items`,{lineItems:r},{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 r=this.mapAddress(t.shippingAddress),n=this.mapAddress(t.billingAddress),i=r??n??{},o=n??r,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 r=this.mapAddress(t.shippingAddress),n=this.mapAddress(t.billingAddress),i=r??n??{},o=n??r,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 At({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 r=t??"default";await this.http.delete(`/api/v1/checkout-sessions/${e}/promotions/${r}`,{token:this.sessionToken})}async getShippingRates(e){return((await this.http.get(`/api/v1/checkout-sessions/${e}/shipping-rates`,{token:this.sessionToken})).rates??[]).map(r=>this.normalizeShippingRate(r))}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,r=t.orderSummaries??[],n=e.summary??t.summary??r[0]??{},i=t.sessionLineItems??[],o=t.customer,a=(g=n.currency??t.selectedPresentmentCurrency)==null?void 0:g.toUpperCase(),c=i.map(l=>{let f=l.price,p=l.variant??(f==null?void 0:f.variant)??{},h=l.product??p.product??{},y=(f==null?void 0:f.currencyOptions)??{},d=(a?y[a]:void 0)??y[Object.keys(y)[0]],m=(d==null?void 0:d.amount)??0;return{id:l.id,variantId:l.variantId,priceId:l.priceId,productName:h.name??"",variantName:p.name??"",quantity:l.quantity??1,unitAmount:m,totalAmount:m*(l.quantity??1),currency:a??"USD",imageUrl:p.imageUrl??h.imageUrl??"",...f!=null&&f.recurring?{recurring:{interval:f.interval??"month",intervalCount:f.intervalCount??1}}:{}}}),u=n.items??[];return{id:t.id,storeId:t.storeId,checkoutToken:t.checkoutToken,currency:a??"USD",items:c,totals:{subtotal:n.subtotalAmount??0,discount:n.totalPromotionAmount??0,shipping:n.shippingCost??0,tax:n.totalTaxAmount??0,total:n.totalAdjustedAmount??n.totalAmount??u.reduce((l,f)=>l+(f.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,r={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(r).some(n=>n!==void 0&&n!=="")?r:void 0}},Ke=ne.parseTokensFromUrl;function At(s){let e={};for(let[t,r]of Object.entries(s))r!=null&&r!==""&&(e[t]=r);return Object.keys(e).length>0?e:void 0}function fe(s){var t,r;if(!s)return;let e={firstName:s.givenName,lastName:s.familyName,line1:(t=s.addressLines)==null?void 0:t[0],line2:(r=s.addressLines)==null?void 0:r[1],city:s.locality,state:s.administrativeArea,postalCode:s.postalCode,country:s.countryCode,phone:s.phoneNumber};return Be(e)?e:void 0}function he(s){if(!s)return;let[e,...t]=(s.name??"").trim().split(/\s+/),r={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 Be(r)?r:void 0}function Be(s){var e,t;return!!((e=s.line1)!=null&&e.trim()&&((t=s.country)!=null&&t.trim()))}var _e="headless",Le="1.19.0";var ze="https://cdn.jsdelivr.net/npm/@tagadapay/headless-sdk@1.19.0/dist/tagada-pixels.min.js";function We(s,e){return e()?Promise.resolve():new Promise((t,r)=>{let n=document.createElement("script");n.src=s,n.async=!0,n.onload=()=>t(),n.onerror=()=>r(new Error("runtime script failed to load")),document.head.appendChild(n)})}async function Tt(){if(typeof window>"u")return null;if(ze){let s=window;return s.TagadaPixels?s.TagadaPixels:(await We(ze,()=>!!s.TagadaPixels),s.TagadaPixels??null)}return await import("../../pixels/index.js")}var Ve="__tgd_track",Ot="__tgd_aid",Et="__tgd_sid",Je=50,_t=2e3,Qe=1e3,Lt=64;function Pe(s){if(!(!Array.isArray(s)||s.length===0))return s.map(e=>({id:e.variantId,quantity:e.quantity,item_price:e.unitAmount}))}function Ye(s){if(!s)return;let e={};for(let[t,r]of Object.entries(s))(typeof r=="string"||typeof r=="number"||typeof r=="boolean")&&(e[t]=r);return Object.keys(e).length>0?e:void 0}var Ut={lead:"Lead",product_viewed:"ViewContent",added_to_cart:"AddToCart"};function Ue(){try{return crypto.randomUUID()}catch{return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}}function Nt(s){let e={};for(let t of s){let{provider:r,id:n,idKey:i,...o}=t;(e[r]??(e[r]=[])).push({...o,enabled:!0,[i]:n,events:t.events??{}})}return e}var ye=class{constructor(e,t,r){this.baseUrl=e;this.storeId=t;this.funnelKey=r;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(Ve)??"").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(Ve,`${this.storeId}:${this.funnelKey}`)}catch{}}step(e,t){if(typeof window>"u")return;this.arm();let r=(t==null?void 0:t.path)??window.location.pathname,n=`${e}|${r}`,i=Date.now(),o=this.lastStep.get(n);o!==void 0&&i-o<Qe||(this.remember(n,i),this.currentStepId=e,this.listen(),this.push({kind:"step",stepId:e,at:i,path:r}),this.pixels().then(a=>a==null?void 0:a.pageView(r,{stepId:e})),this.core().then(a=>a==null?void 0:a.page({step_id:e})).catch(()=>{}))}event(e,t){if(this.off())return;let r=this.currentStepId;if(r===null)return;let n=Ut[e],i=`${n??e}_${Ue()}`;this.push({kind:"event",stepId:r,name:e,at:Date.now(),eventId:i,props:Ye(t)}),this.pixels().then(o=>n?o==null?void 0:o.track(n,t,{stepId:r,eventId:i}):o==null?void 0:o.trackCustom(e,t,{stepId:r})),this.core().then(o=>o==null?void 0:o.track(e,{...Ye(t)??{},step_id:r,pixel_event_id:i})).catch(()=>{})}remember(e,t){for(let[r,n]of this.lastStep)t-n>=Qe&&this.lastStep.delete(r);for(;this.lastStep.size>=Lt;){let r=this.lastStep.keys().next();if(r.done===!0)break;this.lastStep.delete(r.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,r){this.off()||this.pixels().then(n=>{var i;return n==null?void 0:n.track(e,{value:r.amount,currency:r.currency,contents:r.items,num_items:(i=r.items)==null?void 0:i.length},{eventId:`${e}_${t}`})})}noteSignal(e,t,r){this.off()||(this.signals.push({signal:e,value:t,detail:r}),this.listen(),this.push({kind:"signal",signal:e,value:t,detail:r}))}snapshot(){return{enabled:typeof window>"u"?!1:this.enabled(),storeId:this.storeId,funnelKey:this.flagFunnelKey(),sdk:{name:_e,version:Le},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 r=await t.json();return this.manifestHash=r.manifestHash||null,r}catch{return null}})(),this.configPromise}core(){return typeof window>"u"?Promise.resolve(null):(this.corePromise??(this.corePromise=(async()=>{var e,t;try{let r=await this.config();if(!r||!r.collect&&!r.experiments)return null;let n=this.baseUrl.replace(/\/+$/,""),i=window;return typeof((e=i.tgd)==null?void 0:e.init)!="function"&&await We(n+"/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:r.collect?new URL(r.collect.url).origin:n,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 r=await Tt();if(r===null)return null;let n=r.createPixelEngine({pixels:Nt(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 n.init(),this.loadedProviders=[...new Set((t.pixels??[]).map(i=>i.provider))],n}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>=Je){this.flush();return}this.flushTimer===null&&(this.flushTimer=setTimeout(()=>this.flush(),_t))}}identifier(e,t){try{let r=e==="local"?localStorage:sessionStorage,n=r.getItem(t);if(n)return n;let i=Ue();return r.setItem(t,i),i}catch{return Ue()}}flush(){if(this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.records.length===0)return;let e=this.records.splice(0,Je),t={storeId:this.storeId,funnelKey:this.flagFunnelKey(),sdk:{name:_e,version:Le},anonymousId:this.identifier("local",Ot),sessionId:this.identifier("session",Et),records:e};this.manifestHash!==null&&(t.manifestHash=this.manifestHash);let r=JSON.stringify(t),n=`${this.baseUrl}/api/public/v1/sdk/events`;try{if(typeof navigator<"u"&&typeof navigator.sendBeacon=="function"&&navigator.sendBeacon(n,new Blob([r],{type:"text/plain;charset=UTF-8"})))return}catch{}try{fetch(n,{method:"POST",body:r,keepalive:!0,headers:{"content-type":"text/plain;charset=UTF-8"}}).catch(()=>{})}catch{}}};var Dt=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,r=s.settings??{},n=r.processors,i=r.publishableKey;return{enabled:!0,method:t,provider:e?void 0:s.type,type:e?"card":s.type,label:s.title,logoUrl:s.iconUrl,express:Dt.has(t),integrationId:e?void 0:s.id,processorId:(o=n==null?void 0:n[0])==null?void 0:o.processorId,publishableKey:typeof i=="string"?i:void 0,metadata:s.metadata??void 0}}var we=class{constructor(e,t,r,n,i,o){this.http=e;this.storeId=t;this.environment=r;this.checkout=n;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 r=this.readInjectedStepConfig();if(r)return this.lastPaymentSetup=r,r;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 X))throw i}let n=await this.getPaymentSetupFromPickerList(e);return this.lastPaymentSetup=n,n}async getPaymentSetupFromPickerList(e){let t=await this.http.get("/api/v1/payment-methods",{params:{checkoutSessionId:e}}),r=Array.isArray(t)?t.map(Mt):(t==null?void 0:t.methods)??[],n={};for(let i of r){let o=i.provider&&i.provider!==i.method?`${i.method}:${i.provider}`:i.method;n[o]=i}return n}async getExpressMethods(e,t){var i,o,a,c,u,g,l,f,p,h;let r=await this.getPaymentSetup(e,t),n={};for(let[y,d]of Object.entries(r)){if(!d.enabled)continue;if(y.startsWith("express_checkout:")&&d.methods){let R={available:!0,processorId:d.processorId,publishableKey:d.publishableKey,metadata:d.metadata};if((i=d.methods.apple_pay)!=null&&i.enabled){let C=typeof window<"u"&&"ApplePaySession"in window&&((a=(o=window.ApplePaySession)==null?void 0:o.canMakePayments)==null?void 0:a.call(o));n.applePay={...R,type:"apple_pay",available:!!C}}(c=d.methods.google_pay)!=null&&c.enabled&&(typeof window<"u"&&!("PaymentRequest"in window)&&((u=this.onSignal)==null||u.call(this,"googlePay",{reason:"no-payment-request-api"})),n.googlePay={...R,type:"google_pay"}),(g=d.methods.link)!=null&&g.enabled&&(n.link={...R,type:"link"}),(l=d.methods.klarna_express)!=null&&l.enabled&&(n.klarna={...R,type:"klarna_express"});continue}if(!d.express)continue;let m=d.method,S={type:m,available:!0,processorId:d.processorId,publishableKey:d.publishableKey,metadata:d.metadata};if(m==="apple_pay"||d.type==="apple_pay"){let R=typeof window<"u"&&"ApplePaySession"in window&&((p=(f=window.ApplePaySession)==null?void 0:f.canMakePayments)==null?void 0:p.call(f));n.applePay={...S,available:!!R}}else m==="google_pay"||d.type==="google_pay"?(typeof window<"u"&&!("PaymentRequest"in window)&&((h=this.onSignal)==null||h.call(this,"googlePay",{reason:"no-payment-request-api"})),n.googlePay=S):m==="paypal"?n.paypal=S:m==="klarna"||m==="klarna_express"?n.klarna=S:m==="link"&&(n.link=S)}return n}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 r=await this.getPaymentSetup(e,t);return Object.entries(r).filter(([,n])=>n.enabled).map(([n])=>n)}async tokenizeCard(e){let t=await this.loadCoreJs(),r=new t.Tokenizer({environment:this.environment});await r.initialize();let n={cardNumber:e.cardNumber,expiryDate:e.expiryDate,cvc:e.cvc};e.cardholderName&&(n.cardholderName=e.cardholderName);let i=await r.tokenizeCardRaw(n);return{tagadaToken:t.createTagadaToken(i,r.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:r,billingAddress:n}=t;if(!r&&!n)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:r,billingAddress:n})}async processApplePay(e){var a,c,u,g,l,f,p,h,y;await this.syncWalletContact(e.checkoutSessionId,{shippingAddress:fe(e.shippingContact),billingAddress:fe(e.billingContact),email:((a=e.shippingContact)==null?void 0:a.emailAddress)??((c=e.billingContact)==null?void 0:c.emailAddress),phone:((u=e.shippingContact)==null?void 0:u.phoneNumber)??((g=e.billingContact)==null?void 0:g.phoneNumber),firstName:((l=e.shippingContact)==null?void 0:l.givenName)??((f=e.billingContact)==null?void 0:f.givenName),lastName:((p=e.shippingContact)==null?void 0:p.familyName)??((h=e.billingContact)==null?void 0:h.familyName)});let t=e.merchantRegistrationId??((y=await this.resolveApplePayRegistration(e.checkoutSessionId))==null?void 0:y.merchantRegistrationId),r=await this.loadCoreJs(),n=new r.Tokenizer({environment:this.environment});await n.initialize();let i=await n.tokenizeApplePay(e.applePayToken,t),o=btoa(JSON.stringify(r.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 r=i=>{var o;for(let a of Object.values(i??{})){let c=(o=a==null?void 0:a.metadata)==null?void 0:o.applePayByok;if(!c||typeof c!="object")continue;let u=c[t];if(u!=null&&u.merchantRegistrationId)return{merchantRegistrationId:u.merchantRegistrationId,displayName:u.displayName}}return null},n=r(this.readInjectedStepConfig())??r(this.lastPaymentSetup);if(n)return n;if(this.lastPaymentSetup||this.readInjectedStepConfig()||!e)return null;try{return r(await this.getPaymentSetup(e))}catch{return null}}async processGooglePay(e){var o,a,c,u;await this.syncWalletContact(e.checkoutSessionId,{shippingAddress:he(e.shippingAddress),billingAddress:he(e.billingAddress),email:e.email??((o=e.shippingAddress)==null?void 0:o.emailAddress)??((a=e.billingAddress)==null?void 0:a.emailAddress),phone:((c=e.shippingAddress)==null?void 0:c.phoneNumber)??((u=e.billingAddress)==null?void 0:u.phoneNumber)});let t=await this.loadCoreJs(),r=new t.Tokenizer({environment:this.environment});await r.initialize();let n=await r.tokenizeGooglePay(e.googlePayToken),i=btoa(JSON.stringify(t.createTagadaDigitalWalletToken(n,"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 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 r=e.payment,n=(t==null?void 0:t.returnUrl)??(typeof window<"u"?window.location.href:void 0);return r.status==="succeeded"?(this.emitPaid((i=e.order)==null?void 0:i.id,r),{status:"succeeded",payment:r,order:e.order}):r.status==="failed"||r.status==="declined"?{status:"failed",error:((o=r.requireActionData)==null?void 0:o.message)||((a=r.requireActionData)==null?void 0:a.errorCode)||`Payment ${r.status}`,payment:r}:r.requireAction&&r.requireAction!=="none"&&r.requireActionData?this.handlePaymentAction(r,{returnUrl:n}):this.pollUntilDone(r.id)}async resumeAfterRedirect(e){return this.pollUntilDone(e)}async maybeResumeFromUrl(e){if(typeof window>"u"&&!(e!=null&&e.url))return null;let t=(e==null?void 0:e.url)??window.location.href,r;try{r=new URL(t)}catch{return null}let n=r.searchParams.get("paymentAction"),i=r.searchParams.get("paymentActionStatus"),o=r.searchParams.get("paymentId");if(n!=="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 c=new URLSearchParams(window.location.search);["paymentAction","paymentActionStatus","paymentId","payment_intent","payment_intent_client_secret","source_type","redirect_status","sessionId"].forEach(g=>c.delete(g));let u=c.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 r=(t==null?void 0:t.intervalMs)??1500,n=(t==null?void 0:t.timeoutMs)??6e4,i=Date.now();for(;Date.now()-i<n;){let o=await this.getPaymentStatus(e);if(o.status==="succeeded"||o.status==="failed"||o.status==="declined")return o;await new Promise(a=>setTimeout(a,r))}throw new Error(`Payment ${e} did not reach terminal status within ${n}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 r=e.requireActionData;switch(await this.markActionProcessed(e.id),r.type){case"threeds_auth":return this.handleThreedsAuth(e,t);case"processor_auth":case"redirect_to_payment":return this.extractRedirect(e,r);case"redirect":return this.extractRedirect(e,r);case"error":return{status:"failed",error:r.message||r.errorCode||"Payment failed",payment:e};default:return this.extractRedirect(e,r)}}extractRedirect(e,t){var i,o;let r=(i=t.metadata)==null?void 0:i.redirect,n=(r==null?void 0:r.redirectUrl)||t.redirectUrl;return n?{status:"requires_redirect",redirectUrl:n,method:((o=r==null?void 0:r.method)==null?void 0:o.toUpperCase())||"GET",postData:r==null?void 0:r.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 r=(o=(i=e.requireActionData)==null?void 0:i.metadata)==null?void 0:o.threedsSession;if(!(r!=null&&r.externalSessionId))return this.extractRedirect(e,e.requireActionData);let n;try{n=await import("@tagadapay/core-js")}catch{return r.acsChallengeUrl?{status:"requires_redirect",redirectUrl:r.acsChallengeUrl,paymentId:e.id}:this.extractRedirect(e,e.requireActionData)}try{let a=new n.ThreedsManager({provider:"basis_theory"});return await a.initialize({apiKey:void 0}),await a.startChallenge({sessionId:r.externalSessionId,acsChallengeUrl:r.acsChallengeUrl,acsTransactionId:r.acsTransID,threeDSVersion:r.messageVersion}),await this.completeAfter3ds(e.id),this.pollUntilDone(e.id)}catch{return r.acsChallengeUrl?{status:"requires_redirect",redirectUrl:r.acsChallengeUrl,paymentId:e.id}:{status:"failed",error:"3D Secure authentication failed",payment:e}}}async pollUntilDone(e,t){var a;let r=(t==null?void 0:t.intervalMs)??1500,n=(t==null?void 0:t.timeoutMs)??6e4,i=Date.now(),o=0;for(;Date.now()-i<n;){let c;try{c=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,r));continue}if(c.status==="succeeded"||c.status==="pending"&&c.subStatus==="authorized")return c.status==="succeeded"&&this.emitPaid((a=c.order)==null?void 0:a.id,c),{status:"succeeded",payment:c,order:c.order};if(c.status==="failed"||c.status==="declined")return{status:"failed",error:c.status,payment:c};if(c.requireAction&&c.requireAction!=="none"&&c.requireActionData&&!c.requireActionData.processed)return this.handlePaymentAction(c,{});await new Promise(u=>setTimeout(u,r))}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 r;if(!(!e||!this.onPaid))try{let n=(r=this.checkout)==null?void 0:r.getCurrentSession();this.onPaid({orderId:e,amount:t.amount,currency:t.currency,items:Pe(n==null?void 0:n.items)})}catch{}}async loadCoreJs(){try{return await import("@tagadapay/core-js")}catch(e){let t=new Error("This method requires @tagadapay/core-js. Install it: npm install @tagadapay/core-js");throw t.cause=e,t}}};var V=typeof document>"u"?null:document.currentScript,Ft=V!=null&&V.src?new URL("tagada-headless-commerce.min.js",V.src).href:"https://cdn.jsdelivr.net/npm/@tagadapay/headless-sdk@1.19.0/dist/tagada-headless-commerce.min.js",Ce;function ee(){return window.TagadaHeadlessCommerce?Promise.resolve(window.TagadaHeadlessCommerce):(Ce||(Ce=new Promise((s,e)=>{let t=document.createElement("script");t.src=Ft,t.async=!0,V!=null&&V.nonce&&(t.nonce=V.nonce),t.addEventListener("load",()=>window.TagadaHeadlessCommerce?s(window.TagadaHeadlessCommerce):e(new Error("Commerce bundle did not initialize"))),t.addEventListener("error",()=>{t.remove(),e(new Error("Unable to load commerce bundle"))}),document.head.appendChild(t)}).catch(s=>{throw Ce=void 0,s})),Ce)}var se=class{constructor(...e){this.args=e}load(){return this.instance||(this.instance=ee().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"])se.prototype[s]=function(...e){return this.load().then(t=>t[s](...e))};var ie=class{constructor(...e){this.args=e}load(){return this.instance||(this.instance=ee().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"])ie.prototype[s]=function(...e){return this.load().then(t=>t[s](...e))};var oe=class{constructor(...e){this.args=e}load(){return this.instance||(this.instance=ee().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"])oe.prototype[s]=function(...e){return this.load().then(t=>t[s](...e))};var Se=class{constructor(e,t){this.http=e;this.storeId=t}async getProducts(e){var n,i;let t={storeId:this.storeId,includeVariants:!0,includePrices:!0};return(n=e==null?void 0:e.productIds)!=null&&n.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 ve=class{constructor(e,t,r,n,i){this.http=e;this.storeId=t;this.checkout=r;this.accountId=n;this.onFunnelSession=i}async navigate(e){var a,c;let t=this.checkout.getCurrentSession();if(!t)throw new q("No checkout session loaded. Call sdk.checkout.loadSession(...) before sdk.funnel.navigate(...).","no_cart_loaded");let r=e.accountId??this.accountId;if(!r)throw new q("accountId is required for funnel.navigate(). Set it on createHeadlessClient({ accountId }) or pass it per call.","missing_account_id");let n=e.currentUrl??(typeof globalThis<"u"?(a=globalThis.location)==null?void 0:a.href:void 0);await this.ensureCmsSession(t,r,e);let i=await this.initializeFunnel({funnelId:e.funnelId,stepId:e.stepId,accountId:r,currentUrl:n});try{(c=this.onFunnelSession)==null||c.call(this,i)}catch{}return{url:await this.runNavigate({funnelSessionId:i,stepId:e.stepId,session:t,input:e,currentUrl:n}),funnelSessionId:i}}async ensureCmsSession(e,t,r){var o,a,c;if(this._cmsToken&&this._cmsSessionId&&this._cmsCustomerId)return;let n=await this.http.post("/api/v1/cms/session/anonymous",{storeId:this.storeId,role:"anonymous",draft:!1});this._cmsToken=n.token,this._cmsSessionId=n.sessionId;let i=await this.http.post("/api/v1/cms/session/v2/init",{storeId:this.storeId,accountId:t,customerId:"anon_placeholder",browserLocale:((o=r.customer)==null?void 0:o.locale)??qt(),userAgent:Ht(),queryCurrency:((a=r.customer)==null?void 0:a.currency)??e.currency,queryLocale:(c=r.customer)==null?void 0:c.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 l,f,p,h;let{funnelSessionId:t,stepId:r,session:n,input:i,currentUrl:o}=e,a=n.items.map(y=>({variantId:y.variantId,priceId:y.priceId,quantity:y.quantity})),c=i.discountCodes??(n.promotionCode?[n.promotionCode]:void 0),u={email:((l=i.customer)==null?void 0:l.email)??((f=n.customer)==null?void 0:f.email),currency:((p=i.customer)==null?void 0:p.currency)??n.currency,locale:(h=i.customer)==null?void 0:h.locale};return(await this.http.post("/api/v1/funnel/navigate",{sessionId:t,currentUrl:o,funnelStepId:r,fireAndForget:!1,event:{type:"INIT_CHECKOUT",data:{checkoutInit:{cartToken:n.id,lineItems:a,customer:u,returnUrl:i.returnUrl,storeId:this.storeId,metadata:i.metadata,discountCodes:c,externalShipping:i.externalShipping}}}},{token:this._cmsToken})).result.url}};function qt(){return typeof navigator<"u"&&navigator.language?navigator.language:"en-US"}function Ht(){return typeof navigator<"u"&&navigator.userAgent?navigator.userAgent:"tagadapay-headless-sdk"}var ke=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 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 Ie=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,r,n,i;return((r=(t=this.bootstrap)==null?void 0:t.experiments[e])==null?void 0:r.arm)??((i=(n=this.bootstrap)==null?void 0:n.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:r}of this.subscribers.splice(0))try{e?e.onVariant(t,r):r(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,r,n,i;return this.runtime?this.runtime.getPayload(e):(this.read(e),((r=(t=this.bootstrap)==null?void 0:t.experiments[e])==null?void 0:r.payload)??((i=(n=this.bootstrap)==null?void 0:n.flags[e])==null?void 0:i.payload)??null)}isEnabled(e){var t,r;return this.runtime?this.runtime.isEnabled(e):(this.read(e),((r=(t=this.bootstrap)==null?void 0:t.flags[e])==null?void 0:r.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 Ne=class{constructor(e){let t=e.environment??"production",r=re.resolveBaseUrl(t,e.baseUrl);this.config={...e,environment:t,baseUrl:r,timeout:e.timeout??3e4},this.http=new re({baseUrl:r,timeout:this.config.timeout,apiKey:e.apiKey,getToken:()=>this._sessionToken}),this.track=new ye(r,this.config.storeId,this.config.funnel??"main"),this.track.bootstrap=this.config.bootstrap,this.experiments=new Ie(()=>this.track.core(),this.config.bootstrap);let n=i=>{this._sessionToken=i};this.checkout=new ne(this.http,this.config.storeId,n,i=>this.track.noteCheckout({checkoutSessionId:i.id,amount:i.totals.total,currency:i.totals.currency,items:Pe(i.items)})),this.payment=new we(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 se(this.http,this.config.storeId,this.payment),this.customer=new ie(this.http,this.config.storeId),this.portal=new oe(this.http,this.config.storeId,n),this.catalog=new Se(this.http,this.config.storeId),this.funnel=new ve(this.http,this.config.storeId,this.checkout,this.config.accountId,i=>this.track.noteFunnelSession(i)),this.rx=new ke(this.http,this.config.storeId)}setSessionToken(e){this._sessionToken=e}};function Ze(s){return new Ne(s)}var tt=M("react/jsx-runtime"),Xe=(0,Q.createContext)(null);function Gt(s){let e={storeId:s.storeId,environment:s.environment,apiKey:s.apiKey,baseUrl:s.baseUrl,accountId:s.accountId,funnel:s.funnel,timeout:s.timeout,bootstrap:s.bootstrap};return JSON.stringify(e)}function jt(s){if(s.config)return s.config;let{storeId:e,environment:t,apiKey:r,baseUrl:n}=s;return{storeId:e,environment:t,apiKey:r,baseUrl:n}}function et(s){let e=jt(s),t=Gt(e),r=(0,Q.useMemo)(()=>Ze(e),[t]),n=(0,Q.useMemo)(()=>({client:r}),[r]);return(0,tt.jsx)(Xe.Provider,{value:n,children:s.children})}function E(){let s=(0,Q.useContext)(Xe);if(!s)throw new Error("useHeadlessClient must be used within <TagadaHeadlessProvider>");return s.client}var _=M("react");function rt(s,e){let t=E(),[r,n]=(0,_.useState)(null),[i,o]=(0,_.useState)(!1),[a,c]=(0,_.useState)(null),u=(0,_.useCallback)(async()=>{if(s){o(!0),c(null);try{let C=await t.checkout.loadSession(s,e);n(C)}catch(C){c(C instanceof Error?C:new Error(String(C)))}finally{o(!1)}}},[t,s,e]);(0,_.useEffect)(()=>{u()},[u]);let g=(0,_.useCallback)(async C=>{o(!0),c(null);try{let P=await t.checkout.createSession(C),v=new URL(window.location.href);v.searchParams.set("checkoutToken",P.checkoutToken),v.searchParams.set("token",P.sessionToken),window.history.replaceState({},"",v.toString());let O=await t.checkout.loadSession(P.checkoutToken,P.sessionToken);n(O)}catch(P){c(P instanceof Error?P:new Error(String(P)))}finally{o(!1)}},[t]),l=(0,_.useCallback)(async C=>{c(null);try{return await t.checkout.createSessionUrl(C)}catch(P){let v=P instanceof Error?P:new Error(String(P));throw c(v),v}},[t]),f=(0,_.useCallback)(async C=>{if(r){o(!0);try{await t.checkout.updateCart(r.id,C),await u()}catch(P){c(P instanceof Error?P:new Error(String(P)))}finally{o(!1)}}},[t,r,u]),p=(0,_.useCallback)(async C=>{r&&await t.checkout.updateCustomer(r.id,C)},[t,r]),h=(0,_.useCallback)(async C=>{if(r){o(!0);try{await t.checkout.updateAddress(r.id,C),await u()}catch(P){c(P instanceof Error?P:new Error(String(P)))}finally{o(!1)}}},[t,r,u]),y=(0,_.useCallback)(async C=>{if(r){o(!0);try{await t.checkout.updateCustomerAndAddress(r.id,C),await u()}catch(P){c(P instanceof Error?P:new Error(String(P)))}finally{o(!1)}}},[t,r,u]),d=(0,_.useCallback)(async C=>{if(r){o(!0);try{await t.checkout.applyPromoCode(r.id,C),await u()}catch(P){c(P instanceof Error?P:new Error(String(P)))}finally{o(!1)}}},[t,r,u]),m=(0,_.useCallback)(async C=>{if(r){o(!0);try{await t.checkout.removePromoCode(r.id,C),await u()}catch(P){c(P instanceof Error?P:new Error(String(P)))}finally{o(!1)}}},[t,r,u]),S=(0,_.useCallback)(async()=>r?t.checkout.getShippingRates(r.id):[],[t,r]),R=(0,_.useCallback)(async C=>{if(r){o(!0);try{await t.checkout.selectShippingRate(r.id,C),await u()}catch(P){c(P instanceof Error?P:new Error(String(P)))}finally{o(!1)}}},[t,r,u]);return{session:r,isLoading:i,error:a,refresh:u,createSession:g,createSessionUrl:l,updateCart:f,updateCustomer:p,updateAddress:h,updateCustomerAndAddress:y,applyPromo:d,removePromo:m,getShippingRates:S,selectShippingRate:R}}var A=M("react");var nt=new Set;function be(s){return nt.has(s)?!1:(nt.add(s),!0)}function st(s){let e=E(),[t,r]=(0,A.useState)(null),[n,i]=(0,A.useState)(null),[o,a]=(0,A.useState)(null),[c,u]=(0,A.useState)(!1),[g,l]=(0,A.useState)(null),[f,p]=(0,A.useState)(null),h=(0,A.useRef)(!1),y=(0,A.useRef)(!1),d=(0,A.useRef)(s);d.current=s,(0,A.useEffect)(()=>{if(typeof window>"u"||y.current)return;let b=new URLSearchParams(window.location.search),w=b.get("paymentAction"),k=b.get("paymentActionStatus"),U=b.get("paymentId");if(w!=="requireAction"||k!=="completed"||!U||(y.current=!0,!be(U)))return;u(!0),p(null),(async()=>{var I,x,j,Z;try{let D=await e.payment.resumeAfterRedirect(U),Oe=new URLSearchParams(window.location.search);["paymentAction","paymentActionStatus","paymentId","payment_intent","payment_intent_client_secret","source_type","redirect_status"].forEach(wt=>Oe.delete(wt));let Pt=Oe.toString()?`${window.location.pathname}?${Oe.toString()}`:window.location.pathname;window.history.replaceState({},document.title,Pt),D.status==="succeeded"?(x=(I=d.current)==null?void 0:I.onPaymentSuccess)==null||x.call(I,D):D.status==="failed"&&(p(new Error(D.error)),(Z=(j=d.current)==null?void 0:j.onPaymentFailed)==null||Z.call(j,D))}catch(D){p(D instanceof Error?D:new Error(String(D)))}finally{u(!1)}})()},[e]);let m=(0,A.useCallback)(async(b,w)=>{var U;if(h.current)return;h.current=!0;let k=w!=null&&w.paymentSetupConfig?{paymentSetupConfig:w.paymentSetupConfig}:(U=d.current)!=null&&U.paymentSetupConfig?{paymentSetupConfig:d.current.paymentSetupConfig}:void 0;try{let[N,I,x]=await Promise.all([e.payment.getPaymentSetup(b,k),e.payment.getExpressMethods(b,k),e.payment.getStoreConfig()]);r(N),i(I),a(x)}catch(N){h.current=!1,p(N instanceof Error?N:new Error(String(N)))}},[e]),S=(0,A.useCallback)(async b=>{var w,k,U,N;u(!0),p(null);try{let I=await e.payment.processPayment(b);if(I.status==="requires_redirect"){if(I.method==="POST"&&I.postData){let x=document.createElement("form");x.method="POST",x.action=I.redirectUrl;for(let[j,Z]of Object.entries(I.postData)){let D=document.createElement("input");D.type="hidden",D.name=j,D.value=Z,x.appendChild(D)}document.body.appendChild(x),x.submit()}else window.location.href=I.redirectUrl;return I}return I.status==="succeeded"?(k=(w=d.current)==null?void 0:w.onPaymentSuccess)==null||k.call(w,I):I.status==="failed"&&(p(new Error(I.error)),(N=(U=d.current)==null?void 0:U.onPaymentFailed)==null||N.call(U,I)),I}catch(I){let x=I instanceof Error?I:new Error(String(I));return p(x),{status:"failed",error:x.message}}finally{u(!1)}},[e]),R=(0,A.useCallback)(b=>async()=>{u(!0),p(null);try{return await b()}catch(w){let k=w instanceof Error?w:new Error(String(w));throw p(k),k}finally{u(!1)}},[]),C=(0,A.useCallback)(async b=>{u(!0),p(null);try{let w=await e.payment.pay(b);return l(w),w}catch(w){let k=w instanceof Error?w:new Error(String(w));throw p(k),k}finally{u(!1)}},[e]),P=(0,A.useCallback)(b=>e.payment.tokenizeCard(b),[e]),v=(0,A.useCallback)(async b=>{let k=await R(()=>e.payment.processApplePay(b))();return l(k),k},[e,R]),O=(0,A.useCallback)(async b=>{let k=await R(()=>e.payment.processGooglePay(b))();return l(k),k},[e,R]),z=(0,A.useCallback)(async b=>{let k=await R(()=>e.payment.processApm(b))();return l(k),k},[e,R]),G=(0,A.useCallback)(b=>e.payment.pollPaymentStatus(b),[e]);return{paymentSetup:t,expressMethods:n,storeConfig:o,isProcessing:c,result:g,error:f,loadPaymentSetup:m,processPayment:S,pay:C,tokenizeCard:P,processApplePay:v,processGooglePay:O,processApm:z,pollStatus:G}}var T=M("react");function it(s){let e=E(),[t,r]=(0,T.useState)(null),[n,i]=(0,T.useState)(null),[o,a]=(0,T.useState)(!1),[c,u]=(0,T.useState)(null),g=(0,T.useRef)(s);g.current=s;let l=(0,T.useRef)(!1);(0,T.useEffect)(()=>{var w;if(typeof window>"u"||(w=g.current)!=null&&w.disableAutoResume||l.current)return;let v=new URLSearchParams(window.location.search),O=v.get("paymentAction"),z=v.get("paymentActionStatus"),G=v.get("paymentId");if(O!=="requireAction"||z!=="completed"||!G||(l.current=!0,!be(G)))return;a(!0),u(null),(async()=>{var k,U,N,I;try{let x=await e.payment.resumeAfterRedirect(G),j=new URLSearchParams(window.location.search);["paymentAction","paymentActionStatus","paymentId","payment_intent","payment_intent_client_secret","source_type","redirect_status"].forEach(D=>j.delete(D));let Z=j.toString()?`${window.location.pathname}?${j.toString()}`:window.location.pathname;window.history.replaceState({},document.title,Z),x.status==="succeeded"?(U=(k=g.current)==null?void 0:k.onOfferAccepted)==null||U.call(k,x):x.status==="failed"&&(u(new Error(x.error)),(I=(N=g.current)==null?void 0:N.onOfferDeclined)==null||I.call(N,x))}catch(x){u(x instanceof Error?x:new Error(String(x)))}finally{a(!1)}})()},[e]);let f=(0,T.useCallback)(async v=>{a(!0),u(null);try{return await v()}catch(O){let z=O instanceof Error?O:new Error(String(O));throw u(z),z}finally{a(!1)}},[]),p=(0,T.useCallback)(v=>f(async()=>{let O=await e.offers.getOffer(v);return r(O),O}),[e,f]),h=(0,T.useCallback)(v=>e.offers.listOffers(v),[e]),y=(0,T.useCallback)(v=>f(async()=>{let O=await e.offers.previewOffer(v);return i(O),O}),[e,f]),d=(0,T.useCallback)(v=>f(()=>e.offers.payPreviewedOffer(v)),[e,f]),m=(0,T.useCallback)(async v=>{var O,z,G,b;a(!0),u(null);try{let w=await e.offers.processOfferPayment(v);if(w.status==="requires_redirect"){if(w.method==="POST"&&w.postData){let k=document.createElement("form");k.method="POST",k.action=w.redirectUrl;for(let[U,N]of Object.entries(w.postData)){let I=document.createElement("input");I.type="hidden",I.name=U,I.value=N,k.appendChild(I)}document.body.appendChild(k),k.submit()}else window.location.href=w.redirectUrl;return w}return w.status==="succeeded"?(z=(O=g.current)==null?void 0:O.onOfferAccepted)==null||z.call(O,w):w.status==="failed"&&(u(new Error(w.error)),(b=(G=g.current)==null?void 0:G.onOfferDeclined)==null||b.call(G,w)),w}catch(w){let k=w instanceof Error?w:new Error(String(w));return u(k),{status:"failed",error:k.message}}finally{a(!1)}},[e]),S=(0,T.useCallback)(v=>e.offers.toggleOrderBump(v),[e]),R=(0,T.useCallback)(v=>e.offers.listPostPurchaseOffers(v),[e]),C=(0,T.useCallback)(v=>f(()=>e.offers.acceptPostPurchaseOffer(v)),[e,f]),P=(0,T.useCallback)(v=>f(()=>e.offers.declinePostPurchaseOffer(v)),[e,f]);return{offer:t,preview:n,isLoading:o,error:c,getOffer:p,listOffers:h,previewOffer:y,processOfferPayment:m,payPreviewedOffer:d,toggleOrderBump:S,listPostPurchaseOffers:R,acceptPostPurchaseOffer:C,declinePostPurchaseOffer:P}}var H=M("react");function ot(s){let e=E(),[t,r]=(0,H.useState)(null),[n,i]=(0,H.useState)([]),[o,a]=(0,H.useState)([]),[c,u]=(0,H.useState)(!1),[g,l]=(0,H.useState)(null),f=(0,H.useCallback)(async d=>{u(!0),l(null);try{let m=await e.customer.getProfile(d);r(m)}catch(m){l(m instanceof Error?m:new Error(String(m)))}finally{u(!1)}},[e]),p=(0,H.useCallback)(async d=>{try{let m=await e.customer.getOrders(d);i(m.orders)}catch(m){l(m instanceof Error?m:new Error(String(m)))}},[e]),h=(0,H.useCallback)(async d=>{try{let m=await e.customer.getSubscriptions(d);a(m)}catch(m){l(m instanceof Error?m:new Error(String(m)))}},[e]),y=(0,H.useCallback)(async(d,m)=>{try{let S=await e.customer.updateProfile(d,m);r(S)}catch(S){l(S instanceof Error?S:new Error(String(S)))}},[e]);return(0,H.useEffect)(()=>{s&&f(s)},[s,f]),{customer:t,orders:n,subscriptions:o,isLoading:c,error:g,loadCustomer:f,loadOrders:p,loadSubscriptions:h,updateProfile:y}}var $=M("react");function at(s,e){let t=E(),[r,n]=(0,$.useState)(null),[i,o]=(0,$.useState)(!1),[a,c]=(0,$.useState)(null),u=(e==null?void 0:e.watchRelatedOrders)??!0,g=(e==null?void 0:e.watchTimeoutMs)??8e3,l=(e==null?void 0:e.watchIntervalMs)??2e3,f=(0,$.useRef)(0),p=(0,$.useCallback)(async()=>{if(s)try{let h=await t.customer.getOrder(s);n(h)}catch(h){c(h instanceof Error?h:new Error(String(h)))}},[t,s]);return(0,$.useEffect)(()=>{if(!s)return;let h=++f.current,y=()=>f.current===h;return o(!0),c(null),(async()=>{var d,m;try{let S=await t.customer.getOrder(s);if(!y()||(n(S),o(!1),!u||(d=S.relatedOrders)!=null&&d.length))return;let R=Date.now()+g;for(;Date.now()<R&&y();){if(await new Promise(C=>setTimeout(C,l)),!y()||(S=await t.customer.getOrder(s),!y()))return;if((m=S.relatedOrders)!=null&&m.length){n(S);return}}}catch(S){if(!y())return;c(S instanceof Error?S:new Error(String(S))),o(!1)}})(),()=>{f.current++}},[t,s,u,g,l]),{order:r,relatedOrders:(r==null?void 0:r.relatedOrders)??[],isLoading:i,error:a,refresh:p}}var Y=M("react");function ct(){let s=E(),[e,t]=(0,Y.useState)([]),[r,n]=(0,Y.useState)(!1),[i,o]=(0,Y.useState)(null),a=(0,Y.useCallback)(async u=>{n(!0),o(null);try{let g=await s.catalog.getProducts(u);return t(g),g}catch(g){let l=g instanceof Error?g:new Error(String(g));throw o(l),l}finally{n(!1)}},[s]),c=(0,Y.useCallback)(async u=>{n(!0),o(null);try{return await s.catalog.getProduct(u)}catch(g){let l=g instanceof Error?g:new Error(String(g));throw o(l),l}finally{n(!1)}},[s]);return{products:e,isLoading:r,error:i,loadProducts:a,loadProduct:c}}var F=M("react");var $t=new Set(["approved","shipped","delivered","declined","cancelled","error"]);function ut(){let s=E(),[e,t]=(0,F.useState)([]),[r,n]=(0,F.useState)(null),[i,o]=(0,F.useState)(!1),[a,c]=(0,F.useState)(null),u=(0,F.useRef)(null);(0,F.useEffect)(()=>()=>{u.current&&clearInterval(u.current)},[]);let g=(0,F.useCallback)(async(y,d)=>{o(!0),c(null);try{return await s.rx.isRequiredForProduct(y,d)}catch(m){let S=m instanceof Error?m:new Error(String(m));throw c(S),S}finally{o(!1)}},[s]),l=(0,F.useCallback)(async(y,d)=>{o(!0),c(null);try{return await s.rx.getQuestionsForProduct(y,d)}catch(m){let S=m instanceof Error?m:new Error(String(m));throw c(S),S}finally{o(!1)}},[s]),f=(0,F.useCallback)(async y=>{o(!0),c(null);try{let d=await s.rx.submitCase(y);return n(d),d}catch(d){let m=d instanceof Error?d:new Error(String(d));throw c(m),m}finally{o(!1)}},[s]),p=(0,F.useCallback)(async y=>{o(!0),c(null);try{let d=await s.rx.getCasesForOrder(y);return t(d.cases),d.cases}catch(d){let m=d instanceof Error?d:new Error(String(d));throw c(m),m}finally{o(!1)}},[s]),h=(0,F.useCallback)(({orderId:y,checkoutToken:d},m)=>{u.current&&clearInterval(u.current);let S=(m==null?void 0:m.intervalMs)??5e3,R=async()=>{var C;try{let P=await s.rx.getCasesForOrder({orderId:y,checkoutToken:d});t(P.cases),(C=m==null?void 0:m.onUpdate)==null||C.call(m,P.cases),P.cases.length>0&&P.cases.every(v=>$t.has(v.status))&&(u.current&&clearInterval(u.current),u.current=null)}catch(P){let v=P instanceof Error?P:new Error(String(P));c(v)}};return R(),u.current=setInterval(R,S),()=>{u.current&&clearInterval(u.current),u.current=null}},[s]);return{cases:e,lastSubmission:r,isLoading:i,error:a,isRequiredForProduct:g,getQuestionsForProduct:l,submitCase:f,fetchCasesForOrder:p,pollOrder:h}}var lt=M("react");function dt(s,e){let t=E(),r=e?JSON.stringify(e):"";(0,lt.useEffect)(()=>{t.track.step(s,e)},[t,s,r])}var L=M("react");var pt=!1,mt=!1,Re=[];function De(){mt=!0;for(let s of Re)s();Re.length=0}function ae(s,e={}){var t,r;return mt||(r=(t=window.google)==null?void 0:t.maps)!=null&&r.places?(De(),Promise.resolve()):pt?new Promise(n=>Re.push(n)):(pt=!0,new Promise((n,i)=>{if(Re.push(n),document.querySelector('script[src*="maps.googleapis.com"]')){let u=()=>{var g,l;(l=(g=window.google)==null?void 0:g.maps)!=null&&l.places?De():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 c=document.createElement("script");c.src=`https://maps.googleapis.com/maps/api/js?${a}`,c.async=!0,c.defer=!0,c.onload=()=>De(),c.onerror=()=>i(new Error("Failed to load Google Maps script")),document.head.appendChild(c)}))}var K=class s{static async searchPlaces(e,t={}){var n,i;if(!((i=(n=window.google)==null?void 0:n.maps)!=null&&i.places)||!e.trim())return[];let r=new window.google.maps.places.AutocompleteService;return new Promise(o=>{r.getPlacePredictions({input:e,types:t.types??["address"],componentRestrictions:t.componentRestrictions},(a,c)=>{var u,g,l;o(c===((l=(g=(u=window.google)==null?void 0:u.maps)==null?void 0:g.places)==null?void 0:l.PlacesServiceStatus.OK)&&a?a:[])})})}static async getPlaceDetails(e){var r,n;if(!((n=(r=window.google)==null?void 0:r.maps)!=null&&n.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 c,u,g;i(a===((g=(u=(c=window.google)==null?void 0:c.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:""},r="",n="",i="",o="",a="",c="",u="",g="";for(let p of e.address_components??[]){let h=p.types;h.includes("subpremise")&&(t.subpremise=p.long_name),h.includes("street_number")&&(t.streetNumber=p.long_name),h.includes("premise")&&(r=p.long_name),h.includes("route")&&(t.route=p.long_name),h.includes("neighborhood")&&(n=p.long_name),h.includes("sublocality_level_5")&&(i=p.long_name),h.includes("sublocality_level_4")&&(o=p.long_name),h.includes("sublocality_level_3")&&(a=p.long_name),h.includes("sublocality_level_2")&&(c=p.long_name),h.includes("sublocality_level_1")&&(u=p.long_name),h.includes("locality")&&(t.locality=p.long_name),h.includes("postal_town")&&(g=p.long_name),h.includes("administrative_area_level_2")&&(t.administrativeAreaLevel2=p.short_name,t.administrativeAreaLevel2Long=p.long_name),h.includes("administrative_area_level_1")&&(t.administrativeAreaLevel1=p.short_name,t.administrativeAreaLevel1Long=p.long_name),h.includes("country")&&(t.country=p.short_name),h.includes("postal_code")&&(t.postalCode=p.long_name)}t.locality||(t.locality=g||c||u||""),!t.administrativeAreaLevel1&&t.administrativeAreaLevel2&&(t.administrativeAreaLevel1=t.administrativeAreaLevel2Long||t.administrativeAreaLevel2,t.administrativeAreaLevel1Long=t.administrativeAreaLevel2Long);let l=t.streetNumber||r,f=t.route||i||o||a||n;if(t.subpremise&&l&&f)t.fullStreetAddress=`${t.subpremise}/${l} ${f}`;else if(l&&f)if(r&&o&&a){let p=`${a}-${o}-${r}`;c&&(p=`${p} ${c}`),t.fullStreetAddress=p}else t.fullStreetAddress=`${l} ${f}`;else f?t.fullStreetAddress=f:l&&(t.fullStreetAddress=l);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}}};function gt(s){let{apiKey:e,language:t,region:r,version:n,defer:i=!1}=s,[o,a]=(0,L.useState)([]),[c,u]=(0,L.useState)(!1),[g,l]=(0,L.useState)(!1),f=(0,L.useRef)(null),p=(0,L.useRef)(null),h=(0,L.useCallback)(()=>{ae(e,{language:t,region:r,version:n}).then(()=>l(!0))},[e,t,r,n]);(0,L.useEffect)(()=>{!e||i||h()},[e,i,h]),(0,L.useEffect)(()=>{if(g&&p.current){let{input:C,country:P}=p.current;p.current=null,y(C,P)}},[g]);let y=(0,L.useCallback)((C,P)=>{if(!g){i&&(p.current={input:C,country:P},h());return}if(C.length<3){a([]);return}f.current&&clearTimeout(f.current),f.current=setTimeout(async()=>{u(!0);let v=await K.searchPlaces(C,{componentRestrictions:P?{country:P.toLowerCase()}:void 0});a(v),u(!1)},300)},[g,i,h]),d=(0,L.useCallback)(C=>K.getPlaceDetails(C),[]),m=(0,L.useCallback)(C=>K.extractAddressComponents(C),[]),S=(0,L.useCallback)(C=>K.extractFormattedAddress(C),[]),R=(0,L.useCallback)(()=>a([]),[]);return{predictions:o,isLoading:c,isScriptLoaded:g,searchPlaces:y,getPlaceDetails:d,extractAddressComponents:m,extractFormattedAddress:S,clearPredictions:R}}var J=M("react");var ft="https://cvwnizdbugpz6jwk.public.blob.vercel-storage.com/geodata/v1",qe=["en","ru","de","da","fr","es","zh","hi","pt","ja","ar","it","he"],ce=new Map,xe=new Map,Me=new Map,Fe=new Map;async function Kt(s){let e=ce.get(s);if(e)return e;let t=Me.get(s);return t||(t=(async()=>{let r=`${ft}/${s}/countries.json`,n=await fetch(r);if(!n.ok)throw new Error(`Geodata fetch failed: ${r} (${n.status})`);let i=await n.json();return ce.set(s,i),Me.delete(s),i})(),Me.set(s,t),t)}async function Bt(s){let e=xe.get(s);if(e)return e;let t=Fe.get(s);return t||(t=(async()=>{let r=`${ft}/${s}/regions.json`,n=await fetch(r);if(!n.ok)throw new Error(`Geodata fetch failed: ${r} (${n.status})`);let i=await n.json();return xe.set(s,i),Fe.delete(s),i})(),Fe.set(s,t),t)}function zt(s){return ce.get(s)||ce.get("en")||{}}function Vt(s){return xe.get(s)||xe.get("en")||{}}async function ue(s="en"){await Promise.all([Kt(s),Bt(s)])}var Ae=(s="en")=>{let e=zt(s);return Object.entries(e).map(([t,r])=>({code:t,name:r.n,iso3:r.i3,numeric:r.nu})).sort((t,r)=>t.name.localeCompare(r.name))},He=(s,e="en")=>{let r=Vt(e)[s];return r?r.map(([n,i])=>({code:n,name:i,countryCode:s})).sort((n,i)=>n.name.localeCompare(i.name)):[]};function le(s){return ce.has(s)}var B=class s{static ensureLoaded(e="en"){return ue(e)}static getCountries(e="en"){let t=Ae(e),r={};for(let n of t)r[n.code]={iso:n.code,iso3:n.iso3??"",numeric:n.numeric??0,name:n.name};return r}static getCountryOptions(e="en"){return Ae(e).map(t=>({value:t.code,label:t.name}))}static getRegions(e,t="en"){return He(e,t).map(r=>({iso:r.code,name:r.name}))}static getRegionOptions(e,t="en"){return s.getRegions(e,t).map(r=>({value:r.iso,label:r.name}))}static findRegion(e,t,r="en"){return s.getRegions(e,r).find(n=>n.iso===t)??null}static mapGoogleToISO(e,t,r,n="en"){let i=s.getRegions(r,n);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 le(e)}static getAvailableLanguages(){return qe}};function Te(s="en"){let[e,t]=(0,J.useState)(le(s));return(0,J.useEffect)(()=>{let r=!1;return ue(s).then(()=>{r||t(!0)}).catch(n=>console.error("[headless-sdk] Failed to load geodata:",n)),()=>{r=!0}},[s]),(0,J.useMemo)(()=>e?{countries:B.getCountries(s),getRegions:r=>B.getRegions(r,s),findRegion:(r,n)=>B.findRegion(r,n,s),mapGoogleToISO:(r,n,i)=>B.mapGoogleToISO(r,n,i,s),isLoaded:!0}:{countries:{},getRegions:()=>[],findRegion:()=>null,mapGoogleToISO:()=>null,isLoaded:!1},[s,e])}function ht(s="en"){let{countries:e,isLoaded:t}=Te(s);return(0,J.useMemo)(()=>t?Object.values(e).map(r=>({value:r.iso,label:r.name})).sort((r,n)=>r.label.localeCompare(n.label)):[],[e,t])}function yt(s,e="en"){let{getRegions:t,isLoaded:r}=Te(e);return(0,J.useMemo)(()=>!r||!s?[]:t(s).map(n=>({value:n.iso,label:n.name})).sort((n,i)=>n.label.localeCompare(i.label)),[s,t,r])}var Jt={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"},Qt={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"},Yt=new Set(["JPY","KRW","VND","IDR","LAK","KHR","MMK","PYG"]),W=class s{static getSymbol(e){return Jt[e]??e}static getName(e){return Qt[e]??e}static getDecimalPlaces(e){return Yt.has(e)?0:2}static getCurrency(e){return{code:e,symbol:s.getSymbol(e),name:s.getName(e),decimalPlaces:s.getDecimalPlaces(e)}}};function Ge(s,e="USD",t="en-US"){let r=W.getDecimalPlaces(e),n=s/(r===0?100:Math.pow(10,r));try{return new Intl.NumberFormat(t,{style:"currency",currency:e,minimumFractionDigits:r,maximumFractionDigits:r}).format(n)}catch{return`${W.getSymbol(e)}${n.toFixed(r)}`}}return Rt(Wt);})();
|
|
7
7
|
if(typeof window!=="undefined"&&TagadaHeadlessReactBundle){ window.TagadaHeadlessReact=TagadaHeadlessReactBundle;}
|
|
8
8
|
//# sourceMappingURL=tagada-headless-react.min.js.map
|