@wiris/mathtype-ckeditor5 8.15.1 → 8.15.3

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.
@@ -3,24 +3,65 @@ import { ButtonView } from 'ckeditor5';
3
3
  import { ClickObserver, XmlDataProcessor, ViewUpcastWriter, HtmlDataProcessor } from 'ckeditor5';
4
4
  import { Widget, viewToModelPositionOutsideModelElement, toWidget } from 'ckeditor5';
5
5
 
6
- /*! @license DOMPurify 3.3.1 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.3.1/LICENSE */
6
+ /*! @license DOMPurify 3.4.15 | (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.15/LICENSE */
7
7
 
8
- const {
9
- entries,
10
- setPrototypeOf,
11
- isFrozen,
12
- getPrototypeOf,
13
- getOwnPropertyDescriptor
14
- } = Object;
15
- let {
16
- freeze,
17
- seal,
18
- create
19
- } = Object; // eslint-disable-line import/no-mutable-exports
20
- let {
21
- apply,
22
- construct
23
- } = typeof Reflect !== 'undefined' && Reflect;
8
+ function _arrayLikeToArray(r, a) {
9
+ (null == a || a > r.length) && (a = r.length);
10
+ for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
11
+ return n;
12
+ }
13
+ function _arrayWithHoles(r) {
14
+ if (Array.isArray(r)) return r;
15
+ }
16
+ function _iterableToArrayLimit(r, l) {
17
+ var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
18
+ if (null != t) {
19
+ var e,
20
+ n,
21
+ i,
22
+ u,
23
+ a = [],
24
+ f = true,
25
+ o = false;
26
+ try {
27
+ 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);
28
+ } catch (r) {
29
+ o = true, n = r;
30
+ } finally {
31
+ try {
32
+ if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;
33
+ } finally {
34
+ if (o) throw n;
35
+ }
36
+ }
37
+ return a;
38
+ }
39
+ }
40
+ function _nonIterableRest() {
41
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
42
+ }
43
+ function _slicedToArray(r, e) {
44
+ return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
45
+ }
46
+ function _unsupportedIterableToArray(r, a) {
47
+ if (r) {
48
+ if ("string" == typeof r) return _arrayLikeToArray(r, a);
49
+ var t = {}.toString.call(r).slice(8, -1);
50
+ 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;
51
+ }
52
+ }
53
+
54
+ const entries = Object.entries,
55
+ setPrototypeOf = Object.setPrototypeOf,
56
+ isFrozen = Object.isFrozen,
57
+ getPrototypeOf = Object.getPrototypeOf,
58
+ getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
59
+ let freeze = Object.freeze,
60
+ seal = Object.seal,
61
+ create = Object.create; // eslint-disable-line import/no-mutable-exports
62
+ let _ref = typeof Reflect !== 'undefined' && Reflect,
63
+ apply = _ref.apply,
64
+ construct = _ref.construct;
24
65
  if (!freeze) {
25
66
  freeze = function freeze(x) {
26
67
  return x;
@@ -52,13 +93,19 @@ const arrayLastIndexOf = unapply(Array.prototype.lastIndexOf);
52
93
  const arrayPop = unapply(Array.prototype.pop);
53
94
  const arrayPush = unapply(Array.prototype.push);
54
95
  const arraySplice = unapply(Array.prototype.splice);
96
+ const arrayIsArray = Array.isArray;
55
97
  const stringToLowerCase = unapply(String.prototype.toLowerCase);
56
98
  const stringToString = unapply(String.prototype.toString);
57
99
  const stringMatch = unapply(String.prototype.match);
58
100
  const stringReplace = unapply(String.prototype.replace);
59
101
  const stringIndexOf = unapply(String.prototype.indexOf);
60
102
  const stringTrim = unapply(String.prototype.trim);
103
+ const numberToString = unapply(Number.prototype.toString);
104
+ const booleanToString = unapply(Boolean.prototype.toString);
105
+ const bigintToString = typeof BigInt === 'undefined' ? null : unapply(BigInt.prototype.toString);
106
+ const symbolToString = typeof Symbol === 'undefined' ? null : unapply(Symbol.prototype.toString);
61
107
  const objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty);
108
+ const objectToString = unapply(Object.prototype.toString);
62
109
  const regExpTest = unapply(RegExp.prototype.test);
63
110
  const typeErrorCreate = unconstruct(TypeError);
64
111
  /**
@@ -108,6 +155,9 @@ function addToSet(set, array) {
108
155
  // Prevent prototype setters from intercepting set as a this value.
109
156
  setPrototypeOf(set, null);
110
157
  }
158
+ if (!arrayIsArray(array)) {
159
+ return set;
160
+ }
111
161
  let l = array.length;
112
162
  while (l--) {
113
163
  let element = array[l];
@@ -148,10 +198,13 @@ function cleanArray(array) {
148
198
  */
149
199
  function clone(object) {
150
200
  const newObject = create(null);
151
- for (const [property, value] of entries(object)) {
201
+ for (const _ref2 of entries(object)) {
202
+ var _ref3 = _slicedToArray(_ref2, 2);
203
+ const property = _ref3[0];
204
+ const value = _ref3[1];
152
205
  const isPropertyExist = objectHasOwnProperty(object, property);
153
206
  if (isPropertyExist) {
154
- if (Array.isArray(value)) {
207
+ if (arrayIsArray(value)) {
155
208
  newObject[property] = cleanArray(value);
156
209
  } else if (value && typeof value === 'object' && value.constructor === Object) {
157
210
  newObject[property] = clone(value);
@@ -162,6 +215,58 @@ function clone(object) {
162
215
  }
163
216
  return newObject;
164
217
  }
218
+ /**
219
+ * Convert non-node values into strings without depending on direct property access.
220
+ *
221
+ * @param value - The value to stringify.
222
+ * @returns A string representation of the provided value.
223
+ */
224
+ function stringifyValue(value) {
225
+ switch (typeof value) {
226
+ case 'string':
227
+ {
228
+ return value;
229
+ }
230
+ case 'number':
231
+ {
232
+ return numberToString(value);
233
+ }
234
+ case 'boolean':
235
+ {
236
+ return booleanToString(value);
237
+ }
238
+ case 'bigint':
239
+ {
240
+ return bigintToString ? bigintToString(value) : '0';
241
+ }
242
+ case 'symbol':
243
+ {
244
+ return symbolToString ? symbolToString(value) : 'Symbol()';
245
+ }
246
+ case 'undefined':
247
+ {
248
+ return objectToString(value);
249
+ }
250
+ case 'function':
251
+ case 'object':
252
+ {
253
+ if (value === null) {
254
+ return objectToString(value);
255
+ }
256
+ const valueAsRecord = value;
257
+ const valueToString = lookupGetter(valueAsRecord, 'toString');
258
+ if (typeof valueToString === 'function') {
259
+ const stringified = valueToString(valueAsRecord);
260
+ return typeof stringified === 'string' ? stringified : objectToString(stringified);
261
+ }
262
+ return objectToString(value);
263
+ }
264
+ default:
265
+ {
266
+ return objectToString(value);
267
+ }
268
+ }
269
+ }
165
270
  /**
166
271
  * This method automatically checks if the prop is function or getter and behaves accordingly.
167
272
  *
@@ -187,6 +292,14 @@ function lookupGetter(object, prop) {
187
292
  }
188
293
  return fallbackValue;
189
294
  }
295
+ function isRegex(value) {
296
+ try {
297
+ regExpTest(value, '');
298
+ return true;
299
+ } catch (_unused) {
300
+ return false;
301
+ }
302
+ }
190
303
 
191
304
  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']);
192
305
  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']);
@@ -202,15 +315,14 @@ const mathMl$1 = freeze(['math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mgly
202
315
  const mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);
203
316
  const text = freeze(['#text']);
204
317
 
205
- 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']);
206
- 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']);
207
- const mathMl = freeze(['accent', 'accentunder', 'align', 'bevelled', 'close', 'columnsalign', 'columnlines', 'columnspan', 'denomalign', 'depth', 'dir', 'display', 'displaystyle', 'encoding', 'fence', 'frame', 'height', 'href', 'id', 'largeop', 'length', 'linethickness', 'lspace', 'lquote', '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']);
318
+ 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']);
319
+ 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', 'pointer-events', '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', 'vector-effect', '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']);
320
+ 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']);
208
321
  const xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);
209
322
 
210
- // eslint-disable-next-line unicorn/better-regex
211
- const MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode
212
- const ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm);
213
- const TMPLIT_EXPR = seal(/\$\{[\w\W]*/gm); // eslint-disable-line unicorn/better-regex
323
+ const MUSTACHE_EXPR = seal(/{{[\w\W]*|^[\w\W]*}}/g);
324
+ const ERB_EXPR = seal(/<%[\w\W]*|^[\w\W]*%>/g);
325
+ const TMPLIT_EXPR = seal(/\${[\w\W]*/g);
214
326
  const DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]+$/); // eslint-disable-line no-useless-escape
215
327
  const ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape
216
328
  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
@@ -220,30 +332,62 @@ const ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205
220
332
  );
221
333
  const DOCTYPE_NAME = seal(/^html$/i);
222
334
  const CUSTOM_ELEMENT = seal(/^[a-z][.\w]*(-[.\w]+)+$/i);
335
+ // Markup-significant character probes used by _sanitizeElements.
336
+ // Shared module-level instances are safe despite the sticky /g flags:
337
+ // unapply() resets lastIndex for RegExp receivers before every call.
338
+ const ELEMENT_MARKUP_PROBE = seal(/<[/\w!]/g);
339
+ const COMMENT_MARKUP_PROBE = seal(/<[/\w]/g);
340
+ const FALLBACK_TAG_CLOSE = seal(/<\/no(script|embed|frames)/i);
341
+ const SELF_CLOSING_TAG = seal(/\/>/i);
223
342
 
224
- var EXPRESSIONS = /*#__PURE__*/Object.freeze({
225
- __proto__: null,
226
- ARIA_ATTR: ARIA_ATTR,
227
- ATTR_WHITESPACE: ATTR_WHITESPACE,
228
- CUSTOM_ELEMENT: CUSTOM_ELEMENT,
229
- DATA_ATTR: DATA_ATTR,
230
- DOCTYPE_NAME: DOCTYPE_NAME,
231
- ERB_EXPR: ERB_EXPR,
232
- IS_ALLOWED_URI: IS_ALLOWED_URI,
233
- IS_SCRIPT_OR_DATA: IS_SCRIPT_OR_DATA,
234
- MUSTACHE_EXPR: MUSTACHE_EXPR,
235
- TMPLIT_EXPR: TMPLIT_EXPR
236
- });
237
-
238
- /* eslint-disable @typescript-eslint/indent */
239
343
  // https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType
240
344
  const NODE_TYPE = {
241
345
  element: 1,
346
+ attribute: 2,
242
347
  text: 3,
348
+ cdataSection: 4,
349
+ entityReference: 5,
350
+ // Deprecated
351
+ entityNode: 6,
243
352
  // Deprecated
244
- progressingInstruction: 7,
353
+ processingInstruction: 7,
245
354
  comment: 8,
246
- document: 9};
355
+ document: 9,
356
+ documentType: 10,
357
+ documentFragment: 11,
358
+ notation: 12 // Deprecated
359
+ };
360
+ /* HTML-namespace elements whose child text nodes are serialized *literally*
361
+ (unescaped) by the HTML fragment-serialization algorithm. Two reparse-mXSS
362
+ shapes ride on that literal serialization:
363
+ (a) an element child - a tree the HTML parser can never build, but the DOM
364
+ API and an XML/XHTML parse can - after which a `</tag>`-bearing text
365
+ sibling breaks the element open on reparse; and
366
+ (b) text-only content that already carries the element's OWN end tag, e.g.
367
+ `<style>...</style><img onerror=x>` built as a node, which the literal
368
+ serializer emits verbatim for the HTML parser to re-open.
369
+ Shape (a) is handled by the firstElementChild branch in _isUnsafeNode; shape
370
+ (b) by the LITERAL_TEXT_CLOSE probe. Both read textContent (the raw-serialized
371
+ form for these elements) rather than innerHTML, because an XML/XHTML working
372
+ document serializes innerHTML with `<` escaped, which silently blinds the
373
+ innerHTML-based probes (rule 1's second probe and FALLBACK_TAG_CLOSE) there.
374
+ `script` is never allow-listed, but is kept here so the guard matches the
375
+ serializer's own literal-text list exactly. */
376
+ const LITERAL_TEXT_ELEMENT_NAMES = ['style', 'script', 'xmp', 'iframe', 'noembed', 'noframes', 'plaintext', 'noscript'];
377
+ const LITERAL_TEXT_ELEMENTS = freeze(addToSet({}, LITERAL_TEXT_ELEMENT_NAMES));
378
+ /* Per-element end-tag matcher. On an HTML reparse the ONLY token that
379
+ terminates a literal-text element's raw content is its own end tag; a foreign
380
+ literal-text close (e.g. `</xmp>` sitting inside `<style>`) does not break
381
+ out, so matching is per-element, not a shared alternation. The lookahead
382
+ requires an HTML tag-name terminator (whitespace, `/` or `>`) so a longer
383
+ name such as `</styles` is not mistaken for `</style`. */
384
+ const LITERAL_TEXT_CLOSE = function () {
385
+ const map = {};
386
+ arrayForEach(LITERAL_TEXT_ELEMENT_NAMES, name => {
387
+ map[name] = seal(new RegExp('</' + name + '(?=[\\t\\n\\f\\r />])', 'i'));
388
+ });
389
+ return freeze(map);
390
+ }();
247
391
  const getGlobal = function getGlobal() {
248
392
  return typeof window === 'undefined' ? null : window;
249
393
  };
@@ -298,10 +442,40 @@ const _createHooksMap = function _createHooksMap() {
298
442
  uponSanitizeShadowNode: []
299
443
  };
300
444
  };
445
+ /**
446
+ * Resolve a set-valued configuration option: a fresh set built from
447
+ * cfg[key] when it is an own array property (seeded with a clone of
448
+ * options.base when given, case-normalized via options.transform),
449
+ * the fallback set otherwise.
450
+ *
451
+ * @param cfg the cloned, prototype-free configuration object
452
+ * @param key the configuration property to read
453
+ * @param fallback the set to use when the option is absent or not an array
454
+ * @param options transform and optional base set to merge into
455
+ * @returns the resolved set
456
+ */
457
+ const _resolveSetOption = function _resolveSetOption(cfg, key, fallback, options) {
458
+ return objectHasOwnProperty(cfg, key) && arrayIsArray(cfg[key]) ? addToSet(options.base ? clone(options.base) : {}, cfg[key], options.transform) : fallback;
459
+ };
460
+ /**
461
+ * Resolve an object-valued configuration option: a prototype-free clone
462
+ * of cfg[key] when it is an own, truthy object property, else a fresh
463
+ * fallback built by makeFallback (fresh on every parse, so a previous
464
+ * parse can never leak state into the next one).
465
+ *
466
+ * @param cfg the cloned, prototype-free configuration object
467
+ * @param key the configuration property to read
468
+ * @param makeFallback builds the fallback value when the option is absent
469
+ * @returns the resolved object
470
+ */
471
+ const _resolveObjectOption = function _resolveObjectOption(cfg, key, makeFallback) {
472
+ const value = objectHasOwnProperty(cfg, key) ? cfg[key] : undefined;
473
+ return value && typeof value === 'object' ? clone(value) : makeFallback();
474
+ };
301
475
  function createDOMPurify() {
302
476
  let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();
303
477
  const DOMPurify = root => createDOMPurify(root);
304
- DOMPurify.version = '3.3.1';
478
+ DOMPurify.version = '3.4.15';
305
479
  DOMPurify.removed = [];
306
480
  if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document || !window.Element) {
307
481
  // Not running in a browser, provide a factory function
@@ -309,28 +483,46 @@ function createDOMPurify() {
309
483
  DOMPurify.isSupported = false;
310
484
  return DOMPurify;
311
485
  }
312
- let {
313
- document
314
- } = window;
486
+ let document = window.document;
315
487
  const originalDocument = document;
316
488
  const currentScript = originalDocument.currentScript;
317
- const {
318
- DocumentFragment,
319
- HTMLTemplateElement,
320
- Node,
321
- Element,
322
- NodeFilter,
323
- NamedNodeMap = window.NamedNodeMap || window.MozNamedAttrMap,
324
- HTMLFormElement,
325
- DOMParser,
326
- trustedTypes
327
- } = window;
489
+ window.DocumentFragment;
490
+ const HTMLTemplateElement = window.HTMLTemplateElement,
491
+ Node = window.Node,
492
+ Element = window.Element,
493
+ NodeFilter = window.NodeFilter,
494
+ _window$NamedNodeMap = window.NamedNodeMap;
495
+ _window$NamedNodeMap === void 0 ? window.NamedNodeMap || window.MozNamedAttrMap : _window$NamedNodeMap;
496
+ window.HTMLFormElement;
497
+ const DOMParser = window.DOMParser,
498
+ trustedTypes = window.trustedTypes;
328
499
  const ElementPrototype = Element.prototype;
329
500
  const cloneNode = lookupGetter(ElementPrototype, 'cloneNode');
330
501
  const remove = lookupGetter(ElementPrototype, 'remove');
502
+ // Clobber-safe Attr-node removal. On an HTMLFormElement a descendant named
503
+ // "removeAttributeNode" shadows the prototype method via
504
+ // [LegacyOverrideBuiltIns], so element.removeAttributeNode(attr) throws.
505
+ // Calling the cached Element.prototype method with the element as the
506
+ // receiver removes the exact live Attr node regardless of the shadowing.
507
+ const removeAttributeNode = lookupGetter(ElementPrototype, 'removeAttributeNode');
331
508
  const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');
332
509
  const getChildNodes = lookupGetter(ElementPrototype, 'childNodes');
333
510
  const getParentNode = lookupGetter(ElementPrototype, 'parentNode');
511
+ const getShadowRoot = lookupGetter(ElementPrototype, 'shadowRoot');
512
+ const getAttributes = lookupGetter(ElementPrototype, 'attributes');
513
+ const getNodeType = Node && Node.prototype ? lookupGetter(Node.prototype, 'nodeType') : null;
514
+ const getNodeName = Node && Node.prototype ? lookupGetter(Node.prototype, 'nodeName') : null;
515
+ const getOwnerDocument = Node && Node.prototype ? lookupGetter(Node.prototype, 'ownerDocument') : null;
516
+ /* Clobber-safe nodeType / nodeName reads through the cached Node.prototype
517
+ getters, with a direct-property fallback for environments that lack
518
+ Node.prototype. Sites that need a different fallback (e.g. _isClobbered
519
+ returns early on a null name) intentionally keep their own reads. */
520
+ const _readNodeType = function _readNodeType(node) {
521
+ return getNodeType ? getNodeType(node) : node.nodeType;
522
+ };
523
+ const _readNodeName = function _readNodeName(node) {
524
+ return getNodeName ? getNodeName(node) : node.nodeName;
525
+ };
334
526
  // As per issue #47, the web-components registry is inherited by a
335
527
  // new document created via createHTMLDocument. As per the spec
336
528
  // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)
@@ -345,33 +537,74 @@ function createDOMPurify() {
345
537
  }
346
538
  let trustedTypesPolicy;
347
539
  let emptyHTML = '';
348
- const {
349
- implementation,
350
- createNodeIterator,
351
- createDocumentFragment,
352
- getElementsByTagName
353
- } = document;
354
- const {
355
- importNode
356
- } = originalDocument;
540
+ // The instance's own internal Trusted Types policy. Unlike a caller-supplied
541
+ // `TRUSTED_TYPES_POLICY`, this is created at most once — Trusted Types throws
542
+ // on duplicate policy names — and is the only policy allowed to persist
543
+ // across configurations and survive `clearConfig()`.
544
+ let defaultTrustedTypesPolicy;
545
+ let defaultTrustedTypesPolicyResolved = false;
546
+ // Tracks whether we are already inside a call to the configured Trusted Types
547
+ // policy (`createHTML` or `createScriptURL`). If a supplied policy callback
548
+ // itself calls `DOMPurify.sanitize` (the cause of #1422), `sanitize` would
549
+ // re-enter the policy and recurse until the stack overflows. We detect that
550
+ // re-entry and throw a clear, actionable error instead. The guard is shared
551
+ // across both callbacks, because either one re-entering `sanitize` triggers
552
+ // the same unbounded recursion.
553
+ let IN_TRUSTED_TYPES_POLICY = 0;
554
+ const _assertNotInTrustedTypesPolicy = function _assertNotInTrustedTypesPolicy() {
555
+ if (IN_TRUSTED_TYPES_POLICY > 0) {
556
+ 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.');
557
+ }
558
+ };
559
+ const _createTrustedHTML = function _createTrustedHTML(html) {
560
+ _assertNotInTrustedTypesPolicy();
561
+ IN_TRUSTED_TYPES_POLICY++;
562
+ try {
563
+ return trustedTypesPolicy.createHTML(html);
564
+ } finally {
565
+ IN_TRUSTED_TYPES_POLICY--;
566
+ }
567
+ };
568
+ const _createTrustedScriptURL = function _createTrustedScriptURL(scriptUrl) {
569
+ _assertNotInTrustedTypesPolicy();
570
+ IN_TRUSTED_TYPES_POLICY++;
571
+ try {
572
+ return trustedTypesPolicy.createScriptURL(scriptUrl);
573
+ } finally {
574
+ IN_TRUSTED_TYPES_POLICY--;
575
+ }
576
+ };
577
+ // Lazily resolve (and cache) the instance's internal default policy.
578
+ // Resolution is attempted at most once: a successful `createPolicy` cannot be
579
+ // repeated (Trusted Types throws on duplicate names), and a failed or
580
+ // unsupported attempt must not be retried on every parse.
581
+ const _getDefaultTrustedTypesPolicy = function _getDefaultTrustedTypesPolicy() {
582
+ if (!defaultTrustedTypesPolicyResolved) {
583
+ defaultTrustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);
584
+ defaultTrustedTypesPolicyResolved = true;
585
+ }
586
+ return defaultTrustedTypesPolicy;
587
+ };
588
+ const _document = document,
589
+ implementation = _document.implementation,
590
+ createNodeIterator = _document.createNodeIterator,
591
+ createDocumentFragment = _document.createDocumentFragment,
592
+ getElementsByTagName = _document.getElementsByTagName;
593
+ const importNode = originalDocument.importNode;
357
594
  let hooks = _createHooksMap();
358
595
  /**
359
596
  * Expose whether this browser supports running the full DOMPurify.
360
597
  */
361
598
  DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNode === 'function' && implementation && implementation.createHTMLDocument !== undefined;
362
- const {
363
- MUSTACHE_EXPR,
364
- ERB_EXPR,
365
- TMPLIT_EXPR,
366
- DATA_ATTR,
367
- ARIA_ATTR,
368
- IS_SCRIPT_OR_DATA,
369
- ATTR_WHITESPACE,
370
- CUSTOM_ELEMENT
371
- } = EXPRESSIONS;
372
- let {
373
- IS_ALLOWED_URI: IS_ALLOWED_URI$1
374
- } = EXPRESSIONS;
599
+ const MUSTACHE_EXPR$1 = MUSTACHE_EXPR,
600
+ ERB_EXPR$1 = ERB_EXPR,
601
+ TMPLIT_EXPR$1 = TMPLIT_EXPR,
602
+ DATA_ATTR$1 = DATA_ATTR,
603
+ ARIA_ATTR$1 = ARIA_ATTR,
604
+ IS_SCRIPT_OR_DATA$1 = IS_SCRIPT_OR_DATA,
605
+ ATTR_WHITESPACE$1 = ATTR_WHITESPACE,
606
+ CUSTOM_ELEMENT$1 = CUSTOM_ELEMENT;
607
+ let IS_ALLOWED_URI$1 = IS_ALLOWED_URI;
375
608
  /**
376
609
  * We consider the elements and attributes below to be safe. Ideally
377
610
  * don't add any new ones but feel free to remove unwanted ones.
@@ -448,6 +681,13 @@ function createDOMPurify() {
448
681
  let WHOLE_DOCUMENT = false;
449
682
  /* Track whether config is already set on this instance of DOMPurify. */
450
683
  let SET_CONFIG = false;
684
+ /* Pristine allowlist bindings captured at setConfig() time. On the
685
+ * persistent-config path sanitize() restores the sets from these before
686
+ * the per-walk hook clone-guard, so a hook's in-call widening cannot
687
+ * carry across calls. Null until setConfig() is called; reset by
688
+ * clearConfig(). */
689
+ let SET_CONFIG_ALLOWED_TAGS = null;
690
+ let SET_CONFIG_ALLOWED_ATTR = null;
451
691
  /* Decide if all elements (e.g. style, script) must be children of
452
692
  * document.body. By default, browsers might move them to document.head */
453
693
  let FORCE_BODY = false;
@@ -490,7 +730,17 @@ function createDOMPurify() {
490
730
  let USE_PROFILES = {};
491
731
  /* Tags to ignore content of when KEEP_CONTENT is true */
492
732
  let FORBID_CONTENTS = null;
493
- 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']);
733
+ const DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script',
734
+ // <selectedcontent> mirrors the selected <option>'s subtree, cloned by
735
+ // the UA (customizable <select>) — including any on* handlers — and the
736
+ // engine re-mirrors synchronously whenever a removal changes which
737
+ // option/selectedcontent is current, even inside DOMPurify's inert
738
+ // DOMParser document. Hoisting its children on removal re-inserts a fresh
739
+ // mirror target ahead of the walk, which the engine refills, looping
740
+ // forever (DoS) and amplifying output. Dropping its content on removal
741
+ // (rather than hoisting) breaks that cascade; the content is a duplicate
742
+ // of the option, which is sanitized on its own. See campaign-3 F1/F6.
743
+ 'selectedcontent', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']);
494
744
  /* Tags that are safe for data: URIs */
495
745
  let DATA_URI_TAGS = null;
496
746
  const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);
@@ -506,8 +756,10 @@ function createDOMPurify() {
506
756
  /* Allowed XHTML+XML namespaces */
507
757
  let ALLOWED_NAMESPACES = null;
508
758
  const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);
509
- let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']);
510
- let HTML_INTEGRATION_POINTS = addToSet({}, ['annotation-xml']);
759
+ const DEFAULT_MATHML_TEXT_INTEGRATION_POINTS = freeze(['mi', 'mo', 'mn', 'ms', 'mtext']);
760
+ let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, DEFAULT_MATHML_TEXT_INTEGRATION_POINTS);
761
+ const DEFAULT_HTML_INTEGRATION_POINTS = freeze(['annotation-xml']);
762
+ let HTML_INTEGRATION_POINTS = addToSet({}, DEFAULT_HTML_INTEGRATION_POINTS);
511
763
  // Certain elements are allowed in both SVG and HTML
512
764
  // namespace. We need to specify them explicitly
513
765
  // so that they don't get erroneously deleted from
@@ -549,15 +801,33 @@ function createDOMPurify() {
549
801
  // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.
550
802
  transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase;
551
803
  /* Set configuration parameters */
552
- ALLOWED_TAGS = objectHasOwnProperty(cfg, 'ALLOWED_TAGS') ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS;
553
- ALLOWED_ATTR = objectHasOwnProperty(cfg, 'ALLOWED_ATTR') ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR;
554
- ALLOWED_NAMESPACES = objectHasOwnProperty(cfg, 'ALLOWED_NAMESPACES') ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES;
555
- 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;
556
- 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;
557
- FORBID_CONTENTS = objectHasOwnProperty(cfg, 'FORBID_CONTENTS') ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS;
558
- FORBID_TAGS = objectHasOwnProperty(cfg, 'FORBID_TAGS') ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : clone({});
559
- FORBID_ATTR = objectHasOwnProperty(cfg, 'FORBID_ATTR') ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : clone({});
560
- USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES : false;
804
+ ALLOWED_TAGS = _resolveSetOption(cfg, 'ALLOWED_TAGS', DEFAULT_ALLOWED_TAGS, {
805
+ transform: transformCaseFunc
806
+ });
807
+ ALLOWED_ATTR = _resolveSetOption(cfg, 'ALLOWED_ATTR', DEFAULT_ALLOWED_ATTR, {
808
+ transform: transformCaseFunc
809
+ });
810
+ ALLOWED_NAMESPACES = _resolveSetOption(cfg, 'ALLOWED_NAMESPACES', DEFAULT_ALLOWED_NAMESPACES, {
811
+ transform: stringToString
812
+ });
813
+ URI_SAFE_ATTRIBUTES = _resolveSetOption(cfg, 'ADD_URI_SAFE_ATTR', DEFAULT_URI_SAFE_ATTRIBUTES, {
814
+ transform: transformCaseFunc,
815
+ base: DEFAULT_URI_SAFE_ATTRIBUTES
816
+ });
817
+ DATA_URI_TAGS = _resolveSetOption(cfg, 'ADD_DATA_URI_TAGS', DEFAULT_DATA_URI_TAGS, {
818
+ transform: transformCaseFunc,
819
+ base: DEFAULT_DATA_URI_TAGS
820
+ });
821
+ FORBID_CONTENTS = _resolveSetOption(cfg, 'FORBID_CONTENTS', DEFAULT_FORBID_CONTENTS, {
822
+ transform: transformCaseFunc
823
+ });
824
+ FORBID_TAGS = _resolveSetOption(cfg, 'FORBID_TAGS', clone({}), {
825
+ transform: transformCaseFunc
826
+ });
827
+ FORBID_ATTR = _resolveSetOption(cfg, 'FORBID_ATTR', clone({}), {
828
+ transform: transformCaseFunc
829
+ });
830
+ USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES && typeof cfg.USE_PROFILES === 'object' ? clone(cfg.USE_PROFILES) : cfg.USE_PROFILES : false;
561
831
  ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true
562
832
  ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true
563
833
  ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false
@@ -573,20 +843,24 @@ function createDOMPurify() {
573
843
  SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false
574
844
  KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true
575
845
  IN_PLACE = cfg.IN_PLACE || false; // Default false
576
- IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI;
577
- NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;
578
- MATHML_TEXT_INTEGRATION_POINTS = cfg.MATHML_TEXT_INTEGRATION_POINTS || MATHML_TEXT_INTEGRATION_POINTS;
579
- HTML_INTEGRATION_POINTS = cfg.HTML_INTEGRATION_POINTS || HTML_INTEGRATION_POINTS;
580
- CUSTOM_ELEMENT_HANDLING = cfg.CUSTOM_ELEMENT_HANDLING || {};
581
- if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) {
582
- CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck;
583
- }
584
- if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) {
585
- CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck;
586
- }
587
- if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === 'boolean') {
588
- CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements;
589
- }
846
+ IS_ALLOWED_URI$1 = isRegex(cfg.ALLOWED_URI_REGEXP) ? cfg.ALLOWED_URI_REGEXP : IS_ALLOWED_URI; // Default regexp
847
+ NAMESPACE = typeof cfg.NAMESPACE === 'string' ? cfg.NAMESPACE : HTML_NAMESPACE; // Default HTML namespace
848
+ MATHML_TEXT_INTEGRATION_POINTS = _resolveObjectOption(cfg, 'MATHML_TEXT_INTEGRATION_POINTS', () => addToSet({}, DEFAULT_MATHML_TEXT_INTEGRATION_POINTS) // Default built-in map
849
+ );
850
+ HTML_INTEGRATION_POINTS = _resolveObjectOption(cfg, 'HTML_INTEGRATION_POINTS', () => addToSet({}, DEFAULT_HTML_INTEGRATION_POINTS) // Default built-in map
851
+ );
852
+ const customElementHandling = _resolveObjectOption(cfg, 'CUSTOM_ELEMENT_HANDLING', () => create(null));
853
+ CUSTOM_ELEMENT_HANDLING = create(null);
854
+ if (objectHasOwnProperty(customElementHandling, 'tagNameCheck') && isRegexOrFunction(customElementHandling.tagNameCheck)) {
855
+ CUSTOM_ELEMENT_HANDLING.tagNameCheck = customElementHandling.tagNameCheck; // Default undefined
856
+ }
857
+ if (objectHasOwnProperty(customElementHandling, 'attributeNameCheck') && isRegexOrFunction(customElementHandling.attributeNameCheck)) {
858
+ CUSTOM_ELEMENT_HANDLING.attributeNameCheck = customElementHandling.attributeNameCheck; // Default undefined
859
+ }
860
+ if (objectHasOwnProperty(customElementHandling, 'allowCustomizedBuiltInElements') && typeof customElementHandling.allowCustomizedBuiltInElements === 'boolean') {
861
+ CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = customElementHandling.allowCustomizedBuiltInElements; // Default undefined
862
+ }
863
+ seal(CUSTOM_ELEMENT_HANDLING);
590
864
  if (SAFE_FOR_TEMPLATES) {
591
865
  ALLOW_DATA_ATTR = false;
592
866
  }
@@ -596,7 +870,7 @@ function createDOMPurify() {
596
870
  /* Parse profile info */
597
871
  if (USE_PROFILES) {
598
872
  ALLOWED_TAGS = addToSet({}, text);
599
- ALLOWED_ATTR = [];
873
+ ALLOWED_ATTR = create(null);
600
874
  if (USE_PROFILES.html === true) {
601
875
  addToSet(ALLOWED_TAGS, html$1);
602
876
  addToSet(ALLOWED_ATTR, html);
@@ -617,37 +891,32 @@ function createDOMPurify() {
617
891
  addToSet(ALLOWED_ATTR, xml);
618
892
  }
619
893
  }
894
+ /* Always reset function-based ADD_TAGS / ADD_ATTR checks to prevent
895
+ * leaking across calls when switching from function to array config */
896
+ EXTRA_ELEMENT_HANDLING.tagCheck = null;
897
+ EXTRA_ELEMENT_HANDLING.attributeCheck = null;
620
898
  /* Merge configuration parameters */
621
- if (cfg.ADD_TAGS) {
899
+ if (objectHasOwnProperty(cfg, 'ADD_TAGS')) {
622
900
  if (typeof cfg.ADD_TAGS === 'function') {
623
901
  EXTRA_ELEMENT_HANDLING.tagCheck = cfg.ADD_TAGS;
624
- } else {
902
+ } else if (arrayIsArray(cfg.ADD_TAGS)) {
625
903
  if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
626
904
  ALLOWED_TAGS = clone(ALLOWED_TAGS);
627
905
  }
628
906
  addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);
629
907
  }
630
908
  }
631
- if (cfg.ADD_ATTR) {
909
+ if (objectHasOwnProperty(cfg, 'ADD_ATTR')) {
632
910
  if (typeof cfg.ADD_ATTR === 'function') {
633
911
  EXTRA_ELEMENT_HANDLING.attributeCheck = cfg.ADD_ATTR;
634
- } else {
912
+ } else if (arrayIsArray(cfg.ADD_ATTR)) {
635
913
  if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
636
914
  ALLOWED_ATTR = clone(ALLOWED_ATTR);
637
915
  }
638
916
  addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);
639
917
  }
640
918
  }
641
- if (cfg.ADD_URI_SAFE_ATTR) {
642
- addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);
643
- }
644
- if (cfg.FORBID_CONTENTS) {
645
- if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
646
- FORBID_CONTENTS = clone(FORBID_CONTENTS);
647
- }
648
- addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);
649
- }
650
- if (cfg.ADD_FORBID_CONTENTS) {
919
+ if (objectHasOwnProperty(cfg, 'ADD_FORBID_CONTENTS') && arrayIsArray(cfg.ADD_FORBID_CONTENTS)) {
651
920
  if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
652
921
  FORBID_CONTENTS = clone(FORBID_CONTENTS);
653
922
  }
@@ -666,6 +935,13 @@ function createDOMPurify() {
666
935
  addToSet(ALLOWED_TAGS, ['tbody']);
667
936
  delete FORBID_TAGS.tbody;
668
937
  }
938
+ // Re-derive the active Trusted Types policy from this configuration on
939
+ // every parse. The active policy must never be sticky closure state that
940
+ // outlives the config that set it: a caller-supplied policy left in place
941
+ // after `clearConfig()` — or after a later call that supplied none, or
942
+ // `TRUSTED_TYPES_POLICY: null` — could sign a subsequent "default"
943
+ // `RETURN_TRUSTED_TYPE` result with a foreign, possibly unsafe policy.
944
+ // See GHSA-vxr8-fq34-vvx9.
669
945
  if (cfg.TRUSTED_TYPES_POLICY) {
670
946
  if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') {
671
947
  throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');
@@ -673,18 +949,45 @@ function createDOMPurify() {
673
949
  if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') {
674
950
  throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');
675
951
  }
676
- // Overwrite existing TrustedTypes policy.
952
+ // A caller-supplied policy applies to this configuration only.
953
+ const previousTrustedTypesPolicy = trustedTypesPolicy;
677
954
  trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;
678
- // Sign local variables required by `sanitize`.
679
- emptyHTML = trustedTypesPolicy.createHTML('');
955
+ // Sign local variables required by `sanitize`. If the supplied policy's
956
+ // `createHTML` is circular (i.e. it calls `DOMPurify.sanitize`), this
957
+ // throws via the re-entrancy guard. Restore the previous policy first so
958
+ // the instance is not left in a poisoned state. See #1422.
959
+ try {
960
+ emptyHTML = _createTrustedHTML('');
961
+ } catch (error) {
962
+ trustedTypesPolicy = previousTrustedTypesPolicy;
963
+ throw error;
964
+ }
965
+ } else if (cfg.TRUSTED_TYPES_POLICY === null) {
966
+ // Explicit opt-out for this call: perform no Trusted Types signing and
967
+ // create nothing (so a strict `trusted-types` CSP that disallows a
968
+ // `dompurify` policy can still call `sanitize` from inside its own
969
+ // policy — see #1422). Resetting to `undefined` rather than a sticky
970
+ // `null` also drops any previously retained caller policy, so it cannot
971
+ // resurface on a later call, while still allowing the next config-less
972
+ // call to restore the internal default policy. See GHSA-vxr8-fq34-vvx9.
973
+ trustedTypesPolicy = undefined;
974
+ emptyHTML = '';
680
975
  } else {
681
- // Uninitialized policy, attempt to initialize the internal dompurify policy.
976
+ // No policy supplied: keep the currently active policy if one is set — a
977
+ // previously supplied policy is intentionally sticky across config-less
978
+ // calls — otherwise fall back to the instance's own internal policy,
979
+ // created at most once. (A policy supplied for a *single* call still
980
+ // lingers by design; what must not linger is a policy whose configuration
981
+ // has been torn down via `clearConfig()`, which restores the default.)
682
982
  if (trustedTypesPolicy === undefined) {
683
- trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);
983
+ trustedTypesPolicy = _getDefaultTrustedTypesPolicy();
684
984
  }
685
- // If creating the internal policy succeeded sign internal variables.
686
- if (trustedTypesPolicy !== null && typeof emptyHTML === 'string') {
687
- emptyHTML = trustedTypesPolicy.createHTML('');
985
+ // Sign internal variables only when a policy is active. A falsy policy
986
+ // (Trusted Types unsupported, creation failed, or an explicit opt-out)
987
+ // leaves `emptyHTML` as a plain string, so we never call `.createHTML` on
988
+ // a non-policy and throw. See #1422.
989
+ if (trustedTypesPolicy && typeof emptyHTML === 'string') {
990
+ emptyHTML = _createTrustedHTML('');
688
991
  }
689
992
  }
690
993
  // Prevent further manipulation of configuration.
@@ -699,6 +1002,77 @@ function createDOMPurify() {
699
1002
  * correctly. */
700
1003
  const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]);
701
1004
  const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]);
1005
+ /**
1006
+ * Namespace rules for an element in the SVG namespace.
1007
+ *
1008
+ * @param tagName the element's lowercase tag name
1009
+ * @param parent the (possibly simulated) parent node
1010
+ * @param parentTagName the parent's lowercase tag name
1011
+ * @returns true if a spec-compliant parser could produce this element
1012
+ */
1013
+ const _checkSvgNamespace = function _checkSvgNamespace(tagName, parent, parentTagName) {
1014
+ // The only way to switch from HTML namespace to SVG
1015
+ // is via <svg>. If it happens via any other tag, then
1016
+ // it should be killed.
1017
+ if (parent.namespaceURI === HTML_NAMESPACE) {
1018
+ return tagName === 'svg';
1019
+ }
1020
+ // The only way to switch from MathML to SVG is via <svg>
1021
+ // if the parent is either <annotation-xml> or a MathML
1022
+ // text integration point.
1023
+ if (parent.namespaceURI === MATHML_NAMESPACE) {
1024
+ return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
1025
+ }
1026
+ // We only allow elements that are defined in SVG
1027
+ // spec. All others are disallowed in SVG namespace.
1028
+ return Boolean(ALL_SVG_TAGS[tagName]);
1029
+ };
1030
+ /**
1031
+ * Namespace rules for an element in the MathML namespace.
1032
+ *
1033
+ * @param tagName the element's lowercase tag name
1034
+ * @param parent the (possibly simulated) parent node
1035
+ * @param parentTagName the parent's lowercase tag name
1036
+ * @returns true if a spec-compliant parser could produce this element
1037
+ */
1038
+ const _checkMathMlNamespace = function _checkMathMlNamespace(tagName, parent, parentTagName) {
1039
+ // The only way to switch from HTML namespace to MathML
1040
+ // is via <math>. If it happens via any other tag, then
1041
+ // it should be killed.
1042
+ if (parent.namespaceURI === HTML_NAMESPACE) {
1043
+ return tagName === 'math';
1044
+ }
1045
+ // The only way to switch from SVG to MathML is via
1046
+ // <math> and HTML integration points
1047
+ if (parent.namespaceURI === SVG_NAMESPACE) {
1048
+ return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
1049
+ }
1050
+ // We only allow elements that are defined in MathML
1051
+ // spec. All others are disallowed in MathML namespace.
1052
+ return Boolean(ALL_MATHML_TAGS[tagName]);
1053
+ };
1054
+ /**
1055
+ * Namespace rules for an element in the HTML namespace.
1056
+ *
1057
+ * @param tagName the element's lowercase tag name
1058
+ * @param parent the (possibly simulated) parent node
1059
+ * @param parentTagName the parent's lowercase tag name
1060
+ * @returns true if a spec-compliant parser could produce this element
1061
+ */
1062
+ const _checkHtmlNamespace = function _checkHtmlNamespace(tagName, parent, parentTagName) {
1063
+ // The only way to switch from SVG to HTML is via
1064
+ // HTML integration points, and from MathML to HTML
1065
+ // is via MathML text integration points
1066
+ if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
1067
+ return false;
1068
+ }
1069
+ if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
1070
+ return false;
1071
+ }
1072
+ // We disallow tags that are specific for MathML
1073
+ // or SVG and should never appear in HTML namespace
1074
+ return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
1075
+ };
702
1076
  /**
703
1077
  * @param element a DOM element whose namespace is being checked
704
1078
  * @returns Return false if the element has a
@@ -721,51 +1095,13 @@ function createDOMPurify() {
721
1095
  return false;
722
1096
  }
723
1097
  if (element.namespaceURI === SVG_NAMESPACE) {
724
- // The only way to switch from HTML namespace to SVG
725
- // is via <svg>. If it happens via any other tag, then
726
- // it should be killed.
727
- if (parent.namespaceURI === HTML_NAMESPACE) {
728
- return tagName === 'svg';
729
- }
730
- // The only way to switch from MathML to SVG is via`
731
- // svg if parent is either <annotation-xml> or MathML
732
- // text integration points.
733
- if (parent.namespaceURI === MATHML_NAMESPACE) {
734
- return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
735
- }
736
- // We only allow elements that are defined in SVG
737
- // spec. All others are disallowed in SVG namespace.
738
- return Boolean(ALL_SVG_TAGS[tagName]);
1098
+ return _checkSvgNamespace(tagName, parent, parentTagName);
739
1099
  }
740
1100
  if (element.namespaceURI === MATHML_NAMESPACE) {
741
- // The only way to switch from HTML namespace to MathML
742
- // is via <math>. If it happens via any other tag, then
743
- // it should be killed.
744
- if (parent.namespaceURI === HTML_NAMESPACE) {
745
- return tagName === 'math';
746
- }
747
- // The only way to switch from SVG to MathML is via
748
- // <math> and HTML integration points
749
- if (parent.namespaceURI === SVG_NAMESPACE) {
750
- return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
751
- }
752
- // We only allow elements that are defined in MathML
753
- // spec. All others are disallowed in MathML namespace.
754
- return Boolean(ALL_MATHML_TAGS[tagName]);
1101
+ return _checkMathMlNamespace(tagName, parent, parentTagName);
755
1102
  }
756
1103
  if (element.namespaceURI === HTML_NAMESPACE) {
757
- // The only way to switch from SVG to HTML is via
758
- // HTML integration points, and from MathML to HTML
759
- // is via MathML text integration points
760
- if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
761
- return false;
762
- }
763
- if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
764
- return false;
765
- }
766
- // We disallow tags that are specific for MathML
767
- // or SVG and should never appear in HTML namespace
768
- return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
1104
+ return _checkHtmlNamespace(tagName, parent, parentTagName);
769
1105
  }
770
1106
  // For XHTML and XML documents that support custom namespaces
771
1107
  if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) {
@@ -790,28 +1126,153 @@ function createDOMPurify() {
790
1126
  // eslint-disable-next-line unicorn/prefer-dom-node-remove
791
1127
  getParentNode(node).removeChild(node);
792
1128
  } catch (_) {
1129
+ /* The normal detach failed — this is reached for a parentless node
1130
+ (getParentNode() is null, so .removeChild throws). Element.prototype
1131
+ .remove() is itself a spec no-op on a parentless node, so a recorded
1132
+ "removal" would otherwise hand the caller back an intact,
1133
+ payload-bearing node (e.g. a detached IN_PLACE root the mXSS canary or
1134
+ the style-with-element-child rule decided to kill). Fail closed by
1135
+ throwing — exactly as a clobbered root does at the IN_PLACE entry —
1136
+ rather than trying to "neutralize" the node via its own methods.
1137
+ Neutralizing would mean calling getAttributeNames()/removeAttribute()
1138
+ on the node, both of which a <form> root can clobber via a named child
1139
+ (and _isClobbered does not even probe getAttributeNames), so the
1140
+ neutralize step could itself be silently defeated, leaving the payload
1141
+ intact. A throw touches only the cached, clobber-safe remove() and
1142
+ getParentNode(). Generalizes GHSA-r47g-fvhr-h676 (clobbered-form root)
1143
+ to every root-kill reason. REPORT-3.
1144
+ This lives inside the catch, so it never fires for a normally-removed
1145
+ in-tree node: those have a parent, removeChild() succeeds, and the
1146
+ catch is not entered. Only a kept (parentless) root reaches here. */
793
1147
  remove(node);
1148
+ if (!getParentNode(node)) {
1149
+ throw typeErrorCreate('a node selected for removal could not be detached from its tree ' + 'and cannot be safely returned; refusing to sanitize in place');
1150
+ }
1151
+ }
1152
+ };
1153
+ /**
1154
+ * _stripAttributeNode
1155
+ *
1156
+ * Remove a single Attr node case/namespace-exactly on an attribute-teardown
1157
+ * path. Name-based removeAttribute() ASCII-lowercases its lookup key for an
1158
+ * HTML element in an HTML document and so silently misses a case-preserved
1159
+ * handler (e.g. `ONERROR` off an XML/XHTML import) - the same defect
1160
+ * _removeAttribute() was fixed for, which a name-based call would reintroduce
1161
+ * on these IN_PLACE teardown paths. Unlike _removeAttribute this does not
1162
+ * record into DOMPurify.removed: the neutralize passes intentionally do not
1163
+ * book-keep. A clobbered/detached node falls back to best-effort name-based
1164
+ * removal.
1165
+ *
1166
+ * @param element the element to strip the attribute from
1167
+ * @param attribute the Attr node to remove
1168
+ * @param name the attribute's name, for the fallback path
1169
+ */
1170
+ const _stripAttributeNode = function _stripAttributeNode(element, attribute, name) {
1171
+ try {
1172
+ removeAttributeNode(element, attribute);
1173
+ } catch (_) {
1174
+ try {
1175
+ element.removeAttribute(name);
1176
+ } catch (_) {}
1177
+ }
1178
+ };
1179
+ /**
1180
+ * _neutralizeRoot
1181
+ *
1182
+ * Fail-closed teardown of an in-place root after the sanitize walk aborts
1183
+ * (campaign-3 F2). An internal throw mid-walk — e.g. a page-registered
1184
+ * custom element's reaction detaches a node so `_forceRemove`'s deliberate
1185
+ * parentless guard throws, or any other re-entrant engine mutation — would
1186
+ * otherwise leave the caller's *live* tree half-sanitized, with everything
1187
+ * after the abort point still carrying its handlers. There is no safe way
1188
+ * to resume the walk (the tree mutated under us), so we strip the root bare:
1189
+ * remove every child and every attribute, then let the caller's catch see
1190
+ * the original error. Clobber-safe (cached `remove`/`childNodes`/`attributes`
1191
+ * getters; the root was already clobber-pre-flighted at the IN_PLACE entry).
1192
+ *
1193
+ * @param root the in-place root to empty
1194
+ */
1195
+ const _neutralizeRoot = function _neutralizeRoot(root) {
1196
+ /* Strip every disallowed attribute (on* handlers included) off the whole
1197
+ subtree BEFORE detaching anything. Detaching first would hand back
1198
+ handler-bearing originals (e.g. an already-loading `<img onerror>`)
1199
+ whose queued resource event still fires in page scope after we throw.
1200
+ Clobber-safe reads; a doomed clobbered node's own attributes are
1201
+ irrelevant while its non-clobbered descendants are reached and scrubbed. */
1202
+ _neutralizeSubtree(root);
1203
+ const childNodes = getChildNodes(root);
1204
+ if (childNodes) {
1205
+ const snapshot = [];
1206
+ arrayForEach(childNodes, child => {
1207
+ arrayPush(snapshot, child);
1208
+ });
1209
+ arrayForEach(snapshot, child => {
1210
+ try {
1211
+ remove(child);
1212
+ } catch (_) {
1213
+ /* Best-effort teardown; a still-attached child is handled below */
1214
+ }
1215
+ });
1216
+ }
1217
+ const attributes = getAttributes(root);
1218
+ if (attributes) {
1219
+ for (let i = attributes.length - 1; i >= 0; --i) {
1220
+ const attribute = attributes[i];
1221
+ const name = attribute && attribute.name;
1222
+ if (typeof name === 'string') {
1223
+ _stripAttributeNode(root, attribute, name);
1224
+ }
1225
+ }
794
1226
  }
795
1227
  };
796
1228
  /**
797
1229
  * _removeAttribute
798
1230
  *
1231
+ * Name-based getAttributeNode()/removeAttribute() ASCII-lowercase their
1232
+ * lookup key for HTML elements in an HTML document, so they silently miss an
1233
+ * attribute whose stored qualified name still contains uppercase ASCII
1234
+ * letters. That happens when the node came from a case-preserving source
1235
+ * (an XML/XHTML document imported via importNode(), or createAttributeNS()),
1236
+ * where e.g. `ONERROR` survives the walk: the policy check lowercases to
1237
+ * `onerror` and rejects it, but `removeAttribute('ONERROR')` looks up
1238
+ * `onerror` and finds nothing. Remove the exact Attr node instead, which is
1239
+ * case- and namespace-exact, and fall back to name-based removal only when
1240
+ * the caller could not supply the node.
1241
+ *
799
1242
  * @param name an Attribute name
800
1243
  * @param element a DOM node
1244
+ * @param attr the exact Attr node to remove, when the caller has it
801
1245
  */
802
- const _removeAttribute = function _removeAttribute(name, element) {
1246
+ const _removeAttribute = function _removeAttribute(name, element, attr) {
1247
+ if (!attr) {
1248
+ try {
1249
+ attr = element.getAttributeNode(name);
1250
+ } catch (_) {
1251
+ attr = null;
1252
+ }
1253
+ }
1254
+ arrayPush(DOMPurify.removed, {
1255
+ attribute: attr || null,
1256
+ from: element
1257
+ });
803
1258
  try {
804
- arrayPush(DOMPurify.removed, {
805
- attribute: element.getAttributeNode(name),
806
- from: element
807
- });
1259
+ if (attr) {
1260
+ removeAttributeNode(element, attr);
1261
+ } else {
1262
+ element.removeAttribute(name);
1263
+ }
808
1264
  } catch (_) {
809
- arrayPush(DOMPurify.removed, {
810
- attribute: null,
811
- from: element
812
- });
1265
+ /* Clobbered or already-detached node - best-effort fall back to a
1266
+ name-based removal so the "is" handling below still runs. Note this
1267
+ fallback ASCII-lowercases its lookup key in an HTML document and so
1268
+ cannot reach a case-preserved attribute name; the cached
1269
+ removeAttributeNode() above is what removes those, and a clobbered
1270
+ form is already removed wholesale by _isClobbered() before reaching
1271
+ here. */
1272
+ try {
1273
+ element.removeAttribute(name);
1274
+ } catch (_) {}
813
1275
  }
814
- element.removeAttribute(name);
815
1276
  // We void attribute values for unremovable "is" attributes
816
1277
  if (name === 'is') {
817
1278
  if (RETURN_DOM || RETURN_DOM_FRAGMENT) {
@@ -825,6 +1286,164 @@ function createDOMPurify() {
825
1286
  }
826
1287
  }
827
1288
  };
1289
+ /**
1290
+ * _stripDisallowedAttributes
1291
+ *
1292
+ * Removes every attribute the active configuration does not allow from a
1293
+ * single element, using the same allowlist as the main attribute pass (so
1294
+ * `on*` handlers go, but no `/^on/` blocklist is introduced). Used only to
1295
+ * neutralise nodes that are being discarded from an in-place tree.
1296
+ *
1297
+ * @param element the element to strip
1298
+ */
1299
+ const _stripDisallowedAttributes = function _stripDisallowedAttributes(element) {
1300
+ const attributes = getAttributes(element);
1301
+ if (!attributes) {
1302
+ return;
1303
+ }
1304
+ for (let i = attributes.length - 1; i >= 0; --i) {
1305
+ const attribute = attributes[i];
1306
+ const name = attribute && attribute.name;
1307
+ if (typeof name !== 'string' || ALLOWED_ATTR[transformCaseFunc(name)]) {
1308
+ continue;
1309
+ }
1310
+ _stripAttributeNode(element, attribute, name);
1311
+ }
1312
+ };
1313
+ /**
1314
+ * _neutralizeSubtree
1315
+ *
1316
+ * Completes the audit-5 F1 fix across every removal path. The KEEP_CONTENT
1317
+ * move-hoist neutralises only disallowed-tag removals; clobber, mXSS-canary,
1318
+ * namespace, comment, processing-instruction and KEEP_CONTENT:false removals
1319
+ * all drop their subtree wholesale via `_forceRemove`. On the IN_PLACE path
1320
+ * those dropped nodes are detached from the caller's LIVE tree but a
1321
+ * handler-bearing original among them (an `<img onerror>`/`<video>` that was
1322
+ * loading) keeps its queued resource event, which fires in page scope after
1323
+ * sanitize returns. This walks a removed subtree and strips every attribute
1324
+ * the active configuration does not allow — so `on*` handlers are cancelled
1325
+ * through the SAME allowlist that governs kept nodes, not a separate `/^on/`
1326
+ * blocklist. Run synchronously before sanitize returns, i.e. before any
1327
+ * queued event can fire. Hook-free by design: these nodes leave the output,
1328
+ * so firing attribute hooks for them would be surprising. Clobber-safe reads;
1329
+ * a doomed clobbered node may shadow `removeAttribute` (its own attributes are
1330
+ * irrelevant — it is discarded — while its non-clobbered descendants, e.g.
1331
+ * the `<img>`, are reached and scrubbed).
1332
+ *
1333
+ * @param root the root of a removed subtree to neutralise
1334
+ */
1335
+ const _neutralizeSubtree = function _neutralizeSubtree(root) {
1336
+ const stack = [root];
1337
+ while (stack.length > 0) {
1338
+ const node = stack.pop();
1339
+ const nodeType = _readNodeType(node);
1340
+ if (nodeType === NODE_TYPE.element) {
1341
+ _stripDisallowedAttributes(node);
1342
+ }
1343
+ const childNodes = getChildNodes(node);
1344
+ if (childNodes) {
1345
+ for (let i = childNodes.length - 1; i >= 0; --i) {
1346
+ stack.push(childNodes[i]);
1347
+ }
1348
+ }
1349
+ }
1350
+ };
1351
+ /**
1352
+ * _neutralizePatchLinkage
1353
+ *
1354
+ * IN_PLACE entry pre-pass (declarative-partial-updates / streaming
1355
+ * hardening, https://github.com/WICG/declarative-partial-updates).
1356
+ *
1357
+ * The main walk strips patch linkage (`for`/`patchsrc`) and removes range
1358
+ * markers (PIs / markup comments) node-by-node, in document order, AS it
1359
+ * reaches each node. On a live in-place root that leaves a window: from the
1360
+ * moment the root is connected until the walk arrives at a given node, that
1361
+ * node's linkage is live. A patch applied on connection/stream can fire as
1362
+ * a microtask during the walk and inject or teleport an unsanitized DOM
1363
+ * range into a region the iterator has already passed and will not revisit,
1364
+ * so the post-return "tree is sanitized" contract is violated. Sweep the
1365
+ * whole tree once up front and sever every linkage before the walk begins,
1366
+ * closing that window.
1367
+ *
1368
+ * This CANNOT undo a patch that already fired before sanitize ran — that is
1369
+ * the irreducible "do not IN_PLACE a live-connected attacker tree" caveat —
1370
+ * but it closes everything from sanitize-start onward. Gated on SAFE_FOR_XML
1371
+ * to group with the rest of the declarative-partial-updates handling and
1372
+ * stay overridable, consistent with the codebase.
1373
+ *
1374
+ * Clobber-safe traversal (cached childNodes getter); per-node try/catch so a
1375
+ * clobbered root cannot defeat the sweep of its non-clobbered descendants.
1376
+ *
1377
+ * NOTE (pending real-Chrome confirmation, see test/declarative-patch-probe
1378
+ * .html Q1): this mirrors the existing policy of keeping `for` on
1379
+ * <label>/<output>. If the shipping feature can drive a patch through a
1380
+ * surviving `for`-on-label/output + `id` pair, this pre-pass and the
1381
+ * attribute check at _isBasicCustomElement's caller must additionally drop
1382
+ * that pair on the IN_PLACE path. Left as-is until the taxonomy is verified.
1383
+ *
1384
+ * @param root the in-place root to sweep
1385
+ */
1386
+ /**
1387
+ * Central policy for declarative-partial-updates patch-linkage attributes,
1388
+ * shared by the _neutralizePatchLinkage pre-pass and _isValidAttribute so
1389
+ * the two sites cannot drift: `patchsrc` always links, `for` links
1390
+ * everywhere except on <label>/<output>, and the whole policy is gated on
1391
+ * SAFE_FOR_XML (see the rationale block in _isValidAttribute).
1392
+ *
1393
+ * @param lcName the transformCaseFunc'd attribute name
1394
+ * @param lcTag the transformCaseFunc'd tag name of the carrying element
1395
+ * @return true if the attribute is patch linkage and must be dropped
1396
+ */
1397
+ const _isPatchLinkageAttribute = function _isPatchLinkageAttribute(lcName, lcTag) {
1398
+ if (!SAFE_FOR_XML) {
1399
+ return false;
1400
+ }
1401
+ if (lcName === 'patchsrc') {
1402
+ return true;
1403
+ }
1404
+ return lcName === 'for' && lcTag !== 'label' && lcTag !== 'output';
1405
+ };
1406
+ const _neutralizePatchLinkage = function _neutralizePatchLinkage(root) {
1407
+ if (!SAFE_FOR_XML) {
1408
+ return;
1409
+ }
1410
+ const stack = [root];
1411
+ while (stack.length > 0) {
1412
+ const node = stack.pop();
1413
+ const nodeType = _readNodeType(node);
1414
+ /* Remove range markers (the target side of a patch linkage): every
1415
+ processing instruction, and any markup-bearing comment. */
1416
+ if (nodeType === NODE_TYPE.processingInstruction || nodeType === NODE_TYPE.comment && regExpTest(COMMENT_MARKUP_PROBE, node.data)) {
1417
+ try {
1418
+ remove(node);
1419
+ } catch (_) {
1420
+ /* Best-effort */
1421
+ }
1422
+ continue;
1423
+ }
1424
+ /* Strip patch-source attributes (the source side) off elements. */
1425
+ if (nodeType === NODE_TYPE.element) {
1426
+ const element = node;
1427
+ const lcTag = transformCaseFunc(_readNodeName(node));
1428
+ try {
1429
+ if (element.hasAttribute && element.hasAttribute('patchsrc')) {
1430
+ element.removeAttribute('patchsrc');
1431
+ }
1432
+ if (element.hasAttribute && element.hasAttribute('for') && _isPatchLinkageAttribute('for', lcTag)) {
1433
+ element.removeAttribute('for');
1434
+ }
1435
+ } catch (_) {
1436
+ /* Clobbered removeAttribute/hasAttribute on a doomed node — ignore */
1437
+ }
1438
+ }
1439
+ const childNodes = getChildNodes(node);
1440
+ if (childNodes) {
1441
+ for (let i = childNodes.length - 1; i >= 0; --i) {
1442
+ stack.push(childNodes[i]);
1443
+ }
1444
+ }
1445
+ }
1446
+ };
828
1447
  /**
829
1448
  * _initDocument
830
1449
  *
@@ -846,7 +1465,7 @@ function createDOMPurify() {
846
1465
  // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)
847
1466
  dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + '</body></html>';
848
1467
  }
849
- const dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
1468
+ const dirtyPayload = trustedTypesPolicy ? _createTrustedHTML(dirty) : dirty;
850
1469
  /*
851
1470
  * Use the DOMParser API by default, fallback later if needs be
852
1471
  * DOMParser not work for svg when has multiple root element.
@@ -882,33 +1501,374 @@ function createDOMPurify() {
882
1501
  * @return The created NodeIterator
883
1502
  */
884
1503
  const _createNodeIterator = function _createNodeIterator(root) {
885
- return createNodeIterator.call(root.ownerDocument || root, root,
1504
+ /* Read ownerDocument through the cached Node.prototype getter, never the
1505
+ direct property. HTMLFormElement has [LegacyOverrideBuiltIns], so a
1506
+ clobbering child (<input name="ownerDocument"> or a form-associated
1507
+ external input) shadows the prototype getter and makes a direct read
1508
+ return that <input>. createNodeIterator.call(<input>, ...) then throws
1509
+ "Illegal invocation", and on the IN_PLACE path that throw lands before
1510
+ the walk's fail-closed barrier - leaving the caller's live tree, with
1511
+ any already-armed handler in it, un-neutralized. The cached getter
1512
+ returns the real Document regardless of the clobber. */
1513
+ const doc = getOwnerDocument ? getOwnerDocument(root) : root.ownerDocument;
1514
+ return createNodeIterator.call(doc || root, root,
886
1515
  // eslint-disable-next-line no-bitwise
887
1516
  NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null);
888
1517
  };
1518
+ /**
1519
+ * Replace template expression syntax (mustache, ERB, template
1520
+ * literal) with a space; shared by all SAFE_FOR_TEMPLATES scrub
1521
+ * sites. Order matters: mustache, then ERB, then template literal.
1522
+ *
1523
+ * @param value the string to scrub
1524
+ * @returns the scrubbed string
1525
+ */
1526
+ const _stripTemplateExpressions = function _stripTemplateExpressions(value) {
1527
+ value = stringReplace(value, MUSTACHE_EXPR$1, ' ');
1528
+ value = stringReplace(value, ERB_EXPR$1, ' ');
1529
+ value = stringReplace(value, TMPLIT_EXPR$1, ' ');
1530
+ return value;
1531
+ };
1532
+ /**
1533
+ * Strip template-engine expressions ({{...}}, ${...}, <%...%>) from the
1534
+ * character data of an element subtree. Used as the final safety net for
1535
+ * SAFE_FOR_TEMPLATES on every DOM-returning code path so that expressions
1536
+ * which only form after text-node normalization (e.g. fragments split across
1537
+ * stripped elements) cannot survive into a template-evaluating framework.
1538
+ *
1539
+ * Walks text/comment/CDATA/processing-instruction nodes and mutates `.data`
1540
+ * in place rather than round-tripping through innerHTML. This preserves
1541
+ * descendant node references (important for IN_PLACE callers), avoids a
1542
+ * serialize/reparse cycle, and reads literal character data — which means
1543
+ * `<%...%>` in text content matches the ERB regex against its real bytes
1544
+ * instead of the HTML-entity-escaped form innerHTML would produce.
1545
+ *
1546
+ * Attribute values are not visited here; SAFE_FOR_TEMPLATES handling for
1547
+ * attributes is performed during the per-node `_sanitizeAttributes` pass.
1548
+ *
1549
+ * @param node The root element whose character data should be scrubbed.
1550
+ */
1551
+ const _scrubTemplateExpressions2 = function _scrubTemplateExpressions(node) {
1552
+ var _node$querySelectorAl;
1553
+ node.normalize();
1554
+ /* Clobber-safe ownerDocument read, same reasoning as _createNodeIterator:
1555
+ under SAFE_FOR_TEMPLATES this runs on the live IN_PLACE root, which may
1556
+ carry a form-named-getter override of ownerDocument. */
1557
+ const doc = getOwnerDocument ? getOwnerDocument(node) : node.ownerDocument;
1558
+ const walker = createNodeIterator.call(doc || node, node,
1559
+ // eslint-disable-next-line no-bitwise
1560
+ NodeFilter.SHOW_TEXT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_CDATA_SECTION | NodeFilter.SHOW_PROCESSING_INSTRUCTION, null);
1561
+ let currentNode = walker.nextNode();
1562
+ while (currentNode) {
1563
+ currentNode.data = _stripTemplateExpressions(currentNode.data);
1564
+ currentNode = walker.nextNode();
1565
+ }
1566
+ // NodeIterator does not descend into <template>.content per the DOM spec,
1567
+ // so we must explicitly recurse into each template's content fragment,
1568
+ // mirroring the approach used by _sanitizeShadowDOM.
1569
+ const templates = (_node$querySelectorAl = node.querySelectorAll) === null || _node$querySelectorAl === void 0 ? void 0 : _node$querySelectorAl.call(node, 'template');
1570
+ if (templates) {
1571
+ arrayForEach(templates, tmpl => {
1572
+ if (_isDocumentFragment(tmpl.content)) {
1573
+ _scrubTemplateExpressions2(tmpl.content);
1574
+ }
1575
+ });
1576
+ }
1577
+ };
889
1578
  /**
890
1579
  * _isClobbered
891
1580
  *
1581
+ * Detect DOM-clobbering on HTMLFormElement nodes. Form is the only HTML
1582
+ * interface with [LegacyOverrideBuiltIns]; a descendant element with a
1583
+ * `name` attribute matching a prototype property shadows that property
1584
+ * on direct reads. We use this check at the IN_PLACE entry-point and
1585
+ * during attribute sanitization to refuse clobbered forms.
1586
+ *
892
1587
  * @param element element to check for clobbering attacks
893
1588
  * @return true if clobbered, false if safe
894
1589
  */
895
1590
  const _isClobbered = function _isClobbered(element) {
896
- 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');
1591
+ // Realm-independent tag-name probe. If we can't determine the tag
1592
+ // name at all, we can't reason about clobbering — return false
1593
+ // (the caller's other defences still apply).
1594
+ const realTagName = getNodeName ? getNodeName(element) : null;
1595
+ if (typeof realTagName !== 'string') {
1596
+ return false;
1597
+ }
1598
+ if (transformCaseFunc(realTagName) !== 'form') {
1599
+ return false;
1600
+ }
1601
+ return typeof element.nodeName !== 'string' || typeof element.textContent !== 'string' || typeof element.removeChild !== 'function' ||
1602
+ // Realm-safe NamedNodeMap detection: equality against the cached
1603
+ // prototype getter. Clobbered .attributes (e.g. <input name="attributes">)
1604
+ // makes the direct read diverge from the cached read; a clean form
1605
+ // (same-realm OR foreign-realm) has both reads pointing at the same
1606
+ // canonical NamedNodeMap.
1607
+ element.attributes !== getAttributes(element) || typeof element.removeAttribute !== 'function' ||
1608
+ // A form descendant named "removeAttributeNode" or "getAttributeNode"
1609
+ // shadows these Attr-node methods via [LegacyOverrideBuiltIns].
1610
+ // _removeAttribute() / _stripAttributeNode() reach for
1611
+ // element.removeAttributeNode(attr) first; when it is shadowed the call
1612
+ // throws and the name-based fallback element.removeAttribute(name)
1613
+ // ASCII-lowercases its lookup key in an HTML document, silently missing
1614
+ // a case-preserved event-handler attribute (e.g. an ONANIMATIONSTART
1615
+ // that reached the sanitizer through an XML/XHTML parse). Flag the form
1616
+ // so it is removed wholesale, exactly as for the other shadowed methods.
1617
+ typeof element.removeAttributeNode !== 'function' || typeof element.getAttributeNode !== 'function' || typeof element.setAttribute !== 'function' || typeof element.namespaceURI !== 'string' || typeof element.insertBefore !== 'function' || typeof element.hasChildNodes !== 'function' ||
1618
+ // NodeType clobbering probe. Cached Node.prototype.nodeType getter
1619
+ // returns the integer 1 for any Element regardless of realm; direct
1620
+ // read on a clobbered form (e.g. <input name="nodeType">) returns
1621
+ // the named child element. Cheap addition — nodeType is read from
1622
+ // an internal slot, no serialization cost — and removes a residual
1623
+ // clobbering surface used by several mXSS / PI / comment branches
1624
+ // in _sanitizeElements that compare currentNode.nodeType directly.
1625
+ element.nodeType !== getNodeType(element) ||
1626
+ // HTMLFormElement has [LegacyOverrideBuiltIns]: a descendant named
1627
+ // "childNodes" shadows the prototype getter. Direct reads of
1628
+ // form.childNodes from a clobbered form return the named child
1629
+ // instead of the real NodeList, so any walk that reads it directly
1630
+ // skips the form's real children. Compare the direct read to the
1631
+ // cached Node.prototype getter — when the form's named-property
1632
+ // getter intercepts the read, the two values differ and we flag
1633
+ // the form. This catches every clobbering child type (input,
1634
+ // select, etc.) regardless of whether the named child happens to
1635
+ // carry a numeric .length, which a typeof-based probe would miss
1636
+ // (e.g. HTMLSelectElement.length is a defined unsigned-long).
1637
+ element.childNodes !== getChildNodes(element);
897
1638
  };
898
1639
  /**
899
- * Checks whether the given object is a DOM node.
1640
+ * Checks whether the given value is a DocumentFragment from any realm.
1641
+ *
1642
+ * The realm-independent replacement reads `nodeType` through the cached
1643
+ * Node.prototype getter and compares to the DOCUMENT_FRAGMENT_NODE
1644
+ * constant (11). nodeType is a numeric value resolved from the node's
1645
+ * internal slot, identical across realms for the same kind of node.
1646
+ *
1647
+ * @param value object to check
1648
+ * @return true if value is a DocumentFragment-shaped node from any realm
1649
+ */
1650
+ const _isDocumentFragment = function _isDocumentFragment(value) {
1651
+ if (!getNodeType || typeof value !== 'object' || value === null) {
1652
+ return false;
1653
+ }
1654
+ try {
1655
+ return getNodeType(value) === NODE_TYPE.documentFragment;
1656
+ } catch (_) {
1657
+ return false;
1658
+ }
1659
+ };
1660
+ /**
1661
+ * Checks whether the given object is a DOM node, including nodes that
1662
+ * originate from a different window/realm (e.g. an iframe's
1663
+ * contentDocument). The previous `value instanceof Node` check was
1664
+ * realm-bound: nodes from a different window failed it, causing
1665
+ * sanitize() to silently stringify them and reset IN_PLACE to false,
1666
+ * returning the original node unsanitized. See GHSA-4w3q-35jp-p934.
900
1667
  *
901
1668
  * @param value object to check whether it's a DOM node
902
- * @return true is object is a DOM node
1669
+ * @return true if value is a DOM node from any realm
903
1670
  */
904
1671
  const _isNode = function _isNode(value) {
905
- return typeof Node === 'function' && value instanceof Node;
1672
+ if (!getNodeType || typeof value !== 'object' || value === null) {
1673
+ return false;
1674
+ }
1675
+ try {
1676
+ return typeof getNodeType(value) === 'number';
1677
+ } catch (_) {
1678
+ return false;
1679
+ }
906
1680
  };
907
1681
  function _executeHooks(hooks, currentNode, data) {
1682
+ if (hooks.length === 0) {
1683
+ return;
1684
+ }
908
1685
  arrayForEach(hooks, hook => {
909
1686
  hook.call(DOMPurify, currentNode, data, CONFIG);
910
1687
  });
911
1688
  }
1689
+ /**
1690
+ * Structural-threat checks that condemn a node regardless of the
1691
+ * allowlists: mXSS via namespace confusion, risky CSS construction,
1692
+ * processing instructions, markup-bearing comments. Pure predicate;
1693
+ * the caller removes. Check order is load-bearing.
1694
+ *
1695
+ * @param currentNode the node to inspect
1696
+ * @param tagName the node's transformCaseFunc'd tag name
1697
+ * @return true if the node must be removed
1698
+ */
1699
+ const _isUnsafeNode = function _isUnsafeNode(currentNode, tagName) {
1700
+ /* Detect mXSS attempts abusing namespace confusion */
1701
+ if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.textContent) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.innerHTML)) {
1702
+ return true;
1703
+ }
1704
+ /* Remove rawtext/literal-text elements whose literal serialization
1705
+ re-opens markup on an HTML reparse - shapes (a) and (b) documented at
1706
+ LITERAL_TEXT_ELEMENTS. Both are invisible to rule 1 above (which
1707
+ self-disables once there is an element child, and whose second probe
1708
+ reads the innerHTML an XML/XHTML document serializes escaped), which
1709
+ is why both probes here read textContent instead. Previously only
1710
+ `style`-with-element-child was covered; every element in
1711
+ LITERAL_TEXT_ELEMENTS shares this literal serialization and is
1712
+ equally affected. */
1713
+ if (SAFE_FOR_XML && currentNode.namespaceURI === HTML_NAMESPACE && LITERAL_TEXT_ELEMENTS[tagName] && (_isNode(currentNode.firstElementChild) || typeof currentNode.textContent === 'string' && regExpTest(LITERAL_TEXT_CLOSE[tagName], currentNode.textContent))) {
1714
+ return true;
1715
+ }
1716
+ /* Remove any occurrence of processing instructions */
1717
+ if (currentNode.nodeType === NODE_TYPE.processingInstruction) {
1718
+ return true;
1719
+ }
1720
+ /* Remove any kind of possibly harmful comments */
1721
+ if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(COMMENT_MARKUP_PROBE, currentNode.data)) {
1722
+ return true;
1723
+ }
1724
+ return false;
1725
+ };
1726
+ /**
1727
+ * Evaluate a CUSTOM_ELEMENT_HANDLING check (a RegExp or a predicate
1728
+ * function, per the validation in _parseConfig) against a name.
1729
+ * Additional arguments are forwarded to predicate functions - the
1730
+ * attributeNameCheck predicate receives the tag name as its second
1731
+ * argument. A null/absent check never matches.
1732
+ *
1733
+ * @param check the configured tagNameCheck / attributeNameCheck value
1734
+ * @param name the name to test
1735
+ * @param args extra arguments forwarded to a predicate function
1736
+ * @return true if the check matches the name
1737
+ */
1738
+ const _matchesNameCheck = function _matchesNameCheck(check, name) {
1739
+ if (check instanceof RegExp) {
1740
+ return regExpTest(check, name);
1741
+ }
1742
+ if (check instanceof Function) {
1743
+ for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
1744
+ args[_key - 2] = arguments[_key];
1745
+ }
1746
+ return Boolean(check(name, ...args));
1747
+ }
1748
+ return false;
1749
+ };
1750
+ /**
1751
+ * Handle a node whose tag is forbidden or not allowlisted: keep
1752
+ * allowed custom elements (false return exits _sanitizeElements
1753
+ * early - the namespace and fallback-tag removal checks are
1754
+ * intentionally skipped for kept custom elements), else hoist
1755
+ * content per KEEP_CONTENT and remove.
1756
+ *
1757
+ * A kept custom element is the ONLY case in which this function
1758
+ * returns false, so the caller uses that return value to run the
1759
+ * afterSanitizeElements hook on the kept element and keep the
1760
+ * element-hook lifecycle consistent with normal allowlisted
1761
+ * elements (GHSA-c2j3-45gr-mqc4).
1762
+ *
1763
+ * @param currentNode the disallowed node
1764
+ * @param tagName the node's transformCaseFunc'd tag name
1765
+ * @return true if the node was removed, false if kept
1766
+ */
1767
+ const _sanitizeDisallowedNode = function _sanitizeDisallowedNode(currentNode, tagName, root) {
1768
+ /* Check if we have a custom element to handle */
1769
+ if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName) && _matchesNameCheck(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {
1770
+ return false;
1771
+ }
1772
+ /* Keep content except for bad-listed elements.
1773
+ Use the cached prototype getters exclusively — the previous code
1774
+ had `|| currentNode.parentNode` / `|| currentNode.childNodes`
1775
+ fallbacks, but the cached getters always return the canonical
1776
+ value (or null for a real parent-less node), so the fallback
1777
+ path was dead in safe cases and a clobbering surface in unsafe
1778
+ ones. Falsy cached results stay falsy; the `if (childNodes &&
1779
+ parentNode)` check already gates correctly. */
1780
+ if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
1781
+ const parentNode = getParentNode(currentNode);
1782
+ const childNodes = getChildNodes(currentNode);
1783
+ if (childNodes && parentNode) {
1784
+ const childCount = childNodes.length;
1785
+ /* Hoist by moving each child up one level rather than deep-cloning
1786
+ it. Moving transfers every descendant exactly once, so a chain of
1787
+ nested disallowed elements costs O(n) instead of the O(n^2) that
1788
+ re-cloning the shrinking subtree at each level produced; it also
1789
+ empties the removed original, so `DOMPurify.removed` no longer
1790
+ pins whole subtrees. Moving preserves the in-place guarantee too:
1791
+ an original carrying already-queued resource events (`<img
1792
+ onerror>`, `<video>`/`<audio>` error, lazy/`onload`, …) is
1793
+ relocated and sanitised rather than left detached but still armed.
1794
+ The sole case that must clone is removing the walk root itself.
1795
+ The result is serialised from the root's subtree, so a restrictive
1796
+ ALLOWED_TAGS that strips the root (`body` on the string path) must
1797
+ leave the content inside it, which only cloning does. In IN_PLACE
1798
+ the root is pre-validated as an allowed tag and so is never removed
1799
+ here, so that path always takes the move branch.
1800
+ `childNodes` is live; a tail-to-head walk keeps `childNodes[i]`
1801
+ valid whether we move (drops the trailing entry) or clone (leaves
1802
+ the list intact). */
1803
+ for (let i = childCount - 1; i >= 0; --i) {
1804
+ const hoisted = currentNode === root ? cloneNode(childNodes[i], true) : childNodes[i];
1805
+ parentNode.insertBefore(hoisted, getNextSibling(currentNode));
1806
+ }
1807
+ }
1808
+ }
1809
+ _forceRemove(currentNode);
1810
+ return true;
1811
+ };
1812
+ /**
1813
+ * Fork a hook-mutable allowlist off its shared binding the first time a
1814
+ * (possibly lazily-installed) uponSanitize* hook is about to see it, so the
1815
+ * hook cannot widen the per-instance default or the setConfig binding by
1816
+ * reference and leak past the call. Returns the set unchanged once it is
1817
+ * already call-local, so repeated calls across elements are idempotent.
1818
+ *
1819
+ * @param hookList the uponSanitize* hook array for this event
1820
+ * @param set the current ALLOWED_TAGS / ALLOWED_ATTR binding
1821
+ * @param defaultSet the per-instance DEFAULT_ALLOWED_* constant
1822
+ * @param setConfigSet the captured setConfig() binding, or null
1823
+ * @return a call-local clone if a hook is present and set is still shared,
1824
+ * else set unchanged
1825
+ */
1826
+ const _forkSharedAllowlist = function _forkSharedAllowlist(hookList, set, defaultSet, setConfigSet) {
1827
+ if (hookList.length === 0) {
1828
+ return set;
1829
+ }
1830
+ return set === defaultSet || set === setConfigSet ? clone(set) : set;
1831
+ };
1832
+ /**
1833
+ * Shared guard for a node that a hook has detached from the walk tree,
1834
+ * used after each element-hook site in _sanitizeElements. Detaching is a
1835
+ * long-standing user pattern (issue #469; draw.io-style foreignObject
1836
+ * filtering). Per the cached, unclobberable parentNode getter the node is
1837
+ * genuinely out of the tree, so it can reach neither the serialized
1838
+ * output nor an IN_PLACE live tree; treat it as removed and stop
1839
+ * processing it. Without this guard, the unsafe-node / namespace checks
1840
+ * would call _forceRemove on a parentless node and hit the REPORT-3
1841
+ * fail-closed throw — which exists for nodes DOMPurify wants gone but
1842
+ * *cannot* detach (clobbered / parentless roots), the opposite of a node
1843
+ * that is already safely gone. The walk root is exempt: a detached
1844
+ * IN_PLACE root is legitimate input and must still be fully sanitized,
1845
+ * and a kill-decision on it must keep hitting the REPORT-3 throw.
1846
+ *
1847
+ * Nodes detached by hooks stay the hook's responsibility for placement:
1848
+ * they are not recorded in DOMPurify.removed, so the post-walk IN_PLACE
1849
+ * pass (which iterates DOMPurify.removed) does not reach them. But a
1850
+ * hook-detached subtree can still hold a queued resource-event handler -
1851
+ * e.g. an <img onload> that began loading when the caller built the live
1852
+ * tree - which fires in page scope after sanitize returns even though the
1853
+ * handler never reached the returned tree. That is the audit-5 F1 hazard,
1854
+ * and the documented node.remove() hook pattern walks straight into it.
1855
+ * So on the IN_PLACE path we neutralize the detached subtree inline,
1856
+ * stripping its non-allow-listed attributes before returning, exactly as
1857
+ * the post-walk pass does for _forceRemove'd subtrees.
1858
+ *
1859
+ * @param currentNode the node a hook may have detached
1860
+ * @param root the current walk root
1861
+ * @return true if the node is detached and now handled, false otherwise
1862
+ */
1863
+ const _handleHookDetachedNode = function _handleHookDetachedNode(currentNode, root) {
1864
+ if (currentNode === root || getParentNode(currentNode) !== null) {
1865
+ return false;
1866
+ }
1867
+ if (IN_PLACE) {
1868
+ _neutralizeSubtree(currentNode);
1869
+ }
1870
+ return true;
1871
+ };
912
1872
  /**
913
1873
  * _sanitizeElements
914
1874
  *
@@ -918,81 +1878,81 @@ function createDOMPurify() {
918
1878
  * @param currentNode to check for permission to exist
919
1879
  * @return true if node was killed, false if left alive
920
1880
  */
921
- const _sanitizeElements = function _sanitizeElements(currentNode) {
922
- let content = null;
1881
+ const _sanitizeElements = function _sanitizeElements(currentNode, root) {
923
1882
  /* Execute a hook if present */
924
1883
  _executeHooks(hooks.beforeSanitizeElements, currentNode, null);
1884
+ /* A hook may have detached the node - treat it as removed (see
1885
+ _handleHookDetachedNode for the full rationale). */
1886
+ if (_handleHookDetachedNode(currentNode, root)) {
1887
+ return true;
1888
+ }
925
1889
  /* Check if element is clobbered or can clobber */
926
1890
  if (_isClobbered(currentNode)) {
927
1891
  _forceRemove(currentNode);
928
1892
  return true;
929
1893
  }
930
1894
  /* Now let's check the element's type and name */
931
- const tagName = transformCaseFunc(currentNode.nodeName);
1895
+ const tagName = transformCaseFunc(_readNodeName(currentNode));
1896
+ /* Close the pre-walk clone-guard's timing gap: an uponSanitizeElement
1897
+ hook may have been installed after that guard sampled the hook arrays
1898
+ (e.g. lazily from beforeSanitizeElements), leaving ALLOWED_TAGS still
1899
+ aliasing a shared binding that a widening hook would mutate by
1900
+ reference. Fork it before exposing it to the hook. */
1901
+ ALLOWED_TAGS = _forkSharedAllowlist(hooks.uponSanitizeElement, ALLOWED_TAGS, DEFAULT_ALLOWED_TAGS, SET_CONFIG_ALLOWED_TAGS);
932
1902
  /* Execute a hook if present */
933
1903
  _executeHooks(hooks.uponSanitizeElement, currentNode, {
934
1904
  tagName,
935
- allowedTags: ALLOWED_TAGS
936
- });
937
- /* Detect mXSS attempts abusing namespace confusion */
938
- if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(/<[/\w!]/g, currentNode.innerHTML) && regExpTest(/<[/\w!]/g, currentNode.textContent)) {
939
- _forceRemove(currentNode);
940
- return true;
941
- }
942
- /* Remove any occurrence of processing instructions */
943
- if (currentNode.nodeType === NODE_TYPE.progressingInstruction) {
944
- _forceRemove(currentNode);
1905
+ allowedTags: ALLOWED_TAGS
1906
+ });
1907
+ /* The uponSanitizeElement hook may have detached the node, exactly as
1908
+ above (see _handleHookDetachedNode for the full rationale). */
1909
+ if (_handleHookDetachedNode(currentNode, root)) {
945
1910
  return true;
946
1911
  }
947
- /* Remove any kind of possibly harmful comments */
948
- if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(/<[/\w]/g, currentNode.data)) {
1912
+ /* Remove mXSS vectors, processing instructions and risky comments */
1913
+ if (_isUnsafeNode(currentNode, tagName)) {
949
1914
  _forceRemove(currentNode);
950
1915
  return true;
951
1916
  }
952
1917
  /* Remove element if anything forbids its presence */
953
- if (!(EXTRA_ELEMENT_HANDLING.tagCheck instanceof Function && EXTRA_ELEMENT_HANDLING.tagCheck(tagName)) && (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName])) {
954
- /* Check if we have a custom element to handle */
955
- if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {
956
- if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {
957
- return false;
958
- }
959
- if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) {
960
- return false;
961
- }
962
- }
963
- /* Keep content except for bad-listed elements */
964
- if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
965
- const parentNode = getParentNode(currentNode) || currentNode.parentNode;
966
- const childNodes = getChildNodes(currentNode) || currentNode.childNodes;
967
- if (childNodes && parentNode) {
968
- const childCount = childNodes.length;
969
- for (let i = childCount - 1; i >= 0; --i) {
970
- const childClone = cloneNode(childNodes[i], true);
971
- childClone.__removalCount = (currentNode.__removalCount || 0) + 1;
972
- parentNode.insertBefore(childClone, getNextSibling(currentNode));
973
- }
974
- }
1918
+ if (FORBID_TAGS[tagName] || !(EXTRA_ELEMENT_HANDLING.tagCheck instanceof Function && EXTRA_ELEMENT_HANDLING.tagCheck(tagName)) && !ALLOWED_TAGS[tagName]) {
1919
+ const removed = _sanitizeDisallowedNode(currentNode, tagName, root);
1920
+ /* A false return means the node is a custom element kept via
1921
+ CUSTOM_ELEMENT_HANDLING - the only keep path through
1922
+ _sanitizeDisallowedNode. Run afterSanitizeElements on it so the
1923
+ element-hook lifecycle matches normal allowlisted elements: a
1924
+ security policy applied in this hook (e.g. stripping an attribute
1925
+ from every surviving element) must not silently skip kept custom
1926
+ elements (GHSA-c2j3-45gr-mqc4). This mirrors the normal-element
1927
+ tail below - the hook runs, then the walker's subsequent
1928
+ _sanitizeAttributes pass sanitizes the element's attributes. The
1929
+ deliberately skipped namespace and fallback-tag removal checks stay
1930
+ skipped; they are removal decisions, not the hook contract. */
1931
+ if (removed === false) {
1932
+ _executeHooks(hooks.afterSanitizeElements, currentNode, null);
975
1933
  }
976
- _forceRemove(currentNode);
977
- return true;
978
- }
979
- /* Check whether element has a valid namespace */
980
- if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {
1934
+ return removed;
1935
+ }
1936
+ /* Check whether element has a valid namespace.
1937
+ Realm-safe check (GHSA-hpcv-96wg-7vj8): use the cached Node.prototype
1938
+ nodeType getter rather than `instanceof Element`, which is realm-
1939
+ bound and short-circuits to false for any node minted in a different
1940
+ realm — letting a foreign-realm element with a forbidden namespace
1941
+ slip past the namespace check entirely. */
1942
+ const nt = _readNodeType(currentNode);
1943
+ if (nt === NODE_TYPE.element && !_checkValidNamespace(currentNode)) {
981
1944
  _forceRemove(currentNode);
982
1945
  return true;
983
1946
  }
984
1947
  /* Make sure that older browsers don't get fallback-tag mXSS */
985
- if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(/<\/no(script|embed|frames)/i, currentNode.innerHTML)) {
1948
+ if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(FALLBACK_TAG_CLOSE, currentNode.innerHTML)) {
986
1949
  _forceRemove(currentNode);
987
1950
  return true;
988
1951
  }
989
1952
  /* Sanitize element content to be template-safe */
990
1953
  if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) {
991
1954
  /* Get the element's text content */
992
- content = currentNode.textContent;
993
- arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
994
- content = stringReplace(content, expr, ' ');
995
- });
1955
+ const content = _stripTemplateExpressions(currentNode.textContent);
996
1956
  if (currentNode.textContent !== content) {
997
1957
  arrayPush(DOMPurify.removed, {
998
1958
  element: currentNode.cloneNode()
@@ -1014,31 +1974,96 @@ function createDOMPurify() {
1014
1974
  */
1015
1975
  // eslint-disable-next-line complexity
1016
1976
  const _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {
1977
+ /* FORBID_ATTR must always win, even if ADD_ATTR predicate would allow it */
1978
+ if (FORBID_ATTR[lcName]) {
1979
+ return false;
1980
+ }
1981
+ /* Reject declarative-partial-updates patch-linkage attributes
1982
+ (https://github.com/WICG/declarative-partial-updates).
1983
+ Empirical note (Chrome 150, verified — see
1984
+ test/declarative-patch-probe-v3.html): expansion is NOT applied after
1985
+ sanitization. For the string path it fires during sanitize()'s own
1986
+ parse, so the walk sees and sanitizes the fully materialized expanded
1987
+ tree — teleports into MathML/SVG integration points included; a
1988
+ weaponized `<template for>`->`<img onerror>` comes back with the handler
1989
+ stripped. For the IN_PLACE path it fires on connection, before the walk.
1990
+ Either way DOMPurify is NOT blind to the patch.
1991
+ This removal is therefore defense-in-depth rather than the sole barrier:
1992
+ it prevents live linkage from surviving into the OUTPUT and re-expanding
1993
+ in the caller's context, and keeps behaviour deterministic if a future
1994
+ engine defers expansion. `for` is legitimate only on <label>/<output>;
1995
+ anywhere else (notably <template for>) it links the element to a patch
1996
+ target and teleports or removes an arbitrary DOM range by id/marker name.
1997
+ `patchsrc` fetches remote markup and is treated as a script-loading
1998
+ mechanism (CSP). Gated on SAFE_FOR_XML so the removal groups with the
1999
+ other structural-threat checks and stays overridable, consistent with
2000
+ the rest of the codebase. PI range markers are already removed by
2001
+ _isUnsafeNode. */
2002
+ if (_isPatchLinkageAttribute(lcName, lcTag)) {
2003
+ return false;
2004
+ }
1017
2005
  /* Make sure attribute cannot clobber */
1018
2006
  if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {
1019
2007
  return false;
1020
2008
  }
2009
+ const nameIsPermitted = ALLOWED_ATTR[lcName] || EXTRA_ELEMENT_HANDLING.attributeCheck instanceof Function && EXTRA_ELEMENT_HANDLING.attributeCheck(lcName, lcTag);
1021
2010
  /* Allow valid data-* attributes: At least one character after "-"
1022
2011
  (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
1023
2012
  XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)
1024
2013
  We don't need to check the value; it's always URI safe. */
1025
- 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]) {
1026
- if (
1027
- // First condition does a very basic check if a) it's basically a valid custom element tagname AND
1028
- // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
1029
- // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck
1030
- _isBasicCustomElement(lcTag) && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag)) && (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName) || CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName, lcTag)) ||
1031
- // Alternative, second condition checks if it's an `is`-attribute, AND
1032
- // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
1033
- lcName === 'is' && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(value))) ; else {
1034
- return false;
1035
- }
1036
- /* Check value is safe. First, is attr inert? If so, is safe */
1037
- } 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) {
1038
- return false;
1039
- } else ;
1040
- return true;
2014
+ if (ALLOW_DATA_ATTR && regExpTest(DATA_ATTR$1, lcName)) {
2015
+ return true;
2016
+ }
2017
+ /* Allow valid aria-* attributes, the value is always URI safe */
2018
+ if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR$1, lcName)) {
2019
+ return true;
2020
+ }
2021
+ /* A name outside the allowlist is acceptable on custom-element terms
2022
+ only. The value checks below are intentionally skipped in that case:
2023
+ if the user supplied a tagNameCheck we also allow derived custom
2024
+ elements using the same test, and attributes passing the configured
2025
+ attributeNameCheck are allowed as custom elements define these at
2026
+ their own discretion. */
2027
+ if (!nameIsPermitted) {
2028
+ return (
2029
+ // Condition a) covers a basically valid custom element tag name whose
2030
+ // tag passes the configured tagNameCheck and whose attribute name
2031
+ // passes the configured attributeNameCheck ...
2032
+ _isBasicCustomElement(lcTag) && _matchesNameCheck(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) && _matchesNameCheck(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName, lcTag) ||
2033
+ // Condition b) covers an `is` attribute whose value passes the
2034
+ // configured tagNameCheck while customized built-in elements are
2035
+ // allowed.
2036
+ lcName === 'is' && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && _matchesNameCheck(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value)
2037
+ );
2038
+ }
2039
+ /* Check value is safe. First, is attr inert? If so, is safe */
2040
+ if (URI_SAFE_ATTRIBUTES[lcName]) {
2041
+ return true;
2042
+ }
2043
+ /* Check no script, data or unknown possibly unsafe URI
2044
+ unless we know URI values are safe for that attribute */
2045
+ if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE$1, ''))) {
2046
+ return true;
2047
+ }
2048
+ /* Keep image data URIs alive if src/xlink:href is allowed */
2049
+ /* Further prevent gadget XSS for dynamically built script tags */
2050
+ if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]) {
2051
+ return true;
2052
+ }
2053
+ /* Allow unknown protocols: This provides support for links that
2054
+ are handled by protocol handlers which may be unknown ahead of
2055
+ time, e.g. fb:, spotify: */
2056
+ if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA$1, stringReplace(value, ATTR_WHITESPACE$1, ''))) {
2057
+ return true;
2058
+ }
2059
+ /* Only an empty (binary) value remains safe at this point;
2060
+ anything else is presumed unsafe, do not add it back */
2061
+ return !value;
1041
2062
  };
2063
+ /* Names the HTML spec reserves from valid-custom-element-name; these must
2064
+ * never be treated as basic custom elements even when a permissive
2065
+ * CUSTOM_ELEMENT_HANDLING.tagNameCheck is configured. */
2066
+ 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']);
1042
2067
  /**
1043
2068
  * _isBasicCustomElement
1044
2069
  * checks if at least one dash is included in tagName, and it's not the first char
@@ -1048,7 +2073,75 @@ function createDOMPurify() {
1048
2073
  * @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false.
1049
2074
  */
1050
2075
  const _isBasicCustomElement = function _isBasicCustomElement(tagName) {
1051
- return tagName !== 'annotation-xml' && stringMatch(tagName, CUSTOM_ELEMENT);
2076
+ return !RESERVED_CUSTOM_ELEMENT_NAMES[stringToLowerCase(tagName)] && regExpTest(CUSTOM_ELEMENT$1, tagName);
2077
+ };
2078
+ /**
2079
+ * Wrap an attribute value in the matching Trusted Types object when
2080
+ * the active policy requires it. Namespaced attributes pass through
2081
+ * unchanged (no TT support yet, see
2082
+ * https://bugs.chromium.org/p/chromium/issues/detail?id=1305293).
2083
+ *
2084
+ * @param lcTag lowercase tag name of the containing element
2085
+ * @param lcName lowercase attribute name
2086
+ * @param namespaceURI the attribute's namespace, if any
2087
+ * @param value the attribute value to wrap
2088
+ * @return the value, wrapped when Trusted Types demand it
2089
+ */
2090
+ const _applyTrustedTypesToAttribute = function _applyTrustedTypesToAttribute(lcTag, lcName, namespaceURI, value) {
2091
+ if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function' && !namespaceURI) {
2092
+ switch (trustedTypes.getAttributeType(lcTag, lcName)) {
2093
+ case 'TrustedHTML':
2094
+ {
2095
+ return _createTrustedHTML(value);
2096
+ }
2097
+ case 'TrustedScriptURL':
2098
+ {
2099
+ return _createTrustedScriptURL(value);
2100
+ }
2101
+ }
2102
+ }
2103
+ return value;
2104
+ };
2105
+ /**
2106
+ * Write a modified attribute value back onto the element. On
2107
+ * success, re-probe for clobbering introduced by the new value and
2108
+ * remove the element when found; otherwise, when this writeback is the
2109
+ * recreate half of the SANITIZE_NAMED_PROPS remove-and-recreate, pop the
2110
+ * removal entry that path recorded so it does not show as removed. On
2111
+ * failure, remove the attribute instead.
2112
+ *
2113
+ * Returns true only on a clean write (the value was set and the new value
2114
+ * introduced no clobbering). The caller uses that, together with its own
2115
+ * knowledge of whether this attribute pushed a DOMPurify.removed record, to
2116
+ * decide whether to pop that record. The pop must happen ONLY for the
2117
+ * named-prop remove-and-recreate; popping on any other value change (trim,
2118
+ * template scrubbing, Trusted Types) would consume an unrelated _forceRemove
2119
+ * subtree-cleanup record and let that detached subtree keep a live event
2120
+ * handler through the IN_PLACE neutralization pass (SO-001).
2121
+ *
2122
+ * @param currentNode the element carrying the attribute
2123
+ * @param name the attribute name as present on the element
2124
+ * @param namespaceURI the attribute's namespace, if any
2125
+ * @param value the new attribute value
2126
+ * @return true if the value was written without introducing clobbering
2127
+ */
2128
+ const _setAttributeValue = function _setAttributeValue(currentNode, name, namespaceURI, value) {
2129
+ try {
2130
+ if (namespaceURI) {
2131
+ currentNode.setAttributeNS(namespaceURI, name, value);
2132
+ } else {
2133
+ /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
2134
+ currentNode.setAttribute(name, value);
2135
+ }
2136
+ if (_isClobbered(currentNode)) {
2137
+ _forceRemove(currentNode);
2138
+ return false;
2139
+ }
2140
+ return true;
2141
+ } catch (_) {
2142
+ _removeAttribute(name, currentNode);
2143
+ return false;
2144
+ }
1052
2145
  };
1053
2146
  /**
1054
2147
  * _sanitizeAttributes
@@ -1060,16 +2153,18 @@ function createDOMPurify() {
1060
2153
  *
1061
2154
  * @param currentNode to sanitize
1062
2155
  */
2156
+ // eslint-disable-next-line complexity
1063
2157
  const _sanitizeAttributes = function _sanitizeAttributes(currentNode) {
1064
2158
  /* Execute a hook if present */
1065
2159
  _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null);
1066
- const {
1067
- attributes
1068
- } = currentNode;
2160
+ const attributes = currentNode.attributes;
1069
2161
  /* Check if we have attributes; if not we might have a text node */
1070
2162
  if (!attributes || _isClobbered(currentNode)) {
1071
2163
  return;
1072
2164
  }
2165
+ /* Same lazy-install guard as uponSanitizeElement (see there): fork the
2166
+ attribute allowlist off its shared binding before a hook can see it. */
2167
+ ALLOWED_ATTR = _forkSharedAllowlist(hooks.uponSanitizeAttribute, ALLOWED_ATTR, DEFAULT_ALLOWED_ATTR, SET_CONFIG_ALLOWED_ATTR);
1073
2168
  const hookEvent = {
1074
2169
  attrName: '',
1075
2170
  attrValue: '',
@@ -1078,17 +2173,25 @@ function createDOMPurify() {
1078
2173
  forceKeepAttr: undefined
1079
2174
  };
1080
2175
  let l = attributes.length;
2176
+ const lcTag = transformCaseFunc(currentNode.nodeName);
1081
2177
  /* Go backwards over all attributes; safely remove bad ones */
1082
2178
  while (l--) {
1083
2179
  const attr = attributes[l];
1084
- const {
1085
- name,
1086
- namespaceURI,
1087
- value: attrValue
1088
- } = attr;
2180
+ const name = attr.name,
2181
+ namespaceURI = attr.namespaceURI,
2182
+ attrValue = attr.value;
1089
2183
  const lcName = transformCaseFunc(name);
1090
2184
  const initValue = attrValue;
1091
2185
  let value = name === 'value' ? initValue : stringTrim(initValue);
2186
+ /* Tracks whether this specific attribute pushed a DOMPurify.removed
2187
+ record that a later _setAttributeValue() writeback is expected to pop
2188
+ back off (the SANITIZE_NAMED_PROPS remove-and-recreate below is the
2189
+ only path that does). A value that merely changed via trim, template
2190
+ scrubbing, or Trusted Types pushes no such record, so its writeback
2191
+ must NOT pop — otherwise it consumes an unrelated _forceRemove subtree
2192
+ record and that detached subtree escapes the IN_PLACE handler-
2193
+ neutralization pass (SO-001). */
2194
+ let recreatedNamedProp = false;
1092
2195
  /* Execute a hook if present */
1093
2196
  hookEvent.attrName = lcName;
1094
2197
  hookEvent.attrValue = value;
@@ -1099,81 +2202,61 @@ function createDOMPurify() {
1099
2202
  /* Full DOM Clobbering protection via namespace isolation,
1100
2203
  * Prefix id and name attributes with `user-content-`
1101
2204
  */
1102
- if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name')) {
2205
+ if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name') && stringIndexOf(value, SANITIZE_NAMED_PROPS_PREFIX) !== 0) {
1103
2206
  // Remove the attribute with this value
1104
- _removeAttribute(name, currentNode);
2207
+ _removeAttribute(name, currentNode, attr);
1105
2208
  // Prefix the value and later re-create the attribute with the sanitized value
1106
2209
  value = SANITIZE_NAMED_PROPS_PREFIX + value;
2210
+ // This attribute owns the record just pushed; its recreate writeback
2211
+ // is the one allowed to pop it back off.
2212
+ recreatedNamedProp = true;
1107
2213
  }
2214
+ // Else: already prefixed, leave the attribute alone — the prefix is
2215
+ // itself the clobbering protection, and re-applying it is incorrect.
1108
2216
  /* Work around a security issue with comments inside attributes */
1109
- if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\/(style|title|textarea)/i, value)) {
1110
- _removeAttribute(name, currentNode);
2217
+ if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i, value)) {
2218
+ _removeAttribute(name, currentNode, attr);
1111
2219
  continue;
1112
2220
  }
1113
2221
  /* Make sure we cannot easily use animated hrefs, even if animations are allowed */
1114
2222
  if (lcName === 'attributename' && stringMatch(value, 'href')) {
1115
- _removeAttribute(name, currentNode);
2223
+ _removeAttribute(name, currentNode, attr);
1116
2224
  continue;
1117
2225
  }
1118
- /* Did the hooks approve of the attribute? */
2226
+ /* Did the hooks force-keep the attribute? */
1119
2227
  if (hookEvent.forceKeepAttr) {
1120
2228
  continue;
1121
2229
  }
1122
2230
  /* Did the hooks approve of the attribute? */
1123
2231
  if (!hookEvent.keepAttr) {
1124
- _removeAttribute(name, currentNode);
2232
+ _removeAttribute(name, currentNode, attr);
1125
2233
  continue;
1126
2234
  }
1127
2235
  /* Work around a security issue in jQuery 3.0 */
1128
- if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) {
1129
- _removeAttribute(name, currentNode);
2236
+ if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(SELF_CLOSING_TAG, value)) {
2237
+ _removeAttribute(name, currentNode, attr);
1130
2238
  continue;
1131
2239
  }
1132
2240
  /* Sanitize attribute content to be template-safe */
1133
2241
  if (SAFE_FOR_TEMPLATES) {
1134
- arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
1135
- value = stringReplace(value, expr, ' ');
1136
- });
2242
+ value = _stripTemplateExpressions(value);
1137
2243
  }
1138
2244
  /* Is `value` valid for this attribute? */
1139
- const lcTag = transformCaseFunc(currentNode.nodeName);
1140
2245
  if (!_isValidAttribute(lcTag, lcName, value)) {
1141
- _removeAttribute(name, currentNode);
2246
+ _removeAttribute(name, currentNode, attr);
1142
2247
  continue;
1143
2248
  }
1144
2249
  /* Handle attributes that require Trusted Types */
1145
- if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function') {
1146
- if (namespaceURI) ; else {
1147
- switch (trustedTypes.getAttributeType(lcTag, lcName)) {
1148
- case 'TrustedHTML':
1149
- {
1150
- value = trustedTypesPolicy.createHTML(value);
1151
- break;
1152
- }
1153
- case 'TrustedScriptURL':
1154
- {
1155
- value = trustedTypesPolicy.createScriptURL(value);
1156
- break;
1157
- }
1158
- }
1159
- }
1160
- }
2250
+ value = _applyTrustedTypesToAttribute(lcTag, lcName, namespaceURI, value);
1161
2251
  /* Handle invalid data-* attribute set by try-catching it */
1162
2252
  if (value !== initValue) {
1163
- try {
1164
- if (namespaceURI) {
1165
- currentNode.setAttributeNS(namespaceURI, name, value);
1166
- } else {
1167
- /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
1168
- currentNode.setAttribute(name, value);
1169
- }
1170
- if (_isClobbered(currentNode)) {
1171
- _forceRemove(currentNode);
1172
- } else {
1173
- arrayPop(DOMPurify.removed);
1174
- }
1175
- } catch (_) {
1176
- _removeAttribute(name, currentNode);
2253
+ const cleanWrite = _setAttributeValue(currentNode, name, namespaceURI, value);
2254
+ /* Only the named-prop remove-and-recreate owns a DOMPurify.removed
2255
+ record to pop; a plain trim/template/Trusted-Types writeback owns
2256
+ none, so popping here would drop an unrelated subtree's cleanup
2257
+ record (SO-001). */
2258
+ if (cleanWrite && recreatedNamedProp) {
2259
+ arrayPop(DOMPurify.removed);
1177
2260
  }
1178
2261
  }
1179
2262
  }
@@ -1185,7 +2268,7 @@ function createDOMPurify() {
1185
2268
  *
1186
2269
  * @param fragment to iterate over recursively
1187
2270
  */
1188
- const _sanitizeShadowDOM = function _sanitizeShadowDOM(fragment) {
2271
+ const _sanitizeShadowDOM2 = function _sanitizeShadowDOM(fragment) {
1189
2272
  let shadowNode = null;
1190
2273
  const shadowIterator = _createNodeIterator(fragment);
1191
2274
  /* Execute a hook if present */
@@ -1194,17 +2277,135 @@ function createDOMPurify() {
1194
2277
  /* Execute a hook if present */
1195
2278
  _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null);
1196
2279
  /* Sanitize tags and elements */
1197
- _sanitizeElements(shadowNode);
2280
+ _sanitizeElements(shadowNode, fragment);
1198
2281
  /* Check attributes next */
1199
2282
  _sanitizeAttributes(shadowNode);
1200
- /* Deep shadow DOM detected */
1201
- if (shadowNode.content instanceof DocumentFragment) {
1202
- _sanitizeShadowDOM(shadowNode.content);
2283
+ /* Deep shadow DOM detected.
2284
+ Realm-safe check (GHSA-hpcv-96wg-7vj8): use nodeType against the
2285
+ DOCUMENT_FRAGMENT_NODE constant rather than instanceof, so we
2286
+ recurse into <template>.content from foreign realms too. */
2287
+ if (_isDocumentFragment(shadowNode.content)) {
2288
+ _sanitizeShadowDOM2(shadowNode.content);
2289
+ }
2290
+ /* An element iterated here may itself host an attached
2291
+ shadow root. The default NodeIterator does not enter shadow
2292
+ trees, so a shadow root nested inside template.content was
2293
+ previously reached by no walk at all (the pre-pass at
2294
+ _sanitizeAttachedShadowRoots descends via childNodes, which
2295
+ doesn't enter template.content; the template-content recursion
2296
+ above iterates the content but never inspected shadowRoot).
2297
+ Walk it explicitly. The nodeType guard avoids reading
2298
+ shadowRoot off text / comment / CDATA / PI nodes that the
2299
+ iterator also surfaces. */
2300
+ if (_readNodeType(shadowNode) === NODE_TYPE.element) {
2301
+ const innerSr = getShadowRoot(shadowNode);
2302
+ if (_isDocumentFragment(innerSr)) {
2303
+ _sanitizeAttachedShadowRoots(innerSr);
2304
+ _sanitizeShadowDOM2(innerSr);
2305
+ }
1203
2306
  }
1204
2307
  }
1205
2308
  /* Execute a hook if present */
1206
2309
  _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null);
1207
2310
  };
2311
+ /**
2312
+ * _sanitizeAttachedShadowRoots
2313
+ *
2314
+ * Walks `root` and feeds every attached shadow root we encounter into
2315
+ * the existing _sanitizeShadowDOM pipeline. The default node iterator
2316
+ * does not descend into shadow trees, so nodes inside an attached
2317
+ * shadow root would otherwise be skipped entirely.
2318
+ *
2319
+ * Two real input paths put attached shadow roots in front of us:
2320
+ * 1. IN_PLACE on a DOM node that already has shadow roots attached.
2321
+ * 2. DOM-node input where importNode(dirty, true) deep-clones the
2322
+ * shadow root because it was created with `clonable: true`.
2323
+ *
2324
+ * This pass runs once, up front, so the main iteration loop (and the
2325
+ * existing _sanitizeShadowDOM template-content recursion) stay
2326
+ * untouched — string-input paths are not affected.
2327
+ *
2328
+ * @param root the subtree root to walk for attached shadow roots
2329
+ */
2330
+ const _sanitizeAttachedShadowRoots = function _sanitizeAttachedShadowRoots(root) {
2331
+ /* Iterative (explicit stack) rather than per-child recursion. DOM APIs
2332
+ impose no depth cap, so an attacker-shaped tree (JSON/CRDT/editor data
2333
+ built straight into the DOM — the IN_PLACE surface) deeper than the JS
2334
+ call-stack budget would otherwise overflow native recursion here and
2335
+ throw at the IN_PLACE entry pre-pass, before a single node is
2336
+ sanitized, leaving the caller's live tree untouched (fail-open). See
2337
+ campaign-3 F4. A heap stack keeps depth off the call stack.
2338
+ Each work item is either a node to descend into, or a deferred
2339
+ `_sanitizeShadowDOM` for an already-walked shadow root. The deferred
2340
+ form preserves the original post-order discipline: a shadow root's
2341
+ nested shadow roots are discovered before the outer shadow is
2342
+ sanitized (which may remove hosts). Pushes are in reverse of the
2343
+ desired processing order (LIFO): template content, then children, then
2344
+ the shadow-sanitize, then the shadow walk — so the order matches the
2345
+ previous recursion exactly. */
2346
+ const stack = [{
2347
+ node: root,
2348
+ shadow: null
2349
+ }];
2350
+ while (stack.length > 0) {
2351
+ const item = stack.pop();
2352
+ /* Deferred shadow-DOM sanitisation: runs after its subtree was walked. */
2353
+ if (item.shadow) {
2354
+ _sanitizeShadowDOM2(item.shadow);
2355
+ continue;
2356
+ }
2357
+ const node = item.node;
2358
+ const nodeType = _readNodeType(node);
2359
+ const isElement = nodeType === NODE_TYPE.element;
2360
+ /* (pushed last → processed first) Children, snapshotted in reverse so
2361
+ the first child is processed first. Snapshotting matters because a
2362
+ hook may detach siblings mid-walk. */
2363
+ const childNodes = getChildNodes(node);
2364
+ if (childNodes) {
2365
+ for (let i = childNodes.length - 1; i >= 0; --i) {
2366
+ stack.push({
2367
+ node: childNodes[i],
2368
+ shadow: null
2369
+ });
2370
+ }
2371
+ }
2372
+ /* (pushed before children → processed after them, matching the old
2373
+ "template content last" order) When the node is a <template>,
2374
+ descend into its content. */
2375
+ if (isElement) {
2376
+ const rootName = getNodeName ? getNodeName(node) : null;
2377
+ if (typeof rootName === 'string' && transformCaseFunc(rootName) === 'template') {
2378
+ const content = node.content;
2379
+ if (_isDocumentFragment(content)) {
2380
+ stack.push({
2381
+ node: content,
2382
+ shadow: null
2383
+ });
2384
+ }
2385
+ }
2386
+ }
2387
+ /* Shadow root (processed first): walk its subtree, then sanitise it.
2388
+ Realm-safe check (GHSA-hpcv-96wg-7vj8): nodeType-based detection
2389
+ rather than `instanceof DocumentFragment`, which is realm-bound and
2390
+ silently skipped foreign-realm shadow roots (e.g.
2391
+ iframe.contentDocument attachShadow). */
2392
+ if (isElement) {
2393
+ const sr = getShadowRoot(node);
2394
+ if (_isDocumentFragment(sr)) {
2395
+ /* Push the deferred sanitise first so it pops after the shadow
2396
+ walk we push next, i.e. nested shadow roots are discovered
2397
+ before this one is sanitised. */
2398
+ stack.push({
2399
+ node: null,
2400
+ shadow: sr
2401
+ }, {
2402
+ node: sr,
2403
+ shadow: null
2404
+ });
2405
+ }
2406
+ }
2407
+ }
2408
+ };
1208
2409
  // eslint-disable-next-line complexity
1209
2410
  DOMPurify.sanitize = function (dirty) {
1210
2411
  let cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
@@ -1221,13 +2422,9 @@ function createDOMPurify() {
1221
2422
  }
1222
2423
  /* Stringify, in case dirty is an object */
1223
2424
  if (typeof dirty !== 'string' && !_isNode(dirty)) {
1224
- if (typeof dirty.toString === 'function') {
1225
- dirty = dirty.toString();
1226
- if (typeof dirty !== 'string') {
1227
- throw typeErrorCreate('dirty is not a string, aborting');
1228
- }
1229
- } else {
1230
- throw typeErrorCreate('toString is not a function');
2425
+ dirty = stringifyValue(dirty);
2426
+ if (typeof dirty !== 'string') {
2427
+ throw typeErrorCreate('dirty is not a string, aborting');
1231
2428
  }
1232
2429
  }
1233
2430
  /* Return dirty HTML if DOMPurify cannot run */
@@ -1235,24 +2432,90 @@ function createDOMPurify() {
1235
2432
  return dirty;
1236
2433
  }
1237
2434
  /* Assign config vars */
1238
- if (!SET_CONFIG) {
2435
+ if (SET_CONFIG) {
2436
+ /* Persistent setConfig() path: _parseConfig is skipped, so the sets are
2437
+ * not re-derived per call. Restore them from the pristine bindings
2438
+ * captured at setConfig() time so a previous call's hook clone (mutated
2439
+ * below) does not carry over. */
2440
+ ALLOWED_TAGS = SET_CONFIG_ALLOWED_TAGS;
2441
+ ALLOWED_ATTR = SET_CONFIG_ALLOWED_ATTR;
2442
+ } else {
1239
2443
  _parseConfig(cfg);
1240
2444
  }
2445
+ /* Clone the hook-mutable allowlists before the walk whenever an
2446
+ * uponSanitize* hook is registered. The hook event exposes ALLOWED_TAGS
2447
+ * and ALLOWED_ATTR by reference (as allowedTags / allowedAttributes), so
2448
+ * a hook that widens them would otherwise mutate the shared set
2449
+ * permanently: across later calls and across every element. Cloning per
2450
+ * walk keeps documented in-call widening working while scoping it to the
2451
+ * call. A single guard for both config paths - the per-call path rebinds
2452
+ * the sets in _parseConfig each call, the persistent path restores them
2453
+ * from the captured bindings just above - so the two cannot diverge. */
2454
+ if (hooks.uponSanitizeElement.length > 0 || hooks.uponSanitizeAttribute.length > 0) {
2455
+ ALLOWED_TAGS = clone(ALLOWED_TAGS);
2456
+ }
2457
+ if (hooks.uponSanitizeAttribute.length > 0) {
2458
+ ALLOWED_ATTR = clone(ALLOWED_ATTR);
2459
+ }
1241
2460
  /* Clean up removed elements */
1242
2461
  DOMPurify.removed = [];
1243
- /* Check if dirty is correctly typed for IN_PLACE */
1244
- if (typeof dirty === 'string') {
1245
- IN_PLACE = false;
1246
- }
1247
- if (IN_PLACE) {
1248
- /* Do some early pre-sanitization to avoid unsafe root nodes */
1249
- if (dirty.nodeName) {
1250
- const tagName = transformCaseFunc(dirty.nodeName);
2462
+ /* Resolve IN_PLACE for this call without mutating persistent config.
2463
+ Writing the IN_PLACE closure variable here leaks under setConfig(),
2464
+ where _parseConfig is skipped on later calls: a single string call would
2465
+ disable in-place mode for every subsequent node call, returning a
2466
+ sanitized copy while leaving the caller's node — which in-place callers
2467
+ keep using and whose return value they ignore unsanitized. REPORT-2. */
2468
+ const inPlace = IN_PLACE && typeof dirty !== 'string' && _isNode(dirty);
2469
+ if (inPlace) {
2470
+ /* Declarative-partial-updates / streaming pre-pass: sever every patch
2471
+ linkage across the live tree BEFORE the walk, so no patch can fire
2472
+ mid-walk and inject into an already-processed region. Runs first, so
2473
+ it also covers the forbidden/clobbered roots that throw below. */
2474
+ _neutralizePatchLinkage(dirty);
2475
+ /* Do some early pre-sanitization to avoid unsafe root nodes.
2476
+ Read nodeName through the cached prototype getter — a clobbering
2477
+ child named "nodeName" on the form root would otherwise shadow
2478
+ the property and let this check skip the root-allowlist
2479
+ validation entirely. */
2480
+ const nn = _readNodeName(dirty);
2481
+ if (typeof nn === 'string') {
2482
+ const tagName = transformCaseFunc(nn);
1251
2483
  if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
2484
+ /* Fail closed on a live root: neutralize handlers/children before
2485
+ throwing, exactly as the mid-walk abort path does. */
2486
+ _neutralizeRoot(dirty);
1252
2487
  throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');
1253
2488
  }
1254
2489
  }
1255
- } else if (dirty instanceof Node) {
2490
+ /* Pre-flight the root through _isClobbered. The iterator-driven
2491
+ removal path can not detach a parent-less root: _forceRemove
2492
+ falls through to Element.prototype.remove(), which per spec
2493
+ is a no-op on a node with no parent. A clobbered root would
2494
+ then survive the main loop with its attributes uninspected,
2495
+ because _sanitizeAttributes early-returns on _isClobbered. The
2496
+ result would be an attacker-controlled form, complete with any
2497
+ event-handler attributes the caller passed in, handed back to
2498
+ the application unsanitized. Refuse to sanitize such a root
2499
+ the same way we refuse a forbidden tag. GHSA-r47g-fvhr-h676. */
2500
+ if (_isClobbered(dirty)) {
2501
+ /* Fail closed on a live clobbered root before throwing.
2502
+ _neutralizeRoot's reads are clobber-safe (cached getters); the
2503
+ form's non-clobbered descendants, e.g. an armed <img>, are scrubbed. */
2504
+ _neutralizeRoot(dirty);
2505
+ throw typeErrorCreate('root node is clobbered and cannot be sanitized in-place');
2506
+ }
2507
+ /* Sanitize attached shadow roots before the main iterator runs.
2508
+ The iterator does not descend into shadow trees. Same fail-closed
2509
+ barrier as the main walk (campaign-3 F2): a custom-element reaction
2510
+ inside a shadow root could abort this pre-pass before the walk runs,
2511
+ which would otherwise leave the entire live tree unsanitized. */
2512
+ try {
2513
+ _sanitizeAttachedShadowRoots(dirty);
2514
+ } catch (error) {
2515
+ _neutralizeRoot(dirty);
2516
+ throw error;
2517
+ }
2518
+ } else if (_isNode(dirty)) {
1256
2519
  /* If dirty is a DOM element, append to an empty document to avoid
1257
2520
  elements being stripped by the parser */
1258
2521
  body = _initDocument('<!---->');
@@ -1266,12 +2529,25 @@ function createDOMPurify() {
1266
2529
  // eslint-disable-next-line unicorn/prefer-dom-node-append
1267
2530
  body.appendChild(importedNode);
1268
2531
  }
2532
+ /* Clonable shadow roots are deep-cloned by importNode(); sanitize
2533
+ them before the main iterator runs, since the iterator does not
2534
+ descend into shadow trees. The walk routes every read through a
2535
+ cached prototype getter so clobbering descendants on a form root
2536
+ cannot hide a shadow host from this pass.
2537
+ Traverse from `body`, not `importedNode`: when importedNode is a
2538
+ DocumentFragment, the appendChild() above moves its children into
2539
+ `body` and leaves the fragment empty, so walking importedNode would
2540
+ scan nothing and miss every attached shadow host now under `body`
2541
+ (SO-003). In the BODY/HTML branches `body === importedNode`, so this
2542
+ is equivalent there; in the element branch `body` contains the
2543
+ appended element and its descendants. `body` covers all three. */
2544
+ _sanitizeAttachedShadowRoots(body);
1269
2545
  } else {
1270
2546
  /* Exit directly if we have nothing to do */
1271
2547
  if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT &&
1272
2548
  // eslint-disable-next-line unicorn/prefer-includes
1273
2549
  dirty.indexOf('<') === -1) {
1274
- return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;
2550
+ return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? _createTrustedHTML(dirty) : dirty;
1275
2551
  }
1276
2552
  /* Initialize the document to work on */
1277
2553
  body = _initDocument(dirty);
@@ -1285,24 +2561,72 @@ function createDOMPurify() {
1285
2561
  _forceRemove(body.firstChild);
1286
2562
  }
1287
2563
  /* Get node iterator */
1288
- const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body);
1289
- /* Now start iterating over the created document */
1290
- while (currentNode = nodeIterator.nextNode()) {
1291
- /* Sanitize tags and elements */
1292
- _sanitizeElements(currentNode);
1293
- /* Check attributes next */
1294
- _sanitizeAttributes(currentNode);
1295
- /* Shadow DOM detected, sanitize it */
1296
- if (currentNode.content instanceof DocumentFragment) {
1297
- _sanitizeShadowDOM(currentNode.content);
2564
+ const walkRoot = inPlace ? dirty : body;
2565
+ /* Now start iterating over the created document.
2566
+ The walk runs inside an exception barrier (campaign-3 F2): a re-entrant
2567
+ engine/custom-element mutation can detach a node mid-walk so
2568
+ `_forceRemove`'s parentless guard throws, aborting the loop. Without the
2569
+ barrier the caller's in-place tree would be left half-sanitized with the
2570
+ unvisited tail still armed. _createNodeIterator itself is inside the
2571
+ barrier too: constructing the iterator dereferences the root's document,
2572
+ and any failure there (e.g. an exotic/clobbered root) must still fail
2573
+ closed rather than skip the neutralize. On any throw we fail closed -
2574
+ strip the in-place root bare - then rethrow so the existing throw
2575
+ contract is preserved. (String/DOM-copy paths never return the partial
2576
+ body, so the propagating throw is already fail-closed there.) */
2577
+ try {
2578
+ const nodeIterator = _createNodeIterator(walkRoot);
2579
+ while (currentNode = nodeIterator.nextNode()) {
2580
+ /* Sanitize tags and elements */
2581
+ _sanitizeElements(currentNode, walkRoot);
2582
+ /* Check attributes next */
2583
+ _sanitizeAttributes(currentNode);
2584
+ /* Shadow DOM detected, sanitize it.
2585
+ Realm-safe check (GHSA-hpcv-96wg-7vj8): nodeType-based detection
2586
+ instead of instanceof, so foreign-realm <template>.content is
2587
+ walked correctly. */
2588
+ if (_isDocumentFragment(currentNode.content)) {
2589
+ _sanitizeShadowDOM2(currentNode.content);
2590
+ }
2591
+ }
2592
+ } catch (error) {
2593
+ if (inPlace) {
2594
+ _neutralizeRoot(dirty);
2595
+ /* Nodes _forceRemove'd earlier in the aborted walk are already
2596
+ detached from the root, so _neutralizeRoot's subtree pass does not
2597
+ reach them. Defuse them too, mirroring the success-path loop below. */
2598
+ arrayForEach(DOMPurify.removed, entry => {
2599
+ if (entry.element) {
2600
+ _neutralizeSubtree(entry.element);
2601
+ }
2602
+ });
1298
2603
  }
2604
+ throw error;
1299
2605
  }
1300
2606
  /* If we sanitized `dirty` in-place, return it. */
1301
- if (IN_PLACE) {
2607
+ if (inPlace) {
2608
+ /* Fail-closed completion of the audit-5 F1 fix: every node removed from
2609
+ the caller's live tree is detached but may still hold a queued
2610
+ resource-event handler that fires in page scope after we return. The
2611
+ move-hoist covers only disallowed-tag KEEP_CONTENT removals; strip the
2612
+ non-allow-listed attributes off every other removed subtree (clobber,
2613
+ mXSS, namespace, comments, KEEP_CONTENT:false, …) so those handlers are
2614
+ cancelled before any event can fire. Runs synchronously, pre-return. */
2615
+ arrayForEach(DOMPurify.removed, entry => {
2616
+ if (entry.element) {
2617
+ _neutralizeSubtree(entry.element);
2618
+ }
2619
+ });
2620
+ if (SAFE_FOR_TEMPLATES) {
2621
+ _scrubTemplateExpressions2(dirty);
2622
+ }
1302
2623
  return dirty;
1303
2624
  }
1304
2625
  /* Return sanitized string or DOM */
1305
2626
  if (RETURN_DOM) {
2627
+ if (SAFE_FOR_TEMPLATES) {
2628
+ _scrubTemplateExpressions2(body);
2629
+ }
1306
2630
  if (RETURN_DOM_FRAGMENT) {
1307
2631
  returnNode = createDocumentFragment.call(body.ownerDocument);
1308
2632
  while (body.firstChild) {
@@ -1331,20 +2655,28 @@ function createDOMPurify() {
1331
2655
  }
1332
2656
  /* Sanitize final string template-safe */
1333
2657
  if (SAFE_FOR_TEMPLATES) {
1334
- arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
1335
- serializedHTML = stringReplace(serializedHTML, expr, ' ');
1336
- });
2658
+ serializedHTML = _stripTemplateExpressions(serializedHTML);
1337
2659
  }
1338
- return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;
2660
+ return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? _createTrustedHTML(serializedHTML) : serializedHTML;
1339
2661
  };
1340
2662
  DOMPurify.setConfig = function () {
1341
2663
  let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1342
2664
  _parseConfig(cfg);
1343
2665
  SET_CONFIG = true;
2666
+ SET_CONFIG_ALLOWED_TAGS = ALLOWED_TAGS;
2667
+ SET_CONFIG_ALLOWED_ATTR = ALLOWED_ATTR;
1344
2668
  };
1345
2669
  DOMPurify.clearConfig = function () {
1346
2670
  CONFIG = null;
1347
2671
  SET_CONFIG = false;
2672
+ SET_CONFIG_ALLOWED_TAGS = null;
2673
+ SET_CONFIG_ALLOWED_ATTR = null;
2674
+ // Drop any caller-supplied Trusted Types policy so it cannot poison later
2675
+ // `RETURN_TRUSTED_TYPE` output. The internal default policy (cached, and
2676
+ // never recreated — Trusted Types throws on duplicate names) is restored by
2677
+ // the next `_parseConfig`. See GHSA-vxr8-fq34-vvx9.
2678
+ trustedTypesPolicy = defaultTrustedTypesPolicy;
2679
+ emptyHTML = '';
1348
2680
  };
1349
2681
  DOMPurify.isValidAttribute = function (tag, attr, value) {
1350
2682
  /* Initialize shared config vars if necessary. */
@@ -1359,9 +2691,19 @@ function createDOMPurify() {
1359
2691
  if (typeof hookFunction !== 'function') {
1360
2692
  return;
1361
2693
  }
2694
+ /* Reject unknown entry points. Without this, a non-hook key (e.g.
2695
+ * '__proto__') indexes off the prototype chain rather than a real
2696
+ * hook array, and arrayPush then writes to Object.prototype. Guard
2697
+ * with an own-property check against the known hook names. */
2698
+ if (!objectHasOwnProperty(hooks, entryPoint)) {
2699
+ return;
2700
+ }
1362
2701
  arrayPush(hooks[entryPoint], hookFunction);
1363
2702
  };
1364
2703
  DOMPurify.removeHook = function (entryPoint, hookFunction) {
2704
+ if (!objectHasOwnProperty(hooks, entryPoint)) {
2705
+ return undefined;
2706
+ }
1365
2707
  if (hookFunction !== undefined) {
1366
2708
  const index = arrayLastIndexOf(hooks[entryPoint], hookFunction);
1367
2709
  return index === -1 ? undefined : arraySplice(hooks[entryPoint], index, 1)[0];
@@ -1369,6 +2711,9 @@ function createDOMPurify() {
1369
2711
  return arrayPop(hooks[entryPoint]);
1370
2712
  };
1371
2713
  DOMPurify.removeHooks = function (entryPoint) {
2714
+ if (!objectHasOwnProperty(hooks, entryPoint)) {
2715
+ return;
2716
+ }
1372
2717
  hooks[entryPoint] = [];
1373
2718
  };
1374
2719
  DOMPurify.removeAllHooks = function () {
@@ -3805,7 +5150,7 @@ var translations = {
3805
5150
  * @returns {string} html sanitized.
3806
5151
  * @static
3807
5152
  */ static htmlSanitize(html) {
3808
- const annotationRegex = /\<annotation.+\<\/annotation\>/;
5153
+ const annotationRegex = /(<annotation [^>]*>)([\s\S]*?)(<\/annotation>)/i;
3809
5154
  // Get all the annotation content including the tags.
3810
5155
  const annotation = html.match(annotationRegex);
3811
5156
  // Sanitize html code without removing our supported MathML tags and attributes.
@@ -3824,8 +5169,17 @@ var translations = {
3824
5169
  "stackalign"
3825
5170
  ]
3826
5171
  });
3827
- // Readd old annotation content.
3828
- return html.replace(annotationRegex, annotation);
5172
+ if (annotation) {
5173
+ const startTag = annotation[1];
5174
+ const content = annotation[2];
5175
+ const endTag = annotation[3];
5176
+ // Encode strictly <, >, and & to their HTML entities to force the browser to render any HTML as text.
5177
+ const safeContent = content.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
5178
+ const safeAnnotation = startTag + safeContent + endTag;
5179
+ // Re-insert the safely encoded annotation content.
5180
+ html = html.replace(annotationRegex, safeAnnotation);
5181
+ }
5182
+ return html;
3829
5183
  }
3830
5184
  /**
3831
5185
  * Parses a text and replaces all the HTML entities by their characters.
@@ -11295,49 +12649,68 @@ delete Array.prototype.__class__; // @codingStandardsIgnoreEnd
11295
12649
  * @param {String} mathml MathML to update old one or insert
11296
12650
  * @returns {module:engine/model/element~Element} The model element corresponding to the inserted image
11297
12651
  */ insertMathml(mathml) {
11298
- // This returns the value returned by the callback function (writer => {...})
11299
12652
  return this.editorObject.model.change((writer)=>{
11300
- const core = this.getCore();
12653
+ const { isNewElement, temporalImage } = this.getCore().editionProperties;
11301
12654
  const selection = this.editorObject.model.document.selection;
12655
+ const attributes = Object.fromEntries(selection.getAttributes());
11302
12656
  const modelElementNew = writer.createElement("mathml", {
11303
12657
  formula: mathml,
11304
- ...Object.fromEntries(selection.getAttributes())
12658
+ ...attributes
11305
12659
  });
11306
- // Obtain the DOM <span><img ... /></span> object corresponding to the formula
11307
- if (core.editionProperties.isNewElement) {
11308
- // Don't bother inserting anything at all if the MathML is empty.
11309
- if (!mathml) return;
11310
- const viewSelection = this.core.editionProperties.selection || this.editorObject.editing.view.document.selection;
11311
- const modelPosition = this.editorObject.editing.mapper.toModelPosition(viewSelection.getLastPosition());
11312
- this.editorObject.model.insertObject(modelElementNew, modelPosition);
11313
- // Remove selection
11314
- if (!viewSelection.isCollapsed) {
11315
- for (const range of viewSelection.getRanges()){
11316
- const modelRange = this.editorObject.editing.mapper.toModelRange(range);
11317
- const modelSelection = this.editorObject.model.createSelection(modelRange);
11318
- this.editorObject.model.deleteContent(modelSelection);
11319
- }
11320
- }
11321
- // Set carret after the formula
11322
- const position = this.editorObject.model.createPositionAfter(modelElementNew);
11323
- writer.setSelection(position);
11324
- } else {
11325
- const img = core.editionProperties.temporalImage;
11326
- const viewElement = this.editorObject.editing.view.domConverter.domToView(img).parent;
11327
- const modelElementOld = this.editorObject.editing.mapper.toModelElement(viewElement);
11328
- // Insert the new <mathml> and remove the old one
11329
- const position = this.editorObject.model.createPositionBefore(modelElementOld);
11330
- // If the given MathML is empty, don't insert a new formula.
11331
- if (mathml) {
11332
- this.editorObject.model.insertObject(modelElementNew, position);
11333
- }
11334
- this.editorObject.model.deleteContent(this.editorObject.model.createSelection(modelElementOld, 'on'));
12660
+ if (isNewElement) {
12661
+ return this.insertNewFormula(writer, mathml, modelElementNew);
11335
12662
  }
11336
- // eslint-disable-next-line consistent-return
11337
- return modelElementNew;
12663
+ return this.replaceExistingFormula(mathml, modelElementNew, temporalImage);
11338
12664
  });
11339
12665
  }
11340
12666
  /**
12667
+ * Inserts a new formula at the current selection position.
12668
+ */ insertNewFormula(writer, mathml, modelElement) {
12669
+ if (!mathml) {
12670
+ return;
12671
+ }
12672
+ const viewSelection = this.core.editionProperties.selection || this.editorObject.editing.view.document.selection;
12673
+ const modelPosition = this.editorObject.editing.mapper.toModelPosition(viewSelection.getLastPosition());
12674
+ this.editorObject.model.insertObject(modelElement, modelPosition);
12675
+ this.deleteViewSelection(viewSelection);
12676
+ // Set carret after the formula.
12677
+ const position = this.editorObject.model.createPositionAfter(modelElement);
12678
+ writer.setSelection(position);
12679
+ return modelElement;
12680
+ }
12681
+ deleteViewSelection(viewSelection) {
12682
+ if (viewSelection.isCollapsed) {
12683
+ return;
12684
+ }
12685
+ for (const range of viewSelection.getRanges()){
12686
+ const modelRange = this.editorObject.editing.mapper.toModelRange(range);
12687
+ const modelSelection = this.editorObject.model.createSelection(modelRange);
12688
+ this.editorObject.model.deleteContent(modelSelection);
12689
+ }
12690
+ }
12691
+ /**
12692
+ * Replaces an existing formula with updated MathML.
12693
+ */ replaceExistingFormula(mathml, modelElement, temporalImage) {
12694
+ const viewNode = this.editorObject.editing.view.domConverter.domToView(temporalImage);
12695
+ // Check if image exists in view to do standard formula editing
12696
+ if (viewNode?.parent) {
12697
+ const modelElementOld = this.editorObject.editing.mapper.toModelElement(viewNode.parent);
12698
+ // Insert the new <mathml> and remove the old one
12699
+ const position = this.editorObject.model.createPositionBefore(modelElementOld);
12700
+ if (mathml) {
12701
+ this.editorObject.model.insertObject(modelElement, position);
12702
+ }
12703
+ this.editorObject.model.deleteContent(this.editorObject.model.createSelection(modelElementOld, "on"));
12704
+ return modelElement;
12705
+ }
12706
+ // Otherwise it's LaTeX editing, so we insert at current selection
12707
+ if (!mathml) {
12708
+ return;
12709
+ }
12710
+ this.editorObject.model.insertContent(modelElement);
12711
+ return modelElement;
12712
+ }
12713
+ /**
11341
12714
  * Finds the text node corresponding to given DOM text element.
11342
12715
  * @param {element} viewElement Element to find corresponding text node of.
11343
12716
  * @returns {module:engine/model/text~Text|undefined} Text node corresponding to the given element or undefined if it doesn't exist.
@@ -11364,81 +12737,26 @@ delete Array.prototype.__class__; // @codingStandardsIgnoreEnd
11364
12737
  }
11365
12738
  }
11366
12739
  }
11367
- /** @inheritdoc */ insertFormula(focusElement, windowTarget, mathml, wirisProperties) {
12740
+ /** @inheritdoc */ insertFormula(_focusElement, windowTarget, mathml, _wirisProperties) {
11368
12741
  // eslint-disable-line no-unused-vars
11369
12742
  const returnObject = {};
11370
12743
  let mathmlOrigin;
11371
12744
  if (!mathml) {
11372
12745
  this.insertMathml("");
11373
12746
  } else if (this.core.editMode === "latex") {
11374
- returnObject.latex = Latex.getLatexFromMathML(mathml);
11375
- returnObject.node = windowTarget.document.createTextNode(`$$${returnObject.latex}$$`);
11376
- this.editorObject.model.change((writer)=>{
11377
- const { latexRange } = this.core.editionProperties;
11378
- // Add null check for latexRange.
11379
- // When the editor is initialized in a textarea element, latexRange may not be set on initial load.
11380
- // This check ensures formulas can still be inserted by falling back to MathML insertion if latexRange is not available.
11381
- if (!latexRange) {
11382
- // Fallback to regular MathML insertion if latexRange is not available
11383
- this.insertMathml(mathml);
11384
- return;
11385
- }
11386
- const startNode = this.findText(latexRange.startContainer);
11387
- const endNode = this.findText(latexRange.endContainer);
11388
- let startPosition = writer.createPositionAt(startNode.parent, startNode.startOffset + latexRange.startOffset);
11389
- let endPosition = writer.createPositionAt(endNode.parent, endNode.startOffset + latexRange.endOffset);
11390
- let range = writer.createRange(startPosition, endPosition);
11391
- // When Latex is next to image/formula.
11392
- if (latexRange.startContainer.nodeType === 3 && latexRange.startContainer.previousSibling?.nodeType === 1) {
11393
- // Get the position of the latex to be replaced.
11394
- const latexEdited = `$$${Latex.getLatexFromMathML(MathML.safeXmlDecode(this.core.editionProperties.temporalImage.dataset.mathml))}$$`;
11395
- let data = latexRange.startContainer.data;
11396
- // Remove invisible characters.
11397
- data = data.replaceAll(String.fromCharCode(8288), "");
11398
- // Get to the start of the latex we are editing.
11399
- const offset = data.indexOf(latexEdited);
11400
- const dataOffset = data.substring(offset);
11401
- const second$ = dataOffset.substring(2).indexOf("$$") + 4;
11402
- const substring = dataOffset.substr(0, second$);
11403
- data = data.replace(substring, "");
11404
- if (!data) {
11405
- startPosition = writer.createPositionBefore(startNode);
11406
- range = startNode;
11407
- } else {
11408
- startPosition = startPosition = writer.createPositionAt(startNode.parent, startNode.startOffset + offset);
11409
- endPosition = writer.createPositionAt(endNode.parent, endNode.startOffset + second$ + offset);
11410
- range = writer.createRange(startPosition, endPosition);
11411
- }
11412
- }
11413
- const modelSelection = this.editorObject.model.createSelection(range);
11414
- this.editorObject.model.deleteContent(modelSelection);
11415
- writer.insertText(`$$${returnObject.latex}$$`, startNode.getAttributes(), startPosition);
11416
- });
12747
+ this.handleLatexInsertion(returnObject, windowTarget, mathml);
11417
12748
  } else {
11418
- mathmlOrigin = this.core.editionProperties.temporalImage?.dataset.mathml;
11419
- try {
11420
- returnObject.node = this.editorObject.editing.view.domConverter.viewToDom(this.editorObject.editing.mapper.toViewElement(this.insertMathml(mathml)), windowTarget.document);
11421
- } catch (e) {
11422
- const x = e.toString();
11423
- if (x.includes("CKEditorError: Cannot read property 'parent' of undefined")) {
11424
- this.core.modalDialog.cancelAction();
11425
- }
11426
- }
12749
+ mathmlOrigin = this.handleMathmlInsertion(returnObject, windowTarget, mathml);
11427
12750
  }
11428
- // Build the telemeter payload separated to delete null/undefined entries.
11429
12751
  const payload = {
11430
- mathml_origin: mathmlOrigin ? MathML.safeXmlDecode(mathmlOrigin) : mathmlOrigin,
11431
- mathml: mathml ? MathML.safeXmlDecode(mathml) : mathml,
12752
+ mathml: mathml ? MathML.safeXmlDecode(mathml) : undefined,
11432
12753
  elapsed_time: Date.now() - this.core.editionProperties.editionStartTime,
11433
- editor_origin: null,
11434
12754
  toolbar: this.core.modalDialog.contentManager.toolbar,
11435
12755
  size: mathml?.length
11436
12756
  };
11437
- // Remove desired null keys.
11438
- Object.keys(payload).forEach((key)=>{
11439
- if (key === "mathml_origin" || key === "editor_origin") !payload[key] ? delete payload[key] : {};
11440
- });
11441
- // Call Telemetry service to track the event.
12757
+ if (mathmlOrigin) {
12758
+ payload.mathml_origin = MathML.safeXmlDecode(mathmlOrigin);
12759
+ }
11442
12760
  try {
11443
12761
  Telemeter.telemeter.track("INSERTED_FORMULA", {
11444
12762
  ...payload
@@ -11446,15 +12764,312 @@ delete Array.prototype.__class__; // @codingStandardsIgnoreEnd
11446
12764
  } catch (error) {
11447
12765
  console.error("Error tracking INSERTED_FORMULA", error);
11448
12766
  }
11449
- /* Due to PLUGINS-1329, we add the onChange event to the CK4 insertFormula.
11450
- We probably should add it here as well, but we should look further into how */ // this.editorObject.fire('change');
11451
- // Remove temporal image of inserted formula
11452
12767
  this.core.editionProperties.temporalImage = null;
11453
12768
  return returnObject;
11454
12769
  }
12770
+ handleLatexInsertion(returnObject, windowTarget, mathml) {
12771
+ returnObject.latex = Latex.getLatexFromMathML(mathml);
12772
+ returnObject.node = windowTarget.document.createTextNode(`$$${returnObject.latex}$$`);
12773
+ const { latexRange } = this.core.editionProperties;
12774
+ // When latexRange exists (meaning the whole LaTeX was selected or the editor was opened),
12775
+ // find the node contaning the LaTeX and replace it fully.
12776
+ if (latexRange) {
12777
+ const startNode = this.findText(latexRange.startContainer);
12778
+ const endNode = this.findText(latexRange.endContainer);
12779
+ // If nodes found, use standard replacement.
12780
+ if (startNode && endNode) {
12781
+ this.replaceLatexWithNodes(startNode, endNode, latexRange, returnObject.latex);
12782
+ return;
12783
+ }
12784
+ }
12785
+ this.replaceLatexUsingModelSearch(returnObject.latex);
12786
+ }
12787
+ handleMathmlInsertion(returnObject, windowTarget, mathml) {
12788
+ const mathmlOrigin = this.core.editionProperties.temporalImage?.dataset.mathml;
12789
+ try {
12790
+ const modelElement = this.insertMathml(mathml);
12791
+ const viewElement = this.editorObject.editing.mapper.toViewElement(modelElement);
12792
+ returnObject.node = this.editorObject.editing.view.domConverter.viewToDom(viewElement, windowTarget.document);
12793
+ } catch (error) {
12794
+ if (error.toString().includes("Cannot read property 'parent' of undefined")) {
12795
+ this.core.modalDialog.cancelAction();
12796
+ }
12797
+ }
12798
+ return mathmlOrigin;
12799
+ }
11455
12800
  /**
11456
- * Function called when the content submits an action.
11457
- */ notifyWindowClosed() {
12801
+ * Gets selection attributes excluding track changes tags.
12802
+ */ getCleanSelectionAttributes() {
12803
+ const attributes = {};
12804
+ for (const [key, value] of this.editorObject.model.document.selection.getAttributes()){
12805
+ if (!key.startsWith("suggestion:") && !key.startsWith("comment:")) {
12806
+ attributes[key] = value;
12807
+ }
12808
+ }
12809
+ return attributes;
12810
+ }
12811
+ /**
12812
+ * Searches for the original LaTeX in the model and replaces it.
12813
+ * Fallback when findText() cannot locate DOM nodes (like when there are track changes modifications).
12814
+ */ replaceLatexUsingModelSearch(newLatex) {
12815
+ const foundRange = this.findLatexBlockNearSelection();
12816
+ if (foundRange) {
12817
+ this.editorObject.model.change((writer)=>writer.setSelection(foundRange));
12818
+ this.replaceRangeWithLatex(newLatex);
12819
+ } else {
12820
+ // Insert at current position as a last resort.
12821
+ this.editorObject.model.change((writer)=>{
12822
+ const newLatexText = writer.createText(`$$${newLatex}$$`, this.getCleanSelectionAttributes());
12823
+ this.editorObject.model.insertContent(newLatexText);
12824
+ });
12825
+ }
12826
+ this.core.editionProperties.extractedLatex = null;
12827
+ }
12828
+ /**
12829
+ * Checks if a text proxy has a track changes deletion marker.
12830
+ */ isDeletedText(text) {
12831
+ for (const [key, value] of text.getAttributes()){
12832
+ if (key.startsWith("suggestion:") && value === "deletion") {
12833
+ return true;
12834
+ }
12835
+ }
12836
+ return false;
12837
+ }
12838
+ /**
12839
+ * Finds a LaTeX block ($$...$$) near the current selection.
12840
+ * Handles track changes by considering the "accepted" version of text.
12841
+ */ findLatexBlockNearSelection() {
12842
+ const position = this.editorObject.model.document.selection.getFirstPosition();
12843
+ if (!position?.parent) {
12844
+ return;
12845
+ }
12846
+ // Build LaTeX with track changes accepted suggestions, if any.
12847
+ const { textParts, acceptedText } = this.collectTextParts(position.parent);
12848
+ if (!acceptedText.includes("$$")) {
12849
+ return;
12850
+ }
12851
+ // To handle multiple LaTeX on same line.
12852
+ const targetLatex = this.core.editionProperties.extractedLatex;
12853
+ const fullLatex = `$$${targetLatex}$$`;
12854
+ const startIndex = acceptedText.indexOf(fullLatex);
12855
+ if (startIndex === -1) {
12856
+ return;
12857
+ }
12858
+ const latexBoundaries = {
12859
+ start: startIndex,
12860
+ end: startIndex + fullLatex.length
12861
+ };
12862
+ return this.convertAcceptedOffsetsToModelRange(textParts, latexBoundaries);
12863
+ }
12864
+ /**
12865
+ * Collects all text fragments from a paragraph, tracking both model and accepted text positions.
12866
+ * This is necessary to handle track changes where some LaTeX may have suggestions.
12867
+ */ collectTextParts(paragraph) {
12868
+ const textParts = [];
12869
+ let acceptedTextOffset = 0;
12870
+ let acceptedText = "";
12871
+ for (const item of this.editorObject.model.createRangeIn(paragraph).getItems()){
12872
+ if (item.is("$textProxy")) {
12873
+ const isDeleted = this.isDeletedText(item);
12874
+ textParts.push({
12875
+ text: item.data,
12876
+ startOffset: item.startOffset,
12877
+ endOffset: item.startOffset + item.data.length,
12878
+ parent: item.textNode.parent,
12879
+ acceptedStart: isDeleted ? null : acceptedTextOffset,
12880
+ acceptedEnd: isDeleted ? null : acceptedTextOffset + item.data.length,
12881
+ isDeleted
12882
+ });
12883
+ if (!isDeleted) {
12884
+ acceptedText += item.data;
12885
+ acceptedTextOffset += item.data.length;
12886
+ }
12887
+ }
12888
+ }
12889
+ return {
12890
+ textParts,
12891
+ acceptedText
12892
+ };
12893
+ }
12894
+ /**
12895
+ * Converts LaTeX with track changes accepted suggestions to a CKEditor model Range.
12896
+ */ convertAcceptedOffsetsToModelRange(textParts, latexBoundaries) {
12897
+ let startPartIndex = -1, endPartIndex = -1;
12898
+ let startOffsetInPart = 0, endOffsetInPart = 0;
12899
+ // Find which text parts contain the LaTeX block boundaries
12900
+ for(let i = 0; i < textParts.length; i++){
12901
+ const part = textParts[i];
12902
+ if (part.isDeleted) continue;
12903
+ if (startPartIndex === -1 && latexBoundaries.start >= part.acceptedStart && latexBoundaries.start <= part.acceptedEnd) {
12904
+ startPartIndex = i;
12905
+ startOffsetInPart = latexBoundaries.start - part.acceptedStart;
12906
+ }
12907
+ if (latexBoundaries.end >= part.acceptedStart && latexBoundaries.end <= part.acceptedEnd) {
12908
+ endPartIndex = i;
12909
+ endOffsetInPart = latexBoundaries.end - part.acceptedStart;
12910
+ }
12911
+ }
12912
+ if (startPartIndex === -1 || endPartIndex === -1) {
12913
+ return;
12914
+ }
12915
+ // Extend range to include any consecutive deleted parts after the block.
12916
+ let finalEndIndex = endPartIndex;
12917
+ let finalEndOffset = endOffsetInPart;
12918
+ for(let i = endPartIndex + 1; i < textParts.length && textParts[i].isDeleted; i++){
12919
+ finalEndIndex = i;
12920
+ finalEndOffset = textParts[i].text.length;
12921
+ }
12922
+ const startPart = textParts[startPartIndex];
12923
+ const endPart = textParts[finalEndIndex];
12924
+ return this.editorObject.model.createRange(this.editorObject.model.createPositionAt(startPart.parent, startPart.startOffset + startOffsetInPart), this.editorObject.model.createPositionAt(endPart.parent, endPart.startOffset + finalEndOffset));
12925
+ }
12926
+ replaceRangeWithLatex(newLatex) {
12927
+ this.editorObject.model.change((writer)=>{
12928
+ this.editorObject.model.deleteContent(this.editorObject.model.document.selection);
12929
+ const newLatexText = writer.createText(`$$${newLatex}$$`, this.getCleanSelectionAttributes());
12930
+ this.editorObject.model.insertContent(newLatexText);
12931
+ });
12932
+ }
12933
+ /**
12934
+ * Replaces the whole LaTeX in the CKEditor5 model.
12935
+ */ replaceLatexWithNodes(startNode, endNode, latexRange, newLatex) {
12936
+ this.editorObject.model.change((writer)=>{
12937
+ const startOffset = startNode.startOffset + latexRange.startOffset;
12938
+ const endOffset = endNode.startOffset + latexRange.endOffset;
12939
+ let startPosition = writer.createPositionAt(startNode.parent, startOffset);
12940
+ let endPosition = writer.createPositionAt(endNode.parent, endOffset);
12941
+ // Adjust positions when LaTeX is adjacent to a formula.
12942
+ const startContainer = latexRange.startContainer;
12943
+ if (startContainer.nodeType === Node.TEXT_NODE && startContainer.previousSibling?.nodeType === Node.ELEMENT_NODE) {
12944
+ const originalLatex = `$$${Latex.getLatexFromMathML(MathML.safeXmlDecode(this.core.editionProperties.temporalImage.dataset.mathml))}$$`;
12945
+ const textData = startContainer.data.replaceAll(String.fromCodePoint(8288), "");
12946
+ const latexOffset = textData.indexOf(originalLatex);
12947
+ if (latexOffset !== -1) {
12948
+ const closingDelimiterOffset = textData.substring(latexOffset + 2).indexOf("$$") + 4;
12949
+ startPosition = writer.createPositionAt(startNode.parent, startNode.startOffset + latexOffset);
12950
+ endPosition = writer.createPositionAt(endNode.parent, endNode.startOffset + closingDelimiterOffset + latexOffset);
12951
+ }
12952
+ }
12953
+ writer.setSelection(writer.createRange(startPosition, endPosition));
12954
+ });
12955
+ this.replaceRangeWithLatex(newLatex);
12956
+ }
12957
+ /**
12958
+ * Inherited method from IntegrationModel.
12959
+ * Gets the MathML from a text node containing LaTeX.
12960
+ * Handles track changes by simulating "accept all changes" before conversion.
12961
+ */ getMathmlFromTextNode(textNode, caretPosition) {
12962
+ const standardResult = Latex.getLatexFromTextNode(textNode, caretPosition);
12963
+ const acceptedLatex = this.extractAcceptedLatexFromDOM(textNode, caretPosition);
12964
+ // Prioritize accepted LaTeX if it differs from standard extraction (for track changes compatibility).
12965
+ // Important node: use explicit undefined check to allow empty LaTeX strings, otherwise it would not detect $$$$ as valid LaTeX.
12966
+ const latex = acceptedLatex !== undefined && acceptedLatex !== standardResult?.latex ? acceptedLatex : standardResult?.latex;
12967
+ // Do not continue if no LaTeX found by either method.
12968
+ // This is necessary since both parameters can be independently undefined in some edge cases.
12969
+ if (latex === undefined && acceptedLatex === undefined) {
12970
+ return;
12971
+ }
12972
+ // Verify caret is inside LaTeX block for track changes edge cases.
12973
+ if (!standardResult && acceptedLatex !== undefined && !this.isCaretInsideLatexBlock(textNode, caretPosition)) {
12974
+ return;
12975
+ }
12976
+ const finalLatex = latex === undefined ? acceptedLatex : latex;
12977
+ this.storeLatexRangeWithFallback(textNode, caretPosition, finalLatex);
12978
+ return Latex.getMathMLFromLatex(finalLatex);
12979
+ }
12980
+ isCaretInsideLatexBlock(textNode, caretPosition = 0) {
12981
+ // If LaTeX is found, the caret is inside one.
12982
+ return this.extractAcceptedLatexFromDOM(textNode, caretPosition) !== undefined;
12983
+ }
12984
+ /**
12985
+ * Stores the LaTeX range for its replacement later.
12986
+ */ storeLatexRangeWithFallback(textNode, caretPosition, latex) {
12987
+ const parentTag = textNode.parentElement?.tagName?.toLowerCase();
12988
+ if (!textNode.parentElement || parentTag === "textarea") {
12989
+ return;
12990
+ }
12991
+ const latexResult = Latex.getLatexFromTextNode(textNode, caretPosition);
12992
+ if (latexResult) {
12993
+ const range = document.createRange();
12994
+ range.setStart(latexResult.startNode, latexResult.startPosition);
12995
+ range.setEnd(latexResult.endNode, latexResult.endPosition);
12996
+ this.core.editionProperties.latexRange = range;
12997
+ } else {
12998
+ this.core.editionProperties.latexRange = null;
12999
+ }
13000
+ this.core.editionProperties.extractedLatex = latex;
13001
+ }
13002
+ /**
13003
+ * Finds a container element containing a complete LaTeX block.
13004
+ * Necessary for track changes handling, to find the full LaTeX even with the suggestions.
13005
+ */ findLatexContainerElement(textNode) {
13006
+ const MAX_DEPTH = 10; // Prevent excessive loops.
13007
+ let element = textNode.parentElement;
13008
+ for(let i = 0; i < MAX_DEPTH && element; i++){
13009
+ const text = element.textContent || "";
13010
+ const openDelim = text.indexOf("$$");
13011
+ if (openDelim !== -1 && text.includes("$$", openDelim + 2)) {
13012
+ return element;
13013
+ }
13014
+ element = element.parentElement;
13015
+ }
13016
+ return null;
13017
+ }
13018
+ /**
13019
+ * Extracts LaTeX from DOM, skipping track changes deletion markers.
13020
+ */ extractAcceptedLatexFromDOM(textNode, caretPositionInNode = 0) {
13021
+ const container = this.findLatexContainerElement(textNode);
13022
+ if (!container) {
13023
+ return;
13024
+ }
13025
+ const acceptedText = this.getAcceptedTextContent(container);
13026
+ // Calculate caret offset that will be used later to find the correct LaTeX block.
13027
+ // This includes all accepted text before textNode, plus the caret position within textNode.
13028
+ const walker = document.createTreeWalker(container, NodeFilter.SHOW_TEXT);
13029
+ let node = walker.nextNode();
13030
+ let caretOffset = 0;
13031
+ while(node && node !== textNode){
13032
+ if (!node.parentElement?.classList?.contains("ck-suggestion-marker-deletion")) {
13033
+ caretOffset += node.textContent?.length || 0;
13034
+ }
13035
+ node = walker.nextNode();
13036
+ }
13037
+ // Add the caret position within the text node, only if textNode is not deleted by Track Changes.
13038
+ if (node === textNode && !textNode.parentElement?.classList?.contains("ck-suggestion-marker-deletion")) {
13039
+ caretOffset += caretPositionInNode;
13040
+ }
13041
+ // Find the LaTeX block that contains the caret.
13042
+ let nextSearchIndex = 0;
13043
+ while(nextSearchIndex < acceptedText.length){
13044
+ const openDelim = acceptedText.indexOf("$$", nextSearchIndex);
13045
+ if (openDelim === -1) {
13046
+ break;
13047
+ }
13048
+ const closeDelim = acceptedText.indexOf("$$", openDelim + 2);
13049
+ if (closeDelim === -1) {
13050
+ break;
13051
+ }
13052
+ if (caretOffset >= openDelim && caretOffset <= closeDelim + 2) {
13053
+ return acceptedText.substring(openDelim + 2, closeDelim);
13054
+ }
13055
+ nextSearchIndex = closeDelim + 2;
13056
+ }
13057
+ }
13058
+ /**
13059
+ * Recursively extracts text content, skipping track changes tags.
13060
+ */ getAcceptedTextContent(node) {
13061
+ if (node.nodeType === Node.TEXT_NODE) {
13062
+ return node.textContent || "";
13063
+ }
13064
+ if (node.nodeType === Node.ELEMENT_NODE) {
13065
+ if (node.classList?.contains("ck-suggestion-marker-deletion")) {
13066
+ return "";
13067
+ }
13068
+ return Array.from(node.childNodes).map((child)=>this.getAcceptedTextContent(child)).join("");
13069
+ }
13070
+ return "";
13071
+ }
13072
+ /** Called when the modal window is closed. */ notifyWindowClosed() {
11458
13073
  this.editorObject.editing.view.focus();
11459
13074
  }
11460
13075
  }
@@ -11532,7 +13147,7 @@ var mathIcon = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!-- Generator: Adob
11532
13147
 
11533
13148
  var chemIcon = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!-- Generator: Adobe Illustrator 22.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->\n<svg version=\"1.1\" id=\"Layer_1\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" x=\"0px\" y=\"0px\"\n\t viewBox=\"0 0 40.3 49.5\" style=\"enable-background:new 0 0 40.3 49.5;\" xml:space=\"preserve\">\n<style type=\"text/css\">\n\t.st0{fill:#A4CF61;}\n</style>\n<path class=\"st0\" d=\"M39.2,12.1c0-1.9-1.1-3.6-2.7-4.4L24.5,0.9l0,0c-0.7-0.4-1.5-0.6-2.4-0.6c-0.9,0-1.7,0.2-2.4,0.6l0,0L2.3,10.8\n\tl0,0C0.9,11.7,0,13.2,0,14.9h0v19.6h0c0,1.7,0.9,3.3,2.3,4.1l0,0l17.4,9.9l0,0c0.7,0.4,1.5,0.6,2.4,0.6c0.9,0,1.7-0.2,2.4-0.6l0,0\n\tl12.2-6.9h0c1.5-0.8,2.6-2.5,2.6-4.3c0-2.7-2.2-4.9-4.9-4.9c-0.9,0-1.8,0.3-2.5,0.7l0,0l-9.7,5.6l-12.3-7V17.8l12.3-7l9.9,5.7l0,0\n\tc0.7,0.4,1.5,0.6,2.4,0.6C37,17,39.2,14.8,39.2,12.1\"/>\n</svg>\n";
11534
13149
 
11535
- var version = "8.15.1";
13150
+ var version = "8.15.3";
11536
13151
  var packageInfo = {
11537
13152
  version: version};
11538
13153
 
@@ -11884,11 +13499,7 @@ class MathType extends Plugin {
11884
13499
  * we must create a new EmptyElement which is independent of the
11885
13500
  * DataProcessor being used by this editor instance
11886
13501
  */ if (imgElement) {
11887
- return viewWriter.createEmptyElement("img", imgElement.getAttributes(), {
11888
- renderUnsafeAttributes: [
11889
- "src"
11890
- ]
11891
- });
13502
+ return viewWriter.createEmptyElement("img", imgElement.getAttributes());
11892
13503
  }
11893
13504
  return null;
11894
13505
  }
@@ -11986,8 +13597,10 @@ class MathType extends Plugin {
11986
13597
  e.return = MathML.removeSafeXMLSemantics(previewOutput);
11987
13598
  return;
11988
13599
  }
11989
- // In save mode, convert formula images back to clean MathML
11990
- const parsedResult = Parser.endParse(output);
13600
+ // Clean track changes markers only from LaTeX content before converting to MathML.
13601
+ const latexParsedOutput = this._endParseEditModeWithTrackChangesSupport(output);
13602
+ // Convert formula images to MathML. It's important to use the save mode to prevent issues.
13603
+ const parsedResult = Parser.endParseSaveMode(latexParsedOutput);
11991
13604
  // Remove all semantic annotations (including handwritten data points)
11992
13605
  // to ensure clean, standard MathML format for storage
11993
13606
  e.return = MathML.removeSafeXMLSemantics(parsedResult);
@@ -12029,6 +13642,38 @@ class MathType extends Plugin {
12029
13642
  });
12030
13643
  }
12031
13644
  /**
13645
+ * When track changes markers are present inside a LaTeX block:
13646
+ * - The LaTeX is preserved as text (not converted to MathML) to maintain suggestions.
13647
+ * - It also prevents the issue where the suggestions were placed as MathML tags.
13648
+ *
13649
+ * When no track changes markers are inside a LaTeX block:
13650
+ * - The LaTeX is converted to MathML normally. (previous default behavior)
13651
+ *
13652
+ * This is to ensure that:
13653
+ * 1. LaTeX without suggestions gets converted to MathML for final output.
13654
+ * 2. LaTeX with pending suggestions is preserved so setData(getData()) works correctly.
13655
+ */ _endParseEditModeWithTrackChangesSupport(code) {
13656
+ if (!Configuration.get("parseModes").includes("latex")) {
13657
+ return code;
13658
+ }
13659
+ const latexBlockRegex = /\$\$([\s\S]*?)\$\$/g;
13660
+ const trackChangesRegex = /<(suggestion|comment)-(start|end)/i;
13661
+ //TODO: Validate if replace all is needed instead of just replace when it is all implemented.
13662
+ return code.replace(latexBlockRegex, (fullMatch, latexContent)=>{
13663
+ // Check if this LaTeX contains track changes markers to prevent conversion.
13664
+ if (trackChangesRegex.test(latexContent)) {
13665
+ return fullMatch;
13666
+ }
13667
+ // When LaTeX has no suggestion, it can be converted to MathML.
13668
+ const decodedLatex = Util.htmlEntitiesDecode(latexContent);
13669
+ let mathml = Util.htmlSanitize(Latex.getMathMLFromLatex(decodedLatex, true));
13670
+ if (!Configuration.get("saveHandTraces")) {
13671
+ mathml = MathML.removeAnnotation(mathml, "application/json");
13672
+ }
13673
+ return mathml;
13674
+ });
13675
+ }
13676
+ /**
12032
13677
  * Expose the WirisPlugin variable to the window
12033
13678
  */ // eslint-disable-next-line class-methods-use-this
12034
13679
  _exposeWiris() {
@@ -12055,8 +13700,21 @@ class MathType extends Plugin {
12055
13700
  // Adds custom label replacing the default 'mathml'.
12056
13701
  // Handles both singular and plural forms.
12057
13702
  trackChangesEditing.descriptionFactory.registerElementLabel("mathml", (quantity)=>(quantity > 1 ? `${quantity} ` : "") + StringManager.get(quantity > 1 ? "formulas" : "formula", integration?.getLanguage() || "en"));
13703
+ this._registerLatexTrackChangesAdapter(integration);
12058
13704
  }
12059
13705
  }
13706
+ /**
13707
+ * Register a custom adapter for handling LaTeX text changes.
13708
+ * This ensures that LaTeX formulas ($$...$$) are treated as atomic units
13709
+ * when used by the track changes feature and avoid partial edits.
13710
+ */ _registerLatexTrackChangesAdapter(integration) {
13711
+ const { editor } = this;
13712
+ editor.model.document.on("change:data", ()=>{
13713
+ if (integration) {
13714
+ integration._trackChangesEnabled = editor.commands.get("trackChanges")?.value ?? false;
13715
+ }
13716
+ });
13717
+ }
12060
13718
  }
12061
13719
 
12062
13720
  export { CKEditor5Integration, ChemTypeCommand, MathTypeCommand, MathType as default };