@gate-forge/pack-playwright 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/dist/discovery/config-locations.d.ts +4 -0
  2. package/dist/discovery/config-locations.d.ts.map +1 -1
  3. package/dist/discovery/config-locations.js +9 -0
  4. package/dist/discovery/config-locations.js.map +1 -1
  5. package/dist/discovery/cypress-runner-adapter.d.ts +1 -1
  6. package/dist/discovery/cypress-runner-adapter.d.ts.map +1 -1
  7. package/dist/discovery/cypress-runner-adapter.js +9 -7
  8. package/dist/discovery/cypress-runner-adapter.js.map +1 -1
  9. package/dist/discovery/discover.d.ts +10 -0
  10. package/dist/discovery/discover.d.ts.map +1 -1
  11. package/dist/discovery/discover.js +123 -6
  12. package/dist/discovery/discover.js.map +1 -1
  13. package/dist/discovery/index.d.ts +1 -1
  14. package/dist/discovery/index.d.ts.map +1 -1
  15. package/dist/discovery/index.js +1 -1
  16. package/dist/discovery/index.js.map +1 -1
  17. package/dist/discovery/playwright-runner-adapter.d.ts.map +1 -1
  18. package/dist/discovery/playwright-runner-adapter.js +4 -1
  19. package/dist/discovery/playwright-runner-adapter.js.map +1 -1
  20. package/dist/discovery/prepare-barrier.d.ts +2 -1
  21. package/dist/discovery/prepare-barrier.d.ts.map +1 -1
  22. package/dist/discovery/prepare-barrier.js +2 -1
  23. package/dist/discovery/prepare-barrier.js.map +1 -1
  24. package/dist/discovery/pytest-runner-adapter.d.ts.map +1 -1
  25. package/dist/discovery/pytest-runner-adapter.js +11 -14
  26. package/dist/discovery/pytest-runner-adapter.js.map +1 -1
  27. package/dist/discovery/reconcile.d.ts +7 -7
  28. package/dist/discovery/reconcile.d.ts.map +1 -1
  29. package/dist/discovery/reconcile.js +36 -29
  30. package/dist/discovery/reconcile.js.map +1 -1
  31. package/dist/discovery/runner-config-paths.d.ts.map +1 -1
  32. package/dist/discovery/runner-config-paths.js +3 -4
  33. package/dist/discovery/runner-config-paths.js.map +1 -1
  34. package/dist/discovery/runner-env.d.ts +12 -0
  35. package/dist/discovery/runner-env.d.ts.map +1 -1
  36. package/dist/discovery/runner-env.js +36 -2
  37. package/dist/discovery/runner-env.js.map +1 -1
  38. package/dist/discovery/runner-file-scope.d.ts.map +1 -1
  39. package/dist/discovery/runner-file-scope.js +8 -0
  40. package/dist/discovery/runner-file-scope.js.map +1 -1
  41. package/dist/discovery/supervised-run.d.ts +11 -1
  42. package/dist/discovery/supervised-run.d.ts.map +1 -1
  43. package/dist/discovery/supervised-run.js +32 -12
  44. package/dist/discovery/supervised-run.js.map +1 -1
  45. package/dist/discovery/vitest-runner-adapter.d.ts +8 -1
  46. package/dist/discovery/vitest-runner-adapter.d.ts.map +1 -1
  47. package/dist/discovery/vitest-runner-adapter.js +28 -21
  48. package/dist/discovery/vitest-runner-adapter.js.map +1 -1
  49. package/dist/fixture/api-request.d.ts +11 -18
  50. package/dist/fixture/api-request.d.ts.map +1 -1
  51. package/dist/fixture/api-request.js +91 -32
  52. package/dist/fixture/api-request.js.map +1 -1
  53. package/dist/fixture/auto-session-env.d.ts +3 -0
  54. package/dist/fixture/auto-session-env.d.ts.map +1 -0
  55. package/dist/fixture/auto-session-env.js +7 -0
  56. package/dist/fixture/auto-session-env.js.map +1 -0
  57. package/dist/fixture/auto-session-loader.mjs +20 -0
  58. package/dist/fixture/auto-session-playwright-wrapper.mjs +6 -0
  59. package/dist/fixture/auto-session-root.cjs +14 -0
  60. package/dist/fixture/auto-session-wrapper.cjs +8 -0
  61. package/dist/fixture/auto-session-wrapper.mjs +6 -0
  62. package/dist/fixture/auto-session.cjs +36 -0
  63. package/dist/fixture/fixture.d.ts +45 -34
  64. package/dist/fixture/fixture.d.ts.map +1 -1
  65. package/dist/fixture/fixture.js +356 -242
  66. package/dist/fixture/fixture.js.map +1 -1
  67. package/dist/index.d.ts +2 -1
  68. package/dist/index.d.ts.map +1 -1
  69. package/dist/index.js +2 -1
  70. package/dist/index.js.map +1 -1
  71. package/dist/reporter/reporter.cjs +4 -0
  72. package/dist/reporter/reporter.cjs.map +1 -1
  73. package/dist/reporter/reporter.d.ts +8 -0
  74. package/dist/reporter/reporter.d.ts.map +1 -1
  75. package/dist/reporter/reporter.js +40 -0
  76. package/dist/reporter/reporter.js.map +1 -1
  77. package/dist/supervisor/drain.d.ts.map +1 -1
  78. package/dist/supervisor/drain.js +27 -0
  79. package/dist/supervisor/drain.js.map +1 -1
  80. package/dist/supervisor/spool.d.ts +5 -0
  81. package/dist/supervisor/spool.d.ts.map +1 -1
  82. package/dist/supervisor/spool.js +20 -1
  83. package/dist/supervisor/spool.js.map +1 -1
  84. package/dist/vitest/index.d.ts.map +1 -1
  85. package/dist/vitest/index.js +2 -1
  86. package/dist/vitest/index.js.map +1 -1
  87. package/dist/vitest/reporter.d.ts.map +1 -1
  88. package/dist/vitest/reporter.js +2 -1
  89. package/dist/vitest/reporter.js.map +1 -1
  90. package/package.json +4 -4
@@ -10,14 +10,13 @@
10
10
  * API. Tests that use engine-driven UI must extend this runner with a
11
11
  * declarative `surface` descriptor (`test.extend({ surface })`) — the
12
12
  * pack carries no application-specific selectors. Tests must
13
- * import `{ test, expect }` FROM A RUNNER EXTENDED LIKE THIS — importing
14
- * raw `playwright/test` bypasses the fixture and produces claims with no
15
- * records (the engine grades the obligation `missing`; GF-24).
13
+ * import `{ test, expect }` FROM A RUNNER EXTENDED LIKE THIS. Witnessed
14
+ * runs automatically redirect consumer `@playwright/test` and `playwright/test`
15
+ * imports here too; an uninstrumented test produces no browser records.
16
16
  *
17
- * API requests made directly from test code are never E2E evidence. The
18
- * `request` fixture, owned `page.request`/`context.request`, and exported
19
- * `request` factory all go directly to the app; only browser page traffic
20
- * rides the session proxy.
17
+ * API requests made from test code are never E2E evidence. Test-owned
18
+ * `request` contexts ride the session proxy with a test-code marker for
19
+ * the HTTP ledger; owned `page.request`/`context.request` stay direct.
21
20
  */
22
21
  import { chromium, firefox, webkit, request as playwrightRequest } from 'playwright';
23
22
  import { createServer as createTcpServer } from 'node:net';
@@ -26,7 +25,7 @@ import { expect, test as base } from './consumer-runner.js';
26
25
  import { setTimeout as delay } from 'node:timers/promises';
27
26
  import { ENV_WITNESS_URL } from '../constants.js';
28
27
  import { createEvidence, } from './evidence.js';
29
- import { wrapDirectRequestContext } from './api-request.js';
28
+ import { wrapRequestContext } from './api-request.js';
30
29
  import { WitnessClient } from './witness-client.js';
31
30
  const browserDebuggingPorts = new WeakMap();
32
31
  const unavailableInitiatorBrowsers = new Set();
@@ -84,14 +83,17 @@ function projectBaseURL(testInfo) {
84
83
  const baseURL = testInfo.project.use['baseURL'];
85
84
  return typeof baseURL === 'string' && baseURL !== '' ? baseURL : undefined;
86
85
  }
87
- async function attachInitiatorTracking(page, appBaseURL) {
86
+ async function attachInitiatorTracking(page, appOrigins) {
88
87
  const session = await page.context().newCDPSession(page);
89
88
  const pending = new Map();
90
89
  // Route callbacks that arrived before their CDP event, oldest first.
91
90
  const waiting = new Map();
92
- const appOriginPrefix = `${new URL(appBaseURL).origin}/`;
91
+ // EVERY app origin this session routes, not just the primary one: an
92
+ // unclassified request on a declared second app would otherwise be
93
+ // graded `unknown` and lose the test-code marking it must keep.
94
+ const appOriginPrefixes = appOrigins.map((origin) => `${origin.origin}/`);
93
95
  session.on('Network.requestWillBeSent', (event) => {
94
- if (!event.request.url.startsWith(appOriginPrefix))
96
+ if (!appOriginPrefixes.some((prefix) => event.request.url.startsWith(prefix)))
95
97
  return;
96
98
  let deepest = event.initiator?.stack;
97
99
  while (deepest?.parent !== undefined)
@@ -143,44 +145,95 @@ async function attachInitiatorTracking(page, appBaseURL) {
143
145
  };
144
146
  }
145
147
  /**
146
- * Routes browser requests for the configured app origin through the
147
- * supervisor-issued session proxy, preserving the app URL and path.
148
+ * Routes browser requests for every CONFIGURED app origin through the
149
+ * supervisor-issued session proxy of that origin, preserving the app URL
150
+ * and path.
148
151
  *
149
- * Every OTHER origin the page requests is continued untouched — that is
150
- * what a third-party asset needs. When such an origin is on the app's
151
- * own host (or loopback) it is also a silent ORIGIN MISMATCH: the page
152
- * is talking to an app origin Gateforge never configured, so nothing it
153
- * fetches can reach the session proxy. `onUnroutedOrigin` reports those
154
- * origins so the witness's zero-traffic note can name the real cause
155
- * (plan 0.9.2 item F). It is diagnostic text: no record, no verdict.
152
+ * A run may declare more than one app origin (`.gateforge.yml`
153
+ * `additionalAppOrigins`): a consumer whose tests drive a platform admin
154
+ * console beside the tenant app loads both, and traffic on the second one
155
+ * used to pass unwitnessed — the test passed and earned nothing. Each
156
+ * origin rewrites onto ITS OWN session proxy, and both land on the same
157
+ * session, so attribution and claims are unchanged.
158
+ *
159
+ * Every OTHER origin the page requests is passed to remaining routes
160
+ * untouched, preserving the consumer's handlers for third-party assets.
161
+ * When an origin is on a routed app's own host (or loopback) it is also a
162
+ * silent ORIGIN MISMATCH: the page is talking to an app origin Gateforge
163
+ * never configured, so nothing it fetches can reach the session proxy.
164
+ * `onUnroutedOrigin` reports those origins so the witness's zero-traffic
165
+ * note can name the real cause (plan 0.9.2 item F). It is diagnostic text:
166
+ * no record, no verdict.
156
167
  *
157
168
  * Args:
158
169
  * page: Playwright page used by the current test.
159
- * appBaseURL: shared observation-proxy origin from the operator.
160
- * sessionProxyURL: dedicated observation-proxy origin for this test.
170
+ * appBaseURL: the primary app origin from the operator.
171
+ * sessionProxyURL: that origin's dedicated session-proxy origin.
161
172
  * onUnroutedOrigin: optional sink for unrouted same-host origins.
173
+ * initiatorForRequest: optional UI-vs-test-code classifier.
174
+ * additionalProxies: the DECLARED further origins and their proxies
175
+ * (from the session credential), when the run declares any.
162
176
  */
163
- export async function routePageThroughSessionProxy(page, appBaseURL, sessionProxyURL, onUnroutedOrigin, initiatorForRequest) {
164
- const appOrigin = new URL(appBaseURL);
165
- const sessionOrigin = new URL(sessionProxyURL);
166
- if (appOrigin.protocol !== 'http:' ||
167
- sessionOrigin.protocol !== appOrigin.protocol ||
168
- sessionOrigin.hostname !== appOrigin.hostname) {
169
- throw new Error('Gateforge session proxy and app base must share the same loopback HTTP host');
170
- }
171
- if (appOrigin.origin === sessionOrigin.origin)
177
+ export async function routePageThroughSessionProxy(page, appBaseURL, sessionProxyURL, onUnroutedOrigin, initiatorForRequest, additionalProxies = []) {
178
+ const routes = sessionProxyRoutes(appBaseURL, sessionProxyURL, additionalProxies);
179
+ if (routes.length === 0)
172
180
  return;
173
- await page.route('**/*', async (route) => {
181
+ await page.route('**/*', sessionProxyRoute(routes, onUnroutedOrigin, initiatorForRequest));
182
+ }
183
+ /**
184
+ * The session's app-origin routing table: one entry per origin that
185
+ * actually needs a rewrite, validated exactly as the single-origin case
186
+ * always was (same loopback HTTP host, or no rewrite at all).
187
+ *
188
+ * Args:
189
+ * appBaseURL: the primary app origin from the operator, or null when the
190
+ * suite configured none.
191
+ * sessionProxyURL: that origin's dedicated session-proxy origin, or null
192
+ * when this session has no primary proxy (nothing to rewrite).
193
+ * additionalProxies: the declared further origins and their proxies.
194
+ *
195
+ * Returns:
196
+ * SessionProxyRoute[]: the entries to rewrite, primary first.
197
+ *
198
+ * Raises:
199
+ * Error: when a session proxy does not share its app origin's loopback
200
+ * HTTP host — the proxy would answer with the wrong `Host`.
201
+ */
202
+ function sessionProxyRoutes(appBaseURL, sessionProxyURL, additionalProxies) {
203
+ const candidates = [
204
+ ...(appBaseURL !== null && sessionProxyURL !== null ? [{ appOrigin: appBaseURL, proxyUrl: sessionProxyURL }] : []),
205
+ ...additionalProxies,
206
+ ];
207
+ const routes = [];
208
+ const seen = new Set();
209
+ for (const candidate of candidates) {
210
+ const appOrigin = new URL(candidate.appOrigin);
211
+ const sessionOrigin = new URL(candidate.proxyUrl);
212
+ if (appOrigin.protocol !== 'http:' ||
213
+ sessionOrigin.protocol !== appOrigin.protocol ||
214
+ sessionOrigin.hostname !== appOrigin.hostname) {
215
+ throw new Error('Gateforge session proxy and app base must share the same loopback HTTP host');
216
+ }
217
+ if (appOrigin.origin === sessionOrigin.origin || seen.has(appOrigin.origin))
218
+ continue;
219
+ seen.add(appOrigin.origin);
220
+ routes.push({ appOrigin, sessionOrigin });
221
+ }
222
+ return routes;
223
+ }
224
+ function sessionProxyRoute(routes, onUnroutedOrigin, initiatorForRequest) {
225
+ return async (route) => {
174
226
  const requestURL = new URL(route.request().url());
175
- if (requestURL.origin !== appOrigin.origin) {
176
- if (onUnroutedOrigin !== undefined && isAppHostOrigin(requestURL, appOrigin)) {
227
+ const routed = routes.find((entry) => requestURL.origin === entry.appOrigin.origin);
228
+ if (routed === undefined) {
229
+ if (onUnroutedOrigin !== undefined && isAppHostOrigin(requestURL, routes)) {
177
230
  onUnroutedOrigin(requestURL.origin);
178
231
  }
179
- await route.continue();
232
+ await route.fallback();
180
233
  return;
181
234
  }
182
235
  const originalURL = requestURL.href;
183
- requestURL.host = sessionOrigin.host;
236
+ requestURL.host = routed.sessionOrigin.host;
184
237
  const initiator = await initiatorForRequest?.(route.request().method(), originalURL);
185
238
  const headers = {
186
239
  ...route.request().headers(),
@@ -188,16 +241,19 @@ export async function routePageThroughSessionProxy(page, appBaseURL, sessionProx
188
241
  };
189
242
  if (initiator === 'test-code')
190
243
  headers['x-gateforge-initiator'] = 'test-code';
191
- await route.continue({ url: requestURL.href, headers });
192
- });
244
+ // Yield to consumer context routes while carrying the session rewrite.
245
+ // continue() would skip their stubs and change the test's response.
246
+ await route.fallback({ url: requestURL.href, headers });
247
+ };
193
248
  }
194
249
  /**
195
- * Whether an unrouted origin is a plausible app origin at all: the app
196
- * base's own host, or loopback (where every local deployment lives). A
197
- * CDN or an analytics host is not a mismatch and is never reported.
250
+ * Whether an unrouted origin is a plausible app origin at all: the host of
251
+ * an origin this session DOES route, or loopback (where every local
252
+ * deployment lives). A CDN or an analytics host is not a mismatch and is
253
+ * never reported.
198
254
  */
199
- function isAppHostOrigin(url, appOrigin) {
200
- return url.hostname === appOrigin.hostname || isLoopbackHostname(url.hostname);
255
+ function isAppHostOrigin(url, routes) {
256
+ return routes.some((entry) => url.hostname === entry.appOrigin.hostname) || isLoopbackHostname(url.hostname);
201
257
  }
202
258
  /** Loopback in the three forms a browser URL can carry it. */
203
259
  function isLoopbackHostname(hostname) {
@@ -211,20 +267,23 @@ const UNROUTED_ORIGIN_CAP = 5;
211
267
  * Args:
212
268
  * witness: the session's witness client.
213
269
  * session: the session the report belongs to (its own, never another's).
214
- * appBaseURL: the base URL the fixture routes — the origin the page
215
- * was supposed to load.
270
+ * appBaseURL: the primary base URL the fixture routes.
271
+ * additionalAppOrigins: the run's DECLARED further app origins. They are
272
+ * routed too, so a report naming one would be the fixture accusing
273
+ * itself of a mismatch it does not have.
216
274
  *
217
275
  * Returns:
218
276
  * UnroutedOriginReporter: the bounded, non-blocking reporter.
219
277
  */
220
278
  export function createUnroutedOriginReporter(options) {
221
279
  const appBaseUrl = new URL(options.appBaseURL).origin;
280
+ const routedOrigins = [appBaseUrl, ...(options.additionalAppOrigins ?? []).map((url) => new URL(url).origin)];
222
281
  const origins = [];
223
282
  const inFlight = new Set();
224
283
  return {
225
284
  origins,
226
285
  report(origin) {
227
- if (origin === appBaseUrl || origins.includes(origin))
286
+ if (routedOrigins.includes(origin) || origins.includes(origin))
228
287
  return;
229
288
  if (origins.length >= UNROUTED_ORIGIN_CAP)
230
289
  return;
@@ -248,47 +307,6 @@ export function createUnroutedOriginReporter(options) {
248
307
  },
249
308
  };
250
309
  }
251
- const directExchangeReporters = new Map();
252
- function directExchangeReporterFor(testInfo) {
253
- const existing = directExchangeReporters.get(testInfo.testId);
254
- if (existing !== undefined)
255
- return existing;
256
- const inFlight = new Set();
257
- const witness = new WitnessClient();
258
- const reporter = {
259
- report(exchange) {
260
- const sent = (async () => {
261
- const session = await resolveSessionBounded(witness, testInfo.testId, testInfo.workerIndex, 5_000);
262
- if (session === null)
263
- return;
264
- await witness.reportSessionDirectExchanges({
265
- sessionId: session.sessionId,
266
- sessionToken: session.sessionToken,
267
- exchanges: [exchange],
268
- });
269
- })().catch(() => undefined);
270
- inFlight.add(sent);
271
- void sent.then(() => inFlight.delete(sent));
272
- },
273
- async settled() {
274
- while (inFlight.size > 0)
275
- await Promise.all([...inFlight]);
276
- },
277
- };
278
- directExchangeReporters.set(testInfo.testId, reporter);
279
- return reporter;
280
- }
281
- async function settleDirectExchangeReports(testInfo) {
282
- const reporter = directExchangeReporters.get(testInfo.testId);
283
- if (reporter === undefined)
284
- return;
285
- try {
286
- await reporter.settled();
287
- }
288
- finally {
289
- directExchangeReporters.delete(testInfo.testId);
290
- }
291
- }
292
310
  /**
293
311
  * The runner the evidence fixtures extend. Page observation needs a
294
312
  * Chromium debugging port, so only then does it replace Playwright's
@@ -328,141 +346,250 @@ const browserRunner = process.env['GATEFORGE_PAGE_OBSERVATION_ENABLED'] === '1'
328
346
  * was wired.
329
347
  */
330
348
  const extended = browserRunner.extend({
331
- directApiReports: [async ({}, use, testInfo) => {
349
+ browserPages: [async ({ browser, browserName }, use, testInfo) => {
332
350
  if (!process.env[ENV_WITNESS_URL]) {
333
351
  await use(undefined);
334
352
  return;
335
353
  }
336
- directExchangeReporterFor(testInfo);
337
- try {
338
- await use(undefined);
354
+ const appBaseURL = process.env['GATEFORGE_APP_BASE_URL']?.trim();
355
+ const witness = new WitnessClient();
356
+ const session = await resolveSessionBounded(witness, testInfo.testId, testInfo.workerIndex, 5_000);
357
+ if (session === null) {
358
+ throw new Error(`No supervisor-issued witness session for ${testInfo.testId}.`);
339
359
  }
340
- finally {
341
- await settleDirectExchangeReports(testInfo);
360
+ // The auto fixture also runs for tests that never create a context or
361
+ // page. Require app routing configuration only at those browser edges.
362
+ //
363
+ // The routing table is built from the SESSION CREDENTIAL, never from a
364
+ // suite-side variable: which origins exist is controller-held (the
365
+ // owner's `.gateforge.yml` declaration, resolved by the CLI into the
366
+ // witness's per-session proxies), so a test process cannot widen its
367
+ // own routing by setting an environment variable.
368
+ const additionalProxies = session.additionalProxyUrls ?? [];
369
+ const appOrigins = appBaseURL === undefined
370
+ ? null
371
+ : [new URL(appBaseURL), ...additionalProxies.map((entry) => new URL(entry.appOrigin))];
372
+ const appOriginPrefixes = appOrigins === null ? null : appOrigins.map((origin) => `${origin.origin}/`);
373
+ const routes = sessionProxyRoutes(appBaseURL ?? null, session.proxyUrl, additionalProxies);
374
+ let pageObserverRegistered = false;
375
+ const debuggingPort = browserDebuggingPorts.get(browser);
376
+ // Authority cutover (0.13): the request carries ONLY session
377
+ // credentials + the debugging port. Grading configuration is
378
+ // controller-held (supervisor-registered page-observation context);
379
+ // a registration the witness refuses (tampered session, unbound
380
+ // context) is surfaced and never retried from suite-side state.
381
+ if (debuggingPort !== undefined && process.env['GATEFORGE_PAGE_OBSERVATION_ENABLED'] === '1') {
382
+ try {
383
+ await witness.registerPageObserver({
384
+ sessionId: session.sessionId,
385
+ sessionToken: session.sessionToken,
386
+ testId: session.testId,
387
+ debuggingPort,
388
+ });
389
+ pageObserverRegistered = true;
390
+ }
391
+ catch (error) {
392
+ const detail = error instanceof Error ? error.message : String(error);
393
+ if (detail.startsWith('PAGE_OBSERVATION_TAMPER_RISK')) {
394
+ // The WITNESS refused this session's records from the
395
+ // controller context (its decision is not env-mutable here);
396
+ // surface it and continue — the page obligations stay
397
+ // unproven, never satisfied by a tampered session.
398
+ console.error(detail);
399
+ }
400
+ else {
401
+ throw error;
402
+ }
403
+ }
342
404
  }
343
- }, { auto: true }],
344
- page: async ({ page, browser, browserName }, use, testInfo) => {
345
- if (!process.env[ENV_WITNESS_URL]) {
346
- await use(page);
347
- return;
348
- }
349
- const appBaseURL = process.env['GATEFORGE_APP_BASE_URL']?.trim();
350
- if (!appBaseURL) {
351
- throw new Error('GATEFORGE_APP_BASE_URL is required for witnessed browser traffic.');
352
- }
353
- const witness = new WitnessClient();
354
- const session = await resolveSessionBounded(witness, testInfo.testId, testInfo.workerIndex, 5_000);
355
- if (session === null) {
356
- throw new Error(`No supervisor-issued witness session for ${testInfo.testId}.`);
357
- }
358
- let pageObserverRegistered = false;
359
- const debuggingPort = browserDebuggingPorts.get(browser);
360
- // Authority cutover (0.13): the request carries ONLY session
361
- // credentials + the debugging port. Grading configuration is
362
- // controller-held (supervisor-registered page-observation context);
363
- // a registration the witness refuses (tampered session, unbound
364
- // context) is surfaced and never retried from suite-side state.
365
- if (debuggingPort !== undefined && process.env['GATEFORGE_PAGE_OBSERVATION_ENABLED'] === '1') {
366
- try {
367
- await witness.registerPageObserver({
405
+ const flushPageObserver = async () => {
406
+ if (!pageObserverRegistered)
407
+ return;
408
+ await flushPageObserverEvidence(witness, {
368
409
  sessionId: session.sessionId,
369
410
  sessionToken: session.sessionToken,
370
411
  testId: session.testId,
371
- debuggingPort,
372
412
  });
373
- pageObserverRegistered = true;
374
- }
375
- catch (error) {
376
- const detail = error instanceof Error ? error.message : String(error);
377
- if (detail.startsWith('PAGE_OBSERVATION_TAMPER_RISK')) {
378
- // The WITNESS refused this session's records from the
379
- // controller context (its decision is not env-mutable here);
380
- // surface it and continue — the page obligations stay
381
- // unproven, never satisfied by a tampered session.
382
- console.error(detail);
413
+ };
414
+ const reporter = appBaseURL
415
+ ? createUnroutedOriginReporter({
416
+ witness,
417
+ session,
418
+ appBaseURL,
419
+ additionalAppOrigins: additionalProxies.map((entry) => entry.appOrigin),
420
+ })
421
+ : null;
422
+ const initialPopupRoute = routes.length === 0 || reporter === null
423
+ ? null
424
+ : sessionProxyRoute(routes, reporter.report);
425
+ const pages = new Map();
426
+ const tracking = new Map();
427
+ const pageClosers = new Map();
428
+ const pageRoutes = new Map();
429
+ const contexts = new Map();
430
+ let active = true;
431
+ const preparePage = (page) => {
432
+ if (!appBaseURL || appOrigins === null || reporter === null) {
433
+ throw new Error('GATEFORGE_APP_BASE_URL is required for witnessed browser traffic.');
383
434
  }
384
- else {
385
- throw error;
435
+ const existing = pages.get(page);
436
+ if (existing !== undefined)
437
+ return existing;
438
+ const close = page.close;
439
+ pageClosers.set(page, close);
440
+ page.close = async (...args) => {
441
+ await pages.get(page);
442
+ await flushPageObserver();
443
+ await close.apply(page, args);
444
+ };
445
+ const ready = (async () => {
446
+ let initiator;
447
+ if (browserName === 'chromium') {
448
+ initiator = await attachInitiatorTracking(page, appOrigins ?? []);
449
+ tracking.set(page, initiator);
450
+ }
451
+ else if (!unavailableInitiatorBrowsers.has(browserName)) {
452
+ unavailableInitiatorBrowsers.add(browserName);
453
+ console.warn(`initiator check unavailable for ${browserName}; requests started by test code cannot be told apart`);
454
+ }
455
+ if (routes.length > 0) {
456
+ const handler = sessionProxyRoute(routes, reporter.report, initiator?.classify);
457
+ pageRoutes.set(page, handler);
458
+ await page.route('**/*', handler);
459
+ }
460
+ })();
461
+ pages.set(page, ready);
462
+ // Event-created pages have no awaiting caller. Retain the rejection
463
+ // for teardown while preventing an unhandled-rejection process exit.
464
+ void ready.catch(() => undefined);
465
+ return ready;
466
+ };
467
+ const prepareContext = async (context) => {
468
+ if (appOriginPrefixes === null) {
469
+ throw new Error('GATEFORGE_APP_BASE_URL is required for witnessed browser traffic.');
386
470
  }
387
- }
388
- }
389
- const flushPageObserver = async () => {
390
- if (!pageObserverRegistered)
391
- return;
392
- await flushPageObserverEvidence(witness, {
393
- sessionId: session.sessionId,
394
- sessionToken: session.sessionToken,
395
- testId: session.testId,
396
- });
397
- };
398
- let initiatorTracking;
399
- if (browserName === 'chromium') {
400
- initiatorTracking = await attachInitiatorTracking(page, appBaseURL);
401
- }
402
- else if (!unavailableInitiatorBrowsers.has(browserName)) {
403
- unavailableInitiatorBrowsers.add(browserName);
404
- console.warn(`initiator check unavailable for ${browserName}; requests started by test code cannot be told apart`);
405
- }
406
- if (session.proxyUrl !== null) {
407
- const sessionProxyUrl = session.proxyUrl;
408
- const reporter = createUnroutedOriginReporter({ witness, session, appBaseURL });
409
- await routePageThroughSessionProxy(page, appBaseURL, sessionProxyUrl, reporter.report, initiatorTracking?.classify);
410
- // Do not wrap page/context.request: Playwright's Route.fetch uses
411
- // the context request internally to forward browser traffic here.
471
+ if (contexts.has(context))
472
+ return;
473
+ const newPage = context.newPage;
474
+ const contextRoute = context.route;
475
+ const contextClose = context.close;
476
+ const listener = (page) => { if (active)
477
+ void preparePage(page); };
478
+ // Playwright cannot page-route a popup's initial navigation. A
479
+ // context guard catches only requests that missed the page route;
480
+ // normal page routes rewrite first and fall through untouched here.
481
+ const popupRoute = async (route) => {
482
+ if (!active || initialPopupRoute === null || route.request().serviceWorker() !== null || !(appOriginPrefixes ?? []).some((prefix) => route.request().url().startsWith(prefix))) {
483
+ await route.fallback();
484
+ return;
485
+ }
486
+ // Initial popup requests can arrive before their frame exists.
487
+ // There is no CDP page to classify yet; subsequent requests use
488
+ // the event-installed page route and its initiator tracking.
489
+ await initialPopupRoute(route);
490
+ };
491
+ contexts.set(context, { newPage, route: contextRoute, close: contextClose, listener, popupRoute });
492
+ context.close = async (...args) => {
493
+ // A popup can finish loading before its asynchronous CDP setup.
494
+ // Complete that setup before the consumer destroys the context.
495
+ await Promise.all(context.pages().map(preparePage));
496
+ await flushPageObserver();
497
+ await contextClose.apply(context, args);
498
+ };
499
+ context.newPage = async (...args) => {
500
+ const page = await newPage.apply(context, args);
501
+ if (active)
502
+ await preparePage(page);
503
+ return page;
504
+ };
505
+ context.on('page', listener);
506
+ if (session.proxyUrl !== null) {
507
+ await contextRoute.call(context, '**/*', popupRoute);
508
+ context.route = async (...args) => {
509
+ await contextRoute.apply(context, args);
510
+ if (active) {
511
+ // Keep the initial-popup guard ahead of newly added context
512
+ // routes; fallback still passes the rewritten URL to them.
513
+ await context.unroute('**/*', popupRoute);
514
+ await contextRoute.call(context, '**/*', popupRoute);
515
+ }
516
+ };
517
+ }
518
+ await Promise.all(context.pages().map(preparePage));
519
+ };
520
+ const newContext = browser.newContext;
521
+ const newPage = browser.newPage;
522
+ browser.newContext = async (...args) => {
523
+ const context = await newContext.apply(browser, args);
524
+ if (active)
525
+ await prepareContext(context);
526
+ return context;
527
+ };
528
+ // Browser.newPage delegates internally to newContext in the pinned
529
+ // runner, but also await page readiness explicitly at its public edge.
530
+ browser.newPage = async (...args) => {
531
+ const page = await newPage.apply(browser, args);
532
+ if (active) {
533
+ await prepareContext(page.context());
534
+ await preparePage(page);
535
+ }
536
+ return page;
537
+ };
412
538
  try {
413
- await use(page);
539
+ await Promise.all(browser.contexts().map(prepareContext));
540
+ await use(undefined);
414
541
  }
415
542
  finally {
543
+ active = false;
544
+ browser.newContext = newContext;
545
+ browser.newPage = newPage;
546
+ for (const [context, hooks] of contexts) {
547
+ context.newPage = hooks.newPage;
548
+ context.route = hooks.route;
549
+ context.close = hooks.close;
550
+ context.off('page', hooks.listener);
551
+ }
552
+ for (const [page, close] of pageClosers)
553
+ page.close = close;
416
554
  try {
417
- await reporter.settled();
555
+ await Promise.all(pages.values());
556
+ await reporter?.settled();
557
+ await flushPageObserver();
418
558
  }
419
559
  finally {
420
- try {
421
- await flushPageObserver();
560
+ for (const [page, handler] of pageRoutes) {
561
+ if (!page.isClosed())
562
+ await page.unroute('**/*', handler);
422
563
  }
423
- finally {
424
- await initiatorTracking?.session.detach();
564
+ for (const [context, hooks] of contexts) {
565
+ if (browser.contexts().includes(context))
566
+ await context.unroute('**/*', hooks.popupRoute);
567
+ }
568
+ for (const [page, initiator] of tracking) {
569
+ if (!page.isClosed())
570
+ await initiator.session.detach();
425
571
  }
426
572
  }
427
573
  }
428
- return;
429
- }
430
- try {
431
- await use(page);
432
- }
433
- finally {
434
- try {
435
- await flushPageObserver();
436
- }
437
- finally {
438
- await initiatorTracking?.session.detach();
439
- }
440
- }
441
- },
574
+ }, { auto: Boolean(process.env[ENV_WITNESS_URL]) }],
442
575
  request: async ({ request }, use, testInfo) => {
443
576
  if (!process.env[ENV_WITNESS_URL]) {
444
577
  await use(request);
445
578
  return;
446
579
  }
447
- const appBaseURL = process.env['GATEFORGE_APP_BASE_URL']?.trim();
448
- if (!appBaseURL) {
449
- throw new Error('GATEFORGE_APP_BASE_URL is required for witnessed API traffic.');
450
- }
580
+ const appBaseURL = process.env['GATEFORGE_APP_BASE_URL']?.trim() || projectBaseURL(testInfo);
451
581
  const witness = new WitnessClient();
452
582
  const session = await resolveSessionBounded(witness, testInfo.testId, testInfo.workerIndex, 5_000);
453
583
  if (session === null) {
454
584
  throw new Error(`No supervisor-issued witness session for ${testInfo.testId}.`);
455
585
  }
456
- const directReporter = directExchangeReporterFor(testInfo);
457
- try {
458
- await use(wrapDirectRequestContext(request, {
459
- ...(projectBaseURL(testInfo) === undefined ? {} : { baseURL: projectBaseURL(testInfo) }),
460
- onExchange: (exchange) => directReporter.report(exchange),
461
- }));
462
- }
463
- finally {
464
- await directReporter.settled();
465
- }
586
+ if (session.proxyUrl === null)
587
+ throw new Error(`No session proxy for ${testInfo.testId}.`);
588
+ await use(wrapRequestContext(request, {
589
+ ...(projectBaseURL(testInfo) === undefined ? {} : { baseURL: projectBaseURL(testInfo) }),
590
+ ...(appBaseURL === undefined ? {} : { appBaseURL }),
591
+ sessionProxyUrl: async () => session.proxyUrl,
592
+ }));
466
593
  },
467
594
  surface: async ({}, use) => {
468
595
  await use(undefined);
@@ -538,71 +665,58 @@ function trackedHook(callback) {
538
665
  export const test = withHookTracking(extended);
539
666
  export { expect }; // re-exported so tests never need `playwright/test`
540
667
  /**
541
- * The module-scope `request` of `@gate-forge/pack-playwright/fixture`.
542
- * `newContext(options)` creates a normal Playwright API context with the
543
- * supplied options and never rehosts its calls onto the session proxy.
544
- * App-origin calls made in a test body are reported as direct-API
545
- * diagnostics only; they can never satisfy an E2E claim. Calls made at
546
- * module scope have no owning test and are not reported.
547
- *
548
- * In worker hooks, calls go straight to the app and remain uncredited;
549
- * the first test's session may already be open, but that does not make
550
- * hook traffic test-body evidence.
668
+ * Test-created standalone API contexts use the CURRENT test's session.
669
+ * base.info() throwing detects module/global scope; workerHookDepth detects
670
+ * beforeAll/afterAll even when Playwright already exposes the first test.
671
+ * Contexts created there remain native/direct and never acquire attribution.
551
672
  */
552
673
  export const request = {
553
674
  async newContext(options = {}) {
554
675
  if (!process.env[ENV_WITNESS_URL])
555
676
  return await playwrightRequest.newContext(options);
556
- const appBaseURL = process.env['GATEFORGE_APP_BASE_URL']?.trim();
557
- if (appBaseURL === undefined || appBaseURL === '')
558
- return await playwrightRequest.newContext(options);
559
- const directContext = async (testInfo) => {
560
- // Calls go to the app directly. The project's own base URL rides
561
- // along when the caller gave none, so relative setup calls retain
562
- // the suite's configured resolution.
563
- const fallbackBaseURL = options.baseURL ?? (testInfo === undefined ? undefined : projectBaseURL(testInfo));
564
- const context = await playwrightRequest.newContext(fallbackBaseURL === undefined ? options : { ...options, baseURL: fallbackBaseURL });
565
- return wrapDirectRequestContext(context, {
566
- ...(fallbackBaseURL === undefined ? {} : { baseURL: fallbackBaseURL }),
567
- onExchange: (exchange) => {
568
- let owner = testInfo;
569
- if (owner === undefined) {
570
- try {
571
- owner = base.info();
572
- }
573
- catch {
574
- return;
575
- }
576
- }
577
- directExchangeReporterFor(owner).report(exchange);
578
- },
579
- });
580
- };
581
677
  let testInfo;
582
678
  try {
583
679
  testInfo = base.info();
584
680
  }
585
681
  catch {
586
- // Module scope: no test owns this context.
587
- return await directContext();
588
- }
589
- if (workerHookDepth > 0) {
590
- // A worker hook: setup traffic, never credited — even though the
591
- // first test's session may already be open here.
592
- return await directContext(testInfo);
682
+ return await playwrightRequest.newContext(options);
593
683
  }
684
+ const baseURL = options.baseURL ?? projectBaseURL(testInfo);
685
+ const contextOptions = baseURL === undefined ? options : { ...options, baseURL };
686
+ if (workerHookDepth > 0)
687
+ return await playwrightRequest.newContext(contextOptions);
688
+ const appBaseURL = process.env['GATEFORGE_APP_BASE_URL']?.trim() || projectBaseURL(testInfo);
594
689
  const witness = new WitnessClient();
595
- // Inside a test body the supervisor has already opened (or is
596
- // opening) this test's session: wait the same bound the
597
- // fixtures use. A missing session must NOT fall back to a
598
- // direct context here — that would silently bypass the
599
- // witness for in-test traffic (only module scope and worker
600
- // hooks are setup traffic, which stays uncredited by design).
601
- const session = await resolveSessionBounded(witness, testInfo.testId, testInfo.workerIndex, 5_000);
602
- if (session === null) {
603
- throw new Error(`No supervisor-issued witness session for ${testInfo.testId}.`);
690
+ let owner = testInfo;
691
+ let session = await resolveSessionBounded(witness, owner.testId, owner.workerIndex, 5_000);
692
+ if (session === null || session.proxyUrl === null) {
693
+ throw new Error(`No supervisor-issued witness session proxy for ${owner.testId}.`);
604
694
  }
605
- return await directContext(testInfo);
695
+ const context = await playwrightRequest.newContext(contextOptions);
696
+ return wrapRequestContext(context, {
697
+ ...(baseURL === undefined ? {} : { baseURL }),
698
+ ...(appBaseURL === undefined ? {} : { appBaseURL }),
699
+ ...(options.maxRedirects === undefined ? {} : { maxRedirects: options.maxRedirects }),
700
+ sessionProxyUrl: async () => {
701
+ let current;
702
+ try {
703
+ current = base.info();
704
+ }
705
+ catch {
706
+ return null;
707
+ }
708
+ if (workerHookDepth > 0)
709
+ return null;
710
+ if (current !== owner) {
711
+ owner = current;
712
+ session = await resolveSessionBounded(witness, owner.testId, owner.workerIndex, 5_000);
713
+ }
714
+ if (session === null || session.proxyUrl === null) {
715
+ throw new Error(`No supervisor-issued witness session proxy for ${owner.testId}.`);
716
+ }
717
+ return session.proxyUrl;
718
+ },
719
+ });
606
720
  },
607
721
  };
608
722
  //# sourceMappingURL=fixture.js.map