@smoothdeploy/playwright 1.58.4 → 1.60.1

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 (182) hide show
  1. package/ThirdPartyNotices.txt +8 -5036
  2. package/lib/agents/agentParser.js +2 -2
  3. package/lib/agents/generateAgents.js +21 -22
  4. package/lib/agents/playwright-test-healer.agent.md +1 -0
  5. package/lib/agents/playwright-test-planner.agent.md +2 -1
  6. package/lib/cli/reportActions.js +78 -0
  7. package/lib/cli/testActions.js +211 -0
  8. package/lib/common/index.js +2898 -0
  9. package/lib/common/index.js.txt +35 -0
  10. package/lib/errorContext.js +130 -0
  11. package/lib/index.js +258 -206
  12. package/lib/{isomorphic/testServerConnection.js → isomorphic.js} +70 -35
  13. package/lib/isomorphic.js.txt +9 -0
  14. package/lib/loader/loaderProcessEntry.js +34 -0
  15. package/lib/loader/loaderProcessEntry.js.txt +9 -0
  16. package/lib/matchers/expect.js +12988 -249
  17. package/lib/matchers/expect.js.LICENSE +693 -0
  18. package/lib/matchers/expect.js.txt +72 -0
  19. package/lib/mcp/test/browserBackend.js +49 -22
  20. package/lib/mcp/test/generatorTools.js +16 -16
  21. package/lib/mcp/test/plannerTools.js +25 -20
  22. package/lib/mcp/test/seed.js +7 -7
  23. package/lib/mcp/test/testBackend.js +30 -30
  24. package/lib/mcp/test/testContext.js +50 -33
  25. package/lib/mcp/test/testTools.js +15 -25
  26. package/lib/{internalsForTest.js → package.js} +13 -8
  27. package/lib/program.js +63 -263
  28. package/lib/runner/index.js +8339 -0
  29. package/lib/runner/index.js.txt +60 -0
  30. package/lib/transform/babelBundle.js +71002 -18
  31. package/lib/transform/babelBundle.js.LICENSE +2359 -0
  32. package/lib/transform/babelBundle.js.txt +325 -0
  33. package/lib/transform/esmLoader.js +5884 -30
  34. package/lib/transform/esmLoader.js.LICENSE +335 -0
  35. package/lib/transform/esmLoader.js.txt +55 -0
  36. package/lib/util.js +37 -34
  37. package/lib/worker/workerProcessEntry.js +3251 -0
  38. package/lib/worker/workerProcessEntry.js.txt +24 -0
  39. package/package.json +5 -16
  40. package/test.mjs +1 -0
  41. package/types/test.d.ts +172 -12
  42. package/types/testReporter.d.ts +7 -5
  43. package/lib/common/config.js +0 -282
  44. package/lib/common/configLoader.js +0 -344
  45. package/lib/common/esmLoaderHost.js +0 -104
  46. package/lib/common/expectBundle.js +0 -28
  47. package/lib/common/expectBundleImpl.js +0 -407
  48. package/lib/common/fixtures.js +0 -302
  49. package/lib/common/ipc.js +0 -60
  50. package/lib/common/poolBuilder.js +0 -85
  51. package/lib/common/process.js +0 -132
  52. package/lib/common/suiteUtils.js +0 -140
  53. package/lib/common/test.js +0 -321
  54. package/lib/common/testLoader.js +0 -101
  55. package/lib/common/testType.js +0 -298
  56. package/lib/common/validators.js +0 -68
  57. package/lib/fsWatcher.js +0 -67
  58. package/lib/isomorphic/events.js +0 -77
  59. package/lib/isomorphic/folders.js +0 -30
  60. package/lib/isomorphic/stringInternPool.js +0 -69
  61. package/lib/isomorphic/teleReceiver.js +0 -521
  62. package/lib/isomorphic/teleSuiteUpdater.js +0 -157
  63. package/lib/isomorphic/testServerInterface.js +0 -16
  64. package/lib/isomorphic/testTree.js +0 -329
  65. package/lib/isomorphic/types.d.js +0 -16
  66. package/lib/loader/loaderMain.js +0 -59
  67. package/lib/matchers/matcherHint.js +0 -44
  68. package/lib/matchers/matchers.js +0 -383
  69. package/lib/matchers/toBeTruthy.js +0 -75
  70. package/lib/matchers/toEqual.js +0 -100
  71. package/lib/matchers/toHaveURL.js +0 -101
  72. package/lib/matchers/toMatchAriaSnapshot.js +0 -159
  73. package/lib/matchers/toMatchSnapshot.js +0 -342
  74. package/lib/matchers/toMatchText.js +0 -99
  75. package/lib/mcp/browser/browserContextFactory.js +0 -329
  76. package/lib/mcp/browser/browserServerBackend.js +0 -84
  77. package/lib/mcp/browser/config.js +0 -421
  78. package/lib/mcp/browser/context.js +0 -244
  79. package/lib/mcp/browser/response.js +0 -278
  80. package/lib/mcp/browser/sessionLog.js +0 -75
  81. package/lib/mcp/browser/tab.js +0 -343
  82. package/lib/mcp/browser/tools/common.js +0 -65
  83. package/lib/mcp/browser/tools/console.js +0 -46
  84. package/lib/mcp/browser/tools/dialogs.js +0 -60
  85. package/lib/mcp/browser/tools/evaluate.js +0 -61
  86. package/lib/mcp/browser/tools/files.js +0 -58
  87. package/lib/mcp/browser/tools/form.js +0 -63
  88. package/lib/mcp/browser/tools/install.js +0 -72
  89. package/lib/mcp/browser/tools/keyboard.js +0 -107
  90. package/lib/mcp/browser/tools/mouse.js +0 -107
  91. package/lib/mcp/browser/tools/navigate.js +0 -71
  92. package/lib/mcp/browser/tools/network.js +0 -63
  93. package/lib/mcp/browser/tools/open.js +0 -57
  94. package/lib/mcp/browser/tools/pdf.js +0 -49
  95. package/lib/mcp/browser/tools/runCode.js +0 -78
  96. package/lib/mcp/browser/tools/screenshot.js +0 -93
  97. package/lib/mcp/browser/tools/snapshot.js +0 -173
  98. package/lib/mcp/browser/tools/tabs.js +0 -67
  99. package/lib/mcp/browser/tools/tool.js +0 -47
  100. package/lib/mcp/browser/tools/tracing.js +0 -74
  101. package/lib/mcp/browser/tools/utils.js +0 -94
  102. package/lib/mcp/browser/tools/verify.js +0 -143
  103. package/lib/mcp/browser/tools/wait.js +0 -63
  104. package/lib/mcp/browser/tools.js +0 -84
  105. package/lib/mcp/browser/watchdog.js +0 -44
  106. package/lib/mcp/config.d.js +0 -16
  107. package/lib/mcp/extension/cdpRelay.js +0 -351
  108. package/lib/mcp/extension/extensionContextFactory.js +0 -76
  109. package/lib/mcp/extension/protocol.js +0 -28
  110. package/lib/mcp/index.js +0 -61
  111. package/lib/mcp/log.js +0 -35
  112. package/lib/mcp/program.js +0 -111
  113. package/lib/mcp/sdk/exports.js +0 -28
  114. package/lib/mcp/sdk/http.js +0 -152
  115. package/lib/mcp/sdk/inProcessTransport.js +0 -71
  116. package/lib/mcp/sdk/server.js +0 -223
  117. package/lib/mcp/sdk/tool.js +0 -47
  118. package/lib/mcp/terminal/cli.js +0 -296
  119. package/lib/mcp/terminal/command.js +0 -56
  120. package/lib/mcp/terminal/commands.js +0 -333
  121. package/lib/mcp/terminal/daemon.js +0 -129
  122. package/lib/mcp/terminal/help.json +0 -32
  123. package/lib/mcp/terminal/helpGenerator.js +0 -88
  124. package/lib/mcp/terminal/socketConnection.js +0 -80
  125. package/lib/plugins/gitCommitInfoPlugin.js +0 -198
  126. package/lib/plugins/index.js +0 -28
  127. package/lib/plugins/webServerPlugin.js +0 -237
  128. package/lib/reporters/base.js +0 -634
  129. package/lib/reporters/blob.js +0 -138
  130. package/lib/reporters/dot.js +0 -99
  131. package/lib/reporters/empty.js +0 -32
  132. package/lib/reporters/github.js +0 -128
  133. package/lib/reporters/html.js +0 -633
  134. package/lib/reporters/internalReporter.js +0 -138
  135. package/lib/reporters/json.js +0 -254
  136. package/lib/reporters/junit.js +0 -232
  137. package/lib/reporters/line.js +0 -131
  138. package/lib/reporters/list.js +0 -253
  139. package/lib/reporters/listModeReporter.js +0 -69
  140. package/lib/reporters/markdown.js +0 -144
  141. package/lib/reporters/merge.js +0 -558
  142. package/lib/reporters/multiplexer.js +0 -112
  143. package/lib/reporters/reporterV2.js +0 -102
  144. package/lib/reporters/smoothdeploy.js +0 -333
  145. package/lib/reporters/teleEmitter.js +0 -317
  146. package/lib/reporters/versions/blobV1.js +0 -16
  147. package/lib/runner/dispatcher.js +0 -531
  148. package/lib/runner/failureTracker.js +0 -72
  149. package/lib/runner/lastRun.js +0 -77
  150. package/lib/runner/loadUtils.js +0 -334
  151. package/lib/runner/loaderHost.js +0 -89
  152. package/lib/runner/processHost.js +0 -180
  153. package/lib/runner/projectUtils.js +0 -241
  154. package/lib/runner/rebase.js +0 -189
  155. package/lib/runner/reporters.js +0 -140
  156. package/lib/runner/sigIntWatcher.js +0 -96
  157. package/lib/runner/storage.js +0 -91
  158. package/lib/runner/taskRunner.js +0 -127
  159. package/lib/runner/tasks.js +0 -410
  160. package/lib/runner/testGroups.js +0 -125
  161. package/lib/runner/testRunner.js +0 -398
  162. package/lib/runner/testServer.js +0 -269
  163. package/lib/runner/uiModeReporter.js +0 -30
  164. package/lib/runner/vcs.js +0 -72
  165. package/lib/runner/watchMode.js +0 -396
  166. package/lib/runner/workerHost.js +0 -104
  167. package/lib/third_party/pirates.js +0 -62
  168. package/lib/third_party/tsconfig-loader.js +0 -103
  169. package/lib/transform/babelBundleImpl.js +0 -461
  170. package/lib/transform/compilationCache.js +0 -274
  171. package/lib/transform/md.js +0 -221
  172. package/lib/transform/portTransport.js +0 -67
  173. package/lib/transform/transform.js +0 -303
  174. package/lib/utilsBundle.js +0 -50
  175. package/lib/utilsBundleImpl.js +0 -103
  176. package/lib/worker/fixtureRunner.js +0 -262
  177. package/lib/worker/testInfo.js +0 -536
  178. package/lib/worker/testTracing.js +0 -345
  179. package/lib/worker/timeoutManager.js +0 -174
  180. package/lib/worker/util.js +0 -31
  181. package/lib/worker/workerMain.js +0 -530
  182. /package/lib/{common/globals.js → globals.js} +0 -0
@@ -0,0 +1,3251 @@
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 __commonJS = (cb, mod) => function __require() {
9
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ // If the importer is in node compatibility mode or this is not an ESM
21
+ // file that has been converted to a CommonJS file using a Babel-
22
+ // compatible transform (i.e. "__esModule" has not been set), then set
23
+ // "default" to the CommonJS "module.exports" for node compatibility.
24
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
+ mod
26
+ ));
27
+
28
+ // packages/utils/third_party/yauzl/pend.js
29
+ var require_pend = __commonJS({
30
+ "packages/utils/third_party/yauzl/pend.js"(exports2, module2) {
31
+ "use strict";
32
+ module2.exports = Pend;
33
+ function Pend() {
34
+ this.pending = 0;
35
+ this.max = Infinity;
36
+ this.listeners = [];
37
+ this.waiting = [];
38
+ this.error = null;
39
+ }
40
+ Pend.prototype.go = function(fn) {
41
+ if (this.pending < this.max) {
42
+ pendGo(this, fn);
43
+ } else {
44
+ this.waiting.push(fn);
45
+ }
46
+ };
47
+ Pend.prototype.wait = function(cb) {
48
+ if (this.pending === 0) {
49
+ cb(this.error);
50
+ } else {
51
+ this.listeners.push(cb);
52
+ }
53
+ };
54
+ Pend.prototype.hold = function() {
55
+ return pendHold(this);
56
+ };
57
+ function pendHold(self) {
58
+ self.pending += 1;
59
+ var called = false;
60
+ return onCb;
61
+ function onCb(err) {
62
+ if (called) throw new Error("callback called twice");
63
+ called = true;
64
+ self.error = self.error || err;
65
+ self.pending -= 1;
66
+ if (self.waiting.length > 0 && self.pending < self.max) {
67
+ pendGo(self, self.waiting.shift());
68
+ } else if (self.pending === 0) {
69
+ var listeners = self.listeners;
70
+ self.listeners = [];
71
+ listeners.forEach(cbListener);
72
+ }
73
+ }
74
+ function cbListener(listener) {
75
+ listener(self.error);
76
+ }
77
+ }
78
+ function pendGo(self, fn) {
79
+ fn(pendHold(self));
80
+ }
81
+ }
82
+ });
83
+
84
+ // packages/utils/third_party/yauzl/fd-slicer.js
85
+ var require_fd_slicer = __commonJS({
86
+ "packages/utils/third_party/yauzl/fd-slicer.js"(exports2) {
87
+ "use strict";
88
+ var fs4 = require("fs");
89
+ var util2 = require("util");
90
+ var stream = require("stream");
91
+ var Readable = stream.Readable;
92
+ var Writable = stream.Writable;
93
+ var PassThrough = stream.PassThrough;
94
+ var Pend = require_pend();
95
+ var EventEmitter = require("events").EventEmitter;
96
+ exports2.createFromBuffer = createFromBuffer;
97
+ exports2.createFromFd = createFromFd;
98
+ exports2.BufferSlicer = BufferSlicer;
99
+ exports2.FdSlicer = FdSlicer;
100
+ util2.inherits(FdSlicer, EventEmitter);
101
+ function FdSlicer(fd, options2) {
102
+ options2 = options2 || {};
103
+ EventEmitter.call(this);
104
+ this.fd = fd;
105
+ this.pend = new Pend();
106
+ this.pend.max = 1;
107
+ this.refCount = 0;
108
+ this.autoClose = !!options2.autoClose;
109
+ }
110
+ FdSlicer.prototype.read = function(buffer, offset, length, position, callback) {
111
+ var self = this;
112
+ self.pend.go(function(cb) {
113
+ fs4.read(self.fd, buffer, offset, length, position, function(err, bytesRead, buffer2) {
114
+ cb();
115
+ callback(err, bytesRead, buffer2);
116
+ });
117
+ });
118
+ };
119
+ FdSlicer.prototype.write = function(buffer, offset, length, position, callback) {
120
+ var self = this;
121
+ self.pend.go(function(cb) {
122
+ fs4.write(self.fd, buffer, offset, length, position, function(err, written, buffer2) {
123
+ cb();
124
+ callback(err, written, buffer2);
125
+ });
126
+ });
127
+ };
128
+ FdSlicer.prototype.createReadStream = function(options2) {
129
+ return new ReadStream(this, options2);
130
+ };
131
+ FdSlicer.prototype.createWriteStream = function(options2) {
132
+ return new WriteStream(this, options2);
133
+ };
134
+ FdSlicer.prototype.ref = function() {
135
+ this.refCount += 1;
136
+ };
137
+ FdSlicer.prototype.unref = function() {
138
+ var self = this;
139
+ self.refCount -= 1;
140
+ if (self.refCount > 0) return;
141
+ if (self.refCount < 0) throw new Error("invalid unref");
142
+ if (self.autoClose) {
143
+ fs4.close(self.fd, onCloseDone);
144
+ }
145
+ function onCloseDone(err) {
146
+ if (err) {
147
+ self.emit("error", err);
148
+ } else {
149
+ self.emit("close");
150
+ }
151
+ }
152
+ };
153
+ util2.inherits(ReadStream, Readable);
154
+ function ReadStream(context, options2) {
155
+ options2 = options2 || {};
156
+ Readable.call(this, options2);
157
+ this.context = context;
158
+ this.context.ref();
159
+ this.start = options2.start || 0;
160
+ this.endOffset = options2.end;
161
+ this.pos = this.start;
162
+ this._destroyed = false;
163
+ }
164
+ ReadStream.prototype._read = function(n) {
165
+ var self = this;
166
+ if (self._destroyed) return;
167
+ var toRead = Math.min(self._readableState.highWaterMark, n);
168
+ if (self.endOffset != null) {
169
+ toRead = Math.min(toRead, self.endOffset - self.pos);
170
+ }
171
+ if (toRead <= 0) {
172
+ self._destroyed = true;
173
+ self.push(null);
174
+ self.context.unref();
175
+ return;
176
+ }
177
+ self.context.pend.go(function(cb) {
178
+ if (self._destroyed) return cb();
179
+ var buffer = Buffer.allocUnsafe(toRead);
180
+ fs4.read(self.context.fd, buffer, 0, toRead, self.pos, function(err, bytesRead) {
181
+ if (self._destroyed) return cb();
182
+ if (err) {
183
+ self.destroy(err);
184
+ } else if (bytesRead === 0) {
185
+ self._destroyed = true;
186
+ self.push(null);
187
+ self.context.unref();
188
+ } else {
189
+ self.pos += bytesRead;
190
+ self.push(buffer.slice(0, bytesRead));
191
+ }
192
+ cb();
193
+ });
194
+ });
195
+ };
196
+ ReadStream.prototype.destroy = function(err) {
197
+ if (err == null && !this.readableEnded) {
198
+ err = new Error("stream destroyed");
199
+ }
200
+ return Readable.prototype.destroy.call(this, err);
201
+ };
202
+ ReadStream.prototype._destroy = function(err, cb) {
203
+ if (!this._destroyed) {
204
+ this._destroyed = true;
205
+ this.context.unref();
206
+ }
207
+ cb(err);
208
+ };
209
+ util2.inherits(WriteStream, Writable);
210
+ function WriteStream(context, options2) {
211
+ options2 = options2 || {};
212
+ Writable.call(this, options2);
213
+ this.context = context;
214
+ this.context.ref();
215
+ this.start = options2.start || 0;
216
+ this.endOffset = options2.end == null ? Infinity : +options2.end;
217
+ this.bytesWritten = 0;
218
+ this.pos = this.start;
219
+ this._destroyed = false;
220
+ this.on("finish", this.destroy.bind(this));
221
+ }
222
+ WriteStream.prototype._write = function(buffer, encoding, callback) {
223
+ var self = this;
224
+ if (self._destroyed) return;
225
+ if (self.pos + buffer.length > self.endOffset) {
226
+ var err = new Error("maximum file length exceeded");
227
+ err.code = "ETOOBIG";
228
+ self.destroy();
229
+ callback(err);
230
+ return;
231
+ }
232
+ self.context.pend.go(function(cb) {
233
+ if (self._destroyed) return cb();
234
+ fs4.write(self.context.fd, buffer, 0, buffer.length, self.pos, function(err2, bytes) {
235
+ if (err2) {
236
+ self.destroy();
237
+ cb();
238
+ callback(err2);
239
+ } else {
240
+ self.bytesWritten += bytes;
241
+ self.pos += bytes;
242
+ self.emit("progress");
243
+ cb();
244
+ callback();
245
+ }
246
+ });
247
+ });
248
+ };
249
+ WriteStream.prototype._destroy = function(err, cb) {
250
+ if (!this._destroyed) {
251
+ this._destroyed = true;
252
+ this.context.unref();
253
+ }
254
+ cb(err);
255
+ };
256
+ util2.inherits(BufferSlicer, EventEmitter);
257
+ function BufferSlicer(buffer, options2) {
258
+ EventEmitter.call(this);
259
+ options2 = options2 || {};
260
+ this.refCount = 0;
261
+ this.buffer = buffer;
262
+ this.maxChunkSize = options2.maxChunkSize || Number.MAX_SAFE_INTEGER;
263
+ }
264
+ BufferSlicer.prototype.read = function(buffer, offset, length, position, callback) {
265
+ if (!(0 <= offset && offset <= buffer.length)) throw new RangeError("offset outside buffer: 0 <= " + offset + " <= " + buffer.length);
266
+ if (position < 0) throw new RangeError("position is negative: " + position);
267
+ if (offset + length > buffer.length) {
268
+ length = buffer.length - offset;
269
+ }
270
+ if (position + length > this.buffer.length) {
271
+ length = this.buffer.length - position;
272
+ }
273
+ if (length <= 0) {
274
+ setImmediate(function() {
275
+ callback(null, 0);
276
+ });
277
+ return;
278
+ }
279
+ this.buffer.copy(buffer, offset, position, position + length);
280
+ setImmediate(function() {
281
+ callback(null, length);
282
+ });
283
+ };
284
+ BufferSlicer.prototype.write = function(buffer, offset, length, position, callback) {
285
+ buffer.copy(this.buffer, position, offset, offset + length);
286
+ setImmediate(function() {
287
+ callback(null, length, buffer);
288
+ });
289
+ };
290
+ BufferSlicer.prototype.createReadStream = function(options2) {
291
+ options2 = options2 || {};
292
+ var readStream = new PassThrough(options2);
293
+ readStream._destroyed = false;
294
+ readStream.start = options2.start || 0;
295
+ readStream.endOffset = options2.end;
296
+ readStream.pos = readStream.endOffset || this.buffer.length;
297
+ var entireSlice = this.buffer.slice(readStream.start, readStream.pos);
298
+ var offset = 0;
299
+ while (true) {
300
+ var nextOffset = offset + this.maxChunkSize;
301
+ if (nextOffset >= entireSlice.length) {
302
+ if (offset < entireSlice.length) {
303
+ readStream.write(entireSlice.slice(offset, entireSlice.length));
304
+ }
305
+ break;
306
+ }
307
+ readStream.write(entireSlice.slice(offset, nextOffset));
308
+ offset = nextOffset;
309
+ }
310
+ readStream.end();
311
+ readStream._destroy = function(err, cb) {
312
+ readStream._destroyed = true;
313
+ PassThrough.prototype._destroy.call(readStream, err, cb);
314
+ };
315
+ return readStream;
316
+ };
317
+ BufferSlicer.prototype.createWriteStream = function(options2) {
318
+ var bufferSlicer = this;
319
+ options2 = options2 || {};
320
+ var writeStream = new Writable(options2);
321
+ writeStream.start = options2.start || 0;
322
+ writeStream.endOffset = options2.end == null ? this.buffer.length : +options2.end;
323
+ writeStream.bytesWritten = 0;
324
+ writeStream.pos = writeStream.start;
325
+ writeStream._destroyed = false;
326
+ writeStream._write = function(buffer, encoding, callback) {
327
+ if (writeStream._destroyed) return;
328
+ var end = writeStream.pos + buffer.length;
329
+ if (end > writeStream.endOffset) {
330
+ var err = new Error("maximum file length exceeded");
331
+ err.code = "ETOOBIG";
332
+ writeStream._destroyed = true;
333
+ callback(err);
334
+ return;
335
+ }
336
+ buffer.copy(bufferSlicer.buffer, writeStream.pos, 0, buffer.length);
337
+ writeStream.bytesWritten += buffer.length;
338
+ writeStream.pos = end;
339
+ writeStream.emit("progress");
340
+ callback();
341
+ };
342
+ writeStream._destroy = function(err, cb) {
343
+ writeStream._destroyed = true;
344
+ cb(err);
345
+ };
346
+ return writeStream;
347
+ };
348
+ BufferSlicer.prototype.ref = function() {
349
+ this.refCount += 1;
350
+ };
351
+ BufferSlicer.prototype.unref = function() {
352
+ this.refCount -= 1;
353
+ if (this.refCount < 0) {
354
+ throw new Error("invalid unref");
355
+ }
356
+ };
357
+ function createFromBuffer(buffer, options2) {
358
+ return new BufferSlicer(buffer, options2);
359
+ }
360
+ function createFromFd(fd, options2) {
361
+ return new FdSlicer(fd, options2);
362
+ }
363
+ }
364
+ });
365
+
366
+ // packages/utils/third_party/yauzl/buffer-crc32.js
367
+ var require_buffer_crc32 = __commonJS({
368
+ "packages/utils/third_party/yauzl/buffer-crc32.js"(exports2, module2) {
369
+ "use strict";
370
+ var Buffer2 = require("buffer").Buffer;
371
+ var CRC_TABLE = [
372
+ 0,
373
+ 1996959894,
374
+ 3993919788,
375
+ 2567524794,
376
+ 124634137,
377
+ 1886057615,
378
+ 3915621685,
379
+ 2657392035,
380
+ 249268274,
381
+ 2044508324,
382
+ 3772115230,
383
+ 2547177864,
384
+ 162941995,
385
+ 2125561021,
386
+ 3887607047,
387
+ 2428444049,
388
+ 498536548,
389
+ 1789927666,
390
+ 4089016648,
391
+ 2227061214,
392
+ 450548861,
393
+ 1843258603,
394
+ 4107580753,
395
+ 2211677639,
396
+ 325883990,
397
+ 1684777152,
398
+ 4251122042,
399
+ 2321926636,
400
+ 335633487,
401
+ 1661365465,
402
+ 4195302755,
403
+ 2366115317,
404
+ 997073096,
405
+ 1281953886,
406
+ 3579855332,
407
+ 2724688242,
408
+ 1006888145,
409
+ 1258607687,
410
+ 3524101629,
411
+ 2768942443,
412
+ 901097722,
413
+ 1119000684,
414
+ 3686517206,
415
+ 2898065728,
416
+ 853044451,
417
+ 1172266101,
418
+ 3705015759,
419
+ 2882616665,
420
+ 651767980,
421
+ 1373503546,
422
+ 3369554304,
423
+ 3218104598,
424
+ 565507253,
425
+ 1454621731,
426
+ 3485111705,
427
+ 3099436303,
428
+ 671266974,
429
+ 1594198024,
430
+ 3322730930,
431
+ 2970347812,
432
+ 795835527,
433
+ 1483230225,
434
+ 3244367275,
435
+ 3060149565,
436
+ 1994146192,
437
+ 31158534,
438
+ 2563907772,
439
+ 4023717930,
440
+ 1907459465,
441
+ 112637215,
442
+ 2680153253,
443
+ 3904427059,
444
+ 2013776290,
445
+ 251722036,
446
+ 2517215374,
447
+ 3775830040,
448
+ 2137656763,
449
+ 141376813,
450
+ 2439277719,
451
+ 3865271297,
452
+ 1802195444,
453
+ 476864866,
454
+ 2238001368,
455
+ 4066508878,
456
+ 1812370925,
457
+ 453092731,
458
+ 2181625025,
459
+ 4111451223,
460
+ 1706088902,
461
+ 314042704,
462
+ 2344532202,
463
+ 4240017532,
464
+ 1658658271,
465
+ 366619977,
466
+ 2362670323,
467
+ 4224994405,
468
+ 1303535960,
469
+ 984961486,
470
+ 2747007092,
471
+ 3569037538,
472
+ 1256170817,
473
+ 1037604311,
474
+ 2765210733,
475
+ 3554079995,
476
+ 1131014506,
477
+ 879679996,
478
+ 2909243462,
479
+ 3663771856,
480
+ 1141124467,
481
+ 855842277,
482
+ 2852801631,
483
+ 3708648649,
484
+ 1342533948,
485
+ 654459306,
486
+ 3188396048,
487
+ 3373015174,
488
+ 1466479909,
489
+ 544179635,
490
+ 3110523913,
491
+ 3462522015,
492
+ 1591671054,
493
+ 702138776,
494
+ 2966460450,
495
+ 3352799412,
496
+ 1504918807,
497
+ 783551873,
498
+ 3082640443,
499
+ 3233442989,
500
+ 3988292384,
501
+ 2596254646,
502
+ 62317068,
503
+ 1957810842,
504
+ 3939845945,
505
+ 2647816111,
506
+ 81470997,
507
+ 1943803523,
508
+ 3814918930,
509
+ 2489596804,
510
+ 225274430,
511
+ 2053790376,
512
+ 3826175755,
513
+ 2466906013,
514
+ 167816743,
515
+ 2097651377,
516
+ 4027552580,
517
+ 2265490386,
518
+ 503444072,
519
+ 1762050814,
520
+ 4150417245,
521
+ 2154129355,
522
+ 426522225,
523
+ 1852507879,
524
+ 4275313526,
525
+ 2312317920,
526
+ 282753626,
527
+ 1742555852,
528
+ 4189708143,
529
+ 2394877945,
530
+ 397917763,
531
+ 1622183637,
532
+ 3604390888,
533
+ 2714866558,
534
+ 953729732,
535
+ 1340076626,
536
+ 3518719985,
537
+ 2797360999,
538
+ 1068828381,
539
+ 1219638859,
540
+ 3624741850,
541
+ 2936675148,
542
+ 906185462,
543
+ 1090812512,
544
+ 3747672003,
545
+ 2825379669,
546
+ 829329135,
547
+ 1181335161,
548
+ 3412177804,
549
+ 3160834842,
550
+ 628085408,
551
+ 1382605366,
552
+ 3423369109,
553
+ 3138078467,
554
+ 570562233,
555
+ 1426400815,
556
+ 3317316542,
557
+ 2998733608,
558
+ 733239954,
559
+ 1555261956,
560
+ 3268935591,
561
+ 3050360625,
562
+ 752459403,
563
+ 1541320221,
564
+ 2607071920,
565
+ 3965973030,
566
+ 1969922972,
567
+ 40735498,
568
+ 2617837225,
569
+ 3943577151,
570
+ 1913087877,
571
+ 83908371,
572
+ 2512341634,
573
+ 3803740692,
574
+ 2075208622,
575
+ 213261112,
576
+ 2463272603,
577
+ 3855990285,
578
+ 2094854071,
579
+ 198958881,
580
+ 2262029012,
581
+ 4057260610,
582
+ 1759359992,
583
+ 534414190,
584
+ 2176718541,
585
+ 4139329115,
586
+ 1873836001,
587
+ 414664567,
588
+ 2282248934,
589
+ 4279200368,
590
+ 1711684554,
591
+ 285281116,
592
+ 2405801727,
593
+ 4167216745,
594
+ 1634467795,
595
+ 376229701,
596
+ 2685067896,
597
+ 3608007406,
598
+ 1308918612,
599
+ 956543938,
600
+ 2808555105,
601
+ 3495958263,
602
+ 1231636301,
603
+ 1047427035,
604
+ 2932959818,
605
+ 3654703836,
606
+ 1088359270,
607
+ 936918e3,
608
+ 2847714899,
609
+ 3736837829,
610
+ 1202900863,
611
+ 817233897,
612
+ 3183342108,
613
+ 3401237130,
614
+ 1404277552,
615
+ 615818150,
616
+ 3134207493,
617
+ 3453421203,
618
+ 1423857449,
619
+ 601450431,
620
+ 3009837614,
621
+ 3294710456,
622
+ 1567103746,
623
+ 711928724,
624
+ 3020668471,
625
+ 3272380065,
626
+ 1510334235,
627
+ 755167117
628
+ ];
629
+ if (typeof Int32Array !== "undefined") {
630
+ CRC_TABLE = new Int32Array(CRC_TABLE);
631
+ }
632
+ function ensureBuffer(input) {
633
+ if (Buffer2.isBuffer(input)) {
634
+ return input;
635
+ }
636
+ var hasNewBufferAPI = typeof Buffer2.alloc === "function" && typeof Buffer2.from === "function";
637
+ if (typeof input === "number") {
638
+ return hasNewBufferAPI ? Buffer2.alloc(input) : new Buffer2(input);
639
+ } else if (typeof input === "string") {
640
+ return hasNewBufferAPI ? Buffer2.from(input) : new Buffer2(input);
641
+ } else {
642
+ throw new Error("input must be buffer, number, or string, received " + typeof input);
643
+ }
644
+ }
645
+ function bufferizeInt(num) {
646
+ var tmp = ensureBuffer(4);
647
+ tmp.writeInt32BE(num, 0);
648
+ return tmp;
649
+ }
650
+ function _crc32(buf, previous) {
651
+ buf = ensureBuffer(buf);
652
+ if (Buffer2.isBuffer(previous)) {
653
+ previous = previous.readUInt32BE(0);
654
+ }
655
+ var crc = ~~previous ^ -1;
656
+ for (var n = 0; n < buf.length; n++) {
657
+ crc = CRC_TABLE[(crc ^ buf[n]) & 255] ^ crc >>> 8;
658
+ }
659
+ return crc ^ -1;
660
+ }
661
+ function crc32() {
662
+ return bufferizeInt(_crc32.apply(null, arguments));
663
+ }
664
+ crc32.signed = function() {
665
+ return _crc32.apply(null, arguments);
666
+ };
667
+ crc32.unsigned = function() {
668
+ return _crc32.apply(null, arguments) >>> 0;
669
+ };
670
+ module2.exports = crc32;
671
+ }
672
+ });
673
+
674
+ // packages/utils/third_party/yauzl/index.js
675
+ var require_yauzl = __commonJS({
676
+ "packages/utils/third_party/yauzl/index.js"(exports2) {
677
+ "use strict";
678
+ var fs4 = require("fs");
679
+ var zlib = require("zlib");
680
+ var fd_slicer = require_fd_slicer();
681
+ var crc32 = require_buffer_crc32();
682
+ var util2 = require("util");
683
+ var EventEmitter = require("events").EventEmitter;
684
+ var Transform = require("stream").Transform;
685
+ var PassThrough = require("stream").PassThrough;
686
+ var Writable = require("stream").Writable;
687
+ exports2.open = open2;
688
+ exports2.fromFd = fromFd;
689
+ exports2.fromBuffer = fromBuffer;
690
+ exports2.fromRandomAccessReader = fromRandomAccessReader;
691
+ exports2.dosDateTimeToDate = dosDateTimeToDate;
692
+ exports2.getFileNameLowLevel = getFileNameLowLevel;
693
+ exports2.validateFileName = validateFileName;
694
+ exports2.parseExtraFields = parseExtraFields;
695
+ exports2.ZipFile = ZipFile;
696
+ exports2.Entry = Entry;
697
+ exports2.LocalFileHeader = LocalFileHeader;
698
+ exports2.RandomAccessReader = RandomAccessReader;
699
+ function open2(path4, options2, callback) {
700
+ if (typeof options2 === "function") {
701
+ callback = options2;
702
+ options2 = null;
703
+ }
704
+ if (options2 == null) options2 = {};
705
+ if (options2.autoClose == null) options2.autoClose = true;
706
+ if (options2.lazyEntries == null) options2.lazyEntries = false;
707
+ if (options2.decodeStrings == null) options2.decodeStrings = true;
708
+ if (options2.validateEntrySizes == null) options2.validateEntrySizes = true;
709
+ if (options2.strictFileNames == null) options2.strictFileNames = false;
710
+ if (callback == null) callback = defaultCallback;
711
+ fs4.open(path4, "r", function(err, fd) {
712
+ if (err) return callback(err);
713
+ fromFd(fd, options2, function(err2, zipfile) {
714
+ if (err2) fs4.close(fd, defaultCallback);
715
+ callback(err2, zipfile);
716
+ });
717
+ });
718
+ }
719
+ function fromFd(fd, options2, callback) {
720
+ if (typeof options2 === "function") {
721
+ callback = options2;
722
+ options2 = null;
723
+ }
724
+ if (options2 == null) options2 = {};
725
+ if (options2.autoClose == null) options2.autoClose = false;
726
+ if (options2.lazyEntries == null) options2.lazyEntries = false;
727
+ if (options2.decodeStrings == null) options2.decodeStrings = true;
728
+ if (options2.validateEntrySizes == null) options2.validateEntrySizes = true;
729
+ if (options2.strictFileNames == null) options2.strictFileNames = false;
730
+ if (callback == null) callback = defaultCallback;
731
+ fs4.fstat(fd, function(err, stats) {
732
+ if (err) return callback(err);
733
+ var reader = fd_slicer.createFromFd(fd, { autoClose: true });
734
+ fromRandomAccessReader(reader, stats.size, options2, callback);
735
+ });
736
+ }
737
+ function fromBuffer(buffer, options2, callback) {
738
+ if (typeof options2 === "function") {
739
+ callback = options2;
740
+ options2 = null;
741
+ }
742
+ if (options2 == null) options2 = {};
743
+ options2.autoClose = false;
744
+ if (options2.lazyEntries == null) options2.lazyEntries = false;
745
+ if (options2.decodeStrings == null) options2.decodeStrings = true;
746
+ if (options2.validateEntrySizes == null) options2.validateEntrySizes = true;
747
+ if (options2.strictFileNames == null) options2.strictFileNames = false;
748
+ var reader = fd_slicer.createFromBuffer(buffer, { maxChunkSize: 65536 });
749
+ fromRandomAccessReader(reader, buffer.length, options2, callback);
750
+ }
751
+ function fromRandomAccessReader(reader, totalSize, options2, callback) {
752
+ if (typeof options2 === "function") {
753
+ callback = options2;
754
+ options2 = null;
755
+ }
756
+ if (options2 == null) options2 = {};
757
+ if (options2.autoClose == null) options2.autoClose = true;
758
+ if (options2.lazyEntries == null) options2.lazyEntries = false;
759
+ if (options2.decodeStrings == null) options2.decodeStrings = true;
760
+ var decodeStrings = !!options2.decodeStrings;
761
+ if (options2.validateEntrySizes == null) options2.validateEntrySizes = true;
762
+ if (options2.strictFileNames == null) options2.strictFileNames = false;
763
+ if (callback == null) callback = defaultCallback;
764
+ if (typeof totalSize !== "number") throw new Error("expected totalSize parameter to be a number");
765
+ if (totalSize > Number.MAX_SAFE_INTEGER) {
766
+ throw new Error("zip file too large. only file sizes up to 2^52 are supported due to JavaScript's Number type being an IEEE 754 double.");
767
+ }
768
+ reader.ref();
769
+ var eocdrWithoutCommentSize = 22;
770
+ var zip64EocdlSize = 20;
771
+ var maxCommentSize = 65535;
772
+ var bufferSize = Math.min(zip64EocdlSize + eocdrWithoutCommentSize + maxCommentSize, totalSize);
773
+ var buffer = newBuffer(bufferSize);
774
+ var bufferReadStart = totalSize - buffer.length;
775
+ readAndAssertNoEof(reader, buffer, 0, bufferSize, bufferReadStart, function(err) {
776
+ if (err) return callback(err);
777
+ for (var i = bufferSize - eocdrWithoutCommentSize; i >= 0; i -= 1) {
778
+ if (buffer.readUInt32LE(i) !== 101010256) continue;
779
+ var eocdrBuffer = buffer.subarray(i);
780
+ var diskNumber = eocdrBuffer.readUInt16LE(4);
781
+ var entryCount = eocdrBuffer.readUInt16LE(10);
782
+ var centralDirectoryOffset = eocdrBuffer.readUInt32LE(16);
783
+ var commentLength = eocdrBuffer.readUInt16LE(20);
784
+ var expectedCommentLength = eocdrBuffer.length - eocdrWithoutCommentSize;
785
+ if (commentLength !== expectedCommentLength) {
786
+ return callback(new Error("Invalid comment length. Expected: " + expectedCommentLength + ". Found: " + commentLength + ". Are there extra bytes at the end of the file? Or is the end of central dir signature `PK\u263A\u263B` in the comment?"));
787
+ }
788
+ var comment = decodeStrings ? decodeBuffer(eocdrBuffer.subarray(22), false) : eocdrBuffer.subarray(22);
789
+ if (i - zip64EocdlSize >= 0 && buffer.readUInt32LE(i - zip64EocdlSize) === 117853008) {
790
+ var zip64EocdlBuffer = buffer.subarray(i - zip64EocdlSize, i - zip64EocdlSize + zip64EocdlSize);
791
+ var zip64EocdrOffset = readUInt64LE(zip64EocdlBuffer, 8);
792
+ var zip64EocdrBuffer = newBuffer(56);
793
+ return readAndAssertNoEof(reader, zip64EocdrBuffer, 0, zip64EocdrBuffer.length, zip64EocdrOffset, function(err2) {
794
+ if (err2) return callback(err2);
795
+ if (zip64EocdrBuffer.readUInt32LE(0) !== 101075792) {
796
+ return callback(new Error("invalid zip64 end of central directory record signature"));
797
+ }
798
+ diskNumber = zip64EocdrBuffer.readUInt32LE(16);
799
+ if (diskNumber !== 0) {
800
+ return callback(new Error("multi-disk zip files are not supported: found disk number: " + diskNumber));
801
+ }
802
+ entryCount = readUInt64LE(zip64EocdrBuffer, 32);
803
+ centralDirectoryOffset = readUInt64LE(zip64EocdrBuffer, 48);
804
+ return callback(null, new ZipFile(reader, centralDirectoryOffset, totalSize, entryCount, comment, options2.autoClose, options2.lazyEntries, decodeStrings, options2.validateEntrySizes, options2.strictFileNames));
805
+ });
806
+ }
807
+ if (diskNumber !== 0) {
808
+ return callback(new Error("multi-disk zip files are not supported: found disk number: " + diskNumber));
809
+ }
810
+ return callback(null, new ZipFile(reader, centralDirectoryOffset, totalSize, entryCount, comment, options2.autoClose, options2.lazyEntries, decodeStrings, options2.validateEntrySizes, options2.strictFileNames));
811
+ }
812
+ callback(new Error("End of central directory record signature not found. Either not a zip file, or file is truncated."));
813
+ });
814
+ }
815
+ util2.inherits(ZipFile, EventEmitter);
816
+ function ZipFile(reader, centralDirectoryOffset, fileSize, entryCount, comment, autoClose, lazyEntries, decodeStrings, validateEntrySizes, strictFileNames) {
817
+ var self = this;
818
+ EventEmitter.call(self);
819
+ self.reader = reader;
820
+ self.reader.on("error", function(err) {
821
+ emitError(self, err);
822
+ });
823
+ self.reader.once("close", function() {
824
+ self.emit("close");
825
+ });
826
+ self.readEntryCursor = centralDirectoryOffset;
827
+ self.fileSize = fileSize;
828
+ self.entryCount = entryCount;
829
+ self.comment = comment;
830
+ self.entriesRead = 0;
831
+ self.autoClose = !!autoClose;
832
+ self.lazyEntries = !!lazyEntries;
833
+ self.decodeStrings = !!decodeStrings;
834
+ self.validateEntrySizes = !!validateEntrySizes;
835
+ self.strictFileNames = !!strictFileNames;
836
+ self.isOpen = true;
837
+ self.emittedError = false;
838
+ if (!self.lazyEntries) self._readEntry();
839
+ }
840
+ ZipFile.prototype.close = function() {
841
+ if (!this.isOpen) return;
842
+ this.isOpen = false;
843
+ this.reader.unref();
844
+ };
845
+ function emitErrorAndAutoClose(self, err) {
846
+ if (self.autoClose) self.close();
847
+ emitError(self, err);
848
+ }
849
+ function emitError(self, err) {
850
+ if (self.emittedError) return;
851
+ self.emittedError = true;
852
+ self.emit("error", err);
853
+ }
854
+ ZipFile.prototype.readEntry = function() {
855
+ if (!this.lazyEntries) throw new Error("readEntry() called without lazyEntries:true");
856
+ this._readEntry();
857
+ };
858
+ ZipFile.prototype._readEntry = function() {
859
+ var self = this;
860
+ if (self.entryCount === self.entriesRead) {
861
+ setImmediate(function() {
862
+ if (self.autoClose) self.close();
863
+ if (self.emittedError) return;
864
+ self.emit("end");
865
+ });
866
+ return;
867
+ }
868
+ if (self.emittedError) return;
869
+ var buffer = newBuffer(46);
870
+ readAndAssertNoEof(self.reader, buffer, 0, buffer.length, self.readEntryCursor, function(err) {
871
+ if (err) return emitErrorAndAutoClose(self, err);
872
+ if (self.emittedError) return;
873
+ var entry = new Entry();
874
+ var signature = buffer.readUInt32LE(0);
875
+ if (signature !== 33639248) return emitErrorAndAutoClose(self, new Error("invalid central directory file header signature: 0x" + signature.toString(16)));
876
+ entry.versionMadeBy = buffer.readUInt16LE(4);
877
+ entry.versionNeededToExtract = buffer.readUInt16LE(6);
878
+ entry.generalPurposeBitFlag = buffer.readUInt16LE(8);
879
+ entry.compressionMethod = buffer.readUInt16LE(10);
880
+ entry.lastModFileTime = buffer.readUInt16LE(12);
881
+ entry.lastModFileDate = buffer.readUInt16LE(14);
882
+ entry.crc32 = buffer.readUInt32LE(16);
883
+ entry.compressedSize = buffer.readUInt32LE(20);
884
+ entry.uncompressedSize = buffer.readUInt32LE(24);
885
+ entry.fileNameLength = buffer.readUInt16LE(28);
886
+ entry.extraFieldLength = buffer.readUInt16LE(30);
887
+ entry.fileCommentLength = buffer.readUInt16LE(32);
888
+ entry.internalFileAttributes = buffer.readUInt16LE(36);
889
+ entry.externalFileAttributes = buffer.readUInt32LE(38);
890
+ entry.relativeOffsetOfLocalHeader = buffer.readUInt32LE(42);
891
+ if (entry.generalPurposeBitFlag & 64) return emitErrorAndAutoClose(self, new Error("strong encryption is not supported"));
892
+ self.readEntryCursor += 46;
893
+ buffer = newBuffer(entry.fileNameLength + entry.extraFieldLength + entry.fileCommentLength);
894
+ readAndAssertNoEof(self.reader, buffer, 0, buffer.length, self.readEntryCursor, function(err2) {
895
+ if (err2) return emitErrorAndAutoClose(self, err2);
896
+ if (self.emittedError) return;
897
+ entry.fileNameRaw = buffer.subarray(0, entry.fileNameLength);
898
+ var fileCommentStart = entry.fileNameLength + entry.extraFieldLength;
899
+ entry.extraFieldRaw = buffer.subarray(entry.fileNameLength, fileCommentStart);
900
+ entry.fileCommentRaw = buffer.subarray(fileCommentStart, fileCommentStart + entry.fileCommentLength);
901
+ try {
902
+ entry.extraFields = parseExtraFields(entry.extraFieldRaw);
903
+ } catch (err3) {
904
+ return emitErrorAndAutoClose(self, err3);
905
+ }
906
+ if (self.decodeStrings) {
907
+ var isUtf8 = (entry.generalPurposeBitFlag & 2048) !== 0;
908
+ entry.fileComment = decodeBuffer(entry.fileCommentRaw, isUtf8);
909
+ entry.fileName = getFileNameLowLevel(entry.generalPurposeBitFlag, entry.fileNameRaw, entry.extraFields, self.strictFileNames);
910
+ var errorMessage = validateFileName(entry.fileName);
911
+ if (errorMessage != null) return emitErrorAndAutoClose(self, new Error(errorMessage));
912
+ } else {
913
+ entry.fileComment = entry.fileCommentRaw;
914
+ entry.fileName = entry.fileNameRaw;
915
+ }
916
+ entry.comment = entry.fileComment;
917
+ self.readEntryCursor += buffer.length;
918
+ self.entriesRead += 1;
919
+ for (var i = 0; i < entry.extraFields.length; i++) {
920
+ var extraField = entry.extraFields[i];
921
+ if (extraField.id !== 1) continue;
922
+ var zip64EiefBuffer = extraField.data;
923
+ var index = 0;
924
+ if (entry.uncompressedSize === 4294967295) {
925
+ if (index + 8 > zip64EiefBuffer.length) {
926
+ return emitErrorAndAutoClose(self, new Error("zip64 extended information extra field does not include uncompressed size"));
927
+ }
928
+ entry.uncompressedSize = readUInt64LE(zip64EiefBuffer, index);
929
+ index += 8;
930
+ }
931
+ if (entry.compressedSize === 4294967295) {
932
+ if (index + 8 > zip64EiefBuffer.length) {
933
+ return emitErrorAndAutoClose(self, new Error("zip64 extended information extra field does not include compressed size"));
934
+ }
935
+ entry.compressedSize = readUInt64LE(zip64EiefBuffer, index);
936
+ index += 8;
937
+ }
938
+ if (entry.relativeOffsetOfLocalHeader === 4294967295) {
939
+ if (index + 8 > zip64EiefBuffer.length) {
940
+ return emitErrorAndAutoClose(self, new Error("zip64 extended information extra field does not include relative header offset"));
941
+ }
942
+ entry.relativeOffsetOfLocalHeader = readUInt64LE(zip64EiefBuffer, index);
943
+ index += 8;
944
+ }
945
+ break;
946
+ }
947
+ if (self.validateEntrySizes && entry.compressionMethod === 0) {
948
+ var expectedCompressedSize = entry.uncompressedSize;
949
+ if (entry.isEncrypted()) {
950
+ expectedCompressedSize += 12;
951
+ }
952
+ if (entry.compressedSize !== expectedCompressedSize) {
953
+ var msg = "compressed/uncompressed size mismatch for stored file: " + entry.compressedSize + " != " + entry.uncompressedSize;
954
+ return emitErrorAndAutoClose(self, new Error(msg));
955
+ }
956
+ }
957
+ self.emit("entry", entry);
958
+ if (!self.lazyEntries) self._readEntry();
959
+ });
960
+ });
961
+ };
962
+ ZipFile.prototype.openReadStream = function(entry, options2, callback) {
963
+ var self = this;
964
+ var relativeStart = 0;
965
+ var relativeEnd = entry.compressedSize;
966
+ if (callback == null) {
967
+ callback = options2;
968
+ options2 = null;
969
+ }
970
+ if (options2 == null) {
971
+ options2 = {};
972
+ } else {
973
+ if (options2.decrypt != null) {
974
+ if (!entry.isEncrypted()) {
975
+ throw new Error("options.decrypt can only be specified for encrypted entries");
976
+ }
977
+ if (options2.decrypt !== false) throw new Error("invalid options.decrypt value: " + options2.decrypt);
978
+ if (entry.isCompressed()) {
979
+ if (options2.decompress !== false) throw new Error("entry is encrypted and compressed, and options.decompress !== false");
980
+ }
981
+ }
982
+ if (options2.decompress != null) {
983
+ if (!entry.isCompressed()) {
984
+ throw new Error("options.decompress can only be specified for compressed entries");
985
+ }
986
+ if (!(options2.decompress === false || options2.decompress === true)) {
987
+ throw new Error("invalid options.decompress value: " + options2.decompress);
988
+ }
989
+ }
990
+ if (options2.start != null || options2.end != null) {
991
+ if (entry.isCompressed() && options2.decompress !== false) {
992
+ throw new Error("start/end range not allowed for compressed entry without options.decompress === false");
993
+ }
994
+ if (entry.isEncrypted() && options2.decrypt !== false) {
995
+ throw new Error("start/end range not allowed for encrypted entry without options.decrypt === false");
996
+ }
997
+ }
998
+ if (options2.start != null) {
999
+ relativeStart = options2.start;
1000
+ if (relativeStart < 0) throw new Error("options.start < 0");
1001
+ if (relativeStart > entry.compressedSize) throw new Error("options.start > entry.compressedSize");
1002
+ }
1003
+ if (options2.end != null) {
1004
+ relativeEnd = options2.end;
1005
+ if (relativeEnd < 0) throw new Error("options.end < 0");
1006
+ if (relativeEnd > entry.compressedSize) throw new Error("options.end > entry.compressedSize");
1007
+ if (relativeEnd < relativeStart) throw new Error("options.end < options.start");
1008
+ }
1009
+ }
1010
+ if (!self.isOpen) return callback(new Error("closed"));
1011
+ if (entry.isEncrypted()) {
1012
+ if (options2.decrypt !== false) return callback(new Error("entry is encrypted, and options.decrypt !== false"));
1013
+ }
1014
+ var decompress;
1015
+ if (entry.compressionMethod === 0) {
1016
+ decompress = false;
1017
+ } else if (entry.compressionMethod === 8) {
1018
+ decompress = options2.decompress != null ? options2.decompress : true;
1019
+ } else {
1020
+ return callback(new Error("unsupported compression method: " + entry.compressionMethod));
1021
+ }
1022
+ self.readLocalFileHeader(entry, { minimal: true }, function(err, localFileHeader) {
1023
+ if (err) return callback(err);
1024
+ self.openReadStreamLowLevel(
1025
+ localFileHeader.fileDataStart,
1026
+ entry.compressedSize,
1027
+ relativeStart,
1028
+ relativeEnd,
1029
+ decompress,
1030
+ entry.uncompressedSize,
1031
+ callback
1032
+ );
1033
+ });
1034
+ };
1035
+ ZipFile.prototype.openReadStreamLowLevel = function(fileDataStart, compressedSize, relativeStart, relativeEnd, decompress, uncompressedSize, callback) {
1036
+ var self = this;
1037
+ var fileDataEnd = fileDataStart + compressedSize;
1038
+ var readStream = self.reader.createReadStream({
1039
+ start: fileDataStart + relativeStart,
1040
+ end: fileDataStart + relativeEnd
1041
+ });
1042
+ var endpointStream = readStream;
1043
+ if (decompress) {
1044
+ var destroyed = false;
1045
+ var inflateFilter = zlib.createInflateRaw();
1046
+ readStream.on("error", function(err) {
1047
+ setImmediate(function() {
1048
+ if (!destroyed) inflateFilter.emit("error", err);
1049
+ });
1050
+ });
1051
+ readStream.pipe(inflateFilter);
1052
+ if (self.validateEntrySizes) {
1053
+ endpointStream = new AssertByteCountStream(uncompressedSize);
1054
+ inflateFilter.on("error", function(err) {
1055
+ setImmediate(function() {
1056
+ if (!destroyed) endpointStream.emit("error", err);
1057
+ });
1058
+ });
1059
+ inflateFilter.pipe(endpointStream);
1060
+ } else {
1061
+ endpointStream = inflateFilter;
1062
+ }
1063
+ installDestroyFn(endpointStream, function() {
1064
+ destroyed = true;
1065
+ if (inflateFilter !== endpointStream) inflateFilter.unpipe(endpointStream);
1066
+ readStream.unpipe(inflateFilter);
1067
+ readStream.destroy();
1068
+ });
1069
+ }
1070
+ callback(null, endpointStream);
1071
+ };
1072
+ ZipFile.prototype.readLocalFileHeader = function(entry, options2, callback) {
1073
+ var self = this;
1074
+ if (callback == null) {
1075
+ callback = options2;
1076
+ options2 = null;
1077
+ }
1078
+ if (options2 == null) options2 = {};
1079
+ self.reader.ref();
1080
+ var buffer = newBuffer(30);
1081
+ readAndAssertNoEof(self.reader, buffer, 0, buffer.length, entry.relativeOffsetOfLocalHeader, function(err) {
1082
+ try {
1083
+ if (err) return callback(err);
1084
+ var signature = buffer.readUInt32LE(0);
1085
+ if (signature !== 67324752) {
1086
+ return callback(new Error("invalid local file header signature: 0x" + signature.toString(16)));
1087
+ }
1088
+ var fileNameLength = buffer.readUInt16LE(26);
1089
+ var extraFieldLength = buffer.readUInt16LE(28);
1090
+ var fileDataStart = entry.relativeOffsetOfLocalHeader + 30 + fileNameLength + extraFieldLength;
1091
+ if (fileDataStart + entry.compressedSize > self.fileSize) {
1092
+ return callback(new Error("file data overflows file bounds: " + fileDataStart + " + " + entry.compressedSize + " > " + self.fileSize));
1093
+ }
1094
+ if (options2.minimal) {
1095
+ return callback(null, { fileDataStart });
1096
+ }
1097
+ var localFileHeader = new LocalFileHeader();
1098
+ localFileHeader.fileDataStart = fileDataStart;
1099
+ localFileHeader.versionNeededToExtract = buffer.readUInt16LE(4);
1100
+ localFileHeader.generalPurposeBitFlag = buffer.readUInt16LE(6);
1101
+ localFileHeader.compressionMethod = buffer.readUInt16LE(8);
1102
+ localFileHeader.lastModFileTime = buffer.readUInt16LE(10);
1103
+ localFileHeader.lastModFileDate = buffer.readUInt16LE(12);
1104
+ localFileHeader.crc32 = buffer.readUInt32LE(14);
1105
+ localFileHeader.compressedSize = buffer.readUInt32LE(18);
1106
+ localFileHeader.uncompressedSize = buffer.readUInt32LE(22);
1107
+ localFileHeader.fileNameLength = fileNameLength;
1108
+ localFileHeader.extraFieldLength = extraFieldLength;
1109
+ buffer = newBuffer(fileNameLength + extraFieldLength);
1110
+ self.reader.ref();
1111
+ readAndAssertNoEof(self.reader, buffer, 0, buffer.length, entry.relativeOffsetOfLocalHeader + 30, function(err2) {
1112
+ try {
1113
+ if (err2) return callback(err2);
1114
+ localFileHeader.fileName = buffer.subarray(0, fileNameLength);
1115
+ localFileHeader.extraField = buffer.subarray(fileNameLength);
1116
+ return callback(null, localFileHeader);
1117
+ } finally {
1118
+ self.reader.unref();
1119
+ }
1120
+ });
1121
+ } finally {
1122
+ self.reader.unref();
1123
+ }
1124
+ });
1125
+ };
1126
+ function Entry() {
1127
+ }
1128
+ Entry.prototype.getLastModDate = function(options2) {
1129
+ if (options2 == null) options2 = {};
1130
+ if (!options2.forceDosFormat) {
1131
+ for (var i = 0; i < this.extraFields.length; i++) {
1132
+ var extraField = this.extraFields[i];
1133
+ if (extraField.id === 21589) {
1134
+ var data = extraField.data;
1135
+ if (data.length < 5) continue;
1136
+ var flags = data[0];
1137
+ var HAS_MTIME = 1;
1138
+ if (!(flags & HAS_MTIME)) continue;
1139
+ var posixTimestamp = data.readInt32LE(1);
1140
+ return new Date(posixTimestamp * 1e3);
1141
+ } else if (extraField.id === 10) {
1142
+ var data = extraField.data;
1143
+ if (data.length !== 32) continue;
1144
+ if (data.readUInt16LE(4) !== 1) continue;
1145
+ if (data.readUInt16LE(6) !== 24) continue;
1146
+ var hundredNanoSecondsSince1601 = data.readUInt32LE(8) + 4294967296 * data.readInt32LE(12);
1147
+ var millisecondsSince1970 = hundredNanoSecondsSince1601 / 1e4 - 116444736e5;
1148
+ return new Date(millisecondsSince1970);
1149
+ }
1150
+ }
1151
+ }
1152
+ return dosDateTimeToDate(this.lastModFileDate, this.lastModFileTime, options2.timezone);
1153
+ };
1154
+ Entry.prototype.isEncrypted = function() {
1155
+ return (this.generalPurposeBitFlag & 1) !== 0;
1156
+ };
1157
+ Entry.prototype.isCompressed = function() {
1158
+ return this.compressionMethod === 8;
1159
+ };
1160
+ function LocalFileHeader() {
1161
+ }
1162
+ function dosDateTimeToDate(date, time, timezone) {
1163
+ var day = date & 31;
1164
+ var month = (date >> 5 & 15) - 1;
1165
+ var year = (date >> 9 & 127) + 1980;
1166
+ var millisecond = 0;
1167
+ var second = (time & 31) * 2;
1168
+ var minute = time >> 5 & 63;
1169
+ var hour = time >> 11 & 31;
1170
+ if (timezone == null || timezone === "local") {
1171
+ return new Date(year, month, day, hour, minute, second, millisecond);
1172
+ } else if (timezone === "UTC") {
1173
+ return new Date(Date.UTC(year, month, day, hour, minute, second, millisecond));
1174
+ } else {
1175
+ throw new Error("unrecognized options.timezone: " + options.timezone);
1176
+ }
1177
+ }
1178
+ function getFileNameLowLevel(generalPurposeBitFlag, fileNameBuffer, extraFields, strictFileNames) {
1179
+ var fileName = null;
1180
+ for (var i = 0; i < extraFields.length; i++) {
1181
+ var extraField = extraFields[i];
1182
+ if (extraField.id === 28789) {
1183
+ if (extraField.data.length < 6) {
1184
+ continue;
1185
+ }
1186
+ if (extraField.data.readUInt8(0) !== 1) {
1187
+ continue;
1188
+ }
1189
+ var oldNameCrc32 = extraField.data.readUInt32LE(1);
1190
+ if (crc32.unsigned(fileNameBuffer) !== oldNameCrc32) {
1191
+ continue;
1192
+ }
1193
+ fileName = decodeBuffer(extraField.data.subarray(5), true);
1194
+ break;
1195
+ }
1196
+ }
1197
+ if (fileName == null) {
1198
+ var isUtf8 = (generalPurposeBitFlag & 2048) !== 0;
1199
+ fileName = decodeBuffer(fileNameBuffer, isUtf8);
1200
+ }
1201
+ if (!strictFileNames) {
1202
+ fileName = fileName.replace(/\\/g, "/");
1203
+ }
1204
+ return fileName;
1205
+ }
1206
+ function validateFileName(fileName) {
1207
+ if (fileName.indexOf("\\") !== -1) {
1208
+ return "invalid characters in fileName: " + fileName;
1209
+ }
1210
+ if (/^[a-zA-Z]:/.test(fileName) || /^\//.test(fileName)) {
1211
+ return "absolute path: " + fileName;
1212
+ }
1213
+ if (fileName.split("/").indexOf("..") !== -1) {
1214
+ return "invalid relative path: " + fileName;
1215
+ }
1216
+ return null;
1217
+ }
1218
+ function parseExtraFields(extraFieldBuffer) {
1219
+ var extraFields = [];
1220
+ var i = 0;
1221
+ while (i < extraFieldBuffer.length - 3) {
1222
+ var headerId = extraFieldBuffer.readUInt16LE(i + 0);
1223
+ var dataSize = extraFieldBuffer.readUInt16LE(i + 2);
1224
+ var dataStart = i + 4;
1225
+ var dataEnd = dataStart + dataSize;
1226
+ if (dataEnd > extraFieldBuffer.length) throw new Error("extra field length exceeds extra field buffer size");
1227
+ var dataBuffer = extraFieldBuffer.subarray(dataStart, dataEnd);
1228
+ extraFields.push({
1229
+ id: headerId,
1230
+ data: dataBuffer
1231
+ });
1232
+ i = dataEnd;
1233
+ }
1234
+ return extraFields;
1235
+ }
1236
+ function readAndAssertNoEof(reader, buffer, offset, length, position, callback) {
1237
+ if (length === 0) {
1238
+ return setImmediate(function() {
1239
+ callback(null, newBuffer(0));
1240
+ });
1241
+ }
1242
+ reader.read(buffer, offset, length, position, function(err, bytesRead) {
1243
+ if (err) return callback(err);
1244
+ if (bytesRead < length) {
1245
+ return callback(new Error("unexpected EOF"));
1246
+ }
1247
+ callback();
1248
+ });
1249
+ }
1250
+ util2.inherits(AssertByteCountStream, Transform);
1251
+ function AssertByteCountStream(byteCount) {
1252
+ Transform.call(this);
1253
+ this.actualByteCount = 0;
1254
+ this.expectedByteCount = byteCount;
1255
+ }
1256
+ AssertByteCountStream.prototype._transform = function(chunk, encoding, cb) {
1257
+ this.actualByteCount += chunk.length;
1258
+ if (this.actualByteCount > this.expectedByteCount) {
1259
+ var msg = "too many bytes in the stream. expected " + this.expectedByteCount + ". got at least " + this.actualByteCount;
1260
+ return cb(new Error(msg));
1261
+ }
1262
+ cb(null, chunk);
1263
+ };
1264
+ AssertByteCountStream.prototype._flush = function(cb) {
1265
+ if (this.actualByteCount < this.expectedByteCount) {
1266
+ var msg = "not enough bytes in the stream. expected " + this.expectedByteCount + ". got only " + this.actualByteCount;
1267
+ return cb(new Error(msg));
1268
+ }
1269
+ cb();
1270
+ };
1271
+ util2.inherits(RandomAccessReader, EventEmitter);
1272
+ function RandomAccessReader() {
1273
+ EventEmitter.call(this);
1274
+ this.refCount = 0;
1275
+ }
1276
+ RandomAccessReader.prototype.ref = function() {
1277
+ this.refCount += 1;
1278
+ };
1279
+ RandomAccessReader.prototype.unref = function() {
1280
+ var self = this;
1281
+ self.refCount -= 1;
1282
+ if (self.refCount > 0) return;
1283
+ if (self.refCount < 0) throw new Error("invalid unref");
1284
+ self.close(onCloseDone);
1285
+ function onCloseDone(err) {
1286
+ if (err) return self.emit("error", err);
1287
+ self.emit("close");
1288
+ }
1289
+ };
1290
+ RandomAccessReader.prototype.createReadStream = function(options2) {
1291
+ if (options2 == null) options2 = {};
1292
+ var start = options2.start;
1293
+ var end = options2.end;
1294
+ if (start === end) {
1295
+ var emptyStream = new PassThrough();
1296
+ setImmediate(function() {
1297
+ emptyStream.end();
1298
+ });
1299
+ return emptyStream;
1300
+ }
1301
+ var stream = this._readStreamForRange(start, end);
1302
+ var destroyed = false;
1303
+ var refUnrefFilter = new RefUnrefFilter(this);
1304
+ stream.on("error", function(err) {
1305
+ setImmediate(function() {
1306
+ if (!destroyed) refUnrefFilter.emit("error", err);
1307
+ });
1308
+ });
1309
+ installDestroyFn(refUnrefFilter, function() {
1310
+ stream.unpipe(refUnrefFilter);
1311
+ refUnrefFilter.unref();
1312
+ stream.destroy();
1313
+ });
1314
+ var byteCounter = new AssertByteCountStream(end - start);
1315
+ refUnrefFilter.on("error", function(err) {
1316
+ setImmediate(function() {
1317
+ if (!destroyed) byteCounter.emit("error", err);
1318
+ });
1319
+ });
1320
+ installDestroyFn(byteCounter, function() {
1321
+ destroyed = true;
1322
+ refUnrefFilter.unpipe(byteCounter);
1323
+ refUnrefFilter.destroy();
1324
+ });
1325
+ return stream.pipe(refUnrefFilter).pipe(byteCounter);
1326
+ };
1327
+ RandomAccessReader.prototype._readStreamForRange = function(start, end) {
1328
+ throw new Error("not implemented");
1329
+ };
1330
+ RandomAccessReader.prototype.read = function(buffer, offset, length, position, callback) {
1331
+ var readStream = this.createReadStream({ start: position, end: position + length });
1332
+ var writeStream = new Writable();
1333
+ var written = 0;
1334
+ writeStream._write = function(chunk, encoding, cb) {
1335
+ chunk.copy(buffer, offset + written, 0, chunk.length);
1336
+ written += chunk.length;
1337
+ cb();
1338
+ };
1339
+ writeStream.on("finish", callback);
1340
+ readStream.on("error", function(error) {
1341
+ callback(error);
1342
+ });
1343
+ readStream.pipe(writeStream);
1344
+ };
1345
+ RandomAccessReader.prototype.close = function(callback) {
1346
+ setImmediate(callback);
1347
+ };
1348
+ util2.inherits(RefUnrefFilter, PassThrough);
1349
+ function RefUnrefFilter(context) {
1350
+ PassThrough.call(this);
1351
+ this.context = context;
1352
+ this.context.ref();
1353
+ this.unreffedYet = false;
1354
+ }
1355
+ RefUnrefFilter.prototype._flush = function(cb) {
1356
+ this.unref();
1357
+ cb();
1358
+ };
1359
+ RefUnrefFilter.prototype.unref = function(cb) {
1360
+ if (this.unreffedYet) return;
1361
+ this.unreffedYet = true;
1362
+ this.context.unref();
1363
+ };
1364
+ var cp437 = "\0\u263A\u263B\u2665\u2666\u2663\u2660\u2022\u25D8\u25CB\u25D9\u2642\u2640\u266A\u266B\u263C\u25BA\u25C4\u2195\u203C\xB6\xA7\u25AC\u21A8\u2191\u2193\u2192\u2190\u221F\u2194\u25B2\u25BC !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\u2302\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xEF\xEE\xEC\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xF2\xFB\xF9\xFF\xD6\xDC\xA2\xA3\xA5\u20A7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\u2310\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0";
1365
+ function decodeBuffer(buffer, isUtf8) {
1366
+ if (isUtf8) {
1367
+ return buffer.toString("utf8");
1368
+ } else {
1369
+ var result = "";
1370
+ for (var i = 0; i < buffer.length; i++) {
1371
+ result += cp437[buffer[i]];
1372
+ }
1373
+ return result;
1374
+ }
1375
+ }
1376
+ function readUInt64LE(buffer, offset) {
1377
+ var lower32 = buffer.readUInt32LE(offset);
1378
+ var upper32 = buffer.readUInt32LE(offset + 4);
1379
+ return upper32 * 4294967296 + lower32;
1380
+ }
1381
+ var newBuffer;
1382
+ if (typeof Buffer.allocUnsafe === "function") {
1383
+ newBuffer = function(len) {
1384
+ return Buffer.allocUnsafe(len);
1385
+ };
1386
+ } else {
1387
+ newBuffer = function(len) {
1388
+ return new Buffer(len);
1389
+ };
1390
+ }
1391
+ function installDestroyFn(stream, fn) {
1392
+ if (typeof stream.destroy === "function") {
1393
+ stream._destroy = function(err, cb) {
1394
+ fn();
1395
+ if (cb != null) cb(err);
1396
+ };
1397
+ } else {
1398
+ stream.destroy = fn;
1399
+ }
1400
+ }
1401
+ function defaultCallback(err) {
1402
+ if (err) throw err;
1403
+ }
1404
+ }
1405
+ });
1406
+
1407
+ // packages/playwright/src/worker/workerProcessEntry.ts
1408
+ var import_common4 = require("../common");
1409
+
1410
+ // packages/playwright/src/worker/workerMain.ts
1411
+ var import_common3 = require("../common");
1412
+ var globals = __toESM(require("../globals"));
1413
+ var import_expect = require("../matchers/expect");
1414
+
1415
+ // packages/playwright/src/util.ts
1416
+ var import_fs = __toESM(require("fs"));
1417
+ var import_path = __toESM(require("path"));
1418
+ var import_util = __toESM(require("util"));
1419
+ var debug = require("playwright-core/lib/utilsBundle").debug;
1420
+ var mime = require("playwright-core/lib/utilsBundle").mime;
1421
+ var minimatch = require("playwright-core/lib/utilsBundle").minimatch;
1422
+ var { calculateSha1 } = require("playwright-core/lib/coreBundle").utils;
1423
+ var { sanitizeForFilePath } = require("playwright-core/lib/coreBundle").utils;
1424
+ var { isRegExp } = require("playwright-core/lib/coreBundle").iso;
1425
+ var { parseStackFrame, stringifyStackFrames } = require("playwright-core/lib/coreBundle").iso;
1426
+ var { ansiRegex, isString, stripAnsiEscapes } = require("playwright-core/lib/coreBundle").iso;
1427
+ var PLAYWRIGHT_TEST_PATH = import_path.default.join(__dirname, "..");
1428
+ var PLAYWRIGHT_CORE_PATH = import_path.default.dirname(require.resolve("playwright-core/package.json"));
1429
+ function filterStackTrace(e) {
1430
+ const name = e.name ? e.name + ": " : "";
1431
+ const cause = e.cause instanceof Error ? filterStackTrace(e.cause) : void 0;
1432
+ if (process.env.PWDEBUGIMPL)
1433
+ return { message: name + e.message, stack: e.stack || "", cause };
1434
+ const stackLines = stringifyStackFrames(filteredStackTrace(e.stack?.split("\n") || []));
1435
+ return {
1436
+ message: name + e.message,
1437
+ stack: `${name}${e.message}${stackLines.map((line) => "\n" + line).join("")}`,
1438
+ cause
1439
+ };
1440
+ }
1441
+ function filterStackFile(file) {
1442
+ if (process.env.PWDEBUGIMPL)
1443
+ return true;
1444
+ if (file.startsWith(PLAYWRIGHT_TEST_PATH))
1445
+ return false;
1446
+ if (file.startsWith(PLAYWRIGHT_CORE_PATH))
1447
+ return false;
1448
+ return true;
1449
+ }
1450
+ function filteredStackTrace(rawStack) {
1451
+ const frames = [];
1452
+ for (const line of rawStack) {
1453
+ const frame = parseStackFrame(line, import_path.default.sep, !!process.env.PWDEBUGIMPL);
1454
+ if (!frame || !frame.file)
1455
+ continue;
1456
+ if (!filterStackFile(frame.file))
1457
+ continue;
1458
+ frames.push(frame);
1459
+ }
1460
+ return frames;
1461
+ }
1462
+ function serializeError(error) {
1463
+ if (error instanceof Error)
1464
+ return filterStackTrace(error);
1465
+ return {
1466
+ value: import_util.default.inspect(error)
1467
+ };
1468
+ }
1469
+ function relativeFilePath(file) {
1470
+ if (!import_path.default.isAbsolute(file))
1471
+ return file;
1472
+ return import_path.default.relative(process.cwd(), file);
1473
+ }
1474
+ function formatLocation(location) {
1475
+ return relativeFilePath(location.file) + ":" + location.line + ":" + location.column;
1476
+ }
1477
+ var windowsFilesystemFriendlyLength = 60;
1478
+ function trimLongString(s, length = 100) {
1479
+ if (s.length <= length)
1480
+ return s;
1481
+ const hash = calculateSha1(s);
1482
+ const middle = `-${hash.substring(0, 5)}-`;
1483
+ const start = Math.floor((length - middle.length) / 2);
1484
+ const end = length - middle.length - start;
1485
+ return s.substring(0, start) + middle + s.slice(-end);
1486
+ }
1487
+ function addSuffixToFilePath(filePath, suffix) {
1488
+ const ext = import_path.default.extname(filePath);
1489
+ const base = filePath.substring(0, filePath.length - ext.length);
1490
+ return base + suffix + ext;
1491
+ }
1492
+ function sanitizeFilePathBeforeExtension(filePath, ext) {
1493
+ ext ??= import_path.default.extname(filePath);
1494
+ const base = filePath.substring(0, filePath.length - ext.length);
1495
+ return sanitizeForFilePath(base) + ext;
1496
+ }
1497
+ function getContainedPath(parentPath, subPath = "") {
1498
+ const resolvedPath = import_path.default.resolve(parentPath, subPath);
1499
+ if (resolvedPath === parentPath || resolvedPath.startsWith(parentPath + import_path.default.sep))
1500
+ return resolvedPath;
1501
+ return null;
1502
+ }
1503
+ var debugTest = debug("pw:test");
1504
+ async function normalizeAndSaveAttachment(outputPath, name, options2 = {}) {
1505
+ if (options2.path === void 0 && options2.body === void 0)
1506
+ return { name, contentType: "text/plain" };
1507
+ if ((options2.path !== void 0 ? 1 : 0) + (options2.body !== void 0 ? 1 : 0) !== 1)
1508
+ throw new Error(`Exactly one of "path" and "body" must be specified`);
1509
+ if (options2.path !== void 0) {
1510
+ const hash = calculateSha1(options2.path);
1511
+ if (!isString(name))
1512
+ throw new Error('"name" should be string.');
1513
+ const sanitizedNamePrefix = sanitizeForFilePath(name) + "-";
1514
+ const dest = import_path.default.join(outputPath, "attachments", sanitizedNamePrefix + hash + import_path.default.extname(options2.path));
1515
+ await import_fs.default.promises.mkdir(import_path.default.dirname(dest), { recursive: true });
1516
+ await import_fs.default.promises.copyFile(options2.path, dest);
1517
+ const contentType = options2.contentType ?? (mime.getType(import_path.default.basename(options2.path)) || "application/octet-stream");
1518
+ return { name, contentType, path: dest };
1519
+ } else {
1520
+ const contentType = options2.contentType ?? (typeof options2.body === "string" ? "text/plain" : "application/octet-stream");
1521
+ return { name, contentType, body: typeof options2.body === "string" ? Buffer.from(options2.body) : options2.body };
1522
+ }
1523
+ }
1524
+
1525
+ // packages/playwright/src/worker/fixtureRunner.ts
1526
+ var import_common = require("../common");
1527
+ var { ManualPromise } = require("playwright-core/lib/coreBundle").iso;
1528
+ var { escapeWithQuotes } = require("playwright-core/lib/coreBundle").iso;
1529
+ var Fixture = class {
1530
+ constructor(runner, registration) {
1531
+ this.failed = false;
1532
+ this._deps = /* @__PURE__ */ new Set();
1533
+ this._usages = /* @__PURE__ */ new Set();
1534
+ this.runner = runner;
1535
+ this.registration = registration;
1536
+ this.value = null;
1537
+ const isUserFixture = this.registration.location && filterStackFile(this.registration.location.file);
1538
+ const title = this.registration.customTitle || this.registration.name;
1539
+ const location = isUserFixture ? this.registration.location : void 0;
1540
+ this._stepInfo = { title: `Fixture ${escapeWithQuotes(title, '"')}`, category: "fixture", location };
1541
+ if (this.registration.box === "self")
1542
+ this._stepInfo = void 0;
1543
+ else if (this.registration.box)
1544
+ this._stepInfo.group = isUserFixture ? "configuration" : "internal";
1545
+ this._setupDescription = {
1546
+ title,
1547
+ phase: "setup",
1548
+ location,
1549
+ slot: this.registration.timeout !== void 0 ? {
1550
+ timeout: this.registration.timeout,
1551
+ elapsed: 0
1552
+ } : this.registration.scope === "worker" ? {
1553
+ timeout: this.runner.workerFixtureTimeout,
1554
+ elapsed: 0
1555
+ } : void 0
1556
+ };
1557
+ this._teardownDescription = { ...this._setupDescription, phase: "teardown" };
1558
+ }
1559
+ async setup(testInfo, runnable) {
1560
+ this.runner.instanceForId.set(this.registration.id, this);
1561
+ if (typeof this.registration.fn !== "function") {
1562
+ this.value = this.registration.fn;
1563
+ return;
1564
+ }
1565
+ const run = () => testInfo._runWithTimeout({ ...runnable, fixture: this._setupDescription }, () => this._setupInternal(testInfo));
1566
+ if (this._stepInfo)
1567
+ await testInfo._runAsStep(this._stepInfo, run);
1568
+ else
1569
+ await run();
1570
+ }
1571
+ async _setupInternal(testInfo) {
1572
+ const params = {};
1573
+ for (const name of this.registration.deps) {
1574
+ const registration = this.runner.pool.resolve(name, this.registration);
1575
+ const dep = this.runner.instanceForId.get(registration.id);
1576
+ if (!dep) {
1577
+ this.failed = true;
1578
+ return;
1579
+ }
1580
+ dep._usages.add(this);
1581
+ this._deps.add(dep);
1582
+ params[name] = dep.value;
1583
+ if (dep.failed) {
1584
+ this.failed = true;
1585
+ return;
1586
+ }
1587
+ }
1588
+ let called = false;
1589
+ const useFuncStarted = new ManualPromise();
1590
+ const useFunc = async (value) => {
1591
+ if (called)
1592
+ throw new Error(`Cannot provide fixture value for the second time`);
1593
+ called = true;
1594
+ this.value = value;
1595
+ this._useFuncFinished = new ManualPromise();
1596
+ useFuncStarted.resolve();
1597
+ await this._useFuncFinished;
1598
+ };
1599
+ const workerInfo = { config: testInfo.config, parallelIndex: testInfo.parallelIndex, workerIndex: testInfo.workerIndex, project: testInfo.project };
1600
+ const info = this.registration.scope === "worker" ? workerInfo : testInfo;
1601
+ this._selfTeardownComplete = (async () => {
1602
+ try {
1603
+ await this.registration.fn(params, useFunc, info);
1604
+ if (!useFuncStarted.isDone())
1605
+ throw new Error(`use() was not called in fixture "${this.registration.name}"`);
1606
+ } catch (error) {
1607
+ this.failed = true;
1608
+ if (!useFuncStarted.isDone())
1609
+ useFuncStarted.reject(error);
1610
+ else
1611
+ throw error;
1612
+ }
1613
+ })();
1614
+ await useFuncStarted;
1615
+ }
1616
+ async teardown(testInfo, runnable) {
1617
+ try {
1618
+ const fixtureRunnable = { ...runnable, fixture: this._teardownDescription };
1619
+ if (!testInfo._timeoutManager.isTimeExhaustedFor(fixtureRunnable)) {
1620
+ const run = () => testInfo._runWithTimeout(fixtureRunnable, () => this._teardownInternal());
1621
+ if (this._stepInfo)
1622
+ await testInfo._runAsStep(this._stepInfo, run);
1623
+ else
1624
+ await run();
1625
+ }
1626
+ } finally {
1627
+ for (const dep of this._deps)
1628
+ dep._usages.delete(this);
1629
+ this.runner.instanceForId.delete(this.registration.id);
1630
+ }
1631
+ }
1632
+ async _teardownInternal() {
1633
+ if (typeof this.registration.fn !== "function")
1634
+ return;
1635
+ if (this._usages.size !== 0) {
1636
+ console.error("Internal error: fixture integrity at", this._teardownDescription.title);
1637
+ this._usages.clear();
1638
+ }
1639
+ if (this._useFuncFinished) {
1640
+ this._useFuncFinished.resolve();
1641
+ this._useFuncFinished = void 0;
1642
+ await this._selfTeardownComplete;
1643
+ }
1644
+ }
1645
+ _collectFixturesInTeardownOrder(scope, collector) {
1646
+ if (this.registration.scope !== scope)
1647
+ return;
1648
+ for (const fixture of this._usages)
1649
+ fixture._collectFixturesInTeardownOrder(scope, collector);
1650
+ collector.add(this);
1651
+ }
1652
+ };
1653
+ var FixtureRunner = class {
1654
+ constructor() {
1655
+ this.testScopeClean = true;
1656
+ this.instanceForId = /* @__PURE__ */ new Map();
1657
+ this.workerFixtureTimeout = 0;
1658
+ }
1659
+ setPool(pool) {
1660
+ if (!this.testScopeClean)
1661
+ throw new Error("Did not teardown test scope");
1662
+ if (this.pool && pool.digest !== this.pool.digest) {
1663
+ throw new Error([
1664
+ `Playwright detected inconsistent test.use() options.`,
1665
+ `Most common mistakes that lead to this issue:`,
1666
+ ` - Calling test.use() outside of the test file, for example in a common helper.`,
1667
+ ` - One test file imports from another test file.`
1668
+ ].join("\n"));
1669
+ }
1670
+ this.pool = pool;
1671
+ }
1672
+ _collectFixturesInSetupOrder(registration, collector) {
1673
+ if (collector.has(registration))
1674
+ return;
1675
+ for (const name of registration.deps) {
1676
+ const dep = this.pool.resolve(name, registration);
1677
+ this._collectFixturesInSetupOrder(dep, collector);
1678
+ }
1679
+ collector.add(registration);
1680
+ }
1681
+ async teardownScope(scope, testInfo, runnable) {
1682
+ const allFixtures = Array.from(this.instanceForId.values()).reverse();
1683
+ const collector = /* @__PURE__ */ new Set();
1684
+ for (const fixture of allFixtures)
1685
+ fixture._collectFixturesInTeardownOrder(scope, collector);
1686
+ let firstError;
1687
+ for (const fixture of collector) {
1688
+ try {
1689
+ await fixture.teardown(testInfo, runnable);
1690
+ } catch (error) {
1691
+ firstError = firstError ?? error;
1692
+ }
1693
+ }
1694
+ if (scope === "test")
1695
+ this.testScopeClean = true;
1696
+ if (firstError)
1697
+ throw firstError;
1698
+ }
1699
+ async resolveParametersForFunction(fn, testInfo, autoFixtures, runnable) {
1700
+ const collector = /* @__PURE__ */ new Set();
1701
+ const auto = [];
1702
+ for (const registration of this.pool.autoFixtures()) {
1703
+ let shouldRun = true;
1704
+ if (autoFixtures === "all-hooks-only")
1705
+ shouldRun = registration.scope === "worker" || registration.auto === "all-hooks-included";
1706
+ else if (autoFixtures === "worker")
1707
+ shouldRun = registration.scope === "worker";
1708
+ if (shouldRun)
1709
+ auto.push(registration);
1710
+ }
1711
+ auto.sort((r1, r2) => (r1.scope === "worker" ? 0 : 1) - (r2.scope === "worker" ? 0 : 1));
1712
+ for (const registration of auto)
1713
+ this._collectFixturesInSetupOrder(registration, collector);
1714
+ const names = getRequiredFixtureNames(fn);
1715
+ for (const name of names)
1716
+ this._collectFixturesInSetupOrder(this.pool.resolve(name), collector);
1717
+ for (const registration of collector)
1718
+ await this._setupFixtureForRegistration(registration, testInfo, runnable);
1719
+ const params = {};
1720
+ for (const name of names) {
1721
+ const registration = this.pool.resolve(name);
1722
+ const fixture = this.instanceForId.get(registration.id);
1723
+ if (!fixture || fixture.failed)
1724
+ return null;
1725
+ params[name] = fixture.value;
1726
+ }
1727
+ return { result: params };
1728
+ }
1729
+ async resolveParametersAndRunFunction(fn, testInfo, autoFixtures, runnable) {
1730
+ const params = await this.resolveParametersForFunction(fn, testInfo, autoFixtures, runnable);
1731
+ if (params === null) {
1732
+ return null;
1733
+ }
1734
+ await testInfo._runWithTimeout(runnable, () => fn(params.result, testInfo));
1735
+ }
1736
+ async _setupFixtureForRegistration(registration, testInfo, runnable) {
1737
+ if (registration.scope === "test")
1738
+ this.testScopeClean = false;
1739
+ let fixture = this.instanceForId.get(registration.id);
1740
+ if (fixture)
1741
+ return fixture;
1742
+ fixture = new Fixture(this, registration);
1743
+ await fixture.setup(testInfo, runnable);
1744
+ return fixture;
1745
+ }
1746
+ dependsOnWorkerFixturesOnly(fn, location) {
1747
+ const names = getRequiredFixtureNames(fn, location);
1748
+ for (const name of names) {
1749
+ const registration = this.pool.resolve(name);
1750
+ if (registration.scope !== "worker")
1751
+ return false;
1752
+ }
1753
+ return true;
1754
+ }
1755
+ };
1756
+ function getRequiredFixtureNames(fn, location) {
1757
+ return import_common.fixtures.fixtureParameterNames(fn, location ?? { file: "<unknown>", line: 1, column: 1 }, (e) => {
1758
+ throw new Error(`${formatLocation(e.location)}: ${e.message}`);
1759
+ });
1760
+ }
1761
+
1762
+ // packages/playwright/src/worker/testInfo.ts
1763
+ var import_fs3 = __toESM(require("fs"));
1764
+ var import_path3 = __toESM(require("path"));
1765
+
1766
+ // packages/playwright/src/worker/timeoutManager.ts
1767
+ var colors = require("playwright-core/lib/utilsBundle").colors;
1768
+ var { ManualPromise: ManualPromise2 } = require("playwright-core/lib/coreBundle").iso;
1769
+ var { monotonicTime } = require("playwright-core/lib/coreBundle").iso;
1770
+ var kMaxDeadline = 2147483647;
1771
+ var TimeoutManager = class {
1772
+ constructor(timeout) {
1773
+ this._ignoreTimeouts = false;
1774
+ this._slow = false;
1775
+ this._defaultSlot = { timeout, elapsed: 0 };
1776
+ }
1777
+ setIgnoreTimeouts(ignoreTimeouts) {
1778
+ if (this._ignoreTimeouts === ignoreTimeouts)
1779
+ return;
1780
+ this._ignoreTimeouts = ignoreTimeouts;
1781
+ if (this._running) {
1782
+ if (ignoreTimeouts)
1783
+ this._running.slot.elapsed += monotonicTime() - this._running.start;
1784
+ else
1785
+ this._running.start = monotonicTime();
1786
+ this._updateTimeout(this._running);
1787
+ }
1788
+ }
1789
+ interrupt() {
1790
+ if (this._running)
1791
+ this._running.timeoutPromise.reject(this._createTimeoutError(this._running));
1792
+ }
1793
+ isTimeExhaustedFor(runnable) {
1794
+ const slot = runnable.fixture?.slot || runnable.slot || this._defaultSlot;
1795
+ return slot.timeout > 0 && slot.elapsed >= slot.timeout - 1;
1796
+ }
1797
+ async withRunnable(runnable, cb) {
1798
+ if (this._running)
1799
+ throw new Error(`Internal error: duplicate runnable`);
1800
+ const running = this._running = {
1801
+ runnable,
1802
+ slot: runnable.fixture?.slot || runnable.slot || this._defaultSlot,
1803
+ start: monotonicTime(),
1804
+ deadline: kMaxDeadline,
1805
+ timer: void 0,
1806
+ timeoutPromise: new ManualPromise2()
1807
+ };
1808
+ let debugTitle = "";
1809
+ try {
1810
+ if (debugTest.enabled) {
1811
+ debugTitle = runnable.fixture ? `${runnable.fixture.phase} "${runnable.fixture.title}"` : runnable.type;
1812
+ const location = runnable.location ? ` at "${formatLocation(runnable.location)}"` : ``;
1813
+ debugTest(`started ${debugTitle}${location}`);
1814
+ }
1815
+ this._updateTimeout(running);
1816
+ return await Promise.race([
1817
+ cb(),
1818
+ running.timeoutPromise
1819
+ ]);
1820
+ } finally {
1821
+ if (running.timer)
1822
+ clearTimeout(running.timer);
1823
+ running.timer = void 0;
1824
+ running.slot.elapsed += monotonicTime() - running.start;
1825
+ this._running = void 0;
1826
+ if (debugTest.enabled)
1827
+ debugTest(`finished ${debugTitle}`);
1828
+ }
1829
+ }
1830
+ _updateTimeout(running) {
1831
+ if (running.timer)
1832
+ clearTimeout(running.timer);
1833
+ running.timer = void 0;
1834
+ if (this._ignoreTimeouts || !running.slot.timeout) {
1835
+ running.deadline = kMaxDeadline;
1836
+ return;
1837
+ }
1838
+ running.deadline = running.start + (running.slot.timeout - running.slot.elapsed);
1839
+ const timeout = running.deadline - monotonicTime() + 1;
1840
+ if (timeout <= 0)
1841
+ running.timeoutPromise.reject(this._createTimeoutError(running));
1842
+ else
1843
+ running.timer = setTimeout(() => running.timeoutPromise.reject(this._createTimeoutError(running)), timeout);
1844
+ }
1845
+ defaultSlot() {
1846
+ return this._defaultSlot;
1847
+ }
1848
+ slow() {
1849
+ if (this._slow)
1850
+ return;
1851
+ this._slow = true;
1852
+ const slot = this._running ? this._running.slot : this._defaultSlot;
1853
+ slot.timeout = slot.timeout * 3;
1854
+ if (this._running)
1855
+ this._updateTimeout(this._running);
1856
+ }
1857
+ setTimeout(timeout) {
1858
+ const slot = this._running ? this._running.slot : this._defaultSlot;
1859
+ slot.timeout = timeout;
1860
+ if (this._running)
1861
+ this._updateTimeout(this._running);
1862
+ }
1863
+ currentSlotDeadline() {
1864
+ return this._running ? this._running.deadline : kMaxDeadline;
1865
+ }
1866
+ currentSlotType() {
1867
+ return this._running ? this._running.runnable.type : "test";
1868
+ }
1869
+ _createTimeoutError(running) {
1870
+ let message = "";
1871
+ const timeout = running.slot.timeout;
1872
+ const runnable = running.runnable;
1873
+ switch (runnable.type) {
1874
+ case "test": {
1875
+ if (runnable.fixture) {
1876
+ if (runnable.fixture.phase === "setup")
1877
+ message = `Test timeout of ${timeout}ms exceeded while setting up "${runnable.fixture.title}".`;
1878
+ else
1879
+ message = `Tearing down "${runnable.fixture.title}" exceeded the test timeout of ${timeout}ms.`;
1880
+ } else {
1881
+ message = `Test timeout of ${timeout}ms exceeded.`;
1882
+ }
1883
+ break;
1884
+ }
1885
+ case "afterEach":
1886
+ case "beforeEach":
1887
+ message = `Test timeout of ${timeout}ms exceeded while running "${runnable.type}" hook.`;
1888
+ break;
1889
+ case "beforeAll":
1890
+ case "afterAll":
1891
+ message = `"${runnable.type}" hook timeout of ${timeout}ms exceeded.`;
1892
+ break;
1893
+ case "teardown": {
1894
+ if (runnable.fixture)
1895
+ message = `Worker teardown timeout of ${timeout}ms exceeded while ${runnable.fixture.phase === "setup" ? "setting up" : "tearing down"} "${runnable.fixture.title}".`;
1896
+ else
1897
+ message = `Worker teardown timeout of ${timeout}ms exceeded.`;
1898
+ break;
1899
+ }
1900
+ case "skip":
1901
+ case "slow":
1902
+ case "fixme":
1903
+ case "fail":
1904
+ message = `"${runnable.type}" modifier timeout of ${timeout}ms exceeded.`;
1905
+ break;
1906
+ }
1907
+ const fixtureWithSlot = runnable.fixture?.slot ? runnable.fixture : void 0;
1908
+ if (fixtureWithSlot)
1909
+ message = `Fixture "${fixtureWithSlot.title}" timeout of ${timeout}ms exceeded during ${fixtureWithSlot.phase}.`;
1910
+ message = colors.red(message);
1911
+ const location = (fixtureWithSlot || runnable).location;
1912
+ const error = new TimeoutManagerError(message);
1913
+ error.name = "";
1914
+ error.stack = message + (location ? `
1915
+ at ${location.file}:${location.line}:${location.column}` : "");
1916
+ return error;
1917
+ }
1918
+ };
1919
+ var TimeoutManagerError = class extends Error {
1920
+ };
1921
+
1922
+ // packages/playwright/src/worker/testTracing.ts
1923
+ var import_fs2 = __toESM(require("fs"));
1924
+ var import_path2 = __toESM(require("path"));
1925
+ var yauzl = __toESM(require_yauzl());
1926
+ var import_coreBundle = require("playwright-core/lib/coreBundle");
1927
+ var yazl = require("playwright-core/lib/utilsBundle").yazl;
1928
+ var { ManualPromise: ManualPromise3 } = require("playwright-core/lib/coreBundle").iso;
1929
+ var { monotonicTime: monotonicTime2 } = require("playwright-core/lib/coreBundle").iso;
1930
+ var { calculateSha1: calculateSha12, createGuid } = require("playwright-core/lib/coreBundle").utils;
1931
+ var { SerializedFS } = require("playwright-core/lib/coreBundle").utils;
1932
+ var testTraceEntryName = "test.trace";
1933
+ var version = 8;
1934
+ var traceOrdinal = 0;
1935
+ var TestTracing = class {
1936
+ constructor(testInfo, artifactsDir) {
1937
+ this._traceEvents = [];
1938
+ this._temporaryTraceFiles = [];
1939
+ this._didFinishTestFunctionAndAfterEachHooks = false;
1940
+ this._testInfo = testInfo;
1941
+ this._artifactsDir = artifactsDir;
1942
+ this._tracesDir = import_path2.default.join(this._artifactsDir, "traces");
1943
+ this._contextCreatedEvent = {
1944
+ version,
1945
+ type: "context-options",
1946
+ origin: "testRunner",
1947
+ browserName: "",
1948
+ playwrightVersion: (0, import_coreBundle.getPlaywrightVersion)(),
1949
+ options: {},
1950
+ platform: process.platform,
1951
+ wallTime: Date.now(),
1952
+ monotonicTime: monotonicTime2(),
1953
+ sdkLanguage: "javascript"
1954
+ };
1955
+ this._appendTraceEvent(this._contextCreatedEvent);
1956
+ }
1957
+ _shouldCaptureTrace() {
1958
+ if (this._options?.mode === "on")
1959
+ return true;
1960
+ if (this._options?.mode === "retain-on-failure")
1961
+ return true;
1962
+ if (this._options?.mode === "on-first-retry" && this._testInfo.retry === 1)
1963
+ return true;
1964
+ if (this._options?.mode === "on-all-retries" && this._testInfo.retry > 0)
1965
+ return true;
1966
+ if (this._options?.mode === "retain-on-first-failure" && this._testInfo.retry === 0)
1967
+ return true;
1968
+ if (this._options?.mode === "retain-on-failure-and-retries")
1969
+ return true;
1970
+ return false;
1971
+ }
1972
+ async startIfNeeded(value) {
1973
+ const defaultTraceOptions = { screenshots: true, snapshots: true, sources: true, attachments: true, live: false, mode: "off" };
1974
+ if (!value) {
1975
+ this._options = defaultTraceOptions;
1976
+ } else if (typeof value === "string") {
1977
+ this._options = { ...defaultTraceOptions, mode: value === "retry-with-trace" ? "on-first-retry" : value };
1978
+ } else {
1979
+ const mode = value.mode || "off";
1980
+ this._options = { ...defaultTraceOptions, ...value, mode: mode === "retry-with-trace" ? "on-first-retry" : mode };
1981
+ }
1982
+ if (!this._shouldCaptureTrace()) {
1983
+ this._options = void 0;
1984
+ return;
1985
+ }
1986
+ if (!this._liveTraceFile && this._options.live) {
1987
+ this._liveTraceFile = { file: import_path2.default.join(this._tracesDir, `${this._testInfo.testId}-test.trace`), fs: new SerializedFS() };
1988
+ this._liveTraceFile.fs.mkdir(import_path2.default.dirname(this._liveTraceFile.file));
1989
+ const data = this._traceEvents.map((e) => JSON.stringify(e)).join("\n") + "\n";
1990
+ this._liveTraceFile.fs.writeFile(this._liveTraceFile.file, data);
1991
+ }
1992
+ }
1993
+ didFinishTestFunctionAndAfterEachHooks() {
1994
+ this._didFinishTestFunctionAndAfterEachHooks = true;
1995
+ }
1996
+ artifactsDir() {
1997
+ return this._artifactsDir;
1998
+ }
1999
+ tracesDir() {
2000
+ return this._tracesDir;
2001
+ }
2002
+ traceTitle() {
2003
+ return [import_path2.default.relative(this._testInfo.project.testDir, this._testInfo.file) + ":" + this._testInfo.line, ...this._testInfo.titlePath.slice(1)].join(" \u203A ");
2004
+ }
2005
+ generateNextTraceRecordingName() {
2006
+ const ordinalSuffix = traceOrdinal ? `-recording${traceOrdinal}` : "";
2007
+ ++traceOrdinal;
2008
+ const retrySuffix = this._testInfo.retry ? `-retry${this._testInfo.retry}` : "";
2009
+ return `${this._testInfo.testId}${retrySuffix}${ordinalSuffix}`;
2010
+ }
2011
+ _generateNextTraceRecordingPath() {
2012
+ const file = import_path2.default.join(this._artifactsDir, createGuid() + ".zip");
2013
+ this._temporaryTraceFiles.push(file);
2014
+ return file;
2015
+ }
2016
+ traceOptions() {
2017
+ return this._options;
2018
+ }
2019
+ maybeGenerateNextTraceRecordingPath() {
2020
+ if (this._didFinishTestFunctionAndAfterEachHooks && this._shouldAbandonTrace())
2021
+ return;
2022
+ return this._generateNextTraceRecordingPath();
2023
+ }
2024
+ _shouldAbandonTrace() {
2025
+ if (!this._options)
2026
+ return true;
2027
+ const testFailed = this._testInfo.status !== this._testInfo.expectedStatus;
2028
+ if (this._options.mode === "retain-on-failure-and-retries")
2029
+ return !testFailed && this._testInfo.retry === 0;
2030
+ return !testFailed && (this._options.mode === "retain-on-failure" || this._options.mode === "retain-on-first-failure");
2031
+ }
2032
+ async stopIfNeeded() {
2033
+ this._contextCreatedEvent.testTimeout = this._testInfo.timeout;
2034
+ if (!this._options)
2035
+ return;
2036
+ const error = await this._liveTraceFile?.fs.syncAndGetError();
2037
+ if (error)
2038
+ throw error;
2039
+ if (this._shouldAbandonTrace()) {
2040
+ for (const file of this._temporaryTraceFiles)
2041
+ await import_fs2.default.promises.unlink(file).catch(() => {
2042
+ });
2043
+ return;
2044
+ }
2045
+ const zipFile = new yazl.ZipFile();
2046
+ if (!this._options?.attachments) {
2047
+ for (const event of this._traceEvents) {
2048
+ if (event.type === "after")
2049
+ delete event.attachments;
2050
+ }
2051
+ }
2052
+ if (this._options?.sources) {
2053
+ const sourceFiles = /* @__PURE__ */ new Set();
2054
+ for (const event of this._traceEvents) {
2055
+ if (event.type === "before") {
2056
+ for (const frame of event.stack || [])
2057
+ sourceFiles.add(frame.file);
2058
+ }
2059
+ }
2060
+ for (const sourceFile of sourceFiles) {
2061
+ await import_fs2.default.promises.readFile(sourceFile, "utf8").then((source) => {
2062
+ zipFile.addBuffer(Buffer.from(source), "resources/src@" + calculateSha12(sourceFile) + ".txt");
2063
+ }).catch(() => {
2064
+ });
2065
+ }
2066
+ }
2067
+ const sha1s = /* @__PURE__ */ new Set();
2068
+ for (const event of this._traceEvents.filter((e) => e.type === "after")) {
2069
+ for (const attachment of event.attachments || []) {
2070
+ let contentPromise;
2071
+ if (attachment.path)
2072
+ contentPromise = import_fs2.default.promises.readFile(attachment.path).catch(() => void 0);
2073
+ else if (attachment.base64)
2074
+ contentPromise = Promise.resolve(Buffer.from(attachment.base64, "base64"));
2075
+ const content = await contentPromise;
2076
+ if (content === void 0)
2077
+ continue;
2078
+ const sha1 = calculateSha12(content);
2079
+ attachment.sha1 = sha1;
2080
+ delete attachment.path;
2081
+ delete attachment.base64;
2082
+ if (sha1s.has(sha1))
2083
+ continue;
2084
+ sha1s.add(sha1);
2085
+ zipFile.addBuffer(content, "resources/" + sha1);
2086
+ }
2087
+ }
2088
+ const traceContent = Buffer.from(this._traceEvents.map((e) => JSON.stringify(e)).join("\n"));
2089
+ zipFile.addBuffer(traceContent, testTraceEntryName);
2090
+ await new Promise((f) => {
2091
+ zipFile.end(void 0, () => {
2092
+ zipFile.outputStream.pipe(import_fs2.default.createWriteStream(this._generateNextTraceRecordingPath())).on("close", f);
2093
+ });
2094
+ });
2095
+ const tracePath = this._testInfo.outputPath("trace.zip");
2096
+ await mergeTraceFiles(tracePath, this._temporaryTraceFiles);
2097
+ this._testInfo.attachments.push({ name: "trace", path: tracePath, contentType: "application/zip" });
2098
+ }
2099
+ appendForError(error) {
2100
+ const rawStack = error.stack?.split("\n") || [];
2101
+ const stack = rawStack ? filteredStackTrace(rawStack) : [];
2102
+ this._appendTraceEvent({
2103
+ type: "error",
2104
+ message: this._formatError(error),
2105
+ stack
2106
+ });
2107
+ }
2108
+ _formatError(error) {
2109
+ const parts = [error.message || String(error.value)];
2110
+ if (error.cause)
2111
+ parts.push("[cause]: " + this._formatError(error.cause));
2112
+ return parts.join("\n");
2113
+ }
2114
+ appendStdioToTrace(type, chunk) {
2115
+ this._appendTraceEvent({
2116
+ type,
2117
+ timestamp: monotonicTime2(),
2118
+ text: typeof chunk === "string" ? chunk : void 0,
2119
+ base64: typeof chunk === "string" ? void 0 : chunk.toString("base64")
2120
+ });
2121
+ }
2122
+ appendBeforeActionForStep(options2) {
2123
+ this._appendTraceEvent({
2124
+ type: "before",
2125
+ callId: options2.stepId,
2126
+ stepId: options2.stepId,
2127
+ parentId: options2.parentId,
2128
+ startTime: monotonicTime2(),
2129
+ class: "Test",
2130
+ method: options2.category,
2131
+ title: options2.title,
2132
+ params: Object.fromEntries(Object.entries(options2.params || {}).map(([name, value]) => [name, generatePreview(value)])),
2133
+ stack: options2.stack,
2134
+ group: options2.group
2135
+ });
2136
+ }
2137
+ appendAfterActionForStep(callId, error, attachments = [], annotations) {
2138
+ this._appendTraceEvent({
2139
+ type: "after",
2140
+ callId,
2141
+ endTime: monotonicTime2(),
2142
+ attachments: serializeAttachments(attachments),
2143
+ annotations,
2144
+ error
2145
+ });
2146
+ }
2147
+ _appendTraceEvent(event) {
2148
+ this._traceEvents.push(event);
2149
+ if (this._liveTraceFile)
2150
+ this._liveTraceFile.fs.appendFile(this._liveTraceFile.file, JSON.stringify(event) + "\n", true);
2151
+ }
2152
+ };
2153
+ function serializeAttachments(attachments) {
2154
+ if (attachments.length === 0)
2155
+ return void 0;
2156
+ return attachments.filter((a) => a.name !== "trace").map((a) => {
2157
+ return {
2158
+ name: a.name,
2159
+ contentType: a.contentType,
2160
+ path: a.path,
2161
+ base64: a.body?.toString("base64")
2162
+ };
2163
+ });
2164
+ }
2165
+ function generatePreview(value, visited = /* @__PURE__ */ new Set()) {
2166
+ if (visited.has(value))
2167
+ return "";
2168
+ visited.add(value);
2169
+ if (typeof value === "string")
2170
+ return value;
2171
+ if (typeof value === "number")
2172
+ return value.toString();
2173
+ if (typeof value === "boolean")
2174
+ return value.toString();
2175
+ if (value === null)
2176
+ return "null";
2177
+ if (value === void 0)
2178
+ return "undefined";
2179
+ if (Array.isArray(value))
2180
+ return "[" + value.map((v) => generatePreview(v, visited)).join(", ") + "]";
2181
+ if (typeof value === "object")
2182
+ return "Object";
2183
+ return String(value);
2184
+ }
2185
+ async function mergeTraceFiles(fileName, temporaryTraceFiles) {
2186
+ temporaryTraceFiles = temporaryTraceFiles.filter((file) => import_fs2.default.existsSync(file));
2187
+ if (temporaryTraceFiles.length === 1) {
2188
+ await import_fs2.default.promises.rename(temporaryTraceFiles[0], fileName);
2189
+ return;
2190
+ }
2191
+ const mergePromise = new ManualPromise3();
2192
+ const zipFile = new yazl.ZipFile();
2193
+ const entryNames = /* @__PURE__ */ new Set();
2194
+ zipFile.on("error", (error) => mergePromise.reject(error));
2195
+ for (let i = temporaryTraceFiles.length - 1; i >= 0; --i) {
2196
+ const tempFile = temporaryTraceFiles[i];
2197
+ const promise = new ManualPromise3();
2198
+ yauzl.open(tempFile, (err, inZipFile) => {
2199
+ if (err) {
2200
+ promise.reject(err);
2201
+ return;
2202
+ }
2203
+ let pendingEntries = inZipFile.entryCount;
2204
+ inZipFile.on("entry", (entry) => {
2205
+ let entryName = entry.fileName;
2206
+ if (entry.fileName === testTraceEntryName) {
2207
+ } else if (entry.fileName.match(/trace\.[a-z]*$/)) {
2208
+ entryName = i + "-" + entry.fileName;
2209
+ }
2210
+ if (entryNames.has(entryName)) {
2211
+ if (--pendingEntries === 0)
2212
+ promise.resolve();
2213
+ return;
2214
+ }
2215
+ entryNames.add(entryName);
2216
+ inZipFile.openReadStream(entry, (err2, readStream) => {
2217
+ if (err2) {
2218
+ promise.reject(err2);
2219
+ return;
2220
+ }
2221
+ zipFile.addReadStream(readStream, entryName);
2222
+ if (--pendingEntries === 0)
2223
+ promise.resolve();
2224
+ });
2225
+ });
2226
+ });
2227
+ await promise;
2228
+ }
2229
+ zipFile.end(void 0, () => {
2230
+ zipFile.outputStream.pipe(import_fs2.default.createWriteStream(fileName)).on("close", () => {
2231
+ void Promise.all(temporaryTraceFiles.map((tempFile) => import_fs2.default.promises.unlink(tempFile))).then(() => {
2232
+ mergePromise.resolve();
2233
+ }).catch((error) => mergePromise.reject(error));
2234
+ }).on("error", (error) => mergePromise.reject(error));
2235
+ });
2236
+ await mergePromise;
2237
+ }
2238
+
2239
+ // packages/playwright/src/worker/util.ts
2240
+ function testInfoError(error) {
2241
+ const result = serializeError(error);
2242
+ const matcherResult = error instanceof Error ? error.matcherResult : void 0;
2243
+ if (matcherResult?.ariaSnapshot !== void 0)
2244
+ result.errorContext = matcherResult.ariaSnapshot;
2245
+ return result;
2246
+ }
2247
+
2248
+ // packages/playwright/src/worker/testInfo.ts
2249
+ var import_common2 = require("../common");
2250
+ var { ManualPromise: ManualPromise4 } = require("playwright-core/lib/coreBundle").iso;
2251
+ var { captureRawStack, stringifyStackFrames: stringifyStackFrames2 } = require("playwright-core/lib/coreBundle").iso;
2252
+ var { escapeWithQuotes: escapeWithQuotes2 } = require("playwright-core/lib/coreBundle").iso;
2253
+ var { monotonicTime: monotonicTime3 } = require("playwright-core/lib/coreBundle").iso;
2254
+ var { createGuid: createGuid2 } = require("playwright-core/lib/coreBundle").utils;
2255
+ var { sanitizeForFilePath: sanitizeForFilePath2 } = require("playwright-core/lib/coreBundle").utils;
2256
+ var { currentZone } = require("playwright-core/lib/coreBundle").utils;
2257
+ var emtpyTestInfoCallbacks = {
2258
+ onStepBegin: () => {
2259
+ },
2260
+ onStepEnd: () => {
2261
+ },
2262
+ onAttach: () => {
2263
+ },
2264
+ onTestPaused: () => Promise.reject(new Error("TestInfoImpl not initialized"))
2265
+ };
2266
+ var TestInfoImpl = class {
2267
+ constructor(configInternal, projectInternal, workerParams, test, retry, callbacks) {
2268
+ this._snapshotNames = { lastAnonymousSnapshotIndex: 0, lastNamedSnapshotIndex: {} };
2269
+ this._ariaSnapshotNames = { lastAnonymousSnapshotIndex: 0, lastNamedSnapshotIndex: {} };
2270
+ this._interruptedPromise = new ManualPromise4();
2271
+ this._lastStepId = 0;
2272
+ this._steps = [];
2273
+ this._stepMap = /* @__PURE__ */ new Map();
2274
+ this._onDidFinishTestFunctionCallbacks = /* @__PURE__ */ new Set();
2275
+ this._hasNonRetriableError = false;
2276
+ this._hasUnhandledError = false;
2277
+ this._allowSkips = false;
2278
+ this.duration = 0;
2279
+ this.annotations = [];
2280
+ this.attachments = [];
2281
+ this.status = "passed";
2282
+ this.snapshotSuffix = "";
2283
+ this.errors = [];
2284
+ this._ignoreTimeoutsCounter = 0;
2285
+ this.testId = test?.id ?? "";
2286
+ this._callbacks = callbacks;
2287
+ this._startTime = monotonicTime3();
2288
+ this._startWallTime = Date.now();
2289
+ this._requireFile = test?._requireFile ?? "";
2290
+ this._uniqueSymbol = Symbol("testInfoUniqueSymbol");
2291
+ this._workerParams = workerParams;
2292
+ this.repeatEachIndex = workerParams.repeatEachIndex;
2293
+ this.retry = retry;
2294
+ this.workerIndex = workerParams.workerIndex;
2295
+ this.parallelIndex = workerParams.parallelIndex;
2296
+ this._projectInternal = projectInternal;
2297
+ this.project = projectInternal.project;
2298
+ this._configInternal = configInternal;
2299
+ this.config = configInternal.config;
2300
+ this.title = test?.title ?? "";
2301
+ this.titlePath = test?.titlePath() ?? [];
2302
+ this.file = test?.location.file ?? "";
2303
+ this.line = test?.location.line ?? 0;
2304
+ this.column = test?.location.column ?? 0;
2305
+ this.tags = test?.tags ?? [];
2306
+ this.fn = test?.fn ?? (() => {
2307
+ });
2308
+ this.expectedStatus = test?.expectedStatus ?? "skipped";
2309
+ this._timeoutManager = new TimeoutManager(this.project.timeout);
2310
+ if (configInternal.configCLIOverrides.debug === "inspector")
2311
+ this._setIgnoreTimeouts(true);
2312
+ this.outputDir = (() => {
2313
+ const relativeTestFilePath = import_path3.default.relative(this.project.testDir, this._requireFile.replace(/\.(spec|test)\.(js|ts|jsx|tsx|mjs|mts|cjs|cts)$/, ""));
2314
+ const sanitizedRelativePath = relativeTestFilePath.replace(process.platform === "win32" ? new RegExp("\\\\", "g") : new RegExp("/", "g"), "-");
2315
+ const fullTitleWithoutSpec = this.titlePath.slice(1).join(" ");
2316
+ let testOutputDir = trimLongString(sanitizedRelativePath + "-" + sanitizeForFilePath2(fullTitleWithoutSpec), windowsFilesystemFriendlyLength);
2317
+ if (projectInternal.id)
2318
+ testOutputDir += "-" + sanitizeForFilePath2(projectInternal.id);
2319
+ if (this.retry)
2320
+ testOutputDir += "-retry" + this.retry;
2321
+ if (this.repeatEachIndex)
2322
+ testOutputDir += "-repeat" + this.repeatEachIndex;
2323
+ return import_path3.default.join(this.project.outputDir, testOutputDir);
2324
+ })();
2325
+ this.snapshotDir = (() => {
2326
+ const relativeTestFilePath = import_path3.default.relative(this.project.testDir, this._requireFile);
2327
+ return import_path3.default.join(this.project.snapshotDir, relativeTestFilePath + "-snapshots");
2328
+ })();
2329
+ this._attachmentsPush = this.attachments.push.bind(this.attachments);
2330
+ const attachmentsPush = (...attachments) => {
2331
+ for (const a of attachments)
2332
+ this._attach(a, this._parentStep()?.stepId);
2333
+ return this.attachments.length;
2334
+ };
2335
+ Object.defineProperty(this.attachments, "push", {
2336
+ value: attachmentsPush,
2337
+ writable: true,
2338
+ enumerable: false,
2339
+ configurable: true
2340
+ });
2341
+ this._tracing = new TestTracing(this, workerParams.artifactsDir);
2342
+ this.skip = import_common2.transform.wrapFunctionWithLocation((location, ...args) => this._modifier("skip", location, args));
2343
+ this.fixme = import_common2.transform.wrapFunctionWithLocation((location, ...args) => this._modifier("fixme", location, args));
2344
+ this.fail = import_common2.transform.wrapFunctionWithLocation((location, ...args) => this._modifier("fail", location, args));
2345
+ this.slow = import_common2.transform.wrapFunctionWithLocation((location, ...args) => this._modifier("slow", location, args));
2346
+ }
2347
+ get error() {
2348
+ return this.errors[0];
2349
+ }
2350
+ set error(e) {
2351
+ if (e === void 0)
2352
+ throw new Error("Cannot assign testInfo.error undefined value!");
2353
+ this.errors[0] = e;
2354
+ }
2355
+ get timeout() {
2356
+ return this._timeoutManager.defaultSlot().timeout;
2357
+ }
2358
+ set timeout(timeout) {
2359
+ }
2360
+ _deadline() {
2361
+ return { deadline: this._timeoutManager.currentSlotDeadline(), timeout: this.timeout };
2362
+ }
2363
+ _modifier(type, location, modifierArgs) {
2364
+ if (typeof modifierArgs[1] === "function") {
2365
+ throw new Error([
2366
+ "It looks like you are calling test.skip() inside the test and pass a callback.",
2367
+ "Pass a condition instead and optional description instead:",
2368
+ `test('my test', async ({ page, isMobile }) => {`,
2369
+ ` test.skip(isMobile, 'This test is not applicable on mobile');`,
2370
+ `});`
2371
+ ].join("\n"));
2372
+ }
2373
+ if (modifierArgs.length >= 1 && !modifierArgs[0])
2374
+ return;
2375
+ const description = modifierArgs[1];
2376
+ this.annotations.push({ type, description, location });
2377
+ if (type === "slow") {
2378
+ this._timeoutManager.slow();
2379
+ } else if (type === "skip" || type === "fixme") {
2380
+ this.expectedStatus = "skipped";
2381
+ throw new TestSkipError("Test is skipped: " + (description || ""));
2382
+ } else if (type === "fail") {
2383
+ if (this.expectedStatus !== "skipped")
2384
+ this.expectedStatus = "failed";
2385
+ }
2386
+ }
2387
+ _findLastPredefinedStep(steps) {
2388
+ for (let i = steps.length - 1; i >= 0; i--) {
2389
+ const child = this._findLastPredefinedStep(steps[i].steps);
2390
+ if (child)
2391
+ return child;
2392
+ if ((steps[i].category === "hook" || steps[i].category === "fixture") && !steps[i].endWallTime)
2393
+ return steps[i];
2394
+ }
2395
+ }
2396
+ _parentStep() {
2397
+ return currentZone().data("stepZone") ?? this._findLastPredefinedStep(this._steps);
2398
+ }
2399
+ _addStep(data, parentStep) {
2400
+ const stepId = `${data.category}@${++this._lastStepId}`;
2401
+ if (data.category === "hook" || data.category === "fixture") {
2402
+ parentStep = this._findLastPredefinedStep(this._steps);
2403
+ } else {
2404
+ if (!parentStep)
2405
+ parentStep = this._parentStep();
2406
+ }
2407
+ const filteredStack = filteredStackTrace(captureRawStack());
2408
+ let boxedStack = parentStep?.boxedStack;
2409
+ let location = data.location;
2410
+ if (!boxedStack && data.box) {
2411
+ boxedStack = filteredStack.slice(1);
2412
+ location = location || boxedStack[0];
2413
+ }
2414
+ location = location || filteredStack[0];
2415
+ const step = {
2416
+ ...data,
2417
+ stepId,
2418
+ group: parentStep?.group ?? data.group,
2419
+ boxedStack,
2420
+ location,
2421
+ steps: [],
2422
+ attachmentIndices: [],
2423
+ info: new TestStepInfoImpl(this, stepId, data.title, parentStep?.info),
2424
+ complete: (result) => {
2425
+ if (step.endWallTime)
2426
+ return;
2427
+ step.endWallTime = Date.now();
2428
+ if (result.attachments) {
2429
+ for (const attachment of result.attachments)
2430
+ this._attach(attachment, stepId);
2431
+ }
2432
+ if (result.error) {
2433
+ if (typeof result.error === "object" && !result.error?.[stepSymbol])
2434
+ result.error[stepSymbol] = step;
2435
+ const error = testInfoError(result.error);
2436
+ if (step.boxedStack)
2437
+ error.stack = `${error.message}
2438
+ ${stringifyStackFrames2(step.boxedStack).join("\n")}`;
2439
+ step.error = error;
2440
+ }
2441
+ if (result.softError) {
2442
+ step.infectParentStepsWithError = true;
2443
+ this._failWithError(result.softError);
2444
+ }
2445
+ if (result.shouldNotRetryTest)
2446
+ this._hasNonRetriableError = true;
2447
+ if (!step.error) {
2448
+ for (const childStep of step.steps) {
2449
+ if (childStep.error && childStep.infectParentStepsWithError) {
2450
+ step.error = childStep.error;
2451
+ step.infectParentStepsWithError = true;
2452
+ break;
2453
+ }
2454
+ }
2455
+ }
2456
+ if (!step.group) {
2457
+ const payload = {
2458
+ testId: this.testId,
2459
+ stepId,
2460
+ wallTime: step.endWallTime,
2461
+ error: step.error ? import_common2.ipc.toTestInfoErrorPayload(step.error) : void 0,
2462
+ suggestedRebaseline: result.suggestedRebaseline,
2463
+ annotations: step.info.annotations
2464
+ };
2465
+ this._callbacks.onStepEnd(payload);
2466
+ }
2467
+ if (step.group !== "internal") {
2468
+ const errorForTrace = step.error ? { name: "", message: step.error.message || "", stack: step.error.stack } : void 0;
2469
+ const attachments = step.attachmentIndices.map((i) => this.attachments[i]);
2470
+ this._tracing.appendAfterActionForStep(stepId, errorForTrace, attachments, step.info.annotations);
2471
+ }
2472
+ }
2473
+ };
2474
+ const parentStepList = parentStep ? parentStep.steps : this._steps;
2475
+ parentStepList.push(step);
2476
+ this._stepMap.set(stepId, step);
2477
+ if (!step.group) {
2478
+ const payload = {
2479
+ testId: this.testId,
2480
+ stepId,
2481
+ parentStepId: parentStep ? parentStep.stepId : void 0,
2482
+ title: step.title,
2483
+ category: step.category,
2484
+ wallTime: Date.now(),
2485
+ location: step.location
2486
+ };
2487
+ this._callbacks.onStepBegin(payload);
2488
+ }
2489
+ if (step.group !== "internal") {
2490
+ this._tracing.appendBeforeActionForStep({
2491
+ stepId,
2492
+ parentId: parentStep?.stepId,
2493
+ title: step.shortTitle ?? step.title,
2494
+ category: step.category,
2495
+ params: step.params,
2496
+ stack: step.location ? [step.location] : [],
2497
+ group: step.group
2498
+ });
2499
+ }
2500
+ return step;
2501
+ }
2502
+ _abort(location, message) {
2503
+ this.annotations.push({ type: "abort", description: message, location });
2504
+ throw new TestAbortError("Test aborted" + (message ? ": " + message : ""));
2505
+ }
2506
+ _interrupt() {
2507
+ this._interruptedPromise.resolve();
2508
+ this._timeoutManager.interrupt();
2509
+ if (this.status === "passed")
2510
+ this.status = "interrupted";
2511
+ }
2512
+ _failWithError(error) {
2513
+ if (this.status === "passed" || this.status === "skipped")
2514
+ this.status = error instanceof TimeoutManagerError ? "timedOut" : "failed";
2515
+ const serialized = testInfoError(error);
2516
+ const step = typeof error === "object" ? error?.[stepSymbol] : void 0;
2517
+ if (step && step.boxedStack)
2518
+ serialized.stack = `${error.name}: ${error.message}
2519
+ ${stringifyStackFrames2(step.boxedStack).join("\n")}`;
2520
+ this.errors.push(serialized);
2521
+ this._tracing.appendForError(serialized);
2522
+ }
2523
+ async _runAsStep(stepInfo, cb) {
2524
+ const step = this._addStep(stepInfo);
2525
+ try {
2526
+ await cb();
2527
+ step.complete({});
2528
+ } catch (error) {
2529
+ step.complete({ error });
2530
+ throw error;
2531
+ }
2532
+ }
2533
+ async _runWithTimeout(runnable, cb) {
2534
+ try {
2535
+ await this._timeoutManager.withRunnable(runnable, async () => {
2536
+ try {
2537
+ await cb();
2538
+ } catch (e) {
2539
+ if (this._allowSkips && e instanceof TestSkipError) {
2540
+ if (this.status === "passed")
2541
+ this.status = "skipped";
2542
+ } else {
2543
+ this._failWithError(e);
2544
+ }
2545
+ throw e;
2546
+ }
2547
+ });
2548
+ } catch (error) {
2549
+ if (!this._interruptedPromise.isDone() && error instanceof TimeoutManagerError)
2550
+ this._failWithError(error);
2551
+ throw error;
2552
+ }
2553
+ }
2554
+ _isFailure() {
2555
+ return this.status !== "skipped" && this.status !== this.expectedStatus;
2556
+ }
2557
+ _currentHookType() {
2558
+ const type = this._timeoutManager.currentSlotType();
2559
+ return ["beforeAll", "afterAll", "beforeEach", "afterEach"].includes(type) ? type : void 0;
2560
+ }
2561
+ _setIgnoreTimeouts(ignoreTimeouts) {
2562
+ this._ignoreTimeoutsCounter += ignoreTimeouts ? 1 : -1;
2563
+ this._timeoutManager.setIgnoreTimeouts(this._ignoreTimeoutsCounter > 0);
2564
+ }
2565
+ async _didFinishTestFunction() {
2566
+ const shouldPause = this._workerParams.pauseAtEnd && !this._isFailure() || this._workerParams.pauseOnError && this._isFailure();
2567
+ if (shouldPause) {
2568
+ await Promise.race([
2569
+ this._callbacks.onTestPaused({ testId: this.testId, errors: this._isFailure() ? this.errors.map(import_common2.ipc.toTestInfoErrorPayload) : [], status: this.status }),
2570
+ this._interruptedPromise
2571
+ ]);
2572
+ }
2573
+ for (const cb of this._onDidFinishTestFunctionCallbacks)
2574
+ await cb();
2575
+ }
2576
+ // ------------ TestInfo methods ------------
2577
+ async attach(name, options2 = {}) {
2578
+ const step = this._addStep({
2579
+ title: `Attach ${escapeWithQuotes2(name, '"')}`,
2580
+ category: "test.attach"
2581
+ });
2582
+ this._attach(
2583
+ await normalizeAndSaveAttachment(this.outputPath(), name, options2),
2584
+ step.stepId
2585
+ );
2586
+ step.complete({});
2587
+ }
2588
+ _attach(attachment, stepId) {
2589
+ const index = this._attachmentsPush(attachment) - 1;
2590
+ let step = stepId ? this._stepMap.get(stepId) : void 0;
2591
+ if (!!step?.group)
2592
+ step = void 0;
2593
+ if (step) {
2594
+ step.attachmentIndices.push(index);
2595
+ } else {
2596
+ const stepId2 = `attach@${createGuid2()}`;
2597
+ this._tracing.appendBeforeActionForStep({ stepId: stepId2, title: `Attach ${escapeWithQuotes2(attachment.name, '"')}`, category: "test.attach", stack: [] });
2598
+ this._tracing.appendAfterActionForStep(stepId2, void 0, [attachment]);
2599
+ }
2600
+ this._callbacks.onAttach({
2601
+ testId: this.testId,
2602
+ name: attachment.name,
2603
+ contentType: attachment.contentType,
2604
+ path: attachment.path,
2605
+ body: attachment.body?.toString("base64"),
2606
+ stepId: step?.stepId
2607
+ });
2608
+ }
2609
+ outputPath(...pathSegments) {
2610
+ const outputPath = this._getOutputPath(...pathSegments);
2611
+ import_fs3.default.mkdirSync(this.outputDir, { recursive: true });
2612
+ return outputPath;
2613
+ }
2614
+ _getOutputPath(...pathSegments) {
2615
+ const joinedPath = import_path3.default.join(...pathSegments);
2616
+ const outputPath = getContainedPath(this.outputDir, joinedPath);
2617
+ if (outputPath)
2618
+ return outputPath;
2619
+ throw new Error(`The outputPath is not allowed outside of the parent directory. Please fix the defined path.
2620
+
2621
+ outputPath: ${joinedPath}`);
2622
+ }
2623
+ _fsSanitizedTestName() {
2624
+ const fullTitleWithoutSpec = this.titlePath.slice(1).join(" ");
2625
+ return sanitizeForFilePath2(trimLongString(fullTitleWithoutSpec));
2626
+ }
2627
+ _resolveSnapshotPaths(kind, name, updateSnapshotIndex, anonymousExtension) {
2628
+ const snapshotNames = kind === "aria" ? this._ariaSnapshotNames : this._snapshotNames;
2629
+ const defaultExtensions = { "aria": ".aria.yml", "screenshot": ".png", "snapshot": ".txt" };
2630
+ const ariaAwareExtname = (filePath) => kind === "aria" && filePath.endsWith(".aria.yml") ? ".aria.yml" : import_path3.default.extname(filePath);
2631
+ let subPath;
2632
+ let ext;
2633
+ let relativeOutputPath;
2634
+ if (!name) {
2635
+ const index = snapshotNames.lastAnonymousSnapshotIndex + 1;
2636
+ if (updateSnapshotIndex === "updateSnapshotIndex")
2637
+ snapshotNames.lastAnonymousSnapshotIndex = index;
2638
+ const fullTitleWithoutSpec = [...this.titlePath.slice(1), index].join(" ");
2639
+ ext = anonymousExtension ?? defaultExtensions[kind];
2640
+ subPath = sanitizeFilePathBeforeExtension(trimLongString(fullTitleWithoutSpec) + ext, ext);
2641
+ relativeOutputPath = sanitizeFilePathBeforeExtension(trimLongString(fullTitleWithoutSpec, windowsFilesystemFriendlyLength) + ext, ext);
2642
+ } else {
2643
+ if (Array.isArray(name)) {
2644
+ subPath = import_path3.default.join(...name);
2645
+ relativeOutputPath = import_path3.default.join(...name);
2646
+ ext = ariaAwareExtname(subPath);
2647
+ } else {
2648
+ ext = ariaAwareExtname(name);
2649
+ subPath = sanitizeFilePathBeforeExtension(name, ext);
2650
+ relativeOutputPath = sanitizeFilePathBeforeExtension(trimLongString(name, windowsFilesystemFriendlyLength), ext);
2651
+ }
2652
+ const index = (snapshotNames.lastNamedSnapshotIndex[relativeOutputPath] || 0) + 1;
2653
+ if (updateSnapshotIndex === "updateSnapshotIndex")
2654
+ snapshotNames.lastNamedSnapshotIndex[relativeOutputPath] = index;
2655
+ if (index > 1)
2656
+ relativeOutputPath = addSuffixToFilePath(relativeOutputPath, `-${index - 1}`);
2657
+ }
2658
+ const legacyTemplate = "{snapshotDir}/{testFileDir}/{testFileName}-snapshots/{arg}{-projectName}{-snapshotSuffix}{ext}";
2659
+ let template;
2660
+ if (kind === "screenshot") {
2661
+ template = this._projectInternal.expect?.toHaveScreenshot?.pathTemplate || this._projectInternal.snapshotPathTemplate || legacyTemplate;
2662
+ } else if (kind === "aria") {
2663
+ const ariaDefaultTemplate = "{snapshotDir}/{testFileDir}/{testFileName}-snapshots/{arg}{ext}";
2664
+ template = this._projectInternal.expect?.toMatchAriaSnapshot?.pathTemplate || this._projectInternal.snapshotPathTemplate || ariaDefaultTemplate;
2665
+ } else {
2666
+ template = this._projectInternal.snapshotPathTemplate || legacyTemplate;
2667
+ }
2668
+ const nameArgument = import_path3.default.join(import_path3.default.dirname(subPath), import_path3.default.basename(subPath, ext));
2669
+ const absoluteSnapshotPath = this._applyPathTemplate(template, nameArgument, ext);
2670
+ return { absoluteSnapshotPath, relativeOutputPath };
2671
+ }
2672
+ _applyPathTemplate(template, nameArgument, ext) {
2673
+ const relativeTestFilePath = import_path3.default.relative(this.project.testDir, this._requireFile);
2674
+ const parsedRelativeTestFilePath = import_path3.default.parse(relativeTestFilePath);
2675
+ const projectNamePathSegment = sanitizeForFilePath2(this.project.name);
2676
+ const snapshotPath = template.replace(/\{(.)?testDir\}/g, "$1" + this.project.testDir).replace(/\{(.)?snapshotDir\}/g, "$1" + this.project.snapshotDir).replace(/\{(.)?snapshotSuffix\}/g, this.snapshotSuffix ? "$1" + this.snapshotSuffix : "").replace(/\{(.)?testFileDir\}/g, "$1" + parsedRelativeTestFilePath.dir).replace(/\{(.)?platform\}/g, "$1" + process.platform).replace(/\{(.)?projectName\}/g, projectNamePathSegment ? "$1" + projectNamePathSegment : "").replace(/\{(.)?testName\}/g, "$1" + this._fsSanitizedTestName()).replace(/\{(.)?testFileBaseName\}/g, "$1" + parsedRelativeTestFilePath.name).replace(/\{(.)?testFileName\}/g, "$1" + parsedRelativeTestFilePath.base).replace(/\{(.)?testFilePath\}/g, "$1" + relativeTestFilePath).replace(/\{(.)?arg\}/g, "$1" + nameArgument).replace(/\{(.)?ext\}/g, ext ? "$1" + ext : "");
2677
+ return import_path3.default.normalize(import_path3.default.resolve(this._configInternal.configDir, snapshotPath));
2678
+ }
2679
+ snapshotPath(...args) {
2680
+ let name = args;
2681
+ let kind = "snapshot";
2682
+ const options2 = args[args.length - 1];
2683
+ if (options2 && typeof options2 === "object") {
2684
+ kind = options2.kind ?? kind;
2685
+ name = args.slice(0, -1);
2686
+ }
2687
+ if (!["snapshot", "screenshot", "aria"].includes(kind))
2688
+ throw new Error(`testInfo.snapshotPath: unknown kind "${kind}", must be one of "snapshot", "screenshot" or "aria"`);
2689
+ return this._resolveSnapshotPaths(kind, name.length <= 1 ? name[0] : name, "dontUpdateSnapshotIndex").absoluteSnapshotPath;
2690
+ }
2691
+ setTimeout(timeout) {
2692
+ this._timeoutManager.setTimeout(timeout);
2693
+ }
2694
+ artifactsDir() {
2695
+ return this._workerParams.artifactsDir;
2696
+ }
2697
+ };
2698
+ var TestStepInfoImpl = class {
2699
+ constructor(testInfo, stepId, title, parentStep) {
2700
+ this.annotations = [];
2701
+ this._testInfo = testInfo;
2702
+ this._stepId = stepId;
2703
+ this._title = title;
2704
+ this._parentStep = parentStep;
2705
+ this.skip = import_common2.transform.wrapFunctionWithLocation((location, ...args) => {
2706
+ if (args.length > 0 && !args[0])
2707
+ return;
2708
+ const description = args[1];
2709
+ this.annotations.push({ type: "skip", description, location });
2710
+ throw new StepSkipError(description);
2711
+ });
2712
+ }
2713
+ async _runStepBody(skip, body, location) {
2714
+ if (skip) {
2715
+ this.annotations.push({ type: "skip", location });
2716
+ return void 0;
2717
+ }
2718
+ try {
2719
+ return await body(this);
2720
+ } catch (e) {
2721
+ if (e instanceof StepSkipError)
2722
+ return void 0;
2723
+ throw e;
2724
+ }
2725
+ }
2726
+ async attach(name, options2) {
2727
+ this._testInfo._attach(await normalizeAndSaveAttachment(this._testInfo.outputPath(), name, options2), this._stepId);
2728
+ }
2729
+ get titlePath() {
2730
+ const parent = this._parentStep ?? this._testInfo;
2731
+ return [...parent.titlePath, this._title];
2732
+ }
2733
+ };
2734
+ var TestSkipError = class extends Error {
2735
+ };
2736
+ var TestAbortError = class extends Error {
2737
+ };
2738
+ var StepSkipError = class extends Error {
2739
+ };
2740
+ var stepSymbol = Symbol("step");
2741
+
2742
+ // packages/playwright/src/worker/workerMain.ts
2743
+ var colors2 = require("playwright-core/lib/utilsBundle").colors;
2744
+ var { ManualPromise: ManualPromise5 } = require("playwright-core/lib/coreBundle").iso;
2745
+ var { removeFolders } = require("playwright-core/lib/coreBundle").utils;
2746
+ var { gracefullyCloseAll } = require("playwright-core/lib/coreBundle").utils;
2747
+ var WorkerMain = class extends import_common3.ProcessRunner {
2748
+ constructor(params) {
2749
+ super();
2750
+ // Accumulated fatal errors that cannot be attributed to a test.
2751
+ this._fatalErrors = [];
2752
+ // The stage of the full cleanup. Once "finished", we can safely stop running anything.
2753
+ this._didRunFullCleanup = false;
2754
+ // Whether the worker was stopped due to an unhandled error in a test marked with test.fail().
2755
+ // This should force dispatcher to use a new worker instead.
2756
+ this._stoppedDueToUnhandledErrorInTestFail = false;
2757
+ // Whether the worker was requested to stop.
2758
+ this._isStopped = false;
2759
+ // This promise resolves once the single "run test group" call finishes.
2760
+ this._runFinished = new ManualPromise5();
2761
+ this._currentTest = null;
2762
+ this._lastRunningTests = [];
2763
+ this._totalRunningTests = 0;
2764
+ // Suites that had their beforeAll hooks, but not afterAll hooks executed.
2765
+ // These suites still need afterAll hooks to be executed for the proper cleanup.
2766
+ // Contains dynamic annotations originated by modifiers with a callback, e.g. `test.skip(() => true)`.
2767
+ this._activeSuites = /* @__PURE__ */ new Map();
2768
+ process.env.TEST_WORKER_INDEX = String(params.workerIndex);
2769
+ process.env.TEST_PARALLEL_INDEX = String(params.parallelIndex);
2770
+ globals.setIsWorkerProcess();
2771
+ this._params = params;
2772
+ this._fixtureRunner = new FixtureRunner();
2773
+ this._runFinished.resolve();
2774
+ process.on("unhandledRejection", (reason) => this.unhandledError(reason));
2775
+ process.on("uncaughtException", (error) => this.unhandledError(error));
2776
+ process.stdout.write = (chunk, cb) => {
2777
+ this.dispatchEvent("stdOut", import_common3.ipc.stdioChunkToParams(chunk));
2778
+ this._currentTest?._tracing.appendStdioToTrace("stdout", chunk);
2779
+ if (typeof cb === "function")
2780
+ process.nextTick(cb);
2781
+ return true;
2782
+ };
2783
+ if (!process.env.PW_RUNNER_DEBUG) {
2784
+ process.stderr.write = (chunk, cb) => {
2785
+ this.dispatchEvent("stdErr", import_common3.ipc.stdioChunkToParams(chunk));
2786
+ this._currentTest?._tracing.appendStdioToTrace("stderr", chunk);
2787
+ if (typeof cb === "function")
2788
+ process.nextTick(cb);
2789
+ return true;
2790
+ };
2791
+ }
2792
+ }
2793
+ _stop() {
2794
+ if (!this._isStopped) {
2795
+ this._isStopped = true;
2796
+ this._currentTest?._interrupt();
2797
+ }
2798
+ return this._runFinished;
2799
+ }
2800
+ async gracefullyClose() {
2801
+ try {
2802
+ await this._stop();
2803
+ if (!this._config) {
2804
+ return;
2805
+ }
2806
+ const fakeTestInfo = new TestInfoImpl(this._config, this._project, this._params, void 0, 0, emtpyTestInfoCallbacks);
2807
+ const runnable = { type: "teardown" };
2808
+ await fakeTestInfo._runWithTimeout(runnable, () => this._loadIfNeeded()).catch(() => {
2809
+ });
2810
+ await this._fixtureRunner.teardownScope("test", fakeTestInfo, runnable).catch(() => {
2811
+ });
2812
+ await this._fixtureRunner.teardownScope("worker", fakeTestInfo, runnable).catch(() => {
2813
+ });
2814
+ await fakeTestInfo._runWithTimeout(runnable, () => gracefullyCloseAll()).catch(() => {
2815
+ });
2816
+ this._fatalErrors.push(...fakeTestInfo.errors);
2817
+ } catch (e) {
2818
+ this._fatalErrors.push(testInfoError(e));
2819
+ }
2820
+ if (this._fatalErrors.length) {
2821
+ this._appendProcessTeardownDiagnostics(this._fatalErrors[this._fatalErrors.length - 1]);
2822
+ const payload = { fatalErrors: this._fatalErrors.map(import_common3.ipc.toTestInfoErrorPayload) };
2823
+ this.dispatchEvent("teardownErrors", payload);
2824
+ }
2825
+ }
2826
+ _appendProcessTeardownDiagnostics(error) {
2827
+ if (!this._lastRunningTests.length)
2828
+ return;
2829
+ const count = this._totalRunningTests === 1 ? "1 test" : `${this._totalRunningTests} tests`;
2830
+ let lastMessage = "";
2831
+ if (this._lastRunningTests.length < this._totalRunningTests)
2832
+ lastMessage = `, last ${this._lastRunningTests.length} tests were`;
2833
+ const message = [
2834
+ "",
2835
+ "",
2836
+ colors2.red(`Failed worker ran ${count}${lastMessage}:`),
2837
+ ...this._lastRunningTests.map((test) => formatTestTitle(test, this._project.project.name))
2838
+ ].join("\n");
2839
+ if (error.message) {
2840
+ if (error.stack) {
2841
+ let index = error.stack.indexOf(error.message);
2842
+ if (index !== -1) {
2843
+ index += error.message.length;
2844
+ error.stack = error.stack.substring(0, index) + message + error.stack.substring(index);
2845
+ }
2846
+ }
2847
+ error.message += message;
2848
+ } else if (error.value) {
2849
+ error.value += message;
2850
+ }
2851
+ }
2852
+ unhandledError(error) {
2853
+ if (!this._currentTest) {
2854
+ if (!this._fatalErrors.length)
2855
+ this._fatalErrors.push(testInfoError(error));
2856
+ void this._stop();
2857
+ return;
2858
+ }
2859
+ if (!this._currentTest._hasUnhandledError) {
2860
+ this._currentTest._hasUnhandledError = true;
2861
+ this._currentTest._failWithError(error);
2862
+ }
2863
+ const isExpectError = error instanceof Error && !!error.matcherResult;
2864
+ const shouldContinueInThisWorker = this._currentTest.expectedStatus === "failed" && isExpectError;
2865
+ if (!shouldContinueInThisWorker) {
2866
+ this._stoppedDueToUnhandledErrorInTestFail = true;
2867
+ void this._stop();
2868
+ }
2869
+ }
2870
+ async _loadIfNeeded() {
2871
+ if (this._config)
2872
+ return;
2873
+ const config = await import_common3.configLoader.deserializeConfig(this._params.config);
2874
+ const project = config.projects.find((p) => p.id === this._params.projectId);
2875
+ if (!project)
2876
+ throw new Error(`Project "${this._params.projectId}" not found in the worker process. Make sure project name does not change.`);
2877
+ this._config = config;
2878
+ this._project = project;
2879
+ this._poolBuilder = import_common3.poolBuilder.PoolBuilder.createForWorker(this._project);
2880
+ this._fixtureRunner.workerFixtureTimeout = this._project.project.timeout;
2881
+ }
2882
+ async runTestGroup(runPayload) {
2883
+ this._runFinished = new ManualPromise5();
2884
+ const entries = new Map(runPayload.entries.map((e) => [e.testId, e]));
2885
+ let fatalUnknownTestIds;
2886
+ try {
2887
+ await this._loadIfNeeded();
2888
+ const fileSuite = await import_common3.testLoader.loadTestFile(runPayload.file, this._config);
2889
+ const suite = import_common3.suiteUtils.bindFileSuiteToProject(this._project, fileSuite);
2890
+ if (this._params.repeatEachIndex)
2891
+ import_common3.suiteUtils.applyRepeatEachIndex(this._project, suite, this._params.repeatEachIndex);
2892
+ import_common3.suiteUtils.filterTestsRemoveEmptySuites(suite, (test) => entries.has(test.id));
2893
+ const tests = suite.allTests();
2894
+ const unknownTestIds = new Set(entries.keys());
2895
+ for (const test of tests)
2896
+ unknownTestIds.delete(test.id);
2897
+ if (unknownTestIds.size) {
2898
+ fatalUnknownTestIds = [...unknownTestIds];
2899
+ void this._stop();
2900
+ return;
2901
+ }
2902
+ this._poolBuilder.buildPools(suite);
2903
+ this._activeSuites = /* @__PURE__ */ new Map();
2904
+ this._didRunFullCleanup = false;
2905
+ for (let i = 0; i < tests.length; i++) {
2906
+ if (this._isStopped && this._didRunFullCleanup)
2907
+ break;
2908
+ const entry = entries.get(tests[i].id);
2909
+ entries.delete(tests[i].id);
2910
+ debugTest(`test started "${tests[i].title}"`);
2911
+ await this._runTest(tests[i], entry.retry, tests[i + 1]);
2912
+ debugTest(`test finished "${tests[i].title}"`);
2913
+ }
2914
+ } catch (e) {
2915
+ this._fatalErrors.push(testInfoError(e));
2916
+ void this._stop();
2917
+ } finally {
2918
+ const donePayload = {
2919
+ fatalErrors: this._fatalErrors.map(import_common3.ipc.toTestInfoErrorPayload),
2920
+ skipTestsDueToSetupFailure: [],
2921
+ fatalUnknownTestIds,
2922
+ stoppedDueToUnhandledErrorInTestFail: this._stoppedDueToUnhandledErrorInTestFail
2923
+ };
2924
+ for (const test of this._skipRemainingTestsInSuite?.allTests() || []) {
2925
+ if (entries.has(test.id))
2926
+ donePayload.skipTestsDueToSetupFailure.push(test.id);
2927
+ }
2928
+ this.dispatchEvent("done", donePayload);
2929
+ this._fatalErrors = [];
2930
+ this._skipRemainingTestsInSuite = void 0;
2931
+ this._runFinished.resolve();
2932
+ }
2933
+ }
2934
+ async customMessage(payload) {
2935
+ try {
2936
+ if (this._currentTest?.testId !== payload.testId)
2937
+ throw new Error("Test has already stopped");
2938
+ const response = await this._currentTest._onCustomMessageCallback?.(payload.request);
2939
+ return { response };
2940
+ } catch (error) {
2941
+ return { response: {}, error: import_common3.ipc.toTestInfoErrorPayload(testInfoError(error)) };
2942
+ }
2943
+ }
2944
+ resume(payload) {
2945
+ this._resumePromise?.resolve(payload);
2946
+ }
2947
+ async _runTest(test, retry, nextTest) {
2948
+ const testInfo = new TestInfoImpl(this._config, this._project, this._params, test, retry, {
2949
+ onStepBegin: (payload) => this.dispatchEvent("stepBegin", payload),
2950
+ onStepEnd: (payload) => this.dispatchEvent("stepEnd", payload),
2951
+ onAttach: (payload) => this.dispatchEvent("attach", payload),
2952
+ onTestPaused: (payload) => {
2953
+ this._resumePromise = new ManualPromise5();
2954
+ this.dispatchEvent("testPaused", payload);
2955
+ return this._resumePromise;
2956
+ }
2957
+ });
2958
+ const processAnnotation = (annotation) => {
2959
+ testInfo.annotations.push(annotation);
2960
+ switch (annotation.type) {
2961
+ case "fixme":
2962
+ case "skip":
2963
+ testInfo.expectedStatus = "skipped";
2964
+ break;
2965
+ case "fail":
2966
+ if (testInfo.expectedStatus !== "skipped")
2967
+ testInfo.expectedStatus = "failed";
2968
+ break;
2969
+ case "slow":
2970
+ testInfo._timeoutManager.slow();
2971
+ break;
2972
+ }
2973
+ };
2974
+ if (!this._isStopped)
2975
+ this._fixtureRunner.setPool(test._pool);
2976
+ const suites = getSuites(test);
2977
+ const reversedSuites = suites.slice().reverse();
2978
+ const nextSuites = new Set(getSuites(nextTest));
2979
+ testInfo._timeoutManager.setTimeout(test.timeout);
2980
+ for (const annotation of test.annotations)
2981
+ processAnnotation(annotation);
2982
+ for (const suite of suites) {
2983
+ const extraAnnotations = this._activeSuites.get(suite) || [];
2984
+ for (const annotation of extraAnnotations)
2985
+ processAnnotation(annotation);
2986
+ }
2987
+ this._currentTest = testInfo;
2988
+ globals.setCurrentTestInfo(testInfo);
2989
+ (0, import_expect.setExpectConfig)({
2990
+ testInfo,
2991
+ filteredStackTrace,
2992
+ ignoreSnapshots: testInfo._projectInternal.project.ignoreSnapshots,
2993
+ updateSnapshots: testInfo.config.updateSnapshots,
2994
+ timeout: testInfo._projectInternal.expect?.timeout,
2995
+ toHaveScreenshot: testInfo._projectInternal.expect?.toHaveScreenshot,
2996
+ toMatchSnapshot: testInfo._projectInternal.expect?.toMatchSnapshot,
2997
+ toMatchAriaSnapshot: testInfo._projectInternal.expect?.toMatchAriaSnapshot,
2998
+ toPass: testInfo._projectInternal.expect?.toPass
2999
+ });
3000
+ this.dispatchEvent("testBegin", buildTestBeginPayload(testInfo));
3001
+ const isSkipped = testInfo.expectedStatus === "skipped";
3002
+ const hasAfterAllToRunBeforeNextTest = reversedSuites.some((suite) => {
3003
+ return this._activeSuites.has(suite) && !nextSuites.has(suite) && suite._hooks.some((hook) => hook.type === "afterAll");
3004
+ });
3005
+ if (isSkipped && nextTest && !hasAfterAllToRunBeforeNextTest) {
3006
+ testInfo.status = "skipped";
3007
+ this.dispatchEvent("testEnd", buildTestEndPayload(testInfo));
3008
+ return;
3009
+ }
3010
+ this._totalRunningTests++;
3011
+ this._lastRunningTests.push(test);
3012
+ if (this._lastRunningTests.length > 10)
3013
+ this._lastRunningTests.shift();
3014
+ let shouldRunAfterEachHooks = false;
3015
+ testInfo._allowSkips = true;
3016
+ await (async () => {
3017
+ await testInfo._runWithTimeout({ type: "test" }, async () => {
3018
+ const traceFixtureRegistration = test._pool.resolve("trace");
3019
+ if (!traceFixtureRegistration)
3020
+ return;
3021
+ if (typeof traceFixtureRegistration.fn === "function")
3022
+ throw new Error(`"trace" option cannot be a function`);
3023
+ await testInfo._tracing.startIfNeeded(traceFixtureRegistration.fn);
3024
+ });
3025
+ if (this._isStopped || isSkipped) {
3026
+ testInfo.status = "skipped";
3027
+ return;
3028
+ }
3029
+ await removeFolders([testInfo.outputDir]);
3030
+ let testFunctionParams = null;
3031
+ await testInfo._runAsStep({ title: "Before Hooks", category: "hook" }, async () => {
3032
+ for (const suite of suites)
3033
+ await this._runBeforeAllHooksForSuite(suite, testInfo);
3034
+ shouldRunAfterEachHooks = true;
3035
+ await this._runEachHooksForSuites(suites, "beforeEach", testInfo);
3036
+ const params = await this._fixtureRunner.resolveParametersForFunction(test.fn, testInfo, "test", { type: "test" });
3037
+ if (params !== null)
3038
+ testFunctionParams = params.result;
3039
+ });
3040
+ if (testFunctionParams === null) {
3041
+ return;
3042
+ }
3043
+ await testInfo._runWithTimeout({ type: "test" }, async () => {
3044
+ const fn = test.fn;
3045
+ await fn(testFunctionParams, testInfo);
3046
+ });
3047
+ })().catch(() => {
3048
+ });
3049
+ testInfo.duration = testInfo._timeoutManager.defaultSlot().elapsed | 0;
3050
+ testInfo._allowSkips = true;
3051
+ const afterHooksTimeout = calculateMaxTimeout(this._project.project.timeout, testInfo.timeout);
3052
+ const afterHooksSlot = { timeout: afterHooksTimeout, elapsed: 0 };
3053
+ await testInfo._runAsStep({ title: "After Hooks", category: "hook" }, async () => {
3054
+ let firstAfterHooksError;
3055
+ try {
3056
+ await testInfo._runWithTimeout({ type: "test", slot: afterHooksSlot }, () => testInfo._didFinishTestFunction());
3057
+ } catch (error) {
3058
+ firstAfterHooksError = firstAfterHooksError ?? error;
3059
+ }
3060
+ try {
3061
+ if (shouldRunAfterEachHooks)
3062
+ await this._runEachHooksForSuites(reversedSuites, "afterEach", testInfo, afterHooksSlot);
3063
+ } catch (error) {
3064
+ firstAfterHooksError = firstAfterHooksError ?? error;
3065
+ }
3066
+ testInfo._tracing.didFinishTestFunctionAndAfterEachHooks();
3067
+ try {
3068
+ await this._fixtureRunner.teardownScope("test", testInfo, { type: "test", slot: afterHooksSlot });
3069
+ } catch (error) {
3070
+ firstAfterHooksError = firstAfterHooksError ?? error;
3071
+ }
3072
+ for (const suite of reversedSuites) {
3073
+ if (!nextSuites.has(suite) || testInfo._isFailure()) {
3074
+ try {
3075
+ await this._runAfterAllHooksForSuite(suite, testInfo);
3076
+ } catch (error) {
3077
+ firstAfterHooksError = firstAfterHooksError ?? error;
3078
+ }
3079
+ }
3080
+ }
3081
+ if (firstAfterHooksError)
3082
+ throw firstAfterHooksError;
3083
+ }).catch(() => {
3084
+ });
3085
+ if (testInfo._isFailure())
3086
+ this._isStopped = true;
3087
+ if (this._isStopped) {
3088
+ this._didRunFullCleanup = true;
3089
+ await testInfo._runAsStep({ title: "Worker Cleanup", category: "hook" }, async () => {
3090
+ let firstWorkerCleanupError;
3091
+ const teardownSlot = { timeout: this._project.project.timeout, elapsed: 0 };
3092
+ try {
3093
+ await this._fixtureRunner.teardownScope("test", testInfo, { type: "test", slot: teardownSlot });
3094
+ } catch (error) {
3095
+ firstWorkerCleanupError = firstWorkerCleanupError ?? error;
3096
+ }
3097
+ for (const suite of reversedSuites) {
3098
+ try {
3099
+ await this._runAfterAllHooksForSuite(suite, testInfo);
3100
+ } catch (error) {
3101
+ firstWorkerCleanupError = firstWorkerCleanupError ?? error;
3102
+ }
3103
+ }
3104
+ try {
3105
+ await this._fixtureRunner.teardownScope("worker", testInfo, { type: "teardown", slot: teardownSlot });
3106
+ } catch (error) {
3107
+ firstWorkerCleanupError = firstWorkerCleanupError ?? error;
3108
+ }
3109
+ if (firstWorkerCleanupError)
3110
+ throw firstWorkerCleanupError;
3111
+ }).catch(() => {
3112
+ });
3113
+ }
3114
+ const tracingSlot = { timeout: this._project.project.timeout, elapsed: 0 };
3115
+ await testInfo._runWithTimeout({ type: "test", slot: tracingSlot }, async () => {
3116
+ await testInfo._tracing.stopIfNeeded();
3117
+ }).catch(() => {
3118
+ });
3119
+ testInfo.duration = testInfo._timeoutManager.defaultSlot().elapsed + afterHooksSlot.elapsed | 0;
3120
+ this._currentTest = null;
3121
+ globals.setCurrentTestInfo(null);
3122
+ (0, import_expect.setExpectConfig)({ testInfo: null, filteredStackTrace, ignoreSnapshots: false, updateSnapshots: "missing" });
3123
+ this.dispatchEvent("testEnd", buildTestEndPayload(testInfo));
3124
+ const preserveOutput = this._config.config.preserveOutput === "always" || this._config.config.preserveOutput === "failures-only" && testInfo._isFailure();
3125
+ if (!preserveOutput)
3126
+ await removeFolders([testInfo.outputDir]);
3127
+ }
3128
+ _collectHooksAndModifiers(suite, type, testInfo) {
3129
+ const runnables = [];
3130
+ for (const modifier of suite._modifiers) {
3131
+ const modifierType = this._fixtureRunner.dependsOnWorkerFixturesOnly(modifier.fn, modifier.location) ? "beforeAll" : "beforeEach";
3132
+ if (modifierType !== type)
3133
+ continue;
3134
+ const fn = async (fixtures3) => {
3135
+ const result = await modifier.fn(fixtures3);
3136
+ testInfo._modifier(modifier.type, modifier.location, [!!result, modifier.description]);
3137
+ };
3138
+ import_common3.fixtures.inheritFixtureNames(modifier.fn, fn);
3139
+ runnables.push({
3140
+ title: `${modifier.type} modifier`,
3141
+ location: modifier.location,
3142
+ type: modifier.type,
3143
+ fn
3144
+ });
3145
+ }
3146
+ runnables.push(...suite._hooks.filter((hook) => hook.type === type));
3147
+ return runnables;
3148
+ }
3149
+ async _runBeforeAllHooksForSuite(suite, testInfo) {
3150
+ if (this._activeSuites.has(suite))
3151
+ return;
3152
+ const extraAnnotations = [];
3153
+ this._activeSuites.set(suite, extraAnnotations);
3154
+ await this._runAllHooksForSuite(suite, testInfo, "beforeAll", extraAnnotations);
3155
+ }
3156
+ async _runAllHooksForSuite(suite, testInfo, type, extraAnnotations) {
3157
+ let firstError;
3158
+ for (const hook of this._collectHooksAndModifiers(suite, type, testInfo)) {
3159
+ try {
3160
+ await testInfo._runAsStep({ title: hook.title, category: "hook", location: hook.location }, async () => {
3161
+ const timeSlot = { timeout: this._project.project.timeout, elapsed: 0 };
3162
+ const runnable = { type: hook.type, slot: timeSlot, location: hook.location };
3163
+ const existingAnnotations = new Set(testInfo.annotations);
3164
+ try {
3165
+ await this._fixtureRunner.resolveParametersAndRunFunction(hook.fn, testInfo, "all-hooks-only", runnable);
3166
+ } finally {
3167
+ if (extraAnnotations) {
3168
+ const newAnnotations = testInfo.annotations.filter((a) => !existingAnnotations.has(a));
3169
+ extraAnnotations.push(...newAnnotations);
3170
+ }
3171
+ await this._fixtureRunner.teardownScope("test", testInfo, runnable);
3172
+ }
3173
+ });
3174
+ } catch (error) {
3175
+ firstError = firstError ?? error;
3176
+ if (type === "beforeAll" && error instanceof TestSkipError)
3177
+ break;
3178
+ if (type === "beforeAll" && !this._skipRemainingTestsInSuite) {
3179
+ this._skipRemainingTestsInSuite = suite;
3180
+ }
3181
+ }
3182
+ }
3183
+ if (firstError)
3184
+ throw firstError;
3185
+ }
3186
+ async _runAfterAllHooksForSuite(suite, testInfo) {
3187
+ if (!this._activeSuites.has(suite))
3188
+ return;
3189
+ this._activeSuites.delete(suite);
3190
+ await this._runAllHooksForSuite(suite, testInfo, "afterAll");
3191
+ }
3192
+ async _runEachHooksForSuites(suites, type, testInfo, slot) {
3193
+ let firstError;
3194
+ const hooks = suites.map((suite) => this._collectHooksAndModifiers(suite, type, testInfo)).flat();
3195
+ for (const hook of hooks) {
3196
+ const runnable = { type: hook.type, location: hook.location, slot };
3197
+ if (testInfo._timeoutManager.isTimeExhaustedFor(runnable)) {
3198
+ continue;
3199
+ }
3200
+ try {
3201
+ await testInfo._runAsStep({ title: hook.title, category: "hook", location: hook.location }, async () => {
3202
+ await this._fixtureRunner.resolveParametersAndRunFunction(hook.fn, testInfo, "test", runnable);
3203
+ });
3204
+ } catch (error) {
3205
+ firstError = firstError ?? error;
3206
+ if (error instanceof TestSkipError)
3207
+ break;
3208
+ }
3209
+ }
3210
+ if (firstError)
3211
+ throw firstError;
3212
+ }
3213
+ };
3214
+ function buildTestBeginPayload(testInfo) {
3215
+ return {
3216
+ testId: testInfo.testId,
3217
+ startWallTime: testInfo._startWallTime
3218
+ };
3219
+ }
3220
+ function buildTestEndPayload(testInfo) {
3221
+ return {
3222
+ testId: testInfo.testId,
3223
+ duration: testInfo.duration,
3224
+ status: testInfo.status,
3225
+ errors: testInfo.errors.map(import_common3.ipc.toTestInfoErrorPayload),
3226
+ hasNonRetriableError: testInfo._hasNonRetriableError,
3227
+ expectedStatus: testInfo.expectedStatus,
3228
+ annotations: testInfo.annotations,
3229
+ timeout: testInfo.timeout
3230
+ };
3231
+ }
3232
+ function getSuites(test) {
3233
+ const suites = [];
3234
+ for (let suite = test?.parent; suite; suite = suite.parent)
3235
+ suites.push(suite);
3236
+ suites.reverse();
3237
+ return suites;
3238
+ }
3239
+ function formatTestTitle(test, projectName) {
3240
+ const [, ...titles] = test.titlePath();
3241
+ const location = `${relativeFilePath(test.location.file)}:${test.location.line}:${test.location.column}`;
3242
+ const projectTitle = projectName ? `[${projectName}] \u203A ` : "";
3243
+ return `${projectTitle}${location} \u203A ${titles.join(" \u203A ")}`;
3244
+ }
3245
+ function calculateMaxTimeout(t1, t2) {
3246
+ return !t1 || !t2 ? 0 : Math.max(t1, t2);
3247
+ }
3248
+ var create = (params) => new WorkerMain(params);
3249
+
3250
+ // packages/playwright/src/worker/workerProcessEntry.ts
3251
+ (0, import_common4.startProcessRunner)(create);