test-inventory 0.10.4 → 0.11.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 (49) hide show
  1. package/CHANGELOG.md +106 -0
  2. package/README.md +6 -4
  3. package/dist/cli.d.ts +1 -1
  4. package/dist/cli.js +18 -6
  5. package/dist/config-runs.d.ts +30 -4
  6. package/dist/config-runs.js +193 -38
  7. package/dist/config.d.ts +7 -6
  8. package/dist/config.js +260 -26
  9. package/dist/dependency-hash.d.ts +9 -1
  10. package/dist/dependency-hash.js +128 -13
  11. package/dist/diff.js +2 -0
  12. package/dist/extract.js +75 -17
  13. package/dist/files.js +2 -1
  14. package/dist/filter.js +1 -0
  15. package/dist/framework-version.d.ts +6 -0
  16. package/dist/framework-version.js +37 -9
  17. package/dist/frameworks/bindings.d.ts +9 -0
  18. package/dist/frameworks/bindings.js +28 -5
  19. package/dist/frameworks/bun.js +2 -2
  20. package/dist/frameworks/common.d.ts +12 -3
  21. package/dist/frameworks/common.js +30 -12
  22. package/dist/frameworks/jasmine.js +11 -3
  23. package/dist/frameworks/jest.js +11 -7
  24. package/dist/frameworks/mocha.js +3 -3
  25. package/dist/frameworks/node.js +6 -4
  26. package/dist/frameworks/playwright.d.ts +11 -3
  27. package/dist/frameworks/playwright.js +101 -32
  28. package/dist/frameworks/test-functions.d.ts +13 -7
  29. package/dist/frameworks/test-functions.js +41 -27
  30. package/dist/frameworks/vitest.js +11 -6
  31. package/dist/index.d.ts +2 -0
  32. package/dist/index.js +1 -0
  33. package/dist/model.d.ts +4 -1
  34. package/dist/node-scripts.d.ts +15 -1
  35. package/dist/node-scripts.js +140 -13
  36. package/dist/parse.d.ts +3 -0
  37. package/dist/parse.js +33 -0
  38. package/dist/records.js +7 -4
  39. package/dist/resolve.d.ts +3 -1
  40. package/dist/resolve.js +48 -15
  41. package/dist/run-commands.d.ts +20 -0
  42. package/dist/run-commands.js +107 -0
  43. package/dist/scan.js +15 -5
  44. package/dist/types.d.ts +9 -1
  45. package/dist/values.d.ts +21 -3
  46. package/dist/values.js +112 -13
  47. package/package.json +1 -1
  48. package/schema/diff-v1.json +12 -1
  49. package/schema/v1.json +9 -1
package/dist/index.js CHANGED
@@ -3,3 +3,4 @@ export { diffInventories } from "./diff.js";
3
3
  export { formatDiffMarkdown } from "./diff-markdown.js";
4
4
  export { scanSource } from "./scan-source.js";
5
5
  export { filterInventory, pickTestFields } from "./filter.js";
6
+ export { runCommands } from "./run-commands.js";
package/dist/model.d.ts CHANGED
@@ -83,7 +83,10 @@ interface Declaration {
83
83
  skipPassedDown?: number;
84
84
  details: Details;
85
85
  fn: FunctionNode | null;
86
- /** The function whose code is hashed: `fn`, or a function declared in the file and passed by name. */
86
+ /**
87
+ * The function whose code is hashed: `fn`, a function declared in the file and passed by name, or the one function a
88
+ * wrapper call receives, as in `test('fills an order', withBroker(async () => {}))`.
89
+ */
87
90
  hashed: FunctionNode | null;
88
91
  isParameterized: boolean;
89
92
  /** Number of cases of `.each` or `.for` when the table is written out; null otherwise. */
@@ -10,7 +10,7 @@ export declare function nodeTestCommands(script: string, setups?: boolean): stri
10
10
  */
11
11
  export declare function scriptsRunBy(scripts: Record<string, unknown>, name: string): string[];
12
12
  /** The runners a script can start with a config of its own, which the scan then takes as one more that runs files. */
13
- export type ScriptRunner = 'vitest' | 'jest' | 'playwright' | 'cypress' | 'webdriverio';
13
+ export type ScriptRunner = 'vitest' | 'jest' | 'playwright' | 'cypress' | 'webdriverio' | 'mocha';
14
14
  /** A command of a script that starts a test runner. */
15
15
  export interface RunnerCommand {
16
16
  /** The config it names, as written; null when it names none. */
@@ -19,9 +19,23 @@ export interface RunnerCommand {
19
19
  root: string | null;
20
20
  /** Whether it names its config or root in a way the scan can't read: a variable, or Jest's inline JSON. */
21
21
  unreadable: boolean;
22
+ /** For Mocha, which takes its files and settings from them, the words after the program. */
23
+ args?: string[];
22
24
  }
23
25
  /**
24
26
  * The commands of a package.json script that start a runner, with the config and root each names. Only a command whose
25
27
  * program is the runner counts, so `eslint --plugin jest -c .eslintrc.json` and `npm run jest` start none.
26
28
  */
27
29
  export declare function runnerCommands(script: string, runner: ScriptRunner): RunnerCommand[];
30
+ /** What a Mocha command line gives: the specs, positional or `--spec`, and each option's values, aliases resolved. */
31
+ export interface MochaArguments {
32
+ positional: string[];
33
+ /** Values by option name, in order; a flag has none. */
34
+ options: Map<string, string[]>;
35
+ }
36
+ /**
37
+ * Reads a Mocha command line as Mocha does: an option written `--name value` or `--name=value`, a list option given
38
+ * more than once or, but for `spec` and `ignore`, split at commas; any other word is a spec. A flag it doesn't know
39
+ * takes no value.
40
+ */
41
+ export declare function mochaArguments(args: readonly string[]): MochaArguments;
@@ -94,9 +94,10 @@ export function nodeTestCommands(script, setups = false) {
94
94
  }
95
95
  /** The commands of a script, each as its words, without quotes. */
96
96
  function commandsOf(script) {
97
+ // A word is quoted in whole or in part, as `--server-args="-screen 0 1280x1024x24"`, and the shell drops the quotes.
97
98
  return script
98
99
  .split(/&&|\|\||[;|]/)
99
- .map((command) => [...command.matchAll(/'([^']*)'|"([^"]*)"|(\S+)/g)].map((match) => match[1] ?? match[2] ?? match[3]));
100
+ .map((command) => [...command.matchAll(/(?:[^\s'"]+|'[^']*'|"[^"]*")+/g)].map(([word]) => word.replaceAll(/'([^']*)'|"([^"]*)"/g, '$1$2')));
100
101
  }
101
102
  /**
102
103
  * A package.json script and those it runs in turn, each once: through `npm run`, `npm test`, `pnpm`, `yarn`,
@@ -143,20 +144,48 @@ function calledScripts(words, names) {
143
144
  return first === 'run' ? [second] : [first];
144
145
  return [];
145
146
  }
146
- /** Each runner's program, the subcommands that run tests, and the options that name its config and its root. */
147
+ /**
148
+ * Each runner's programs, with the subcommands that run tests (null for none), and the options that name its config and
149
+ * its root. Currents' `pwc` and `pwc-p` start Playwright with the options they are given, and its `cypress-cloud` runs
150
+ * Cypress with Cypress's own options.
151
+ */
147
152
  const RUNNERS = {
148
- vitest: { program: 'vitest', subcommands: null, config: ['--config', '-c'], root: ['--root', '-r'] },
149
- jest: { program: 'jest', subcommands: null, config: ['--config', '-c'], root: [] },
150
- playwright: { program: 'playwright', subcommands: ['test'], config: ['--config', '-c'], root: [] },
153
+ vitest: { programs: { vitest: null }, config: ['--config', '-c'], root: ['--root', '-r'] },
154
+ jest: { programs: { jest: null }, config: ['--config', '-c'], root: [] },
155
+ playwright: { programs: { playwright: ['test'], pwc: null, 'pwc-p': null }, config: ['--config', '-c'], root: [] },
151
156
  cypress: {
152
- program: 'cypress',
153
- subcommands: ['run', 'open'],
157
+ programs: { cypress: ['run', 'open'], 'cypress-cloud': null },
154
158
  config: ['--config-file', '-C'],
155
159
  root: ['--project', '-P'],
156
160
  },
157
161
  // `wdio run <config>` and `wdio <config>` take the config as the first argument.
158
- webdriverio: { program: 'wdio', subcommands: null, config: [], root: [] },
162
+ webdriverio: { programs: { wdio: null }, config: [], root: [] },
163
+ mocha: { programs: { mocha: null, _mocha: null, 'ts-mocha': null }, config: ['--config'], root: [] },
159
164
  };
165
+ /** The programs a coverage tool starts the command after it with: the runners', and those that start one in turn. */
166
+ const STARTERS = new Set([
167
+ ...Object.values(RUNNERS).flatMap((runner) => Object.keys(runner.programs)),
168
+ 'node',
169
+ 'npx',
170
+ 'pnpm',
171
+ 'yarn',
172
+ 'bunx',
173
+ ]);
174
+ /** The options of `xvfb-run` written with their value as the next word. */
175
+ const XVFB_VALUE_OPTIONS = new Set([
176
+ '-n',
177
+ '-s',
178
+ '-e',
179
+ '-f',
180
+ '-p',
181
+ '-w',
182
+ '--server-num',
183
+ '--server-args',
184
+ '--error-file',
185
+ '--auth-file',
186
+ '--xauth-protocol',
187
+ '--wait',
188
+ ]);
160
189
  /** The program each package's files start when `node` runs them. */
161
190
  const RUNNER_PACKAGES = {
162
191
  vitest: 'vitest',
@@ -166,18 +195,20 @@ const RUNNER_PACKAGES = {
166
195
  playwright: 'playwright',
167
196
  cypress: 'cypress',
168
197
  '@wdio/cli': 'wdio',
198
+ mocha: 'mocha',
169
199
  };
170
200
  /**
171
201
  * The commands of a package.json script that start a runner, with the config and root each names. Only a command whose
172
202
  * program is the runner counts, so `eslint --plugin jest -c .eslintrc.json` and `npm run jest` start none.
173
203
  */
174
204
  export function runnerCommands(script, runner) {
175
- const { program, subcommands, config, root } = RUNNERS[runner];
205
+ const { programs, config, root } = RUNNERS[runner];
176
206
  const found = [];
177
207
  for (const words of commandsOf(script)) {
178
208
  const started = programOf(words);
179
- if (started?.program !== program)
209
+ if (!started || !Object.hasOwn(programs, started.program))
180
210
  continue;
211
+ const subcommands = programs[started.program];
181
212
  let args = started.args;
182
213
  if (subcommands) {
183
214
  if (!subcommands.includes(args[0]))
@@ -185,6 +216,8 @@ export function runnerCommands(script, runner) {
185
216
  args = args.slice(1);
186
217
  }
187
218
  const command = { config: null, root: null, unreadable: false };
219
+ if (runner === 'mocha')
220
+ command.args = args;
188
221
  if (runner === 'webdriverio') {
189
222
  const first = args.at(0) === 'run' ? args.at(1) : args.at(0);
190
223
  if (first !== undefined && !first.startsWith('-'))
@@ -210,9 +243,9 @@ export function runnerCommands(script, runner) {
210
243
  return found;
211
244
  }
212
245
  /**
213
- * The program a command starts, with its arguments: past variables set before it, `cross-env`, `dotenv --`, and `npx`,
214
- * `bunx`, `pnpm exec`, `yarn exec`, `npm exec` or a package manager given a binary's name; for `node`, the runner whose
215
- * package holds the file it runs. Null when there is none.
246
+ * The program a command starts, with its arguments: past variables set before it, `cross-env`, `dotenv --`,
247
+ * `xvfb-run` and `xvfb-maybe`, the coverage tools `nyc`, `c8` and `mcr`, and `npx`, `bunx`, `pnpm exec`, `yarn exec`, `npm exec` or a package manager given a
248
+ * binary's name; for `node`, the runner whose package holds the file it runs. Null when there is none.
216
249
  */
217
250
  function programOf(words) {
218
251
  let index = 0;
@@ -232,6 +265,22 @@ function programOf(words) {
232
265
  const end = words.indexOf('--', index);
233
266
  index = end === -1 ? index + 2 : end + 1;
234
267
  }
268
+ else if (word === 'xvfb-run') {
269
+ // Its options before the command, some of which take the next word as their value.
270
+ index++;
271
+ while (words.at(index)?.startsWith('-'))
272
+ index += XVFB_VALUE_OPTIONS.has(words[index]) ? 2 : 1;
273
+ }
274
+ else if (word === 'xvfb-maybe') {
275
+ index += next === '--' ? 2 : 1;
276
+ }
277
+ else if (word === 'nyc' || word === 'c8' || word === 'mcr') {
278
+ // A coverage tool's options can take values, so its command starts at the first program that starts one.
279
+ const start = words.findIndex((item, at) => at > index && STARTERS.has(item.split(/[/\\]/).at(-1)));
280
+ if (start === -1)
281
+ return null;
282
+ index = start;
283
+ }
235
284
  else if (word === 'npx' || word === 'bunx') {
236
285
  index++;
237
286
  skip((item) => item.startsWith('-'));
@@ -262,3 +311,81 @@ function programOf(words) {
262
311
  const name = word.split(/[/\\]/).at(-1);
263
312
  return { program: name.replace(/\.(cmd|exe|[cm]?js)$/, ''), args: words.slice(index + 1) };
264
313
  }
314
+ /** Mocha's options that take a value, by name and alias, from its `run-option-metadata`. */
315
+ const MOCHA_VALUES = {
316
+ config: 'config',
317
+ extension: 'extension',
318
+ file: 'file',
319
+ global: 'global',
320
+ globals: 'global',
321
+ ignore: 'ignore',
322
+ exclude: 'ignore',
323
+ 'node-option': 'node-option',
324
+ n: 'node-option',
325
+ 'reporter-option': 'reporter-option',
326
+ 'reporter-options': 'reporter-option',
327
+ O: 'reporter-option',
328
+ require: 'require',
329
+ r: 'require',
330
+ spec: 'spec',
331
+ 'watch-files': 'watch-files',
332
+ 'watch-ignore': 'watch-ignore',
333
+ fgrep: 'fgrep',
334
+ f: 'fgrep',
335
+ grep: 'grep',
336
+ g: 'grep',
337
+ package: 'package',
338
+ reporter: 'reporter',
339
+ R: 'reporter',
340
+ ui: 'ui',
341
+ u: 'ui',
342
+ slow: 'slow',
343
+ s: 'slow',
344
+ timeout: 'timeout',
345
+ timeouts: 'timeout',
346
+ t: 'timeout',
347
+ retries: 'retries',
348
+ jobs: 'jobs',
349
+ j: 'jobs',
350
+ };
351
+ /** The flags Mocha's options take, aliases resolved, that change which files run. */
352
+ const MOCHA_FLAGS = {
353
+ recursive: 'recursive',
354
+ 'no-config': 'no-config',
355
+ 'no-package': 'no-package',
356
+ };
357
+ /**
358
+ * Reads a Mocha command line as Mocha does: an option written `--name value` or `--name=value`, a list option given
359
+ * more than once or, but for `spec` and `ignore`, split at commas; any other word is a spec. A flag it doesn't know
360
+ * takes no value.
361
+ */
362
+ export function mochaArguments(args) {
363
+ const positional = [];
364
+ const options = new Map();
365
+ for (let index = 0; index < args.length; index++) {
366
+ const word = args[index];
367
+ if (word === '--') {
368
+ positional.push(...args.slice(index + 1));
369
+ break;
370
+ }
371
+ const option = /^--?([^=]+)(?:=(.*))?$/s.exec(word);
372
+ if (!option || word === '-') {
373
+ positional.push(word);
374
+ continue;
375
+ }
376
+ const name = option[1];
377
+ const valued = MOCHA_VALUES[name];
378
+ if (valued === undefined) {
379
+ const flag = MOCHA_FLAGS[name];
380
+ if (flag !== undefined)
381
+ options.set(flag, []);
382
+ continue;
383
+ }
384
+ const value = option.at(2) ?? args.at(++index);
385
+ if (value === undefined)
386
+ break;
387
+ const values = valued === 'spec' || valued === 'ignore' ? [value] : value.split(',');
388
+ options.set(valued, [...(options.get(valued) ?? []), ...values]);
389
+ }
390
+ return { positional, options };
391
+ }
package/dist/parse.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { type OxcError, type Program } from 'oxc-parser';
2
+ import type { Span } from './model.ts';
2
3
  import { SourceText } from './source.ts';
3
4
  export interface ParsedFile {
4
5
  source: SourceText;
@@ -23,4 +24,6 @@ export interface ParsedFile {
23
24
  export declare function tooDeeplyNested(text: string, limit: number): number | null;
24
25
  /** The first parser error, located at its first label, or at the start of the file when it has none. */
25
26
  export declare function firstError(errors: readonly OxcError[]): ParsedFile['error'];
27
+ /** The first node nested more than `limit` deep, the program's statements being 1 deep; null when there is none. */
28
+ export declare function tooDeepTree(program: Program, limit: number): Span | null;
26
29
  export declare function parseFile(fileName: string, code: string): ParsedFile;
package/dist/parse.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { parseSync } from 'oxc-parser';
2
+ import { childNodes } from "./ast.js";
2
3
  import { SourceText } from "./source.js";
3
4
  function parserOptions(fileName) {
4
5
  const extension = /\.[cm]?[jt]sx?$/.exec(fileName)?.[0] ?? '.ts';
@@ -13,6 +14,11 @@ function parserOptions(fileName) {
13
14
  * development dependencies, minified bundles included, the deepest nests 34.
14
15
  */
15
16
  const MAX_NESTING = 500;
17
+ /**
18
+ * How deep the syntax tree may nest. The scan walks it recursively: a chain of 1,000 calls, 2,000 levels deep, overflows
19
+ * Node.js's default stack. Of 447,597 test files in 2,500 popular projects, the deepest nests 270.
20
+ */
21
+ const MAX_DEPTH = 1000;
16
22
  /** Words after which a `/` starts a regular expression rather than a division. */
17
23
  const BEFORE_REGEX = new Set([
18
24
  'return',
@@ -209,6 +215,20 @@ export function firstError(errors) {
209
215
  const label = first.labels.at(0);
210
216
  return { message: first.message, start: label?.start ?? 0, end: label?.end ?? 0 };
211
217
  }
218
+ /** The first node nested more than `limit` deep, the program's statements being 1 deep; null when there is none. */
219
+ export function tooDeepTree(program, limit) {
220
+ // A stack of its own, as the walk that measures how deep the tree goes can't recurse that deep either.
221
+ const stack = [[program, 0]];
222
+ for (let item = stack.pop(); item; item = stack.pop()) {
223
+ const [node, depth] = item;
224
+ if (depth > limit)
225
+ return node;
226
+ // Pushed last to first, so the first node too deep is the first in the code.
227
+ for (const child of childNodes(node).reverse())
228
+ stack.push([child, depth + 1]);
229
+ }
230
+ return null;
231
+ }
212
232
  export function parseFile(fileName, code) {
213
233
  // A byte order mark is not part of the code, and editors don't count it as a column.
214
234
  const text = code.charCodeAt(0) === 0xfeff ? code.slice(1) : code;
@@ -238,6 +258,19 @@ export function parseFile(fileName, code) {
238
258
  error: { message: error.message, start: 0, end: 0 },
239
259
  };
240
260
  }
261
+ const deep = tooDeepTree(program, MAX_DEPTH);
262
+ if (deep) {
263
+ return {
264
+ source: new SourceText(text),
265
+ program: parseSync(fileName, '', parserOptions(fileName)).program,
266
+ comments: [],
267
+ error: {
268
+ message: `Expressions are nested more than ${MAX_DEPTH} deep, too deep to read safely`,
269
+ start: deep.start,
270
+ end: deep.end,
271
+ },
272
+ };
273
+ }
241
274
  return {
242
275
  source: new SourceText(text),
243
276
  program,
package/dist/records.js CHANGED
@@ -559,7 +559,8 @@ class RecordBuilder {
559
559
  bodyHash: declaration.hashed ? hashNodes([declaration.hashed]) : null,
560
560
  dependencyHash: dependencies.hash,
561
561
  dependencies: dependencies.files,
562
- hasUnfollowedDependencies: !dependencies.isComplete,
562
+ hasUnfollowedDependencies: dependencies.unfollowed.length > 0,
563
+ unfollowedDependencies: dependencies.unfollowed,
563
564
  suiteId: describes.length > 0 ? this.suiteIds.get(describes[describes.length - 1]) : null,
564
565
  parentTestId: null,
565
566
  suitePath,
@@ -647,11 +648,13 @@ class RecordBuilder {
647
648
  if (test.declaration.title.isDynamic)
648
649
  continue;
649
650
  const describes = outward(test.scope).filter((scope) => scope.kind === 'describe');
651
+ // A describe title the scan can't work out keeps its source text, the same on every pass of a loop, while the
652
+ // runner's titles differ.
653
+ if (playwright && describes.some((scope) => suiteOf(scope).declaration.title?.isDynamic))
654
+ continue;
650
655
  const titles = describes.flatMap((scope) => suiteOf(scope).declaration.title?.text ?? []).reverse();
651
656
  // In a loop, a title path that never changes is registered again on each pass.
652
- const repeated = playwright &&
653
- test.passes.some((passes) => passes !== null && passes > 1) &&
654
- describes.every((scope) => !suiteOf(scope).declaration.title?.isDynamic);
657
+ const repeated = playwright && test.passes.some((passes) => passes !== null && passes > 1);
655
658
  if (repeated) {
656
659
  const message = 'The test is declared in a loop with the same title on each pass, so Playwright fails to load the file and runs no tests at all.';
657
660
  const item = problem('duplicate-title', test.site ?? test.call, message, test.declaration.title.text);
package/dist/resolve.d.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  import type { ModuleReader } from './model.ts';
2
+ /** The file a path refers to, found the way TypeScript and Node do: as is, with an extension, or a folder's index. */
3
+ export declare function findFile(base: string): string | null;
2
4
  /** Parses JSON written with comments and trailing commas, as tsconfig files often are; null when it isn't JSON. */
3
5
  export declare function parseJsonc(text: string): unknown;
4
6
  /**
@@ -26,7 +28,7 @@ export interface ImportMap {
26
28
  /**
27
29
  * Returns a reader for the modules a test file imports. It follows the import map of the config the file runs with,
28
30
  * relative paths, tsconfig `paths` and `baseUrl` from the tsconfig nearest the importing file, package.json `imports`
29
- * (`#name`), and workspace packages whose entry is TypeScript source. Each module it reads carries a reader for the
31
+ * (`#name`), and workspace packages to their source. Each module it reads carries a reader for the
30
32
  * modules that module imports in turn, with the same import map.
31
33
  */
32
34
  export declare function moduleResolver(root: string): (fromFile: string, map?: ImportMap | null) => ModuleReader;
package/dist/resolve.js CHANGED
@@ -4,11 +4,12 @@ import path from 'node:path';
4
4
  import { globSync } from 'tinyglobby';
5
5
  const EXTENSIONS = ['.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs'];
6
6
  const TYPESCRIPT_SOURCE = /(?<!\.d)\.[cm]?tsx?$/;
7
+ const JAVASCRIPT = /\.[cm]?jsx?$/;
7
8
  function isFile(file) {
8
9
  return existsSync(file) && statSync(file).isFile();
9
10
  }
10
11
  /** The file a path refers to, found the way TypeScript and Node do: as is, with an extension, or a folder's index. */
11
- function findFile(base) {
12
+ export function findFile(base) {
12
13
  const stripped = base.replace(/\.(?:[cm]?js|jsx)$/, '');
13
14
  const candidates = [
14
15
  base,
@@ -193,7 +194,10 @@ function aliasFiles(specifier, options) {
193
194
  return null;
194
195
  return targetStrings(options.paths[match.key]).map((target) => path.resolve(options.pathsBase, target.replaceAll('${configDir}', options.configDir).replaceAll('*', match.star)));
195
196
  }
196
- /** Files a `#name` import may stand for, from `imports` in the nearest package.json. */
197
+ /**
198
+ * Files a `#name` import may stand for, from `imports` in the nearest package.json. A target in build output is taken
199
+ * from the source next to it first, as for a workspace package.
200
+ */
197
201
  function subpathImportFiles(specifier, directory) {
198
202
  for (let folder = directory;; folder = path.dirname(folder)) {
199
203
  const manifest = readJson(path.join(folder, 'package.json'));
@@ -202,7 +206,10 @@ function subpathImportFiles(specifier, directory) {
202
206
  const match = imports ? matchPattern(Object.keys(imports), specifier) : null;
203
207
  if (!match || !imports)
204
208
  return [];
205
- return targetStrings(imports[match.key]).map((target) => path.resolve(folder, target.replaceAll('*', match.star)));
209
+ return targetStrings(imports[match.key]).flatMap((target) => {
210
+ const filled = target.replaceAll('*', match.star);
211
+ return [...sourceOf(filled), filled].map((file) => path.resolve(folder, file));
212
+ });
206
213
  }
207
214
  if (path.dirname(folder) === folder)
208
215
  return [];
@@ -212,19 +219,27 @@ const BUILD_FOLDERS = new Set(['dist', 'build', 'lib', 'out']);
212
219
  const FORMAT_FOLDERS = new Set(['esm', 'cjs', 'es', 'mjs', 'umd', 'types']);
213
220
  /**
214
221
  * Where the TypeScript source of a built file usually is, for a workspace package that hasn't been built: both
215
- * `dist/esm/index.js` and `dist/types/index.d.ts` come from `src/index.ts`.
222
+ * `dist/esm/index.js` and `dist/types/index.d.ts` come from `src/index.ts`, or from `index.ts` in a package without a
223
+ * `src` folder.
216
224
  */
217
225
  function sourceOf(target) {
218
226
  const parts = target.replace(/^\.\//, '').split('/');
219
227
  if (parts.length < 2 || !BUILD_FOLDERS.has(parts[0]))
220
228
  return [];
221
229
  const rest = parts.length > 2 && FORMAT_FOLDERS.has(parts[1]) ? parts.slice(2) : parts.slice(1);
222
- const base = ['src', ...rest].join('/').replace(/(\.d)?\.[cm]?[jt]sx?$/, '');
223
- return [`${base}.ts`, `${base}.tsx`];
230
+ const base = rest.join('/').replace(/(\.d)?\.[cm]?[jt]sx?$/, '');
231
+ return [`src/${base}.ts`, `src/${base}.tsx`, `${base}.ts`, `${base}.tsx`];
232
+ }
233
+ /** Whether a path in a package is in a folder builds write to, as `dist/index.js` and `esm/index.js` are. */
234
+ function isBuilt(target) {
235
+ const first = target.replace(/^\.[\\/]/, '').split(/[\\/]/)[0];
236
+ return BUILD_FOLDERS.has(first) || FORMAT_FOLDERS.has(first);
224
237
  }
225
238
  /**
226
- * The TypeScript source a package's exports, types or main point to for a subpath such as `.` or `./fixtures`. When they
227
- * point to build output, the source next to it is used, as in a workspace package that hasn't been built.
239
+ * The source a package's exports, types or main point to for a subpath such as `.` or `./fixtures`: TypeScript first,
240
+ * then JavaScript outside build folders, which a package written in JavaScript runs as it is. When they point to build
241
+ * output, the source next to it is used, as in a workspace package that hasn't been built; built JavaScript itself is
242
+ * not followed, as a change to its source would not reach it until the next build.
228
243
  */
229
244
  function packageEntry(folder, subpath) {
230
245
  const manifest = readJson(path.join(folder, 'package.json'));
@@ -236,17 +251,26 @@ function packageEntry(folder, subpath) {
236
251
  const match = matchPattern(Object.keys(map), subpath);
237
252
  targets = match ? targetStrings(map[match.key]).map((target) => target.replaceAll('*', match.star)) : [];
238
253
  }
254
+ else if (exports === undefined && subpath !== '.') {
255
+ // Without exports, a subpath is a file in the package, as `@trading/test-utils/src/fixtures.ts` is.
256
+ const file = findFile(path.resolve(folder, subpath));
257
+ targets = [file ? path.relative(folder, file) : subpath];
258
+ }
239
259
  else {
240
260
  targets = subpath === '.' ? targetStrings(exports) : [];
241
261
  }
242
262
  if (subpath === '.')
243
263
  targets.push(...targetStrings(manifest?.types), ...targetStrings(manifest?.main));
244
- const file = [...targets.filter((target) => TYPESCRIPT_SOURCE.test(target)), ...targets.flatMap(sourceOf)]
264
+ const file = [
265
+ ...targets.filter((target) => TYPESCRIPT_SOURCE.test(target)),
266
+ ...targets.flatMap(sourceOf),
267
+ ...targets.filter((target) => JAVASCRIPT.test(target) && !isBuilt(target)),
268
+ ]
245
269
  .map((target) => path.resolve(folder, target))
246
270
  .find(isFile);
247
271
  return file
248
272
  ? { file }
249
- : { reason: "is a workspace package whose exports, types and main don't point to TypeScript source" };
273
+ : { reason: "is a workspace package whose exports, types and main don't point to source code" };
250
274
  }
251
275
  /**
252
276
  * The `packages` list of a pnpm-workspace.yaml, as a block list or a flow list. The file holds little more than this
@@ -303,7 +327,7 @@ function workspaceAt(folder) {
303
327
  return packages;
304
328
  }
305
329
  /**
306
- * A workspace package followed to its TypeScript source: through its link in node_modules, or, before an install, from
330
+ * A workspace package followed to its source: through its link in node_modules, or, before an install, from
307
331
  * the packages the workspace lists. A package installed from a registry is not followed.
308
332
  */
309
333
  function workspaceSource(specifier, directory, packagesOf) {
@@ -323,6 +347,8 @@ function workspaceSource(specifier, directory, packagesOf) {
323
347
  const local = packagesOf(directory).get(name);
324
348
  return local ? packageEntry(local, subpath) : null;
325
349
  }
350
+ /** Why a bare name is not followed when it is no local file: it is taken to be an installed package. */
351
+ const NOT_LOCAL = 'is not a local file, a path alias or a workspace package';
326
352
  /** A file a bare name stands for in the folders an import map adds; null when none has it. */
327
353
  function searched(specifier, directory, map) {
328
354
  const folders = [...map.paths];
@@ -352,7 +378,7 @@ function mapped(specifier, alias) {
352
378
  /**
353
379
  * Returns a reader for the modules a test file imports. It follows the import map of the config the file runs with,
354
380
  * relative paths, tsconfig `paths` and `baseUrl` from the tsconfig nearest the importing file, package.json `imports`
355
- * (`#name`), and workspace packages whose entry is TypeScript source. Each module it reads carries a reader for the
381
+ * (`#name`), and workspace packages to their source. Each module it reads carries a reader for the
356
382
  * modules that module imports in turn, with the same import map.
357
383
  */
358
384
  export function moduleResolver(root) {
@@ -422,7 +448,7 @@ export function moduleResolver(root) {
422
448
  return { reason: targets ? 'could not be read' : 'is a path alias that no tsconfig paths or config define' };
423
449
  }
424
450
  if (!file)
425
- return { reason: 'is not a local file, a path alias or a workspace package' };
451
+ return { reason: NOT_LOCAL };
426
452
  candidates = [file];
427
453
  }
428
454
  }
@@ -432,7 +458,8 @@ export function moduleResolver(root) {
432
458
  const shown = (name) => (path.isAbsolute(name) ? path.relative(root, name).replaceAll('\\', '/') : name);
433
459
  const reader = (fromFile, map = null) => (specifier) => {
434
460
  const directory = path.dirname(fromFile);
435
- const aliased = map?.aliases.map((alias) => mapped(specifier, alias)).find((names) => names !== null);
461
+ const alias = map?.aliases.find((item) => mapped(specifier, item) !== null);
462
+ const aliased = alias && mapped(specifier, alias);
436
463
  if (aliased?.length === 0)
437
464
  return { reason: 'has a config alias whose replacement could not be worked out' };
438
465
  // Vite takes `/src/x` from its root first, unless it is already a path inside the root.
@@ -443,9 +470,15 @@ export function moduleResolver(root) {
443
470
  const located = (aliased?.flatMap(fromRoot) ?? [specifier]).map((name) => locate(name, directory, map));
444
471
  const found = located.find((item) => typeof item === 'string');
445
472
  if (found === undefined) {
473
+ const reasons = located;
474
+ // Jest resolves what moduleNameMapper gives as it does an import, so a package there, as next/jest's mocks or
475
+ // `identity-obj-proxy`, is left out as an imported package is.
476
+ const isPackage = alias?.replacesName && reasons.some((item) => item.reason === NOT_LOCAL);
477
+ if (isPackage)
478
+ return { reason: NOT_LOCAL };
446
479
  return aliased
447
480
  ? { reason: `is mapped by the config to ${aliased.map(shown).join(' or ')}, which could not be read` }
448
- : located[0];
481
+ : reasons[0];
449
482
  }
450
483
  let known = modules.get(map);
451
484
  if (!known) {
@@ -0,0 +1,20 @@
1
+ import type { Inventory } from './types.ts';
2
+ /** A command line that runs some test files of an inventory with their runner, config and projects. */
3
+ export interface RunCommand {
4
+ /** The config the files run with, from the project root; null when the scan found none. */
5
+ config: string | null;
6
+ /** The projects of the config that run the files, as the command selects them; `[]` to run every project. */
7
+ projects: string[];
8
+ /** The test files, sorted. */
9
+ files: string[];
10
+ /** The command line, to run from the project root in a POSIX shell. */
11
+ command: string;
12
+ /** What the command runs beyond `files` or why it can't run them as it is; null otherwise. */
13
+ caveat: string | null;
14
+ }
15
+ /**
16
+ * The commands that run the tests an inventory keeps, as after `filterInventory()` with `related`: one for each config,
17
+ * and for Cypress one for each testing type, with the projects that run the tests, sorted by config. A test whose
18
+ * projects are unknown runs in every project of its config.
19
+ */
20
+ export declare function runCommands(inventory: Inventory): RunCommand[];