@tagadapay/headless-sdk 1.0.0 → 1.1.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/dist/core/client.d.ts +3 -0
- package/dist/core/client.d.ts.map +1 -1
- package/dist/core/client.js +2 -0
- package/dist/core/client.js.map +1 -1
- package/dist/core/index.d.ts +2 -1
- 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/catalog.d.ts +27 -0
- package/dist/core/modules/catalog.d.ts.map +1 -0
- package/dist/core/modules/catalog.js +38 -0
- package/dist/core/modules/catalog.js.map +1 -0
- package/dist/core/modules/checkout.d.ts +15 -8
- package/dist/core/modules/checkout.d.ts.map +1 -1
- package/dist/core/modules/checkout.js +50 -14
- package/dist/core/modules/checkout.js.map +1 -1
- package/dist/core/types.d.ts +34 -0
- package/dist/core/types.d.ts.map +1 -1
- package/dist/react/hooks/useCatalog.d.ts +25 -0
- package/dist/react/hooks/useCatalog.d.ts.map +1 -0
- package/dist/react/hooks/useCatalog.js +58 -0
- package/dist/react/hooks/useCatalog.js.map +1 -0
- package/dist/react/hooks/useCheckout.d.ts +1 -1
- package/dist/react/hooks/useCheckout.d.ts.map +1 -1
- package/dist/react/hooks/useCheckout.js +61 -16
- package/dist/react/hooks/useCheckout.js.map +1 -1
- package/dist/react/index.d.ts +3 -1
- package/dist/react/index.d.ts.map +1 -1
- package/dist/react/index.js +1 -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 +101 -21
- package/dist/tagada-headless.min.js +2 -2
- package/dist/tagada-headless.min.js.map +4 -4
- package/package.json +1 -1
package/dist/tagada-headless.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @tagadapay/headless-sdk v1.
|
|
2
|
+
* @tagadapay/headless-sdk v1.1.1
|
|
3
3
|
* Headless checkout, payments, analytics, and CRM
|
|
4
4
|
* @license MIT
|
|
5
5
|
*/
|
|
@@ -44,6 +44,7 @@ var TagadaHeadlessBundle = (() => {
|
|
|
44
44
|
var core_exports = {};
|
|
45
45
|
__export(core_exports, {
|
|
46
46
|
AnalyticsModule: () => AnalyticsModule,
|
|
47
|
+
CatalogModule: () => CatalogModule,
|
|
47
48
|
CheckoutModule: () => CheckoutModule,
|
|
48
49
|
CustomerModule: () => CustomerModule,
|
|
49
50
|
HeadlessClient: () => HeadlessClient,
|
|
@@ -295,40 +296,80 @@ var TagadaHeadlessBundle = (() => {
|
|
|
295
296
|
/** Replace the cart items for an existing session. */
|
|
296
297
|
async updateCart(sessionId, items) {
|
|
297
298
|
return this.http.post(
|
|
298
|
-
`/api/v1/checkout-sessions/${sessionId}/items`,
|
|
299
|
+
`/api/v1/checkout-sessions/${sessionId}/line-items`,
|
|
299
300
|
{ items },
|
|
300
301
|
{ token: this.sessionToken }
|
|
301
302
|
);
|
|
302
303
|
}
|
|
303
|
-
/**
|
|
304
|
+
/**
|
|
305
|
+
* Update customer + address information on the session.
|
|
306
|
+
* Uses the combined endpoint with `partial: true` so missing fields are tolerated.
|
|
307
|
+
*/
|
|
304
308
|
async updateCustomer(sessionId, customer) {
|
|
305
|
-
|
|
306
|
-
`/api/v1/checkout-sessions/${sessionId}/customer`,
|
|
307
|
-
{
|
|
309
|
+
await this.http.post(
|
|
310
|
+
`/api/v1/checkout-sessions/${sessionId}/customer-and-session-info`,
|
|
311
|
+
{
|
|
312
|
+
checkoutSessionId: sessionId,
|
|
313
|
+
partial: true,
|
|
314
|
+
customerData: {
|
|
315
|
+
email: customer.email
|
|
316
|
+
},
|
|
317
|
+
shippingAddress: {
|
|
318
|
+
firstName: customer.firstName,
|
|
319
|
+
lastName: customer.lastName,
|
|
320
|
+
phone: customer.phone
|
|
321
|
+
},
|
|
322
|
+
billingAddress: {},
|
|
323
|
+
differentBillingAddress: false
|
|
324
|
+
},
|
|
308
325
|
{ token: this.sessionToken }
|
|
309
326
|
);
|
|
310
327
|
}
|
|
311
|
-
/**
|
|
328
|
+
/**
|
|
329
|
+
* Update shipping and/or billing address on the session.
|
|
330
|
+
*
|
|
331
|
+
* Address fields use the API's naming: `address1`, `postal`, etc.
|
|
332
|
+
*/
|
|
312
333
|
async updateAddress(sessionId, addresses) {
|
|
313
|
-
|
|
334
|
+
const mapAddress = (a) => {
|
|
335
|
+
if (!a)
|
|
336
|
+
return void 0;
|
|
337
|
+
return {
|
|
338
|
+
address1: a.line1,
|
|
339
|
+
address2: a.line2,
|
|
340
|
+
city: a.city,
|
|
341
|
+
state: a.state,
|
|
342
|
+
postal: a.postalCode,
|
|
343
|
+
country: a.country
|
|
344
|
+
};
|
|
345
|
+
};
|
|
346
|
+
await this.http.post(
|
|
314
347
|
`/api/v1/checkout-sessions/${sessionId}/address`,
|
|
315
|
-
{
|
|
348
|
+
{
|
|
349
|
+
checkoutSessionId: sessionId,
|
|
350
|
+
data: {
|
|
351
|
+
shippingAddress: mapAddress(addresses.shippingAddress) ?? {},
|
|
352
|
+
billingAddress: mapAddress(addresses.billingAddress)
|
|
353
|
+
}
|
|
354
|
+
},
|
|
316
355
|
{ token: this.sessionToken }
|
|
317
356
|
);
|
|
318
357
|
}
|
|
319
358
|
/** Apply a promotion code to the session. */
|
|
320
359
|
async applyPromoCode(sessionId, code) {
|
|
321
|
-
|
|
322
|
-
`/api/v1/checkout-sessions/${sessionId}/
|
|
323
|
-
{ code },
|
|
360
|
+
await this.http.post(
|
|
361
|
+
`/api/v1/checkout-sessions/${sessionId}/promotions/apply`,
|
|
362
|
+
{ checkoutSessionId: sessionId, code },
|
|
324
363
|
{ token: this.sessionToken }
|
|
325
364
|
);
|
|
326
365
|
}
|
|
327
|
-
/** Remove the
|
|
328
|
-
async removePromoCode(sessionId) {
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
366
|
+
/** Remove a promotion from the session by promotion ID. */
|
|
367
|
+
async removePromoCode(sessionId, promotionId) {
|
|
368
|
+
const promoId = promotionId ?? "default";
|
|
369
|
+
await this.http.delete(
|
|
370
|
+
`/api/v1/checkout-sessions/${sessionId}/promotions/${promoId}`,
|
|
371
|
+
{ token: this.sessionToken }
|
|
372
|
+
);
|
|
332
373
|
}
|
|
333
374
|
/** Fetch available shipping rates for the session's address. */
|
|
334
375
|
async getShippingRates(sessionId) {
|
|
@@ -336,13 +377,13 @@ var TagadaHeadlessBundle = (() => {
|
|
|
336
377
|
`/api/v1/checkout-sessions/${sessionId}/shipping-rates`,
|
|
337
378
|
{ token: this.sessionToken }
|
|
338
379
|
);
|
|
339
|
-
return res.rates;
|
|
380
|
+
return res.rates ?? [];
|
|
340
381
|
}
|
|
341
382
|
/** Select a shipping rate for the session. */
|
|
342
383
|
async selectShippingRate(sessionId, rateId) {
|
|
343
|
-
|
|
344
|
-
`/api/v1/checkout-sessions/${sessionId}/shipping-
|
|
345
|
-
{ rateId },
|
|
384
|
+
await this.http.post(
|
|
385
|
+
`/api/v1/checkout-sessions/${sessionId}/shipping-rate`,
|
|
386
|
+
{ checkoutSessionId: sessionId, shippingRateId: rateId },
|
|
346
387
|
{ token: this.sessionToken }
|
|
347
388
|
);
|
|
348
389
|
}
|
|
@@ -1054,6 +1095,44 @@ var TagadaHeadlessBundle = (() => {
|
|
|
1054
1095
|
}
|
|
1055
1096
|
};
|
|
1056
1097
|
|
|
1098
|
+
// src/core/modules/catalog.ts
|
|
1099
|
+
var CatalogModule = class {
|
|
1100
|
+
constructor(http, storeId) {
|
|
1101
|
+
this.http = http;
|
|
1102
|
+
this.storeId = storeId;
|
|
1103
|
+
}
|
|
1104
|
+
/**
|
|
1105
|
+
* List all active products for the store, including variants and prices.
|
|
1106
|
+
*
|
|
1107
|
+
* @param opts.productIds Optional filter to specific product IDs.
|
|
1108
|
+
* @param opts.variantIds Optional filter to products containing these variant IDs.
|
|
1109
|
+
*/
|
|
1110
|
+
async getProducts(opts) {
|
|
1111
|
+
var _a, _b;
|
|
1112
|
+
const body = {
|
|
1113
|
+
storeId: this.storeId,
|
|
1114
|
+
includeVariants: true,
|
|
1115
|
+
includePrices: true
|
|
1116
|
+
};
|
|
1117
|
+
if ((_a = opts == null ? void 0 : opts.productIds) == null ? void 0 : _a.length)
|
|
1118
|
+
body.productIds = opts.productIds;
|
|
1119
|
+
if ((_b = opts == null ? void 0 : opts.variantIds) == null ? void 0 : _b.length)
|
|
1120
|
+
body.variantIds = opts.variantIds;
|
|
1121
|
+
const res = await this.http.post(
|
|
1122
|
+
"/api/v1/products",
|
|
1123
|
+
body
|
|
1124
|
+
);
|
|
1125
|
+
return res.items ?? [];
|
|
1126
|
+
}
|
|
1127
|
+
/**
|
|
1128
|
+
* Get a single product by ID.
|
|
1129
|
+
*/
|
|
1130
|
+
async getProduct(productId) {
|
|
1131
|
+
const items = await this.getProducts({ productIds: [productId] });
|
|
1132
|
+
return items[0] ?? null;
|
|
1133
|
+
}
|
|
1134
|
+
};
|
|
1135
|
+
|
|
1057
1136
|
// src/core/client.ts
|
|
1058
1137
|
var HeadlessClient = class {
|
|
1059
1138
|
constructor(config) {
|
|
@@ -1079,6 +1158,7 @@ var TagadaHeadlessBundle = (() => {
|
|
|
1079
1158
|
this.analytics = new AnalyticsModule(this.http, this.config.storeId);
|
|
1080
1159
|
this.offers = new OffersModule(this.http, this.config.storeId);
|
|
1081
1160
|
this.customer = new CustomerModule(this.http, this.config.storeId);
|
|
1161
|
+
this.catalog = new CatalogModule(this.http, this.config.storeId);
|
|
1082
1162
|
}
|
|
1083
1163
|
/** Manually set the session token (e.g. from URL params on page load). */
|
|
1084
1164
|
setSessionToken(token) {
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @tagadapay/headless-sdk v1.
|
|
2
|
+
* @tagadapay/headless-sdk v1.1.1
|
|
3
3
|
* Headless checkout, payments, analytics, and CRM
|
|
4
4
|
* @license MIT
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var TagadaHeadlessBundle=(()=>{var N=Object.create;var A=Object.defineProperty;var U=Object.getOwnPropertyDescriptor;var _=Object.getOwnPropertyNames;var D=Object.getPrototypeOf,L=Object.prototype.hasOwnProperty;var F=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var z=(o,e)=>{for(var t in e)A(o,t,{get:e[t],enumerable:!0})},q=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of _(e))!L.call(o,s)&&s!==t&&A(o,s,{get:()=>e[s],enumerable:!(n=U(e,s))||n.enumerable});return o};var V=(o,e,t)=>(t=o!=null?N(D(o)):{},q(e||!o||!o.__esModule?A(t,"default",{value:o,enumerable:!0}):t,o)),G=o=>q(A({},"__esModule",{value:!0}),o);var J={};z(J,{AnalyticsModule:()=>T,CheckoutModule:()=>P,CustomerModule:()=>b,HeadlessClient:()=>x,HttpClient:()=>g,OffersModule:()=>S,PaymentModule:()=>C,TagadaAuthError:()=>k,TagadaError:()=>u,TagadaNetworkError:()=>l,TagadaNotFoundError:()=>I,TagadaPaymentError:()=>O,TagadaRateLimitError:()=>v,TagadaValidationError:()=>w,createHeadlessClient:()=>H});var u=class extends Error{constructor(e,t,n,s){super(e),this.name="TagadaError",this.code=t,this.statusCode=n,this.details=s}},k=class extends u{constructor(e="Authentication failed. Check your API key or checkout token."){super(e,"auth_error",401),this.name="TagadaAuthError"}},w=class extends u{constructor(e,t=[]){super(e,"validation_error",422,{errors:t}),this.name="TagadaValidationError",this.errors=t}},I=class extends u{constructor(e,t){super(`${e} "${t}" not found.`,"not_found",404),this.name="TagadaNotFoundError"}},v=class extends u{constructor(e=1e3){super(`Rate limited. Retry after ${e}ms.`,"rate_limit",429),this.name="TagadaRateLimitError",this.retryAfterMs=e}},O=class extends u{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}},l=class extends u{constructor(e="Network request failed. Check your connection."){super(e,"network_error"),this.name="TagadaNetworkError"}};var $={production:"https://app.tagadapay.com",development:"https://app.dev.tagadapay.com",local:"http://localhost:3000"},g=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??$[e]??$.production}async request(e,t={}){var h;let{method:n="GET",body:s,headers:i={},params:r,token:a,signal:c}=t,p=`${this.baseUrl}${e}`;if(r){let d=new URLSearchParams;for(let[j,M]of Object.entries(r))M!==void 0&&d.set(j,String(M));let R=d.toString();R&&(p+=`?${R}`)}let m={"Content-Type":"application/json",...i},y=a??this.apiKey??((h=this.getToken)==null?void 0:h.call(this));y&&(m["x-cms-token"]=y);let E=new AbortController,f=setTimeout(()=>E.abort(),this.timeout);try{let d=await fetch(p,{method:n,headers:m,body:s!=null?JSON.stringify(s):void 0,signal:c??E.signal});if(clearTimeout(f),d.ok){let R=await d.text();return R?JSON.parse(R):{}}throw await this.handleErrorResponse(d,e),new u("Unexpected error","unknown",d.status)}catch(d){throw clearTimeout(f),d instanceof u?d:d instanceof DOMException&&d.name==="AbortError"?new l(`Request to ${e} timed out after ${this.timeout}ms.`):new l(d instanceof Error?d.message:"Network request failed.")}}get(e,t){return this.request(e,{...t,method:"GET"})}post(e,t,n){return this.request(e,{...n,method:"POST",body:t})}patch(e,t,n){return this.request(e,{...n,method:"PATCH",body:t})}put(e,t,n){return this.request(e,{...n,method:"PUT",body:t})}delete(e,t){return this.request(e,{...t,method:"DELETE"})}async handleErrorResponse(e,t){let n={};try{n=await e.json()}catch{}let s=n.message??n.error??`Request failed: ${e.status} ${e.statusText} on ${t}`;switch(e.status){case 401:case 403:throw new k(s);case 404:throw new I(t,"");case 422:{let i=Array.isArray(n.errors)?n.errors:[];throw new w(s,i)}case 429:{let i=Number(e.headers.get("Retry-After")??"1")*1e3;throw new v(i)}default:throw new u(s,"api_error",e.status,n)}}};var P=class{constructor(e,t,n){this.http=e;this.storeId=t;this.onTokenChange=n}async loadSession(e,t){var s;t&&(this.sessionToken=t,(s=this.onTokenChange)==null||s.call(this,t));let n=await this.http.get(`/api/v1/checkout-sessions/${e}/v2`,{params:{skipAsyncWait:"false"},token:this.sessionToken});return this.normalizeSession(n)}async createSession(e){var a;let t=e.items.map(c=>({variantId:c.variantId,priceId:c.priceId,quantity:c.quantity})),n={storeId:this.storeId,lineItems:t};e.currency&&(n.currency=e.currency),e.returnUrl&&(n.returnUrl=e.returnUrl),e.customerEmail&&(n.customer={email:e.customerEmail,firstName:e.customerFirstName,lastName:e.customerLastName,currency:e.currency});let s=await this.http.post("/api/v1/checkout/session/init",n),r=new URL(s.checkoutUrl).searchParams.get("token")??"";return this.sessionToken=r,r&&((a=this.onTokenChange)==null||a.call(this,r)),{checkoutUrl:s.checkoutUrl,checkoutToken:s.checkoutToken,sessionToken:r,customerId:s.customerId}}async updateCart(e,t){return this.http.post(`/api/v1/checkout-sessions/${e}/items`,{items:t},{token:this.sessionToken})}async updateCustomer(e,t){return this.http.patch(`/api/v1/checkout-sessions/${e}/customer`,{data:t},{token:this.sessionToken})}async updateAddress(e,t){return this.http.post(`/api/v1/checkout-sessions/${e}/address`,{data:t},{token:this.sessionToken})}async applyPromoCode(e,t){return this.http.post(`/api/v1/checkout-sessions/${e}/promo`,{code:t},{token:this.sessionToken})}async removePromoCode(e){return this.http.delete(`/api/v1/checkout-sessions/${e}/promo`,{token:this.sessionToken})}async getShippingRates(e){return(await this.http.get(`/api/v1/checkout-sessions/${e}/shipping-rates`,{token:this.sessionToken})).rates}async selectShippingRate(e,t){return this.http.post(`/api/v1/checkout-sessions/${e}/shipping-rates`,{rateId:t},{token:this.sessionToken})}normalizeSession(e){let t=e.checkoutSession,n=t.orderSummaries??[],s=e.summary??t.summary??n[0]??{},i=t.sessionLineItems??[],r=t.customer,a=i.map(p=>{let m=p.price,y=(m==null?void 0:m.variant)??{},E=y.product??{},f=(m==null?void 0:m.currencyOptions)??{},h=f.USD??f[Object.keys(f)[0]];return{id:p.id,variantId:p.variantId,priceId:p.priceId,productName:E.name??"",variantName:y.name??"",quantity:p.quantity??1,unitAmount:(h==null?void 0:h.amount)??0,totalAmount:((h==null?void 0:h.amount)??0)*(p.quantity??1),currency:t.selectedPresentmentCurrency??"USD",imageUrl:y.imageUrl??""}}),c=s.items??[];return{id:t.id,storeId:t.storeId,checkoutToken:t.checkoutToken,currency:t.selectedPresentmentCurrency??"USD",items:a,totals:{subtotal:s.subtotalAmount??0,discount:s.totalPromotionAmount??0,shipping:s.shippingCost??0,tax:s.totalTaxAmount??0,total:s.totalAmount??c.reduce((p,m)=>p+(m.amount??0),0),currency:s.currency??t.selectedPresentmentCurrency??"USD"},customer:r?{id:r.id,email:r.email,firstName:r.firstName,lastName:r.lastName}:void 0,shippingAddress:t.shippingAddress,billingAddress:t.billingAddress,metadata:t.metadata}}};var C=class{constructor(e,t,n){this.http=e;this.storeId=t;this.environment=n}async getPaymentSetup(e){let t=await this.http.get("/api/v1/payment-methods",{params:{checkoutSessionId:e}}),n={};for(let s of t.methods??[]){let i=s.provider?`${s.method}:${s.provider}`:s.method;n[i]=s}return n}async getExpressMethods(e){var s,i;let t=await this.getPaymentSetup(e),n={};for(let[,r]of Object.entries(t)){if(!r.enabled||!r.express)continue;let a=r.method,c={type:a,available:!0,processorId:r.processorId,publishableKey:r.publishableKey,metadata:r.metadata};if(a==="apple_pay"||r.type==="apple_pay"){let p=typeof window<"u"&&"ApplePaySession"in window&&((i=(s=window.ApplePaySession)==null?void 0:s.canMakePayments)==null?void 0:i.call(s));n.applePay={...c,available:!!p}}else a==="google_pay"||r.type==="google_pay"?n.googlePay=c:a==="paypal"?n.paypal=c:a==="klarna"||a==="klarna_express"?n.klarna=c:a==="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){let t=await this.getPaymentSetup(e);return Object.entries(t).filter(([,n])=>n.enabled).map(([n])=>n)}async tokenizeCard(e){let t=await this.loadCoreJs(),n=new t.Tokenizer({environment:this.environment});await n.initialize();let s={cardNumber:e.cardNumber,expiryDate:e.expiryDate,cvc:e.cvc};e.cardholderName&&(s.cardholderName=e.cardholderName);let[i,r]=await Promise.all([n.tokenizeCard(s),n.tokenizeCardRaw(s)]);return{tagadaToken:i,rawToken:r}}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,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})}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})}async processApplePay(e){let t=await this.loadCoreJs(),n=new t.Tokenizer({environment:this.environment});await n.initialize();let{tagadaToken:s}=await n.tokenizeApplePay(e.applePayToken);return this.pay({checkoutSessionId:e.checkoutSessionId,tagadaToken:s,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:"apple_pay",isExpress:!0})}async processGooglePay(e){let t=await this.loadCoreJs(),n=new t.Tokenizer({environment:this.environment});await n.initialize();let{tagadaToken:s}=await n.tokenizeGooglePay(e.googlePayToken);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 getPaymentStatus(e){return this.http.get(`/api/v1/payments/${e}`)}async pollPaymentStatus(e,t){let n=(t==null?void 0:t.intervalMs)??1500,s=(t==null?void 0:t.timeoutMs)??6e4,i=Date.now();for(;Date.now()-i<s;){let r=await this.getPaymentStatus(e);if(r.status==="succeeded"||r.status==="failed"||r.status==="declined")return r;await new Promise(a=>setTimeout(a,n))}throw new Error(`Payment ${e} did not reach terminal status within ${s}ms.`)}async completeAfter3ds(e){return this.http.post("/api/v1/payments/complete-after-3ds",{paymentId:e})}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 T=class{constructor(e,t){this.http=e;this.storeId=t;this.pixels={loaded:!1};this.eventQueue=[];this.dedupeSet=new Set}async init(e){if(this.pixels.loaded)return;let t=e==null?void 0:e.pixelConfig;if(!t)try{t=(await this.http.get("/api/v1/checkout/config",{params:{storeId:this.storeId}})).pixels}catch{}this.pixels={loaded:!0,config:t},typeof window<"u"&&t&&this.loadPixelScripts(t),this.flushQueue()}trackPageView(e){this.fireEvent("PageView",{page:e??this.getCurrentPath()})}trackViewContent(e){this.fireEvent("ViewContent",e)}trackAddToCart(e){this.fireEvent("AddToCart",e)}trackInitiateCheckout(e){this.fireEvent("InitiateCheckout",e??{})}trackAddPaymentInfo(e){this.fireEvent("AddPaymentInfo",e??{})}trackPurchase(e){this.fireEvent("Purchase",e,!0)}trackCustomEvent(e,t){this.fireEvent(e,t??{})}trackStep(e){this.fireEvent("FunnelStep",e),this.http.post("/api/v1/funnel-tracking/step",{storeId:this.storeId,...e}).catch(()=>{})}trackConversion(e){this.fireEvent("Conversion",e,!0)}fireEvent(e,t,n=!1){if(n){let s=`${e}:${JSON.stringify(t)}`;if(this.dedupeSet.has(s))return;this.dedupeSet.add(s)}if(!this.pixels.loaded){this.eventQueue.push({event:e,data:t});return}this.sendToMeta(e,t),this.sendToTikTok(e,t),this.sendToSnapchat(e,t),this.sendToGTM(e,t),this.sendToGA(e,t)}flushQueue(){let e=[...this.eventQueue];this.eventQueue=[];for(let{event:t,data:n}of e)this.fireEvent(t,n)}getCurrentPath(){return typeof window<"u"?window.location.pathname:"/"}loadPixelScripts(e){e.metaPixelId&&this.loadMetaPixel(e.metaPixelId),e.tiktokPixelId&&this.loadTikTokPixel(e.tiktokPixelId),e.snapchatPixelId&&this.loadSnapchatPixel(e.snapchatPixelId),e.gtmId&&this.loadGTM(e.gtmId),e.gaId&&this.loadGA(e.gaId)}loadMetaPixel(e){if(typeof window>"u")return;let t=window;if(t.fbq)return;let n=t.fbq=function(...s){n.callMethod?n.callMethod(...s):n.queue.push(s)};n.queue=[],n.loaded=!0,n.version="2.0",this.injectScript("https://connect.facebook.net/en_US/fbevents.js"),t.fbq("init",e)}loadTikTokPixel(e){if(typeof window>"u")return;let t=window;if(t.ttq)return;let n={};n.methods=["page","track","identify","instances","debug","on","off","once","ready","alias","group","enableCookie","disableCookie"],n.setAndDefer=function(s,i){s[i]=function(...r){s.push([i,...r])}},t.ttq=n,this.injectScript("https://analytics.tiktok.com/i18n/pixel/events.js?sdkid="+e)}loadSnapchatPixel(e){if(typeof window>"u")return;let t=window;t.snaptr||(t.snaptr=function(...n){t.snaptr.handleRequest?t.snaptr.handleRequest(...n):t.snaptr.queue.push(n)},t.snaptr.queue=[],this.injectScript("https://sc-static.net/scevent.min.js"),t.snaptr("init",e))}loadGTM(e){if(typeof window>"u")return;let t=window;t.dataLayer=t.dataLayer??[],t.dataLayer.push({"gtm.start":Date.now(),event:"gtm.js"}),this.injectScript(`https://www.googletagmanager.com/gtm.js?id=${e}`)}loadGA(e){if(typeof window>"u")return;this.injectScript(`https://www.googletagmanager.com/gtag/js?id=${e}`);let t=window;t.dataLayer=t.dataLayer??[],t.gtag=function(...n){t.dataLayer.push(n)},t.gtag("js",new Date),t.gtag("config",e)}injectScript(e){if(typeof document>"u")return;let t=document.createElement("script");t.async=!0,t.src=e,document.head.appendChild(t)}sendToMeta(e,t){let n=typeof window<"u"?window:null,s=n==null?void 0:n.fbq;if(!s)return;let r={PageView:"PageView",ViewContent:"ViewContent",AddToCart:"AddToCart",InitiateCheckout:"InitiateCheckout",AddPaymentInfo:"AddPaymentInfo",Purchase:"Purchase"}[e];r?s("track",r,t):s("trackCustom",e,t)}sendToTikTok(e,t){var i,r;let n=typeof window<"u"?window:null,s=n==null?void 0:n.ttq;s&&(e==="PageView"?(i=s.page)==null||i.call(s):(r=s.track)==null||r.call(s,e,t))}sendToSnapchat(e,t){let n=typeof window<"u"?window:null,s=n==null?void 0:n.snaptr;if(!s)return;let r={PageView:"PAGE_VIEW",ViewContent:"VIEW_CONTENT",AddToCart:"ADD_CART",InitiateCheckout:"START_CHECKOUT",Purchase:"PURCHASE"}[e];r&&s("track",r,t)}sendToGTM(e,t){let n=typeof window<"u"?window:null,s=n==null?void 0:n.dataLayer;s&&s.push({event:e,...t})}sendToGA(e,t){let n=typeof window<"u"?window:null,s=n==null?void 0:n.gtag;s&&s("event",e,t)}};var S=class{constructor(e,t){this.http=e;this.storeId=t}async loadOffer(e){return(await this.http.get(`/api/v1/checkout-offers/${e}`,{params:{storeId:this.storeId}})).offer}async listOffers(e){return(await this.http.get("/api/v1/checkout-offers",{params:{storeId:this.storeId,type:e==null?void 0:e.type}})).offers}async acceptOffer(e){return this.http.post("/api/v1/checkout-offers/accept",{offerId:e.offerId,checkoutSessionId:e.checkoutSessionId,storeId:this.storeId,paymentInstrumentId:e.paymentInstrumentId})}async declineOffer(e){return this.http.post("/api/v1/checkout-offers/decline",{offerId:e.offerId,checkoutSessionId:e.checkoutSessionId,storeId:this.storeId})}async listOrderBumps(e){return(await this.http.get("/api/v1/checkout-offers",{params:{storeId:this.storeId,checkoutSessionId:e,type:"orderbump"}})).offers}async toggleOrderBump(e){await this.http.post(`/api/v1/checkout-sessions/${e.checkoutSessionId}/order-bumps`,{offerId:e.offerId,selected:e.selected})}};var b=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 x=class{constructor(e){let t=e.environment??"production",n=g.resolveBaseUrl(t,e.baseUrl);this.config={...e,environment:t,baseUrl:n,timeout:e.timeout??3e4},this.http=new g({baseUrl:n,timeout:this.config.timeout,apiKey:e.apiKey,getToken:()=>this._sessionToken});let s=i=>{this._sessionToken=i};this.checkout=new P(this.http,this.config.storeId,s),this.payment=new C(this.http,this.config.storeId,t),this.analytics=new T(this.http,this.config.storeId),this.offers=new S(this.http,this.config.storeId),this.customer=new b(this.http,this.config.storeId)}setSessionToken(e){this._sessionToken=e}};function H(o){return new x(o)}return G(J);})();
|
|
6
|
+
"use strict";var TagadaHeadlessBundle=(()=>{var U=Object.create;var O=Object.defineProperty;var _=Object.getOwnPropertyDescriptor;var D=Object.getOwnPropertyNames;var L=Object.getPrototypeOf,F=Object.prototype.hasOwnProperty;var z=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var V=(o,e)=>{for(var t in e)O(o,t,{get:e[t],enumerable:!0})},N=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of D(e))!F.call(o,s)&&s!==t&&O(o,s,{get:()=>e[s],enumerable:!(n=_(e,s))||n.enumerable});return o};var G=(o,e,t)=>(t=o!=null?U(L(o)):{},N(e||!o||!o.__esModule?O(t,"default",{value:o,enumerable:!0}):t,o)),J=o=>N(O({},"__esModule",{value:!0}),o);var K={};V(K,{AnalyticsModule:()=>T,CatalogModule:()=>R,CheckoutModule:()=>P,CustomerModule:()=>b,HeadlessClient:()=>A,HttpClient:()=>g,OffersModule:()=>S,PaymentModule:()=>C,TagadaAuthError:()=>k,TagadaError:()=>u,TagadaNetworkError:()=>l,TagadaNotFoundError:()=>I,TagadaPaymentError:()=>M,TagadaRateLimitError:()=>v,TagadaValidationError:()=>w,createHeadlessClient:()=>H});var u=class extends Error{constructor(e,t,n,s){super(e),this.name="TagadaError",this.code=t,this.statusCode=n,this.details=s}},k=class extends u{constructor(e="Authentication failed. Check your API key or checkout token."){super(e,"auth_error",401),this.name="TagadaAuthError"}},w=class extends u{constructor(e,t=[]){super(e,"validation_error",422,{errors:t}),this.name="TagadaValidationError",this.errors=t}},I=class extends u{constructor(e,t){super(`${e} "${t}" not found.`,"not_found",404),this.name="TagadaNotFoundError"}},v=class extends u{constructor(e=1e3){super(`Rate limited. Retry after ${e}ms.`,"rate_limit",429),this.name="TagadaRateLimitError",this.retryAfterMs=e}},M=class extends u{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}},l=class extends u{constructor(e="Network request failed. Check your connection."){super(e,"network_error"),this.name="TagadaNetworkError"}};var $={production:"https://app.tagadapay.com",development:"https://app.dev.tagadapay.com",local:"http://localhost:3000"},g=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??$[e]??$.production}async request(e,t={}){var h;let{method:n="GET",body:s,headers:i={},params:r,token:a,signal:c}=t,p=`${this.baseUrl}${e}`;if(r){let d=new URLSearchParams;for(let[j,q]of Object.entries(r))q!==void 0&&d.set(j,String(q));let x=d.toString();x&&(p+=`?${x}`)}let m={"Content-Type":"application/json",...i},y=a??this.apiKey??((h=this.getToken)==null?void 0:h.call(this));y&&(m["x-cms-token"]=y);let E=new AbortController,f=setTimeout(()=>E.abort(),this.timeout);try{let d=await fetch(p,{method:n,headers:m,body:s!=null?JSON.stringify(s):void 0,signal:c??E.signal});if(clearTimeout(f),d.ok){let x=await d.text();return x?JSON.parse(x):{}}throw await this.handleErrorResponse(d,e),new u("Unexpected error","unknown",d.status)}catch(d){throw clearTimeout(f),d instanceof u?d:d instanceof DOMException&&d.name==="AbortError"?new l(`Request to ${e} timed out after ${this.timeout}ms.`):new l(d instanceof Error?d.message:"Network request failed.")}}get(e,t){return this.request(e,{...t,method:"GET"})}post(e,t,n){return this.request(e,{...n,method:"POST",body:t})}patch(e,t,n){return this.request(e,{...n,method:"PATCH",body:t})}put(e,t,n){return this.request(e,{...n,method:"PUT",body:t})}delete(e,t){return this.request(e,{...t,method:"DELETE"})}async handleErrorResponse(e,t){let n={};try{n=await e.json()}catch{}let s=n.message??n.error??`Request failed: ${e.status} ${e.statusText} on ${t}`;switch(e.status){case 401:case 403:throw new k(s);case 404:throw new I(t,"");case 422:{let i=Array.isArray(n.errors)?n.errors:[];throw new w(s,i)}case 429:{let i=Number(e.headers.get("Retry-After")??"1")*1e3;throw new v(i)}default:throw new u(s,"api_error",e.status,n)}}};var P=class{constructor(e,t,n){this.http=e;this.storeId=t;this.onTokenChange=n}async loadSession(e,t){var s;t&&(this.sessionToken=t,(s=this.onTokenChange)==null||s.call(this,t));let n=await this.http.get(`/api/v1/checkout-sessions/${e}/v2`,{params:{skipAsyncWait:"false"},token:this.sessionToken});return this.normalizeSession(n)}async createSession(e){var a;let t=e.items.map(c=>({variantId:c.variantId,priceId:c.priceId,quantity:c.quantity})),n={storeId:this.storeId,lineItems:t};e.currency&&(n.currency=e.currency),e.returnUrl&&(n.returnUrl=e.returnUrl),e.customerEmail&&(n.customer={email:e.customerEmail,firstName:e.customerFirstName,lastName:e.customerLastName,currency:e.currency});let s=await this.http.post("/api/v1/checkout/session/init",n),r=new URL(s.checkoutUrl).searchParams.get("token")??"";return this.sessionToken=r,r&&((a=this.onTokenChange)==null||a.call(this,r)),{checkoutUrl:s.checkoutUrl,checkoutToken:s.checkoutToken,sessionToken:r,customerId:s.customerId}}async updateCart(e,t){return this.http.post(`/api/v1/checkout-sessions/${e}/line-items`,{items:t},{token:this.sessionToken})}async updateCustomer(e,t){await this.http.post(`/api/v1/checkout-sessions/${e}/customer-and-session-info`,{checkoutSessionId:e,partial:!0,customerData:{email:t.email},shippingAddress:{firstName:t.firstName,lastName:t.lastName,phone:t.phone},billingAddress:{},differentBillingAddress:!1},{token:this.sessionToken})}async updateAddress(e,t){let n=s=>{if(s)return{address1:s.line1,address2:s.line2,city:s.city,state:s.state,postal:s.postalCode,country:s.country}};await this.http.post(`/api/v1/checkout-sessions/${e}/address`,{checkoutSessionId:e,data:{shippingAddress:n(t.shippingAddress)??{},billingAddress:n(t.billingAddress)}},{token:this.sessionToken})}async applyPromoCode(e,t){await this.http.post(`/api/v1/checkout-sessions/${e}/promotions/apply`,{checkoutSessionId:e,code:t},{token:this.sessionToken})}async removePromoCode(e,t){let n=t??"default";await this.http.delete(`/api/v1/checkout-sessions/${e}/promotions/${n}`,{token:this.sessionToken})}async getShippingRates(e){return(await this.http.get(`/api/v1/checkout-sessions/${e}/shipping-rates`,{token:this.sessionToken})).rates??[]}async selectShippingRate(e,t){await this.http.post(`/api/v1/checkout-sessions/${e}/shipping-rate`,{checkoutSessionId:e,shippingRateId:t},{token:this.sessionToken})}normalizeSession(e){let t=e.checkoutSession,n=t.orderSummaries??[],s=e.summary??t.summary??n[0]??{},i=t.sessionLineItems??[],r=t.customer,a=i.map(p=>{let m=p.price,y=(m==null?void 0:m.variant)??{},E=y.product??{},f=(m==null?void 0:m.currencyOptions)??{},h=f.USD??f[Object.keys(f)[0]];return{id:p.id,variantId:p.variantId,priceId:p.priceId,productName:E.name??"",variantName:y.name??"",quantity:p.quantity??1,unitAmount:(h==null?void 0:h.amount)??0,totalAmount:((h==null?void 0:h.amount)??0)*(p.quantity??1),currency:t.selectedPresentmentCurrency??"USD",imageUrl:y.imageUrl??""}}),c=s.items??[];return{id:t.id,storeId:t.storeId,checkoutToken:t.checkoutToken,currency:t.selectedPresentmentCurrency??"USD",items:a,totals:{subtotal:s.subtotalAmount??0,discount:s.totalPromotionAmount??0,shipping:s.shippingCost??0,tax:s.totalTaxAmount??0,total:s.totalAmount??c.reduce((p,m)=>p+(m.amount??0),0),currency:s.currency??t.selectedPresentmentCurrency??"USD"},customer:r?{id:r.id,email:r.email,firstName:r.firstName,lastName:r.lastName}:void 0,shippingAddress:t.shippingAddress,billingAddress:t.billingAddress,metadata:t.metadata}}};var C=class{constructor(e,t,n){this.http=e;this.storeId=t;this.environment=n}async getPaymentSetup(e){let t=await this.http.get("/api/v1/payment-methods",{params:{checkoutSessionId:e}}),n={};for(let s of t.methods??[]){let i=s.provider?`${s.method}:${s.provider}`:s.method;n[i]=s}return n}async getExpressMethods(e){var s,i;let t=await this.getPaymentSetup(e),n={};for(let[,r]of Object.entries(t)){if(!r.enabled||!r.express)continue;let a=r.method,c={type:a,available:!0,processorId:r.processorId,publishableKey:r.publishableKey,metadata:r.metadata};if(a==="apple_pay"||r.type==="apple_pay"){let p=typeof window<"u"&&"ApplePaySession"in window&&((i=(s=window.ApplePaySession)==null?void 0:s.canMakePayments)==null?void 0:i.call(s));n.applePay={...c,available:!!p}}else a==="google_pay"||r.type==="google_pay"?n.googlePay=c:a==="paypal"?n.paypal=c:a==="klarna"||a==="klarna_express"?n.klarna=c:a==="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){let t=await this.getPaymentSetup(e);return Object.entries(t).filter(([,n])=>n.enabled).map(([n])=>n)}async tokenizeCard(e){let t=await this.loadCoreJs(),n=new t.Tokenizer({environment:this.environment});await n.initialize();let s={cardNumber:e.cardNumber,expiryDate:e.expiryDate,cvc:e.cvc};e.cardholderName&&(s.cardholderName=e.cardholderName);let[i,r]=await Promise.all([n.tokenizeCard(s),n.tokenizeCardRaw(s)]);return{tagadaToken:i,rawToken:r}}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,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})}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})}async processApplePay(e){let t=await this.loadCoreJs(),n=new t.Tokenizer({environment:this.environment});await n.initialize();let{tagadaToken:s}=await n.tokenizeApplePay(e.applePayToken);return this.pay({checkoutSessionId:e.checkoutSessionId,tagadaToken:s,paymentFlowId:e.paymentFlowId,processorId:e.processorId,paymentMethod:"apple_pay",isExpress:!0})}async processGooglePay(e){let t=await this.loadCoreJs(),n=new t.Tokenizer({environment:this.environment});await n.initialize();let{tagadaToken:s}=await n.tokenizeGooglePay(e.googlePayToken);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 getPaymentStatus(e){return this.http.get(`/api/v1/payments/${e}`)}async pollPaymentStatus(e,t){let n=(t==null?void 0:t.intervalMs)??1500,s=(t==null?void 0:t.timeoutMs)??6e4,i=Date.now();for(;Date.now()-i<s;){let r=await this.getPaymentStatus(e);if(r.status==="succeeded"||r.status==="failed"||r.status==="declined")return r;await new Promise(a=>setTimeout(a,n))}throw new Error(`Payment ${e} did not reach terminal status within ${s}ms.`)}async completeAfter3ds(e){return this.http.post("/api/v1/payments/complete-after-3ds",{paymentId:e})}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 T=class{constructor(e,t){this.http=e;this.storeId=t;this.pixels={loaded:!1};this.eventQueue=[];this.dedupeSet=new Set}async init(e){if(this.pixels.loaded)return;let t=e==null?void 0:e.pixelConfig;if(!t)try{t=(await this.http.get("/api/v1/checkout/config",{params:{storeId:this.storeId}})).pixels}catch{}this.pixels={loaded:!0,config:t},typeof window<"u"&&t&&this.loadPixelScripts(t),this.flushQueue()}trackPageView(e){this.fireEvent("PageView",{page:e??this.getCurrentPath()})}trackViewContent(e){this.fireEvent("ViewContent",e)}trackAddToCart(e){this.fireEvent("AddToCart",e)}trackInitiateCheckout(e){this.fireEvent("InitiateCheckout",e??{})}trackAddPaymentInfo(e){this.fireEvent("AddPaymentInfo",e??{})}trackPurchase(e){this.fireEvent("Purchase",e,!0)}trackCustomEvent(e,t){this.fireEvent(e,t??{})}trackStep(e){this.fireEvent("FunnelStep",e),this.http.post("/api/v1/funnel-tracking/step",{storeId:this.storeId,...e}).catch(()=>{})}trackConversion(e){this.fireEvent("Conversion",e,!0)}fireEvent(e,t,n=!1){if(n){let s=`${e}:${JSON.stringify(t)}`;if(this.dedupeSet.has(s))return;this.dedupeSet.add(s)}if(!this.pixels.loaded){this.eventQueue.push({event:e,data:t});return}this.sendToMeta(e,t),this.sendToTikTok(e,t),this.sendToSnapchat(e,t),this.sendToGTM(e,t),this.sendToGA(e,t)}flushQueue(){let e=[...this.eventQueue];this.eventQueue=[];for(let{event:t,data:n}of e)this.fireEvent(t,n)}getCurrentPath(){return typeof window<"u"?window.location.pathname:"/"}loadPixelScripts(e){e.metaPixelId&&this.loadMetaPixel(e.metaPixelId),e.tiktokPixelId&&this.loadTikTokPixel(e.tiktokPixelId),e.snapchatPixelId&&this.loadSnapchatPixel(e.snapchatPixelId),e.gtmId&&this.loadGTM(e.gtmId),e.gaId&&this.loadGA(e.gaId)}loadMetaPixel(e){if(typeof window>"u")return;let t=window;if(t.fbq)return;let n=t.fbq=function(...s){n.callMethod?n.callMethod(...s):n.queue.push(s)};n.queue=[],n.loaded=!0,n.version="2.0",this.injectScript("https://connect.facebook.net/en_US/fbevents.js"),t.fbq("init",e)}loadTikTokPixel(e){if(typeof window>"u")return;let t=window;if(t.ttq)return;let n={};n.methods=["page","track","identify","instances","debug","on","off","once","ready","alias","group","enableCookie","disableCookie"],n.setAndDefer=function(s,i){s[i]=function(...r){s.push([i,...r])}},t.ttq=n,this.injectScript("https://analytics.tiktok.com/i18n/pixel/events.js?sdkid="+e)}loadSnapchatPixel(e){if(typeof window>"u")return;let t=window;t.snaptr||(t.snaptr=function(...n){t.snaptr.handleRequest?t.snaptr.handleRequest(...n):t.snaptr.queue.push(n)},t.snaptr.queue=[],this.injectScript("https://sc-static.net/scevent.min.js"),t.snaptr("init",e))}loadGTM(e){if(typeof window>"u")return;let t=window;t.dataLayer=t.dataLayer??[],t.dataLayer.push({"gtm.start":Date.now(),event:"gtm.js"}),this.injectScript(`https://www.googletagmanager.com/gtm.js?id=${e}`)}loadGA(e){if(typeof window>"u")return;this.injectScript(`https://www.googletagmanager.com/gtag/js?id=${e}`);let t=window;t.dataLayer=t.dataLayer??[],t.gtag=function(...n){t.dataLayer.push(n)},t.gtag("js",new Date),t.gtag("config",e)}injectScript(e){if(typeof document>"u")return;let t=document.createElement("script");t.async=!0,t.src=e,document.head.appendChild(t)}sendToMeta(e,t){let n=typeof window<"u"?window:null,s=n==null?void 0:n.fbq;if(!s)return;let r={PageView:"PageView",ViewContent:"ViewContent",AddToCart:"AddToCart",InitiateCheckout:"InitiateCheckout",AddPaymentInfo:"AddPaymentInfo",Purchase:"Purchase"}[e];r?s("track",r,t):s("trackCustom",e,t)}sendToTikTok(e,t){var i,r;let n=typeof window<"u"?window:null,s=n==null?void 0:n.ttq;s&&(e==="PageView"?(i=s.page)==null||i.call(s):(r=s.track)==null||r.call(s,e,t))}sendToSnapchat(e,t){let n=typeof window<"u"?window:null,s=n==null?void 0:n.snaptr;if(!s)return;let r={PageView:"PAGE_VIEW",ViewContent:"VIEW_CONTENT",AddToCart:"ADD_CART",InitiateCheckout:"START_CHECKOUT",Purchase:"PURCHASE"}[e];r&&s("track",r,t)}sendToGTM(e,t){let n=typeof window<"u"?window:null,s=n==null?void 0:n.dataLayer;s&&s.push({event:e,...t})}sendToGA(e,t){let n=typeof window<"u"?window:null,s=n==null?void 0:n.gtag;s&&s("event",e,t)}};var S=class{constructor(e,t){this.http=e;this.storeId=t}async loadOffer(e){return(await this.http.get(`/api/v1/checkout-offers/${e}`,{params:{storeId:this.storeId}})).offer}async listOffers(e){return(await this.http.get("/api/v1/checkout-offers",{params:{storeId:this.storeId,type:e==null?void 0:e.type}})).offers}async acceptOffer(e){return this.http.post("/api/v1/checkout-offers/accept",{offerId:e.offerId,checkoutSessionId:e.checkoutSessionId,storeId:this.storeId,paymentInstrumentId:e.paymentInstrumentId})}async declineOffer(e){return this.http.post("/api/v1/checkout-offers/decline",{offerId:e.offerId,checkoutSessionId:e.checkoutSessionId,storeId:this.storeId})}async listOrderBumps(e){return(await this.http.get("/api/v1/checkout-offers",{params:{storeId:this.storeId,checkoutSessionId:e,type:"orderbump"}})).offers}async toggleOrderBump(e){await this.http.post(`/api/v1/checkout-sessions/${e.checkoutSessionId}/order-bumps`,{offerId:e.offerId,selected:e.selected})}};var b=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 R=class{constructor(e,t){this.http=e;this.storeId=t}async getProducts(e){var s,i;let t={storeId:this.storeId,includeVariants:!0,includePrices:!0};return(s=e==null?void 0:e.productIds)!=null&&s.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 A=class{constructor(e){let t=e.environment??"production",n=g.resolveBaseUrl(t,e.baseUrl);this.config={...e,environment:t,baseUrl:n,timeout:e.timeout??3e4},this.http=new g({baseUrl:n,timeout:this.config.timeout,apiKey:e.apiKey,getToken:()=>this._sessionToken});let s=i=>{this._sessionToken=i};this.checkout=new P(this.http,this.config.storeId,s),this.payment=new C(this.http,this.config.storeId,t),this.analytics=new T(this.http,this.config.storeId),this.offers=new S(this.http,this.config.storeId),this.customer=new b(this.http,this.config.storeId),this.catalog=new R(this.http,this.config.storeId)}setSessionToken(e){this._sessionToken=e}};function H(o){return new A(o)}return J(K);})();
|
|
7
7
|
if(typeof window!=="undefined"&&TagadaHeadlessBundle){ window.TagadaHeadless=TagadaHeadlessBundle; window.TagadaHeadless.create=TagadaHeadlessBundle.createHeadlessClient;}
|
|
8
8
|
//# sourceMappingURL=tagada-headless.min.js.map
|