fast-xml-validator 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Amit Kumar Gupta
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,47 @@
1
+
2
+ > Created by the author of [Fast XML Parser](https://github.com/NaturalIntelligence/fast-xml-parser).
3
+
4
+ This library exposes 2 type of XML validators
5
+ 1. Syntax validator
6
+ 2. Business rule validator (Schema)
7
+
8
+ ## Syntax validator
9
+
10
+ Validate XML file for syntax errors. It
11
+
12
+ ```js
13
+ const { SyntaxValidator } = require("fast-xml-validator");
14
+ const result = SyntaxValidator.validate(xmlData, { allowBooleanAttributes: true });
15
+ ```
16
+
17
+ Options:
18
+
19
+ - allowBooleanAttributes: allow attributes without value (e.g `<book published />`)
20
+ - unpairedTags: list of tags without closing tags (e.g `<br>`, `<hr>`)
21
+ - docType: options for validating DOCTYPE entity count and size
22
+ - maxEntityCount: maximum number of entities in DOCTYPE (default: Infinity)
23
+ - maxEntitySize: maximum size of each entity in DOCTYPE (default: Infinity)
24
+
25
+ ## Business rule validator
26
+
27
+ This is somewhat like XML schema validator but with some or rather more additional features.Checkout the [Business Rule Validato](./BusinessRuleValidator.md) for more information.
28
+
29
+ ```js
30
+ const { BusinessRulesValidator } = require("fast-xml-validator");
31
+ const options = {};
32
+ const validator = new BusinessRulesValidator(rulesXml);
33
+
34
+ const result = validator.validate(xmlData, options);
35
+ ```
36
+
37
+ ### Applications
38
+ - You want to ensure the data type or, minimum or maximum value for a field.
39
+ - You want to ensure the minimum or maximum occurences of a tag.
40
+ - You want to ensure the sequence of sibling tags.
41
+ - You want to ensure that the discounted price is always lesser than total price
42
+ - You want to be informed if there are students who scored less than 35 in any subject.
43
+ - You want to ensure that the shipment date must come after an order date.
44
+ - You want to ensure that a PO must have at least one order item
45
+ - You want to ensure that email is unique for all employees
46
+ - You have your own business validations.
47
+
package/lib/fxv.cjs ADDED
@@ -0,0 +1 @@
1
+ (()=>{"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:()=>oe,SyntaxValidator:()=>le});const n=":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",r=new RegExp("^["+n+"]["+n+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$"),i=function(t){return!(null==r.exec(t))},s={maxEntityCount:1/0,maxEntitySize:1/0};class a{constructor(t){this.options=Object.assign({},s,t),this.suppressValidationErr=!t}validateDocType(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;let n=1,r=!1,i=!1,s=0;for(;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&&l(t,"!ENTITY",e))e+=7,[s,e]=this._validateEntityExp(t,e+1,s);else if(r&&l(t,"!ELEMENT",e))e+=8,e=this._validateElementExp(t,e+1);else{if(r&&l(t,"!ATTLIST",e)){e+=8,e=this._validateAttlistExp(t,e+1);continue}if(r&&l(t,"!NOTATION",e))e+=9,e=this._validateNotationExp(t,e+1);else{if(!l(t,"!--",e))throw new Error("Invalid DOCTYPE");i=!0}}n++}if(0!==n)throw new Error("Unclosed DOCTYPE");return e}_validateEntityExp(t,e,n){const r=e=o(t,e);for(;e<t.length&&!/\s/.test(t[e])&&'"'!==t[e]&&"'"!==t[e];)e++;const i=t.substring(r,e);if(h(i),e=o(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 s;[e,s]=u(t,e,"entity");const{maxEntitySize:a,maxEntityCount:l}=this.options;if(s.length>a)throw new Error(`Entity "${i}" size (${s.length}) exceeds maximum allowed size (${a})`);if(-1===s.indexOf("&")&&++n>l)throw new Error(`Entity count (${n}) exceeds maximum allowed (${l})`);return[n,e-1]}_validateNotationExp(t,e){const n=e=o(t,e);for(;e<t.length&&!/\s/.test(t[e]);)e++;const r=t.substring(n,e);!this.suppressValidationErr&&h(r),e=o(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}"`);return e=o(t,e+=i.length),"PUBLIC"===i?([e]=u(t,e,"publicIdentifier"),'"'!==t[e=o(t,e)]&&"'"!==t[e]||([e]=u(t,e,"systemIdentifier"))):"SYSTEM"===i&&([e]=u(t,e,"systemIdentifier")),--e}_validateElementExp(t,e){const n=e=o(t,e);for(;e<t.length&&!/\s/.test(t[e]);)e++;const r=t.substring(n,e);if(!this.suppressValidationErr&&!i(r))throw new Error(`Invalid element name: "${r}"`);if("E"===t[e=o(t,e)]&&l(t,"MPTY",e))e+=4;else if("A"===t[e]&&l(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}_validateAttlistExp(t,e){const n=e=o(t,e);for(;e<t.length&&!/\s/.test(t[e]);)e++;h(t.substring(n,e));const r=e=o(t,e);for(;e<t.length&&!/\s/.test(t[e]);)e++;if(h(t.substring(r,e)),e=o(t,e),"NOTATION"===t.substring(e,e+8).toUpperCase()){if("("!==t[e=o(t,e+=8)])throw new Error(`Expected '(', found "${t[e]}"`);for(e++;e<t.length&&")"!==t[e];){const n=e;for(;e<t.length&&"|"!==t[e]&&")"!==t[e];)e++;h(t.substring(n,e).trim()),"|"===t[e]&&(e=o(t,++e))}if(")"!==t[e])throw new Error("Unterminated list of notations");e++}else{const n=e;for(;e<t.length&&!/\s/.test(t[e]);)e++;const r=t.substring(n,e),i=["CDATA","ID","IDREF","IDREFS","ENTITY","ENTITIES","NMTOKEN","NMTOKENS"];if(!this.suppressValidationErr&&!i.includes(r.toUpperCase()))throw new Error(`Invalid attribute type: "${r}"`)}return e=o(t,e),"#REQUIRED"===t.substring(e,e+9).toUpperCase()?e+=9:"#IMPLIED"===t.substring(e,e+8).toUpperCase()?e+=8:[e]=u(t,e,"ATTLIST default value"),e}}function o(t,e){for(;e<t.length&&/\s/.test(t[e]);)e++;return e}function l(t,e,n){for(let r=0;r<e.length;r++)if(e[r]!==t[n+r+1])return!1;return!0}function h(t){if(!i(t))throw new Error(`Invalid entity name "${t}"`)}function u(t,e,n){const r=t[e];if('"'!==r&&"'"!==r)throw new Error(`Expected quoted string for ${n}, found "${r}"`);const i=++e;for(;e<t.length&&t[e]!==r;)e++;if(t[e]!==r)throw new Error(`Unterminated ${n} value`);const s=t.substring(i,e);return[++e,s]}class c extends Error{constructor(t,e,n,r){super(t),this.name=this.constructor.name,this.code=e,this.line=n,this.col=r,Error.captureStackTrace?.(this,this.constructor)}}const d={allowBooleanAttributes:!1,unpairedTags:[],docType:{maxEntityCount:1/0,maxEntitySize:1/0}};function p(t){return" "===t||"\t"===t||"\n"===t||"\r"===t}function f(t,e){const n=e,r=e;for(;e<t.length;e++){const i=t[e];if(" "===i||"?"===i){if("xml"===t.substr(r,e-r).toLowerCase())return v("InvalidXml","XML declaration allowed only at the start of the document.",w(t,n-2));if("?"===i&&">"===t[e+1])return++e}}return v("InvalidXml",'Processing instruction is not closed with "?>".',w(t,n-2))}function g(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}function m(t,e){let n="",r="",i=!1;for(;e<t.length;e++){if('"'===t[e]||"'"===t[e])""===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 x=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function E(t,e){const n=function(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}(t,x),r={};for(let t=0;t<n.length;t++){if(0===n[t][1].length)return{err:{code:"InvalidAttr",msg:"Attribute '"+n[t][2]+"' has no space in starting.",line:N(n[t])}};if(void 0!==n[t][3]&&void 0===n[t][4])return{err:{code:"InvalidAttr",msg:"Attribute '"+n[t][2]+"' is without value.",line:N(n[t])}};if(void 0===n[t][3]&&!e.allowBooleanAttributes)return{err:{code:"InvalidAttr",msg:"boolean attribute '"+n[t][2]+"' is not allowed.",line:N(n[t])}};const i=n[t][2];if(!y(i))return{err:{code:"InvalidAttr",msg:"Attribute '"+i+"' is an invalid name.",line:N(n[t])}};if("xmlns"===i&&""===n[t][6])return{err:{code:"InvalidAttr",msg:'Undeclaring the default namespace with xmlns="" is only permitted in XML 1.1 documents.',line:N(n[t])}};if(Object.prototype.hasOwnProperty.call(r,i))return{err:{code:"InvalidAttr",msg:"Attribute '"+i+"' is repeated.",line:N(n[t])}};r[i]=1}return!0}function b(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 v(t,e,n){throw new c(e,t,n.line||n,n.col)}function y(t){if(!t||0===t.length)return!1;const e=t.indexOf(":");if(-1===e)return i(t);if(-1!==t.indexOf(":",e+1))return!1;const n=t.substring(0,e),r=t.substring(e+1);return 0!==n.length&&0!==r.length&&i(n)&&i(r)}function w(t,e){const n=t.substring(0,e).split(/\r?\n/);return{line:n.length,col:n[n.length-1].length+1}}function N(t){return t.startIndex+t[1].length}const _=":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",S=new RegExp("^["+_+"]["+_+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$");function T(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 I=function(t){return!(null==S.exec(t))},C=["hasOwnProperty","toString","valueOf","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"],A=["__proto__","constructor","prototype"],O=t=>C.includes(t)?"__"+t:t,D={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:O};function P(t,e){if("string"!=typeof t)return;const n=t.toLowerCase();if(C.some(t=>n===t.toLowerCase()))throw new Error(`[SECURITY] Invalid ${e}: "${t}" is a reserved JavaScript keyword that could cause prototype pollution`);if(A.some(t=>n===t.toLowerCase()))throw new Error(`[SECURITY] Invalid ${e}: "${t}" is a reserved JavaScript keyword that could cause prototype pollution`)}function M(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"}:M(!0)}const k=function(t){const e=Object.assign({},D,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&&P(t,e);return null===e.onDangerousProperty&&(e.onDangerousProperty=O),e.processEntities=M(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 $;$="function"!=typeof Symbol?"@@xmlMetadata":Symbol("XML Node Metadata");class V{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][$]={startIndex:e})}static getMetaDataSymbol(){return $}}class F{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&&L(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&&L(t,"!ELEMENT",e)){e+=8;const{index:n}=this.readElementExp(t,e+1);e=n}else if(s&&L(t,"!ATTLIST",e))e+=8;else if(s&&L(t,"!NOTATION",e)){e+=9;const{index:n}=this.readNotationExp(t,e+1,this.suppressValidationErr);e=n}else{if(!L(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=j(t,e);for(;e<t.length&&!/\s/.test(t[e])&&'"'!==t[e]&&"'"!==t[e];)e++;let r=t.substring(n,e);if(U(r),e=j(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=j(t,e);for(;e<t.length&&!/\s/.test(t[e]);)e++;let r=t.substring(n,e);!this.suppressValidationErr&&U(r),e=j(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=j(t,e);let s=null,a=null;if("PUBLIC"===i)[e,s]=this.readIdentifierVal(t,e,"publicIdentifier"),'"'!==t[e=j(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=j(t,e);for(;e<t.length&&!/\s/.test(t[e]);)e++;let r=t.substring(n,e);if(!this.suppressValidationErr&&!I(r))throw new Error(`Invalid element name: "${r}"`);let i="";if("E"===t[e=j(t,e)]&&L(t,"MPTY",e))e+=4;else if("A"===t[e]&&L(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=j(t,e);for(;e<t.length&&!/\s/.test(t[e]);)e++;let r=t.substring(n,e);for(U(r),n=e=j(t,e);e<t.length&&!/\s/.test(t[e]);)e++;let i=t.substring(n,e);if(!U(i))throw new Error(`Invalid attribute name: "${i}"`);e=j(t,e);let s="";if("NOTATION"===t.substring(e,e+8).toUpperCase()){if(s="NOTATION","("!==t[e=j(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(),!U(i))throw new Error(`Invalid notation name: "${i}"`);n.push(i),"|"===t[e]&&(e++,e=j(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=j(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 j=(t,e)=>{for(;e<t.length&&/\s/.test(t[e]);)e++;return e};function L(t,e,n){for(let r=0;r<e.length;r++)if(e[r]!==t[n+r+1])return!1;return!0}function U(t){if(I(t))return t;throw new Error(`Invalid entity name ${t}`)}const R=/^[-+]?0x[a-fA-F0-9]+$/,B=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,Y={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0,infinity:"original"};const q=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;class X{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 W{constructor(t={}){this.separator=t.separator||".",this.path=[],this.siblingStacks=[],this._pathStringCache=null,this._view=new X(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 z{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 G{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 Z={cent:"¢",pound:"£",curren:"¤",yen:"¥",euro:"€",dollar:"$",euro:"€",fnof:"ƒ",inr:"₹",af:"؋",birr:"ብር",peso:"₱",rub:"₽",won:"₩",yuan:"¥",cedil:"¸"},J={amp:"&",apos:"'",gt:">",lt:"<",quot:'"'},K={nbsp:" ",copy:"©",reg:"®",trade:"™",mdash:"—",ndash:"–",hellip:"…",laquo:"«",raquo:"»",lsquo:"‘",rsquo:"’",ldquo:"“",rdquo:"”",bull:"•",para:"¶",sect:"§",deg:"°",frac12:"½",frac14:"¼",frac34:"¾"},Q=new Set("!?\\\\/[]$%{}^&*()<>|+");function H(t){if("#"===t[0])throw new Error(`[EntityReplacer] Invalid character '#' in entity name: "${t}"`);for(const e of t)if(Q.has(e))throw new Error(`[EntityReplacer] Invalid character '${e}' in entity name: "${t}"`);return t}function tt(...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 et="external",nt="base",rt="all",it=Object.freeze({allow:0,leave:1,remove:2,throw:3}),st=new Set([9,10,13]);class at{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??et)&&e!==et?e===rt?new Set([rt]):e===nt?new Set([nt]):Array.isArray(e)?new Set(e):new Set([et]):new Set([et]),this._numericAllowed=t.numericAllowed??!0,this._baseMap=tt(J,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:it.allow,nullLevel:it.remove};const e=1.1===t.xmlVersion?1.1:1,n=it[t.onNCR]??it.allow,r=it[t.nullNCR]??it.remove;return{xmlVersion:e,onLevel:n,nullLevel:Math.max(r,it.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))H(e);this._externalMap=tt(t)}addExternalEntity(t,e){H(t),"string"==typeof e&&-1===e.indexOf("&")&&(this._externalMap[t]=e)}addInputEntities(t){this._totalExpansions=0,this._expandedLength=0,this._inputMap=tt(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=et);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=nt}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(rt)||this._limitTiers.has(t)}_resolveName(t){return t in this._inputMap?{value:this._inputMap[t],tier:et}:t in this._externalMap?{value:this._externalMap[t],tier:et}:t in this._baseMap?{value:this._baseMap[t],tier:nt}:void 0}_classifyNCR(t){return 0===t?this._ncrNullLevel:t>=55296&&t<=57343||1===this._ncrXmlVersion&&t>=1&&t<=31&&!st.has(t)?it.remove:-1}_applyNCRAction(t,e,n){switch(t){case it.allow:return String.fromCodePoint(n);case it.remove:return"";case it.leave:return;case it.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<it.remove)return;const i=-1===r?this._ncrOnLevel:Math.max(this._ncrOnLevel,r);return this._applyNCRAction(i,t,n)}}function ot(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 lt(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 ht{constructor(t){var e;this.options=t,this.currentNode=null,this.tagsNodeStack=[],this.parseXml=ft,this.parseTextData=ut,this.resolveNameSpace=ct,this.buildAttributesMap=pt,this.isItStopNode=Et,this.replaceEntitiesValue=mt,this.readStopNodeData=wt,this.saveTextToParentTag=xt,this.addChild=gt,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={...J};this.options.entityDecoder?this.entityDecoder=this.options.entityDecoder:("object"==typeof this.options.htmlEntities?n=this.options.htmlEntities:!0===this.options.htmlEntities&&(n={...K,...Z}),this.entityDecoder=new at({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 W,this.readonlyMatcher=this.matcher.readOnly(),this.isCurrentNodeStopNode=!1,this.stopNodeExpressionsSet=new G;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 z(e)):e instanceof z&&this.stopNodeExpressionsSet.add(e)}this.stopNodeExpressionsSet.seal()}}}function ut(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?Nt(t,o.parseTagValue,o.numberParseOptions):t}}function ct(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 dt=new RegExp("([^\\s=]+)\\s*(=\\s*(['\"])([\\s\\S]*?)\\3)?","gm");function pt(t,e,n,r=!1){const i=this.options;if(!0===r||!0!==i.ignoreAttributes&&"string"==typeof t){const r=T(t,dt),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=St(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:Nt(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 ft=function(t){t=t.replace(/\r\n?/g,"\n");const e=new V("!xml");let n=e,r="";this.matcher.reset(),this.entityDecoder.reset(),this.entityExpansionCount=0,this.currentExpandedLength=0;const i=this.options,s=new F(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=bt(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=_t(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=yt(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 V(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=bt(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=bt(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=yt(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}=_t(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,x={};g=lt(h),l!==e.tagname&&this.matcher.push(l,{},g),l!==u&&c&&(m=this.buildAttributesMap(u,this.matcher,l),m&&(x=ot(m,i))),l!==e.tagname&&(this.isCurrentNodeStopNode=this.isItStopNode());const E=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 V(l);m&&(r[":@"]=m),r.add(i.textNodeName,e),this.matcher.pop(),this.isCurrentNodeStopNode=!1,this.addChild(n,r,this.readonlyMatcher,E)}else{if(f){({tagName:l,tagExp:u}=_t(i.transformTagName,l,u,i));const t=new V(l);m&&(t[":@"]=m),this.addChild(n,t,this.readonlyMatcher,E),this.matcher.pop(),this.isCurrentNodeStopNode=!1}else{if(i.unpairedTagsSet.has(l)){const t=new V(l);m&&(t[":@"]=m),this.addChild(n,t,this.readonlyMatcher,E),this.matcher.pop(),this.isCurrentNodeStopNode=!1,o=s.closeIndex;continue}{const t=new V(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,E),n=t}}r="",o=d}}}else r+=t[o];return e.child};function gt(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 mt(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 xt(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 Et(){return 0!==this.stopNodeExpressionsSet.size&&this.matcher.matchesAny(this.stopNodeExpressionsSet)}function bt(t,e,n,r){const i=t.indexOf(e,n);if(-1===i)throw new Error(r);return i+e.length-1}function vt(t,e,n,r){const i=t.indexOf(e,n);if(-1===i)throw new Error(r);return i}function yt(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 wt(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=vt(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=bt(t,"?>",n+1,"StopNode is not closed.");else if(33===s&&45===t.charCodeAt(n+2)&&45===t.charCodeAt(n+3))n=bt(t,"--\x3e",n+3,"StopNode is not closed.");else if(33===s&&91===t.charCodeAt(n+2))n=bt(t,"]]>",n,"StopNode is not closed.")-2;else{const r=yt(t,n,">");r&&((r&&r.tagName)===e&&"/"!==r.tagExp[r.tagExp.length-1]&&i++,n=r.closeIndex)}}}function Nt(t,e,n){if(e&&"string"==typeof t){const e=t.trim();return"true"===e||"false"!==e&&function(t,e={}){if(e=Object.assign({},Y,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&&R.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(q);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=B.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 _t(t,e,n,r){if(t){const r=t(e);n===e&&(n=r),e=r}return{tagName:e=St(e,r),tagExp:n}}function St(t,e){if(A.includes(t))throw new Error(`[SECURITY] Invalid name: "${t}" is a reserved JavaScript keyword that could cause prototype pollution`);return C.includes(t)?e.onDangerousProperty(t):t}const Tt=V.getMetaDataSymbol();function It(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 Ct(t,e,n,r){return At(t,e,n,r)}function At(t,e,n,r){let i;const s={};for(let a=0;a<t.length;a++){const o=t[a],l=Ot(o);if(void 0!==l&&l!==e.textNodeName){const t=It(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=At(o[l],e,n,r);const i=Pt(t,e);if(o[":@"]?Dt(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[Tt]&&"object"==typeof t&&null!==t&&(t[Tt]=o[Tt]),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 Ot(t){const e=Object.keys(t);for(let t=0;t<e.length;t++){const n=e[t];if(":@"!==n)return n}}function Dt(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 Pt(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 Mt={allowBooleanAttributes:!1,unpairedTags:[]};function kt(t,e){e=Object.assign({},Mt,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=Vt(t,s),s.err)return s}else{if("<"!==t[s]){if($t(t[s]))continue;return qt("InvalidChar","char '"+t[s]+"' is not expected.",zt(t,s))}{let a=s;if(s++,"!"===t[s]){s=Ft(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--),!Wt(l)){let e;return e=0===l.trim().length?"Invalid space after '<'.":"Tag '"+l+"' is an invalid name.",qt("InvalidTag",e,zt(t,s))}const h=Ut(t,s);if(!1===h)return qt("InvalidAttr","Attributes for '"+l+"' have open quote.",zt(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=Bt(u,e);if(!0!==i)return qt(i.err.code,i.err.msg,zt(t,n+i.err.line));r=!0}else if(o){if(!h.tagClosed)return qt("InvalidTag","Closing tag '"+l+"' doesn't have proper closing.",zt(t,s));if(u.trim().length>0)return qt("InvalidTag","Closing tag '"+l+"' can't have attributes or invalid starting.",zt(t,a));if(0===n.length)return qt("InvalidTag","Closing tag '"+l+"' has not been opened.",zt(t,a));{const e=n.pop();if(l!==e.tagName){let n=zt(t,e.tagStartPos);return qt("InvalidTag","Expected closing tag '"+e.tagName+"' (opened in line "+n.line+", col "+n.col+") instead of closing tag '"+l+"'.",zt(t,a))}0==n.length&&(i=!0)}}else{const o=Bt(u,e);if(!0!==o)return qt(o.err.code,o.err.msg,zt(t,s-u.length+o.err.line));if(!0===i)return qt("InvalidXml","Multiple possible root nodes found.",zt(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=Ft(t,s);continue}if("?"!==t[s+1])break;if(s=Vt(t,++s),s.err)return s}else if("&"===t[s]){const e=Yt(t,s);if(-1==e)return qt("InvalidChar","char '&' is not expected.",zt(t,s));s=e}else if(!0===i&&!$t(t[s]))return qt("InvalidXml","Extra text at the end",zt(t,s));"<"===t[s]&&s--}}}return r?1==n.length?qt("InvalidTag","Unclosed tag '"+n[0].tagName+"'.",zt(t,n[0].tagStartPos)):!(n.length>0)||qt("InvalidXml","Invalid '"+JSON.stringify(n.map(t=>t.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):qt("InvalidXml","Start tag expected.",1)}function $t(t){return" "===t||"\t"===t||"\n"===t||"\r"===t}function Vt(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 qt("InvalidXml","XML declaration allowed only at the start of the document.",zt(t,e));if("?"==t[e]&&">"==t[e+1]){e++;break}continue}return e}function Ft(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 jt='"',Lt="'";function Ut(t,e){let n="",r="",i=!1;for(;e<t.length;e++){if(t[e]===jt||t[e]===Lt)""===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 Rt=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function Bt(t,e){const n=T(t,Rt),r={};for(let t=0;t<n.length;t++){if(0===n[t][1].length)return qt("InvalidAttr","Attribute '"+n[t][2]+"' has no space in starting.",Gt(n[t]));if(void 0!==n[t][3]&&void 0===n[t][4])return qt("InvalidAttr","Attribute '"+n[t][2]+"' is without value.",Gt(n[t]));if(void 0===n[t][3]&&!e.allowBooleanAttributes)return qt("InvalidAttr","boolean attribute '"+n[t][2]+"' is not allowed.",Gt(n[t]));const i=n[t][2];if(!Xt(i))return qt("InvalidAttr","Attribute '"+i+"' is an invalid name.",Gt(n[t]));if(Object.prototype.hasOwnProperty.call(r,i))return qt("InvalidAttr","Attribute '"+i+"' is repeated.",Gt(n[t]));r[i]=1}return!0}function Yt(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 qt(t,e,n){return{err:{code:t,msg:e,line:n.line||n,col:n.col}}}function Xt(t){return I(t)}function Wt(t){return I(t)}function zt(t,e){const n=t.substring(0,e).split(/\r?\n/);return{line:n.length,col:n[n.length-1].length+1}}function Gt(t){return t.startIndex+t[1].length}class Zt{constructor(t){this.externalEntities={},this.options=k(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=kt(t,e);if(!0!==n)throw Error(`${n.err.msg}:${n.err.line}:${n.err.col}`)}const n=new ht(this.options);n.entityDecoder.setExternalEntities(this.externalEntities);const r=n.parseXml(t);return this.options.preserveOrder||void 0===r?r:Ct(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 '&#xD;'");if("&"===e)throw new Error("An entity with value '&' is not permitted");this.externalEntities[t]=e}static getMetaDataSymbol(){return V.getMetaDataSymbol()}}const Jt={validate:kt},Kt={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},Qt={min:(t,e)=>Number(e)>=t,max:(t,e)=>Number(e)<=t},Ht={minOccurs:(t,e)=>e>=t,maxOccurs:(t,e)=>e<=t},te=(t,e)=>Date.parse(e)>=Date.parse(t),ee=(t,e)=>Date.parse(e)<=Date.parse(t),ne=["positiveInteger","integer","positiveDecimal","decimal","number"];class re{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!==ne.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!==ne.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||te(i,e)||this.setInvalidValueError("min",n,e,i),void 0===s||ee(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]);Ht[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]);Qt[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]);Kt[r](i,e)||this.setInvalidValueError(r,n,e,i)}}),["fixed","in"].forEach(r=>{if(void 0!==t[r]){const i=t[r];Kt[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];Kt.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 ie=re.prototype.traverse;re.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;ie.call(this,t[s],e,r,a)}}),void(t.length>0&&"object"==typeof t[0]&&this._runSiblingUniqueness(t,n,r));ie.call(this,t,e,n,r)},re.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 se={unknownAllow:!0,boolean:["true","false"]};function ae(t){if(!t)throw new Error("Empty data");if("string"!=typeof t)throw new Error("Not a valid string");const e=Jt.validate(t,{allowBooleanAttributes:!0});if(!0!==e)throw new Error(e.err.msg+":"+e.err.line)}const oe=class{constructor(t,e){ae(t);const n=new Zt({ignoreAttributes:!1,attributesGroupName:"@rules",attributeNamePrefix:"",allowBooleanAttributes:!0});this.rules=n.parse(t),this.options=Object.assign({},se,e),this.validators={},this.data=null}register(t,e){this.validators[t]=e}validate(t){ae(t);const e=new Map,n=new Zt({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 re(this.options,this.validators,e);return r.traverse(n,"",this.rules,""),r.failures}};class le{static validate(t,e){return function(t,e){e=Object.assign({},d,e);const n=new a(e.docType),r=[];let i=!1,s=!1;if("\ufeff"===t[0]&&(t=t.substr(1)),t.startsWith("<?xml")){const e=t.indexOf("?>");if(-1===e)return v("InvalidXml",'Processing instruction is not closed with "?>".',{line:1,col:1});t=t.substring(e+2)}for(let a=0;a<t.length;a++)if("<"===t[a]&&"?"===t[a+1]){if(a+=2,a=f(t,a),a.err)return a}else{if("<"!==t[a]){if(p(t[a]))continue;return s?v("InvalidXml","Extra text at the end: '"+t[a]+"' is not expected.",w(t,a)):v("InvalidChar","char '"+t[a]+"' is not expected.",w(t,a))}{let o=a;if(a++,"!"===t[a]){try{a=g(t,a,n)}catch(e){return v("InvalidTag",e.message,w(t,a-1))}continue}{let l=!1;"/"===t[a]&&(l=!0,a++);let h="";for(;a<t.length&&">"!==t[a]&&" "!==t[a]&&"\t"!==t[a]&&"\n"!==t[a]&&"\r"!==t[a];a++)h+=t[a];if(h=h.trim(),"/"===h[h.length-1]&&(h=h.substring(0,h.length-1),a--),!y(h)){let e;return e=0===h.trim().length?"Invalid space after '<'.":"Tag '"+h+"' is an invalid name.",v("InvalidTag",e,w(t,o))}const u=m(t,a);if(!1===u)return v("InvalidAttr","Attributes for '"+h+"' have open quote.",w(t,a));let c=u.value;if(a=u.index,"/"===c[c.length-1]){const n=a-c.length;c=c.substring(0,c.length-1);const l=E(c,e);if(!0!==l)return v(l.err.code,l.err.msg,w(t,n+l.err.line));if(!0===s)return v("InvalidXml","Multiple possible root nodes found.",w(t,o));i=!0,0===r.length&&(s=!0)}else if(l){if(!u.tagClosed)return v("InvalidTag","Closing tag '"+h+"' doesn't have proper closing.",w(t,a));if(c.trim().length>0)return v("InvalidTag","Closing tag '"+h+"' can't have attributes or invalid starting.",w(t,o));if(0===r.length)return v("InvalidTag","Closing tag '"+h+"' has not been opened.",w(t,o));{const e=r.pop();if(h!==e.tagName){let n=w(t,e.tagStartPos);return v("InvalidTag","Expected closing tag '"+e.tagName+"' (opened in line "+n.line+", col "+n.col+") instead of closing tag '"+h+"'.",w(t,o))}0===r.length&&(s=!0)}}else{const n=E(c,e);if(!0!==n)return v(n.err.code,n.err.msg,w(t,a-c.length+n.err.line));if(!0===s)return v("InvalidXml","Multiple possible root nodes found.",w(t,a));-1!==e.unpairedTags.indexOf(h)||r.push({tagName:h,tagStartPos:o}),i=!0}for(a++;a<t.length;a++)if("<"===t[a]){if("!"===t[a+1]){a++;try{a=g(t,a,n)}catch(e){return v("InvalidDocType",e.message,w(t,a-1))}continue}if("?"!==t[a+1])break;if(a+=2,a=f(t,a),a.err)return a}else if("&"===t[a]){const e=b(t,a);if(-1===e)return v("InvalidChar","char '&' is not expected.",w(t,a));a=e}else if(!0===s&&!p(t[a]))return v("InvalidXml","Extra text at the end",w(t,a));"<"===t[a]&&a--}}}return i?1===r.length?v("InvalidTag","Unclosed tag '"+r[0].tagName+"'.",w(t,r[0].tagStartPos)):!(r.length>0)||v("InvalidXml","Invalid '"+JSON.stringify(r.map(t=>t.tagName)).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):v("InvalidXml","Start tag expected.",{line:1,col:1})}(t,e)}}module.exports=e})();
package/lib/fxv.d.cts ADDED
@@ -0,0 +1,129 @@
1
+ type docTypeOptions = {
2
+ /**
3
+ * maximum number of entity present in DOCTYPE
4
+ *
5
+ * Defaults to `Infinity`
6
+ */
7
+ maxEntityCount?: number;
8
+
9
+ /**
10
+ * maximum size of each entity present in DOCTYPE
11
+ *
12
+ * Defaults to `Infinity`
13
+ */
14
+ maxEntitySize?: number;
15
+ }
16
+
17
+ type validationOptions = {
18
+ /**
19
+ * Whether to allow attributes without value
20
+ *
21
+ * Defaults to `false`
22
+ */
23
+ allowBooleanAttributes?: boolean;
24
+
25
+ /**
26
+ * List of tags without closing tags
27
+ *
28
+ * Defaults to `[]`
29
+ */
30
+ unpairedTags?: string[];
31
+
32
+ docType?: docTypeOptions;
33
+ };
34
+
35
+ type ValidationError = {
36
+ err: {
37
+ code: string;
38
+ msg: string,
39
+ line: number,
40
+ col: number
41
+ };
42
+ };
43
+
44
+
45
+ declare class SyntaxValidator {
46
+ static validate(xmlData: string, options?: validationOptions): true | ValidationError;
47
+ }
48
+
49
+ interface BusinessRulesValidatorOptions {
50
+ unknownAllow?: boolean;
51
+ boolean?: string[];
52
+ }
53
+
54
+ type ValidationFailure = {
55
+ code: string;
56
+ path: string;
57
+ value?: string;
58
+ actual?: number | string;
59
+ expected?: number | string;
60
+ }
61
+
62
+ type CustomValidatorFn = (
63
+ value: string,
64
+ path: string
65
+ ) => ValidationFailure | Record<string, unknown> | undefined | null | void;
66
+
67
+ declare class BusinessRulesValidator {
68
+ /**
69
+ * Create a new Validator with a rules XML string.
70
+ *
71
+ * @param rules - XML string whose attributes define validation constraints.
72
+ * @param options - Optional configuration.
73
+ *
74
+ * @throws {Error} If `rules` is empty, not a string, or contains XML syntax errors.
75
+ *
76
+ * @example
77
+ * ```ts
78
+ * const validator = new Validator(`
79
+ * <students>
80
+ * <student repeatable minOccurs="1">
81
+ * <email unique="true" nillable="false"></email>
82
+ * <age type="integer" range="18..65"></age>
83
+ * </student>
84
+ * </students>
85
+ * `);
86
+ * ```
87
+ */
88
+ constructor(rules: string, options?: BusinessRulesValidatorOptions);
89
+
90
+ /**
91
+ * Register a custom validation function under a name.
92
+ * Reference it in rules XML with `checkBy="<name>"`.
93
+ *
94
+ * @example
95
+ * ```ts
96
+ * validator.register("isEmail", (value, path) => {
97
+ * if (!value.includes("@")) {
98
+ * return { code: "invalid-email", path, value };
99
+ * }
100
+ * });
101
+ * ```
102
+ */
103
+ register(name: string, fn: CustomValidatorFn): void;
104
+
105
+ /**
106
+ * Validate an XML string against the rules.
107
+ *
108
+ * @param xmldata - XML string to validate.
109
+ * @returns Array of failure objects. Empty array means the document is valid.
110
+ *
111
+ * @throws {Error} If `xmldata` is empty, not a string, or contains XML syntax errors.
112
+ */
113
+ validate(xmldata: string): ValidationFailure[];
114
+ }
115
+
116
+
117
+ declare namespace fxv {
118
+ export {
119
+ SyntaxValidator,
120
+ ValidationError,
121
+ validationOptions,
122
+ BusinessRulesValidatorOptions,
123
+
124
+ }
125
+ }
126
+
127
+
128
+
129
+ export = fxv;
package/lib/fxv.min.js ADDED
@@ -0,0 +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:()=>ce,SyntaxValidator:()=>de});var n=":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",r=new RegExp("^["+n+"]["+n+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$"),i=function(t){return!(null==r.exec(t))},s={maxEntityCount:1/0,maxEntitySize:1/0},a=function(){function t(t){this.options=Object.assign({},s,t),this.suppressValidationErr=!t}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&&l(t,"!ENTITY",e)){e+=7;var a=this._validateEntityExp(t,e+1,s);s=a[0],e=a[1]}else if(r&&l(t,"!ELEMENT",e))e+=8,e=this._validateElementExp(t,e+1);else{if(r&&l(t,"!ATTLIST",e)){e+=8,e=this._validateAttlistExp(t,e+1);continue}if(r&&l(t,"!NOTATION",e))e+=9,e=this._validateNotationExp(t,e+1);else{if(!l(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=o(t,e);e<t.length&&!/\s/.test(t[e])&&'"'!==t[e]&&"'"!==t[e];)e++;var i,s=t.substring(r,e);if(u(s),e=o(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=h(t,e,"entity");e=a[0],i=a[1];var l=this.options,c=l.maxEntitySize,d=l.maxEntityCount;if(i.length>c)throw new Error('Entity "'+s+'" size ('+i.length+") exceeds maximum allowed size ("+c+")");if(-1===i.indexOf("&")&&++n>d)throw new Error("Entity count ("+n+") exceeds maximum allowed ("+d+")");return[n,e-1]},e._validateNotationExp=function(t,e){for(var n=e=o(t,e);e<t.length&&!/\s/.test(t[e]);)e++;var r=t.substring(n,e);!this.suppressValidationErr&&u(r),e=o(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=o(t,e+=i.length),"PUBLIC"===i?'"'!==t[e=o(t,e=h(t,e,"publicIdentifier")[0])]&&"'"!==t[e]||(e=h(t,e,"systemIdentifier")[0]):"SYSTEM"===i&&(e=h(t,e,"systemIdentifier")[0]),--e},e._validateElementExp=function(t,e){for(var n=e=o(t,e);e<t.length&&!/\s/.test(t[e]);)e++;var r=t.substring(n,e);if(!this.suppressValidationErr&&!i(r))throw new Error('Invalid element name: "'+r+'"');if("E"===t[e=o(t,e)]&&l(t,"MPTY",e))e+=4;else if("A"===t[e]&&l(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=o(t,e);e<t.length&&!/\s/.test(t[e]);)e++;u(t.substring(n,e));for(var r=e=o(t,e);e<t.length&&!/\s/.test(t[e]);)e++;if(u(t.substring(r,e)),e=o(t,e),"NOTATION"===t.substring(e,e+8).toUpperCase()){if("("!==t[e=o(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++;u(t.substring(i,e).trim()),"|"===t[e]&&(e=o(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=o(t,e),"#REQUIRED"===t.substring(e,e+9).toUpperCase()?e+=9:"#IMPLIED"===t.substring(e,e+8).toUpperCase()?e+=8:e=h(t,e,"ATTLIST default value")[0],e},t}();function o(t,e){for(;e<t.length&&/\s/.test(t[e]);)e++;return e}function l(t,e,n){for(var r=0;r<e.length;r++)if(e[r]!==t[n+r+1])return!1;return!0}function u(t){if(!i(t))throw new Error('Invalid entity name "'+t+'"')}function h(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 c(t){var e="function"==typeof Map?new Map:void 0;return c=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(d())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,e);var i=new(t.bind.apply(t,r));return n&&p(i,n.prototype),i}(t,arguments,f(this).constructor)}return n.prototype=Object.create(t.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),p(n,t)},c(t)}function d(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(d=function(){return!!t})()}function p(t,e){return p=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},p(t,e)}function f(t){return f=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},f(t)}var g=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,p(n,r),e}(c(Error)),m={allowBooleanAttributes:!1,unpairedTags:[],docType:{maxEntityCount:1/0,maxEntitySize:1/0}};function v(t){return" "===t||"\t"===t||"\n"===t||"\r"===t}function x(t,e){for(var n=e,r=e;e<t.length;e++){var i=t[e];if(" "===i||"?"===i){if("xml"===t.substr(r,e-r).toLowerCase())return _("InvalidXml","XML declaration allowed only at the start of the document.",T(t,n-2));if("?"===i&&">"===t[e+1])return++e}}return _("InvalidXml",'Processing instruction is not closed with "?>".',T(t,n-2))}function b(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}function E(t,e){for(var n="",r="",i=!1;e<t.length;e++){if('"'===t[e]||"'"===t[e])""===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 y=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function w(t,e){for(var n=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,y),r={},i=0;i<n.length;i++){if(0===n[i][1].length)return{err:{code:"InvalidAttr",msg:"Attribute '"+n[i][2]+"' has no space in starting.",line:I(n[i])}};if(void 0!==n[i][3]&&void 0===n[i][4])return{err:{code:"InvalidAttr",msg:"Attribute '"+n[i][2]+"' is without value.",line:I(n[i])}};if(void 0===n[i][3]&&!e.allowBooleanAttributes)return{err:{code:"InvalidAttr",msg:"boolean attribute '"+n[i][2]+"' is not allowed.",line:I(n[i])}};var s=n[i][2];if(!S(s))return{err:{code:"InvalidAttr",msg:"Attribute '"+s+"' is an invalid name.",line:I(n[i])}};if("xmlns"===s&&""===n[i][6])return{err:{code:"InvalidAttr",msg:'Undeclaring the default namespace with xmlns="" is only permitted in XML 1.1 documents.',line:I(n[i])}};if(Object.prototype.hasOwnProperty.call(r,s))return{err:{code:"InvalidAttr",msg:"Attribute '"+s+"' is repeated.",line:I(n[i])}};r[s]=1}return!0}function N(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 _(t,e,n){throw new g(e,t,n.line||n,n.col)}function S(t){if(!t||0===t.length)return!1;var e=t.indexOf(":");if(-1===e)return i(t);if(-1!==t.indexOf(":",e+1))return!1;var n=t.substring(0,e),r=t.substring(e+1);return 0!==n.length&&0!==r.length&&i(n)&&i(r)}function T(t,e){var n=t.substring(0,e).split(/\r?\n/);return{line:n.length,col:n[n.length-1].length+1}}function I(t){return t.startIndex+t[1].length}const C=":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",A=new RegExp("^["+C+"]["+C+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$");function O(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 D=function(t){return!(null==A.exec(t))},P=["hasOwnProperty","toString","valueOf","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"],M=["__proto__","constructor","prototype"],k=t=>P.includes(t)?"__"+t:t,V={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:k};function j(t,e){if("string"!=typeof t)return;const n=t.toLowerCase();if(P.some(t=>n===t.toLowerCase()))throw new Error(`[SECURITY] Invalid ${e}: "${t}" is a reserved JavaScript keyword that could cause prototype pollution`);if(M.some(t=>n===t.toLowerCase()))throw new Error(`[SECURITY] Invalid ${e}: "${t}" is a reserved JavaScript keyword that could cause prototype pollution`)}function F(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"}:F(!0)}const $=function(t){const e=Object.assign({},V,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&&j(t,e);return null===e.onDangerousProperty&&(e.onDangerousProperty=k),e.processEntities=F(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 L;L="function"!=typeof Symbol?"@@xmlMetadata":Symbol("XML Node Metadata");class U{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][L]={startIndex:e})}static getMetaDataSymbol(){return L}}class R{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&&Y(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&&Y(t,"!ELEMENT",e)){e+=8;const{index:n}=this.readElementExp(t,e+1);e=n}else if(s&&Y(t,"!ATTLIST",e))e+=8;else if(s&&Y(t,"!NOTATION",e)){e+=9;const{index:n}=this.readNotationExp(t,e+1,this.suppressValidationErr);e=n}else{if(!Y(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=B(t,e);for(;e<t.length&&!/\s/.test(t[e])&&'"'!==t[e]&&"'"!==t[e];)e++;let r=t.substring(n,e);if(q(r),e=B(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=B(t,e);for(;e<t.length&&!/\s/.test(t[e]);)e++;let r=t.substring(n,e);!this.suppressValidationErr&&q(r),e=B(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=B(t,e);let s=null,a=null;if("PUBLIC"===i)[e,s]=this.readIdentifierVal(t,e,"publicIdentifier"),'"'!==t[e=B(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=B(t,e);for(;e<t.length&&!/\s/.test(t[e]);)e++;let r=t.substring(n,e);if(!this.suppressValidationErr&&!D(r))throw new Error(`Invalid element name: "${r}"`);let i="";if("E"===t[e=B(t,e)]&&Y(t,"MPTY",e))e+=4;else if("A"===t[e]&&Y(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=B(t,e);for(;e<t.length&&!/\s/.test(t[e]);)e++;let r=t.substring(n,e);for(q(r),n=e=B(t,e);e<t.length&&!/\s/.test(t[e]);)e++;let i=t.substring(n,e);if(!q(i))throw new Error(`Invalid attribute name: "${i}"`);e=B(t,e);let s="";if("NOTATION"===t.substring(e,e+8).toUpperCase()){if(s="NOTATION","("!==t[e=B(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(),!q(i))throw new Error(`Invalid notation name: "${i}"`);n.push(i),"|"===t[e]&&(e++,e=B(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=B(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 B=(t,e)=>{for(;e<t.length&&/\s/.test(t[e]);)e++;return e};function Y(t,e,n){for(let r=0;r<e.length;r++)if(e[r]!==t[n+r+1])return!1;return!0}function q(t){if(D(t))return t;throw new Error(`Invalid entity name ${t}`)}const X=/^[-+]?0x[a-fA-F0-9]+$/,W=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,z={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0,infinity:"original"};const G=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;class Z{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 J{constructor(t={}){this.separator=t.separator||".",this.path=[],this.siblingStacks=[],this._pathStringCache=null,this._view=new Z(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 K{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 Q{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 H={cent:"¢",pound:"£",curren:"¤",yen:"¥",euro:"€",dollar:"$",euro:"€",fnof:"ƒ",inr:"₹",af:"؋",birr:"ብር",peso:"₱",rub:"₽",won:"₩",yuan:"¥",cedil:"¸"},tt={amp:"&",apos:"'",gt:">",lt:"<",quot:'"'},et={nbsp:" ",copy:"©",reg:"®",trade:"™",mdash:"—",ndash:"–",hellip:"…",laquo:"«",raquo:"»",lsquo:"‘",rsquo:"’",ldquo:"“",rdquo:"”",bull:"•",para:"¶",sect:"§",deg:"°",frac12:"½",frac14:"¼",frac34:"¾"},nt=new Set("!?\\\\/[]$%{}^&*()<>|+");function rt(t){if("#"===t[0])throw new Error(`[EntityReplacer] Invalid character '#' in entity name: "${t}"`);for(const e of t)if(nt.has(e))throw new Error(`[EntityReplacer] Invalid character '${e}' in entity name: "${t}"`);return t}function it(...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 st="external",at="base",ot="all",lt=Object.freeze({allow:0,leave:1,remove:2,throw:3}),ut=new Set([9,10,13]);class ht{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??st)&&e!==st?e===ot?new Set([ot]):e===at?new Set([at]):Array.isArray(e)?new Set(e):new Set([st]):new Set([st]),this._numericAllowed=t.numericAllowed??!0,this._baseMap=it(tt,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:lt.allow,nullLevel:lt.remove};const e=1.1===t.xmlVersion?1.1:1,n=lt[t.onNCR]??lt.allow,r=lt[t.nullNCR]??lt.remove;return{xmlVersion:e,onLevel:n,nullLevel:Math.max(r,lt.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))rt(e);this._externalMap=it(t)}addExternalEntity(t,e){rt(t),"string"==typeof e&&-1===e.indexOf("&")&&(this._externalMap[t]=e)}addInputEntities(t){this._totalExpansions=0,this._expandedLength=0,this._inputMap=it(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 u=t.slice(s+1,e);if(0===u.length){s++;continue}let h,c;if(this._removeSet.has(u))h="",void 0===c&&(c=st);else{if(this._leaveSet.has(u)){s++;continue}if(35===u.charCodeAt(0)){const t=this._resolveNCR(u);if(void 0===t){s++;continue}h=t,c=at}else{const t=this._resolveName(u);h=t?.value,c=t?.tier}}if(void 0!==h){if(s>i&&n.push(t.slice(i,s)),n.push(h),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=h.length-(u.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 u=0===n.length?t:n.join("");return this._postCheck(u,e)}_tierCounts(t){return!!this._limitTiers.has(ot)||this._limitTiers.has(t)}_resolveName(t){return t in this._inputMap?{value:this._inputMap[t],tier:st}:t in this._externalMap?{value:this._externalMap[t],tier:st}:t in this._baseMap?{value:this._baseMap[t],tier:at}:void 0}_classifyNCR(t){return 0===t?this._ncrNullLevel:t>=55296&&t<=57343||1===this._ncrXmlVersion&&t>=1&&t<=31&&!ut.has(t)?lt.remove:-1}_applyNCRAction(t,e,n){switch(t){case lt.allow:return String.fromCodePoint(n);case lt.remove:return"";case lt.leave:return;case lt.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<lt.remove)return;const i=-1===r?this._ncrOnLevel:Math.max(this._ncrOnLevel,r);return this._applyNCRAction(i,t,n)}}function ct(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 dt(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 pt{constructor(t){var e;this.options=t,this.currentNode=null,this.tagsNodeStack=[],this.parseXml=xt,this.parseTextData=ft,this.resolveNameSpace=gt,this.buildAttributesMap=vt,this.isItStopNode=wt,this.replaceEntitiesValue=Et,this.readStopNodeData=Tt,this.saveTextToParentTag=yt,this.addChild=bt,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={...tt};this.options.entityDecoder?this.entityDecoder=this.options.entityDecoder:("object"==typeof this.options.htmlEntities?n=this.options.htmlEntities:!0===this.options.htmlEntities&&(n={...et,...H}),this.entityDecoder=new ht({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 J,this.readonlyMatcher=this.matcher.readOnly(),this.isCurrentNodeStopNode=!1,this.stopNodeExpressionsSet=new Q;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 K(e)):e instanceof K&&this.stopNodeExpressionsSet.add(e)}this.stopNodeExpressionsSet.seal()}}}function ft(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?It(t,o.parseTagValue,o.numberParseOptions):t}}function gt(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 mt=new RegExp("([^\\s=]+)\\s*(=\\s*(['\"])([\\s\\S]*?)\\3)?","gm");function vt(t,e,n,r=!1){const i=this.options;if(!0===r||!0!==i.ignoreAttributes&&"string"==typeof t){const r=O(t,mt),s=r.length,a={},o=new Array(s);let l=!1;const u={};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,u[e]=r,l=!0}}l&&"object"==typeof e&&e.updateCurrent&&e.updateCurrent(u);const h=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,h))continue;let n=i.attributeNamePrefix+e;if(e.length)if(i.transformAttributeName&&(n=i.transformAttributeName(n)),n=At(n,i),void 0!==r[t][4]){const r=o[t],s=i.attributeValueProcessor(e,r,h);a[n]=null==s?r:typeof s!=typeof r||s!==r?s:It(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 xt=function(t){t=t.replace(/\r\n?/g,"\n");const e=new U("!xml");let n=e,r="";this.matcher.reset(),this.entityDecoder.reset(),this.entityExpansionCount=0,this.currentExpandedLength=0;const i=this.options,s=new R(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=Nt(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=Ct(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=St(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 U(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=Nt(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=Nt(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=St(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 u=s.rawTagName;let h=s.tagExp,c=s.attrExpPresent,d=s.closeIndex;if(({tagName:l,tagExp:h}=Ct(i.transformTagName,l,h,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;h.length>0&&h.lastIndexOf("/")===h.length-1&&(f=!0,"/"===l[l.length-1]?(l=l.substr(0,l.length-1),h=l):h=h.substr(0,h.length-1),c=l!==h);let g,m=null,v={};g=dt(u),l!==e.tagname&&this.matcher.push(l,{},g),l!==h&&c&&(m=this.buildAttributesMap(h,this.matcher,l),m&&(v=ct(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,u,d+1);if(!n)throw new Error(`Unexpected end of ${u}`);o=n.i,e=n.tagContent}const r=new U(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:h}=Ct(i.transformTagName,l,h,i));const t=new U(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 U(l);m&&(t[":@"]=m),this.addChild(n,t,this.readonlyMatcher,x),this.matcher.pop(),this.isCurrentNodeStopNode=!1,o=s.closeIndex;continue}{const t=new U(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 bt(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 Et(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 yt(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 wt(){return 0!==this.stopNodeExpressionsSet.size&&this.matcher.matchesAny(this.stopNodeExpressionsSet)}function Nt(t,e,n,r){const i=t.indexOf(e,n);if(-1===i)throw new Error(r);return i+e.length-1}function _t(t,e,n,r){const i=t.indexOf(e,n);if(-1===i)throw new Error(r);return i}function St(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,u=!0;-1!==o&&(l=s.substring(0,o),s=s.substring(o+1).trimStart());const h=l;if(n){const t=l.indexOf(":");-1!==t&&(l=l.substr(t+1),u=l!==i.data.substr(t+1))}return{tagName:l,tagExp:s,closeIndex:a,attrExpPresent:u,rawTagName:h}}function Tt(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=_t(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=Nt(t,"?>",n+1,"StopNode is not closed.");else if(33===s&&45===t.charCodeAt(n+2)&&45===t.charCodeAt(n+3))n=Nt(t,"--\x3e",n+3,"StopNode is not closed.");else if(33===s&&91===t.charCodeAt(n+2))n=Nt(t,"]]>",n,"StopNode is not closed.")-2;else{const r=St(t,n,">");r&&((r&&r.tagName)===e&&"/"!==r.tagExp[r.tagExp.length-1]&&i++,n=r.closeIndex)}}}function It(t,e,n){if(e&&"string"==typeof t){const e=t.trim();return"true"===e||"false"!==e&&function(t,e={}){if(e=Object.assign({},z,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&&X.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(G);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=W.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 Ct(t,e,n,r){if(t){const r=t(e);n===e&&(n=r),e=r}return{tagName:e=At(e,r),tagExp:n}}function At(t,e){if(M.includes(t))throw new Error(`[SECURITY] Invalid name: "${t}" is a reserved JavaScript keyword that could cause prototype pollution`);return P.includes(t)?e.onDangerousProperty(t):t}const Ot=U.getMetaDataSymbol();function Dt(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 Pt(t,e,n,r){return Mt(t,e,n,r)}function Mt(t,e,n,r){let i;const s={};for(let a=0;a<t.length;a++){const o=t[a],l=kt(o);if(void 0!==l&&l!==e.textNodeName){const t=Dt(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=Mt(o[l],e,n,r);const i=jt(t,e);if(o[":@"]?Vt(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[Ot]&&"object"==typeof t&&null!==t&&(t[Ot]=o[Ot]),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 kt(t){const e=Object.keys(t);for(let t=0;t<e.length;t++){const n=e[t];if(":@"!==n)return n}}function Vt(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 jt(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 Ft={allowBooleanAttributes:!1,unpairedTags:[]};function $t(t,e){e=Object.assign({},Ft,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=Ut(t,s),s.err)return s}else{if("<"!==t[s]){if(Lt(t[s]))continue;return Gt("InvalidChar","char '"+t[s]+"' is not expected.",Kt(t,s))}{let a=s;if(s++,"!"===t[s]){s=Rt(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--),!Jt(l)){let e;return e=0===l.trim().length?"Invalid space after '<'.":"Tag '"+l+"' is an invalid name.",Gt("InvalidTag",e,Kt(t,s))}const u=qt(t,s);if(!1===u)return Gt("InvalidAttr","Attributes for '"+l+"' have open quote.",Kt(t,s));let h=u.value;if(s=u.index,"/"===h[h.length-1]){const n=s-h.length;h=h.substring(0,h.length-1);const i=Wt(h,e);if(!0!==i)return Gt(i.err.code,i.err.msg,Kt(t,n+i.err.line));r=!0}else if(o){if(!u.tagClosed)return Gt("InvalidTag","Closing tag '"+l+"' doesn't have proper closing.",Kt(t,s));if(h.trim().length>0)return Gt("InvalidTag","Closing tag '"+l+"' can't have attributes or invalid starting.",Kt(t,a));if(0===n.length)return Gt("InvalidTag","Closing tag '"+l+"' has not been opened.",Kt(t,a));{const e=n.pop();if(l!==e.tagName){let n=Kt(t,e.tagStartPos);return Gt("InvalidTag","Expected closing tag '"+e.tagName+"' (opened in line "+n.line+", col "+n.col+") instead of closing tag '"+l+"'.",Kt(t,a))}0==n.length&&(i=!0)}}else{const o=Wt(h,e);if(!0!==o)return Gt(o.err.code,o.err.msg,Kt(t,s-h.length+o.err.line));if(!0===i)return Gt("InvalidXml","Multiple possible root nodes found.",Kt(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=Rt(t,s);continue}if("?"!==t[s+1])break;if(s=Ut(t,++s),s.err)return s}else if("&"===t[s]){const e=zt(t,s);if(-1==e)return Gt("InvalidChar","char '&' is not expected.",Kt(t,s));s=e}else if(!0===i&&!Lt(t[s]))return Gt("InvalidXml","Extra text at the end",Kt(t,s));"<"===t[s]&&s--}}}return r?1==n.length?Gt("InvalidTag","Unclosed tag '"+n[0].tagName+"'.",Kt(t,n[0].tagStartPos)):!(n.length>0)||Gt("InvalidXml","Invalid '"+JSON.stringify(n.map(t=>t.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):Gt("InvalidXml","Start tag expected.",1)}function Lt(t){return" "===t||"\t"===t||"\n"===t||"\r"===t}function Ut(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 Gt("InvalidXml","XML declaration allowed only at the start of the document.",Kt(t,e));if("?"==t[e]&&">"==t[e+1]){e++;break}continue}return e}function Rt(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 Bt='"',Yt="'";function qt(t,e){let n="",r="",i=!1;for(;e<t.length;e++){if(t[e]===Bt||t[e]===Yt)""===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 Xt=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function Wt(t,e){const n=O(t,Xt),r={};for(let t=0;t<n.length;t++){if(0===n[t][1].length)return Gt("InvalidAttr","Attribute '"+n[t][2]+"' has no space in starting.",Qt(n[t]));if(void 0!==n[t][3]&&void 0===n[t][4])return Gt("InvalidAttr","Attribute '"+n[t][2]+"' is without value.",Qt(n[t]));if(void 0===n[t][3]&&!e.allowBooleanAttributes)return Gt("InvalidAttr","boolean attribute '"+n[t][2]+"' is not allowed.",Qt(n[t]));const i=n[t][2];if(!Zt(i))return Gt("InvalidAttr","Attribute '"+i+"' is an invalid name.",Qt(n[t]));if(Object.prototype.hasOwnProperty.call(r,i))return Gt("InvalidAttr","Attribute '"+i+"' is repeated.",Qt(n[t]));r[i]=1}return!0}function zt(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 Gt(t,e,n){return{err:{code:t,msg:e,line:n.line||n,col:n.col}}}function Zt(t){return D(t)}function Jt(t){return D(t)}function Kt(t,e){const n=t.substring(0,e).split(/\r?\n/);return{line:n.length,col:n[n.length-1].length+1}}function Qt(t){return t.startIndex+t[1].length}class Ht{constructor(t){this.externalEntities={},this.options=$(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=$t(t,e);if(!0!==n)throw Error(`${n.err.msg}:${n.err.line}:${n.err.col}`)}const n=new pt(this.options);n.entityDecoder.setExternalEntities(this.externalEntities);const r=n.parseXml(t);return this.options.preserveOrder||void 0===r?r:Pt(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 '&#xD;'");if("&"===e)throw new Error("An entity with value '&' is not permitted");this.externalEntities[t]=e}static getMetaDataSymbol(){return U.getMetaDataSymbol()}}const te={validate:$t},ee={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},ne={min:(t,e)=>Number(e)>=t,max:(t,e)=>Number(e)<=t},re={minOccurs:(t,e)=>e>=t,maxOccurs:(t,e)=>e<=t},ie=(t,e)=>Date.parse(e)>=Date.parse(t),se=(t,e)=>Date.parse(e)<=Date.parse(t),ae=["positiveInteger","integer","positiveDecimal","decimal","number"];class oe{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 u=this._relationalCompare(String(o),String(s),l);if(null===u)return;let h=!1;"sameAs"===e&&0!==u&&(h=!0),"notSameAs"===e&&0===u&&(h=!0),"lessThan"===e&&u>=0&&(h=!0),"moreThan"===e&&u<=0&&(h=!0),h&&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!==ae.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!==ae.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||ie(i,e)||this.setInvalidValueError("min",n,e,i),void 0===s||se(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]);re[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]);ne[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]);ee[r](i,e)||this.setInvalidValueError(r,n,e,i)}}),["fixed","in"].forEach(r=>{if(void 0!==t[r]){const i=t[r];ee[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];ee.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 le=oe.prototype.traverse;oe.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;le.call(this,t[s],e,r,a)}}),void(t.length>0&&"object"==typeof t[0]&&this._runSiblingUniqueness(t,n,r));le.call(this,t,e,n,r)},oe.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 ue={unknownAllow:!0,boolean:["true","false"]};function he(t){if(!t)throw new Error("Empty data");if("string"!=typeof t)throw new Error("Not a valid string");const e=te.validate(t,{allowBooleanAttributes:!0});if(!0!==e)throw new Error(e.err.msg+":"+e.err.line)}const ce=class{constructor(t,e){he(t);const n=new Ht({ignoreAttributes:!1,attributesGroupName:"@rules",attributeNamePrefix:"",allowBooleanAttributes:!0});this.rules=n.parse(t),this.options=Object.assign({},ue,e),this.validators={},this.data=null}register(t,e){this.validators[t]=e}validate(t){he(t);const e=new Map,n=new Ht({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 oe(this.options,this.validators,e);return r.traverse(n,"",this.rules,""),r.failures}};var de=function(){function t(){}return t.validate=function(t,e){return function(t,e){e=Object.assign({},m,e);var n=new a(e.docType),r=[],i=!1,s=!1;if("\ufeff"===t[0]&&(t=t.substr(1)),t.startsWith("<?xml")){var o=t.indexOf("?>");if(-1===o)return _("InvalidXml",'Processing instruction is not closed with "?>".',{line:1,col:1});t=t.substring(o+2)}for(var l=0;l<t.length;l++)if("<"===t[l]&&"?"===t[l+1]){if((l=x(t,l+=2)).err)return l}else{if("<"!==t[l]){if(v(t[l]))continue;return s?_("InvalidXml","Extra text at the end: '"+t[l]+"' is not expected.",T(t,l)):_("InvalidChar","char '"+t[l]+"' is not expected.",T(t,l))}var u=l;if("!"===t[++l]){try{l=b(t,l,n)}catch(e){return _("InvalidTag",e.message,T(t,l-1))}continue}var h=!1;"/"===t[l]&&(h=!0,l++);for(var c="";l<t.length&&">"!==t[l]&&" "!==t[l]&&"\t"!==t[l]&&"\n"!==t[l]&&"\r"!==t[l];l++)c+=t[l];if("/"===(c=c.trim())[c.length-1]&&(c=c.substring(0,c.length-1),l--),!S(c))return _("InvalidTag",0===c.trim().length?"Invalid space after '<'.":"Tag '"+c+"' is an invalid name.",T(t,u));var d=E(t,l);if(!1===d)return _("InvalidAttr","Attributes for '"+c+"' have open quote.",T(t,l));var p=d.value;if(l=d.index,"/"===p[p.length-1]){var f=l-p.length,g=w(p=p.substring(0,p.length-1),e);if(!0!==g)return _(g.err.code,g.err.msg,T(t,f+g.err.line));if(!0===s)return _("InvalidXml","Multiple possible root nodes found.",T(t,u));i=!0,0===r.length&&(s=!0)}else if(h){if(!d.tagClosed)return _("InvalidTag","Closing tag '"+c+"' doesn't have proper closing.",T(t,l));if(p.trim().length>0)return _("InvalidTag","Closing tag '"+c+"' can't have attributes or invalid starting.",T(t,u));if(0===r.length)return _("InvalidTag","Closing tag '"+c+"' has not been opened.",T(t,u));var y=r.pop();if(c!==y.tagName){var I=T(t,y.tagStartPos);return _("InvalidTag","Expected closing tag '"+y.tagName+"' (opened in line "+I.line+", col "+I.col+") instead of closing tag '"+c+"'.",T(t,u))}0===r.length&&(s=!0)}else{var C=w(p,e);if(!0!==C)return _(C.err.code,C.err.msg,T(t,l-p.length+C.err.line));if(!0===s)return _("InvalidXml","Multiple possible root nodes found.",T(t,l));-1!==e.unpairedTags.indexOf(c)||r.push({tagName:c,tagStartPos:u}),i=!0}for(l++;l<t.length;l++)if("<"===t[l]){if("!"===t[l+1]){l++;try{l=b(t,l,n)}catch(e){return _("InvalidDocType",e.message,T(t,l-1))}continue}if("?"!==t[l+1])break;if((l=x(t,l+=2)).err)return l}else if("&"===t[l]){var A=N(t,l);if(-1===A)return _("InvalidChar","char '&' is not expected.",T(t,l));l=A}else if(!0===s&&!v(t[l]))return _("InvalidXml","Extra text at the end",T(t,l));"<"===t[l]&&l--}return i?1===r.length?_("InvalidTag","Unclosed tag '"+r[0].tagName+"'.",T(t,r[0].tagStartPos)):!(r.length>0)||_("InvalidXml","Invalid '"+JSON.stringify(r.map(function(t){return t.tagName})).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):_("InvalidXml","Start tag expected.",{line:1,col:1})}(t,e)},t}();return e})());
2
+ //# sourceMappingURL=fxv.min.js.map