@tagadapay/headless-sdk 1.12.0 → 1.13.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +233 -220
- package/dist/core/index.d.ts +1 -0
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js +1 -0
- package/dist/core/index.js.map +1 -1
- package/dist/core/modules/checkout.d.ts +15 -0
- package/dist/core/modules/checkout.d.ts.map +1 -1
- package/dist/core/modules/checkout.js +21 -1
- package/dist/core/modules/checkout.js.map +1 -1
- package/dist/core/modules/customer.d.ts +28 -2
- package/dist/core/modules/customer.d.ts.map +1 -1
- package/dist/core/modules/customer.js +40 -6
- package/dist/core/modules/customer.js.map +1 -1
- package/dist/core/modules/payment.d.ts +8 -0
- package/dist/core/modules/payment.d.ts.map +1 -1
- package/dist/core/modules/payment.js +58 -4
- package/dist/core/modules/payment.js.map +1 -1
- package/dist/core/modules/rx.d.ts +1 -1
- package/dist/core/modules/rx.d.ts.map +1 -1
- package/dist/core/modules/rx.js +2 -2
- package/dist/core/modules/rx.js.map +1 -1
- package/dist/core/types.d.ts +19 -0
- package/dist/core/types.d.ts.map +1 -1
- package/dist/react/hooks/useCheckout.d.ts +23 -0
- package/dist/react/hooks/useCheckout.d.ts.map +1 -1
- package/dist/react/hooks/useCheckout.js +12 -0
- package/dist/react/hooks/useCheckout.js.map +1 -1
- package/dist/react/hooks/useOrder.d.ts +60 -0
- package/dist/react/hooks/useOrder.d.ts.map +1 -0
- package/dist/react/hooks/useOrder.js +103 -0
- package/dist/react/hooks/useOrder.js.map +1 -0
- package/dist/react/hooks/useRx.d.ts +1 -1
- package/dist/react/hooks/useRx.d.ts.map +1 -1
- package/dist/react/hooks/useRx.js +2 -2
- package/dist/react/hooks/useRx.js.map +1 -1
- package/dist/react/index.d.ts +3 -0
- package/dist/react/index.d.ts.map +1 -1
- package/dist/react/index.js +3 -0
- package/dist/react/index.js.map +1 -1
- package/dist/tagada-headless-react.min.js +2 -2
- package/dist/tagada-headless-react.min.js.map +4 -4
- package/dist/tagada-headless.js +106 -19
- package/dist/tagada-headless.min.js +2 -2
- package/dist/tagada-headless.min.js.map +3 -3
- package/package.json +13 -14
package/dist/tagada-headless.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @tagadapay/headless-sdk v1.
|
|
2
|
+
* @tagadapay/headless-sdk v1.13.1
|
|
3
3
|
* Headless checkout, payments, offers, and CRM
|
|
4
4
|
* @license MIT
|
|
5
5
|
*/
|
|
@@ -69,7 +69,8 @@ var TagadaHeadlessBundle = (() => {
|
|
|
69
69
|
getCountries: () => getCountries,
|
|
70
70
|
getStatesForCountry: () => getStatesForCountry,
|
|
71
71
|
isLanguageLoaded: () => isLanguageLoaded,
|
|
72
|
-
loadGoogleMapsScript: () => loadGoogleMapsScript
|
|
72
|
+
loadGoogleMapsScript: () => loadGoogleMapsScript,
|
|
73
|
+
parseTokensFromUrl: () => parseTokensFromUrl
|
|
73
74
|
});
|
|
74
75
|
|
|
75
76
|
// src/core/errors.ts
|
|
@@ -235,7 +236,7 @@ var TagadaHeadlessBundle = (() => {
|
|
|
235
236
|
};
|
|
236
237
|
|
|
237
238
|
// src/core/modules/checkout.ts
|
|
238
|
-
var CheckoutModule = class {
|
|
239
|
+
var CheckoutModule = class _CheckoutModule {
|
|
239
240
|
constructor(http, storeId, onTokenChange) {
|
|
240
241
|
this.http = http;
|
|
241
242
|
this.storeId = storeId;
|
|
@@ -405,6 +406,10 @@ var TagadaHeadlessBundle = (() => {
|
|
|
405
406
|
const sessionToken = parsed.searchParams.get("sessionToken") ?? parsed.searchParams.get("token") ?? "";
|
|
406
407
|
return { checkoutToken, sessionToken };
|
|
407
408
|
}
|
|
409
|
+
/** Instance alias of {@link CheckoutModule.parseTokensFromUrl}. */
|
|
410
|
+
parseTokensFromUrl(url) {
|
|
411
|
+
return _CheckoutModule.parseTokensFromUrl(url);
|
|
412
|
+
}
|
|
408
413
|
/**
|
|
409
414
|
* Add or update cart items on an existing session (upsert by product).
|
|
410
415
|
*
|
|
@@ -648,7 +653,11 @@ var TagadaHeadlessBundle = (() => {
|
|
|
648
653
|
discount: summary.totalPromotionAmount ?? 0,
|
|
649
654
|
shipping: summary.shippingCost ?? 0,
|
|
650
655
|
tax: summary.totalTaxAmount ?? 0,
|
|
651
|
-
|
|
656
|
+
// `totalAdjustedAmount` is what gets charged (subtotal − discounts + shipping + tax).
|
|
657
|
+
// The raw adjuster summary also carries `totalAmount` = subtotal + shipping only —
|
|
658
|
+
// reading that first showed a pre-discount, pre-tax total (#TAG-2246). The legacy
|
|
659
|
+
// `orderSummaries[0]` shape only has `totalAmount`, already aliased to the adjusted total.
|
|
660
|
+
total: summary.totalAdjustedAmount ?? summary.totalAmount ?? summaryItems.reduce((s, i) => s + (i.amount ?? 0), 0),
|
|
652
661
|
currency: sessionCurrency ?? "USD"
|
|
653
662
|
},
|
|
654
663
|
customer: customer ? {
|
|
@@ -689,6 +698,7 @@ var TagadaHeadlessBundle = (() => {
|
|
|
689
698
|
return Object.values(out).some((v) => v !== void 0 && v !== "") ? out : void 0;
|
|
690
699
|
}
|
|
691
700
|
};
|
|
701
|
+
var parseTokensFromUrl = CheckoutModule.parseTokensFromUrl;
|
|
692
702
|
function stripEmpty(obj) {
|
|
693
703
|
const result = {};
|
|
694
704
|
for (const [k, v] of Object.entries(obj)) {
|
|
@@ -740,6 +750,28 @@ var TagadaHeadlessBundle = (() => {
|
|
|
740
750
|
}
|
|
741
751
|
|
|
742
752
|
// src/core/modules/payment.ts
|
|
753
|
+
var EXPRESS_METHOD_TYPES = /* @__PURE__ */ new Set(["apple_pay", "google_pay", "paypal", "klarna", "klarna_express", "link"]);
|
|
754
|
+
function paymentMethodListEntryToConfig(entry) {
|
|
755
|
+
var _a;
|
|
756
|
+
const isCard = entry.type === "credit-card";
|
|
757
|
+
const method = isCard ? "card" : entry.type;
|
|
758
|
+
const settings = entry.settings ?? {};
|
|
759
|
+
const processors = settings.processors;
|
|
760
|
+
const publishableKey = settings.publishableKey;
|
|
761
|
+
return {
|
|
762
|
+
enabled: true,
|
|
763
|
+
method,
|
|
764
|
+
provider: isCard ? void 0 : entry.type,
|
|
765
|
+
type: isCard ? "card" : entry.type,
|
|
766
|
+
label: entry.title,
|
|
767
|
+
logoUrl: entry.iconUrl,
|
|
768
|
+
express: EXPRESS_METHOD_TYPES.has(method),
|
|
769
|
+
integrationId: isCard ? void 0 : entry.id,
|
|
770
|
+
processorId: (_a = processors == null ? void 0 : processors[0]) == null ? void 0 : _a.processorId,
|
|
771
|
+
publishableKey: typeof publishableKey === "string" ? publishableKey : void 0,
|
|
772
|
+
metadata: entry.metadata ?? void 0
|
|
773
|
+
};
|
|
774
|
+
}
|
|
743
775
|
var PaymentModule = class {
|
|
744
776
|
constructor(http, storeId, environment, checkout) {
|
|
745
777
|
this.http = http;
|
|
@@ -776,16 +808,36 @@ var TagadaHeadlessBundle = (() => {
|
|
|
776
808
|
this.lastPaymentSetup = injected;
|
|
777
809
|
return injected;
|
|
778
810
|
}
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
811
|
+
try {
|
|
812
|
+
const res = await this.http.get(
|
|
813
|
+
`/api/v1/checkout-sessions/${checkoutSessionId}/payment-setup`
|
|
814
|
+
);
|
|
815
|
+
const config2 = { ...(res == null ? void 0 : res.config) ?? {} };
|
|
816
|
+
this.lastPaymentSetup = config2;
|
|
817
|
+
return config2;
|
|
818
|
+
} catch (err) {
|
|
819
|
+
if (!(err instanceof TagadaNotFoundError))
|
|
820
|
+
throw err;
|
|
821
|
+
}
|
|
822
|
+
const config = await this.getPaymentSetupFromPickerList(checkoutSessionId);
|
|
823
|
+
this.lastPaymentSetup = config;
|
|
824
|
+
return config;
|
|
825
|
+
}
|
|
826
|
+
/**
|
|
827
|
+
* Transitional fallback: `/api/v1/payment-methods` answers with a flat
|
|
828
|
+
* array of `{ id, type, title, iconUrl, default, settings, metadata }`
|
|
829
|
+
* picker rows (`type` = 'credit-card' or the integration provider). Map
|
|
830
|
+
* them to the setup-config shape. Only used when the backend does not
|
|
831
|
+
* serve `/checkout-sessions/:id/payment-setup` yet.
|
|
832
|
+
*/
|
|
833
|
+
async getPaymentSetupFromPickerList(checkoutSessionId) {
|
|
834
|
+
const res = await this.http.get("/api/v1/payment-methods", { params: { checkoutSessionId } });
|
|
835
|
+
const entries = Array.isArray(res) ? res.map(paymentMethodListEntryToConfig) : (res == null ? void 0 : res.methods) ?? [];
|
|
783
836
|
const config = {};
|
|
784
|
-
for (const m of
|
|
785
|
-
const key = m.provider ? `${m.method}:${m.provider}` : m.method;
|
|
837
|
+
for (const m of entries) {
|
|
838
|
+
const key = m.provider && m.provider !== m.method ? `${m.method}:${m.provider}` : m.method;
|
|
786
839
|
config[key] = m;
|
|
787
840
|
}
|
|
788
|
-
this.lastPaymentSetup = config;
|
|
789
841
|
return config;
|
|
790
842
|
}
|
|
791
843
|
/**
|
|
@@ -1722,12 +1774,47 @@ var TagadaHeadlessBundle = (() => {
|
|
|
1722
1774
|
{ params: { storeId: this.storeId, limit: opts == null ? void 0 : opts.limit, offset: opts == null ? void 0 : opts.offset } }
|
|
1723
1775
|
);
|
|
1724
1776
|
}
|
|
1725
|
-
/**
|
|
1726
|
-
|
|
1727
|
-
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
1777
|
+
/**
|
|
1778
|
+
* Get a single order by ID.
|
|
1779
|
+
*
|
|
1780
|
+
* **Thank-you pages:** accepted one-click upsells create *child orders*
|
|
1781
|
+
* (`metadata.mainOrderId` = this order's id) that land asynchronously —
|
|
1782
|
+
* the first fetch right after an accept usually misses them. Pass
|
|
1783
|
+
* `waitForRelatedOrders: true` to poll until `order.relatedOrders` is
|
|
1784
|
+
* non-empty or the timeout elapses. On timeout the latest snapshot is
|
|
1785
|
+
* returned (never throws), so an order with no accepted upsell simply
|
|
1786
|
+
* comes back with an empty `relatedOrders` after `timeoutMs`.
|
|
1787
|
+
*
|
|
1788
|
+
* @example
|
|
1789
|
+
* ```ts
|
|
1790
|
+
* // Thank-you page: show the main order AND the upsells
|
|
1791
|
+
* const order = await tagada.customer.getOrder(orderId, {
|
|
1792
|
+
* waitForRelatedOrders: true,
|
|
1793
|
+
* });
|
|
1794
|
+
* renderOrders([order, ...(order.relatedOrders ?? [])]);
|
|
1795
|
+
* ```
|
|
1796
|
+
*/
|
|
1797
|
+
async getOrder(orderId, opts) {
|
|
1798
|
+
var _a, _b;
|
|
1799
|
+
const fetchOrder = async () => {
|
|
1800
|
+
const res = await this.http.get(`/api/v1/orders/${orderId}`, {
|
|
1801
|
+
params: { storeId: this.storeId }
|
|
1802
|
+
});
|
|
1803
|
+
return res.order;
|
|
1804
|
+
};
|
|
1805
|
+
let order = await fetchOrder();
|
|
1806
|
+
if (!(opts == null ? void 0 : opts.waitForRelatedOrders) || ((_a = order.relatedOrders) == null ? void 0 : _a.length))
|
|
1807
|
+
return order;
|
|
1808
|
+
const timeoutMs = opts.timeoutMs ?? 8e3;
|
|
1809
|
+
const intervalMs = opts.intervalMs ?? 2e3;
|
|
1810
|
+
const deadline = Date.now() + timeoutMs;
|
|
1811
|
+
while (Date.now() < deadline) {
|
|
1812
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(intervalMs, Math.max(0, deadline - Date.now()))));
|
|
1813
|
+
order = await fetchOrder();
|
|
1814
|
+
if ((_b = order.relatedOrders) == null ? void 0 : _b.length)
|
|
1815
|
+
return order;
|
|
1816
|
+
}
|
|
1817
|
+
return order;
|
|
1731
1818
|
}
|
|
1732
1819
|
/** List subscriptions for a customer. */
|
|
1733
1820
|
async getSubscriptions(customerId) {
|
|
@@ -1974,9 +2061,9 @@ var TagadaHeadlessBundle = (() => {
|
|
|
1974
2061
|
* Fetch the network-authored intake questions for a product.
|
|
1975
2062
|
* Empty `questions` means the storefront should use its local quiz.
|
|
1976
2063
|
*/
|
|
1977
|
-
async getQuestionsForProduct(productId) {
|
|
2064
|
+
async getQuestionsForProduct(productId, variantId) {
|
|
1978
2065
|
return this.http.get("/api/public/v1/rx/questions-for-product", {
|
|
1979
|
-
params: { productId }
|
|
2066
|
+
params: variantId ? { productId, variantId } : { productId }
|
|
1980
2067
|
});
|
|
1981
2068
|
}
|
|
1982
2069
|
};
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @tagadapay/headless-sdk v1.
|
|
2
|
+
* @tagadapay/headless-sdk v1.13.1
|
|
3
3
|
* Headless checkout, payments, offers, and CRM
|
|
4
4
|
* @license MIT
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var TagadaHeadlessBundle=(()=>{var ue=Object.create;var j=Object.defineProperty;var ce=Object.getOwnPropertyDescriptor;var le=Object.getOwnPropertyNames;var me=Object.getPrototypeOf,pe=Object.prototype.hasOwnProperty;var ee=(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 ge=(s,e)=>{for(var t in e)j(s,t,{get:e[t],enumerable:!0})},te=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of le(e))!pe.call(s,n)&&n!==t&&j(s,n,{get:()=>e[n],enumerable:!(r=ce(e,n))||r.enumerable});return s};var re=(s,e,t)=>(t=s!=null?ue(me(s)):{},te(e||!s||!s.__esModule?j(t,"default",{value:s,enumerable:!0}):t,s)),he=s=>te(j({},"__esModule",{value:!0}),s);var Re={};ge(Re,{AVAILABLE_LANGUAGES:()=>M,CatalogModule:()=>N,CheckoutModule:()=>R,CurrencyUtils:()=>C,CustomerModule:()=>T,FunnelModule:()=>L,GoogleAutocompleteCore:()=>E,HeadlessClient:()=>U,HttpClient:()=>w,ISODataCore:()=>G,OffersModule:()=>x,PaymentModule:()=>b,RxModule:()=>_,TagadaAuthError:()=>k,TagadaError:()=>y,TagadaNetworkError:()=>I,TagadaNotFoundError:()=>v,TagadaPaymentError:()=>K,TagadaRateLimitError:()=>A,TagadaValidationError:()=>S,createHeadlessClient:()=>ie,ensureGeoDataLoaded:()=>$,formatMoney:()=>X,getCountries:()=>O,getStatesForCountry:()=>q,isLanguageLoaded:()=>F,loadGoogleMapsScript:()=>Q});var y=class extends Error{constructor(e,t,r,n){super(e),this.name="TagadaError",this.code=t,this.statusCode=r,this.details=n}},k=class extends y{constructor(e="Authentication failed. Check your API key or checkout token."){super(e,"auth_error",401),this.name="TagadaAuthError"}},S=class extends y{constructor(e,t=[],r,n){super(e,"validation_error",422,{errors:t,...n}),this.name="TagadaValidationError",this.errors=t,this.appCode=r}},v=class extends y{constructor(e,t){super(`${e} "${t}" not found.`,"not_found",404),this.name="TagadaNotFoundError"}},A=class extends y{constructor(e=1e3){super(`Rate limited. Retry after ${e}ms.`,"rate_limit",429),this.name="TagadaRateLimitError",this.retryAfterMs=e}},K=class extends y{constructor(e,t){super(e,"payment_error",void 0,t==null?void 0:t.details),this.name="TagadaPaymentError",this.paymentId=t==null?void 0:t.paymentId,this.requireAction=t==null?void 0:t.requireAction}},I=class extends y{constructor(e="Network request failed. Check your connection."){super(e,"network_error"),this.name="TagadaNetworkError"}};var ne={production:"https://api.tagada.io",development:"https://api.tagada.dev",local:"http://localhost:3000"},w=class{constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.timeout=e.timeout,this.apiKey=e.apiKey,this.getToken=e.getToken}static resolveBaseUrl(e,t){return t??ne[e]??ne.production}async request(e,t={}){var u;let{method:r="GET",body:n,headers:i={},params:a,token:o,signal:d}=t,c=`${this.baseUrl}${e}`;if(a){let p=new URLSearchParams;for(let[P,H]of Object.entries(a))H!==void 0&&p.set(P,String(H));let f=p.toString();f&&(c+=`?${f}`)}let h={"Content-Type":"application/json",...i},m=o??this.apiKey??((u=this.getToken)==null?void 0:u.call(this));m&&(h["x-cms-token"]=m);let g=new AbortController,l=setTimeout(()=>g.abort(),this.timeout);try{let p=await fetch(c,{method:r,headers:h,body:n!=null?JSON.stringify(n):void 0,signal:d??g.signal});if(clearTimeout(l),p.ok){let f=await p.text();return f?JSON.parse(f):{}}throw await this.handleErrorResponse(p,e),new y("Unexpected error","unknown",p.status)}catch(p){throw clearTimeout(l),p instanceof y?p:p instanceof DOMException&&p.name==="AbortError"?new I(`Request to ${e} timed out after ${this.timeout}ms.`):new I(p instanceof Error?p.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=r.data??{},i=r.message??r.error??(typeof n.message=="string"?n.message:void 0)??(typeof r.data=="string"?r.data:void 0)??`Request failed: ${e.status} ${e.statusText} on ${t}`,a=typeof n.code=="string"?n.code:void 0;switch(e.status){case 401:case 403:throw new k(i);case 404:throw new v(t,"");case 422:{let o=Array.isArray(r.errors)?r.errors:[];throw new S(i,o,a,r)}case 429:{let o=Number(e.headers.get("Retry-After")??"1")*1e3;throw new A(o)}default:throw new y(i,"api_error",e.status,r)}}};var R=class{constructor(e,t,r){this.http=e;this.storeId=t;this.onTokenChange=r}getCurrentSession(){return this._currentSession}async loadSession(e,t,r){var o;t&&(this.sessionToken=t,(o=this.onTokenChange)==null||o.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}),a=this.normalizeSession(i);return this._currentSession=a,a}async createSession(e){var d;let t=e.items.map(c=>({variantId:c.variantId,priceId:c.priceId,quantity:c.quantity})),r={storeId:this.storeId,lineItems:t};e.returnUrl&&(r.returnUrl=e.returnUrl);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),o=new URL(i.checkoutUrl).searchParams.get("token")??"";return this.sessionToken=o,o&&((d=this.onTokenChange)==null||d.call(this,o)),{checkoutUrl:i.checkoutUrl,checkoutToken:i.checkoutToken,sessionToken:o,customerId:i.customerId}}async createSessionUrl(e){let t=await this.createSession({items:e.items,currency:e.currency,returnUrl:e.returnUrl,customerEmail:e.customerEmail,customerFirstName:e.customerFirstName,customerLastName:e.customerLastName}),r=e.origin??(typeof window<"u"?window.location.origin:""),n=e.checkoutPath??"/checkout",i=new URLSearchParams({checkoutToken:t.checkoutToken,sessionToken:t.sessionToken}),a=`${r}${n}?${i.toString()}`;return{...t,url:a}}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}}async updateCart(e,t){let r=t.map(n=>({variantId:n.variantId,priceId:n.priceId,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??{},a=n??r,o=!!(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:a??{},differentBillingAddress:o},{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??{},a=n??r,o=!!(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:a??{},differentBillingAddress:o},{token:this.sessionToken})}mapAddress(e){if(e)return ye({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 h;let t=e.checkoutSession,r=t.orderSummaries??[],n=e.summary??t.summary??r[0]??{},i=t.sessionLineItems??[],a=t.customer,o=(h=n.currency??t.selectedPresentmentCurrency)==null?void 0:h.toUpperCase(),d=i.map(m=>{let g=m.price,l=m.variant??(g==null?void 0:g.variant)??{},u=m.product??l.product??{},p=(g==null?void 0:g.currencyOptions)??{},f=(o?p[o]:void 0)??p[Object.keys(p)[0]],P=(f==null?void 0:f.amount)??0;return{id:m.id,variantId:m.variantId,priceId:m.priceId,productName:u.name??"",variantName:l.name??"",quantity:m.quantity??1,unitAmount:P,totalAmount:P*(m.quantity??1),currency:o??"USD",imageUrl:l.imageUrl??u.imageUrl??""}}),c=n.items??[];return{id:t.id,storeId:t.storeId,checkoutToken:t.checkoutToken,currency:o??"USD",items:d,totals:{subtotal:n.subtotalAmount??0,discount:n.totalPromotionAmount??0,shipping:n.shippingCost??0,tax:n.totalTaxAmount??0,total:n.totalAmount??c.reduce((m,g)=>m+(g.amount??0),0),currency:o??"USD"},customer:a?{id:a.id,email:a.email,firstName:a.firstName,lastName:a.lastName,phone:a.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}};function ye(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 B(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 se(e)?e:void 0}function z(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 se(r)?r:void 0}function se(s){var e,t;return!!((e=s.line1)!=null&&e.trim()&&((t=s.country)!=null&&t.trim()))}var b=class{constructor(e,t,r,n){this.http=e;this.storeId=t;this.environment=r;this.checkout=n;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;let n=await this.http.get("/api/v1/payment-methods",{params:{checkoutSessionId:e}}),i={};for(let a of n.methods??[]){let o=a.provider?`${a.method}:${a.provider}`:a.method;i[o]=a}return this.lastPaymentSetup=i,i}async getExpressMethods(e,t){var i,a,o,d,c,h,m,g;let r=await this.getPaymentSetup(e,t),n={};for(let[l,u]of Object.entries(r)){if(!u.enabled)continue;if(l.startsWith("express_checkout:")&&u.methods){let P={available:!0,processorId:u.processorId,publishableKey:u.publishableKey,metadata:u.metadata};if((i=u.methods.apple_pay)!=null&&i.enabled){let H=typeof window<"u"&&"ApplePaySession"in window&&((o=(a=window.ApplePaySession)==null?void 0:a.canMakePayments)==null?void 0:o.call(a));n.applePay={...P,type:"apple_pay",available:!!H}}(d=u.methods.google_pay)!=null&&d.enabled&&(n.googlePay={...P,type:"google_pay"}),(c=u.methods.link)!=null&&c.enabled&&(n.link={...P,type:"link"}),(h=u.methods.klarna_express)!=null&&h.enabled&&(n.klarna={...P,type:"klarna_express"});continue}if(!u.express)continue;let p=u.method,f={type:p,available:!0,processorId:u.processorId,publishableKey:u.publishableKey,metadata:u.metadata};if(p==="apple_pay"||u.type==="apple_pay"){let P=typeof window<"u"&&"ApplePaySession"in window&&((g=(m=window.ApplePaySession)==null?void 0:m.canMakePayments)==null?void 0:g.call(m));n.applePay={...f,available:!!P}}else p==="google_pay"||u.type==="google_pay"?n.googlePay=f:p==="paypal"?n.paypal=f:p==="klarna"||p==="klarna_express"?n.klarna=f:p==="link"&&(n.link=f)}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 o,d,c,h,m,g,l,u,p;await this.syncWalletContact(e.checkoutSessionId,{shippingAddress:B(e.shippingContact),billingAddress:B(e.billingContact),email:((o=e.shippingContact)==null?void 0:o.emailAddress)??((d=e.billingContact)==null?void 0:d.emailAddress),phone:((c=e.shippingContact)==null?void 0:c.phoneNumber)??((h=e.billingContact)==null?void 0:h.phoneNumber),firstName:((m=e.shippingContact)==null?void 0:m.givenName)??((g=e.billingContact)==null?void 0:g.givenName),lastName:((l=e.shippingContact)==null?void 0:l.familyName)??((u=e.billingContact)==null?void 0:u.familyName)});let t=e.merchantRegistrationId??((p=await this.resolveApplePayRegistration(e.checkoutSessionId))==null?void 0:p.merchantRegistrationId),r=await this.loadCoreJs(),n=new r.Tokenizer({environment:this.environment});await n.initialize();let i=await n.tokenizeApplePay(e.applePayToken,t),a=btoa(JSON.stringify(r.createTagadaDigitalWalletToken(i,"apple_pay")));return this.pay({checkoutSessionId:e.checkoutSessionId,tagadaToken:a,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 a;for(let o of Object.values(i??{})){let d=(a=o==null?void 0:o.metadata)==null?void 0:a.applePayByok;if(!d||typeof d!="object")continue;let c=d[t];if(c!=null&&c.merchantRegistrationId)return{merchantRegistrationId:c.merchantRegistrationId,displayName:c.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 a,o,d,c;await this.syncWalletContact(e.checkoutSessionId,{shippingAddress:z(e.shippingAddress),billingAddress:z(e.billingAddress),email:e.email??((a=e.shippingAddress)==null?void 0:a.emailAddress)??((o=e.billingAddress)==null?void 0:o.emailAddress),phone:((d=e.shippingAddress)==null?void 0:d.phoneNumber)??((c=e.billingAddress)==null?void 0:c.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,a;let r=e.payment,n=(t==null?void 0:t.returnUrl)??(typeof window<"u"?window.location.href:void 0);return r.status==="succeeded"?{status:"succeeded",payment:r,order:e.order}:r.status==="failed"||r.status==="declined"?{status:"failed",error:((i=r.requireActionData)==null?void 0:i.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"),a=r.searchParams.get("paymentId");if(n!=="requireAction"||i!=="completed"||!a)return null;let o=await this.resumeAfterRedirect(a);if((e==null?void 0:e.cleanUrl)!==!1&&typeof window<"u"&&!(e!=null&&e.url)){let d=new URLSearchParams(window.location.search);["paymentAction","paymentActionStatus","paymentId","payment_intent","payment_intent_client_secret","source_type","redirect_status","sessionId"].forEach(h=>d.delete(h));let c=d.toString();try{window.history.replaceState({},document.title,window.location.pathname+(c?"?"+c:""))}catch{}}return o}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 a=await this.getPaymentStatus(e);if(a.status==="succeeded"||a.status==="failed"||a.status==="declined")return a;await new Promise(o=>setTimeout(o,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,a;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:((a=r==null?void 0:r.method)==null?void 0:a.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,a;let r=(a=(i=e.requireActionData)==null?void 0:i.metadata)==null?void 0:a.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 o=new n.ThreedsManager({provider:"basis_theory"});return await o.initialize({apiKey:void 0}),await o.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){let r=(t==null?void 0:t.intervalMs)??1500,n=(t==null?void 0:t.timeoutMs)??6e4,i=Date.now(),a=0;for(;Date.now()-i<n;){let o;try{o=await this.getPaymentStatus(e),a=0}catch{if(a++,a>=3)return{status:"failed",error:"Payment verification failed due to network errors"};await new Promise(d=>setTimeout(d,r));continue}if(o.status==="succeeded"||o.status==="pending"&&o.subStatus==="authorized")return{status:"succeeded",payment:o,order:o.order};if(o.status==="failed"||o.status==="declined")return{status:"failed",error:o.status,payment:o};if(o.requireAction&&o.requireAction!=="none"&&o.requireActionData&&!o.requireActionData.processed)return this.handlePaymentAction(o,{});await new Promise(d=>setTimeout(d,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}}async loadCoreJs(){try{return await import("@tagadapay/core-js")}catch{throw new Error("This method requires @tagadapay/core-js. Install it: npm install @tagadapay/core-js")}}};var x=class{constructor(e,t,r){this.http=e;this.storeId=t;this.payment=r}async getOffer(e){return this.http.get(`/api/v1/offers/${e}`)}async listOffers(e){var i;let t=`/api/v1/stores/${this.storeId}/offers`,r=[];if(e!=null&&e.type&&r.push(`type=${encodeURIComponent(e.type)}`),(i=e==null?void 0:e.ids)!=null&&i.length)for(let a of e.ids)r.push(`ids=${encodeURIComponent(a)}`);return r.length&&(t+=`?${r.join("&")}`),(await this.http.get(t)).offers??[]}async previewOffer(e){return this.http.post(`/api/v1/offers/${e.offerId}/preview`,{offerId:e.offerId,currency:e.currency??"",lineItems:e.lineItems})}async payPreviewedOffer(e){return this.http.post(`/api/v1/offers/${e.offerId}/pay-preview`,{offerId:e.offerId,currency:e.currency??"",lineItems:e.lineItems,returnUrl:e.returnUrl??(typeof window<"u"?window.location.href:""),mainOrderId:e.mainOrderId,paymentInstrumentId:e.paymentInstrumentId})}async processOfferPayment(e){if(!this.payment)throw new Error("OffersModule: no PaymentModule injected. Use createHeadlessClient() instead of constructing OffersModule directly.");let t=e.returnUrl??(typeof window<"u"?window.location.href:void 0),r=await this.payPreviewedOffer({...e,returnUrl:t});return this.payment.finalize({payment:r.payment,order:r.order},{returnUrl:t})}async toggleOrderBump(e){return this.http.post(`/api/v1/checkout-sessions/${e.checkoutSessionId}/toggle-order-bump`,{orderBumpOfferId:e.orderBumpOfferId,selected:e.selected})}async listPostPurchaseOffers(e){let t=await this.http.get(`/api/v1/post-purchase/${e}/offers`);return Array.isArray(t)?t:[]}async acceptPostPurchaseOffer(e){return this.http.post(`/api/v1/orders/${e.orderId}/post-purchase-offers/${e.offerId}/accept`,{items:e.items??[]})}async declinePostPurchaseOffer(e){return this.http.post(`/api/v1/orders/${e.orderId}/post-purchase-offers/${e.offerId}/decline`)}};var T=class{constructor(e,t){this.http=e;this.storeId=t}async getProfile(e){return(await this.http.get(`/api/v1/customers/${e}`,{params:{storeId:this.storeId}})).customer}async getByEmail(e){try{return(await this.http.get("/api/v1/customers/by-email",{params:{email:e,storeId:this.storeId}})).customer}catch{return null}}async updateProfile(e,t){return(await this.http.patch(`/api/v1/customers/${e}`,{storeId:this.storeId,...t})).customer}async getOrders(e,t){return this.http.get(`/api/v1/customers/${e}/orders`,{params:{storeId:this.storeId,limit:t==null?void 0:t.limit,offset:t==null?void 0:t.offset}})}async getOrder(e){return(await this.http.get(`/api/v1/orders/${e}`,{params:{storeId:this.storeId}})).order}async getSubscriptions(e){return(await this.http.get(`/api/v1/customers/${e}/subscriptions`,{params:{storeId:this.storeId}})).subscriptions}async getSubscription(e){return(await this.http.get(`/api/v1/subscriptions/${e}`,{params:{storeId:this.storeId}})).subscription}};var N=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 L=class{constructor(e,t,r,n){this.http=e;this.storeId=t;this.checkout=r;this.accountId=n}async navigate(e){var o;let t=this.checkout.getCurrentSession();if(!t)throw new y("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 y("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"?(o=globalThis.location)==null?void 0:o.href:void 0);await this.ensureCmsSession(t,r,e);let i=await this.initializeFunnel({funnelId:e.funnelId,stepId:e.stepId,accountId:r,currentUrl:n});return{url:await this.runNavigate({funnelSessionId:i,stepId:e.stepId,session:t,input:e,currentUrl:n}),funnelSessionId:i}}async ensureCmsSession(e,t,r){var a,o,d;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:((a=r.customer)==null?void 0:a.locale)??fe(),userAgent:Pe(),queryCurrency:((o=r.customer)==null?void 0:o.currency)??e.currency,queryLocale:(d=r.customer)==null?void 0:d.locale},{token:this._cmsToken});this._cmsCustomerId=i.customer.id}async initializeFunnel(e){return(await this.http.post("/api/v1/funnel/initialize",{cmsSession:{customerId:this._cmsCustomerId,sessionId:this._cmsSessionId,storeId:this.storeId,accountId:e.accountId},funnelId:e.funnelId,entryStepId:e.stepId,funnelStepId:e.stepId,currentUrl:e.currentUrl,draft:!1},{token:this._cmsToken})).context.sessionId}async runNavigate(e){var m,g,l,u;let{funnelSessionId:t,stepId:r,session:n,input:i,currentUrl:a}=e,o=n.items.map(p=>({variantId:p.variantId,priceId:p.priceId,quantity:p.quantity})),d=i.discountCodes??(n.promotionCode?[n.promotionCode]:void 0),c={email:((m=i.customer)==null?void 0:m.email)??((g=n.customer)==null?void 0:g.email),currency:((l=i.customer)==null?void 0:l.currency)??n.currency,locale:(u=i.customer)==null?void 0:u.locale};return(await this.http.post("/api/v1/funnel/navigate",{sessionId:t,currentUrl:a,funnelStepId:r,fireAndForget:!1,event:{type:"INIT_CHECKOUT",data:{checkoutInit:{cartToken:n.id,lineItems:o,customer:c,returnUrl:i.returnUrl,storeId:this.storeId,metadata:i.metadata,discountCodes:d,externalShipping:i.externalShipping}}}},{token:this._cmsToken})).result.url}};function fe(){return typeof navigator<"u"&&navigator.language?navigator.language:"en-US"}function Pe(){return typeof navigator<"u"&&navigator.userAgent?navigator.userAgent:"tagadapay-headless-sdk"}var _=class{constructor(e){this.http=e}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){return this.http.get("/api/public/v1/rx/questions-for-product",{params:{productId:e}})}};var U=class{constructor(e){let t=e.environment??"production",r=w.resolveBaseUrl(t,e.baseUrl);this.config={...e,environment:t,baseUrl:r,timeout:e.timeout??3e4},this.http=new w({baseUrl:r,timeout:this.config.timeout,apiKey:e.apiKey,getToken:()=>this._sessionToken});let n=i=>{this._sessionToken=i};this.checkout=new R(this.http,this.config.storeId,n),this.payment=new b(this.http,this.config.storeId,t,this.checkout),this.offers=new x(this.http,this.config.storeId,this.payment),this.customer=new T(this.http,this.config.storeId),this.catalog=new N(this.http,this.config.storeId),this.funnel=new L(this.http,this.config.storeId,this.checkout,this.config.accountId),this.rx=new _(this.http)}setSessionToken(e){this._sessionToken=e}};function ie(s){return new U(s)}var oe=!1,ae=!1,J=[];function V(){ae=!0;for(let s of J)s();J.length=0}function Q(s,e={}){var t,r;return ae||(r=(t=window.google)==null?void 0:t.maps)!=null&&r.places?(V(),Promise.resolve()):oe?new Promise(n=>J.push(n)):(oe=!0,new Promise((n,i)=>{if(J.push(n),document.querySelector('script[src*="maps.googleapis.com"]')){let c=()=>{var h,m;(m=(h=window.google)==null?void 0:h.maps)!=null&&m.places?V():setTimeout(c,100)};c();return}let o=new URLSearchParams({key:s,libraries:"places",v:e.version??"weekly"});e.language&&o.set("language",e.language),e.region&&o.set("region",e.region);let d=document.createElement("script");d.src=`https://maps.googleapis.com/maps/api/js?${o}`,d.async=!0,d.defer=!0,d.onload=()=>V(),d.onerror=()=>i(new Error("Failed to load Google Maps script")),document.head.appendChild(d)}))}var E=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(a=>{r.getPlacePredictions({input:e,types:t.types??["address"],componentRestrictions:t.componentRestrictions},(o,d)=>{var c,h,m;a(d===((m=(h=(c=window.google)==null?void 0:c.maps)==null?void 0:h.places)==null?void 0:m.PlacesServiceStatus.OK)&&o?o:[])})})}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"]},(a,o)=>{var d,c,h;i(o===((h=(c=(d=window.google)==null?void 0:d.maps)==null?void 0:c.places)==null?void 0:h.PlacesServiceStatus.OK)&&a?a:null)})})}static extractAddressComponents(e){let t={subpremise:"",streetNumber:"",route:"",locality:"",administrativeAreaLevel1:"",administrativeAreaLevel1Long:"",administrativeAreaLevel2:"",administrativeAreaLevel2Long:"",country:"",postalCode:"",fullStreetAddress:""},r="",n="",i="",a="",o="",d="",c="",h="";for(let l of e.address_components??[]){let u=l.types;u.includes("subpremise")&&(t.subpremise=l.long_name),u.includes("street_number")&&(t.streetNumber=l.long_name),u.includes("premise")&&(r=l.long_name),u.includes("route")&&(t.route=l.long_name),u.includes("neighborhood")&&(n=l.long_name),u.includes("sublocality_level_5")&&(i=l.long_name),u.includes("sublocality_level_4")&&(a=l.long_name),u.includes("sublocality_level_3")&&(o=l.long_name),u.includes("sublocality_level_2")&&(d=l.long_name),u.includes("sublocality_level_1")&&(c=l.long_name),u.includes("locality")&&(t.locality=l.long_name),u.includes("postal_town")&&(h=l.long_name),u.includes("administrative_area_level_2")&&(t.administrativeAreaLevel2=l.short_name,t.administrativeAreaLevel2Long=l.long_name),u.includes("administrative_area_level_1")&&(t.administrativeAreaLevel1=l.short_name,t.administrativeAreaLevel1Long=l.long_name),u.includes("country")&&(t.country=l.short_name),u.includes("postal_code")&&(t.postalCode=l.long_name)}t.locality||(t.locality=h||d||c||""),!t.administrativeAreaLevel1&&t.administrativeAreaLevel2&&(t.administrativeAreaLevel1=t.administrativeAreaLevel2Long||t.administrativeAreaLevel2,t.administrativeAreaLevel1Long=t.administrativeAreaLevel2Long);let m=t.streetNumber||r,g=t.route||i||a||o||n;if(t.subpremise&&m&&g)t.fullStreetAddress=`${t.subpremise}/${m} ${g}`;else if(m&&g)if(r&&a&&o){let l=`${o}-${a}-${r}`;d&&(l=`${l} ${d}`),t.fullStreetAddress=l}else t.fullStreetAddress=`${m} ${g}`;else g?t.fullStreetAddress=g:m&&(t.fullStreetAddress=m);return t.fullStreetAddress=t.fullStreetAddress.trim(),t}static extractFormattedAddress(e){let t=s.extractAddressComponents(e);return{address1:t.fullStreetAddress,city:t.locality,country:t.country,state:t.administrativeAreaLevel1,postal:t.postalCode}}};var de="https://cvwnizdbugpz6jwk.public.blob.vercel-storage.com/geodata/v1",M=["en","ru","de","da","fr","es","zh","hi","pt","ja","ar","it","he"],D=new Map,W=new Map,Y=new Map,Z=new Map;async function Ie(s){let e=D.get(s);if(e)return e;let t=Y.get(s);return t||(t=(async()=>{let r=`${de}/${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 D.set(s,i),Y.delete(s),i})(),Y.set(s,t),t)}async function we(s){let e=W.get(s);if(e)return e;let t=Z.get(s);return t||(t=(async()=>{let r=`${de}/${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 W.set(s,i),Z.delete(s),i})(),Z.set(s,t),t)}function Ce(s){return D.get(s)||D.get("en")||{}}function ke(s){return W.get(s)||W.get("en")||{}}async function $(s="en"){await Promise.all([Ie(s),we(s)])}var O=(s="en")=>{let e=Ce(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))},q=(s,e="en")=>{let r=ke(e)[s];return r?r.map(([n,i])=>({code:n,name:i,countryCode:s})).sort((n,i)=>n.name.localeCompare(i.name)):[]};function F(s){return D.has(s)}var G=class s{static ensureLoaded(e="en"){return $(e)}static getCountries(e="en"){let t=O(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 O(e).map(t=>({value:t.code,label:t.name}))}static getRegions(e,t="en"){return q(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 a=i.find(o=>o.iso===e);return a||(a=i.find(o=>o.name.toLowerCase()===e.toLowerCase()),a)||(a=i.find(o=>o.name.toLowerCase()===t.toLowerCase()),a)?a:(a=i.find(o=>o.name.toLowerCase().includes(t.toLowerCase())||t.toLowerCase().includes(o.name.toLowerCase())),a??null)}static isLanguageLoaded(e){return F(e)}static getAvailableLanguages(){return M}};var Se={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"},ve={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"},Ae=new Set(["JPY","KRW","VND","IDR","LAK","KHR","MMK","PYG"]),C=class s{static getSymbol(e){return Se[e]??e}static getName(e){return ve[e]??e}static getDecimalPlaces(e){return Ae.has(e)?0:2}static getCurrency(e){return{code:e,symbol:s.getSymbol(e),name:s.getName(e),decimalPlaces:s.getDecimalPlaces(e)}}};function X(s,e="USD",t="en-US"){let r=C.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`${C.getSymbol(e)}${n.toFixed(r)}`}}return he(Re);})();
|
|
6
|
+
"use strict";var TagadaHeadlessBundle=(()=>{var ce=Object.create;var j=Object.defineProperty;var le=Object.getOwnPropertyDescriptor;var me=Object.getOwnPropertyNames;var pe=Object.getPrototypeOf,ge=Object.prototype.hasOwnProperty;var ee=(i=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(i,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):i)(function(i){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+i+'" is not supported')});var he=(i,e)=>{for(var t in e)j(i,t,{get:e[t],enumerable:!0})},te=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of me(e))!ge.call(i,n)&&n!==t&&j(i,n,{get:()=>e[n],enumerable:!(r=le(e,n))||r.enumerable});return i};var re=(i,e,t)=>(t=i!=null?ce(pe(i)):{},te(e||!i||!i.__esModule?j(t,"default",{value:i,enumerable:!0}):t,i)),ye=i=>te(j({},"__esModule",{value:!0}),i);var Te={};he(Te,{AVAILABLE_LANGUAGES:()=>M,CatalogModule:()=>N,CheckoutModule:()=>k,CurrencyUtils:()=>S,CustomerModule:()=>T,FunnelModule:()=>L,GoogleAutocompleteCore:()=>E,HeadlessClient:()=>U,HttpClient:()=>C,ISODataCore:()=>G,OffersModule:()=>x,PaymentModule:()=>b,RxModule:()=>O,TagadaAuthError:()=>v,TagadaError:()=>y,TagadaNetworkError:()=>w,TagadaNotFoundError:()=>I,TagadaPaymentError:()=>K,TagadaRateLimitError:()=>R,TagadaValidationError:()=>A,createHeadlessClient:()=>oe,ensureGeoDataLoaded:()=>$,formatMoney:()=>X,getCountries:()=>_,getStatesForCountry:()=>F,isLanguageLoaded:()=>q,loadGoogleMapsScript:()=>Y,parseTokensFromUrl:()=>se});var y=class extends Error{constructor(e,t,r,n){super(e),this.name="TagadaError",this.code=t,this.statusCode=r,this.details=n}},v=class extends y{constructor(e="Authentication failed. Check your API key or checkout token."){super(e,"auth_error",401),this.name="TagadaAuthError"}},A=class extends y{constructor(e,t=[],r,n){super(e,"validation_error",422,{errors:t,...n}),this.name="TagadaValidationError",this.errors=t,this.appCode=r}},I=class extends y{constructor(e,t){super(`${e} "${t}" not found.`,"not_found",404),this.name="TagadaNotFoundError"}},R=class extends y{constructor(e=1e3){super(`Rate limited. Retry after ${e}ms.`,"rate_limit",429),this.name="TagadaRateLimitError",this.retryAfterMs=e}},K=class extends y{constructor(e,t){super(e,"payment_error",void 0,t==null?void 0:t.details),this.name="TagadaPaymentError",this.paymentId=t==null?void 0:t.paymentId,this.requireAction=t==null?void 0:t.requireAction}},w=class extends y{constructor(e="Network request failed. Check your connection."){super(e,"network_error"),this.name="TagadaNetworkError"}};var ne={production:"https://api.tagada.io",development:"https://api.tagada.dev",local:"http://localhost:3000"},C=class{constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.timeout=e.timeout,this.apiKey=e.apiKey,this.getToken=e.getToken}static resolveBaseUrl(e,t){return t??ne[e]??ne.production}async request(e,t={}){var u;let{method:r="GET",body:n,headers:s={},params:o,token:a,signal:d}=t,c=`${this.baseUrl}${e}`;if(o){let p=new URLSearchParams;for(let[P,H]of Object.entries(o))H!==void 0&&p.set(P,String(H));let f=p.toString();f&&(c+=`?${f}`)}let g={"Content-Type":"application/json",...s},m=a??this.apiKey??((u=this.getToken)==null?void 0:u.call(this));m&&(g["x-cms-token"]=m);let h=new AbortController,l=setTimeout(()=>h.abort(),this.timeout);try{let p=await fetch(c,{method:r,headers:g,body:n!=null?JSON.stringify(n):void 0,signal:d??h.signal});if(clearTimeout(l),p.ok){let f=await p.text();return f?JSON.parse(f):{}}throw await this.handleErrorResponse(p,e),new y("Unexpected error","unknown",p.status)}catch(p){throw clearTimeout(l),p instanceof y?p:p instanceof DOMException&&p.name==="AbortError"?new w(`Request to ${e} timed out after ${this.timeout}ms.`):new w(p instanceof Error?p.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=r.data??{},s=r.message??r.error??(typeof n.message=="string"?n.message:void 0)??(typeof r.data=="string"?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 v(s);case 404:throw new I(t,"");case 422:{let a=Array.isArray(r.errors)?r.errors:[];throw new A(s,a,o,r)}case 429:{let a=Number(e.headers.get("Retry-After")??"1")*1e3;throw new R(a)}default:throw new y(s,"api_error",e.status,r)}}};var k=class i{constructor(e,t,r){this.http=e;this.storeId=t;this.onTokenChange=r}getCurrentSession(){return this._currentSession}async loadSession(e,t,r){var a;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 s=await this.http.get(`/api/v1/checkout-sessions/${e}/v2`,{params:n,token:this.sessionToken}),o=this.normalizeSession(s);return this._currentSession=o,o}async createSession(e){var d;let t=e.items.map(c=>({variantId:c.variantId,priceId:c.priceId,quantity:c.quantity})),r={storeId:this.storeId,lineItems:t};e.returnUrl&&(r.returnUrl=e.returnUrl);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 s=await this.http.post("/api/v1/checkout/session/init",r),a=new URL(s.checkoutUrl).searchParams.get("token")??"";return this.sessionToken=a,a&&((d=this.onTokenChange)==null||d.call(this,a)),{checkoutUrl:s.checkoutUrl,checkoutToken:s.checkoutToken,sessionToken:a,customerId:s.customerId}}async createSessionUrl(e){let t=await this.createSession({items:e.items,currency:e.currency,returnUrl:e.returnUrl,customerEmail:e.customerEmail,customerFirstName:e.customerFirstName,customerLastName:e.customerLastName}),r=e.origin??(typeof window<"u"?window.location.origin:""),n=e.checkoutPath??"/checkout",s=new URLSearchParams({checkoutToken:t.checkoutToken,sessionToken:t.sessionToken}),o=`${r}${n}?${s.toString()}`;return{...t,url:o}}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 s=r.searchParams.get("sessionToken")??r.searchParams.get("token")??"";return{checkoutToken:n,sessionToken:s}}parseTokensFromUrl(e){return i.parseTokensFromUrl(e)}async updateCart(e,t){let r=t.map(n=>({variantId:n.variantId,priceId:n.priceId,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),s=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:s,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),s=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:s,billingAddress:o??{},differentBillingAddress:a},{token:this.sessionToken})}mapAddress(e){if(e)return fe({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]??{},s=t.sessionLineItems??[],o=t.customer,a=(g=n.currency??t.selectedPresentmentCurrency)==null?void 0:g.toUpperCase(),d=s.map(m=>{let h=m.price,l=m.variant??(h==null?void 0:h.variant)??{},u=m.product??l.product??{},p=(h==null?void 0:h.currencyOptions)??{},f=(a?p[a]:void 0)??p[Object.keys(p)[0]],P=(f==null?void 0:f.amount)??0;return{id:m.id,variantId:m.variantId,priceId:m.priceId,productName:u.name??"",variantName:l.name??"",quantity:m.quantity??1,unitAmount:P,totalAmount:P*(m.quantity??1),currency:a??"USD",imageUrl:l.imageUrl??u.imageUrl??""}}),c=n.items??[];return{id:t.id,storeId:t.storeId,checkoutToken:t.checkoutToken,currency:a??"USD",items:d,totals:{subtotal:n.subtotalAmount??0,discount:n.totalPromotionAmount??0,shipping:n.shippingCost??0,tax:n.totalTaxAmount??0,total:n.totalAdjustedAmount??n.totalAmount??c.reduce((m,h)=>m+(h.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}},se=k.parseTokensFromUrl;function fe(i){let e={};for(let[t,r]of Object.entries(i))r!=null&&r!==""&&(e[t]=r);return Object.keys(e).length>0?e:void 0}function B(i){var t,r;if(!i)return;let e={firstName:i.givenName,lastName:i.familyName,line1:(t=i.addressLines)==null?void 0:t[0],line2:(r=i.addressLines)==null?void 0:r[1],city:i.locality,state:i.administrativeArea,postalCode:i.postalCode,country:i.countryCode,phone:i.phoneNumber};return ie(e)?e:void 0}function z(i){if(!i)return;let[e,...t]=(i.name??"").trim().split(/\s+/),r={firstName:e||void 0,lastName:t.length?t.join(" "):void 0,line1:i.address1,line2:[i.address2,i.address3].filter(Boolean).join(" ")||void 0,city:i.locality,state:i.administrativeArea,postalCode:i.postalCode,country:i.countryCode,phone:i.phoneNumber};return ie(r)?r:void 0}function ie(i){var e,t;return!!((e=i.line1)!=null&&e.trim()&&((t=i.country)!=null&&t.trim()))}var Pe=new Set(["apple_pay","google_pay","paypal","klarna","klarna_express","link"]);function Ie(i){var o;let e=i.type==="credit-card",t=e?"card":i.type,r=i.settings??{},n=r.processors,s=r.publishableKey;return{enabled:!0,method:t,provider:e?void 0:i.type,type:e?"card":i.type,label:i.title,logoUrl:i.iconUrl,express:Pe.has(t),integrationId:e?void 0:i.id,processorId:(o=n==null?void 0:n[0])==null?void 0:o.processorId,publishableKey:typeof s=="string"?s:void 0,metadata:i.metadata??void 0}}var b=class{constructor(e,t,r,n){this.http=e;this.storeId=t;this.environment=r;this.checkout=n;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 s=await this.http.get(`/api/v1/checkout-sessions/${e}/payment-setup`),o={...(s==null?void 0:s.config)??{}};return this.lastPaymentSetup=o,o}catch(s){if(!(s instanceof I))throw s}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(Ie):(t==null?void 0:t.methods)??[],n={};for(let s of r){let o=s.provider&&s.provider!==s.method?`${s.method}:${s.provider}`:s.method;n[o]=s}return n}async getExpressMethods(e,t){var s,o,a,d,c,g,m,h;let r=await this.getPaymentSetup(e,t),n={};for(let[l,u]of Object.entries(r)){if(!u.enabled)continue;if(l.startsWith("express_checkout:")&&u.methods){let P={available:!0,processorId:u.processorId,publishableKey:u.publishableKey,metadata:u.metadata};if((s=u.methods.apple_pay)!=null&&s.enabled){let H=typeof window<"u"&&"ApplePaySession"in window&&((a=(o=window.ApplePaySession)==null?void 0:o.canMakePayments)==null?void 0:a.call(o));n.applePay={...P,type:"apple_pay",available:!!H}}(d=u.methods.google_pay)!=null&&d.enabled&&(n.googlePay={...P,type:"google_pay"}),(c=u.methods.link)!=null&&c.enabled&&(n.link={...P,type:"link"}),(g=u.methods.klarna_express)!=null&&g.enabled&&(n.klarna={...P,type:"klarna_express"});continue}if(!u.express)continue;let p=u.method,f={type:p,available:!0,processorId:u.processorId,publishableKey:u.publishableKey,metadata:u.metadata};if(p==="apple_pay"||u.type==="apple_pay"){let P=typeof window<"u"&&"ApplePaySession"in window&&((h=(m=window.ApplePaySession)==null?void 0:m.canMakePayments)==null?void 0:h.call(m));n.applePay={...f,available:!!P}}else p==="google_pay"||u.type==="google_pay"?n.googlePay=f:p==="paypal"?n.paypal=f:p==="klarna"||p==="klarna_express"?n.klarna=f:p==="link"&&(n.link=f)}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 s=await r.tokenizeCardRaw(n);return{tagadaToken:t.createTagadaToken(s,r.getProvider().getProviderName()),rawToken:s}}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 s={};t.email&&(s.email=t.email),t.phone&&(s.phone=t.phone),t.firstName&&(s.firstName=t.firstName),t.lastName&&(s.lastName=t.lastName),await this.checkout.updateCustomerAndAddress(e,{customer:s,shippingAddress:r,billingAddress:n})}async processApplePay(e){var a,d,c,g,m,h,l,u,p;await this.syncWalletContact(e.checkoutSessionId,{shippingAddress:B(e.shippingContact),billingAddress:B(e.billingContact),email:((a=e.shippingContact)==null?void 0:a.emailAddress)??((d=e.billingContact)==null?void 0:d.emailAddress),phone:((c=e.shippingContact)==null?void 0:c.phoneNumber)??((g=e.billingContact)==null?void 0:g.phoneNumber),firstName:((m=e.shippingContact)==null?void 0:m.givenName)??((h=e.billingContact)==null?void 0:h.givenName),lastName:((l=e.shippingContact)==null?void 0:l.familyName)??((u=e.billingContact)==null?void 0:u.familyName)});let t=e.merchantRegistrationId??((p=await this.resolveApplePayRegistration(e.checkoutSessionId))==null?void 0:p.merchantRegistrationId),r=await this.loadCoreJs(),n=new r.Tokenizer({environment:this.environment});await n.initialize();let s=await n.tokenizeApplePay(e.applePayToken,t),o=btoa(JSON.stringify(r.createTagadaDigitalWalletToken(s,"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=s=>{var o;for(let a of Object.values(s??{})){let d=(o=a==null?void 0:a.metadata)==null?void 0:o.applePayByok;if(!d||typeof d!="object")continue;let c=d[t];if(c!=null&&c.merchantRegistrationId)return{merchantRegistrationId:c.merchantRegistrationId,displayName:c.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,d,c;await this.syncWalletContact(e.checkoutSessionId,{shippingAddress:z(e.shippingAddress),billingAddress:z(e.billingAddress),email:e.email??((o=e.shippingAddress)==null?void 0:o.emailAddress)??((a=e.billingAddress)==null?void 0:a.emailAddress),phone:((d=e.shippingAddress)==null?void 0:d.phoneNumber)??((c=e.billingAddress)==null?void 0:c.phoneNumber)});let t=await this.loadCoreJs(),r=new t.Tokenizer({environment:this.environment});await r.initialize();let n=await r.tokenizeGooglePay(e.googlePayToken),s=btoa(JSON.stringify(t.createTagadaDigitalWalletToken(n,"google_pay")));return this.pay({checkoutSessionId:e.checkoutSessionId,tagadaToken:s,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 s,o;let r=e.payment,n=(t==null?void 0:t.returnUrl)??(typeof window<"u"?window.location.href:void 0);return r.status==="succeeded"?{status:"succeeded",payment:r,order:e.order}:r.status==="failed"||r.status==="declined"?{status:"failed",error:((s=r.requireActionData)==null?void 0:s.message)||((o=r.requireActionData)==null?void 0:o.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"),s=r.searchParams.get("paymentActionStatus"),o=r.searchParams.get("paymentId");if(n!=="requireAction"||s!=="completed"||!o)return null;let a=await this.resumeAfterRedirect(o);if((e==null?void 0:e.cleanUrl)!==!1&&typeof window<"u"&&!(e!=null&&e.url)){let d=new URLSearchParams(window.location.search);["paymentAction","paymentActionStatus","paymentId","payment_intent","payment_intent_client_secret","source_type","redirect_status","sessionId"].forEach(g=>d.delete(g));let c=d.toString();try{window.history.replaceState({},document.title,window.location.pathname+(c?"?"+c:""))}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,s=Date.now();for(;Date.now()-s<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 s,o;let r=(s=t.metadata)==null?void 0:s.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 s,o;let r=(o=(s=e.requireActionData)==null?void 0:s.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){let r=(t==null?void 0:t.intervalMs)??1500,n=(t==null?void 0:t.timeoutMs)??6e4,s=Date.now(),o=0;for(;Date.now()-s<n;){let a;try{a=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(d=>setTimeout(d,r));continue}if(a.status==="succeeded"||a.status==="pending"&&a.subStatus==="authorized")return{status:"succeeded",payment:a,order:a.order};if(a.status==="failed"||a.status==="declined")return{status:"failed",error:a.status,payment:a};if(a.requireAction&&a.requireAction!=="none"&&a.requireActionData&&!a.requireActionData.processed)return this.handlePaymentAction(a,{});await new Promise(d=>setTimeout(d,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}}async loadCoreJs(){try{return await import("@tagadapay/core-js")}catch{throw new Error("This method requires @tagadapay/core-js. Install it: npm install @tagadapay/core-js")}}};var x=class{constructor(e,t,r){this.http=e;this.storeId=t;this.payment=r}async getOffer(e){return this.http.get(`/api/v1/offers/${e}`)}async listOffers(e){var s;let t=`/api/v1/stores/${this.storeId}/offers`,r=[];if(e!=null&&e.type&&r.push(`type=${encodeURIComponent(e.type)}`),(s=e==null?void 0:e.ids)!=null&&s.length)for(let o of e.ids)r.push(`ids=${encodeURIComponent(o)}`);return r.length&&(t+=`?${r.join("&")}`),(await this.http.get(t)).offers??[]}async previewOffer(e){return this.http.post(`/api/v1/offers/${e.offerId}/preview`,{offerId:e.offerId,currency:e.currency??"",lineItems:e.lineItems})}async payPreviewedOffer(e){return this.http.post(`/api/v1/offers/${e.offerId}/pay-preview`,{offerId:e.offerId,currency:e.currency??"",lineItems:e.lineItems,returnUrl:e.returnUrl??(typeof window<"u"?window.location.href:""),mainOrderId:e.mainOrderId,paymentInstrumentId:e.paymentInstrumentId})}async processOfferPayment(e){if(!this.payment)throw new Error("OffersModule: no PaymentModule injected. Use createHeadlessClient() instead of constructing OffersModule directly.");let t=e.returnUrl??(typeof window<"u"?window.location.href:void 0),r=await this.payPreviewedOffer({...e,returnUrl:t});return this.payment.finalize({payment:r.payment,order:r.order},{returnUrl:t})}async toggleOrderBump(e){return this.http.post(`/api/v1/checkout-sessions/${e.checkoutSessionId}/toggle-order-bump`,{orderBumpOfferId:e.orderBumpOfferId,selected:e.selected})}async listPostPurchaseOffers(e){let t=await this.http.get(`/api/v1/post-purchase/${e}/offers`);return Array.isArray(t)?t:[]}async acceptPostPurchaseOffer(e){return this.http.post(`/api/v1/orders/${e.orderId}/post-purchase-offers/${e.offerId}/accept`,{items:e.items??[]})}async declinePostPurchaseOffer(e){return this.http.post(`/api/v1/orders/${e.orderId}/post-purchase-offers/${e.offerId}/decline`)}};var T=class{constructor(e,t){this.http=e;this.storeId=t}async getProfile(e){return(await this.http.get(`/api/v1/customers/${e}`,{params:{storeId:this.storeId}})).customer}async getByEmail(e){try{return(await this.http.get("/api/v1/customers/by-email",{params:{email:e,storeId:this.storeId}})).customer}catch{return null}}async updateProfile(e,t){return(await this.http.patch(`/api/v1/customers/${e}`,{storeId:this.storeId,...t})).customer}async getOrders(e,t){return this.http.get(`/api/v1/customers/${e}/orders`,{params:{storeId:this.storeId,limit:t==null?void 0:t.limit,offset:t==null?void 0:t.offset}})}async getOrder(e,t){var d,c;let r=async()=>(await this.http.get(`/api/v1/orders/${e}`,{params:{storeId:this.storeId}})).order,n=await r();if(!(t!=null&&t.waitForRelatedOrders)||(d=n.relatedOrders)!=null&&d.length)return n;let s=t.timeoutMs??8e3,o=t.intervalMs??2e3,a=Date.now()+s;for(;Date.now()<a;)if(await new Promise(g=>setTimeout(g,Math.min(o,Math.max(0,a-Date.now())))),n=await r(),(c=n.relatedOrders)!=null&&c.length)return n;return n}async getSubscriptions(e){return(await this.http.get(`/api/v1/customers/${e}/subscriptions`,{params:{storeId:this.storeId}})).subscriptions}async getSubscription(e){return(await this.http.get(`/api/v1/subscriptions/${e}`,{params:{storeId:this.storeId}})).subscription}};var N=class{constructor(e,t){this.http=e;this.storeId=t}async getProducts(e){var n,s;let t={storeId:this.storeId,includeVariants:!0,includePrices:!0};return(n=e==null?void 0:e.productIds)!=null&&n.length&&(t.productIds=e.productIds),(s=e==null?void 0:e.variantIds)!=null&&s.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 L=class{constructor(e,t,r,n){this.http=e;this.storeId=t;this.checkout=r;this.accountId=n}async navigate(e){var a;let t=this.checkout.getCurrentSession();if(!t)throw new y("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 y("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 s=await this.initializeFunnel({funnelId:e.funnelId,stepId:e.stepId,accountId:r,currentUrl:n});return{url:await this.runNavigate({funnelSessionId:s,stepId:e.stepId,session:t,input:e,currentUrl:n}),funnelSessionId:s}}async ensureCmsSession(e,t,r){var o,a,d;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 s=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)??we(),userAgent:Ce(),queryCurrency:((a=r.customer)==null?void 0:a.currency)??e.currency,queryLocale:(d=r.customer)==null?void 0:d.locale},{token:this._cmsToken});this._cmsCustomerId=s.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 m,h,l,u;let{funnelSessionId:t,stepId:r,session:n,input:s,currentUrl:o}=e,a=n.items.map(p=>({variantId:p.variantId,priceId:p.priceId,quantity:p.quantity})),d=s.discountCodes??(n.promotionCode?[n.promotionCode]:void 0),c={email:((m=s.customer)==null?void 0:m.email)??((h=n.customer)==null?void 0:h.email),currency:((l=s.customer)==null?void 0:l.currency)??n.currency,locale:(u=s.customer)==null?void 0:u.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:c,returnUrl:s.returnUrl,storeId:this.storeId,metadata:s.metadata,discountCodes:d,externalShipping:s.externalShipping}}}},{token:this._cmsToken})).result.url}};function we(){return typeof navigator<"u"&&navigator.language?navigator.language:"en-US"}function Ce(){return typeof navigator<"u"&&navigator.userAgent?navigator.userAgent:"tagadapay-headless-sdk"}var O=class{constructor(e){this.http=e}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 U=class{constructor(e){let t=e.environment??"production",r=C.resolveBaseUrl(t,e.baseUrl);this.config={...e,environment:t,baseUrl:r,timeout:e.timeout??3e4},this.http=new C({baseUrl:r,timeout:this.config.timeout,apiKey:e.apiKey,getToken:()=>this._sessionToken});let n=s=>{this._sessionToken=s};this.checkout=new k(this.http,this.config.storeId,n),this.payment=new b(this.http,this.config.storeId,t,this.checkout),this.offers=new x(this.http,this.config.storeId,this.payment),this.customer=new T(this.http,this.config.storeId),this.catalog=new N(this.http,this.config.storeId),this.funnel=new L(this.http,this.config.storeId,this.checkout,this.config.accountId),this.rx=new O(this.http)}setSessionToken(e){this._sessionToken=e}};function oe(i){return new U(i)}var ae=!1,de=!1,J=[];function V(){de=!0;for(let i of J)i();J.length=0}function Y(i,e={}){var t,r;return de||(r=(t=window.google)==null?void 0:t.maps)!=null&&r.places?(V(),Promise.resolve()):ae?new Promise(n=>J.push(n)):(ae=!0,new Promise((n,s)=>{if(J.push(n),document.querySelector('script[src*="maps.googleapis.com"]')){let c=()=>{var g,m;(m=(g=window.google)==null?void 0:g.maps)!=null&&m.places?V():setTimeout(c,100)};c();return}let a=new URLSearchParams({key:i,libraries:"places",v:e.version??"weekly"});e.language&&a.set("language",e.language),e.region&&a.set("region",e.region);let d=document.createElement("script");d.src=`https://maps.googleapis.com/maps/api/js?${a}`,d.async=!0,d.defer=!0,d.onload=()=>V(),d.onerror=()=>s(new Error("Failed to load Google Maps script")),document.head.appendChild(d)}))}var E=class i{static async searchPlaces(e,t={}){var n,s;if(!((s=(n=window.google)==null?void 0:n.maps)!=null&&s.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,d)=>{var c,g,m;o(d===((m=(g=(c=window.google)==null?void 0:c.maps)==null?void 0:g.places)==null?void 0:m.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(s=>{t.getDetails({placeId:e,fields:["place_id","formatted_address","address_components","geometry"]},(o,a)=>{var d,c,g;s(a===((g=(c=(d=window.google)==null?void 0:d.maps)==null?void 0:c.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="",s="",o="",a="",d="",c="",g="";for(let l of e.address_components??[]){let u=l.types;u.includes("subpremise")&&(t.subpremise=l.long_name),u.includes("street_number")&&(t.streetNumber=l.long_name),u.includes("premise")&&(r=l.long_name),u.includes("route")&&(t.route=l.long_name),u.includes("neighborhood")&&(n=l.long_name),u.includes("sublocality_level_5")&&(s=l.long_name),u.includes("sublocality_level_4")&&(o=l.long_name),u.includes("sublocality_level_3")&&(a=l.long_name),u.includes("sublocality_level_2")&&(d=l.long_name),u.includes("sublocality_level_1")&&(c=l.long_name),u.includes("locality")&&(t.locality=l.long_name),u.includes("postal_town")&&(g=l.long_name),u.includes("administrative_area_level_2")&&(t.administrativeAreaLevel2=l.short_name,t.administrativeAreaLevel2Long=l.long_name),u.includes("administrative_area_level_1")&&(t.administrativeAreaLevel1=l.short_name,t.administrativeAreaLevel1Long=l.long_name),u.includes("country")&&(t.country=l.short_name),u.includes("postal_code")&&(t.postalCode=l.long_name)}t.locality||(t.locality=g||d||c||""),!t.administrativeAreaLevel1&&t.administrativeAreaLevel2&&(t.administrativeAreaLevel1=t.administrativeAreaLevel2Long||t.administrativeAreaLevel2,t.administrativeAreaLevel1Long=t.administrativeAreaLevel2Long);let m=t.streetNumber||r,h=t.route||s||o||a||n;if(t.subpremise&&m&&h)t.fullStreetAddress=`${t.subpremise}/${m} ${h}`;else if(m&&h)if(r&&o&&a){let l=`${a}-${o}-${r}`;d&&(l=`${l} ${d}`),t.fullStreetAddress=l}else t.fullStreetAddress=`${m} ${h}`;else h?t.fullStreetAddress=h:m&&(t.fullStreetAddress=m);return t.fullStreetAddress=t.fullStreetAddress.trim(),t}static extractFormattedAddress(e){let t=i.extractAddressComponents(e);return{address1:t.fullStreetAddress,city:t.locality,country:t.country,state:t.administrativeAreaLevel1,postal:t.postalCode}}};var ue="https://cvwnizdbugpz6jwk.public.blob.vercel-storage.com/geodata/v1",M=["en","ru","de","da","fr","es","zh","hi","pt","ja","ar","it","he"],D=new Map,W=new Map,Q=new Map,Z=new Map;async function ke(i){let e=D.get(i);if(e)return e;let t=Q.get(i);return t||(t=(async()=>{let r=`${ue}/${i}/countries.json`,n=await fetch(r);if(!n.ok)throw new Error(`Geodata fetch failed: ${r} (${n.status})`);let s=await n.json();return D.set(i,s),Q.delete(i),s})(),Q.set(i,t),t)}async function Se(i){let e=W.get(i);if(e)return e;let t=Z.get(i);return t||(t=(async()=>{let r=`${ue}/${i}/regions.json`,n=await fetch(r);if(!n.ok)throw new Error(`Geodata fetch failed: ${r} (${n.status})`);let s=await n.json();return W.set(i,s),Z.delete(i),s})(),Z.set(i,t),t)}function ve(i){return D.get(i)||D.get("en")||{}}function Ae(i){return W.get(i)||W.get("en")||{}}async function $(i="en"){await Promise.all([ke(i),Se(i)])}var _=(i="en")=>{let e=ve(i);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))},F=(i,e="en")=>{let r=Ae(e)[i];return r?r.map(([n,s])=>({code:n,name:s,countryCode:i})).sort((n,s)=>n.name.localeCompare(s.name)):[]};function q(i){return D.has(i)}var G=class i{static ensureLoaded(e="en"){return $(e)}static getCountries(e="en"){let t=_(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 _(e).map(t=>({value:t.code,label:t.name}))}static getRegions(e,t="en"){return F(e,t).map(r=>({iso:r.code,name:r.name}))}static getRegionOptions(e,t="en"){return i.getRegions(e,t).map(r=>({value:r.iso,label:r.name}))}static findRegion(e,t,r="en"){return i.getRegions(e,r).find(n=>n.iso===t)??null}static mapGoogleToISO(e,t,r,n="en"){let s=i.getRegions(r,n);if(s.length===0)return null;let o=s.find(a=>a.iso===e);return o||(o=s.find(a=>a.name.toLowerCase()===e.toLowerCase()),o)||(o=s.find(a=>a.name.toLowerCase()===t.toLowerCase()),o)?o:(o=s.find(a=>a.name.toLowerCase().includes(t.toLowerCase())||t.toLowerCase().includes(a.name.toLowerCase())),o??null)}static isLanguageLoaded(e){return q(e)}static getAvailableLanguages(){return M}};var Re={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"},be={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"},xe=new Set(["JPY","KRW","VND","IDR","LAK","KHR","MMK","PYG"]),S=class i{static getSymbol(e){return Re[e]??e}static getName(e){return be[e]??e}static getDecimalPlaces(e){return xe.has(e)?0:2}static getCurrency(e){return{code:e,symbol:i.getSymbol(e),name:i.getName(e),decimalPlaces:i.getDecimalPlaces(e)}}};function X(i,e="USD",t="en-US"){let r=S.getDecimalPlaces(e),n=i/(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`${S.getSymbol(e)}${n.toFixed(r)}`}}return ye(Te);})();
|
|
7
7
|
if(typeof window!=="undefined"&&TagadaHeadlessBundle){ window.TagadaHeadless=TagadaHeadlessBundle; window.TagadaHeadless.create=TagadaHeadlessBundle.createHeadlessClient;}
|
|
8
8
|
//# sourceMappingURL=tagada-headless.min.js.map
|