@flakemetry/wdio-reporter 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,640 @@
1
+ Object.defineProperties(exports, {
2
+ __esModule: { value: true },
3
+ [Symbol.toStringTag]: { value: "Module" }
4
+ });
5
+ // \0rolldown/runtime.js
6
+ var __create = Object.create;
7
+ var __defProp = Object.defineProperty;
8
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
9
+ var __getOwnPropNames = Object.getOwnPropertyNames;
10
+ var __getProtoOf = Object.getPrototypeOf;
11
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
14
+ key = keys[i];
15
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
16
+ get: ((k) => from[k]).bind(null, key),
17
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
18
+ });
19
+ }
20
+ return to;
21
+ };
22
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
23
+ value: mod,
24
+ enumerable: true
25
+ }) : target, mod));
26
+ let node_path = require("node:path");
27
+ let _flakemetry_contracts = require("@flakemetry/contracts");
28
+ let node_url = require("node:url");
29
+ let node_util = require("node:util");
30
+ let _flakemetry_sdk = require("@flakemetry/sdk");
31
+ let _wdio_reporter = require("@wdio/reporter");
32
+ _wdio_reporter = __toESM(_wdio_reporter, 1);
33
+ let node_fs = require("node:fs");
34
+ // src/mapping.ts
35
+ const STACK_FRAME = /^\s+at\s/;
36
+ const MAX_MESSAGE_LENGTH = 8e3;
37
+ const MAX_VARIANT_LENGTH = 100;
38
+ const MAX_IDEMPOTENCY_KEY_LENGTH = 128;
39
+ const NOT_RUN = [/^Test skipped due to failure in hook\b/, /^Not run because a beforeAll function failed\b/];
40
+ const stripAnsi = (value) => (0, node_util.stripVTControlCharacters)(value);
41
+ const errorOf = (errors, error) => errors?.find((candidate) => Boolean(candidate)) ?? error ?? void 0;
42
+ const neverRan = (error) => {
43
+ const message = stripAnsi(error?.message ?? "").trim();
44
+ return NOT_RUN.some((pattern) => pattern.test(message));
45
+ };
46
+ const summarizeError = (error, fallback) => {
47
+ const lines = stripAnsi(error?.message ?? "").split("\n");
48
+ const frame = lines.findIndex((line) => STACK_FRAME.test(line));
49
+ const message = (frame === -1 ? lines : lines.slice(0, frame)).join("\n").trim();
50
+ return {
51
+ type: error?.name ?? error?.type ?? null,
52
+ message: message.length > 0 ? message.slice(0, MAX_MESSAGE_LENGTH) : fallback,
53
+ stack: error?.stack ? stripAnsi(error.stack) : null
54
+ };
55
+ };
56
+ const commandStatus = (result) => {
57
+ const record = result && typeof result === "object" ? result : {};
58
+ const thrown = record.error;
59
+ if (thrown) {
60
+ const detail = thrown;
61
+ return {
62
+ status: "error",
63
+ error: {
64
+ type: detail.name ?? null,
65
+ message: stripAnsi(detail.message ?? String(thrown)).split("\n")[0] || "command failed"
66
+ }
67
+ };
68
+ }
69
+ const value = record.value;
70
+ if (value && typeof value === "object" && typeof value.error === "string") {
71
+ const detail = {
72
+ error: value.error,
73
+ message: typeof value.message === "string" ? value.message : void 0
74
+ };
75
+ return {
76
+ status: "error",
77
+ error: {
78
+ type: detail.error,
79
+ message: stripAnsi(detail.message ?? detail.error).split("\n")[0] || detail.error
80
+ }
81
+ };
82
+ }
83
+ return {
84
+ status: "ok",
85
+ error: null
86
+ };
87
+ };
88
+ const toFilePath = (raw) => {
89
+ if (!raw || raw === "unknown spec file") return void 0;
90
+ if (raw.startsWith("file://")) try {
91
+ return (0, node_url.fileURLToPath)(raw);
92
+ } catch {
93
+ return;
94
+ }
95
+ return raw;
96
+ };
97
+ const relativize = (rootDir, filePath) => {
98
+ if (!(0, node_path.isAbsolute)(filePath)) return filePath.split(node_path.sep).join("/");
99
+ const inside = (0, node_path.relative)(rootDir, filePath);
100
+ return (inside && !inside.startsWith("..") && !(0, node_path.isAbsolute)(inside) ? inside : filePath).split(node_path.sep).join("/");
101
+ };
102
+ const text = (value) => typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
103
+ const unwrap = (capabilities) => {
104
+ const alwaysMatch = capabilities.alwaysMatch;
105
+ return alwaysMatch && typeof alwaysMatch === "object" ? {
106
+ ...alwaysMatch,
107
+ ...capabilities
108
+ } : capabilities;
109
+ };
110
+ const explicitVariant = (capabilities) => capabilities ? text(unwrap(capabilities)["flakemetry:variant"]) : void 0;
111
+ const capabilityLabel = (capabilities) => {
112
+ if (!capabilities) return void 0;
113
+ const caps = unwrap(capabilities);
114
+ const explicit = text(caps["flakemetry:variant"]);
115
+ if (explicit) return explicit;
116
+ const label = [text(caps.platformName), text(caps.browserName) ?? text(caps["appium:deviceName"]) ?? text(caps.deviceName)].filter(Boolean).join(" ");
117
+ return label.length > 0 ? label : void 0;
118
+ };
119
+ const capabilityIndex = (cid) => {
120
+ const index = Number.parseInt(cid ?? "", 10);
121
+ return Number.isInteger(index) && index >= 0 ? index : void 0;
122
+ };
123
+ const resolveVariant = ({ cid, requested, configured, multiremote }) => {
124
+ if (multiremote) return void 0;
125
+ const index = capabilityIndex(cid);
126
+ const own = index !== void 0 ? configured?.[index] : void 0;
127
+ const explicit = explicitVariant(requested) ?? explicitVariant(own);
128
+ if (explicit) return explicit.slice(0, MAX_VARIANT_LENGTH);
129
+ if (!configured || configured.length < 2 || index === void 0) return void 0;
130
+ const labels = configured.map((capabilities, position) => capabilityLabel(capabilities) ?? `capability ${position + 1}`);
131
+ const label = labels[index] ?? capabilityLabel(requested) ?? `capability ${index + 1}`;
132
+ return (labels.filter((candidate) => candidate === label).length > 1 ? `${label} (${index + 1})` : label).slice(0, MAX_VARIANT_LENGTH);
133
+ };
134
+ const shardOf = (shard) => {
135
+ if (!shard || typeof shard !== "object") return null;
136
+ const { current, total } = shard;
137
+ return typeof current === "number" && typeof total === "number" && total > 1 ? {
138
+ current,
139
+ total
140
+ } : null;
141
+ };
142
+ const workerOutputFile = (file, cid) => {
143
+ const extension = (0, node_path.extname)(file);
144
+ const name = (0, node_path.basename)(file, extension);
145
+ const worker = cid.replace(/[^\w.-]+/g, "-");
146
+ return (0, node_path.join)((0, node_path.dirname)(file), `${name}-${worker}${extension}`);
147
+ };
148
+ const workerIdempotencyKey = (key, cid) => {
149
+ const suffix = `-w${cid.replace(/[^\w.-]+/g, "-")}`;
150
+ return `${key.slice(0, MAX_IDEMPOTENCY_KEY_LENGTH - suffix.length)}${suffix}`;
151
+ };
152
+ const runFailed = (tests) => tests.some((test) => test.status === "fail");
153
+ // src/collector.ts
154
+ const SUITE_SEPARATOR = " > ";
155
+ const NODE_MODULES = `${node_path.sep}node_modules${node_path.sep}`;
156
+ const usableFile = (raw) => {
157
+ const file = toFilePath(raw);
158
+ return file && !file.includes(NODE_MODULES) && !file.includes("/node_modules/") ? file : void 0;
159
+ };
160
+ var WdioCollector = class {
161
+ now;
162
+ suites = /* @__PURE__ */ new Map();
163
+ stack = [];
164
+ owners = [];
165
+ retrying = /* @__PURE__ */ new Map();
166
+ collected = [];
167
+ fallbackFile;
168
+ constructor(now = Date.now) {
169
+ this.now = now;
170
+ }
171
+ get size() {
172
+ return this.collected.length;
173
+ }
174
+ setSpecs(specs) {
175
+ this.fallbackFile = usableFile(specs?.[0]);
176
+ }
177
+ suiteStart(suite) {
178
+ this.suites.set(suite.uid, suite);
179
+ this.stack.push(suite.uid);
180
+ }
181
+ suiteEnd(suite) {
182
+ for (const owner of [...this.owners]) if (owner.type === "test" && owner.suiteUids.includes(suite.uid)) this.finalize(owner);
183
+ const index = this.stack.lastIndexOf(suite.uid);
184
+ if (index !== -1) this.stack.splice(index, 1);
185
+ }
186
+ hookStart(hook) {
187
+ this.owners.push({
188
+ type: "hook",
189
+ stats: hook,
190
+ ...this.ownerBase(hook, hook.start)
191
+ });
192
+ }
193
+ hookEnd(hook) {
194
+ const owner = this.findOwner("hook", hook.uid);
195
+ if (!owner) return;
196
+ this.remove(owner);
197
+ this.closeOpen(owner);
198
+ const durationMs = this.durationOf(hook.duration, owner.startedAt);
199
+ const error = errorOf(hook.errors, hook.error);
200
+ if (Boolean(error) || hook.state === "failed") {
201
+ if (hook.retried || hook.failedTestUid) return;
202
+ this.collected.push({
203
+ file: owner.file,
204
+ test: {
205
+ suite: owner.suite.join(SUITE_SEPARATOR),
206
+ title: owner.title || "hook",
207
+ status: "fail",
208
+ attempt: 1,
209
+ retryOfIndex: null,
210
+ startedAt: owner.startedAt,
211
+ durationMs,
212
+ error: summarizeError(error, "hook failed"),
213
+ steps: owner.steps.length > 0 ? owner.steps : null
214
+ }
215
+ });
216
+ return;
217
+ }
218
+ const attempt = this.latestOwner(hook.contextId, "test");
219
+ if (!attempt) return;
220
+ this.addStep(attempt, attempt.steps, {
221
+ name: owner.title || "hook",
222
+ kind: "step",
223
+ startedAt: owner.startedAt,
224
+ durationMs,
225
+ status: "ok",
226
+ ...owner.steps.length > 0 ? { children: owner.steps } : {}
227
+ });
228
+ attempt.spans += owner.spans;
229
+ }
230
+ testStart(test) {
231
+ if (this.findOwner("test", test.uid)) return;
232
+ this.open(test);
233
+ }
234
+ testPass(test) {
235
+ this.attemptFor(test).outcome = "pass";
236
+ }
237
+ testFail(test) {
238
+ const attempt = this.attemptFor(test);
239
+ const error = errorOf(test.errors, test.error);
240
+ attempt.outcome = neverRan(error) ? "skip" : "fail";
241
+ attempt.error = attempt.outcome === "fail" ? error : void 0;
242
+ }
243
+ testRetry(test) {
244
+ const attempt = this.attemptFor(test);
245
+ attempt.outcome = "fail";
246
+ attempt.error = errorOf(test.errors, test.error);
247
+ const index = this.finalize(attempt);
248
+ this.retrying.set(attempt.key, {
249
+ attempt: attempt.attempt,
250
+ firstIndex: attempt.retryOf ?? index
251
+ });
252
+ }
253
+ testSkip(test) {
254
+ this.attemptFor(test).outcome = "skip";
255
+ }
256
+ testEnd(test) {
257
+ const attempt = this.findOwner("test", test.uid);
258
+ if (attempt) this.finalize(attempt);
259
+ }
260
+ beforeCommand(command) {
261
+ const owner = this.latestOwner(command.contextId);
262
+ if (!owner) return;
263
+ const parent = owner.assertions.at(-1)?.step;
264
+ const started = this.now();
265
+ const attributes = {};
266
+ if (command.command) attributes["wdio.command"] = command.command;
267
+ if (command.method) attributes["http.request.method"] = command.method;
268
+ if (command.endpoint) attributes["url.path"] = command.endpoint;
269
+ const step = {
270
+ name: command.command || "command",
271
+ kind: "browser",
272
+ startedAt: new Date(started),
273
+ durationMs: 0,
274
+ status: "unset",
275
+ attributes
276
+ };
277
+ if (!this.addStep(owner, parent ? parent.children ??= [] : owner.steps, step)) return;
278
+ owner.commands.push({
279
+ key: this.commandKey(command),
280
+ step,
281
+ started
282
+ });
283
+ }
284
+ afterCommand(command) {
285
+ const owner = this.latestOwner(command.contextId);
286
+ if (!owner) return;
287
+ const key = this.commandKey(command);
288
+ const index = owner.commands.findIndex((open) => open.key === key);
289
+ if (index === -1) return;
290
+ const [open] = owner.commands.splice(index, 1);
291
+ if (!open) return;
292
+ const outcome = commandStatus(command.result);
293
+ open.step.durationMs = Math.max(0, this.now() - open.started);
294
+ open.step.status = outcome.status;
295
+ open.step.error = outcome.error;
296
+ }
297
+ beforeAssertion(assertion) {
298
+ const owner = this.latestOwner(assertion.contextId);
299
+ if (!owner) return;
300
+ const parent = owner.assertions.at(-1)?.step;
301
+ const started = this.now();
302
+ const step = {
303
+ name: `expect.${assertion.matcherName || "assertion"}`,
304
+ kind: "step",
305
+ startedAt: new Date(started),
306
+ durationMs: 0,
307
+ status: "unset"
308
+ };
309
+ if (!this.addStep(owner, parent ? parent.children ??= [] : owner.steps, step)) return;
310
+ owner.assertions.push({
311
+ step,
312
+ started
313
+ });
314
+ }
315
+ afterAssertion(assertion) {
316
+ const open = this.latestOwner(assertion.contextId)?.assertions.pop();
317
+ if (!open) return;
318
+ open.step.durationMs = Math.max(0, this.now() - open.started);
319
+ const pass = assertion.result?.pass;
320
+ if (typeof pass === "boolean") open.step.attributes = { "wdio.assertion.pass": pass };
321
+ }
322
+ finish({ rootDir, variant }) {
323
+ for (const owner of [...this.owners]) if (owner.type === "test") this.finalize(owner);
324
+ else this.remove(owner);
325
+ return this.collected.map(({ file, test }) => ({
326
+ ...test,
327
+ filePath: file ? relativize(rootDir, file) : "unknown",
328
+ variant
329
+ }));
330
+ }
331
+ ownerBase(stats, start) {
332
+ const { titles, uids } = this.locate(stats);
333
+ return {
334
+ uid: stats.uid,
335
+ contextId: stats.contextId,
336
+ title: stats.title,
337
+ suite: titles,
338
+ suiteUids: uids,
339
+ file: this.fileOf(stats.file, uids),
340
+ startedAt: this.dateOf(start),
341
+ steps: [],
342
+ spans: 0,
343
+ commands: [],
344
+ assertions: []
345
+ };
346
+ }
347
+ open(test) {
348
+ const base = this.ownerBase(test, test.start);
349
+ const key = [
350
+ base.file ?? "",
351
+ base.suite.join(SUITE_SEPARATOR),
352
+ test.title
353
+ ].join("\0");
354
+ const stale = this.owners.find((owner) => owner.type === "test" && owner.key === key);
355
+ if (stale) {
356
+ this.remove(stale);
357
+ this.closeOpen(stale);
358
+ }
359
+ const previous = stale ? void 0 : this.retrying.get(key);
360
+ if (previous) this.retrying.delete(key);
361
+ const attempt = {
362
+ ...base,
363
+ ...stale ? {
364
+ startedAt: stale.startedAt,
365
+ steps: stale.steps,
366
+ spans: stale.spans
367
+ } : {},
368
+ type: "test",
369
+ stats: test,
370
+ key,
371
+ attempt: stale ? stale.attempt : previous ? previous.attempt + 1 : 1,
372
+ retryOf: stale ? stale.retryOf : previous ? previous.firstIndex : null
373
+ };
374
+ this.owners.push(attempt);
375
+ return attempt;
376
+ }
377
+ attemptFor(test) {
378
+ return this.findOwner("test", test.uid) ?? this.open(test);
379
+ }
380
+ finalize(attempt) {
381
+ this.remove(attempt);
382
+ this.closeOpen(attempt);
383
+ const status = attempt.outcome === "pass" ? attempt.attempt > 1 ? "flaky" : "pass" : attempt.outcome === "fail" ? "fail" : "skip";
384
+ this.collected.push({
385
+ file: attempt.file,
386
+ test: {
387
+ suite: attempt.suite.join(SUITE_SEPARATOR),
388
+ title: attempt.title || "untitled",
389
+ status,
390
+ attempt: attempt.attempt,
391
+ retryOfIndex: attempt.retryOf,
392
+ startedAt: attempt.startedAt,
393
+ durationMs: this.durationOf(attempt.stats.duration, attempt.startedAt),
394
+ error: status === "fail" ? summarizeError(attempt.error, "test failed") : null,
395
+ steps: attempt.steps.length > 0 ? attempt.steps : null
396
+ }
397
+ });
398
+ return this.collected.length - 1;
399
+ }
400
+ addStep(owner, siblings, step) {
401
+ if (owner.spans >= _flakemetry_contracts.MAX_SPANS_PER_EXECUTION) return false;
402
+ siblings.push(step);
403
+ owner.spans += 1;
404
+ return true;
405
+ }
406
+ closeOpen(owner) {
407
+ const now = this.now();
408
+ for (const open of owner.commands) open.step.durationMs = Math.max(0, now - open.started);
409
+ for (const open of owner.assertions) open.step.durationMs = Math.max(0, now - open.started);
410
+ owner.commands = [];
411
+ owner.assertions = [];
412
+ }
413
+ commandKey(command) {
414
+ return `${command.command ?? ""} ${command.method ?? ""} ${command.endpoint ?? ""}`;
415
+ }
416
+ findOwner(type, uid) {
417
+ for (let index = this.owners.length - 1; index >= 0; index -= 1) {
418
+ const owner = this.owners[index];
419
+ if (owner && owner.type === type && owner.uid === uid) return owner;
420
+ }
421
+ }
422
+ latestOwner(contextId, type) {
423
+ for (let index = this.owners.length - 1; index >= 0; index -= 1) {
424
+ const owner = this.owners[index];
425
+ if (!owner || type && owner.type !== type) continue;
426
+ if (contextId === void 0 || owner.contextId === contextId) return owner;
427
+ }
428
+ }
429
+ remove(owner) {
430
+ const index = this.owners.indexOf(owner);
431
+ if (index !== -1) this.owners.splice(index, 1);
432
+ }
433
+ locate(stats) {
434
+ const anchor = stats.hookSuiteUid ?? stats.parentUid;
435
+ const uids = anchor === null ? [] : (anchor ? this.chain(anchor) : null) ?? [...this.stack];
436
+ return {
437
+ titles: uids.map((uid) => this.suites.get(uid)?.title ?? "").filter((title) => title.length > 0),
438
+ uids
439
+ };
440
+ }
441
+ chain(uid) {
442
+ const uids = [];
443
+ let current = uid;
444
+ while (current) {
445
+ const suite = this.suites.get(current);
446
+ if (!suite || suite.parentUid === void 0) return null;
447
+ uids.unshift(current);
448
+ current = suite.parentUid;
449
+ }
450
+ return uids;
451
+ }
452
+ fileOf(own, uids) {
453
+ const direct = usableFile(own);
454
+ if (direct) return direct;
455
+ for (let index = uids.length - 1; index >= 0; index -= 1) {
456
+ const file = usableFile(this.suites.get(uids[index] ?? "")?.file);
457
+ if (file) return file;
458
+ }
459
+ return this.fallbackFile;
460
+ }
461
+ dateOf(start) {
462
+ if (start instanceof Date && !Number.isNaN(start.getTime())) return start;
463
+ if (typeof start === "number" && Number.isFinite(start)) return new Date(start);
464
+ return new Date(this.now());
465
+ }
466
+ durationOf(duration, startedAt) {
467
+ if (typeof duration === "number" && Number.isFinite(duration)) return Math.max(0, Math.round(duration));
468
+ return Math.max(0, Math.round(this.now() - startedAt.getTime()));
469
+ }
470
+ };
471
+ // src/capabilities.ts
472
+ const DEFAULT_CONFIG_FILES = [
473
+ "wdio.conf.ts",
474
+ "wdio.conf.js",
475
+ "wdio.conf.mts",
476
+ "wdio.conf.mjs",
477
+ "wdio.conf.cts",
478
+ "wdio.conf.cjs"
479
+ ];
480
+ const IMPLIED_EXTENSIONS = [
481
+ "",
482
+ ".ts",
483
+ ".js"
484
+ ];
485
+ const isRecord = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
486
+ const findConfigFile = (config, cwd, exists = node_fs.existsSync) => {
487
+ const given = [config?.["config-path"], config?.configPath].find((value) => typeof value === "string" && value.length > 0);
488
+ return (given ? IMPLIED_EXTENSIONS.map((extension) => (0, node_path.resolve)(cwd, `${given}${extension}`)) : DEFAULT_CONFIG_FILES.map((name) => (0, node_path.resolve)(cwd, name))).find((candidate) => exists(candidate));
489
+ };
490
+ const loadConfiguredCapabilities = async (config, cwd, importModule = (specifier) => import(specifier), exists = node_fs.existsSync) => {
491
+ try {
492
+ const file = findConfigFile(config, cwd, exists);
493
+ if (!file) return null;
494
+ const loaded = await importModule((0, node_url.pathToFileURL)(file).href);
495
+ const capabilities = (loaded?.config ?? loaded?.default?.config)?.capabilities;
496
+ return Array.isArray(capabilities) ? capabilities.map((entry) => isRecord(entry) ? entry : {}) : null;
497
+ } catch {
498
+ return null;
499
+ }
500
+ };
501
+ // src/reporter.ts
502
+ const WDIOReporter = _wdio_reporter.default.default ?? _wdio_reporter.default;
503
+ const SILENT = { write: () => true };
504
+ const asRecord = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
505
+ const deliveryOptions = (options) => {
506
+ const { endpoint, token, outputFile, transport, bufferDir, sampleRate, rng } = options;
507
+ return {
508
+ endpoint,
509
+ token,
510
+ outputFile,
511
+ transport,
512
+ bufferDir,
513
+ sampleRate,
514
+ rng
515
+ };
516
+ };
517
+ var FlakemetryWdioReporter = class extends WDIOReporter {
518
+ delivery;
519
+ env;
520
+ collector;
521
+ configured = Promise.resolve(null);
522
+ startedAt;
523
+ delivering = false;
524
+ constructor(options = {}) {
525
+ super({
526
+ ...options,
527
+ logFile: void 0,
528
+ outputDir: void 0,
529
+ writeStream: options.writeStream ?? SILENT
530
+ });
531
+ this.delivery = deliveryOptions(options);
532
+ this.env = process.env;
533
+ this.collector = new WdioCollector();
534
+ }
535
+ get isSynchronised() {
536
+ return !this.delivering;
537
+ }
538
+ onRunnerStart(runner) {
539
+ this.guard(() => {
540
+ this.startedAt = runner.start instanceof Date ? runner.start : /* @__PURE__ */ new Date();
541
+ this.collector.setSpecs(runner.specs);
542
+ this.configured = loadConfiguredCapabilities(asRecord(runner.config), process.cwd());
543
+ });
544
+ }
545
+ onSuiteStart(suite) {
546
+ this.guard(() => this.collector.suiteStart(suite));
547
+ }
548
+ onSuiteEnd(suite) {
549
+ this.guard(() => this.collector.suiteEnd(suite));
550
+ }
551
+ onHookStart(hook) {
552
+ this.guard(() => this.collector.hookStart(hook));
553
+ }
554
+ onHookEnd(hook) {
555
+ this.guard(() => this.collector.hookEnd(hook));
556
+ }
557
+ onTestStart(test) {
558
+ this.guard(() => this.collector.testStart(test));
559
+ }
560
+ onTestPass(test) {
561
+ this.guard(() => this.collector.testPass(test));
562
+ }
563
+ onTestFail(test) {
564
+ this.guard(() => this.collector.testFail(test));
565
+ }
566
+ onTestRetry(test) {
567
+ this.guard(() => this.collector.testRetry(test));
568
+ }
569
+ onTestSkip(test) {
570
+ this.guard(() => this.collector.testSkip(test));
571
+ }
572
+ onTestPending(test) {
573
+ this.guard(() => this.collector.testSkip(test));
574
+ }
575
+ onTestEnd(test) {
576
+ this.guard(() => this.collector.testEnd(test));
577
+ }
578
+ onBeforeCommand(command) {
579
+ this.guard(() => this.collector.beforeCommand(command));
580
+ }
581
+ onAfterCommand(command) {
582
+ this.guard(() => this.collector.afterCommand(command));
583
+ }
584
+ onBeforeAssertion(assertion) {
585
+ this.guard(() => this.collector.beforeAssertion(assertion));
586
+ }
587
+ onAfterAssertion(assertion) {
588
+ this.guard(() => this.collector.afterAssertion(assertion));
589
+ }
590
+ onRunnerEnd(runner) {
591
+ this.delivering = true;
592
+ this.deliver(runner).finally(() => {
593
+ this.delivering = false;
594
+ });
595
+ }
596
+ async deliver(runner) {
597
+ try {
598
+ const config = asRecord(runner.config) ?? {};
599
+ const rootDir = typeof config.rootDir === "string" ? config.rootDir : process.cwd();
600
+ const cid = runner.cid ?? this.env.WDIO_WORKER_ID ?? "0-0";
601
+ const variant = resolveVariant({
602
+ cid,
603
+ requested: asRecord(config.capabilities) ?? asRecord(runner.capabilities),
604
+ configured: await this.configured,
605
+ multiremote: Boolean(runner.isMultiremote ?? runner.isMultiRemote)
606
+ });
607
+ const tests = this.collector.finish({
608
+ rootDir,
609
+ variant
610
+ });
611
+ if (tests.length === 0) return;
612
+ const context = (0, _flakemetry_sdk.resolveRunContext)(this.env, shardOf(config.shard));
613
+ const recorder = new _flakemetry_sdk.TestRunRecorder(context);
614
+ recorder.startRun(this.startedAt ?? tests[0]?.startedAt ?? /* @__PURE__ */ new Date());
615
+ for (const test of tests) recorder.record(test);
616
+ recorder.finishRun(runFailed(tests) ? "failed" : "passed", runner.end instanceof Date ? runner.end : /* @__PURE__ */ new Date());
617
+ const outputFile = this.delivery.outputFile ?? this.env.FLAKEMETRY_OUTPUT_FILE;
618
+ const idempotencyKey = workerIdempotencyKey((0, _flakemetry_sdk.buildIdempotencyKey)(context, this.env), cid);
619
+ await (0, _flakemetry_sdk.deliverRun)(recorder, idempotencyKey, {
620
+ ...this.delivery,
621
+ outputFile: outputFile ? workerOutputFile(outputFile, cid) : void 0
622
+ }, this.env, rootDir);
623
+ } catch (error) {
624
+ process.stderr.write(`flakemetry: the run was not delivered (${error instanceof Error ? error.message : String(error)})\n`);
625
+ }
626
+ }
627
+ guard(action) {
628
+ try {
629
+ action();
630
+ } catch (error) {
631
+ process.stderr.write(`flakemetry: an event was not recorded (${error instanceof Error ? error.message : String(error)})\n`);
632
+ }
633
+ }
634
+ };
635
+ exports.WdioCollector = WdioCollector;
636
+ exports.capabilityLabel = capabilityLabel;
637
+ exports.default = FlakemetryWdioReporter;
638
+ exports.resolveVariant = resolveVariant;
639
+
640
+ //# sourceMappingURL=index.cjs.map