@tagadapay/plugin-sdk 3.1.11 → 3.1.22

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.
Files changed (116) hide show
  1. package/README.md +1129 -1129
  2. package/build-cdn.js +231 -228
  3. package/dist/data/iso3166.d.ts +23 -33
  4. package/dist/data/iso3166.js +134 -198
  5. package/dist/data/languages.d.ts +5 -64
  6. package/dist/data/languages.js +23 -143
  7. package/dist/external-tracker.js +968 -102
  8. package/dist/external-tracker.min.js +2 -2
  9. package/dist/external-tracker.min.js.map +4 -4
  10. package/dist/react/hooks/useISOData.js +1 -1
  11. package/dist/react/hooks/usePaymentPolling.d.ts +3 -3
  12. package/dist/react/hooks/useShippingRates.d.ts +6 -0
  13. package/dist/react/hooks/useShippingRates.js +38 -0
  14. package/dist/react/providers/TagadaProvider.js +5 -5
  15. package/dist/react/services/apiService.d.ts +21 -0
  16. package/dist/react/services/apiService.js +10 -0
  17. package/dist/tagada-sdk.js +2079 -179
  18. package/dist/tagada-sdk.min.js +4 -2
  19. package/dist/tagada-sdk.min.js.map +4 -4
  20. package/dist/v2/core/client.d.ts +4 -2
  21. package/dist/v2/core/client.js +4 -3
  22. package/dist/v2/core/errors.d.ts +75 -0
  23. package/dist/v2/core/errors.js +104 -0
  24. package/dist/v2/core/funnelClient.d.ts +16 -15
  25. package/dist/v2/core/funnelClient.js +1 -1
  26. package/dist/v2/core/index.d.ts +1 -0
  27. package/dist/v2/core/index.js +2 -0
  28. package/dist/v2/core/pixelMapping.d.ts +49 -0
  29. package/dist/v2/core/pixelMapping.js +325 -0
  30. package/dist/v2/core/resources/apiClient.d.ts +2 -0
  31. package/dist/v2/core/resources/apiClient.js +52 -9
  32. package/dist/v2/core/resources/checkout.d.ts +89 -30
  33. package/dist/v2/core/resources/checkout.js +8 -0
  34. package/dist/v2/core/resources/customer.d.ts +20 -19
  35. package/dist/v2/core/resources/funnel.d.ts +17 -17
  36. package/dist/v2/core/resources/payments.d.ts +84 -13
  37. package/dist/v2/core/resources/payments.js +26 -9
  38. package/dist/v2/core/resources/shippingRates.d.ts +15 -0
  39. package/dist/v2/core/resources/shippingRates.js +11 -0
  40. package/dist/v2/core/types.d.ts +50 -12
  41. package/dist/v2/core/types.js +0 -3
  42. package/dist/v2/core/utils/checkout.d.ts +2 -2
  43. package/dist/v2/core/utils/checkout.js +7 -2
  44. package/dist/v2/core/utils/order.d.ts +11 -9
  45. package/dist/v2/core/utils/previewModeIndicator.js +101 -101
  46. package/dist/v2/index.d.ts +4 -2
  47. package/dist/v2/index.js +1 -1
  48. package/dist/v2/react/components/ApplePayButton.js +13 -4
  49. package/dist/v2/react/components/FunnelScriptInjector.js +51 -30
  50. package/dist/v2/react/components/WhopCheckout.d.ts +24 -0
  51. package/dist/v2/react/components/WhopCheckout.js +231 -0
  52. package/dist/v2/react/hooks/__examples__/FunnelContextExample.js +1 -1
  53. package/dist/v2/react/hooks/payment-actions/useAirwallexRadarAction.d.ts +14 -0
  54. package/dist/v2/react/hooks/payment-actions/useAirwallexRadarAction.js +181 -0
  55. package/dist/v2/react/hooks/payment-actions/useErrorAction.d.ts +9 -0
  56. package/dist/v2/react/hooks/payment-actions/useErrorAction.js +21 -0
  57. package/dist/v2/react/hooks/payment-actions/useFinixRadarAction.d.ts +14 -0
  58. package/dist/v2/react/hooks/payment-actions/useFinixRadarAction.js +187 -0
  59. package/dist/v2/react/hooks/payment-actions/useKessPayAction.d.ts +11 -0
  60. package/dist/v2/react/hooks/payment-actions/useKessPayAction.js +91 -0
  61. package/dist/v2/react/hooks/payment-actions/useMasterCardAction.d.ts +24 -0
  62. package/dist/v2/react/hooks/payment-actions/useMasterCardAction.js +221 -0
  63. package/dist/v2/react/hooks/payment-actions/usePaymentActionHandler.d.ts +15 -0
  64. package/dist/v2/react/hooks/payment-actions/usePaymentActionHandler.js +142 -0
  65. package/dist/v2/react/hooks/payment-actions/useProcessorAuthAction.d.ts +3 -0
  66. package/dist/v2/react/hooks/payment-actions/useProcessorAuthAction.js +13 -0
  67. package/dist/v2/react/hooks/payment-actions/useRedirectAction.d.ts +10 -0
  68. package/dist/v2/react/hooks/payment-actions/useRedirectAction.js +35 -0
  69. package/dist/v2/react/hooks/payment-actions/useStripeRadarAction.d.ts +14 -0
  70. package/dist/v2/react/hooks/payment-actions/useStripeRadarAction.js +192 -0
  71. package/dist/v2/react/hooks/payment-actions/useThreedsAuthAction.d.ts +14 -0
  72. package/dist/v2/react/hooks/payment-actions/useThreedsAuthAction.js +81 -0
  73. package/dist/v2/react/hooks/payment-actions/useTrustFlowAction.d.ts +11 -0
  74. package/dist/v2/react/hooks/payment-actions/useTrustFlowAction.js +84 -0
  75. package/dist/v2/react/hooks/payment-processing/usePaymentInstruments.d.ts +14 -0
  76. package/dist/v2/react/hooks/payment-processing/usePaymentInstruments.js +36 -0
  77. package/dist/v2/react/hooks/payment-processing/usePaymentProcessors.d.ts +31 -0
  78. package/dist/v2/react/hooks/payment-processing/usePaymentProcessors.js +212 -0
  79. package/dist/v2/react/hooks/payment-redirect/useAirwallex3dsReturn.d.ts +14 -0
  80. package/dist/v2/react/hooks/payment-redirect/useAirwallex3dsReturn.js +207 -0
  81. package/dist/v2/react/hooks/payment-redirect/useGenericPaymentReturn.d.ts +12 -0
  82. package/dist/v2/react/hooks/payment-redirect/useGenericPaymentReturn.js +101 -0
  83. package/dist/v2/react/hooks/useCheckoutQuery.d.ts +6 -0
  84. package/dist/v2/react/hooks/useCheckoutQuery.js +45 -0
  85. package/dist/v2/react/hooks/useFunnel.d.ts +1 -2
  86. package/dist/v2/react/hooks/useGeoLocation.d.ts +2 -1
  87. package/dist/v2/react/hooks/useGeoLocation.js +4 -2
  88. package/dist/v2/react/hooks/useGoogleAutocomplete.js +82 -33
  89. package/dist/v2/react/hooks/useISOData.js +1 -1
  90. package/dist/v2/react/hooks/usePaymentPolling.d.ts +3 -3
  91. package/dist/v2/react/hooks/usePaymentQuery.d.ts +18 -5
  92. package/dist/v2/react/hooks/usePaymentQuery.js +63 -1015
  93. package/dist/v2/react/hooks/usePaymentRetrieve.d.ts +3 -2
  94. package/dist/v2/react/hooks/usePaymentRetrieve.js +3 -1
  95. package/dist/v2/react/hooks/usePixelTracking.d.ts +5 -43
  96. package/dist/v2/react/hooks/usePixelTracking.js +213 -407
  97. package/dist/v2/react/hooks/useShippingRatesQuery.d.ts +6 -0
  98. package/dist/v2/react/hooks/useShippingRatesQuery.js +47 -4
  99. package/dist/v2/react/hooks/useStepConfig.d.ts +2 -8
  100. package/dist/v2/react/hooks/useStepConfig.js +1 -1
  101. package/dist/v2/react/hooks/useWhopPaymentPolling.d.ts +30 -0
  102. package/dist/v2/react/hooks/useWhopPaymentPolling.js +61 -0
  103. package/dist/v2/react/index.d.ts +7 -0
  104. package/dist/v2/react/index.js +4 -0
  105. package/dist/v2/react/providers/ExpressPaymentMethodsProvider.d.ts +2 -1
  106. package/dist/v2/react/providers/ExpressPaymentMethodsProvider.js +3 -1
  107. package/dist/v2/react/providers/TagadaProvider.js +76 -7
  108. package/dist/v2/standalone/external-tracker.d.ts +52 -46
  109. package/dist/v2/standalone/external-tracker.js +205 -98
  110. package/dist/v2/standalone/index.d.ts +22 -0
  111. package/dist/v2/standalone/index.js +125 -0
  112. package/package.json +112 -112
  113. package/dist/react/utils/__tests__/urlUtils.test.d.ts +0 -1
  114. package/dist/react/utils/__tests__/urlUtils.test.js +0 -189
  115. package/dist/v2/core/__tests__/pathRemapping.test.d.ts +0 -11
  116. package/dist/v2/core/__tests__/pathRemapping.test.js +0 -776
@@ -1,17 +1,19 @@
1
1
  /**
2
- * TagadaPay SDK v3.1.11
2
+ * TagadaPay SDK v3.1.22
3
3
  * CDN Bundle - Full standalone SDK (Debug Build)
4
4
  * Usage: window.tgd.createTagadaClient(), window.tgd.formatMoney(), etc.
5
5
  * @license MIT
6
6
  */
7
7
  "use strict";
8
8
  var TagadaSDKBundle = (() => {
9
+ var __create = Object.create;
9
10
  var __defProp = Object.defineProperty;
10
11
  var __defProps = Object.defineProperties;
11
12
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
13
  var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
13
14
  var __getOwnPropNames = Object.getOwnPropertyNames;
14
15
  var __getOwnPropSymbols = Object.getOwnPropertySymbols;
16
+ var __getProtoOf = Object.getPrototypeOf;
15
17
  var __hasOwnProp = Object.prototype.hasOwnProperty;
16
18
  var __propIsEnum = Object.prototype.propertyIsEnumerable;
17
19
  var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name);
@@ -34,6 +36,9 @@ var TagadaSDKBundle = (() => {
34
36
  var __esm = (fn, res) => function __init() {
35
37
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
36
38
  };
39
+ var __commonJS = (cb, mod) => function __require() {
40
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
41
+ };
37
42
  var __export = (target, all3) => {
38
43
  for (var name in all3)
39
44
  __defProp(target, name, { get: all3[name], enumerable: true });
@@ -46,6 +51,14 @@ var TagadaSDKBundle = (() => {
46
51
  }
47
52
  return to;
48
53
  };
54
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
55
+ // If the importer is in node compatibility mode or this is not an ESM
56
+ // file that has been converted to a CommonJS file using a Babel-
57
+ // compatible transform (i.e. "__esModule" has not been set), then set
58
+ // "default" to the CommonJS "module.exports" for node compatibility.
59
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
60
+ mod
61
+ ));
49
62
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
50
63
  var __await = function(promise, isYieldStar) {
51
64
  this[0] = promise;
@@ -1173,7 +1186,7 @@ var TagadaSDKBundle = (() => {
1173
1186
  TrackingProvider2["FACEBOOK"] = "facebook";
1174
1187
  TrackingProvider2["TIKTOK"] = "tiktok";
1175
1188
  TrackingProvider2["SNAPCHAT"] = "snapchat";
1176
- TrackingProvider2["META_CONVERSION"] = "meta_conversion";
1189
+ TrackingProvider2["PINTEREST"] = "pinterest";
1177
1190
  TrackingProvider2["GTM"] = "gtm";
1178
1191
  return TrackingProvider2;
1179
1192
  })(TrackingProvider || {});
@@ -1582,6 +1595,361 @@ var TagadaSDKBundle = (() => {
1582
1595
  }
1583
1596
  });
1584
1597
 
1598
+ // ../../node_modules/.pnpm/path-to-regexp@8.3.0/node_modules/path-to-regexp/dist/index.js
1599
+ var require_dist = __commonJS({
1600
+ "../../node_modules/.pnpm/path-to-regexp@8.3.0/node_modules/path-to-regexp/dist/index.js"(exports) {
1601
+ "use strict";
1602
+ Object.defineProperty(exports, "__esModule", { value: true });
1603
+ exports.PathError = exports.TokenData = void 0;
1604
+ exports.parse = parse;
1605
+ exports.compile = compile;
1606
+ exports.match = match2;
1607
+ exports.pathToRegexp = pathToRegexp;
1608
+ exports.stringify = stringify;
1609
+ var DEFAULT_DELIMITER = "/";
1610
+ var NOOP_VALUE = (value) => value;
1611
+ var ID_START = new RegExp("^[$_\\p{ID_Start}]$", "u");
1612
+ var ID_CONTINUE = new RegExp("^[$\\u200c\\u200d\\p{ID_Continue}]$", "u");
1613
+ var SIMPLE_TOKENS = {
1614
+ // Groups.
1615
+ "{": "{",
1616
+ "}": "}",
1617
+ // Reserved.
1618
+ "(": "(",
1619
+ ")": ")",
1620
+ "[": "[",
1621
+ "]": "]",
1622
+ "+": "+",
1623
+ "?": "?",
1624
+ "!": "!"
1625
+ };
1626
+ function escapeText(str) {
1627
+ return str.replace(/[{}()\[\]+?!:*\\]/g, "\\$&");
1628
+ }
1629
+ function escape(str) {
1630
+ return str.replace(/[.+*?^${}()[\]|/\\]/g, "\\$&");
1631
+ }
1632
+ var TokenData = class {
1633
+ constructor(tokens, originalPath) {
1634
+ this.tokens = tokens;
1635
+ this.originalPath = originalPath;
1636
+ }
1637
+ };
1638
+ exports.TokenData = TokenData;
1639
+ var PathError = class extends TypeError {
1640
+ constructor(message, originalPath) {
1641
+ let text = message;
1642
+ if (originalPath)
1643
+ text += ": ".concat(originalPath);
1644
+ text += "; visit https://git.new/pathToRegexpError for info";
1645
+ super(text);
1646
+ this.originalPath = originalPath;
1647
+ }
1648
+ };
1649
+ exports.PathError = PathError;
1650
+ function parse(str, options = {}) {
1651
+ const { encodePath = NOOP_VALUE } = options;
1652
+ const chars = [...str];
1653
+ const tokens = [];
1654
+ let index = 0;
1655
+ let pos = 0;
1656
+ function name() {
1657
+ let value = "";
1658
+ if (ID_START.test(chars[index])) {
1659
+ do {
1660
+ value += chars[index++];
1661
+ } while (ID_CONTINUE.test(chars[index]));
1662
+ } else if (chars[index] === '"') {
1663
+ let quoteStart = index;
1664
+ while (index++ < chars.length) {
1665
+ if (chars[index] === '"') {
1666
+ index++;
1667
+ quoteStart = 0;
1668
+ break;
1669
+ }
1670
+ if (chars[index] === "\\")
1671
+ index++;
1672
+ value += chars[index];
1673
+ }
1674
+ if (quoteStart) {
1675
+ throw new PathError("Unterminated quote at index ".concat(quoteStart), str);
1676
+ }
1677
+ }
1678
+ if (!value) {
1679
+ throw new PathError("Missing parameter name at index ".concat(index), str);
1680
+ }
1681
+ return value;
1682
+ }
1683
+ while (index < chars.length) {
1684
+ const value = chars[index];
1685
+ const type = SIMPLE_TOKENS[value];
1686
+ if (type) {
1687
+ tokens.push({ type, index: index++, value });
1688
+ } else if (value === "\\") {
1689
+ tokens.push({ type: "escape", index: index++, value: chars[index++] });
1690
+ } else if (value === ":") {
1691
+ tokens.push({ type: "param", index: index++, value: name() });
1692
+ } else if (value === "*") {
1693
+ tokens.push({ type: "wildcard", index: index++, value: name() });
1694
+ } else {
1695
+ tokens.push({ type: "char", index: index++, value });
1696
+ }
1697
+ }
1698
+ tokens.push({ type: "end", index, value: "" });
1699
+ function consumeUntil(endType) {
1700
+ const output = [];
1701
+ while (true) {
1702
+ const token = tokens[pos++];
1703
+ if (token.type === endType)
1704
+ break;
1705
+ if (token.type === "char" || token.type === "escape") {
1706
+ let path = token.value;
1707
+ let cur = tokens[pos];
1708
+ while (cur.type === "char" || cur.type === "escape") {
1709
+ path += cur.value;
1710
+ cur = tokens[++pos];
1711
+ }
1712
+ output.push({
1713
+ type: "text",
1714
+ value: encodePath(path)
1715
+ });
1716
+ continue;
1717
+ }
1718
+ if (token.type === "param" || token.type === "wildcard") {
1719
+ output.push({
1720
+ type: token.type,
1721
+ name: token.value
1722
+ });
1723
+ continue;
1724
+ }
1725
+ if (token.type === "{") {
1726
+ output.push({
1727
+ type: "group",
1728
+ tokens: consumeUntil("}")
1729
+ });
1730
+ continue;
1731
+ }
1732
+ throw new PathError("Unexpected ".concat(token.type, " at index ").concat(token.index, ", expected ").concat(endType), str);
1733
+ }
1734
+ return output;
1735
+ }
1736
+ return new TokenData(consumeUntil("end"), str);
1737
+ }
1738
+ function compile(path, options = {}) {
1739
+ const { encode: encode3 = encodeURIComponent, delimiter = DEFAULT_DELIMITER } = options;
1740
+ const data = typeof path === "object" ? path : parse(path, options);
1741
+ const fn = tokensToFunction(data.tokens, delimiter, encode3);
1742
+ return function path2(params = {}) {
1743
+ const [path3, ...missing] = fn(params);
1744
+ if (missing.length) {
1745
+ throw new TypeError("Missing parameters: ".concat(missing.join(", ")));
1746
+ }
1747
+ return path3;
1748
+ };
1749
+ }
1750
+ function tokensToFunction(tokens, delimiter, encode3) {
1751
+ const encoders = tokens.map((token) => tokenToFunction(token, delimiter, encode3));
1752
+ return (data) => {
1753
+ const result = [""];
1754
+ for (const encoder of encoders) {
1755
+ const [value, ...extras] = encoder(data);
1756
+ result[0] += value;
1757
+ result.push(...extras);
1758
+ }
1759
+ return result;
1760
+ };
1761
+ }
1762
+ function tokenToFunction(token, delimiter, encode3) {
1763
+ if (token.type === "text")
1764
+ return () => [token.value];
1765
+ if (token.type === "group") {
1766
+ const fn = tokensToFunction(token.tokens, delimiter, encode3);
1767
+ return (data) => {
1768
+ const [value, ...missing] = fn(data);
1769
+ if (!missing.length)
1770
+ return [value];
1771
+ return [""];
1772
+ };
1773
+ }
1774
+ const encodeValue = encode3 || NOOP_VALUE;
1775
+ if (token.type === "wildcard" && encode3 !== false) {
1776
+ return (data) => {
1777
+ const value = data[token.name];
1778
+ if (value == null)
1779
+ return ["", token.name];
1780
+ if (!Array.isArray(value) || value.length === 0) {
1781
+ throw new TypeError('Expected "'.concat(token.name, '" to be a non-empty array'));
1782
+ }
1783
+ return [
1784
+ value.map((value2, index) => {
1785
+ if (typeof value2 !== "string") {
1786
+ throw new TypeError('Expected "'.concat(token.name, "/").concat(index, '" to be a string'));
1787
+ }
1788
+ return encodeValue(value2);
1789
+ }).join(delimiter)
1790
+ ];
1791
+ };
1792
+ }
1793
+ return (data) => {
1794
+ const value = data[token.name];
1795
+ if (value == null)
1796
+ return ["", token.name];
1797
+ if (typeof value !== "string") {
1798
+ throw new TypeError('Expected "'.concat(token.name, '" to be a string'));
1799
+ }
1800
+ return [encodeValue(value)];
1801
+ };
1802
+ }
1803
+ function match2(path, options = {}) {
1804
+ const { decode = decodeURIComponent, delimiter = DEFAULT_DELIMITER } = options;
1805
+ const { regexp, keys } = pathToRegexp(path, options);
1806
+ const decoders = keys.map((key) => {
1807
+ if (decode === false)
1808
+ return NOOP_VALUE;
1809
+ if (key.type === "param")
1810
+ return decode;
1811
+ return (value) => value.split(delimiter).map(decode);
1812
+ });
1813
+ return function match3(input) {
1814
+ const m = regexp.exec(input);
1815
+ if (!m)
1816
+ return false;
1817
+ const path2 = m[0];
1818
+ const params = /* @__PURE__ */ Object.create(null);
1819
+ for (let i = 1; i < m.length; i++) {
1820
+ if (m[i] === void 0)
1821
+ continue;
1822
+ const key = keys[i - 1];
1823
+ const decoder = decoders[i - 1];
1824
+ params[key.name] = decoder(m[i]);
1825
+ }
1826
+ return { path: path2, params };
1827
+ };
1828
+ }
1829
+ function pathToRegexp(path, options = {}) {
1830
+ const { delimiter = DEFAULT_DELIMITER, end = true, sensitive = false, trailing = true } = options;
1831
+ const keys = [];
1832
+ const flags = sensitive ? "" : "i";
1833
+ const sources = [];
1834
+ for (const input of pathsToArray(path, [])) {
1835
+ const data = typeof input === "object" ? input : parse(input, options);
1836
+ for (const tokens of flatten(data.tokens, 0, [])) {
1837
+ sources.push(toRegExpSource(tokens, delimiter, keys, data.originalPath));
1838
+ }
1839
+ }
1840
+ let pattern = "^(?:".concat(sources.join("|"), ")");
1841
+ if (trailing)
1842
+ pattern += "(?:".concat(escape(delimiter), "$)?");
1843
+ pattern += end ? "$" : "(?=".concat(escape(delimiter), "|$)");
1844
+ const regexp = new RegExp(pattern, flags);
1845
+ return { regexp, keys };
1846
+ }
1847
+ function pathsToArray(paths, init) {
1848
+ if (Array.isArray(paths)) {
1849
+ for (const p of paths)
1850
+ pathsToArray(p, init);
1851
+ } else {
1852
+ init.push(paths);
1853
+ }
1854
+ return init;
1855
+ }
1856
+ function* flatten(tokens, index, init) {
1857
+ if (index === tokens.length) {
1858
+ return yield init;
1859
+ }
1860
+ const token = tokens[index];
1861
+ if (token.type === "group") {
1862
+ for (const seq of flatten(token.tokens, 0, init.slice())) {
1863
+ yield* __yieldStar(flatten(tokens, index + 1, seq));
1864
+ }
1865
+ } else {
1866
+ init.push(token);
1867
+ }
1868
+ yield* __yieldStar(flatten(tokens, index + 1, init));
1869
+ }
1870
+ function toRegExpSource(tokens, delimiter, keys, originalPath) {
1871
+ let result = "";
1872
+ let backtrack = "";
1873
+ let isSafeSegmentParam = true;
1874
+ for (const token of tokens) {
1875
+ if (token.type === "text") {
1876
+ result += escape(token.value);
1877
+ backtrack += token.value;
1878
+ isSafeSegmentParam || (isSafeSegmentParam = token.value.includes(delimiter));
1879
+ continue;
1880
+ }
1881
+ if (token.type === "param" || token.type === "wildcard") {
1882
+ if (!isSafeSegmentParam && !backtrack) {
1883
+ throw new PathError('Missing text before "'.concat(token.name, '" ').concat(token.type), originalPath);
1884
+ }
1885
+ if (token.type === "param") {
1886
+ result += "(".concat(negate(delimiter, isSafeSegmentParam ? "" : backtrack), "+)");
1887
+ } else {
1888
+ result += "([\\s\\S]+)";
1889
+ }
1890
+ keys.push(token);
1891
+ backtrack = "";
1892
+ isSafeSegmentParam = false;
1893
+ continue;
1894
+ }
1895
+ }
1896
+ return result;
1897
+ }
1898
+ function negate(delimiter, backtrack) {
1899
+ if (backtrack.length < 2) {
1900
+ if (delimiter.length < 2)
1901
+ return "[^".concat(escape(delimiter + backtrack), "]");
1902
+ return "(?:(?!".concat(escape(delimiter), ")[^").concat(escape(backtrack), "])");
1903
+ }
1904
+ if (delimiter.length < 2) {
1905
+ return "(?:(?!".concat(escape(backtrack), ")[^").concat(escape(delimiter), "])");
1906
+ }
1907
+ return "(?:(?!".concat(escape(backtrack), "|").concat(escape(delimiter), ")[\\s\\S])");
1908
+ }
1909
+ function stringifyTokens(tokens) {
1910
+ let value = "";
1911
+ let i = 0;
1912
+ function name(value2) {
1913
+ const isSafe = isNameSafe(value2) && isNextNameSafe(tokens[i]);
1914
+ return isSafe ? value2 : JSON.stringify(value2);
1915
+ }
1916
+ while (i < tokens.length) {
1917
+ const token = tokens[i++];
1918
+ if (token.type === "text") {
1919
+ value += escapeText(token.value);
1920
+ continue;
1921
+ }
1922
+ if (token.type === "group") {
1923
+ value += "{".concat(stringifyTokens(token.tokens), "}");
1924
+ continue;
1925
+ }
1926
+ if (token.type === "param") {
1927
+ value += ":".concat(name(token.name));
1928
+ continue;
1929
+ }
1930
+ if (token.type === "wildcard") {
1931
+ value += "*".concat(name(token.name));
1932
+ continue;
1933
+ }
1934
+ throw new TypeError("Unknown token type: ".concat(token.type));
1935
+ }
1936
+ return value;
1937
+ }
1938
+ function stringify(data) {
1939
+ return stringifyTokens(data.tokens);
1940
+ }
1941
+ function isNameSafe(name) {
1942
+ const [first, ...rest] = name;
1943
+ return ID_START.test(first) && rest.every((char) => ID_CONTINUE.test(char));
1944
+ }
1945
+ function isNextNameSafe(token) {
1946
+ if (token && token.type === "text")
1947
+ return !ID_CONTINUE.test(token.value[0]);
1948
+ return true;
1949
+ }
1950
+ }
1951
+ });
1952
+
1585
1953
  // src/v2/standalone/index.ts
1586
1954
  var index_exports = {};
1587
1955
  __export(index_exports, {
@@ -1590,15 +1958,28 @@ var TagadaSDKBundle = (() => {
1590
1958
  CheckoutUtils: () => CheckoutUtils,
1591
1959
  CurrencyUtils: () => CurrencyUtils,
1592
1960
  FunnelActionType: () => FunnelActionType,
1961
+ GoogleAutocompleteCore: () => GoogleAutocompleteCore,
1962
+ ISODataCore: () => ISODataCore,
1593
1963
  OrderBumpUtils: () => OrderBumpUtils,
1594
1964
  OrderUtils: () => OrderUtils,
1965
+ OrdersResource: () => OrdersResource,
1966
+ PaymentsResource: () => PaymentsResource,
1595
1967
  PluginConfigUtils: () => PluginConfigUtils,
1596
1968
  PostPurchasesUtils: () => PostPurchasesUtils,
1597
1969
  ProductsUtils: () => ProductsUtils,
1598
1970
  PromotionsUtils: () => PromotionsUtils,
1971
+ ShippingRatesResource: () => ShippingRatesResource,
1972
+ TagadaApiError: () => TagadaApiError,
1973
+ TagadaAuthError: () => TagadaAuthError,
1974
+ TagadaCircuitBreakerError: () => TagadaCircuitBreakerError,
1599
1975
  TagadaClient: () => TagadaClient,
1976
+ TagadaError: () => TagadaError,
1977
+ TagadaErrorCode: () => TagadaErrorCode,
1600
1978
  TagadaExternalTracker: () => TagadaExternalTracker,
1979
+ TagadaNetworkError: () => TagadaNetworkError,
1601
1980
  TagadaTracker: () => TagadaTracker,
1981
+ TagadaValidationError: () => TagadaValidationError,
1982
+ applyGoogleAdsConversion: () => applyGoogleAdsConversion,
1602
1983
  broadcastConfigUpdate: () => broadcastConfigUpdate,
1603
1984
  clearFunnelSessionCookie: () => clearFunnelSessionCookie,
1604
1985
  createRawPluginConfig: () => createRawPluginConfig,
@@ -1606,13 +1987,26 @@ var TagadaSDKBundle = (() => {
1606
1987
  debounceConfigUpdate: () => debounceConfigUpdate,
1607
1988
  formatMoney: () => formatMoney,
1608
1989
  funnelQueryKeys: () => funnelQueryKeys,
1990
+ getEligiblePixels: () => getEligiblePixels,
1609
1991
  getFunnelSessionCookie: () => getFunnelSessionCookie,
1610
1992
  getFunnelVariantId: () => getFunnelVariantId,
1993
+ getInternalPath: () => getInternalPath,
1994
+ getPathInfo: () => getPathInfo,
1611
1995
  getPluginConfig: () => getPluginConfig,
1612
1996
  hasFunnelSessionCookie: () => hasFunnelSessionCookie,
1997
+ injectStepConfigScripts: () => injectStepConfigScripts,
1998
+ isEventEnabled: () => isEventEnabled,
1999
+ isPathRemapped: () => isPathRemapped,
1613
2000
  loadLocalConfig: () => loadLocalConfig,
1614
2001
  loadPluginConfig: () => loadPluginConfig,
2002
+ mapGTMEvent: () => mapGTMEvent,
2003
+ mapMetaEvent: () => mapMetaEvent,
2004
+ mapPinterestEvent: () => mapPinterestEvent,
2005
+ mapSnapchatEvent: () => mapSnapchatEvent,
2006
+ mapTikTokEvent: () => mapTikTokEvent,
2007
+ matchRoute: () => matchRoute,
1615
2008
  onConfigUpdate: () => onConfigUpdate,
2009
+ resolvePixelEvents: () => resolvePixelEvents,
1616
2010
  sendConfigUpdate: () => sendConfigUpdate,
1617
2011
  setFunnelSessionCookie: () => setFunnelSessionCookie
1618
2012
  });
@@ -2221,8 +2615,8 @@ var TagadaSDKBundle = (() => {
2221
2615
  "%20": "+",
2222
2616
  "%00": "\0"
2223
2617
  };
2224
- return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {
2225
- return charMap[match];
2618
+ return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match2) {
2619
+ return charMap[match2];
2226
2620
  });
2227
2621
  }
2228
2622
  function AxiosURLSearchParams(params, options) {
@@ -2401,8 +2795,8 @@ var TagadaSDKBundle = (() => {
2401
2795
 
2402
2796
  // ../../node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/helpers/formDataToJSON.js
2403
2797
  function parsePropPath(name) {
2404
- return utils_default.matchAll(/\w+|\[(\w*)]/g, name).map((match) => {
2405
- return match[0] === "[]" ? "" : match[1] || match[0];
2798
+ return utils_default.matchAll(/\w+|\[(\w*)]/g, name).map((match2) => {
2799
+ return match2[0] === "[]" ? "" : match2[1] || match2[0];
2406
2800
  });
2407
2801
  }
2408
2802
  function arrayToObject(arr) {
@@ -2620,9 +3014,9 @@ var TagadaSDKBundle = (() => {
2620
3014
  function parseTokens(str) {
2621
3015
  const tokens = /* @__PURE__ */ Object.create(null);
2622
3016
  const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
2623
- let match;
2624
- while (match = tokensRE.exec(str)) {
2625
- tokens[match[1]] = match[2];
3017
+ let match2;
3018
+ while (match2 = tokensRE.exec(str)) {
3019
+ tokens[match2[1]] = match2[2];
2626
3020
  }
2627
3021
  return tokens;
2628
3022
  }
@@ -2881,8 +3275,8 @@ var TagadaSDKBundle = (() => {
2881
3275
 
2882
3276
  // ../../node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/helpers/parseProtocol.js
2883
3277
  function parseProtocol(url) {
2884
- const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
2885
- return match && match[1] || "";
3278
+ const match2 = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
3279
+ return match2 && match2[1] || "";
2886
3280
  }
2887
3281
 
2888
3282
  // ../../node_modules/.pnpm/axios@1.13.2/node_modules/axios/lib/helpers/speedometer.js
@@ -3026,8 +3420,8 @@ var TagadaSDKBundle = (() => {
3026
3420
  },
3027
3421
  read(name) {
3028
3422
  if (typeof document === "undefined") return null;
3029
- const match = document.cookie.match(new RegExp("(?:^|; )" + name + "=([^;]*)"));
3030
- return match ? decodeURIComponent(match[1]) : null;
3423
+ const match2 = document.cookie.match(new RegExp("(?:^|; )" + name + "=([^;]*)"));
3424
+ return match2 ? decodeURIComponent(match2[1]) : null;
3031
3425
  },
3032
3426
  remove(name) {
3033
3427
  this.write(name, "", Date.now() - 864e5, "/");
@@ -4238,6 +4632,86 @@ var TagadaSDKBundle = (() => {
4238
4632
  mergeConfig: mergeConfig2
4239
4633
  } = axios_default;
4240
4634
 
4635
+ // src/v2/core/errors.ts
4636
+ var TagadaErrorCode = {
4637
+ NETWORK_ERROR: "network_error",
4638
+ API_ERROR: "api_error",
4639
+ AUTH_REQUIRED: "auth_required",
4640
+ TOKEN_EXPIRED: "token_expired",
4641
+ NOT_FOUND: "not_found",
4642
+ VALIDATION_ERROR: "validation_error",
4643
+ CIRCUIT_BREAKER: "circuit_breaker",
4644
+ PAYMENT_FAILED: "payment_failed",
4645
+ CARD_DECLINED: "card_declined",
4646
+ SESSION_EXPIRED: "session_expired",
4647
+ RATE_LIMITED: "rate_limited",
4648
+ TIMEOUT: "timeout",
4649
+ UNKNOWN: "unknown"
4650
+ };
4651
+ var TagadaError = class extends Error {
4652
+ constructor(message, options) {
4653
+ var _a;
4654
+ super(message);
4655
+ this.name = "TagadaError";
4656
+ this.code = options.code;
4657
+ this.statusCode = options.statusCode;
4658
+ this.retryable = (_a = options.retryable) != null ? _a : false;
4659
+ this.details = options.details;
4660
+ Object.setPrototypeOf(this, new.target.prototype);
4661
+ }
4662
+ };
4663
+ var TagadaApiError = class extends TagadaError {
4664
+ constructor(message, statusCode, options) {
4665
+ var _a, _b;
4666
+ super(message, {
4667
+ code: (_a = options == null ? void 0 : options.code) != null ? _a : TagadaErrorCode.API_ERROR,
4668
+ statusCode,
4669
+ retryable: (_b = options == null ? void 0 : options.retryable) != null ? _b : statusCode >= 500,
4670
+ details: options == null ? void 0 : options.details
4671
+ });
4672
+ this.name = "TagadaApiError";
4673
+ }
4674
+ };
4675
+ var TagadaNetworkError = class extends TagadaError {
4676
+ constructor(message = "Network request failed") {
4677
+ super(message, {
4678
+ code: TagadaErrorCode.NETWORK_ERROR,
4679
+ retryable: true
4680
+ });
4681
+ this.name = "TagadaNetworkError";
4682
+ }
4683
+ };
4684
+ var TagadaAuthError = class extends TagadaError {
4685
+ constructor(message = "Authentication required", statusCode = 401) {
4686
+ super(message, {
4687
+ code: TagadaErrorCode.AUTH_REQUIRED,
4688
+ statusCode,
4689
+ retryable: false
4690
+ });
4691
+ this.name = "TagadaAuthError";
4692
+ }
4693
+ };
4694
+ var TagadaValidationError = class extends TagadaError {
4695
+ constructor(message, details) {
4696
+ super(message, {
4697
+ code: TagadaErrorCode.VALIDATION_ERROR,
4698
+ statusCode: 400,
4699
+ retryable: false,
4700
+ details
4701
+ });
4702
+ this.name = "TagadaValidationError";
4703
+ }
4704
+ };
4705
+ var TagadaCircuitBreakerError = class extends TagadaError {
4706
+ constructor(message) {
4707
+ super(message, {
4708
+ code: TagadaErrorCode.CIRCUIT_BREAKER,
4709
+ retryable: false
4710
+ });
4711
+ this.name = "TagadaCircuitBreakerError";
4712
+ }
4713
+ };
4714
+
4241
4715
  // src/v2/core/resources/apiClient.ts
4242
4716
  var ApiClient = class {
4243
4717
  // Max 30 requests per endpoint in window
@@ -4295,12 +4769,18 @@ var TagadaSDKBundle = (() => {
4295
4769
  }
4296
4770
  );
4297
4771
  this.axios.interceptors.response.use(
4298
- (response) => {
4299
- return response;
4300
- },
4772
+ (response) => response,
4301
4773
  (error) => {
4302
4774
  console.error("[SDK] Response error:", error.message);
4303
- return Promise.reject(error instanceof Error ? error : new Error(String(error)));
4775
+ if (error instanceof TagadaError) {
4776
+ return Promise.reject(error);
4777
+ }
4778
+ if (axios_default.isAxiosError(error)) {
4779
+ return Promise.reject(this.toTagadaError(error));
4780
+ }
4781
+ return Promise.reject(
4782
+ error instanceof Error ? error : new Error(String(error))
4783
+ );
4304
4784
  }
4305
4785
  );
4306
4786
  }
@@ -4366,30 +4846,66 @@ var TagadaSDKBundle = (() => {
4366
4846
  // Circuit Breaker Implementation
4367
4847
  checkRequestLimit(key) {
4368
4848
  const now = Date.now();
4369
- const history = this.requestHistory.get(key);
4370
- if (!history) {
4849
+ const history2 = this.requestHistory.get(key);
4850
+ if (!history2) {
4371
4851
  this.requestHistory.set(key, { count: 1, firstRequestTime: now });
4372
4852
  return;
4373
4853
  }
4374
- if (now - history.firstRequestTime > this.WINDOW_MS) {
4854
+ if (now - history2.firstRequestTime > this.WINDOW_MS) {
4375
4855
  this.requestHistory.set(key, { count: 1, firstRequestTime: now });
4376
4856
  return;
4377
4857
  }
4378
- history.count++;
4379
- if (history.count > this.MAX_REQUESTS) {
4380
- const error = new Error("Circuit Breaker: Too many requests to ".concat(key, " (").concat(history.count, " in ").concat(this.WINDOW_MS, "ms)"));
4381
- error.isCircuitBreaker = true;
4382
- throw error;
4858
+ history2.count++;
4859
+ if (history2.count > this.MAX_REQUESTS) {
4860
+ throw new TagadaCircuitBreakerError(
4861
+ "Circuit Breaker: Too many requests to ".concat(key, " (").concat(history2.count, " in ").concat(this.WINDOW_MS, "ms)")
4862
+ );
4383
4863
  }
4384
4864
  }
4385
4865
  cleanupHistory() {
4386
4866
  const now = Date.now();
4387
- for (const [key, history] of this.requestHistory.entries()) {
4388
- if (now - history.firstRequestTime > this.WINDOW_MS) {
4867
+ for (const [key, history2] of this.requestHistory.entries()) {
4868
+ if (now - history2.firstRequestTime > this.WINDOW_MS) {
4389
4869
  this.requestHistory.delete(key);
4390
4870
  }
4391
4871
  }
4392
4872
  }
4873
+ /** Convert an AxiosError into the appropriate TagadaError subclass. */
4874
+ toTagadaError(error) {
4875
+ var _a, _b, _c, _d, _e;
4876
+ const status = (_a = error.response) == null ? void 0 : _a.status;
4877
+ const data = (_b = error.response) == null ? void 0 : _b.data;
4878
+ const serverMessage = (_d = (_c = data == null ? void 0 : data.message) != null ? _c : data == null ? void 0 : data.error) != null ? _d : error.message;
4879
+ if (!error.response) {
4880
+ if (error.code === "ECONNABORTED") {
4881
+ return new TagadaApiError("Request timed out", 0, {
4882
+ code: TagadaErrorCode.TIMEOUT,
4883
+ retryable: true
4884
+ });
4885
+ }
4886
+ return new TagadaNetworkError(serverMessage);
4887
+ }
4888
+ if (status === 401 || status === 403) {
4889
+ return new TagadaAuthError(serverMessage, status);
4890
+ }
4891
+ if (status === 429) {
4892
+ return new TagadaApiError(serverMessage, 429, {
4893
+ code: TagadaErrorCode.RATE_LIMITED,
4894
+ retryable: true
4895
+ });
4896
+ }
4897
+ if (status === 404) {
4898
+ return new TagadaApiError(serverMessage, 404, {
4899
+ code: TagadaErrorCode.NOT_FOUND,
4900
+ retryable: false
4901
+ });
4902
+ }
4903
+ return new TagadaApiError(serverMessage, status != null ? status : 0, {
4904
+ code: (_e = data == null ? void 0 : data.code) != null ? _e : TagadaErrorCode.API_ERROR,
4905
+ details: data,
4906
+ retryable: (status != null ? status : 0) >= 500
4907
+ });
4908
+ }
4393
4909
  };
4394
4910
 
4395
4911
  // ../../node_modules/.pnpm/@ua-parser-js+pro-enterprise@2.0.6/node_modules/@ua-parser-js/pro-enterprise/src/main/ua-parser.mjs
@@ -4558,7 +5074,7 @@ var TagadaSDKBundle = (() => {
4558
5074
  };
4559
5075
  var rgxMapper = function(ua, arrays) {
4560
5076
  if (!ua || !arrays) return;
4561
- var i = 0, j, k, p, q, matches, match;
5077
+ var i = 0, j, k, p, q, matches, match2;
4562
5078
  while (i < arrays.length && !matches) {
4563
5079
  var regex = arrays[i], props = arrays[i + 1];
4564
5080
  j = k = 0;
@@ -4569,34 +5085,34 @@ var TagadaSDKBundle = (() => {
4569
5085
  matches = regex[j++].exec(ua);
4570
5086
  if (!!matches) {
4571
5087
  for (p = 0; p < props.length; p++) {
4572
- match = matches[++k];
5088
+ match2 = matches[++k];
4573
5089
  q = props[p];
4574
5090
  if (typeof q === TYPEOF.OBJECT && q.length > 0) {
4575
5091
  if (q.length === 2) {
4576
5092
  if (typeof q[1] == TYPEOF.FUNCTION) {
4577
- this[q[0]] = q[1].call(this, match);
5093
+ this[q[0]] = q[1].call(this, match2);
4578
5094
  } else {
4579
5095
  this[q[0]] = q[1];
4580
5096
  }
4581
5097
  } else if (q.length >= 3) {
4582
5098
  if (typeof q[1] === TYPEOF.FUNCTION && !(q[1].exec && q[1].test)) {
4583
5099
  if (q.length > 3) {
4584
- this[q[0]] = match ? q[1].apply(this, q.slice(2)) : void 0;
5100
+ this[q[0]] = match2 ? q[1].apply(this, q.slice(2)) : void 0;
4585
5101
  } else {
4586
- this[q[0]] = match ? q[1].call(this, match, q[2]) : void 0;
5102
+ this[q[0]] = match2 ? q[1].call(this, match2, q[2]) : void 0;
4587
5103
  }
4588
5104
  } else {
4589
5105
  if (q.length == 3) {
4590
- this[q[0]] = match ? match.replace(q[1], q[2]) : void 0;
5106
+ this[q[0]] = match2 ? match2.replace(q[1], q[2]) : void 0;
4591
5107
  } else if (q.length == 4) {
4592
- this[q[0]] = match ? q[3].call(this, match.replace(q[1], q[2])) : void 0;
5108
+ this[q[0]] = match2 ? q[3].call(this, match2.replace(q[1], q[2])) : void 0;
4593
5109
  } else if (q.length > 4) {
4594
- this[q[0]] = match ? q[3].apply(this, [match.replace(q[1], q[2])].concat(q.slice(4))) : void 0;
5110
+ this[q[0]] = match2 ? q[3].apply(this, [match2.replace(q[1], q[2])].concat(q.slice(4))) : void 0;
4595
5111
  }
4596
5112
  }
4597
5113
  }
4598
5114
  } else {
4599
- this[q] = match ? match : void 0;
5115
+ this[q] = match2 ? match2 : void 0;
4600
5116
  }
4601
5117
  }
4602
5118
  }
@@ -8750,7 +9266,7 @@ var TagadaSDKBundle = (() => {
8750
9266
  }
8751
9267
  }
8752
9268
  updateSessionState(response, sessionData) {
8753
- var _a, _b, _c, _d, _e, _f, _g, _h, _i;
9269
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
8754
9270
  if (response.store) {
8755
9271
  const storeData = response.store;
8756
9272
  const storeConfig = __spreadProps(__spreadValues({}, response.store), {
@@ -8788,8 +9304,10 @@ var TagadaSDKBundle = (() => {
8788
9304
  customer: (_g = response.customer) != null ? _g : null,
8789
9305
  auth: authState
8790
9306
  });
8791
- if (this.funnel && sessionData.customerId && ((_h = response.store) == null ? void 0 : _h.id)) {
8792
- const accountId = response.store.accountId || ((_i = this.state.pluginConfig) == null ? void 0 : _i.accountId) || sessionData.accountId || "";
9307
+ const funnelFeature = (_h = this.config.features) == null ? void 0 : _h.funnel;
9308
+ const skipAutoInit = typeof funnelFeature === "object" && funnelFeature.skipAutoInit;
9309
+ if (this.funnel && !skipAutoInit && sessionData.customerId && ((_i = response.store) == null ? void 0 : _i.id)) {
9310
+ const accountId = response.store.accountId || ((_j = this.state.pluginConfig) == null ? void 0 : _j.accountId) || sessionData.accountId || "";
8793
9311
  if (accountId) {
8794
9312
  const urlParams = new URLSearchParams(typeof window !== "undefined" ? window.location.search : "");
8795
9313
  const funnelId = urlParams.get("funnelId") || void 0;
@@ -9249,6 +9767,14 @@ var TagadaSDKBundle = (() => {
9249
9767
  async getAppliedPromotions(checkoutSessionId) {
9250
9768
  return this.apiClient.get("/api/v1/checkout-sessions/".concat(checkoutSessionId, "/promotions"));
9251
9769
  }
9770
+ /**
9771
+ * Replace all session line items (full rewrite)
9772
+ */
9773
+ async replaceSessionLineItems(checkoutSessionId, lineItems) {
9774
+ return this.apiClient.post("/api/v1/checkout-sessions/".concat(checkoutSessionId, "/line-items"), {
9775
+ lineItems
9776
+ });
9777
+ }
9252
9778
  /**
9253
9779
  * Update line items
9254
9780
  */
@@ -9310,118 +9836,696 @@ var TagadaSDKBundle = (() => {
9310
9836
  };
9311
9837
 
9312
9838
  // src/v2/standalone/index.ts
9313
- init_funnel();
9839
+ init_funnelClient();
9314
9840
 
9315
- // src/v2/core/utils/products.ts
9316
- var ProductsUtils = class {
9841
+ // src/v2/core/resources/shippingRates.ts
9842
+ var ShippingRatesResource = class {
9843
+ constructor(apiClient) {
9844
+ this.apiClient = apiClient;
9845
+ }
9317
9846
  /**
9318
- * Find a variant by ID within products
9847
+ * Get shipping rates for a checkout session
9319
9848
  */
9320
- static findVariant(products, variantId) {
9321
- for (const product of products) {
9322
- const variant = product.variants.find((v) => v.id === variantId);
9323
- if (variant) {
9324
- return variant;
9325
- }
9326
- }
9327
- return null;
9849
+ async getShippingRates(sessionId) {
9850
+ return this.apiClient.get("/api/v1/checkout-sessions/".concat(sessionId, "/shipping-rates"));
9328
9851
  }
9329
9852
  /**
9330
- * Get price for a variant in a specific currency
9853
+ * Set selected shipping rate for a checkout session
9331
9854
  */
9332
- static getVariantPrice(variant, currency = "USD") {
9333
- const price = variant.prices.find((p) => p.currency === currency);
9334
- if (price) {
9335
- return price;
9336
- }
9337
- const defaultPrice = variant.prices.find((p) => p.default);
9338
- if (defaultPrice) {
9339
- return defaultPrice;
9855
+ async setShippingRate(sessionId, shippingRateId) {
9856
+ return this.apiClient.post("/api/v1/checkout-sessions/".concat(sessionId, "/shipping-rate"), {
9857
+ shippingRateId
9858
+ });
9859
+ }
9860
+ /**
9861
+ * Preview shipping rates for a country without updating session
9862
+ * Useful for showing rates before user enters email
9863
+ */
9864
+ async previewShippingRates(sessionId, params) {
9865
+ const queryParams = new URLSearchParams({ countryCode: params.countryCode });
9866
+ if (params.stateCode) {
9867
+ queryParams.set("stateCode", params.stateCode);
9340
9868
  }
9341
- return variant.prices[0] || null;
9869
+ return this.apiClient.get(
9870
+ "/api/v1/checkout-sessions/".concat(sessionId, "/shipping-rates/preview?").concat(queryParams.toString())
9871
+ );
9872
+ }
9873
+ };
9874
+
9875
+ // src/v2/core/resources/payments.ts
9876
+ var PaymentsResource = class {
9877
+ constructor(apiClient) {
9878
+ this.apiClient = apiClient;
9342
9879
  }
9343
9880
  /**
9344
- * Get all variants from products
9881
+ * Create payment instrument
9345
9882
  */
9346
- static getAllVariants(products) {
9347
- const allVariants = [];
9348
- for (const product of products) {
9349
- if (product.variants) {
9350
- for (const variant of product.variants) {
9351
- allVariants.push({ product, variant });
9352
- }
9883
+ async createPaymentInstrument(paymentInstrumentData) {
9884
+ return this.apiClient.post("/api/v1/payment/create-payment-instrument", {
9885
+ paymentInstrumentData
9886
+ });
9887
+ }
9888
+ /**
9889
+ * Create card payment instrument
9890
+ */
9891
+ async createCardPaymentInstrument(basisTheory, cardData) {
9892
+ var _a, _b;
9893
+ if (!basisTheory) {
9894
+ throw new Error("Payment processor not initialized");
9895
+ }
9896
+ console.log("Creating card payment instrument");
9897
+ const btResponse = await basisTheory.tokens.create({
9898
+ type: "card",
9899
+ data: __spreadValues({
9900
+ cvc: cardData.cvc,
9901
+ number: Number(cardData.cardNumber.replace(/\s+/g, ""))
9902
+ }, this.getCardMonthAndYear(cardData.expiryDate)),
9903
+ metadata: {
9904
+ nonSensitiveField: "nonSensitiveValue"
9353
9905
  }
9354
- }
9355
- return allVariants;
9906
+ });
9907
+ const { expiration_month, expiration_year } = this.getCardMonthAndYear(cardData.expiryDate);
9908
+ const paymentInstrumentData = {
9909
+ type: btResponse.type,
9910
+ card: {
9911
+ maskedCardNumber: ((_b = (_a = btResponse.enrichments) == null ? void 0 : _a.cardDetails) == null ? void 0 : _b.bin) ? "".concat(btResponse.enrichments.cardDetails.bin, "****").concat(btResponse.enrichments.cardDetails.last4) : cardData.cardNumber.replace(/\d(?=\d{4})/g, "*"),
9912
+ expirationMonth: expiration_month,
9913
+ expirationYear: expiration_year
9914
+ },
9915
+ token: btResponse.id
9916
+ };
9917
+ const response = await this.apiClient.post(
9918
+ "/api/v1/payment/create-payment-instrument",
9919
+ { paymentInstrumentData }
9920
+ );
9921
+ console.log("Payment instrument created:", response);
9922
+ return response;
9356
9923
  }
9357
9924
  /**
9358
- * Filter variants by predicate
9925
+ * Create Apple Pay payment instrument
9359
9926
  */
9360
- static filterVariants(products, predicate) {
9361
- const filtered = [];
9362
- for (const product of products) {
9363
- if (product.variants) {
9364
- for (const variant of product.variants) {
9365
- if (predicate(variant, product)) {
9366
- filtered.push({ product, variant });
9367
- }
9368
- }
9927
+ async createApplePayPaymentInstrument(basisTheory, applePayToken) {
9928
+ if (!basisTheory) {
9929
+ throw new Error("Payment processor not initialized");
9930
+ }
9931
+ if (!applePayToken.id) {
9932
+ throw new Error("Apple Pay token is missing");
9933
+ }
9934
+ const paymentInstrumentData = {
9935
+ type: "apple_pay",
9936
+ token: applePayToken.id,
9937
+ dpanType: applePayToken.type,
9938
+ card: {
9939
+ bin: applePayToken.card.bin,
9940
+ last4: applePayToken.card.last4,
9941
+ expirationMonth: applePayToken.card.expiration_month,
9942
+ expirationYear: applePayToken.card.expiration_year,
9943
+ brand: applePayToken.card.brand
9369
9944
  }
9945
+ };
9946
+ const response = await this.apiClient.post(
9947
+ "/api/v1/payment/create-payment-instrument",
9948
+ { paymentInstrumentData }
9949
+ );
9950
+ return response;
9951
+ }
9952
+ /**
9953
+ * Create Google Pay payment instrument
9954
+ */
9955
+ async createGooglePayPaymentInstrument(basisTheory, googlePayToken) {
9956
+ var _a;
9957
+ if (!basisTheory) {
9958
+ throw new Error("Payment processor not initialized");
9959
+ }
9960
+ if (!googlePayToken.id) {
9961
+ throw new Error("Google Pay token is missing");
9962
+ }
9963
+ const paymentInstrumentData = {
9964
+ type: "google_pay",
9965
+ token: googlePayToken.id,
9966
+ dpanType: googlePayToken.type,
9967
+ card: {
9968
+ bin: googlePayToken.card.bin,
9969
+ last4: googlePayToken.card.last4,
9970
+ expirationMonth: googlePayToken.card.expiration_month,
9971
+ expirationYear: googlePayToken.card.expiration_year,
9972
+ brand: googlePayToken.card.brand
9973
+ },
9974
+ authMethod: (_a = googlePayToken == null ? void 0 : googlePayToken.details) == null ? void 0 : _a.auth_method
9975
+ };
9976
+ const response = await this.apiClient.post(
9977
+ "/api/v1/payment/create-payment-instrument",
9978
+ { paymentInstrumentData }
9979
+ );
9980
+ return response;
9981
+ }
9982
+ /**
9983
+ * Create APM payment instrument (Klarna, Afterpay, PayPal, etc.)
9984
+ */
9985
+ async createApmPaymentInstrument(apmData) {
9986
+ console.log("Creating APM payment instrument:", apmData);
9987
+ const paymentInstrumentData = {
9988
+ type: "apm",
9989
+ provider: apmData.provider,
9990
+ paymentMethod: apmData.paymentMethod,
9991
+ processorId: apmData.processorId
9992
+ };
9993
+ const response = await this.apiClient.post(
9994
+ "/api/v1/payment/create-payment-instrument",
9995
+ { paymentInstrumentData }
9996
+ );
9997
+ console.log("APM payment instrument created:", response);
9998
+ return response;
9999
+ }
10000
+ /**
10001
+ * Helper function to format expiry date
10002
+ */
10003
+ getCardMonthAndYear(expiryDate) {
10004
+ const [month, year] = expiryDate.split("/");
10005
+ const currentYear = (/* @__PURE__ */ new Date()).getFullYear();
10006
+ const century = Math.floor(currentYear / 100) * 100;
10007
+ const fullYear = Number(year) + century;
10008
+ return {
10009
+ expiration_month: Number(month),
10010
+ expiration_year: fullYear
10011
+ };
10012
+ }
10013
+ /**
10014
+ * Process payment directly with checkout session
10015
+ */
10016
+ async processPaymentDirect(checkoutSessionId, paymentInstrumentId, threedsSessionId, options = {}) {
10017
+ console.log("[PaymentsResource] processPaymentDirect START", options.paymentFlowId ? "(flow: ".concat(options.paymentFlowId, ")") : "");
10018
+ console.log("[PaymentsResource] Full options object:", JSON.stringify(options, null, 2));
10019
+ console.log("[PaymentsResource] processorId:", options.processorId, "paymentMethod:", options.paymentMethod);
10020
+ try {
10021
+ const requestBody = __spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({
10022
+ checkoutSessionId,
10023
+ paymentInstrumentId
10024
+ }, threedsSessionId && { threedsSessionId }), options.initiatedBy && { initiatedBy: options.initiatedBy }), options.source && { source: options.source }), options.paymentFlowId && { paymentFlowId: options.paymentFlowId }), options.processorId && { processorId: options.processorId }), options.paymentMethod && { paymentMethod: options.paymentMethod });
10025
+ console.log("[PaymentsResource] Request body being sent:", JSON.stringify(requestBody, null, 2));
10026
+ const response = await this.apiClient.post("/api/public/v1/checkout/pay-v2", requestBody);
10027
+ console.log("[PaymentsResource] processPaymentDirect SUCCESS:", response);
10028
+ return response;
10029
+ } catch (error) {
10030
+ console.error("[PaymentsResource] processPaymentDirect ERROR:", error);
10031
+ throw error;
9370
10032
  }
9371
- return filtered;
9372
10033
  }
9373
- };
9374
-
9375
- // src/v2/core/utils/order.ts
9376
- var OrderUtils = class {
9377
10034
  /**
9378
- * Get order line items
10035
+ * Get card payment instruments for customer
9379
10036
  */
9380
- static getOrderLineItems(order) {
9381
- return order.items || [];
10037
+ async getCardPaymentInstruments() {
10038
+ return this.apiClient.get("/api/v1/payment-instruments/customer");
9382
10039
  }
9383
10040
  /**
9384
- * Get order total
10041
+ * Mark payment action as processed
9385
10042
  */
9386
- static getOrderTotal(order) {
9387
- return order.paidAmount || 0;
10043
+ async markPaymentActionProcessed(paymentId) {
10044
+ return this.apiClient.post("/api/v1/payments/require-action/processed", {
10045
+ paymentId
10046
+ });
9388
10047
  }
9389
10048
  /**
9390
- * Get order status
10049
+ * Get payment status
9391
10050
  */
9392
- static getOrderStatus(order) {
9393
- return order.status || "unknown";
10051
+ async getPaymentStatus(paymentId) {
10052
+ return this.apiClient.get("/api/v1/payments/".concat(paymentId));
9394
10053
  }
9395
10054
  /**
9396
- * Check if order is completed
10055
+ * Retrieve payment status from processor
10056
+ * Used for external payment flows that require server-side status checks
9397
10057
  */
9398
- static isOrderCompleted(order) {
9399
- return order.status === "completed" || order.status === "fulfilled";
10058
+ async retrievePayment(paymentId) {
10059
+ return this.apiClient.post("/api/v1/payments/retrieve", {
10060
+ paymentId
10061
+ });
10062
+ }
10063
+ async saveRadarSession(data) {
10064
+ return this.apiClient.post("/api/v1/radar-sessions", data);
9400
10065
  }
9401
10066
  /**
9402
- * Check if order is pending
10067
+ * Complete payment after an action (3DS, radar, etc.)
10068
+ * This resumes the payment flow that was paused for additional authentication/verification
9403
10069
  */
9404
- static isOrderPending(order) {
9405
- return order.status === "pending" || order.status === "processing";
10070
+ async completePaymentAfterAction(paymentId) {
10071
+ return this.apiClient.post("/api/v1/payments/complete-after-3ds", {
10072
+ paymentId
10073
+ });
9406
10074
  }
9407
10075
  /**
9408
- * Check if order is cancelled
10076
+ * Update 3DS session status (used for Airwallex 3DS return handling)
9409
10077
  */
9410
- static isOrderCancelled(order) {
9411
- return order.status === "cancelled" || order.status === "refunded";
10078
+ async updateThreedsStatus(data) {
10079
+ return this.apiClient.post("/api/v1/threeds/status", data);
9412
10080
  }
9413
10081
  };
9414
10082
 
9415
- // src/v2/core/utils/currency.ts
9416
- function formatMoney(amountMinorUnits, currencyCode = "USD", locale = "en-US") {
9417
- const decimalPlaces = CurrencyUtils.getDecimalPlaces(currencyCode);
9418
- let value;
9419
- if (decimalPlaces === 0) {
9420
- value = amountMinorUnits / 100;
9421
- } else {
9422
- value = amountMinorUnits / Math.pow(10, decimalPlaces);
10083
+ // src/v2/core/resources/orders.ts
10084
+ var OrdersResource = class {
10085
+ constructor(apiClient) {
10086
+ this.apiClient = apiClient;
9423
10087
  }
9424
- try {
10088
+ /**
10089
+ * Fetch order by ID
10090
+ */
10091
+ async getOrder(orderId) {
10092
+ const response = await this.apiClient.get("/api/v1/orders/".concat(orderId));
10093
+ if (typeof response === "object" && response !== null && "success" in response && response.success === false) {
10094
+ throw new Error(response.error || "Failed to fetch order");
10095
+ }
10096
+ const orderData = typeof response === "object" && response !== null && "order" in response ? response.order : response;
10097
+ if (!orderData) {
10098
+ throw new Error("Order not found");
10099
+ }
10100
+ return orderData;
10101
+ }
10102
+ /**
10103
+ * Create a new order
10104
+ */
10105
+ async createOrder(checkoutSessionId) {
10106
+ return this.apiClient.post("/api/v1/orders", {
10107
+ checkoutSessionId
10108
+ });
10109
+ }
10110
+ /**
10111
+ * Update order status
10112
+ */
10113
+ async updateOrderStatus(orderId, status) {
10114
+ return this.apiClient.patch("/api/v1/orders/".concat(orderId, "/status"), {
10115
+ status
10116
+ });
10117
+ }
10118
+ /**
10119
+ * Add items to an order
10120
+ */
10121
+ async addOrderItems(orderId, items) {
10122
+ return this.apiClient.post("/api/v1/orders/".concat(orderId, "/items"), {
10123
+ items
10124
+ });
10125
+ }
10126
+ /**
10127
+ * Get order line items
10128
+ */
10129
+ async getOrderLineItems(orderId) {
10130
+ const order = await this.getOrder(orderId);
10131
+ return order.items || [];
10132
+ }
10133
+ };
10134
+
10135
+ // src/data/iso3166.ts
10136
+ var GEODATA_CDN_BASE = "https://cvwnizdbugpz6jwk.public.blob.vercel-storage.com/geodata/v1";
10137
+ var countriesCache = /* @__PURE__ */ new Map();
10138
+ var regionsCache = /* @__PURE__ */ new Map();
10139
+ var inflightCountries = /* @__PURE__ */ new Map();
10140
+ var inflightRegions = /* @__PURE__ */ new Map();
10141
+ async function fetchCountriesRaw(language) {
10142
+ const cached = countriesCache.get(language);
10143
+ if (cached) return cached;
10144
+ let inflight = inflightCountries.get(language);
10145
+ if (inflight) return inflight;
10146
+ inflight = (async () => {
10147
+ const url = "".concat(GEODATA_CDN_BASE, "/").concat(language, "/countries.json");
10148
+ const res = await fetch(url);
10149
+ if (!res.ok) throw new Error("Geodata fetch failed: ".concat(url, " (").concat(res.status, ")"));
10150
+ const data = await res.json();
10151
+ countriesCache.set(language, data);
10152
+ inflightCountries.delete(language);
10153
+ return data;
10154
+ })();
10155
+ inflightCountries.set(language, inflight);
10156
+ return inflight;
10157
+ }
10158
+ async function fetchRegionsRaw(language) {
10159
+ const cached = regionsCache.get(language);
10160
+ if (cached) return cached;
10161
+ let inflight = inflightRegions.get(language);
10162
+ if (inflight) return inflight;
10163
+ inflight = (async () => {
10164
+ const url = "".concat(GEODATA_CDN_BASE, "/").concat(language, "/regions.json");
10165
+ const res = await fetch(url);
10166
+ if (!res.ok) throw new Error("Geodata fetch failed: ".concat(url, " (").concat(res.status, ")"));
10167
+ const data = await res.json();
10168
+ regionsCache.set(language, data);
10169
+ inflightRegions.delete(language);
10170
+ return data;
10171
+ })();
10172
+ inflightRegions.set(language, inflight);
10173
+ return inflight;
10174
+ }
10175
+ function getCountriesCached(language) {
10176
+ return countriesCache.get(language) || countriesCache.get("en") || {};
10177
+ }
10178
+ function getRegionsCached(language) {
10179
+ return regionsCache.get(language) || regionsCache.get("en") || {};
10180
+ }
10181
+ async function ensureGeoDataLoaded(language = "en") {
10182
+ await Promise.all([fetchCountriesRaw(language), fetchRegionsRaw(language)]);
10183
+ }
10184
+ var getCountries = (language = "en") => {
10185
+ const raw = getCountriesCached(language);
10186
+ return Object.entries(raw).map(([code, c]) => ({
10187
+ code,
10188
+ name: c.n,
10189
+ iso3: c.i3,
10190
+ numeric: c.nu,
10191
+ uniqueKey: "country-".concat(code)
10192
+ })).sort((a, b) => a.name.localeCompare(b.name));
10193
+ };
10194
+ var getStatesForCountry = (countryCode, language = "en") => {
10195
+ const raw = getRegionsCached(language);
10196
+ const tuples = raw[countryCode];
10197
+ if (!tuples) return [];
10198
+ return tuples.map(([iso, name], i) => ({
10199
+ code: iso,
10200
+ name,
10201
+ countryCode,
10202
+ uniqueKey: "state-".concat(countryCode, "-").concat(iso, "-").concat(i)
10203
+ })).sort((a, b) => a.name.localeCompare(b.name));
10204
+ };
10205
+ function isLanguageRegistered(language) {
10206
+ return countriesCache.has(language);
10207
+ }
10208
+ function getRegisteredLanguages() {
10209
+ return [...countriesCache.keys()];
10210
+ }
10211
+ async function importLanguage(language) {
10212
+ await ensureGeoDataLoaded(language);
10213
+ }
10214
+ if (typeof globalThis !== "undefined" && typeof fetch !== "undefined") {
10215
+ ensureGeoDataLoaded("en").catch(() => {
10216
+ });
10217
+ }
10218
+
10219
+ // src/v2/core/isoData.ts
10220
+ var ISODataCore = class {
10221
+ /**
10222
+ * Get countries data for a specific language
10223
+ */
10224
+ static getCountriesData(language = "en") {
10225
+ try {
10226
+ const countriesArray = getCountries(language);
10227
+ const countries = {};
10228
+ countriesArray.forEach((country) => {
10229
+ countries[country.code] = {
10230
+ iso: country.code,
10231
+ iso3: country.iso3 || "",
10232
+ numeric: country.numeric || 0,
10233
+ name: country.name
10234
+ };
10235
+ });
10236
+ return countries;
10237
+ } catch (error) {
10238
+ console.error("Failed to load ISO data for language: ".concat(language), error);
10239
+ return {};
10240
+ }
10241
+ }
10242
+ /**
10243
+ * Get regions for a specific country
10244
+ */
10245
+ static getRegions(countryCode, language = "en") {
10246
+ try {
10247
+ const states = getStatesForCountry(countryCode, language);
10248
+ return states.map((state) => ({
10249
+ iso: state.code,
10250
+ name: state.name
10251
+ }));
10252
+ } catch (e) {
10253
+ return [];
10254
+ }
10255
+ }
10256
+ /**
10257
+ * Find a specific region by ISO code
10258
+ */
10259
+ static findRegion(countryCode, regionCode, language = "en") {
10260
+ var _a;
10261
+ const regions = this.getRegions(countryCode, language);
10262
+ return (_a = regions.find((region) => region.iso === regionCode)) != null ? _a : null;
10263
+ }
10264
+ /**
10265
+ * Map Google Places state to ISO region (proven 100% success rate)
10266
+ */
10267
+ static mapGoogleToISO(googleState, googleStateLong, countryCode, language = "en") {
10268
+ const regions = this.getRegions(countryCode, language);
10269
+ if (regions.length === 0) return null;
10270
+ let match2 = regions.find((r) => r.iso === googleState);
10271
+ if (match2) return match2;
10272
+ match2 = regions.find((r) => r.name.toLowerCase() === googleState.toLowerCase());
10273
+ if (match2) return match2;
10274
+ match2 = regions.find((r) => r.name.toLowerCase() === googleStateLong.toLowerCase());
10275
+ if (match2) return match2;
10276
+ match2 = regions.find(
10277
+ (r) => r.name.toLowerCase().includes(googleStateLong.toLowerCase()) || googleStateLong.toLowerCase().includes(r.name.toLowerCase())
10278
+ );
10279
+ return match2 != null ? match2 : null;
10280
+ }
10281
+ /**
10282
+ * Check if language is registered
10283
+ */
10284
+ static isLanguageRegistered(language) {
10285
+ return isLanguageRegistered(language);
10286
+ }
10287
+ /**
10288
+ * Get registered languages
10289
+ */
10290
+ static getRegisteredLanguages() {
10291
+ return getRegisteredLanguages();
10292
+ }
10293
+ /**
10294
+ * Import language data
10295
+ */
10296
+ static async importLanguage(language) {
10297
+ return importLanguage(language);
10298
+ }
10299
+ /**
10300
+ * Get available languages for ISO data
10301
+ */
10302
+ static getAvailableLanguages() {
10303
+ return ["en", "ru", "de", "fr", "es", "zh", "hi", "pt", "ja", "ar", "it", "he"];
10304
+ }
10305
+ };
10306
+
10307
+ // src/v2/core/googleAutocomplete.ts
10308
+ var GoogleAutocompleteCore = class {
10309
+ /**
10310
+ * Initialize Google Places API
10311
+ */
10312
+ static initialize(apiKey) {
10313
+ var _a, _b;
10314
+ this.apiKey = apiKey;
10315
+ if (typeof window !== "undefined" && ((_b = (_a = window.google) == null ? void 0 : _a.maps) == null ? void 0 : _b.places)) {
10316
+ this.service = new window.google.maps.places.AutocompleteService();
10317
+ }
10318
+ }
10319
+ /**
10320
+ * Search for places
10321
+ */
10322
+ static async searchPlaces(input, options = {}) {
10323
+ if (!this.service || !input.trim()) {
10324
+ return [];
10325
+ }
10326
+ return new Promise((resolve, reject) => {
10327
+ this.service.getPlacePredictions(
10328
+ {
10329
+ input,
10330
+ types: options.types || ["address"],
10331
+ componentRestrictions: options.componentRestrictions
10332
+ },
10333
+ (predictions, status) => {
10334
+ var _a, _b, _c;
10335
+ if (status === ((_c = (_b = (_a = window.google) == null ? void 0 : _a.maps) == null ? void 0 : _b.places) == null ? void 0 : _c.PlacesServiceStatus.OK) && predictions) {
10336
+ resolve(predictions);
10337
+ } else {
10338
+ resolve([]);
10339
+ }
10340
+ }
10341
+ );
10342
+ });
10343
+ }
10344
+ /**
10345
+ * Get place details
10346
+ */
10347
+ static async getPlaceDetails(placeId) {
10348
+ var _a, _b;
10349
+ if (typeof window === "undefined" || !((_b = (_a = window.google) == null ? void 0 : _a.maps) == null ? void 0 : _b.places)) {
10350
+ return null;
10351
+ }
10352
+ return new Promise((resolve, reject) => {
10353
+ const service = new window.google.maps.places.PlacesService(
10354
+ document.createElement("div")
10355
+ );
10356
+ service.getDetails(
10357
+ {
10358
+ placeId,
10359
+ fields: ["place_id", "formatted_address", "address_components", "geometry"]
10360
+ },
10361
+ (place, status) => {
10362
+ var _a2, _b2, _c;
10363
+ if (status === ((_c = (_b2 = (_a2 = window.google) == null ? void 0 : _a2.maps) == null ? void 0 : _b2.places) == null ? void 0 : _c.PlacesServiceStatus.OK) && place) {
10364
+ resolve(place);
10365
+ } else {
10366
+ resolve(null);
10367
+ }
10368
+ }
10369
+ );
10370
+ });
10371
+ }
10372
+ /**
10373
+ * Extract address components from place details
10374
+ */
10375
+ static extractAddressComponents(placeDetails) {
10376
+ const components = {};
10377
+ for (const component of placeDetails.address_components) {
10378
+ const types = component.types;
10379
+ if (types.includes("street_number")) {
10380
+ components.streetNumber = component.long_name;
10381
+ } else if (types.includes("route")) {
10382
+ components.route = component.long_name;
10383
+ } else if (types.includes("locality")) {
10384
+ components.city = component.long_name;
10385
+ components.locality = component.long_name;
10386
+ } else if (types.includes("administrative_area_level_2")) {
10387
+ components.administrativeAreaLevel2 = component.short_name;
10388
+ components.administrativeAreaLevel2Long = component.long_name;
10389
+ if (!components.city) {
10390
+ components.city = component.long_name;
10391
+ components.locality = component.long_name;
10392
+ }
10393
+ } else if (types.includes("administrative_area_level_1")) {
10394
+ components.state = component.long_name;
10395
+ components.administrativeAreaLevel1 = component.short_name;
10396
+ components.administrativeAreaLevel1Long = component.long_name;
10397
+ } else if (types.includes("postal_code")) {
10398
+ components.postalCode = component.long_name;
10399
+ } else if (types.includes("country")) {
10400
+ components.country = component.long_name;
10401
+ components.countryCode = component.short_name;
10402
+ components.iso = component.short_name;
10403
+ }
10404
+ }
10405
+ if (!components.administrativeAreaLevel1 && components.administrativeAreaLevel2) {
10406
+ components.state = components.administrativeAreaLevel2Long || components.administrativeAreaLevel2;
10407
+ components.administrativeAreaLevel1 = components.administrativeAreaLevel2;
10408
+ components.administrativeAreaLevel1Long = components.administrativeAreaLevel2Long;
10409
+ }
10410
+ return components;
10411
+ }
10412
+ };
10413
+ GoogleAutocompleteCore.apiKey = null;
10414
+ GoogleAutocompleteCore.service = null;
10415
+
10416
+ // src/v2/standalone/index.ts
10417
+ init_funnel();
10418
+
10419
+ // src/v2/core/utils/products.ts
10420
+ var ProductsUtils = class {
10421
+ /**
10422
+ * Find a variant by ID within products
10423
+ */
10424
+ static findVariant(products, variantId) {
10425
+ for (const product of products) {
10426
+ const variant = product.variants.find((v) => v.id === variantId);
10427
+ if (variant) {
10428
+ return variant;
10429
+ }
10430
+ }
10431
+ return null;
10432
+ }
10433
+ /**
10434
+ * Get price for a variant in a specific currency
10435
+ */
10436
+ static getVariantPrice(variant, currency = "USD") {
10437
+ const price = variant.prices.find((p) => p.currency === currency);
10438
+ if (price) {
10439
+ return price;
10440
+ }
10441
+ const defaultPrice = variant.prices.find((p) => p.default);
10442
+ if (defaultPrice) {
10443
+ return defaultPrice;
10444
+ }
10445
+ return variant.prices[0] || null;
10446
+ }
10447
+ /**
10448
+ * Get all variants from products
10449
+ */
10450
+ static getAllVariants(products) {
10451
+ const allVariants = [];
10452
+ for (const product of products) {
10453
+ if (product.variants) {
10454
+ for (const variant of product.variants) {
10455
+ allVariants.push({ product, variant });
10456
+ }
10457
+ }
10458
+ }
10459
+ return allVariants;
10460
+ }
10461
+ /**
10462
+ * Filter variants by predicate
10463
+ */
10464
+ static filterVariants(products, predicate) {
10465
+ const filtered = [];
10466
+ for (const product of products) {
10467
+ if (product.variants) {
10468
+ for (const variant of product.variants) {
10469
+ if (predicate(variant, product)) {
10470
+ filtered.push({ product, variant });
10471
+ }
10472
+ }
10473
+ }
10474
+ }
10475
+ return filtered;
10476
+ }
10477
+ };
10478
+
10479
+ // src/v2/core/utils/order.ts
10480
+ var OrderUtils = class {
10481
+ /**
10482
+ * Get order line items
10483
+ */
10484
+ static getOrderLineItems(order) {
10485
+ return order.items || [];
10486
+ }
10487
+ /**
10488
+ * Get order total
10489
+ */
10490
+ static getOrderTotal(order) {
10491
+ return order.paidAmount || 0;
10492
+ }
10493
+ /**
10494
+ * Get order status
10495
+ */
10496
+ static getOrderStatus(order) {
10497
+ return order.status || "unknown";
10498
+ }
10499
+ /**
10500
+ * Check if order is completed
10501
+ */
10502
+ static isOrderCompleted(order) {
10503
+ return order.status === "completed" || order.status === "fulfilled";
10504
+ }
10505
+ /**
10506
+ * Check if order is pending
10507
+ */
10508
+ static isOrderPending(order) {
10509
+ return order.status === "pending" || order.status === "processing";
10510
+ }
10511
+ /**
10512
+ * Check if order is cancelled
10513
+ */
10514
+ static isOrderCancelled(order) {
10515
+ return order.status === "cancelled" || order.status === "refunded";
10516
+ }
10517
+ };
10518
+
10519
+ // src/v2/core/utils/currency.ts
10520
+ function formatMoney(amountMinorUnits, currencyCode = "USD", locale = "en-US") {
10521
+ const decimalPlaces = CurrencyUtils.getDecimalPlaces(currencyCode);
10522
+ let value;
10523
+ if (decimalPlaces === 0) {
10524
+ value = amountMinorUnits / 100;
10525
+ } else {
10526
+ value = amountMinorUnits / Math.pow(10, decimalPlaces);
10527
+ }
10528
+ try {
9425
10529
  return new Intl.NumberFormat(locale, {
9426
10530
  style: "currency",
9427
10531
  currency: currencyCode,
@@ -9710,18 +10814,23 @@ var TagadaSDKBundle = (() => {
9710
10814
  return ((_a = checkoutData.checkoutSession) == null ? void 0 : _a.id) || "";
9711
10815
  }
9712
10816
  /**
9713
- * Get checkout line items
10817
+ * Get checkout line items
9714
10818
  */
9715
10819
  static getLineItems(checkoutData) {
9716
10820
  var _a;
9717
- return ((_a = checkoutData.checkoutSession) == null ? void 0 : _a.lineItems) || [];
10821
+ const lineItems = (_a = checkoutData.checkoutSession) == null ? void 0 : _a.lineItems;
10822
+ if (!Array.isArray(lineItems)) {
10823
+ return [];
10824
+ }
10825
+ return lineItems;
9718
10826
  }
9719
10827
  /**
9720
10828
  * Get checkout total
9721
10829
  */
9722
10830
  static getTotal(checkoutData) {
9723
10831
  var _a;
9724
- return ((_a = checkoutData.checkoutSession) == null ? void 0 : _a.totalPrice) || 0;
10832
+ const totalPrice = (_a = checkoutData.checkoutSession) == null ? void 0 : _a.totalPrice;
10833
+ return typeof totalPrice === "number" ? totalPrice : 0;
9725
10834
  }
9726
10835
  /**
9727
10836
  * Check if customer is club member
@@ -9912,8 +11021,597 @@ var TagadaSDKBundle = (() => {
9912
11021
  };
9913
11022
  }
9914
11023
 
11024
+ // src/v2/core/pathRemapping.ts
11025
+ var import_path_to_regexp = __toESM(require_dist());
11026
+ var internalPathCache = void 0;
11027
+ var isBrowser = typeof window !== "undefined" && typeof document !== "undefined";
11028
+ var originalPushState = isBrowser ? history.pushState.bind(history) : null;
11029
+ var originalReplaceState = isBrowser ? history.replaceState.bind(history) : null;
11030
+ function clearCache() {
11031
+ internalPathCache = void 0;
11032
+ }
11033
+ if (isBrowser) {
11034
+ window.addEventListener("popstate", clearCache);
11035
+ window.addEventListener("hashchange", clearCache);
11036
+ history.pushState = function(...args) {
11037
+ clearCache();
11038
+ return originalPushState.apply(this, args);
11039
+ };
11040
+ history.replaceState = function(...args) {
11041
+ clearCache();
11042
+ return originalReplaceState.apply(this, args);
11043
+ };
11044
+ }
11045
+ function getInternalPath() {
11046
+ if (!isBrowser) {
11047
+ if (typeof process !== "undefined" && true) {
11048
+ console.warn("[TagadaPay SDK] getInternalPath() called in SSR context");
11049
+ }
11050
+ return null;
11051
+ }
11052
+ if (internalPathCache !== void 0) {
11053
+ console.log("[TagadaPay SDK] \u{1F4E6} Returning cached internal path:", internalPathCache);
11054
+ return internalPathCache;
11055
+ }
11056
+ console.log("[TagadaPay SDK] \u{1F50D} getInternalPath() called for:", window.location.pathname);
11057
+ try {
11058
+ const isLocalhost = window.location.hostname === "localhost" || window.location.hostname === "127.0.0.1" || window.location.hostname.endsWith(".localhost");
11059
+ console.log("[TagadaPay SDK] \u{1F3E0} isLocalhost:", isLocalhost);
11060
+ if (isLocalhost) {
11061
+ const urlParams = new URLSearchParams(window.location.search);
11062
+ const queryRemap = urlParams.get("__remap");
11063
+ console.log("[TagadaPay SDK] \u{1F50D} Query parameter __remap:", queryRemap);
11064
+ if (queryRemap) {
11065
+ internalPathCache = queryRemap;
11066
+ if (typeof process !== "undefined" && true) {
11067
+ console.log("[TagadaPay SDK] \u{1F527} Simulating path remap via query: ".concat(window.location.pathname, " \u2192 ").concat(queryRemap));
11068
+ }
11069
+ return queryRemap;
11070
+ }
11071
+ try {
11072
+ const storageRemap = localStorage.getItem("tagadapay-remap");
11073
+ console.log("[TagadaPay SDK] \u{1F50D} localStorage tagadapay-remap:", storageRemap);
11074
+ if (storageRemap) {
11075
+ try {
11076
+ const remapConfig = JSON.parse(storageRemap);
11077
+ console.log("[TagadaPay SDK] \u{1F4DD} Parsed remap config:", remapConfig);
11078
+ if (remapConfig.externalPath && remapConfig.internalPath) {
11079
+ const currentPath = window.location.pathname;
11080
+ console.log("[TagadaPay SDK] \u{1F50D} Checking if", currentPath, "matches pattern", remapConfig.externalPath);
11081
+ const matchFn = (0, import_path_to_regexp.match)(remapConfig.externalPath, {
11082
+ decode: decodeURIComponent,
11083
+ end: true
11084
+ });
11085
+ const result = matchFn(currentPath);
11086
+ console.log("[TagadaPay SDK] \u{1F3AF} Match result:", result);
11087
+ if (result !== false) {
11088
+ internalPathCache = remapConfig.internalPath;
11089
+ console.log("[TagadaPay SDK] \u2705 Path remap: ".concat(remapConfig.externalPath, " \u2192 ").concat(remapConfig.internalPath));
11090
+ console.log("[TagadaPay SDK] \u2705 Current URL ".concat(currentPath, " matches external pattern"));
11091
+ console.log("[TagadaPay SDK] \u{1F4E6} Caching and returning:", remapConfig.internalPath);
11092
+ return remapConfig.internalPath;
11093
+ } else {
11094
+ console.log("[TagadaPay SDK] \u274C Current URL ".concat(currentPath, " does NOT match external pattern ").concat(remapConfig.externalPath));
11095
+ internalPathCache = null;
11096
+ return null;
11097
+ }
11098
+ } else {
11099
+ console.log("[TagadaPay SDK] \u26A0\uFE0F Parsed config missing externalPath or internalPath");
11100
+ }
11101
+ } catch (jsonError) {
11102
+ console.log("[TagadaPay SDK] \u26A0\uFE0F Failed to parse as JSON, using legacy format:", jsonError);
11103
+ internalPathCache = storageRemap;
11104
+ if (typeof process !== "undefined" && true) {
11105
+ console.log("[TagadaPay SDK] \u{1F527} Simulating path remap (legacy): ".concat(window.location.pathname, " \u2192 ").concat(storageRemap));
11106
+ }
11107
+ return storageRemap;
11108
+ }
11109
+ } else {
11110
+ console.log("[TagadaPay SDK] \u{1F4ED} No localStorage tagadapay-remap found");
11111
+ }
11112
+ } catch (e) {
11113
+ console.log("[TagadaPay SDK] \u274C localStorage error:", e);
11114
+ }
11115
+ }
11116
+ const fullRemapMetaTag = document.querySelector('meta[name="tagadapay-path-remap"]');
11117
+ if (fullRemapMetaTag) {
11118
+ try {
11119
+ const content2 = fullRemapMetaTag.getAttribute("content");
11120
+ if (content2) {
11121
+ const decodedContent = decodeURIComponent(content2);
11122
+ const parsed = JSON.parse(decodedContent);
11123
+ if (parsed.internal) {
11124
+ console.log("[TagadaPay SDK] \u2705 Got internal path from full remap config:", parsed.internal);
11125
+ internalPathCache = parsed.internal;
11126
+ return parsed.internal;
11127
+ }
11128
+ }
11129
+ } catch (e) {
11130
+ console.error("[TagadaPay SDK] Error parsing full remap config:", e);
11131
+ }
11132
+ }
11133
+ const metaTag = document.querySelector('meta[name="x-plugin-internal-path"]');
11134
+ if (!metaTag) {
11135
+ console.log("[TagadaPay SDK] \u2139\uFE0F No path remap meta tags found");
11136
+ internalPathCache = null;
11137
+ return null;
11138
+ }
11139
+ const content = metaTag.getAttribute("content");
11140
+ if (!content || content.trim() === "") {
11141
+ if (typeof process !== "undefined" && true) {
11142
+ console.warn("[TagadaPay SDK] Meta tag found but content is empty");
11143
+ }
11144
+ internalPathCache = null;
11145
+ return null;
11146
+ }
11147
+ const trimmedContent = content.trim();
11148
+ if (!trimmedContent.startsWith("/")) {
11149
+ if (typeof process !== "undefined" && true) {
11150
+ console.warn('[TagadaPay SDK] Invalid internal path format: "'.concat(trimmedContent, '" (must start with /)'));
11151
+ }
11152
+ internalPathCache = null;
11153
+ return null;
11154
+ }
11155
+ console.log("[TagadaPay SDK] \u2705 Got internal path from legacy meta tag:", trimmedContent);
11156
+ internalPathCache = trimmedContent;
11157
+ return trimmedContent;
11158
+ } catch (error) {
11159
+ if (typeof process !== "undefined" && true) {
11160
+ console.error("[TagadaPay SDK] Error reading internal path:", error);
11161
+ }
11162
+ internalPathCache = null;
11163
+ return null;
11164
+ }
11165
+ }
11166
+ function isPathRemapped() {
11167
+ return getInternalPath() !== null;
11168
+ }
11169
+ function getPathInfo() {
11170
+ if (!isBrowser) {
11171
+ throw new Error("[TagadaPay SDK] getPathInfo() cannot be called in SSR context");
11172
+ }
11173
+ try {
11174
+ const externalPath = window.location.pathname;
11175
+ const internalPath = getInternalPath();
11176
+ const query = new URLSearchParams(window.location.search);
11177
+ const hash = window.location.hash.replace(/^#/, "");
11178
+ return {
11179
+ externalPath,
11180
+ internalPath,
11181
+ isRemapped: internalPath !== null,
11182
+ fullUrl: window.location.href,
11183
+ query,
11184
+ hash
11185
+ };
11186
+ } catch (error) {
11187
+ if (typeof process !== "undefined" && true) {
11188
+ console.error("[TagadaPay SDK] Error getting path info:", error);
11189
+ }
11190
+ return {
11191
+ externalPath: "/",
11192
+ internalPath: null,
11193
+ isRemapped: false,
11194
+ fullUrl: "",
11195
+ query: new URLSearchParams(),
11196
+ hash: ""
11197
+ };
11198
+ }
11199
+ }
11200
+ function matchesPathPattern(pathname, pattern) {
11201
+ try {
11202
+ if (pathname === pattern) {
11203
+ return { matched: true, params: {} };
11204
+ }
11205
+ const hasPatternSyntax = pattern.includes(":") || pattern.includes("*") || pattern.includes("{");
11206
+ if (!hasPatternSyntax) {
11207
+ return { matched: pathname === pattern, params: {} };
11208
+ }
11209
+ const matchFn = (0, import_path_to_regexp.match)(pattern, {
11210
+ decode: decodeURIComponent,
11211
+ end: true
11212
+ });
11213
+ const result = matchFn(pathname);
11214
+ if (typeof process !== "undefined" && true) {
11215
+ console.log('[TagadaPay SDK] Pattern match: "'.concat(pathname, '" against "').concat(pattern, '" ='), result !== false);
11216
+ }
11217
+ if (result === false) {
11218
+ return { matched: false, params: {} };
11219
+ }
11220
+ const params = {};
11221
+ if (typeof result === "object" && result.params) {
11222
+ Object.keys(result.params).forEach((key) => {
11223
+ const value = result.params[key];
11224
+ params[key] = Array.isArray(value) ? value.join("/") : String(value);
11225
+ });
11226
+ }
11227
+ return { matched: true, params };
11228
+ } catch (error) {
11229
+ if (typeof process !== "undefined" && true) {
11230
+ console.warn('[TagadaPay SDK] Pattern matching failed for "'.concat(pattern, '":'), error);
11231
+ }
11232
+ return { matched: pathname === pattern, params: {} };
11233
+ }
11234
+ }
11235
+ function mapParamNames(externalParams, externalPattern, internalPattern) {
11236
+ const externalParamNames = extractParamNames(externalPattern);
11237
+ const internalParamNames = extractParamNames(internalPattern);
11238
+ if (externalParamNames.length === 0 || externalParamNames.length !== internalParamNames.length) {
11239
+ return externalParams;
11240
+ }
11241
+ const mappedParams = {};
11242
+ externalParamNames.forEach((externalName, index) => {
11243
+ const internalName = internalParamNames[index];
11244
+ const value = externalParams[externalName];
11245
+ if (value !== void 0) {
11246
+ mappedParams[internalName] = value;
11247
+ }
11248
+ });
11249
+ return mappedParams;
11250
+ }
11251
+ function extractParamNames(pattern) {
11252
+ const matches = pattern.match(/:([a-zA-Z0-9_]+)/g);
11253
+ if (!matches) return [];
11254
+ return matches.map((m) => m.substring(1));
11255
+ }
11256
+ function matchRoute(internalPath) {
11257
+ if (typeof internalPath !== "string") {
11258
+ throw new Error("[TagadaPay SDK] internalPath must be a string, got ".concat(typeof internalPath));
11259
+ }
11260
+ if (internalPath.trim() === "") {
11261
+ throw new Error("[TagadaPay SDK] internalPath cannot be empty");
11262
+ }
11263
+ if (!internalPath.startsWith("/")) {
11264
+ throw new Error('[TagadaPay SDK] internalPath must start with /, got "'.concat(internalPath, '"'));
11265
+ }
11266
+ if (!isBrowser) {
11267
+ return { matched: false, params: {} };
11268
+ }
11269
+ try {
11270
+ const currentPath = window.location.pathname;
11271
+ const remappedInternalPath = getInternalPath();
11272
+ if (remappedInternalPath) {
11273
+ const internalMatch = matchesPathPattern(remappedInternalPath, internalPath);
11274
+ if (!internalMatch.matched) {
11275
+ return { matched: false, params: {} };
11276
+ }
11277
+ let externalPattern = null;
11278
+ if (typeof localStorage !== "undefined") {
11279
+ try {
11280
+ const remapData = localStorage.getItem("tagadapay-remap");
11281
+ if (remapData) {
11282
+ const parsed = JSON.parse(remapData);
11283
+ if (parsed.externalPath && parsed.internalPath === remappedInternalPath) {
11284
+ externalPattern = parsed.externalPath;
11285
+ }
11286
+ }
11287
+ } catch (e) {
11288
+ }
11289
+ }
11290
+ if (!externalPattern && typeof document !== "undefined") {
11291
+ console.log("[TagadaPay SDK] \u{1F50D} Checking for production path remap meta tag...");
11292
+ const metaTag = document.querySelector('meta[name="tagadapay-path-remap"]');
11293
+ if (metaTag) {
11294
+ try {
11295
+ const content = metaTag.getAttribute("content");
11296
+ console.log("[TagadaPay SDK] \u{1F4C4} Found meta tag content (encoded):", (content == null ? void 0 : content.substring(0, 100)) + "...");
11297
+ if (content) {
11298
+ const decodedContent = decodeURIComponent(content);
11299
+ console.log("[TagadaPay SDK] \u{1F4C4} Decoded content:", decodedContent);
11300
+ const parsed = JSON.parse(decodedContent);
11301
+ console.log("[TagadaPay SDK] \u{1F4E6} Parsed remap config:", parsed);
11302
+ console.log("[TagadaPay SDK] \u{1F50D} Checking if internal path matches:", {
11303
+ parsedInternal: parsed.internal,
11304
+ remappedInternalPath
11305
+ });
11306
+ if (parsed.external && parsed.internal === remappedInternalPath) {
11307
+ externalPattern = parsed.external;
11308
+ console.log("[TagadaPay SDK] \u2705 Using external pattern from meta tag:", externalPattern);
11309
+ } else {
11310
+ console.log("[TagadaPay SDK] \u26A0\uFE0F Internal path mismatch - not using meta tag config");
11311
+ }
11312
+ }
11313
+ } catch (e) {
11314
+ console.error("[TagadaPay SDK] \u274C Error parsing path remap meta tag:", e);
11315
+ }
11316
+ } else {
11317
+ console.log("[TagadaPay SDK] \u274C No tagadapay-path-remap meta tag found");
11318
+ }
11319
+ }
11320
+ if (externalPattern) {
11321
+ const externalMatch = matchesPathPattern(currentPath, externalPattern);
11322
+ if (externalMatch.matched) {
11323
+ console.log("[TagadaPay SDK] \u{1F504} Mapping params from external to internal pattern");
11324
+ console.log("[TagadaPay SDK] External params:", externalMatch.params);
11325
+ console.log("[TagadaPay SDK] External pattern:", externalPattern);
11326
+ console.log("[TagadaPay SDK] Internal pattern:", internalPath);
11327
+ const mappedParams = mapParamNames(
11328
+ externalMatch.params,
11329
+ externalPattern,
11330
+ internalPath
11331
+ );
11332
+ console.log("[TagadaPay SDK] Mapped params:", mappedParams);
11333
+ return { matched: true, params: mappedParams };
11334
+ }
11335
+ }
11336
+ const currentMatch = matchesPathPattern(currentPath, internalPath);
11337
+ return { matched: true, params: currentMatch.params };
11338
+ }
11339
+ return matchesPathPattern(currentPath, internalPath);
11340
+ } catch (error) {
11341
+ if (typeof process !== "undefined" && true) {
11342
+ console.error("[TagadaPay SDK] Error in matchRoute:", error);
11343
+ }
11344
+ return { matched: false, params: {} };
11345
+ }
11346
+ }
11347
+
11348
+ // src/v2/core/pixelMapping.ts
11349
+ var ZERO_DECIMAL_CURRENCIES = /* @__PURE__ */ new Set([
11350
+ "BIF",
11351
+ "CLP",
11352
+ "DJF",
11353
+ "GNF",
11354
+ "ISK",
11355
+ "JPY",
11356
+ "KMF",
11357
+ "KRW",
11358
+ "PYG",
11359
+ "RWF",
11360
+ "UGX",
11361
+ "VND",
11362
+ "VUV",
11363
+ "XAF",
11364
+ "XOF",
11365
+ "XPF"
11366
+ ]);
11367
+ var THREE_DECIMAL_CURRENCIES = /* @__PURE__ */ new Set(["BHD", "IQD", "JOD", "KWD", "LYD", "OMR", "TND"]);
11368
+ function minorToMajor(amount, currency) {
11369
+ const code = currency.toUpperCase();
11370
+ if (ZERO_DECIMAL_CURRENCIES.has(code)) return amount;
11371
+ if (THREE_DECIMAL_CURRENCIES.has(code)) return amount / 1e3;
11372
+ return amount / 100;
11373
+ }
11374
+ function isEventEnabled(pixel, eventName) {
11375
+ if (!("events" in pixel) || !pixel.events) return true;
11376
+ const events = pixel.events;
11377
+ if (!(eventName in events)) return true;
11378
+ return events[eventName] === true;
11379
+ }
11380
+ function getEligiblePixels(pixels, eventName) {
11381
+ if (!pixels) return [];
11382
+ return pixels.filter((p) => p.enabled && isEventEnabled(p, eventName));
11383
+ }
11384
+ function ensureCurrencyUppercase(params) {
11385
+ if (params.currency && typeof params.currency === "string") {
11386
+ return __spreadProps(__spreadValues({}, params), { currency: params.currency.toUpperCase() });
11387
+ }
11388
+ return __spreadValues({}, params);
11389
+ }
11390
+ function convertValueToMajor(params) {
11391
+ if (params.currency && params.value != null) {
11392
+ const currency = String(params.currency);
11393
+ const major = minorToMajor(Number(params.value), currency);
11394
+ return __spreadProps(__spreadValues({}, params), { value: major });
11395
+ }
11396
+ return params;
11397
+ }
11398
+ function baseTransform(params) {
11399
+ let p = ensureCurrencyUppercase(params);
11400
+ p = convertValueToMajor(p);
11401
+ return p;
11402
+ }
11403
+ var META_EVENT_MAP = {
11404
+ PageView: "PageView",
11405
+ ViewContent: "ViewContent",
11406
+ AddToCart: "AddToCart",
11407
+ AddToWishlist: "AddToWishlist",
11408
+ Search: "Search",
11409
+ InitiateCheckout: "InitiateCheckout",
11410
+ AddPaymentInfo: "AddPaymentInfo",
11411
+ Purchase: "Purchase",
11412
+ Lead: "Lead",
11413
+ CompleteRegistration: "CompleteRegistration"
11414
+ };
11415
+ function mapMetaEvent(eventName, parameters) {
11416
+ var _a, _b;
11417
+ const name = (_a = META_EVENT_MAP[eventName]) != null ? _a : eventName;
11418
+ const params = baseTransform(parameters);
11419
+ if (params.contents && Array.isArray(params.contents)) {
11420
+ params.content_ids = params.contents.map((i) => i.content_id).filter(Boolean);
11421
+ params.content_type = (_b = params.content_type) != null ? _b : "product";
11422
+ }
11423
+ return { name, params };
11424
+ }
11425
+ var TIKTOK_EVENT_MAP = {
11426
+ PageView: "Pageview",
11427
+ ViewContent: "ViewContent",
11428
+ AddToCart: "AddToCart",
11429
+ AddToWishlist: "AddToWishlist",
11430
+ Search: "Search",
11431
+ InitiateCheckout: "InitiateCheckout",
11432
+ AddPaymentInfo: "AddPaymentInfo",
11433
+ Purchase: "Purchase",
11434
+ Lead: "SubmitForm",
11435
+ CompleteRegistration: "CompleteRegistration"
11436
+ };
11437
+ function mapTikTokEvent(eventName, parameters) {
11438
+ var _a, _b;
11439
+ const name = (_a = TIKTOK_EVENT_MAP[eventName]) != null ? _a : eventName;
11440
+ const params = baseTransform(parameters);
11441
+ const currency = params.currency ? String(params.currency) : null;
11442
+ if (currency) {
11443
+ for (const field of ["shipping", "tax", "subtotal", "total_discount"]) {
11444
+ if (params[field] != null) {
11445
+ params[field] = minorToMajor(Number(params[field]), currency);
11446
+ }
11447
+ }
11448
+ }
11449
+ if (params.contents && Array.isArray(params.contents)) {
11450
+ if (!params.content_ids) {
11451
+ params.content_ids = params.contents.map((i) => i.content_id).filter(Boolean);
11452
+ }
11453
+ params.contents = params.contents.map((item) => {
11454
+ var _a2;
11455
+ const itemCurrency = item.currency ? String(item.currency) : currency;
11456
+ return {
11457
+ content_id: item.content_id,
11458
+ content_name: item.content_name,
11459
+ content_type: (_a2 = item.content_type) != null ? _a2 : "product",
11460
+ content_category: item.content_category,
11461
+ price: item.price != null && itemCurrency ? minorToMajor(Number(item.price), itemCurrency) : item.price != null ? Number(item.price) : void 0,
11462
+ original_price: item.original_price != null && itemCurrency ? minorToMajor(Number(item.original_price), itemCurrency) : item.original_price != null ? Number(item.original_price) : void 0,
11463
+ quantity: item.quantity != null ? Number(item.quantity) : void 0,
11464
+ description: item.description
11465
+ };
11466
+ });
11467
+ }
11468
+ if (eventName === "InitiateCheckout") {
11469
+ params.content_type = (_b = params.content_type) != null ? _b : "product";
11470
+ if (!params.delivery_category) {
11471
+ params.delivery_category = "home_delivery";
11472
+ }
11473
+ }
11474
+ return { name, params };
11475
+ }
11476
+ var SNAPCHAT_EVENT_MAP = {
11477
+ PageView: "PAGE_VIEW",
11478
+ ViewContent: "VIEW_CONTENT",
11479
+ AddToCart: "ADD_CART",
11480
+ AddToWishlist: "ADD_TO_WISHLIST",
11481
+ Search: "SEARCH",
11482
+ InitiateCheckout: "START_CHECKOUT",
11483
+ AddPaymentInfo: "ADD_BILLING",
11484
+ Purchase: "PURCHASE",
11485
+ Lead: "LEAD",
11486
+ CompleteRegistration: "SIGN_UP"
11487
+ };
11488
+ function mapSnapchatEvent(eventName, parameters) {
11489
+ var _a;
11490
+ const name = (_a = SNAPCHAT_EVENT_MAP[eventName]) != null ? _a : eventName;
11491
+ let params = baseTransform(parameters);
11492
+ if ("value" in params) {
11493
+ params = __spreadProps(__spreadValues({}, params), { price: params.value });
11494
+ delete params.value;
11495
+ }
11496
+ if ("num_items" in params) {
11497
+ params = __spreadProps(__spreadValues({}, params), { number_items: params.num_items });
11498
+ delete params.num_items;
11499
+ }
11500
+ if (params.contents && Array.isArray(params.contents)) {
11501
+ params.item_ids = params.contents.map((i) => i.content_id).filter(Boolean);
11502
+ }
11503
+ return { name, params };
11504
+ }
11505
+ var PINTEREST_EVENT_MAP = {
11506
+ PageView: "pagevisit",
11507
+ ViewContent: "viewcontent",
11508
+ AddToCart: "addtocart",
11509
+ AddToWishlist: "addtowishlist",
11510
+ Search: "search",
11511
+ InitiateCheckout: "initiatecheckout",
11512
+ AddPaymentInfo: "addpaymentinfo",
11513
+ Purchase: "checkout",
11514
+ Lead: "lead",
11515
+ CompleteRegistration: "signup"
11516
+ };
11517
+ function mapPinterestEvent(eventName, parameters) {
11518
+ var _a;
11519
+ const name = (_a = PINTEREST_EVENT_MAP[eventName]) != null ? _a : eventName.toLowerCase();
11520
+ const params = baseTransform(parameters);
11521
+ if (params.order_quantity !== void 0) {
11522
+ params.order_quantity = Number(params.order_quantity);
11523
+ }
11524
+ if (params.contents && Array.isArray(params.contents)) {
11525
+ params.line_items = params.contents.map((item) => ({
11526
+ product_id: item.content_id,
11527
+ product_name: item.content_name,
11528
+ product_category: item.content_category,
11529
+ product_price: item.price != null ? Number(item.price) : void 0,
11530
+ product_quantity: item.quantity != null ? Number(item.quantity) : void 0
11531
+ }));
11532
+ }
11533
+ return { name, params };
11534
+ }
11535
+ var GTM_EVENT_MAP = {
11536
+ PageView: "page_view",
11537
+ ViewContent: "view_item",
11538
+ AddToCart: "add_to_cart",
11539
+ AddToWishlist: "add_to_wishlist",
11540
+ Search: "search",
11541
+ InitiateCheckout: "begin_checkout",
11542
+ AddPaymentInfo: "add_payment_info",
11543
+ Purchase: "purchase",
11544
+ Lead: "generate_lead",
11545
+ CompleteRegistration: "sign_up",
11546
+ Conversion: "conversion"
11547
+ };
11548
+ function mapGTMEvent(eventName, parameters) {
11549
+ var _a;
11550
+ const name = (_a = GTM_EVENT_MAP[eventName]) != null ? _a : eventName.toLowerCase();
11551
+ const params = baseTransform(parameters);
11552
+ if (params.num_items !== void 0) {
11553
+ params.num_items = Number(params.num_items);
11554
+ }
11555
+ if (params.contents && Array.isArray(params.contents)) {
11556
+ params.items = params.contents.map((item) => ({
11557
+ item_id: item.content_id,
11558
+ item_name: item.content_name,
11559
+ item_category: item.content_category,
11560
+ price: item.price != null ? Number(item.price) : void 0,
11561
+ quantity: item.quantity != null ? Number(item.quantity) : void 0
11562
+ }));
11563
+ params.contents = params.contents.map((item) => ({
11564
+ id: item.content_id,
11565
+ name: item.content_name,
11566
+ category: item.content_category,
11567
+ price: item.price != null ? Number(item.price) : void 0,
11568
+ quantity: item.quantity != null ? Number(item.quantity) : void 0
11569
+ }));
11570
+ }
11571
+ return { name, params };
11572
+ }
11573
+ function applyGoogleAdsConversion(params, eventName, pixel) {
11574
+ if ((eventName === "Purchase" || eventName === "Conversion") && pixel.googleAdsConversionId && pixel.googleAdsConversionLabel) {
11575
+ return __spreadProps(__spreadValues({}, params), { send_to: "".concat(pixel.googleAdsConversionId, "/").concat(pixel.googleAdsConversionLabel) });
11576
+ }
11577
+ return params;
11578
+ }
11579
+ function resolvePixelEvents(pixels, eventName, parameters) {
11580
+ const results = [];
11581
+ const fb = getEligiblePixels(pixels.facebook, eventName);
11582
+ if (fb.length > 0) {
11583
+ const mapped = mapMetaEvent(eventName, parameters);
11584
+ fb.forEach((pixel) => results.push({ provider: "facebook", mapped, pixel }));
11585
+ }
11586
+ const tt = getEligiblePixels(pixels.tiktok, eventName);
11587
+ if (tt.length > 0) {
11588
+ const mapped = mapTikTokEvent(eventName, parameters);
11589
+ tt.forEach((pixel) => results.push({ provider: "tiktok", mapped, pixel }));
11590
+ }
11591
+ const sc = getEligiblePixels(pixels.snapchat, eventName);
11592
+ if (sc.length > 0) {
11593
+ const mapped = mapSnapchatEvent(eventName, parameters);
11594
+ sc.forEach((pixel) => results.push({ provider: "snapchat", mapped, pixel }));
11595
+ }
11596
+ const pt = getEligiblePixels(pixels.pinterest, eventName);
11597
+ if (pt.length > 0) {
11598
+ const mapped = mapPinterestEvent(eventName, parameters);
11599
+ pt.forEach((pixel) => results.push({ provider: "pinterest", mapped, pixel }));
11600
+ }
11601
+ const gtm = getEligiblePixels(pixels.gtm, eventName);
11602
+ if (gtm.length > 0) {
11603
+ const mapped = mapGTMEvent(eventName, parameters);
11604
+ gtm.forEach((pixel) => {
11605
+ const finalParams = applyGoogleAdsConversion(mapped.params, eventName, pixel);
11606
+ results.push({ provider: "gtm", mapped: { name: mapped.name, params: finalParams }, pixel });
11607
+ });
11608
+ }
11609
+ return results;
11610
+ }
11611
+
9915
11612
  // src/v2/standalone/external-tracker.ts
9916
11613
  init_tokenStorage();
11614
+ var TRACKER_VERSION = "1.0.0";
9917
11615
  function getUrlParam(name) {
9918
11616
  if (typeof window === "undefined") return null;
9919
11617
  const params = new URLSearchParams(window.location.search);
@@ -9924,58 +11622,133 @@ var TagadaSDKBundle = (() => {
9924
11622
  console.log("[TagadaTracker]", ...args);
9925
11623
  }
9926
11624
  }
11625
+ function warn(...args) {
11626
+ console.warn("[TagadaTracker]", ...args);
11627
+ }
11628
+ function validate(config) {
11629
+ if (!config.storeId || typeof config.storeId !== "string") {
11630
+ throw new Error("TagadaTracker: storeId is required and must be a non-empty string.");
11631
+ }
11632
+ if (!config.accountId || typeof config.accountId !== "string") {
11633
+ throw new Error("TagadaTracker: accountId is required and must be a non-empty string.");
11634
+ }
11635
+ if (!config.stepId || typeof config.stepId !== "string") {
11636
+ throw new Error("TagadaTracker: stepId is required and must be a non-empty string.");
11637
+ }
11638
+ if (config.apiBaseUrl) {
11639
+ try {
11640
+ new URL(config.apiBaseUrl);
11641
+ } catch (e) {
11642
+ throw new Error('TagadaTracker: apiBaseUrl is not a valid URL: "'.concat(config.apiBaseUrl, '"'));
11643
+ }
11644
+ }
11645
+ }
11646
+ async function retryWithBackoff(fn, maxRetries, debug) {
11647
+ let lastError;
11648
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
11649
+ try {
11650
+ return await fn();
11651
+ } catch (err) {
11652
+ lastError = err instanceof Error ? err : new Error(String(err));
11653
+ if (attempt < maxRetries) {
11654
+ const delay = Math.min(1e3 * 2 ** attempt, 8e3);
11655
+ log(debug, "Retry ".concat(attempt + 1, "/").concat(maxRetries, " in ").concat(delay, "ms..."));
11656
+ await new Promise((r) => setTimeout(r, delay));
11657
+ }
11658
+ }
11659
+ }
11660
+ throw lastError;
11661
+ }
9927
11662
  var TagadaExternalTracker = class {
9928
11663
  constructor() {
9929
11664
  this.config = null;
9930
11665
  this.client = null;
9931
11666
  this.initialized = false;
9932
11667
  this.initializing = false;
11668
+ this.unsubscribe = null;
11669
+ /** Tracker version */
11670
+ this.version = TRACKER_VERSION;
9933
11671
  }
9934
11672
  /**
9935
- * Initialize the tracker using SDK infrastructure
11673
+ * Initialize the tracker.
11674
+ * When `onError` is provided, errors are passed to the callback and init()
11675
+ * resolves to `null` instead of throwing.
9936
11676
  */
9937
11677
  async init(config) {
9938
- var _a, _b, _c, _d;
9939
- if (this.initialized || this.initializing) {
9940
- log(config.debug || false, "Already initialized or initializing");
11678
+ var _a, _b;
11679
+ if (this.initialized) {
11680
+ log(config.debug || false, "Already initialized \u2014 returning existing session.");
9941
11681
  return this.getSession();
9942
11682
  }
11683
+ if (this.initializing) {
11684
+ log(config.debug || false, "Initialization in progress \u2014 skipping duplicate call.");
11685
+ return null;
11686
+ }
9943
11687
  this.initializing = true;
9944
- this.config = __spreadValues({
9945
- debug: false
9946
- }, config);
9947
- log(this.config.debug, "\u{1F680} Initializing external tracker with SDK...", config);
11688
+ this.config = __spreadValues({ debug: false }, config);
11689
+ const debug = this.config.debug;
11690
+ try {
11691
+ validate(this.config);
11692
+ } catch (err) {
11693
+ this.initializing = false;
11694
+ const error = err instanceof Error ? err : new Error(String(err));
11695
+ if (this.config.onError) {
11696
+ this.config.onError(error);
11697
+ return null;
11698
+ }
11699
+ throw error;
11700
+ }
11701
+ log(debug, "\u{1F680} Initializing external tracker v".concat(TRACKER_VERSION), {
11702
+ storeId: config.storeId,
11703
+ accountId: config.accountId,
11704
+ stepId: config.stepId,
11705
+ funnelId: config.funnelId
11706
+ });
9948
11707
  try {
9949
11708
  const urlToken = getUrlParam("token");
9950
11709
  if (urlToken) {
9951
11710
  setClientToken(urlToken);
9952
- log(this.config.debug, "\u{1F511} Bootstrapped token from URL");
11711
+ log(debug, "\u{1F511} Bootstrapped token from URL");
9953
11712
  }
9954
11713
  this.client = createTagadaClient({
9955
- debugMode: this.config.debug,
9956
- features: { funnel: true }
11714
+ debugMode: debug,
11715
+ features: { funnel: { skipAutoInit: true } },
11716
+ rawPluginConfig: {
11717
+ storeId: this.config.storeId,
11718
+ accountId: this.config.accountId
11719
+ },
11720
+ customApiConfig: this.config.apiBaseUrl ? {
11721
+ apiConfig: {
11722
+ baseUrl: this.config.apiBaseUrl.trim()
11723
+ }
11724
+ } : void 0
9957
11725
  });
9958
11726
  await this.waitForClientReady();
9959
- const funnelContext = await this.initializeFunnel();
9960
- log(this.config.debug, "\u2705 Session initialized (tracking handled by orchestrator):", funnelContext);
11727
+ const funnelContext = await retryWithBackoff(
11728
+ () => this.initializeFunnel(),
11729
+ 2,
11730
+ debug
11731
+ );
11732
+ log(debug, "\u2705 Session initialized:", funnelContext);
9961
11733
  this.initialized = true;
9962
11734
  const session = this.getSession();
9963
11735
  if (session) {
9964
11736
  (_b = (_a = this.config).onReady) == null ? void 0 : _b.call(_a, session);
9965
11737
  }
9966
11738
  return session;
9967
- } catch (error) {
9968
- const err = error instanceof Error ? error : new Error(String(error));
9969
- log(this.config.debug, "\u274C Initialization failed:", err);
9970
- (_d = (_c = this.config).onError) == null ? void 0 : _d.call(_c, err);
9971
- throw err;
11739
+ } catch (err) {
11740
+ const error = err instanceof Error ? err : new Error(String(err));
11741
+ log(debug, "\u274C Initialization failed:", error);
11742
+ if (this.config.onError) {
11743
+ this.config.onError(error);
11744
+ return null;
11745
+ }
11746
+ throw error;
9972
11747
  } finally {
9973
11748
  this.initializing = false;
9974
11749
  }
9975
11750
  }
9976
- /**
9977
- * Get current session from SDK state
9978
- */
11751
+ /** Get current session data. */
9979
11752
  getSession() {
9980
11753
  var _a, _b;
9981
11754
  if (!((_b = (_a = this.client) == null ? void 0 : _a.funnel) == null ? void 0 : _b.state.context)) return null;
@@ -9989,19 +11762,18 @@ var TagadaSDKBundle = (() => {
9989
11762
  cmsToken: this.client.state.token || void 0
9990
11763
  };
9991
11764
  }
9992
- /**
9993
- * Check if tracker is ready
9994
- */
11765
+ /** Whether the tracker is fully initialized and ready. */
9995
11766
  isReady() {
9996
11767
  var _a, _b;
9997
11768
  return this.initialized && !!((_b = (_a = this.client) == null ? void 0 : _a.funnel) == null ? void 0 : _b.state.context);
9998
11769
  }
9999
11770
  /**
10000
- * Navigate to next step in funnel using SDK's funnel client
11771
+ * Navigate to the next step in the funnel.
11772
+ * By default, auto-redirects the browser window.
10001
11773
  */
10002
11774
  async navigate(options) {
10003
11775
  if (!this.isReady()) {
10004
- throw new Error("Tracker not initialized. Call init() first.");
11776
+ throw new Error("TagadaTracker: not initialized. Call init() first.");
10005
11777
  }
10006
11778
  log(this.config.debug, "\u{1F680} Navigating:", options);
10007
11779
  const shouldAutoRedirect = options.autoRedirect !== false;
@@ -10012,7 +11784,6 @@ var TagadaSDKBundle = (() => {
10012
11784
  data: options.eventData || {}
10013
11785
  },
10014
11786
  { autoRedirect: false }
10015
- // Always disable SDK auto-redirect, we handle it here
10016
11787
  );
10017
11788
  if (result == null ? void 0 : result.url) {
10018
11789
  log(this.config.debug, "\u2705 Navigation result:", result.url);
@@ -10028,36 +11799,48 @@ var TagadaSDKBundle = (() => {
10028
11799
  }
10029
11800
  }
10030
11801
  /**
10031
- * Get customer ID (for identifying the user)
11802
+ * Track a custom event (e.g., button click, scroll depth, video play).
11803
+ * Events are sent through the funnel orchestrator for unified analytics.
10032
11804
  */
11805
+ async trackEvent(options) {
11806
+ if (!this.isReady()) {
11807
+ warn("trackEvent called before init \u2014 event dropped:", options.name);
11808
+ return;
11809
+ }
11810
+ log(this.config.debug, "\u{1F4CA} Tracking event:", options.name, options.data);
11811
+ try {
11812
+ await this.client.funnel.navigate(
11813
+ {
11814
+ type: options.name,
11815
+ data: options.data || {}
11816
+ },
11817
+ { autoRedirect: false }
11818
+ );
11819
+ } catch (e) {
11820
+ log(this.config.debug, "\u26A0\uFE0F Event tracking failed (non-critical):", options.name);
11821
+ }
11822
+ }
11823
+ /** Get customer ID. */
10033
11824
  getCustomerId() {
10034
11825
  var _a, _b, _c, _d, _e;
10035
11826
  return ((_b = (_a = this.client) == null ? void 0 : _a.state.auth.customer) == null ? void 0 : _b.id) || ((_e = (_d = (_c = this.client) == null ? void 0 : _c.funnel) == null ? void 0 : _d.state.context) == null ? void 0 : _e.customerId) || null;
10036
11827
  }
10037
- /**
10038
- * Get funnel session ID
10039
- */
11828
+ /** Get funnel session ID. */
10040
11829
  getFunnelSessionId() {
10041
11830
  var _a, _b, _c;
10042
11831
  return ((_c = (_b = (_a = this.client) == null ? void 0 : _a.funnel) == null ? void 0 : _b.state.context) == null ? void 0 : _c.sessionId) || null;
10043
11832
  }
10044
11833
  /**
10045
- * Build a URL with funnel context parameters
10046
- * Useful for linking to other external pages while preserving session
11834
+ * Build a URL that preserves funnel session context.
11835
+ * Use this to link to other external pages within the same funnel.
10047
11836
  */
10048
11837
  buildUrl(baseUrl, additionalParams) {
10049
11838
  const session = this.getSession();
10050
- if (!session) {
10051
- return baseUrl;
10052
- }
11839
+ if (!session) return baseUrl;
10053
11840
  const url = new URL(baseUrl, typeof window !== "undefined" ? window.location.origin : void 0);
10054
11841
  url.searchParams.set("funnelSessionId", session.sessionId);
10055
- if (session.cmsToken) {
10056
- url.searchParams.set("token", session.cmsToken);
10057
- }
10058
- if (session.funnelId) {
10059
- url.searchParams.set("funnelId", session.funnelId);
10060
- }
11842
+ if (session.cmsToken) url.searchParams.set("token", session.cmsToken);
11843
+ if (session.funnelId) url.searchParams.set("funnelId", session.funnelId);
10061
11844
  url.searchParams.set("storeId", session.storeId);
10062
11845
  if (additionalParams) {
10063
11846
  Object.entries(additionalParams).forEach(([key, value]) => {
@@ -10066,55 +11849,98 @@ var TagadaSDKBundle = (() => {
10066
11849
  }
10067
11850
  return url.toString();
10068
11851
  }
10069
- /**
10070
- * Get the underlying SDK client (for advanced usage)
10071
- */
11852
+ /** Get the underlying SDK client (advanced usage). */
10072
11853
  getClient() {
10073
11854
  return this.client;
10074
11855
  }
11856
+ /**
11857
+ * Reset the tracker to a new step without re-creating the session.
11858
+ * Useful for SPAs that navigate between funnel steps client-side.
11859
+ */
11860
+ async reset(newStepId) {
11861
+ var _a, _b;
11862
+ if (!this.client || !this.config) {
11863
+ throw new Error("TagadaTracker: not initialized. Call init() first.");
11864
+ }
11865
+ log(this.config.debug, "\u{1F504} Resetting to step:", newStepId);
11866
+ this.config.stepId = newStepId;
11867
+ const ctx = await this.initializeFunnel();
11868
+ const session = this.getSession();
11869
+ if (session) (_b = (_a = this.config).onReady) == null ? void 0 : _b.call(_a, session);
11870
+ return session;
11871
+ }
11872
+ /**
11873
+ * Destroy the tracker, clean up event listeners and state.
11874
+ * Call this when the tracker is no longer needed (e.g., SPA teardown).
11875
+ */
11876
+ destroy() {
11877
+ var _a, _b;
11878
+ if (this.unsubscribe) {
11879
+ this.unsubscribe();
11880
+ this.unsubscribe = null;
11881
+ }
11882
+ if (this.client) {
11883
+ (_b = (_a = this.client).destroy) == null ? void 0 : _b.call(_a);
11884
+ }
11885
+ this.client = null;
11886
+ this.config = null;
11887
+ this.initialized = false;
11888
+ this.initializing = false;
11889
+ log(false, "\u{1F5D1}\uFE0F Tracker destroyed");
11890
+ }
10075
11891
  // ========================================================================
10076
11892
  // PRIVATE METHODS
10077
11893
  // ========================================================================
10078
11894
  async waitForClientReady() {
10079
11895
  if (!this.client) return;
10080
11896
  return new Promise((resolve) => {
10081
- let retries = 0;
10082
- const checkReady = () => {
10083
- var _a, _b;
10084
- if (((_a = this.client) == null ? void 0 : _a.state.isInitialized) || ((_b = this.client) == null ? void 0 : _b.state.token)) {
11897
+ var _a;
11898
+ if ((_a = this.client) == null ? void 0 : _a.state.isInitialized) {
11899
+ resolve();
11900
+ return;
11901
+ }
11902
+ let resolved = false;
11903
+ const timeout = setTimeout(() => {
11904
+ var _a2;
11905
+ if (!resolved) {
11906
+ resolved = true;
11907
+ log(((_a2 = this.config) == null ? void 0 : _a2.debug) || false, "\u23F1\uFE0F Client ready timeout \u2014 proceeding");
10085
11908
  resolve();
10086
- } else if (retries > 40) {
11909
+ }
11910
+ }, 1e4);
11911
+ this.unsubscribe = this.client.subscribe(() => {
11912
+ var _a2;
11913
+ if (!resolved && ((_a2 = this.client) == null ? void 0 : _a2.state.isInitialized)) {
11914
+ resolved = true;
11915
+ clearTimeout(timeout);
10087
11916
  resolve();
10088
- } else {
10089
- retries++;
10090
- setTimeout(checkReady, 50);
10091
11917
  }
10092
- };
10093
- checkReady();
11918
+ });
10094
11919
  });
10095
11920
  }
10096
11921
  async initializeFunnel() {
10097
11922
  var _a, _b, _c;
10098
11923
  if (!((_a = this.client) == null ? void 0 : _a.funnel)) return null;
11924
+ const customerId = (_b = this.client.state.auth.customer) == null ? void 0 : _b.id;
11925
+ const sessionId = (_c = this.client.state.auth.session) == null ? void 0 : _c.sessionId;
11926
+ if (!customerId && !sessionId) {
11927
+ warn("No auth session available \u2014 funnel init may fail.");
11928
+ }
10099
11929
  const authSession = {
10100
- customerId: ((_b = this.client.state.auth.customer) == null ? void 0 : _b.id) || "anon_placeholder",
10101
- sessionId: ((_c = this.client.state.auth.session) == null ? void 0 : _c.sessionId) || "sess_placeholder"
11930
+ customerId: customerId || "anon_placeholder",
11931
+ sessionId: sessionId || "sess_placeholder"
10102
11932
  };
10103
11933
  const store = {
10104
11934
  id: this.config.storeId,
10105
- accountId: this.config.accountId || ""
11935
+ accountId: this.config.accountId
10106
11936
  };
10107
11937
  const entryStepId = this.config.stepId;
10108
- if (!entryStepId) {
10109
- throw new Error("stepId is required for external page tracking (URL mapping does not work for external pages)");
10110
- }
10111
- log(this.config.debug, "\u{1F50D} Initializing external page at step:", entryStepId);
11938
+ log(this.config.debug, "\u{1F50D} Initializing funnel at step:", entryStepId);
10112
11939
  return this.client.funnel.initialize(
10113
11940
  authSession,
10114
11941
  store,
10115
11942
  this.config.funnelId || getUrlParam("funnelId") || void 0,
10116
11943
  entryStepId
10117
- // ✅ Explicitly tell orchestrator which step we're on
10118
11944
  );
10119
11945
  }
10120
11946
  };
@@ -10124,6 +11950,79 @@ var TagadaSDKBundle = (() => {
10124
11950
  }
10125
11951
 
10126
11952
  // src/v2/standalone/index.ts
11953
+ function parseStepConfigScripts() {
11954
+ if (typeof window === "undefined" || typeof document === "undefined") {
11955
+ return [];
11956
+ }
11957
+ const stepConfig = getAssignedStepConfig();
11958
+ if (stepConfig == null ? void 0 : stepConfig.scripts) {
11959
+ return stepConfig.scripts.filter((s) => s.enabled);
11960
+ }
11961
+ return [];
11962
+ }
11963
+ function injectScript(script, index) {
11964
+ const position = script.position || "body-end";
11965
+ const scriptId = "tagada-stepconfig-script-".concat(index);
11966
+ if (document.getElementById(scriptId)) {
11967
+ return;
11968
+ }
11969
+ let scriptBody = script.content.trim();
11970
+ const scriptTagMatch = scriptBody.match(/^<script[^>]*>([\s\S]*)<\/script>$/i);
11971
+ if (scriptTagMatch) {
11972
+ scriptBody = scriptTagMatch[1].trim();
11973
+ }
11974
+ if (!scriptBody) return;
11975
+ const wrappedScript = "(function() {\n try {\n // Script: " + script.name + "\n" + scriptBody + '\n } catch (error) {\n console.error("[TagadaPay] StepConfig script error:", error);\n }\n})();';
11976
+ const scriptElement = document.createElement("script");
11977
+ scriptElement.id = scriptId;
11978
+ scriptElement.setAttribute("data-tagada-stepconfig-script", "true");
11979
+ scriptElement.setAttribute("data-script-name", script.name);
11980
+ scriptElement.textContent = wrappedScript;
11981
+ switch (position) {
11982
+ case "head-start":
11983
+ if (document.head.firstChild) {
11984
+ document.head.insertBefore(scriptElement, document.head.firstChild);
11985
+ } else {
11986
+ document.head.appendChild(scriptElement);
11987
+ }
11988
+ break;
11989
+ case "head-end":
11990
+ document.head.appendChild(scriptElement);
11991
+ break;
11992
+ case "body-start":
11993
+ if (document.body.firstChild) {
11994
+ document.body.insertBefore(scriptElement, document.body.firstChild);
11995
+ } else {
11996
+ document.body.appendChild(scriptElement);
11997
+ }
11998
+ break;
11999
+ case "body-end":
12000
+ default:
12001
+ document.body.appendChild(scriptElement);
12002
+ break;
12003
+ }
12004
+ }
12005
+ function injectStepConfigScripts() {
12006
+ const scripts = parseStepConfigScripts();
12007
+ if (scripts.length === 0) return;
12008
+ scripts.forEach((script, index) => {
12009
+ injectScript(script, index);
12010
+ });
12011
+ }
12012
+ if (typeof window !== "undefined" && typeof document !== "undefined") {
12013
+ const runInjection = () => {
12014
+ if (document.body) {
12015
+ injectStepConfigScripts();
12016
+ } else {
12017
+ document.addEventListener("DOMContentLoaded", injectStepConfigScripts, { once: true });
12018
+ }
12019
+ };
12020
+ if ("requestIdleCallback" in window) {
12021
+ window.requestIdleCallback(runInjection, { timeout: 100 });
12022
+ } else {
12023
+ setTimeout(runInjection, 0);
12024
+ }
12025
+ }
10127
12026
  function createTagadaClient(config = {}) {
10128
12027
  return new TagadaClient(config);
10129
12028
  }
@@ -10162,5 +12061,6 @@ if (typeof window !== 'undefined' && TagadaSDKBundle) {
10162
12061
  window.tgd.sendConfigUpdate = TagadaSDKBundle.sendConfigUpdate;
10163
12062
  window.tgd.broadcastConfigUpdate = TagadaSDKBundle.broadcastConfigUpdate;
10164
12063
  window.tgd.formatMoney = TagadaSDKBundle.formatMoney;
12064
+ window.tgd.injectStepConfigScripts = TagadaSDKBundle.injectStepConfigScripts;
10165
12065
  window.tgd.sdk = TagadaSDKBundle;
10166
12066
  }