• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

NaturalIntelligence / fast-xml-parser / 22012305802

14 Feb 2026 05:53AM UTC coverage: 97.755% (+0.1%) from 97.617%
22012305802

push

github

amitguptagwl
update release info

1275 of 1319 branches covered (96.66%)

9753 of 9977 relevant lines covered (97.75%)

447181.27 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

98.16
/src/xmlparser/OrderedObjParser.js
1
'use strict';
5✔
2
///@ts-check
5✔
3

5✔
4
import { getAllMatches, isExist } from '../util.js';
5✔
5
import xmlNode from './xmlNode.js';
5✔
6
import DocTypeReader from './DocTypeReader.js';
5✔
7
import toNumber from "strnum";
5✔
8
import getIgnoreAttributesFn from "../ignoreAttributes.js";
5✔
9

5✔
10
// const regx =
5✔
11
//   '<((!\\[CDATA\\[([\\s\\S]*?)(]]>))|((NAME:)?(NAME))([^>]*)>|((\\/)(NAME)\\s*>))([^<]*)'
5✔
12
//   .replace(/NAME/g, util.nameRegexp);
5✔
13

5✔
14
//const tagsRegx = new RegExp("<(\\/?[\\w:\\-\._]+)([^>]*)>(\\s*"+cdataRegx+")*([^<]+)?","g");
5✔
15
//const tagsRegx = new RegExp("<(\\/?)((\\w*:)?([\\w:\\-\._]+))([^>]*)>([^<]*)("+cdataRegx+"([^<]*))*([^<]+)?","g");
5✔
16

5✔
17
export default class OrderedObjParser {
5✔
18
  constructor(options) {
5✔
19
    this.options = options;
1,015✔
20
    this.currentNode = null;
1,015✔
21
    this.tagsNodeStack = [];
1,015✔
22
    this.docTypeEntities = {};
1,015✔
23
    this.lastEntities = {
1,015✔
24
      "apos": { regex: /&(apos|#39|#x27);/g, val: "'" },
1,015✔
25
      "gt": { regex: /&(gt|#62|#x3E);/g, val: ">" },
1,015✔
26
      "lt": { regex: /&(lt|#60|#x3C);/g, val: "<" },
1,015✔
27
      "quot": { regex: /&(quot|#34|#x22);/g, val: "\"" },
1,015✔
28
    };
1,015✔
29
    this.ampEntity = { regex: /&(amp|#38|#x26);/g, val: "&" };
1,015✔
30
    this.htmlEntities = {
1,015✔
31
      "space": { regex: /&(nbsp|#160);/g, val: " " },
1,015✔
32
      // "lt" : { regex: /&(lt|#60);/g, val: "<" },
1,015✔
33
      // "gt" : { regex: /&(gt|#62);/g, val: ">" },
1,015✔
34
      // "amp" : { regex: /&(amp|#38);/g, val: "&" },
1,015✔
35
      // "quot" : { regex: /&(quot|#34);/g, val: "\"" },
1,015✔
36
      // "apos" : { regex: /&(apos|#39);/g, val: "'" },
1,015✔
37
      "cent": { regex: /&(cent|#162);/g, val: "¢" },
1,015✔
38
      "pound": { regex: /&(pound|#163);/g, val: "£" },
1,015✔
39
      "yen": { regex: /&(yen|#165);/g, val: "Â¥" },
1,015✔
40
      "euro": { regex: /&(euro|#8364);/g, val: "€" },
1,015✔
41
      "copyright": { regex: /&(copy|#169);/g, val: "©" },
1,015✔
42
      "reg": { regex: /&(reg|#174);/g, val: "®" },
1,015✔
43
      "inr": { regex: /&(inr|#8377);/g, val: "₹" },
1,015✔
44
      "num_dec": { regex: /&#([0-9]{1,7});/g, val: (_, str) => fromCodePoint(str, 10, "&#") },
1,015✔
45
      "num_hex": { regex: /&#x([0-9a-fA-F]{1,6});/g, val: (_, str) => fromCodePoint(str, 16, "&#x") },
1,015✔
46
    };
1,015✔
47
    this.addExternalEntities = addExternalEntities;
1,015✔
48
    this.parseXml = parseXml;
1,015✔
49
    this.parseTextData = parseTextData;
1,015✔
50
    this.resolveNameSpace = resolveNameSpace;
1,015✔
51
    this.buildAttributesMap = buildAttributesMap;
1,015✔
52
    this.isItStopNode = isItStopNode;
1,015✔
53
    this.replaceEntitiesValue = replaceEntitiesValue;
1,015✔
54
    this.readStopNodeData = readStopNodeData;
1,015✔
55
    this.saveTextToParentTag = saveTextToParentTag;
1,015✔
56
    this.addChild = addChild;
1,015✔
57
    this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes)
1,015✔
58
    this.entityExpansionCount = 0;
1,015✔
59
    this.currentExpandedLength = 0;
1,015✔
60

1,015✔
61
    if (this.options.stopNodes && this.options.stopNodes.length > 0) {
1,015✔
62
      this.stopNodesExact = new Set();
105✔
63
      this.stopNodesWildcard = new Set();
105✔
64
      for (let i = 0; i < this.options.stopNodes.length; i++) {
105✔
65
        const stopNodeExp = this.options.stopNodes[i];
160✔
66
        if (typeof stopNodeExp !== 'string') continue;
160!
67
        if (stopNodeExp.startsWith("*.")) {
160✔
68
          this.stopNodesWildcard.add(stopNodeExp.substring(2));
70✔
69
        } else {
160✔
70
          this.stopNodesExact.add(stopNodeExp);
90✔
71
        }
90✔
72
      }
160✔
73
    }
105✔
74
  }
1,015✔
75

5✔
76
}
5✔
77

5✔
78
function addExternalEntities(externalEntities) {
1,015✔
79
  const entKeys = Object.keys(externalEntities);
1,015✔
80
  for (let i = 0; i < entKeys.length; i++) {
1,015✔
81
    const ent = entKeys[i];
15✔
82
    const escaped = ent.replace(/[.\-+*:]/g, '\\.');
15✔
83
    this.lastEntities[ent] = {
15✔
84
      regex: new RegExp("&" + escaped + ";", "g"),
15✔
85
      val: externalEntities[ent]
15✔
86
    }
15✔
87
  }
15✔
88
}
1,015✔
89

5✔
90
/**
5✔
91
 * @param {string} val
5✔
92
 * @param {string} tagName
5✔
93
 * @param {string} jPath
5✔
94
 * @param {boolean} dontTrim
5✔
95
 * @param {boolean} hasAttributes
5✔
96
 * @param {boolean} isLeafNode
5✔
97
 * @param {boolean} escapeEntities
5✔
98
 */
5✔
99
function parseTextData(val, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) {
5,630✔
100
  if (val !== undefined) {
5,630✔
101
    if (this.options.trimValues && !dontTrim) {
5,630✔
102
      val = val.trim();
5,220✔
103
    }
5,220✔
104
    if (val.length > 0) {
5,630✔
105
      if (!escapeEntities) val = this.replaceEntitiesValue(val, tagName, jPath);
2,290✔
106

2,260✔
107
      const newval = this.options.tagValueProcessor(tagName, val, jPath, hasAttributes, isLeafNode);
2,260✔
108
      if (newval === null || newval === undefined) {
2,290✔
109
        //don't parse
50✔
110
        return val;
50✔
111
      } else if (typeof newval !== typeof val || newval !== val) {
2,290✔
112
        //overwrite
20✔
113
        return newval;
20✔
114
      } else if (this.options.trimValues) {
2,210✔
115
        return parseValue(val, this.options.parseTagValue, this.options.numberParseOptions);
2,130✔
116
      } else {
2,190✔
117
        const trimmedVal = val.trim();
60✔
118
        if (trimmedVal === val) {
60✔
119
          return parseValue(val, this.options.parseTagValue, this.options.numberParseOptions);
15✔
120
        } else {
60✔
121
          return val;
45✔
122
        }
45✔
123
      }
60✔
124
    }
2,290✔
125
  }
5,630✔
126
}
5,630✔
127

5✔
128
function resolveNameSpace(tagname) {
1,430✔
129
  if (this.options.removeNSPrefix) {
1,430✔
130
    const tags = tagname.split(':');
110✔
131
    const prefix = tagname.charAt(0) === '/' ? '/' : '';
110!
132
    if (tags[0] === 'xmlns') {
110✔
133
      return '';
35✔
134
    }
35✔
135
    if (tags.length === 2) {
110✔
136
      tagname = prefix + tags[1];
30✔
137
    }
30✔
138
  }
110✔
139
  return tagname;
1,395✔
140
}
1,430✔
141

5✔
142
//TODO: change regex to capture NS
5✔
143
//const attrsRegx = new RegExp("([\\w\\-\\.\\:]+)\\s*=\\s*(['\"])((.|\n)*?)\\2","gm");
5✔
144
const attrsRegx = new RegExp('([^\\s=]+)\\s*(=\\s*([\'"])([\\s\\S]*?)\\3)?', 'gm');
5✔
145

5✔
146
function buildAttributesMap(attrStr, jPath, tagName) {
1,145✔
147
  if (this.options.ignoreAttributes !== true && typeof attrStr === 'string') {
1,145✔
148
    // attrStr = attrStr.replace(/\r?\n/g, ' ');
980✔
149
    //attrStr = attrStr || attrStr.trim();
980✔
150

980✔
151
    const matches = getAllMatches(attrStr, attrsRegx);
980✔
152
    const len = matches.length; //don't make it inline
980✔
153
    const attrs = {};
980✔
154
    for (let i = 0; i < len; i++) {
980✔
155
      const attrName = this.resolveNameSpace(matches[i][1]);
1,430✔
156
      if (this.ignoreAttributesFn(attrName, jPath)) {
1,430✔
157
        continue
50✔
158
      }
50✔
159
      let oldVal = matches[i][4];
1,380✔
160
      let aName = this.options.attributeNamePrefix + attrName;
1,380✔
161
      if (attrName.length) {
1,430✔
162
        if (this.options.transformAttributeName) {
1,345✔
163
          aName = this.options.transformAttributeName(aName);
20✔
164
        }
20✔
165
        if (aName === "__proto__") aName = "#__proto__";
1,345!
166
        if (oldVal !== undefined) {
1,345✔
167
          if (this.options.trimValues) {
1,255✔
168
            oldVal = oldVal.trim();
1,230✔
169
          }
1,230✔
170
          oldVal = this.replaceEntitiesValue(oldVal, tagName, jPath);
1,255✔
171
          const newVal = this.options.attributeValueProcessor(attrName, oldVal, jPath);
1,255✔
172
          if (newVal === null || newVal === undefined) {
1,255!
173
            //don't parse
×
174
            attrs[aName] = oldVal;
×
175
          } else if (typeof newVal !== typeof oldVal || newVal !== oldVal) {
1,255!
176
            //overwrite
×
177
            attrs[aName] = newVal;
×
178
          } else {
1,255✔
179
            //parse
1,255✔
180
            attrs[aName] = parseValue(
1,255✔
181
              oldVal,
1,255✔
182
              this.options.parseAttributeValue,
1,255✔
183
              this.options.numberParseOptions
1,255✔
184
            );
1,255✔
185
          }
1,255✔
186
        } else if (this.options.allowBooleanAttributes) {
1,345✔
187
          attrs[aName] = true;
80✔
188
        }
80✔
189
      }
1,345✔
190
    }
1,430✔
191
    if (!Object.keys(attrs).length) {
980✔
192
      return;
95✔
193
    }
95✔
194
    if (this.options.attributesGroupName) {
980✔
195
      const attrCollection = {};
60✔
196
      attrCollection[this.options.attributesGroupName] = attrs;
60✔
197
      return attrCollection;
60✔
198
    }
60✔
199
    return attrs
825✔
200
  }
825✔
201
}
1,145✔
202

5✔
203
const parseXml = function (xmlData) {
5✔
204
  xmlData = xmlData.replace(/\r\n?/g, "\n"); //TODO: remove this line
1,015✔
205
  const xmlObj = new xmlNode('!xml');
1,015✔
206
  let currentNode = xmlObj;
1,015✔
207
  let textData = "";
1,015✔
208
  let jPath = "";
1,015✔
209

1,015✔
210
  // Reset entity expansion counters for this document
1,015✔
211
  this.entityExpansionCount = 0;
1,015✔
212
  this.currentExpandedLength = 0;
1,015✔
213

1,015✔
214
  const docTypeReader = new DocTypeReader(this.options.processEntities);
1,015✔
215
  for (let i = 0; i < xmlData.length; i++) {//for each char in XML data
1,015✔
216
    const ch = xmlData[i];
303,940✔
217
    if (ch === '<') {
303,940✔
218
      // const nextIndex = i+1;
7,620✔
219
      // const _2ndChar = xmlData[nextIndex];
7,620✔
220
      if (xmlData[i + 1] === '/') {//Closing Tag
7,620✔
221
        const closeIndex = findClosingIndex(xmlData, ">", i, "Closing Tag is not closed.")
3,100✔
222
        let tagName = xmlData.substring(i + 2, closeIndex).trim();
3,100✔
223

3,100✔
224
        if (this.options.removeNSPrefix) {
3,100✔
225
          const colonIndex = tagName.indexOf(":");
115✔
226
          if (colonIndex !== -1) {
115✔
227
            tagName = tagName.substr(colonIndex + 1);
50✔
228
          }
50✔
229
        }
115✔
230

3,095✔
231
        if (this.options.transformTagName) {
3,100✔
232
          tagName = this.options.transformTagName(tagName);
75✔
233
        }
75✔
234

3,095✔
235
        if (currentNode) {
3,095✔
236
          textData = this.saveTextToParentTag(textData, currentNode, jPath);
3,095✔
237
        }
3,095✔
238

3,065✔
239
        //check if last tag of nested tag was unpaired tag
3,065✔
240
        const lastTagName = jPath.substring(jPath.lastIndexOf(".") + 1);
3,065✔
241
        if (tagName && this.options.unpairedTags.indexOf(tagName) !== -1) {
3,100✔
242
          throw new Error(`Unpaired tag can not be used as closing tag: </${tagName}>`);
5✔
243
        }
5✔
244
        let propIndex = 0
3,060✔
245
        if (lastTagName && this.options.unpairedTags.indexOf(lastTagName) !== -1) {
3,100✔
246
          propIndex = jPath.lastIndexOf('.', jPath.lastIndexOf('.') - 1)
80✔
247
          this.tagsNodeStack.pop();
80✔
248
        } else {
3,100✔
249
          propIndex = jPath.lastIndexOf(".");
2,980✔
250
        }
2,980✔
251
        jPath = jPath.substring(0, propIndex);
3,060✔
252

3,060✔
253
        currentNode = this.tagsNodeStack.pop();//avoid recursion, set the parent tag scope
3,060✔
254
        textData = "";
3,060✔
255
        i = closeIndex;
3,060✔
256
      } else if (xmlData[i + 1] === '?') {
7,620✔
257

245✔
258
        let tagData = readTagExp(xmlData, i, false, "?>");
245✔
259
        if (!tagData) throw new Error("Pi Tag is not closed.");
245✔
260

235✔
261
        textData = this.saveTextToParentTag(textData, currentNode, jPath);
235✔
262
        if ((this.options.ignoreDeclaration && tagData.tagName === "?xml") || this.options.ignorePiTags) {
245✔
263
          //do nothing
25✔
264
        } else {
245✔
265

210✔
266
          const childNode = new xmlNode(tagData.tagName);
210✔
267
          childNode.add(this.options.textNodeName, "");
210✔
268

210✔
269
          if (tagData.tagName !== tagData.tagExp && tagData.attrExpPresent) {
210✔
270
            childNode[":@"] = this.buildAttributesMap(tagData.tagExp, jPath, tagData.tagName);
200✔
271
          }
200✔
272
          this.addChild(currentNode, childNode, jPath, i);
210✔
273
        }
210✔
274

235✔
275

235✔
276
        i = tagData.closeIndex + 1;
235✔
277
      } else if (xmlData.substr(i + 1, 3) === '!--') {
4,520✔
278
        const endIndex = findClosingIndex(xmlData, "-->", i + 4, "Comment is not closed.")
60✔
279
        if (this.options.commentPropName) {
60✔
280
          const comment = xmlData.substring(i + 4, endIndex - 2);
25✔
281

25✔
282
          textData = this.saveTextToParentTag(textData, currentNode, jPath);
25✔
283

25✔
284
          currentNode.add(this.options.commentPropName, [{ [this.options.textNodeName]: comment }]);
25✔
285
        }
25✔
286
        i = endIndex;
55✔
287
      } else if (xmlData.substr(i + 1, 2) === '!D') {
4,275✔
288
        const result = docTypeReader.readDocType(xmlData, i);
220✔
289
        this.docTypeEntities = result.entities;
220✔
290
        i = result.i;
220✔
291
      } else if (xmlData.substr(i + 1, 2) === '![') {
4,215✔
292
        const closeIndex = findClosingIndex(xmlData, "]]>", i, "CDATA is not closed.") - 2;
260✔
293
        const tagExp = xmlData.substring(i + 9, closeIndex);
260✔
294

260✔
295
        textData = this.saveTextToParentTag(textData, currentNode, jPath);
260✔
296

260✔
297
        let val = this.parseTextData(tagExp, currentNode.tagname, jPath, true, false, true, true);
260✔
298
        if (val == undefined) val = "";
260✔
299

255✔
300
        //cdata should be set even if it is 0 length string
255✔
301
        if (this.options.cdataPropName) {
260✔
302
          currentNode.add(this.options.cdataPropName, [{ [this.options.textNodeName]: tagExp }]);
65✔
303
        } else {
260✔
304
          currentNode.add(this.options.textNodeName, val);
190✔
305
        }
190✔
306

255✔
307
        i = closeIndex + 2;
255✔
308
      } else {//Opening tag
3,995✔
309
        let result = readTagExp(xmlData, i, this.options.removeNSPrefix);
3,735✔
310
        let tagName = result.tagName;
3,735✔
311
        const rawTagName = result.rawTagName;
3,735✔
312
        let tagExp = result.tagExp;
3,735✔
313
        let attrExpPresent = result.attrExpPresent;
3,735✔
314
        let closeIndex = result.closeIndex;
3,735✔
315

3,735✔
316
        if (this.options.transformTagName) {
3,735✔
317
          //console.log(tagExp, tagName)
80✔
318
          const newTagName = this.options.transformTagName(tagName);
80✔
319
          if (tagExp === tagName) {
80✔
320
            tagExp = newTagName
50✔
321
          }
50✔
322
          tagName = newTagName;
80✔
323
        }
80✔
324

3,735✔
325
        //save text as child node
3,735✔
326
        if (currentNode && textData) {
3,735✔
327
          if (currentNode.tagname !== '!xml') {
2,630✔
328
            //when nested tag is found
2,335✔
329
            textData = this.saveTextToParentTag(textData, currentNode, jPath, false);
2,335✔
330
          }
2,335✔
331
        }
2,630✔
332

3,735✔
333
        //check if last tag was unpaired tag
3,735✔
334
        const lastTag = currentNode;
3,735✔
335
        if (lastTag && this.options.unpairedTags.indexOf(lastTag.tagname) !== -1) {
3,735✔
336
          currentNode = this.tagsNodeStack.pop();
120✔
337
          jPath = jPath.substring(0, jPath.lastIndexOf("."));
120✔
338
        }
120✔
339
        if (tagName !== xmlObj.tagname) {
3,735✔
340
          jPath += jPath ? "." + tagName : tagName;
3,735✔
341
        }
3,735✔
342
        const startIndex = i;
3,735✔
343
        if (this.isItStopNode(this.stopNodesExact, this.stopNodesWildcard, jPath, tagName)) {
3,735✔
344
          let tagContent = "";
130✔
345
          //self-closing tag
130✔
346
          if (tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1) {
130✔
347
            if (tagName[tagName.length - 1] === "/") { //remove trailing '/'
10!
348
              tagName = tagName.substr(0, tagName.length - 1);
×
349
              jPath = jPath.substr(0, jPath.length - 1);
×
350
              tagExp = tagName;
×
351
            } else {
10✔
352
              tagExp = tagExp.substr(0, tagExp.length - 1);
10✔
353
            }
10✔
354
            i = result.closeIndex;
10✔
355
          }
10✔
356
          //unpaired tag
120✔
357
          else if (this.options.unpairedTags.indexOf(tagName) !== -1) {
120✔
358

5✔
359
            i = result.closeIndex;
5✔
360
          }
5✔
361
          //normal tag
115✔
362
          else {
115✔
363
            //read until closing tag is found
115✔
364
            const result = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1);
115✔
365
            if (!result) throw new Error(`Unexpected end of ${rawTagName}`);
115!
366
            i = result.i;
115✔
367
            tagContent = result.tagContent;
115✔
368
          }
115✔
369

130✔
370
          const childNode = new xmlNode(tagName);
130✔
371

130✔
372
          if (tagName !== tagExp && attrExpPresent) {
130✔
373
            childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName);
45✔
374
          }
45✔
375
          if (tagContent) {
130✔
376
            tagContent = this.parseTextData(tagContent, tagName, jPath, true, attrExpPresent, true, true);
95✔
377
          }
95✔
378

130✔
379
          jPath = jPath.substr(0, jPath.lastIndexOf("."));
130✔
380
          childNode.add(this.options.textNodeName, tagContent);
130✔
381

130✔
382
          this.addChild(currentNode, childNode, jPath, startIndex);
130✔
383
        } else {
3,735✔
384
          //selfClosing tag
3,605✔
385
          if (tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1) {
3,605✔
386
            if (tagName[tagName.length - 1] === "/") { //remove trailing '/'
290✔
387
              tagName = tagName.substr(0, tagName.length - 1);
105✔
388
              jPath = jPath.substr(0, jPath.length - 1);
105✔
389
              tagExp = tagName;
105✔
390
            } else {
290✔
391
              tagExp = tagExp.substr(0, tagExp.length - 1);
185✔
392
            }
185✔
393

290✔
394
            if (this.options.transformTagName) {
290✔
395
              const newTagName = this.options.transformTagName(tagName);
5✔
396
              if (tagExp === tagName) {
5✔
397
                tagExp = newTagName
5✔
398
              }
5✔
399
              tagName = newTagName;
5✔
400
            }
5✔
401

290✔
402
            const childNode = new xmlNode(tagName);
290✔
403
            if (tagName !== tagExp && attrExpPresent) {
290✔
404
              childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName);
185✔
405
            }
185✔
406
            this.addChild(currentNode, childNode, jPath, startIndex);
290✔
407
            jPath = jPath.substr(0, jPath.lastIndexOf("."));
290✔
408
          }
290✔
409
          //opening tag
3,315✔
410
          else {
3,315✔
411
            const childNode = new xmlNode(tagName);
3,315✔
412
            this.tagsNodeStack.push(currentNode);
3,315✔
413

3,315✔
414
            if (tagName !== tagExp && attrExpPresent) {
3,315✔
415
              childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName);
715✔
416
            }
715✔
417
            this.addChild(currentNode, childNode, jPath, startIndex);
3,315✔
418
            currentNode = childNode;
3,315✔
419
          }
3,315✔
420
          textData = "";
3,605✔
421
          i = closeIndex;
3,605✔
422
        }
3,605✔
423
      }
3,735✔
424
    } else {
303,940✔
425
      textData += xmlData[i];
296,320✔
426
    }
296,320✔
427
  }
303,940✔
428
  return xmlObj.child;
930✔
429
}
1,015✔
430

5✔
431
function addChild(currentNode, childNode, jPath, startIndex) {
3,945✔
432
  // unset startIndex if not requested
3,945✔
433
  if (!this.options.captureMetaData) startIndex = undefined;
3,945✔
434
  const result = this.options.updateTag(childNode.tagname, jPath, childNode[":@"])
3,945✔
435
  if (result === false) {
3,945✔
436
    //do nothing
25✔
437
  } else if (typeof result === "string") {
3,945✔
438
    childNode.tagname = result
3,920✔
439
    currentNode.addChild(childNode, startIndex);
3,920✔
440
  } else {
3,920!
441
    currentNode.addChild(childNode, startIndex);
×
442
  }
×
443
}
3,945✔
444

5✔
445
const replaceEntitiesValue = function (val, tagName, jPath) {
5✔
446
  // Performance optimization: Early return if no entities to replace
3,215✔
447
  if (val.indexOf('&') === -1) {
3,215✔
448
    return val;
2,855✔
449
  }
2,855✔
450

360✔
451
  const entityConfig = this.options.processEntities;
360✔
452

360✔
453
  if (!entityConfig.enabled) {
3,215✔
454
    return val;
25✔
455
  }
25✔
456

335✔
457
  // Check tag-specific filtering
335✔
458
  if (entityConfig.allowedTags) {
3,215✔
459
    if (!entityConfig.allowedTags.includes(tagName)) {
30✔
460
      return val; // Skip entity replacement for current tag as not set
10✔
461
    }
10✔
462
  }
30✔
463

325✔
464
  if (entityConfig.tagFilter) {
3,215✔
465
    if (!entityConfig.tagFilter(tagName, jPath)) {
25✔
466
      return val; // Skip based on custom filter
15✔
467
    }
15✔
468
  }
25✔
469

310✔
470
  // Replace DOCTYPE entities
310✔
471
  for (let entityName in this.docTypeEntities) {
3,215✔
472
    const entity = this.docTypeEntities[entityName];
432✔
473
    const matches = val.match(entity.regx);
432✔
474

432✔
475
    if (matches) {
432✔
476
      // Track expansions
377✔
477
      this.entityExpansionCount += matches.length;
377✔
478

377✔
479
      // Check expansion limit
377✔
480
      if (entityConfig.maxTotalExpansions &&
377✔
481
        this.entityExpansionCount > entityConfig.maxTotalExpansions) {
377✔
482
        throw new Error(
15✔
483
          `Entity expansion limit exceeded: ${this.entityExpansionCount} > ${entityConfig.maxTotalExpansions}`
15✔
484
        );
15✔
485
      }
15✔
486

362✔
487
      // Store length before replacement
362✔
488
      const lengthBefore = val.length;
362✔
489
      val = val.replace(entity.regx, entity.val);
362✔
490

362✔
491
      // Check expanded length immediately after replacement
362✔
492
      if (entityConfig.maxExpandedLength) {
362✔
493
        this.currentExpandedLength += (val.length - lengthBefore);
362✔
494

362✔
495
        if (this.currentExpandedLength > entityConfig.maxExpandedLength) {
362✔
496
          throw new Error(
15✔
497
            `Total expanded content size exceeded: ${this.currentExpandedLength} > ${entityConfig.maxExpandedLength}`
15✔
498
          );
15✔
499
        }
15✔
500
      }
362✔
501
    }
377✔
502
  }
432✔
503
  if (val.indexOf('&') === -1) return val;  // Early exit
3,215✔
504

140✔
505
  // Replace standard entities
140✔
506
  for (let entityName in this.lastEntities) {
3,215✔
507
    const entity = this.lastEntities[entityName];
644✔
508
    val = val.replace(entity.regex, entity.val);
644✔
509
  }
644✔
510
  if (val.indexOf('&') === -1) return val;  // Early exit
3,215✔
511

100✔
512
  // Replace HTML entities if enabled
100✔
513
  if (this.options.htmlEntities) {
3,215✔
514
    for (let entityName in this.htmlEntities) {
40✔
515
      const entity = this.htmlEntities[entityName];
426✔
516
      val = val.replace(entity.regex, entity.val);
426✔
517
    }
426✔
518
  }
40✔
519

100✔
520
  // Replace ampersand entity last
100✔
521
  val = val.replace(this.ampEntity.regex, this.ampEntity.val);
100✔
522

100✔
523
  return val;
100✔
524
}
3,215✔
525

5✔
526

5✔
527
function saveTextToParentTag(textData, currentNode, jPath, isLeafNode) {
5,945✔
528
  if (textData) { //store previously collected data as textNode
5,945✔
529
    if (isLeafNode === undefined) isLeafNode = currentNode.child.length === 0
5,280✔
530

5,280✔
531
    textData = this.parseTextData(textData,
5,280✔
532
      currentNode.tagname,
5,280✔
533
      jPath,
5,280✔
534
      false,
5,280✔
535
      currentNode[":@"] ? Object.keys(currentNode[":@"]).length !== 0 : false,
5,280✔
536
      isLeafNode);
5,280✔
537

5,280✔
538
    if (textData !== undefined && textData !== "")
5,280✔
539
      currentNode.add(this.options.textNodeName, textData);
5,280✔
540
    textData = "";
5,250✔
541
  }
5,250✔
542
  return textData;
5,915✔
543
}
5,945✔
544

5✔
545
//TODO: use jPath to simplify the logic
5✔
546
/**
5✔
547
 * @param {Set} stopNodesExact
5✔
548
 * @param {Set} stopNodesWildcard
5✔
549
 * @param {string} jPath
5✔
550
 * @param {string} currentTagName
5✔
551
 */
5✔
552
function isItStopNode(stopNodesExact, stopNodesWildcard, jPath, currentTagName) {
3,735✔
553
  if (stopNodesWildcard && stopNodesWildcard.has(currentTagName)) return true;
3,735✔
554
  if (stopNodesExact && stopNodesExact.has(jPath)) return true;
3,735✔
555
  return false;
3,605✔
556
}
3,735✔
557

5✔
558
/**
5✔
559
 * Returns the tag Expression and where it is ending handling single-double quotes situation
5✔
560
 * @param {string} xmlData 
5✔
561
 * @param {number} i starting index
5✔
562
 * @returns 
5✔
563
 */
5✔
564
function tagExpWithClosingIndex(xmlData, i, closingChar = ">") {
4,135✔
565
  let attrBoundary;
4,135✔
566
  let tagExp = "";
4,135✔
567
  for (let index = i; index < xmlData.length; index++) {
4,135✔
568
    let ch = xmlData[index];
55,825✔
569
    if (attrBoundary) {
55,825✔
570
      if (ch === attrBoundary) attrBoundary = "";//reset
14,760✔
571
    } else if (ch === '"' || ch === "'") {
55,825✔
572
      attrBoundary = ch;
1,570✔
573
    } else if (ch === closingChar[0]) {
41,065✔
574
      if (closingChar[1]) {
4,365✔
575
        if (xmlData[index + 1] === closingChar[1]) {
480✔
576
          return {
235✔
577
            data: tagExp,
235✔
578
            index: index
235✔
579
          }
235✔
580
        }
235✔
581
      } else {
4,365✔
582
        return {
3,885✔
583
          data: tagExp,
3,885✔
584
          index: index
3,885✔
585
        }
3,885✔
586
      }
3,885✔
587
    } else if (ch === '\t') {
39,495✔
588
      ch = " "
20✔
589
    }
20✔
590
    tagExp += ch;
51,705✔
591
  }
51,705✔
592
}
4,135✔
593

5✔
594
function findClosingIndex(xmlData, str, i, errMsg) {
3,690✔
595
  const closingIndex = xmlData.indexOf(str, i);
3,690✔
596
  if (closingIndex === -1) {
3,690✔
597
    throw new Error(errMsg)
15✔
598
  } else {
3,690✔
599
    return closingIndex + str.length - 1;
3,675✔
600
  }
3,675✔
601
}
3,690✔
602

5✔
603
function readTagExp(xmlData, i, removeNSPrefix, closingChar = ">") {
4,135✔
604
  const result = tagExpWithClosingIndex(xmlData, i + 1, closingChar);
4,135✔
605
  if (!result) return;
4,135✔
606
  let tagExp = result.data;
4,120✔
607
  const closeIndex = result.index;
4,120✔
608
  const separatorIndex = tagExp.search(/\s/);
4,120✔
609
  let tagName = tagExp;
4,120✔
610
  let attrExpPresent = true;
4,120✔
611
  if (separatorIndex !== -1) {//separate tag name and attributes expression
4,135✔
612
    tagName = tagExp.substring(0, separatorIndex);
1,225✔
613
    tagExp = tagExp.substring(separatorIndex + 1).trimStart();
1,225✔
614
  }
1,225✔
615

4,120✔
616
  const rawTagName = tagName;
4,120✔
617
  if (removeNSPrefix) {
4,135✔
618
    const colonIndex = tagName.indexOf(":");
280✔
619
    if (colonIndex !== -1) {
280✔
620
      tagName = tagName.substr(colonIndex + 1);
65✔
621
      attrExpPresent = tagName !== result.data.substr(colonIndex + 1);
65✔
622
    }
65✔
623
  }
280✔
624

4,120✔
625
  return {
4,120✔
626
    tagName: tagName,
4,120✔
627
    tagExp: tagExp,
4,120✔
628
    closeIndex: closeIndex,
4,120✔
629
    attrExpPresent: attrExpPresent,
4,120✔
630
    rawTagName: rawTagName,
4,120✔
631
  }
4,120✔
632
}
4,135✔
633
/**
5✔
634
 * find paired tag for a stop node
5✔
635
 * @param {string} xmlData 
5✔
636
 * @param {string} tagName 
5✔
637
 * @param {number} i 
5✔
638
 */
5✔
639
function readStopNodeData(xmlData, tagName, i) {
115✔
640
  const startIndex = i;
115✔
641
  // Starting at 1 since we already have an open tag
115✔
642
  let openTagCount = 1;
115✔
643

115✔
644
  for (; i < xmlData.length; i++) {
115✔
645
    if (xmlData[i] === "<") {
4,725✔
646
      if (xmlData[i + 1] === "/") {//close tag
425✔
647
        const closeIndex = findClosingIndex(xmlData, ">", i, `${tagName} is not closed`);
260✔
648
        let closeTagName = xmlData.substring(i + 2, closeIndex).trim();
260✔
649
        if (closeTagName === tagName) {
260✔
650
          openTagCount--;
120✔
651
          if (openTagCount === 0) {
120✔
652
            return {
115✔
653
              tagContent: xmlData.substring(startIndex, i),
115✔
654
              i: closeIndex
115✔
655
            }
115✔
656
          }
115✔
657
        }
120✔
658
        i = closeIndex;
145✔
659
      } else if (xmlData[i + 1] === '?') {
425!
660
        const closeIndex = findClosingIndex(xmlData, "?>", i + 1, "StopNode is not closed.")
×
661
        i = closeIndex;
×
662
      } else if (xmlData.substr(i + 1, 3) === '!--') {
165✔
663
        const closeIndex = findClosingIndex(xmlData, "-->", i + 3, "StopNode is not closed.")
5✔
664
        i = closeIndex;
5✔
665
      } else if (xmlData.substr(i + 1, 2) === '![') {
165✔
666
        const closeIndex = findClosingIndex(xmlData, "]]>", i, "StopNode is not closed.") - 2;
5✔
667
        i = closeIndex;
5✔
668
      } else {
160✔
669
        const tagData = readTagExp(xmlData, i, '>')
155✔
670

155✔
671
        if (tagData) {
155✔
672
          const openTagName = tagData && tagData.tagName;
150✔
673
          if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length - 1] !== "/") {
150✔
674
            openTagCount++;
5✔
675
          }
5✔
676
          i = tagData.closeIndex;
150✔
677
        }
150✔
678
      }
155✔
679
    }
425✔
680
  }//end for loop
115✔
681
}
115✔
682

5✔
683
function parseValue(val, shouldParse, options) {
3,400✔
684
  if (shouldParse && typeof val === 'string') {
3,400✔
685
    //console.log(options)
2,365✔
686
    const newval = val.trim();
2,365✔
687
    if (newval === 'true') return true;
2,365✔
688
    else if (newval === 'false') return false;
2,330✔
689
    else return toNumber(val, options);
2,315✔
690
  } else {
3,400✔
691
    if (isExist(val)) {
1,035✔
692
      return val;
1,035✔
693
    } else {
1,035!
694
      return '';
×
695
    }
×
696
  }
1,035✔
697
}
3,400✔
698

5✔
699
function fromCodePoint(str, base, prefix) {
50✔
700
  const codePoint = Number.parseInt(str, base);
50✔
701

50✔
702
  if (codePoint >= 0 && codePoint <= 0x10FFFF) {
50✔
703
    return String.fromCodePoint(codePoint);
40✔
704
  } else {
50✔
705
    return prefix + str + ";";
10✔
706
  }
10✔
707
}
50✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc