@ukic/web-components 3.28.0 → 3.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/components/ic-accordion.js +53 -38
  2. package/components/ic-accordion.js.map +1 -1
  3. package/components/ic-breadcrumb-group.js +16 -12
  4. package/components/ic-breadcrumb-group.js.map +1 -1
  5. package/components/ic-menu-item2.js +7 -2
  6. package/components/ic-menu-item2.js.map +1 -1
  7. package/components/ic-menu2.js +1393 -307
  8. package/components/ic-menu2.js.map +1 -1
  9. package/components/ic-navigation-button.js +8 -5
  10. package/components/ic-navigation-button.js.map +1 -1
  11. package/components/ic-pagination-bar.js.map +1 -1
  12. package/components/ic-pagination-item2.js.map +1 -1
  13. package/components/ic-pagination2.js.map +1 -1
  14. package/components/ic-popover-menu.js +17 -5
  15. package/components/ic-popover-menu.js.map +1 -1
  16. package/components/ic-radio-group.js.map +1 -1
  17. package/components/ic-skip-link.js.map +1 -1
  18. package/components/ic-status-tag.js.map +1 -1
  19. package/dist/cjs/core.cjs.js +1 -1
  20. package/dist/cjs/ic-accordion.cjs.entry.js +53 -38
  21. package/dist/cjs/ic-accordion.cjs.entry.js.map +1 -1
  22. package/dist/cjs/ic-breadcrumb-group.cjs.entry.js +16 -12
  23. package/dist/cjs/ic-breadcrumb-group.cjs.entry.js.map +1 -1
  24. package/dist/cjs/ic-button_3.cjs.entry.js.map +1 -1
  25. package/dist/cjs/ic-horizontal-scroll.cjs.entry.js.map +1 -1
  26. package/dist/cjs/ic-input-component-container_3.cjs.entry.js +1393 -307
  27. package/dist/cjs/ic-input-component-container_3.cjs.entry.js.map +1 -1
  28. package/dist/cjs/ic-menu-item.cjs.entry.js +5 -1
  29. package/dist/cjs/ic-menu-item.cjs.entry.js.map +1 -1
  30. package/dist/cjs/ic-navigation-button.cjs.entry.js +8 -5
  31. package/dist/cjs/ic-navigation-button.cjs.entry.js.map +1 -1
  32. package/dist/cjs/ic-popover-menu.cjs.entry.js +16 -5
  33. package/dist/cjs/ic-popover-menu.cjs.entry.js.map +1 -1
  34. package/dist/cjs/loader.cjs.js +1 -1
  35. package/dist/collection/components/ic-accordion/ic-accordion.js +53 -38
  36. package/dist/collection/components/ic-accordion/ic-accordion.js.map +1 -1
  37. package/dist/collection/components/ic-breadcrumb-group/ic-breadcrumb-group.js +17 -13
  38. package/dist/collection/components/ic-breadcrumb-group/ic-breadcrumb-group.js.map +1 -1
  39. package/dist/collection/components/ic-menu-item/ic-menu-item.css +9 -14
  40. package/dist/collection/components/ic-menu-item/ic-menu-item.js +24 -0
  41. package/dist/collection/components/ic-menu-item/ic-menu-item.js.map +1 -1
  42. package/dist/collection/components/ic-navigation-button/ic-navigation-button.js +8 -5
  43. package/dist/collection/components/ic-navigation-button/ic-navigation-button.js.map +1 -1
  44. package/dist/collection/components/ic-popover-menu/ic-popover-menu.js +36 -5
  45. package/dist/collection/components/ic-popover-menu/ic-popover-menu.js.map +1 -1
  46. package/dist/collection/components/ic-popover-menu/ic-popover-menu.stories.js +169 -1
  47. package/dist/components/ic-accordion.js +53 -38
  48. package/dist/components/ic-accordion.js.map +1 -1
  49. package/dist/components/ic-back-to-top.js.map +1 -1
  50. package/dist/components/ic-breadcrumb-group.js +16 -12
  51. package/dist/components/ic-breadcrumb-group.js.map +1 -1
  52. package/dist/components/ic-menu-item2.js +7 -2
  53. package/dist/components/ic-menu-item2.js.map +1 -1
  54. package/dist/components/ic-menu2.js +1393 -307
  55. package/dist/components/ic-menu2.js.map +1 -1
  56. package/dist/components/ic-navigation-button.js +8 -5
  57. package/dist/components/ic-navigation-button.js.map +1 -1
  58. package/dist/components/ic-popover-menu.js +17 -5
  59. package/dist/components/ic-popover-menu.js.map +1 -1
  60. package/dist/components/ic-radio-group.js.map +1 -1
  61. package/dist/components/ic-radio-option.js.map +1 -1
  62. package/dist/components/ic-side-navigation.js.map +1 -1
  63. package/dist/components/ic-skip-link.js.map +1 -1
  64. package/dist/components/ic-status-tag.js.map +1 -1
  65. package/dist/core/core.esm.js +1 -1
  66. package/dist/core/core.esm.js.map +1 -1
  67. package/dist/core/{p-9ced00a7.entry.js → p-41bbdc4c.entry.js} +2 -2
  68. package/dist/core/{p-9ced00a7.entry.js.map → p-41bbdc4c.entry.js.map} +1 -1
  69. package/dist/core/p-8fc5e9f9.entry.js.map +1 -1
  70. package/dist/core/p-98dee727.entry.js.map +1 -1
  71. package/dist/core/{p-fc4b7d2b.entry.js → p-9cf35c23.entry.js} +2 -2
  72. package/dist/core/p-9cf35c23.entry.js.map +1 -0
  73. package/dist/core/p-be8bbed8.entry.js +2 -0
  74. package/dist/core/p-be8bbed8.entry.js.map +1 -0
  75. package/dist/core/p-ccba84b7.entry.js +3 -0
  76. package/dist/core/p-ccba84b7.entry.js.map +1 -0
  77. package/dist/core/p-ef289935.entry.js +2 -0
  78. package/dist/core/p-ef289935.entry.js.map +1 -0
  79. package/dist/core/p-f8aa89ff.entry.js +2 -0
  80. package/dist/core/p-f8aa89ff.entry.js.map +1 -0
  81. package/dist/esm/core.js +1 -1
  82. package/dist/esm/ic-accordion.entry.js +53 -38
  83. package/dist/esm/ic-accordion.entry.js.map +1 -1
  84. package/dist/esm/ic-breadcrumb-group.entry.js +16 -12
  85. package/dist/esm/ic-breadcrumb-group.entry.js.map +1 -1
  86. package/dist/esm/ic-button_3.entry.js.map +1 -1
  87. package/dist/esm/ic-horizontal-scroll.entry.js.map +1 -1
  88. package/dist/esm/ic-input-component-container_3.entry.js +1393 -307
  89. package/dist/esm/ic-input-component-container_3.entry.js.map +1 -1
  90. package/dist/esm/ic-menu-item.entry.js +5 -1
  91. package/dist/esm/ic-menu-item.entry.js.map +1 -1
  92. package/dist/esm/ic-navigation-button.entry.js +8 -5
  93. package/dist/esm/ic-navigation-button.entry.js.map +1 -1
  94. package/dist/esm/ic-popover-menu.entry.js +16 -5
  95. package/dist/esm/ic-popover-menu.entry.js.map +1 -1
  96. package/dist/esm/loader.js +1 -1
  97. package/dist/types/components/ic-accordion/ic-accordion.d.ts +2 -0
  98. package/dist/types/components/ic-breadcrumb-group/ic-breadcrumb-group.d.ts +6 -1
  99. package/dist/types/components/ic-menu-item/ic-menu-item.d.ts +4 -0
  100. package/dist/types/components/ic-popover-menu/ic-popover-menu.d.ts +4 -0
  101. package/dist/types/components.d.ts +18 -2
  102. package/hydrate/index.js +1494 -369
  103. package/hydrate/index.mjs +1494 -369
  104. package/package.json +10 -6
  105. package/vscode-data.json +20 -1
  106. package/dist/core/p-2b1ce5b7.entry.js +0 -2
  107. package/dist/core/p-2b1ce5b7.entry.js.map +0 -1
  108. package/dist/core/p-56ab6fb7.entry.js +0 -2
  109. package/dist/core/p-56ab6fb7.entry.js.map +0 -1
  110. package/dist/core/p-d5fcd4f9.entry.js +0 -2
  111. package/dist/core/p-d5fcd4f9.entry.js.map +0 -1
  112. package/dist/core/p-fc4b7d2b.entry.js.map +0 -1
  113. package/dist/core/p-fdc4376e.entry.js +0 -3
  114. package/dist/core/p-fdc4376e.entry.js.map +0 -1
@@ -97,28 +97,69 @@ var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof win
97
97
 
98
98
  var purify = {exports: {}};
99
99
 
100
- /*! @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 */
100
+ /*! @license DOMPurify 3.4.13 | (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.13/LICENSE */
101
101
 
102
102
  (function (module, exports) {
103
103
  (function (global, factory) {
104
104
  module.exports = factory() ;
105
105
  })(commonjsGlobal, (function () {
106
- const {
107
- entries,
108
- setPrototypeOf,
109
- isFrozen,
110
- getPrototypeOf,
111
- getOwnPropertyDescriptor
112
- } = Object;
113
- let {
114
- freeze,
115
- seal,
116
- create
117
- } = Object; // eslint-disable-line import/no-mutable-exports
118
- let {
119
- apply,
120
- construct
121
- } = typeof Reflect !== 'undefined' && Reflect;
106
+ function _arrayLikeToArray(r, a) {
107
+ (null == a || a > r.length) && (a = r.length);
108
+ for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
109
+ return n;
110
+ }
111
+ function _arrayWithHoles(r) {
112
+ if (Array.isArray(r)) return r;
113
+ }
114
+ function _iterableToArrayLimit(r, l) {
115
+ var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
116
+ if (null != t) {
117
+ var e,
118
+ n,
119
+ i,
120
+ u,
121
+ a = [],
122
+ f = true,
123
+ o = false;
124
+ try {
125
+ 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);
126
+ } catch (r) {
127
+ o = true, n = r;
128
+ } finally {
129
+ try {
130
+ if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;
131
+ } finally {
132
+ if (o) throw n;
133
+ }
134
+ }
135
+ return a;
136
+ }
137
+ }
138
+ function _nonIterableRest() {
139
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
140
+ }
141
+ function _slicedToArray(r, e) {
142
+ return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
143
+ }
144
+ function _unsupportedIterableToArray(r, a) {
145
+ if (r) {
146
+ if ("string" == typeof r) return _arrayLikeToArray(r, a);
147
+ var t = {}.toString.call(r).slice(8, -1);
148
+ 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;
149
+ }
150
+ }
151
+
152
+ const entries = Object.entries,
153
+ setPrototypeOf = Object.setPrototypeOf,
154
+ isFrozen = Object.isFrozen,
155
+ getPrototypeOf = Object.getPrototypeOf,
156
+ getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
157
+ let freeze = Object.freeze,
158
+ seal = Object.seal,
159
+ create = Object.create; // eslint-disable-line import/no-mutable-exports
160
+ let _ref = typeof Reflect !== 'undefined' && Reflect,
161
+ apply = _ref.apply,
162
+ construct = _ref.construct;
122
163
  if (!freeze) {
123
164
  freeze = function freeze(x) {
124
165
  return x;
@@ -150,13 +191,19 @@ var purify = {exports: {}};
150
191
  const arrayPop = unapply(Array.prototype.pop);
151
192
  const arrayPush = unapply(Array.prototype.push);
152
193
  const arraySplice = unapply(Array.prototype.splice);
194
+ const arrayIsArray = Array.isArray;
153
195
  const stringToLowerCase = unapply(String.prototype.toLowerCase);
154
196
  const stringToString = unapply(String.prototype.toString);
155
197
  const stringMatch = unapply(String.prototype.match);
156
198
  const stringReplace = unapply(String.prototype.replace);
157
199
  const stringIndexOf = unapply(String.prototype.indexOf);
158
200
  const stringTrim = unapply(String.prototype.trim);
201
+ const numberToString = unapply(Number.prototype.toString);
202
+ const booleanToString = unapply(Boolean.prototype.toString);
203
+ const bigintToString = typeof BigInt === 'undefined' ? null : unapply(BigInt.prototype.toString);
204
+ const symbolToString = typeof Symbol === 'undefined' ? null : unapply(Symbol.prototype.toString);
159
205
  const objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty);
206
+ const objectToString = unapply(Object.prototype.toString);
160
207
  const regExpTest = unapply(RegExp.prototype.test);
161
208
  const typeErrorCreate = unconstruct(TypeError);
162
209
  /**
@@ -206,6 +253,9 @@ var purify = {exports: {}};
206
253
  // Prevent prototype setters from intercepting set as a this value.
207
254
  setPrototypeOf(set, null);
208
255
  }
256
+ if (!arrayIsArray(array)) {
257
+ return set;
258
+ }
209
259
  let l = array.length;
210
260
  while (l--) {
211
261
  let element = array[l];
@@ -246,10 +296,13 @@ var purify = {exports: {}};
246
296
  */
247
297
  function clone(object) {
248
298
  const newObject = create(null);
249
- for (const [property, value] of entries(object)) {
299
+ for (const _ref2 of entries(object)) {
300
+ var _ref3 = _slicedToArray(_ref2, 2);
301
+ const property = _ref3[0];
302
+ const value = _ref3[1];
250
303
  const isPropertyExist = objectHasOwnProperty(object, property);
251
304
  if (isPropertyExist) {
252
- if (Array.isArray(value)) {
305
+ if (arrayIsArray(value)) {
253
306
  newObject[property] = cleanArray(value);
254
307
  } else if (value && typeof value === 'object' && value.constructor === Object) {
255
308
  newObject[property] = clone(value);
@@ -260,6 +313,58 @@ var purify = {exports: {}};
260
313
  }
261
314
  return newObject;
262
315
  }
316
+ /**
317
+ * Convert non-node values into strings without depending on direct property access.
318
+ *
319
+ * @param value - The value to stringify.
320
+ * @returns A string representation of the provided value.
321
+ */
322
+ function stringifyValue(value) {
323
+ switch (typeof value) {
324
+ case 'string':
325
+ {
326
+ return value;
327
+ }
328
+ case 'number':
329
+ {
330
+ return numberToString(value);
331
+ }
332
+ case 'boolean':
333
+ {
334
+ return booleanToString(value);
335
+ }
336
+ case 'bigint':
337
+ {
338
+ return bigintToString ? bigintToString(value) : '0';
339
+ }
340
+ case 'symbol':
341
+ {
342
+ return symbolToString ? symbolToString(value) : 'Symbol()';
343
+ }
344
+ case 'undefined':
345
+ {
346
+ return objectToString(value);
347
+ }
348
+ case 'function':
349
+ case 'object':
350
+ {
351
+ if (value === null) {
352
+ return objectToString(value);
353
+ }
354
+ const valueAsRecord = value;
355
+ const valueToString = lookupGetter(valueAsRecord, 'toString');
356
+ if (typeof valueToString === 'function') {
357
+ const stringified = valueToString(valueAsRecord);
358
+ return typeof stringified === 'string' ? stringified : objectToString(stringified);
359
+ }
360
+ return objectToString(value);
361
+ }
362
+ default:
363
+ {
364
+ return objectToString(value);
365
+ }
366
+ }
367
+ }
263
368
  /**
264
369
  * This method automatically checks if the prop is function or getter and behaves accordingly.
265
370
  *
@@ -285,6 +390,14 @@ var purify = {exports: {}};
285
390
  }
286
391
  return fallbackValue;
287
392
  }
393
+ function isRegex(value) {
394
+ try {
395
+ regExpTest(value, '');
396
+ return true;
397
+ } catch (_unused) {
398
+ return false;
399
+ }
400
+ }
288
401
 
289
402
  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']);
290
403
  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']);
@@ -300,15 +413,14 @@ var purify = {exports: {}};
300
413
  const mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);
301
414
  const text = freeze(['#text']);
302
415
 
303
- 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']);
304
- 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']);
416
+ 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']);
417
+ 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', 'dominant-baseline', '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-orientation', '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']);
305
418
  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']);
306
419
  const xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);
307
420
 
308
- // eslint-disable-next-line unicorn/better-regex
309
- const MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode
310
- const ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm);
311
- const TMPLIT_EXPR = seal(/\$\{[\w\W]*/gm); // eslint-disable-line unicorn/better-regex
421
+ const MUSTACHE_EXPR = seal(/{{[\w\W]*|^[\w\W]*}}/g);
422
+ const ERB_EXPR = seal(/<%[\w\W]*|^[\w\W]*%>/g);
423
+ const TMPLIT_EXPR = seal(/\${[\w\W]*/g);
312
424
  const DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]+$/); // eslint-disable-line no-useless-escape
313
425
  const ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape
314
426
  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
@@ -318,30 +430,31 @@ var purify = {exports: {}};
318
430
  );
319
431
  const DOCTYPE_NAME = seal(/^html$/i);
320
432
  const CUSTOM_ELEMENT = seal(/^[a-z][.\w]*(-[.\w]+)+$/i);
433
+ // Markup-significant character probes used by _sanitizeElements.
434
+ // Shared module-level instances are safe despite the sticky /g flags:
435
+ // unapply() resets lastIndex for RegExp receivers before every call.
436
+ const ELEMENT_MARKUP_PROBE = seal(/<[/\w!]/g);
437
+ const COMMENT_MARKUP_PROBE = seal(/<[/\w]/g);
438
+ const FALLBACK_TAG_CLOSE = seal(/<\/no(script|embed|frames)/i);
439
+ const SELF_CLOSING_TAG = seal(/\/>/i);
321
440
 
322
- var EXPRESSIONS = /*#__PURE__*/Object.freeze({
323
- __proto__: null,
324
- ARIA_ATTR: ARIA_ATTR,
325
- ATTR_WHITESPACE: ATTR_WHITESPACE,
326
- CUSTOM_ELEMENT: CUSTOM_ELEMENT,
327
- DATA_ATTR: DATA_ATTR,
328
- DOCTYPE_NAME: DOCTYPE_NAME,
329
- ERB_EXPR: ERB_EXPR,
330
- IS_ALLOWED_URI: IS_ALLOWED_URI,
331
- IS_SCRIPT_OR_DATA: IS_SCRIPT_OR_DATA,
332
- MUSTACHE_EXPR: MUSTACHE_EXPR,
333
- TMPLIT_EXPR: TMPLIT_EXPR
334
- });
335
-
336
- /* eslint-disable @typescript-eslint/indent */
337
441
  // https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType
338
442
  const NODE_TYPE = {
339
443
  element: 1,
444
+ attribute: 2,
340
445
  text: 3,
446
+ cdataSection: 4,
447
+ entityReference: 5,
341
448
  // Deprecated
342
- progressingInstruction: 7,
449
+ entityNode: 6,
450
+ // Deprecated
451
+ processingInstruction: 7,
343
452
  comment: 8,
344
- document: 9};
453
+ document: 9,
454
+ documentType: 10,
455
+ documentFragment: 11,
456
+ notation: 12 // Deprecated
457
+ };
345
458
  const getGlobal = function getGlobal() {
346
459
  return typeof window === 'undefined' ? null : window;
347
460
  };
@@ -396,10 +509,25 @@ var purify = {exports: {}};
396
509
  uponSanitizeShadowNode: []
397
510
  };
398
511
  };
512
+ /**
513
+ * Resolve a set-valued configuration option: a fresh set built from
514
+ * cfg[key] when it is an own array property (seeded with a clone of
515
+ * options.base when given, case-normalized via options.transform),
516
+ * the fallback set otherwise.
517
+ *
518
+ * @param cfg the cloned, prototype-free configuration object
519
+ * @param key the configuration property to read
520
+ * @param fallback the set to use when the option is absent or not an array
521
+ * @param options transform and optional base set to merge into
522
+ * @returns the resolved set
523
+ */
524
+ const _resolveSetOption = function _resolveSetOption(cfg, key, fallback, options) {
525
+ return objectHasOwnProperty(cfg, key) && arrayIsArray(cfg[key]) ? addToSet(options.base ? clone(options.base) : {}, cfg[key], options.transform) : fallback;
526
+ };
399
527
  function createDOMPurify() {
400
528
  let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();
401
529
  const DOMPurify = root => createDOMPurify(root);
402
- DOMPurify.version = '3.4.0';
530
+ DOMPurify.version = '3.4.13';
403
531
  DOMPurify.removed = [];
404
532
  if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document || !window.Element) {
405
533
  // Not running in a browser, provide a factory function
@@ -407,28 +535,26 @@ var purify = {exports: {}};
407
535
  DOMPurify.isSupported = false;
408
536
  return DOMPurify;
409
537
  }
410
- let {
411
- document
412
- } = window;
538
+ let document = window.document;
413
539
  const originalDocument = document;
414
540
  const currentScript = originalDocument.currentScript;
415
- const {
416
- DocumentFragment,
417
- HTMLTemplateElement,
418
- Node,
419
- Element,
420
- NodeFilter,
421
- NamedNodeMap = window.NamedNodeMap || window.MozNamedAttrMap,
422
- HTMLFormElement,
423
- DOMParser,
424
- trustedTypes
425
- } = window;
541
+ const HTMLTemplateElement = window.HTMLTemplateElement,
542
+ Node = window.Node,
543
+ Element = window.Element,
544
+ NodeFilter = window.NodeFilter;
545
+ const DOMParser = window.DOMParser,
546
+ trustedTypes = window.trustedTypes;
426
547
  const ElementPrototype = Element.prototype;
427
548
  const cloneNode = lookupGetter(ElementPrototype, 'cloneNode');
428
549
  const remove = lookupGetter(ElementPrototype, 'remove');
429
550
  const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');
430
551
  const getChildNodes = lookupGetter(ElementPrototype, 'childNodes');
431
552
  const getParentNode = lookupGetter(ElementPrototype, 'parentNode');
553
+ const getShadowRoot = lookupGetter(ElementPrototype, 'shadowRoot');
554
+ const getAttributes = lookupGetter(ElementPrototype, 'attributes');
555
+ const getNodeType = Node && Node.prototype ? lookupGetter(Node.prototype, 'nodeType') : null;
556
+ const getNodeName = Node && Node.prototype ? lookupGetter(Node.prototype, 'nodeName') : null;
557
+ const getOwnerDocument = Node && Node.prototype ? lookupGetter(Node.prototype, 'ownerDocument') : null;
432
558
  // As per issue #47, the web-components registry is inherited by a
433
559
  // new document created via createHTMLDocument. As per the spec
434
560
  // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)
@@ -443,33 +569,74 @@ var purify = {exports: {}};
443
569
  }
444
570
  let trustedTypesPolicy;
445
571
  let emptyHTML = '';
446
- const {
447
- implementation,
448
- createNodeIterator,
449
- createDocumentFragment,
450
- getElementsByTagName
451
- } = document;
452
- const {
453
- importNode
454
- } = originalDocument;
572
+ // The instance's own internal Trusted Types policy. Unlike a caller-supplied
573
+ // `TRUSTED_TYPES_POLICY`, this is created at most once — Trusted Types throws
574
+ // on duplicate policy names — and is the only policy allowed to persist
575
+ // across configurations and survive `clearConfig()`.
576
+ let defaultTrustedTypesPolicy;
577
+ let defaultTrustedTypesPolicyResolved = false;
578
+ // Tracks whether we are already inside a call to the configured Trusted Types
579
+ // policy (`createHTML` or `createScriptURL`). If a supplied policy callback
580
+ // itself calls `DOMPurify.sanitize` (the cause of #1422), `sanitize` would
581
+ // re-enter the policy and recurse until the stack overflows. We detect that
582
+ // re-entry and throw a clear, actionable error instead. The guard is shared
583
+ // across both callbacks, because either one re-entering `sanitize` triggers
584
+ // the same unbounded recursion.
585
+ let IN_TRUSTED_TYPES_POLICY = 0;
586
+ const _assertNotInTrustedTypesPolicy = function _assertNotInTrustedTypesPolicy() {
587
+ if (IN_TRUSTED_TYPES_POLICY > 0) {
588
+ 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.');
589
+ }
590
+ };
591
+ const _createTrustedHTML = function _createTrustedHTML(html) {
592
+ _assertNotInTrustedTypesPolicy();
593
+ IN_TRUSTED_TYPES_POLICY++;
594
+ try {
595
+ return trustedTypesPolicy.createHTML(html);
596
+ } finally {
597
+ IN_TRUSTED_TYPES_POLICY--;
598
+ }
599
+ };
600
+ const _createTrustedScriptURL = function _createTrustedScriptURL(scriptUrl) {
601
+ _assertNotInTrustedTypesPolicy();
602
+ IN_TRUSTED_TYPES_POLICY++;
603
+ try {
604
+ return trustedTypesPolicy.createScriptURL(scriptUrl);
605
+ } finally {
606
+ IN_TRUSTED_TYPES_POLICY--;
607
+ }
608
+ };
609
+ // Lazily resolve (and cache) the instance's internal default policy.
610
+ // Resolution is attempted at most once: a successful `createPolicy` cannot be
611
+ // repeated (Trusted Types throws on duplicate names), and a failed or
612
+ // unsupported attempt must not be retried on every parse.
613
+ const _getDefaultTrustedTypesPolicy = function _getDefaultTrustedTypesPolicy() {
614
+ if (!defaultTrustedTypesPolicyResolved) {
615
+ defaultTrustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);
616
+ defaultTrustedTypesPolicyResolved = true;
617
+ }
618
+ return defaultTrustedTypesPolicy;
619
+ };
620
+ const _document = document,
621
+ implementation = _document.implementation,
622
+ createNodeIterator = _document.createNodeIterator,
623
+ createDocumentFragment = _document.createDocumentFragment,
624
+ getElementsByTagName = _document.getElementsByTagName;
625
+ const importNode = originalDocument.importNode;
455
626
  let hooks = _createHooksMap();
456
627
  /**
457
628
  * Expose whether this browser supports running the full DOMPurify.
458
629
  */
459
630
  DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNode === 'function' && implementation && implementation.createHTMLDocument !== undefined;
460
- const {
461
- MUSTACHE_EXPR,
462
- ERB_EXPR,
463
- TMPLIT_EXPR,
464
- DATA_ATTR,
465
- ARIA_ATTR,
466
- IS_SCRIPT_OR_DATA,
467
- ATTR_WHITESPACE,
468
- CUSTOM_ELEMENT
469
- } = EXPRESSIONS;
470
- let {
471
- IS_ALLOWED_URI: IS_ALLOWED_URI$1
472
- } = EXPRESSIONS;
631
+ const MUSTACHE_EXPR$1 = MUSTACHE_EXPR,
632
+ ERB_EXPR$1 = ERB_EXPR,
633
+ TMPLIT_EXPR$1 = TMPLIT_EXPR,
634
+ DATA_ATTR$1 = DATA_ATTR,
635
+ ARIA_ATTR$1 = ARIA_ATTR,
636
+ IS_SCRIPT_OR_DATA$1 = IS_SCRIPT_OR_DATA,
637
+ ATTR_WHITESPACE$1 = ATTR_WHITESPACE,
638
+ CUSTOM_ELEMENT$1 = CUSTOM_ELEMENT;
639
+ let IS_ALLOWED_URI$1 = IS_ALLOWED_URI;
473
640
  /**
474
641
  * We consider the elements and attributes below to be safe. Ideally
475
642
  * don't add any new ones but feel free to remove unwanted ones.
@@ -546,6 +713,13 @@ var purify = {exports: {}};
546
713
  let WHOLE_DOCUMENT = false;
547
714
  /* Track whether config is already set on this instance of DOMPurify. */
548
715
  let SET_CONFIG = false;
716
+ /* Pristine allowlist bindings captured at setConfig() time. On the
717
+ * persistent-config path sanitize() restores the sets from these before
718
+ * the per-walk hook clone-guard, so a hook's in-call widening cannot
719
+ * carry across calls. Null until setConfig() is called; reset by
720
+ * clearConfig(). */
721
+ let SET_CONFIG_ALLOWED_TAGS = null;
722
+ let SET_CONFIG_ALLOWED_ATTR = null;
549
723
  /* Decide if all elements (e.g. style, script) must be children of
550
724
  * document.body. By default, browsers might move them to document.head */
551
725
  let FORCE_BODY = false;
@@ -588,7 +762,17 @@ var purify = {exports: {}};
588
762
  let USE_PROFILES = {};
589
763
  /* Tags to ignore content of when KEEP_CONTENT is true */
590
764
  let FORBID_CONTENTS = null;
591
- 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']);
765
+ const DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script',
766
+ // <selectedcontent> mirrors the selected <option>'s subtree, cloned by
767
+ // the UA (customizable <select>) — including any on* handlers — and the
768
+ // engine re-mirrors synchronously whenever a removal changes which
769
+ // option/selectedcontent is current, even inside DOMPurify's inert
770
+ // DOMParser document. Hoisting its children on removal re-inserts a fresh
771
+ // mirror target ahead of the walk, which the engine refills, looping
772
+ // forever (DoS) and amplifying output. Dropping its content on removal
773
+ // (rather than hoisting) breaks that cascade; the content is a duplicate
774
+ // of the option, which is sanitized on its own. See campaign-3 F1/F6.
775
+ 'selectedcontent', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']);
592
776
  /* Tags that are safe for data: URIs */
593
777
  let DATA_URI_TAGS = null;
594
778
  const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);
@@ -604,8 +788,10 @@ var purify = {exports: {}};
604
788
  /* Allowed XHTML+XML namespaces */
605
789
  let ALLOWED_NAMESPACES = null;
606
790
  const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);
607
- let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']);
608
- let HTML_INTEGRATION_POINTS = addToSet({}, ['annotation-xml']);
791
+ const DEFAULT_MATHML_TEXT_INTEGRATION_POINTS = freeze(['mi', 'mo', 'mn', 'ms', 'mtext']);
792
+ let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, DEFAULT_MATHML_TEXT_INTEGRATION_POINTS);
793
+ const DEFAULT_HTML_INTEGRATION_POINTS = freeze(['annotation-xml']);
794
+ let HTML_INTEGRATION_POINTS = addToSet({}, DEFAULT_HTML_INTEGRATION_POINTS);
609
795
  // Certain elements are allowed in both SVG and HTML
610
796
  // namespace. We need to specify them explicitly
611
797
  // so that they don't get erroneously deleted from
@@ -647,15 +833,33 @@ var purify = {exports: {}};
647
833
  // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.
648
834
  transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase;
649
835
  /* Set configuration parameters */
650
- ALLOWED_TAGS = objectHasOwnProperty(cfg, 'ALLOWED_TAGS') ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS;
651
- ALLOWED_ATTR = objectHasOwnProperty(cfg, 'ALLOWED_ATTR') ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR;
652
- ALLOWED_NAMESPACES = objectHasOwnProperty(cfg, 'ALLOWED_NAMESPACES') ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES;
653
- 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;
654
- 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;
655
- FORBID_CONTENTS = objectHasOwnProperty(cfg, 'FORBID_CONTENTS') ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS;
656
- FORBID_TAGS = objectHasOwnProperty(cfg, 'FORBID_TAGS') ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : clone({});
657
- FORBID_ATTR = objectHasOwnProperty(cfg, 'FORBID_ATTR') ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : clone({});
658
- USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES : false;
836
+ ALLOWED_TAGS = _resolveSetOption(cfg, 'ALLOWED_TAGS', DEFAULT_ALLOWED_TAGS, {
837
+ transform: transformCaseFunc
838
+ });
839
+ ALLOWED_ATTR = _resolveSetOption(cfg, 'ALLOWED_ATTR', DEFAULT_ALLOWED_ATTR, {
840
+ transform: transformCaseFunc
841
+ });
842
+ ALLOWED_NAMESPACES = _resolveSetOption(cfg, 'ALLOWED_NAMESPACES', DEFAULT_ALLOWED_NAMESPACES, {
843
+ transform: stringToString
844
+ });
845
+ URI_SAFE_ATTRIBUTES = _resolveSetOption(cfg, 'ADD_URI_SAFE_ATTR', DEFAULT_URI_SAFE_ATTRIBUTES, {
846
+ transform: transformCaseFunc,
847
+ base: DEFAULT_URI_SAFE_ATTRIBUTES
848
+ });
849
+ DATA_URI_TAGS = _resolveSetOption(cfg, 'ADD_DATA_URI_TAGS', DEFAULT_DATA_URI_TAGS, {
850
+ transform: transformCaseFunc,
851
+ base: DEFAULT_DATA_URI_TAGS
852
+ });
853
+ FORBID_CONTENTS = _resolveSetOption(cfg, 'FORBID_CONTENTS', DEFAULT_FORBID_CONTENTS, {
854
+ transform: transformCaseFunc
855
+ });
856
+ FORBID_TAGS = _resolveSetOption(cfg, 'FORBID_TAGS', clone({}), {
857
+ transform: transformCaseFunc
858
+ });
859
+ FORBID_ATTR = _resolveSetOption(cfg, 'FORBID_ATTR', clone({}), {
860
+ transform: transformCaseFunc
861
+ });
862
+ USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES && typeof cfg.USE_PROFILES === 'object' ? clone(cfg.USE_PROFILES) : cfg.USE_PROFILES : false;
659
863
  ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true
660
864
  ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true
661
865
  ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false
@@ -671,20 +875,22 @@ var purify = {exports: {}};
671
875
  SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false
672
876
  KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true
673
877
  IN_PLACE = cfg.IN_PLACE || false; // Default false
674
- IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI;
675
- NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;
676
- MATHML_TEXT_INTEGRATION_POINTS = cfg.MATHML_TEXT_INTEGRATION_POINTS || MATHML_TEXT_INTEGRATION_POINTS;
677
- HTML_INTEGRATION_POINTS = cfg.HTML_INTEGRATION_POINTS || HTML_INTEGRATION_POINTS;
678
- CUSTOM_ELEMENT_HANDLING = cfg.CUSTOM_ELEMENT_HANDLING || create(null);
679
- if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) {
680
- CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck;
681
- }
682
- if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) {
683
- CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck;
684
- }
685
- if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === 'boolean') {
686
- CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements;
687
- }
878
+ IS_ALLOWED_URI$1 = isRegex(cfg.ALLOWED_URI_REGEXP) ? cfg.ALLOWED_URI_REGEXP : IS_ALLOWED_URI; // Default regexp
879
+ NAMESPACE = typeof cfg.NAMESPACE === 'string' ? cfg.NAMESPACE : HTML_NAMESPACE; // Default HTML namespace
880
+ 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
881
+ 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
882
+ const customElementHandling = objectHasOwnProperty(cfg, 'CUSTOM_ELEMENT_HANDLING') && cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING === 'object' ? clone(cfg.CUSTOM_ELEMENT_HANDLING) : create(null);
883
+ CUSTOM_ELEMENT_HANDLING = create(null);
884
+ if (objectHasOwnProperty(customElementHandling, 'tagNameCheck') && isRegexOrFunction(customElementHandling.tagNameCheck)) {
885
+ CUSTOM_ELEMENT_HANDLING.tagNameCheck = customElementHandling.tagNameCheck; // Default undefined
886
+ }
887
+ if (objectHasOwnProperty(customElementHandling, 'attributeNameCheck') && isRegexOrFunction(customElementHandling.attributeNameCheck)) {
888
+ CUSTOM_ELEMENT_HANDLING.attributeNameCheck = customElementHandling.attributeNameCheck; // Default undefined
889
+ }
890
+ if (objectHasOwnProperty(customElementHandling, 'allowCustomizedBuiltInElements') && typeof customElementHandling.allowCustomizedBuiltInElements === 'boolean') {
891
+ CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = customElementHandling.allowCustomizedBuiltInElements; // Default undefined
892
+ }
893
+ seal(CUSTOM_ELEMENT_HANDLING);
688
894
  if (SAFE_FOR_TEMPLATES) {
689
895
  ALLOW_DATA_ATTR = false;
690
896
  }
@@ -720,36 +926,36 @@ var purify = {exports: {}};
720
926
  EXTRA_ELEMENT_HANDLING.tagCheck = null;
721
927
  EXTRA_ELEMENT_HANDLING.attributeCheck = null;
722
928
  /* Merge configuration parameters */
723
- if (cfg.ADD_TAGS) {
929
+ if (objectHasOwnProperty(cfg, 'ADD_TAGS')) {
724
930
  if (typeof cfg.ADD_TAGS === 'function') {
725
931
  EXTRA_ELEMENT_HANDLING.tagCheck = cfg.ADD_TAGS;
726
- } else {
932
+ } else if (arrayIsArray(cfg.ADD_TAGS)) {
727
933
  if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
728
934
  ALLOWED_TAGS = clone(ALLOWED_TAGS);
729
935
  }
730
936
  addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);
731
937
  }
732
938
  }
733
- if (cfg.ADD_ATTR) {
939
+ if (objectHasOwnProperty(cfg, 'ADD_ATTR')) {
734
940
  if (typeof cfg.ADD_ATTR === 'function') {
735
941
  EXTRA_ELEMENT_HANDLING.attributeCheck = cfg.ADD_ATTR;
736
- } else {
942
+ } else if (arrayIsArray(cfg.ADD_ATTR)) {
737
943
  if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
738
944
  ALLOWED_ATTR = clone(ALLOWED_ATTR);
739
945
  }
740
946
  addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);
741
947
  }
742
948
  }
743
- if (cfg.ADD_URI_SAFE_ATTR) {
949
+ if (objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') && arrayIsArray(cfg.ADD_URI_SAFE_ATTR)) {
744
950
  addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);
745
951
  }
746
- if (cfg.FORBID_CONTENTS) {
952
+ if (objectHasOwnProperty(cfg, 'FORBID_CONTENTS') && arrayIsArray(cfg.FORBID_CONTENTS)) {
747
953
  if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
748
954
  FORBID_CONTENTS = clone(FORBID_CONTENTS);
749
955
  }
750
956
  addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);
751
957
  }
752
- if (cfg.ADD_FORBID_CONTENTS) {
958
+ if (objectHasOwnProperty(cfg, 'ADD_FORBID_CONTENTS') && arrayIsArray(cfg.ADD_FORBID_CONTENTS)) {
753
959
  if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
754
960
  FORBID_CONTENTS = clone(FORBID_CONTENTS);
755
961
  }
@@ -768,6 +974,13 @@ var purify = {exports: {}};
768
974
  addToSet(ALLOWED_TAGS, ['tbody']);
769
975
  delete FORBID_TAGS.tbody;
770
976
  }
977
+ // Re-derive the active Trusted Types policy from this configuration on
978
+ // every parse. The active policy must never be sticky closure state that
979
+ // outlives the config that set it: a caller-supplied policy left in place
980
+ // after `clearConfig()` — or after a later call that supplied none, or
981
+ // `TRUSTED_TYPES_POLICY: null` — could sign a subsequent "default"
982
+ // `RETURN_TRUSTED_TYPE` result with a foreign, possibly unsafe policy.
983
+ // See GHSA-vxr8-fq34-vvx9.
771
984
  if (cfg.TRUSTED_TYPES_POLICY) {
772
985
  if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') {
773
986
  throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');
@@ -775,18 +988,45 @@ var purify = {exports: {}};
775
988
  if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') {
776
989
  throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');
777
990
  }
778
- // Overwrite existing TrustedTypes policy.
991
+ // A caller-supplied policy applies to this configuration only.
992
+ const previousTrustedTypesPolicy = trustedTypesPolicy;
779
993
  trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;
780
- // Sign local variables required by `sanitize`.
781
- emptyHTML = trustedTypesPolicy.createHTML('');
994
+ // Sign local variables required by `sanitize`. If the supplied policy's
995
+ // `createHTML` is circular (i.e. it calls `DOMPurify.sanitize`), this
996
+ // throws via the re-entrancy guard. Restore the previous policy first so
997
+ // the instance is not left in a poisoned state. See #1422.
998
+ try {
999
+ emptyHTML = _createTrustedHTML('');
1000
+ } catch (error) {
1001
+ trustedTypesPolicy = previousTrustedTypesPolicy;
1002
+ throw error;
1003
+ }
1004
+ } else if (cfg.TRUSTED_TYPES_POLICY === null) {
1005
+ // Explicit opt-out for this call: perform no Trusted Types signing and
1006
+ // create nothing (so a strict `trusted-types` CSP that disallows a
1007
+ // `dompurify` policy can still call `sanitize` from inside its own
1008
+ // policy — see #1422). Resetting to `undefined` rather than a sticky
1009
+ // `null` also drops any previously retained caller policy, so it cannot
1010
+ // resurface on a later call, while still allowing the next config-less
1011
+ // call to restore the internal default policy. See GHSA-vxr8-fq34-vvx9.
1012
+ trustedTypesPolicy = undefined;
1013
+ emptyHTML = '';
782
1014
  } else {
783
- // Uninitialized policy, attempt to initialize the internal dompurify policy.
1015
+ // No policy supplied: keep the currently active policy if one is set — a
1016
+ // previously supplied policy is intentionally sticky across config-less
1017
+ // calls — otherwise fall back to the instance's own internal policy,
1018
+ // created at most once. (A policy supplied for a *single* call still
1019
+ // lingers by design; what must not linger is a policy whose configuration
1020
+ // has been torn down via `clearConfig()`, which restores the default.)
784
1021
  if (trustedTypesPolicy === undefined) {
785
- trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);
1022
+ trustedTypesPolicy = _getDefaultTrustedTypesPolicy();
786
1023
  }
787
- // If creating the internal policy succeeded sign internal variables.
788
- if (trustedTypesPolicy !== null && typeof emptyHTML === 'string') {
789
- emptyHTML = trustedTypesPolicy.createHTML('');
1024
+ // Sign internal variables only when a policy is active. A falsy policy
1025
+ // (Trusted Types unsupported, creation failed, or an explicit opt-out)
1026
+ // leaves `emptyHTML` as a plain string, so we never call `.createHTML` on
1027
+ // a non-policy and throw. See #1422.
1028
+ if (trustedTypesPolicy && typeof emptyHTML === 'string') {
1029
+ emptyHTML = _createTrustedHTML('');
790
1030
  }
791
1031
  }
792
1032
  // Prevent further manipulation of configuration.
@@ -801,6 +1041,77 @@ var purify = {exports: {}};
801
1041
  * correctly. */
802
1042
  const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]);
803
1043
  const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]);
1044
+ /**
1045
+ * Namespace rules for an element in the SVG namespace.
1046
+ *
1047
+ * @param tagName the element's lowercase tag name
1048
+ * @param parent the (possibly simulated) parent node
1049
+ * @param parentTagName the parent's lowercase tag name
1050
+ * @returns true if a spec-compliant parser could produce this element
1051
+ */
1052
+ const _checkSvgNamespace = function _checkSvgNamespace(tagName, parent, parentTagName) {
1053
+ // The only way to switch from HTML namespace to SVG
1054
+ // is via <svg>. If it happens via any other tag, then
1055
+ // it should be killed.
1056
+ if (parent.namespaceURI === HTML_NAMESPACE) {
1057
+ return tagName === 'svg';
1058
+ }
1059
+ // The only way to switch from MathML to SVG is via <svg>
1060
+ // if the parent is either <annotation-xml> or a MathML
1061
+ // text integration point.
1062
+ if (parent.namespaceURI === MATHML_NAMESPACE) {
1063
+ return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
1064
+ }
1065
+ // We only allow elements that are defined in SVG
1066
+ // spec. All others are disallowed in SVG namespace.
1067
+ return Boolean(ALL_SVG_TAGS[tagName]);
1068
+ };
1069
+ /**
1070
+ * Namespace rules for an element in the MathML namespace.
1071
+ *
1072
+ * @param tagName the element's lowercase tag name
1073
+ * @param parent the (possibly simulated) parent node
1074
+ * @param parentTagName the parent's lowercase tag name
1075
+ * @returns true if a spec-compliant parser could produce this element
1076
+ */
1077
+ const _checkMathMlNamespace = function _checkMathMlNamespace(tagName, parent, parentTagName) {
1078
+ // The only way to switch from HTML namespace to MathML
1079
+ // is via <math>. If it happens via any other tag, then
1080
+ // it should be killed.
1081
+ if (parent.namespaceURI === HTML_NAMESPACE) {
1082
+ return tagName === 'math';
1083
+ }
1084
+ // The only way to switch from SVG to MathML is via
1085
+ // <math> and HTML integration points
1086
+ if (parent.namespaceURI === SVG_NAMESPACE) {
1087
+ return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
1088
+ }
1089
+ // We only allow elements that are defined in MathML
1090
+ // spec. All others are disallowed in MathML namespace.
1091
+ return Boolean(ALL_MATHML_TAGS[tagName]);
1092
+ };
1093
+ /**
1094
+ * Namespace rules for an element in the HTML namespace.
1095
+ *
1096
+ * @param tagName the element's lowercase tag name
1097
+ * @param parent the (possibly simulated) parent node
1098
+ * @param parentTagName the parent's lowercase tag name
1099
+ * @returns true if a spec-compliant parser could produce this element
1100
+ */
1101
+ const _checkHtmlNamespace = function _checkHtmlNamespace(tagName, parent, parentTagName) {
1102
+ // The only way to switch from SVG to HTML is via
1103
+ // HTML integration points, and from MathML to HTML
1104
+ // is via MathML text integration points
1105
+ if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
1106
+ return false;
1107
+ }
1108
+ if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
1109
+ return false;
1110
+ }
1111
+ // We disallow tags that are specific for MathML
1112
+ // or SVG and should never appear in HTML namespace
1113
+ return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
1114
+ };
804
1115
  /**
805
1116
  * @param element a DOM element whose namespace is being checked
806
1117
  * @returns Return false if the element has a
@@ -823,51 +1134,13 @@ var purify = {exports: {}};
823
1134
  return false;
824
1135
  }
825
1136
  if (element.namespaceURI === SVG_NAMESPACE) {
826
- // The only way to switch from HTML namespace to SVG
827
- // is via <svg>. If it happens via any other tag, then
828
- // it should be killed.
829
- if (parent.namespaceURI === HTML_NAMESPACE) {
830
- return tagName === 'svg';
831
- }
832
- // The only way to switch from MathML to SVG is via`
833
- // svg if parent is either <annotation-xml> or MathML
834
- // text integration points.
835
- if (parent.namespaceURI === MATHML_NAMESPACE) {
836
- return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
837
- }
838
- // We only allow elements that are defined in SVG
839
- // spec. All others are disallowed in SVG namespace.
840
- return Boolean(ALL_SVG_TAGS[tagName]);
1137
+ return _checkSvgNamespace(tagName, parent, parentTagName);
841
1138
  }
842
1139
  if (element.namespaceURI === MATHML_NAMESPACE) {
843
- // The only way to switch from HTML namespace to MathML
844
- // is via <math>. If it happens via any other tag, then
845
- // it should be killed.
846
- if (parent.namespaceURI === HTML_NAMESPACE) {
847
- return tagName === 'math';
848
- }
849
- // The only way to switch from SVG to MathML is via
850
- // <math> and HTML integration points
851
- if (parent.namespaceURI === SVG_NAMESPACE) {
852
- return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
853
- }
854
- // We only allow elements that are defined in MathML
855
- // spec. All others are disallowed in MathML namespace.
856
- return Boolean(ALL_MATHML_TAGS[tagName]);
1140
+ return _checkMathMlNamespace(tagName, parent, parentTagName);
857
1141
  }
858
1142
  if (element.namespaceURI === HTML_NAMESPACE) {
859
- // The only way to switch from SVG to HTML is via
860
- // HTML integration points, and from MathML to HTML
861
- // is via MathML text integration points
862
- if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
863
- return false;
864
- }
865
- if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
866
- return false;
867
- }
868
- // We disallow tags that are specific for MathML
869
- // or SVG and should never appear in HTML namespace
870
- return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
1143
+ return _checkHtmlNamespace(tagName, parent, parentTagName);
871
1144
  }
872
1145
  // For XHTML and XML documents that support custom namespaces
873
1146
  if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) {
@@ -892,7 +1165,81 @@ var purify = {exports: {}};
892
1165
  // eslint-disable-next-line unicorn/prefer-dom-node-remove
893
1166
  getParentNode(node).removeChild(node);
894
1167
  } catch (_) {
1168
+ /* The normal detach failed — this is reached for a parentless node
1169
+ (getParentNode() is null, so .removeChild throws). Element.prototype
1170
+ .remove() is itself a spec no-op on a parentless node, so a recorded
1171
+ "removal" would otherwise hand the caller back an intact,
1172
+ payload-bearing node (e.g. a detached IN_PLACE root the mXSS canary or
1173
+ the style-with-element-child rule decided to kill). Fail closed by
1174
+ throwing — exactly as a clobbered root does at the IN_PLACE entry —
1175
+ rather than trying to "neutralize" the node via its own methods.
1176
+ Neutralizing would mean calling getAttributeNames()/removeAttribute()
1177
+ on the node, both of which a <form> root can clobber via a named child
1178
+ (and _isClobbered does not even probe getAttributeNames), so the
1179
+ neutralize step could itself be silently defeated, leaving the payload
1180
+ intact. A throw touches only the cached, clobber-safe remove() and
1181
+ getParentNode(). Generalizes GHSA-r47g-fvhr-h676 (clobbered-form root)
1182
+ to every root-kill reason. REPORT-3.
1183
+ This lives inside the catch, so it never fires for a normally-removed
1184
+ in-tree node: those have a parent, removeChild() succeeds, and the
1185
+ catch is not entered. Only a kept (parentless) root reaches here. */
895
1186
  remove(node);
1187
+ if (!getParentNode(node)) {
1188
+ throw typeErrorCreate('a node selected for removal could not be detached from its tree ' + 'and cannot be safely returned; refusing to sanitize in place');
1189
+ }
1190
+ }
1191
+ };
1192
+ /**
1193
+ * _neutralizeRoot
1194
+ *
1195
+ * Fail-closed teardown of an in-place root after the sanitize walk aborts
1196
+ * (campaign-3 F2). An internal throw mid-walk — e.g. a page-registered
1197
+ * custom element's reaction detaches a node so `_forceRemove`'s deliberate
1198
+ * parentless guard throws, or any other re-entrant engine mutation — would
1199
+ * otherwise leave the caller's *live* tree half-sanitized, with everything
1200
+ * after the abort point still carrying its handlers. There is no safe way
1201
+ * to resume the walk (the tree mutated under us), so we strip the root bare:
1202
+ * remove every child and every attribute, then let the caller's catch see
1203
+ * the original error. Clobber-safe (cached `remove`/`childNodes`/`attributes`
1204
+ * getters; the root was already clobber-pre-flighted at the IN_PLACE entry).
1205
+ *
1206
+ * @param root the in-place root to empty
1207
+ */
1208
+ const _neutralizeRoot = function _neutralizeRoot(root) {
1209
+ /* Strip every disallowed attribute (on* handlers included) off the whole
1210
+ subtree BEFORE detaching anything. Detaching first would hand back
1211
+ handler-bearing originals (e.g. an already-loading `<img onerror>`)
1212
+ whose queued resource event still fires in page scope after we throw.
1213
+ Clobber-safe reads; a doomed clobbered node's own attributes are
1214
+ irrelevant while its non-clobbered descendants are reached and scrubbed. */
1215
+ _neutralizeSubtree(root);
1216
+ const childNodes = getChildNodes(root);
1217
+ if (childNodes) {
1218
+ const snapshot = [];
1219
+ arrayForEach(childNodes, child => {
1220
+ arrayPush(snapshot, child);
1221
+ });
1222
+ arrayForEach(snapshot, child => {
1223
+ try {
1224
+ remove(child);
1225
+ } catch (_) {
1226
+ /* Best-effort teardown; a still-attached child is handled below */
1227
+ }
1228
+ });
1229
+ }
1230
+ const attributes = getAttributes(root);
1231
+ if (attributes) {
1232
+ for (let i = attributes.length - 1; i >= 0; --i) {
1233
+ const attribute = attributes[i];
1234
+ const name = attribute && attribute.name;
1235
+ if (typeof name === 'string') {
1236
+ try {
1237
+ root.removeAttribute(name);
1238
+ } catch (_) {
1239
+ /* Clobbered removeAttribute — ignore (fail-closed best effort) */
1240
+ }
1241
+ }
1242
+ }
896
1243
  }
897
1244
  };
898
1245
  /**
@@ -927,6 +1274,148 @@ var purify = {exports: {}};
927
1274
  }
928
1275
  }
929
1276
  };
1277
+ /**
1278
+ * _stripDisallowedAttributes
1279
+ *
1280
+ * Removes every attribute the active configuration does not allow from a
1281
+ * single element, using the same allowlist as the main attribute pass (so
1282
+ * `on*` handlers go, but no `/^on/` blocklist is introduced). Used only to
1283
+ * neutralise nodes that are being discarded from an in-place tree.
1284
+ *
1285
+ * @param element the element to strip
1286
+ */
1287
+ const _stripDisallowedAttributes = function _stripDisallowedAttributes(element) {
1288
+ const attributes = getAttributes(element);
1289
+ if (!attributes) {
1290
+ return;
1291
+ }
1292
+ for (let i = attributes.length - 1; i >= 0; --i) {
1293
+ const attribute = attributes[i];
1294
+ const name = attribute && attribute.name;
1295
+ if (typeof name !== 'string' || ALLOWED_ATTR[transformCaseFunc(name)]) {
1296
+ continue;
1297
+ }
1298
+ try {
1299
+ element.removeAttribute(name);
1300
+ } catch (_) {
1301
+ /* Clobbered removeAttribute on a doomed node — ignore */
1302
+ }
1303
+ }
1304
+ };
1305
+ /**
1306
+ * _neutralizeSubtree
1307
+ *
1308
+ * Completes the audit-5 F1 fix across every removal path. The KEEP_CONTENT
1309
+ * move-hoist neutralises only disallowed-tag removals; clobber, mXSS-canary,
1310
+ * namespace, comment, processing-instruction and KEEP_CONTENT:false removals
1311
+ * all drop their subtree wholesale via `_forceRemove`. On the IN_PLACE path
1312
+ * those dropped nodes are detached from the caller's LIVE tree but a
1313
+ * handler-bearing original among them (an `<img onerror>`/`<video>` that was
1314
+ * loading) keeps its queued resource event, which fires in page scope after
1315
+ * sanitize returns. This walks a removed subtree and strips every attribute
1316
+ * the active configuration does not allow — so `on*` handlers are cancelled
1317
+ * through the SAME allowlist that governs kept nodes, not a separate `/^on/`
1318
+ * blocklist. Run synchronously before sanitize returns, i.e. before any
1319
+ * queued event can fire. Hook-free by design: these nodes leave the output,
1320
+ * so firing attribute hooks for them would be surprising. Clobber-safe reads;
1321
+ * a doomed clobbered node may shadow `removeAttribute` (its own attributes are
1322
+ * irrelevant — it is discarded — while its non-clobbered descendants, e.g.
1323
+ * the `<img>`, are reached and scrubbed).
1324
+ *
1325
+ * @param root the root of a removed subtree to neutralise
1326
+ */
1327
+ const _neutralizeSubtree = function _neutralizeSubtree(root) {
1328
+ const stack = [root];
1329
+ while (stack.length > 0) {
1330
+ const node = stack.pop();
1331
+ const nodeType = getNodeType ? getNodeType(node) : node.nodeType;
1332
+ if (nodeType === NODE_TYPE.element) {
1333
+ _stripDisallowedAttributes(node);
1334
+ }
1335
+ const childNodes = getChildNodes(node);
1336
+ if (childNodes) {
1337
+ for (let i = childNodes.length - 1; i >= 0; --i) {
1338
+ stack.push(childNodes[i]);
1339
+ }
1340
+ }
1341
+ }
1342
+ };
1343
+ /**
1344
+ * _neutralizePatchLinkage
1345
+ *
1346
+ * IN_PLACE entry pre-pass (declarative-partial-updates / streaming
1347
+ * hardening, https://github.com/WICG/declarative-partial-updates).
1348
+ *
1349
+ * The main walk strips patch linkage (`for`/`patchsrc`) and removes range
1350
+ * markers (PIs / markup comments) node-by-node, in document order, AS it
1351
+ * reaches each node. On a live in-place root that leaves a window: from the
1352
+ * moment the root is connected until the walk arrives at a given node, that
1353
+ * node's linkage is live. A patch applied on connection/stream can fire as
1354
+ * a microtask during the walk and inject or teleport an unsanitized DOM
1355
+ * range into a region the iterator has already passed and will not revisit,
1356
+ * so the post-return "tree is sanitized" contract is violated. Sweep the
1357
+ * whole tree once up front and sever every linkage before the walk begins,
1358
+ * closing that window.
1359
+ *
1360
+ * This CANNOT undo a patch that already fired before sanitize ran — that is
1361
+ * the irreducible "do not IN_PLACE a live-connected attacker tree" caveat —
1362
+ * but it closes everything from sanitize-start onward. Gated on SAFE_FOR_XML
1363
+ * to group with the rest of the declarative-partial-updates handling and
1364
+ * stay overridable, consistent with the codebase.
1365
+ *
1366
+ * Clobber-safe traversal (cached childNodes getter); per-node try/catch so a
1367
+ * clobbered root cannot defeat the sweep of its non-clobbered descendants.
1368
+ *
1369
+ * NOTE (pending real-Chrome confirmation, see test/declarative-patch-probe
1370
+ * .html Q1): this mirrors the existing policy of keeping `for` on
1371
+ * <label>/<output>. If the shipping feature can drive a patch through a
1372
+ * surviving `for`-on-label/output + `id` pair, this pre-pass and the
1373
+ * attribute check at _isBasicCustomElement's caller must additionally drop
1374
+ * that pair on the IN_PLACE path. Left as-is until the taxonomy is verified.
1375
+ *
1376
+ * @param root the in-place root to sweep
1377
+ */
1378
+ const _neutralizePatchLinkage = function _neutralizePatchLinkage(root) {
1379
+ if (!SAFE_FOR_XML) {
1380
+ return;
1381
+ }
1382
+ const stack = [root];
1383
+ while (stack.length > 0) {
1384
+ const node = stack.pop();
1385
+ const nodeType = getNodeType ? getNodeType(node) : node.nodeType;
1386
+ /* Remove range markers (the target side of a patch linkage): every
1387
+ processing instruction, and any markup-bearing comment. */
1388
+ if (nodeType === NODE_TYPE.processingInstruction || nodeType === NODE_TYPE.comment && regExpTest(COMMENT_MARKUP_PROBE, node.data)) {
1389
+ try {
1390
+ remove(node);
1391
+ } catch (_) {
1392
+ /* Best-effort */
1393
+ }
1394
+ continue;
1395
+ }
1396
+ /* Strip patch-source attributes (the source side) off elements. */
1397
+ if (nodeType === NODE_TYPE.element) {
1398
+ const element = node;
1399
+ const lcTag = transformCaseFunc(getNodeName ? getNodeName(node) : node.nodeName);
1400
+ try {
1401
+ if (element.hasAttribute && element.hasAttribute('patchsrc')) {
1402
+ element.removeAttribute('patchsrc');
1403
+ }
1404
+ if (element.hasAttribute && element.hasAttribute('for') && lcTag !== 'label' && lcTag !== 'output') {
1405
+ element.removeAttribute('for');
1406
+ }
1407
+ } catch (_) {
1408
+ /* Clobbered removeAttribute/hasAttribute on a doomed node — ignore */
1409
+ }
1410
+ }
1411
+ const childNodes = getChildNodes(node);
1412
+ if (childNodes) {
1413
+ for (let i = childNodes.length - 1; i >= 0; --i) {
1414
+ stack.push(childNodes[i]);
1415
+ }
1416
+ }
1417
+ }
1418
+ };
930
1419
  /**
931
1420
  * _initDocument
932
1421
  *
@@ -948,7 +1437,7 @@ var purify = {exports: {}};
948
1437
  // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)
949
1438
  dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + '</body></html>';
950
1439
  }
951
- const dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
1440
+ const dirtyPayload = trustedTypesPolicy ? _createTrustedHTML(dirty) : dirty;
952
1441
  /*
953
1442
  * Use the DOMParser API by default, fallback later if needs be
954
1443
  * DOMParser not work for svg when has multiple root element.
@@ -984,33 +1473,297 @@ var purify = {exports: {}};
984
1473
  * @return The created NodeIterator
985
1474
  */
986
1475
  const _createNodeIterator = function _createNodeIterator(root) {
987
- return createNodeIterator.call(root.ownerDocument || root, root,
1476
+ /* Read ownerDocument through the cached Node.prototype getter, never the
1477
+ direct property. HTMLFormElement has [LegacyOverrideBuiltIns], so a
1478
+ clobbering child (<input name="ownerDocument"> or a form-associated
1479
+ external input) shadows the prototype getter and makes a direct read
1480
+ return that <input>. createNodeIterator.call(<input>, ...) then throws
1481
+ "Illegal invocation", and on the IN_PLACE path that throw lands before
1482
+ the walk's fail-closed barrier - leaving the caller's live tree, with
1483
+ any already-armed handler in it, un-neutralized. The cached getter
1484
+ returns the real Document regardless of the clobber. */
1485
+ const doc = getOwnerDocument ? getOwnerDocument(root) : root.ownerDocument;
1486
+ return createNodeIterator.call(doc || root, root,
988
1487
  // eslint-disable-next-line no-bitwise
989
1488
  NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null);
990
1489
  };
1490
+ /**
1491
+ * Replace template expression syntax (mustache, ERB, template
1492
+ * literal) with a space; shared by all SAFE_FOR_TEMPLATES scrub
1493
+ * sites. Order matters: mustache, then ERB, then template literal.
1494
+ *
1495
+ * @param value the string to scrub
1496
+ * @returns the scrubbed string
1497
+ */
1498
+ const _stripTemplateExpressions = function _stripTemplateExpressions(value) {
1499
+ value = stringReplace(value, MUSTACHE_EXPR$1, ' ');
1500
+ value = stringReplace(value, ERB_EXPR$1, ' ');
1501
+ value = stringReplace(value, TMPLIT_EXPR$1, ' ');
1502
+ return value;
1503
+ };
1504
+ /**
1505
+ * Strip template-engine expressions ({{...}}, ${...}, <%...%>) from the
1506
+ * character data of an element subtree. Used as the final safety net for
1507
+ * SAFE_FOR_TEMPLATES on every DOM-returning code path so that expressions
1508
+ * which only form after text-node normalization (e.g. fragments split across
1509
+ * stripped elements) cannot survive into a template-evaluating framework.
1510
+ *
1511
+ * Walks text/comment/CDATA/processing-instruction nodes and mutates `.data`
1512
+ * in place rather than round-tripping through innerHTML. This preserves
1513
+ * descendant node references (important for IN_PLACE callers), avoids a
1514
+ * serialize/reparse cycle, and reads literal character data — which means
1515
+ * `<%...%>` in text content matches the ERB regex against its real bytes
1516
+ * instead of the HTML-entity-escaped form innerHTML would produce.
1517
+ *
1518
+ * Attribute values are not visited here; SAFE_FOR_TEMPLATES handling for
1519
+ * attributes is performed during the per-node `_sanitizeAttributes` pass.
1520
+ *
1521
+ * @param node The root element whose character data should be scrubbed.
1522
+ */
1523
+ const _scrubTemplateExpressions2 = function _scrubTemplateExpressions(node) {
1524
+ var _node$querySelectorAl;
1525
+ node.normalize();
1526
+ /* Clobber-safe ownerDocument read, same reasoning as _createNodeIterator:
1527
+ under SAFE_FOR_TEMPLATES this runs on the live IN_PLACE root, which may
1528
+ carry a form-named-getter override of ownerDocument. */
1529
+ const doc = getOwnerDocument ? getOwnerDocument(node) : node.ownerDocument;
1530
+ const walker = createNodeIterator.call(doc || node, node,
1531
+ // eslint-disable-next-line no-bitwise
1532
+ NodeFilter.SHOW_TEXT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_CDATA_SECTION | NodeFilter.SHOW_PROCESSING_INSTRUCTION, null);
1533
+ let currentNode = walker.nextNode();
1534
+ while (currentNode) {
1535
+ currentNode.data = _stripTemplateExpressions(currentNode.data);
1536
+ currentNode = walker.nextNode();
1537
+ }
1538
+ // NodeIterator does not descend into <template>.content per the DOM spec,
1539
+ // so we must explicitly recurse into each template's content fragment,
1540
+ // mirroring the approach used by _sanitizeShadowDOM.
1541
+ const templates = (_node$querySelectorAl = node.querySelectorAll) === null || _node$querySelectorAl === void 0 ? void 0 : _node$querySelectorAl.call(node, 'template');
1542
+ if (templates) {
1543
+ arrayForEach(templates, tmpl => {
1544
+ if (_isDocumentFragment(tmpl.content)) {
1545
+ _scrubTemplateExpressions2(tmpl.content);
1546
+ }
1547
+ });
1548
+ }
1549
+ };
991
1550
  /**
992
1551
  * _isClobbered
993
1552
  *
1553
+ * Detect DOM-clobbering on HTMLFormElement nodes. Form is the only HTML
1554
+ * interface with [LegacyOverrideBuiltIns]; a descendant element with a
1555
+ * `name` attribute matching a prototype property shadows that property
1556
+ * on direct reads. We use this check at the IN_PLACE entry-point and
1557
+ * during attribute sanitization to refuse clobbered forms.
1558
+ *
994
1559
  * @param element element to check for clobbering attacks
995
1560
  * @return true if clobbered, false if safe
996
1561
  */
997
1562
  const _isClobbered = function _isClobbered(element) {
998
- 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');
1563
+ // Realm-independent tag-name probe. If we can't determine the tag
1564
+ // name at all, we can't reason about clobbering — return false
1565
+ // (the caller's other defences still apply).
1566
+ const realTagName = getNodeName ? getNodeName(element) : null;
1567
+ if (typeof realTagName !== 'string') {
1568
+ return false;
1569
+ }
1570
+ if (transformCaseFunc(realTagName) !== 'form') {
1571
+ return false;
1572
+ }
1573
+ return typeof element.nodeName !== 'string' || typeof element.textContent !== 'string' || typeof element.removeChild !== 'function' ||
1574
+ // Realm-safe NamedNodeMap detection: equality against the cached
1575
+ // prototype getter. Clobbered .attributes (e.g. <input name="attributes">)
1576
+ // makes the direct read diverge from the cached read; a clean form
1577
+ // (same-realm OR foreign-realm) has both reads pointing at the same
1578
+ // canonical NamedNodeMap.
1579
+ element.attributes !== getAttributes(element) || typeof element.removeAttribute !== 'function' || typeof element.setAttribute !== 'function' || typeof element.namespaceURI !== 'string' || typeof element.insertBefore !== 'function' || typeof element.hasChildNodes !== 'function' ||
1580
+ // NodeType clobbering probe. Cached Node.prototype.nodeType getter
1581
+ // returns the integer 1 for any Element regardless of realm; direct
1582
+ // read on a clobbered form (e.g. <input name="nodeType">) returns
1583
+ // the named child element. Cheap addition — nodeType is read from
1584
+ // an internal slot, no serialization cost — and removes a residual
1585
+ // clobbering surface used by several mXSS / PI / comment branches
1586
+ // in _sanitizeElements that compare currentNode.nodeType directly.
1587
+ element.nodeType !== getNodeType(element) ||
1588
+ // HTMLFormElement has [LegacyOverrideBuiltIns]: a descendant named
1589
+ // "childNodes" shadows the prototype getter. Direct reads of
1590
+ // form.childNodes from a clobbered form return the named child
1591
+ // instead of the real NodeList, so any walk that reads it directly
1592
+ // skips the form's real children. Compare the direct read to the
1593
+ // cached Node.prototype getter — when the form's named-property
1594
+ // getter intercepts the read, the two values differ and we flag
1595
+ // the form. This catches every clobbering child type (input,
1596
+ // select, etc.) regardless of whether the named child happens to
1597
+ // carry a numeric .length, which a typeof-based probe would miss
1598
+ // (e.g. HTMLSelectElement.length is a defined unsigned-long).
1599
+ element.childNodes !== getChildNodes(element);
999
1600
  };
1000
1601
  /**
1001
- * Checks whether the given object is a DOM node.
1602
+ * Checks whether the given value is a DocumentFragment from any realm.
1603
+ *
1604
+ * The realm-independent replacement reads `nodeType` through the cached
1605
+ * Node.prototype getter and compares to the DOCUMENT_FRAGMENT_NODE
1606
+ * constant (11). nodeType is a numeric value resolved from the node's
1607
+ * internal slot, identical across realms for the same kind of node.
1608
+ *
1609
+ * @param value object to check
1610
+ * @return true if value is a DocumentFragment-shaped node from any realm
1611
+ */
1612
+ const _isDocumentFragment = function _isDocumentFragment(value) {
1613
+ if (!getNodeType || typeof value !== 'object' || value === null) {
1614
+ return false;
1615
+ }
1616
+ try {
1617
+ return getNodeType(value) === NODE_TYPE.documentFragment;
1618
+ } catch (_) {
1619
+ return false;
1620
+ }
1621
+ };
1622
+ /**
1623
+ * Checks whether the given object is a DOM node, including nodes that
1624
+ * originate from a different window/realm (e.g. an iframe's
1625
+ * contentDocument). The previous `value instanceof Node` check was
1626
+ * realm-bound: nodes from a different window failed it, causing
1627
+ * sanitize() to silently stringify them and reset IN_PLACE to false,
1628
+ * returning the original node unsanitized. See GHSA-4w3q-35jp-p934.
1002
1629
  *
1003
1630
  * @param value object to check whether it's a DOM node
1004
- * @return true is object is a DOM node
1631
+ * @return true if value is a DOM node from any realm
1005
1632
  */
1006
1633
  const _isNode = function _isNode(value) {
1007
- return typeof Node === 'function' && value instanceof Node;
1634
+ if (!getNodeType || typeof value !== 'object' || value === null) {
1635
+ return false;
1636
+ }
1637
+ try {
1638
+ return typeof getNodeType(value) === 'number';
1639
+ } catch (_) {
1640
+ return false;
1641
+ }
1008
1642
  };
1009
1643
  function _executeHooks(hooks, currentNode, data) {
1644
+ if (hooks.length === 0) {
1645
+ return;
1646
+ }
1010
1647
  arrayForEach(hooks, hook => {
1011
1648
  hook.call(DOMPurify, currentNode, data, CONFIG);
1012
1649
  });
1013
1650
  }
1651
+ /**
1652
+ * Structural-threat checks that condemn a node regardless of the
1653
+ * allowlists: mXSS via namespace confusion, risky CSS construction,
1654
+ * processing instructions, markup-bearing comments. Pure predicate;
1655
+ * the caller removes. Check order is load-bearing.
1656
+ *
1657
+ * @param currentNode the node to inspect
1658
+ * @param tagName the node's transformCaseFunc'd tag name
1659
+ * @return true if the node must be removed
1660
+ */
1661
+ const _isUnsafeNode = function _isUnsafeNode(currentNode, tagName) {
1662
+ /* Detect mXSS attempts abusing namespace confusion */
1663
+ if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.textContent) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.innerHTML)) {
1664
+ return true;
1665
+ }
1666
+ /* Remove risky CSS construction leading to mXSS */
1667
+ if (SAFE_FOR_XML && currentNode.namespaceURI === HTML_NAMESPACE && tagName === 'style' && _isNode(currentNode.firstElementChild)) {
1668
+ return true;
1669
+ }
1670
+ /* Remove any occurrence of processing instructions */
1671
+ if (currentNode.nodeType === NODE_TYPE.processingInstruction) {
1672
+ return true;
1673
+ }
1674
+ /* Remove any kind of possibly harmful comments */
1675
+ if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(COMMENT_MARKUP_PROBE, currentNode.data)) {
1676
+ return true;
1677
+ }
1678
+ return false;
1679
+ };
1680
+ /**
1681
+ * Handle a node whose tag is forbidden or not allowlisted: keep
1682
+ * allowed custom elements (false return exits _sanitizeElements
1683
+ * early - the namespace and fallback-tag removal checks are
1684
+ * intentionally skipped for kept custom elements), else hoist
1685
+ * content per KEEP_CONTENT and remove.
1686
+ *
1687
+ * A kept custom element is the ONLY case in which this function
1688
+ * returns false, so the caller uses that return value to run the
1689
+ * afterSanitizeElements hook on the kept element and keep the
1690
+ * element-hook lifecycle consistent with normal allowlisted
1691
+ * elements (GHSA-c2j3-45gr-mqc4).
1692
+ *
1693
+ * @param currentNode the disallowed node
1694
+ * @param tagName the node's transformCaseFunc'd tag name
1695
+ * @return true if the node was removed, false if kept
1696
+ */
1697
+ const _sanitizeDisallowedNode = function _sanitizeDisallowedNode(currentNode, tagName, root) {
1698
+ /* Check if we have a custom element to handle */
1699
+ if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {
1700
+ if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {
1701
+ return false;
1702
+ }
1703
+ if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) {
1704
+ return false;
1705
+ }
1706
+ }
1707
+ /* Keep content except for bad-listed elements.
1708
+ Use the cached prototype getters exclusively — the previous code
1709
+ had `|| currentNode.parentNode` / `|| currentNode.childNodes`
1710
+ fallbacks, but the cached getters always return the canonical
1711
+ value (or null for a real parent-less node), so the fallback
1712
+ path was dead in safe cases and a clobbering surface in unsafe
1713
+ ones. Falsy cached results stay falsy; the `if (childNodes &&
1714
+ parentNode)` check already gates correctly. */
1715
+ if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
1716
+ const parentNode = getParentNode(currentNode);
1717
+ const childNodes = getChildNodes(currentNode);
1718
+ if (childNodes && parentNode) {
1719
+ const childCount = childNodes.length;
1720
+ /* Hoist by moving each child up one level rather than deep-cloning
1721
+ it. Moving transfers every descendant exactly once, so a chain of
1722
+ nested disallowed elements costs O(n) instead of the O(n^2) that
1723
+ re-cloning the shrinking subtree at each level produced; it also
1724
+ empties the removed original, so `DOMPurify.removed` no longer
1725
+ pins whole subtrees. Moving preserves the in-place guarantee too:
1726
+ an original carrying already-queued resource events (`<img
1727
+ onerror>`, `<video>`/`<audio>` error, lazy/`onload`, …) is
1728
+ relocated and sanitised rather than left detached but still armed.
1729
+ The sole case that must clone is removing the walk root itself.
1730
+ The result is serialised from the root's subtree, so a restrictive
1731
+ ALLOWED_TAGS that strips the root (`body` on the string path) must
1732
+ leave the content inside it, which only cloning does. In IN_PLACE
1733
+ the root is pre-validated as an allowed tag and so is never removed
1734
+ here, so that path always takes the move branch.
1735
+ `childNodes` is live; a tail-to-head walk keeps `childNodes[i]`
1736
+ valid whether we move (drops the trailing entry) or clone (leaves
1737
+ the list intact). */
1738
+ for (let i = childCount - 1; i >= 0; --i) {
1739
+ const hoisted = currentNode === root ? cloneNode(childNodes[i], true) : childNodes[i];
1740
+ parentNode.insertBefore(hoisted, getNextSibling(currentNode));
1741
+ }
1742
+ }
1743
+ }
1744
+ _forceRemove(currentNode);
1745
+ return true;
1746
+ };
1747
+ /**
1748
+ * Fork a hook-mutable allowlist off its shared binding the first time a
1749
+ * (possibly lazily-installed) uponSanitize* hook is about to see it, so the
1750
+ * hook cannot widen the per-instance default or the setConfig binding by
1751
+ * reference and leak past the call. Returns the set unchanged once it is
1752
+ * already call-local, so repeated calls across elements are idempotent.
1753
+ *
1754
+ * @param hookList the uponSanitize* hook array for this event
1755
+ * @param set the current ALLOWED_TAGS / ALLOWED_ATTR binding
1756
+ * @param defaultSet the per-instance DEFAULT_ALLOWED_* constant
1757
+ * @param setConfigSet the captured setConfig() binding, or null
1758
+ * @return a call-local clone if a hook is present and set is still shared,
1759
+ * else set unchanged
1760
+ */
1761
+ const _forkSharedAllowlist = function _forkSharedAllowlist(hookList, set, defaultSet, setConfigSet) {
1762
+ if (hookList.length === 0) {
1763
+ return set;
1764
+ }
1765
+ return set === defaultSet || set === setConfigSet ? clone(set) : set;
1766
+ };
1014
1767
  /**
1015
1768
  * _sanitizeElements
1016
1769
  *
@@ -1020,86 +1773,112 @@ var purify = {exports: {}};
1020
1773
  * @param currentNode to check for permission to exist
1021
1774
  * @return true if node was killed, false if left alive
1022
1775
  */
1023
- const _sanitizeElements = function _sanitizeElements(currentNode) {
1024
- let content = null;
1776
+ // eslint-disable-next-line complexity
1777
+ const _sanitizeElements = function _sanitizeElements(currentNode, root) {
1025
1778
  /* Execute a hook if present */
1026
1779
  _executeHooks(hooks.beforeSanitizeElements, currentNode, null);
1780
+ /* A hook may have detached the node - treat it as removed (see the
1781
+ detached-node comment after the uponSanitizeElement hook below). On
1782
+ the IN_PLACE path, neutralize the detached subtree first so a queued
1783
+ resource handler on it cannot fire in page scope after we return. */
1784
+ if (currentNode !== root && getParentNode(currentNode) === null) {
1785
+ if (IN_PLACE) {
1786
+ _neutralizeSubtree(currentNode);
1787
+ }
1788
+ return true;
1789
+ }
1027
1790
  /* Check if element is clobbered or can clobber */
1028
1791
  if (_isClobbered(currentNode)) {
1029
1792
  _forceRemove(currentNode);
1030
1793
  return true;
1031
1794
  }
1032
1795
  /* Now let's check the element's type and name */
1033
- const tagName = transformCaseFunc(currentNode.nodeName);
1796
+ const tagName = transformCaseFunc(getNodeName ? getNodeName(currentNode) : currentNode.nodeName);
1797
+ /* Close the pre-walk clone-guard's timing gap: an uponSanitizeElement
1798
+ hook may have been installed after that guard sampled the hook arrays
1799
+ (e.g. lazily from beforeSanitizeElements), leaving ALLOWED_TAGS still
1800
+ aliasing a shared binding that a widening hook would mutate by
1801
+ reference. Fork it before exposing it to the hook. */
1802
+ ALLOWED_TAGS = _forkSharedAllowlist(hooks.uponSanitizeElement, ALLOWED_TAGS, DEFAULT_ALLOWED_TAGS, SET_CONFIG_ALLOWED_TAGS);
1034
1803
  /* Execute a hook if present */
1035
1804
  _executeHooks(hooks.uponSanitizeElement, currentNode, {
1036
1805
  tagName,
1037
1806
  allowedTags: ALLOWED_TAGS
1038
1807
  });
1039
- /* Detect mXSS attempts abusing namespace confusion */
1040
- if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(/<[/\w!]/g, currentNode.innerHTML) && regExpTest(/<[/\w!]/g, currentNode.textContent)) {
1041
- _forceRemove(currentNode);
1042
- return true;
1043
- }
1044
- /* Remove risky CSS construction leading to mXSS */
1045
- if (SAFE_FOR_XML && currentNode.namespaceURI === HTML_NAMESPACE && tagName === 'style' && _isNode(currentNode.firstElementChild)) {
1046
- _forceRemove(currentNode);
1808
+ /* A hook may have detached the node from the tree — a long-standing
1809
+ user pattern (issue #469; draw.io-style foreignObject filtering).
1810
+ Per the cached, unclobberable parentNode getter the node is
1811
+ genuinely out of the tree, so it can reach neither the serialized
1812
+ output nor an IN_PLACE live tree; treat it as removed and stop
1813
+ processing it. Without this guard, the unsafe-node / namespace
1814
+ checks below would call _forceRemove on a parentless node and hit
1815
+ the REPORT-3 fail-closed throw — which exists for nodes DOMPurify
1816
+ wants gone but *cannot* detach (clobbered / parentless roots), the
1817
+ opposite of a node that is already safely gone. The walk root is
1818
+ exempt: a detached IN_PLACE root is legitimate input and must still
1819
+ be fully sanitized, and a kill-decision on it must keep hitting the
1820
+ REPORT-3 throw. Nodes detached by hooks stay the hook's
1821
+ responsibility for placement: they are not recorded in
1822
+ DOMPurify.removed, so the post-walk IN_PLACE pass (which iterates
1823
+ DOMPurify.removed) does not reach them. But a hook-detached subtree
1824
+ can still hold a queued resource-event handler - e.g. an <img onload>
1825
+ that began loading when the caller built the live tree - which fires
1826
+ in page scope after sanitize returns even though the handler never
1827
+ reached the returned tree. That is the audit-5 F1 hazard, and the
1828
+ documented node.remove() hook pattern walks straight into it. So on
1829
+ the IN_PLACE path we neutralize the detached subtree inline here,
1830
+ stripping its non-allow-listed attributes before returning, exactly
1831
+ as the post-walk pass does for _forceRemove'd subtrees. */
1832
+ if (currentNode !== root && getParentNode(currentNode) === null) {
1833
+ if (IN_PLACE) {
1834
+ _neutralizeSubtree(currentNode);
1835
+ }
1047
1836
  return true;
1048
1837
  }
1049
- /* Remove any occurrence of processing instructions */
1050
- if (currentNode.nodeType === NODE_TYPE.progressingInstruction) {
1051
- _forceRemove(currentNode);
1052
- return true;
1053
- }
1054
- /* Remove any kind of possibly harmful comments */
1055
- if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(/<[/\w]/g, currentNode.data)) {
1838
+ /* Remove mXSS vectors, processing instructions and risky comments */
1839
+ if (_isUnsafeNode(currentNode, tagName)) {
1056
1840
  _forceRemove(currentNode);
1057
1841
  return true;
1058
1842
  }
1059
1843
  /* Remove element if anything forbids its presence */
1060
1844
  if (FORBID_TAGS[tagName] || !(EXTRA_ELEMENT_HANDLING.tagCheck instanceof Function && EXTRA_ELEMENT_HANDLING.tagCheck(tagName)) && !ALLOWED_TAGS[tagName]) {
1061
- /* Check if we have a custom element to handle */
1062
- if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {
1063
- if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {
1064
- return false;
1065
- }
1066
- if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) {
1067
- return false;
1068
- }
1069
- }
1070
- /* Keep content except for bad-listed elements */
1071
- if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
1072
- const parentNode = getParentNode(currentNode) || currentNode.parentNode;
1073
- const childNodes = getChildNodes(currentNode) || currentNode.childNodes;
1074
- if (childNodes && parentNode) {
1075
- const childCount = childNodes.length;
1076
- for (let i = childCount - 1; i >= 0; --i) {
1077
- const childClone = cloneNode(childNodes[i], true);
1078
- childClone.__removalCount = (currentNode.__removalCount || 0) + 1;
1079
- parentNode.insertBefore(childClone, getNextSibling(currentNode));
1080
- }
1081
- }
1845
+ const removed = _sanitizeDisallowedNode(currentNode, tagName, root);
1846
+ /* A false return means the node is a custom element kept via
1847
+ CUSTOM_ELEMENT_HANDLING - the only keep path through
1848
+ _sanitizeDisallowedNode. Run afterSanitizeElements on it so the
1849
+ element-hook lifecycle matches normal allowlisted elements: a
1850
+ security policy applied in this hook (e.g. stripping an attribute
1851
+ from every surviving element) must not silently skip kept custom
1852
+ elements (GHSA-c2j3-45gr-mqc4). This mirrors the normal-element
1853
+ tail below - the hook runs, then the walker's subsequent
1854
+ _sanitizeAttributes pass sanitizes the element's attributes. The
1855
+ deliberately skipped namespace and fallback-tag removal checks stay
1856
+ skipped; they are removal decisions, not the hook contract. */
1857
+ if (removed === false) {
1858
+ _executeHooks(hooks.afterSanitizeElements, currentNode, null);
1082
1859
  }
1083
- _forceRemove(currentNode);
1084
- return true;
1085
- }
1086
- /* Check whether element has a valid namespace */
1087
- if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {
1860
+ return removed;
1861
+ }
1862
+ /* Check whether element has a valid namespace.
1863
+ Realm-safe check (GHSA-hpcv-96wg-7vj8): use the cached Node.prototype
1864
+ nodeType getter rather than `instanceof Element`, which is realm-
1865
+ bound and short-circuits to false for any node minted in a different
1866
+ realm — letting a foreign-realm element with a forbidden namespace
1867
+ slip past the namespace check entirely. */
1868
+ const nt = getNodeType ? getNodeType(currentNode) : currentNode.nodeType;
1869
+ if (nt === NODE_TYPE.element && !_checkValidNamespace(currentNode)) {
1088
1870
  _forceRemove(currentNode);
1089
1871
  return true;
1090
1872
  }
1091
1873
  /* Make sure that older browsers don't get fallback-tag mXSS */
1092
- if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(/<\/no(script|embed|frames)/i, currentNode.innerHTML)) {
1874
+ if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(FALLBACK_TAG_CLOSE, currentNode.innerHTML)) {
1093
1875
  _forceRemove(currentNode);
1094
1876
  return true;
1095
1877
  }
1096
1878
  /* Sanitize element content to be template-safe */
1097
1879
  if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) {
1098
1880
  /* Get the element's text content */
1099
- content = currentNode.textContent;
1100
- arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
1101
- content = stringReplace(content, expr, ' ');
1102
- });
1881
+ const content = _stripTemplateExpressions(currentNode.textContent);
1103
1882
  if (currentNode.textContent !== content) {
1104
1883
  arrayPush(DOMPurify.removed, {
1105
1884
  element: currentNode.cloneNode()
@@ -1125,15 +1904,43 @@ var purify = {exports: {}};
1125
1904
  if (FORBID_ATTR[lcName]) {
1126
1905
  return false;
1127
1906
  }
1907
+ /* Reject declarative-partial-updates patch-linkage attributes
1908
+ (https://github.com/WICG/declarative-partial-updates).
1909
+ Empirical note (Chrome 150, verified — see
1910
+ test/declarative-patch-probe-v3.html): expansion is NOT applied after
1911
+ sanitization. For the string path it fires during sanitize()'s own
1912
+ parse, so the walk sees and sanitizes the fully materialized expanded
1913
+ tree — teleports into MathML/SVG integration points included; a
1914
+ weaponized `<template for>`->`<img onerror>` comes back with the handler
1915
+ stripped. For the IN_PLACE path it fires on connection, before the walk.
1916
+ Either way DOMPurify is NOT blind to the patch.
1917
+ This removal is therefore defense-in-depth rather than the sole barrier:
1918
+ it prevents live linkage from surviving into the OUTPUT and re-expanding
1919
+ in the caller's context, and keeps behaviour deterministic if a future
1920
+ engine defers expansion. `for` is legitimate only on <label>/<output>;
1921
+ anywhere else (notably <template for>) it links the element to a patch
1922
+ target and teleports or removes an arbitrary DOM range by id/marker name.
1923
+ `patchsrc` fetches remote markup and is treated as a script-loading
1924
+ mechanism (CSP). Gated on SAFE_FOR_XML so the removal groups with the
1925
+ other structural-threat checks and stays overridable, consistent with
1926
+ the rest of the codebase. PI range markers are already removed by
1927
+ _isUnsafeNode. */
1928
+ if (SAFE_FOR_XML && lcName === 'patchsrc') {
1929
+ return false;
1930
+ }
1931
+ if (SAFE_FOR_XML && lcName === 'for' && lcTag !== 'label' && lcTag !== 'output') {
1932
+ return false;
1933
+ }
1128
1934
  /* Make sure attribute cannot clobber */
1129
1935
  if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {
1130
1936
  return false;
1131
1937
  }
1938
+ const nameIsPermitted = ALLOWED_ATTR[lcName] || EXTRA_ELEMENT_HANDLING.attributeCheck instanceof Function && EXTRA_ELEMENT_HANDLING.attributeCheck(lcName, lcTag);
1132
1939
  /* Allow valid data-* attributes: At least one character after "-"
1133
1940
  (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
1134
1941
  XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)
1135
1942
  We don't need to check the value; it's always URI safe. */
1136
- 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]) {
1943
+ if (ALLOW_DATA_ATTR && regExpTest(DATA_ATTR$1, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR$1, lcName)) ; else if (!nameIsPermitted) {
1137
1944
  if (
1138
1945
  // First condition does a very basic check if a) it's basically a valid custom element tagname AND
1139
1946
  // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
@@ -1145,11 +1952,15 @@ var purify = {exports: {}};
1145
1952
  return false;
1146
1953
  }
1147
1954
  /* Check value is safe. First, is attr inert? If so, is safe */
1148
- } 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) {
1955
+ } 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) {
1149
1956
  return false;
1150
1957
  } else ;
1151
1958
  return true;
1152
1959
  };
1960
+ /* Names the HTML spec reserves from valid-custom-element-name; these must
1961
+ * never be treated as basic custom elements even when a permissive
1962
+ * CUSTOM_ELEMENT_HANDLING.tagNameCheck is configured. */
1963
+ 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']);
1153
1964
  /**
1154
1965
  * _isBasicCustomElement
1155
1966
  * checks if at least one dash is included in tagName, and it's not the first char
@@ -1159,7 +1970,64 @@ var purify = {exports: {}};
1159
1970
  * @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false.
1160
1971
  */
1161
1972
  const _isBasicCustomElement = function _isBasicCustomElement(tagName) {
1162
- return tagName !== 'annotation-xml' && stringMatch(tagName, CUSTOM_ELEMENT);
1973
+ return !RESERVED_CUSTOM_ELEMENT_NAMES[stringToLowerCase(tagName)] && regExpTest(CUSTOM_ELEMENT$1, tagName);
1974
+ };
1975
+ /**
1976
+ * Wrap an attribute value in the matching Trusted Types object when
1977
+ * the active policy requires it. Namespaced attributes pass through
1978
+ * unchanged (no TT support yet, see
1979
+ * https://bugs.chromium.org/p/chromium/issues/detail?id=1305293).
1980
+ *
1981
+ * @param lcTag lowercase tag name of the containing element
1982
+ * @param lcName lowercase attribute name
1983
+ * @param namespaceURI the attribute's namespace, if any
1984
+ * @param value the attribute value to wrap
1985
+ * @return the value, wrapped when Trusted Types demand it
1986
+ */
1987
+ const _applyTrustedTypesToAttribute = function _applyTrustedTypesToAttribute(lcTag, lcName, namespaceURI, value) {
1988
+ if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function' && !namespaceURI) {
1989
+ switch (trustedTypes.getAttributeType(lcTag, lcName)) {
1990
+ case 'TrustedHTML':
1991
+ {
1992
+ return _createTrustedHTML(value);
1993
+ }
1994
+ case 'TrustedScriptURL':
1995
+ {
1996
+ return _createTrustedScriptURL(value);
1997
+ }
1998
+ }
1999
+ }
2000
+ return value;
2001
+ };
2002
+ /**
2003
+ * Write a modified attribute value back onto the element. On
2004
+ * success, re-probe for clobbering introduced by the new value and
2005
+ * remove the element when found; otherwise pop the removal entry
2006
+ * recorded by the earlier _removeAttribute (long-standing pairing
2007
+ * with the SANITIZE_NAMED_PROPS path - do not "fix" casually). On
2008
+ * failure, remove the attribute instead.
2009
+ *
2010
+ * @param currentNode the element carrying the attribute
2011
+ * @param name the attribute name as present on the element
2012
+ * @param namespaceURI the attribute's namespace, if any
2013
+ * @param value the new attribute value
2014
+ */
2015
+ const _setAttributeValue = function _setAttributeValue(currentNode, name, namespaceURI, value) {
2016
+ try {
2017
+ if (namespaceURI) {
2018
+ currentNode.setAttributeNS(namespaceURI, name, value);
2019
+ } else {
2020
+ /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
2021
+ currentNode.setAttribute(name, value);
2022
+ }
2023
+ if (_isClobbered(currentNode)) {
2024
+ _forceRemove(currentNode);
2025
+ } else {
2026
+ arrayPop(DOMPurify.removed);
2027
+ }
2028
+ } catch (_) {
2029
+ _removeAttribute(name, currentNode);
2030
+ }
1163
2031
  };
1164
2032
  /**
1165
2033
  * _sanitizeAttributes
@@ -1174,13 +2042,14 @@ var purify = {exports: {}};
1174
2042
  const _sanitizeAttributes = function _sanitizeAttributes(currentNode) {
1175
2043
  /* Execute a hook if present */
1176
2044
  _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null);
1177
- const {
1178
- attributes
1179
- } = currentNode;
2045
+ const attributes = currentNode.attributes;
1180
2046
  /* Check if we have attributes; if not we might have a text node */
1181
2047
  if (!attributes || _isClobbered(currentNode)) {
1182
2048
  return;
1183
2049
  }
2050
+ /* Same lazy-install guard as uponSanitizeElement (see there): fork the
2051
+ attribute allowlist off its shared binding before a hook can see it. */
2052
+ ALLOWED_ATTR = _forkSharedAllowlist(hooks.uponSanitizeAttribute, ALLOWED_ATTR, DEFAULT_ALLOWED_ATTR, SET_CONFIG_ALLOWED_ATTR);
1184
2053
  const hookEvent = {
1185
2054
  attrName: '',
1186
2055
  attrValue: '',
@@ -1189,14 +2058,13 @@ var purify = {exports: {}};
1189
2058
  forceKeepAttr: undefined
1190
2059
  };
1191
2060
  let l = attributes.length;
2061
+ const lcTag = transformCaseFunc(currentNode.nodeName);
1192
2062
  /* Go backwards over all attributes; safely remove bad ones */
1193
2063
  while (l--) {
1194
2064
  const attr = attributes[l];
1195
- const {
1196
- name,
1197
- namespaceURI,
1198
- value: attrValue
1199
- } = attr;
2065
+ const name = attr.name,
2066
+ namespaceURI = attr.namespaceURI,
2067
+ attrValue = attr.value;
1200
2068
  const lcName = transformCaseFunc(name);
1201
2069
  const initValue = attrValue;
1202
2070
  let value = name === 'value' ? initValue : stringTrim(initValue);
@@ -1210,12 +2078,14 @@ var purify = {exports: {}};
1210
2078
  /* Full DOM Clobbering protection via namespace isolation,
1211
2079
  * Prefix id and name attributes with `user-content-`
1212
2080
  */
1213
- if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name')) {
2081
+ if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name') && stringIndexOf(value, SANITIZE_NAMED_PROPS_PREFIX) !== 0) {
1214
2082
  // Remove the attribute with this value
1215
2083
  _removeAttribute(name, currentNode);
1216
2084
  // Prefix the value and later re-create the attribute with the sanitized value
1217
2085
  value = SANITIZE_NAMED_PROPS_PREFIX + value;
1218
2086
  }
2087
+ // Else: already prefixed, leave the attribute alone — the prefix is
2088
+ // itself the clobbering protection, and re-applying it is incorrect.
1219
2089
  /* Work around a security issue with comments inside attributes */
1220
2090
  if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i, value)) {
1221
2091
  _removeAttribute(name, currentNode);
@@ -1226,7 +2096,7 @@ var purify = {exports: {}};
1226
2096
  _removeAttribute(name, currentNode);
1227
2097
  continue;
1228
2098
  }
1229
- /* Did the hooks approve of the attribute? */
2099
+ /* Did the hooks force-keep the attribute? */
1230
2100
  if (hookEvent.forceKeepAttr) {
1231
2101
  continue;
1232
2102
  }
@@ -1236,56 +2106,24 @@ var purify = {exports: {}};
1236
2106
  continue;
1237
2107
  }
1238
2108
  /* Work around a security issue in jQuery 3.0 */
1239
- if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) {
2109
+ if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(SELF_CLOSING_TAG, value)) {
1240
2110
  _removeAttribute(name, currentNode);
1241
2111
  continue;
1242
2112
  }
1243
2113
  /* Sanitize attribute content to be template-safe */
1244
2114
  if (SAFE_FOR_TEMPLATES) {
1245
- arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
1246
- value = stringReplace(value, expr, ' ');
1247
- });
2115
+ value = _stripTemplateExpressions(value);
1248
2116
  }
1249
2117
  /* Is `value` valid for this attribute? */
1250
- const lcTag = transformCaseFunc(currentNode.nodeName);
1251
2118
  if (!_isValidAttribute(lcTag, lcName, value)) {
1252
2119
  _removeAttribute(name, currentNode);
1253
2120
  continue;
1254
2121
  }
1255
2122
  /* Handle attributes that require Trusted Types */
1256
- if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function') {
1257
- if (namespaceURI) ; else {
1258
- switch (trustedTypes.getAttributeType(lcTag, lcName)) {
1259
- case 'TrustedHTML':
1260
- {
1261
- value = trustedTypesPolicy.createHTML(value);
1262
- break;
1263
- }
1264
- case 'TrustedScriptURL':
1265
- {
1266
- value = trustedTypesPolicy.createScriptURL(value);
1267
- break;
1268
- }
1269
- }
1270
- }
1271
- }
2123
+ value = _applyTrustedTypesToAttribute(lcTag, lcName, namespaceURI, value);
1272
2124
  /* Handle invalid data-* attribute set by try-catching it */
1273
2125
  if (value !== initValue) {
1274
- try {
1275
- if (namespaceURI) {
1276
- currentNode.setAttributeNS(namespaceURI, name, value);
1277
- } else {
1278
- /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
1279
- currentNode.setAttribute(name, value);
1280
- }
1281
- if (_isClobbered(currentNode)) {
1282
- _forceRemove(currentNode);
1283
- } else {
1284
- arrayPop(DOMPurify.removed);
1285
- }
1286
- } catch (_) {
1287
- _removeAttribute(name, currentNode);
1288
- }
2126
+ _setAttributeValue(currentNode, name, namespaceURI, value);
1289
2127
  }
1290
2128
  }
1291
2129
  /* Execute a hook if present */
@@ -1305,17 +2143,136 @@ var purify = {exports: {}};
1305
2143
  /* Execute a hook if present */
1306
2144
  _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null);
1307
2145
  /* Sanitize tags and elements */
1308
- _sanitizeElements(shadowNode);
2146
+ _sanitizeElements(shadowNode, fragment);
1309
2147
  /* Check attributes next */
1310
2148
  _sanitizeAttributes(shadowNode);
1311
- /* Deep shadow DOM detected */
1312
- if (shadowNode.content instanceof DocumentFragment) {
2149
+ /* Deep shadow DOM detected.
2150
+ Realm-safe check (GHSA-hpcv-96wg-7vj8): use nodeType against the
2151
+ DOCUMENT_FRAGMENT_NODE constant rather than instanceof, so we
2152
+ recurse into <template>.content from foreign realms too. */
2153
+ if (_isDocumentFragment(shadowNode.content)) {
1313
2154
  _sanitizeShadowDOM2(shadowNode.content);
1314
2155
  }
2156
+ /* An element iterated here may itself host an attached
2157
+ shadow root. The default NodeIterator does not enter shadow
2158
+ trees, so a shadow root nested inside template.content was
2159
+ previously reached by no walk at all (the pre-pass at
2160
+ _sanitizeAttachedShadowRoots descends via childNodes, which
2161
+ doesn't enter template.content; the template-content recursion
2162
+ above iterates the content but never inspected shadowRoot).
2163
+ Walk it explicitly. The nodeType guard avoids reading
2164
+ shadowRoot off text / comment / CDATA / PI nodes that the
2165
+ iterator also surfaces. */
2166
+ const shadowNodeType = getNodeType ? getNodeType(shadowNode) : shadowNode.nodeType;
2167
+ if (shadowNodeType === NODE_TYPE.element) {
2168
+ const innerSr = getShadowRoot(shadowNode);
2169
+ if (_isDocumentFragment(innerSr)) {
2170
+ _sanitizeAttachedShadowRoots(innerSr);
2171
+ _sanitizeShadowDOM2(innerSr);
2172
+ }
2173
+ }
1315
2174
  }
1316
2175
  /* Execute a hook if present */
1317
2176
  _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null);
1318
2177
  };
2178
+ /**
2179
+ * _sanitizeAttachedShadowRoots
2180
+ *
2181
+ * Walks `root` and feeds every attached shadow root we encounter into
2182
+ * the existing _sanitizeShadowDOM pipeline. The default node iterator
2183
+ * does not descend into shadow trees, so nodes inside an attached
2184
+ * shadow root would otherwise be skipped entirely.
2185
+ *
2186
+ * Two real input paths put attached shadow roots in front of us:
2187
+ * 1. IN_PLACE on a DOM node that already has shadow roots attached.
2188
+ * 2. DOM-node input where importNode(dirty, true) deep-clones the
2189
+ * shadow root because it was created with `clonable: true`.
2190
+ *
2191
+ * This pass runs once, up front, so the main iteration loop (and the
2192
+ * existing _sanitizeShadowDOM template-content recursion) stay
2193
+ * untouched — string-input paths are not affected.
2194
+ *
2195
+ * @param root the subtree root to walk for attached shadow roots
2196
+ */
2197
+ const _sanitizeAttachedShadowRoots = function _sanitizeAttachedShadowRoots(root) {
2198
+ /* Iterative (explicit stack) rather than per-child recursion. DOM APIs
2199
+ impose no depth cap, so an attacker-shaped tree (JSON/CRDT/editor data
2200
+ built straight into the DOM — the IN_PLACE surface) deeper than the JS
2201
+ call-stack budget would otherwise overflow native recursion here and
2202
+ throw at the IN_PLACE entry pre-pass, before a single node is
2203
+ sanitized, leaving the caller's live tree untouched (fail-open). See
2204
+ campaign-3 F4. A heap stack keeps depth off the call stack.
2205
+ Each work item is either a node to descend into, or a deferred
2206
+ `_sanitizeShadowDOM` for an already-walked shadow root. The deferred
2207
+ form preserves the original post-order discipline: a shadow root's
2208
+ nested shadow roots are discovered before the outer shadow is
2209
+ sanitized (which may remove hosts). Pushes are in reverse of the
2210
+ desired processing order (LIFO): template content, then children, then
2211
+ the shadow-sanitize, then the shadow walk — so the order matches the
2212
+ previous recursion exactly. */
2213
+ const stack = [{
2214
+ node: root,
2215
+ shadow: null
2216
+ }];
2217
+ while (stack.length > 0) {
2218
+ const item = stack.pop();
2219
+ /* Deferred shadow-DOM sanitisation: runs after its subtree was walked. */
2220
+ if (item.shadow) {
2221
+ _sanitizeShadowDOM2(item.shadow);
2222
+ continue;
2223
+ }
2224
+ const node = item.node;
2225
+ const nodeType = getNodeType ? getNodeType(node) : node.nodeType;
2226
+ const isElement = nodeType === NODE_TYPE.element;
2227
+ /* (pushed last → processed first) Children, snapshotted in reverse so
2228
+ the first child is processed first. Snapshotting matters because a
2229
+ hook may detach siblings mid-walk. */
2230
+ const childNodes = getChildNodes(node);
2231
+ if (childNodes) {
2232
+ for (let i = childNodes.length - 1; i >= 0; --i) {
2233
+ stack.push({
2234
+ node: childNodes[i],
2235
+ shadow: null
2236
+ });
2237
+ }
2238
+ }
2239
+ /* (pushed before children → processed after them, matching the old
2240
+ "template content last" order) When the node is a <template>,
2241
+ descend into its content. */
2242
+ if (isElement) {
2243
+ const rootName = getNodeName ? getNodeName(node) : null;
2244
+ if (typeof rootName === 'string' && transformCaseFunc(rootName) === 'template') {
2245
+ const content = node.content;
2246
+ if (_isDocumentFragment(content)) {
2247
+ stack.push({
2248
+ node: content,
2249
+ shadow: null
2250
+ });
2251
+ }
2252
+ }
2253
+ }
2254
+ /* Shadow root (processed first): walk its subtree, then sanitise it.
2255
+ Realm-safe check (GHSA-hpcv-96wg-7vj8): nodeType-based detection
2256
+ rather than `instanceof DocumentFragment`, which is realm-bound and
2257
+ silently skipped foreign-realm shadow roots (e.g.
2258
+ iframe.contentDocument attachShadow). */
2259
+ if (isElement) {
2260
+ const sr = getShadowRoot(node);
2261
+ if (_isDocumentFragment(sr)) {
2262
+ /* Push the deferred sanitise first so it pops after the shadow
2263
+ walk we push next, i.e. nested shadow roots are discovered
2264
+ before this one is sanitised. */
2265
+ stack.push({
2266
+ node: null,
2267
+ shadow: sr
2268
+ }, {
2269
+ node: sr,
2270
+ shadow: null
2271
+ });
2272
+ }
2273
+ }
2274
+ }
2275
+ };
1319
2276
  // eslint-disable-next-line complexity
1320
2277
  DOMPurify.sanitize = function (dirty) {
1321
2278
  let cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
@@ -1332,13 +2289,9 @@ var purify = {exports: {}};
1332
2289
  }
1333
2290
  /* Stringify, in case dirty is an object */
1334
2291
  if (typeof dirty !== 'string' && !_isNode(dirty)) {
1335
- if (typeof dirty.toString === 'function') {
1336
- dirty = dirty.toString();
1337
- if (typeof dirty !== 'string') {
1338
- throw typeErrorCreate('dirty is not a string, aborting');
1339
- }
1340
- } else {
1341
- throw typeErrorCreate('toString is not a function');
2292
+ dirty = stringifyValue(dirty);
2293
+ if (typeof dirty !== 'string') {
2294
+ throw typeErrorCreate('dirty is not a string, aborting');
1342
2295
  }
1343
2296
  }
1344
2297
  /* Return dirty HTML if DOMPurify cannot run */
@@ -1346,24 +2299,90 @@ var purify = {exports: {}};
1346
2299
  return dirty;
1347
2300
  }
1348
2301
  /* Assign config vars */
1349
- if (!SET_CONFIG) {
2302
+ if (SET_CONFIG) {
2303
+ /* Persistent setConfig() path: _parseConfig is skipped, so the sets are
2304
+ * not re-derived per call. Restore them from the pristine bindings
2305
+ * captured at setConfig() time so a previous call's hook clone (mutated
2306
+ * below) does not carry over. */
2307
+ ALLOWED_TAGS = SET_CONFIG_ALLOWED_TAGS;
2308
+ ALLOWED_ATTR = SET_CONFIG_ALLOWED_ATTR;
2309
+ } else {
1350
2310
  _parseConfig(cfg);
1351
2311
  }
2312
+ /* Clone the hook-mutable allowlists before the walk whenever an
2313
+ * uponSanitize* hook is registered. The hook event exposes ALLOWED_TAGS
2314
+ * and ALLOWED_ATTR by reference (as allowedTags / allowedAttributes), so
2315
+ * a hook that widens them would otherwise mutate the shared set
2316
+ * permanently: across later calls and across every element. Cloning per
2317
+ * walk keeps documented in-call widening working while scoping it to the
2318
+ * call. A single guard for both config paths - the per-call path rebinds
2319
+ * the sets in _parseConfig each call, the persistent path restores them
2320
+ * from the captured bindings just above - so the two cannot diverge. */
2321
+ if (hooks.uponSanitizeElement.length > 0 || hooks.uponSanitizeAttribute.length > 0) {
2322
+ ALLOWED_TAGS = clone(ALLOWED_TAGS);
2323
+ }
2324
+ if (hooks.uponSanitizeAttribute.length > 0) {
2325
+ ALLOWED_ATTR = clone(ALLOWED_ATTR);
2326
+ }
1352
2327
  /* Clean up removed elements */
1353
2328
  DOMPurify.removed = [];
1354
- /* Check if dirty is correctly typed for IN_PLACE */
1355
- if (typeof dirty === 'string') {
1356
- IN_PLACE = false;
1357
- }
1358
- if (IN_PLACE) {
1359
- /* Do some early pre-sanitization to avoid unsafe root nodes */
1360
- if (dirty.nodeName) {
1361
- const tagName = transformCaseFunc(dirty.nodeName);
2329
+ /* Resolve IN_PLACE for this call without mutating persistent config.
2330
+ Writing the IN_PLACE closure variable here leaks under setConfig(),
2331
+ where _parseConfig is skipped on later calls: a single string call would
2332
+ disable in-place mode for every subsequent node call, returning a
2333
+ sanitized copy while leaving the caller's node — which in-place callers
2334
+ keep using and whose return value they ignore — unsanitized. REPORT-2. */
2335
+ const inPlace = IN_PLACE && typeof dirty !== 'string' && _isNode(dirty);
2336
+ if (inPlace) {
2337
+ /* Declarative-partial-updates / streaming pre-pass: sever every patch
2338
+ linkage across the live tree BEFORE the walk, so no patch can fire
2339
+ mid-walk and inject into an already-processed region. Runs first, so
2340
+ it also covers the forbidden/clobbered roots that throw below. */
2341
+ _neutralizePatchLinkage(dirty);
2342
+ /* Do some early pre-sanitization to avoid unsafe root nodes.
2343
+ Read nodeName through the cached prototype getter — a clobbering
2344
+ child named "nodeName" on the form root would otherwise shadow
2345
+ the property and let this check skip the root-allowlist
2346
+ validation entirely. */
2347
+ const nn = getNodeName ? getNodeName(dirty) : dirty.nodeName;
2348
+ if (typeof nn === 'string') {
2349
+ const tagName = transformCaseFunc(nn);
1362
2350
  if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
2351
+ /* Fail closed on a live root: neutralize handlers/children before
2352
+ throwing, exactly as the mid-walk abort path does. */
2353
+ _neutralizeRoot(dirty);
1363
2354
  throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');
1364
2355
  }
1365
2356
  }
1366
- } else if (dirty instanceof Node) {
2357
+ /* Pre-flight the root through _isClobbered. The iterator-driven
2358
+ removal path can not detach a parent-less root: _forceRemove
2359
+ falls through to Element.prototype.remove(), which per spec
2360
+ is a no-op on a node with no parent. A clobbered root would
2361
+ then survive the main loop with its attributes uninspected,
2362
+ because _sanitizeAttributes early-returns on _isClobbered. The
2363
+ result would be an attacker-controlled form, complete with any
2364
+ event-handler attributes the caller passed in, handed back to
2365
+ the application unsanitized. Refuse to sanitize such a root
2366
+ the same way we refuse a forbidden tag. GHSA-r47g-fvhr-h676. */
2367
+ if (_isClobbered(dirty)) {
2368
+ /* Fail closed on a live clobbered root before throwing.
2369
+ _neutralizeRoot's reads are clobber-safe (cached getters); the
2370
+ form's non-clobbered descendants, e.g. an armed <img>, are scrubbed. */
2371
+ _neutralizeRoot(dirty);
2372
+ throw typeErrorCreate('root node is clobbered and cannot be sanitized in-place');
2373
+ }
2374
+ /* Sanitize attached shadow roots before the main iterator runs.
2375
+ The iterator does not descend into shadow trees. Same fail-closed
2376
+ barrier as the main walk (campaign-3 F2): a custom-element reaction
2377
+ inside a shadow root could abort this pre-pass before the walk runs,
2378
+ which would otherwise leave the entire live tree unsanitized. */
2379
+ try {
2380
+ _sanitizeAttachedShadowRoots(dirty);
2381
+ } catch (error) {
2382
+ _neutralizeRoot(dirty);
2383
+ throw error;
2384
+ }
2385
+ } else if (_isNode(dirty)) {
1367
2386
  /* If dirty is a DOM element, append to an empty document to avoid
1368
2387
  elements being stripped by the parser */
1369
2388
  body = _initDocument('<!---->');
@@ -1377,12 +2396,18 @@ var purify = {exports: {}};
1377
2396
  // eslint-disable-next-line unicorn/prefer-dom-node-append
1378
2397
  body.appendChild(importedNode);
1379
2398
  }
2399
+ /* Clonable shadow roots are deep-cloned by importNode(); sanitize
2400
+ them before the main iterator runs, since the iterator does not
2401
+ descend into shadow trees. The walk routes every read through a
2402
+ cached prototype getter so clobbering descendants on a form root
2403
+ cannot hide a shadow host from this pass. */
2404
+ _sanitizeAttachedShadowRoots(importedNode);
1380
2405
  } else {
1381
2406
  /* Exit directly if we have nothing to do */
1382
2407
  if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT &&
1383
2408
  // eslint-disable-next-line unicorn/prefer-includes
1384
2409
  dirty.indexOf('<') === -1) {
1385
- return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;
2410
+ return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? _createTrustedHTML(dirty) : dirty;
1386
2411
  }
1387
2412
  /* Initialize the document to work on */
1388
2413
  body = _initDocument(dirty);
@@ -1396,31 +2421,71 @@ var purify = {exports: {}};
1396
2421
  _forceRemove(body.firstChild);
1397
2422
  }
1398
2423
  /* Get node iterator */
1399
- const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body);
1400
- /* Now start iterating over the created document */
1401
- while (currentNode = nodeIterator.nextNode()) {
1402
- /* Sanitize tags and elements */
1403
- _sanitizeElements(currentNode);
1404
- /* Check attributes next */
1405
- _sanitizeAttributes(currentNode);
1406
- /* Shadow DOM detected, sanitize it */
1407
- if (currentNode.content instanceof DocumentFragment) {
1408
- _sanitizeShadowDOM2(currentNode.content);
2424
+ const walkRoot = inPlace ? dirty : body;
2425
+ /* Now start iterating over the created document.
2426
+ The walk runs inside an exception barrier (campaign-3 F2): a re-entrant
2427
+ engine/custom-element mutation can detach a node mid-walk so
2428
+ `_forceRemove`'s parentless guard throws, aborting the loop. Without the
2429
+ barrier the caller's in-place tree would be left half-sanitized with the
2430
+ unvisited tail still armed. _createNodeIterator itself is inside the
2431
+ barrier too: constructing the iterator dereferences the root's document,
2432
+ and any failure there (e.g. an exotic/clobbered root) must still fail
2433
+ closed rather than skip the neutralize. On any throw we fail closed -
2434
+ strip the in-place root bare - then rethrow so the existing throw
2435
+ contract is preserved. (String/DOM-copy paths never return the partial
2436
+ body, so the propagating throw is already fail-closed there.) */
2437
+ try {
2438
+ const nodeIterator = _createNodeIterator(walkRoot);
2439
+ while (currentNode = nodeIterator.nextNode()) {
2440
+ /* Sanitize tags and elements */
2441
+ _sanitizeElements(currentNode, walkRoot);
2442
+ /* Check attributes next */
2443
+ _sanitizeAttributes(currentNode);
2444
+ /* Shadow DOM detected, sanitize it.
2445
+ Realm-safe check (GHSA-hpcv-96wg-7vj8): nodeType-based detection
2446
+ instead of instanceof, so foreign-realm <template>.content is
2447
+ walked correctly. */
2448
+ if (_isDocumentFragment(currentNode.content)) {
2449
+ _sanitizeShadowDOM2(currentNode.content);
2450
+ }
1409
2451
  }
2452
+ } catch (error) {
2453
+ if (inPlace) {
2454
+ _neutralizeRoot(dirty);
2455
+ /* Nodes _forceRemove'd earlier in the aborted walk are already
2456
+ detached from the root, so _neutralizeRoot's subtree pass does not
2457
+ reach them. Defuse them too, mirroring the success-path loop below. */
2458
+ arrayForEach(DOMPurify.removed, entry => {
2459
+ if (entry.element) {
2460
+ _neutralizeSubtree(entry.element);
2461
+ }
2462
+ });
2463
+ }
2464
+ throw error;
1410
2465
  }
1411
2466
  /* If we sanitized `dirty` in-place, return it. */
1412
- if (IN_PLACE) {
2467
+ if (inPlace) {
2468
+ /* Fail-closed completion of the audit-5 F1 fix: every node removed from
2469
+ the caller's live tree is detached but may still hold a queued
2470
+ resource-event handler that fires in page scope after we return. The
2471
+ move-hoist covers only disallowed-tag KEEP_CONTENT removals; strip the
2472
+ non-allow-listed attributes off every other removed subtree (clobber,
2473
+ mXSS, namespace, comments, KEEP_CONTENT:false, …) so those handlers are
2474
+ cancelled before any event can fire. Runs synchronously, pre-return. */
2475
+ arrayForEach(DOMPurify.removed, entry => {
2476
+ if (entry.element) {
2477
+ _neutralizeSubtree(entry.element);
2478
+ }
2479
+ });
2480
+ if (SAFE_FOR_TEMPLATES) {
2481
+ _scrubTemplateExpressions2(dirty);
2482
+ }
1413
2483
  return dirty;
1414
2484
  }
1415
2485
  /* Return sanitized string or DOM */
1416
2486
  if (RETURN_DOM) {
1417
2487
  if (SAFE_FOR_TEMPLATES) {
1418
- body.normalize();
1419
- let html = body.innerHTML;
1420
- arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
1421
- html = stringReplace(html, expr, ' ');
1422
- });
1423
- body.innerHTML = html;
2488
+ _scrubTemplateExpressions2(body);
1424
2489
  }
1425
2490
  if (RETURN_DOM_FRAGMENT) {
1426
2491
  returnNode = createDocumentFragment.call(body.ownerDocument);
@@ -1450,20 +2515,28 @@ var purify = {exports: {}};
1450
2515
  }
1451
2516
  /* Sanitize final string template-safe */
1452
2517
  if (SAFE_FOR_TEMPLATES) {
1453
- arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
1454
- serializedHTML = stringReplace(serializedHTML, expr, ' ');
1455
- });
2518
+ serializedHTML = _stripTemplateExpressions(serializedHTML);
1456
2519
  }
1457
- return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;
2520
+ return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? _createTrustedHTML(serializedHTML) : serializedHTML;
1458
2521
  };
1459
2522
  DOMPurify.setConfig = function () {
1460
2523
  let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1461
2524
  _parseConfig(cfg);
1462
2525
  SET_CONFIG = true;
2526
+ SET_CONFIG_ALLOWED_TAGS = ALLOWED_TAGS;
2527
+ SET_CONFIG_ALLOWED_ATTR = ALLOWED_ATTR;
1463
2528
  };
1464
2529
  DOMPurify.clearConfig = function () {
1465
2530
  CONFIG = null;
1466
2531
  SET_CONFIG = false;
2532
+ SET_CONFIG_ALLOWED_TAGS = null;
2533
+ SET_CONFIG_ALLOWED_ATTR = null;
2534
+ // Drop any caller-supplied Trusted Types policy so it cannot poison later
2535
+ // `RETURN_TRUSTED_TYPE` output. The internal default policy (cached, and
2536
+ // never recreated — Trusted Types throws on duplicate names) is restored by
2537
+ // the next `_parseConfig`. See GHSA-vxr8-fq34-vvx9.
2538
+ trustedTypesPolicy = defaultTrustedTypesPolicy;
2539
+ emptyHTML = '';
1467
2540
  };
1468
2541
  DOMPurify.isValidAttribute = function (tag, attr, value) {
1469
2542
  /* Initialize shared config vars if necessary. */
@@ -1478,9 +2551,19 @@ var purify = {exports: {}};
1478
2551
  if (typeof hookFunction !== 'function') {
1479
2552
  return;
1480
2553
  }
2554
+ /* Reject unknown entry points. Without this, a non-hook key (e.g.
2555
+ * '__proto__') indexes off the prototype chain rather than a real
2556
+ * hook array, and arrayPush then writes to Object.prototype. Guard
2557
+ * with an own-property check against the known hook names. */
2558
+ if (!objectHasOwnProperty(hooks, entryPoint)) {
2559
+ return;
2560
+ }
1481
2561
  arrayPush(hooks[entryPoint], hookFunction);
1482
2562
  };
1483
2563
  DOMPurify.removeHook = function (entryPoint, hookFunction) {
2564
+ if (!objectHasOwnProperty(hooks, entryPoint)) {
2565
+ return undefined;
2566
+ }
1484
2567
  if (hookFunction !== undefined) {
1485
2568
  const index = arrayLastIndexOf(hooks[entryPoint], hookFunction);
1486
2569
  return index === -1 ? undefined : arraySplice(hooks[entryPoint], index, 1)[0];
@@ -1488,6 +2571,9 @@ var purify = {exports: {}};
1488
2571
  return arrayPop(hooks[entryPoint]);
1489
2572
  };
1490
2573
  DOMPurify.removeHooks = function (entryPoint) {
2574
+ if (!objectHasOwnProperty(hooks, entryPoint)) {
2575
+ return;
2576
+ }
1491
2577
  hooks[entryPoint] = [];
1492
2578
  };
1493
2579
  DOMPurify.removeAllHooks = function () {