fast-xml-validator 1.3.0 → 1.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/fxv.cjs +1 -1
- package/lib/fxv.d.cts +65 -1
- package/lib/fxv.min.js +1 -1
- package/lib/fxv.min.js.map +1 -1
- package/package.json +3 -2
- package/src/SyntaxValidator.js +414 -0
- package/src/fxv.d.ts +65 -1
- package/src/fxv.js +2 -8
- package/src/util.js +27 -1
- package/src/validators/AttributeStringValidator.js +115 -0
- package/src/validators/CommentCdataReader.js +106 -0
- package/src/validators/ControlCharValidator.js +44 -0
- package/src/validators/DocTypeValidator.js +280 -0
- package/src/validators/RawSubtreeReader.js +47 -0
- package/src/validators/SkipTagMatcher.js +54 -0
- package/src/validators/XmlDeclarationValidator.js +103 -0
- package/src/validators/XmlNameValidator.js +24 -0
package/lib/fxv.min.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.fxp=e():t.fxp=e()}(this,()=>(()=>{"use strict";var t={d:(e,n)=>{for(var r in n)t.o(n,r)&&!t.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:n[r]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};t.r(e),t.d(e,{BusinessRulesValidator:()=>ye,SyntaxValidator:()=>we});const n=":A-Za-z_À-ÖØ-öø-˿Ͱ-ͽͿ-҆҈--⁰-Ⰰ-、-豈-﷏ﷰ-�",r=":A-Za-z_À-˿Ͱ-ͽͿ-҆҈--⁰-Ⰰ-、-豈-﷏ﷰ-�𐀀-",i=r+"\\-\\.\\d·̀-ͯ҇‿-⁀",s=(t,e,n="")=>{const r=`[${t.replace(":","")}][${e.replace(":","")}]*`;return{name:new RegExp(`^[${t}][${e}]*$`,n),ncName:new RegExp(`^${r}$`,n),qName:new RegExp(`^${r}(?::${r})?$`,n),nmToken:new RegExp(`^[${e}]+$`,n),nmTokens:new RegExp(`^[${e}]+(?:\\s+[${e}]+)*$`,n)}},a=s(n,n+"\\-\\.\\d·̀-ͯ‿-⁀"),o=s(r,i,"u"),l=":A-Za-z_",h=s(l,l+"\\-\\.\\d"),u=(t="1.0",e=!1)=>e?h:"1.1"===t?o:a,c=(t,{xmlVersion:e="1.0",asciiOnly:n=!1}={})=>u(e,n).name.test(t),d=["name","ncName","qName","nmToken","nmTokens"],p=(t,{xmlVersion:e="1.0",asciiOnly:n=!1,maxCacheSize:r=2048}={})=>{if(!d.includes(t))throw new TypeError(`Unknown production "${t}". Must be one of: ${d.join(", ")}`);const i=u(e,n)[t];let s=new Map;const a=t=>{const e=s.get(t);if(void 0!==e)return e;const n=i.test(t);return s.size<r&&s.set(t,n),n};return a.reset=()=>{s=new Map},a};var f={maxEntityCount:1/0,maxEntitySize:1/0},g=function(){function t(t,e){void 0===e&&(e="1.0"),this.options=Object.assign({},f,t),this.suppressValidationErr=!t,this.xmlVersion=e}var e=t.prototype;return e.validateDocType=function(t,e){if("O"!==t[e+3]||"C"!==t[e+4]||"T"!==t[e+5]||"Y"!==t[e+6]||"P"!==t[e+7]||"E"!==t[e+8])throw new Error("Invalid Tag instead of DOCTYPE");e+=9;for(var n=1,r=!1,i=!1,s=0;e<t.length;e++)if("<"!==t[e]||i)if(">"===t[e]){if(i?"-"===t[e-1]&&"-"===t[e-2]&&(i=!1,n--):n--,0===n)break}else"["===t[e]&&(r=!0);else{if(r&&v(t,"!ENTITY",e)){e+=7;var a=this._validateEntityExp(t,e+1,s);s=a[0],e=a[1]}else if(r&&v(t,"!ELEMENT",e))e+=8,e=this._validateElementExp(t,e+1);else{if(r&&v(t,"!ATTLIST",e)){e+=8,e=this._validateAttlistExp(t,e+1);continue}if(r&&v(t,"!NOTATION",e))e+=9,e=this._validateNotationExp(t,e+1);else{if(!v(t,"!--",e))throw new Error("Invalid DOCTYPE");i=!0}}n++}if(0!==n)throw new Error("Unclosed DOCTYPE");return e},e._validateEntityExp=function(t,e,n){for(var r=e=m(t,e);e<t.length&&!/\s/.test(t[e])&&'"'!==t[e]&&"'"!==t[e];)e++;var i,s=t.substring(r,e);if(x(s,this.xmlVersion),e=m(t,e),!this.suppressValidationErr){if("SYSTEM"===t.substring(e,e+6).toUpperCase())throw new Error("External entities are not supported");if("%"===t[e])throw new Error("Parameter entities are not supported")}var a=b(t,e,"entity");e=a[0],i=a[1];var o=this.options,l=o.maxEntitySize,h=o.maxEntityCount;if(i.length>l)throw new Error('Entity "'+s+'" size ('+i.length+") exceeds maximum allowed size ("+l+")");if(-1===i.indexOf("&")&&++n>h)throw new Error("Entity count ("+n+") exceeds maximum allowed ("+h+")");return[n,e-1]},e._validateNotationExp=function(t,e){for(var n=e=m(t,e);e<t.length&&!/\s/.test(t[e]);)e++;var r=t.substring(n,e);!this.suppressValidationErr&&x(r,this.xmlVersion),e=m(t,e);var i=t.substring(e,e+6).toUpperCase();if(!this.suppressValidationErr&&"SYSTEM"!==i&&"PUBLIC"!==i)throw new Error('Expected SYSTEM or PUBLIC, found "'+i+'"');return e=m(t,e+=i.length),"PUBLIC"===i?'"'!==t[e=m(t,e=b(t,e,"publicIdentifier")[0])]&&"'"!==t[e]||(e=b(t,e,"systemIdentifier")[0]):"SYSTEM"===i&&(e=b(t,e,"systemIdentifier")[0]),--e},e._validateElementExp=function(t,e){for(var n=e=m(t,e);e<t.length&&!/\s/.test(t[e]);)e++;var r=t.substring(n,e);if(!this.suppressValidationErr&&!c(r,{xmlVersion:this.xmlVersion}))throw new Error('Invalid element name: "'+r+'"');if("E"===t[e=m(t,e)]&&v(t,"MPTY",e))e+=4;else if("A"===t[e]&&v(t,"NY",e))e+=2;else if("("===t[e]){for(e++;e<t.length&&")"!==t[e];)e++;if(")"!==t[e])throw new Error("Unterminated content model")}else if(!this.suppressValidationErr)throw new Error('Invalid Element Expression, found "'+t[e]+'"');return e},e._validateAttlistExp=function(t,e){for(var n=e=m(t,e);e<t.length&&!/\s/.test(t[e]);)e++;x(t.substring(n,e),this.xmlVersion);for(var r=e=m(t,e);e<t.length&&!/\s/.test(t[e]);)e++;if(x(t.substring(r,e),this.xmlVersion),e=m(t,e),"NOTATION"===t.substring(e,e+8).toUpperCase()){if("("!==t[e=m(t,e+=8)])throw new Error("Expected '(', found \""+t[e]+'"');for(e++;e<t.length&&")"!==t[e];){for(var i=e;e<t.length&&"|"!==t[e]&&")"!==t[e];)e++;x(t.substring(i,e).trim(),this.xmlVersion),"|"===t[e]&&(e=m(t,++e))}if(")"!==t[e])throw new Error("Unterminated list of notations");e++}else{for(var s=e;e<t.length&&!/\s/.test(t[e]);)e++;var a=t.substring(s,e);if(!this.suppressValidationErr&&!["CDATA","ID","IDREF","IDREFS","ENTITY","ENTITIES","NMTOKEN","NMTOKENS"].includes(a.toUpperCase()))throw new Error('Invalid attribute type: "'+a+'"')}return e=m(t,e),"#REQUIRED"===t.substring(e,e+9).toUpperCase()?e+=9:"#IMPLIED"===t.substring(e,e+8).toUpperCase()?e+=8:e=b(t,e,"ATTLIST default value")[0],e},t}();function m(t,e){for(;e<t.length&&/\s/.test(t[e]);)e++;return e}function v(t,e,n){for(var r=0;r<e.length;r++)if(e[r]!==t[n+r+1])return!1;return!0}function x(t,e){if(void 0===e&&(e="1.0"),!c(t,{xmlVersion:e}))throw new Error('Invalid entity name "'+t+'"')}function b(t,e,n){var r=t[e];if('"'!==r&&"'"!==r)throw new Error("Expected quoted string for "+n+', found "'+r+'"');for(var i=++e;e<t.length&&t[e]!==r;)e++;if(t[e]!==r)throw new Error("Unterminated "+n+" value");var s=t.substring(i,e);return[++e,s]}function E(t){var e="function"==typeof Map?new Map:void 0;return E=function(t){if(null===t||!function(t){try{return-1!==Function.toString.call(t).indexOf("[native code]")}catch(e){return"function"==typeof t}}(t))return t;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,n)}function n(){return function(t,e,n){if(y())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,e);var i=new(t.bind.apply(t,r));return n&&w(i,n.prototype),i}(t,arguments,N(this).constructor)}return n.prototype=Object.create(t.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),w(n,t)},E(t)}function y(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(y=function(){return!!t})()}function w(t,e){return w=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},w(t,e)}function N(t){return N=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},N(t)}var _=function(t){function e(e,n,r,i){var s;return(s=t.call(this,e)||this).name=s.constructor.name,s.code=n,s.line=r,s.col=i,null==Error.captureStackTrace||Error.captureStackTrace(s,s.constructor),s}var n,r;return r=t,(n=e).prototype=Object.create(r.prototype),n.prototype.constructor=n,w(n,r),e}(E(Error)),S={allowBooleanAttributes:!1,unpairedTags:[],docType:{maxEntityCount:1/0,maxEntitySize:1/0}};function T(t){return" "===t||"\t"===t||"\n"===t||"\r"===t}function I(t,e,n){for(var r=e,i=e,s=!1;e<t.length;e++){var a=t[e];if(!s&&(" "===a||"?"===a)){var o=t.substr(i,e-i);s=!0,"xml"===o.toLowerCase()?V("InvalidXml","XML declaration allowed only at the start of the document.",$(t,r-2)):n(o)||V("InvalidXml",'Processing instruction target "'+o+'" is not a valid XML Name.',$(t,r-2))}if("?"===a&&">"===t[e+1])return++e}V("InvalidXml",'Processing instruction is not closed with "?>".',$(t,r-2))}function C(t,e,n){if(t.length>e+2&&"-"===t[e+1]&&"-"===t[e+2]){for(e+=3;e<t.length;e++)if("-"===t[e]&&"-"===t[e+1]&&">"===t[e+2]){e+=2;break}if(">"!==t[e])throw new Error('Comment is not closed with "--\x3e".')}else if(t.length>e+7&&"D"===t[e+1]&&"O"===t[e+2]&&"C"===t[e+3]&&"T"===t[e+4]&&"Y"===t[e+5]&&"P"===t[e+6]&&"E"===t[e+7])e=n.validateDocType(t,e-1);else{if(!(t.length>e+8&&"["===t[e+1]&&"C"===t[e+2]&&"D"===t[e+3]&&"A"===t[e+4]&&"T"===t[e+5]&&"A"===t[e+6]&&"["===t[e+7]))throw new Error("Invalid construct starting with '<!'.");for(e+=8;e<t.length;e++)if("]"===t[e]&&"]"===t[e+1]&&">"===t[e+2]){e+=2;break}if(">"!==t[e])throw new Error('CDATA section is not closed with "]]>".')}return e}var A='"',O="'";function P(t,e){for(var n="",r="",i=!1;e<t.length;e++){if(t[e]===A||t[e]===O)""===r?r=t[e]:r!==t[e]||(r="");else if(">"===t[e]&&""===r){i=!0;break}n+=t[e]}return""===r&&{value:n,index:e,tagClosed:i}}var M=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function D(t,e,n,r){for(var i=function(t,e){for(var n=[],r=e.exec(t);r;){var i=[];i.startIndex=e.lastIndex-r[0].length;for(var s=r.length,a=0;a<s;a++)i.push(r[a]);n.push(i),r=e.exec(t)}return n}(t,M),s={},a=0;a<i.length;a++){if(0===i[a][1].length)return{err:{code:"InvalidAttr",msg:"Attribute '"+i[a][2]+"' has no space in starting.",line:j(i[a])}};if(void 0!==i[a][3]&&void 0===i[a][4])return{err:{code:"InvalidAttr",msg:"Attribute '"+i[a][2]+"' is without value.",line:j(i[a])}};if(void 0===i[a][3]&&!e.allowBooleanAttributes)return{err:{code:"InvalidAttr",msg:"boolean attribute '"+i[a][2]+"' is not allowed.",line:j(i[a])}};var o=i[a][2];if(!n(o))return{err:{code:"InvalidAttr",msg:"Attribute '"+o+"' is an invalid name.",line:j(i[a])}};if(o.startsWith("xmlns:")&&""===i[a][6]&&"1.0"===r)return{err:{code:"InvalidAttr",msg:"Undeclaring the prefixed namespace "+o+'="" is only permitted in XML 1.1 documents.',line:j(i[a])}};if(Object.prototype.hasOwnProperty.call(s,o))return{err:{code:"InvalidAttr",msg:"Attribute '"+o+"' is repeated.",line:j(i[a])}};s[o]=1}return!0}function k(t,e){if(";"===t[++e])return-1;if("#"===t[e])return function(t,e){var n=/\d/;for("x"===t[e]&&(e++,n=/[\da-fA-F]/);e<t.length;e++){if(";"===t[e])return e;if(!t[e].match(n))break}return-1}(t,++e);for(var n=0;e<t.length;e++,n++)if(!(t[e].match(/\w/)&&n<20)){if(";"===t[e])break;return-1}return e}function V(t,e,n){throw new _(e,t,n.line||n,n.col)}function $(t,e){var n=t.substring(0,e).split(/\r?\n/);return{line:n.length,col:n[n.length-1].length+1}}function j(t){return t.startIndex+t[1].length}const L=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",U=new RegExp("^["+L+"]["+L+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$");function F(t,e){const n=[];let r=e.exec(t);for(;r;){const i=[];i.startIndex=e.lastIndex-r[0].length;const s=r.length;for(let t=0;t<s;t++)i.push(r[t]);n.push(i),r=e.exec(t)}return n}const R=function(t){return!(null==U.exec(t))},X=["hasOwnProperty","toString","valueOf","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"],q=["__proto__","constructor","prototype"],B=t=>X.includes(t)?"__"+t:t,Y={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(t,e){return e},attributeValueProcessor:function(t,e){return e},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,entityDecoder:null,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(t,e,n){return t},captureMetaData:!1,maxNestedTags:100,strictReservedNames:!0,jPath:!0,onDangerousProperty:B};function z(t,e){if("string"!=typeof t)return;const n=t.toLowerCase();if(X.some(t=>n===t.toLowerCase()))throw new Error(`[SECURITY] Invalid ${e}: "${t}" is a reserved JavaScript keyword that could cause prototype pollution`);if(q.some(t=>n===t.toLowerCase()))throw new Error(`[SECURITY] Invalid ${e}: "${t}" is a reserved JavaScript keyword that could cause prototype pollution`)}function W(t,e){return"boolean"==typeof t?{enabled:t,maxEntitySize:1e4,maxExpansionDepth:1e4,maxTotalExpansions:1/0,maxExpandedLength:1e5,maxEntityCount:1e3,allowedTags:null,tagFilter:null,appliesTo:"all"}:"object"==typeof t&&null!==t?{enabled:!1!==t.enabled,maxEntitySize:Math.max(1,t.maxEntitySize??1e4),maxExpansionDepth:Math.max(1,t.maxExpansionDepth??1e4),maxTotalExpansions:Math.max(1,t.maxTotalExpansions??1/0),maxExpandedLength:Math.max(1,t.maxExpandedLength??1e5),maxEntityCount:Math.max(1,t.maxEntityCount??1e3),allowedTags:t.allowedTags??null,tagFilter:t.tagFilter??null,appliesTo:t.appliesTo??"all"}:W(!0)}const G=function(t){const e=Object.assign({},Y,t),n=[{value:e.attributeNamePrefix,name:"attributeNamePrefix"},{value:e.attributesGroupName,name:"attributesGroupName"},{value:e.textNodeName,name:"textNodeName"},{value:e.cdataPropName,name:"cdataPropName"},{value:e.commentPropName,name:"commentPropName"}];for(const{value:t,name:e}of n)t&&z(t,e);return null===e.onDangerousProperty&&(e.onDangerousProperty=B),e.processEntities=W(e.processEntities,e.htmlEntities),e.unpairedTagsSet=new Set(e.unpairedTags),e.stopNodes&&Array.isArray(e.stopNodes)&&(e.stopNodes=e.stopNodes.map(t=>"string"==typeof t&&t.startsWith("*.")?".."+t.substring(2):t)),e};let Z;Z="function"!=typeof Symbol?"@@xmlMetadata":Symbol("XML Node Metadata");class J{constructor(t){this.tagname=t,this.child=[],this[":@"]=Object.create(null)}add(t,e){"__proto__"===t&&(t="#__proto__"),this.child.push({[t]:e})}addChild(t,e){"__proto__"===t.tagname&&(t.tagname="#__proto__"),t[":@"]&&Object.keys(t[":@"]).length>0?this.child.push({[t.tagname]:t.child,":@":t[":@"]}):this.child.push({[t.tagname]:t.child}),void 0!==e&&(this.child[this.child.length-1][Z]={startIndex:e})}static getMetaDataSymbol(){return Z}}class K{constructor(t){this.suppressValidationErr=!t,this.options=t}readDocType(t,e){const n=Object.create(null);let r=0;if("O"!==t[e+3]||"C"!==t[e+4]||"T"!==t[e+5]||"Y"!==t[e+6]||"P"!==t[e+7]||"E"!==t[e+8])throw new Error("Invalid Tag instead of DOCTYPE");{e+=9;let i=1,s=!1,a=!1,o="";for(;e<t.length;e++)if("<"!==t[e]||a)if(">"===t[e]){if(a?"-"===t[e-1]&&"-"===t[e-2]&&(a=!1,i--):i--,0===i)break}else"["===t[e]?s=!0:o+=t[e];else{if(s&&H(t,"!ENTITY",e)){let i,s;if(e+=7,[i,s,e]=this.readEntityExp(t,e+1,this.suppressValidationErr),-1===s.indexOf("&")){if(!1!==this.options.enabled&&null!=this.options.maxEntityCount&&r>=this.options.maxEntityCount)throw new Error(`Entity count (${r+1}) exceeds maximum allowed (${this.options.maxEntityCount})`);n[i]=s,r++}}else if(s&&H(t,"!ELEMENT",e)){e+=8;const{index:n}=this.readElementExp(t,e+1);e=n}else if(s&&H(t,"!ATTLIST",e))e+=8;else if(s&&H(t,"!NOTATION",e)){e+=9;const{index:n}=this.readNotationExp(t,e+1,this.suppressValidationErr);e=n}else{if(!H(t,"!--",e))throw new Error("Invalid DOCTYPE");a=!0}i++,o=""}if(0!==i)throw new Error("Unclosed DOCTYPE")}return{entities:n,i:e}}readEntityExp(t,e){const n=e=Q(t,e);for(;e<t.length&&!/\s/.test(t[e])&&'"'!==t[e]&&"'"!==t[e];)e++;let r=t.substring(n,e);if(tt(r),e=Q(t,e),!this.suppressValidationErr){if("SYSTEM"===t.substring(e,e+6).toUpperCase())throw new Error("External entities are not supported");if("%"===t[e])throw new Error("Parameter entities are not supported")}let i="";if([e,i]=this.readIdentifierVal(t,e,"entity"),!1!==this.options.enabled&&null!=this.options.maxEntitySize&&i.length>this.options.maxEntitySize)throw new Error(`Entity "${r}" size (${i.length}) exceeds maximum allowed size (${this.options.maxEntitySize})`);return[r,i,--e]}readNotationExp(t,e){const n=e=Q(t,e);for(;e<t.length&&!/\s/.test(t[e]);)e++;let r=t.substring(n,e);!this.suppressValidationErr&&tt(r),e=Q(t,e);const i=t.substring(e,e+6).toUpperCase();if(!this.suppressValidationErr&&"SYSTEM"!==i&&"PUBLIC"!==i)throw new Error(`Expected SYSTEM or PUBLIC, found "${i}"`);e+=i.length,e=Q(t,e);let s=null,a=null;if("PUBLIC"===i)[e,s]=this.readIdentifierVal(t,e,"publicIdentifier"),'"'!==t[e=Q(t,e)]&&"'"!==t[e]||([e,a]=this.readIdentifierVal(t,e,"systemIdentifier"));else if("SYSTEM"===i&&([e,a]=this.readIdentifierVal(t,e,"systemIdentifier"),!this.suppressValidationErr&&!a))throw new Error("Missing mandatory system identifier for SYSTEM notation");return{notationName:r,publicIdentifier:s,systemIdentifier:a,index:--e}}readIdentifierVal(t,e,n){let r="";const i=t[e];if('"'!==i&&"'"!==i)throw new Error(`Expected quoted string, found "${i}"`);const s=++e;for(;e<t.length&&t[e]!==i;)e++;if(r=t.substring(s,e),t[e]!==i)throw new Error(`Unterminated ${n} value`);return[++e,r]}readElementExp(t,e){const n=e=Q(t,e);for(;e<t.length&&!/\s/.test(t[e]);)e++;let r=t.substring(n,e);if(!this.suppressValidationErr&&!R(r))throw new Error(`Invalid element name: "${r}"`);let i="";if("E"===t[e=Q(t,e)]&&H(t,"MPTY",e))e+=4;else if("A"===t[e]&&H(t,"NY",e))e+=2;else if("("===t[e]){const n=++e;for(;e<t.length&&")"!==t[e];)e++;if(i=t.substring(n,e),")"!==t[e])throw new Error("Unterminated content model")}else if(!this.suppressValidationErr)throw new Error(`Invalid Element Expression, found "${t[e]}"`);return{elementName:r,contentModel:i.trim(),index:e}}readAttlistExp(t,e){let n=e=Q(t,e);for(;e<t.length&&!/\s/.test(t[e]);)e++;let r=t.substring(n,e);for(tt(r),n=e=Q(t,e);e<t.length&&!/\s/.test(t[e]);)e++;let i=t.substring(n,e);if(!tt(i))throw new Error(`Invalid attribute name: "${i}"`);e=Q(t,e);let s="";if("NOTATION"===t.substring(e,e+8).toUpperCase()){if(s="NOTATION","("!==t[e=Q(t,e+=8)])throw new Error(`Expected '(', found "${t[e]}"`);e++;let n=[];for(;e<t.length&&")"!==t[e];){const r=e;for(;e<t.length&&"|"!==t[e]&&")"!==t[e];)e++;let i=t.substring(r,e);if(i=i.trim(),!tt(i))throw new Error(`Invalid notation name: "${i}"`);n.push(i),"|"===t[e]&&(e++,e=Q(t,e))}if(")"!==t[e])throw new Error("Unterminated list of notations");e++,s+=" ("+n.join("|")+")"}else{const n=e;for(;e<t.length&&!/\s/.test(t[e]);)e++;s+=t.substring(n,e);const r=["CDATA","ID","IDREF","IDREFS","ENTITY","ENTITIES","NMTOKEN","NMTOKENS"];if(!this.suppressValidationErr&&!r.includes(s.toUpperCase()))throw new Error(`Invalid attribute type: "${s}"`)}e=Q(t,e);let a="";return"#REQUIRED"===t.substring(e,e+8).toUpperCase()?(a="#REQUIRED",e+=8):"#IMPLIED"===t.substring(e,e+7).toUpperCase()?(a="#IMPLIED",e+=7):[e,a]=this.readIdentifierVal(t,e,"ATTLIST"),{elementName:r,attributeName:i,attributeType:s,defaultValue:a,index:e}}}const Q=(t,e)=>{for(;e<t.length&&/\s/.test(t[e]);)e++;return e};function H(t,e,n){for(let r=0;r<e.length;r++)if(e[r]!==t[n+r+1])return!1;return!0}function tt(t){if(R(t))return t;throw new Error(`Invalid entity name ${t}`)}const et=/^[-+]?0x[a-fA-F0-9]+$/,nt=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,rt={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0,infinity:"original"};const it=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;class st{constructor(t){this._matcher=t}get separator(){return this._matcher.separator}getCurrentTag(){const t=this._matcher.path;return t.length>0?t[t.length-1].tag:void 0}getCurrentNamespace(){const t=this._matcher.path;return t.length>0?t[t.length-1].namespace:void 0}getAttrValue(t){const e=this._matcher.path;if(0!==e.length)return e[e.length-1].values?.[t]}hasAttr(t){const e=this._matcher.path;if(0===e.length)return!1;const n=e[e.length-1];return void 0!==n.values&&t in n.values}getPosition(){const t=this._matcher.path;return 0===t.length?-1:t[t.length-1].position??0}getCounter(){const t=this._matcher.path;return 0===t.length?-1:t[t.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this._matcher.path.length}toString(t,e=!0){return this._matcher.toString(t,e)}toArray(){return this._matcher.path.map(t=>t.tag)}matches(t){return this._matcher.matches(t)}matchesAny(t){return t.matchesAny(this._matcher)}}class at{constructor(t={}){this.separator=t.separator||".",this.path=[],this.siblingStacks=[],this._pathStringCache=null,this._view=new st(this)}push(t,e=null,n=null){this._pathStringCache=null,this.path.length>0&&(this.path[this.path.length-1].values=void 0);const r=this.path.length;this.siblingStacks[r]||(this.siblingStacks[r]=new Map);const i=this.siblingStacks[r],s=n?`${n}:${t}`:t,a=i.get(s)||0;let o=0;for(const t of i.values())o+=t;i.set(s,a+1);const l={tag:t,position:o,counter:a};null!=n&&(l.namespace=n),null!=e&&(l.values=e),this.path.push(l)}pop(){if(0===this.path.length)return;this._pathStringCache=null;const t=this.path.pop();return this.siblingStacks.length>this.path.length+1&&(this.siblingStacks.length=this.path.length+1),t}updateCurrent(t){if(this.path.length>0){const e=this.path[this.path.length-1];null!=t&&(e.values=t)}}getCurrentTag(){return this.path.length>0?this.path[this.path.length-1].tag:void 0}getCurrentNamespace(){return this.path.length>0?this.path[this.path.length-1].namespace:void 0}getAttrValue(t){if(0!==this.path.length)return this.path[this.path.length-1].values?.[t]}hasAttr(t){if(0===this.path.length)return!1;const e=this.path[this.path.length-1];return void 0!==e.values&&t in e.values}getPosition(){return 0===this.path.length?-1:this.path[this.path.length-1].position??0}getCounter(){return 0===this.path.length?-1:this.path[this.path.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this.path.length}toString(t,e=!0){const n=t||this.separator;if(n===this.separator&&!0===e){if(null!==this._pathStringCache)return this._pathStringCache;const t=this.path.map(t=>t.namespace?`${t.namespace}:${t.tag}`:t.tag).join(n);return this._pathStringCache=t,t}return this.path.map(t=>e&&t.namespace?`${t.namespace}:${t.tag}`:t.tag).join(n)}toArray(){return this.path.map(t=>t.tag)}reset(){this._pathStringCache=null,this.path=[],this.siblingStacks=[]}matches(t){const e=t.segments;return 0!==e.length&&(t.hasDeepWildcard()?this._matchWithDeepWildcard(e):this._matchSimple(e))}_matchSimple(t){if(this.path.length!==t.length)return!1;for(let e=0;e<t.length;e++)if(!this._matchSegment(t[e],this.path[e],e===this.path.length-1))return!1;return!0}_matchWithDeepWildcard(t){let e=this.path.length-1,n=t.length-1;for(;n>=0&&e>=0;){const r=t[n];if("deep-wildcard"===r.type){if(n--,n<0)return!0;const r=t[n];let i=!1;for(let t=e;t>=0;t--)if(this._matchSegment(r,this.path[t],t===this.path.length-1)){e=t-1,n--,i=!0;break}if(!i)return!1}else{if(!this._matchSegment(r,this.path[e],e===this.path.length-1))return!1;e--,n--}}return n<0}_matchSegment(t,e,n){if("*"!==t.tag&&t.tag!==e.tag)return!1;if(void 0!==t.namespace&&"*"!==t.namespace&&t.namespace!==e.namespace)return!1;if(void 0!==t.attrName){if(!n)return!1;if(!e.values||!(t.attrName in e.values))return!1;if(void 0!==t.attrValue&&String(e.values[t.attrName])!==String(t.attrValue))return!1}if(void 0!==t.position){if(!n)return!1;const r=e.counter??0;if("first"===t.position&&0!==r)return!1;if("odd"===t.position&&r%2!=1)return!1;if("even"===t.position&&r%2!=0)return!1;if("nth"===t.position&&r!==t.positionValue)return!1}return!0}matchesAny(t){return t.matchesAny(this)}snapshot(){return{path:this.path.map(t=>({...t})),siblingStacks:this.siblingStacks.map(t=>new Map(t))}}restore(t){this._pathStringCache=null,this.path=t.path.map(t=>({...t})),this.siblingStacks=t.siblingStacks.map(t=>new Map(t))}readOnly(){return this._view}}class ot{constructor(t,e={},n){this.pattern=t,this.separator=e.separator||".",this.segments=this._parse(t),this.data=n,this._hasDeepWildcard=this.segments.some(t=>"deep-wildcard"===t.type),this._hasAttributeCondition=this.segments.some(t=>void 0!==t.attrName),this._hasPositionSelector=this.segments.some(t=>void 0!==t.position)}_parse(t){const e=[];let n=0,r="";for(;n<t.length;)t[n]===this.separator?n+1<t.length&&t[n+1]===this.separator?(r.trim()&&(e.push(this._parseSegment(r.trim())),r=""),e.push({type:"deep-wildcard"}),n+=2):(r.trim()&&e.push(this._parseSegment(r.trim())),r="",n++):(r+=t[n],n++);return r.trim()&&e.push(this._parseSegment(r.trim())),e}_parseSegment(t){const e={type:"tag"};let n=null,r=t;const i=t.match(/^([^\[]+)(\[[^\]]*\])(.*)$/);if(i&&(r=i[1]+i[3],i[2])){const t=i[2].slice(1,-1);t&&(n=t)}let s,a,o=r;if(r.includes("::")){const e=r.indexOf("::");if(s=r.substring(0,e).trim(),o=r.substring(e+2).trim(),!s)throw new Error(`Invalid namespace in pattern: ${t}`)}let l=null;if(o.includes(":")){const t=o.lastIndexOf(":"),e=o.substring(0,t).trim(),n=o.substring(t+1).trim();["first","last","odd","even"].includes(n)||/^nth\(\d+\)$/.test(n)?(a=e,l=n):a=o}else a=o;if(!a)throw new Error(`Invalid segment pattern: ${t}`);if(e.tag=a,s&&(e.namespace=s),n)if(n.includes("=")){const t=n.indexOf("=");e.attrName=n.substring(0,t).trim(),e.attrValue=n.substring(t+1).trim()}else e.attrName=n.trim();if(l){const t=l.match(/^nth\((\d+)\)$/);t?(e.position="nth",e.positionValue=parseInt(t[1],10)):e.position=l}return e}get length(){return this.segments.length}hasDeepWildcard(){return this._hasDeepWildcard}hasAttributeCondition(){return this._hasAttributeCondition}hasPositionSelector(){return this._hasPositionSelector}toString(){return this.pattern}}class lt{constructor(){this._byDepthAndTag=new Map,this._wildcardByDepth=new Map,this._deepWildcards=[],this._patterns=new Set,this._sealed=!1}add(t){if(this._sealed)throw new TypeError("ExpressionSet is sealed. Create a new ExpressionSet to add more expressions.");if(this._patterns.has(t.pattern))return this;if(this._patterns.add(t.pattern),t.hasDeepWildcard())return this._deepWildcards.push(t),this;const e=t.length,n=t.segments[t.segments.length-1],r=n?.tag;if(r&&"*"!==r){const n=`${e}:${r}`;this._byDepthAndTag.has(n)||this._byDepthAndTag.set(n,[]),this._byDepthAndTag.get(n).push(t)}else this._wildcardByDepth.has(e)||this._wildcardByDepth.set(e,[]),this._wildcardByDepth.get(e).push(t);return this}addAll(t){for(const e of t)this.add(e);return this}has(t){return this._patterns.has(t.pattern)}get size(){return this._patterns.size}seal(){return this._sealed=!0,this}get isSealed(){return this._sealed}matchesAny(t){return null!==this.findMatch(t)}findMatch(t){const e=t.getDepth(),n=`${e}:${t.getCurrentTag()}`,r=this._byDepthAndTag.get(n);if(r)for(let e=0;e<r.length;e++)if(t.matches(r[e]))return r[e];const i=this._wildcardByDepth.get(e);if(i)for(let e=0;e<i.length;e++)if(t.matches(i[e]))return i[e];for(let e=0;e<this._deepWildcards.length;e++)if(t.matches(this._deepWildcards[e]))return this._deepWildcards[e];return null}}const ht={cent:"¢",pound:"£",curren:"¤",yen:"¥",euro:"€",dollar:"$",euro:"€",fnof:"ƒ",inr:"₹",af:"؋",birr:"ብር",peso:"₱",rub:"₽",won:"₩",yuan:"¥",cedil:"¸"},ut={amp:"&",apos:"'",gt:">",lt:"<",quot:'"'},ct={nbsp:" ",copy:"©",reg:"®",trade:"™",mdash:"—",ndash:"–",hellip:"…",laquo:"«",raquo:"»",lsquo:"‘",rsquo:"’",ldquo:"“",rdquo:"”",bull:"•",para:"¶",sect:"§",deg:"°",frac12:"½",frac14:"¼",frac34:"¾"},dt=new Set("!?\\\\/[]$%{}^&*()<>|+");function pt(t){if("#"===t[0])throw new Error(`[EntityReplacer] Invalid character '#' in entity name: "${t}"`);for(const e of t)if(dt.has(e))throw new Error(`[EntityReplacer] Invalid character '${e}' in entity name: "${t}"`);return t}function ft(...t){const e=Object.create(null);for(const n of t)if(n)for(const t of Object.keys(n)){const r=n[t];if("string"==typeof r)e[t]=r;else if(r&&"object"==typeof r&&void 0!==r.val){const n=r.val;"string"==typeof n&&(e[t]=n)}}return e}const gt="external",mt="base",vt="all",xt=Object.freeze({allow:0,leave:1,remove:2,throw:3}),bt=new Set([9,10,13]);class Et{constructor(t={}){var e;this._limit=t.limit||{},this._maxTotalExpansions=this._limit.maxTotalExpansions||0,this._maxExpandedLength=this._limit.maxExpandedLength||0,this._postCheck="function"==typeof t.postCheck?t.postCheck:t=>t,this._limitTiers=(e=this._limit.applyLimitsTo??gt)&&e!==gt?e===vt?new Set([vt]):e===mt?new Set([mt]):Array.isArray(e)?new Set(e):new Set([gt]):new Set([gt]),this._numericAllowed=t.numericAllowed??!0,this._baseMap=ft(ut,t.namedEntities||null),this._externalMap=Object.create(null),this._inputMap=Object.create(null),this._totalExpansions=0,this._expandedLength=0,this._removeSet=new Set(t.remove&&Array.isArray(t.remove)?t.remove:[]),this._leaveSet=new Set(t.leave&&Array.isArray(t.leave)?t.leave:[]);const n=function(t){if(!t)return{xmlVersion:1,onLevel:xt.allow,nullLevel:xt.remove};const e=1.1===t.xmlVersion?1.1:1,n=xt[t.onNCR]??xt.allow,r=xt[t.nullNCR]??xt.remove;return{xmlVersion:e,onLevel:n,nullLevel:Math.max(r,xt.remove)}}(t.ncr);this._ncrXmlVersion=n.xmlVersion,this._ncrOnLevel=n.onLevel,this._ncrNullLevel=n.nullLevel}setExternalEntities(t){if(t)for(const e of Object.keys(t))pt(e);this._externalMap=ft(t)}addExternalEntity(t,e){pt(t),"string"==typeof e&&-1===e.indexOf("&")&&(this._externalMap[t]=e)}addInputEntities(t){this._totalExpansions=0,this._expandedLength=0,this._inputMap=ft(t)}reset(){return this._inputMap=Object.create(null),this._totalExpansions=0,this._expandedLength=0,this}setXmlVersion(t){this._ncrXmlVersion=1.1===t?1.1:1}decode(t){if("string"!=typeof t||0===t.length)return t;const e=t,n=[],r=t.length;let i=0,s=0;const a=this._maxTotalExpansions>0,o=this._maxExpandedLength>0,l=a||o;for(;s<r;){if(38!==t.charCodeAt(s)){s++;continue}let e=s+1;for(;e<r&&59!==t.charCodeAt(e)&&e-s<=32;)e++;if(e>=r||59!==t.charCodeAt(e)){s++;continue}const h=t.slice(s+1,e);if(0===h.length){s++;continue}let u,c;if(this._removeSet.has(h))u="",void 0===c&&(c=gt);else{if(this._leaveSet.has(h)){s++;continue}if(35===h.charCodeAt(0)){const t=this._resolveNCR(h);if(void 0===t){s++;continue}u=t,c=mt}else{const t=this._resolveName(h);u=t?.value,c=t?.tier}}if(void 0!==u){if(s>i&&n.push(t.slice(i,s)),n.push(u),i=e+1,s=i,l&&this._tierCounts(c)){if(a&&(this._totalExpansions++,this._totalExpansions>this._maxTotalExpansions))throw new Error(`[EntityReplacer] Entity expansion count limit exceeded: ${this._totalExpansions} > ${this._maxTotalExpansions}`);if(o){const t=u.length-(h.length+2);if(t>0&&(this._expandedLength+=t,this._expandedLength>this._maxExpandedLength))throw new Error(`[EntityReplacer] Expanded content length limit exceeded: ${this._expandedLength} > ${this._maxExpandedLength}`)}}}else s++}i<r&&n.push(t.slice(i));const h=0===n.length?t:n.join("");return this._postCheck(h,e)}_tierCounts(t){return!!this._limitTiers.has(vt)||this._limitTiers.has(t)}_resolveName(t){return t in this._inputMap?{value:this._inputMap[t],tier:gt}:t in this._externalMap?{value:this._externalMap[t],tier:gt}:t in this._baseMap?{value:this._baseMap[t],tier:mt}:void 0}_classifyNCR(t){return 0===t?this._ncrNullLevel:t>=55296&&t<=57343||1===this._ncrXmlVersion&&t>=1&&t<=31&&!bt.has(t)?xt.remove:-1}_applyNCRAction(t,e,n){switch(t){case xt.allow:return String.fromCodePoint(n);case xt.remove:return"";case xt.leave:return;case xt.throw:throw new Error(`[EntityDecoder] Prohibited numeric character reference &${e}; (U+${n.toString(16).toUpperCase().padStart(4,"0")})`);default:return String.fromCodePoint(n)}}_resolveNCR(t){const e=t.charCodeAt(1);let n;if(n=120===e||88===e?parseInt(t.slice(2),16):parseInt(t.slice(1),10),Number.isNaN(n)||n<0||n>1114111)return;const r=this._classifyNCR(n);if(!this._numericAllowed&&r<xt.remove)return;const i=-1===r?this._ncrOnLevel:Math.max(this._ncrOnLevel,r);return this._applyNCRAction(i,t,n)}}function yt(t,e){if(!t)return{};const n=e.attributesGroupName?t[e.attributesGroupName]:t;if(!n)return{};const r={};for(const t in n)t.startsWith(e.attributeNamePrefix)?r[t.substring(e.attributeNamePrefix.length)]=n[t]:r[t]=n[t];return r}function wt(t){if(!t||"string"!=typeof t)return;const e=t.indexOf(":");if(-1!==e&&e>0){const n=t.substring(0,e);if("xmlns"!==n)return n}}class Nt{constructor(t){var e;this.options=t,this.currentNode=null,this.tagsNodeStack=[],this.parseXml=Ct,this.parseTextData=_t,this.resolveNameSpace=St,this.buildAttributesMap=It,this.isItStopNode=Mt,this.replaceEntitiesValue=Ot,this.readStopNodeData=$t,this.saveTextToParentTag=Pt,this.addChild=At,this.ignoreAttributesFn="function"==typeof(e=this.options.ignoreAttributes)?e:Array.isArray(e)?t=>{for(const n of e){if("string"==typeof n&&t===n)return!0;if(n instanceof RegExp&&n.test(t))return!0}}:()=>!1,this.entityExpansionCount=0,this.currentExpandedLength=0;let n={...ut};this.options.entityDecoder?this.entityDecoder=this.options.entityDecoder:("object"==typeof this.options.htmlEntities?n=this.options.htmlEntities:!0===this.options.htmlEntities&&(n={...ct,...ht}),this.entityDecoder=new Et({namedEntities:n,numericAllowed:this.options.htmlEntities,limit:{maxTotalExpansions:this.options.processEntities.maxTotalExpansions,maxExpandedLength:this.options.processEntities.maxExpandedLength,applyLimitsTo:this.options.processEntities.appliesTo}})),this.matcher=new at,this.readonlyMatcher=this.matcher.readOnly(),this.isCurrentNodeStopNode=!1,this.stopNodeExpressionsSet=new lt;const r=this.options.stopNodes;if(r&&r.length>0){for(let t=0;t<r.length;t++){const e=r[t];"string"==typeof e?this.stopNodeExpressionsSet.add(new ot(e)):e instanceof ot&&this.stopNodeExpressionsSet.add(e)}this.stopNodeExpressionsSet.seal()}}}function _t(t,e,n,r,i,s,a){const o=this.options;if(void 0!==t&&(o.trimValues&&!r&&(t=t.trim()),t.length>0)){a||(t=this.replaceEntitiesValue(t,e,n));const r=o.jPath?n.toString():n,l=o.tagValueProcessor(e,t,r,i,s);return null==l?t:typeof l!=typeof t||l!==t?l:o.trimValues||t.trim()===t?jt(t,o.parseTagValue,o.numberParseOptions):t}}function St(t){if(this.options.removeNSPrefix){const e=t.split(":"),n="/"===t.charAt(0)?"/":"";if("xmlns"===e[0])return"";2===e.length&&(t=n+e[1])}return t}const Tt=new RegExp("([^\\s=]+)\\s*(=\\s*(['\"])([\\s\\S]*?)\\3)?","gm");function It(t,e,n,r=!1){const i=this.options;if(!0===r||!0!==i.ignoreAttributes&&"string"==typeof t){const r=F(t,Tt),s=r.length,a={},o=new Array(s);let l=!1;const h={};for(let t=0;t<s;t++){const e=this.resolveNameSpace(r[t][1]),s=r[t][4];if(e.length&&void 0!==s){let r=s;i.trimValues&&(r=r.trim()),r=this.replaceEntitiesValue(r,n,this.readonlyMatcher),o[t]=r,h[e]=r,l=!0}}l&&"object"==typeof e&&e.updateCurrent&&e.updateCurrent(h);const u=i.jPath?e.toString():this.readonlyMatcher;let c=!1;for(let t=0;t<s;t++){const e=this.resolveNameSpace(r[t][1]);if(this.ignoreAttributesFn(e,u))continue;let n=i.attributeNamePrefix+e;if(e.length)if(i.transformAttributeName&&(n=i.transformAttributeName(n)),n=Ut(n,i),void 0!==r[t][4]){const r=o[t],s=i.attributeValueProcessor(e,r,u);a[n]=null==s?r:typeof s!=typeof r||s!==r?s:jt(r,i.parseAttributeValue,i.numberParseOptions),c=!0}else i.allowBooleanAttributes&&(a[n]=!0,c=!0)}if(!c)return;if(i.attributesGroupName){const t={};return t[i.attributesGroupName]=a,t}return a}}const Ct=function(t){t=t.replace(/\r\n?/g,"\n");const e=new J("!xml");let n=e,r="";this.matcher.reset(),this.entityDecoder.reset(),this.entityExpansionCount=0,this.currentExpandedLength=0;const i=this.options,s=new K(i.processEntities),a=t.length;for(let o=0;o<a;o++)if("<"===t[o]){const l=t.charCodeAt(o+1);if(47===l){const e=Dt(t,">",o,"Closing Tag is not closed.");let s=t.substring(o+2,e).trim();if(i.removeNSPrefix){const t=s.indexOf(":");-1!==t&&(s=s.substr(t+1))}s=Lt(i.transformTagName,s,"",i).tagName,n&&(r=this.saveTextToParentTag(r,n,this.readonlyMatcher));const a=this.matcher.getCurrentTag();if(s&&i.unpairedTagsSet.has(s))throw new Error(`Unpaired tag can not be used as closing tag: </${s}>`);a&&i.unpairedTagsSet.has(a)&&(this.matcher.pop(),this.tagsNodeStack.pop()),this.matcher.pop(),this.isCurrentNodeStopNode=!1,n=this.tagsNodeStack.pop(),r="",o=e}else if(63===l){let e=Vt(t,o,!1,"?>");if(!e)throw new Error("Pi Tag is not closed.");r=this.saveTextToParentTag(r,n,this.readonlyMatcher);const s=this.buildAttributesMap(e.tagExp,this.matcher,e.tagName,!0);if(s){const t=s[this.options.attributeNamePrefix+"version"];this.entityDecoder.setXmlVersion(Number(t)||1)}if(i.ignoreDeclaration&&"?xml"===e.tagName||i.ignorePiTags);else{const t=new J(e.tagName);t.add(i.textNodeName,""),e.tagName!==e.tagExp&&e.attrExpPresent&&!0!==i.ignoreAttributes&&(t[":@"]=s),this.addChild(n,t,this.readonlyMatcher,o)}o=e.closeIndex+1}else if(33===l&&45===t.charCodeAt(o+2)&&45===t.charCodeAt(o+3)){const e=Dt(t,"--\x3e",o+4,"Comment is not closed.");if(i.commentPropName){const s=t.substring(o+4,e-2);r=this.saveTextToParentTag(r,n,this.readonlyMatcher),n.add(i.commentPropName,[{[i.textNodeName]:s}])}o=e}else if(33===l&&68===t.charCodeAt(o+2)){const e=s.readDocType(t,o);this.entityDecoder.addInputEntities(e.entities),o=e.i}else if(33===l&&91===t.charCodeAt(o+2)){const e=Dt(t,"]]>",o,"CDATA is not closed.")-2,s=t.substring(o+9,e);r=this.saveTextToParentTag(r,n,this.readonlyMatcher);let a=this.parseTextData(s,n.tagname,this.readonlyMatcher,!0,!1,!0,!0);null==a&&(a=""),i.cdataPropName?n.add(i.cdataPropName,[{[i.textNodeName]:s}]):n.add(i.textNodeName,a),o=e+2}else{let s=Vt(t,o,i.removeNSPrefix);if(!s){const e=t.substring(Math.max(0,o-50),Math.min(a,o+50));throw new Error(`readTagExp returned undefined at position ${o}. Context: "${e}"`)}let l=s.tagName;const h=s.rawTagName;let u=s.tagExp,c=s.attrExpPresent,d=s.closeIndex;if(({tagName:l,tagExp:u}=Lt(i.transformTagName,l,u,i)),i.strictReservedNames&&(l===i.commentPropName||l===i.cdataPropName||l===i.textNodeName||l===i.attributesGroupName))throw new Error(`Invalid tag name: ${l}`);n&&r&&"!xml"!==n.tagname&&(r=this.saveTextToParentTag(r,n,this.readonlyMatcher,!1));const p=n;p&&i.unpairedTagsSet.has(p.tagname)&&(n=this.tagsNodeStack.pop(),this.matcher.pop());let f=!1;u.length>0&&u.lastIndexOf("/")===u.length-1&&(f=!0,"/"===l[l.length-1]?(l=l.substr(0,l.length-1),u=l):u=u.substr(0,u.length-1),c=l!==u);let g,m=null,v={};g=wt(h),l!==e.tagname&&this.matcher.push(l,{},g),l!==u&&c&&(m=this.buildAttributesMap(u,this.matcher,l),m&&(v=yt(m,i))),l!==e.tagname&&(this.isCurrentNodeStopNode=this.isItStopNode());const x=o;if(this.isCurrentNodeStopNode){let e="";if(f)o=s.closeIndex;else if(i.unpairedTagsSet.has(l))o=s.closeIndex;else{const n=this.readStopNodeData(t,h,d+1);if(!n)throw new Error(`Unexpected end of ${h}`);o=n.i,e=n.tagContent}const r=new J(l);m&&(r[":@"]=m),r.add(i.textNodeName,e),this.matcher.pop(),this.isCurrentNodeStopNode=!1,this.addChild(n,r,this.readonlyMatcher,x)}else{if(f){({tagName:l,tagExp:u}=Lt(i.transformTagName,l,u,i));const t=new J(l);m&&(t[":@"]=m),this.addChild(n,t,this.readonlyMatcher,x),this.matcher.pop(),this.isCurrentNodeStopNode=!1}else{if(i.unpairedTagsSet.has(l)){const t=new J(l);m&&(t[":@"]=m),this.addChild(n,t,this.readonlyMatcher,x),this.matcher.pop(),this.isCurrentNodeStopNode=!1,o=s.closeIndex;continue}{const t=new J(l);if(this.tagsNodeStack.length>i.maxNestedTags)throw new Error("Maximum nested tags exceeded");this.tagsNodeStack.push(n),m&&(t[":@"]=m),this.addChild(n,t,this.readonlyMatcher,x),n=t}}r="",o=d}}}else r+=t[o];return e.child};function At(t,e,n,r){this.options.captureMetaData||(r=void 0);const i=this.options.jPath?n.toString():n,s=this.options.updateTag(e.tagname,i,e[":@"]);!1===s||("string"==typeof s?(e.tagname=s,t.addChild(e,r)):t.addChild(e,r))}function Ot(t,e,n){const r=this.options.processEntities;if(!r||!r.enabled)return t;if(r.allowedTags){const i=this.options.jPath?n.toString():n;if(!(Array.isArray(r.allowedTags)?r.allowedTags.includes(e):r.allowedTags(e,i)))return t}if(r.tagFilter){const i=this.options.jPath?n.toString():n;if(!r.tagFilter(e,i))return t}return this.entityDecoder.decode(t)}function Pt(t,e,n,r){return t&&(void 0===r&&(r=0===e.child.length),void 0!==(t=this.parseTextData(t,e.tagname,n,!1,!!e[":@"]&&0!==Object.keys(e[":@"]).length,r))&&""!==t&&e.add(this.options.textNodeName,t),t=""),t}function Mt(){return 0!==this.stopNodeExpressionsSet.size&&this.matcher.matchesAny(this.stopNodeExpressionsSet)}function Dt(t,e,n,r){const i=t.indexOf(e,n);if(-1===i)throw new Error(r);return i+e.length-1}function kt(t,e,n,r){const i=t.indexOf(e,n);if(-1===i)throw new Error(r);return i}function Vt(t,e,n,r=">"){const i=function(t,e,n=">"){let r=0;const i=[],s=t.length,a=n.charCodeAt(0),o=n.length>1?n.charCodeAt(1):-1;for(let n=e;n<s;n++){const e=t.charCodeAt(n);if(r)e===r&&(r=0);else if(34===e||39===e)r=e;else if(e===a){if(-1===o)return{data:String.fromCharCode(...i),index:n};if(t.charCodeAt(n+1)===o)return{data:String.fromCharCode(...i),index:n}}else if(9===e){i.push(32);continue}i.push(e)}}(t,e+1,r);if(!i)return;let s=i.data;const a=i.index,o=s.search(/\s/);let l=s,h=!0;-1!==o&&(l=s.substring(0,o),s=s.substring(o+1).trimStart());const u=l;if(n){const t=l.indexOf(":");-1!==t&&(l=l.substr(t+1),h=l!==i.data.substr(t+1))}return{tagName:l,tagExp:s,closeIndex:a,attrExpPresent:h,rawTagName:u}}function $t(t,e,n){const r=n;let i=1;const s=t.length;for(;n<s;n++)if("<"===t[n]){const s=t.charCodeAt(n+1);if(47===s){const s=kt(t,">",n,`${e} is not closed`);if(t.substring(n+2,s).trim()===e&&(i--,0===i))return{tagContent:t.substring(r,n),i:s};n=s}else if(63===s)n=Dt(t,"?>",n+1,"StopNode is not closed.");else if(33===s&&45===t.charCodeAt(n+2)&&45===t.charCodeAt(n+3))n=Dt(t,"--\x3e",n+3,"StopNode is not closed.");else if(33===s&&91===t.charCodeAt(n+2))n=Dt(t,"]]>",n,"StopNode is not closed.")-2;else{const r=Vt(t,n,">");r&&((r&&r.tagName)===e&&"/"!==r.tagExp[r.tagExp.length-1]&&i++,n=r.closeIndex)}}}function jt(t,e,n){if(e&&"string"==typeof t){const e=t.trim();return"true"===e||"false"!==e&&function(t,e={}){if(e=Object.assign({},rt,e),!t||"string"!=typeof t)return t;let n=t.trim();if(0===n.length)return t;if(void 0!==e.skipLike&&e.skipLike.test(n))return t;if("0"===n)return 0;if(e.hex&&et.test(n))return function(t){if(parseInt)return parseInt(t,16);if(Number.parseInt)return Number.parseInt(t,16);if(window&&window.parseInt)return window.parseInt(t,16);throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}(n);if(isFinite(n)){if(n.includes("e")||n.includes("E"))return function(t,e,n){if(!n.eNotation)return t;const r=e.match(it);if(r){let i=r[1]||"";const s=-1===r[3].indexOf("e")?"E":"e",a=r[2],o=i?t[a.length+1]===s:t[a.length]===s;return a.length>1&&o?t:(1!==a.length||!r[3].startsWith(`.${s}`)&&r[3][0]!==s)&&a.length>0?n.leadingZeros&&!o?(e=(r[1]||"")+r[3],Number(e)):t:Number(e)}return t}(t,n,e);{const i=nt.exec(n);if(i){const s=i[1]||"",a=i[2];let o=(r=i[3])&&-1!==r.indexOf(".")?("."===(r=r.replace(/0+$/,""))?r="0":"."===r[0]?r="0"+r:"."===r[r.length-1]&&(r=r.substring(0,r.length-1)),r):r;const l=s?"."===t[a.length+1]:"."===t[a.length];if(!e.leadingZeros&&(a.length>1||1===a.length&&!l))return t;{const r=Number(n),i=String(r);if(0===r)return r;if(-1!==i.search(/[eE]/))return e.eNotation?r:t;if(-1!==n.indexOf("."))return"0"===i||i===o||i===`${s}${o}`?r:t;let l=a?o:n;return a?l===i||s+l===i?r:t:l===i||l===s+i?r:t}}return t}}var r;return function(t,e,n){const r=e===1/0;switch(n.infinity.toLowerCase()){case"null":return null;case"infinity":return e;case"string":return r?"Infinity":"-Infinity";default:return t}}(t,Number(n),e)}(t,n)}return void 0!==t?t:""}function Lt(t,e,n,r){if(t){const r=t(e);n===e&&(n=r),e=r}return{tagName:e=Ut(e,r),tagExp:n}}function Ut(t,e){if(q.includes(t))throw new Error(`[SECURITY] Invalid name: "${t}" is a reserved JavaScript keyword that could cause prototype pollution`);return X.includes(t)?e.onDangerousProperty(t):t}const Ft=J.getMetaDataSymbol();function Rt(t,e){if(!t||"object"!=typeof t)return{};if(!e)return t;const n={};for(const r in t)r.startsWith(e)?n[r.substring(e.length)]=t[r]:n[r]=t[r];return n}function Xt(t,e,n,r){return qt(t,e,n,r)}function qt(t,e,n,r){let i;const s={};for(let a=0;a<t.length;a++){const o=t[a],l=Bt(o);if(void 0!==l&&l!==e.textNodeName){const t=Rt(o[":@"]||{},e.attributeNamePrefix);n.push(l,t)}if(l===e.textNodeName)void 0===i?i=o[l]:i+=""+o[l];else{if(void 0===l)continue;if(o[l]){let t=qt(o[l],e,n,r);const i=zt(t,e);if(o[":@"]?Yt(t,o[":@"],r,e):1!==Object.keys(t).length||void 0===t[e.textNodeName]||e.alwaysCreateTextNode?0===Object.keys(t).length&&(e.alwaysCreateTextNode?t[e.textNodeName]="":t=""):t=t[e.textNodeName],void 0!==o[Ft]&&"object"==typeof t&&null!==t&&(t[Ft]=o[Ft]),void 0!==s[l]&&Object.prototype.hasOwnProperty.call(s,l))Array.isArray(s[l])||(s[l]=[s[l]]),s[l].push(t);else{const n=e.jPath?r.toString():r;e.isArray(l,n,i)?s[l]=[t]:s[l]=t}void 0!==l&&l!==e.textNodeName&&n.pop()}}}return"string"==typeof i?i.length>0&&(s[e.textNodeName]=i):void 0!==i&&(s[e.textNodeName]=i),s}function Bt(t){const e=Object.keys(t);for(let t=0;t<e.length;t++){const n=e[t];if(":@"!==n)return n}}function Yt(t,e,n,r){if(e){const i=Object.keys(e),s=i.length;for(let a=0;a<s;a++){const s=i[a],o=s.startsWith(r.attributeNamePrefix)?s.substring(r.attributeNamePrefix.length):s,l=r.jPath?n.toString()+"."+o:n;r.isArray(s,l,!0,!0)?t[s]=[e[s]]:t[s]=e[s]}}}function zt(t,e){const{textNodeName:n}=e,r=Object.keys(t).length;return 0===r||!(1!==r||!t[n]&&"boolean"!=typeof t[n]&&0!==t[n])}const Wt={allowBooleanAttributes:!1,unpairedTags:[]};function Gt(t,e){e=Object.assign({},Wt,e);const n=[];let r=!1,i=!1;"\ufeff"===t[0]&&(t=t.substr(1));for(let s=0;s<t.length;s++)if("<"===t[s]&&"?"===t[s+1]){if(s+=2,s=Jt(t,s),s.err)return s}else{if("<"!==t[s]){if(Zt(t[s]))continue;return ie("InvalidChar","char '"+t[s]+"' is not expected.",oe(t,s))}{let a=s;if(s++,"!"===t[s]){s=Kt(t,s);continue}{let o=!1;"/"===t[s]&&(o=!0,s++);let l="";for(;s<t.length&&">"!==t[s]&&" "!==t[s]&&"\t"!==t[s]&&"\n"!==t[s]&&"\r"!==t[s];s++)l+=t[s];if(l=l.trim(),"/"===l[l.length-1]&&(l=l.substring(0,l.length-1),s--),!ae(l)){let e;return e=0===l.trim().length?"Invalid space after '<'.":"Tag '"+l+"' is an invalid name.",ie("InvalidTag",e,oe(t,s))}const h=te(t,s);if(!1===h)return ie("InvalidAttr","Attributes for '"+l+"' have open quote.",oe(t,s));let u=h.value;if(s=h.index,"/"===u[u.length-1]){const n=s-u.length;u=u.substring(0,u.length-1);const i=ne(u,e);if(!0!==i)return ie(i.err.code,i.err.msg,oe(t,n+i.err.line));r=!0}else if(o){if(!h.tagClosed)return ie("InvalidTag","Closing tag '"+l+"' doesn't have proper closing.",oe(t,s));if(u.trim().length>0)return ie("InvalidTag","Closing tag '"+l+"' can't have attributes or invalid starting.",oe(t,a));if(0===n.length)return ie("InvalidTag","Closing tag '"+l+"' has not been opened.",oe(t,a));{const e=n.pop();if(l!==e.tagName){let n=oe(t,e.tagStartPos);return ie("InvalidTag","Expected closing tag '"+e.tagName+"' (opened in line "+n.line+", col "+n.col+") instead of closing tag '"+l+"'.",oe(t,a))}0==n.length&&(i=!0)}}else{const o=ne(u,e);if(!0!==o)return ie(o.err.code,o.err.msg,oe(t,s-u.length+o.err.line));if(!0===i)return ie("InvalidXml","Multiple possible root nodes found.",oe(t,s));-1!==e.unpairedTags.indexOf(l)||n.push({tagName:l,tagStartPos:a}),r=!0}for(s++;s<t.length;s++)if("<"===t[s]){if("!"===t[s+1]){s++,s=Kt(t,s);continue}if("?"!==t[s+1])break;if(s=Jt(t,++s),s.err)return s}else if("&"===t[s]){const e=re(t,s);if(-1==e)return ie("InvalidChar","char '&' is not expected.",oe(t,s));s=e}else if(!0===i&&!Zt(t[s]))return ie("InvalidXml","Extra text at the end",oe(t,s));"<"===t[s]&&s--}}}return r?1==n.length?ie("InvalidTag","Unclosed tag '"+n[0].tagName+"'.",oe(t,n[0].tagStartPos)):!(n.length>0)||ie("InvalidXml","Invalid '"+JSON.stringify(n.map(t=>t.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):ie("InvalidXml","Start tag expected.",1)}function Zt(t){return" "===t||"\t"===t||"\n"===t||"\r"===t}function Jt(t,e){const n=e;for(;e<t.length;e++)if("?"==t[e]||" "==t[e]){const r=t.substr(n,e-n);if(e>5&&"xml"===r)return ie("InvalidXml","XML declaration allowed only at the start of the document.",oe(t,e));if("?"==t[e]&&">"==t[e+1]){e++;break}continue}return e}function Kt(t,e){if(t.length>e+5&&"-"===t[e+1]&&"-"===t[e+2]){for(e+=3;e<t.length;e++)if("-"===t[e]&&"-"===t[e+1]&&">"===t[e+2]){e+=2;break}}else if(t.length>e+8&&"D"===t[e+1]&&"O"===t[e+2]&&"C"===t[e+3]&&"T"===t[e+4]&&"Y"===t[e+5]&&"P"===t[e+6]&&"E"===t[e+7]){let n=1;for(e+=8;e<t.length;e++)if("<"===t[e])n++;else if(">"===t[e]&&(n--,0===n))break}else if(t.length>e+9&&"["===t[e+1]&&"C"===t[e+2]&&"D"===t[e+3]&&"A"===t[e+4]&&"T"===t[e+5]&&"A"===t[e+6]&&"["===t[e+7])for(e+=8;e<t.length;e++)if("]"===t[e]&&"]"===t[e+1]&&">"===t[e+2]){e+=2;break}return e}const Qt='"',Ht="'";function te(t,e){let n="",r="",i=!1;for(;e<t.length;e++){if(t[e]===Qt||t[e]===Ht)""===r?r=t[e]:r!==t[e]||(r="");else if(">"===t[e]&&""===r){i=!0;break}n+=t[e]}return""===r&&{value:n,index:e,tagClosed:i}}const ee=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function ne(t,e){const n=F(t,ee),r={};for(let t=0;t<n.length;t++){if(0===n[t][1].length)return ie("InvalidAttr","Attribute '"+n[t][2]+"' has no space in starting.",le(n[t]));if(void 0!==n[t][3]&&void 0===n[t][4])return ie("InvalidAttr","Attribute '"+n[t][2]+"' is without value.",le(n[t]));if(void 0===n[t][3]&&!e.allowBooleanAttributes)return ie("InvalidAttr","boolean attribute '"+n[t][2]+"' is not allowed.",le(n[t]));const i=n[t][2];if(!se(i))return ie("InvalidAttr","Attribute '"+i+"' is an invalid name.",le(n[t]));if(Object.prototype.hasOwnProperty.call(r,i))return ie("InvalidAttr","Attribute '"+i+"' is repeated.",le(n[t]));r[i]=1}return!0}function re(t,e){if(";"===t[++e])return-1;if("#"===t[e])return function(t,e){let n=/\d/;for("x"===t[e]&&(e++,n=/[\da-fA-F]/);e<t.length;e++){if(";"===t[e])return e;if(!t[e].match(n))break}return-1}(t,++e);let n=0;for(;e<t.length;e++,n++)if(!(t[e].match(/\w/)&&n<20)){if(";"===t[e])break;return-1}return e}function ie(t,e,n){return{err:{code:t,msg:e,line:n.line||n,col:n.col}}}function se(t){return R(t)}function ae(t){return R(t)}function oe(t,e){const n=t.substring(0,e).split(/\r?\n/);return{line:n.length,col:n[n.length-1].length+1}}function le(t){return t.startIndex+t[1].length}class he{constructor(t){this.externalEntities={},this.options=G(t)}parse(t,e){if("string"!=typeof t&&t.toString)t=t.toString();else if("string"!=typeof t)throw new Error("XML data is accepted in String or Bytes[] form.");if(e){!0===e&&(e={});const n=Gt(t,e);if(!0!==n)throw Error(`${n.err.msg}:${n.err.line}:${n.err.col}`)}const n=new Nt(this.options);n.entityDecoder.setExternalEntities(this.externalEntities);const r=n.parseXml(t);return this.options.preserveOrder||void 0===r?r:Xt(r,this.options,n.matcher,n.readonlyMatcher)}addEntity(t,e){if(-1!==e.indexOf("&"))throw new Error("Entity value can't have '&'");if(-1!==t.indexOf("&")||-1!==t.indexOf(";"))throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '
'");if("&"===e)throw new Error("An entity with value '&' is not permitted");this.externalEntities[t]=e}static getMetaDataSymbol(){return J.getMetaDataSymbol()}}const ue={validate:Gt},ce={minLength:(t,e)=>e.length>=t,maxLength:(t,e)=>e.length<=t,length:(t,e)=>e.length===t,pattern:(t,e,n="")=>new RegExp(t,n).test(e),fixed:(t,e)=>t===e,in:(t,e)=>t.split(",").indexOf(e)>-1},de={min:(t,e)=>Number(e)>=t,max:(t,e)=>Number(e)<=t},pe={minOccurs:(t,e)=>e>=t,maxOccurs:(t,e)=>e<=t},fe=(t,e)=>Date.parse(e)>=Date.parse(t),ge=(t,e)=>Date.parse(e)<=Date.parse(t),me=["positiveInteger","integer","positiveDecimal","decimal","number"];class ve{constructor(t,e,n){this.options=t,this.failures=[],this.validators=e,this._globalUnique=new Map,this._siblingOrder=n||new Map}traverse(t,e,n,r){if(Array.isArray(t)){if(void 0!==n&&void 0!==n["@rules"]&&void 0!==n["@rules"].repeatable)return this.checkOccurences(n["@rules"],t.length,r),void t.forEach((i,s)=>{const a=r+"["+s+"]";Object.keys(n).length>1?this.callForCommonProperties(t[s],n,a):this.traverse(t[s],e,n,a)});this.failures.push({code:"unexpected sequence",path:r.substr(1)})}else"object"==typeof t?this.callForCommonProperties(t,n,r):("object"==typeof n&&n["@rules"]?this.checkDataAndType(t,e,n,r):this.isMapType(n)&&this.validateMandatoryFields(n,r),this.applyCustomValidators(t,n,r))}applyCustomValidators(t,e,n){if(e["@rules"]&&e["@rules"].checkBy&&"function"==typeof this.validators[e["@rules"].checkBy]){let r=this.validators[e["@rules"].checkBy](t,n.substr(1));"object"==typeof r&&this.failures.push(r)}}callForCommonProperties(t,e,n){const r=function(t,e){const n={data:[],rules:[],common:[]};for(let r=0;r<t.length;r++)-1===e.indexOf(t[r])?n.data.push(t[r]):n.common.push(t[r]);for(let r=0;r<e.length;r++)-1===t.indexOf(e[r])&&"@"!==e[r]&&n.rules.push(e[r]);return n}(Object.keys(t),Object.keys(e));this.checkUnknownSiblings(r,n),this.checkMissingSiblings(r,e,n),this.applyCustomValidators(t,e,n);const i=this._buildSiblingValues(t,e,r.common);r.common.forEach(r=>{const i=n+"."+r;this.traverse(t[r],r,e[r],i)}),this._checkOrderingConstraints(t,e,r.common,n),this._checkUniquenessConstraints(t,e,r.common,n,i),this._checkRelationalConstraints(t,e,r.common,n)}_checkOrderingConstraints(t,e,n,r){const i=r.substr(1),s=this._siblingOrder.get(i);s&&n.forEach(n=>{const i=e[n];if(!i||!i["@rules"])return;const a=i["@rules"],o=s.indexOf(n);if(-1!==o){if(a.after){const e=a.after;if(void 0===t[e])return;const i=s.indexOf(e);if(-1===i)return;o<=i&&this.failures.push({code:"after",path:(r+"."+n).substr(1),actual:n,expected:e})}if(a.before){const e=a.before;if(void 0===t[e])return;const i=s.indexOf(e);if(-1===i)return;o>=i&&this.failures.push({code:"before",path:(r+"."+n).substr(1),actual:n,expected:e})}}})}_checkRelationalConstraints(t,e,n,r){const i=["sameAs","notSameAs","lessThan","moreThan"];n.forEach(n=>{const s=e[n];if(!s||!s["@rules"])return;const a=s["@rules"];if(!i.some(t=>void 0!==a[t]))return;const o=t[n];if(null==o)return;if("object"==typeof o)return;const l=a.type||"string";i.forEach(e=>{if(void 0===a[e])return;const i=a[e],s=t[i];if(null==s)return;if("object"==typeof s)return;const h=this._relationalCompare(String(o),String(s),l);if(null===h)return;let u=!1;"sameAs"===e&&0!==h&&(u=!0),"notSameAs"===e&&0===h&&(u=!0),"lessThan"===e&&h>=0&&(u=!0),"moreThan"===e&&h<=0&&(u=!0),u&&this.failures.push({code:e,path:(r+"."+n).substr(1),actual:String(o),expected:i})})})}_relationalCompare(t,e,n){if("date"===n){const n=Date.parse(t),r=Date.parse(e);return isNaN(n)||isNaN(r)?null:n-r}if(-1!==me.indexOf(n)){const n=Number(t),r=Number(e);return isNaN(n)||isNaN(r)?null:n-r}return t<e?-1:t>e?1:0}_buildSiblingValues(t,e,n){const r=new Map;return n.forEach(e=>{const n=t[e];Array.isArray(n)?r.set(e,n.map(String)):null!=n&&"object"!=typeof n&&r.set(e,[String(n)])}),r}_checkUniquenessConstraints(t,e,n,r,i){n.forEach(n=>{const s=e[n];if(!s||!s["@rules"])return;const a=s["@rules"].unique;if(!a)return;const o=i.get(n)||[];"global"===a&&o.forEach((e,i)=>{const s=Array.isArray(t[n])?(r+"."+n+"["+i+"]").substr(1):(r+"."+n).substr(1);this._assertGlobalUnique(n,e,s)})})}_checkUniqueInCollection(t,e,n){const r=new Map;t.forEach((t,i)=>{const s=t[e];if(null==s||"object"==typeof s)return;const a=String(s);r.has(a)?this.failures.push({code:"unique",path:(n+"["+i+"]."+e).substr(1),value:a}):r.set(a,i)})}_assertGlobalUnique(t,e,n){this._globalUnique.has(t)||this._globalUnique.set(t,new Set);const r=this._globalUnique.get(t);r.has(e)?this.failures.push({code:"unique",path:n,value:e}):r.add(e)}checkDataAndType(t,e,n,r){!0===n["@rules"].repeatable&&this.checkOccurences(n["@rules"],1,r);const i=n["@rules"].type,s=this._expandRange(n);if("map"===i||!i&&this.isMapType(n))"string"==typeof t&&t.length>0&&this.failures.push({code:"unexpected value in a map",path:r.substr(1),value:t}),this.validateMandatoryFields(n,r);else if("date"===i)this.validateDate(t,i,r),this._checkDateBounds(n,t,r);else if("boolean"===i)this.validateBoolean(t,i,r);else if(-1!==me.indexOf(i))this.isValidNum(i,t)?this.assertValue(s["@rules"],"num",Number(t),r):this.setInvalidDataType(i,r,t);else{if("string"!==i&&i)throw new Error("Unsupported data type in Rules:"+i);this.assertValue(s["@rules"],"string",t,r)}}_expandRange(t){if(!t["@rules"]||!t["@rules"].range)return t;const e=function(t){if("string"!=typeof t)return null;const e=t.split("..");if(2!==e.length)return null;const n=Number(e[0]),r=Number(e[1]);return isNaN(n)||isNaN(r)?null:{min:n,max:r}}(t["@rules"].range);return e?{...t,"@rules":{...t["@rules"],min:void 0!==t["@rules"].min?t["@rules"].min:String(e.min),max:void 0!==t["@rules"].max?t["@rules"].max:String(e.max)}}:t}_checkDateBounds(t,e,n){if(isNaN(Date.parse(e)))return;const r=t["@rules"];let i=r.min,s=r.max;if(r.range&&(!i||!s)){const t=function(t){if("string"!=typeof t)return null;const e=t.split("..");if(2!==e.length)return null;const[n,r]=e;return isNaN(Date.parse(n))||isNaN(Date.parse(r))?null:{min:n,max:r}}(r.range);t&&(i||(i=t.min),s||(s=t.max))}void 0===i||fe(i,e)||this.setInvalidValueError("min",n,e,i),void 0===s||ge(s,e)||this.setInvalidValueError("max",n,e,s)}validateMandatoryFields(t,e){const n=Object.keys(t);for(let r=0;r<n.length;r++){if("@rules"===n[r])continue;const i=t[n[r]]["@rules"];i&&(i.minOccurs&&i.minOccurs>0||void 0!==i.nillable&&"false"===i.nillable)&&this.failures.push({code:"missing",path:(e+"."+n[r]).substr(1)})}}isMapType(t){if("string"==typeof t)return!1;const e=Object.keys(t);return t["@rules"]?1!==e.length&&void 0:0!==e.length}setInvalidValueError(t,e,n,r){this.failures.push({code:t,path:e.substr(1),actual:n,expected:r})}checkOccurences(t,e,n){["minOccurs","maxOccurs"].forEach(r=>{if(void 0!==t[r]){const i=Number(t[r]);pe[r](i,e)||this.setInvalidValueError(r,n,e,i)}})}checkNumeric(t,e,n){["min","max"].forEach(r=>{if(void 0!==t[r]){const i=Number(t[r]);de[r](i,e)||this.setInvalidValueError(r,n,e,i)}})}checkString(t,e,n){["minLength","maxLength","length"].forEach(r=>{if(void 0!==t[r]){const i=Number(t[r]);ce[r](i,e)||this.setInvalidValueError(r,n,e,i)}}),["fixed","in"].forEach(r=>{if(void 0!==t[r]){const i=t[r];ce[r](i,e)||this.setInvalidValueError(r,n,e,i)}}),["pattern","pattern_i","pattern_im","pattern_mi"].forEach(r=>{if(void 0!==t[r]){let i="";r.length>8&&(i=r.substring(8));const s=t[r];ce.pattern(s,e,i)||this.setInvalidValueError("pattern",n,e,s)}})}assertValue(t,e,n,r){"string"===e?this.checkString(t,n,r):"num"===e&&this.checkNumeric(t,n,r)}validateBoolean(t,e,n){-1===this.options.boolean.indexOf(t)&&this.setInvalidDataType(e,n,t)}isValidNum(t,e){if(isNaN(e))return!1;{const n=Number(e);if("positiveInteger"===t&&n<0||"positiveDecimal"===t&&n<0||"integer"===t&&!function(t){const e=parseFloat(t);return(0|e)===e}(e))return!1}return!0}validateDate(t,e,n){const r=Date.parse(t);isNaN(r)&&this.setInvalidDataType(e,n,t)}setInvalidDataType(t,e,n){this.failures.push({code:"not a "+t,path:e.substr(1),value:n})}checkMissingSiblings(t,e,n){t.rules&&t.rules.forEach(t=>{const r=e[t]["@rules"];r&&("false"===r.nillable||r.minOccurs>0)&&this.failures.push({code:"missing",path:(n+"."+t).substr(1)})})}checkUnknownSiblings(t,e){t.data&&!this.options.unknownAllow&&t.data.forEach(t=>{this.failures.push({code:"unknown",path:(e+"."+t).substr(1)})})}}const xe=ve.prototype.traverse;ve.prototype.traverse=function(t,e,n,r){if(Array.isArray(t)&&void 0!==n&&void 0!==n["@rules"]&&void 0!==n["@rules"].repeatable)return this.checkOccurences(n["@rules"],t.length,r),t.forEach((i,s)=>{const a=r+"["+s+"]";if(Object.keys(n).length>1)this.callForCommonProperties(t[s],n,a);else{const r=n;xe.call(this,t[s],e,r,a)}}),void(t.length>0&&"object"==typeof t[0]&&this._runSiblingUniqueness(t,n,r));xe.call(this,t,e,n,r)},ve.prototype._runSiblingUniqueness=function(t,e,n){Object.keys(e).filter(t=>"@rules"!==t).forEach(r=>{const i=e[r];i&&i["@rules"]&&"true"===i["@rules"].unique&&this._checkUniqueInCollection(t,r,n)})};const be={unknownAllow:!0,boolean:["true","false"]};function Ee(t){if(!t)throw new Error("Empty data");if("string"!=typeof t)throw new Error("Not a valid string");const e=ue.validate(t,{allowBooleanAttributes:!0});if(!0!==e)throw new Error(e.err.msg+":"+e.err.line)}const ye=class{constructor(t,e){Ee(t);const n=new he({ignoreAttributes:!1,attributesGroupName:"@rules",attributeNamePrefix:"",allowBooleanAttributes:!0});this.rules=n.parse(t),this.options=Object.assign({},be,e),this.validators={},this.data=null}register(t,e){this.validators[t]=e}validate(t){Ee(t);const e=new Map,n=new he({ignoreAttributes:!1,attributesGroupName:":a",attributeNamePrefix:"",parseTagValue:!1,tagValueProcessor:(t,n,r)=>{const i=r.lastIndexOf("."),s=-1===i?"":r.substring(0,i);e.has(s)||e.set(s,[]);const a=e.get(s);return a[a.length-1]!==t&&a.push(t),n}}).parse(t);this.data=n;const r=new ve(this.options,this.validators,e);return r.traverse(n,"",this.rules,""),r.failures}};var we=function(){function t(){}return t.validate=function(t,e){return function(t,e){e=Object.assign({},S,e);var n=[],r=!1,i=!1;"\ufeff"===t[0]&&(t=t.substr(1));var s="1.0";if(t.startsWith("<?xml")){var a=function(t){var e=t.indexOf("?>");-1===e&&V("InvalidXml",'XML declaration is not closed with "?>".',{line:1,col:1});for(var n,r=t.substring(5,e),i=e+2,s=["version","encoding","standalone"],a=/\s+([\w]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g,o="1.0",l=-1;null!==(n=a.exec(r));){var h=n[1],u=void 0!==n[2]?n[2]:n[3],c=n.index,d=s.indexOf(h);-1===d&&V("InvalidXml",'XML declaration contains unknown attribute "'+h+'". Allowed: version, encoding, standalone.',{line:1,col:6+c}),d<=l&&V("InvalidXml",'XML declaration attribute "'+h+'" is out of order. Required order: version, encoding, standalone.',{line:1,col:6+c}),l=d,"version"===h?("1.0"!==u&&"1.1"!==u&&V("InvalidXml",'XML declaration version "'+u+'" is not supported. Must be "1.0" or "1.1".',{line:1,col:6+c}),o=u):"standalone"===h&&"yes"!==u&&"no"!==u&&V("InvalidXml",'XML declaration standalone "'+u+'" is invalid. Must be "yes" or "no".',{line:1,col:6+c})}var p=r.replace(/\s+[\w]+\s*=\s*(?:"[^"]*"|'[^']*')/g,"").trim();return p.length>0&&V("InvalidXml",'XML declaration contains invalid content: "'+p+'".',{line:1,col:1}),{version:o,end:i}}(t);if(a.err)return a;s=a.version,t=t.substring(a.end)}for(var o=new g(e.docType,s),l=p("qName",{xmlVersion:s}),h=p("name",{xmlVersion:s}),u=0;u<t.length;u++)if("<"===t[u]&&"?"===t[u+1]){if((u=I(t,u+=2,h)).err)return u}else if("<"===t[u]){var c=u;if("!"===t[++u]){try{u=C(t,u,o)}catch(e){V("InvalidTag",e.message,$(t,u-1))}continue}var d=!1;"/"===t[u]&&(d=!0,u++);for(var f="";u<t.length&&">"!==t[u]&&" "!==t[u]&&"\t"!==t[u]&&"\n"!==t[u]&&"\r"!==t[u];u++)f+=t[u];"/"===(f=f.trim())[f.length-1]&&(f=f.substring(0,f.length-1),u--),l(f)||V("InvalidTag",0===f.trim().length?"Invalid space after '<'.":"Tag '"+f+"' is an invalid name.",$(t,c));var m=P(t,u);!1===m&&V("InvalidAttr","Attributes for '"+f+"' have open quote.",$(t,u));var v=m.value;if(u=m.index,"/"===v[v.length-1]){var x=u-v.length,b=D(v=v.substring(0,v.length-1),e,l,s);!0===b?(!0===i&&V("InvalidXml","Multiple possible root nodes found.",$(t,c)),r=!0,0===n.length&&(i=!0)):V(b.err.code,b.err.msg,$(t,x+b.err.line))}else if(d)if(m.tagClosed)if(v.trim().length>0)V("InvalidTag","Closing tag '"+f+"' can't have attributes or invalid starting.",$(t,c));else if(0===n.length)V("InvalidTag","Closing tag '"+f+"' has not been opened.",$(t,c));else{var E=n.pop();if(f!==E.tagName){var y=$(t,E.tagStartPos);V("InvalidTag","Expected closing tag '"+E.tagName+"' (opened in line "+y.line+", col "+y.col+") instead of closing tag '"+f+"'.",$(t,c))}0===n.length&&(i=!0)}else V("InvalidTag","Closing tag '"+f+"' doesn't have proper closing.",$(t,u));else{var w=D(v,e,l,s);!0!==w&&V(w.err.code,w.err.msg,$(t,u-v.length+w.err.line)),!0===i?V("InvalidXml","Multiple possible root nodes found.",$(t,u)):-1!==e.unpairedTags.indexOf(f)||n.push({tagName:f,tagStartPos:c}),r=!0}for(u++;u<t.length;u++)if("<"===t[u]){if("!"===t[u+1]){u++;try{u=C(t,u,o)}catch(e){V("InvalidDocType",e.message,$(t,u-1))}continue}if("?"!==t[u+1])break;if((u=I(t,u+=2,h)).err)return u}else if("&"===t[u]){var N=k(t,u);-1===N&&V("InvalidChar","char '&' is not expected.",$(t,u)),u=N}else!0!==i||T(t[u])||V("InvalidXml","Extra text at the end",$(t,u));"<"===t[u]&&u--}else{if(T(t[u]))continue;i&&V("InvalidXml","Extra text at the end: '"+t[u]+"' is not expected.",$(t,u)),V("InvalidChar","char '"+t[u]+"' is not expected.",$(t,u))}return r?1===n.length?V("InvalidTag","Unclosed tag '"+n[0].tagName+"'.",$(t,n[0].tagStartPos)):n.length>0&&V("InvalidXml","Invalid '"+JSON.stringify(n.map(function(t){return t.tagName})).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):V("InvalidXml","Start tag expected.",{line:1,col:1}),!0}(t,e)},t}();return e})());
|
|
1
|
+
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.fxp=e():t.fxp=e()}(this,()=>(()=>{"use strict";var t={d:(e,r)=>{for(var n in r)t.o(r,n)&&!t.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:r[n]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};function r(t){var e="function"==typeof Map?new Map:void 0;return r=function(t){if(null===t||!function(t){try{return-1!==Function.toString.call(t).indexOf("[native code]")}catch(e){return"function"==typeof t}}(t))return t;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,r)}function r(){return function(t,e,r){if(n())return Reflect.construct.apply(null,arguments);var i=[null];i.push.apply(i,e);var a=new(t.bind.apply(t,i));return r&&s(a,r.prototype),a}(t,arguments,i(this).constructor)}return r.prototype=Object.create(t.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),s(r,t)},r(t)}function n(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(n=function(){return!!t})()}function s(t,e){return s=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},s(t,e)}function i(t){return i=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},i(t)}t.r(e),t.d(e,{BusinessRulesValidator:()=>br,SyntaxValidator:()=>q});var a=function(t){function e(e,r,n,s){var i;return(i=t.call(this,e)||this).name=i.constructor.name,i.code=r,i.line=n,i.col=s,null==Error.captureStackTrace||Error.captureStackTrace(i,i.constructor),i}var r,n;return n=t,(r=e).prototype=Object.create(n.prototype),r.prototype.constructor=r,s(r,n),e}(r(Error));function o(t){return" "===t||"\t"===t||"\n"===t||"\r"===t}function l(t){return t<=8||11===t||12===t||t>=14&&t<=31}function c(t,e){var r=t.substring(0,e).split(/\r?\n/);return{line:r.length,col:r[r.length-1].length+1}}function h(t){return t.startIndex+t[1].length}const u=":A-Za-z_À-ÖØ-öø-˿Ͱ-ͽͿ-҆҈--⁰-Ⰰ-、-豈-﷏ﷰ-�",d=":A-Za-z_À-˿Ͱ-ͽͿ-҆҈--⁰-Ⰰ-、-豈-﷏ﷰ-�𐀀-",p=d+"\\-\\.\\d·̀-ͯ҇‿-⁀",f=(t,e,r="")=>{const n=`[${t.replace(":","")}][${e.replace(":","")}]*`;return{name:new RegExp(`^[${t}][${e}]*$`,r),ncName:new RegExp(`^${n}$`,r),qName:new RegExp(`^${n}(?::${n})?$`,r),nmToken:new RegExp(`^[${e}]+$`,r),nmTokens:new RegExp(`^[${e}]+(?:\\s+[${e}]+)*$`,r)}},g=f(u,u+"\\-\\.\\d·̀-ͯ‿-⁀"),m=f(d,p,"u"),_=":A-Za-z_",E=f(_,_+"\\-\\.\\d"),b=(t="1.0",e=!1)=>e?E:"1.1"===t?m:g,x=(t,{xmlVersion:e="1.0",asciiOnly:r=!1}={})=>b(e,r).name.test(t),y=["name","ncName","qName","nmToken","nmTokens"],T=(t,{xmlVersion:e="1.0",asciiOnly:r=!1,maxCacheSize:n=2048}={})=>{if(!y.includes(t))throw new TypeError(`Unknown production "${t}". Must be one of: ${y.join(", ")}`);const s=b(e,r)[t];let i=new Map;const a=t=>{const e=i.get(t);if(void 0!==e)return e;const r=s.test(t);return i.size<n&&i.set(t,r),r};return a.reset=()=>{i=new Map},a};var w=function(){function t(t){void 0===t&&(t="1.0"),this.xmlVersion=t,this.qName=T("qName",{xmlVersion:t}),this.name=T("name",{xmlVersion:t})}var e=t.prototype;return e.isValidQName=function(t){return this.qName(t)},e.isValidName=function(t){return this.name(t)},t}(),v=function(){function t(t,e){void 0===t&&(t={}),this.optional=void 0===t.optional||t.optional,this.argPosition=void 0!==t.argPosition?t.argPosition:void 0===t.argPostion||t.argPostion,this._throwError=e}return t.prototype.validate=function(t){if(!t.startsWith("<?xml"))return this.optional||this._throwError("InvalidXml","XML declaration is required but missing.",{line:1,col:1}),{version:"1.0",end:0};var e=t.indexOf("?>");-1===e&&this._throwError("InvalidXml",'XML declaration is not closed with "?>".',{line:1,col:1});for(var r,n=t.substring(5,e),s=e+2,i=["version","encoding","standalone"],a=/\s+([\w]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g,o="1.0",l=-1;null!==(r=a.exec(n));){var c=r[1],h=void 0!==r[2]?r[2]:r[3],u=r.index,d=i.indexOf(c);-1===d&&this._throwError("InvalidXml",'XML declaration contains unknown attribute "'+c+'". Allowed: version, encoding, standalone.',{line:1,col:6+u}),this.argPosition&&d<=l&&this._throwError("InvalidXml",'XML declaration attribute "'+c+'" is out of order. Required order: version, encoding, standalone.',{line:1,col:6+u}),l=d,"version"===c?("1.0"!==h&&"1.1"!==h&&this._throwError("InvalidXml",'XML declaration version "'+h+'" is not supported. Must be "1.0" or "1.1".',{line:1,col:6+u}),o=h):"standalone"===c&&"yes"!==h&&"no"!==h&&this._throwError("InvalidXml",'XML declaration standalone "'+h+'" is invalid. Must be "yes" or "no".',{line:1,col:6+u})}var p=n.replace(/\s+[\w]+\s*=\s*(?:"[^"]*"|'[^']*')/g,"").trim();return p.length>0&&this._throwError("InvalidXml",'XML declaration contains invalid content: "'+p+'".',{line:1,col:1}),{version:o,end:s}},t}(),I=function(){function t(){}return t.findIllegalIndex=function(t){for(var e=t.length,r=0;r<e;r++)if(l(t.charCodeAt(r)))return r;return-1},t.hasIllegalChar=function(t){return-1!==this.findIllegalIndex(t)},t.describe=function(t){return"0x"+t.toString(16).padStart(2,"0")},t}(),A=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g"),N=function(){function t(t,e,r){this.options=t,this.nameValidator=e,this.xmlVersion=r}var e=t.prototype;return e.validate=function(t){for(var e,r=function(t,e){for(var r=[],n=e.exec(t);n;){var s=[];s.startIndex=e.lastIndex-n[0].length;for(var i=n.length,a=0;a<i;a++)s.push(n[a]);r.push(s),n=e.exec(t)}return r}(t,A),n={},s=!0===(null==(e=this.options.invalidCharSequence)?void 0:e.attrLt),i=0;i<r.length;i++){var a=r[i];if(0===a[1].length)return this._err("InvalidAttr","Attribute '"+a[2]+"' has no space in starting.",a);var o=void 0!==a[3],l=void 0!==a[4];if(o&&!l)return this._err("UnquotedAttributeValue","Attribute '"+a[2]+"' is without value.",a);if(!o&&!this.options.allowBooleanAttributes)return this._err("InvalidAttr","boolean attribute '"+a[2]+"' is not allowed.",a);var c=a[2];if(!this.nameValidator.isValidQName(c))return this._err("InvalidAttr","Attribute '"+c+"' is an invalid name.",a);var h=a[6]||"";if(l){var u=I.findIllegalIndex(h);if(-1!==u){var d=h.charCodeAt(u);return this._err("IllegalCharacter","Illegal control character "+I.describe(d)+" in attribute '"+c+"' value.",a)}if(s&&-1!==h.indexOf("<"))return this._err("InvalidAttr","Attribute '"+c+"' value must not contain '<'.",a)}if(c.startsWith("xmlns:")&&""===a[6]&&"1.0"===this.xmlVersion)return this._err("InvalidAttr","Undeclaring the prefixed namespace "+c+'="" is only permitted in XML 1.1 documents.',a);if(Object.prototype.hasOwnProperty.call(n,c))return this._err("InvalidAttr","Attribute '"+c+"' is repeated.",a);n[c]=1}return!0},e._err=function(t,e,r){return{err:{code:t,msg:e,line:h(r)}}},t}(),S=function(){function t(t){var e;void 0===t&&(t={}),this.checkCommentDashes=!0===(null==(e=t.invalidCharSequence)?void 0:e.comment)}var e=t.prototype;return e.read=function(t,e,r){if(t.length>e+2&&"-"===t[e+1]&&"-"===t[e+2])return this._readComment(t,e);if(t.length>e+7&&"D"===t[e+1]&&"O"===t[e+2]&&"C"===t[e+3]&&"T"===t[e+4]&&"Y"===t[e+5]&&"P"===t[e+6]&&"E"===t[e+7])return r.validateDocType(t,e-1);if(t.length>e+8&&"["===t[e+1]&&"C"===t[e+2]&&"D"===t[e+3]&&"A"===t[e+4]&&"T"===t[e+5]&&"A"===t[e+6]&&"["===t[e+7])return this._readCdata(t,e);throw new Error("Invalid construct starting with '<!'.")},e._readComment=function(t,e){var r=e+3;for(e=r;e<t.length;e++)if("-"===t[e]&&"-"===t[e+1]&&">"===t[e+2]){e+=2;break}if(">"!==t[e])throw new Error('Comment is not closed with "--\x3e".');var n=t.substring(r,e-2),s=I.findIllegalIndex(n);if(-1!==s){var i=n.charCodeAt(s);throw new Error("Illegal control character "+I.describe(i)+" in comment.")}if(this.checkCommentDashes&&-1!==n.indexOf("--"))throw new Error("Comment must not contain '--'.");return e},e._readCdata=function(t,e){var r=e+8;for(e=r;e<t.length;e++)if("]"===t[e]&&"]"===t[e+1]&&">"===t[e+2]){e+=2;break}if(">"!==t[e])throw new Error('CDATA section is not closed with "]]>".');var n=t.substring(r,e-2),s=I.findIllegalIndex(n);if(-1!==s){var i=n.charCodeAt(s);throw new Error("Illegal control character "+I.describe(i)+" in CDATA section.")}return e},t}();class C{constructor(t,e={},r){this.pattern=t,this.separator=e.separator||".",this.segments=this._parse(t),this.data=r,this._hasDeepWildcard=this.segments.some(t=>"deep-wildcard"===t.type),this._hasAttributeCondition=this.segments.some(t=>void 0!==t.attrName),this._hasPositionSelector=this.segments.some(t=>void 0!==t.position)}_parse(t){const e=[];let r=0,n="";for(;r<t.length;)t[r]===this.separator?r+1<t.length&&t[r+1]===this.separator?(n.trim()&&(e.push(this._parseSegment(n.trim())),n=""),e.push({type:"deep-wildcard"}),r+=2):(n.trim()&&e.push(this._parseSegment(n.trim())),n="",r++):(n+=t[r],r++);return n.trim()&&e.push(this._parseSegment(n.trim())),e}_parseSegment(t){const e={type:"tag"};let r=null,n=t;const s=t.match(/^([^\[]+)(\[[^\]]*\])(.*)$/);if(s&&(n=s[1]+s[3],s[2])){const t=s[2].slice(1,-1);t&&(r=t)}let i,a,o=n;if(n.includes("::")){const e=n.indexOf("::");if(i=n.substring(0,e).trim(),o=n.substring(e+2).trim(),!i)throw new Error(`Invalid namespace in pattern: ${t}`)}let l=null;if(o.includes(":")){const t=o.lastIndexOf(":"),e=o.substring(0,t).trim(),r=o.substring(t+1).trim();["first","last","odd","even"].includes(r)||/^nth\(\d+\)$/.test(r)?(a=e,l=r):a=o}else a=o;if(!a)throw new Error(`Invalid segment pattern: ${t}`);if(e.tag=a,i&&(e.namespace=i),r)if(r.includes("=")){const t=r.indexOf("=");e.attrName=r.substring(0,t).trim(),e.attrValue=r.substring(t+1).trim()}else e.attrName=r.trim();if(l){const t=l.match(/^nth\((\d+)\)$/);t?(e.position="nth",e.positionValue=parseInt(t[1],10)):e.position=l}return e}get length(){return this.segments.length}hasDeepWildcard(){return this._hasDeepWildcard}hasAttributeCondition(){return this._hasAttributeCondition}hasPositionSelector(){return this._hasPositionSelector}toString(){return this.pattern}}class D{constructor(t){this._matcher=t}get separator(){return this._matcher.separator}getCurrentTag(){const t=this._matcher.path;return t.length>0?t[t.length-1].tag:void 0}getCurrentNamespace(){const t=this._matcher.path;return t.length>0?t[t.length-1].namespace:void 0}getAttrValue(t){const e=this._matcher.path;if(0!==e.length)return e[e.length-1].values?.[t]}hasAttr(t){const e=this._matcher.path;if(0===e.length)return!1;const r=e[e.length-1];return void 0!==r.values&&t in r.values}getAnyParentAttr(t){return this._matcher.getAnyParentAttr(t)}hasAnyParentAttr(t){return this._matcher.hasAnyParentAttr(t)}getPosition(){const t=this._matcher.path;return 0===t.length?-1:t[t.length-1].position??0}getCounter(){const t=this._matcher.path;return 0===t.length?-1:t[t.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this._matcher.path.length}toString(t,e=!0){return this._matcher.toString(t,e)}toArray(){return this._matcher.path.map(t=>t.tag)}matches(t){return this._matcher.matches(t)}matchesAny(t){return t.matchesAny(this._matcher)}}class O{constructor(t={}){this.separator=t.separator||".",this.path=[],this.siblingStacks=[],this._pathStringCache=null,this._view=new D(this),this._keptAttrs=[]}push(t,e=null,r=null,n=null){this._pathStringCache=null,this.path.length>0&&(this.path[this.path.length-1].values=void 0);const s=this.path.length;let i=this.siblingStacks[s];i||(i={counts:new Map,total:0},this.siblingStacks[s]=i);const a=r?`${r}:${t}`:t,o=i.counts.get(a)||0,l=i.total;i.counts.set(a,o+1),i.total++;const c={tag:t,position:l,counter:o};null!=r&&(c.namespace=r),null!=e&&(c.values=e),this.path.push(c);const h=this.path.length,u=null!==n?n.keep:null;if(null!=u&&u.length>0&&e)for(let t=0;t<u.length;t++){const r=u[t];void 0!==e[r]&&this._keptAttrs.push({depth:h,name:r,value:e[r]})}}pop(){if(0===this.path.length)return;this._pathStringCache=null;const t=this.path.pop();this.siblingStacks.length>this.path.length+1&&(this.siblingStacks.length=this.path.length+1);const e=this.path.length+1;for(;this._keptAttrs.length>0&&this._keptAttrs[this._keptAttrs.length-1].depth>=e;)this._keptAttrs.pop();return t}updateCurrent(t){if(this.path.length>0){const e=this.path[this.path.length-1];null!=t&&(e.values=t)}}getCurrentTag(){return this.path.length>0?this.path[this.path.length-1].tag:void 0}getCurrentNamespace(){return this.path.length>0?this.path[this.path.length-1].namespace:void 0}getAttrValue(t){if(0!==this.path.length)return this.path[this.path.length-1].values?.[t]}hasAttr(t){if(0===this.path.length)return!1;const e=this.path[this.path.length-1];return void 0!==e.values&&t in e.values}getAnyParentAttr(t){const e=this._keptAttrs;for(let r=e.length-1;r>=0;r--)if(e[r].name===t)return e[r].value}hasAnyParentAttr(t){const e=this._keptAttrs;for(let r=e.length-1;r>=0;r--)if(e[r].name===t)return!0;return!1}getPosition(){return 0===this.path.length?-1:this.path[this.path.length-1].position??0}getCounter(){return 0===this.path.length?-1:this.path[this.path.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this.path.length}toString(t,e=!0){const r=t||this.separator;if(r===this.separator&&!0===e){if(null!==this._pathStringCache)return this._pathStringCache;const t=this.path.map(t=>t.namespace?`${t.namespace}:${t.tag}`:t.tag).join(r);return this._pathStringCache=t,t}return this.path.map(t=>e&&t.namespace?`${t.namespace}:${t.tag}`:t.tag).join(r)}toArray(){return this.path.map(t=>t.tag)}reset(){this._pathStringCache=null,this.path=[],this.siblingStacks=[],this._keptAttrs=[]}matches(t){const e=t.segments;return 0!==e.length&&(t.hasDeepWildcard()?this._matchWithDeepWildcard(e):this._matchSimple(e))}_matchSimple(t){if(this.path.length!==t.length)return!1;for(let e=0;e<t.length;e++)if(!this._matchSegment(t[e],this.path[e],e===this.path.length-1))return!1;return!0}_matchWithDeepWildcard(t){let e=this.path.length-1,r=t.length-1;for(;r>=0&&e>=0;){const n=t[r];if("deep-wildcard"===n.type){if(r--,r<0)return!0;const n=t[r];let s=!1;for(let t=e;t>=0;t--)if(this._matchSegment(n,this.path[t],t===this.path.length-1)){e=t-1,r--,s=!0;break}if(!s)return!1}else{if(!this._matchSegment(n,this.path[e],e===this.path.length-1))return!1;e--,r--}}return r<0}_matchSegment(t,e,r){if("*"!==t.tag&&t.tag!==e.tag)return!1;if(void 0!==t.namespace&&"*"!==t.namespace&&t.namespace!==e.namespace)return!1;if(void 0!==t.attrName){if(!r)return!1;if(!e.values||!(t.attrName in e.values))return!1;if(void 0!==t.attrValue&&String(e.values[t.attrName])!==String(t.attrValue))return!1}if(void 0!==t.position){if(!r)return!1;const n=e.counter??0;if("first"===t.position&&0!==n)return!1;if("odd"===t.position&&n%2!=1)return!1;if("even"===t.position&&n%2!=0)return!1;if("nth"===t.position&&n!==t.positionValue)return!1}return!0}matchesAny(t){return t.matchesAny(this)}snapshot(){return{path:this.path.map(t=>({...t})),siblingStacks:this.siblingStacks.map(t=>t?{counts:new Map(t.counts),total:t.total}:t),keptAttrs:this._keptAttrs.map(t=>({...t}))}}restore(t){this._pathStringCache=null,this.path=t.path.map(t=>({...t})),this.siblingStacks=t.siblingStacks.map(t=>t?{counts:new Map(t.counts),total:t.total}:t),this._keptAttrs=(t.keptAttrs||[]).map(t=>({...t}))}readOnly(){return this._view}}function k(t,e){for(var r=0;r<e.length;r++){var n=e[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,P(n.key),n)}}function P(t){var e=function(t){if("object"!=typeof t||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var r=e.call(t,"string");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==typeof e?e:e+""}var L=function(){function t(t){void 0===t&&(t=[]),this._expressions=t.map(function(t){return new C(t)}),this._matcher=new O,this._enabled=this._expressions.length>0}var e,r,n=t.prototype;return n.push=function(t,e){if(!this._enabled)return!1;this._matcher.push(t,e||null);for(var r=0;r<this._expressions.length;r++)if(this._matcher.matches(this._expressions[r]))return!0;return!1},n.pop=function(){this._enabled&&this._matcher.pop()},e=t,(r=[{key:"enabled",get:function(){return this._enabled}}])&&k(e.prototype,r),Object.defineProperty(e,"prototype",{writable:!1}),e}(),U=function(){function t(){}return t.consume=function(t,e,r){for(var n="</"+e,s=r;;){var i=t.indexOf(n,s);if(-1===i)throw new Error("Unclosed skipped tag '"+e+"'.");for(var a=i+n.length;a<t.length&&/\s/.test(t[a]);)a++;if(">"===t[a])return a;s=i+n.length}},t}(),M={maxEntityCount:1/0,maxEntitySize:1/0},B=function(){function t(t,e){void 0===e&&(e="1.0"),this.options=Object.assign({},M,t),this.suppressValidationErr=!t,this.xmlVersion=e}var e=t.prototype;return e.validateDocType=function(t,e){if("O"!==t[e+3]||"C"!==t[e+4]||"T"!==t[e+5]||"Y"!==t[e+6]||"P"!==t[e+7]||"E"!==t[e+8])throw new Error("Invalid Tag instead of DOCTYPE");e+=9;for(var r=1,n=!1,s=!1,i=0;e<t.length;e++)if("<"!==t[e]||s)if(">"===t[e]){if(s?"-"===t[e-1]&&"-"===t[e-2]&&(s=!1,r--):r--,0===r)break}else"["===t[e]&&(n=!0);else{if(n&&$(t,"!ENTITY",e)){e+=7;var a=this._validateEntityExp(t,e+1,i);i=a[0],e=a[1]}else if(n&&$(t,"!ELEMENT",e))e+=8,e=this._validateElementExp(t,e+1);else{if(n&&$(t,"!ATTLIST",e)){e+=8,e=this._validateAttlistExp(t,e+1);continue}if(n&&$(t,"!NOTATION",e))e+=9,e=this._validateNotationExp(t,e+1);else{if(!$(t,"!--",e))throw new Error("Invalid DOCTYPE");s=!0}}r++}if(0!==r)throw new Error("Unclosed DOCTYPE");return e},e._validateEntityExp=function(t,e,r){for(var n=e=R(t,e);e<t.length&&!/\s/.test(t[e])&&'"'!==t[e]&&"'"!==t[e];)e++;var s,i=t.substring(n,e);if(V(i,this.xmlVersion),e=R(t,e),!this.suppressValidationErr){if("SYSTEM"===t.substring(e,e+6).toUpperCase())throw new Error("External entities are not supported");if("%"===t[e])throw new Error("Parameter entities are not supported")}var a=j(t,e,"entity");e=a[0],s=a[1];var o=this.options,l=o.maxEntitySize,c=o.maxEntityCount;if(s.length>l)throw new Error('Entity "'+i+'" size ('+s.length+") exceeds maximum allowed size ("+l+")");if(-1===s.indexOf("&")&&++r>c)throw new Error("Entity count ("+r+") exceeds maximum allowed ("+c+")");return[r,e-1]},e._validateNotationExp=function(t,e){for(var r=e=R(t,e);e<t.length&&!/\s/.test(t[e]);)e++;var n=t.substring(r,e);!this.suppressValidationErr&&V(n,this.xmlVersion),e=R(t,e);var s=t.substring(e,e+6).toUpperCase();if(!this.suppressValidationErr&&"SYSTEM"!==s&&"PUBLIC"!==s)throw new Error('Expected SYSTEM or PUBLIC, found "'+s+'"');return e=R(t,e+=s.length),"PUBLIC"===s?'"'!==t[e=R(t,e=j(t,e,"publicIdentifier")[0])]&&"'"!==t[e]||(e=j(t,e,"systemIdentifier")[0]):"SYSTEM"===s&&(e=j(t,e,"systemIdentifier")[0]),--e},e._validateElementExp=function(t,e){for(var r=e=R(t,e);e<t.length&&!/\s/.test(t[e]);)e++;var n=t.substring(r,e);if(!this.suppressValidationErr&&!x(n,{xmlVersion:this.xmlVersion}))throw new Error('Invalid element name: "'+n+'"');if("E"===t[e=R(t,e)]&&$(t,"MPTY",e))e+=4;else if("A"===t[e]&&$(t,"NY",e))e+=2;else if("("===t[e]){for(e++;e<t.length&&")"!==t[e];)e++;if(")"!==t[e])throw new Error("Unterminated content model")}else if(!this.suppressValidationErr)throw new Error('Invalid Element Expression, found "'+t[e]+'"');return e},e._validateAttlistExp=function(t,e){for(var r=e=R(t,e);e<t.length&&!/\s/.test(t[e]);)e++;V(t.substring(r,e),this.xmlVersion);for(var n=e=R(t,e);e<t.length&&!/\s/.test(t[e]);)e++;if(V(t.substring(n,e),this.xmlVersion),e=R(t,e),"NOTATION"===t.substring(e,e+8).toUpperCase()){if("("!==t[e=R(t,e+=8)])throw new Error("Expected '(', found \""+t[e]+'"');for(e++;e<t.length&&")"!==t[e];){for(var s=e;e<t.length&&"|"!==t[e]&&")"!==t[e];)e++;V(t.substring(s,e).trim(),this.xmlVersion),"|"===t[e]&&(e=R(t,++e))}if(")"!==t[e])throw new Error("Unterminated list of notations");e++}else{for(var i=e;e<t.length&&!/\s/.test(t[e]);)e++;var a=t.substring(i,e);if(!this.suppressValidationErr&&!["CDATA","ID","IDREF","IDREFS","ENTITY","ENTITIES","NMTOKEN","NMTOKENS"].includes(a.toUpperCase()))throw new Error('Invalid attribute type: "'+a+'"')}return e=R(t,e),"#REQUIRED"===t.substring(e,e+9).toUpperCase()?e+=9:"#IMPLIED"===t.substring(e,e+8).toUpperCase()?e+=8:e=j(t,e,"ATTLIST default value")[0],e},t}();function R(t,e){for(;e<t.length&&/\s/.test(t[e]);)e++;return e}function $(t,e,r){for(var n=0;n<e.length;n++)if(e[n]!==t[r+n+1])return!1;return!0}function V(t,e){if(void 0===e&&(e="1.0"),!x(t,{xmlVersion:e}))throw new Error('Invalid entity name "'+t+'"')}function j(t,e,r){var n=t[e];if('"'!==n&&"'"!==n)throw new Error("Expected quoted string for "+r+', found "'+n+'"');for(var s=++e;e<t.length&&t[e]!==n;)e++;if(t[e]!==n)throw new Error("Unterminated "+r+" value");var i=t.substring(s,e);return[++e,i]}var X={allowBooleanAttributes:!1,unpairedTags:[],docType:{maxEntityCount:1/0,maxEntitySize:1/0},invalidCharSequence:{comment:!1,tagValue:!1,attrLt:!1},xmlDeclaraion:{optional:!0,argPosition:!0},multipleRoots:!0,skipTags:[]},q=function(){function t(t){this.options=function(t,e){var r=Object.assign({},t,e);return r.docType=Object.assign({},t.docType,null==e?void 0:e.docType),r.invalidCharSequence=Object.assign({},t.invalidCharSequence,null==e?void 0:e.invalidCharSequence),r.xmlDeclaraion=Object.assign({},t.xmlDeclaraion,null==e?void 0:e.xmlDeclaraion,null==e?void 0:e.xmlDeclaration),r.skipTags=(null==e?void 0:e.skipTags)||t.skipTags,r}(X,t)}t.validate=function(e,r){return new t(r).validate(e)};var e=t.prototype;return e.validate=function(t){var e,r=this.options,n=[],s=!1,i=!1,h=!1;"\ufeff"===t[0]&&(t=t.substr(1));var u=function(t,e,r){throw new a(e,t,r.line||r,r.col)},d=new v(r.xmlDeclaraion,u).validate(t),p=d.version;t=t.substring(d.end);for(var f=new B(r.docType,p),g=new S(r),m=new w(p),_=new N(r,m,p),E=new L(r.skipTags),b=!0===(null==(e=r.invalidCharSequence)?void 0:e.tagValue),x=function(e){"<!DOCTYPE"===t.substring(e,e+9).toUpperCase()&&(h&&u("InvalidXml","Multiple DOCTYPE declarations found.",c(t,e)),(s||n.length>0)&&u("InvalidXml","DOCTYPE must appear before the root element.",c(t,e)),h=!0)},y=0;y<t.length;y++)if("<"===t[y]&&"?"===t[y+1])y+=2,y=this._readPI(t,y,m,u);else if("<"===t[y]){var T=y;if(y++,"!"===t[y]){try{x(T),y=g.read(t,y,f)}catch(e){u("InvalidDocType",e.message,c(t,y-1))}continue}var A=!1;"/"===t[y]&&(A=!0,y++);for(var C="";y<t.length&&">"!==t[y]&&" "!==t[y]&&"\t"!==t[y]&&"\n"!==t[y]&&"\r"!==t[y];y++)C+=t[y];if("/"===(C=C.trim())[C.length-1]&&(C=C.substring(0,C.length-1),y--),!m.isValidQName(C)){var D;D=0===C.trim().length?"Invalid space after '<'.":"Tag '"+C+"' is an invalid name.",u("InvalidTag",D,c(t,T))}var O=this._readAttributeStr(t,y);!1===O&&u("InvalidAttr","Attributes for '"+C+"' have open quote.",c(t,y));var k=O.value;if(y=O.index,"/"===k[k.length-1]){var P=y-k.length;k=k.substring(0,k.length-1);var M=_.validate(k);!0===M?(!0!==i||r.multipleRoots||u("InvalidXml","Multiple possible root nodes found.",c(t,T)),s=!0,0===n.length&&(i=!0),E.push(C),E.pop()):u(M.err.code,M.err.msg,c(t,P+M.err.line))}else if(A)if(O.tagClosed)if(k.trim().length>0)u("InvalidTag","Closing tag '"+C+"' can't have attributes or invalid starting.",c(t,T));else if(0===n.length)u("InvalidTag","Closing tag '"+C+"' has not been opened.",c(t,T));else{var R=n.pop();if(C!==R.tagName){var $=c(t,R.tagStartPos);u("InvalidTag","Expected closing tag '"+R.tagName+"' (opened in line "+$.line+", col "+$.col+") instead of closing tag '"+C+"'.",c(t,T))}E.pop(),0===n.length&&(i=!0)}else u("InvalidTag","Closing tag '"+C+"' doesn't have proper closing.",c(t,y));else{var V=E.push(C);if(!V){var j=_.validate(k);!0!==j&&u(j.err.code,j.err.msg,c(t,y-k.length+j.err.line))}if(!0!==i||r.multipleRoots)if(-1!==r.unpairedTags.indexOf(C))E.pop();else{if(V){y=U.consume(t,C,y+1),E.pop(),0===n.length&&(i=!0),s=!0;continue}n.push({tagName:C,tagStartPos:T})}else u("InvalidXml","Multiple possible root nodes found.",c(t,y));s=!0}var X="";for(y++;y<t.length;y++)if("<"===t[y]){if("!"===t[y+1]){y++;try{x(y-1),y=g.read(t,y,f)}catch(e){u("InvalidDocType",e.message,c(t,y-1))}X="";continue}if("?"!==t[y+1])break;y+=2,y=this._readPI(t,y,m,u),X=""}else if("&"===t[y]){var q=this._validateAmpersand(t,y);-1===q&&u("InvalidChar","char '&' is not expected.",c(t,y)),y=q,X=""}else{var F=t.charCodeAt(y);l(F)&&u("IllegalCharacter","Illegal control character "+I.describe(F)+" in document content.",c(t,y)),!0!==i||0!==n.length||o(t[y])||u("InvalidXml","Extra text at the end",c(t,y)),b&&"]]"===(X=(X+t[y]).slice(-2))&&">"===t[y+1]&&u("InvalidXml","Element text content must not contain ']]>'.",c(t,y-1))}"<"===t[y]&&y--}else{if(o(t[y]))continue;i&&u("InvalidXml","Extra text at the end: '"+t[y]+"' is not expected.",c(t,y)),u("InvalidChar","char '"+t[y]+"' is not expected.",c(t,y))}return s?1===n.length?u("InvalidTag","Unclosed tag '"+n[0].tagName+"'.",c(t,n[0].tagStartPos)):n.length>0&&u("InvalidXml","Invalid '"+JSON.stringify(n.map(function(t){return t.tagName})).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):u("InvalidXml","Start tag expected.",{line:1,col:1}),!0},e._readPI=function(t,e,r,n){for(var s=e,i=e,a=!1;e<t.length;e++){var o=t[e];if(!a&&(" "===o||"?"===o)){var l=t.substr(i,e-i);a=!0,"xml"===l.toLowerCase()?n("InvalidXml","XML declaration allowed only at the start of the document.",c(t,s-2)):r.isValidName(l)||n("InvalidXml",'Processing instruction target "'+l+'" is not a valid XML Name.',c(t,s-2))}if("?"===o&&">"===t[e+1])return++e}n("InvalidXml",'Processing instruction is not closed with "?>".',c(t,s-2))},e._readAttributeStr=function(t,e){for(var r="",n="",s=!1;e<t.length;e++){if('"'===t[e]||"'"===t[e])""===n?n=t[e]:n!==t[e]||(n="");else if(">"===t[e]&&""===n){s=!0;break}r+=t[e]}return""===n&&{value:r,index:e,tagClosed:s}},e._validateNumberAmpersand=function(t,e){var r=/\d/;for("x"===t[e]&&(e++,r=/[\da-fA-F]/);e<t.length;e++){if(";"===t[e])return e;if(!t[e].match(r))break}return-1},e._validateAmpersand=function(t,e){if(";"===t[++e])return-1;if("#"===t[e])return e++,this._validateNumberAmpersand(t,e);for(var r=0;e<t.length;e++,r++)if(!(t[e].match(/\w/)&&r<20)){if(";"===t[e])break;return-1}return e},t}();class F{constructor(){this._byDepthAndTag=new Map,this._wildcardByDepth=new Map,this._deepWildcards=[],this._deepByTerminalTag=new Map,this._patterns=new Set,this._sealed=!1}add(t){if(this._sealed)throw new TypeError("ExpressionSet is sealed. Create a new ExpressionSet to add more expressions.");if(this._patterns.has(t.pattern))return this;if(this._patterns.add(t.pattern),t.hasDeepWildcard()){const e=t.segments[t.segments.length-1];if(e&&"deep-wildcard"!==e.type&&"*"!==e.tag){const r=e.tag;this._deepByTerminalTag.has(r)||this._deepByTerminalTag.set(r,[]),this._deepByTerminalTag.get(r).push(t)}else this._deepWildcards.push(t);return this}const e=t.length,r=t.segments[t.segments.length-1],n=r?.tag;if(n&&"*"!==n){const r=`${e}:${n}`;this._byDepthAndTag.has(r)||this._byDepthAndTag.set(r,[]),this._byDepthAndTag.get(r).push(t)}else this._wildcardByDepth.has(e)||this._wildcardByDepth.set(e,[]),this._wildcardByDepth.get(e).push(t);return this}addAll(t){for(const e of t)this.add(e);return this}has(t){return this._patterns.has(t.pattern)}get size(){return this._patterns.size}seal(){return this._sealed=!0,this}get isSealed(){return this._sealed}matchesAny(t){return null!==this.findMatch(t)}findMatch(t){const e=t.getDepth(),r=t.getCurrentTag(),n=`${e}:${r}`,s=this._byDepthAndTag.get(n);if(s)for(let e=0;e<s.length;e++)if(t.matches(s[e]))return s[e];const i=this._wildcardByDepth.get(e);if(i)for(let e=0;e<i.length;e++)if(t.matches(i[e]))return i[e];const a=this._deepByTerminalTag.get(r);if(a)for(let e=0;e<a.length;e++)if(t.matches(a[e]))return a[e];for(let e=0;e<this._deepWildcards.length;e++)if(t.matches(this._deepWildcards[e]))return this._deepWildcards[e];return null}}const Y={nameFor:{},skip:{},tags:{valueParsers:[]},attributes:{valueParsers:[]},textJoint:"",alwaysArray:[],forceArray:null,forceTextNode:!1},z=["ws","entity","boolean","number"],G=["entity","number","boolean"];function H(t){const e=W(Y);t&&void 0!==t.tags?.valueParsers||(e.tags.valueParsers=[...z]),t&&void 0!==t.attributes?.valueParsers||(e.attributes.valueParsers=[...G]);const r=Array.isArray(t?.alwaysArray)?t.alwaysArray:e.alwaysArray,n=new F;for(const t of r)J(t,"alwaysArray",n);return n.seal(),e._alwaysArraySet=n,t&&Q(e,t),e}function W(t){if(null===t||"object"!=typeof t)return t;if(Array.isArray(t))return t.map(W);const e={};for(const r of Object.keys(t))e[r]=W(t[r]);return e}function Q(t,e){for(const r of Object.keys(e))"__proto__"!==r&&"constructor"!==r&&"prototype"!==r&&("function"==typeof e[r]||Array.isArray(e[r])?t[r]=e[r]:"object"==typeof e[r]&&null!==e[r]?("object"==typeof t[r]&&null!==t[r]||(t[r]={}),Q(t[r],e[r])):t[r]=e[r])}function J(t,e,r){let n;if("string"==typeof t){if(0===t.length)throw new Error(`${e} expression cannot be empty`);n=t}else{if(!("string"==typeof t?.pattern&&t.pattern.length>0&&Array.isArray(t?.segments)))throw new Error(`Invalid ${e} entry: expected a string, or Expression.`);n=t.toString()}const s=new C(n);return r.add(s),s}const Z={amp:"&",apos:"'",gt:">",lt:"<",quot:'"'},K=Object.freeze({ALLOW:"allow",BLOCK:"block",THROW:"throw"}),tt=new Set("!?\\\\/[]$%{}^&*()<>|+");function et(t){if("#"===t[0])throw new Error(`[EntityReplacer] Invalid character '#' in entity name: "${t}"`);for(const e of t)if(tt.has(e))throw new Error(`[EntityReplacer] Invalid character '${e}' in entity name: "${t}"`);return t}function rt(...t){const e=Object.create(null);for(const r of t)if(r)for(const t of Object.keys(r)){const n=r[t];if("string"==typeof n)e[t]=n;else if(n&&"object"==typeof n&&void 0!==n.val){const r=n.val;"string"==typeof r&&(e[t]=r)}}return e}const nt="external",st="base",it="all",at=Object.freeze({allow:0,leave:1,remove:2,throw:3}),ot=new Set([9,10,13]);class lt{constructor(t={}){var e;this._limit=t.limit||{},this._maxTotalExpansions=this._limit.maxTotalExpansions||0,this._maxExpandedLength=this._limit.maxExpandedLength||0,this._postCheck="function"==typeof t.postCheck?t.postCheck:t=>t,this._limitTiers=(e=this._limit.applyLimitsTo??nt)&&e!==nt?e===it?new Set([it]):e===st?new Set([st]):Array.isArray(e)?new Set(e):new Set([nt]):new Set([nt]),this._numericAllowed=t.numericAllowed??!0,this._baseMap=rt(Z,t.namedEntities||null),this._externalMap=Object.create(null),this._inputMap=Object.create(null),this._totalExpansions=0,this._expandedLength=0,this._removeSet=new Set(t.remove&&Array.isArray(t.remove)?t.remove:[]),this._leaveSet=new Set(t.leave&&Array.isArray(t.leave)?t.leave:[]);const r=function(t){if(!t)return{xmlVersion:1,onLevel:at.allow,nullLevel:at.remove};const e=1.1===t.xmlVersion?1.1:1,r=at[t.onNCR]??at.allow,n=at[t.nullNCR]??at.remove;return{xmlVersion:e,onLevel:r,nullLevel:Math.max(n,at.remove)}}(t.ncr);this._ncrXmlVersion=r.xmlVersion,this._ncrOnLevel=r.onLevel,this._ncrNullLevel=r.nullLevel,this._onExternalEntity="function"==typeof t.onExternalEntity?t.onExternalEntity:null,this._onInputEntity="function"==typeof t.onInputEntity?t.onInputEntity:null}_applyRegistrationHook(t,e,r,n){if(!t)return!0;const s=t(e,r);if(s===K.BLOCK)return!1;if(s===K.THROW)throw new Error(`[EntityDecoder] Registration of ${n} entity "&${e};" was rejected by hook`);return!0}setExternalEntities(t){if(t)for(const e of Object.keys(t))et(e);if(!this._onExternalEntity)return void(this._externalMap=rt(t));const e=rt(t),r=Object.create(null);for(const[t,n]of Object.entries(e))this._applyRegistrationHook(this._onExternalEntity,t,n,"external")&&(r[t]=n);this._externalMap=r}addExternalEntity(t,e){et(t),"string"==typeof e&&-1===e.indexOf("&")&&this._applyRegistrationHook(this._onExternalEntity,t,e,"external")&&(this._externalMap[t]=e)}addInputEntities(t){if(this._totalExpansions=0,this._expandedLength=0,!this._onInputEntity)return void(this._inputMap=rt(t));const e=rt(t),r=Object.create(null);for(const[t,n]of Object.entries(e))this._applyRegistrationHook(this._onInputEntity,t,n,"input")&&(r[t]=n);this._inputMap=r}reset(){return this._inputMap=Object.create(null),this._totalExpansions=0,this._expandedLength=0,this}setXmlVersion(t){this._ncrXmlVersion=1.1===t?1.1:1}decode(t){if("string"!=typeof t||0===t.length)return t;if(-1===t.indexOf("&"))return t;const e=t,r=[],n=t.length;let s=0,i=0;const a=this._maxTotalExpansions>0,o=this._maxExpandedLength>0,l=a||o;for(;i<n;){if(38!==t.charCodeAt(i)){i++;continue}let e=i+1;for(;e<n&&59!==t.charCodeAt(e)&&e-i<=32;)e++;if(e>=n||59!==t.charCodeAt(e)){i++;continue}const c=t.slice(i+1,e);if(0===c.length){i++;continue}let h,u;if(this._removeSet.has(c))h="",void 0===u&&(u=nt);else{if(this._leaveSet.has(c)){i++;continue}if(35===c.charCodeAt(0)){const t=this._resolveNCR(c);if(void 0===t){i++;continue}h=t,u=st}else{const t=this._resolveName(c);h=t?.value,u=t?.tier}}if(void 0!==h){if(i>s&&r.push(t.slice(s,i)),r.push(h),s=e+1,i=s,l&&this._tierCounts(u)){if(a&&(this._totalExpansions++,this._totalExpansions>this._maxTotalExpansions))throw new Error(`[EntityReplacer] Entity expansion count limit exceeded: ${this._totalExpansions} > ${this._maxTotalExpansions}`);if(o){const t=h.length-(c.length+2);if(t>0&&(this._expandedLength+=t,this._expandedLength>this._maxExpandedLength))throw new Error(`[EntityReplacer] Expanded content length limit exceeded: ${this._expandedLength} > ${this._maxExpandedLength}`)}}}else i++}s<n&&r.push(t.slice(s));const c=0===r.length?t:r.join("");return this._postCheck(c,e)}_tierCounts(t){return!!this._limitTiers.has(it)||this._limitTiers.has(t)}_resolveName(t){return t in this._inputMap?{value:this._inputMap[t],tier:nt}:t in this._externalMap?{value:this._externalMap[t],tier:nt}:t in this._baseMap?{value:this._baseMap[t],tier:st}:void 0}_classifyNCR(t){return 0===t?this._ncrNullLevel:t>=55296&&t<=57343||1===this._ncrXmlVersion&&t>=1&&t<=31&&!ot.has(t)?at.remove:-1}_applyNCRAction(t,e,r){switch(t){case at.allow:return String.fromCodePoint(r);case at.remove:return"";case at.leave:return;case at.throw:throw new Error(`[EntityDecoder] Prohibited numeric character reference &${e}; (U+${r.toString(16).toUpperCase().padStart(4,"0")})`);default:return String.fromCodePoint(r)}}_resolveNCR(t){const e=t.charCodeAt(1);let r;if(r=120===e||88===e?parseInt(t.slice(2),16):parseInt(t.slice(1),10),Number.isNaN(r)||r<0||r>1114111)return;const n=this._classifyNCR(r);if(!this._numericAllowed&&n<at.remove)return;const s=-1===n?this._ncrOnLevel:Math.max(this._ncrOnLevel,n);return this._applyNCRAction(s,t,r)}}const ct=[{id:"sql-block-comment-open",description:"SQL block comment open: /* ... */ — unusual in legitimate user text",pattern:/\/\*/},{id:"sql-union-select",description:"UNION SELECT — most common SQL injection aggregation attack",pattern:/\bUNION\s{1,20}(?:ALL\s{1,20})?SELECT\b/i},{id:"sql-drop-table",description:"DROP TABLE — destructive DDL injection",pattern:/\bDROP\s{1,20}TABLE\b/i},{id:"sql-drop-database",description:"DROP DATABASE — destructive DDL injection",pattern:/\bDROP\s{1,20}DATABASE\b/i},{id:"sql-insert-into",description:"INSERT INTO — data injection",pattern:/\bINSERT\s{1,20}INTO\b/i},{id:"sql-delete-from",description:"DELETE FROM — data deletion injection",pattern:/\bDELETE\s{1,20}FROM\b/i},{id:"sql-update-set",description:"UPDATE ... SET — data modification injection",pattern:/\bUPDATE\b[\s\S]{1,60}\bSET\b/i},{id:"sql-exec-xp",description:"EXEC xp_ — MSSQL extended stored procedure execution",pattern:/\bEXEC(?:UTE)?\s{1,20}xp_/i},{id:"sql-tautology-string",description:'Classic string tautology: \' OR \'1\'=\'1 or " OR "1"="1"',pattern:/'\s{0,10}OR\s{0,10}'[^']{0,20}'\s*=\s*'[^']{0,20}/i},{id:"sql-tautology-numeric",description:"Numeric tautology: OR 1=1",pattern:/\bOR\s{1,10}1\s*=\s*1\b/i},{id:"sql-always-true-zero",description:"Numeric tautology: OR 0=0",pattern:/\bOR\s{1,10}0\s*=\s*0\b/i},{id:"sql-sleep-benchmark",description:"Time-based blind injection: SLEEP() or BENCHMARK()",pattern:/\b(?:SLEEP|BENCHMARK)\s*\(/i},{id:"sql-waitfor-delay",description:"MSSQL time-based blind injection: WAITFOR DELAY",pattern:/\bWAITFOR\s{1,20}DELAY\b/i},{id:"sql-char-function",description:"CHAR() function — used to obfuscate injected strings",pattern:/\bCHAR\s*\(\s*\d{1,3}/i},{id:"sql-information-schema",description:"INFORMATION_SCHEMA — reconnaissance query for table/column enumeration",pattern:/\bINFORMATION_SCHEMA\b/i}],ht="[\"'\\s]*:",ut={HTML:[{id:"html-script-open",description:"<script opening tag",pattern:/<script[\s>/]/i},{id:"html-script-close",description:"<\/script closing tag",pattern:/<\/script[\s>]/i},{id:"html-javascript-protocol",description:"javascript: URI scheme (with optional whitespace/encoding)",pattern:/j[\t\n\r ]*a[\t\n\r ]*v[\t\n\r ]*a[\t\n\r ]*s[\t\n\r ]*c[\t\n\r ]*r[\t\n\r ]*i[\t\n\r ]*p[\t\n\r ]*t[\t\n\r ]*:/i},{id:"html-vbscript-protocol",description:"vbscript: URI scheme",pattern:/vbscript[\t\n\r ]*:/i},{id:"html-data-html",description:"data:text/html URI — can execute scripts in browsers",pattern:/data[\t\n\r ]*:[\t\n\r ]*text\/html/i},{id:"html-data-xhtml",description:"data:application/xhtml+xml URI",pattern:/data[\t\n\r ]*:[\t\n\r ]*application\/xhtml/i},{id:"html-data-svg",description:"data:image/svg+xml URI — can execute scripts",pattern:/data[\t\n\r ]*:[\t\n\r ]*image\/svg\+xml/i},{id:"html-inline-event-handler",description:"Inline event handler attributes: onclick=, onerror=, onload=, etc.",pattern:/\bon\w{1,30}\s*=/i},{id:"html-entity-obfuscated-script",description:"HTML-entity-encoded <script (e.g. <script or <script)",pattern:/(?:�*3[Cc];?|�*60;?|<)\s*script/i},{id:"html-entity-obfuscated-javascript",description:'HTML-entity-encoded javascript: (partial — catches common j or j for "j")',pattern:/(?:�*6[Aa];?|�*106;?)\s*(?:�*61;?|a)[\s\S]{0,80}script\s*:/i},{id:"html-style-expression",description:"CSS expression() — IE-era code execution in style attributes",pattern:/style[\s\S]{0,20}expression\s*\(/i},{id:"html-object-embed",description:"<object or <embed tags that can load active content",pattern:/<(?:object|embed)[\s>/]/i},{id:"html-base-tag",description:"<base href= — can hijack all relative URLs on a page",pattern:/<base[\s>]/i},{id:"html-meta-refresh",description:'<meta http-equiv="refresh" — can redirect users',pattern:/<meta[\s\S]{0,40}http-equiv[\s\S]{0,20}refresh/i},{id:"html-srcdoc",description:"srcdoc= attribute on iframes — embeds HTML that can run scripts",pattern:/srcdoc\s*=/i},{id:"html-iframe",description:"<iframe tag",pattern:/<iframe[\s>/]/i},{id:"html-form",description:"<form tag — can be used for phishing / credential harvesting injection",pattern:/<form[\s>/]/i}],XML:[{id:"xml-cdata-injection",description:"CDATA section injection: <![CDATA[ breaks out of text node context",pattern:/<!\[CDATA\[/i},{id:"xml-cdata-close",description:"CDATA close sequence: ]]> can terminate an enclosing CDATA section",pattern:/\]\]>/},{id:"xml-processing-instruction",description:"XML processing instruction: <?xml-stylesheet or <?php etc.",pattern:/<\?(?:xml[\- ]|php|asp)/i},{id:"xml-doctype-injection",description:"DOCTYPE declaration embedded in content — can define entities",pattern:/<!DOCTYPE(?:[\s[]|$)/i},{id:"xml-entity-system",description:"SYSTEM keyword — used in external entity declarations (XXE)",pattern:/\bSYSTEM\s+["']/i},{id:"xml-entity-public",description:"PUBLIC keyword — used in external entity declarations (XXE)",pattern:/\bPUBLIC\s+["']/i},{id:"xml-entity-declaration",description:"<!ENTITY declaration — defines entities, potential XXE or entity expansion",pattern:/<!ENTITY[\s%]/i},{id:"xml-billion-laughs",description:"Entity reference chaining / billion laughs: repeated &eX; style references",pattern:/(?:&\w{1,20};){3,}/},{id:"xml-namespace-confusion",description:"xmlns: attribute injection — can redefine namespaces to confuse parsers",pattern:/\bxmlns\s*(?::\w{1,40})?\s*=/i},{id:"xml-comment-injection",description:"\x3c!-- comment injection — can hide content from some parsers",pattern:/<!--/},{id:"xml-comment-close",description:"--\x3e closes an enclosing XML comment",pattern:/-->/},{id:"xml-pi-close",description:"?> closes an enclosing processing instruction",pattern:/\?>/}],SVG:[{id:"svg-script-element",description:"<script element inside SVG executes JavaScript",pattern:/<script[\s>/]/i},{id:"svg-xlink-href-javascript",description:"xlink:href with javascript: — classic SVG XSS via <a> or <use>",pattern:/xlink\s*:\s*href\s*=\s*["']?\s*javascript\s*:/i},{id:"svg-href-javascript",description:"href= with javascript: in SVG context (<a>, <animate>, etc.)",pattern:/href\s*=\s*["']?\s*javascript\s*:/i},{id:"svg-foreignobject",description:"<foreignObject embeds HTML inside SVG — can execute scripts",pattern:/<foreignObject[\s>/]/i},{id:"svg-use-external",description:"<use xlink:href or href pointing to external resource (non-fragment URL)",pattern:/<use[\s\S]{0,60}(?:xlink\s*:\s*)?href\s*=\s*(?:["'][^#]|[^"'#\s>])/i},{id:"svg-animate-href",description:'<animate attributeName="href" — can dynamically change href to javascript:',pattern:/<animate[\s\S]{0,80}attributeName\s*=\s*["'][\s]*href["']/i},{id:"svg-animate-xlinkhref",description:'<animate attributeName="xlink:href"',pattern:/<animate[\s\S]{0,80}attributeName\s*=\s*["'][\s]*xlink\s*:\s*href["']/i},{id:"svg-set-javascript",description:'<set to="javascript:..." — sets an attribute to a javascript: URI',pattern:/<set[\s\S]{0,80}to\s*=\s*["']?\s*javascript\s*:/i},{id:"svg-event-handler",description:"SVG-specific event handler attributes: onload=, onerror=, onactivate=, etc.",pattern:/\bon(?:load|error|activate|begin|end|repeat|focus|blur|click|mouse\w{1,20}|key\w{1,20})\s*=/i},{id:"svg-handler-generic",description:"Generic on* handler catch-all for SVG attributes",pattern:/\bon\w{1,30}\s*=/i},{id:"svg-filter-feimage",description:"<feImage href= — filter primitive that can load external resources",pattern:/<feImage[\s\S]{0,80}(?:xlink\s*:\s*)?href\s*=/i},{id:"svg-image-external",description:"<image xlink:href with http/https or javascript protocol",pattern:/<image[\s\S]{0,80}(?:xlink\s*:\s*)?href\s*=\s*["']?\s*(?:https?|javascript)\s*:/i},{id:"svg-style-javascript",description:"style= attribute containing javascript: (e.g. background:url(javascript:...))",pattern:/style\s*=[\s\S]{0,60}javascript\s*:/i}],SQL:ct,"SQL-STRICT":[...ct,{id:"sql-line-comment",description:"SQL line comment: -- followed by whitespace or end of string",pattern:/--(?:\s|$)/},{id:"sql-stacked-query",description:"Stacked queries: semicolon immediately followed by a SQL keyword",pattern:/;\s{0,10}(?:SELECT|INSERT|UPDATE|DELETE|DROP|CREATE|ALTER|EXEC)\b/i},{id:"sql-hex-encoding",description:"Hex-encoded string injection: 0x41414141 style (MySQL)",pattern:/\b0x[0-9a-f]{4,}/i}],SHELL:[{id:"shell-path-traversal-unix",description:"Unix path traversal: ../ — climbing the directory tree",pattern:/\.\.\//},{id:"shell-path-traversal-windows",description:"Windows path traversal: ..\\ — climbing the directory tree",pattern:/\.\.\\/},{id:"shell-path-traversal-encoded",description:"URL-encoded path traversal: %2e%2e or %2f variants",pattern:/%2e%2e|%2f\.\.|\.\.%2f/i},{id:"shell-null-byte",description:"Null byte injection: \\x00 or %00 — truncates strings in C-backed functions",pattern:/\x00|%00/},{id:"shell-semicolon",description:"Semicolon command separator: cmd1; cmd2",pattern:/;/},{id:"shell-pipe",description:"Pipe operator: cmd1 | cmd2",pattern:/\|/},{id:"shell-and-operator",description:"AND operator: cmd1 && cmd2",pattern:/&&/},{id:"shell-or-operator",description:"OR operator: cmd1 || cmd2",pattern:/\|\|/},{id:"shell-backtick",description:"Backtick command substitution: `cmd`",pattern:/`/},{id:"shell-dollar-paren",description:"Dollar-paren command substitution: $(cmd)",pattern:/\$\(/},{id:"shell-dollar-brace",description:"Dollar-brace variable expansion: ${var} — can be abused for injection",pattern:/\$\{/},{id:"shell-redirect-out",description:"Output redirection: cmd > file or cmd >> file",pattern:/>{1,2}/},{id:"shell-redirect-in",description:"Input redirection: cmd < file",pattern:/</},{id:"shell-newline-injection",description:"Newline injection: \\n or \\r — can inject new shell commands",pattern:/[\n\r]/},{id:"shell-glob-star",description:"Glob expansion: * or ? — can expand to unintended files",pattern:/[/\\][*?]/},{id:"shell-absolute-root",description:"Absolute root path injection: string starting with / or \\ (Windows UNC)",pattern:/^(?:\/|\\\\)/},{id:"shell-windows-drive",description:"Windows drive letter path injection: C:\\ or D:/",pattern:/^[a-zA-Z]:[/\\]/},{id:"shell-curl-wget",description:"curl/wget with URL or flags — can exfiltrate data or download payloads",pattern:/\b(?:curl|wget)\s+(?:https?:\/\/|ftp:\/\/|-)/i}],REDOS:[{id:"redos-nested-quantifier-plus",description:"Nested + quantifier inside a group with outer quantifier: (a+)+, (.+b)*, etc.",pattern:/\([^)]*\+[^)]*\)[+*]/},{id:"redos-nested-quantifier-star",description:"Nested * quantifier: (a*)* or (a*)+ — catastrophic backtracking",pattern:/\([^)]*\*[^)]*\)[*+]/},{id:"redos-nested-groups",description:"Doubly nested quantified groups: ((a+)+) — guaranteed catastrophic",pattern:/\(\([^)]{0,40}\)[+*]\)[+*]/},{id:"redos-alternation-overlap",description:"Overlapping alternation under quantifier: (a|a)+ — ambiguous NFA paths",pattern:/\(([^|()]{1,20})\|(?:\1)(?:\|[^|()]{1,20}){0,5}\)[+*?]{1,2}/},{id:"redos-star-plus-concat",description:"(x*x)+ pattern — triggers super-linear backtracking",pattern:/\([^)]{0,10}\*[^)]{0,10}\)[+*]/},{id:"redos-dot-star-greedy",description:"(.*){n,} or (.+){n,} — repeated greedy dot quantifiers",pattern:/\(\.[*+]\)\{?\d/},{id:"redos-large-repetition",description:"Very large fixed or range repetition count {1000,} or {1000,n} — denial of service via backtracking",pattern:/\{\d{4,}(?:,\d*)?\}/},{id:"redos-catastrophic-alternation",description:"Long alternation with many similar branches — polynomial backtracking risk",pattern:/\([^)]{0,200}(?:\|[^|)]{0,50}){9,}\)/}],NOSQL:[{id:"nosql-where-operator",description:"$where — executes arbitrary JavaScript server-side in MongoDB",pattern:new RegExp(`\\$where${ht}`,"i")},{id:"nosql-ne-operator",description:'$ne — "not equal" operator used to bypass equality checks',pattern:new RegExp(`\\$ne${ht}`,"i")},{id:"nosql-gt-operator",description:'$gt — "greater than" used to bypass password/value checks',pattern:new RegExp(`\\$gte?${ht}`,"i")},{id:"nosql-lt-operator",description:'$lt / $lte — "less than" bypass variants',pattern:new RegExp(`\\$lte?${ht}`,"i")},{id:"nosql-regex-operator",description:"$regex — can be used to extract data character by character (blind injection)",pattern:new RegExp(`\\$regex${ht}`,"i")},{id:"nosql-or-operator",description:"$or — logical OR; used to create always-true conditions",pattern:new RegExp(`\\$or${ht}\\s*\\[`,"i")},{id:"nosql-and-operator",description:"$and — logical AND operator injection",pattern:new RegExp(`\\$and${ht}\\s*\\[`,"i")},{id:"nosql-nor-operator",description:"$nor — logical NOR operator injection",pattern:new RegExp(`\\$nor${ht}\\s*\\[`,"i")},{id:"nosql-exists-operator",description:"$exists — can enumerate fields to determine schema",pattern:new RegExp(`\\$exists${ht}`,"i")},{id:"nosql-in-operator",description:"$in — matches any value in a list; can enumerate values",pattern:new RegExp(`\\$in${ht}\\s*\\[`,"i")},{id:"nosql-expr-operator",description:"$expr — allows aggregation expressions in queries (MongoDB 3.6+)",pattern:new RegExp(`\\$expr${ht}`,"i")},{id:"nosql-function-operator",description:"$function — executes arbitrary JavaScript in MongoDB 4.4+",pattern:new RegExp(`\\$function${ht}`,"i")},{id:"nosql-accumulator-operator",description:"$accumulator — custom aggregation with arbitrary JS execution",pattern:new RegExp(`\\$accumulator${ht}`,"i")},{id:"nosql-proto-pollution",description:"__proto__ — prototype pollution via object key injection",pattern:/__proto__/},{id:"nosql-constructor-prototype",description:"constructor.prototype — alternative prototype pollution vector (dot notation or JSON key)",pattern:/constructor[\s"':.,{\[]*prototype/i},{id:"nosql-proto-bracket",description:'["__proto__"] — bracket-notation prototype pollution',pattern:/\[["']__proto__["']\]/}],LOG:[{id:"log-crlf-injection",description:"CRLF injection: literal \\r or \\n embeds fake log lines",pattern:/[\r\n]/},{id:"log-url-encoded-crlf",description:"URL-encoded CRLF: %0d, %0a, %0D, %0A — decoded by some log parsers",pattern:/%0[dDaA]/},{id:"log-unicode-newline",description:"Unicode newline variants: U+2028 (line separator), U+2029 (paragraph separator)",pattern:/[\u2028\u2029]/},{id:"log-log4shell-jndi",description:"Log4Shell: ${jndi:...} triggers remote code execution in Apache Log4j",pattern:/\$\{jndi\s*:/i},{id:"log-log4shell-obfuscated",description:"Obfuscated Log4Shell: ${::-j}... lookup-bypass prefix used to evade WAF detection",pattern:/\$\{::-/},{id:"log-log4j-lookup",description:"Log4j lookup syntax: ${env:...}, ${sys:...}, ${ctx:...} — data exfiltration",pattern:/\$\{(?:env|sys|ctx|main|map|sd|web|docker|k8s|spring)\s*:/i},{id:"log-ssti-double-brace",description:"SSTI double-brace: {{expression}} — Jinja2, Twig, Handlebars, etc.",pattern:/\{\{[\s\S]{0,80}\}\}/},{id:"log-ssti-hash-brace",description:"SSTI hash-brace: #{expression} — Thymeleaf, Velocity, Ruby ERB",pattern:/#\{[\s\S]{0,80}\}/},{id:"log-ssti-dollar-brace",description:"SSTI/EL injection: ${expression with operators or method calls} — JSP EL, Freemarker, SpEL",pattern:/\$\{[^}]*(?:\.|\(|\*|\+|\bclass\b|\bruntime\b|\bprocess\b|\bexec\b)[^}]{0,80}\}/i},{id:"log-ssti-percent-tag",description:"SSTI ERB/ASP tag: <%= expression %> — Ruby ERB, ASP",pattern:/<%=[\s\S]{0,80}%>/},{id:"log-null-byte",description:"Null byte: \\x00 or %00 — can truncate log entries in C-backed loggers",pattern:/\x00|%00/},{id:"log-ansi-escape",description:"ANSI escape sequence: ESC[ — can manipulate terminal output when logs are tailed",pattern:/\x1b\[/}]},dt=ut,pt=Object.freeze(Object.fromEntries(Object.keys(ut).map(t=>[t,t])));function ft(t,e){const r=dt[e];for(const n of r)if(n.pattern.test(t))return{context:e,id:n.id,description:n.description,pattern:n.pattern};return null}function gt(t,e){if(function(t){if("string"!=typeof t)throw new TypeError("is-unsafe: first argument must be a string, got "+typeof t)}(t),function(t){if(!(t instanceof RegExp))if("string"!=typeof t){if(!Array.isArray(t))throw new TypeError("is-unsafe: second argument must be a context string, array of context strings, or RegExp. Got: "+typeof t);if(0===t.length)throw new TypeError("is-unsafe: context array must not be empty");for(const e of t)if("string"!=typeof e||!dt[e])throw new TypeError(`is-unsafe: unknown context "${e}" in array. Valid contexts: ${Object.keys(pt).join(", ")}`)}else if(!dt[t])throw new TypeError(`is-unsafe: unknown context "${t}". Valid contexts: ${Object.keys(pt).join(", ")}`)}(e),e instanceof RegExp)return e.test(t);if("string"==typeof e)return null!==ft(t,e);for(const r of e)if(null!==ft(t,r))return!0;return!1}class mt{constructor(t=!1){this.IS_FINAL=t}init(t){this.ctx=t}reset(){}parse(t,e){throw new Error("You must implement parse() in a value parser.")}}const _t={namedEntities:{...Z},numericAllowed:!0,onInputEntity:(t,e)=>gt(e,[pt.XML])?K.BLOCK:K.ALLOW},Et=[48,1632,1776,2406,2534,2662,2790,2918,3046,3174,3302,3430,3558,3664,3792,3872,4160,4240,6112,6160,6470,6608,6784,6800,6992,7088,7232,7248,65296,120782,120792,120802,120812,120822,66720,68912,69734,69872,69942,70096,70384,70736,70864,71248,71360,71472,71904,72016,72688,72784,73040,73120,73552,92768,92864,93008,123200,123632,124144,125264,130032],bt=new Map,xt=1632,yt=new Uint8Array(63904).fill(255);for(const t of Et)for(let e=0;e<10;e++){const r=t+e;r<=65535?yt[r-xt]=e:bt.set(r,e)}const Tt=new Set([8722,65293,65123]),wt=/^[-+]?0x[a-fA-F0-9]+$/,vt=/^0b[01]+$/,It=/^0o[0-7]+$/,At=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,Nt={hex:!0,binary:!1,octal:!1,leadingZeros:!0,decimalPoint:".",eNotation:!0,infinity:"original",unicode:!1};function St(t,e={}){if(e=Object.assign({},Nt,e),!t||"string"!=typeof t)return t;let r=t.trim();if(0===r.length)return t;if(void 0!==e.skipLike&&e.skipLike.test(r))return t;if("0"===r)return 0;if(e.unicode&&(r=function(t){if("string"!=typeof t)return t;const e=t.length;if(0===e)return t;let r=-1;for(let n=0;n<e;n++){const s=t.charCodeAt(n);if(!(s>=48&&s<=57||45===s))if(s<xt){if(Tt.has(s)){r=n;break}}else if(s>=55296&&s<=56319){if(n+1<e){const e=t.charCodeAt(n+1);if(e>=56320&&e<=57343){const t=65536+(s-55296<<10)+(e-56320);if(bt.has(t)){r=n;break}}}}else if(255!==yt[s-xt]||Tt.has(s)){r=n;break}}if(-1===r)return t;const n=[];r>0&&n.push(t.slice(0,r));for(let s=r;s<e;s++){const r=t.charCodeAt(s);if(r>=48&&r<=57||45===r){n.push(t[s]);continue}if(r<xt){n.push(Tt.has(r)?"-":t[s]);continue}if(r>=55296&&r<=56319){if(s+1<e){const e=t.charCodeAt(s+1);if(e>=56320&&e<=57343){const t=65536+(r-55296<<10)+(e-56320),i=bt.get(t);if(void 0!==i){n.push(String.fromCharCode(i+48)),s++;continue}}}n.push(t[s]);continue}if(Tt.has(r)){n.push("-");continue}const i=yt[r-xt];n.push(255!==i?String.fromCharCode(i+48):t[s])}return n.join("")}(r),"0"===r))return 0;if(e.hex&&wt.test(r))return Dt(r,16);if(e.binary&&vt.test(r))return Dt(r,2);if(e.octal&&It.test(r))return Dt(r,8);if(isFinite(r)){if(r.includes("e")||r.includes("E"))return function(t,e,r){if(!r.eNotation)return t;const n=e.match(Ct);if(n){let s=n[1]||"";const i=-1===n[3].indexOf("e")?"E":"e",a=n[2],o=s?t[a.length+1]===i:t[a.length]===i;return a.length>1&&o?t:(1!==a.length||!n[3].startsWith(`.${i}`)&&n[3][0]!==i)&&a.length>0?r.leadingZeros&&!o?(e=(n[1]||"")+n[3],Number(e)):t:Number(e)}return t}(t,r,e);{const s=At.exec(r);if(s){const i=s[1]||"",a=s[2];let o=(n=s[3])&&-1!==n.indexOf(".")?("."===(n=n.replace(/0+$/,""))?n="0":"."===n[0]?n="0"+n:"."===n[n.length-1]&&(n=n.substring(0,n.length-1)),n):n;const l=i?"."===t[a.length+1]:"."===t[a.length];if(!e.leadingZeros&&(a.length>1||1===a.length&&!l))return t;{const n=Number(r),s=String(n);if(0===n)return n;if(-1!==s.search(/[eE]/))return e.eNotation?n:t;if(-1!==r.indexOf("."))return"0"===s||s===o||s===`${i}${o}`?n:t;let l=a?o:r;return a?l===s||i+l===s?n:t:l===s||l===i+s?n:t}}return t}}var n;return function(t,e,r){const n=e===1/0;switch(r.infinity.toLowerCase()){case"null":return null;case"infinity":return e;case"string":return n?"Infinity":"-Infinity";default:return t}}(t,Number(r),e)}const Ct=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;function Dt(t,e){const r=t.trim();if(2!==e&&8!==e||(t=r.substring(2)),parseInt)return parseInt(t,e);if(Number.parseInt)return Number.parseInt(t,e);if(window&&window.parseInt)return window.parseInt(t,e);throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}class Ot extends mt{constructor(t,e=!1){super(e),this.options=t||{}}parse(t){if("string"==typeof t){const e=St(t,this.options);if(typeof e!==t)return this.IS_FINAL?new Ut(e):e}return t}}const kt={entity:new class extends mt{#t=!1;#e=null;#r=null;constructor(t,e=!1){super(e),this.#r={..._t,...t||{},namedEntities:{..._t.namedEntities,...t?.namedEntities||{}}}}#n(){if(this.#e||(this.#e=new lt(this.#r)),!this.#t){const t=this.ctx?.get("xmlVersion"),e=this.ctx?.get("inputEntities");t&&this.#e.setXmlVersion(t),e&&this.#e.addInputEntities(e),this.#t=!0}}reset(){this.#t=!1,this.#e&&this.#e.reset()}parse(t){return"string"!=typeof t?t:(this.#n(),this.#e.decode(t))}},trim:new class extends mt{parse(t){return"string"==typeof t?t.trim():t}},ws:new class extends mt{constructor(t,e=!1){super(e);const r=t?.exclude??[],n=new F;for(const t of r)n.add("string"==typeof t?new C(t):t);n.seal(),this._excludeSet=n}parse(t,e){if("string"!=typeof t)return t;if(e){if(e.isAttribute)return t;if(e.matcher){if("preserve"===e.matcher.getAnyParentAttr("xml:space"))return t;if(this._excludeSet.size>0&&this._excludeSet.matchesAny(e.matcher))return t}}return t.replace(/[ \t\r\n]+/g," ").trim()}},boolean:new class extends mt{constructor(t,e,r=!1){super(r),this.trueList=t||["true"],this.falseList=e||["false"]}parse(t){if("string"==typeof t){const e=t.toLowerCase();if(-1!==this.trueList.indexOf(e))return!this.IS_FINAL||new Ut(!0);if(-1!==this.falseList.indexOf(e))return!!this.IS_FINAL&&new Ut(!1)}return t}},number:new Ot({hex:!0,leadingZeros:!0,eNotation:!0})};class Pt{constructor(){this.registered={...kt}}register(t,e){if(!t||"string"!=typeof t)throw new Error("name must be a string");if(!e)throw new Error("parser is required");if(!e.reset||"function"!=typeof e.reset)throw new Error("parser must implement reset()");if(!e.parse||"function"!=typeof e.parse)throw new Error("parser must implement parse()");this.registered[t]=e}reset(t){this.registered[t]?.reset()}resetAll(){for(const t in this.registered)this.registered[t]?.reset()}get(t){const e=this.registered[t];if(!e)throw new Error("parser not found: "+t);return e}}class Lt{constructor(t,e,r,n=!1){this.elementName=t,this.matcher=e,this.isLeafNode=r,this.isAttribute=n}}class Ut{constructor(t){this.value=t}}class Mt{#s={};set(t,e){this.#s[t]=e}get(t){return this.#s[t]}clear(){this.#s={}}}class Bt{constructor(t=[],e,r=null){this.valParsers=t,this.registry=e,this.sharedContext=r||new Mt,this._initAll(t)}run(t,e){for(let r=0;r<this.valParsers.length;r++){let n=this.valParsers[r];if("string"==typeof n&&(n=this.registry.get(n)),n){const r=n.parse(t,e);if(r instanceof Ut)return r.value;t=r}}return t}resetAll(){for(let t=0;t<this.valParsers.length;t++){let e=this.valParsers[t];"string"==typeof e&&(e=this.registry.get(e)),e&&e.reset&&"function"==typeof e.reset&&e.reset()}}register(t,e){this.registry.register(t,e),e.init&&e.init(this.sharedContext)}_initAll(t){if(!this.sharedContext)return;const e=new Set;for(const r of t){let t=r;"string"==typeof r&&(t=this.registry.get(r)),t&&"function"==typeof t.init&&!e.has(t)&&(e.add(t),t.init(this.sharedContext))}}}const Rt=["ws","entity","boolean","number"],$t=["entity","boolean","number"];class Vt{constructor(t,e,r,n,s=!0){this.matcher=r,this._rootName="^",this.parserOptions=t,this.builderOptions=e,this.registry=n;const i=e?.tags?.valueParsers??Rt,a=e?.attributes?.valueParsers??$t;this.sharedContext=new Mt,this.tagsPipeline=new Bt(i,this.registry,this.sharedContext),this.attrsPipeline=new Bt(a,this.registry,this.sharedContext),s&&(this.tagsPipeline.resetAll(),this.attrsPipeline.resetAll()),this._pendingStopNode=!1}addAttribute(t,e,r){"version"===t&&this.tagName===this._rootName&&this.sharedContext?.set("xmlVersion",+e);const n=`${this.parserOptions.attributes.prefix}${t}${this.parserOptions.attributes.suffix}`,s=new Lt(t,r,!0,!0);this.attributes[n]=this.attrsPipeline.run(e,s)}_addChild(t,e){}addComment(t){this.parserOptions.skip.comment||this.parserOptions.nameFor.comment&&this._addChild(this.parserOptions.nameFor.comment,t)}addLiteral(t){this.parserOptions.skip.cdata||(this.parserOptions.nameFor.cdata?this._addChild(this.parserOptions.nameFor.cdata,t):this.addRawValue(t||""))}addRawValue(t){this.addValue(t)}addInputEntities(t){this.sharedContext?.set("inputEntities",t)}addDeclaration(t){this.addInstruction(t)}addInstruction(t){}onStopNode(t,e){this._pendingStopNode=!0,"function"==typeof this.parserOptions.onStopNode&&this.parserOptions.onStopNode(t,e,this.matcher)}onExit(t){}}class jt{constructor(t={}){this.builderOptions=t,this.registry=new Pt}registerValueParser(t,e){this.registry.register(t,e)}getInstance(t,e){throw new Error("getInstance is not implemented")}}class Xt extends jt{constructor(t={}){super(),this.builderOptions=H(t)}getInstance(t,e){return new qt(t,this.builderOptions,e,this.registry)}}class qt extends Vt{constructor(t,e,r,n){super(t,e,r,n),this.parserOptions=t,this.builderOptions=e,this.tagsStack=[],this.root={},this.parent=this.root,this.tagName=this._rootName,this.value={},this.textValue="",this.attributes={},this.hasAttributes=!1}_buildAttributeValue(){return Ft(this.attributes)?(this.hasAttributes=!1,""):(this.hasAttributes=!0,this.parserOptions.attributes.groupBy?{[this.parserOptions.attributes.groupBy]:this.attributes}:this.attributes)}addElement(t){const e=this._buildAttributeValue();this.tagsStack.push([this.tagName,this.textValue,this.value,this.hasAttributes]),this.tagName=t.name,this.value=e,this.textValue="",this.attributes={}}_resolveForceArray(t){let e,r;if(this.builderOptions._alwaysArraySet.matchesAny(this.matcher)&&(e=!0),"function"==typeof this.builderOptions.forceArray){const e=this.builderOptions.forceArray(this.matcher,t);!0===e?r=!0:!1===e&&(r=!1)}return!1!==e&&!1!==r&&(!0===e||!0===r)}closeElement(){const t=this.tagName;let e=this.value;const r=this.textValue,n=this.hasAttributes,s="object"!=typeof e||Array.isArray(e)||Ft(e)||n,i=new Lt(t,this.matcher,s,!1);if(s){const t=this._pendingStopNode?r:this.tagsPipeline.run(r,i);n?(""!==t&&null!=t||this.builderOptions.forceTextNode)&&(e[this.parserOptions.nameFor.text]=t):e=this.builderOptions.forceTextNode?{[this.parserOptions.nameFor.text]:t}:t}else if(r.length>0||this.builderOptions.forceTextNode){const t=this._pendingStopNode?r:this.tagsPipeline.run(r,i);e[this.parserOptions.nameFor.text]=t}let a={tagName:t,value:e};const o=this.tagsStack.pop();let l=o[2];const c=this._resolveForceArray(s);l=this._addChildTo(a.tagName,a.value,l,c),this.tagName=o[0],this.textValue=o[1],this.value=l,this.hasAttributes=o[3],this._pendingStopNode=!1}_addChild(t,e){"string"==typeof this.value&&(this.value={[this.parserOptions.nameFor.text]:this.value}),this._addChildTo(t,e,this.value,!1),this.attributes={}}_addChildTo(t,e,r,n){return"string"==typeof r&&(r={}),Object.prototype.hasOwnProperty.call(r,t)?(Array.isArray(r[t])||(r[t]=[r[t]]),r[t].push(e)):r[t]=n?[e]:e,r}addValue(t){this.textValue.length>0?this.textValue+=`${this.builderOptions.textJoint}${t}`:this.textValue=t}addInstruction(t){const e=this._buildAttributeValue();this._addChild(t,e),this.attributes={}}onExit(t){}getOutput(){return this.value}}function Ft(t){return 0===Object.keys(t).length}class Yt extends Error{constructor(t,e,r={}){super(t),this.name="ParseError",this.code=e,this.index=r.index??void 0}toString(){const t=this._posStr();return t?`${this.name} [${this.code}] at ${t}: ${this.message}`:`${this.name} [${this.code}]: ${this.message}`}_posStr(){return void 0!==this.index?`index ${this.index}`:null}}const zt=Object.freeze({INVALID_INPUT:"INVALID_INPUT",INVALID_STREAM:"INVALID_STREAM",ALREADY_STREAMING:"ALREADY_STREAMING",NOT_STREAMING:"NOT_STREAMING",DATA_MUST_BE_STRING:"DATA_MUST_BE_STRING",UNEXPECTED_END:"UNEXPECTED_END",UNEXPECTED_CLOSE_TAG:"UNEXPECTED_CLOSE_TAG",MISMATCHED_CLOSE_TAG:"MISMATCHED_CLOSE_TAG",UNEXPECTED_TRAILING_DATA:"UNEXPECTED_TRAILING_DATA",INVALID_TAG:"INVALID_TAG",UNCLOSED_QUOTE:"UNCLOSED_QUOTE",INVALID_ATTRIBUTE_NAME:"INVALID_ATTRIBUTE_NAME",MULTIPLE_NAMESPACES:"MULTIPLE_NAMESPACES",ILLEGAL_CHARACTER:"ILLEGAL_CHARACTER",DUPLICATE_ATTRIBUTE:"DUPLICATE_ATTRIBUTE",UNQUOTED_ATTRIBUTE_VALUE:"UNQUOTED_ATTRIBUTE_VALUE",BOOLEAN_ATTRIBUTE_REJECTED:"BOOLEAN_ATTRIBUTE_REJECTED",SECURITY_PROTOTYPE_POLLUTION:"SECURITY_PROTOTYPE_POLLUTION",SECURITY_RESERVED_OPTION:"SECURITY_RESERVED_OPTION",SECURITY_RESTRICTED_NAME:"SECURITY_RESTRICTED_NAME",LIMIT_MAX_NESTED_TAGS:"LIMIT_MAX_NESTED_TAGS",LIMIT_MAX_ATTRIBUTES:"LIMIT_MAX_ATTRIBUTES",ENTITY_MAX_COUNT:"ENTITY_MAX_COUNT",ENTITY_MAX_SIZE:"ENTITY_MAX_SIZE",ENTITY_MAX_EXPANSIONS:"ENTITY_MAX_EXPANSIONS",ENTITY_MAX_EXPANDED_LENGTH:"ENTITY_MAX_EXPANDED_LENGTH",ENTITY_INVALID_KEY:"ENTITY_INVALID_KEY",ENTITY_INVALID_VALUE:"ENTITY_INVALID_VALUE",UNSUPPORTED_ENCODING:"UNSUPPORTED_ENCODING",INVALID_DECODER:"INVALID_DECODER",ENCODING_MISMATCH:"ENCODING_MISMATCH"});function Gt(t){return" "===t||"\t"===t||"\n"===t||"\r"===t||"\f"===t}function Ht(t){return 32===t||9===t||10===t||13===t||12===t}const Wt=["hasOwnProperty","toString","valueOf","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__","toLocaleString","isPrototypeOf","propertyIsEnumerable"],Qt=["__proto__","constructor","prototype"];function Jt(t){return t.startIndex+(t._baseOffset||0)}function Zt(t){return{index:Jt(t)}}function Kt(t){return t<=8||11===t||12===t||t>=14&&t<=31}function te(t,e){const r=t.length;let n=!1;for(let s=0;s<r;s++){const r=t.charCodeAt(s);if(Kt(r))throw new Yt(`Illegal control character 0x${r.toString(16).padStart(2,"0")} in document content`,zt.ILLEGAL_CHARACTER,e?Zt(e):{});13===r&&(n=!0)}if(!n)return t;let s="",i=0;for(let e=0;e<r;e++)13===t.charCodeAt(e)&&(s+=t.substring(i,e)+"\n",10===t.charCodeAt(e+1)&&e++,i=e+1);return s+=t.substring(i),s}function ee(t,e,r,n=!1){const s=e.length;if(!t.canRead(s))throw new Yt(`Unexpected end of source reading ${r}`,zt.UNEXPECTED_END,Zt(t));if(!0!==t.matchAhead(e,n))throw new Yt(`Invalid ${r}`,zt.INVALID_TAG,Zt(t));t.updateBufferBoundary(s)}function re(t,e,r){if(!t.canRead(e))throw new Yt(`Unexpected end of source reading ${r}`,zt.UNEXPECTED_END,Zt(t))}const ne=t=>Wt.includes(t)?"__"+t:t,se={skip:{declaration:!1,pi:!1,attributes:!0,cdata:!1,comment:!1,nsPrefix:!1,tags:[],whitespaceText:!0},nameFor:{text:"#text",cdata:"",comment:""},attributes:{booleanType:"allow",duplicate:"overwrite",groupBy:"",prefix:"@_",suffix:""},tags:{unpaired:[],stopNodes:[]},strictReservedNames:!1,onDangerousProperty:ne,sanitizeNames:!0,only:[],doctypeOptions:{enabled:!1,maxEntityCount:100,maxEntitySize:1e4},autoClose:null,limits:{maxNestedTags:null,maxAttributesPerTag:null},feedable:{maxBufferSize:10485760,autoFlush:!0,flushThreshold:1024,bufferSize:256},exitIf:()=>!1,OutputBuilder:null,decoding:{encoding:"auto",customDecoders:null}},ie=new Set([...Qt,...Wt]);function ae(t,e){if("string"==typeof t&&""!==t&&ie.has(t))throw new Yt(`SECURITY: '${t}' is a reserved JavaScript keyword and cannot be used as ${e}`,zt.SECURITY_RESERVED_OPTION)}const oe=function(t){if(t&&(t.nameFor?.text&&ae(t.nameFor.text,"nameFor.text"),t.nameFor?.cdata&&ae(t.nameFor.cdata,"nameFor.cdata"),t.nameFor?.comment&&ae(t.nameFor.comment,"nameFor.comment"),t.attributes?.prefix&&ae(t.attributes.prefix,"attributes.prefix"),t.attributes?.groupBy&&ae(t.attributes.groupBy,"attributes.groupBy"),void 0!==t.limits&&null!==t.limits)){if("object"!=typeof t.limits)throw new Yt("'limits' must be an object, got "+typeof t.limits,zt.INVALID_INPUT);const{maxNestedTags:e,maxAttributesPerTag:r}=t.limits;if(null!=e&&("number"!=typeof e||!Number.isInteger(e)||e<1))throw new Yt(`'limits.maxNestedTags' must be a positive integer, got ${e}`,zt.INVALID_INPUT);if(null!=r&&("number"!=typeof r||!Number.isInteger(r)||r<0))throw new Yt(`'limits.maxAttributesPerTag' must be a non-negative integer, got ${r}`,zt.INVALID_INPUT)}const e=he(se);if(t&&ue(e,t),e.OutputBuilder||(e.OutputBuilder=new Xt),Array.isArray(e.tags?.stopNodes)){const t=new F;e.tags.stopNodes=e.tags.stopNodes.map(e=>ce(e,"stopNodes",t)),t.seal(),e.tags.stopNodesSet=t}if(Array.isArray(e.skip?.tags)){const t=new F;e.skip.tags=e.skip.tags.map(e=>ce(e,"skip.tags",t)),t.seal(),e.skip.tagsSet=t}if(null===e.onDangerousProperty&&(e.onDangerousProperty=ne),null!==e.exitIf&&void 0!==e.exitIf&&"function"!=typeof e.exitIf)throw new Yt("'exitIf' must be a function, got "+typeof e.exitIf,zt.INVALID_INPUT);return e.autoClose=function(t,e){if(!t)return null;if("html"===t){const t=e.tags.unpaired||[],r=[...new Set([...t,...le])];return e.tags={...e.tags,unpaired:r},{onEof:"closeAll",onMismatch:"discard",collectErrors:!0}}return"string"==typeof t?{onEof:t,onMismatch:"throw",collectErrors:!1}:"object"==typeof t?{onEof:t.onEof||"throw",onMismatch:t.onMismatch||"throw",collectErrors:t.collectErrors||!1}:null}(e.autoClose,e),e},le=["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"];function ce(t,e,r){let n,s,i;if("string"==typeof t){if(0===t.length)throw new Yt(`${e} expression cannot be empty`,zt.INVALID_INPUT);n=t,s=!1,i=[]}else if(t instanceof C)n=t.toString(),s=t.data?.nested??!1,i=t.data?.skipEnclosures??[];else{if(!t||"object"!=typeof t||void 0===t.expression)throw new Yt(`Invalid ${e} entry: expected a string, Expression, or { expression, nested?, skipEnclosures? } object.`,zt.INVALID_INPUT);{const r=t.expression;if("string"==typeof r){if(0===r.length)throw new Yt(`${e} expression cannot be empty`,zt.INVALID_INPUT);n=r}else{if(!(r instanceof C))throw new Yt(`${e} expression must be a string or Expression instance`,zt.INVALID_INPUT);n=r.toString()}s=!0===t.nested,i=Array.isArray(t.skipEnclosures)?t.skipEnclosures:[]}}const a=new C(n,{},{nested:s,skipEnclosures:i});return r.add(a),a}function he(t){if(null===t||"object"!=typeof t)return t;if(Array.isArray(t))return t.map(he);if(t instanceof RegExp)return t;if(t instanceof C)return t;const e={};for(const r of Object.keys(t))e[r]="function"==typeof t[r]?t[r]:he(t[r]);return e}function ue(t,e){for(const r of Object.keys(e))"__proto__"!==r&&"constructor"!==r&&"prototype"!==r&&("OutputBuilder"===r||"function"==typeof e[r]||e[r]instanceof RegExp||Array.isArray(e[r])?t[r]=e[r]:"object"==typeof e[r]&&null!==e[r]?("object"==typeof t[r]&&null!==t[r]||(t[r]={}),ue(t[r],e[r])):t[r]=e[r])}function de(){const t=this.buffer,e=t.length,r=this.startIndex,n=this._quotePairs,s=n.length;let i=0,a=!1,o=!1;for(let l=r;l<e;l++){const e=t[l];if("'"===e)o||(a=!a,i<s&&(n[i++]=l-r));else if('"'===e)a||(o=!o,i<s&&(n[i++]=l-r));else if(">"===e&&!a&&!o)return this._quotePairsLen=i,l-r}return this._quotePairsLen=i,-1}function pe(){const t=this.buffer,e=t.length,r=this.startIndex;let n=!1,s=!1;for(let i=r;i<e;i++){const e=t[i];if("'"===e)s||(n=!n);else if('"'===e)n||(s=!s);else if(">"===e&&!n&&!s)return i-r}return-1}class fe{constructor(t,e={}){this.buffer=t,this.startIndex=0,this._baseOffset=0,this.autoFlush=!1!==e.autoFlush,this.flushThreshold=e.flushThreshold??1024,this._marks=[-1,-1],this._quotePairs=new Int32Array(128),this._quotePairsLen=0}markTokenStart(t=0){this._marks[t]=this.startIndex}rewindToMark(){}clearMark(){this._marks[0]=-1,this._marks[1]=-1}flush(){let t=this.startIndex;for(const e of this._marks)e>=0&&e<t&&(t=e);if(t>0){this.buffer=this.buffer.substring(t);const e=this._marks.length;for(let r=0;r<e;r++)this._marks[r]>=0&&(this._marks[r]-=t);this.startIndex-=t,this._baseOffset+=t}}readCh(){return this.buffer[this.startIndex++]}readChAt(t){return this.buffer[this.startIndex+t]}readStr(t,e){return void 0===e&&(e=this.startIndex),this.buffer.substring(e,e+t)}matchAhead(t,e=!1){const r=t.length;for(let n=0;n<r;n++){let r=this.buffer[this.startIndex+n];if(void 0===r)return null;if(e&&(r=r.toLowerCase()),r!==t[n])return!1}return!0}scanTagExpEnd=de;scanTagExpEndFast=pe;readUpto(t){const e=this.buffer.length,r=t.length;for(let n=this.startIndex;n<e;n++){let e=!0;for(let s=0;s<r;s++)if(this.buffer[n+s]!==t[s]){e=!1;break}if(e){const t=this.buffer.substring(this.startIndex,n);return this.startIndex=n+r,t}}throw new Yt(`Unexpected end of source reading '${t}'`,zt.UNEXPECTED_END)}readUptoChar(t){const e=this.buffer.indexOf(t,this.startIndex);if(-1===e)throw new Yt(`Unexpected end of source reading '${t}'`,zt.UNEXPECTED_END);const r=this.buffer.substring(this.startIndex,e);return this.startIndex=e+1,r}readUptoCloseTag(t){const e=this.buffer.length,r=t.length;let n=-1,s=0;for(let i=this.startIndex;i<e;i++){if(1===s){const t=this.buffer[i];if(Gt(t))continue;">"===t?s=2:(s=0,n=-1)}else{let e=!0;for(let n=0;n<r;n++)if(this.buffer[i+n]!==t[n]){e=!1;break}e&&(s=1,n=i,i+=r-1)}if(2===s){const t=this.buffer.substring(this.startIndex,n);return this.startIndex=i+1,t}}throw new Yt(`Unexpected end of source reading '${t}'`,zt.UNEXPECTED_END)}readFromBuffer(t,e){const r=1===t?this.buffer[this.startIndex]:this.buffer.substring(this.startIndex,this.startIndex+t);return e&&this.updateBufferBoundary(t),r}updateBufferBoundary(t=1){this.startIndex+=t,this.autoFlush&&this.startIndex>=this.flushThreshold&&this.flush()}canRead(t=0){return this.startIndex+t<this.buffer.length}}function ge(t,e="utf8",r=()=>!1){return{readCh(){const{char:e,width:r}=t(this.buffer,this.startIndex);return this.startIndex+=r,e},readChAt(e){return t(this.buffer,this.startIndex+e).char},readStr(t,r){return void 0===r&&(r=this.startIndex),this.buffer.slice(r,r+t).toString(e)},matchAhead(t,e=!1){const r=t.length;for(let n=0;n<r;n++){const r=this.buffer[this.startIndex+n];if(void 0===r)return null;let s=r;if(e&&s>=65&&s<=90&&(s+=32),s!==t.charCodeAt(n))return!1}return!0},scanTagExpEnd(){const t=this.buffer,e=t.length,r=this.startIndex,n=this._quotePairs,s=n.length;let i=0,a=!1,o=!1;for(let l=r;l<e;l++){const e=t[l];if(39===e)o||(a=!a,i<s&&(n[i++]=l-r));else if(34===e)a||(o=!o,i<s&&(n[i++]=l-r));else if(62===e&&!a&&!o)return this._quotePairsLen=i,l-r}return this._quotePairsLen=i,-1},scanTagExpEndFast(){const t=this.buffer,e=t.length,r=this.startIndex;let n=!1,s=!1;for(let i=r;i<e;i++){const e=t[i];if(39===e)s||(n=!n);else if(34===e)n||(s=!s);else if(62===e&&!n&&!s)return i-r}return-1},readUpto(t){const r=this.buffer.length,n=t.length,s=Buffer.from(t);for(let t=this.startIndex;t<r;t++){let r=!0;for(let e=0;e<n;e++)if(this.buffer[t+e]!==s[e]){r=!1;break}if(r){const r=this.buffer.slice(this.startIndex,t).toString(e);return this.startIndex=t+n,r}}throw new Yt(`Unexpected end of source reading '${t}'`,zt.UNEXPECTED_END)},readUptoChar(t){const r=t.charCodeAt(0),n=this.buffer,s=n.length;for(let t=this.startIndex;t<s;t++)if(n[t]===r){const r=n.slice(this.startIndex,t).toString(e);return this.startIndex=t+1,r}throw new Yt(`Unexpected end of source reading '${t}'`,zt.UNEXPECTED_END)},readUptoCloseTag(t){const r=this.buffer.length,n=t.length,s=Buffer.from(t);let i=-1,a=0;for(let t=this.startIndex;t<r;t++){const r=this.buffer[t];if(1===a){if(Ht(r))continue;62===r?a=2:(a=0,i=-1)}else{let e=!0;for(let r=0;r<n;r++)if(this.buffer[t+r]!==s[r]){e=!1;break}e&&(a=1,i=t,t+=n-1)}if(2===a){const r=this.buffer.slice(this.startIndex,i).toString(e);return this.startIndex=t+1,r}}throw new Yt(`Unexpected end of source reading '${t}'`,zt.UNEXPECTED_END)},readFromBuffer(r,n){if(1===r){const{char:e,width:r}=t(this.buffer,this.startIndex);return n&&this.updateBufferBoundary(r),e}const s=this.buffer.slice(this.startIndex,this.startIndex+r).toString(e);return n&&this.updateBufferBoundary(r),s},updateBufferBoundary(t=1){this.startIndex+=t,this.autoFlush&&this.startIndex>=this.flushThreshold&&this._tokenStart<0&&this.flush()},canRead(t=0){return this.startIndex+t<this.buffer.length}}}function me(t,e){return{char:String.fromCharCode(t[e]),width:1}}function _e(t,e){const r=t[e];let n=1;return 128&r?192==(224&r)?n=2:224==(240&r)?n=3:240==(248&r)&&(n=4):n=1,e+n>t.length&&(n=t.length-e),{char:t.toString("utf8",e,e+n),width:n}}const Ee=ge(_e,"utf8");class be{constructor(t,e={},r=null){if(this.buffer=r?.bomLength?t.subarray(r.bomLength):t,r?.decodeFirst){const t=r.descriptor.createDecoder();this.buffer=t.write(this.buffer)+t.end()}this.startIndex=0,this._baseOffset=0,this.autoFlush=!1!==e.autoFlush,this.flushThreshold=e.flushThreshold??1024,this._tokenStart=-1,this._quotePairs=new Int32Array(128),this._quotePairsLen=0;const n=r?.scanStrategy??Ee;Object.assign(this,n),this.encodingName=r?.descriptor?.name??"utf8",this._quotePairsUsable=!!r&&!1!==r.quotePairsUsable}markTokenStart(){this._tokenStart=this.startIndex}rewindToMark(){}flush(){const t=this._tokenStart>=0?this._tokenStart:this.startIndex;t>0&&(this.buffer=Buffer.from(this.buffer.subarray(t)),this._tokenStart>=0?(this.startIndex-=t,this._tokenStart=0):this.startIndex=0,this._baseOffset+=t)}}function xe(t,e){const r=function(t,e){for(const r of e.bomCandidates()){const e=r.bomBytes;if(t.length>=e.length&&e.equals(t.subarray(0,e.length)))return{descriptor:r,bomLength:e.length}}return null}(t,e),n=function(t,e){const r=t.subarray(e,Math.min(t.length,e+200)).toString("latin1").match(/^\s*<\?xml\s+[^?]*\?>/);if(!r)return null;const n=r[0].match(/encoding\s*=\s*["']([^"']+)["']/i);return n?n[1].toLowerCase():null}(t,r?r.bomLength:0);if(r&&n&&!function(t,e,r){try{return r.resolve(t).name===r.resolve(e).name}catch{return!1}}(r.descriptor.name,n,e))throw new Yt(`Byte-order mark indicates "${r.descriptor.name}" but the XML declaration says encoding="${n}"`,zt.ENCODING_MISMATCH);return r?{encoding:r.descriptor.name,bomLength:r.bomLength,declaredEncoding:n}:n?{encoding:n,bomLength:0,declaredEncoding:n}:{encoding:"utf8",bomLength:0,declaredEncoding:null}}function ye(t){const e=new TextDecoder(t,{fatal:!1,ignoreBOM:!0});return{write:t=>e.decode(t,{stream:!0}),end:()=>e.decode()}}class Te{constructor(){this._byName=new Map,this._seedDefaults()}_seedDefaults(){this.register({name:"utf8",aliases:["utf-8"],bomBytes:Buffer.from([239,187,191]),selfSynchronizing:!0,variableWidth:!0,createDecoder:()=>ye("utf-8")}),this.register({name:"ascii",aliases:[],bomBytes:null,selfSynchronizing:!0,variableWidth:!1,createDecoder:()=>ye("windows-1252")}),this.register({name:"latin1",aliases:["iso-8859-1","binary"],bomBytes:null,selfSynchronizing:!0,variableWidth:!1,createDecoder:()=>ye("iso-8859-1")}),this.register({name:"utf16le",aliases:["utf-16le","ucs2","ucs-2"],bomBytes:Buffer.from([255,254]),selfSynchronizing:!1,variableWidth:!0,createDecoder:()=>ye("utf-16le")}),this.register({name:"utf16be",aliases:["utf-16be"],bomBytes:Buffer.from([254,255]),selfSynchronizing:!1,variableWidth:!0,createDecoder:()=>function(){const t=ye("utf-16le");let e=null;return{write(r){let n=e?function(t,e){const r=new Uint8Array(t.length+e.length);return r.set(t,0),r.set(e,t.length),r}(e,r):r;e=null,n.length%2==1&&(e=n.subarray(n.length-1),n=n.subarray(0,n.length-1));const s=function(t){const e=new Uint8Array(t);for(let t=0;t+1<e.length;t+=2){const r=e[t];e[t]=e[t+1],e[t+1]=r}return e}(n);return t.write(s)},end:()=>t.end()}}()})}register(t){if(!t||"string"!=typeof t.name||!t.name)throw new Yt('Encoding descriptor requires a non-empty "name"',zt.INVALID_DECODER);if("function"!=typeof t.createDecoder)throw new Yt(`Encoding "${t.name}" is missing createDecoder()`,zt.INVALID_DECODER);const e=t.createDecoder();if(!e||"function"!=typeof e.write||"function"!=typeof e.end)throw new Yt(`Encoding "${t.name}"'s createDecoder() must return an object with write()/end()`,zt.INVALID_DECODER);const r={selfSynchronizing:!1,variableWidth:!0,aliases:[],bomBytes:null,...t};this._byName.set(r.name.toLowerCase(),r);for(const t of r.aliases)this._byName.set(t.toLowerCase(),r)}resolve(t){const e=this._byName.get(String(t).toLowerCase());if(!e)throw new Yt(`Unsupported encoding "${t}"`,zt.UNSUPPORTED_ENCODING);return e}bomCandidates(){const t=new Set,e=[];for(const r of this._byName.values())r.bomBytes&&!t.has(r.name)&&(t.add(r.name),e.push(r));return e.sort((t,e)=>e.bomBytes.length-t.bomBytes.length)}}const we=new Te;function ve(t){return t<=8||11===t||12===t||t>=14&&t<=31}function Ie(t,e,r,n){let s="",i=e;for(;e<r;e++){const r=t.charCodeAt(e);if(13===r)s+=t.substring(i,e)+" ",10===t.charCodeAt(e+1)&&e++,i=e+1;else if(10===r||9===r)s+=t.substring(i,e)+" ",i=e+1;else if(ve(r))throw new Yt(`Illegal control character 0x${r.toString(16).padStart(2,"0")} in attribute value`,zt.ILLEGAL_CHARACTER,n?Zt(n.source):{})}return s+=t.substring(i,e),s}function Ae(t,e,r,n){if(!t||0===t.length)return;const s=e.options.limits?.maxAttributesPerTag;if(null!=s&&n>s){const t=e.currentTagDetail?.name??"(unknown)";throw new Yt(`Tag '${t}' has ${n} attributes, exceeding limit of ${s}`,zt.LIMIT_MAX_ATTRIBUTES,Zt(e.source))}const i=t.length;for(let n=0;n<i;n++){const s=t[n],i=void 0!==r?{index:r+s.index}:void 0;e.outputBuilder.addAttribute(s.name,s.value,e.readonlyMatcher,i)}}class Ne{constructor(){this.tagName="",this.selfClosing=!1,this.rawAttributes={},this._attrsExp="",this._attrsExpStart=void 0,this._rawAttrMatchCount=0,this._parsedAttrs=[]}}function Se(t){t.source.markTokenStart(1);const e=Jt(t.source),r=!t.options.skip.attributes,n=r?t.source.scanTagExpEnd():t.source.scanTagExpEndFast();if(-1===n)throw new Yt("Unexpected closing of source waiting for '>'",zt.UNEXPECTED_END);const s=t.source.readStr(n);t.source.updateBufferBoundary(n+1);const i=r&&!1!==t.source._quotePairsUsable;return Ce(s,t,e,!1,i?t.source._quotePairs:void 0,i?t.source._quotePairsLen:0)}function Ce(t,e,r,n=!1,s=void 0,i=0){const a=new Ne;"/"===t[t.length-1]&&(a.selfClosing=!0,t=t.slice(0,-1));let o,l="",c=0;for(;c<t.length;c++)if(Gt(t[c])){a.tagName=t.substring(0,c),l=t.substring(c+1),o=c+1,void 0!==r&&(a._attrsExpStart=r+c+1);break}if(0===a.tagName.length&&c===t.length&&(a.tagName=t),a.tagName=a.tagName.trimEnd(),a._attrsExp=l,!e.isValidQName(a.tagName))throw new Yt("Invalid tag name",zt.INVALID_TAG_NAME);return(n||l.length>0)&&function(t,e,r,n,s,i){if(!t||0===t.length)return;const a=function(t,e,r,n=0,s){const i=[],a=t.length;let o=0;const l=void 0!==e&&n>0;let c=0;for(;o<a;){for(;o<a&&Ht(t.charCodeAt(o));)o++;if(o>=a)break;const h=o;for(;o<a&&61!==t.charCodeAt(o)&&!Ht(t.charCodeAt(o));)o++;const u=t.substring(h,o);for(;o<a&&Ht(t.charCodeAt(o));)o++;if(o>=a||61!==t.charCodeAt(o)){i.push({name:u,value:void 0,startIndex:h});continue}for(o++;o<a&&Ht(t.charCodeAt(o));)o++;const d=t.charCodeAt(o);if(34!==d&&39!==d)throw new Yt(`Attribute '${u}' has an unquoted value — attribute values must be wrapped in '"' or "'"`,zt.UNQUOTED_ATTRIBUTE_VALUE,s?Zt(s.source):{});let p,f=-1;if(l&&c+1<n&&e[c]===o+r&&(f=e[c+1]-r,c+=2),o++,f>=0)p=f;else for(p=o;p<a&&t.charCodeAt(p)!==d;)p++;const g=Ie(t,o,p,s);o=p+1,i.push({name:u,value:g,startIndex:h})}return i}(t,n,s,i,e),o=a.length;r._rawAttrMatchCount=o;const l=[];let c=0;const h=e.options.attributes?.duplicate||"overwrite",u="overwrite"!==h?new Set:null,d=e.options.attributes?.booleanType||"allow";for(let t=0;t<o;t++){const n=a[t];if(u){if(u.has(n.name)){if("throw"===h)throw new Yt(`Duplicate attribute '${n.name}'`,zt.DUPLICATE_ATTRIBUTE,Zt(e.source));continue}u.add(n.name)}const s=n.value;if(void 0===s){if("throw"===d)throw new Yt(`Valueless attribute '${n.name}' is not allowed`,zt.BOOLEAN_ATTRIBUTE_REJECTED,Zt(e.source));if("ignore"===d)continue}const i=e.processAttrName(n.name);if(!1===i)continue;c++;const o=void 0===s||s;r.rawAttributes[n.name]=o,l.push({name:i,value:o,index:n.startIndex})}r.rawAttributesLen=c,r._parsedAttrs=l}(l,e,a,s,o,i),a}class De{constructor(t,{nested:e=!1,skipEnclosures:r=[]}={}){this._tagName=t,this._nested=e,this._enclosures=r,this._content="",this._depth=1,this._active=!1}isActive(){return this._active}activate(){this._active=!0,this._content="",this._depth=1}resumeAfterOpenTag(){this._content="",this._depth=1}collect(t){t.markTokenStart(1);const e=this._enclosures.length;return this._nested||0!==e?this._nested&&0===e?this._collectDepthOnly(t):!this._nested&&e>0?this._collectEnclosureOnly(t):this._collectFull(t):this._collectPlain(t)}_collectPlain(t){for(;t.canRead();)if("<"===t.readChAt(0)){if(this._tryConsumeCloseTag(t))return this._finish(t);this._content+=t.readCh()}else this._content+=t.readCh();throw this._unclosedError()}_collectDepthOnly(t){for(;this._depth>0;)if(re(t,0,`stop node <${this._tagName}> content`),this._stepDepthTracking(t))return this._finish(t);throw this._unclosedError()}_collectEnclosureOnly(t){for(;t.canRead();)if(!this._trySkipEnclosure(t))if("<"===t.readChAt(0)){if(this._tryConsumeCloseTag(t))return this._finish(t);this._content+=t.readCh()}else this._content+=t.readCh();throw this._unclosedError()}_collectFull(t){for(;this._depth>0;)if(re(t,0,`stop node <${this._tagName}> content`),!this._trySkipEnclosure(t)&&this._stepDepthTracking(t))return this._finish(t);throw this._unclosedError()}_finish(t){const e=this._content,r={index:Jt(t)};return this._active=!1,this._content="",this._depth=1,{content:e,end:r}}_trySkipEnclosure(t){const e=this._matchEnclosureOpen(t);if(-1===e)return!1;const r=this._enclosures[e];this._skipChars(t,r.open.length),this._content+=r.open;const n=this._readUpto(t,r.close);return this._content+=n+r.close,!0}_tryConsumeCloseTag(t){const e="</"+this._tagName;if(!this._peekMatch(t,e))return!1;let r=e.length,n=!1;for(;;){const e=t.readChAt(r);if(">"===e){n=!0;break}if(!Gt(e))break;r++}if(!n)return!1;for(this._skipChars(t,e.length);t.canRead()&&">"!==t.readCh(););return!0}_stepDepthTracking(t){if("<"!==t.readChAt(0))return this._content+=t.readCh(),!1;if(t.readCh(),re(t,0,`stop node <${this._tagName}> tag after '<'`),"/"===t.readChAt(0)){t.readCh();const e=this._readTagName(t),r=this._readToAngleClose(t);return e===this._tagName&&(this._depth--,0===this._depth)||(this._content+="</"+e+r,!1)}const e=this._readTagName(t);this._content+="<"+e;const{selfClosing:r,attrText:n}=this._readTagTail(t);return this._content+=n,r||e!==this._tagName||this._depth++,!1}_unclosedError(){return new Yt(`Unclosed stop node <${this._tagName}> — unexpected end of input`,zt.UNEXPECTED_END)}_matchEnclosureOpen(t){const e=this._enclosures.length;for(let r=0;r<e;r++)if(this._peekMatch(t,this._enclosures[r].open))return r;return-1}_readUpto(t,e){const r=e[0],n=e.length,s=t.startIndex;let i=0;for(;t.canRead();){if(t.readChAt(0)===r&&this._peekMatch(t,e)){const e=t.readStr(i,s);return this._skipChars(t,n),e}t.readCh(),i++}throw new Yt(`Unclosed stop node <${this._tagName}> — unexpected end looking for '${e}'`,zt.UNEXPECTED_END)}_peekMatch(t,e){const r=e.length;for(let n=0;n<r;n++)if(t.readChAt(n)!==e[n])return!1;return!0}_skipChars(t,e){for(let r=0;r<e;r++)t.readCh()}_readTagName(t){let e="";for(;t.canRead();){const r=t.readChAt(0);if(">"===r||"/"===r||Gt(r))break;e+=t.readCh()}return e}_readTagTail(t){const e=t.startIndex;let r=0,n=!1,s=!1;for(;t.canRead();){const i=t.readCh();if(r++,"'"!==i||s)if('"'!==i||n){if(!n&&!s){if(">"===i)return{selfClosing:!1,attrText:t.readStr(r,e)};if("/"===i&&t.canRead()&&">"===t.readChAt(0))return t.readCh(),r++,{selfClosing:!0,attrText:t.readStr(r,e)}}}else s=!s;else n=!n}throw new Yt(`Unclosed stop node <${this._tagName}> — unexpected end inside tag`,zt.UNEXPECTED_END)}_readToAngleClose(t){const e=t.startIndex;let r=0;for(;t.canRead();){const n=t.readCh();if(r++,">"===n)return t.readStr(r,e);if(!Gt(n))throw new Yt(`Malformed closing tag for </${this._tagName}>`,zt.UNEXPECTED_END)}throw new Yt(`Unclosed stop node <${this._tagName}> — unexpected end looking for '>'`,zt.UNEXPECTED_END)}}function Oe(t){const e=t.options.skip;t.source.markTokenStart(1);let r=function(t){t.source.markTokenStart(1);const e=Jt(t.source);let r,n=!1,s=!1,i=!1;for(r=0;t.source.canRead(r);r++){const e=t.source.readChAt(r),a=t.source.readChAt(r+1);if("'"!==e||s?'"'!==e||n||(s=!s):n=!n,!n&&!s&&"?"===e&&">"===a){i=!0;break}}if(!i)throw new Yt("Unexpected closing of source waiting for '?>'",zt.UNEXPECTED_END);if(n||s)throw new Yt("Invalid attribute expression. Quote is not properly closed in PI tag expression",zt.UNCLOSED_QUOTE);const a=t.source.readStr(r);return t.source.updateBufferBoundary(r+2),Ce(a,t,e,!0)}(t);if(!r)throw new Yt("Invalid Pi Tag expression.",zt.INVALID_TAG,Zt(t.source));if("xml"===r.tagName){const e=r.rawAttributes?.version;"1.1"===e&&(t.xmlDec.version=1.1),t.xmlDec.encoding=r.rawAttributes?.encoding,t.xmlDec.standalone=r.rawAttributes?.standalone,t._nameValidators={}}e.attributes||Ae(r._parsedAttrs,t,r._attrsExpStart,r._rawAttrMatchCount),"xml"===r.tagName?e.declaration||t.outputBuilder.addDeclaration("?xml",t.xmlDec):e.pi||t.outputBuilder.addInstruction("?"+r.tagName)}function ke(t){const e=t.source;Be(e),re(e,1,"entity name");const r=e.startIndex;let n=0;for(;e.canRead();){const t=e.readCh();if(Gt(t)||'"'===t||"'"===t)break;n++}const s=e.readStr(n,r);if(re(e,1,`entity name "${s}"`),Re(s,t),Be(e),re(e,0,`after entity name "${s}"`),e.canRead(5)&&!0===e.matchAhead("system",!0))throw new Yt("External entities are not supported",zt.INVALID_TAG,Zt(e));if("%"===e.readStr(1))throw new Yt("Parameter entities are not supported",zt.INVALID_TAG,Zt(e));re(e,0,`entity value for "${s}"`);const[i]=Me(e,"entity"),a=t.options?.doctypeOptions;if(a?.maxEntitySize&&i.length>a.maxEntitySize)throw new Yt(`Entity "${s}" size (${i.length}) exceeds maximum allowed size (${a.maxEntitySize})`,zt.ENTITY_MAX_SIZE,Zt(e));return e.readUptoChar(">"),[s,i]}function Pe(t){const e=t.source;Be(e),re(e,1,"ELEMENT name");const r=e.startIndex;let n=0;for(;e.canRead()&&!Gt(e.readCh());)n++;const s=e.readStr(n,r);if(re(e,1,"ELEMENT name"),!t.getNameValidator("name")(s))throw new Yt(`Invalid element name: "${s}"`,zt.INVALID_TAG,Zt(e));Be(e),re(e,1,"ELEMENT name");let i=e.readStr(1);if("E"===i)try{ee(e,"EMPTY","ELEMENT content model keyword EMPTY")}catch(t){return e.readUptoChar(">"),{elementName:s,contentModel:""}}else if("A"===i)try{ee(e,"ANY","ELEMENT content model keyword ANY")}catch(t){return e.readUptoChar(">"),{elementName:s,contentModel:""}}else"("===i&&(e.updateBufferBoundary(1),e.readUptoChar(")"));return e.readUptoChar(">"),{elementName:s}}function Le(t){t.source.readUptoChar(">")}function Ue(t){const e=t.source;Be(e),re(e,1,"NOTATION name");const r=e.startIndex;let n=0;for(;e.canRead()&&!Gt(e.readCh());)n++;const s=e.readStr(n,r);if(re(e,1,`after NOTATION name "${s}"`),Re(s,t),Be(e),re(e,6,"NOTATION identifier type"),!0===e.matchAhead("system",!0))e.updateBufferBoundary(6),Be(e),Me(e,"systemIdentifier");else{if(!0!==e.matchAhead("public",!0))throw new Yt(`Expected SYSTEM or PUBLIC in NOTATION, found "${e.readStr(6)}"`,zt.INVALID_TAG,Zt(e));{e.updateBufferBoundary(6),Be(e),Me(e,"publicIdentifier"),Be(e),re(e,1,"after NOTATION PUBLIC identifier");let t=e.readStr(1);'"'!==t&&"'"!==t||Me(e,"systemIdentifier")}}e.readUptoChar(">")}function Me(t,e){re(t,1,e+" opening quote");let r=t.readStr(1);if('"'!==r&&"'"!==r)throw new Yt(`Expected quoted string for ${e}, found "${r}"`,zt.INVALID_TAG,Zt(t));return t.updateBufferBoundary(1),[t.readUptoChar(r)]}function Be(t){for(;t.canRead()&&Gt(t.readChAt(0));)t.updateBufferBoundary(1)}function Re(t,e){if(e.getNameValidator("name")(t))return t;throw new Yt(`Invalid entity name "${t}"`,zt.ENTITY_INVALID_KEY,{})}const $e=Object.freeze({UNCLOSED_EOF:"unclosed-eof",MISMATCHED_CLOSE:"mismatched-close",PHANTOM_CLOSE:"phantom-close",PARTIAL_TAG:"partial-tag"});class Ve{constructor(t){this.onEof=t.onEof||"throw",this.onMismatch=t.onMismatch||"throw",this.collectErrors=t.collectErrors||!1,this.errors=[]}handleEof(t){if("throw"===this.onEof)throw new Yt("Unexpected data in the end of document",zt.UNEXPECTED_TRAILING_DATA);const{addTextNode:e,popTag:r}=t;let n=t.currentTagDetail;for(;n&&!n.root;)this._recordError($e.UNCLOSED_EOF,{tag:n.name,expected:null,index:n.index}),e(),r(),n=t.currentTagDetail}handleMismatch(t,e){const{tagsStack:r,currentTagDetail:n,source:s,addTextNode:i}=e;if("throw"===this.onMismatch)throw new Yt(`Unexpected closing tag '${t}' expecting '${n.name}'`,zt.MISMATCHED_CLOSE_TAG,{index:s?Jt(s):void 0});if("discard"===this.onMismatch)return this._recordError($e.MISMATCHED_CLOSE,{tag:t,expected:n.name,index:s?Jt(s):null}),{action:"discard"};const a=[...r,n];let o=-1;const l=a.length;for(let e=l-1;e>=0;e--)if(a[e].name===t){o=e;break}if(-1===o)return this._recordError($e.PHANTOM_CLOSE,{tag:t,expected:n.name,index:s?Jt(s):null}),{action:"discard"};const c=l-1-o;for(let r=0;r<c;r++){const n=a[l-1-r];this._recordError($e.MISMATCHED_CLOSE,{tag:n.name,expected:t,index:n.index}),i(),e.popTag()}return e.currentTagDetail=a[o],{action:"close-matched"}}handlePartialTag(t,e){this._recordError($e.PARTIAL_TAG,{tag:je(t),expected:null,index:e.source?Jt(e.source):null}),e.tagTextData="",this.handleEof(e)}getErrors(){return this.errors.slice()}reset(){this.errors=[]}_recordError(t,e){this.collectErrors&&this.errors.push({type:t,...e})}}function je(t){if(!t)return null;const e=("string"==typeof t.message?t.message:String(t)).match(/[Rr]eading closing tag '<\/([^']*)/);return e&&e[1]||null}const Xe={keep:["xml:space"]};function qe(t,e,r){const n=t.get(e);if(void 0!==n||t.has(e))return n;const s=r();return t.size>=2e3&&t.clear(),t.set(e,s),s}class Fe{constructor(t,e=0,r=void 0,n=void 0){this.name=t,this.index=e,this.openEnd=r,this.rawName=n}}class Ye{constructor(t){this.options=t,this.currentTagDetail=null,this.tagTextData="",this.tagsStack=[],this.doctypeFound=!1,this.matcher=new O,this.readonlyMatcher=this.matcher.readOnly(),this.autoCloseHandler=t.autoClose?new Ve(t.autoClose):null,this._unpairedSet=new Set(this.options.tags.unpaired),this.stopNodeExpressionsSet=this.options.tags.stopNodesSet??new F,0===this.stopNodeExpressionsSet.size?this.isStopNode=()=>!1:this.isStopNode=He,this.skipTagExpressionsSet=this.options.skip.tagsSet??new F,0===this.skipTagExpressionsSet.size?this.isSkipTag=()=>!1:this.isSkipTag=We,this._exitIf="function"==typeof t.exitIf?t.exitIf:()=>!1,this._nameCache=t._nameCache||(t._nameCache={tags:new Map,attrs:new Map})}initializeParser(){this.tagTextData="",this.tagsStack=[],this.doctypeFound=!1,this._stopNodeProcessor=null,this._exitIfTriggered=!1,this._nameValidators={},this._validQNames=new Set,this.xmlDec={version:1,lang:null,encoding:null,standalone:"yes"},this.matcher||(this.matcher=new O,this.readonlyMatcher=this.matcher.readOnly()),this.outputBuilder=this._createOutputBuilder(),this.root={root:!0,name:""},this.currentTagDetail=this.root}_createOutputBuilder(){return this.options.OutputBuilder.getInstance(this.options,this.readonlyMatcher)}wasExited(){return!0===this._exitIfTriggered}parse(t){return this.source=new fe(t),this.initializeParser(),this._parseAndFinalize(),this.outputBuilder.getOutput()}parseBytesArr(t){const e=this.options.decoding?._registry,r=function(t,e={},r=we){const n=e.encoding||"auto";let s,i;if("auto"===n){const e=xe(t,r);s=e.encoding,i=e.bomLength}else s=n,i=0;const a=r.resolve(s),o=a.selfSynchronizing?ge("utf8"===a.name?_e:me,a.name):{readCh(){return this.buffer[this.startIndex++]},readChAt(t){return this.buffer[this.startIndex+t]},readStr(t,e){return void 0===e&&(e=this.startIndex),this.buffer.substring(e,e+t)},matchAhead(t,e=!1){const r=t.length;for(let n=0;n<r;n++){let r=this.buffer[this.startIndex+n];if(void 0===r)return null;if(e&&(r=r.toLowerCase()),r!==t[n])return!1}return!0},scanTagExpEnd:de,scanTagExpEndFast:pe,readUpto(t){const e=this.buffer.length,r=t.length;for(let n=this.startIndex;n<e;n++){let e=!0;for(let s=0;s<r;s++)if(this.buffer[n+s]!==t[s]){e=!1;break}if(e){const t=this.buffer.substring(this.startIndex,n);return this.startIndex=n+r,t}}throw new Yt(`Unexpected end of source reading '${t}'`,zt.UNEXPECTED_END)},readUptoChar(t){const e=this.buffer.indexOf(t,this.startIndex);if(-1===e)throw new Yt(`Unexpected end of source reading '${t}'`,zt.UNEXPECTED_END);const r=this.buffer.substring(this.startIndex,e);return this.startIndex=e+1,r},readUptoCloseTag(t){const e=this.buffer.length,r=t.length;let n=-1,s=0;for(let i=this.startIndex;i<e;i++){if(1===s){const t=this.buffer[i];if(Gt(t))continue;">"===t?s=2:(s=0,n=-1)}else{let e=!0;for(let n=0;n<r;n++)if(this.buffer[i+n]!==t[n]){e=!1;break}e&&(s=1,n=i,i+=r-1)}if(2===s){const t=this.buffer.substring(this.startIndex,n);return this.startIndex=i+1,t}}throw new Yt(`Unexpected end of source reading '${t}'`,zt.UNEXPECTED_END)},readFromBuffer(t,e){const r=1===t?this.buffer[this.startIndex]:this.buffer.substring(this.startIndex,this.startIndex+t);return e&&this.updateBufferBoundary(t),r},updateBufferBoundary(t=1){this.startIndex+=t,this.autoFlush&&this.startIndex>=this.flushThreshold&&this._tokenStart<0&&this.flush()},canRead(t=0){return this.startIndex+t<this.buffer.length}},l=!a.selfSynchronizing||"utf8"!==a.name;return{descriptor:a,bomLength:i,scanStrategy:o,decodeFirst:!a.selfSynchronizing,quotePairsUsable:l}}(t,this.options.decoding,e);return this.source=new be(t,{},r),this.initializeParser(),this._parseAndFinalize(),this.outputBuilder.getOutput()}parseXml(){for(;this.source.canRead()&&!this._exitIfTriggered;){this.source.markTokenStart(0);const t=Zt(this.source),e=this.source.readCh();if(void 0===e||""===e)break;if("<"===e){const e=t,r=this.source.readChAt(0);if(""===r)throw new Yt("Unexpected end of source after '<'",zt.UNEXPECTED_END,Zt(this.source));"/"===r?(this.source.updateBufferBoundary(),this.readClosingTag(e)):"!"===r?(this.source.updateBufferBoundary(),this.addTextNode(),this.readSpecialTag(r)):"?"===r?(this.source.updateBufferBoundary(),this.addTextNode(),Oe(this)):this.readOpeningTag(e)}else{let t=0;for(;;){const e=this.source.readChAt(t);if("<"===e||void 0===e||""===e)break;t++}t>0?(this.tagTextData+=e+this.source.readStr(t,this.source.startIndex),this.source.updateBufferBoundary(t)):this.tagTextData+=e}}}finalizeXml(){if(this._exitIfTriggered)return;const t=this.tagsStack.length>0||this.currentTagDetail&&!this.currentTagDetail.root,e=!t&&void 0!==this.tagTextData&&this.tagTextData.trimEnd().length>0;if(t||e){if(!this.autoCloseHandler||!t||e)throw new Yt("Unexpected data in the end of document",zt.UNEXPECTED_TRAILING_DATA,Zt(this.source));this.autoCloseHandler.handleEof(this._parserState())}}_parseAndFinalize(){let t=null;this.autoCloseHandler&&this.autoCloseHandler.reset();try{this.parseXml()}catch(e){if(!this.autoCloseHandler||!function(t){return t instanceof Yt?t.code===zt.UNEXPECTED_END:t.message.startsWith("Unexpected end of source")||t.message.startsWith("Unexpected closing of source")}(e))throw e;t=e}t?this.autoCloseHandler.handlePartialTag(t,this._parserState()):this.finalizeXml()}readClosingTag(t){const e=this.currentTagDetail;if(e&&!e.root&&void 0!==e.rawName){const r=function(t,e){if(!0!==t.matchAhead(e))return-1;let r=e.length,n=t.readChAt(r);if(">"===n)return r+1;for(;Gt(n);)if(r++,n=t.readChAt(r),">"===n)return r+1;return">"!==n?-1:r+1}(this.source,e.rawName);if(-1!==r){this.source.updateBufferBoundary(r);const n={name:e.name,index:t.index,closeEnd:Jt(this.source)};return this.addTextNode(),void this.popTag(n)}}const r=this.processTagName(function(t){t.markTokenStart(1);const e=t.startIndex;try{return t.readUptoChar(">").trimEnd()}catch(r){const n=t.readStr(Number.MAX_SAFE_INTEGER,e);throw new Yt(`Unexpected end of source reading closing tag '</${n}'`,zt.UNEXPECTED_END)}}(this.source)),n={name:r,index:t.index,closeEnd:Jt(this.source)};if(this.isUnpaired(r)||this.isStopNode())throw new Yt(`Unexpected closing tag '${r}'`,zt.UNEXPECTED_CLOSE_TAG,Zt(this.source));if(r!==this.currentTagDetail.name){if(!this.autoCloseHandler)throw new Yt(`Unexpected closing tag '${r}' expecting '${this.currentTagDetail.name}'`,zt.MISMATCHED_CLOSE_TAG,Zt(this.source));if("discard"===this.autoCloseHandler.handleMismatch(r,this._parserState()).action)return}this.currentTagDetail.root||this.addTextNode(),this.popTag(n)}readOpeningTag(t){const e=this.options;if(this.addTextNode(),this._stopNodeProcessor&&this._stopNodeProcessor.isActive()){const{tagDetail:t,isSkip:e}=this._stopNodeProcessorMeta;this._stopNodeProcessor.resumeAfterOpenTag(),Se(this),t.openEnd=Jt(this.source);const{content:r,end:n}=this._stopNodeProcessor.collect(this.source);return e||(this.outputBuilder.addElement(t,this.readonlyMatcher),this.outputBuilder.onStopNode?.(t,r,this.readonlyMatcher,n),this.outputBuilder.addValue(r,this.readonlyMatcher),this.outputBuilder.closeElement(this.readonlyMatcher,{name:t.name,closeEnd:n.index})),this.matcher.pop(),this._stopNodeProcessor=null,void(this._stopNodeProcessorMeta=null)}let r=Se(this);const n=this.processTagName(r.tagName),s=new Fe(n,t.index,Jt(this.source),r.tagName),i=r.tagName.indexOf(":"),a=-1!==i?r.tagName.slice(0,i):void 0,o=void 0!==a?r.tagName.slice(i+1):n,l=e.limits?.maxNestedTags;if(null!=l){const t=this.tagsStack.length+1;if(t>l)throw new Yt(`Nesting depth ${t} exceeds limit of ${l} (tag: '${n}')`,zt.LIMIT_MAX_NESTED_TAGS,{index:s.index})}let c={},h=0;r.rawAttributes&&(c=r.rawAttributes,h=r.rawAttributesLen),h>0?this.matcher.push(o,c,a,Xe):this.matcher.push(o,{},a);const u=this.isStopNode(),d=u?null:this.isSkipTag();if(e.skip.attributes||d||Ae(r._parsedAttrs,this,r._attrsExpStart,r._rawAttrMatchCount),this.isUnpaired(n))this.outputBuilder.addElement(s,this.readonlyMatcher),this.outputBuilder.closeElement(this.readonlyMatcher,this._closeMetaFor(s)),this.matcher.pop();else if(r.selfClosing)d||(this.outputBuilder.addElement(s,this.readonlyMatcher),this.outputBuilder.closeElement(this.readonlyMatcher,this._closeMetaFor(s))),this.matcher.pop();else if(u){this._stopNodeProcessor=new De(r.tagName,{nested:u.nested,skipEnclosures:u.skipEnclosures}),this._stopNodeProcessorMeta={tagDetail:s,isSkip:!1},this._stopNodeProcessor.activate();const{content:t,end:e}=this._stopNodeProcessor.collect(this.source);this.outputBuilder.addElement(s,this.readonlyMatcher),this.outputBuilder.onStopNode?.(s,t,this.readonlyMatcher,e),this.outputBuilder.addValue(t,this.readonlyMatcher),this.outputBuilder.closeElement(this.readonlyMatcher,{name:s.name,closeEnd:e.index}),this.matcher.pop(),this._stopNodeProcessor=null,this._stopNodeProcessorMeta=null}else if(d)this._stopNodeProcessor=new De(r.tagName,{nested:d.nested,skipEnclosures:d.skipEnclosures}),this._stopNodeProcessorMeta={tagDetail:s,isSkip:!0},this._stopNodeProcessor.activate(),this._stopNodeProcessor.collect(this.source),this.matcher.pop(),this._stopNodeProcessor=null,this._stopNodeProcessorMeta=null;else if(this._exitIf(this.readonlyMatcher)){const t=this.tagsStack.length;for(this.matcher.pop();this.currentTagDetail&&!this.currentTagDetail.root;)this.addTextNode(),this.popTag();"function"==typeof this.outputBuilder.onExit&&this.outputBuilder.onExit({tagDetail:s,matcher:this.readonlyMatcher,depth:t}),this._exitIfTriggered=!0}else this.pushTag(s)}pushTag(t){this.tagsStack.push(this.currentTagDetail),this.outputBuilder.addElement(t,this.readonlyMatcher),this.currentTagDetail=t}popTag(t){this.outputBuilder.closeElement(this.readonlyMatcher,t??{name:this.currentTagDetail?.name}),this.matcher.pop(),this.currentTagDetail=this.tagsStack.pop()}_closeMetaFor(t){return{name:t.name,index:t.index,closeEnd:t.openEnd}}readSpecialTag(t){if("!"!==t)throw new Yt(`Invalid tag '<${t}'`,zt.INVALID_TAG,Zt(this.source));{let t=this.source.readCh();if(null==t)throw new Yt("Unexpected end of source after '<!'",zt.UNEXPECTED_END,Zt(this.source));if("-"===t)!function(t){t.source.markTokenStart(1),ee(t.source,"-","comment second dash");let e=t.source.readUpto("--\x3e");e=te(e,t.source),t.outputBuilder.addComment(e)}(this);else if("["===t)!function(t){t.source.markTokenStart(1),ee(t.source,"CDATA[","CDATA preamble");let e=t.source.readUpto("]]>");e=te(e,t.source),t.outputBuilder.addLiteral(e)}(this);else if("D"===t){const t=function(t){t.source.markTokenStart(1),ee(t.source,"OCTYPE","DOCTYPE preamble");const e={};let r=0,n=!1,s=!1;for(;t.source.canRead();){const i=t.source.startIndex;let a=t.source.readCh();if("<"===a&&n&&!s)try{re(t.source,0,"DOCTYPE sub-tag");let n=t.source.readStr(1);if(t.source.updateBufferBoundary(1),"!"!==n)throw new Yt(`Invalid DOCTYPE body tag starting with "<${n}"`,zt.INVALID_TAG,Zt(t.source));re(t.source,0,"DOCTYPE sub-tag type");let s=t.source.readStr(1);if(t.source.updateBufferBoundary(1),"-"===s){re(t.source,0,"DOCTYPE comment");let e=t.source.readStr(1);if(t.source.updateBufferBoundary(1),"-"!==e)throw new Yt("Invalid comment in DOCTYPE",zt.INVALID_TAG,Zt(t.source));t.source.readUpto("--\x3e")}else if("E"===s){re(t.source,0,"DOCTYPE E-type sub-tag");let n=t.source.readStr(1);if(t.source.updateBufferBoundary(1),"N"===n){ee(t.source,"TITY","DOCTYPE ENTITY keyword");const[n,s]=ke(t);if(-1===s.indexOf("&")){const i=t.options?.doctypeOptions;if(i?.maxEntityCount&&r>=i.maxEntityCount)throw new Yt(`Entity count (${r+1}) exceeds maximum allowed (${i.maxEntityCount})`,zt.ENTITY_MAX_COUNT,Zt(t.source));const a=n.replace(/[.\-+*:]/g,"\\$&");e[n]={regx:RegExp(`&${a};`,"g"),val:s},r++}}else{if("L"!==n)throw new Yt(`Invalid DOCTYPE sub-tag "<!E${n}"`,zt.INVALID_TAG,Zt(t.source));ee(t.source,"EMENT","DOCTYPE ELEMENT keyword"),Pe(t)}}else if("A"===s)ee(t.source,"TTLIST","DOCTYPE ATTLIST keyword"),Le(t);else{if("N"!==s)throw new Yt(`Invalid DOCTYPE sub-tag "<!${s}"`,zt.INVALID_TAG,Zt(t.source));ee(t.source,"OTATION","DOCTYPE NOTATION keyword"),Ue(t)}}catch(e){throw e.code===zt.UNEXPECTED_END&&(t.source.startIndex=i),e}else if("["===a)n=!0;else if("]"===a)s=!0;else if(">"===a&&(!n||s))return e}throw new Yt("Unclosed DOCTYPE",zt.UNEXPECTED_END,Zt(t.source))}(this);if(this.doctypeFound)throw new Yt("Multiple DOCTYPE declarations found.",zt.INVALID_INPUT,Zt(this.source));this.doctypeFound=!0,this.options.doctypeOptions.enabled&&t&&Object.keys(t).length>0&&this.outputBuilder.addInputEntities(t)}}}addTextNode(){void 0!==this.tagTextData&&""!==this.tagTextData&&(this.tagTextData=te(this.tagTextData,this.source),(!this.options.skip.whitespaceText||this.tagTextData.trim().length>0)&&this.outputBuilder.addValue(this.tagTextData,this.readonlyMatcher),this.tagTextData="")}isValidQName(t){const e=this._validQNames;if(e.has(t))return!0;const r=this.getNameValidator("qName")(t);return r&&(e.size>=2e3&&e.clear(),e.add(t)),r}getNameValidator(t){let e=this._nameValidators[t];if(!e){const r=1.1===this.xmlDec.version||"1.1"===this.xmlDec.version?"1.1":"1.0";e=T(t,{xmlVersion:r}),this._nameValidators[t]=e}return e}processAttrName(t){return qe(this._nameCache.attrs,t,()=>{const e=this.options;let r=ze(t,e.skip.nsPrefix);if(!this.getNameValidator("qName")(r))throw new Yt(`Invalid attribute name: ${r}`,zt.INVALID_ATTRIBUTE_NAME,Zt(this.source));if(r=Ge(r,e.onDangerousProperty,e.sanitizeNames,this.source),e.strictReservedNames&&r===e.attributes.groupBy)throw new Yt(`Restricted attribute name: ${r}`,zt.SECURITY_RESTRICTED_NAME,Zt(this.source));return r})}processTagName(t){return qe(this._nameCache.tags,t,()=>{const e=this.options,r=e.nameFor;let n=ze(t,e.skip.nsPrefix);if(n=Ge(n,e.onDangerousProperty,e.sanitizeNames,this.source),e.strictReservedNames&&(n===r.comment||n===r.cdata||n===r.text))throw new Yt(`Restricted tag name: ${n}`,zt.SECURITY_RESTRICTED_NAME,Zt(this.source));return n})}isUnpaired(t){return this._unpairedSet.has(t)}_parserState(){const t=this;return{get tagsStack(){return t.tagsStack},get currentTagDetail(){return t.currentTagDetail},set currentTagDetail(e){t.currentTagDetail=e},get outputBuilder(){return t.outputBuilder},get readonlyMatcher(){return t.readonlyMatcher},get matcher(){return t.matcher},get source(){return t.source},get tagTextData(){return t.tagTextData},set tagTextData(e){t.tagTextData=e},addTextNode:t.addTextNode.bind(t),popTag:t.popTag.bind(t)}}}function ze(t,e){if(e){const e=t.split(":");if(2===e.length)return"xmlns"!==e[0]&&e[1];if(e.length>2)throw new Yt(`Multiple namespaces in name: ${t}`,zt.MULTIPLE_NAMESPACES,Zt(this.source))}return t}function Ge(t,e,r,n){if(Qt.includes(t))throw new Yt(`[SECURITY] Invalid name: "${t}" is a reserved JavaScript keyword that could cause prototype pollution`,zt.SECURITY_PROTOTYPE_POLLUTION,Zt(n));return!1===r?t:Wt.includes(t)?e(t):t}function He(){if(0===this.stopNodeExpressionsSet.size)return null;const t=this.stopNodeExpressionsSet.findMatch(this.matcher);return t?t.data:null}function We(){if(0===this.skipTagExpressionsSet.size)return null;const t=this.skipTagExpressionsSet.findMatch(this.matcher);return t?t.data:null}class Qe{constructor(t={}){this.buffer="",this.startIndex=0,this.isComplete=!1,this._baseOffset=0,this.maxBufferSize=t.maxBufferSize||10485760,this.autoFlush=!1!==t.autoFlush,this.flushThreshold=t.flushThreshold||1024,this._decodingOptions=t.decoding||null;const e=this._decodingOptions?.encoding;if(this._detecting="auto"===e,this._sniffBuffer=this._detecting?Buffer.alloc(0):null,!this._detecting&&e&&this._decodingOptions.registry){const t=this._decodingOptions.registry;this._createDecoder=()=>t.resolve(e).createDecoder()}else this._createDecoder="function"==typeof t.createDecoder?t.createDecoder:null;this._marks=[null,null],this._decoder=null,this._quotePairs=new Int32Array(128),this._quotePairsLen=0}feed(t){if(this._detecting)if("string"==typeof t)this._detecting=!1;else{const e=Buffer.isBuffer(t)?t:Buffer.from(t);this._sniffBuffer=this._sniffBuffer.length?Buffer.concat([this._sniffBuffer,e]):e;const r=this._sniffBuffer.includes(Buffer.from("?>"));if(this._sniffBuffer.length<200&&!r)return 0;t=this._resolveDetection()}let e=this._decodeNow(t);const r=this.buffer.length-this.startIndex;if(r+e.length>this.maxBufferSize)throw new Yt(`Buffer size limit exceeded (${r+e.length} > ${this.maxBufferSize}). Increase feedable.maxBufferSize or reduce chunk size.`,zt.INVALID_INPUT);return this.buffer+=e,e.length}_decodeNow(t){if("string"==typeof t)return t;if(Buffer.isBuffer(t))return this._decoder||(this._decoder=this._createDecoder?this._createDecoder():ye("utf-8")),this._decoder.write(t);if(t?.toString)return t.toString();throw new Yt("feed() data must be a string or Buffer.",zt.DATA_MUST_BE_STRING)}_resolveDetection(){const t=this._decodingOptions.registry,{encoding:e,bomLength:r}=xe(this._sniffBuffer,t),n=t.resolve(e);this._createDecoder=()=>n.createDecoder(),this._detecting=!1;const s=r?this._sniffBuffer.subarray(r):this._sniffBuffer;return this._sniffBuffer=null,s}end(){if(this._detecting){const t=this._resolveDetection();this.buffer+=this._decodeNow(t)}if(this._decoder){const t=this._decoder.end();t&&(this.buffer+=t)}this.isComplete=!0}canRead(t=0){return this.startIndex+t<this.buffer.length}markTokenStart(t=0){this._marks[t]=this.startIndex}rewindToMark(){null!==this._marks[0]&&(this.startIndex=this._marks[0]),this._marks[0]=null,this._marks[1]=null}clearMark(){this._marks[0]=null,this._marks[1]=null}readCh(){return this.buffer[this.startIndex++]}readChAt(t){return this.buffer[this.startIndex+t]}readStr(t,e){return void 0===e&&(e=this.startIndex),this.buffer.substring(e,e+t)}matchAhead(t,e=!1){const r=t.length;for(let n=0;n<r;n++){let r=this.buffer[this.startIndex+n];if(void 0===r)return null;if(e&&(r=r.toLowerCase()),r!==t[n])return!1}return!0}scanTagExpEnd=de;scanTagExpEndFast=pe;readUpto(t){const e=this.buffer.length,r=t.length;for(let n=this.startIndex;n<e;n++){let e=!0;for(let s=0;s<r;s++)if(this.buffer[n+s]!==t[s]){e=!1;break}if(e){const t=this.buffer.substring(this.startIndex,n);return this.startIndex=n+r,t}}throw new Yt(`Unexpected end of source reading '${t}'`,zt.UNEXPECTED_END)}readUptoChar(t){const e=this.buffer.indexOf(t,this.startIndex);if(-1===e)throw new Yt(`Unexpected end of source reading '${t}'`,zt.UNEXPECTED_END);const r=this.buffer.substring(this.startIndex,e);return this.startIndex=e+1,r}readUptoCloseTag(t){const e=this.buffer.length,r=t.length;let n=-1,s=0;for(let i=this.startIndex;i<e;i++){if(1===s){const t=this.buffer[i];if(Gt(t))continue;">"===t?s=2:(s=0,n=-1)}else{let e=!0;for(let n=0;n<r;n++)if(this.buffer[i+n]!==t[n]){e=!1;break}e&&(s=1,n=i,i+=r-1)}if(2===s){const t=this.buffer.substring(this.startIndex,n);return this.startIndex=i+1,t}}throw new Yt(`Unexpected end of source reading '${t}'`,zt.UNEXPECTED_END)}updateBufferBoundary(t=1){this.startIndex+=t,this.autoFlush&&this.startIndex>=this.flushThreshold&&this.flush()}flush(){let t=this.startIndex;for(const e of this._marks)null!==e&&e<t&&(t=e);if(t>0){this.buffer=this.buffer.substring(t);const e=this._marks.length;for(let r=0;r<e;r++)null!==this._marks[r]&&(this._marks[r]-=t);this.startIndex-=t,this._baseOffset+=t}}}class Je extends Qe{attachStream(t,e,r,n){t.on("data",t=>{try{this.feed(t),e(null)}catch(t){e(t)}}),t.on("error",n),t.on("end",()=>{try{this.end(),r()}catch(t){n(t)}})}}class Ze{constructor(t){if(this.options=oe(t),this._feedParser=null,this._feedSource=null,this._isFeeding=!1,this._pendingBytes=0,this._batchThreshold=this.options.feedable?.bufferSize,this.options.decoding?.customDecoders){const t=new Te;for(const[e,r]of Object.entries(this.options.decoding.customDecoders))t.register({name:e,...r});this.options.decoding._registry=t}else this.options.decoding=this.options.decoding||{},this.options.decoding._registry=we;this.options._nameCache={tags:new Map,attrs:new Map}}parse(t){if(t instanceof Buffer||ArrayBuffer.isView(t))return this.parseBytesArr(t);if("string"!=typeof t){if(!t||"function"!=typeof t.toString)throw new Yt("XML data must be a string or Buffer.",zt.INVALID_INPUT);t=t.toString()}const e=this._createParser(),r=e.parse(t);return this.wasExited=e.wasExited(),this._lastParseErrors=e.autoCloseHandler?.getErrors()??[],r}parseBytesArr(t){if(!(t instanceof Uint8Array||ArrayBuffer.isView(t)))throw new Yt("XML data must be a Uint8Array or ArrayBufferView.",zt.INVALID_INPUT);t=Buffer.from(t);const e=this._createParser(),r=e.parseBytesArr(t);return this.wasExited=e.wasExited(),this._lastParseErrors=e.autoCloseHandler?.getErrors()??[],r}parseStream(t){if(null===(e=t)||"object"!=typeof e||"function"!=typeof e.read||"function"!=typeof e.on||"boolean"!=typeof e.readableEnded)throw new Yt("parseStream() requires a Node.js Readable stream.",zt.INVALID_STREAM);var e;const r=new Je({...this.options.feedable,decoding:{encoding:this.options.decoding.encoding,registry:this.options.decoding._registry}}),n=this._createParser();return n.source=r,n.initializeParser(),new Promise((e,s)=>{let i=!1;const a=e=>{i||(i=!0,t.destroy(),s(e))};r.attachStream(t,t=>{if(t)a(t);else try{n.parseXml()}catch(t){t.code===zt.UNEXPECTED_END?r.rewindToMark():a(t)}},()=>{if(!i)try{n.parseXml(),n.finalizeXml(),this._lastParseErrors=n.autoCloseHandler?.getErrors()??[],i=!0,e(n.outputBuilder.getOutput())}catch(t){a(t)}},a)})}_runParse(){if(!this._feedParser)return;const t=Jt(this._feedSource);try{this._feedParser.parseXml()}catch(t){if(t.code!==zt.UNEXPECTED_END)throw t;this._feedSource.rewindToMark()}Jt(this._feedSource)>t?(this._pendingBytes=0,this._batchThreshold=this.options.feedable.bufferSize):this._batchThreshold=Math.min(2*this._batchThreshold,this.options.feedable.maxBufferSize)}feed(t){this._isFeeding||this._initFeedSession();const e=this._feedSource.feed(t);return this._pendingBytes+=e,this._pendingBytes>=this._batchThreshold&&this._runParse(),this}end(){if(!this._isFeeding)throw new Yt("No data fed. Call feed() before end().",zt.NOT_STREAMING);this._runParse();try{this._feedSource.end();let t=null;const e=this._feedParser.autoCloseHandler;e&&e.reset();try{this._feedParser.parseXml()}catch(r){if(r.code!==zt.UNEXPECTED_END)throw r;if(!e)throw r;t=r}return t?e.handlePartialTag(t,this._feedParser._parserState()):this._feedParser.finalizeXml(),this._lastParseErrors=e?.getErrors()??[],this.wasExited=this._feedParser.wasExited(),this._feedParser.outputBuilder.getOutput()}finally{this._cleanupFeedSession()}}getParseErrors(){return this._lastParseErrors??[]}_createParser(){return new Ye(this.options)}_initFeedSession(){this._feedSource=new Qe({...this.options.feedable,decoding:{encoding:this.options.decoding.encoding,registry:this.options.decoding._registry}}),this._feedParser=this._createParser(),this._feedParser.source=this._feedSource,this._feedParser.initializeParser(),this._isFeeding=!0}_cleanupFeedSession(){this._feedParser=null,this._feedSource=null,this._isFeeding=!1}}class Ke extends qt{constructor(t,e,r,n){super(t,e,r,n),this.siblingOrder=new Map}addElement(t){const e=this.matcher.toString(),r=e.lastIndexOf("."),n=-1===r?"":e.substring(0,r);this.siblingOrder.has(n)||this.siblingOrder.set(n,[]);const s=this.siblingOrder.get(n);s[s.length-1]!==t.name&&s.push(t.name),super.addElement(t)}getOutput(){return{data:super.getOutput(),siblingOrder:this.siblingOrder}}}const tr=new Ot({hex:!0,leadingZeros:!0,eNotation:!0,unicode:!0});function er(t){const e=tr.parse(t);return"number"==typeof e?e:NaN}const rr={minLength:(t,e)=>e.length>=t,maxLength:(t,e)=>e.length<=t,length:(t,e)=>e.length===t,pattern:(t,e,r="")=>new RegExp(t,r).test(e),fixed:(t,e)=>t===e,in:(t,e)=>t.split(",").indexOf(e)>-1},nr={min:(t,e)=>er(e)>=t,max:(t,e)=>er(e)<=t},sr={minOccurs:(t,e)=>e>=t,maxOccurs:(t,e)=>e<=t},ir=(t,e)=>Date.parse(e)>=Date.parse(t),ar=(t,e)=>Date.parse(e)<=Date.parse(t),or=["positiveInteger","integer","positiveDecimal","decimal","number"];class lr{constructor(t,e,r){this.options=t,this.failures=[],this.validators=e,this._globalUnique=new Map,this._siblingOrder=r||new Map}traverse(t,e,r,n){if(Array.isArray(t)){if(void 0!==r&&void 0!==r["@rules"]&&void 0!==r["@rules"].repeatable)return this.checkOccurences(r["@rules"],t.length,n),void t.forEach((s,i)=>{const a=n+"["+i+"]";Object.keys(r).length>1?this.callForCommonProperties(t[i],r,a):this.traverse(t[i],e,r,a)});this.failures.push({code:"unexpected sequence",path:n.substr(1)})}else"object"==typeof t?this.callForCommonProperties(t,r,n):("object"==typeof r&&r["@rules"]?this.checkDataAndType(t,e,r,n):this.isMapType(r)&&this.validateMandatoryFields(r,n),this.applyCustomValidators(t,r,n))}applyCustomValidators(t,e,r){if(e["@rules"]&&e["@rules"].checkBy&&"function"==typeof this.validators[e["@rules"].checkBy]){let n=this.validators[e["@rules"].checkBy](t,r.substr(1));"object"==typeof n&&this.failures.push(n)}}callForCommonProperties(t,e,r){const n=function(t,e){const r={data:[],rules:[],common:[]};for(let n=0;n<t.length;n++)-1===e.indexOf(t[n])?r.data.push(t[n]):r.common.push(t[n]);for(let n=0;n<e.length;n++)-1===t.indexOf(e[n])&&"@"!==e[n]&&r.rules.push(e[n]);return r}(Object.keys(t),Object.keys(e));this.checkUnknownSiblings(n,r),this.checkMissingSiblings(n,e,r),this.applyCustomValidators(t,e,r);const s=this._buildSiblingValues(t,e,n.common);n.common.forEach(n=>{const s=r+"."+n;this.traverse(t[n],n,e[n],s)}),this._checkOrderingConstraints(t,e,n.common,r),this._checkUniquenessConstraints(t,e,n.common,r,s),this._checkRelationalConstraints(t,e,n.common,r)}_checkOrderingConstraints(t,e,r,n){const s=n.substr(1),i=this._siblingOrder.get(s);i&&r.forEach(r=>{const s=e[r];if(!s||!s["@rules"])return;const a=s["@rules"],o=i.indexOf(r);if(-1!==o){if(a.after){const e=a.after;if(void 0===t[e])return;const s=i.indexOf(e);if(-1===s)return;o<=s&&this.failures.push({code:"after",path:(n+"."+r).substr(1),actual:r,expected:e})}if(a.before){const e=a.before;if(void 0===t[e])return;const s=i.indexOf(e);if(-1===s)return;o>=s&&this.failures.push({code:"before",path:(n+"."+r).substr(1),actual:r,expected:e})}}})}_checkRelationalConstraints(t,e,r,n){const s=["sameAs","notSameAs","lessThan","moreThan"];r.forEach(r=>{const i=e[r];if(!i||!i["@rules"])return;const a=i["@rules"];if(!s.some(t=>void 0!==a[t]))return;const o=t[r];if(null==o)return;if("object"==typeof o)return;const l=a.type||"string";s.forEach(e=>{if(void 0===a[e])return;const s=a[e],i=t[s];if(null==i)return;if("object"==typeof i)return;const c=this._relationalCompare(String(o),String(i),l);if(null===c)return;let h=!1;"sameAs"===e&&0!==c&&(h=!0),"notSameAs"===e&&0===c&&(h=!0),"lessThan"===e&&c>=0&&(h=!0),"moreThan"===e&&c<=0&&(h=!0),h&&this.failures.push({code:e,path:(n+"."+r).substr(1),actual:String(o),expected:s})})})}_relationalCompare(t,e,r){if("date"===r){const r=Date.parse(t),n=Date.parse(e);return isNaN(r)||isNaN(n)?null:r-n}if(-1!==or.indexOf(r)){const r=er(t),n=er(e);return isNaN(r)||isNaN(n)?null:r-n}return t<e?-1:t>e?1:0}_buildSiblingValues(t,e,r){const n=new Map;return r.forEach(e=>{const r=t[e];Array.isArray(r)?n.set(e,r.map(String)):null!=r&&"object"!=typeof r&&n.set(e,[String(r)])}),n}_checkUniquenessConstraints(t,e,r,n,s){r.forEach(r=>{const i=e[r];if(!i||!i["@rules"])return;const a=i["@rules"].unique;if(!a)return;const o=s.get(r)||[];"global"===a&&o.forEach((e,s)=>{const i=Array.isArray(t[r])?(n+"."+r+"["+s+"]").substr(1):(n+"."+r).substr(1);this._assertGlobalUnique(r,e,i)})})}_checkUniqueInCollection(t,e,r){const n=new Map;t.forEach((t,s)=>{const i=t[e];if(null==i||"object"==typeof i)return;const a=String(i);n.has(a)?this.failures.push({code:"unique",path:(r+"["+s+"]."+e).substr(1),value:a}):n.set(a,s)})}_assertGlobalUnique(t,e,r){this._globalUnique.has(t)||this._globalUnique.set(t,new Set);const n=this._globalUnique.get(t);n.has(e)?this.failures.push({code:"unique",path:r,value:e}):n.add(e)}checkDataAndType(t,e,r,n){!0===r["@rules"].repeatable&&this.checkOccurences(r["@rules"],1,n);const s=r["@rules"].type,i=this._expandRange(r);if("map"===s||!s&&this.isMapType(r))"string"==typeof t&&t.length>0&&this.failures.push({code:"unexpected value in a map",path:n.substr(1),value:t}),this.validateMandatoryFields(r,n);else if("date"===s)this.validateDate(t,s,n),this._checkDateBounds(r,t,n);else if("boolean"===s)this.validateBoolean(t,s,n);else if(-1!==or.indexOf(s))this.isValidNum(s,t)?this.assertValue(i["@rules"],"num",er(t),n):this.setInvalidDataType(s,n,t);else{if("string"!==s&&s)throw new Error("Unsupported data type in Rules:"+s);this.assertValue(i["@rules"],"string",t,n)}}_expandRange(t){if(!t["@rules"]||!t["@rules"].range)return t;const e=function(t){if("string"!=typeof t)return null;const e=t.split("..");if(2!==e.length)return null;const r=er(e[0]),n=er(e[1]);return isNaN(r)||isNaN(n)?null:{min:r,max:n}}(t["@rules"].range);return e?{...t,"@rules":{...t["@rules"],min:void 0!==t["@rules"].min?t["@rules"].min:String(e.min),max:void 0!==t["@rules"].max?t["@rules"].max:String(e.max)}}:t}_checkDateBounds(t,e,r){if(isNaN(Date.parse(e)))return;const n=t["@rules"];let s=n.min,i=n.max;if(n.range&&(!s||!i)){const t=function(t){if("string"!=typeof t)return null;const e=t.split("..");if(2!==e.length)return null;const[r,n]=e;return isNaN(Date.parse(r))||isNaN(Date.parse(n))?null:{min:r,max:n}}(n.range);t&&(s||(s=t.min),i||(i=t.max))}void 0===s||ir(s,e)||this.setInvalidValueError("min",r,e,s),void 0===i||ar(i,e)||this.setInvalidValueError("max",r,e,i)}validateMandatoryFields(t,e){const r=Object.keys(t);for(let n=0;n<r.length;n++){if("@rules"===r[n])continue;const s=t[r[n]]["@rules"];s&&(s.minOccurs&&s.minOccurs>0||void 0!==s.nillable&&"false"===s.nillable)&&this.failures.push({code:"missing",path:(e+"."+r[n]).substr(1)})}}isMapType(t){if("string"==typeof t)return!1;const e=Object.keys(t);return t["@rules"]?1!==e.length&&void 0:0!==e.length}setInvalidValueError(t,e,r,n){this.failures.push({code:t,path:e.substr(1),actual:r,expected:n})}checkOccurences(t,e,r){["minOccurs","maxOccurs"].forEach(n=>{if(void 0!==t[n]){const s=Number(t[n]);sr[n](s,e)||this.setInvalidValueError(n,r,e,s)}})}checkNumeric(t,e,r){["min","max"].forEach(n=>{if(void 0!==t[n]){const s=Number(t[n]);nr[n](s,e)||this.setInvalidValueError(n,r,e,s)}})}checkString(t,e,r){["minLength","maxLength","length"].forEach(n=>{if(void 0!==t[n]){const s=Number(t[n]);rr[n](s,e)||this.setInvalidValueError(n,r,e,s)}}),["fixed","in"].forEach(n=>{if(void 0!==t[n]){const s=t[n];rr[n](s,e)||this.setInvalidValueError(n,r,e,s)}}),["pattern","pattern_i","pattern_im","pattern_mi"].forEach(n=>{if(void 0!==t[n]){let s="";n.length>8&&(s=n.substring(8));const i=t[n];rr.pattern(i,e,s)||this.setInvalidValueError("pattern",r,e,i)}})}assertValue(t,e,r,n){"string"===e?this.checkString(t,r,n):"num"===e&&this.checkNumeric(t,r,n)}validateBoolean(t,e,r){-1===this.options.boolean.indexOf(t)&&this.setInvalidDataType(e,r,t)}isValidNum(t,e){const r=er(e);return!isNaN(r)&&!("positiveInteger"===t&&r<0||"positiveDecimal"===t&&r<0||"integer"===t&&!function(t){return(0|t)===t}(r))}validateDate(t,e,r){const n=Date.parse(t);isNaN(n)&&this.setInvalidDataType(e,r,t)}setInvalidDataType(t,e,r){this.failures.push({code:"not a "+t,path:e.substr(1),value:r})}checkMissingSiblings(t,e,r){t.rules&&t.rules.forEach(t=>{const n=e[t]["@rules"];n&&("false"===n.nillable||n.minOccurs>0)&&this.failures.push({code:"missing",path:(r+"."+t).substr(1)})})}checkUnknownSiblings(t,e){t.data&&!this.options.unknownAllow&&t.data.forEach(t=>{this.failures.push({code:"unknown",path:(e+"."+t).substr(1)})})}}const cr=lr.prototype.traverse;lr.prototype.traverse=function(t,e,r,n){if(Array.isArray(t)&&void 0!==r&&void 0!==r["@rules"]&&void 0!==r["@rules"].repeatable)return this.checkOccurences(r["@rules"],t.length,n),t.forEach((s,i)=>{const a=n+"["+i+"]";if(Object.keys(r).length>1)this.callForCommonProperties(t[i],r,a);else{const n=r;cr.call(this,t[i],e,n,a)}}),void(t.length>0&&"object"==typeof t[0]&&this._runSiblingUniqueness(t,r,n));cr.call(this,t,e,r,n)},lr.prototype._runSiblingUniqueness=function(t,e,r){Object.keys(e).filter(t=>"@rules"!==t).forEach(n=>{const s=e[n];s&&s["@rules"]&&"true"===s["@rules"].unique&&this._checkUniqueInCollection(t,n,r)})};const hr={unknownAllow:!0,boolean:["true","false"]},ur={tags:{valueParsers:[]},attributes:{valueParsers:[]}},dr=new Ze({skip:{attributes:!1},attributes:{prefix:"",groupBy:"@rules",booleanType:!0},OutputBuilder:new Xt(ur)}),pr=new Ze({skip:{attributes:!1},attributes:{prefix:"",groupBy:":a"},OutputBuilder:new class extends Xt{getInstance(t,e){return new Ke(t,this.builderOptions,e,this.registry)}}(ur)}),fr="__nodableAttrsBucket__",gr=/<(\/?):a(\s|>|\/)/g;function mr(t){if(Array.isArray(t))for(const e of t)mr(e);else if(null!==t&&"object"==typeof t){Object.prototype.hasOwnProperty.call(t,fr)&&(t[":a"]=t[fr],delete t[fr]);for(const e of Object.keys(t))mr(t[e])}return t}function _r(t){if(!t)throw new Error("Empty data");if("string"!=typeof t)throw new Error("Not a valid string")}function Er(t,e){try{return t.parse(e)}catch(t){if(t instanceof Yt){let r=t.message;if("INVALID_ATTRIBUTE_NAME"===t.code){const t=r.slice(r.indexOf(": ")+2);r=`Attribute '${t}' is an invalid name.`}if(void 0===t.index)throw new Error(r);const n=e.substring(0,t.index).split("\n").length;throw new Error(r+":"+n)}throw t}}const br=class{constructor(t,e){_r(t),this.rules=mr(Er(dr,function(t){return t.replace(gr,`<$1${fr}$2`)}(t))),this.options=Object.assign({},hr,e),this.validators={},this.data=null}register(t,e){this.validators[t]=e}validate(t){_r(t);const{data:e,siblingOrder:r}=Er(pr,t);this.data=e;const n=new lr(this.options,this.validators,r);return n.traverse(e,"",this.rules,""),n.failures}};return e})());
|
|
2
2
|
//# sourceMappingURL=fxv.min.js.map
|