@piwitests/reporter 0.64.0 → 0.65.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.
@@ -34,9 +34,6 @@ __export(global_setup_module_exports, {
34
34
  });
35
35
  module.exports = __toCommonJS(global_setup_module_exports);
36
36
 
37
- // src/public/global-setup.ts
38
- var path8 = __toESM(require("path"));
39
-
40
37
  // src/internal/support/errors.ts
41
38
  function errorMessage(error) {
42
39
  if (error instanceof Error) return error.message;
@@ -227,6 +224,11 @@ function readBool(val) {
227
224
  if (val === void 0) return void 0;
228
225
  return ["true", "1", "yes", "on"].includes(val.trim().toLowerCase());
229
226
  }
227
+ function readNumber(val) {
228
+ const trimmed = val.trim();
229
+ const number = Number(trimmed);
230
+ return trimmed !== "" && Number.isFinite(number) && number >= 0 ? number : void 0;
231
+ }
230
232
  var ENV_FALLBACK_SPECS = [
231
233
  { option: "serverUrl", env: PIWI_ENV_KEYS.serverUrl, kind: "string" },
232
234
  { option: "projectName", env: PIWI_ENV_KEYS.projectName, kind: "string" },
@@ -272,16 +274,22 @@ function desktopAppMode(option, envValue) {
272
274
  var desktopDiscovered = false;
273
275
  var desktopReplacedServerUrl = null;
274
276
  var dotEnvUse = null;
277
+ var ignoredEnv = [];
275
278
  function resolveOptions(raw, configDir) {
276
279
  const env = process.env;
277
280
  const mergedRaw = { ...raw };
281
+ ignoredEnv = [];
278
282
  for (const spec of ENV_FALLBACK_SPECS) {
279
283
  if (mergedRaw[spec.option] !== void 0) continue;
280
284
  const value = env[spec.env];
281
285
  if (spec.kind === "bool") {
282
286
  if (value !== void 0) mergedRaw[spec.option] = readBool(value);
287
+ } else if (value && spec.kind === "number") {
288
+ const number = readNumber(value);
289
+ if (number === void 0) ignoredEnv.push({ name: spec.env, value, fallback: DEFAULTS[spec.option] });
290
+ else mergedRaw[spec.option] = number;
283
291
  } else if (value) {
284
- mergedRaw[spec.option] = spec.kind === "number" ? Number(value) : value;
292
+ mergedRaw[spec.option] = value;
285
293
  }
286
294
  }
287
295
  dotEnvUse = null;
@@ -369,15 +377,6 @@ var Logger = class {
369
377
  };
370
378
 
371
379
  // src/internal/transport/http-client.ts
372
- function parseErrorMessage(text) {
373
- try {
374
- const parsed = JSON.parse(text);
375
- const message = parsed?.message;
376
- return typeof message === "string" ? message : void 0;
377
- } catch {
378
- return void 0;
379
- }
380
- }
381
380
  var HttpError = class extends Error {
382
381
  constructor(status, message = `Request failed with status ${status}`) {
383
382
  super(message);
@@ -385,19 +384,62 @@ var HttpError = class extends Error {
385
384
  this.name = "HttpError";
386
385
  }
387
386
  };
387
+ var FAILURE_DETAIL_MAX = 500;
388
+ function failureDetail(res) {
389
+ let text = null;
390
+ try {
391
+ const body = JSON.parse(res.text);
392
+ text = typeof body?.message === "string" ? body.message : body?.statusMessage;
393
+ } catch {
394
+ if (/^text\/plain\b/i.test(res.headers["content-type"] ?? "")) text = res.text;
395
+ }
396
+ if (typeof text !== "string") return null;
397
+ const line = text.replace(/[\p{Cc}\s]+/gu, " ").trim();
398
+ if (!line) return null;
399
+ return line.length > FAILURE_DETAIL_MAX ? `${line.slice(0, FAILURE_DETAIL_MAX - 1)}\u2026` : line;
400
+ }
401
+ function failedRequest(res) {
402
+ const detail = failureDetail(res);
403
+ return new HttpError(res.status, `Request failed with status ${res.status}${detail ? `: ${detail}` : ""}`);
404
+ }
405
+ function parseAnswer(pathname, res) {
406
+ try {
407
+ return JSON.parse(res.text);
408
+ } catch {
409
+ const contentType = res.headers["content-type"] || "no content type";
410
+ throw new Error(
411
+ `The answer to ${pathname} is not JSON (${contentType}): check that serverUrl is the dashboard's address and that no sign-in page or proxy answers in its place.`
412
+ );
413
+ }
414
+ }
415
+ function serverUrlProblem(serverUrl) {
416
+ let url;
417
+ try {
418
+ url = new import_node_url.URL(serverUrl);
419
+ } catch {
420
+ return `serverUrl "${serverUrl}" is not a URL: give the dashboard's whole address, such as https://piwi.example.com.`;
421
+ }
422
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
423
+ return `serverUrl "${serverUrl}" is not an http:// or https:// URL: give the dashboard's whole address, such as https://piwi.example.com.`;
424
+ }
425
+ return null;
426
+ }
427
+ function abortError(signal) {
428
+ return signal.reason instanceof Error ? signal.reason : new Error("The request was cancelled");
429
+ }
388
430
  var HttpClient = class {
389
431
  /**
390
432
  * @param serverUrl Base URL of the Piwi Dashboard server (e.g. `http://localhost:3000`).
391
433
  * @param logger Prefixed logger for verbose diagnostics.
392
434
  * @param timeout Socket inactivity timeout in ms (default 30s), so a hung
393
435
  * server fails fast rather than stalling the reporter.
394
- * @param uploadTimeout Socket inactivity timeout of a multipart upload in ms
395
- * (default 10 min): the dashboard answers one only once it
396
- * has stored every report and trace in it.
436
+ * @param uploadTimeout Socket inactivity timeout of a multipart upload, or of
437
+ * a run's results sent as JSON, in ms (default 10 min): the
438
+ * dashboard answers one only once it has stored all of it.
397
439
  */
398
- constructor(serverUrl, logger = new Logger(), timeout = 3e4, uploadTimeout = 10 * 60 * 1e3) {
440
+ constructor(serverUrl, logger2 = new Logger(), timeout = 3e4, uploadTimeout = 10 * 60 * 1e3) {
399
441
  this.serverUrl = serverUrl;
400
- this.logger = logger;
442
+ this.logger = logger2;
401
443
  this.timeout = timeout;
402
444
  this.uploadTimeout = uploadTimeout;
403
445
  /** Requests in flight, so `close` can abort them. */
@@ -502,28 +544,32 @@ var HttpClient = class {
502
544
  return null;
503
545
  }
504
546
  }
505
- /** Send a JSON POST request. `auth` can be an API key (prefix `pd_`) or a session cookie string. */
506
- async postJSON(pathname, payload, auth) {
547
+ /**
548
+ * Send a JSON POST request. `auth` can be an API key (prefix `pd_`) or a session cookie string. Resolves to the
549
+ * answer's JSON; an answer that is not JSON fails, and `signal` ends the request. With `upload`, the answer may come
550
+ * as late as a multipart upload's: the body is a run's results, which the dashboard stores before it answers.
551
+ * `headers` go with the request beside its own.
552
+ */
553
+ async postJSON(pathname, payload, auth, signal, { upload = false, headers = {} } = {}) {
507
554
  const body = JSON.stringify(payload);
508
555
  const res = await this.request("POST", pathname, {
509
556
  headers: {
557
+ ...headers,
510
558
  "Content-Type": "application/json",
511
559
  "Content-Length": Buffer.byteLength(body)
512
560
  },
513
561
  body,
514
- auth
562
+ auth,
563
+ signal,
564
+ ...upload && { timeout: this.uploadTimeout }
515
565
  });
516
566
  if (res.status < 200 || res.status >= 300) {
517
567
  this.logger.debugError(`Response: ${res.text}`);
518
- throw new HttpError(res.status);
519
- }
520
- try {
521
- return JSON.parse(res.text);
522
- } catch {
523
- return {};
568
+ throw failedRequest(res);
524
569
  }
570
+ return parseAnswer(pathname, res);
525
571
  }
526
- /** Send a JSON PUT request. Used for the declared-surface manifest upload. */
572
+ /** Send a JSON PUT request. Used for the declared-surface manifest upload. An answer that is not JSON fails. */
527
573
  async putJSON(pathname, payload, auth) {
528
574
  const body = JSON.stringify(payload);
529
575
  const res = await this.request("PUT", pathname, {
@@ -536,39 +582,43 @@ var HttpClient = class {
536
582
  });
537
583
  if (res.status < 200 || res.status >= 300) {
538
584
  this.logger.debugError(`Response: ${res.text}`);
539
- throw new HttpError(res.status);
540
- }
541
- try {
542
- return JSON.parse(res.text);
543
- } catch {
544
- return {};
585
+ throw failedRequest(res);
545
586
  }
587
+ return parseAnswer(pathname, res);
546
588
  }
547
- /** Send a multipart form-data POST request. Used for report and trace uploads. */
548
- async postFormData(pathname, form, auth) {
589
+ /**
590
+ * Send a multipart form-data POST request. Used for report and trace uploads. An answer that is not JSON fails, and
591
+ * `signal` ends the upload.
592
+ */
593
+ async postFormData(pathname, form, auth, signal) {
549
594
  const headers = form.getHeaders();
550
- const res = await this.request("POST", pathname, { headers, form, auth, timeout: this.uploadTimeout });
595
+ const res = await this.request("POST", pathname, { headers, form, auth, timeout: this.uploadTimeout, signal });
551
596
  if (res.status < 200 || res.status >= 300) {
552
597
  this.logger.debugError(`Response: ${res.text}`);
553
- const detail = parseErrorMessage(res.text);
554
- throw new HttpError(
555
- res.status,
556
- detail ? `Request failed with status ${res.status}: ${detail}` : `Request failed with status ${res.status}`
557
- );
558
- }
559
- try {
560
- return JSON.parse(res.text);
561
- } catch {
562
- return {};
598
+ throw failedRequest(res);
563
599
  }
600
+ return parseAnswer(pathname, res);
564
601
  }
565
- /** Unified request core: transport, headers, auth, response accumulation, timeout. */
602
+ /**
603
+ * Unified request core: transport, headers, auth, response accumulation, timeout. Nothing is sent to a `serverUrl`
604
+ * that is not an `http://` or `https://` URL.
605
+ */
566
606
  request(method, pathname, opts) {
567
- return new Promise((resolve3, reject) => {
607
+ return new Promise((resolve4, reject) => {
568
608
  if (this.closedReason !== null) {
569
609
  reject(new Error(this.closedReason));
570
610
  return;
571
611
  }
612
+ const problem = serverUrlProblem(this.serverUrl);
613
+ if (problem) {
614
+ reject(new Error(problem));
615
+ return;
616
+ }
617
+ const signal = opts.signal;
618
+ if (signal?.aborted) {
619
+ reject(abortError(signal));
620
+ return;
621
+ }
572
622
  const url = new import_node_url.URL(pathname, this.serverUrl);
573
623
  const transport = url.protocol === "https:" ? https : http;
574
624
  const headers = { ...opts.headers };
@@ -582,12 +632,16 @@ var HttpClient = class {
582
632
  headers
583
633
  },
584
634
  (res) => {
585
- let data = "";
635
+ const chunks = [];
586
636
  res.on("data", (chunk) => {
587
- data += chunk;
637
+ chunks.push(chunk);
588
638
  });
589
639
  res.on("end", () => {
590
- resolve3({ status: res.statusCode ?? 0, text: data, headers: res.headers });
640
+ resolve4({
641
+ status: res.statusCode ?? 0,
642
+ text: Buffer.concat(chunks).toString("utf8"),
643
+ headers: res.headers
644
+ });
591
645
  });
592
646
  res.on("error", reject);
593
647
  res.on("close", () => {
@@ -598,7 +652,12 @@ var HttpClient = class {
598
652
  }
599
653
  );
600
654
  this.inFlight.add(req);
601
- req.on("close", () => this.inFlight.delete(req));
655
+ const onAbort = () => req.destroy(abortError(signal));
656
+ signal?.addEventListener("abort", onAbort, { once: true });
657
+ req.on("close", () => {
658
+ this.inFlight.delete(req);
659
+ signal?.removeEventListener("abort", onAbort);
660
+ });
602
661
  req.on("error", reject);
603
662
  const timeout = opts.timeout ?? this.timeout;
604
663
  req.setTimeout(timeout, () => {
@@ -652,6 +711,7 @@ function resolveShardInfo(config, env = process.env) {
652
711
 
653
712
  // src/internal/collect/metadata-collector.ts
654
713
  var import_node_child_process = require("child_process");
714
+ var import_node_util = require("util");
655
715
 
656
716
  // src/internal/support/test-paths.ts
657
717
  var path3 = __toESM(require("path"));
@@ -730,21 +790,38 @@ var SECRET_FIELD_SELECTOR = [
730
790
  `textarea[autocomplete~="${token}" i]`
731
791
  ])
732
792
  ].join(", ");
733
- var SECRET_SHAPES = [
734
- /\beyJ[\w-]{5,}\.[\w-]{5,}\.[\w-]*/g,
735
- /\bBearer(?:\s+|%20)[\w.~+/-]{8,}=*/gi,
736
- /\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{8,}/g,
737
- /\bwhsec_[A-Za-z0-9]{20,}/g,
738
- /\bsk-(?=[\w-]{0,200}\d)(?=[\w-]{0,200}[A-Z])[\w-]{32,}/g,
739
- /\bglpat-[\w-]{20,}/g,
740
- /\bnpm_[A-Za-z0-9]{36}\b/g,
741
- /\bSK[0-9a-f]{32}\b/g,
742
- /\bAKIA[0-9A-Z]{16}\b/g,
743
- /\bAIza[\w-]{30,}/g,
744
- /\bgh[opsu]_[A-Za-z0-9]{20,}/g,
745
- /\bgithub_pat_\w{20,}/g,
746
- /\bxox[abprs]-[\w-]{8,}/g
793
+ var SHAPES = [
794
+ { re: /\beyJ[\w-]{5,}\.[\w-]{5,}\.[\w-]*/g, starts: ["eyJ"] },
795
+ { re: /\bBearer(?:\s+|%20)[\w.~+/-]{8,}=*/gi, starts: ["Bearer"] },
796
+ {
797
+ re: /\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{8,}/g,
798
+ starts: ["sk_live_", "sk_test_", "rk_live_", "rk_test_"]
799
+ },
800
+ { re: /\bwhsec_[A-Za-z0-9]{20,}/g, starts: ["whsec_"] },
801
+ { re: /\bsk-(?=[\w-]{0,200}\d)(?=[\w-]{0,200}[A-Z])[\w-]{32,}/g, starts: ["sk-"] },
802
+ { re: /\bglpat-[\w-]{20,}/g, starts: ["glpat-"] },
803
+ { re: /\bnpm_[A-Za-z0-9]{36}\b/g, starts: ["npm_"] },
804
+ { re: /\bSK[0-9a-f]{32}\b/g, starts: ["SK"] },
805
+ { re: /\bAKIA[0-9A-Z]{16}\b/g, starts: ["AKIA"] },
806
+ { re: /\bAIza[\w-]{30,}/g, starts: ["AIza"] },
807
+ { re: /\bgh[opsu]_[A-Za-z0-9]{20,}/g, starts: ["gho_", "ghp_", "ghs_", "ghu_"] },
808
+ { re: /\bgithub_pat_\w{20,}/g, starts: ["github_pat_"] },
809
+ { re: /\bxox[abprs]-[\w-]{8,}/g, starts: ["xoxa-", "xoxb-", "xoxp-", "xoxr-", "xoxs-"] },
810
+ // Piwi's: an API key or the desktop app's token, an extension's device code, an MCP client's secret, authorization
811
+ // code, access and refresh tokens, a share link's and an assistant turn's token; a live view's key.
812
+ {
813
+ re: /\b(?:pd[acor]?|mcps|psl|pwt)_[0-9a-f]{32,}/g,
814
+ starts: ["pd_", "pda_", "pdc_", "pdo_", "pdr_", "mcps_", "psl_", "pwt_"]
815
+ },
816
+ { re: /\bpdl_[\w-]{40,}/g, starts: ["pdl_"] }
747
817
  ];
818
+ var SECRET_SHAPES = SHAPES.map((shape) => shape.re);
819
+ var SECRET_SHAPE_STARTS = SHAPES.flatMap(
820
+ ({ re, starts }) => starts.map((start) => ({ start, anyCase: re.flags.includes("i") }))
821
+ );
822
+ var COLORED_SHAPES = SECRET_SHAPES.map(
823
+ (re) => new RegExp(`(\\u001b\\[[\\d;]*m)${re.source.replace(/^\\b/, "")}`, re.flags)
824
+ );
748
825
  var WHOLE_SHAPES = SECRET_SHAPES.map(
749
826
  (re) => new RegExp(`^(?:${re.source})$`, re.flags.replace("g", ""))
750
827
  );
@@ -760,36 +837,63 @@ function isLiveViewKey(value) {
760
837
  }
761
838
 
762
839
  // src/internal/support/setup-file.ts
763
- var path4 = __toESM(require("path"));
764
- var os3 = __toESM(require("os"));
840
+ var path5 = __toESM(require("path"));
841
+ var fs4 = __toESM(require("fs"));
842
+
843
+ // src/internal/support/private-file.ts
844
+ var crypto2 = __toESM(require("crypto"));
765
845
  var fs3 = __toESM(require("fs"));
766
- function getSetupFilePath(projectName) {
767
- return path4.join(os3.tmpdir(), `piwi-dashboard-setup-${hashForProject(projectName)}.json`);
846
+ var os3 = __toESM(require("os"));
847
+ var path4 = __toESM(require("path"));
848
+ function privateTempDir() {
849
+ if (process.platform !== "win32") return os3.tmpdir();
850
+ const dir = path4.join(process.env.LOCALAPPDATA || path4.join(os3.homedir(), "AppData", "Local"), "piwi", "tmp");
851
+ try {
852
+ fs3.mkdirSync(dir, { recursive: true });
853
+ } catch {
854
+ }
855
+ return dir;
856
+ }
857
+ var NO_FOLLOW = fs3.constants.O_NOFOLLOW ?? 0;
858
+ var NO_WAIT = fs3.constants.O_NONBLOCK ?? 0;
859
+ function writePrivateFile(file, text) {
860
+ const temp = `${file}.${process.pid}.${crypto2.randomBytes(6).toString("hex")}.tmp`;
861
+ try {
862
+ fs3.writeFileSync(temp, text, { encoding: "utf8", flag: "wx", mode: 384 });
863
+ fs3.renameSync(temp, file);
864
+ } catch (error) {
865
+ fs3.rmSync(temp, { force: true });
866
+ throw error;
867
+ }
868
+ }
869
+
870
+ // src/internal/support/setup-file.ts
871
+ var logger = new Logger();
872
+ function getSetupFilePath(projectName, pid = process.pid) {
873
+ return path5.join(privateTempDir(), `piwi-dashboard-setup-${hashForProject(projectName)}-${pid}.json`);
768
874
  }
769
875
  function writeSetupInfo(info) {
770
- const setupFile = getSetupFilePath(info.projectName);
771
- fs3.writeFileSync(setupFile, JSON.stringify(info), { mode: 384 });
876
+ writePrivateFile(getSetupFilePath(info.projectName), JSON.stringify(info));
772
877
  }
773
878
 
774
879
  // src/internal/support/aria-sampling.ts
775
- var path5 = __toESM(require("path"));
776
- var os4 = __toESM(require("os"));
777
- var fs4 = __toESM(require("fs"));
880
+ var path6 = __toESM(require("path"));
881
+ var fs5 = __toESM(require("fs"));
778
882
  function ariaSampleIdentity(filePath, title) {
779
883
  return `${filePath}\0${title}`;
780
884
  }
781
885
  function getAriaSampleFilePath(projectName) {
782
- return path5.join(os4.tmpdir(), `piwi-dashboard-aria-sample-${hashForProject(projectName)}.json`);
886
+ return path6.join(privateTempDir(), `piwi-dashboard-aria-sample-${hashForProject(projectName)}.json`);
783
887
  }
784
888
  function writeAriaSampleFile(projectName, identities) {
785
889
  try {
786
- fs4.writeFileSync(getAriaSampleFilePath(projectName), JSON.stringify({ projectName, identities }));
890
+ writePrivateFile(getAriaSampleFilePath(projectName), JSON.stringify({ projectName, identities }));
787
891
  } catch {
788
892
  }
789
893
  }
790
894
  function clearAriaSampleFile(projectName) {
791
895
  try {
792
- fs4.rmSync(getAriaSampleFilePath(projectName), { force: true });
896
+ fs5.rmSync(getAriaSampleFilePath(projectName), { force: true });
793
897
  } catch {
794
898
  }
795
899
  }
@@ -955,7 +1059,7 @@ async function checkBaseUrl(target, options = {}) {
955
1059
  } else {
956
1060
  reason = outcome.error;
957
1061
  }
958
- if (attempt < attempts) await new Promise((resolve3) => setTimeout(resolve3, delayMs));
1062
+ if (attempt < attempts) await new Promise((resolve4) => setTimeout(resolve4, delayMs));
959
1063
  }
960
1064
  return `${reason} (${attempts} ${attempts === 1 ? "attempt" : "attempts"})`;
961
1065
  }
@@ -986,8 +1090,8 @@ async function checkBaseUrls(config, options = {}) {
986
1090
  }
987
1091
 
988
1092
  // src/internal/manifest/collect.ts
989
- var fs5 = __toESM(require("fs"));
990
- var path6 = __toESM(require("path"));
1093
+ var fs6 = __toESM(require("fs"));
1094
+ var path7 = __toESM(require("path"));
991
1095
 
992
1096
  // src/internal/transport/backend-request.ts
993
1097
  var http2 = __toESM(require("http"));
@@ -1021,10 +1125,10 @@ function hasInstrumentationHeader(headers) {
1021
1125
  return INSTRUMENTATION_HEADERS.some((h) => get(h) != null && get(h) !== "");
1022
1126
  }
1023
1127
  function readCommittedManifest(configDir) {
1024
- const file = path6.join(configDir, COMMITTED_MANIFEST_FILE);
1128
+ const file = path7.join(configDir, COMMITTED_MANIFEST_FILE);
1025
1129
  try {
1026
- if (!fs5.existsSync(file)) return null;
1027
- return parseManifestJson(fs5.readFileSync(file, "utf8"));
1130
+ if (!fs6.existsSync(file)) return null;
1131
+ return parseManifestJson(fs6.readFileSync(file, "utf8"));
1028
1132
  } catch {
1029
1133
  return null;
1030
1134
  }
@@ -1034,8 +1138,8 @@ var MAX_MANIFEST_BYTES = 4 * 1024 * 1024;
1034
1138
  function instrumentationManifestUrls(baseUrl) {
1035
1139
  const base = new URL(baseUrl);
1036
1140
  const root = new URL(INSTRUMENTATION_MANIFEST_PATH, base).toString();
1037
- const path9 = base.pathname.replace(/\/+$/, "");
1038
- return path9 ? [new URL(`${path9}${INSTRUMENTATION_MANIFEST_PATH}`, base).toString(), root] : [root];
1141
+ const path11 = base.pathname.replace(/\/+$/, "");
1142
+ return path11 ? [new URL(`${path11}${INSTRUMENTATION_MANIFEST_PATH}`, base).toString(), root] : [root];
1039
1143
  }
1040
1144
  async function fetchInstrumentationManifest(baseUrl, fetchImpl = fetch) {
1041
1145
  try {
@@ -1062,14 +1166,14 @@ async function lookupProjectId(httpClient, auth, projectName) {
1062
1166
  (p) => p.name.toLowerCase() === projectName.toLowerCase()
1063
1167
  )?.id;
1064
1168
  }
1065
- async function uploadManifest(httpClient, auth, projectId, upload, logger) {
1066
- await httpClient.putJSON(`/api/projects/${projectId}/surface/manifest`, upload, auth).catch((e) => logger.debug(`Manifest upload (${upload.source}) skipped: ${errorMessage(e)}`));
1169
+ async function uploadManifest(httpClient, auth, projectId, upload, logger2) {
1170
+ await httpClient.putJSON(`/api/projects/${projectId}/surface/manifest`, upload, auth).catch((e) => logger2.debug(`Manifest upload (${upload.source}) skipped: ${errorMessage(e)}`));
1067
1171
  }
1068
1172
 
1069
1173
  // src/internal/collect/source-checksums.ts
1070
- var crypto2 = __toESM(require("crypto"));
1071
- var fs6 = __toESM(require("fs"));
1072
- var path7 = __toESM(require("path"));
1174
+ var crypto3 = __toESM(require("crypto"));
1175
+ var fs7 = __toESM(require("fs"));
1176
+ var path8 = __toESM(require("path"));
1073
1177
 
1074
1178
  // src/internal/collect/server-coverage.ts
1075
1179
  var DEFAULT_COLLECTOR_LIMITS = {
@@ -1088,39 +1192,67 @@ function baseUrlsFromConfig(config) {
1088
1192
  return [...new Set(urls.filter((url) => typeof url === "string" && url !== ""))];
1089
1193
  }
1090
1194
 
1195
+ // src/internal/support/reporter-entry.ts
1196
+ var path9 = __toESM(require("path"));
1197
+ var import_node_module = require("module");
1198
+ var PIWI_REPORTER_MODULE = "@piwitests/reporter";
1199
+ var OWN_ENTRY = path9.resolve(__dirname, "index.js");
1200
+ function resolveFrom(id, dir) {
1201
+ try {
1202
+ return (0, import_node_module.createRequire)(path9.join(dir, "noop.js")).resolve(id);
1203
+ } catch {
1204
+ return null;
1205
+ }
1206
+ }
1207
+ function isPiwiReporterModule(id, dir) {
1208
+ if (id === PIWI_REPORTER_MODULE) return true;
1209
+ const file = resolveFrom(id, dir);
1210
+ if (!file) return false;
1211
+ return file === OWN_ENTRY || file === resolveFrom(PIWI_REPORTER_MODULE, dir);
1212
+ }
1213
+
1214
+ // src/internal/support/reporter-version.ts
1215
+ var fs8 = __toESM(require("fs"));
1216
+ var path10 = __toESM(require("path"));
1217
+ var cachedVersion = null;
1218
+ var CANDIDATE_OFFSETS = ["..", "../../.."];
1219
+ function findOwnPackageJson(fromDir) {
1220
+ for (const offset of CANDIDATE_OFFSETS) {
1221
+ try {
1222
+ const pkgPath = path10.resolve(fromDir, offset, "package.json");
1223
+ const pkg = JSON.parse(fs8.readFileSync(pkgPath, "utf-8"));
1224
+ const { name, version } = pkg;
1225
+ if (name === "@piwitests/reporter" && typeof version === "string")
1226
+ return { version, root: path10.dirname(pkgPath) };
1227
+ } catch {
1228
+ }
1229
+ }
1230
+ return void 0;
1231
+ }
1232
+ function getReporterVersion() {
1233
+ if (cachedVersion) return cachedVersion;
1234
+ cachedVersion = findOwnPackageJson(__dirname)?.version ?? "unknown";
1235
+ return cachedVersion;
1236
+ }
1237
+
1091
1238
  // src/public/global-setup.ts
1092
1239
  function createGlobalSetup(options, userSetup) {
1093
1240
  return async function globalSetupFn(config) {
1094
- const piwiReporterPath = path8.resolve(__dirname, "./index.js");
1095
- let inlineReporterOptions = {};
1096
- if (Array.isArray(config?.reporter)) {
1097
- for (const r of config.reporter) {
1098
- if (!Array.isArray(r) || typeof r[0] !== "string") continue;
1099
- const isPiwi = r[0].toLowerCase().includes("piwi") || (() => {
1100
- try {
1101
- return path8.resolve(require.resolve(r[0])) === piwiReporterPath;
1102
- } catch {
1103
- return false;
1104
- }
1105
- })();
1106
- if (isPiwi && r[1] && typeof r[1] === "object") {
1107
- inlineReporterOptions = r[1];
1108
- break;
1109
- }
1110
- }
1111
- }
1112
- const opts = resolveOptions(
1113
- { ...inlineReporterOptions, ...options },
1114
- configDirFromConfig(config)
1115
- );
1116
- const logger = new Logger(opts.verbose ?? false);
1241
+ const configDir = configDirFromConfig(config);
1242
+ const piwiReporter = Array.isArray(config?.reporter) ? config.reporter.find(
1243
+ (r) => Array.isArray(r) && typeof r[0] === "string" && isPiwiReporterModule(r[0], configDir)
1244
+ ) : void 0;
1245
+ const inline = piwiReporter?.[1];
1246
+ const inlineReporterOptions = inline && typeof inline === "object" ? inline : {};
1247
+ const opts = resolveOptions({ ...inlineReporterOptions, ...options }, configDir);
1248
+ const logger2 = new Logger(opts.verbose ?? false);
1117
1249
  if (isUiMode()) {
1118
- logger.debug("UI mode detected \u2014 skipping run registration.");
1250
+ logger2.debug("UI mode detected \u2014 skipping run registration.");
1119
1251
  if (userSetup) return userSetup(config);
1120
1252
  return;
1121
1253
  }
1122
1254
  if (isListMode()) {
1123
- logger.debug("List mode detected \u2014 skipping run registration.");
1255
+ logger2.debug("List mode detected \u2014 skipping run registration.");
1124
1256
  if (userSetup) return userSetup(config);
1125
1257
  return;
1126
1258
  }
@@ -1129,67 +1261,28 @@ function createGlobalSetup(options, userSetup) {
1129
1261
  for (const target of checked) {
1130
1262
  const note = remoteBrowserNote(target);
1131
1263
  if (note) {
1132
- logger.info(
1264
+ logger2.info(
1133
1265
  `Base URL answered: ${target.url}. ${note} A navigation failure from that browser can mean its machine cannot reach the app, not that the app is down.`
1134
1266
  );
1135
1267
  } else {
1136
- logger.debug(`Base URL answered: ${target.url}`);
1268
+ logger2.debug(`Base URL answered: ${target.url}`);
1137
1269
  }
1138
1270
  }
1139
1271
  }
1140
1272
  if (opts.enabled === false || !opts.serverUrl) {
1141
- logger.info("Not enabled \u2014 set PIWI_DASHBOARD_URL or serverUrl to enable.");
1273
+ logger2.info("Not enabled \u2014 set PIWI_DASHBOARD_URL or serverUrl to enable.");
1142
1274
  if (userSetup) return userSetup(config);
1143
1275
  return;
1144
1276
  }
1145
- const hasPiwi = Object.keys(inlineReporterOptions).length > 0 || Array.isArray(config?.reporter) && config.reporter.some((r) => {
1146
- if (!Array.isArray(r) || typeof r[0] !== "string") return false;
1147
- if (r[0].toLowerCase().includes("piwi")) return true;
1148
- try {
1149
- return path8.resolve(require.resolve(r[0])) === piwiReporterPath;
1150
- } catch {
1151
- return false;
1152
- }
1153
- });
1154
- if (!hasPiwi) {
1155
- logger.debug("Not reporting \u2014 Piwi is not in the Playwright reporters list.");
1277
+ if (!piwiReporter) {
1278
+ logger2.debug("Not reporting \u2014 Piwi is not in the Playwright reporters list.");
1156
1279
  if (userSetup) return userSetup(config);
1157
1280
  return;
1158
1281
  }
1159
- const httpClient = new HttpClient(opts.serverUrl, logger);
1282
+ const httpClient = new HttpClient(opts.serverUrl, logger2);
1160
1283
  try {
1161
1284
  const auth = await httpClient.resolveAuth(opts);
1162
- const shard = resolveShardInfo(config);
1163
- const response = await httpClient.postJSON(
1164
- "/api/test-runs/setup",
1165
- {
1166
- projectName: opts.projectName,
1167
- projectDescription: opts.projectDescription,
1168
- environment: opts.environment || null,
1169
- label: opts.label || null,
1170
- keep: opts.keep === true,
1171
- startTime: (/* @__PURE__ */ new Date()).toISOString(),
1172
- instanceId: computeInstanceId(opts.projectName, resolveRunLabel(opts.runLabel, shard !== null)),
1173
- shardIndex: shard?.current,
1174
- shardTotal: shard?.total,
1175
- // A key for the run's live view: the instance hands one out only for a project that turned it on, and the
1176
- // desktop app none. A CI run's workers stream with it at once; a run outside CI sends nothing with it until a
1177
- // person shares the run.
1178
- liveView: true
1179
- },
1180
- auth
1181
- );
1182
- if (response?.runId && response?.setupToken) {
1183
- const liveViewKey = response.liveView?.key;
1184
- writeSetupInfo({
1185
- runId: response.runId,
1186
- setupToken: response.setupToken,
1187
- projectName: opts.projectName,
1188
- ...isLiveViewKey(liveViewKey) ? { liveViewKey } : {},
1189
- ...response.liveView?.refused === "local" ? { liveViewLocal: true } : {}
1190
- });
1191
- logger.debug(`Global setup: initializing run #${response.runId}`);
1192
- }
1285
+ if (opts.streaming !== false) await registerRun(httpClient, auth, opts, config, logger2);
1193
1286
  if (opts.projectName) clearAriaSampleFile(opts.projectName);
1194
1287
  const wantsAria = opts.sampleAriaOnPass !== false && !!opts.projectName;
1195
1288
  const committedManifest = opts.uploadManifest !== false ? readCommittedManifest(configDirFromConfig(config)) : null;
@@ -1205,7 +1298,7 @@ function createGlobalSetup(options, userSetup) {
1205
1298
  if (tests) {
1206
1299
  const identities = tests.filter((t) => typeof t.filePath === "string" && typeof t.title === "string").map((t) => ariaSampleIdentity(t.filePath, t.title));
1207
1300
  writeAriaSampleFile(opts.projectName, identities);
1208
- logger.debug(`Green ARIA sampling: ${identities.length} test(s) due a sample.`);
1301
+ logger2.debug(`Green ARIA sampling: ${identities.length} test(s) due a sample.`);
1209
1302
  }
1210
1303
  }
1211
1304
  if (wantsManifest && projectId != null) {
@@ -1216,22 +1309,57 @@ function createGlobalSetup(options, userSetup) {
1216
1309
  auth,
1217
1310
  projectId,
1218
1311
  { source: "committed", branch, manifest: committedManifest },
1219
- logger
1312
+ logger2
1220
1313
  );
1221
1314
  }
1222
1315
  const declared = await Promise.all(manifestBaseUrls.map((url) => fetchInstrumentationManifest(url)));
1223
1316
  for (const manifest of declared) {
1224
1317
  if (manifest) {
1225
- await uploadManifest(httpClient, auth, projectId, { source: "instrumentation", branch, manifest }, logger);
1318
+ await uploadManifest(httpClient, auth, projectId, { source: "instrumentation", branch, manifest }, logger2);
1226
1319
  }
1227
1320
  }
1228
1321
  }
1229
1322
  } catch (error) {
1230
- logger.warn(`Could not register global setup: ${errorMessage(error)}`);
1323
+ logger2.warn(`Could not register global setup: ${errorMessage(error)}`);
1231
1324
  }
1232
1325
  if (userSetup) return userSetup(config);
1233
1326
  };
1234
1327
  }
1328
+ async function registerRun(httpClient, auth, opts, config, logger2) {
1329
+ const shard = resolveShardInfo(config);
1330
+ const response = await httpClient.postJSON(
1331
+ "/api/test-runs/setup",
1332
+ {
1333
+ projectName: opts.projectName,
1334
+ projectDescription: opts.projectDescription,
1335
+ environment: opts.environment || null,
1336
+ label: opts.label || null,
1337
+ keep: opts.keep === true,
1338
+ startTime: (/* @__PURE__ */ new Date()).toISOString(),
1339
+ instanceId: computeInstanceId(opts.projectName, resolveRunLabel(opts.runLabel, shard !== null)),
1340
+ shardIndex: shard?.current,
1341
+ shardTotal: shard?.total,
1342
+ // The dashboard reads from it whether the run's `/begin` carries its setup token in a header too.
1343
+ reporterVersion: getReporterVersion(),
1344
+ // A key for the run's live view: the instance hands one out only for a project that turned it on, and the
1345
+ // desktop app none. A CI run's workers stream with it at once; a run outside CI sends nothing with it until a
1346
+ // person shares the run.
1347
+ liveView: true
1348
+ },
1349
+ auth
1350
+ );
1351
+ if (response?.runId && response?.setupToken) {
1352
+ const liveViewKey = response.liveView?.key;
1353
+ writeSetupInfo({
1354
+ runId: response.runId,
1355
+ setupToken: response.setupToken,
1356
+ projectName: opts.projectName,
1357
+ ...isLiveViewKey(liveViewKey) ? { liveViewKey } : {},
1358
+ ...response.liveView?.refused === "local" ? { liveViewLocal: true } : {}
1359
+ });
1360
+ logger2.debug(`Global setup: initializing run #${response.runId}`);
1361
+ }
1362
+ }
1235
1363
 
1236
1364
  // src/global-setup-module.ts
1237
1365
  var global_setup_module_default = createGlobalSetup();