@ai-ecoverse/slicc-shared-web 1.25.0 → 1.25.2

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/README.md CHANGED
@@ -218,7 +218,7 @@ test('boots', async (t) => {
218
218
  - the summary runs in the test process, which also serves the page's files and talks CDP, so it is linear in the trace's events: a busy page's half-million-event trace takes well under a second, and the page's fetches keep getting answers meanwhile;
219
219
  - it adds a line for every debugger pause still held in the browser, in any target, with its id, URL, start time, reason and top call frames.
220
220
 
221
- Coverage is kept as one entry per script URL, each worker's counts summed into it as the worker's coverage is taken, so a run of thousands of workers keeps no more than its distinct scripts. A worker paused at its exit breakpoint is resumed as soon as its coverage and profile are taken; the profile is written to disk after. A pause in one target blocks every page in the same renderer process, so those pause lines name the culprit even when it isn't the page under test. The harness resumes its own coverage pauses (`beforeunload`, worker exits) within 10 s, even when collecting coverage fails. Downloads of intercepted URLs time out after 60 s and are tried up to three times; a `4xx` is not retried. `chrome.requests` lists the paths the server saw in this test, `chrome.overrides` is a `Map` of paths to bodies served instead of files, and `chrome.cdn` takes `status` (answer every intercepted request with it), `corrupt` (flip the last byte) and lists the intercepted `requests`. All of them reset with each test. `serve(options)` starts the same server on its own, for an `npm start`.
221
+ Coverage is kept as one entry per script URL, each worker's counts summed into it as the worker's coverage is taken, so a run of thousands of workers keeps no more than its distinct scripts. A worker paused at its exit breakpoint is resumed as soon as its coverage and profile are taken; the profile is written to disk after. A pause in one target blocks every page in the same renderer process, so those pause lines name the culprit even when it isn't the page under test. The harness resumes its own coverage pauses (`beforeunload`, worker exits) within 10 s, even when collecting coverage fails. Any other pause in a session of its own, such as a `debugger;` statement, it resumes too, unless a test debugs that target in a session it attached itself (with `Target.attachToTarget` on `chrome.cdp`, say, and `Debugger.enable`): then that pause stays held for `Debugger.evaluateOnCallFrame` until the test resumes it. The harness never resumes a session the test attached, sends it no commands and takes no coverage, console lines or profiles from it. Downloads of intercepted URLs time out after 60 s and are tried up to three times; a `4xx` is not retried. `chrome.requests` lists the paths the server saw in this test, `chrome.overrides` is a `Map` of paths to bodies served instead of files, and `chrome.cdn` takes `status` (answer every intercepted request with it), `corrupt` (flip the last byte) and lists the intercepted `requests`. All of them reset with each test. `serve(options)` starts the same server on its own, for an `npm start`.
222
222
 
223
223
  Why it works the way it does:
224
224
 
@@ -230,7 +230,7 @@ Why it works the way it does:
230
230
  - Coverage of a script served from `chrome.overrides` would be mapped onto the file on disk, so a path overridden during a test is left out of that test's coverage.
231
231
  - A CI cache restored with a prefix key kept packuments from before a release, so pnpm in the page saw an outdated `latest` and failed with `ERR_PNPM_NO_MATCHING_VERSION`. Tarballs and versioned CDN files never change and stay cached forever; registry documents do change, so the disk copy is only the offline fallback.
232
232
  - An unscoped packument cached at `registry.npmjs.org/<name>` sat where the tarball directory `registry.npmjs.org/<name>/-/` goes, so saving one after the other failed with `EISDIR` and pnpm in the page saw `ECONNREFUSED`. Registry documents are now cached as `<path>/index.json`; a file left at the old place is a miss and is removed when something needs its place.
233
- - `--disable-component-extensions-with-background-pages`, and `--disable-extensions-except` naming only the harness extension and the `extensions` a test loads, keep a Hangouts service worker and every other extension out of every run. A launch with no extension at all keeps `--disable-extensions`.
233
+ - `--disable-component-extensions-with-background-pages` keeps a Hangouts service worker out of every run, and the fresh profile has no other extension. A launch with no extension at all keeps `--disable-extensions`. No extension goes on the command line (`--load-extension`, `--disable-extensions-except`): every extension, the harness's and a test's, loads once, through `Extensions.loadUnpacked`, because a second load gives an extension two service workers and drops its first runtime port. Once they are loaded, `launch()` fails if any target belongs to an extension it did not load.
234
234
  - The attach event can arrive before `Target.createTarget` returns, so new tabs wait on a slot keyed by target id.
235
235
  - A worker blocked in `Atomics.wait`, or one that is already gone, may never answer; snapshots give up after 3 s, and closing a context or the browser after 10 s. A call to a target that detaches or crashes fails instead of waiting forever, and a new tab that never attaches fails after 10 s.
236
236
  - A WebSocket that has closed takes new messages without an error, and a crashed target never answers, so after a crash every call used to wait out its own deadline: a browser that died 4 s in showed up as `no answer` 15 minutes later. The harness now remembers the crash or the exit and fails each call with it.
@@ -241,7 +241,7 @@ Real users run content-script extensions, such as password managers and Grammarl
241
241
 
242
242
  `harness/extension/` is an MV3 extension with no permissions, only a content script on `<all_urls>`, in all frames, at `document_start`. It sets `data-slicc-harness-extension="<id>"` on `document.documentElement`. On a page whose URL has the query flag `slicc-extension-frame` (`/?slicc-extension-frame`), it also adds a hidden `<iframe>` of its own `chrome-extension://<id>/frame.html` to the top frame, for testing extension-origin frames. Its manifest has a fixed `key`, so its id is always `ankmbodmgimjemnojmeddfcdlbocolob`, exported as `EXTENSION_ID` (and its directory as `EXTENSION_PATH`) from the harness. `chrome.extension` is `{ id, path }` for a launch that loaded it and `null` for one that didn't, so a test can assert either.
243
243
 
244
- Chrome gets `--headless=new`, which runs extensions, `--load-extension=<dir>` and `--disable-extensions-except=<dir>` (plus any `extensions` the test loads). Chrome does not run extensions in the off-the-record contexts each test gets, so once attached the harness also loads the same directory with `Extensions.loadUnpacked` and `enableInIncognito: true` (behind `--enable-unsafe-extension-debugging`). The extension then runs in every per-test context, and tests stay in their own contexts. If it loads with any other id, or not at all, `launch()` fails rather than going on without it. Its script is not counted for coverage.
244
+ Chrome gets `--headless=new`, which runs extensions, and `--enable-unsafe-extension-debugging`. Once attached, the harness loads the extension directory with `Extensions.loadUnpacked` and `enableInIncognito: true`, so it runs in the default context and in the off-the-record context each test gets, and tests stay in their own contexts. If it loads with any other id, or not at all, `launch()` fails rather than going on without it. Its script is not counted for coverage.
245
245
 
246
246
  A lane that can't have it opts out explicitly, in one of two ways:
247
247
  - `launch({ extension: false })`, for one launch;
@@ -10,8 +10,8 @@ import { cdn } from './cdn.mjs';
10
10
  import { CRASHED, connect, pipe } from './cdp.mjs';
11
11
  import { crashpad } from './dumps.mjs';
12
12
  import {
13
- BUILTIN_PATH,
14
13
  builtinWanted,
14
+ exclusive,
15
15
  extensionSource,
16
16
  install,
17
17
  installBuiltin,
@@ -51,22 +51,15 @@ export function commandLine(
51
51
  extensions = [],
52
52
  extra = [],
53
53
  realistic = false,
54
- preloaded = []
54
+ builtin = false
55
55
  ) {
56
- const all = [...preloaded, ...extensions];
57
- const loaded = all.length > 0;
56
+ const loaded = builtin || extensions.length > 0;
58
57
  const dropped = new Set([
59
58
  ...(loaded ? ['--disable-extensions'] : []),
60
59
  ...(realistic ? unrealistic : []),
61
60
  ]);
62
61
  const base = flags.filter((flag) => !dropped.has(flag));
63
- const load = loaded
64
- ? [
65
- '--enable-unsafe-extension-debugging',
66
- ...(preloaded.length > 0 ? [`--load-extension=${preloaded.join(',')}`] : []),
67
- `--disable-extensions-except=${all.join(',')}`,
68
- ]
69
- : [];
62
+ const load = loaded ? ['--enable-unsafe-extension-debugging'] : [];
70
63
  return [...base, ...load, ...extra, `--user-data-dir=${profile}`, 'about:blank'];
71
64
  }
72
65
 
@@ -336,7 +329,7 @@ export async function launch({
336
329
  const dumps = await crashpad();
337
330
  const { child, exited, stderr } = await start(
338
331
  userData,
339
- commandLine(userData, loaded, args, realistic, builtin ? [BUILTIN_PATH] : []),
332
+ commandLine(userData, loaded, args, realistic, builtin),
340
333
  browser,
341
334
  dumps.env
342
335
  ).catch(async (error) => {
@@ -373,16 +366,18 @@ export async function launch({
373
366
  waitForDebuggerOnStart: true,
374
367
  flatten: true,
375
368
  });
376
- const harnessExtension = builtin
377
- ? await installBuiltin(cdp).catch(async (error) => {
378
- await stop(cdp, child);
379
- untrack();
380
- await rm(userData, { recursive: true, force: true });
381
- await Promise.all([dumps.remove(), server.close()]);
382
- throw error;
383
- })
384
- : null;
385
- await install(cdp, found);
369
+ const harnessExtension = await (async () => {
370
+ const own = builtin ? await installBuiltin(cdp) : null;
371
+ await install(cdp, found);
372
+ await exclusive(cdp, [...(own ? [own.id] : []), ...found.keys()]);
373
+ return own;
374
+ })().catch(async (error) => {
375
+ await stop(cdp, child);
376
+ untrack();
377
+ await rm(userData, { recursive: true, force: true });
378
+ await Promise.all([dumps.remove(), server.close()]);
379
+ throw error;
380
+ });
386
381
 
387
382
  async function tabs() {
388
383
  const { targetInfos } = await cdp.send('Target.getTargets');
@@ -64,3 +64,15 @@ export async function installBuiltin(cdp) {
64
64
  }
65
65
  return { id, path: BUILTIN_PATH };
66
66
  }
67
+
68
+ export async function exclusive(cdp, allowed) {
69
+ const { targetInfos } = await cdp.send('Target.getTargets');
70
+ const hosts = targetInfos
71
+ .map(({ url }) => url)
72
+ .filter((url) => url.startsWith('chrome-extension://'))
73
+ .map((url) => new URL(url).host);
74
+ const foreign = [...new Set(hosts)].filter((host) => !allowed.includes(host));
75
+ if (foreign.length > 0) {
76
+ throw new Error(`Chrome loaded extensions the harness did not ask for: ${foreign.join(', ')}`);
77
+ }
78
+ }
@@ -11,7 +11,8 @@ const Util = mcrUtil.Util ?? mcrUtil.default;
11
11
 
12
12
  const profiled = new Set(['page', 'worker', 'service_worker', 'shared_worker']);
13
13
  const sampling = [['Profiler.setSamplingInterval', { interval: 100 }], ['Profiler.start']];
14
- const unload = "addEventListener('beforeunload', () => { debugger; })";
14
+ const unloading = 'sliccHarnessUnload';
15
+ const unload = `addEventListener('beforeunload', function ${unloading}() { debugger; })`;
15
16
 
16
17
  function pathOf(url) {
17
18
  return URL.canParse(url) ? new URL(url).pathname : '';
@@ -133,6 +134,44 @@ function contextOf(sessions, parents, sessionId) {
133
134
  return undefined;
134
135
  }
135
136
 
137
+ export function caused({ callFrames = [], hitBreakpoints = [] }, target = {}, exits = new Map()) {
138
+ const [top] = callFrames;
139
+ if (!top) return false;
140
+ const unloaded = target.type === 'page' && top.url === '';
141
+ if (unloaded && top.functionName === unloading) return true;
142
+ const lines = hitBreakpoints.length > 0 ? exits.get(pathOf(top.url)) : undefined;
143
+ return Boolean(lines?.includes(top.location.lineNumber));
144
+ }
145
+
146
+ export function ownership(parents) {
147
+ const owned = new Map();
148
+ const targets = new Map();
149
+ const debugging = new Set();
150
+ const mine = (sessionId) => owned.get(targets.get(sessionId)) === sessionId;
151
+ return {
152
+ mine,
153
+ adopt({ sessionId, targetInfo }, parent) {
154
+ targets.set(sessionId, targetInfo.targetId);
155
+ if ((parent && !mine(parent)) || owned.has(targetInfo.targetId)) return false;
156
+ owned.set(targetInfo.targetId, sessionId);
157
+ if (parent) parents.set(sessionId, parent);
158
+ return true;
159
+ },
160
+ watch(sessionId) {
161
+ if (targets.has(sessionId) && !mine(sessionId)) debugging.add(sessionId);
162
+ },
163
+ held(sessionId) {
164
+ const targetId = targets.get(sessionId);
165
+ return [...debugging].some((other) => targets.get(other) === targetId);
166
+ },
167
+ drop(sessionId) {
168
+ if (mine(sessionId)) owned.delete(targets.get(sessionId));
169
+ targets.delete(sessionId);
170
+ debugging.delete(sessionId);
171
+ },
172
+ };
173
+ }
174
+
136
175
  export function retain(scripts, result) {
137
176
  for (const script of result) {
138
177
  const prev = scripts.get(script.url);
@@ -180,6 +219,7 @@ export function recorder(cdp, server, { coverage = ['/'], exits = new Map(), pro
180
219
  const parents = new Map();
181
220
  const tabs = new Map();
182
221
  const early = [];
222
+ const own = ownership(parents);
183
223
  const ours = covered(server, coverage);
184
224
  let run = null;
185
225
 
@@ -264,12 +304,12 @@ export function recorder(cdp, server, { coverage = ['/'], exits = new Map(), pro
264
304
 
265
305
  cdp.on(async ({ method, params, sessionId }) => {
266
306
  if (method === 'Target.attachedToTarget') {
267
- if (sessionId) parents.set(params.sessionId, sessionId);
268
- await attach(params);
307
+ if (own.adopt(params, sessionId)) await attach(params);
269
308
  }
270
309
  if (method === 'Target.detachedFromTarget') {
271
310
  sessions.delete(params.sessionId);
272
311
  pauses.delete(params.sessionId);
312
+ own.drop(params.sessionId);
273
313
  }
274
314
  if (method === 'Runtime.consoleAPICalled') {
275
315
  const text = params.args.map((arg) => arg.value ?? arg.description).join(' ');
@@ -279,9 +319,12 @@ export function recorder(cdp, server, { coverage = ['/'], exits = new Map(), pro
279
319
  const { exception, text } = params.exceptionDetails;
280
320
  log(sessionId, `uncaught ${exception?.description ?? text}`);
281
321
  }
322
+ if (method?.startsWith('Debugger.')) own.watch(sessionId);
282
323
  if (method === 'Debugger.paused') {
283
324
  pauses.set(sessionId, pauseOf(sessions.get(sessionId), params));
284
- await paused(sessionId);
325
+ const target = sessions.get(sessionId);
326
+ const resumable = !own.held(sessionId) || caused(params, target, exits);
327
+ if (own.mine(sessionId) && resumable) await paused(sessionId);
285
328
  }
286
329
  if (method === 'Debugger.resumed') pauses.delete(sessionId);
287
330
  if (method === CRASHED) log(sessionId, params.reason);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-ecoverse/slicc-shared-web",
3
- "version": "1.25.0",
3
+ "version": "1.25.2",
4
4
  "description": "Shared Renovate, Biome, TypeScript, lefthook and GitHub Actions configuration, plus the CDP integration-test harness, for SLICC's web repos",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",