patchright-bun 1.58.1 → 1.59.0

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