ortoni-report 4.0.0 → 4.0.1-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,744 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
4
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
5
+ }) : x)(function(x) {
6
+ if (typeof require !== "undefined") return require.apply(this, arguments);
7
+ throw Error('Dynamic require of "' + x + '" is not supported');
8
+ });
9
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
10
+
11
+ // src/utils/utils.ts
12
+ import path from "path";
13
+ function normalizeFilePath(filePath) {
14
+ const normalizedPath = path.normalize(filePath);
15
+ return path.basename(normalizedPath);
16
+ }
17
+ function ensureHtmlExtension(filename) {
18
+ const ext = path.extname(filename);
19
+ if (ext && ext.toLowerCase() === ".html") {
20
+ return filename;
21
+ }
22
+ return `${filename}.html`;
23
+ }
24
+ function escapeHtml(unsafe) {
25
+ if (typeof unsafe !== "string") {
26
+ return String(unsafe);
27
+ }
28
+ return unsafe.replace(/[&<"']/g, function(match) {
29
+ const escapeMap = {
30
+ "&": "&amp;",
31
+ "<": "&lt;",
32
+ ">": "&gt;",
33
+ '"': "&quot;",
34
+ "'": "&#039;"
35
+ };
36
+ return escapeMap[match] || match;
37
+ });
38
+ }
39
+ function formatDateLocal(dateInput) {
40
+ const date = typeof dateInput === "string" ? new Date(dateInput) : dateInput;
41
+ const options = {
42
+ year: "numeric",
43
+ month: "short",
44
+ day: "2-digit",
45
+ hour: "2-digit",
46
+ minute: "2-digit",
47
+ hour12: true,
48
+ timeZoneName: "short"
49
+ // or "Asia/Kolkata"
50
+ };
51
+ return new Intl.DateTimeFormat(void 0, options).format(date);
52
+ }
53
+ function extractSuites(titlePath) {
54
+ const tagPattern = /@[\w]+/g;
55
+ const suiteParts = titlePath.slice(3, titlePath.length - 1).map((p) => p.replace(tagPattern, "").trim());
56
+ return {
57
+ hierarchy: suiteParts.join(" > "),
58
+ // full hierarchy
59
+ topLevelSuite: suiteParts[0] ?? "",
60
+ // first suite
61
+ parentSuite: suiteParts[suiteParts.length - 1] ?? ""
62
+ // last suite
63
+ };
64
+ }
65
+
66
+ // src/helpers/databaseManager.ts
67
+ import { open } from "sqlite";
68
+ import sqlite3 from "sqlite3";
69
+ var DatabaseManager = class {
70
+ constructor() {
71
+ this.db = null;
72
+ }
73
+ async initialize(dbPath) {
74
+ try {
75
+ this.db = await open({
76
+ filename: dbPath,
77
+ driver: sqlite3.Database
78
+ });
79
+ await this.createTables();
80
+ await this.createIndexes();
81
+ } catch (error) {
82
+ console.error("OrtoniReport: Error initializing database:", error);
83
+ }
84
+ }
85
+ async createTables() {
86
+ if (!this.db) {
87
+ console.error("OrtoniReport: Database not initialized");
88
+ return;
89
+ }
90
+ try {
91
+ await this.db.exec(`
92
+ CREATE TABLE IF NOT EXISTS test_runs (
93
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
94
+ run_date TEXT
95
+ );
96
+
97
+ CREATE TABLE IF NOT EXISTS test_results (
98
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
99
+ run_id INTEGER,
100
+ test_id TEXT,
101
+ status TEXT,
102
+ duration INTEGER, -- store duration as raw ms
103
+ error_message TEXT,
104
+ FOREIGN KEY (run_id) REFERENCES test_runs (id)
105
+ );
106
+ `);
107
+ } catch (error) {
108
+ console.error("OrtoniReport: Error creating tables:", error);
109
+ }
110
+ }
111
+ async createIndexes() {
112
+ if (!this.db) {
113
+ console.error("OrtoniReport: Database not initialized");
114
+ return;
115
+ }
116
+ try {
117
+ await this.db.exec(`
118
+ CREATE INDEX IF NOT EXISTS idx_test_id ON test_results (test_id);
119
+ CREATE INDEX IF NOT EXISTS idx_run_id ON test_results (run_id);
120
+ `);
121
+ } catch (error) {
122
+ console.error("OrtoniReport: Error creating indexes:", error);
123
+ }
124
+ }
125
+ async saveTestRun() {
126
+ if (!this.db) {
127
+ console.error("OrtoniReport: Database not initialized");
128
+ return null;
129
+ }
130
+ try {
131
+ const runDate = (/* @__PURE__ */ new Date()).toISOString();
132
+ const { lastID } = await this.db.run(
133
+ `
134
+ INSERT INTO test_runs (run_date)
135
+ VALUES (?)
136
+ `,
137
+ [runDate]
138
+ );
139
+ return lastID;
140
+ } catch (error) {
141
+ console.error("OrtoniReport: Error saving test run:", error);
142
+ return null;
143
+ }
144
+ }
145
+ async saveTestResults(runId, results) {
146
+ if (!this.db) {
147
+ console.error("OrtoniReport: Database not initialized");
148
+ return;
149
+ }
150
+ try {
151
+ await this.db.exec("BEGIN TRANSACTION;");
152
+ const stmt = await this.db.prepare(`
153
+ INSERT INTO test_results (run_id, test_id, status, duration, error_message)
154
+ VALUES (?, ?, ?, ?, ?)
155
+ `);
156
+ for (const result of results) {
157
+ await stmt.run([
158
+ runId,
159
+ `${result.filePath}:${result.projectName}:${result.title}`,
160
+ result.status,
161
+ result.duration,
162
+ // store raw ms
163
+ result.errors.join("\n")
164
+ ]);
165
+ }
166
+ await stmt.finalize();
167
+ await this.db.exec("COMMIT;");
168
+ } catch (error) {
169
+ await this.db.exec("ROLLBACK;");
170
+ console.error("OrtoniReport: Error saving test results:", error);
171
+ }
172
+ }
173
+ async getTestHistory(testId, limit = 10) {
174
+ if (!this.db) {
175
+ console.error("OrtoniReport: Database not initialized");
176
+ return [];
177
+ }
178
+ try {
179
+ const results = await this.db.all(
180
+ `
181
+ SELECT tr.status, tr.duration, tr.error_message, trun.run_date
182
+ FROM test_results tr
183
+ JOIN test_runs trun ON tr.run_id = trun.id
184
+ WHERE tr.test_id = ?
185
+ ORDER BY trun.run_date DESC
186
+ LIMIT ?
187
+ `,
188
+ [testId, limit]
189
+ );
190
+ return results.map((result) => ({
191
+ ...result,
192
+ run_date: formatDateLocal(result.run_date)
193
+ }));
194
+ } catch (error) {
195
+ console.error("OrtoniReport: Error getting test history:", error);
196
+ return [];
197
+ }
198
+ }
199
+ async close() {
200
+ if (this.db) {
201
+ try {
202
+ await this.db.close();
203
+ } catch (error) {
204
+ console.error("OrtoniReport: Error closing database:", error);
205
+ } finally {
206
+ this.db = null;
207
+ }
208
+ }
209
+ }
210
+ async getSummaryData() {
211
+ if (!this.db) {
212
+ console.error("OrtoniReport: Database not initialized");
213
+ return {
214
+ totalRuns: 0,
215
+ totalTests: 0,
216
+ passed: 0,
217
+ failed: 0,
218
+ passRate: 0,
219
+ avgDuration: 0
220
+ };
221
+ }
222
+ try {
223
+ const summary = await this.db.get(`
224
+ SELECT
225
+ (SELECT COUNT(*) FROM test_runs) as totalRuns,
226
+ (SELECT COUNT(*) FROM test_results) as totalTests,
227
+ (SELECT COUNT(*) FROM test_results WHERE status = 'passed') as passed,
228
+ (SELECT COUNT(*) FROM test_results WHERE status = 'failed') as failed,
229
+ (SELECT AVG(duration) FROM test_results) as avgDuration
230
+ `);
231
+ const passRate = summary.totalTests ? (summary.passed / summary.totalTests * 100).toFixed(2) : 0;
232
+ return {
233
+ totalRuns: summary.totalRuns,
234
+ totalTests: summary.totalTests,
235
+ passed: summary.passed,
236
+ failed: summary.failed,
237
+ passRate: parseFloat(passRate.toString()),
238
+ avgDuration: Math.round(summary.avgDuration || 0)
239
+ // raw ms avg
240
+ };
241
+ } catch (error) {
242
+ console.error("OrtoniReport: Error getting summary data:", error);
243
+ return {
244
+ totalRuns: 0,
245
+ totalTests: 0,
246
+ passed: 0,
247
+ failed: 0,
248
+ passRate: 0,
249
+ avgDuration: 0
250
+ };
251
+ }
252
+ }
253
+ async getTrends(limit = 100) {
254
+ if (!this.db) {
255
+ console.error("OrtoniReport: Database not initialized");
256
+ return [];
257
+ }
258
+ try {
259
+ const rows = await this.db.all(
260
+ `
261
+ SELECT trun.run_date,
262
+ SUM(CASE WHEN tr.status = 'passed' THEN 1 ELSE 0 END) AS passed,
263
+ SUM(CASE WHEN tr.status = 'failed' THEN 1 ELSE 0 END) AS failed,
264
+ AVG(tr.duration) AS avg_duration
265
+ FROM test_results tr
266
+ JOIN test_runs trun ON tr.run_id = trun.id
267
+ GROUP BY trun.run_date
268
+ ORDER BY trun.run_date DESC
269
+ LIMIT ?
270
+ `,
271
+ [limit]
272
+ );
273
+ return rows.reverse().map((row) => ({
274
+ ...row,
275
+ run_date: formatDateLocal(row.run_date),
276
+ avg_duration: Math.round(row.avg_duration || 0)
277
+ // raw ms avg
278
+ }));
279
+ } catch (error) {
280
+ console.error("OrtoniReport: Error getting trends data:", error);
281
+ return [];
282
+ }
283
+ }
284
+ async getFlakyTests(limit = 10) {
285
+ if (!this.db) {
286
+ console.error("OrtoniReport: Database not initialized");
287
+ return [];
288
+ }
289
+ try {
290
+ return await this.db.all(
291
+ `
292
+ SELECT
293
+ test_id,
294
+ COUNT(*) AS total,
295
+ SUM(CASE WHEN status = 'flaky' THEN 1 ELSE 0 END) AS flaky,
296
+ AVG(duration) AS avg_duration
297
+ FROM test_results
298
+ GROUP BY test_id
299
+ HAVING flaky > 0
300
+ ORDER BY flaky DESC
301
+ LIMIT ?
302
+ `,
303
+ [limit]
304
+ );
305
+ } catch (error) {
306
+ console.error("OrtoniReport: Error getting flaky tests:", error);
307
+ return [];
308
+ }
309
+ }
310
+ async getSlowTests(limit = 10) {
311
+ if (!this.db) {
312
+ console.error("OrtoniReport: Database not initialized");
313
+ return [];
314
+ }
315
+ try {
316
+ const rows = await this.db.all(
317
+ `
318
+ SELECT
319
+ test_id,
320
+ AVG(duration) AS avg_duration
321
+ FROM test_results
322
+ GROUP BY test_id
323
+ ORDER BY avg_duration DESC
324
+ LIMIT ?
325
+ `,
326
+ [limit]
327
+ );
328
+ return rows.map((row) => ({
329
+ test_id: row.test_id,
330
+ avg_duration: Math.round(row.avg_duration || 0)
331
+ // raw ms avg
332
+ }));
333
+ } catch (error) {
334
+ console.error("OrtoniReport: Error getting slow tests:", error);
335
+ return [];
336
+ }
337
+ }
338
+ };
339
+
340
+ // src/utils/groupProjects.ts
341
+ function groupResults(config, results) {
342
+ if (config.showProject) {
343
+ const groupedResults = results.reduce((acc, result, index) => {
344
+ const testId = `${result.filePath}:${result.projectName}:${result.title}`;
345
+ const key = `${testId}-${result.key}-${result.retryAttemptCount}`;
346
+ const { filePath, suite, projectName } = result;
347
+ acc[filePath] = acc[filePath] || {};
348
+ acc[filePath][suite] = acc[filePath][suite] || {};
349
+ acc[filePath][suite][projectName] = acc[filePath][suite][projectName] || [];
350
+ acc[filePath][suite][projectName].push({ ...result, index, testId, key });
351
+ return acc;
352
+ }, {});
353
+ return groupedResults;
354
+ } else {
355
+ const groupedResults = results.reduce((acc, result, index) => {
356
+ const testId = `${result.filePath}:${result.projectName}:${result.title}`;
357
+ const key = `${testId}-${result.key}-${result.retryAttemptCount}`;
358
+ const { filePath, suite } = result;
359
+ acc[filePath] = acc[filePath] || {};
360
+ acc[filePath][suite] = acc[filePath][suite] || [];
361
+ acc[filePath][suite].push({ ...result, index, testId, key });
362
+ return acc;
363
+ }, {});
364
+ return groupedResults;
365
+ }
366
+ }
367
+
368
+ // src/helpers/HTMLGenerator.ts
369
+ var HTMLGenerator = class {
370
+ constructor(ortoniConfig, dbManager) {
371
+ this.ortoniConfig = ortoniConfig;
372
+ this.dbManager = dbManager;
373
+ }
374
+ async generateFinalReport(filteredResults, totalDuration, results, projectSet) {
375
+ const data = await this.prepareReportData(
376
+ filteredResults,
377
+ totalDuration,
378
+ results,
379
+ projectSet
380
+ );
381
+ return data;
382
+ }
383
+ /**
384
+ * Return safe analytics/report data.
385
+ * If no dbManager is provided, return empty defaults and a note explaining why.
386
+ */
387
+ async getReportData() {
388
+ if (!this.dbManager) {
389
+ return {
390
+ summary: {},
391
+ trends: {},
392
+ flakyTests: [],
393
+ slowTests: [],
394
+ note: "Test history/trends are unavailable (saveHistory disabled or DB not initialized)."
395
+ };
396
+ }
397
+ try {
398
+ const [summary, trends, flakyTests, slowTests] = await Promise.all([
399
+ this.dbManager.getSummaryData ? this.dbManager.getSummaryData() : Promise.resolve({}),
400
+ this.dbManager.getTrends ? this.dbManager.getTrends() : Promise.resolve({}),
401
+ this.dbManager.getFlakyTests ? this.dbManager.getFlakyTests() : Promise.resolve([]),
402
+ this.dbManager.getSlowTests ? this.dbManager.getSlowTests() : Promise.resolve([])
403
+ ]);
404
+ return {
405
+ summary: summary ?? {},
406
+ trends: trends ?? {},
407
+ flakyTests: flakyTests ?? [],
408
+ slowTests: slowTests ?? []
409
+ };
410
+ } catch (err) {
411
+ console.warn(
412
+ "HTMLGenerator: failed to read analytics from DB, continuing without history.",
413
+ err
414
+ );
415
+ return {
416
+ summary: {},
417
+ trends: {},
418
+ flakyTests: [],
419
+ slowTests: [],
420
+ note: "Test history/trends could not be loaded due to a DB error."
421
+ };
422
+ }
423
+ }
424
+ async prepareReportData(filteredResults, totalDuration, results, projectSet) {
425
+ const totalTests = filteredResults.length;
426
+ const passedTests = results.filter((r) => r.status === "passed").length;
427
+ const flakyTests = results.filter((r) => r.status === "flaky").length;
428
+ const failed = filteredResults.filter(
429
+ (r) => r.status === "failed" || r.status === "timedOut"
430
+ ).length;
431
+ const successRate = totalTests === 0 ? "0.00" : ((passedTests + flakyTests) / totalTests * 100).toFixed(2);
432
+ const allTags = /* @__PURE__ */ new Set();
433
+ results.forEach(
434
+ (result) => (result.testTags || []).forEach((tag) => allTags.add(tag))
435
+ );
436
+ const projectResults = this.calculateProjectResults(
437
+ filteredResults,
438
+ results,
439
+ projectSet
440
+ );
441
+ const lastRunDate = (/* @__PURE__ */ new Date()).toLocaleString();
442
+ const testHistories = await Promise.all(
443
+ results.map(async (result) => {
444
+ const testId = `${result.filePath}:${result.projectName}:${result.title}`;
445
+ if (!this.dbManager || !this.dbManager.getTestHistory) {
446
+ return {
447
+ testId,
448
+ history: []
449
+ };
450
+ }
451
+ try {
452
+ const history = await this.dbManager.getTestHistory(testId);
453
+ return {
454
+ testId,
455
+ history: history ?? []
456
+ };
457
+ } catch (err) {
458
+ console.warn(
459
+ `HTMLGenerator: failed to read history for ${testId}`,
460
+ err
461
+ );
462
+ return {
463
+ testId,
464
+ history: []
465
+ };
466
+ }
467
+ })
468
+ );
469
+ const reportData = await this.getReportData();
470
+ return {
471
+ summary: {
472
+ overAllResult: {
473
+ pass: passedTests,
474
+ fail: failed,
475
+ skip: results.filter((r) => r.status === "skipped").length,
476
+ retry: results.filter((r) => r.retryAttemptCount).length,
477
+ flaky: flakyTests,
478
+ total: filteredResults.length
479
+ },
480
+ successRate,
481
+ lastRunDate,
482
+ totalDuration,
483
+ stats: this.extractProjectStats(projectResults)
484
+ },
485
+ testResult: {
486
+ tests: groupResults(this.ortoniConfig, results),
487
+ testHistories,
488
+ allTags: Array.from(allTags),
489
+ set: projectSet
490
+ },
491
+ userConfig: {
492
+ projectName: this.ortoniConfig.projectName,
493
+ authorName: this.ortoniConfig.authorName,
494
+ type: this.ortoniConfig.testType,
495
+ title: this.ortoniConfig.title
496
+ },
497
+ userMeta: {
498
+ meta: this.ortoniConfig.meta
499
+ },
500
+ preferences: {
501
+ logo: this.ortoniConfig.logo || void 0,
502
+ showProject: this.ortoniConfig.showProject || false
503
+ },
504
+ analytics: {
505
+ reportData
506
+ }
507
+ };
508
+ }
509
+ calculateProjectResults(filteredResults, results, projectSet) {
510
+ return Array.from(projectSet).map((projectName) => {
511
+ const projectTests = filteredResults.filter(
512
+ (r) => r.projectName === projectName
513
+ );
514
+ const allProjectTests = results.filter(
515
+ (r) => r.projectName === projectName
516
+ );
517
+ return {
518
+ projectName,
519
+ passedTests: projectTests.filter((r) => r.status === "passed").length,
520
+ failedTests: projectTests.filter(
521
+ (r) => r.status === "failed" || r.status === "timedOut"
522
+ ).length,
523
+ skippedTests: allProjectTests.filter((r) => r.status === "skipped").length,
524
+ retryTests: allProjectTests.filter((r) => r.retryAttemptCount).length,
525
+ flakyTests: allProjectTests.filter((r) => r.status === "flaky").length,
526
+ totalTests: projectTests.length
527
+ };
528
+ });
529
+ }
530
+ extractProjectStats(projectResults) {
531
+ return {
532
+ projectNames: projectResults.map((result) => result.projectName),
533
+ totalTests: projectResults.map((result) => result.totalTests),
534
+ passedTests: projectResults.map((result) => result.passedTests),
535
+ failedTests: projectResults.map((result) => result.failedTests),
536
+ skippedTests: projectResults.map((result) => result.skippedTests),
537
+ retryTests: projectResults.map((result) => result.retryTests),
538
+ flakyTests: projectResults.map((result) => result.flakyTests)
539
+ };
540
+ }
541
+ };
542
+
543
+ // src/helpers/fileManager.ts
544
+ import fs2 from "fs";
545
+ import path3 from "path";
546
+
547
+ // src/helpers/templateLoader.ts
548
+ import fs from "fs";
549
+ import path2 from "path";
550
+ async function readBundledTemplate(pkgName = "ortoni-report") {
551
+ const packagedRel = "dist/index.html";
552
+ try {
553
+ if (typeof __require === "function") {
554
+ const resolved = __require.resolve(`${pkgName}/${packagedRel}`);
555
+ if (fs.existsSync(resolved)) {
556
+ return fs.readFileSync(resolved, "utf-8");
557
+ }
558
+ }
559
+ } catch {
560
+ }
561
+ try {
562
+ const moduleNS = await import("module");
563
+ if (moduleNS && typeof moduleNS.createRequire === "function") {
564
+ const createRequire = moduleNS.createRequire;
565
+ const req = createRequire(
566
+ // @ts-ignore
567
+ typeof __filename !== "undefined" ? __filename : import.meta.url
568
+ );
569
+ const resolved = req.resolve(`${pkgName}/${packagedRel}`);
570
+ if (fs.existsSync(resolved)) {
571
+ return fs.readFileSync(resolved, "utf-8");
572
+ }
573
+ }
574
+ } catch {
575
+ }
576
+ try {
577
+ const here = path2.resolve(__dirname, "../dist/index.html");
578
+ if (fs.existsSync(here)) return fs.readFileSync(here, "utf-8");
579
+ } catch {
580
+ }
581
+ try {
582
+ const nm = path2.join(process.cwd(), "node_modules", pkgName, packagedRel);
583
+ if (fs.existsSync(nm)) return fs.readFileSync(nm, "utf-8");
584
+ } catch {
585
+ }
586
+ try {
587
+ const alt = path2.join(process.cwd(), "dist", "index.html");
588
+ if (fs.existsSync(alt)) return fs.readFileSync(alt, "utf-8");
589
+ } catch {
590
+ }
591
+ throw new Error(
592
+ `ortoni-report template not found (tried:
593
+ - require.resolve('${pkgName}/${packagedRel}')
594
+ - import('module').createRequire(...).resolve('${pkgName}/${packagedRel}')
595
+ - relative ../dist/index.html
596
+ - ${path2.join(
597
+ process.cwd(),
598
+ "node_modules",
599
+ pkgName,
600
+ packagedRel
601
+ )}
602
+ - ${path2.join(process.cwd(), "dist", "index.html")}
603
+ Ensure 'dist/index.html' is present in the published package and package.json 'files' includes 'dist/'.`
604
+ );
605
+ }
606
+
607
+ // src/helpers/fileManager.ts
608
+ var FileManager = class {
609
+ constructor(folderPath) {
610
+ this.folderPath = folderPath;
611
+ }
612
+ ensureReportDirectory() {
613
+ const ortoniDataFolder = path3.join(this.folderPath, "ortoni-data");
614
+ if (!fs2.existsSync(this.folderPath)) {
615
+ fs2.mkdirSync(this.folderPath, { recursive: true });
616
+ } else {
617
+ if (fs2.existsSync(ortoniDataFolder)) {
618
+ fs2.rmSync(ortoniDataFolder, { recursive: true, force: true });
619
+ }
620
+ }
621
+ }
622
+ async writeReportFile(filename, data) {
623
+ let html = await readBundledTemplate();
624
+ const reportJSON = JSON.stringify({
625
+ data
626
+ });
627
+ html = html.replace("__ORTONI_TEST_REPORTDATA__", reportJSON);
628
+ const outputPath = path3.join(process.cwd(), this.folderPath, filename);
629
+ fs2.writeFileSync(outputPath, html);
630
+ return outputPath;
631
+ }
632
+ writeRawFile(filename, data) {
633
+ const outputPath = path3.join(process.cwd(), this.folderPath, filename);
634
+ fs2.mkdirSync(path3.dirname(outputPath), { recursive: true });
635
+ const content = typeof data === "string" ? data : JSON.stringify(data, null, 2);
636
+ fs2.writeFileSync(outputPath, content, "utf-8");
637
+ return outputPath;
638
+ }
639
+ copyTraceViewerAssets(skip) {
640
+ if (skip) return;
641
+ const traceViewerFolder = path3.join(
642
+ __require.resolve("playwright-core"),
643
+ "..",
644
+ "lib",
645
+ "vite",
646
+ "traceViewer"
647
+ );
648
+ const traceViewerTargetFolder = path3.join(this.folderPath, "trace");
649
+ const traceViewerAssetsTargetFolder = path3.join(
650
+ traceViewerTargetFolder,
651
+ "assets"
652
+ );
653
+ fs2.mkdirSync(traceViewerAssetsTargetFolder, { recursive: true });
654
+ for (const file of fs2.readdirSync(traceViewerFolder)) {
655
+ if (file.endsWith(".map") || file.includes("watch") || file.includes("assets"))
656
+ continue;
657
+ fs2.copyFileSync(
658
+ path3.join(traceViewerFolder, file),
659
+ path3.join(traceViewerTargetFolder, file)
660
+ );
661
+ }
662
+ const assetsFolder = path3.join(traceViewerFolder, "assets");
663
+ for (const file of fs2.readdirSync(assetsFolder)) {
664
+ if (file.endsWith(".map") || file.includes("xtermModule")) continue;
665
+ fs2.copyFileSync(
666
+ path3.join(assetsFolder, file),
667
+ path3.join(traceViewerAssetsTargetFolder, file)
668
+ );
669
+ }
670
+ }
671
+ };
672
+
673
+ // src/utils/expressServer.ts
674
+ import express from "express";
675
+ import path4 from "path";
676
+ import { spawn } from "child_process";
677
+ function startReportServer(reportFolder, reportFilename, port = 2004, open2) {
678
+ const app = express();
679
+ app.use(express.static(reportFolder));
680
+ app.get("/", (_req, res) => {
681
+ try {
682
+ res.sendFile(path4.resolve(reportFolder, reportFilename));
683
+ } catch (error) {
684
+ console.error("Ortoni Report: Error sending report file:", error);
685
+ res.status(500).send("Error loading report");
686
+ }
687
+ });
688
+ try {
689
+ const server = app.listen(port, () => {
690
+ console.log(
691
+ `Server is running at http://localhost:${port}
692
+ Press Ctrl+C to stop.`
693
+ );
694
+ if (open2 === "always" || open2 === "on-failure") {
695
+ try {
696
+ openBrowser(`http://localhost:${port}`);
697
+ } catch (error) {
698
+ console.error("Ortoni Report: Error opening browser:", error);
699
+ }
700
+ }
701
+ });
702
+ server.on("error", (error) => {
703
+ if (error.code === "EADDRINUSE") {
704
+ console.error(
705
+ `Ortoni Report: Port ${port} is already in use. Trying a different port...`
706
+ );
707
+ } else {
708
+ console.error("Ortoni Report: Server error:", error);
709
+ }
710
+ });
711
+ } catch (error) {
712
+ console.error("Ortoni Report: Error starting the server:", error);
713
+ }
714
+ }
715
+ function openBrowser(url) {
716
+ const platform = process.platform;
717
+ let command;
718
+ try {
719
+ if (platform === "win32") {
720
+ command = "cmd";
721
+ spawn(command, ["/c", "start", url]);
722
+ } else if (platform === "darwin") {
723
+ command = "open";
724
+ spawn(command, [url]);
725
+ } else {
726
+ command = "xdg-open";
727
+ spawn(command, [url]);
728
+ }
729
+ } catch (error) {
730
+ console.error("Ortoni Report: Error opening the browser:", error);
731
+ }
732
+ }
733
+
734
+ export {
735
+ __publicField,
736
+ normalizeFilePath,
737
+ ensureHtmlExtension,
738
+ escapeHtml,
739
+ extractSuites,
740
+ DatabaseManager,
741
+ HTMLGenerator,
742
+ FileManager,
743
+ startReportServer
744
+ };