@arghajit/playwright-pulse-report 0.2.1 → 0.2.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,2341 @@
1
+ #!/usr/bin/env node
2
+
3
+ import * as fs from "fs/promises";
4
+ import { readFileSync, existsSync as fsExistsSync } from "fs";
5
+ import path from "path";
6
+ import { fork } from "child_process";
7
+ import { fileURLToPath } from "url";
8
+
9
+ // Use dynamic import for chalk as it's ESM only
10
+ let chalk;
11
+ try {
12
+ chalk = (await import("chalk")).default;
13
+ } catch (e) {
14
+ console.warn("Chalk could not be imported. Using plain console logs.");
15
+ chalk = {
16
+ green: (text) => text,
17
+ red: (text) => text,
18
+ yellow: (text) => text,
19
+ blue: (text) => text,
20
+ bold: (text) => text,
21
+ gray: (text) => text,
22
+ };
23
+ }
24
+ // Default configuration
25
+ const DEFAULT_OUTPUT_DIR = "pulse-report";
26
+ const DEFAULT_JSON_FILE = "playwright-pulse-report.json";
27
+ const DEFAULT_HTML_FILE = "playwright-pulse-report.html";
28
+ // Helper functions
29
+ export function ansiToHtml(text) {
30
+ if (!text) {
31
+ return "";
32
+ }
33
+
34
+ const codes = {
35
+ 0: "color:inherit;font-weight:normal;font-style:normal;text-decoration:none;opacity:1;background-color:inherit;",
36
+ 1: "font-weight:bold",
37
+ 2: "opacity:0.6",
38
+ 3: "font-style:italic",
39
+ 4: "text-decoration:underline",
40
+ 30: "color:#000", // black
41
+ 31: "color:#d00", // red
42
+ 32: "color:#0a0", // green
43
+ 33: "color:#aa0", // yellow
44
+ 34: "color:#00d", // blue
45
+ 35: "color:#a0a", // magenta
46
+ 36: "color:#0aa", // cyan
47
+ 37: "color:#aaa", // light grey
48
+ 39: "color:inherit", // default foreground color
49
+ 40: "background-color:#000", // black background
50
+ 41: "background-color:#d00", // red background
51
+ 42: "background-color:#0a0", // green background
52
+ 43: "background-color:#aa0", // yellow background
53
+ 44: "background-color:#00d", // blue background
54
+ 45: "background-color:#a0a", // magenta background
55
+ 46: "background-color:#0aa", // cyan background
56
+ 47: "background-color:#aaa", // light grey background
57
+ 49: "background-color:inherit", // default background color
58
+ 90: "color:#555", // dark grey
59
+ 91: "color:#f55", // light red
60
+ 92: "color:#5f5", // light green
61
+ 93: "color:#ff5", // light yellow
62
+ 94: "color:#55f", // light blue
63
+ 95: "color:#f5f", // light magenta
64
+ 96: "color:#5ff", // light cyan
65
+ 97: "color:#fff", // white
66
+ };
67
+
68
+ let currentStylesArray = [];
69
+ let html = "";
70
+ let openSpan = false;
71
+
72
+ const applyStyles = () => {
73
+ if (openSpan) {
74
+ html += "</span>";
75
+ openSpan = false;
76
+ }
77
+ if (currentStylesArray.length > 0) {
78
+ const styleString = currentStylesArray.filter((s) => s).join(";");
79
+ if (styleString) {
80
+ html += `<span style="${styleString}">`;
81
+ openSpan = true;
82
+ }
83
+ }
84
+ };
85
+
86
+ const resetAndApplyNewCodes = (newCodesStr) => {
87
+ const newCodes = newCodesStr.split(";");
88
+
89
+ if (newCodes.includes("0")) {
90
+ currentStylesArray = [];
91
+ if (codes["0"]) currentStylesArray.push(codes["0"]);
92
+ }
93
+
94
+ for (const code of newCodes) {
95
+ if (code === "0") continue;
96
+
97
+ if (codes[code]) {
98
+ if (code === "39") {
99
+ currentStylesArray = currentStylesArray.filter(
100
+ (s) => !s.startsWith("color:")
101
+ );
102
+ currentStylesArray.push("color:inherit");
103
+ } else if (code === "49") {
104
+ currentStylesArray = currentStylesArray.filter(
105
+ (s) => !s.startsWith("background-color:")
106
+ );
107
+ currentStylesArray.push("background-color:inherit");
108
+ } else {
109
+ currentStylesArray.push(codes[code]);
110
+ }
111
+ } else if (code.startsWith("38;2;") || code.startsWith("48;2;")) {
112
+ const parts = code.split(";");
113
+ const type = parts[0] === "38" ? "color" : "background-color";
114
+ if (parts.length === 5) {
115
+ currentStylesArray = currentStylesArray.filter(
116
+ (s) => !s.startsWith(type + ":")
117
+ );
118
+ currentStylesArray.push(
119
+ `${type}:rgb(${parts[2]},${parts[3]},${parts[4]})`
120
+ );
121
+ }
122
+ }
123
+ }
124
+ applyStyles();
125
+ };
126
+
127
+ const segments = text.split(/(\x1b\[[0-9;]*m)/g);
128
+
129
+ for (const segment of segments) {
130
+ if (!segment) continue;
131
+
132
+ if (segment.startsWith("\x1b[") && segment.endsWith("m")) {
133
+ const command = segment.slice(2, -1);
134
+ resetAndApplyNewCodes(command);
135
+ } else {
136
+ const escapedContent = segment
137
+ .replace(/&/g, "&amp;")
138
+ .replace(/</g, "&lt;")
139
+ .replace(/>/g, "&gt;")
140
+ .replace(/"/g, "&quot;")
141
+ .replace(/'/g, "&#039;");
142
+ html += escapedContent;
143
+ }
144
+ }
145
+
146
+ if (openSpan) {
147
+ html += "</span>";
148
+ }
149
+
150
+ return html;
151
+ }
152
+ function sanitizeHTML(str) {
153
+ if (str === null || str === undefined) return "";
154
+ return String(str).replace(/[&<>"']/g, (match) => {
155
+ const replacements = {
156
+ "&": "&",
157
+ "<": "<",
158
+ ">": ">",
159
+ '"': '"',
160
+ "'": "'",
161
+ };
162
+ return replacements[match] || match;
163
+ });
164
+ }
165
+ function capitalize(str) {
166
+ if (!str) return "";
167
+ return str[0].toUpperCase() + str.slice(1).toLowerCase();
168
+ }
169
+ function formatPlaywrightError(error) {
170
+ const commandOutput = ansiToHtml(error || error.message);
171
+ return convertPlaywrightErrorToHTML(commandOutput);
172
+ }
173
+ function convertPlaywrightErrorToHTML(str) {
174
+ if (!str) return "";
175
+ return str
176
+ .replace(/^(\s+)/gm, (match) =>
177
+ match.replace(/ /g, " ").replace(/\t/g, " ")
178
+ )
179
+ .replace(/<red>/g, '<span style="color: red;">')
180
+ .replace(/<green>/g, '<span style="color: green;">')
181
+ .replace(/<dim>/g, '<span style="opacity: 0.6;">')
182
+ .replace(/<intensity>/g, '<span style="font-weight: bold;">')
183
+ .replace(/<\/color>/g, "</span>")
184
+ .replace(/<\/intensity>/g, "</span>")
185
+ .replace(/\n/g, "<br>");
186
+ }
187
+ function formatDuration(ms, options = {}) {
188
+ const {
189
+ precision = 1,
190
+ invalidInputReturn = "N/A",
191
+ defaultForNullUndefinedNegative = null,
192
+ } = options;
193
+
194
+ const validPrecision = Math.max(0, Math.floor(precision));
195
+ const zeroWithPrecision = (0).toFixed(validPrecision) + "s";
196
+ const resolvedNullUndefNegReturn =
197
+ defaultForNullUndefinedNegative === null
198
+ ? zeroWithPrecision
199
+ : defaultForNullUndefinedNegative;
200
+
201
+ if (ms === undefined || ms === null) {
202
+ return resolvedNullUndefNegReturn;
203
+ }
204
+
205
+ const numMs = Number(ms);
206
+
207
+ if (Number.isNaN(numMs) || !Number.isFinite(numMs)) {
208
+ return invalidInputReturn;
209
+ }
210
+
211
+ if (numMs < 0) {
212
+ return resolvedNullUndefNegReturn;
213
+ }
214
+
215
+ if (numMs === 0) {
216
+ return zeroWithPrecision;
217
+ }
218
+
219
+ const MS_PER_SECOND = 1000;
220
+ const SECONDS_PER_MINUTE = 60;
221
+ const MINUTES_PER_HOUR = 60;
222
+ const SECONDS_PER_HOUR = SECONDS_PER_MINUTE * MINUTES_PER_HOUR;
223
+
224
+ const totalRawSeconds = numMs / MS_PER_SECOND;
225
+
226
+ if (
227
+ totalRawSeconds < SECONDS_PER_MINUTE &&
228
+ Math.ceil(totalRawSeconds) < SECONDS_PER_MINUTE
229
+ ) {
230
+ return `${totalRawSeconds.toFixed(validPrecision)}s`;
231
+ } else {
232
+ const totalMsRoundedUpToSecond =
233
+ Math.ceil(numMs / MS_PER_SECOND) * MS_PER_SECOND;
234
+
235
+ let remainingMs = totalMsRoundedUpToSecond;
236
+
237
+ const h = Math.floor(remainingMs / (MS_PER_SECOND * SECONDS_PER_HOUR));
238
+ remainingMs %= MS_PER_SECOND * SECONDS_PER_HOUR;
239
+
240
+ const m = Math.floor(remainingMs / (MS_PER_SECOND * SECONDS_PER_MINUTE));
241
+ remainingMs %= MS_PER_SECOND * SECONDS_PER_MINUTE;
242
+
243
+ const s = Math.floor(remainingMs / MS_PER_SECOND);
244
+
245
+ const parts = [];
246
+ if (h > 0) {
247
+ parts.push(`${h}h`);
248
+ }
249
+ if (h > 0 || m > 0 || numMs >= MS_PER_SECOND * SECONDS_PER_MINUTE) {
250
+ parts.push(`${m}m`);
251
+ }
252
+ parts.push(`${s}s`);
253
+
254
+ return parts.join(" ");
255
+ }
256
+ }
257
+ function generateTestTrendsChart(trendData) {
258
+ if (!trendData || !trendData.overall || trendData.overall.length === 0) {
259
+ return '<div class="no-data">No overall trend data available for test counts.</div>';
260
+ }
261
+
262
+ const chartId = `testTrendsChart-${Date.now()}-${Math.random()
263
+ .toString(36)
264
+ .substring(2, 7)}`;
265
+ const renderFunctionName = `renderTestTrendsChart_${chartId.replace(
266
+ /-/g,
267
+ "_"
268
+ )}`;
269
+ const runs = trendData.overall;
270
+
271
+ const series = [
272
+ {
273
+ name: "Total",
274
+ data: runs.map((r) => r.totalTests),
275
+ color: "var(--primary-color)",
276
+ marker: { symbol: "circle" },
277
+ },
278
+ {
279
+ name: "Passed",
280
+ data: runs.map((r) => r.passed),
281
+ color: "var(--success-color)",
282
+ marker: { symbol: "circle" },
283
+ },
284
+ {
285
+ name: "Failed",
286
+ data: runs.map((r) => r.failed),
287
+ color: "var(--danger-color)",
288
+ marker: { symbol: "circle" },
289
+ },
290
+ {
291
+ name: "Skipped",
292
+ data: runs.map((r) => r.skipped || 0),
293
+ color: "var(--warning-color)",
294
+ marker: { symbol: "circle" },
295
+ },
296
+ ];
297
+ const runsForTooltip = runs.map((r) => ({
298
+ runId: r.runId,
299
+ timestamp: r.timestamp,
300
+ duration: r.duration,
301
+ }));
302
+
303
+ const categoriesString = JSON.stringify(runs.map((run, i) => `Run ${i + 1}`));
304
+ const seriesString = JSON.stringify(series);
305
+ const runsForTooltipString = JSON.stringify(runsForTooltip);
306
+
307
+ return `
308
+ <div id="${chartId}" class="trend-chart-container lazy-load-chart" data-render-function-name="${renderFunctionName}">
309
+ <div class="no-data">Loading Test Volume Trends...</div>
310
+ </div>
311
+ <script>
312
+ window.${renderFunctionName} = function() {
313
+ const chartContainer = document.getElementById('${chartId}');
314
+ if (!chartContainer) { console.error("Chart container ${chartId} not found for lazy loading."); return; }
315
+ if (typeof Highcharts !== 'undefined' && typeof formatDuration !== 'undefined') {
316
+ try {
317
+ chartContainer.innerHTML = ''; // Clear placeholder
318
+ const chartOptions = {
319
+ chart: { type: "line", height: 350, backgroundColor: "transparent" },
320
+ title: { text: null },
321
+ xAxis: { categories: ${categoriesString}, crosshair: true, labels: { style: { color: 'var(--text-color-secondary)', fontSize: '12px' }}},
322
+ yAxis: { title: { text: "Test Count", style: { color: 'var(--text-color)'} }, min: 0, labels: { style: { color: 'var(--text-color-secondary)', fontSize: '12px' }}},
323
+ legend: { layout: "horizontal", align: "center", verticalAlign: "bottom", itemStyle: { fontSize: "12px", color: 'var(--text-color)' }},
324
+ plotOptions: { series: { marker: { radius: 4, states: { hover: { radius: 6 }}}, states: { hover: { halo: { size: 5, opacity: 0.1 }}}}, line: { lineWidth: 2.5 }},
325
+ tooltip: {
326
+ shared: true, useHTML: true, backgroundColor: 'rgba(10,10,10,0.92)', borderColor: 'rgba(10,10,10,0.92)', style: { color: '#f5f5f5' },
327
+ formatter: function () {
328
+ const runsData = ${runsForTooltipString};
329
+ const pointIndex = this.points[0].point.x;
330
+ const run = runsData[pointIndex];
331
+ let tooltip = '<strong>Run ' + (run.runId || pointIndex + 1) + '</strong><br>' + 'Date: ' + new Date(run.timestamp).toLocaleString() + '<br><br>';
332
+ this.points.forEach(point => { tooltip += '<span style="color:' + point.color + '">●</span> ' + point.series.name + ': <b>' + point.y + '</b><br>'; });
333
+ tooltip += '<br>Duration: ' + formatDuration(run.duration);
334
+ return tooltip;
335
+ }
336
+ },
337
+ series: ${seriesString},
338
+ credits: { enabled: false }
339
+ };
340
+ Highcharts.chart('${chartId}', chartOptions);
341
+ } catch (e) {
342
+ console.error("Error rendering chart ${chartId} (lazy):", e);
343
+ chartContainer.innerHTML = '<div class="no-data">Error rendering test trends chart.</div>';
344
+ }
345
+ } else {
346
+ chartContainer.innerHTML = '<div class="no-data">Charting library not available for test trends.</div>';
347
+ }
348
+ };
349
+ </script>
350
+ `;
351
+ }
352
+ function generateDurationTrendChart(trendData) {
353
+ if (!trendData || !trendData.overall || trendData.overall.length === 0) {
354
+ return '<div class="no-data">No overall trend data available for durations.</div>';
355
+ }
356
+ const chartId = `durationTrendChart-${Date.now()}-${Math.random()
357
+ .toString(36)
358
+ .substring(2, 7)}`;
359
+ const renderFunctionName = `renderDurationTrendChart_${chartId.replace(
360
+ /-/g,
361
+ "_"
362
+ )}`;
363
+ const runs = trendData.overall;
364
+
365
+ const accentColorAltRGB = "255, 152, 0"; // Assuming var(--accent-color-alt) is Orange #FF9800
366
+
367
+ const chartDataString = JSON.stringify(runs.map((run) => run.duration));
368
+ const categoriesString = JSON.stringify(runs.map((run, i) => `Run ${i + 1}`));
369
+ const runsForTooltip = runs.map((r) => ({
370
+ runId: r.runId,
371
+ timestamp: r.timestamp,
372
+ duration: r.duration,
373
+ totalTests: r.totalTests,
374
+ }));
375
+ const runsForTooltipString = JSON.stringify(runsForTooltip);
376
+
377
+ const seriesStringForRender = `[{
378
+ name: 'Duration',
379
+ data: ${chartDataString},
380
+ color: 'var(--accent-color-alt)',
381
+ type: 'area',
382
+ marker: { symbol: 'circle', enabled: true, radius: 4, states: { hover: { radius: 6, lineWidthPlus: 0 } } },
383
+ fillColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [[0, 'rgba(${accentColorAltRGB}, 0.4)'], [1, 'rgba(${accentColorAltRGB}, 0.05)']] },
384
+ lineWidth: 2.5
385
+ }]`;
386
+
387
+ return `
388
+ <div id="${chartId}" class="trend-chart-container lazy-load-chart" data-render-function-name="${renderFunctionName}">
389
+ <div class="no-data">Loading Duration Trends...</div>
390
+ </div>
391
+ <script>
392
+ window.${renderFunctionName} = function() {
393
+ const chartContainer = document.getElementById('${chartId}');
394
+ if (!chartContainer) { console.error("Chart container ${chartId} not found for lazy loading."); return; }
395
+ if (typeof Highcharts !== 'undefined' && typeof formatDuration !== 'undefined') {
396
+ try {
397
+ chartContainer.innerHTML = ''; // Clear placeholder
398
+ const chartOptions = {
399
+ chart: { type: 'area', height: 350, backgroundColor: 'transparent' },
400
+ title: { text: null },
401
+ xAxis: { categories: ${categoriesString}, crosshair: true, labels: { style: { color: 'var(--text-color-secondary)', fontSize: '12px' }}},
402
+ yAxis: {
403
+ title: { text: 'Duration', style: { color: 'var(--text-color)' } },
404
+ labels: { formatter: function() { return formatDuration(this.value); }, style: { color: 'var(--text-color-secondary)', fontSize: '12px' }},
405
+ min: 0
406
+ },
407
+ legend: { layout: 'horizontal', align: 'center', verticalAlign: 'bottom', itemStyle: { fontSize: '12px', color: 'var(--text-color)' }},
408
+ plotOptions: { area: { lineWidth: 2.5, states: { hover: { lineWidthPlus: 0 } }, threshold: null }},
409
+ tooltip: {
410
+ shared: true, useHTML: true, backgroundColor: 'rgba(10,10,10,0.92)', borderColor: 'rgba(10,10,10,0.92)', style: { color: '#f5f5f5' },
411
+ formatter: function () {
412
+ const runsData = ${runsForTooltipString};
413
+ const pointIndex = this.points[0].point.x;
414
+ const run = runsData[pointIndex];
415
+ let tooltip = '<strong>Run ' + (run.runId || pointIndex + 1) + '</strong><br>' + 'Date: ' + new Date(run.timestamp).toLocaleString() + '<br>';
416
+ this.points.forEach(point => { tooltip += '<span style="color:' + point.series.color + '">●</span> ' + point.series.name + ': <b>' + formatDuration(point.y) + '</b><br>'; });
417
+ tooltip += '<br>Tests: ' + run.totalTests;
418
+ return tooltip;
419
+ }
420
+ },
421
+ series: ${seriesStringForRender}, // This is already a string representation of an array
422
+ credits: { enabled: false }
423
+ };
424
+ Highcharts.chart('${chartId}', chartOptions);
425
+ } catch (e) {
426
+ console.error("Error rendering chart ${chartId} (lazy):", e);
427
+ chartContainer.innerHTML = '<div class="no-data">Error rendering duration trend chart.</div>';
428
+ }
429
+ } else {
430
+ chartContainer.innerHTML = '<div class="no-data">Charting library not available for duration trends.</div>';
431
+ }
432
+ };
433
+ </script>
434
+ `;
435
+ }
436
+ function formatDate(dateStrOrDate) {
437
+ if (!dateStrOrDate) return "N/A";
438
+ try {
439
+ const date = new Date(dateStrOrDate);
440
+ if (isNaN(date.getTime())) return "Invalid Date";
441
+ return (
442
+ date.toLocaleDateString(undefined, {
443
+ year: "2-digit",
444
+ month: "2-digit",
445
+ day: "2-digit",
446
+ }) +
447
+ " " +
448
+ date.toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit" })
449
+ );
450
+ } catch (e) {
451
+ return "Invalid Date Format";
452
+ }
453
+ }
454
+ function generateTestHistoryChart(history) {
455
+ if (!history || history.length === 0)
456
+ return '<div class="no-data-chart">No data for chart</div>';
457
+ const validHistory = history.filter(
458
+ (h) => h && typeof h.duration === "number" && h.duration >= 0
459
+ );
460
+ if (validHistory.length === 0)
461
+ return '<div class="no-data-chart">No valid data for chart</div>';
462
+
463
+ const chartId = `testHistoryChart-${Date.now()}-${Math.random()
464
+ .toString(36)
465
+ .substring(2, 7)}`;
466
+ const renderFunctionName = `renderTestHistoryChart_${chartId.replace(
467
+ /-/g,
468
+ "_"
469
+ )}`;
470
+
471
+ const seriesDataPoints = validHistory.map((run) => {
472
+ let color;
473
+ switch (String(run.status).toLowerCase()) {
474
+ case "passed":
475
+ color = "var(--success-color)";
476
+ break;
477
+ case "failed":
478
+ color = "var(--danger-color)";
479
+ break;
480
+ case "skipped":
481
+ color = "var(--warning-color)";
482
+ break;
483
+ default:
484
+ color = "var(--dark-gray-color)";
485
+ }
486
+ return {
487
+ y: run.duration,
488
+ marker: {
489
+ fillColor: color,
490
+ symbol: "circle",
491
+ radius: 3.5,
492
+ states: { hover: { radius: 5 } },
493
+ },
494
+ status: run.status,
495
+ runId: run.runId,
496
+ };
497
+ });
498
+
499
+ const accentColorRGB = "103, 58, 183"; // Assuming var(--accent-color) is Deep Purple #673ab7
500
+
501
+ const categoriesString = JSON.stringify(
502
+ validHistory.map((_, i) => `R${i + 1}`)
503
+ );
504
+ const seriesDataPointsString = JSON.stringify(seriesDataPoints);
505
+
506
+ return `
507
+ <div id="${chartId}" style="width: 320px; height: 100px;" class="lazy-load-chart" data-render-function-name="${renderFunctionName}">
508
+ <div class="no-data-chart">Loading History...</div>
509
+ </div>
510
+ <script>
511
+ window.${renderFunctionName} = function() {
512
+ const chartContainer = document.getElementById('${chartId}');
513
+ if (!chartContainer) { console.error("Chart container ${chartId} not found for lazy loading."); return; }
514
+ if (typeof Highcharts !== 'undefined' && typeof formatDuration !== 'undefined') {
515
+ try {
516
+ chartContainer.innerHTML = ''; // Clear placeholder
517
+ const chartOptions = {
518
+ chart: { type: 'area', height: 100, width: 320, backgroundColor: 'transparent', spacing: [10,10,15,35] },
519
+ title: { text: null },
520
+ xAxis: { categories: ${categoriesString}, labels: { style: { fontSize: '10px', color: 'var(--text-color-secondary)' }}},
521
+ yAxis: {
522
+ title: { text: null },
523
+ labels: { formatter: function() { return formatDuration(this.value); }, style: { fontSize: '10px', color: 'var(--text-color-secondary)' }, align: 'left', x: -35, y: 3 },
524
+ min: 0, gridLineWidth: 0, tickAmount: 4
525
+ },
526
+ legend: { enabled: false },
527
+ plotOptions: {
528
+ area: {
529
+ lineWidth: 2, lineColor: 'var(--accent-color)',
530
+ fillColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [[0, 'rgba(${accentColorRGB}, 0.4)'],[1, 'rgba(${accentColorRGB}, 0)']]},
531
+ marker: { enabled: true }, threshold: null
532
+ }
533
+ },
534
+ tooltip: {
535
+ useHTML: true, backgroundColor: 'rgba(10,10,10,0.92)', borderColor: 'rgba(10,10,10,0.92)', style: { color: '#f5f5f5', padding: '8px' },
536
+ formatter: function() {
537
+ const pointData = this.point;
538
+ let statusBadgeHtml = '<span style="padding: 2px 5px; border-radius: 3px; font-size: 0.9em; font-weight: 600; color: white; text-transform: uppercase; background-color: ';
539
+ switch(String(pointData.status).toLowerCase()) {
540
+ case 'passed': statusBadgeHtml += 'var(--success-color)'; break;
541
+ case 'failed': statusBadgeHtml += 'var(--danger-color)'; break;
542
+ case 'skipped': statusBadgeHtml += 'var(--warning-color)'; break;
543
+ default: statusBadgeHtml += 'var(--dark-gray-color)';
544
+ }
545
+ statusBadgeHtml += ';">' + String(pointData.status).toUpperCase() + '</span>';
546
+ return '<strong>Run ' + (pointData.runId || (this.point.index + 1)) + '</strong><br>' + 'Status: ' + statusBadgeHtml + '<br>' + 'Duration: ' + formatDuration(pointData.y);
547
+ }
548
+ },
549
+ series: [{ data: ${seriesDataPointsString}, showInLegend: false }],
550
+ credits: { enabled: false }
551
+ };
552
+ Highcharts.chart('${chartId}', chartOptions);
553
+ } catch (e) {
554
+ console.error("Error rendering chart ${chartId} (lazy):", e);
555
+ chartContainer.innerHTML = '<div class="no-data-chart">Error rendering history chart.</div>';
556
+ }
557
+ } else {
558
+ chartContainer.innerHTML = '<div class="no-data-chart">Charting library not available for history.</div>';
559
+ }
560
+ };
561
+ </script>
562
+ `;
563
+ }
564
+ function generatePieChart(data, chartWidth = 300, chartHeight = 300) {
565
+ const total = data.reduce((sum, d) => sum + d.value, 0);
566
+ if (total === 0) {
567
+ return '<div class="pie-chart-wrapper"><h3>Test Distribution</h3><div class="no-data">No data for Test Distribution chart.</div></div>';
568
+ }
569
+ const passedEntry = data.find((d) => d.label === "Passed");
570
+ const passedPercentage = Math.round(
571
+ ((passedEntry ? passedEntry.value : 0) / total) * 100
572
+ );
573
+
574
+ const chartId = `pieChart-${Date.now()}-${Math.random()
575
+ .toString(36)
576
+ .substring(2, 7)}`;
577
+
578
+ const seriesData = [
579
+ {
580
+ name: "Tests", // Changed from 'Test Distribution' for tooltip clarity
581
+ data: data
582
+ .filter((d) => d.value > 0)
583
+ .map((d) => {
584
+ let color;
585
+ switch (d.label) {
586
+ case "Passed":
587
+ color = "var(--success-color)";
588
+ break;
589
+ case "Failed":
590
+ color = "var(--danger-color)";
591
+ break;
592
+ case "Skipped":
593
+ color = "var(--warning-color)";
594
+ break;
595
+ default:
596
+ color = "#CCCCCC"; // A neutral default color
597
+ }
598
+ return { name: d.label, y: d.value, color: color };
599
+ }),
600
+ size: "100%",
601
+ innerSize: "55%",
602
+ dataLabels: { enabled: false },
603
+ showInLegend: true,
604
+ },
605
+ ];
606
+
607
+ // Approximate font size for center text, can be adjusted or made dynamic with more client-side JS
608
+ const centerTitleFontSize =
609
+ Math.max(12, Math.min(chartWidth, chartHeight) / 12) + "px";
610
+ const centerSubtitleFontSize =
611
+ Math.max(10, Math.min(chartWidth, chartHeight) / 18) + "px";
612
+
613
+ const optionsObjectString = `
614
+ {
615
+ chart: {
616
+ type: 'pie',
617
+ width: ${chartWidth},
618
+ height: ${
619
+ chartHeight - 40
620
+ }, // Adjusted height to make space for legend if chartHeight is for the whole wrapper
621
+ backgroundColor: 'transparent',
622
+ plotShadow: false,
623
+ spacingBottom: 40 // Ensure space for legend
624
+ },
625
+ title: {
626
+ text: '${passedPercentage}%',
627
+ align: 'center',
628
+ verticalAlign: 'middle',
629
+ y: 5,
630
+ style: { fontSize: '${centerTitleFontSize}', fontWeight: 'bold', color: 'var(--primary-color)' }
631
+ },
632
+ subtitle: {
633
+ text: 'Passed',
634
+ align: 'center',
635
+ verticalAlign: 'middle',
636
+ y: 25,
637
+ style: { fontSize: '${centerSubtitleFontSize}', color: 'var(--text-color-secondary)' }
638
+ },
639
+ tooltip: {
640
+ pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b> ({point.y})',
641
+ backgroundColor: 'rgba(10,10,10,0.92)',
642
+ borderColor: 'rgba(10,10,10,0.92)',
643
+ style: { color: '#f5f5f5' }
644
+ },
645
+ legend: {
646
+ layout: 'horizontal',
647
+ align: 'center',
648
+ verticalAlign: 'bottom',
649
+ itemStyle: { color: 'var(--text-color)', fontWeight: 'normal', fontSize: '12px' }
650
+ },
651
+ plotOptions: {
652
+ pie: {
653
+ allowPointSelect: true,
654
+ cursor: 'pointer',
655
+ borderWidth: 3,
656
+ borderColor: 'var(--card-background-color)', // Match D3 style
657
+ states: {
658
+ hover: {
659
+ // Using default Highcharts halo which is generally good
660
+ }
661
+ }
662
+ }
663
+ },
664
+ series: ${JSON.stringify(seriesData)},
665
+ credits: { enabled: false }
666
+ }
667
+ `;
668
+
669
+ return `
670
+ <div class="pie-chart-wrapper" style="align-items: center; max-height: 450px">
671
+ <div style="display: flex; align-items: start; width: 100%;"><h3>Test Distribution</h3></div>
672
+ <div id="${chartId}" style="width: ${chartWidth}px; height: ${
673
+ chartHeight - 40
674
+ }px;"></div>
675
+ <script>
676
+ document.addEventListener('DOMContentLoaded', function() {
677
+ if (typeof Highcharts !== 'undefined') {
678
+ try {
679
+ const chartOptions = ${optionsObjectString};
680
+ Highcharts.chart('${chartId}', chartOptions);
681
+ } catch (e) {
682
+ console.error("Error rendering chart ${chartId}:", e);
683
+ document.getElementById('${chartId}').innerHTML = '<div class="no-data">Error rendering pie chart.</div>';
684
+ }
685
+ } else {
686
+ document.getElementById('${chartId}').innerHTML = '<div class="no-data">Charting library not available.</div>';
687
+ }
688
+ });
689
+ </script>
690
+ </div>
691
+ `;
692
+ }
693
+ function generateEnvironmentDashboard(environment, dashboardHeight = 600) {
694
+ // Format memory for display
695
+ const formattedMemory = environment.memory.replace(/(\d+\.\d{2})GB/, "$1 GB");
696
+
697
+ // Generate a unique ID for the dashboard
698
+ const dashboardId = `envDashboard-${Date.now()}-${Math.random()
699
+ .toString(36)
700
+ .substring(2, 7)}`;
701
+
702
+ const cardHeight = Math.floor(dashboardHeight * 0.44);
703
+ const cardContentPadding = 16; // px
704
+
705
+ return `
706
+ <div class="environment-dashboard-wrapper" id="${dashboardId}">
707
+ <style>
708
+ .environment-dashboard-wrapper *,
709
+ .environment-dashboard-wrapper *::before,
710
+ .environment-dashboard-wrapper *::after {
711
+ box-sizing: border-box;
712
+ }
713
+
714
+ .environment-dashboard-wrapper {
715
+ --primary-color: #007bff;
716
+ --primary-light-color: #e6f2ff;
717
+ --secondary-color: #6c757d;
718
+ --success-color: #28a745;
719
+ --success-light-color: #eaf6ec;
720
+ --warning-color: #ffc107;
721
+ --warning-light-color: #fff9e6;
722
+ --danger-color: #dc3545;
723
+
724
+ --background-color: #ffffff;
725
+ --card-background-color: #ffffff;
726
+ --text-color: #212529;
727
+ --text-color-secondary: #6c757d;
728
+ --border-color: #dee2e6;
729
+ --border-light-color: #f1f3f5;
730
+ --icon-color: #495057;
731
+ --chip-background: #e9ecef;
732
+ --chip-text: #495057;
733
+ --shadow-color: rgba(0, 0, 0, 0.075);
734
+
735
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji';
736
+ background-color: var(--background-color);
737
+ border-radius: 12px;
738
+ box-shadow: 0 6px 12px var(--shadow-color);
739
+ padding: 24px;
740
+ color: var(--text-color);
741
+ display: grid;
742
+ grid-template-columns: 1fr 1fr;
743
+ grid-template-rows: auto 1fr;
744
+ gap: 20px;
745
+ font-size: 14px;
746
+ }
747
+
748
+ .env-dashboard-header {
749
+ grid-column: 1 / -1;
750
+ display: flex;
751
+ justify-content: space-between;
752
+ align-items: center;
753
+ border-bottom: 1px solid var(--border-color);
754
+ padding-bottom: 16px;
755
+ margin-bottom: 8px;
756
+ }
757
+
758
+ .env-dashboard-title {
759
+ font-size: 1.5rem;
760
+ font-weight: 600;
761
+ color: var(--text-color);
762
+ margin: 0;
763
+ }
764
+
765
+ .env-dashboard-subtitle {
766
+ font-size: 0.875rem;
767
+ color: var(--text-color-secondary);
768
+ margin-top: 4px;
769
+ }
770
+
771
+ .env-card {
772
+ background-color: var(--card-background-color);
773
+ border-radius: 8px;
774
+ padding: ${cardContentPadding}px;
775
+ box-shadow: 0 3px 6px var(--shadow-color);
776
+ height: ${cardHeight}px;
777
+ display: flex;
778
+ flex-direction: column;
779
+ overflow: hidden;
780
+ }
781
+
782
+ .env-card-header {
783
+ font-weight: 600;
784
+ font-size: 1rem;
785
+ margin-bottom: 12px;
786
+ color: var(--text-color);
787
+ display: flex;
788
+ align-items: center;
789
+ padding-bottom: 8px;
790
+ border-bottom: 1px solid var(--border-light-color);
791
+ }
792
+
793
+ .env-card-header svg {
794
+ margin-right: 10px;
795
+ width: 18px;
796
+ height: 18px;
797
+ fill: var(--icon-color);
798
+ }
799
+
800
+ .env-card-content {
801
+ flex-grow: 1;
802
+ overflow-y: auto;
803
+ padding-right: 5px;
804
+ }
805
+
806
+ .env-detail-row {
807
+ display: flex;
808
+ justify-content: space-between;
809
+ align-items: center;
810
+ padding: 10px 0;
811
+ border-bottom: 1px solid var(--border-light-color);
812
+ font-size: 0.875rem;
813
+ }
814
+
815
+ .env-detail-row:last-child {
816
+ border-bottom: none;
817
+ }
818
+
819
+ .env-detail-label {
820
+ color: var(--text-color-secondary);
821
+ font-weight: 500;
822
+ margin-right: 10px;
823
+ }
824
+
825
+ .env-detail-value {
826
+ color: var(--text-color);
827
+ font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
828
+ text-align: right;
829
+ word-break: break-all;
830
+ }
831
+
832
+ .env-chip {
833
+ display: inline-block;
834
+ padding: 4px 10px;
835
+ border-radius: 16px;
836
+ font-size: 0.75rem;
837
+ font-weight: 500;
838
+ line-height: 1.2;
839
+ background-color: var(--chip-background);
840
+ color: var(--chip-text);
841
+ }
842
+
843
+ .env-chip-primary {
844
+ background-color: var(--primary-light-color);
845
+ color: var(--primary-color);
846
+ }
847
+
848
+ .env-chip-success {
849
+ background-color: var(--success-light-color);
850
+ color: var(--success-color);
851
+ }
852
+
853
+ .env-chip-warning {
854
+ background-color: var(--warning-light-color);
855
+ color: var(--warning-color);
856
+ }
857
+
858
+ .env-cpu-cores {
859
+ display: flex;
860
+ align-items: center;
861
+ gap: 6px;
862
+ }
863
+
864
+ .env-core-indicator {
865
+ width: 12px;
866
+ height: 12px;
867
+ border-radius: 50%;
868
+ background-color: var(--success-color);
869
+ border: 1px solid rgba(0,0,0,0.1);
870
+ }
871
+
872
+ .env-core-indicator.inactive {
873
+ background-color: var(--border-light-color);
874
+ opacity: 0.7;
875
+ border-color: var(--border-color);
876
+ }
877
+ </style>
878
+
879
+ <div class="env-dashboard-header">
880
+ <div>
881
+ <h3 class="env-dashboard-title">System Environment</h3>
882
+ <p class="env-dashboard-subtitle">Snapshot of the execution environment</p>
883
+ </div>
884
+ <span class="env-chip env-chip-primary">${environment.host}</span>
885
+ </div>
886
+
887
+ <div class="env-card">
888
+ <div class="env-card-header">
889
+ <svg viewBox="0 0 24 24"><path d="M4 6h16V4H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V8h-2v10H4V6zm18-2h-4a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2H6a2 2 0 0 0-2 2v2h20V6a2 2 0 0 0-2-2zM8 12h8v2H8v-2zm0 4h8v2H8v-2z"/></svg>
890
+ Hardware
891
+ </div>
892
+ <div class="env-card-content">
893
+ <div class="env-detail-row">
894
+ <span class="env-detail-label">CPU Model</span>
895
+ <span class="env-detail-value">${environment.cpu.model}</span>
896
+ </div>
897
+ <div class="env-detail-row">
898
+ <span class="env-detail-label">CPU Cores</span>
899
+ <span class="env-detail-value">
900
+ <div class="env-cpu-cores">
901
+ ${Array.from(
902
+ { length: Math.max(0, environment.cpu.cores || 0) },
903
+ (_, i) =>
904
+ `<div class="env-core-indicator ${
905
+ i >=
906
+ (environment.cpu.cores >= 8 ? 8 : environment.cpu.cores)
907
+ ? "inactive"
908
+ : ""
909
+ }" title="Core ${i + 1}"></div>`
910
+ ).join("")}
911
+ <span>${environment.cpu.cores || "N/A"} cores</span>
912
+ </div>
913
+ </span>
914
+ </div>
915
+ <div class="env-detail-row">
916
+ <span class="env-detail-label">Memory</span>
917
+ <span class="env-detail-value">${formattedMemory}</span>
918
+ </div>
919
+ </div>
920
+ </div>
921
+
922
+ <div class="env-card">
923
+ <div class="env-card-header">
924
+ <svg viewBox="0 0 24 24"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-0.01 18c-2.76 0-5.26-1.12-7.07-2.93A7.973 7.973 0 0 1 4 12c0-2.21.9-4.21 2.36-5.64A7.994 7.994 0 0 1 11.99 4c4.41 0 8 3.59 8 8 0 2.76-1.12 5.26-2.93 7.07A7.973 7.973 0 0 1 11.99 20zM12 8c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4z"/></svg>
925
+ Operating System
926
+ </div>
927
+ <div class="env-card-content">
928
+ <div class="env-detail-row">
929
+ <span class="env-detail-label">OS Type</span>
930
+ <span class="env-detail-value">${
931
+ environment.os.split(" ")[0] === "darwin"
932
+ ? "darwin (macOS)"
933
+ : environment.os.split(" ")[0] || "Unknown"
934
+ }</span>
935
+ </div>
936
+ <div class="env-detail-row">
937
+ <span class="env-detail-label">OS Version</span>
938
+ <span class="env-detail-value">${
939
+ environment.os.split(" ")[1] || "N/A"
940
+ }</span>
941
+ </div>
942
+ <div class="env-detail-row">
943
+ <span class="env-detail-label">Hostname</span>
944
+ <span class="env-detail-value" title="${environment.host}">${
945
+ environment.host
946
+ }</span>
947
+ </div>
948
+ </div>
949
+ </div>
950
+
951
+ <div class="env-card">
952
+ <div class="env-card-header">
953
+ <svg viewBox="0 0 24 24"><path d="M9.4 16.6L4.8 12l4.6-4.6L8 6l-6 6 6 6 1.4-1.4zm5.2 0l4.6-4.6-4.6-4.6L16 6l6 6-6 6-1.4-1.4z"/></svg>
954
+ Node.js Runtime
955
+ </div>
956
+ <div class="env-card-content">
957
+ <div class="env-detail-row">
958
+ <span class="env-detail-label">Node Version</span>
959
+ <span class="env-detail-value">${environment.node}</span>
960
+ </div>
961
+ <div class="env-detail-row">
962
+ <span class="env-detail-label">V8 Engine</span>
963
+ <span class="env-detail-value">${environment.v8}</span>
964
+ </div>
965
+ <div class="env-detail-row">
966
+ <span class="env-detail-label">Working Dir</span>
967
+ <span class="env-detail-value" title="${environment.cwd}">${
968
+ environment.cwd.length > 25
969
+ ? "..." + environment.cwd.slice(-22)
970
+ : environment.cwd
971
+ }</span>
972
+ </div>
973
+ </div>
974
+ </div>
975
+
976
+ <div class="env-card">
977
+ <div class="env-card-header">
978
+ <svg viewBox="0 0 24 24"><path d="M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.6 5.64 5.35 8.04 2.34 8.36 0 10.91 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96zM19 18H6c-2.21 0-4-1.79-4-4s1.79-4 4-4h.71C7.37 8.69 9.48 7 12 7c2.76 0 5 2.24 5 5v1h2c1.66 0 3 1.34 3 3s-1.34 3-3 3z"/></svg>
979
+ System Summary
980
+ </div>
981
+ <div class="env-card-content">
982
+ <div class="env-detail-row">
983
+ <span class="env-detail-label">Platform Arch</span>
984
+ <span class="env-detail-value">
985
+ <span class="env-chip ${
986
+ environment.os.includes("darwin") &&
987
+ environment.cpu.model.toLowerCase().includes("apple")
988
+ ? "env-chip-success"
989
+ : "env-chip-warning"
990
+ }">
991
+ ${
992
+ environment.os.includes("darwin") &&
993
+ environment.cpu.model.toLowerCase().includes("apple")
994
+ ? "Apple Silicon"
995
+ : environment.cpu.model.toLowerCase().includes("arm") ||
996
+ environment.cpu.model.toLowerCase().includes("aarch64")
997
+ ? "ARM-based"
998
+ : "x86/Other"
999
+ }
1000
+ </span>
1001
+ </span>
1002
+ </div>
1003
+ <div class="env-detail-row">
1004
+ <span class="env-detail-label">Memory per Core</span>
1005
+ <span class="env-detail-value">${
1006
+ environment.cpu.cores > 0
1007
+ ? (
1008
+ parseFloat(environment.memory) / environment.cpu.cores
1009
+ ).toFixed(2) + " GB"
1010
+ : "N/A"
1011
+ }</span>
1012
+ </div>
1013
+ <div class="env-detail-row">
1014
+ <span class="env-detail-label">Run Context</span>
1015
+ <span class="env-detail-value">CI/Local Test</span>
1016
+ </div>
1017
+ </div>
1018
+ </div>
1019
+ </div>
1020
+ `;
1021
+ }
1022
+ function generateTestHistoryContent(trendData) {
1023
+ if (
1024
+ !trendData ||
1025
+ !trendData.testRuns ||
1026
+ Object.keys(trendData.testRuns).length === 0
1027
+ ) {
1028
+ return '<div class="no-data">No historical test data available.</div>';
1029
+ }
1030
+
1031
+ const allTestNamesAndPaths = new Map();
1032
+ Object.values(trendData.testRuns).forEach((run) => {
1033
+ if (Array.isArray(run)) {
1034
+ run.forEach((test) => {
1035
+ if (test && test.testName && !allTestNamesAndPaths.has(test.testName)) {
1036
+ const parts = test.testName.split(" > ");
1037
+ const title = parts[parts.length - 1];
1038
+ allTestNamesAndPaths.set(test.testName, title);
1039
+ }
1040
+ });
1041
+ }
1042
+ });
1043
+
1044
+ if (allTestNamesAndPaths.size === 0) {
1045
+ return '<div class="no-data">No historical test data found after processing.</div>';
1046
+ }
1047
+
1048
+ const testHistory = Array.from(allTestNamesAndPaths.entries())
1049
+ .map(([fullTestName, testTitle]) => {
1050
+ const history = [];
1051
+ (trendData.overall || []).forEach((overallRun, index) => {
1052
+ const runKey = overallRun.runId
1053
+ ? `test run ${overallRun.runId}`
1054
+ : `test run ${index + 1}`;
1055
+ const testRunForThisOverallRun = trendData.testRuns[runKey]?.find(
1056
+ (t) => t && t.testName === fullTestName
1057
+ );
1058
+ if (testRunForThisOverallRun) {
1059
+ history.push({
1060
+ runId: overallRun.runId || index + 1,
1061
+ status: testRunForThisOverallRun.status || "unknown",
1062
+ duration: testRunForThisOverallRun.duration || 0,
1063
+ timestamp:
1064
+ testRunForThisOverallRun.timestamp ||
1065
+ overallRun.timestamp ||
1066
+ new Date(),
1067
+ });
1068
+ }
1069
+ });
1070
+ return { fullTestName, testTitle, history };
1071
+ })
1072
+ .filter((item) => item.history.length > 0);
1073
+
1074
+ return `
1075
+ <div class="test-history-container">
1076
+ <div class="filters" style="border-color: black; border-style: groove;">
1077
+ <input type="text" id="history-filter-name" placeholder="Search by test title..." style="border-color: black; border-style: outset;">
1078
+ <select id="history-filter-status">
1079
+ <option value="">All Statuses</option>
1080
+ <option value="passed">Passed</option>
1081
+ <option value="failed">Failed</option>
1082
+ <option value="skipped">Skipped</option>
1083
+ </select>
1084
+ <button id="clear-history-filters" class="clear-filters-btn">Clear Filters</button>
1085
+ </div>
1086
+
1087
+ <div class="test-history-grid">
1088
+ ${testHistory
1089
+ .map((test) => {
1090
+ const latestRun =
1091
+ test.history.length > 0
1092
+ ? test.history[test.history.length - 1]
1093
+ : { status: "unknown" };
1094
+ return `
1095
+ <div class="test-history-card" data-test-name="${sanitizeHTML(
1096
+ test.testTitle.toLowerCase()
1097
+ )}" data-latest-status="${latestRun.status}">
1098
+ <div class="test-history-header">
1099
+ <p title="${sanitizeHTML(test.testTitle)}">${capitalize(
1100
+ sanitizeHTML(test.testTitle)
1101
+ )}</p>
1102
+ <span class="status-badge ${getStatusClass(latestRun.status)}">
1103
+ ${String(latestRun.status).toUpperCase()}
1104
+ </span>
1105
+ </div>
1106
+ <div class="test-history-trend">
1107
+ ${generateTestHistoryChart(test.history)}
1108
+ </div>
1109
+ <details class="test-history-details-collapsible">
1110
+ <summary>Show Run Details (${test.history.length})</summary>
1111
+ <div class="test-history-details">
1112
+ <table>
1113
+ <thead><tr><th>Run</th><th>Status</th><th>Duration</th><th>Date</th></tr></thead>
1114
+ <tbody>
1115
+ ${test.history
1116
+ .slice()
1117
+ .reverse()
1118
+ .map(
1119
+ (run) => `
1120
+ <tr>
1121
+ <td>${run.runId}</td>
1122
+ <td><span class="status-badge-small ${getStatusClass(
1123
+ run.status
1124
+ )}">${String(run.status).toUpperCase()}</span></td>
1125
+ <td>${formatDuration(run.duration)}</td>
1126
+ <td>${formatDate(run.timestamp)}</td>
1127
+ </tr>`
1128
+ )
1129
+ .join("")}
1130
+ </tbody>
1131
+ </table>
1132
+ </div>
1133
+ </details>
1134
+ </div>`;
1135
+ })
1136
+ .join("")}
1137
+ </div>
1138
+ </div>
1139
+ `;
1140
+ }
1141
+ function getStatusClass(status) {
1142
+ switch (String(status).toLowerCase()) {
1143
+ case "passed":
1144
+ return "status-passed";
1145
+ case "failed":
1146
+ return "status-failed";
1147
+ case "skipped":
1148
+ return "status-skipped";
1149
+ default:
1150
+ return "status-unknown";
1151
+ }
1152
+ }
1153
+ function getStatusIcon(status) {
1154
+ switch (String(status).toLowerCase()) {
1155
+ case "passed":
1156
+ return "✅";
1157
+ case "failed":
1158
+ return "❌";
1159
+ case "skipped":
1160
+ return "⏭️";
1161
+ default:
1162
+ return "❓";
1163
+ }
1164
+ }
1165
+ function getSuitesData(results) {
1166
+ const suitesMap = new Map();
1167
+ if (!results || results.length === 0) return [];
1168
+
1169
+ results.forEach((test) => {
1170
+ const browser = test.browser || "unknown";
1171
+ const suiteParts = test.name.split(" > ");
1172
+ let suiteNameCandidate = "Default Suite";
1173
+ if (suiteParts.length > 2) {
1174
+ suiteNameCandidate = suiteParts[1];
1175
+ } else if (suiteParts.length > 1) {
1176
+ suiteNameCandidate = suiteParts[0]
1177
+ .split(path.sep)
1178
+ .pop()
1179
+ .replace(/\.(spec|test)\.(ts|js|mjs|cjs)$/, "");
1180
+ } else {
1181
+ suiteNameCandidate = test.name
1182
+ .split(path.sep)
1183
+ .pop()
1184
+ .replace(/\.(spec|test)\.(ts|js|mjs|cjs)$/, "");
1185
+ }
1186
+ const suiteName = suiteNameCandidate;
1187
+ const key = `${suiteName}|${browser}`;
1188
+
1189
+ if (!suitesMap.has(key)) {
1190
+ suitesMap.set(key, {
1191
+ id: test.id || key,
1192
+ name: suiteName,
1193
+ browser: browser,
1194
+ passed: 0,
1195
+ failed: 0,
1196
+ skipped: 0,
1197
+ count: 0,
1198
+ statusOverall: "passed",
1199
+ });
1200
+ }
1201
+ const suite = suitesMap.get(key);
1202
+ suite.count++;
1203
+ const currentStatus = String(test.status).toLowerCase();
1204
+ if (currentStatus && suite[currentStatus] !== undefined) {
1205
+ suite[currentStatus]++;
1206
+ }
1207
+ if (currentStatus === "failed") suite.statusOverall = "failed";
1208
+ else if (currentStatus === "skipped" && suite.statusOverall !== "failed")
1209
+ suite.statusOverall = "skipped";
1210
+ });
1211
+ return Array.from(suitesMap.values());
1212
+ }
1213
+ function generateSuitesWidget(suitesData) {
1214
+ if (!suitesData || suitesData.length === 0) {
1215
+ return `<div class="suites-widget"><div class="suites-header"><h2>Test Suites</h2></div><div class="no-data">No suite data available.</div></div>`;
1216
+ }
1217
+ return `
1218
+ <div class="suites-widget">
1219
+ <div class="suites-header">
1220
+ <h2>Test Suites</h2>
1221
+ <span class="summary-badge">${
1222
+ suitesData.length
1223
+ } suites • ${suitesData.reduce(
1224
+ (sum, suite) => sum + suite.count,
1225
+ 0
1226
+ )} tests</span>
1227
+ </div>
1228
+ <div class="suites-grid">
1229
+ ${suitesData
1230
+ .map(
1231
+ (suite) => `
1232
+ <div class="suite-card status-${suite.statusOverall}">
1233
+ <div class="suite-card-header">
1234
+ <h3 class="suite-name" title="${sanitizeHTML(
1235
+ suite.name
1236
+ )} (${sanitizeHTML(suite.browser)})">${sanitizeHTML(suite.name)}</h3>
1237
+ </div>
1238
+ <div>🖥️ <span class="browser-tag">${sanitizeHTML(
1239
+ suite.browser
1240
+ )}</span></div>
1241
+ <div class="suite-card-body">
1242
+ <span class="test-count">${suite.count} test${
1243
+ suite.count !== 1 ? "s" : ""
1244
+ }</span>
1245
+ <div class="suite-stats">
1246
+ ${
1247
+ suite.passed > 0
1248
+ ? `<span class="stat-passed" title="Passed"><svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" fill="currentColor" class="bi bi-check-circle-fill" viewBox="0 0 16 16"><path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-3.97-3.03a.75.75 0 0 0-1.08.022L7.477 9.417 5.384 7.323a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-.01-1.05z"/></svg> ${suite.passed}</span>`
1249
+ : ""
1250
+ }
1251
+ ${
1252
+ suite.failed > 0
1253
+ ? `<span class="stat-failed" title="Failed"><svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" fill="currentColor" class="bi bi-x-circle-fill" viewBox="0 0 16 16"><path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zM5.354 4.646a.5.5 0 1 0-.708.708L7.293 8l-2.647 2.646a.5.5 0 0 0 .708.708L8 8.707l2.646 2.647a.5.5 0 0 0 .708-.708L8.707 8l2.647-2.646a.5.5 0 0 0-.708-.708L8 7.293 5.354 4.646z"/></svg> ${suite.failed}</span>`
1254
+ : ""
1255
+ }
1256
+ ${
1257
+ suite.skipped > 0
1258
+ ? `<span class="stat-skipped" title="Skipped"><svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" fill="currentColor" class="bi bi-exclamation-triangle-fill" viewBox="0 0 16 16"><path d="M8.982 1.566a1.13 1.13 0 0 0-1.96 0L.165 13.233c-.457.778.091 1.767.98 1.767h13.713c.889 0 1.438-.99.98-1.767L8.982 1.566zM8 5c.535 0 .954.462.9.995l-.35 3.507a.552.552 0 0 1-1.1 0L7.1 5.995A.905.905 0 0 1 8 5zm.002 6a1 1 0 1 1 0 2 1 1 0 0 1 0-2z"/></svg> ${suite.skipped}</span>`
1259
+ : ""
1260
+ }
1261
+ </div>
1262
+ </div>
1263
+ </div>`
1264
+ )
1265
+ .join("")}
1266
+ </div>
1267
+ </div>`;
1268
+ }
1269
+ function getAttachmentIcon(contentType) {
1270
+ if (contentType.includes("pdf")) return "📄";
1271
+ if (contentType.includes("json")) return "{ }";
1272
+ if (contentType.includes("html") || contentType.includes("xml")) return "</>";
1273
+ if (contentType.includes("csv")) return "📊";
1274
+ if (contentType.startsWith("text/")) return "📝";
1275
+ return "📎";
1276
+ }
1277
+ function generateHTML(reportData, trendData = null) {
1278
+ const { run, results } = reportData;
1279
+ const suitesData = getSuitesData(reportData.results || []);
1280
+ const runSummary = run || {
1281
+ totalTests: 0,
1282
+ passed: 0,
1283
+ failed: 0,
1284
+ skipped: 0,
1285
+ duration: 0,
1286
+ timestamp: new Date().toISOString(),
1287
+ };
1288
+ const totalTestsOr1 = runSummary.totalTests || 1;
1289
+ const passPercentage = Math.round((runSummary.passed / totalTestsOr1) * 100);
1290
+ const failPercentage = Math.round((runSummary.failed / totalTestsOr1) * 100);
1291
+ const skipPercentage = Math.round(
1292
+ ((runSummary.skipped || 0) / totalTestsOr1) * 100
1293
+ );
1294
+ const avgTestDuration =
1295
+ runSummary.totalTests > 0
1296
+ ? formatDuration(runSummary.duration / runSummary.totalTests)
1297
+ : "0.0s";
1298
+ function generateTestCasesHTML() {
1299
+ if (!results || results.length === 0)
1300
+ return '<div class="no-tests">No test results found in this run.</div>';
1301
+ return results
1302
+ .map((test, index) => {
1303
+ const browser = test.browser || "unknown";
1304
+ const testFileParts = test.name.split(" > ");
1305
+ const testTitle =
1306
+ testFileParts[testFileParts.length - 1] || "Unnamed Test";
1307
+ const generateStepsHTML = (steps, depth = 0) => {
1308
+ if (!steps || steps.length === 0)
1309
+ return "<div class='no-steps'>No steps recorded for this test.</div>";
1310
+ return steps
1311
+ .map((step) => {
1312
+ const hasNestedSteps = step.steps && step.steps.length > 0;
1313
+ const isHook = step.hookType;
1314
+ const stepClass = isHook
1315
+ ? `step-hook step-hook-${step.hookType}`
1316
+ : "";
1317
+ const hookIndicator = isHook ? ` (${step.hookType} hook)` : "";
1318
+ return `
1319
+ <div class="step-item" style="--depth: ${depth};">
1320
+ <div class="step-header ${stepClass}" role="button" aria-expanded="false">
1321
+ <span class="step-icon">${getStatusIcon(step.status)}</span>
1322
+ <span class="step-title">${sanitizeHTML(
1323
+ step.title
1324
+ )}${hookIndicator}</span>
1325
+ <span class="step-duration">${formatDuration(
1326
+ step.duration
1327
+ )}</span>
1328
+ </div>
1329
+ <div class="step-details" style="display: none;">
1330
+ ${
1331
+ step.codeLocation
1332
+ ? `<div class="step-info"><strong>Location:</strong> ${sanitizeHTML(
1333
+ step.codeLocation
1334
+ )}</div>`
1335
+ : ""
1336
+ }
1337
+ ${
1338
+ step.errorMessage
1339
+ ? `<div class="step-error">
1340
+ ${
1341
+ step.stackTrace
1342
+ ? `<div class="stack-trace">${formatPlaywrightError(
1343
+ step.stackTrace
1344
+ )}</div>`
1345
+ : ""
1346
+ }
1347
+ <button
1348
+ class="copy-error-btn"
1349
+ onclick="copyErrorToClipboard(this)"
1350
+ style="
1351
+ margin-top: 8px;
1352
+ padding: 4px 8px;
1353
+ background: #f0f0f0;
1354
+ border: 2px solid #ccc;
1355
+ border-radius: 4px;
1356
+ cursor: pointer;
1357
+ font-size: 12px;
1358
+ border-color: #8B0000;
1359
+ color: #8B0000;
1360
+ "
1361
+ onmouseover="this.style.background='#e0e0e0'"
1362
+ onmouseout="this.style.background='#f0f0f0'"
1363
+ >
1364
+ Copy Error Prompt
1365
+ </button>
1366
+ </div>`
1367
+ : ""
1368
+ }
1369
+ ${
1370
+ hasNestedSteps
1371
+ ? `<div class="nested-steps">${generateStepsHTML(
1372
+ step.steps,
1373
+ depth + 1
1374
+ )}</div>`
1375
+ : ""
1376
+ }
1377
+ </div>
1378
+ </div>`;
1379
+ })
1380
+ .join("");
1381
+ };
1382
+
1383
+ return `
1384
+ <div class="test-case" data-status="${
1385
+ test.status
1386
+ }" data-browser="${sanitizeHTML(browser)}" data-tags="${(test.tags || [])
1387
+ .join(",")
1388
+ .toLowerCase()}">
1389
+ <div class="test-case-header" role="button" aria-expanded="false">
1390
+ <div class="test-case-summary">
1391
+ <span class="status-badge ${getStatusClass(test.status)}">${String(
1392
+ test.status
1393
+ ).toUpperCase()}</span>
1394
+ <span class="test-case-title" title="${sanitizeHTML(
1395
+ test.name
1396
+ )}">${sanitizeHTML(testTitle)}</span>
1397
+ <span class="test-case-browser">(${sanitizeHTML(browser)})</span>
1398
+ </div>
1399
+ <div class="test-case-meta">
1400
+ ${
1401
+ test.tags && test.tags.length > 0
1402
+ ? test.tags
1403
+ .map((t) => `<span class="tag">${sanitizeHTML(t)}</span>`)
1404
+ .join(" ")
1405
+ : ""
1406
+ }
1407
+ <span class="test-duration">${formatDuration(test.duration)}</span>
1408
+ </div>
1409
+ </div>
1410
+ <div class="test-case-content" style="display: none;">
1411
+ <p><strong>Full Path:</strong> ${sanitizeHTML(test.name)}</p>
1412
+ <p><strong>Test run Worker ID:</strong> ${sanitizeHTML(
1413
+ test.workerId
1414
+ )} [<strong>Total No. of Workers:</strong> ${sanitizeHTML(
1415
+ test.totalWorkers
1416
+ )}]</p>
1417
+ ${
1418
+ test.errorMessage
1419
+ ? `<div class="test-error-summary">${formatPlaywrightError(
1420
+ test.errorMessage
1421
+ )}
1422
+ <button
1423
+ class="copy-error-btn"
1424
+ onclick="copyErrorToClipboard(this)"
1425
+ style="
1426
+ margin-top: 8px;
1427
+ padding: 4px 8px;
1428
+ background: #f0f0f0;
1429
+ border: 2px solid #ccc;
1430
+ border-radius: 4px;
1431
+ cursor: pointer;
1432
+ font-size: 12px;
1433
+ border-color: #8B0000;
1434
+ color: #8B0000;
1435
+ "
1436
+ onmouseover="this.style.background='#e0e0e0'"
1437
+ onmouseout="this.style.background='#f0f0f0'"
1438
+ >
1439
+ Copy Error Prompt
1440
+ </button>
1441
+ </div>`
1442
+ : ""
1443
+ }
1444
+ <h4>Steps</h4>
1445
+ <div class="steps-list">${generateStepsHTML(test.steps)}</div>
1446
+ ${
1447
+ test.stdout && test.stdout.length > 0
1448
+ ? `<div class="console-output-section"><h4>Console Output (stdout)</h4><pre class="console-log stdout-log" style="background-color: #2d2d2d; color: wheat; padding: 1.25em; border-radius: 0.85em; line-height: 1.2;">${formatPlaywrightError(
1449
+ test.stdout.map((line) => sanitizeHTML(line)).join("\n")
1450
+ )}</pre></div>`
1451
+ : ""
1452
+ }
1453
+ ${
1454
+ test.stderr && test.stderr.length > 0
1455
+ ? `<div class="console-output-section"><h4>Console Output (stderr)</h4><pre class="console-log stderr-log" style="background-color: #2d2d2d; color: indianred; padding: 1.25em; border-radius: 0.85em; line-height: 1.2;">${formatPlaywrightError(
1456
+ test.stderr.map((line) => sanitizeHTML(line)).join("\n")
1457
+ )}</pre></div>`
1458
+ : ""
1459
+ }
1460
+ ${
1461
+ test.screenshots && test.screenshots.length > 0
1462
+ ? `
1463
+ <div class="attachments-section">
1464
+ <h4>Screenshots</h4>
1465
+ <div class="attachments-grid">
1466
+ ${test.screenshots
1467
+ .map(
1468
+ (screenshot, index) => `
1469
+ <div class="attachment-item">
1470
+ <img src="${screenshot}" alt="Screenshot ${index + 1}">
1471
+ <div class="attachment-info">
1472
+ <div class="trace-actions">
1473
+ <a href="${screenshot}" target="_blank" class="view-full">View Full Image</a>
1474
+ <a href="${screenshot}" target="_blank" download="screenshot-${Date.now()}-${index}.png">Download</a>
1475
+ </div>
1476
+ </div>
1477
+ </div>
1478
+ `
1479
+ )
1480
+ .join("")}
1481
+ </div>
1482
+ </div>
1483
+ `
1484
+ : ""
1485
+ }
1486
+ ${
1487
+ test.videoPath && test.videoPath.length > 0
1488
+ ? `<div class="attachments-section"><h4>Videos</h4><div class="attachments-grid">${test.videoPath
1489
+ .map((videoUrl, index) => {
1490
+ const fileExtension = String(videoUrl)
1491
+ .split(".")
1492
+ .pop()
1493
+ .toLowerCase();
1494
+ const mimeType =
1495
+ {
1496
+ mp4: "video/mp4",
1497
+ webm: "video/webm",
1498
+ ogg: "video/ogg",
1499
+ mov: "video/quicktime",
1500
+ avi: "video/x-msvideo",
1501
+ }[fileExtension] || "video/mp4";
1502
+ return `<div class="attachment-item video-item">
1503
+ <video controls width="100%" height="auto" title="Video ${
1504
+ index + 1
1505
+ }">
1506
+ <source src="${sanitizeHTML(
1507
+ videoUrl
1508
+ )}" type="${mimeType}">
1509
+ Your browser does not support the video tag.
1510
+ </video>
1511
+ <div class="attachment-info">
1512
+ <div class="trace-actions">
1513
+ <a href="${sanitizeHTML(
1514
+ videoUrl
1515
+ )}" target="_blank" download="video-${Date.now()}-${index}.${fileExtension}">Download</a>
1516
+ </div>
1517
+ </div>
1518
+ </div>`;
1519
+ })
1520
+ .join("")}</div></div>`
1521
+ : ""
1522
+ }
1523
+ ${
1524
+ test.tracePath
1525
+ ? `
1526
+ <div class="attachments-section">
1527
+ <h4>Trace Files</h4>
1528
+ <div class="attachments-grid">
1529
+ <div class="attachment-item trace-item">
1530
+ <div class="trace-preview">
1531
+ <span class="trace-icon">📄</span>
1532
+ <span class="trace-name">${sanitizeHTML(
1533
+ path.basename(test.tracePath)
1534
+ )}</span>
1535
+ </div>
1536
+ <div class="attachment-info">
1537
+ <div class="trace-actions">
1538
+ <a href="${sanitizeHTML(
1539
+ test.tracePath
1540
+ )}" target="_blank" download="${sanitizeHTML(
1541
+ path.basename(test.tracePath)
1542
+ )}" class="download-trace">Download Trace</a>
1543
+ </div>
1544
+ </div>
1545
+ </div>
1546
+ </div>
1547
+ </div>
1548
+ `
1549
+ : ""
1550
+ }
1551
+ ${
1552
+ test.attachments && test.attachments.length > 0
1553
+ ? `
1554
+ <div class="attachments-section">
1555
+ <h4>Other Attachments</h4>
1556
+ <div class="attachments-grid">
1557
+ ${test.attachments
1558
+ .map(
1559
+ (attachment) => `
1560
+ <div class="attachment-item generic-attachment">
1561
+ <div class="attachment-icon">${getAttachmentIcon(
1562
+ attachment.contentType
1563
+ )}</div>
1564
+ <div class="attachment-caption">
1565
+ <span class="attachment-name" title="${sanitizeHTML(
1566
+ attachment.name
1567
+ )}">${sanitizeHTML(attachment.name)}</span>
1568
+ <span class="attachment-type">${sanitizeHTML(
1569
+ attachment.contentType
1570
+ )}</span>
1571
+ </div>
1572
+ <div class="attachment-info">
1573
+ <div class="trace-actions">
1574
+ <a href="${sanitizeHTML(
1575
+ attachment.path
1576
+ )}" target="_blank" download="${sanitizeHTML(
1577
+ attachment.name
1578
+ )}" class="download-trace">Download</a>
1579
+ </div>
1580
+ </div>
1581
+ </div>
1582
+ `
1583
+ )
1584
+ .join("")}
1585
+ </div>
1586
+ </div>
1587
+ `
1588
+ : ""
1589
+ }
1590
+ ${
1591
+ test.codeSnippet
1592
+ ? `<div class="code-section"><h4>Code Snippet</h4><pre><code>${formatPlaywrightError(
1593
+ sanitizeHTML(test.codeSnippet)
1594
+ )}</code></pre></div>`
1595
+ : ""
1596
+ }
1597
+ </div>
1598
+ </div>`;
1599
+ })
1600
+ .join("");
1601
+ }
1602
+ return `
1603
+ <!DOCTYPE html>
1604
+ <html lang="en">
1605
+ <head>
1606
+ <meta charset="UTF-8">
1607
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
1608
+ <link rel="icon" type="image/png" href="https://i.postimg.cc/XqVn1NhF/pulse.png">
1609
+ <link rel="apple-touch-icon" href="https://i.postimg.cc/XqVn1NhF/pulse.png">
1610
+ <script src="https://code.highcharts.com/highcharts.js" defer></script>
1611
+ <title>Playwright Pulse Report</title>
1612
+ <style>
1613
+ :root {
1614
+ --primary-color: #3f51b5; --secondary-color: #ff4081; --accent-color: #673ab7; --accent-color-alt: #FF9800;
1615
+ --success-color: #4CAF50; --danger-color: #F44336; --warning-color: #FFC107; --info-color: #2196F3;
1616
+ --light-gray-color: #f5f5f5; --medium-gray-color: #e0e0e0; --dark-gray-color: #757575;
1617
+ --text-color: #333; --text-color-secondary: #555; --border-color: #ddd; --background-color: #f8f9fa;
1618
+ --card-background-color: #fff; --font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
1619
+ --border-radius: 8px; --box-shadow: 0 5px 15px rgba(0,0,0,0.08); --box-shadow-light: 0 3px 8px rgba(0,0,0,0.05); --box-shadow-inset: inset 0 1px 3px rgba(0,0,0,0.07);
1620
+ }
1621
+ .trend-chart-container, .test-history-trend div[id^="testHistoryChart-"] { min-height: 100px; }
1622
+ .lazy-load-chart .no-data, .lazy-load-chart .no-data-chart { display: flex; align-items: center; justify-content: center; height: 100%; font-style: italic; color: var(--dark-gray-color); }
1623
+ .highcharts-background { fill: transparent; }
1624
+ .highcharts-title, .highcharts-subtitle { font-family: var(--font-family); }
1625
+ .highcharts-axis-labels text, .highcharts-legend-item text { fill: var(--text-color-secondary) !important; font-size: 12px !important; }
1626
+ .highcharts-axis-title { fill: var(--text-color) !important; }
1627
+ .highcharts-tooltip > span { background-color: rgba(10,10,10,0.92) !important; border-color: rgba(10,10,10,0.92) !important; color: #f5f5f5 !important; padding: 10px !important; border-radius: 6px !important; }
1628
+ body { font-family: var(--font-family); margin: 0; background-color: var(--background-color); color: var(--text-color); line-height: 1.65; font-size: 16px; }
1629
+ .container { padding: 30px; border-radius: var(--border-radius); box-shadow: var(--box-shadow); background: repeating-linear-gradient(#f1f8e9, #f9fbe7, #fce4ec); }
1630
+ .header { display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; padding-bottom: 25px; border-bottom: 1px solid var(--border-color); margin-bottom: 25px; }
1631
+ .header-title { display: flex; align-items: center; gap: 15px; }
1632
+ .header h1 { margin: 0; font-size: 1.85em; font-weight: 600; color: var(--primary-color); }
1633
+ #report-logo { height: 40px; width: 40px; border-radius: 4px; box-shadow: 0 1px 2px rgba(0,0,0,0.1);}
1634
+ .run-info { font-size: 0.9em; text-align: right; color: var(--text-color-secondary); line-height:1.5;}
1635
+ .run-info strong { color: var(--text-color); }
1636
+ .tabs { display: flex; border-bottom: 2px solid var(--border-color); margin-bottom: 30px; overflow-x: auto; }
1637
+ .tab-button { padding: 15px 25px; background: none; border: none; border-bottom: 3px solid transparent; cursor: pointer; font-size: 1.1em; font-weight: 600; color: black; transition: color 0.2s ease, border-color 0.2s ease; white-space: nowrap; }
1638
+ .tab-button:hover { color: var(--accent-color); }
1639
+ .tab-button.active { color: var(--primary-color); border-bottom-color: var(--primary-color); }
1640
+ .tab-content { display: none; animation: fadeIn 0.4s ease-out; }
1641
+ .tab-content.active { display: block; }
1642
+ @keyframes fadeIn { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } }
1643
+ .dashboard-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(190px, 1fr)); gap: 22px; margin-bottom: 35px; }
1644
+ .summary-card { background-color: var(--card-background-color); border: 1px solid var(--border-color); border-radius: var(--border-radius); padding: 22px; text-align: center; box-shadow: var(--box-shadow-light); transition: transform 0.2s ease, box-shadow 0.2s ease; }
1645
+ .summary-card:hover { transform: translateY(-5px); box-shadow: var(--box-shadow); }
1646
+ .summary-card h3 { margin: 0 0 10px; font-size: 1.05em; font-weight: 500; color: var(--text-color-secondary); }
1647
+ .summary-card .value { font-size: 2.4em; font-weight: 600; margin-bottom: 8px; }
1648
+ .summary-card .trend-percentage { font-size: 1em; color: var(--dark-gray-color); }
1649
+ .status-passed .value, .stat-passed svg { color: var(--success-color); }
1650
+ .status-failed .value, .stat-failed svg { color: var(--danger-color); }
1651
+ .status-skipped .value, .stat-skipped svg { color: var(--warning-color); }
1652
+ .dashboard-bottom-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(350px, 1fr)); gap: 28px; align-items: stretch; }
1653
+ .pie-chart-wrapper, .suites-widget, .trend-chart { background-color: var(--card-background-color); padding: 28px; border-radius: var(--border-radius); box-shadow: var(--box-shadow-light); display: flex; flex-direction: column; }
1654
+ .pie-chart-wrapper h3, .suites-header h2, .trend-chart h3 { text-align: center; margin-top: 0; margin-bottom: 25px; font-size: 1.25em; font-weight: 600; color: var(--text-color); }
1655
+ .trend-chart-container, .pie-chart-wrapper div[id^="pieChart-"] { flex-grow: 1; min-height: 250px; }
1656
+ .status-badge-small-tooltip { padding: 2px 5px; border-radius: 3px; font-size: 0.9em; font-weight: 600; color: white; text-transform: uppercase; }
1657
+ .status-badge-small-tooltip.status-passed { background-color: var(--success-color); }
1658
+ .status-badge-small-tooltip.status-failed { background-color: var(--danger-color); }
1659
+ .status-badge-small-tooltip.status-skipped { background-color: var(--warning-color); }
1660
+ .status-badge-small-tooltip.status-unknown { background-color: var(--dark-gray-color); }
1661
+ .suites-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
1662
+ .summary-badge { background-color: var(--light-gray-color); color: var(--text-color-secondary); padding: 7px 14px; border-radius: 16px; font-size: 0.9em; }
1663
+ .suites-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 20px; }
1664
+ .suite-card { border: 1px solid var(--border-color); border-left-width: 5px; border-radius: calc(var(--border-radius) / 1.5); padding: 20px; background-color: var(--card-background-color); transition: box-shadow 0.2s ease, border-left-color 0.2s ease; }
1665
+ .suite-card:hover { box-shadow: var(--box-shadow); }
1666
+ .suite-card.status-passed { border-left-color: var(--success-color); }
1667
+ .suite-card.status-failed { border-left-color: var(--danger-color); }
1668
+ .suite-card.status-skipped { border-left-color: var(--warning-color); }
1669
+ .suite-card-header { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 12px; }
1670
+ .suite-name { font-weight: 600; font-size: 1.05em; color: var(--text-color); margin-right: 10px; word-break: break-word;}
1671
+ .browser-tag { font-size: 0.8em; background-color: var(--medium-gray-color); color: var(--text-color-secondary); padding: 3px 8px; border-radius: 4px; white-space: nowrap;}
1672
+ .suite-card-body .test-count { font-size: 0.95em; color: var(--text-color-secondary); display: block; margin-bottom: 10px; }
1673
+ .suite-stats { display: flex; gap: 14px; font-size: 0.95em; align-items: center; }
1674
+ .suite-stats span { display: flex; align-items: center; gap: 6px; }
1675
+ .suite-stats svg { vertical-align: middle; font-size: 1.15em; }
1676
+ .filters { display: flex; flex-wrap: wrap; gap: 18px; margin-bottom: 28px; padding: 20px; background-color: var(--light-gray-color); border-radius: var(--border-radius); box-shadow: var(--box-shadow-inset); border-color: black; border-style: groove; }
1677
+ .filters input, .filters select, .filters button { padding: 11px 15px; border: 1px solid var(--border-color); border-radius: 6px; font-size: 1em; }
1678
+ .filters input { flex-grow: 1; min-width: 240px;}
1679
+ .filters select {min-width: 180px;}
1680
+ .filters button { background-color: var(--primary-color); color: white; cursor: pointer; transition: background-color 0.2s ease, box-shadow 0.2s ease; border: none; }
1681
+ .filters button:hover { background-color: var(--accent-color); box-shadow: 0 2px 5px rgba(0,0,0,0.15);}
1682
+ .test-case { margin-bottom: 15px; border: 1px solid var(--border-color); border-radius: var(--border-radius); background-color: var(--card-background-color); box-shadow: var(--box-shadow-light); overflow: hidden; }
1683
+ .test-case-header { padding: 10px 15px; background-color: #fff; cursor: pointer; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid transparent; transition: background-color 0.2s ease; }
1684
+ .test-case-header:hover { background-color: #f4f6f8; }
1685
+ .test-case-header[aria-expanded="true"] { border-bottom-color: var(--border-color); background-color: #f9fafb; }
1686
+ .test-case-summary { display: flex; align-items: center; gap: 14px; flex-grow: 1; flex-wrap: wrap;}
1687
+ .test-case-title { font-weight: 600; color: var(--text-color); font-size: 1em; }
1688
+ .test-case-browser { font-size: 0.9em; color: var(--text-color-secondary); }
1689
+ .test-case-meta { display: flex; align-items: center; gap: 12px; font-size: 0.9em; color: var(--text-color-secondary); flex-shrink: 0; }
1690
+ .test-duration { background-color: var(--light-gray-color); padding: 4px 10px; border-radius: 12px; font-size: 0.9em;}
1691
+ .status-badge { padding: 5px; border-radius: 6px; font-size: 0.8em; font-weight: 600; color: white; text-transform: uppercase; min-width: 70px; text-align: center; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
1692
+ .status-badge.status-passed { background-color: var(--success-color); }
1693
+ .status-badge.status-failed { background-color: var(--danger-color); }
1694
+ .status-badge.status-skipped { background-color: var(--warning-color); }
1695
+ .status-badge.status-unknown { background-color: var(--dark-gray-color); }
1696
+ .tag { display: inline-block; background: linear-gradient( #fff, #333, #000); color: #fff; padding: 3px 10px; border-radius: 12px; font-size: 0.85em; margin-right: 6px; font-weight: 400; }
1697
+ .test-case-content { display: none; padding: 20px; border-top: 1px solid var(--border-color); background-color: #fcfdff; }
1698
+ .test-case-content h4 { margin-top: 22px; margin-bottom: 14px; font-size: 1.15em; color: var(--primary-color); }
1699
+ .test-case-content p { margin-bottom: 10px; font-size: 1em; }
1700
+ .test-error-summary { margin-bottom: 20px; padding: 14px; background-color: rgba(244,67,54,0.05); border: 1px solid rgba(244,67,54,0.2); border-left: 4px solid var(--danger-color); border-radius: 4px; }
1701
+ .test-error-summary h4 { color: var(--danger-color); margin-top:0;}
1702
+ .test-error-summary pre { white-space: pre-wrap; word-break: break-all; color: var(--danger-color); font-size: 0.95em;}
1703
+ .steps-list { margin: 18px 0; }
1704
+ .step-item { margin-bottom: 8px; padding-left: calc(var(--depth, 0) * 28px); }
1705
+ .step-header { display: flex; align-items: center; cursor: pointer; padding: 10px 14px; border-radius: 6px; background-color: #fff; border: 1px solid var(--light-gray-color); transition: background-color 0.2s ease, border-color 0.2s ease, box-shadow 0.2s ease; }
1706
+ .step-header:hover { background-color: #f0f2f5; border-color: var(--medium-gray-color); box-shadow: var(--box-shadow-inset); }
1707
+ .step-icon { margin-right: 12px; width: 20px; text-align: center; font-size: 1.1em; }
1708
+ .step-title { flex: 1; font-size: 1em; }
1709
+ .step-duration { color: var(--dark-gray-color); font-size: 0.9em; }
1710
+ .step-details { display: none; padding: 14px; margin-top: 8px; background: #fdfdfd; border-radius: 6px; font-size: 0.95em; border: 1px solid var(--light-gray-color); }
1711
+ .step-info { margin-bottom: 8px; }
1712
+ .step-error { color: var(--danger-color); margin-top: 12px; padding: 14px; background: rgba(244,67,54,0.05); border-radius: 4px; font-size: 0.95em; border-left: 3px solid var(--danger-color); }
1713
+ .step-error pre.stack-trace { margin-top: 10px; padding: 12px; background-color: rgba(0,0,0,0.03); border-radius: 4px; font-size:0.9em; max-height: 280px; overflow-y: auto; white-space: pre-wrap; word-break: break-all; }
1714
+ .step-hook { background-color: rgba(33,150,243,0.04); border-left: 3px solid var(--info-color) !important; }
1715
+ .step-hook .step-title { font-style: italic; color: var(--info-color)}
1716
+ .nested-steps { margin-top: 12px; }
1717
+ .attachments-section { margin-top: 28px; padding-top: 20px; border-top: 1px solid var(--light-gray-color); }
1718
+ .attachments-section h4 { margin-top: 0; margin-bottom: 20px; font-size: 1.1em; color: var(--text-color); }
1719
+ .attachments-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 22px; }
1720
+ .attachment-item { border: 1px solid var(--border-color); border-radius: var(--border-radius); background-color: #fff; box-shadow: var(--box-shadow-light); overflow: hidden; display: flex; flex-direction: column; transition: transform 0.2s ease-out, box-shadow 0.2s ease-out; }
1721
+ .attachment-item:hover { transform: translateY(-4px); box-shadow: var(--box-shadow); }
1722
+ .attachment-item img { width: 100%; height: 180px; object-fit: cover; display: block; border-bottom: 1px solid var(--border-color); transition: opacity 0.3s ease; }
1723
+ .attachment-info { padding: 12px; margin-top: auto; background-color: #fafafa;}
1724
+ .attachment-item a:hover img { opacity: 0.85; }
1725
+ .attachment-caption { padding: 12px 15px; font-size: 0.9em; text-align: center; color: var(--text-color-secondary); word-break: break-word; background-color: var(--light-gray-color); }
1726
+ .video-item a, .trace-item a { display: block; margin-bottom: 8px; color: var(--primary-color); text-decoration: none; font-weight: 500; }
1727
+ .video-item a:hover, .trace-item a:hover { text-decoration: underline; }
1728
+ .code-section pre { background-color: #2d2d2d; color: #f0f0f0; padding: 20px; border-radius: 6px; overflow-x: auto; font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace; font-size: 0.95em; line-height:1.6;}
1729
+ .trace-actions { display: flex; justify-content: center; }
1730
+ .trace-actions a { text-decoration: none; color: var(--primary-color); font-weight: 500; font-size: 0.9em; }
1731
+ .generic-attachment { text-align: center; padding: 1rem; justify-content: center; }
1732
+ .attachment-icon { font-size: 2.5rem; display: block; margin-bottom: 0.75rem; }
1733
+ .attachment-caption { display: flex; flex-direction: column; }
1734
+ .attachment-name { font-weight: 500; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
1735
+ .attachment-type { font-size: 0.8rem; color: var(--text-color-secondary); }
1736
+ .trend-charts-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(480px, 1fr)); gap: 28px; margin-bottom: 35px; }
1737
+ .test-history-container h2.tab-main-title { font-size: 1.6em; margin-bottom: 18px; color: var(--primary-color); border-bottom: 1px solid var(--border-color); padding-bottom: 12px;}
1738
+ .test-history-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(380px, 1fr)); gap: 22px; margin-top: 22px; }
1739
+ .test-history-card { background: var(--card-background-color); border: 1px solid var(--border-color); border-radius: var(--border-radius); padding: 22px; box-shadow: var(--box-shadow-light); display: flex; flex-direction: column; }
1740
+ .test-history-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; padding-bottom: 14px; border-bottom: 1px solid var(--light-gray-color); }
1741
+ .test-history-header h3 { margin: 0; font-size: 1.15em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } /* This was h3, changed to p for consistency with user file */
1742
+ .test-history-header p { font-weight: 500 } /* Added this */
1743
+ .test-history-trend { margin-bottom: 20px; min-height: 110px; }
1744
+ .test-history-trend div[id^="testHistoryChart-"] { display: block; margin: 0 auto; max-width:100%; height: 100px; width: 320px; }
1745
+ .test-history-details-collapsible summary { cursor: pointer; font-size: 1em; color: var(--primary-color); margin-bottom: 10px; font-weight:500; }
1746
+ .test-history-details-collapsible summary:hover {text-decoration: underline;}
1747
+ .test-history-details table { width: 100%; border-collapse: collapse; font-size: 0.95em; }
1748
+ .test-history-details th, .test-history-details td { padding: 9px 12px; text-align: left; border-bottom: 1px solid var(--light-gray-color); }
1749
+ .test-history-details th { background-color: var(--light-gray-color); font-weight: 600; }
1750
+ .status-badge-small { padding: 3px 7px; border-radius: 4px; font-size: 0.8em; font-weight: 600; color: white; text-transform: uppercase; display: inline-block; }
1751
+ .status-badge-small.status-passed { background-color: var(--success-color); }
1752
+ .status-badge-small.status-failed { background-color: var(--danger-color); }
1753
+ .status-badge-small.status-skipped { background-color: var(--warning-color); }
1754
+ .status-badge-small.status-unknown { background-color: var(--dark-gray-color); }
1755
+ .no-data, .no-tests, .no-steps, .no-data-chart { padding: 28px; text-align: center; color: var(--dark-gray-color); font-style: italic; font-size:1.1em; background-color: var(--light-gray-color); border-radius: var(--border-radius); margin: 18px 0; border: 1px dashed var(--medium-gray-color); }
1756
+ .no-data-chart {font-size: 0.95em; padding: 18px;}
1757
+ #test-ai iframe { border: 1px solid var(--border-color); width: 100%; height: 85vh; border-radius: var(--border-radius); box-shadow: var(--box-shadow-light); }
1758
+ #test-ai p {margin-bottom: 18px; font-size: 1em; color: var(--text-color-secondary);}
1759
+ .trace-preview { padding: 1rem; text-align: center; background: #f5f5f5; border-bottom: 1px solid #e1e1e1; }
1760
+ .trace-icon { font-size: 2rem; display: block; margin-bottom: 0.5rem; }
1761
+ .trace-name { word-break: break-word; font-size: 0.9rem; }
1762
+ .trace-actions { display: flex; gap: 0.5rem; }
1763
+ .trace-actions a { flex: 1; text-align: center; padding: 0.25rem 0.5rem; font-size: 0.85rem; border-radius: 4px; text-decoration: none; background: cornflowerblue; color: aliceblue; }
1764
+ .view-trace { background: #3182ce; color: white; }
1765
+ .view-trace:hover { background: #2c5282; }
1766
+ .download-trace { background: #e2e8f0; color: #2d3748; }
1767
+ .download-trace:hover { background: #cbd5e0; }
1768
+ .filters button.clear-filters-btn { background-color: var(--medium-gray-color); color: var(--text-color); }
1769
+ .filters button.clear-filters-btn:hover { background-color: var(--dark-gray-color); color: #fff; }
1770
+ @media (max-width: 1200px) { .trend-charts-row { grid-template-columns: 1fr; } }
1771
+ @media (max-width: 992px) { .dashboard-bottom-row { grid-template-columns: 1fr; } .pie-chart-wrapper div[id^="pieChart-"] { max-width: 350px; margin: 0 auto; } .filters input { min-width: 180px; } .filters select { min-width: 150px; } }
1772
+ @media (max-width: 768px) { body { font-size: 15px; } .container { margin: 10px; padding: 20px; } .header { flex-direction: column; align-items: flex-start; gap: 15px; } .header h1 { font-size: 1.6em; } .run-info { text-align: left; font-size:0.9em; } .tabs { margin-bottom: 25px;} .tab-button { padding: 12px 20px; font-size: 1.05em;} .dashboard-grid { grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 18px;} .summary-card .value {font-size: 2em;} .summary-card h3 {font-size: 0.95em;} .filters { flex-direction: column; padding: 18px; gap: 12px;} .filters input, .filters select, .filters button {width: 100%; box-sizing: border-box;} .test-case-header { flex-direction: column; align-items: flex-start; gap: 10px; padding: 14px; } .test-case-summary {gap: 10px;} .test-case-title {font-size: 1.05em;} .test-case-meta { flex-direction: row; flex-wrap: wrap; gap: 8px; margin-top: 8px;} .attachments-grid {grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); gap: 18px;} .test-history-grid {grid-template-columns: 1fr;} .pie-chart-wrapper {min-height: auto;} }
1773
+ @media (max-width: 480px) { body {font-size: 14px;} .container {padding: 15px;} .header h1 {font-size: 1.4em;} #report-logo { height: 35px; width: 35px; } .tab-button {padding: 10px 15px; font-size: 1em;} .summary-card .value {font-size: 1.8em;} .attachments-grid {grid-template-columns: 1fr;} .step-item {padding-left: calc(var(--depth, 0) * 18px);} .test-case-content, .step-details {padding: 15px;} .trend-charts-row {gap: 20px;} .trend-chart {padding: 20px;} }
1774
+ </style>
1775
+ </head>
1776
+ <body>
1777
+ <div class="container">
1778
+ <header class="header">
1779
+ <div class="header-title">
1780
+ <img id="report-logo" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCI+PHBhdGggZD0iTTEyIDJMNCA3bDggNSA4LTUtOC01eiIgZmlsbD0iIzNmNTFiNSIvPjxwYXRoIGQ9Ik0xMiA2TDQgMTFsOCA1IDgtNS04LTV6IiBmaWxsPSIjNDI4NWY0Ii8+PHBhdGggZD0iTTEyIDEwbC04IDUgOCA1IDgtNS04LTV6IiBmaWxsPSIjM2Q1NWI0Ii8+PC9zdmc+" alt="Report Logo">
1781
+ <h1>Playwright Pulse Report</h1>
1782
+ </div>
1783
+ <div class="run-info"><strong>Run Date:</strong> ${formatDate(
1784
+ runSummary.timestamp
1785
+ )}<br><strong>Total Duration:</strong> ${formatDuration(
1786
+ runSummary.duration
1787
+ )}</div>
1788
+ </header>
1789
+ <div class="tabs">
1790
+ <button class="tab-button active" data-tab="dashboard">Dashboard</button>
1791
+ <button class="tab-button" data-tab="test-runs">Test Run Summary</button>
1792
+ <button class="tab-button" data-tab="test-history">Test History</button>
1793
+ <button class="tab-button" data-tab="test-ai">AI Analysis</button>
1794
+ </div>
1795
+ <div id="dashboard" class="tab-content active">
1796
+ <div class="dashboard-grid">
1797
+ <div class="summary-card"><h3>Total Tests</h3><div class="value">${
1798
+ runSummary.totalTests
1799
+ }</div></div>
1800
+ <div class="summary-card status-passed"><h3>Passed</h3><div class="value">${
1801
+ runSummary.passed
1802
+ }</div><div class="trend-percentage">${passPercentage}%</div></div>
1803
+ <div class="summary-card status-failed"><h3>Failed</h3><div class="value">${
1804
+ runSummary.failed
1805
+ }</div><div class="trend-percentage">${failPercentage}%</div></div>
1806
+ <div class="summary-card status-skipped"><h3>Skipped</h3><div class="value">${
1807
+ runSummary.skipped || 0
1808
+ }</div><div class="trend-percentage">${skipPercentage}%</div></div>
1809
+ <div class="summary-card"><h3>Avg. Test Time</h3><div class="value">${avgTestDuration}</div></div>
1810
+ <div class="summary-card"><h3>Run Duration</h3><div class="value">${formatDuration(
1811
+ runSummary.duration
1812
+ )}</div></div>
1813
+ </div>
1814
+ <div class="dashboard-bottom-row">
1815
+ <div style="display: grid; gap: 20px">
1816
+ ${generatePieChart(
1817
+ [
1818
+ { label: "Passed", value: runSummary.passed },
1819
+ { label: "Failed", value: runSummary.failed },
1820
+ { label: "Skipped", value: runSummary.skipped || 0 },
1821
+ ],
1822
+ 400,
1823
+ 390
1824
+ )}
1825
+ ${
1826
+ runSummary.environment &&
1827
+ Object.keys(runSummary.environment).length > 0
1828
+ ? generateEnvironmentDashboard(runSummary.environment)
1829
+ : '<div class="no-data">Environment data not available.</div>'
1830
+ }
1831
+ </div>
1832
+ ${generateSuitesWidget(suitesData)}
1833
+ </div>
1834
+ </div>
1835
+ <div id="test-runs" class="tab-content">
1836
+ <div class="filters">
1837
+ <input type="text" id="filter-name" placeholder="Filter by test name/path..." style="border-color: black; border-style: outset;">
1838
+ <select id="filter-status"><option value="">All Statuses</option><option value="passed">Passed</option><option value="failed">Failed</option><option value="skipped">Skipped</option></select>
1839
+ <select id="filter-browser"><option value="">All Browsers</option>${Array.from(
1840
+ new Set(
1841
+ (results || []).map((test) => test.browser || "unknown")
1842
+ )
1843
+ )
1844
+ .map(
1845
+ (browser) =>
1846
+ `<option value="${sanitizeHTML(browser)}">${sanitizeHTML(
1847
+ browser
1848
+ )}</option>`
1849
+ )
1850
+ .join("")}</select>
1851
+ <button id="expand-all-tests">Expand All</button> <button id="collapse-all-tests">Collapse All</button> <button id="clear-run-summary-filters" class="clear-filters-btn">Clear Filters</button>
1852
+ </div>
1853
+ <div class="test-cases-list">${generateTestCasesHTML()}</div>
1854
+ </div>
1855
+ <div id="test-history" class="tab-content">
1856
+ <h2 class="tab-main-title">Execution Trends</h2>
1857
+ <div class="trend-charts-row">
1858
+ <div class="trend-chart"><h3 class="chart-title-header">Test Volume & Outcome Trends</h3>
1859
+ ${
1860
+ trendData && trendData.overall && trendData.overall.length > 0
1861
+ ? generateTestTrendsChart(trendData)
1862
+ : '<div class="no-data">Overall trend data not available for test counts.</div>'
1863
+ }
1864
+ </div>
1865
+ <div class="trend-chart"><h3 class="chart-title-header">Execution Duration Trends</h3>
1866
+ ${
1867
+ trendData && trendData.overall && trendData.overall.length > 0
1868
+ ? generateDurationTrendChart(trendData)
1869
+ : '<div class="no-data">Overall trend data not available for durations.</div>'
1870
+ }
1871
+ </div>
1872
+ </div>
1873
+ <h2 class="tab-main-title">Individual Test History</h2>
1874
+ ${
1875
+ trendData &&
1876
+ trendData.testRuns &&
1877
+ Object.keys(trendData.testRuns).length > 0
1878
+ ? generateTestHistoryContent(trendData)
1879
+ : '<div class="no-data">Individual test history data not available.</div>'
1880
+ }
1881
+ </div>
1882
+ <div id="test-ai" class="tab-content">
1883
+ <iframe data-src="https://ai-test-analyser.netlify.app/" width="100%" height="100%" frameborder="0" allowfullscreen class="lazy-load-iframe" title="AI Test Analyser" style="border: none; height: 100vh;"></iframe>
1884
+ </div>
1885
+ <footer style="padding: 0.5rem; box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05); text-align: center; font-family: 'Segoe UI', system-ui, sans-serif;">
1886
+ <div style="display: inline-flex; align-items: center; gap: 0.5rem; color: #333; font-size: 0.9rem; font-weight: 600; letter-spacing: 0.5px;">
1887
+ <img width="48" height="48" src="https://img.icons8.com/emoji/48/index-pointing-at-the-viewer-light-skin-tone-emoji.png" alt="index-pointing-at-the-viewer-light-skin-tone-emoji"/>
1888
+ <span>Created by</span>
1889
+ <a href="https://github.com/Arghajit47" target="_blank" rel="noopener noreferrer" style="color: #7737BF; font-weight: 700; font-style: italic; text-decoration: none; transition: all 0.2s ease;" onmouseover="this.style.color='#BF5C37'" onmouseout="this.style.color='#7737BF'">Arghajit Singha</a>
1890
+ </div>
1891
+ <div style="margin-top: 0.5rem; font-size: 0.75rem; color: #666;">Crafted with precision</div>
1892
+ </footer>
1893
+ </div>
1894
+ <script>
1895
+ // Ensure formatDuration is globally available
1896
+ if (typeof formatDuration === 'undefined') {
1897
+ function formatDuration(ms) {
1898
+ if (ms === undefined || ms === null || ms < 0) return "0.0s";
1899
+ return (ms / 1000).toFixed(1) + "s";
1900
+ }
1901
+ }
1902
+ function initializeReportInteractivity() {
1903
+ const tabButtons = document.querySelectorAll('.tab-button');
1904
+ const tabContents = document.querySelectorAll('.tab-content');
1905
+ tabButtons.forEach(button => {
1906
+ button.addEventListener('click', () => {
1907
+ tabButtons.forEach(btn => btn.classList.remove('active'));
1908
+ tabContents.forEach(content => content.classList.remove('active'));
1909
+ button.classList.add('active');
1910
+ const tabId = button.getAttribute('data-tab');
1911
+ const activeContent = document.getElementById(tabId);
1912
+ if (activeContent) {
1913
+ activeContent.classList.add('active');
1914
+ // Check if IntersectionObserver is already handling elements in this tab
1915
+ // For simplicity, we assume if an element is observed, it will be handled when it becomes visible.
1916
+ // If IntersectionObserver is not supported, already-visible elements would have been loaded by fallback.
1917
+ }
1918
+ });
1919
+ });
1920
+ // --- Test Run Summary Filters ---
1921
+ const nameFilter = document.getElementById('filter-name');
1922
+ const statusFilter = document.getElementById('filter-status');
1923
+ const browserFilter = document.getElementById('filter-browser');
1924
+ const clearRunSummaryFiltersBtn = document.getElementById('clear-run-summary-filters');
1925
+ function filterTestCases() {
1926
+ const nameValue = nameFilter ? nameFilter.value.toLowerCase() : "";
1927
+ const statusValue = statusFilter ? statusFilter.value : "";
1928
+ const browserValue = browserFilter ? browserFilter.value : "";
1929
+ document.querySelectorAll('#test-runs .test-case').forEach(testCaseElement => {
1930
+ const titleElement = testCaseElement.querySelector('.test-case-title');
1931
+ const fullTestName = titleElement ? titleElement.getAttribute('title').toLowerCase() : "";
1932
+ const status = testCaseElement.getAttribute('data-status');
1933
+ const browser = testCaseElement.getAttribute('data-browser');
1934
+ const nameMatch = fullTestName.includes(nameValue);
1935
+ const statusMatch = !statusValue || status === statusValue;
1936
+ const browserMatch = !browserValue || browser === browserValue;
1937
+ testCaseElement.style.display = (nameMatch && statusMatch && browserMatch) ? '' : 'none';
1938
+ });
1939
+ }
1940
+ if(nameFilter) nameFilter.addEventListener('input', filterTestCases);
1941
+ if(statusFilter) statusFilter.addEventListener('change', filterTestCases);
1942
+ if(browserFilter) browserFilter.addEventListener('change', filterTestCases);
1943
+ if(clearRunSummaryFiltersBtn) clearRunSummaryFiltersBtn.addEventListener('click', () => {
1944
+ if(nameFilter) nameFilter.value = ''; if(statusFilter) statusFilter.value = ''; if(browserFilter) browserFilter.value = '';
1945
+ filterTestCases();
1946
+ });
1947
+ // --- Test History Filters ---
1948
+ const historyNameFilter = document.getElementById('history-filter-name');
1949
+ const historyStatusFilter = document.getElementById('history-filter-status');
1950
+ const clearHistoryFiltersBtn = document.getElementById('clear-history-filters');
1951
+ function filterTestHistoryCards() {
1952
+ const nameValue = historyNameFilter ? historyNameFilter.value.toLowerCase() : "";
1953
+ const statusValue = historyStatusFilter ? historyStatusFilter.value : "";
1954
+ document.querySelectorAll('.test-history-card').forEach(card => {
1955
+ const testTitle = card.getAttribute('data-test-name').toLowerCase();
1956
+ const latestStatus = card.getAttribute('data-latest-status');
1957
+ const nameMatch = testTitle.includes(nameValue);
1958
+ const statusMatch = !statusValue || latestStatus === statusValue;
1959
+ card.style.display = (nameMatch && statusMatch) ? '' : 'none';
1960
+ });
1961
+ }
1962
+ if(historyNameFilter) historyNameFilter.addEventListener('input', filterTestHistoryCards);
1963
+ if(historyStatusFilter) historyStatusFilter.addEventListener('change', filterTestHistoryCards);
1964
+ if(clearHistoryFiltersBtn) clearHistoryFiltersBtn.addEventListener('click', () => {
1965
+ if(historyNameFilter) historyNameFilter.value = ''; if(historyStatusFilter) historyStatusFilter.value = '';
1966
+ filterTestHistoryCards();
1967
+ });
1968
+ // --- Expand/Collapse and Toggle Details Logic ---
1969
+ function toggleElementDetails(headerElement, contentSelector) {
1970
+ let contentElement;
1971
+ if (headerElement.classList.contains('test-case-header')) {
1972
+ contentElement = headerElement.parentElement.querySelector('.test-case-content');
1973
+ } else if (headerElement.classList.contains('step-header')) {
1974
+ contentElement = headerElement.nextElementSibling;
1975
+ if (!contentElement || !contentElement.matches(contentSelector || '.step-details')) {
1976
+ contentElement = null;
1977
+ }
1978
+ }
1979
+ if (contentElement) {
1980
+ const isExpanded = contentElement.style.display === 'block';
1981
+ contentElement.style.display = isExpanded ? 'none' : 'block';
1982
+ headerElement.setAttribute('aria-expanded', String(!isExpanded));
1983
+ }
1984
+ }
1985
+ document.querySelectorAll('#test-runs .test-case-header').forEach(header => {
1986
+ header.addEventListener('click', () => toggleElementDetails(header));
1987
+ });
1988
+ document.querySelectorAll('#test-runs .step-header').forEach(header => {
1989
+ header.addEventListener('click', () => toggleElementDetails(header, '.step-details'));
1990
+ });
1991
+ const expandAllBtn = document.getElementById('expand-all-tests');
1992
+ const collapseAllBtn = document.getElementById('collapse-all-tests');
1993
+ function setAllTestRunDetailsVisibility(displayMode, ariaState) {
1994
+ document.querySelectorAll('#test-runs .test-case-content').forEach(el => el.style.display = displayMode);
1995
+ document.querySelectorAll('#test-runs .step-details').forEach(el => el.style.display = displayMode);
1996
+ document.querySelectorAll('#test-runs .test-case-header[aria-expanded]').forEach(el => el.setAttribute('aria-expanded', ariaState));
1997
+ document.querySelectorAll('#test-runs .step-header[aria-expanded]').forEach(el => el.setAttribute('aria-expanded', ariaState));
1998
+ }
1999
+ if (expandAllBtn) expandAllBtn.addEventListener('click', () => setAllTestRunDetailsVisibility('block', 'true'));
2000
+ if (collapseAllBtn) collapseAllBtn.addEventListener('click', () => setAllTestRunDetailsVisibility('none', 'false'));
2001
+ // --- Intersection Observer for Lazy Loading ---
2002
+ const lazyLoadElements = document.querySelectorAll('.lazy-load-chart, .lazy-load-iframe');
2003
+ if ('IntersectionObserver' in window) {
2004
+ let lazyObserver = new IntersectionObserver((entries, observer) => {
2005
+ entries.forEach(entry => {
2006
+ if (entry.isIntersecting) {
2007
+ const element = entry.target;
2008
+ if (element.classList.contains('lazy-load-iframe')) {
2009
+ if (element.dataset.src) {
2010
+ element.src = element.dataset.src;
2011
+ element.removeAttribute('data-src'); // Optional: remove data-src after loading
2012
+ console.log('Lazy loaded iframe:', element.title || 'Untitled Iframe');
2013
+ }
2014
+ } else if (element.classList.contains('lazy-load-chart')) {
2015
+ const renderFunctionName = element.dataset.renderFunctionName;
2016
+ if (renderFunctionName && typeof window[renderFunctionName] === 'function') {
2017
+ try {
2018
+ console.log('Lazy loading chart with function:', renderFunctionName);
2019
+ window[renderFunctionName](); // Call the render function
2020
+ } catch (e) {
2021
+ console.error(\`Error lazy-loading chart \${element.id} using \${renderFunctionName}:\`, e);
2022
+ element.innerHTML = '<div class="no-data-chart">Error lazy-loading chart.</div>';
2023
+ }
2024
+ } else {
2025
+ console.warn(\`Render function \${renderFunctionName} not found or not a function for chart:\`, element.id);
2026
+ }
2027
+ }
2028
+ observer.unobserve(element); // Important: stop observing once loaded
2029
+ }
2030
+ });
2031
+ }, {
2032
+ rootMargin: "0px 0px 200px 0px" // Start loading when element is 200px from viewport bottom
2033
+ });
2034
+
2035
+ lazyLoadElements.forEach(el => {
2036
+ lazyObserver.observe(el);
2037
+ });
2038
+ } else { // Fallback for browsers without IntersectionObserver
2039
+ console.warn("IntersectionObserver not supported. Loading all items immediately.");
2040
+ lazyLoadElements.forEach(element => {
2041
+ if (element.classList.contains('lazy-load-iframe')) {
2042
+ if (element.dataset.src) {
2043
+ element.src = element.dataset.src;
2044
+ element.removeAttribute('data-src');
2045
+ }
2046
+ } else if (element.classList.contains('lazy-load-chart')) {
2047
+ const renderFunctionName = element.dataset.renderFunctionName;
2048
+ if (renderFunctionName && typeof window[renderFunctionName] === 'function') {
2049
+ try {
2050
+ window[renderFunctionName]();
2051
+ } catch (e) {
2052
+ console.error(\`Error loading chart (fallback) \${element.id} using \${renderFunctionName}:\`, e);
2053
+ element.innerHTML = '<div class="no-data-chart">Error loading chart (fallback).</div>';
2054
+ }
2055
+ }
2056
+ }
2057
+ });
2058
+ }
2059
+ }
2060
+ document.addEventListener('DOMContentLoaded', initializeReportInteractivity);
2061
+
2062
+ function copyErrorToClipboard(button) {
2063
+ // 1. Find the main error container, which should always be present.
2064
+ const errorContainer = button.closest('.step-error');
2065
+ if (!errorContainer) {
2066
+ console.error("Could not find '.step-error' container. The report's HTML structure might have changed.");
2067
+ return;
2068
+ }
2069
+
2070
+ let errorText;
2071
+
2072
+ // 2. First, try to find the preferred .stack-trace element (the "happy path").
2073
+ const stackTraceElement = errorContainer.querySelector('.stack-trace');
2074
+
2075
+ if (stackTraceElement) {
2076
+ // If it exists, use its text content. This handles standard assertion errors.
2077
+ errorText = stackTraceElement.textContent;
2078
+ } else {
2079
+ // 3. FALLBACK: If .stack-trace doesn't exist, this is likely an unstructured error.
2080
+ // We clone the container to avoid manipulating the live DOM or copying the button's own text.
2081
+ const clonedContainer = errorContainer.cloneNode(true);
2082
+
2083
+ // Remove the button from our clone before extracting the text.
2084
+ const buttonInClone = clonedContainer.querySelector('button');
2085
+ if (buttonInClone) {
2086
+ buttonInClone.remove();
2087
+ }
2088
+
2089
+ // Use the text content of the cleaned container as the fallback.
2090
+ errorText = clonedContainer.textContent;
2091
+ }
2092
+
2093
+ // 4. Proceed with the clipboard logic, ensuring text is not null and is trimmed.
2094
+ if (!errorText) {
2095
+ console.error('Could not extract error text.');
2096
+ button.textContent = 'Nothing to copy';
2097
+ setTimeout(() => { button.textContent = 'Copy Error'; }, 2000);
2098
+ return;
2099
+ }
2100
+
2101
+ const textarea = document.createElement('textarea');
2102
+ textarea.value = errorText.trim(); // Trim whitespace for a cleaner copy.
2103
+ textarea.style.position = 'fixed'; // Prevent screen scroll
2104
+ textarea.style.top = '-9999px';
2105
+ document.body.appendChild(textarea);
2106
+ textarea.select();
2107
+
2108
+ try {
2109
+ const successful = document.execCommand('copy');
2110
+ const originalText = button.textContent;
2111
+ button.textContent = successful ? 'Copied!' : 'Failed';
2112
+ setTimeout(() => {
2113
+ button.textContent = originalText;
2114
+ }, 2000);
2115
+ } catch (err) {
2116
+ console.error('Failed to copy: ', err);
2117
+ button.textContent = 'Failed';
2118
+ }
2119
+
2120
+ document.body.removeChild(textarea);
2121
+ }
2122
+ </script>
2123
+ </body>
2124
+ </html>
2125
+ `;
2126
+ }
2127
+ async function runScript(scriptPath) {
2128
+ return new Promise((resolve, reject) => {
2129
+ console.log(chalk.blue(`Executing script: ${scriptPath}...`));
2130
+ const process = fork(scriptPath, [], {
2131
+ stdio: "inherit",
2132
+ });
2133
+
2134
+ process.on("error", (err) => {
2135
+ console.error(chalk.red(`Failed to start script: ${scriptPath}`), err);
2136
+ reject(err);
2137
+ });
2138
+
2139
+ process.on("exit", (code) => {
2140
+ if (code === 0) {
2141
+ console.log(chalk.green(`Script ${scriptPath} finished successfully.`));
2142
+ resolve();
2143
+ } else {
2144
+ const errorMessage = `Script ${scriptPath} exited with code ${code}.`;
2145
+ console.error(chalk.red(errorMessage));
2146
+ reject(new Error(errorMessage));
2147
+ }
2148
+ });
2149
+ });
2150
+ }
2151
+ async function main() {
2152
+ const __filename = fileURLToPath(import.meta.url);
2153
+ const __dirname = path.dirname(__filename);
2154
+
2155
+ // Script to archive current run to JSON history (this is your modified "generate-trend.mjs")
2156
+ const archiveRunScriptPath = path.resolve(
2157
+ __dirname,
2158
+ "generate-trend.mjs" // Keeping the filename as per your request
2159
+ );
2160
+
2161
+ const outputDir = path.resolve(process.cwd(), DEFAULT_OUTPUT_DIR);
2162
+ const reportJsonPath = path.resolve(outputDir, DEFAULT_JSON_FILE); // Current run's main JSON
2163
+ const reportHtmlPath = path.resolve(outputDir, DEFAULT_HTML_FILE);
2164
+
2165
+ const historyDir = path.join(outputDir, "history"); // Directory for historical JSON files
2166
+ const HISTORY_FILE_PREFIX = "trend-"; // Match prefix used in archiving script
2167
+ const MAX_HISTORY_FILES_TO_LOAD_FOR_REPORT = 15; // How many historical runs to show in the report
2168
+
2169
+ console.log(chalk.blue(`Starting static HTML report generation...`));
2170
+ console.log(chalk.blue(`Output directory set to: ${outputDir}`));
2171
+
2172
+ // Step 1: Ensure current run data is archived to the history folder
2173
+ try {
2174
+ await runScript(archiveRunScriptPath); // This script now handles JSON history
2175
+ console.log(
2176
+ chalk.green("Current run data archiving to history completed.")
2177
+ );
2178
+ } catch (error) {
2179
+ console.error(
2180
+ chalk.red(
2181
+ "Failed to archive current run data. Report might use stale or incomplete historical trends."
2182
+ ),
2183
+ error
2184
+ );
2185
+ }
2186
+
2187
+ // Step 2: Load current run's data (for non-trend sections of the report)
2188
+ let currentRunReportData;
2189
+ try {
2190
+ const jsonData = await fs.readFile(reportJsonPath, "utf-8");
2191
+ currentRunReportData = JSON.parse(jsonData);
2192
+ if (
2193
+ !currentRunReportData ||
2194
+ typeof currentRunReportData !== "object" ||
2195
+ !currentRunReportData.results
2196
+ ) {
2197
+ throw new Error(
2198
+ "Invalid report JSON structure. 'results' field is missing or invalid."
2199
+ );
2200
+ }
2201
+ if (!Array.isArray(currentRunReportData.results)) {
2202
+ currentRunReportData.results = [];
2203
+ console.warn(
2204
+ chalk.yellow(
2205
+ "Warning: 'results' field in current run JSON was not an array. Treated as empty."
2206
+ )
2207
+ );
2208
+ }
2209
+ } catch (error) {
2210
+ console.error(
2211
+ chalk.red(
2212
+ `Critical Error: Could not read or parse main report JSON at ${reportJsonPath}: ${error.message}`
2213
+ )
2214
+ );
2215
+ process.exit(1);
2216
+ }
2217
+
2218
+ // Step 3: Load historical data for trends
2219
+ let historicalRuns = [];
2220
+ try {
2221
+ await fs.access(historyDir);
2222
+ const allHistoryFiles = await fs.readdir(historyDir);
2223
+
2224
+ const jsonHistoryFiles = allHistoryFiles
2225
+ .filter(
2226
+ (file) => file.startsWith(HISTORY_FILE_PREFIX) && file.endsWith(".json")
2227
+ )
2228
+ .map((file) => {
2229
+ const timestampPart = file
2230
+ .replace(HISTORY_FILE_PREFIX, "")
2231
+ .replace(".json", "");
2232
+ return {
2233
+ name: file,
2234
+ path: path.join(historyDir, file),
2235
+ timestamp: parseInt(timestampPart, 10),
2236
+ };
2237
+ })
2238
+ .filter((file) => !isNaN(file.timestamp))
2239
+ .sort((a, b) => b.timestamp - a.timestamp);
2240
+
2241
+ const filesToLoadForTrend = jsonHistoryFiles.slice(
2242
+ 0,
2243
+ MAX_HISTORY_FILES_TO_LOAD_FOR_REPORT
2244
+ );
2245
+
2246
+ for (const fileMeta of filesToLoadForTrend) {
2247
+ try {
2248
+ const fileContent = await fs.readFile(fileMeta.path, "utf-8");
2249
+ const runJsonData = JSON.parse(fileContent);
2250
+ historicalRuns.push(runJsonData);
2251
+ } catch (fileReadError) {
2252
+ console.warn(
2253
+ chalk.yellow(
2254
+ `Could not read/parse history file ${fileMeta.name}: ${fileReadError.message}`
2255
+ )
2256
+ );
2257
+ }
2258
+ }
2259
+ historicalRuns.reverse(); // Oldest first for charts
2260
+ console.log(
2261
+ chalk.green(
2262
+ `Loaded ${historicalRuns.length} historical run(s) for trend analysis.`
2263
+ )
2264
+ );
2265
+ } catch (error) {
2266
+ if (error.code === "ENOENT") {
2267
+ console.warn(
2268
+ chalk.yellow(
2269
+ `History directory '${historyDir}' not found. No historical trends will be displayed.`
2270
+ )
2271
+ );
2272
+ } else {
2273
+ console.warn(
2274
+ chalk.yellow(
2275
+ `Error loading historical data from '${historyDir}': ${error.message}`
2276
+ )
2277
+ );
2278
+ }
2279
+ }
2280
+
2281
+ // Step 4: Prepare trendData object
2282
+ const trendData = {
2283
+ overall: [],
2284
+ testRuns: {},
2285
+ };
2286
+
2287
+ if (historicalRuns.length > 0) {
2288
+ historicalRuns.forEach((histRunReport) => {
2289
+ if (histRunReport.run) {
2290
+ const runTimestamp = new Date(histRunReport.run.timestamp);
2291
+ trendData.overall.push({
2292
+ runId: runTimestamp.getTime(),
2293
+ timestamp: runTimestamp,
2294
+ duration: histRunReport.run.duration,
2295
+ totalTests: histRunReport.run.totalTests,
2296
+ passed: histRunReport.run.passed,
2297
+ failed: histRunReport.run.failed,
2298
+ skipped: histRunReport.run.skipped || 0,
2299
+ });
2300
+
2301
+ if (histRunReport.results && Array.isArray(histRunReport.results)) {
2302
+ const runKeyForTestHistory = `test run ${runTimestamp.getTime()}`;
2303
+ trendData.testRuns[runKeyForTestHistory] = histRunReport.results.map(
2304
+ (test) => ({
2305
+ testName: test.name,
2306
+ duration: test.duration,
2307
+ status: test.status,
2308
+ timestamp: new Date(test.startTime),
2309
+ })
2310
+ );
2311
+ }
2312
+ }
2313
+ });
2314
+ trendData.overall.sort(
2315
+ (a, b) => a.timestamp.getTime() - b.timestamp.getTime()
2316
+ );
2317
+ }
2318
+
2319
+ // Step 5: Generate and write HTML
2320
+ try {
2321
+ const htmlContent = generateHTML(currentRunReportData, trendData);
2322
+ await fs.writeFile(reportHtmlPath, htmlContent, "utf-8");
2323
+ console.log(
2324
+ chalk.green.bold(
2325
+ `🎉 Pulse report generated successfully at: ${reportHtmlPath}`
2326
+ )
2327
+ );
2328
+ console.log(chalk.gray(`(You can open this file in your browser)`));
2329
+ } catch (error) {
2330
+ console.error(chalk.red(`Error generating HTML report: ${error.message}`));
2331
+ console.error(chalk.red(error.stack));
2332
+ process.exit(1);
2333
+ }
2334
+ }
2335
+ main().catch((err) => {
2336
+ console.error(
2337
+ chalk.red.bold(`Unhandled error during script execution: ${err.message}`)
2338
+ );
2339
+ console.error(err.stack);
2340
+ process.exit(1);
2341
+ });