@blotoutio/providers-blotout-wallet-sdk 0.42.2 → 0.44.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/index.cjs.js CHANGED
@@ -1,18 +1,149 @@
1
1
  'use strict';
2
2
 
3
+ /**
4
+ * Returns whether A contains the entirety of B (A superset of B)
5
+ *
6
+ * A ⊇ B
7
+ */
8
+ const isSuperset = (a, b) => {
9
+ for (const item of b) {
10
+ if (!a.has(item)) {
11
+ return false;
12
+ }
13
+ }
14
+ return true;
15
+ };
16
+ /**
17
+ * Returns whether A is entirely contained within B (A subset of B)
18
+ *
19
+ * A ⊆ B
20
+ */
21
+ const isSubset = (a, b) => {
22
+ for (const item of a) {
23
+ if (!b.has(item)) {
24
+ return false;
25
+ }
26
+ }
27
+ return true;
28
+ };
29
+ /**
30
+ * Returns true when the two ets contain the same set of elements
31
+ *
32
+ * A = B
33
+ */
34
+ const areEquivalent = (a, b) => a.size == b.size && isSuperset(a, b) && isSubset(a, b);
35
+
36
+ const expand = (str) => str.split(',').flatMap((entry) => {
37
+ if (!entry.includes('-')) {
38
+ return entry;
39
+ }
40
+ const result = [];
41
+ const [start, end] = entry.split('-').map(Number);
42
+ for (let i = start; i <= end; i++) {
43
+ result.push(i.toString());
44
+ }
45
+ return result;
46
+ });
47
+ /**
48
+ * Exported from https://en.wikipedia.org/wiki/List_of_North_American_Numbering_Plan_area_codes
49
+ *
50
+ * In Dev Tools, select the `tbody` element containing the area codes and run the following code,
51
+ * replacing the emdash character with a simple endash:
52
+ *
53
+ * ```ts
54
+ * [...$0.querySelectorAll('td:first-child')]
55
+ * .filter(cell => cell.firstChild.nodeName != 'A')
56
+ * .map(cell => cell.textContent.trim()).join(',')
57
+ * ```
58
+ */
59
+ new Set([
60
+ ...expand('200,211,221,222,230,232,233,235,237-238,241,243,244,245,247,255,257,258-259,261,265,266,271,273,274,275,277,278,280,282,283,285-287,288,290-299'),
61
+ ...expand('300,311,322,324,327,328,333,335,338,342,344,348-349,353,355,356,357-359,362,366,369,370-379,381,382,383-384,387,388,389,390-399'),
62
+ ...expand('400,411,420,421-422,426-427,428,429,433,439,444,446,449,451-454,455,456,457,459,460,461-462,465,466,467,471,476,477,481-483,485-486,487,488,489,490-499'),
63
+ ...expand('511,532,535,536,537,538,542-543,545-547,549-550,552-554,555,556,558,560,565,568,569,576,578,583,589,590-599'),
64
+ ...expand('611,621,624,625,627,632,633,634-635,637-638,642-643,644,648,652-654,655,663,665,666,668,673-676,677,679,685,686,687,688,690-699'),
65
+ ...expand('711,722,723,729,733,735-736,739,741,744,745-746,748,749-751,752,755,756,759,761,764,766,768,776,777,783,788,789,790-799'),
66
+ ...expand('811,821,822,823-824,827,834,836,841-842,846,851,852-853,871,874-875,879,880-887,889,890-899'),
67
+ ...expand('911,921,922,923,924,926,927,932,933,935,942,944,946,950,953,955,957-958,960-969,974,975,976,977,981-982,987,988,990-999'),
68
+ ]);
69
+
3
70
  const packageName = 'blotoutWallet';
71
+ const customAttributes = {
72
+ '--bw-primary': { type: 'color', defaultValue: '#f25c2b' },
73
+ '--bw-secondary': { type: 'color', defaultValue: '#172a41' },
74
+ '--bw-button': { type: 'color', defaultValue: '#da2e3a' },
75
+ '--bw-foreground': { type: 'color', defaultValue: 'white' },
76
+ '--bw-input-border': { type: 'color', defaultValue: '#dbe2eb' },
77
+ '--bw-input-foreground': { type: 'color', defaultValue: '#172a41' },
78
+ '--bw-input-background': { type: 'color', defaultValue: 'white' },
79
+ '--bw-backdrop': { type: 'color', defaultValue: '#00000077' },
80
+ '--bw-z-index': { type: 'number', defaultValue: '9999' },
81
+ };
4
82
 
83
+ const canLog = () => {
84
+ try {
85
+ return localStorage.getItem('edgeTagDebug') === '1';
86
+ }
87
+ catch {
88
+ return false;
89
+ }
90
+ };
91
+ const logger = {
92
+ log: (...args) => {
93
+ if (canLog()) {
94
+ console.log(...args);
95
+ }
96
+ },
97
+ error: (...args) => {
98
+ if (canLog()) {
99
+ console.error(...args);
100
+ }
101
+ },
102
+ info: (...args) => {
103
+ if (canLog()) {
104
+ console.info(...args);
105
+ }
106
+ },
107
+ trace: (...args) => {
108
+ if (canLog()) {
109
+ console.trace(...args);
110
+ }
111
+ },
112
+ table: (...args) => {
113
+ if (canLog()) {
114
+ console.table(...args);
115
+ }
116
+ },
117
+ dir: (...args) => {
118
+ if (canLog()) {
119
+ console.dir(...args);
120
+ }
121
+ },
122
+ };
123
+
124
+ // eslint-disable-next-line @nx/enforce-module-boundaries
5
125
  class APIError extends Error {
6
126
  constructor(...args) {
7
127
  super(...args);
8
128
  }
9
129
  }
130
+ const getItemKey = (item) => `${item.productId}-${item.variantId}`;
131
+ const postMessageKey = 'blotoutWallet';
10
132
  class WalletAPI {
11
- constructor({ baseUrl, userId }) {
133
+ constructor({ baseUrl, userId, enabled }) {
12
134
  this.listeners = new Set();
13
135
  this._cart = { cartId: null, items: [], email: false };
136
+ this.onWindowMessage = (event) => {
137
+ var _a;
138
+ if (((_a = event.data) === null || _a === void 0 ? void 0 : _a.name) == postMessageKey) {
139
+ this.cart = event.data.cart;
140
+ }
141
+ };
14
142
  this.baseUrl = baseUrl;
15
143
  this.userId = userId;
144
+ this.enabled = enabled;
145
+ logger.info(`[Blotout Wallet] User is ${enabled ? 'enabled' : 'disabled'}`);
146
+ window.addEventListener('message', this.onWindowMessage);
16
147
  }
17
148
  getHeaders(json = false) {
18
149
  const headers = new Headers({
@@ -27,6 +158,7 @@ class WalletAPI {
27
158
  return `${this.baseUrl}/providers/blotoutWallet${path}`;
28
159
  }
29
160
  notify() {
161
+ var _a;
30
162
  for (const listener of this.listeners) {
31
163
  try {
32
164
  listener(this.cart);
@@ -35,13 +167,44 @@ class WalletAPI {
35
167
  console.error(err);
36
168
  }
37
169
  }
170
+ (_a = window.top) === null || _a === void 0 ? void 0 : _a.postMessage({ name: postMessageKey, cart: this.cart }, '*');
38
171
  }
39
172
  get cart() {
40
173
  return this._cart;
41
174
  }
42
175
  set cart(value) {
43
- this._cart = value;
44
- this.notify();
176
+ if (this.isCartUpdated(value)) {
177
+ this._cart = value;
178
+ this.notify();
179
+ }
180
+ }
181
+ isCartUpdated(value) {
182
+ if (value.cartId != this.cart.cartId ||
183
+ value.email != this.cart.email ||
184
+ value.items.length != this.cart.items.length) {
185
+ return true;
186
+ }
187
+ const newItemsMap = new Map(value.items.map((item) => [item.itemId, item]));
188
+ const newItemsKeys = new Set(newItemsMap.keys());
189
+ const currenItemsMap = new Map(this.cart.items.map((item) => [item.itemId, item]));
190
+ const currentItemsKeys = new Set(currenItemsMap.keys());
191
+ if (!areEquivalent(newItemsKeys, currentItemsKeys)) {
192
+ return true;
193
+ }
194
+ for (const [key, newItem] of newItemsMap) {
195
+ const currentItem = currenItemsMap.get(key);
196
+ if (newItem.amount != currentItem.amount ||
197
+ newItem.value != currentItem.value ||
198
+ newItem.name != currentItem.name ||
199
+ newItem.productId != currentItem.productId ||
200
+ newItem.variantId != currentItem.variantId) {
201
+ return true;
202
+ }
203
+ }
204
+ return false;
205
+ }
206
+ get segmentEnabled() {
207
+ return this.enabled;
45
208
  }
46
209
  subscribe(listener) {
47
210
  this.listeners.add(listener);
@@ -74,6 +237,26 @@ class WalletAPI {
74
237
  return (this.cart = await response.json());
75
238
  });
76
239
  }
240
+ removeItems(items) {
241
+ const cartLookup = new Map(this._cart.items.map((item) => [getItemKey(item), item]));
242
+ const itemLookup = new Map(items.map((item) => [getItemKey(item), item]));
243
+ const updatedCartItems = [];
244
+ for (const [itemKey, walletItem] of cartLookup.entries()) {
245
+ const itemToRemove = itemLookup.get(itemKey);
246
+ if (itemToRemove) {
247
+ // if the removed amount is equal or greater, we simply don't push the
248
+ // wallet item into the updated cart contents
249
+ if (walletItem.amount > itemToRemove.amount) {
250
+ walletItem.amount -= itemToRemove.amount;
251
+ updatedCartItems.push(walletItem);
252
+ }
253
+ }
254
+ else {
255
+ updatedCartItems.push(walletItem);
256
+ }
257
+ }
258
+ return this.setItems(updatedCartItems);
259
+ }
77
260
  setItems(items) {
78
261
  return fetch(this.getUrl('/items'), {
79
262
  method: 'PUT',
@@ -87,7 +270,7 @@ class WalletAPI {
87
270
  });
88
271
  }
89
272
  updateItem(item) {
90
- fetch(this.getUrl(`/items/${item.itemId}`), {
273
+ return fetch(this.getUrl(`/items/${item.itemId}`), {
91
274
  method: 'PUT',
92
275
  headers: this.getHeaders(true),
93
276
  body: JSON.stringify({
@@ -104,7 +287,7 @@ class WalletAPI {
104
287
  });
105
288
  }
106
289
  removeItem(itemId) {
107
- fetch(this.getUrl(`/items/${itemId}`), {
290
+ return fetch(this.getUrl(`/items/${itemId}`), {
108
291
  method: 'DELETE',
109
292
  headers: this.getHeaders(),
110
293
  }).then(async (response) => {
@@ -114,19 +297,6 @@ class WalletAPI {
114
297
  return (this.cart = await response.json());
115
298
  });
116
299
  }
117
- purchase(orderId) {
118
- return fetch(this.getUrl('/cart/purchase'), {
119
- method: 'POST',
120
- body: JSON.stringify({ orderId }),
121
- headers: this.getHeaders(true),
122
- }).then((response) => {
123
- if (!response.ok) {
124
- throw new APIError(`Could not mark purchase`, { cause: response });
125
- }
126
- this.cart = { cartId: null, email: this.cart.email, items: [] };
127
- this.notify();
128
- });
129
- }
130
300
  saveEmail(email) {
131
301
  return fetch(this.getUrl('/cart/email'), {
132
302
  method: 'POST',
@@ -273,15 +443,42 @@ const spring = 'linear(0, 0.009, 0.035 2.1%, 0.141, 0.281 6.7%, 0.723 12.9%, 0.9
273
443
 
274
444
  const cssVars = i$4 `
275
445
  :host {
276
- --primary: var(--bw-primary, #f25c2b);
277
- --secondary: var(--bw-secondary, #172a41);
278
- --button: var(--bw-primary, #da2e3a);
279
- --foreground: var(--bw-foreground, white);
280
- --input-border: var(--bw-input-border, #dbe2eb);
281
- --input-foreground: var(--wb-input-foreground, var(--secondary));
282
- --input-background: var(--wb-input-background, white);
283
- --backdrop: var(--wb-backdrop, #00000077);
284
- --z-index: var(--wb-z-index, 9999);
446
+ --primary: var(
447
+ --bw-primary,
448
+ ${r$5(customAttributes['--bw-primary'].defaultValue)}
449
+ );
450
+ --secondary: var(
451
+ --bw-secondary,
452
+ ${r$5(customAttributes['--bw-secondary'].defaultValue)}
453
+ );
454
+ --button: var(
455
+ --bw-button,
456
+ ${r$5(customAttributes['--bw-button'].defaultValue)}
457
+ );
458
+ --foreground: var(
459
+ --bw-foreground,
460
+ ${r$5(customAttributes['--bw-foreground'].defaultValue)}
461
+ );
462
+ --input-border: var(
463
+ --bw-input-border,
464
+ ${r$5(customAttributes['--bw-input-border'].defaultValue)}
465
+ );
466
+ --input-foreground: var(
467
+ --bw-input-foreground,
468
+ ${r$5(customAttributes['--bw-input-foreground'].defaultValue)}
469
+ );
470
+ --input-background: var(
471
+ --bw-input-background,
472
+ ${r$5(customAttributes['--bw-input-background'].defaultValue)}
473
+ );
474
+ --backdrop: var(
475
+ --bw-backdrop,
476
+ ${r$5(customAttributes['--bw-backdrop'].defaultValue)}
477
+ );
478
+ --z-index: var(
479
+ --bw-z-index,
480
+ ${r$5(customAttributes['--bw-z-index'].defaultValue)}
481
+ );
285
482
 
286
483
  --spring-easing: ${r$5(spring)};
287
484
 
@@ -420,22 +617,22 @@ const validPositions = new Set([
420
617
  'top-left',
421
618
  'top-right',
422
619
  ]);
423
- const getItemKey = (item) => `${item.productId}-${item.variantId}`;
424
620
  const wait = (timeout) => new Promise((res) => setTimeout(res, timeout));
425
621
  let BlotoutWallet = class BlotoutWallet extends s {
426
622
  constructor() {
427
623
  super(...arguments);
428
- this._buttonVisible = false;
429
- this._bannerVisible = false;
430
- this._hasItemsInWallet = false;
431
- this._hasEmail = false;
432
- this.onWalletUpdated = () => {
433
- const cart = this._walletApi.cart;
434
- this._hasItemsInWallet = cart.items.length > 0;
435
- if (this._hasItemsInWallet || !this._hasEmail) {
624
+ this.buttonVisible = false;
625
+ this.bannerVisible = false;
626
+ this.hasItemsInWallet = false;
627
+ this.hasEmail = false;
628
+ this.onWalletUpdated = (walletContent) => {
629
+ logger.log('[Blotout Wallet] Cart updated', walletContent);
630
+ this.hasItemsInWallet = walletContent.items.length > 0;
631
+ this.hasEmail = walletContent.email;
632
+ if (this.isSegmentEnabled && (this.hasItemsInWallet || !this.hasEmail)) {
436
633
  this.showButton();
437
634
  }
438
- else if (!this._hasItemsInWallet && this._hasEmail) {
635
+ else if (!this.hasItemsInWallet && this.hasEmail) {
439
636
  this.hideButton();
440
637
  }
441
638
  };
@@ -444,164 +641,152 @@ let BlotoutWallet = class BlotoutWallet extends s {
444
641
  ev.preventDefault();
445
642
  ev.stopPropagation();
446
643
  const modalAnimation = this.hideModal();
447
- const email = (_a = this._email) === null || _a === void 0 ? void 0 : _a.value.trim();
644
+ const email = (_a = this.email) === null || _a === void 0 ? void 0 : _a.value.trim();
448
645
  if (email) {
449
- this._walletApi.saveEmail(email)
646
+ this.walletApi.saveEmail(email)
450
647
  .then(() => {
451
- this._email.value = '';
452
- this._hasEmail = true;
648
+ this.email.value = '';
649
+ this.hasEmail = true;
453
650
  this.dispatchEvent(new CustomEvent('blotout-wallet-email-saved', { bubbles: true }));
454
651
  })
455
- .catch((err) => console.error(err));
652
+ .catch((err) => logger.error(err));
456
653
  }
457
- if (this._hasItemsInWallet) {
458
- this._storeApi.clearCart()
459
- .then(() => this._storeApi.addItems(this._walletApi.cart.items))
460
- .then(() => this._walletApi.restore())
654
+ if (this.hasItemsInWallet) {
655
+ this.storeApi.addItems(this.walletApi.cart.items)
656
+ .then(() => this.walletApi.restore())
461
657
  .then(() => {
462
658
  this.dispatchEvent(new CustomEvent('blotout-wallet-restored', { bubbles: true }));
463
659
  return modalAnimation.then(() => this.showRestorationBanner());
464
660
  })
465
- .catch((err) => console.error(err));
661
+ .then(() => wait(1000))
662
+ .then(() => (window.location.href = `${window.Shopify.routes.root}cart`))
663
+ .catch((err) => logger.error(err));
466
664
  }
467
665
  };
468
666
  this.showRestorationBanner = async () => {
469
- this._bannerVisible = true;
667
+ if (this.bannerVisible) {
668
+ return;
669
+ }
670
+ this.bannerVisible = true;
470
671
  await new Promise(requestAnimationFrame);
471
- await springInFromBottom(this._banner, '120%');
472
- await wait(5000);
473
- await springOutToBottom(this._banner, '120%');
474
- this._bannerVisible = false;
672
+ await springInFromBottom(this.banner, '120%');
673
+ };
674
+ this.hideRestorationBanner = async () => {
675
+ if (!this.bannerVisible) {
676
+ return;
677
+ }
678
+ await springOutToBottom(this.banner, '120%');
679
+ this.bannerVisible = false;
475
680
  };
476
681
  }
477
- get _storeApi() {
682
+ get storeApi() {
478
683
  var _a;
479
684
  return (_a = window[registryKey]) === null || _a === void 0 ? void 0 : _a.storeAPI;
480
685
  }
481
- get _walletApi() {
686
+ get walletApi() {
482
687
  var _a;
483
688
  return (_a = window[registryKey]) === null || _a === void 0 ? void 0 : _a.walletAPI;
484
689
  }
690
+ get isSegmentEnabled() {
691
+ var _a;
692
+ return (_a = this.walletApi) === null || _a === void 0 ? void 0 : _a.segmentEnabled;
693
+ }
485
694
  get _position() {
486
695
  return validPositions.has(this.position) ? this.position : 'bottom-left';
487
696
  }
488
697
  connectedCallback() {
489
698
  var _a;
490
699
  super.connectedCallback();
491
- this._unsubscribe = (_a = this._walletApi) === null || _a === void 0 ? void 0 : _a.subscribe(this.onWalletUpdated);
492
- this.syncItems().then((hasItemsSaved) => {
700
+ this.unsubscribe = (_a = this.walletApi) === null || _a === void 0 ? void 0 : _a.subscribe(this.onWalletUpdated);
701
+ this.syncItems().then(() => {
493
702
  this.dispatchEvent(new CustomEvent('blotout-wallet-loaded', { bubbles: true }));
494
- this._hasItemsInWallet = hasItemsSaved;
495
- if (this._hasItemsInWallet) {
496
- this.showButton();
497
- }
498
703
  });
499
704
  }
500
705
  disconnectedCallback() {
501
706
  var _a;
502
707
  super.disconnectedCallback();
503
- (_a = this._unsubscribe) === null || _a === void 0 ? void 0 : _a.call(this);
504
- this._unsubscribe = undefined;
708
+ (_a = this.unsubscribe) === null || _a === void 0 ? void 0 : _a.call(this);
709
+ this.unsubscribe = undefined;
505
710
  }
506
711
  async syncItems() {
507
- if (!this._walletApi || !this._storeApi) {
508
- console.error('The required APIs are not available');
712
+ if (!this.walletApi) {
713
+ logger.error('The required APIs are not available');
509
714
  return false;
510
715
  }
511
- const [savedCart, shopItems] = await Promise.all([
512
- this._walletApi.getCart(),
513
- this._storeApi.getCart(),
514
- ]);
515
- this._hasEmail = savedCart.email;
516
- const savedItemsLookup = new Map(savedCart.items.map((item) => [getItemKey(item), item]));
517
- const missingItems = [];
518
- for (const item of shopItems) {
519
- const walletItem = savedItemsLookup.get(getItemKey(item));
520
- if (!walletItem) {
521
- missingItems.push(item);
522
- }
523
- else if (walletItem.amount < item.amount) {
524
- missingItems.push({
525
- ...item,
526
- amount: item.amount - walletItem.amount,
527
- });
528
- }
529
- }
530
- if (missingItems.length > 0) {
531
- await this._walletApi.addItems(missingItems);
532
- }
716
+ const savedCart = await this.walletApi.getCart();
717
+ this.hasEmail = savedCart.email;
533
718
  return savedCart.items.length > 0;
534
719
  }
535
720
  async showButton() {
536
- if (this._buttonVisible) {
721
+ if (this.buttonVisible) {
537
722
  return;
538
723
  }
539
- this._buttonVisible = true;
724
+ this.buttonVisible = true;
540
725
  await new Promise(requestAnimationFrame).then(() => {
541
- switch (this._position) {
726
+ switch (this.position) {
542
727
  case 'top-left':
543
728
  case 'left':
544
729
  case 'bottom-left': {
545
- return springInFromLeft(this._button);
730
+ return springInFromLeft(this.button);
546
731
  }
547
732
  case 'top-right':
548
733
  case 'right':
549
734
  case 'bottom-right': {
550
- return springInFromRight(this._button);
735
+ return springInFromRight(this.button);
551
736
  }
552
737
  case 'bottom': {
553
- return springInFromBottom(this._button);
738
+ return springInFromBottom(this.button);
554
739
  }
555
740
  case 'top': {
556
- return springInFromTop(this._button);
741
+ return springInFromTop(this.button);
557
742
  }
558
743
  default: {
559
- return springInFromLeft(this._button);
744
+ return springInFromLeft(this.button);
560
745
  }
561
746
  }
562
747
  });
563
748
  this.dispatchEvent(new CustomEvent('blotout-wallet-shown', { bubbles: true }));
564
749
  }
565
750
  async hideButton() {
566
- if (!this._buttonVisible) {
751
+ if (!this.buttonVisible) {
567
752
  return;
568
753
  }
569
- switch (this._position) {
754
+ switch (this.position) {
570
755
  case 'top-left':
571
756
  case 'left':
572
757
  case 'bottom-left': {
573
- await springOutToLeft(this._button);
758
+ await springOutToLeft(this.button);
574
759
  break;
575
760
  }
576
761
  case 'top-right':
577
762
  case 'right':
578
763
  case 'bottom-right': {
579
- await springOutToRight(this._button);
764
+ await springOutToRight(this.button);
580
765
  break;
581
766
  }
582
767
  case 'bottom': {
583
- await springOutToBottom(this._button);
768
+ await springOutToBottom(this.button);
584
769
  break;
585
770
  }
586
771
  case 'top': {
587
- await springOutToTop(this._button);
772
+ await springOutToTop(this.button);
588
773
  break;
589
774
  }
590
775
  default: {
591
- await springOutToLeft(this._button);
776
+ await springOutToLeft(this.button);
592
777
  }
593
778
  }
594
- this._buttonVisible = false;
779
+ this.buttonVisible = false;
595
780
  this.dispatchEvent(new CustomEvent('blotout-wallet-hidden', { bubbles: true }));
596
781
  }
597
782
  async showModal() {
598
- this._dialog.showModal();
783
+ this.dialog.showModal();
599
784
  await new Promise(requestAnimationFrame);
600
- await fadeInDialog(this._dialog);
785
+ await fadeInDialog(this.dialog);
601
786
  }
602
787
  async hideModal() {
603
- await fadeOutToBottom(this._dialog);
604
- this._dialog.close();
788
+ await fadeOutToBottom(this.dialog);
789
+ this.dialog.close();
605
790
  }
606
791
  render() {
607
792
  return x `
@@ -609,7 +794,7 @@ let BlotoutWallet = class BlotoutWallet extends s {
609
794
  class="${e({
610
795
  cta: true,
611
796
  [this._position]: true,
612
- hidden: !this._buttonVisible,
797
+ hidden: !this.buttonVisible,
613
798
  })}"
614
799
  @click=${this.showModal}
615
800
  >
@@ -620,7 +805,7 @@ let BlotoutWallet = class BlotoutWallet extends s {
620
805
  <button class="dismiss" @click=${this.hideModal}>${cross()}</button>
621
806
  ${blotout({ class: 'logo' })}
622
807
  <form method="dialog" @submit=${this.onSubmit}>
623
- ${this._hasItemsInWallet
808
+ ${this.hasItemsInWallet
624
809
  ? x `<p>
625
810
  Hey! Your <strong>cart has expired!</strong><br />But we've got
626
811
  you covered. ${wink({ style: 'vertical-align:middle' })}
@@ -635,15 +820,15 @@ let BlotoutWallet = class BlotoutWallet extends s {
635
820
  type="email"
636
821
  name="email"
637
822
  placeholder="Enter your email ID"
638
- ?required=${!this._hasEmail}
823
+ ?required=${!this.hasEmail}
639
824
  style=${o({
640
- display: this._hasEmail ? 'none' : 'block',
825
+ display: this.hasEmail ? 'none' : 'block',
641
826
  })}
642
827
  />
643
828
  </p>
644
829
  <p>
645
830
  <button class="restore" type="submit">
646
- ${this._hasItemsInWallet ? 'Restore Cart' : 'Save Cart'}
831
+ ${this.hasItemsInWallet ? 'Restore Cart' : 'Save Cart'}
647
832
  </button>
648
833
  </p>
649
834
  </form>
@@ -651,7 +836,7 @@ let BlotoutWallet = class BlotoutWallet extends s {
651
836
 
652
837
  <div
653
838
  class="banner"
654
- style=${o({ display: this._bannerVisible ? '' : 'none' })}
839
+ style=${o({ display: this.bannerVisible ? '' : 'none' })}
655
840
  >
656
841
  ${blotout({
657
842
  class: 'logo',
@@ -754,7 +939,6 @@ BlotoutWallet.styles = [
754
939
  }
755
940
 
756
941
  dialog {
757
- position: relative;
758
942
  width: 430px;
759
943
  max-width: 100vw;
760
944
  background: var(--secondary);
@@ -838,97 +1022,92 @@ __decorate([
838
1022
  __decorate([
839
1023
  e$2('dialog'),
840
1024
  __metadata("design:type", HTMLDialogElement)
841
- ], BlotoutWallet.prototype, "_dialog", void 0);
1025
+ ], BlotoutWallet.prototype, "dialog", void 0);
842
1026
  __decorate([
843
1027
  e$2('button.cta'),
844
1028
  __metadata("design:type", HTMLButtonElement)
845
- ], BlotoutWallet.prototype, "_button", void 0);
1029
+ ], BlotoutWallet.prototype, "button", void 0);
846
1030
  __decorate([
847
1031
  e$2('input[name=email]'),
848
1032
  __metadata("design:type", HTMLInputElement)
849
- ], BlotoutWallet.prototype, "_email", void 0);
1033
+ ], BlotoutWallet.prototype, "email", void 0);
850
1034
  __decorate([
851
1035
  e$2('.banner'),
852
1036
  __metadata("design:type", HTMLDivElement)
853
- ], BlotoutWallet.prototype, "_banner", void 0);
1037
+ ], BlotoutWallet.prototype, "banner", void 0);
854
1038
  __decorate([
855
1039
  r(),
856
1040
  __metadata("design:type", Boolean)
857
- ], BlotoutWallet.prototype, "_buttonVisible", void 0);
1041
+ ], BlotoutWallet.prototype, "buttonVisible", void 0);
858
1042
  __decorate([
859
1043
  r(),
860
1044
  __metadata("design:type", Boolean)
861
- ], BlotoutWallet.prototype, "_bannerVisible", void 0);
1045
+ ], BlotoutWallet.prototype, "bannerVisible", void 0);
862
1046
  __decorate([
863
1047
  r(),
864
1048
  __metadata("design:type", Boolean)
865
- ], BlotoutWallet.prototype, "_hasItemsInWallet", void 0);
1049
+ ], BlotoutWallet.prototype, "hasItemsInWallet", void 0);
866
1050
  __decorate([
867
1051
  r(),
868
1052
  __metadata("design:type", Boolean)
869
- ], BlotoutWallet.prototype, "_hasEmail", void 0);
1053
+ ], BlotoutWallet.prototype, "hasEmail", void 0);
870
1054
  BlotoutWallet = __decorate([
871
1055
  t$1('blotout-wallet')
872
1056
  ], BlotoutWallet);
873
1057
 
874
1058
  const init = (params) => {
875
- var _a, _b;
876
- if (window && document && !window[registryKey].wallet) {
877
- window[registryKey].walletAPI = new WalletAPI({
1059
+ var _a, _b, _c;
1060
+ if (
1061
+ // if loaded in non-browser SDKs
1062
+ !window ||
1063
+ !document) {
1064
+ return;
1065
+ }
1066
+ let walletAPI = window[registryKey].walletAPI;
1067
+ if (!window[registryKey].walletAPI) {
1068
+ walletAPI = window[registryKey].walletAPI = new WalletAPI({
878
1069
  baseUrl: params.baseUrl,
879
1070
  userId: params.userId,
1071
+ enabled: !!((_a = params.manifest.variables) === null || _a === void 0 ? void 0 : _a['enabled']),
880
1072
  });
881
- const store = (window[registryKey].storeAPI =
882
- (_b = (_a = window[registryKey]).storeAPIFactory) === null || _b === void 0 ? void 0 : _b.call(_a));
1073
+ }
1074
+ let store = window[registryKey].storeAPI;
1075
+ if (!store) {
1076
+ store = window[registryKey].storeAPI =
1077
+ (_c = (_b = window[registryKey]).storeAPIFactory) === null || _c === void 0 ? void 0 : _c.call(_b);
883
1078
  if (!store) {
884
1079
  throw new Error('Implementation for store API missing!');
885
1080
  }
1081
+ }
1082
+ const initComponent = () => {
1083
+ var _a, _b;
886
1084
  const element = (window[registryKey].wallet =
887
1085
  document.createElement('blotout-wallet'));
888
- element.setAttribute('tag-name', params.manifest.tagName);
889
- document.body.append(element);
890
- }
891
- };
892
-
893
- const canLog = () => {
894
- try {
895
- return localStorage.getItem('edgeTagDebug') === '1';
896
- }
897
- catch {
898
- return false;
899
- }
900
- };
901
- const logger = {
902
- log: (...args) => {
903
- if (canLog()) {
904
- console.log(...args);
905
- }
906
- },
907
- error: (...args) => {
908
- if (canLog()) {
909
- console.error(...args);
910
- }
911
- },
912
- info: (...args) => {
913
- if (canLog()) {
914
- console.info(...args);
1086
+ const theme = (_a = params.manifest.variables) === null || _a === void 0 ? void 0 : _a['theme'];
1087
+ if (theme) {
1088
+ element.style.cssText = Object.entries(theme)
1089
+ .map(([name, value]) => `${name}:${value}`)
1090
+ .join(';');
915
1091
  }
916
- },
917
- trace: (...args) => {
918
- if (canLog()) {
919
- console.trace(...args);
1092
+ const position = (_b = params.manifest.variables) === null || _b === void 0 ? void 0 : _b['position'];
1093
+ if (position) {
1094
+ element.setAttribute('position', position);
920
1095
  }
921
- },
922
- table: (...args) => {
923
- if (canLog()) {
924
- console.table(...args);
1096
+ document.body.append(element);
1097
+ };
1098
+ if (window.top === window && !window[registryKey].wallet) {
1099
+ if (params.isNewUser) {
1100
+ // sync items from cart to wallet if a new user is detected
1101
+ store
1102
+ .getCart()
1103
+ .then((cartContent) => walletAPI.addItems(cartContent).catch(logger.error))
1104
+ .then(() => initComponent())
1105
+ .catch((err) => logger.error(err));
925
1106
  }
926
- },
927
- dir: (...args) => {
928
- if (canLog()) {
929
- console.dir(...args);
1107
+ else {
1108
+ initComponent();
930
1109
  }
931
- },
1110
+ }
932
1111
  };
933
1112
 
934
1113
  const transformItems = (data) => {
@@ -942,44 +1121,35 @@ const transformItems = (data) => {
942
1121
  }));
943
1122
  };
944
1123
  const tag = (params) => {
945
- const wallet = window[registryKey].walletAPI;
946
- if (!wallet) {
1124
+ var _a;
1125
+ if (!((_a = window === null || window === void 0 ? void 0 : window[registryKey]) === null || _a === void 0 ? void 0 : _a.walletAPI)) {
1126
+ logger.error(`[Blotout Wallet] No wallet API available`);
947
1127
  return;
948
1128
  }
1129
+ const wallet = window[registryKey].walletAPI;
949
1130
  switch (params.eventName) {
950
1131
  case 'AddToCart': {
951
1132
  const items = transformItems(params.data);
952
- if (items) {
1133
+ if (items === null || items === void 0 ? void 0 : items.length) {
953
1134
  wallet.addItems(items).catch(logger.error);
954
1135
  }
955
1136
  return;
956
1137
  }
957
- case 'InitiateCheckout': {
1138
+ case 'RemoveFromCart': {
958
1139
  const items = transformItems(params.data);
959
- if (items) {
960
- wallet.setItems(items).catch(logger.error);
1140
+ if (items === null || items === void 0 ? void 0 : items.length) {
1141
+ wallet.removeItems(items).catch(logger.error);
961
1142
  }
962
1143
  return;
963
1144
  }
964
- case 'Purchase': {
965
- const { orderId } = params.data;
966
- wallet.purchase(orderId).catch(logger.error);
967
- return;
968
- }
969
1145
  }
970
1146
  };
971
1147
 
972
- // eslint-disable-next-line @nx/enforce-module-boundaries
973
- const user = (params) => {
974
- console.log(`[${packageName}]: user`, params);
975
- };
976
-
977
1148
  // eslint-disable-next-line @nx/enforce-module-boundaries
978
1149
  const data = {
979
1150
  name: packageName,
980
1151
  init,
981
1152
  tag,
982
- user,
983
1153
  };
984
1154
  try {
985
1155
  if (window) {