@tagadapay/headless-sdk 1.1.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/core/client.d.ts +2 -5
- package/dist/core/client.d.ts.map +1 -1
- package/dist/core/client.js +1 -3
- package/dist/core/client.js.map +1 -1
- package/dist/core/index.d.ts +1 -2
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js +0 -1
- package/dist/core/index.js.map +1 -1
- 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/modules/offers.d.ts +64 -23
- package/dist/core/modules/offers.d.ts.map +1 -1
- package/dist/core/modules/offers.js +70 -33
- package/dist/core/modules/offers.js.map +1 -1
- package/dist/core/types.d.ts +26 -16
- package/dist/core/types.d.ts.map +1 -1
- 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/hooks/useOffers.d.ts +63 -22
- package/dist/react/hooks/useOffers.d.ts.map +1 -1
- package/dist/react/hooks/useOffers.js +36 -52
- package/dist/react/hooks/useOffers.js.map +1 -1
- package/dist/react/index.d.ts +1 -3
- package/dist/react/index.d.ts.map +1 -1
- package/dist/react/index.js +0 -1
- 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 +127 -311
- package/dist/tagada-headless.min.js +2 -2
- package/dist/tagada-headless.min.js.map +4 -4
- package/package.json +3 -3
- package/dist/core/modules/analytics.d.ts +0 -79
- package/dist/core/modules/analytics.d.ts.map +0 -1
- package/dist/core/modules/analytics.js +0 -265
- package/dist/core/modules/analytics.js.map +0 -1
- package/dist/react/hooks/useAnalytics.d.ts +0 -59
- package/dist/react/hooks/useAnalytics.d.ts.map +0 -1
- package/dist/react/hooks/useAnalytics.js +0 -49
- package/dist/react/hooks/useAnalytics.js.map +0 -1
package/dist/tagada-headless.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @tagadapay/headless-sdk v1.
|
|
2
|
+
* @tagadapay/headless-sdk v1.2.0
|
|
3
3
|
* Headless checkout, payments, analytics, and CRM
|
|
4
4
|
* @license MIT
|
|
5
5
|
*/
|
|
@@ -43,7 +43,6 @@ var TagadaHeadlessBundle = (() => {
|
|
|
43
43
|
// src/core/index.ts
|
|
44
44
|
var core_exports = {};
|
|
45
45
|
__export(core_exports, {
|
|
46
|
-
AnalyticsModule: () => AnalyticsModule,
|
|
47
46
|
CatalogModule: () => CatalogModule,
|
|
48
47
|
CheckoutModule: () => CheckoutModule,
|
|
49
48
|
CustomerModule: () => CustomerModule,
|
|
@@ -296,40 +295,80 @@ var TagadaHeadlessBundle = (() => {
|
|
|
296
295
|
/** Replace the cart items for an existing session. */
|
|
297
296
|
async updateCart(sessionId, items) {
|
|
298
297
|
return this.http.post(
|
|
299
|
-
`/api/v1/checkout-sessions/${sessionId}/items`,
|
|
298
|
+
`/api/v1/checkout-sessions/${sessionId}/line-items`,
|
|
300
299
|
{ items },
|
|
301
300
|
{ token: this.sessionToken }
|
|
302
301
|
);
|
|
303
302
|
}
|
|
304
|
-
/**
|
|
303
|
+
/**
|
|
304
|
+
* Update customer + address information on the session.
|
|
305
|
+
* Uses the combined endpoint with `partial: true` so missing fields are tolerated.
|
|
306
|
+
*/
|
|
305
307
|
async updateCustomer(sessionId, customer) {
|
|
306
|
-
|
|
307
|
-
`/api/v1/checkout-sessions/${sessionId}/customer`,
|
|
308
|
-
{
|
|
308
|
+
await this.http.post(
|
|
309
|
+
`/api/v1/checkout-sessions/${sessionId}/customer-and-session-info`,
|
|
310
|
+
{
|
|
311
|
+
checkoutSessionId: sessionId,
|
|
312
|
+
partial: true,
|
|
313
|
+
customerData: {
|
|
314
|
+
email: customer.email
|
|
315
|
+
},
|
|
316
|
+
shippingAddress: {
|
|
317
|
+
firstName: customer.firstName,
|
|
318
|
+
lastName: customer.lastName,
|
|
319
|
+
phone: customer.phone
|
|
320
|
+
},
|
|
321
|
+
billingAddress: {},
|
|
322
|
+
differentBillingAddress: false
|
|
323
|
+
},
|
|
309
324
|
{ token: this.sessionToken }
|
|
310
325
|
);
|
|
311
326
|
}
|
|
312
|
-
/**
|
|
327
|
+
/**
|
|
328
|
+
* Update shipping and/or billing address on the session.
|
|
329
|
+
*
|
|
330
|
+
* Address fields use the API's naming: `address1`, `postal`, etc.
|
|
331
|
+
*/
|
|
313
332
|
async updateAddress(sessionId, addresses) {
|
|
314
|
-
|
|
333
|
+
const mapAddress = (a) => {
|
|
334
|
+
if (!a)
|
|
335
|
+
return void 0;
|
|
336
|
+
return {
|
|
337
|
+
address1: a.line1,
|
|
338
|
+
address2: a.line2,
|
|
339
|
+
city: a.city,
|
|
340
|
+
state: a.state,
|
|
341
|
+
postal: a.postalCode,
|
|
342
|
+
country: a.country
|
|
343
|
+
};
|
|
344
|
+
};
|
|
345
|
+
await this.http.post(
|
|
315
346
|
`/api/v1/checkout-sessions/${sessionId}/address`,
|
|
316
|
-
{
|
|
347
|
+
{
|
|
348
|
+
checkoutSessionId: sessionId,
|
|
349
|
+
data: {
|
|
350
|
+
shippingAddress: mapAddress(addresses.shippingAddress) ?? {},
|
|
351
|
+
billingAddress: mapAddress(addresses.billingAddress)
|
|
352
|
+
}
|
|
353
|
+
},
|
|
317
354
|
{ token: this.sessionToken }
|
|
318
355
|
);
|
|
319
356
|
}
|
|
320
357
|
/** Apply a promotion code to the session. */
|
|
321
358
|
async applyPromoCode(sessionId, code) {
|
|
322
|
-
|
|
323
|
-
`/api/v1/checkout-sessions/${sessionId}/
|
|
324
|
-
{ code },
|
|
359
|
+
await this.http.post(
|
|
360
|
+
`/api/v1/checkout-sessions/${sessionId}/promotions/apply`,
|
|
361
|
+
{ checkoutSessionId: sessionId, code },
|
|
325
362
|
{ token: this.sessionToken }
|
|
326
363
|
);
|
|
327
364
|
}
|
|
328
|
-
/** Remove the
|
|
329
|
-
async removePromoCode(sessionId) {
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
365
|
+
/** Remove a promotion from the session by promotion ID. */
|
|
366
|
+
async removePromoCode(sessionId, promotionId) {
|
|
367
|
+
const promoId = promotionId ?? "default";
|
|
368
|
+
await this.http.delete(
|
|
369
|
+
`/api/v1/checkout-sessions/${sessionId}/promotions/${promoId}`,
|
|
370
|
+
{ token: this.sessionToken }
|
|
371
|
+
);
|
|
333
372
|
}
|
|
334
373
|
/** Fetch available shipping rates for the session's address. */
|
|
335
374
|
async getShippingRates(sessionId) {
|
|
@@ -337,13 +376,13 @@ var TagadaHeadlessBundle = (() => {
|
|
|
337
376
|
`/api/v1/checkout-sessions/${sessionId}/shipping-rates`,
|
|
338
377
|
{ token: this.sessionToken }
|
|
339
378
|
);
|
|
340
|
-
return res.rates;
|
|
379
|
+
return res.rates ?? [];
|
|
341
380
|
}
|
|
342
381
|
/** Select a shipping rate for the session. */
|
|
343
382
|
async selectShippingRate(sessionId, rateId) {
|
|
344
|
-
|
|
345
|
-
`/api/v1/checkout-sessions/${sessionId}/shipping-
|
|
346
|
-
{ rateId },
|
|
383
|
+
await this.http.post(
|
|
384
|
+
`/api/v1/checkout-sessions/${sessionId}/shipping-rate`,
|
|
385
|
+
{ checkoutSessionId: sessionId, shippingRateId: rateId },
|
|
347
386
|
{ token: this.sessionToken }
|
|
348
387
|
);
|
|
349
388
|
}
|
|
@@ -677,315 +716,93 @@ var TagadaHeadlessBundle = (() => {
|
|
|
677
716
|
}
|
|
678
717
|
};
|
|
679
718
|
|
|
680
|
-
// src/core/modules/
|
|
681
|
-
var
|
|
719
|
+
// src/core/modules/offers.ts
|
|
720
|
+
var OffersModule = class {
|
|
682
721
|
constructor(http, storeId) {
|
|
683
722
|
this.http = http;
|
|
684
723
|
this.storeId = storeId;
|
|
685
|
-
this.pixels = { loaded: false };
|
|
686
|
-
this.eventQueue = [];
|
|
687
|
-
this.dedupeSet = /* @__PURE__ */ new Set();
|
|
688
|
-
}
|
|
689
|
-
/**
|
|
690
|
-
* Initialize analytics by loading pixel configuration from the store.
|
|
691
|
-
* Call this once on page load. Events fired before init completes are queued.
|
|
692
|
-
*/
|
|
693
|
-
async init(opts) {
|
|
694
|
-
if (this.pixels.loaded)
|
|
695
|
-
return;
|
|
696
|
-
let config = opts == null ? void 0 : opts.pixelConfig;
|
|
697
|
-
if (!config) {
|
|
698
|
-
try {
|
|
699
|
-
const res = await this.http.get(
|
|
700
|
-
"/api/v1/checkout/config",
|
|
701
|
-
{ params: { storeId: this.storeId } }
|
|
702
|
-
);
|
|
703
|
-
config = res.pixels;
|
|
704
|
-
} catch {
|
|
705
|
-
}
|
|
706
|
-
}
|
|
707
|
-
this.pixels = { loaded: true, config };
|
|
708
|
-
if (typeof window !== "undefined" && config) {
|
|
709
|
-
this.loadPixelScripts(config);
|
|
710
|
-
}
|
|
711
|
-
this.flushQueue();
|
|
712
724
|
}
|
|
713
725
|
// ---------------------------------------------------------------------------
|
|
714
|
-
//
|
|
726
|
+
// Offer loading
|
|
715
727
|
// ---------------------------------------------------------------------------
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
trackViewContent(data) {
|
|
720
|
-
this.fireEvent("ViewContent", data);
|
|
721
|
-
}
|
|
722
|
-
trackAddToCart(data) {
|
|
723
|
-
this.fireEvent("AddToCart", data);
|
|
724
|
-
}
|
|
725
|
-
trackInitiateCheckout(data) {
|
|
726
|
-
this.fireEvent("InitiateCheckout", data ?? {});
|
|
727
|
-
}
|
|
728
|
-
trackAddPaymentInfo(data) {
|
|
729
|
-
this.fireEvent("AddPaymentInfo", data ?? {});
|
|
730
|
-
}
|
|
731
|
-
trackPurchase(data) {
|
|
732
|
-
this.fireEvent("Purchase", data, true);
|
|
728
|
+
/** Get a single offer by ID. */
|
|
729
|
+
async getOffer(offerId) {
|
|
730
|
+
return this.http.get(`/api/v1/offers/${offerId}`);
|
|
733
731
|
}
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
});
|
|
745
|
-
}
|
|
746
|
-
trackConversion(data) {
|
|
747
|
-
this.fireEvent("Conversion", data, true);
|
|
748
|
-
}
|
|
749
|
-
// ---------------------------------------------------------------------------
|
|
750
|
-
// Internals
|
|
751
|
-
// ---------------------------------------------------------------------------
|
|
752
|
-
fireEvent(event, data, dedupe = false) {
|
|
753
|
-
if (dedupe) {
|
|
754
|
-
const key = `${event}:${JSON.stringify(data)}`;
|
|
755
|
-
if (this.dedupeSet.has(key))
|
|
756
|
-
return;
|
|
757
|
-
this.dedupeSet.add(key);
|
|
758
|
-
}
|
|
759
|
-
if (!this.pixels.loaded) {
|
|
760
|
-
this.eventQueue.push({ event, data });
|
|
761
|
-
return;
|
|
762
|
-
}
|
|
763
|
-
this.sendToMeta(event, data);
|
|
764
|
-
this.sendToTikTok(event, data);
|
|
765
|
-
this.sendToSnapchat(event, data);
|
|
766
|
-
this.sendToGTM(event, data);
|
|
767
|
-
this.sendToGA(event, data);
|
|
768
|
-
}
|
|
769
|
-
flushQueue() {
|
|
770
|
-
const queue = [...this.eventQueue];
|
|
771
|
-
this.eventQueue = [];
|
|
772
|
-
for (const { event, data } of queue) {
|
|
773
|
-
this.fireEvent(event, data);
|
|
732
|
+
/** List offers for the current store. Optionally filter by type or a set of IDs. */
|
|
733
|
+
async listOffers(opts) {
|
|
734
|
+
var _a;
|
|
735
|
+
let url = `/api/v1/stores/${this.storeId}/offers`;
|
|
736
|
+
const queryParts = [];
|
|
737
|
+
if (opts == null ? void 0 : opts.type)
|
|
738
|
+
queryParts.push(`type=${encodeURIComponent(opts.type)}`);
|
|
739
|
+
if ((_a = opts == null ? void 0 : opts.ids) == null ? void 0 : _a.length) {
|
|
740
|
+
for (const id of opts.ids)
|
|
741
|
+
queryParts.push(`ids=${encodeURIComponent(id)}`);
|
|
774
742
|
}
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
// ---------------------------------------------------------------------------
|
|
780
|
-
// Pixel script loaders
|
|
781
|
-
// ---------------------------------------------------------------------------
|
|
782
|
-
loadPixelScripts(config) {
|
|
783
|
-
if (config.metaPixelId)
|
|
784
|
-
this.loadMetaPixel(config.metaPixelId);
|
|
785
|
-
if (config.tiktokPixelId)
|
|
786
|
-
this.loadTikTokPixel(config.tiktokPixelId);
|
|
787
|
-
if (config.snapchatPixelId)
|
|
788
|
-
this.loadSnapchatPixel(config.snapchatPixelId);
|
|
789
|
-
if (config.gtmId)
|
|
790
|
-
this.loadGTM(config.gtmId);
|
|
791
|
-
if (config.gaId)
|
|
792
|
-
this.loadGA(config.gaId);
|
|
793
|
-
}
|
|
794
|
-
loadMetaPixel(pixelId) {
|
|
795
|
-
if (typeof window === "undefined")
|
|
796
|
-
return;
|
|
797
|
-
const w = window;
|
|
798
|
-
if (w.fbq)
|
|
799
|
-
return;
|
|
800
|
-
const n = w.fbq = function(...args) {
|
|
801
|
-
n.callMethod ? n.callMethod(...args) : n.queue.push(args);
|
|
802
|
-
};
|
|
803
|
-
n.queue = [];
|
|
804
|
-
n.loaded = true;
|
|
805
|
-
n.version = "2.0";
|
|
806
|
-
this.injectScript("https://connect.facebook.net/en_US/fbevents.js");
|
|
807
|
-
w.fbq("init", pixelId);
|
|
808
|
-
}
|
|
809
|
-
loadTikTokPixel(pixelId) {
|
|
810
|
-
if (typeof window === "undefined")
|
|
811
|
-
return;
|
|
812
|
-
const w = window;
|
|
813
|
-
if (w.ttq)
|
|
814
|
-
return;
|
|
815
|
-
const ttq = {};
|
|
816
|
-
ttq.methods = ["page", "track", "identify", "instances", "debug", "on", "off", "once", "ready", "alias", "group", "enableCookie", "disableCookie"];
|
|
817
|
-
ttq.setAndDefer = function(t, e) {
|
|
818
|
-
t[e] = function(...args) {
|
|
819
|
-
t.push([e, ...args]);
|
|
820
|
-
};
|
|
821
|
-
};
|
|
822
|
-
w.ttq = ttq;
|
|
823
|
-
this.injectScript("https://analytics.tiktok.com/i18n/pixel/events.js?sdkid=" + pixelId);
|
|
824
|
-
}
|
|
825
|
-
loadSnapchatPixel(pixelId) {
|
|
826
|
-
if (typeof window === "undefined")
|
|
827
|
-
return;
|
|
828
|
-
const w = window;
|
|
829
|
-
if (w.snaptr)
|
|
830
|
-
return;
|
|
831
|
-
w.snaptr = function(...args) {
|
|
832
|
-
w.snaptr.handleRequest ? w.snaptr.handleRequest(...args) : w.snaptr.queue.push(args);
|
|
833
|
-
};
|
|
834
|
-
w.snaptr.queue = [];
|
|
835
|
-
this.injectScript("https://sc-static.net/scevent.min.js");
|
|
836
|
-
w.snaptr("init", pixelId);
|
|
837
|
-
}
|
|
838
|
-
loadGTM(gtmId) {
|
|
839
|
-
if (typeof window === "undefined")
|
|
840
|
-
return;
|
|
841
|
-
const w = window;
|
|
842
|
-
w.dataLayer = w.dataLayer ?? [];
|
|
843
|
-
w.dataLayer.push({ "gtm.start": Date.now(), event: "gtm.js" });
|
|
844
|
-
this.injectScript(`https://www.googletagmanager.com/gtm.js?id=${gtmId}`);
|
|
845
|
-
}
|
|
846
|
-
loadGA(gaId) {
|
|
847
|
-
if (typeof window === "undefined")
|
|
848
|
-
return;
|
|
849
|
-
this.injectScript(`https://www.googletagmanager.com/gtag/js?id=${gaId}`);
|
|
850
|
-
const w = window;
|
|
851
|
-
w.dataLayer = w.dataLayer ?? [];
|
|
852
|
-
w.gtag = function(...args) {
|
|
853
|
-
w.dataLayer.push(args);
|
|
854
|
-
};
|
|
855
|
-
w.gtag("js", /* @__PURE__ */ new Date());
|
|
856
|
-
w.gtag("config", gaId);
|
|
857
|
-
}
|
|
858
|
-
injectScript(src) {
|
|
859
|
-
if (typeof document === "undefined")
|
|
860
|
-
return;
|
|
861
|
-
const s = document.createElement("script");
|
|
862
|
-
s.async = true;
|
|
863
|
-
s.src = src;
|
|
864
|
-
document.head.appendChild(s);
|
|
743
|
+
if (queryParts.length)
|
|
744
|
+
url += `?${queryParts.join("&")}`;
|
|
745
|
+
const res = await this.http.get(url);
|
|
746
|
+
return res.offers ?? [];
|
|
865
747
|
}
|
|
866
748
|
// ---------------------------------------------------------------------------
|
|
867
|
-
//
|
|
749
|
+
// Preview & pay (one-click upsell flow from plugin-sdk)
|
|
868
750
|
// ---------------------------------------------------------------------------
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
ViewContent: "ViewContent",
|
|
877
|
-
AddToCart: "AddToCart",
|
|
878
|
-
InitiateCheckout: "InitiateCheckout",
|
|
879
|
-
AddPaymentInfo: "AddPaymentInfo",
|
|
880
|
-
Purchase: "Purchase"
|
|
881
|
-
};
|
|
882
|
-
const mapped = metaEventMap[event];
|
|
883
|
-
if (mapped) {
|
|
884
|
-
fbq("track", mapped, data);
|
|
885
|
-
} else {
|
|
886
|
-
fbq("trackCustom", event, data);
|
|
887
|
-
}
|
|
888
|
-
}
|
|
889
|
-
sendToTikTok(event, data) {
|
|
890
|
-
var _a, _b;
|
|
891
|
-
const w = typeof window !== "undefined" ? window : null;
|
|
892
|
-
const ttq = w == null ? void 0 : w.ttq;
|
|
893
|
-
if (!ttq)
|
|
894
|
-
return;
|
|
895
|
-
if (event === "PageView") {
|
|
896
|
-
(_a = ttq.page) == null ? void 0 : _a.call(ttq);
|
|
897
|
-
} else {
|
|
898
|
-
(_b = ttq.track) == null ? void 0 : _b.call(ttq, event, data);
|
|
899
|
-
}
|
|
900
|
-
}
|
|
901
|
-
sendToSnapchat(event, data) {
|
|
902
|
-
const w = typeof window !== "undefined" ? window : null;
|
|
903
|
-
const snaptr = w == null ? void 0 : w.snaptr;
|
|
904
|
-
if (!snaptr)
|
|
905
|
-
return;
|
|
906
|
-
const snapEventMap = {
|
|
907
|
-
PageView: "PAGE_VIEW",
|
|
908
|
-
ViewContent: "VIEW_CONTENT",
|
|
909
|
-
AddToCart: "ADD_CART",
|
|
910
|
-
InitiateCheckout: "START_CHECKOUT",
|
|
911
|
-
Purchase: "PURCHASE"
|
|
912
|
-
};
|
|
913
|
-
const mapped = snapEventMap[event];
|
|
914
|
-
if (mapped)
|
|
915
|
-
snaptr("track", mapped, data);
|
|
916
|
-
}
|
|
917
|
-
sendToGTM(event, data) {
|
|
918
|
-
const w = typeof window !== "undefined" ? window : null;
|
|
919
|
-
const dataLayer = w == null ? void 0 : w.dataLayer;
|
|
920
|
-
if (!dataLayer)
|
|
921
|
-
return;
|
|
922
|
-
dataLayer.push({ event, ...data });
|
|
923
|
-
}
|
|
924
|
-
sendToGA(event, data) {
|
|
925
|
-
const w = typeof window !== "undefined" ? window : null;
|
|
926
|
-
const gtag = w == null ? void 0 : w.gtag;
|
|
927
|
-
if (!gtag)
|
|
928
|
-
return;
|
|
929
|
-
gtag("event", event, data);
|
|
930
|
-
}
|
|
931
|
-
};
|
|
932
|
-
|
|
933
|
-
// src/core/modules/offers.ts
|
|
934
|
-
var OffersModule = class {
|
|
935
|
-
constructor(http, storeId) {
|
|
936
|
-
this.http = http;
|
|
937
|
-
this.storeId = storeId;
|
|
938
|
-
}
|
|
939
|
-
/** Load offer details by ID. */
|
|
940
|
-
async loadOffer(offerId) {
|
|
941
|
-
const res = await this.http.get(
|
|
942
|
-
`/api/v1/checkout-offers/${offerId}`,
|
|
943
|
-
{ params: { storeId: this.storeId } }
|
|
944
|
-
);
|
|
945
|
-
return res.offer;
|
|
946
|
-
}
|
|
947
|
-
/** List all offers for the store. */
|
|
948
|
-
async listOffers(opts) {
|
|
949
|
-
const res = await this.http.get(
|
|
950
|
-
"/api/v1/checkout-offers",
|
|
951
|
-
{ params: { storeId: this.storeId, type: opts == null ? void 0 : opts.type } }
|
|
952
|
-
);
|
|
953
|
-
return res.offers;
|
|
751
|
+
/** Preview offer pricing. Returns line items with amounts and totals. */
|
|
752
|
+
async previewOffer(opts) {
|
|
753
|
+
return this.http.post(`/api/v1/offers/${opts.offerId}/preview`, {
|
|
754
|
+
offerId: opts.offerId,
|
|
755
|
+
currency: opts.currency ?? "",
|
|
756
|
+
lineItems: opts.lineItems
|
|
757
|
+
});
|
|
954
758
|
}
|
|
955
759
|
/**
|
|
956
|
-
*
|
|
957
|
-
*
|
|
760
|
+
* Pay a previously previewed offer (one-click charge).
|
|
761
|
+
* Used after a main order so the stored payment instrument is reused.
|
|
958
762
|
*/
|
|
959
|
-
async
|
|
960
|
-
return this.http.post(
|
|
763
|
+
async payPreviewedOffer(opts) {
|
|
764
|
+
return this.http.post(`/api/v1/offers/${opts.offerId}/pay-preview`, {
|
|
961
765
|
offerId: opts.offerId,
|
|
962
|
-
|
|
963
|
-
|
|
766
|
+
currency: opts.currency ?? "",
|
|
767
|
+
lineItems: opts.lineItems,
|
|
768
|
+
returnUrl: opts.returnUrl ?? (typeof window !== "undefined" ? window.location.href : ""),
|
|
769
|
+
mainOrderId: opts.mainOrderId,
|
|
964
770
|
paymentInstrumentId: opts.paymentInstrumentId
|
|
965
771
|
});
|
|
966
772
|
}
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
773
|
+
// ---------------------------------------------------------------------------
|
|
774
|
+
// Order bumps (checkout-session scoped)
|
|
775
|
+
// ---------------------------------------------------------------------------
|
|
776
|
+
/** Toggle an order bump on/off within a checkout session. */
|
|
777
|
+
async toggleOrderBump(opts) {
|
|
778
|
+
return this.http.post(
|
|
779
|
+
`/api/v1/checkout-sessions/${opts.checkoutSessionId}/toggle-order-bump`,
|
|
780
|
+
{
|
|
781
|
+
orderBumpOfferId: opts.orderBumpOfferId,
|
|
782
|
+
selected: opts.selected
|
|
783
|
+
}
|
|
784
|
+
);
|
|
974
785
|
}
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
786
|
+
// ---------------------------------------------------------------------------
|
|
787
|
+
// Post-purchase offers (order-scoped)
|
|
788
|
+
// ---------------------------------------------------------------------------
|
|
789
|
+
/** List post-purchase offers for an order. */
|
|
790
|
+
async listPostPurchaseOffers(orderId) {
|
|
791
|
+
const res = await this.http.get(`/api/v1/post-purchase/${orderId}/offers`);
|
|
792
|
+
return Array.isArray(res) ? res : [];
|
|
793
|
+
}
|
|
794
|
+
/** Accept a post-purchase offer. */
|
|
795
|
+
async acceptPostPurchaseOffer(opts) {
|
|
796
|
+
return this.http.post(
|
|
797
|
+
`/api/v1/orders/${opts.orderId}/post-purchase-offers/${opts.offerId}/accept`,
|
|
798
|
+
{ items: opts.items ?? [] }
|
|
980
799
|
);
|
|
981
|
-
return res.offers;
|
|
982
800
|
}
|
|
983
|
-
/**
|
|
984
|
-
async
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
});
|
|
801
|
+
/** Decline a post-purchase offer. */
|
|
802
|
+
async declinePostPurchaseOffer(opts) {
|
|
803
|
+
return this.http.post(
|
|
804
|
+
`/api/v1/orders/${opts.orderId}/post-purchase-offers/${opts.offerId}/decline`
|
|
805
|
+
);
|
|
989
806
|
}
|
|
990
807
|
};
|
|
991
808
|
|
|
@@ -1115,7 +932,6 @@ var TagadaHeadlessBundle = (() => {
|
|
|
1115
932
|
};
|
|
1116
933
|
this.checkout = new CheckoutModule(this.http, this.config.storeId, setToken);
|
|
1117
934
|
this.payment = new PaymentModule(this.http, this.config.storeId, environment);
|
|
1118
|
-
this.analytics = new AnalyticsModule(this.http, this.config.storeId);
|
|
1119
935
|
this.offers = new OffersModule(this.http, this.config.storeId);
|
|
1120
936
|
this.customer = new CustomerModule(this.http, this.config.storeId);
|
|
1121
937
|
this.catalog = new CatalogModule(this.http, this.config.storeId);
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @tagadapay/headless-sdk v1.
|
|
2
|
+
* @tagadapay/headless-sdk v1.2.0
|
|
3
3
|
* Headless checkout, payments, analytics, and CRM
|
|
4
4
|
* @license MIT
|
|
5
5
|
*/
|
|
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})},H=(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)):{},H(e||!o||!o.__esModule?O(t,"default",{value:o,enumerable:!0}):t,o)),J=o=>H(O({},"__esModule",{value:!0}),o);var K={};V(K,{AnalyticsModule:()=>T,CatalogModule:()=>R,CheckoutModule:()=>P,CustomerModule:()=>b,HeadlessClient:()=>E,HttpClient:()=>g,OffersModule:()=>S,PaymentModule:()=>C,TagadaAuthError:()=>k,TagadaError:()=>u,TagadaNetworkError:()=>l,TagadaNotFoundError:()=>I,TagadaPaymentError:()=>M,TagadaRateLimitError:()=>v,TagadaValidationError:()=>w,createHeadlessClient:()=>j});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[N,q]of Object.entries(r))q!==void 0&&d.set(N,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 A=new AbortController,f=setTimeout(()=>A.abort(),this.timeout);try{let d=await fetch(p,{method:n,headers:m,body:s!=null?JSON.stringify(s):void 0,signal:c??A.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}/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)??{},A=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:A.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 E=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 j(o){return new E(o)}return J(K);})();
|
|
6
|
+
"use strict";var TagadaHeadlessBundle=(()=>{var H=Object.create;var x=Object.defineProperty;var j=Object.getOwnPropertyDescriptor;var _=Object.getOwnPropertyNames;var D=Object.getPrototypeOf,F=Object.prototype.hasOwnProperty;var z=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var L=(n,e)=>{for(var t in e)x(n,t,{get:e[t],enumerable:!0})},M=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of _(e))!F.call(n,s)&&s!==t&&x(n,s,{get:()=>e[s],enumerable:!(r=j(e,s))||r.enumerable});return n};var B=(n,e,t)=>(t=n!=null?H(D(n)):{},M(e||!n||!n.__esModule?x(t,"default",{value:n,enumerable:!0}):t,n)),J=n=>M(x({},"__esModule",{value:!0}),n);var K={};L(K,{CatalogModule:()=>S,CheckoutModule:()=>v,CustomerModule:()=>b,HeadlessClient:()=>R,HttpClient:()=>g,OffersModule:()=>T,PaymentModule:()=>C,TagadaAuthError:()=>I,TagadaError:()=>c,TagadaNetworkError:()=>h,TagadaNotFoundError:()=>w,TagadaPaymentError:()=>E,TagadaRateLimitError:()=>P,TagadaValidationError:()=>k,createHeadlessClient:()=>N});var c=class extends Error{constructor(e,t,r,s){super(e),this.name="TagadaError",this.code=t,this.statusCode=r,this.details=s}},I=class extends c{constructor(e="Authentication failed. Check your API key or checkout token."){super(e,"auth_error",401),this.name="TagadaAuthError"}},k=class extends c{constructor(e,t=[]){super(e,"validation_error",422,{errors:t}),this.name="TagadaValidationError",this.errors=t}},w=class extends c{constructor(e,t){super(`${e} "${t}" not found.`,"not_found",404),this.name="TagadaNotFoundError"}},P=class extends c{constructor(e=1e3){super(`Rate limited. Retry after ${e}ms.`,"rate_limit",429),this.name="TagadaRateLimitError",this.retryAfterMs=e}},E=class extends c{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}},h=class extends c{constructor(e="Network request failed. Check your connection."){super(e,"network_error"),this.name="TagadaNetworkError"}};var q={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??q[e]??q.production}async request(e,t={}){var l;let{method:r="GET",body:s,headers:i={},params:o,token:a,signal:u}=t,m=`${this.baseUrl}${e}`;if(o){let d=new URLSearchParams;for(let[U,$]of Object.entries(o))$!==void 0&&d.set(U,String($));let O=d.toString();O&&(m+=`?${O}`)}let p={"Content-Type":"application/json",...i},y=a??this.apiKey??((l=this.getToken)==null?void 0:l.call(this));y&&(p["x-cms-token"]=y);let A=new AbortController,f=setTimeout(()=>A.abort(),this.timeout);try{let d=await fetch(m,{method:r,headers:p,body:s!=null?JSON.stringify(s):void 0,signal:u??A.signal});if(clearTimeout(f),d.ok){let O=await d.text();return O?JSON.parse(O):{}}throw await this.handleErrorResponse(d,e),new c("Unexpected error","unknown",d.status)}catch(d){throw clearTimeout(f),d instanceof c?d:d instanceof DOMException&&d.name==="AbortError"?new h(`Request to ${e} timed out after ${this.timeout}ms.`):new h(d instanceof Error?d.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 s=r.message??r.error??`Request failed: ${e.status} ${e.statusText} on ${t}`;switch(e.status){case 401:case 403:throw new I(s);case 404:throw new w(t,"");case 422:{let i=Array.isArray(r.errors)?r.errors:[];throw new k(s,i)}case 429:{let i=Number(e.headers.get("Retry-After")??"1")*1e3;throw new P(i)}default:throw new c(s,"api_error",e.status,r)}}};var v=class{constructor(e,t,r){this.http=e;this.storeId=t;this.onTokenChange=r}async loadSession(e,t){var s;t&&(this.sessionToken=t,(s=this.onTokenChange)==null||s.call(this,t));let r=await this.http.get(`/api/v1/checkout-sessions/${e}/v2`,{params:{skipAsyncWait:"false"},token:this.sessionToken});return this.normalizeSession(r)}async createSession(e){var a;let t=e.items.map(u=>({variantId:u.variantId,priceId:u.priceId,quantity:u.quantity})),r={storeId:this.storeId,lineItems:t};e.currency&&(r.currency=e.currency),e.returnUrl&&(r.returnUrl=e.returnUrl),e.customerEmail&&(r.customer={email:e.customerEmail,firstName:e.customerFirstName,lastName:e.customerLastName,currency:e.currency});let s=await this.http.post("/api/v1/checkout/session/init",r),o=new URL(s.checkoutUrl).searchParams.get("token")??"";return this.sessionToken=o,o&&((a=this.onTokenChange)==null||a.call(this,o)),{checkoutUrl:s.checkoutUrl,checkoutToken:s.checkoutToken,sessionToken:o,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 r=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:r(t.shippingAddress)??{},billingAddress:r(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 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??[]}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,r=t.orderSummaries??[],s=e.summary??t.summary??r[0]??{},i=t.sessionLineItems??[],o=t.customer,a=i.map(m=>{let p=m.price,y=(p==null?void 0:p.variant)??{},A=y.product??{},f=(p==null?void 0:p.currencyOptions)??{},l=f.USD??f[Object.keys(f)[0]];return{id:m.id,variantId:m.variantId,priceId:m.priceId,productName:A.name??"",variantName:y.name??"",quantity:m.quantity??1,unitAmount:(l==null?void 0:l.amount)??0,totalAmount:((l==null?void 0:l.amount)??0)*(m.quantity??1),currency:t.selectedPresentmentCurrency??"USD",imageUrl:y.imageUrl??""}}),u=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??u.reduce((m,p)=>m+(p.amount??0),0),currency:s.currency??t.selectedPresentmentCurrency??"USD"},customer:o?{id:o.id,email:o.email,firstName:o.firstName,lastName:o.lastName}:void 0,shippingAddress:t.shippingAddress,billingAddress:t.billingAddress,metadata:t.metadata}}};var C=class{constructor(e,t,r){this.http=e;this.storeId=t;this.environment=r}async getPaymentSetup(e){let t=await this.http.get("/api/v1/payment-methods",{params:{checkoutSessionId:e}}),r={};for(let s of t.methods??[]){let i=s.provider?`${s.method}:${s.provider}`:s.method;r[i]=s}return r}async getExpressMethods(e){var s,i;let t=await this.getPaymentSetup(e),r={};for(let[,o]of Object.entries(t)){if(!o.enabled||!o.express)continue;let a=o.method,u={type:a,available:!0,processorId:o.processorId,publishableKey:o.publishableKey,metadata:o.metadata};if(a==="apple_pay"||o.type==="apple_pay"){let m=typeof window<"u"&&"ApplePaySession"in window&&((i=(s=window.ApplePaySession)==null?void 0:s.canMakePayments)==null?void 0:i.call(s));r.applePay={...u,available:!!m}}else a==="google_pay"||o.type==="google_pay"?r.googlePay=u:a==="paypal"?r.paypal=u:a==="klarna"||a==="klarna_express"?r.klarna=u:a==="link"&&(r.link=u)}return r}async getStoreConfig(){let e=await this.http.get("/api/v1/checkout/config",{params:{storeId:this.storeId}});return e.config??e}async getEnabledMethods(e){let t=await this.getPaymentSetup(e);return Object.entries(t).filter(([,r])=>r.enabled).map(([r])=>r)}async tokenizeCard(e){let t=await this.loadCoreJs(),r=new t.Tokenizer({environment:this.environment});await r.initialize();let s={cardNumber:e.cardNumber,expiryDate:e.expiryDate,cvc:e.cvc};e.cardholderName&&(s.cardholderName=e.cardholderName);let[i,o]=await Promise.all([r.tokenizeCard(s),r.tokenizeCardRaw(s)]);return{tagadaToken:i,rawToken:o}}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(),r=new t.Tokenizer({environment:this.environment});await r.initialize();let{tagadaToken:s}=await r.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(),r=new t.Tokenizer({environment:this.environment});await r.initialize();let{tagadaToken:s}=await r.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 r=(t==null?void 0:t.intervalMs)??1500,s=(t==null?void 0:t.timeoutMs)??6e4,i=Date.now();for(;Date.now()-i<s;){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 ${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}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 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 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 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 S=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 R=class{constructor(e){let t=e.environment??"production",r=g.resolveBaseUrl(t,e.baseUrl);this.config={...e,environment:t,baseUrl:r,timeout:e.timeout??3e4},this.http=new g({baseUrl:r,timeout:this.config.timeout,apiKey:e.apiKey,getToken:()=>this._sessionToken});let s=i=>{this._sessionToken=i};this.checkout=new v(this.http,this.config.storeId,s),this.payment=new C(this.http,this.config.storeId,t),this.offers=new T(this.http,this.config.storeId),this.customer=new b(this.http,this.config.storeId),this.catalog=new S(this.http,this.config.storeId)}setSessionToken(e){this._sessionToken=e}};function N(n){return new R(n)}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
|