elit 3.3.2 → 3.3.4

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 (143) hide show
  1. package/dist/build.d.mts +1 -1
  2. package/dist/build.js +1 -0
  3. package/dist/build.js.map +1 -0
  4. package/dist/build.mjs +1 -0
  5. package/dist/build.mjs.map +1 -0
  6. package/dist/chokidar.js +1 -0
  7. package/dist/chokidar.js.map +1 -0
  8. package/dist/chokidar.mjs +1 -0
  9. package/dist/chokidar.mjs.map +1 -0
  10. package/dist/cli.js +4691 -34
  11. package/dist/config.d.mts +3 -1
  12. package/dist/config.d.ts +3 -1
  13. package/dist/config.d.ts.map +1 -1
  14. package/dist/config.js +1 -0
  15. package/dist/config.js.map +1 -0
  16. package/dist/config.mjs +1 -0
  17. package/dist/config.mjs.map +1 -0
  18. package/dist/coverage.d.mts +85 -0
  19. package/dist/coverage.d.ts +76 -0
  20. package/dist/coverage.d.ts.map +1 -0
  21. package/dist/coverage.js +1549 -0
  22. package/dist/coverage.js.map +1 -0
  23. package/dist/coverage.mjs +1520 -0
  24. package/dist/coverage.mjs.map +1 -0
  25. package/dist/database.d.mts +31 -6
  26. package/dist/database.d.ts +31 -6
  27. package/dist/database.d.ts.map +1 -1
  28. package/dist/database.js +60 -33
  29. package/dist/database.js.map +1 -0
  30. package/dist/database.mjs +60 -33
  31. package/dist/database.mjs.map +1 -0
  32. package/dist/dom.js +1 -0
  33. package/dist/dom.js.map +1 -0
  34. package/dist/dom.mjs +1 -0
  35. package/dist/dom.mjs.map +1 -0
  36. package/dist/el.js +1 -0
  37. package/dist/el.js.map +1 -0
  38. package/dist/el.mjs +1 -0
  39. package/dist/el.mjs.map +1 -0
  40. package/dist/fs.js +1 -0
  41. package/dist/fs.js.map +1 -0
  42. package/dist/fs.mjs +1 -0
  43. package/dist/fs.mjs.map +1 -0
  44. package/dist/hmr.js +1 -0
  45. package/dist/hmr.js.map +1 -0
  46. package/dist/hmr.mjs +1 -0
  47. package/dist/hmr.mjs.map +1 -0
  48. package/dist/http.js +1 -0
  49. package/dist/http.js.map +1 -0
  50. package/dist/http.mjs +1 -0
  51. package/dist/http.mjs.map +1 -0
  52. package/dist/https.d.mts +1 -1
  53. package/dist/https.js +1 -0
  54. package/dist/https.js.map +1 -0
  55. package/dist/https.mjs +1 -0
  56. package/dist/https.mjs.map +1 -0
  57. package/dist/index.d.mts +1 -1
  58. package/dist/index.js +1 -0
  59. package/dist/index.js.map +1 -0
  60. package/dist/index.mjs +1 -0
  61. package/dist/index.mjs.map +1 -0
  62. package/dist/mime-types.js +1 -0
  63. package/dist/mime-types.js.map +1 -0
  64. package/dist/mime-types.mjs +1 -0
  65. package/dist/mime-types.mjs.map +1 -0
  66. package/dist/path.js +1 -0
  67. package/dist/path.js.map +1 -0
  68. package/dist/path.mjs +1 -0
  69. package/dist/path.mjs.map +1 -0
  70. package/dist/router.js +1 -0
  71. package/dist/router.js.map +1 -0
  72. package/dist/router.mjs +1 -0
  73. package/dist/router.mjs.map +1 -0
  74. package/dist/runtime.js +1 -0
  75. package/dist/runtime.js.map +1 -0
  76. package/dist/runtime.mjs +1 -0
  77. package/dist/runtime.mjs.map +1 -0
  78. package/dist/{server-Cz3z-5ls.d.mts → server-BFTzgJpO.d.mts} +62 -1
  79. package/dist/{server-BG2CaVMh.d.ts → server-CIXtexNS.d.ts} +62 -1
  80. package/dist/server.d.mts +1 -1
  81. package/dist/server.d.ts +9 -0
  82. package/dist/server.d.ts.map +1 -1
  83. package/dist/server.js +12 -0
  84. package/dist/server.js.map +1 -0
  85. package/dist/server.mjs +12 -0
  86. package/dist/server.mjs.map +1 -0
  87. package/dist/state.d.mts +1 -1
  88. package/dist/state.js +1 -0
  89. package/dist/state.js.map +1 -0
  90. package/dist/state.mjs +1 -0
  91. package/dist/state.mjs.map +1 -0
  92. package/dist/style.js +1 -0
  93. package/dist/style.js.map +1 -0
  94. package/dist/style.mjs +1 -0
  95. package/dist/style.mjs.map +1 -0
  96. package/dist/test-globals.d.ts +184 -0
  97. package/dist/test-reporter.d.mts +77 -0
  98. package/dist/test-reporter.d.ts +73 -0
  99. package/dist/test-reporter.d.ts.map +1 -0
  100. package/dist/test-reporter.js +726 -0
  101. package/dist/test-reporter.js.map +1 -0
  102. package/dist/test-reporter.mjs +696 -0
  103. package/dist/test-reporter.mjs.map +1 -0
  104. package/dist/test-runtime.d.mts +122 -0
  105. package/dist/test-runtime.d.ts +120 -0
  106. package/dist/test-runtime.d.ts.map +1 -0
  107. package/dist/test-runtime.js +1292 -0
  108. package/dist/test-runtime.js.map +1 -0
  109. package/dist/test-runtime.mjs +1269 -0
  110. package/dist/test-runtime.mjs.map +1 -0
  111. package/dist/test.d.mts +39 -0
  112. package/dist/test.d.ts +38 -0
  113. package/dist/test.d.ts.map +1 -0
  114. package/dist/test.js +4966 -0
  115. package/dist/test.js.map +1 -0
  116. package/dist/test.mjs +4944 -0
  117. package/dist/test.mjs.map +1 -0
  118. package/dist/types.d.mts +62 -1
  119. package/dist/types.d.ts +52 -0
  120. package/dist/types.d.ts.map +1 -1
  121. package/dist/types.js +1 -0
  122. package/dist/types.js.map +1 -0
  123. package/dist/types.mjs +1 -0
  124. package/dist/types.mjs.map +1 -0
  125. package/dist/ws.js +1 -0
  126. package/dist/ws.js.map +1 -0
  127. package/dist/ws.mjs +1 -0
  128. package/dist/ws.mjs.map +1 -0
  129. package/dist/wss.js +1 -0
  130. package/dist/wss.js.map +1 -0
  131. package/dist/wss.mjs +1 -0
  132. package/dist/wss.mjs.map +1 -0
  133. package/package.json +37 -5
  134. package/src/cli.ts +169 -1
  135. package/src/config.ts +3 -1
  136. package/src/coverage.ts +1479 -0
  137. package/src/database.ts +71 -35
  138. package/src/server.ts +12 -0
  139. package/src/test-globals.d.ts +184 -0
  140. package/src/test-reporter.ts +609 -0
  141. package/src/test-runtime.ts +1359 -0
  142. package/src/test.ts +368 -0
  143. package/src/types.ts +59 -0
package/dist/test.js ADDED
@@ -0,0 +1,4966 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __esm = (fn, res) => function __init() {
9
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
+ };
11
+ var __export = (target, all) => {
12
+ for (var name in all)
13
+ __defProp(target, name, { get: all[name], enumerable: true });
14
+ };
15
+ var __copyProps = (to, from, except, desc) => {
16
+ if (from && typeof from === "object" || typeof from === "function") {
17
+ for (let key of __getOwnPropNames(from))
18
+ if (!__hasOwnProp.call(to, key) && key !== except)
19
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
+ }
21
+ return to;
22
+ };
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
+ // If the importer is in node compatibility mode or this is not an ESM
25
+ // file that has been converted to a CommonJS file using a Babel-
26
+ // compatible transform (i.e. "__esModule" has not been set), then set
27
+ // "default" to the CommonJS "module.exports" for node compatibility.
28
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
+ mod
30
+ ));
31
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
+
33
+ // src/runtime.ts
34
+ var runtime, isNode, isBun, isDeno;
35
+ var init_runtime = __esm({
36
+ "src/runtime.ts"() {
37
+ "use strict";
38
+ runtime = (() => {
39
+ if (typeof Deno !== "undefined") return "deno";
40
+ if (typeof Bun !== "undefined") return "bun";
41
+ return "node";
42
+ })();
43
+ isNode = runtime === "node";
44
+ isBun = runtime === "bun";
45
+ isDeno = runtime === "deno";
46
+ }
47
+ });
48
+
49
+ // src/fs.ts
50
+ function parseOptions(options, defaultValue) {
51
+ return typeof options === "string" ? { encoding: options } : options || defaultValue;
52
+ }
53
+ function decodeContent(content, encoding) {
54
+ if (encoding) {
55
+ return new TextDecoder(encoding).decode(content);
56
+ }
57
+ return Buffer.from(content instanceof ArrayBuffer ? new Uint8Array(content) : content);
58
+ }
59
+ function dataToUint8Array(data) {
60
+ if (typeof data === "string") {
61
+ return new TextEncoder().encode(data);
62
+ }
63
+ if (data instanceof Buffer) {
64
+ return new Uint8Array(data);
65
+ }
66
+ return data;
67
+ }
68
+ function processDenoEntries(iterator, withFileTypes) {
69
+ const entries = [];
70
+ for (const entry of iterator) {
71
+ if (withFileTypes) {
72
+ entries.push(createDirentFromDenoEntry(entry));
73
+ } else {
74
+ entries.push(entry.name);
75
+ }
76
+ }
77
+ return entries;
78
+ }
79
+ async function readFile(path, options) {
80
+ const opts = parseOptions(options, {});
81
+ if (isNode) {
82
+ return fsPromises.readFile(path, opts);
83
+ } else if (isBun) {
84
+ const file = Bun.file(path);
85
+ const content = await file.arrayBuffer();
86
+ return decodeContent(content, opts.encoding);
87
+ } else if (isDeno) {
88
+ const content = await Deno.readFile(path);
89
+ return decodeContent(content, opts.encoding);
90
+ }
91
+ throw new Error("Unsupported runtime");
92
+ }
93
+ function readFileSync(path, options) {
94
+ const opts = parseOptions(options, {});
95
+ if (isNode) {
96
+ return fs.readFileSync(path, opts);
97
+ } else if (isBun) {
98
+ const file = Bun.file(path);
99
+ const content = file.arrayBuffer();
100
+ return decodeContent(content, opts.encoding);
101
+ } else if (isDeno) {
102
+ const content = Deno.readFileSync(path);
103
+ return decodeContent(content, opts.encoding);
104
+ }
105
+ throw new Error("Unsupported runtime");
106
+ }
107
+ function writeFileSync(path, data, options) {
108
+ const opts = parseOptions(options, {});
109
+ if (isNode) {
110
+ fs.writeFileSync(path, data, opts);
111
+ } else if (isBun) {
112
+ Bun.write(path, data);
113
+ } else if (isDeno) {
114
+ Deno.writeFileSync(path, dataToUint8Array(data));
115
+ }
116
+ }
117
+ function existsSync(path) {
118
+ try {
119
+ statSync(path);
120
+ return true;
121
+ } catch {
122
+ return false;
123
+ }
124
+ }
125
+ function statSync(path) {
126
+ if (isNode) {
127
+ return fs.statSync(path);
128
+ } else if (isBun) {
129
+ const file = Bun.file(path);
130
+ const size = file.size;
131
+ try {
132
+ file.arrayBuffer();
133
+ } catch {
134
+ throw new Error(`ENOENT: no such file or directory, stat '${path}'`);
135
+ }
136
+ return createStatsObject(path, size, false);
137
+ } else if (isDeno) {
138
+ const info = Deno.statSync(path);
139
+ return createStatsFromDenoFileInfo(info);
140
+ }
141
+ throw new Error("Unsupported runtime");
142
+ }
143
+ function mkdirSync(path, options) {
144
+ const opts = typeof options === "number" ? { mode: options } : options || {};
145
+ if (isNode) {
146
+ fs.mkdirSync(path, opts);
147
+ } else if (isBun) {
148
+ Deno.mkdirSync(path, { recursive: opts.recursive });
149
+ } else if (isDeno) {
150
+ Deno.mkdirSync(path, { recursive: opts.recursive });
151
+ }
152
+ }
153
+ function readdirSync(path, options) {
154
+ const opts = parseOptions(options, {});
155
+ if (isNode) {
156
+ return fs.readdirSync(path, opts);
157
+ } else if (isBunOrDeno) {
158
+ return processDenoEntries(Deno.readDirSync(path), opts.withFileTypes);
159
+ }
160
+ throw new Error("Unsupported runtime");
161
+ }
162
+ function createStatsObject(_path, size, isDir) {
163
+ const now = Date.now();
164
+ return {
165
+ isFile: () => !isDir,
166
+ isDirectory: () => isDir,
167
+ isBlockDevice: () => false,
168
+ isCharacterDevice: () => false,
169
+ isSymbolicLink: () => false,
170
+ isFIFO: () => false,
171
+ isSocket: () => false,
172
+ dev: 0,
173
+ ino: 0,
174
+ mode: isDir ? 16877 : 33188,
175
+ nlink: 1,
176
+ uid: 0,
177
+ gid: 0,
178
+ rdev: 0,
179
+ size,
180
+ blksize: 4096,
181
+ blocks: Math.ceil(size / 512),
182
+ atimeMs: now,
183
+ mtimeMs: now,
184
+ ctimeMs: now,
185
+ birthtimeMs: now,
186
+ atime: new Date(now),
187
+ mtime: new Date(now),
188
+ ctime: new Date(now),
189
+ birthtime: new Date(now)
190
+ };
191
+ }
192
+ function createStatsFromDenoFileInfo(info) {
193
+ return {
194
+ isFile: () => info.isFile,
195
+ isDirectory: () => info.isDirectory,
196
+ isBlockDevice: () => false,
197
+ isCharacterDevice: () => false,
198
+ isSymbolicLink: () => info.isSymlink || false,
199
+ isFIFO: () => false,
200
+ isSocket: () => false,
201
+ dev: info.dev || 0,
202
+ ino: info.ino || 0,
203
+ mode: info.mode || 0,
204
+ nlink: info.nlink || 1,
205
+ uid: info.uid || 0,
206
+ gid: info.gid || 0,
207
+ rdev: 0,
208
+ size: info.size,
209
+ blksize: info.blksize || 4096,
210
+ blocks: info.blocks || Math.ceil(info.size / 512),
211
+ atimeMs: info.atime?.getTime() || Date.now(),
212
+ mtimeMs: info.mtime?.getTime() || Date.now(),
213
+ ctimeMs: info.birthtime?.getTime() || Date.now(),
214
+ birthtimeMs: info.birthtime?.getTime() || Date.now(),
215
+ atime: info.atime || /* @__PURE__ */ new Date(),
216
+ mtime: info.mtime || /* @__PURE__ */ new Date(),
217
+ ctime: info.birthtime || /* @__PURE__ */ new Date(),
218
+ birthtime: info.birthtime || /* @__PURE__ */ new Date()
219
+ };
220
+ }
221
+ function createDirentFromDenoEntry(entry) {
222
+ return {
223
+ name: entry.name,
224
+ isFile: () => entry.isFile,
225
+ isDirectory: () => entry.isDirectory,
226
+ isBlockDevice: () => false,
227
+ isCharacterDevice: () => false,
228
+ isSymbolicLink: () => entry.isSymlink || false,
229
+ isFIFO: () => false,
230
+ isSocket: () => false
231
+ };
232
+ }
233
+ var isBunOrDeno, fs, fsPromises;
234
+ var init_fs = __esm({
235
+ "src/fs.ts"() {
236
+ "use strict";
237
+ init_runtime();
238
+ isBunOrDeno = isBun || isDeno;
239
+ if (isNode) {
240
+ fs = require("fs");
241
+ fsPromises = require("fs/promises");
242
+ }
243
+ }
244
+ });
245
+
246
+ // src/path.ts
247
+ function getSeparator(isWin) {
248
+ return isWin ? "\\" : "/";
249
+ }
250
+ function getCwd() {
251
+ if (isNode || isBun) {
252
+ return process.cwd();
253
+ } else if (isDeno) {
254
+ return Deno.cwd();
255
+ }
256
+ return "/";
257
+ }
258
+ function findLastSeparator(path) {
259
+ return Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
260
+ }
261
+ function createPathOps(isWin) {
262
+ return {
263
+ sep: getSeparator(isWin),
264
+ delimiter: isWin ? ";" : ":",
265
+ normalize: (path) => normalizePath(path, isWin),
266
+ join: (...paths) => joinPaths(paths, isWin),
267
+ resolve: (...paths) => resolvePaths(paths, isWin),
268
+ isAbsolute: (path) => isWin ? isAbsoluteWin(path) : isAbsolutePosix(path),
269
+ relative: (from, to) => relativePath(from, to, isWin),
270
+ dirname: (path) => getDirname(path, isWin),
271
+ basename: (path, ext) => getBasename(path, ext, isWin),
272
+ extname: (path) => getExtname(path),
273
+ parse: (path) => parsePath(path, isWin),
274
+ format: (pathObject) => formatPath(pathObject, isWin)
275
+ };
276
+ }
277
+ function isAbsolutePosix(path) {
278
+ return path.length > 0 && path[0] === "/";
279
+ }
280
+ function isAbsoluteWin(path) {
281
+ const len = path.length;
282
+ if (len === 0) return false;
283
+ const code = path.charCodeAt(0);
284
+ if (code === 47 || code === 92) {
285
+ return true;
286
+ }
287
+ if (code >= 65 && code <= 90 || code >= 97 && code <= 122) {
288
+ if (len > 2 && path.charCodeAt(1) === 58) {
289
+ const code2 = path.charCodeAt(2);
290
+ if (code2 === 47 || code2 === 92) {
291
+ return true;
292
+ }
293
+ }
294
+ }
295
+ return false;
296
+ }
297
+ function normalizePath(path, isWin) {
298
+ if (path.length === 0) return ".";
299
+ const separator = getSeparator(isWin);
300
+ const isAbsolute2 = isWin ? isAbsoluteWin(path) : isAbsolutePosix(path);
301
+ const trailingSeparator = path[path.length - 1] === separator || isWin && path[path.length - 1] === "/";
302
+ let normalized = path.replace(isWin ? /[\/\\]+/g : /\/+/g, separator);
303
+ const parts = normalized.split(separator);
304
+ const result = [];
305
+ for (let i = 0; i < parts.length; i++) {
306
+ const part = parts[i];
307
+ if (part === "" || part === ".") {
308
+ if (i === 0 && isAbsolute2) result.push("");
309
+ continue;
310
+ }
311
+ if (part === "..") {
312
+ if (result.length > 0 && result[result.length - 1] !== "..") {
313
+ if (!(result.length === 1 && result[0] === "")) {
314
+ result.pop();
315
+ }
316
+ } else if (!isAbsolute2) {
317
+ result.push("..");
318
+ }
319
+ } else {
320
+ result.push(part);
321
+ }
322
+ }
323
+ let final = result.join(separator);
324
+ if (final.length === 0) {
325
+ return isAbsolute2 ? separator : ".";
326
+ }
327
+ if (trailingSeparator && final[final.length - 1] !== separator) {
328
+ final += separator;
329
+ }
330
+ return final;
331
+ }
332
+ function joinPaths(paths, isWin) {
333
+ if (paths.length === 0) return ".";
334
+ const separator = getSeparator(isWin);
335
+ let joined = "";
336
+ for (let i = 0; i < paths.length; i++) {
337
+ const path = paths[i];
338
+ if (path && path.length > 0) {
339
+ if (joined.length === 0) {
340
+ joined = path;
341
+ } else {
342
+ joined += separator + path;
343
+ }
344
+ }
345
+ }
346
+ if (joined.length === 0) return ".";
347
+ return normalizePath(joined, isWin);
348
+ }
349
+ function resolvePaths(paths, isWin) {
350
+ const separator = getSeparator(isWin);
351
+ let resolved = "";
352
+ let isAbsolute2 = false;
353
+ for (let i = paths.length - 1; i >= 0 && !isAbsolute2; i--) {
354
+ const path = paths[i];
355
+ if (path && path.length > 0) {
356
+ resolved = path + (resolved.length > 0 ? separator + resolved : "");
357
+ isAbsolute2 = isWin ? isAbsoluteWin(resolved) : isAbsolutePosix(resolved);
358
+ }
359
+ }
360
+ if (!isAbsolute2) {
361
+ const cwd = getCwd();
362
+ resolved = cwd + (resolved.length > 0 ? separator + resolved : "");
363
+ }
364
+ return normalizePath(resolved, isWin);
365
+ }
366
+ function relativePath(from, to, isWin) {
367
+ from = resolvePaths([from], isWin);
368
+ to = resolvePaths([to], isWin);
369
+ if (from === to) return "";
370
+ const separator = getSeparator(isWin);
371
+ const fromParts = from.split(separator).filter((p) => p.length > 0);
372
+ const toParts = to.split(separator).filter((p) => p.length > 0);
373
+ let commonLength = 0;
374
+ const minLength = Math.min(fromParts.length, toParts.length);
375
+ for (let i = 0; i < minLength; i++) {
376
+ if (fromParts[i] === toParts[i]) {
377
+ commonLength++;
378
+ } else {
379
+ break;
380
+ }
381
+ }
382
+ const upCount = fromParts.length - commonLength;
383
+ const result = [];
384
+ for (let i = 0; i < upCount; i++) {
385
+ result.push("..");
386
+ }
387
+ for (let i = commonLength; i < toParts.length; i++) {
388
+ result.push(toParts[i]);
389
+ }
390
+ return result.join(separator) || ".";
391
+ }
392
+ function getDirname(path, isWin) {
393
+ if (path.length === 0) return ".";
394
+ const separator = getSeparator(isWin);
395
+ const normalized = normalizePath(path, isWin);
396
+ const lastSepIndex = normalized.lastIndexOf(separator);
397
+ if (lastSepIndex === -1) return ".";
398
+ if (lastSepIndex === 0) return separator;
399
+ return normalized.slice(0, lastSepIndex);
400
+ }
401
+ function getBasename(path, ext, isWin) {
402
+ if (path.length === 0) return "";
403
+ const lastSepIndex = isWin ? findLastSeparator(path) : path.lastIndexOf("/");
404
+ let base = lastSepIndex === -1 ? path : path.slice(lastSepIndex + 1);
405
+ if (ext && base.endsWith(ext)) {
406
+ base = base.slice(0, base.length - ext.length);
407
+ }
408
+ return base;
409
+ }
410
+ function getExtname(path) {
411
+ const lastDotIndex = path.lastIndexOf(".");
412
+ const lastSepIndex = findLastSeparator(path);
413
+ if (lastDotIndex === -1 || lastDotIndex < lastSepIndex || lastDotIndex === path.length - 1) {
414
+ return "";
415
+ }
416
+ return path.slice(lastDotIndex);
417
+ }
418
+ function parsePath(path, isWin) {
419
+ let root = "";
420
+ if (isWin) {
421
+ if (path.length >= 2 && path[1] === ":") {
422
+ root = path.slice(0, 2);
423
+ if (path.length > 2 && (path[2] === "\\" || path[2] === "/")) {
424
+ root += "\\";
425
+ }
426
+ } else if (path[0] === "\\" || path[0] === "/") {
427
+ root = "\\";
428
+ }
429
+ } else {
430
+ if (path[0] === "/") {
431
+ root = "/";
432
+ }
433
+ }
434
+ const dir = getDirname(path, isWin);
435
+ const base = getBasename(path, void 0, isWin);
436
+ const ext = getExtname(path);
437
+ const name = ext ? base.slice(0, base.length - ext.length) : base;
438
+ return { root, dir, base, ext, name };
439
+ }
440
+ function formatPath(pathObject, isWin) {
441
+ const separator = getSeparator(isWin);
442
+ const dir = pathObject.dir || pathObject.root || "";
443
+ const base = pathObject.base || (pathObject.name || "") + (pathObject.ext || "");
444
+ if (!dir) return base;
445
+ if (dir === pathObject.root) return dir + base;
446
+ return dir + separator + base;
447
+ }
448
+ function join(...paths) {
449
+ return joinPaths(paths, isWindows);
450
+ }
451
+ function relative(from, to) {
452
+ return relativePath(from, to, isWindows);
453
+ }
454
+ function dirname(path) {
455
+ return getDirname(path, isWindows);
456
+ }
457
+ var isWindows, posix, win32;
458
+ var init_path = __esm({
459
+ "src/path.ts"() {
460
+ "use strict";
461
+ init_runtime();
462
+ isWindows = (() => {
463
+ if (isNode) {
464
+ return process.platform === "win32";
465
+ } else if (isDeno) {
466
+ return Deno.build.os === "windows";
467
+ }
468
+ return typeof process !== "undefined" && process.platform === "win32";
469
+ })();
470
+ posix = createPathOps(false);
471
+ win32 = createPathOps(true);
472
+ }
473
+ });
474
+
475
+ // src/coverage.ts
476
+ var coverage_exports = {};
477
+ __export(coverage_exports, {
478
+ calculateUncoveredLines: () => calculateUncoveredLines,
479
+ generateCloverXml: () => generateCloverXml,
480
+ generateCoverageFinalJson: () => generateCoverageFinalJson,
481
+ generateHtmlReport: () => generateHtmlReport,
482
+ generateTextReport: () => generateTextReport,
483
+ getExecutedLines: () => getExecutedLines,
484
+ initializeCoverageTracking: () => initializeCoverageTracking,
485
+ markFileAsCovered: () => markFileAsCovered,
486
+ markLineExecuted: () => markLineExecuted,
487
+ processCoverage: () => processCoverage,
488
+ resetCoverageTracking: () => resetCoverageTracking
489
+ });
490
+ function getExecutableLines(filePath) {
491
+ const executableLines = /* @__PURE__ */ new Set();
492
+ try {
493
+ const sourceCode = readFileSync(filePath, "utf-8").toString();
494
+ const lines = sourceCode.split("\n");
495
+ for (let i = 0; i < lines.length; i++) {
496
+ const line = lines[i];
497
+ const trimmed = line.trim();
498
+ if (!trimmed || trimmed.startsWith("//") || trimmed.startsWith("*") || trimmed.startsWith("/*") || trimmed.startsWith("*/") || trimmed.startsWith("import ") || trimmed.startsWith("export ") && !trimmed.includes("function") && !trimmed.includes("class") && !trimmed.includes("const") && !trimmed.includes("let") && !trimmed.includes("var") || trimmed.startsWith("interface ") || trimmed.startsWith("type ") || trimmed.startsWith("enum ") || trimmed.match(/^class\s+\w+.*{?\s*$/) || trimmed === "{" || trimmed === "}" || trimmed === "();") {
499
+ continue;
500
+ }
501
+ executableLines.add(i + 1);
502
+ }
503
+ } catch (e) {
504
+ }
505
+ return executableLines;
506
+ }
507
+ function markFileAsCovered(_filePath) {
508
+ }
509
+ function markLineExecuted(filePath, lineNumber) {
510
+ if (!executedLinesMap.has(filePath)) {
511
+ executedLinesMap.set(filePath, /* @__PURE__ */ new Set());
512
+ }
513
+ executedLinesMap.get(filePath).add(lineNumber);
514
+ }
515
+ function getExecutedLines(filePath) {
516
+ return executedLinesMap.get(filePath) || /* @__PURE__ */ new Set();
517
+ }
518
+ function calculateUncoveredLines(filePath) {
519
+ const executableLines = getExecutableLines(filePath);
520
+ const executedLines = getExecutedLines(filePath);
521
+ const uncovered = [];
522
+ for (const line of executableLines) {
523
+ if (!executedLines.has(line)) {
524
+ uncovered.push(line);
525
+ }
526
+ }
527
+ return uncovered.sort((a, b) => a - b);
528
+ }
529
+ function resetCoverageTracking() {
530
+ executedLinesMap.clear();
531
+ totalLinesMap.clear();
532
+ }
533
+ function initializeCoverageTracking() {
534
+ resetCoverageTracking();
535
+ }
536
+ function globToRegex(pattern) {
537
+ let regexStr = "^";
538
+ for (let i = 0; i < pattern.length; i++) {
539
+ const char = pattern[i];
540
+ switch (char) {
541
+ case ".":
542
+ regexStr += "\\.";
543
+ break;
544
+ case "*":
545
+ if (i + 1 < pattern.length && pattern[i + 1] === "*") {
546
+ regexStr += "(?:[^/]*(?:/|$))*";
547
+ i++;
548
+ } else {
549
+ regexStr += "[^/]*";
550
+ }
551
+ break;
552
+ case "?":
553
+ regexStr += "[^/]";
554
+ break;
555
+ case "/":
556
+ regexStr += "/";
557
+ break;
558
+ // Escape special regex characters
559
+ case "^":
560
+ case "$":
561
+ case "+":
562
+ case "(":
563
+ case ")":
564
+ case "[":
565
+ case "]":
566
+ case "{":
567
+ case "}":
568
+ case "|":
569
+ case "\\":
570
+ regexStr += "\\" + char;
571
+ break;
572
+ default:
573
+ regexStr += char;
574
+ break;
575
+ }
576
+ }
577
+ regexStr += "$";
578
+ return new RegExp(regexStr);
579
+ }
580
+ function matchesInclude(filePath, include) {
581
+ if (include.length === 0) return true;
582
+ const normalizedPath = filePath.replace(/\\/g, "/");
583
+ for (const pattern of include) {
584
+ const regex = globToRegex(pattern);
585
+ if (regex.test(normalizedPath)) {
586
+ return true;
587
+ }
588
+ }
589
+ return false;
590
+ }
591
+ function matchesExclude(filePath, exclude) {
592
+ const normalizedPath = filePath.replace(/\\/g, "/");
593
+ for (const pattern of exclude) {
594
+ const regex = globToRegex(pattern);
595
+ if (regex.test(normalizedPath)) {
596
+ return true;
597
+ }
598
+ }
599
+ return false;
600
+ }
601
+ function findAllTypeScriptFiles(dir, include, exclude) {
602
+ const files = [];
603
+ if (!existsSync(dir)) {
604
+ return files;
605
+ }
606
+ try {
607
+ const entries = readdirSync(dir, { withFileTypes: true });
608
+ for (const entry of entries) {
609
+ if (typeof entry === "string") continue;
610
+ const fullPath = join(dir, entry.name);
611
+ if (entry.isDirectory()) {
612
+ if (matchesExclude(fullPath, exclude)) continue;
613
+ files.push(...findAllTypeScriptFiles(fullPath, include, exclude));
614
+ } else if (entry.isFile() && fullPath.endsWith(".ts")) {
615
+ if (matchesInclude(fullPath, include) && !matchesExclude(fullPath, exclude)) {
616
+ files.push(fullPath);
617
+ }
618
+ }
619
+ }
620
+ } catch (e) {
621
+ }
622
+ return files;
623
+ }
624
+ function analyzeSourceFile(filePath) {
625
+ try {
626
+ const sourceCode = readFileSync(filePath, "utf-8").toString();
627
+ const lines = sourceCode.split("\n");
628
+ let statements = 0;
629
+ let branches = 0;
630
+ let functions = 0;
631
+ let executableLines = 0;
632
+ const branchKeywords = ["if", "else if", "for", "while", "switch", "case", "catch", "?", "&&", "||"];
633
+ const functionPatterns = [/function\s+\w+/, /(\w+)\s*\([^)]*\)\s*{/, /\(\s*\w+\s*(?:,\s*\w+\s*)*\)\s*=>/];
634
+ for (const line of lines) {
635
+ const trimmed = line.trim();
636
+ if (!trimmed || trimmed.startsWith("//") || trimmed.startsWith("*") || trimmed.startsWith("/*") || trimmed.startsWith("import ") || trimmed.startsWith("export ") || trimmed.startsWith("interface ") || trimmed.startsWith("type ") || trimmed.startsWith("enum ") || trimmed.match(/^class\s+\w+/)) {
637
+ continue;
638
+ }
639
+ for (const keyword of branchKeywords) {
640
+ if (trimmed.includes(keyword)) {
641
+ branches++;
642
+ break;
643
+ }
644
+ }
645
+ for (const pattern of functionPatterns) {
646
+ if (pattern.test(trimmed)) {
647
+ functions++;
648
+ break;
649
+ }
650
+ }
651
+ const codeOnly = trimmed.replace(/\{|\}|\(|\)|;$/g, "").replace(/^import\s+.*$/, "").replace(/^export\s+.*$/, "").replace(/^interface\s+.*$/, "").replace(/^type\s+.*$/, "").replace(/^enum\s+.*$/, "").replace(/^class\s+\w+.*$/, "").trim();
652
+ if (codeOnly && codeOnly.length > 0) {
653
+ statements++;
654
+ executableLines++;
655
+ }
656
+ }
657
+ return { statements, branches, functions, lines: executableLines };
658
+ } catch (e) {
659
+ return { statements: 0, branches: 0, functions: 0, lines: 0 };
660
+ }
661
+ }
662
+ async function processCoverage(options) {
663
+ const {
664
+ include = ["**/*.ts"],
665
+ exclude = ["**/*.test.ts", "**/*.spec.ts", "**/node_modules/**", "**/dist/**", "**/coverage/**"],
666
+ coveredFiles: coveredFiles2
667
+ } = options;
668
+ const coverageMap = /* @__PURE__ */ new Map();
669
+ const allTsFiles = findAllTypeScriptFiles(process.cwd(), include, exclude);
670
+ for (const tsFile of allTsFiles) {
671
+ const isCovered = coveredFiles2?.has(tsFile) || false;
672
+ const analysis = analyzeSourceFile(tsFile);
673
+ const executableLines = getExecutableLines(tsFile);
674
+ const executedLines = isCovered ? executableLines : /* @__PURE__ */ new Set();
675
+ const uncoveredLinesArray = [];
676
+ for (const line of executableLines) {
677
+ if (!executedLines.has(line)) {
678
+ uncoveredLinesArray.push(line);
679
+ }
680
+ }
681
+ const uncoveredLines = uncoveredLinesArray.length > 0 ? uncoveredLinesArray.sort((a, b) => a - b) : void 0;
682
+ const coveredLinesCount = executedLines.size;
683
+ coverageMap.set(tsFile, {
684
+ path: tsFile,
685
+ statements: analysis.statements,
686
+ coveredStatements: isCovered ? analysis.statements : 0,
687
+ branches: analysis.branches,
688
+ coveredBranches: isCovered ? analysis.branches : 0,
689
+ functions: analysis.functions,
690
+ coveredFunctions: isCovered ? analysis.functions : 0,
691
+ lines: executableLines.size,
692
+ coveredLines: coveredLinesCount,
693
+ uncoveredLines
694
+ });
695
+ }
696
+ if (coveredFiles2) {
697
+ for (const coveredFile of coveredFiles2) {
698
+ if (coverageMap.has(coveredFile)) continue;
699
+ const relativePath2 = relative(process.cwd(), coveredFile);
700
+ const isOutsideProject = relativePath2.startsWith("..");
701
+ if (!coveredFile.includes("node_modules") && !coveredFile.includes("dist") && !isOutsideProject) {
702
+ const analysis = analyzeSourceFile(coveredFile);
703
+ const executableLines = getExecutableLines(coveredFile);
704
+ const executedLines = executableLines;
705
+ const uncoveredLinesArray = [];
706
+ for (const line of executableLines) {
707
+ if (!executedLines.has(line)) {
708
+ uncoveredLinesArray.push(line);
709
+ }
710
+ }
711
+ const uncoveredLines = uncoveredLinesArray.length > 0 ? uncoveredLinesArray.sort((a, b) => a - b) : void 0;
712
+ const coveredLinesCount = executedLines.size;
713
+ coverageMap.set(coveredFile, {
714
+ path: coveredFile,
715
+ statements: analysis.statements,
716
+ coveredStatements: analysis.statements,
717
+ branches: analysis.branches,
718
+ coveredBranches: analysis.branches,
719
+ functions: analysis.functions,
720
+ coveredFunctions: analysis.functions,
721
+ lines: executableLines.size,
722
+ coveredLines: coveredLinesCount,
723
+ uncoveredLines
724
+ });
725
+ }
726
+ }
727
+ }
728
+ return coverageMap;
729
+ }
730
+ function getColorForPercentage(pct) {
731
+ if (pct >= 80) return colors2.green;
732
+ if (pct >= 50) return colors2.yellow;
733
+ return colors2.red;
734
+ }
735
+ function calculateFileCoverage(file) {
736
+ const stmtPct = file.statements > 0 ? file.coveredStatements / file.statements * 100 : 0;
737
+ const branchPct = file.branches > 0 ? file.coveredBranches / file.branches * 100 : 0;
738
+ const funcPct = file.functions > 0 ? file.coveredFunctions / file.functions * 100 : 0;
739
+ const linePct = file.lines > 0 ? file.coveredLines / file.lines * 100 : 0;
740
+ return {
741
+ statements: { total: file.statements, covered: file.coveredStatements, percentage: stmtPct },
742
+ branches: { total: file.branches, covered: file.coveredBranches, percentage: branchPct },
743
+ functions: { total: file.functions, covered: file.coveredFunctions, percentage: funcPct },
744
+ lines: { total: file.lines, covered: file.coveredLines, percentage: linePct }
745
+ };
746
+ }
747
+ function stripAnsi(str) {
748
+ return str.replace(/\x1b\[[0-9;]*m/g, "");
749
+ }
750
+ function getVisibleWidth(str) {
751
+ return stripAnsi(str).length;
752
+ }
753
+ function formatMetricFixedWidth(covered, total, percentage, includeSeparator = false) {
754
+ const color = getColorForPercentage(percentage);
755
+ const pctStr = percentage.toFixed(2);
756
+ const pct = color + pctStr + "%" + colors2.reset;
757
+ const coveredPadded = covered.toString().padStart(4);
758
+ const totalPadded = total.toString().padStart(4);
759
+ const count = `${colors2.dim}${coveredPadded}${colors2.reset}/${totalPadded}`;
760
+ const metric = `${pct} (${count})`;
761
+ const visibleWidth = getVisibleWidth(metric);
762
+ const padding = " ".repeat(Math.max(0, 19 - visibleWidth));
763
+ const separator = includeSeparator ? `${colors2.dim}\u2502${colors2.reset}` : " ";
764
+ return metric + padding + separator;
765
+ }
766
+ function formatUncoveredLines(uncoveredLines) {
767
+ if (!uncoveredLines || uncoveredLines.length === 0) {
768
+ return "";
769
+ }
770
+ const ranges = [];
771
+ let start = uncoveredLines[0];
772
+ let end = uncoveredLines[0];
773
+ for (let i = 1; i < uncoveredLines.length; i++) {
774
+ if (uncoveredLines[i] === end + 1) {
775
+ end = uncoveredLines[i];
776
+ } else {
777
+ if (start === end) {
778
+ ranges.push(start.toString());
779
+ } else {
780
+ ranges.push(`${start}-${end}`);
781
+ }
782
+ start = uncoveredLines[i];
783
+ end = uncoveredLines[i];
784
+ }
785
+ }
786
+ if (start === end) {
787
+ ranges.push(start.toString());
788
+ } else {
789
+ ranges.push(`${start}-${end}`);
790
+ }
791
+ return ranges.join(",");
792
+ }
793
+ function generateTextReport(coverageMap, testResults2) {
794
+ let output = "\n";
795
+ void testResults2;
796
+ let totalStatements = 0, coveredStatements = 0;
797
+ let totalBranches = 0, coveredBranches = 0;
798
+ let totalFunctions = 0, coveredFunctions = 0;
799
+ let totalLines = 0, coveredLines = 0;
800
+ for (const coverage of coverageMap.values()) {
801
+ totalStatements += coverage.statements;
802
+ coveredStatements += coverage.coveredStatements;
803
+ totalBranches += coverage.branches;
804
+ coveredBranches += coverage.coveredBranches;
805
+ totalFunctions += coverage.functions;
806
+ coveredFunctions += coverage.coveredFunctions;
807
+ totalLines += coverage.lines;
808
+ coveredLines += coverage.coveredLines;
809
+ }
810
+ const pctStmts = totalStatements > 0 ? coveredStatements / totalStatements * 100 : 0;
811
+ const pctBranch = totalBranches > 0 ? coveredBranches / totalBranches * 100 : 0;
812
+ const pctFunc = totalFunctions > 0 ? coveredFunctions / totalFunctions * 100 : 0;
813
+ const pctLines = totalLines > 0 ? coveredLines / totalLines * 100 : 0;
814
+ output += `${colors2.bold}% Coverage report from v8\x1B[0m
815
+ `;
816
+ output += `
817
+ `;
818
+ output += `${colors2.dim}${colors2.bold}All files\x1B[0m`;
819
+ const maxFileNameLength = Math.max(...Array.from(coverageMap.keys()).map((f) => relative(process.cwd(), f).length));
820
+ const namePadding = Math.max(45, maxFileNameLength + 2);
821
+ output += " ".repeat(namePadding - 9);
822
+ const stmtsMetric = formatMetricFixedWidth(coveredStatements, totalStatements, pctStmts, true);
823
+ const branchMetric = formatMetricFixedWidth(coveredBranches, totalBranches, pctBranch, true);
824
+ const funcsMetric = formatMetricFixedWidth(coveredFunctions, totalFunctions, pctFunc, true);
825
+ const linesMetric = formatMetricFixedWidth(coveredLines, totalLines, pctLines, true);
826
+ output += `${stmtsMetric}${branchMetric}${funcsMetric}${linesMetric}
827
+ `;
828
+ output += `${colors2.dim}`;
829
+ output += " ".repeat(namePadding);
830
+ output += " ".repeat(5) + "Statements";
831
+ output += " ".repeat(12) + "Branch";
832
+ output += " ".repeat(12) + "Functions";
833
+ output += " ".repeat(13) + "Lines";
834
+ output += " ".repeat(12) + "Uncovered";
835
+ output += `${colors2.reset}
836
+ `;
837
+ output += `${colors2.dim}`;
838
+ output += "\u2500".repeat(namePadding);
839
+ output += "\u2500".repeat(19);
840
+ output += "\u253C";
841
+ output += "\u2500".repeat(19);
842
+ output += "\u253C";
843
+ output += "\u2500".repeat(19);
844
+ output += "\u253C";
845
+ output += "\u2500".repeat(19);
846
+ output += "\u253C";
847
+ output += "\u2500".repeat(19);
848
+ output += `${colors2.reset}
849
+ `;
850
+ const groupedFiles = /* @__PURE__ */ new Map();
851
+ for (const [filePath, coverage] of coverageMap.entries()) {
852
+ const dir = dirname(filePath);
853
+ if (!groupedFiles.has(dir)) {
854
+ groupedFiles.set(dir, []);
855
+ }
856
+ groupedFiles.get(dir).push({ path: filePath, coverage });
857
+ }
858
+ const cwd = process.cwd();
859
+ const toRelative = (path) => relative(cwd, path).replace(/\\/g, "/");
860
+ for (const [dir, files] of groupedFiles.entries()) {
861
+ const relDir = toRelative(dir);
862
+ if (relDir !== ".") {
863
+ output += `
864
+ ${colors2.cyan}${relDir}/${colors2.reset}
865
+ `;
866
+ }
867
+ for (const { path, coverage } of files) {
868
+ const stats = calculateFileCoverage(coverage);
869
+ const relPath = toRelative(path);
870
+ let displayName = relPath;
871
+ if (displayName.length > namePadding - 2) {
872
+ displayName = "..." + displayName.slice(-(namePadding - 5));
873
+ }
874
+ output += displayName.padEnd(namePadding);
875
+ output += formatMetricFixedWidth(
876
+ stats.statements.covered,
877
+ stats.statements.total,
878
+ stats.statements.percentage,
879
+ true
880
+ // Include separator
881
+ );
882
+ output += formatMetricFixedWidth(
883
+ stats.branches.covered,
884
+ stats.branches.total,
885
+ stats.branches.percentage,
886
+ true
887
+ // Include separator
888
+ );
889
+ output += formatMetricFixedWidth(
890
+ stats.functions.covered,
891
+ stats.functions.total,
892
+ stats.functions.percentage,
893
+ true
894
+ // Include separator
895
+ );
896
+ output += formatMetricFixedWidth(
897
+ stats.lines.covered,
898
+ stats.lines.total,
899
+ stats.lines.percentage,
900
+ true
901
+ // Include separator
902
+ );
903
+ const uncoveredStr = formatUncoveredLines(coverage.uncoveredLines);
904
+ output += `${colors2.red}${uncoveredStr}${colors2.reset}`;
905
+ output += "\n";
906
+ }
907
+ }
908
+ output += `
909
+ `;
910
+ output += `${colors2.dim}${colors2.bold}Test Files\x1B[0m ${coverageMap.size} passed (100%)
911
+ `;
912
+ output += `${colors2.dim}${colors2.bold}Tests\x1B[0m ${coverageMap.size} passed (100%)
913
+ `;
914
+ output += `
915
+ `;
916
+ output += `${colors2.dim}${colors2.bold}Statements\x1B[0m ${colors2.green}${coveredStatements}${colors2.reset} ${colors2.dim}/${colors2.reset} ${totalStatements}
917
+ `;
918
+ output += `${colors2.dim}${colors2.bold}Branches\x1B[0m ${colors2.green}${coveredBranches}${colors2.reset} ${colors2.dim}/${colors2.reset} ${totalBranches}
919
+ `;
920
+ output += `${colors2.dim}${colors2.bold}Functions\x1B[0m ${colors2.green}${coveredFunctions}${colors2.reset} ${colors2.dim}/${colors2.reset} ${totalFunctions}
921
+ `;
922
+ output += `${colors2.dim}${colors2.bold}Lines\x1B[0m ${colors2.green}${coveredLines}${colors2.reset} ${colors2.dim}/${colors2.reset} ${totalLines}
923
+ `;
924
+ return output;
925
+ }
926
+ function generateHtmlReport(coverageMap, reportsDir) {
927
+ if (!existsSync(reportsDir)) {
928
+ mkdirSync(reportsDir, { recursive: true });
929
+ }
930
+ let totalStatements = 0, coveredStatements = 0;
931
+ let totalBranches = 0, coveredBranches = 0;
932
+ let totalFunctions = 0, coveredFunctions = 0;
933
+ let totalLines = 0, coveredLines = 0;
934
+ for (const coverage of coverageMap.values()) {
935
+ totalStatements += coverage.statements;
936
+ coveredStatements += coverage.coveredStatements;
937
+ totalBranches += coverage.branches;
938
+ coveredBranches += coverage.coveredBranches;
939
+ totalFunctions += coverage.functions;
940
+ coveredFunctions += coverage.coveredFunctions;
941
+ totalLines += coverage.lines;
942
+ coveredLines += coverage.coveredLines;
943
+ }
944
+ const pctStmts = totalStatements > 0 ? coveredStatements / totalStatements * 100 : 0;
945
+ const pctBranch = totalBranches > 0 ? coveredBranches / totalBranches * 100 : 0;
946
+ const pctFunc = totalFunctions > 0 ? coveredFunctions / totalFunctions * 100 : 0;
947
+ const pctLines = totalLines > 0 ? coveredLines / totalLines * 100 : 0;
948
+ const overallPct = (pctStmts + pctBranch + pctFunc + pctLines) / 4;
949
+ const totalFiles = coverageMap.size;
950
+ const coveredFiles2 = Array.from(coverageMap.values()).filter((c) => c.coveredStatements > 0).length;
951
+ const cwd = process.cwd();
952
+ const toRelative = (path) => relative(cwd, path).replace(/\\/g, "/");
953
+ const indexHtml = `<!DOCTYPE html>
954
+ <html>
955
+ <head>
956
+ <meta charset="utf-8">
957
+ <title>Coverage Report</title>
958
+ <link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Cdefs%3E%3ClinearGradient id='grad' x1='0%25' y1='0%25' x2='100%25' y2='100%25'%3E%3Cstop offset='0%25' stop-color='%236366f1'/%3E%3Cstop offset='100%25' stop-color='%238b5cf6'/%3E%3C/linearGradient%3E%3C/defs%3E%3Crect width='100' height='100' rx='20' fill='url(%23grad)'/%3E%3Crect x='28' y='25' width='44' height='8' rx='4' fill='white'/%3E%3Crect x='28' y='46' width='32' height='8' rx='4' fill='white'/%3E%3Crect x='28' y='67' width='44' height='8' rx='4' fill='white'/%3E%3Crect x='28' y='25' width='8' height='50' rx='4' fill='white'/%3E%3Ccircle cx='72' cy='50' r='6' fill='white' opacity='0.5'/%3E%3C/svg%3E">
959
+ <style>
960
+ * { margin: 0; padding: 0; box-sizing: border-box; }
961
+ body {
962
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
963
+ background: #0d1117;
964
+ color: #c9d1d9;
965
+ padding: 20px;
966
+ }
967
+ .container { max-width: 1400px; margin: 0 auto; }
968
+ h1 {
969
+ font-size: 24px;
970
+ font-weight: 600;
971
+ margin-bottom: 20px;
972
+ color: #58a6ff;
973
+ }
974
+ .overall-bar {
975
+ background: #161b22;
976
+ border: 1px solid #30363d;
977
+ border-radius: 6px;
978
+ padding: 15px 20px;
979
+ margin-bottom: 20px;
980
+ }
981
+ .overall-bar-inner {
982
+ display: flex;
983
+ align-items: center;
984
+ gap: 15px;
985
+ }
986
+ .overall-bar-label {
987
+ font-size: 14px;
988
+ font-weight: 600;
989
+ color: #8b949e;
990
+ min-width: 140px;
991
+ }
992
+ .overall-bar-visual {
993
+ flex: 1;
994
+ height: 24px;
995
+ background: #21262d;
996
+ border-radius: 4px;
997
+ overflow: hidden;
998
+ position: relative;
999
+ }
1000
+ .overall-bar-fill {
1001
+ height: 100%;
1002
+ background: ${overallPct >= 80 ? "#3fb950" : overallPct >= 50 ? "#d29922" : "#f85149"};
1003
+ display: flex;
1004
+ align-items: center;
1005
+ justify-content: center;
1006
+ transition: width 0.3s ease;
1007
+ }
1008
+ .overall-bar-text {
1009
+ position: absolute;
1010
+ right: 10px;
1011
+ top: 50%;
1012
+ transform: translateY(-50%);
1013
+ font-size: 12px;
1014
+ font-weight: 600;
1015
+ color: #ffffff;
1016
+ text-shadow: 0 1px 2px rgba(0,0,0,0.3);
1017
+ }
1018
+ .files-info {
1019
+ font-size: 13px;
1020
+ color: #8b949e;
1021
+ margin-top: 8px;
1022
+ }
1023
+ .files-info span { color: #58a6ff; font-weight: 600; }
1024
+ .summary {
1025
+ background: #161b22;
1026
+ border: 1px solid #30363d;
1027
+ border-radius: 6px;
1028
+ padding: 20px;
1029
+ margin-bottom: 20px;
1030
+ }
1031
+ .summary-title {
1032
+ font-size: 16px;
1033
+ font-weight: 600;
1034
+ margin-bottom: 15px;
1035
+ color: #c9d1d9;
1036
+ }
1037
+ .metrics { display: grid; grid-template-columns: repeat(4, 1fr); gap: 15px; }
1038
+ .metric {
1039
+ background: #21262d;
1040
+ border: 1px solid #30363d;
1041
+ border-radius: 6px;
1042
+ padding: 15px;
1043
+ text-align: center;
1044
+ }
1045
+ .metric-label { font-size: 12px; color: #8b949e; margin-bottom: 5px; text-transform: uppercase; letter-spacing: 0.5px; }
1046
+ .metric-value { font-size: 24px; font-weight: 700; }
1047
+ .metric-value.high { color: #3fb950; }
1048
+ .metric-value.medium { color: #d29922; }
1049
+ .metric-value.low { color: #f85149; }
1050
+ .progress-bar {
1051
+ height: 8px;
1052
+ background: #21262d;
1053
+ border-radius: 4px;
1054
+ overflow: hidden;
1055
+ margin-top: 8px;
1056
+ }
1057
+ .progress-fill { height: 100%; transition: width 0.3s ease; }
1058
+ .progress-fill.high { background: #3fb950; }
1059
+ .progress-fill.medium { background: #d29922; }
1060
+ .progress-fill.low { background: #f85149; }
1061
+ .metric-count { font-size: 11px; color: #8b949e; margin-top: 5px; }
1062
+ .file-list {
1063
+ background: #161b22;
1064
+ border: 1px solid #30363d;
1065
+ border-radius: 6px;
1066
+ overflow: hidden;
1067
+ }
1068
+ .file-header {
1069
+ display: grid;
1070
+ grid-template-columns: 1fr 80px 80px 80px 80px;
1071
+ padding: 12px 15px;
1072
+ background: #21262d;
1073
+ font-size: 12px;
1074
+ font-weight: 600;
1075
+ color: #8b949e;
1076
+ border-bottom: 1px solid #30363d;
1077
+ }
1078
+ .file-row {
1079
+ display: grid;
1080
+ grid-template-columns: 1fr 80px 80px 80px 80px;
1081
+ padding: 10px 15px;
1082
+ border-bottom: 1px solid #21262d;
1083
+ font-size: 13px;
1084
+ }
1085
+ .file-row:hover { background: #21262d; }
1086
+ .file-row:last-child { border-bottom: none; }
1087
+ .file-name { color: #58a6ff; text-decoration: none; cursor: pointer; }
1088
+ .file-name:hover { text-decoration: underline; }
1089
+ .percentage { font-weight: 600; }
1090
+ .percentage.high { color: #3fb950; }
1091
+ .percentage.medium { color: #d29922; }
1092
+ .percentage.low { color: #f85149; }
1093
+ .metric-detail { font-size: 11px; color: #8b949e; margin-top: 2px; }
1094
+ .badge { display: inline-block; padding: 2px 8px; border-radius: 12px; font-size: 11px; font-weight: 600; margin-left: 8px; }
1095
+ .badge.covered { background: #238636; color: #fff; }
1096
+ .badge.uncovered { background: #da3633; color: #fff; }
1097
+ .coverage-cell { text-align: center; }
1098
+ .coverage-percent { font-weight: 600; }
1099
+ .coverage-percent.high { color: #3fb950; }
1100
+ .coverage-percent.medium { color: #d29922; }
1101
+ .coverage-percent.low { color: #f85149; }
1102
+ .coverage-count { font-size: 11px; color: #8b949e; margin-top: 2px; }
1103
+ .search-container {
1104
+ background: #161b22;
1105
+ border: 1px solid #30363d;
1106
+ border-radius: 6px;
1107
+ padding: 15px;
1108
+ margin-bottom: 20px;
1109
+ }
1110
+ .search-input {
1111
+ width: 100%;
1112
+ padding: 10px 15px;
1113
+ background: #21262d;
1114
+ border: 1px solid #30363d;
1115
+ border-radius: 6px;
1116
+ color: #c9d1d9;
1117
+ font-size: 14px;
1118
+ font-family: inherit;
1119
+ outline: none;
1120
+ transition: border-color 0.2s ease;
1121
+ }
1122
+ .search-input:focus {
1123
+ border-color: #58a6ff;
1124
+ }
1125
+ .search-input::placeholder {
1126
+ color: #8b949e;
1127
+ }
1128
+ .hidden { display: none !important; }
1129
+ .no-results {
1130
+ padding: 20px;
1131
+ text-align: center;
1132
+ color: #8b949e;
1133
+ font-size: 14px;
1134
+ }
1135
+ </style>
1136
+ </head>
1137
+ <body>
1138
+ <div class="container">
1139
+ <h1>Coverage Report</h1>
1140
+
1141
+ <div class="overall-bar">
1142
+ <div class="overall-bar-inner">
1143
+ <div class="overall-bar-label">Overall Coverage</div>
1144
+ <div class="overall-bar-visual">
1145
+ <div class="overall-bar-fill" style="width: ${overallPct}%"></div>
1146
+ <div class="overall-bar-text">${overallPct.toFixed(2)}%</div>
1147
+ </div>
1148
+ </div>
1149
+ <div class="files-info"><span>${coveredFiles2}</span> of ${totalFiles} files covered</div>
1150
+ </div>
1151
+
1152
+ <div class="summary">
1153
+ <div class="summary-title">Coverage Metrics</div>
1154
+ <div class="metrics">
1155
+ <div class="metric">
1156
+ <div class="metric-label">Statements</div>
1157
+ <div class="metric-value ${pctStmts >= 80 ? "high" : pctStmts >= 50 ? "medium" : "low"}">${pctStmts.toFixed(2)}%</div>
1158
+ <div class="progress-bar">
1159
+ <div class="progress-fill ${pctStmts >= 80 ? "high" : pctStmts >= 50 ? "medium" : "low"}" style="width: ${pctStmts}%"></div>
1160
+ </div>
1161
+ <div class="metric-count">${coveredStatements}/${totalStatements}</div>
1162
+ </div>
1163
+ <div class="metric">
1164
+ <div class="metric-label">Branches</div>
1165
+ <div class="metric-value ${pctBranch >= 80 ? "high" : pctBranch >= 50 ? "medium" : "low"}">${pctBranch.toFixed(2)}%</div>
1166
+ <div class="progress-bar">
1167
+ <div class="progress-fill ${pctBranch >= 80 ? "high" : pctBranch >= 50 ? "medium" : "low"}" style="width: ${pctBranch}%"></div>
1168
+ </div>
1169
+ <div class="metric-count">${coveredBranches}/${totalBranches}</div>
1170
+ </div>
1171
+ <div class="metric">
1172
+ <div class="metric-label">Functions</div>
1173
+ <div class="metric-value ${pctFunc >= 80 ? "high" : pctFunc >= 50 ? "medium" : "low"}">${pctFunc.toFixed(2)}%</div>
1174
+ <div class="progress-bar">
1175
+ <div class="progress-fill ${pctFunc >= 80 ? "high" : pctFunc >= 50 ? "medium" : "low"}" style="width: ${pctFunc}%"></div>
1176
+ </div>
1177
+ <div class="metric-count">${coveredFunctions}/${totalFunctions}</div>
1178
+ </div>
1179
+ <div class="metric">
1180
+ <div class="metric-label">Lines</div>
1181
+ <div class="metric-value ${pctLines >= 80 ? "high" : pctLines >= 50 ? "medium" : "low"}">${pctLines.toFixed(2)}%</div>
1182
+ <div class="progress-bar">
1183
+ <div class="progress-fill ${pctLines >= 80 ? "high" : pctLines >= 50 ? "medium" : "low"}" style="width: ${pctLines}%"></div>
1184
+ </div>
1185
+ <div class="metric-count">${coveredLines}/${totalLines}</div>
1186
+ </div>
1187
+ </div>
1188
+ </div>
1189
+
1190
+ <div class="search-container">
1191
+ <input type="text" id="search-input" class="search-input" placeholder="\u{1F50D} Search files..." autocomplete="off">
1192
+ </div>
1193
+
1194
+ <div class="file-list">
1195
+ <div class="file-header">
1196
+ <div>File</div>
1197
+ <div style="text-align: center">Stmts</div>
1198
+ <div style="text-align: center">Branch</div>
1199
+ <div style="text-align: center">Funcs</div>
1200
+ <div style="text-align: center">Lines</div>
1201
+ </div>
1202
+ <div id="file-rows">
1203
+ ${Array.from(coverageMap.entries()).map(([filePath, coverage]) => {
1204
+ const stats = calculateFileCoverage(coverage);
1205
+ const fileName = toRelative(filePath);
1206
+ const safeFileName = fileName.replace(/[\/\\]/g, "_") + ".html";
1207
+ const isCovered = coverage.coveredStatements > 0;
1208
+ return `
1209
+ <div class="file-row" onclick="window.location.href='${safeFileName}'">
1210
+ <div>
1211
+ <span class="file-name">${fileName}</span>
1212
+ ${isCovered ? '<span class="badge covered">Covered</span>' : '<span class="badge uncovered">Not Covered</span>'}
1213
+ </div>
1214
+ <div class="coverage-cell">
1215
+ <div class="coverage-percent ${stats.statements.percentage >= 80 ? "high" : stats.statements.percentage >= 50 ? "medium" : "low"}">${stats.statements.percentage.toFixed(2)}%</div>
1216
+ <div class="coverage-count">${coverage.coveredStatements}/${coverage.statements}</div>
1217
+ </div>
1218
+ <div class="coverage-cell">
1219
+ <div class="coverage-percent ${stats.branches.percentage >= 80 ? "high" : stats.branches.percentage >= 50 ? "medium" : "low"}">${stats.branches.percentage.toFixed(2)}%</div>
1220
+ <div class="coverage-count">${coverage.coveredBranches}/${coverage.branches}</div>
1221
+ </div>
1222
+ <div class="coverage-cell">
1223
+ <div class="coverage-percent ${stats.functions.percentage >= 80 ? "high" : stats.functions.percentage >= 50 ? "medium" : "low"}">${stats.functions.percentage.toFixed(2)}%</div>
1224
+ <div class="coverage-count">${coverage.coveredFunctions}/${coverage.functions}</div>
1225
+ </div>
1226
+ <div class="coverage-cell">
1227
+ <div class="coverage-percent ${stats.lines.percentage >= 80 ? "high" : stats.lines.percentage >= 50 ? "medium" : "low"}">${stats.lines.percentage.toFixed(2)}%</div>
1228
+ <div class="coverage-count">${coverage.coveredLines}/${coverage.lines}</div>
1229
+ </div>
1230
+ </div>
1231
+ `;
1232
+ }).join("")}
1233
+ </div>
1234
+ <div id="no-results" class="no-results hidden">No files found matching your search</div>
1235
+ </div>
1236
+ </div>
1237
+
1238
+ <script>
1239
+ const searchInput = document.getElementById('search-input');
1240
+ const fileRows = document.getElementById('file-rows');
1241
+ const noResults = document.getElementById('no-results');
1242
+ const fileRowElements = fileRows.querySelectorAll('.file-row');
1243
+
1244
+ searchInput.addEventListener('input', function() {
1245
+ const searchTerm = this.value.toLowerCase().trim();
1246
+ let visibleCount = 0;
1247
+
1248
+ fileRowElements.forEach(function(row) {
1249
+ const fileName = row.querySelector('.file-name').textContent.toLowerCase();
1250
+ if (fileName.includes(searchTerm)) {
1251
+ row.classList.remove('hidden');
1252
+ visibleCount++;
1253
+ } else {
1254
+ row.classList.add('hidden');
1255
+ }
1256
+ });
1257
+
1258
+ if (visibleCount === 0) {
1259
+ noResults.classList.remove('hidden');
1260
+ } else {
1261
+ noResults.classList.add('hidden');
1262
+ }
1263
+ });
1264
+ </script>
1265
+ </body>
1266
+ </html>`;
1267
+ writeFileSync(join(reportsDir, "index.html"), indexHtml, "utf-8");
1268
+ for (const [filePath, coverage] of coverageMap.entries()) {
1269
+ generateFileDetailPage(filePath, coverage, reportsDir, toRelative);
1270
+ }
1271
+ }
1272
+ function generateFileDetailPage(filePath, coverage, reportsDir, toRelative) {
1273
+ const fileName = toRelative(filePath);
1274
+ const safeFileName = fileName.replace(/[\/\\]/g, "_") + ".html";
1275
+ const stats = calculateFileCoverage(coverage);
1276
+ let sourceLines = [];
1277
+ try {
1278
+ const sourceCode = readFileSync(filePath, "utf-8").toString();
1279
+ sourceLines = sourceCode.split("\n");
1280
+ } catch (e) {
1281
+ sourceLines = ["// Unable to read source file"];
1282
+ }
1283
+ const uncoveredSet = new Set(coverage.uncoveredLines || []);
1284
+ const fileHtml = `<!DOCTYPE html>
1285
+ <html>
1286
+ <head>
1287
+ <meta charset="utf-8">
1288
+ <title>Coverage: ${fileName}</title>
1289
+ <link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Cdefs%3E%3ClinearGradient id='grad' x1='0%25' y1='0%25' x2='100%25' y2='100%25'%3E%3Cstop offset='0%25' stop-color='%236366f1'/%3E%3Cstop offset='100%25' stop-color='%238b5cf6'/%3E%3C/linearGradient%3E%3C/defs%3E%3Crect width='100' height='100' rx='20' fill='url(%23grad)'/%3E%3Crect x='28' y='25' width='44' height='8' rx='4' fill='white'/%3E%3Crect x='28' y='46' width='32' height='8' rx='4' fill='white'/%3E%3Crect x='28' y='67' width='44' height='8' rx='4' fill='white'/%3E%3Crect x='28' y='25' width='8' height='50' rx='4' fill='white'/%3E%3Ccircle cx='72' cy='50' r='6' fill='white' opacity='0.5'/%3E%3C/svg%3E">
1290
+ <style>
1291
+ * { margin: 0; padding: 0; box-sizing: border-box; }
1292
+ body {
1293
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
1294
+ background: #0d1117;
1295
+ color: #c9d1d9;
1296
+ padding: 20px;
1297
+ }
1298
+ .container { max-width: 1400px; margin: 0 auto; }
1299
+ a { color: #58a6ff; text-decoration: none; }
1300
+ a:hover { text-decoration: underline; }
1301
+ h1 {
1302
+ font-size: 24px;
1303
+ font-weight: 600;
1304
+ margin-bottom: 10px;
1305
+ color: #58a6ff;
1306
+ }
1307
+ .breadcrumb {
1308
+ font-size: 14px;
1309
+ color: #8b949e;
1310
+ margin-bottom: 20px;
1311
+ }
1312
+ .breadcrumb a { color: #58a6ff; }
1313
+ .summary {
1314
+ background: #161b22;
1315
+ border: 1px solid #30363d;
1316
+ border-radius: 6px;
1317
+ padding: 20px;
1318
+ margin-bottom: 20px;
1319
+ }
1320
+ .summary-title {
1321
+ font-size: 16px;
1322
+ font-weight: 600;
1323
+ margin-bottom: 15px;
1324
+ color: #c9d1d9;
1325
+ }
1326
+ .metrics { display: grid; grid-template-columns: repeat(4, 1fr); gap: 15px; }
1327
+ .metric {
1328
+ background: #21262d;
1329
+ border: 1px solid #30363d;
1330
+ border-radius: 6px;
1331
+ padding: 15px;
1332
+ text-align: center;
1333
+ }
1334
+ .metric-label { font-size: 12px; color: #8b949e; margin-bottom: 5px; text-transform: uppercase; letter-spacing: 0.5px; }
1335
+ .metric-value { font-size: 24px; font-weight: 700; }
1336
+ .metric-value.high { color: #3fb950; }
1337
+ .metric-value.medium { color: #d29922; }
1338
+ .metric-value.low { color: #f85149; }
1339
+ .progress-bar {
1340
+ height: 8px;
1341
+ background: #21262d;
1342
+ border-radius: 4px;
1343
+ overflow: hidden;
1344
+ margin-top: 8px;
1345
+ }
1346
+ .progress-fill { height: 100%; transition: width 0.3s ease; }
1347
+ .progress-fill.high { background: #3fb950; }
1348
+ .progress-fill.medium { background: #d29922; }
1349
+ .progress-fill.low { background: #f85149; }
1350
+ .metric-count { font-size: 11px; color: #8b949e; margin-top: 5px; }
1351
+ .code-container {
1352
+ background: #161b22;
1353
+ border: 1px solid #30363d;
1354
+ border-radius: 6px;
1355
+ overflow: hidden;
1356
+ }
1357
+ .code-header {
1358
+ padding: 10px 15px;
1359
+ background: #21262d;
1360
+ border-bottom: 1px solid #30363d;
1361
+ font-size: 13px;
1362
+ color: #8b949e;
1363
+ display: flex;
1364
+ justify-content: space-between;
1365
+ }
1366
+ .legend { display: flex; gap: 15px; font-size: 12px; }
1367
+ .legend-item { display: flex; align-items: center; gap: 5px; }
1368
+ .legend-box { width: 12px; height: 12px; border-radius: 2px; }
1369
+ .legend-box.covered { background: rgba(63, 185, 80, 0.2); border: 1px solid #3fb950; }
1370
+ .legend-box.uncovered { background: rgba(248, 81, 73, 0.2); border: 1px solid #f85149; }
1371
+ .code-table { width: 100%; border-collapse: collapse; }
1372
+ .code-table td { padding: 0; }
1373
+ .line-number {
1374
+ width: 50px;
1375
+ text-align: right;
1376
+ padding: 0 15px;
1377
+ color: #8b949e;
1378
+ font-size: 12px;
1379
+ user-select: none;
1380
+ border-right: 1px solid #30363d;
1381
+ }
1382
+ .line-content {
1383
+ padding: 0 15px;
1384
+ font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
1385
+ font-size: 13px;
1386
+ line-height: 20px;
1387
+ white-space: pre;
1388
+ }
1389
+ tr.covered .line-content { background: rgba(63, 185, 80, 0.1); }
1390
+ tr.uncovered .line-content { background: rgba(248, 81, 73, 0.15); }
1391
+ tr.uncovered .line-number { color: #f85149; }
1392
+ tr:hover td { background: rgba(88, 166, 255, 0.1); }
1393
+ </style>
1394
+ </head>
1395
+ <body>
1396
+ <div class="container">
1397
+ <div class="breadcrumb">
1398
+ <a href="index.html">\u2190 Back to Coverage Report</a>
1399
+ </div>
1400
+
1401
+ <h1>${fileName}</h1>
1402
+
1403
+ <div class="summary">
1404
+ <div class="summary-title">Coverage Metrics</div>
1405
+ <div class="metrics">
1406
+ <div class="metric">
1407
+ <div class="metric-label">Statements</div>
1408
+ <div class="metric-value ${stats.statements.percentage >= 80 ? "high" : stats.statements.percentage >= 50 ? "medium" : "low"}">${stats.statements.percentage.toFixed(2)}%</div>
1409
+ <div class="progress-bar">
1410
+ <div class="progress-fill ${stats.statements.percentage >= 80 ? "high" : stats.statements.percentage >= 50 ? "medium" : "low"}" style="width: ${stats.statements.percentage}%"></div>
1411
+ </div>
1412
+ <div class="metric-count">${coverage.coveredStatements}/${coverage.statements}</div>
1413
+ </div>
1414
+ <div class="metric">
1415
+ <div class="metric-label">Branches</div>
1416
+ <div class="metric-value ${stats.branches.percentage >= 80 ? "high" : stats.branches.percentage >= 50 ? "medium" : "low"}">${stats.branches.percentage.toFixed(2)}%</div>
1417
+ <div class="progress-bar">
1418
+ <div class="progress-fill ${stats.branches.percentage >= 80 ? "high" : stats.branches.percentage >= 50 ? "medium" : "low"}" style="width: ${stats.branches.percentage}%"></div>
1419
+ </div>
1420
+ <div class="metric-count">${coverage.coveredBranches}/${coverage.branches}</div>
1421
+ </div>
1422
+ <div class="metric">
1423
+ <div class="metric-label">Functions</div>
1424
+ <div class="metric-value ${stats.functions.percentage >= 80 ? "high" : stats.functions.percentage >= 50 ? "medium" : "low"}">${stats.functions.percentage.toFixed(2)}%</div>
1425
+ <div class="progress-bar">
1426
+ <div class="progress-fill ${stats.functions.percentage >= 80 ? "high" : stats.functions.percentage >= 50 ? "medium" : "low"}" style="width: ${stats.functions.percentage}%"></div>
1427
+ </div>
1428
+ <div class="metric-count">${coverage.coveredFunctions}/${coverage.functions}</div>
1429
+ </div>
1430
+ <div class="metric">
1431
+ <div class="metric-label">Lines</div>
1432
+ <div class="metric-value ${stats.lines.percentage >= 80 ? "high" : stats.lines.percentage >= 50 ? "medium" : "low"}">${stats.lines.percentage.toFixed(2)}%</div>
1433
+ <div class="progress-bar">
1434
+ <div class="progress-fill ${stats.lines.percentage >= 80 ? "high" : stats.lines.percentage >= 50 ? "medium" : "low"}" style="width: ${stats.lines.percentage}%"></div>
1435
+ </div>
1436
+ <div class="metric-count">${coverage.coveredLines}/${coverage.lines}</div>
1437
+ </div>
1438
+ </div>
1439
+ </div>
1440
+
1441
+ ${coverage.uncoveredLines && coverage.uncoveredLines.length > 0 ? `
1442
+ <div class="summary">
1443
+ <div class="summary-title">Uncovered Lines</div>
1444
+ <div style="font-size: 13px; color: #f85149;">${formatUncoveredLines(coverage.uncoveredLines)}</div>
1445
+ </div>
1446
+ ` : ""}
1447
+
1448
+ <div class="code-container">
1449
+ <div class="code-header">
1450
+ <span>Source Code</span>
1451
+ <div class="legend">
1452
+ <div class="legend-item"><div class="legend-box covered"></div><span>Covered</span></div>
1453
+ <div class="legend-item"><div class="legend-box uncovered"></div><span>Uncovered</span></div>
1454
+ </div>
1455
+ </div>
1456
+ <table class="code-table">
1457
+ ${sourceLines.map((line, index) => {
1458
+ const lineNum = index + 1;
1459
+ const isUncovered = uncoveredSet.has(lineNum);
1460
+ const isExecutable = coverage.lines > 0;
1461
+ const rowClass = isExecutable ? isUncovered ? "uncovered" : "covered" : "";
1462
+ return `
1463
+ <tr class="${rowClass}">
1464
+ <td class="line-number">${lineNum}</td>
1465
+ <td class="line-content">${escapeHtml(line) || " "}</td>
1466
+ </tr>
1467
+ `;
1468
+ }).join("")}
1469
+ </table>
1470
+ </div>
1471
+ </div>
1472
+ </body>
1473
+ </html>`;
1474
+ writeFileSync(join(reportsDir, safeFileName), fileHtml, "utf-8");
1475
+ }
1476
+ function escapeHtml(text) {
1477
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
1478
+ }
1479
+ function escapeXml(text) {
1480
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
1481
+ }
1482
+ function generateCoverageFinalJson(coverageMap, reportsDir) {
1483
+ const coverageData = {};
1484
+ for (const [filePath, coverage] of coverageMap.entries()) {
1485
+ const relativePath2 = relative(process.cwd(), filePath).replace(/\\/g, "/");
1486
+ const lineMap = {};
1487
+ const executableLines = getExecutableLines(filePath);
1488
+ for (const line of executableLines) {
1489
+ const isCovered = coverage.coveredStatements > 0;
1490
+ lineMap[line] = isCovered ? 1 : 0;
1491
+ }
1492
+ coverageData[relativePath2] = {
1493
+ lines: lineMap
1494
+ };
1495
+ }
1496
+ const jsonData = JSON.stringify(coverageData, null, 2);
1497
+ writeFileSync(join(reportsDir, "coverage-final.json"), jsonData, "utf-8");
1498
+ }
1499
+ function generateCloverXml(coverageMap, reportsDir) {
1500
+ const timestamp = Date.now();
1501
+ let totalFiles = 0;
1502
+ let totalClasses = 0;
1503
+ let totalElements = 0;
1504
+ let coveredElements = 0;
1505
+ let totalStatements = 0;
1506
+ let coveredStatements = 0;
1507
+ let totalBranches = 0;
1508
+ let coveredBranches = 0;
1509
+ let totalFunctions = 0;
1510
+ let coveredFunctions = 0;
1511
+ let totalLines = 0;
1512
+ let coveredLines = 0;
1513
+ const fileEntries = [];
1514
+ for (const [filePath, coverage] of coverageMap.entries()) {
1515
+ const relativePath2 = relative(process.cwd(), filePath).replace(/\\/g, "/");
1516
+ totalFiles++;
1517
+ totalClasses++;
1518
+ totalStatements += coverage.statements;
1519
+ coveredStatements += coverage.coveredStatements;
1520
+ totalBranches += coverage.branches;
1521
+ coveredBranches += coverage.coveredBranches;
1522
+ totalFunctions += coverage.functions;
1523
+ coveredFunctions += coverage.coveredFunctions;
1524
+ totalLines += coverage.lines;
1525
+ coveredLines += coverage.coveredLines;
1526
+ const fileElements = coverage.statements + coverage.branches + coverage.functions;
1527
+ const fileCoveredElements = coverage.coveredStatements + coverage.coveredBranches + coverage.coveredFunctions;
1528
+ totalElements += fileElements;
1529
+ coveredElements += fileCoveredElements;
1530
+ const escapedPath = escapeXml(relativePath2);
1531
+ fileEntries.push(`
1532
+ <file name="${escapedPath}">
1533
+ <class name="${escapedPath}">
1534
+ <metrics complexity="0" elements="${fileElements}" coveredelements="${fileCoveredElements}"
1535
+ methods="${coverage.functions}" coveredmethods="${coverage.coveredFunctions}"
1536
+ statements="${coverage.statements}" coveredstatements="${coverage.coveredStatements}" />
1537
+ </class>
1538
+ <line num="1" type="stmt" count="${coverage.coveredStatements > 0 ? 1 : 0}" />
1539
+ </file>`);
1540
+ }
1541
+ const complexity = 0;
1542
+ const elements = totalElements;
1543
+ const xml = `<?xml version="1.0" encoding="UTF-8"?>
1544
+ <coverage generated="${timestamp}" clover="3.2.0">
1545
+ <project timestamp="${timestamp}" name="Coverage">
1546
+ <metrics complexity="${complexity}" elements="${elements}" coveredelements="${coveredElements}"
1547
+ conditionals="${totalBranches}" coveredconditionals="${coveredBranches}"
1548
+ statements="${totalStatements}" coveredstatements="${coveredStatements}"
1549
+ methods="${totalFunctions}" coveredmethods="${coveredFunctions}"
1550
+ classes="${totalClasses}" coveredclasses="${coverageMap.size > 0 ? Array.from(coverageMap.values()).filter((c) => c.coveredStatements > 0).length : 0}"
1551
+ files="${totalFiles}" loc="${totalLines}" ncloc="${totalLines - coveredLines}"
1552
+ packages="${totalFiles}" classes="${totalClasses}" />
1553
+ <package name="root">
1554
+ <metrics complexity="${complexity}" elements="${elements}" coveredelements="${coveredElements}"
1555
+ conditionals="${totalBranches}" coveredconditionals="${coveredBranches}"
1556
+ statements="${totalStatements}" coveredstatements="${coveredStatements}"
1557
+ methods="${totalFunctions}" coveredmethods="${coveredFunctions}"
1558
+ classes="${totalClasses}" coveredclasses="${coverageMap.size > 0 ? Array.from(coverageMap.values()).filter((c) => c.coveredStatements > 0).length : 0}"
1559
+ files="${totalFiles}" loc="${totalLines}" ncloc="${totalLines - coveredLines}" />
1560
+ ${fileEntries.join("")}
1561
+ </package>
1562
+ </project>
1563
+ </coverage>`;
1564
+ writeFileSync(join(reportsDir, "clover.xml"), xml, "utf-8");
1565
+ }
1566
+ var executedLinesMap, totalLinesMap, colors2;
1567
+ var init_coverage = __esm({
1568
+ "src/coverage.ts"() {
1569
+ "use strict";
1570
+ init_fs();
1571
+ init_path();
1572
+ executedLinesMap = /* @__PURE__ */ new Map();
1573
+ totalLinesMap = /* @__PURE__ */ new Map();
1574
+ colors2 = {
1575
+ reset: "\x1B[0m",
1576
+ bold: "\x1B[1m",
1577
+ dim: "\x1B[2m",
1578
+ red: "\x1B[31m",
1579
+ green: "\x1B[32m",
1580
+ yellow: "\x1B[33m",
1581
+ cyan: "\x1B[36m"
1582
+ };
1583
+ }
1584
+ });
1585
+
1586
+ // node_modules/readdirp/esm/index.js
1587
+ function readdirp(root, options = {}) {
1588
+ let type = options.entryType || options.type;
1589
+ if (type === "both")
1590
+ type = EntryTypes.FILE_DIR_TYPE;
1591
+ if (type)
1592
+ options.type = type;
1593
+ if (!root) {
1594
+ throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");
1595
+ } else if (typeof root !== "string") {
1596
+ throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");
1597
+ } else if (type && !ALL_TYPES.includes(type)) {
1598
+ throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(", ")}`);
1599
+ }
1600
+ options.root = root;
1601
+ return new ReaddirpStream(options);
1602
+ }
1603
+ var import_promises, import_node_stream, import_node_path, EntryTypes, defaultOptions, RECURSIVE_ERROR_CODE, NORMAL_FLOW_ERRORS, ALL_TYPES, DIR_TYPES, FILE_TYPES, isNormalFlowError, wantBigintFsStats, emptyFn, normalizeFilter, ReaddirpStream;
1604
+ var init_esm = __esm({
1605
+ "node_modules/readdirp/esm/index.js"() {
1606
+ "use strict";
1607
+ import_promises = require("fs/promises");
1608
+ import_node_stream = require("stream");
1609
+ import_node_path = require("path");
1610
+ EntryTypes = {
1611
+ FILE_TYPE: "files",
1612
+ DIR_TYPE: "directories",
1613
+ FILE_DIR_TYPE: "files_directories",
1614
+ EVERYTHING_TYPE: "all"
1615
+ };
1616
+ defaultOptions = {
1617
+ root: ".",
1618
+ fileFilter: (_entryInfo) => true,
1619
+ directoryFilter: (_entryInfo) => true,
1620
+ type: EntryTypes.FILE_TYPE,
1621
+ lstat: false,
1622
+ depth: 2147483648,
1623
+ alwaysStat: false,
1624
+ highWaterMark: 4096
1625
+ };
1626
+ Object.freeze(defaultOptions);
1627
+ RECURSIVE_ERROR_CODE = "READDIRP_RECURSIVE_ERROR";
1628
+ NORMAL_FLOW_ERRORS = /* @__PURE__ */ new Set(["ENOENT", "EPERM", "EACCES", "ELOOP", RECURSIVE_ERROR_CODE]);
1629
+ ALL_TYPES = [
1630
+ EntryTypes.DIR_TYPE,
1631
+ EntryTypes.EVERYTHING_TYPE,
1632
+ EntryTypes.FILE_DIR_TYPE,
1633
+ EntryTypes.FILE_TYPE
1634
+ ];
1635
+ DIR_TYPES = /* @__PURE__ */ new Set([
1636
+ EntryTypes.DIR_TYPE,
1637
+ EntryTypes.EVERYTHING_TYPE,
1638
+ EntryTypes.FILE_DIR_TYPE
1639
+ ]);
1640
+ FILE_TYPES = /* @__PURE__ */ new Set([
1641
+ EntryTypes.EVERYTHING_TYPE,
1642
+ EntryTypes.FILE_DIR_TYPE,
1643
+ EntryTypes.FILE_TYPE
1644
+ ]);
1645
+ isNormalFlowError = (error) => NORMAL_FLOW_ERRORS.has(error.code);
1646
+ wantBigintFsStats = process.platform === "win32";
1647
+ emptyFn = (_entryInfo) => true;
1648
+ normalizeFilter = (filter) => {
1649
+ if (filter === void 0)
1650
+ return emptyFn;
1651
+ if (typeof filter === "function")
1652
+ return filter;
1653
+ if (typeof filter === "string") {
1654
+ const fl = filter.trim();
1655
+ return (entry) => entry.basename === fl;
1656
+ }
1657
+ if (Array.isArray(filter)) {
1658
+ const trItems = filter.map((item) => item.trim());
1659
+ return (entry) => trItems.some((f) => entry.basename === f);
1660
+ }
1661
+ return emptyFn;
1662
+ };
1663
+ ReaddirpStream = class extends import_node_stream.Readable {
1664
+ constructor(options = {}) {
1665
+ super({
1666
+ objectMode: true,
1667
+ autoDestroy: true,
1668
+ highWaterMark: options.highWaterMark
1669
+ });
1670
+ const opts = { ...defaultOptions, ...options };
1671
+ const { root, type } = opts;
1672
+ this._fileFilter = normalizeFilter(opts.fileFilter);
1673
+ this._directoryFilter = normalizeFilter(opts.directoryFilter);
1674
+ const statMethod = opts.lstat ? import_promises.lstat : import_promises.stat;
1675
+ if (wantBigintFsStats) {
1676
+ this._stat = (path) => statMethod(path, { bigint: true });
1677
+ } else {
1678
+ this._stat = statMethod;
1679
+ }
1680
+ this._maxDepth = opts.depth ?? defaultOptions.depth;
1681
+ this._wantsDir = type ? DIR_TYPES.has(type) : false;
1682
+ this._wantsFile = type ? FILE_TYPES.has(type) : false;
1683
+ this._wantsEverything = type === EntryTypes.EVERYTHING_TYPE;
1684
+ this._root = (0, import_node_path.resolve)(root);
1685
+ this._isDirent = !opts.alwaysStat;
1686
+ this._statsProp = this._isDirent ? "dirent" : "stats";
1687
+ this._rdOptions = { encoding: "utf8", withFileTypes: this._isDirent };
1688
+ this.parents = [this._exploreDir(root, 1)];
1689
+ this.reading = false;
1690
+ this.parent = void 0;
1691
+ }
1692
+ async _read(batch) {
1693
+ if (this.reading)
1694
+ return;
1695
+ this.reading = true;
1696
+ try {
1697
+ while (!this.destroyed && batch > 0) {
1698
+ const par = this.parent;
1699
+ const fil = par && par.files;
1700
+ if (fil && fil.length > 0) {
1701
+ const { path, depth } = par;
1702
+ const slice = fil.splice(0, batch).map((dirent) => this._formatEntry(dirent, path));
1703
+ const awaited = await Promise.all(slice);
1704
+ for (const entry of awaited) {
1705
+ if (!entry)
1706
+ continue;
1707
+ if (this.destroyed)
1708
+ return;
1709
+ const entryType = await this._getEntryType(entry);
1710
+ if (entryType === "directory" && this._directoryFilter(entry)) {
1711
+ if (depth <= this._maxDepth) {
1712
+ this.parents.push(this._exploreDir(entry.fullPath, depth + 1));
1713
+ }
1714
+ if (this._wantsDir) {
1715
+ this.push(entry);
1716
+ batch--;
1717
+ }
1718
+ } else if ((entryType === "file" || this._includeAsFile(entry)) && this._fileFilter(entry)) {
1719
+ if (this._wantsFile) {
1720
+ this.push(entry);
1721
+ batch--;
1722
+ }
1723
+ }
1724
+ }
1725
+ } else {
1726
+ const parent = this.parents.pop();
1727
+ if (!parent) {
1728
+ this.push(null);
1729
+ break;
1730
+ }
1731
+ this.parent = await parent;
1732
+ if (this.destroyed)
1733
+ return;
1734
+ }
1735
+ }
1736
+ } catch (error) {
1737
+ this.destroy(error);
1738
+ } finally {
1739
+ this.reading = false;
1740
+ }
1741
+ }
1742
+ async _exploreDir(path, depth) {
1743
+ let files;
1744
+ try {
1745
+ files = await (0, import_promises.readdir)(path, this._rdOptions);
1746
+ } catch (error) {
1747
+ this._onError(error);
1748
+ }
1749
+ return { files, depth, path };
1750
+ }
1751
+ async _formatEntry(dirent, path) {
1752
+ let entry;
1753
+ const basename3 = this._isDirent ? dirent.name : dirent;
1754
+ try {
1755
+ const fullPath = (0, import_node_path.resolve)((0, import_node_path.join)(path, basename3));
1756
+ entry = { path: (0, import_node_path.relative)(this._root, fullPath), fullPath, basename: basename3 };
1757
+ entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
1758
+ } catch (err) {
1759
+ this._onError(err);
1760
+ return;
1761
+ }
1762
+ return entry;
1763
+ }
1764
+ _onError(err) {
1765
+ if (isNormalFlowError(err) && !this.destroyed) {
1766
+ this.emit("warn", err);
1767
+ } else {
1768
+ this.destroy(err);
1769
+ }
1770
+ }
1771
+ async _getEntryType(entry) {
1772
+ if (!entry && this._statsProp in entry) {
1773
+ return "";
1774
+ }
1775
+ const stats = entry[this._statsProp];
1776
+ if (stats.isFile())
1777
+ return "file";
1778
+ if (stats.isDirectory())
1779
+ return "directory";
1780
+ if (stats && stats.isSymbolicLink()) {
1781
+ const full = entry.fullPath;
1782
+ try {
1783
+ const entryRealPath = await (0, import_promises.realpath)(full);
1784
+ const entryRealPathStats = await (0, import_promises.lstat)(entryRealPath);
1785
+ if (entryRealPathStats.isFile()) {
1786
+ return "file";
1787
+ }
1788
+ if (entryRealPathStats.isDirectory()) {
1789
+ const len = entryRealPath.length;
1790
+ if (full.startsWith(entryRealPath) && full.substr(len, 1) === import_node_path.sep) {
1791
+ const recursiveError = new Error(`Circular symlink detected: "${full}" points to "${entryRealPath}"`);
1792
+ recursiveError.code = RECURSIVE_ERROR_CODE;
1793
+ return this._onError(recursiveError);
1794
+ }
1795
+ return "directory";
1796
+ }
1797
+ } catch (error) {
1798
+ this._onError(error);
1799
+ return "";
1800
+ }
1801
+ }
1802
+ }
1803
+ _includeAsFile(entry) {
1804
+ const stats = entry && entry[this._statsProp];
1805
+ return stats && this._wantsEverything && !stats.isDirectory();
1806
+ }
1807
+ };
1808
+ }
1809
+ });
1810
+
1811
+ // node_modules/chokidar/esm/handler.js
1812
+ function createFsWatchInstance(path, options, listener, errHandler, emitRaw) {
1813
+ const handleEvent = (rawEvent, evPath) => {
1814
+ listener(path);
1815
+ emitRaw(rawEvent, evPath, { watchedPath: path });
1816
+ if (evPath && path !== evPath) {
1817
+ fsWatchBroadcast(sysPath.resolve(path, evPath), KEY_LISTENERS, sysPath.join(path, evPath));
1818
+ }
1819
+ };
1820
+ try {
1821
+ return (0, import_fs3.watch)(path, {
1822
+ persistent: options.persistent
1823
+ }, handleEvent);
1824
+ } catch (error) {
1825
+ errHandler(error);
1826
+ return void 0;
1827
+ }
1828
+ }
1829
+ var import_fs3, import_promises2, sysPath, import_os, STR_DATA, STR_END, STR_CLOSE, EMPTY_FN, pl, isWindows2, isMacos, isLinux, isFreeBSD, isIBMi, EVENTS, EV, THROTTLE_MODE_WATCH, statMethods, KEY_LISTENERS, KEY_ERR, KEY_RAW, HANDLER_KEYS, binaryExtensions, isBinaryPath, foreach, addAndConvert, clearItem, delFromSet, isEmptySet, FsWatchInstances, fsWatchBroadcast, setFsWatchListener, FsWatchFileInstances, setFsWatchFileListener, NodeFsHandler;
1830
+ var init_handler = __esm({
1831
+ "node_modules/chokidar/esm/handler.js"() {
1832
+ "use strict";
1833
+ import_fs3 = require("fs");
1834
+ import_promises2 = require("fs/promises");
1835
+ sysPath = __toESM(require("path"), 1);
1836
+ import_os = require("os");
1837
+ STR_DATA = "data";
1838
+ STR_END = "end";
1839
+ STR_CLOSE = "close";
1840
+ EMPTY_FN = () => {
1841
+ };
1842
+ pl = process.platform;
1843
+ isWindows2 = pl === "win32";
1844
+ isMacos = pl === "darwin";
1845
+ isLinux = pl === "linux";
1846
+ isFreeBSD = pl === "freebsd";
1847
+ isIBMi = (0, import_os.type)() === "OS400";
1848
+ EVENTS = {
1849
+ ALL: "all",
1850
+ READY: "ready",
1851
+ ADD: "add",
1852
+ CHANGE: "change",
1853
+ ADD_DIR: "addDir",
1854
+ UNLINK: "unlink",
1855
+ UNLINK_DIR: "unlinkDir",
1856
+ RAW: "raw",
1857
+ ERROR: "error"
1858
+ };
1859
+ EV = EVENTS;
1860
+ THROTTLE_MODE_WATCH = "watch";
1861
+ statMethods = { lstat: import_promises2.lstat, stat: import_promises2.stat };
1862
+ KEY_LISTENERS = "listeners";
1863
+ KEY_ERR = "errHandlers";
1864
+ KEY_RAW = "rawEmitters";
1865
+ HANDLER_KEYS = [KEY_LISTENERS, KEY_ERR, KEY_RAW];
1866
+ binaryExtensions = /* @__PURE__ */ new Set([
1867
+ "3dm",
1868
+ "3ds",
1869
+ "3g2",
1870
+ "3gp",
1871
+ "7z",
1872
+ "a",
1873
+ "aac",
1874
+ "adp",
1875
+ "afdesign",
1876
+ "afphoto",
1877
+ "afpub",
1878
+ "ai",
1879
+ "aif",
1880
+ "aiff",
1881
+ "alz",
1882
+ "ape",
1883
+ "apk",
1884
+ "appimage",
1885
+ "ar",
1886
+ "arj",
1887
+ "asf",
1888
+ "au",
1889
+ "avi",
1890
+ "bak",
1891
+ "baml",
1892
+ "bh",
1893
+ "bin",
1894
+ "bk",
1895
+ "bmp",
1896
+ "btif",
1897
+ "bz2",
1898
+ "bzip2",
1899
+ "cab",
1900
+ "caf",
1901
+ "cgm",
1902
+ "class",
1903
+ "cmx",
1904
+ "cpio",
1905
+ "cr2",
1906
+ "cur",
1907
+ "dat",
1908
+ "dcm",
1909
+ "deb",
1910
+ "dex",
1911
+ "djvu",
1912
+ "dll",
1913
+ "dmg",
1914
+ "dng",
1915
+ "doc",
1916
+ "docm",
1917
+ "docx",
1918
+ "dot",
1919
+ "dotm",
1920
+ "dra",
1921
+ "DS_Store",
1922
+ "dsk",
1923
+ "dts",
1924
+ "dtshd",
1925
+ "dvb",
1926
+ "dwg",
1927
+ "dxf",
1928
+ "ecelp4800",
1929
+ "ecelp7470",
1930
+ "ecelp9600",
1931
+ "egg",
1932
+ "eol",
1933
+ "eot",
1934
+ "epub",
1935
+ "exe",
1936
+ "f4v",
1937
+ "fbs",
1938
+ "fh",
1939
+ "fla",
1940
+ "flac",
1941
+ "flatpak",
1942
+ "fli",
1943
+ "flv",
1944
+ "fpx",
1945
+ "fst",
1946
+ "fvt",
1947
+ "g3",
1948
+ "gh",
1949
+ "gif",
1950
+ "graffle",
1951
+ "gz",
1952
+ "gzip",
1953
+ "h261",
1954
+ "h263",
1955
+ "h264",
1956
+ "icns",
1957
+ "ico",
1958
+ "ief",
1959
+ "img",
1960
+ "ipa",
1961
+ "iso",
1962
+ "jar",
1963
+ "jpeg",
1964
+ "jpg",
1965
+ "jpgv",
1966
+ "jpm",
1967
+ "jxr",
1968
+ "key",
1969
+ "ktx",
1970
+ "lha",
1971
+ "lib",
1972
+ "lvp",
1973
+ "lz",
1974
+ "lzh",
1975
+ "lzma",
1976
+ "lzo",
1977
+ "m3u",
1978
+ "m4a",
1979
+ "m4v",
1980
+ "mar",
1981
+ "mdi",
1982
+ "mht",
1983
+ "mid",
1984
+ "midi",
1985
+ "mj2",
1986
+ "mka",
1987
+ "mkv",
1988
+ "mmr",
1989
+ "mng",
1990
+ "mobi",
1991
+ "mov",
1992
+ "movie",
1993
+ "mp3",
1994
+ "mp4",
1995
+ "mp4a",
1996
+ "mpeg",
1997
+ "mpg",
1998
+ "mpga",
1999
+ "mxu",
2000
+ "nef",
2001
+ "npx",
2002
+ "numbers",
2003
+ "nupkg",
2004
+ "o",
2005
+ "odp",
2006
+ "ods",
2007
+ "odt",
2008
+ "oga",
2009
+ "ogg",
2010
+ "ogv",
2011
+ "otf",
2012
+ "ott",
2013
+ "pages",
2014
+ "pbm",
2015
+ "pcx",
2016
+ "pdb",
2017
+ "pdf",
2018
+ "pea",
2019
+ "pgm",
2020
+ "pic",
2021
+ "png",
2022
+ "pnm",
2023
+ "pot",
2024
+ "potm",
2025
+ "potx",
2026
+ "ppa",
2027
+ "ppam",
2028
+ "ppm",
2029
+ "pps",
2030
+ "ppsm",
2031
+ "ppsx",
2032
+ "ppt",
2033
+ "pptm",
2034
+ "pptx",
2035
+ "psd",
2036
+ "pya",
2037
+ "pyc",
2038
+ "pyo",
2039
+ "pyv",
2040
+ "qt",
2041
+ "rar",
2042
+ "ras",
2043
+ "raw",
2044
+ "resources",
2045
+ "rgb",
2046
+ "rip",
2047
+ "rlc",
2048
+ "rmf",
2049
+ "rmvb",
2050
+ "rpm",
2051
+ "rtf",
2052
+ "rz",
2053
+ "s3m",
2054
+ "s7z",
2055
+ "scpt",
2056
+ "sgi",
2057
+ "shar",
2058
+ "snap",
2059
+ "sil",
2060
+ "sketch",
2061
+ "slk",
2062
+ "smv",
2063
+ "snk",
2064
+ "so",
2065
+ "stl",
2066
+ "suo",
2067
+ "sub",
2068
+ "swf",
2069
+ "tar",
2070
+ "tbz",
2071
+ "tbz2",
2072
+ "tga",
2073
+ "tgz",
2074
+ "thmx",
2075
+ "tif",
2076
+ "tiff",
2077
+ "tlz",
2078
+ "ttc",
2079
+ "ttf",
2080
+ "txz",
2081
+ "udf",
2082
+ "uvh",
2083
+ "uvi",
2084
+ "uvm",
2085
+ "uvp",
2086
+ "uvs",
2087
+ "uvu",
2088
+ "viv",
2089
+ "vob",
2090
+ "war",
2091
+ "wav",
2092
+ "wax",
2093
+ "wbmp",
2094
+ "wdp",
2095
+ "weba",
2096
+ "webm",
2097
+ "webp",
2098
+ "whl",
2099
+ "wim",
2100
+ "wm",
2101
+ "wma",
2102
+ "wmv",
2103
+ "wmx",
2104
+ "woff",
2105
+ "woff2",
2106
+ "wrm",
2107
+ "wvx",
2108
+ "xbm",
2109
+ "xif",
2110
+ "xla",
2111
+ "xlam",
2112
+ "xls",
2113
+ "xlsb",
2114
+ "xlsm",
2115
+ "xlsx",
2116
+ "xlt",
2117
+ "xltm",
2118
+ "xltx",
2119
+ "xm",
2120
+ "xmind",
2121
+ "xpi",
2122
+ "xpm",
2123
+ "xwd",
2124
+ "xz",
2125
+ "z",
2126
+ "zip",
2127
+ "zipx"
2128
+ ]);
2129
+ isBinaryPath = (filePath) => binaryExtensions.has(sysPath.extname(filePath).slice(1).toLowerCase());
2130
+ foreach = (val, fn) => {
2131
+ if (val instanceof Set) {
2132
+ val.forEach(fn);
2133
+ } else {
2134
+ fn(val);
2135
+ }
2136
+ };
2137
+ addAndConvert = (main, prop, item) => {
2138
+ let container = main[prop];
2139
+ if (!(container instanceof Set)) {
2140
+ main[prop] = container = /* @__PURE__ */ new Set([container]);
2141
+ }
2142
+ container.add(item);
2143
+ };
2144
+ clearItem = (cont) => (key) => {
2145
+ const set = cont[key];
2146
+ if (set instanceof Set) {
2147
+ set.clear();
2148
+ } else {
2149
+ delete cont[key];
2150
+ }
2151
+ };
2152
+ delFromSet = (main, prop, item) => {
2153
+ const container = main[prop];
2154
+ if (container instanceof Set) {
2155
+ container.delete(item);
2156
+ } else if (container === item) {
2157
+ delete main[prop];
2158
+ }
2159
+ };
2160
+ isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;
2161
+ FsWatchInstances = /* @__PURE__ */ new Map();
2162
+ fsWatchBroadcast = (fullPath, listenerType, val1, val2, val3) => {
2163
+ const cont = FsWatchInstances.get(fullPath);
2164
+ if (!cont)
2165
+ return;
2166
+ foreach(cont[listenerType], (listener) => {
2167
+ listener(val1, val2, val3);
2168
+ });
2169
+ };
2170
+ setFsWatchListener = (path, fullPath, options, handlers) => {
2171
+ const { listener, errHandler, rawEmitter } = handlers;
2172
+ let cont = FsWatchInstances.get(fullPath);
2173
+ let watcher;
2174
+ if (!options.persistent) {
2175
+ watcher = createFsWatchInstance(path, options, listener, errHandler, rawEmitter);
2176
+ if (!watcher)
2177
+ return;
2178
+ return watcher.close.bind(watcher);
2179
+ }
2180
+ if (cont) {
2181
+ addAndConvert(cont, KEY_LISTENERS, listener);
2182
+ addAndConvert(cont, KEY_ERR, errHandler);
2183
+ addAndConvert(cont, KEY_RAW, rawEmitter);
2184
+ } else {
2185
+ watcher = createFsWatchInstance(
2186
+ path,
2187
+ options,
2188
+ fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS),
2189
+ errHandler,
2190
+ // no need to use broadcast here
2191
+ fsWatchBroadcast.bind(null, fullPath, KEY_RAW)
2192
+ );
2193
+ if (!watcher)
2194
+ return;
2195
+ watcher.on(EV.ERROR, async (error) => {
2196
+ const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
2197
+ if (cont)
2198
+ cont.watcherUnusable = true;
2199
+ if (isWindows2 && error.code === "EPERM") {
2200
+ try {
2201
+ const fd = await (0, import_promises2.open)(path, "r");
2202
+ await fd.close();
2203
+ broadcastErr(error);
2204
+ } catch (err) {
2205
+ }
2206
+ } else {
2207
+ broadcastErr(error);
2208
+ }
2209
+ });
2210
+ cont = {
2211
+ listeners: listener,
2212
+ errHandlers: errHandler,
2213
+ rawEmitters: rawEmitter,
2214
+ watcher
2215
+ };
2216
+ FsWatchInstances.set(fullPath, cont);
2217
+ }
2218
+ return () => {
2219
+ delFromSet(cont, KEY_LISTENERS, listener);
2220
+ delFromSet(cont, KEY_ERR, errHandler);
2221
+ delFromSet(cont, KEY_RAW, rawEmitter);
2222
+ if (isEmptySet(cont.listeners)) {
2223
+ cont.watcher.close();
2224
+ FsWatchInstances.delete(fullPath);
2225
+ HANDLER_KEYS.forEach(clearItem(cont));
2226
+ cont.watcher = void 0;
2227
+ Object.freeze(cont);
2228
+ }
2229
+ };
2230
+ };
2231
+ FsWatchFileInstances = /* @__PURE__ */ new Map();
2232
+ setFsWatchFileListener = (path, fullPath, options, handlers) => {
2233
+ const { listener, rawEmitter } = handlers;
2234
+ let cont = FsWatchFileInstances.get(fullPath);
2235
+ const copts = cont && cont.options;
2236
+ if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
2237
+ (0, import_fs3.unwatchFile)(fullPath);
2238
+ cont = void 0;
2239
+ }
2240
+ if (cont) {
2241
+ addAndConvert(cont, KEY_LISTENERS, listener);
2242
+ addAndConvert(cont, KEY_RAW, rawEmitter);
2243
+ } else {
2244
+ cont = {
2245
+ listeners: listener,
2246
+ rawEmitters: rawEmitter,
2247
+ options,
2248
+ watcher: (0, import_fs3.watchFile)(fullPath, options, (curr, prev) => {
2249
+ foreach(cont.rawEmitters, (rawEmitter2) => {
2250
+ rawEmitter2(EV.CHANGE, fullPath, { curr, prev });
2251
+ });
2252
+ const currmtime = curr.mtimeMs;
2253
+ if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {
2254
+ foreach(cont.listeners, (listener2) => listener2(path, curr));
2255
+ }
2256
+ })
2257
+ };
2258
+ FsWatchFileInstances.set(fullPath, cont);
2259
+ }
2260
+ return () => {
2261
+ delFromSet(cont, KEY_LISTENERS, listener);
2262
+ delFromSet(cont, KEY_RAW, rawEmitter);
2263
+ if (isEmptySet(cont.listeners)) {
2264
+ FsWatchFileInstances.delete(fullPath);
2265
+ (0, import_fs3.unwatchFile)(fullPath);
2266
+ cont.options = cont.watcher = void 0;
2267
+ Object.freeze(cont);
2268
+ }
2269
+ };
2270
+ };
2271
+ NodeFsHandler = class {
2272
+ constructor(fsW) {
2273
+ this.fsw = fsW;
2274
+ this._boundHandleError = (error) => fsW._handleError(error);
2275
+ }
2276
+ /**
2277
+ * Watch file for changes with fs_watchFile or fs_watch.
2278
+ * @param path to file or dir
2279
+ * @param listener on fs change
2280
+ * @returns closer for the watcher instance
2281
+ */
2282
+ _watchWithNodeFs(path, listener) {
2283
+ const opts = this.fsw.options;
2284
+ const directory = sysPath.dirname(path);
2285
+ const basename3 = sysPath.basename(path);
2286
+ const parent = this.fsw._getWatchedDir(directory);
2287
+ parent.add(basename3);
2288
+ const absolutePath = sysPath.resolve(path);
2289
+ const options = {
2290
+ persistent: opts.persistent
2291
+ };
2292
+ if (!listener)
2293
+ listener = EMPTY_FN;
2294
+ let closer;
2295
+ if (opts.usePolling) {
2296
+ const enableBin = opts.interval !== opts.binaryInterval;
2297
+ options.interval = enableBin && isBinaryPath(basename3) ? opts.binaryInterval : opts.interval;
2298
+ closer = setFsWatchFileListener(path, absolutePath, options, {
2299
+ listener,
2300
+ rawEmitter: this.fsw._emitRaw
2301
+ });
2302
+ } else {
2303
+ closer = setFsWatchListener(path, absolutePath, options, {
2304
+ listener,
2305
+ errHandler: this._boundHandleError,
2306
+ rawEmitter: this.fsw._emitRaw
2307
+ });
2308
+ }
2309
+ return closer;
2310
+ }
2311
+ /**
2312
+ * Watch a file and emit add event if warranted.
2313
+ * @returns closer for the watcher instance
2314
+ */
2315
+ _handleFile(file, stats, initialAdd) {
2316
+ if (this.fsw.closed) {
2317
+ return;
2318
+ }
2319
+ const dirname4 = sysPath.dirname(file);
2320
+ const basename3 = sysPath.basename(file);
2321
+ const parent = this.fsw._getWatchedDir(dirname4);
2322
+ let prevStats = stats;
2323
+ if (parent.has(basename3))
2324
+ return;
2325
+ const listener = async (path, newStats) => {
2326
+ if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5))
2327
+ return;
2328
+ if (!newStats || newStats.mtimeMs === 0) {
2329
+ try {
2330
+ const newStats2 = await (0, import_promises2.stat)(file);
2331
+ if (this.fsw.closed)
2332
+ return;
2333
+ const at = newStats2.atimeMs;
2334
+ const mt = newStats2.mtimeMs;
2335
+ if (!at || at <= mt || mt !== prevStats.mtimeMs) {
2336
+ this.fsw._emit(EV.CHANGE, file, newStats2);
2337
+ }
2338
+ if ((isMacos || isLinux || isFreeBSD) && prevStats.ino !== newStats2.ino) {
2339
+ this.fsw._closeFile(path);
2340
+ prevStats = newStats2;
2341
+ const closer2 = this._watchWithNodeFs(file, listener);
2342
+ if (closer2)
2343
+ this.fsw._addPathCloser(path, closer2);
2344
+ } else {
2345
+ prevStats = newStats2;
2346
+ }
2347
+ } catch (error) {
2348
+ this.fsw._remove(dirname4, basename3);
2349
+ }
2350
+ } else if (parent.has(basename3)) {
2351
+ const at = newStats.atimeMs;
2352
+ const mt = newStats.mtimeMs;
2353
+ if (!at || at <= mt || mt !== prevStats.mtimeMs) {
2354
+ this.fsw._emit(EV.CHANGE, file, newStats);
2355
+ }
2356
+ prevStats = newStats;
2357
+ }
2358
+ };
2359
+ const closer = this._watchWithNodeFs(file, listener);
2360
+ if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {
2361
+ if (!this.fsw._throttle(EV.ADD, file, 0))
2362
+ return;
2363
+ this.fsw._emit(EV.ADD, file, stats);
2364
+ }
2365
+ return closer;
2366
+ }
2367
+ /**
2368
+ * Handle symlinks encountered while reading a dir.
2369
+ * @param entry returned by readdirp
2370
+ * @param directory path of dir being read
2371
+ * @param path of this item
2372
+ * @param item basename of this item
2373
+ * @returns true if no more processing is needed for this entry.
2374
+ */
2375
+ async _handleSymlink(entry, directory, path, item) {
2376
+ if (this.fsw.closed) {
2377
+ return;
2378
+ }
2379
+ const full = entry.fullPath;
2380
+ const dir = this.fsw._getWatchedDir(directory);
2381
+ if (!this.fsw.options.followSymlinks) {
2382
+ this.fsw._incrReadyCount();
2383
+ let linkPath;
2384
+ try {
2385
+ linkPath = await (0, import_promises2.realpath)(path);
2386
+ } catch (e) {
2387
+ this.fsw._emitReady();
2388
+ return true;
2389
+ }
2390
+ if (this.fsw.closed)
2391
+ return;
2392
+ if (dir.has(item)) {
2393
+ if (this.fsw._symlinkPaths.get(full) !== linkPath) {
2394
+ this.fsw._symlinkPaths.set(full, linkPath);
2395
+ this.fsw._emit(EV.CHANGE, path, entry.stats);
2396
+ }
2397
+ } else {
2398
+ dir.add(item);
2399
+ this.fsw._symlinkPaths.set(full, linkPath);
2400
+ this.fsw._emit(EV.ADD, path, entry.stats);
2401
+ }
2402
+ this.fsw._emitReady();
2403
+ return true;
2404
+ }
2405
+ if (this.fsw._symlinkPaths.has(full)) {
2406
+ return true;
2407
+ }
2408
+ this.fsw._symlinkPaths.set(full, true);
2409
+ }
2410
+ _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
2411
+ directory = sysPath.join(directory, "");
2412
+ throttler = this.fsw._throttle("readdir", directory, 1e3);
2413
+ if (!throttler)
2414
+ return;
2415
+ const previous = this.fsw._getWatchedDir(wh.path);
2416
+ const current = /* @__PURE__ */ new Set();
2417
+ let stream = this.fsw._readdirp(directory, {
2418
+ fileFilter: (entry) => wh.filterPath(entry),
2419
+ directoryFilter: (entry) => wh.filterDir(entry)
2420
+ });
2421
+ if (!stream)
2422
+ return;
2423
+ stream.on(STR_DATA, async (entry) => {
2424
+ if (this.fsw.closed) {
2425
+ stream = void 0;
2426
+ return;
2427
+ }
2428
+ const item = entry.path;
2429
+ let path = sysPath.join(directory, item);
2430
+ current.add(item);
2431
+ if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path, item)) {
2432
+ return;
2433
+ }
2434
+ if (this.fsw.closed) {
2435
+ stream = void 0;
2436
+ return;
2437
+ }
2438
+ if (item === target || !target && !previous.has(item)) {
2439
+ this.fsw._incrReadyCount();
2440
+ path = sysPath.join(dir, sysPath.relative(dir, path));
2441
+ this._addToNodeFs(path, initialAdd, wh, depth + 1);
2442
+ }
2443
+ }).on(EV.ERROR, this._boundHandleError);
2444
+ return new Promise((resolve3, reject) => {
2445
+ if (!stream)
2446
+ return reject();
2447
+ stream.once(STR_END, () => {
2448
+ if (this.fsw.closed) {
2449
+ stream = void 0;
2450
+ return;
2451
+ }
2452
+ const wasThrottled = throttler ? throttler.clear() : false;
2453
+ resolve3(void 0);
2454
+ previous.getChildren().filter((item) => {
2455
+ return item !== directory && !current.has(item);
2456
+ }).forEach((item) => {
2457
+ this.fsw._remove(directory, item);
2458
+ });
2459
+ stream = void 0;
2460
+ if (wasThrottled)
2461
+ this._handleRead(directory, false, wh, target, dir, depth, throttler);
2462
+ });
2463
+ });
2464
+ }
2465
+ /**
2466
+ * Read directory to add / remove files from `@watched` list and re-read it on change.
2467
+ * @param dir fs path
2468
+ * @param stats
2469
+ * @param initialAdd
2470
+ * @param depth relative to user-supplied path
2471
+ * @param target child path targeted for watch
2472
+ * @param wh Common watch helpers for this path
2473
+ * @param realpath
2474
+ * @returns closer for the watcher instance.
2475
+ */
2476
+ async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath2) {
2477
+ const parentDir = this.fsw._getWatchedDir(sysPath.dirname(dir));
2478
+ const tracked = parentDir.has(sysPath.basename(dir));
2479
+ if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {
2480
+ this.fsw._emit(EV.ADD_DIR, dir, stats);
2481
+ }
2482
+ parentDir.add(sysPath.basename(dir));
2483
+ this.fsw._getWatchedDir(dir);
2484
+ let throttler;
2485
+ let closer;
2486
+ const oDepth = this.fsw.options.depth;
2487
+ if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath2)) {
2488
+ if (!target) {
2489
+ await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
2490
+ if (this.fsw.closed)
2491
+ return;
2492
+ }
2493
+ closer = this._watchWithNodeFs(dir, (dirPath, stats2) => {
2494
+ if (stats2 && stats2.mtimeMs === 0)
2495
+ return;
2496
+ this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
2497
+ });
2498
+ }
2499
+ return closer;
2500
+ }
2501
+ /**
2502
+ * Handle added file, directory, or glob pattern.
2503
+ * Delegates call to _handleFile / _handleDir after checks.
2504
+ * @param path to file or ir
2505
+ * @param initialAdd was the file added at watch instantiation?
2506
+ * @param priorWh depth relative to user-supplied path
2507
+ * @param depth Child path actually targeted for watch
2508
+ * @param target Child path actually targeted for watch
2509
+ */
2510
+ async _addToNodeFs(path, initialAdd, priorWh, depth, target) {
2511
+ const ready = this.fsw._emitReady;
2512
+ if (this.fsw._isIgnored(path) || this.fsw.closed) {
2513
+ ready();
2514
+ return false;
2515
+ }
2516
+ const wh = this.fsw._getWatchHelpers(path);
2517
+ if (priorWh) {
2518
+ wh.filterPath = (entry) => priorWh.filterPath(entry);
2519
+ wh.filterDir = (entry) => priorWh.filterDir(entry);
2520
+ }
2521
+ try {
2522
+ const stats = await statMethods[wh.statMethod](wh.watchPath);
2523
+ if (this.fsw.closed)
2524
+ return;
2525
+ if (this.fsw._isIgnored(wh.watchPath, stats)) {
2526
+ ready();
2527
+ return false;
2528
+ }
2529
+ const follow = this.fsw.options.followSymlinks;
2530
+ let closer;
2531
+ if (stats.isDirectory()) {
2532
+ const absPath = sysPath.resolve(path);
2533
+ const targetPath = follow ? await (0, import_promises2.realpath)(path) : path;
2534
+ if (this.fsw.closed)
2535
+ return;
2536
+ closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
2537
+ if (this.fsw.closed)
2538
+ return;
2539
+ if (absPath !== targetPath && targetPath !== void 0) {
2540
+ this.fsw._symlinkPaths.set(absPath, targetPath);
2541
+ }
2542
+ } else if (stats.isSymbolicLink()) {
2543
+ const targetPath = follow ? await (0, import_promises2.realpath)(path) : path;
2544
+ if (this.fsw.closed)
2545
+ return;
2546
+ const parent = sysPath.dirname(wh.watchPath);
2547
+ this.fsw._getWatchedDir(parent).add(wh.watchPath);
2548
+ this.fsw._emit(EV.ADD, wh.watchPath, stats);
2549
+ closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath);
2550
+ if (this.fsw.closed)
2551
+ return;
2552
+ if (targetPath !== void 0) {
2553
+ this.fsw._symlinkPaths.set(sysPath.resolve(path), targetPath);
2554
+ }
2555
+ } else {
2556
+ closer = this._handleFile(wh.watchPath, stats, initialAdd);
2557
+ }
2558
+ ready();
2559
+ if (closer)
2560
+ this.fsw._addPathCloser(path, closer);
2561
+ return false;
2562
+ } catch (error) {
2563
+ if (this.fsw._handleError(error)) {
2564
+ ready();
2565
+ return path;
2566
+ }
2567
+ }
2568
+ }
2569
+ };
2570
+ }
2571
+ });
2572
+
2573
+ // node_modules/chokidar/esm/index.js
2574
+ var esm_exports = {};
2575
+ __export(esm_exports, {
2576
+ FSWatcher: () => FSWatcher,
2577
+ WatchHelper: () => WatchHelper,
2578
+ default: () => esm_default,
2579
+ watch: () => watch
2580
+ });
2581
+ function arrify(item) {
2582
+ return Array.isArray(item) ? item : [item];
2583
+ }
2584
+ function createPattern(matcher) {
2585
+ if (typeof matcher === "function")
2586
+ return matcher;
2587
+ if (typeof matcher === "string")
2588
+ return (string) => matcher === string;
2589
+ if (matcher instanceof RegExp)
2590
+ return (string) => matcher.test(string);
2591
+ if (typeof matcher === "object" && matcher !== null) {
2592
+ return (string) => {
2593
+ if (matcher.path === string)
2594
+ return true;
2595
+ if (matcher.recursive) {
2596
+ const relative4 = sysPath2.relative(matcher.path, string);
2597
+ if (!relative4) {
2598
+ return false;
2599
+ }
2600
+ return !relative4.startsWith("..") && !sysPath2.isAbsolute(relative4);
2601
+ }
2602
+ return false;
2603
+ };
2604
+ }
2605
+ return () => false;
2606
+ }
2607
+ function normalizePath2(path) {
2608
+ if (typeof path !== "string")
2609
+ throw new Error("string expected");
2610
+ path = sysPath2.normalize(path);
2611
+ path = path.replace(/\\/g, "/");
2612
+ let prepend = false;
2613
+ if (path.startsWith("//"))
2614
+ prepend = true;
2615
+ const DOUBLE_SLASH_RE2 = /\/\//;
2616
+ while (path.match(DOUBLE_SLASH_RE2))
2617
+ path = path.replace(DOUBLE_SLASH_RE2, "/");
2618
+ if (prepend)
2619
+ path = "/" + path;
2620
+ return path;
2621
+ }
2622
+ function matchPatterns(patterns, testString, stats) {
2623
+ const path = normalizePath2(testString);
2624
+ for (let index = 0; index < patterns.length; index++) {
2625
+ const pattern = patterns[index];
2626
+ if (pattern(path, stats)) {
2627
+ return true;
2628
+ }
2629
+ }
2630
+ return false;
2631
+ }
2632
+ function anymatch(matchers, testString) {
2633
+ if (matchers == null) {
2634
+ throw new TypeError("anymatch: specify first argument");
2635
+ }
2636
+ const matchersArray = arrify(matchers);
2637
+ const patterns = matchersArray.map((matcher) => createPattern(matcher));
2638
+ if (testString == null) {
2639
+ return (testString2, stats) => {
2640
+ return matchPatterns(patterns, testString2, stats);
2641
+ };
2642
+ }
2643
+ return matchPatterns(patterns, testString);
2644
+ }
2645
+ function watch(paths, options = {}) {
2646
+ const watcher = new FSWatcher(options);
2647
+ watcher.add(paths);
2648
+ return watcher;
2649
+ }
2650
+ var import_fs4, import_promises3, import_events, sysPath2, SLASH, SLASH_SLASH, ONE_DOT, TWO_DOTS, STRING_TYPE, BACK_SLASH_RE, DOUBLE_SLASH_RE, DOT_RE, REPLACER_RE, isMatcherObject, unifyPaths, toUnix, normalizePathToUnix, normalizeIgnored, getAbsolutePath, EMPTY_SET, DirEntry, STAT_METHOD_F, STAT_METHOD_L, WatchHelper, FSWatcher, esm_default;
2651
+ var init_esm2 = __esm({
2652
+ "node_modules/chokidar/esm/index.js"() {
2653
+ "use strict";
2654
+ import_fs4 = require("fs");
2655
+ import_promises3 = require("fs/promises");
2656
+ import_events = require("events");
2657
+ sysPath2 = __toESM(require("path"), 1);
2658
+ init_esm();
2659
+ init_handler();
2660
+ SLASH = "/";
2661
+ SLASH_SLASH = "//";
2662
+ ONE_DOT = ".";
2663
+ TWO_DOTS = "..";
2664
+ STRING_TYPE = "string";
2665
+ BACK_SLASH_RE = /\\/g;
2666
+ DOUBLE_SLASH_RE = /\/\//;
2667
+ DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
2668
+ REPLACER_RE = /^\.[/\\]/;
2669
+ isMatcherObject = (matcher) => typeof matcher === "object" && matcher !== null && !(matcher instanceof RegExp);
2670
+ unifyPaths = (paths_) => {
2671
+ const paths = arrify(paths_).flat();
2672
+ if (!paths.every((p) => typeof p === STRING_TYPE)) {
2673
+ throw new TypeError(`Non-string provided as watch path: ${paths}`);
2674
+ }
2675
+ return paths.map(normalizePathToUnix);
2676
+ };
2677
+ toUnix = (string) => {
2678
+ let str = string.replace(BACK_SLASH_RE, SLASH);
2679
+ let prepend = false;
2680
+ if (str.startsWith(SLASH_SLASH)) {
2681
+ prepend = true;
2682
+ }
2683
+ while (str.match(DOUBLE_SLASH_RE)) {
2684
+ str = str.replace(DOUBLE_SLASH_RE, SLASH);
2685
+ }
2686
+ if (prepend) {
2687
+ str = SLASH + str;
2688
+ }
2689
+ return str;
2690
+ };
2691
+ normalizePathToUnix = (path) => toUnix(sysPath2.normalize(toUnix(path)));
2692
+ normalizeIgnored = (cwd = "") => (path) => {
2693
+ if (typeof path === "string") {
2694
+ return normalizePathToUnix(sysPath2.isAbsolute(path) ? path : sysPath2.join(cwd, path));
2695
+ } else {
2696
+ return path;
2697
+ }
2698
+ };
2699
+ getAbsolutePath = (path, cwd) => {
2700
+ if (sysPath2.isAbsolute(path)) {
2701
+ return path;
2702
+ }
2703
+ return sysPath2.join(cwd, path);
2704
+ };
2705
+ EMPTY_SET = Object.freeze(/* @__PURE__ */ new Set());
2706
+ DirEntry = class {
2707
+ constructor(dir, removeWatcher) {
2708
+ this.path = dir;
2709
+ this._removeWatcher = removeWatcher;
2710
+ this.items = /* @__PURE__ */ new Set();
2711
+ }
2712
+ add(item) {
2713
+ const { items } = this;
2714
+ if (!items)
2715
+ return;
2716
+ if (item !== ONE_DOT && item !== TWO_DOTS)
2717
+ items.add(item);
2718
+ }
2719
+ async remove(item) {
2720
+ const { items } = this;
2721
+ if (!items)
2722
+ return;
2723
+ items.delete(item);
2724
+ if (items.size > 0)
2725
+ return;
2726
+ const dir = this.path;
2727
+ try {
2728
+ await (0, import_promises3.readdir)(dir);
2729
+ } catch (err) {
2730
+ if (this._removeWatcher) {
2731
+ this._removeWatcher(sysPath2.dirname(dir), sysPath2.basename(dir));
2732
+ }
2733
+ }
2734
+ }
2735
+ has(item) {
2736
+ const { items } = this;
2737
+ if (!items)
2738
+ return;
2739
+ return items.has(item);
2740
+ }
2741
+ getChildren() {
2742
+ const { items } = this;
2743
+ if (!items)
2744
+ return [];
2745
+ return [...items.values()];
2746
+ }
2747
+ dispose() {
2748
+ this.items.clear();
2749
+ this.path = "";
2750
+ this._removeWatcher = EMPTY_FN;
2751
+ this.items = EMPTY_SET;
2752
+ Object.freeze(this);
2753
+ }
2754
+ };
2755
+ STAT_METHOD_F = "stat";
2756
+ STAT_METHOD_L = "lstat";
2757
+ WatchHelper = class {
2758
+ constructor(path, follow, fsw) {
2759
+ this.fsw = fsw;
2760
+ const watchPath = path;
2761
+ this.path = path = path.replace(REPLACER_RE, "");
2762
+ this.watchPath = watchPath;
2763
+ this.fullWatchPath = sysPath2.resolve(watchPath);
2764
+ this.dirParts = [];
2765
+ this.dirParts.forEach((parts) => {
2766
+ if (parts.length > 1)
2767
+ parts.pop();
2768
+ });
2769
+ this.followSymlinks = follow;
2770
+ this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
2771
+ }
2772
+ entryPath(entry) {
2773
+ return sysPath2.join(this.watchPath, sysPath2.relative(this.watchPath, entry.fullPath));
2774
+ }
2775
+ filterPath(entry) {
2776
+ const { stats } = entry;
2777
+ if (stats && stats.isSymbolicLink())
2778
+ return this.filterDir(entry);
2779
+ const resolvedPath = this.entryPath(entry);
2780
+ return this.fsw._isntIgnored(resolvedPath, stats) && this.fsw._hasReadPermissions(stats);
2781
+ }
2782
+ filterDir(entry) {
2783
+ return this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
2784
+ }
2785
+ };
2786
+ FSWatcher = class extends import_events.EventEmitter {
2787
+ // Not indenting methods for history sake; for now.
2788
+ constructor(_opts = {}) {
2789
+ super();
2790
+ this.closed = false;
2791
+ this._closers = /* @__PURE__ */ new Map();
2792
+ this._ignoredPaths = /* @__PURE__ */ new Set();
2793
+ this._throttled = /* @__PURE__ */ new Map();
2794
+ this._streams = /* @__PURE__ */ new Set();
2795
+ this._symlinkPaths = /* @__PURE__ */ new Map();
2796
+ this._watched = /* @__PURE__ */ new Map();
2797
+ this._pendingWrites = /* @__PURE__ */ new Map();
2798
+ this._pendingUnlinks = /* @__PURE__ */ new Map();
2799
+ this._readyCount = 0;
2800
+ this._readyEmitted = false;
2801
+ const awf = _opts.awaitWriteFinish;
2802
+ const DEF_AWF = { stabilityThreshold: 2e3, pollInterval: 100 };
2803
+ const opts = {
2804
+ // Defaults
2805
+ persistent: true,
2806
+ ignoreInitial: false,
2807
+ ignorePermissionErrors: false,
2808
+ interval: 100,
2809
+ binaryInterval: 300,
2810
+ followSymlinks: true,
2811
+ usePolling: false,
2812
+ // useAsync: false,
2813
+ atomic: true,
2814
+ // NOTE: overwritten later (depends on usePolling)
2815
+ ..._opts,
2816
+ // Change format
2817
+ ignored: _opts.ignored ? arrify(_opts.ignored) : arrify([]),
2818
+ awaitWriteFinish: awf === true ? DEF_AWF : typeof awf === "object" ? { ...DEF_AWF, ...awf } : false
2819
+ };
2820
+ if (isIBMi)
2821
+ opts.usePolling = true;
2822
+ if (opts.atomic === void 0)
2823
+ opts.atomic = !opts.usePolling;
2824
+ const envPoll = process.env.CHOKIDAR_USEPOLLING;
2825
+ if (envPoll !== void 0) {
2826
+ const envLower = envPoll.toLowerCase();
2827
+ if (envLower === "false" || envLower === "0")
2828
+ opts.usePolling = false;
2829
+ else if (envLower === "true" || envLower === "1")
2830
+ opts.usePolling = true;
2831
+ else
2832
+ opts.usePolling = !!envLower;
2833
+ }
2834
+ const envInterval = process.env.CHOKIDAR_INTERVAL;
2835
+ if (envInterval)
2836
+ opts.interval = Number.parseInt(envInterval, 10);
2837
+ let readyCalls = 0;
2838
+ this._emitReady = () => {
2839
+ readyCalls++;
2840
+ if (readyCalls >= this._readyCount) {
2841
+ this._emitReady = EMPTY_FN;
2842
+ this._readyEmitted = true;
2843
+ process.nextTick(() => this.emit(EVENTS.READY));
2844
+ }
2845
+ };
2846
+ this._emitRaw = (...args) => this.emit(EVENTS.RAW, ...args);
2847
+ this._boundRemove = this._remove.bind(this);
2848
+ this.options = opts;
2849
+ this._nodeFsHandler = new NodeFsHandler(this);
2850
+ Object.freeze(opts);
2851
+ }
2852
+ _addIgnoredPath(matcher) {
2853
+ if (isMatcherObject(matcher)) {
2854
+ for (const ignored of this._ignoredPaths) {
2855
+ if (isMatcherObject(ignored) && ignored.path === matcher.path && ignored.recursive === matcher.recursive) {
2856
+ return;
2857
+ }
2858
+ }
2859
+ }
2860
+ this._ignoredPaths.add(matcher);
2861
+ }
2862
+ _removeIgnoredPath(matcher) {
2863
+ this._ignoredPaths.delete(matcher);
2864
+ if (typeof matcher === "string") {
2865
+ for (const ignored of this._ignoredPaths) {
2866
+ if (isMatcherObject(ignored) && ignored.path === matcher) {
2867
+ this._ignoredPaths.delete(ignored);
2868
+ }
2869
+ }
2870
+ }
2871
+ }
2872
+ // Public methods
2873
+ /**
2874
+ * Adds paths to be watched on an existing FSWatcher instance.
2875
+ * @param paths_ file or file list. Other arguments are unused
2876
+ */
2877
+ add(paths_, _origAdd, _internal) {
2878
+ const { cwd } = this.options;
2879
+ this.closed = false;
2880
+ this._closePromise = void 0;
2881
+ let paths = unifyPaths(paths_);
2882
+ if (cwd) {
2883
+ paths = paths.map((path) => {
2884
+ const absPath = getAbsolutePath(path, cwd);
2885
+ return absPath;
2886
+ });
2887
+ }
2888
+ paths.forEach((path) => {
2889
+ this._removeIgnoredPath(path);
2890
+ });
2891
+ this._userIgnored = void 0;
2892
+ if (!this._readyCount)
2893
+ this._readyCount = 0;
2894
+ this._readyCount += paths.length;
2895
+ Promise.all(paths.map(async (path) => {
2896
+ const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, void 0, 0, _origAdd);
2897
+ if (res)
2898
+ this._emitReady();
2899
+ return res;
2900
+ })).then((results) => {
2901
+ if (this.closed)
2902
+ return;
2903
+ results.forEach((item) => {
2904
+ if (item)
2905
+ this.add(sysPath2.dirname(item), sysPath2.basename(_origAdd || item));
2906
+ });
2907
+ });
2908
+ return this;
2909
+ }
2910
+ /**
2911
+ * Close watchers or start ignoring events from specified paths.
2912
+ */
2913
+ unwatch(paths_) {
2914
+ if (this.closed)
2915
+ return this;
2916
+ const paths = unifyPaths(paths_);
2917
+ const { cwd } = this.options;
2918
+ paths.forEach((path) => {
2919
+ if (!sysPath2.isAbsolute(path) && !this._closers.has(path)) {
2920
+ if (cwd)
2921
+ path = sysPath2.join(cwd, path);
2922
+ path = sysPath2.resolve(path);
2923
+ }
2924
+ this._closePath(path);
2925
+ this._addIgnoredPath(path);
2926
+ if (this._watched.has(path)) {
2927
+ this._addIgnoredPath({
2928
+ path,
2929
+ recursive: true
2930
+ });
2931
+ }
2932
+ this._userIgnored = void 0;
2933
+ });
2934
+ return this;
2935
+ }
2936
+ /**
2937
+ * Close watchers and remove all listeners from watched paths.
2938
+ */
2939
+ close() {
2940
+ if (this._closePromise) {
2941
+ return this._closePromise;
2942
+ }
2943
+ this.closed = true;
2944
+ this.removeAllListeners();
2945
+ const closers = [];
2946
+ this._closers.forEach((closerList) => closerList.forEach((closer) => {
2947
+ const promise = closer();
2948
+ if (promise instanceof Promise)
2949
+ closers.push(promise);
2950
+ }));
2951
+ this._streams.forEach((stream) => stream.destroy());
2952
+ this._userIgnored = void 0;
2953
+ this._readyCount = 0;
2954
+ this._readyEmitted = false;
2955
+ this._watched.forEach((dirent) => dirent.dispose());
2956
+ this._closers.clear();
2957
+ this._watched.clear();
2958
+ this._streams.clear();
2959
+ this._symlinkPaths.clear();
2960
+ this._throttled.clear();
2961
+ this._closePromise = closers.length ? Promise.all(closers).then(() => void 0) : Promise.resolve();
2962
+ return this._closePromise;
2963
+ }
2964
+ /**
2965
+ * Expose list of watched paths
2966
+ * @returns for chaining
2967
+ */
2968
+ getWatched() {
2969
+ const watchList = {};
2970
+ this._watched.forEach((entry, dir) => {
2971
+ const key = this.options.cwd ? sysPath2.relative(this.options.cwd, dir) : dir;
2972
+ const index = key || ONE_DOT;
2973
+ watchList[index] = entry.getChildren().sort();
2974
+ });
2975
+ return watchList;
2976
+ }
2977
+ emitWithAll(event, args) {
2978
+ this.emit(event, ...args);
2979
+ if (event !== EVENTS.ERROR)
2980
+ this.emit(EVENTS.ALL, event, ...args);
2981
+ }
2982
+ // Common helpers
2983
+ // --------------
2984
+ /**
2985
+ * Normalize and emit events.
2986
+ * Calling _emit DOES NOT MEAN emit() would be called!
2987
+ * @param event Type of event
2988
+ * @param path File or directory path
2989
+ * @param stats arguments to be passed with event
2990
+ * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
2991
+ */
2992
+ async _emit(event, path, stats) {
2993
+ if (this.closed)
2994
+ return;
2995
+ const opts = this.options;
2996
+ if (isWindows2)
2997
+ path = sysPath2.normalize(path);
2998
+ if (opts.cwd)
2999
+ path = sysPath2.relative(opts.cwd, path);
3000
+ const args = [path];
3001
+ if (stats != null)
3002
+ args.push(stats);
3003
+ const awf = opts.awaitWriteFinish;
3004
+ let pw;
3005
+ if (awf && (pw = this._pendingWrites.get(path))) {
3006
+ pw.lastChange = /* @__PURE__ */ new Date();
3007
+ return this;
3008
+ }
3009
+ if (opts.atomic) {
3010
+ if (event === EVENTS.UNLINK) {
3011
+ this._pendingUnlinks.set(path, [event, ...args]);
3012
+ setTimeout(() => {
3013
+ this._pendingUnlinks.forEach((entry, path2) => {
3014
+ this.emit(...entry);
3015
+ this.emit(EVENTS.ALL, ...entry);
3016
+ this._pendingUnlinks.delete(path2);
3017
+ });
3018
+ }, typeof opts.atomic === "number" ? opts.atomic : 100);
3019
+ return this;
3020
+ }
3021
+ if (event === EVENTS.ADD && this._pendingUnlinks.has(path)) {
3022
+ event = EVENTS.CHANGE;
3023
+ this._pendingUnlinks.delete(path);
3024
+ }
3025
+ }
3026
+ if (awf && (event === EVENTS.ADD || event === EVENTS.CHANGE) && this._readyEmitted) {
3027
+ const awfEmit = (err, stats2) => {
3028
+ if (err) {
3029
+ event = EVENTS.ERROR;
3030
+ args[0] = err;
3031
+ this.emitWithAll(event, args);
3032
+ } else if (stats2) {
3033
+ if (args.length > 1) {
3034
+ args[1] = stats2;
3035
+ } else {
3036
+ args.push(stats2);
3037
+ }
3038
+ this.emitWithAll(event, args);
3039
+ }
3040
+ };
3041
+ this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);
3042
+ return this;
3043
+ }
3044
+ if (event === EVENTS.CHANGE) {
3045
+ const isThrottled = !this._throttle(EVENTS.CHANGE, path, 50);
3046
+ if (isThrottled)
3047
+ return this;
3048
+ }
3049
+ if (opts.alwaysStat && stats === void 0 && (event === EVENTS.ADD || event === EVENTS.ADD_DIR || event === EVENTS.CHANGE)) {
3050
+ const fullPath = opts.cwd ? sysPath2.join(opts.cwd, path) : path;
3051
+ let stats2;
3052
+ try {
3053
+ stats2 = await (0, import_promises3.stat)(fullPath);
3054
+ } catch (err) {
3055
+ }
3056
+ if (!stats2 || this.closed)
3057
+ return;
3058
+ args.push(stats2);
3059
+ }
3060
+ this.emitWithAll(event, args);
3061
+ return this;
3062
+ }
3063
+ /**
3064
+ * Common handler for errors
3065
+ * @returns The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
3066
+ */
3067
+ _handleError(error) {
3068
+ const code = error && error.code;
3069
+ if (error && code !== "ENOENT" && code !== "ENOTDIR" && (!this.options.ignorePermissionErrors || code !== "EPERM" && code !== "EACCES")) {
3070
+ this.emit(EVENTS.ERROR, error);
3071
+ }
3072
+ return error || this.closed;
3073
+ }
3074
+ /**
3075
+ * Helper utility for throttling
3076
+ * @param actionType type being throttled
3077
+ * @param path being acted upon
3078
+ * @param timeout duration of time to suppress duplicate actions
3079
+ * @returns tracking object or false if action should be suppressed
3080
+ */
3081
+ _throttle(actionType, path, timeout) {
3082
+ if (!this._throttled.has(actionType)) {
3083
+ this._throttled.set(actionType, /* @__PURE__ */ new Map());
3084
+ }
3085
+ const action = this._throttled.get(actionType);
3086
+ if (!action)
3087
+ throw new Error("invalid throttle");
3088
+ const actionPath = action.get(path);
3089
+ if (actionPath) {
3090
+ actionPath.count++;
3091
+ return false;
3092
+ }
3093
+ let timeoutObject;
3094
+ const clear = () => {
3095
+ const item = action.get(path);
3096
+ const count = item ? item.count : 0;
3097
+ action.delete(path);
3098
+ clearTimeout(timeoutObject);
3099
+ if (item)
3100
+ clearTimeout(item.timeoutObject);
3101
+ return count;
3102
+ };
3103
+ timeoutObject = setTimeout(clear, timeout);
3104
+ const thr = { timeoutObject, clear, count: 0 };
3105
+ action.set(path, thr);
3106
+ return thr;
3107
+ }
3108
+ _incrReadyCount() {
3109
+ return this._readyCount++;
3110
+ }
3111
+ /**
3112
+ * Awaits write operation to finish.
3113
+ * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
3114
+ * @param path being acted upon
3115
+ * @param threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
3116
+ * @param event
3117
+ * @param awfEmit Callback to be called when ready for event to be emitted.
3118
+ */
3119
+ _awaitWriteFinish(path, threshold, event, awfEmit) {
3120
+ const awf = this.options.awaitWriteFinish;
3121
+ if (typeof awf !== "object")
3122
+ return;
3123
+ const pollInterval = awf.pollInterval;
3124
+ let timeoutHandler;
3125
+ let fullPath = path;
3126
+ if (this.options.cwd && !sysPath2.isAbsolute(path)) {
3127
+ fullPath = sysPath2.join(this.options.cwd, path);
3128
+ }
3129
+ const now = /* @__PURE__ */ new Date();
3130
+ const writes = this._pendingWrites;
3131
+ function awaitWriteFinishFn(prevStat) {
3132
+ (0, import_fs4.stat)(fullPath, (err, curStat) => {
3133
+ if (err || !writes.has(path)) {
3134
+ if (err && err.code !== "ENOENT")
3135
+ awfEmit(err);
3136
+ return;
3137
+ }
3138
+ const now2 = Number(/* @__PURE__ */ new Date());
3139
+ if (prevStat && curStat.size !== prevStat.size) {
3140
+ writes.get(path).lastChange = now2;
3141
+ }
3142
+ const pw = writes.get(path);
3143
+ const df = now2 - pw.lastChange;
3144
+ if (df >= threshold) {
3145
+ writes.delete(path);
3146
+ awfEmit(void 0, curStat);
3147
+ } else {
3148
+ timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval, curStat);
3149
+ }
3150
+ });
3151
+ }
3152
+ if (!writes.has(path)) {
3153
+ writes.set(path, {
3154
+ lastChange: now,
3155
+ cancelWait: () => {
3156
+ writes.delete(path);
3157
+ clearTimeout(timeoutHandler);
3158
+ return event;
3159
+ }
3160
+ });
3161
+ timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval);
3162
+ }
3163
+ }
3164
+ /**
3165
+ * Determines whether user has asked to ignore this path.
3166
+ */
3167
+ _isIgnored(path, stats) {
3168
+ if (this.options.atomic && DOT_RE.test(path))
3169
+ return true;
3170
+ if (!this._userIgnored) {
3171
+ const { cwd } = this.options;
3172
+ const ign = this.options.ignored;
3173
+ const ignored = (ign || []).map(normalizeIgnored(cwd));
3174
+ const ignoredPaths = [...this._ignoredPaths];
3175
+ const list = [...ignoredPaths.map(normalizeIgnored(cwd)), ...ignored];
3176
+ this._userIgnored = anymatch(list, void 0);
3177
+ }
3178
+ return this._userIgnored(path, stats);
3179
+ }
3180
+ _isntIgnored(path, stat4) {
3181
+ return !this._isIgnored(path, stat4);
3182
+ }
3183
+ /**
3184
+ * Provides a set of common helpers and properties relating to symlink handling.
3185
+ * @param path file or directory pattern being watched
3186
+ */
3187
+ _getWatchHelpers(path) {
3188
+ return new WatchHelper(path, this.options.followSymlinks, this);
3189
+ }
3190
+ // Directory helpers
3191
+ // -----------------
3192
+ /**
3193
+ * Provides directory tracking objects
3194
+ * @param directory path of the directory
3195
+ */
3196
+ _getWatchedDir(directory) {
3197
+ const dir = sysPath2.resolve(directory);
3198
+ if (!this._watched.has(dir))
3199
+ this._watched.set(dir, new DirEntry(dir, this._boundRemove));
3200
+ return this._watched.get(dir);
3201
+ }
3202
+ // File helpers
3203
+ // ------------
3204
+ /**
3205
+ * Check for read permissions: https://stackoverflow.com/a/11781404/1358405
3206
+ */
3207
+ _hasReadPermissions(stats) {
3208
+ if (this.options.ignorePermissionErrors)
3209
+ return true;
3210
+ return Boolean(Number(stats.mode) & 256);
3211
+ }
3212
+ /**
3213
+ * Handles emitting unlink events for
3214
+ * files and directories, and via recursion, for
3215
+ * files and directories within directories that are unlinked
3216
+ * @param directory within which the following item is located
3217
+ * @param item base path of item/directory
3218
+ */
3219
+ _remove(directory, item, isDirectory) {
3220
+ const path = sysPath2.join(directory, item);
3221
+ const fullPath = sysPath2.resolve(path);
3222
+ isDirectory = isDirectory != null ? isDirectory : this._watched.has(path) || this._watched.has(fullPath);
3223
+ if (!this._throttle("remove", path, 100))
3224
+ return;
3225
+ if (!isDirectory && this._watched.size === 1) {
3226
+ this.add(directory, item, true);
3227
+ }
3228
+ const wp = this._getWatchedDir(path);
3229
+ const nestedDirectoryChildren = wp.getChildren();
3230
+ nestedDirectoryChildren.forEach((nested) => this._remove(path, nested));
3231
+ const parent = this._getWatchedDir(directory);
3232
+ const wasTracked = parent.has(item);
3233
+ parent.remove(item);
3234
+ if (this._symlinkPaths.has(fullPath)) {
3235
+ this._symlinkPaths.delete(fullPath);
3236
+ }
3237
+ let relPath = path;
3238
+ if (this.options.cwd)
3239
+ relPath = sysPath2.relative(this.options.cwd, path);
3240
+ if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
3241
+ const event = this._pendingWrites.get(relPath).cancelWait();
3242
+ if (event === EVENTS.ADD)
3243
+ return;
3244
+ }
3245
+ this._watched.delete(path);
3246
+ this._watched.delete(fullPath);
3247
+ const eventName = isDirectory ? EVENTS.UNLINK_DIR : EVENTS.UNLINK;
3248
+ if (wasTracked && !this._isIgnored(path))
3249
+ this._emit(eventName, path);
3250
+ this._closePath(path);
3251
+ }
3252
+ /**
3253
+ * Closes all watchers for a path
3254
+ */
3255
+ _closePath(path) {
3256
+ this._closeFile(path);
3257
+ const dir = sysPath2.dirname(path);
3258
+ this._getWatchedDir(dir).remove(sysPath2.basename(path));
3259
+ }
3260
+ /**
3261
+ * Closes only file-specific watchers
3262
+ */
3263
+ _closeFile(path) {
3264
+ const closers = this._closers.get(path);
3265
+ if (!closers)
3266
+ return;
3267
+ closers.forEach((closer) => closer());
3268
+ this._closers.delete(path);
3269
+ }
3270
+ _addPathCloser(path, closer) {
3271
+ if (!closer)
3272
+ return;
3273
+ let list = this._closers.get(path);
3274
+ if (!list) {
3275
+ list = [];
3276
+ this._closers.set(path, list);
3277
+ }
3278
+ list.push(closer);
3279
+ }
3280
+ _readdirp(root, opts) {
3281
+ if (this.closed)
3282
+ return;
3283
+ const options = { type: EVENTS.ALL, alwaysStat: true, lstat: true, ...opts, depth: 0 };
3284
+ let stream = readdirp(root, options);
3285
+ this._streams.add(stream);
3286
+ stream.once(STR_CLOSE, () => {
3287
+ stream = void 0;
3288
+ });
3289
+ stream.once(STR_END, () => {
3290
+ if (stream) {
3291
+ this._streams.delete(stream);
3292
+ stream = void 0;
3293
+ }
3294
+ });
3295
+ return stream;
3296
+ }
3297
+ };
3298
+ esm_default = { watch, FSWatcher };
3299
+ }
3300
+ });
3301
+
3302
+ // src/test.ts
3303
+ var test_exports = {};
3304
+ __export(test_exports, {
3305
+ runJestTests: () => runJestTests,
3306
+ runWatchMode: () => runWatchMode
3307
+ });
3308
+ module.exports = __toCommonJS(test_exports);
3309
+ init_fs();
3310
+ init_path();
3311
+
3312
+ // src/test-runtime.ts
3313
+ var import_esbuild = require("esbuild");
3314
+ init_fs();
3315
+ init_path();
3316
+ var import_source_map = require("source-map");
3317
+ function escapeRegex(str) {
3318
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3319
+ }
3320
+ var AssertionError = class extends Error {
3321
+ constructor(message, filePath, lineNumber, columnNumber, codeSnippet) {
3322
+ super(message);
3323
+ this.filePath = filePath;
3324
+ this.lineNumber = lineNumber;
3325
+ this.columnNumber = columnNumber;
3326
+ this.codeSnippet = codeSnippet;
3327
+ this.name = "AssertionError";
3328
+ }
3329
+ };
3330
+ var currentSuite = {
3331
+ name: "root",
3332
+ tests: [],
3333
+ suites: [],
3334
+ skip: false,
3335
+ only: false
3336
+ };
3337
+ var testResults = [];
3338
+ var hasOnly = false;
3339
+ var coveredFiles = /* @__PURE__ */ new Set();
3340
+ var describePattern = void 0;
3341
+ var testPattern = void 0;
3342
+ var currentTestFile = void 0;
3343
+ var currentSourceMapConsumer = void 0;
3344
+ var wrapperLineOffset = 0;
3345
+ function createTestFunction(defaultTimeout = 5e3) {
3346
+ const testFn = function(name, fn, timeout) {
3347
+ const test2 = {
3348
+ name,
3349
+ fn,
3350
+ skip: currentSuite.skip,
3351
+ only: false,
3352
+ todo: false,
3353
+ timeout: timeout ?? defaultTimeout,
3354
+ suite: currentSuite
3355
+ };
3356
+ currentSuite.tests.push(test2);
3357
+ };
3358
+ testFn.skip = (name, fn, timeout) => {
3359
+ const test2 = {
3360
+ name,
3361
+ fn,
3362
+ skip: true,
3363
+ only: false,
3364
+ todo: false,
3365
+ timeout: timeout ?? defaultTimeout,
3366
+ suite: currentSuite
3367
+ };
3368
+ currentSuite.tests.push(test2);
3369
+ };
3370
+ testFn.only = (name, fn, timeout) => {
3371
+ hasOnly = true;
3372
+ const test2 = {
3373
+ name,
3374
+ fn,
3375
+ skip: false,
3376
+ only: true,
3377
+ todo: false,
3378
+ timeout: timeout ?? defaultTimeout,
3379
+ suite: currentSuite
3380
+ };
3381
+ currentSuite.tests.push(test2);
3382
+ };
3383
+ testFn.todo = (name, fn, timeout) => {
3384
+ const test2 = {
3385
+ name,
3386
+ fn,
3387
+ skip: false,
3388
+ only: false,
3389
+ todo: true,
3390
+ timeout: timeout ?? defaultTimeout,
3391
+ suite: currentSuite
3392
+ };
3393
+ currentSuite.tests.push(test2);
3394
+ };
3395
+ return testFn;
3396
+ }
3397
+ function createDescribeFunction() {
3398
+ const describeFn = function(name, fn) {
3399
+ const parent = currentSuite;
3400
+ const suite = {
3401
+ name,
3402
+ tests: [],
3403
+ suites: [],
3404
+ parent,
3405
+ skip: parent.skip,
3406
+ only: parent.only
3407
+ };
3408
+ parent.suites.push(suite);
3409
+ currentSuite = suite;
3410
+ fn();
3411
+ currentSuite = parent;
3412
+ };
3413
+ describeFn.skip = (name, fn) => {
3414
+ const parent = currentSuite;
3415
+ const suite = {
3416
+ name,
3417
+ tests: [],
3418
+ suites: [],
3419
+ parent,
3420
+ skip: true,
3421
+ only: false
3422
+ };
3423
+ parent.suites.push(suite);
3424
+ currentSuite = suite;
3425
+ fn();
3426
+ currentSuite = parent;
3427
+ };
3428
+ describeFn.only = (name, fn) => {
3429
+ hasOnly = true;
3430
+ const parent = currentSuite;
3431
+ const suite = {
3432
+ name,
3433
+ tests: [],
3434
+ suites: [],
3435
+ parent,
3436
+ skip: false,
3437
+ only: true
3438
+ };
3439
+ parent.suites.push(suite);
3440
+ currentSuite = suite;
3441
+ fn();
3442
+ currentSuite = parent;
3443
+ };
3444
+ return describeFn;
3445
+ }
3446
+ var Expect = class _Expect {
3447
+ constructor(actual, isNot = false, isAsync = false) {
3448
+ this.actual = actual;
3449
+ this.isNot = isNot;
3450
+ this.isAsync = isAsync;
3451
+ this._not = null;
3452
+ this._resolves = null;
3453
+ this._rejects = null;
3454
+ }
3455
+ get not() {
3456
+ if (!this._not) {
3457
+ this._not = new _Expect(this.actual, !this.isNot, false);
3458
+ }
3459
+ return this._not;
3460
+ }
3461
+ get resolves() {
3462
+ if (!this._resolves) {
3463
+ this._resolves = new _Expect(this.actual, this.isNot, true);
3464
+ }
3465
+ return this._resolves;
3466
+ }
3467
+ get rejects() {
3468
+ if (!this._rejects) {
3469
+ this._rejects = new _Expect(this.actual, this.isNot, true);
3470
+ }
3471
+ return this._rejects;
3472
+ }
3473
+ assertCondition(condition, message, showExpectedReceived = true, expectedDisplay, callerStack) {
3474
+ if (this.isNot) {
3475
+ condition = !condition;
3476
+ }
3477
+ if (!condition) {
3478
+ let errorMsg = message;
3479
+ if (showExpectedReceived) {
3480
+ const expectedValue = expectedDisplay ?? this.stringify(this.expected ?? "truthy");
3481
+ errorMsg += `
3482
+ Expected: ${expectedValue}
3483
+ Received: ${this.stringify(this.actual)}`;
3484
+ }
3485
+ const stack = callerStack || new Error().stack;
3486
+ let lineNumber = void 0;
3487
+ let codeSnippet = void 0;
3488
+ let assertionMethod = void 0;
3489
+ if (stack) {
3490
+ const assertionMatch = stack.match(/at _Expect\.(\w+)/);
3491
+ if (assertionMatch) {
3492
+ assertionMethod = assertionMatch[1];
3493
+ }
3494
+ }
3495
+ if (stack) {
3496
+ const lines = stack.split("\n");
3497
+ const stackFrames = [];
3498
+ for (const line of lines) {
3499
+ const match = line.match(/<anonymous>:([0-9]+):([0-9]+)/);
3500
+ if (match) {
3501
+ stackFrames.push({
3502
+ line: parseInt(match[1], 10),
3503
+ column: parseInt(match[2], 10)
3504
+ });
3505
+ }
3506
+ }
3507
+ const targetFrame = stackFrames.length > 1 ? stackFrames[1] : stackFrames[0];
3508
+ if (targetFrame && currentSourceMapConsumer) {
3509
+ try {
3510
+ const transpiledLine = targetFrame.line - wrapperLineOffset;
3511
+ const originalPosition = currentSourceMapConsumer.originalPositionFor({
3512
+ line: transpiledLine,
3513
+ column: targetFrame.column
3514
+ });
3515
+ if (originalPosition.line !== null) {
3516
+ lineNumber = originalPosition.line;
3517
+ if (currentTestFile) {
3518
+ try {
3519
+ let sourceCode = readFileSync(currentTestFile, "utf-8");
3520
+ if (Buffer.isBuffer(sourceCode)) {
3521
+ sourceCode = sourceCode.toString("utf-8");
3522
+ }
3523
+ const sourceLines = sourceCode.split("\n");
3524
+ let targetPattern = ".toBe(";
3525
+ if (assertionMethod === "toEqual") targetPattern = ".toEqual(";
3526
+ else if (assertionMethod === "toStrictEqual") targetPattern = ".toStrictEqual(";
3527
+ else if (assertionMethod === "toMatch") targetPattern = ".toMatch(";
3528
+ else if (assertionMethod === "toContain") targetPattern = ".toContain(";
3529
+ else if (assertionMethod === "toHaveLength") targetPattern = ".toHaveLength(";
3530
+ else if (assertionMethod === "toBeDefined") targetPattern = ".toBeDefined(";
3531
+ else if (assertionMethod === "toBeNull") targetPattern = ".toBeNull(";
3532
+ else if (assertionMethod === "toBeUndefined") targetPattern = ".toBeUndefined(";
3533
+ else if (assertionMethod === "toBeTruthy") targetPattern = ".toBeTruthy(";
3534
+ else if (assertionMethod === "toBeFalsy") targetPattern = ".toBeFalsy(";
3535
+ else if (assertionMethod === "toThrow") targetPattern = ".toThrow(";
3536
+ else if (assertionMethod === "toBeGreaterThan") targetPattern = ".toBeGreaterThan(";
3537
+ else if (assertionMethod === "toBeGreaterThanOrEqual") targetPattern = ".toBeGreaterThanOrEqual(";
3538
+ else if (assertionMethod === "toBeLessThan") targetPattern = ".toBeLessThan(";
3539
+ else if (assertionMethod === "toBeLessThanOrEqual") targetPattern = ".toBeLessThanOrEqual(";
3540
+ if (lineNumber > 0 && lineNumber <= sourceLines.length) {
3541
+ const mappedLine = sourceLines[lineNumber - 1];
3542
+ const hasMatchingAssertion = mappedLine.includes(targetPattern);
3543
+ if (!hasMatchingAssertion) {
3544
+ for (let i = 1; i <= 3; i++) {
3545
+ const searchLine = lineNumber - i;
3546
+ if (searchLine > 0 && searchLine <= sourceLines.length) {
3547
+ const testLine = sourceLines[searchLine - 1];
3548
+ if (testLine.includes(targetPattern)) {
3549
+ lineNumber = searchLine;
3550
+ break;
3551
+ }
3552
+ }
3553
+ }
3554
+ }
3555
+ }
3556
+ } catch (e) {
3557
+ }
3558
+ }
3559
+ } else {
3560
+ const posWithoutColumn = currentSourceMapConsumer.originalPositionFor({
3561
+ line: transpiledLine,
3562
+ column: 0
3563
+ });
3564
+ if (posWithoutColumn.line !== null) {
3565
+ lineNumber = posWithoutColumn.line;
3566
+ } else {
3567
+ const lineMappings = [];
3568
+ currentSourceMapConsumer.eachMapping((mapping) => {
3569
+ if (mapping.originalLine !== null) {
3570
+ const distance = Math.abs(mapping.generatedLine - transpiledLine);
3571
+ lineMappings.push({
3572
+ line: mapping.originalLine,
3573
+ distance
3574
+ });
3575
+ }
3576
+ });
3577
+ if (lineMappings.length > 0) {
3578
+ lineMappings.sort((a, b) => a.distance - b.distance);
3579
+ lineNumber = lineMappings[0].line;
3580
+ }
3581
+ }
3582
+ }
3583
+ } catch (e) {
3584
+ }
3585
+ }
3586
+ if (currentTestFile && lineNumber) {
3587
+ try {
3588
+ let sourceCode = readFileSync(currentTestFile, "utf-8");
3589
+ if (Buffer.isBuffer(sourceCode)) {
3590
+ sourceCode = sourceCode.toString("utf-8");
3591
+ }
3592
+ const sourceLines = sourceCode.split("\n");
3593
+ if (lineNumber > 0 && lineNumber <= sourceLines.length) {
3594
+ const codeLine = sourceLines[lineNumber - 1];
3595
+ if (codeLine) {
3596
+ codeSnippet = codeLine.trim();
3597
+ }
3598
+ }
3599
+ } catch (e) {
3600
+ }
3601
+ }
3602
+ }
3603
+ throw new AssertionError(errorMsg, currentTestFile, lineNumber, void 0, codeSnippet);
3604
+ }
3605
+ }
3606
+ stringify(value) {
3607
+ if (value === void 0) return "undefined";
3608
+ if (value === null) return "null";
3609
+ if (typeof value === "string") return `"${value}"`;
3610
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
3611
+ if (typeof value === "function") return "Function";
3612
+ if (Array.isArray(value)) return `[${value.map((v) => this.stringify(v)).join(", ")}]`;
3613
+ if (typeof value === "object") {
3614
+ const keys = Object.keys(value);
3615
+ if (keys.length === 0) return "{}";
3616
+ return `{ ${keys.slice(0, 3).map((k) => `${k}: ${this.stringify(value[k])}`).join(", ")}${keys.length > 3 ? "..." : ""} }`;
3617
+ }
3618
+ return String(value);
3619
+ }
3620
+ async handleAsyncAssertion(value, assertion) {
3621
+ try {
3622
+ const resolvedValue = await this.actual;
3623
+ if (this.isNot) {
3624
+ throw new Error(`Promise resolved when it should have rejected`);
3625
+ }
3626
+ assertion(resolvedValue);
3627
+ return Promise.resolve(resolvedValue);
3628
+ } catch (error) {
3629
+ if (this.isNot) {
3630
+ return Promise.resolve(void 0);
3631
+ }
3632
+ if (typeof value === "string") {
3633
+ this.assertCondition(
3634
+ error.message?.includes(value),
3635
+ `Expected error message to include "${value}"`
3636
+ );
3637
+ } else if (value instanceof RegExp) {
3638
+ this.assertCondition(
3639
+ value.test(error.message),
3640
+ `Expected error message to match ${value}`
3641
+ );
3642
+ }
3643
+ return Promise.resolve(void 0);
3644
+ }
3645
+ }
3646
+ toBe(value) {
3647
+ const stack = new Error().stack;
3648
+ if (this.isAsync) {
3649
+ return this.handleAsyncAssertion(value, (actual) => {
3650
+ this.expected = value;
3651
+ this.assertCondition(actual === value, `Expected values to be strictly equal (using ===)`, false, void 0, stack);
3652
+ if (typeof actual !== typeof value) {
3653
+ throw new Error(`Types don't match: expected ${typeof value} but got ${typeof actual}`);
3654
+ }
3655
+ });
3656
+ }
3657
+ this.expected = value;
3658
+ this.assertCondition(this.actual === value, `Expected values to be strictly equal (using ===)`, true, void 0, stack);
3659
+ if (typeof this.actual !== typeof value) {
3660
+ throw new Error(`Types don't match: expected ${typeof value} but got ${typeof this.actual}`);
3661
+ }
3662
+ }
3663
+ toEqual(value) {
3664
+ const stack = new Error().stack;
3665
+ this.expected = value;
3666
+ const isEqual = (a, b) => {
3667
+ if (a === b) return true;
3668
+ if (a == null || b == null) return a === b;
3669
+ if (typeof a !== typeof b) return false;
3670
+ if (typeof a !== "object") return a === b;
3671
+ if (Array.isArray(a) !== Array.isArray(b)) return false;
3672
+ if (Array.isArray(a)) {
3673
+ if (a.length !== b.length) return false;
3674
+ return a.every((item, i) => isEqual(item, b[i]));
3675
+ }
3676
+ const keysA = Object.keys(a);
3677
+ const keysB = Object.keys(b);
3678
+ if (keysA.length !== keysB.length) return false;
3679
+ return keysA.every((key) => isEqual(a[key], b[key]));
3680
+ };
3681
+ this.assertCondition(isEqual(this.actual, value), "Expected values to be deeply equal", false, void 0, stack);
3682
+ }
3683
+ toBeTruthy() {
3684
+ const stack = new Error().stack;
3685
+ this.assertCondition(!!this.actual, `Expected value to be truthy`, false, void 0, stack);
3686
+ }
3687
+ toBeFalsy() {
3688
+ const stack = new Error().stack;
3689
+ this.assertCondition(!this.actual, `Expected value to be falsy`, false, void 0, stack);
3690
+ }
3691
+ toBeNull() {
3692
+ const stack = new Error().stack;
3693
+ this.assertCondition(this.actual === null, `Expected value to be null`, false, void 0, stack);
3694
+ }
3695
+ toBeUndefined() {
3696
+ const stack = new Error().stack;
3697
+ this.assertCondition(this.actual === void 0, `Expected value to be undefined`, false, void 0, stack);
3698
+ }
3699
+ toBeDefined() {
3700
+ const stack = new Error().stack;
3701
+ this.assertCondition(this.actual !== void 0, `Expected value to be defined`, false, void 0, stack);
3702
+ }
3703
+ toBeGreaterThan(value) {
3704
+ const stack = new Error().stack;
3705
+ this.expected = value;
3706
+ this.assertCondition(
3707
+ typeof this.actual === "number" && this.actual > value,
3708
+ `Expected ${this.stringify(this.actual)} to be greater than ${value}`,
3709
+ true,
3710
+ String(value),
3711
+ stack
3712
+ );
3713
+ }
3714
+ toBeGreaterThanOrEqual(value) {
3715
+ const stack = new Error().stack;
3716
+ this.expected = value;
3717
+ this.assertCondition(
3718
+ typeof this.actual === "number" && this.actual >= value,
3719
+ `Expected ${this.stringify(this.actual)} to be greater than or equal to ${value}`,
3720
+ true,
3721
+ `${value}`,
3722
+ stack
3723
+ );
3724
+ }
3725
+ toBeLessThan(value) {
3726
+ const stack = new Error().stack;
3727
+ this.expected = value;
3728
+ this.assertCondition(
3729
+ typeof this.actual === "number" && this.actual < value,
3730
+ `Expected ${this.stringify(this.actual)} to be less than ${value}`,
3731
+ true,
3732
+ String(value),
3733
+ stack
3734
+ );
3735
+ }
3736
+ toBeLessThanOrEqual(value) {
3737
+ const stack = new Error().stack;
3738
+ this.expected = value;
3739
+ this.assertCondition(
3740
+ typeof this.actual === "number" && this.actual <= value,
3741
+ `Expected ${this.stringify(this.actual)} to be less than or equal to ${value}`,
3742
+ true,
3743
+ `${value}`,
3744
+ stack
3745
+ );
3746
+ }
3747
+ toContain(value) {
3748
+ const stack = new Error().stack;
3749
+ this.expected = value;
3750
+ if (typeof this.actual === "string") {
3751
+ this.assertCondition(
3752
+ this.actual.includes(value),
3753
+ `Expected "${this.actual}" to contain "${value}"`,
3754
+ false,
3755
+ void 0,
3756
+ stack
3757
+ );
3758
+ } else if (Array.isArray(this.actual)) {
3759
+ this.assertCondition(
3760
+ this.actual.some((item) => this.deepEqual(item, value)),
3761
+ `Expected array to contain ${this.stringify(value)}`,
3762
+ false,
3763
+ void 0,
3764
+ stack
3765
+ );
3766
+ } else {
3767
+ throw new Error(`toContain expects string or array, got ${typeof this.actual}`);
3768
+ }
3769
+ }
3770
+ toHaveLength(length) {
3771
+ const stack = new Error().stack;
3772
+ this.expected = length;
3773
+ const actualLength = this.actual?.length;
3774
+ this.assertCondition(
3775
+ actualLength === length,
3776
+ `Expected length to be ${length}, but got ${actualLength}`,
3777
+ false,
3778
+ void 0,
3779
+ stack
3780
+ );
3781
+ }
3782
+ toThrow(error) {
3783
+ if (this.isAsync) {
3784
+ return this.handleAsyncAssertion(error, () => {
3785
+ });
3786
+ }
3787
+ let threw = false;
3788
+ let thrownError = null;
3789
+ try {
3790
+ if (typeof this.actual === "function") {
3791
+ this.actual();
3792
+ }
3793
+ } catch (e) {
3794
+ threw = true;
3795
+ thrownError = e;
3796
+ }
3797
+ this.assertCondition(threw, `Expected function to throw an error`);
3798
+ if (error) {
3799
+ if (typeof error === "string") {
3800
+ this.assertCondition(
3801
+ thrownError.message.includes(error),
3802
+ `Expected error message to include "${error}"`
3803
+ );
3804
+ } else if (error instanceof RegExp) {
3805
+ this.assertCondition(
3806
+ error.test(thrownError.message),
3807
+ `Expected error message to match ${error}`
3808
+ );
3809
+ }
3810
+ }
3811
+ }
3812
+ toMatch(pattern) {
3813
+ this.expected = pattern;
3814
+ const str = String(this.actual);
3815
+ if (pattern instanceof RegExp) {
3816
+ this.assertCondition(
3817
+ pattern.test(str),
3818
+ `Expected "${str}" to match ${pattern}`
3819
+ );
3820
+ } else {
3821
+ this.assertCondition(
3822
+ str.includes(pattern),
3823
+ `Expected "${str}" to contain "${pattern}"`
3824
+ );
3825
+ }
3826
+ }
3827
+ toBeInstanceOf(classType) {
3828
+ this.expected = classType;
3829
+ this.assertCondition(
3830
+ this.actual instanceof classType,
3831
+ `Expected value to be instance of ${classType.name}`
3832
+ );
3833
+ }
3834
+ toHaveProperty(path, value) {
3835
+ const keys = Array.isArray(path) ? path : path.split(".");
3836
+ let obj = this.actual;
3837
+ for (const key of keys) {
3838
+ if (obj == null || !Object.hasOwnProperty.call(obj, key)) {
3839
+ throw new Error(`Expected object to have property "${path}"`);
3840
+ }
3841
+ obj = obj[key];
3842
+ }
3843
+ if (value !== void 0) {
3844
+ this.assertCondition(
3845
+ this.deepEqual(obj, value),
3846
+ `Expected property "${path}" to equal ${this.stringify(value)}`
3847
+ );
3848
+ }
3849
+ }
3850
+ // Mock function matchers
3851
+ toBeCalled() {
3852
+ this.assertCondition(
3853
+ this.actual._isMock && this.actual._calls.length > 0,
3854
+ `Expected mock function to have been called`
3855
+ );
3856
+ }
3857
+ toBeCalledTimes(times) {
3858
+ this.assertCondition(
3859
+ this.actual._isMock && this.actual._calls.length === times,
3860
+ `Expected mock to be called ${times} times, but was called ${this.actual._calls?.length || 0} times`
3861
+ );
3862
+ }
3863
+ toBeCalledWith(...args) {
3864
+ this.assertCondition(this.actual._isMock && this.actual._calls.some((call) => this.deepEqual(call, args)), `Expected mock to be called with ${this.stringify(args)}`);
3865
+ }
3866
+ lastReturnedWith(value) {
3867
+ const lastResult = this.actual._results?.[this.actual._results.length - 1];
3868
+ this.assertCondition(
3869
+ lastResult && this.deepEqual(lastResult.value, value),
3870
+ `Expected last call to return ${this.stringify(value)}`
3871
+ );
3872
+ }
3873
+ deepEqual(a, b) {
3874
+ return JSON.stringify(a) === JSON.stringify(b);
3875
+ }
3876
+ };
3877
+ function expect(actual) {
3878
+ return new Expect(actual);
3879
+ }
3880
+ function createMockFunction() {
3881
+ const mock = function(...args) {
3882
+ mock._calls.push(args);
3883
+ try {
3884
+ const result = mock._implementation ? mock._implementation(...args) : void 0;
3885
+ mock._results.push({ type: "return", value: result });
3886
+ return result;
3887
+ } catch (error) {
3888
+ mock._results.push({ type: "throw", value: error });
3889
+ throw error;
3890
+ }
3891
+ };
3892
+ mock._isMock = true;
3893
+ mock._calls = [];
3894
+ mock._results = [];
3895
+ mock._implementation = null;
3896
+ mock.mockImplementation = function(fn) {
3897
+ mock._implementation = fn;
3898
+ return mock;
3899
+ };
3900
+ mock.mockReturnValue = function(value) {
3901
+ mock._implementation = (() => value);
3902
+ return mock;
3903
+ };
3904
+ mock.mockResolvedValue = function(value) {
3905
+ mock._implementation = (() => Promise.resolve(value));
3906
+ return mock;
3907
+ };
3908
+ mock.mockRejectedValue = function(value) {
3909
+ mock._implementation = (() => Promise.reject(value));
3910
+ return mock;
3911
+ };
3912
+ mock.restore = function() {
3913
+ mock._calls = [];
3914
+ mock._results = [];
3915
+ mock._implementation = null;
3916
+ };
3917
+ mock.clear = function() {
3918
+ mock._calls = [];
3919
+ mock._results = [];
3920
+ };
3921
+ return mock;
3922
+ }
3923
+ var vi = {
3924
+ fn: () => createMockFunction(),
3925
+ spyOn: (obj, method) => {
3926
+ const original = obj[method];
3927
+ const mock = createMockFunction();
3928
+ mock.mockImplementation(original);
3929
+ obj[method] = mock;
3930
+ mock.restore = () => {
3931
+ obj[method] = original;
3932
+ };
3933
+ return mock;
3934
+ },
3935
+ clearAllMocks: () => {
3936
+ },
3937
+ restoreAllMocks: () => {
3938
+ }
3939
+ };
3940
+ var beforeAllHooks = [];
3941
+ var afterAllHooks = [];
3942
+ var beforeEachHooks = [];
3943
+ var afterEachHooks = [];
3944
+ var beforeAll = (fn) => beforeAllHooks.push(fn);
3945
+ var afterAll = (fn) => afterAllHooks.push(fn);
3946
+ var beforeEach = (fn) => beforeEachHooks.push(fn);
3947
+ var afterEach = (fn) => afterEachHooks.push(fn);
3948
+ async function runTests(options) {
3949
+ const { files, timeout = 5e3, bail = false, describePattern: descPattern, testPattern: tPattern } = options;
3950
+ describePattern = descPattern;
3951
+ testPattern = tPattern;
3952
+ testResults.length = 0;
3953
+ hasOnly = false;
3954
+ for (const file of files) {
3955
+ currentTestFile = file;
3956
+ try {
3957
+ const source = await readFile(file, "utf-8");
3958
+ const testFileDir = dirname(file);
3959
+ const importRegex = /import\s+{\s*([^}]+)\s*}\s+from\s+['"]([^'"]+)['"]/g;
3960
+ const imports = {};
3961
+ let importIndex = 0;
3962
+ let codeWithoutImports = source.replace(importRegex, (_, named, path) => {
3963
+ const varName = `__import_${importIndex++}`;
3964
+ const trimmedNamed = named.trim();
3965
+ imports[varName] = { path, named: trimmedNamed };
3966
+ return `// ${trimmedNamed} import injected later
3967
+ `;
3968
+ });
3969
+ const result = (0, import_esbuild.transformSync)(codeWithoutImports, {
3970
+ loader: file.endsWith(".ts") || file.endsWith(".tsx") ? "ts" : "js",
3971
+ format: "iife",
3972
+ sourcemap: "inline",
3973
+ target: "es2020",
3974
+ tsconfigRaw: {
3975
+ compilerOptions: {
3976
+ jsx: "react",
3977
+ jsxFactory: "h",
3978
+ jsxFragmentFactory: "Fragment"
3979
+ }
3980
+ }
3981
+ });
3982
+ let code = result.code;
3983
+ const sourceMapMatch = code.match(/\/\/# sourceMappingURL=data:application\/json;base64,(.+)/);
3984
+ if (sourceMapMatch) {
3985
+ const base64 = sourceMapMatch[1];
3986
+ const json = Buffer.from(base64, "base64").toString("utf-8");
3987
+ const sourceMap = JSON.parse(json);
3988
+ currentSourceMapConsumer = await new import_source_map.SourceMapConsumer(sourceMap);
3989
+ } else {
3990
+ currentSourceMapConsumer = void 0;
3991
+ }
3992
+ const importedValues = {};
3993
+ const importParamNames = [];
3994
+ const importAssignments = [];
3995
+ if (Object.keys(imports).length > 0) {
3996
+ for (const [, { path, named }] of Object.entries(imports)) {
3997
+ let resolvedPath = path;
3998
+ if (path.startsWith(".")) {
3999
+ const nodePath = require("path");
4000
+ resolvedPath = nodePath.resolve(testFileDir, path);
4001
+ }
4002
+ if (!resolvedPath.endsWith(".ts") && !resolvedPath.endsWith(".js") && !resolvedPath.endsWith(".mjs") && !resolvedPath.endsWith(".cjs")) {
4003
+ resolvedPath += ".ts";
4004
+ }
4005
+ if (resolvedPath.endsWith(".ts")) {
4006
+ try {
4007
+ const importSource = await readFile(resolvedPath, "utf-8");
4008
+ const transpiled = (0, import_esbuild.transformSync)(importSource, {
4009
+ loader: "ts",
4010
+ format: "cjs",
4011
+ target: "es2020",
4012
+ tsconfigRaw: {
4013
+ compilerOptions: {
4014
+ jsx: "react",
4015
+ jsxFactory: "h",
4016
+ jsxFragmentFactory: "Fragment"
4017
+ }
4018
+ }
4019
+ });
4020
+ const moduleExports = {};
4021
+ const moduleObj = { exports: moduleExports };
4022
+ const fn2 = new Function("module", "exports", "require", "__filename", "__dirname", transpiled.code);
4023
+ const requireFn = (id) => {
4024
+ if (id.startsWith("elit/") || id === "elit") {
4025
+ return require(id);
4026
+ }
4027
+ if (id.startsWith(".")) {
4028
+ const nodePath = require("path");
4029
+ const absPath = nodePath.resolve(dirname(resolvedPath), id);
4030
+ return require(absPath);
4031
+ }
4032
+ return require(id);
4033
+ };
4034
+ fn2(moduleObj, moduleExports, requireFn, resolvedPath, dirname(resolvedPath));
4035
+ if (!resolvedPath.includes(".test.") && !resolvedPath.includes(".spec.")) {
4036
+ coveredFiles.add(resolvedPath);
4037
+ }
4038
+ let exportedValue = moduleObj.exports[named];
4039
+ if (exportedValue === void 0 && moduleObj.exports.default) {
4040
+ exportedValue = moduleObj.exports.default[named];
4041
+ }
4042
+ if (exportedValue === void 0 && typeof moduleObj.exports === "object") {
4043
+ exportedValue = moduleObj.exports[named];
4044
+ }
4045
+ const paramKey = `__import_${Math.random().toString(36).substring(2, 11)}`;
4046
+ importedValues[paramKey] = exportedValue;
4047
+ importParamNames.push(paramKey);
4048
+ importAssignments.push(`const ${named} = ${paramKey};`);
4049
+ } catch (err) {
4050
+ const paramKey = `__import_${Math.random().toString(36).substring(2, 11)}`;
4051
+ importedValues[paramKey] = null;
4052
+ importParamNames.push(paramKey);
4053
+ importAssignments.push(`const ${named} = ${paramKey}; /* Error importing ${resolvedPath}: ${err} */`);
4054
+ }
4055
+ } else {
4056
+ const requiredModule = require(resolvedPath);
4057
+ const exportedValue = requiredModule[named];
4058
+ const paramKey = `__import_${Math.random().toString(36).substring(2, 11)}`;
4059
+ importedValues[paramKey] = exportedValue;
4060
+ importParamNames.push(paramKey);
4061
+ importAssignments.push(`const ${named} = ${paramKey};`);
4062
+ }
4063
+ }
4064
+ }
4065
+ let preamble = "";
4066
+ if (Object.keys(imports).length > 0) {
4067
+ const iifeStartMatch = code.match(/^(\s*(?:var\s+\w+\s*=\s*)?\(\(\)\s*=>\s*\{\n)/);
4068
+ if (iifeStartMatch) {
4069
+ const iifePrefix = iifeStartMatch[1];
4070
+ const assignments = `${importAssignments.join("\n")}
4071
+ `;
4072
+ preamble = iifePrefix;
4073
+ code = iifePrefix + assignments + code.slice(iifeStartMatch[1].length);
4074
+ } else {
4075
+ preamble = importAssignments.join("\n") + "\n";
4076
+ code = preamble + code;
4077
+ }
4078
+ }
4079
+ wrapperLineOffset = preamble.split("\n").length;
4080
+ setupGlobals();
4081
+ const allParams = ["describe", "it", "test", "expect", "beforeAll", "afterAll", "beforeEach", "afterEach", "vi", "require", "module", "__filename", "__dirname", ...importParamNames];
4082
+ const allArgs = [describe, it, test, expect, beforeAll, afterAll, beforeEach, afterEach, vi, require, module, file, testFileDir, ...importParamNames.map((p) => importedValues[p])];
4083
+ const fn = new Function(...allParams, code);
4084
+ await fn(...allArgs);
4085
+ await executeSuite(currentSuite, timeout, bail);
4086
+ if (currentSourceMapConsumer) {
4087
+ currentSourceMapConsumer.destroy();
4088
+ currentSourceMapConsumer = void 0;
4089
+ }
4090
+ currentSuite = {
4091
+ name: "root",
4092
+ tests: [],
4093
+ suites: [],
4094
+ skip: false,
4095
+ only: false
4096
+ };
4097
+ hasOnly = false;
4098
+ beforeAllHooks = [];
4099
+ afterAllHooks = [];
4100
+ beforeEachHooks = [];
4101
+ afterEachHooks = [];
4102
+ } catch (error) {
4103
+ if (currentSourceMapConsumer) {
4104
+ currentSourceMapConsumer.destroy();
4105
+ currentSourceMapConsumer = void 0;
4106
+ }
4107
+ console.error(`Error loading test file ${file}:`, error);
4108
+ }
4109
+ }
4110
+ const passed = testResults.filter((r) => r.status === "pass").length;
4111
+ const failed = testResults.filter((r) => r.status === "fail").length;
4112
+ const skipped = testResults.filter((r) => r.status === "skip").length;
4113
+ const todo = testResults.filter((r) => r.status === "todo").length;
4114
+ return { passed, failed, skipped, todo, results: testResults };
4115
+ }
4116
+ async function executeSuite(suite, timeout, bail, parentMatched = false) {
4117
+ let directMatch = false;
4118
+ if (describePattern) {
4119
+ const escapedPattern = escapeRegex(describePattern);
4120
+ const regex = new RegExp(escapedPattern, "i");
4121
+ directMatch = regex.test(suite.name);
4122
+ }
4123
+ function suiteOrDescendantMatches(s) {
4124
+ if (!describePattern) return true;
4125
+ const escapedPattern = escapeRegex(describePattern);
4126
+ const regex = new RegExp(escapedPattern, "i");
4127
+ if (regex.test(s.name)) return true;
4128
+ for (const child of s.suites) {
4129
+ if (suiteOrDescendantMatches(child)) return true;
4130
+ }
4131
+ return false;
4132
+ }
4133
+ const shouldRunSuite = !describePattern || directMatch || parentMatched || suiteOrDescendantMatches(suite);
4134
+ if (!shouldRunSuite) {
4135
+ return;
4136
+ }
4137
+ if (suite.suites.length > 0) {
4138
+ for (const childSuite of suite.suites) {
4139
+ await executeSuite(childSuite, timeout, bail, parentMatched || directMatch);
4140
+ }
4141
+ }
4142
+ const shouldRunTests = !describePattern || directMatch || parentMatched || suite.name === "";
4143
+ if (!shouldRunTests) {
4144
+ return;
4145
+ }
4146
+ for (const hook of beforeAllHooks) {
4147
+ await hook();
4148
+ }
4149
+ for (const test2 of suite.tests) {
4150
+ if (hasOnly && !test2.only && !suite.only) {
4151
+ continue;
4152
+ }
4153
+ let testMatches = true;
4154
+ if (testPattern) {
4155
+ const escapedPattern = escapeRegex(testPattern);
4156
+ const regex = new RegExp(escapedPattern, "i");
4157
+ testMatches = regex.test(test2.name);
4158
+ }
4159
+ if (!testMatches) {
4160
+ continue;
4161
+ }
4162
+ if (test2.skip || suite.skip) {
4163
+ testResults.push({
4164
+ name: test2.name,
4165
+ status: "skip",
4166
+ duration: 0,
4167
+ suite: suite.name,
4168
+ file: currentTestFile
4169
+ });
4170
+ continue;
4171
+ }
4172
+ if (test2.todo) {
4173
+ testResults.push({
4174
+ name: test2.name,
4175
+ status: "todo",
4176
+ duration: 0,
4177
+ suite: suite.name,
4178
+ file: currentTestFile
4179
+ });
4180
+ continue;
4181
+ }
4182
+ for (const hook of beforeEachHooks) {
4183
+ await hook();
4184
+ }
4185
+ const startTime = Date.now();
4186
+ try {
4187
+ await Promise.race([
4188
+ test2.fn(),
4189
+ new Promise(
4190
+ (_, reject) => setTimeout(() => reject(new Error(`Test timed out after ${test2.timeout}ms`)), test2.timeout)
4191
+ )
4192
+ ]);
4193
+ testResults.push({
4194
+ name: test2.name,
4195
+ status: "pass",
4196
+ duration: Date.now() - startTime,
4197
+ suite: suite.name,
4198
+ file: currentTestFile
4199
+ });
4200
+ } catch (error) {
4201
+ let lineNumber = void 0;
4202
+ let codeSnippet = void 0;
4203
+ if (error instanceof AssertionError) {
4204
+ lineNumber = error.lineNumber;
4205
+ codeSnippet = error.codeSnippet;
4206
+ }
4207
+ testResults.push({
4208
+ name: test2.name,
4209
+ status: "fail",
4210
+ duration: Date.now() - startTime,
4211
+ error,
4212
+ suite: suite.name,
4213
+ file: currentTestFile,
4214
+ lineNumber,
4215
+ codeSnippet
4216
+ });
4217
+ if (bail) {
4218
+ throw error;
4219
+ }
4220
+ }
4221
+ for (const hook of afterEachHooks) {
4222
+ await hook();
4223
+ }
4224
+ }
4225
+ for (const hook of afterAllHooks) {
4226
+ await hook();
4227
+ }
4228
+ }
4229
+ var globals = {
4230
+ describe: createDescribeFunction(),
4231
+ it: createTestFunction(5e3),
4232
+ test: createTestFunction(5e3),
4233
+ expect,
4234
+ beforeAll,
4235
+ afterAll,
4236
+ beforeEach,
4237
+ afterEach,
4238
+ vi
4239
+ };
4240
+ function setupGlobals() {
4241
+ global.describe = globals.describe;
4242
+ global.it = globals.it;
4243
+ global.test = globals.test;
4244
+ global.expect = globals.expect;
4245
+ global.beforeAll = globals.beforeAll;
4246
+ global.afterAll = globals.afterAll;
4247
+ global.beforeEach = globals.beforeEach;
4248
+ global.afterEach = globals.afterEach;
4249
+ global.vi = globals.vi;
4250
+ }
4251
+ function clearGlobals() {
4252
+ delete global.describe;
4253
+ delete global.it;
4254
+ delete global.test;
4255
+ delete global.expect;
4256
+ delete global.beforeAll;
4257
+ delete global.afterAll;
4258
+ delete global.beforeEach;
4259
+ delete global.afterEach;
4260
+ delete global.vi;
4261
+ }
4262
+ function getCoveredFiles() {
4263
+ return coveredFiles;
4264
+ }
4265
+ function resetCoveredFiles() {
4266
+ coveredFiles.clear();
4267
+ }
4268
+
4269
+ // src/test-reporter.ts
4270
+ init_path();
4271
+ var colors = {
4272
+ reset: "\x1B[0m",
4273
+ bold: "\x1B[1m",
4274
+ dim: "\x1B[2m",
4275
+ red: "\x1B[31m",
4276
+ green: "\x1B[32m",
4277
+ yellow: "\x1B[33m",
4278
+ blue: "\x1B[34m",
4279
+ cyan: "\x1B[36m",
4280
+ white: "\x1B[37m"
4281
+ };
4282
+ function extractArg(code, functionName) {
4283
+ const searchStr = `.${functionName}(`;
4284
+ const startIndex = code.indexOf(searchStr);
4285
+ if (startIndex === -1) return null;
4286
+ let parenCount = 0;
4287
+ let inString = false;
4288
+ let stringChar = "";
4289
+ let argStart = startIndex + searchStr.length;
4290
+ for (let i = argStart; i < code.length; i++) {
4291
+ const char = code[i];
4292
+ if (!inString) {
4293
+ if (char === "(") parenCount++;
4294
+ else if (char === ")") {
4295
+ parenCount--;
4296
+ if (parenCount < 0) {
4297
+ return code.slice(argStart, i);
4298
+ }
4299
+ } else if (char === '"' || char === "'" || char === "`") {
4300
+ inString = true;
4301
+ stringChar = char;
4302
+ }
4303
+ } else {
4304
+ if (char === "\\" && i + 1 < code.length) {
4305
+ i++;
4306
+ } else if (char === stringChar) {
4307
+ inString = false;
4308
+ }
4309
+ }
4310
+ }
4311
+ return null;
4312
+ }
4313
+ function extractReceivedValue(errorMsg) {
4314
+ const receivedIndex = errorMsg.indexOf("Received:");
4315
+ if (receivedIndex === -1) return null;
4316
+ const afterReceived = errorMsg.slice(receivedIndex + 9).trimStart();
4317
+ const newlineIndex = afterReceived.indexOf("\n");
4318
+ if (newlineIndex !== -1) {
4319
+ return afterReceived.slice(0, newlineIndex).trimEnd();
4320
+ }
4321
+ return afterReceived.trimEnd();
4322
+ }
4323
+ function parseQuotedString(str) {
4324
+ if (str.length < 2) return null;
4325
+ const firstChar = str[0];
4326
+ const lastChar = str[str.length - 1];
4327
+ if ((firstChar === '"' || firstChar === "'" || firstChar === "`") && firstChar === lastChar) {
4328
+ return {
4329
+ quote: firstChar,
4330
+ content: str.slice(1, -1)
4331
+ };
4332
+ }
4333
+ return null;
4334
+ }
4335
+ function stripQuotes(str) {
4336
+ if (str.length < 2) return str;
4337
+ const firstChar = str[0];
4338
+ const lastChar = str[str.length - 1];
4339
+ if ((firstChar === '"' || firstChar === "'" || firstChar === "`") && firstChar === lastChar) {
4340
+ return str.slice(1, -1);
4341
+ }
4342
+ return str;
4343
+ }
4344
+ var TestReporter = class {
4345
+ constructor(options = {}) {
4346
+ this.startTime = 0;
4347
+ this.currentFile = void 0;
4348
+ this.fileTestCount = 0;
4349
+ this.totalFiles = 0;
4350
+ this.options = {
4351
+ verbose: false,
4352
+ colors: true,
4353
+ ...options
4354
+ };
4355
+ }
4356
+ c(color, text) {
4357
+ return this.options.colors !== false ? colors[color] + text + colors.reset : text;
4358
+ }
4359
+ onRunStart(files) {
4360
+ this.startTime = Date.now();
4361
+ this.totalFiles = files.length;
4362
+ console.log(`
4363
+ ${this.c("bold", "Test Files")}: ${files.length}`);
4364
+ console.log(`${this.c("dim", "\u2500".repeat(50))}
4365
+ `);
4366
+ }
4367
+ onTestResult(result) {
4368
+ const filePath = result.file ? relative(process.cwd(), result.file).split("\\").join("/") : void 0;
4369
+ if (filePath !== this.currentFile) {
4370
+ if (this.currentFile && this.fileTestCount > 0) {
4371
+ console.log("");
4372
+ }
4373
+ this.currentFile = filePath;
4374
+ this.fileTestCount = 0;
4375
+ if (filePath) {
4376
+ console.log(`${this.c("cyan", "\u25CF")} ${this.c("bold", filePath)}`);
4377
+ console.log(`${this.c("dim", "\u2504".repeat(50))}`);
4378
+ }
4379
+ }
4380
+ this.fileTestCount++;
4381
+ if (result.status === "pass") {
4382
+ console.log(` ${this.c("green", "\u2713")} ${this.c("dim", result.suite + " > ")}${result.name} ${this.c("dim", `(${result.duration}ms)`)}`);
4383
+ } else if (result.status === "fail") {
4384
+ console.log(` ${this.c("red", "\u2715")} ${this.c("dim", result.suite + " > ")}${result.name}`);
4385
+ if (result.error) {
4386
+ const filePath2 = result.file;
4387
+ if (filePath2) {
4388
+ const relativePath2 = relative(process.cwd(), filePath2).split("\\").join("/");
4389
+ const lineSuffix = result.lineNumber ? `:${result.lineNumber}` : "";
4390
+ console.log(` ${this.c("cyan", `\u{1F4C4} ${relativePath2}${lineSuffix}`)}`);
4391
+ }
4392
+ const lines = result.error.message.split("\n");
4393
+ for (const line of lines) {
4394
+ if (line.includes("Expected:")) {
4395
+ console.log(` ${this.c("green", "Expected:")} ${line.trim().replace("Expected:", "").trim()}`);
4396
+ } else if (line.includes("Received:")) {
4397
+ console.log(` ${this.c("red", "Received:")} ${line.trim().replace("Received:", "").trim()}`);
4398
+ } else {
4399
+ console.log(` ${this.c("red", line.trim())}`);
4400
+ }
4401
+ }
4402
+ if (result.codeSnippet) {
4403
+ let suggestion = "";
4404
+ const code = result.codeSnippet;
4405
+ const errorMsg = result.error?.message || "";
4406
+ const receivedValue = extractReceivedValue(errorMsg);
4407
+ if (code.includes(".toBeGreaterThanOrEqual(")) {
4408
+ const currentValue = extractArg(code, "toBeGreaterThanOrEqual");
4409
+ if (currentValue && receivedValue) {
4410
+ const actualValue = Number(receivedValue);
4411
+ if (!isNaN(actualValue)) {
4412
+ suggestion = code.replace(
4413
+ `.toBeGreaterThanOrEqual(${currentValue})`,
4414
+ `.toBeGreaterThanOrEqual(${actualValue})`
4415
+ );
4416
+ }
4417
+ }
4418
+ } else if (code.includes(".toBeGreaterThan(")) {
4419
+ const currentValue = extractArg(code, "toBeGreaterThan");
4420
+ if (currentValue && receivedValue) {
4421
+ const actualValue = Number(receivedValue);
4422
+ if (!isNaN(actualValue)) {
4423
+ suggestion = code.replace(
4424
+ `.toBeGreaterThan(${currentValue})`,
4425
+ `.toBeGreaterThan(${actualValue - 1})`
4426
+ );
4427
+ }
4428
+ }
4429
+ } else if (code.includes(".toBeLessThanOrEqual(")) {
4430
+ const currentValue = extractArg(code, "toBeLessThanOrEqual");
4431
+ if (currentValue && receivedValue) {
4432
+ const actualValue = Number(receivedValue);
4433
+ if (!isNaN(actualValue)) {
4434
+ suggestion = code.replace(
4435
+ `.toBeLessThanOrEqual(${currentValue})`,
4436
+ `.toBeLessThanOrEqual(${actualValue})`
4437
+ );
4438
+ }
4439
+ }
4440
+ } else if (code.includes(".toBeLessThan(")) {
4441
+ const currentValue = extractArg(code, "toBeLessThan");
4442
+ if (currentValue && receivedValue) {
4443
+ const actualValue = Number(receivedValue);
4444
+ if (!isNaN(actualValue)) {
4445
+ suggestion = code.replace(
4446
+ `.toBeLessThan(${currentValue})`,
4447
+ `.toBeLessThan(${actualValue + 1})`
4448
+ );
4449
+ }
4450
+ }
4451
+ } else if (code.includes(".toStrictEqual(")) {
4452
+ const expectedValue = extractArg(code, "toStrictEqual");
4453
+ if (expectedValue && receivedValue) {
4454
+ const quoted = parseQuotedString(expectedValue);
4455
+ if (quoted) {
4456
+ const strippedReceived = stripQuotes(receivedValue);
4457
+ suggestion = code.replace(
4458
+ `.toStrictEqual(${expectedValue})`,
4459
+ `.toStrictEqual(${quoted.quote}${strippedReceived}${quoted.quote})`
4460
+ );
4461
+ } else {
4462
+ suggestion = code.replace(
4463
+ `.toStrictEqual(${expectedValue})`,
4464
+ `.toStrictEqual(${receivedValue})`
4465
+ );
4466
+ }
4467
+ }
4468
+ } else if (code.includes(".toEqual(")) {
4469
+ const expectedValue = extractArg(code, "toEqual");
4470
+ if (expectedValue && receivedValue) {
4471
+ const quoted = parseQuotedString(expectedValue);
4472
+ if (quoted) {
4473
+ const strippedReceived = stripQuotes(receivedValue);
4474
+ suggestion = code.replace(
4475
+ `.toEqual(${expectedValue})`,
4476
+ `.toEqual(${quoted.quote}${strippedReceived}${quoted.quote})`
4477
+ );
4478
+ } else {
4479
+ suggestion = code.replace(
4480
+ `.toEqual(${expectedValue})`,
4481
+ `.toEqual(${receivedValue})`
4482
+ );
4483
+ }
4484
+ }
4485
+ } else if (code.includes(".toMatch(")) {
4486
+ const expectedPattern = extractArg(code, "toMatch");
4487
+ if (expectedPattern && receivedValue) {
4488
+ const quoted = parseQuotedString(expectedPattern);
4489
+ if (quoted) {
4490
+ const strippedReceived = stripQuotes(receivedValue);
4491
+ suggestion = code.replace(
4492
+ `.toMatch(${expectedPattern})`,
4493
+ `.toMatch(${quoted.quote}${strippedReceived}${quoted.quote})`
4494
+ );
4495
+ }
4496
+ }
4497
+ } else if (code.includes(".toContain(")) {
4498
+ const expectedValue = extractArg(code, "toContain");
4499
+ if (expectedValue && receivedValue) {
4500
+ const quoted = parseQuotedString(expectedValue);
4501
+ if (quoted) {
4502
+ const strippedReceived = stripQuotes(receivedValue);
4503
+ suggestion = code.replace(
4504
+ `.toContain(${expectedValue})`,
4505
+ `.toContain(${quoted.quote}${strippedReceived}${quoted.quote})`
4506
+ );
4507
+ } else {
4508
+ suggestion = code.replace(
4509
+ `.toContain(${expectedValue})`,
4510
+ `.toContain(${receivedValue})`
4511
+ );
4512
+ }
4513
+ }
4514
+ } else if (code.includes(".toHaveLength(")) {
4515
+ const expectedLength = extractArg(code, "toHaveLength");
4516
+ if (expectedLength && receivedValue) {
4517
+ const actualLength = Number(receivedValue);
4518
+ if (!isNaN(actualLength)) {
4519
+ suggestion = code.replace(
4520
+ `.toHaveLength(${expectedLength})`,
4521
+ `.toHaveLength(${actualLength})`
4522
+ );
4523
+ }
4524
+ }
4525
+ } else if (code.includes(".toBe(")) {
4526
+ const expectedValue = extractArg(code, "toBe");
4527
+ if (expectedValue) {
4528
+ if (receivedValue) {
4529
+ const quoted = parseQuotedString(expectedValue);
4530
+ if (quoted) {
4531
+ const strippedReceived = stripQuotes(receivedValue);
4532
+ suggestion = code.replace(
4533
+ `.toBe(${expectedValue})`,
4534
+ `.toBe(${quoted.quote}${strippedReceived}${quoted.quote})`
4535
+ );
4536
+ } else {
4537
+ suggestion = code.replace(
4538
+ `.toBe(${expectedValue})`,
4539
+ `.toBe(${receivedValue})`
4540
+ );
4541
+ }
4542
+ } else if (expectedValue.includes("'") || expectedValue.includes('"')) {
4543
+ suggestion = code.replace(".toBe(", ".toEqual(");
4544
+ }
4545
+ }
4546
+ } else if (code.includes(".toBeDefined()")) {
4547
+ suggestion = code.replace(".toBeDefined()", ".toBeTruthy()");
4548
+ } else if (code.includes(".toBeNull()")) {
4549
+ suggestion = code.replace(".toBeNull()", ".toBeUndefined()");
4550
+ } else if (code.includes(".toBeUndefined()")) {
4551
+ suggestion = code.replace(".toBeUndefined()", ".toBeNull()");
4552
+ } else if (code.includes(".toBeTruthy()")) {
4553
+ suggestion = code.replace(".toBeTruthy()", ".toBeDefined()");
4554
+ } else if (code.includes(".toBeFalsy()")) {
4555
+ suggestion = code.replace(".toBeFalsy()", ".toBeUndefined()");
4556
+ }
4557
+ console.log(` ${this.c("dim", "Code:")}`);
4558
+ console.log(` ${this.c("dim", code)}`);
4559
+ if (suggestion && suggestion !== code) {
4560
+ console.log(` ${this.c("yellow", "example \u2192")} ${this.c("green", suggestion)}`);
4561
+ }
4562
+ }
4563
+ if (this.options.verbose && result.error.stack) {
4564
+ const stack = result.error.stack.split("\n").slice(1, 3).join("\n");
4565
+ console.log(` ${this.c("dim", stack)}`);
4566
+ }
4567
+ }
4568
+ } else if (result.status === "skip") {
4569
+ console.log(` ${this.c("yellow", "\u25CB")} ${this.c("dim", result.suite + " > ")}${result.name} ${this.c("yellow", "(skipped)")}`);
4570
+ } else if (result.status === "todo") {
4571
+ console.log(` ${this.c("cyan", "\u25CB")} ${this.c("dim", result.suite + " > ")}${result.name} ${this.c("cyan", "(todo)")}`);
4572
+ }
4573
+ }
4574
+ onRunEnd(results) {
4575
+ const duration = Date.now() - this.startTime;
4576
+ const passed = results.filter((r) => r.status === "pass").length;
4577
+ const failed = results.filter((r) => r.status === "fail").length;
4578
+ const skipped = results.filter((r) => r.status === "skip").length;
4579
+ const total = results.length;
4580
+ if (this.currentFile && this.fileTestCount > 0) {
4581
+ console.log("");
4582
+ }
4583
+ console.log(`${this.c("dim", "\u2500".repeat(50))}`);
4584
+ console.log("");
4585
+ console.log(`${this.c("bold", "Test Suites:")} ${this.c("green", `${this.totalFiles} passed`)}${this.c("dim", `, ${this.totalFiles} total`)}`);
4586
+ console.log(`${this.c("bold", "Tests:")} ${this.c("green", `${passed} passed`)}${failed > 0 ? `, ${this.c("red", `${failed} failed`)}` : ""}${skipped > 0 ? `, ${this.c("yellow", `${skipped} skipped`)}` : ""}${this.c("dim", `, ${total} total`)}`);
4587
+ console.log(`${this.c("bold", "Snapshots:")} ${this.c("dim", "0 total")}`);
4588
+ console.log(`${this.c("bold", "Time:")} ${this.c("dim", `${(duration / 1e3).toFixed(2)}s`)}`);
4589
+ console.log("");
4590
+ }
4591
+ };
4592
+ var DotReporter = class {
4593
+ constructor() {
4594
+ this.passed = 0;
4595
+ this.failed = 0;
4596
+ this.skipped = 0;
4597
+ this.todo = 0;
4598
+ this.lineLength = 0;
4599
+ }
4600
+ onRunStart(files) {
4601
+ console.log(`
4602
+ ${files.length} test files
4603
+ `);
4604
+ }
4605
+ onTestResult(result) {
4606
+ const symbol = result.status === "pass" ? "." : result.status === "fail" ? this.c("red", "F") : result.status === "skip" ? this.c("yellow", "o") : this.c("cyan", "o");
4607
+ process.stdout.write(symbol);
4608
+ this.lineLength++;
4609
+ if (result.status === "pass") this.passed++;
4610
+ else if (result.status === "fail") this.failed++;
4611
+ else if (result.status === "skip") this.skipped++;
4612
+ else if (result.status === "todo") this.todo++;
4613
+ if (this.lineLength >= 50) {
4614
+ process.stdout.write("\n ");
4615
+ this.lineLength = 0;
4616
+ }
4617
+ }
4618
+ onRunEnd(_results) {
4619
+ console.log(`
4620
+
4621
+ ${this.c("green", this.passed + " passed")} ${this.c("dim", "\xB7")} ${this.c("red", this.failed + " failed")} ${this.c("dim", "\xB7")} ${this.c("yellow", this.skipped + " skipped")}
4622
+ `);
4623
+ }
4624
+ c(color, text) {
4625
+ return colors[color] + text + colors.reset;
4626
+ }
4627
+ };
4628
+ var JsonReporter = class {
4629
+ constructor() {
4630
+ this.startTime = 0;
4631
+ this.results = [];
4632
+ }
4633
+ onRunStart(_files) {
4634
+ this.startTime = Date.now();
4635
+ this.results = [];
4636
+ }
4637
+ onTestResult(result) {
4638
+ this.results.push(result);
4639
+ }
4640
+ onRunEnd(results) {
4641
+ const report = {
4642
+ summary: {
4643
+ total: results.length,
4644
+ passed: results.filter((r) => r.status === "pass").length,
4645
+ failed: results.filter((r) => r.status === "fail").length,
4646
+ skipped: results.filter((r) => r.status === "skip").length,
4647
+ todo: results.filter((r) => r.status === "todo").length,
4648
+ duration: Date.now() - this.startTime
4649
+ },
4650
+ tests: results.map((r) => ({
4651
+ status: r.status === "pass" ? "passed" : r.status === "fail" ? "failed" : r.status === "skip" ? "skipped" : "todo",
4652
+ name: r.name,
4653
+ suite: r.suite,
4654
+ duration: r.duration,
4655
+ error: r.error ? {
4656
+ message: r.error.message,
4657
+ stack: r.error.stack
4658
+ } : void 0
4659
+ }))
4660
+ };
4661
+ console.log(JSON.stringify(report, null, 2));
4662
+ }
4663
+ };
4664
+ var VerboseReporter = class {
4665
+ constructor() {
4666
+ this.currentSuite = "";
4667
+ }
4668
+ onRunStart(_files) {
4669
+ console.log(`
4670
+ ${colors.cyan}Running tests${colors.reset}
4671
+ `);
4672
+ }
4673
+ onTestResult(result) {
4674
+ if (result.suite !== this.currentSuite) {
4675
+ this.currentSuite = result.suite;
4676
+ console.log(`
4677
+ ${colors.dim}${result.suite}${colors.reset}`);
4678
+ }
4679
+ const icon = result.status === "pass" ? colors.green + " \u2713" : result.status === "fail" ? colors.red + " \u2715" : result.status === "skip" ? colors.yellow + " \u2298" : colors.cyan + " \u25CB";
4680
+ console.log(`${icon}${colors.reset} ${result.name}${colors.dim} (${result.duration}ms)${colors.reset}`);
4681
+ if (result.status === "fail" && result.error) {
4682
+ console.log(`
4683
+ ${colors.red} ${result.error.message}${colors.reset}`);
4684
+ if (result.error.stack) {
4685
+ const lines = result.error.stack.split("\n").slice(1, 4);
4686
+ lines.forEach((line) => console.log(`${colors.dim} ${line}${colors.reset}`));
4687
+ }
4688
+ }
4689
+ }
4690
+ onRunEnd(results) {
4691
+ const passed = results.filter((r) => r.status === "pass").length;
4692
+ const failed = results.filter((r) => r.status === "fail").length;
4693
+ const skipped = results.filter((r) => r.status === "skip").length;
4694
+ console.log(`
4695
+ ${colors.dim}${"\u2500".repeat(50)}${colors.reset}
4696
+ `);
4697
+ if (failed === 0) {
4698
+ console.log(`${colors.green}All tests passed!${colors.reset}`);
4699
+ console.log(`${colors.dim}${passed} tests${colors.reset}
4700
+ `);
4701
+ } else {
4702
+ console.log(`${colors.red}${failed} tests failed${colors.reset}`);
4703
+ console.log(`${colors.green}${passed} tests passed${colors.reset}`);
4704
+ if (skipped > 0) {
4705
+ console.log(`${colors.yellow}${skipped} tests skipped${colors.reset}`);
4706
+ }
4707
+ console.log("");
4708
+ }
4709
+ }
4710
+ };
4711
+
4712
+ // src/test.ts
4713
+ function globToRegex2(pattern) {
4714
+ let expanded = pattern;
4715
+ const openBraceIndex = pattern.indexOf("{");
4716
+ if (openBraceIndex !== -1) {
4717
+ const closeBraceIndex = pattern.indexOf("}", openBraceIndex);
4718
+ if (closeBraceIndex !== -1) {
4719
+ const options = pattern.slice(openBraceIndex + 1, closeBraceIndex).split(",");
4720
+ const before = pattern.slice(0, openBraceIndex);
4721
+ const after = pattern.slice(closeBraceIndex + 1);
4722
+ expanded = before + "(" + options.join("|") + ")" + after;
4723
+ }
4724
+ }
4725
+ let regexStr = "^";
4726
+ for (let i = 0; i < expanded.length; i++) {
4727
+ const char = expanded[i];
4728
+ switch (char) {
4729
+ case ".":
4730
+ regexStr += "\\.";
4731
+ break;
4732
+ case "*":
4733
+ regexStr += ".*";
4734
+ break;
4735
+ case "?":
4736
+ regexStr += ".";
4737
+ break;
4738
+ case "+":
4739
+ case "^":
4740
+ case "$":
4741
+ case "|":
4742
+ case "(":
4743
+ case ")":
4744
+ case "[":
4745
+ case "]":
4746
+ case "{":
4747
+ case "}":
4748
+ case "\\":
4749
+ regexStr += "\\" + char;
4750
+ break;
4751
+ default:
4752
+ regexStr += char;
4753
+ }
4754
+ }
4755
+ regexStr += "$";
4756
+ return new RegExp(regexStr);
4757
+ }
4758
+ function matchesPattern(relativePath2, pattern) {
4759
+ const openBraceIndex = pattern.indexOf("{");
4760
+ if (openBraceIndex !== -1) {
4761
+ const closeBraceIndex = pattern.indexOf("}", openBraceIndex);
4762
+ if (closeBraceIndex !== -1) {
4763
+ const options = pattern.slice(openBraceIndex + 1, closeBraceIndex).split(",");
4764
+ const before = pattern.slice(0, openBraceIndex);
4765
+ const after = pattern.slice(closeBraceIndex + 1);
4766
+ for (const option of options) {
4767
+ const testPattern2 = before + option + after;
4768
+ if (matchesPattern(relativePath2, testPattern2)) {
4769
+ return true;
4770
+ }
4771
+ }
4772
+ return false;
4773
+ }
4774
+ }
4775
+ const regex = globToRegex2(pattern);
4776
+ return regex.test(relativePath2);
4777
+ }
4778
+ function findTestFiles(root, include, exclude) {
4779
+ const files = [];
4780
+ function normalizePathForPattern(path) {
4781
+ return path.replace(/\\/g, "/");
4782
+ }
4783
+ function scanDir(dir) {
4784
+ try {
4785
+ const entries = readdirSync(dir, { withFileTypes: true });
4786
+ for (const entry of entries) {
4787
+ if (typeof entry === "string") continue;
4788
+ const fullPath = join(dir, entry.name);
4789
+ if (entry.isDirectory()) {
4790
+ const relativePath2 = normalizePathForPattern(relative(root, fullPath));
4791
+ if (exclude.some((pattern) => matchesPattern(relativePath2, pattern))) {
4792
+ continue;
4793
+ }
4794
+ scanDir(fullPath);
4795
+ } else if (entry.isFile()) {
4796
+ const relativePath2 = normalizePathForPattern(relative(root, fullPath));
4797
+ if (exclude.some((pattern) => matchesPattern(relativePath2, pattern))) {
4798
+ continue;
4799
+ }
4800
+ for (const pattern of include) {
4801
+ if (matchesPattern(relativePath2, pattern)) {
4802
+ files.push(fullPath);
4803
+ break;
4804
+ }
4805
+ }
4806
+ }
4807
+ }
4808
+ } catch (error) {
4809
+ }
4810
+ }
4811
+ scanDir(root);
4812
+ return files;
4813
+ }
4814
+ async function runJestTests(options = {}) {
4815
+ const {
4816
+ include = ["**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}"],
4817
+ exclude = ["**/node_modules/**", "**/dist/**", "**/coverage/**", "**/.elit-tests-temp/**"],
4818
+ reporter = "default",
4819
+ timeout = 5e3,
4820
+ bail = false,
4821
+ globals: globals2 = true
4822
+ } = options;
4823
+ const root = process.cwd();
4824
+ const files = options.files || findTestFiles(root, include, exclude);
4825
+ if (files.length === 0) {
4826
+ console.log("\n No test files found\n");
4827
+ return {
4828
+ success: true,
4829
+ passed: 0,
4830
+ failed: 0,
4831
+ total: 0
4832
+ };
4833
+ }
4834
+ if (globals2) {
4835
+ setupGlobals();
4836
+ }
4837
+ let testReporter;
4838
+ switch (reporter) {
4839
+ case "dot":
4840
+ testReporter = new DotReporter();
4841
+ break;
4842
+ case "json":
4843
+ testReporter = new JsonReporter();
4844
+ break;
4845
+ case "verbose":
4846
+ testReporter = new VerboseReporter();
4847
+ break;
4848
+ default:
4849
+ testReporter = new TestReporter({ colors: true });
4850
+ }
4851
+ if ("onRunStart" in testReporter) {
4852
+ testReporter.onRunStart(files);
4853
+ }
4854
+ resetCoveredFiles();
4855
+ const results = await runTests({
4856
+ files,
4857
+ timeout,
4858
+ bail,
4859
+ describePattern: options.describePattern,
4860
+ testPattern: options.testPattern
4861
+ });
4862
+ if ("onTestResult" in testReporter) {
4863
+ for (const result of results.results) {
4864
+ testReporter.onTestResult(result);
4865
+ }
4866
+ }
4867
+ if ("onRunEnd" in testReporter) {
4868
+ testReporter.onRunEnd(results.results);
4869
+ }
4870
+ if (globals2) {
4871
+ clearGlobals();
4872
+ }
4873
+ if (options.coverage?.enabled) {
4874
+ await generateCoverage(options.coverage, results.results);
4875
+ }
4876
+ return {
4877
+ success: results.failed === 0,
4878
+ passed: results.passed,
4879
+ failed: results.failed,
4880
+ total: results.passed + results.failed + results.skipped + results.todo
4881
+ };
4882
+ }
4883
+ async function generateCoverage(options, testResults2) {
4884
+ const { processCoverage: processCoverage2, generateTextReport: generateTextReport2, generateHtmlReport: generateHtmlReport2, generateCoverageFinalJson: generateCoverageFinalJson2, generateCloverXml: generateCloverXml2 } = await Promise.resolve().then(() => (init_coverage(), coverage_exports));
4885
+ const coveredFilesForCoverage = getCoveredFiles();
4886
+ const coverageMap = await processCoverage2({
4887
+ reportsDirectory: "./coverage",
4888
+ include: options.include || ["**/*.ts", "**/*.js"],
4889
+ exclude: options.exclude || ["**/*.test.ts", "**/*.spec.ts", "**/node_modules/**"],
4890
+ reporter: options.reporter || ["text", "html"],
4891
+ coveredFiles: coveredFilesForCoverage
4892
+ });
4893
+ const reporters = options.reporter || ["text", "html"];
4894
+ if (reporters.includes("text")) {
4895
+ console.log("\n" + generateTextReport2(coverageMap, testResults2));
4896
+ }
4897
+ if (reporters.includes("html")) {
4898
+ generateHtmlReport2(coverageMap, "./coverage");
4899
+ console.log(`
4900
+ Coverage report: coverage/index.html
4901
+ `);
4902
+ }
4903
+ if (reporters.includes("coverage-final.json")) {
4904
+ generateCoverageFinalJson2(coverageMap, "./coverage");
4905
+ console.log(`
4906
+ Coverage report: coverage/coverage-final.json
4907
+ `);
4908
+ }
4909
+ if (reporters.includes("clover")) {
4910
+ generateCloverXml2(coverageMap, "./coverage");
4911
+ console.log(`
4912
+ Coverage report: coverage/clover.xml
4913
+ `);
4914
+ }
4915
+ }
4916
+ async function runWatchMode(options = {}) {
4917
+ const chokidar = await Promise.resolve().then(() => (init_esm2(), esm_exports));
4918
+ console.log("\n \uFFFD watch mode - files will be re-run on change\n");
4919
+ let isRunning = false;
4920
+ let needsRerun = false;
4921
+ const runTests2 = async () => {
4922
+ if (isRunning) {
4923
+ needsRerun = true;
4924
+ return;
4925
+ }
4926
+ isRunning = true;
4927
+ needsRerun = false;
4928
+ console.clear();
4929
+ await runJestTests(options);
4930
+ isRunning = false;
4931
+ if (needsRerun) {
4932
+ await runTests2();
4933
+ }
4934
+ };
4935
+ await runTests2();
4936
+ const { include, exclude } = options;
4937
+ const watchPatterns = include || ["**/*.test.ts", "**/*.test.js", "**/*.spec.ts", "**/*.spec.js"];
4938
+ const ignoredPatterns = exclude || ["**/node_modules/**", "**/dist/**", "**/coverage/**"];
4939
+ const watcher = chokidar.default.watch(watchPatterns, {
4940
+ ignored: ignoredPatterns,
4941
+ persistent: true
4942
+ });
4943
+ watcher.on("change", async (path) => {
4944
+ console.log(`
4945
+ \u{1F4C4} ${path} changed
4946
+ `);
4947
+ await runTests2();
4948
+ });
4949
+ watcher.on("add", async (path) => {
4950
+ console.log(`
4951
+ \u{1F4C4} ${path} added
4952
+ `);
4953
+ await runTests2();
4954
+ });
4955
+ }
4956
+ // Annotate the CommonJS export names for ESM import in node:
4957
+ 0 && (module.exports = {
4958
+ runJestTests,
4959
+ runWatchMode
4960
+ });
4961
+ /*! Bundled license information:
4962
+
4963
+ chokidar/esm/index.js:
4964
+ (*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) *)
4965
+ */
4966
+ //# sourceMappingURL=test.js.map