@srobroek/pi-code-quality 0.0.0-stage → 0.15.3

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.
Files changed (55) hide show
  1. package/CHANGELOG.md +191 -0
  2. package/LICENSE +202 -0
  3. package/README.md +150 -2
  4. package/agents/adversarial-challenger.md +29 -0
  5. package/extensions/quality.js +4583 -0
  6. package/package.json +40 -4
  7. package/skills/prototype-logic/LICENSE +21 -0
  8. package/skills/prototype-logic/NOTICE +26 -0
  9. package/skills/prototype-logic/SKILL.md +76 -0
  10. package/skills/quality-code-design/LICENSE-mattpocock-skills +21 -0
  11. package/skills/quality-code-design/NOTICE +63 -0
  12. package/skills/quality-code-design/SKILL.md +63 -0
  13. package/skills/quality-code-design/references/contracts.md +37 -0
  14. package/skills/quality-code-design/references/debugging.md +85 -0
  15. package/skills/quality-code-design/references/deep-modules.md +67 -0
  16. package/skills/quality-code-design/references/dependencies.md +81 -0
  17. package/skills/quality-code-design/references/encapsulation.md +148 -0
  18. package/skills/quality-code-design/references/feature-flags.md +189 -0
  19. package/skills/quality-code-design/references/go.md +110 -0
  20. package/skills/quality-code-design/references/lifecycle.md +66 -0
  21. package/skills/quality-code-design/references/middleware.md +55 -0
  22. package/skills/quality-code-design/references/other-paradigms.md +44 -0
  23. package/skills/quality-code-design/references/persistence.md +52 -0
  24. package/skills/quality-code-design/references/python.md +100 -0
  25. package/skills/quality-code-design/references/release.md +59 -0
  26. package/skills/quality-code-design/references/review.md +121 -0
  27. package/skills/quality-code-design/references/rust.md +140 -0
  28. package/skills/quality-code-design/references/safe-mutation.md +33 -0
  29. package/skills/quality-code-design/references/security.md +65 -0
  30. package/skills/quality-code-design/references/simplicity.md +165 -0
  31. package/skills/quality-code-design/references/solid.md +165 -0
  32. package/skills/quality-code-design/references/supporting-principles.md +78 -0
  33. package/skills/quality-code-design/references/telemetry.md +54 -0
  34. package/skills/quality-code-design/references/test-first.md +78 -0
  35. package/skills/quality-code-design/references/typescript.md +93 -0
  36. package/skills/quality-code-design/references/verification.md +53 -0
  37. package/skills/quality-code-policy/SKILL.md +34 -0
  38. package/skills/quality-profiling/SKILL.md +48 -0
  39. package/skills/quality-profiling/references/hygiene.md +27 -0
  40. package/skills/quality-profiling/references/reading-profiles.md +21 -0
  41. package/skills/quality-profiling/references/system.md +51 -0
  42. package/skills/quality-test-audit/SKILL.md +122 -0
  43. package/skills/quality-test-audit/references/catalog.md +108 -0
  44. package/skills/quality-test-audit/references/evidence.md +123 -0
  45. package/skills/quality-test-audit/references/report.md +75 -0
  46. package/skills/quality-testing/SKILL.md +62 -0
  47. package/skills/quality-testing/references/bad-tests.md +258 -0
  48. package/skills/quality-testing/references/doubles.md +49 -0
  49. package/skills/quality-testing/references/good-tests.md +90 -0
  50. package/skills/quality-testing/references/maintenance.md +96 -0
  51. package/skills/quality-testing/references/review-tests.md +72 -0
  52. package/skills/quality-testing/references/shared-contracts.md +30 -0
  53. package/skills/quality-testing/references/signals.md +50 -0
  54. package/skills/quality-testing/references/test-budget.md +81 -0
  55. package/skills/quality-testing/references/what-to-test.md +58 -0
@@ -0,0 +1,4583 @@
1
+ // @bun
2
+ // Generated by scripts/build.ts. Do not edit.
3
+ // plugins/quality/pi-src/quality.ts
4
+ import { mkdirSync, realpathSync as realpathSync2 } from "fs";
5
+ import { tmpdir as tmpdir2 } from "os";
6
+ import { join as join2 } from "path";
7
+ import { Type } from "typebox";
8
+
9
+ // plugins/quality/shared/audit-util.ts
10
+ import { readFileSync, realpathSync, statSync } from "fs";
11
+ import { tmpdir } from "os";
12
+ import { isAbsolute, join, relative, resolve, sep } from "path";
13
+ var TEXT_CAP = 4000;
14
+ function opencodeTempDir() {
15
+ return join(realpathSync(tmpdir()), "opencode");
16
+ }
17
+ function capText(lines, cap = TEXT_CAP) {
18
+ const text = lines.join(`
19
+ `);
20
+ if (text.length <= cap)
21
+ return text;
22
+ return `${text.slice(0, cap - 24).trimEnd()}
23
+ ... (output truncated)`;
24
+ }
25
+ function median(values) {
26
+ if (values.length === 0)
27
+ return Number.NaN;
28
+ const sorted = [...values].sort((a, b) => a - b);
29
+ const mid = sorted.length >> 1;
30
+ return sorted.length % 2 === 1 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
31
+ }
32
+ function compactRanges(lines, maxRanges = 12) {
33
+ const sorted = [...new Set(lines)].sort((a, b) => a - b);
34
+ const ranges = [];
35
+ let start = 0;
36
+ for (let i = 0;i < sorted.length; i++) {
37
+ const current = sorted[i];
38
+ if (i + 1 < sorted.length && sorted[i + 1] === current + 1)
39
+ continue;
40
+ const first = sorted[start];
41
+ ranges.push(first === current ? `${current}` : `${first}-${current}`);
42
+ start = i + 1;
43
+ }
44
+ if (ranges.length <= maxRanges)
45
+ return ranges.join(",");
46
+ return `${ranges.slice(0, maxRanges).join(",")},... (+${ranges.length - maxRanges} ranges)`;
47
+ }
48
+ function percent(part, whole) {
49
+ return whole === 0 ? 100 : Math.round(part / whole * 1000) / 10;
50
+ }
51
+ function inside(root, target) {
52
+ const rel = relative(root, target);
53
+ return rel === "" || rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
54
+ }
55
+
56
+ class PathError extends Error {
57
+ }
58
+ function reportRoots(sessionDirectory, temporaryDirectory = opencodeTempDir()) {
59
+ const real = (path) => {
60
+ try {
61
+ return realpathSync(path);
62
+ } catch {
63
+ return resolve(path);
64
+ }
65
+ };
66
+ return [real(sessionDirectory), real(temporaryDirectory)];
67
+ }
68
+ var MAX_REPORT_BYTES = 200 * 1024 * 1024;
69
+ function readReportFile(sessionDirectory, path, roots = reportRoots(sessionDirectory)) {
70
+ const target = isAbsolute(path) ? path : resolve(sessionDirectory, path);
71
+ let real;
72
+ try {
73
+ real = realpathSync(target);
74
+ } catch {
75
+ if (!roots.some((root) => inside(root, resolve(target))))
76
+ throw new PathError(`${path} is outside the session and allowed report directories`);
77
+ throw new Error(`${path} does not exist`);
78
+ }
79
+ if (!roots.some((root) => inside(root, real)))
80
+ throw new PathError(`${path} is outside the session and allowed report directories`);
81
+ if (statSync(real).size > MAX_REPORT_BYTES)
82
+ throw new Error(`${path} is larger than ${MAX_REPORT_BYTES / 1024 / 1024} MB`);
83
+ return readFileSync(real, "utf8");
84
+ }
85
+
86
+ // node_modules/fast-xml-parser/src/util.js
87
+ var nameStartChar = ":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";
88
+ var nameChar = nameStartChar + "\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040";
89
+ var nameRegexp = "[" + nameStartChar + "][" + nameChar + "]*";
90
+ var regexName = new RegExp("^" + nameRegexp + "$");
91
+ function getAllMatches(string, regex) {
92
+ const matches = [];
93
+ let match = regex.exec(string);
94
+ while (match) {
95
+ const allmatches = [];
96
+ allmatches.startIndex = regex.lastIndex - match[0].length;
97
+ const len = match.length;
98
+ for (let index = 0;index < len; index++) {
99
+ allmatches.push(match[index]);
100
+ }
101
+ matches.push(allmatches);
102
+ match = regex.exec(string);
103
+ }
104
+ return matches;
105
+ }
106
+ var isName = function(string) {
107
+ const match = regexName.exec(string);
108
+ return !(match === null || typeof match === "undefined");
109
+ };
110
+ function isExist(v) {
111
+ return typeof v !== "undefined";
112
+ }
113
+ var DANGEROUS_PROPERTY_NAMES = [
114
+ "hasOwnProperty",
115
+ "toString",
116
+ "valueOf",
117
+ "__defineGetter__",
118
+ "__defineSetter__",
119
+ "__lookupGetter__",
120
+ "__lookupSetter__"
121
+ ];
122
+ var criticalProperties = ["__proto__", "constructor", "prototype"];
123
+
124
+ // node_modules/fast-xml-parser/src/validator.js
125
+ var defaultOptions = {
126
+ allowBooleanAttributes: false,
127
+ unpairedTags: []
128
+ };
129
+ function validate(xmlData, options) {
130
+ options = Object.assign({}, defaultOptions, options);
131
+ const tags = [];
132
+ let tagFound = false;
133
+ let reachedRoot = false;
134
+ if (xmlData[0] === "\uFEFF") {
135
+ xmlData = xmlData.substr(1);
136
+ }
137
+ for (let i = 0;i < xmlData.length; i++) {
138
+ if (xmlData[i] === "<" && xmlData[i + 1] === "?") {
139
+ i += 2;
140
+ i = readPI(xmlData, i);
141
+ if (i.err)
142
+ return i;
143
+ } else if (xmlData[i] === "<") {
144
+ let tagStartPos = i;
145
+ i++;
146
+ if (xmlData[i] === "!") {
147
+ i = readCommentAndCDATA(xmlData, i);
148
+ continue;
149
+ } else {
150
+ let closingTag = false;
151
+ if (xmlData[i] === "/") {
152
+ closingTag = true;
153
+ i++;
154
+ }
155
+ let tagName = "";
156
+ for (;i < xmlData.length && xmlData[i] !== ">" && xmlData[i] !== " " && xmlData[i] !== "\t" && xmlData[i] !== `
157
+ ` && xmlData[i] !== "\r"; i++) {
158
+ tagName += xmlData[i];
159
+ }
160
+ tagName = tagName.trim();
161
+ if (tagName[tagName.length - 1] === "/") {
162
+ tagName = tagName.substring(0, tagName.length - 1);
163
+ i--;
164
+ }
165
+ if (!validateTagName(tagName)) {
166
+ let msg;
167
+ if (tagName.trim().length === 0) {
168
+ msg = "Invalid space after '<'.";
169
+ } else {
170
+ msg = "Tag '" + tagName + "' is an invalid name.";
171
+ }
172
+ return getErrorObject("InvalidTag", msg, getLineNumberForPosition(xmlData, i));
173
+ }
174
+ const result = readAttributeStr(xmlData, i);
175
+ if (result === false) {
176
+ return getErrorObject("InvalidAttr", "Attributes for '" + tagName + "' have open quote.", getLineNumberForPosition(xmlData, i));
177
+ }
178
+ let attrStr = result.value;
179
+ i = result.index;
180
+ if (attrStr[attrStr.length - 1] === "/") {
181
+ const attrStrStart = i - attrStr.length;
182
+ attrStr = attrStr.substring(0, attrStr.length - 1);
183
+ const isValid = validateAttributeString(attrStr, options);
184
+ if (isValid === true) {
185
+ tagFound = true;
186
+ } else {
187
+ return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid.err.line));
188
+ }
189
+ } else if (closingTag) {
190
+ if (!result.tagClosed) {
191
+ return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' doesn't have proper closing.", getLineNumberForPosition(xmlData, i));
192
+ } else if (attrStr.trim().length > 0) {
193
+ return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' can't have attributes or invalid starting.", getLineNumberForPosition(xmlData, tagStartPos));
194
+ } else if (tags.length === 0) {
195
+ return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' has not been opened.", getLineNumberForPosition(xmlData, tagStartPos));
196
+ } else {
197
+ const otg = tags.pop();
198
+ if (tagName !== otg.tagName) {
199
+ let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos);
200
+ return getErrorObject("InvalidTag", "Expected closing tag '" + otg.tagName + "' (opened in line " + openPos.line + ", col " + openPos.col + ") instead of closing tag '" + tagName + "'.", getLineNumberForPosition(xmlData, tagStartPos));
201
+ }
202
+ if (tags.length == 0) {
203
+ reachedRoot = true;
204
+ }
205
+ }
206
+ } else {
207
+ const isValid = validateAttributeString(attrStr, options);
208
+ if (isValid !== true) {
209
+ return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, i - attrStr.length + isValid.err.line));
210
+ }
211
+ if (reachedRoot === true) {
212
+ return getErrorObject("InvalidXml", "Multiple possible root nodes found.", getLineNumberForPosition(xmlData, i));
213
+ } else if (options.unpairedTags.indexOf(tagName) !== -1) {} else {
214
+ tags.push({ tagName, tagStartPos });
215
+ }
216
+ tagFound = true;
217
+ }
218
+ for (i++;i < xmlData.length; i++) {
219
+ if (xmlData[i] === "<") {
220
+ if (xmlData[i + 1] === "!") {
221
+ i++;
222
+ i = readCommentAndCDATA(xmlData, i);
223
+ continue;
224
+ } else if (xmlData[i + 1] === "?") {
225
+ i = readPI(xmlData, ++i);
226
+ if (i.err)
227
+ return i;
228
+ } else {
229
+ break;
230
+ }
231
+ } else if (xmlData[i] === "&") {
232
+ const afterAmp = validateAmpersand(xmlData, i);
233
+ if (afterAmp == -1)
234
+ return getErrorObject("InvalidChar", "char '&' is not expected.", getLineNumberForPosition(xmlData, i));
235
+ i = afterAmp;
236
+ } else {
237
+ if (reachedRoot === true && !isWhiteSpace(xmlData[i])) {
238
+ return getErrorObject("InvalidXml", "Extra text at the end", getLineNumberForPosition(xmlData, i));
239
+ }
240
+ }
241
+ }
242
+ if (xmlData[i] === "<") {
243
+ i--;
244
+ }
245
+ }
246
+ } else {
247
+ if (isWhiteSpace(xmlData[i])) {
248
+ continue;
249
+ }
250
+ return getErrorObject("InvalidChar", "char '" + xmlData[i] + "' is not expected.", getLineNumberForPosition(xmlData, i));
251
+ }
252
+ }
253
+ if (!tagFound) {
254
+ return getErrorObject("InvalidXml", "Start tag expected.", 1);
255
+ } else if (tags.length == 1) {
256
+ return getErrorObject("InvalidTag", "Unclosed tag '" + tags[0].tagName + "'.", getLineNumberForPosition(xmlData, tags[0].tagStartPos));
257
+ } else if (tags.length > 0) {
258
+ return getErrorObject("InvalidXml", "Invalid '" + JSON.stringify(tags.map((t) => t.tagName), null, 4).replace(/\r?\n/g, "") + "' found.", { line: 1, col: 1 });
259
+ }
260
+ return true;
261
+ }
262
+ function isWhiteSpace(char) {
263
+ return char === " " || char === "\t" || char === `
264
+ ` || char === "\r";
265
+ }
266
+ function readPI(xmlData, i) {
267
+ const start = i;
268
+ for (;i < xmlData.length; i++) {
269
+ if (xmlData[i] == "?" || xmlData[i] == " ") {
270
+ const tagname = xmlData.substr(start, i - start);
271
+ if (i > 5 && tagname === "xml") {
272
+ return getErrorObject("InvalidXml", "XML declaration allowed only at the start of the document.", getLineNumberForPosition(xmlData, i));
273
+ } else if (xmlData[i] == "?" && xmlData[i + 1] == ">") {
274
+ i++;
275
+ break;
276
+ } else {
277
+ continue;
278
+ }
279
+ }
280
+ }
281
+ return i;
282
+ }
283
+ function readCommentAndCDATA(xmlData, i) {
284
+ if (xmlData.length > i + 5 && xmlData[i + 1] === "-" && xmlData[i + 2] === "-") {
285
+ for (i += 3;i < xmlData.length; i++) {
286
+ if (xmlData[i] === "-" && xmlData[i + 1] === "-" && xmlData[i + 2] === ">") {
287
+ i += 2;
288
+ break;
289
+ }
290
+ }
291
+ } else if (xmlData.length > i + 8 && xmlData[i + 1] === "D" && xmlData[i + 2] === "O" && xmlData[i + 3] === "C" && xmlData[i + 4] === "T" && xmlData[i + 5] === "Y" && xmlData[i + 6] === "P" && xmlData[i + 7] === "E") {
292
+ let angleBracketsCount = 1;
293
+ for (i += 8;i < xmlData.length; i++) {
294
+ if (xmlData[i] === "<") {
295
+ angleBracketsCount++;
296
+ } else if (xmlData[i] === ">") {
297
+ angleBracketsCount--;
298
+ if (angleBracketsCount === 0) {
299
+ break;
300
+ }
301
+ }
302
+ }
303
+ } else if (xmlData.length > i + 9 && xmlData[i + 1] === "[" && xmlData[i + 2] === "C" && xmlData[i + 3] === "D" && xmlData[i + 4] === "A" && xmlData[i + 5] === "T" && xmlData[i + 6] === "A" && xmlData[i + 7] === "[") {
304
+ for (i += 8;i < xmlData.length; i++) {
305
+ if (xmlData[i] === "]" && xmlData[i + 1] === "]" && xmlData[i + 2] === ">") {
306
+ i += 2;
307
+ break;
308
+ }
309
+ }
310
+ }
311
+ return i;
312
+ }
313
+ var doubleQuote = '"';
314
+ var singleQuote = "'";
315
+ function readAttributeStr(xmlData, i) {
316
+ let attrStr = "";
317
+ let startChar = "";
318
+ let tagClosed = false;
319
+ for (;i < xmlData.length; i++) {
320
+ if (xmlData[i] === doubleQuote || xmlData[i] === singleQuote) {
321
+ if (startChar === "") {
322
+ startChar = xmlData[i];
323
+ } else if (startChar !== xmlData[i]) {} else {
324
+ startChar = "";
325
+ }
326
+ } else if (xmlData[i] === ">") {
327
+ if (startChar === "") {
328
+ tagClosed = true;
329
+ break;
330
+ }
331
+ }
332
+ attrStr += xmlData[i];
333
+ }
334
+ if (startChar !== "") {
335
+ return false;
336
+ }
337
+ return {
338
+ value: attrStr,
339
+ index: i,
340
+ tagClosed
341
+ };
342
+ }
343
+ function scanAttributeTokens(attrStr) {
344
+ const tokens = [];
345
+ const len = attrStr.length;
346
+ let i = 0;
347
+ while (i < len) {
348
+ const tokenStart = i;
349
+ while (i < len && isWhiteSpace(attrStr[i]))
350
+ i++;
351
+ if (i >= len)
352
+ break;
353
+ if (attrStr[i] === "=") {
354
+ i++;
355
+ continue;
356
+ }
357
+ const leadingWs = attrStr.slice(tokenStart, i);
358
+ const nameStart = i;
359
+ while (i < len && !isWhiteSpace(attrStr[i]) && attrStr[i] !== "=")
360
+ i++;
361
+ const name = attrStr.slice(nameStart, i);
362
+ let equalsGroup;
363
+ let j = i;
364
+ while (j < len && isWhiteSpace(attrStr[j]))
365
+ j++;
366
+ if (j < len && attrStr[j] === "=") {
367
+ equalsGroup = attrStr.slice(i, j + 1);
368
+ i = j + 1;
369
+ }
370
+ let quoteChar;
371
+ let value;
372
+ let k = i;
373
+ while (k < len && isWhiteSpace(attrStr[k]))
374
+ k++;
375
+ if (k < len && (attrStr[k] === '"' || attrStr[k] === "'")) {
376
+ const valueStart = k + 1;
377
+ const closeIdx = attrStr.indexOf(attrStr[k], valueStart);
378
+ if (closeIdx !== -1) {
379
+ quoteChar = attrStr[k];
380
+ value = attrStr.slice(valueStart, closeIdx);
381
+ i = closeIdx + 1;
382
+ }
383
+ }
384
+ const token = { startIndex: tokenStart };
385
+ token[1] = leadingWs;
386
+ token[2] = name;
387
+ token[3] = equalsGroup;
388
+ token[4] = quoteChar !== undefined ? true : undefined;
389
+ token[5] = quoteChar;
390
+ token[6] = value;
391
+ tokens.push(token);
392
+ }
393
+ return tokens;
394
+ }
395
+ function validateAttributeString(attrStr, options) {
396
+ const matches = scanAttributeTokens(attrStr);
397
+ const attrNames = {};
398
+ for (let i = 0;i < matches.length; i++) {
399
+ if (matches[i][1].length === 0) {
400
+ return getErrorObject("InvalidAttr", "Attribute '" + matches[i][2] + "' has no space in starting.", getPositionFromMatch(matches[i]));
401
+ } else if (matches[i][3] !== undefined && matches[i][4] === undefined) {
402
+ return getErrorObject("InvalidAttr", "Attribute '" + matches[i][2] + "' is without value.", getPositionFromMatch(matches[i]));
403
+ } else if (matches[i][3] === undefined && !options.allowBooleanAttributes) {
404
+ return getErrorObject("InvalidAttr", "boolean attribute '" + matches[i][2] + "' is not allowed.", getPositionFromMatch(matches[i]));
405
+ }
406
+ const attrName = matches[i][2];
407
+ if (!validateAttrName(attrName)) {
408
+ return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is an invalid name.", getPositionFromMatch(matches[i]));
409
+ }
410
+ if (!Object.prototype.hasOwnProperty.call(attrNames, attrName)) {
411
+ attrNames[attrName] = 1;
412
+ } else {
413
+ return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is repeated.", getPositionFromMatch(matches[i]));
414
+ }
415
+ }
416
+ return true;
417
+ }
418
+ function validateNumberAmpersand(xmlData, i) {
419
+ let re = /\d/;
420
+ if (xmlData[i] === "x") {
421
+ i++;
422
+ re = /[\da-fA-F]/;
423
+ }
424
+ for (;i < xmlData.length; i++) {
425
+ if (xmlData[i] === ";")
426
+ return i;
427
+ if (!xmlData[i].match(re))
428
+ break;
429
+ }
430
+ return -1;
431
+ }
432
+ function validateAmpersand(xmlData, i) {
433
+ i++;
434
+ if (xmlData[i] === ";")
435
+ return -1;
436
+ if (xmlData[i] === "#") {
437
+ i++;
438
+ return validateNumberAmpersand(xmlData, i);
439
+ }
440
+ let count = 0;
441
+ for (;i < xmlData.length; i++, count++) {
442
+ if (xmlData[i].match(/\w/) && count < 20)
443
+ continue;
444
+ if (xmlData[i] === ";")
445
+ break;
446
+ return -1;
447
+ }
448
+ return i;
449
+ }
450
+ function getErrorObject(code, message, lineNumber) {
451
+ return {
452
+ err: {
453
+ code,
454
+ msg: message,
455
+ line: lineNumber.line || lineNumber,
456
+ col: lineNumber.col
457
+ }
458
+ };
459
+ }
460
+ function validateAttrName(attrName) {
461
+ return isName(attrName);
462
+ }
463
+ function validateTagName(tagname) {
464
+ return isName(tagname);
465
+ }
466
+ function getLineNumberForPosition(xmlData, index) {
467
+ const lines = xmlData.substring(0, index).split(/\r?\n/);
468
+ return {
469
+ line: lines.length,
470
+ col: lines[lines.length - 1].length + 1
471
+ };
472
+ }
473
+ function getPositionFromMatch(match) {
474
+ return match.startIndex + match[1].length;
475
+ }
476
+
477
+ // node_modules/@nodable/entities/src/entities.js
478
+ var CURRENCY = {
479
+ cent: "\xA2",
480
+ pound: "\xA3",
481
+ curren: "\xA4",
482
+ yen: "\xA5",
483
+ euro: "\u20AC",
484
+ dollar: "$",
485
+ fnof: "\u0192",
486
+ inr: "\u20B9",
487
+ af: "\u060B",
488
+ birr: "\u1265\u122D",
489
+ peso: "\u20B1",
490
+ rub: "\u20BD",
491
+ won: "\u20A9",
492
+ yuan: "\xA5",
493
+ cedil: "\xB8"
494
+ };
495
+ var XML = {
496
+ amp: "&",
497
+ apos: "'",
498
+ gt: ">",
499
+ lt: "<",
500
+ quot: '"'
501
+ };
502
+ var COMMON_HTML = {
503
+ nbsp: "\xA0",
504
+ copy: "\xA9",
505
+ reg: "\xAE",
506
+ trade: "\u2122",
507
+ mdash: "\u2014",
508
+ ndash: "\u2013",
509
+ hellip: "\u2026",
510
+ laquo: "\xAB",
511
+ raquo: "\xBB",
512
+ lsquo: "\u2018",
513
+ rsquo: "\u2019",
514
+ ldquo: "\u201C",
515
+ rdquo: "\u201D",
516
+ bull: "\u2022",
517
+ para: "\xB6",
518
+ sect: "\xA7",
519
+ deg: "\xB0",
520
+ frac12: "\xBD",
521
+ frac14: "\xBC",
522
+ frac34: "\xBE"
523
+ };
524
+
525
+ // node_modules/@nodable/entities/src/EntityDecoder.js
526
+ var ENTITY_ACTION = Object.freeze({
527
+ ALLOW: "allow",
528
+ BLOCK: "block",
529
+ THROW: "throw"
530
+ });
531
+ var SPECIAL_CHARS = new Set("!?\\\\/[]$%{}^&*()<>|+");
532
+ function validateEntityName(name) {
533
+ if (name[0] === "#") {
534
+ throw new Error(`[EntityReplacer] Invalid character '#' in entity name: "${name}"`);
535
+ }
536
+ for (const ch of name) {
537
+ if (SPECIAL_CHARS.has(ch)) {
538
+ throw new Error(`[EntityReplacer] Invalid character '${ch}' in entity name: "${name}"`);
539
+ }
540
+ }
541
+ return name;
542
+ }
543
+ function mergeEntityMaps(...maps) {
544
+ const out = Object.create(null);
545
+ for (const map of maps) {
546
+ if (!map)
547
+ continue;
548
+ for (const key of Object.keys(map)) {
549
+ const raw = map[key];
550
+ if (typeof raw === "string") {
551
+ out[key] = raw;
552
+ } else if (raw && typeof raw === "object" && raw.val !== undefined) {
553
+ const val = raw.val;
554
+ if (typeof val === "string") {
555
+ out[key] = val;
556
+ }
557
+ }
558
+ }
559
+ }
560
+ return out;
561
+ }
562
+ var LIMIT_TIER_EXTERNAL = "external";
563
+ var LIMIT_TIER_BASE = "base";
564
+ var LIMIT_TIER_ALL = "all";
565
+ function parseLimitTiers(raw) {
566
+ if (!raw || raw === LIMIT_TIER_EXTERNAL)
567
+ return new Set([LIMIT_TIER_EXTERNAL]);
568
+ if (raw === LIMIT_TIER_ALL)
569
+ return new Set([LIMIT_TIER_ALL]);
570
+ if (raw === LIMIT_TIER_BASE)
571
+ return new Set([LIMIT_TIER_BASE]);
572
+ if (Array.isArray(raw))
573
+ return new Set(raw);
574
+ return new Set([LIMIT_TIER_EXTERNAL]);
575
+ }
576
+ var NCR_LEVEL = Object.freeze({ allow: 0, leave: 1, remove: 2, throw: 3 });
577
+ var XML10_ALLOWED_C0 = new Set([9, 10, 13]);
578
+ function parseNCRConfig(ncr) {
579
+ if (!ncr) {
580
+ return { xmlVersion: 1, onLevel: NCR_LEVEL.allow, nullLevel: NCR_LEVEL.remove };
581
+ }
582
+ const xmlVersion = ncr.xmlVersion === 1.1 ? 1.1 : 1;
583
+ const onLevel = NCR_LEVEL[ncr.onNCR] ?? NCR_LEVEL.allow;
584
+ const nullLevel = NCR_LEVEL[ncr.nullNCR] ?? NCR_LEVEL.remove;
585
+ const clampedNull = Math.max(nullLevel, NCR_LEVEL.remove);
586
+ return { xmlVersion, onLevel, nullLevel: clampedNull };
587
+ }
588
+
589
+ class EntityDecoder {
590
+ constructor(options = {}) {
591
+ this._limit = options.limit || {};
592
+ this._maxTotalExpansions = this._limit.maxTotalExpansions || 0;
593
+ this._maxExpandedLength = this._limit.maxExpandedLength || 0;
594
+ this._postCheck = typeof options.postCheck === "function" ? options.postCheck : (r) => r;
595
+ this._limitTiers = parseLimitTiers(this._limit.applyLimitsTo ?? LIMIT_TIER_EXTERNAL);
596
+ this._numericAllowed = options.numericAllowed ?? true;
597
+ this._baseMap = mergeEntityMaps(XML, options.namedEntities || null);
598
+ this._externalMap = Object.create(null);
599
+ this._inputMap = Object.create(null);
600
+ this._totalExpansions = 0;
601
+ this._expandedLength = 0;
602
+ this._removeSet = new Set(options.remove && Array.isArray(options.remove) ? options.remove : []);
603
+ this._leaveSet = new Set(options.leave && Array.isArray(options.leave) ? options.leave : []);
604
+ const ncrCfg = parseNCRConfig(options.ncr);
605
+ this._ncrXmlVersion = ncrCfg.xmlVersion;
606
+ this._ncrOnLevel = ncrCfg.onLevel;
607
+ this._ncrNullLevel = ncrCfg.nullLevel;
608
+ this._onExternalEntity = typeof options.onExternalEntity === "function" ? options.onExternalEntity : null;
609
+ this._onInputEntity = typeof options.onInputEntity === "function" ? options.onInputEntity : null;
610
+ }
611
+ _applyRegistrationHook(hook, name, value, context) {
612
+ if (!hook)
613
+ return true;
614
+ const action = hook(name, value);
615
+ if (action === ENTITY_ACTION.BLOCK)
616
+ return false;
617
+ if (action === ENTITY_ACTION.THROW) {
618
+ throw new Error(`[EntityDecoder] Registration of ${context} entity "&${name};" was rejected by hook`);
619
+ }
620
+ return true;
621
+ }
622
+ setExternalEntities(map) {
623
+ if (map) {
624
+ for (const key of Object.keys(map)) {
625
+ validateEntityName(key);
626
+ }
627
+ }
628
+ if (!this._onExternalEntity) {
629
+ this._externalMap = mergeEntityMaps(map);
630
+ return;
631
+ }
632
+ const flat = mergeEntityMaps(map);
633
+ const filtered = Object.create(null);
634
+ for (const [name, value] of Object.entries(flat)) {
635
+ if (this._applyRegistrationHook(this._onExternalEntity, name, value, "external")) {
636
+ filtered[name] = value;
637
+ }
638
+ }
639
+ this._externalMap = filtered;
640
+ }
641
+ addExternalEntity(key, value) {
642
+ validateEntityName(key);
643
+ if (typeof value === "string" && value.indexOf("&") === -1) {
644
+ if (this._applyRegistrationHook(this._onExternalEntity, key, value, "external")) {
645
+ this._externalMap[key] = value;
646
+ }
647
+ }
648
+ }
649
+ addInputEntities(map) {
650
+ this._totalExpansions = 0;
651
+ this._expandedLength = 0;
652
+ if (!this._onInputEntity) {
653
+ this._inputMap = mergeEntityMaps(map);
654
+ return;
655
+ }
656
+ const flat = mergeEntityMaps(map);
657
+ const filtered = Object.create(null);
658
+ for (const [name, value] of Object.entries(flat)) {
659
+ if (this._applyRegistrationHook(this._onInputEntity, name, value, "input")) {
660
+ filtered[name] = value;
661
+ }
662
+ }
663
+ this._inputMap = filtered;
664
+ }
665
+ reset() {
666
+ this._inputMap = Object.create(null);
667
+ this._totalExpansions = 0;
668
+ this._expandedLength = 0;
669
+ return this;
670
+ }
671
+ setXmlVersion(version) {
672
+ this._ncrXmlVersion = version === 1.1 ? 1.1 : 1;
673
+ }
674
+ decode(str) {
675
+ if (typeof str !== "string" || str.length === 0)
676
+ return str;
677
+ if (str.indexOf("&") === -1)
678
+ return str;
679
+ const original = str;
680
+ const chunks = [];
681
+ const len = str.length;
682
+ let last = 0;
683
+ let i = 0;
684
+ const limitExpansions = this._maxTotalExpansions > 0;
685
+ const limitLength = this._maxExpandedLength > 0;
686
+ const checkLimits = limitExpansions || limitLength;
687
+ while (i < len) {
688
+ if (str.charCodeAt(i) !== 38) {
689
+ i++;
690
+ continue;
691
+ }
692
+ let j = i + 1;
693
+ while (j < len && str.charCodeAt(j) !== 59 && j - i <= 32)
694
+ j++;
695
+ if (j >= len || str.charCodeAt(j) !== 59) {
696
+ i++;
697
+ continue;
698
+ }
699
+ const token = str.slice(i + 1, j);
700
+ if (token.length === 0) {
701
+ i++;
702
+ continue;
703
+ }
704
+ let replacement;
705
+ let tier;
706
+ if (this._removeSet.has(token)) {
707
+ replacement = "";
708
+ if (tier === undefined) {
709
+ tier = LIMIT_TIER_EXTERNAL;
710
+ }
711
+ } else if (this._leaveSet.has(token)) {
712
+ i++;
713
+ continue;
714
+ } else if (token.charCodeAt(0) === 35) {
715
+ const ncrResult = this._resolveNCR(token);
716
+ if (ncrResult === undefined) {
717
+ i++;
718
+ continue;
719
+ }
720
+ replacement = ncrResult;
721
+ tier = LIMIT_TIER_BASE;
722
+ } else {
723
+ const resolved = this._resolveName(token);
724
+ replacement = resolved?.value;
725
+ tier = resolved?.tier;
726
+ }
727
+ if (replacement === undefined) {
728
+ i++;
729
+ continue;
730
+ }
731
+ if (i > last)
732
+ chunks.push(str.slice(last, i));
733
+ chunks.push(replacement);
734
+ last = j + 1;
735
+ i = last;
736
+ if (checkLimits && this._tierCounts(tier)) {
737
+ if (limitExpansions) {
738
+ this._totalExpansions++;
739
+ if (this._totalExpansions > this._maxTotalExpansions) {
740
+ throw new Error(`[EntityReplacer] Entity expansion count limit exceeded: ` + `${this._totalExpansions} > ${this._maxTotalExpansions}`);
741
+ }
742
+ }
743
+ if (limitLength) {
744
+ const delta = replacement.length - (token.length + 2);
745
+ if (delta > 0) {
746
+ this._expandedLength += delta;
747
+ if (this._expandedLength > this._maxExpandedLength) {
748
+ throw new Error(`[EntityReplacer] Expanded content length limit exceeded: ` + `${this._expandedLength} > ${this._maxExpandedLength}`);
749
+ }
750
+ }
751
+ }
752
+ }
753
+ }
754
+ if (last < len)
755
+ chunks.push(str.slice(last));
756
+ const result = chunks.length === 0 ? str : chunks.join("");
757
+ return this._postCheck(result, original);
758
+ }
759
+ _tierCounts(tier) {
760
+ if (this._limitTiers.has(LIMIT_TIER_ALL))
761
+ return true;
762
+ return this._limitTiers.has(tier);
763
+ }
764
+ _resolveName(name) {
765
+ if (name in this._inputMap)
766
+ return { value: this._inputMap[name], tier: LIMIT_TIER_EXTERNAL };
767
+ if (name in this._externalMap)
768
+ return { value: this._externalMap[name], tier: LIMIT_TIER_EXTERNAL };
769
+ if (name in this._baseMap)
770
+ return { value: this._baseMap[name], tier: LIMIT_TIER_BASE };
771
+ return;
772
+ }
773
+ _classifyNCR(cp) {
774
+ if (cp === 0)
775
+ return this._ncrNullLevel;
776
+ if (cp >= 55296 && cp <= 57343)
777
+ return NCR_LEVEL.remove;
778
+ if (this._ncrXmlVersion === 1) {
779
+ if (cp >= 1 && cp <= 31 && !XML10_ALLOWED_C0.has(cp))
780
+ return NCR_LEVEL.remove;
781
+ }
782
+ return -1;
783
+ }
784
+ _applyNCRAction(action, token, cp) {
785
+ switch (action) {
786
+ case NCR_LEVEL.allow:
787
+ return String.fromCodePoint(cp);
788
+ case NCR_LEVEL.remove:
789
+ return "";
790
+ case NCR_LEVEL.leave:
791
+ return;
792
+ case NCR_LEVEL.throw:
793
+ throw new Error(`[EntityDecoder] Prohibited numeric character reference ` + `&${token}; (U+${cp.toString(16).toUpperCase().padStart(4, "0")})`);
794
+ default:
795
+ return String.fromCodePoint(cp);
796
+ }
797
+ }
798
+ _resolveNCR(token) {
799
+ const second = token.charCodeAt(1);
800
+ let cp;
801
+ if (second === 120 || second === 88) {
802
+ cp = parseInt(token.slice(2), 16);
803
+ } else {
804
+ cp = parseInt(token.slice(1), 10);
805
+ }
806
+ if (Number.isNaN(cp) || cp < 0 || cp > 1114111)
807
+ return;
808
+ const minimum = this._classifyNCR(cp);
809
+ if (!this._numericAllowed && minimum < NCR_LEVEL.remove)
810
+ return;
811
+ const effective = minimum === -1 ? this._ncrOnLevel : Math.max(this._ncrOnLevel, minimum);
812
+ return this._applyNCRAction(effective, token, cp);
813
+ }
814
+ }
815
+ // node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js
816
+ var defaultOnDangerousProperty = (name) => {
817
+ if (DANGEROUS_PROPERTY_NAMES.includes(name)) {
818
+ return "__" + name;
819
+ }
820
+ return name;
821
+ };
822
+ var defaultOptions2 = {
823
+ preserveOrder: false,
824
+ attributeNamePrefix: "@_",
825
+ attributesGroupName: false,
826
+ textNodeName: "#text",
827
+ ignoreAttributes: true,
828
+ removeNSPrefix: false,
829
+ allowBooleanAttributes: false,
830
+ parseTagValue: true,
831
+ parseAttributeValue: false,
832
+ trimValues: true,
833
+ cdataPropName: false,
834
+ numberParseOptions: {
835
+ hex: true,
836
+ leadingZeros: true,
837
+ eNotation: true,
838
+ unicode: false
839
+ },
840
+ tagValueProcessor: function(tagName, val) {
841
+ return val;
842
+ },
843
+ attributeValueProcessor: function(attrName, val) {
844
+ return val;
845
+ },
846
+ stopNodes: [],
847
+ alwaysCreateTextNode: false,
848
+ isArray: () => false,
849
+ commentPropName: false,
850
+ unpairedTags: [],
851
+ processEntities: true,
852
+ htmlEntities: false,
853
+ entityDecoder: null,
854
+ ignoreDeclaration: false,
855
+ ignorePiTags: false,
856
+ transformTagName: false,
857
+ transformAttributeName: false,
858
+ updateTag: function(tagName, jPath, attrs) {
859
+ return tagName;
860
+ },
861
+ captureMetaData: false,
862
+ maxNestedTags: 100,
863
+ strictReservedNames: true,
864
+ jPath: true,
865
+ onDangerousProperty: defaultOnDangerousProperty
866
+ };
867
+ function validatePropertyName(propertyName, optionName) {
868
+ if (typeof propertyName !== "string") {
869
+ return;
870
+ }
871
+ const normalized = propertyName.toLowerCase();
872
+ if (DANGEROUS_PROPERTY_NAMES.some((dangerous) => normalized === dangerous.toLowerCase())) {
873
+ throw new Error(`[SECURITY] Invalid ${optionName}: "${propertyName}" is a reserved JavaScript keyword that could cause prototype pollution`);
874
+ }
875
+ if (criticalProperties.some((dangerous) => normalized === dangerous.toLowerCase())) {
876
+ throw new Error(`[SECURITY] Invalid ${optionName}: "${propertyName}" is a reserved JavaScript keyword that could cause prototype pollution`);
877
+ }
878
+ }
879
+ function normalizeProcessEntities(value, htmlEntities) {
880
+ if (typeof value === "boolean") {
881
+ return {
882
+ enabled: value,
883
+ maxEntitySize: 1e4,
884
+ maxExpansionDepth: 1e4,
885
+ maxTotalExpansions: Infinity,
886
+ maxExpandedLength: 1e5,
887
+ maxEntityCount: 1000,
888
+ allowedTags: null,
889
+ tagFilter: null,
890
+ appliesTo: "all"
891
+ };
892
+ }
893
+ if (typeof value === "object" && value !== null) {
894
+ return {
895
+ enabled: value.enabled !== false,
896
+ maxEntitySize: Math.max(1, value.maxEntitySize ?? 1e4),
897
+ maxExpansionDepth: Math.max(1, value.maxExpansionDepth ?? 1e4),
898
+ maxTotalExpansions: Math.max(1, value.maxTotalExpansions ?? Infinity),
899
+ maxExpandedLength: Math.max(1, value.maxExpandedLength ?? 1e5),
900
+ maxEntityCount: Math.max(1, value.maxEntityCount ?? 1000),
901
+ allowedTags: value.allowedTags ?? null,
902
+ tagFilter: value.tagFilter ?? null,
903
+ appliesTo: value.appliesTo ?? "all"
904
+ };
905
+ }
906
+ return normalizeProcessEntities(true);
907
+ }
908
+ var buildOptions = function(options) {
909
+ const built = Object.assign({}, defaultOptions2, options);
910
+ const propertyNameOptions = [
911
+ { value: built.attributeNamePrefix, name: "attributeNamePrefix" },
912
+ { value: built.attributesGroupName, name: "attributesGroupName" },
913
+ { value: built.textNodeName, name: "textNodeName" },
914
+ { value: built.cdataPropName, name: "cdataPropName" },
915
+ { value: built.commentPropName, name: "commentPropName" }
916
+ ];
917
+ for (const { value, name } of propertyNameOptions) {
918
+ if (value) {
919
+ validatePropertyName(value, name);
920
+ }
921
+ }
922
+ if (built.onDangerousProperty === null) {
923
+ built.onDangerousProperty = defaultOnDangerousProperty;
924
+ }
925
+ built.processEntities = normalizeProcessEntities(built.processEntities, built.htmlEntities);
926
+ built.unpairedTagsSet = new Set(built.unpairedTags);
927
+ if (built.stopNodes && Array.isArray(built.stopNodes)) {
928
+ built.stopNodes = built.stopNodes.map((node) => {
929
+ if (typeof node === "string" && node.startsWith("*.")) {
930
+ return ".." + node.substring(2);
931
+ }
932
+ return node;
933
+ });
934
+ }
935
+ return built;
936
+ };
937
+
938
+ // node_modules/fast-xml-parser/src/xmlparser/xmlNode.js
939
+ var METADATA_SYMBOL;
940
+ if (typeof Symbol !== "function") {
941
+ METADATA_SYMBOL = "@@xmlMetadata";
942
+ } else {
943
+ METADATA_SYMBOL = Symbol("XML Node Metadata");
944
+ }
945
+
946
+ class XmlNode {
947
+ constructor(tagname) {
948
+ this.tagname = tagname;
949
+ this.child = [];
950
+ this[":@"] = Object.create(null);
951
+ }
952
+ add(key, val) {
953
+ if (key === "__proto__")
954
+ key = "#__proto__";
955
+ this.child.push({ [key]: val });
956
+ }
957
+ addChild(node, startIndex) {
958
+ if (node.tagname === "__proto__")
959
+ node.tagname = "#__proto__";
960
+ if (node[":@"] && Object.keys(node[":@"]).length > 0) {
961
+ this.child.push({ [node.tagname]: node.child, [":@"]: node[":@"] });
962
+ } else {
963
+ this.child.push({ [node.tagname]: node.child });
964
+ }
965
+ this.addStartIndex(startIndex);
966
+ }
967
+ addStartIndex(startIndex) {
968
+ if (startIndex !== undefined) {
969
+ this.child[this.child.length - 1][METADATA_SYMBOL] = { startIndex };
970
+ }
971
+ }
972
+ addEndIndex(endIndex) {
973
+ const lastChild = this.child[this.child.length - 1];
974
+ if (lastChild !== undefined && lastChild[METADATA_SYMBOL] !== undefined && lastChild[METADATA_SYMBOL].endIndex === undefined) {
975
+ lastChild[METADATA_SYMBOL].endIndex = endIndex;
976
+ }
977
+ }
978
+ static getMetaDataSymbol() {
979
+ return METADATA_SYMBOL;
980
+ }
981
+ }
982
+
983
+ // node_modules/xml-naming/src/index.js
984
+ var nameStartChar10 = ":A-Za-z_" + "\xC0-\xD6\xD8-\xF6\xF8-\u02FF" + "\u0370-\u037D" + "\u037F-\u0486\u0488-\u1FFF" + "\u200C-\u200D" + "\u2070-\u218F" + "\u2C00-\u2FEF" + "\u3001-\uD7FF" + "\uF900-\uFDCF" + "\uFDF0-\uFFFD";
985
+ var nameChar10 = nameStartChar10 + "\\-\\.\\d" + "\xB7" + "\u0300-\u036F" + "\u203F-\u2040";
986
+ var nameStartChar11 = ":A-Za-z_" + "\xC0-\u02FF" + "\u0370-\u037D" + "\u037F-\u0486\u0488-\u1FFF" + "\u200C-\u200D" + "\u2070-\u218F" + "\u2C00-\u2FEF" + "\u3001-\uD7FF" + "\uF900-\uFDCF" + "\uFDF0-\uFFFD" + "\uD800\uDC00-\uDB7F\uDFFF";
987
+ var nameChar11 = nameStartChar11 + "\\-\\.\\d" + "\xB7" + "\u0300-\u036F" + "\u0487" + "\u203F-\u2040";
988
+ var buildRegexes = (startChar, char, flags = "") => {
989
+ const ncStart = startChar.replace(":", "");
990
+ const ncChar = char.replace(":", "");
991
+ const ncNamePat = `[${ncStart}][${ncChar}]*`;
992
+ return {
993
+ name: new RegExp(`^[${startChar}][${char}]*$`, flags),
994
+ ncName: new RegExp(`^${ncNamePat}$`, flags),
995
+ qName: new RegExp(`^${ncNamePat}(?::${ncNamePat})?$`, flags),
996
+ nmToken: new RegExp(`^[${char}]+$`, flags),
997
+ nmTokens: new RegExp(`^[${char}]+(?:\\s+[${char}]+)*$`, flags)
998
+ };
999
+ };
1000
+ var regexes10 = buildRegexes(nameStartChar10, nameChar10);
1001
+ var regexes11 = buildRegexes(nameStartChar11, nameChar11, "u");
1002
+ var nameStartCharAscii = ":A-Za-z_";
1003
+ var nameCharAscii = nameStartCharAscii + "\\-\\.\\d";
1004
+ var regexesAscii = buildRegexes(nameStartCharAscii, nameCharAscii);
1005
+ var getRegexes = (xmlVersion = "1.0", asciiOnly = false) => {
1006
+ if (asciiOnly)
1007
+ return regexesAscii;
1008
+ return xmlVersion === "1.1" ? regexes11 : regexes10;
1009
+ };
1010
+ var qName = (str, { xmlVersion = "1.0", asciiOnly = false } = {}) => getRegexes(xmlVersion, asciiOnly).qName.test(str);
1011
+
1012
+ // node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js
1013
+ class DocTypeReader {
1014
+ constructor(options, xmlVersion) {
1015
+ this.suppressValidationErr = !options;
1016
+ this.options = options;
1017
+ this.xmlVersion = xmlVersion || 1;
1018
+ }
1019
+ setXmlVersion(xmlVersion = 1) {
1020
+ this.xmlVersion = xmlVersion;
1021
+ }
1022
+ readDocType(xmlData, i) {
1023
+ const entities = Object.create(null);
1024
+ let entityCount = 0;
1025
+ if (xmlData[i + 3] === "O" && xmlData[i + 4] === "C" && xmlData[i + 5] === "T" && xmlData[i + 6] === "Y" && xmlData[i + 7] === "P" && xmlData[i + 8] === "E") {
1026
+ i = i + 9;
1027
+ let angleBracketsCount = 1;
1028
+ let hasBody = false, comment = false;
1029
+ let quoteChar = null;
1030
+ let exp = "";
1031
+ for (;i < xmlData.length; i++) {
1032
+ if (quoteChar !== null) {
1033
+ if (xmlData[i] === quoteChar)
1034
+ quoteChar = null;
1035
+ exp += xmlData[i];
1036
+ continue;
1037
+ }
1038
+ if (!hasBody && !comment && (xmlData[i] === '"' || xmlData[i] === "'")) {
1039
+ quoteChar = xmlData[i];
1040
+ exp += xmlData[i];
1041
+ continue;
1042
+ }
1043
+ if (xmlData[i] === "<" && !comment) {
1044
+ if (hasBody && hasSeq(xmlData, "!ENTITY", i)) {
1045
+ i += 7;
1046
+ let entityName, val;
1047
+ [entityName, val, i] = this.readEntityExp(xmlData, i + 1, this.suppressValidationErr);
1048
+ if (val.indexOf("&") === -1) {
1049
+ if (this.options.enabled !== false && this.options.maxEntityCount != null && entityCount >= this.options.maxEntityCount) {
1050
+ throw new Error(`Entity count (${entityCount + 1}) exceeds maximum allowed (${this.options.maxEntityCount})`);
1051
+ }
1052
+ entities[entityName] = val;
1053
+ entityCount++;
1054
+ }
1055
+ } else if (hasBody && hasSeq(xmlData, "!ELEMENT", i)) {
1056
+ i += 8;
1057
+ const { index } = this.readElementExp(xmlData, i + 1);
1058
+ i = index;
1059
+ } else if (hasBody && hasSeq(xmlData, "!ATTLIST", i)) {
1060
+ i += 8;
1061
+ } else if (hasBody && hasSeq(xmlData, "!NOTATION", i)) {
1062
+ i += 9;
1063
+ const { index } = this.readNotationExp(xmlData, i + 1, this.suppressValidationErr);
1064
+ i = index;
1065
+ } else if (hasSeq(xmlData, "!--", i))
1066
+ comment = true;
1067
+ else
1068
+ throw new Error(`Invalid DOCTYPE`);
1069
+ angleBracketsCount++;
1070
+ exp = "";
1071
+ } else if (xmlData[i] === ">") {
1072
+ if (comment) {
1073
+ if (xmlData[i - 1] === "-" && xmlData[i - 2] === "-") {
1074
+ comment = false;
1075
+ angleBracketsCount--;
1076
+ }
1077
+ } else {
1078
+ angleBracketsCount--;
1079
+ }
1080
+ if (angleBracketsCount === 0) {
1081
+ break;
1082
+ }
1083
+ } else if (xmlData[i] === "[") {
1084
+ hasBody = true;
1085
+ } else {
1086
+ exp += xmlData[i];
1087
+ }
1088
+ }
1089
+ if (quoteChar !== null || angleBracketsCount !== 0) {
1090
+ throw new Error(`Unclosed DOCTYPE`);
1091
+ }
1092
+ } else {
1093
+ throw new Error(`Invalid Tag instead of DOCTYPE`);
1094
+ }
1095
+ return { entities, i };
1096
+ }
1097
+ readEntityExp(xmlData, i) {
1098
+ i = skipWhitespace(xmlData, i);
1099
+ const startIndex = i;
1100
+ while (i < xmlData.length && !/\s/.test(xmlData[i]) && xmlData[i] !== '"' && xmlData[i] !== "'") {
1101
+ i++;
1102
+ }
1103
+ let entityName = xmlData.substring(startIndex, i);
1104
+ validateEntityName2(entityName, { xmlVersion: this.xmlVersion });
1105
+ i = skipWhitespace(xmlData, i);
1106
+ if (!this.suppressValidationErr) {
1107
+ if (xmlData.substring(i, i + 6).toUpperCase() === "SYSTEM") {
1108
+ throw new Error("External entities are not supported");
1109
+ } else if (xmlData[i] === "%") {
1110
+ throw new Error("Parameter entities are not supported");
1111
+ }
1112
+ }
1113
+ let entityValue = "";
1114
+ [i, entityValue] = this.readIdentifierVal(xmlData, i, "entity");
1115
+ if (this.options.enabled !== false && this.options.maxEntitySize != null && entityValue.length > this.options.maxEntitySize) {
1116
+ throw new Error(`Entity "${entityName}" size (${entityValue.length}) exceeds maximum allowed size (${this.options.maxEntitySize})`);
1117
+ }
1118
+ i--;
1119
+ return [entityName, entityValue, i];
1120
+ }
1121
+ readNotationExp(xmlData, i) {
1122
+ i = skipWhitespace(xmlData, i);
1123
+ const startIndex = i;
1124
+ while (i < xmlData.length && !/\s/.test(xmlData[i])) {
1125
+ i++;
1126
+ }
1127
+ let notationName = xmlData.substring(startIndex, i);
1128
+ !this.suppressValidationErr && validateEntityName2(notationName, { xmlVersion: this.xmlVersion });
1129
+ i = skipWhitespace(xmlData, i);
1130
+ const identifierType = xmlData.substring(i, i + 6).toUpperCase();
1131
+ if (!this.suppressValidationErr && identifierType !== "SYSTEM" && identifierType !== "PUBLIC") {
1132
+ throw new Error(`Expected SYSTEM or PUBLIC, found "${identifierType}"`);
1133
+ }
1134
+ i += identifierType.length;
1135
+ i = skipWhitespace(xmlData, i);
1136
+ let publicIdentifier = null;
1137
+ let systemIdentifier = null;
1138
+ if (identifierType === "PUBLIC") {
1139
+ [i, publicIdentifier] = this.readIdentifierVal(xmlData, i, "publicIdentifier");
1140
+ i = skipWhitespace(xmlData, i);
1141
+ if (xmlData[i] === '"' || xmlData[i] === "'") {
1142
+ [i, systemIdentifier] = this.readIdentifierVal(xmlData, i, "systemIdentifier");
1143
+ }
1144
+ } else if (identifierType === "SYSTEM") {
1145
+ [i, systemIdentifier] = this.readIdentifierVal(xmlData, i, "systemIdentifier");
1146
+ if (!this.suppressValidationErr && !systemIdentifier) {
1147
+ throw new Error("Missing mandatory system identifier for SYSTEM notation");
1148
+ }
1149
+ }
1150
+ return { notationName, publicIdentifier, systemIdentifier, index: --i };
1151
+ }
1152
+ readIdentifierVal(xmlData, i, type) {
1153
+ let identifierVal = "";
1154
+ const startChar = xmlData[i];
1155
+ if (startChar !== '"' && startChar !== "'") {
1156
+ throw new Error(`Expected quoted string, found "${startChar}"`);
1157
+ }
1158
+ i++;
1159
+ const startIndex = i;
1160
+ while (i < xmlData.length && xmlData[i] !== startChar) {
1161
+ i++;
1162
+ }
1163
+ identifierVal = xmlData.substring(startIndex, i);
1164
+ if (xmlData[i] !== startChar) {
1165
+ throw new Error(`Unterminated ${type} value`);
1166
+ }
1167
+ i++;
1168
+ return [i, identifierVal];
1169
+ }
1170
+ readElementExp(xmlData, i) {
1171
+ i = skipWhitespace(xmlData, i);
1172
+ const startIndex = i;
1173
+ while (i < xmlData.length && !/\s/.test(xmlData[i])) {
1174
+ i++;
1175
+ }
1176
+ let elementName = xmlData.substring(startIndex, i);
1177
+ if (!this.suppressValidationErr && !qName(elementName, { xmlVersion: this.xmlVersion })) {
1178
+ throw new Error(`Invalid element name: "${elementName}"`);
1179
+ }
1180
+ i = skipWhitespace(xmlData, i);
1181
+ let contentModel = "";
1182
+ if (xmlData[i] === "E" && hasSeq(xmlData, "MPTY", i))
1183
+ i += 4;
1184
+ else if (xmlData[i] === "A" && hasSeq(xmlData, "NY", i))
1185
+ i += 2;
1186
+ else if (xmlData[i] === "(") {
1187
+ i++;
1188
+ const startIndex = i;
1189
+ while (i < xmlData.length && xmlData[i] !== ")") {
1190
+ i++;
1191
+ }
1192
+ contentModel = xmlData.substring(startIndex, i);
1193
+ if (xmlData[i] !== ")") {
1194
+ throw new Error("Unterminated content model");
1195
+ }
1196
+ } else if (!this.suppressValidationErr) {
1197
+ throw new Error(`Invalid Element Expression, found "${xmlData[i]}"`);
1198
+ }
1199
+ return {
1200
+ elementName,
1201
+ contentModel: contentModel.trim(),
1202
+ index: i
1203
+ };
1204
+ }
1205
+ readAttlistExp(xmlData, i) {
1206
+ i = skipWhitespace(xmlData, i);
1207
+ let startIndex = i;
1208
+ while (i < xmlData.length && !/\s/.test(xmlData[i])) {
1209
+ i++;
1210
+ }
1211
+ let elementName = xmlData.substring(startIndex, i);
1212
+ validateEntityName2(elementName, { xmlVersion: this.xmlVersion });
1213
+ i = skipWhitespace(xmlData, i);
1214
+ startIndex = i;
1215
+ while (i < xmlData.length && !/\s/.test(xmlData[i])) {
1216
+ i++;
1217
+ }
1218
+ let attributeName = xmlData.substring(startIndex, i);
1219
+ if (!validateEntityName2(attributeName, { xmlVersion: this.xmlVersion })) {
1220
+ throw new Error(`Invalid attribute name: "${attributeName}"`);
1221
+ }
1222
+ i = skipWhitespace(xmlData, i);
1223
+ let attributeType = "";
1224
+ if (xmlData.substring(i, i + 8).toUpperCase() === "NOTATION") {
1225
+ attributeType = "NOTATION";
1226
+ i += 8;
1227
+ i = skipWhitespace(xmlData, i);
1228
+ if (xmlData[i] !== "(") {
1229
+ throw new Error(`Expected '(', found "${xmlData[i]}"`);
1230
+ }
1231
+ i++;
1232
+ let allowedNotations = [];
1233
+ while (i < xmlData.length && xmlData[i] !== ")") {
1234
+ const startIndex = i;
1235
+ while (i < xmlData.length && xmlData[i] !== "|" && xmlData[i] !== ")") {
1236
+ i++;
1237
+ }
1238
+ let notation = xmlData.substring(startIndex, i);
1239
+ notation = notation.trim();
1240
+ if (!validateEntityName2(notation, { xmlVersion: this.xmlVersion })) {
1241
+ throw new Error(`Invalid notation name: "${notation}"`);
1242
+ }
1243
+ allowedNotations.push(notation);
1244
+ if (xmlData[i] === "|") {
1245
+ i++;
1246
+ i = skipWhitespace(xmlData, i);
1247
+ }
1248
+ }
1249
+ if (xmlData[i] !== ")") {
1250
+ throw new Error("Unterminated list of notations");
1251
+ }
1252
+ i++;
1253
+ attributeType += " (" + allowedNotations.join("|") + ")";
1254
+ } else {
1255
+ const startIndex = i;
1256
+ while (i < xmlData.length && !/\s/.test(xmlData[i])) {
1257
+ i++;
1258
+ }
1259
+ attributeType += xmlData.substring(startIndex, i);
1260
+ const validTypes = ["CDATA", "ID", "IDREF", "IDREFS", "ENTITY", "ENTITIES", "NMTOKEN", "NMTOKENS"];
1261
+ if (!this.suppressValidationErr && !validTypes.includes(attributeType.toUpperCase())) {
1262
+ throw new Error(`Invalid attribute type: "${attributeType}"`);
1263
+ }
1264
+ }
1265
+ i = skipWhitespace(xmlData, i);
1266
+ let defaultValue = "";
1267
+ if (xmlData.substring(i, i + 8).toUpperCase() === "#REQUIRED") {
1268
+ defaultValue = "#REQUIRED";
1269
+ i += 8;
1270
+ } else if (xmlData.substring(i, i + 7).toUpperCase() === "#IMPLIED") {
1271
+ defaultValue = "#IMPLIED";
1272
+ i += 7;
1273
+ } else {
1274
+ [i, defaultValue] = this.readIdentifierVal(xmlData, i, "ATTLIST");
1275
+ }
1276
+ return {
1277
+ elementName,
1278
+ attributeName,
1279
+ attributeType,
1280
+ defaultValue,
1281
+ index: i
1282
+ };
1283
+ }
1284
+ }
1285
+ var skipWhitespace = (data, index) => {
1286
+ while (index < data.length && /\s/.test(data[index])) {
1287
+ index++;
1288
+ }
1289
+ return index;
1290
+ };
1291
+ function hasSeq(data, seq, i) {
1292
+ for (let j = 0;j < seq.length; j++) {
1293
+ if (seq[j] !== data[i + j + 1])
1294
+ return false;
1295
+ }
1296
+ return true;
1297
+ }
1298
+ function validateEntityName2(name, xmlVersion) {
1299
+ if (qName(name, { xmlVersion }))
1300
+ return name;
1301
+ else
1302
+ throw new Error(`Invalid entity name ${name}`);
1303
+ }
1304
+
1305
+ // node_modules/anynum/digitTable.js
1306
+ var SCRIPT_ZEROS = [
1307
+ 48,
1308
+ 1632,
1309
+ 1776,
1310
+ 2406,
1311
+ 2534,
1312
+ 2662,
1313
+ 2790,
1314
+ 2918,
1315
+ 3046,
1316
+ 3174,
1317
+ 3302,
1318
+ 3430,
1319
+ 3558,
1320
+ 3664,
1321
+ 3792,
1322
+ 3872,
1323
+ 4160,
1324
+ 4240,
1325
+ 6112,
1326
+ 6160,
1327
+ 6470,
1328
+ 6608,
1329
+ 6784,
1330
+ 6800,
1331
+ 6992,
1332
+ 7088,
1333
+ 7232,
1334
+ 7248,
1335
+ 65296,
1336
+ 120782,
1337
+ 120792,
1338
+ 120802,
1339
+ 120812,
1340
+ 120822,
1341
+ 66720,
1342
+ 68912,
1343
+ 69734,
1344
+ 69872,
1345
+ 69942,
1346
+ 70096,
1347
+ 70384,
1348
+ 70736,
1349
+ 70864,
1350
+ 71248,
1351
+ 71360,
1352
+ 71472,
1353
+ 71904,
1354
+ 72016,
1355
+ 72688,
1356
+ 72784,
1357
+ 73040,
1358
+ 73120,
1359
+ 73552,
1360
+ 92768,
1361
+ 92864,
1362
+ 93008,
1363
+ 123200,
1364
+ 123632,
1365
+ 124144,
1366
+ 125264,
1367
+ 130032
1368
+ ];
1369
+ var NOT_DIGIT = 255;
1370
+ var HIGH_MAP = new Map;
1371
+ var LOW_MAX = 65535;
1372
+ var LOW_MIN = 1632;
1373
+ var TABLE_OFFSET = LOW_MIN;
1374
+ var TABLE_SIZE = LOW_MAX - LOW_MIN + 1;
1375
+ var TABLE = new Uint8Array(TABLE_SIZE).fill(NOT_DIGIT);
1376
+ for (const zero of SCRIPT_ZEROS) {
1377
+ for (let d = 0;d < 10; d++) {
1378
+ const cp = zero + d;
1379
+ if (cp <= LOW_MAX) {
1380
+ TABLE[cp - TABLE_OFFSET] = d;
1381
+ } else {
1382
+ HIGH_MAP.set(cp, d);
1383
+ }
1384
+ }
1385
+ }
1386
+
1387
+ // node_modules/anynum/anynum.js
1388
+ var CHAR_0 = 48;
1389
+ var CHAR_9 = 57;
1390
+ var CHAR_MINUS = 45;
1391
+ var MINUS_SET = new Set([8722, 65293, 65123]);
1392
+ function anynum(str) {
1393
+ if (typeof str !== "string")
1394
+ return str;
1395
+ const len = str.length;
1396
+ if (len === 0)
1397
+ return str;
1398
+ let firstHit = -1;
1399
+ for (let i = 0;i < len; i++) {
1400
+ const cc = str.charCodeAt(i);
1401
+ if (cc >= CHAR_0 && cc <= CHAR_9 || cc === CHAR_MINUS)
1402
+ continue;
1403
+ if (cc < TABLE_OFFSET) {
1404
+ if (MINUS_SET.has(cc)) {
1405
+ firstHit = i;
1406
+ break;
1407
+ }
1408
+ continue;
1409
+ }
1410
+ if (cc >= 55296 && cc <= 56319) {
1411
+ if (i + 1 < len) {
1412
+ const low = str.charCodeAt(i + 1);
1413
+ if (low >= 56320 && low <= 57343) {
1414
+ const cp = 65536 + (cc - 55296 << 10) + (low - 56320);
1415
+ if (HIGH_MAP.has(cp)) {
1416
+ firstHit = i;
1417
+ break;
1418
+ }
1419
+ }
1420
+ }
1421
+ continue;
1422
+ }
1423
+ if (TABLE[cc - TABLE_OFFSET] !== NOT_DIGIT || MINUS_SET.has(cc)) {
1424
+ firstHit = i;
1425
+ break;
1426
+ }
1427
+ }
1428
+ if (firstHit === -1)
1429
+ return str;
1430
+ const chars = [];
1431
+ if (firstHit > 0)
1432
+ chars.push(str.slice(0, firstHit));
1433
+ for (let i = firstHit;i < len; i++) {
1434
+ const cc = str.charCodeAt(i);
1435
+ if (cc >= CHAR_0 && cc <= CHAR_9 || cc === CHAR_MINUS) {
1436
+ chars.push(str[i]);
1437
+ continue;
1438
+ }
1439
+ if (cc < TABLE_OFFSET) {
1440
+ chars.push(MINUS_SET.has(cc) ? "-" : str[i]);
1441
+ continue;
1442
+ }
1443
+ if (cc >= 55296 && cc <= 56319) {
1444
+ if (i + 1 < len) {
1445
+ const low = str.charCodeAt(i + 1);
1446
+ if (low >= 56320 && low <= 57343) {
1447
+ const cp = 65536 + (cc - 55296 << 10) + (low - 56320);
1448
+ const d = HIGH_MAP.get(cp);
1449
+ if (d !== undefined) {
1450
+ chars.push(String.fromCharCode(d + 48));
1451
+ i++;
1452
+ continue;
1453
+ }
1454
+ }
1455
+ }
1456
+ chars.push(str[i]);
1457
+ continue;
1458
+ }
1459
+ if (MINUS_SET.has(cc)) {
1460
+ chars.push("-");
1461
+ continue;
1462
+ }
1463
+ const d = TABLE[cc - TABLE_OFFSET];
1464
+ chars.push(d !== NOT_DIGIT ? String.fromCharCode(d + 48) : str[i]);
1465
+ }
1466
+ return chars.join("");
1467
+ }
1468
+ var anynum_default = anynum;
1469
+
1470
+ // node_modules/strnum/strnum.js
1471
+ var hexRegex = /^[-+]?0x[a-fA-F0-9]+$/;
1472
+ var binRegex = /^0b[01]+$/;
1473
+ var octRegex = /^0o[0-7]+$/;
1474
+ var numRegex = /^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/;
1475
+ var consider = {
1476
+ hex: true,
1477
+ binary: false,
1478
+ octal: false,
1479
+ leadingZeros: true,
1480
+ decimalPoint: ".",
1481
+ eNotation: true,
1482
+ infinity: "original",
1483
+ unicode: false
1484
+ };
1485
+ function toNumber(str, options = {}) {
1486
+ options = Object.assign({}, consider, options);
1487
+ if (!str || typeof str !== "string")
1488
+ return str;
1489
+ let trimmedStr = str.trim();
1490
+ if (trimmedStr.length === 0)
1491
+ return str;
1492
+ else if (options.skipLike !== undefined && options.skipLike.test(trimmedStr))
1493
+ return str;
1494
+ else if (trimmedStr === "0")
1495
+ return 0;
1496
+ if (options.unicode) {
1497
+ trimmedStr = anynum_default(trimmedStr);
1498
+ if (trimmedStr === "0")
1499
+ return 0;
1500
+ }
1501
+ if (options.hex && hexRegex.test(trimmedStr)) {
1502
+ return parse_int(trimmedStr, 16);
1503
+ } else if (options.binary && binRegex.test(trimmedStr)) {
1504
+ return parse_int(trimmedStr, 2);
1505
+ } else if (options.octal && octRegex.test(trimmedStr)) {
1506
+ return parse_int(trimmedStr, 8);
1507
+ } else if (!isFinite(trimmedStr)) {
1508
+ const num = Number(trimmedStr);
1509
+ if (Number.isNaN(num))
1510
+ return str;
1511
+ return handleInfinity(str, num, options);
1512
+ } else if (trimmedStr.includes("e") || trimmedStr.includes("E")) {
1513
+ return resolveEnotation(str, trimmedStr, options);
1514
+ } else {
1515
+ const match = numRegex.exec(trimmedStr);
1516
+ if (match) {
1517
+ const sign = match[1] || "";
1518
+ const leadingZeros = match[2];
1519
+ let numTrimmedByZeros = trimZeros(match[3]);
1520
+ const decimalAdjacentToLeadingZeros = sign ? trimmedStr[leadingZeros.length + 1] === "." : trimmedStr[leadingZeros.length] === ".";
1521
+ if (!options.leadingZeros && (leadingZeros.length > 1 || leadingZeros.length === 1 && !decimalAdjacentToLeadingZeros)) {
1522
+ return str;
1523
+ } else {
1524
+ const num = Number(trimmedStr);
1525
+ const parsedStr = String(num);
1526
+ if (num === 0)
1527
+ return num;
1528
+ if (parsedStr.search(/[eE]/) !== -1) {
1529
+ if (options.eNotation)
1530
+ return num;
1531
+ else
1532
+ return str;
1533
+ } else if (trimmedStr.indexOf(".") !== -1) {
1534
+ if (parsedStr === "0")
1535
+ return num;
1536
+ else if (parsedStr === numTrimmedByZeros)
1537
+ return num;
1538
+ else if (parsedStr === `${sign}${numTrimmedByZeros}`)
1539
+ return num;
1540
+ else
1541
+ return str;
1542
+ }
1543
+ let n = leadingZeros ? numTrimmedByZeros : trimmedStr;
1544
+ if (leadingZeros) {
1545
+ return n === parsedStr || sign + n === parsedStr ? num : str;
1546
+ } else {
1547
+ return n === parsedStr || n === sign + parsedStr ? num : str;
1548
+ }
1549
+ }
1550
+ } else {
1551
+ return str;
1552
+ }
1553
+ }
1554
+ }
1555
+ var eNotationRegx = /^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;
1556
+ function resolveEnotation(str, trimmedStr, options) {
1557
+ if (!options.eNotation)
1558
+ return str;
1559
+ const notation = trimmedStr.match(eNotationRegx);
1560
+ if (notation) {
1561
+ let sign = notation[1] || "";
1562
+ const eChar = notation[3].indexOf("e") === -1 ? "E" : "e";
1563
+ const leadingZeros = notation[2];
1564
+ const eAdjacentToLeadingZeros = sign ? trimmedStr[leadingZeros.length + 1] === eChar : trimmedStr[leadingZeros.length] === eChar;
1565
+ if (leadingZeros.length > 1 && eAdjacentToLeadingZeros)
1566
+ return str;
1567
+ else if (leadingZeros.length === 1 && (notation[3].startsWith(`.${eChar}`) || notation[3][0] === eChar)) {
1568
+ return Number(trimmedStr);
1569
+ } else if (leadingZeros.length > 0) {
1570
+ if (options.leadingZeros && !eAdjacentToLeadingZeros) {
1571
+ return Number(trimmedStr);
1572
+ } else
1573
+ return str;
1574
+ } else {
1575
+ return Number(trimmedStr);
1576
+ }
1577
+ } else {
1578
+ return str;
1579
+ }
1580
+ }
1581
+ function trimZeros(numStr) {
1582
+ if (numStr && numStr.indexOf(".") !== -1) {
1583
+ let end = numStr.length;
1584
+ while (end > 0 && numStr.charCodeAt(end - 1) === 48)
1585
+ end--;
1586
+ numStr = numStr.slice(0, end);
1587
+ if (numStr === ".")
1588
+ numStr = "0";
1589
+ else if (numStr[0] === ".")
1590
+ numStr = "0" + numStr;
1591
+ else if (numStr[numStr.length - 1] === ".")
1592
+ numStr = numStr.substring(0, numStr.length - 1);
1593
+ return numStr;
1594
+ }
1595
+ return numStr;
1596
+ }
1597
+ function parse_int(numStr, base) {
1598
+ const str = numStr.trim();
1599
+ if (base === 2 || base === 8)
1600
+ numStr = str.substring(2);
1601
+ if (parseInt)
1602
+ return parseInt(numStr, base);
1603
+ else if (Number.parseInt)
1604
+ return Number.parseInt(numStr, base);
1605
+ else if (window && window.parseInt)
1606
+ return window.parseInt(numStr, base);
1607
+ else
1608
+ throw new Error("parseInt, Number.parseInt, window.parseInt are not supported");
1609
+ }
1610
+ function handleInfinity(str, num, options) {
1611
+ const isPositive = num === Infinity;
1612
+ switch (options.infinity.toLowerCase()) {
1613
+ case "null":
1614
+ return null;
1615
+ case "infinity":
1616
+ return num;
1617
+ case "string":
1618
+ return isPositive ? "Infinity" : "-Infinity";
1619
+ case "original":
1620
+ default:
1621
+ return str;
1622
+ }
1623
+ }
1624
+
1625
+ // node_modules/fast-xml-parser/src/ignoreAttributes.js
1626
+ function getIgnoreAttributesFn(ignoreAttributes) {
1627
+ if (typeof ignoreAttributes === "function") {
1628
+ return ignoreAttributes;
1629
+ }
1630
+ if (Array.isArray(ignoreAttributes)) {
1631
+ return (attrName) => {
1632
+ for (const pattern of ignoreAttributes) {
1633
+ if (typeof pattern === "string" && attrName === pattern) {
1634
+ return true;
1635
+ }
1636
+ if (pattern instanceof RegExp && pattern.test(attrName)) {
1637
+ return true;
1638
+ }
1639
+ }
1640
+ };
1641
+ }
1642
+ return () => false;
1643
+ }
1644
+
1645
+ // node_modules/path-expression-matcher/src/Expression.js
1646
+ class Expression {
1647
+ constructor(pattern, options = {}, data) {
1648
+ this.pattern = pattern;
1649
+ this.separator = options.separator || ".";
1650
+ this.segments = this._parse(pattern);
1651
+ this.data = data;
1652
+ this._hasDeepWildcard = this.segments.some((seg) => seg.type === "deep-wildcard");
1653
+ this._hasAttributeCondition = this.segments.some((seg) => seg.attrName !== undefined);
1654
+ this._hasPositionSelector = this.segments.some((seg) => seg.position !== undefined);
1655
+ }
1656
+ _parse(pattern) {
1657
+ const segments = [];
1658
+ let i = 0;
1659
+ let currentPart = "";
1660
+ while (i < pattern.length) {
1661
+ if (pattern[i] === this.separator) {
1662
+ if (i + 1 < pattern.length && pattern[i + 1] === this.separator) {
1663
+ if (currentPart.trim()) {
1664
+ segments.push(this._parseSegment(currentPart.trim()));
1665
+ currentPart = "";
1666
+ }
1667
+ segments.push({ type: "deep-wildcard" });
1668
+ i += 2;
1669
+ } else {
1670
+ if (currentPart.trim()) {
1671
+ segments.push(this._parseSegment(currentPart.trim()));
1672
+ }
1673
+ currentPart = "";
1674
+ i++;
1675
+ }
1676
+ } else {
1677
+ currentPart += pattern[i];
1678
+ i++;
1679
+ }
1680
+ }
1681
+ if (currentPart.trim()) {
1682
+ segments.push(this._parseSegment(currentPart.trim()));
1683
+ }
1684
+ return segments;
1685
+ }
1686
+ _parseSegment(part) {
1687
+ const segment = { type: "tag" };
1688
+ let bracketContent = null;
1689
+ let withoutBrackets = part;
1690
+ const bracketMatch = part.match(/^([^\[]+)(\[[^\]]*\])(.*)$/);
1691
+ if (bracketMatch) {
1692
+ withoutBrackets = bracketMatch[1] + bracketMatch[3];
1693
+ if (bracketMatch[2]) {
1694
+ const content = bracketMatch[2].slice(1, -1);
1695
+ if (content) {
1696
+ bracketContent = content;
1697
+ }
1698
+ }
1699
+ }
1700
+ let namespace = undefined;
1701
+ let tagAndPosition = withoutBrackets;
1702
+ if (withoutBrackets.includes("::")) {
1703
+ const nsIndex = withoutBrackets.indexOf("::");
1704
+ namespace = withoutBrackets.substring(0, nsIndex).trim();
1705
+ tagAndPosition = withoutBrackets.substring(nsIndex + 2).trim();
1706
+ if (!namespace) {
1707
+ throw new Error(`Invalid namespace in pattern: ${part}`);
1708
+ }
1709
+ }
1710
+ let tag = undefined;
1711
+ let positionMatch = null;
1712
+ if (tagAndPosition.includes(":")) {
1713
+ const colonIndex = tagAndPosition.lastIndexOf(":");
1714
+ const tagPart = tagAndPosition.substring(0, colonIndex).trim();
1715
+ const posPart = tagAndPosition.substring(colonIndex + 1).trim();
1716
+ const isPositionKeyword = ["first", "last", "odd", "even"].includes(posPart) || /^nth\(\d+\)$/.test(posPart);
1717
+ if (isPositionKeyword) {
1718
+ tag = tagPart;
1719
+ positionMatch = posPart;
1720
+ } else {
1721
+ tag = tagAndPosition;
1722
+ }
1723
+ } else {
1724
+ tag = tagAndPosition;
1725
+ }
1726
+ if (!tag) {
1727
+ throw new Error(`Invalid segment pattern: ${part}`);
1728
+ }
1729
+ segment.tag = tag;
1730
+ if (namespace) {
1731
+ segment.namespace = namespace;
1732
+ }
1733
+ if (bracketContent) {
1734
+ if (bracketContent.includes("=")) {
1735
+ const eqIndex = bracketContent.indexOf("=");
1736
+ segment.attrName = bracketContent.substring(0, eqIndex).trim();
1737
+ segment.attrValue = bracketContent.substring(eqIndex + 1).trim();
1738
+ } else {
1739
+ segment.attrName = bracketContent.trim();
1740
+ }
1741
+ }
1742
+ if (positionMatch) {
1743
+ const nthMatch = positionMatch.match(/^nth\((\d+)\)$/);
1744
+ if (nthMatch) {
1745
+ segment.position = "nth";
1746
+ segment.positionValue = parseInt(nthMatch[1], 10);
1747
+ } else {
1748
+ segment.position = positionMatch;
1749
+ }
1750
+ }
1751
+ return segment;
1752
+ }
1753
+ get length() {
1754
+ return this.segments.length;
1755
+ }
1756
+ hasDeepWildcard() {
1757
+ return this._hasDeepWildcard;
1758
+ }
1759
+ hasAttributeCondition() {
1760
+ return this._hasAttributeCondition;
1761
+ }
1762
+ hasPositionSelector() {
1763
+ return this._hasPositionSelector;
1764
+ }
1765
+ toString() {
1766
+ return this.pattern;
1767
+ }
1768
+ }
1769
+
1770
+ // node_modules/path-expression-matcher/src/ExpressionSet.js
1771
+ class ExpressionSet {
1772
+ constructor() {
1773
+ this._byDepthAndTag = new Map;
1774
+ this._wildcardByDepth = new Map;
1775
+ this._deepWildcards = [];
1776
+ this._deepByTerminalTag = new Map;
1777
+ this._patterns = new Set;
1778
+ this._sealed = false;
1779
+ }
1780
+ add(expression) {
1781
+ if (this._sealed) {
1782
+ throw new TypeError("ExpressionSet is sealed. Create a new ExpressionSet to add more expressions.");
1783
+ }
1784
+ if (this._patterns.has(expression.pattern))
1785
+ return this;
1786
+ this._patterns.add(expression.pattern);
1787
+ if (expression.hasDeepWildcard()) {
1788
+ const lastSeg = expression.segments[expression.segments.length - 1];
1789
+ if (lastSeg && lastSeg.type !== "deep-wildcard" && lastSeg.tag !== "*") {
1790
+ const tag = lastSeg.tag;
1791
+ if (!this._deepByTerminalTag.has(tag))
1792
+ this._deepByTerminalTag.set(tag, []);
1793
+ this._deepByTerminalTag.get(tag).push(expression);
1794
+ } else {
1795
+ this._deepWildcards.push(expression);
1796
+ }
1797
+ return this;
1798
+ }
1799
+ const depth = expression.length;
1800
+ const lastSeg = expression.segments[expression.segments.length - 1];
1801
+ const tag = lastSeg?.tag;
1802
+ if (!tag || tag === "*") {
1803
+ if (!this._wildcardByDepth.has(depth))
1804
+ this._wildcardByDepth.set(depth, []);
1805
+ this._wildcardByDepth.get(depth).push(expression);
1806
+ } else {
1807
+ const key = `${depth}:${tag}`;
1808
+ if (!this._byDepthAndTag.has(key))
1809
+ this._byDepthAndTag.set(key, []);
1810
+ this._byDepthAndTag.get(key).push(expression);
1811
+ }
1812
+ return this;
1813
+ }
1814
+ addAll(expressions) {
1815
+ for (const expr of expressions)
1816
+ this.add(expr);
1817
+ return this;
1818
+ }
1819
+ has(expression) {
1820
+ return this._patterns.has(expression.pattern);
1821
+ }
1822
+ get size() {
1823
+ return this._patterns.size;
1824
+ }
1825
+ seal() {
1826
+ this._sealed = true;
1827
+ return this;
1828
+ }
1829
+ get isSealed() {
1830
+ return this._sealed;
1831
+ }
1832
+ matchesAny(matcher) {
1833
+ return this.findMatch(matcher) !== null;
1834
+ }
1835
+ findMatch(matcher) {
1836
+ const depth = matcher.getDepth();
1837
+ const tag = matcher.getCurrentTag();
1838
+ const exactKey = `${depth}:${tag}`;
1839
+ const exactBucket = this._byDepthAndTag.get(exactKey);
1840
+ if (exactBucket) {
1841
+ for (let i = 0;i < exactBucket.length; i++) {
1842
+ if (matcher.matches(exactBucket[i]))
1843
+ return exactBucket[i];
1844
+ }
1845
+ }
1846
+ const wildcardBucket = this._wildcardByDepth.get(depth);
1847
+ if (wildcardBucket) {
1848
+ for (let i = 0;i < wildcardBucket.length; i++) {
1849
+ if (matcher.matches(wildcardBucket[i]))
1850
+ return wildcardBucket[i];
1851
+ }
1852
+ }
1853
+ const deepBucket = this._deepByTerminalTag.get(tag);
1854
+ if (deepBucket) {
1855
+ for (let i = 0;i < deepBucket.length; i++) {
1856
+ if (matcher.matches(deepBucket[i]))
1857
+ return deepBucket[i];
1858
+ }
1859
+ }
1860
+ for (let i = 0;i < this._deepWildcards.length; i++) {
1861
+ if (matcher.matches(this._deepWildcards[i]))
1862
+ return this._deepWildcards[i];
1863
+ }
1864
+ return null;
1865
+ }
1866
+ }
1867
+
1868
+ // node_modules/path-expression-matcher/src/Matcher.js
1869
+ class MatcherView {
1870
+ constructor(matcher) {
1871
+ this._matcher = matcher;
1872
+ }
1873
+ get separator() {
1874
+ return this._matcher.separator;
1875
+ }
1876
+ getCurrentTag() {
1877
+ const path = this._matcher.path;
1878
+ return path.length > 0 ? path[path.length - 1].tag : undefined;
1879
+ }
1880
+ getCurrentNamespace() {
1881
+ const path = this._matcher.path;
1882
+ return path.length > 0 ? path[path.length - 1].namespace : undefined;
1883
+ }
1884
+ getAttrValue(attrName) {
1885
+ const path = this._matcher.path;
1886
+ if (path.length === 0)
1887
+ return;
1888
+ return path[path.length - 1].values?.[attrName];
1889
+ }
1890
+ hasAttr(attrName) {
1891
+ const path = this._matcher.path;
1892
+ if (path.length === 0)
1893
+ return false;
1894
+ const current = path[path.length - 1];
1895
+ return current.values !== undefined && attrName in current.values;
1896
+ }
1897
+ getAnyParentAttr(attrName) {
1898
+ return this._matcher.getAnyParentAttr(attrName);
1899
+ }
1900
+ hasAnyParentAttr(attrName) {
1901
+ return this._matcher.hasAnyParentAttr(attrName);
1902
+ }
1903
+ getPosition() {
1904
+ const path = this._matcher.path;
1905
+ if (path.length === 0)
1906
+ return -1;
1907
+ return path[path.length - 1].position ?? 0;
1908
+ }
1909
+ getCounter() {
1910
+ const path = this._matcher.path;
1911
+ if (path.length === 0)
1912
+ return -1;
1913
+ return path[path.length - 1].counter ?? 0;
1914
+ }
1915
+ getIndex() {
1916
+ return this.getPosition();
1917
+ }
1918
+ getDepth() {
1919
+ return this._matcher.path.length;
1920
+ }
1921
+ toString(separator, includeNamespace = true) {
1922
+ return this._matcher.toString(separator, includeNamespace);
1923
+ }
1924
+ toArray() {
1925
+ return this._matcher.path.map((n) => n.tag);
1926
+ }
1927
+ matches(expression) {
1928
+ return this._matcher.matches(expression);
1929
+ }
1930
+ matchesAny(exprSet) {
1931
+ return exprSet.matchesAny(this._matcher);
1932
+ }
1933
+ }
1934
+
1935
+ class Matcher {
1936
+ constructor(options = {}) {
1937
+ this.separator = options.separator || ".";
1938
+ this.path = [];
1939
+ this.siblingStacks = [];
1940
+ this._pathStringCache = null;
1941
+ this._view = new MatcherView(this);
1942
+ this._keptAttrs = [];
1943
+ }
1944
+ push(tagName, attrValues = null, namespace = null, options = null) {
1945
+ this._pathStringCache = null;
1946
+ if (this.path.length > 0) {
1947
+ this.path[this.path.length - 1].values = undefined;
1948
+ }
1949
+ const currentLevel = this.path.length;
1950
+ let level = this.siblingStacks[currentLevel];
1951
+ if (!level) {
1952
+ level = { counts: new Map, total: 0 };
1953
+ this.siblingStacks[currentLevel] = level;
1954
+ }
1955
+ const siblingKey = namespace ? `${namespace}:${tagName}` : tagName;
1956
+ const counter = level.counts.get(siblingKey) || 0;
1957
+ const position = level.total;
1958
+ level.counts.set(siblingKey, counter + 1);
1959
+ level.total++;
1960
+ const node = {
1961
+ tag: tagName,
1962
+ position,
1963
+ counter
1964
+ };
1965
+ if (namespace !== null && namespace !== undefined) {
1966
+ node.namespace = namespace;
1967
+ }
1968
+ if (attrValues !== null && attrValues !== undefined) {
1969
+ node.values = attrValues;
1970
+ }
1971
+ this.path.push(node);
1972
+ const depth = this.path.length;
1973
+ const keep = options !== null ? options.keep : null;
1974
+ if (keep !== null && keep !== undefined && keep.length > 0 && attrValues) {
1975
+ for (let i = 0;i < keep.length; i++) {
1976
+ const name = keep[i];
1977
+ if (attrValues[name] !== undefined) {
1978
+ this._keptAttrs.push({ depth, name, value: attrValues[name] });
1979
+ }
1980
+ }
1981
+ }
1982
+ }
1983
+ pop() {
1984
+ if (this.path.length === 0)
1985
+ return;
1986
+ this._pathStringCache = null;
1987
+ const node = this.path.pop();
1988
+ if (this.siblingStacks.length > this.path.length + 1) {
1989
+ this.siblingStacks.length = this.path.length + 1;
1990
+ }
1991
+ const poppedDepth = this.path.length + 1;
1992
+ while (this._keptAttrs.length > 0 && this._keptAttrs[this._keptAttrs.length - 1].depth >= poppedDepth) {
1993
+ this._keptAttrs.pop();
1994
+ }
1995
+ return node;
1996
+ }
1997
+ updateCurrent(attrValues) {
1998
+ if (this.path.length > 0) {
1999
+ const current = this.path[this.path.length - 1];
2000
+ if (attrValues !== null && attrValues !== undefined) {
2001
+ current.values = attrValues;
2002
+ }
2003
+ }
2004
+ }
2005
+ getCurrentTag() {
2006
+ return this.path.length > 0 ? this.path[this.path.length - 1].tag : undefined;
2007
+ }
2008
+ getCurrentNamespace() {
2009
+ return this.path.length > 0 ? this.path[this.path.length - 1].namespace : undefined;
2010
+ }
2011
+ getAttrValue(attrName) {
2012
+ if (this.path.length === 0)
2013
+ return;
2014
+ return this.path[this.path.length - 1].values?.[attrName];
2015
+ }
2016
+ hasAttr(attrName) {
2017
+ if (this.path.length === 0)
2018
+ return false;
2019
+ const current = this.path[this.path.length - 1];
2020
+ return current.values !== undefined && attrName in current.values;
2021
+ }
2022
+ getAnyParentAttr(attrName) {
2023
+ const kept = this._keptAttrs;
2024
+ for (let i = kept.length - 1;i >= 0; i--) {
2025
+ if (kept[i].name === attrName)
2026
+ return kept[i].value;
2027
+ }
2028
+ return;
2029
+ }
2030
+ hasAnyParentAttr(attrName) {
2031
+ const kept = this._keptAttrs;
2032
+ for (let i = kept.length - 1;i >= 0; i--) {
2033
+ if (kept[i].name === attrName)
2034
+ return true;
2035
+ }
2036
+ return false;
2037
+ }
2038
+ getPosition() {
2039
+ if (this.path.length === 0)
2040
+ return -1;
2041
+ return this.path[this.path.length - 1].position ?? 0;
2042
+ }
2043
+ getCounter() {
2044
+ if (this.path.length === 0)
2045
+ return -1;
2046
+ return this.path[this.path.length - 1].counter ?? 0;
2047
+ }
2048
+ getIndex() {
2049
+ return this.getPosition();
2050
+ }
2051
+ getDepth() {
2052
+ return this.path.length;
2053
+ }
2054
+ toString(separator, includeNamespace = true) {
2055
+ const sep = separator || this.separator;
2056
+ const isDefault = sep === this.separator && includeNamespace === true;
2057
+ if (isDefault) {
2058
+ if (this._pathStringCache !== null) {
2059
+ return this._pathStringCache;
2060
+ }
2061
+ const result = this.path.map((n) => n.namespace ? `${n.namespace}:${n.tag}` : n.tag).join(sep);
2062
+ this._pathStringCache = result;
2063
+ return result;
2064
+ }
2065
+ return this.path.map((n) => includeNamespace && n.namespace ? `${n.namespace}:${n.tag}` : n.tag).join(sep);
2066
+ }
2067
+ toArray() {
2068
+ return this.path.map((n) => n.tag);
2069
+ }
2070
+ reset() {
2071
+ this._pathStringCache = null;
2072
+ this.path = [];
2073
+ this.siblingStacks = [];
2074
+ this._keptAttrs = [];
2075
+ }
2076
+ matches(expression) {
2077
+ const segments = expression.segments;
2078
+ if (segments.length === 0) {
2079
+ return false;
2080
+ }
2081
+ if (expression.hasDeepWildcard()) {
2082
+ return this._matchWithDeepWildcard(segments);
2083
+ }
2084
+ return this._matchSimple(segments);
2085
+ }
2086
+ _matchSimple(segments) {
2087
+ if (this.path.length !== segments.length) {
2088
+ return false;
2089
+ }
2090
+ for (let i = 0;i < segments.length; i++) {
2091
+ if (!this._matchSegment(segments[i], this.path[i], i === this.path.length - 1)) {
2092
+ return false;
2093
+ }
2094
+ }
2095
+ return true;
2096
+ }
2097
+ _matchWithDeepWildcard(segments) {
2098
+ let pathIdx = this.path.length - 1;
2099
+ let segIdx = segments.length - 1;
2100
+ while (segIdx >= 0 && pathIdx >= 0) {
2101
+ const segment = segments[segIdx];
2102
+ if (segment.type === "deep-wildcard") {
2103
+ segIdx--;
2104
+ if (segIdx < 0) {
2105
+ return true;
2106
+ }
2107
+ const nextSeg = segments[segIdx];
2108
+ let found = false;
2109
+ for (let i = pathIdx;i >= 0; i--) {
2110
+ if (this._matchSegment(nextSeg, this.path[i], i === this.path.length - 1)) {
2111
+ pathIdx = i - 1;
2112
+ segIdx--;
2113
+ found = true;
2114
+ break;
2115
+ }
2116
+ }
2117
+ if (!found) {
2118
+ return false;
2119
+ }
2120
+ } else {
2121
+ if (!this._matchSegment(segment, this.path[pathIdx], pathIdx === this.path.length - 1)) {
2122
+ return false;
2123
+ }
2124
+ pathIdx--;
2125
+ segIdx--;
2126
+ }
2127
+ }
2128
+ return segIdx < 0;
2129
+ }
2130
+ _matchSegment(segment, node, isCurrentNode) {
2131
+ if (segment.tag !== "*" && segment.tag !== node.tag) {
2132
+ return false;
2133
+ }
2134
+ if (segment.namespace !== undefined) {
2135
+ if (segment.namespace !== "*" && segment.namespace !== node.namespace) {
2136
+ return false;
2137
+ }
2138
+ }
2139
+ if (segment.attrName !== undefined) {
2140
+ if (!isCurrentNode) {
2141
+ return false;
2142
+ }
2143
+ if (!node.values || !(segment.attrName in node.values)) {
2144
+ return false;
2145
+ }
2146
+ if (segment.attrValue !== undefined) {
2147
+ if (String(node.values[segment.attrName]) !== String(segment.attrValue)) {
2148
+ return false;
2149
+ }
2150
+ }
2151
+ }
2152
+ if (segment.position !== undefined) {
2153
+ if (!isCurrentNode) {
2154
+ return false;
2155
+ }
2156
+ const counter = node.counter ?? 0;
2157
+ if (segment.position === "first" && counter !== 0) {
2158
+ return false;
2159
+ } else if (segment.position === "odd" && counter % 2 !== 1) {
2160
+ return false;
2161
+ } else if (segment.position === "even" && counter % 2 !== 0) {
2162
+ return false;
2163
+ } else if (segment.position === "nth" && counter !== segment.positionValue) {
2164
+ return false;
2165
+ }
2166
+ }
2167
+ return true;
2168
+ }
2169
+ matchesAny(exprSet) {
2170
+ return exprSet.matchesAny(this);
2171
+ }
2172
+ snapshot() {
2173
+ return {
2174
+ path: this.path.map((node) => ({ ...node })),
2175
+ siblingStacks: this.siblingStacks.map((level) => level ? { counts: new Map(level.counts), total: level.total } : level),
2176
+ keptAttrs: this._keptAttrs.map((entry) => ({ ...entry }))
2177
+ };
2178
+ }
2179
+ restore(snapshot) {
2180
+ this._pathStringCache = null;
2181
+ this.path = snapshot.path.map((node) => ({ ...node }));
2182
+ this.siblingStacks = snapshot.siblingStacks.map((level) => level ? { counts: new Map(level.counts), total: level.total } : level);
2183
+ this._keptAttrs = (snapshot.keptAttrs || []).map((entry) => ({ ...entry }));
2184
+ }
2185
+ readOnly() {
2186
+ return this._view;
2187
+ }
2188
+ }
2189
+
2190
+ // node_modules/is-unsafe/src/contexts/html.js
2191
+ var HTML_PATTERNS = [
2192
+ {
2193
+ id: "html-script-open",
2194
+ description: "<script opening tag",
2195
+ pattern: /<script[\s>/]/i
2196
+ },
2197
+ {
2198
+ id: "html-script-close",
2199
+ description: "</script closing tag",
2200
+ pattern: /<\/script[\s>]/i
2201
+ },
2202
+ {
2203
+ id: "html-javascript-protocol",
2204
+ description: "javascript: URI scheme (with optional whitespace/encoding)",
2205
+ pattern: /j[\t\n\r ]*a[\t\n\r ]*v[\t\n\r ]*a[\t\n\r ]*s[\t\n\r ]*c[\t\n\r ]*r[\t\n\r ]*i[\t\n\r ]*p[\t\n\r ]*t[\t\n\r ]*:/i
2206
+ },
2207
+ {
2208
+ id: "html-vbscript-protocol",
2209
+ description: "vbscript: URI scheme",
2210
+ pattern: /vbscript[\t\n\r ]*:/i
2211
+ },
2212
+ {
2213
+ id: "html-data-html",
2214
+ description: "data:text/html URI \u2014 can execute scripts in browsers",
2215
+ pattern: /data[\t\n\r ]*:[\t\n\r ]*text\/html/i
2216
+ },
2217
+ {
2218
+ id: "html-data-xhtml",
2219
+ description: "data:application/xhtml+xml URI",
2220
+ pattern: /data[\t\n\r ]*:[\t\n\r ]*application\/xhtml/i
2221
+ },
2222
+ {
2223
+ id: "html-data-svg",
2224
+ description: "data:image/svg+xml URI \u2014 can execute scripts",
2225
+ pattern: /data[\t\n\r ]*:[\t\n\r ]*image\/svg\+xml/i
2226
+ },
2227
+ {
2228
+ id: "html-inline-event-handler",
2229
+ description: "Inline event handler attributes: onclick=, onerror=, onload=, etc.",
2230
+ pattern: /\bon\w{1,30}\s*=/i
2231
+ },
2232
+ {
2233
+ id: "html-entity-obfuscated-script",
2234
+ description: "HTML-entity-encoded <script (e.g. &#x3C;script or &lt;script)",
2235
+ pattern: /(?:&#x0*3[Cc];?|&#0*60;?|&lt;)\s*script/i
2236
+ },
2237
+ {
2238
+ id: "html-entity-obfuscated-javascript",
2239
+ description: 'HTML-entity-encoded javascript: (partial \u2014 catches common &#106; or &#x6a; for "j")',
2240
+ pattern: /(?:&#x0*6[Aa];?|&#0*106;?)\s*(?:&#x0*61;?|a)[\s\S]{0,80}script\s*:/i
2241
+ },
2242
+ {
2243
+ id: "html-style-expression",
2244
+ description: "CSS expression() \u2014 IE-era code execution in style attributes",
2245
+ pattern: /style[\s\S]{0,20}expression\s*\(/i
2246
+ },
2247
+ {
2248
+ id: "html-object-embed",
2249
+ description: "<object or <embed tags that can load active content",
2250
+ pattern: /<(?:object|embed)[\s>/]/i
2251
+ },
2252
+ {
2253
+ id: "html-base-tag",
2254
+ description: "<base href= \u2014 can hijack all relative URLs on a page",
2255
+ pattern: /<base[\s>]/i
2256
+ },
2257
+ {
2258
+ id: "html-meta-refresh",
2259
+ description: '<meta http-equiv="refresh" \u2014 can redirect users',
2260
+ pattern: /<meta[\s\S]{0,40}http-equiv[\s\S]{0,20}refresh/i
2261
+ },
2262
+ {
2263
+ id: "html-srcdoc",
2264
+ description: "srcdoc= attribute on iframes \u2014 embeds HTML that can run scripts",
2265
+ pattern: /srcdoc\s*=/i
2266
+ },
2267
+ {
2268
+ id: "html-iframe",
2269
+ description: "<iframe tag",
2270
+ pattern: /<iframe[\s>/]/i
2271
+ },
2272
+ {
2273
+ id: "html-form",
2274
+ description: "<form tag \u2014 can be used for phishing / credential harvesting injection",
2275
+ pattern: /<form[\s>/]/i
2276
+ }
2277
+ ];
2278
+ var html_default = HTML_PATTERNS;
2279
+ // node_modules/is-unsafe/src/contexts/xml.js
2280
+ var XML_PATTERNS = [
2281
+ {
2282
+ id: "xml-cdata-injection",
2283
+ description: "CDATA section injection: <![CDATA[ breaks out of text node context",
2284
+ pattern: /<!\[CDATA\[/i
2285
+ },
2286
+ {
2287
+ id: "xml-cdata-close",
2288
+ description: "CDATA close sequence: ]]> can terminate an enclosing CDATA section",
2289
+ pattern: /\]\]>/
2290
+ },
2291
+ {
2292
+ id: "xml-processing-instruction",
2293
+ description: "XML processing instruction: <?xml-stylesheet or <?php etc.",
2294
+ pattern: /<\?(?:xml[\- ]|php|asp)/i
2295
+ },
2296
+ {
2297
+ id: "xml-doctype-injection",
2298
+ description: "DOCTYPE declaration embedded in content \u2014 can define entities",
2299
+ pattern: /<!DOCTYPE(?:[\s[]|$)/i
2300
+ },
2301
+ {
2302
+ id: "xml-entity-system",
2303
+ description: "SYSTEM keyword \u2014 used in external entity declarations (XXE)",
2304
+ pattern: /\bSYSTEM\s+["']/i
2305
+ },
2306
+ {
2307
+ id: "xml-entity-public",
2308
+ description: "PUBLIC keyword \u2014 used in external entity declarations (XXE)",
2309
+ pattern: /\bPUBLIC\s+["']/i
2310
+ },
2311
+ {
2312
+ id: "xml-entity-declaration",
2313
+ description: "<!ENTITY declaration \u2014 defines entities, potential XXE or entity expansion",
2314
+ pattern: /<!ENTITY[\s%]/i
2315
+ },
2316
+ {
2317
+ id: "xml-billion-laughs",
2318
+ description: "Entity reference chaining / billion laughs: repeated &eX; style references",
2319
+ pattern: /(?:&\w{1,20};){3,}/
2320
+ },
2321
+ {
2322
+ id: "xml-namespace-confusion",
2323
+ description: "xmlns: attribute injection \u2014 can redefine namespaces to confuse parsers",
2324
+ pattern: /\bxmlns(?::\w{1,40})?\s*=/i
2325
+ },
2326
+ {
2327
+ id: "xml-comment-injection",
2328
+ description: "<!-- comment injection \u2014 can hide content from some parsers",
2329
+ pattern: /<!--/
2330
+ },
2331
+ {
2332
+ id: "xml-comment-close",
2333
+ description: "--> closes an enclosing XML comment",
2334
+ pattern: /-->/
2335
+ },
2336
+ {
2337
+ id: "xml-pi-close",
2338
+ description: "?> closes an enclosing processing instruction",
2339
+ pattern: /\?>/
2340
+ }
2341
+ ];
2342
+ var xml_default = XML_PATTERNS;
2343
+ // node_modules/is-unsafe/src/contexts/svg.js
2344
+ var SVG_PATTERNS = [
2345
+ {
2346
+ id: "svg-script-element",
2347
+ description: "<script element inside SVG executes JavaScript",
2348
+ pattern: /<script[\s>/]/i
2349
+ },
2350
+ {
2351
+ id: "svg-xlink-href-javascript",
2352
+ description: "xlink:href with javascript: \u2014 classic SVG XSS via <a> or <use>",
2353
+ pattern: /xlink\s*:\s*href\s*=\s*["']?\s*javascript\s*:/i
2354
+ },
2355
+ {
2356
+ id: "svg-href-javascript",
2357
+ description: "href= with javascript: in SVG context (<a>, <animate>, etc.)",
2358
+ pattern: /href\s*=\s*["']?\s*javascript\s*:/i
2359
+ },
2360
+ {
2361
+ id: "svg-foreignobject",
2362
+ description: "<foreignObject embeds HTML inside SVG \u2014 can execute scripts",
2363
+ pattern: /<foreignObject[\s>/]/i
2364
+ },
2365
+ {
2366
+ id: "svg-use-external",
2367
+ description: "<use xlink:href or href pointing to external resource (non-fragment URL)",
2368
+ pattern: /<use[\s\S]{0,60}(?:xlink\s*:\s*)?href\s*=\s*(?:["'][^#]|[^"'#\s>])/i
2369
+ },
2370
+ {
2371
+ id: "svg-animate-href",
2372
+ description: '<animate attributeName="href" \u2014 can dynamically change href to javascript:',
2373
+ pattern: /<animate[\s\S]{0,80}attributeName\s*=\s*["'][\s]*href["']/i
2374
+ },
2375
+ {
2376
+ id: "svg-animate-xlinkhref",
2377
+ description: '<animate attributeName="xlink:href"',
2378
+ pattern: /<animate[\s\S]{0,80}attributeName\s*=\s*["'][\s]*xlink\s*:\s*href["']/i
2379
+ },
2380
+ {
2381
+ id: "svg-set-javascript",
2382
+ description: '<set to="javascript:..." \u2014 sets an attribute to a javascript: URI',
2383
+ pattern: /<set[\s\S]{0,80}to\s*=\s*["']?\s*javascript\s*:/i
2384
+ },
2385
+ {
2386
+ id: "svg-event-handler",
2387
+ description: "SVG-specific event handler attributes: onload=, onerror=, onactivate=, etc.",
2388
+ pattern: /\bon(?:load|error|activate|begin|end|repeat|focus|blur|click|mouse\w{1,20}|key\w{1,20})\s*=/i
2389
+ },
2390
+ {
2391
+ id: "svg-handler-generic",
2392
+ description: "Generic on* handler catch-all for SVG attributes",
2393
+ pattern: /\bon\w{1,30}\s*=/i
2394
+ },
2395
+ {
2396
+ id: "svg-filter-feimage",
2397
+ description: "<feImage href= \u2014 filter primitive that can load external resources",
2398
+ pattern: /<feImage[\s\S]{0,80}(?:xlink\s*:\s*)?href\s*=/i
2399
+ },
2400
+ {
2401
+ id: "svg-image-external",
2402
+ description: "<image xlink:href with http/https or javascript protocol",
2403
+ pattern: /<image[\s\S]{0,80}(?:xlink\s*:\s*)?href\s*=\s*["']?\s*(?:https?|javascript)\s*:/i
2404
+ },
2405
+ {
2406
+ id: "svg-style-javascript",
2407
+ description: "style= attribute containing javascript: (e.g. background:url(javascript:...))",
2408
+ pattern: /style\s*=[\s\S]{0,60}javascript\s*:/i
2409
+ }
2410
+ ];
2411
+ var svg_default = SVG_PATTERNS;
2412
+
2413
+ // node_modules/is-unsafe/src/contexts/sql.js
2414
+ var SQL_PATTERNS = [
2415
+ {
2416
+ id: "sql-block-comment-open",
2417
+ description: "SQL block comment open: /* ... */ \u2014 unusual in legitimate user text",
2418
+ pattern: /\/\*/
2419
+ },
2420
+ {
2421
+ id: "sql-union-select",
2422
+ description: "UNION SELECT \u2014 most common SQL injection aggregation attack",
2423
+ pattern: /\bUNION\s{1,20}(?:ALL\s{1,20})?SELECT\b/i
2424
+ },
2425
+ {
2426
+ id: "sql-drop-table",
2427
+ description: "DROP TABLE \u2014 destructive DDL injection",
2428
+ pattern: /\bDROP\s{1,20}TABLE\b/i
2429
+ },
2430
+ {
2431
+ id: "sql-drop-database",
2432
+ description: "DROP DATABASE \u2014 destructive DDL injection",
2433
+ pattern: /\bDROP\s{1,20}DATABASE\b/i
2434
+ },
2435
+ {
2436
+ id: "sql-insert-into",
2437
+ description: "INSERT INTO \u2014 data injection",
2438
+ pattern: /\bINSERT\s{1,20}INTO\b/i
2439
+ },
2440
+ {
2441
+ id: "sql-delete-from",
2442
+ description: "DELETE FROM \u2014 data deletion injection",
2443
+ pattern: /\bDELETE\s{1,20}FROM\b/i
2444
+ },
2445
+ {
2446
+ id: "sql-update-set",
2447
+ description: "UPDATE ... SET \u2014 data modification injection",
2448
+ pattern: /\bUPDATE\b[\s\S]{1,60}\bSET\b/i
2449
+ },
2450
+ {
2451
+ id: "sql-exec-xp",
2452
+ description: "EXEC xp_ \u2014 MSSQL extended stored procedure execution",
2453
+ pattern: /\bEXEC(?:UTE)?\s{1,20}xp_/i
2454
+ },
2455
+ {
2456
+ id: "sql-tautology-string",
2457
+ description: `Classic string tautology: ' OR '1'='1 or " OR "1"="1"`,
2458
+ pattern: /'\s{0,10}OR\s{0,10}'[^']{0,20}'\s*=\s*'[^']{0,20}/i
2459
+ },
2460
+ {
2461
+ id: "sql-tautology-numeric",
2462
+ description: "Numeric tautology: OR 1=1",
2463
+ pattern: /\bOR\s{1,10}1\s*=\s*1\b/i
2464
+ },
2465
+ {
2466
+ id: "sql-always-true-zero",
2467
+ description: "Numeric tautology: OR 0=0",
2468
+ pattern: /\bOR\s{1,10}0\s*=\s*0\b/i
2469
+ },
2470
+ {
2471
+ id: "sql-sleep-benchmark",
2472
+ description: "Time-based blind injection: SLEEP() or BENCHMARK()",
2473
+ pattern: /\b(?:SLEEP|BENCHMARK)\s*\(/i
2474
+ },
2475
+ {
2476
+ id: "sql-waitfor-delay",
2477
+ description: "MSSQL time-based blind injection: WAITFOR DELAY",
2478
+ pattern: /\bWAITFOR\s{1,20}DELAY\b/i
2479
+ },
2480
+ {
2481
+ id: "sql-char-function",
2482
+ description: "CHAR() function \u2014 used to obfuscate injected strings",
2483
+ pattern: /\bCHAR\s*\(\s*\d{1,3}/i
2484
+ },
2485
+ {
2486
+ id: "sql-information-schema",
2487
+ description: "INFORMATION_SCHEMA \u2014 reconnaissance query for table/column enumeration",
2488
+ pattern: /\bINFORMATION_SCHEMA\b/i
2489
+ }
2490
+ ];
2491
+ var sql_default = SQL_PATTERNS;
2492
+
2493
+ // node_modules/is-unsafe/src/contexts/shell.js
2494
+ var SHELL_PATTERNS = [
2495
+ {
2496
+ id: "shell-path-traversal-unix",
2497
+ description: "Unix path traversal: ../ \u2014 climbing the directory tree",
2498
+ pattern: /\.\.\//
2499
+ },
2500
+ {
2501
+ id: "shell-path-traversal-windows",
2502
+ description: "Windows path traversal: ..\\ \u2014 climbing the directory tree",
2503
+ pattern: /\.\.\\/
2504
+ },
2505
+ {
2506
+ id: "shell-path-traversal-encoded",
2507
+ description: "URL-encoded path traversal: %2e%2e or %2f variants",
2508
+ pattern: /%2e%2e|%2f\.\.|\.\.%2f/i
2509
+ },
2510
+ {
2511
+ id: "shell-null-byte",
2512
+ description: "Null byte injection: \\x00 or %00 \u2014 truncates strings in C-backed functions",
2513
+ pattern: /\x00|%00/
2514
+ },
2515
+ {
2516
+ id: "shell-semicolon",
2517
+ description: "Semicolon command separator: cmd1; cmd2",
2518
+ pattern: /;/
2519
+ },
2520
+ {
2521
+ id: "shell-pipe",
2522
+ description: "Pipe operator: cmd1 | cmd2",
2523
+ pattern: /\|/
2524
+ },
2525
+ {
2526
+ id: "shell-and-operator",
2527
+ description: "AND operator: cmd1 && cmd2",
2528
+ pattern: /&&/
2529
+ },
2530
+ {
2531
+ id: "shell-or-operator",
2532
+ description: "OR operator: cmd1 || cmd2",
2533
+ pattern: /\|\|/
2534
+ },
2535
+ {
2536
+ id: "shell-backtick",
2537
+ description: "Backtick command substitution: `cmd`",
2538
+ pattern: /`/
2539
+ },
2540
+ {
2541
+ id: "shell-dollar-paren",
2542
+ description: "Dollar-paren command substitution: $(cmd)",
2543
+ pattern: /\$\(/
2544
+ },
2545
+ {
2546
+ id: "shell-dollar-brace",
2547
+ description: "Dollar-brace variable expansion: ${var} \u2014 can be abused for injection",
2548
+ pattern: /\$\{/
2549
+ },
2550
+ {
2551
+ id: "shell-redirect-out",
2552
+ description: "Output redirection: cmd > file or cmd >> file",
2553
+ pattern: />{1,2}/
2554
+ },
2555
+ {
2556
+ id: "shell-redirect-in",
2557
+ description: "Input redirection: cmd < file",
2558
+ pattern: /</
2559
+ },
2560
+ {
2561
+ id: "shell-newline-injection",
2562
+ description: "Newline injection: \\n or \\r \u2014 can inject new shell commands",
2563
+ pattern: /[\n\r]/
2564
+ },
2565
+ {
2566
+ id: "shell-glob-star",
2567
+ description: "Glob expansion: * or ? \u2014 can expand to unintended files",
2568
+ pattern: /[/\\][*?]/
2569
+ },
2570
+ {
2571
+ id: "shell-absolute-root",
2572
+ description: "Absolute root path injection: string starting with / or \\ (Windows UNC)",
2573
+ pattern: /^(?:\/|\\\\)/
2574
+ },
2575
+ {
2576
+ id: "shell-windows-drive",
2577
+ description: "Windows drive letter path injection: C:\\ or D:/",
2578
+ pattern: /^[a-zA-Z]:[/\\]/
2579
+ },
2580
+ {
2581
+ id: "shell-curl-wget",
2582
+ description: "curl/wget with URL or flags \u2014 can exfiltrate data or download payloads",
2583
+ pattern: /\b(?:curl|wget)\s+(?:https?:\/\/|ftp:\/\/|-)/i
2584
+ }
2585
+ ];
2586
+ var shell_default = SHELL_PATTERNS;
2587
+
2588
+ // node_modules/is-unsafe/src/contexts/redos.js
2589
+ var REDOS_PATTERNS = [
2590
+ {
2591
+ id: "redos-nested-quantifier-plus",
2592
+ description: "Nested + quantifier inside a group with outer quantifier: (a+)+, (.+b)*, etc.",
2593
+ pattern: /\([^)]*\+[^)]*\)[+*]/
2594
+ },
2595
+ {
2596
+ id: "redos-nested-quantifier-star",
2597
+ description: "Nested * quantifier: (a*)* or (a*)+ \u2014 catastrophic backtracking",
2598
+ pattern: /\([^)]*\*[^)]*\)[*+]/
2599
+ },
2600
+ {
2601
+ id: "redos-nested-groups",
2602
+ description: "Doubly nested quantified groups: ((a+)+) \u2014 guaranteed catastrophic",
2603
+ pattern: /\(\([^)]{0,40}\)[+*]\)[+*]/
2604
+ },
2605
+ {
2606
+ id: "redos-alternation-overlap",
2607
+ description: "Overlapping alternation under quantifier: (a|a)+ \u2014 ambiguous NFA paths",
2608
+ pattern: /\(([^|()]{1,20})\|(?:\1)(?:\|[^|()]{1,20}){0,5}\)[+*?]{1,2}/
2609
+ },
2610
+ {
2611
+ id: "redos-star-plus-concat",
2612
+ description: "(x*x)+ pattern \u2014 triggers super-linear backtracking",
2613
+ pattern: /\([^)]{0,10}\*[^)]{0,10}\)[+*]/
2614
+ },
2615
+ {
2616
+ id: "redos-dot-star-greedy",
2617
+ description: "(.*){n,} or (.+){n,} \u2014 repeated greedy dot quantifiers",
2618
+ pattern: /\(\.[*+]\)\{?\d/
2619
+ },
2620
+ {
2621
+ id: "redos-large-repetition",
2622
+ description: "Very large fixed or range repetition count {1000,} or {1000,n} \u2014 denial of service via backtracking",
2623
+ pattern: /\{\d{4,}(?:,\d*)?\}/
2624
+ },
2625
+ {
2626
+ id: "redos-catastrophic-alternation",
2627
+ description: "Long alternation with many similar branches \u2014 polynomial backtracking risk",
2628
+ pattern: /\([^)]{0,200}(?:\|[^|)]{0,50}){9,}\)/
2629
+ }
2630
+ ];
2631
+ var redos_default = REDOS_PATTERNS;
2632
+
2633
+ // node_modules/is-unsafe/src/contexts/nosql.js
2634
+ var sep2 = `["'\\s]*:`;
2635
+ var NOSQL_PATTERNS = [
2636
+ {
2637
+ id: "nosql-where-operator",
2638
+ description: "$where \u2014 executes arbitrary JavaScript server-side in MongoDB",
2639
+ pattern: new RegExp(`\\$where${sep2}`, "i")
2640
+ },
2641
+ {
2642
+ id: "nosql-ne-operator",
2643
+ description: '$ne \u2014 "not equal" operator used to bypass equality checks',
2644
+ pattern: new RegExp(`\\$ne${sep2}`, "i")
2645
+ },
2646
+ {
2647
+ id: "nosql-gt-operator",
2648
+ description: '$gt \u2014 "greater than" used to bypass password/value checks',
2649
+ pattern: new RegExp(`\\$gte?${sep2}`, "i")
2650
+ },
2651
+ {
2652
+ id: "nosql-lt-operator",
2653
+ description: '$lt / $lte \u2014 "less than" bypass variants',
2654
+ pattern: new RegExp(`\\$lte?${sep2}`, "i")
2655
+ },
2656
+ {
2657
+ id: "nosql-regex-operator",
2658
+ description: "$regex \u2014 can be used to extract data character by character (blind injection)",
2659
+ pattern: new RegExp(`\\$regex${sep2}`, "i")
2660
+ },
2661
+ {
2662
+ id: "nosql-or-operator",
2663
+ description: "$or \u2014 logical OR; used to create always-true conditions",
2664
+ pattern: new RegExp(`\\$or${sep2}\\s*\\[`, "i")
2665
+ },
2666
+ {
2667
+ id: "nosql-and-operator",
2668
+ description: "$and \u2014 logical AND operator injection",
2669
+ pattern: new RegExp(`\\$and${sep2}\\s*\\[`, "i")
2670
+ },
2671
+ {
2672
+ id: "nosql-nor-operator",
2673
+ description: "$nor \u2014 logical NOR operator injection",
2674
+ pattern: new RegExp(`\\$nor${sep2}\\s*\\[`, "i")
2675
+ },
2676
+ {
2677
+ id: "nosql-exists-operator",
2678
+ description: "$exists \u2014 can enumerate fields to determine schema",
2679
+ pattern: new RegExp(`\\$exists${sep2}`, "i")
2680
+ },
2681
+ {
2682
+ id: "nosql-in-operator",
2683
+ description: "$in \u2014 matches any value in a list; can enumerate values",
2684
+ pattern: new RegExp(`\\$in${sep2}\\s*\\[`, "i")
2685
+ },
2686
+ {
2687
+ id: "nosql-expr-operator",
2688
+ description: "$expr \u2014 allows aggregation expressions in queries (MongoDB 3.6+)",
2689
+ pattern: new RegExp(`\\$expr${sep2}`, "i")
2690
+ },
2691
+ {
2692
+ id: "nosql-function-operator",
2693
+ description: "$function \u2014 executes arbitrary JavaScript in MongoDB 4.4+",
2694
+ pattern: new RegExp(`\\$function${sep2}`, "i")
2695
+ },
2696
+ {
2697
+ id: "nosql-accumulator-operator",
2698
+ description: "$accumulator \u2014 custom aggregation with arbitrary JS execution",
2699
+ pattern: new RegExp(`\\$accumulator${sep2}`, "i")
2700
+ },
2701
+ {
2702
+ id: "nosql-proto-pollution",
2703
+ description: "__proto__ \u2014 prototype pollution via object key injection",
2704
+ pattern: /__proto__/
2705
+ },
2706
+ {
2707
+ id: "nosql-constructor-prototype",
2708
+ description: "constructor.prototype \u2014 alternative prototype pollution vector (dot notation or JSON key)",
2709
+ pattern: /constructor[\s"':.,{\[]*prototype/i
2710
+ },
2711
+ {
2712
+ id: "nosql-proto-bracket",
2713
+ description: '["__proto__"] \u2014 bracket-notation prototype pollution',
2714
+ pattern: /\[["']__proto__["']\]/
2715
+ }
2716
+ ];
2717
+ var nosql_default = NOSQL_PATTERNS;
2718
+
2719
+ // node_modules/is-unsafe/src/contexts/log.js
2720
+ var LOG_PATTERNS = [
2721
+ {
2722
+ id: "log-crlf-injection",
2723
+ description: "CRLF injection: literal \\r or \\n embeds fake log lines",
2724
+ pattern: /[\r\n]/
2725
+ },
2726
+ {
2727
+ id: "log-url-encoded-crlf",
2728
+ description: "URL-encoded CRLF: %0d, %0a, %0D, %0A \u2014 decoded by some log parsers",
2729
+ pattern: /%0[dDaA]/
2730
+ },
2731
+ {
2732
+ id: "log-unicode-newline",
2733
+ description: "Unicode newline variants: U+2028 (line separator), U+2029 (paragraph separator)",
2734
+ pattern: /[\u2028\u2029]/
2735
+ },
2736
+ {
2737
+ id: "log-log4shell-jndi",
2738
+ description: "Log4Shell: ${jndi:...} triggers remote code execution in Apache Log4j",
2739
+ pattern: /\$\{jndi\s*:/i
2740
+ },
2741
+ {
2742
+ id: "log-log4shell-obfuscated",
2743
+ description: "Obfuscated Log4Shell: ${::-j}... lookup-bypass prefix used to evade WAF detection",
2744
+ pattern: /\$\{::-/
2745
+ },
2746
+ {
2747
+ id: "log-log4j-lookup",
2748
+ description: "Log4j lookup syntax: ${env:...}, ${sys:...}, ${ctx:...} \u2014 data exfiltration",
2749
+ pattern: /\$\{(?:env|sys|ctx|main|map|sd|web|docker|k8s|spring)\s*:/i
2750
+ },
2751
+ {
2752
+ id: "log-ssti-double-brace",
2753
+ description: "SSTI double-brace: {{expression}} \u2014 Jinja2, Twig, Handlebars, etc.",
2754
+ pattern: /\{\{[\s\S]{0,80}\}\}/
2755
+ },
2756
+ {
2757
+ id: "log-ssti-hash-brace",
2758
+ description: "SSTI hash-brace: #{expression} \u2014 Thymeleaf, Velocity, Ruby ERB",
2759
+ pattern: /#\{[\s\S]{0,80}\}/
2760
+ },
2761
+ {
2762
+ id: "log-ssti-dollar-brace",
2763
+ description: "SSTI/EL injection: ${expression with operators or method calls} \u2014 JSP EL, Freemarker, SpEL",
2764
+ pattern: /\$\{[^}]*(?:\.|\(|\*|\+|\bclass\b|\bruntime\b|\bprocess\b|\bexec\b)[^}]{0,80}\}/i
2765
+ },
2766
+ {
2767
+ id: "log-ssti-percent-tag",
2768
+ description: "SSTI ERB/ASP tag: <%= expression %> \u2014 Ruby ERB, ASP",
2769
+ pattern: /<%=[\s\S]{0,80}%>/
2770
+ },
2771
+ {
2772
+ id: "log-null-byte",
2773
+ description: "Null byte: \\x00 or %00 \u2014 can truncate log entries in C-backed loggers",
2774
+ pattern: /\x00|%00/
2775
+ },
2776
+ {
2777
+ id: "log-ansi-escape",
2778
+ description: "ANSI escape sequence: ESC[ \u2014 can manipulate terminal output when logs are tailed",
2779
+ pattern: /\x1b\[/
2780
+ }
2781
+ ];
2782
+ var log_default = LOG_PATTERNS;
2783
+
2784
+ // node_modules/is-unsafe/src/contexts/sql-strict.js
2785
+ var SQL_STRICT_EXTRA = [
2786
+ {
2787
+ id: "sql-line-comment",
2788
+ description: "SQL line comment: -- followed by whitespace or end of string",
2789
+ pattern: /--(?:\s|$)/
2790
+ },
2791
+ {
2792
+ id: "sql-stacked-query",
2793
+ description: "Stacked queries: semicolon immediately followed by a SQL keyword",
2794
+ pattern: /;\s{0,10}(?:SELECT|INSERT|UPDATE|DELETE|DROP|CREATE|ALTER|EXEC)\b/i
2795
+ },
2796
+ {
2797
+ id: "sql-hex-encoding",
2798
+ description: "Hex-encoded string injection: 0x41414141 style (MySQL)",
2799
+ pattern: /\b0x[0-9a-f]{4,}/i
2800
+ }
2801
+ ];
2802
+ var SQL_STRICT_PATTERNS = [...sql_default, ...SQL_STRICT_EXTRA];
2803
+ var sql_strict_default = SQL_STRICT_PATTERNS;
2804
+
2805
+ // node_modules/is-unsafe/src/util/decode-entities.js
2806
+ var NAMED = Object.freeze({
2807
+ colon: ":",
2808
+ Tab: "\t",
2809
+ NewLine: `
2810
+ `
2811
+ });
2812
+ var ENTITY_RE = /&(?:#[xX]0*([0-9a-fA-F]{1,6});?|#0*([0-9]{1,7});?|([a-zA-Z][a-zA-Z0-9]{1,15});)/g;
2813
+ function decodeEntities(input) {
2814
+ if (input.indexOf("&") === -1)
2815
+ return input;
2816
+ return input.replace(ENTITY_RE, (match, hex, dec, name) => {
2817
+ if (name !== undefined) {
2818
+ return Object.prototype.hasOwnProperty.call(NAMED, name) ? NAMED[name] : match;
2819
+ }
2820
+ const cp = hex !== undefined ? parseInt(hex, 16) : parseInt(dec, 10);
2821
+ if (!Number.isFinite(cp) || cp > 1114111)
2822
+ return match;
2823
+ return String.fromCodePoint(cp);
2824
+ });
2825
+ }
2826
+
2827
+ // node_modules/is-unsafe/src/index.js
2828
+ html_default.label = "HTML";
2829
+ xml_default.label = "XML";
2830
+ svg_default.label = "SVG";
2831
+ html_default.decodeEntities = true;
2832
+ xml_default.decodeEntities = true;
2833
+ svg_default.decodeEntities = true;
2834
+ sql_default.label = "SQL";
2835
+ sql_strict_default.label = "SQL-STRICT";
2836
+ shell_default.label = "SHELL";
2837
+ redos_default.label = "REDOS";
2838
+ nosql_default.label = "NOSQL";
2839
+ log_default.label = "LOG";
2840
+ var VALID_CONTEXTS = Object.freeze({
2841
+ HTML: html_default,
2842
+ XML: xml_default,
2843
+ SVG: svg_default,
2844
+ SQL: sql_default,
2845
+ "SQL-STRICT": sql_strict_default,
2846
+ SHELL: shell_default,
2847
+ REDOS: redos_default,
2848
+ NOSQL: nosql_default,
2849
+ LOG: log_default
2850
+ });
2851
+ function assertString(value) {
2852
+ if (typeof value !== "string") {
2853
+ throw new TypeError(`is-unsafe: first argument must be a string, got ${typeof value}`);
2854
+ }
2855
+ }
2856
+ function assertContext(context) {
2857
+ if (context instanceof RegExp)
2858
+ return;
2859
+ if (Array.isArray(context)) {
2860
+ if (context.length === 0) {
2861
+ throw new TypeError("is-unsafe: context must not be an empty array");
2862
+ }
2863
+ if (Array.isArray(context[0])) {
2864
+ for (const list of context) {
2865
+ if (!Array.isArray(list) || list.length === 0) {
2866
+ throw new TypeError("is-unsafe: each context in the array must be a non-empty pattern array (PatternList)");
2867
+ }
2868
+ }
2869
+ }
2870
+ return;
2871
+ }
2872
+ throw new TypeError(`is-unsafe: second argument must be a PatternList (e.g. HTML), ` + `an array of PatternLists (e.g. [HTML, XML]), or a RegExp. Got: ${typeof context}`);
2873
+ }
2874
+ function normalise(context) {
2875
+ if (context instanceof RegExp)
2876
+ return { lists: null, regex: context };
2877
+ if (Array.isArray(context[0]))
2878
+ return { lists: context, regex: null };
2879
+ return { lists: [context], regex: null };
2880
+ }
2881
+ function decodedCopy(value, list) {
2882
+ if (!list.decodeEntities)
2883
+ return null;
2884
+ const decoded = decodeEntities(value);
2885
+ return decoded === value ? null : decoded;
2886
+ }
2887
+ function matchList(value, list) {
2888
+ const label = list.label ?? "CUSTOM";
2889
+ const decoded = decodedCopy(value, list);
2890
+ for (const rule of list) {
2891
+ if (rule.pattern.test(value) || decoded !== null && rule.pattern.test(decoded)) {
2892
+ return { context: label, id: rule.id, description: rule.description, pattern: rule.pattern };
2893
+ }
2894
+ }
2895
+ return null;
2896
+ }
2897
+ function isUnsafe(value, context) {
2898
+ assertString(value);
2899
+ assertContext(context);
2900
+ const { lists, regex } = normalise(context);
2901
+ if (regex)
2902
+ return regex.test(value);
2903
+ for (const list of lists) {
2904
+ if (matchList(value, list) !== null)
2905
+ return true;
2906
+ }
2907
+ return false;
2908
+ }
2909
+
2910
+ // node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js
2911
+ function extractRawAttributes(prefixedAttrs, options) {
2912
+ if (!prefixedAttrs)
2913
+ return {};
2914
+ const attrs = options.attributesGroupName ? prefixedAttrs[options.attributesGroupName] : prefixedAttrs;
2915
+ if (!attrs)
2916
+ return {};
2917
+ const rawAttrs = {};
2918
+ for (const key in attrs) {
2919
+ if (key.startsWith(options.attributeNamePrefix)) {
2920
+ const rawName = key.substring(options.attributeNamePrefix.length);
2921
+ rawAttrs[rawName] = attrs[key];
2922
+ } else {
2923
+ rawAttrs[key] = attrs[key];
2924
+ }
2925
+ }
2926
+ return rawAttrs;
2927
+ }
2928
+ function extractNamespace(rawTagName) {
2929
+ if (!rawTagName || typeof rawTagName !== "string")
2930
+ return;
2931
+ const colonIndex = rawTagName.indexOf(":");
2932
+ if (colonIndex !== -1 && colonIndex > 0) {
2933
+ const ns = rawTagName.substring(0, colonIndex);
2934
+ if (ns !== "xmlns") {
2935
+ return ns;
2936
+ }
2937
+ }
2938
+ return;
2939
+ }
2940
+
2941
+ class OrderedObjParser {
2942
+ constructor(options, externalEntities) {
2943
+ this.options = options;
2944
+ this.currentNode = null;
2945
+ this.tagsNodeStack = [];
2946
+ this.parseXml = parseXml;
2947
+ this.parseTextData = parseTextData;
2948
+ this.resolveNameSpace = resolveNameSpace;
2949
+ this.buildAttributesMap = buildAttributesMap;
2950
+ this.isItStopNode = isItStopNode;
2951
+ this.replaceEntitiesValue = replaceEntitiesValue;
2952
+ this.readStopNodeData = readStopNodeData;
2953
+ this.saveTextToParentTag = saveTextToParentTag;
2954
+ this.addChild = addChild;
2955
+ this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes);
2956
+ this.entityExpansionCount = 0;
2957
+ this.currentExpandedLength = 0;
2958
+ this.doctypefound = false;
2959
+ let namedEntities = { ...XML };
2960
+ if (this.options.entityDecoder) {
2961
+ this.entityDecoder = this.options.entityDecoder;
2962
+ } else {
2963
+ if (typeof this.options.htmlEntities === "object")
2964
+ namedEntities = this.options.htmlEntities;
2965
+ else if (this.options.htmlEntities === true)
2966
+ namedEntities = { ...COMMON_HTML, ...CURRENCY };
2967
+ this.entityDecoder = new EntityDecoder({
2968
+ namedEntities: { ...namedEntities, ...externalEntities },
2969
+ numericAllowed: this.options.htmlEntities,
2970
+ limit: {
2971
+ maxTotalExpansions: this.options.processEntities.maxTotalExpansions,
2972
+ maxExpandedLength: this.options.processEntities.maxExpandedLength,
2973
+ applyLimitsTo: this.options.processEntities.appliesTo
2974
+ },
2975
+ onInputEntity: (name, value) => isUnsafe(value, [html_default, xml_default]) ? ENTITY_ACTION.BLOCK : ENTITY_ACTION.ALLOW
2976
+ });
2977
+ }
2978
+ this.matcher = new Matcher;
2979
+ this.readonlyMatcher = this.matcher.readOnly();
2980
+ this.isCurrentNodeStopNode = false;
2981
+ this.stopNodeExpressionsSet = new ExpressionSet;
2982
+ const stopNodesOpts = this.options.stopNodes;
2983
+ if (stopNodesOpts && stopNodesOpts.length > 0) {
2984
+ for (let i = 0;i < stopNodesOpts.length; i++) {
2985
+ const stopNodeExp = stopNodesOpts[i];
2986
+ if (typeof stopNodeExp === "string") {
2987
+ this.stopNodeExpressionsSet.add(new Expression(stopNodeExp));
2988
+ } else if (stopNodeExp instanceof Expression) {
2989
+ this.stopNodeExpressionsSet.add(stopNodeExp);
2990
+ }
2991
+ }
2992
+ this.stopNodeExpressionsSet.seal();
2993
+ }
2994
+ }
2995
+ }
2996
+ function parseTextData(val, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) {
2997
+ const options = this.options;
2998
+ if (val !== undefined) {
2999
+ if (options.trimValues && !dontTrim) {
3000
+ val = val.trim();
3001
+ }
3002
+ if (val.length > 0) {
3003
+ if (!escapeEntities)
3004
+ val = this.replaceEntitiesValue(val, tagName, jPath);
3005
+ const jPathOrMatcher = options.jPath ? jPath.toString() : jPath;
3006
+ const newval = options.tagValueProcessor(tagName, val, jPathOrMatcher, hasAttributes, isLeafNode);
3007
+ if (newval === null || newval === undefined) {
3008
+ return val;
3009
+ } else if (typeof newval !== typeof val || newval !== val) {
3010
+ return newval;
3011
+ } else if (options.trimValues) {
3012
+ return parseValue(val, options.parseTagValue, options.numberParseOptions);
3013
+ } else {
3014
+ const trimmedVal = val.trim();
3015
+ if (trimmedVal === val) {
3016
+ return parseValue(val, options.parseTagValue, options.numberParseOptions);
3017
+ } else {
3018
+ return val;
3019
+ }
3020
+ }
3021
+ }
3022
+ }
3023
+ }
3024
+ function resolveNameSpace(tagname) {
3025
+ if (this.options.removeNSPrefix) {
3026
+ const tags = tagname.split(":");
3027
+ const prefix = tagname.charAt(0) === "/" ? "/" : "";
3028
+ if (tags[0] === "xmlns") {
3029
+ return "";
3030
+ }
3031
+ if (tags.length === 2) {
3032
+ tagname = prefix + tags[1];
3033
+ }
3034
+ }
3035
+ return tagname;
3036
+ }
3037
+ var attrsRegx = /([^\s=]+)\s*(=\s*(?:"([^"]*)"|'([^']*)'))?/gm;
3038
+ function attrValue(match) {
3039
+ return match[3] !== undefined ? match[3] : match[4];
3040
+ }
3041
+ function buildAttributesMap(attrStr, jPath, tagName, force = false) {
3042
+ const options = this.options;
3043
+ if (force === true || options.ignoreAttributes !== true && typeof attrStr === "string") {
3044
+ const matches = getAllMatches(attrStr, attrsRegx);
3045
+ const len = matches.length;
3046
+ const attrs = {};
3047
+ const processedVals = new Array(len);
3048
+ let hasRawAttrs = false;
3049
+ const rawAttrsForMatcher = {};
3050
+ for (let i = 0;i < len; i++) {
3051
+ const attrName = this.resolveNameSpace(matches[i][1]);
3052
+ const oldVal = attrValue(matches[i]);
3053
+ if (attrName.length && oldVal !== undefined) {
3054
+ let val = oldVal;
3055
+ if (options.trimValues)
3056
+ val = val.trim();
3057
+ val = this.replaceEntitiesValue(val, tagName, this.readonlyMatcher);
3058
+ processedVals[i] = val;
3059
+ rawAttrsForMatcher[attrName] = val;
3060
+ hasRawAttrs = true;
3061
+ }
3062
+ }
3063
+ if (hasRawAttrs && typeof jPath === "object" && jPath.updateCurrent) {
3064
+ jPath.updateCurrent(rawAttrsForMatcher);
3065
+ }
3066
+ const jPathStr = options.jPath ? jPath.toString() : this.readonlyMatcher;
3067
+ let hasAttrs = false;
3068
+ for (let i = 0;i < len; i++) {
3069
+ const attrName = this.resolveNameSpace(matches[i][1]);
3070
+ if (this.ignoreAttributesFn(attrName, jPathStr))
3071
+ continue;
3072
+ let aName = options.attributeNamePrefix + attrName;
3073
+ if (attrName.length) {
3074
+ if (options.transformAttributeName) {
3075
+ aName = options.transformAttributeName(aName);
3076
+ }
3077
+ aName = sanitizeName(aName, options);
3078
+ if (attrValue(matches[i]) !== undefined) {
3079
+ const oldVal = processedVals[i];
3080
+ const newVal = options.attributeValueProcessor(attrName, oldVal, jPathStr);
3081
+ if (newVal === null || newVal === undefined) {
3082
+ attrs[aName] = oldVal;
3083
+ } else if (typeof newVal !== typeof oldVal || newVal !== oldVal) {
3084
+ attrs[aName] = newVal;
3085
+ } else {
3086
+ attrs[aName] = parseValue(oldVal, options.parseAttributeValue, options.numberParseOptions);
3087
+ }
3088
+ hasAttrs = true;
3089
+ } else if (options.allowBooleanAttributes) {
3090
+ attrs[aName] = true;
3091
+ hasAttrs = true;
3092
+ }
3093
+ }
3094
+ }
3095
+ if (!hasAttrs)
3096
+ return;
3097
+ if (options.attributesGroupName && !options.preserveOrder) {
3098
+ const attrCollection = {};
3099
+ attrCollection[options.attributesGroupName] = attrs;
3100
+ return attrCollection;
3101
+ }
3102
+ return attrs;
3103
+ }
3104
+ }
3105
+ var parseXml = function(xmlData) {
3106
+ const options = this.options;
3107
+ const crlfPositions = options.captureMetaData ? [] : undefined;
3108
+ xmlData = xmlData.replace(/\r\n?/g, options.captureMetaData ? (newline, index) => {
3109
+ if (newline.length === 2) {
3110
+ crlfPositions.push(index - crlfPositions.length);
3111
+ }
3112
+ return `
3113
+ `;
3114
+ } : `
3115
+ `);
3116
+ const xmlObj = new XmlNode("!xml");
3117
+ let currentNode = xmlObj;
3118
+ let textData = "";
3119
+ this.matcher.reset();
3120
+ this.entityDecoder.reset();
3121
+ this.entityExpansionCount = 0;
3122
+ this.currentExpandedLength = 0;
3123
+ this.doctypefound = false;
3124
+ const docTypeReader = new DocTypeReader(options.processEntities);
3125
+ const xmlLen = xmlData.length;
3126
+ for (let i = 0;i < xmlLen; i++) {
3127
+ const ch = xmlData[i];
3128
+ if (ch === "<") {
3129
+ const c1 = xmlData.charCodeAt(i + 1);
3130
+ if (c1 === 47) {
3131
+ const closeIndex = findClosingIndex(xmlData, ">", i, "Closing Tag is not closed.");
3132
+ let tagName = xmlData.substring(i + 2, closeIndex).trim();
3133
+ if (options.removeNSPrefix) {
3134
+ const colonIndex = tagName.indexOf(":");
3135
+ if (colonIndex !== -1) {
3136
+ tagName = tagName.substr(colonIndex + 1);
3137
+ }
3138
+ }
3139
+ tagName = transformTagName(options.transformTagName, tagName, "", options).tagName;
3140
+ if (currentNode) {
3141
+ textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);
3142
+ }
3143
+ const lastTagName = this.matcher.getCurrentTag();
3144
+ if (tagName && options.unpairedTagsSet.has(tagName)) {
3145
+ throw new Error(`Unpaired tag can not be used as closing tag: </${tagName}>`);
3146
+ }
3147
+ if (lastTagName && options.unpairedTagsSet.has(lastTagName)) {
3148
+ this.matcher.pop();
3149
+ this.tagsNodeStack.pop();
3150
+ }
3151
+ this.matcher.pop();
3152
+ this.isCurrentNodeStopNode = false;
3153
+ currentNode = this.tagsNodeStack.pop() || xmlObj;
3154
+ if (options.captureMetaData && currentNode) {
3155
+ currentNode.addEndIndex(getOriginalIndex(closeIndex + 1, crlfPositions));
3156
+ }
3157
+ textData = "";
3158
+ i = closeIndex;
3159
+ } else if (c1 === 63) {
3160
+ let tagData = readTagExp(xmlData, i, false, "?>");
3161
+ if (!tagData)
3162
+ throw new Error("Pi Tag is not closed.");
3163
+ textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);
3164
+ const attsMap = this.buildAttributesMap(tagData.tagExp, this.matcher, tagData.tagName, true);
3165
+ if (attsMap) {
3166
+ const ver = attsMap[this.options.attributeNamePrefix + "version"];
3167
+ this.entityDecoder.setXmlVersion(Number(ver) || 1);
3168
+ docTypeReader.setXmlVersion(Number(ver) || 1);
3169
+ }
3170
+ if (options.ignoreDeclaration && tagData.tagName === "?xml" || options.ignorePiTags) {} else {
3171
+ const childNode = new XmlNode(tagData.tagName);
3172
+ childNode.add(options.textNodeName, "");
3173
+ if (tagData.tagName !== tagData.tagExp && tagData.attrExpPresent && options.ignoreAttributes !== true) {
3174
+ childNode[":@"] = attsMap;
3175
+ }
3176
+ const startIndex = options.captureMetaData ? getOriginalIndex(i, crlfPositions) : i;
3177
+ this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);
3178
+ if (options.captureMetaData) {
3179
+ currentNode.addEndIndex(getOriginalIndex(tagData.closeIndex + 2, crlfPositions));
3180
+ }
3181
+ }
3182
+ i = tagData.closeIndex + 1;
3183
+ } else if (c1 === 33 && xmlData.charCodeAt(i + 2) === 45 && xmlData.charCodeAt(i + 3) === 45) {
3184
+ const endIndex = findClosingIndex(xmlData, "-->", i + 4, "Comment is not closed.");
3185
+ if (options.commentPropName) {
3186
+ const comment = xmlData.substring(i + 4, endIndex - 2);
3187
+ textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);
3188
+ currentNode.add(options.commentPropName, [{ [options.textNodeName]: comment }]);
3189
+ }
3190
+ i = endIndex;
3191
+ } else if (c1 === 33 && xmlData.charCodeAt(i + 2) === 68) {
3192
+ if (this.doctypefound)
3193
+ throw new Error("Multiple DOCTYPE declarations found.");
3194
+ this.doctypefound = true;
3195
+ const result = docTypeReader.readDocType(xmlData, i);
3196
+ this.entityDecoder.addInputEntities(result.entities);
3197
+ i = result.i;
3198
+ } else if (c1 === 33 && xmlData.charCodeAt(i + 2) === 91) {
3199
+ const closeIndex = findClosingIndex(xmlData, "]]>", i, "CDATA is not closed.") - 2;
3200
+ const tagExp = xmlData.substring(i + 9, closeIndex);
3201
+ textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);
3202
+ let val = this.parseTextData(tagExp, currentNode.tagname, this.readonlyMatcher, true, false, true, true);
3203
+ if (val == undefined)
3204
+ val = "";
3205
+ if (options.cdataPropName) {
3206
+ currentNode.add(options.cdataPropName, [{ [options.textNodeName]: tagExp }]);
3207
+ } else {
3208
+ currentNode.add(options.textNodeName, val);
3209
+ }
3210
+ i = closeIndex + 2;
3211
+ } else {
3212
+ let result = readTagExp(xmlData, i, options.removeNSPrefix);
3213
+ if (!result) {
3214
+ const context = xmlData.substring(Math.max(0, i - 50), Math.min(xmlLen, i + 50));
3215
+ throw new Error(`readTagExp returned undefined at position ${i}. Context: "${context}"`);
3216
+ }
3217
+ let tagName = result.tagName;
3218
+ const rawTagName = result.rawTagName;
3219
+ let tagExp = result.tagExp;
3220
+ let attrExpPresent = result.attrExpPresent;
3221
+ let closeIndex = result.closeIndex;
3222
+ ({ tagName, tagExp } = transformTagName(options.transformTagName, tagName, tagExp, options));
3223
+ if (options.strictReservedNames && (tagName === options.commentPropName || tagName === options.cdataPropName || tagName === options.textNodeName || tagName === options.attributesGroupName)) {
3224
+ throw new Error(`Invalid tag name: ${tagName}`);
3225
+ }
3226
+ if (currentNode && textData) {
3227
+ if (currentNode.tagname !== "!xml") {
3228
+ textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher, false);
3229
+ }
3230
+ }
3231
+ const lastTag = currentNode;
3232
+ if (lastTag && options.unpairedTagsSet.has(lastTag.tagname)) {
3233
+ currentNode = this.tagsNodeStack.pop();
3234
+ this.matcher.pop();
3235
+ }
3236
+ let isSelfClosing = false;
3237
+ if (tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1) {
3238
+ isSelfClosing = true;
3239
+ if (tagName[tagName.length - 1] === "/") {
3240
+ tagName = tagName.substr(0, tagName.length - 1);
3241
+ tagExp = tagName;
3242
+ } else {
3243
+ tagExp = tagExp.substr(0, tagExp.length - 1);
3244
+ }
3245
+ attrExpPresent = tagName !== tagExp;
3246
+ }
3247
+ let prefixedAttrs = null;
3248
+ let rawAttrs = {};
3249
+ let namespace = undefined;
3250
+ namespace = extractNamespace(rawTagName);
3251
+ if (tagName !== xmlObj.tagname) {
3252
+ this.matcher.push(tagName, {}, namespace);
3253
+ }
3254
+ if (tagName !== tagExp && attrExpPresent) {
3255
+ prefixedAttrs = this.buildAttributesMap(tagExp, this.matcher, tagName);
3256
+ if (prefixedAttrs) {
3257
+ rawAttrs = extractRawAttributes(prefixedAttrs, options);
3258
+ }
3259
+ }
3260
+ if (tagName !== xmlObj.tagname) {
3261
+ this.isCurrentNodeStopNode = this.isItStopNode();
3262
+ }
3263
+ const startIndex = options.captureMetaData ? getOriginalIndex(i, crlfPositions) : i;
3264
+ if (this.isCurrentNodeStopNode) {
3265
+ let tagContent = "";
3266
+ if (isSelfClosing) {
3267
+ i = result.closeIndex;
3268
+ } else if (options.unpairedTagsSet.has(tagName)) {
3269
+ i = result.closeIndex;
3270
+ } else {
3271
+ const result = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1);
3272
+ if (!result)
3273
+ throw new Error(`Unexpected end of ${rawTagName}`);
3274
+ i = result.i;
3275
+ tagContent = result.tagContent;
3276
+ }
3277
+ const childNode = new XmlNode(tagName);
3278
+ if (prefixedAttrs) {
3279
+ childNode[":@"] = prefixedAttrs;
3280
+ }
3281
+ childNode.add(options.textNodeName, tagContent);
3282
+ this.matcher.pop();
3283
+ this.isCurrentNodeStopNode = false;
3284
+ this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);
3285
+ if (options.captureMetaData) {
3286
+ currentNode.addEndIndex(getOriginalIndex(i + 1, crlfPositions));
3287
+ }
3288
+ } else {
3289
+ if (isSelfClosing) {
3290
+ ({ tagName, tagExp } = transformTagName(options.transformTagName, tagName, tagExp, options));
3291
+ const childNode = new XmlNode(tagName);
3292
+ if (prefixedAttrs) {
3293
+ childNode[":@"] = prefixedAttrs;
3294
+ }
3295
+ this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);
3296
+ if (options.captureMetaData) {
3297
+ currentNode.addEndIndex(getOriginalIndex(closeIndex + 1, crlfPositions));
3298
+ }
3299
+ this.matcher.pop();
3300
+ this.isCurrentNodeStopNode = false;
3301
+ } else if (options.unpairedTagsSet.has(tagName)) {
3302
+ const childNode = new XmlNode(tagName);
3303
+ if (prefixedAttrs) {
3304
+ childNode[":@"] = prefixedAttrs;
3305
+ }
3306
+ this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);
3307
+ if (options.captureMetaData) {
3308
+ currentNode.addEndIndex(getOriginalIndex(result.closeIndex + 1, crlfPositions));
3309
+ }
3310
+ this.matcher.pop();
3311
+ this.isCurrentNodeStopNode = false;
3312
+ i = result.closeIndex;
3313
+ continue;
3314
+ } else {
3315
+ const childNode = new XmlNode(tagName);
3316
+ if (this.tagsNodeStack.length > options.maxNestedTags) {
3317
+ throw new Error("Maximum nested tags exceeded");
3318
+ }
3319
+ this.tagsNodeStack.push(currentNode);
3320
+ if (prefixedAttrs) {
3321
+ childNode[":@"] = prefixedAttrs;
3322
+ }
3323
+ this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);
3324
+ currentNode = childNode;
3325
+ }
3326
+ textData = "";
3327
+ i = closeIndex;
3328
+ }
3329
+ }
3330
+ } else {
3331
+ textData += xmlData[i];
3332
+ }
3333
+ }
3334
+ return xmlObj.child;
3335
+ };
3336
+ function getOriginalIndex(index, crlfPositions) {
3337
+ let low = 0;
3338
+ let high = crlfPositions.length;
3339
+ while (low < high) {
3340
+ const middle = Math.floor((low + high) / 2);
3341
+ if (crlfPositions[middle] < index)
3342
+ low = middle + 1;
3343
+ else
3344
+ high = middle;
3345
+ }
3346
+ return index + low;
3347
+ }
3348
+ function addChild(currentNode, childNode, matcher, startIndex) {
3349
+ if (!this.options.captureMetaData)
3350
+ startIndex = undefined;
3351
+ const jPathOrMatcher = this.options.jPath ? matcher.toString() : matcher;
3352
+ const result = this.options.updateTag(childNode.tagname, jPathOrMatcher, childNode[":@"]);
3353
+ if (result === false) {} else if (typeof result === "string") {
3354
+ childNode.tagname = result;
3355
+ currentNode.addChild(childNode, startIndex);
3356
+ } else {
3357
+ currentNode.addChild(childNode, startIndex);
3358
+ }
3359
+ }
3360
+ function replaceEntitiesValue(val, tagName, jPath) {
3361
+ const entityConfig = this.options.processEntities;
3362
+ if (!entityConfig || !entityConfig.enabled) {
3363
+ return val;
3364
+ }
3365
+ if (entityConfig.allowedTags) {
3366
+ const jPathOrMatcher = this.options.jPath ? jPath.toString() : jPath;
3367
+ const allowed = Array.isArray(entityConfig.allowedTags) ? entityConfig.allowedTags.includes(tagName) : entityConfig.allowedTags(tagName, jPathOrMatcher);
3368
+ if (!allowed) {
3369
+ return val;
3370
+ }
3371
+ }
3372
+ if (entityConfig.tagFilter) {
3373
+ const jPathOrMatcher = this.options.jPath ? jPath.toString() : jPath;
3374
+ if (!entityConfig.tagFilter(tagName, jPathOrMatcher)) {
3375
+ return val;
3376
+ }
3377
+ }
3378
+ return this.entityDecoder.decode(val);
3379
+ }
3380
+ function saveTextToParentTag(textData, parentNode, matcher, isLeafNode) {
3381
+ if (textData) {
3382
+ if (isLeafNode === undefined)
3383
+ isLeafNode = parentNode.child.length === 0;
3384
+ textData = this.parseTextData(textData, parentNode.tagname, matcher, false, parentNode[":@"] ? Object.keys(parentNode[":@"]).length !== 0 : false, isLeafNode);
3385
+ if (textData !== undefined && textData !== "")
3386
+ parentNode.add(this.options.textNodeName, textData);
3387
+ textData = "";
3388
+ }
3389
+ return textData;
3390
+ }
3391
+ function isItStopNode() {
3392
+ if (this.stopNodeExpressionsSet.size === 0)
3393
+ return false;
3394
+ return this.matcher.matchesAny(this.stopNodeExpressionsSet);
3395
+ }
3396
+ function tagExpWithClosingIndex(xmlData, i, closingChar = ">") {
3397
+ const len = xmlData.length;
3398
+ const closeCode0 = closingChar.charCodeAt(0);
3399
+ const closeCode1 = closingChar.length > 1 ? closingChar.charCodeAt(1) : -1;
3400
+ let result = "";
3401
+ let segmentStart = i;
3402
+ for (let index = i;index < len; index++) {
3403
+ const code = xmlData.charCodeAt(index);
3404
+ if (code === 34 || code === 39) {
3405
+ index = xmlData.indexOf(xmlData[index], index + 1);
3406
+ if (index === -1)
3407
+ return;
3408
+ } else if (code === closeCode0) {
3409
+ if (closeCode1 !== -1) {
3410
+ if (xmlData.charCodeAt(index + 1) === closeCode1) {
3411
+ result += xmlData.substring(segmentStart, index);
3412
+ return { data: result, index };
3413
+ }
3414
+ } else {
3415
+ result += xmlData.substring(segmentStart, index);
3416
+ return { data: result, index };
3417
+ }
3418
+ } else if (code === 9) {
3419
+ result += xmlData.substring(segmentStart, index) + " ";
3420
+ segmentStart = index + 1;
3421
+ }
3422
+ }
3423
+ }
3424
+ function findClosingIndex(xmlData, str, i, errMsg) {
3425
+ const closingIndex = xmlData.indexOf(str, i);
3426
+ if (closingIndex === -1) {
3427
+ throw new Error(errMsg);
3428
+ } else {
3429
+ return closingIndex + str.length - 1;
3430
+ }
3431
+ }
3432
+ function findClosingChar(xmlData, char, i, errMsg) {
3433
+ const closingIndex = xmlData.indexOf(char, i);
3434
+ if (closingIndex === -1)
3435
+ throw new Error(errMsg);
3436
+ return closingIndex;
3437
+ }
3438
+ function readTagExp(xmlData, i, removeNSPrefix, closingChar = ">") {
3439
+ const result = tagExpWithClosingIndex(xmlData, i + 1, closingChar);
3440
+ if (!result)
3441
+ return;
3442
+ let tagExp = result.data;
3443
+ const closeIndex = result.index;
3444
+ const separatorIndex = tagExp.search(/\s/);
3445
+ let tagName = tagExp;
3446
+ let attrExpPresent = true;
3447
+ if (separatorIndex !== -1) {
3448
+ tagName = tagExp.substring(0, separatorIndex);
3449
+ tagExp = tagExp.substring(separatorIndex + 1).trimStart();
3450
+ }
3451
+ const rawTagName = tagName;
3452
+ if (removeNSPrefix) {
3453
+ const colonIndex = tagName.indexOf(":");
3454
+ if (colonIndex !== -1) {
3455
+ tagName = tagName.substr(colonIndex + 1);
3456
+ attrExpPresent = tagName !== result.data.substr(colonIndex + 1);
3457
+ }
3458
+ }
3459
+ return {
3460
+ tagName,
3461
+ tagExp,
3462
+ closeIndex,
3463
+ attrExpPresent,
3464
+ rawTagName
3465
+ };
3466
+ }
3467
+ function readStopNodeData(xmlData, tagName, i) {
3468
+ const startIndex = i;
3469
+ let openTagCount = 1;
3470
+ let lenient = false;
3471
+ let nextGt = -1;
3472
+ const xmllen = xmlData.length;
3473
+ for (;i < xmllen; i++) {
3474
+ if (xmlData[i] === "<") {
3475
+ const c1 = xmlData.charCodeAt(i + 1);
3476
+ if (c1 === 47) {
3477
+ const closeIndex = findClosingChar(xmlData, ">", i, `${tagName} is not closed`);
3478
+ let closeTagName = xmlData.substring(i + 2, closeIndex).trim();
3479
+ if (closeTagName === tagName) {
3480
+ openTagCount--;
3481
+ if (openTagCount === 0) {
3482
+ return {
3483
+ tagContent: xmlData.substring(startIndex, i),
3484
+ i: closeIndex
3485
+ };
3486
+ }
3487
+ }
3488
+ i = closeIndex;
3489
+ } else if (c1 === 63) {
3490
+ const closeIndex = findClosingIndex(xmlData, "?>", i + 1, "StopNode is not closed.");
3491
+ i = closeIndex;
3492
+ } else if (c1 === 33 && xmlData.charCodeAt(i + 2) === 45 && xmlData.charCodeAt(i + 3) === 45) {
3493
+ const closeIndex = findClosingIndex(xmlData, "-->", i + 3, "StopNode is not closed.");
3494
+ i = closeIndex;
3495
+ } else if (c1 === 33 && xmlData.charCodeAt(i + 2) === 91) {
3496
+ const closeIndex = findClosingIndex(xmlData, "]]>", i, "StopNode is not closed.") - 2;
3497
+ i = closeIndex;
3498
+ } else {
3499
+ const tagData = lenient ? undefined : readTagExp(xmlData, i, false);
3500
+ if (tagData) {
3501
+ const openTagName = tagData.tagName;
3502
+ if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length - 1] !== "/") {
3503
+ openTagCount++;
3504
+ }
3505
+ i = tagData.closeIndex;
3506
+ } else {
3507
+ lenient = true;
3508
+ if (nextGt < i) {
3509
+ nextGt = xmlData.indexOf(">", i);
3510
+ if (nextGt === -1)
3511
+ return;
3512
+ }
3513
+ const nextLt = xmlData.indexOf("<", i + 1);
3514
+ if (nextLt === -1 || nextLt > nextGt) {
3515
+ const exp = xmlData.substring(i + 1, nextGt);
3516
+ const sep = exp.search(/\s/);
3517
+ const name = sep === -1 ? exp : exp.substring(0, sep);
3518
+ if (name === tagName && exp[exp.length - 1] !== "/")
3519
+ openTagCount++;
3520
+ i = nextGt;
3521
+ }
3522
+ }
3523
+ }
3524
+ }
3525
+ }
3526
+ }
3527
+ function parseValue(val, shouldParse, options) {
3528
+ if (shouldParse && typeof val === "string") {
3529
+ const newval = val.trim();
3530
+ if (newval === "true")
3531
+ return true;
3532
+ else if (newval === "false")
3533
+ return false;
3534
+ else
3535
+ return toNumber(val, options);
3536
+ } else {
3537
+ if (isExist(val)) {
3538
+ return val;
3539
+ } else {
3540
+ return "";
3541
+ }
3542
+ }
3543
+ }
3544
+ function transformTagName(fn, tagName, tagExp, options) {
3545
+ if (fn) {
3546
+ const newTagName = fn(tagName);
3547
+ if (tagExp === tagName) {
3548
+ tagExp = newTagName;
3549
+ }
3550
+ tagName = newTagName;
3551
+ }
3552
+ tagName = sanitizeName(tagName, options);
3553
+ return { tagName, tagExp };
3554
+ }
3555
+ function sanitizeName(name, options) {
3556
+ if (criticalProperties.includes(name)) {
3557
+ throw new Error(`[SECURITY] Invalid name: "${name}" is a reserved JavaScript keyword that could cause prototype pollution`);
3558
+ } else if (DANGEROUS_PROPERTY_NAMES.includes(name)) {
3559
+ return options.onDangerousProperty(name);
3560
+ }
3561
+ return name;
3562
+ }
3563
+
3564
+ // node_modules/fast-xml-parser/src/xmlparser/node2json.js
3565
+ var METADATA_SYMBOL2 = XmlNode.getMetaDataSymbol();
3566
+ function stripAttributePrefix(attrs, prefix) {
3567
+ if (!attrs || typeof attrs !== "object")
3568
+ return {};
3569
+ if (!prefix)
3570
+ return attrs;
3571
+ const rawAttrs = {};
3572
+ for (const key in attrs) {
3573
+ if (key.startsWith(prefix)) {
3574
+ const rawName = key.substring(prefix.length);
3575
+ rawAttrs[rawName] = attrs[key];
3576
+ } else {
3577
+ rawAttrs[key] = attrs[key];
3578
+ }
3579
+ }
3580
+ return rawAttrs;
3581
+ }
3582
+ function prettify(node, options, matcher, readonlyMatcher) {
3583
+ return compress(node, options, matcher, readonlyMatcher);
3584
+ }
3585
+ function compress(arr, options, matcher, readonlyMatcher) {
3586
+ let text;
3587
+ const compressedObj = {};
3588
+ for (let i = 0;i < arr.length; i++) {
3589
+ const tagObj = arr[i];
3590
+ const property = propName(tagObj);
3591
+ if (property !== undefined && property !== options.textNodeName) {
3592
+ const rawAttrs = stripAttributePrefix(tagObj[":@"] || {}, options.attributeNamePrefix);
3593
+ matcher.push(property, rawAttrs);
3594
+ }
3595
+ if (property === options.textNodeName) {
3596
+ if (text === undefined)
3597
+ text = tagObj[property];
3598
+ else
3599
+ text += "" + tagObj[property];
3600
+ } else if (property === undefined) {
3601
+ continue;
3602
+ } else if (tagObj[property]) {
3603
+ let val = compress(tagObj[property], options, matcher, readonlyMatcher);
3604
+ const isLeaf = isLeafTag(val, options);
3605
+ if (Object.keys(val).length === 0 && options.alwaysCreateTextNode) {
3606
+ val[options.textNodeName] = "";
3607
+ }
3608
+ if (tagObj[":@"]) {
3609
+ assignAttributes(val, tagObj[":@"], readonlyMatcher, options);
3610
+ } else if (Object.keys(val).length === 1 && val[options.textNodeName] !== undefined && !options.alwaysCreateTextNode) {
3611
+ val = val[options.textNodeName];
3612
+ } else if (Object.keys(val).length === 0) {
3613
+ if (options.alwaysCreateTextNode)
3614
+ val[options.textNodeName] = "";
3615
+ else
3616
+ val = "";
3617
+ }
3618
+ if (tagObj[METADATA_SYMBOL2] !== undefined && typeof val === "object" && val !== null) {
3619
+ val[METADATA_SYMBOL2] = tagObj[METADATA_SYMBOL2];
3620
+ }
3621
+ if (compressedObj[property] !== undefined && Object.prototype.hasOwnProperty.call(compressedObj, property)) {
3622
+ if (!Array.isArray(compressedObj[property])) {
3623
+ compressedObj[property] = [compressedObj[property]];
3624
+ }
3625
+ compressedObj[property].push(val);
3626
+ } else {
3627
+ const jPathOrMatcher = options.jPath ? readonlyMatcher.toString() : readonlyMatcher;
3628
+ if (options.isArray(property, jPathOrMatcher, isLeaf)) {
3629
+ compressedObj[property] = [val];
3630
+ } else {
3631
+ compressedObj[property] = val;
3632
+ }
3633
+ }
3634
+ if (property !== undefined && property !== options.textNodeName) {
3635
+ matcher.pop();
3636
+ }
3637
+ }
3638
+ }
3639
+ if (typeof text === "string") {
3640
+ if (text.length > 0)
3641
+ compressedObj[options.textNodeName] = text;
3642
+ } else if (text !== undefined)
3643
+ compressedObj[options.textNodeName] = text;
3644
+ return compressedObj;
3645
+ }
3646
+ function propName(obj) {
3647
+ const keys = Object.keys(obj);
3648
+ for (let i = 0;i < keys.length; i++) {
3649
+ const key = keys[i];
3650
+ if (key !== ":@")
3651
+ return key;
3652
+ }
3653
+ }
3654
+ function assignAttributes(obj, attrMap, readonlyMatcher, options) {
3655
+ if (attrMap) {
3656
+ const keys = Object.keys(attrMap);
3657
+ const len = keys.length;
3658
+ for (let i = 0;i < len; i++) {
3659
+ const atrrName = keys[i];
3660
+ const rawAttrName = atrrName.startsWith(options.attributeNamePrefix) ? atrrName.substring(options.attributeNamePrefix.length) : atrrName;
3661
+ const jPathOrMatcher = options.jPath ? readonlyMatcher.toString() + "." + rawAttrName : readonlyMatcher;
3662
+ if (options.isArray(atrrName, jPathOrMatcher, true, true)) {
3663
+ obj[atrrName] = [attrMap[atrrName]];
3664
+ } else {
3665
+ obj[atrrName] = attrMap[atrrName];
3666
+ }
3667
+ }
3668
+ }
3669
+ }
3670
+ function isLeafTag(obj, options) {
3671
+ const { textNodeName } = options;
3672
+ const propCount = Object.keys(obj).length;
3673
+ if (propCount === 0) {
3674
+ return true;
3675
+ }
3676
+ if (propCount === 1 && (obj[textNodeName] || typeof obj[textNodeName] === "boolean" || obj[textNodeName] === 0)) {
3677
+ return true;
3678
+ }
3679
+ return false;
3680
+ }
3681
+
3682
+ // node_modules/fast-xml-parser/src/xmlparser/XMLParser.js
3683
+ class XMLParser {
3684
+ constructor(options) {
3685
+ this.externalEntities = {};
3686
+ this.options = buildOptions(options);
3687
+ }
3688
+ parse(xmlData, validationOption) {
3689
+ if (typeof xmlData !== "string" && xmlData.toString) {
3690
+ if (xmlData instanceof Uint8Array && !(typeof Buffer !== "undefined" && Buffer.isBuffer(xmlData))) {
3691
+ xmlData = new TextDecoder("utf-8", { ignoreBOM: true }).decode(xmlData);
3692
+ } else {
3693
+ xmlData = xmlData.toString();
3694
+ }
3695
+ } else if (typeof xmlData !== "string") {
3696
+ throw new Error("XML data is accepted in String or Bytes[] form.");
3697
+ }
3698
+ if (validationOption) {
3699
+ if (validationOption === true)
3700
+ validationOption = {};
3701
+ const result = validate(xmlData, validationOption);
3702
+ if (result !== true) {
3703
+ throw Error(`${result.err.msg}:${result.err.line}:${result.err.col}`);
3704
+ }
3705
+ }
3706
+ const orderedObjParser = new OrderedObjParser(this.options, this.externalEntities);
3707
+ const orderedResult = orderedObjParser.parseXml(xmlData);
3708
+ if (this.options.preserveOrder || orderedResult === undefined)
3709
+ return orderedResult;
3710
+ else
3711
+ return prettify(orderedResult, this.options, orderedObjParser.matcher, orderedObjParser.readonlyMatcher);
3712
+ }
3713
+ addEntity(key, value) {
3714
+ if (value.indexOf("&") !== -1) {
3715
+ throw new Error("Entity value can't have '&'");
3716
+ } else if (key.indexOf("&") !== -1 || key.indexOf(";") !== -1) {
3717
+ throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");
3718
+ } else if (value === "&") {
3719
+ throw new Error("An entity with value '&' is not permitted");
3720
+ } else {
3721
+ this.externalEntities[key] = value;
3722
+ }
3723
+ }
3724
+ static getMetaDataSymbol() {
3725
+ return XmlNode.getMetaDataSymbol();
3726
+ }
3727
+ }
3728
+
3729
+ // node_modules/fast-xml-parser/src/fxp.js
3730
+ var XMLValidator = {
3731
+ validate
3732
+ };
3733
+
3734
+ // plugins/quality/shared/coverage.ts
3735
+ var normalizePath = (path, root) => {
3736
+ let p = path.trim().replaceAll("\\", "/");
3737
+ if (root !== undefined) {
3738
+ const prefix = `${root.replaceAll("\\", "/").replace(/\/+$/, "")}/`;
3739
+ if (p.startsWith(prefix))
3740
+ p = p.slice(prefix.length);
3741
+ }
3742
+ return p.replace(/^(\.\/)+/, "");
3743
+ };
3744
+ function file(report, path) {
3745
+ let entry = report.get(path);
3746
+ if (entry === undefined) {
3747
+ entry = { lines: new Map, branches: new Map };
3748
+ report.set(path, entry);
3749
+ }
3750
+ return entry;
3751
+ }
3752
+ function mark(map, key, covered) {
3753
+ map.set(key, (map.get(key) ?? false) || covered);
3754
+ }
3755
+ var round2 = (n) => Math.round(n * 100) / 100;
3756
+ function addBranches(entry, line, covered, total) {
3757
+ const prior = entry.branches.get(line);
3758
+ entry.branches.set(line, {
3759
+ covered: round2(Math.max(prior?.covered ?? 0, covered)),
3760
+ total: Math.max(prior?.total ?? 0, total)
3761
+ });
3762
+ }
3763
+ function detectCoverageFormat(text) {
3764
+ const head = text.trimStart();
3765
+ if (head.startsWith("mode:"))
3766
+ return "gocover";
3767
+ if (head.startsWith("<"))
3768
+ return "cobertura";
3769
+ if (/^SF:/m.test(head))
3770
+ return "lcov";
3771
+ return;
3772
+ }
3773
+ function parseLcov(text, root) {
3774
+ const files = new Map;
3775
+ let current;
3776
+ let hasBranches = false;
3777
+ const perLine = new Map;
3778
+ const flush = () => {
3779
+ for (const [no, c] of perLine)
3780
+ if (current !== undefined)
3781
+ addBranches(current, Number(no), c.covered, c.total);
3782
+ perLine.clear();
3783
+ };
3784
+ for (const raw of text.split(/\r?\n/)) {
3785
+ const line = raw.trim();
3786
+ if (line.startsWith("SF:")) {
3787
+ flush();
3788
+ current = file(files, normalizePath(line.slice(3), root));
3789
+ } else if (line === "end_of_record") {
3790
+ flush();
3791
+ current = undefined;
3792
+ } else if (current !== undefined && line.startsWith("DA:")) {
3793
+ const [no, hits] = line.slice(3).split(",");
3794
+ const n = Number(no);
3795
+ if (Number.isInteger(n))
3796
+ mark(current.lines, n, Number(hits) > 0);
3797
+ } else if (current !== undefined && line.startsWith("BRDA:")) {
3798
+ const [no, , , taken] = line.slice(5).split(",");
3799
+ hasBranches = true;
3800
+ const c = perLine.get(no) ?? { covered: 0, total: 0 };
3801
+ c.total++;
3802
+ if (taken !== "-" && Number(taken) > 0)
3803
+ c.covered++;
3804
+ perLine.set(no, c);
3805
+ }
3806
+ }
3807
+ flush();
3808
+ return { format: "lcov", files, hasBranches };
3809
+ }
3810
+ var xml = new XMLParser({
3811
+ ignoreAttributes: false,
3812
+ attributeNamePrefix: "@_",
3813
+ parseAttributeValue: false,
3814
+ parseTagValue: false,
3815
+ isArray: (name) => ["package", "class", "line", "condition"].includes(name)
3816
+ });
3817
+ var asNodes = (value) => Array.isArray(value) ? value.filter((v) => typeof v === "object" && v !== null) : [];
3818
+ function parseCobertura(text, root) {
3819
+ const valid = XMLValidator.validate(text);
3820
+ if (valid !== true)
3821
+ throw new Error(`invalid Cobertura XML: ${valid.err.msg} (line ${valid.err.line})`);
3822
+ const doc = xml.parse(text);
3823
+ if (doc.coverage === undefined || typeof doc.coverage !== "object")
3824
+ throw new Error("not a Cobertura report: no coverage element");
3825
+ const files = new Map;
3826
+ let hasBranches = false;
3827
+ const packages = asNodes(doc.coverage.packages?.package);
3828
+ for (const pkg of packages) {
3829
+ for (const cls of asNodes(pkg.classes?.class)) {
3830
+ const name = String(cls["@_filename"] ?? "");
3831
+ if (!name)
3832
+ continue;
3833
+ const entry = file(files, normalizePath(name, root));
3834
+ for (const line of asNodes(cls.lines?.line)) {
3835
+ const n = Number(line["@_number"]);
3836
+ if (!Number.isInteger(n))
3837
+ continue;
3838
+ mark(entry.lines, n, Number(line["@_hits"]) > 0);
3839
+ const conditions = asNodes(line.conditions?.condition);
3840
+ const summary = /\((\d+)\/(\d+)\)/.exec(String(line["@_condition-coverage"] ?? ""));
3841
+ if (summary !== null) {
3842
+ hasBranches = true;
3843
+ addBranches(entry, n, Number(summary[1]), Number(summary[2]));
3844
+ } else if (conditions.length > 0) {
3845
+ hasBranches = true;
3846
+ let covered = 0;
3847
+ for (const c of conditions)
3848
+ covered += Math.min(100, Math.max(0, Number.parseFloat(String(c["@_coverage"] ?? "0")) || 0)) / 100;
3849
+ addBranches(entry, n, covered, conditions.length);
3850
+ }
3851
+ }
3852
+ }
3853
+ }
3854
+ return { format: "cobertura", files, hasBranches };
3855
+ }
3856
+ function parseGoCover(text, root) {
3857
+ const files = new Map;
3858
+ for (const raw of text.split(/\r?\n/)) {
3859
+ const m = /^(.+):(\d+)\.\d+,(\d+)\.\d+ \d+ (\d+)$/.exec(raw.trim());
3860
+ if (m === null)
3861
+ continue;
3862
+ const entry = file(files, normalizePath(m[1], root));
3863
+ for (let n = Number(m[2]);n <= Number(m[3]); n++)
3864
+ mark(entry.lines, n, Number(m[4]) > 0);
3865
+ }
3866
+ return { format: "gocover", files, hasBranches: false };
3867
+ }
3868
+ function parseCoverage(text, format, root) {
3869
+ const kind = format ?? detectCoverageFormat(text);
3870
+ if (kind === undefined)
3871
+ throw new Error("cannot detect the coverage format; pass format: lcov, cobertura or gocover");
3872
+ if (kind === "lcov")
3873
+ return parseLcov(text, root);
3874
+ if (kind === "cobertura")
3875
+ return parseCobertura(text, root);
3876
+ return parseGoCover(text, root);
3877
+ }
3878
+ function totals(report, branches) {
3879
+ let covered = 0;
3880
+ let total = 0;
3881
+ for (const f of report.files.values()) {
3882
+ if (branches) {
3883
+ for (const count of f.branches.values()) {
3884
+ total += count.total;
3885
+ covered += count.covered;
3886
+ }
3887
+ continue;
3888
+ }
3889
+ for (const hit of f.lines.values()) {
3890
+ total++;
3891
+ if (hit)
3892
+ covered++;
3893
+ }
3894
+ }
3895
+ return { covered: round2(covered), total, percent: percent(covered, total) };
3896
+ }
3897
+ function compareCoverage(baseline, candidate) {
3898
+ const bothBranches = baseline.hasBranches && candidate.hasBranches;
3899
+ const lost = [];
3900
+ const disappeared = [];
3901
+ let gained = 0;
3902
+ for (const [name, base] of baseline.files) {
3903
+ const cand = candidate.files.get(name);
3904
+ const baseLines = [...base.lines].filter(([, hit]) => hit).map(([n]) => n);
3905
+ if (cand === undefined) {
3906
+ if (baseLines.length > 0 || bothBranches && [...base.branches.values()].some((c) => c.covered > 0))
3907
+ disappeared.push({ file: name, coveredLines: baseLines.length });
3908
+ continue;
3909
+ }
3910
+ const lines = baseLines.filter((n) => cand.lines.get(n) !== true).sort((a, b) => a - b);
3911
+ const branches = [];
3912
+ let lostBranchCount = 0;
3913
+ if (bothBranches) {
3914
+ for (const [n, count] of [...base.branches].sort((x, y) => x[0] - y[0])) {
3915
+ const now = cand.branches.get(n);
3916
+ if (count.covered > (now?.covered ?? 0)) {
3917
+ branches.push(`${n} (${count.covered}/${count.total} -> ${now?.covered ?? 0}/${now?.total ?? 0})`);
3918
+ lostBranchCount = round2(lostBranchCount + count.covered - (now?.covered ?? 0));
3919
+ }
3920
+ }
3921
+ }
3922
+ if (lines.length > 0 || branches.length > 0)
3923
+ lost.push({ file: name, lines, branches, lostLineCount: lines.length, lostBranchCount });
3924
+ }
3925
+ for (const [name, cand] of candidate.files) {
3926
+ const base = baseline.files.get(name);
3927
+ for (const [n, hit] of cand.lines)
3928
+ if (hit && base?.lines.get(n) !== true)
3929
+ gained++;
3930
+ }
3931
+ return {
3932
+ kind: "coverage",
3933
+ baselineFormat: baseline.format,
3934
+ candidateFormat: candidate.format,
3935
+ lines: { baseline: totals(baseline, false), candidate: totals(candidate, false) },
3936
+ branches: bothBranches ? { baseline: totals(baseline, true), candidate: totals(candidate, true) } : null,
3937
+ lost: lost.sort((a, b) => b.lostLineCount + b.lostBranchCount - (a.lostLineCount + a.lostBranchCount) || a.file.localeCompare(b.file)),
3938
+ disappeared: disappeared.sort((a, b) => a.file.localeCompare(b.file)),
3939
+ gained
3940
+ };
3941
+ }
3942
+ var fmt = (t) => `${t.percent}% (${t.covered}/${t.total})`;
3943
+ function formatCoverage(c, maxFiles = 15) {
3944
+ const lines = [
3945
+ `coverage: lines ${fmt(c.lines.baseline)} -> ${fmt(c.lines.candidate)}`,
3946
+ c.branches ? `branches ${fmt(c.branches.baseline)} -> ${fmt(c.branches.candidate)}` : "branches: not measured (a report has no branch data)"
3947
+ ];
3948
+ const nothing = c.lost.length === 0 && c.disappeared.length === 0;
3949
+ lines.push(nothing ? "no baseline-covered line or branch is uncovered in the candidate" : "LOST COVERAGE (covered in baseline, not in candidate):");
3950
+ for (const f of c.lost.slice(0, maxFiles)) {
3951
+ const parts = [];
3952
+ if (f.lines.length > 0)
3953
+ parts.push(`lines ${compactRanges(f.lines)}`);
3954
+ if (f.branches.length > 0)
3955
+ parts.push(`${f.lostBranchCount} branch(es) ${f.branches.slice(0, 6).join(" ")}${f.branches.length > 6 ? " ..." : ""}`);
3956
+ lines.push(` ${f.file}: ${parts.join("; ")}`);
3957
+ }
3958
+ if (c.lost.length > maxFiles)
3959
+ lines.push(` ... +${c.lost.length - maxFiles} more files`);
3960
+ if (c.disappeared.length > 0) {
3961
+ lines.push(`files missing from the candidate (${c.disappeared.length}):`);
3962
+ for (const d of c.disappeared.slice(0, maxFiles))
3963
+ lines.push(` ${d.file} (${d.coveredLines} covered lines in baseline)`);
3964
+ if (c.disappeared.length > maxFiles)
3965
+ lines.push(` ... +${c.disappeared.length - maxFiles} more`);
3966
+ }
3967
+ if (c.gained > 0)
3968
+ lines.push(`lines newly covered in the candidate: ${c.gained}`);
3969
+ return capText(lines);
3970
+ }
3971
+
3972
+ // plugins/quality/shared/junit.ts
3973
+ var parser = new XMLParser({
3974
+ ignoreAttributes: false,
3975
+ attributeNamePrefix: "@_",
3976
+ parseAttributeValue: false,
3977
+ parseTagValue: false,
3978
+ trimValues: true,
3979
+ isArray: (name) => name === "testcase"
3980
+ });
3981
+ var isNode = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
3982
+ function count(value) {
3983
+ return Array.isArray(value) ? value.length : value === undefined ? 0 : 1;
3984
+ }
3985
+ function caseStatus(node) {
3986
+ if ("failure" in node || "rerunFailure" in node)
3987
+ return "failed";
3988
+ if ("error" in node || "rerunError" in node)
3989
+ return "error";
3990
+ if ("skipped" in node)
3991
+ return "skipped";
3992
+ return "passed";
3993
+ }
3994
+ var TIMEOUT = /time(?:d)?[\s-]?out/i;
3995
+ var FAILURE_KEYS = ["failure", "error", "rerunFailure", "rerunError"];
3996
+ var BODY_LIMIT = 2000;
3997
+ var str = (value) => typeof value === "string" ? value : "";
3998
+ function elementText(value) {
3999
+ if (typeof value === "string")
4000
+ return value;
4001
+ if (Array.isArray(value))
4002
+ return value.map(elementText).join(`
4003
+ `);
4004
+ return isNode(value) ? str(value["#text"]) : "";
4005
+ }
4006
+ function classifyFailure(node) {
4007
+ for (const key of FAILURE_KEYS) {
4008
+ const value = node[key];
4009
+ for (const item of Array.isArray(value) ? value : [value]) {
4010
+ const fields = isNode(item) ? [str(item["@_message"]), str(item["@_type"]), str(item["#text"]).slice(0, BODY_LIMIT)] : [str(item).slice(0, BODY_LIMIT)];
4011
+ if (fields.some((field) => TIMEOUT.test(field)))
4012
+ return "timeout";
4013
+ }
4014
+ }
4015
+ return "other";
4016
+ }
4017
+ function stderrLines(value) {
4018
+ return elementText(value).split(/\r?\n/).filter((line) => line.trim() !== "").length;
4019
+ }
4020
+ function nestedStderrLines(node) {
4021
+ if (Array.isArray(node))
4022
+ return node.reduce((sum, item) => sum + nestedStderrLines(item), 0);
4023
+ if (!isNode(node))
4024
+ return 0;
4025
+ let lines = 0;
4026
+ for (const [key, value] of Object.entries(node)) {
4027
+ if (key.startsWith("@_"))
4028
+ continue;
4029
+ lines += key === "system-err" ? stderrLines(value) : nestedStderrLines(value);
4030
+ }
4031
+ return lines;
4032
+ }
4033
+ function collect(node, out) {
4034
+ if (Array.isArray(node)) {
4035
+ for (const item of node)
4036
+ collect(item, out);
4037
+ return;
4038
+ }
4039
+ if (!isNode(node))
4040
+ return;
4041
+ for (const [key, value] of Object.entries(node)) {
4042
+ if (key.startsWith("@_"))
4043
+ continue;
4044
+ if (key === "system-err") {
4045
+ out.stderrLines += stderrLines(value);
4046
+ continue;
4047
+ }
4048
+ if (key !== "testcase") {
4049
+ collect(value, out);
4050
+ continue;
4051
+ }
4052
+ for (const raw of value) {
4053
+ const tc = isNode(raw) ? raw : {};
4054
+ const name = String(tc["@_name"] ?? "");
4055
+ const classname = String(tc["@_classname"] ?? "");
4056
+ const file = tc["@_file"] === undefined ? "" : String(tc["@_file"]);
4057
+ const label = [classname, name].filter(Boolean).join(" :: ");
4058
+ const time = Number.parseFloat(String(tc["@_time"] ?? "0"));
4059
+ const status = caseStatus(tc);
4060
+ out.stderrLines += nestedStderrLines(tc);
4061
+ out.cases.push({
4062
+ id: file ? `${file} :: ${label}` : label,
4063
+ status,
4064
+ time: Number.isFinite(time) ? time : 0,
4065
+ retries: count(tc.flakyFailure) + count(tc.flakyError),
4066
+ ...status === "failed" || status === "error" ? { failureKind: classifyFailure(tc) } : {}
4067
+ });
4068
+ }
4069
+ }
4070
+ }
4071
+ function parseJunitReport(xml) {
4072
+ const valid = XMLValidator.validate(xml);
4073
+ if (valid !== true)
4074
+ throw new Error(`invalid XML: ${valid.err.msg} (line ${valid.err.line})`);
4075
+ const doc = parser.parse(xml);
4076
+ if (!("testsuites" in doc) && !("testsuite" in doc))
4077
+ throw new Error("not a JUnit report: no testsuite element");
4078
+ const out = { cases: [], stderrLines: 0 };
4079
+ collect(doc, out);
4080
+ return out;
4081
+ }
4082
+
4083
+ // plugins/quality/shared/mutation.ts
4084
+ var isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
4085
+ function detectMutationFormat(data) {
4086
+ if (!isObj(data))
4087
+ return;
4088
+ if (isObj(data.files) && "schemaVersion" in data)
4089
+ return "mutation-testing";
4090
+ if (Array.isArray(data.outcomes))
4091
+ return "cargo-mutants";
4092
+ if (Array.isArray(data.files) && "go_module" in data)
4093
+ return "gremlins";
4094
+ return;
4095
+ }
4096
+ function add(into, mutant) {
4097
+ const base = `${mutant.file}|${mutant.mutator}|${mutant.location}|${mutant.replacement}`;
4098
+ let key = base;
4099
+ for (let n = 2;into.has(key); n++)
4100
+ key = `${base}#${n}`;
4101
+ into.set(key, { ...mutant, key });
4102
+ }
4103
+ var STRYKER = {
4104
+ Killed: "detected",
4105
+ Timeout: "detected",
4106
+ Survived: "survived",
4107
+ NoCoverage: "nocoverage"
4108
+ };
4109
+ var pos = (p) => isObj(p) ? `${p.line}:${p.column}` : "?";
4110
+ var span = (loc) => isObj(loc) ? `${pos(loc.start)}-${pos(loc.end)}` : "?";
4111
+ function parseMutationTesting(data) {
4112
+ const mutants = new Map;
4113
+ for (const [name, entry] of Object.entries(isObj(data.files) ? data.files : {})) {
4114
+ if (!isObj(entry) || !Array.isArray(entry.mutants))
4115
+ continue;
4116
+ for (const m of entry.mutants) {
4117
+ if (!isObj(m))
4118
+ continue;
4119
+ const status = String(m.status ?? "");
4120
+ add(mutants, {
4121
+ file: name.replaceAll("\\", "/"),
4122
+ mutator: String(m.mutatorName ?? ""),
4123
+ location: span(m.location),
4124
+ replacement: typeof m.replacement === "string" ? m.replacement : "",
4125
+ status,
4126
+ class: STRYKER[status] ?? "ignored"
4127
+ });
4128
+ }
4129
+ }
4130
+ return { format: "mutation-testing", mutants };
4131
+ }
4132
+ var CARGO = { CaughtMutant: "detected", Timeout: "detected", MissedMutant: "survived" };
4133
+ function parseCargoMutants(data) {
4134
+ const mutants = new Map;
4135
+ for (const outcome of Array.isArray(data.outcomes) ? data.outcomes : []) {
4136
+ if (!isObj(outcome) || !isObj(outcome.scenario) || !isObj(outcome.scenario.Mutant))
4137
+ continue;
4138
+ const m = outcome.scenario.Mutant;
4139
+ const status = String(outcome.summary ?? "");
4140
+ add(mutants, {
4141
+ file: String(m.file ?? "").replaceAll("\\", "/"),
4142
+ mutator: String(m.genre ?? ""),
4143
+ location: span(m.span),
4144
+ replacement: String(m.replacement ?? ""),
4145
+ status,
4146
+ class: CARGO[status] ?? "ignored"
4147
+ });
4148
+ }
4149
+ return { format: "cargo-mutants", mutants };
4150
+ }
4151
+ var GREMLINS = {
4152
+ KILLED: "detected",
4153
+ "TIMED OUT": "detected",
4154
+ LIVED: "survived",
4155
+ "NOT COVERED": "nocoverage"
4156
+ };
4157
+ function parseGremlins(data) {
4158
+ const mutants = new Map;
4159
+ for (const f of Array.isArray(data.files) ? data.files : []) {
4160
+ if (!isObj(f) || !Array.isArray(f.mutations))
4161
+ continue;
4162
+ for (const m of f.mutations) {
4163
+ if (!isObj(m))
4164
+ continue;
4165
+ const status = String(m.status ?? "");
4166
+ add(mutants, {
4167
+ file: String(f.file_name ?? "").replaceAll("\\", "/"),
4168
+ mutator: String(m.type ?? ""),
4169
+ location: `${m.line}:${m.column}`,
4170
+ replacement: "",
4171
+ status,
4172
+ class: GREMLINS[status] ?? "ignored"
4173
+ });
4174
+ }
4175
+ }
4176
+ return { format: "gremlins", mutants };
4177
+ }
4178
+ function parseMutation(text, format) {
4179
+ const data = JSON.parse(text);
4180
+ const kind = format ?? detectMutationFormat(data);
4181
+ if (kind === undefined || !isObj(data))
4182
+ throw new Error("cannot detect the mutation format; pass format: mutation-testing, cargo-mutants or gremlins");
4183
+ if (kind === "mutation-testing")
4184
+ return parseMutationTesting(data);
4185
+ if (kind === "cargo-mutants")
4186
+ return parseCargoMutants(data);
4187
+ return parseGremlins(data);
4188
+ }
4189
+ function scoreOf(report) {
4190
+ const s = { detected: 0, survived: 0, nocoverage: 0, ignored: 0, score: 0 };
4191
+ for (const m of report.mutants.values())
4192
+ s[m.class]++;
4193
+ s.score = percent(s.detected, s.detected + s.survived + s.nocoverage);
4194
+ return s;
4195
+ }
4196
+ var ref = (m, other) => ({
4197
+ key: m.key,
4198
+ file: m.file,
4199
+ mutator: m.mutator,
4200
+ location: m.location,
4201
+ replacement: m.replacement,
4202
+ was: m.status,
4203
+ now: other?.status ?? "absent"
4204
+ });
4205
+ var undetected = (c) => c === "survived" || c === "nocoverage";
4206
+ function compareMutation(baseline, candidate) {
4207
+ const lostProtection = [];
4208
+ const newlyKilled = [];
4209
+ const onlyInBaseline = [];
4210
+ const onlyInCandidate = [];
4211
+ for (const [key, base] of baseline.mutants) {
4212
+ const cand = candidate.mutants.get(key);
4213
+ if (cand === undefined)
4214
+ onlyInBaseline.push(ref(base));
4215
+ else if (base.class === "detected" && undetected(cand.class))
4216
+ lostProtection.push(ref(base, cand));
4217
+ else if (undetected(base.class) && cand.class === "detected")
4218
+ newlyKilled.push({ ...ref(base, cand) });
4219
+ }
4220
+ for (const [key, cand] of candidate.mutants)
4221
+ if (!baseline.mutants.has(key))
4222
+ onlyInCandidate.push(ref(cand));
4223
+ return {
4224
+ kind: "mutation",
4225
+ baselineFormat: baseline.format,
4226
+ candidateFormat: candidate.format,
4227
+ baseline: scoreOf(baseline),
4228
+ candidate: scoreOf(candidate),
4229
+ lostProtection,
4230
+ newlyKilled,
4231
+ onlyInBaseline,
4232
+ onlyInCandidate
4233
+ };
4234
+ }
4235
+ var describe = (r) => `${r.file}:${r.location.split("-")[0]} ${r.mutator}${r.replacement ? ` -> ${r.replacement.replace(/\s+/g, " ").slice(0, 40)}` : ""}`;
4236
+ function section(title, refs, limit, show) {
4237
+ if (refs.length === 0)
4238
+ return [];
4239
+ const out = [`${title} (${refs.length}):`, ...refs.slice(0, limit).map((r) => ` ${show(r)}`)];
4240
+ if (refs.length > limit)
4241
+ out.push(` ... +${refs.length - limit} more`);
4242
+ return out;
4243
+ }
4244
+ var fmtScore = (s) => `${s.score}% (${s.detected} detected, ${s.survived} survived, ${s.nocoverage} no coverage, ${s.ignored} ignored)`;
4245
+ function formatMutation(c) {
4246
+ const lines = [`mutation score: ${fmtScore(c.baseline)} -> ${fmtScore(c.candidate)}`];
4247
+ lines.push(...section("LOST PROTECTION (detected in baseline, survived or uncovered in candidate)", c.lostProtection, 25, (r) => `${describe(r)} [${r.was} -> ${r.now}]`));
4248
+ if (c.lostProtection.length === 0)
4249
+ lines.push("lost protection: none");
4250
+ lines.push(...section("newly killed", c.newlyKilled, 8, describe), ...section("only in baseline (candidate has no such mutant)", c.onlyInBaseline, 8, (r) => `${describe(r)} [${r.was}]`), ...section("only in candidate", c.onlyInCandidate, 8, (r) => `${describe(r)} [${r.was}]`));
4251
+ return capText(lines);
4252
+ }
4253
+
4254
+ // plugins/quality/shared/test-repeat.ts
4255
+ var NOISY_STDERR_LINES = 1000;
4256
+ var NOISY_FILE_BYTES = 5000000;
4257
+ var isShuffledMode = (mode) => mode !== undefined && /shuffle|random/i.test(mode);
4258
+ var SLOWEST = 10;
4259
+ function foldRun(cases) {
4260
+ const folded = new Map;
4261
+ for (const c of cases) {
4262
+ const status = c.status === "error" || c.status === "failed" ? "failed" : c.status;
4263
+ const kind = status === "failed" ? c.failureKind ?? "other" : undefined;
4264
+ const prior = folded.get(c.id);
4265
+ if (prior === undefined) {
4266
+ folded.set(c.id, { status, time: c.time, retries: c.retries, kind });
4267
+ continue;
4268
+ }
4269
+ prior.time += c.time;
4270
+ prior.retries += c.retries;
4271
+ if (status === "failed")
4272
+ prior.kind = prior.kind === "timeout" || kind === "timeout" ? "timeout" : "other";
4273
+ if (status === "failed" || status === "passed" && prior.status === "skipped")
4274
+ prior.status = status;
4275
+ }
4276
+ return folded;
4277
+ }
4278
+ var newTally = () => ({ passed: 0, failed: 0, skipped: 0, times: [], retried: 0, timeouts: 0, other: 0 });
4279
+ function runStats(record, stderrLimit, bytesLimit) {
4280
+ const testSeconds = record.report === "used" ? record.cases.reduce((sum, c) => sum + c.time, 0) : undefined;
4281
+ return {
4282
+ run: record.run,
4283
+ mode: record.mode,
4284
+ fileBytes: record.fileBytes,
4285
+ stderrLines: record.stderrLines,
4286
+ testSeconds,
4287
+ noisy: (record.stderrLines ?? 0) > stderrLimit || (record.fileBytes ?? 0) > bytesLimit
4288
+ };
4289
+ }
4290
+ function summarizeRuns(records, options = {}) {
4291
+ const stderrLimit = options.noisyStderrLines ?? NOISY_STDERR_LINES;
4292
+ const bytesLimit = options.noisyFileBytes ?? NOISY_FILE_BYTES;
4293
+ const used = records.filter((r) => r.report === "used");
4294
+ const perTest = new Map;
4295
+ const unshuffled = new Map;
4296
+ const defaultRuns = used.filter((r) => !isShuffledMode(r.mode)).length;
4297
+ const shuffledTally = new Map;
4298
+ const failedModes = new Map;
4299
+ for (const record of used) {
4300
+ const shuffled = isShuffledMode(record.mode);
4301
+ for (const [id, c] of foldRun(record.cases)) {
4302
+ const stats = perTest.get(id) ?? newTally();
4303
+ stats[c.status]++;
4304
+ if (c.status !== "skipped")
4305
+ stats.times.push(c.time);
4306
+ if (c.retries > 0)
4307
+ stats.retried++;
4308
+ if (c.kind === "timeout")
4309
+ stats.timeouts++;
4310
+ else if (c.kind === "other")
4311
+ stats.other++;
4312
+ perTest.set(id, stats);
4313
+ if (!shuffled) {
4314
+ const base = unshuffled.get(id) ?? newTally();
4315
+ base[c.status]++;
4316
+ unshuffled.set(id, base);
4317
+ } else {
4318
+ const sh = shuffledTally.get(id) ?? newTally();
4319
+ sh[c.status]++;
4320
+ shuffledTally.set(id, sh);
4321
+ if (c.status === "failed")
4322
+ failedModes.set(id, (failedModes.get(id) ?? new Set).add(record.mode));
4323
+ }
4324
+ }
4325
+ }
4326
+ const all = [...perTest].map(([id, s]) => ({
4327
+ id,
4328
+ passed: s.passed,
4329
+ failed: s.failed,
4330
+ skipped: s.skipped,
4331
+ medianSeconds: median(s.times),
4332
+ retried: s.retried,
4333
+ timeouts: s.timeouts,
4334
+ otherFailures: s.other
4335
+ }));
4336
+ const byId = (a, b) => a.id.localeCompare(b.id);
4337
+ const given = records.some((r) => r.exitCode !== undefined);
4338
+ const exitCodes = given ? records.map((r) => r.exitCode ?? null) : null;
4339
+ const knownCodes = exitCodes?.filter((c) => c !== null);
4340
+ const known = knownCodes === undefined || knownCodes.length === 0 ? null : knownCodes;
4341
+ const modeCounts = new Map;
4342
+ for (const r of records)
4343
+ if (r.mode !== undefined)
4344
+ modeCounts.set(r.mode, (modeCounts.get(r.mode) ?? 0) + 1);
4345
+ const flakyIn = (t) => {
4346
+ const base = unshuffled.get(t.id);
4347
+ return base !== undefined && base.passed > 0 && base.failed > 0;
4348
+ };
4349
+ const withModes = (t) => ({ ...t, failedModes: [...failedModes.get(t.id) ?? []].sort() });
4350
+ const shuffledFail = all.filter((t) => failedModes.has(t.id));
4351
+ const defaultPass = (t) => (unshuffled.get(t.id)?.passed ?? 0) > 0;
4352
+ const defaultFail = (t) => (unshuffled.get(t.id)?.failed ?? 0) > 0;
4353
+ const orderDependent = shuffledFail.filter((t) => defaultPass(t) && !defaultFail(t)).map(withModes).sort(byId);
4354
+ const failsDefaultPassesShuffled = (t) => defaultFail(t) && !defaultPass(t) && (shuffledTally.get(t.id)?.passed ?? 0) > 0;
4355
+ const failsEveryDefault = (t) => (unshuffled.get(t.id)?.failed ?? 0) === defaultRuns;
4356
+ const failedDefaultPassedShuffled = all.filter((t) => failsDefaultPassesShuffled(t) && failsEveryDefault(t)).sort(byId);
4357
+ const incompleteDefaults = all.filter((t) => failsDefaultPassesShuffled(t) && !failsEveryDefault(t)).map(withModes);
4358
+ const inconclusive = [...shuffledFail.filter((t) => !defaultPass(t) && !defaultFail(t)).map(withModes), ...incompleteDefaults].sort(byId);
4359
+ return {
4360
+ runs: records.length,
4361
+ exitCodes,
4362
+ exitCodesAgree: known === null ? null : new Set(known).size <= 1,
4363
+ exitCodesUnknown: exitCodes === null ? 0 : exitCodes.length - (known?.length ?? 0),
4364
+ reportRuns: used.length,
4365
+ unreadable: records.filter((r) => r.report !== "used").map((r) => ({ run: r.run, reason: r.reason ?? "unreadable" })),
4366
+ totalCases: all.length,
4367
+ flaky: all.filter(flakyIn).sort(byId),
4368
+ orderDependent,
4369
+ inconclusive,
4370
+ failedDefaultPassedShuffled,
4371
+ noisyStderrLines: stderrLimit,
4372
+ noisyFileBytes: bytesLimit,
4373
+ modes: [...modeCounts].map(([mode, runs]) => ({ mode, runs })),
4374
+ runStats: records.map((r) => runStats(r, stderrLimit, bytesLimit)),
4375
+ failedEveryRun: all.filter((t) => used.length > 0 && t.failed === used.length).sort(byId),
4376
+ slowest: all.filter((t) => Number.isFinite(t.medianSeconds)).sort((a, b) => b.medianSeconds - a.medianSeconds || byId(a, b)).slice(0, SLOWEST),
4377
+ retriedInRun: all.filter((t) => t.retried > 0 && t.failed === 0).map((t) => t.id).sort()
4378
+ };
4379
+ }
4380
+ var secs = (n) => `${n < 10 ? n.toFixed(2) : n.toFixed(1)}s`;
4381
+ function list(title, items, show, limit) {
4382
+ if (items.length === 0)
4383
+ return [];
4384
+ const lines = [`${title} (${items.length}):`, ...items.slice(0, limit).map((i) => ` ${show(i)}`)];
4385
+ if (items.length > limit)
4386
+ lines.push(` ... +${items.length - limit} more`);
4387
+ return lines;
4388
+ }
4389
+ var failureSplit = (t) => `fail ${t.failed} (timeout ${t.timeouts}, assertion/error ${t.otherFailures})`;
4390
+ var mb = (bytes) => bytes < 1e6 ? `${bytes} bytes` : `${(bytes / 1e6).toFixed(1)} MB`;
4391
+ var LABEL_LIMIT = 30;
4392
+ var label = (text) => text.length > LABEL_LIMIT ? `${text.slice(0, LABEL_LIMIT - 3)}...` : text;
4393
+ function runLine(r) {
4394
+ const parts = [
4395
+ r.fileBytes === undefined ? undefined : mb(r.fileBytes),
4396
+ r.stderrLines === undefined ? undefined : `${r.stderrLines} stderr lines`,
4397
+ r.testSeconds === undefined ? undefined : `summed test time ${secs(r.testSeconds)}`
4398
+ ].filter((p) => p !== undefined);
4399
+ return `run ${r.run}${r.mode === undefined ? "" : ` [${label(r.mode)}]`}: ${parts.join(", ")}${r.noisy ? " NOISY" : ""}`;
4400
+ }
4401
+ var MAX_FAILED_MODES = 3;
4402
+ var failedIn = (t) => {
4403
+ if (t.failedModes.length === 0)
4404
+ return "default runs incomplete (skipped or absent)";
4405
+ const more = t.failedModes.length > MAX_FAILED_MODES ? `, +${t.failedModes.length - MAX_FAILED_MODES} more` : "";
4406
+ return `failed in ${t.failedModes.slice(0, MAX_FAILED_MODES).map(label).join(", ")}${more}`;
4407
+ };
4408
+ var MAX_RUN_LINES = 8;
4409
+ var MAX_MODES = 6;
4410
+ function formatSummary(summary) {
4411
+ const lines = [`Summarized ${summary.runs} report(s); readable: ${summary.reportRuns}; test cases: ${summary.totalCases}`];
4412
+ if (summary.exitCodes !== null) {
4413
+ const known = summary.exitCodes.filter((c) => c !== null);
4414
+ const failed = known.filter((c) => c !== 0).length;
4415
+ lines.push(`exit codes: ${summary.exitCodes.map((c) => c === null ? "unknown" : String(c)).join(" ")} (${known.length - failed} zero, ${failed} non-zero, ${summary.exitCodesUnknown} unknown)`);
4416
+ if (summary.exitCodesAgree === false)
4417
+ lines.push("exit codes differ between runs: the suite is flaky");
4418
+ }
4419
+ for (const { run, reason } of summary.unreadable.slice(0, 10))
4420
+ lines.push(`report ${run}: unreadable (${reason})`);
4421
+ lines.push(`findings: flaky ${summary.flaky.length}, order-dependent ${summary.orderDependent.length}, inconclusive ${summary.inconclusive.length}, failed-default-passed-shuffled ${summary.failedDefaultPassedShuffled.length}, failed-every-report ${summary.failedEveryRun.length}`, ...list("flaky (passed and failed in unshuffled runs)", summary.flaky, (t) => `${t.id} pass ${t.passed} / ${failureSplit(t)}`, 15), ...list("order-dependent (failed only in shuffled runs)", summary.orderDependent, (t) => `${t.id} ${failureSplit(t)}; ${failedIn(t)}`, 15), ...list("inconclusive (no complete default-order evidence)", summary.inconclusive, (t) => `${t.id} ${failureSplit(t)}; ${failedIn(t)}`, 15), ...list("failed in every default run, passed in a shuffled run", summary.failedDefaultPassedShuffled, (t) => `${t.id} ${failureSplit(t)}`, 15), ...list("failed in every report", summary.failedEveryRun, (t) => `${t.id} ${failureSplit(t)}`, 15), ...list("retried inside a run, then passed", summary.retriedInRun, (id) => id, 5), ...list("slowest by median", summary.slowest, (t) => `${secs(t.medianSeconds).padStart(7)} ${t.id}`, SLOWEST));
4422
+ const anyFinding = summary.flaky.length + summary.orderDependent.length + summary.inconclusive.length + summary.failedDefaultPassedShuffled.length + summary.failedEveryRun.length;
4423
+ if (summary.reportRuns > 0 && anyFinding === 0)
4424
+ lines.push("no test both passed and failed; none failed in every report");
4425
+ if (summary.modes.length > 0) {
4426
+ const shownModes = summary.modes.slice(0, MAX_MODES).map((m) => `${label(m.mode)} x${m.runs}`);
4427
+ const more = summary.modes.length > MAX_MODES ? `, +${summary.modes.length - MAX_MODES} more` : "";
4428
+ lines.push(`run modes: ${shownModes.join(", ")}${more}`);
4429
+ }
4430
+ const measured = summary.runStats.filter((r) => r.fileBytes !== undefined || r.stderrLines !== undefined || r.testSeconds !== undefined);
4431
+ const noisy = measured.filter((r) => r.noisy);
4432
+ const shown = [...noisy.slice(0, MAX_RUN_LINES), ...measured.filter((r) => !r.noisy)].slice(0, MAX_RUN_LINES);
4433
+ lines.push(...list("per-run size, stderr and summed test time", shown, runLine, MAX_RUN_LINES));
4434
+ if (noisy.length > 0)
4435
+ lines.push(`noisy runs: ${noisy.slice(0, 20).map((r) => r.run).join(", ")}${noisy.length > 20 ? ", ..." : ""} (above ${summary.noisyStderrLines} stderr lines or ${mb(summary.noisyFileBytes)}): check for a missing environment setup or unmocked I/O`);
4436
+ return capText(lines);
4437
+ }
4438
+
4439
+ // plugins/quality/shared/test-audit.ts
4440
+ var TEST_SUMMARIZE_TOOL = "quality_test_summarize";
4441
+ var TEST_COMPARE_TOOL = "quality_test_compare";
4442
+ var MAX_REPORTS = 50;
4443
+ var MAX_MODE_LENGTH = 60;
4444
+ function parseSummarizeInput(input) {
4445
+ const raw = input ?? {};
4446
+ const { reports, exitCodes, modes, noisyStderrLines, noisyFileBytes } = raw;
4447
+ if (!Array.isArray(reports) || reports.length < 1 || reports.length > MAX_REPORTS || reports.some((r) => typeof r !== "string" || r === ""))
4448
+ return `reports must be 1 to ${MAX_REPORTS} non-empty paths`;
4449
+ if (exitCodes !== undefined) {
4450
+ if (!Array.isArray(exitCodes) || exitCodes.length !== reports.length || exitCodes.some((c) => c !== null && !Number.isInteger(c)))
4451
+ return "exitCodes must be integers or null, one per report";
4452
+ }
4453
+ if (modes !== undefined) {
4454
+ if (!Array.isArray(modes) || modes.length !== reports.length || modes.some((m) => typeof m !== "string" || m.trim() === "" || m.length > MAX_MODE_LENGTH))
4455
+ return `modes must be non-empty strings of at most ${MAX_MODE_LENGTH} characters, one per report`;
4456
+ }
4457
+ for (const [name, value] of [["noisyStderrLines", noisyStderrLines], ["noisyFileBytes", noisyFileBytes]])
4458
+ if (value !== undefined && (!Number.isInteger(value) || value < 1))
4459
+ return `${name} must be a positive integer`;
4460
+ return {
4461
+ reports,
4462
+ exitCodes,
4463
+ modes,
4464
+ noisyStderrLines,
4465
+ noisyFileBytes
4466
+ };
4467
+ }
4468
+ function summarizeReports(root, raw, temporaryDirectory = opencodeTempDir()) {
4469
+ const fail = (message) => ({ content: `${TEST_SUMMARIZE_TOOL}: ${message}`, metadata: { error: message } });
4470
+ const input = parseSummarizeInput(raw);
4471
+ if (typeof input === "string")
4472
+ return fail(input);
4473
+ const roots = reportRoots(root, temporaryDirectory);
4474
+ const records = [];
4475
+ for (const [i, path] of input.reports.entries()) {
4476
+ const record = { run: i + 1, exitCode: input.exitCodes?.[i], mode: input.modes?.[i], report: "unreadable", cases: [] };
4477
+ try {
4478
+ const text = readReportFile(root, path, roots);
4479
+ record.fileBytes = Buffer.byteLength(text);
4480
+ const parsed = parseJunitReport(text);
4481
+ record.cases = parsed.cases;
4482
+ record.stderrLines = parsed.stderrLines;
4483
+ record.report = "used";
4484
+ } catch (error) {
4485
+ if (error instanceof PathError)
4486
+ return fail(`refused: ${error.message}`);
4487
+ record.reason = error instanceof Error ? error.message : String(error);
4488
+ }
4489
+ records.push(record);
4490
+ }
4491
+ const summary = summarizeRuns(records, { noisyStderrLines: input.noisyStderrLines, noisyFileBytes: input.noisyFileBytes });
4492
+ return { content: formatSummary(summary), metadata: { ...summary } };
4493
+ }
4494
+ var COVERAGE_FORMATS = ["lcov", "cobertura", "gocover"];
4495
+ var MUTATION_FORMATS = ["mutation-testing", "cargo-mutants", "gremlins"];
4496
+ function compareReports(root, input, temporaryDirectory = opencodeTempDir()) {
4497
+ const fail = (message) => ({ content: `${TEST_COMPARE_TOOL}: ${message}`, metadata: { error: message } });
4498
+ if (input.kind !== "coverage" && input.kind !== "mutation")
4499
+ return fail("kind must be coverage or mutation");
4500
+ if (typeof input.baseline !== "string" || typeof input.candidate !== "string")
4501
+ return fail("baseline and candidate must be paths");
4502
+ const allowed = input.kind === "coverage" ? COVERAGE_FORMATS : MUTATION_FORMATS;
4503
+ if (input.format !== undefined && !allowed.includes(input.format))
4504
+ return fail(`format for ${input.kind} must be one of ${allowed.join(", ")}`);
4505
+ try {
4506
+ const roots = reportRoots(root, temporaryDirectory);
4507
+ const baseText = readReportFile(root, input.baseline, roots);
4508
+ const candText = readReportFile(root, input.candidate, roots);
4509
+ if (input.kind === "coverage") {
4510
+ const format = input.format;
4511
+ const result = compareCoverage(parseCoverage(baseText, format, root), parseCoverage(candText, format, root));
4512
+ return { content: formatCoverage(result), metadata: { ...result } };
4513
+ }
4514
+ const format = input.format;
4515
+ const result = compareMutation(parseMutation(baseText, format), parseMutation(candText, format));
4516
+ const cap = (list) => list.slice(0, 200);
4517
+ return {
4518
+ content: formatMutation(result),
4519
+ metadata: {
4520
+ ...result,
4521
+ lostProtection: cap(result.lostProtection),
4522
+ newlyKilled: cap(result.newlyKilled),
4523
+ onlyInBaseline: cap(result.onlyInBaseline),
4524
+ onlyInCandidate: cap(result.onlyInCandidate),
4525
+ lostProtectionCount: result.lostProtection.length
4526
+ }
4527
+ };
4528
+ } catch (error) {
4529
+ if (error instanceof PathError)
4530
+ return fail(`refused: ${error.message}`);
4531
+ return fail(error instanceof Error ? error.message : String(error));
4532
+ }
4533
+ }
4534
+
4535
+ // plugins/quality/pi-src/quality.ts
4536
+ var PI_REPORTS_TEMP_DIR = join2(realpathSync2(tmpdir2()), "pi", "quality-test-audit");
4537
+ mkdirSync(PI_REPORTS_TEMP_DIR, { recursive: true });
4538
+ function result(output) {
4539
+ return { content: [{ type: "text", text: output.content }], details: output.metadata };
4540
+ }
4541
+ function quality_default(pi) {
4542
+ pi.registerTool({
4543
+ name: TEST_SUMMARIZE_TOOL,
4544
+ label: "Summarize test runs",
4545
+ description: `Read-only: summarize JUnit XML reports from repeated test runs; flaky, always-failing and slow tests.
4546
+ ` + "Run the test command several times through the shell, writing one JUnit report per run, then pass the paths in run " + "order. Add modes (default, shuffle-files, shuffle-tests) to split order-dependent from flaky tests. Reports timeout vs " + "assertion failures, file size and stderr lines. Reads pytest, Vitest, bun test, gotestsum and cargo-nextest JUnit. " + "Paths must be in the session or Pi's temporary directory.",
4547
+ parameters: Type.Object({
4548
+ reports: Type.Array(Type.String(), { minItems: 1, maxItems: MAX_REPORTS, description: "JUnit XML paths, one per run, in run order" }),
4549
+ exitCodes: Type.Optional(Type.Array(Type.Union([Type.Integer(), Type.Null()]), { description: "Exit code of each run, same length as reports; null when unknown" })),
4550
+ noisyStderrLines: Type.Optional(Type.Integer({ minimum: 1, description: "Flag a run above this many stderr lines; default 1000" })),
4551
+ noisyFileBytes: Type.Optional(Type.Integer({ minimum: 1, description: "Flag a run whose report passes this many bytes; default 5000000" })),
4552
+ modes: Type.Optional(Type.Array(Type.String({ maxLength: MAX_MODE_LENGTH }), { description: "Order mode of each run, same length as reports: default, shuffle-files, shuffle-tests or free text" }))
4553
+ }, { required: ["reports"], additionalProperties: false }),
4554
+ async execute(_id, raw, _signal, _update, ctx) {
4555
+ return result(summarizeReports(ctx.cwd, raw, PI_REPORTS_TEMP_DIR));
4556
+ }
4557
+ });
4558
+ pi.registerTool({
4559
+ name: TEST_COMPARE_TOOL,
4560
+ label: "Compare test protection",
4561
+ description: `Read-only: compare a baseline and a candidate coverage or mutation report to show lost test protection.
4562
+ ` + "Coverage: LCOV, Cobertura XML, Go cover profile. Mutation: Stryker/mutation-testing-report JSON, cargo-mutants " + "outcomes.json, Gremlins JSON. Both paths must be in the session or Pi's temporary directory.",
4563
+ parameters: Type.Object({
4564
+ kind: Type.Union([Type.Literal("coverage"), Type.Literal("mutation")], { description: "Report kind" }),
4565
+ baseline: Type.String({ description: "Report before the change; relative to the session directory or absolute" }),
4566
+ candidate: Type.String({ description: "Report after the change; same rules" }),
4567
+ format: Type.Optional(Type.Union([
4568
+ Type.Literal("lcov"),
4569
+ Type.Literal("cobertura"),
4570
+ Type.Literal("gocover"),
4571
+ Type.Literal("mutation-testing"),
4572
+ Type.Literal("cargo-mutants"),
4573
+ Type.Literal("gremlins")
4574
+ ], { description: "Report format; detected when omitted" }))
4575
+ }, { required: ["kind", "baseline", "candidate"], additionalProperties: false }),
4576
+ async execute(_id, raw, _signal, _update, ctx) {
4577
+ return result(compareReports(ctx.cwd, raw, PI_REPORTS_TEMP_DIR));
4578
+ }
4579
+ });
4580
+ }
4581
+ export {
4582
+ quality_default as default
4583
+ };