@piwitests/reporter 0.72.0 → 0.73.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/cli/index.js CHANGED
@@ -3988,10 +3988,10 @@ async function planRequest(url, init, apiKey, what) {
3988
3988
  }
3989
3989
  return await res.json();
3990
3990
  }
3991
- function fetchPlanSources(options, projectId, selection, playwrightVersion) {
3991
+ function fetchPlanSources(options, projectId, selection, playwrightVersion, environment) {
3992
3992
  return planRequest(
3993
3993
  `${options.serverUrl}/api/projects/${projectId}/run-plans/sources`,
3994
- { method: "POST", body: JSON.stringify({ selection, playwrightVersion }) },
3994
+ { method: "POST", body: JSON.stringify({ selection, playwrightVersion, environment }) },
3995
3995
  options.apiKey,
3996
3996
  "finding the passes to reuse"
3997
3997
  );
@@ -8399,6 +8399,8 @@ Pass reuse (experimental, run only):
8399
8399
  --reuse Skip each test whose code has not changed since it last
8400
8400
  passed (see piwi plan); "full" plans the whole suite
8401
8401
  --plan <id> Run the tests of a plan made by piwi plan
8402
+ --environment <key> The environment the run reports (env PIWI_ENVIRONMENT):
8403
+ only passes of that environment are reused
8402
8404
 
8403
8405
  Behavior:
8404
8406
  --strict Fail (exit 2) instead of falling back when unreachable
@@ -8421,7 +8423,8 @@ var VALUE_FLAGS3 = /* @__PURE__ */ new Set([
8421
8423
  "--shard",
8422
8424
  "--base",
8423
8425
  "--pkg-runner",
8424
- "--plan"
8426
+ "--plan",
8427
+ "--environment"
8425
8428
  ]);
8426
8429
  function readOption7(argv, name) {
8427
8430
  const withEquals = argv.find((arg) => arg.startsWith(`${name}=`));
@@ -8681,7 +8684,7 @@ async function runRunImpact(args, env) {
8681
8684
  console.error(`piwi run: no tests impacted by ${impact.impact.changedFiles} changed file(s) \u2014 nothing to run`);
8682
8685
  return EXIT_OK6;
8683
8686
  }
8684
- const runEnv = {
8687
+ const runEnv2 = {
8685
8688
  ...env,
8686
8689
  PIWI_SELECTION: IMPACT_KEY,
8687
8690
  PIWI_SELECTION_VERSION: "0",
@@ -8690,7 +8693,7 @@ async function runRunImpact(args, env) {
8690
8693
  ...shardEnv(args)
8691
8694
  };
8692
8695
  console.error(`piwi run: impact \u2192 ${impact.estimate.count} test(s)${lineLevelNote(impact)}`);
8693
- return spawnPlaywrightForRun(args.pkgRunner, [...impact.materialization.args, ...args.extra], runEnv);
8696
+ return spawnPlaywrightForRun(args.pkgRunner, [...impact.materialization.args, ...args.extra], runEnv2);
8694
8697
  }
8695
8698
  async function runRun(argv, env = process.env) {
8696
8699
  if (argv.includes("-h") || argv.includes("--help")) {
@@ -8734,7 +8737,7 @@ async function runRun(argv, env = process.env) {
8734
8737
  console.error(`piwi run: "${args.key}" resolved to 0 tests`);
8735
8738
  return EXIT_ERROR7;
8736
8739
  }
8737
- const runEnv = {
8740
+ const runEnv2 = {
8738
8741
  ...env,
8739
8742
  PIWI_SELECTION: resolution.key ?? args.key,
8740
8743
  PIWI_SELECTION_VERSION: String(resolution.version ?? 0),
@@ -8745,7 +8748,7 @@ async function runRun(argv, env = process.env) {
8745
8748
  console.error(
8746
8749
  `piwi run: ${args.key} \u2192 ${resolution.estimate.count} tests${resolution.materialization.format !== args.format ? ` (materialized as ${resolution.materialization.format})` : ""}`
8747
8750
  );
8748
- return spawnPlaywrightForRun(args.pkgRunner, [...resolution.materialization.args, ...args.extra], runEnv);
8751
+ return spawnPlaywrightForRun(args.pkgRunner, [...resolution.materialization.args, ...args.extra], runEnv2);
8749
8752
  }
8750
8753
 
8751
8754
  // src/cli/plan.ts
@@ -8773,6 +8776,10 @@ Connection:
8773
8776
  --api-key <key> API key (env PIWI_API_KEY, .env)
8774
8777
  --project <name|id> Project (env PIWI_PROJECT_NAME, .env)
8775
8778
 
8779
+ Run:
8780
+ --environment <key> The environment the run reports (env PIWI_ENVIRONMENT):
8781
+ only passes of that environment are reused
8782
+
8776
8783
  Behavior:
8777
8784
  --json Print the plan as JSON instead of its id
8778
8785
  -h, --help Show this help
@@ -8788,7 +8795,8 @@ var REASON_LABELS = {
8788
8795
  "open-cluster": "open failure",
8789
8796
  quarantined: "quarantined",
8790
8797
  "no-reuse-tag": "@no-reuse",
8791
- serial: "serial group"
8798
+ serial: "serial group",
8799
+ "deployed-version-unknown": "deployed version unknown"
8792
8800
  };
8793
8801
  function parsePlanArgs(argv, env, command) {
8794
8802
  const dashIndex = argv.indexOf("--");
@@ -8822,6 +8830,7 @@ function parsePlanArgs(argv, env, command) {
8822
8830
  planId: planRaw === void 0 ? null : Number(planRaw),
8823
8831
  reuse: own.includes("--reuse"),
8824
8832
  shard,
8833
+ environment: (readOption7(own, "--environment") ?? env[PIWI_ENV_KEYS.environment])?.trim() || null,
8825
8834
  strict: own.includes("--strict"),
8826
8835
  json: own.includes("--json"),
8827
8836
  pkgRunner: readOption7(own, "--pkg-runner") ?? "npx",
@@ -8870,7 +8879,7 @@ function formatPlanReasons(reasons) {
8870
8879
  }
8871
8880
  async function makePlan(args, projectId, key) {
8872
8881
  const playwrightVersion = readInstalledPlaywrightVersion(process.cwd());
8873
- const sources = await fetchPlanSources(args, projectId, key, playwrightVersion);
8882
+ const sources = await fetchPlanSources(args, projectId, key, playwrightVersion, args.environment);
8874
8883
  const untracked = (tryGit(["ls-files", "--others", "--exclude-standard", "--full-name", "--", ":/"]) ?? "").split("\n").filter(Boolean);
8875
8884
  const diffs = [];
8876
8885
  for (const { commit } of sources.commits) {
@@ -8898,6 +8907,7 @@ async function makePlan(args, projectId, key) {
8898
8907
  return createPlan(args, projectId, {
8899
8908
  selection: key,
8900
8909
  playwrightVersion,
8910
+ environment: args.environment,
8901
8911
  commit: tryGit(["rev-parse", "HEAD"]),
8902
8912
  branch: branch && branch !== "HEAD" ? branch : null,
8903
8913
  worktree: worktreeState(),
@@ -8934,6 +8944,9 @@ async function runPlanCommand(argv, env = process.env) {
8934
8944
  return EXIT_ERROR8;
8935
8945
  }
8936
8946
  }
8947
+ function runEnv(args, env) {
8948
+ return args.environment ? { ...env, [PIWI_ENV_KEYS.environment]: args.environment } : env;
8949
+ }
8937
8950
  function isPlannedRun(argv) {
8938
8951
  const dashIndex = argv.indexOf("--");
8939
8952
  const own = dashIndex === -1 ? argv : argv.slice(0, dashIndex);
@@ -8957,11 +8970,20 @@ async function runStoredPlan(args, projectId, planId, env, madeHere) {
8957
8970
  throw new Error(`plan ${planId} and this checkout must both match their commit to skip tests in another job`);
8958
8971
  }
8959
8972
  }
8973
+ const planned = plan.environment?.trim() || null;
8974
+ const named = args.environment;
8975
+ if (planned && named && planned.toLowerCase() !== named.toLowerCase()) {
8976
+ throw new Error(`plan ${planId} was made for the environment ${planned}, and this run names ${named}`);
8977
+ }
8960
8978
  const shardArgs = args.shard ? [`--shard=${args.shard.replace(/\s+/g, "")}`] : [];
8961
8979
  console.error(
8962
8980
  `piwi run: plan ${planId}${args.shard ? ` (shard ${args.shard})` : ""} \u2192 ${plan.selection.key}, skipping ${plan.counts.reused} reused test(s)`
8963
8981
  );
8964
- const planEnv = { ...env, [PIWI_PLAN_ENV]: String(planId) };
8982
+ const planEnv = {
8983
+ ...runEnv(args, env),
8984
+ ...planned && !named ? { [PIWI_ENV_KEYS.environment]: planned } : {},
8985
+ [PIWI_PLAN_ENV]: String(planId)
8986
+ };
8965
8987
  if (plan.skip.length === 0) {
8966
8988
  return spawnPlaywrightForRun(args.pkgRunner, [...plan.args, ...shardArgs, ...args.extra], planEnv);
8967
8989
  }
@@ -9025,12 +9047,12 @@ async function runPlannedRun(argv, env = process.env) {
9025
9047
  function fallBack(args, argv, env, reason) {
9026
9048
  if (args.reuse && args.key && args.key !== "full") {
9027
9049
  console.error(`piwi run: ${reason} \u2014 running "${args.key}" without reuse`);
9028
- return runRun(withoutReuse(argv), env);
9050
+ return runRun(withoutReuse(argv), runEnv(args, env));
9029
9051
  }
9030
9052
  console.error(
9031
9053
  `piwi run: ${reason} \u2014 running the full suite${args.shard ? ` (all of it, not shard ${args.shard})` : ""}`
9032
9054
  );
9033
- return spawnPlaywrightForRun(args.pkgRunner, args.extra, env);
9055
+ return spawnPlaywrightForRun(args.pkgRunner, args.extra, runEnv(args, env));
9034
9056
  }
9035
9057
 
9036
9058
  // src/cli/preflight.ts
package/dist/index.js CHANGED
@@ -538,8 +538,8 @@ function readPrivateFile(file) {
538
538
  const fd = fs3.openSync(file, fs3.constants.O_RDONLY | NO_FOLLOW | NO_WAIT);
539
539
  try {
540
540
  const stat2 = fs3.fstatSync(fd);
541
- const opened = untrustedReason(stat2);
542
- if (opened) return { untrusted: opened };
541
+ const opened2 = untrustedReason(stat2);
542
+ if (opened2) return { untrusted: opened2 };
543
543
  return { text: fs3.readFileSync(fd, "utf8"), mode: stat2.mode };
544
544
  } finally {
545
545
  fs3.closeSync(fd);
@@ -7474,10 +7474,10 @@ var StreamManager = class {
7474
7474
  next ? "The run is open on the dashboard: streaming live steps." : "Nobody is watching the run: live steps are not sent."
7475
7475
  );
7476
7476
  }
7477
- const opened = next === true && this.watched !== true;
7477
+ const opened2 = next === true && this.watched !== true;
7478
7478
  const unwatched = next === false && this.watched !== false;
7479
7479
  this.watched = next;
7480
- if (opened) this.onWatched?.();
7480
+ if (opened2) this.onWatched?.();
7481
7481
  if (unwatched && this.heartbeatTimer) {
7482
7482
  clearTimeout(this.heartbeatTimer);
7483
7483
  this.heartbeatTimer = null;
@@ -8824,6 +8824,14 @@ async function checkBaseUrls(config, options = {}) {
8824
8824
  var fs17 = __toESM(require("fs"));
8825
8825
  var path17 = __toESM(require("path"));
8826
8826
 
8827
+ // ../core/src/deployed-commit.ts
8828
+ var DEPLOYED_COMMIT = /^[0-9a-f]{7,40}$/i;
8829
+ function deployedCommitOf(raw) {
8830
+ if (typeof raw !== "string") return null;
8831
+ const value = raw.trim();
8832
+ return DEPLOYED_COMMIT.test(value) ? value.toLowerCase() : null;
8833
+ }
8834
+
8827
8835
  // src/internal/transport/backend-request.ts
8828
8836
  var http2 = __toESM(require("http"));
8829
8837
  var https2 = __toESM(require("https"));
@@ -8976,6 +8984,7 @@ function parseServerEnvironment(text2) {
8976
8984
  globalization: cutField(o.globalization),
8977
8985
  environmentName: cutField(o.environmentName),
8978
8986
  appVersion: cutField(o.appVersion),
8987
+ appCommit: deployedCommitOf(o.appCommit),
8979
8988
  hostname: cutField(o.hostname),
8980
8989
  instance: cutField(o.instance),
8981
8990
  startedAt: cutField(o.startedAt),
@@ -10302,6 +10311,13 @@ function fulfillHeaders(responseHeaders, contentType) {
10302
10311
  if (contentType) headers["content-type"] = contentType;
10303
10312
  return headers;
10304
10313
  }
10314
+ function isMainFrameRequest(page, request3) {
10315
+ try {
10316
+ return request3.frame() === page.mainFrame();
10317
+ } catch {
10318
+ return false;
10319
+ }
10320
+ }
10305
10321
  function originOf2(url) {
10306
10322
  try {
10307
10323
  const origin = new URL(url).origin;
@@ -10346,25 +10362,31 @@ async function installRouteRules(page, rules) {
10346
10362
  });
10347
10363
  return { state };
10348
10364
  }
10349
- async function installProbeInterception(page, item) {
10365
+ async function installProbeInterception(page, item, baseURL = null) {
10350
10366
  if (!isFaultAllowed(item.level ?? "client", item.fault)) {
10351
10367
  return { applied: () => false, appliedFault: () => null, serverError: () => false };
10352
10368
  }
10353
10369
  let applied = false;
10354
10370
  let appliedFault = null;
10355
10371
  let serverError = false;
10356
- let appOrigin = null;
10372
+ const appOrigins = /* @__PURE__ */ new Set();
10373
+ const baseOrigin = baseURL ? originOf2(baseURL) : null;
10374
+ if (baseOrigin) appOrigins.add(baseOrigin);
10375
+ let firstOpened = false;
10357
10376
  const probeSecret = process.env[PIWI_PROBE_ENV.secret];
10358
- page.on("framenavigated", (frame) => {
10359
- if (frame === page.mainFrame()) {
10360
- const origin = originOf2(page.url());
10361
- if (origin) appOrigin = origin;
10362
- }
10377
+ page.on("request", (request3) => {
10378
+ if (firstOpened || !request3.isNavigationRequest() || request3.redirectedFrom()) return;
10379
+ if (!isMainFrameRequest(page, request3)) return;
10380
+ const origin = originOf2(request3.url());
10381
+ if (!origin) return;
10382
+ firstOpened = true;
10383
+ appOrigins.add(origin);
10363
10384
  });
10364
10385
  const handle = async (route, startedAt) => {
10365
10386
  const request3 = route.request();
10366
10387
  if (item.level === "server") {
10367
- if (!probeSecret || appOrigin !== null && originOf2(request3.url()) !== appOrigin) {
10388
+ const origin = originOf2(request3.url());
10389
+ if (!probeSecret || origin === null || !appOrigins.has(origin)) {
10368
10390
  await route.fallback();
10369
10391
  return;
10370
10392
  }
@@ -10372,7 +10394,8 @@ async function installProbeInterception(page, item) {
10372
10394
  if (item.dependency) spec.dependency = item.dependency;
10373
10395
  try {
10374
10396
  const response = await route.fetch({
10375
- headers: { ...request3.headers(), "x-piwi-probe": buildProbeHeader(probeSecret, spec) }
10397
+ headers: { ...request3.headers(), "x-piwi-probe": buildProbeHeader(probeSecret, spec) },
10398
+ maxRedirects: 0
10376
10399
  });
10377
10400
  const trace = parseProbeTrace(response.headers()["x-piwi-trace"]);
10378
10401
  appliedFault = trace.appliedFault;
@@ -12391,6 +12414,7 @@ function captureCallerLocation(stack = new Error().stack ?? "") {
12391
12414
  }
12392
12415
 
12393
12416
  // src/internal/capture/quiet-capture.ts
12417
+ var import_node_async_hooks = require("async_hooks");
12394
12418
  var import_node_module2 = require("module");
12395
12419
  var path23 = __toESM(require("path"));
12396
12420
  var BOXED_PREFIX_EXPORTS = [
@@ -12451,6 +12475,7 @@ function boxCaptureFrames(extraPrefixes = []) {
12451
12475
  function callMethod(target, prop, args) {
12452
12476
  return target[prop](...args);
12453
12477
  }
12478
+ var outsideCalls = import_node_async_hooks.AsyncResource.bind((run) => run());
12454
12479
  function internalCall(owner, run) {
12455
12480
  const wrap = owner?._wrapApiCall;
12456
12481
  if (typeof wrap !== "function") return run();
@@ -12904,16 +12929,16 @@ var PageReader = class {
12904
12929
  let session = this.sessions.get(page);
12905
12930
  if (!session) {
12906
12931
  session = internalCall(page, async () => {
12907
- const opened2 = await page.context().newCDPSession(page);
12908
- await opened2.send("Performance.enable", { timeDomain: "threadTicks" });
12909
- return opened2;
12932
+ const opened3 = await page.context().newCDPSession(page);
12933
+ await opened3.send("Performance.enable", { timeDomain: "threadTicks" });
12934
+ return opened3;
12910
12935
  }).catch(() => null);
12911
12936
  this.sessions.set(page, session);
12912
12937
  }
12913
- const opened = await session;
12914
- if (!opened) return null;
12938
+ const opened2 = await session;
12939
+ if (!opened2) return null;
12915
12940
  try {
12916
- const result = await internalCall(page, () => opened.send("Performance.getMetrics"));
12941
+ const result = await internalCall(page, () => opened2.send("Performance.getMetrics"));
12917
12942
  const values = new Map((result.metrics ?? []).map((metric) => [metric.name, metric.value]));
12918
12943
  const main = {
12919
12944
  cpuMs: Math.round((values.get("TaskDuration") ?? 0) * 1e3),
@@ -12921,7 +12946,7 @@ var PageReader = class {
12921
12946
  nodes: values.get("Nodes") ?? 0,
12922
12947
  listeners: values.get("JSEventListeners") ?? 0
12923
12948
  };
12924
- const elements = await this.countElements(page, opened);
12949
+ const elements = await this.countElements(page, opened2);
12925
12950
  if (elements !== null) main.elements = elements;
12926
12951
  return main;
12927
12952
  } catch {
@@ -12967,6 +12992,18 @@ var PERSISTENT_CALL = /launchPersistentContext$/;
12967
12992
  var CLOSE_TIMEOUT_MS = 5e3;
12968
12993
  var PAGE_READ_CAP = 50;
12969
12994
  var PAGE_READ_TIMEOUT_MS = 1e3;
12995
+ var callPageListeners = /* @__PURE__ */ new Set();
12996
+ function pageOfCall(object) {
12997
+ for (let owner = object; owner; owner = owner._parent) {
12998
+ if (owner._type === "Page") return owner;
12999
+ if (owner._type === "Frame" && owner._page) return owner._page;
13000
+ }
13001
+ return null;
13002
+ }
13003
+ function onTestCallPage(listener) {
13004
+ callPageListeners.add(listener);
13005
+ return () => callPageListeners.delete(listener);
13006
+ }
12970
13007
  var HOOK_PHASES = /* @__PURE__ */ new Set(["beforeAll", "afterAll", "beforeEach", "afterEach"]);
12971
13008
  var KIND_ORDER = { browser: 0, context: 1, page: 2, request: 3 };
12972
13009
  function relativePath(file, cwd = process.cwd(), windows = process.platform === "win32") {
@@ -13225,6 +13262,7 @@ var ResourceLedger = class {
13225
13262
  }
13226
13263
  if (options?.internal || !options?.frames?.length || TRAFFIC_TYPES.has(String(object._type))) return;
13227
13264
  if (CLOSE_METHODS.has(String(method))) return this.noteClosing(object);
13265
+ this.tellCallPage(object);
13228
13266
  const site = zoneSite(options);
13229
13267
  this.touch(object, site);
13230
13268
  if (result && typeof result.then === "function") {
@@ -13241,6 +13279,7 @@ var ResourceLedger = class {
13241
13279
  const id = info?.waitId;
13242
13280
  if (id === void 0) return;
13243
13281
  if (info?.phase === "before" && !options?.internal && options?.frames?.length) {
13282
+ this.tellCallPage(object);
13244
13283
  if (this.waits.size >= WAITS_CAP) this.waits.clear();
13245
13284
  const site = zoneSite(options);
13246
13285
  this.waits.set(id, { object, site });
@@ -13251,6 +13290,12 @@ var ResourceLedger = class {
13251
13290
  if (waited) this.touch(waited.object, waited.site);
13252
13291
  }
13253
13292
  }
13293
+ /** Tell the listeners of `onTestCallPage` the page a call of the test lands on, when it lands on one. */
13294
+ tellCallPage(object) {
13295
+ if (!callPageListeners.size) return;
13296
+ const page = pageOfCall(object);
13297
+ if (page) for (const listener of callPageListeners) this.guard(() => outsideCalls(() => listener(page)));
13298
+ }
13254
13299
  /**
13255
13300
  * Mark an object, and the page, context and browser it belongs to, used now
13256
13301
  * by the call at `site`. A close that began before it did not end: the
@@ -13879,18 +13924,18 @@ function tallyLifecycleSteps(attempt3, steps, source2) {
13879
13924
  walk(step.steps ?? [], blockHook(step, source2), fixture);
13880
13925
  continue;
13881
13926
  }
13882
- const opened = OPEN_STEPS[step.title];
13927
+ const opened2 = OPEN_STEPS[step.title];
13883
13928
  const closed = CLOSE_STEPS[step.title];
13884
- if (step.category === "pw:api" && !step.error && (opened || closed)) {
13929
+ if (step.category === "pw:api" && !step.error && (opened2 || closed)) {
13885
13930
  const { location } = step;
13886
13931
  const site = location ? `${relativeFile(location.file)}:${location.line}` : null;
13887
- const method = opened?.method ?? "close";
13932
+ const method = opened2?.method ?? "close";
13888
13933
  const key = location ? `${location.file}:${location.line}:${location.column}:${method}` : "";
13889
13934
  const nth = seen.get(key) ?? 0;
13890
13935
  seen.set(key, nth + 1);
13891
13936
  const names = namesAt(step, source2, method, nth);
13892
13937
  const call = { site, block, fixture: fixture !== null, on: names.on };
13893
- if (opened) calls.push({ op: "open", kind: opened.kind, ...call, name: fixture ?? names.name });
13938
+ if (opened2) calls.push({ op: "open", kind: opened2.kind, ...call, name: fixture ?? names.name });
13894
13939
  else calls.push({ op: "close", kind: closed, ...call, name: fixture });
13895
13940
  }
13896
13941
  walk(step.steps ?? [], block, step.category === "fixture" ? fixtureName(step) : fixture);
@@ -14000,9 +14045,10 @@ function buildResourceReport(input2) {
14000
14045
  findings.push(...groupIdle(idle, input2.fixturesByTest ?? /* @__PURE__ */ new Map()));
14001
14046
  findings.push(...groupLingering(lingering, all, spans));
14002
14047
  findings.push(...probableFindings(input2.tallies ?? []));
14048
+ const leftOpenPages = leaked.filter((leak) => leak.tracked.birth.kind === "page" && leak.to > leak.from).map((leak) => ({ worker: leak.tracked.worker, from: leak.from, to: leak.to }));
14003
14049
  const counts = { leaked: 0, lingering: 0, idle: 0, piling: 0, handle: 0, probable: 0 };
14004
14050
  for (const finding of findings) counts[finding.verdict] += finding.verdict === "idle" ? finding.count : 1;
14005
- return { findings, counts, spans: spans.sort((a, b) => a.from - b.from) };
14051
+ return { findings, counts, spans: spans.sort((a, b) => a.from - b.from), leftOpenPages };
14006
14052
  }
14007
14053
  function sameFile(birth, ref) {
14008
14054
  return !!ref && !!birth.test && ref.file === birth.test.file;
@@ -14456,12 +14502,12 @@ function unpairedOpens(attempts) {
14456
14502
  (o) => o.call.name === null && o.counted,
14457
14503
  (o) => o.call.name === null
14458
14504
  ] : [(o) => o.counted, () => true];
14459
- const levels = [
14505
+ const levels2 = [
14460
14506
  (o) => o.scope === scope,
14461
14507
  (o) => o.scope === "block",
14462
14508
  (o) => o.counted
14463
14509
  ];
14464
- for (const level of levels) {
14510
+ for (const level of levels2) {
14465
14511
  for (const rank2 of ranks) {
14466
14512
  const open4 = latest((o) => free(o) && level(o) && rank2(o));
14467
14513
  if (open4) return open4;
@@ -15429,20 +15475,35 @@ function pagesOverTime(censuses, live = false) {
15429
15475
  for (const close2 of census.closed) if (pages.has(close2.id)) changes2.push([close2.at, -1]);
15430
15476
  }
15431
15477
  if (changes2.length === 0) continue;
15432
- changes2.sort((a, b) => a[0] - b[0] || b[1] - a[1]);
15433
- const events = [];
15434
- let open4 = 0;
15435
- for (const [at, delta] of changes2) {
15436
- open4 = Math.max(0, open4 + delta);
15437
- const last = events[events.length - 1];
15438
- if (last && last[0] === at) last[1] = open4;
15439
- else events.push([at, open4]);
15440
- }
15478
+ const events = levels(changes2);
15479
+ const open4 = events[events.length - 1][1];
15441
15480
  if (!live && open4 > 0 && lastAt >= events[events.length - 1][0]) events.push([lastAt, 0]);
15442
15481
  out.push({ worker, events });
15443
15482
  }
15444
15483
  return out;
15445
15484
  }
15485
+ function levels(changes2) {
15486
+ const sorted = [...changes2].sort((a, b) => a[0] - b[0] || b[1] - a[1]);
15487
+ const events = [];
15488
+ let open4 = 0;
15489
+ for (const [at, delta] of sorted) {
15490
+ open4 = Math.max(0, open4 + delta);
15491
+ const last = events[events.length - 1];
15492
+ if (last && last[0] === at) last[1] = open4;
15493
+ else events.push([at, open4]);
15494
+ }
15495
+ return events;
15496
+ }
15497
+ function leftOpenOverTime(pages) {
15498
+ const byWorker = /* @__PURE__ */ new Map();
15499
+ for (const { worker, from, to } of pages) {
15500
+ if (to <= from) continue;
15501
+ const changes2 = byWorker.get(worker) ?? [];
15502
+ changes2.push([from, 1], [to, -1]);
15503
+ byWorker.set(worker, changes2);
15504
+ }
15505
+ return new Map([...byWorker].map(([worker, changes2]) => [worker, levels(changes2)]));
15506
+ }
15446
15507
  function workerTreesByIndex(samples, censuses) {
15447
15508
  const byPid = /* @__PURE__ */ new Map();
15448
15509
  for (const census of censuses) {
@@ -15483,8 +15544,9 @@ function wireSpan(span, startedAt) {
15483
15544
  ...span.test ? { test: span.test } : {}
15484
15545
  };
15485
15546
  }
15486
- function resourceTimeline(samples, censuses, spans = []) {
15547
+ function resourceTimeline(samples, censuses, spans = [], leftOpenPages = []) {
15487
15548
  const workers = pagesOverTime(censuses);
15549
+ const leftOpen = leftOpenOverTime(leftOpenPages);
15488
15550
  const hasSamples = samples !== null && (samples.cpuPct.length > 0 || samples.memoryBytes.length > 0);
15489
15551
  const kept = keptSpans(spans);
15490
15552
  if (!hasSamples && workers.length === 0 && kept.length === 0) return null;
@@ -15493,6 +15555,11 @@ function resourceTimeline(samples, censuses, spans = []) {
15493
15555
  for (const span of kept) startedAt = Math.min(startedAt, span.from);
15494
15556
  const shift = hasSamples ? samples.startedAt - startedAt : 0;
15495
15557
  const relative11 = (points, by) => points.map(([at, value]) => [Math.round(at + by), value]);
15558
+ const level = (events) => {
15559
+ const points = relative11(events, -startedAt);
15560
+ const last = points.pop();
15561
+ return [...downsamplePoints(points, TIMELINE_WORKER_POINTS_CAP - 1, "max"), last];
15562
+ };
15496
15563
  const trees = hasSamples ? workerTreesByIndex(samples, censuses) : [];
15497
15564
  const perWorker = Math.max(
15498
15565
  60,
@@ -15503,9 +15570,8 @@ function resourceTimeline(samples, censuses, spans = []) {
15503
15570
  cpuPct: hasSamples ? downsamplePoints(relative11(samples.cpuPct, shift), TIMELINE_SERIES_CAP, "mean") : [],
15504
15571
  memoryBytes: hasSamples ? downsamplePoints(relative11(samples.memoryBytes, shift), TIMELINE_SERIES_CAP, "max") : [],
15505
15572
  pages: workers.map(({ worker, events }) => {
15506
- const points = relative11(events, -startedAt);
15507
- const last = points.pop();
15508
- return { worker, points: [...downsamplePoints(points, TIMELINE_WORKER_POINTS_CAP - 1, "max"), last] };
15573
+ const left = leftOpen.get(worker);
15574
+ return { worker, points: level(events), ...left?.length ? { leftOpen: level(left) } : {} };
15509
15575
  }),
15510
15576
  workers: trees.map((tree) => ({
15511
15577
  worker: tree.worker,
@@ -15526,7 +15592,7 @@ function resourceReportWire(input2) {
15526
15592
  workers: openPagesByWorker(input2.censuses),
15527
15593
  artifactBytes: nonZero(input2.artifacts) ?? {},
15528
15594
  workerHealth: workerHealthOf(input2.censuses),
15529
- timeline: resourceTimeline(input2.samples ?? null, input2.censuses, report?.spans ?? [])
15595
+ timeline: resourceTimeline(input2.samples ?? null, input2.censuses, report?.spans ?? [], report?.leftOpenPages ?? [])
15530
15596
  };
15531
15597
  }
15532
15598
 
@@ -23874,13 +23940,14 @@ async function keptResponse(id) {
23874
23940
  var CLOSE_MS2 = 1e3;
23875
23941
  var test = null;
23876
23942
  var stop = null;
23943
+ var opened = [];
23877
23944
  var subscribers = /* @__PURE__ */ new Set();
23878
23945
  var pageListeners = /* @__PURE__ */ new Set();
23879
23946
  var pageTold;
23880
23947
  var source = null;
23881
23948
  var closingOf = /* @__PURE__ */ new WeakMap();
23882
23949
  function laneTestBegan(id) {
23883
- test = { id, fixture: null, seen: [] };
23950
+ test = { id, fixture: null, called: null };
23884
23951
  void sync();
23885
23952
  tellPage();
23886
23953
  }
@@ -23891,9 +23958,23 @@ function lanePage(page) {
23891
23958
  tellPage();
23892
23959
  }
23893
23960
  function laneSawPage(page) {
23894
- if (!test || test.seen.includes(page)) return;
23895
- test.seen.push(page);
23896
- if (!source) void sync();
23961
+ if (opened.includes(page)) return;
23962
+ opened.push(page);
23963
+ if (typeof page.once === "function") {
23964
+ page.once("close", () => {
23965
+ const at = opened.indexOf(page);
23966
+ if (at >= 0) opened.splice(at, 1);
23967
+ tellPage();
23968
+ });
23969
+ }
23970
+ if (!test) return;
23971
+ void sync();
23972
+ tellPage();
23973
+ }
23974
+ function laneCalled(page) {
23975
+ if (!test || test.called === page || !opened.includes(page)) return;
23976
+ test.called = page;
23977
+ void sync();
23897
23978
  tellPage();
23898
23979
  }
23899
23980
  async function laneTestEnded() {
@@ -23933,7 +24014,9 @@ function tellPage() {
23933
24014
  }
23934
24015
  if (page === pageTold) return;
23935
24016
  pageTold = page;
23936
- for (const listener of pageListeners) listener();
24017
+ outsideCalls(() => {
24018
+ for (const listener of pageListeners) listener();
24019
+ });
23937
24020
  }
23938
24021
  function restamp() {
23939
24022
  const kept = source?.latest;
@@ -23954,7 +24037,14 @@ function lanePageShown() {
23954
24037
  const own = open4(stop?.page ?? null);
23955
24038
  if (own) return own;
23956
24039
  if (!test) return null;
23957
- return open4(test.fixture) ?? test.seen.find((page) => !page.isClosed()) ?? null;
24040
+ return open4(test.fixture) ?? open4(test.called) ?? lastOpened();
24041
+ }
24042
+ function lastOpened() {
24043
+ for (let at = opened.length - 1; at >= 0; at--) {
24044
+ const page = opened[at];
24045
+ if (!page.isClosed()) return page;
24046
+ }
24047
+ return null;
23958
24048
  }
23959
24049
  function pacerOf(own) {
23960
24050
  return new LatestPacer({
@@ -23998,11 +24088,7 @@ function subscribeLane(sink) {
23998
24088
  return subscribers.has(own) && kept && !("refused" in kept) && current2(kept) ? kept : null;
23999
24089
  },
24000
24090
  refresh: () => {
24001
- for (const subscriber of subscribers) {
24002
- subscriber.last = null;
24003
- subscriber.pacer.close();
24004
- subscriber.pacer = pacerOf(subscriber);
24005
- }
24091
+ for (const subscriber of subscribers) forgetFrames(subscriber);
24006
24092
  if (source) source.latest = null;
24007
24093
  void source?.view.then((view3) => view3?.refresh());
24008
24094
  },
@@ -24032,14 +24118,22 @@ function asked() {
24032
24118
  shotMs: Math.min(...sinks.map((sink) => sink.shotMs))
24033
24119
  };
24034
24120
  }
24121
+ function forgetFrames(subscriber) {
24122
+ subscriber.last = null;
24123
+ subscriber.pacer.close();
24124
+ subscriber.pacer = pacerOf(subscriber);
24125
+ }
24035
24126
  function sync() {
24036
24127
  const page = subscribers.size ? lanePageShown() : null;
24037
24128
  const options = page ? asked() : null;
24038
24129
  const key = options ? JSON.stringify(options) : "";
24039
24130
  if (source && source.page === page && source.asked === key) return Promise.resolve();
24040
- const closed = source ? close(source) : Promise.resolve();
24041
- source = page && options ? open2(page, options, key) : null;
24042
- return closed;
24131
+ if (source && source.page !== page) for (const subscriber of subscribers) forgetFrames(subscriber);
24132
+ return outsideCalls(() => {
24133
+ const closed = source ? close(source) : Promise.resolve();
24134
+ source = page && options ? open2(page, options, key) : null;
24135
+ return closed;
24136
+ });
24043
24137
  }
24044
24138
  function close(shown2) {
24045
24139
  if (source === shown2) source = null;
@@ -24860,6 +24954,7 @@ function shownInFull(own) {
24860
24954
  return own.asked?.full ?? true;
24861
24955
  }
24862
24956
  var link = null;
24957
+ var unhearLane = null;
24863
24958
  var missing = null;
24864
24959
  var changes = /* @__PURE__ */ new Set();
24865
24960
  var shareTurn = Promise.resolve();
@@ -24965,6 +25060,7 @@ function openLiveView(worker, env = process.env, ci = detectCi(env)) {
24965
25060
  asked: null
24966
25061
  };
24967
25062
  if (link.sharing) connect2(link);
25063
+ unhearLane = onLanePage(lanePageChanged);
24968
25064
  inspectSent.clear();
24969
25065
  filmstrip?.close();
24970
25066
  filmstrip = new LaneFilmstrip(watchedLane, (kept, test2) => {
@@ -24980,6 +25076,8 @@ function closeLiveView() {
24980
25076
  link = null;
24981
25077
  running = null;
24982
25078
  missing = null;
25079
+ unhearLane?.();
25080
+ unhearLane = null;
24983
25081
  filmstrip?.close();
24984
25082
  filmstrip = null;
24985
25083
  thumbPosts.queue = [];
@@ -25025,15 +25123,24 @@ async function stopSharing() {
25025
25123
  }
25026
25124
  function liveViewTestBegan(title, call, mayPause2 = false) {
25027
25125
  if (!link) return;
25028
- running = { title, page: null, call, mayPause: mayPause2, began: Date.now() };
25126
+ running = { title, call, mayPause: mayPause2, began: Date.now() };
25029
25127
  textGeneration++;
25030
25128
  filmstrip?.forget();
25031
25129
  thumbPosts.queue = [];
25130
+ lanePageChanged();
25032
25131
  }
25033
- function liveViewPage(page) {
25034
- if (!link || !running || running.page) return;
25035
- running.page = page;
25036
- if (link.viewers > 0 && active(link)) startView();
25132
+ function lanePageChanged() {
25133
+ const own = link;
25134
+ if (!own || !running || !active(own) || own.viewers === 0) return;
25135
+ const page = lanePageNow();
25136
+ if (view?.page === page) return;
25137
+ if (!view) {
25138
+ if (page) startView();
25139
+ } else if (!page) {
25140
+ void stopView();
25141
+ } else {
25142
+ moveView(own, page);
25143
+ }
25037
25144
  }
25038
25145
  async function liveViewTestEnded(status) {
25039
25146
  if (!running) return;
@@ -25359,14 +25466,15 @@ function startThumbPosts(own) {
25359
25466
  }
25360
25467
  function startView() {
25361
25468
  const own = link;
25362
- const page = running?.page ?? null;
25469
+ const page = running ? lanePageNow() : null;
25363
25470
  if (!own || !active(own) || view) return;
25364
25471
  if (!page || page.isClosed()) {
25365
25472
  void post(own, { type: "frame", ...own.id, refused: NO_PAGE });
25366
25473
  return;
25367
25474
  }
25368
- const live = () => view?.page === page && link === own && active(own) && own.viewers > 0;
25369
- const frames = subscribeLane({
25475
+ let frames = null;
25476
+ const live = () => !!frames && view?.frames === frames && link === own && active(own) && own.viewers > 0;
25477
+ frames = subscribeLane({
25370
25478
  get maxWidth() {
25371
25479
  return own.asked?.width ?? LIVE_FRAME_WIDTH;
25372
25480
  },
@@ -25391,14 +25499,26 @@ function startView() {
25391
25499
  if (live()) void post(own, { type: "frame", ...own.id, refused: why ?? TOO_HEAVY });
25392
25500
  }
25393
25501
  });
25394
- const onClose = () => {
25395
- if (view?.page === page) void stopView();
25396
- };
25502
+ const onClose = () => lanePageChanged();
25397
25503
  page.once("close", onClose);
25398
25504
  view = { page, frames, onClose, following: null };
25399
25505
  followCalls(own);
25400
25506
  applyLayers(own, /* @__PURE__ */ new Set());
25401
25507
  }
25508
+ function moveView(own, page) {
25509
+ const shown2 = view;
25510
+ if (!shown2) return;
25511
+ shown2.page.off("close", shown2.onClose);
25512
+ void shown2.following?.then((stop2) => stop2?.());
25513
+ shown2.following = null;
25514
+ forgetLog(own);
25515
+ shown2.page = page;
25516
+ page.once("close", shown2.onClose);
25517
+ textGeneration++;
25518
+ void stopInspect();
25519
+ followCalls(own);
25520
+ applyLayers(own, new Set((own.asked?.layers ?? []).filter((layer) => layer !== "text")));
25521
+ }
25402
25522
  function followCalls(own) {
25403
25523
  const shown2 = view;
25404
25524
  if (!shown2 || own !== link) return;
@@ -25410,7 +25530,7 @@ function followCalls(own) {
25410
25530
  page,
25411
25531
  running.began,
25412
25532
  (log) => {
25413
- if (view === shown2 && link === own && active(own) && own.viewers > 0) postLog(own, log);
25533
+ if (view === shown2 && shown2.page === page && link === own && active(own) && own.viewers > 0) postLog(own, log);
25414
25534
  },
25415
25535
  { source: source2, titleOf: layersTitleOf, secrets: knownSecrets }
25416
25536
  ).catch(() => null);
@@ -25613,7 +25733,7 @@ async function openRunChannel(worker, handlers, env = process.env) {
25613
25733
  if (socket || !channel || !ref) return false;
25614
25734
  const opening = net4.connect(channel.path);
25615
25735
  opening.setEncoding("utf8");
25616
- const opened = await new Promise((resolve15) => {
25736
+ const opened2 = await new Promise((resolve15) => {
25617
25737
  const timer = setTimeout(() => resolve15(false), CONNECT_MS);
25618
25738
  opening.once("connect", () => {
25619
25739
  clearTimeout(timer);
@@ -25624,7 +25744,7 @@ async function openRunChannel(worker, handlers, env = process.env) {
25624
25744
  resolve15(false);
25625
25745
  });
25626
25746
  });
25627
- if (!opened || opening.destroyed) {
25747
+ if (!opened2 || opening.destroyed) {
25628
25748
  opening.destroy();
25629
25749
  return false;
25630
25750
  }
@@ -26082,20 +26202,20 @@ function startView2(holding) {
26082
26202
  const started = (async () => {
26083
26203
  if (view2) await stopView2();
26084
26204
  const opening = openView2(page, holding.stop);
26085
- const opened = await answerWithin(opening, PAGE_ANSWER_MS, "late");
26086
- if (opened === "late") {
26205
+ const opened2 = await answerWithin(opening, PAGE_ANSWER_MS, "late");
26206
+ if (opened2 === "late") {
26087
26207
  void opening.then((late) => late?.close());
26088
26208
  return { ok: false, message: NO_ANSWER };
26089
26209
  }
26090
- if (!opened) return { ok: false, message: "The page could not be shown: it closed, or does not answer." };
26210
+ if (!opened2) return { ok: false, message: "The page could not be shown: it closed, or does not answer." };
26091
26211
  if (held !== holding || page.isClosed()) {
26092
- await within5(opened.close(), VIEW_END_MS2);
26212
+ await within5(opened2.close(), VIEW_END_MS2);
26093
26213
  return { ok: false, message: WENT_ON };
26094
26214
  }
26095
- view2 = opened;
26215
+ view2 = opened2;
26096
26216
  return {
26097
26217
  ok: true,
26098
- message: opened.screencast ? "The live view is on." : "The live view is on, as images of the page twice a second: the page's screencast is in use."
26218
+ message: opened2.screencast ? "The live view is on." : "The live view is on, as images of the page twice a second: the page's screencast is in use."
26099
26219
  };
26100
26220
  })().finally(() => {
26101
26221
  if (viewStarting?.started === started) viewStarting = null;
@@ -26116,8 +26236,8 @@ async function openView2(page, stop2) {
26116
26236
  if (ours(at)) tellHub({ type: "frame", stop: stop2, refused: why ?? TOO_HEAVY2 });
26117
26237
  }
26118
26238
  });
26119
- const opened = await subscription.ready();
26120
- if (!opened) {
26239
+ const opened2 = await subscription.ready();
26240
+ if (!opened2) {
26121
26241
  await subscription.close();
26122
26242
  return null;
26123
26243
  }
@@ -26127,7 +26247,7 @@ async function openView2(page, stop2) {
26127
26247
  page.once("close", onClose);
26128
26248
  return {
26129
26249
  stop: stop2,
26130
- screencast: opened.screencast,
26250
+ screencast: opened2.screencast,
26131
26251
  resend: subscription.resend,
26132
26252
  close: async () => {
26133
26253
  page.off("close", onClose);
@@ -27356,7 +27476,7 @@ function readPageInteraction() {
27356
27476
  const doc = globalThis.document;
27357
27477
  const SKIPPED_TEXT = ["SCRIPT", "STYLE", "NOSCRIPT", "TEMPLATE"];
27358
27478
  const pathOf = (el) => {
27359
- const levels = [];
27479
+ const levels2 = [];
27360
27480
  for (let node = el; node; ) {
27361
27481
  const steps = [];
27362
27482
  let root = null;
@@ -27368,10 +27488,10 @@ function readPageInteraction() {
27368
27488
  steps.unshift(`${cur.localName}:${position}`);
27369
27489
  if (!cur.parentElement) root = cur.parentNode;
27370
27490
  }
27371
- levels.unshift(steps.join("/"));
27491
+ levels2.unshift(steps.join("/"));
27372
27492
  node = root && root.host ? root.host : null;
27373
27493
  }
27374
- return levels.join("|");
27494
+ return levels2.join("|");
27375
27495
  };
27376
27496
  const isField = (el) => /^(input|textarea|select)$/.test(el.localName) || !!el.isContentEditable;
27377
27497
  const label = (el) => {
@@ -29126,7 +29246,7 @@ function instrumentPage(page) {
29126
29246
  laneSawPage(page);
29127
29247
  const probeSink = currentSink;
29128
29248
  if (probeSink?.probeItem && !probeSink.probeInterception) {
29129
- void installProbeInterception(page, probeSink.probeItem).then((interception) => {
29249
+ void installProbeInterception(page, probeSink.probeItem, probeSink.baseURL).then((interception) => {
29130
29250
  probeSink.probeInterception = interception;
29131
29251
  }).catch(() => {
29132
29252
  });
@@ -29822,13 +29942,16 @@ var piwiFixtures = {
29822
29942
  observeApiRequests(playwright, apiCallRecorder);
29823
29943
  openLiveView(workerInfo);
29824
29944
  if (liveViewOpen()) trackCalls(playwright);
29825
- if (await openRunChannel(workerInfo, runControl)) {
29945
+ const channel = await openRunChannel(workerInfo, runControl);
29946
+ if (channel) {
29826
29947
  watchCalls(playwright);
29827
29948
  trackCalls(playwright);
29828
29949
  }
29950
+ const unhearCallPages = liveViewOpen() || channel ? onTestCallPage((page) => laneCalled(page)) : () => void 0;
29829
29951
  try {
29830
29952
  await use();
29831
29953
  } finally {
29954
+ unhearCallPages();
29832
29955
  closeLiveView();
29833
29956
  closeRunChannel();
29834
29957
  stopResourceLedger();
@@ -29857,7 +29980,6 @@ var piwiFixtures = {
29857
29980
  await awaitFlakeConditions();
29858
29981
  await maybeStartCodeReach(page);
29859
29982
  lanePage(page);
29860
- liveViewPage(page);
29861
29983
  await use(page);
29862
29984
  const sink = currentSink;
29863
29985
  if (sink) await holdFailure(sink, page);
@@ -868,6 +868,8 @@ declare class ResourceLedger {
868
868
  * in use until then.
869
869
  */
870
870
  private onWait;
871
+ /** Tell the listeners of `onTestCallPage` the page a call of the test lands on, when it lands on one. */
872
+ private tellCallPage;
871
873
  /**
872
874
  * Mark an object, and the page, context and browser it belongs to, used now
873
875
  * by the call at `site`. A close that began before it did not end: the
@@ -2999,8 +2999,8 @@ function readPrivateFile(file) {
2999
2999
  const fd = fs3.openSync(file, fs3.constants.O_RDONLY | NO_FOLLOW | NO_WAIT);
3000
3000
  try {
3001
3001
  const stat2 = fs3.fstatSync(fd);
3002
- const opened = untrustedReason(stat2);
3003
- if (opened) return { untrusted: opened };
3002
+ const opened2 = untrustedReason(stat2);
3003
+ if (opened2) return { untrusted: opened2 };
3004
3004
  return { text: fs3.readFileSync(fd, "utf8"), mode: stat2.mode };
3005
3005
  } finally {
3006
3006
  fs3.closeSync(fd);
@@ -3440,6 +3440,13 @@ function fulfillHeaders(responseHeaders, contentType) {
3440
3440
  if (contentType) headers["content-type"] = contentType;
3441
3441
  return headers;
3442
3442
  }
3443
+ function isMainFrameRequest(page, request) {
3444
+ try {
3445
+ return request.frame() === page.mainFrame();
3446
+ } catch {
3447
+ return false;
3448
+ }
3449
+ }
3443
3450
  function originOf(url) {
3444
3451
  try {
3445
3452
  const origin = new URL(url).origin;
@@ -3484,25 +3491,31 @@ async function installRouteRules(page, rules) {
3484
3491
  });
3485
3492
  return { state };
3486
3493
  }
3487
- async function installProbeInterception(page, item) {
3494
+ async function installProbeInterception(page, item, baseURL = null) {
3488
3495
  if (!isFaultAllowed(item.level ?? "client", item.fault)) {
3489
3496
  return { applied: () => false, appliedFault: () => null, serverError: () => false };
3490
3497
  }
3491
3498
  let applied = false;
3492
3499
  let appliedFault = null;
3493
3500
  let serverError = false;
3494
- let appOrigin = null;
3501
+ const appOrigins = /* @__PURE__ */ new Set();
3502
+ const baseOrigin = baseURL ? originOf(baseURL) : null;
3503
+ if (baseOrigin) appOrigins.add(baseOrigin);
3504
+ let firstOpened = false;
3495
3505
  const probeSecret = process.env[PIWI_PROBE_ENV.secret];
3496
- page.on("framenavigated", (frame) => {
3497
- if (frame === page.mainFrame()) {
3498
- const origin = originOf(page.url());
3499
- if (origin) appOrigin = origin;
3500
- }
3506
+ page.on("request", (request) => {
3507
+ if (firstOpened || !request.isNavigationRequest() || request.redirectedFrom()) return;
3508
+ if (!isMainFrameRequest(page, request)) return;
3509
+ const origin = originOf(request.url());
3510
+ if (!origin) return;
3511
+ firstOpened = true;
3512
+ appOrigins.add(origin);
3501
3513
  });
3502
3514
  const handle = async (route, startedAt) => {
3503
3515
  const request = route.request();
3504
3516
  if (item.level === "server") {
3505
- if (!probeSecret || appOrigin !== null && originOf(request.url()) !== appOrigin) {
3517
+ const origin = originOf(request.url());
3518
+ if (!probeSecret || origin === null || !appOrigins.has(origin)) {
3506
3519
  await route.fallback();
3507
3520
  return;
3508
3521
  }
@@ -3510,7 +3523,8 @@ async function installProbeInterception(page, item) {
3510
3523
  if (item.dependency) spec.dependency = item.dependency;
3511
3524
  try {
3512
3525
  const response = await route.fetch({
3513
- headers: { ...request.headers(), "x-piwi-probe": buildProbeHeader(probeSecret, spec) }
3526
+ headers: { ...request.headers(), "x-piwi-probe": buildProbeHeader(probeSecret, spec) },
3527
+ maxRedirects: 0
3514
3528
  });
3515
3529
  const trace = parseProbeTrace(response.headers()["x-piwi-trace"]);
3516
3530
  appliedFault = trace.appliedFault;
@@ -6069,6 +6083,7 @@ var FrameAcks = class {
6069
6083
  var import_node_module2 = require("module");
6070
6084
 
6071
6085
  // src/internal/capture/quiet-capture.ts
6086
+ var import_node_async_hooks = require("async_hooks");
6072
6087
  var import_node_module = require("module");
6073
6088
  var path8 = __toESM(require("path"));
6074
6089
 
@@ -6155,6 +6170,7 @@ function boxCaptureFrames(extraPrefixes = []) {
6155
6170
  function callMethod(target, prop, args) {
6156
6171
  return target[prop](...args);
6157
6172
  }
6173
+ var outsideCalls = import_node_async_hooks.AsyncResource.bind((run) => run());
6158
6174
  function internalCall(owner, run) {
6159
6175
  const wrap = owner?._wrapApiCall;
6160
6176
  if (typeof wrap !== "function") return run();
@@ -9835,13 +9851,14 @@ async function keptResponse(id) {
9835
9851
  var CLOSE_MS = 1e3;
9836
9852
  var test = null;
9837
9853
  var stop = null;
9854
+ var opened = [];
9838
9855
  var subscribers = /* @__PURE__ */ new Set();
9839
9856
  var pageListeners = /* @__PURE__ */ new Set();
9840
9857
  var pageTold;
9841
9858
  var source = null;
9842
9859
  var closingOf = /* @__PURE__ */ new WeakMap();
9843
9860
  function laneTestBegan(id) {
9844
- test = { id, fixture: null, seen: [] };
9861
+ test = { id, fixture: null, called: null };
9845
9862
  void sync();
9846
9863
  tellPage();
9847
9864
  }
@@ -9852,9 +9869,23 @@ function lanePage(page) {
9852
9869
  tellPage();
9853
9870
  }
9854
9871
  function laneSawPage(page) {
9855
- if (!test || test.seen.includes(page)) return;
9856
- test.seen.push(page);
9857
- if (!source) void sync();
9872
+ if (opened.includes(page)) return;
9873
+ opened.push(page);
9874
+ if (typeof page.once === "function") {
9875
+ page.once("close", () => {
9876
+ const at = opened.indexOf(page);
9877
+ if (at >= 0) opened.splice(at, 1);
9878
+ tellPage();
9879
+ });
9880
+ }
9881
+ if (!test) return;
9882
+ void sync();
9883
+ tellPage();
9884
+ }
9885
+ function laneCalled(page) {
9886
+ if (!test || test.called === page || !opened.includes(page)) return;
9887
+ test.called = page;
9888
+ void sync();
9858
9889
  tellPage();
9859
9890
  }
9860
9891
  async function laneTestEnded() {
@@ -9894,7 +9925,9 @@ function tellPage() {
9894
9925
  }
9895
9926
  if (page === pageTold) return;
9896
9927
  pageTold = page;
9897
- for (const listener of pageListeners) listener();
9928
+ outsideCalls(() => {
9929
+ for (const listener of pageListeners) listener();
9930
+ });
9898
9931
  }
9899
9932
  function restamp() {
9900
9933
  const kept = source?.latest;
@@ -9915,7 +9948,14 @@ function lanePageShown() {
9915
9948
  const own = open4(stop?.page ?? null);
9916
9949
  if (own) return own;
9917
9950
  if (!test) return null;
9918
- return open4(test.fixture) ?? test.seen.find((page) => !page.isClosed()) ?? null;
9951
+ return open4(test.fixture) ?? open4(test.called) ?? lastOpened();
9952
+ }
9953
+ function lastOpened() {
9954
+ for (let at = opened.length - 1; at >= 0; at--) {
9955
+ const page = opened[at];
9956
+ if (!page.isClosed()) return page;
9957
+ }
9958
+ return null;
9919
9959
  }
9920
9960
  function pacerOf(own) {
9921
9961
  return new LatestPacer({
@@ -9959,11 +9999,7 @@ function subscribeLane(sink) {
9959
9999
  return subscribers.has(own) && kept && !("refused" in kept) && current2(kept) ? kept : null;
9960
10000
  },
9961
10001
  refresh: () => {
9962
- for (const subscriber of subscribers) {
9963
- subscriber.last = null;
9964
- subscriber.pacer.close();
9965
- subscriber.pacer = pacerOf(subscriber);
9966
- }
10002
+ for (const subscriber of subscribers) forgetFrames(subscriber);
9967
10003
  if (source) source.latest = null;
9968
10004
  void source?.view.then((view3) => view3?.refresh());
9969
10005
  },
@@ -9993,14 +10029,22 @@ function asked() {
9993
10029
  shotMs: Math.min(...sinks.map((sink) => sink.shotMs))
9994
10030
  };
9995
10031
  }
10032
+ function forgetFrames(subscriber) {
10033
+ subscriber.last = null;
10034
+ subscriber.pacer.close();
10035
+ subscriber.pacer = pacerOf(subscriber);
10036
+ }
9996
10037
  function sync() {
9997
10038
  const page = subscribers.size ? lanePageShown() : null;
9998
10039
  const options = page ? asked() : null;
9999
10040
  const key = options ? JSON.stringify(options) : "";
10000
10041
  if (source && source.page === page && source.asked === key) return Promise.resolve();
10001
- const closed = source ? close(source) : Promise.resolve();
10002
- source = page && options ? open2(page, options, key) : null;
10003
- return closed;
10042
+ if (source && source.page !== page) for (const subscriber of subscribers) forgetFrames(subscriber);
10043
+ return outsideCalls(() => {
10044
+ const closed = source ? close(source) : Promise.resolve();
10045
+ source = page && options ? open2(page, options, key) : null;
10046
+ return closed;
10047
+ });
10004
10048
  }
10005
10049
  function close(shown2) {
10006
10050
  if (source === shown2) source = null;
@@ -10848,6 +10892,7 @@ function shownInFull(own) {
10848
10892
  return own.asked?.full ?? true;
10849
10893
  }
10850
10894
  var link = null;
10895
+ var unhearLane = null;
10851
10896
  var missing = null;
10852
10897
  var changes = /* @__PURE__ */ new Set();
10853
10898
  var shareTurn = Promise.resolve();
@@ -10953,6 +10998,7 @@ function openLiveView(worker, env = process.env, ci = detectCi(env)) {
10953
10998
  asked: null
10954
10999
  };
10955
11000
  if (link.sharing) connect(link);
11001
+ unhearLane = onLanePage(lanePageChanged);
10956
11002
  inspectSent.clear();
10957
11003
  filmstrip?.close();
10958
11004
  filmstrip = new LaneFilmstrip(watchedLane, (kept, test2) => {
@@ -10968,6 +11014,8 @@ function closeLiveView() {
10968
11014
  link = null;
10969
11015
  running = null;
10970
11016
  missing = null;
11017
+ unhearLane?.();
11018
+ unhearLane = null;
10971
11019
  filmstrip?.close();
10972
11020
  filmstrip = null;
10973
11021
  thumbPosts.queue = [];
@@ -11013,15 +11061,24 @@ async function stopSharing() {
11013
11061
  }
11014
11062
  function liveViewTestBegan(title, call, mayPause2 = false) {
11015
11063
  if (!link) return;
11016
- running = { title, page: null, call, mayPause: mayPause2, began: Date.now() };
11064
+ running = { title, call, mayPause: mayPause2, began: Date.now() };
11017
11065
  textGeneration++;
11018
11066
  filmstrip?.forget();
11019
11067
  thumbPosts.queue = [];
11068
+ lanePageChanged();
11020
11069
  }
11021
- function liveViewPage(page) {
11022
- if (!link || !running || running.page) return;
11023
- running.page = page;
11024
- if (link.viewers > 0 && active(link)) startView();
11070
+ function lanePageChanged() {
11071
+ const own = link;
11072
+ if (!own || !running || !active(own) || own.viewers === 0) return;
11073
+ const page = lanePageNow();
11074
+ if (view?.page === page) return;
11075
+ if (!view) {
11076
+ if (page) startView();
11077
+ } else if (!page) {
11078
+ void stopView();
11079
+ } else {
11080
+ moveView(own, page);
11081
+ }
11025
11082
  }
11026
11083
  async function liveViewTestEnded(status) {
11027
11084
  if (!running) return;
@@ -11347,14 +11404,15 @@ function startThumbPosts(own) {
11347
11404
  }
11348
11405
  function startView() {
11349
11406
  const own = link;
11350
- const page = running?.page ?? null;
11407
+ const page = running ? lanePageNow() : null;
11351
11408
  if (!own || !active(own) || view) return;
11352
11409
  if (!page || page.isClosed()) {
11353
11410
  void post(own, { type: "frame", ...own.id, refused: NO_PAGE });
11354
11411
  return;
11355
11412
  }
11356
- const live = () => view?.page === page && link === own && active(own) && own.viewers > 0;
11357
- const frames = subscribeLane({
11413
+ let frames = null;
11414
+ const live = () => !!frames && view?.frames === frames && link === own && active(own) && own.viewers > 0;
11415
+ frames = subscribeLane({
11358
11416
  get maxWidth() {
11359
11417
  return own.asked?.width ?? LIVE_FRAME_WIDTH;
11360
11418
  },
@@ -11379,14 +11437,26 @@ function startView() {
11379
11437
  if (live()) void post(own, { type: "frame", ...own.id, refused: why ?? TOO_HEAVY });
11380
11438
  }
11381
11439
  });
11382
- const onClose = () => {
11383
- if (view?.page === page) void stopView();
11384
- };
11440
+ const onClose = () => lanePageChanged();
11385
11441
  page.once("close", onClose);
11386
11442
  view = { page, frames, onClose, following: null };
11387
11443
  followCalls(own);
11388
11444
  applyLayers(own, /* @__PURE__ */ new Set());
11389
11445
  }
11446
+ function moveView(own, page) {
11447
+ const shown2 = view;
11448
+ if (!shown2) return;
11449
+ shown2.page.off("close", shown2.onClose);
11450
+ void shown2.following?.then((stop2) => stop2?.());
11451
+ shown2.following = null;
11452
+ forgetLog(own);
11453
+ shown2.page = page;
11454
+ page.once("close", shown2.onClose);
11455
+ textGeneration++;
11456
+ void stopInspect();
11457
+ followCalls(own);
11458
+ applyLayers(own, new Set((own.asked?.layers ?? []).filter((layer) => layer !== "text")));
11459
+ }
11390
11460
  function followCalls(own) {
11391
11461
  const shown2 = view;
11392
11462
  if (!shown2 || own !== link) return;
@@ -11398,7 +11468,7 @@ function followCalls(own) {
11398
11468
  page,
11399
11469
  running.began,
11400
11470
  (log) => {
11401
- if (view === shown2 && link === own && active(own) && own.viewers > 0) postLog(own, log);
11471
+ if (view === shown2 && shown2.page === page && link === own && active(own) && own.viewers > 0) postLog(own, log);
11402
11472
  },
11403
11473
  { source: source2, titleOf: layersTitleOf, secrets: knownSecrets }
11404
11474
  ).catch(() => null);
@@ -11601,7 +11671,7 @@ async function openRunChannel(worker, handlers, env = process.env) {
11601
11671
  if (socket || !channel || !ref) return false;
11602
11672
  const opening = net.connect(channel.path);
11603
11673
  opening.setEncoding("utf8");
11604
- const opened = await new Promise((resolve7) => {
11674
+ const opened2 = await new Promise((resolve7) => {
11605
11675
  const timer = setTimeout(() => resolve7(false), CONNECT_MS);
11606
11676
  opening.once("connect", () => {
11607
11677
  clearTimeout(timer);
@@ -11612,7 +11682,7 @@ async function openRunChannel(worker, handlers, env = process.env) {
11612
11682
  resolve7(false);
11613
11683
  });
11614
11684
  });
11615
- if (!opened || opening.destroyed) {
11685
+ if (!opened2 || opening.destroyed) {
11616
11686
  opening.destroy();
11617
11687
  return false;
11618
11688
  }
@@ -12070,20 +12140,20 @@ function startView2(holding) {
12070
12140
  const started = (async () => {
12071
12141
  if (view2) await stopView2();
12072
12142
  const opening = openView2(page, holding.stop);
12073
- const opened = await answerWithin(opening, PAGE_ANSWER_MS, "late");
12074
- if (opened === "late") {
12143
+ const opened2 = await answerWithin(opening, PAGE_ANSWER_MS, "late");
12144
+ if (opened2 === "late") {
12075
12145
  void opening.then((late) => late?.close());
12076
12146
  return { ok: false, message: NO_ANSWER };
12077
12147
  }
12078
- if (!opened) return { ok: false, message: "The page could not be shown: it closed, or does not answer." };
12148
+ if (!opened2) return { ok: false, message: "The page could not be shown: it closed, or does not answer." };
12079
12149
  if (held !== holding || page.isClosed()) {
12080
- await within5(opened.close(), VIEW_END_MS2);
12150
+ await within5(opened2.close(), VIEW_END_MS2);
12081
12151
  return { ok: false, message: WENT_ON };
12082
12152
  }
12083
- view2 = opened;
12153
+ view2 = opened2;
12084
12154
  return {
12085
12155
  ok: true,
12086
- message: opened.screencast ? "The live view is on." : "The live view is on, as images of the page twice a second: the page's screencast is in use."
12156
+ message: opened2.screencast ? "The live view is on." : "The live view is on, as images of the page twice a second: the page's screencast is in use."
12087
12157
  };
12088
12158
  })().finally(() => {
12089
12159
  if (viewStarting?.started === started) viewStarting = null;
@@ -12104,8 +12174,8 @@ async function openView2(page, stop2) {
12104
12174
  if (ours(at)) tellHub({ type: "frame", stop: stop2, refused: why ?? TOO_HEAVY2 });
12105
12175
  }
12106
12176
  });
12107
- const opened = await subscription.ready();
12108
- if (!opened) {
12177
+ const opened2 = await subscription.ready();
12178
+ if (!opened2) {
12109
12179
  await subscription.close();
12110
12180
  return null;
12111
12181
  }
@@ -12115,7 +12185,7 @@ async function openView2(page, stop2) {
12115
12185
  page.once("close", onClose);
12116
12186
  return {
12117
12187
  stop: stop2,
12118
- screencast: opened.screencast,
12188
+ screencast: opened2.screencast,
12119
12189
  resend: subscription.resend,
12120
12190
  close: async () => {
12121
12191
  page.off("close", onClose);
@@ -14378,16 +14448,16 @@ var PageReader = class {
14378
14448
  let session = this.sessions.get(page);
14379
14449
  if (!session) {
14380
14450
  session = internalCall(page, async () => {
14381
- const opened2 = await page.context().newCDPSession(page);
14382
- await opened2.send("Performance.enable", { timeDomain: "threadTicks" });
14383
- return opened2;
14451
+ const opened3 = await page.context().newCDPSession(page);
14452
+ await opened3.send("Performance.enable", { timeDomain: "threadTicks" });
14453
+ return opened3;
14384
14454
  }).catch(() => null);
14385
14455
  this.sessions.set(page, session);
14386
14456
  }
14387
- const opened = await session;
14388
- if (!opened) return null;
14457
+ const opened2 = await session;
14458
+ if (!opened2) return null;
14389
14459
  try {
14390
- const result = await internalCall(page, () => opened.send("Performance.getMetrics"));
14460
+ const result = await internalCall(page, () => opened2.send("Performance.getMetrics"));
14391
14461
  const values = new Map((result.metrics ?? []).map((metric) => [metric.name, metric.value]));
14392
14462
  const main = {
14393
14463
  cpuMs: Math.round((values.get("TaskDuration") ?? 0) * 1e3),
@@ -14395,7 +14465,7 @@ var PageReader = class {
14395
14465
  nodes: values.get("Nodes") ?? 0,
14396
14466
  listeners: values.get("JSEventListeners") ?? 0
14397
14467
  };
14398
- const elements = await this.countElements(page, opened);
14468
+ const elements = await this.countElements(page, opened2);
14399
14469
  if (elements !== null) main.elements = elements;
14400
14470
  return main;
14401
14471
  } catch {
@@ -14441,6 +14511,18 @@ var PERSISTENT_CALL = /launchPersistentContext$/;
14441
14511
  var CLOSE_TIMEOUT_MS = 5e3;
14442
14512
  var PAGE_READ_CAP = 50;
14443
14513
  var PAGE_READ_TIMEOUT_MS = 1e3;
14514
+ var callPageListeners = /* @__PURE__ */ new Set();
14515
+ function pageOfCall(object) {
14516
+ for (let owner = object; owner; owner = owner._parent) {
14517
+ if (owner._type === "Page") return owner;
14518
+ if (owner._type === "Frame" && owner._page) return owner._page;
14519
+ }
14520
+ return null;
14521
+ }
14522
+ function onTestCallPage(listener) {
14523
+ callPageListeners.add(listener);
14524
+ return () => callPageListeners.delete(listener);
14525
+ }
14444
14526
  var HOOK_PHASES = /* @__PURE__ */ new Set(["beforeAll", "afterAll", "beforeEach", "afterEach"]);
14445
14527
  var KIND_ORDER = { browser: 0, context: 1, page: 2, request: 3 };
14446
14528
  function relativePath(file, cwd = process.cwd(), windows = process.platform === "win32") {
@@ -14699,6 +14781,7 @@ var ResourceLedger = class {
14699
14781
  }
14700
14782
  if (options?.internal || !options?.frames?.length || TRAFFIC_TYPES.has(String(object._type))) return;
14701
14783
  if (CLOSE_METHODS.has(String(method))) return this.noteClosing(object);
14784
+ this.tellCallPage(object);
14702
14785
  const site = zoneSite(options);
14703
14786
  this.touch(object, site);
14704
14787
  if (result && typeof result.then === "function") {
@@ -14715,6 +14798,7 @@ var ResourceLedger = class {
14715
14798
  const id = info?.waitId;
14716
14799
  if (id === void 0) return;
14717
14800
  if (info?.phase === "before" && !options?.internal && options?.frames?.length) {
14801
+ this.tellCallPage(object);
14718
14802
  if (this.waits.size >= WAITS_CAP) this.waits.clear();
14719
14803
  const site = zoneSite(options);
14720
14804
  this.waits.set(id, { object, site });
@@ -14725,6 +14809,12 @@ var ResourceLedger = class {
14725
14809
  if (waited) this.touch(waited.object, waited.site);
14726
14810
  }
14727
14811
  }
14812
+ /** Tell the listeners of `onTestCallPage` the page a call of the test lands on, when it lands on one. */
14813
+ tellCallPage(object) {
14814
+ if (!callPageListeners.size) return;
14815
+ const page = pageOfCall(object);
14816
+ if (page) for (const listener of callPageListeners) this.guard(() => outsideCalls(() => listener(page)));
14817
+ }
14728
14818
  /**
14729
14819
  * Mark an object, and the page, context and browser it belongs to, used now
14730
14820
  * by the call at `site`. A close that began before it did not end: the
@@ -17068,7 +17158,7 @@ function instrumentPage(page) {
17068
17158
  laneSawPage(page);
17069
17159
  const probeSink = currentSink;
17070
17160
  if (probeSink?.probeItem && !probeSink.probeInterception) {
17071
- void installProbeInterception(page, probeSink.probeItem).then((interception) => {
17161
+ void installProbeInterception(page, probeSink.probeItem, probeSink.baseURL).then((interception) => {
17072
17162
  probeSink.probeInterception = interception;
17073
17163
  }).catch(() => {
17074
17164
  });
@@ -17764,13 +17854,16 @@ var piwiFixtures = {
17764
17854
  observeApiRequests(playwright, apiCallRecorder);
17765
17855
  openLiveView(workerInfo);
17766
17856
  if (liveViewOpen()) trackCalls(playwright);
17767
- if (await openRunChannel(workerInfo, runControl)) {
17857
+ const channel = await openRunChannel(workerInfo, runControl);
17858
+ if (channel) {
17768
17859
  watchCalls(playwright);
17769
17860
  trackCalls(playwright);
17770
17861
  }
17862
+ const unhearCallPages = liveViewOpen() || channel ? onTestCallPage((page) => laneCalled(page)) : () => void 0;
17771
17863
  try {
17772
17864
  await use();
17773
17865
  } finally {
17866
+ unhearCallPages();
17774
17867
  closeLiveView();
17775
17868
  closeRunChannel();
17776
17869
  stopResourceLedger();
@@ -17799,7 +17892,6 @@ var piwiFixtures = {
17799
17892
  await awaitFlakeConditions();
17800
17893
  await maybeStartCodeReach(page);
17801
17894
  lanePage(page);
17802
- liveViewPage(page);
17803
17895
  await use(page);
17804
17896
  const sink = currentSink;
17805
17897
  if (sink) await holdFailure(sink, page);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@piwitests/reporter",
3
- "version": "0.72.0",
3
+ "version": "0.73.0",
4
4
  "description": "Playwright reporter that streams results, traces and HTML reports to a Piwi Dashboard instance",
5
5
  "url": "https://github.com/PiwiTests/piwi",
6
6
  "homepage": "https://piwitests.dev",