@paydock/client-sdk 1.144.1-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 (50) hide show
  1. package/README.md +422 -31
  2. package/bundles/index.cjs +1972 -532
  3. package/bundles/index.cjs.d.ts +192 -8
  4. package/bundles/index.mjs +1972 -532
  5. package/bundles/index.mjs.d.ts +192 -8
  6. package/bundles/types/helper/browser.d.ts.map +1 -1
  7. package/bundles/types/helper/element-id.d.ts +3 -1
  8. package/bundles/types/helper/element-id.d.ts.map +1 -1
  9. package/bundles/types/helper/uuid.d.ts.map +1 -1
  10. package/bundles/types/open-wallets/apple-pay-open-wallet-button.d.ts +41 -0
  11. package/bundles/types/open-wallets/apple-pay-open-wallet-button.d.ts.map +1 -1
  12. package/bundles/types/open-wallets/base/open-wallet-buttons.d.ts +10 -0
  13. package/bundles/types/open-wallets/base/open-wallet-buttons.d.ts.map +1 -1
  14. package/bundles/types/open-wallets/base/service-config-cache.d.ts +23 -0
  15. package/bundles/types/open-wallets/base/service-config-cache.d.ts.map +1 -0
  16. package/bundles/types/open-wallets/google-pay-open-wallet-button.d.ts +33 -1
  17. package/bundles/types/open-wallets/google-pay-open-wallet-button.d.ts.map +1 -1
  18. package/bundles/types/open-wallets/index.d.ts +82 -1
  19. package/bundles/types/open-wallets/index.d.ts.map +1 -1
  20. package/bundles/types/open-wallets/interfaces/apple-pay/apple-pay-availability.interface.d.ts +41 -0
  21. package/bundles/types/open-wallets/interfaces/apple-pay/apple-pay-availability.interface.d.ts.map +1 -0
  22. package/bundles/types/open-wallets/interfaces/apple-pay/index.d.ts +1 -0
  23. package/bundles/types/open-wallets/interfaces/apple-pay/index.d.ts.map +1 -1
  24. package/bundles/types/open-wallets/interfaces/google-pay/google-pay-availability.interface.d.ts +25 -0
  25. package/bundles/types/open-wallets/interfaces/google-pay/google-pay-availability.interface.d.ts.map +1 -0
  26. package/bundles/types/open-wallets/interfaces/google-pay/index.d.ts +1 -0
  27. package/bundles/types/open-wallets/interfaces/google-pay/index.d.ts.map +1 -1
  28. package/bundles/types/open-wallets/interfaces/index.d.ts +3 -0
  29. package/bundles/types/open-wallets/interfaces/index.d.ts.map +1 -1
  30. package/bundles/types/open-wallets/interfaces/open-wallet-availability.interface.d.ts +31 -0
  31. package/bundles/types/open-wallets/interfaces/open-wallet-availability.interface.d.ts.map +1 -0
  32. package/bundles/types/open-wallets/services/apple-pay/apple-pay-availability.d.ts +58 -0
  33. package/bundles/types/open-wallets/services/apple-pay/apple-pay-availability.d.ts.map +1 -0
  34. package/bundles/types/open-wallets/services/apple-pay/apple-pay.open-wallet.service.d.ts +8 -10
  35. package/bundles/types/open-wallets/services/apple-pay/apple-pay.open-wallet.service.d.ts.map +1 -1
  36. package/bundles/types/open-wallets/services/apple-pay/index.d.ts +1 -0
  37. package/bundles/types/open-wallets/services/apple-pay/index.d.ts.map +1 -1
  38. package/bundles/types/open-wallets/services/google-pay/google-pay-availability.d.ts +53 -0
  39. package/bundles/types/open-wallets/services/google-pay/google-pay-availability.d.ts.map +1 -0
  40. package/bundles/types/open-wallets/services/google-pay/google-pay.open-wallet.service.d.ts.map +1 -1
  41. package/bundles/types/open-wallets/services/google-pay/index.d.ts +1 -0
  42. package/bundles/types/open-wallets/services/google-pay/index.d.ts.map +1 -1
  43. package/bundles/widget.umd.js +1972 -532
  44. package/bundles/widget.umd.js.d.ts +192 -8
  45. package/bundles/widget.umd.js.min.d.ts +192 -8
  46. package/bundles/widget.umd.min.js +1 -1
  47. package/docs/open-wallet-buttons-examples.md +170 -2
  48. package/docs/open-wallet-buttons.md +252 -29
  49. package/package.json +10 -7
  50. package/slate.md +170 -2
@@ -834,16 +834,28 @@
834
834
  value: function getBrowserName() {
835
835
  var sUsrAg = navigator.userAgent;
836
836
  // "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:61.0) Gecko/20100101 Firefox/61.0"
837
- if (sUsrAg.indexOf('Firefox') > -1) return 'Mozilla Firefox';
838
- if (sUsrAg.indexOf('Opera') > -1) return 'Opera';
837
+ if (sUsrAg.indexOf('Firefox') > -1) {
838
+ return 'Mozilla Firefox';
839
+ }
840
+ if (sUsrAg.indexOf('Opera') > -1) {
841
+ return 'Opera';
842
+ }
839
843
  // "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"
840
- if (sUsrAg.indexOf('Trident') > -1) return 'Microsoft Internet Explorer';
844
+ if (sUsrAg.indexOf('Trident') > -1) {
845
+ return 'Microsoft Internet Explorer';
846
+ }
841
847
  // "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"
842
- if (sUsrAg.indexOf('Edge') > -1) return 'Microsoft Edge';
848
+ if (sUsrAg.indexOf('Edge') > -1) {
849
+ return 'Microsoft Edge';
850
+ }
843
851
  // "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"
844
- if (sUsrAg.indexOf('Chrome') > -1) return 'Google Chrome or Chromium';
852
+ if (sUsrAg.indexOf('Chrome') > -1) {
853
+ return 'Google Chrome or Chromium';
854
+ }
845
855
  // "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"
846
- if (sUsrAg.indexOf('Safari') > -1) return 'Apple Safari';
856
+ if (sUsrAg.indexOf('Safari') > -1) {
857
+ return 'Apple Safari';
858
+ }
847
859
  return 'unknown';
848
860
  }
849
861
  }, {
@@ -874,11 +886,13 @@
874
886
  }, {
875
887
  key: "getBrowserInfo",
876
888
  value: function getBrowserInfo() {
877
- var ua = navigator.userAgent;
889
+ // Bound the user-agent length before running any regex to avoid
890
+ // pathological backtracking (ReDoS) on maliciously long inputs.
891
+ var ua = (navigator.userAgent || '').slice(0, 256);
878
892
  var M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
879
- var tem;
880
- if (/trident/i.test(M[1])) {
881
- tem = /\brv[ :](\d+)/.exec(ua) || [];
893
+ var tem = null;
894
+ if (/trident/i.test(M[1] || '')) {
895
+ tem = ua.match(/\brv[ :](\d+)/) || [];
882
896
  return {
883
897
  name: 'IE',
884
898
  version: tem[1] || ''
@@ -894,8 +908,8 @@
894
908
  }
895
909
  }
896
910
  M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
897
- // tslint:disable-next-line:no-conditional-assignment
898
- if ((tem = ua.match(/version\/(\d+)/i)) != null) {
911
+ tem = ua.match(/version\/(\d+)/i);
912
+ if (tem != null) {
899
913
  M.splice(1, 1, tem[1]);
900
914
  }
901
915
  return {
@@ -1855,7 +1869,7 @@
1855
1869
  version: 'x-sdk-version',
1856
1870
  type: 'x-sdk-type'
1857
1871
  });
1858
- SDK._version = 'v1.144.1-beta';
1872
+ SDK._version = 'v1.145.0-beta';
1859
1873
 
1860
1874
  var ACCESS_HEADER_NAME = {
1861
1875
  accessToken: 'x-access-token',
@@ -5654,12 +5668,12 @@
5654
5668
  return _createClass(Uuid, null, [{
5655
5669
  key: "generate",
5656
5670
  value: function generate() {
5657
- if (typeof window !== "undefined" && typeof window.crypto !== "undefined" && typeof window.crypto.getRandomValues !== "undefined") {
5671
+ if (typeof window !== 'undefined' && typeof window.crypto !== 'undefined' && typeof window.crypto.getRandomValues !== 'undefined') {
5658
5672
  var buf = new Uint16Array(8);
5659
5673
  window.crypto.getRandomValues(buf);
5660
- 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]);
5674
+ 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]);
5661
5675
  } else {
5662
- return this.random() + this.random() + "-" + this.random() + "-" + this.random() + "-" + this.random() + "-" + this.random() + this.random() + this.random();
5676
+ return Uuid.random() + Uuid.random() + '-' + Uuid.random() + '-' + Uuid.random() + '-' + Uuid.random() + '-' + Uuid.random() + Uuid.random() + Uuid.random();
5663
5677
  }
5664
5678
  }
5665
5679
  }, {
@@ -5667,14 +5681,22 @@
5667
5681
  value: function hash(number) {
5668
5682
  var hash = number.toString(16);
5669
5683
  while (hash.length < 4) {
5670
- hash = "0" + hash;
5684
+ hash = '0' + hash;
5671
5685
  }
5672
5686
  return hash;
5673
5687
  }
5674
5688
  }, {
5675
5689
  key: "random",
5676
5690
  value: function random() {
5677
- return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
5691
+ var value;
5692
+ if (typeof crypto !== 'undefined' && typeof crypto.getRandomValues === 'function') {
5693
+ var buf = new Uint16Array(1);
5694
+ crypto.getRandomValues(buf);
5695
+ value = buf[0] / 0x10000;
5696
+ } else {
5697
+ value = Math.random();
5698
+ }
5699
+ return Math.floor((1 + value) * 0x10000).toString(16).substring(1);
5678
5700
  }
5679
5701
  }]);
5680
5702
  }();
@@ -8349,7 +8371,7 @@
8349
8371
  }]);
8350
8372
  }(WalletService);
8351
8373
 
8352
- /*! @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 */
8374
+ /*! @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 */
8353
8375
 
8354
8376
  var purify_cjs;
8355
8377
  var hasRequiredPurify_cjs;
@@ -8358,22 +8380,63 @@
8358
8380
  if (hasRequiredPurify_cjs) return purify_cjs;
8359
8381
  hasRequiredPurify_cjs = 1;
8360
8382
 
8361
- const {
8362
- entries,
8363
- setPrototypeOf,
8364
- isFrozen,
8365
- getPrototypeOf,
8366
- getOwnPropertyDescriptor
8367
- } = Object;
8368
- let {
8369
- freeze,
8370
- seal,
8371
- create
8372
- } = Object; // eslint-disable-line import/no-mutable-exports
8373
- let {
8374
- apply,
8375
- construct
8376
- } = typeof Reflect !== 'undefined' && Reflect;
8383
+ function _arrayLikeToArray(r, a) {
8384
+ (null == a || a > r.length) && (a = r.length);
8385
+ for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
8386
+ return n;
8387
+ }
8388
+ function _arrayWithHoles(r) {
8389
+ if (Array.isArray(r)) return r;
8390
+ }
8391
+ function _iterableToArrayLimit(r, l) {
8392
+ var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
8393
+ if (null != t) {
8394
+ var e,
8395
+ n,
8396
+ i,
8397
+ u,
8398
+ a = [],
8399
+ f = true,
8400
+ o = false;
8401
+ try {
8402
+ 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);
8403
+ } catch (r) {
8404
+ o = true, n = r;
8405
+ } finally {
8406
+ try {
8407
+ if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;
8408
+ } finally {
8409
+ if (o) throw n;
8410
+ }
8411
+ }
8412
+ return a;
8413
+ }
8414
+ }
8415
+ function _nonIterableRest() {
8416
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
8417
+ }
8418
+ function _slicedToArray(r, e) {
8419
+ return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
8420
+ }
8421
+ function _unsupportedIterableToArray(r, a) {
8422
+ if (r) {
8423
+ if ("string" == typeof r) return _arrayLikeToArray(r, a);
8424
+ var t = {}.toString.call(r).slice(8, -1);
8425
+ 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;
8426
+ }
8427
+ }
8428
+
8429
+ const entries = Object.entries,
8430
+ setPrototypeOf = Object.setPrototypeOf,
8431
+ isFrozen = Object.isFrozen,
8432
+ getPrototypeOf = Object.getPrototypeOf,
8433
+ getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
8434
+ let freeze = Object.freeze,
8435
+ seal = Object.seal,
8436
+ create = Object.create; // eslint-disable-line import/no-mutable-exports
8437
+ let _ref = typeof Reflect !== 'undefined' && Reflect,
8438
+ apply = _ref.apply,
8439
+ construct = _ref.construct;
8377
8440
  if (!freeze) {
8378
8441
  freeze = function freeze(x) {
8379
8442
  return x;
@@ -8405,13 +8468,19 @@
8405
8468
  const arrayPop = unapply(Array.prototype.pop);
8406
8469
  const arrayPush = unapply(Array.prototype.push);
8407
8470
  const arraySplice = unapply(Array.prototype.splice);
8471
+ const arrayIsArray = Array.isArray;
8408
8472
  const stringToLowerCase = unapply(String.prototype.toLowerCase);
8409
8473
  const stringToString = unapply(String.prototype.toString);
8410
8474
  const stringMatch = unapply(String.prototype.match);
8411
8475
  const stringReplace = unapply(String.prototype.replace);
8412
8476
  const stringIndexOf = unapply(String.prototype.indexOf);
8413
8477
  const stringTrim = unapply(String.prototype.trim);
8478
+ const numberToString = unapply(Number.prototype.toString);
8479
+ const booleanToString = unapply(Boolean.prototype.toString);
8480
+ const bigintToString = typeof BigInt === 'undefined' ? null : unapply(BigInt.prototype.toString);
8481
+ const symbolToString = typeof Symbol === 'undefined' ? null : unapply(Symbol.prototype.toString);
8414
8482
  const objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty);
8483
+ const objectToString = unapply(Object.prototype.toString);
8415
8484
  const regExpTest = unapply(RegExp.prototype.test);
8416
8485
  const typeErrorCreate = unconstruct(TypeError);
8417
8486
  /**
@@ -8461,6 +8530,9 @@
8461
8530
  // Prevent prototype setters from intercepting set as a this value.
8462
8531
  setPrototypeOf(set, null);
8463
8532
  }
8533
+ if (!arrayIsArray(array)) {
8534
+ return set;
8535
+ }
8464
8536
  let l = array.length;
8465
8537
  while (l--) {
8466
8538
  let element = array[l];
@@ -8501,10 +8573,13 @@
8501
8573
  */
8502
8574
  function clone(object) {
8503
8575
  const newObject = create(null);
8504
- for (const [property, value] of entries(object)) {
8576
+ for (const _ref2 of entries(object)) {
8577
+ var _ref3 = _slicedToArray(_ref2, 2);
8578
+ const property = _ref3[0];
8579
+ const value = _ref3[1];
8505
8580
  const isPropertyExist = objectHasOwnProperty(object, property);
8506
8581
  if (isPropertyExist) {
8507
- if (Array.isArray(value)) {
8582
+ if (arrayIsArray(value)) {
8508
8583
  newObject[property] = cleanArray(value);
8509
8584
  } else if (value && typeof value === 'object' && value.constructor === Object) {
8510
8585
  newObject[property] = clone(value);
@@ -8515,6 +8590,58 @@
8515
8590
  }
8516
8591
  return newObject;
8517
8592
  }
8593
+ /**
8594
+ * Convert non-node values into strings without depending on direct property access.
8595
+ *
8596
+ * @param value - The value to stringify.
8597
+ * @returns A string representation of the provided value.
8598
+ */
8599
+ function stringifyValue(value) {
8600
+ switch (typeof value) {
8601
+ case 'string':
8602
+ {
8603
+ return value;
8604
+ }
8605
+ case 'number':
8606
+ {
8607
+ return numberToString(value);
8608
+ }
8609
+ case 'boolean':
8610
+ {
8611
+ return booleanToString(value);
8612
+ }
8613
+ case 'bigint':
8614
+ {
8615
+ return bigintToString ? bigintToString(value) : '0';
8616
+ }
8617
+ case 'symbol':
8618
+ {
8619
+ return symbolToString ? symbolToString(value) : 'Symbol()';
8620
+ }
8621
+ case 'undefined':
8622
+ {
8623
+ return objectToString(value);
8624
+ }
8625
+ case 'function':
8626
+ case 'object':
8627
+ {
8628
+ if (value === null) {
8629
+ return objectToString(value);
8630
+ }
8631
+ const valueAsRecord = value;
8632
+ const valueToString = lookupGetter(valueAsRecord, 'toString');
8633
+ if (typeof valueToString === 'function') {
8634
+ const stringified = valueToString(valueAsRecord);
8635
+ return typeof stringified === 'string' ? stringified : objectToString(stringified);
8636
+ }
8637
+ return objectToString(value);
8638
+ }
8639
+ default:
8640
+ {
8641
+ return objectToString(value);
8642
+ }
8643
+ }
8644
+ }
8518
8645
  /**
8519
8646
  * This method automatically checks if the prop is function or getter and behaves accordingly.
8520
8647
  *
@@ -8540,6 +8667,14 @@
8540
8667
  }
8541
8668
  return fallbackValue;
8542
8669
  }
8670
+ function isRegex(value) {
8671
+ try {
8672
+ regExpTest(value, '');
8673
+ return true;
8674
+ } catch (_unused) {
8675
+ return false;
8676
+ }
8677
+ }
8543
8678
 
8544
8679
  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']);
8545
8680
  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']);
@@ -8555,15 +8690,14 @@
8555
8690
  const mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);
8556
8691
  const text = freeze(['#text']);
8557
8692
 
8558
- 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']);
8693
+ 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']);
8559
8694
  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']);
8560
8695
  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']);
8561
8696
  const xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);
8562
8697
 
8563
- // eslint-disable-next-line unicorn/better-regex
8564
- const MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode
8565
- const ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm);
8566
- const TMPLIT_EXPR = seal(/\$\{[\w\W]*/gm); // eslint-disable-line unicorn/better-regex
8698
+ const MUSTACHE_EXPR = seal(/{{[\w\W]*|^[\w\W]*}}/g);
8699
+ const ERB_EXPR = seal(/<%[\w\W]*|^[\w\W]*%>/g);
8700
+ const TMPLIT_EXPR = seal(/\${[\w\W]*/g);
8567
8701
  const DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]+$/); // eslint-disable-line no-useless-escape
8568
8702
  const ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape
8569
8703
  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
@@ -8573,30 +8707,31 @@
8573
8707
  );
8574
8708
  const DOCTYPE_NAME = seal(/^html$/i);
8575
8709
  const CUSTOM_ELEMENT = seal(/^[a-z][.\w]*(-[.\w]+)+$/i);
8710
+ // Markup-significant character probes used by _sanitizeElements.
8711
+ // Shared module-level instances are safe despite the sticky /g flags:
8712
+ // unapply() resets lastIndex for RegExp receivers before every call.
8713
+ const ELEMENT_MARKUP_PROBE = seal(/<[/\w!]/g);
8714
+ const COMMENT_MARKUP_PROBE = seal(/<[/\w]/g);
8715
+ const FALLBACK_TAG_CLOSE = seal(/<\/no(script|embed|frames)/i);
8716
+ const SELF_CLOSING_TAG = seal(/\/>/i);
8576
8717
 
8577
- var EXPRESSIONS = /*#__PURE__*/Object.freeze({
8578
- __proto__: null,
8579
- ARIA_ATTR: ARIA_ATTR,
8580
- ATTR_WHITESPACE: ATTR_WHITESPACE,
8581
- CUSTOM_ELEMENT: CUSTOM_ELEMENT,
8582
- DATA_ATTR: DATA_ATTR,
8583
- DOCTYPE_NAME: DOCTYPE_NAME,
8584
- ERB_EXPR: ERB_EXPR,
8585
- IS_ALLOWED_URI: IS_ALLOWED_URI,
8586
- IS_SCRIPT_OR_DATA: IS_SCRIPT_OR_DATA,
8587
- MUSTACHE_EXPR: MUSTACHE_EXPR,
8588
- TMPLIT_EXPR: TMPLIT_EXPR
8589
- });
8590
-
8591
- /* eslint-disable @typescript-eslint/indent */
8592
8718
  // https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType
8593
8719
  const NODE_TYPE = {
8594
8720
  element: 1,
8721
+ attribute: 2,
8595
8722
  text: 3,
8723
+ cdataSection: 4,
8724
+ entityReference: 5,
8596
8725
  // Deprecated
8597
- progressingInstruction: 7,
8726
+ entityNode: 6,
8727
+ // Deprecated
8728
+ processingInstruction: 7,
8598
8729
  comment: 8,
8599
- document: 9};
8730
+ document: 9,
8731
+ documentType: 10,
8732
+ documentFragment: 11,
8733
+ notation: 12 // Deprecated
8734
+ };
8600
8735
  const getGlobal = function getGlobal() {
8601
8736
  return typeof window === 'undefined' ? null : window;
8602
8737
  };
@@ -8651,10 +8786,25 @@
8651
8786
  uponSanitizeShadowNode: []
8652
8787
  };
8653
8788
  };
8789
+ /**
8790
+ * Resolve a set-valued configuration option: a fresh set built from
8791
+ * cfg[key] when it is an own array property (seeded with a clone of
8792
+ * options.base when given, case-normalized via options.transform),
8793
+ * the fallback set otherwise.
8794
+ *
8795
+ * @param cfg the cloned, prototype-free configuration object
8796
+ * @param key the configuration property to read
8797
+ * @param fallback the set to use when the option is absent or not an array
8798
+ * @param options transform and optional base set to merge into
8799
+ * @returns the resolved set
8800
+ */
8801
+ const _resolveSetOption = function _resolveSetOption(cfg, key, fallback, options) {
8802
+ return objectHasOwnProperty(cfg, key) && arrayIsArray(cfg[key]) ? addToSet(options.base ? clone(options.base) : {}, cfg[key], options.transform) : fallback;
8803
+ };
8654
8804
  function createDOMPurify() {
8655
8805
  let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();
8656
8806
  const DOMPurify = root => createDOMPurify(root);
8657
- DOMPurify.version = '3.4.0';
8807
+ DOMPurify.version = '3.4.11';
8658
8808
  DOMPurify.removed = [];
8659
8809
  if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document || !window.Element) {
8660
8810
  // Not running in a browser, provide a factory function
@@ -8662,28 +8812,29 @@
8662
8812
  DOMPurify.isSupported = false;
8663
8813
  return DOMPurify;
8664
8814
  }
8665
- let {
8666
- document
8667
- } = window;
8815
+ let document = window.document;
8668
8816
  const originalDocument = document;
8669
8817
  const currentScript = originalDocument.currentScript;
8670
- const {
8671
- DocumentFragment,
8672
- HTMLTemplateElement,
8673
- Node,
8674
- Element,
8675
- NodeFilter,
8676
- NamedNodeMap = window.NamedNodeMap || window.MozNamedAttrMap,
8677
- HTMLFormElement,
8678
- DOMParser,
8679
- trustedTypes
8680
- } = window;
8818
+ window.DocumentFragment;
8819
+ const HTMLTemplateElement = window.HTMLTemplateElement,
8820
+ Node = window.Node,
8821
+ Element = window.Element,
8822
+ NodeFilter = window.NodeFilter,
8823
+ _window$NamedNodeMap = window.NamedNodeMap;
8824
+ _window$NamedNodeMap === void 0 ? window.NamedNodeMap || window.MozNamedAttrMap : _window$NamedNodeMap;
8825
+ window.HTMLFormElement;
8826
+ const DOMParser = window.DOMParser,
8827
+ trustedTypes = window.trustedTypes;
8681
8828
  const ElementPrototype = Element.prototype;
8682
8829
  const cloneNode = lookupGetter(ElementPrototype, 'cloneNode');
8683
8830
  const remove = lookupGetter(ElementPrototype, 'remove');
8684
8831
  const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');
8685
8832
  const getChildNodes = lookupGetter(ElementPrototype, 'childNodes');
8686
8833
  const getParentNode = lookupGetter(ElementPrototype, 'parentNode');
8834
+ const getShadowRoot = lookupGetter(ElementPrototype, 'shadowRoot');
8835
+ const getAttributes = lookupGetter(ElementPrototype, 'attributes');
8836
+ const getNodeType = Node && Node.prototype ? lookupGetter(Node.prototype, 'nodeType') : null;
8837
+ const getNodeName = Node && Node.prototype ? lookupGetter(Node.prototype, 'nodeName') : null;
8687
8838
  // As per issue #47, the web-components registry is inherited by a
8688
8839
  // new document created via createHTMLDocument. As per the spec
8689
8840
  // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)
@@ -8698,33 +8849,74 @@
8698
8849
  }
8699
8850
  let trustedTypesPolicy;
8700
8851
  let emptyHTML = '';
8701
- const {
8702
- implementation,
8703
- createNodeIterator,
8704
- createDocumentFragment,
8705
- getElementsByTagName
8706
- } = document;
8707
- const {
8708
- importNode
8709
- } = originalDocument;
8852
+ // The instance's own internal Trusted Types policy. Unlike a caller-supplied
8853
+ // `TRUSTED_TYPES_POLICY`, this is created at most once — Trusted Types throws
8854
+ // on duplicate policy names — and is the only policy allowed to persist
8855
+ // across configurations and survive `clearConfig()`.
8856
+ let defaultTrustedTypesPolicy;
8857
+ let defaultTrustedTypesPolicyResolved = false;
8858
+ // Tracks whether we are already inside a call to the configured Trusted Types
8859
+ // policy (`createHTML` or `createScriptURL`). If a supplied policy callback
8860
+ // itself calls `DOMPurify.sanitize` (the cause of #1422), `sanitize` would
8861
+ // re-enter the policy and recurse until the stack overflows. We detect that
8862
+ // re-entry and throw a clear, actionable error instead. The guard is shared
8863
+ // across both callbacks, because either one re-entering `sanitize` triggers
8864
+ // the same unbounded recursion.
8865
+ let IN_TRUSTED_TYPES_POLICY = 0;
8866
+ const _assertNotInTrustedTypesPolicy = function _assertNotInTrustedTypesPolicy() {
8867
+ if (IN_TRUSTED_TYPES_POLICY > 0) {
8868
+ 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.');
8869
+ }
8870
+ };
8871
+ const _createTrustedHTML = function _createTrustedHTML(html) {
8872
+ _assertNotInTrustedTypesPolicy();
8873
+ IN_TRUSTED_TYPES_POLICY++;
8874
+ try {
8875
+ return trustedTypesPolicy.createHTML(html);
8876
+ } finally {
8877
+ IN_TRUSTED_TYPES_POLICY--;
8878
+ }
8879
+ };
8880
+ const _createTrustedScriptURL = function _createTrustedScriptURL(scriptUrl) {
8881
+ _assertNotInTrustedTypesPolicy();
8882
+ IN_TRUSTED_TYPES_POLICY++;
8883
+ try {
8884
+ return trustedTypesPolicy.createScriptURL(scriptUrl);
8885
+ } finally {
8886
+ IN_TRUSTED_TYPES_POLICY--;
8887
+ }
8888
+ };
8889
+ // Lazily resolve (and cache) the instance's internal default policy.
8890
+ // Resolution is attempted at most once: a successful `createPolicy` cannot be
8891
+ // repeated (Trusted Types throws on duplicate names), and a failed or
8892
+ // unsupported attempt must not be retried on every parse.
8893
+ const _getDefaultTrustedTypesPolicy = function _getDefaultTrustedTypesPolicy() {
8894
+ if (!defaultTrustedTypesPolicyResolved) {
8895
+ defaultTrustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);
8896
+ defaultTrustedTypesPolicyResolved = true;
8897
+ }
8898
+ return defaultTrustedTypesPolicy;
8899
+ };
8900
+ const _document = document,
8901
+ implementation = _document.implementation,
8902
+ createNodeIterator = _document.createNodeIterator,
8903
+ createDocumentFragment = _document.createDocumentFragment,
8904
+ getElementsByTagName = _document.getElementsByTagName;
8905
+ const importNode = originalDocument.importNode;
8710
8906
  let hooks = _createHooksMap();
8711
8907
  /**
8712
8908
  * Expose whether this browser supports running the full DOMPurify.
8713
8909
  */
8714
8910
  DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNode === 'function' && implementation && implementation.createHTMLDocument !== undefined;
8715
- const {
8716
- MUSTACHE_EXPR,
8717
- ERB_EXPR,
8718
- TMPLIT_EXPR,
8719
- DATA_ATTR,
8720
- ARIA_ATTR,
8721
- IS_SCRIPT_OR_DATA,
8722
- ATTR_WHITESPACE,
8723
- CUSTOM_ELEMENT
8724
- } = EXPRESSIONS;
8725
- let {
8726
- IS_ALLOWED_URI: IS_ALLOWED_URI$1
8727
- } = EXPRESSIONS;
8911
+ const MUSTACHE_EXPR$1 = MUSTACHE_EXPR,
8912
+ ERB_EXPR$1 = ERB_EXPR,
8913
+ TMPLIT_EXPR$1 = TMPLIT_EXPR,
8914
+ DATA_ATTR$1 = DATA_ATTR,
8915
+ ARIA_ATTR$1 = ARIA_ATTR,
8916
+ IS_SCRIPT_OR_DATA$1 = IS_SCRIPT_OR_DATA,
8917
+ ATTR_WHITESPACE$1 = ATTR_WHITESPACE,
8918
+ CUSTOM_ELEMENT$1 = CUSTOM_ELEMENT;
8919
+ let IS_ALLOWED_URI$1 = IS_ALLOWED_URI;
8728
8920
  /**
8729
8921
  * We consider the elements and attributes below to be safe. Ideally
8730
8922
  * don't add any new ones but feel free to remove unwanted ones.
@@ -8801,6 +8993,13 @@
8801
8993
  let WHOLE_DOCUMENT = false;
8802
8994
  /* Track whether config is already set on this instance of DOMPurify. */
8803
8995
  let SET_CONFIG = false;
8996
+ /* Pristine allowlist bindings captured at setConfig() time. On the
8997
+ * persistent-config path sanitize() restores the sets from these before
8998
+ * the per-walk hook clone-guard, so a hook's in-call widening cannot
8999
+ * carry across calls. Null until setConfig() is called; reset by
9000
+ * clearConfig(). */
9001
+ let SET_CONFIG_ALLOWED_TAGS = null;
9002
+ let SET_CONFIG_ALLOWED_ATTR = null;
8804
9003
  /* Decide if all elements (e.g. style, script) must be children of
8805
9004
  * document.body. By default, browsers might move them to document.head */
8806
9005
  let FORCE_BODY = false;
@@ -8843,7 +9042,17 @@
8843
9042
  let USE_PROFILES = {};
8844
9043
  /* Tags to ignore content of when KEEP_CONTENT is true */
8845
9044
  let FORBID_CONTENTS = null;
8846
- 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']);
9045
+ const DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script',
9046
+ // <selectedcontent> mirrors the selected <option>'s subtree, cloned by
9047
+ // the UA (customizable <select>) — including any on* handlers — and the
9048
+ // engine re-mirrors synchronously whenever a removal changes which
9049
+ // option/selectedcontent is current, even inside DOMPurify's inert
9050
+ // DOMParser document. Hoisting its children on removal re-inserts a fresh
9051
+ // mirror target ahead of the walk, which the engine refills, looping
9052
+ // forever (DoS) and amplifying output. Dropping its content on removal
9053
+ // (rather than hoisting) breaks that cascade; the content is a duplicate
9054
+ // of the option, which is sanitized on its own. See campaign-3 F1/F6.
9055
+ 'selectedcontent', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']);
8847
9056
  /* Tags that are safe for data: URIs */
8848
9057
  let DATA_URI_TAGS = null;
8849
9058
  const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);
@@ -8859,8 +9068,10 @@
8859
9068
  /* Allowed XHTML+XML namespaces */
8860
9069
  let ALLOWED_NAMESPACES = null;
8861
9070
  const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);
8862
- let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']);
8863
- let HTML_INTEGRATION_POINTS = addToSet({}, ['annotation-xml']);
9071
+ const DEFAULT_MATHML_TEXT_INTEGRATION_POINTS = freeze(['mi', 'mo', 'mn', 'ms', 'mtext']);
9072
+ let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, DEFAULT_MATHML_TEXT_INTEGRATION_POINTS);
9073
+ const DEFAULT_HTML_INTEGRATION_POINTS = freeze(['annotation-xml']);
9074
+ let HTML_INTEGRATION_POINTS = addToSet({}, DEFAULT_HTML_INTEGRATION_POINTS);
8864
9075
  // Certain elements are allowed in both SVG and HTML
8865
9076
  // namespace. We need to specify them explicitly
8866
9077
  // so that they don't get erroneously deleted from
@@ -8902,15 +9113,33 @@
8902
9113
  // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.
8903
9114
  transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase;
8904
9115
  /* Set configuration parameters */
8905
- ALLOWED_TAGS = objectHasOwnProperty(cfg, 'ALLOWED_TAGS') ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS;
8906
- ALLOWED_ATTR = objectHasOwnProperty(cfg, 'ALLOWED_ATTR') ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR;
8907
- ALLOWED_NAMESPACES = objectHasOwnProperty(cfg, 'ALLOWED_NAMESPACES') ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES;
8908
- 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;
8909
- 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;
8910
- FORBID_CONTENTS = objectHasOwnProperty(cfg, 'FORBID_CONTENTS') ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS;
8911
- FORBID_TAGS = objectHasOwnProperty(cfg, 'FORBID_TAGS') ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : clone({});
8912
- FORBID_ATTR = objectHasOwnProperty(cfg, 'FORBID_ATTR') ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : clone({});
8913
- USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES : false;
9116
+ ALLOWED_TAGS = _resolveSetOption(cfg, 'ALLOWED_TAGS', DEFAULT_ALLOWED_TAGS, {
9117
+ transform: transformCaseFunc
9118
+ });
9119
+ ALLOWED_ATTR = _resolveSetOption(cfg, 'ALLOWED_ATTR', DEFAULT_ALLOWED_ATTR, {
9120
+ transform: transformCaseFunc
9121
+ });
9122
+ ALLOWED_NAMESPACES = _resolveSetOption(cfg, 'ALLOWED_NAMESPACES', DEFAULT_ALLOWED_NAMESPACES, {
9123
+ transform: stringToString
9124
+ });
9125
+ URI_SAFE_ATTRIBUTES = _resolveSetOption(cfg, 'ADD_URI_SAFE_ATTR', DEFAULT_URI_SAFE_ATTRIBUTES, {
9126
+ transform: transformCaseFunc,
9127
+ base: DEFAULT_URI_SAFE_ATTRIBUTES
9128
+ });
9129
+ DATA_URI_TAGS = _resolveSetOption(cfg, 'ADD_DATA_URI_TAGS', DEFAULT_DATA_URI_TAGS, {
9130
+ transform: transformCaseFunc,
9131
+ base: DEFAULT_DATA_URI_TAGS
9132
+ });
9133
+ FORBID_CONTENTS = _resolveSetOption(cfg, 'FORBID_CONTENTS', DEFAULT_FORBID_CONTENTS, {
9134
+ transform: transformCaseFunc
9135
+ });
9136
+ FORBID_TAGS = _resolveSetOption(cfg, 'FORBID_TAGS', clone({}), {
9137
+ transform: transformCaseFunc
9138
+ });
9139
+ FORBID_ATTR = _resolveSetOption(cfg, 'FORBID_ATTR', clone({}), {
9140
+ transform: transformCaseFunc
9141
+ });
9142
+ USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES && typeof cfg.USE_PROFILES === 'object' ? clone(cfg.USE_PROFILES) : cfg.USE_PROFILES : false;
8914
9143
  ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true
8915
9144
  ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true
8916
9145
  ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false
@@ -8926,20 +9155,22 @@
8926
9155
  SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false
8927
9156
  KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true
8928
9157
  IN_PLACE = cfg.IN_PLACE || false; // Default false
8929
- IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI;
8930
- NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;
8931
- MATHML_TEXT_INTEGRATION_POINTS = cfg.MATHML_TEXT_INTEGRATION_POINTS || MATHML_TEXT_INTEGRATION_POINTS;
8932
- HTML_INTEGRATION_POINTS = cfg.HTML_INTEGRATION_POINTS || HTML_INTEGRATION_POINTS;
8933
- CUSTOM_ELEMENT_HANDLING = cfg.CUSTOM_ELEMENT_HANDLING || create(null);
8934
- if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) {
8935
- CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck;
9158
+ IS_ALLOWED_URI$1 = isRegex(cfg.ALLOWED_URI_REGEXP) ? cfg.ALLOWED_URI_REGEXP : IS_ALLOWED_URI; // Default regexp
9159
+ NAMESPACE = typeof cfg.NAMESPACE === 'string' ? cfg.NAMESPACE : HTML_NAMESPACE; // Default HTML namespace
9160
+ 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
9161
+ 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
9162
+ const customElementHandling = objectHasOwnProperty(cfg, 'CUSTOM_ELEMENT_HANDLING') && cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING === 'object' ? clone(cfg.CUSTOM_ELEMENT_HANDLING) : create(null);
9163
+ CUSTOM_ELEMENT_HANDLING = create(null);
9164
+ if (objectHasOwnProperty(customElementHandling, 'tagNameCheck') && isRegexOrFunction(customElementHandling.tagNameCheck)) {
9165
+ CUSTOM_ELEMENT_HANDLING.tagNameCheck = customElementHandling.tagNameCheck; // Default undefined
8936
9166
  }
8937
- if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) {
8938
- CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck;
9167
+ if (objectHasOwnProperty(customElementHandling, 'attributeNameCheck') && isRegexOrFunction(customElementHandling.attributeNameCheck)) {
9168
+ CUSTOM_ELEMENT_HANDLING.attributeNameCheck = customElementHandling.attributeNameCheck; // Default undefined
8939
9169
  }
8940
- if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === 'boolean') {
8941
- CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements;
9170
+ if (objectHasOwnProperty(customElementHandling, 'allowCustomizedBuiltInElements') && typeof customElementHandling.allowCustomizedBuiltInElements === 'boolean') {
9171
+ CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = customElementHandling.allowCustomizedBuiltInElements; // Default undefined
8942
9172
  }
9173
+ seal(CUSTOM_ELEMENT_HANDLING);
8943
9174
  if (SAFE_FOR_TEMPLATES) {
8944
9175
  ALLOW_DATA_ATTR = false;
8945
9176
  }
@@ -8975,36 +9206,36 @@
8975
9206
  EXTRA_ELEMENT_HANDLING.tagCheck = null;
8976
9207
  EXTRA_ELEMENT_HANDLING.attributeCheck = null;
8977
9208
  /* Merge configuration parameters */
8978
- if (cfg.ADD_TAGS) {
9209
+ if (objectHasOwnProperty(cfg, 'ADD_TAGS')) {
8979
9210
  if (typeof cfg.ADD_TAGS === 'function') {
8980
9211
  EXTRA_ELEMENT_HANDLING.tagCheck = cfg.ADD_TAGS;
8981
- } else {
9212
+ } else if (arrayIsArray(cfg.ADD_TAGS)) {
8982
9213
  if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
8983
9214
  ALLOWED_TAGS = clone(ALLOWED_TAGS);
8984
9215
  }
8985
9216
  addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);
8986
9217
  }
8987
9218
  }
8988
- if (cfg.ADD_ATTR) {
9219
+ if (objectHasOwnProperty(cfg, 'ADD_ATTR')) {
8989
9220
  if (typeof cfg.ADD_ATTR === 'function') {
8990
9221
  EXTRA_ELEMENT_HANDLING.attributeCheck = cfg.ADD_ATTR;
8991
- } else {
9222
+ } else if (arrayIsArray(cfg.ADD_ATTR)) {
8992
9223
  if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
8993
9224
  ALLOWED_ATTR = clone(ALLOWED_ATTR);
8994
9225
  }
8995
9226
  addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);
8996
9227
  }
8997
9228
  }
8998
- if (cfg.ADD_URI_SAFE_ATTR) {
9229
+ if (objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') && arrayIsArray(cfg.ADD_URI_SAFE_ATTR)) {
8999
9230
  addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);
9000
9231
  }
9001
- if (cfg.FORBID_CONTENTS) {
9232
+ if (objectHasOwnProperty(cfg, 'FORBID_CONTENTS') && arrayIsArray(cfg.FORBID_CONTENTS)) {
9002
9233
  if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
9003
9234
  FORBID_CONTENTS = clone(FORBID_CONTENTS);
9004
9235
  }
9005
9236
  addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);
9006
9237
  }
9007
- if (cfg.ADD_FORBID_CONTENTS) {
9238
+ if (objectHasOwnProperty(cfg, 'ADD_FORBID_CONTENTS') && arrayIsArray(cfg.ADD_FORBID_CONTENTS)) {
9008
9239
  if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
9009
9240
  FORBID_CONTENTS = clone(FORBID_CONTENTS);
9010
9241
  }
@@ -9023,6 +9254,13 @@
9023
9254
  addToSet(ALLOWED_TAGS, ['tbody']);
9024
9255
  delete FORBID_TAGS.tbody;
9025
9256
  }
9257
+ // Re-derive the active Trusted Types policy from this configuration on
9258
+ // every parse. The active policy must never be sticky closure state that
9259
+ // outlives the config that set it: a caller-supplied policy left in place
9260
+ // after `clearConfig()` — or after a later call that supplied none, or
9261
+ // `TRUSTED_TYPES_POLICY: null` — could sign a subsequent "default"
9262
+ // `RETURN_TRUSTED_TYPE` result with a foreign, possibly unsafe policy.
9263
+ // See GHSA-vxr8-fq34-vvx9.
9026
9264
  if (cfg.TRUSTED_TYPES_POLICY) {
9027
9265
  if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') {
9028
9266
  throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');
@@ -9030,18 +9268,45 @@
9030
9268
  if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') {
9031
9269
  throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');
9032
9270
  }
9033
- // Overwrite existing TrustedTypes policy.
9271
+ // A caller-supplied policy applies to this configuration only.
9272
+ const previousTrustedTypesPolicy = trustedTypesPolicy;
9034
9273
  trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;
9035
- // Sign local variables required by `sanitize`.
9036
- emptyHTML = trustedTypesPolicy.createHTML('');
9274
+ // Sign local variables required by `sanitize`. If the supplied policy's
9275
+ // `createHTML` is circular (i.e. it calls `DOMPurify.sanitize`), this
9276
+ // throws via the re-entrancy guard. Restore the previous policy first so
9277
+ // the instance is not left in a poisoned state. See #1422.
9278
+ try {
9279
+ emptyHTML = _createTrustedHTML('');
9280
+ } catch (error) {
9281
+ trustedTypesPolicy = previousTrustedTypesPolicy;
9282
+ throw error;
9283
+ }
9284
+ } else if (cfg.TRUSTED_TYPES_POLICY === null) {
9285
+ // Explicit opt-out for this call: perform no Trusted Types signing and
9286
+ // create nothing (so a strict `trusted-types` CSP that disallows a
9287
+ // `dompurify` policy can still call `sanitize` from inside its own
9288
+ // policy — see #1422). Resetting to `undefined` rather than a sticky
9289
+ // `null` also drops any previously retained caller policy, so it cannot
9290
+ // resurface on a later call, while still allowing the next config-less
9291
+ // call to restore the internal default policy. See GHSA-vxr8-fq34-vvx9.
9292
+ trustedTypesPolicy = undefined;
9293
+ emptyHTML = '';
9037
9294
  } else {
9038
- // Uninitialized policy, attempt to initialize the internal dompurify policy.
9295
+ // No policy supplied: keep the currently active policy if one is set — a
9296
+ // previously supplied policy is intentionally sticky across config-less
9297
+ // calls — otherwise fall back to the instance's own internal policy,
9298
+ // created at most once. (A policy supplied for a *single* call still
9299
+ // lingers by design; what must not linger is a policy whose configuration
9300
+ // has been torn down via `clearConfig()`, which restores the default.)
9039
9301
  if (trustedTypesPolicy === undefined) {
9040
- trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);
9302
+ trustedTypesPolicy = _getDefaultTrustedTypesPolicy();
9041
9303
  }
9042
- // If creating the internal policy succeeded sign internal variables.
9043
- if (trustedTypesPolicy !== null && typeof emptyHTML === 'string') {
9044
- emptyHTML = trustedTypesPolicy.createHTML('');
9304
+ // Sign internal variables only when a policy is active. A falsy policy
9305
+ // (Trusted Types unsupported, creation failed, or an explicit opt-out)
9306
+ // leaves `emptyHTML` as a plain string, so we never call `.createHTML` on
9307
+ // a non-policy and throw. See #1422.
9308
+ if (trustedTypesPolicy && typeof emptyHTML === 'string') {
9309
+ emptyHTML = _createTrustedHTML('');
9045
9310
  }
9046
9311
  }
9047
9312
  // Prevent further manipulation of configuration.
@@ -9056,6 +9321,77 @@
9056
9321
  * correctly. */
9057
9322
  const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]);
9058
9323
  const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]);
9324
+ /**
9325
+ * Namespace rules for an element in the SVG namespace.
9326
+ *
9327
+ * @param tagName the element's lowercase tag name
9328
+ * @param parent the (possibly simulated) parent node
9329
+ * @param parentTagName the parent's lowercase tag name
9330
+ * @returns true if a spec-compliant parser could produce this element
9331
+ */
9332
+ const _checkSvgNamespace = function _checkSvgNamespace(tagName, parent, parentTagName) {
9333
+ // The only way to switch from HTML namespace to SVG
9334
+ // is via <svg>. If it happens via any other tag, then
9335
+ // it should be killed.
9336
+ if (parent.namespaceURI === HTML_NAMESPACE) {
9337
+ return tagName === 'svg';
9338
+ }
9339
+ // The only way to switch from MathML to SVG is via <svg>
9340
+ // if the parent is either <annotation-xml> or a MathML
9341
+ // text integration point.
9342
+ if (parent.namespaceURI === MATHML_NAMESPACE) {
9343
+ return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
9344
+ }
9345
+ // We only allow elements that are defined in SVG
9346
+ // spec. All others are disallowed in SVG namespace.
9347
+ return Boolean(ALL_SVG_TAGS[tagName]);
9348
+ };
9349
+ /**
9350
+ * Namespace rules for an element in the MathML namespace.
9351
+ *
9352
+ * @param tagName the element's lowercase tag name
9353
+ * @param parent the (possibly simulated) parent node
9354
+ * @param parentTagName the parent's lowercase tag name
9355
+ * @returns true if a spec-compliant parser could produce this element
9356
+ */
9357
+ const _checkMathMlNamespace = function _checkMathMlNamespace(tagName, parent, parentTagName) {
9358
+ // The only way to switch from HTML namespace to MathML
9359
+ // is via <math>. If it happens via any other tag, then
9360
+ // it should be killed.
9361
+ if (parent.namespaceURI === HTML_NAMESPACE) {
9362
+ return tagName === 'math';
9363
+ }
9364
+ // The only way to switch from SVG to MathML is via
9365
+ // <math> and HTML integration points
9366
+ if (parent.namespaceURI === SVG_NAMESPACE) {
9367
+ return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
9368
+ }
9369
+ // We only allow elements that are defined in MathML
9370
+ // spec. All others are disallowed in MathML namespace.
9371
+ return Boolean(ALL_MATHML_TAGS[tagName]);
9372
+ };
9373
+ /**
9374
+ * Namespace rules for an element in the HTML namespace.
9375
+ *
9376
+ * @param tagName the element's lowercase tag name
9377
+ * @param parent the (possibly simulated) parent node
9378
+ * @param parentTagName the parent's lowercase tag name
9379
+ * @returns true if a spec-compliant parser could produce this element
9380
+ */
9381
+ const _checkHtmlNamespace = function _checkHtmlNamespace(tagName, parent, parentTagName) {
9382
+ // The only way to switch from SVG to HTML is via
9383
+ // HTML integration points, and from MathML to HTML
9384
+ // is via MathML text integration points
9385
+ if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
9386
+ return false;
9387
+ }
9388
+ if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
9389
+ return false;
9390
+ }
9391
+ // We disallow tags that are specific for MathML
9392
+ // or SVG and should never appear in HTML namespace
9393
+ return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
9394
+ };
9059
9395
  /**
9060
9396
  * @param element a DOM element whose namespace is being checked
9061
9397
  * @returns Return false if the element has a
@@ -9078,51 +9414,13 @@
9078
9414
  return false;
9079
9415
  }
9080
9416
  if (element.namespaceURI === SVG_NAMESPACE) {
9081
- // The only way to switch from HTML namespace to SVG
9082
- // is via <svg>. If it happens via any other tag, then
9083
- // it should be killed.
9084
- if (parent.namespaceURI === HTML_NAMESPACE) {
9085
- return tagName === 'svg';
9086
- }
9087
- // The only way to switch from MathML to SVG is via`
9088
- // svg if parent is either <annotation-xml> or MathML
9089
- // text integration points.
9090
- if (parent.namespaceURI === MATHML_NAMESPACE) {
9091
- return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
9092
- }
9093
- // We only allow elements that are defined in SVG
9094
- // spec. All others are disallowed in SVG namespace.
9095
- return Boolean(ALL_SVG_TAGS[tagName]);
9417
+ return _checkSvgNamespace(tagName, parent, parentTagName);
9096
9418
  }
9097
9419
  if (element.namespaceURI === MATHML_NAMESPACE) {
9098
- // The only way to switch from HTML namespace to MathML
9099
- // is via <math>. If it happens via any other tag, then
9100
- // it should be killed.
9101
- if (parent.namespaceURI === HTML_NAMESPACE) {
9102
- return tagName === 'math';
9103
- }
9104
- // The only way to switch from SVG to MathML is via
9105
- // <math> and HTML integration points
9106
- if (parent.namespaceURI === SVG_NAMESPACE) {
9107
- return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
9108
- }
9109
- // We only allow elements that are defined in MathML
9110
- // spec. All others are disallowed in MathML namespace.
9111
- return Boolean(ALL_MATHML_TAGS[tagName]);
9420
+ return _checkMathMlNamespace(tagName, parent, parentTagName);
9112
9421
  }
9113
9422
  if (element.namespaceURI === HTML_NAMESPACE) {
9114
- // The only way to switch from SVG to HTML is via
9115
- // HTML integration points, and from MathML to HTML
9116
- // is via MathML text integration points
9117
- if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
9118
- return false;
9119
- }
9120
- if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
9121
- return false;
9122
- }
9123
- // We disallow tags that are specific for MathML
9124
- // or SVG and should never appear in HTML namespace
9125
- return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
9423
+ return _checkHtmlNamespace(tagName, parent, parentTagName);
9126
9424
  }
9127
9425
  // For XHTML and XML documents that support custom namespaces
9128
9426
  if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) {
@@ -9147,7 +9445,74 @@
9147
9445
  // eslint-disable-next-line unicorn/prefer-dom-node-remove
9148
9446
  getParentNode(node).removeChild(node);
9149
9447
  } catch (_) {
9448
+ /* The normal detach failed — this is reached for a parentless node
9449
+ (getParentNode() is null, so .removeChild throws). Element.prototype
9450
+ .remove() is itself a spec no-op on a parentless node, so a recorded
9451
+ "removal" would otherwise hand the caller back an intact,
9452
+ payload-bearing node (e.g. a detached IN_PLACE root the mXSS canary or
9453
+ the style-with-element-child rule decided to kill). Fail closed by
9454
+ throwing — exactly as a clobbered root does at the IN_PLACE entry —
9455
+ rather than trying to "neutralize" the node via its own methods.
9456
+ Neutralizing would mean calling getAttributeNames()/removeAttribute()
9457
+ on the node, both of which a <form> root can clobber via a named child
9458
+ (and _isClobbered does not even probe getAttributeNames), so the
9459
+ neutralize step could itself be silently defeated, leaving the payload
9460
+ intact. A throw touches only the cached, clobber-safe remove() and
9461
+ getParentNode(). Generalizes GHSA-r47g-fvhr-h676 (clobbered-form root)
9462
+ to every root-kill reason. REPORT-3.
9463
+ This lives inside the catch, so it never fires for a normally-removed
9464
+ in-tree node: those have a parent, removeChild() succeeds, and the
9465
+ catch is not entered. Only a kept (parentless) root reaches here. */
9150
9466
  remove(node);
9467
+ if (!getParentNode(node)) {
9468
+ throw typeErrorCreate('a node selected for removal could not be detached from its tree ' + 'and cannot be safely returned; refusing to sanitize in place');
9469
+ }
9470
+ }
9471
+ };
9472
+ /**
9473
+ * _neutralizeRoot
9474
+ *
9475
+ * Fail-closed teardown of an in-place root after the sanitize walk aborts
9476
+ * (campaign-3 F2). An internal throw mid-walk — e.g. a page-registered
9477
+ * custom element's reaction detaches a node so `_forceRemove`'s deliberate
9478
+ * parentless guard throws, or any other re-entrant engine mutation — would
9479
+ * otherwise leave the caller's *live* tree half-sanitized, with everything
9480
+ * after the abort point still carrying its handlers. There is no safe way
9481
+ * to resume the walk (the tree mutated under us), so we strip the root bare:
9482
+ * remove every child and every attribute, then let the caller's catch see
9483
+ * the original error. Clobber-safe (cached `remove`/`childNodes`/`attributes`
9484
+ * getters; the root was already clobber-pre-flighted at the IN_PLACE entry).
9485
+ *
9486
+ * @param root the in-place root to empty
9487
+ */
9488
+ const _neutralizeRoot = function _neutralizeRoot(root) {
9489
+ const childNodes = getChildNodes(root);
9490
+ if (childNodes) {
9491
+ const snapshot = [];
9492
+ arrayForEach(childNodes, child => {
9493
+ arrayPush(snapshot, child);
9494
+ });
9495
+ arrayForEach(snapshot, child => {
9496
+ try {
9497
+ remove(child);
9498
+ } catch (_) {
9499
+ /* Best-effort teardown; a still-attached child is handled below */
9500
+ }
9501
+ });
9502
+ }
9503
+ const attributes = getAttributes(root);
9504
+ if (attributes) {
9505
+ for (let i = attributes.length - 1; i >= 0; --i) {
9506
+ const attribute = attributes[i];
9507
+ const name = attribute && attribute.name;
9508
+ if (typeof name === 'string') {
9509
+ try {
9510
+ root.removeAttribute(name);
9511
+ } catch (_) {
9512
+ /* Clobbered removeAttribute — ignore (fail-closed best effort) */
9513
+ }
9514
+ }
9515
+ }
9151
9516
  }
9152
9517
  };
9153
9518
  /**
@@ -9182,6 +9547,72 @@
9182
9547
  }
9183
9548
  }
9184
9549
  };
9550
+ /**
9551
+ * _stripDisallowedAttributes
9552
+ *
9553
+ * Removes every attribute the active configuration does not allow from a
9554
+ * single element, using the same allowlist as the main attribute pass (so
9555
+ * `on*` handlers go, but no `/^on/` blocklist is introduced). Used only to
9556
+ * neutralise nodes that are being discarded from an in-place tree.
9557
+ *
9558
+ * @param element the element to strip
9559
+ */
9560
+ const _stripDisallowedAttributes = function _stripDisallowedAttributes(element) {
9561
+ const attributes = getAttributes(element);
9562
+ if (!attributes) {
9563
+ return;
9564
+ }
9565
+ for (let i = attributes.length - 1; i >= 0; --i) {
9566
+ const attribute = attributes[i];
9567
+ const name = attribute && attribute.name;
9568
+ if (typeof name !== 'string' || ALLOWED_ATTR[transformCaseFunc(name)]) {
9569
+ continue;
9570
+ }
9571
+ try {
9572
+ element.removeAttribute(name);
9573
+ } catch (_) {
9574
+ /* Clobbered removeAttribute on a doomed node — ignore */
9575
+ }
9576
+ }
9577
+ };
9578
+ /**
9579
+ * _neutralizeSubtree
9580
+ *
9581
+ * Completes the audit-5 F1 fix across every removal path. The KEEP_CONTENT
9582
+ * move-hoist neutralises only disallowed-tag removals; clobber, mXSS-canary,
9583
+ * namespace, comment, processing-instruction and KEEP_CONTENT:false removals
9584
+ * all drop their subtree wholesale via `_forceRemove`. On the IN_PLACE path
9585
+ * those dropped nodes are detached from the caller's LIVE tree but a
9586
+ * handler-bearing original among them (an `<img onerror>`/`<video>` that was
9587
+ * loading) keeps its queued resource event, which fires in page scope after
9588
+ * sanitize returns. This walks a removed subtree and strips every attribute
9589
+ * the active configuration does not allow — so `on*` handlers are cancelled
9590
+ * through the SAME allowlist that governs kept nodes, not a separate `/^on/`
9591
+ * blocklist. Run synchronously before sanitize returns, i.e. before any
9592
+ * queued event can fire. Hook-free by design: these nodes leave the output,
9593
+ * so firing attribute hooks for them would be surprising. Clobber-safe reads;
9594
+ * a doomed clobbered node may shadow `removeAttribute` (its own attributes are
9595
+ * irrelevant — it is discarded — while its non-clobbered descendants, e.g.
9596
+ * the `<img>`, are reached and scrubbed).
9597
+ *
9598
+ * @param root the root of a removed subtree to neutralise
9599
+ */
9600
+ const _neutralizeSubtree = function _neutralizeSubtree(root) {
9601
+ const stack = [root];
9602
+ while (stack.length > 0) {
9603
+ const node = stack.pop();
9604
+ const nodeType = getNodeType ? getNodeType(node) : node.nodeType;
9605
+ if (nodeType === NODE_TYPE.element) {
9606
+ _stripDisallowedAttributes(node);
9607
+ }
9608
+ const childNodes = getChildNodes(node);
9609
+ if (childNodes) {
9610
+ for (let i = childNodes.length - 1; i >= 0; --i) {
9611
+ stack.push(childNodes[i]);
9612
+ }
9613
+ }
9614
+ }
9615
+ };
9185
9616
  /**
9186
9617
  * _initDocument
9187
9618
  *
@@ -9203,7 +9634,7 @@
9203
9634
  // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)
9204
9635
  dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + '</body></html>';
9205
9636
  }
9206
- const dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
9637
+ const dirtyPayload = trustedTypesPolicy ? _createTrustedHTML(dirty) : dirty;
9207
9638
  /*
9208
9639
  * Use the DOMParser API by default, fallback later if needs be
9209
9640
  * DOMParser not work for svg when has multiple root element.
@@ -9243,29 +9674,254 @@
9243
9674
  // eslint-disable-next-line no-bitwise
9244
9675
  NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null);
9245
9676
  };
9677
+ /**
9678
+ * Replace template expression syntax (mustache, ERB, template
9679
+ * literal) with a space; shared by all SAFE_FOR_TEMPLATES scrub
9680
+ * sites. Order matters: mustache, then ERB, then template literal.
9681
+ *
9682
+ * @param value the string to scrub
9683
+ * @returns the scrubbed string
9684
+ */
9685
+ const _stripTemplateExpressions = function _stripTemplateExpressions(value) {
9686
+ value = stringReplace(value, MUSTACHE_EXPR$1, ' ');
9687
+ value = stringReplace(value, ERB_EXPR$1, ' ');
9688
+ value = stringReplace(value, TMPLIT_EXPR$1, ' ');
9689
+ return value;
9690
+ };
9691
+ /**
9692
+ * Strip template-engine expressions ({{...}}, ${...}, <%...%>) from the
9693
+ * character data of an element subtree. Used as the final safety net for
9694
+ * SAFE_FOR_TEMPLATES on every DOM-returning code path so that expressions
9695
+ * which only form after text-node normalization (e.g. fragments split across
9696
+ * stripped elements) cannot survive into a template-evaluating framework.
9697
+ *
9698
+ * Walks text/comment/CDATA/processing-instruction nodes and mutates `.data`
9699
+ * in place rather than round-tripping through innerHTML. This preserves
9700
+ * descendant node references (important for IN_PLACE callers), avoids a
9701
+ * serialize/reparse cycle, and reads literal character data — which means
9702
+ * `<%...%>` in text content matches the ERB regex against its real bytes
9703
+ * instead of the HTML-entity-escaped form innerHTML would produce.
9704
+ *
9705
+ * Attribute values are not visited here; SAFE_FOR_TEMPLATES handling for
9706
+ * attributes is performed during the per-node `_sanitizeAttributes` pass.
9707
+ *
9708
+ * @param node The root element whose character data should be scrubbed.
9709
+ */
9710
+ const _scrubTemplateExpressions2 = function _scrubTemplateExpressions(node) {
9711
+ var _node$querySelectorAl;
9712
+ node.normalize();
9713
+ const walker = createNodeIterator.call(node.ownerDocument || node, node,
9714
+ // eslint-disable-next-line no-bitwise
9715
+ NodeFilter.SHOW_TEXT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_CDATA_SECTION | NodeFilter.SHOW_PROCESSING_INSTRUCTION, null);
9716
+ let currentNode = walker.nextNode();
9717
+ while (currentNode) {
9718
+ currentNode.data = _stripTemplateExpressions(currentNode.data);
9719
+ currentNode = walker.nextNode();
9720
+ }
9721
+ // NodeIterator does not descend into <template>.content per the DOM spec,
9722
+ // so we must explicitly recurse into each template's content fragment,
9723
+ // mirroring the approach used by _sanitizeShadowDOM.
9724
+ const templates = (_node$querySelectorAl = node.querySelectorAll) === null || _node$querySelectorAl === void 0 ? void 0 : _node$querySelectorAl.call(node, 'template');
9725
+ if (templates) {
9726
+ arrayForEach(templates, tmpl => {
9727
+ if (_isDocumentFragment(tmpl.content)) {
9728
+ _scrubTemplateExpressions2(tmpl.content);
9729
+ }
9730
+ });
9731
+ }
9732
+ };
9246
9733
  /**
9247
9734
  * _isClobbered
9248
9735
  *
9736
+ * Detect DOM-clobbering on HTMLFormElement nodes. Form is the only HTML
9737
+ * interface with [LegacyOverrideBuiltIns]; a descendant element with a
9738
+ * `name` attribute matching a prototype property shadows that property
9739
+ * on direct reads. We use this check at the IN_PLACE entry-point and
9740
+ * during attribute sanitization to refuse clobbered forms.
9741
+ *
9249
9742
  * @param element element to check for clobbering attacks
9250
9743
  * @return true if clobbered, false if safe
9251
9744
  */
9252
9745
  const _isClobbered = function _isClobbered(element) {
9253
- 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');
9746
+ // Realm-independent tag-name probe. If we can't determine the tag
9747
+ // name at all, we can't reason about clobbering — return false
9748
+ // (the caller's other defences still apply).
9749
+ const realTagName = getNodeName ? getNodeName(element) : null;
9750
+ if (typeof realTagName !== 'string') {
9751
+ return false;
9752
+ }
9753
+ if (transformCaseFunc(realTagName) !== 'form') {
9754
+ return false;
9755
+ }
9756
+ return typeof element.nodeName !== 'string' || typeof element.textContent !== 'string' || typeof element.removeChild !== 'function' ||
9757
+ // Realm-safe NamedNodeMap detection: equality against the cached
9758
+ // prototype getter. Clobbered .attributes (e.g. <input name="attributes">)
9759
+ // makes the direct read diverge from the cached read; a clean form
9760
+ // (same-realm OR foreign-realm) has both reads pointing at the same
9761
+ // canonical NamedNodeMap.
9762
+ element.attributes !== getAttributes(element) || typeof element.removeAttribute !== 'function' || typeof element.setAttribute !== 'function' || typeof element.namespaceURI !== 'string' || typeof element.insertBefore !== 'function' || typeof element.hasChildNodes !== 'function' ||
9763
+ // NodeType clobbering probe. Cached Node.prototype.nodeType getter
9764
+ // returns the integer 1 for any Element regardless of realm; direct
9765
+ // read on a clobbered form (e.g. <input name="nodeType">) returns
9766
+ // the named child element. Cheap addition — nodeType is read from
9767
+ // an internal slot, no serialization cost — and removes a residual
9768
+ // clobbering surface used by several mXSS / PI / comment branches
9769
+ // in _sanitizeElements that compare currentNode.nodeType directly.
9770
+ element.nodeType !== getNodeType(element) ||
9771
+ // HTMLFormElement has [LegacyOverrideBuiltIns]: a descendant named
9772
+ // "childNodes" shadows the prototype getter. Direct reads of
9773
+ // form.childNodes from a clobbered form return the named child
9774
+ // instead of the real NodeList, so any walk that reads it directly
9775
+ // skips the form's real children. Compare the direct read to the
9776
+ // cached Node.prototype getter — when the form's named-property
9777
+ // getter intercepts the read, the two values differ and we flag
9778
+ // the form. This catches every clobbering child type (input,
9779
+ // select, etc.) regardless of whether the named child happens to
9780
+ // carry a numeric .length, which a typeof-based probe would miss
9781
+ // (e.g. HTMLSelectElement.length is a defined unsigned-long).
9782
+ element.childNodes !== getChildNodes(element);
9783
+ };
9784
+ /**
9785
+ * Checks whether the given value is a DocumentFragment from any realm.
9786
+ *
9787
+ * The realm-independent replacement reads `nodeType` through the cached
9788
+ * Node.prototype getter and compares to the DOCUMENT_FRAGMENT_NODE
9789
+ * constant (11). nodeType is a numeric value resolved from the node's
9790
+ * internal slot, identical across realms for the same kind of node.
9791
+ *
9792
+ * @param value object to check
9793
+ * @return true if value is a DocumentFragment-shaped node from any realm
9794
+ */
9795
+ const _isDocumentFragment = function _isDocumentFragment(value) {
9796
+ if (!getNodeType || typeof value !== 'object' || value === null) {
9797
+ return false;
9798
+ }
9799
+ try {
9800
+ return getNodeType(value) === NODE_TYPE.documentFragment;
9801
+ } catch (_) {
9802
+ return false;
9803
+ }
9254
9804
  };
9255
9805
  /**
9256
- * Checks whether the given object is a DOM node.
9806
+ * Checks whether the given object is a DOM node, including nodes that
9807
+ * originate from a different window/realm (e.g. an iframe's
9808
+ * contentDocument). The previous `value instanceof Node` check was
9809
+ * realm-bound: nodes from a different window failed it, causing
9810
+ * sanitize() to silently stringify them and reset IN_PLACE to false,
9811
+ * returning the original node unsanitized. See GHSA-4w3q-35jp-p934.
9257
9812
  *
9258
9813
  * @param value object to check whether it's a DOM node
9259
- * @return true is object is a DOM node
9814
+ * @return true if value is a DOM node from any realm
9260
9815
  */
9261
9816
  const _isNode = function _isNode(value) {
9262
- return typeof Node === 'function' && value instanceof Node;
9817
+ if (!getNodeType || typeof value !== 'object' || value === null) {
9818
+ return false;
9819
+ }
9820
+ try {
9821
+ return typeof getNodeType(value) === 'number';
9822
+ } catch (_) {
9823
+ return false;
9824
+ }
9263
9825
  };
9264
9826
  function _executeHooks(hooks, currentNode, data) {
9827
+ if (hooks.length === 0) {
9828
+ return;
9829
+ }
9265
9830
  arrayForEach(hooks, hook => {
9266
9831
  hook.call(DOMPurify, currentNode, data, CONFIG);
9267
9832
  });
9268
9833
  }
9834
+ /**
9835
+ * Structural-threat checks that condemn a node regardless of the
9836
+ * allowlists: mXSS via namespace confusion, risky CSS construction,
9837
+ * processing instructions, markup-bearing comments. Pure predicate;
9838
+ * the caller removes. Check order is load-bearing.
9839
+ *
9840
+ * @param currentNode the node to inspect
9841
+ * @param tagName the node's transformCaseFunc'd tag name
9842
+ * @return true if the node must be removed
9843
+ */
9844
+ const _isUnsafeNode = function _isUnsafeNode(currentNode, tagName) {
9845
+ /* Detect mXSS attempts abusing namespace confusion */
9846
+ if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.textContent) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.innerHTML)) {
9847
+ return true;
9848
+ }
9849
+ /* Remove risky CSS construction leading to mXSS */
9850
+ if (SAFE_FOR_XML && currentNode.namespaceURI === HTML_NAMESPACE && tagName === 'style' && _isNode(currentNode.firstElementChild)) {
9851
+ return true;
9852
+ }
9853
+ /* Remove any occurrence of processing instructions */
9854
+ if (currentNode.nodeType === NODE_TYPE.processingInstruction) {
9855
+ return true;
9856
+ }
9857
+ /* Remove any kind of possibly harmful comments */
9858
+ if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(COMMENT_MARKUP_PROBE, currentNode.data)) {
9859
+ return true;
9860
+ }
9861
+ return false;
9862
+ };
9863
+ /**
9864
+ * Handle a node whose tag is forbidden or not allowlisted: keep
9865
+ * allowed custom elements (false return exits _sanitizeElements
9866
+ * early - namespace/fallback checks and the afterSanitizeElements
9867
+ * hook are intentionally skipped for kept custom elements), else
9868
+ * hoist content per KEEP_CONTENT and remove.
9869
+ *
9870
+ * @param currentNode the disallowed node
9871
+ * @param tagName the node's transformCaseFunc'd tag name
9872
+ * @return true if the node was removed, false if kept
9873
+ */
9874
+ const _sanitizeDisallowedNode = function _sanitizeDisallowedNode(currentNode, tagName) {
9875
+ /* Check if we have a custom element to handle */
9876
+ if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {
9877
+ if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {
9878
+ return false;
9879
+ }
9880
+ if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) {
9881
+ return false;
9882
+ }
9883
+ }
9884
+ /* Keep content except for bad-listed elements.
9885
+ Use the cached prototype getters exclusively — the previous code
9886
+ had `|| currentNode.parentNode` / `|| currentNode.childNodes`
9887
+ fallbacks, but the cached getters always return the canonical
9888
+ value (or null for a real parent-less node), so the fallback
9889
+ path was dead in safe cases and a clobbering surface in unsafe
9890
+ ones. Falsy cached results stay falsy; the `if (childNodes &&
9891
+ parentNode)` check already gates correctly. */
9892
+ if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
9893
+ const parentNode = getParentNode(currentNode);
9894
+ const childNodes = getChildNodes(currentNode);
9895
+ if (childNodes && parentNode) {
9896
+ const childCount = childNodes.length;
9897
+ /* In-place: hoist the *original* children so the iterator visits
9898
+ and sanitises them through the same allowlist pass as every other
9899
+ node. The caller built the tree in the live document, so the
9900
+ originals carry already-queued resource events (`<img onerror>`,
9901
+ `<video>`/`<audio>` error, lazy/`onload`, …); cloning would leave
9902
+ those originals detached but still armed, firing in page scope
9903
+ while the returned tree looked clean. Moving is safe in-place: the
9904
+ root is pre-validated as an allowed tag and so is never the node
9905
+ being removed, which keeps `parentNode` inside the iterator root
9906
+ and the relocated child inside the serialised tree.
9907
+ Otherwise (string / DOM-copy paths): clone. The iterator is rooted
9908
+ at — and the result serialised from — `body`, so a restrictive
9909
+ ALLOWED_TAGS that removes `body` itself must leave its content in
9910
+ place, which only cloning does; and those paths parse into an
9911
+ inert document, so their discarded originals never had a queued
9912
+ event to neutralise.
9913
+ `childNodes` is live; a tail-to-head walk keeps `childNodes[i]`
9914
+ valid whether we move (drops the trailing entry) or clone (leaves
9915
+ the list intact). */
9916
+ for (let i = childCount - 1; i >= 0; --i) {
9917
+ const hoisted = IN_PLACE ? childNodes[i] : cloneNode(childNodes[i], true);
9918
+ parentNode.insertBefore(hoisted, getNextSibling(currentNode));
9919
+ }
9920
+ }
9921
+ }
9922
+ _forceRemove(currentNode);
9923
+ return true;
9924
+ };
9269
9925
  /**
9270
9926
  * _sanitizeElements
9271
9927
  *
@@ -9276,7 +9932,6 @@
9276
9932
  * @return true if node was killed, false if left alive
9277
9933
  */
9278
9934
  const _sanitizeElements = function _sanitizeElements(currentNode) {
9279
- let content = null;
9280
9935
  /* Execute a hook if present */
9281
9936
  _executeHooks(hooks.beforeSanitizeElements, currentNode, null);
9282
9937
  /* Check if element is clobbered or can clobber */
@@ -9285,76 +9940,41 @@
9285
9940
  return true;
9286
9941
  }
9287
9942
  /* Now let's check the element's type and name */
9288
- const tagName = transformCaseFunc(currentNode.nodeName);
9943
+ const tagName = transformCaseFunc(getNodeName ? getNodeName(currentNode) : currentNode.nodeName);
9289
9944
  /* Execute a hook if present */
9290
9945
  _executeHooks(hooks.uponSanitizeElement, currentNode, {
9291
9946
  tagName,
9292
9947
  allowedTags: ALLOWED_TAGS
9293
9948
  });
9294
- /* Detect mXSS attempts abusing namespace confusion */
9295
- if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(/<[/\w!]/g, currentNode.innerHTML) && regExpTest(/<[/\w!]/g, currentNode.textContent)) {
9296
- _forceRemove(currentNode);
9297
- return true;
9298
- }
9299
- /* Remove risky CSS construction leading to mXSS */
9300
- if (SAFE_FOR_XML && currentNode.namespaceURI === HTML_NAMESPACE && tagName === 'style' && _isNode(currentNode.firstElementChild)) {
9301
- _forceRemove(currentNode);
9302
- return true;
9303
- }
9304
- /* Remove any occurrence of processing instructions */
9305
- if (currentNode.nodeType === NODE_TYPE.progressingInstruction) {
9306
- _forceRemove(currentNode);
9307
- return true;
9308
- }
9309
- /* Remove any kind of possibly harmful comments */
9310
- if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(/<[/\w]/g, currentNode.data)) {
9949
+ /* Remove mXSS vectors, processing instructions and risky comments */
9950
+ if (_isUnsafeNode(currentNode, tagName)) {
9311
9951
  _forceRemove(currentNode);
9312
9952
  return true;
9313
9953
  }
9314
9954
  /* Remove element if anything forbids its presence */
9315
9955
  if (FORBID_TAGS[tagName] || !(EXTRA_ELEMENT_HANDLING.tagCheck instanceof Function && EXTRA_ELEMENT_HANDLING.tagCheck(tagName)) && !ALLOWED_TAGS[tagName]) {
9316
- /* Check if we have a custom element to handle */
9317
- if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {
9318
- if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {
9319
- return false;
9320
- }
9321
- if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) {
9322
- return false;
9323
- }
9324
- }
9325
- /* Keep content except for bad-listed elements */
9326
- if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
9327
- const parentNode = getParentNode(currentNode) || currentNode.parentNode;
9328
- const childNodes = getChildNodes(currentNode) || currentNode.childNodes;
9329
- if (childNodes && parentNode) {
9330
- const childCount = childNodes.length;
9331
- for (let i = childCount - 1; i >= 0; --i) {
9332
- const childClone = cloneNode(childNodes[i], true);
9333
- childClone.__removalCount = (currentNode.__removalCount || 0) + 1;
9334
- parentNode.insertBefore(childClone, getNextSibling(currentNode));
9335
- }
9336
- }
9337
- }
9338
- _forceRemove(currentNode);
9339
- return true;
9956
+ return _sanitizeDisallowedNode(currentNode, tagName);
9340
9957
  }
9341
- /* Check whether element has a valid namespace */
9342
- if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {
9958
+ /* Check whether element has a valid namespace.
9959
+ Realm-safe check (GHSA-hpcv-96wg-7vj8): use the cached Node.prototype
9960
+ nodeType getter rather than `instanceof Element`, which is realm-
9961
+ bound and short-circuits to false for any node minted in a different
9962
+ realm — letting a foreign-realm element with a forbidden namespace
9963
+ slip past the namespace check entirely. */
9964
+ const nt = getNodeType ? getNodeType(currentNode) : currentNode.nodeType;
9965
+ if (nt === NODE_TYPE.element && !_checkValidNamespace(currentNode)) {
9343
9966
  _forceRemove(currentNode);
9344
9967
  return true;
9345
9968
  }
9346
9969
  /* Make sure that older browsers don't get fallback-tag mXSS */
9347
- if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(/<\/no(script|embed|frames)/i, currentNode.innerHTML)) {
9970
+ if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(FALLBACK_TAG_CLOSE, currentNode.innerHTML)) {
9348
9971
  _forceRemove(currentNode);
9349
9972
  return true;
9350
9973
  }
9351
9974
  /* Sanitize element content to be template-safe */
9352
9975
  if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) {
9353
9976
  /* Get the element's text content */
9354
- content = currentNode.textContent;
9355
- arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
9356
- content = stringReplace(content, expr, ' ');
9357
- });
9977
+ const content = _stripTemplateExpressions(currentNode.textContent);
9358
9978
  if (currentNode.textContent !== content) {
9359
9979
  arrayPush(DOMPurify.removed, {
9360
9980
  element: currentNode.cloneNode()
@@ -9384,11 +10004,12 @@
9384
10004
  if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {
9385
10005
  return false;
9386
10006
  }
10007
+ const nameIsPermitted = ALLOWED_ATTR[lcName] || EXTRA_ELEMENT_HANDLING.attributeCheck instanceof Function && EXTRA_ELEMENT_HANDLING.attributeCheck(lcName, lcTag);
9387
10008
  /* Allow valid data-* attributes: At least one character after "-"
9388
10009
  (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
9389
10010
  XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)
9390
10011
  We don't need to check the value; it's always URI safe. */
9391
- 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]) {
10012
+ if (ALLOW_DATA_ATTR && regExpTest(DATA_ATTR$1, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR$1, lcName)) ; else if (!nameIsPermitted) {
9392
10013
  if (
9393
10014
  // First condition does a very basic check if a) it's basically a valid custom element tagname AND
9394
10015
  // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
@@ -9400,11 +10021,15 @@
9400
10021
  return false;
9401
10022
  }
9402
10023
  /* Check value is safe. First, is attr inert? If so, is safe */
9403
- } 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) {
10024
+ } 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) {
9404
10025
  return false;
9405
10026
  } else ;
9406
10027
  return true;
9407
10028
  };
10029
+ /* Names the HTML spec reserves from valid-custom-element-name; these must
10030
+ * never be treated as basic custom elements even when a permissive
10031
+ * CUSTOM_ELEMENT_HANDLING.tagNameCheck is configured. */
10032
+ 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']);
9408
10033
  /**
9409
10034
  * _isBasicCustomElement
9410
10035
  * checks if at least one dash is included in tagName, and it's not the first char
@@ -9414,7 +10039,64 @@
9414
10039
  * @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false.
9415
10040
  */
9416
10041
  const _isBasicCustomElement = function _isBasicCustomElement(tagName) {
9417
- return tagName !== 'annotation-xml' && stringMatch(tagName, CUSTOM_ELEMENT);
10042
+ return !RESERVED_CUSTOM_ELEMENT_NAMES[stringToLowerCase(tagName)] && regExpTest(CUSTOM_ELEMENT$1, tagName);
10043
+ };
10044
+ /**
10045
+ * Wrap an attribute value in the matching Trusted Types object when
10046
+ * the active policy requires it. Namespaced attributes pass through
10047
+ * unchanged (no TT support yet, see
10048
+ * https://bugs.chromium.org/p/chromium/issues/detail?id=1305293).
10049
+ *
10050
+ * @param lcTag lowercase tag name of the containing element
10051
+ * @param lcName lowercase attribute name
10052
+ * @param namespaceURI the attribute's namespace, if any
10053
+ * @param value the attribute value to wrap
10054
+ * @return the value, wrapped when Trusted Types demand it
10055
+ */
10056
+ const _applyTrustedTypesToAttribute = function _applyTrustedTypesToAttribute(lcTag, lcName, namespaceURI, value) {
10057
+ if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function' && !namespaceURI) {
10058
+ switch (trustedTypes.getAttributeType(lcTag, lcName)) {
10059
+ case 'TrustedHTML':
10060
+ {
10061
+ return _createTrustedHTML(value);
10062
+ }
10063
+ case 'TrustedScriptURL':
10064
+ {
10065
+ return _createTrustedScriptURL(value);
10066
+ }
10067
+ }
10068
+ }
10069
+ return value;
10070
+ };
10071
+ /**
10072
+ * Write a modified attribute value back onto the element. On
10073
+ * success, re-probe for clobbering introduced by the new value and
10074
+ * remove the element when found; otherwise pop the removal entry
10075
+ * recorded by the earlier _removeAttribute (long-standing pairing
10076
+ * with the SANITIZE_NAMED_PROPS path - do not "fix" casually). On
10077
+ * failure, remove the attribute instead.
10078
+ *
10079
+ * @param currentNode the element carrying the attribute
10080
+ * @param name the attribute name as present on the element
10081
+ * @param namespaceURI the attribute's namespace, if any
10082
+ * @param value the new attribute value
10083
+ */
10084
+ const _setAttributeValue = function _setAttributeValue(currentNode, name, namespaceURI, value) {
10085
+ try {
10086
+ if (namespaceURI) {
10087
+ currentNode.setAttributeNS(namespaceURI, name, value);
10088
+ } else {
10089
+ /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
10090
+ currentNode.setAttribute(name, value);
10091
+ }
10092
+ if (_isClobbered(currentNode)) {
10093
+ _forceRemove(currentNode);
10094
+ } else {
10095
+ arrayPop(DOMPurify.removed);
10096
+ }
10097
+ } catch (_) {
10098
+ _removeAttribute(name, currentNode);
10099
+ }
9418
10100
  };
9419
10101
  /**
9420
10102
  * _sanitizeAttributes
@@ -9429,9 +10111,7 @@
9429
10111
  const _sanitizeAttributes = function _sanitizeAttributes(currentNode) {
9430
10112
  /* Execute a hook if present */
9431
10113
  _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null);
9432
- const {
9433
- attributes
9434
- } = currentNode;
10114
+ const attributes = currentNode.attributes;
9435
10115
  /* Check if we have attributes; if not we might have a text node */
9436
10116
  if (!attributes || _isClobbered(currentNode)) {
9437
10117
  return;
@@ -9444,14 +10124,13 @@
9444
10124
  forceKeepAttr: undefined
9445
10125
  };
9446
10126
  let l = attributes.length;
10127
+ const lcTag = transformCaseFunc(currentNode.nodeName);
9447
10128
  /* Go backwards over all attributes; safely remove bad ones */
9448
10129
  while (l--) {
9449
10130
  const attr = attributes[l];
9450
- const {
9451
- name,
9452
- namespaceURI,
9453
- value: attrValue
9454
- } = attr;
10131
+ const name = attr.name,
10132
+ namespaceURI = attr.namespaceURI,
10133
+ attrValue = attr.value;
9455
10134
  const lcName = transformCaseFunc(name);
9456
10135
  const initValue = attrValue;
9457
10136
  let value = name === 'value' ? initValue : stringTrim(initValue);
@@ -9465,12 +10144,14 @@
9465
10144
  /* Full DOM Clobbering protection via namespace isolation,
9466
10145
  * Prefix id and name attributes with `user-content-`
9467
10146
  */
9468
- if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name')) {
10147
+ if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name') && stringIndexOf(value, SANITIZE_NAMED_PROPS_PREFIX) !== 0) {
9469
10148
  // Remove the attribute with this value
9470
10149
  _removeAttribute(name, currentNode);
9471
10150
  // Prefix the value and later re-create the attribute with the sanitized value
9472
10151
  value = SANITIZE_NAMED_PROPS_PREFIX + value;
9473
10152
  }
10153
+ // Else: already prefixed, leave the attribute alone — the prefix is
10154
+ // itself the clobbering protection, and re-applying it is incorrect.
9474
10155
  /* Work around a security issue with comments inside attributes */
9475
10156
  if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i, value)) {
9476
10157
  _removeAttribute(name, currentNode);
@@ -9481,7 +10162,7 @@
9481
10162
  _removeAttribute(name, currentNode);
9482
10163
  continue;
9483
10164
  }
9484
- /* Did the hooks approve of the attribute? */
10165
+ /* Did the hooks force-keep the attribute? */
9485
10166
  if (hookEvent.forceKeepAttr) {
9486
10167
  continue;
9487
10168
  }
@@ -9491,56 +10172,24 @@
9491
10172
  continue;
9492
10173
  }
9493
10174
  /* Work around a security issue in jQuery 3.0 */
9494
- if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) {
10175
+ if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(SELF_CLOSING_TAG, value)) {
9495
10176
  _removeAttribute(name, currentNode);
9496
10177
  continue;
9497
10178
  }
9498
10179
  /* Sanitize attribute content to be template-safe */
9499
10180
  if (SAFE_FOR_TEMPLATES) {
9500
- arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
9501
- value = stringReplace(value, expr, ' ');
9502
- });
10181
+ value = _stripTemplateExpressions(value);
9503
10182
  }
9504
10183
  /* Is `value` valid for this attribute? */
9505
- const lcTag = transformCaseFunc(currentNode.nodeName);
9506
10184
  if (!_isValidAttribute(lcTag, lcName, value)) {
9507
10185
  _removeAttribute(name, currentNode);
9508
10186
  continue;
9509
10187
  }
9510
10188
  /* Handle attributes that require Trusted Types */
9511
- if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function') {
9512
- if (namespaceURI) ; else {
9513
- switch (trustedTypes.getAttributeType(lcTag, lcName)) {
9514
- case 'TrustedHTML':
9515
- {
9516
- value = trustedTypesPolicy.createHTML(value);
9517
- break;
9518
- }
9519
- case 'TrustedScriptURL':
9520
- {
9521
- value = trustedTypesPolicy.createScriptURL(value);
9522
- break;
9523
- }
9524
- }
9525
- }
9526
- }
10189
+ value = _applyTrustedTypesToAttribute(lcTag, lcName, namespaceURI, value);
9527
10190
  /* Handle invalid data-* attribute set by try-catching it */
9528
10191
  if (value !== initValue) {
9529
- try {
9530
- if (namespaceURI) {
9531
- currentNode.setAttributeNS(namespaceURI, name, value);
9532
- } else {
9533
- /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
9534
- currentNode.setAttribute(name, value);
9535
- }
9536
- if (_isClobbered(currentNode)) {
9537
- _forceRemove(currentNode);
9538
- } else {
9539
- arrayPop(DOMPurify.removed);
9540
- }
9541
- } catch (_) {
9542
- _removeAttribute(name, currentNode);
9543
- }
10192
+ _setAttributeValue(currentNode, name, namespaceURI, value);
9544
10193
  }
9545
10194
  }
9546
10195
  /* Execute a hook if present */
@@ -9563,14 +10212,133 @@
9563
10212
  _sanitizeElements(shadowNode);
9564
10213
  /* Check attributes next */
9565
10214
  _sanitizeAttributes(shadowNode);
9566
- /* Deep shadow DOM detected */
9567
- if (shadowNode.content instanceof DocumentFragment) {
10215
+ /* Deep shadow DOM detected.
10216
+ Realm-safe check (GHSA-hpcv-96wg-7vj8): use nodeType against the
10217
+ DOCUMENT_FRAGMENT_NODE constant rather than instanceof, so we
10218
+ recurse into <template>.content from foreign realms too. */
10219
+ if (_isDocumentFragment(shadowNode.content)) {
9568
10220
  _sanitizeShadowDOM2(shadowNode.content);
9569
10221
  }
10222
+ /* An element iterated here may itself host an attached
10223
+ shadow root. The default NodeIterator does not enter shadow
10224
+ trees, so a shadow root nested inside template.content was
10225
+ previously reached by no walk at all (the pre-pass at
10226
+ _sanitizeAttachedShadowRoots descends via childNodes, which
10227
+ doesn't enter template.content; the template-content recursion
10228
+ above iterates the content but never inspected shadowRoot).
10229
+ Walk it explicitly. The nodeType guard avoids reading
10230
+ shadowRoot off text / comment / CDATA / PI nodes that the
10231
+ iterator also surfaces. */
10232
+ const shadowNodeType = getNodeType ? getNodeType(shadowNode) : shadowNode.nodeType;
10233
+ if (shadowNodeType === NODE_TYPE.element) {
10234
+ const innerSr = getShadowRoot(shadowNode);
10235
+ if (_isDocumentFragment(innerSr)) {
10236
+ _sanitizeAttachedShadowRoots(innerSr);
10237
+ _sanitizeShadowDOM2(innerSr);
10238
+ }
10239
+ }
9570
10240
  }
9571
10241
  /* Execute a hook if present */
9572
10242
  _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null);
9573
10243
  };
10244
+ /**
10245
+ * _sanitizeAttachedShadowRoots
10246
+ *
10247
+ * Walks `root` and feeds every attached shadow root we encounter into
10248
+ * the existing _sanitizeShadowDOM pipeline. The default node iterator
10249
+ * does not descend into shadow trees, so nodes inside an attached
10250
+ * shadow root would otherwise be skipped entirely.
10251
+ *
10252
+ * Two real input paths put attached shadow roots in front of us:
10253
+ * 1. IN_PLACE on a DOM node that already has shadow roots attached.
10254
+ * 2. DOM-node input where importNode(dirty, true) deep-clones the
10255
+ * shadow root because it was created with `clonable: true`.
10256
+ *
10257
+ * This pass runs once, up front, so the main iteration loop (and the
10258
+ * existing _sanitizeShadowDOM template-content recursion) stay
10259
+ * untouched — string-input paths are not affected.
10260
+ *
10261
+ * @param root the subtree root to walk for attached shadow roots
10262
+ */
10263
+ const _sanitizeAttachedShadowRoots = function _sanitizeAttachedShadowRoots(root) {
10264
+ /* Iterative (explicit stack) rather than per-child recursion. DOM APIs
10265
+ impose no depth cap, so an attacker-shaped tree (JSON/CRDT/editor data
10266
+ built straight into the DOM — the IN_PLACE surface) deeper than the JS
10267
+ call-stack budget would otherwise overflow native recursion here and
10268
+ throw at the IN_PLACE entry pre-pass, before a single node is
10269
+ sanitized, leaving the caller's live tree untouched (fail-open). See
10270
+ campaign-3 F4. A heap stack keeps depth off the call stack.
10271
+ Each work item is either a node to descend into, or a deferred
10272
+ `_sanitizeShadowDOM` for an already-walked shadow root. The deferred
10273
+ form preserves the original post-order discipline: a shadow root's
10274
+ nested shadow roots are discovered before the outer shadow is
10275
+ sanitized (which may remove hosts). Pushes are in reverse of the
10276
+ desired processing order (LIFO): template content, then children, then
10277
+ the shadow-sanitize, then the shadow walk — so the order matches the
10278
+ previous recursion exactly. */
10279
+ const stack = [{
10280
+ node: root,
10281
+ shadow: null
10282
+ }];
10283
+ while (stack.length > 0) {
10284
+ const item = stack.pop();
10285
+ /* Deferred shadow-DOM sanitisation: runs after its subtree was walked. */
10286
+ if (item.shadow) {
10287
+ _sanitizeShadowDOM2(item.shadow);
10288
+ continue;
10289
+ }
10290
+ const node = item.node;
10291
+ const nodeType = getNodeType ? getNodeType(node) : node.nodeType;
10292
+ const isElement = nodeType === NODE_TYPE.element;
10293
+ /* (pushed last → processed first) Children, snapshotted in reverse so
10294
+ the first child is processed first. Snapshotting matters because a
10295
+ hook may detach siblings mid-walk. */
10296
+ const childNodes = getChildNodes(node);
10297
+ if (childNodes) {
10298
+ for (let i = childNodes.length - 1; i >= 0; --i) {
10299
+ stack.push({
10300
+ node: childNodes[i],
10301
+ shadow: null
10302
+ });
10303
+ }
10304
+ }
10305
+ /* (pushed before children → processed after them, matching the old
10306
+ "template content last" order) When the node is a <template>,
10307
+ descend into its content. */
10308
+ if (isElement) {
10309
+ const rootName = getNodeName ? getNodeName(node) : null;
10310
+ if (typeof rootName === 'string' && transformCaseFunc(rootName) === 'template') {
10311
+ const content = node.content;
10312
+ if (_isDocumentFragment(content)) {
10313
+ stack.push({
10314
+ node: content,
10315
+ shadow: null
10316
+ });
10317
+ }
10318
+ }
10319
+ }
10320
+ /* Shadow root (processed first): walk its subtree, then sanitise it.
10321
+ Realm-safe check (GHSA-hpcv-96wg-7vj8): nodeType-based detection
10322
+ rather than `instanceof DocumentFragment`, which is realm-bound and
10323
+ silently skipped foreign-realm shadow roots (e.g.
10324
+ iframe.contentDocument attachShadow). */
10325
+ if (isElement) {
10326
+ const sr = getShadowRoot(node);
10327
+ if (_isDocumentFragment(sr)) {
10328
+ /* Push the deferred sanitise first so it pops after the shadow
10329
+ walk we push next, i.e. nested shadow roots are discovered
10330
+ before this one is sanitised. */
10331
+ stack.push({
10332
+ node: null,
10333
+ shadow: sr
10334
+ }, {
10335
+ node: sr,
10336
+ shadow: null
10337
+ });
10338
+ }
10339
+ }
10340
+ }
10341
+ };
9574
10342
  // eslint-disable-next-line complexity
9575
10343
  DOMPurify.sanitize = function (dirty) {
9576
10344
  let cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
@@ -9587,13 +10355,9 @@
9587
10355
  }
9588
10356
  /* Stringify, in case dirty is an object */
9589
10357
  if (typeof dirty !== 'string' && !_isNode(dirty)) {
9590
- if (typeof dirty.toString === 'function') {
9591
- dirty = dirty.toString();
9592
- if (typeof dirty !== 'string') {
9593
- throw typeErrorCreate('dirty is not a string, aborting');
9594
- }
9595
- } else {
9596
- throw typeErrorCreate('toString is not a function');
10358
+ dirty = stringifyValue(dirty);
10359
+ if (typeof dirty !== 'string') {
10360
+ throw typeErrorCreate('dirty is not a string, aborting');
9597
10361
  }
9598
10362
  }
9599
10363
  /* Return dirty HTML if DOMPurify cannot run */
@@ -9601,24 +10365,78 @@
9601
10365
  return dirty;
9602
10366
  }
9603
10367
  /* Assign config vars */
9604
- if (!SET_CONFIG) {
10368
+ if (SET_CONFIG) {
10369
+ /* Persistent setConfig() path: _parseConfig is skipped, so the sets are
10370
+ * not re-derived per call. Restore them from the pristine bindings
10371
+ * captured at setConfig() time so a previous call's hook clone (mutated
10372
+ * below) does not carry over. */
10373
+ ALLOWED_TAGS = SET_CONFIG_ALLOWED_TAGS;
10374
+ ALLOWED_ATTR = SET_CONFIG_ALLOWED_ATTR;
10375
+ } else {
9605
10376
  _parseConfig(cfg);
9606
10377
  }
10378
+ /* Clone the hook-mutable allowlists before the walk whenever an
10379
+ * uponSanitize* hook is registered. The hook event exposes ALLOWED_TAGS
10380
+ * and ALLOWED_ATTR by reference (as allowedTags / allowedAttributes), so
10381
+ * a hook that widens them would otherwise mutate the shared set
10382
+ * permanently: across later calls and across every element. Cloning per
10383
+ * walk keeps documented in-call widening working while scoping it to the
10384
+ * call. A single guard for both config paths - the per-call path rebinds
10385
+ * the sets in _parseConfig each call, the persistent path restores them
10386
+ * from the captured bindings just above - so the two cannot diverge. */
10387
+ if (hooks.uponSanitizeElement.length > 0 || hooks.uponSanitizeAttribute.length > 0) {
10388
+ ALLOWED_TAGS = clone(ALLOWED_TAGS);
10389
+ }
10390
+ if (hooks.uponSanitizeAttribute.length > 0) {
10391
+ ALLOWED_ATTR = clone(ALLOWED_ATTR);
10392
+ }
9607
10393
  /* Clean up removed elements */
9608
10394
  DOMPurify.removed = [];
9609
- /* Check if dirty is correctly typed for IN_PLACE */
9610
- if (typeof dirty === 'string') {
9611
- IN_PLACE = false;
9612
- }
9613
- if (IN_PLACE) {
9614
- /* Do some early pre-sanitization to avoid unsafe root nodes */
9615
- if (dirty.nodeName) {
9616
- const tagName = transformCaseFunc(dirty.nodeName);
10395
+ /* Resolve IN_PLACE for this call without mutating persistent config.
10396
+ Writing the IN_PLACE closure variable here leaks under setConfig(),
10397
+ where _parseConfig is skipped on later calls: a single string call would
10398
+ disable in-place mode for every subsequent node call, returning a
10399
+ sanitized copy while leaving the caller's node — which in-place callers
10400
+ keep using and whose return value they ignore — unsanitized. REPORT-2. */
10401
+ const inPlace = IN_PLACE && typeof dirty !== 'string' && _isNode(dirty);
10402
+ if (inPlace) {
10403
+ /* Do some early pre-sanitization to avoid unsafe root nodes.
10404
+ Read nodeName through the cached prototype getter — a clobbering
10405
+ child named "nodeName" on the form root would otherwise shadow
10406
+ the property and let this check skip the root-allowlist
10407
+ validation entirely. */
10408
+ const nn = getNodeName ? getNodeName(dirty) : dirty.nodeName;
10409
+ if (typeof nn === 'string') {
10410
+ const tagName = transformCaseFunc(nn);
9617
10411
  if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
9618
10412
  throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');
9619
10413
  }
9620
10414
  }
9621
- } else if (dirty instanceof Node) {
10415
+ /* Pre-flight the root through _isClobbered. The iterator-driven
10416
+ removal path can not detach a parent-less root: _forceRemove
10417
+ falls through to Element.prototype.remove(), which per spec
10418
+ is a no-op on a node with no parent. A clobbered root would
10419
+ then survive the main loop with its attributes uninspected,
10420
+ because _sanitizeAttributes early-returns on _isClobbered. The
10421
+ result would be an attacker-controlled form, complete with any
10422
+ event-handler attributes the caller passed in, handed back to
10423
+ the application unsanitized. Refuse to sanitize such a root
10424
+ the same way we refuse a forbidden tag. GHSA-r47g-fvhr-h676. */
10425
+ if (_isClobbered(dirty)) {
10426
+ throw typeErrorCreate('root node is clobbered and cannot be sanitized in-place');
10427
+ }
10428
+ /* Sanitize attached shadow roots before the main iterator runs.
10429
+ The iterator does not descend into shadow trees. Same fail-closed
10430
+ barrier as the main walk (campaign-3 F2): a custom-element reaction
10431
+ inside a shadow root could abort this pre-pass before the walk runs,
10432
+ which would otherwise leave the entire live tree unsanitized. */
10433
+ try {
10434
+ _sanitizeAttachedShadowRoots(dirty);
10435
+ } catch (error) {
10436
+ _neutralizeRoot(dirty);
10437
+ throw error;
10438
+ }
10439
+ } else if (_isNode(dirty)) {
9622
10440
  /* If dirty is a DOM element, append to an empty document to avoid
9623
10441
  elements being stripped by the parser */
9624
10442
  body = _initDocument('<!---->');
@@ -9632,12 +10450,18 @@
9632
10450
  // eslint-disable-next-line unicorn/prefer-dom-node-append
9633
10451
  body.appendChild(importedNode);
9634
10452
  }
10453
+ /* Clonable shadow roots are deep-cloned by importNode(); sanitize
10454
+ them before the main iterator runs, since the iterator does not
10455
+ descend into shadow trees. The walk routes every read through a
10456
+ cached prototype getter so clobbering descendants on a form root
10457
+ cannot hide a shadow host from this pass. */
10458
+ _sanitizeAttachedShadowRoots(importedNode);
9635
10459
  } else {
9636
10460
  /* Exit directly if we have nothing to do */
9637
10461
  if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT &&
9638
10462
  // eslint-disable-next-line unicorn/prefer-includes
9639
10463
  dirty.indexOf('<') === -1) {
9640
- return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;
10464
+ return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? _createTrustedHTML(dirty) : dirty;
9641
10465
  }
9642
10466
  /* Initialize the document to work on */
9643
10467
  body = _initDocument(dirty);
@@ -9651,31 +10475,59 @@
9651
10475
  _forceRemove(body.firstChild);
9652
10476
  }
9653
10477
  /* Get node iterator */
9654
- const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body);
9655
- /* Now start iterating over the created document */
9656
- while (currentNode = nodeIterator.nextNode()) {
9657
- /* Sanitize tags and elements */
9658
- _sanitizeElements(currentNode);
9659
- /* Check attributes next */
9660
- _sanitizeAttributes(currentNode);
9661
- /* Shadow DOM detected, sanitize it */
9662
- if (currentNode.content instanceof DocumentFragment) {
9663
- _sanitizeShadowDOM2(currentNode.content);
10478
+ const nodeIterator = _createNodeIterator(inPlace ? dirty : body);
10479
+ /* Now start iterating over the created document.
10480
+ The walk runs inside an exception barrier (campaign-3 F2): a re-entrant
10481
+ engine/custom-element mutation can detach a node mid-walk so
10482
+ `_forceRemove`'s parentless guard throws, aborting the loop. Without the
10483
+ barrier the caller's in-place tree would be left half-sanitized with the
10484
+ unvisited tail still armed. On any throw we fail closed — strip the
10485
+ in-place root bare — then rethrow so the existing throw contract is
10486
+ preserved. (String/DOM-copy paths never return the partial body, so the
10487
+ propagating throw is already fail-closed there.) */
10488
+ try {
10489
+ while (currentNode = nodeIterator.nextNode()) {
10490
+ /* Sanitize tags and elements */
10491
+ _sanitizeElements(currentNode);
10492
+ /* Check attributes next */
10493
+ _sanitizeAttributes(currentNode);
10494
+ /* Shadow DOM detected, sanitize it.
10495
+ Realm-safe check (GHSA-hpcv-96wg-7vj8): nodeType-based detection
10496
+ instead of instanceof, so foreign-realm <template>.content is
10497
+ walked correctly. */
10498
+ if (_isDocumentFragment(currentNode.content)) {
10499
+ _sanitizeShadowDOM2(currentNode.content);
10500
+ }
9664
10501
  }
10502
+ } catch (error) {
10503
+ if (inPlace) {
10504
+ _neutralizeRoot(dirty);
10505
+ }
10506
+ throw error;
9665
10507
  }
9666
10508
  /* If we sanitized `dirty` in-place, return it. */
9667
- if (IN_PLACE) {
10509
+ if (inPlace) {
10510
+ /* Fail-closed completion of the audit-5 F1 fix: every node removed from
10511
+ the caller's live tree is detached but may still hold a queued
10512
+ resource-event handler that fires in page scope after we return. The
10513
+ move-hoist covers only disallowed-tag KEEP_CONTENT removals; strip the
10514
+ non-allow-listed attributes off every other removed subtree (clobber,
10515
+ mXSS, namespace, comments, KEEP_CONTENT:false, …) so those handlers are
10516
+ cancelled before any event can fire. Runs synchronously, pre-return. */
10517
+ arrayForEach(DOMPurify.removed, entry => {
10518
+ if (entry.element) {
10519
+ _neutralizeSubtree(entry.element);
10520
+ }
10521
+ });
10522
+ if (SAFE_FOR_TEMPLATES) {
10523
+ _scrubTemplateExpressions2(dirty);
10524
+ }
9668
10525
  return dirty;
9669
10526
  }
9670
10527
  /* Return sanitized string or DOM */
9671
10528
  if (RETURN_DOM) {
9672
10529
  if (SAFE_FOR_TEMPLATES) {
9673
- body.normalize();
9674
- let html = body.innerHTML;
9675
- arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
9676
- html = stringReplace(html, expr, ' ');
9677
- });
9678
- body.innerHTML = html;
10530
+ _scrubTemplateExpressions2(body);
9679
10531
  }
9680
10532
  if (RETURN_DOM_FRAGMENT) {
9681
10533
  returnNode = createDocumentFragment.call(body.ownerDocument);
@@ -9705,20 +10557,28 @@
9705
10557
  }
9706
10558
  /* Sanitize final string template-safe */
9707
10559
  if (SAFE_FOR_TEMPLATES) {
9708
- arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
9709
- serializedHTML = stringReplace(serializedHTML, expr, ' ');
9710
- });
10560
+ serializedHTML = _stripTemplateExpressions(serializedHTML);
9711
10561
  }
9712
- return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;
10562
+ return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? _createTrustedHTML(serializedHTML) : serializedHTML;
9713
10563
  };
9714
10564
  DOMPurify.setConfig = function () {
9715
10565
  let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
9716
10566
  _parseConfig(cfg);
9717
10567
  SET_CONFIG = true;
10568
+ SET_CONFIG_ALLOWED_TAGS = ALLOWED_TAGS;
10569
+ SET_CONFIG_ALLOWED_ATTR = ALLOWED_ATTR;
9718
10570
  };
9719
10571
  DOMPurify.clearConfig = function () {
9720
10572
  CONFIG = null;
9721
10573
  SET_CONFIG = false;
10574
+ SET_CONFIG_ALLOWED_TAGS = null;
10575
+ SET_CONFIG_ALLOWED_ATTR = null;
10576
+ // Drop any caller-supplied Trusted Types policy so it cannot poison later
10577
+ // `RETURN_TRUSTED_TYPE` output. The internal default policy (cached, and
10578
+ // never recreated — Trusted Types throws on duplicate names) is restored by
10579
+ // the next `_parseConfig`. See GHSA-vxr8-fq34-vvx9.
10580
+ trustedTypesPolicy = defaultTrustedTypesPolicy;
10581
+ emptyHTML = '';
9722
10582
  };
9723
10583
  DOMPurify.isValidAttribute = function (tag, attr, value) {
9724
10584
  /* Initialize shared config vars if necessary. */
@@ -9733,9 +10593,19 @@
9733
10593
  if (typeof hookFunction !== 'function') {
9734
10594
  return;
9735
10595
  }
10596
+ /* Reject unknown entry points. Without this, a non-hook key (e.g.
10597
+ * '__proto__') indexes off the prototype chain rather than a real
10598
+ * hook array, and arrayPush then writes to Object.prototype. Guard
10599
+ * with an own-property check against the known hook names. */
10600
+ if (!objectHasOwnProperty(hooks, entryPoint)) {
10601
+ return;
10602
+ }
9736
10603
  arrayPush(hooks[entryPoint], hookFunction);
9737
10604
  };
9738
10605
  DOMPurify.removeHook = function (entryPoint, hookFunction) {
10606
+ if (!objectHasOwnProperty(hooks, entryPoint)) {
10607
+ return undefined;
10608
+ }
9739
10609
  if (hookFunction !== undefined) {
9740
10610
  const index = arrayLastIndexOf(hooks[entryPoint], hookFunction);
9741
10611
  return index === -1 ? undefined : arraySplice(hooks[entryPoint], index, 1)[0];
@@ -9743,6 +10613,9 @@
9743
10613
  return arrayPop(hooks[entryPoint]);
9744
10614
  };
9745
10615
  DOMPurify.removeHooks = function (entryPoint) {
10616
+ if (!objectHasOwnProperty(hooks, entryPoint)) {
10617
+ return;
10618
+ }
9746
10619
  hooks[entryPoint] = [];
9747
10620
  };
9748
10621
  DOMPurify.removeAllHooks = function () {
@@ -10003,10 +10876,26 @@
10003
10876
  }(Background);
10004
10877
 
10005
10878
  /**
10006
- * Generate a unique id compatible with HTML element id
10879
+ * Generate a unique id compatible with HTML element id.
10880
+ * Uses the Web Crypto API for cryptographically strong randomness, with a
10881
+ * deterministic fallback only when crypto is unavailable.
10007
10882
  */
10008
10883
  function getUniqueId() {
10009
- return Math.random().toString(36).replace(/[^a-z]+/g, '').substr(2, 10);
10884
+ var letters = 'abcdefghijklmnopqrstuvwxyz';
10885
+ var length = 10;
10886
+ var bytes = new Uint8Array(length);
10887
+ if (typeof crypto !== 'undefined' && typeof crypto.getRandomValues === 'function') {
10888
+ crypto.getRandomValues(bytes);
10889
+ } else {
10890
+ for (var i = 0; i < length; i++) {
10891
+ bytes[i] = (i * 31 + 7) % 256;
10892
+ }
10893
+ }
10894
+ var id = '';
10895
+ for (var _i = 0; _i < length; _i++) {
10896
+ id += letters[bytes[_i] % letters.length];
10897
+ }
10898
+ return id;
10010
10899
  }
10011
10900
 
10012
10901
  function getFlypayV2Button(widgetId) {
@@ -19138,6 +20027,90 @@
19138
20027
  EVENT["ON_SHIPPING_OPTIONS_CHANGE"] = "onShippingOptionsChange";
19139
20028
  })(EVENT$1 || (EVENT$1 = {}));
19140
20029
 
20030
+ /** TTL for a cached service configuration: 1 day, in milliseconds. */
20031
+ var CACHE_TTL_MS = 86400000;
20032
+ /** Builds the `localStorage` key used to cache a service's configuration. */
20033
+ function serviceConfigStorageKey(serviceId) {
20034
+ return "paydock-serviceConfig-".concat(serviceId);
20035
+ }
20036
+ /**
20037
+ * Removes the cached service configuration for the given service ID, forcing the next
20038
+ * fetch to go to the network. Called on error / unavailable flows so a potentially
20039
+ * stale cached config is not reused after something changed server-side. No-throw when
20040
+ * `localStorage` is unavailable.
20041
+ *
20042
+ * @param serviceId - The service ID whose cached configuration should be cleared.
20043
+ */
20044
+ function clearServiceConfigCache(serviceId) {
20045
+ try {
20046
+ localStorage.removeItem(serviceConfigStorageKey(serviceId));
20047
+ } catch (_error) {
20048
+ // localStorage may be unavailable; nothing to clear
20049
+ }
20050
+ }
20051
+ /**
20052
+ * Fetches the wallet service configuration, backed by a 1-day `localStorage` cache
20053
+ * keyed on the service ID. Falls back gracefully (no caching) when `localStorage`
20054
+ * is unavailable (e.g. private browsing). Shared by the instance `load()` flow and
20055
+ * the static availability checks so both reuse the same cached fetch.
20056
+ *
20057
+ * @param api - The configured API client (env must already be set).
20058
+ * @param serviceId - The service ID to fetch the configuration for.
20059
+ * @returns The service configuration response.
20060
+ */
20061
+ function getServiceConfigCached(api, serviceId) {
20062
+ return __awaiter(this, void 0, void 0, /*#__PURE__*/_regenerator().m(function _callee() {
20063
+ var storageKey, cachedData, _JSON$parse, data, timestamp, serviceConfigResponse, encodedData;
20064
+ return _regenerator().w(function (_context) {
20065
+ while (1) switch (_context.p = _context.n) {
20066
+ case 0:
20067
+ storageKey = serviceConfigStorageKey(serviceId);
20068
+ _context.p = 1;
20069
+ cachedData = localStorage.getItem(storageKey);
20070
+ if (!cachedData) {
20071
+ _context.n = 5;
20072
+ break;
20073
+ }
20074
+ _context.p = 2;
20075
+ _JSON$parse = JSON.parse(atob(cachedData)), data = _JSON$parse.data, timestamp = _JSON$parse.timestamp;
20076
+ if (!(Date.now() - timestamp < CACHE_TTL_MS)) {
20077
+ _context.n = 3;
20078
+ break;
20079
+ }
20080
+ return _context.a(2, JSON.parse(data));
20081
+ case 3:
20082
+ _context.n = 5;
20083
+ break;
20084
+ case 4:
20085
+ _context.p = 4;
20086
+ _context.v;
20087
+ localStorage.removeItem(storageKey);
20088
+ case 5:
20089
+ _context.n = 7;
20090
+ break;
20091
+ case 6:
20092
+ _context.p = 6;
20093
+ _context.v;
20094
+ case 7:
20095
+ _context.n = 8;
20096
+ return api.service().getConfig(serviceId);
20097
+ case 8:
20098
+ serviceConfigResponse = _context.v;
20099
+ try {
20100
+ encodedData = btoa(JSON.stringify({
20101
+ data: JSON.stringify(serviceConfigResponse),
20102
+ timestamp: Date.now()
20103
+ }));
20104
+ localStorage.setItem(storageKey, encodedData);
20105
+ } catch (_error) {
20106
+ // localStorage may be unavailable; proceed without caching
20107
+ }
20108
+ return _context.a(2, serviceConfigResponse);
20109
+ }
20110
+ }, _callee, null, [[2, 4], [1, 6]]);
20111
+ }));
20112
+ }
20113
+
19141
20114
  /**
19142
20115
  * @classdesc Abstract base class for Open Wallet buttons. **Do not instantiate directly.**
19143
20116
  * Use {@link ApplePayOpenWalletButton} or {@link GooglePayOpenWalletButton} instead.
@@ -19171,10 +20144,30 @@
19171
20144
  this.api = new ApiInternal(publicKeyOrAccessToken, this.getApiAuthType(publicKeyOrAccessToken));
19172
20145
  this.serviceId = serviceId;
19173
20146
  this.meta = meta;
20147
+ this.registerCacheInvalidationOnError();
19174
20148
  this.validateBaseMeta();
19175
20149
  this.validateWalletMeta();
19176
20150
  }
20151
+ /**
20152
+ * Invalidates the cached service configuration whenever an error or unavailable
20153
+ * event fires, so the next `load()` re-fetches a fresh config. The cache is keyed
20154
+ * on the service ID with a 1-day TTL; clearing it on failure means a config that
20155
+ * changed server-side (and caused the failure) is not reused until the TTL expires.
20156
+ * Registered once per button, independently of any merchant-registered handlers.
20157
+ *
20158
+ * @private
20159
+ */
19177
20160
  return _createClass(OpenWalletButtons, [{
20161
+ key: "registerCacheInvalidationOnError",
20162
+ value: function registerCacheInvalidationOnError() {
20163
+ var _this = this;
20164
+ var invalidate = function invalidate() {
20165
+ return clearServiceConfigCache(_this.serviceId);
20166
+ };
20167
+ this.eventEmitter.subscribe(EVENT$1.ERROR, invalidate);
20168
+ this.eventEmitter.subscribe(EVENT$1.UNAVAILABLE, invalidate);
20169
+ }
20170
+ }, {
19178
20171
  key: "getApiAuthType",
19179
20172
  value: function getApiAuthType(publicKeyOrAccessToken) {
19180
20173
  if (AccessToken.validateJWT(publicKeyOrAccessToken)) {
@@ -19208,57 +20201,7 @@
19208
20201
  }, {
19209
20202
  key: "getOpenWalletServiceConfig",
19210
20203
  value: function getOpenWalletServiceConfig() {
19211
- return __awaiter(this, void 0, void 0, /*#__PURE__*/_regenerator().m(function _callee() {
19212
- var storageKey, cachedData, _JSON$parse, data, timestamp, oneDay, serviceConfigResponse, encodedData;
19213
- return _regenerator().w(function (_context) {
19214
- while (1) switch (_context.p = _context.n) {
19215
- case 0:
19216
- storageKey = "serviceConfig-".concat(this.serviceId);
19217
- _context.p = 1;
19218
- cachedData = localStorage.getItem(storageKey);
19219
- if (!cachedData) {
19220
- _context.n = 5;
19221
- break;
19222
- }
19223
- _context.p = 2;
19224
- _JSON$parse = JSON.parse(atob(cachedData)), data = _JSON$parse.data, timestamp = _JSON$parse.timestamp;
19225
- oneDay = 86400000;
19226
- if (!(Date.now() - timestamp < oneDay)) {
19227
- _context.n = 3;
19228
- break;
19229
- }
19230
- return _context.a(2, JSON.parse(data));
19231
- case 3:
19232
- _context.n = 5;
19233
- break;
19234
- case 4:
19235
- _context.p = 4;
19236
- _context.v;
19237
- localStorage.removeItem(storageKey);
19238
- case 5:
19239
- _context.n = 7;
19240
- break;
19241
- case 6:
19242
- _context.p = 6;
19243
- _context.v;
19244
- case 7:
19245
- _context.n = 8;
19246
- return this.api.service().getConfig(this.serviceId);
19247
- case 8:
19248
- serviceConfigResponse = _context.v;
19249
- try {
19250
- encodedData = btoa(JSON.stringify({
19251
- data: JSON.stringify(serviceConfigResponse),
19252
- timestamp: Date.now()
19253
- }));
19254
- localStorage.setItem(storageKey, encodedData);
19255
- } catch (_error) {
19256
- // localStorage may be unavailable; proceed without caching
19257
- }
19258
- return _context.a(2, serviceConfigResponse);
19259
- }
19260
- }, _callee, this, [[2, 4], [1, 6]]);
19261
- }));
20204
+ return getServiceConfigCached(this.api, this.serviceId);
19262
20205
  }
19263
20206
  }, {
19264
20207
  key: "handleOnError",
@@ -19293,13 +20236,13 @@
19293
20236
  }, {
19294
20237
  key: "load",
19295
20238
  value: function load() {
19296
- var _this = this;
20239
+ var _this2 = this;
19297
20240
  this.getOpenWalletServiceConfig().then(function (serviceConfig) {
19298
- _this.validateServiceType(serviceConfig);
19299
- _this.walletService = _this.createWalletService(serviceConfig);
19300
- _this.walletService.load();
20241
+ _this2.validateServiceType(serviceConfig);
20242
+ _this2.walletService = _this2.createWalletService(serviceConfig);
20243
+ _this2.walletService.load();
19301
20244
  })["catch"](function (error) {
19302
- _this.handleOnError(error instanceof Error ? error : new Error(String(error)), exports.ERROR_OPERATION.CONFIGURATION);
20245
+ _this2.handleOnError(error instanceof Error ? error : new Error(String(error)), exports.ERROR_OPERATION.CONFIGURATION);
19303
20246
  });
19304
20247
  }
19305
20248
  /**
@@ -19497,28 +20440,28 @@
19497
20440
  }, {
19498
20441
  key: "onSuccess",
19499
20442
  value: function onSuccess(handler) {
19500
- var _this2 = this;
20443
+ var _this3 = this;
19501
20444
  if (typeof handler === 'function') {
19502
20445
  this.eventEmitter.subscribe(EVENT$1.SUCCESS, function (data) {
19503
- return __awaiter(_this2, void 0, void 0, /*#__PURE__*/_regenerator().m(function _callee2() {
19504
- var _t3;
19505
- return _regenerator().w(function (_context2) {
19506
- while (1) switch (_context2.p = _context2.n) {
20446
+ return __awaiter(_this3, void 0, void 0, /*#__PURE__*/_regenerator().m(function _callee() {
20447
+ var _t;
20448
+ return _regenerator().w(function (_context) {
20449
+ while (1) switch (_context.p = _context.n) {
19507
20450
  case 0:
19508
- _context2.p = 0;
19509
- _context2.n = 1;
20451
+ _context.p = 0;
20452
+ _context.n = 1;
19510
20453
  return handler(data);
19511
20454
  case 1:
19512
- _context2.n = 3;
20455
+ _context.n = 3;
19513
20456
  break;
19514
20457
  case 2:
19515
- _context2.p = 2;
19516
- _t3 = _context2.v;
19517
- console.warn('Merchant onSuccess handler threw (swallowed):', _t3);
20458
+ _context.p = 2;
20459
+ _t = _context.v;
20460
+ console.warn('Merchant onSuccess handler threw (swallowed):', _t);
19518
20461
  case 3:
19519
- return _context2.a(2);
20462
+ return _context.a(2);
19520
20463
  }
19521
- }, _callee2, null, [[0, 2]]);
20464
+ }, _callee, null, [[0, 2]]);
19522
20465
  }));
19523
20466
  });
19524
20467
  return;
@@ -19549,28 +20492,28 @@
19549
20492
  }, {
19550
20493
  key: "onUnavailable",
19551
20494
  value: function onUnavailable(handler) {
19552
- var _this3 = this;
20495
+ var _this4 = this;
19553
20496
  if (typeof handler === 'function') {
19554
20497
  this.eventEmitter.subscribe(EVENT$1.UNAVAILABLE, function (data) {
19555
- return __awaiter(_this3, void 0, void 0, /*#__PURE__*/_regenerator().m(function _callee3() {
19556
- var _t4;
19557
- return _regenerator().w(function (_context3) {
19558
- while (1) switch (_context3.p = _context3.n) {
20498
+ return __awaiter(_this4, void 0, void 0, /*#__PURE__*/_regenerator().m(function _callee2() {
20499
+ var _t2;
20500
+ return _regenerator().w(function (_context2) {
20501
+ while (1) switch (_context2.p = _context2.n) {
19559
20502
  case 0:
19560
- _context3.p = 0;
19561
- _context3.n = 1;
20503
+ _context2.p = 0;
20504
+ _context2.n = 1;
19562
20505
  return handler(data);
19563
20506
  case 1:
19564
- _context3.n = 3;
20507
+ _context2.n = 3;
19565
20508
  break;
19566
20509
  case 2:
19567
- _context3.p = 2;
19568
- _t4 = _context3.v;
19569
- console.warn('Merchant onUnavailable handler threw (swallowed):', _t4);
20510
+ _context2.p = 2;
20511
+ _t2 = _context2.v;
20512
+ console.warn('Merchant onUnavailable handler threw (swallowed):', _t2);
19570
20513
  case 3:
19571
- return _context3.a(2);
20514
+ return _context2.a(2);
19572
20515
  }
19573
- }, _callee3, null, [[0, 2]]);
20516
+ }, _callee2, null, [[0, 2]]);
19574
20517
  }));
19575
20518
  });
19576
20519
  return;
@@ -19602,28 +20545,28 @@
19602
20545
  }, {
19603
20546
  key: "onError",
19604
20547
  value: function onError(handler) {
19605
- var _this4 = this;
20548
+ var _this5 = this;
19606
20549
  if (typeof handler === 'function') {
19607
20550
  this.eventEmitter.subscribe(EVENT$1.ERROR, function (data) {
19608
- return __awaiter(_this4, void 0, void 0, /*#__PURE__*/_regenerator().m(function _callee4() {
19609
- var _t5;
19610
- return _regenerator().w(function (_context4) {
19611
- while (1) switch (_context4.p = _context4.n) {
20551
+ return __awaiter(_this5, void 0, void 0, /*#__PURE__*/_regenerator().m(function _callee3() {
20552
+ var _t3;
20553
+ return _regenerator().w(function (_context3) {
20554
+ while (1) switch (_context3.p = _context3.n) {
19612
20555
  case 0:
19613
- _context4.p = 0;
19614
- _context4.n = 1;
20556
+ _context3.p = 0;
20557
+ _context3.n = 1;
19615
20558
  return handler(data);
19616
20559
  case 1:
19617
- _context4.n = 3;
20560
+ _context3.n = 3;
19618
20561
  break;
19619
20562
  case 2:
19620
- _context4.p = 2;
19621
- _t5 = _context4.v;
19622
- console.warn('Merchant onError handler threw (swallowed):', _t5);
20563
+ _context3.p = 2;
20564
+ _t3 = _context3.v;
20565
+ console.warn('Merchant onError handler threw (swallowed):', _t3);
19623
20566
  case 3:
19624
- return _context4.a(2);
20567
+ return _context3.a(2);
19625
20568
  }
19626
- }, _callee4, null, [[0, 2]]);
20569
+ }, _callee3, null, [[0, 2]]);
19627
20570
  }));
19628
20571
  });
19629
20572
  return;
@@ -19654,28 +20597,28 @@
19654
20597
  }, {
19655
20598
  key: "onCancel",
19656
20599
  value: function onCancel(handler) {
19657
- var _this5 = this;
20600
+ var _this6 = this;
19658
20601
  if (typeof handler === 'function') {
19659
20602
  this.eventEmitter.subscribe(EVENT$1.CHECKOUT_CLOSE, function (data) {
19660
- return __awaiter(_this5, void 0, void 0, /*#__PURE__*/_regenerator().m(function _callee5() {
19661
- var _t6;
19662
- return _regenerator().w(function (_context5) {
19663
- while (1) switch (_context5.p = _context5.n) {
20603
+ return __awaiter(_this6, void 0, void 0, /*#__PURE__*/_regenerator().m(function _callee4() {
20604
+ var _t4;
20605
+ return _regenerator().w(function (_context4) {
20606
+ while (1) switch (_context4.p = _context4.n) {
19664
20607
  case 0:
19665
- _context5.p = 0;
19666
- _context5.n = 1;
20608
+ _context4.p = 0;
20609
+ _context4.n = 1;
19667
20610
  return handler(data);
19668
20611
  case 1:
19669
- _context5.n = 3;
20612
+ _context4.n = 3;
19670
20613
  break;
19671
20614
  case 2:
19672
- _context5.p = 2;
19673
- _t6 = _context5.v;
19674
- console.warn('Merchant onCancel handler threw (swallowed):', _t6);
20615
+ _context4.p = 2;
20616
+ _t4 = _context4.v;
20617
+ console.warn('Merchant onCancel handler threw (swallowed):', _t4);
19675
20618
  case 3:
19676
- return _context5.a(2);
20619
+ return _context4.a(2);
19677
20620
  }
19678
- }, _callee5, null, [[0, 2]]);
20621
+ }, _callee4, null, [[0, 2]]);
19679
20622
  }));
19680
20623
  });
19681
20624
  return;
@@ -19699,28 +20642,28 @@
19699
20642
  }, {
19700
20643
  key: "onLoaded",
19701
20644
  value: function onLoaded(handler) {
19702
- var _this6 = this;
20645
+ var _this7 = this;
19703
20646
  if (typeof handler === 'function') {
19704
20647
  this.eventEmitter.subscribe(EVENT$1.LOADED, function (data) {
19705
- return __awaiter(_this6, void 0, void 0, /*#__PURE__*/_regenerator().m(function _callee6() {
19706
- var _t7;
19707
- return _regenerator().w(function (_context6) {
19708
- while (1) switch (_context6.p = _context6.n) {
20648
+ return __awaiter(_this7, void 0, void 0, /*#__PURE__*/_regenerator().m(function _callee5() {
20649
+ var _t5;
20650
+ return _regenerator().w(function (_context5) {
20651
+ while (1) switch (_context5.p = _context5.n) {
19709
20652
  case 0:
19710
- _context6.p = 0;
19711
- _context6.n = 1;
20653
+ _context5.p = 0;
20654
+ _context5.n = 1;
19712
20655
  return handler(data);
19713
20656
  case 1:
19714
- _context6.n = 3;
20657
+ _context5.n = 3;
19715
20658
  break;
19716
20659
  case 2:
19717
- _context6.p = 2;
19718
- _t7 = _context6.v;
19719
- console.warn('Merchant onLoaded handler threw (swallowed):', _t7);
20660
+ _context5.p = 2;
20661
+ _t5 = _context5.v;
20662
+ console.warn('Merchant onLoaded handler threw (swallowed):', _t5);
19720
20663
  case 3:
19721
- return _context6.a(2);
20664
+ return _context5.a(2);
19722
20665
  }
19723
- }, _callee6, null, [[0, 2]]);
20666
+ }, _callee5, null, [[0, 2]]);
19724
20667
  }));
19725
20668
  });
19726
20669
  return;
@@ -20068,7 +21011,143 @@
20068
21011
  WALLET_TYPES["GOOGLE_PAY"] = "google";
20069
21012
  })(exports.WALLET_TYPES || (exports.WALLET_TYPES = {}));
20070
21013
 
20071
- var DEFAULT_APPLE_PAY_CAPABILITIES$1 = ['paymentCredentialsAvailable'];
21014
+ /** CDN location of Apple's web SDK (provides the `<apple-pay-button>` web component). */
21015
+ var APPLE_PAY_SDK_URL = 'https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js';
21016
+ /**
21017
+ * Statuses that count as available when the merchant does not override them.
21018
+ * Includes `paymentCredentialStatusUnknown` so the button is shown in third-party /
21019
+ * cross-device (QR) browsers, per Apple's guidance.
21020
+ */
21021
+ var DEFAULT_APPLE_PAY_CAPABILITIES$1 = ['paymentCredentialsAvailable', 'paymentCredentialStatusUnknown'];
21022
+ /**
21023
+ * Maps the SDK's friendly capability tokens to Apple's `PaymentCredentialStatus` values.
21024
+ * Unknown tokens are passed through unchanged.
21025
+ */
21026
+ function formatCapabilities(capabilities) {
21027
+ var fieldMap = {
21028
+ credentials_available: 'paymentCredentialsAvailable',
21029
+ credentials_status_unknown: 'paymentCredentialStatusUnknown',
21030
+ credentials_unavailable: 'paymentCredentialsUnavailable'
21031
+ };
21032
+ return capabilities.map(function (capability) {
21033
+ return fieldMap[capability] || capability;
21034
+ });
21035
+ }
21036
+ /**
21037
+ * Synchronous, network-free check for a **native, same-device** Apple Pay session
21038
+ * (`window.ApplePaySession` exists and `canMakePayments()` is `true`). Safe to call in
21039
+ * any environment (never throws).
21040
+ *
21041
+ * Note: this is a legacy/Safari-oriented signal. It is **not** authoritative for
21042
+ * cross-browser / cross-device (QR) availability — in Chrome/Edge/Firefox
21043
+ * `window.ApplePaySession` is supplied by the CDN SDK and may be absent until it loads,
21044
+ * and the cross-device flow is reflected by `applePayCapabilities()`, not this call.
21045
+ * Use {@link evaluateApplePayAvailability} for the authoritative, cross-browser answer.
21046
+ */
21047
+ function hasNativeApplePaySession() {
21048
+ try {
21049
+ return typeof window !== 'undefined' && !!window.ApplePaySession && typeof ApplePaySession !== 'undefined' && ApplePaySession.canMakePayments();
21050
+ } catch (_a) {
21051
+ return false;
21052
+ }
21053
+ }
21054
+ var sdkLoadPromise = null;
21055
+ /**
21056
+ * Idempotently loads Apple's web SDK from the CDN.
21057
+ * Resolves immediately if the `<apple-pay-button>` custom element is already
21058
+ * registered, and de-duplicates concurrent loads. Rejects if the script fails to load.
21059
+ */
21060
+ function loadApplePaySdk() {
21061
+ if (typeof customElements !== 'undefined' && customElements.get('apple-pay-button')) {
21062
+ return Promise.resolve();
21063
+ }
21064
+ if (sdkLoadPromise) {
21065
+ return sdkLoadPromise;
21066
+ }
21067
+ sdkLoadPromise = new Promise(function (resolve, reject) {
21068
+ var script = document.createElement('script');
21069
+ script.src = APPLE_PAY_SDK_URL;
21070
+ script.type = 'text/javascript';
21071
+ script.crossOrigin = 'anonymous';
21072
+ script.onload = function () {
21073
+ return resolve();
21074
+ };
21075
+ script.onerror = function () {
21076
+ // Allow a future retry after a transient failure.
21077
+ sdkLoadPromise = null;
21078
+ reject(new Error('Failed to load Apple Pay script'));
21079
+ };
21080
+ document.head.appendChild(script);
21081
+ });
21082
+ return sdkLoadPromise;
21083
+ }
21084
+ /**
21085
+ * Core Apple Pay availability evaluation, shared by the instance flow
21086
+ * (`ApplePayOpenWalletService`) and the static `ApplePayOpenWalletButton.checkAvailability`.
21087
+ *
21088
+ * Assumes the Apple Pay SDK is already loaded (call {@link loadApplePaySdk} first).
21089
+ */
21090
+ function evaluateApplePayAvailability(params) {
21091
+ return __awaiter(this, void 0, void 0, /*#__PURE__*/_regenerator().m(function _callee() {
21092
+ var _a, hasNativeSession, allowed, capabilities, paymentCredentialStatus, available;
21093
+ return _regenerator().w(function (_context) {
21094
+ while (1) switch (_context.p = _context.n) {
21095
+ case 0:
21096
+ if (!(typeof window === 'undefined' || !window.ApplePaySession)) {
21097
+ _context.n = 1;
21098
+ break;
21099
+ }
21100
+ return _context.a(2, {
21101
+ available: false,
21102
+ supported: false,
21103
+ has_native_session: false,
21104
+ reason: 'unsupported_browser'
21105
+ });
21106
+ case 1:
21107
+ hasNativeSession = hasNativeApplePaySession();
21108
+ allowed = ((_a = params.apple_pay_capabilities) === null || _a === void 0 ? void 0 : _a.length) ? formatCapabilities(params.apple_pay_capabilities) : DEFAULT_APPLE_PAY_CAPABILITIES$1;
21109
+ _context.p = 2;
21110
+ _context.n = 3;
21111
+ return ApplePaySession.applePayCapabilities(params.merchantId);
21112
+ case 3:
21113
+ capabilities = _context.v;
21114
+ paymentCredentialStatus = capabilities === null || capabilities === void 0 ? void 0 : capabilities.paymentCredentialStatus; // `applePayCapabilities` is authoritative: trust an explicit `applePayUnsupported`
21115
+ // (e.g. an unregistered/misconfigured merchant) rather than overriding it with the
21116
+ // coarse `canMakePayments()` signal.
21117
+ if (!(paymentCredentialStatus === 'applePayUnsupported')) {
21118
+ _context.n = 4;
21119
+ break;
21120
+ }
21121
+ return _context.a(2, {
21122
+ available: false,
21123
+ supported: false,
21124
+ has_native_session: hasNativeSession,
21125
+ payment_credential_status: paymentCredentialStatus,
21126
+ reason: 'unsupported_browser'
21127
+ });
21128
+ case 4:
21129
+ available = allowed.includes(paymentCredentialStatus);
21130
+ return _context.a(2, {
21131
+ available: available,
21132
+ supported: true,
21133
+ has_native_session: hasNativeSession,
21134
+ payment_credential_status: paymentCredentialStatus,
21135
+ reason: available ? undefined : 'no_credentials'
21136
+ });
21137
+ case 5:
21138
+ _context.p = 5;
21139
+ _context.v;
21140
+ return _context.a(2, {
21141
+ available: false,
21142
+ supported: hasNativeSession,
21143
+ has_native_session: hasNativeSession,
21144
+ reason: 'query_failed'
21145
+ });
21146
+ }
21147
+ }, _callee, null, [[2, 5]]);
21148
+ }));
21149
+ }
21150
+
20072
21151
  /**
20073
21152
  * Apple Pay implementation of the OpenWallet service.
20074
21153
  *
@@ -20344,7 +21423,6 @@
20344
21423
  value: function load() {
20345
21424
  return __awaiter(this, void 0, void 0, /*#__PURE__*/_regenerator().m(function _callee3() {
20346
21425
  var _this4 = this;
20347
- var applePayScript;
20348
21426
  return _regenerator().w(function (_context3) {
20349
21427
  while (1) switch (_context3.n) {
20350
21428
  case 0:
@@ -20355,26 +21433,12 @@
20355
21433
  this.handleOnUnavailable('Promises not supported');
20356
21434
  return _context3.a(2);
20357
21435
  case 1:
20358
- if (!(customElements === null || customElements === void 0 ? void 0 : customElements.get('apple-pay-button'))) {
20359
- _context3.n = 2;
20360
- break;
20361
- }
20362
- this.onScriptLoaded();
20363
- return _context3.a(2);
20364
- case 2:
20365
- applePayScript = document.createElement('script');
20366
- applePayScript.src = 'https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js';
20367
- applePayScript.type = 'text/javascript';
20368
- applePayScript.crossOrigin = 'anonymous';
20369
- applePayScript.onload = function () {
21436
+ loadApplePaySdk().then(function () {
20370
21437
  _this4.onScriptLoaded();
20371
- };
20372
- applePayScript.onerror = function () {
21438
+ })["catch"](function () {
20373
21439
  _this4.handleOnUnavailable('Failed to load Apple Pay script');
20374
- return;
20375
- };
20376
- document.head.appendChild(applePayScript);
20377
- case 3:
21440
+ });
21441
+ case 2:
20378
21442
  return _context3.a(2);
20379
21443
  }
20380
21444
  }, _callee3, this);
@@ -20402,26 +21466,22 @@
20402
21466
  }, {
20403
21467
  key: "checkAvailability",
20404
21468
  value: function checkAvailability() {
20405
- var _this6 = this;
20406
- return new Promise(function (resolve) {
20407
- var _a;
20408
- if (!window.ApplePaySession || !ApplePaySession) {
20409
- return resolve(false);
20410
- }
20411
- var formattedCapabilities = DEFAULT_APPLE_PAY_CAPABILITIES$1;
20412
- if (((_a = _this6.meta.apple_pay_capabilities) === null || _a === void 0 ? void 0 : _a.length) > 0) {
20413
- formattedCapabilities = _this6.formatCapabilities(_this6.meta.apple_pay_capabilities);
20414
- }
20415
- ApplePaySession.applePayCapabilities(_this6.getMerchantId()).then(function (capabilities) {
20416
- if (_this6.isUnsuportedBrowser(capabilities)) {
20417
- return resolve(ApplePaySession.canMakePayments());
21469
+ return __awaiter(this, void 0, void 0, /*#__PURE__*/_regenerator().m(function _callee4() {
21470
+ var result;
21471
+ return _regenerator().w(function (_context4) {
21472
+ while (1) switch (_context4.n) {
21473
+ case 0:
21474
+ _context4.n = 1;
21475
+ return evaluateApplePayAvailability({
21476
+ merchantId: this.getMerchantId(),
21477
+ apple_pay_capabilities: this.meta.apple_pay_capabilities
21478
+ });
21479
+ case 1:
21480
+ result = _context4.v;
21481
+ return _context4.a(2, result.available);
20418
21482
  }
20419
- var allowedCapability = formattedCapabilities.includes(capabilities === null || capabilities === void 0 ? void 0 : capabilities.paymentCredentialStatus);
20420
- return resolve(allowedCapability);
20421
- })["catch"](function () {
20422
- resolve(false);
20423
- });
20424
- });
21483
+ }, _callee4, this);
21484
+ }));
20425
21485
  }
20426
21486
  }, {
20427
21487
  key: "mount",
@@ -20447,7 +21507,7 @@
20447
21507
  }, {
20448
21508
  key: "onApplePayButtonClicked",
20449
21509
  value: function onApplePayButtonClicked() {
20450
- var _this7 = this;
21510
+ var _this6 = this;
20451
21511
  if (this.isButtonDisabled()) {
20452
21512
  return;
20453
21513
  }
@@ -20466,26 +21526,27 @@
20466
21526
  // As part of PAYCA-2065 we detect that the paymentSession.onvalidatemerchant is not
20467
21527
  // executed if the browser is not safari. In that case, we handle it outside the
20468
21528
  // actual merchant validation function.
20469
- var isIOS = /iPhone|iPad|iPod/.test(navigator.userAgent);
20470
- var isDesktopRequestIOS = navigator.maxTouchPoints > 1 && /Macintosh/.test(navigator.userAgent);
21529
+ var userAgent = navigator.userAgent || '';
21530
+ var isIOS = userAgent.includes('iPhone') || userAgent.includes('iPad') || userAgent.includes('iPod');
21531
+ var isDesktopRequestIOS = navigator.maxTouchPoints > 1 && userAgent.includes('Macintosh');
20471
21532
  if (!window.safari && !isIOS && !isDesktopRequestIOS) {
20472
21533
  this.handleMerchantOnButtonClickEvent()["catch"](function (err) {
20473
21534
  console.error('Error while processing merchant callback', err);
20474
- _this7.paymentSession.abort();
21535
+ _this6.paymentSession.abort();
20475
21536
  });
20476
21537
  }
20477
21538
  }
20478
21539
  }, {
20479
21540
  key: "getMerchantSession",
20480
21541
  value: function getMerchantSession() {
20481
- var _this8 = this;
21542
+ var _this7 = this;
20482
21543
  return new Promise(function (resolve, reject) {
20483
- return _this8.api.paymentSource().createSession(_extends({
20484
- service_id: _this8.serviceId,
21544
+ return _this7.api.paymentSource().createSession(_extends({
21545
+ service_id: _this7.serviceId,
20485
21546
  session_id: window.location.hostname,
20486
- store_name: _this8.meta.store_name
20487
- }, _this8.isShippingRequired() && {
20488
- request_shipping: _this8.meta.request_shipping
21547
+ store_name: _this7.meta.store_name
21548
+ }, _this7.isShippingRequired() && {
21549
+ request_shipping: _this7.meta.request_shipping
20489
21550
  })).then(function (res) {
20490
21551
  resolve(res);
20491
21552
  })["catch"](function (err) {
@@ -20496,42 +21557,30 @@
20496
21557
  }, {
20497
21558
  key: "handleMerchantOnButtonClickEvent",
20498
21559
  value: function handleMerchantOnButtonClickEvent() {
20499
- return __awaiter(this, void 0, void 0, /*#__PURE__*/_regenerator().m(function _callee4() {
21560
+ return __awaiter(this, void 0, void 0, /*#__PURE__*/_regenerator().m(function _callee5() {
20500
21561
  var results;
20501
- return _regenerator().w(function (_context4) {
20502
- while (1) switch (_context4.n) {
21562
+ return _regenerator().w(function (_context5) {
21563
+ while (1) switch (_context5.n) {
20503
21564
  case 0:
20504
- _context4.n = 1;
21565
+ _context5.n = 1;
20505
21566
  return this.eventEmitter.emitWithResult(EVENT$1.ON_CLICK, {
20506
21567
  event: EVENT$1.ON_CLICK
20507
21568
  });
20508
21569
  case 1:
20509
- results = _context4.v;
21570
+ results = _context5.v;
20510
21571
  if (!results.some(function (r) {
20511
21572
  return r === false;
20512
21573
  })) {
20513
- _context4.n = 2;
21574
+ _context5.n = 2;
20514
21575
  break;
20515
21576
  }
20516
21577
  throw new Error('onClick handler aborted the payment flow');
20517
21578
  case 2:
20518
- return _context4.a(2);
21579
+ return _context5.a(2);
20519
21580
  }
20520
- }, _callee4, this);
21581
+ }, _callee5, this);
20521
21582
  }));
20522
21583
  }
20523
- }, {
20524
- key: "formatCapabilities",
20525
- value: function formatCapabilities(capabilities) {
20526
- var fieldMap = {
20527
- credentials_available: 'paymentCredentialsAvailable',
20528
- credentials_status_unknown: 'paymentCredentialStatusUnknown',
20529
- credentials_unavailable: 'paymentCredentialsUnavailable'
20530
- };
20531
- return capabilities.map(function (capability) {
20532
- return fieldMap[capability] || capability;
20533
- });
20534
- }
20535
21584
  }, {
20536
21585
  key: "formatErrorFields",
20537
21586
  value: function formatErrorFields(error) {
@@ -20698,11 +21747,6 @@
20698
21747
  applePayLaterAvailability: this.meta.apple_pay_later_availability
20699
21748
  });
20700
21749
  }
20701
- }, {
20702
- key: "isUnsuportedBrowser",
20703
- value: function isUnsuportedBrowser(capabilities) {
20704
- return (capabilities === null || capabilities === void 0 ? void 0 : capabilities.paymentCredentialStatus) === 'applePayUnsupported';
20705
- }
20706
21750
  }]);
20707
21751
  }(OpenWalletService);
20708
21752
 
@@ -20751,17 +21795,57 @@
20751
21795
  return _this;
20752
21796
  }
20753
21797
  /**
20754
- * Validates Apple Pay-specific required metadata fields.
20755
- * Apple Pay requires `amount_label` and `store_name` to be present and strings.
21798
+ * Checks Apple Pay availability **without instantiating the button** — the single,
21799
+ * authoritative, cross-browser-aware availability entry point.
20756
21800
  *
20757
- * @private
20758
- * @throws {Error} If `amount_label` is missing or not a string.
20759
- * @throws {Error} If `store_name` is missing or not a string.
21801
+ * Resolves the merchant identifier (either supplied directly or fetched from the
21802
+ * service configuration), loads Apple's web SDK if needed, then queries
21803
+ * `ApplePaySession.applePayCapabilities()`. Returns a convenience `available` verdict
21804
+ * (computed against `apple_pay_capabilities`), the raw device-reported
21805
+ * `payment_credential_status`, and `has_native_session` so callers can infer the transport:
21806
+ * `available && has_native_session` ⇒ native sheet likely; `available && !has_native_session`
21807
+ * ⇒ cross-device / QR handoff likely.
21808
+ *
21809
+ * Pass `{ sync: true }` for a cheap, network-free native same-device pre-check that
21810
+ * resolves immediately (see {@link ApplePayAvailabilityOptions.sync}).
21811
+ *
21812
+ * @param {ApplePayAvailabilityOptions} [options] - Merchant context, allowed capabilities, and mode.
21813
+ * @returns {Promise<ApplePayAvailabilityResult>} The availability result.
21814
+ *
21815
+ * @example
21816
+ * // Lightest path — no network, when you already know the merchant identifier:
21817
+ * const result = await ApplePayOpenWalletButton.checkAvailability({ merchant_id });
21818
+ *
21819
+ * @example
21820
+ * // Resolve the merchant identifier from the service configuration:
21821
+ * const result = await ApplePayOpenWalletButton.checkAvailability({
21822
+ * public_key_or_access_token,
21823
+ * service_id,
21824
+ * env: 'sandbox',
21825
+ * });
21826
+ * if (result.available) {
21827
+ * // Render the Apple Pay button (native sheet or cross-device QR, per has_native_session).
21828
+ * } else {
21829
+ * console.log('Unavailable:', result.reason, result.payment_credential_status);
21830
+ * }
21831
+ *
21832
+ * @example
21833
+ * // Synchronous native-only fast check (no network / SDK load):
21834
+ * const { has_native_session } = await ApplePayOpenWalletButton.checkAvailability({ sync: true });
20760
21835
  */
20761
21836
  _inherits(ApplePayOpenWalletButton, _OpenWalletButtons);
20762
21837
  return _createClass(ApplePayOpenWalletButton, [{
20763
21838
  key: "validateWalletMeta",
20764
- value: function validateWalletMeta() {
21839
+ value:
21840
+ /**
21841
+ * Validates Apple Pay-specific required metadata fields.
21842
+ * Apple Pay requires `amount_label` and `store_name` to be present and strings.
21843
+ *
21844
+ * @private
21845
+ * @throws {Error} If `amount_label` is missing or not a string.
21846
+ * @throws {Error} If `store_name` is missing or not a string.
21847
+ */
21848
+ function validateWalletMeta() {
20765
21849
  if (typeof this.meta.amount_label !== 'string' || this.meta.amount_label.trim() === '') {
20766
21850
  throw new Error("meta.amount_label is required for Apple Pay and must be a non-empty string (e.g. 'TOTAL').");
20767
21851
  }
@@ -20795,6 +21879,114 @@
20795
21879
  value: function createWalletService(serviceConfig) {
20796
21880
  return new ApplePayOpenWalletService(this.api, this.eventEmitter, this.serviceId, this.container, this.meta, serviceConfig);
20797
21881
  }
21882
+ }], [{
21883
+ key: "checkAvailability",
21884
+ value: function checkAvailability() {
21885
+ return __awaiter(this, arguments, void 0, function () {
21886
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
21887
+ return /*#__PURE__*/_regenerator().m(function _callee() {
21888
+ var hasNativeSession, merchantId, authType, api, serviceConfig;
21889
+ return _regenerator().w(function (_context) {
21890
+ while (1) switch (_context.p = _context.n) {
21891
+ case 0:
21892
+ hasNativeSession = hasNativeApplePaySession();
21893
+ if (!options.sync) {
21894
+ _context.n = 1;
21895
+ break;
21896
+ }
21897
+ return _context.a(2, {
21898
+ available: hasNativeSession,
21899
+ supported: hasNativeSession,
21900
+ has_native_session: hasNativeSession,
21901
+ reason: hasNativeSession ? undefined : 'no_native_session'
21902
+ });
21903
+ case 1:
21904
+ merchantId = options.merchant_id;
21905
+ if (merchantId) {
21906
+ _context.n = 6;
21907
+ break;
21908
+ }
21909
+ if (!(!options.public_key_or_access_token || !options.service_id)) {
21910
+ _context.n = 2;
21911
+ break;
21912
+ }
21913
+ return _context.a(2, {
21914
+ available: false,
21915
+ supported: hasNativeSession,
21916
+ has_native_session: hasNativeSession,
21917
+ reason: 'missing_merchant_id'
21918
+ });
21919
+ case 2:
21920
+ _context.p = 2;
21921
+ authType = AccessToken.validateJWT(options.public_key_or_access_token) ? API_AUTH_TYPE.TOKEN : API_AUTH_TYPE.PUBLIC_KEY;
21922
+ api = new ApiInternal(options.public_key_or_access_token, authType);
21923
+ if (options.env) {
21924
+ api.setEnv(options.env);
21925
+ }
21926
+ _context.n = 3;
21927
+ return getServiceConfigCached(api, options.service_id);
21928
+ case 3:
21929
+ serviceConfig = _context.v;
21930
+ if (!(serviceConfig.type !== SERVICE_TYPES.APPLE_PAY)) {
21931
+ _context.n = 4;
21932
+ break;
21933
+ }
21934
+ return _context.a(2, {
21935
+ available: false,
21936
+ supported: hasNativeSession,
21937
+ has_native_session: hasNativeSession,
21938
+ reason: 'service_type_mismatch'
21939
+ });
21940
+ case 4:
21941
+ merchantId = serviceConfig.merchant;
21942
+ _context.n = 6;
21943
+ break;
21944
+ case 5:
21945
+ _context.p = 5;
21946
+ _context.v;
21947
+ return _context.a(2, {
21948
+ available: false,
21949
+ supported: hasNativeSession,
21950
+ has_native_session: hasNativeSession,
21951
+ reason: 'config_fetch_failed'
21952
+ });
21953
+ case 6:
21954
+ if (merchantId) {
21955
+ _context.n = 7;
21956
+ break;
21957
+ }
21958
+ return _context.a(2, {
21959
+ available: false,
21960
+ supported: hasNativeSession,
21961
+ has_native_session: hasNativeSession,
21962
+ reason: 'missing_merchant_id'
21963
+ });
21964
+ case 7:
21965
+ _context.p = 7;
21966
+ _context.n = 8;
21967
+ return loadApplePaySdk();
21968
+ case 8:
21969
+ _context.n = 10;
21970
+ break;
21971
+ case 9:
21972
+ _context.p = 9;
21973
+ _context.v;
21974
+ return _context.a(2, {
21975
+ available: false,
21976
+ supported: hasNativeSession,
21977
+ has_native_session: hasNativeSession,
21978
+ reason: 'sdk_load_failed'
21979
+ });
21980
+ case 10:
21981
+ return _context.a(2, evaluateApplePayAvailability({
21982
+ merchantId: merchantId,
21983
+ apple_pay_capabilities: options.apple_pay_capabilities
21984
+ }));
21985
+ }
21986
+ }, _callee, null, [[7, 9], [2, 5]]);
21987
+ })();
21988
+ });
21989
+ }
20798
21990
  }]);
20799
21991
  }(OpenWalletButtons);
20800
21992
 
@@ -20831,6 +22023,137 @@
20831
22023
  SHIPPING_OPTION: EVENT$1.ON_SHIPPING_OPTIONS_CHANGE
20832
22024
  });
20833
22025
 
22026
+ /**
22027
+ * Synchronous, network-free check for whether the Google Pay JS API is already present
22028
+ * in the page (`window.google.payments.api.PaymentsClient`). Safe to call in any
22029
+ * environment (never throws).
22030
+ *
22031
+ * Note: Google Pay has no synchronous device/card capability API — this only reports
22032
+ * whether the SDK script has loaded. The authoritative readiness signal comes from
22033
+ * {@link evaluateGooglePayAvailability} (which runs `isReadyToPay`).
22034
+ */
22035
+ function isGooglePayApiPresent() {
22036
+ var _a, _b, _c;
22037
+ try {
22038
+ 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);
22039
+ } catch (_d) {
22040
+ return false;
22041
+ }
22042
+ }
22043
+ var scriptLoadPromise = null;
22044
+ /**
22045
+ * Idempotently loads the Google Pay JS SDK from the CDN.
22046
+ * Resolves immediately if the API is already present, de-duplicates concurrent loads,
22047
+ * and rejects if the script fails to load.
22048
+ */
22049
+ function loadGooglePayScript() {
22050
+ if (isGooglePayApiPresent()) {
22051
+ return Promise.resolve();
22052
+ }
22053
+ if (scriptLoadPromise) {
22054
+ return scriptLoadPromise;
22055
+ }
22056
+ scriptLoadPromise = new Promise(function (resolve, reject) {
22057
+ var script = document.createElement('script');
22058
+ script.type = 'text/javascript';
22059
+ script.src = GOOGLE_PAY_SCRIPT_URL;
22060
+ script.async = true;
22061
+ script.onload = function () {
22062
+ if (!isGooglePayApiPresent()) {
22063
+ scriptLoadPromise = null;
22064
+ reject(new Error('Google Pay not available'));
22065
+ return;
22066
+ }
22067
+ resolve();
22068
+ };
22069
+ script.onerror = function () {
22070
+ // Allow a future retry after a transient failure.
22071
+ scriptLoadPromise = null;
22072
+ reject(new Error('Failed to load Google Pay script'));
22073
+ };
22074
+ document.head.appendChild(script);
22075
+ });
22076
+ return scriptLoadPromise;
22077
+ }
22078
+ /**
22079
+ * Builds the base `isReadyToPay` request using the default card configuration
22080
+ * (standard auth methods + card networks). Mirrors the instance service's request:
22081
+ * `existingPaymentMethodRequired` is `false` on Safari (where Google Pay surfaces a
22082
+ * different flow) and `true` elsewhere.
22083
+ */
22084
+ function buildIsReadyToPayRequest() {
22085
+ var isSafariBrowser = Browser.getBrowserName() === 'Apple Safari';
22086
+ return _extends(_extends({}, GOOGLE_PAY_API_CONFIG), {
22087
+ allowedPaymentMethods: [{
22088
+ type: 'CARD',
22089
+ parameters: {
22090
+ allowedAuthMethods: GOOGLE_PAY_AUTH_METHODS,
22091
+ allowedCardNetworks: GOOGLE_PAY_CARD_NETWORKS
22092
+ }
22093
+ }],
22094
+ existingPaymentMethodRequired: !isSafariBrowser
22095
+ });
22096
+ }
22097
+ /**
22098
+ * Core Google Pay availability evaluation, shared by the instance flow
22099
+ * (`GooglePayOpenWalletService`) and the static `GooglePayOpenWalletButton.checkAvailability`.
22100
+ *
22101
+ * The static check passes no `request`, so it uses the **default** card configuration
22102
+ * (a button instance with a custom `card_config` may produce a different result). The
22103
+ * instance flow passes its own `paymentsClient` and `request` so the readiness check
22104
+ * honours the merchant's `card_config` and runs against the same client it pays with.
22105
+ *
22106
+ * Assumes the Google Pay SDK is already loaded (call {@link loadGooglePayScript} first).
22107
+ */
22108
+ function evaluateGooglePayAvailability() {
22109
+ return __awaiter(this, arguments, void 0, function () {
22110
+ var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
22111
+ return /*#__PURE__*/_regenerator().m(function _callee() {
22112
+ var _a, _b, paymentsClient, response, available;
22113
+ return _regenerator().w(function (_context) {
22114
+ while (1) switch (_context.p = _context.n) {
22115
+ case 0:
22116
+ if (isGooglePayApiPresent()) {
22117
+ _context.n = 1;
22118
+ break;
22119
+ }
22120
+ return _context.a(2, {
22121
+ available: false,
22122
+ supported: false,
22123
+ reason: 'unsupported_browser'
22124
+ });
22125
+ case 1:
22126
+ _context.p = 1;
22127
+ paymentsClient = (_a = params.paymentsClient) !== null && _a !== void 0 ? _a : new google.payments.api.PaymentsClient({
22128
+ merchantInfo: {
22129
+ merchantId: params.merchantId || ''
22130
+ }
22131
+ });
22132
+ _context.n = 2;
22133
+ return paymentsClient.isReadyToPay((_b = params.request) !== null && _b !== void 0 ? _b : buildIsReadyToPayRequest());
22134
+ case 2:
22135
+ response = _context.v;
22136
+ available = !!response.result;
22137
+ return _context.a(2, {
22138
+ available: available,
22139
+ supported: true,
22140
+ payment_method_present: response.paymentMethodPresent,
22141
+ reason: available ? undefined : 'no_payment_method'
22142
+ });
22143
+ case 3:
22144
+ _context.p = 3;
22145
+ _context.v;
22146
+ return _context.a(2, {
22147
+ available: false,
22148
+ supported: isGooglePayApiPresent(),
22149
+ reason: 'query_failed'
22150
+ });
22151
+ }
22152
+ }, _callee, null, [[1, 3]]);
22153
+ })();
22154
+ });
22155
+ }
22156
+
20834
22157
  /**
20835
22158
  * Parses intermediate payment data from Google Pay into a normalized format
20836
22159
  * for use in shipping address/option change events.
@@ -21166,14 +22489,18 @@
21166
22489
  key: "checkAvailability",
21167
22490
  value: function checkAvailability() {
21168
22491
  return __awaiter(this, void 0, void 0, /*#__PURE__*/_regenerator().m(function _callee2() {
22492
+ var result;
21169
22493
  return _regenerator().w(function (_context2) {
21170
22494
  while (1) switch (_context2.n) {
21171
22495
  case 0:
21172
- return _context2.a(2, this.paymentsClient.isReadyToPay(this.createRequest()).then(function (response) {
21173
- return !!response.result;
21174
- })["catch"](function () {
21175
- return false;
21176
- }));
22496
+ _context2.n = 1;
22497
+ return evaluateGooglePayAvailability({
22498
+ paymentsClient: this.paymentsClient,
22499
+ request: this.createRequest()
22500
+ });
22501
+ case 1:
22502
+ result = _context2.v;
22503
+ return _context2.a(2, result.available);
21177
22504
  }
21178
22505
  }, _callee2, this);
21179
22506
  }));
@@ -21631,14 +22958,46 @@
21631
22958
  return _this;
21632
22959
  }
21633
22960
  /**
21634
- * Validates Google Pay-specific required metadata fields.
21635
- * Google Pay has no additional required fields beyond the base (amount, currency, country).
21636
- * @private
22961
+ * Checks Google Pay availability **without instantiating the button** — the static
22962
+ * availability entry point.
22963
+ *
22964
+ * Loads the Google Pay JS SDK if needed, then runs `PaymentsClient.isReadyToPay()` using
22965
+ * the **default** card configuration (a button instance with a custom `card_config` may
22966
+ * produce a different result). All options are optional — unlike Apple Pay, Google Pay's
22967
+ * readiness check does not require a merchant identifier; supplying `service_id` +
22968
+ * `public_key_or_access_token` additionally validates that the service is a Google Pay service.
22969
+ *
22970
+ * Pass `{ sync: true }` for a cheap, network-free check that only reports whether the
22971
+ * Google Pay JS API is already present (see {@link GooglePayAvailabilityOptions.sync}).
22972
+ *
22973
+ * @param {GooglePayAvailabilityOptions} [options] - Optional merchant context and mode.
22974
+ * @returns {Promise<GooglePayAvailabilityResult>} The availability result.
22975
+ *
22976
+ * @example
22977
+ * // Simplest form — no merchant context needed:
22978
+ * const result = await GooglePayOpenWalletButton.checkAvailability();
22979
+ * if (result.available) {
22980
+ * // Render the Google Pay button.
22981
+ * }
22982
+ *
22983
+ * @example
22984
+ * // Validate the service is a Google Pay service while checking:
22985
+ * const result = await GooglePayOpenWalletButton.checkAvailability({
22986
+ * public_key_or_access_token,
22987
+ * service_id,
22988
+ * env: 'sandbox',
22989
+ * });
21637
22990
  */
21638
22991
  _inherits(GooglePayOpenWalletButton, _OpenWalletButtons);
21639
22992
  return _createClass(GooglePayOpenWalletButton, [{
21640
22993
  key: "validateWalletMeta",
21641
- value: function validateWalletMeta() {
22994
+ value:
22995
+ /**
22996
+ * Validates Google Pay-specific required metadata fields.
22997
+ * Google Pay has no additional required fields beyond the base (amount, currency, country).
22998
+ * @private
22999
+ */
23000
+ function validateWalletMeta() {
21642
23001
  // Google Pay has no additional required meta fields beyond the base.
21643
23002
  // Optional fields (merchant_name, card_config, etc.) are validated
21644
23003
  // at runtime by the Google Pay SDK.
@@ -21669,6 +23028,87 @@
21669
23028
  value: function createWalletService(serviceConfig) {
21670
23029
  return new GooglePayOpenWalletService(this.api, this.eventEmitter, this.serviceId, this.container, this.meta, serviceConfig);
21671
23030
  }
23031
+ }], [{
23032
+ key: "checkAvailability",
23033
+ value: function checkAvailability() {
23034
+ return __awaiter(this, arguments, void 0, function () {
23035
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
23036
+ return /*#__PURE__*/_regenerator().m(function _callee() {
23037
+ var present, merchantId, authType, api, serviceConfig;
23038
+ return _regenerator().w(function (_context) {
23039
+ while (1) switch (_context.p = _context.n) {
23040
+ case 0:
23041
+ if (!options.sync) {
23042
+ _context.n = 1;
23043
+ break;
23044
+ }
23045
+ present = isGooglePayApiPresent();
23046
+ return _context.a(2, {
23047
+ available: present,
23048
+ supported: present,
23049
+ reason: present ? undefined : 'api_not_loaded'
23050
+ });
23051
+ case 1:
23052
+ merchantId = options.merchant_id;
23053
+ if (!(!merchantId && options.public_key_or_access_token && options.service_id)) {
23054
+ _context.n = 6;
23055
+ break;
23056
+ }
23057
+ _context.p = 2;
23058
+ authType = AccessToken.validateJWT(options.public_key_or_access_token) ? API_AUTH_TYPE.TOKEN : API_AUTH_TYPE.PUBLIC_KEY;
23059
+ api = new ApiInternal(options.public_key_or_access_token, authType);
23060
+ if (options.env) {
23061
+ api.setEnv(options.env);
23062
+ }
23063
+ _context.n = 3;
23064
+ return getServiceConfigCached(api, options.service_id);
23065
+ case 3:
23066
+ serviceConfig = _context.v;
23067
+ if (!(serviceConfig.type !== SERVICE_TYPES.GOOGLE_PAY)) {
23068
+ _context.n = 4;
23069
+ break;
23070
+ }
23071
+ return _context.a(2, {
23072
+ available: false,
23073
+ supported: isGooglePayApiPresent(),
23074
+ reason: 'service_type_mismatch'
23075
+ });
23076
+ case 4:
23077
+ merchantId = serviceConfig.merchant;
23078
+ _context.n = 6;
23079
+ break;
23080
+ case 5:
23081
+ _context.p = 5;
23082
+ _context.v;
23083
+ return _context.a(2, {
23084
+ available: false,
23085
+ supported: isGooglePayApiPresent(),
23086
+ reason: 'config_fetch_failed'
23087
+ });
23088
+ case 6:
23089
+ _context.p = 6;
23090
+ _context.n = 7;
23091
+ return loadGooglePayScript();
23092
+ case 7:
23093
+ _context.n = 9;
23094
+ break;
23095
+ case 8:
23096
+ _context.p = 8;
23097
+ _context.v;
23098
+ return _context.a(2, {
23099
+ available: false,
23100
+ supported: isGooglePayApiPresent(),
23101
+ reason: 'sdk_load_failed'
23102
+ });
23103
+ case 9:
23104
+ return _context.a(2, evaluateGooglePayAvailability({
23105
+ merchantId: merchantId
23106
+ }));
23107
+ }
23108
+ }, _callee, null, [[6, 8], [2, 5]]);
23109
+ })();
23110
+ });
23111
+ }
21672
23112
  }]);
21673
23113
  }(OpenWalletButtons);
21674
23114