Team Ai
Datasetpublic

Brunobkr/llama.cpp_AlgMor24_github

ΩFFFΣLLIa • llama.cpp • AlgMor24 ██████╗ ███████╗███████╗███████╗██╗ ██╗ ██╗ █████╗ ██╔═══██╗██╔════╝██╔════╝██╔════╝██║ ██║ ██║██╔══██╗ ██║ ██║█████╗ █████╗ █████╗ ██║ ██║ ██║███████║ ██║ ██║██╔══╝ ██╔══╝ ██╔══╝ ██║ ██║ ██║██╔══██║ ╚██████╔╝██║ ██║ ███████╗███████╗███████╗██║██║ ██║ ╚═════╝ ╚═╝ ╚═╝ ╚══════╝╚══════╝╚══════╝╚═╝╚═╝ ╚═╝ High-Performance LLM / VLM Inference & Autonomous Agentic Ecosystem… See the full description on the dataset page: https://huggingface.co/datasets/Brunobkr/llama.cpp_AlgMor24_github.

sourceHugging Faceupdated 2mo agoView on Hugging Face
0likes3.1kdownloads
purify.es.mjs2489 linesDownload Raw Back to dist
1/*! @license DOMPurify 3.4.13 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.4.13/LICENSE */2 3function _arrayLikeToArray(r, a) {4  (null == a || a > r.length) && (a = r.length);5  for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];6  return n;7}8function _arrayWithHoles(r) {9  if (Array.isArray(r)) return r;10}11function _iterableToArrayLimit(r, l) {12  var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];13  if (null != t) {14    var e,15      n,16      i,17      u,18      a = [],19      f = true,20      o = false;21    try {22      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);23    } catch (r) {24      o = true, n = r;25    } finally {26      try {27        if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;28      } finally {29        if (o) throw n;30      }31    }32    return a;33  }34}35function _nonIterableRest() {36  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");37}38function _slicedToArray(r, e) {39  return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();40}41function _unsupportedIterableToArray(r, a) {42  if (r) {43    if ("string" == typeof r) return _arrayLikeToArray(r, a);44    var t = {}.toString.call(r).slice(8, -1);45    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;46  }47}48 49const entries = Object.entries,50  setPrototypeOf = Object.setPrototypeOf,51  isFrozen = Object.isFrozen,52  getPrototypeOf = Object.getPrototypeOf,53  getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;54let freeze = Object.freeze,55  seal = Object.seal,56  create = Object.create; // eslint-disable-line import/no-mutable-exports57let _ref = typeof Reflect !== 'undefined' && Reflect,58  apply = _ref.apply,59  construct = _ref.construct;60if (!freeze) {61  freeze = function freeze(x) {62    return x;63  };64}65if (!seal) {66  seal = function seal(x) {67    return x;68  };69}70if (!apply) {71  apply = function apply(func, thisArg) {72    for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {73      args[_key - 2] = arguments[_key];74    }75    return func.apply(thisArg, args);76  };77}78if (!construct) {79  construct = function construct(Func) {80    for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {81      args[_key2 - 1] = arguments[_key2];82    }83    return new Func(...args);84  };85}86const arrayForEach = unapply(Array.prototype.forEach);87const arrayLastIndexOf = unapply(Array.prototype.lastIndexOf);88const arrayPop = unapply(Array.prototype.pop);89const arrayPush = unapply(Array.prototype.push);90const arraySplice = unapply(Array.prototype.splice);91const arrayIsArray = Array.isArray;92const stringToLowerCase = unapply(String.prototype.toLowerCase);93const stringToString = unapply(String.prototype.toString);94const stringMatch = unapply(String.prototype.match);95const stringReplace = unapply(String.prototype.replace);96const stringIndexOf = unapply(String.prototype.indexOf);97const stringTrim = unapply(String.prototype.trim);98const numberToString = unapply(Number.prototype.toString);99const booleanToString = unapply(Boolean.prototype.toString);100const bigintToString = typeof BigInt === 'undefined' ? null : unapply(BigInt.prototype.toString);101const symbolToString = typeof Symbol === 'undefined' ? null : unapply(Symbol.prototype.toString);102const objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty);103const objectToString = unapply(Object.prototype.toString);104const regExpTest = unapply(RegExp.prototype.test);105const typeErrorCreate = unconstruct(TypeError);106/**107 * Creates a new function that calls the given function with a specified thisArg and arguments.108 *109 * @param func - The function to be wrapped and called.110 * @returns A new function that calls the given function with a specified thisArg and arguments.111 */112function unapply(func) {113  return function (thisArg) {114    if (thisArg instanceof RegExp) {115      thisArg.lastIndex = 0;116    }117    for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {118      args[_key3 - 1] = arguments[_key3];119    }120    return apply(func, thisArg, args);121  };122}123/**124 * Creates a new function that constructs an instance of the given constructor function with the provided arguments.125 *126 * @param func - The constructor function to be wrapped and called.127 * @returns A new function that constructs an instance of the given constructor function with the provided arguments.128 */129function unconstruct(Func) {130  return function () {131    for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {132      args[_key4] = arguments[_key4];133    }134    return construct(Func, args);135  };136}137/**138 * Add properties to a lookup table139 *140 * @param set - The set to which elements will be added.141 * @param array - The array containing elements to be added to the set.142 * @param transformCaseFunc - An optional function to transform the case of each element before adding to the set.143 * @returns The modified set with added elements.144 */145function addToSet(set, array) {146  let transformCaseFunc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : stringToLowerCase;147  if (setPrototypeOf) {148    // Make 'in' and truthy checks like Boolean(set.constructor)149    // independent of any properties defined on Object.prototype.150    // Prevent prototype setters from intercepting set as a this value.151    setPrototypeOf(set, null);152  }153  if (!arrayIsArray(array)) {154    return set;155  }156  let l = array.length;157  while (l--) {158    let element = array[l];159    if (typeof element === 'string') {160      const lcElement = transformCaseFunc(element);161      if (lcElement !== element) {162        // Config presets (e.g. tags.js, attrs.js) are immutable.163        if (!isFrozen(array)) {164          array[l] = lcElement;165        }166        element = lcElement;167      }168    }169    set[element] = true;170  }171  return set;172}173/**174 * Clean up an array to harden against CSPP175 *176 * @param array - The array to be cleaned.177 * @returns The cleaned version of the array178 */179function cleanArray(array) {180  for (let index = 0; index < array.length; index++) {181    const isPropertyExist = objectHasOwnProperty(array, index);182    if (!isPropertyExist) {183      array[index] = null;184    }185  }186  return array;187}188/**189 * Shallow clone an object190 *191 * @param object - The object to be cloned.192 * @returns A new object that copies the original.193 */194function clone(object) {195  const newObject = create(null);196  for (const _ref2 of entries(object)) {197    var _ref3 = _slicedToArray(_ref2, 2);198    const property = _ref3[0];199    const value = _ref3[1];200    const isPropertyExist = objectHasOwnProperty(object, property);201    if (isPropertyExist) {202      if (arrayIsArray(value)) {203        newObject[property] = cleanArray(value);204      } else if (value && typeof value === 'object' && value.constructor === Object) {205        newObject[property] = clone(value);206      } else {207        newObject[property] = value;208      }209    }210  }211  return newObject;212}213/**214 * Convert non-node values into strings without depending on direct property access.215 *216 * @param value - The value to stringify.217 * @returns A string representation of the provided value.218 */219function stringifyValue(value) {220  switch (typeof value) {221    case 'string':222      {223        return value;224      }225    case 'number':226      {227        return numberToString(value);228      }229    case 'boolean':230      {231        return booleanToString(value);232      }233    case 'bigint':234      {235        return bigintToString ? bigintToString(value) : '0';236      }237    case 'symbol':238      {239        return symbolToString ? symbolToString(value) : 'Symbol()';240      }241    case 'undefined':242      {243        return objectToString(value);244      }245    case 'function':246    case 'object':247      {248        if (value === null) {249          return objectToString(value);250        }251        const valueAsRecord = value;252        const valueToString = lookupGetter(valueAsRecord, 'toString');253        if (typeof valueToString === 'function') {254          const stringified = valueToString(valueAsRecord);255          return typeof stringified === 'string' ? stringified : objectToString(stringified);256        }257        return objectToString(value);258      }259    default:260      {261        return objectToString(value);262      }263  }264}265/**266 * This method automatically checks if the prop is function or getter and behaves accordingly.267 *268 * @param object - The object to look up the getter function in its prototype chain.269 * @param prop - The property name for which to find the getter function.270 * @returns The getter function found in the prototype chain or a fallback function.271 */272function lookupGetter(object, prop) {273  while (object !== null) {274    const desc = getOwnPropertyDescriptor(object, prop);275    if (desc) {276      if (desc.get) {277        return unapply(desc.get);278      }279      if (typeof desc.value === 'function') {280        return unapply(desc.value);281      }282    }283    object = getPrototypeOf(object);284  }285  function fallbackValue() {286    return null;287  }288  return fallbackValue;289}290function isRegex(value) {291  try {292    regExpTest(value, '');293    return true;294  } catch (_unused) {295    return false;296  }297}298 299const 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']);300const 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']);301const 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']);302// List of SVG elements that are disallowed by default.303// We still need to know them so that we can do namespace304// checks properly in case one wants to add them to305// allow-list.306const 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']);307const 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']);308// Similarly to SVG, we want to know all MathML elements,309// even those that we disallow by default.310const mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);311const text = freeze(['#text']);312 313const 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']);314const svg = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', 'amplitude', 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'baseline-shift', 'begin', 'bias', 'by', 'class', 'clip', 'clippathunits', 'clip-path', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconstant', 'direction', 'display', 'divisor', 'dominant-baseline', 'dur', 'edgemode', 'elevation', 'end', 'exponent', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'filterunits', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'image-rendering', 'in', 'in2', 'intercept', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints', 'keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatrix', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid', 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits', 'maskunits', 'max', 'mask', 'mask-type', 'media', 'method', 'mode', 'min', 'name', 'numoctaves', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits', 'points', 'preservealpha', 'preserveaspectratio', 'primitiveunits', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 'repeatdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'slope', 'specularconstant', 'specularexponent', 'spreadmethod', 'startoffset', 'stddeviation', 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width', 'style', 'surfacescale', 'systemlanguage', 'tabindex', 'tablevalues', 'targetx', 'targety', 'transform', 'transform-origin', 'text-anchor', 'text-decoration', 'text-orientation', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', 'values', 'viewbox', 'visibility', 'version', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'width', 'word-spacing', 'wrap', 'writing-mode', 'xchannelselector', 'ychannelselector', 'x', 'x1', 'x2', 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpan']);315const 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']);316const xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);317 318const MUSTACHE_EXPR = seal(/{{[\w\W]*|^[\w\W]*}}/g);319const ERB_EXPR = seal(/<%[\w\W]*|^[\w\W]*%>/g);320const TMPLIT_EXPR = seal(/\${[\w\W]*/g);321const DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]+$/); // eslint-disable-line no-useless-escape322const ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape323const 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-escape324);325const IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i);326const ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g // eslint-disable-line no-control-regex327);328const DOCTYPE_NAME = seal(/^html$/i);329const CUSTOM_ELEMENT = seal(/^[a-z][.\w]*(-[.\w]+)+$/i);330// Markup-significant character probes used by _sanitizeElements.331// Shared module-level instances are safe despite the sticky /g flags:332// unapply() resets lastIndex for RegExp receivers before every call.333const ELEMENT_MARKUP_PROBE = seal(/<[/\w!]/g);334const COMMENT_MARKUP_PROBE = seal(/<[/\w]/g);335const FALLBACK_TAG_CLOSE = seal(/<\/no(script|embed|frames)/i);336const SELF_CLOSING_TAG = seal(/\/>/i);337 338// https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType339const NODE_TYPE = {340  element: 1,341  attribute: 2,342  text: 3,343  cdataSection: 4,344  entityReference: 5,345  // Deprecated346  entityNode: 6,347  // Deprecated348  processingInstruction: 7,349  comment: 8,350  document: 9,351  documentType: 10,352  documentFragment: 11,353  notation: 12 // Deprecated354};355const getGlobal = function getGlobal() {356  return typeof window === 'undefined' ? null : window;357};358/**359 * Creates a no-op policy for internal use only.360 * Don't export this function outside this module!361 * @param trustedTypes The policy factory.362 * @param purifyHostElement The Script element used to load DOMPurify (to determine policy name suffix).363 * @return The policy created (or null, if Trusted Types364 * are not supported or creating the policy failed).365 */366const _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, purifyHostElement) {367  if (typeof trustedTypes !== 'object' || typeof trustedTypes.createPolicy !== 'function') {368    return null;369  }370  // Allow the callers to control the unique policy name371  // by adding a data-tt-policy-suffix to the script element with the DOMPurify.372  // Policy creation with duplicate names throws in Trusted Types.373  let suffix = null;374  const ATTR_NAME = 'data-tt-policy-suffix';375  if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) {376    suffix = purifyHostElement.getAttribute(ATTR_NAME);377  }378  const policyName = 'dompurify' + (suffix ? '#' + suffix : '');379  try {380    return trustedTypes.createPolicy(policyName, {381      createHTML(html) {382        return html;383      },384      createScriptURL(scriptUrl) {385        return scriptUrl;386      }387    });388  } catch (_) {389    // Policy creation failed (most likely another DOMPurify script has390    // already run). Skip creating the policy, as this will only cause errors391    // if TT are enforced.392    console.warn('TrustedTypes policy ' + policyName + ' could not be created.');393    return null;394  }395};396const _createHooksMap = function _createHooksMap() {397  return {398    afterSanitizeAttributes: [],399    afterSanitizeElements: [],400    afterSanitizeShadowDOM: [],401    beforeSanitizeAttributes: [],402    beforeSanitizeElements: [],403    beforeSanitizeShadowDOM: [],404    uponSanitizeAttribute: [],405    uponSanitizeElement: [],406    uponSanitizeShadowNode: []407  };408};409/**410 * Resolve a set-valued configuration option: a fresh set built from411 * cfg[key] when it is an own array property (seeded with a clone of412 * options.base when given, case-normalized via options.transform),413 * the fallback set otherwise.414 *415 * @param cfg the cloned, prototype-free configuration object416 * @param key the configuration property to read417 * @param fallback the set to use when the option is absent or not an array418 * @param options transform and optional base set to merge into419 * @returns the resolved set420 */421const _resolveSetOption = function _resolveSetOption(cfg, key, fallback, options) {422  return objectHasOwnProperty(cfg, key) && arrayIsArray(cfg[key]) ? addToSet(options.base ? clone(options.base) : {}, cfg[key], options.transform) : fallback;423};424function createDOMPurify() {425  let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();426  const DOMPurify = root => createDOMPurify(root);427  DOMPurify.version = '3.4.13';428  DOMPurify.removed = [];429  if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document || !window.Element) {430    // Not running in a browser, provide a factory function431    // so that you can pass your own Window432    DOMPurify.isSupported = false;433    return DOMPurify;434  }435  let document = window.document;436  const originalDocument = document;437  const currentScript = originalDocument.currentScript;438  window.DocumentFragment;439    const HTMLTemplateElement = window.HTMLTemplateElement,440    Node = window.Node,441    Element = window.Element,442    NodeFilter = window.NodeFilter,443    _window$NamedNodeMap = window.NamedNodeMap;444    _window$NamedNodeMap === void 0 ? window.NamedNodeMap || window.MozNamedAttrMap : _window$NamedNodeMap;445    window.HTMLFormElement;446    const DOMParser = window.DOMParser,447    trustedTypes = window.trustedTypes;448  const ElementPrototype = Element.prototype;449  const cloneNode = lookupGetter(ElementPrototype, 'cloneNode');450  const remove = lookupGetter(ElementPrototype, 'remove');451  const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');452  const getChildNodes = lookupGetter(ElementPrototype, 'childNodes');453  const getParentNode = lookupGetter(ElementPrototype, 'parentNode');454  const getShadowRoot = lookupGetter(ElementPrototype, 'shadowRoot');455  const getAttributes = lookupGetter(ElementPrototype, 'attributes');456  const getNodeType = Node && Node.prototype ? lookupGetter(Node.prototype, 'nodeType') : null;457  const getNodeName = Node && Node.prototype ? lookupGetter(Node.prototype, 'nodeName') : null;458  const getOwnerDocument = Node && Node.prototype ? lookupGetter(Node.prototype, 'ownerDocument') : null;459  // As per issue #47, the web-components registry is inherited by a460  // new document created via createHTMLDocument. As per the spec461  // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)462  // a new empty registry is used when creating a template contents owner463  // document, so we use that as our parent document to ensure nothing464  // is inherited.465  if (typeof HTMLTemplateElement === 'function') {466    const template = document.createElement('template');467    if (template.content && template.content.ownerDocument) {468      document = template.content.ownerDocument;469    }470  }471  let trustedTypesPolicy;472  let emptyHTML = '';473  // The instance's own internal Trusted Types policy. Unlike a caller-supplied474  // `TRUSTED_TYPES_POLICY`, this is created at most once — Trusted Types throws475  // on duplicate policy names — and is the only policy allowed to persist476  // across configurations and survive `clearConfig()`.477  let defaultTrustedTypesPolicy;478  let defaultTrustedTypesPolicyResolved = false;479  // Tracks whether we are already inside a call to the configured Trusted Types480  // policy (`createHTML` or `createScriptURL`). If a supplied policy callback481  // itself calls `DOMPurify.sanitize` (the cause of #1422), `sanitize` would482  // re-enter the policy and recurse until the stack overflows. We detect that483  // re-entry and throw a clear, actionable error instead. The guard is shared484  // across both callbacks, because either one re-entering `sanitize` triggers485  // the same unbounded recursion.486  let IN_TRUSTED_TYPES_POLICY = 0;487  const _assertNotInTrustedTypesPolicy = function _assertNotInTrustedTypesPolicy() {488    if (IN_TRUSTED_TYPES_POLICY > 0) {489      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.');490    }491  };492  const _createTrustedHTML = function _createTrustedHTML(html) {493    _assertNotInTrustedTypesPolicy();494    IN_TRUSTED_TYPES_POLICY++;495    try {496      return trustedTypesPolicy.createHTML(html);497    } finally {498      IN_TRUSTED_TYPES_POLICY--;499    }500  };501  const _createTrustedScriptURL = function _createTrustedScriptURL(scriptUrl) {502    _assertNotInTrustedTypesPolicy();503    IN_TRUSTED_TYPES_POLICY++;504    try {505      return trustedTypesPolicy.createScriptURL(scriptUrl);506    } finally {507      IN_TRUSTED_TYPES_POLICY--;508    }509  };510  // Lazily resolve (and cache) the instance's internal default policy.511  // Resolution is attempted at most once: a successful `createPolicy` cannot be512  // repeated (Trusted Types throws on duplicate names), and a failed or513  // unsupported attempt must not be retried on every parse.514  const _getDefaultTrustedTypesPolicy = function _getDefaultTrustedTypesPolicy() {515    if (!defaultTrustedTypesPolicyResolved) {516      defaultTrustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);517      defaultTrustedTypesPolicyResolved = true;518    }519    return defaultTrustedTypesPolicy;520  };521  const _document = document,522    implementation = _document.implementation,523    createNodeIterator = _document.createNodeIterator,524    createDocumentFragment = _document.createDocumentFragment,525    getElementsByTagName = _document.getElementsByTagName;526  const importNode = originalDocument.importNode;527  let hooks = _createHooksMap();528  /**529   * Expose whether this browser supports running the full DOMPurify.530   */531  DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNode === 'function' && implementation && implementation.createHTMLDocument !== undefined;532  const MUSTACHE_EXPR$1 = MUSTACHE_EXPR,533    ERB_EXPR$1 = ERB_EXPR,534    TMPLIT_EXPR$1 = TMPLIT_EXPR,535    DATA_ATTR$1 = DATA_ATTR,536    ARIA_ATTR$1 = ARIA_ATTR,537    IS_SCRIPT_OR_DATA$1 = IS_SCRIPT_OR_DATA,538    ATTR_WHITESPACE$1 = ATTR_WHITESPACE,539    CUSTOM_ELEMENT$1 = CUSTOM_ELEMENT;540  let IS_ALLOWED_URI$1 = IS_ALLOWED_URI;541  /**542   * We consider the elements and attributes below to be safe. Ideally543   * don't add any new ones but feel free to remove unwanted ones.544   */545  /* allowed element names */546  let ALLOWED_TAGS = null;547  const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...text]);548  /* Allowed attribute names */549  let ALLOWED_ATTR = null;550  const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]);551  /*552   * Configure how DOMPurify should handle custom elements and their attributes as well as customized built-in elements.553   * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements)554   * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list)555   * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`.556   */557  let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, {558    tagNameCheck: {559      writable: true,560      configurable: false,561      enumerable: true,562      value: null563    },564    attributeNameCheck: {565      writable: true,566      configurable: false,567      enumerable: true,568      value: null569    },570    allowCustomizedBuiltInElements: {571      writable: true,572      configurable: false,573      enumerable: true,574      value: false575    }576  }));577  /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */578  let FORBID_TAGS = null;579  /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */580  let FORBID_ATTR = null;581  /* Config object to store ADD_TAGS/ADD_ATTR functions (when used as functions) */582  const EXTRA_ELEMENT_HANDLING = Object.seal(create(null, {583    tagCheck: {584      writable: true,585      configurable: false,586      enumerable: true,587      value: null588    },589    attributeCheck: {590      writable: true,591      configurable: false,592      enumerable: true,593      value: null594    }595  }));596  /* Decide if ARIA attributes are okay */597  let ALLOW_ARIA_ATTR = true;598  /* Decide if custom data attributes are okay */599  let ALLOW_DATA_ATTR = true;600  /* Decide if unknown protocols are okay */601  let ALLOW_UNKNOWN_PROTOCOLS = false;602  /* Decide if self-closing tags in attributes are allowed.603   * Usually removed due to a mXSS issue in jQuery 3.0 */604  let ALLOW_SELF_CLOSE_IN_ATTR = true;605  /* Output should be safe for common template engines.606   * This means, DOMPurify removes data attributes, mustaches and ERB607   */608  let SAFE_FOR_TEMPLATES = false;609  /* Output should be safe even for XML used within HTML and alike.610   * This means, DOMPurify removes comments when containing risky content.611   */612  let SAFE_FOR_XML = true;613  /* Decide if document with <html>... should be returned */614  let WHOLE_DOCUMENT = false;615  /* Track whether config is already set on this instance of DOMPurify. */616  let SET_CONFIG = false;617  /* Pristine allowlist bindings captured at setConfig() time. On the618   * persistent-config path sanitize() restores the sets from these before619   * the per-walk hook clone-guard, so a hook's in-call widening cannot620   * carry across calls. Null until setConfig() is called; reset by621   * clearConfig(). */622  let SET_CONFIG_ALLOWED_TAGS = null;623  let SET_CONFIG_ALLOWED_ATTR = null;624  /* Decide if all elements (e.g. style, script) must be children of625   * document.body. By default, browsers might move them to document.head */626  let FORCE_BODY = false;627  /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html628   * string (or a TrustedHTML object if Trusted Types are supported).629   * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead630   */631  let RETURN_DOM = false;632  /* Decide if a DOM `DocumentFragment` should be returned, instead of a html633   * string  (or a TrustedHTML object if Trusted Types are supported) */634  let RETURN_DOM_FRAGMENT = false;635  /* Try to return a Trusted Type object instead of a string, return a string in636   * case Trusted Types are not supported  */637  let RETURN_TRUSTED_TYPE = false;638  /* Output should be free from DOM clobbering attacks?639   * This sanitizes markups named with colliding, clobberable built-in DOM APIs.640   */641  let SANITIZE_DOM = true;642  /* Achieve full DOM Clobbering protection by isolating the namespace of named643   * properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules.644   *645   * HTML/DOM spec rules that enable DOM Clobbering:646   *   - Named Access on Window (§7.3.3)647   *   - DOM Tree Accessors (§3.1.5)648   *   - Form Element Parent-Child Relations (§4.10.3)649   *   - Iframe srcdoc / Nested WindowProxies (§4.8.5)650   *   - HTMLCollection (§4.2.10.2)651   *652   * Namespace isolation is implemented by prefixing `id` and `name` attributes653   * with a constant string, i.e., `user-content-`654   */655  let SANITIZE_NAMED_PROPS = false;656  const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-';657  /* Keep element content when removing element? */658  let KEEP_CONTENT = true;659  /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead660   * of importing it into a new Document and returning a sanitized copy */661  let IN_PLACE = false;662  /* Allow usage of profiles like html, svg and mathMl */663  let USE_PROFILES = {};664  /* Tags to ignore content of when KEEP_CONTENT is true */665  let FORBID_CONTENTS = null;666  const DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script',667  // <selectedcontent> mirrors the selected <option>'s subtree, cloned by668  // the UA (customizable <select>) — including any on* handlers — and the669  // engine re-mirrors synchronously whenever a removal changes which670  // option/selectedcontent is current, even inside DOMPurify's inert671  // DOMParser document. Hoisting its children on removal re-inserts a fresh672  // mirror target ahead of the walk, which the engine refills, looping673  // forever (DoS) and amplifying output. Dropping its content on removal674  // (rather than hoisting) breaks that cascade; the content is a duplicate675  // of the option, which is sanitized on its own. See campaign-3 F1/F6.676  'selectedcontent', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']);677  /* Tags that are safe for data: URIs */678  let DATA_URI_TAGS = null;679  const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);680  /* Attributes safe for values like "javascript:" */681  let URI_SAFE_ATTRIBUTES = null;682  const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']);683  const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';684  const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';685  const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';686  /* Document namespace */687  let NAMESPACE = HTML_NAMESPACE;688  let IS_EMPTY_INPUT = false;689  /* Allowed XHTML+XML namespaces */690  let ALLOWED_NAMESPACES = null;691  const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);692  const DEFAULT_MATHML_TEXT_INTEGRATION_POINTS = freeze(['mi', 'mo', 'mn', 'ms', 'mtext']);693  let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, DEFAULT_MATHML_TEXT_INTEGRATION_POINTS);694  const DEFAULT_HTML_INTEGRATION_POINTS = freeze(['annotation-xml']);695  let HTML_INTEGRATION_POINTS = addToSet({}, DEFAULT_HTML_INTEGRATION_POINTS);696  // Certain elements are allowed in both SVG and HTML697  // namespace. We need to specify them explicitly698  // so that they don't get erroneously deleted from699  // HTML namespace.700  const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']);701  /* Parsing of strict XHTML documents */702  let PARSER_MEDIA_TYPE = null;703  const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html'];704  const DEFAULT_PARSER_MEDIA_TYPE = 'text/html';705  let transformCaseFunc = null;706  /* Keep a reference to config to pass to hooks */707  let CONFIG = null;708  /* Ideally, do not touch anything below this line */709  /* ______________________________________________ */710  const formElement = document.createElement('form');711  const isRegexOrFunction = function isRegexOrFunction(testValue) {712    return testValue instanceof RegExp || testValue instanceof Function;713  };714  /**715   * _parseConfig716   *717   * @param cfg optional config literal718   */719  // eslint-disable-next-line complexity720  const _parseConfig = function _parseConfig() {721    let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};722    if (CONFIG && CONFIG === cfg) {723      return;724    }725    /* Shield configuration object from tampering */726    if (!cfg || typeof cfg !== 'object') {727      cfg = {};728    }729    /* Shield configuration object from prototype pollution */730    cfg = clone(cfg);731    PARSER_MEDIA_TYPE =732    // eslint-disable-next-line unicorn/prefer-includes733    SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? DEFAULT_PARSER_MEDIA_TYPE : cfg.PARSER_MEDIA_TYPE;734    // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.735    transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase;736    /* Set configuration parameters */737    ALLOWED_TAGS = _resolveSetOption(cfg, 'ALLOWED_TAGS', DEFAULT_ALLOWED_TAGS, {738      transform: transformCaseFunc739    });740    ALLOWED_ATTR = _resolveSetOption(cfg, 'ALLOWED_ATTR', DEFAULT_ALLOWED_ATTR, {741      transform: transformCaseFunc742    });743    ALLOWED_NAMESPACES = _resolveSetOption(cfg, 'ALLOWED_NAMESPACES', DEFAULT_ALLOWED_NAMESPACES, {744      transform: stringToString745    });746    URI_SAFE_ATTRIBUTES = _resolveSetOption(cfg, 'ADD_URI_SAFE_ATTR', DEFAULT_URI_SAFE_ATTRIBUTES, {747      transform: transformCaseFunc,748      base: DEFAULT_URI_SAFE_ATTRIBUTES749    });750    DATA_URI_TAGS = _resolveSetOption(cfg, 'ADD_DATA_URI_TAGS', DEFAULT_DATA_URI_TAGS, {751      transform: transformCaseFunc,752      base: DEFAULT_DATA_URI_TAGS753    });754    FORBID_CONTENTS = _resolveSetOption(cfg, 'FORBID_CONTENTS', DEFAULT_FORBID_CONTENTS, {755      transform: transformCaseFunc756    });757    FORBID_TAGS = _resolveSetOption(cfg, 'FORBID_TAGS', clone({}), {758      transform: transformCaseFunc759    });760    FORBID_ATTR = _resolveSetOption(cfg, 'FORBID_ATTR', clone({}), {761      transform: transformCaseFunc762    });763    USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES && typeof cfg.USE_PROFILES === 'object' ? clone(cfg.USE_PROFILES) : cfg.USE_PROFILES : false;764    ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true765    ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true766    ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false767    ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true768    SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false769    SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; // Default true770    WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false771    RETURN_DOM = cfg.RETURN_DOM || false; // Default false772    RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false773    RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false774    FORCE_BODY = cfg.FORCE_BODY || false; // Default false775    SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true776    SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false777    KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true778    IN_PLACE = cfg.IN_PLACE || false; // Default false779    IS_ALLOWED_URI$1 = isRegex(cfg.ALLOWED_URI_REGEXP) ? cfg.ALLOWED_URI_REGEXP : IS_ALLOWED_URI; // Default regexp780    NAMESPACE = typeof cfg.NAMESPACE === 'string' ? cfg.NAMESPACE : HTML_NAMESPACE; // Default HTML namespace781    MATHML_TEXT_INTEGRATION_POINTS = objectHasOwnProperty(cfg, 'MATHML_TEXT_INTEGRATION_POINTS') && cfg.MATHML_TEXT_INTEGRATION_POINTS && typeof cfg.MATHML_TEXT_INTEGRATION_POINTS === 'object' ? clone(cfg.MATHML_TEXT_INTEGRATION_POINTS) : addToSet({}, DEFAULT_MATHML_TEXT_INTEGRATION_POINTS); // Default built-in map782    HTML_INTEGRATION_POINTS = objectHasOwnProperty(cfg, 'HTML_INTEGRATION_POINTS') && cfg.HTML_INTEGRATION_POINTS && typeof cfg.HTML_INTEGRATION_POINTS === 'object' ? clone(cfg.HTML_INTEGRATION_POINTS) : addToSet({}, DEFAULT_HTML_INTEGRATION_POINTS); // Default built-in map783    const customElementHandling = objectHasOwnProperty(cfg, 'CUSTOM_ELEMENT_HANDLING') && cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING === 'object' ? clone(cfg.CUSTOM_ELEMENT_HANDLING) : create(null);784    CUSTOM_ELEMENT_HANDLING = create(null);785    if (objectHasOwnProperty(customElementHandling, 'tagNameCheck') && isRegexOrFunction(customElementHandling.tagNameCheck)) {786      CUSTOM_ELEMENT_HANDLING.tagNameCheck = customElementHandling.tagNameCheck; // Default undefined787    }788    if (objectHasOwnProperty(customElementHandling, 'attributeNameCheck') && isRegexOrFunction(customElementHandling.attributeNameCheck)) {789      CUSTOM_ELEMENT_HANDLING.attributeNameCheck = customElementHandling.attributeNameCheck; // Default undefined790    }791    if (objectHasOwnProperty(customElementHandling, 'allowCustomizedBuiltInElements') && typeof customElementHandling.allowCustomizedBuiltInElements === 'boolean') {792      CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = customElementHandling.allowCustomizedBuiltInElements; // Default undefined793    }794    seal(CUSTOM_ELEMENT_HANDLING);795    if (SAFE_FOR_TEMPLATES) {796      ALLOW_DATA_ATTR = false;797    }798    if (RETURN_DOM_FRAGMENT) {799      RETURN_DOM = true;800    }801    /* Parse profile info */802    if (USE_PROFILES) {803      ALLOWED_TAGS = addToSet({}, text);804      ALLOWED_ATTR = create(null);805      if (USE_PROFILES.html === true) {806        addToSet(ALLOWED_TAGS, html$1);807        addToSet(ALLOWED_ATTR, html);808      }809      if (USE_PROFILES.svg === true) {810        addToSet(ALLOWED_TAGS, svg$1);811        addToSet(ALLOWED_ATTR, svg);812        addToSet(ALLOWED_ATTR, xml);813      }814      if (USE_PROFILES.svgFilters === true) {815        addToSet(ALLOWED_TAGS, svgFilters);816        addToSet(ALLOWED_ATTR, svg);817        addToSet(ALLOWED_ATTR, xml);818      }819      if (USE_PROFILES.mathMl === true) {820        addToSet(ALLOWED_TAGS, mathMl$1);821        addToSet(ALLOWED_ATTR, mathMl);822        addToSet(ALLOWED_ATTR, xml);823      }824    }825    /* Always reset function-based ADD_TAGS / ADD_ATTR checks to prevent826     * leaking across calls when switching from function to array config */827    EXTRA_ELEMENT_HANDLING.tagCheck = null;828    EXTRA_ELEMENT_HANDLING.attributeCheck = null;829    /* Merge configuration parameters */830    if (objectHasOwnProperty(cfg, 'ADD_TAGS')) {831      if (typeof cfg.ADD_TAGS === 'function') {832        EXTRA_ELEMENT_HANDLING.tagCheck = cfg.ADD_TAGS;833      } else if (arrayIsArray(cfg.ADD_TAGS)) {834        if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {835          ALLOWED_TAGS = clone(ALLOWED_TAGS);836        }837        addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);838      }839    }840    if (objectHasOwnProperty(cfg, 'ADD_ATTR')) {841      if (typeof cfg.ADD_ATTR === 'function') {842        EXTRA_ELEMENT_HANDLING.attributeCheck = cfg.ADD_ATTR;843      } else if (arrayIsArray(cfg.ADD_ATTR)) {844        if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {845          ALLOWED_ATTR = clone(ALLOWED_ATTR);846        }847        addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);848      }849    }850    if (objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') && arrayIsArray(cfg.ADD_URI_SAFE_ATTR)) {851      addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);852    }853    if (objectHasOwnProperty(cfg, 'FORBID_CONTENTS') && arrayIsArray(cfg.FORBID_CONTENTS)) {854      if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {855        FORBID_CONTENTS = clone(FORBID_CONTENTS);856      }857      addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);858    }859    if (objectHasOwnProperty(cfg, 'ADD_FORBID_CONTENTS') && arrayIsArray(cfg.ADD_FORBID_CONTENTS)) {860      if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {861        FORBID_CONTENTS = clone(FORBID_CONTENTS);862      }863      addToSet(FORBID_CONTENTS, cfg.ADD_FORBID_CONTENTS, transformCaseFunc);864    }865    /* Add #text in case KEEP_CONTENT is set to true */866    if (KEEP_CONTENT) {867      ALLOWED_TAGS['#text'] = true;868    }869    /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */870    if (WHOLE_DOCUMENT) {871      addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);872    }873    /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */874    if (ALLOWED_TAGS.table) {875      addToSet(ALLOWED_TAGS, ['tbody']);876      delete FORBID_TAGS.tbody;877    }878    // Re-derive the active Trusted Types policy from this configuration on879    // every parse. The active policy must never be sticky closure state that880    // outlives the config that set it: a caller-supplied policy left in place881    // after `clearConfig()` — or after a later call that supplied none, or882    // `TRUSTED_TYPES_POLICY: null` — could sign a subsequent "default"883    // `RETURN_TRUSTED_TYPE` result with a foreign, possibly unsafe policy.884    // See GHSA-vxr8-fq34-vvx9.885    if (cfg.TRUSTED_TYPES_POLICY) {886      if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') {887        throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');888      }889      if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') {890        throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');891      }892      // A caller-supplied policy applies to this configuration only.893      const previousTrustedTypesPolicy = trustedTypesPolicy;894      trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;895      // Sign local variables required by `sanitize`. If the supplied policy's896      // `createHTML` is circular (i.e. it calls `DOMPurify.sanitize`), this897      // throws via the re-entrancy guard. Restore the previous policy first so898      // the instance is not left in a poisoned state. See #1422.899      try {900        emptyHTML = _createTrustedHTML('');901      } catch (error) {902        trustedTypesPolicy = previousTrustedTypesPolicy;903        throw error;904      }905    } else if (cfg.TRUSTED_TYPES_POLICY === null) {906      // Explicit opt-out for this call: perform no Trusted Types signing and907      // create nothing (so a strict `trusted-types` CSP that disallows a908      // `dompurify` policy can still call `sanitize` from inside its own909      // policy — see #1422). Resetting to `undefined` rather than a sticky910      // `null` also drops any previously retained caller policy, so it cannot911      // resurface on a later call, while still allowing the next config-less912      // call to restore the internal default policy. See GHSA-vxr8-fq34-vvx9.913      trustedTypesPolicy = undefined;914      emptyHTML = '';915    } else {916      // No policy supplied: keep the currently active policy if one is set — a917      // previously supplied policy is intentionally sticky across config-less918      // calls — otherwise fall back to the instance's own internal policy,919      // created at most once. (A policy supplied for a *single* call still920      // lingers by design; what must not linger is a policy whose configuration921      // has been torn down via `clearConfig()`, which restores the default.)922      if (trustedTypesPolicy === undefined) {923        trustedTypesPolicy = _getDefaultTrustedTypesPolicy();924      }925      // Sign internal variables only when a policy is active. A falsy policy926      // (Trusted Types unsupported, creation failed, or an explicit opt-out)927      // leaves `emptyHTML` as a plain string, so we never call `.createHTML` on928      // a non-policy and throw. See #1422.929      if (trustedTypesPolicy && typeof emptyHTML === 'string') {930        emptyHTML = _createTrustedHTML('');931      }932    }933    // Prevent further manipulation of configuration.934    // Not available in IE8, Safari 5, etc.935    if (freeze) {936      freeze(cfg);937    }938    CONFIG = cfg;939  };940  /* Keep track of all possible SVG and MathML tags941   * so that we can perform the namespace checks942   * correctly. */943  const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]);944  const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]);945  /**946   * Namespace rules for an element in the SVG namespace.947   *948   * @param tagName the element's lowercase tag name949   * @param parent the (possibly simulated) parent node950   * @param parentTagName the parent's lowercase tag name951   * @returns true if a spec-compliant parser could produce this element952   */953  const _checkSvgNamespace = function _checkSvgNamespace(tagName, parent, parentTagName) {954    // The only way to switch from HTML namespace to SVG955    // is via <svg>. If it happens via any other tag, then956    // it should be killed.957    if (parent.namespaceURI === HTML_NAMESPACE) {958      return tagName === 'svg';959    }960    // The only way to switch from MathML to SVG is via <svg>961    // if the parent is either <annotation-xml> or a MathML962    // text integration point.963    if (parent.namespaceURI === MATHML_NAMESPACE) {964      return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);965    }966    // We only allow elements that are defined in SVG967    // spec. All others are disallowed in SVG namespace.968    return Boolean(ALL_SVG_TAGS[tagName]);969  };970  /**971   * Namespace rules for an element in the MathML namespace.972   *973   * @param tagName the element's lowercase tag name974   * @param parent the (possibly simulated) parent node975   * @param parentTagName the parent's lowercase tag name976   * @returns true if a spec-compliant parser could produce this element977   */978  const _checkMathMlNamespace = function _checkMathMlNamespace(tagName, parent, parentTagName) {979    // The only way to switch from HTML namespace to MathML980    // is via <math>. If it happens via any other tag, then981    // it should be killed.982    if (parent.namespaceURI === HTML_NAMESPACE) {983      return tagName === 'math';984    }985    // The only way to switch from SVG to MathML is via986    // <math> and HTML integration points987    if (parent.namespaceURI === SVG_NAMESPACE) {988      return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];989    }990    // We only allow elements that are defined in MathML991    // spec. All others are disallowed in MathML namespace.992    return Boolean(ALL_MATHML_TAGS[tagName]);993  };994  /**995   * Namespace rules for an element in the HTML namespace.996   *997   * @param tagName the element's lowercase tag name998   * @param parent the (possibly simulated) parent node999   * @param parentTagName the parent's lowercase tag name1000   * @returns true if a spec-compliant parser could produce this element1001   */1002  const _checkHtmlNamespace = function _checkHtmlNamespace(tagName, parent, parentTagName) {1003    // The only way to switch from SVG to HTML is via1004    // HTML integration points, and from MathML to HTML1005    // is via MathML text integration points1006    if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {1007      return false;1008    }1009    if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {1010      return false;1011    }1012    // We disallow tags that are specific for MathML1013    // or SVG and should never appear in HTML namespace1014    return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);1015  };1016  /**1017   * @param element a DOM element whose namespace is being checked1018   * @returns Return false if the element has a1019   *  namespace that a spec-compliant parser would never1020   *  return. Return true otherwise.1021   */1022  const _checkValidNamespace = function _checkValidNamespace(element) {1023    let parent = getParentNode(element);1024    // In JSDOM, if we're inside shadow DOM, then parentNode1025    // can be null. We just simulate parent in this case.1026    if (!parent || !parent.tagName) {1027      parent = {1028        namespaceURI: NAMESPACE,1029        tagName: 'template'1030      };1031    }1032    const tagName = stringToLowerCase(element.tagName);1033    const parentTagName = stringToLowerCase(parent.tagName);1034    if (!ALLOWED_NAMESPACES[element.namespaceURI]) {1035      return false;1036    }1037    if (element.namespaceURI === SVG_NAMESPACE) {1038      return _checkSvgNamespace(tagName, parent, parentTagName);1039    }1040    if (element.namespaceURI === MATHML_NAMESPACE) {1041      return _checkMathMlNamespace(tagName, parent, parentTagName);1042    }1043    if (element.namespaceURI === HTML_NAMESPACE) {1044      return _checkHtmlNamespace(tagName, parent, parentTagName);1045    }1046    // For XHTML and XML documents that support custom namespaces1047    if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) {1048      return true;1049    }1050    // The code should never reach this place (this means1051    // that the element somehow got namespace that is not1052    // HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES).1053    // Return false just in case.1054    return false;1055  };1056  /**1057   * _forceRemove1058   *1059   * @param node a DOM node1060   */1061  const _forceRemove = function _forceRemove(node) {1062    arrayPush(DOMPurify.removed, {1063      element: node1064    });1065    try {1066      // eslint-disable-next-line unicorn/prefer-dom-node-remove1067      getParentNode(node).removeChild(node);1068    } catch (_) {1069      /* The normal detach failed — this is reached for a parentless node1070         (getParentNode() is null, so .removeChild throws). Element.prototype1071         .remove() is itself a spec no-op on a parentless node, so a recorded1072         "removal" would otherwise hand the caller back an intact,1073         payload-bearing node (e.g. a detached IN_PLACE root the mXSS canary or1074         the style-with-element-child rule decided to kill). Fail closed by1075         throwing — exactly as a clobbered root does at the IN_PLACE entry —1076         rather than trying to "neutralize" the node via its own methods.1077         Neutralizing would mean calling getAttributeNames()/removeAttribute()1078         on the node, both of which a <form> root can clobber via a named child1079         (and _isClobbered does not even probe getAttributeNames), so the1080         neutralize step could itself be silently defeated, leaving the payload1081         intact. A throw touches only the cached, clobber-safe remove() and1082         getParentNode(). Generalizes GHSA-r47g-fvhr-h676 (clobbered-form root)1083         to every root-kill reason. REPORT-3.1084                This lives inside the catch, so it never fires for a normally-removed1085         in-tree node: those have a parent, removeChild() succeeds, and the1086         catch is not entered. Only a kept (parentless) root reaches here. */1087      remove(node);1088      if (!getParentNode(node)) {1089        throw typeErrorCreate('a node selected for removal could not be detached from its tree ' + 'and cannot be safely returned; refusing to sanitize in place');1090      }1091    }1092  };1093  /**1094   * _neutralizeRoot1095   *1096   * Fail-closed teardown of an in-place root after the sanitize walk aborts1097   * (campaign-3 F2). An internal throw mid-walk — e.g. a page-registered1098   * custom element's reaction detaches a node so `_forceRemove`'s deliberate1099   * parentless guard throws, or any other re-entrant engine mutation — would1100   * otherwise leave the caller's *live* tree half-sanitized, with everything1101   * after the abort point still carrying its handlers. There is no safe way1102   * to resume the walk (the tree mutated under us), so we strip the root bare:1103   * remove every child and every attribute, then let the caller's catch see1104   * the original error. Clobber-safe (cached `remove`/`childNodes`/`attributes`1105   * getters; the root was already clobber-pre-flighted at the IN_PLACE entry).1106   *1107   * @param root the in-place root to empty1108   */1109  const _neutralizeRoot = function _neutralizeRoot(root) {1110    /* Strip every disallowed attribute (on* handlers included) off the whole1111       subtree BEFORE detaching anything. Detaching first would hand back1112       handler-bearing originals (e.g. an already-loading `<img onerror>`)1113       whose queued resource event still fires in page scope after we throw.1114       Clobber-safe reads; a doomed clobbered node's own attributes are1115       irrelevant while its non-clobbered descendants are reached and scrubbed. */1116    _neutralizeSubtree(root);1117    const childNodes = getChildNodes(root);1118    if (childNodes) {1119      const snapshot = [];1120      arrayForEach(childNodes, child => {1121        arrayPush(snapshot, child);1122      });1123      arrayForEach(snapshot, child => {1124        try {1125          remove(child);1126        } catch (_) {1127          /* Best-effort teardown; a still-attached child is handled below */1128        }1129      });1130    }1131    const attributes = getAttributes(root);1132    if (attributes) {1133      for (let i = attributes.length - 1; i >= 0; --i) {1134        const attribute = attributes[i];1135        const name = attribute && attribute.name;1136        if (typeof name === 'string') {1137          try {1138            root.removeAttribute(name);1139          } catch (_) {1140            /* Clobbered removeAttribute — ignore (fail-closed best effort) */1141          }1142        }1143      }1144    }1145  };1146  /**1147   * _removeAttribute1148   *1149   * @param name an Attribute name1150   * @param element a DOM node1151   */1152  const _removeAttribute = function _removeAttribute(name, element) {1153    try {1154      arrayPush(DOMPurify.removed, {1155        attribute: element.getAttributeNode(name),1156        from: element1157      });1158    } catch (_) {1159      arrayPush(DOMPurify.removed, {1160        attribute: null,1161        from: element1162      });1163    }1164    element.removeAttribute(name);1165    // We void attribute values for unremovable "is" attributes1166    if (name === 'is') {1167      if (RETURN_DOM || RETURN_DOM_FRAGMENT) {1168        try {1169          _forceRemove(element);1170        } catch (_) {}1171      } else {1172        try {1173          element.setAttribute(name, '');1174        } catch (_) {}1175      }1176    }1177  };1178  /**1179   * _stripDisallowedAttributes1180   *1181   * Removes every attribute the active configuration does not allow from a1182   * single element, using the same allowlist as the main attribute pass (so1183   * `on*` handlers go, but no `/^on/` blocklist is introduced). Used only to1184   * neutralise nodes that are being discarded from an in-place tree.1185   *1186   * @param element the element to strip1187   */1188  const _stripDisallowedAttributes = function _stripDisallowedAttributes(element) {1189    const attributes = getAttributes(element);1190    if (!attributes) {1191      return;1192    }1193    for (let i = attributes.length - 1; i >= 0; --i) {1194      const attribute = attributes[i];1195      const name = attribute && attribute.name;1196      if (typeof name !== 'string' || ALLOWED_ATTR[transformCaseFunc(name)]) {1197        continue;1198      }1199      try {1200        element.removeAttribute(name);

Showing the first 1,200 of 2489 lines. Download the file for the rest.

Brunobkr/llama.cpp_AlgMor24_github · Team Ai