@wix/entity-advanced-permissions 1.1421.0 → 1.1422.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -34383,6 +34383,9 @@ var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
34383
34383
  /******/ return module.exports;
34384
34384
  /******/ }
34385
34385
  /******/
34386
+ /******/ // expose the modules object (__webpack_modules__)
34387
+ /******/ __webpack_require__.m = __webpack_modules__;
34388
+ /******/
34386
34389
  /************************************************************************/
34387
34390
  /******/ /* webpack/runtime/compat get default export */
34388
34391
  /******/ (() => {
@@ -34438,6 +34441,37 @@ var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
34438
34441
  /******/ };
34439
34442
  /******/ })();
34440
34443
  /******/
34444
+ /******/ /* webpack/runtime/ensure chunk */
34445
+ /******/ (() => {
34446
+ /******/ __webpack_require__.f = {};
34447
+ /******/ // This file contains only the entry chunk.
34448
+ /******/ // The chunk loading function for additional chunks
34449
+ /******/ __webpack_require__.e = (chunkId) => {
34450
+ /******/ return Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {
34451
+ /******/ __webpack_require__.f[key](chunkId, promises);
34452
+ /******/ return promises;
34453
+ /******/ }, []));
34454
+ /******/ };
34455
+ /******/ })();
34456
+ /******/
34457
+ /******/ /* webpack/runtime/get javascript chunk filename */
34458
+ /******/ (() => {
34459
+ /******/ // This function allow to reference async chunks
34460
+ /******/ __webpack_require__.u = (chunkId) => {
34461
+ /******/ // return url for filenames based on template
34462
+ /******/ return "" + chunkId + ".chunk.js";
34463
+ /******/ };
34464
+ /******/ })();
34465
+ /******/
34466
+ /******/ /* webpack/runtime/get mini-css chunk filename */
34467
+ /******/ (() => {
34468
+ /******/ // This function allow to reference async chunks
34469
+ /******/ __webpack_require__.miniCssF = (chunkId) => {
34470
+ /******/ // return url for filenames based on template
34471
+ /******/ return undefined;
34472
+ /******/ };
34473
+ /******/ })();
34474
+ /******/
34441
34475
  /******/ /* webpack/runtime/global */
34442
34476
  /******/ (() => {
34443
34477
  /******/ __webpack_require__.g = (function() {
@@ -34455,6 +34489,54 @@ var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
34455
34489
  /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
34456
34490
  /******/ })();
34457
34491
  /******/
34492
+ /******/ /* webpack/runtime/load script */
34493
+ /******/ (() => {
34494
+ /******/ var inProgress = {};
34495
+ /******/ var dataWebpackPrefix = "_wix_entity_advanced_permissions:";
34496
+ /******/ // loadScript function to load a script via script tag
34497
+ /******/ __webpack_require__.l = (url, done, key, chunkId) => {
34498
+ /******/ if(inProgress[url]) { inProgress[url].push(done); return; }
34499
+ /******/ var script, needAttach;
34500
+ /******/ if(key !== undefined) {
34501
+ /******/ var scripts = document.getElementsByTagName("script");
34502
+ /******/ for(var i = 0; i < scripts.length; i++) {
34503
+ /******/ var s = scripts[i];
34504
+ /******/ if(s.getAttribute("src") == url || s.getAttribute("data-webpack") == dataWebpackPrefix + key) { script = s; break; }
34505
+ /******/ }
34506
+ /******/ }
34507
+ /******/ if(!script) {
34508
+ /******/ needAttach = true;
34509
+ /******/ script = document.createElement('script');
34510
+ /******/
34511
+ /******/ script.charset = 'utf-8';
34512
+ /******/ if (__webpack_require__.nc) {
34513
+ /******/ script.setAttribute("nonce", __webpack_require__.nc);
34514
+ /******/ }
34515
+ /******/ script.setAttribute("data-webpack", dataWebpackPrefix + key);
34516
+ /******/
34517
+ /******/ script.src = url;
34518
+ /******/ if (script.src.indexOf(window.location.origin + '/') !== 0) {
34519
+ /******/ script.crossOrigin = "anonymous";
34520
+ /******/ }
34521
+ /******/ }
34522
+ /******/ inProgress[url] = [done];
34523
+ /******/ var onScriptComplete = (prev, event) => {
34524
+ /******/ // avoid mem leaks in IE.
34525
+ /******/ script.onerror = script.onload = null;
34526
+ /******/ clearTimeout(timeout);
34527
+ /******/ var doneFns = inProgress[url];
34528
+ /******/ delete inProgress[url];
34529
+ /******/ script.parentNode && script.parentNode.removeChild(script);
34530
+ /******/ doneFns && doneFns.forEach((fn) => (fn(event)));
34531
+ /******/ if(prev) return prev(event);
34532
+ /******/ }
34533
+ /******/ var timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), 120000);
34534
+ /******/ script.onerror = onScriptComplete.bind(null, script.onerror);
34535
+ /******/ script.onload = onScriptComplete.bind(null, script.onload);
34536
+ /******/ needAttach && document.head.appendChild(script);
34537
+ /******/ };
34538
+ /******/ })();
34539
+ /******/
34458
34540
  /******/ /* webpack/runtime/make namespace object */
34459
34541
  /******/ (() => {
34460
34542
  /******/ // define __esModule on exports
@@ -34595,6 +34677,101 @@ var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
34595
34677
  /******/ })(__webpack_require__)
34596
34678
  /******/ })();
34597
34679
  /******/
34680
+ /******/ /* webpack/runtime/publicPath */
34681
+ /******/ (() => {
34682
+ /******/ __webpack_require__.p = "https://static.parastorage.com/services/entity-advanced-permissions/2d3c9f417fccd2d8cf1a6f97d92b2559fe9a858751e61d49b7832f58/";
34683
+ /******/ })();
34684
+ /******/
34685
+ /******/ /* webpack/runtime/jsonp chunk loading */
34686
+ /******/ (() => {
34687
+ /******/ // no baseURI
34688
+ /******/
34689
+ /******/ // object to store loaded and loading chunks
34690
+ /******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched
34691
+ /******/ // [resolve, reject, Promise] = chunk loading, 0 = chunk loaded
34692
+ /******/ var installedChunks = {
34693
+ /******/ 318: 0
34694
+ /******/ };
34695
+ /******/
34696
+ /******/ __webpack_require__.f.j = (chunkId, promises) => {
34697
+ /******/ // JSONP chunk loading for javascript
34698
+ /******/ var installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;
34699
+ /******/ if(installedChunkData !== 0) { // 0 means "already installed".
34700
+ /******/
34701
+ /******/ // a Promise means "currently loading".
34702
+ /******/ if(installedChunkData) {
34703
+ /******/ promises.push(installedChunkData[2]);
34704
+ /******/ } else {
34705
+ /******/ if(true) { // all chunks have JS
34706
+ /******/ // setup Promise in chunk cache
34707
+ /******/ var promise = new Promise((resolve, reject) => (installedChunkData = installedChunks[chunkId] = [resolve, reject]));
34708
+ /******/ promises.push(installedChunkData[2] = promise);
34709
+ /******/
34710
+ /******/ // start chunk loading
34711
+ /******/ var url = __webpack_require__.p + __webpack_require__.u(chunkId);
34712
+ /******/ // create error before stack unwound to get useful stacktrace later
34713
+ /******/ var error = new Error();
34714
+ /******/ var loadingEnded = (event) => {
34715
+ /******/ if(__webpack_require__.o(installedChunks, chunkId)) {
34716
+ /******/ installedChunkData = installedChunks[chunkId];
34717
+ /******/ if(installedChunkData !== 0) installedChunks[chunkId] = undefined;
34718
+ /******/ if(installedChunkData) {
34719
+ /******/ var errorType = event && (event.type === 'load' ? 'missing' : event.type);
34720
+ /******/ var realSrc = event && event.target && event.target.src;
34721
+ /******/ error.message = 'Loading chunk ' + chunkId + ' failed.\n(' + errorType + ': ' + realSrc + ')';
34722
+ /******/ error.name = 'ChunkLoadError';
34723
+ /******/ error.type = errorType;
34724
+ /******/ error.request = realSrc;
34725
+ /******/ installedChunkData[1](error);
34726
+ /******/ }
34727
+ /******/ }
34728
+ /******/ };
34729
+ /******/ __webpack_require__.l(url, loadingEnded, "chunk-" + chunkId, chunkId);
34730
+ /******/ }
34731
+ /******/ }
34732
+ /******/ }
34733
+ /******/ };
34734
+ /******/
34735
+ /******/ // no prefetching
34736
+ /******/
34737
+ /******/ // no preloaded
34738
+ /******/
34739
+ /******/ // no HMR
34740
+ /******/
34741
+ /******/ // no HMR manifest
34742
+ /******/
34743
+ /******/ // no on chunks loaded
34744
+ /******/
34745
+ /******/ // install a JSONP callback for chunk loading
34746
+ /******/ var webpackJsonpCallback = (parentChunkLoadingFunction, data) => {
34747
+ /******/ var [chunkIds, moreModules, runtime] = data;
34748
+ /******/ // add "moreModules" to the modules object,
34749
+ /******/ // then flag all "chunkIds" as loaded and fire callback
34750
+ /******/ var moduleId, chunkId, i = 0;
34751
+ /******/ if(chunkIds.some((id) => (installedChunks[id] !== 0))) {
34752
+ /******/ for(moduleId in moreModules) {
34753
+ /******/ if(__webpack_require__.o(moreModules, moduleId)) {
34754
+ /******/ __webpack_require__.m[moduleId] = moreModules[moduleId];
34755
+ /******/ }
34756
+ /******/ }
34757
+ /******/ if(runtime) var result = runtime(__webpack_require__);
34758
+ /******/ }
34759
+ /******/ if(parentChunkLoadingFunction) parentChunkLoadingFunction(data);
34760
+ /******/ for(;i < chunkIds.length; i++) {
34761
+ /******/ chunkId = chunkIds[i];
34762
+ /******/ if(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {
34763
+ /******/ installedChunks[chunkId][0]();
34764
+ /******/ }
34765
+ /******/ installedChunks[chunkId] = 0;
34766
+ /******/ }
34767
+ /******/
34768
+ /******/ }
34769
+ /******/
34770
+ /******/ var chunkLoadingGlobal = (typeof self !== 'undefined' ? self : this)["webpackJsonp__wix_entity_advanced_permissions"] = (typeof self !== 'undefined' ? self : this)["webpackJsonp__wix_entity_advanced_permissions"] || [];
34771
+ /******/ chunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));
34772
+ /******/ chunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));
34773
+ /******/ })();
34774
+ /******/
34598
34775
  /******/ /* webpack/runtime/nonce */
34599
34776
  /******/ (() => {
34600
34777
  /******/ __webpack_require__.nc = undefined;
@@ -34606,7 +34783,7 @@ var __webpack_exports__ = {};
34606
34783
  (() => {
34607
34784
  "use strict";
34608
34785
  /*!********************************!*\
34609
- !*** ./index.ts + 566 modules ***!
34786
+ !*** ./index.ts + 565 modules ***!
34610
34787
  \********************************/
34611
34788
  // ESM COMPAT FLAG
34612
34789
  __webpack_require__.r(__webpack_exports__);
@@ -35533,7 +35710,7 @@ if(false /* HMR */) // removed by dead control flow
35533
35710
  {}
35534
35711
 
35535
35712
  ;// ../../../node_modules/@wix/design-system/dist/esm/utils/versionedNamespace.js
35536
- const placeholder = 'wds_1_331_0';
35713
+ const placeholder = 'wds_1_334_0';
35537
35714
  const versionedNamespace = placeholder.startsWith('wds_')
35538
35715
  ? placeholder
35539
35716
  : '';
@@ -40556,7 +40733,7 @@ class PopoverComponent extends external_React_.PureComponent {
40556
40733
  if (theme) {
40557
40734
  deprecationLog_deprecationLog('<Popover/> - theme prop is deprecated and will be removed in next major version, please use skin instead');
40558
40735
  }
40559
- return external_React_default().createElement(PopoverCore, { timeout: timeout, ...rest, skin: skin || theme });
40736
+ return (external_React_default().createElement(PopoverCore, { timeout: timeout, ...rest, skin: skin || theme || 'light' }));
40560
40737
  }
40561
40738
  }
40562
40739
  PopoverComponent.displayName = 'Popover';
@@ -40564,7 +40741,6 @@ PopoverComponent.Element = PopoverCore.Element;
40564
40741
  PopoverComponent.Content = PopoverCore.Content;
40565
40742
  PopoverComponent.defaultProps = {
40566
40743
  appendTo: 'parent',
40567
- theme: 'light', // TODO: add default skin value once theme is removed
40568
40744
  animate: false,
40569
40745
  interactive: true,
40570
40746
  };
@@ -40778,7 +40954,7 @@ const Tooltip = (0,external_React_.forwardRef)((componentProps, ref) => {
40778
40954
  // @ts-ignore
40779
40955
  external_React_default().createElement(RawText, { dataHook: constants_dataHooks.tooltipText, size: textSize, light: true, className: Tooltip_classes_classes.text(), renderChildren: ({ text }) => text, renderElement: ({ element }) => element }, content)) : (content)));
40780
40956
  }, [content, textAlign, size]);
40781
- return (external_React_default().createElement(Popover, { role: "tooltip", showArrow: size !== 'small', className: Tooltip_classes_classes.root({ size, inline }, className), placement: placement, shown: isDisabled ? false : shown, onPointerEnter: trackPointerType, onPointerLeave: trackPointerType, onMouseEnter: isDisabled ? undefined : openFromHover, onMouseLeave: closeFromHover, onPointerDown: onTriggerPointerDown, onClick: onTriggerClick, onContentClick: onContentClick, onClickOutside: close, onEscPress: close, onShow: handleShow, onHide: handleHide, "data-size": size, hideDelay: exitDelay, showDelay: enterDelay, moveBy: moveBy, moveArrowTo: moveArrowTo, appendTo: appendTo, id: ariaLabelledBy || ariaDescribedBy, flip: flip, fixed: fixed, maxWidth: maxWidth, fluid: fluid, disableClickOutsideWhenClosed: true, zIndex: zIndex, interactive: interactive, ...rest, theme: "dark", timeout: TIMEOUT },
40957
+ return (external_React_default().createElement(Popover, { role: "tooltip", showArrow: size !== 'small', className: Tooltip_classes_classes.root({ size, inline }, className), placement: placement, shown: isDisabled ? false : shown, onPointerEnter: trackPointerType, onPointerLeave: trackPointerType, onMouseEnter: isDisabled ? undefined : openFromHover, onMouseLeave: closeFromHover, onPointerDown: onTriggerPointerDown, onClick: onTriggerClick, onContentClick: onContentClick, onClickOutside: close, onEscPress: close, onShow: handleShow, onHide: handleHide, "data-size": size, hideDelay: exitDelay, showDelay: enterDelay, moveBy: moveBy, moveArrowTo: moveArrowTo, appendTo: appendTo, id: ariaLabelledBy || ariaDescribedBy, flip: flip, fixed: fixed, maxWidth: maxWidth, fluid: fluid, disableClickOutsideWhenClosed: true, zIndex: zIndex, interactive: interactive, ...rest, skin: "dark", timeout: TIMEOUT },
40782
40958
  external_React_default().createElement(Popover.Element, null, triggerElement),
40783
40959
  external_React_default().createElement(Popover.Content, null,
40784
40960
  external_React_default().createElement("div", { ref: contentRef, style: { maxWidth } }, contentElement))));
@@ -59152,6 +59328,7 @@ const APPEND_TO = {
59152
59328
  scrollParent: 'scrollParent',
59153
59329
  parent: 'parent',
59154
59330
  };
59331
+ const DEFAULT_BOUNDARY_PADDING = 5;
59155
59332
  const PopoverNext_constants_placements = (/* unused pure expression or super */ null && ([
59156
59333
  'top',
59157
59334
  'top-start',
@@ -59267,7 +59444,16 @@ const utils_getByPredicate = (predicate, element) => {
59267
59444
 
59268
59445
 
59269
59446
 
59270
- const usePositioning = ({ flip = true, fixed = false, placement, appendTo, rootRef, }) => {
59447
+ const resolveBoundaryPadding = (boundaryPadding = DEFAULT_BOUNDARY_PADDING) => typeof boundaryPadding === 'number'
59448
+ ? boundaryPadding
59449
+ : {
59450
+ top: DEFAULT_BOUNDARY_PADDING,
59451
+ right: DEFAULT_BOUNDARY_PADDING,
59452
+ bottom: DEFAULT_BOUNDARY_PADDING,
59453
+ left: DEFAULT_BOUNDARY_PADDING,
59454
+ ...boundaryPadding,
59455
+ };
59456
+ const usePositioning = ({ flip = true, fixed = false, placement, appendTo, rootRef, boundaryPadding, }) => {
59271
59457
  const [portalRoot, setPortalRoot] = (0,external_React_.useState)(null);
59272
59458
  // TODO: check if a rerender can be avoided
59273
59459
  // https://github.com/wix-private/wix-design-systems/pull/14279#discussion_r1842099301
@@ -59311,6 +59497,7 @@ const usePositioning = ({ flip = true, fixed = false, placement, appendTo, rootR
59311
59497
  }
59312
59498
  };
59313
59499
  const flipPlacement = isFlipPlacement(placement) ? placement : undefined;
59500
+ const padding = resolveBoundaryPadding(boundaryPadding);
59314
59501
  const getFallbackPlacements = (placement) => {
59315
59502
  if (fixed) {
59316
59503
  return flip ? undefined : [placement];
@@ -59323,20 +59510,20 @@ const usePositioning = ({ flip = true, fixed = false, placement, appendTo, rootR
59323
59510
  flip: {
59324
59511
  fallbackAxisSideDirection: 'end',
59325
59512
  mainAxis: isMainAxis || (flip && !fixed),
59326
- padding: 5,
59513
+ padding,
59327
59514
  crossAxis: false,
59328
59515
  fallbackPlacements: getFallbackPlacements(flipPlacement),
59329
59516
  },
59330
59517
  }
59331
59518
  : {
59332
59519
  autoPlacement: {
59333
- padding: 5,
59520
+ padding,
59334
59521
  autoAlignment: false,
59335
59522
  alignment: getAutoPlacement(placement),
59336
59523
  },
59337
59524
  }),
59338
59525
  shift: {
59339
- padding: 5,
59526
+ padding,
59340
59527
  crossAxis: shouldShiftByCrossAxis,
59341
59528
  mainAxis: !fixed,
59342
59529
  },
@@ -59499,7 +59686,7 @@ const getFloatingWidthStyles = ({ appendTo, width, minWidth, maxWidth, dynamicWi
59499
59686
 
59500
59687
 
59501
59688
  const ANIMATED_DURATION = { open: 150, close: 100 };
59502
- function usePopover({ dataHook, open = false, onOpenChange, focusManagerEnabled = true, appendTo = APPEND_TO.parent, dynamicWidth = false, zIndex = ZIndex.popover, width, minWidth, maxWidth, excludeClass, moveBy, flip: shouldFlip = true, placement = 'bottom', fixed = false, rootRef, showDelay, hideDelay, timeout: duration, skin, transitionSettings, onClickOutside, overlay = false, role, tabIndex, 'aria-label': ariaLabel, 'aria-labelledby': ariaLabelledBy, 'aria-describedby': ariaDescribedBy, id, style, onClick, animate, showArrow = false, customArrow, contentClassName, onMouseEnter, onMouseLeave, autoUpdateOptions, }) {
59689
+ function usePopover({ dataHook, open = false, onOpenChange, focusManagerEnabled = true, appendTo = APPEND_TO.parent, dynamicWidth = false, zIndex = ZIndex.popover, width, minWidth, maxWidth, excludeClass, moveBy, flip: shouldFlip = true, placement = 'bottom', fixed = false, boundaryPadding, rootRef, showDelay, hideDelay, timeout: duration, skin, transitionSettings, onClickOutside, overlay = false, role, tabIndex, 'aria-label': ariaLabel, 'aria-labelledby': ariaLabelledBy, 'aria-describedby': ariaDescribedBy, id, style, onClick, animate, showArrow = false, customArrow, contentClassName, onMouseEnter, onMouseLeave, autoUpdateOptions, }) {
59503
59690
  const { contextClassName } = (0,external_React_.useContext)(WixDesignSystemContext);
59504
59691
  const isHoverMode = Boolean(onMouseEnter && onMouseLeave);
59505
59692
  const isHybridMode = Boolean(onMouseEnter) !== Boolean(onMouseLeave);
@@ -59523,6 +59710,7 @@ function usePopover({ dataHook, open = false, onOpenChange, focusManagerEnabled
59523
59710
  placement,
59524
59711
  appendTo,
59525
59712
  rootRef,
59713
+ boundaryPadding,
59526
59714
  });
59527
59715
  const { getArrowProps, arrowMiddleware, getContentWithArrowStyles } = useArrow(showArrow);
59528
59716
  const { context, middlewareData, floatingStyles, placement: floatingPlacement, } = floating_ui_react_useFloating({
@@ -64052,2743 +64240,15 @@ function withErrorBoundary(component, errorBoundaryProps) {
64052
64240
 
64053
64241
 
64054
64242
 
64055
- ;// ../../../node_modules/@wix/wix-ui-icons-common/node_modules/dompurify/dist/purify.es.mjs
64056
- /*! @license DOMPurify 3.4.15 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.4.15/LICENSE */
64057
-
64058
- function _arrayLikeToArray(r, a) {
64059
- (null == a || a > r.length) && (a = r.length);
64060
- for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
64061
- return n;
64062
- }
64063
- function _arrayWithHoles(r) {
64064
- if (Array.isArray(r)) return r;
64065
- }
64066
- function _iterableToArrayLimit(r, l) {
64067
- var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
64068
- if (null != t) {
64069
- var e,
64070
- n,
64071
- i,
64072
- u,
64073
- a = [],
64074
- f = true,
64075
- o = false;
64076
- try {
64077
- 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);
64078
- } catch (r) {
64079
- o = true, n = r;
64080
- } finally {
64081
- try {
64082
- if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;
64083
- } finally {
64084
- if (o) throw n;
64085
- }
64086
- }
64087
- return a;
64088
- }
64089
- }
64090
- function _nonIterableRest() {
64091
- throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
64092
- }
64093
- function _slicedToArray(r, e) {
64094
- return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
64095
- }
64096
- function _unsupportedIterableToArray(r, a) {
64097
- if (r) {
64098
- if ("string" == typeof r) return _arrayLikeToArray(r, a);
64099
- var t = {}.toString.call(r).slice(8, -1);
64100
- 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;
64101
- }
64102
- }
64103
-
64104
- const entries = Object.entries,
64105
- setPrototypeOf = Object.setPrototypeOf,
64106
- isFrozen = Object.isFrozen,
64107
- getPrototypeOf = Object.getPrototypeOf,
64108
- getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
64109
- let freeze = Object.freeze,
64110
- seal = Object.seal,
64111
- create = Object.create; // eslint-disable-line import/no-mutable-exports
64112
- let _ref = typeof Reflect !== 'undefined' && Reflect,
64113
- apply = _ref.apply,
64114
- construct = _ref.construct;
64115
- if (!freeze) {
64116
- freeze = function freeze(x) {
64117
- return x;
64118
- };
64119
- }
64120
- if (!seal) {
64121
- seal = function seal(x) {
64122
- return x;
64123
- };
64124
- }
64125
- if (!apply) {
64126
- apply = function apply(func, thisArg) {
64127
- for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
64128
- args[_key - 2] = arguments[_key];
64129
- }
64130
- return func.apply(thisArg, args);
64131
- };
64132
- }
64133
- if (!construct) {
64134
- construct = function construct(Func) {
64135
- for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
64136
- args[_key2 - 1] = arguments[_key2];
64137
- }
64138
- return new Func(...args);
64139
- };
64140
- }
64141
- const arrayForEach = unapply(Array.prototype.forEach);
64142
- const arrayLastIndexOf = unapply(Array.prototype.lastIndexOf);
64143
- const arrayPop = unapply(Array.prototype.pop);
64144
- const arrayPush = unapply(Array.prototype.push);
64145
- const arraySplice = unapply(Array.prototype.splice);
64146
- const arrayIsArray = Array.isArray;
64147
- const stringToLowerCase = unapply(String.prototype.toLowerCase);
64148
- const stringToString = unapply(String.prototype.toString);
64149
- const stringMatch = unapply(String.prototype.match);
64150
- const stringReplace = unapply(String.prototype.replace);
64151
- const stringIndexOf = unapply(String.prototype.indexOf);
64152
- const stringTrim = unapply(String.prototype.trim);
64153
- const numberToString = unapply(Number.prototype.toString);
64154
- const booleanToString = unapply(Boolean.prototype.toString);
64155
- const bigintToString = typeof BigInt === 'undefined' ? null : unapply(BigInt.prototype.toString);
64156
- const symbolToString = typeof Symbol === 'undefined' ? null : unapply(Symbol.prototype.toString);
64157
- const objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty);
64158
- const objectToString = unapply(Object.prototype.toString);
64159
- const regExpTest = unapply(RegExp.prototype.test);
64160
- const typeErrorCreate = unconstruct(TypeError);
64161
- /**
64162
- * Creates a new function that calls the given function with a specified thisArg and arguments.
64163
- *
64164
- * @param func - The function to be wrapped and called.
64165
- * @returns A new function that calls the given function with a specified thisArg and arguments.
64166
- */
64167
- function unapply(func) {
64168
- return function (thisArg) {
64169
- if (thisArg instanceof RegExp) {
64170
- thisArg.lastIndex = 0;
64171
- }
64172
- for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
64173
- args[_key3 - 1] = arguments[_key3];
64174
- }
64175
- return apply(func, thisArg, args);
64176
- };
64177
- }
64178
- /**
64179
- * Creates a new function that constructs an instance of the given constructor function with the provided arguments.
64180
- *
64181
- * @param func - The constructor function to be wrapped and called.
64182
- * @returns A new function that constructs an instance of the given constructor function with the provided arguments.
64183
- */
64184
- function unconstruct(Func) {
64185
- return function () {
64186
- for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
64187
- args[_key4] = arguments[_key4];
64188
- }
64189
- return construct(Func, args);
64190
- };
64191
- }
64192
- /**
64193
- * Add properties to a lookup table
64194
- *
64195
- * @param set - The set to which elements will be added.
64196
- * @param array - The array containing elements to be added to the set.
64197
- * @param transformCaseFunc - An optional function to transform the case of each element before adding to the set.
64198
- * @returns The modified set with added elements.
64199
- */
64200
- function addToSet(set, array) {
64201
- let transformCaseFunc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : stringToLowerCase;
64202
- if (setPrototypeOf) {
64203
- // Make 'in' and truthy checks like Boolean(set.constructor)
64204
- // independent of any properties defined on Object.prototype.
64205
- // Prevent prototype setters from intercepting set as a this value.
64206
- setPrototypeOf(set, null);
64207
- }
64208
- if (!arrayIsArray(array)) {
64209
- return set;
64210
- }
64211
- let l = array.length;
64212
- while (l--) {
64213
- let element = array[l];
64214
- if (typeof element === 'string') {
64215
- const lcElement = transformCaseFunc(element);
64216
- if (lcElement !== element) {
64217
- // Config presets (e.g. tags.js, attrs.js) are immutable.
64218
- if (!isFrozen(array)) {
64219
- array[l] = lcElement;
64220
- }
64221
- element = lcElement;
64222
- }
64223
- }
64224
- set[element] = true;
64225
- }
64226
- return set;
64227
- }
64228
- /**
64229
- * Clean up an array to harden against CSPP
64230
- *
64231
- * @param array - The array to be cleaned.
64232
- * @returns The cleaned version of the array
64233
- */
64234
- function cleanArray(array) {
64235
- for (let index = 0; index < array.length; index++) {
64236
- const isPropertyExist = objectHasOwnProperty(array, index);
64237
- if (!isPropertyExist) {
64238
- array[index] = null;
64239
- }
64240
- }
64241
- return array;
64242
- }
64243
- /**
64244
- * Shallow clone an object
64245
- *
64246
- * @param object - The object to be cloned.
64247
- * @returns A new object that copies the original.
64248
- */
64249
- function clone(object) {
64250
- const newObject = create(null);
64251
- for (const _ref2 of entries(object)) {
64252
- var _ref3 = _slicedToArray(_ref2, 2);
64253
- const property = _ref3[0];
64254
- const value = _ref3[1];
64255
- const isPropertyExist = objectHasOwnProperty(object, property);
64256
- if (isPropertyExist) {
64257
- if (arrayIsArray(value)) {
64258
- newObject[property] = cleanArray(value);
64259
- } else if (value && typeof value === 'object' && value.constructor === Object) {
64260
- newObject[property] = clone(value);
64261
- } else {
64262
- newObject[property] = value;
64263
- }
64264
- }
64265
- }
64266
- return newObject;
64267
- }
64268
- /**
64269
- * Convert non-node values into strings without depending on direct property access.
64270
- *
64271
- * @param value - The value to stringify.
64272
- * @returns A string representation of the provided value.
64273
- */
64274
- function stringifyValue(value) {
64275
- switch (typeof value) {
64276
- case 'string':
64277
- {
64278
- return value;
64279
- }
64280
- case 'number':
64281
- {
64282
- return numberToString(value);
64283
- }
64284
- case 'boolean':
64285
- {
64286
- return booleanToString(value);
64287
- }
64288
- case 'bigint':
64289
- {
64290
- return bigintToString ? bigintToString(value) : '0';
64291
- }
64292
- case 'symbol':
64293
- {
64294
- return symbolToString ? symbolToString(value) : 'Symbol()';
64295
- }
64296
- case 'undefined':
64297
- {
64298
- return objectToString(value);
64299
- }
64300
- case 'function':
64301
- case 'object':
64302
- {
64303
- if (value === null) {
64304
- return objectToString(value);
64305
- }
64306
- const valueAsRecord = value;
64307
- const valueToString = lookupGetter(valueAsRecord, 'toString');
64308
- if (typeof valueToString === 'function') {
64309
- const stringified = valueToString(valueAsRecord);
64310
- return typeof stringified === 'string' ? stringified : objectToString(stringified);
64311
- }
64312
- return objectToString(value);
64313
- }
64314
- default:
64315
- {
64316
- return objectToString(value);
64317
- }
64318
- }
64319
- }
64320
- /**
64321
- * This method automatically checks if the prop is function or getter and behaves accordingly.
64322
- *
64323
- * @param object - The object to look up the getter function in its prototype chain.
64324
- * @param prop - The property name for which to find the getter function.
64325
- * @returns The getter function found in the prototype chain or a fallback function.
64326
- */
64327
- function lookupGetter(object, prop) {
64328
- while (object !== null) {
64329
- const desc = getOwnPropertyDescriptor(object, prop);
64330
- if (desc) {
64331
- if (desc.get) {
64332
- return unapply(desc.get);
64333
- }
64334
- if (typeof desc.value === 'function') {
64335
- return unapply(desc.value);
64336
- }
64337
- }
64338
- object = getPrototypeOf(object);
64339
- }
64340
- function fallbackValue() {
64341
- return null;
64342
- }
64343
- return fallbackValue;
64344
- }
64345
- function isRegex(value) {
64346
- try {
64347
- regExpTest(value, '');
64348
- return true;
64349
- } catch (_unused) {
64350
- return false;
64351
- }
64352
- }
64353
-
64354
- 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']);
64355
- 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']);
64356
- 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']);
64357
- // List of SVG elements that are disallowed by default.
64358
- // We still need to know them so that we can do namespace
64359
- // checks properly in case one wants to add them to
64360
- // allow-list.
64361
- 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']);
64362
- 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']);
64363
- // Similarly to SVG, we want to know all MathML elements,
64364
- // even those that we disallow by default.
64365
- const mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);
64366
- const purify_es_text = freeze(['#text']);
64367
-
64368
- 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']);
64369
- const svg = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', 'amplitude', 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'baseline-shift', 'begin', 'bias', 'by', 'class', 'clip', 'clippathunits', 'clip-path', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconstant', 'direction', 'display', 'divisor', 'dominant-baseline', 'dur', 'edgemode', 'elevation', 'end', 'exponent', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'filterunits', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'image-rendering', 'in', 'in2', 'intercept', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints', 'keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatrix', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid', 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits', 'maskunits', 'max', 'mask', 'mask-type', 'media', 'method', 'mode', 'min', 'name', 'numoctaves', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits', 'pointer-events', 'points', 'preservealpha', 'preserveaspectratio', 'primitiveunits', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 'repeatdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'slope', 'specularconstant', 'specularexponent', 'spreadmethod', 'startoffset', 'stddeviation', 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width', 'style', 'surfacescale', 'systemlanguage', 'tabindex', 'tablevalues', 'targetx', 'targety', 'transform', 'transform-origin', 'text-anchor', 'text-decoration', 'text-orientation', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', 'values', 'vector-effect', 'viewbox', 'visibility', 'version', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'width', 'word-spacing', 'wrap', 'writing-mode', 'xchannelselector', 'ychannelselector', 'x', 'x1', 'x2', 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpan']);
64370
- 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']);
64371
- const xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);
64372
-
64373
- const MUSTACHE_EXPR = seal(/{{[\w\W]*|^[\w\W]*}}/g);
64374
- const ERB_EXPR = seal(/<%[\w\W]*|^[\w\W]*%>/g);
64375
- const TMPLIT_EXPR = seal(/\${[\w\W]*/g);
64376
- const purify_es_DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]+$/); // eslint-disable-line no-useless-escape
64377
- const ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape
64378
- 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
64379
- );
64380
- const IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i);
64381
- const ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g // eslint-disable-line no-control-regex
64382
- );
64383
- const DOCTYPE_NAME = seal(/^html$/i);
64384
- const CUSTOM_ELEMENT = seal(/^[a-z][.\w]*(-[.\w]+)+$/i);
64385
- // Markup-significant character probes used by _sanitizeElements.
64386
- // Shared module-level instances are safe despite the sticky /g flags:
64387
- // unapply() resets lastIndex for RegExp receivers before every call.
64388
- const ELEMENT_MARKUP_PROBE = seal(/<[/\w!]/g);
64389
- const COMMENT_MARKUP_PROBE = seal(/<[/\w]/g);
64390
- const FALLBACK_TAG_CLOSE = seal(/<\/no(script|embed|frames)/i);
64391
- const SELF_CLOSING_TAG = seal(/\/>/i);
64392
-
64393
- // https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType
64394
- const NODE_TYPE = {
64395
- element: 1,
64396
- attribute: 2,
64397
- text: 3,
64398
- cdataSection: 4,
64399
- entityReference: 5,
64400
- // Deprecated
64401
- entityNode: 6,
64402
- // Deprecated
64403
- processingInstruction: 7,
64404
- comment: 8,
64405
- document: 9,
64406
- documentType: 10,
64407
- documentFragment: 11,
64408
- notation: 12 // Deprecated
64409
- };
64410
- /* HTML-namespace elements whose child text nodes are serialized *literally*
64411
- (unescaped) by the HTML fragment-serialization algorithm. Two reparse-mXSS
64412
- shapes ride on that literal serialization:
64413
- (a) an element child - a tree the HTML parser can never build, but the DOM
64414
- API and an XML/XHTML parse can - after which a `</tag>`-bearing text
64415
- sibling breaks the element open on reparse; and
64416
- (b) text-only content that already carries the element's OWN end tag, e.g.
64417
- `<style>...</style><img onerror=x>` built as a node, which the literal
64418
- serializer emits verbatim for the HTML parser to re-open.
64419
- Shape (a) is handled by the firstElementChild branch in _isUnsafeNode; shape
64420
- (b) by the LITERAL_TEXT_CLOSE probe. Both read textContent (the raw-serialized
64421
- form for these elements) rather than innerHTML, because an XML/XHTML working
64422
- document serializes innerHTML with `<` escaped, which silently blinds the
64423
- innerHTML-based probes (rule 1's second probe and FALLBACK_TAG_CLOSE) there.
64424
- `script` is never allow-listed, but is kept here so the guard matches the
64425
- serializer's own literal-text list exactly. */
64426
- const LITERAL_TEXT_ELEMENT_NAMES = ['style', 'script', 'xmp', 'iframe', 'noembed', 'noframes', 'plaintext', 'noscript'];
64427
- const LITERAL_TEXT_ELEMENTS = freeze(addToSet({}, LITERAL_TEXT_ELEMENT_NAMES));
64428
- /* Per-element end-tag matcher. On an HTML reparse the ONLY token that
64429
- terminates a literal-text element's raw content is its own end tag; a foreign
64430
- literal-text close (e.g. `</xmp>` sitting inside `<style>`) does not break
64431
- out, so matching is per-element, not a shared alternation. The lookahead
64432
- requires an HTML tag-name terminator (whitespace, `/` or `>`) so a longer
64433
- name such as `</styles` is not mistaken for `</style`. */
64434
- const LITERAL_TEXT_CLOSE = function () {
64435
- const map = {};
64436
- arrayForEach(LITERAL_TEXT_ELEMENT_NAMES, name => {
64437
- map[name] = seal(new RegExp('</' + name + '(?=[\\t\\n\\f\\r />])', 'i'));
64438
- });
64439
- return freeze(map);
64440
- }();
64441
- const getGlobal = function getGlobal() {
64442
- return typeof window === 'undefined' ? null : window;
64443
- };
64444
- /**
64445
- * Creates a no-op policy for internal use only.
64446
- * Don't export this function outside this module!
64447
- * @param trustedTypes The policy factory.
64448
- * @param purifyHostElement The Script element used to load DOMPurify (to determine policy name suffix).
64449
- * @return The policy created (or null, if Trusted Types
64450
- * are not supported or creating the policy failed).
64451
- */
64452
- const _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, purifyHostElement) {
64453
- if (typeof trustedTypes !== 'object' || typeof trustedTypes.createPolicy !== 'function') {
64454
- return null;
64455
- }
64456
- // Allow the callers to control the unique policy name
64457
- // by adding a data-tt-policy-suffix to the script element with the DOMPurify.
64458
- // Policy creation with duplicate names throws in Trusted Types.
64459
- let suffix = null;
64460
- const ATTR_NAME = 'data-tt-policy-suffix';
64461
- if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) {
64462
- suffix = purifyHostElement.getAttribute(ATTR_NAME);
64463
- }
64464
- const policyName = 'dompurify' + (suffix ? '#' + suffix : '');
64465
- try {
64466
- return trustedTypes.createPolicy(policyName, {
64467
- createHTML(html) {
64468
- return html;
64469
- },
64470
- createScriptURL(scriptUrl) {
64471
- return scriptUrl;
64472
- }
64473
- });
64474
- } catch (_) {
64475
- // Policy creation failed (most likely another DOMPurify script has
64476
- // already run). Skip creating the policy, as this will only cause errors
64477
- // if TT are enforced.
64478
- console.warn('TrustedTypes policy ' + policyName + ' could not be created.');
64479
- return null;
64480
- }
64481
- };
64482
- const _createHooksMap = function _createHooksMap() {
64483
- return {
64484
- afterSanitizeAttributes: [],
64485
- afterSanitizeElements: [],
64486
- afterSanitizeShadowDOM: [],
64487
- beforeSanitizeAttributes: [],
64488
- beforeSanitizeElements: [],
64489
- beforeSanitizeShadowDOM: [],
64490
- uponSanitizeAttribute: [],
64491
- uponSanitizeElement: [],
64492
- uponSanitizeShadowNode: []
64493
- };
64494
- };
64495
- /**
64496
- * Resolve a set-valued configuration option: a fresh set built from
64497
- * cfg[key] when it is an own array property (seeded with a clone of
64498
- * options.base when given, case-normalized via options.transform),
64499
- * the fallback set otherwise.
64500
- *
64501
- * @param cfg the cloned, prototype-free configuration object
64502
- * @param key the configuration property to read
64503
- * @param fallback the set to use when the option is absent or not an array
64504
- * @param options transform and optional base set to merge into
64505
- * @returns the resolved set
64506
- */
64507
- const _resolveSetOption = function _resolveSetOption(cfg, key, fallback, options) {
64508
- return objectHasOwnProperty(cfg, key) && arrayIsArray(cfg[key]) ? addToSet(options.base ? clone(options.base) : {}, cfg[key], options.transform) : fallback;
64509
- };
64510
- /**
64511
- * Resolve an object-valued configuration option: a prototype-free clone
64512
- * of cfg[key] when it is an own, truthy object property, else a fresh
64513
- * fallback built by makeFallback (fresh on every parse, so a previous
64514
- * parse can never leak state into the next one).
64515
- *
64516
- * @param cfg the cloned, prototype-free configuration object
64517
- * @param key the configuration property to read
64518
- * @param makeFallback builds the fallback value when the option is absent
64519
- * @returns the resolved object
64520
- */
64521
- const _resolveObjectOption = function _resolveObjectOption(cfg, key, makeFallback) {
64522
- const value = objectHasOwnProperty(cfg, key) ? cfg[key] : undefined;
64523
- return value && typeof value === 'object' ? clone(value) : makeFallback();
64524
- };
64525
- function createDOMPurify() {
64526
- let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();
64527
- const DOMPurify = root => createDOMPurify(root);
64528
- DOMPurify.version = '3.4.15';
64529
- DOMPurify.removed = [];
64530
- if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document || !window.Element) {
64531
- // Not running in a browser, provide a factory function
64532
- // so that you can pass your own Window
64533
- DOMPurify.isSupported = false;
64534
- return DOMPurify;
64535
- }
64536
- let document = window.document;
64537
- const originalDocument = document;
64538
- const currentScript = originalDocument.currentScript;
64539
- window.DocumentFragment;
64540
- const HTMLTemplateElement = window.HTMLTemplateElement,
64541
- Node = window.Node,
64542
- Element = window.Element,
64543
- NodeFilter = window.NodeFilter,
64544
- _window$NamedNodeMap = window.NamedNodeMap;
64545
- _window$NamedNodeMap === void 0 ? window.NamedNodeMap || window.MozNamedAttrMap : _window$NamedNodeMap;
64546
- window.HTMLFormElement;
64547
- const DOMParser = window.DOMParser,
64548
- trustedTypes = window.trustedTypes;
64549
- const ElementPrototype = Element.prototype;
64550
- const cloneNode = lookupGetter(ElementPrototype, 'cloneNode');
64551
- const remove = lookupGetter(ElementPrototype, 'remove');
64552
- // Clobber-safe Attr-node removal. On an HTMLFormElement a descendant named
64553
- // "removeAttributeNode" shadows the prototype method via
64554
- // [LegacyOverrideBuiltIns], so element.removeAttributeNode(attr) throws.
64555
- // Calling the cached Element.prototype method with the element as the
64556
- // receiver removes the exact live Attr node regardless of the shadowing.
64557
- const removeAttributeNode = lookupGetter(ElementPrototype, 'removeAttributeNode');
64558
- const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');
64559
- const getChildNodes = lookupGetter(ElementPrototype, 'childNodes');
64560
- const getParentNode = lookupGetter(ElementPrototype, 'parentNode');
64561
- const getShadowRoot = lookupGetter(ElementPrototype, 'shadowRoot');
64562
- const getAttributes = lookupGetter(ElementPrototype, 'attributes');
64563
- const getNodeType = Node && Node.prototype ? lookupGetter(Node.prototype, 'nodeType') : null;
64564
- const getNodeName = Node && Node.prototype ? lookupGetter(Node.prototype, 'nodeName') : null;
64565
- const getOwnerDocument = Node && Node.prototype ? lookupGetter(Node.prototype, 'ownerDocument') : null;
64566
- /* Clobber-safe nodeType / nodeName reads through the cached Node.prototype
64567
- getters, with a direct-property fallback for environments that lack
64568
- Node.prototype. Sites that need a different fallback (e.g. _isClobbered
64569
- returns early on a null name) intentionally keep their own reads. */
64570
- const _readNodeType = function _readNodeType(node) {
64571
- return getNodeType ? getNodeType(node) : node.nodeType;
64572
- };
64573
- const _readNodeName = function _readNodeName(node) {
64574
- return getNodeName ? getNodeName(node) : node.nodeName;
64575
- };
64576
- // As per issue #47, the web-components registry is inherited by a
64577
- // new document created via createHTMLDocument. As per the spec
64578
- // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)
64579
- // a new empty registry is used when creating a template contents owner
64580
- // document, so we use that as our parent document to ensure nothing
64581
- // is inherited.
64582
- if (typeof HTMLTemplateElement === 'function') {
64583
- const template = document.createElement('template');
64584
- if (template.content && template.content.ownerDocument) {
64585
- document = template.content.ownerDocument;
64586
- }
64587
- }
64588
- let trustedTypesPolicy;
64589
- let emptyHTML = '';
64590
- // The instance's own internal Trusted Types policy. Unlike a caller-supplied
64591
- // `TRUSTED_TYPES_POLICY`, this is created at most once — Trusted Types throws
64592
- // on duplicate policy names — and is the only policy allowed to persist
64593
- // across configurations and survive `clearConfig()`.
64594
- let defaultTrustedTypesPolicy;
64595
- let defaultTrustedTypesPolicyResolved = false;
64596
- // Tracks whether we are already inside a call to the configured Trusted Types
64597
- // policy (`createHTML` or `createScriptURL`). If a supplied policy callback
64598
- // itself calls `DOMPurify.sanitize` (the cause of #1422), `sanitize` would
64599
- // re-enter the policy and recurse until the stack overflows. We detect that
64600
- // re-entry and throw a clear, actionable error instead. The guard is shared
64601
- // across both callbacks, because either one re-entering `sanitize` triggers
64602
- // the same unbounded recursion.
64603
- let IN_TRUSTED_TYPES_POLICY = 0;
64604
- const _assertNotInTrustedTypesPolicy = function _assertNotInTrustedTypesPolicy() {
64605
- if (IN_TRUSTED_TYPES_POLICY > 0) {
64606
- throw typeErrorCreate('A configured TRUSTED_TYPES_POLICY callback (createHTML or ' + 'createScriptURL) must not call DOMPurify.sanitize, as that causes ' + 'infinite recursion. Do not pass a policy whose callbacks wrap ' + 'DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted ' + 'Types" section of the README.');
64607
- }
64608
- };
64609
- const _createTrustedHTML = function _createTrustedHTML(html) {
64610
- _assertNotInTrustedTypesPolicy();
64611
- IN_TRUSTED_TYPES_POLICY++;
64612
- try {
64613
- return trustedTypesPolicy.createHTML(html);
64614
- } finally {
64615
- IN_TRUSTED_TYPES_POLICY--;
64616
- }
64617
- };
64618
- const _createTrustedScriptURL = function _createTrustedScriptURL(scriptUrl) {
64619
- _assertNotInTrustedTypesPolicy();
64620
- IN_TRUSTED_TYPES_POLICY++;
64621
- try {
64622
- return trustedTypesPolicy.createScriptURL(scriptUrl);
64623
- } finally {
64624
- IN_TRUSTED_TYPES_POLICY--;
64625
- }
64626
- };
64627
- // Lazily resolve (and cache) the instance's internal default policy.
64628
- // Resolution is attempted at most once: a successful `createPolicy` cannot be
64629
- // repeated (Trusted Types throws on duplicate names), and a failed or
64630
- // unsupported attempt must not be retried on every parse.
64631
- const _getDefaultTrustedTypesPolicy = function _getDefaultTrustedTypesPolicy() {
64632
- if (!defaultTrustedTypesPolicyResolved) {
64633
- defaultTrustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);
64634
- defaultTrustedTypesPolicyResolved = true;
64635
- }
64636
- return defaultTrustedTypesPolicy;
64637
- };
64638
- const _document = document,
64639
- implementation = _document.implementation,
64640
- createNodeIterator = _document.createNodeIterator,
64641
- createDocumentFragment = _document.createDocumentFragment,
64642
- getElementsByTagName = _document.getElementsByTagName;
64643
- const importNode = originalDocument.importNode;
64644
- let hooks = _createHooksMap();
64645
- /**
64646
- * Expose whether this browser supports running the full DOMPurify.
64647
- */
64648
- DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNode === 'function' && implementation && implementation.createHTMLDocument !== undefined;
64649
- const MUSTACHE_EXPR$1 = MUSTACHE_EXPR,
64650
- ERB_EXPR$1 = ERB_EXPR,
64651
- TMPLIT_EXPR$1 = TMPLIT_EXPR,
64652
- DATA_ATTR$1 = purify_es_DATA_ATTR,
64653
- ARIA_ATTR$1 = ARIA_ATTR,
64654
- IS_SCRIPT_OR_DATA$1 = IS_SCRIPT_OR_DATA,
64655
- ATTR_WHITESPACE$1 = ATTR_WHITESPACE,
64656
- CUSTOM_ELEMENT$1 = CUSTOM_ELEMENT;
64657
- let IS_ALLOWED_URI$1 = IS_ALLOWED_URI;
64658
- /**
64659
- * We consider the elements and attributes below to be safe. Ideally
64660
- * don't add any new ones but feel free to remove unwanted ones.
64661
- */
64662
- /* allowed element names */
64663
- let ALLOWED_TAGS = null;
64664
- const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...purify_es_text]);
64665
- /* Allowed attribute names */
64666
- let ALLOWED_ATTR = null;
64667
- const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]);
64668
- /*
64669
- * Configure how DOMPurify should handle custom elements and their attributes as well as customized built-in elements.
64670
- * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements)
64671
- * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list)
64672
- * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`.
64673
- */
64674
- let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, {
64675
- tagNameCheck: {
64676
- writable: true,
64677
- configurable: false,
64678
- enumerable: true,
64679
- value: null
64680
- },
64681
- attributeNameCheck: {
64682
- writable: true,
64683
- configurable: false,
64684
- enumerable: true,
64685
- value: null
64686
- },
64687
- allowCustomizedBuiltInElements: {
64688
- writable: true,
64689
- configurable: false,
64690
- enumerable: true,
64691
- value: false
64692
- }
64693
- }));
64694
- /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */
64695
- let FORBID_TAGS = null;
64696
- /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */
64697
- let FORBID_ATTR = null;
64698
- /* Config object to store ADD_TAGS/ADD_ATTR functions (when used as functions) */
64699
- const EXTRA_ELEMENT_HANDLING = Object.seal(create(null, {
64700
- tagCheck: {
64701
- writable: true,
64702
- configurable: false,
64703
- enumerable: true,
64704
- value: null
64705
- },
64706
- attributeCheck: {
64707
- writable: true,
64708
- configurable: false,
64709
- enumerable: true,
64710
- value: null
64711
- }
64712
- }));
64713
- /* Decide if ARIA attributes are okay */
64714
- let ALLOW_ARIA_ATTR = true;
64715
- /* Decide if custom data attributes are okay */
64716
- let ALLOW_DATA_ATTR = true;
64717
- /* Decide if unknown protocols are okay */
64718
- let ALLOW_UNKNOWN_PROTOCOLS = false;
64719
- /* Decide if self-closing tags in attributes are allowed.
64720
- * Usually removed due to a mXSS issue in jQuery 3.0 */
64721
- let ALLOW_SELF_CLOSE_IN_ATTR = true;
64722
- /* Output should be safe for common template engines.
64723
- * This means, DOMPurify removes data attributes, mustaches and ERB
64724
- */
64725
- let SAFE_FOR_TEMPLATES = false;
64726
- /* Output should be safe even for XML used within HTML and alike.
64727
- * This means, DOMPurify removes comments when containing risky content.
64728
- */
64729
- let SAFE_FOR_XML = true;
64730
- /* Decide if document with <html>... should be returned */
64731
- let WHOLE_DOCUMENT = false;
64732
- /* Track whether config is already set on this instance of DOMPurify. */
64733
- let SET_CONFIG = false;
64734
- /* Pristine allowlist bindings captured at setConfig() time. On the
64735
- * persistent-config path sanitize() restores the sets from these before
64736
- * the per-walk hook clone-guard, so a hook's in-call widening cannot
64737
- * carry across calls. Null until setConfig() is called; reset by
64738
- * clearConfig(). */
64739
- let SET_CONFIG_ALLOWED_TAGS = null;
64740
- let SET_CONFIG_ALLOWED_ATTR = null;
64741
- /* Decide if all elements (e.g. style, script) must be children of
64742
- * document.body. By default, browsers might move them to document.head */
64743
- let FORCE_BODY = false;
64744
- /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html
64745
- * string (or a TrustedHTML object if Trusted Types are supported).
64746
- * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead
64747
- */
64748
- let RETURN_DOM = false;
64749
- /* Decide if a DOM `DocumentFragment` should be returned, instead of a html
64750
- * string (or a TrustedHTML object if Trusted Types are supported) */
64751
- let RETURN_DOM_FRAGMENT = false;
64752
- /* Try to return a Trusted Type object instead of a string, return a string in
64753
- * case Trusted Types are not supported */
64754
- let RETURN_TRUSTED_TYPE = false;
64755
- /* Output should be free from DOM clobbering attacks?
64756
- * This sanitizes markups named with colliding, clobberable built-in DOM APIs.
64757
- */
64758
- let SANITIZE_DOM = true;
64759
- /* Achieve full DOM Clobbering protection by isolating the namespace of named
64760
- * properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules.
64761
- *
64762
- * HTML/DOM spec rules that enable DOM Clobbering:
64763
- * - Named Access on Window (§7.3.3)
64764
- * - DOM Tree Accessors (§3.1.5)
64765
- * - Form Element Parent-Child Relations (§4.10.3)
64766
- * - Iframe srcdoc / Nested WindowProxies (§4.8.5)
64767
- * - HTMLCollection (§4.2.10.2)
64768
- *
64769
- * Namespace isolation is implemented by prefixing `id` and `name` attributes
64770
- * with a constant string, i.e., `user-content-`
64771
- */
64772
- let SANITIZE_NAMED_PROPS = false;
64773
- const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-';
64774
- /* Keep element content when removing element? */
64775
- let KEEP_CONTENT = true;
64776
- /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead
64777
- * of importing it into a new Document and returning a sanitized copy */
64778
- let IN_PLACE = false;
64779
- /* Allow usage of profiles like html, svg and mathMl */
64780
- let USE_PROFILES = {};
64781
- /* Tags to ignore content of when KEEP_CONTENT is true */
64782
- let FORBID_CONTENTS = null;
64783
- const DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script',
64784
- // <selectedcontent> mirrors the selected <option>'s subtree, cloned by
64785
- // the UA (customizable <select>) — including any on* handlers — and the
64786
- // engine re-mirrors synchronously whenever a removal changes which
64787
- // option/selectedcontent is current, even inside DOMPurify's inert
64788
- // DOMParser document. Hoisting its children on removal re-inserts a fresh
64789
- // mirror target ahead of the walk, which the engine refills, looping
64790
- // forever (DoS) and amplifying output. Dropping its content on removal
64791
- // (rather than hoisting) breaks that cascade; the content is a duplicate
64792
- // of the option, which is sanitized on its own. See campaign-3 F1/F6.
64793
- 'selectedcontent', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']);
64794
- /* Tags that are safe for data: URIs */
64795
- let DATA_URI_TAGS = null;
64796
- const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);
64797
- /* Attributes safe for values like "javascript:" */
64798
- let URI_SAFE_ATTRIBUTES = null;
64799
- const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']);
64800
- const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
64801
- const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
64802
- const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
64803
- /* Document namespace */
64804
- let NAMESPACE = HTML_NAMESPACE;
64805
- let IS_EMPTY_INPUT = false;
64806
- /* Allowed XHTML+XML namespaces */
64807
- let ALLOWED_NAMESPACES = null;
64808
- const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);
64809
- const DEFAULT_MATHML_TEXT_INTEGRATION_POINTS = freeze(['mi', 'mo', 'mn', 'ms', 'mtext']);
64810
- let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, DEFAULT_MATHML_TEXT_INTEGRATION_POINTS);
64811
- const DEFAULT_HTML_INTEGRATION_POINTS = freeze(['annotation-xml']);
64812
- let HTML_INTEGRATION_POINTS = addToSet({}, DEFAULT_HTML_INTEGRATION_POINTS);
64813
- // Certain elements are allowed in both SVG and HTML
64814
- // namespace. We need to specify them explicitly
64815
- // so that they don't get erroneously deleted from
64816
- // HTML namespace.
64817
- const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']);
64818
- /* Parsing of strict XHTML documents */
64819
- let PARSER_MEDIA_TYPE = null;
64820
- const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html'];
64821
- const DEFAULT_PARSER_MEDIA_TYPE = 'text/html';
64822
- let transformCaseFunc = null;
64823
- /* Keep a reference to config to pass to hooks */
64824
- let CONFIG = null;
64825
- /* Ideally, do not touch anything below this line */
64826
- /* ______________________________________________ */
64827
- const formElement = document.createElement('form');
64828
- const isRegexOrFunction = function isRegexOrFunction(testValue) {
64829
- return testValue instanceof RegExp || testValue instanceof Function;
64830
- };
64831
- /**
64832
- * _parseConfig
64833
- *
64834
- * @param cfg optional config literal
64835
- */
64836
- // eslint-disable-next-line complexity
64837
- const _parseConfig = function _parseConfig() {
64838
- let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
64839
- if (CONFIG && CONFIG === cfg) {
64840
- return;
64841
- }
64842
- /* Shield configuration object from tampering */
64843
- if (!cfg || typeof cfg !== 'object') {
64844
- cfg = {};
64845
- }
64846
- /* Shield configuration object from prototype pollution */
64847
- cfg = clone(cfg);
64848
- PARSER_MEDIA_TYPE =
64849
- // eslint-disable-next-line unicorn/prefer-includes
64850
- SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? DEFAULT_PARSER_MEDIA_TYPE : cfg.PARSER_MEDIA_TYPE;
64851
- // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.
64852
- transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase;
64853
- /* Set configuration parameters */
64854
- ALLOWED_TAGS = _resolveSetOption(cfg, 'ALLOWED_TAGS', DEFAULT_ALLOWED_TAGS, {
64855
- transform: transformCaseFunc
64856
- });
64857
- ALLOWED_ATTR = _resolveSetOption(cfg, 'ALLOWED_ATTR', DEFAULT_ALLOWED_ATTR, {
64858
- transform: transformCaseFunc
64859
- });
64860
- ALLOWED_NAMESPACES = _resolveSetOption(cfg, 'ALLOWED_NAMESPACES', DEFAULT_ALLOWED_NAMESPACES, {
64861
- transform: stringToString
64862
- });
64863
- URI_SAFE_ATTRIBUTES = _resolveSetOption(cfg, 'ADD_URI_SAFE_ATTR', DEFAULT_URI_SAFE_ATTRIBUTES, {
64864
- transform: transformCaseFunc,
64865
- base: DEFAULT_URI_SAFE_ATTRIBUTES
64866
- });
64867
- DATA_URI_TAGS = _resolveSetOption(cfg, 'ADD_DATA_URI_TAGS', DEFAULT_DATA_URI_TAGS, {
64868
- transform: transformCaseFunc,
64869
- base: DEFAULT_DATA_URI_TAGS
64870
- });
64871
- FORBID_CONTENTS = _resolveSetOption(cfg, 'FORBID_CONTENTS', DEFAULT_FORBID_CONTENTS, {
64872
- transform: transformCaseFunc
64873
- });
64874
- FORBID_TAGS = _resolveSetOption(cfg, 'FORBID_TAGS', clone({}), {
64875
- transform: transformCaseFunc
64876
- });
64877
- FORBID_ATTR = _resolveSetOption(cfg, 'FORBID_ATTR', clone({}), {
64878
- transform: transformCaseFunc
64879
- });
64880
- USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES && typeof cfg.USE_PROFILES === 'object' ? clone(cfg.USE_PROFILES) : cfg.USE_PROFILES : false;
64881
- ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true
64882
- ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true
64883
- ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false
64884
- ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true
64885
- SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false
64886
- SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; // Default true
64887
- WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false
64888
- RETURN_DOM = cfg.RETURN_DOM || false; // Default false
64889
- RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false
64890
- RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false
64891
- FORCE_BODY = cfg.FORCE_BODY || false; // Default false
64892
- SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true
64893
- SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false
64894
- KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true
64895
- IN_PLACE = cfg.IN_PLACE || false; // Default false
64896
- IS_ALLOWED_URI$1 = isRegex(cfg.ALLOWED_URI_REGEXP) ? cfg.ALLOWED_URI_REGEXP : IS_ALLOWED_URI; // Default regexp
64897
- NAMESPACE = typeof cfg.NAMESPACE === 'string' ? cfg.NAMESPACE : HTML_NAMESPACE; // Default HTML namespace
64898
- MATHML_TEXT_INTEGRATION_POINTS = _resolveObjectOption(cfg, 'MATHML_TEXT_INTEGRATION_POINTS', () => addToSet({}, DEFAULT_MATHML_TEXT_INTEGRATION_POINTS) // Default built-in map
64899
- );
64900
- HTML_INTEGRATION_POINTS = _resolveObjectOption(cfg, 'HTML_INTEGRATION_POINTS', () => addToSet({}, DEFAULT_HTML_INTEGRATION_POINTS) // Default built-in map
64901
- );
64902
- const customElementHandling = _resolveObjectOption(cfg, 'CUSTOM_ELEMENT_HANDLING', () => create(null));
64903
- CUSTOM_ELEMENT_HANDLING = create(null);
64904
- if (objectHasOwnProperty(customElementHandling, 'tagNameCheck') && isRegexOrFunction(customElementHandling.tagNameCheck)) {
64905
- CUSTOM_ELEMENT_HANDLING.tagNameCheck = customElementHandling.tagNameCheck; // Default undefined
64906
- }
64907
- if (objectHasOwnProperty(customElementHandling, 'attributeNameCheck') && isRegexOrFunction(customElementHandling.attributeNameCheck)) {
64908
- CUSTOM_ELEMENT_HANDLING.attributeNameCheck = customElementHandling.attributeNameCheck; // Default undefined
64909
- }
64910
- if (objectHasOwnProperty(customElementHandling, 'allowCustomizedBuiltInElements') && typeof customElementHandling.allowCustomizedBuiltInElements === 'boolean') {
64911
- CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = customElementHandling.allowCustomizedBuiltInElements; // Default undefined
64912
- }
64913
- seal(CUSTOM_ELEMENT_HANDLING);
64914
- if (SAFE_FOR_TEMPLATES) {
64915
- ALLOW_DATA_ATTR = false;
64916
- }
64917
- if (RETURN_DOM_FRAGMENT) {
64918
- RETURN_DOM = true;
64919
- }
64920
- /* Parse profile info */
64921
- if (USE_PROFILES) {
64922
- ALLOWED_TAGS = addToSet({}, purify_es_text);
64923
- ALLOWED_ATTR = create(null);
64924
- if (USE_PROFILES.html === true) {
64925
- addToSet(ALLOWED_TAGS, html$1);
64926
- addToSet(ALLOWED_ATTR, html);
64927
- }
64928
- if (USE_PROFILES.svg === true) {
64929
- addToSet(ALLOWED_TAGS, svg$1);
64930
- addToSet(ALLOWED_ATTR, svg);
64931
- addToSet(ALLOWED_ATTR, xml);
64932
- }
64933
- if (USE_PROFILES.svgFilters === true) {
64934
- addToSet(ALLOWED_TAGS, svgFilters);
64935
- addToSet(ALLOWED_ATTR, svg);
64936
- addToSet(ALLOWED_ATTR, xml);
64937
- }
64938
- if (USE_PROFILES.mathMl === true) {
64939
- addToSet(ALLOWED_TAGS, mathMl$1);
64940
- addToSet(ALLOWED_ATTR, mathMl);
64941
- addToSet(ALLOWED_ATTR, xml);
64942
- }
64943
- }
64944
- /* Always reset function-based ADD_TAGS / ADD_ATTR checks to prevent
64945
- * leaking across calls when switching from function to array config */
64946
- EXTRA_ELEMENT_HANDLING.tagCheck = null;
64947
- EXTRA_ELEMENT_HANDLING.attributeCheck = null;
64948
- /* Merge configuration parameters */
64949
- if (objectHasOwnProperty(cfg, 'ADD_TAGS')) {
64950
- if (typeof cfg.ADD_TAGS === 'function') {
64951
- EXTRA_ELEMENT_HANDLING.tagCheck = cfg.ADD_TAGS;
64952
- } else if (arrayIsArray(cfg.ADD_TAGS)) {
64953
- if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
64954
- ALLOWED_TAGS = clone(ALLOWED_TAGS);
64955
- }
64956
- addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);
64957
- }
64958
- }
64959
- if (objectHasOwnProperty(cfg, 'ADD_ATTR')) {
64960
- if (typeof cfg.ADD_ATTR === 'function') {
64961
- EXTRA_ELEMENT_HANDLING.attributeCheck = cfg.ADD_ATTR;
64962
- } else if (arrayIsArray(cfg.ADD_ATTR)) {
64963
- if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
64964
- ALLOWED_ATTR = clone(ALLOWED_ATTR);
64965
- }
64966
- addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);
64967
- }
64968
- }
64969
- if (objectHasOwnProperty(cfg, 'ADD_FORBID_CONTENTS') && arrayIsArray(cfg.ADD_FORBID_CONTENTS)) {
64970
- if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
64971
- FORBID_CONTENTS = clone(FORBID_CONTENTS);
64972
- }
64973
- addToSet(FORBID_CONTENTS, cfg.ADD_FORBID_CONTENTS, transformCaseFunc);
64974
- }
64975
- /* Add #text in case KEEP_CONTENT is set to true */
64976
- if (KEEP_CONTENT) {
64977
- ALLOWED_TAGS['#text'] = true;
64978
- }
64979
- /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */
64980
- if (WHOLE_DOCUMENT) {
64981
- addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);
64982
- }
64983
- /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */
64984
- if (ALLOWED_TAGS.table) {
64985
- addToSet(ALLOWED_TAGS, ['tbody']);
64986
- delete FORBID_TAGS.tbody;
64987
- }
64988
- // Re-derive the active Trusted Types policy from this configuration on
64989
- // every parse. The active policy must never be sticky closure state that
64990
- // outlives the config that set it: a caller-supplied policy left in place
64991
- // after `clearConfig()` — or after a later call that supplied none, or
64992
- // `TRUSTED_TYPES_POLICY: null` — could sign a subsequent "default"
64993
- // `RETURN_TRUSTED_TYPE` result with a foreign, possibly unsafe policy.
64994
- // See GHSA-vxr8-fq34-vvx9.
64995
- if (cfg.TRUSTED_TYPES_POLICY) {
64996
- if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') {
64997
- throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');
64998
- }
64999
- if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') {
65000
- throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');
65001
- }
65002
- // A caller-supplied policy applies to this configuration only.
65003
- const previousTrustedTypesPolicy = trustedTypesPolicy;
65004
- trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;
65005
- // Sign local variables required by `sanitize`. If the supplied policy's
65006
- // `createHTML` is circular (i.e. it calls `DOMPurify.sanitize`), this
65007
- // throws via the re-entrancy guard. Restore the previous policy first so
65008
- // the instance is not left in a poisoned state. See #1422.
65009
- try {
65010
- emptyHTML = _createTrustedHTML('');
65011
- } catch (error) {
65012
- trustedTypesPolicy = previousTrustedTypesPolicy;
65013
- throw error;
65014
- }
65015
- } else if (cfg.TRUSTED_TYPES_POLICY === null) {
65016
- // Explicit opt-out for this call: perform no Trusted Types signing and
65017
- // create nothing (so a strict `trusted-types` CSP that disallows a
65018
- // `dompurify` policy can still call `sanitize` from inside its own
65019
- // policy — see #1422). Resetting to `undefined` rather than a sticky
65020
- // `null` also drops any previously retained caller policy, so it cannot
65021
- // resurface on a later call, while still allowing the next config-less
65022
- // call to restore the internal default policy. See GHSA-vxr8-fq34-vvx9.
65023
- trustedTypesPolicy = undefined;
65024
- emptyHTML = '';
65025
- } else {
65026
- // No policy supplied: keep the currently active policy if one is set — a
65027
- // previously supplied policy is intentionally sticky across config-less
65028
- // calls — otherwise fall back to the instance's own internal policy,
65029
- // created at most once. (A policy supplied for a *single* call still
65030
- // lingers by design; what must not linger is a policy whose configuration
65031
- // has been torn down via `clearConfig()`, which restores the default.)
65032
- if (trustedTypesPolicy === undefined) {
65033
- trustedTypesPolicy = _getDefaultTrustedTypesPolicy();
65034
- }
65035
- // Sign internal variables only when a policy is active. A falsy policy
65036
- // (Trusted Types unsupported, creation failed, or an explicit opt-out)
65037
- // leaves `emptyHTML` as a plain string, so we never call `.createHTML` on
65038
- // a non-policy and throw. See #1422.
65039
- if (trustedTypesPolicy && typeof emptyHTML === 'string') {
65040
- emptyHTML = _createTrustedHTML('');
65041
- }
65042
- }
65043
- // Prevent further manipulation of configuration.
65044
- // Not available in IE8, Safari 5, etc.
65045
- if (freeze) {
65046
- freeze(cfg);
65047
- }
65048
- CONFIG = cfg;
65049
- };
65050
- /* Keep track of all possible SVG and MathML tags
65051
- * so that we can perform the namespace checks
65052
- * correctly. */
65053
- const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]);
65054
- const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]);
65055
- /**
65056
- * Namespace rules for an element in the SVG namespace.
65057
- *
65058
- * @param tagName the element's lowercase tag name
65059
- * @param parent the (possibly simulated) parent node
65060
- * @param parentTagName the parent's lowercase tag name
65061
- * @returns true if a spec-compliant parser could produce this element
65062
- */
65063
- const _checkSvgNamespace = function _checkSvgNamespace(tagName, parent, parentTagName) {
65064
- // The only way to switch from HTML namespace to SVG
65065
- // is via <svg>. If it happens via any other tag, then
65066
- // it should be killed.
65067
- if (parent.namespaceURI === HTML_NAMESPACE) {
65068
- return tagName === 'svg';
65069
- }
65070
- // The only way to switch from MathML to SVG is via <svg>
65071
- // if the parent is either <annotation-xml> or a MathML
65072
- // text integration point.
65073
- if (parent.namespaceURI === MATHML_NAMESPACE) {
65074
- return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
65075
- }
65076
- // We only allow elements that are defined in SVG
65077
- // spec. All others are disallowed in SVG namespace.
65078
- return Boolean(ALL_SVG_TAGS[tagName]);
65079
- };
65080
- /**
65081
- * Namespace rules for an element in the MathML namespace.
65082
- *
65083
- * @param tagName the element's lowercase tag name
65084
- * @param parent the (possibly simulated) parent node
65085
- * @param parentTagName the parent's lowercase tag name
65086
- * @returns true if a spec-compliant parser could produce this element
65087
- */
65088
- const _checkMathMlNamespace = function _checkMathMlNamespace(tagName, parent, parentTagName) {
65089
- // The only way to switch from HTML namespace to MathML
65090
- // is via <math>. If it happens via any other tag, then
65091
- // it should be killed.
65092
- if (parent.namespaceURI === HTML_NAMESPACE) {
65093
- return tagName === 'math';
65094
- }
65095
- // The only way to switch from SVG to MathML is via
65096
- // <math> and HTML integration points
65097
- if (parent.namespaceURI === SVG_NAMESPACE) {
65098
- return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
65099
- }
65100
- // We only allow elements that are defined in MathML
65101
- // spec. All others are disallowed in MathML namespace.
65102
- return Boolean(ALL_MATHML_TAGS[tagName]);
65103
- };
65104
- /**
65105
- * Namespace rules for an element in the HTML namespace.
65106
- *
65107
- * @param tagName the element's lowercase tag name
65108
- * @param parent the (possibly simulated) parent node
65109
- * @param parentTagName the parent's lowercase tag name
65110
- * @returns true if a spec-compliant parser could produce this element
65111
- */
65112
- const _checkHtmlNamespace = function _checkHtmlNamespace(tagName, parent, parentTagName) {
65113
- // The only way to switch from SVG to HTML is via
65114
- // HTML integration points, and from MathML to HTML
65115
- // is via MathML text integration points
65116
- if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
65117
- return false;
65118
- }
65119
- if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
65120
- return false;
65121
- }
65122
- // We disallow tags that are specific for MathML
65123
- // or SVG and should never appear in HTML namespace
65124
- return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
65125
- };
65126
- /**
65127
- * @param element a DOM element whose namespace is being checked
65128
- * @returns Return false if the element has a
65129
- * namespace that a spec-compliant parser would never
65130
- * return. Return true otherwise.
65131
- */
65132
- const _checkValidNamespace = function _checkValidNamespace(element) {
65133
- let parent = getParentNode(element);
65134
- // In JSDOM, if we're inside shadow DOM, then parentNode
65135
- // can be null. We just simulate parent in this case.
65136
- if (!parent || !parent.tagName) {
65137
- parent = {
65138
- namespaceURI: NAMESPACE,
65139
- tagName: 'template'
65140
- };
65141
- }
65142
- const tagName = stringToLowerCase(element.tagName);
65143
- const parentTagName = stringToLowerCase(parent.tagName);
65144
- if (!ALLOWED_NAMESPACES[element.namespaceURI]) {
65145
- return false;
65146
- }
65147
- if (element.namespaceURI === SVG_NAMESPACE) {
65148
- return _checkSvgNamespace(tagName, parent, parentTagName);
65149
- }
65150
- if (element.namespaceURI === MATHML_NAMESPACE) {
65151
- return _checkMathMlNamespace(tagName, parent, parentTagName);
65152
- }
65153
- if (element.namespaceURI === HTML_NAMESPACE) {
65154
- return _checkHtmlNamespace(tagName, parent, parentTagName);
65155
- }
65156
- // For XHTML and XML documents that support custom namespaces
65157
- if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) {
65158
- return true;
65159
- }
65160
- // The code should never reach this place (this means
65161
- // that the element somehow got namespace that is not
65162
- // HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES).
65163
- // Return false just in case.
65164
- return false;
65165
- };
65166
- /**
65167
- * _forceRemove
65168
- *
65169
- * @param node a DOM node
65170
- */
65171
- const _forceRemove = function _forceRemove(node) {
65172
- arrayPush(DOMPurify.removed, {
65173
- element: node
65174
- });
65175
- try {
65176
- // eslint-disable-next-line unicorn/prefer-dom-node-remove
65177
- getParentNode(node).removeChild(node);
65178
- } catch (_) {
65179
- /* The normal detach failed — this is reached for a parentless node
65180
- (getParentNode() is null, so .removeChild throws). Element.prototype
65181
- .remove() is itself a spec no-op on a parentless node, so a recorded
65182
- "removal" would otherwise hand the caller back an intact,
65183
- payload-bearing node (e.g. a detached IN_PLACE root the mXSS canary or
65184
- the style-with-element-child rule decided to kill). Fail closed by
65185
- throwing — exactly as a clobbered root does at the IN_PLACE entry —
65186
- rather than trying to "neutralize" the node via its own methods.
65187
- Neutralizing would mean calling getAttributeNames()/removeAttribute()
65188
- on the node, both of which a <form> root can clobber via a named child
65189
- (and _isClobbered does not even probe getAttributeNames), so the
65190
- neutralize step could itself be silently defeated, leaving the payload
65191
- intact. A throw touches only the cached, clobber-safe remove() and
65192
- getParentNode(). Generalizes GHSA-r47g-fvhr-h676 (clobbered-form root)
65193
- to every root-kill reason. REPORT-3.
65194
- This lives inside the catch, so it never fires for a normally-removed
65195
- in-tree node: those have a parent, removeChild() succeeds, and the
65196
- catch is not entered. Only a kept (parentless) root reaches here. */
65197
- remove(node);
65198
- if (!getParentNode(node)) {
65199
- throw typeErrorCreate('a node selected for removal could not be detached from its tree ' + 'and cannot be safely returned; refusing to sanitize in place');
65200
- }
65201
- }
65202
- };
65203
- /**
65204
- * _stripAttributeNode
65205
- *
65206
- * Remove a single Attr node case/namespace-exactly on an attribute-teardown
65207
- * path. Name-based removeAttribute() ASCII-lowercases its lookup key for an
65208
- * HTML element in an HTML document and so silently misses a case-preserved
65209
- * handler (e.g. `ONERROR` off an XML/XHTML import) - the same defect
65210
- * _removeAttribute() was fixed for, which a name-based call would reintroduce
65211
- * on these IN_PLACE teardown paths. Unlike _removeAttribute this does not
65212
- * record into DOMPurify.removed: the neutralize passes intentionally do not
65213
- * book-keep. A clobbered/detached node falls back to best-effort name-based
65214
- * removal.
65215
- *
65216
- * @param element the element to strip the attribute from
65217
- * @param attribute the Attr node to remove
65218
- * @param name the attribute's name, for the fallback path
65219
- */
65220
- const _stripAttributeNode = function _stripAttributeNode(element, attribute, name) {
65221
- try {
65222
- removeAttributeNode(element, attribute);
65223
- } catch (_) {
65224
- try {
65225
- element.removeAttribute(name);
65226
- } catch (_) {}
65227
- }
65228
- };
65229
- /**
65230
- * _neutralizeRoot
65231
- *
65232
- * Fail-closed teardown of an in-place root after the sanitize walk aborts
65233
- * (campaign-3 F2). An internal throw mid-walk — e.g. a page-registered
65234
- * custom element's reaction detaches a node so `_forceRemove`'s deliberate
65235
- * parentless guard throws, or any other re-entrant engine mutation — would
65236
- * otherwise leave the caller's *live* tree half-sanitized, with everything
65237
- * after the abort point still carrying its handlers. There is no safe way
65238
- * to resume the walk (the tree mutated under us), so we strip the root bare:
65239
- * remove every child and every attribute, then let the caller's catch see
65240
- * the original error. Clobber-safe (cached `remove`/`childNodes`/`attributes`
65241
- * getters; the root was already clobber-pre-flighted at the IN_PLACE entry).
65242
- *
65243
- * @param root the in-place root to empty
65244
- */
65245
- const _neutralizeRoot = function _neutralizeRoot(root) {
65246
- /* Strip every disallowed attribute (on* handlers included) off the whole
65247
- subtree BEFORE detaching anything. Detaching first would hand back
65248
- handler-bearing originals (e.g. an already-loading `<img onerror>`)
65249
- whose queued resource event still fires in page scope after we throw.
65250
- Clobber-safe reads; a doomed clobbered node's own attributes are
65251
- irrelevant while its non-clobbered descendants are reached and scrubbed. */
65252
- _neutralizeSubtree(root);
65253
- const childNodes = getChildNodes(root);
65254
- if (childNodes) {
65255
- const snapshot = [];
65256
- arrayForEach(childNodes, child => {
65257
- arrayPush(snapshot, child);
65258
- });
65259
- arrayForEach(snapshot, child => {
65260
- try {
65261
- remove(child);
65262
- } catch (_) {
65263
- /* Best-effort teardown; a still-attached child is handled below */
65264
- }
65265
- });
65266
- }
65267
- const attributes = getAttributes(root);
65268
- if (attributes) {
65269
- for (let i = attributes.length - 1; i >= 0; --i) {
65270
- const attribute = attributes[i];
65271
- const name = attribute && attribute.name;
65272
- if (typeof name === 'string') {
65273
- _stripAttributeNode(root, attribute, name);
65274
- }
65275
- }
65276
- }
65277
- };
65278
- /**
65279
- * _removeAttribute
65280
- *
65281
- * Name-based getAttributeNode()/removeAttribute() ASCII-lowercase their
65282
- * lookup key for HTML elements in an HTML document, so they silently miss an
65283
- * attribute whose stored qualified name still contains uppercase ASCII
65284
- * letters. That happens when the node came from a case-preserving source
65285
- * (an XML/XHTML document imported via importNode(), or createAttributeNS()),
65286
- * where e.g. `ONERROR` survives the walk: the policy check lowercases to
65287
- * `onerror` and rejects it, but `removeAttribute('ONERROR')` looks up
65288
- * `onerror` and finds nothing. Remove the exact Attr node instead, which is
65289
- * case- and namespace-exact, and fall back to name-based removal only when
65290
- * the caller could not supply the node.
65291
- *
65292
- * @param name an Attribute name
65293
- * @param element a DOM node
65294
- * @param attr the exact Attr node to remove, when the caller has it
65295
- */
65296
- const _removeAttribute = function _removeAttribute(name, element, attr) {
65297
- if (!attr) {
65298
- try {
65299
- attr = element.getAttributeNode(name);
65300
- } catch (_) {
65301
- attr = null;
65302
- }
65303
- }
65304
- arrayPush(DOMPurify.removed, {
65305
- attribute: attr || null,
65306
- from: element
65307
- });
65308
- try {
65309
- if (attr) {
65310
- removeAttributeNode(element, attr);
65311
- } else {
65312
- element.removeAttribute(name);
65313
- }
65314
- } catch (_) {
65315
- /* Clobbered or already-detached node - best-effort fall back to a
65316
- name-based removal so the "is" handling below still runs. Note this
65317
- fallback ASCII-lowercases its lookup key in an HTML document and so
65318
- cannot reach a case-preserved attribute name; the cached
65319
- removeAttributeNode() above is what removes those, and a clobbered
65320
- form is already removed wholesale by _isClobbered() before reaching
65321
- here. */
65322
- try {
65323
- element.removeAttribute(name);
65324
- } catch (_) {}
65325
- }
65326
- // We void attribute values for unremovable "is" attributes
65327
- if (name === 'is') {
65328
- if (RETURN_DOM || RETURN_DOM_FRAGMENT) {
65329
- try {
65330
- _forceRemove(element);
65331
- } catch (_) {}
65332
- } else {
65333
- try {
65334
- element.setAttribute(name, '');
65335
- } catch (_) {}
65336
- }
65337
- }
65338
- };
65339
- /**
65340
- * _stripDisallowedAttributes
65341
- *
65342
- * Removes every attribute the active configuration does not allow from a
65343
- * single element, using the same allowlist as the main attribute pass (so
65344
- * `on*` handlers go, but no `/^on/` blocklist is introduced). Used only to
65345
- * neutralise nodes that are being discarded from an in-place tree.
65346
- *
65347
- * @param element the element to strip
65348
- */
65349
- const _stripDisallowedAttributes = function _stripDisallowedAttributes(element) {
65350
- const attributes = getAttributes(element);
65351
- if (!attributes) {
65352
- return;
65353
- }
65354
- for (let i = attributes.length - 1; i >= 0; --i) {
65355
- const attribute = attributes[i];
65356
- const name = attribute && attribute.name;
65357
- if (typeof name !== 'string' || ALLOWED_ATTR[transformCaseFunc(name)]) {
65358
- continue;
65359
- }
65360
- _stripAttributeNode(element, attribute, name);
65361
- }
65362
- };
65363
- /**
65364
- * _neutralizeSubtree
65365
- *
65366
- * Completes the audit-5 F1 fix across every removal path. The KEEP_CONTENT
65367
- * move-hoist neutralises only disallowed-tag removals; clobber, mXSS-canary,
65368
- * namespace, comment, processing-instruction and KEEP_CONTENT:false removals
65369
- * all drop their subtree wholesale via `_forceRemove`. On the IN_PLACE path
65370
- * those dropped nodes are detached from the caller's LIVE tree but a
65371
- * handler-bearing original among them (an `<img onerror>`/`<video>` that was
65372
- * loading) keeps its queued resource event, which fires in page scope after
65373
- * sanitize returns. This walks a removed subtree and strips every attribute
65374
- * the active configuration does not allow — so `on*` handlers are cancelled
65375
- * through the SAME allowlist that governs kept nodes, not a separate `/^on/`
65376
- * blocklist. Run synchronously before sanitize returns, i.e. before any
65377
- * queued event can fire. Hook-free by design: these nodes leave the output,
65378
- * so firing attribute hooks for them would be surprising. Clobber-safe reads;
65379
- * a doomed clobbered node may shadow `removeAttribute` (its own attributes are
65380
- * irrelevant — it is discarded — while its non-clobbered descendants, e.g.
65381
- * the `<img>`, are reached and scrubbed).
65382
- *
65383
- * @param root the root of a removed subtree to neutralise
65384
- */
65385
- const _neutralizeSubtree = function _neutralizeSubtree(root) {
65386
- const stack = [root];
65387
- while (stack.length > 0) {
65388
- const node = stack.pop();
65389
- const nodeType = _readNodeType(node);
65390
- if (nodeType === NODE_TYPE.element) {
65391
- _stripDisallowedAttributes(node);
65392
- }
65393
- const childNodes = getChildNodes(node);
65394
- if (childNodes) {
65395
- for (let i = childNodes.length - 1; i >= 0; --i) {
65396
- stack.push(childNodes[i]);
65397
- }
65398
- }
65399
- }
65400
- };
65401
- /**
65402
- * _neutralizePatchLinkage
65403
- *
65404
- * IN_PLACE entry pre-pass (declarative-partial-updates / streaming
65405
- * hardening, https://github.com/WICG/declarative-partial-updates).
65406
- *
65407
- * The main walk strips patch linkage (`for`/`patchsrc`) and removes range
65408
- * markers (PIs / markup comments) node-by-node, in document order, AS it
65409
- * reaches each node. On a live in-place root that leaves a window: from the
65410
- * moment the root is connected until the walk arrives at a given node, that
65411
- * node's linkage is live. A patch applied on connection/stream can fire as
65412
- * a microtask during the walk and inject or teleport an unsanitized DOM
65413
- * range into a region the iterator has already passed and will not revisit,
65414
- * so the post-return "tree is sanitized" contract is violated. Sweep the
65415
- * whole tree once up front and sever every linkage before the walk begins,
65416
- * closing that window.
65417
- *
65418
- * This CANNOT undo a patch that already fired before sanitize ran — that is
65419
- * the irreducible "do not IN_PLACE a live-connected attacker tree" caveat —
65420
- * but it closes everything from sanitize-start onward. Gated on SAFE_FOR_XML
65421
- * to group with the rest of the declarative-partial-updates handling and
65422
- * stay overridable, consistent with the codebase.
65423
- *
65424
- * Clobber-safe traversal (cached childNodes getter); per-node try/catch so a
65425
- * clobbered root cannot defeat the sweep of its non-clobbered descendants.
65426
- *
65427
- * NOTE (pending real-Chrome confirmation, see test/declarative-patch-probe
65428
- * .html Q1): this mirrors the existing policy of keeping `for` on
65429
- * <label>/<output>. If the shipping feature can drive a patch through a
65430
- * surviving `for`-on-label/output + `id` pair, this pre-pass and the
65431
- * attribute check at _isBasicCustomElement's caller must additionally drop
65432
- * that pair on the IN_PLACE path. Left as-is until the taxonomy is verified.
65433
- *
65434
- * @param root the in-place root to sweep
65435
- */
65436
- /**
65437
- * Central policy for declarative-partial-updates patch-linkage attributes,
65438
- * shared by the _neutralizePatchLinkage pre-pass and _isValidAttribute so
65439
- * the two sites cannot drift: `patchsrc` always links, `for` links
65440
- * everywhere except on <label>/<output>, and the whole policy is gated on
65441
- * SAFE_FOR_XML (see the rationale block in _isValidAttribute).
65442
- *
65443
- * @param lcName the transformCaseFunc'd attribute name
65444
- * @param lcTag the transformCaseFunc'd tag name of the carrying element
65445
- * @return true if the attribute is patch linkage and must be dropped
65446
- */
65447
- const _isPatchLinkageAttribute = function _isPatchLinkageAttribute(lcName, lcTag) {
65448
- if (!SAFE_FOR_XML) {
65449
- return false;
65450
- }
65451
- if (lcName === 'patchsrc') {
65452
- return true;
65453
- }
65454
- return lcName === 'for' && lcTag !== 'label' && lcTag !== 'output';
65455
- };
65456
- const _neutralizePatchLinkage = function _neutralizePatchLinkage(root) {
65457
- if (!SAFE_FOR_XML) {
65458
- return;
65459
- }
65460
- const stack = [root];
65461
- while (stack.length > 0) {
65462
- const node = stack.pop();
65463
- const nodeType = _readNodeType(node);
65464
- /* Remove range markers (the target side of a patch linkage): every
65465
- processing instruction, and any markup-bearing comment. */
65466
- if (nodeType === NODE_TYPE.processingInstruction || nodeType === NODE_TYPE.comment && regExpTest(COMMENT_MARKUP_PROBE, node.data)) {
65467
- try {
65468
- remove(node);
65469
- } catch (_) {
65470
- /* Best-effort */
65471
- }
65472
- continue;
65473
- }
65474
- /* Strip patch-source attributes (the source side) off elements. */
65475
- if (nodeType === NODE_TYPE.element) {
65476
- const element = node;
65477
- const lcTag = transformCaseFunc(_readNodeName(node));
65478
- try {
65479
- if (element.hasAttribute && element.hasAttribute('patchsrc')) {
65480
- element.removeAttribute('patchsrc');
65481
- }
65482
- if (element.hasAttribute && element.hasAttribute('for') && _isPatchLinkageAttribute('for', lcTag)) {
65483
- element.removeAttribute('for');
65484
- }
65485
- } catch (_) {
65486
- /* Clobbered removeAttribute/hasAttribute on a doomed node — ignore */
65487
- }
65488
- }
65489
- const childNodes = getChildNodes(node);
65490
- if (childNodes) {
65491
- for (let i = childNodes.length - 1; i >= 0; --i) {
65492
- stack.push(childNodes[i]);
65493
- }
65494
- }
65495
- }
65496
- };
65497
- /**
65498
- * _initDocument
65499
- *
65500
- * @param dirty - a string of dirty markup
65501
- * @return a DOM, filled with the dirty markup
65502
- */
65503
- const _initDocument = function _initDocument(dirty) {
65504
- /* Create a HTML document */
65505
- let doc = null;
65506
- let leadingWhitespace = null;
65507
- if (FORCE_BODY) {
65508
- dirty = '<remove></remove>' + dirty;
65509
- } else {
65510
- /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */
65511
- const matches = stringMatch(dirty, /^[\r\n\t ]+/);
65512
- leadingWhitespace = matches && matches[0];
65513
- }
65514
- if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && NAMESPACE === HTML_NAMESPACE) {
65515
- // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)
65516
- dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + '</body></html>';
65517
- }
65518
- const dirtyPayload = trustedTypesPolicy ? _createTrustedHTML(dirty) : dirty;
65519
- /*
65520
- * Use the DOMParser API by default, fallback later if needs be
65521
- * DOMParser not work for svg when has multiple root element.
65522
- */
65523
- if (NAMESPACE === HTML_NAMESPACE) {
65524
- try {
65525
- doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);
65526
- } catch (_) {}
65527
- }
65528
- /* Use createHTMLDocument in case DOMParser is not available */
65529
- if (!doc || !doc.documentElement) {
65530
- doc = implementation.createDocument(NAMESPACE, 'template', null);
65531
- try {
65532
- doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload;
65533
- } catch (_) {
65534
- // Syntax error if dirtyPayload is invalid xml
65535
- }
65536
- }
65537
- const body = doc.body || doc.documentElement;
65538
- if (dirty && leadingWhitespace) {
65539
- body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null);
65540
- }
65541
- /* Work on whole document or just its body */
65542
- if (NAMESPACE === HTML_NAMESPACE) {
65543
- return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0];
65544
- }
65545
- return WHOLE_DOCUMENT ? doc.documentElement : body;
65546
- };
65547
- /**
65548
- * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document.
65549
- *
65550
- * @param root The root element or node to start traversing on.
65551
- * @return The created NodeIterator
65552
- */
65553
- const _createNodeIterator = function _createNodeIterator(root) {
65554
- /* Read ownerDocument through the cached Node.prototype getter, never the
65555
- direct property. HTMLFormElement has [LegacyOverrideBuiltIns], so a
65556
- clobbering child (<input name="ownerDocument"> or a form-associated
65557
- external input) shadows the prototype getter and makes a direct read
65558
- return that <input>. createNodeIterator.call(<input>, ...) then throws
65559
- "Illegal invocation", and on the IN_PLACE path that throw lands before
65560
- the walk's fail-closed barrier - leaving the caller's live tree, with
65561
- any already-armed handler in it, un-neutralized. The cached getter
65562
- returns the real Document regardless of the clobber. */
65563
- const doc = getOwnerDocument ? getOwnerDocument(root) : root.ownerDocument;
65564
- return createNodeIterator.call(doc || root, root,
65565
- // eslint-disable-next-line no-bitwise
65566
- NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null);
65567
- };
65568
- /**
65569
- * Replace template expression syntax (mustache, ERB, template
65570
- * literal) with a space; shared by all SAFE_FOR_TEMPLATES scrub
65571
- * sites. Order matters: mustache, then ERB, then template literal.
65572
- *
65573
- * @param value the string to scrub
65574
- * @returns the scrubbed string
65575
- */
65576
- const _stripTemplateExpressions = function _stripTemplateExpressions(value) {
65577
- value = stringReplace(value, MUSTACHE_EXPR$1, ' ');
65578
- value = stringReplace(value, ERB_EXPR$1, ' ');
65579
- value = stringReplace(value, TMPLIT_EXPR$1, ' ');
65580
- return value;
65581
- };
65582
- /**
65583
- * Strip template-engine expressions ({{...}}, ${...}, <%...%>) from the
65584
- * character data of an element subtree. Used as the final safety net for
65585
- * SAFE_FOR_TEMPLATES on every DOM-returning code path so that expressions
65586
- * which only form after text-node normalization (e.g. fragments split across
65587
- * stripped elements) cannot survive into a template-evaluating framework.
65588
- *
65589
- * Walks text/comment/CDATA/processing-instruction nodes and mutates `.data`
65590
- * in place rather than round-tripping through innerHTML. This preserves
65591
- * descendant node references (important for IN_PLACE callers), avoids a
65592
- * serialize/reparse cycle, and reads literal character data — which means
65593
- * `<%...%>` in text content matches the ERB regex against its real bytes
65594
- * instead of the HTML-entity-escaped form innerHTML would produce.
65595
- *
65596
- * Attribute values are not visited here; SAFE_FOR_TEMPLATES handling for
65597
- * attributes is performed during the per-node `_sanitizeAttributes` pass.
65598
- *
65599
- * @param node The root element whose character data should be scrubbed.
65600
- */
65601
- const _scrubTemplateExpressions2 = function _scrubTemplateExpressions(node) {
65602
- var _node$querySelectorAl;
65603
- node.normalize();
65604
- /* Clobber-safe ownerDocument read, same reasoning as _createNodeIterator:
65605
- under SAFE_FOR_TEMPLATES this runs on the live IN_PLACE root, which may
65606
- carry a form-named-getter override of ownerDocument. */
65607
- const doc = getOwnerDocument ? getOwnerDocument(node) : node.ownerDocument;
65608
- const walker = createNodeIterator.call(doc || node, node,
65609
- // eslint-disable-next-line no-bitwise
65610
- NodeFilter.SHOW_TEXT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_CDATA_SECTION | NodeFilter.SHOW_PROCESSING_INSTRUCTION, null);
65611
- let currentNode = walker.nextNode();
65612
- while (currentNode) {
65613
- currentNode.data = _stripTemplateExpressions(currentNode.data);
65614
- currentNode = walker.nextNode();
65615
- }
65616
- // NodeIterator does not descend into <template>.content per the DOM spec,
65617
- // so we must explicitly recurse into each template's content fragment,
65618
- // mirroring the approach used by _sanitizeShadowDOM.
65619
- const templates = (_node$querySelectorAl = node.querySelectorAll) === null || _node$querySelectorAl === void 0 ? void 0 : _node$querySelectorAl.call(node, 'template');
65620
- if (templates) {
65621
- arrayForEach(templates, tmpl => {
65622
- if (_isDocumentFragment(tmpl.content)) {
65623
- _scrubTemplateExpressions2(tmpl.content);
65624
- }
65625
- });
65626
- }
65627
- };
65628
- /**
65629
- * _isClobbered
65630
- *
65631
- * Detect DOM-clobbering on HTMLFormElement nodes. Form is the only HTML
65632
- * interface with [LegacyOverrideBuiltIns]; a descendant element with a
65633
- * `name` attribute matching a prototype property shadows that property
65634
- * on direct reads. We use this check at the IN_PLACE entry-point and
65635
- * during attribute sanitization to refuse clobbered forms.
65636
- *
65637
- * @param element element to check for clobbering attacks
65638
- * @return true if clobbered, false if safe
65639
- */
65640
- const _isClobbered = function _isClobbered(element) {
65641
- // Realm-independent tag-name probe. If we can't determine the tag
65642
- // name at all, we can't reason about clobbering — return false
65643
- // (the caller's other defences still apply).
65644
- const realTagName = getNodeName ? getNodeName(element) : null;
65645
- if (typeof realTagName !== 'string') {
65646
- return false;
65647
- }
65648
- if (transformCaseFunc(realTagName) !== 'form') {
65649
- return false;
65650
- }
65651
- return typeof element.nodeName !== 'string' || typeof element.textContent !== 'string' || typeof element.removeChild !== 'function' ||
65652
- // Realm-safe NamedNodeMap detection: equality against the cached
65653
- // prototype getter. Clobbered .attributes (e.g. <input name="attributes">)
65654
- // makes the direct read diverge from the cached read; a clean form
65655
- // (same-realm OR foreign-realm) has both reads pointing at the same
65656
- // canonical NamedNodeMap.
65657
- element.attributes !== getAttributes(element) || typeof element.removeAttribute !== 'function' ||
65658
- // A form descendant named "removeAttributeNode" or "getAttributeNode"
65659
- // shadows these Attr-node methods via [LegacyOverrideBuiltIns].
65660
- // _removeAttribute() / _stripAttributeNode() reach for
65661
- // element.removeAttributeNode(attr) first; when it is shadowed the call
65662
- // throws and the name-based fallback element.removeAttribute(name)
65663
- // ASCII-lowercases its lookup key in an HTML document, silently missing
65664
- // a case-preserved event-handler attribute (e.g. an ONANIMATIONSTART
65665
- // that reached the sanitizer through an XML/XHTML parse). Flag the form
65666
- // so it is removed wholesale, exactly as for the other shadowed methods.
65667
- typeof element.removeAttributeNode !== 'function' || typeof element.getAttributeNode !== 'function' || typeof element.setAttribute !== 'function' || typeof element.namespaceURI !== 'string' || typeof element.insertBefore !== 'function' || typeof element.hasChildNodes !== 'function' ||
65668
- // NodeType clobbering probe. Cached Node.prototype.nodeType getter
65669
- // returns the integer 1 for any Element regardless of realm; direct
65670
- // read on a clobbered form (e.g. <input name="nodeType">) returns
65671
- // the named child element. Cheap addition — nodeType is read from
65672
- // an internal slot, no serialization cost — and removes a residual
65673
- // clobbering surface used by several mXSS / PI / comment branches
65674
- // in _sanitizeElements that compare currentNode.nodeType directly.
65675
- element.nodeType !== getNodeType(element) ||
65676
- // HTMLFormElement has [LegacyOverrideBuiltIns]: a descendant named
65677
- // "childNodes" shadows the prototype getter. Direct reads of
65678
- // form.childNodes from a clobbered form return the named child
65679
- // instead of the real NodeList, so any walk that reads it directly
65680
- // skips the form's real children. Compare the direct read to the
65681
- // cached Node.prototype getter — when the form's named-property
65682
- // getter intercepts the read, the two values differ and we flag
65683
- // the form. This catches every clobbering child type (input,
65684
- // select, etc.) regardless of whether the named child happens to
65685
- // carry a numeric .length, which a typeof-based probe would miss
65686
- // (e.g. HTMLSelectElement.length is a defined unsigned-long).
65687
- element.childNodes !== getChildNodes(element);
65688
- };
65689
- /**
65690
- * Checks whether the given value is a DocumentFragment from any realm.
65691
- *
65692
- * The realm-independent replacement reads `nodeType` through the cached
65693
- * Node.prototype getter and compares to the DOCUMENT_FRAGMENT_NODE
65694
- * constant (11). nodeType is a numeric value resolved from the node's
65695
- * internal slot, identical across realms for the same kind of node.
65696
- *
65697
- * @param value object to check
65698
- * @return true if value is a DocumentFragment-shaped node from any realm
65699
- */
65700
- const _isDocumentFragment = function _isDocumentFragment(value) {
65701
- if (!getNodeType || typeof value !== 'object' || value === null) {
65702
- return false;
65703
- }
65704
- try {
65705
- return getNodeType(value) === NODE_TYPE.documentFragment;
65706
- } catch (_) {
65707
- return false;
65708
- }
65709
- };
65710
- /**
65711
- * Checks whether the given object is a DOM node, including nodes that
65712
- * originate from a different window/realm (e.g. an iframe's
65713
- * contentDocument). The previous `value instanceof Node` check was
65714
- * realm-bound: nodes from a different window failed it, causing
65715
- * sanitize() to silently stringify them and reset IN_PLACE to false,
65716
- * returning the original node unsanitized. See GHSA-4w3q-35jp-p934.
65717
- *
65718
- * @param value object to check whether it's a DOM node
65719
- * @return true if value is a DOM node from any realm
65720
- */
65721
- const _isNode = function _isNode(value) {
65722
- if (!getNodeType || typeof value !== 'object' || value === null) {
65723
- return false;
65724
- }
65725
- try {
65726
- return typeof getNodeType(value) === 'number';
65727
- } catch (_) {
65728
- return false;
65729
- }
65730
- };
65731
- function _executeHooks(hooks, currentNode, data) {
65732
- if (hooks.length === 0) {
65733
- return;
65734
- }
65735
- arrayForEach(hooks, hook => {
65736
- hook.call(DOMPurify, currentNode, data, CONFIG);
65737
- });
65738
- }
65739
- /**
65740
- * Structural-threat checks that condemn a node regardless of the
65741
- * allowlists: mXSS via namespace confusion, risky CSS construction,
65742
- * processing instructions, markup-bearing comments. Pure predicate;
65743
- * the caller removes. Check order is load-bearing.
65744
- *
65745
- * @param currentNode the node to inspect
65746
- * @param tagName the node's transformCaseFunc'd tag name
65747
- * @return true if the node must be removed
65748
- */
65749
- const _isUnsafeNode = function _isUnsafeNode(currentNode, tagName) {
65750
- /* Detect mXSS attempts abusing namespace confusion */
65751
- if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.textContent) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.innerHTML)) {
65752
- return true;
65753
- }
65754
- /* Remove rawtext/literal-text elements whose literal serialization
65755
- re-opens markup on an HTML reparse - shapes (a) and (b) documented at
65756
- LITERAL_TEXT_ELEMENTS. Both are invisible to rule 1 above (which
65757
- self-disables once there is an element child, and whose second probe
65758
- reads the innerHTML an XML/XHTML document serializes escaped), which
65759
- is why both probes here read textContent instead. Previously only
65760
- `style`-with-element-child was covered; every element in
65761
- LITERAL_TEXT_ELEMENTS shares this literal serialization and is
65762
- equally affected. */
65763
- if (SAFE_FOR_XML && currentNode.namespaceURI === HTML_NAMESPACE && LITERAL_TEXT_ELEMENTS[tagName] && (_isNode(currentNode.firstElementChild) || typeof currentNode.textContent === 'string' && regExpTest(LITERAL_TEXT_CLOSE[tagName], currentNode.textContent))) {
65764
- return true;
65765
- }
65766
- /* Remove any occurrence of processing instructions */
65767
- if (currentNode.nodeType === NODE_TYPE.processingInstruction) {
65768
- return true;
65769
- }
65770
- /* Remove any kind of possibly harmful comments */
65771
- if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(COMMENT_MARKUP_PROBE, currentNode.data)) {
65772
- return true;
65773
- }
65774
- return false;
65775
- };
65776
- /**
65777
- * Evaluate a CUSTOM_ELEMENT_HANDLING check (a RegExp or a predicate
65778
- * function, per the validation in _parseConfig) against a name.
65779
- * Additional arguments are forwarded to predicate functions - the
65780
- * attributeNameCheck predicate receives the tag name as its second
65781
- * argument. A null/absent check never matches.
65782
- *
65783
- * @param check the configured tagNameCheck / attributeNameCheck value
65784
- * @param name the name to test
65785
- * @param args extra arguments forwarded to a predicate function
65786
- * @return true if the check matches the name
65787
- */
65788
- const _matchesNameCheck = function _matchesNameCheck(check, name) {
65789
- if (check instanceof RegExp) {
65790
- return regExpTest(check, name);
65791
- }
65792
- if (check instanceof Function) {
65793
- for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
65794
- args[_key - 2] = arguments[_key];
65795
- }
65796
- return Boolean(check(name, ...args));
65797
- }
65798
- return false;
65799
- };
65800
- /**
65801
- * Handle a node whose tag is forbidden or not allowlisted: keep
65802
- * allowed custom elements (false return exits _sanitizeElements
65803
- * early - the namespace and fallback-tag removal checks are
65804
- * intentionally skipped for kept custom elements), else hoist
65805
- * content per KEEP_CONTENT and remove.
65806
- *
65807
- * A kept custom element is the ONLY case in which this function
65808
- * returns false, so the caller uses that return value to run the
65809
- * afterSanitizeElements hook on the kept element and keep the
65810
- * element-hook lifecycle consistent with normal allowlisted
65811
- * elements (GHSA-c2j3-45gr-mqc4).
65812
- *
65813
- * @param currentNode the disallowed node
65814
- * @param tagName the node's transformCaseFunc'd tag name
65815
- * @return true if the node was removed, false if kept
65816
- */
65817
- const _sanitizeDisallowedNode = function _sanitizeDisallowedNode(currentNode, tagName, root) {
65818
- /* Check if we have a custom element to handle */
65819
- if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName) && _matchesNameCheck(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {
65820
- return false;
65821
- }
65822
- /* Keep content except for bad-listed elements.
65823
- Use the cached prototype getters exclusively — the previous code
65824
- had `|| currentNode.parentNode` / `|| currentNode.childNodes`
65825
- fallbacks, but the cached getters always return the canonical
65826
- value (or null for a real parent-less node), so the fallback
65827
- path was dead in safe cases and a clobbering surface in unsafe
65828
- ones. Falsy cached results stay falsy; the `if (childNodes &&
65829
- parentNode)` check already gates correctly. */
65830
- if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
65831
- const parentNode = getParentNode(currentNode);
65832
- const childNodes = getChildNodes(currentNode);
65833
- if (childNodes && parentNode) {
65834
- const childCount = childNodes.length;
65835
- /* Hoist by moving each child up one level rather than deep-cloning
65836
- it. Moving transfers every descendant exactly once, so a chain of
65837
- nested disallowed elements costs O(n) instead of the O(n^2) that
65838
- re-cloning the shrinking subtree at each level produced; it also
65839
- empties the removed original, so `DOMPurify.removed` no longer
65840
- pins whole subtrees. Moving preserves the in-place guarantee too:
65841
- an original carrying already-queued resource events (`<img
65842
- onerror>`, `<video>`/`<audio>` error, lazy/`onload`, …) is
65843
- relocated and sanitised rather than left detached but still armed.
65844
- The sole case that must clone is removing the walk root itself.
65845
- The result is serialised from the root's subtree, so a restrictive
65846
- ALLOWED_TAGS that strips the root (`body` on the string path) must
65847
- leave the content inside it, which only cloning does. In IN_PLACE
65848
- the root is pre-validated as an allowed tag and so is never removed
65849
- here, so that path always takes the move branch.
65850
- `childNodes` is live; a tail-to-head walk keeps `childNodes[i]`
65851
- valid whether we move (drops the trailing entry) or clone (leaves
65852
- the list intact). */
65853
- for (let i = childCount - 1; i >= 0; --i) {
65854
- const hoisted = currentNode === root ? cloneNode(childNodes[i], true) : childNodes[i];
65855
- parentNode.insertBefore(hoisted, getNextSibling(currentNode));
65856
- }
65857
- }
65858
- }
65859
- _forceRemove(currentNode);
65860
- return true;
65861
- };
65862
- /**
65863
- * Fork a hook-mutable allowlist off its shared binding the first time a
65864
- * (possibly lazily-installed) uponSanitize* hook is about to see it, so the
65865
- * hook cannot widen the per-instance default or the setConfig binding by
65866
- * reference and leak past the call. Returns the set unchanged once it is
65867
- * already call-local, so repeated calls across elements are idempotent.
65868
- *
65869
- * @param hookList the uponSanitize* hook array for this event
65870
- * @param set the current ALLOWED_TAGS / ALLOWED_ATTR binding
65871
- * @param defaultSet the per-instance DEFAULT_ALLOWED_* constant
65872
- * @param setConfigSet the captured setConfig() binding, or null
65873
- * @return a call-local clone if a hook is present and set is still shared,
65874
- * else set unchanged
65875
- */
65876
- const _forkSharedAllowlist = function _forkSharedAllowlist(hookList, set, defaultSet, setConfigSet) {
65877
- if (hookList.length === 0) {
65878
- return set;
65879
- }
65880
- return set === defaultSet || set === setConfigSet ? clone(set) : set;
65881
- };
65882
- /**
65883
- * Shared guard for a node that a hook has detached from the walk tree,
65884
- * used after each element-hook site in _sanitizeElements. Detaching is a
65885
- * long-standing user pattern (issue #469; draw.io-style foreignObject
65886
- * filtering). Per the cached, unclobberable parentNode getter the node is
65887
- * genuinely out of the tree, so it can reach neither the serialized
65888
- * output nor an IN_PLACE live tree; treat it as removed and stop
65889
- * processing it. Without this guard, the unsafe-node / namespace checks
65890
- * would call _forceRemove on a parentless node and hit the REPORT-3
65891
- * fail-closed throw — which exists for nodes DOMPurify wants gone but
65892
- * *cannot* detach (clobbered / parentless roots), the opposite of a node
65893
- * that is already safely gone. The walk root is exempt: a detached
65894
- * IN_PLACE root is legitimate input and must still be fully sanitized,
65895
- * and a kill-decision on it must keep hitting the REPORT-3 throw.
65896
- *
65897
- * Nodes detached by hooks stay the hook's responsibility for placement:
65898
- * they are not recorded in DOMPurify.removed, so the post-walk IN_PLACE
65899
- * pass (which iterates DOMPurify.removed) does not reach them. But a
65900
- * hook-detached subtree can still hold a queued resource-event handler -
65901
- * e.g. an <img onload> that began loading when the caller built the live
65902
- * tree - which fires in page scope after sanitize returns even though the
65903
- * handler never reached the returned tree. That is the audit-5 F1 hazard,
65904
- * and the documented node.remove() hook pattern walks straight into it.
65905
- * So on the IN_PLACE path we neutralize the detached subtree inline,
65906
- * stripping its non-allow-listed attributes before returning, exactly as
65907
- * the post-walk pass does for _forceRemove'd subtrees.
65908
- *
65909
- * @param currentNode the node a hook may have detached
65910
- * @param root the current walk root
65911
- * @return true if the node is detached and now handled, false otherwise
65912
- */
65913
- const _handleHookDetachedNode = function _handleHookDetachedNode(currentNode, root) {
65914
- if (currentNode === root || getParentNode(currentNode) !== null) {
65915
- return false;
65916
- }
65917
- if (IN_PLACE) {
65918
- _neutralizeSubtree(currentNode);
65919
- }
65920
- return true;
65921
- };
65922
- /**
65923
- * _sanitizeElements
65924
- *
65925
- * @protect nodeName
65926
- * @protect textContent
65927
- * @protect removeChild
65928
- * @param currentNode to check for permission to exist
65929
- * @return true if node was killed, false if left alive
65930
- */
65931
- const _sanitizeElements = function _sanitizeElements(currentNode, root) {
65932
- /* Execute a hook if present */
65933
- _executeHooks(hooks.beforeSanitizeElements, currentNode, null);
65934
- /* A hook may have detached the node - treat it as removed (see
65935
- _handleHookDetachedNode for the full rationale). */
65936
- if (_handleHookDetachedNode(currentNode, root)) {
65937
- return true;
65938
- }
65939
- /* Check if element is clobbered or can clobber */
65940
- if (_isClobbered(currentNode)) {
65941
- _forceRemove(currentNode);
65942
- return true;
65943
- }
65944
- /* Now let's check the element's type and name */
65945
- const tagName = transformCaseFunc(_readNodeName(currentNode));
65946
- /* Close the pre-walk clone-guard's timing gap: an uponSanitizeElement
65947
- hook may have been installed after that guard sampled the hook arrays
65948
- (e.g. lazily from beforeSanitizeElements), leaving ALLOWED_TAGS still
65949
- aliasing a shared binding that a widening hook would mutate by
65950
- reference. Fork it before exposing it to the hook. */
65951
- ALLOWED_TAGS = _forkSharedAllowlist(hooks.uponSanitizeElement, ALLOWED_TAGS, DEFAULT_ALLOWED_TAGS, SET_CONFIG_ALLOWED_TAGS);
65952
- /* Execute a hook if present */
65953
- _executeHooks(hooks.uponSanitizeElement, currentNode, {
65954
- tagName,
65955
- allowedTags: ALLOWED_TAGS
65956
- });
65957
- /* The uponSanitizeElement hook may have detached the node, exactly as
65958
- above (see _handleHookDetachedNode for the full rationale). */
65959
- if (_handleHookDetachedNode(currentNode, root)) {
65960
- return true;
65961
- }
65962
- /* Remove mXSS vectors, processing instructions and risky comments */
65963
- if (_isUnsafeNode(currentNode, tagName)) {
65964
- _forceRemove(currentNode);
65965
- return true;
65966
- }
65967
- /* Remove element if anything forbids its presence */
65968
- if (FORBID_TAGS[tagName] || !(EXTRA_ELEMENT_HANDLING.tagCheck instanceof Function && EXTRA_ELEMENT_HANDLING.tagCheck(tagName)) && !ALLOWED_TAGS[tagName]) {
65969
- const removed = _sanitizeDisallowedNode(currentNode, tagName, root);
65970
- /* A false return means the node is a custom element kept via
65971
- CUSTOM_ELEMENT_HANDLING - the only keep path through
65972
- _sanitizeDisallowedNode. Run afterSanitizeElements on it so the
65973
- element-hook lifecycle matches normal allowlisted elements: a
65974
- security policy applied in this hook (e.g. stripping an attribute
65975
- from every surviving element) must not silently skip kept custom
65976
- elements (GHSA-c2j3-45gr-mqc4). This mirrors the normal-element
65977
- tail below - the hook runs, then the walker's subsequent
65978
- _sanitizeAttributes pass sanitizes the element's attributes. The
65979
- deliberately skipped namespace and fallback-tag removal checks stay
65980
- skipped; they are removal decisions, not the hook contract. */
65981
- if (removed === false) {
65982
- _executeHooks(hooks.afterSanitizeElements, currentNode, null);
65983
- }
65984
- return removed;
65985
- }
65986
- /* Check whether element has a valid namespace.
65987
- Realm-safe check (GHSA-hpcv-96wg-7vj8): use the cached Node.prototype
65988
- nodeType getter rather than `instanceof Element`, which is realm-
65989
- bound and short-circuits to false for any node minted in a different
65990
- realm — letting a foreign-realm element with a forbidden namespace
65991
- slip past the namespace check entirely. */
65992
- const nt = _readNodeType(currentNode);
65993
- if (nt === NODE_TYPE.element && !_checkValidNamespace(currentNode)) {
65994
- _forceRemove(currentNode);
65995
- return true;
65996
- }
65997
- /* Make sure that older browsers don't get fallback-tag mXSS */
65998
- if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(FALLBACK_TAG_CLOSE, currentNode.innerHTML)) {
65999
- _forceRemove(currentNode);
66000
- return true;
66001
- }
66002
- /* Sanitize element content to be template-safe */
66003
- if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) {
66004
- /* Get the element's text content */
66005
- const content = _stripTemplateExpressions(currentNode.textContent);
66006
- if (currentNode.textContent !== content) {
66007
- arrayPush(DOMPurify.removed, {
66008
- element: currentNode.cloneNode()
66009
- });
66010
- currentNode.textContent = content;
66011
- }
66012
- }
66013
- /* Execute a hook if present */
66014
- _executeHooks(hooks.afterSanitizeElements, currentNode, null);
66015
- return false;
66016
- };
66017
- /**
66018
- * _isValidAttribute
66019
- *
66020
- * @param lcTag Lowercase tag name of containing element.
66021
- * @param lcName Lowercase attribute name.
66022
- * @param value Attribute value.
66023
- * @return Returns true if `value` is valid, otherwise false.
66024
- */
66025
- // eslint-disable-next-line complexity
66026
- const _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {
66027
- /* FORBID_ATTR must always win, even if ADD_ATTR predicate would allow it */
66028
- if (FORBID_ATTR[lcName]) {
66029
- return false;
66030
- }
66031
- /* Reject declarative-partial-updates patch-linkage attributes
66032
- (https://github.com/WICG/declarative-partial-updates).
66033
- Empirical note (Chrome 150, verified — see
66034
- test/declarative-patch-probe-v3.html): expansion is NOT applied after
66035
- sanitization. For the string path it fires during sanitize()'s own
66036
- parse, so the walk sees and sanitizes the fully materialized expanded
66037
- tree — teleports into MathML/SVG integration points included; a
66038
- weaponized `<template for>`->`<img onerror>` comes back with the handler
66039
- stripped. For the IN_PLACE path it fires on connection, before the walk.
66040
- Either way DOMPurify is NOT blind to the patch.
66041
- This removal is therefore defense-in-depth rather than the sole barrier:
66042
- it prevents live linkage from surviving into the OUTPUT and re-expanding
66043
- in the caller's context, and keeps behaviour deterministic if a future
66044
- engine defers expansion. `for` is legitimate only on <label>/<output>;
66045
- anywhere else (notably <template for>) it links the element to a patch
66046
- target and teleports or removes an arbitrary DOM range by id/marker name.
66047
- `patchsrc` fetches remote markup and is treated as a script-loading
66048
- mechanism (CSP). Gated on SAFE_FOR_XML so the removal groups with the
66049
- other structural-threat checks and stays overridable, consistent with
66050
- the rest of the codebase. PI range markers are already removed by
66051
- _isUnsafeNode. */
66052
- if (_isPatchLinkageAttribute(lcName, lcTag)) {
66053
- return false;
66054
- }
66055
- /* Make sure attribute cannot clobber */
66056
- if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {
66057
- return false;
66058
- }
66059
- const nameIsPermitted = ALLOWED_ATTR[lcName] || EXTRA_ELEMENT_HANDLING.attributeCheck instanceof Function && EXTRA_ELEMENT_HANDLING.attributeCheck(lcName, lcTag);
66060
- /* Allow valid data-* attributes: At least one character after "-"
66061
- (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
66062
- XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)
66063
- We don't need to check the value; it's always URI safe. */
66064
- if (ALLOW_DATA_ATTR && regExpTest(DATA_ATTR$1, lcName)) {
66065
- return true;
66066
- }
66067
- /* Allow valid aria-* attributes, the value is always URI safe */
66068
- if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR$1, lcName)) {
66069
- return true;
66070
- }
66071
- /* A name outside the allowlist is acceptable on custom-element terms
66072
- only. The value checks below are intentionally skipped in that case:
66073
- if the user supplied a tagNameCheck we also allow derived custom
66074
- elements using the same test, and attributes passing the configured
66075
- attributeNameCheck are allowed as custom elements define these at
66076
- their own discretion. */
66077
- if (!nameIsPermitted) {
66078
- return (
66079
- // Condition a) covers a basically valid custom element tag name whose
66080
- // tag passes the configured tagNameCheck and whose attribute name
66081
- // passes the configured attributeNameCheck ...
66082
- _isBasicCustomElement(lcTag) && _matchesNameCheck(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) && _matchesNameCheck(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName, lcTag) ||
66083
- // Condition b) covers an `is` attribute whose value passes the
66084
- // configured tagNameCheck while customized built-in elements are
66085
- // allowed.
66086
- lcName === 'is' && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && _matchesNameCheck(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value)
66087
- );
66088
- }
66089
- /* Check value is safe. First, is attr inert? If so, is safe */
66090
- if (URI_SAFE_ATTRIBUTES[lcName]) {
66091
- return true;
66092
- }
66093
- /* Check no script, data or unknown possibly unsafe URI
66094
- unless we know URI values are safe for that attribute */
66095
- if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE$1, ''))) {
66096
- return true;
66097
- }
66098
- /* Keep image data URIs alive if src/xlink:href is allowed */
66099
- /* Further prevent gadget XSS for dynamically built script tags */
66100
- if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]) {
66101
- return true;
66102
- }
66103
- /* Allow unknown protocols: This provides support for links that
66104
- are handled by protocol handlers which may be unknown ahead of
66105
- time, e.g. fb:, spotify: */
66106
- if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA$1, stringReplace(value, ATTR_WHITESPACE$1, ''))) {
66107
- return true;
66108
- }
66109
- /* Only an empty (binary) value remains safe at this point;
66110
- anything else is presumed unsafe, do not add it back */
66111
- return !value;
66112
- };
66113
- /* Names the HTML spec reserves from valid-custom-element-name; these must
66114
- * never be treated as basic custom elements even when a permissive
66115
- * CUSTOM_ELEMENT_HANDLING.tagNameCheck is configured. */
66116
- 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']);
66117
- /**
66118
- * _isBasicCustomElement
66119
- * checks if at least one dash is included in tagName, and it's not the first char
66120
- * for more sophisticated checking see https://github.com/sindresorhus/validate-element-name
66121
- *
66122
- * @param tagName name of the tag of the node to sanitize
66123
- * @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false.
66124
- */
66125
- const _isBasicCustomElement = function _isBasicCustomElement(tagName) {
66126
- return !RESERVED_CUSTOM_ELEMENT_NAMES[stringToLowerCase(tagName)] && regExpTest(CUSTOM_ELEMENT$1, tagName);
66127
- };
66128
- /**
66129
- * Wrap an attribute value in the matching Trusted Types object when
66130
- * the active policy requires it. Namespaced attributes pass through
66131
- * unchanged (no TT support yet, see
66132
- * https://bugs.chromium.org/p/chromium/issues/detail?id=1305293).
66133
- *
66134
- * @param lcTag lowercase tag name of the containing element
66135
- * @param lcName lowercase attribute name
66136
- * @param namespaceURI the attribute's namespace, if any
66137
- * @param value the attribute value to wrap
66138
- * @return the value, wrapped when Trusted Types demand it
66139
- */
66140
- const _applyTrustedTypesToAttribute = function _applyTrustedTypesToAttribute(lcTag, lcName, namespaceURI, value) {
66141
- if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function' && !namespaceURI) {
66142
- switch (trustedTypes.getAttributeType(lcTag, lcName)) {
66143
- case 'TrustedHTML':
66144
- {
66145
- return _createTrustedHTML(value);
66146
- }
66147
- case 'TrustedScriptURL':
66148
- {
66149
- return _createTrustedScriptURL(value);
66150
- }
66151
- }
66152
- }
66153
- return value;
66154
- };
66155
- /**
66156
- * Write a modified attribute value back onto the element. On
66157
- * success, re-probe for clobbering introduced by the new value and
66158
- * remove the element when found; otherwise, when this writeback is the
66159
- * recreate half of the SANITIZE_NAMED_PROPS remove-and-recreate, pop the
66160
- * removal entry that path recorded so it does not show as removed. On
66161
- * failure, remove the attribute instead.
66162
- *
66163
- * Returns true only on a clean write (the value was set and the new value
66164
- * introduced no clobbering). The caller uses that, together with its own
66165
- * knowledge of whether this attribute pushed a DOMPurify.removed record, to
66166
- * decide whether to pop that record. The pop must happen ONLY for the
66167
- * named-prop remove-and-recreate; popping on any other value change (trim,
66168
- * template scrubbing, Trusted Types) would consume an unrelated _forceRemove
66169
- * subtree-cleanup record and let that detached subtree keep a live event
66170
- * handler through the IN_PLACE neutralization pass (SO-001).
66171
- *
66172
- * @param currentNode the element carrying the attribute
66173
- * @param name the attribute name as present on the element
66174
- * @param namespaceURI the attribute's namespace, if any
66175
- * @param value the new attribute value
66176
- * @return true if the value was written without introducing clobbering
66177
- */
66178
- const _setAttributeValue = function _setAttributeValue(currentNode, name, namespaceURI, value) {
66179
- try {
66180
- if (namespaceURI) {
66181
- currentNode.setAttributeNS(namespaceURI, name, value);
66182
- } else {
66183
- /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
66184
- currentNode.setAttribute(name, value);
66185
- }
66186
- if (_isClobbered(currentNode)) {
66187
- _forceRemove(currentNode);
66188
- return false;
66189
- }
66190
- return true;
66191
- } catch (_) {
66192
- _removeAttribute(name, currentNode);
66193
- return false;
66194
- }
66195
- };
66196
- /**
66197
- * _sanitizeAttributes
66198
- *
66199
- * @protect attributes
66200
- * @protect nodeName
66201
- * @protect removeAttribute
66202
- * @protect setAttribute
66203
- *
66204
- * @param currentNode to sanitize
66205
- */
66206
- // eslint-disable-next-line complexity
66207
- const _sanitizeAttributes = function _sanitizeAttributes(currentNode) {
66208
- /* Execute a hook if present */
66209
- _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null);
66210
- const attributes = currentNode.attributes;
66211
- /* Check if we have attributes; if not we might have a text node */
66212
- if (!attributes || _isClobbered(currentNode)) {
66213
- return;
66214
- }
66215
- /* Same lazy-install guard as uponSanitizeElement (see there): fork the
66216
- attribute allowlist off its shared binding before a hook can see it. */
66217
- ALLOWED_ATTR = _forkSharedAllowlist(hooks.uponSanitizeAttribute, ALLOWED_ATTR, DEFAULT_ALLOWED_ATTR, SET_CONFIG_ALLOWED_ATTR);
66218
- const hookEvent = {
66219
- attrName: '',
66220
- attrValue: '',
66221
- keepAttr: true,
66222
- allowedAttributes: ALLOWED_ATTR,
66223
- forceKeepAttr: undefined
66224
- };
66225
- let l = attributes.length;
66226
- const lcTag = transformCaseFunc(currentNode.nodeName);
66227
- /* Go backwards over all attributes; safely remove bad ones */
66228
- while (l--) {
66229
- const attr = attributes[l];
66230
- const name = attr.name,
66231
- namespaceURI = attr.namespaceURI,
66232
- attrValue = attr.value;
66233
- const lcName = transformCaseFunc(name);
66234
- const initValue = attrValue;
66235
- let value = name === 'value' ? initValue : stringTrim(initValue);
66236
- /* Tracks whether this specific attribute pushed a DOMPurify.removed
66237
- record that a later _setAttributeValue() writeback is expected to pop
66238
- back off (the SANITIZE_NAMED_PROPS remove-and-recreate below is the
66239
- only path that does). A value that merely changed via trim, template
66240
- scrubbing, or Trusted Types pushes no such record, so its writeback
66241
- must NOT pop — otherwise it consumes an unrelated _forceRemove subtree
66242
- record and that detached subtree escapes the IN_PLACE handler-
66243
- neutralization pass (SO-001). */
66244
- let recreatedNamedProp = false;
66245
- /* Execute a hook if present */
66246
- hookEvent.attrName = lcName;
66247
- hookEvent.attrValue = value;
66248
- hookEvent.keepAttr = true;
66249
- hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set
66250
- _executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent);
66251
- value = hookEvent.attrValue;
66252
- /* Full DOM Clobbering protection via namespace isolation,
66253
- * Prefix id and name attributes with `user-content-`
66254
- */
66255
- if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name') && stringIndexOf(value, SANITIZE_NAMED_PROPS_PREFIX) !== 0) {
66256
- // Remove the attribute with this value
66257
- _removeAttribute(name, currentNode, attr);
66258
- // Prefix the value and later re-create the attribute with the sanitized value
66259
- value = SANITIZE_NAMED_PROPS_PREFIX + value;
66260
- // This attribute owns the record just pushed; its recreate writeback
66261
- // is the one allowed to pop it back off.
66262
- recreatedNamedProp = true;
66263
- }
66264
- // Else: already prefixed, leave the attribute alone — the prefix is
66265
- // itself the clobbering protection, and re-applying it is incorrect.
66266
- /* Work around a security issue with comments inside attributes */
66267
- if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i, value)) {
66268
- _removeAttribute(name, currentNode, attr);
66269
- continue;
66270
- }
66271
- /* Make sure we cannot easily use animated hrefs, even if animations are allowed */
66272
- if (lcName === 'attributename' && stringMatch(value, 'href')) {
66273
- _removeAttribute(name, currentNode, attr);
66274
- continue;
66275
- }
66276
- /* Did the hooks force-keep the attribute? */
66277
- if (hookEvent.forceKeepAttr) {
66278
- continue;
66279
- }
66280
- /* Did the hooks approve of the attribute? */
66281
- if (!hookEvent.keepAttr) {
66282
- _removeAttribute(name, currentNode, attr);
66283
- continue;
66284
- }
66285
- /* Work around a security issue in jQuery 3.0 */
66286
- if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(SELF_CLOSING_TAG, value)) {
66287
- _removeAttribute(name, currentNode, attr);
66288
- continue;
66289
- }
66290
- /* Sanitize attribute content to be template-safe */
66291
- if (SAFE_FOR_TEMPLATES) {
66292
- value = _stripTemplateExpressions(value);
66293
- }
66294
- /* Is `value` valid for this attribute? */
66295
- if (!_isValidAttribute(lcTag, lcName, value)) {
66296
- _removeAttribute(name, currentNode, attr);
66297
- continue;
66298
- }
66299
- /* Handle attributes that require Trusted Types */
66300
- value = _applyTrustedTypesToAttribute(lcTag, lcName, namespaceURI, value);
66301
- /* Handle invalid data-* attribute set by try-catching it */
66302
- if (value !== initValue) {
66303
- const cleanWrite = _setAttributeValue(currentNode, name, namespaceURI, value);
66304
- /* Only the named-prop remove-and-recreate owns a DOMPurify.removed
66305
- record to pop; a plain trim/template/Trusted-Types writeback owns
66306
- none, so popping here would drop an unrelated subtree's cleanup
66307
- record (SO-001). */
66308
- if (cleanWrite && recreatedNamedProp) {
66309
- arrayPop(DOMPurify.removed);
66310
- }
66311
- }
66312
- }
66313
- /* Execute a hook if present */
66314
- _executeHooks(hooks.afterSanitizeAttributes, currentNode, null);
66315
- };
66316
- /**
66317
- * _sanitizeShadowDOM
66318
- *
66319
- * @param fragment to iterate over recursively
66320
- */
66321
- const _sanitizeShadowDOM2 = function _sanitizeShadowDOM(fragment) {
66322
- let shadowNode = null;
66323
- const shadowIterator = _createNodeIterator(fragment);
66324
- /* Execute a hook if present */
66325
- _executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null);
66326
- while (shadowNode = shadowIterator.nextNode()) {
66327
- /* Execute a hook if present */
66328
- _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null);
66329
- /* Sanitize tags and elements */
66330
- _sanitizeElements(shadowNode, fragment);
66331
- /* Check attributes next */
66332
- _sanitizeAttributes(shadowNode);
66333
- /* Deep shadow DOM detected.
66334
- Realm-safe check (GHSA-hpcv-96wg-7vj8): use nodeType against the
66335
- DOCUMENT_FRAGMENT_NODE constant rather than instanceof, so we
66336
- recurse into <template>.content from foreign realms too. */
66337
- if (_isDocumentFragment(shadowNode.content)) {
66338
- _sanitizeShadowDOM2(shadowNode.content);
66339
- }
66340
- /* An element iterated here may itself host an attached
66341
- shadow root. The default NodeIterator does not enter shadow
66342
- trees, so a shadow root nested inside template.content was
66343
- previously reached by no walk at all (the pre-pass at
66344
- _sanitizeAttachedShadowRoots descends via childNodes, which
66345
- doesn't enter template.content; the template-content recursion
66346
- above iterates the content but never inspected shadowRoot).
66347
- Walk it explicitly. The nodeType guard avoids reading
66348
- shadowRoot off text / comment / CDATA / PI nodes that the
66349
- iterator also surfaces. */
66350
- if (_readNodeType(shadowNode) === NODE_TYPE.element) {
66351
- const innerSr = getShadowRoot(shadowNode);
66352
- if (_isDocumentFragment(innerSr)) {
66353
- _sanitizeAttachedShadowRoots(innerSr);
66354
- _sanitizeShadowDOM2(innerSr);
66355
- }
66356
- }
66357
- }
66358
- /* Execute a hook if present */
66359
- _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null);
66360
- };
66361
- /**
66362
- * _sanitizeAttachedShadowRoots
66363
- *
66364
- * Walks `root` and feeds every attached shadow root we encounter into
66365
- * the existing _sanitizeShadowDOM pipeline. The default node iterator
66366
- * does not descend into shadow trees, so nodes inside an attached
66367
- * shadow root would otherwise be skipped entirely.
66368
- *
66369
- * Two real input paths put attached shadow roots in front of us:
66370
- * 1. IN_PLACE on a DOM node that already has shadow roots attached.
66371
- * 2. DOM-node input where importNode(dirty, true) deep-clones the
66372
- * shadow root because it was created with `clonable: true`.
66373
- *
66374
- * This pass runs once, up front, so the main iteration loop (and the
66375
- * existing _sanitizeShadowDOM template-content recursion) stay
66376
- * untouched — string-input paths are not affected.
66377
- *
66378
- * @param root the subtree root to walk for attached shadow roots
66379
- */
66380
- const _sanitizeAttachedShadowRoots = function _sanitizeAttachedShadowRoots(root) {
66381
- /* Iterative (explicit stack) rather than per-child recursion. DOM APIs
66382
- impose no depth cap, so an attacker-shaped tree (JSON/CRDT/editor data
66383
- built straight into the DOM — the IN_PLACE surface) deeper than the JS
66384
- call-stack budget would otherwise overflow native recursion here and
66385
- throw at the IN_PLACE entry pre-pass, before a single node is
66386
- sanitized, leaving the caller's live tree untouched (fail-open). See
66387
- campaign-3 F4. A heap stack keeps depth off the call stack.
66388
- Each work item is either a node to descend into, or a deferred
66389
- `_sanitizeShadowDOM` for an already-walked shadow root. The deferred
66390
- form preserves the original post-order discipline: a shadow root's
66391
- nested shadow roots are discovered before the outer shadow is
66392
- sanitized (which may remove hosts). Pushes are in reverse of the
66393
- desired processing order (LIFO): template content, then children, then
66394
- the shadow-sanitize, then the shadow walk — so the order matches the
66395
- previous recursion exactly. */
66396
- const stack = [{
66397
- node: root,
66398
- shadow: null
66399
- }];
66400
- while (stack.length > 0) {
66401
- const item = stack.pop();
66402
- /* Deferred shadow-DOM sanitisation: runs after its subtree was walked. */
66403
- if (item.shadow) {
66404
- _sanitizeShadowDOM2(item.shadow);
66405
- continue;
66406
- }
66407
- const node = item.node;
66408
- const nodeType = _readNodeType(node);
66409
- const isElement = nodeType === NODE_TYPE.element;
66410
- /* (pushed last → processed first) Children, snapshotted in reverse so
66411
- the first child is processed first. Snapshotting matters because a
66412
- hook may detach siblings mid-walk. */
66413
- const childNodes = getChildNodes(node);
66414
- if (childNodes) {
66415
- for (let i = childNodes.length - 1; i >= 0; --i) {
66416
- stack.push({
66417
- node: childNodes[i],
66418
- shadow: null
66419
- });
66420
- }
66421
- }
66422
- /* (pushed before children → processed after them, matching the old
66423
- "template content last" order) When the node is a <template>,
66424
- descend into its content. */
66425
- if (isElement) {
66426
- const rootName = getNodeName ? getNodeName(node) : null;
66427
- if (typeof rootName === 'string' && transformCaseFunc(rootName) === 'template') {
66428
- const content = node.content;
66429
- if (_isDocumentFragment(content)) {
66430
- stack.push({
66431
- node: content,
66432
- shadow: null
66433
- });
66434
- }
66435
- }
66436
- }
66437
- /* Shadow root (processed first): walk its subtree, then sanitise it.
66438
- Realm-safe check (GHSA-hpcv-96wg-7vj8): nodeType-based detection
66439
- rather than `instanceof DocumentFragment`, which is realm-bound and
66440
- silently skipped foreign-realm shadow roots (e.g.
66441
- iframe.contentDocument attachShadow). */
66442
- if (isElement) {
66443
- const sr = getShadowRoot(node);
66444
- if (_isDocumentFragment(sr)) {
66445
- /* Push the deferred sanitise first so it pops after the shadow
66446
- walk we push next, i.e. nested shadow roots are discovered
66447
- before this one is sanitised. */
66448
- stack.push({
66449
- node: null,
66450
- shadow: sr
66451
- }, {
66452
- node: sr,
66453
- shadow: null
66454
- });
66455
- }
66456
- }
66457
- }
66458
- };
66459
- // eslint-disable-next-line complexity
66460
- DOMPurify.sanitize = function (dirty) {
66461
- let cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
66462
- let body = null;
66463
- let importedNode = null;
66464
- let currentNode = null;
66465
- let returnNode = null;
66466
- /* Make sure we have a string to sanitize.
66467
- DO NOT return early, as this will return the wrong type if
66468
- the user has requested a DOM object rather than a string */
66469
- IS_EMPTY_INPUT = !dirty;
66470
- if (IS_EMPTY_INPUT) {
66471
- dirty = '<!-->';
66472
- }
66473
- /* Stringify, in case dirty is an object */
66474
- if (typeof dirty !== 'string' && !_isNode(dirty)) {
66475
- dirty = stringifyValue(dirty);
66476
- if (typeof dirty !== 'string') {
66477
- throw typeErrorCreate('dirty is not a string, aborting');
66478
- }
66479
- }
66480
- /* Return dirty HTML if DOMPurify cannot run */
66481
- if (!DOMPurify.isSupported) {
66482
- return dirty;
66483
- }
66484
- /* Assign config vars */
66485
- if (SET_CONFIG) {
66486
- /* Persistent setConfig() path: _parseConfig is skipped, so the sets are
66487
- * not re-derived per call. Restore them from the pristine bindings
66488
- * captured at setConfig() time so a previous call's hook clone (mutated
66489
- * below) does not carry over. */
66490
- ALLOWED_TAGS = SET_CONFIG_ALLOWED_TAGS;
66491
- ALLOWED_ATTR = SET_CONFIG_ALLOWED_ATTR;
66492
- } else {
66493
- _parseConfig(cfg);
66494
- }
66495
- /* Clone the hook-mutable allowlists before the walk whenever an
66496
- * uponSanitize* hook is registered. The hook event exposes ALLOWED_TAGS
66497
- * and ALLOWED_ATTR by reference (as allowedTags / allowedAttributes), so
66498
- * a hook that widens them would otherwise mutate the shared set
66499
- * permanently: across later calls and across every element. Cloning per
66500
- * walk keeps documented in-call widening working while scoping it to the
66501
- * call. A single guard for both config paths - the per-call path rebinds
66502
- * the sets in _parseConfig each call, the persistent path restores them
66503
- * from the captured bindings just above - so the two cannot diverge. */
66504
- if (hooks.uponSanitizeElement.length > 0 || hooks.uponSanitizeAttribute.length > 0) {
66505
- ALLOWED_TAGS = clone(ALLOWED_TAGS);
66506
- }
66507
- if (hooks.uponSanitizeAttribute.length > 0) {
66508
- ALLOWED_ATTR = clone(ALLOWED_ATTR);
66509
- }
66510
- /* Clean up removed elements */
66511
- DOMPurify.removed = [];
66512
- /* Resolve IN_PLACE for this call without mutating persistent config.
66513
- Writing the IN_PLACE closure variable here leaks under setConfig(),
66514
- where _parseConfig is skipped on later calls: a single string call would
66515
- disable in-place mode for every subsequent node call, returning a
66516
- sanitized copy while leaving the caller's node — which in-place callers
66517
- keep using and whose return value they ignore — unsanitized. REPORT-2. */
66518
- const inPlace = IN_PLACE && typeof dirty !== 'string' && _isNode(dirty);
66519
- if (inPlace) {
66520
- /* Declarative-partial-updates / streaming pre-pass: sever every patch
66521
- linkage across the live tree BEFORE the walk, so no patch can fire
66522
- mid-walk and inject into an already-processed region. Runs first, so
66523
- it also covers the forbidden/clobbered roots that throw below. */
66524
- _neutralizePatchLinkage(dirty);
66525
- /* Do some early pre-sanitization to avoid unsafe root nodes.
66526
- Read nodeName through the cached prototype getter — a clobbering
66527
- child named "nodeName" on the form root would otherwise shadow
66528
- the property and let this check skip the root-allowlist
66529
- validation entirely. */
66530
- const nn = _readNodeName(dirty);
66531
- if (typeof nn === 'string') {
66532
- const tagName = transformCaseFunc(nn);
66533
- if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
66534
- /* Fail closed on a live root: neutralize handlers/children before
66535
- throwing, exactly as the mid-walk abort path does. */
66536
- _neutralizeRoot(dirty);
66537
- throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');
66538
- }
66539
- }
66540
- /* Pre-flight the root through _isClobbered. The iterator-driven
66541
- removal path can not detach a parent-less root: _forceRemove
66542
- falls through to Element.prototype.remove(), which per spec
66543
- is a no-op on a node with no parent. A clobbered root would
66544
- then survive the main loop with its attributes uninspected,
66545
- because _sanitizeAttributes early-returns on _isClobbered. The
66546
- result would be an attacker-controlled form, complete with any
66547
- event-handler attributes the caller passed in, handed back to
66548
- the application unsanitized. Refuse to sanitize such a root
66549
- the same way we refuse a forbidden tag. GHSA-r47g-fvhr-h676. */
66550
- if (_isClobbered(dirty)) {
66551
- /* Fail closed on a live clobbered root before throwing.
66552
- _neutralizeRoot's reads are clobber-safe (cached getters); the
66553
- form's non-clobbered descendants, e.g. an armed <img>, are scrubbed. */
66554
- _neutralizeRoot(dirty);
66555
- throw typeErrorCreate('root node is clobbered and cannot be sanitized in-place');
66556
- }
66557
- /* Sanitize attached shadow roots before the main iterator runs.
66558
- The iterator does not descend into shadow trees. Same fail-closed
66559
- barrier as the main walk (campaign-3 F2): a custom-element reaction
66560
- inside a shadow root could abort this pre-pass before the walk runs,
66561
- which would otherwise leave the entire live tree unsanitized. */
66562
- try {
66563
- _sanitizeAttachedShadowRoots(dirty);
66564
- } catch (error) {
66565
- _neutralizeRoot(dirty);
66566
- throw error;
66567
- }
66568
- } else if (_isNode(dirty)) {
66569
- /* If dirty is a DOM element, append to an empty document to avoid
66570
- elements being stripped by the parser */
66571
- body = _initDocument('<!---->');
66572
- importedNode = body.ownerDocument.importNode(dirty, true);
66573
- if (importedNode.nodeType === NODE_TYPE.element && importedNode.nodeName === 'BODY') {
66574
- /* Node is already a body, use as is */
66575
- body = importedNode;
66576
- } else if (importedNode.nodeName === 'HTML') {
66577
- body = importedNode;
66578
- } else {
66579
- // eslint-disable-next-line unicorn/prefer-dom-node-append
66580
- body.appendChild(importedNode);
66581
- }
66582
- /* Clonable shadow roots are deep-cloned by importNode(); sanitize
66583
- them before the main iterator runs, since the iterator does not
66584
- descend into shadow trees. The walk routes every read through a
66585
- cached prototype getter so clobbering descendants on a form root
66586
- cannot hide a shadow host from this pass.
66587
- Traverse from `body`, not `importedNode`: when importedNode is a
66588
- DocumentFragment, the appendChild() above moves its children into
66589
- `body` and leaves the fragment empty, so walking importedNode would
66590
- scan nothing and miss every attached shadow host now under `body`
66591
- (SO-003). In the BODY/HTML branches `body === importedNode`, so this
66592
- is equivalent there; in the element branch `body` contains the
66593
- appended element and its descendants. `body` covers all three. */
66594
- _sanitizeAttachedShadowRoots(body);
66595
- } else {
66596
- /* Exit directly if we have nothing to do */
66597
- if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT &&
66598
- // eslint-disable-next-line unicorn/prefer-includes
66599
- dirty.indexOf('<') === -1) {
66600
- return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? _createTrustedHTML(dirty) : dirty;
66601
- }
66602
- /* Initialize the document to work on */
66603
- body = _initDocument(dirty);
66604
- /* Check we have a DOM node from the data */
66605
- if (!body) {
66606
- return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';
66607
- }
66608
- }
66609
- /* Remove first element node (ours) if FORCE_BODY is set */
66610
- if (body && FORCE_BODY) {
66611
- _forceRemove(body.firstChild);
66612
- }
66613
- /* Get node iterator */
66614
- const walkRoot = inPlace ? dirty : body;
66615
- /* Now start iterating over the created document.
66616
- The walk runs inside an exception barrier (campaign-3 F2): a re-entrant
66617
- engine/custom-element mutation can detach a node mid-walk so
66618
- `_forceRemove`'s parentless guard throws, aborting the loop. Without the
66619
- barrier the caller's in-place tree would be left half-sanitized with the
66620
- unvisited tail still armed. _createNodeIterator itself is inside the
66621
- barrier too: constructing the iterator dereferences the root's document,
66622
- and any failure there (e.g. an exotic/clobbered root) must still fail
66623
- closed rather than skip the neutralize. On any throw we fail closed -
66624
- strip the in-place root bare - then rethrow so the existing throw
66625
- contract is preserved. (String/DOM-copy paths never return the partial
66626
- body, so the propagating throw is already fail-closed there.) */
66627
- try {
66628
- const nodeIterator = _createNodeIterator(walkRoot);
66629
- while (currentNode = nodeIterator.nextNode()) {
66630
- /* Sanitize tags and elements */
66631
- _sanitizeElements(currentNode, walkRoot);
66632
- /* Check attributes next */
66633
- _sanitizeAttributes(currentNode);
66634
- /* Shadow DOM detected, sanitize it.
66635
- Realm-safe check (GHSA-hpcv-96wg-7vj8): nodeType-based detection
66636
- instead of instanceof, so foreign-realm <template>.content is
66637
- walked correctly. */
66638
- if (_isDocumentFragment(currentNode.content)) {
66639
- _sanitizeShadowDOM2(currentNode.content);
66640
- }
66641
- }
66642
- } catch (error) {
66643
- if (inPlace) {
66644
- _neutralizeRoot(dirty);
66645
- /* Nodes _forceRemove'd earlier in the aborted walk are already
66646
- detached from the root, so _neutralizeRoot's subtree pass does not
66647
- reach them. Defuse them too, mirroring the success-path loop below. */
66648
- arrayForEach(DOMPurify.removed, entry => {
66649
- if (entry.element) {
66650
- _neutralizeSubtree(entry.element);
66651
- }
66652
- });
66653
- }
66654
- throw error;
66655
- }
66656
- /* If we sanitized `dirty` in-place, return it. */
66657
- if (inPlace) {
66658
- /* Fail-closed completion of the audit-5 F1 fix: every node removed from
66659
- the caller's live tree is detached but may still hold a queued
66660
- resource-event handler that fires in page scope after we return. The
66661
- move-hoist covers only disallowed-tag KEEP_CONTENT removals; strip the
66662
- non-allow-listed attributes off every other removed subtree (clobber,
66663
- mXSS, namespace, comments, KEEP_CONTENT:false, …) so those handlers are
66664
- cancelled before any event can fire. Runs synchronously, pre-return. */
66665
- arrayForEach(DOMPurify.removed, entry => {
66666
- if (entry.element) {
66667
- _neutralizeSubtree(entry.element);
66668
- }
66669
- });
66670
- if (SAFE_FOR_TEMPLATES) {
66671
- _scrubTemplateExpressions2(dirty);
66672
- }
66673
- return dirty;
66674
- }
66675
- /* Return sanitized string or DOM */
66676
- if (RETURN_DOM) {
66677
- if (SAFE_FOR_TEMPLATES) {
66678
- _scrubTemplateExpressions2(body);
66679
- }
66680
- if (RETURN_DOM_FRAGMENT) {
66681
- returnNode = createDocumentFragment.call(body.ownerDocument);
66682
- while (body.firstChild) {
66683
- // eslint-disable-next-line unicorn/prefer-dom-node-append
66684
- returnNode.appendChild(body.firstChild);
66685
- }
66686
- } else {
66687
- returnNode = body;
66688
- }
66689
- if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) {
66690
- /*
66691
- AdoptNode() is not used because internal state is not reset
66692
- (e.g. the past names map of a HTMLFormElement), this is safe
66693
- in theory but we would rather not risk another attack vector.
66694
- The state that is cloned by importNode() is explicitly defined
66695
- by the specs.
66696
- */
66697
- returnNode = importNode.call(originalDocument, returnNode, true);
66698
- }
66699
- return returnNode;
66700
- }
66701
- let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;
66702
- /* Serialize doctype if allowed */
66703
- if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) {
66704
- serializedHTML = '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\n' + serializedHTML;
66705
- }
66706
- /* Sanitize final string template-safe */
66707
- if (SAFE_FOR_TEMPLATES) {
66708
- serializedHTML = _stripTemplateExpressions(serializedHTML);
66709
- }
66710
- return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? _createTrustedHTML(serializedHTML) : serializedHTML;
66711
- };
66712
- DOMPurify.setConfig = function () {
66713
- let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
66714
- _parseConfig(cfg);
66715
- SET_CONFIG = true;
66716
- SET_CONFIG_ALLOWED_TAGS = ALLOWED_TAGS;
66717
- SET_CONFIG_ALLOWED_ATTR = ALLOWED_ATTR;
66718
- };
66719
- DOMPurify.clearConfig = function () {
66720
- CONFIG = null;
66721
- SET_CONFIG = false;
66722
- SET_CONFIG_ALLOWED_TAGS = null;
66723
- SET_CONFIG_ALLOWED_ATTR = null;
66724
- // Drop any caller-supplied Trusted Types policy so it cannot poison later
66725
- // `RETURN_TRUSTED_TYPE` output. The internal default policy (cached, and
66726
- // never recreated — Trusted Types throws on duplicate names) is restored by
66727
- // the next `_parseConfig`. See GHSA-vxr8-fq34-vvx9.
66728
- trustedTypesPolicy = defaultTrustedTypesPolicy;
66729
- emptyHTML = '';
66730
- };
66731
- DOMPurify.isValidAttribute = function (tag, attr, value) {
66732
- /* Initialize shared config vars if necessary. */
66733
- if (!CONFIG) {
66734
- _parseConfig({});
66735
- }
66736
- const lcTag = transformCaseFunc(tag);
66737
- const lcName = transformCaseFunc(attr);
66738
- return _isValidAttribute(lcTag, lcName, value);
66739
- };
66740
- DOMPurify.addHook = function (entryPoint, hookFunction) {
66741
- if (typeof hookFunction !== 'function') {
66742
- return;
66743
- }
66744
- /* Reject unknown entry points. Without this, a non-hook key (e.g.
66745
- * '__proto__') indexes off the prototype chain rather than a real
66746
- * hook array, and arrayPush then writes to Object.prototype. Guard
66747
- * with an own-property check against the known hook names. */
66748
- if (!objectHasOwnProperty(hooks, entryPoint)) {
66749
- return;
66750
- }
66751
- arrayPush(hooks[entryPoint], hookFunction);
66752
- };
66753
- DOMPurify.removeHook = function (entryPoint, hookFunction) {
66754
- if (!objectHasOwnProperty(hooks, entryPoint)) {
66755
- return undefined;
66756
- }
66757
- if (hookFunction !== undefined) {
66758
- const index = arrayLastIndexOf(hooks[entryPoint], hookFunction);
66759
- return index === -1 ? undefined : arraySplice(hooks[entryPoint], index, 1)[0];
66760
- }
66761
- return arrayPop(hooks[entryPoint]);
66762
- };
66763
- DOMPurify.removeHooks = function (entryPoint) {
66764
- if (!objectHasOwnProperty(hooks, entryPoint)) {
66765
- return;
66766
- }
66767
- hooks[entryPoint] = [];
66768
- };
66769
- DOMPurify.removeAllHooks = function () {
66770
- hooks = _createHooksMap();
66771
- };
66772
- return DOMPurify;
66773
- }
66774
- var purify = createDOMPurify();
66775
-
66776
-
66777
- //# sourceMappingURL=purify.es.mjs.map
66778
-
66779
64243
  ;// ../../../node_modules/@wix/wix-ui-icons-common/dist/esm/core/fetcher.js
66780
-
66781
64244
  const ABORT_SIGNAL_TIMEOUT = 5e3;
66782
- const SVG_NAMESPACE = "http://www.w3.org/2000/svg";
66783
- function sanitizeSvgContent(content) {
66784
- if (typeof content !== "string" || !purify.isSupported) {
66785
- return "";
66786
- }
66787
- return purify.sanitize(content, {
66788
- USE_PROFILES: { svg: true, svgFilters: true },
66789
- NAMESPACE: SVG_NAMESPACE
66790
- });
66791
- }
64245
+ let sanitizer;
64246
+ const loadSanitizer = () => sanitizer ?? (sanitizer = __webpack_require__.e(/*! import() */ 500).then(__webpack_require__.bind(__webpack_require__, /*! ./sanitize.js */ 7500)).catch((error) => {
64247
+ sanitizer = void 0;
64248
+ throw error;
64249
+ }));
64250
+ loadSanitizer().catch(() => {
64251
+ });
66792
64252
  const isTransientError = (error) => error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError");
66793
64253
  function createTimeoutSignal(timeout) {
66794
64254
  if (typeof AbortSignal.timeout === "function") {
@@ -66847,7 +64307,7 @@ class IconContentFetcher {
66847
64307
  throw error;
66848
64308
  }
66849
64309
  };
66850
- const request = fetchContent(2).then((data) => {
64310
+ const request = Promise.all([fetchContent(2), loadSanitizer()]).then(([data, { sanitizeSvgContent }]) => {
66851
64311
  this.cache.set(cacheKey, sanitizeSvgContent(data.content));
66852
64312
  this.pendingRequests.delete(cacheKey);
66853
64313
  }).catch((error) => {
@@ -68907,12 +66367,12 @@ function _objectWithoutProperties(e, t) {
68907
66367
  }
68908
66368
 
68909
66369
  ;// ../../../node_modules/@babel/runtime/helpers/esm/arrayWithHoles.js
68910
- function arrayWithHoles_arrayWithHoles(r) {
66370
+ function _arrayWithHoles(r) {
68911
66371
  if (Array.isArray(r)) return r;
68912
66372
  }
68913
66373
 
68914
66374
  ;// ../../../node_modules/@babel/runtime/helpers/esm/iterableToArrayLimit.js
68915
- function iterableToArrayLimit_iterableToArrayLimit(r, l) {
66375
+ function _iterableToArrayLimit(r, l) {
68916
66376
  var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
68917
66377
  if (null != t) {
68918
66378
  var e,
@@ -68941,7 +66401,7 @@ function iterableToArrayLimit_iterableToArrayLimit(r, l) {
68941
66401
  }
68942
66402
 
68943
66403
  ;// ../../../node_modules/@babel/runtime/helpers/esm/arrayLikeToArray.js
68944
- function arrayLikeToArray_arrayLikeToArray(r, a) {
66404
+ function _arrayLikeToArray(r, a) {
68945
66405
  (null == a || a > r.length) && (a = r.length);
68946
66406
  for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
68947
66407
  return n;
@@ -68949,16 +66409,16 @@ function arrayLikeToArray_arrayLikeToArray(r, a) {
68949
66409
 
68950
66410
  ;// ../../../node_modules/@babel/runtime/helpers/esm/unsupportedIterableToArray.js
68951
66411
 
68952
- function unsupportedIterableToArray_unsupportedIterableToArray(r, a) {
66412
+ function _unsupportedIterableToArray(r, a) {
68953
66413
  if (r) {
68954
- if ("string" == typeof r) return arrayLikeToArray_arrayLikeToArray(r, a);
66414
+ if ("string" == typeof r) return _arrayLikeToArray(r, a);
68955
66415
  var t = {}.toString.call(r).slice(8, -1);
68956
- 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_arrayLikeToArray(r, a) : void 0;
66416
+ 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;
68957
66417
  }
68958
66418
  }
68959
66419
 
68960
66420
  ;// ../../../node_modules/@babel/runtime/helpers/esm/nonIterableRest.js
68961
- function nonIterableRest_nonIterableRest() {
66421
+ function _nonIterableRest() {
68962
66422
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
68963
66423
  }
68964
66424
 
@@ -68967,14 +66427,14 @@ function nonIterableRest_nonIterableRest() {
68967
66427
 
68968
66428
 
68969
66429
 
68970
- function slicedToArray_slicedToArray(r, e) {
68971
- return arrayWithHoles_arrayWithHoles(r) || iterableToArrayLimit_iterableToArrayLimit(r, e) || unsupportedIterableToArray_unsupportedIterableToArray(r, e) || nonIterableRest_nonIterableRest();
66430
+ function _slicedToArray(r, e) {
66431
+ return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
68972
66432
  }
68973
66433
 
68974
66434
  ;// ../../../node_modules/@babel/runtime/helpers/esm/arrayWithoutHoles.js
68975
66435
 
68976
66436
  function _arrayWithoutHoles(r) {
68977
- if (Array.isArray(r)) return arrayLikeToArray_arrayLikeToArray(r);
66437
+ if (Array.isArray(r)) return _arrayLikeToArray(r);
68978
66438
  }
68979
66439
 
68980
66440
  ;// ../../../node_modules/@babel/runtime/helpers/esm/iterableToArray.js
@@ -68993,7 +66453,7 @@ function _nonIterableSpread() {
68993
66453
 
68994
66454
 
68995
66455
  function _toConsumableArray(r) {
68996
- return _arrayWithoutHoles(r) || _iterableToArray(r) || unsupportedIterableToArray_unsupportedIterableToArray(r) || _nonIterableSpread();
66456
+ return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread();
68997
66457
  }
68998
66458
 
68999
66459
  ;// ../../../node_modules/@babel/runtime/helpers/esm/classCallCheck.js
@@ -70928,14 +68388,14 @@ var createFilter = function createFilter(config) {
70928
68388
 
70929
68389
  function Select_e1cf49ae_browser_esm_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
70930
68390
 
70931
- var Select_e1cf49ae_browser_esm_ref = true ? {
68391
+ var _ref = true ? {
70932
68392
  name: "1laao21-a11yText",
70933
68393
  styles: "label:a11yText;z-index:9999;border:0;clip:rect(1px, 1px, 1px, 1px);height:1px;width:1px;position:absolute;overflow:hidden;padding:0;white-space:nowrap;"
70934
68394
  } : 0;
70935
68395
 
70936
68396
  var A11yText = function A11yText(props) {
70937
68397
  return core_browser_esm_jsx("span", _extends({
70938
- css: Select_e1cf49ae_browser_esm_ref
68398
+ css: _ref
70939
68399
  }, props));
70940
68400
  };
70941
68401
 
@@ -72439,12 +69899,12 @@ var Select = /*#__PURE__*/function (_Component) {
72439
69899
 
72440
69900
  _this.buildMenuOptions = memoize_one_esm(_this.buildMenuOptions, function (newArgs, lastArgs) {
72441
69901
  var _ref6 = newArgs,
72442
- _ref7 = slicedToArray_slicedToArray(_ref6, 2),
69902
+ _ref7 = _slicedToArray(_ref6, 2),
72443
69903
  newProps = _ref7[0],
72444
69904
  newSelectValue = _ref7[1];
72445
69905
 
72446
69906
  var _ref8 = lastArgs,
72447
- _ref9 = slicedToArray_slicedToArray(_ref8, 2),
69907
+ _ref9 = _slicedToArray(_ref8, 2),
72448
69908
  lastProps = _ref9[0],
72449
69909
  lastSelectValue = _ref9[1];
72450
69910
 
@@ -80547,9 +78007,8 @@ const formatPx = (maxWidth) => maxWidth === undefined
80547
78007
  : typeof maxWidth === 'string'
80548
78008
  ? maxWidth
80549
78009
  : `${maxWidth}px`;
80550
- const Tag = ({ id, onClick, onRemove, maxWidth, dataHook, size = Tag_constants_SIZE.small, type = TYPE.solid, theme = Tag_constants_SKIN.standard, // TODO: add default value for skin once theme is removed
80551
- removable = true, disabled, thumb, ellipsisProps, className, children, closeButtonRef, ...props }) => {
80552
- const skin = props.skin || theme;
78010
+ const Tag = ({ id, onClick, onRemove, maxWidth, dataHook, size = Tag_constants_SIZE.small, type = TYPE.solid, theme, removable = true, disabled, thumb, ellipsisProps, className, children, closeButtonRef, ...props }) => {
78011
+ const skin = props.skin || theme || Tag_constants_SKIN.standard;
80553
78012
  (0,external_React_.useEffect)(() => {
80554
78013
  if (theme) {
80555
78014
  deprecationLog_deprecationLog('<Tag/> - theme prop is deprecated and will be removed in next major version, please use skin instead');