@paydock/client-sdk 1.144.0-beta → 1.145.0-beta

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 (53) hide show
  1. package/README.md +422 -31
  2. package/bundles/index.cjs +2476 -988
  3. package/bundles/index.cjs.d.ts +627 -431
  4. package/bundles/index.mjs +2476 -988
  5. package/bundles/index.mjs.d.ts +627 -431
  6. package/bundles/types/api/api-base.d.ts +15 -2
  7. package/bundles/types/api/api-base.d.ts.map +1 -1
  8. package/bundles/types/helper/browser.d.ts.map +1 -1
  9. package/bundles/types/helper/element-id.d.ts +3 -1
  10. package/bundles/types/helper/element-id.d.ts.map +1 -1
  11. package/bundles/types/helper/uuid.d.ts.map +1 -1
  12. package/bundles/types/open-wallets/apple-pay-open-wallet-button.d.ts +41 -0
  13. package/bundles/types/open-wallets/apple-pay-open-wallet-button.d.ts.map +1 -1
  14. package/bundles/types/open-wallets/base/open-wallet-buttons.d.ts +10 -0
  15. package/bundles/types/open-wallets/base/open-wallet-buttons.d.ts.map +1 -1
  16. package/bundles/types/open-wallets/base/service-config-cache.d.ts +23 -0
  17. package/bundles/types/open-wallets/base/service-config-cache.d.ts.map +1 -0
  18. package/bundles/types/open-wallets/google-pay-open-wallet-button.d.ts +33 -1
  19. package/bundles/types/open-wallets/google-pay-open-wallet-button.d.ts.map +1 -1
  20. package/bundles/types/open-wallets/index.d.ts +82 -1
  21. package/bundles/types/open-wallets/index.d.ts.map +1 -1
  22. package/bundles/types/open-wallets/interfaces/apple-pay/apple-pay-availability.interface.d.ts +41 -0
  23. package/bundles/types/open-wallets/interfaces/apple-pay/apple-pay-availability.interface.d.ts.map +1 -0
  24. package/bundles/types/open-wallets/interfaces/apple-pay/index.d.ts +1 -0
  25. package/bundles/types/open-wallets/interfaces/apple-pay/index.d.ts.map +1 -1
  26. package/bundles/types/open-wallets/interfaces/google-pay/google-pay-availability.interface.d.ts +25 -0
  27. package/bundles/types/open-wallets/interfaces/google-pay/google-pay-availability.interface.d.ts.map +1 -0
  28. package/bundles/types/open-wallets/interfaces/google-pay/index.d.ts +1 -0
  29. package/bundles/types/open-wallets/interfaces/google-pay/index.d.ts.map +1 -1
  30. package/bundles/types/open-wallets/interfaces/index.d.ts +3 -0
  31. package/bundles/types/open-wallets/interfaces/index.d.ts.map +1 -1
  32. package/bundles/types/open-wallets/interfaces/open-wallet-availability.interface.d.ts +31 -0
  33. package/bundles/types/open-wallets/interfaces/open-wallet-availability.interface.d.ts.map +1 -0
  34. package/bundles/types/open-wallets/services/apple-pay/apple-pay-availability.d.ts +58 -0
  35. package/bundles/types/open-wallets/services/apple-pay/apple-pay-availability.d.ts.map +1 -0
  36. package/bundles/types/open-wallets/services/apple-pay/apple-pay.open-wallet.service.d.ts +8 -10
  37. package/bundles/types/open-wallets/services/apple-pay/apple-pay.open-wallet.service.d.ts.map +1 -1
  38. package/bundles/types/open-wallets/services/apple-pay/index.d.ts +1 -0
  39. package/bundles/types/open-wallets/services/apple-pay/index.d.ts.map +1 -1
  40. package/bundles/types/open-wallets/services/google-pay/google-pay-availability.d.ts +53 -0
  41. package/bundles/types/open-wallets/services/google-pay/google-pay-availability.d.ts.map +1 -0
  42. package/bundles/types/open-wallets/services/google-pay/google-pay.open-wallet.service.d.ts.map +1 -1
  43. package/bundles/types/open-wallets/services/google-pay/index.d.ts +1 -0
  44. package/bundles/types/open-wallets/services/google-pay/index.d.ts.map +1 -1
  45. package/bundles/types/secure-remote-commerce/secure-remote-commerce.d.ts.map +1 -1
  46. package/bundles/widget.umd.js +2476 -988
  47. package/bundles/widget.umd.js.d.ts +627 -431
  48. package/bundles/widget.umd.js.min.d.ts +627 -431
  49. package/bundles/widget.umd.min.js +1 -1
  50. package/docs/open-wallet-buttons-examples.md +170 -2
  51. package/docs/open-wallet-buttons.md +252 -29
  52. package/package.json +15 -8
  53. package/slate.md +170 -2
package/bundles/index.mjs CHANGED
@@ -828,16 +828,28 @@ var Browser = /*#__PURE__*/function () {
828
828
  value: function getBrowserName() {
829
829
  var sUsrAg = navigator.userAgent;
830
830
  // "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:61.0) Gecko/20100101 Firefox/61.0"
831
- if (sUsrAg.indexOf('Firefox') > -1) return 'Mozilla Firefox';
832
- if (sUsrAg.indexOf('Opera') > -1) return 'Opera';
831
+ if (sUsrAg.indexOf('Firefox') > -1) {
832
+ return 'Mozilla Firefox';
833
+ }
834
+ if (sUsrAg.indexOf('Opera') > -1) {
835
+ return 'Opera';
836
+ }
833
837
  // "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; Zoom 3.6.0; wbx 1.0.0; rv:11.0) like Gecko"
834
- if (sUsrAg.indexOf('Trident') > -1) return 'Microsoft Internet Explorer';
838
+ if (sUsrAg.indexOf('Trident') > -1) {
839
+ return 'Microsoft Internet Explorer';
840
+ }
835
841
  // "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299"
836
- if (sUsrAg.indexOf('Edge') > -1) return 'Microsoft Edge';
842
+ if (sUsrAg.indexOf('Edge') > -1) {
843
+ return 'Microsoft Edge';
844
+ }
837
845
  // "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/66.0.3359.181 Chrome/66.0.3359.181 Safari/537.36"
838
- if (sUsrAg.indexOf('Chrome') > -1) return 'Google Chrome or Chromium';
846
+ if (sUsrAg.indexOf('Chrome') > -1) {
847
+ return 'Google Chrome or Chromium';
848
+ }
839
849
  // "Mozilla/5.0 (iPhone; CPU iPhone OS 11_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/11.0 Mobile/15E148 Safari/604.1 980x1306"
840
- if (sUsrAg.indexOf('Safari') > -1) return 'Apple Safari';
850
+ if (sUsrAg.indexOf('Safari') > -1) {
851
+ return 'Apple Safari';
852
+ }
841
853
  return 'unknown';
842
854
  }
843
855
  }, {
@@ -868,11 +880,13 @@ var Browser = /*#__PURE__*/function () {
868
880
  }, {
869
881
  key: "getBrowserInfo",
870
882
  value: function getBrowserInfo() {
871
- var ua = navigator.userAgent;
883
+ // Bound the user-agent length before running any regex to avoid
884
+ // pathological backtracking (ReDoS) on maliciously long inputs.
885
+ var ua = (navigator.userAgent || '').slice(0, 256);
872
886
  var M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
873
- var tem;
874
- if (/trident/i.test(M[1])) {
875
- tem = /\brv[ :](\d+)/.exec(ua) || [];
887
+ var tem = null;
888
+ if (/trident/i.test(M[1] || '')) {
889
+ tem = ua.match(/\brv[ :](\d+)/) || [];
876
890
  return {
877
891
  name: 'IE',
878
892
  version: tem[1] || ''
@@ -888,8 +902,8 @@ var Browser = /*#__PURE__*/function () {
888
902
  }
889
903
  }
890
904
  M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
891
- // tslint:disable-next-line:no-conditional-assignment
892
- if ((tem = ua.match(/version\/(\d+)/i)) != null) {
905
+ tem = ua.match(/version\/(\d+)/i);
906
+ if (tem != null) {
893
907
  M.splice(1, 1, tem[1]);
894
908
  }
895
909
  return {
@@ -954,246 +968,6 @@ var ApiCharge = /*#__PURE__*/function () {
954
968
  }]);
955
969
  }();
956
970
 
957
- var ENV = {
958
- SANDBOX: 'sandbox',
959
- SANDBOX_KOVENA: 'sandbox-kovena',
960
- SANDBOX_DEMO: 'sandbox-demo',
961
- SANDBOX_DEMO_KOVENA: 'sandbox-demo-kovena',
962
- PROD: 'production',
963
- STAGING: 'staging',
964
- STAGING_1: 'staging_1',
965
- STAGING_2: 'staging_2',
966
- STAGING_3: 'staging_3',
967
- STAGING_4: 'staging_4',
968
- STAGING_5: 'staging_5',
969
- STAGING_6: 'staging_6',
970
- STAGING_7: 'staging_7',
971
- STAGING_8: 'staging_8',
972
- STAGING_9: 'staging_9',
973
- STAGING_10: 'staging_10',
974
- STAGING_11: 'staging_11',
975
- STAGING_12: 'staging_12',
976
- STAGING_13: 'staging_13',
977
- STAGING_14: 'staging_14',
978
- STAGING_15: 'staging_15'
979
- };
980
- var WIDGET_URL = [{
981
- env: ENV.SANDBOX,
982
- url: 'https://widget-sandbox.'
983
- }, {
984
- env: ENV.SANDBOX_KOVENA,
985
- url: 'https://widget-sandbox.'
986
- }, {
987
- env: ENV.SANDBOX_DEMO,
988
- url: 'https://widget-sandbox-demo.'
989
- }, {
990
- env: ENV.SANDBOX_DEMO_KOVENA,
991
- url: 'https://widget-sandbox-demo.'
992
- }, {
993
- env: ENV.PROD,
994
- url: 'https://widget.'
995
- }, {
996
- env: ENV.STAGING,
997
- url: 'https://widsta.'
998
- }, {
999
- env: ENV.STAGING_1,
1000
- url: 'https://widsta-1.'
1001
- }, {
1002
- env: ENV.STAGING_2,
1003
- url: 'https://widsta-2.'
1004
- }, {
1005
- env: ENV.STAGING_3,
1006
- url: 'https://widsta-3.'
1007
- }, {
1008
- env: ENV.STAGING_4,
1009
- url: 'https://widsta-4.'
1010
- }, {
1011
- env: ENV.STAGING_5,
1012
- url: 'https://widsta-5.'
1013
- }, {
1014
- env: ENV.STAGING_6,
1015
- url: 'https://widsta-6.'
1016
- }, {
1017
- env: ENV.STAGING_7,
1018
- url: 'https://widsta-7.'
1019
- }, {
1020
- env: ENV.STAGING_8,
1021
- url: 'https://widsta-8.'
1022
- }, {
1023
- env: ENV.STAGING_9,
1024
- url: 'https://widsta-9.'
1025
- }, {
1026
- env: ENV.STAGING_10,
1027
- url: 'https://widsta-10.'
1028
- }, {
1029
- env: ENV.STAGING_11,
1030
- url: 'https://widsta-11.'
1031
- }, {
1032
- env: ENV.STAGING_12,
1033
- url: 'https://widsta-12.'
1034
- }, {
1035
- env: ENV.STAGING_13,
1036
- url: 'https://widsta-13.'
1037
- }, {
1038
- env: ENV.STAGING_14,
1039
- url: 'https://widsta-14.'
1040
- }, {
1041
- env: ENV.STAGING_15,
1042
- url: 'https://widsta-15.'
1043
- }];
1044
- var API_URL = [{
1045
- env: ENV.SANDBOX,
1046
- url: 'https://api-sandbox.'
1047
- }, {
1048
- env: ENV.PROD,
1049
- url: 'https://api.'
1050
- }, {
1051
- env: ENV.STAGING,
1052
- url: 'https://apista.'
1053
- }, {
1054
- env: ENV.STAGING_1,
1055
- url: 'https://apista-1.'
1056
- }, {
1057
- env: ENV.STAGING_2,
1058
- url: 'https://apista-2.'
1059
- }, {
1060
- env: ENV.STAGING_3,
1061
- url: 'https://apista-3.'
1062
- }, {
1063
- env: ENV.STAGING_4,
1064
- url: 'https://apista-4.'
1065
- }, {
1066
- env: ENV.STAGING_5,
1067
- url: 'https://apista-5.'
1068
- }, {
1069
- env: ENV.STAGING_6,
1070
- url: 'https://apista-6.'
1071
- }, {
1072
- env: ENV.STAGING_7,
1073
- url: 'https://apista-7.'
1074
- }, {
1075
- env: ENV.STAGING_8,
1076
- url: 'https://apista-8.'
1077
- }, {
1078
- env: ENV.STAGING_9,
1079
- url: 'https://apista-9.'
1080
- }, {
1081
- env: ENV.STAGING_10,
1082
- url: 'https://apista-10.'
1083
- }, {
1084
- env: ENV.STAGING_11,
1085
- url: 'https://apista-11.'
1086
- }, {
1087
- env: ENV.STAGING_12,
1088
- url: 'https://apista-12.'
1089
- }, {
1090
- env: ENV.STAGING_13,
1091
- url: 'https://apista-13.'
1092
- }, {
1093
- env: ENV.STAGING_14,
1094
- url: 'https://apista-14.'
1095
- }, {
1096
- env: ENV.STAGING_15,
1097
- url: 'https://apista-15.'
1098
- }];
1099
- var ADDITIONAL_ENV = [ENV.SANDBOX_KOVENA, ENV.SANDBOX_DEMO_KOVENA];
1100
- var REGEX_ALIAS = '^([a-zA-Z0-9](?:(?:[a-zA-Z0-9-.]*(?!-)\\.(?![-.]))*[a-zA-Z0-9]+)?)$';
1101
- var DEFAULT_ENV = ENV.SANDBOX;
1102
- var DEFAULT_ALIAS = {
1103
- PAYDOCK: 'paydock.com',
1104
- KOVENA: 'kovena.com'
1105
- };
1106
- // TODO @ingeniousraccoons we should take advantage of TypeScript mechanism for static environmentId checking and simplified runtime validation
1107
- // TODO @ingeniousraccoons unify `environment.paydock.ts` and `environment.cba.ts` making them configuration driven
1108
- var Env = /*#__PURE__*/function () {
1109
- function Env(configs) {
1110
- var defaultEnv = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_ENV;
1111
- _classCallCheck(this, Env);
1112
- this.environmentConfigurations = configs;
1113
- this.setEnv(defaultEnv);
1114
- }
1115
- return _createClass(Env, [{
1116
- key: "setEnv",
1117
- value: function setEnv(environmentId, alias) {
1118
- this.validateAlias(alias);
1119
- this.validateEnvironmentId(environmentId);
1120
- this.environmentId = environmentId;
1121
- if (alias) {
1122
- this.alias = alias;
1123
- } else if (ADDITIONAL_ENV.includes(this.environmentId)) {
1124
- this.alias = DEFAULT_ALIAS.KOVENA;
1125
- } else {
1126
- this.alias = DEFAULT_ALIAS.PAYDOCK;
1127
- }
1128
- }
1129
- }, {
1130
- key: "getEnv",
1131
- value: function getEnv() {
1132
- return this.environmentId;
1133
- }
1134
- }, {
1135
- key: "getConf",
1136
- value: function getConf() {
1137
- for (var index in this.environmentConfigurations) {
1138
- if (!Object.hasOwn(this.environmentConfigurations, index)) {
1139
- continue;
1140
- }
1141
- if (this.environmentConfigurations[index].env === this.getEnv()) {
1142
- return {
1143
- url: this.environmentConfigurations[index].url.indexOf('localhost') !== -1 ? this.environmentConfigurations[index].url : this.environmentConfigurations[index].url + this.alias,
1144
- env: this.environmentConfigurations[index].env
1145
- };
1146
- }
1147
- }
1148
- throw new Error('Env could not obtain configuration. Unknown environmentId.');
1149
- }
1150
- }, {
1151
- key: "validateAlias",
1152
- value: function validateAlias(alias) {
1153
- if (typeof alias === 'undefined') {
1154
- return;
1155
- }
1156
- if (typeof alias !== 'string') {
1157
- throw new TypeError("Env expects parameter 'alias' to be of type 'string' or 'undefined'.");
1158
- }
1159
- if (!alias.match(REGEX_ALIAS)) {
1160
- throw new Error("Env received malformed alias: ".concat(alias, ". Ensure it satisfies the regex: '").concat(REGEX_ALIAS, "'."));
1161
- }
1162
- }
1163
- }, {
1164
- key: "validateEnvironmentId",
1165
- value: function validateEnvironmentId(environmentId) {
1166
- for (var index in this.environmentConfigurations) {
1167
- if (!Object.hasOwn(this.environmentConfigurations, index)) {
1168
- continue;
1169
- }
1170
- if (this.environmentConfigurations[index].env === environmentId) {
1171
- return;
1172
- }
1173
- }
1174
- throw new TypeError("Env received unknown environmentId: ".concat(environmentId));
1175
- }
1176
- }]);
1177
- }();
1178
-
1179
- var SDK = /*#__PURE__*/function () {
1180
- function SDK() {
1181
- _classCallCheck(this, SDK);
1182
- }
1183
- return _createClass(SDK, null, [{
1184
- key: "version",
1185
- get: function get() {
1186
- return SDK._version.trim() || null;
1187
- }
1188
- }]);
1189
- }();
1190
- SDK.type = 'client';
1191
- SDK.headerKeys = Object.freeze({
1192
- version: 'x-sdk-version',
1193
- type: 'x-sdk-type'
1194
- });
1195
- SDK._version = 'v1.144.0-beta';
1196
-
1197
971
  function isFunction(value) {
1198
972
  return typeof value === 'function';
1199
973
  }
@@ -1851,17 +1625,257 @@ var BehaviorSubject = (function (_super) {
1851
1625
  return BehaviorSubject;
1852
1626
  }(Subject));
1853
1627
 
1854
- var ACCESS_HEADER_NAME = {
1855
- accessToken: 'x-access-token',
1856
- publicKey: 'x-user-public-key'
1857
- };
1858
- var AccessToken = /*#__PURE__*/function () {
1859
- function AccessToken() {
1860
- _classCallCheck(this, AccessToken);
1861
- }
1862
- return _createClass(AccessToken, null, [{
1863
- key: "validateJWT",
1864
- value: function validateJWT(jwt) {
1628
+ var ENV = {
1629
+ SANDBOX: 'sandbox',
1630
+ SANDBOX_KOVENA: 'sandbox-kovena',
1631
+ SANDBOX_DEMO: 'sandbox-demo',
1632
+ SANDBOX_DEMO_KOVENA: 'sandbox-demo-kovena',
1633
+ PROD: 'production',
1634
+ STAGING: 'staging',
1635
+ STAGING_1: 'staging_1',
1636
+ STAGING_2: 'staging_2',
1637
+ STAGING_3: 'staging_3',
1638
+ STAGING_4: 'staging_4',
1639
+ STAGING_5: 'staging_5',
1640
+ STAGING_6: 'staging_6',
1641
+ STAGING_7: 'staging_7',
1642
+ STAGING_8: 'staging_8',
1643
+ STAGING_9: 'staging_9',
1644
+ STAGING_10: 'staging_10',
1645
+ STAGING_11: 'staging_11',
1646
+ STAGING_12: 'staging_12',
1647
+ STAGING_13: 'staging_13',
1648
+ STAGING_14: 'staging_14',
1649
+ STAGING_15: 'staging_15'
1650
+ };
1651
+ var WIDGET_URL = [{
1652
+ env: ENV.SANDBOX,
1653
+ url: 'https://widget-sandbox.'
1654
+ }, {
1655
+ env: ENV.SANDBOX_KOVENA,
1656
+ url: 'https://widget-sandbox.'
1657
+ }, {
1658
+ env: ENV.SANDBOX_DEMO,
1659
+ url: 'https://widget-sandbox-demo.'
1660
+ }, {
1661
+ env: ENV.SANDBOX_DEMO_KOVENA,
1662
+ url: 'https://widget-sandbox-demo.'
1663
+ }, {
1664
+ env: ENV.PROD,
1665
+ url: 'https://widget.'
1666
+ }, {
1667
+ env: ENV.STAGING,
1668
+ url: 'https://widsta.'
1669
+ }, {
1670
+ env: ENV.STAGING_1,
1671
+ url: 'https://widsta-1.'
1672
+ }, {
1673
+ env: ENV.STAGING_2,
1674
+ url: 'https://widsta-2.'
1675
+ }, {
1676
+ env: ENV.STAGING_3,
1677
+ url: 'https://widsta-3.'
1678
+ }, {
1679
+ env: ENV.STAGING_4,
1680
+ url: 'https://widsta-4.'
1681
+ }, {
1682
+ env: ENV.STAGING_5,
1683
+ url: 'https://widsta-5.'
1684
+ }, {
1685
+ env: ENV.STAGING_6,
1686
+ url: 'https://widsta-6.'
1687
+ }, {
1688
+ env: ENV.STAGING_7,
1689
+ url: 'https://widsta-7.'
1690
+ }, {
1691
+ env: ENV.STAGING_8,
1692
+ url: 'https://widsta-8.'
1693
+ }, {
1694
+ env: ENV.STAGING_9,
1695
+ url: 'https://widsta-9.'
1696
+ }, {
1697
+ env: ENV.STAGING_10,
1698
+ url: 'https://widsta-10.'
1699
+ }, {
1700
+ env: ENV.STAGING_11,
1701
+ url: 'https://widsta-11.'
1702
+ }, {
1703
+ env: ENV.STAGING_12,
1704
+ url: 'https://widsta-12.'
1705
+ }, {
1706
+ env: ENV.STAGING_13,
1707
+ url: 'https://widsta-13.'
1708
+ }, {
1709
+ env: ENV.STAGING_14,
1710
+ url: 'https://widsta-14.'
1711
+ }, {
1712
+ env: ENV.STAGING_15,
1713
+ url: 'https://widsta-15.'
1714
+ }];
1715
+ var API_URL = [{
1716
+ env: ENV.SANDBOX,
1717
+ url: 'https://api-sandbox.'
1718
+ }, {
1719
+ env: ENV.PROD,
1720
+ url: 'https://api.'
1721
+ }, {
1722
+ env: ENV.STAGING,
1723
+ url: 'https://apista.'
1724
+ }, {
1725
+ env: ENV.STAGING_1,
1726
+ url: 'https://apista-1.'
1727
+ }, {
1728
+ env: ENV.STAGING_2,
1729
+ url: 'https://apista-2.'
1730
+ }, {
1731
+ env: ENV.STAGING_3,
1732
+ url: 'https://apista-3.'
1733
+ }, {
1734
+ env: ENV.STAGING_4,
1735
+ url: 'https://apista-4.'
1736
+ }, {
1737
+ env: ENV.STAGING_5,
1738
+ url: 'https://apista-5.'
1739
+ }, {
1740
+ env: ENV.STAGING_6,
1741
+ url: 'https://apista-6.'
1742
+ }, {
1743
+ env: ENV.STAGING_7,
1744
+ url: 'https://apista-7.'
1745
+ }, {
1746
+ env: ENV.STAGING_8,
1747
+ url: 'https://apista-8.'
1748
+ }, {
1749
+ env: ENV.STAGING_9,
1750
+ url: 'https://apista-9.'
1751
+ }, {
1752
+ env: ENV.STAGING_10,
1753
+ url: 'https://apista-10.'
1754
+ }, {
1755
+ env: ENV.STAGING_11,
1756
+ url: 'https://apista-11.'
1757
+ }, {
1758
+ env: ENV.STAGING_12,
1759
+ url: 'https://apista-12.'
1760
+ }, {
1761
+ env: ENV.STAGING_13,
1762
+ url: 'https://apista-13.'
1763
+ }, {
1764
+ env: ENV.STAGING_14,
1765
+ url: 'https://apista-14.'
1766
+ }, {
1767
+ env: ENV.STAGING_15,
1768
+ url: 'https://apista-15.'
1769
+ }];
1770
+ var ADDITIONAL_ENV = [ENV.SANDBOX_KOVENA, ENV.SANDBOX_DEMO_KOVENA];
1771
+ var REGEX_ALIAS = '^([a-zA-Z0-9](?:(?:[a-zA-Z0-9-.]*(?!-)\\.(?![-.]))*[a-zA-Z0-9]+)?)$';
1772
+ var DEFAULT_ENV = ENV.SANDBOX;
1773
+ var DEFAULT_ALIAS = {
1774
+ PAYDOCK: 'paydock.com',
1775
+ KOVENA: 'kovena.com'
1776
+ };
1777
+ // TODO @ingeniousraccoons we should take advantage of TypeScript mechanism for static environmentId checking and simplified runtime validation
1778
+ // TODO @ingeniousraccoons unify `environment.paydock.ts` and `environment.cba.ts` making them configuration driven
1779
+ var Env = /*#__PURE__*/function () {
1780
+ function Env(configs) {
1781
+ var defaultEnv = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_ENV;
1782
+ _classCallCheck(this, Env);
1783
+ this.environmentConfigurations = configs;
1784
+ this.setEnv(defaultEnv);
1785
+ }
1786
+ return _createClass(Env, [{
1787
+ key: "setEnv",
1788
+ value: function setEnv(environmentId, alias) {
1789
+ this.validateAlias(alias);
1790
+ this.validateEnvironmentId(environmentId);
1791
+ this.environmentId = environmentId;
1792
+ if (alias) {
1793
+ this.alias = alias;
1794
+ } else if (ADDITIONAL_ENV.includes(this.environmentId)) {
1795
+ this.alias = DEFAULT_ALIAS.KOVENA;
1796
+ } else {
1797
+ this.alias = DEFAULT_ALIAS.PAYDOCK;
1798
+ }
1799
+ }
1800
+ }, {
1801
+ key: "getEnv",
1802
+ value: function getEnv() {
1803
+ return this.environmentId;
1804
+ }
1805
+ }, {
1806
+ key: "getConf",
1807
+ value: function getConf() {
1808
+ for (var index in this.environmentConfigurations) {
1809
+ if (!Object.hasOwn(this.environmentConfigurations, index)) {
1810
+ continue;
1811
+ }
1812
+ if (this.environmentConfigurations[index].env === this.getEnv()) {
1813
+ return {
1814
+ url: this.environmentConfigurations[index].url.indexOf('localhost') !== -1 ? this.environmentConfigurations[index].url : this.environmentConfigurations[index].url + this.alias,
1815
+ env: this.environmentConfigurations[index].env
1816
+ };
1817
+ }
1818
+ }
1819
+ throw new Error('Env could not obtain configuration. Unknown environmentId.');
1820
+ }
1821
+ }, {
1822
+ key: "validateAlias",
1823
+ value: function validateAlias(alias) {
1824
+ if (typeof alias === 'undefined') {
1825
+ return;
1826
+ }
1827
+ if (typeof alias !== 'string') {
1828
+ throw new TypeError("Env expects parameter 'alias' to be of type 'string' or 'undefined'.");
1829
+ }
1830
+ if (!alias.match(REGEX_ALIAS)) {
1831
+ throw new Error("Env received malformed alias: ".concat(alias, ". Ensure it satisfies the regex: '").concat(REGEX_ALIAS, "'."));
1832
+ }
1833
+ }
1834
+ }, {
1835
+ key: "validateEnvironmentId",
1836
+ value: function validateEnvironmentId(environmentId) {
1837
+ for (var index in this.environmentConfigurations) {
1838
+ if (!Object.hasOwn(this.environmentConfigurations, index)) {
1839
+ continue;
1840
+ }
1841
+ if (this.environmentConfigurations[index].env === environmentId) {
1842
+ return;
1843
+ }
1844
+ }
1845
+ throw new TypeError("Env received unknown environmentId: ".concat(environmentId));
1846
+ }
1847
+ }]);
1848
+ }();
1849
+
1850
+ var SDK = /*#__PURE__*/function () {
1851
+ function SDK() {
1852
+ _classCallCheck(this, SDK);
1853
+ }
1854
+ return _createClass(SDK, null, [{
1855
+ key: "version",
1856
+ get: function get() {
1857
+ return SDK._version.trim() || null;
1858
+ }
1859
+ }]);
1860
+ }();
1861
+ SDK.type = 'client';
1862
+ SDK.headerKeys = Object.freeze({
1863
+ version: 'x-sdk-version',
1864
+ type: 'x-sdk-type'
1865
+ });
1866
+ SDK._version = 'v1.145.0-beta';
1867
+
1868
+ var ACCESS_HEADER_NAME = {
1869
+ accessToken: 'x-access-token',
1870
+ publicKey: 'x-user-public-key'
1871
+ };
1872
+ var AccessToken = /*#__PURE__*/function () {
1873
+ function AccessToken() {
1874
+ _classCallCheck(this, AccessToken);
1875
+ }
1876
+ return _createClass(AccessToken, null, [{
1877
+ key: "validateJWT",
1878
+ value: function validateJWT(jwt) {
1865
1879
  if (!jwt) return null;
1866
1880
  var _jwt$split = jwt.split("."),
1867
1881
  _jwt$split2 = _slicedToArray(_jwt$split, 3),
@@ -1939,7 +1953,140 @@ var AccessToken = /*#__PURE__*/function () {
1939
1953
  return jwtPattern.test(value);
1940
1954
  }
1941
1955
  }]);
1942
- }();
1956
+ }();
1957
+
1958
+ /**
1959
+ * Top-level classification of an error. Used by the SDK to route errors to the
1960
+ * right category in instrumentation and to give consumers a coarse-grained
1961
+ * tag for grouping/filtering. See {@link getErrorCategory} for the mapping
1962
+ * between {@link ERROR_CAUSE} and {@link ERROR_CATEGORY}.
1963
+ */
1964
+ var ERROR_CATEGORY = {
1965
+ /** SDK was misconfigured (missing keys, invalid options, etc.). */
1966
+ CONFIGURATION: 'configuration',
1967
+ /** Authentication or authorization failure. */
1968
+ IDENTITY: 'identity_access_management',
1969
+ /** SDK internal failure or upstream service problem. */
1970
+ INTERNAL: 'internal',
1971
+ /** Flow lifecycle event (user cancelled, aborted, etc.) — not a real fault. */
1972
+ PROCESS: 'process',
1973
+ /** Resource lookup failed or was rate-limited. */
1974
+ RESOURCE: 'resource',
1975
+ /** Invalid input or business-rule validation failure. */
1976
+ VALIDATION: 'validation'
1977
+ };
1978
+ /**
1979
+ * Concrete cause of an error. More specific than {@link ERROR_CATEGORY} —
1980
+ * useful for deciding programmatic responses (e.g. show a retry button only
1981
+ * when `cause` is `'service_unreachable'` or `'server_busy'`).
1982
+ */
1983
+ var ERROR_CAUSE = {
1984
+ /** Operation was aborted programmatically. */
1985
+ ABORTED: 'aborted',
1986
+ /** Caller has insufficient permissions for the operation. */
1987
+ ACCESS_FORBIDDEN: 'access_forbidden',
1988
+ /** Resource already exists when create was expected. */
1989
+ ALREADY_EXISTS: 'already_exists',
1990
+ /** User cancelled the flow (e.g. closed the wallet sheet). */
1991
+ CANCELED: 'canceled',
1992
+ /** SDK was instantiated or invoked with invalid configuration. */
1993
+ INVALID_CONFIGURATION: 'invalid_configuration',
1994
+ /** Input failed structural or business-rule validation. */
1995
+ INVALID_INPUT: 'invalid_input',
1996
+ /** Resource was not found by the backend. */
1997
+ NOT_FOUND: 'not_found',
1998
+ /** Operation is not supported in the current context or version. */
1999
+ NOT_IMPLEMENTED: 'not_implemented',
2000
+ /** Caller exceeded the allowed request rate. */
2001
+ RATE_LIMITED: 'rate_limited',
2002
+ /** Backend is healthy but currently overloaded — typically retryable. */
2003
+ SERVER_BUSY: 'server_busy',
2004
+ /** Backend or third-party service could not be reached — typically retryable. */
2005
+ SERVICE_UNREACHABLE: 'service_unreachable',
2006
+ /** Caller is not authenticated. */
2007
+ UNAUTHORIZED: 'unauthorized',
2008
+ /** Catch-all when no other cause applies. */
2009
+ UNKNOWN: 'unknown_error',
2010
+ /** Request was syntactically valid but semantically rejected. */
2011
+ UNPROCESSABLE_ENTITY: 'unprocessable_entity'
2012
+ };
2013
+ var EventError = /*#__PURE__*/function (_Error) {
2014
+ function EventError(cause, category, retryable, details) {
2015
+ var _this;
2016
+ _classCallCheck(this, EventError);
2017
+ _this = _callSuper(this, EventError, [details.message]);
2018
+ _this.cause = cause;
2019
+ _this.category = category;
2020
+ _this.retryable = retryable;
2021
+ _this.details = details;
2022
+ Object.setPrototypeOf(_this, EventError.prototype);
2023
+ _this.name = EventError.name;
2024
+ return _this;
2025
+ }
2026
+ _inherits(EventError, _Error);
2027
+ return _createClass(EventError, [{
2028
+ key: "toJSON",
2029
+ value: function toJSON() {
2030
+ return {
2031
+ error: {
2032
+ category: this.category,
2033
+ cause: this.cause,
2034
+ details: this.details,
2035
+ retryable: this.retryable
2036
+ }
2037
+ };
2038
+ }
2039
+ }, {
2040
+ key: "setContextId",
2041
+ value: function setContextId(contextId) {
2042
+ this.details.contextId = contextId;
2043
+ }
2044
+ }, {
2045
+ key: "setPurpose",
2046
+ value: function setPurpose(purpose) {
2047
+ this.purpose = purpose;
2048
+ }
2049
+ }], [{
2050
+ key: "create",
2051
+ value: function create(cause, message) {
2052
+ var contextId = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
2053
+ var retryable = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
2054
+ var details = {
2055
+ cause: cause,
2056
+ contextId: contextId,
2057
+ message: message,
2058
+ timestamp: new Date().toISOString()
2059
+ };
2060
+ var category = getErrorCategory(cause);
2061
+ return new EventError(cause, category, retryable, details);
2062
+ }
2063
+ }]);
2064
+ }(/*#__PURE__*/_wrapNativeSuper(Error));
2065
+ function getErrorCategory(cause) {
2066
+ switch (cause) {
2067
+ case ERROR_CAUSE.INVALID_CONFIGURATION:
2068
+ return ERROR_CATEGORY.CONFIGURATION;
2069
+ case ERROR_CAUSE.ACCESS_FORBIDDEN:
2070
+ case ERROR_CAUSE.UNAUTHORIZED:
2071
+ return ERROR_CATEGORY.IDENTITY;
2072
+ case ERROR_CAUSE.SERVICE_UNREACHABLE:
2073
+ case ERROR_CAUSE.NOT_IMPLEMENTED:
2074
+ case ERROR_CAUSE.SERVER_BUSY:
2075
+ return ERROR_CATEGORY.INTERNAL;
2076
+ case ERROR_CAUSE.ABORTED:
2077
+ case ERROR_CAUSE.CANCELED:
2078
+ return ERROR_CATEGORY.PROCESS;
2079
+ case ERROR_CAUSE.NOT_FOUND:
2080
+ case ERROR_CAUSE.RATE_LIMITED:
2081
+ return ERROR_CATEGORY.RESOURCE;
2082
+ case ERROR_CAUSE.ALREADY_EXISTS:
2083
+ case ERROR_CAUSE.INVALID_INPUT:
2084
+ case ERROR_CAUSE.UNPROCESSABLE_ENTITY:
2085
+ return ERROR_CATEGORY.VALIDATION;
2086
+ default:
2087
+ return ERROR_CATEGORY.INTERNAL;
2088
+ }
2089
+ }
1943
2090
 
1944
2091
  var HttpRequest = /*#__PURE__*/function () {
1945
2092
  function HttpRequest(request) {
@@ -4635,18 +4782,23 @@ var ApiBase = /*#__PURE__*/function () {
4635
4782
  var errorCb = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : function (data) {
4636
4783
  return undefined;
4637
4784
  };
4785
+ var onError = function onError(err) {
4786
+ _this4.reportError(errorRepository, err, _extends(_extends({}, _this4.ctx), {
4787
+ classMethod: 'getClient',
4788
+ description: 'Send unsuccessful.'
4789
+ }));
4790
+ errorCb(err);
4791
+ };
4638
4792
  request.onload = function () {
4639
4793
  return _this4.parser({
4640
4794
  text: request.responseText,
4641
4795
  status: request.status
4642
- }, cb, function (err) {
4643
- _this4.reportError(errorRepository, err, _extends(_extends({}, _this4.ctx), {
4644
- classMethod: 'getClient',
4645
- description: 'Send unsuccessful.'
4646
- }));
4647
- errorCb(err);
4648
- });
4796
+ }, cb, onError);
4649
4797
  };
4798
+ // Transport-level failures (dropped connection, failed CORS
4799
+ // preflight, HTTP/2 protocol error, timeout) never fire `onload`,
4800
+ // so without these handlers the request would fail silently.
4801
+ _this4.attachFailureHandlers(request, onError);
4650
4802
  request.send(JSON.stringify(body));
4651
4803
  }
4652
4804
  };
@@ -4659,13 +4811,18 @@ var ApiBase = /*#__PURE__*/function () {
4659
4811
  return {
4660
4812
  config: request,
4661
4813
  send: function send(body) {
4662
- return new Promise(function (resolve, _reject) {
4814
+ return new Promise(function (resolve, reject) {
4663
4815
  request.onload = function () {
4664
4816
  return resolve({
4665
4817
  text: request.responseText,
4666
4818
  status: request.status
4667
4819
  });
4668
4820
  };
4821
+ // Transport-level failures (dropped connection, failed CORS
4822
+ // preflight, HTTP/2 protocol error, timeout) never fire
4823
+ // `onload`, so without these handlers the promise would never
4824
+ // settle and the caller would hang silently.
4825
+ _this5.attachFailureHandlers(request, reject);
4669
4826
  request.send(JSON.stringify(body));
4670
4827
  }).then(function (value) {
4671
4828
  return _this5.parserPromise(value);
@@ -4717,6 +4874,36 @@ var ApiBase = /*#__PURE__*/function () {
4717
4874
  return Promise.reject(err);
4718
4875
  }
4719
4876
  }
4877
+ /**
4878
+ * Wires the XHR failure events that `onload` does not cover. `onload` only
4879
+ * fires when an HTTP response is received (any status, including 4xx/5xx);
4880
+ * transport-level failures — a dropped connection, a failed CORS preflight,
4881
+ * an HTTP/2 protocol error, or a timeout — fire `onerror`/`ontimeout`/
4882
+ * `onabort` instead. Without these the request never settles and fails
4883
+ * silently (e.g. `onUnavailable` is never invoked for wallet callbacks).
4884
+ */
4885
+ }, {
4886
+ key: "attachFailureHandlers",
4887
+ value: function attachFailureHandlers(request, onFailure) {
4888
+ request.onerror = function () {
4889
+ return onFailure({
4890
+ message: 'Network request failed: the service could not be reached.',
4891
+ code: ERROR_CAUSE.SERVICE_UNREACHABLE
4892
+ });
4893
+ };
4894
+ request.ontimeout = function () {
4895
+ return onFailure({
4896
+ message: 'Network request timed out: the service could not be reached.',
4897
+ code: ERROR_CAUSE.SERVICE_UNREACHABLE
4898
+ });
4899
+ };
4900
+ request.onabort = function () {
4901
+ return onFailure({
4902
+ message: 'Network request was aborted.',
4903
+ code: ERROR_CAUSE.ABORTED
4904
+ });
4905
+ };
4906
+ }
4720
4907
  }, {
4721
4908
  key: "newApiRequest",
4722
4909
  value: function newApiRequest(method, link) {
@@ -5475,12 +5662,12 @@ var Uuid = /*#__PURE__*/function () {
5475
5662
  return _createClass(Uuid, null, [{
5476
5663
  key: "generate",
5477
5664
  value: function generate() {
5478
- if (typeof window !== "undefined" && typeof window.crypto !== "undefined" && typeof window.crypto.getRandomValues !== "undefined") {
5665
+ if (typeof window !== 'undefined' && typeof window.crypto !== 'undefined' && typeof window.crypto.getRandomValues !== 'undefined') {
5479
5666
  var buf = new Uint16Array(8);
5480
5667
  window.crypto.getRandomValues(buf);
5481
- return this.hash(buf[0]) + this.hash(buf[1]) + "-" + this.hash(buf[2]) + "-" + this.hash(buf[3]) + "-" + this.hash(buf[4]) + "-" + this.hash(buf[5]) + this.hash(buf[6]) + this.hash(buf[7]);
5668
+ return Uuid.hash(buf[0]) + Uuid.hash(buf[1]) + '-' + Uuid.hash(buf[2]) + '-' + Uuid.hash(buf[3]) + '-' + Uuid.hash(buf[4]) + '-' + Uuid.hash(buf[5]) + Uuid.hash(buf[6]) + Uuid.hash(buf[7]);
5482
5669
  } else {
5483
- return this.random() + this.random() + "-" + this.random() + "-" + this.random() + "-" + this.random() + "-" + this.random() + this.random() + this.random();
5670
+ return Uuid.random() + Uuid.random() + '-' + Uuid.random() + '-' + Uuid.random() + '-' + Uuid.random() + '-' + Uuid.random() + Uuid.random() + Uuid.random();
5484
5671
  }
5485
5672
  }
5486
5673
  }, {
@@ -5488,14 +5675,22 @@ var Uuid = /*#__PURE__*/function () {
5488
5675
  value: function hash(number) {
5489
5676
  var hash = number.toString(16);
5490
5677
  while (hash.length < 4) {
5491
- hash = "0" + hash;
5678
+ hash = '0' + hash;
5492
5679
  }
5493
5680
  return hash;
5494
5681
  }
5495
5682
  }, {
5496
5683
  key: "random",
5497
5684
  value: function random() {
5498
- return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
5685
+ var value;
5686
+ if (typeof crypto !== 'undefined' && typeof crypto.getRandomValues === 'function') {
5687
+ var buf = new Uint16Array(1);
5688
+ crypto.getRandomValues(buf);
5689
+ value = buf[0] / 0x10000;
5690
+ } else {
5691
+ value = Math.random();
5692
+ }
5693
+ return Math.floor((1 + value) * 0x10000).toString(16).substring(1);
5499
5694
  }
5500
5695
  }]);
5501
5696
  }();
@@ -8170,7 +8365,7 @@ var AfterPayWalletService = /*#__PURE__*/function (_WalletService) {
8170
8365
  }]);
8171
8366
  }(WalletService);
8172
8367
 
8173
- /*! @license DOMPurify 3.4.0 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.4.0/LICENSE */
8368
+ /*! @license DOMPurify 3.4.11 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.4.11/LICENSE */
8174
8369
 
8175
8370
  var purify_cjs;
8176
8371
  var hasRequiredPurify_cjs;
@@ -8179,22 +8374,63 @@ function requirePurify_cjs () {
8179
8374
  if (hasRequiredPurify_cjs) return purify_cjs;
8180
8375
  hasRequiredPurify_cjs = 1;
8181
8376
 
8182
- const {
8183
- entries,
8184
- setPrototypeOf,
8185
- isFrozen,
8186
- getPrototypeOf,
8187
- getOwnPropertyDescriptor
8188
- } = Object;
8189
- let {
8190
- freeze,
8191
- seal,
8192
- create
8193
- } = Object; // eslint-disable-line import/no-mutable-exports
8194
- let {
8195
- apply,
8196
- construct
8197
- } = typeof Reflect !== 'undefined' && Reflect;
8377
+ function _arrayLikeToArray(r, a) {
8378
+ (null == a || a > r.length) && (a = r.length);
8379
+ for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
8380
+ return n;
8381
+ }
8382
+ function _arrayWithHoles(r) {
8383
+ if (Array.isArray(r)) return r;
8384
+ }
8385
+ function _iterableToArrayLimit(r, l) {
8386
+ var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
8387
+ if (null != t) {
8388
+ var e,
8389
+ n,
8390
+ i,
8391
+ u,
8392
+ a = [],
8393
+ f = true,
8394
+ o = false;
8395
+ try {
8396
+ if (i = (t = t.call(r)).next, 0 === l) ; else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);
8397
+ } catch (r) {
8398
+ o = true, n = r;
8399
+ } finally {
8400
+ try {
8401
+ if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;
8402
+ } finally {
8403
+ if (o) throw n;
8404
+ }
8405
+ }
8406
+ return a;
8407
+ }
8408
+ }
8409
+ function _nonIterableRest() {
8410
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
8411
+ }
8412
+ function _slicedToArray(r, e) {
8413
+ return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
8414
+ }
8415
+ function _unsupportedIterableToArray(r, a) {
8416
+ if (r) {
8417
+ if ("string" == typeof r) return _arrayLikeToArray(r, a);
8418
+ var t = {}.toString.call(r).slice(8, -1);
8419
+ return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
8420
+ }
8421
+ }
8422
+
8423
+ const entries = Object.entries,
8424
+ setPrototypeOf = Object.setPrototypeOf,
8425
+ isFrozen = Object.isFrozen,
8426
+ getPrototypeOf = Object.getPrototypeOf,
8427
+ getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
8428
+ let freeze = Object.freeze,
8429
+ seal = Object.seal,
8430
+ create = Object.create; // eslint-disable-line import/no-mutable-exports
8431
+ let _ref = typeof Reflect !== 'undefined' && Reflect,
8432
+ apply = _ref.apply,
8433
+ construct = _ref.construct;
8198
8434
  if (!freeze) {
8199
8435
  freeze = function freeze(x) {
8200
8436
  return x;
@@ -8226,13 +8462,19 @@ function requirePurify_cjs () {
8226
8462
  const arrayPop = unapply(Array.prototype.pop);
8227
8463
  const arrayPush = unapply(Array.prototype.push);
8228
8464
  const arraySplice = unapply(Array.prototype.splice);
8465
+ const arrayIsArray = Array.isArray;
8229
8466
  const stringToLowerCase = unapply(String.prototype.toLowerCase);
8230
8467
  const stringToString = unapply(String.prototype.toString);
8231
8468
  const stringMatch = unapply(String.prototype.match);
8232
8469
  const stringReplace = unapply(String.prototype.replace);
8233
8470
  const stringIndexOf = unapply(String.prototype.indexOf);
8234
8471
  const stringTrim = unapply(String.prototype.trim);
8472
+ const numberToString = unapply(Number.prototype.toString);
8473
+ const booleanToString = unapply(Boolean.prototype.toString);
8474
+ const bigintToString = typeof BigInt === 'undefined' ? null : unapply(BigInt.prototype.toString);
8475
+ const symbolToString = typeof Symbol === 'undefined' ? null : unapply(Symbol.prototype.toString);
8235
8476
  const objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty);
8477
+ const objectToString = unapply(Object.prototype.toString);
8236
8478
  const regExpTest = unapply(RegExp.prototype.test);
8237
8479
  const typeErrorCreate = unconstruct(TypeError);
8238
8480
  /**
@@ -8282,6 +8524,9 @@ function requirePurify_cjs () {
8282
8524
  // Prevent prototype setters from intercepting set as a this value.
8283
8525
  setPrototypeOf(set, null);
8284
8526
  }
8527
+ if (!arrayIsArray(array)) {
8528
+ return set;
8529
+ }
8285
8530
  let l = array.length;
8286
8531
  while (l--) {
8287
8532
  let element = array[l];
@@ -8322,10 +8567,13 @@ function requirePurify_cjs () {
8322
8567
  */
8323
8568
  function clone(object) {
8324
8569
  const newObject = create(null);
8325
- for (const [property, value] of entries(object)) {
8570
+ for (const _ref2 of entries(object)) {
8571
+ var _ref3 = _slicedToArray(_ref2, 2);
8572
+ const property = _ref3[0];
8573
+ const value = _ref3[1];
8326
8574
  const isPropertyExist = objectHasOwnProperty(object, property);
8327
8575
  if (isPropertyExist) {
8328
- if (Array.isArray(value)) {
8576
+ if (arrayIsArray(value)) {
8329
8577
  newObject[property] = cleanArray(value);
8330
8578
  } else if (value && typeof value === 'object' && value.constructor === Object) {
8331
8579
  newObject[property] = clone(value);
@@ -8336,6 +8584,58 @@ function requirePurify_cjs () {
8336
8584
  }
8337
8585
  return newObject;
8338
8586
  }
8587
+ /**
8588
+ * Convert non-node values into strings without depending on direct property access.
8589
+ *
8590
+ * @param value - The value to stringify.
8591
+ * @returns A string representation of the provided value.
8592
+ */
8593
+ function stringifyValue(value) {
8594
+ switch (typeof value) {
8595
+ case 'string':
8596
+ {
8597
+ return value;
8598
+ }
8599
+ case 'number':
8600
+ {
8601
+ return numberToString(value);
8602
+ }
8603
+ case 'boolean':
8604
+ {
8605
+ return booleanToString(value);
8606
+ }
8607
+ case 'bigint':
8608
+ {
8609
+ return bigintToString ? bigintToString(value) : '0';
8610
+ }
8611
+ case 'symbol':
8612
+ {
8613
+ return symbolToString ? symbolToString(value) : 'Symbol()';
8614
+ }
8615
+ case 'undefined':
8616
+ {
8617
+ return objectToString(value);
8618
+ }
8619
+ case 'function':
8620
+ case 'object':
8621
+ {
8622
+ if (value === null) {
8623
+ return objectToString(value);
8624
+ }
8625
+ const valueAsRecord = value;
8626
+ const valueToString = lookupGetter(valueAsRecord, 'toString');
8627
+ if (typeof valueToString === 'function') {
8628
+ const stringified = valueToString(valueAsRecord);
8629
+ return typeof stringified === 'string' ? stringified : objectToString(stringified);
8630
+ }
8631
+ return objectToString(value);
8632
+ }
8633
+ default:
8634
+ {
8635
+ return objectToString(value);
8636
+ }
8637
+ }
8638
+ }
8339
8639
  /**
8340
8640
  * This method automatically checks if the prop is function or getter and behaves accordingly.
8341
8641
  *
@@ -8361,6 +8661,14 @@ function requirePurify_cjs () {
8361
8661
  }
8362
8662
  return fallbackValue;
8363
8663
  }
8664
+ function isRegex(value) {
8665
+ try {
8666
+ regExpTest(value, '');
8667
+ return true;
8668
+ } catch (_unused) {
8669
+ return false;
8670
+ }
8671
+ }
8364
8672
 
8365
8673
  const html$1 = freeze(['a', 'abbr', 'acronym', 'address', 'area', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo', 'big', 'blink', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'content', 'data', 'datalist', 'dd', 'decorator', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'element', 'em', 'fieldset', 'figcaption', 'figure', 'font', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meter', 'nav', 'nobr', 'ol', 'optgroup', 'option', 'output', 'p', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'search', 'section', 'select', 'shadow', 'slot', 'small', 'source', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr']);
8366
8674
  const svg$1 = freeze(['svg', 'a', 'altglyph', 'altglyphdef', 'altglyphitem', 'animatecolor', 'animatemotion', 'animatetransform', 'circle', 'clippath', 'defs', 'desc', 'ellipse', 'enterkeyhint', 'exportparts', 'filter', 'font', 'g', 'glyph', 'glyphref', 'hkern', 'image', 'inputmode', 'line', 'lineargradient', 'marker', 'mask', 'metadata', 'mpath', 'part', 'path', 'pattern', 'polygon', 'polyline', 'radialgradient', 'rect', 'stop', 'style', 'switch', 'symbol', 'text', 'textpath', 'title', 'tref', 'tspan', 'view', 'vkern']);
@@ -8376,15 +8684,14 @@ function requirePurify_cjs () {
8376
8684
  const mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);
8377
8685
  const text = freeze(['#text']);
8378
8686
 
8379
- const html = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'autocomplete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'border', 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'controls', 'controlslist', 'coords', 'crossorigin', 'datetime', 'decoding', 'default', 'dir', 'disabled', 'disablepictureinpicture', 'disableremoteplayback', 'download', 'draggable', 'enctype', 'enterkeyhint', 'exportparts', 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', 'inert', 'inputmode', 'integrity', 'ismap', 'kind', 'label', 'lang', 'list', 'loading', 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'multiple', 'muted', 'name', 'nonce', 'noshade', 'novalidate', 'nowrap', 'open', 'optimum', 'part', 'pattern', 'placeholder', 'playsinline', 'popover', 'popovertarget', 'popovertargetaction', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'slot', 'span', 'srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'wrap', 'xmlns', 'slot']);
8687
+ const html = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'autocomplete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'border', 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'command', 'commandfor', 'controls', 'controlslist', 'coords', 'crossorigin', 'datetime', 'decoding', 'default', 'dir', 'disabled', 'disablepictureinpicture', 'disableremoteplayback', 'download', 'draggable', 'enctype', 'enterkeyhint', 'exportparts', 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', 'inert', 'inputmode', 'integrity', 'ismap', 'kind', 'label', 'lang', 'list', 'loading', 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'multiple', 'muted', 'name', 'nonce', 'noshade', 'novalidate', 'nowrap', 'open', 'optimum', 'part', 'pattern', 'placeholder', 'playsinline', 'popover', 'popovertarget', 'popovertargetaction', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'slot', 'span', 'srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'wrap', 'xmlns']);
8380
8688
  const svg = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', 'amplitude', 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'baseline-shift', 'begin', 'bias', 'by', 'class', 'clip', 'clippathunits', 'clip-path', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconstant', 'direction', 'display', 'divisor', 'dur', 'edgemode', 'elevation', 'end', 'exponent', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'filterunits', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'image-rendering', 'in', 'in2', 'intercept', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints', 'keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatrix', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid', 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits', 'maskunits', 'max', 'mask', 'mask-type', 'media', 'method', 'mode', 'min', 'name', 'numoctaves', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits', 'points', 'preservealpha', 'preserveaspectratio', 'primitiveunits', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 'repeatdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'slope', 'specularconstant', 'specularexponent', 'spreadmethod', 'startoffset', 'stddeviation', 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width', 'style', 'surfacescale', 'systemlanguage', 'tabindex', 'tablevalues', 'targetx', 'targety', 'transform', 'transform-origin', 'text-anchor', 'text-decoration', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', 'values', 'viewbox', 'visibility', 'version', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'width', 'word-spacing', 'wrap', 'writing-mode', 'xchannelselector', 'ychannelselector', 'x', 'x1', 'x2', 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpan']);
8381
8689
  const mathMl = freeze(['accent', 'accentunder', 'align', 'bevelled', 'close', 'columnalign', 'columnlines', 'columnspacing', 'columnspan', 'denomalign', 'depth', 'dir', 'display', 'displaystyle', 'encoding', 'fence', 'frame', 'height', 'href', 'id', 'largeop', 'length', 'linethickness', 'lquote', 'lspace', 'mathbackground', 'mathcolor', 'mathsize', 'mathvariant', 'maxsize', 'minsize', 'movablelimits', 'notation', 'numalign', 'open', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'rquote', 'scriptlevel', 'scriptminsize', 'scriptsizemultiplier', 'selection', 'separator', 'separators', 'stretchy', 'subscriptshift', 'supscriptshift', 'symmetric', 'voffset', 'width', 'xmlns']);
8382
8690
  const xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);
8383
8691
 
8384
- // eslint-disable-next-line unicorn/better-regex
8385
- const MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode
8386
- const ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm);
8387
- const TMPLIT_EXPR = seal(/\$\{[\w\W]*/gm); // eslint-disable-line unicorn/better-regex
8692
+ const MUSTACHE_EXPR = seal(/{{[\w\W]*|^[\w\W]*}}/g);
8693
+ const ERB_EXPR = seal(/<%[\w\W]*|^[\w\W]*%>/g);
8694
+ const TMPLIT_EXPR = seal(/\${[\w\W]*/g);
8388
8695
  const DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]+$/); // eslint-disable-line no-useless-escape
8389
8696
  const ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape
8390
8697
  const IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i // eslint-disable-line no-useless-escape
@@ -8394,30 +8701,31 @@ function requirePurify_cjs () {
8394
8701
  );
8395
8702
  const DOCTYPE_NAME = seal(/^html$/i);
8396
8703
  const CUSTOM_ELEMENT = seal(/^[a-z][.\w]*(-[.\w]+)+$/i);
8704
+ // Markup-significant character probes used by _sanitizeElements.
8705
+ // Shared module-level instances are safe despite the sticky /g flags:
8706
+ // unapply() resets lastIndex for RegExp receivers before every call.
8707
+ const ELEMENT_MARKUP_PROBE = seal(/<[/\w!]/g);
8708
+ const COMMENT_MARKUP_PROBE = seal(/<[/\w]/g);
8709
+ const FALLBACK_TAG_CLOSE = seal(/<\/no(script|embed|frames)/i);
8710
+ const SELF_CLOSING_TAG = seal(/\/>/i);
8397
8711
 
8398
- var EXPRESSIONS = /*#__PURE__*/Object.freeze({
8399
- __proto__: null,
8400
- ARIA_ATTR: ARIA_ATTR,
8401
- ATTR_WHITESPACE: ATTR_WHITESPACE,
8402
- CUSTOM_ELEMENT: CUSTOM_ELEMENT,
8403
- DATA_ATTR: DATA_ATTR,
8404
- DOCTYPE_NAME: DOCTYPE_NAME,
8405
- ERB_EXPR: ERB_EXPR,
8406
- IS_ALLOWED_URI: IS_ALLOWED_URI,
8407
- IS_SCRIPT_OR_DATA: IS_SCRIPT_OR_DATA,
8408
- MUSTACHE_EXPR: MUSTACHE_EXPR,
8409
- TMPLIT_EXPR: TMPLIT_EXPR
8410
- });
8411
-
8412
- /* eslint-disable @typescript-eslint/indent */
8413
8712
  // https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType
8414
8713
  const NODE_TYPE = {
8415
8714
  element: 1,
8715
+ attribute: 2,
8416
8716
  text: 3,
8717
+ cdataSection: 4,
8718
+ entityReference: 5,
8417
8719
  // Deprecated
8418
- progressingInstruction: 7,
8720
+ entityNode: 6,
8721
+ // Deprecated
8722
+ processingInstruction: 7,
8419
8723
  comment: 8,
8420
- document: 9};
8724
+ document: 9,
8725
+ documentType: 10,
8726
+ documentFragment: 11,
8727
+ notation: 12 // Deprecated
8728
+ };
8421
8729
  const getGlobal = function getGlobal() {
8422
8730
  return typeof window === 'undefined' ? null : window;
8423
8731
  };
@@ -8472,10 +8780,25 @@ function requirePurify_cjs () {
8472
8780
  uponSanitizeShadowNode: []
8473
8781
  };
8474
8782
  };
8783
+ /**
8784
+ * Resolve a set-valued configuration option: a fresh set built from
8785
+ * cfg[key] when it is an own array property (seeded with a clone of
8786
+ * options.base when given, case-normalized via options.transform),
8787
+ * the fallback set otherwise.
8788
+ *
8789
+ * @param cfg the cloned, prototype-free configuration object
8790
+ * @param key the configuration property to read
8791
+ * @param fallback the set to use when the option is absent or not an array
8792
+ * @param options transform and optional base set to merge into
8793
+ * @returns the resolved set
8794
+ */
8795
+ const _resolveSetOption = function _resolveSetOption(cfg, key, fallback, options) {
8796
+ return objectHasOwnProperty(cfg, key) && arrayIsArray(cfg[key]) ? addToSet(options.base ? clone(options.base) : {}, cfg[key], options.transform) : fallback;
8797
+ };
8475
8798
  function createDOMPurify() {
8476
8799
  let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();
8477
8800
  const DOMPurify = root => createDOMPurify(root);
8478
- DOMPurify.version = '3.4.0';
8801
+ DOMPurify.version = '3.4.11';
8479
8802
  DOMPurify.removed = [];
8480
8803
  if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document || !window.Element) {
8481
8804
  // Not running in a browser, provide a factory function
@@ -8483,28 +8806,29 @@ function requirePurify_cjs () {
8483
8806
  DOMPurify.isSupported = false;
8484
8807
  return DOMPurify;
8485
8808
  }
8486
- let {
8487
- document
8488
- } = window;
8809
+ let document = window.document;
8489
8810
  const originalDocument = document;
8490
8811
  const currentScript = originalDocument.currentScript;
8491
- const {
8492
- DocumentFragment,
8493
- HTMLTemplateElement,
8494
- Node,
8495
- Element,
8496
- NodeFilter,
8497
- NamedNodeMap = window.NamedNodeMap || window.MozNamedAttrMap,
8498
- HTMLFormElement,
8499
- DOMParser,
8500
- trustedTypes
8501
- } = window;
8812
+ window.DocumentFragment;
8813
+ const HTMLTemplateElement = window.HTMLTemplateElement,
8814
+ Node = window.Node,
8815
+ Element = window.Element,
8816
+ NodeFilter = window.NodeFilter,
8817
+ _window$NamedNodeMap = window.NamedNodeMap;
8818
+ _window$NamedNodeMap === void 0 ? window.NamedNodeMap || window.MozNamedAttrMap : _window$NamedNodeMap;
8819
+ window.HTMLFormElement;
8820
+ const DOMParser = window.DOMParser,
8821
+ trustedTypes = window.trustedTypes;
8502
8822
  const ElementPrototype = Element.prototype;
8503
8823
  const cloneNode = lookupGetter(ElementPrototype, 'cloneNode');
8504
8824
  const remove = lookupGetter(ElementPrototype, 'remove');
8505
8825
  const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');
8506
8826
  const getChildNodes = lookupGetter(ElementPrototype, 'childNodes');
8507
8827
  const getParentNode = lookupGetter(ElementPrototype, 'parentNode');
8828
+ const getShadowRoot = lookupGetter(ElementPrototype, 'shadowRoot');
8829
+ const getAttributes = lookupGetter(ElementPrototype, 'attributes');
8830
+ const getNodeType = Node && Node.prototype ? lookupGetter(Node.prototype, 'nodeType') : null;
8831
+ const getNodeName = Node && Node.prototype ? lookupGetter(Node.prototype, 'nodeName') : null;
8508
8832
  // As per issue #47, the web-components registry is inherited by a
8509
8833
  // new document created via createHTMLDocument. As per the spec
8510
8834
  // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)
@@ -8519,33 +8843,74 @@ function requirePurify_cjs () {
8519
8843
  }
8520
8844
  let trustedTypesPolicy;
8521
8845
  let emptyHTML = '';
8522
- const {
8523
- implementation,
8524
- createNodeIterator,
8525
- createDocumentFragment,
8526
- getElementsByTagName
8527
- } = document;
8528
- const {
8529
- importNode
8530
- } = originalDocument;
8846
+ // The instance's own internal Trusted Types policy. Unlike a caller-supplied
8847
+ // `TRUSTED_TYPES_POLICY`, this is created at most once — Trusted Types throws
8848
+ // on duplicate policy names — and is the only policy allowed to persist
8849
+ // across configurations and survive `clearConfig()`.
8850
+ let defaultTrustedTypesPolicy;
8851
+ let defaultTrustedTypesPolicyResolved = false;
8852
+ // Tracks whether we are already inside a call to the configured Trusted Types
8853
+ // policy (`createHTML` or `createScriptURL`). If a supplied policy callback
8854
+ // itself calls `DOMPurify.sanitize` (the cause of #1422), `sanitize` would
8855
+ // re-enter the policy and recurse until the stack overflows. We detect that
8856
+ // re-entry and throw a clear, actionable error instead. The guard is shared
8857
+ // across both callbacks, because either one re-entering `sanitize` triggers
8858
+ // the same unbounded recursion.
8859
+ let IN_TRUSTED_TYPES_POLICY = 0;
8860
+ const _assertNotInTrustedTypesPolicy = function _assertNotInTrustedTypesPolicy() {
8861
+ if (IN_TRUSTED_TYPES_POLICY > 0) {
8862
+ throw typeErrorCreate('A configured TRUSTED_TYPES_POLICY callback (createHTML or ' + 'createScriptURL) must not call DOMPurify.sanitize, as that causes ' + 'infinite recursion. Do not pass a policy whose callbacks wrap ' + 'DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted ' + 'Types" section of the README.');
8863
+ }
8864
+ };
8865
+ const _createTrustedHTML = function _createTrustedHTML(html) {
8866
+ _assertNotInTrustedTypesPolicy();
8867
+ IN_TRUSTED_TYPES_POLICY++;
8868
+ try {
8869
+ return trustedTypesPolicy.createHTML(html);
8870
+ } finally {
8871
+ IN_TRUSTED_TYPES_POLICY--;
8872
+ }
8873
+ };
8874
+ const _createTrustedScriptURL = function _createTrustedScriptURL(scriptUrl) {
8875
+ _assertNotInTrustedTypesPolicy();
8876
+ IN_TRUSTED_TYPES_POLICY++;
8877
+ try {
8878
+ return trustedTypesPolicy.createScriptURL(scriptUrl);
8879
+ } finally {
8880
+ IN_TRUSTED_TYPES_POLICY--;
8881
+ }
8882
+ };
8883
+ // Lazily resolve (and cache) the instance's internal default policy.
8884
+ // Resolution is attempted at most once: a successful `createPolicy` cannot be
8885
+ // repeated (Trusted Types throws on duplicate names), and a failed or
8886
+ // unsupported attempt must not be retried on every parse.
8887
+ const _getDefaultTrustedTypesPolicy = function _getDefaultTrustedTypesPolicy() {
8888
+ if (!defaultTrustedTypesPolicyResolved) {
8889
+ defaultTrustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);
8890
+ defaultTrustedTypesPolicyResolved = true;
8891
+ }
8892
+ return defaultTrustedTypesPolicy;
8893
+ };
8894
+ const _document = document,
8895
+ implementation = _document.implementation,
8896
+ createNodeIterator = _document.createNodeIterator,
8897
+ createDocumentFragment = _document.createDocumentFragment,
8898
+ getElementsByTagName = _document.getElementsByTagName;
8899
+ const importNode = originalDocument.importNode;
8531
8900
  let hooks = _createHooksMap();
8532
8901
  /**
8533
8902
  * Expose whether this browser supports running the full DOMPurify.
8534
8903
  */
8535
8904
  DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNode === 'function' && implementation && implementation.createHTMLDocument !== undefined;
8536
- const {
8537
- MUSTACHE_EXPR,
8538
- ERB_EXPR,
8539
- TMPLIT_EXPR,
8540
- DATA_ATTR,
8541
- ARIA_ATTR,
8542
- IS_SCRIPT_OR_DATA,
8543
- ATTR_WHITESPACE,
8544
- CUSTOM_ELEMENT
8545
- } = EXPRESSIONS;
8546
- let {
8547
- IS_ALLOWED_URI: IS_ALLOWED_URI$1
8548
- } = EXPRESSIONS;
8905
+ const MUSTACHE_EXPR$1 = MUSTACHE_EXPR,
8906
+ ERB_EXPR$1 = ERB_EXPR,
8907
+ TMPLIT_EXPR$1 = TMPLIT_EXPR,
8908
+ DATA_ATTR$1 = DATA_ATTR,
8909
+ ARIA_ATTR$1 = ARIA_ATTR,
8910
+ IS_SCRIPT_OR_DATA$1 = IS_SCRIPT_OR_DATA,
8911
+ ATTR_WHITESPACE$1 = ATTR_WHITESPACE,
8912
+ CUSTOM_ELEMENT$1 = CUSTOM_ELEMENT;
8913
+ let IS_ALLOWED_URI$1 = IS_ALLOWED_URI;
8549
8914
  /**
8550
8915
  * We consider the elements and attributes below to be safe. Ideally
8551
8916
  * don't add any new ones but feel free to remove unwanted ones.
@@ -8622,6 +8987,13 @@ function requirePurify_cjs () {
8622
8987
  let WHOLE_DOCUMENT = false;
8623
8988
  /* Track whether config is already set on this instance of DOMPurify. */
8624
8989
  let SET_CONFIG = false;
8990
+ /* Pristine allowlist bindings captured at setConfig() time. On the
8991
+ * persistent-config path sanitize() restores the sets from these before
8992
+ * the per-walk hook clone-guard, so a hook's in-call widening cannot
8993
+ * carry across calls. Null until setConfig() is called; reset by
8994
+ * clearConfig(). */
8995
+ let SET_CONFIG_ALLOWED_TAGS = null;
8996
+ let SET_CONFIG_ALLOWED_ATTR = null;
8625
8997
  /* Decide if all elements (e.g. style, script) must be children of
8626
8998
  * document.body. By default, browsers might move them to document.head */
8627
8999
  let FORCE_BODY = false;
@@ -8664,7 +9036,17 @@ function requirePurify_cjs () {
8664
9036
  let USE_PROFILES = {};
8665
9037
  /* Tags to ignore content of when KEEP_CONTENT is true */
8666
9038
  let FORBID_CONTENTS = null;
8667
- const DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']);
9039
+ const DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script',
9040
+ // <selectedcontent> mirrors the selected <option>'s subtree, cloned by
9041
+ // the UA (customizable <select>) — including any on* handlers — and the
9042
+ // engine re-mirrors synchronously whenever a removal changes which
9043
+ // option/selectedcontent is current, even inside DOMPurify's inert
9044
+ // DOMParser document. Hoisting its children on removal re-inserts a fresh
9045
+ // mirror target ahead of the walk, which the engine refills, looping
9046
+ // forever (DoS) and amplifying output. Dropping its content on removal
9047
+ // (rather than hoisting) breaks that cascade; the content is a duplicate
9048
+ // of the option, which is sanitized on its own. See campaign-3 F1/F6.
9049
+ 'selectedcontent', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']);
8668
9050
  /* Tags that are safe for data: URIs */
8669
9051
  let DATA_URI_TAGS = null;
8670
9052
  const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);
@@ -8680,8 +9062,10 @@ function requirePurify_cjs () {
8680
9062
  /* Allowed XHTML+XML namespaces */
8681
9063
  let ALLOWED_NAMESPACES = null;
8682
9064
  const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);
8683
- let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']);
8684
- let HTML_INTEGRATION_POINTS = addToSet({}, ['annotation-xml']);
9065
+ const DEFAULT_MATHML_TEXT_INTEGRATION_POINTS = freeze(['mi', 'mo', 'mn', 'ms', 'mtext']);
9066
+ let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, DEFAULT_MATHML_TEXT_INTEGRATION_POINTS);
9067
+ const DEFAULT_HTML_INTEGRATION_POINTS = freeze(['annotation-xml']);
9068
+ let HTML_INTEGRATION_POINTS = addToSet({}, DEFAULT_HTML_INTEGRATION_POINTS);
8685
9069
  // Certain elements are allowed in both SVG and HTML
8686
9070
  // namespace. We need to specify them explicitly
8687
9071
  // so that they don't get erroneously deleted from
@@ -8723,15 +9107,33 @@ function requirePurify_cjs () {
8723
9107
  // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.
8724
9108
  transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase;
8725
9109
  /* Set configuration parameters */
8726
- ALLOWED_TAGS = objectHasOwnProperty(cfg, 'ALLOWED_TAGS') ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS;
8727
- ALLOWED_ATTR = objectHasOwnProperty(cfg, 'ALLOWED_ATTR') ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR;
8728
- ALLOWED_NAMESPACES = objectHasOwnProperty(cfg, 'ALLOWED_NAMESPACES') ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES;
8729
- URI_SAFE_ATTRIBUTES = objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR, transformCaseFunc) : DEFAULT_URI_SAFE_ATTRIBUTES;
8730
- DATA_URI_TAGS = objectHasOwnProperty(cfg, 'ADD_DATA_URI_TAGS') ? addToSet(clone(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS, transformCaseFunc) : DEFAULT_DATA_URI_TAGS;
8731
- FORBID_CONTENTS = objectHasOwnProperty(cfg, 'FORBID_CONTENTS') ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS;
8732
- FORBID_TAGS = objectHasOwnProperty(cfg, 'FORBID_TAGS') ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : clone({});
8733
- FORBID_ATTR = objectHasOwnProperty(cfg, 'FORBID_ATTR') ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : clone({});
8734
- USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES : false;
9110
+ ALLOWED_TAGS = _resolveSetOption(cfg, 'ALLOWED_TAGS', DEFAULT_ALLOWED_TAGS, {
9111
+ transform: transformCaseFunc
9112
+ });
9113
+ ALLOWED_ATTR = _resolveSetOption(cfg, 'ALLOWED_ATTR', DEFAULT_ALLOWED_ATTR, {
9114
+ transform: transformCaseFunc
9115
+ });
9116
+ ALLOWED_NAMESPACES = _resolveSetOption(cfg, 'ALLOWED_NAMESPACES', DEFAULT_ALLOWED_NAMESPACES, {
9117
+ transform: stringToString
9118
+ });
9119
+ URI_SAFE_ATTRIBUTES = _resolveSetOption(cfg, 'ADD_URI_SAFE_ATTR', DEFAULT_URI_SAFE_ATTRIBUTES, {
9120
+ transform: transformCaseFunc,
9121
+ base: DEFAULT_URI_SAFE_ATTRIBUTES
9122
+ });
9123
+ DATA_URI_TAGS = _resolveSetOption(cfg, 'ADD_DATA_URI_TAGS', DEFAULT_DATA_URI_TAGS, {
9124
+ transform: transformCaseFunc,
9125
+ base: DEFAULT_DATA_URI_TAGS
9126
+ });
9127
+ FORBID_CONTENTS = _resolveSetOption(cfg, 'FORBID_CONTENTS', DEFAULT_FORBID_CONTENTS, {
9128
+ transform: transformCaseFunc
9129
+ });
9130
+ FORBID_TAGS = _resolveSetOption(cfg, 'FORBID_TAGS', clone({}), {
9131
+ transform: transformCaseFunc
9132
+ });
9133
+ FORBID_ATTR = _resolveSetOption(cfg, 'FORBID_ATTR', clone({}), {
9134
+ transform: transformCaseFunc
9135
+ });
9136
+ USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES && typeof cfg.USE_PROFILES === 'object' ? clone(cfg.USE_PROFILES) : cfg.USE_PROFILES : false;
8735
9137
  ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true
8736
9138
  ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true
8737
9139
  ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false
@@ -8747,20 +9149,22 @@ function requirePurify_cjs () {
8747
9149
  SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false
8748
9150
  KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true
8749
9151
  IN_PLACE = cfg.IN_PLACE || false; // Default false
8750
- IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI;
8751
- NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;
8752
- MATHML_TEXT_INTEGRATION_POINTS = cfg.MATHML_TEXT_INTEGRATION_POINTS || MATHML_TEXT_INTEGRATION_POINTS;
8753
- HTML_INTEGRATION_POINTS = cfg.HTML_INTEGRATION_POINTS || HTML_INTEGRATION_POINTS;
8754
- CUSTOM_ELEMENT_HANDLING = cfg.CUSTOM_ELEMENT_HANDLING || create(null);
8755
- if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) {
8756
- CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck;
9152
+ IS_ALLOWED_URI$1 = isRegex(cfg.ALLOWED_URI_REGEXP) ? cfg.ALLOWED_URI_REGEXP : IS_ALLOWED_URI; // Default regexp
9153
+ NAMESPACE = typeof cfg.NAMESPACE === 'string' ? cfg.NAMESPACE : HTML_NAMESPACE; // Default HTML namespace
9154
+ MATHML_TEXT_INTEGRATION_POINTS = objectHasOwnProperty(cfg, 'MATHML_TEXT_INTEGRATION_POINTS') && cfg.MATHML_TEXT_INTEGRATION_POINTS && typeof cfg.MATHML_TEXT_INTEGRATION_POINTS === 'object' ? clone(cfg.MATHML_TEXT_INTEGRATION_POINTS) : addToSet({}, DEFAULT_MATHML_TEXT_INTEGRATION_POINTS); // Default built-in map
9155
+ HTML_INTEGRATION_POINTS = objectHasOwnProperty(cfg, 'HTML_INTEGRATION_POINTS') && cfg.HTML_INTEGRATION_POINTS && typeof cfg.HTML_INTEGRATION_POINTS === 'object' ? clone(cfg.HTML_INTEGRATION_POINTS) : addToSet({}, DEFAULT_HTML_INTEGRATION_POINTS); // Default built-in map
9156
+ const customElementHandling = objectHasOwnProperty(cfg, 'CUSTOM_ELEMENT_HANDLING') && cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING === 'object' ? clone(cfg.CUSTOM_ELEMENT_HANDLING) : create(null);
9157
+ CUSTOM_ELEMENT_HANDLING = create(null);
9158
+ if (objectHasOwnProperty(customElementHandling, 'tagNameCheck') && isRegexOrFunction(customElementHandling.tagNameCheck)) {
9159
+ CUSTOM_ELEMENT_HANDLING.tagNameCheck = customElementHandling.tagNameCheck; // Default undefined
8757
9160
  }
8758
- if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) {
8759
- CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck;
9161
+ if (objectHasOwnProperty(customElementHandling, 'attributeNameCheck') && isRegexOrFunction(customElementHandling.attributeNameCheck)) {
9162
+ CUSTOM_ELEMENT_HANDLING.attributeNameCheck = customElementHandling.attributeNameCheck; // Default undefined
8760
9163
  }
8761
- if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === 'boolean') {
8762
- CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements;
9164
+ if (objectHasOwnProperty(customElementHandling, 'allowCustomizedBuiltInElements') && typeof customElementHandling.allowCustomizedBuiltInElements === 'boolean') {
9165
+ CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = customElementHandling.allowCustomizedBuiltInElements; // Default undefined
8763
9166
  }
9167
+ seal(CUSTOM_ELEMENT_HANDLING);
8764
9168
  if (SAFE_FOR_TEMPLATES) {
8765
9169
  ALLOW_DATA_ATTR = false;
8766
9170
  }
@@ -8796,36 +9200,36 @@ function requirePurify_cjs () {
8796
9200
  EXTRA_ELEMENT_HANDLING.tagCheck = null;
8797
9201
  EXTRA_ELEMENT_HANDLING.attributeCheck = null;
8798
9202
  /* Merge configuration parameters */
8799
- if (cfg.ADD_TAGS) {
9203
+ if (objectHasOwnProperty(cfg, 'ADD_TAGS')) {
8800
9204
  if (typeof cfg.ADD_TAGS === 'function') {
8801
9205
  EXTRA_ELEMENT_HANDLING.tagCheck = cfg.ADD_TAGS;
8802
- } else {
9206
+ } else if (arrayIsArray(cfg.ADD_TAGS)) {
8803
9207
  if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
8804
9208
  ALLOWED_TAGS = clone(ALLOWED_TAGS);
8805
9209
  }
8806
9210
  addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);
8807
9211
  }
8808
9212
  }
8809
- if (cfg.ADD_ATTR) {
9213
+ if (objectHasOwnProperty(cfg, 'ADD_ATTR')) {
8810
9214
  if (typeof cfg.ADD_ATTR === 'function') {
8811
9215
  EXTRA_ELEMENT_HANDLING.attributeCheck = cfg.ADD_ATTR;
8812
- } else {
9216
+ } else if (arrayIsArray(cfg.ADD_ATTR)) {
8813
9217
  if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
8814
9218
  ALLOWED_ATTR = clone(ALLOWED_ATTR);
8815
9219
  }
8816
9220
  addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);
8817
9221
  }
8818
9222
  }
8819
- if (cfg.ADD_URI_SAFE_ATTR) {
9223
+ if (objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') && arrayIsArray(cfg.ADD_URI_SAFE_ATTR)) {
8820
9224
  addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);
8821
9225
  }
8822
- if (cfg.FORBID_CONTENTS) {
9226
+ if (objectHasOwnProperty(cfg, 'FORBID_CONTENTS') && arrayIsArray(cfg.FORBID_CONTENTS)) {
8823
9227
  if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
8824
9228
  FORBID_CONTENTS = clone(FORBID_CONTENTS);
8825
9229
  }
8826
9230
  addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);
8827
9231
  }
8828
- if (cfg.ADD_FORBID_CONTENTS) {
9232
+ if (objectHasOwnProperty(cfg, 'ADD_FORBID_CONTENTS') && arrayIsArray(cfg.ADD_FORBID_CONTENTS)) {
8829
9233
  if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
8830
9234
  FORBID_CONTENTS = clone(FORBID_CONTENTS);
8831
9235
  }
@@ -8844,6 +9248,13 @@ function requirePurify_cjs () {
8844
9248
  addToSet(ALLOWED_TAGS, ['tbody']);
8845
9249
  delete FORBID_TAGS.tbody;
8846
9250
  }
9251
+ // Re-derive the active Trusted Types policy from this configuration on
9252
+ // every parse. The active policy must never be sticky closure state that
9253
+ // outlives the config that set it: a caller-supplied policy left in place
9254
+ // after `clearConfig()` — or after a later call that supplied none, or
9255
+ // `TRUSTED_TYPES_POLICY: null` — could sign a subsequent "default"
9256
+ // `RETURN_TRUSTED_TYPE` result with a foreign, possibly unsafe policy.
9257
+ // See GHSA-vxr8-fq34-vvx9.
8847
9258
  if (cfg.TRUSTED_TYPES_POLICY) {
8848
9259
  if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') {
8849
9260
  throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');
@@ -8851,18 +9262,45 @@ function requirePurify_cjs () {
8851
9262
  if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') {
8852
9263
  throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');
8853
9264
  }
8854
- // Overwrite existing TrustedTypes policy.
9265
+ // A caller-supplied policy applies to this configuration only.
9266
+ const previousTrustedTypesPolicy = trustedTypesPolicy;
8855
9267
  trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;
8856
- // Sign local variables required by `sanitize`.
8857
- emptyHTML = trustedTypesPolicy.createHTML('');
9268
+ // Sign local variables required by `sanitize`. If the supplied policy's
9269
+ // `createHTML` is circular (i.e. it calls `DOMPurify.sanitize`), this
9270
+ // throws via the re-entrancy guard. Restore the previous policy first so
9271
+ // the instance is not left in a poisoned state. See #1422.
9272
+ try {
9273
+ emptyHTML = _createTrustedHTML('');
9274
+ } catch (error) {
9275
+ trustedTypesPolicy = previousTrustedTypesPolicy;
9276
+ throw error;
9277
+ }
9278
+ } else if (cfg.TRUSTED_TYPES_POLICY === null) {
9279
+ // Explicit opt-out for this call: perform no Trusted Types signing and
9280
+ // create nothing (so a strict `trusted-types` CSP that disallows a
9281
+ // `dompurify` policy can still call `sanitize` from inside its own
9282
+ // policy — see #1422). Resetting to `undefined` rather than a sticky
9283
+ // `null` also drops any previously retained caller policy, so it cannot
9284
+ // resurface on a later call, while still allowing the next config-less
9285
+ // call to restore the internal default policy. See GHSA-vxr8-fq34-vvx9.
9286
+ trustedTypesPolicy = undefined;
9287
+ emptyHTML = '';
8858
9288
  } else {
8859
- // Uninitialized policy, attempt to initialize the internal dompurify policy.
9289
+ // No policy supplied: keep the currently active policy if one is set — a
9290
+ // previously supplied policy is intentionally sticky across config-less
9291
+ // calls — otherwise fall back to the instance's own internal policy,
9292
+ // created at most once. (A policy supplied for a *single* call still
9293
+ // lingers by design; what must not linger is a policy whose configuration
9294
+ // has been torn down via `clearConfig()`, which restores the default.)
8860
9295
  if (trustedTypesPolicy === undefined) {
8861
- trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);
9296
+ trustedTypesPolicy = _getDefaultTrustedTypesPolicy();
8862
9297
  }
8863
- // If creating the internal policy succeeded sign internal variables.
8864
- if (trustedTypesPolicy !== null && typeof emptyHTML === 'string') {
8865
- emptyHTML = trustedTypesPolicy.createHTML('');
9298
+ // Sign internal variables only when a policy is active. A falsy policy
9299
+ // (Trusted Types unsupported, creation failed, or an explicit opt-out)
9300
+ // leaves `emptyHTML` as a plain string, so we never call `.createHTML` on
9301
+ // a non-policy and throw. See #1422.
9302
+ if (trustedTypesPolicy && typeof emptyHTML === 'string') {
9303
+ emptyHTML = _createTrustedHTML('');
8866
9304
  }
8867
9305
  }
8868
9306
  // Prevent further manipulation of configuration.
@@ -8877,6 +9315,77 @@ function requirePurify_cjs () {
8877
9315
  * correctly. */
8878
9316
  const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]);
8879
9317
  const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]);
9318
+ /**
9319
+ * Namespace rules for an element in the SVG namespace.
9320
+ *
9321
+ * @param tagName the element's lowercase tag name
9322
+ * @param parent the (possibly simulated) parent node
9323
+ * @param parentTagName the parent's lowercase tag name
9324
+ * @returns true if a spec-compliant parser could produce this element
9325
+ */
9326
+ const _checkSvgNamespace = function _checkSvgNamespace(tagName, parent, parentTagName) {
9327
+ // The only way to switch from HTML namespace to SVG
9328
+ // is via <svg>. If it happens via any other tag, then
9329
+ // it should be killed.
9330
+ if (parent.namespaceURI === HTML_NAMESPACE) {
9331
+ return tagName === 'svg';
9332
+ }
9333
+ // The only way to switch from MathML to SVG is via <svg>
9334
+ // if the parent is either <annotation-xml> or a MathML
9335
+ // text integration point.
9336
+ if (parent.namespaceURI === MATHML_NAMESPACE) {
9337
+ return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
9338
+ }
9339
+ // We only allow elements that are defined in SVG
9340
+ // spec. All others are disallowed in SVG namespace.
9341
+ return Boolean(ALL_SVG_TAGS[tagName]);
9342
+ };
9343
+ /**
9344
+ * Namespace rules for an element in the MathML namespace.
9345
+ *
9346
+ * @param tagName the element's lowercase tag name
9347
+ * @param parent the (possibly simulated) parent node
9348
+ * @param parentTagName the parent's lowercase tag name
9349
+ * @returns true if a spec-compliant parser could produce this element
9350
+ */
9351
+ const _checkMathMlNamespace = function _checkMathMlNamespace(tagName, parent, parentTagName) {
9352
+ // The only way to switch from HTML namespace to MathML
9353
+ // is via <math>. If it happens via any other tag, then
9354
+ // it should be killed.
9355
+ if (parent.namespaceURI === HTML_NAMESPACE) {
9356
+ return tagName === 'math';
9357
+ }
9358
+ // The only way to switch from SVG to MathML is via
9359
+ // <math> and HTML integration points
9360
+ if (parent.namespaceURI === SVG_NAMESPACE) {
9361
+ return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
9362
+ }
9363
+ // We only allow elements that are defined in MathML
9364
+ // spec. All others are disallowed in MathML namespace.
9365
+ return Boolean(ALL_MATHML_TAGS[tagName]);
9366
+ };
9367
+ /**
9368
+ * Namespace rules for an element in the HTML namespace.
9369
+ *
9370
+ * @param tagName the element's lowercase tag name
9371
+ * @param parent the (possibly simulated) parent node
9372
+ * @param parentTagName the parent's lowercase tag name
9373
+ * @returns true if a spec-compliant parser could produce this element
9374
+ */
9375
+ const _checkHtmlNamespace = function _checkHtmlNamespace(tagName, parent, parentTagName) {
9376
+ // The only way to switch from SVG to HTML is via
9377
+ // HTML integration points, and from MathML to HTML
9378
+ // is via MathML text integration points
9379
+ if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
9380
+ return false;
9381
+ }
9382
+ if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
9383
+ return false;
9384
+ }
9385
+ // We disallow tags that are specific for MathML
9386
+ // or SVG and should never appear in HTML namespace
9387
+ return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
9388
+ };
8880
9389
  /**
8881
9390
  * @param element a DOM element whose namespace is being checked
8882
9391
  * @returns Return false if the element has a
@@ -8899,51 +9408,13 @@ function requirePurify_cjs () {
8899
9408
  return false;
8900
9409
  }
8901
9410
  if (element.namespaceURI === SVG_NAMESPACE) {
8902
- // The only way to switch from HTML namespace to SVG
8903
- // is via <svg>. If it happens via any other tag, then
8904
- // it should be killed.
8905
- if (parent.namespaceURI === HTML_NAMESPACE) {
8906
- return tagName === 'svg';
8907
- }
8908
- // The only way to switch from MathML to SVG is via`
8909
- // svg if parent is either <annotation-xml> or MathML
8910
- // text integration points.
8911
- if (parent.namespaceURI === MATHML_NAMESPACE) {
8912
- return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
8913
- }
8914
- // We only allow elements that are defined in SVG
8915
- // spec. All others are disallowed in SVG namespace.
8916
- return Boolean(ALL_SVG_TAGS[tagName]);
9411
+ return _checkSvgNamespace(tagName, parent, parentTagName);
8917
9412
  }
8918
9413
  if (element.namespaceURI === MATHML_NAMESPACE) {
8919
- // The only way to switch from HTML namespace to MathML
8920
- // is via <math>. If it happens via any other tag, then
8921
- // it should be killed.
8922
- if (parent.namespaceURI === HTML_NAMESPACE) {
8923
- return tagName === 'math';
8924
- }
8925
- // The only way to switch from SVG to MathML is via
8926
- // <math> and HTML integration points
8927
- if (parent.namespaceURI === SVG_NAMESPACE) {
8928
- return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
8929
- }
8930
- // We only allow elements that are defined in MathML
8931
- // spec. All others are disallowed in MathML namespace.
8932
- return Boolean(ALL_MATHML_TAGS[tagName]);
9414
+ return _checkMathMlNamespace(tagName, parent, parentTagName);
8933
9415
  }
8934
9416
  if (element.namespaceURI === HTML_NAMESPACE) {
8935
- // The only way to switch from SVG to HTML is via
8936
- // HTML integration points, and from MathML to HTML
8937
- // is via MathML text integration points
8938
- if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
8939
- return false;
8940
- }
8941
- if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
8942
- return false;
8943
- }
8944
- // We disallow tags that are specific for MathML
8945
- // or SVG and should never appear in HTML namespace
8946
- return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
9417
+ return _checkHtmlNamespace(tagName, parent, parentTagName);
8947
9418
  }
8948
9419
  // For XHTML and XML documents that support custom namespaces
8949
9420
  if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) {
@@ -8968,7 +9439,74 @@ function requirePurify_cjs () {
8968
9439
  // eslint-disable-next-line unicorn/prefer-dom-node-remove
8969
9440
  getParentNode(node).removeChild(node);
8970
9441
  } catch (_) {
9442
+ /* The normal detach failed — this is reached for a parentless node
9443
+ (getParentNode() is null, so .removeChild throws). Element.prototype
9444
+ .remove() is itself a spec no-op on a parentless node, so a recorded
9445
+ "removal" would otherwise hand the caller back an intact,
9446
+ payload-bearing node (e.g. a detached IN_PLACE root the mXSS canary or
9447
+ the style-with-element-child rule decided to kill). Fail closed by
9448
+ throwing — exactly as a clobbered root does at the IN_PLACE entry —
9449
+ rather than trying to "neutralize" the node via its own methods.
9450
+ Neutralizing would mean calling getAttributeNames()/removeAttribute()
9451
+ on the node, both of which a <form> root can clobber via a named child
9452
+ (and _isClobbered does not even probe getAttributeNames), so the
9453
+ neutralize step could itself be silently defeated, leaving the payload
9454
+ intact. A throw touches only the cached, clobber-safe remove() and
9455
+ getParentNode(). Generalizes GHSA-r47g-fvhr-h676 (clobbered-form root)
9456
+ to every root-kill reason. REPORT-3.
9457
+ This lives inside the catch, so it never fires for a normally-removed
9458
+ in-tree node: those have a parent, removeChild() succeeds, and the
9459
+ catch is not entered. Only a kept (parentless) root reaches here. */
8971
9460
  remove(node);
9461
+ if (!getParentNode(node)) {
9462
+ throw typeErrorCreate('a node selected for removal could not be detached from its tree ' + 'and cannot be safely returned; refusing to sanitize in place');
9463
+ }
9464
+ }
9465
+ };
9466
+ /**
9467
+ * _neutralizeRoot
9468
+ *
9469
+ * Fail-closed teardown of an in-place root after the sanitize walk aborts
9470
+ * (campaign-3 F2). An internal throw mid-walk — e.g. a page-registered
9471
+ * custom element's reaction detaches a node so `_forceRemove`'s deliberate
9472
+ * parentless guard throws, or any other re-entrant engine mutation — would
9473
+ * otherwise leave the caller's *live* tree half-sanitized, with everything
9474
+ * after the abort point still carrying its handlers. There is no safe way
9475
+ * to resume the walk (the tree mutated under us), so we strip the root bare:
9476
+ * remove every child and every attribute, then let the caller's catch see
9477
+ * the original error. Clobber-safe (cached `remove`/`childNodes`/`attributes`
9478
+ * getters; the root was already clobber-pre-flighted at the IN_PLACE entry).
9479
+ *
9480
+ * @param root the in-place root to empty
9481
+ */
9482
+ const _neutralizeRoot = function _neutralizeRoot(root) {
9483
+ const childNodes = getChildNodes(root);
9484
+ if (childNodes) {
9485
+ const snapshot = [];
9486
+ arrayForEach(childNodes, child => {
9487
+ arrayPush(snapshot, child);
9488
+ });
9489
+ arrayForEach(snapshot, child => {
9490
+ try {
9491
+ remove(child);
9492
+ } catch (_) {
9493
+ /* Best-effort teardown; a still-attached child is handled below */
9494
+ }
9495
+ });
9496
+ }
9497
+ const attributes = getAttributes(root);
9498
+ if (attributes) {
9499
+ for (let i = attributes.length - 1; i >= 0; --i) {
9500
+ const attribute = attributes[i];
9501
+ const name = attribute && attribute.name;
9502
+ if (typeof name === 'string') {
9503
+ try {
9504
+ root.removeAttribute(name);
9505
+ } catch (_) {
9506
+ /* Clobbered removeAttribute — ignore (fail-closed best effort) */
9507
+ }
9508
+ }
9509
+ }
8972
9510
  }
8973
9511
  };
8974
9512
  /**
@@ -9003,6 +9541,72 @@ function requirePurify_cjs () {
9003
9541
  }
9004
9542
  }
9005
9543
  };
9544
+ /**
9545
+ * _stripDisallowedAttributes
9546
+ *
9547
+ * Removes every attribute the active configuration does not allow from a
9548
+ * single element, using the same allowlist as the main attribute pass (so
9549
+ * `on*` handlers go, but no `/^on/` blocklist is introduced). Used only to
9550
+ * neutralise nodes that are being discarded from an in-place tree.
9551
+ *
9552
+ * @param element the element to strip
9553
+ */
9554
+ const _stripDisallowedAttributes = function _stripDisallowedAttributes(element) {
9555
+ const attributes = getAttributes(element);
9556
+ if (!attributes) {
9557
+ return;
9558
+ }
9559
+ for (let i = attributes.length - 1; i >= 0; --i) {
9560
+ const attribute = attributes[i];
9561
+ const name = attribute && attribute.name;
9562
+ if (typeof name !== 'string' || ALLOWED_ATTR[transformCaseFunc(name)]) {
9563
+ continue;
9564
+ }
9565
+ try {
9566
+ element.removeAttribute(name);
9567
+ } catch (_) {
9568
+ /* Clobbered removeAttribute on a doomed node — ignore */
9569
+ }
9570
+ }
9571
+ };
9572
+ /**
9573
+ * _neutralizeSubtree
9574
+ *
9575
+ * Completes the audit-5 F1 fix across every removal path. The KEEP_CONTENT
9576
+ * move-hoist neutralises only disallowed-tag removals; clobber, mXSS-canary,
9577
+ * namespace, comment, processing-instruction and KEEP_CONTENT:false removals
9578
+ * all drop their subtree wholesale via `_forceRemove`. On the IN_PLACE path
9579
+ * those dropped nodes are detached from the caller's LIVE tree but a
9580
+ * handler-bearing original among them (an `<img onerror>`/`<video>` that was
9581
+ * loading) keeps its queued resource event, which fires in page scope after
9582
+ * sanitize returns. This walks a removed subtree and strips every attribute
9583
+ * the active configuration does not allow — so `on*` handlers are cancelled
9584
+ * through the SAME allowlist that governs kept nodes, not a separate `/^on/`
9585
+ * blocklist. Run synchronously before sanitize returns, i.e. before any
9586
+ * queued event can fire. Hook-free by design: these nodes leave the output,
9587
+ * so firing attribute hooks for them would be surprising. Clobber-safe reads;
9588
+ * a doomed clobbered node may shadow `removeAttribute` (its own attributes are
9589
+ * irrelevant — it is discarded — while its non-clobbered descendants, e.g.
9590
+ * the `<img>`, are reached and scrubbed).
9591
+ *
9592
+ * @param root the root of a removed subtree to neutralise
9593
+ */
9594
+ const _neutralizeSubtree = function _neutralizeSubtree(root) {
9595
+ const stack = [root];
9596
+ while (stack.length > 0) {
9597
+ const node = stack.pop();
9598
+ const nodeType = getNodeType ? getNodeType(node) : node.nodeType;
9599
+ if (nodeType === NODE_TYPE.element) {
9600
+ _stripDisallowedAttributes(node);
9601
+ }
9602
+ const childNodes = getChildNodes(node);
9603
+ if (childNodes) {
9604
+ for (let i = childNodes.length - 1; i >= 0; --i) {
9605
+ stack.push(childNodes[i]);
9606
+ }
9607
+ }
9608
+ }
9609
+ };
9006
9610
  /**
9007
9611
  * _initDocument
9008
9612
  *
@@ -9024,7 +9628,7 @@ function requirePurify_cjs () {
9024
9628
  // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)
9025
9629
  dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + '</body></html>';
9026
9630
  }
9027
- const dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
9631
+ const dirtyPayload = trustedTypesPolicy ? _createTrustedHTML(dirty) : dirty;
9028
9632
  /*
9029
9633
  * Use the DOMParser API by default, fallback later if needs be
9030
9634
  * DOMParser not work for svg when has multiple root element.
@@ -9064,29 +9668,254 @@ function requirePurify_cjs () {
9064
9668
  // eslint-disable-next-line no-bitwise
9065
9669
  NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null);
9066
9670
  };
9671
+ /**
9672
+ * Replace template expression syntax (mustache, ERB, template
9673
+ * literal) with a space; shared by all SAFE_FOR_TEMPLATES scrub
9674
+ * sites. Order matters: mustache, then ERB, then template literal.
9675
+ *
9676
+ * @param value the string to scrub
9677
+ * @returns the scrubbed string
9678
+ */
9679
+ const _stripTemplateExpressions = function _stripTemplateExpressions(value) {
9680
+ value = stringReplace(value, MUSTACHE_EXPR$1, ' ');
9681
+ value = stringReplace(value, ERB_EXPR$1, ' ');
9682
+ value = stringReplace(value, TMPLIT_EXPR$1, ' ');
9683
+ return value;
9684
+ };
9685
+ /**
9686
+ * Strip template-engine expressions ({{...}}, ${...}, <%...%>) from the
9687
+ * character data of an element subtree. Used as the final safety net for
9688
+ * SAFE_FOR_TEMPLATES on every DOM-returning code path so that expressions
9689
+ * which only form after text-node normalization (e.g. fragments split across
9690
+ * stripped elements) cannot survive into a template-evaluating framework.
9691
+ *
9692
+ * Walks text/comment/CDATA/processing-instruction nodes and mutates `.data`
9693
+ * in place rather than round-tripping through innerHTML. This preserves
9694
+ * descendant node references (important for IN_PLACE callers), avoids a
9695
+ * serialize/reparse cycle, and reads literal character data — which means
9696
+ * `<%...%>` in text content matches the ERB regex against its real bytes
9697
+ * instead of the HTML-entity-escaped form innerHTML would produce.
9698
+ *
9699
+ * Attribute values are not visited here; SAFE_FOR_TEMPLATES handling for
9700
+ * attributes is performed during the per-node `_sanitizeAttributes` pass.
9701
+ *
9702
+ * @param node The root element whose character data should be scrubbed.
9703
+ */
9704
+ const _scrubTemplateExpressions2 = function _scrubTemplateExpressions(node) {
9705
+ var _node$querySelectorAl;
9706
+ node.normalize();
9707
+ const walker = createNodeIterator.call(node.ownerDocument || node, node,
9708
+ // eslint-disable-next-line no-bitwise
9709
+ NodeFilter.SHOW_TEXT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_CDATA_SECTION | NodeFilter.SHOW_PROCESSING_INSTRUCTION, null);
9710
+ let currentNode = walker.nextNode();
9711
+ while (currentNode) {
9712
+ currentNode.data = _stripTemplateExpressions(currentNode.data);
9713
+ currentNode = walker.nextNode();
9714
+ }
9715
+ // NodeIterator does not descend into <template>.content per the DOM spec,
9716
+ // so we must explicitly recurse into each template's content fragment,
9717
+ // mirroring the approach used by _sanitizeShadowDOM.
9718
+ const templates = (_node$querySelectorAl = node.querySelectorAll) === null || _node$querySelectorAl === void 0 ? void 0 : _node$querySelectorAl.call(node, 'template');
9719
+ if (templates) {
9720
+ arrayForEach(templates, tmpl => {
9721
+ if (_isDocumentFragment(tmpl.content)) {
9722
+ _scrubTemplateExpressions2(tmpl.content);
9723
+ }
9724
+ });
9725
+ }
9726
+ };
9067
9727
  /**
9068
9728
  * _isClobbered
9069
9729
  *
9730
+ * Detect DOM-clobbering on HTMLFormElement nodes. Form is the only HTML
9731
+ * interface with [LegacyOverrideBuiltIns]; a descendant element with a
9732
+ * `name` attribute matching a prototype property shadows that property
9733
+ * on direct reads. We use this check at the IN_PLACE entry-point and
9734
+ * during attribute sanitization to refuse clobbered forms.
9735
+ *
9070
9736
  * @param element element to check for clobbering attacks
9071
9737
  * @return true if clobbered, false if safe
9072
9738
  */
9073
9739
  const _isClobbered = function _isClobbered(element) {
9074
- return element instanceof HTMLFormElement && (typeof element.nodeName !== 'string' || typeof element.textContent !== 'string' || typeof element.removeChild !== 'function' || !(element.attributes instanceof NamedNodeMap) || typeof element.removeAttribute !== 'function' || typeof element.setAttribute !== 'function' || typeof element.namespaceURI !== 'string' || typeof element.insertBefore !== 'function' || typeof element.hasChildNodes !== 'function');
9740
+ // Realm-independent tag-name probe. If we can't determine the tag
9741
+ // name at all, we can't reason about clobbering — return false
9742
+ // (the caller's other defences still apply).
9743
+ const realTagName = getNodeName ? getNodeName(element) : null;
9744
+ if (typeof realTagName !== 'string') {
9745
+ return false;
9746
+ }
9747
+ if (transformCaseFunc(realTagName) !== 'form') {
9748
+ return false;
9749
+ }
9750
+ return typeof element.nodeName !== 'string' || typeof element.textContent !== 'string' || typeof element.removeChild !== 'function' ||
9751
+ // Realm-safe NamedNodeMap detection: equality against the cached
9752
+ // prototype getter. Clobbered .attributes (e.g. <input name="attributes">)
9753
+ // makes the direct read diverge from the cached read; a clean form
9754
+ // (same-realm OR foreign-realm) has both reads pointing at the same
9755
+ // canonical NamedNodeMap.
9756
+ element.attributes !== getAttributes(element) || typeof element.removeAttribute !== 'function' || typeof element.setAttribute !== 'function' || typeof element.namespaceURI !== 'string' || typeof element.insertBefore !== 'function' || typeof element.hasChildNodes !== 'function' ||
9757
+ // NodeType clobbering probe. Cached Node.prototype.nodeType getter
9758
+ // returns the integer 1 for any Element regardless of realm; direct
9759
+ // read on a clobbered form (e.g. <input name="nodeType">) returns
9760
+ // the named child element. Cheap addition — nodeType is read from
9761
+ // an internal slot, no serialization cost — and removes a residual
9762
+ // clobbering surface used by several mXSS / PI / comment branches
9763
+ // in _sanitizeElements that compare currentNode.nodeType directly.
9764
+ element.nodeType !== getNodeType(element) ||
9765
+ // HTMLFormElement has [LegacyOverrideBuiltIns]: a descendant named
9766
+ // "childNodes" shadows the prototype getter. Direct reads of
9767
+ // form.childNodes from a clobbered form return the named child
9768
+ // instead of the real NodeList, so any walk that reads it directly
9769
+ // skips the form's real children. Compare the direct read to the
9770
+ // cached Node.prototype getter — when the form's named-property
9771
+ // getter intercepts the read, the two values differ and we flag
9772
+ // the form. This catches every clobbering child type (input,
9773
+ // select, etc.) regardless of whether the named child happens to
9774
+ // carry a numeric .length, which a typeof-based probe would miss
9775
+ // (e.g. HTMLSelectElement.length is a defined unsigned-long).
9776
+ element.childNodes !== getChildNodes(element);
9075
9777
  };
9076
9778
  /**
9077
- * Checks whether the given object is a DOM node.
9779
+ * Checks whether the given value is a DocumentFragment from any realm.
9780
+ *
9781
+ * The realm-independent replacement reads `nodeType` through the cached
9782
+ * Node.prototype getter and compares to the DOCUMENT_FRAGMENT_NODE
9783
+ * constant (11). nodeType is a numeric value resolved from the node's
9784
+ * internal slot, identical across realms for the same kind of node.
9785
+ *
9786
+ * @param value object to check
9787
+ * @return true if value is a DocumentFragment-shaped node from any realm
9788
+ */
9789
+ const _isDocumentFragment = function _isDocumentFragment(value) {
9790
+ if (!getNodeType || typeof value !== 'object' || value === null) {
9791
+ return false;
9792
+ }
9793
+ try {
9794
+ return getNodeType(value) === NODE_TYPE.documentFragment;
9795
+ } catch (_) {
9796
+ return false;
9797
+ }
9798
+ };
9799
+ /**
9800
+ * Checks whether the given object is a DOM node, including nodes that
9801
+ * originate from a different window/realm (e.g. an iframe's
9802
+ * contentDocument). The previous `value instanceof Node` check was
9803
+ * realm-bound: nodes from a different window failed it, causing
9804
+ * sanitize() to silently stringify them and reset IN_PLACE to false,
9805
+ * returning the original node unsanitized. See GHSA-4w3q-35jp-p934.
9078
9806
  *
9079
9807
  * @param value object to check whether it's a DOM node
9080
- * @return true is object is a DOM node
9808
+ * @return true if value is a DOM node from any realm
9081
9809
  */
9082
9810
  const _isNode = function _isNode(value) {
9083
- return typeof Node === 'function' && value instanceof Node;
9811
+ if (!getNodeType || typeof value !== 'object' || value === null) {
9812
+ return false;
9813
+ }
9814
+ try {
9815
+ return typeof getNodeType(value) === 'number';
9816
+ } catch (_) {
9817
+ return false;
9818
+ }
9084
9819
  };
9085
9820
  function _executeHooks(hooks, currentNode, data) {
9821
+ if (hooks.length === 0) {
9822
+ return;
9823
+ }
9086
9824
  arrayForEach(hooks, hook => {
9087
9825
  hook.call(DOMPurify, currentNode, data, CONFIG);
9088
9826
  });
9089
9827
  }
9828
+ /**
9829
+ * Structural-threat checks that condemn a node regardless of the
9830
+ * allowlists: mXSS via namespace confusion, risky CSS construction,
9831
+ * processing instructions, markup-bearing comments. Pure predicate;
9832
+ * the caller removes. Check order is load-bearing.
9833
+ *
9834
+ * @param currentNode the node to inspect
9835
+ * @param tagName the node's transformCaseFunc'd tag name
9836
+ * @return true if the node must be removed
9837
+ */
9838
+ const _isUnsafeNode = function _isUnsafeNode(currentNode, tagName) {
9839
+ /* Detect mXSS attempts abusing namespace confusion */
9840
+ if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.textContent) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.innerHTML)) {
9841
+ return true;
9842
+ }
9843
+ /* Remove risky CSS construction leading to mXSS */
9844
+ if (SAFE_FOR_XML && currentNode.namespaceURI === HTML_NAMESPACE && tagName === 'style' && _isNode(currentNode.firstElementChild)) {
9845
+ return true;
9846
+ }
9847
+ /* Remove any occurrence of processing instructions */
9848
+ if (currentNode.nodeType === NODE_TYPE.processingInstruction) {
9849
+ return true;
9850
+ }
9851
+ /* Remove any kind of possibly harmful comments */
9852
+ if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(COMMENT_MARKUP_PROBE, currentNode.data)) {
9853
+ return true;
9854
+ }
9855
+ return false;
9856
+ };
9857
+ /**
9858
+ * Handle a node whose tag is forbidden or not allowlisted: keep
9859
+ * allowed custom elements (false return exits _sanitizeElements
9860
+ * early - namespace/fallback checks and the afterSanitizeElements
9861
+ * hook are intentionally skipped for kept custom elements), else
9862
+ * hoist content per KEEP_CONTENT and remove.
9863
+ *
9864
+ * @param currentNode the disallowed node
9865
+ * @param tagName the node's transformCaseFunc'd tag name
9866
+ * @return true if the node was removed, false if kept
9867
+ */
9868
+ const _sanitizeDisallowedNode = function _sanitizeDisallowedNode(currentNode, tagName) {
9869
+ /* Check if we have a custom element to handle */
9870
+ if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {
9871
+ if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {
9872
+ return false;
9873
+ }
9874
+ if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) {
9875
+ return false;
9876
+ }
9877
+ }
9878
+ /* Keep content except for bad-listed elements.
9879
+ Use the cached prototype getters exclusively — the previous code
9880
+ had `|| currentNode.parentNode` / `|| currentNode.childNodes`
9881
+ fallbacks, but the cached getters always return the canonical
9882
+ value (or null for a real parent-less node), so the fallback
9883
+ path was dead in safe cases and a clobbering surface in unsafe
9884
+ ones. Falsy cached results stay falsy; the `if (childNodes &&
9885
+ parentNode)` check already gates correctly. */
9886
+ if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
9887
+ const parentNode = getParentNode(currentNode);
9888
+ const childNodes = getChildNodes(currentNode);
9889
+ if (childNodes && parentNode) {
9890
+ const childCount = childNodes.length;
9891
+ /* In-place: hoist the *original* children so the iterator visits
9892
+ and sanitises them through the same allowlist pass as every other
9893
+ node. The caller built the tree in the live document, so the
9894
+ originals carry already-queued resource events (`<img onerror>`,
9895
+ `<video>`/`<audio>` error, lazy/`onload`, …); cloning would leave
9896
+ those originals detached but still armed, firing in page scope
9897
+ while the returned tree looked clean. Moving is safe in-place: the
9898
+ root is pre-validated as an allowed tag and so is never the node
9899
+ being removed, which keeps `parentNode` inside the iterator root
9900
+ and the relocated child inside the serialised tree.
9901
+ Otherwise (string / DOM-copy paths): clone. The iterator is rooted
9902
+ at — and the result serialised from — `body`, so a restrictive
9903
+ ALLOWED_TAGS that removes `body` itself must leave its content in
9904
+ place, which only cloning does; and those paths parse into an
9905
+ inert document, so their discarded originals never had a queued
9906
+ event to neutralise.
9907
+ `childNodes` is live; a tail-to-head walk keeps `childNodes[i]`
9908
+ valid whether we move (drops the trailing entry) or clone (leaves
9909
+ the list intact). */
9910
+ for (let i = childCount - 1; i >= 0; --i) {
9911
+ const hoisted = IN_PLACE ? childNodes[i] : cloneNode(childNodes[i], true);
9912
+ parentNode.insertBefore(hoisted, getNextSibling(currentNode));
9913
+ }
9914
+ }
9915
+ }
9916
+ _forceRemove(currentNode);
9917
+ return true;
9918
+ };
9090
9919
  /**
9091
9920
  * _sanitizeElements
9092
9921
  *
@@ -9097,7 +9926,6 @@ function requirePurify_cjs () {
9097
9926
  * @return true if node was killed, false if left alive
9098
9927
  */
9099
9928
  const _sanitizeElements = function _sanitizeElements(currentNode) {
9100
- let content = null;
9101
9929
  /* Execute a hook if present */
9102
9930
  _executeHooks(hooks.beforeSanitizeElements, currentNode, null);
9103
9931
  /* Check if element is clobbered or can clobber */
@@ -9106,76 +9934,41 @@ function requirePurify_cjs () {
9106
9934
  return true;
9107
9935
  }
9108
9936
  /* Now let's check the element's type and name */
9109
- const tagName = transformCaseFunc(currentNode.nodeName);
9937
+ const tagName = transformCaseFunc(getNodeName ? getNodeName(currentNode) : currentNode.nodeName);
9110
9938
  /* Execute a hook if present */
9111
9939
  _executeHooks(hooks.uponSanitizeElement, currentNode, {
9112
9940
  tagName,
9113
9941
  allowedTags: ALLOWED_TAGS
9114
9942
  });
9115
- /* Detect mXSS attempts abusing namespace confusion */
9116
- if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(/<[/\w!]/g, currentNode.innerHTML) && regExpTest(/<[/\w!]/g, currentNode.textContent)) {
9117
- _forceRemove(currentNode);
9118
- return true;
9119
- }
9120
- /* Remove risky CSS construction leading to mXSS */
9121
- if (SAFE_FOR_XML && currentNode.namespaceURI === HTML_NAMESPACE && tagName === 'style' && _isNode(currentNode.firstElementChild)) {
9122
- _forceRemove(currentNode);
9123
- return true;
9124
- }
9125
- /* Remove any occurrence of processing instructions */
9126
- if (currentNode.nodeType === NODE_TYPE.progressingInstruction) {
9127
- _forceRemove(currentNode);
9128
- return true;
9129
- }
9130
- /* Remove any kind of possibly harmful comments */
9131
- if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(/<[/\w]/g, currentNode.data)) {
9943
+ /* Remove mXSS vectors, processing instructions and risky comments */
9944
+ if (_isUnsafeNode(currentNode, tagName)) {
9132
9945
  _forceRemove(currentNode);
9133
9946
  return true;
9134
9947
  }
9135
9948
  /* Remove element if anything forbids its presence */
9136
9949
  if (FORBID_TAGS[tagName] || !(EXTRA_ELEMENT_HANDLING.tagCheck instanceof Function && EXTRA_ELEMENT_HANDLING.tagCheck(tagName)) && !ALLOWED_TAGS[tagName]) {
9137
- /* Check if we have a custom element to handle */
9138
- if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {
9139
- if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {
9140
- return false;
9141
- }
9142
- if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) {
9143
- return false;
9144
- }
9145
- }
9146
- /* Keep content except for bad-listed elements */
9147
- if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
9148
- const parentNode = getParentNode(currentNode) || currentNode.parentNode;
9149
- const childNodes = getChildNodes(currentNode) || currentNode.childNodes;
9150
- if (childNodes && parentNode) {
9151
- const childCount = childNodes.length;
9152
- for (let i = childCount - 1; i >= 0; --i) {
9153
- const childClone = cloneNode(childNodes[i], true);
9154
- childClone.__removalCount = (currentNode.__removalCount || 0) + 1;
9155
- parentNode.insertBefore(childClone, getNextSibling(currentNode));
9156
- }
9157
- }
9158
- }
9159
- _forceRemove(currentNode);
9160
- return true;
9950
+ return _sanitizeDisallowedNode(currentNode, tagName);
9161
9951
  }
9162
- /* Check whether element has a valid namespace */
9163
- if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {
9952
+ /* Check whether element has a valid namespace.
9953
+ Realm-safe check (GHSA-hpcv-96wg-7vj8): use the cached Node.prototype
9954
+ nodeType getter rather than `instanceof Element`, which is realm-
9955
+ bound and short-circuits to false for any node minted in a different
9956
+ realm — letting a foreign-realm element with a forbidden namespace
9957
+ slip past the namespace check entirely. */
9958
+ const nt = getNodeType ? getNodeType(currentNode) : currentNode.nodeType;
9959
+ if (nt === NODE_TYPE.element && !_checkValidNamespace(currentNode)) {
9164
9960
  _forceRemove(currentNode);
9165
9961
  return true;
9166
9962
  }
9167
9963
  /* Make sure that older browsers don't get fallback-tag mXSS */
9168
- if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(/<\/no(script|embed|frames)/i, currentNode.innerHTML)) {
9964
+ if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(FALLBACK_TAG_CLOSE, currentNode.innerHTML)) {
9169
9965
  _forceRemove(currentNode);
9170
9966
  return true;
9171
9967
  }
9172
9968
  /* Sanitize element content to be template-safe */
9173
9969
  if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) {
9174
9970
  /* Get the element's text content */
9175
- content = currentNode.textContent;
9176
- arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
9177
- content = stringReplace(content, expr, ' ');
9178
- });
9971
+ const content = _stripTemplateExpressions(currentNode.textContent);
9179
9972
  if (currentNode.textContent !== content) {
9180
9973
  arrayPush(DOMPurify.removed, {
9181
9974
  element: currentNode.cloneNode()
@@ -9205,11 +9998,12 @@ function requirePurify_cjs () {
9205
9998
  if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {
9206
9999
  return false;
9207
10000
  }
10001
+ const nameIsPermitted = ALLOWED_ATTR[lcName] || EXTRA_ELEMENT_HANDLING.attributeCheck instanceof Function && EXTRA_ELEMENT_HANDLING.attributeCheck(lcName, lcTag);
9208
10002
  /* Allow valid data-* attributes: At least one character after "-"
9209
10003
  (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
9210
10004
  XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)
9211
10005
  We don't need to check the value; it's always URI safe. */
9212
- if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR, lcName)) ; else if (EXTRA_ELEMENT_HANDLING.attributeCheck instanceof Function && EXTRA_ELEMENT_HANDLING.attributeCheck(lcName, lcTag)) ; else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) {
10006
+ if (ALLOW_DATA_ATTR && regExpTest(DATA_ATTR$1, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR$1, lcName)) ; else if (!nameIsPermitted) {
9213
10007
  if (
9214
10008
  // First condition does a very basic check if a) it's basically a valid custom element tagname AND
9215
10009
  // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
@@ -9221,11 +10015,15 @@ function requirePurify_cjs () {
9221
10015
  return false;
9222
10016
  }
9223
10017
  /* Check value is safe. First, is attr inert? If so, is safe */
9224
- } else if (URI_SAFE_ATTRIBUTES[lcName]) ; else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE, ''))) ; else if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]) ; else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA, stringReplace(value, ATTR_WHITESPACE, ''))) ; else if (value) {
10018
+ } else if (URI_SAFE_ATTRIBUTES[lcName]) ; else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE$1, ''))) ; else if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]) ; else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA$1, stringReplace(value, ATTR_WHITESPACE$1, ''))) ; else if (value) {
9225
10019
  return false;
9226
10020
  } else ;
9227
10021
  return true;
9228
10022
  };
10023
+ /* Names the HTML spec reserves from valid-custom-element-name; these must
10024
+ * never be treated as basic custom elements even when a permissive
10025
+ * CUSTOM_ELEMENT_HANDLING.tagNameCheck is configured. */
10026
+ const RESERVED_CUSTOM_ELEMENT_NAMES = addToSet({}, ['annotation-xml', 'color-profile', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'missing-glyph']);
9229
10027
  /**
9230
10028
  * _isBasicCustomElement
9231
10029
  * checks if at least one dash is included in tagName, and it's not the first char
@@ -9235,7 +10033,64 @@ function requirePurify_cjs () {
9235
10033
  * @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false.
9236
10034
  */
9237
10035
  const _isBasicCustomElement = function _isBasicCustomElement(tagName) {
9238
- return tagName !== 'annotation-xml' && stringMatch(tagName, CUSTOM_ELEMENT);
10036
+ return !RESERVED_CUSTOM_ELEMENT_NAMES[stringToLowerCase(tagName)] && regExpTest(CUSTOM_ELEMENT$1, tagName);
10037
+ };
10038
+ /**
10039
+ * Wrap an attribute value in the matching Trusted Types object when
10040
+ * the active policy requires it. Namespaced attributes pass through
10041
+ * unchanged (no TT support yet, see
10042
+ * https://bugs.chromium.org/p/chromium/issues/detail?id=1305293).
10043
+ *
10044
+ * @param lcTag lowercase tag name of the containing element
10045
+ * @param lcName lowercase attribute name
10046
+ * @param namespaceURI the attribute's namespace, if any
10047
+ * @param value the attribute value to wrap
10048
+ * @return the value, wrapped when Trusted Types demand it
10049
+ */
10050
+ const _applyTrustedTypesToAttribute = function _applyTrustedTypesToAttribute(lcTag, lcName, namespaceURI, value) {
10051
+ if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function' && !namespaceURI) {
10052
+ switch (trustedTypes.getAttributeType(lcTag, lcName)) {
10053
+ case 'TrustedHTML':
10054
+ {
10055
+ return _createTrustedHTML(value);
10056
+ }
10057
+ case 'TrustedScriptURL':
10058
+ {
10059
+ return _createTrustedScriptURL(value);
10060
+ }
10061
+ }
10062
+ }
10063
+ return value;
10064
+ };
10065
+ /**
10066
+ * Write a modified attribute value back onto the element. On
10067
+ * success, re-probe for clobbering introduced by the new value and
10068
+ * remove the element when found; otherwise pop the removal entry
10069
+ * recorded by the earlier _removeAttribute (long-standing pairing
10070
+ * with the SANITIZE_NAMED_PROPS path - do not "fix" casually). On
10071
+ * failure, remove the attribute instead.
10072
+ *
10073
+ * @param currentNode the element carrying the attribute
10074
+ * @param name the attribute name as present on the element
10075
+ * @param namespaceURI the attribute's namespace, if any
10076
+ * @param value the new attribute value
10077
+ */
10078
+ const _setAttributeValue = function _setAttributeValue(currentNode, name, namespaceURI, value) {
10079
+ try {
10080
+ if (namespaceURI) {
10081
+ currentNode.setAttributeNS(namespaceURI, name, value);
10082
+ } else {
10083
+ /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
10084
+ currentNode.setAttribute(name, value);
10085
+ }
10086
+ if (_isClobbered(currentNode)) {
10087
+ _forceRemove(currentNode);
10088
+ } else {
10089
+ arrayPop(DOMPurify.removed);
10090
+ }
10091
+ } catch (_) {
10092
+ _removeAttribute(name, currentNode);
10093
+ }
9239
10094
  };
9240
10095
  /**
9241
10096
  * _sanitizeAttributes
@@ -9250,9 +10105,7 @@ function requirePurify_cjs () {
9250
10105
  const _sanitizeAttributes = function _sanitizeAttributes(currentNode) {
9251
10106
  /* Execute a hook if present */
9252
10107
  _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null);
9253
- const {
9254
- attributes
9255
- } = currentNode;
10108
+ const attributes = currentNode.attributes;
9256
10109
  /* Check if we have attributes; if not we might have a text node */
9257
10110
  if (!attributes || _isClobbered(currentNode)) {
9258
10111
  return;
@@ -9265,14 +10118,13 @@ function requirePurify_cjs () {
9265
10118
  forceKeepAttr: undefined
9266
10119
  };
9267
10120
  let l = attributes.length;
10121
+ const lcTag = transformCaseFunc(currentNode.nodeName);
9268
10122
  /* Go backwards over all attributes; safely remove bad ones */
9269
10123
  while (l--) {
9270
10124
  const attr = attributes[l];
9271
- const {
9272
- name,
9273
- namespaceURI,
9274
- value: attrValue
9275
- } = attr;
10125
+ const name = attr.name,
10126
+ namespaceURI = attr.namespaceURI,
10127
+ attrValue = attr.value;
9276
10128
  const lcName = transformCaseFunc(name);
9277
10129
  const initValue = attrValue;
9278
10130
  let value = name === 'value' ? initValue : stringTrim(initValue);
@@ -9286,12 +10138,14 @@ function requirePurify_cjs () {
9286
10138
  /* Full DOM Clobbering protection via namespace isolation,
9287
10139
  * Prefix id and name attributes with `user-content-`
9288
10140
  */
9289
- if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name')) {
10141
+ if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name') && stringIndexOf(value, SANITIZE_NAMED_PROPS_PREFIX) !== 0) {
9290
10142
  // Remove the attribute with this value
9291
10143
  _removeAttribute(name, currentNode);
9292
10144
  // Prefix the value and later re-create the attribute with the sanitized value
9293
10145
  value = SANITIZE_NAMED_PROPS_PREFIX + value;
9294
10146
  }
10147
+ // Else: already prefixed, leave the attribute alone — the prefix is
10148
+ // itself the clobbering protection, and re-applying it is incorrect.
9295
10149
  /* Work around a security issue with comments inside attributes */
9296
10150
  if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i, value)) {
9297
10151
  _removeAttribute(name, currentNode);
@@ -9302,7 +10156,7 @@ function requirePurify_cjs () {
9302
10156
  _removeAttribute(name, currentNode);
9303
10157
  continue;
9304
10158
  }
9305
- /* Did the hooks approve of the attribute? */
10159
+ /* Did the hooks force-keep the attribute? */
9306
10160
  if (hookEvent.forceKeepAttr) {
9307
10161
  continue;
9308
10162
  }
@@ -9312,56 +10166,24 @@ function requirePurify_cjs () {
9312
10166
  continue;
9313
10167
  }
9314
10168
  /* Work around a security issue in jQuery 3.0 */
9315
- if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) {
10169
+ if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(SELF_CLOSING_TAG, value)) {
9316
10170
  _removeAttribute(name, currentNode);
9317
10171
  continue;
9318
10172
  }
9319
10173
  /* Sanitize attribute content to be template-safe */
9320
10174
  if (SAFE_FOR_TEMPLATES) {
9321
- arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
9322
- value = stringReplace(value, expr, ' ');
9323
- });
10175
+ value = _stripTemplateExpressions(value);
9324
10176
  }
9325
10177
  /* Is `value` valid for this attribute? */
9326
- const lcTag = transformCaseFunc(currentNode.nodeName);
9327
10178
  if (!_isValidAttribute(lcTag, lcName, value)) {
9328
10179
  _removeAttribute(name, currentNode);
9329
10180
  continue;
9330
10181
  }
9331
10182
  /* Handle attributes that require Trusted Types */
9332
- if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function') {
9333
- if (namespaceURI) ; else {
9334
- switch (trustedTypes.getAttributeType(lcTag, lcName)) {
9335
- case 'TrustedHTML':
9336
- {
9337
- value = trustedTypesPolicy.createHTML(value);
9338
- break;
9339
- }
9340
- case 'TrustedScriptURL':
9341
- {
9342
- value = trustedTypesPolicy.createScriptURL(value);
9343
- break;
9344
- }
9345
- }
9346
- }
9347
- }
10183
+ value = _applyTrustedTypesToAttribute(lcTag, lcName, namespaceURI, value);
9348
10184
  /* Handle invalid data-* attribute set by try-catching it */
9349
10185
  if (value !== initValue) {
9350
- try {
9351
- if (namespaceURI) {
9352
- currentNode.setAttributeNS(namespaceURI, name, value);
9353
- } else {
9354
- /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
9355
- currentNode.setAttribute(name, value);
9356
- }
9357
- if (_isClobbered(currentNode)) {
9358
- _forceRemove(currentNode);
9359
- } else {
9360
- arrayPop(DOMPurify.removed);
9361
- }
9362
- } catch (_) {
9363
- _removeAttribute(name, currentNode);
9364
- }
10186
+ _setAttributeValue(currentNode, name, namespaceURI, value);
9365
10187
  }
9366
10188
  }
9367
10189
  /* Execute a hook if present */
@@ -9384,14 +10206,133 @@ function requirePurify_cjs () {
9384
10206
  _sanitizeElements(shadowNode);
9385
10207
  /* Check attributes next */
9386
10208
  _sanitizeAttributes(shadowNode);
9387
- /* Deep shadow DOM detected */
9388
- if (shadowNode.content instanceof DocumentFragment) {
10209
+ /* Deep shadow DOM detected.
10210
+ Realm-safe check (GHSA-hpcv-96wg-7vj8): use nodeType against the
10211
+ DOCUMENT_FRAGMENT_NODE constant rather than instanceof, so we
10212
+ recurse into <template>.content from foreign realms too. */
10213
+ if (_isDocumentFragment(shadowNode.content)) {
9389
10214
  _sanitizeShadowDOM2(shadowNode.content);
9390
10215
  }
10216
+ /* An element iterated here may itself host an attached
10217
+ shadow root. The default NodeIterator does not enter shadow
10218
+ trees, so a shadow root nested inside template.content was
10219
+ previously reached by no walk at all (the pre-pass at
10220
+ _sanitizeAttachedShadowRoots descends via childNodes, which
10221
+ doesn't enter template.content; the template-content recursion
10222
+ above iterates the content but never inspected shadowRoot).
10223
+ Walk it explicitly. The nodeType guard avoids reading
10224
+ shadowRoot off text / comment / CDATA / PI nodes that the
10225
+ iterator also surfaces. */
10226
+ const shadowNodeType = getNodeType ? getNodeType(shadowNode) : shadowNode.nodeType;
10227
+ if (shadowNodeType === NODE_TYPE.element) {
10228
+ const innerSr = getShadowRoot(shadowNode);
10229
+ if (_isDocumentFragment(innerSr)) {
10230
+ _sanitizeAttachedShadowRoots(innerSr);
10231
+ _sanitizeShadowDOM2(innerSr);
10232
+ }
10233
+ }
9391
10234
  }
9392
10235
  /* Execute a hook if present */
9393
10236
  _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null);
9394
10237
  };
10238
+ /**
10239
+ * _sanitizeAttachedShadowRoots
10240
+ *
10241
+ * Walks `root` and feeds every attached shadow root we encounter into
10242
+ * the existing _sanitizeShadowDOM pipeline. The default node iterator
10243
+ * does not descend into shadow trees, so nodes inside an attached
10244
+ * shadow root would otherwise be skipped entirely.
10245
+ *
10246
+ * Two real input paths put attached shadow roots in front of us:
10247
+ * 1. IN_PLACE on a DOM node that already has shadow roots attached.
10248
+ * 2. DOM-node input where importNode(dirty, true) deep-clones the
10249
+ * shadow root because it was created with `clonable: true`.
10250
+ *
10251
+ * This pass runs once, up front, so the main iteration loop (and the
10252
+ * existing _sanitizeShadowDOM template-content recursion) stay
10253
+ * untouched — string-input paths are not affected.
10254
+ *
10255
+ * @param root the subtree root to walk for attached shadow roots
10256
+ */
10257
+ const _sanitizeAttachedShadowRoots = function _sanitizeAttachedShadowRoots(root) {
10258
+ /* Iterative (explicit stack) rather than per-child recursion. DOM APIs
10259
+ impose no depth cap, so an attacker-shaped tree (JSON/CRDT/editor data
10260
+ built straight into the DOM — the IN_PLACE surface) deeper than the JS
10261
+ call-stack budget would otherwise overflow native recursion here and
10262
+ throw at the IN_PLACE entry pre-pass, before a single node is
10263
+ sanitized, leaving the caller's live tree untouched (fail-open). See
10264
+ campaign-3 F4. A heap stack keeps depth off the call stack.
10265
+ Each work item is either a node to descend into, or a deferred
10266
+ `_sanitizeShadowDOM` for an already-walked shadow root. The deferred
10267
+ form preserves the original post-order discipline: a shadow root's
10268
+ nested shadow roots are discovered before the outer shadow is
10269
+ sanitized (which may remove hosts). Pushes are in reverse of the
10270
+ desired processing order (LIFO): template content, then children, then
10271
+ the shadow-sanitize, then the shadow walk — so the order matches the
10272
+ previous recursion exactly. */
10273
+ const stack = [{
10274
+ node: root,
10275
+ shadow: null
10276
+ }];
10277
+ while (stack.length > 0) {
10278
+ const item = stack.pop();
10279
+ /* Deferred shadow-DOM sanitisation: runs after its subtree was walked. */
10280
+ if (item.shadow) {
10281
+ _sanitizeShadowDOM2(item.shadow);
10282
+ continue;
10283
+ }
10284
+ const node = item.node;
10285
+ const nodeType = getNodeType ? getNodeType(node) : node.nodeType;
10286
+ const isElement = nodeType === NODE_TYPE.element;
10287
+ /* (pushed last → processed first) Children, snapshotted in reverse so
10288
+ the first child is processed first. Snapshotting matters because a
10289
+ hook may detach siblings mid-walk. */
10290
+ const childNodes = getChildNodes(node);
10291
+ if (childNodes) {
10292
+ for (let i = childNodes.length - 1; i >= 0; --i) {
10293
+ stack.push({
10294
+ node: childNodes[i],
10295
+ shadow: null
10296
+ });
10297
+ }
10298
+ }
10299
+ /* (pushed before children → processed after them, matching the old
10300
+ "template content last" order) When the node is a <template>,
10301
+ descend into its content. */
10302
+ if (isElement) {
10303
+ const rootName = getNodeName ? getNodeName(node) : null;
10304
+ if (typeof rootName === 'string' && transformCaseFunc(rootName) === 'template') {
10305
+ const content = node.content;
10306
+ if (_isDocumentFragment(content)) {
10307
+ stack.push({
10308
+ node: content,
10309
+ shadow: null
10310
+ });
10311
+ }
10312
+ }
10313
+ }
10314
+ /* Shadow root (processed first): walk its subtree, then sanitise it.
10315
+ Realm-safe check (GHSA-hpcv-96wg-7vj8): nodeType-based detection
10316
+ rather than `instanceof DocumentFragment`, which is realm-bound and
10317
+ silently skipped foreign-realm shadow roots (e.g.
10318
+ iframe.contentDocument attachShadow). */
10319
+ if (isElement) {
10320
+ const sr = getShadowRoot(node);
10321
+ if (_isDocumentFragment(sr)) {
10322
+ /* Push the deferred sanitise first so it pops after the shadow
10323
+ walk we push next, i.e. nested shadow roots are discovered
10324
+ before this one is sanitised. */
10325
+ stack.push({
10326
+ node: null,
10327
+ shadow: sr
10328
+ }, {
10329
+ node: sr,
10330
+ shadow: null
10331
+ });
10332
+ }
10333
+ }
10334
+ }
10335
+ };
9395
10336
  // eslint-disable-next-line complexity
9396
10337
  DOMPurify.sanitize = function (dirty) {
9397
10338
  let cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
@@ -9408,13 +10349,9 @@ function requirePurify_cjs () {
9408
10349
  }
9409
10350
  /* Stringify, in case dirty is an object */
9410
10351
  if (typeof dirty !== 'string' && !_isNode(dirty)) {
9411
- if (typeof dirty.toString === 'function') {
9412
- dirty = dirty.toString();
9413
- if (typeof dirty !== 'string') {
9414
- throw typeErrorCreate('dirty is not a string, aborting');
9415
- }
9416
- } else {
9417
- throw typeErrorCreate('toString is not a function');
10352
+ dirty = stringifyValue(dirty);
10353
+ if (typeof dirty !== 'string') {
10354
+ throw typeErrorCreate('dirty is not a string, aborting');
9418
10355
  }
9419
10356
  }
9420
10357
  /* Return dirty HTML if DOMPurify cannot run */
@@ -9422,24 +10359,78 @@ function requirePurify_cjs () {
9422
10359
  return dirty;
9423
10360
  }
9424
10361
  /* Assign config vars */
9425
- if (!SET_CONFIG) {
10362
+ if (SET_CONFIG) {
10363
+ /* Persistent setConfig() path: _parseConfig is skipped, so the sets are
10364
+ * not re-derived per call. Restore them from the pristine bindings
10365
+ * captured at setConfig() time so a previous call's hook clone (mutated
10366
+ * below) does not carry over. */
10367
+ ALLOWED_TAGS = SET_CONFIG_ALLOWED_TAGS;
10368
+ ALLOWED_ATTR = SET_CONFIG_ALLOWED_ATTR;
10369
+ } else {
9426
10370
  _parseConfig(cfg);
9427
10371
  }
10372
+ /* Clone the hook-mutable allowlists before the walk whenever an
10373
+ * uponSanitize* hook is registered. The hook event exposes ALLOWED_TAGS
10374
+ * and ALLOWED_ATTR by reference (as allowedTags / allowedAttributes), so
10375
+ * a hook that widens them would otherwise mutate the shared set
10376
+ * permanently: across later calls and across every element. Cloning per
10377
+ * walk keeps documented in-call widening working while scoping it to the
10378
+ * call. A single guard for both config paths - the per-call path rebinds
10379
+ * the sets in _parseConfig each call, the persistent path restores them
10380
+ * from the captured bindings just above - so the two cannot diverge. */
10381
+ if (hooks.uponSanitizeElement.length > 0 || hooks.uponSanitizeAttribute.length > 0) {
10382
+ ALLOWED_TAGS = clone(ALLOWED_TAGS);
10383
+ }
10384
+ if (hooks.uponSanitizeAttribute.length > 0) {
10385
+ ALLOWED_ATTR = clone(ALLOWED_ATTR);
10386
+ }
9428
10387
  /* Clean up removed elements */
9429
10388
  DOMPurify.removed = [];
9430
- /* Check if dirty is correctly typed for IN_PLACE */
9431
- if (typeof dirty === 'string') {
9432
- IN_PLACE = false;
9433
- }
9434
- if (IN_PLACE) {
9435
- /* Do some early pre-sanitization to avoid unsafe root nodes */
9436
- if (dirty.nodeName) {
9437
- const tagName = transformCaseFunc(dirty.nodeName);
10389
+ /* Resolve IN_PLACE for this call without mutating persistent config.
10390
+ Writing the IN_PLACE closure variable here leaks under setConfig(),
10391
+ where _parseConfig is skipped on later calls: a single string call would
10392
+ disable in-place mode for every subsequent node call, returning a
10393
+ sanitized copy while leaving the caller's node — which in-place callers
10394
+ keep using and whose return value they ignore — unsanitized. REPORT-2. */
10395
+ const inPlace = IN_PLACE && typeof dirty !== 'string' && _isNode(dirty);
10396
+ if (inPlace) {
10397
+ /* Do some early pre-sanitization to avoid unsafe root nodes.
10398
+ Read nodeName through the cached prototype getter — a clobbering
10399
+ child named "nodeName" on the form root would otherwise shadow
10400
+ the property and let this check skip the root-allowlist
10401
+ validation entirely. */
10402
+ const nn = getNodeName ? getNodeName(dirty) : dirty.nodeName;
10403
+ if (typeof nn === 'string') {
10404
+ const tagName = transformCaseFunc(nn);
9438
10405
  if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
9439
10406
  throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');
9440
10407
  }
9441
10408
  }
9442
- } else if (dirty instanceof Node) {
10409
+ /* Pre-flight the root through _isClobbered. The iterator-driven
10410
+ removal path can not detach a parent-less root: _forceRemove
10411
+ falls through to Element.prototype.remove(), which per spec
10412
+ is a no-op on a node with no parent. A clobbered root would
10413
+ then survive the main loop with its attributes uninspected,
10414
+ because _sanitizeAttributes early-returns on _isClobbered. The
10415
+ result would be an attacker-controlled form, complete with any
10416
+ event-handler attributes the caller passed in, handed back to
10417
+ the application unsanitized. Refuse to sanitize such a root
10418
+ the same way we refuse a forbidden tag. GHSA-r47g-fvhr-h676. */
10419
+ if (_isClobbered(dirty)) {
10420
+ throw typeErrorCreate('root node is clobbered and cannot be sanitized in-place');
10421
+ }
10422
+ /* Sanitize attached shadow roots before the main iterator runs.
10423
+ The iterator does not descend into shadow trees. Same fail-closed
10424
+ barrier as the main walk (campaign-3 F2): a custom-element reaction
10425
+ inside a shadow root could abort this pre-pass before the walk runs,
10426
+ which would otherwise leave the entire live tree unsanitized. */
10427
+ try {
10428
+ _sanitizeAttachedShadowRoots(dirty);
10429
+ } catch (error) {
10430
+ _neutralizeRoot(dirty);
10431
+ throw error;
10432
+ }
10433
+ } else if (_isNode(dirty)) {
9443
10434
  /* If dirty is a DOM element, append to an empty document to avoid
9444
10435
  elements being stripped by the parser */
9445
10436
  body = _initDocument('<!---->');
@@ -9453,12 +10444,18 @@ function requirePurify_cjs () {
9453
10444
  // eslint-disable-next-line unicorn/prefer-dom-node-append
9454
10445
  body.appendChild(importedNode);
9455
10446
  }
10447
+ /* Clonable shadow roots are deep-cloned by importNode(); sanitize
10448
+ them before the main iterator runs, since the iterator does not
10449
+ descend into shadow trees. The walk routes every read through a
10450
+ cached prototype getter so clobbering descendants on a form root
10451
+ cannot hide a shadow host from this pass. */
10452
+ _sanitizeAttachedShadowRoots(importedNode);
9456
10453
  } else {
9457
10454
  /* Exit directly if we have nothing to do */
9458
10455
  if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT &&
9459
10456
  // eslint-disable-next-line unicorn/prefer-includes
9460
10457
  dirty.indexOf('<') === -1) {
9461
- return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;
10458
+ return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? _createTrustedHTML(dirty) : dirty;
9462
10459
  }
9463
10460
  /* Initialize the document to work on */
9464
10461
  body = _initDocument(dirty);
@@ -9472,31 +10469,59 @@ function requirePurify_cjs () {
9472
10469
  _forceRemove(body.firstChild);
9473
10470
  }
9474
10471
  /* Get node iterator */
9475
- const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body);
9476
- /* Now start iterating over the created document */
9477
- while (currentNode = nodeIterator.nextNode()) {
9478
- /* Sanitize tags and elements */
9479
- _sanitizeElements(currentNode);
9480
- /* Check attributes next */
9481
- _sanitizeAttributes(currentNode);
9482
- /* Shadow DOM detected, sanitize it */
9483
- if (currentNode.content instanceof DocumentFragment) {
9484
- _sanitizeShadowDOM2(currentNode.content);
10472
+ const nodeIterator = _createNodeIterator(inPlace ? dirty : body);
10473
+ /* Now start iterating over the created document.
10474
+ The walk runs inside an exception barrier (campaign-3 F2): a re-entrant
10475
+ engine/custom-element mutation can detach a node mid-walk so
10476
+ `_forceRemove`'s parentless guard throws, aborting the loop. Without the
10477
+ barrier the caller's in-place tree would be left half-sanitized with the
10478
+ unvisited tail still armed. On any throw we fail closed — strip the
10479
+ in-place root bare — then rethrow so the existing throw contract is
10480
+ preserved. (String/DOM-copy paths never return the partial body, so the
10481
+ propagating throw is already fail-closed there.) */
10482
+ try {
10483
+ while (currentNode = nodeIterator.nextNode()) {
10484
+ /* Sanitize tags and elements */
10485
+ _sanitizeElements(currentNode);
10486
+ /* Check attributes next */
10487
+ _sanitizeAttributes(currentNode);
10488
+ /* Shadow DOM detected, sanitize it.
10489
+ Realm-safe check (GHSA-hpcv-96wg-7vj8): nodeType-based detection
10490
+ instead of instanceof, so foreign-realm <template>.content is
10491
+ walked correctly. */
10492
+ if (_isDocumentFragment(currentNode.content)) {
10493
+ _sanitizeShadowDOM2(currentNode.content);
10494
+ }
9485
10495
  }
10496
+ } catch (error) {
10497
+ if (inPlace) {
10498
+ _neutralizeRoot(dirty);
10499
+ }
10500
+ throw error;
9486
10501
  }
9487
10502
  /* If we sanitized `dirty` in-place, return it. */
9488
- if (IN_PLACE) {
10503
+ if (inPlace) {
10504
+ /* Fail-closed completion of the audit-5 F1 fix: every node removed from
10505
+ the caller's live tree is detached but may still hold a queued
10506
+ resource-event handler that fires in page scope after we return. The
10507
+ move-hoist covers only disallowed-tag KEEP_CONTENT removals; strip the
10508
+ non-allow-listed attributes off every other removed subtree (clobber,
10509
+ mXSS, namespace, comments, KEEP_CONTENT:false, …) so those handlers are
10510
+ cancelled before any event can fire. Runs synchronously, pre-return. */
10511
+ arrayForEach(DOMPurify.removed, entry => {
10512
+ if (entry.element) {
10513
+ _neutralizeSubtree(entry.element);
10514
+ }
10515
+ });
10516
+ if (SAFE_FOR_TEMPLATES) {
10517
+ _scrubTemplateExpressions2(dirty);
10518
+ }
9489
10519
  return dirty;
9490
10520
  }
9491
10521
  /* Return sanitized string or DOM */
9492
10522
  if (RETURN_DOM) {
9493
10523
  if (SAFE_FOR_TEMPLATES) {
9494
- body.normalize();
9495
- let html = body.innerHTML;
9496
- arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
9497
- html = stringReplace(html, expr, ' ');
9498
- });
9499
- body.innerHTML = html;
10524
+ _scrubTemplateExpressions2(body);
9500
10525
  }
9501
10526
  if (RETURN_DOM_FRAGMENT) {
9502
10527
  returnNode = createDocumentFragment.call(body.ownerDocument);
@@ -9526,20 +10551,28 @@ function requirePurify_cjs () {
9526
10551
  }
9527
10552
  /* Sanitize final string template-safe */
9528
10553
  if (SAFE_FOR_TEMPLATES) {
9529
- arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
9530
- serializedHTML = stringReplace(serializedHTML, expr, ' ');
9531
- });
10554
+ serializedHTML = _stripTemplateExpressions(serializedHTML);
9532
10555
  }
9533
- return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;
10556
+ return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? _createTrustedHTML(serializedHTML) : serializedHTML;
9534
10557
  };
9535
10558
  DOMPurify.setConfig = function () {
9536
10559
  let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
9537
10560
  _parseConfig(cfg);
9538
10561
  SET_CONFIG = true;
10562
+ SET_CONFIG_ALLOWED_TAGS = ALLOWED_TAGS;
10563
+ SET_CONFIG_ALLOWED_ATTR = ALLOWED_ATTR;
9539
10564
  };
9540
10565
  DOMPurify.clearConfig = function () {
9541
10566
  CONFIG = null;
9542
10567
  SET_CONFIG = false;
10568
+ SET_CONFIG_ALLOWED_TAGS = null;
10569
+ SET_CONFIG_ALLOWED_ATTR = null;
10570
+ // Drop any caller-supplied Trusted Types policy so it cannot poison later
10571
+ // `RETURN_TRUSTED_TYPE` output. The internal default policy (cached, and
10572
+ // never recreated — Trusted Types throws on duplicate names) is restored by
10573
+ // the next `_parseConfig`. See GHSA-vxr8-fq34-vvx9.
10574
+ trustedTypesPolicy = defaultTrustedTypesPolicy;
10575
+ emptyHTML = '';
9543
10576
  };
9544
10577
  DOMPurify.isValidAttribute = function (tag, attr, value) {
9545
10578
  /* Initialize shared config vars if necessary. */
@@ -9554,9 +10587,19 @@ function requirePurify_cjs () {
9554
10587
  if (typeof hookFunction !== 'function') {
9555
10588
  return;
9556
10589
  }
10590
+ /* Reject unknown entry points. Without this, a non-hook key (e.g.
10591
+ * '__proto__') indexes off the prototype chain rather than a real
10592
+ * hook array, and arrayPush then writes to Object.prototype. Guard
10593
+ * with an own-property check against the known hook names. */
10594
+ if (!objectHasOwnProperty(hooks, entryPoint)) {
10595
+ return;
10596
+ }
9557
10597
  arrayPush(hooks[entryPoint], hookFunction);
9558
10598
  };
9559
10599
  DOMPurify.removeHook = function (entryPoint, hookFunction) {
10600
+ if (!objectHasOwnProperty(hooks, entryPoint)) {
10601
+ return undefined;
10602
+ }
9560
10603
  if (hookFunction !== undefined) {
9561
10604
  const index = arrayLastIndexOf(hooks[entryPoint], hookFunction);
9562
10605
  return index === -1 ? undefined : arraySplice(hooks[entryPoint], index, 1)[0];
@@ -9564,6 +10607,9 @@ function requirePurify_cjs () {
9564
10607
  return arrayPop(hooks[entryPoint]);
9565
10608
  };
9566
10609
  DOMPurify.removeHooks = function (entryPoint) {
10610
+ if (!objectHasOwnProperty(hooks, entryPoint)) {
10611
+ return;
10612
+ }
9567
10613
  hooks[entryPoint] = [];
9568
10614
  };
9569
10615
  DOMPurify.removeAllHooks = function () {
@@ -9824,10 +10870,26 @@ var WalletBackground = /*#__PURE__*/function (_Background) {
9824
10870
  }(Background);
9825
10871
 
9826
10872
  /**
9827
- * Generate a unique id compatible with HTML element id
10873
+ * Generate a unique id compatible with HTML element id.
10874
+ * Uses the Web Crypto API for cryptographically strong randomness, with a
10875
+ * deterministic fallback only when crypto is unavailable.
9828
10876
  */
9829
10877
  function getUniqueId() {
9830
- return Math.random().toString(36).replace(/[^a-z]+/g, '').substr(2, 10);
10878
+ var letters = 'abcdefghijklmnopqrstuvwxyz';
10879
+ var length = 10;
10880
+ var bytes = new Uint8Array(length);
10881
+ if (typeof crypto !== 'undefined' && typeof crypto.getRandomValues === 'function') {
10882
+ crypto.getRandomValues(bytes);
10883
+ } else {
10884
+ for (var i = 0; i < length; i++) {
10885
+ bytes[i] = (i * 31 + 7) % 256;
10886
+ }
10887
+ }
10888
+ var id = '';
10889
+ for (var _i = 0; _i < length; _i++) {
10890
+ id += letters[bytes[_i] % letters.length];
10891
+ }
10892
+ return id;
9831
10893
  }
9832
10894
 
9833
10895
  function getFlypayV2Button(widgetId) {
@@ -12793,208 +13855,75 @@ function getBaseFormFields(configuration) {
12793
13855
  function getDefinedFormFields(configuration) {
12794
13856
  return getBaseFormFields(configuration).map(function (field) {
12795
13857
  var _a, _b;
12796
- if ((_a = configuration.defined_form_fields) === null || _a === void 0 ? void 0 : _a.includes(field)) {
12797
- return field;
12798
- }
12799
- if ((_b = configuration.defined_form_fields) === null || _b === void 0 ? void 0 : _b.includes("".concat(field, "*"))) {
12800
- return "".concat(field, "*");
12801
- }
12802
- }).filter(Boolean);
12803
- }
12804
- function getDynamicFormFields(configuration) {
12805
- var _a;
12806
- var baseFormFields = getBaseFormFields(configuration);
12807
- return (_a = configuration.defined_form_fields) === null || _a === void 0 ? void 0 : _a.map(function (field) {
12808
- var sanitizedField = field.replace('*', '');
12809
- if (baseFormFields.includes(sanitizedField)) {
12810
- return field;
12811
- }
12812
- }).filter(Boolean);
12813
- }
12814
- function getMetaFields(configuration) {
12815
- return Object.values(META_FIELDS).reduce(function (accumulator, metaField) {
12816
- var _a;
12817
- var configurationMetaFieldValue = (_a = configuration.meta) === null || _a === void 0 ? void 0 : _a[metaField];
12818
- if (!configurationMetaFieldValue) {
12819
- return accumulator;
12820
- }
12821
- return _extends({}, accumulator, _defineProperty({}, metaField, configuration.meta[metaField]));
12822
- }, {});
12823
- }
12824
- function getPredefinedFields(configuration) {
12825
- var gatewayId = configuration.predefined_fields.gateway_id === 'not_configured' ? '' : configuration.predefined_fields.gateway_id;
12826
- return _extends({}, configuration.predefined_fields, {
12827
- gateway_id: gatewayId
12828
- });
12829
- }
12830
- function getWrongPredefinedFields(configuration) {
12831
- var erroringFields = getBasePredefinedFields(configuration).map(function (field) {
12832
- return !configuration.predefined_fields[field] ? field : '';
12833
- }).filter(Boolean);
12834
- if (erroringFields.length) {
12835
- return erroringFields.join(', ').concat(" ".concat(erroringFields.length > 1 ? 'are' : 'is', " cannot be empty"));
12836
- }
12837
- }
12838
- function getBasePredefinedFields(configuration) {
12839
- var basePredefinedFields = [PREDEFINED_FIELDS.GATEWAY_ID, PREDEFINED_FIELDS.TYPE];
12840
- switch (configuration.predefined_fields.type) {
12841
- case PAYMENT_SOURCE_TYPE.GIFT_CARD:
12842
- {
12843
- return basePredefinedFields.concat([PREDEFINED_FIELDS.CARD_SCHEME, PREDEFINED_FIELDS.CARD_PROCESSING_NETWORK]);
12844
- }
12845
- default:
12846
- {
12847
- return basePredefinedFields;
12848
- }
12849
- }
12850
- }
12851
- function getHandleCvv(configuration) {
12852
- switch (configuration.purpose) {
12853
- case PURPOSE$1.CARD_PAYMENT_SOURCE_WITH_CVV:
12854
- {
12855
- return true;
12856
- }
12857
- case PURPOSE$1.CARD_PAYMENT_SOURCE_WITHOUT_CVV:
12858
- {
12859
- return false;
12860
- }
12861
- default:
12862
- {
12863
- return undefined;
12864
- }
12865
- }
12866
- }
12867
-
12868
- /**
12869
- * Top-level classification of an error. Used by the SDK to route errors to the
12870
- * right category in instrumentation and to give consumers a coarse-grained
12871
- * tag for grouping/filtering. See {@link getErrorCategory} for the mapping
12872
- * between {@link ERROR_CAUSE} and {@link ERROR_CATEGORY}.
12873
- */
12874
- var ERROR_CATEGORY = {
12875
- /** SDK was misconfigured (missing keys, invalid options, etc.). */
12876
- CONFIGURATION: 'configuration',
12877
- /** Authentication or authorization failure. */
12878
- IDENTITY: 'identity_access_management',
12879
- /** SDK internal failure or upstream service problem. */
12880
- INTERNAL: 'internal',
12881
- /** Flow lifecycle event (user cancelled, aborted, etc.) — not a real fault. */
12882
- PROCESS: 'process',
12883
- /** Resource lookup failed or was rate-limited. */
12884
- RESOURCE: 'resource',
12885
- /** Invalid input or business-rule validation failure. */
12886
- VALIDATION: 'validation'
12887
- };
12888
- /**
12889
- * Concrete cause of an error. More specific than {@link ERROR_CATEGORY} —
12890
- * useful for deciding programmatic responses (e.g. show a retry button only
12891
- * when `cause` is `'service_unreachable'` or `'server_busy'`).
12892
- */
12893
- var ERROR_CAUSE = {
12894
- /** Operation was aborted programmatically. */
12895
- ABORTED: 'aborted',
12896
- /** Caller has insufficient permissions for the operation. */
12897
- ACCESS_FORBIDDEN: 'access_forbidden',
12898
- /** Resource already exists when create was expected. */
12899
- ALREADY_EXISTS: 'already_exists',
12900
- /** User cancelled the flow (e.g. closed the wallet sheet). */
12901
- CANCELED: 'canceled',
12902
- /** SDK was instantiated or invoked with invalid configuration. */
12903
- INVALID_CONFIGURATION: 'invalid_configuration',
12904
- /** Input failed structural or business-rule validation. */
12905
- INVALID_INPUT: 'invalid_input',
12906
- /** Resource was not found by the backend. */
12907
- NOT_FOUND: 'not_found',
12908
- /** Operation is not supported in the current context or version. */
12909
- NOT_IMPLEMENTED: 'not_implemented',
12910
- /** Caller exceeded the allowed request rate. */
12911
- RATE_LIMITED: 'rate_limited',
12912
- /** Backend is healthy but currently overloaded — typically retryable. */
12913
- SERVER_BUSY: 'server_busy',
12914
- /** Backend or third-party service could not be reached — typically retryable. */
12915
- SERVICE_UNREACHABLE: 'service_unreachable',
12916
- /** Caller is not authenticated. */
12917
- UNAUTHORIZED: 'unauthorized',
12918
- /** Catch-all when no other cause applies. */
12919
- UNKNOWN: 'unknown_error',
12920
- /** Request was syntactically valid but semantically rejected. */
12921
- UNPROCESSABLE_ENTITY: 'unprocessable_entity'
12922
- };
12923
- var EventError = /*#__PURE__*/function (_Error) {
12924
- function EventError(cause, category, retryable, details) {
12925
- var _this;
12926
- _classCallCheck(this, EventError);
12927
- _this = _callSuper(this, EventError, [details.message]);
12928
- _this.cause = cause;
12929
- _this.category = category;
12930
- _this.retryable = retryable;
12931
- _this.details = details;
12932
- Object.setPrototypeOf(_this, EventError.prototype);
12933
- _this.name = EventError.name;
12934
- return _this;
12935
- }
12936
- _inherits(EventError, _Error);
12937
- return _createClass(EventError, [{
12938
- key: "toJSON",
12939
- value: function toJSON() {
12940
- return {
12941
- error: {
12942
- category: this.category,
12943
- cause: this.cause,
12944
- details: this.details,
12945
- retryable: this.retryable
12946
- }
12947
- };
13858
+ if ((_a = configuration.defined_form_fields) === null || _a === void 0 ? void 0 : _a.includes(field)) {
13859
+ return field;
12948
13860
  }
12949
- }, {
12950
- key: "setContextId",
12951
- value: function setContextId(contextId) {
12952
- this.details.contextId = contextId;
13861
+ if ((_b = configuration.defined_form_fields) === null || _b === void 0 ? void 0 : _b.includes("".concat(field, "*"))) {
13862
+ return "".concat(field, "*");
12953
13863
  }
12954
- }, {
12955
- key: "setPurpose",
12956
- value: function setPurpose(purpose) {
12957
- this.purpose = purpose;
13864
+ }).filter(Boolean);
13865
+ }
13866
+ function getDynamicFormFields(configuration) {
13867
+ var _a;
13868
+ var baseFormFields = getBaseFormFields(configuration);
13869
+ return (_a = configuration.defined_form_fields) === null || _a === void 0 ? void 0 : _a.map(function (field) {
13870
+ var sanitizedField = field.replace('*', '');
13871
+ if (baseFormFields.includes(sanitizedField)) {
13872
+ return field;
12958
13873
  }
12959
- }], [{
12960
- key: "create",
12961
- value: function create(cause, message) {
12962
- var contextId = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
12963
- var retryable = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
12964
- var details = {
12965
- cause: cause,
12966
- contextId: contextId,
12967
- message: message,
12968
- timestamp: new Date().toISOString()
12969
- };
12970
- var category = getErrorCategory(cause);
12971
- return new EventError(cause, category, retryable, details);
13874
+ }).filter(Boolean);
13875
+ }
13876
+ function getMetaFields(configuration) {
13877
+ return Object.values(META_FIELDS).reduce(function (accumulator, metaField) {
13878
+ var _a;
13879
+ var configurationMetaFieldValue = (_a = configuration.meta) === null || _a === void 0 ? void 0 : _a[metaField];
13880
+ if (!configurationMetaFieldValue) {
13881
+ return accumulator;
12972
13882
  }
12973
- }]);
12974
- }(/*#__PURE__*/_wrapNativeSuper(Error));
12975
- function getErrorCategory(cause) {
12976
- switch (cause) {
12977
- case ERROR_CAUSE.INVALID_CONFIGURATION:
12978
- return ERROR_CATEGORY.CONFIGURATION;
12979
- case ERROR_CAUSE.ACCESS_FORBIDDEN:
12980
- case ERROR_CAUSE.UNAUTHORIZED:
12981
- return ERROR_CATEGORY.IDENTITY;
12982
- case ERROR_CAUSE.SERVICE_UNREACHABLE:
12983
- case ERROR_CAUSE.NOT_IMPLEMENTED:
12984
- case ERROR_CAUSE.SERVER_BUSY:
12985
- return ERROR_CATEGORY.INTERNAL;
12986
- case ERROR_CAUSE.ABORTED:
12987
- case ERROR_CAUSE.CANCELED:
12988
- return ERROR_CATEGORY.PROCESS;
12989
- case ERROR_CAUSE.NOT_FOUND:
12990
- case ERROR_CAUSE.RATE_LIMITED:
12991
- return ERROR_CATEGORY.RESOURCE;
12992
- case ERROR_CAUSE.ALREADY_EXISTS:
12993
- case ERROR_CAUSE.INVALID_INPUT:
12994
- case ERROR_CAUSE.UNPROCESSABLE_ENTITY:
12995
- return ERROR_CATEGORY.VALIDATION;
13883
+ return _extends({}, accumulator, _defineProperty({}, metaField, configuration.meta[metaField]));
13884
+ }, {});
13885
+ }
13886
+ function getPredefinedFields(configuration) {
13887
+ var gatewayId = configuration.predefined_fields.gateway_id === 'not_configured' ? '' : configuration.predefined_fields.gateway_id;
13888
+ return _extends({}, configuration.predefined_fields, {
13889
+ gateway_id: gatewayId
13890
+ });
13891
+ }
13892
+ function getWrongPredefinedFields(configuration) {
13893
+ var erroringFields = getBasePredefinedFields(configuration).map(function (field) {
13894
+ return !configuration.predefined_fields[field] ? field : '';
13895
+ }).filter(Boolean);
13896
+ if (erroringFields.length) {
13897
+ return erroringFields.join(', ').concat(" ".concat(erroringFields.length > 1 ? 'are' : 'is', " cannot be empty"));
13898
+ }
13899
+ }
13900
+ function getBasePredefinedFields(configuration) {
13901
+ var basePredefinedFields = [PREDEFINED_FIELDS.GATEWAY_ID, PREDEFINED_FIELDS.TYPE];
13902
+ switch (configuration.predefined_fields.type) {
13903
+ case PAYMENT_SOURCE_TYPE.GIFT_CARD:
13904
+ {
13905
+ return basePredefinedFields.concat([PREDEFINED_FIELDS.CARD_SCHEME, PREDEFINED_FIELDS.CARD_PROCESSING_NETWORK]);
13906
+ }
12996
13907
  default:
12997
- return ERROR_CATEGORY.INTERNAL;
13908
+ {
13909
+ return basePredefinedFields;
13910
+ }
13911
+ }
13912
+ }
13913
+ function getHandleCvv(configuration) {
13914
+ switch (configuration.purpose) {
13915
+ case PURPOSE$1.CARD_PAYMENT_SOURCE_WITH_CVV:
13916
+ {
13917
+ return true;
13918
+ }
13919
+ case PURPOSE$1.CARD_PAYMENT_SOURCE_WITHOUT_CVV:
13920
+ {
13921
+ return false;
13922
+ }
13923
+ default:
13924
+ {
13925
+ return undefined;
13926
+ }
12998
13927
  }
12999
13928
  }
13000
13929
 
@@ -19092,6 +20021,90 @@ var EVENT$2;
19092
20021
  EVENT["ON_SHIPPING_OPTIONS_CHANGE"] = "onShippingOptionsChange";
19093
20022
  })(EVENT$2 || (EVENT$2 = {}));
19094
20023
 
20024
+ /** TTL for a cached service configuration: 1 day, in milliseconds. */
20025
+ var CACHE_TTL_MS = 86400000;
20026
+ /** Builds the `localStorage` key used to cache a service's configuration. */
20027
+ function serviceConfigStorageKey(serviceId) {
20028
+ return "paydock-serviceConfig-".concat(serviceId);
20029
+ }
20030
+ /**
20031
+ * Removes the cached service configuration for the given service ID, forcing the next
20032
+ * fetch to go to the network. Called on error / unavailable flows so a potentially
20033
+ * stale cached config is not reused after something changed server-side. No-throw when
20034
+ * `localStorage` is unavailable.
20035
+ *
20036
+ * @param serviceId - The service ID whose cached configuration should be cleared.
20037
+ */
20038
+ function clearServiceConfigCache(serviceId) {
20039
+ try {
20040
+ localStorage.removeItem(serviceConfigStorageKey(serviceId));
20041
+ } catch (_error) {
20042
+ // localStorage may be unavailable; nothing to clear
20043
+ }
20044
+ }
20045
+ /**
20046
+ * Fetches the wallet service configuration, backed by a 1-day `localStorage` cache
20047
+ * keyed on the service ID. Falls back gracefully (no caching) when `localStorage`
20048
+ * is unavailable (e.g. private browsing). Shared by the instance `load()` flow and
20049
+ * the static availability checks so both reuse the same cached fetch.
20050
+ *
20051
+ * @param api - The configured API client (env must already be set).
20052
+ * @param serviceId - The service ID to fetch the configuration for.
20053
+ * @returns The service configuration response.
20054
+ */
20055
+ function getServiceConfigCached(api, serviceId) {
20056
+ return __awaiter(this, void 0, void 0, /*#__PURE__*/_regenerator().m(function _callee() {
20057
+ var storageKey, cachedData, _JSON$parse, data, timestamp, serviceConfigResponse, encodedData;
20058
+ return _regenerator().w(function (_context) {
20059
+ while (1) switch (_context.p = _context.n) {
20060
+ case 0:
20061
+ storageKey = serviceConfigStorageKey(serviceId);
20062
+ _context.p = 1;
20063
+ cachedData = localStorage.getItem(storageKey);
20064
+ if (!cachedData) {
20065
+ _context.n = 5;
20066
+ break;
20067
+ }
20068
+ _context.p = 2;
20069
+ _JSON$parse = JSON.parse(atob(cachedData)), data = _JSON$parse.data, timestamp = _JSON$parse.timestamp;
20070
+ if (!(Date.now() - timestamp < CACHE_TTL_MS)) {
20071
+ _context.n = 3;
20072
+ break;
20073
+ }
20074
+ return _context.a(2, JSON.parse(data));
20075
+ case 3:
20076
+ _context.n = 5;
20077
+ break;
20078
+ case 4:
20079
+ _context.p = 4;
20080
+ _context.v;
20081
+ localStorage.removeItem(storageKey);
20082
+ case 5:
20083
+ _context.n = 7;
20084
+ break;
20085
+ case 6:
20086
+ _context.p = 6;
20087
+ _context.v;
20088
+ case 7:
20089
+ _context.n = 8;
20090
+ return api.service().getConfig(serviceId);
20091
+ case 8:
20092
+ serviceConfigResponse = _context.v;
20093
+ try {
20094
+ encodedData = btoa(JSON.stringify({
20095
+ data: JSON.stringify(serviceConfigResponse),
20096
+ timestamp: Date.now()
20097
+ }));
20098
+ localStorage.setItem(storageKey, encodedData);
20099
+ } catch (_error) {
20100
+ // localStorage may be unavailable; proceed without caching
20101
+ }
20102
+ return _context.a(2, serviceConfigResponse);
20103
+ }
20104
+ }, _callee, null, [[2, 4], [1, 6]]);
20105
+ }));
20106
+ }
20107
+
19095
20108
  /**
19096
20109
  * @classdesc Abstract base class for Open Wallet buttons. **Do not instantiate directly.**
19097
20110
  * Use {@link ApplePayOpenWalletButton} or {@link GooglePayOpenWalletButton} instead.
@@ -19125,10 +20138,30 @@ var OpenWalletButtons = /*#__PURE__*/function () {
19125
20138
  this.api = new ApiInternal(publicKeyOrAccessToken, this.getApiAuthType(publicKeyOrAccessToken));
19126
20139
  this.serviceId = serviceId;
19127
20140
  this.meta = meta;
20141
+ this.registerCacheInvalidationOnError();
19128
20142
  this.validateBaseMeta();
19129
20143
  this.validateWalletMeta();
19130
20144
  }
20145
+ /**
20146
+ * Invalidates the cached service configuration whenever an error or unavailable
20147
+ * event fires, so the next `load()` re-fetches a fresh config. The cache is keyed
20148
+ * on the service ID with a 1-day TTL; clearing it on failure means a config that
20149
+ * changed server-side (and caused the failure) is not reused until the TTL expires.
20150
+ * Registered once per button, independently of any merchant-registered handlers.
20151
+ *
20152
+ * @private
20153
+ */
19131
20154
  return _createClass(OpenWalletButtons, [{
20155
+ key: "registerCacheInvalidationOnError",
20156
+ value: function registerCacheInvalidationOnError() {
20157
+ var _this = this;
20158
+ var invalidate = function invalidate() {
20159
+ return clearServiceConfigCache(_this.serviceId);
20160
+ };
20161
+ this.eventEmitter.subscribe(EVENT$2.ERROR, invalidate);
20162
+ this.eventEmitter.subscribe(EVENT$2.UNAVAILABLE, invalidate);
20163
+ }
20164
+ }, {
19132
20165
  key: "getApiAuthType",
19133
20166
  value: function getApiAuthType(publicKeyOrAccessToken) {
19134
20167
  if (AccessToken.validateJWT(publicKeyOrAccessToken)) {
@@ -19162,57 +20195,7 @@ var OpenWalletButtons = /*#__PURE__*/function () {
19162
20195
  }, {
19163
20196
  key: "getOpenWalletServiceConfig",
19164
20197
  value: function getOpenWalletServiceConfig() {
19165
- return __awaiter(this, void 0, void 0, /*#__PURE__*/_regenerator().m(function _callee() {
19166
- var storageKey, cachedData, _JSON$parse, data, timestamp, oneDay, serviceConfigResponse, encodedData;
19167
- return _regenerator().w(function (_context) {
19168
- while (1) switch (_context.p = _context.n) {
19169
- case 0:
19170
- storageKey = "serviceConfig-".concat(this.serviceId);
19171
- _context.p = 1;
19172
- cachedData = localStorage.getItem(storageKey);
19173
- if (!cachedData) {
19174
- _context.n = 5;
19175
- break;
19176
- }
19177
- _context.p = 2;
19178
- _JSON$parse = JSON.parse(atob(cachedData)), data = _JSON$parse.data, timestamp = _JSON$parse.timestamp;
19179
- oneDay = 86400000;
19180
- if (!(Date.now() - timestamp < oneDay)) {
19181
- _context.n = 3;
19182
- break;
19183
- }
19184
- return _context.a(2, JSON.parse(data));
19185
- case 3:
19186
- _context.n = 5;
19187
- break;
19188
- case 4:
19189
- _context.p = 4;
19190
- _context.v;
19191
- localStorage.removeItem(storageKey);
19192
- case 5:
19193
- _context.n = 7;
19194
- break;
19195
- case 6:
19196
- _context.p = 6;
19197
- _context.v;
19198
- case 7:
19199
- _context.n = 8;
19200
- return this.api.service().getConfig(this.serviceId);
19201
- case 8:
19202
- serviceConfigResponse = _context.v;
19203
- try {
19204
- encodedData = btoa(JSON.stringify({
19205
- data: JSON.stringify(serviceConfigResponse),
19206
- timestamp: Date.now()
19207
- }));
19208
- localStorage.setItem(storageKey, encodedData);
19209
- } catch (_error) {
19210
- // localStorage may be unavailable; proceed without caching
19211
- }
19212
- return _context.a(2, serviceConfigResponse);
19213
- }
19214
- }, _callee, this, [[2, 4], [1, 6]]);
19215
- }));
20198
+ return getServiceConfigCached(this.api, this.serviceId);
19216
20199
  }
19217
20200
  }, {
19218
20201
  key: "handleOnError",
@@ -19247,13 +20230,13 @@ var OpenWalletButtons = /*#__PURE__*/function () {
19247
20230
  }, {
19248
20231
  key: "load",
19249
20232
  value: function load() {
19250
- var _this = this;
20233
+ var _this2 = this;
19251
20234
  this.getOpenWalletServiceConfig().then(function (serviceConfig) {
19252
- _this.validateServiceType(serviceConfig);
19253
- _this.walletService = _this.createWalletService(serviceConfig);
19254
- _this.walletService.load();
20235
+ _this2.validateServiceType(serviceConfig);
20236
+ _this2.walletService = _this2.createWalletService(serviceConfig);
20237
+ _this2.walletService.load();
19255
20238
  })["catch"](function (error) {
19256
- _this.handleOnError(error instanceof Error ? error : new Error(String(error)), ERROR_OPERATION.CONFIGURATION);
20239
+ _this2.handleOnError(error instanceof Error ? error : new Error(String(error)), ERROR_OPERATION.CONFIGURATION);
19257
20240
  });
19258
20241
  }
19259
20242
  /**
@@ -19451,28 +20434,28 @@ var OpenWalletButtons = /*#__PURE__*/function () {
19451
20434
  }, {
19452
20435
  key: "onSuccess",
19453
20436
  value: function onSuccess(handler) {
19454
- var _this2 = this;
20437
+ var _this3 = this;
19455
20438
  if (typeof handler === 'function') {
19456
20439
  this.eventEmitter.subscribe(EVENT$2.SUCCESS, function (data) {
19457
- return __awaiter(_this2, void 0, void 0, /*#__PURE__*/_regenerator().m(function _callee2() {
19458
- var _t3;
19459
- return _regenerator().w(function (_context2) {
19460
- while (1) switch (_context2.p = _context2.n) {
20440
+ return __awaiter(_this3, void 0, void 0, /*#__PURE__*/_regenerator().m(function _callee() {
20441
+ var _t;
20442
+ return _regenerator().w(function (_context) {
20443
+ while (1) switch (_context.p = _context.n) {
19461
20444
  case 0:
19462
- _context2.p = 0;
19463
- _context2.n = 1;
20445
+ _context.p = 0;
20446
+ _context.n = 1;
19464
20447
  return handler(data);
19465
20448
  case 1:
19466
- _context2.n = 3;
20449
+ _context.n = 3;
19467
20450
  break;
19468
20451
  case 2:
19469
- _context2.p = 2;
19470
- _t3 = _context2.v;
19471
- console.warn('Merchant onSuccess handler threw (swallowed):', _t3);
20452
+ _context.p = 2;
20453
+ _t = _context.v;
20454
+ console.warn('Merchant onSuccess handler threw (swallowed):', _t);
19472
20455
  case 3:
19473
- return _context2.a(2);
20456
+ return _context.a(2);
19474
20457
  }
19475
- }, _callee2, null, [[0, 2]]);
20458
+ }, _callee, null, [[0, 2]]);
19476
20459
  }));
19477
20460
  });
19478
20461
  return;
@@ -19503,28 +20486,28 @@ var OpenWalletButtons = /*#__PURE__*/function () {
19503
20486
  }, {
19504
20487
  key: "onUnavailable",
19505
20488
  value: function onUnavailable(handler) {
19506
- var _this3 = this;
20489
+ var _this4 = this;
19507
20490
  if (typeof handler === 'function') {
19508
20491
  this.eventEmitter.subscribe(EVENT$2.UNAVAILABLE, function (data) {
19509
- return __awaiter(_this3, void 0, void 0, /*#__PURE__*/_regenerator().m(function _callee3() {
19510
- var _t4;
19511
- return _regenerator().w(function (_context3) {
19512
- while (1) switch (_context3.p = _context3.n) {
20492
+ return __awaiter(_this4, void 0, void 0, /*#__PURE__*/_regenerator().m(function _callee2() {
20493
+ var _t2;
20494
+ return _regenerator().w(function (_context2) {
20495
+ while (1) switch (_context2.p = _context2.n) {
19513
20496
  case 0:
19514
- _context3.p = 0;
19515
- _context3.n = 1;
20497
+ _context2.p = 0;
20498
+ _context2.n = 1;
19516
20499
  return handler(data);
19517
20500
  case 1:
19518
- _context3.n = 3;
20501
+ _context2.n = 3;
19519
20502
  break;
19520
20503
  case 2:
19521
- _context3.p = 2;
19522
- _t4 = _context3.v;
19523
- console.warn('Merchant onUnavailable handler threw (swallowed):', _t4);
20504
+ _context2.p = 2;
20505
+ _t2 = _context2.v;
20506
+ console.warn('Merchant onUnavailable handler threw (swallowed):', _t2);
19524
20507
  case 3:
19525
- return _context3.a(2);
20508
+ return _context2.a(2);
19526
20509
  }
19527
- }, _callee3, null, [[0, 2]]);
20510
+ }, _callee2, null, [[0, 2]]);
19528
20511
  }));
19529
20512
  });
19530
20513
  return;
@@ -19556,28 +20539,28 @@ var OpenWalletButtons = /*#__PURE__*/function () {
19556
20539
  }, {
19557
20540
  key: "onError",
19558
20541
  value: function onError(handler) {
19559
- var _this4 = this;
20542
+ var _this5 = this;
19560
20543
  if (typeof handler === 'function') {
19561
20544
  this.eventEmitter.subscribe(EVENT$2.ERROR, function (data) {
19562
- return __awaiter(_this4, void 0, void 0, /*#__PURE__*/_regenerator().m(function _callee4() {
19563
- var _t5;
19564
- return _regenerator().w(function (_context4) {
19565
- while (1) switch (_context4.p = _context4.n) {
20545
+ return __awaiter(_this5, void 0, void 0, /*#__PURE__*/_regenerator().m(function _callee3() {
20546
+ var _t3;
20547
+ return _regenerator().w(function (_context3) {
20548
+ while (1) switch (_context3.p = _context3.n) {
19566
20549
  case 0:
19567
- _context4.p = 0;
19568
- _context4.n = 1;
20550
+ _context3.p = 0;
20551
+ _context3.n = 1;
19569
20552
  return handler(data);
19570
20553
  case 1:
19571
- _context4.n = 3;
20554
+ _context3.n = 3;
19572
20555
  break;
19573
20556
  case 2:
19574
- _context4.p = 2;
19575
- _t5 = _context4.v;
19576
- console.warn('Merchant onError handler threw (swallowed):', _t5);
20557
+ _context3.p = 2;
20558
+ _t3 = _context3.v;
20559
+ console.warn('Merchant onError handler threw (swallowed):', _t3);
19577
20560
  case 3:
19578
- return _context4.a(2);
20561
+ return _context3.a(2);
19579
20562
  }
19580
- }, _callee4, null, [[0, 2]]);
20563
+ }, _callee3, null, [[0, 2]]);
19581
20564
  }));
19582
20565
  });
19583
20566
  return;
@@ -19608,28 +20591,28 @@ var OpenWalletButtons = /*#__PURE__*/function () {
19608
20591
  }, {
19609
20592
  key: "onCancel",
19610
20593
  value: function onCancel(handler) {
19611
- var _this5 = this;
20594
+ var _this6 = this;
19612
20595
  if (typeof handler === 'function') {
19613
20596
  this.eventEmitter.subscribe(EVENT$2.CHECKOUT_CLOSE, function (data) {
19614
- return __awaiter(_this5, void 0, void 0, /*#__PURE__*/_regenerator().m(function _callee5() {
19615
- var _t6;
19616
- return _regenerator().w(function (_context5) {
19617
- while (1) switch (_context5.p = _context5.n) {
20597
+ return __awaiter(_this6, void 0, void 0, /*#__PURE__*/_regenerator().m(function _callee4() {
20598
+ var _t4;
20599
+ return _regenerator().w(function (_context4) {
20600
+ while (1) switch (_context4.p = _context4.n) {
19618
20601
  case 0:
19619
- _context5.p = 0;
19620
- _context5.n = 1;
20602
+ _context4.p = 0;
20603
+ _context4.n = 1;
19621
20604
  return handler(data);
19622
20605
  case 1:
19623
- _context5.n = 3;
20606
+ _context4.n = 3;
19624
20607
  break;
19625
20608
  case 2:
19626
- _context5.p = 2;
19627
- _t6 = _context5.v;
19628
- console.warn('Merchant onCancel handler threw (swallowed):', _t6);
20609
+ _context4.p = 2;
20610
+ _t4 = _context4.v;
20611
+ console.warn('Merchant onCancel handler threw (swallowed):', _t4);
19629
20612
  case 3:
19630
- return _context5.a(2);
20613
+ return _context4.a(2);
19631
20614
  }
19632
- }, _callee5, null, [[0, 2]]);
20615
+ }, _callee4, null, [[0, 2]]);
19633
20616
  }));
19634
20617
  });
19635
20618
  return;
@@ -19653,28 +20636,28 @@ var OpenWalletButtons = /*#__PURE__*/function () {
19653
20636
  }, {
19654
20637
  key: "onLoaded",
19655
20638
  value: function onLoaded(handler) {
19656
- var _this6 = this;
20639
+ var _this7 = this;
19657
20640
  if (typeof handler === 'function') {
19658
20641
  this.eventEmitter.subscribe(EVENT$2.LOADED, function (data) {
19659
- return __awaiter(_this6, void 0, void 0, /*#__PURE__*/_regenerator().m(function _callee6() {
19660
- var _t7;
19661
- return _regenerator().w(function (_context6) {
19662
- while (1) switch (_context6.p = _context6.n) {
20642
+ return __awaiter(_this7, void 0, void 0, /*#__PURE__*/_regenerator().m(function _callee5() {
20643
+ var _t5;
20644
+ return _regenerator().w(function (_context5) {
20645
+ while (1) switch (_context5.p = _context5.n) {
19663
20646
  case 0:
19664
- _context6.p = 0;
19665
- _context6.n = 1;
20647
+ _context5.p = 0;
20648
+ _context5.n = 1;
19666
20649
  return handler(data);
19667
20650
  case 1:
19668
- _context6.n = 3;
20651
+ _context5.n = 3;
19669
20652
  break;
19670
20653
  case 2:
19671
- _context6.p = 2;
19672
- _t7 = _context6.v;
19673
- console.warn('Merchant onLoaded handler threw (swallowed):', _t7);
20654
+ _context5.p = 2;
20655
+ _t5 = _context5.v;
20656
+ console.warn('Merchant onLoaded handler threw (swallowed):', _t5);
19674
20657
  case 3:
19675
- return _context6.a(2);
20658
+ return _context5.a(2);
19676
20659
  }
19677
- }, _callee6, null, [[0, 2]]);
20660
+ }, _callee5, null, [[0, 2]]);
19678
20661
  }));
19679
20662
  });
19680
20663
  return;
@@ -20022,7 +21005,143 @@ var WALLET_TYPES;
20022
21005
  WALLET_TYPES["GOOGLE_PAY"] = "google";
20023
21006
  })(WALLET_TYPES || (WALLET_TYPES = {}));
20024
21007
 
20025
- var DEFAULT_APPLE_PAY_CAPABILITIES$1 = ['paymentCredentialsAvailable'];
21008
+ /** CDN location of Apple's web SDK (provides the `<apple-pay-button>` web component). */
21009
+ var APPLE_PAY_SDK_URL = 'https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js';
21010
+ /**
21011
+ * Statuses that count as available when the merchant does not override them.
21012
+ * Includes `paymentCredentialStatusUnknown` so the button is shown in third-party /
21013
+ * cross-device (QR) browsers, per Apple's guidance.
21014
+ */
21015
+ var DEFAULT_APPLE_PAY_CAPABILITIES$1 = ['paymentCredentialsAvailable', 'paymentCredentialStatusUnknown'];
21016
+ /**
21017
+ * Maps the SDK's friendly capability tokens to Apple's `PaymentCredentialStatus` values.
21018
+ * Unknown tokens are passed through unchanged.
21019
+ */
21020
+ function formatCapabilities(capabilities) {
21021
+ var fieldMap = {
21022
+ credentials_available: 'paymentCredentialsAvailable',
21023
+ credentials_status_unknown: 'paymentCredentialStatusUnknown',
21024
+ credentials_unavailable: 'paymentCredentialsUnavailable'
21025
+ };
21026
+ return capabilities.map(function (capability) {
21027
+ return fieldMap[capability] || capability;
21028
+ });
21029
+ }
21030
+ /**
21031
+ * Synchronous, network-free check for a **native, same-device** Apple Pay session
21032
+ * (`window.ApplePaySession` exists and `canMakePayments()` is `true`). Safe to call in
21033
+ * any environment (never throws).
21034
+ *
21035
+ * Note: this is a legacy/Safari-oriented signal. It is **not** authoritative for
21036
+ * cross-browser / cross-device (QR) availability — in Chrome/Edge/Firefox
21037
+ * `window.ApplePaySession` is supplied by the CDN SDK and may be absent until it loads,
21038
+ * and the cross-device flow is reflected by `applePayCapabilities()`, not this call.
21039
+ * Use {@link evaluateApplePayAvailability} for the authoritative, cross-browser answer.
21040
+ */
21041
+ function hasNativeApplePaySession() {
21042
+ try {
21043
+ return typeof window !== 'undefined' && !!window.ApplePaySession && typeof ApplePaySession !== 'undefined' && ApplePaySession.canMakePayments();
21044
+ } catch (_a) {
21045
+ return false;
21046
+ }
21047
+ }
21048
+ var sdkLoadPromise = null;
21049
+ /**
21050
+ * Idempotently loads Apple's web SDK from the CDN.
21051
+ * Resolves immediately if the `<apple-pay-button>` custom element is already
21052
+ * registered, and de-duplicates concurrent loads. Rejects if the script fails to load.
21053
+ */
21054
+ function loadApplePaySdk() {
21055
+ if (typeof customElements !== 'undefined' && customElements.get('apple-pay-button')) {
21056
+ return Promise.resolve();
21057
+ }
21058
+ if (sdkLoadPromise) {
21059
+ return sdkLoadPromise;
21060
+ }
21061
+ sdkLoadPromise = new Promise(function (resolve, reject) {
21062
+ var script = document.createElement('script');
21063
+ script.src = APPLE_PAY_SDK_URL;
21064
+ script.type = 'text/javascript';
21065
+ script.crossOrigin = 'anonymous';
21066
+ script.onload = function () {
21067
+ return resolve();
21068
+ };
21069
+ script.onerror = function () {
21070
+ // Allow a future retry after a transient failure.
21071
+ sdkLoadPromise = null;
21072
+ reject(new Error('Failed to load Apple Pay script'));
21073
+ };
21074
+ document.head.appendChild(script);
21075
+ });
21076
+ return sdkLoadPromise;
21077
+ }
21078
+ /**
21079
+ * Core Apple Pay availability evaluation, shared by the instance flow
21080
+ * (`ApplePayOpenWalletService`) and the static `ApplePayOpenWalletButton.checkAvailability`.
21081
+ *
21082
+ * Assumes the Apple Pay SDK is already loaded (call {@link loadApplePaySdk} first).
21083
+ */
21084
+ function evaluateApplePayAvailability(params) {
21085
+ return __awaiter(this, void 0, void 0, /*#__PURE__*/_regenerator().m(function _callee() {
21086
+ var _a, hasNativeSession, allowed, capabilities, paymentCredentialStatus, available;
21087
+ return _regenerator().w(function (_context) {
21088
+ while (1) switch (_context.p = _context.n) {
21089
+ case 0:
21090
+ if (!(typeof window === 'undefined' || !window.ApplePaySession)) {
21091
+ _context.n = 1;
21092
+ break;
21093
+ }
21094
+ return _context.a(2, {
21095
+ available: false,
21096
+ supported: false,
21097
+ has_native_session: false,
21098
+ reason: 'unsupported_browser'
21099
+ });
21100
+ case 1:
21101
+ hasNativeSession = hasNativeApplePaySession();
21102
+ allowed = ((_a = params.apple_pay_capabilities) === null || _a === void 0 ? void 0 : _a.length) ? formatCapabilities(params.apple_pay_capabilities) : DEFAULT_APPLE_PAY_CAPABILITIES$1;
21103
+ _context.p = 2;
21104
+ _context.n = 3;
21105
+ return ApplePaySession.applePayCapabilities(params.merchantId);
21106
+ case 3:
21107
+ capabilities = _context.v;
21108
+ paymentCredentialStatus = capabilities === null || capabilities === void 0 ? void 0 : capabilities.paymentCredentialStatus; // `applePayCapabilities` is authoritative: trust an explicit `applePayUnsupported`
21109
+ // (e.g. an unregistered/misconfigured merchant) rather than overriding it with the
21110
+ // coarse `canMakePayments()` signal.
21111
+ if (!(paymentCredentialStatus === 'applePayUnsupported')) {
21112
+ _context.n = 4;
21113
+ break;
21114
+ }
21115
+ return _context.a(2, {
21116
+ available: false,
21117
+ supported: false,
21118
+ has_native_session: hasNativeSession,
21119
+ payment_credential_status: paymentCredentialStatus,
21120
+ reason: 'unsupported_browser'
21121
+ });
21122
+ case 4:
21123
+ available = allowed.includes(paymentCredentialStatus);
21124
+ return _context.a(2, {
21125
+ available: available,
21126
+ supported: true,
21127
+ has_native_session: hasNativeSession,
21128
+ payment_credential_status: paymentCredentialStatus,
21129
+ reason: available ? undefined : 'no_credentials'
21130
+ });
21131
+ case 5:
21132
+ _context.p = 5;
21133
+ _context.v;
21134
+ return _context.a(2, {
21135
+ available: false,
21136
+ supported: hasNativeSession,
21137
+ has_native_session: hasNativeSession,
21138
+ reason: 'query_failed'
21139
+ });
21140
+ }
21141
+ }, _callee, null, [[2, 5]]);
21142
+ }));
21143
+ }
21144
+
20026
21145
  /**
20027
21146
  * Apple Pay implementation of the OpenWallet service.
20028
21147
  *
@@ -20298,7 +21417,6 @@ var ApplePayOpenWalletService = /*#__PURE__*/function (_OpenWalletService) {
20298
21417
  value: function load() {
20299
21418
  return __awaiter(this, void 0, void 0, /*#__PURE__*/_regenerator().m(function _callee3() {
20300
21419
  var _this4 = this;
20301
- var applePayScript;
20302
21420
  return _regenerator().w(function (_context3) {
20303
21421
  while (1) switch (_context3.n) {
20304
21422
  case 0:
@@ -20309,26 +21427,12 @@ var ApplePayOpenWalletService = /*#__PURE__*/function (_OpenWalletService) {
20309
21427
  this.handleOnUnavailable('Promises not supported');
20310
21428
  return _context3.a(2);
20311
21429
  case 1:
20312
- if (!(customElements === null || customElements === void 0 ? void 0 : customElements.get('apple-pay-button'))) {
20313
- _context3.n = 2;
20314
- break;
20315
- }
20316
- this.onScriptLoaded();
20317
- return _context3.a(2);
20318
- case 2:
20319
- applePayScript = document.createElement('script');
20320
- applePayScript.src = 'https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js';
20321
- applePayScript.type = 'text/javascript';
20322
- applePayScript.crossOrigin = 'anonymous';
20323
- applePayScript.onload = function () {
21430
+ loadApplePaySdk().then(function () {
20324
21431
  _this4.onScriptLoaded();
20325
- };
20326
- applePayScript.onerror = function () {
21432
+ })["catch"](function () {
20327
21433
  _this4.handleOnUnavailable('Failed to load Apple Pay script');
20328
- return;
20329
- };
20330
- document.head.appendChild(applePayScript);
20331
- case 3:
21434
+ });
21435
+ case 2:
20332
21436
  return _context3.a(2);
20333
21437
  }
20334
21438
  }, _callee3, this);
@@ -20356,26 +21460,22 @@ var ApplePayOpenWalletService = /*#__PURE__*/function (_OpenWalletService) {
20356
21460
  }, {
20357
21461
  key: "checkAvailability",
20358
21462
  value: function checkAvailability() {
20359
- var _this6 = this;
20360
- return new Promise(function (resolve) {
20361
- var _a;
20362
- if (!window.ApplePaySession || !ApplePaySession) {
20363
- return resolve(false);
20364
- }
20365
- var formattedCapabilities = DEFAULT_APPLE_PAY_CAPABILITIES$1;
20366
- if (((_a = _this6.meta.apple_pay_capabilities) === null || _a === void 0 ? void 0 : _a.length) > 0) {
20367
- formattedCapabilities = _this6.formatCapabilities(_this6.meta.apple_pay_capabilities);
20368
- }
20369
- ApplePaySession.applePayCapabilities(_this6.getMerchantId()).then(function (capabilities) {
20370
- if (_this6.isUnsuportedBrowser(capabilities)) {
20371
- return resolve(ApplePaySession.canMakePayments());
21463
+ return __awaiter(this, void 0, void 0, /*#__PURE__*/_regenerator().m(function _callee4() {
21464
+ var result;
21465
+ return _regenerator().w(function (_context4) {
21466
+ while (1) switch (_context4.n) {
21467
+ case 0:
21468
+ _context4.n = 1;
21469
+ return evaluateApplePayAvailability({
21470
+ merchantId: this.getMerchantId(),
21471
+ apple_pay_capabilities: this.meta.apple_pay_capabilities
21472
+ });
21473
+ case 1:
21474
+ result = _context4.v;
21475
+ return _context4.a(2, result.available);
20372
21476
  }
20373
- var allowedCapability = formattedCapabilities.includes(capabilities === null || capabilities === void 0 ? void 0 : capabilities.paymentCredentialStatus);
20374
- return resolve(allowedCapability);
20375
- })["catch"](function () {
20376
- resolve(false);
20377
- });
20378
- });
21477
+ }, _callee4, this);
21478
+ }));
20379
21479
  }
20380
21480
  }, {
20381
21481
  key: "mount",
@@ -20401,7 +21501,7 @@ var ApplePayOpenWalletService = /*#__PURE__*/function (_OpenWalletService) {
20401
21501
  }, {
20402
21502
  key: "onApplePayButtonClicked",
20403
21503
  value: function onApplePayButtonClicked() {
20404
- var _this7 = this;
21504
+ var _this6 = this;
20405
21505
  if (this.isButtonDisabled()) {
20406
21506
  return;
20407
21507
  }
@@ -20420,26 +21520,27 @@ var ApplePayOpenWalletService = /*#__PURE__*/function (_OpenWalletService) {
20420
21520
  // As part of PAYCA-2065 we detect that the paymentSession.onvalidatemerchant is not
20421
21521
  // executed if the browser is not safari. In that case, we handle it outside the
20422
21522
  // actual merchant validation function.
20423
- var isIOS = /iPhone|iPad|iPod/.test(navigator.userAgent);
20424
- var isDesktopRequestIOS = navigator.maxTouchPoints > 1 && /Macintosh/.test(navigator.userAgent);
21523
+ var userAgent = navigator.userAgent || '';
21524
+ var isIOS = userAgent.includes('iPhone') || userAgent.includes('iPad') || userAgent.includes('iPod');
21525
+ var isDesktopRequestIOS = navigator.maxTouchPoints > 1 && userAgent.includes('Macintosh');
20425
21526
  if (!window.safari && !isIOS && !isDesktopRequestIOS) {
20426
21527
  this.handleMerchantOnButtonClickEvent()["catch"](function (err) {
20427
21528
  console.error('Error while processing merchant callback', err);
20428
- _this7.paymentSession.abort();
21529
+ _this6.paymentSession.abort();
20429
21530
  });
20430
21531
  }
20431
21532
  }
20432
21533
  }, {
20433
21534
  key: "getMerchantSession",
20434
21535
  value: function getMerchantSession() {
20435
- var _this8 = this;
21536
+ var _this7 = this;
20436
21537
  return new Promise(function (resolve, reject) {
20437
- return _this8.api.paymentSource().createSession(_extends({
20438
- service_id: _this8.serviceId,
21538
+ return _this7.api.paymentSource().createSession(_extends({
21539
+ service_id: _this7.serviceId,
20439
21540
  session_id: window.location.hostname,
20440
- store_name: _this8.meta.store_name
20441
- }, _this8.isShippingRequired() && {
20442
- request_shipping: _this8.meta.request_shipping
21541
+ store_name: _this7.meta.store_name
21542
+ }, _this7.isShippingRequired() && {
21543
+ request_shipping: _this7.meta.request_shipping
20443
21544
  })).then(function (res) {
20444
21545
  resolve(res);
20445
21546
  })["catch"](function (err) {
@@ -20450,42 +21551,30 @@ var ApplePayOpenWalletService = /*#__PURE__*/function (_OpenWalletService) {
20450
21551
  }, {
20451
21552
  key: "handleMerchantOnButtonClickEvent",
20452
21553
  value: function handleMerchantOnButtonClickEvent() {
20453
- return __awaiter(this, void 0, void 0, /*#__PURE__*/_regenerator().m(function _callee4() {
21554
+ return __awaiter(this, void 0, void 0, /*#__PURE__*/_regenerator().m(function _callee5() {
20454
21555
  var results;
20455
- return _regenerator().w(function (_context4) {
20456
- while (1) switch (_context4.n) {
21556
+ return _regenerator().w(function (_context5) {
21557
+ while (1) switch (_context5.n) {
20457
21558
  case 0:
20458
- _context4.n = 1;
21559
+ _context5.n = 1;
20459
21560
  return this.eventEmitter.emitWithResult(EVENT$2.ON_CLICK, {
20460
21561
  event: EVENT$2.ON_CLICK
20461
21562
  });
20462
21563
  case 1:
20463
- results = _context4.v;
21564
+ results = _context5.v;
20464
21565
  if (!results.some(function (r) {
20465
21566
  return r === false;
20466
21567
  })) {
20467
- _context4.n = 2;
21568
+ _context5.n = 2;
20468
21569
  break;
20469
21570
  }
20470
21571
  throw new Error('onClick handler aborted the payment flow');
20471
21572
  case 2:
20472
- return _context4.a(2);
21573
+ return _context5.a(2);
20473
21574
  }
20474
- }, _callee4, this);
21575
+ }, _callee5, this);
20475
21576
  }));
20476
21577
  }
20477
- }, {
20478
- key: "formatCapabilities",
20479
- value: function formatCapabilities(capabilities) {
20480
- var fieldMap = {
20481
- credentials_available: 'paymentCredentialsAvailable',
20482
- credentials_status_unknown: 'paymentCredentialStatusUnknown',
20483
- credentials_unavailable: 'paymentCredentialsUnavailable'
20484
- };
20485
- return capabilities.map(function (capability) {
20486
- return fieldMap[capability] || capability;
20487
- });
20488
- }
20489
21578
  }, {
20490
21579
  key: "formatErrorFields",
20491
21580
  value: function formatErrorFields(error) {
@@ -20652,11 +21741,6 @@ var ApplePayOpenWalletService = /*#__PURE__*/function (_OpenWalletService) {
20652
21741
  applePayLaterAvailability: this.meta.apple_pay_later_availability
20653
21742
  });
20654
21743
  }
20655
- }, {
20656
- key: "isUnsuportedBrowser",
20657
- value: function isUnsuportedBrowser(capabilities) {
20658
- return (capabilities === null || capabilities === void 0 ? void 0 : capabilities.paymentCredentialStatus) === 'applePayUnsupported';
20659
- }
20660
21744
  }]);
20661
21745
  }(OpenWalletService);
20662
21746
 
@@ -20705,17 +21789,57 @@ var ApplePayOpenWalletButton = /*#__PURE__*/function (_OpenWalletButtons) {
20705
21789
  return _this;
20706
21790
  }
20707
21791
  /**
20708
- * Validates Apple Pay-specific required metadata fields.
20709
- * Apple Pay requires `amount_label` and `store_name` to be present and strings.
21792
+ * Checks Apple Pay availability **without instantiating the button** — the single,
21793
+ * authoritative, cross-browser-aware availability entry point.
20710
21794
  *
20711
- * @private
20712
- * @throws {Error} If `amount_label` is missing or not a string.
20713
- * @throws {Error} If `store_name` is missing or not a string.
21795
+ * Resolves the merchant identifier (either supplied directly or fetched from the
21796
+ * service configuration), loads Apple's web SDK if needed, then queries
21797
+ * `ApplePaySession.applePayCapabilities()`. Returns a convenience `available` verdict
21798
+ * (computed against `apple_pay_capabilities`), the raw device-reported
21799
+ * `payment_credential_status`, and `has_native_session` so callers can infer the transport:
21800
+ * `available && has_native_session` ⇒ native sheet likely; `available && !has_native_session`
21801
+ * ⇒ cross-device / QR handoff likely.
21802
+ *
21803
+ * Pass `{ sync: true }` for a cheap, network-free native same-device pre-check that
21804
+ * resolves immediately (see {@link ApplePayAvailabilityOptions.sync}).
21805
+ *
21806
+ * @param {ApplePayAvailabilityOptions} [options] - Merchant context, allowed capabilities, and mode.
21807
+ * @returns {Promise<ApplePayAvailabilityResult>} The availability result.
21808
+ *
21809
+ * @example
21810
+ * // Lightest path — no network, when you already know the merchant identifier:
21811
+ * const result = await ApplePayOpenWalletButton.checkAvailability({ merchant_id });
21812
+ *
21813
+ * @example
21814
+ * // Resolve the merchant identifier from the service configuration:
21815
+ * const result = await ApplePayOpenWalletButton.checkAvailability({
21816
+ * public_key_or_access_token,
21817
+ * service_id,
21818
+ * env: 'sandbox',
21819
+ * });
21820
+ * if (result.available) {
21821
+ * // Render the Apple Pay button (native sheet or cross-device QR, per has_native_session).
21822
+ * } else {
21823
+ * console.log('Unavailable:', result.reason, result.payment_credential_status);
21824
+ * }
21825
+ *
21826
+ * @example
21827
+ * // Synchronous native-only fast check (no network / SDK load):
21828
+ * const { has_native_session } = await ApplePayOpenWalletButton.checkAvailability({ sync: true });
20714
21829
  */
20715
21830
  _inherits(ApplePayOpenWalletButton, _OpenWalletButtons);
20716
21831
  return _createClass(ApplePayOpenWalletButton, [{
20717
21832
  key: "validateWalletMeta",
20718
- value: function validateWalletMeta() {
21833
+ value:
21834
+ /**
21835
+ * Validates Apple Pay-specific required metadata fields.
21836
+ * Apple Pay requires `amount_label` and `store_name` to be present and strings.
21837
+ *
21838
+ * @private
21839
+ * @throws {Error} If `amount_label` is missing or not a string.
21840
+ * @throws {Error} If `store_name` is missing or not a string.
21841
+ */
21842
+ function validateWalletMeta() {
20719
21843
  if (typeof this.meta.amount_label !== 'string' || this.meta.amount_label.trim() === '') {
20720
21844
  throw new Error("meta.amount_label is required for Apple Pay and must be a non-empty string (e.g. 'TOTAL').");
20721
21845
  }
@@ -20749,6 +21873,114 @@ var ApplePayOpenWalletButton = /*#__PURE__*/function (_OpenWalletButtons) {
20749
21873
  value: function createWalletService(serviceConfig) {
20750
21874
  return new ApplePayOpenWalletService(this.api, this.eventEmitter, this.serviceId, this.container, this.meta, serviceConfig);
20751
21875
  }
21876
+ }], [{
21877
+ key: "checkAvailability",
21878
+ value: function checkAvailability() {
21879
+ return __awaiter(this, arguments, void 0, function () {
21880
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
21881
+ return /*#__PURE__*/_regenerator().m(function _callee() {
21882
+ var hasNativeSession, merchantId, authType, api, serviceConfig;
21883
+ return _regenerator().w(function (_context) {
21884
+ while (1) switch (_context.p = _context.n) {
21885
+ case 0:
21886
+ hasNativeSession = hasNativeApplePaySession();
21887
+ if (!options.sync) {
21888
+ _context.n = 1;
21889
+ break;
21890
+ }
21891
+ return _context.a(2, {
21892
+ available: hasNativeSession,
21893
+ supported: hasNativeSession,
21894
+ has_native_session: hasNativeSession,
21895
+ reason: hasNativeSession ? undefined : 'no_native_session'
21896
+ });
21897
+ case 1:
21898
+ merchantId = options.merchant_id;
21899
+ if (merchantId) {
21900
+ _context.n = 6;
21901
+ break;
21902
+ }
21903
+ if (!(!options.public_key_or_access_token || !options.service_id)) {
21904
+ _context.n = 2;
21905
+ break;
21906
+ }
21907
+ return _context.a(2, {
21908
+ available: false,
21909
+ supported: hasNativeSession,
21910
+ has_native_session: hasNativeSession,
21911
+ reason: 'missing_merchant_id'
21912
+ });
21913
+ case 2:
21914
+ _context.p = 2;
21915
+ authType = AccessToken.validateJWT(options.public_key_or_access_token) ? API_AUTH_TYPE.TOKEN : API_AUTH_TYPE.PUBLIC_KEY;
21916
+ api = new ApiInternal(options.public_key_or_access_token, authType);
21917
+ if (options.env) {
21918
+ api.setEnv(options.env);
21919
+ }
21920
+ _context.n = 3;
21921
+ return getServiceConfigCached(api, options.service_id);
21922
+ case 3:
21923
+ serviceConfig = _context.v;
21924
+ if (!(serviceConfig.type !== SERVICE_TYPES.APPLE_PAY)) {
21925
+ _context.n = 4;
21926
+ break;
21927
+ }
21928
+ return _context.a(2, {
21929
+ available: false,
21930
+ supported: hasNativeSession,
21931
+ has_native_session: hasNativeSession,
21932
+ reason: 'service_type_mismatch'
21933
+ });
21934
+ case 4:
21935
+ merchantId = serviceConfig.merchant;
21936
+ _context.n = 6;
21937
+ break;
21938
+ case 5:
21939
+ _context.p = 5;
21940
+ _context.v;
21941
+ return _context.a(2, {
21942
+ available: false,
21943
+ supported: hasNativeSession,
21944
+ has_native_session: hasNativeSession,
21945
+ reason: 'config_fetch_failed'
21946
+ });
21947
+ case 6:
21948
+ if (merchantId) {
21949
+ _context.n = 7;
21950
+ break;
21951
+ }
21952
+ return _context.a(2, {
21953
+ available: false,
21954
+ supported: hasNativeSession,
21955
+ has_native_session: hasNativeSession,
21956
+ reason: 'missing_merchant_id'
21957
+ });
21958
+ case 7:
21959
+ _context.p = 7;
21960
+ _context.n = 8;
21961
+ return loadApplePaySdk();
21962
+ case 8:
21963
+ _context.n = 10;
21964
+ break;
21965
+ case 9:
21966
+ _context.p = 9;
21967
+ _context.v;
21968
+ return _context.a(2, {
21969
+ available: false,
21970
+ supported: hasNativeSession,
21971
+ has_native_session: hasNativeSession,
21972
+ reason: 'sdk_load_failed'
21973
+ });
21974
+ case 10:
21975
+ return _context.a(2, evaluateApplePayAvailability({
21976
+ merchantId: merchantId,
21977
+ apple_pay_capabilities: options.apple_pay_capabilities
21978
+ }));
21979
+ }
21980
+ }, _callee, null, [[7, 9], [2, 5]]);
21981
+ })();
21982
+ });
21983
+ }
20752
21984
  }]);
20753
21985
  }(OpenWalletButtons);
20754
21986
 
@@ -20785,6 +22017,137 @@ var GOOGLE_PAY_CARD_NETWORKS = ['AMEX', 'DISCOVER', 'INTERAC', 'JCB', 'MASTERCAR
20785
22017
  SHIPPING_OPTION: EVENT$2.ON_SHIPPING_OPTIONS_CHANGE
20786
22018
  });
20787
22019
 
22020
+ /**
22021
+ * Synchronous, network-free check for whether the Google Pay JS API is already present
22022
+ * in the page (`window.google.payments.api.PaymentsClient`). Safe to call in any
22023
+ * environment (never throws).
22024
+ *
22025
+ * Note: Google Pay has no synchronous device/card capability API — this only reports
22026
+ * whether the SDK script has loaded. The authoritative readiness signal comes from
22027
+ * {@link evaluateGooglePayAvailability} (which runs `isReadyToPay`).
22028
+ */
22029
+ function isGooglePayApiPresent() {
22030
+ var _a, _b, _c;
22031
+ try {
22032
+ return typeof window !== 'undefined' && !!((_c = (_b = (_a = window.google) === null || _a === void 0 ? void 0 : _a.payments) === null || _b === void 0 ? void 0 : _b.api) === null || _c === void 0 ? void 0 : _c.PaymentsClient);
22033
+ } catch (_d) {
22034
+ return false;
22035
+ }
22036
+ }
22037
+ var scriptLoadPromise = null;
22038
+ /**
22039
+ * Idempotently loads the Google Pay JS SDK from the CDN.
22040
+ * Resolves immediately if the API is already present, de-duplicates concurrent loads,
22041
+ * and rejects if the script fails to load.
22042
+ */
22043
+ function loadGooglePayScript() {
22044
+ if (isGooglePayApiPresent()) {
22045
+ return Promise.resolve();
22046
+ }
22047
+ if (scriptLoadPromise) {
22048
+ return scriptLoadPromise;
22049
+ }
22050
+ scriptLoadPromise = new Promise(function (resolve, reject) {
22051
+ var script = document.createElement('script');
22052
+ script.type = 'text/javascript';
22053
+ script.src = GOOGLE_PAY_SCRIPT_URL;
22054
+ script.async = true;
22055
+ script.onload = function () {
22056
+ if (!isGooglePayApiPresent()) {
22057
+ scriptLoadPromise = null;
22058
+ reject(new Error('Google Pay not available'));
22059
+ return;
22060
+ }
22061
+ resolve();
22062
+ };
22063
+ script.onerror = function () {
22064
+ // Allow a future retry after a transient failure.
22065
+ scriptLoadPromise = null;
22066
+ reject(new Error('Failed to load Google Pay script'));
22067
+ };
22068
+ document.head.appendChild(script);
22069
+ });
22070
+ return scriptLoadPromise;
22071
+ }
22072
+ /**
22073
+ * Builds the base `isReadyToPay` request using the default card configuration
22074
+ * (standard auth methods + card networks). Mirrors the instance service's request:
22075
+ * `existingPaymentMethodRequired` is `false` on Safari (where Google Pay surfaces a
22076
+ * different flow) and `true` elsewhere.
22077
+ */
22078
+ function buildIsReadyToPayRequest() {
22079
+ var isSafariBrowser = Browser.getBrowserName() === 'Apple Safari';
22080
+ return _extends(_extends({}, GOOGLE_PAY_API_CONFIG), {
22081
+ allowedPaymentMethods: [{
22082
+ type: 'CARD',
22083
+ parameters: {
22084
+ allowedAuthMethods: GOOGLE_PAY_AUTH_METHODS,
22085
+ allowedCardNetworks: GOOGLE_PAY_CARD_NETWORKS
22086
+ }
22087
+ }],
22088
+ existingPaymentMethodRequired: !isSafariBrowser
22089
+ });
22090
+ }
22091
+ /**
22092
+ * Core Google Pay availability evaluation, shared by the instance flow
22093
+ * (`GooglePayOpenWalletService`) and the static `GooglePayOpenWalletButton.checkAvailability`.
22094
+ *
22095
+ * The static check passes no `request`, so it uses the **default** card configuration
22096
+ * (a button instance with a custom `card_config` may produce a different result). The
22097
+ * instance flow passes its own `paymentsClient` and `request` so the readiness check
22098
+ * honours the merchant's `card_config` and runs against the same client it pays with.
22099
+ *
22100
+ * Assumes the Google Pay SDK is already loaded (call {@link loadGooglePayScript} first).
22101
+ */
22102
+ function evaluateGooglePayAvailability() {
22103
+ return __awaiter(this, arguments, void 0, function () {
22104
+ var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
22105
+ return /*#__PURE__*/_regenerator().m(function _callee() {
22106
+ var _a, _b, paymentsClient, response, available;
22107
+ return _regenerator().w(function (_context) {
22108
+ while (1) switch (_context.p = _context.n) {
22109
+ case 0:
22110
+ if (isGooglePayApiPresent()) {
22111
+ _context.n = 1;
22112
+ break;
22113
+ }
22114
+ return _context.a(2, {
22115
+ available: false,
22116
+ supported: false,
22117
+ reason: 'unsupported_browser'
22118
+ });
22119
+ case 1:
22120
+ _context.p = 1;
22121
+ paymentsClient = (_a = params.paymentsClient) !== null && _a !== void 0 ? _a : new google.payments.api.PaymentsClient({
22122
+ merchantInfo: {
22123
+ merchantId: params.merchantId || ''
22124
+ }
22125
+ });
22126
+ _context.n = 2;
22127
+ return paymentsClient.isReadyToPay((_b = params.request) !== null && _b !== void 0 ? _b : buildIsReadyToPayRequest());
22128
+ case 2:
22129
+ response = _context.v;
22130
+ available = !!response.result;
22131
+ return _context.a(2, {
22132
+ available: available,
22133
+ supported: true,
22134
+ payment_method_present: response.paymentMethodPresent,
22135
+ reason: available ? undefined : 'no_payment_method'
22136
+ });
22137
+ case 3:
22138
+ _context.p = 3;
22139
+ _context.v;
22140
+ return _context.a(2, {
22141
+ available: false,
22142
+ supported: isGooglePayApiPresent(),
22143
+ reason: 'query_failed'
22144
+ });
22145
+ }
22146
+ }, _callee, null, [[1, 3]]);
22147
+ })();
22148
+ });
22149
+ }
22150
+
20788
22151
  /**
20789
22152
  * Parses intermediate payment data from Google Pay into a normalized format
20790
22153
  * for use in shipping address/option change events.
@@ -21120,14 +22483,18 @@ var GooglePayOpenWalletService = /*#__PURE__*/function (_OpenWalletService) {
21120
22483
  key: "checkAvailability",
21121
22484
  value: function checkAvailability() {
21122
22485
  return __awaiter(this, void 0, void 0, /*#__PURE__*/_regenerator().m(function _callee2() {
22486
+ var result;
21123
22487
  return _regenerator().w(function (_context2) {
21124
22488
  while (1) switch (_context2.n) {
21125
22489
  case 0:
21126
- return _context2.a(2, this.paymentsClient.isReadyToPay(this.createRequest()).then(function (response) {
21127
- return !!response.result;
21128
- })["catch"](function () {
21129
- return false;
21130
- }));
22490
+ _context2.n = 1;
22491
+ return evaluateGooglePayAvailability({
22492
+ paymentsClient: this.paymentsClient,
22493
+ request: this.createRequest()
22494
+ });
22495
+ case 1:
22496
+ result = _context2.v;
22497
+ return _context2.a(2, result.available);
21131
22498
  }
21132
22499
  }, _callee2, this);
21133
22500
  }));
@@ -21585,14 +22952,46 @@ var GooglePayOpenWalletButton = /*#__PURE__*/function (_OpenWalletButtons) {
21585
22952
  return _this;
21586
22953
  }
21587
22954
  /**
21588
- * Validates Google Pay-specific required metadata fields.
21589
- * Google Pay has no additional required fields beyond the base (amount, currency, country).
21590
- * @private
22955
+ * Checks Google Pay availability **without instantiating the button** — the static
22956
+ * availability entry point.
22957
+ *
22958
+ * Loads the Google Pay JS SDK if needed, then runs `PaymentsClient.isReadyToPay()` using
22959
+ * the **default** card configuration (a button instance with a custom `card_config` may
22960
+ * produce a different result). All options are optional — unlike Apple Pay, Google Pay's
22961
+ * readiness check does not require a merchant identifier; supplying `service_id` +
22962
+ * `public_key_or_access_token` additionally validates that the service is a Google Pay service.
22963
+ *
22964
+ * Pass `{ sync: true }` for a cheap, network-free check that only reports whether the
22965
+ * Google Pay JS API is already present (see {@link GooglePayAvailabilityOptions.sync}).
22966
+ *
22967
+ * @param {GooglePayAvailabilityOptions} [options] - Optional merchant context and mode.
22968
+ * @returns {Promise<GooglePayAvailabilityResult>} The availability result.
22969
+ *
22970
+ * @example
22971
+ * // Simplest form — no merchant context needed:
22972
+ * const result = await GooglePayOpenWalletButton.checkAvailability();
22973
+ * if (result.available) {
22974
+ * // Render the Google Pay button.
22975
+ * }
22976
+ *
22977
+ * @example
22978
+ * // Validate the service is a Google Pay service while checking:
22979
+ * const result = await GooglePayOpenWalletButton.checkAvailability({
22980
+ * public_key_or_access_token,
22981
+ * service_id,
22982
+ * env: 'sandbox',
22983
+ * });
21591
22984
  */
21592
22985
  _inherits(GooglePayOpenWalletButton, _OpenWalletButtons);
21593
22986
  return _createClass(GooglePayOpenWalletButton, [{
21594
22987
  key: "validateWalletMeta",
21595
- value: function validateWalletMeta() {
22988
+ value:
22989
+ /**
22990
+ * Validates Google Pay-specific required metadata fields.
22991
+ * Google Pay has no additional required fields beyond the base (amount, currency, country).
22992
+ * @private
22993
+ */
22994
+ function validateWalletMeta() {
21596
22995
  // Google Pay has no additional required meta fields beyond the base.
21597
22996
  // Optional fields (merchant_name, card_config, etc.) are validated
21598
22997
  // at runtime by the Google Pay SDK.
@@ -21623,6 +23022,87 @@ var GooglePayOpenWalletButton = /*#__PURE__*/function (_OpenWalletButtons) {
21623
23022
  value: function createWalletService(serviceConfig) {
21624
23023
  return new GooglePayOpenWalletService(this.api, this.eventEmitter, this.serviceId, this.container, this.meta, serviceConfig);
21625
23024
  }
23025
+ }], [{
23026
+ key: "checkAvailability",
23027
+ value: function checkAvailability() {
23028
+ return __awaiter(this, arguments, void 0, function () {
23029
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
23030
+ return /*#__PURE__*/_regenerator().m(function _callee() {
23031
+ var present, merchantId, authType, api, serviceConfig;
23032
+ return _regenerator().w(function (_context) {
23033
+ while (1) switch (_context.p = _context.n) {
23034
+ case 0:
23035
+ if (!options.sync) {
23036
+ _context.n = 1;
23037
+ break;
23038
+ }
23039
+ present = isGooglePayApiPresent();
23040
+ return _context.a(2, {
23041
+ available: present,
23042
+ supported: present,
23043
+ reason: present ? undefined : 'api_not_loaded'
23044
+ });
23045
+ case 1:
23046
+ merchantId = options.merchant_id;
23047
+ if (!(!merchantId && options.public_key_or_access_token && options.service_id)) {
23048
+ _context.n = 6;
23049
+ break;
23050
+ }
23051
+ _context.p = 2;
23052
+ authType = AccessToken.validateJWT(options.public_key_or_access_token) ? API_AUTH_TYPE.TOKEN : API_AUTH_TYPE.PUBLIC_KEY;
23053
+ api = new ApiInternal(options.public_key_or_access_token, authType);
23054
+ if (options.env) {
23055
+ api.setEnv(options.env);
23056
+ }
23057
+ _context.n = 3;
23058
+ return getServiceConfigCached(api, options.service_id);
23059
+ case 3:
23060
+ serviceConfig = _context.v;
23061
+ if (!(serviceConfig.type !== SERVICE_TYPES.GOOGLE_PAY)) {
23062
+ _context.n = 4;
23063
+ break;
23064
+ }
23065
+ return _context.a(2, {
23066
+ available: false,
23067
+ supported: isGooglePayApiPresent(),
23068
+ reason: 'service_type_mismatch'
23069
+ });
23070
+ case 4:
23071
+ merchantId = serviceConfig.merchant;
23072
+ _context.n = 6;
23073
+ break;
23074
+ case 5:
23075
+ _context.p = 5;
23076
+ _context.v;
23077
+ return _context.a(2, {
23078
+ available: false,
23079
+ supported: isGooglePayApiPresent(),
23080
+ reason: 'config_fetch_failed'
23081
+ });
23082
+ case 6:
23083
+ _context.p = 6;
23084
+ _context.n = 7;
23085
+ return loadGooglePayScript();
23086
+ case 7:
23087
+ _context.n = 9;
23088
+ break;
23089
+ case 8:
23090
+ _context.p = 8;
23091
+ _context.v;
23092
+ return _context.a(2, {
23093
+ available: false,
23094
+ supported: isGooglePayApiPresent(),
23095
+ reason: 'sdk_load_failed'
23096
+ });
23097
+ case 9:
23098
+ return _context.a(2, evaluateGooglePayAvailability({
23099
+ merchantId: merchantId
23100
+ }));
23101
+ }
23102
+ }, _callee, null, [[6, 8], [2, 5]]);
23103
+ })();
23104
+ });
23105
+ }
21626
23106
  }]);
21627
23107
  }(OpenWalletButtons);
21628
23108
 
@@ -22895,6 +24375,14 @@ var SRC = /*#__PURE__*/function () {
22895
24375
  if (_this.provider) {
22896
24376
  _this.provider.load();
22897
24377
  }
24378
+ })["catch"](function (error) {
24379
+ var _a;
24380
+ // Surface config-load failures (including transport-level ones now
24381
+ // rejected by ApiBase) instead of leaving the widget hung silently.
24382
+ _this.eventEmitter.emit(EVENT$1.CHECKOUT_ERROR, {
24383
+ type: EVENT_DATA_TYPE.CRITICAL_ERROR,
24384
+ data: (_a = error === null || error === void 0 ? void 0 : error.message) !== null && _a !== void 0 ? _a : 'Failed to load Click to Pay configuration.'
24385
+ });
22898
24386
  });
22899
24387
  }
22900
24388
  /**