@ai-ecoverse/slicc-shared-web 1.15.1 → 1.17.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/README.md CHANGED
@@ -8,9 +8,9 @@ Configuration shared by SLICC's web repos ([slicc-bios](https://github.com/ai-ec
8
8
  | `.github/workflows/node-ci.yml` | Reusable CI: `npm ci`, lint, Chromium's system libraries, integration tests, hotspots and the stack of every crash dump in the job summary, coverage/profiles/screenshots/crash dumps as artifacts. The browser itself comes from each repo's `pretest` | `jobs: { ci: { uses: ai-ecoverse/slicc-shared-web/.github/workflows/node-ci.yml@vX.Y.Z } }` |
9
9
  | `biome.json` | Formatter settings and slicc's strict linter: cognitive complexity ≤ 25, functions ≤ 150 lines, no unused variables or imports, no floating or misused promises, naming conventions, `import type`/`export type`. Test files under `test/` get slicc's test exemptions | `biome.json`: `{ "extends": ["@ai-ecoverse/slicc-shared-web/biome"] }` |
10
10
  | `tsconfig.json` | TypeScript base for Node's type stripping | `tsconfig.json`: `{ "extends": "@ai-ecoverse/slicc-shared-web/tsconfig.json", "include": ["src/**/*.ts"] }` |
11
- | `lefthook.yml` | Pre-commit hooks: Biome, typecheck, no comments, no unit tests in git, AGENTS.md, diff coverage | `lefthook.yml`: `extends: [node_modules/@ai-ecoverse/slicc-shared-web/lefthook.yml]` |
12
- | `mcr.config.mjs` | Unit-test coverage for JS and TS sources in `src/` (TS types are stripped first), written to `coverage/unit/lcov.info` | `test:unit`: `mcr -c node_modules/@ai-ecoverse/slicc-shared-web/mcr.config.mjs node --test 'test/unit/**/*.test.mjs'` |
13
- | `bin/` | `slicc-lint` runs every check below plus Biome and, if the repo has one, `typecheck`. `slicc-lint-comments` runs the [slicc no-comment checker](https://github.com/ai-ecoverse/slicc/tree/main/packages/dev-tools/no-comment) at a pinned commit, allowing AGENTS.md. `slicc-agents-md`, `slicc-no-unit-tests` and `slicc-diff-cover` complete the set. `slicc-minidump <file.dmp>...` prints a crash dump's stack, described [below](#crash-dumps) | `lint`: `slicc-lint`, and the hooks above |
11
+ | `lefthook.yml` | Pre-commit hooks: Biome, typecheck, no comments, no unit tests in git, AGENTS.md, and diff coverage over [only the unit tests the change reaches](#which-unit-tests-a-commit-runs) | `lefthook.yml`: `extends: [node_modules/@ai-ecoverse/slicc-shared-web/lefthook.yml]` |
12
+ | `mcr.config.mjs` | Unit-test coverage for JS and TS sources in `src/` (TS types are stripped first), written to `coverage/unit/lcov.info`. With `SLICC_UNIT_TESTS` set, `node --test` runs only those files ([below](#which-unit-tests-a-commit-runs)) | `test:unit`: `mcr -c node_modules/@ai-ecoverse/slicc-shared-web/mcr.config.mjs node --test 'test/unit/**/*.test.mjs'` |
13
+ | `bin/` | `slicc-lint` runs every check below plus Biome and, if the repo has one, `typecheck`. `slicc-lint-comments` runs the [slicc no-comment checker](https://github.com/ai-ecoverse/slicc/tree/main/packages/dev-tools/no-comment) at a pinned commit, allowing AGENTS.md. `slicc-agents-md`, `slicc-no-unit-tests` and `slicc-diff-cover` complete the set, and `slicc-unit-cover` is the diff-coverage hook. `slicc-minidump <file.dmp>...` prints a crash dump's stack, described [below](#crash-dumps) | `lint`: `slicc-lint`, and the hooks above |
14
14
  | `pnpmfile.mjs` | pnpm's counterpart to the Renovate preset: an `updateConfig` hook that adds `@ai-ecoverse/*` to `minimumReleaseAgeExclude`, so pnpm 12 doesn't hold back our own fresh releases (`ERR_PNPM_MINIMUM_RELEASE_AGE_VIOLATION`) while third-party packages keep its age check | in a repo with a pnpm lockfile, as a [config dependency](https://pnpm.io/config-dependencies) in `pnpm-workspace.yaml`: `configDependencies: { '@ai-ecoverse/slicc-shared-web': X.Y.Z }` plus `pnpmfile: node_modules/.pnpm-config/@ai-ecoverse/slicc-shared-web/pnpmfile.mjs` |
15
15
  | `harness/` | The CDP integration-test harness, described [below](#integration-test-harness) | `import { launch } from '@ai-ecoverse/slicc-shared-web/harness'`, and `--test-global-setup=node_modules/@ai-ecoverse/slicc-shared-web/harness/global.mjs` |
16
16
 
@@ -27,6 +27,23 @@ The hooks expect two scripts in each repo: `test:unit`, which writes `coverage/u
27
27
  - No comments anywhere, and no `.md` files except README.md and AGENTS.md.
28
28
  - Agent guidance committed to a repo lives in AGENTS.md only, at most 1,000 characters per file. The repo has no CLAUDE.md, not even as a symlink, since Claude reads AGENTS.md. The check covers tracked and untracked files; gitignored local files are personal and stay out of it.
29
29
  - Unit tests stay out of git, in a gitignored `test/unit/`. The pre-commit hook requires them to execute every staged line in `src/`.
30
+
31
+ ## Which unit tests a commit runs
32
+
33
+ The diff-coverage hook, `slicc-unit-cover`, runs only the unit tests that cover the staged change, then `slicc-diff-cover` on their `coverage/unit/lcov.info`, so every staged line in `src/` still has to run:
34
+
35
+ - **What counts as changed:** the staged files (`git diff --cached --name-only`). Since `test/unit/` is gitignored, files in it count as changed when they were modified after HEAD last moved (the last commit, checkout or pull).
36
+ - **Which tests run:** every `*.test.*` file in `test/unit/` that is changed, or whose static imports reach a changed file. The import graph is parsed with [acorn](https://github.com/acornjs/acorn), TypeScript after Node's type stripping. It follows `import`, `export … from`, `import()`, `require()` and `new URL(…, import.meta.url)` with literal paths, relative or through the `paths` of `tsconfig.json` (and the files it extends). A path may leave out its extension or name `index`, and `.js` also finds `.ts`. Type-only imports don't count, and nothing is followed into `node_modules/`.
37
+ - **Barrels are followed by name:** a test that imports `{ a, b }` from a module follows only what provides `a` and `b`: `export { a } from`, `export { default as a } from`, an imported binding exported again, and `export * from`, by the target's own exports. `const { a, b } = await import('…')` with a literal path is followed by name too. A name the module declares itself follows all of that module's imports. A namespace import (`import * as`), any other `import()` (bound to a namespace, with `.then`, or destructured with a computed key or a rest element), a `require()`, and an `export *` that leads outside the repo or into CommonJS (any `.cjs` or `.cts` file) all count as the whole module.
38
+ - **No code staged** (only docs, YAML, JSON or lockfiles): no unit tests and no diff coverage; the hook passes.
39
+ - **A staged file no unit test reaches:** no tests run, its lines show as uncovered, and diff coverage fails as before.
40
+ - **A file that won't parse:** one warning line, then every unit test.
41
+
42
+ The hook passes the list to the repo's own `test:unit` in `SLICC_UNIT_TESTS` (one path per line). 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:
43
+
44
+ ```sh
45
+ SLICC_UNIT_ALL=1 git commit
46
+ ```
30
47
  - Integration tests are committed and run in CI.
31
48
 
32
49
  ## Integration-test harness
@@ -0,0 +1,66 @@
1
+ #!/usr/bin/env node
2
+ import { spawnSync } from 'node:child_process';
3
+ import { existsSync } from 'node:fs';
4
+ import { join } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { code, ParseError, select } from '../unit/graph.mjs';
7
+ import { inject } from '../unit/inject.mjs';
8
+
9
+ const root = process.cwd();
10
+ const say = (line) => process.stderr.write(`slicc-unit-cover: ${line}\n`);
11
+
12
+ function git(...args) {
13
+ const run = spawnSync('git', args, { cwd: root, encoding: 'utf8' });
14
+ return run.status === 0 ? run.stdout : undefined;
15
+ }
16
+
17
+ function since() {
18
+ const moved = git('log', '-g', '-1', '--format=%gd', '--date=unix', 'HEAD')?.match(/\{(\d+)\}/);
19
+ const committed = git('log', '-1', '--format=%ct', 'HEAD')?.trim();
20
+ const seconds = Math.max(Number(moved?.[1] ?? 0), Number(committed || 0));
21
+ return seconds > 0 ? seconds * 1000 : undefined;
22
+ }
23
+
24
+ function run(command, args, env) {
25
+ const result = spawnSync(command, args, { cwd: root, env, stdio: 'inherit' });
26
+ if (result.error) throw result.error;
27
+ return result.status ?? 1;
28
+ }
29
+
30
+ function selection(staged) {
31
+ if (process.env.SLICC_UNIT_ALL === '1') return undefined;
32
+ try {
33
+ const { tests, total } = select({ root, changed: staged, since: since() });
34
+ say(`running ${tests.length} of ${total} unit test files`);
35
+ return tests;
36
+ } catch (error) {
37
+ if (!(error instanceof ParseError)) throw error;
38
+ say(
39
+ `could not build the import graph (${error.message.split('\n')[0]}), running every unit test`
40
+ );
41
+ return undefined;
42
+ }
43
+ }
44
+
45
+ const staged = (git('diff', '--cached', '--name-only', '--relative', '--no-renames', '-z') ?? '')
46
+ .split('\0')
47
+ .filter(Boolean);
48
+ if (process.env.SLICC_UNIT_ALL !== '1' && !staged.some((file) => code.test(file))) {
49
+ say('no code staged, skipping unit tests and diff coverage');
50
+ process.exit(0);
51
+ }
52
+
53
+ const env = { ...process.env };
54
+ const tests = selection(staged);
55
+ if (tests === undefined) delete env.SLICC_UNIT_TESTS;
56
+ else {
57
+ env.SLICC_UNIT_TESTS = tests.join('\n');
58
+ env.NODE_OPTIONS = inject(env.NODE_OPTIONS ?? '');
59
+ }
60
+ const status = run('npm', ['run', '--silent', 'test:unit'], env);
61
+ if (status !== 0) process.exit(status);
62
+ const local = join(root, 'node_modules', '.bin', 'slicc-diff-cover');
63
+ const cover = existsSync(local)
64
+ ? local
65
+ : fileURLToPath(new URL('slicc-diff-cover.sh', import.meta.url));
66
+ process.exit(run(cover, [], process.env));
package/lefthook.yml CHANGED
@@ -15,4 +15,4 @@ pre-commit:
15
15
  run: npx --no-install slicc-agents-md
16
16
  - name: diff coverage
17
17
  glob: "src/**.{js,mjs,ts}"
18
- run: npm run --silent test:unit && npx --no-install slicc-diff-cover
18
+ run: npx --no-install slicc-unit-cover
package/mcr.config.mjs CHANGED
@@ -1,4 +1,7 @@
1
1
  import { stripTypeScriptTypes } from 'node:module';
2
+ import { inject } from './unit/inject.mjs';
3
+
4
+ if (process.env.SLICC_UNIT_TESTS !== undefined) process.env.NODE_OPTIONS = inject();
2
5
 
3
6
  const strip = (entry) => {
4
7
  if (entry.url.endsWith('.ts')) entry.source = stripTypeScriptTypes(entry.source);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-ecoverse/slicc-shared-web",
3
- "version": "1.15.1",
3
+ "version": "1.17.0",
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",
@@ -37,7 +37,8 @@
37
37
  "slicc-lint": "bin/slicc-lint.sh",
38
38
  "slicc-lint-comments": "bin/slicc-lint-comments.sh",
39
39
  "slicc-minidump": "bin/slicc-minidump.mjs",
40
- "slicc-no-unit-tests": "bin/slicc-no-unit-tests.sh"
40
+ "slicc-no-unit-tests": "bin/slicc-no-unit-tests.sh",
41
+ "slicc-unit-cover": "bin/slicc-unit-cover.mjs"
41
42
  },
42
43
  "files": [
43
44
  "bin",
@@ -47,7 +48,8 @@
47
48
  "lefthook.yml",
48
49
  "mcr.config.mjs",
49
50
  "tsconfig.json",
50
- "pnpmfile.mjs"
51
+ "pnpmfile.mjs",
52
+ "unit"
51
53
  ],
52
54
  "scripts": {
53
55
  "lint": "bin/slicc-lint.sh && shellcheck bin/*.sh",
@@ -77,5 +79,8 @@
77
79
  "playwright-core": {
78
80
  "optional": true
79
81
  }
82
+ },
83
+ "dependencies": {
84
+ "acorn": "8.19.0"
80
85
  }
81
86
  }
@@ -0,0 +1,167 @@
1
+ export const ALL = '*';
2
+ export const BODY = '\0body';
3
+
4
+ const literal = (node) => {
5
+ if (node?.type === 'Literal' && typeof node.value === 'string') return node.value;
6
+ if (node?.type === 'TemplateLiteral' && node.expressions.length === 0) {
7
+ return node.quasis[0].value.cooked;
8
+ }
9
+ return undefined;
10
+ };
11
+
12
+ const named = (node) => (node.type === 'Literal' ? String(node.value) : node.name);
13
+
14
+ const metaUrl = (node) =>
15
+ node?.type === 'MemberExpression' &&
16
+ node.object.type === 'MetaProperty' &&
17
+ node.property.name === 'url';
18
+
19
+ function dynamic(node) {
20
+ switch (node.type) {
21
+ case 'ImportExpression':
22
+ return literal(node.source);
23
+ case 'CallExpression':
24
+ return node.callee.type === 'Identifier' && node.callee.name === 'require'
25
+ ? literal(node.arguments[0])
26
+ : undefined;
27
+ case 'NewExpression':
28
+ return node.callee.type === 'Identifier' &&
29
+ node.callee.name === 'URL' &&
30
+ metaUrl(node.arguments[1])
31
+ ? literal(node.arguments[0])
32
+ : undefined;
33
+ default:
34
+ return undefined;
35
+ }
36
+ }
37
+
38
+ function picked(node) {
39
+ if (node.type !== 'VariableDeclarator' || node.id.type !== 'ObjectPattern') return undefined;
40
+ const awaited = node.init?.type === 'AwaitExpression' ? node.init.argument : undefined;
41
+ if (awaited?.type !== 'ImportExpression') return undefined;
42
+ const spec = literal(awaited.source);
43
+ const props = node.id.properties;
44
+ if (spec === undefined || props.some((prop) => prop.type !== 'Property' || prop.computed)) {
45
+ return undefined;
46
+ }
47
+ return { spec, names: props.length > 0 ? props.map((prop) => named(prop.key)) : [BODY] };
48
+ }
49
+
50
+ function dynamics(ast) {
51
+ const found = [];
52
+ const stack = [ast];
53
+ while (stack.length > 0) {
54
+ const node = stack.pop();
55
+ const pick = picked(node);
56
+ if (pick) {
57
+ found.push(pick);
58
+ stack.push(node.id);
59
+ continue;
60
+ }
61
+ const value = dynamic(node);
62
+ if (value !== undefined) found.push({ spec: value, names: [ALL] });
63
+ for (const key of Object.keys(node)) {
64
+ const child = node[key];
65
+ if (Array.isArray(child)) {
66
+ for (const item of child) if (item && typeof item.type === 'string') stack.push(item);
67
+ } else if (child && typeof child.type === 'string') {
68
+ stack.push(child);
69
+ }
70
+ }
71
+ }
72
+ return found;
73
+ }
74
+
75
+ function bound(pattern, out = []) {
76
+ if (!pattern) return out;
77
+ switch (pattern.type) {
78
+ case 'Identifier':
79
+ out.push(pattern.name);
80
+ break;
81
+ case 'ObjectPattern':
82
+ for (const property of pattern.properties) bound(property.value ?? property.argument, out);
83
+ break;
84
+ case 'ArrayPattern':
85
+ for (const element of pattern.elements) bound(element, out);
86
+ break;
87
+ case 'RestElement':
88
+ bound(pattern.argument, out);
89
+ break;
90
+ case 'AssignmentPattern':
91
+ bound(pattern.left, out);
92
+ break;
93
+ default:
94
+ break;
95
+ }
96
+ return out;
97
+ }
98
+
99
+ function declared(declaration) {
100
+ if (declaration.type === 'VariableDeclaration') {
101
+ return declaration.declarations.flatMap((item) => bound(item.id));
102
+ }
103
+ return declaration.id ? [declaration.id.name] : [];
104
+ }
105
+
106
+ function imported(node, info) {
107
+ const names = new Set();
108
+ for (const item of node.specifiers) {
109
+ let name = ALL;
110
+ if (item.type === 'ImportDefaultSpecifier') name = 'default';
111
+ else if (item.type === 'ImportSpecifier') name = named(item.imported);
112
+ names.add(name);
113
+ info.bindings.set(item.local.name, { spec: node.source.value, name });
114
+ }
115
+ info.imports.push({ spec: node.source.value, names: names.size > 0 ? [...names] : [BODY] });
116
+ }
117
+
118
+ function exported(node, info) {
119
+ if (node.declaration) {
120
+ for (const name of declared(node.declaration)) info.locals.add(name);
121
+ return;
122
+ }
123
+ for (const item of node.specifiers) {
124
+ const local = named(item.local);
125
+ const name = named(item.exported);
126
+ if (node.source) info.reexports.set(name, { spec: node.source.value, name: local });
127
+ else info.aliases.set(name, local);
128
+ }
129
+ }
130
+
131
+ function exportedDefault(node, info) {
132
+ const { declaration } = node;
133
+ if (declaration.type === 'Identifier') info.aliases.set('default', declaration.name);
134
+ else info.locals.add('default');
135
+ }
136
+
137
+ const handlers = {
138
+ ImportDeclaration: imported,
139
+ ExportNamedDeclaration: exported,
140
+ ExportDefaultDeclaration: exportedDefault,
141
+ ExportAllDeclaration: (node, info) => {
142
+ if (node.exported) {
143
+ info.reexports.set(named(node.exported), { spec: node.source.value, name: ALL });
144
+ } else {
145
+ info.stars.push(node.source.value);
146
+ }
147
+ },
148
+ };
149
+
150
+ export function describe(ast, commonjs = false) {
151
+ const info = {
152
+ whole: commonjs || ast.sourceType !== 'module',
153
+ imports: [],
154
+ bindings: new Map(),
155
+ aliases: new Map(),
156
+ locals: new Set(),
157
+ reexports: new Map(),
158
+ stars: [],
159
+ dynamic: dynamics(ast),
160
+ };
161
+ for (const node of ast.body) handlers[node.type]?.(node, info);
162
+ for (const [name, local] of info.aliases) {
163
+ if (info.bindings.has(local)) info.reexports.set(name, info.bindings.get(local));
164
+ else info.locals.add(name);
165
+ }
166
+ return info;
167
+ }
package/unit/graph.mjs ADDED
@@ -0,0 +1,317 @@
1
+ import { readdirSync, readFileSync, statSync } from 'node:fs';
2
+ import { stripTypeScriptTypes } from 'node:module';
3
+ import { dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path';
4
+ import { parse } from 'acorn';
5
+ import { ALL, BODY, describe } from './exports.mjs';
6
+
7
+ export const code = /\.(m|c)?(j|t)sx?$/;
8
+ const tests = /\.test\.(m|c)?(j|t)sx?$/;
9
+ const typed = /\.(m|c)?tsx?$/;
10
+ const swaps = { '.js': ['.ts', '.tsx'], '.mjs': ['.mts'], '.cjs': ['.cts'], '.jsx': ['.tsx'] };
11
+ const suffixes = ['.mjs', '.js', '.ts', '.tsx', '.mts', '.cjs', '.cts', '.jsx'];
12
+
13
+ export class ParseError extends Error {}
14
+
15
+ const isFile = (path) => {
16
+ try {
17
+ return statSync(path).isFile();
18
+ } catch {
19
+ return false;
20
+ }
21
+ };
22
+
23
+ function walk(dir, found = []) {
24
+ let entries;
25
+ try {
26
+ entries = readdirSync(dir, { withFileTypes: true });
27
+ } catch {
28
+ return found;
29
+ }
30
+ for (const entry of entries) {
31
+ if (entry.name === 'node_modules' || entry.name.startsWith('.')) continue;
32
+ const path = join(dir, entry.name);
33
+ if (entry.isDirectory()) walk(path, found);
34
+ else if (entry.isFile()) found.push(path);
35
+ }
36
+ return found;
37
+ }
38
+
39
+ function quiet(fn) {
40
+ const emit = process.emitWarning;
41
+ process.emitWarning = () => undefined;
42
+ try {
43
+ return fn();
44
+ } finally {
45
+ process.emitWarning = emit;
46
+ }
47
+ }
48
+
49
+ function strip(source) {
50
+ return quiet(() => {
51
+ try {
52
+ return stripTypeScriptTypes(source);
53
+ } catch {
54
+ return stripTypeScriptTypes(source, { mode: 'transform' });
55
+ }
56
+ });
57
+ }
58
+
59
+ function program(file) {
60
+ const raw = readFileSync(file, 'utf8');
61
+ const source = typed.test(file) ? strip(raw) : raw;
62
+ const options = { ecmaVersion: 'latest', allowHashBang: true, allowAwaitOutsideFunction: true };
63
+ try {
64
+ return parse(source, { ...options, sourceType: 'module' });
65
+ } catch (error) {
66
+ if (!/\.c(j|t)s$/.test(file)) throw error;
67
+ return parse(source, { ...options, sourceType: 'script', allowReturnOutsideFunction: true });
68
+ }
69
+ }
70
+
71
+ function candidates(target) {
72
+ const ext = extname(target);
73
+ const base = target.slice(0, target.length - ext.length);
74
+ return [
75
+ target,
76
+ ...(swaps[ext] ?? []).map((swap) => base + swap),
77
+ ...suffixes.map((suffix) => target + suffix),
78
+ ...suffixes.map((suffix) => join(target, `index${suffix}`)),
79
+ ];
80
+ }
81
+
82
+ function skip(text, at) {
83
+ if (text[at] !== '/') return at;
84
+ if (text[at + 1] === '/') {
85
+ const end = text.indexOf('\n', at);
86
+ return end === -1 ? text.length : end;
87
+ }
88
+ if (text[at + 1] === '*') {
89
+ const end = text.indexOf('*/', at + 2);
90
+ return end === -1 ? text.length : end + 2;
91
+ }
92
+ return at;
93
+ }
94
+
95
+ function quoted(text, at) {
96
+ let end = at + 1;
97
+ while (end < text.length && text[end] !== '"') end += text[end] === '\\' ? 2 : 1;
98
+ return end + 1;
99
+ }
100
+
101
+ export function jsonc(text) {
102
+ let out = '';
103
+ let comma = false;
104
+ let at = 0;
105
+ while (at < text.length) {
106
+ const next = skip(text, at);
107
+ if (next !== at) {
108
+ at = next;
109
+ continue;
110
+ }
111
+ const char = text[at];
112
+ if (/\s/.test(char)) {
113
+ at += 1;
114
+ continue;
115
+ }
116
+ if (comma && char !== '}' && char !== ']') out += ',';
117
+ comma = char === ',';
118
+ if (comma) {
119
+ at += 1;
120
+ continue;
121
+ }
122
+ const end = char === '"' ? quoted(text, at) : at + 1;
123
+ out += text.slice(at, end);
124
+ at = end;
125
+ }
126
+ return JSON.parse(comma ? `${out},` : out);
127
+ }
128
+
129
+ function readJson(path) {
130
+ try {
131
+ return jsonc(readFileSync(path, 'utf8'));
132
+ } catch {
133
+ return undefined;
134
+ }
135
+ }
136
+
137
+ function tsconfigPaths(root, file = join(root, 'tsconfig.json'), seen = new Set()) {
138
+ if (seen.has(file)) return [];
139
+ seen.add(file);
140
+ const config = readJson(file);
141
+ if (!config) return [];
142
+ const dir = dirname(file);
143
+ const parents = [config.extends ?? []].flat().flatMap((parent) => {
144
+ const path = parent.startsWith('.') ? resolve(dir, parent) : join(root, 'node_modules', parent);
145
+ const json = path.endsWith('.json') ? path : `${path}.json`;
146
+ return tsconfigPaths(root, json, seen);
147
+ });
148
+ const options = config.compilerOptions ?? {};
149
+ if (!options.paths) return parents;
150
+ const base = resolve(dir, options.baseUrl ?? '.');
151
+ const own = Object.entries(options.paths).map(([pattern, targets]) => ({
152
+ pattern,
153
+ targets: targets.map((target) => resolve(base, target)),
154
+ }));
155
+ return [...own, ...parents];
156
+ }
157
+
158
+ function aliased(spec, aliases) {
159
+ for (const { pattern, targets } of aliases) {
160
+ const star = pattern.indexOf('*');
161
+ if (star === -1) {
162
+ if (spec === pattern) return targets;
163
+ continue;
164
+ }
165
+ const head = pattern.slice(0, star);
166
+ const tail = pattern.slice(star + 1);
167
+ if (spec.length >= head.length + tail.length && spec.startsWith(head) && spec.endsWith(tail)) {
168
+ const middle = spec.slice(head.length, spec.length - tail.length);
169
+ return targets.map((target) => target.replace('*', middle));
170
+ }
171
+ }
172
+ return [];
173
+ }
174
+
175
+ function resolver(root) {
176
+ const aliases = tsconfigPaths(root);
177
+ return (from, spec) => {
178
+ let targets;
179
+ if (spec.startsWith('.')) targets = [resolve(dirname(from), spec)];
180
+ else if (isAbsolute(spec)) targets = [spec];
181
+ else targets = aliased(spec, aliases);
182
+ const missing = [];
183
+ for (const target of targets) {
184
+ const options = candidates(target.split(/[?#]/)[0]);
185
+ const hit = options.find(isFile);
186
+ if (hit) return hit.includes(`${sep}node_modules${sep}`) ? undefined : { hit };
187
+ missing.push(...options);
188
+ }
189
+ return { missing };
190
+ };
191
+ }
192
+
193
+ function modules(root) {
194
+ const find = resolver(root);
195
+ const cache = new Map();
196
+ const load = (file) => {
197
+ if (!cache.has(file)) {
198
+ let info;
199
+ if (code.test(file)) {
200
+ try {
201
+ info = describe(program(file), /\.c(j|t)s$/.test(file));
202
+ } catch (error) {
203
+ throw new ParseError(`${relative(root, file)}: ${error.message}`);
204
+ }
205
+ }
206
+ cache.set(file, info);
207
+ }
208
+ return cache.get(file);
209
+ };
210
+ return { find, load };
211
+ }
212
+
213
+ function provider({ find, load }) {
214
+ const memo = new Map();
215
+ const provides = (file, name, stack = new Set()) => {
216
+ const key = `${file}\0${name}`;
217
+ if (memo.has(key)) return memo.get(key);
218
+ if (stack.has(key)) return false;
219
+ stack.add(key);
220
+ const info = load(file);
221
+ let answer;
222
+ if (!info || info.whole) answer = undefined;
223
+ else if (info.locals.has(name) || info.reexports.has(name)) answer = true;
224
+ else answer = starred(file, info, name, stack);
225
+ memo.set(key, answer);
226
+ return answer;
227
+ };
228
+ const starred = (file, info, name, stack) => {
229
+ let answer = false;
230
+ for (const spec of info.stars) {
231
+ const hit = find(file, spec)?.hit;
232
+ const own = hit ? provides(hit, name, stack) : undefined;
233
+ if (own === undefined) return undefined;
234
+ answer ||= own;
235
+ }
236
+ return answer;
237
+ };
238
+ return provides;
239
+ }
240
+
241
+ function reacher(graph) {
242
+ const { find } = graph;
243
+ const context = { find, provides: provider(graph) };
244
+ return (start) => {
245
+ const touched = new Set();
246
+ const seen = new Set();
247
+ const queue = [[start, BODY]];
248
+ const go = (file, spec, name) => {
249
+ const found = find(file, spec);
250
+ if (found?.hit) queue.push([found.hit, name]);
251
+ else if (found) for (const path of found.missing) touched.add(path);
252
+ };
253
+ while (queue.length > 0) {
254
+ const [file, name] = queue.pop();
255
+ const key = `${file}\0${name}`;
256
+ if (seen.has(key)) continue;
257
+ seen.add(key);
258
+ touched.add(file);
259
+ const info = graph.load(file);
260
+ if (!info) continue;
261
+ for (const [next, wanted, spec] of step(info, name, file, context)) {
262
+ if (spec === undefined) queue.push([next, wanted]);
263
+ else go(next, spec, wanted);
264
+ }
265
+ }
266
+ return touched;
267
+ };
268
+ }
269
+
270
+ function starred(file, info, name, { find, provides }) {
271
+ const targets = info.stars.map((spec) => find(file, spec)?.hit);
272
+ if (targets.some((target) => !target)) return [[file, ALL]];
273
+ const answers = targets.map((target) => provides(target, name));
274
+ if (answers.some((answer) => answer === undefined)) return [[file, ALL]];
275
+ const owners = targets.filter((_, index) => answers[index]);
276
+ return owners.length > 0 ? owners.map((target) => [target, name]) : [[file, ALL]];
277
+ }
278
+
279
+ function step(info, name, file, context) {
280
+ if (name === BODY) {
281
+ return [
282
+ ...info.imports.flatMap(({ spec, names }) => names.map((wanted) => [file, wanted, spec])),
283
+ ...info.dynamic.flatMap(({ spec, names }) => names.map((wanted) => [file, wanted, spec])),
284
+ ];
285
+ }
286
+ if (info.whole) return [[file, BODY]];
287
+ if (name === ALL) {
288
+ return [
289
+ [file, BODY],
290
+ ...[...info.reexports.values()].map(({ spec, name: wanted }) => [file, wanted, spec]),
291
+ ...info.stars.map((spec) => [file, ALL, spec]),
292
+ ];
293
+ }
294
+ if (info.locals.has(name)) return [[file, BODY]];
295
+ const again = info.reexports.get(name);
296
+ if (again) return [[file, again.name, again.spec]];
297
+ if (name === 'default' || info.stars.length === 0) return [[file, ALL]];
298
+ return starred(file, info, name, context);
299
+ }
300
+
301
+ export function select({ root, changed, since }) {
302
+ const unit = join(root, 'test', 'unit');
303
+ const files = walk(unit);
304
+ const all = files.filter((file) => tests.test(file));
305
+ const fresh = files.filter((file) => since === undefined || statSync(file).mtimeMs > since);
306
+ const touched = new Set([...changed.map((file) => resolve(root, file)), ...fresh]);
307
+ const reach = reacher(modules(root));
308
+ const reached = new Set(all.filter((test) => [...reach(test)].some((file) => touched.has(file))));
309
+ const posix = (file) => relative(root, file).split(sep).join('/');
310
+ return {
311
+ tests: all
312
+ .filter((file) => reached.has(file))
313
+ .map(posix)
314
+ .sort(),
315
+ total: all.length,
316
+ };
317
+ }
@@ -0,0 +1,9 @@
1
+ import { fileURLToPath } from 'node:url';
2
+
3
+ export const preload = fileURLToPath(new URL('select.cjs', import.meta.url));
4
+
5
+ export function inject(options = process.env.NODE_OPTIONS ?? '') {
6
+ if (options.includes(preload)) return options;
7
+ const flag = `--require ${/\s/.test(preload) ? `"${preload}"` : preload}`;
8
+ return options ? `${options} ${flag}` : flag;
9
+ }
package/unit/none.mjs ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,31 @@
1
+ 'use strict';
2
+ const { isAbsolute, join, matchesGlob, normalize, relative } = require('node:path');
3
+
4
+ const key = Symbol.for('slicc.unit.select');
5
+ const list = process.env.SLICC_UNIT_TESTS;
6
+
7
+ const inside = (file, pattern) => {
8
+ const path = normalize(isAbsolute(pattern) ? relative(process.cwd(), pattern) : pattern);
9
+ const dir = path.replace(/\/+$/, '');
10
+ return file === path || file.startsWith(`${dir}/`) || matchesGlob(file, path);
11
+ };
12
+
13
+ if (
14
+ list !== undefined &&
15
+ !globalThis[key] &&
16
+ process.execArgv.includes('--test') &&
17
+ !process.env.NODE_TEST_CONTEXT
18
+ ) {
19
+ globalThis[key] = true;
20
+ const patterns = process.argv.slice(1);
21
+ const chosen = list
22
+ .split('\n')
23
+ .filter(Boolean)
24
+ .map((file) => normalize(file))
25
+ .filter((file) => patterns.length === 0 || patterns.some((pattern) => inside(file, pattern)));
26
+ process.argv.splice(
27
+ 1,
28
+ Number.POSITIVE_INFINITY,
29
+ ...(chosen.length > 0 ? chosen : [join(__dirname, 'none.mjs')])
30
+ );
31
+ }