patchright-bun 1.58.0 → 1.58.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (180) hide show
  1. package/README.md +225 -225
  2. package/ThirdPartyNotices.txt +5041 -5041
  3. package/cli.js +19 -19
  4. package/index.d.ts +17 -17
  5. package/index.js +17 -17
  6. package/index.mjs +18 -18
  7. package/jsx-runtime.js +42 -42
  8. package/jsx-runtime.mjs +21 -21
  9. package/lib/agents/agentParser.js +89 -89
  10. package/lib/agents/copilot-setup-steps.yml +34 -34
  11. package/lib/agents/generateAgents.js +348 -348
  12. package/lib/agents/playwright-test-coverage.prompt.md +31 -31
  13. package/lib/agents/playwright-test-generate.prompt.md +8 -8
  14. package/lib/agents/playwright-test-generator.agent.md +88 -88
  15. package/lib/agents/playwright-test-heal.prompt.md +6 -6
  16. package/lib/agents/playwright-test-healer.agent.md +55 -55
  17. package/lib/agents/playwright-test-plan.prompt.md +9 -9
  18. package/lib/agents/playwright-test-planner.agent.md +73 -73
  19. package/lib/common/config.js +282 -282
  20. package/lib/common/configLoader.js +344 -344
  21. package/lib/common/esmLoaderHost.js +104 -104
  22. package/lib/common/expectBundle.js +28 -28
  23. package/lib/common/expectBundleImpl.js +407 -407
  24. package/lib/common/fixtures.js +302 -302
  25. package/lib/common/globals.js +58 -58
  26. package/lib/common/ipc.js +60 -60
  27. package/lib/common/poolBuilder.js +85 -85
  28. package/lib/common/process.js +132 -132
  29. package/lib/common/suiteUtils.js +140 -140
  30. package/lib/common/test.js +321 -321
  31. package/lib/common/testLoader.js +101 -101
  32. package/lib/common/testType.js +298 -298
  33. package/lib/common/validators.js +68 -68
  34. package/lib/fsWatcher.js +67 -67
  35. package/lib/index.js +726 -726
  36. package/lib/internalsForTest.js +42 -42
  37. package/lib/isomorphic/events.js +77 -77
  38. package/lib/isomorphic/folders.js +30 -30
  39. package/lib/isomorphic/stringInternPool.js +69 -69
  40. package/lib/isomorphic/teleReceiver.js +521 -521
  41. package/lib/isomorphic/teleSuiteUpdater.js +157 -157
  42. package/lib/isomorphic/testServerConnection.js +225 -225
  43. package/lib/isomorphic/testServerInterface.js +16 -16
  44. package/lib/isomorphic/testTree.js +329 -329
  45. package/lib/isomorphic/types.d.js +16 -16
  46. package/lib/loader/loaderMain.js +59 -59
  47. package/lib/matchers/expect.js +311 -311
  48. package/lib/matchers/matcherHint.js +44 -44
  49. package/lib/matchers/matchers.js +383 -383
  50. package/lib/matchers/toBeTruthy.js +75 -75
  51. package/lib/matchers/toEqual.js +100 -100
  52. package/lib/matchers/toHaveURL.js +101 -101
  53. package/lib/matchers/toMatchAriaSnapshot.js +159 -159
  54. package/lib/matchers/toMatchSnapshot.js +342 -342
  55. package/lib/matchers/toMatchText.js +99 -99
  56. package/lib/mcp/browser/browserContextFactory.js +329 -329
  57. package/lib/mcp/browser/browserServerBackend.js +84 -84
  58. package/lib/mcp/browser/config.js +421 -421
  59. package/lib/mcp/browser/context.js +244 -244
  60. package/lib/mcp/browser/response.js +278 -278
  61. package/lib/mcp/browser/sessionLog.js +75 -75
  62. package/lib/mcp/browser/tab.js +343 -343
  63. package/lib/mcp/browser/tools/common.js +65 -65
  64. package/lib/mcp/browser/tools/console.js +46 -46
  65. package/lib/mcp/browser/tools/dialogs.js +60 -60
  66. package/lib/mcp/browser/tools/evaluate.js +61 -61
  67. package/lib/mcp/browser/tools/files.js +58 -58
  68. package/lib/mcp/browser/tools/form.js +63 -63
  69. package/lib/mcp/browser/tools/install.js +72 -72
  70. package/lib/mcp/browser/tools/keyboard.js +107 -107
  71. package/lib/mcp/browser/tools/mouse.js +107 -107
  72. package/lib/mcp/browser/tools/navigate.js +71 -71
  73. package/lib/mcp/browser/tools/network.js +63 -63
  74. package/lib/mcp/browser/tools/open.js +57 -57
  75. package/lib/mcp/browser/tools/pdf.js +49 -49
  76. package/lib/mcp/browser/tools/runCode.js +78 -78
  77. package/lib/mcp/browser/tools/screenshot.js +93 -93
  78. package/lib/mcp/browser/tools/snapshot.js +173 -173
  79. package/lib/mcp/browser/tools/tabs.js +67 -67
  80. package/lib/mcp/browser/tools/tool.js +47 -47
  81. package/lib/mcp/browser/tools/tracing.js +74 -74
  82. package/lib/mcp/browser/tools/utils.js +94 -94
  83. package/lib/mcp/browser/tools/verify.js +143 -143
  84. package/lib/mcp/browser/tools/wait.js +63 -63
  85. package/lib/mcp/browser/tools.js +84 -84
  86. package/lib/mcp/browser/watchdog.js +44 -44
  87. package/lib/mcp/config.d.js +16 -16
  88. package/lib/mcp/extension/cdpRelay.js +351 -351
  89. package/lib/mcp/extension/extensionContextFactory.js +76 -76
  90. package/lib/mcp/extension/protocol.js +28 -28
  91. package/lib/mcp/index.js +61 -61
  92. package/lib/mcp/log.js +35 -35
  93. package/lib/mcp/program.js +111 -111
  94. package/lib/mcp/sdk/exports.js +28 -28
  95. package/lib/mcp/sdk/http.js +152 -152
  96. package/lib/mcp/sdk/inProcessTransport.js +71 -71
  97. package/lib/mcp/sdk/server.js +223 -223
  98. package/lib/mcp/sdk/tool.js +47 -47
  99. package/lib/mcp/terminal/cli.js +296 -296
  100. package/lib/mcp/terminal/command.js +56 -56
  101. package/lib/mcp/terminal/commands.js +333 -333
  102. package/lib/mcp/terminal/daemon.js +129 -129
  103. package/lib/mcp/terminal/help.json +31 -31
  104. package/lib/mcp/terminal/helpGenerator.js +88 -88
  105. package/lib/mcp/terminal/socketConnection.js +80 -80
  106. package/lib/mcp/test/browserBackend.js +98 -98
  107. package/lib/mcp/test/generatorTools.js +122 -122
  108. package/lib/mcp/test/plannerTools.js +145 -145
  109. package/lib/mcp/test/seed.js +82 -82
  110. package/lib/mcp/test/streams.js +44 -44
  111. package/lib/mcp/test/testBackend.js +99 -99
  112. package/lib/mcp/test/testContext.js +285 -285
  113. package/lib/mcp/test/testTool.js +30 -30
  114. package/lib/mcp/test/testTools.js +108 -108
  115. package/lib/plugins/gitCommitInfoPlugin.js +198 -198
  116. package/lib/plugins/index.js +28 -28
  117. package/lib/plugins/webServerPlugin.js +237 -237
  118. package/lib/program.js +417 -417
  119. package/lib/reporters/base.js +634 -634
  120. package/lib/reporters/blob.js +138 -138
  121. package/lib/reporters/dot.js +99 -99
  122. package/lib/reporters/empty.js +32 -32
  123. package/lib/reporters/github.js +128 -128
  124. package/lib/reporters/html.js +633 -633
  125. package/lib/reporters/internalReporter.js +138 -138
  126. package/lib/reporters/json.js +254 -254
  127. package/lib/reporters/junit.js +232 -232
  128. package/lib/reporters/line.js +131 -131
  129. package/lib/reporters/list.js +253 -253
  130. package/lib/reporters/listModeReporter.js +69 -69
  131. package/lib/reporters/markdown.js +144 -144
  132. package/lib/reporters/merge.js +558 -558
  133. package/lib/reporters/multiplexer.js +112 -112
  134. package/lib/reporters/reporterV2.js +102 -102
  135. package/lib/reporters/teleEmitter.js +317 -317
  136. package/lib/reporters/versions/blobV1.js +16 -16
  137. package/lib/runner/dispatcher.js +530 -530
  138. package/lib/runner/failureTracker.js +72 -72
  139. package/lib/runner/lastRun.js +77 -77
  140. package/lib/runner/loadUtils.js +334 -334
  141. package/lib/runner/loaderHost.js +89 -89
  142. package/lib/runner/processHost.js +180 -180
  143. package/lib/runner/projectUtils.js +241 -241
  144. package/lib/runner/rebase.js +189 -189
  145. package/lib/runner/reporters.js +138 -138
  146. package/lib/runner/sigIntWatcher.js +96 -96
  147. package/lib/runner/storage.js +91 -91
  148. package/lib/runner/taskRunner.js +127 -127
  149. package/lib/runner/tasks.js +410 -410
  150. package/lib/runner/testGroups.js +125 -125
  151. package/lib/runner/testRunner.js +398 -398
  152. package/lib/runner/testServer.js +269 -269
  153. package/lib/runner/uiModeReporter.js +30 -30
  154. package/lib/runner/vcs.js +72 -72
  155. package/lib/runner/watchMode.js +396 -396
  156. package/lib/runner/workerHost.js +104 -104
  157. package/lib/third_party/pirates.js +62 -62
  158. package/lib/third_party/tsconfig-loader.js +103 -103
  159. package/lib/transform/babelBundle.js +46 -46
  160. package/lib/transform/babelBundleImpl.js +461 -461
  161. package/lib/transform/compilationCache.js +274 -274
  162. package/lib/transform/esmLoader.js +103 -103
  163. package/lib/transform/md.js +221 -221
  164. package/lib/transform/portTransport.js +67 -67
  165. package/lib/transform/transform.js +303 -303
  166. package/lib/util.js +400 -400
  167. package/lib/utilsBundle.js +50 -50
  168. package/lib/utilsBundleImpl.js +103 -103
  169. package/lib/worker/fixtureRunner.js +262 -262
  170. package/lib/worker/testInfo.js +536 -536
  171. package/lib/worker/testTracing.js +345 -345
  172. package/lib/worker/timeoutManager.js +174 -174
  173. package/lib/worker/util.js +31 -31
  174. package/lib/worker/workerMain.js +530 -530
  175. package/package.json +2 -2
  176. package/test.d.ts +18 -18
  177. package/test.js +24 -24
  178. package/test.mjs +34 -34
  179. package/types/test.d.ts +10251 -10251
  180. package/types/testReporter.d.ts +822 -822
@@ -1,633 +1,633 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- var html_exports = {};
30
- __export(html_exports, {
31
- default: () => html_default,
32
- showHTMLReport: () => showHTMLReport,
33
- startHtmlReportServer: () => startHtmlReportServer
34
- });
35
- module.exports = __toCommonJS(html_exports);
36
- var import_fs = __toESM(require("fs"));
37
- var import_path = __toESM(require("path"));
38
- var import_stream = require("stream");
39
- var import_utils = require("patchright-core/lib/utils");
40
- var import_utils2 = require("patchright-core/lib/utils");
41
- var import_utilsBundle = require("patchright-core/lib/utilsBundle");
42
- var import_utilsBundle2 = require("patchright-core/lib/utilsBundle");
43
- var import_zipBundle = require("patchright-core/lib/zipBundle");
44
- var import_base = require("./base");
45
- var import_babelBundle = require("../transform/babelBundle");
46
- var import_util = require("../util");
47
- const htmlReportOptions = ["always", "never", "on-failure"];
48
- const isHtmlReportOption = (type) => {
49
- return htmlReportOptions.includes(type);
50
- };
51
- class HtmlReporter {
52
- constructor(options) {
53
- this._topLevelErrors = [];
54
- this._machines = [];
55
- this._options = options;
56
- }
57
- version() {
58
- return "v2";
59
- }
60
- printsToStdio() {
61
- return false;
62
- }
63
- onConfigure(config) {
64
- this.config = config;
65
- }
66
- onBegin(suite) {
67
- const { outputFolder, open: open2, attachmentsBaseURL, host, port } = this._resolveOptions();
68
- this._outputFolder = outputFolder;
69
- this._open = open2;
70
- this._host = host;
71
- this._port = port;
72
- this._attachmentsBaseURL = attachmentsBaseURL;
73
- const reportedWarnings = /* @__PURE__ */ new Set();
74
- for (const project of this.config.projects) {
75
- if (this._isSubdirectory(outputFolder, project.outputDir) || this._isSubdirectory(project.outputDir, outputFolder)) {
76
- const key = outputFolder + "|" + project.outputDir;
77
- if (reportedWarnings.has(key))
78
- continue;
79
- reportedWarnings.add(key);
80
- writeLine(import_utils2.colors.red(`Configuration Error: HTML reporter output folder clashes with the tests output folder:`));
81
- writeLine(`
82
- html reporter folder: ${import_utils2.colors.bold(outputFolder)}
83
- test results folder: ${import_utils2.colors.bold(project.outputDir)}`);
84
- writeLine("");
85
- writeLine(`HTML reporter will clear its output directory prior to being generated, which will lead to the artifact loss.
86
- `);
87
- }
88
- }
89
- this.suite = suite;
90
- }
91
- _resolveOptions() {
92
- const outputFolder = reportFolderFromEnv() ?? (0, import_util.resolveReporterOutputPath)("playwright-report", this._options.configDir, this._options.outputFolder);
93
- return {
94
- outputFolder,
95
- open: getHtmlReportOptionProcessEnv() || this._options.open || "on-failure",
96
- attachmentsBaseURL: process.env.PLAYWRIGHT_HTML_ATTACHMENTS_BASE_URL || this._options.attachmentsBaseURL || "data/",
97
- host: process.env.PLAYWRIGHT_HTML_HOST || this._options.host,
98
- port: process.env.PLAYWRIGHT_HTML_PORT ? +process.env.PLAYWRIGHT_HTML_PORT : this._options.port
99
- };
100
- }
101
- _isSubdirectory(parentDir, dir) {
102
- const relativePath = import_path.default.relative(parentDir, dir);
103
- return !!relativePath && !relativePath.startsWith("..") && !import_path.default.isAbsolute(relativePath);
104
- }
105
- onError(error) {
106
- this._topLevelErrors.push(error);
107
- }
108
- onMachineEnd(result) {
109
- this._machines.push(result);
110
- }
111
- async onEnd(result) {
112
- const projectSuites = this.suite.suites;
113
- await (0, import_utils.removeFolders)([this._outputFolder]);
114
- let noSnippets;
115
- if (process.env.PLAYWRIGHT_HTML_NO_SNIPPETS === "false" || process.env.PLAYWRIGHT_HTML_NO_SNIPPETS === "0")
116
- noSnippets = false;
117
- else if (process.env.PLAYWRIGHT_HTML_NO_SNIPPETS)
118
- noSnippets = true;
119
- noSnippets = noSnippets || this._options.noSnippets;
120
- let noCopyPrompt;
121
- if (process.env.PLAYWRIGHT_HTML_NO_COPY_PROMPT === "false" || process.env.PLAYWRIGHT_HTML_NO_COPY_PROMPT === "0")
122
- noCopyPrompt = false;
123
- else if (process.env.PLAYWRIGHT_HTML_NO_COPY_PROMPT)
124
- noCopyPrompt = true;
125
- noCopyPrompt = noCopyPrompt || this._options.noCopyPrompt;
126
- const builder = new HtmlBuilder(this.config, this._outputFolder, this._attachmentsBaseURL, {
127
- title: process.env.PLAYWRIGHT_HTML_TITLE || this._options.title,
128
- noSnippets,
129
- noCopyPrompt
130
- });
131
- this._buildResult = await builder.build(this.config.metadata, projectSuites, result, this._topLevelErrors, this._machines);
132
- }
133
- async onExit() {
134
- if (process.env.CI || !this._buildResult)
135
- return;
136
- const { ok, singleTestId } = this._buildResult;
137
- const shouldOpen = !!process.stdin.isTTY && (this._open === "always" || !ok && this._open === "on-failure");
138
- if (shouldOpen) {
139
- await showHTMLReport(this._outputFolder, this._host, this._port, singleTestId);
140
- } else if (this._options._mode === "test" && !!process.stdin.isTTY) {
141
- const packageManagerCommand = (0, import_utils.getPackageManagerExecCommand)();
142
- const relativeReportPath = this._outputFolder === standaloneDefaultFolder() ? "" : " " + import_path.default.relative(process.cwd(), this._outputFolder);
143
- const hostArg = this._host ? ` --host ${this._host}` : "";
144
- const portArg = this._port ? ` --port ${this._port}` : "";
145
- writeLine("");
146
- writeLine("To open last HTML report run:");
147
- writeLine(import_utils2.colors.cyan(`
148
- ${packageManagerCommand} playwright show-report${relativeReportPath}${hostArg}${portArg}
149
- `));
150
- }
151
- }
152
- }
153
- function reportFolderFromEnv() {
154
- const envValue = process.env.PLAYWRIGHT_HTML_OUTPUT_DIR || process.env.PLAYWRIGHT_HTML_REPORT;
155
- return envValue ? import_path.default.resolve(envValue) : void 0;
156
- }
157
- function getHtmlReportOptionProcessEnv() {
158
- const htmlOpenEnv = process.env.PLAYWRIGHT_HTML_OPEN || process.env.PW_TEST_HTML_REPORT_OPEN;
159
- if (!htmlOpenEnv)
160
- return void 0;
161
- if (!isHtmlReportOption(htmlOpenEnv)) {
162
- writeLine(import_utils2.colors.red(`Configuration Error: HTML reporter Invalid value for PLAYWRIGHT_HTML_OPEN: ${htmlOpenEnv}. Valid values are: ${htmlReportOptions.join(", ")}`));
163
- return void 0;
164
- }
165
- return htmlOpenEnv;
166
- }
167
- function standaloneDefaultFolder() {
168
- return reportFolderFromEnv() ?? (0, import_util.resolveReporterOutputPath)("playwright-report", process.cwd(), void 0);
169
- }
170
- async function showHTMLReport(reportFolder, host = "localhost", port, testId) {
171
- const folder = reportFolder ?? standaloneDefaultFolder();
172
- try {
173
- (0, import_utils.assert)(import_fs.default.statSync(folder).isDirectory());
174
- } catch (e) {
175
- writeLine(import_utils2.colors.red(`No report found at "${folder}"`));
176
- (0, import_utils.gracefullyProcessExitDoNotHang)(1);
177
- return;
178
- }
179
- const server = startHtmlReportServer(folder);
180
- await server.start({ port, host, preferredPort: port ? void 0 : 9323 });
181
- let url = server.urlPrefix("human-readable");
182
- writeLine("");
183
- writeLine(import_utils2.colors.cyan(` Serving HTML report at ${url}. Press Ctrl+C to quit.`));
184
- if (testId)
185
- url += `#?testId=${testId}`;
186
- url = url.replace("0.0.0.0", "localhost");
187
- await (0, import_utilsBundle.open)(url, { wait: true }).catch(() => {
188
- });
189
- await new Promise(() => {
190
- });
191
- }
192
- function startHtmlReportServer(folder) {
193
- const server = new import_utils.HttpServer();
194
- server.routePrefix("/", (request, response) => {
195
- let relativePath = new URL("http://localhost" + request.url).pathname;
196
- if (relativePath.startsWith("/trace/file")) {
197
- const url = new URL("http://localhost" + request.url);
198
- try {
199
- return server.serveFile(request, response, url.searchParams.get("path"));
200
- } catch (e) {
201
- return false;
202
- }
203
- }
204
- if (relativePath === "/")
205
- relativePath = "/index.html";
206
- const absolutePath = import_path.default.join(folder, ...relativePath.split("/"));
207
- return server.serveFile(request, response, absolutePath);
208
- });
209
- return server;
210
- }
211
- class HtmlBuilder {
212
- constructor(config, outputDir, attachmentsBaseURL, options) {
213
- this._stepsInFile = new import_utils.MultiMap();
214
- this._hasTraces = false;
215
- this._config = config;
216
- this._reportFolder = outputDir;
217
- this._options = options;
218
- import_fs.default.mkdirSync(this._reportFolder, { recursive: true });
219
- this._dataZipFile = new import_zipBundle.yazl.ZipFile();
220
- this._attachmentsBaseURL = attachmentsBaseURL;
221
- }
222
- async build(metadata, projectSuites, result, topLevelErrors, machines) {
223
- const data = /* @__PURE__ */ new Map();
224
- for (const projectSuite of projectSuites) {
225
- const projectName = projectSuite.project().name;
226
- for (const fileSuite of projectSuite.suites) {
227
- const fileName = this._relativeLocation(fileSuite.location).file;
228
- this._createEntryForSuite(data, projectName, fileSuite, fileName, true);
229
- }
230
- }
231
- if (!this._options.noSnippets)
232
- createSnippets(this._stepsInFile);
233
- let ok = true;
234
- for (const [fileId, { testFile, testFileSummary }] of data) {
235
- const stats = testFileSummary.stats;
236
- for (const test of testFileSummary.tests) {
237
- if (test.outcome === "expected")
238
- ++stats.expected;
239
- if (test.outcome === "skipped")
240
- ++stats.skipped;
241
- if (test.outcome === "unexpected")
242
- ++stats.unexpected;
243
- if (test.outcome === "flaky")
244
- ++stats.flaky;
245
- ++stats.total;
246
- }
247
- stats.ok = stats.unexpected + stats.flaky === 0;
248
- if (!stats.ok)
249
- ok = false;
250
- const testCaseSummaryComparator = (t1, t2) => {
251
- const w1 = (t1.outcome === "unexpected" ? 1e3 : 0) + (t1.outcome === "flaky" ? 1 : 0);
252
- const w2 = (t2.outcome === "unexpected" ? 1e3 : 0) + (t2.outcome === "flaky" ? 1 : 0);
253
- return w2 - w1;
254
- };
255
- testFileSummary.tests.sort(testCaseSummaryComparator);
256
- this._addDataFile(fileId + ".json", testFile);
257
- }
258
- const htmlReport = {
259
- metadata,
260
- startTime: result.startTime.getTime(),
261
- duration: result.duration,
262
- files: [...data.values()].map((e) => e.testFileSummary),
263
- projectNames: projectSuites.map((r) => r.project().name),
264
- stats: { ...[...data.values()].reduce((a, e) => addStats(a, e.testFileSummary.stats), emptyStats()) },
265
- errors: topLevelErrors.map((error) => (0, import_base.formatError)(import_base.internalScreen, error).message),
266
- options: this._options,
267
- machines: machines.map((s) => ({
268
- duration: s.duration,
269
- startTime: s.startTime.getTime(),
270
- tag: s.tag,
271
- shardIndex: s.shardIndex
272
- }))
273
- };
274
- htmlReport.files.sort((f1, f2) => {
275
- const w1 = f1.stats.unexpected * 1e3 + f1.stats.flaky;
276
- const w2 = f2.stats.unexpected * 1e3 + f2.stats.flaky;
277
- return w2 - w1;
278
- });
279
- this._addDataFile("report.json", htmlReport);
280
- let singleTestId;
281
- if (htmlReport.stats.total === 1) {
282
- const testFile = data.values().next().value.testFile;
283
- singleTestId = testFile.tests[0].testId;
284
- }
285
- const appFolder = import_path.default.join(require.resolve("patchright-core"), "..", "lib", "vite", "htmlReport");
286
- await (0, import_utils.copyFileAndMakeWritable)(import_path.default.join(appFolder, "index.html"), import_path.default.join(this._reportFolder, "index.html"));
287
- if (this._hasTraces) {
288
- const traceViewerFolder = import_path.default.join(require.resolve("patchright-core"), "..", "lib", "vite", "traceViewer");
289
- const traceViewerTargetFolder = import_path.default.join(this._reportFolder, "trace");
290
- const traceViewerAssetsTargetFolder = import_path.default.join(traceViewerTargetFolder, "assets");
291
- import_fs.default.mkdirSync(traceViewerAssetsTargetFolder, { recursive: true });
292
- for (const file of import_fs.default.readdirSync(traceViewerFolder)) {
293
- if (file.endsWith(".map") || file.includes("watch") || file.includes("assets"))
294
- continue;
295
- await (0, import_utils.copyFileAndMakeWritable)(import_path.default.join(traceViewerFolder, file), import_path.default.join(traceViewerTargetFolder, file));
296
- }
297
- for (const file of import_fs.default.readdirSync(import_path.default.join(traceViewerFolder, "assets"))) {
298
- if (file.endsWith(".map") || file.includes("xtermModule"))
299
- continue;
300
- await (0, import_utils.copyFileAndMakeWritable)(import_path.default.join(traceViewerFolder, "assets", file), import_path.default.join(traceViewerAssetsTargetFolder, file));
301
- }
302
- }
303
- await this._writeReportData(import_path.default.join(this._reportFolder, "index.html"));
304
- return { ok, singleTestId };
305
- }
306
- async _writeReportData(filePath) {
307
- import_fs.default.appendFileSync(filePath, '<script id="playwrightReportBase64" type="application/zip">data:application/zip;base64,');
308
- await new Promise((f) => {
309
- this._dataZipFile.end(void 0, () => {
310
- this._dataZipFile.outputStream.pipe(new Base64Encoder()).pipe(import_fs.default.createWriteStream(filePath, { flags: "a" })).on("close", f);
311
- });
312
- });
313
- import_fs.default.appendFileSync(filePath, "</script>");
314
- }
315
- _addDataFile(fileName, data) {
316
- this._dataZipFile.addBuffer(Buffer.from(JSON.stringify(data)), fileName);
317
- }
318
- _createEntryForSuite(data, projectName, suite, fileName, deep) {
319
- const fileId = (0, import_utils.calculateSha1)(fileName).slice(0, 20);
320
- let fileEntry = data.get(fileId);
321
- if (!fileEntry) {
322
- fileEntry = {
323
- testFile: { fileId, fileName, tests: [] },
324
- testFileSummary: { fileId, fileName, tests: [], stats: emptyStats() }
325
- };
326
- data.set(fileId, fileEntry);
327
- }
328
- const { testFile, testFileSummary } = fileEntry;
329
- const testEntries = [];
330
- this._processSuite(suite, projectName, [], deep, testEntries);
331
- for (const test of testEntries) {
332
- testFile.tests.push(test.testCase);
333
- testFileSummary.tests.push(test.testCaseSummary);
334
- }
335
- }
336
- _processSuite(suite, projectName, path2, deep, outTests) {
337
- const newPath = [...path2, suite.title];
338
- suite.entries().forEach((e) => {
339
- if (e.type === "test")
340
- outTests.push(this._createTestEntry(e, projectName, newPath));
341
- else if (deep)
342
- this._processSuite(e, projectName, newPath, deep, outTests);
343
- });
344
- }
345
- _createTestEntry(test, projectName, path2) {
346
- const duration = test.results.reduce((a, r) => a + r.duration, 0);
347
- const location = this._relativeLocation(test.location);
348
- path2 = path2.slice(1).filter((path3) => path3.length > 0);
349
- const results = test.results.map((r) => this._createTestResult(test, r));
350
- return {
351
- testCase: {
352
- testId: test.id,
353
- title: test.title,
354
- projectName,
355
- location,
356
- duration,
357
- annotations: this._serializeAnnotations(test.annotations),
358
- tags: test.tags,
359
- outcome: test.outcome(),
360
- path: path2,
361
- results,
362
- ok: test.outcome() === "expected" || test.outcome() === "flaky"
363
- },
364
- testCaseSummary: {
365
- testId: test.id,
366
- title: test.title,
367
- projectName,
368
- location,
369
- duration,
370
- annotations: this._serializeAnnotations(test.annotations),
371
- tags: test.tags,
372
- outcome: test.outcome(),
373
- path: path2,
374
- ok: test.outcome() === "expected" || test.outcome() === "flaky",
375
- results: results.map((result) => {
376
- return { attachments: result.attachments.map((a) => ({ name: a.name, contentType: a.contentType, path: a.path })) };
377
- })
378
- }
379
- };
380
- }
381
- _serializeAttachments(attachments) {
382
- let lastAttachment;
383
- return attachments.map((a) => {
384
- if (a.name === "trace")
385
- this._hasTraces = true;
386
- if ((a.name === "stdout" || a.name === "stderr") && a.contentType === "text/plain") {
387
- if (lastAttachment && lastAttachment.name === a.name && lastAttachment.contentType === a.contentType) {
388
- lastAttachment.body += (0, import_util.stripAnsiEscapes)(a.body);
389
- return null;
390
- }
391
- a.body = (0, import_util.stripAnsiEscapes)(a.body);
392
- lastAttachment = a;
393
- return a;
394
- }
395
- if (a.path) {
396
- let fileName = a.path;
397
- try {
398
- const buffer = import_fs.default.readFileSync(a.path);
399
- const sha1 = (0, import_utils.calculateSha1)(buffer) + import_path.default.extname(a.path);
400
- fileName = this._attachmentsBaseURL + sha1;
401
- import_fs.default.mkdirSync(import_path.default.join(this._reportFolder, "data"), { recursive: true });
402
- import_fs.default.writeFileSync(import_path.default.join(this._reportFolder, "data", sha1), buffer);
403
- } catch (e) {
404
- }
405
- return {
406
- name: a.name,
407
- contentType: a.contentType,
408
- path: fileName,
409
- body: a.body
410
- };
411
- }
412
- if (a.body instanceof Buffer) {
413
- if (isTextContentType(a.contentType)) {
414
- const charset = a.contentType.match(/charset=(.*)/)?.[1];
415
- try {
416
- const body = a.body.toString(charset || "utf-8");
417
- return {
418
- name: a.name,
419
- contentType: a.contentType,
420
- body
421
- };
422
- } catch (e) {
423
- }
424
- }
425
- import_fs.default.mkdirSync(import_path.default.join(this._reportFolder, "data"), { recursive: true });
426
- const extension = (0, import_utils.sanitizeForFilePath)(import_path.default.extname(a.name).replace(/^\./, "")) || import_utilsBundle2.mime.getExtension(a.contentType) || "dat";
427
- const sha1 = (0, import_utils.calculateSha1)(a.body) + "." + extension;
428
- import_fs.default.writeFileSync(import_path.default.join(this._reportFolder, "data", sha1), a.body);
429
- return {
430
- name: a.name,
431
- contentType: a.contentType,
432
- path: this._attachmentsBaseURL + sha1
433
- };
434
- }
435
- return {
436
- name: a.name,
437
- contentType: a.contentType,
438
- body: a.body
439
- };
440
- }).filter(Boolean);
441
- }
442
- _serializeAnnotations(annotations) {
443
- return annotations.map((a) => ({
444
- type: a.type,
445
- description: a.description === void 0 ? void 0 : String(a.description),
446
- location: a.location ? {
447
- file: a.location.file,
448
- line: a.location.line,
449
- column: a.location.column
450
- } : void 0
451
- }));
452
- }
453
- _createTestResult(test, result) {
454
- return {
455
- duration: result.duration,
456
- startTime: result.startTime.toISOString(),
457
- retry: result.retry,
458
- steps: dedupeSteps(result.steps).map((s) => this._createTestStep(s, result)),
459
- errors: (0, import_base.formatResultFailure)(import_base.internalScreen, test, result, "").map((error) => {
460
- return {
461
- message: error.message,
462
- codeframe: error.location ? createErrorCodeframe(error.message, error.location) : void 0
463
- };
464
- }),
465
- status: result.status,
466
- annotations: this._serializeAnnotations(result.annotations),
467
- attachments: this._serializeAttachments([
468
- ...result.attachments,
469
- ...result.stdout.map((m) => stdioAttachment(m, "stdout")),
470
- ...result.stderr.map((m) => stdioAttachment(m, "stderr"))
471
- ])
472
- };
473
- }
474
- _createTestStep(dedupedStep, result) {
475
- const { step, duration, count } = dedupedStep;
476
- const skipped = dedupedStep.step.annotations?.find((a) => a.type === "skip");
477
- let title = step.title;
478
- if (skipped)
479
- title = `${title} (skipped${skipped.description ? ": " + skipped.description : ""})`;
480
- const testStep = {
481
- title,
482
- startTime: step.startTime.toISOString(),
483
- duration,
484
- steps: dedupeSteps(step.steps).map((s) => this._createTestStep(s, result)),
485
- attachments: step.attachments.map((s) => {
486
- const index = result.attachments.indexOf(s);
487
- if (index === -1)
488
- throw new Error("Unexpected, attachment not found");
489
- return index;
490
- }),
491
- location: this._relativeLocation(step.location),
492
- error: step.error?.message,
493
- count,
494
- skipped: !!skipped
495
- };
496
- if (step.location)
497
- this._stepsInFile.set(step.location.file, testStep);
498
- return testStep;
499
- }
500
- _relativeLocation(location) {
501
- if (!location)
502
- return void 0;
503
- const file = (0, import_utils.toPosixPath)(import_path.default.relative(this._config.rootDir, location.file));
504
- return {
505
- file,
506
- line: location.line,
507
- column: location.column
508
- };
509
- }
510
- }
511
- const emptyStats = () => {
512
- return {
513
- total: 0,
514
- expected: 0,
515
- unexpected: 0,
516
- flaky: 0,
517
- skipped: 0,
518
- ok: true
519
- };
520
- };
521
- const addStats = (stats, delta) => {
522
- stats.total += delta.total;
523
- stats.skipped += delta.skipped;
524
- stats.expected += delta.expected;
525
- stats.unexpected += delta.unexpected;
526
- stats.flaky += delta.flaky;
527
- stats.ok = stats.ok && delta.ok;
528
- return stats;
529
- };
530
- class Base64Encoder extends import_stream.Transform {
531
- _transform(chunk, encoding, callback) {
532
- if (this._remainder) {
533
- chunk = Buffer.concat([this._remainder, chunk]);
534
- this._remainder = void 0;
535
- }
536
- const remaining = chunk.length % 3;
537
- if (remaining) {
538
- this._remainder = chunk.slice(chunk.length - remaining);
539
- chunk = chunk.slice(0, chunk.length - remaining);
540
- }
541
- chunk = chunk.toString("base64");
542
- this.push(Buffer.from(chunk));
543
- callback();
544
- }
545
- _flush(callback) {
546
- if (this._remainder)
547
- this.push(Buffer.from(this._remainder.toString("base64")));
548
- callback();
549
- }
550
- }
551
- function isTextContentType(contentType) {
552
- return contentType.startsWith("text/") || contentType.startsWith("application/json");
553
- }
554
- function stdioAttachment(chunk, type) {
555
- return {
556
- name: type,
557
- contentType: "text/plain",
558
- body: typeof chunk === "string" ? chunk : chunk.toString("utf-8")
559
- };
560
- }
561
- function dedupeSteps(steps) {
562
- const result = [];
563
- let lastResult = void 0;
564
- for (const step of steps) {
565
- const canDedupe = !step.error && step.duration >= 0 && step.location?.file && !step.steps.length;
566
- const lastStep = lastResult?.step;
567
- if (canDedupe && lastResult && lastStep && step.category === lastStep.category && step.title === lastStep.title && step.location?.file === lastStep.location?.file && step.location?.line === lastStep.location?.line && step.location?.column === lastStep.location?.column) {
568
- ++lastResult.count;
569
- lastResult.duration += step.duration;
570
- continue;
571
- }
572
- lastResult = { step, count: 1, duration: step.duration };
573
- result.push(lastResult);
574
- if (!canDedupe)
575
- lastResult = void 0;
576
- }
577
- return result;
578
- }
579
- function createSnippets(stepsInFile) {
580
- for (const file of stepsInFile.keys()) {
581
- let source;
582
- try {
583
- source = import_fs.default.readFileSync(file, "utf-8") + "\n//";
584
- } catch (e) {
585
- continue;
586
- }
587
- const lines = source.split("\n").length;
588
- const highlighted = (0, import_babelBundle.codeFrameColumns)(source, { start: { line: lines, column: 1 } }, { highlightCode: true, linesAbove: lines, linesBelow: 0 });
589
- const highlightedLines = highlighted.split("\n");
590
- const lineWithArrow = highlightedLines[highlightedLines.length - 1];
591
- for (const step of stepsInFile.get(file)) {
592
- if (step.location.line < 2 || step.location.line >= lines)
593
- continue;
594
- const snippetLines = highlightedLines.slice(step.location.line - 2, step.location.line + 1);
595
- const index = lineWithArrow.indexOf("^");
596
- const shiftedArrow = lineWithArrow.slice(0, index) + " ".repeat(step.location.column - 1) + lineWithArrow.slice(index);
597
- snippetLines.splice(2, 0, shiftedArrow);
598
- step.snippet = snippetLines.join("\n");
599
- }
600
- }
601
- }
602
- function createErrorCodeframe(message, location) {
603
- let source;
604
- try {
605
- source = import_fs.default.readFileSync(location.file, "utf-8") + "\n//";
606
- } catch (e) {
607
- return;
608
- }
609
- return (0, import_babelBundle.codeFrameColumns)(
610
- source,
611
- {
612
- start: {
613
- line: location.line,
614
- column: location.column
615
- }
616
- },
617
- {
618
- highlightCode: false,
619
- linesAbove: 100,
620
- linesBelow: 100,
621
- message: (0, import_util.stripAnsiEscapes)(message).split("\n")[0] || void 0
622
- }
623
- );
624
- }
625
- function writeLine(line) {
626
- process.stdout.write(line + "\n");
627
- }
628
- var html_default = HtmlReporter;
629
- // Annotate the CommonJS export names for ESM import in node:
630
- 0 && (module.exports = {
631
- showHTMLReport,
632
- startHtmlReportServer
633
- });
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var html_exports = {};
30
+ __export(html_exports, {
31
+ default: () => html_default,
32
+ showHTMLReport: () => showHTMLReport,
33
+ startHtmlReportServer: () => startHtmlReportServer
34
+ });
35
+ module.exports = __toCommonJS(html_exports);
36
+ var import_fs = __toESM(require("fs"));
37
+ var import_path = __toESM(require("path"));
38
+ var import_stream = require("stream");
39
+ var import_utils = require("patchright-bun-core/lib/utils");
40
+ var import_utils2 = require("patchright-bun-core/lib/utils");
41
+ var import_utilsBundle = require("patchright-bun-core/lib/utilsBundle");
42
+ var import_utilsBundle2 = require("patchright-bun-core/lib/utilsBundle");
43
+ var import_zipBundle = require("patchright-bun-core/lib/zipBundle");
44
+ var import_base = require("./base");
45
+ var import_babelBundle = require("../transform/babelBundle");
46
+ var import_util = require("../util");
47
+ const htmlReportOptions = ["always", "never", "on-failure"];
48
+ const isHtmlReportOption = (type) => {
49
+ return htmlReportOptions.includes(type);
50
+ };
51
+ class HtmlReporter {
52
+ constructor(options) {
53
+ this._topLevelErrors = [];
54
+ this._machines = [];
55
+ this._options = options;
56
+ }
57
+ version() {
58
+ return "v2";
59
+ }
60
+ printsToStdio() {
61
+ return false;
62
+ }
63
+ onConfigure(config) {
64
+ this.config = config;
65
+ }
66
+ onBegin(suite) {
67
+ const { outputFolder, open: open2, attachmentsBaseURL, host, port } = this._resolveOptions();
68
+ this._outputFolder = outputFolder;
69
+ this._open = open2;
70
+ this._host = host;
71
+ this._port = port;
72
+ this._attachmentsBaseURL = attachmentsBaseURL;
73
+ const reportedWarnings = /* @__PURE__ */ new Set();
74
+ for (const project of this.config.projects) {
75
+ if (this._isSubdirectory(outputFolder, project.outputDir) || this._isSubdirectory(project.outputDir, outputFolder)) {
76
+ const key = outputFolder + "|" + project.outputDir;
77
+ if (reportedWarnings.has(key))
78
+ continue;
79
+ reportedWarnings.add(key);
80
+ writeLine(import_utils2.colors.red(`Configuration Error: HTML reporter output folder clashes with the tests output folder:`));
81
+ writeLine(`
82
+ html reporter folder: ${import_utils2.colors.bold(outputFolder)}
83
+ test results folder: ${import_utils2.colors.bold(project.outputDir)}`);
84
+ writeLine("");
85
+ writeLine(`HTML reporter will clear its output directory prior to being generated, which will lead to the artifact loss.
86
+ `);
87
+ }
88
+ }
89
+ this.suite = suite;
90
+ }
91
+ _resolveOptions() {
92
+ const outputFolder = reportFolderFromEnv() ?? (0, import_util.resolveReporterOutputPath)("playwright-report", this._options.configDir, this._options.outputFolder);
93
+ return {
94
+ outputFolder,
95
+ open: getHtmlReportOptionProcessEnv() || this._options.open || "on-failure",
96
+ attachmentsBaseURL: process.env.PLAYWRIGHT_HTML_ATTACHMENTS_BASE_URL || this._options.attachmentsBaseURL || "data/",
97
+ host: process.env.PLAYWRIGHT_HTML_HOST || this._options.host,
98
+ port: process.env.PLAYWRIGHT_HTML_PORT ? +process.env.PLAYWRIGHT_HTML_PORT : this._options.port
99
+ };
100
+ }
101
+ _isSubdirectory(parentDir, dir) {
102
+ const relativePath = import_path.default.relative(parentDir, dir);
103
+ return !!relativePath && !relativePath.startsWith("..") && !import_path.default.isAbsolute(relativePath);
104
+ }
105
+ onError(error) {
106
+ this._topLevelErrors.push(error);
107
+ }
108
+ onMachineEnd(result) {
109
+ this._machines.push(result);
110
+ }
111
+ async onEnd(result) {
112
+ const projectSuites = this.suite.suites;
113
+ await (0, import_utils.removeFolders)([this._outputFolder]);
114
+ let noSnippets;
115
+ if (process.env.PLAYWRIGHT_HTML_NO_SNIPPETS === "false" || process.env.PLAYWRIGHT_HTML_NO_SNIPPETS === "0")
116
+ noSnippets = false;
117
+ else if (process.env.PLAYWRIGHT_HTML_NO_SNIPPETS)
118
+ noSnippets = true;
119
+ noSnippets = noSnippets || this._options.noSnippets;
120
+ let noCopyPrompt;
121
+ if (process.env.PLAYWRIGHT_HTML_NO_COPY_PROMPT === "false" || process.env.PLAYWRIGHT_HTML_NO_COPY_PROMPT === "0")
122
+ noCopyPrompt = false;
123
+ else if (process.env.PLAYWRIGHT_HTML_NO_COPY_PROMPT)
124
+ noCopyPrompt = true;
125
+ noCopyPrompt = noCopyPrompt || this._options.noCopyPrompt;
126
+ const builder = new HtmlBuilder(this.config, this._outputFolder, this._attachmentsBaseURL, {
127
+ title: process.env.PLAYWRIGHT_HTML_TITLE || this._options.title,
128
+ noSnippets,
129
+ noCopyPrompt
130
+ });
131
+ this._buildResult = await builder.build(this.config.metadata, projectSuites, result, this._topLevelErrors, this._machines);
132
+ }
133
+ async onExit() {
134
+ if (process.env.CI || !this._buildResult)
135
+ return;
136
+ const { ok, singleTestId } = this._buildResult;
137
+ const shouldOpen = !!process.stdin.isTTY && (this._open === "always" || !ok && this._open === "on-failure");
138
+ if (shouldOpen) {
139
+ await showHTMLReport(this._outputFolder, this._host, this._port, singleTestId);
140
+ } else if (this._options._mode === "test" && !!process.stdin.isTTY) {
141
+ const packageManagerCommand = (0, import_utils.getPackageManagerExecCommand)();
142
+ const relativeReportPath = this._outputFolder === standaloneDefaultFolder() ? "" : " " + import_path.default.relative(process.cwd(), this._outputFolder);
143
+ const hostArg = this._host ? ` --host ${this._host}` : "";
144
+ const portArg = this._port ? ` --port ${this._port}` : "";
145
+ writeLine("");
146
+ writeLine("To open last HTML report run:");
147
+ writeLine(import_utils2.colors.cyan(`
148
+ ${packageManagerCommand} playwright show-report${relativeReportPath}${hostArg}${portArg}
149
+ `));
150
+ }
151
+ }
152
+ }
153
+ function reportFolderFromEnv() {
154
+ const envValue = process.env.PLAYWRIGHT_HTML_OUTPUT_DIR || process.env.PLAYWRIGHT_HTML_REPORT;
155
+ return envValue ? import_path.default.resolve(envValue) : void 0;
156
+ }
157
+ function getHtmlReportOptionProcessEnv() {
158
+ const htmlOpenEnv = process.env.PLAYWRIGHT_HTML_OPEN || process.env.PW_TEST_HTML_REPORT_OPEN;
159
+ if (!htmlOpenEnv)
160
+ return void 0;
161
+ if (!isHtmlReportOption(htmlOpenEnv)) {
162
+ writeLine(import_utils2.colors.red(`Configuration Error: HTML reporter Invalid value for PLAYWRIGHT_HTML_OPEN: ${htmlOpenEnv}. Valid values are: ${htmlReportOptions.join(", ")}`));
163
+ return void 0;
164
+ }
165
+ return htmlOpenEnv;
166
+ }
167
+ function standaloneDefaultFolder() {
168
+ return reportFolderFromEnv() ?? (0, import_util.resolveReporterOutputPath)("playwright-report", process.cwd(), void 0);
169
+ }
170
+ async function showHTMLReport(reportFolder, host = "localhost", port, testId) {
171
+ const folder = reportFolder ?? standaloneDefaultFolder();
172
+ try {
173
+ (0, import_utils.assert)(import_fs.default.statSync(folder).isDirectory());
174
+ } catch (e) {
175
+ writeLine(import_utils2.colors.red(`No report found at "${folder}"`));
176
+ (0, import_utils.gracefullyProcessExitDoNotHang)(1);
177
+ return;
178
+ }
179
+ const server = startHtmlReportServer(folder);
180
+ await server.start({ port, host, preferredPort: port ? void 0 : 9323 });
181
+ let url = server.urlPrefix("human-readable");
182
+ writeLine("");
183
+ writeLine(import_utils2.colors.cyan(` Serving HTML report at ${url}. Press Ctrl+C to quit.`));
184
+ if (testId)
185
+ url += `#?testId=${testId}`;
186
+ url = url.replace("0.0.0.0", "localhost");
187
+ await (0, import_utilsBundle.open)(url, { wait: true }).catch(() => {
188
+ });
189
+ await new Promise(() => {
190
+ });
191
+ }
192
+ function startHtmlReportServer(folder) {
193
+ const server = new import_utils.HttpServer();
194
+ server.routePrefix("/", (request, response) => {
195
+ let relativePath = new URL("http://localhost" + request.url).pathname;
196
+ if (relativePath.startsWith("/trace/file")) {
197
+ const url = new URL("http://localhost" + request.url);
198
+ try {
199
+ return server.serveFile(request, response, url.searchParams.get("path"));
200
+ } catch (e) {
201
+ return false;
202
+ }
203
+ }
204
+ if (relativePath === "/")
205
+ relativePath = "/index.html";
206
+ const absolutePath = import_path.default.join(folder, ...relativePath.split("/"));
207
+ return server.serveFile(request, response, absolutePath);
208
+ });
209
+ return server;
210
+ }
211
+ class HtmlBuilder {
212
+ constructor(config, outputDir, attachmentsBaseURL, options) {
213
+ this._stepsInFile = new import_utils.MultiMap();
214
+ this._hasTraces = false;
215
+ this._config = config;
216
+ this._reportFolder = outputDir;
217
+ this._options = options;
218
+ import_fs.default.mkdirSync(this._reportFolder, { recursive: true });
219
+ this._dataZipFile = new import_zipBundle.yazl.ZipFile();
220
+ this._attachmentsBaseURL = attachmentsBaseURL;
221
+ }
222
+ async build(metadata, projectSuites, result, topLevelErrors, machines) {
223
+ const data = /* @__PURE__ */ new Map();
224
+ for (const projectSuite of projectSuites) {
225
+ const projectName = projectSuite.project().name;
226
+ for (const fileSuite of projectSuite.suites) {
227
+ const fileName = this._relativeLocation(fileSuite.location).file;
228
+ this._createEntryForSuite(data, projectName, fileSuite, fileName, true);
229
+ }
230
+ }
231
+ if (!this._options.noSnippets)
232
+ createSnippets(this._stepsInFile);
233
+ let ok = true;
234
+ for (const [fileId, { testFile, testFileSummary }] of data) {
235
+ const stats = testFileSummary.stats;
236
+ for (const test of testFileSummary.tests) {
237
+ if (test.outcome === "expected")
238
+ ++stats.expected;
239
+ if (test.outcome === "skipped")
240
+ ++stats.skipped;
241
+ if (test.outcome === "unexpected")
242
+ ++stats.unexpected;
243
+ if (test.outcome === "flaky")
244
+ ++stats.flaky;
245
+ ++stats.total;
246
+ }
247
+ stats.ok = stats.unexpected + stats.flaky === 0;
248
+ if (!stats.ok)
249
+ ok = false;
250
+ const testCaseSummaryComparator = (t1, t2) => {
251
+ const w1 = (t1.outcome === "unexpected" ? 1e3 : 0) + (t1.outcome === "flaky" ? 1 : 0);
252
+ const w2 = (t2.outcome === "unexpected" ? 1e3 : 0) + (t2.outcome === "flaky" ? 1 : 0);
253
+ return w2 - w1;
254
+ };
255
+ testFileSummary.tests.sort(testCaseSummaryComparator);
256
+ this._addDataFile(fileId + ".json", testFile);
257
+ }
258
+ const htmlReport = {
259
+ metadata,
260
+ startTime: result.startTime.getTime(),
261
+ duration: result.duration,
262
+ files: [...data.values()].map((e) => e.testFileSummary),
263
+ projectNames: projectSuites.map((r) => r.project().name),
264
+ stats: { ...[...data.values()].reduce((a, e) => addStats(a, e.testFileSummary.stats), emptyStats()) },
265
+ errors: topLevelErrors.map((error) => (0, import_base.formatError)(import_base.internalScreen, error).message),
266
+ options: this._options,
267
+ machines: machines.map((s) => ({
268
+ duration: s.duration,
269
+ startTime: s.startTime.getTime(),
270
+ tag: s.tag,
271
+ shardIndex: s.shardIndex
272
+ }))
273
+ };
274
+ htmlReport.files.sort((f1, f2) => {
275
+ const w1 = f1.stats.unexpected * 1e3 + f1.stats.flaky;
276
+ const w2 = f2.stats.unexpected * 1e3 + f2.stats.flaky;
277
+ return w2 - w1;
278
+ });
279
+ this._addDataFile("report.json", htmlReport);
280
+ let singleTestId;
281
+ if (htmlReport.stats.total === 1) {
282
+ const testFile = data.values().next().value.testFile;
283
+ singleTestId = testFile.tests[0].testId;
284
+ }
285
+ const appFolder = import_path.default.join(require.resolve("patchright-bun-core"), "..", "lib", "vite", "htmlReport");
286
+ await (0, import_utils.copyFileAndMakeWritable)(import_path.default.join(appFolder, "index.html"), import_path.default.join(this._reportFolder, "index.html"));
287
+ if (this._hasTraces) {
288
+ const traceViewerFolder = import_path.default.join(require.resolve("patchright-bun-core"), "..", "lib", "vite", "traceViewer");
289
+ const traceViewerTargetFolder = import_path.default.join(this._reportFolder, "trace");
290
+ const traceViewerAssetsTargetFolder = import_path.default.join(traceViewerTargetFolder, "assets");
291
+ import_fs.default.mkdirSync(traceViewerAssetsTargetFolder, { recursive: true });
292
+ for (const file of import_fs.default.readdirSync(traceViewerFolder)) {
293
+ if (file.endsWith(".map") || file.includes("watch") || file.includes("assets"))
294
+ continue;
295
+ await (0, import_utils.copyFileAndMakeWritable)(import_path.default.join(traceViewerFolder, file), import_path.default.join(traceViewerTargetFolder, file));
296
+ }
297
+ for (const file of import_fs.default.readdirSync(import_path.default.join(traceViewerFolder, "assets"))) {
298
+ if (file.endsWith(".map") || file.includes("xtermModule"))
299
+ continue;
300
+ await (0, import_utils.copyFileAndMakeWritable)(import_path.default.join(traceViewerFolder, "assets", file), import_path.default.join(traceViewerAssetsTargetFolder, file));
301
+ }
302
+ }
303
+ await this._writeReportData(import_path.default.join(this._reportFolder, "index.html"));
304
+ return { ok, singleTestId };
305
+ }
306
+ async _writeReportData(filePath) {
307
+ import_fs.default.appendFileSync(filePath, '<script id="playwrightReportBase64" type="application/zip">data:application/zip;base64,');
308
+ await new Promise((f) => {
309
+ this._dataZipFile.end(void 0, () => {
310
+ this._dataZipFile.outputStream.pipe(new Base64Encoder()).pipe(import_fs.default.createWriteStream(filePath, { flags: "a" })).on("close", f);
311
+ });
312
+ });
313
+ import_fs.default.appendFileSync(filePath, "</script>");
314
+ }
315
+ _addDataFile(fileName, data) {
316
+ this._dataZipFile.addBuffer(Buffer.from(JSON.stringify(data)), fileName);
317
+ }
318
+ _createEntryForSuite(data, projectName, suite, fileName, deep) {
319
+ const fileId = (0, import_utils.calculateSha1)(fileName).slice(0, 20);
320
+ let fileEntry = data.get(fileId);
321
+ if (!fileEntry) {
322
+ fileEntry = {
323
+ testFile: { fileId, fileName, tests: [] },
324
+ testFileSummary: { fileId, fileName, tests: [], stats: emptyStats() }
325
+ };
326
+ data.set(fileId, fileEntry);
327
+ }
328
+ const { testFile, testFileSummary } = fileEntry;
329
+ const testEntries = [];
330
+ this._processSuite(suite, projectName, [], deep, testEntries);
331
+ for (const test of testEntries) {
332
+ testFile.tests.push(test.testCase);
333
+ testFileSummary.tests.push(test.testCaseSummary);
334
+ }
335
+ }
336
+ _processSuite(suite, projectName, path2, deep, outTests) {
337
+ const newPath = [...path2, suite.title];
338
+ suite.entries().forEach((e) => {
339
+ if (e.type === "test")
340
+ outTests.push(this._createTestEntry(e, projectName, newPath));
341
+ else if (deep)
342
+ this._processSuite(e, projectName, newPath, deep, outTests);
343
+ });
344
+ }
345
+ _createTestEntry(test, projectName, path2) {
346
+ const duration = test.results.reduce((a, r) => a + r.duration, 0);
347
+ const location = this._relativeLocation(test.location);
348
+ path2 = path2.slice(1).filter((path3) => path3.length > 0);
349
+ const results = test.results.map((r) => this._createTestResult(test, r));
350
+ return {
351
+ testCase: {
352
+ testId: test.id,
353
+ title: test.title,
354
+ projectName,
355
+ location,
356
+ duration,
357
+ annotations: this._serializeAnnotations(test.annotations),
358
+ tags: test.tags,
359
+ outcome: test.outcome(),
360
+ path: path2,
361
+ results,
362
+ ok: test.outcome() === "expected" || test.outcome() === "flaky"
363
+ },
364
+ testCaseSummary: {
365
+ testId: test.id,
366
+ title: test.title,
367
+ projectName,
368
+ location,
369
+ duration,
370
+ annotations: this._serializeAnnotations(test.annotations),
371
+ tags: test.tags,
372
+ outcome: test.outcome(),
373
+ path: path2,
374
+ ok: test.outcome() === "expected" || test.outcome() === "flaky",
375
+ results: results.map((result) => {
376
+ return { attachments: result.attachments.map((a) => ({ name: a.name, contentType: a.contentType, path: a.path })) };
377
+ })
378
+ }
379
+ };
380
+ }
381
+ _serializeAttachments(attachments) {
382
+ let lastAttachment;
383
+ return attachments.map((a) => {
384
+ if (a.name === "trace")
385
+ this._hasTraces = true;
386
+ if ((a.name === "stdout" || a.name === "stderr") && a.contentType === "text/plain") {
387
+ if (lastAttachment && lastAttachment.name === a.name && lastAttachment.contentType === a.contentType) {
388
+ lastAttachment.body += (0, import_util.stripAnsiEscapes)(a.body);
389
+ return null;
390
+ }
391
+ a.body = (0, import_util.stripAnsiEscapes)(a.body);
392
+ lastAttachment = a;
393
+ return a;
394
+ }
395
+ if (a.path) {
396
+ let fileName = a.path;
397
+ try {
398
+ const buffer = import_fs.default.readFileSync(a.path);
399
+ const sha1 = (0, import_utils.calculateSha1)(buffer) + import_path.default.extname(a.path);
400
+ fileName = this._attachmentsBaseURL + sha1;
401
+ import_fs.default.mkdirSync(import_path.default.join(this._reportFolder, "data"), { recursive: true });
402
+ import_fs.default.writeFileSync(import_path.default.join(this._reportFolder, "data", sha1), buffer);
403
+ } catch (e) {
404
+ }
405
+ return {
406
+ name: a.name,
407
+ contentType: a.contentType,
408
+ path: fileName,
409
+ body: a.body
410
+ };
411
+ }
412
+ if (a.body instanceof Buffer) {
413
+ if (isTextContentType(a.contentType)) {
414
+ const charset = a.contentType.match(/charset=(.*)/)?.[1];
415
+ try {
416
+ const body = a.body.toString(charset || "utf-8");
417
+ return {
418
+ name: a.name,
419
+ contentType: a.contentType,
420
+ body
421
+ };
422
+ } catch (e) {
423
+ }
424
+ }
425
+ import_fs.default.mkdirSync(import_path.default.join(this._reportFolder, "data"), { recursive: true });
426
+ const extension = (0, import_utils.sanitizeForFilePath)(import_path.default.extname(a.name).replace(/^\./, "")) || import_utilsBundle2.mime.getExtension(a.contentType) || "dat";
427
+ const sha1 = (0, import_utils.calculateSha1)(a.body) + "." + extension;
428
+ import_fs.default.writeFileSync(import_path.default.join(this._reportFolder, "data", sha1), a.body);
429
+ return {
430
+ name: a.name,
431
+ contentType: a.contentType,
432
+ path: this._attachmentsBaseURL + sha1
433
+ };
434
+ }
435
+ return {
436
+ name: a.name,
437
+ contentType: a.contentType,
438
+ body: a.body
439
+ };
440
+ }).filter(Boolean);
441
+ }
442
+ _serializeAnnotations(annotations) {
443
+ return annotations.map((a) => ({
444
+ type: a.type,
445
+ description: a.description === void 0 ? void 0 : String(a.description),
446
+ location: a.location ? {
447
+ file: a.location.file,
448
+ line: a.location.line,
449
+ column: a.location.column
450
+ } : void 0
451
+ }));
452
+ }
453
+ _createTestResult(test, result) {
454
+ return {
455
+ duration: result.duration,
456
+ startTime: result.startTime.toISOString(),
457
+ retry: result.retry,
458
+ steps: dedupeSteps(result.steps).map((s) => this._createTestStep(s, result)),
459
+ errors: (0, import_base.formatResultFailure)(import_base.internalScreen, test, result, "").map((error) => {
460
+ return {
461
+ message: error.message,
462
+ codeframe: error.location ? createErrorCodeframe(error.message, error.location) : void 0
463
+ };
464
+ }),
465
+ status: result.status,
466
+ annotations: this._serializeAnnotations(result.annotations),
467
+ attachments: this._serializeAttachments([
468
+ ...result.attachments,
469
+ ...result.stdout.map((m) => stdioAttachment(m, "stdout")),
470
+ ...result.stderr.map((m) => stdioAttachment(m, "stderr"))
471
+ ])
472
+ };
473
+ }
474
+ _createTestStep(dedupedStep, result) {
475
+ const { step, duration, count } = dedupedStep;
476
+ const skipped = dedupedStep.step.annotations?.find((a) => a.type === "skip");
477
+ let title = step.title;
478
+ if (skipped)
479
+ title = `${title} (skipped${skipped.description ? ": " + skipped.description : ""})`;
480
+ const testStep = {
481
+ title,
482
+ startTime: step.startTime.toISOString(),
483
+ duration,
484
+ steps: dedupeSteps(step.steps).map((s) => this._createTestStep(s, result)),
485
+ attachments: step.attachments.map((s) => {
486
+ const index = result.attachments.indexOf(s);
487
+ if (index === -1)
488
+ throw new Error("Unexpected, attachment not found");
489
+ return index;
490
+ }),
491
+ location: this._relativeLocation(step.location),
492
+ error: step.error?.message,
493
+ count,
494
+ skipped: !!skipped
495
+ };
496
+ if (step.location)
497
+ this._stepsInFile.set(step.location.file, testStep);
498
+ return testStep;
499
+ }
500
+ _relativeLocation(location) {
501
+ if (!location)
502
+ return void 0;
503
+ const file = (0, import_utils.toPosixPath)(import_path.default.relative(this._config.rootDir, location.file));
504
+ return {
505
+ file,
506
+ line: location.line,
507
+ column: location.column
508
+ };
509
+ }
510
+ }
511
+ const emptyStats = () => {
512
+ return {
513
+ total: 0,
514
+ expected: 0,
515
+ unexpected: 0,
516
+ flaky: 0,
517
+ skipped: 0,
518
+ ok: true
519
+ };
520
+ };
521
+ const addStats = (stats, delta) => {
522
+ stats.total += delta.total;
523
+ stats.skipped += delta.skipped;
524
+ stats.expected += delta.expected;
525
+ stats.unexpected += delta.unexpected;
526
+ stats.flaky += delta.flaky;
527
+ stats.ok = stats.ok && delta.ok;
528
+ return stats;
529
+ };
530
+ class Base64Encoder extends import_stream.Transform {
531
+ _transform(chunk, encoding, callback) {
532
+ if (this._remainder) {
533
+ chunk = Buffer.concat([this._remainder, chunk]);
534
+ this._remainder = void 0;
535
+ }
536
+ const remaining = chunk.length % 3;
537
+ if (remaining) {
538
+ this._remainder = chunk.slice(chunk.length - remaining);
539
+ chunk = chunk.slice(0, chunk.length - remaining);
540
+ }
541
+ chunk = chunk.toString("base64");
542
+ this.push(Buffer.from(chunk));
543
+ callback();
544
+ }
545
+ _flush(callback) {
546
+ if (this._remainder)
547
+ this.push(Buffer.from(this._remainder.toString("base64")));
548
+ callback();
549
+ }
550
+ }
551
+ function isTextContentType(contentType) {
552
+ return contentType.startsWith("text/") || contentType.startsWith("application/json");
553
+ }
554
+ function stdioAttachment(chunk, type) {
555
+ return {
556
+ name: type,
557
+ contentType: "text/plain",
558
+ body: typeof chunk === "string" ? chunk : chunk.toString("utf-8")
559
+ };
560
+ }
561
+ function dedupeSteps(steps) {
562
+ const result = [];
563
+ let lastResult = void 0;
564
+ for (const step of steps) {
565
+ const canDedupe = !step.error && step.duration >= 0 && step.location?.file && !step.steps.length;
566
+ const lastStep = lastResult?.step;
567
+ if (canDedupe && lastResult && lastStep && step.category === lastStep.category && step.title === lastStep.title && step.location?.file === lastStep.location?.file && step.location?.line === lastStep.location?.line && step.location?.column === lastStep.location?.column) {
568
+ ++lastResult.count;
569
+ lastResult.duration += step.duration;
570
+ continue;
571
+ }
572
+ lastResult = { step, count: 1, duration: step.duration };
573
+ result.push(lastResult);
574
+ if (!canDedupe)
575
+ lastResult = void 0;
576
+ }
577
+ return result;
578
+ }
579
+ function createSnippets(stepsInFile) {
580
+ for (const file of stepsInFile.keys()) {
581
+ let source;
582
+ try {
583
+ source = import_fs.default.readFileSync(file, "utf-8") + "\n//";
584
+ } catch (e) {
585
+ continue;
586
+ }
587
+ const lines = source.split("\n").length;
588
+ const highlighted = (0, import_babelBundle.codeFrameColumns)(source, { start: { line: lines, column: 1 } }, { highlightCode: true, linesAbove: lines, linesBelow: 0 });
589
+ const highlightedLines = highlighted.split("\n");
590
+ const lineWithArrow = highlightedLines[highlightedLines.length - 1];
591
+ for (const step of stepsInFile.get(file)) {
592
+ if (step.location.line < 2 || step.location.line >= lines)
593
+ continue;
594
+ const snippetLines = highlightedLines.slice(step.location.line - 2, step.location.line + 1);
595
+ const index = lineWithArrow.indexOf("^");
596
+ const shiftedArrow = lineWithArrow.slice(0, index) + " ".repeat(step.location.column - 1) + lineWithArrow.slice(index);
597
+ snippetLines.splice(2, 0, shiftedArrow);
598
+ step.snippet = snippetLines.join("\n");
599
+ }
600
+ }
601
+ }
602
+ function createErrorCodeframe(message, location) {
603
+ let source;
604
+ try {
605
+ source = import_fs.default.readFileSync(location.file, "utf-8") + "\n//";
606
+ } catch (e) {
607
+ return;
608
+ }
609
+ return (0, import_babelBundle.codeFrameColumns)(
610
+ source,
611
+ {
612
+ start: {
613
+ line: location.line,
614
+ column: location.column
615
+ }
616
+ },
617
+ {
618
+ highlightCode: false,
619
+ linesAbove: 100,
620
+ linesBelow: 100,
621
+ message: (0, import_util.stripAnsiEscapes)(message).split("\n")[0] || void 0
622
+ }
623
+ );
624
+ }
625
+ function writeLine(line) {
626
+ process.stdout.write(line + "\n");
627
+ }
628
+ var html_default = HtmlReporter;
629
+ // Annotate the CommonJS export names for ESM import in node:
630
+ 0 && (module.exports = {
631
+ showHTMLReport,
632
+ startHtmlReportServer
633
+ });