@ai-ecoverse/slicc-shared-web 2.4.1 → 2.4.3

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
@@ -248,7 +248,7 @@ The diff-coverage hook, `slicc-unit-cover`, runs only the unit tests that cover
248
248
  - **A staged source file missing from the lcov:** the hook fails and names it, so no file passes diff coverage just because nothing measured it. `.jsx` and `.tsx` files are not transformed for coverage, so staging one under the sources fails the hook too.
249
249
  - **A file that won't parse:** one warning line, then every unit test.
250
250
 
251
- The hook passes the list to the repo's own `test:unit` in `SLICC_UNIT_TESTS` (one path per line). A selection of more than `SLICC_UNIT_BATCH` files (60 by default) runs in batches of that size, one `test:unit` run each with its own coverage in `coverage/unit/batch-N/` (the shared `mcr.config.mjs` writes to `SLICC_UNIT_COVERAGE_DIR` when it's set), and `slicc-diff-cover` gets every batch's `lcov.info`; diff-cover counts a line covered when any batch covered it. The hook ends with one verdict line over all batches, `slicc-unit-cover: PASS …` or `slicc-unit-cover: FAIL …` (the first failing batch stops the run and fails it; diff coverage then doesn't run). That keeps the coverage merge, which grows with the number of test files, small enough for a memory-capped hook on a widely imported file. A `--require` preload, which `slicc-unit-cover` and the shared `mcr.config.mjs` add to `NODE_OPTIONS`, makes the `node --test` process run the files on that list that its own patterns match, and none when the list is empty. Without the variable, `npm run test:unit` runs everything as before. To force a full run in the hook:
251
+ The hook passes the list to the repo's own `test:unit` in `SLICC_UNIT_TESTS` (one path per line). A selection of more than `SLICC_UNIT_BATCH` files (60 by default) runs in batches of that size, one `test:unit` run each with its own coverage in `coverage/unit/batch-N/` (the shared `mcr.config.mjs` writes to `SLICC_UNIT_COVERAGE_DIR` when it's set), and `slicc-diff-cover` gets every batch's `lcov.info`; diff-cover counts a line covered when any batch covered it. The hook ends with one verdict line over all batches, `slicc-unit-cover: PASS …` or `slicc-unit-cover: FAIL …` (the first failing batch stops the run and fails it; diff coverage then doesn't run). That keeps the coverage merge, which grows with the number of test files, small enough for a memory-capped hook on a widely imported file. A `--require` preload, which `slicc-unit-cover` and the shared `mcr.config.mjs` add to `NODE_OPTIONS`, makes the `node --test` process run the files on that list that its own patterns match, and none when the list is empty. Without the variable, `npm run test:unit` runs everything as before. In the hook the same preload bounds each test file's process (with the default `--test-isolation=process`; `none` runs no such processes, so nothing is bounded): every test gets `--test-timeout` (`SLICC_UNIT_TIMEOUT` ms, 60000 by default, `0` turns all of these bounds off), a file still running `SLICC_UNIT_TIMEOUT` ms after its tests ended (its top-level `after()` hooks get that long too) is ended, and a file whose event loop is blocked, or that has no test running and nothing finishing, for `SLICC_UNIT_TIMEOUT` + 5 s (one that hangs at top level, or a `before()` hook running that long) is killed; a test's own longer `timeout` is honoured. The FAIL verdict names each test that timed out and each file that was ended (`… was still running 60000ms after its tests ended, open handles kept it alive (TCPServerWrap)`) or killed, and such a file fails even when its tests passed. Each `test:unit` run also has a wall-clock limit, `SLICC_UNIT_BATCH_TIMEOUT` ms (600000 by default, `0` for none): past it the run's whole process group is killed and the FAIL verdict names the batch and its files, which catches anything the per-file bounds miss, such as a test with an unlimited `timeout` of its own. To force a full run in the hook:
252
252
 
253
253
  ```sh
254
254
  SLICC_UNIT_ALL=1 git commit
@@ -312,7 +312,7 @@ test('boots', async (t) => {
312
312
  - both errors end with the last five lines of the browser's stderr, and each test keeps up to 200 lines it wrote during the test in `chrome-stderr.log`.
313
313
  - a test that saw a renderer crash, or a browser that died of anything but `SIGKILL`, keeps Chrome's minidump of it as `<id>.dmp` in its artifact directory (see [Crash dumps](#crash-dumps)).
314
314
 
315
- `chrome.cdp` is the browser's own pipe, the one the harness already drives, with no session of its own: test-only, unguarded access that bypasses everything a product guard would do, and never for product code. `send(method, params, sessionId)` makes a raw call at browser level, or in any session the browser has (the harness's auto-attached ones included); a protocol error rejects with the message and keeps the error object as `error.cdp`. `on(listener)` receives every event the browser sends, as `{ method, params, sessionId }`, until `off(listener)` or the function `on` returned. `waitEvent(method, predicate, ms)` resolves with the next matching event (call it before the action that causes the event); the predicate is optional, a predicate alone works too (`waitEvent(predicate, ms)`), and it rejects after `ms` (10 s unless given). `events` is an append-only array of every event since it was first read. That is the `{ send, waitEvent, events }` client the guard runner of `@ai-ecoverse/slicc-browsers` takes, so `run(set, { client, unguarded: chrome.cdp, … })` gives it the unguarded observer that 14 of its vectors need.
315
+ `chrome.cdp` is the browser's own pipe, the one the harness already drives, with no session of its own: test-only, unguarded access that bypasses everything a product guard would do, and never for product code. `send(method, params, sessionId, ms)` makes a raw call at browser level, or in any session the browser has (the harness's auto-attached ones included), and rejects with `<method>: no answer in <ms> ms` after the caller's `ms` (60 s unless given); a protocol error rejects with the message and keeps the error object as `error.cdp`. `on(listener)` receives every event the browser sends, as `{ method, params, sessionId }`, until `off(listener)` or the function `on` returned. `waitEvent(method, predicate, ms)` resolves with the next matching event (call it before the action that causes the event); the predicate is optional, a predicate alone works too (`waitEvent(predicate, ms)`), and it rejects after `ms` (10 s unless given). `events` is an append-only array of every event since it was first read. That is the `{ send, waitEvent, events }` client the guard runner of `@ai-ecoverse/slicc-browsers` takes, so `run(set, { client, unguarded: chrome.cdp, … })` gives it the unguarded observer that 14 of its vectors need.
316
316
 
317
317
  When one evaluation runs past `stallAfter`, the harness probes once, without interrupting the wait:
318
318
  - it adds a `pending` line to `console.log` for every navigation and request of the page that has no answer yet, with its age. A worker's script loads in the worker's own session, so its request is left out. Chrome holds CDP messages to a page while a navigation is waiting for its response, so an evaluation that hangs while the page is idle usually means one of these;
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import { spawnSync } from 'node:child_process';
3
- import { existsSync, readFileSync } from 'node:fs';
2
+ import { spawn, spawnSync } from 'node:child_process';
3
+ import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
4
+ import { tmpdir } from 'node:os';
4
5
  import { join } from 'node:path';
5
6
  import { fileURLToPath } from 'node:url';
6
7
  import { code, ParseError, select } from '../unit/graph.mjs';
@@ -25,6 +26,35 @@ function run(command, args, env) {
25
26
  return result.status ?? 1;
26
27
  }
27
28
 
29
+ function bounded(command, args, env, ms) {
30
+ const child = spawn(command, args, { cwd: root, env, stdio: 'inherit', detached: true });
31
+ const kill = (signal) => {
32
+ try {
33
+ process.kill(-child.pid, signal);
34
+ } catch {}
35
+ };
36
+ const forward = (signal) => () => kill(signal);
37
+ const signals = ['SIGINT', 'SIGTERM', 'SIGHUP'].map((name) => [name, forward(name)]);
38
+ for (const [name, handler] of signals) process.on(name, handler);
39
+ return new Promise((resolve, reject) => {
40
+ let late = false;
41
+ const timer =
42
+ ms > 0
43
+ ? setTimeout(() => {
44
+ late = true;
45
+ kill('SIGKILL');
46
+ }, ms)
47
+ : undefined;
48
+ child.on('error', reject);
49
+ child.on('close', (status) => {
50
+ clearTimeout(timer);
51
+ for (const [name, handler] of signals) process.off(name, handler);
52
+ kill('SIGKILL');
53
+ resolve({ status: status ?? 1, late });
54
+ });
55
+ });
56
+ }
57
+
28
58
  function selection(staged) {
29
59
  if (process.env.SLICC_UNIT_ALL === '1') return undefined;
30
60
  try {
@@ -69,8 +99,19 @@ const batches = [];
69
99
  if (tests === undefined || !(size > 0) || tests.length <= size) batches.push(tests);
70
100
  else for (let at = 0; at < tests.length; at += size) batches.push(tests.slice(at, at + size));
71
101
  const reports = [];
102
+ const scratch = mkdtempSync(join(tmpdir(), 'slicc-unit-cover-'));
103
+ const report = join(scratch, 'report');
104
+ process.on('exit', () => rmSync(scratch, { recursive: true, force: true }));
105
+ const why = () => {
106
+ const lines = existsSync(report) ? readFileSync(report, 'utf8').trim().split('\n') : [];
107
+ return lines.length > 0 ? `: ${lines.join('; ')}` : '';
108
+ };
72
109
  for (const [index, batch] of batches.entries()) {
73
- const env = { ...process.env };
110
+ const env = {
111
+ ...process.env,
112
+ SLICC_UNIT_TIMEOUT: process.env.SLICC_UNIT_TIMEOUT ?? '60000',
113
+ SLICC_UNIT_REPORT: report,
114
+ };
74
115
  if (batch === undefined) delete env.SLICC_UNIT_TESTS;
75
116
  else {
76
117
  env.SLICC_UNIT_TESTS = batch.join('\n');
@@ -81,10 +122,18 @@ for (const [index, batch] of batches.entries()) {
81
122
  reports.push(join(env.SLICC_UNIT_COVERAGE_DIR, 'lcov.info'));
82
123
  say(`batch ${index + 1} of ${batches.length}: ${batch.length} files`);
83
124
  }
84
- const status = run('npm', ['run', '--silent', 'test:unit'], env);
125
+ const limit = Number(process.env.SLICC_UNIT_BATCH_TIMEOUT ?? 600000);
126
+ const { status, late } = await bounded('npm', ['run', '--silent', 'test:unit'], env, limit);
127
+ const which = batches.length > 1 ? `batch ${index + 1} of ${batches.length}` : 'the unit tests';
128
+ if (late) {
129
+ const named = batch === undefined ? 'every unit test file' : batch.join(' ');
130
+ verdict(
131
+ false,
132
+ `${which} ran past ${limit}ms and ${batches.length > 1 ? 'was' : 'were'} killed (${named})${why()}`
133
+ );
134
+ }
85
135
  if (status !== 0) {
86
- const which = batches.length > 1 ? `batch ${index + 1} of ${batches.length}` : 'the unit tests';
87
- verdict(false, `${which} failed (status ${status})`);
136
+ verdict(false, `${which} failed (status ${status})${why()}`);
88
137
  }
89
138
  }
90
139
  const local = join(root, 'node_modules', '.bin', 'slicc-diff-cover');
@@ -7,7 +7,7 @@ import { env as inherited } from 'node:process';
7
7
  import { promisify } from 'node:util';
8
8
  import { executablePath, explicit } from './browser.mjs';
9
9
  import { cdn } from './cdn.mjs';
10
- import { CRASHED, connect, pipe } from './cdp.mjs';
10
+ import { CRASHED, connect, pipe, SEND_TIMEOUT } from './cdp.mjs';
11
11
  import { crashpad } from './dumps.mjs';
12
12
  import {
13
13
  builtinWanted,
@@ -268,7 +268,8 @@ export function unguarded(cdp) {
268
268
  return () => off(listener);
269
269
  };
270
270
  return {
271
- send: (method, params = {}, sessionId = undefined) => cdp.send(method, params, sessionId),
271
+ send: (method, params = {}, sessionId = undefined, ms = SEND_TIMEOUT) =>
272
+ cdp.send(method, params, sessionId, ms),
272
273
  on,
273
274
  off,
274
275
  get events() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-ecoverse/slicc-shared-web",
3
- "version": "2.4.1",
3
+ "version": "2.4.3",
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",
@@ -64,8 +64,8 @@
64
64
  "release": "semantic-release"
65
65
  },
66
66
  "devDependencies": {
67
- "@ai-ecoverse/slicc-browsers": "1.14.8",
68
- "@ai-ecoverse/slicc-cdp": "1.30.20",
67
+ "@ai-ecoverse/slicc-browsers": "1.15.0",
68
+ "@ai-ecoverse/slicc-cdp": "1.30.22",
69
69
  "@biomejs/biome": "2.5.15",
70
70
  "lefthook": "2.2.2",
71
71
  "monocart-coverage-reports": "2.13.2",
package/unit/guard.cjs ADDED
@@ -0,0 +1,63 @@
1
+ 'use strict';
2
+ const { appendFileSync } = require('node:fs');
3
+ const { relative } = require('node:path');
4
+
5
+ const report = process.env.SLICC_UNIT_REPORT;
6
+ const runner = 'SLICC_UNIT_RUNNER';
7
+ const ms = Number(process.env.SLICC_UNIT_TIMEOUT);
8
+ const stall = ms + 5000;
9
+
10
+ const watchdog = `const { appendFileSync } = require('node:fs');
11
+ const { workerData: { beat, stall, report, line } } = require('node:worker_threads');
12
+ let last = Atomics.load(beat, 0);
13
+ while (Atomics.wait(beat, 0, last, stall) !== 'timed-out') last = Atomics.load(beat, 0);
14
+ appendFileSync(report, line);
15
+ process.kill(process.pid, 'SIGKILL');`;
16
+
17
+ if (report && process.execArgv.includes('--test') && !process.env.NODE_TEST_CONTEXT) {
18
+ process.env[runner] = String(process.pid);
19
+ if (ms > 0) process.execArgv.push(`--test-timeout=${ms}`);
20
+ } else if (
21
+ report &&
22
+ process.env.NODE_TEST_CONTEXT &&
23
+ require('node:worker_threads').isMainThread &&
24
+ process.ppid === Number(process.env[runner])
25
+ ) {
26
+ const file = relative(process.cwd(), process.argv[1] ?? '');
27
+ const note = (line) => appendFileSync(report, `${file}${line}\n`);
28
+ const beat = new Int32Array(new SharedArrayBuffer(4));
29
+ const alive = () => {
30
+ Atomics.add(beat, 0, 1);
31
+ Atomics.notify(beat, 0);
32
+ };
33
+ const { after, afterEach, beforeEach } = require('node:test');
34
+ let running = 0;
35
+ beforeEach(() => {
36
+ running++;
37
+ alive();
38
+ });
39
+ afterEach((t) => {
40
+ running--;
41
+ alive();
42
+ if (t.error?.failureType === 'testTimeoutFailure') note(`: "${t.fullName}" ${t.error.message}`);
43
+ });
44
+ if (ms > 0) {
45
+ const { Worker } = require('node:worker_threads');
46
+ const line = `${file} was killed after ${stall}ms with no test running and nothing finishing, or its event loop blocked\n`;
47
+ new Worker(watchdog, { eval: true, workerData: { beat, stall, report, line } }).unref();
48
+ setInterval(() => running > 0 && alive(), 1000).unref();
49
+ after(() => {
50
+ alive();
51
+ setTimeout(() => {
52
+ let stdio = 3;
53
+ const open = process
54
+ .getActiveResourcesInfo()
55
+ .filter((name) => !(/^(Pipe|TTY)Wrap$/.test(name) && stdio-- > 0));
56
+ note(
57
+ ` was still running ${ms}ms after its tests ended, open handles kept it alive (${open.join(', ')})`
58
+ );
59
+ process.exit(1);
60
+ }, ms).unref();
61
+ });
62
+ }
63
+ }
package/unit/select.cjs CHANGED
@@ -1,4 +1,5 @@
1
1
  'use strict';
2
+ require('./guard.cjs');
2
3
  const { isAbsolute, join, matchesGlob, normalize, relative } = require('node:path');
3
4
 
4
5
  const key = Symbol.for('slicc.unit.select');