dompurify 3.4.2 → 3.4.4

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.
package/dist/purify.js CHANGED
@@ -1,1479 +1,1595 @@
1
- /*! @license DOMPurify 3.4.2 | (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.2/LICENSE */
1
+ /*! @license DOMPurify 3.4.4 | (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.4/LICENSE */
2
2
 
3
3
  (function (global, factory) {
4
- typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
5
- typeof define === 'function' && define.amd ? define(factory) :
6
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.DOMPurify = factory());
4
+ typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
5
+ typeof define === 'function' && define.amd ? define(factory) :
6
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.DOMPurify = factory());
7
7
  })(this, (function () { 'use strict';
8
8
 
9
- const {
10
- entries,
11
- setPrototypeOf,
12
- isFrozen,
13
- getPrototypeOf,
14
- getOwnPropertyDescriptor
15
- } = Object;
16
- let {
17
- freeze,
18
- seal,
19
- create
20
- } = Object; // eslint-disable-line import/no-mutable-exports
21
- let {
22
- apply,
23
- construct
24
- } = typeof Reflect !== 'undefined' && Reflect;
25
- if (!freeze) {
26
- freeze = function freeze(x) {
27
- return x;
28
- };
29
- }
30
- if (!seal) {
31
- seal = function seal(x) {
32
- return x;
33
- };
34
- }
35
- if (!apply) {
36
- apply = function apply(func, thisArg) {
37
- for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
38
- args[_key - 2] = arguments[_key];
9
+ function _arrayLikeToArray(r, a) {
10
+ (null == a || a > r.length) && (a = r.length);
11
+ for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
12
+ return n;
13
+ }
14
+ function _arrayWithHoles(r) {
15
+ if (Array.isArray(r)) return r;
16
+ }
17
+ function _iterableToArrayLimit(r, l) {
18
+ var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
19
+ if (null != t) {
20
+ var e,
21
+ n,
22
+ i,
23
+ u,
24
+ a = [],
25
+ f = true,
26
+ o = false;
27
+ try {
28
+ 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);
29
+ } catch (r) {
30
+ o = true, n = r;
31
+ } finally {
32
+ try {
33
+ if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;
34
+ } finally {
35
+ if (o) throw n;
39
36
  }
40
- return func.apply(thisArg, args);
41
- };
37
+ }
38
+ return a;
42
39
  }
43
- if (!construct) {
44
- construct = function construct(Func) {
45
- for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
46
- args[_key2 - 1] = arguments[_key2];
47
- }
48
- return new Func(...args);
49
- };
40
+ }
41
+ function _nonIterableRest() {
42
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
43
+ }
44
+ function _slicedToArray(r, e) {
45
+ return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
46
+ }
47
+ function _unsupportedIterableToArray(r, a) {
48
+ if (r) {
49
+ if ("string" == typeof r) return _arrayLikeToArray(r, a);
50
+ var t = {}.toString.call(r).slice(8, -1);
51
+ 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;
50
52
  }
51
- const arrayForEach = unapply(Array.prototype.forEach);
52
- const arrayLastIndexOf = unapply(Array.prototype.lastIndexOf);
53
- const arrayPop = unapply(Array.prototype.pop);
54
- const arrayPush = unapply(Array.prototype.push);
55
- const arraySplice = unapply(Array.prototype.splice);
56
- const arrayIsArray = Array.isArray;
57
- const stringToLowerCase = unapply(String.prototype.toLowerCase);
58
- const stringToString = unapply(String.prototype.toString);
59
- const stringMatch = unapply(String.prototype.match);
60
- const stringReplace = unapply(String.prototype.replace);
61
- const stringIndexOf = unapply(String.prototype.indexOf);
62
- const stringTrim = unapply(String.prototype.trim);
63
- const numberToString = unapply(Number.prototype.toString);
64
- const booleanToString = unapply(Boolean.prototype.toString);
65
- const bigintToString = typeof BigInt === 'undefined' ? null : unapply(BigInt.prototype.toString);
66
- const symbolToString = typeof Symbol === 'undefined' ? null : unapply(Symbol.prototype.toString);
67
- const objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty);
68
- const objectToString = unapply(Object.prototype.toString);
69
- const regExpTest = unapply(RegExp.prototype.test);
70
- const typeErrorCreate = unconstruct(TypeError);
71
- /**
72
- * Creates a new function that calls the given function with a specified thisArg and arguments.
73
- *
74
- * @param func - The function to be wrapped and called.
75
- * @returns A new function that calls the given function with a specified thisArg and arguments.
76
- */
77
- function unapply(func) {
78
- return function (thisArg) {
79
- if (thisArg instanceof RegExp) {
80
- thisArg.lastIndex = 0;
81
- }
82
- for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
83
- args[_key3 - 1] = arguments[_key3];
84
- }
85
- return apply(func, thisArg, args);
86
- };
53
+ }
54
+
55
+ const entries = Object.entries,
56
+ setPrototypeOf = Object.setPrototypeOf,
57
+ isFrozen = Object.isFrozen,
58
+ getPrototypeOf = Object.getPrototypeOf,
59
+ getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
60
+ let freeze = Object.freeze,
61
+ seal = Object.seal,
62
+ create = Object.create; // eslint-disable-line import/no-mutable-exports
63
+ let _ref = typeof Reflect !== 'undefined' && Reflect,
64
+ apply = _ref.apply,
65
+ construct = _ref.construct;
66
+ if (!freeze) {
67
+ freeze = function freeze(x) {
68
+ return x;
69
+ };
70
+ }
71
+ if (!seal) {
72
+ seal = function seal(x) {
73
+ return x;
74
+ };
75
+ }
76
+ if (!apply) {
77
+ apply = function apply(func, thisArg) {
78
+ for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
79
+ args[_key - 2] = arguments[_key];
80
+ }
81
+ return func.apply(thisArg, args);
82
+ };
83
+ }
84
+ if (!construct) {
85
+ construct = function construct(Func) {
86
+ for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
87
+ args[_key2 - 1] = arguments[_key2];
88
+ }
89
+ return new Func(...args);
90
+ };
91
+ }
92
+ const arrayForEach = unapply(Array.prototype.forEach);
93
+ const arrayLastIndexOf = unapply(Array.prototype.lastIndexOf);
94
+ const arrayPop = unapply(Array.prototype.pop);
95
+ const arrayPush = unapply(Array.prototype.push);
96
+ const arraySplice = unapply(Array.prototype.splice);
97
+ const arrayIsArray = Array.isArray;
98
+ const stringToLowerCase = unapply(String.prototype.toLowerCase);
99
+ const stringToString = unapply(String.prototype.toString);
100
+ const stringMatch = unapply(String.prototype.match);
101
+ const stringReplace = unapply(String.prototype.replace);
102
+ const stringIndexOf = unapply(String.prototype.indexOf);
103
+ const stringTrim = unapply(String.prototype.trim);
104
+ const numberToString = unapply(Number.prototype.toString);
105
+ const booleanToString = unapply(Boolean.prototype.toString);
106
+ const bigintToString = typeof BigInt === 'undefined' ? null : unapply(BigInt.prototype.toString);
107
+ const symbolToString = typeof Symbol === 'undefined' ? null : unapply(Symbol.prototype.toString);
108
+ const objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty);
109
+ const objectToString = unapply(Object.prototype.toString);
110
+ const regExpTest = unapply(RegExp.prototype.test);
111
+ const typeErrorCreate = unconstruct(TypeError);
112
+ /**
113
+ * Creates a new function that calls the given function with a specified thisArg and arguments.
114
+ *
115
+ * @param func - The function to be wrapped and called.
116
+ * @returns A new function that calls the given function with a specified thisArg and arguments.
117
+ */
118
+ function unapply(func) {
119
+ return function (thisArg) {
120
+ if (thisArg instanceof RegExp) {
121
+ thisArg.lastIndex = 0;
122
+ }
123
+ for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
124
+ args[_key3 - 1] = arguments[_key3];
125
+ }
126
+ return apply(func, thisArg, args);
127
+ };
128
+ }
129
+ /**
130
+ * Creates a new function that constructs an instance of the given constructor function with the provided arguments.
131
+ *
132
+ * @param func - The constructor function to be wrapped and called.
133
+ * @returns A new function that constructs an instance of the given constructor function with the provided arguments.
134
+ */
135
+ function unconstruct(Func) {
136
+ return function () {
137
+ for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
138
+ args[_key4] = arguments[_key4];
139
+ }
140
+ return construct(Func, args);
141
+ };
142
+ }
143
+ /**
144
+ * Add properties to a lookup table
145
+ *
146
+ * @param set - The set to which elements will be added.
147
+ * @param array - The array containing elements to be added to the set.
148
+ * @param transformCaseFunc - An optional function to transform the case of each element before adding to the set.
149
+ * @returns The modified set with added elements.
150
+ */
151
+ function addToSet(set, array) {
152
+ let transformCaseFunc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : stringToLowerCase;
153
+ if (setPrototypeOf) {
154
+ // Make 'in' and truthy checks like Boolean(set.constructor)
155
+ // independent of any properties defined on Object.prototype.
156
+ // Prevent prototype setters from intercepting set as a this value.
157
+ setPrototypeOf(set, null);
87
158
  }
88
- /**
89
- * Creates a new function that constructs an instance of the given constructor function with the provided arguments.
90
- *
91
- * @param func - The constructor function to be wrapped and called.
92
- * @returns A new function that constructs an instance of the given constructor function with the provided arguments.
93
- */
94
- function unconstruct(Func) {
95
- return function () {
96
- for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
97
- args[_key4] = arguments[_key4];
98
- }
99
- return construct(Func, args);
100
- };
159
+ if (!arrayIsArray(array)) {
160
+ return set;
101
161
  }
102
- /**
103
- * Add properties to a lookup table
104
- *
105
- * @param set - The set to which elements will be added.
106
- * @param array - The array containing elements to be added to the set.
107
- * @param transformCaseFunc - An optional function to transform the case of each element before adding to the set.
108
- * @returns The modified set with added elements.
109
- */
110
- function addToSet(set, array) {
111
- let transformCaseFunc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : stringToLowerCase;
112
- if (setPrototypeOf) {
113
- // Make 'in' and truthy checks like Boolean(set.constructor)
114
- // independent of any properties defined on Object.prototype.
115
- // Prevent prototype setters from intercepting set as a this value.
116
- setPrototypeOf(set, null);
117
- }
118
- if (!arrayIsArray(array)) {
119
- return set;
120
- }
121
- let l = array.length;
122
- while (l--) {
123
- let element = array[l];
124
- if (typeof element === 'string') {
125
- const lcElement = transformCaseFunc(element);
126
- if (lcElement !== element) {
127
- // Config presets (e.g. tags.js, attrs.js) are immutable.
128
- if (!isFrozen(array)) {
129
- array[l] = lcElement;
130
- }
131
- element = lcElement;
162
+ let l = array.length;
163
+ while (l--) {
164
+ let element = array[l];
165
+ if (typeof element === 'string') {
166
+ const lcElement = transformCaseFunc(element);
167
+ if (lcElement !== element) {
168
+ // Config presets (e.g. tags.js, attrs.js) are immutable.
169
+ if (!isFrozen(array)) {
170
+ array[l] = lcElement;
132
171
  }
172
+ element = lcElement;
133
173
  }
134
- set[element] = true;
135
174
  }
136
- return set;
175
+ set[element] = true;
137
176
  }
138
- /**
139
- * Clean up an array to harden against CSPP
140
- *
141
- * @param array - The array to be cleaned.
142
- * @returns The cleaned version of the array
143
- */
144
- function cleanArray(array) {
145
- for (let index = 0; index < array.length; index++) {
146
- const isPropertyExist = objectHasOwnProperty(array, index);
147
- if (!isPropertyExist) {
148
- array[index] = null;
149
- }
177
+ return set;
178
+ }
179
+ /**
180
+ * Clean up an array to harden against CSPP
181
+ *
182
+ * @param array - The array to be cleaned.
183
+ * @returns The cleaned version of the array
184
+ */
185
+ function cleanArray(array) {
186
+ for (let index = 0; index < array.length; index++) {
187
+ const isPropertyExist = objectHasOwnProperty(array, index);
188
+ if (!isPropertyExist) {
189
+ array[index] = null;
150
190
  }
151
- return array;
152
191
  }
153
- /**
154
- * Shallow clone an object
155
- *
156
- * @param object - The object to be cloned.
157
- * @returns A new object that copies the original.
158
- */
159
- function clone(object) {
160
- const newObject = create(null);
161
- for (const [property, value] of entries(object)) {
162
- const isPropertyExist = objectHasOwnProperty(object, property);
163
- if (isPropertyExist) {
164
- if (arrayIsArray(value)) {
165
- newObject[property] = cleanArray(value);
166
- } else if (value && typeof value === 'object' && value.constructor === Object) {
167
- newObject[property] = clone(value);
168
- } else {
169
- newObject[property] = value;
170
- }
192
+ return array;
193
+ }
194
+ /**
195
+ * Shallow clone an object
196
+ *
197
+ * @param object - The object to be cloned.
198
+ * @returns A new object that copies the original.
199
+ */
200
+ function clone(object) {
201
+ const newObject = create(null);
202
+ for (const _ref2 of entries(object)) {
203
+ var _ref3 = _slicedToArray(_ref2, 2);
204
+ const property = _ref3[0];
205
+ const value = _ref3[1];
206
+ const isPropertyExist = objectHasOwnProperty(object, property);
207
+ if (isPropertyExist) {
208
+ if (arrayIsArray(value)) {
209
+ newObject[property] = cleanArray(value);
210
+ } else if (value && typeof value === 'object' && value.constructor === Object) {
211
+ newObject[property] = clone(value);
212
+ } else {
213
+ newObject[property] = value;
171
214
  }
172
215
  }
173
- return newObject;
174
216
  }
175
- /**
176
- * Convert non-node values into strings without depending on direct property access.
177
- *
178
- * @param value - The value to stringify.
179
- * @returns A string representation of the provided value.
180
- */
181
- function stringifyValue(value) {
182
- switch (typeof value) {
183
- case 'string':
184
- {
185
- return value;
186
- }
187
- case 'number':
188
- {
189
- return numberToString(value);
190
- }
191
- case 'boolean':
192
- {
193
- return booleanToString(value);
194
- }
195
- case 'bigint':
196
- {
197
- return bigintToString ? bigintToString(value) : '0';
198
- }
199
- case 'symbol':
200
- {
201
- return symbolToString ? symbolToString(value) : 'Symbol()';
202
- }
203
- case 'undefined':
204
- {
217
+ return newObject;
218
+ }
219
+ /**
220
+ * Convert non-node values into strings without depending on direct property access.
221
+ *
222
+ * @param value - The value to stringify.
223
+ * @returns A string representation of the provided value.
224
+ */
225
+ function stringifyValue(value) {
226
+ switch (typeof value) {
227
+ case 'string':
228
+ {
229
+ return value;
230
+ }
231
+ case 'number':
232
+ {
233
+ return numberToString(value);
234
+ }
235
+ case 'boolean':
236
+ {
237
+ return booleanToString(value);
238
+ }
239
+ case 'bigint':
240
+ {
241
+ return bigintToString ? bigintToString(value) : '0';
242
+ }
243
+ case 'symbol':
244
+ {
245
+ return symbolToString ? symbolToString(value) : 'Symbol()';
246
+ }
247
+ case 'undefined':
248
+ {
249
+ return objectToString(value);
250
+ }
251
+ case 'function':
252
+ case 'object':
253
+ {
254
+ if (value === null) {
205
255
  return objectToString(value);
206
256
  }
207
- case 'function':
208
- case 'object':
209
- {
210
- if (value === null) {
211
- return objectToString(value);
212
- }
213
- const valueAsRecord = value;
214
- const valueToString = lookupGetter(valueAsRecord, 'toString');
215
- if (typeof valueToString === 'function') {
216
- const stringified = valueToString(valueAsRecord);
217
- return typeof stringified === 'string' ? stringified : objectToString(stringified);
218
- }
219
- return objectToString(value);
220
- }
221
- default:
222
- {
223
- return objectToString(value);
257
+ const valueAsRecord = value;
258
+ const valueToString = lookupGetter(valueAsRecord, 'toString');
259
+ if (typeof valueToString === 'function') {
260
+ const stringified = valueToString(valueAsRecord);
261
+ return typeof stringified === 'string' ? stringified : objectToString(stringified);
224
262
  }
225
- }
263
+ return objectToString(value);
264
+ }
265
+ default:
266
+ {
267
+ return objectToString(value);
268
+ }
226
269
  }
227
- /**
228
- * This method automatically checks if the prop is function or getter and behaves accordingly.
229
- *
230
- * @param object - The object to look up the getter function in its prototype chain.
231
- * @param prop - The property name for which to find the getter function.
232
- * @returns The getter function found in the prototype chain or a fallback function.
233
- */
234
- function lookupGetter(object, prop) {
235
- while (object !== null) {
236
- const desc = getOwnPropertyDescriptor(object, prop);
237
- if (desc) {
238
- if (desc.get) {
239
- return unapply(desc.get);
240
- }
241
- if (typeof desc.value === 'function') {
242
- return unapply(desc.value);
243
- }
270
+ }
271
+ /**
272
+ * This method automatically checks if the prop is function or getter and behaves accordingly.
273
+ *
274
+ * @param object - The object to look up the getter function in its prototype chain.
275
+ * @param prop - The property name for which to find the getter function.
276
+ * @returns The getter function found in the prototype chain or a fallback function.
277
+ */
278
+ function lookupGetter(object, prop) {
279
+ while (object !== null) {
280
+ const desc = getOwnPropertyDescriptor(object, prop);
281
+ if (desc) {
282
+ if (desc.get) {
283
+ return unapply(desc.get);
284
+ }
285
+ if (typeof desc.value === 'function') {
286
+ return unapply(desc.value);
244
287
  }
245
- object = getPrototypeOf(object);
246
- }
247
- function fallbackValue() {
248
- return null;
249
288
  }
250
- return fallbackValue;
289
+ object = getPrototypeOf(object);
251
290
  }
252
- function isRegex(value) {
253
- try {
254
- regExpTest(value, '');
255
- return true;
256
- } catch (_unused) {
257
- return false;
258
- }
291
+ function fallbackValue() {
292
+ return null;
259
293
  }
294
+ return fallbackValue;
295
+ }
296
+ function isRegex(value) {
297
+ try {
298
+ regExpTest(value, '');
299
+ return true;
300
+ } catch (_unused) {
301
+ return false;
302
+ }
303
+ }
260
304
 
261
- 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']);
262
- 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']);
263
- const svgFilters = freeze(['feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feDropShadow', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']);
264
- // List of SVG elements that are disallowed by default.
265
- // We still need to know them so that we can do namespace
266
- // checks properly in case one wants to add them to
267
- // allow-list.
268
- const svgDisallowed = freeze(['animate', 'color-profile', 'cursor', 'discard', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'foreignobject', 'hatch', 'hatchpath', 'mesh', 'meshgradient', 'meshpatch', 'meshrow', 'missing-glyph', 'script', 'set', 'solidcolor', 'unknown', 'use']);
269
- const mathMl$1 = freeze(['math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mroot', 'mrow', 'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msup', 'msubsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover', 'mprescripts']);
270
- // Similarly to SVG, we want to know all MathML elements,
271
- // even those that we disallow by default.
272
- const mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);
273
- const text = freeze(['#text']);
274
-
275
- 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']);
276
- 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']);
277
- 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']);
278
- const xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);
305
+ 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', 'selectedcontent', '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']);
306
+ 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']);
307
+ const svgFilters = freeze(['feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feDropShadow', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']);
308
+ // List of SVG elements that are disallowed by default.
309
+ // We still need to know them so that we can do namespace
310
+ // checks properly in case one wants to add them to
311
+ // allow-list.
312
+ const svgDisallowed = freeze(['animate', 'color-profile', 'cursor', 'discard', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'foreignobject', 'hatch', 'hatchpath', 'mesh', 'meshgradient', 'meshpatch', 'meshrow', 'missing-glyph', 'script', 'set', 'solidcolor', 'unknown', 'use']);
313
+ const mathMl$1 = freeze(['math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mroot', 'mrow', 'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msup', 'msubsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover', 'mprescripts']);
314
+ // Similarly to SVG, we want to know all MathML elements,
315
+ // even those that we disallow by default.
316
+ const mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);
317
+ const text = freeze(['#text']);
279
318
 
280
- // eslint-disable-next-line unicorn/better-regex
281
- const MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode
282
- const ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm);
283
- const TMPLIT_EXPR = seal(/\$\{[\w\W]*/gm); // eslint-disable-line unicorn/better-regex
284
- const DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]+$/); // eslint-disable-line no-useless-escape
285
- const ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape
286
- 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
287
- );
288
- const IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i);
289
- const ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g // eslint-disable-line no-control-regex
290
- );
291
- const DOCTYPE_NAME = seal(/^html$/i);
292
- const CUSTOM_ELEMENT = seal(/^[a-z][.\w]*(-[.\w]+)+$/i);
319
+ 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']);
320
+ 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']);
321
+ 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']);
322
+ const xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);
293
323
 
294
- var EXPRESSIONS = /*#__PURE__*/Object.freeze({
295
- __proto__: null,
296
- ARIA_ATTR: ARIA_ATTR,
297
- ATTR_WHITESPACE: ATTR_WHITESPACE,
298
- CUSTOM_ELEMENT: CUSTOM_ELEMENT,
299
- DATA_ATTR: DATA_ATTR,
300
- DOCTYPE_NAME: DOCTYPE_NAME,
301
- ERB_EXPR: ERB_EXPR,
302
- IS_ALLOWED_URI: IS_ALLOWED_URI,
303
- IS_SCRIPT_OR_DATA: IS_SCRIPT_OR_DATA,
304
- MUSTACHE_EXPR: MUSTACHE_EXPR,
305
- TMPLIT_EXPR: TMPLIT_EXPR
306
- });
324
+ const MUSTACHE_EXPR = seal(/{{[\w\W]*|^[\w\W]*}}/g);
325
+ const ERB_EXPR = seal(/<%[\w\W]*|^[\w\W]*%>/g);
326
+ const TMPLIT_EXPR = seal(/\${[\w\W]*/g);
327
+ const DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]+$/); // eslint-disable-line no-useless-escape
328
+ const ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape
329
+ 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
330
+ );
331
+ const IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i);
332
+ const ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g // eslint-disable-line no-control-regex
333
+ );
334
+ const DOCTYPE_NAME = seal(/^html$/i);
335
+ const CUSTOM_ELEMENT = seal(/^[a-z][.\w]*(-[.\w]+)+$/i);
307
336
 
308
- /* eslint-disable @typescript-eslint/indent */
309
- // https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType
310
- const NODE_TYPE = {
311
- element: 1,
312
- text: 3,
313
- // Deprecated
314
- progressingInstruction: 7,
315
- comment: 8,
316
- document: 9};
317
- const getGlobal = function getGlobal() {
318
- return typeof window === 'undefined' ? null : window;
337
+ /* eslint-disable @typescript-eslint/indent */
338
+ // https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType
339
+ const NODE_TYPE = {
340
+ element: 1,
341
+ text: 3,
342
+ // Deprecated
343
+ progressingInstruction: 7,
344
+ comment: 8,
345
+ document: 9};
346
+ const getGlobal = function getGlobal() {
347
+ return typeof window === 'undefined' ? null : window;
348
+ };
349
+ /**
350
+ * Creates a no-op policy for internal use only.
351
+ * Don't export this function outside this module!
352
+ * @param trustedTypes The policy factory.
353
+ * @param purifyHostElement The Script element used to load DOMPurify (to determine policy name suffix).
354
+ * @return The policy created (or null, if Trusted Types
355
+ * are not supported or creating the policy failed).
356
+ */
357
+ const _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, purifyHostElement) {
358
+ if (typeof trustedTypes !== 'object' || typeof trustedTypes.createPolicy !== 'function') {
359
+ return null;
360
+ }
361
+ // Allow the callers to control the unique policy name
362
+ // by adding a data-tt-policy-suffix to the script element with the DOMPurify.
363
+ // Policy creation with duplicate names throws in Trusted Types.
364
+ let suffix = null;
365
+ const ATTR_NAME = 'data-tt-policy-suffix';
366
+ if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) {
367
+ suffix = purifyHostElement.getAttribute(ATTR_NAME);
368
+ }
369
+ const policyName = 'dompurify' + (suffix ? '#' + suffix : '');
370
+ try {
371
+ return trustedTypes.createPolicy(policyName, {
372
+ createHTML(html) {
373
+ return html;
374
+ },
375
+ createScriptURL(scriptUrl) {
376
+ return scriptUrl;
377
+ }
378
+ });
379
+ } catch (_) {
380
+ // Policy creation failed (most likely another DOMPurify script has
381
+ // already run). Skip creating the policy, as this will only cause errors
382
+ // if TT are enforced.
383
+ console.warn('TrustedTypes policy ' + policyName + ' could not be created.');
384
+ return null;
385
+ }
386
+ };
387
+ const _createHooksMap = function _createHooksMap() {
388
+ return {
389
+ afterSanitizeAttributes: [],
390
+ afterSanitizeElements: [],
391
+ afterSanitizeShadowDOM: [],
392
+ beforeSanitizeAttributes: [],
393
+ beforeSanitizeElements: [],
394
+ beforeSanitizeShadowDOM: [],
395
+ uponSanitizeAttribute: [],
396
+ uponSanitizeElement: [],
397
+ uponSanitizeShadowNode: []
319
398
  };
399
+ };
400
+ function createDOMPurify() {
401
+ let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();
402
+ const DOMPurify = root => createDOMPurify(root);
403
+ DOMPurify.version = '3.4.4';
404
+ DOMPurify.removed = [];
405
+ if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document || !window.Element) {
406
+ // Not running in a browser, provide a factory function
407
+ // so that you can pass your own Window
408
+ DOMPurify.isSupported = false;
409
+ return DOMPurify;
410
+ }
411
+ let document = window.document;
412
+ const originalDocument = document;
413
+ const currentScript = originalDocument.currentScript;
414
+ const DocumentFragment = window.DocumentFragment,
415
+ HTMLTemplateElement = window.HTMLTemplateElement,
416
+ Node = window.Node,
417
+ Element = window.Element,
418
+ NodeFilter = window.NodeFilter,
419
+ _window$NamedNodeMap = window.NamedNodeMap,
420
+ NamedNodeMap = _window$NamedNodeMap === void 0 ? window.NamedNodeMap || window.MozNamedAttrMap : _window$NamedNodeMap,
421
+ HTMLFormElement = window.HTMLFormElement,
422
+ DOMParser = window.DOMParser,
423
+ trustedTypes = window.trustedTypes;
424
+ const ElementPrototype = Element.prototype;
425
+ const cloneNode = lookupGetter(ElementPrototype, 'cloneNode');
426
+ const remove = lookupGetter(ElementPrototype, 'remove');
427
+ const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');
428
+ const getChildNodes = lookupGetter(ElementPrototype, 'childNodes');
429
+ const getParentNode = lookupGetter(ElementPrototype, 'parentNode');
430
+ const getNodeType = Node && Node.prototype ? lookupGetter(Node.prototype, 'nodeType') : null;
431
+ // As per issue #47, the web-components registry is inherited by a
432
+ // new document created via createHTMLDocument. As per the spec
433
+ // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)
434
+ // a new empty registry is used when creating a template contents owner
435
+ // document, so we use that as our parent document to ensure nothing
436
+ // is inherited.
437
+ if (typeof HTMLTemplateElement === 'function') {
438
+ const template = document.createElement('template');
439
+ if (template.content && template.content.ownerDocument) {
440
+ document = template.content.ownerDocument;
441
+ }
442
+ }
443
+ let trustedTypesPolicy;
444
+ let emptyHTML = '';
445
+ const _document = document,
446
+ implementation = _document.implementation,
447
+ createNodeIterator = _document.createNodeIterator,
448
+ createDocumentFragment = _document.createDocumentFragment,
449
+ getElementsByTagName = _document.getElementsByTagName;
450
+ const importNode = originalDocument.importNode;
451
+ let hooks = _createHooksMap();
320
452
  /**
321
- * Creates a no-op policy for internal use only.
322
- * Don't export this function outside this module!
323
- * @param trustedTypes The policy factory.
324
- * @param purifyHostElement The Script element used to load DOMPurify (to determine policy name suffix).
325
- * @return The policy created (or null, if Trusted Types
326
- * are not supported or creating the policy failed).
453
+ * Expose whether this browser supports running the full DOMPurify.
327
454
  */
328
- const _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, purifyHostElement) {
329
- if (typeof trustedTypes !== 'object' || typeof trustedTypes.createPolicy !== 'function') {
330
- return null;
331
- }
332
- // Allow the callers to control the unique policy name
333
- // by adding a data-tt-policy-suffix to the script element with the DOMPurify.
334
- // Policy creation with duplicate names throws in Trusted Types.
335
- let suffix = null;
336
- const ATTR_NAME = 'data-tt-policy-suffix';
337
- if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) {
338
- suffix = purifyHostElement.getAttribute(ATTR_NAME);
339
- }
340
- const policyName = 'dompurify' + (suffix ? '#' + suffix : '');
341
- try {
342
- return trustedTypes.createPolicy(policyName, {
343
- createHTML(html) {
344
- return html;
345
- },
346
- createScriptURL(scriptUrl) {
347
- return scriptUrl;
348
- }
349
- });
350
- } catch (_) {
351
- // Policy creation failed (most likely another DOMPurify script has
352
- // already run). Skip creating the policy, as this will only cause errors
353
- // if TT are enforced.
354
- console.warn('TrustedTypes policy ' + policyName + ' could not be created.');
355
- return null;
455
+ DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNode === 'function' && implementation && implementation.createHTMLDocument !== undefined;
456
+ const MUSTACHE_EXPR$1 = MUSTACHE_EXPR,
457
+ ERB_EXPR$1 = ERB_EXPR,
458
+ TMPLIT_EXPR$1 = TMPLIT_EXPR,
459
+ DATA_ATTR$1 = DATA_ATTR,
460
+ ARIA_ATTR$1 = ARIA_ATTR,
461
+ IS_SCRIPT_OR_DATA$1 = IS_SCRIPT_OR_DATA,
462
+ ATTR_WHITESPACE$1 = ATTR_WHITESPACE,
463
+ CUSTOM_ELEMENT$1 = CUSTOM_ELEMENT;
464
+ let IS_ALLOWED_URI$1 = IS_ALLOWED_URI;
465
+ /**
466
+ * We consider the elements and attributes below to be safe. Ideally
467
+ * don't add any new ones but feel free to remove unwanted ones.
468
+ */
469
+ /* allowed element names */
470
+ let ALLOWED_TAGS = null;
471
+ const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...text]);
472
+ /* Allowed attribute names */
473
+ let ALLOWED_ATTR = null;
474
+ const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]);
475
+ /*
476
+ * Configure how DOMPurify should handle custom elements and their attributes as well as customized built-in elements.
477
+ * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements)
478
+ * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list)
479
+ * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`.
480
+ */
481
+ let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, {
482
+ tagNameCheck: {
483
+ writable: true,
484
+ configurable: false,
485
+ enumerable: true,
486
+ value: null
487
+ },
488
+ attributeNameCheck: {
489
+ writable: true,
490
+ configurable: false,
491
+ enumerable: true,
492
+ value: null
493
+ },
494
+ allowCustomizedBuiltInElements: {
495
+ writable: true,
496
+ configurable: false,
497
+ enumerable: true,
498
+ value: false
356
499
  }
500
+ }));
501
+ /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */
502
+ let FORBID_TAGS = null;
503
+ /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */
504
+ let FORBID_ATTR = null;
505
+ /* Config object to store ADD_TAGS/ADD_ATTR functions (when used as functions) */
506
+ const EXTRA_ELEMENT_HANDLING = Object.seal(create(null, {
507
+ tagCheck: {
508
+ writable: true,
509
+ configurable: false,
510
+ enumerable: true,
511
+ value: null
512
+ },
513
+ attributeCheck: {
514
+ writable: true,
515
+ configurable: false,
516
+ enumerable: true,
517
+ value: null
518
+ }
519
+ }));
520
+ /* Decide if ARIA attributes are okay */
521
+ let ALLOW_ARIA_ATTR = true;
522
+ /* Decide if custom data attributes are okay */
523
+ let ALLOW_DATA_ATTR = true;
524
+ /* Decide if unknown protocols are okay */
525
+ let ALLOW_UNKNOWN_PROTOCOLS = false;
526
+ /* Decide if self-closing tags in attributes are allowed.
527
+ * Usually removed due to a mXSS issue in jQuery 3.0 */
528
+ let ALLOW_SELF_CLOSE_IN_ATTR = true;
529
+ /* Output should be safe for common template engines.
530
+ * This means, DOMPurify removes data attributes, mustaches and ERB
531
+ */
532
+ let SAFE_FOR_TEMPLATES = false;
533
+ /* Output should be safe even for XML used within HTML and alike.
534
+ * This means, DOMPurify removes comments when containing risky content.
535
+ */
536
+ let SAFE_FOR_XML = true;
537
+ /* Decide if document with <html>... should be returned */
538
+ let WHOLE_DOCUMENT = false;
539
+ /* Track whether config is already set on this instance of DOMPurify. */
540
+ let SET_CONFIG = false;
541
+ /* Decide if all elements (e.g. style, script) must be children of
542
+ * document.body. By default, browsers might move them to document.head */
543
+ let FORCE_BODY = false;
544
+ /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html
545
+ * string (or a TrustedHTML object if Trusted Types are supported).
546
+ * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead
547
+ */
548
+ let RETURN_DOM = false;
549
+ /* Decide if a DOM `DocumentFragment` should be returned, instead of a html
550
+ * string (or a TrustedHTML object if Trusted Types are supported) */
551
+ let RETURN_DOM_FRAGMENT = false;
552
+ /* Try to return a Trusted Type object instead of a string, return a string in
553
+ * case Trusted Types are not supported */
554
+ let RETURN_TRUSTED_TYPE = false;
555
+ /* Output should be free from DOM clobbering attacks?
556
+ * This sanitizes markups named with colliding, clobberable built-in DOM APIs.
557
+ */
558
+ let SANITIZE_DOM = true;
559
+ /* Achieve full DOM Clobbering protection by isolating the namespace of named
560
+ * properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules.
561
+ *
562
+ * HTML/DOM spec rules that enable DOM Clobbering:
563
+ * - Named Access on Window (§7.3.3)
564
+ * - DOM Tree Accessors (§3.1.5)
565
+ * - Form Element Parent-Child Relations (§4.10.3)
566
+ * - Iframe srcdoc / Nested WindowProxies (§4.8.5)
567
+ * - HTMLCollection (§4.2.10.2)
568
+ *
569
+ * Namespace isolation is implemented by prefixing `id` and `name` attributes
570
+ * with a constant string, i.e., `user-content-`
571
+ */
572
+ let SANITIZE_NAMED_PROPS = false;
573
+ const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-';
574
+ /* Keep element content when removing element? */
575
+ let KEEP_CONTENT = true;
576
+ /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead
577
+ * of importing it into a new Document and returning a sanitized copy */
578
+ let IN_PLACE = false;
579
+ /* Allow usage of profiles like html, svg and mathMl */
580
+ let USE_PROFILES = {};
581
+ /* Tags to ignore content of when KEEP_CONTENT is true */
582
+ let FORBID_CONTENTS = null;
583
+ 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']);
584
+ /* Tags that are safe for data: URIs */
585
+ let DATA_URI_TAGS = null;
586
+ const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);
587
+ /* Attributes safe for values like "javascript:" */
588
+ let URI_SAFE_ATTRIBUTES = null;
589
+ const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']);
590
+ const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
591
+ const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
592
+ const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
593
+ /* Document namespace */
594
+ let NAMESPACE = HTML_NAMESPACE;
595
+ let IS_EMPTY_INPUT = false;
596
+ /* Allowed XHTML+XML namespaces */
597
+ let ALLOWED_NAMESPACES = null;
598
+ const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);
599
+ let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']);
600
+ let HTML_INTEGRATION_POINTS = addToSet({}, ['annotation-xml']);
601
+ // Certain elements are allowed in both SVG and HTML
602
+ // namespace. We need to specify them explicitly
603
+ // so that they don't get erroneously deleted from
604
+ // HTML namespace.
605
+ const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']);
606
+ /* Parsing of strict XHTML documents */
607
+ let PARSER_MEDIA_TYPE = null;
608
+ const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html'];
609
+ const DEFAULT_PARSER_MEDIA_TYPE = 'text/html';
610
+ let transformCaseFunc = null;
611
+ /* Keep a reference to config to pass to hooks */
612
+ let CONFIG = null;
613
+ /* Ideally, do not touch anything below this line */
614
+ /* ______________________________________________ */
615
+ const formElement = document.createElement('form');
616
+ const isRegexOrFunction = function isRegexOrFunction(testValue) {
617
+ return testValue instanceof RegExp || testValue instanceof Function;
357
618
  };
358
- const _createHooksMap = function _createHooksMap() {
359
- return {
360
- afterSanitizeAttributes: [],
361
- afterSanitizeElements: [],
362
- afterSanitizeShadowDOM: [],
363
- beforeSanitizeAttributes: [],
364
- beforeSanitizeElements: [],
365
- beforeSanitizeShadowDOM: [],
366
- uponSanitizeAttribute: [],
367
- uponSanitizeElement: [],
368
- uponSanitizeShadowNode: []
369
- };
370
- };
371
- function createDOMPurify() {
372
- let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();
373
- const DOMPurify = root => createDOMPurify(root);
374
- DOMPurify.version = '3.4.2';
375
- DOMPurify.removed = [];
376
- if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document || !window.Element) {
377
- // Not running in a browser, provide a factory function
378
- // so that you can pass your own Window
379
- DOMPurify.isSupported = false;
380
- return DOMPurify;
381
- }
382
- let {
383
- document
384
- } = window;
385
- const originalDocument = document;
386
- const currentScript = originalDocument.currentScript;
387
- const {
388
- DocumentFragment,
389
- HTMLTemplateElement,
390
- Node,
391
- Element,
392
- NodeFilter,
393
- NamedNodeMap = window.NamedNodeMap || window.MozNamedAttrMap,
394
- HTMLFormElement,
395
- DOMParser,
396
- trustedTypes
397
- } = window;
398
- const ElementPrototype = Element.prototype;
399
- const cloneNode = lookupGetter(ElementPrototype, 'cloneNode');
400
- const remove = lookupGetter(ElementPrototype, 'remove');
401
- const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');
402
- const getChildNodes = lookupGetter(ElementPrototype, 'childNodes');
403
- const getParentNode = lookupGetter(ElementPrototype, 'parentNode');
404
- // As per issue #47, the web-components registry is inherited by a
405
- // new document created via createHTMLDocument. As per the spec
406
- // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)
407
- // a new empty registry is used when creating a template contents owner
408
- // document, so we use that as our parent document to ensure nothing
409
- // is inherited.
410
- if (typeof HTMLTemplateElement === 'function') {
411
- const template = document.createElement('template');
412
- if (template.content && template.content.ownerDocument) {
413
- document = template.content.ownerDocument;
414
- }
619
+ /**
620
+ * _parseConfig
621
+ *
622
+ * @param cfg optional config literal
623
+ */
624
+ // eslint-disable-next-line complexity
625
+ const _parseConfig = function _parseConfig() {
626
+ let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
627
+ if (CONFIG && CONFIG === cfg) {
628
+ return;
415
629
  }
416
- let trustedTypesPolicy;
417
- let emptyHTML = '';
418
- const {
419
- implementation,
420
- createNodeIterator,
421
- createDocumentFragment,
422
- getElementsByTagName
423
- } = document;
424
- const {
425
- importNode
426
- } = originalDocument;
427
- let hooks = _createHooksMap();
428
- /**
429
- * Expose whether this browser supports running the full DOMPurify.
430
- */
431
- DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNode === 'function' && implementation && implementation.createHTMLDocument !== undefined;
432
- const {
433
- MUSTACHE_EXPR,
434
- ERB_EXPR,
435
- TMPLIT_EXPR,
436
- DATA_ATTR,
437
- ARIA_ATTR,
438
- IS_SCRIPT_OR_DATA,
439
- ATTR_WHITESPACE,
440
- CUSTOM_ELEMENT
441
- } = EXPRESSIONS;
442
- let {
443
- IS_ALLOWED_URI: IS_ALLOWED_URI$1
444
- } = EXPRESSIONS;
445
- /**
446
- * We consider the elements and attributes below to be safe. Ideally
447
- * don't add any new ones but feel free to remove unwanted ones.
448
- */
449
- /* allowed element names */
450
- let ALLOWED_TAGS = null;
451
- const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...text]);
452
- /* Allowed attribute names */
453
- let ALLOWED_ATTR = null;
454
- const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]);
455
- /*
456
- * Configure how DOMPurify should handle custom elements and their attributes as well as customized built-in elements.
457
- * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements)
458
- * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list)
459
- * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`.
460
- */
461
- let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, {
462
- tagNameCheck: {
463
- writable: true,
464
- configurable: false,
465
- enumerable: true,
466
- value: null
467
- },
468
- attributeNameCheck: {
469
- writable: true,
470
- configurable: false,
471
- enumerable: true,
472
- value: null
473
- },
474
- allowCustomizedBuiltInElements: {
475
- writable: true,
476
- configurable: false,
477
- enumerable: true,
478
- value: false
479
- }
480
- }));
481
- /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */
482
- let FORBID_TAGS = null;
483
- /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */
484
- let FORBID_ATTR = null;
485
- /* Config object to store ADD_TAGS/ADD_ATTR functions (when used as functions) */
486
- const EXTRA_ELEMENT_HANDLING = Object.seal(create(null, {
487
- tagCheck: {
488
- writable: true,
489
- configurable: false,
490
- enumerable: true,
491
- value: null
492
- },
493
- attributeCheck: {
494
- writable: true,
495
- configurable: false,
496
- enumerable: true,
497
- value: null
498
- }
499
- }));
500
- /* Decide if ARIA attributes are okay */
501
- let ALLOW_ARIA_ATTR = true;
502
- /* Decide if custom data attributes are okay */
503
- let ALLOW_DATA_ATTR = true;
504
- /* Decide if unknown protocols are okay */
505
- let ALLOW_UNKNOWN_PROTOCOLS = false;
506
- /* Decide if self-closing tags in attributes are allowed.
507
- * Usually removed due to a mXSS issue in jQuery 3.0 */
508
- let ALLOW_SELF_CLOSE_IN_ATTR = true;
509
- /* Output should be safe for common template engines.
510
- * This means, DOMPurify removes data attributes, mustaches and ERB
511
- */
512
- let SAFE_FOR_TEMPLATES = false;
513
- /* Output should be safe even for XML used within HTML and alike.
514
- * This means, DOMPurify removes comments when containing risky content.
515
- */
516
- let SAFE_FOR_XML = true;
517
- /* Decide if document with <html>... should be returned */
518
- let WHOLE_DOCUMENT = false;
519
- /* Track whether config is already set on this instance of DOMPurify. */
520
- let SET_CONFIG = false;
521
- /* Decide if all elements (e.g. style, script) must be children of
522
- * document.body. By default, browsers might move them to document.head */
523
- let FORCE_BODY = false;
524
- /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html
525
- * string (or a TrustedHTML object if Trusted Types are supported).
526
- * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead
527
- */
528
- let RETURN_DOM = false;
529
- /* Decide if a DOM `DocumentFragment` should be returned, instead of a html
530
- * string (or a TrustedHTML object if Trusted Types are supported) */
531
- let RETURN_DOM_FRAGMENT = false;
532
- /* Try to return a Trusted Type object instead of a string, return a string in
533
- * case Trusted Types are not supported */
534
- let RETURN_TRUSTED_TYPE = false;
535
- /* Output should be free from DOM clobbering attacks?
536
- * This sanitizes markups named with colliding, clobberable built-in DOM APIs.
537
- */
538
- let SANITIZE_DOM = true;
539
- /* Achieve full DOM Clobbering protection by isolating the namespace of named
540
- * properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules.
541
- *
542
- * HTML/DOM spec rules that enable DOM Clobbering:
543
- * - Named Access on Window (§7.3.3)
544
- * - DOM Tree Accessors (§3.1.5)
545
- * - Form Element Parent-Child Relations (§4.10.3)
546
- * - Iframe srcdoc / Nested WindowProxies (§4.8.5)
547
- * - HTMLCollection (§4.2.10.2)
548
- *
549
- * Namespace isolation is implemented by prefixing `id` and `name` attributes
550
- * with a constant string, i.e., `user-content-`
551
- */
552
- let SANITIZE_NAMED_PROPS = false;
553
- const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-';
554
- /* Keep element content when removing element? */
555
- let KEEP_CONTENT = true;
556
- /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead
557
- * of importing it into a new Document and returning a sanitized copy */
558
- let IN_PLACE = false;
559
- /* Allow usage of profiles like html, svg and mathMl */
560
- let USE_PROFILES = {};
561
- /* Tags to ignore content of when KEEP_CONTENT is true */
562
- let FORBID_CONTENTS = null;
563
- 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']);
564
- /* Tags that are safe for data: URIs */
565
- let DATA_URI_TAGS = null;
566
- const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);
567
- /* Attributes safe for values like "javascript:" */
568
- let URI_SAFE_ATTRIBUTES = null;
569
- const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']);
570
- const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
571
- const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
572
- const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
573
- /* Document namespace */
574
- let NAMESPACE = HTML_NAMESPACE;
575
- let IS_EMPTY_INPUT = false;
576
- /* Allowed XHTML+XML namespaces */
577
- let ALLOWED_NAMESPACES = null;
578
- const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);
579
- let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']);
580
- let HTML_INTEGRATION_POINTS = addToSet({}, ['annotation-xml']);
581
- // Certain elements are allowed in both SVG and HTML
582
- // namespace. We need to specify them explicitly
583
- // so that they don't get erroneously deleted from
584
- // HTML namespace.
585
- const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']);
586
- /* Parsing of strict XHTML documents */
587
- let PARSER_MEDIA_TYPE = null;
588
- const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html'];
589
- const DEFAULT_PARSER_MEDIA_TYPE = 'text/html';
590
- let transformCaseFunc = null;
591
- /* Keep a reference to config to pass to hooks */
592
- let CONFIG = null;
593
- /* Ideally, do not touch anything below this line */
594
- /* ______________________________________________ */
595
- const formElement = document.createElement('form');
596
- const isRegexOrFunction = function isRegexOrFunction(testValue) {
597
- return testValue instanceof RegExp || testValue instanceof Function;
598
- };
599
- /**
600
- * _parseConfig
601
- *
602
- * @param cfg optional config literal
603
- */
604
- // eslint-disable-next-line complexity
605
- const _parseConfig = function _parseConfig() {
606
- let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
607
- if (CONFIG && CONFIG === cfg) {
608
- return;
609
- }
610
- /* Shield configuration object from tampering */
611
- if (!cfg || typeof cfg !== 'object') {
612
- cfg = {};
613
- }
614
- /* Shield configuration object from prototype pollution */
615
- cfg = clone(cfg);
616
- PARSER_MEDIA_TYPE =
617
- // eslint-disable-next-line unicorn/prefer-includes
618
- SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? DEFAULT_PARSER_MEDIA_TYPE : cfg.PARSER_MEDIA_TYPE;
619
- // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.
620
- transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase;
621
- /* Set configuration parameters */
622
- ALLOWED_TAGS = objectHasOwnProperty(cfg, 'ALLOWED_TAGS') && arrayIsArray(cfg.ALLOWED_TAGS) ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS;
623
- ALLOWED_ATTR = objectHasOwnProperty(cfg, 'ALLOWED_ATTR') && arrayIsArray(cfg.ALLOWED_ATTR) ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR;
624
- ALLOWED_NAMESPACES = objectHasOwnProperty(cfg, 'ALLOWED_NAMESPACES') && arrayIsArray(cfg.ALLOWED_NAMESPACES) ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES;
625
- URI_SAFE_ATTRIBUTES = objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') && arrayIsArray(cfg.ADD_URI_SAFE_ATTR) ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR, transformCaseFunc) : DEFAULT_URI_SAFE_ATTRIBUTES;
626
- DATA_URI_TAGS = objectHasOwnProperty(cfg, 'ADD_DATA_URI_TAGS') && arrayIsArray(cfg.ADD_DATA_URI_TAGS) ? addToSet(clone(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS, transformCaseFunc) : DEFAULT_DATA_URI_TAGS;
627
- FORBID_CONTENTS = objectHasOwnProperty(cfg, 'FORBID_CONTENTS') && arrayIsArray(cfg.FORBID_CONTENTS) ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS;
628
- FORBID_TAGS = objectHasOwnProperty(cfg, 'FORBID_TAGS') && arrayIsArray(cfg.FORBID_TAGS) ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : clone({});
629
- FORBID_ATTR = objectHasOwnProperty(cfg, 'FORBID_ATTR') && arrayIsArray(cfg.FORBID_ATTR) ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : clone({});
630
- USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES && typeof cfg.USE_PROFILES === 'object' ? clone(cfg.USE_PROFILES) : cfg.USE_PROFILES : false;
631
- ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true
632
- ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true
633
- ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false
634
- ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true
635
- SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false
636
- SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; // Default true
637
- WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false
638
- RETURN_DOM = cfg.RETURN_DOM || false; // Default false
639
- RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false
640
- RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false
641
- FORCE_BODY = cfg.FORCE_BODY || false; // Default false
642
- SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true
643
- SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false
644
- KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true
645
- IN_PLACE = cfg.IN_PLACE || false; // Default false
646
- IS_ALLOWED_URI$1 = isRegex(cfg.ALLOWED_URI_REGEXP) ? cfg.ALLOWED_URI_REGEXP : IS_ALLOWED_URI; // Default regexp
647
- NAMESPACE = typeof cfg.NAMESPACE === 'string' ? cfg.NAMESPACE : HTML_NAMESPACE; // Default HTML namespace
648
- MATHML_TEXT_INTEGRATION_POINTS = objectHasOwnProperty(cfg, 'MATHML_TEXT_INTEGRATION_POINTS') && cfg.MATHML_TEXT_INTEGRATION_POINTS && typeof cfg.MATHML_TEXT_INTEGRATION_POINTS === 'object' ? clone(cfg.MATHML_TEXT_INTEGRATION_POINTS) : addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']); // Default built-in map
649
- HTML_INTEGRATION_POINTS = objectHasOwnProperty(cfg, 'HTML_INTEGRATION_POINTS') && cfg.HTML_INTEGRATION_POINTS && typeof cfg.HTML_INTEGRATION_POINTS === 'object' ? clone(cfg.HTML_INTEGRATION_POINTS) : addToSet({}, ['annotation-xml']); // Default built-in map
650
- const customElementHandling = objectHasOwnProperty(cfg, 'CUSTOM_ELEMENT_HANDLING') && cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING === 'object' ? clone(cfg.CUSTOM_ELEMENT_HANDLING) : create(null);
651
- CUSTOM_ELEMENT_HANDLING = create(null);
652
- if (objectHasOwnProperty(customElementHandling, 'tagNameCheck') && isRegexOrFunction(customElementHandling.tagNameCheck)) {
653
- CUSTOM_ELEMENT_HANDLING.tagNameCheck = customElementHandling.tagNameCheck; // Default undefined
654
- }
655
- if (objectHasOwnProperty(customElementHandling, 'attributeNameCheck') && isRegexOrFunction(customElementHandling.attributeNameCheck)) {
656
- CUSTOM_ELEMENT_HANDLING.attributeNameCheck = customElementHandling.attributeNameCheck; // Default undefined
657
- }
658
- if (objectHasOwnProperty(customElementHandling, 'allowCustomizedBuiltInElements') && typeof customElementHandling.allowCustomizedBuiltInElements === 'boolean') {
659
- CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = customElementHandling.allowCustomizedBuiltInElements; // Default undefined
660
- }
661
- if (SAFE_FOR_TEMPLATES) {
662
- ALLOW_DATA_ATTR = false;
663
- }
664
- if (RETURN_DOM_FRAGMENT) {
665
- RETURN_DOM = true;
666
- }
667
- /* Parse profile info */
668
- if (USE_PROFILES) {
669
- ALLOWED_TAGS = addToSet({}, text);
670
- ALLOWED_ATTR = create(null);
671
- if (USE_PROFILES.html === true) {
672
- addToSet(ALLOWED_TAGS, html$1);
673
- addToSet(ALLOWED_ATTR, html);
674
- }
675
- if (USE_PROFILES.svg === true) {
676
- addToSet(ALLOWED_TAGS, svg$1);
677
- addToSet(ALLOWED_ATTR, svg);
678
- addToSet(ALLOWED_ATTR, xml);
679
- }
680
- if (USE_PROFILES.svgFilters === true) {
681
- addToSet(ALLOWED_TAGS, svgFilters);
682
- addToSet(ALLOWED_ATTR, svg);
683
- addToSet(ALLOWED_ATTR, xml);
684
- }
685
- if (USE_PROFILES.mathMl === true) {
686
- addToSet(ALLOWED_TAGS, mathMl$1);
687
- addToSet(ALLOWED_ATTR, mathMl);
688
- addToSet(ALLOWED_ATTR, xml);
689
- }
690
- }
691
- /* Always reset function-based ADD_TAGS / ADD_ATTR checks to prevent
692
- * leaking across calls when switching from function to array config */
693
- EXTRA_ELEMENT_HANDLING.tagCheck = null;
694
- EXTRA_ELEMENT_HANDLING.attributeCheck = null;
695
- /* Merge configuration parameters */
696
- if (objectHasOwnProperty(cfg, 'ADD_TAGS')) {
697
- if (typeof cfg.ADD_TAGS === 'function') {
698
- EXTRA_ELEMENT_HANDLING.tagCheck = cfg.ADD_TAGS;
699
- } else if (arrayIsArray(cfg.ADD_TAGS)) {
700
- if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
701
- ALLOWED_TAGS = clone(ALLOWED_TAGS);
702
- }
703
- addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);
704
- }
705
- }
706
- if (objectHasOwnProperty(cfg, 'ADD_ATTR')) {
707
- if (typeof cfg.ADD_ATTR === 'function') {
708
- EXTRA_ELEMENT_HANDLING.attributeCheck = cfg.ADD_ATTR;
709
- } else if (arrayIsArray(cfg.ADD_ATTR)) {
710
- if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
711
- ALLOWED_ATTR = clone(ALLOWED_ATTR);
712
- }
713
- addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);
714
- }
715
- }
716
- if (objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') && arrayIsArray(cfg.ADD_URI_SAFE_ATTR)) {
717
- addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);
630
+ /* Shield configuration object from tampering */
631
+ if (!cfg || typeof cfg !== 'object') {
632
+ cfg = {};
633
+ }
634
+ /* Shield configuration object from prototype pollution */
635
+ cfg = clone(cfg);
636
+ PARSER_MEDIA_TYPE =
637
+ // eslint-disable-next-line unicorn/prefer-includes
638
+ SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? DEFAULT_PARSER_MEDIA_TYPE : cfg.PARSER_MEDIA_TYPE;
639
+ // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.
640
+ transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase;
641
+ /* Set configuration parameters */
642
+ ALLOWED_TAGS = objectHasOwnProperty(cfg, 'ALLOWED_TAGS') && arrayIsArray(cfg.ALLOWED_TAGS) ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS;
643
+ ALLOWED_ATTR = objectHasOwnProperty(cfg, 'ALLOWED_ATTR') && arrayIsArray(cfg.ALLOWED_ATTR) ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR;
644
+ ALLOWED_NAMESPACES = objectHasOwnProperty(cfg, 'ALLOWED_NAMESPACES') && arrayIsArray(cfg.ALLOWED_NAMESPACES) ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES;
645
+ URI_SAFE_ATTRIBUTES = objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') && arrayIsArray(cfg.ADD_URI_SAFE_ATTR) ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR, transformCaseFunc) : DEFAULT_URI_SAFE_ATTRIBUTES;
646
+ DATA_URI_TAGS = objectHasOwnProperty(cfg, 'ADD_DATA_URI_TAGS') && arrayIsArray(cfg.ADD_DATA_URI_TAGS) ? addToSet(clone(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS, transformCaseFunc) : DEFAULT_DATA_URI_TAGS;
647
+ FORBID_CONTENTS = objectHasOwnProperty(cfg, 'FORBID_CONTENTS') && arrayIsArray(cfg.FORBID_CONTENTS) ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS;
648
+ FORBID_TAGS = objectHasOwnProperty(cfg, 'FORBID_TAGS') && arrayIsArray(cfg.FORBID_TAGS) ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : clone({});
649
+ FORBID_ATTR = objectHasOwnProperty(cfg, 'FORBID_ATTR') && arrayIsArray(cfg.FORBID_ATTR) ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : clone({});
650
+ USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES && typeof cfg.USE_PROFILES === 'object' ? clone(cfg.USE_PROFILES) : cfg.USE_PROFILES : false;
651
+ ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true
652
+ ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true
653
+ ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false
654
+ ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true
655
+ SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false
656
+ SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; // Default true
657
+ WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false
658
+ RETURN_DOM = cfg.RETURN_DOM || false; // Default false
659
+ RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false
660
+ RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false
661
+ FORCE_BODY = cfg.FORCE_BODY || false; // Default false
662
+ SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true
663
+ SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false
664
+ KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true
665
+ IN_PLACE = cfg.IN_PLACE || false; // Default false
666
+ IS_ALLOWED_URI$1 = isRegex(cfg.ALLOWED_URI_REGEXP) ? cfg.ALLOWED_URI_REGEXP : IS_ALLOWED_URI; // Default regexp
667
+ NAMESPACE = typeof cfg.NAMESPACE === 'string' ? cfg.NAMESPACE : HTML_NAMESPACE; // Default HTML namespace
668
+ MATHML_TEXT_INTEGRATION_POINTS = objectHasOwnProperty(cfg, 'MATHML_TEXT_INTEGRATION_POINTS') && cfg.MATHML_TEXT_INTEGRATION_POINTS && typeof cfg.MATHML_TEXT_INTEGRATION_POINTS === 'object' ? clone(cfg.MATHML_TEXT_INTEGRATION_POINTS) : addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']); // Default built-in map
669
+ HTML_INTEGRATION_POINTS = objectHasOwnProperty(cfg, 'HTML_INTEGRATION_POINTS') && cfg.HTML_INTEGRATION_POINTS && typeof cfg.HTML_INTEGRATION_POINTS === 'object' ? clone(cfg.HTML_INTEGRATION_POINTS) : addToSet({}, ['annotation-xml']); // Default built-in map
670
+ const customElementHandling = objectHasOwnProperty(cfg, 'CUSTOM_ELEMENT_HANDLING') && cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING === 'object' ? clone(cfg.CUSTOM_ELEMENT_HANDLING) : create(null);
671
+ CUSTOM_ELEMENT_HANDLING = create(null);
672
+ if (objectHasOwnProperty(customElementHandling, 'tagNameCheck') && isRegexOrFunction(customElementHandling.tagNameCheck)) {
673
+ CUSTOM_ELEMENT_HANDLING.tagNameCheck = customElementHandling.tagNameCheck; // Default undefined
674
+ }
675
+ if (objectHasOwnProperty(customElementHandling, 'attributeNameCheck') && isRegexOrFunction(customElementHandling.attributeNameCheck)) {
676
+ CUSTOM_ELEMENT_HANDLING.attributeNameCheck = customElementHandling.attributeNameCheck; // Default undefined
677
+ }
678
+ if (objectHasOwnProperty(customElementHandling, 'allowCustomizedBuiltInElements') && typeof customElementHandling.allowCustomizedBuiltInElements === 'boolean') {
679
+ CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = customElementHandling.allowCustomizedBuiltInElements; // Default undefined
680
+ }
681
+ if (SAFE_FOR_TEMPLATES) {
682
+ ALLOW_DATA_ATTR = false;
683
+ }
684
+ if (RETURN_DOM_FRAGMENT) {
685
+ RETURN_DOM = true;
686
+ }
687
+ /* Parse profile info */
688
+ if (USE_PROFILES) {
689
+ ALLOWED_TAGS = addToSet({}, text);
690
+ ALLOWED_ATTR = create(null);
691
+ if (USE_PROFILES.html === true) {
692
+ addToSet(ALLOWED_TAGS, html$1);
693
+ addToSet(ALLOWED_ATTR, html);
694
+ }
695
+ if (USE_PROFILES.svg === true) {
696
+ addToSet(ALLOWED_TAGS, svg$1);
697
+ addToSet(ALLOWED_ATTR, svg);
698
+ addToSet(ALLOWED_ATTR, xml);
699
+ }
700
+ if (USE_PROFILES.svgFilters === true) {
701
+ addToSet(ALLOWED_TAGS, svgFilters);
702
+ addToSet(ALLOWED_ATTR, svg);
703
+ addToSet(ALLOWED_ATTR, xml);
704
+ }
705
+ if (USE_PROFILES.mathMl === true) {
706
+ addToSet(ALLOWED_TAGS, mathMl$1);
707
+ addToSet(ALLOWED_ATTR, mathMl);
708
+ addToSet(ALLOWED_ATTR, xml);
718
709
  }
719
- if (objectHasOwnProperty(cfg, 'FORBID_CONTENTS') && arrayIsArray(cfg.FORBID_CONTENTS)) {
720
- if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
721
- FORBID_CONTENTS = clone(FORBID_CONTENTS);
710
+ }
711
+ /* Always reset function-based ADD_TAGS / ADD_ATTR checks to prevent
712
+ * leaking across calls when switching from function to array config */
713
+ EXTRA_ELEMENT_HANDLING.tagCheck = null;
714
+ EXTRA_ELEMENT_HANDLING.attributeCheck = null;
715
+ /* Merge configuration parameters */
716
+ if (objectHasOwnProperty(cfg, 'ADD_TAGS')) {
717
+ if (typeof cfg.ADD_TAGS === 'function') {
718
+ EXTRA_ELEMENT_HANDLING.tagCheck = cfg.ADD_TAGS;
719
+ } else if (arrayIsArray(cfg.ADD_TAGS)) {
720
+ if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
721
+ ALLOWED_TAGS = clone(ALLOWED_TAGS);
722
722
  }
723
- addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);
723
+ addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);
724
724
  }
725
- if (objectHasOwnProperty(cfg, 'ADD_FORBID_CONTENTS') && arrayIsArray(cfg.ADD_FORBID_CONTENTS)) {
726
- if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
727
- FORBID_CONTENTS = clone(FORBID_CONTENTS);
725
+ }
726
+ if (objectHasOwnProperty(cfg, 'ADD_ATTR')) {
727
+ if (typeof cfg.ADD_ATTR === 'function') {
728
+ EXTRA_ELEMENT_HANDLING.attributeCheck = cfg.ADD_ATTR;
729
+ } else if (arrayIsArray(cfg.ADD_ATTR)) {
730
+ if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
731
+ ALLOWED_ATTR = clone(ALLOWED_ATTR);
728
732
  }
729
- addToSet(FORBID_CONTENTS, cfg.ADD_FORBID_CONTENTS, transformCaseFunc);
730
- }
731
- /* Add #text in case KEEP_CONTENT is set to true */
732
- if (KEEP_CONTENT) {
733
- ALLOWED_TAGS['#text'] = true;
733
+ addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);
734
734
  }
735
- /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */
736
- if (WHOLE_DOCUMENT) {
737
- addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);
735
+ }
736
+ if (objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') && arrayIsArray(cfg.ADD_URI_SAFE_ATTR)) {
737
+ addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);
738
+ }
739
+ if (objectHasOwnProperty(cfg, 'FORBID_CONTENTS') && arrayIsArray(cfg.FORBID_CONTENTS)) {
740
+ if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
741
+ FORBID_CONTENTS = clone(FORBID_CONTENTS);
738
742
  }
739
- /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */
740
- if (ALLOWED_TAGS.table) {
741
- addToSet(ALLOWED_TAGS, ['tbody']);
742
- delete FORBID_TAGS.tbody;
743
+ addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);
744
+ }
745
+ if (objectHasOwnProperty(cfg, 'ADD_FORBID_CONTENTS') && arrayIsArray(cfg.ADD_FORBID_CONTENTS)) {
746
+ if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
747
+ FORBID_CONTENTS = clone(FORBID_CONTENTS);
743
748
  }
744
- if (cfg.TRUSTED_TYPES_POLICY) {
745
- if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') {
746
- throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');
747
- }
748
- if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') {
749
- throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');
750
- }
751
- // Overwrite existing TrustedTypes policy.
752
- trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;
753
- // Sign local variables required by `sanitize`.
749
+ addToSet(FORBID_CONTENTS, cfg.ADD_FORBID_CONTENTS, transformCaseFunc);
750
+ }
751
+ /* Add #text in case KEEP_CONTENT is set to true */
752
+ if (KEEP_CONTENT) {
753
+ ALLOWED_TAGS['#text'] = true;
754
+ }
755
+ /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */
756
+ if (WHOLE_DOCUMENT) {
757
+ addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);
758
+ }
759
+ /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */
760
+ if (ALLOWED_TAGS.table) {
761
+ addToSet(ALLOWED_TAGS, ['tbody']);
762
+ delete FORBID_TAGS.tbody;
763
+ }
764
+ if (cfg.TRUSTED_TYPES_POLICY) {
765
+ if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') {
766
+ throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');
767
+ }
768
+ if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') {
769
+ throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');
770
+ }
771
+ // Overwrite existing TrustedTypes policy.
772
+ trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;
773
+ // Sign local variables required by `sanitize`.
774
+ emptyHTML = trustedTypesPolicy.createHTML('');
775
+ } else {
776
+ // Uninitialized policy, attempt to initialize the internal dompurify policy.
777
+ if (trustedTypesPolicy === undefined) {
778
+ trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);
779
+ }
780
+ // If creating the internal policy succeeded sign internal variables.
781
+ if (trustedTypesPolicy !== null && typeof emptyHTML === 'string') {
754
782
  emptyHTML = trustedTypesPolicy.createHTML('');
755
- } else {
756
- // Uninitialized policy, attempt to initialize the internal dompurify policy.
757
- if (trustedTypesPolicy === undefined) {
758
- trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);
759
- }
760
- // If creating the internal policy succeeded sign internal variables.
761
- if (trustedTypesPolicy !== null && typeof emptyHTML === 'string') {
762
- emptyHTML = trustedTypesPolicy.createHTML('');
763
- }
764
- }
765
- // Prevent further manipulation of configuration.
766
- // Not available in IE8, Safari 5, etc.
767
- if (freeze) {
768
- freeze(cfg);
769
- }
770
- CONFIG = cfg;
771
- };
772
- /* Keep track of all possible SVG and MathML tags
773
- * so that we can perform the namespace checks
774
- * correctly. */
775
- const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]);
776
- const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]);
777
- /**
778
- * @param element a DOM element whose namespace is being checked
779
- * @returns Return false if the element has a
780
- * namespace that a spec-compliant parser would never
781
- * return. Return true otherwise.
782
- */
783
- const _checkValidNamespace = function _checkValidNamespace(element) {
784
- let parent = getParentNode(element);
785
- // In JSDOM, if we're inside shadow DOM, then parentNode
786
- // can be null. We just simulate parent in this case.
787
- if (!parent || !parent.tagName) {
788
- parent = {
789
- namespaceURI: NAMESPACE,
790
- tagName: 'template'
791
- };
792
783
  }
793
- const tagName = stringToLowerCase(element.tagName);
794
- const parentTagName = stringToLowerCase(parent.tagName);
795
- if (!ALLOWED_NAMESPACES[element.namespaceURI]) {
784
+ }
785
+ // Prevent further manipulation of configuration.
786
+ // Not available in IE8, Safari 5, etc.
787
+ if (freeze) {
788
+ freeze(cfg);
789
+ }
790
+ CONFIG = cfg;
791
+ };
792
+ /* Keep track of all possible SVG and MathML tags
793
+ * so that we can perform the namespace checks
794
+ * correctly. */
795
+ const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]);
796
+ const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]);
797
+ /**
798
+ * @param element a DOM element whose namespace is being checked
799
+ * @returns Return false if the element has a
800
+ * namespace that a spec-compliant parser would never
801
+ * return. Return true otherwise.
802
+ */
803
+ const _checkValidNamespace = function _checkValidNamespace(element) {
804
+ let parent = getParentNode(element);
805
+ // In JSDOM, if we're inside shadow DOM, then parentNode
806
+ // can be null. We just simulate parent in this case.
807
+ if (!parent || !parent.tagName) {
808
+ parent = {
809
+ namespaceURI: NAMESPACE,
810
+ tagName: 'template'
811
+ };
812
+ }
813
+ const tagName = stringToLowerCase(element.tagName);
814
+ const parentTagName = stringToLowerCase(parent.tagName);
815
+ if (!ALLOWED_NAMESPACES[element.namespaceURI]) {
816
+ return false;
817
+ }
818
+ if (element.namespaceURI === SVG_NAMESPACE) {
819
+ // The only way to switch from HTML namespace to SVG
820
+ // is via <svg>. If it happens via any other tag, then
821
+ // it should be killed.
822
+ if (parent.namespaceURI === HTML_NAMESPACE) {
823
+ return tagName === 'svg';
824
+ }
825
+ // The only way to switch from MathML to SVG is via`
826
+ // svg if parent is either <annotation-xml> or MathML
827
+ // text integration points.
828
+ if (parent.namespaceURI === MATHML_NAMESPACE) {
829
+ return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
830
+ }
831
+ // We only allow elements that are defined in SVG
832
+ // spec. All others are disallowed in SVG namespace.
833
+ return Boolean(ALL_SVG_TAGS[tagName]);
834
+ }
835
+ if (element.namespaceURI === MATHML_NAMESPACE) {
836
+ // The only way to switch from HTML namespace to MathML
837
+ // is via <math>. If it happens via any other tag, then
838
+ // it should be killed.
839
+ if (parent.namespaceURI === HTML_NAMESPACE) {
840
+ return tagName === 'math';
841
+ }
842
+ // The only way to switch from SVG to MathML is via
843
+ // <math> and HTML integration points
844
+ if (parent.namespaceURI === SVG_NAMESPACE) {
845
+ return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
846
+ }
847
+ // We only allow elements that are defined in MathML
848
+ // spec. All others are disallowed in MathML namespace.
849
+ return Boolean(ALL_MATHML_TAGS[tagName]);
850
+ }
851
+ if (element.namespaceURI === HTML_NAMESPACE) {
852
+ // The only way to switch from SVG to HTML is via
853
+ // HTML integration points, and from MathML to HTML
854
+ // is via MathML text integration points
855
+ if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
796
856
  return false;
797
857
  }
798
- if (element.namespaceURI === SVG_NAMESPACE) {
799
- // The only way to switch from HTML namespace to SVG
800
- // is via <svg>. If it happens via any other tag, then
801
- // it should be killed.
802
- if (parent.namespaceURI === HTML_NAMESPACE) {
803
- return tagName === 'svg';
804
- }
805
- // The only way to switch from MathML to SVG is via`
806
- // svg if parent is either <annotation-xml> or MathML
807
- // text integration points.
808
- if (parent.namespaceURI === MATHML_NAMESPACE) {
809
- return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
810
- }
811
- // We only allow elements that are defined in SVG
812
- // spec. All others are disallowed in SVG namespace.
813
- return Boolean(ALL_SVG_TAGS[tagName]);
814
- }
815
- if (element.namespaceURI === MATHML_NAMESPACE) {
816
- // The only way to switch from HTML namespace to MathML
817
- // is via <math>. If it happens via any other tag, then
818
- // it should be killed.
819
- if (parent.namespaceURI === HTML_NAMESPACE) {
820
- return tagName === 'math';
821
- }
822
- // The only way to switch from SVG to MathML is via
823
- // <math> and HTML integration points
824
- if (parent.namespaceURI === SVG_NAMESPACE) {
825
- return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
826
- }
827
- // We only allow elements that are defined in MathML
828
- // spec. All others are disallowed in MathML namespace.
829
- return Boolean(ALL_MATHML_TAGS[tagName]);
830
- }
831
- if (element.namespaceURI === HTML_NAMESPACE) {
832
- // The only way to switch from SVG to HTML is via
833
- // HTML integration points, and from MathML to HTML
834
- // is via MathML text integration points
835
- if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
836
- return false;
837
- }
838
- if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
839
- return false;
840
- }
841
- // We disallow tags that are specific for MathML
842
- // or SVG and should never appear in HTML namespace
843
- return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
844
- }
845
- // For XHTML and XML documents that support custom namespaces
846
- if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) {
847
- return true;
858
+ if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
859
+ return false;
848
860
  }
849
- // The code should never reach this place (this means
850
- // that the element somehow got namespace that is not
851
- // HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES).
852
- // Return false just in case.
853
- return false;
854
- };
855
- /**
856
- * _forceRemove
857
- *
858
- * @param node a DOM node
859
- */
860
- const _forceRemove = function _forceRemove(node) {
861
+ // We disallow tags that are specific for MathML
862
+ // or SVG and should never appear in HTML namespace
863
+ return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
864
+ }
865
+ // For XHTML and XML documents that support custom namespaces
866
+ if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) {
867
+ return true;
868
+ }
869
+ // The code should never reach this place (this means
870
+ // that the element somehow got namespace that is not
871
+ // HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES).
872
+ // Return false just in case.
873
+ return false;
874
+ };
875
+ /**
876
+ * _forceRemove
877
+ *
878
+ * @param node a DOM node
879
+ */
880
+ const _forceRemove = function _forceRemove(node) {
881
+ arrayPush(DOMPurify.removed, {
882
+ element: node
883
+ });
884
+ try {
885
+ // eslint-disable-next-line unicorn/prefer-dom-node-remove
886
+ getParentNode(node).removeChild(node);
887
+ } catch (_) {
888
+ remove(node);
889
+ }
890
+ };
891
+ /**
892
+ * _removeAttribute
893
+ *
894
+ * @param name an Attribute name
895
+ * @param element a DOM node
896
+ */
897
+ const _removeAttribute = function _removeAttribute(name, element) {
898
+ try {
861
899
  arrayPush(DOMPurify.removed, {
862
- element: node
900
+ attribute: element.getAttributeNode(name),
901
+ from: element
863
902
  });
864
- try {
865
- // eslint-disable-next-line unicorn/prefer-dom-node-remove
866
- getParentNode(node).removeChild(node);
867
- } catch (_) {
868
- remove(node);
869
- }
870
- };
871
- /**
872
- * _removeAttribute
873
- *
874
- * @param name an Attribute name
875
- * @param element a DOM node
876
- */
877
- const _removeAttribute = function _removeAttribute(name, element) {
878
- try {
879
- arrayPush(DOMPurify.removed, {
880
- attribute: element.getAttributeNode(name),
881
- from: element
882
- });
883
- } catch (_) {
884
- arrayPush(DOMPurify.removed, {
885
- attribute: null,
886
- from: element
887
- });
888
- }
889
- element.removeAttribute(name);
890
- // We void attribute values for unremovable "is" attributes
891
- if (name === 'is') {
892
- if (RETURN_DOM || RETURN_DOM_FRAGMENT) {
893
- try {
894
- _forceRemove(element);
895
- } catch (_) {}
896
- } else {
897
- try {
898
- element.setAttribute(name, '');
899
- } catch (_) {}
900
- }
901
- }
902
- };
903
- /**
904
- * _initDocument
905
- *
906
- * @param dirty - a string of dirty markup
907
- * @return a DOM, filled with the dirty markup
908
- */
909
- const _initDocument = function _initDocument(dirty) {
910
- /* Create a HTML document */
911
- let doc = null;
912
- let leadingWhitespace = null;
913
- if (FORCE_BODY) {
914
- dirty = '<remove></remove>' + dirty;
915
- } else {
916
- /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */
917
- const matches = stringMatch(dirty, /^[\r\n\t ]+/);
918
- leadingWhitespace = matches && matches[0];
919
- }
920
- if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && NAMESPACE === HTML_NAMESPACE) {
921
- // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)
922
- dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + '</body></html>';
923
- }
924
- const dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
925
- /*
926
- * Use the DOMParser API by default, fallback later if needs be
927
- * DOMParser not work for svg when has multiple root element.
928
- */
929
- if (NAMESPACE === HTML_NAMESPACE) {
903
+ } catch (_) {
904
+ arrayPush(DOMPurify.removed, {
905
+ attribute: null,
906
+ from: element
907
+ });
908
+ }
909
+ element.removeAttribute(name);
910
+ // We void attribute values for unremovable "is" attributes
911
+ if (name === 'is') {
912
+ if (RETURN_DOM || RETURN_DOM_FRAGMENT) {
930
913
  try {
931
- doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);
914
+ _forceRemove(element);
932
915
  } catch (_) {}
933
- }
934
- /* Use createHTMLDocument in case DOMParser is not available */
935
- if (!doc || !doc.documentElement) {
936
- doc = implementation.createDocument(NAMESPACE, 'template', null);
916
+ } else {
937
917
  try {
938
- doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload;
939
- } catch (_) {
940
- // Syntax error if dirtyPayload is invalid xml
941
- }
942
- }
943
- const body = doc.body || doc.documentElement;
944
- if (dirty && leadingWhitespace) {
945
- body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null);
946
- }
947
- /* Work on whole document or just its body */
948
- if (NAMESPACE === HTML_NAMESPACE) {
949
- return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0];
918
+ element.setAttribute(name, '');
919
+ } catch (_) {}
950
920
  }
951
- return WHOLE_DOCUMENT ? doc.documentElement : body;
952
- };
953
- /**
954
- * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document.
955
- *
956
- * @param root The root element or node to start traversing on.
957
- * @return The created NodeIterator
958
- */
959
- const _createNodeIterator = function _createNodeIterator(root) {
960
- return createNodeIterator.call(root.ownerDocument || root, root,
961
- // eslint-disable-next-line no-bitwise
962
- NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null);
963
- };
964
- /**
965
- * _isClobbered
966
- *
967
- * @param element element to check for clobbering attacks
968
- * @return true if clobbered, false if safe
969
- */
970
- const _isClobbered = function _isClobbered(element) {
971
- 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');
972
- };
973
- /**
974
- * Checks whether the given object is a DOM node.
975
- *
976
- * @param value object to check whether it's a DOM node
977
- * @return true is object is a DOM node
978
- */
979
- const _isNode = function _isNode(value) {
980
- return typeof Node === 'function' && value instanceof Node;
981
- };
982
- function _executeHooks(hooks, currentNode, data) {
983
- arrayForEach(hooks, hook => {
984
- hook.call(DOMPurify, currentNode, data, CONFIG);
985
- });
986
921
  }
987
- /**
988
- * _sanitizeElements
989
- *
990
- * @protect nodeName
991
- * @protect textContent
992
- * @protect removeChild
993
- * @param currentNode to check for permission to exist
994
- * @return true if node was killed, false if left alive
922
+ };
923
+ /**
924
+ * _initDocument
925
+ *
926
+ * @param dirty - a string of dirty markup
927
+ * @return a DOM, filled with the dirty markup
928
+ */
929
+ const _initDocument = function _initDocument(dirty) {
930
+ /* Create a HTML document */
931
+ let doc = null;
932
+ let leadingWhitespace = null;
933
+ if (FORCE_BODY) {
934
+ dirty = '<remove></remove>' + dirty;
935
+ } else {
936
+ /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */
937
+ const matches = stringMatch(dirty, /^[\r\n\t ]+/);
938
+ leadingWhitespace = matches && matches[0];
939
+ }
940
+ if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && NAMESPACE === HTML_NAMESPACE) {
941
+ // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)
942
+ dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + '</body></html>';
943
+ }
944
+ const dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
945
+ /*
946
+ * Use the DOMParser API by default, fallback later if needs be
947
+ * DOMParser not work for svg when has multiple root element.
995
948
  */
996
- const _sanitizeElements = function _sanitizeElements(currentNode) {
997
- let content = null;
998
- /* Execute a hook if present */
999
- _executeHooks(hooks.beforeSanitizeElements, currentNode, null);
1000
- /* Check if element is clobbered or can clobber */
1001
- if (_isClobbered(currentNode)) {
1002
- _forceRemove(currentNode);
1003
- return true;
949
+ if (NAMESPACE === HTML_NAMESPACE) {
950
+ try {
951
+ doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);
952
+ } catch (_) {}
953
+ }
954
+ /* Use createHTMLDocument in case DOMParser is not available */
955
+ if (!doc || !doc.documentElement) {
956
+ doc = implementation.createDocument(NAMESPACE, 'template', null);
957
+ try {
958
+ doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload;
959
+ } catch (_) {
960
+ // Syntax error if dirtyPayload is invalid xml
1004
961
  }
1005
- /* Now let's check the element's type and name */
1006
- const tagName = transformCaseFunc(currentNode.nodeName);
1007
- /* Execute a hook if present */
1008
- _executeHooks(hooks.uponSanitizeElement, currentNode, {
1009
- tagName,
1010
- allowedTags: ALLOWED_TAGS
962
+ }
963
+ const body = doc.body || doc.documentElement;
964
+ if (dirty && leadingWhitespace) {
965
+ body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null);
966
+ }
967
+ /* Work on whole document or just its body */
968
+ if (NAMESPACE === HTML_NAMESPACE) {
969
+ return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0];
970
+ }
971
+ return WHOLE_DOCUMENT ? doc.documentElement : body;
972
+ };
973
+ /**
974
+ * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document.
975
+ *
976
+ * @param root The root element or node to start traversing on.
977
+ * @return The created NodeIterator
978
+ */
979
+ const _createNodeIterator = function _createNodeIterator(root) {
980
+ return createNodeIterator.call(root.ownerDocument || root, root,
981
+ // eslint-disable-next-line no-bitwise
982
+ NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null);
983
+ };
984
+ /**
985
+ * Strip template-engine expressions ({{...}}, ${...}, <%...%>) from the
986
+ * character data of an element subtree. Used as the final safety net for
987
+ * SAFE_FOR_TEMPLATES on every DOM-returning code path so that expressions
988
+ * which only form after text-node normalization (e.g. fragments split across
989
+ * stripped elements) cannot survive into a template-evaluating framework.
990
+ *
991
+ * Walks text/comment/CDATA/processing-instruction nodes and mutates `.data`
992
+ * in place rather than round-tripping through innerHTML. This preserves
993
+ * descendant node references (important for IN_PLACE callers), avoids a
994
+ * serialize/reparse cycle, and reads literal character data — which means
995
+ * `<%...%>` in text content matches the ERB regex against its real bytes
996
+ * instead of the HTML-entity-escaped form innerHTML would produce.
997
+ *
998
+ * Attribute values are not visited here; SAFE_FOR_TEMPLATES handling for
999
+ * attributes is performed during the per-node `_sanitizeAttributes` pass.
1000
+ *
1001
+ * @param node The root element whose character data should be scrubbed.
1002
+ */
1003
+ const _scrubTemplateExpressions = function _scrubTemplateExpressions(node) {
1004
+ node.normalize();
1005
+ const walker = createNodeIterator.call(node.ownerDocument || node, node,
1006
+ // eslint-disable-next-line no-bitwise
1007
+ NodeFilter.SHOW_TEXT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_CDATA_SECTION | NodeFilter.SHOW_PROCESSING_INSTRUCTION, null);
1008
+ let currentNode = walker.nextNode();
1009
+ while (currentNode) {
1010
+ let data = currentNode.data;
1011
+ arrayForEach([MUSTACHE_EXPR$1, ERB_EXPR$1, TMPLIT_EXPR$1], expr => {
1012
+ data = stringReplace(data, expr, ' ');
1011
1013
  });
1012
- /* Detect mXSS attempts abusing namespace confusion */
1013
- if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(/<[/\w!]/g, currentNode.innerHTML) && regExpTest(/<[/\w!]/g, currentNode.textContent)) {
1014
- _forceRemove(currentNode);
1015
- return true;
1016
- }
1017
- /* Remove risky CSS construction leading to mXSS */
1018
- if (SAFE_FOR_XML && currentNode.namespaceURI === HTML_NAMESPACE && tagName === 'style' && _isNode(currentNode.firstElementChild)) {
1019
- _forceRemove(currentNode);
1020
- return true;
1021
- }
1022
- /* Remove any occurrence of processing instructions */
1023
- if (currentNode.nodeType === NODE_TYPE.progressingInstruction) {
1024
- _forceRemove(currentNode);
1025
- return true;
1026
- }
1027
- /* Remove any kind of possibly harmful comments */
1028
- if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(/<[/\w]/g, currentNode.data)) {
1029
- _forceRemove(currentNode);
1030
- return true;
1031
- }
1032
- /* Remove element if anything forbids its presence */
1033
- if (FORBID_TAGS[tagName] || !(EXTRA_ELEMENT_HANDLING.tagCheck instanceof Function && EXTRA_ELEMENT_HANDLING.tagCheck(tagName)) && !ALLOWED_TAGS[tagName]) {
1034
- /* Check if we have a custom element to handle */
1035
- if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {
1036
- if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {
1037
- return false;
1038
- }
1039
- if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) {
1040
- return false;
1041
- }
1014
+ currentNode.data = data;
1015
+ currentNode = walker.nextNode();
1016
+ }
1017
+ };
1018
+ /**
1019
+ * _isClobbered
1020
+ *
1021
+ * @param element element to check for clobbering attacks
1022
+ * @return true if clobbered, false if safe
1023
+ */
1024
+ const _isClobbered = function _isClobbered(element) {
1025
+ 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');
1026
+ };
1027
+ /**
1028
+ * Checks whether the given object is a DOM node, including nodes that
1029
+ * originate from a different window/realm (e.g. an iframe's
1030
+ * contentDocument). The previous `value instanceof Node` check was
1031
+ * realm-bound: nodes from a different window failed it, causing
1032
+ * sanitize() to silently stringify them and reset IN_PLACE to false,
1033
+ * returning the original node unsanitized. See GHSA-4w3q-35jp-p934.
1034
+ *
1035
+ * Implementation: call the cached `nodeType` getter from Node.prototype
1036
+ * directly on the value. This bypasses any clobbered instance property
1037
+ * (e.g. a child element named "nodeType") and works across realms
1038
+ * because the WebIDL `nodeType` getter reads an internal slot that
1039
+ * every real Node has, regardless of which window minted it.
1040
+ *
1041
+ * @param value object to check whether it's a DOM node
1042
+ * @return true if value is a DOM node from any realm
1043
+ */
1044
+ const _isNode = function _isNode(value) {
1045
+ if (!getNodeType || typeof value !== 'object' || value === null) {
1046
+ return false;
1047
+ }
1048
+ try {
1049
+ return typeof getNodeType(value) === 'number';
1050
+ } catch (_) {
1051
+ return false;
1052
+ }
1053
+ };
1054
+ function _executeHooks(hooks, currentNode, data) {
1055
+ arrayForEach(hooks, hook => {
1056
+ hook.call(DOMPurify, currentNode, data, CONFIG);
1057
+ });
1058
+ }
1059
+ /**
1060
+ * _sanitizeElements
1061
+ *
1062
+ * @protect nodeName
1063
+ * @protect textContent
1064
+ * @protect removeChild
1065
+ * @param currentNode to check for permission to exist
1066
+ * @return true if node was killed, false if left alive
1067
+ */
1068
+ const _sanitizeElements = function _sanitizeElements(currentNode) {
1069
+ let content = null;
1070
+ /* Execute a hook if present */
1071
+ _executeHooks(hooks.beforeSanitizeElements, currentNode, null);
1072
+ /* Check if element is clobbered or can clobber */
1073
+ if (_isClobbered(currentNode)) {
1074
+ _forceRemove(currentNode);
1075
+ return true;
1076
+ }
1077
+ /* Now let's check the element's type and name */
1078
+ const tagName = transformCaseFunc(currentNode.nodeName);
1079
+ /* Execute a hook if present */
1080
+ _executeHooks(hooks.uponSanitizeElement, currentNode, {
1081
+ tagName,
1082
+ allowedTags: ALLOWED_TAGS
1083
+ });
1084
+ /* Detect mXSS attempts abusing namespace confusion */
1085
+ if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(/<[/\w!]/g, currentNode.innerHTML) && regExpTest(/<[/\w!]/g, currentNode.textContent)) {
1086
+ _forceRemove(currentNode);
1087
+ return true;
1088
+ }
1089
+ /* Remove risky CSS construction leading to mXSS */
1090
+ if (SAFE_FOR_XML && currentNode.namespaceURI === HTML_NAMESPACE && tagName === 'style' && _isNode(currentNode.firstElementChild)) {
1091
+ _forceRemove(currentNode);
1092
+ return true;
1093
+ }
1094
+ /* Remove any occurrence of processing instructions */
1095
+ if (currentNode.nodeType === NODE_TYPE.progressingInstruction) {
1096
+ _forceRemove(currentNode);
1097
+ return true;
1098
+ }
1099
+ /* Remove any kind of possibly harmful comments */
1100
+ if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(/<[/\w]/g, currentNode.data)) {
1101
+ _forceRemove(currentNode);
1102
+ return true;
1103
+ }
1104
+ /* Remove element if anything forbids its presence */
1105
+ if (FORBID_TAGS[tagName] || !(EXTRA_ELEMENT_HANDLING.tagCheck instanceof Function && EXTRA_ELEMENT_HANDLING.tagCheck(tagName)) && !ALLOWED_TAGS[tagName]) {
1106
+ /* Check if we have a custom element to handle */
1107
+ if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {
1108
+ if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {
1109
+ return false;
1042
1110
  }
1043
- /* Keep content except for bad-listed elements */
1044
- if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
1045
- const parentNode = getParentNode(currentNode) || currentNode.parentNode;
1046
- const childNodes = getChildNodes(currentNode) || currentNode.childNodes;
1047
- if (childNodes && parentNode) {
1048
- const childCount = childNodes.length;
1049
- for (let i = childCount - 1; i >= 0; --i) {
1050
- const childClone = cloneNode(childNodes[i], true);
1051
- parentNode.insertBefore(childClone, getNextSibling(currentNode));
1052
- }
1053
- }
1111
+ if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) {
1112
+ return false;
1054
1113
  }
1055
- _forceRemove(currentNode);
1056
- return true;
1057
1114
  }
1058
- /* Check whether element has a valid namespace */
1059
- if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {
1060
- _forceRemove(currentNode);
1061
- return true;
1062
- }
1063
- /* Make sure that older browsers don't get fallback-tag mXSS */
1064
- if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(/<\/no(script|embed|frames)/i, currentNode.innerHTML)) {
1065
- _forceRemove(currentNode);
1066
- return true;
1115
+ /* Keep content except for bad-listed elements */
1116
+ if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
1117
+ const parentNode = getParentNode(currentNode) || currentNode.parentNode;
1118
+ const childNodes = getChildNodes(currentNode) || currentNode.childNodes;
1119
+ if (childNodes && parentNode) {
1120
+ const childCount = childNodes.length;
1121
+ for (let i = childCount - 1; i >= 0; --i) {
1122
+ const childClone = cloneNode(childNodes[i], true);
1123
+ parentNode.insertBefore(childClone, getNextSibling(currentNode));
1124
+ }
1125
+ }
1067
1126
  }
1068
- /* Sanitize element content to be template-safe */
1069
- if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) {
1070
- /* Get the element's text content */
1071
- content = currentNode.textContent;
1072
- arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
1073
- content = stringReplace(content, expr, ' ');
1127
+ _forceRemove(currentNode);
1128
+ return true;
1129
+ }
1130
+ /* Check whether element has a valid namespace */
1131
+ if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {
1132
+ _forceRemove(currentNode);
1133
+ return true;
1134
+ }
1135
+ /* Make sure that older browsers don't get fallback-tag mXSS */
1136
+ if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(/<\/no(script|embed|frames)/i, currentNode.innerHTML)) {
1137
+ _forceRemove(currentNode);
1138
+ return true;
1139
+ }
1140
+ /* Sanitize element content to be template-safe */
1141
+ if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) {
1142
+ /* Get the element's text content */
1143
+ content = currentNode.textContent;
1144
+ arrayForEach([MUSTACHE_EXPR$1, ERB_EXPR$1, TMPLIT_EXPR$1], expr => {
1145
+ content = stringReplace(content, expr, ' ');
1146
+ });
1147
+ if (currentNode.textContent !== content) {
1148
+ arrayPush(DOMPurify.removed, {
1149
+ element: currentNode.cloneNode()
1074
1150
  });
1075
- if (currentNode.textContent !== content) {
1076
- arrayPush(DOMPurify.removed, {
1077
- element: currentNode.cloneNode()
1078
- });
1079
- currentNode.textContent = content;
1080
- }
1151
+ currentNode.textContent = content;
1081
1152
  }
1082
- /* Execute a hook if present */
1083
- _executeHooks(hooks.afterSanitizeElements, currentNode, null);
1153
+ }
1154
+ /* Execute a hook if present */
1155
+ _executeHooks(hooks.afterSanitizeElements, currentNode, null);
1156
+ return false;
1157
+ };
1158
+ /**
1159
+ * _isValidAttribute
1160
+ *
1161
+ * @param lcTag Lowercase tag name of containing element.
1162
+ * @param lcName Lowercase attribute name.
1163
+ * @param value Attribute value.
1164
+ * @return Returns true if `value` is valid, otherwise false.
1165
+ */
1166
+ // eslint-disable-next-line complexity
1167
+ const _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {
1168
+ /* FORBID_ATTR must always win, even if ADD_ATTR predicate would allow it */
1169
+ if (FORBID_ATTR[lcName]) {
1084
1170
  return false;
1085
- };
1086
- /**
1087
- * _isValidAttribute
1088
- *
1089
- * @param lcTag Lowercase tag name of containing element.
1090
- * @param lcName Lowercase attribute name.
1091
- * @param value Attribute value.
1092
- * @return Returns true if `value` is valid, otherwise false.
1093
- */
1094
- // eslint-disable-next-line complexity
1095
- const _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {
1096
- /* FORBID_ATTR must always win, even if ADD_ATTR predicate would allow it */
1097
- if (FORBID_ATTR[lcName]) {
1098
- return false;
1099
- }
1100
- /* Make sure attribute cannot clobber */
1101
- if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {
1171
+ }
1172
+ /* Make sure attribute cannot clobber */
1173
+ if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {
1174
+ return false;
1175
+ }
1176
+ const nameIsPermitted = ALLOWED_ATTR[lcName] || EXTRA_ELEMENT_HANDLING.attributeCheck instanceof Function && EXTRA_ELEMENT_HANDLING.attributeCheck(lcName, lcTag);
1177
+ /* Allow valid data-* attributes: At least one character after "-"
1178
+ (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
1179
+ XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)
1180
+ We don't need to check the value; it's always URI safe. */
1181
+ if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR$1, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR$1, lcName)) ; else if (!nameIsPermitted || FORBID_ATTR[lcName]) {
1182
+ if (
1183
+ // First condition does a very basic check if a) it's basically a valid custom element tagname AND
1184
+ // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
1185
+ // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck
1186
+ _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)) ||
1187
+ // Alternative, second condition checks if it's an `is`-attribute, AND
1188
+ // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
1189
+ 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 {
1102
1190
  return false;
1103
1191
  }
1104
- const nameIsPermitted = ALLOWED_ATTR[lcName] || EXTRA_ELEMENT_HANDLING.attributeCheck instanceof Function && EXTRA_ELEMENT_HANDLING.attributeCheck(lcName, lcTag);
1105
- /* Allow valid data-* attributes: At least one character after "-"
1106
- (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
1107
- XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)
1108
- We don't need to check the value; it's always URI safe. */
1109
- if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR, lcName)) ; else if (!nameIsPermitted || FORBID_ATTR[lcName]) {
1110
- if (
1111
- // First condition does a very basic check if a) it's basically a valid custom element tagname AND
1112
- // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
1113
- // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck
1114
- _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)) ||
1115
- // Alternative, second condition checks if it's an `is`-attribute, AND
1116
- // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
1117
- 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 {
1118
- return false;
1119
- }
1120
- /* Check value is safe. First, is attr inert? If so, is safe */
1121
- } 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) {
1122
- return false;
1123
- } else ;
1124
- return true;
1125
- };
1126
- /* Names the HTML spec reserves from valid-custom-element-name; these must
1127
- * never be treated as basic custom elements even when a permissive
1128
- * CUSTOM_ELEMENT_HANDLING.tagNameCheck is configured. */
1129
- 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']);
1130
- /**
1131
- * _isBasicCustomElement
1132
- * checks if at least one dash is included in tagName, and it's not the first char
1133
- * for more sophisticated checking see https://github.com/sindresorhus/validate-element-name
1134
- *
1135
- * @param tagName name of the tag of the node to sanitize
1136
- * @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false.
1137
- */
1138
- const _isBasicCustomElement = function _isBasicCustomElement(tagName) {
1139
- return !RESERVED_CUSTOM_ELEMENT_NAMES[stringToLowerCase(tagName)] && regExpTest(CUSTOM_ELEMENT, tagName);
1192
+ /* Check value is safe. First, is attr inert? If so, is safe */
1193
+ } else if (URI_SAFE_ATTRIBUTES[lcName]) ; else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE$1, ''))) ; else if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]) ; else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA$1, stringReplace(value, ATTR_WHITESPACE$1, ''))) ; else if (value) {
1194
+ return false;
1195
+ } else ;
1196
+ return true;
1197
+ };
1198
+ /* Names the HTML spec reserves from valid-custom-element-name; these must
1199
+ * never be treated as basic custom elements even when a permissive
1200
+ * CUSTOM_ELEMENT_HANDLING.tagNameCheck is configured. */
1201
+ 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']);
1202
+ /**
1203
+ * _isBasicCustomElement
1204
+ * checks if at least one dash is included in tagName, and it's not the first char
1205
+ * for more sophisticated checking see https://github.com/sindresorhus/validate-element-name
1206
+ *
1207
+ * @param tagName name of the tag of the node to sanitize
1208
+ * @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false.
1209
+ */
1210
+ const _isBasicCustomElement = function _isBasicCustomElement(tagName) {
1211
+ return !RESERVED_CUSTOM_ELEMENT_NAMES[stringToLowerCase(tagName)] && regExpTest(CUSTOM_ELEMENT$1, tagName);
1212
+ };
1213
+ /**
1214
+ * _sanitizeAttributes
1215
+ *
1216
+ * @protect attributes
1217
+ * @protect nodeName
1218
+ * @protect removeAttribute
1219
+ * @protect setAttribute
1220
+ *
1221
+ * @param currentNode to sanitize
1222
+ */
1223
+ const _sanitizeAttributes = function _sanitizeAttributes(currentNode) {
1224
+ /* Execute a hook if present */
1225
+ _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null);
1226
+ const attributes = currentNode.attributes;
1227
+ /* Check if we have attributes; if not we might have a text node */
1228
+ if (!attributes || _isClobbered(currentNode)) {
1229
+ return;
1230
+ }
1231
+ const hookEvent = {
1232
+ attrName: '',
1233
+ attrValue: '',
1234
+ keepAttr: true,
1235
+ allowedAttributes: ALLOWED_ATTR,
1236
+ forceKeepAttr: undefined
1140
1237
  };
1141
- /**
1142
- * _sanitizeAttributes
1143
- *
1144
- * @protect attributes
1145
- * @protect nodeName
1146
- * @protect removeAttribute
1147
- * @protect setAttribute
1148
- *
1149
- * @param currentNode to sanitize
1150
- */
1151
- const _sanitizeAttributes = function _sanitizeAttributes(currentNode) {
1238
+ let l = attributes.length;
1239
+ /* Go backwards over all attributes; safely remove bad ones */
1240
+ while (l--) {
1241
+ const attr = attributes[l];
1242
+ const name = attr.name,
1243
+ namespaceURI = attr.namespaceURI,
1244
+ attrValue = attr.value;
1245
+ const lcName = transformCaseFunc(name);
1246
+ const initValue = attrValue;
1247
+ let value = name === 'value' ? initValue : stringTrim(initValue);
1152
1248
  /* Execute a hook if present */
1153
- _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null);
1154
- const {
1155
- attributes
1156
- } = currentNode;
1157
- /* Check if we have attributes; if not we might have a text node */
1158
- if (!attributes || _isClobbered(currentNode)) {
1159
- return;
1249
+ hookEvent.attrName = lcName;
1250
+ hookEvent.attrValue = value;
1251
+ hookEvent.keepAttr = true;
1252
+ hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set
1253
+ _executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent);
1254
+ value = hookEvent.attrValue;
1255
+ /* Full DOM Clobbering protection via namespace isolation,
1256
+ * Prefix id and name attributes with `user-content-`
1257
+ */
1258
+ if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name') && stringIndexOf(value, SANITIZE_NAMED_PROPS_PREFIX) !== 0) {
1259
+ // Remove the attribute with this value
1260
+ _removeAttribute(name, currentNode);
1261
+ // Prefix the value and later re-create the attribute with the sanitized value
1262
+ value = SANITIZE_NAMED_PROPS_PREFIX + value;
1263
+ }
1264
+ // Else: already prefixed, leave the attribute alone — the prefix is
1265
+ // itself the clobbering protection, and re-applying it is incorrect.
1266
+ /* Work around a security issue with comments inside attributes */
1267
+ if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i, value)) {
1268
+ _removeAttribute(name, currentNode);
1269
+ continue;
1270
+ }
1271
+ /* Make sure we cannot easily use animated hrefs, even if animations are allowed */
1272
+ if (lcName === 'attributename' && stringMatch(value, 'href')) {
1273
+ _removeAttribute(name, currentNode);
1274
+ continue;
1275
+ }
1276
+ /* Did the hooks approve of the attribute? */
1277
+ if (hookEvent.forceKeepAttr) {
1278
+ continue;
1279
+ }
1280
+ /* Did the hooks approve of the attribute? */
1281
+ if (!hookEvent.keepAttr) {
1282
+ _removeAttribute(name, currentNode);
1283
+ continue;
1284
+ }
1285
+ /* Work around a security issue in jQuery 3.0 */
1286
+ if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) {
1287
+ _removeAttribute(name, currentNode);
1288
+ continue;
1289
+ }
1290
+ /* Sanitize attribute content to be template-safe */
1291
+ if (SAFE_FOR_TEMPLATES) {
1292
+ arrayForEach([MUSTACHE_EXPR$1, ERB_EXPR$1, TMPLIT_EXPR$1], expr => {
1293
+ value = stringReplace(value, expr, ' ');
1294
+ });
1160
1295
  }
1161
- const hookEvent = {
1162
- attrName: '',
1163
- attrValue: '',
1164
- keepAttr: true,
1165
- allowedAttributes: ALLOWED_ATTR,
1166
- forceKeepAttr: undefined
1167
- };
1168
- let l = attributes.length;
1169
- /* Go backwards over all attributes; safely remove bad ones */
1170
- while (l--) {
1171
- const attr = attributes[l];
1172
- const {
1173
- name,
1174
- namespaceURI,
1175
- value: attrValue
1176
- } = attr;
1177
- const lcName = transformCaseFunc(name);
1178
- const initValue = attrValue;
1179
- let value = name === 'value' ? initValue : stringTrim(initValue);
1180
- /* Execute a hook if present */
1181
- hookEvent.attrName = lcName;
1182
- hookEvent.attrValue = value;
1183
- hookEvent.keepAttr = true;
1184
- hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set
1185
- _executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent);
1186
- value = hookEvent.attrValue;
1187
- /* Full DOM Clobbering protection via namespace isolation,
1188
- * Prefix id and name attributes with `user-content-`
1189
- */
1190
- if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name') && stringIndexOf(value, SANITIZE_NAMED_PROPS_PREFIX) !== 0) {
1191
- // Remove the attribute with this value
1192
- _removeAttribute(name, currentNode);
1193
- // Prefix the value and later re-create the attribute with the sanitized value
1194
- value = SANITIZE_NAMED_PROPS_PREFIX + value;
1195
- }
1196
- // Else: already prefixed, leave the attribute alone — the prefix is
1197
- // itself the clobbering protection, and re-applying it is incorrect.
1198
- /* Work around a security issue with comments inside attributes */
1199
- if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i, value)) {
1200
- _removeAttribute(name, currentNode);
1201
- continue;
1202
- }
1203
- /* Make sure we cannot easily use animated hrefs, even if animations are allowed */
1204
- if (lcName === 'attributename' && stringMatch(value, 'href')) {
1205
- _removeAttribute(name, currentNode);
1206
- continue;
1207
- }
1208
- /* Did the hooks approve of the attribute? */
1209
- if (hookEvent.forceKeepAttr) {
1210
- continue;
1211
- }
1212
- /* Did the hooks approve of the attribute? */
1213
- if (!hookEvent.keepAttr) {
1214
- _removeAttribute(name, currentNode);
1215
- continue;
1216
- }
1217
- /* Work around a security issue in jQuery 3.0 */
1218
- if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) {
1219
- _removeAttribute(name, currentNode);
1220
- continue;
1221
- }
1222
- /* Sanitize attribute content to be template-safe */
1223
- if (SAFE_FOR_TEMPLATES) {
1224
- arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
1225
- value = stringReplace(value, expr, ' ');
1226
- });
1227
- }
1228
- /* Is `value` valid for this attribute? */
1229
- const lcTag = transformCaseFunc(currentNode.nodeName);
1230
- if (!_isValidAttribute(lcTag, lcName, value)) {
1231
- _removeAttribute(name, currentNode);
1232
- continue;
1233
- }
1234
- /* Handle attributes that require Trusted Types */
1235
- if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function') {
1236
- if (namespaceURI) ; else {
1237
- switch (trustedTypes.getAttributeType(lcTag, lcName)) {
1238
- case 'TrustedHTML':
1239
- {
1240
- value = trustedTypesPolicy.createHTML(value);
1241
- break;
1242
- }
1243
- case 'TrustedScriptURL':
1244
- {
1245
- value = trustedTypesPolicy.createScriptURL(value);
1246
- break;
1247
- }
1248
- }
1296
+ /* Is `value` valid for this attribute? */
1297
+ const lcTag = transformCaseFunc(currentNode.nodeName);
1298
+ if (!_isValidAttribute(lcTag, lcName, value)) {
1299
+ _removeAttribute(name, currentNode);
1300
+ continue;
1301
+ }
1302
+ /* Handle attributes that require Trusted Types */
1303
+ if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function') {
1304
+ if (namespaceURI) ; else {
1305
+ switch (trustedTypes.getAttributeType(lcTag, lcName)) {
1306
+ case 'TrustedHTML':
1307
+ {
1308
+ value = trustedTypesPolicy.createHTML(value);
1309
+ break;
1310
+ }
1311
+ case 'TrustedScriptURL':
1312
+ {
1313
+ value = trustedTypesPolicy.createScriptURL(value);
1314
+ break;
1315
+ }
1249
1316
  }
1250
1317
  }
1251
- /* Handle invalid data-* attribute set by try-catching it */
1252
- if (value !== initValue) {
1253
- try {
1254
- if (namespaceURI) {
1255
- currentNode.setAttributeNS(namespaceURI, name, value);
1256
- } else {
1257
- /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
1258
- currentNode.setAttribute(name, value);
1259
- }
1260
- if (_isClobbered(currentNode)) {
1261
- _forceRemove(currentNode);
1262
- } else {
1263
- arrayPop(DOMPurify.removed);
1264
- }
1265
- } catch (_) {
1266
- _removeAttribute(name, currentNode);
1318
+ }
1319
+ /* Handle invalid data-* attribute set by try-catching it */
1320
+ if (value !== initValue) {
1321
+ try {
1322
+ if (namespaceURI) {
1323
+ currentNode.setAttributeNS(namespaceURI, name, value);
1324
+ } else {
1325
+ /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
1326
+ currentNode.setAttribute(name, value);
1327
+ }
1328
+ if (_isClobbered(currentNode)) {
1329
+ _forceRemove(currentNode);
1330
+ } else {
1331
+ arrayPop(DOMPurify.removed);
1267
1332
  }
1333
+ } catch (_) {
1334
+ _removeAttribute(name, currentNode);
1268
1335
  }
1269
1336
  }
1337
+ }
1338
+ /* Execute a hook if present */
1339
+ _executeHooks(hooks.afterSanitizeAttributes, currentNode, null);
1340
+ };
1341
+ /**
1342
+ * _sanitizeShadowDOM
1343
+ *
1344
+ * @param fragment to iterate over recursively
1345
+ */
1346
+ const _sanitizeShadowDOM2 = function _sanitizeShadowDOM(fragment) {
1347
+ let shadowNode = null;
1348
+ const shadowIterator = _createNodeIterator(fragment);
1349
+ /* Execute a hook if present */
1350
+ _executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null);
1351
+ while (shadowNode = shadowIterator.nextNode()) {
1270
1352
  /* Execute a hook if present */
1271
- _executeHooks(hooks.afterSanitizeAttributes, currentNode, null);
1272
- };
1273
- /**
1274
- * _sanitizeShadowDOM
1275
- *
1276
- * @param fragment to iterate over recursively
1277
- */
1278
- const _sanitizeShadowDOM2 = function _sanitizeShadowDOM(fragment) {
1279
- let shadowNode = null;
1280
- const shadowIterator = _createNodeIterator(fragment);
1281
- /* Execute a hook if present */
1282
- _executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null);
1283
- while (shadowNode = shadowIterator.nextNode()) {
1284
- /* Execute a hook if present */
1285
- _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null);
1286
- /* Sanitize tags and elements */
1287
- _sanitizeElements(shadowNode);
1288
- /* Check attributes next */
1289
- _sanitizeAttributes(shadowNode);
1290
- /* Deep shadow DOM detected */
1291
- if (shadowNode.content instanceof DocumentFragment) {
1292
- _sanitizeShadowDOM2(shadowNode.content);
1293
- }
1353
+ _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null);
1354
+ /* Sanitize tags and elements */
1355
+ _sanitizeElements(shadowNode);
1356
+ /* Check attributes next */
1357
+ _sanitizeAttributes(shadowNode);
1358
+ /* Deep shadow DOM detected */
1359
+ if (shadowNode.content instanceof DocumentFragment) {
1360
+ _sanitizeShadowDOM2(shadowNode.content);
1294
1361
  }
1295
- /* Execute a hook if present */
1296
- _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null);
1297
- };
1298
- // eslint-disable-next-line complexity
1299
- DOMPurify.sanitize = function (dirty) {
1300
- let cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1301
- let body = null;
1302
- let importedNode = null;
1303
- let currentNode = null;
1304
- let returnNode = null;
1305
- /* Make sure we have a string to sanitize.
1306
- DO NOT return early, as this will return the wrong type if
1307
- the user has requested a DOM object rather than a string */
1308
- IS_EMPTY_INPUT = !dirty;
1309
- if (IS_EMPTY_INPUT) {
1310
- dirty = '<!-->';
1362
+ }
1363
+ /* Execute a hook if present */
1364
+ _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null);
1365
+ };
1366
+ /**
1367
+ * _sanitizeAttachedShadowRoots
1368
+ *
1369
+ * Walks `root` and feeds every attached shadow root we encounter into
1370
+ * the existing _sanitizeShadowDOM pipeline. The default node iterator
1371
+ * does not descend into shadow trees, so nodes inside an attached
1372
+ * shadow root would otherwise be skipped entirely.
1373
+ *
1374
+ * Two real input paths put attached shadow roots in front of us:
1375
+ * 1. IN_PLACE on a DOM node that already has shadow roots attached.
1376
+ * 2. DOM-node input where importNode(dirty, true) deep-clones the
1377
+ * shadow root because it was created with `clonable: true`.
1378
+ *
1379
+ * This pass runs once, up front, so the main iteration loop (and the
1380
+ * existing _sanitizeShadowDOM template-content recursion) stay
1381
+ * untouched — string-input paths are not affected.
1382
+ *
1383
+ * @param root the subtree root to walk for attached shadow roots
1384
+ */
1385
+ const _sanitizeAttachedShadowRoots2 = function _sanitizeAttachedShadowRoots(root) {
1386
+ if (root.nodeType === NODE_TYPE.element && root.shadowRoot instanceof DocumentFragment) {
1387
+ const sr = root.shadowRoot;
1388
+ // Recurse first so that nested shadow roots are reached even if
1389
+ // _sanitizeShadowDOM removes hosts at this level.
1390
+ _sanitizeAttachedShadowRoots2(sr);
1391
+ _sanitizeShadowDOM2(sr);
1392
+ }
1393
+ // Snapshot children before recursing. Sanitization of one subtree
1394
+ // (e.g. via an uponSanitizeShadowNode hook) may detach siblings,
1395
+ // and naive nextSibling traversal would silently skip the rest of
1396
+ // the list once a node is detached.
1397
+ const childNodes = root.childNodes;
1398
+ if (!childNodes) {
1399
+ return;
1400
+ }
1401
+ const snapshot = [];
1402
+ arrayForEach(childNodes, child => {
1403
+ arrayPush(snapshot, child);
1404
+ });
1405
+ for (const child of snapshot) {
1406
+ _sanitizeAttachedShadowRoots2(child);
1407
+ }
1408
+ };
1409
+ // eslint-disable-next-line complexity
1410
+ DOMPurify.sanitize = function (dirty) {
1411
+ let cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1412
+ let body = null;
1413
+ let importedNode = null;
1414
+ let currentNode = null;
1415
+ let returnNode = null;
1416
+ /* Make sure we have a string to sanitize.
1417
+ DO NOT return early, as this will return the wrong type if
1418
+ the user has requested a DOM object rather than a string */
1419
+ IS_EMPTY_INPUT = !dirty;
1420
+ if (IS_EMPTY_INPUT) {
1421
+ dirty = '<!-->';
1422
+ }
1423
+ /* Stringify, in case dirty is an object */
1424
+ if (typeof dirty !== 'string' && !_isNode(dirty)) {
1425
+ dirty = stringifyValue(dirty);
1426
+ if (typeof dirty !== 'string') {
1427
+ throw typeErrorCreate('dirty is not a string, aborting');
1311
1428
  }
1312
- /* Stringify, in case dirty is an object */
1313
- if (typeof dirty !== 'string' && !_isNode(dirty)) {
1314
- dirty = stringifyValue(dirty);
1315
- if (typeof dirty !== 'string') {
1316
- throw typeErrorCreate('dirty is not a string, aborting');
1429
+ }
1430
+ /* Return dirty HTML if DOMPurify cannot run */
1431
+ if (!DOMPurify.isSupported) {
1432
+ return dirty;
1433
+ }
1434
+ /* Assign config vars */
1435
+ if (!SET_CONFIG) {
1436
+ _parseConfig(cfg);
1437
+ }
1438
+ /* Clean up removed elements */
1439
+ DOMPurify.removed = [];
1440
+ /* Check if dirty is correctly typed for IN_PLACE */
1441
+ if (typeof dirty === 'string') {
1442
+ IN_PLACE = false;
1443
+ }
1444
+ if (IN_PLACE) {
1445
+ /* Do some early pre-sanitization to avoid unsafe root nodes */
1446
+ const nn = dirty.nodeName;
1447
+ if (typeof nn === 'string') {
1448
+ const tagName = transformCaseFunc(nn);
1449
+ if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
1450
+ throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');
1317
1451
  }
1318
1452
  }
1319
- /* Return dirty HTML if DOMPurify cannot run */
1320
- if (!DOMPurify.isSupported) {
1321
- return dirty;
1322
- }
1323
- /* Assign config vars */
1324
- if (!SET_CONFIG) {
1325
- _parseConfig(cfg);
1326
- }
1327
- /* Clean up removed elements */
1328
- DOMPurify.removed = [];
1329
- /* Check if dirty is correctly typed for IN_PLACE */
1330
- if (typeof dirty === 'string') {
1331
- IN_PLACE = false;
1332
- }
1333
- if (IN_PLACE) {
1334
- /* Do some early pre-sanitization to avoid unsafe root nodes */
1335
- const nn = dirty.nodeName;
1336
- if (typeof nn === 'string') {
1337
- const tagName = transformCaseFunc(nn);
1338
- if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
1339
- throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');
1340
- }
1341
- }
1342
- } else if (dirty instanceof Node) {
1343
- /* If dirty is a DOM element, append to an empty document to avoid
1344
- elements being stripped by the parser */
1345
- body = _initDocument('<!---->');
1346
- importedNode = body.ownerDocument.importNode(dirty, true);
1347
- if (importedNode.nodeType === NODE_TYPE.element && importedNode.nodeName === 'BODY') {
1348
- /* Node is already a body, use as is */
1349
- body = importedNode;
1350
- } else if (importedNode.nodeName === 'HTML') {
1351
- body = importedNode;
1352
- } else {
1353
- // eslint-disable-next-line unicorn/prefer-dom-node-append
1354
- body.appendChild(importedNode);
1355
- }
1453
+ /* Sanitize attached shadow roots before the main iterator runs.
1454
+ The iterator does not descend into shadow trees. */
1455
+ _sanitizeAttachedShadowRoots2(dirty);
1456
+ } else if (_isNode(dirty)) {
1457
+ /* If dirty is a DOM element, append to an empty document to avoid
1458
+ elements being stripped by the parser */
1459
+ body = _initDocument('<!---->');
1460
+ importedNode = body.ownerDocument.importNode(dirty, true);
1461
+ if (importedNode.nodeType === NODE_TYPE.element && importedNode.nodeName === 'BODY') {
1462
+ /* Node is already a body, use as is */
1463
+ body = importedNode;
1464
+ } else if (importedNode.nodeName === 'HTML') {
1465
+ body = importedNode;
1356
1466
  } else {
1357
- /* Exit directly if we have nothing to do */
1358
- if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT &&
1359
- // eslint-disable-next-line unicorn/prefer-includes
1360
- dirty.indexOf('<') === -1) {
1361
- return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;
1362
- }
1363
- /* Initialize the document to work on */
1364
- body = _initDocument(dirty);
1365
- /* Check we have a DOM node from the data */
1366
- if (!body) {
1367
- return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';
1368
- }
1369
- }
1370
- /* Remove first element node (ours) if FORCE_BODY is set */
1371
- if (body && FORCE_BODY) {
1372
- _forceRemove(body.firstChild);
1373
- }
1374
- /* Get node iterator */
1375
- const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body);
1376
- /* Now start iterating over the created document */
1377
- while (currentNode = nodeIterator.nextNode()) {
1378
- /* Sanitize tags and elements */
1379
- _sanitizeElements(currentNode);
1380
- /* Check attributes next */
1381
- _sanitizeAttributes(currentNode);
1382
- /* Shadow DOM detected, sanitize it */
1383
- if (currentNode.content instanceof DocumentFragment) {
1384
- _sanitizeShadowDOM2(currentNode.content);
1385
- }
1386
- }
1387
- /* If we sanitized `dirty` in-place, return it. */
1388
- if (IN_PLACE) {
1389
- return dirty;
1467
+ // eslint-disable-next-line unicorn/prefer-dom-node-append
1468
+ body.appendChild(importedNode);
1469
+ }
1470
+ /* Clonable shadow roots are deep-cloned by importNode(); sanitize
1471
+ them before the main iterator runs, since the iterator does not
1472
+ descend into shadow trees. */
1473
+ _sanitizeAttachedShadowRoots2(importedNode);
1474
+ } else {
1475
+ /* Exit directly if we have nothing to do */
1476
+ if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT &&
1477
+ // eslint-disable-next-line unicorn/prefer-includes
1478
+ dirty.indexOf('<') === -1) {
1479
+ return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;
1390
1480
  }
1391
- /* Return sanitized string or DOM */
1392
- if (RETURN_DOM) {
1393
- if (SAFE_FOR_TEMPLATES) {
1394
- body.normalize();
1395
- let html = body.innerHTML;
1396
- arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
1397
- html = stringReplace(html, expr, ' ');
1398
- });
1399
- body.innerHTML = html;
1400
- }
1401
- if (RETURN_DOM_FRAGMENT) {
1402
- returnNode = createDocumentFragment.call(body.ownerDocument);
1403
- while (body.firstChild) {
1404
- // eslint-disable-next-line unicorn/prefer-dom-node-append
1405
- returnNode.appendChild(body.firstChild);
1406
- }
1407
- } else {
1408
- returnNode = body;
1409
- }
1410
- if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) {
1411
- /*
1412
- AdoptNode() is not used because internal state is not reset
1413
- (e.g. the past names map of a HTMLFormElement), this is safe
1414
- in theory but we would rather not risk another attack vector.
1415
- The state that is cloned by importNode() is explicitly defined
1416
- by the specs.
1417
- */
1418
- returnNode = importNode.call(originalDocument, returnNode, true);
1419
- }
1420
- return returnNode;
1481
+ /* Initialize the document to work on */
1482
+ body = _initDocument(dirty);
1483
+ /* Check we have a DOM node from the data */
1484
+ if (!body) {
1485
+ return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';
1421
1486
  }
1422
- let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;
1423
- /* Serialize doctype if allowed */
1424
- if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) {
1425
- serializedHTML = '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\n' + serializedHTML;
1487
+ }
1488
+ /* Remove first element node (ours) if FORCE_BODY is set */
1489
+ if (body && FORCE_BODY) {
1490
+ _forceRemove(body.firstChild);
1491
+ }
1492
+ /* Get node iterator */
1493
+ const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body);
1494
+ /* Now start iterating over the created document */
1495
+ while (currentNode = nodeIterator.nextNode()) {
1496
+ /* Sanitize tags and elements */
1497
+ _sanitizeElements(currentNode);
1498
+ /* Check attributes next */
1499
+ _sanitizeAttributes(currentNode);
1500
+ /* Shadow DOM detected, sanitize it */
1501
+ if (currentNode.content instanceof DocumentFragment) {
1502
+ _sanitizeShadowDOM2(currentNode.content);
1426
1503
  }
1427
- /* Sanitize final string template-safe */
1504
+ }
1505
+ /* If we sanitized `dirty` in-place, return it. */
1506
+ if (IN_PLACE) {
1428
1507
  if (SAFE_FOR_TEMPLATES) {
1429
- arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
1430
- serializedHTML = stringReplace(serializedHTML, expr, ' ');
1431
- });
1432
- }
1433
- return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;
1434
- };
1435
- DOMPurify.setConfig = function () {
1436
- let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1437
- _parseConfig(cfg);
1438
- SET_CONFIG = true;
1439
- };
1440
- DOMPurify.clearConfig = function () {
1441
- CONFIG = null;
1442
- SET_CONFIG = false;
1443
- };
1444
- DOMPurify.isValidAttribute = function (tag, attr, value) {
1445
- /* Initialize shared config vars if necessary. */
1446
- if (!CONFIG) {
1447
- _parseConfig({});
1508
+ _scrubTemplateExpressions(dirty);
1448
1509
  }
1449
- const lcTag = transformCaseFunc(tag);
1450
- const lcName = transformCaseFunc(attr);
1451
- return _isValidAttribute(lcTag, lcName, value);
1452
- };
1453
- DOMPurify.addHook = function (entryPoint, hookFunction) {
1454
- if (typeof hookFunction !== 'function') {
1455
- return;
1456
- }
1457
- arrayPush(hooks[entryPoint], hookFunction);
1458
- };
1459
- DOMPurify.removeHook = function (entryPoint, hookFunction) {
1460
- if (hookFunction !== undefined) {
1461
- const index = arrayLastIndexOf(hooks[entryPoint], hookFunction);
1462
- return index === -1 ? undefined : arraySplice(hooks[entryPoint], index, 1)[0];
1510
+ return dirty;
1511
+ }
1512
+ /* Return sanitized string or DOM */
1513
+ if (RETURN_DOM) {
1514
+ if (SAFE_FOR_TEMPLATES) {
1515
+ _scrubTemplateExpressions(body);
1463
1516
  }
1464
- return arrayPop(hooks[entryPoint]);
1465
- };
1466
- DOMPurify.removeHooks = function (entryPoint) {
1467
- hooks[entryPoint] = [];
1468
- };
1469
- DOMPurify.removeAllHooks = function () {
1470
- hooks = _createHooksMap();
1471
- };
1472
- return DOMPurify;
1473
- }
1474
- var purify = createDOMPurify();
1517
+ if (RETURN_DOM_FRAGMENT) {
1518
+ returnNode = createDocumentFragment.call(body.ownerDocument);
1519
+ while (body.firstChild) {
1520
+ // eslint-disable-next-line unicorn/prefer-dom-node-append
1521
+ returnNode.appendChild(body.firstChild);
1522
+ }
1523
+ } else {
1524
+ returnNode = body;
1525
+ }
1526
+ if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) {
1527
+ /*
1528
+ AdoptNode() is not used because internal state is not reset
1529
+ (e.g. the past names map of a HTMLFormElement), this is safe
1530
+ in theory but we would rather not risk another attack vector.
1531
+ The state that is cloned by importNode() is explicitly defined
1532
+ by the specs.
1533
+ */
1534
+ returnNode = importNode.call(originalDocument, returnNode, true);
1535
+ }
1536
+ return returnNode;
1537
+ }
1538
+ let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;
1539
+ /* Serialize doctype if allowed */
1540
+ if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) {
1541
+ serializedHTML = '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\n' + serializedHTML;
1542
+ }
1543
+ /* Sanitize final string template-safe */
1544
+ if (SAFE_FOR_TEMPLATES) {
1545
+ arrayForEach([MUSTACHE_EXPR$1, ERB_EXPR$1, TMPLIT_EXPR$1], expr => {
1546
+ serializedHTML = stringReplace(serializedHTML, expr, ' ');
1547
+ });
1548
+ }
1549
+ return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;
1550
+ };
1551
+ DOMPurify.setConfig = function () {
1552
+ let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1553
+ _parseConfig(cfg);
1554
+ SET_CONFIG = true;
1555
+ };
1556
+ DOMPurify.clearConfig = function () {
1557
+ CONFIG = null;
1558
+ SET_CONFIG = false;
1559
+ };
1560
+ DOMPurify.isValidAttribute = function (tag, attr, value) {
1561
+ /* Initialize shared config vars if necessary. */
1562
+ if (!CONFIG) {
1563
+ _parseConfig({});
1564
+ }
1565
+ const lcTag = transformCaseFunc(tag);
1566
+ const lcName = transformCaseFunc(attr);
1567
+ return _isValidAttribute(lcTag, lcName, value);
1568
+ };
1569
+ DOMPurify.addHook = function (entryPoint, hookFunction) {
1570
+ if (typeof hookFunction !== 'function') {
1571
+ return;
1572
+ }
1573
+ arrayPush(hooks[entryPoint], hookFunction);
1574
+ };
1575
+ DOMPurify.removeHook = function (entryPoint, hookFunction) {
1576
+ if (hookFunction !== undefined) {
1577
+ const index = arrayLastIndexOf(hooks[entryPoint], hookFunction);
1578
+ return index === -1 ? undefined : arraySplice(hooks[entryPoint], index, 1)[0];
1579
+ }
1580
+ return arrayPop(hooks[entryPoint]);
1581
+ };
1582
+ DOMPurify.removeHooks = function (entryPoint) {
1583
+ hooks[entryPoint] = [];
1584
+ };
1585
+ DOMPurify.removeAllHooks = function () {
1586
+ hooks = _createHooksMap();
1587
+ };
1588
+ return DOMPurify;
1589
+ }
1590
+ var purify = createDOMPurify();
1475
1591
 
1476
- return purify;
1592
+ return purify;
1477
1593
 
1478
1594
  }));
1479
1595
  //# sourceMappingURL=purify.js.map