test-inventory 0.12.1 → 0.12.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.
Files changed (56) hide show
  1. package/CHANGELOG.md +141 -0
  2. package/README.md +74 -49
  3. package/dist/ast.d.ts +7 -2
  4. package/dist/ast.js +43 -3
  5. package/dist/case-titles.d.ts +5 -11
  6. package/dist/case-titles.js +69 -55
  7. package/dist/config-runs.d.ts +19 -2
  8. package/dist/config-runs.js +379 -90
  9. package/dist/config.d.ts +0 -5
  10. package/dist/config.js +0 -7
  11. package/dist/dependency-hash.js +1 -32
  12. package/dist/diagnostics.js +17 -2
  13. package/dist/diff.d.ts +2 -45
  14. package/dist/extract.d.ts +13 -3
  15. package/dist/extract.js +837 -89
  16. package/dist/frameworks/bun.js +47 -24
  17. package/dist/frameworks/common.d.ts +4 -2
  18. package/dist/frameworks/common.js +10 -11
  19. package/dist/frameworks/jasmine-registration.d.ts +47 -0
  20. package/dist/frameworks/jasmine-registration.js +632 -0
  21. package/dist/frameworks/jasmine.d.ts +7 -1
  22. package/dist/frameworks/jasmine.js +65 -70
  23. package/dist/frameworks/jest.d.ts +2 -2
  24. package/dist/frameworks/jest.js +126 -51
  25. package/dist/frameworks/vitest.d.ts +2 -3
  26. package/dist/frameworks/vitest.js +80 -16
  27. package/dist/generator-steps.d.ts +56 -0
  28. package/dist/generator-steps.js +254 -0
  29. package/dist/model.d.ts +37 -5
  30. package/dist/mutation-arrays.d.ts +25 -0
  31. package/dist/mutation-arrays.js +229 -0
  32. package/dist/mutation-calls.d.ts +33 -0
  33. package/dist/mutation-calls.js +774 -0
  34. package/dist/mutation-order.d.ts +19 -0
  35. package/dist/mutation-order.js +55 -0
  36. package/dist/mutation-references.d.ts +109 -0
  37. package/dist/mutation-references.js +462 -0
  38. package/dist/mutation-returns.d.ts +13 -0
  39. package/dist/mutation-returns.js +71 -0
  40. package/dist/node-scripts.d.ts +4 -1
  41. package/dist/node-scripts.js +77 -11
  42. package/dist/options.d.ts +2 -0
  43. package/dist/options.js +6 -1
  44. package/dist/records.d.ts +5 -3
  45. package/dist/records.js +81 -28
  46. package/dist/scan-file.d.ts +18 -4
  47. package/dist/scan-file.js +44 -5
  48. package/dist/scan-source.js +2 -1
  49. package/dist/scan.js +30 -13
  50. package/dist/types.d.ts +45 -1
  51. package/dist/values.d.ts +72 -18
  52. package/dist/values.js +651 -172
  53. package/dist/vitest-concurrency.d.ts +16 -0
  54. package/dist/vitest-concurrency.js +55 -0
  55. package/package.json +2 -2
  56. package/schema/v1.json +1 -0
@@ -0,0 +1,71 @@
1
+ import { isFunctionNode, returnValues, unwrapChain } from "./ast.js";
2
+ export function analyzeReturns(fn) {
3
+ const body = fn.body;
4
+ const all = body && returnValues(fn);
5
+ return {
6
+ candidates: all ?? (body && returnValues(fn, false, 'ignore')) ?? [],
7
+ complete: !!all && (body.type !== 'BlockStatement' || body.body.at(-1)?.type === 'ReturnStatement'),
8
+ };
9
+ }
10
+ /** Closures and bound arguments keep the closest factory whose bindings they use. */
11
+ export function capturedResult(target, frame) {
12
+ const factory = frame.caller.factories.get(frame.call) ?? frame;
13
+ const depth = target.scopes.indexOf(frame.fn);
14
+ if (depth >= 0 && (!target.factory || depth > target.scopes.indexOf(target.factory.fn)))
15
+ return { ...target, factory };
16
+ if (!target.bound)
17
+ return target;
18
+ return {
19
+ ...target,
20
+ bound: target.bound.map((capture) => !capture.factory && capture.scopes.includes(frame.fn) ? { ...capture, factory } : capture),
21
+ };
22
+ }
23
+ export function conditionArgument(test, scopes, frame, values) {
24
+ if (test.type !== 'Identifier' ||
25
+ frame?.mode !== 'direct' ||
26
+ frame.bound ||
27
+ values.declarationOf(test.name, scopes) !== frame.fn)
28
+ return;
29
+ const index = frame.fn.params.findIndex((param) => param.type === 'Identifier' && param.name === test.name);
30
+ const args = frame.call.arguments;
31
+ if (index < 0 || args.slice(0, index).some((arg) => arg.type === 'SpreadElement'))
32
+ return;
33
+ const arg = args.at(index);
34
+ if (!arg || arg.type === 'SpreadElement')
35
+ return;
36
+ const changed = values.assignedIn(frame.fn.body);
37
+ if (!changed.has(test.name) && !changed.has('arguments'))
38
+ return arg;
39
+ }
40
+ /** Mark functions whose creation alone cannot execute the writes in their bodies. */
41
+ export function markReturnedLocals(expression, scopes, owner, values, out, seen = new Set()) {
42
+ const value = unwrapChain(expression);
43
+ if (isFunctionNode(value))
44
+ out.add(value);
45
+ else if (value.type === 'Identifier') {
46
+ const constant = values.constantOf(value.name, scopes);
47
+ if (constant) {
48
+ if (!seen.has(constant.init)) {
49
+ seen.add(constant.init);
50
+ // An alias can point to a function declared outside the factory.
51
+ if (constant.scopes.includes(owner))
52
+ markReturnedLocals(constant.init, constant.scopes, owner, values, out, seen);
53
+ }
54
+ }
55
+ else {
56
+ const local = values.functionWithScopes(value.name, scopes);
57
+ if (local?.scopes.includes(owner))
58
+ out.add(local.fn);
59
+ }
60
+ }
61
+ else if (value.type === 'ConditionalExpression' || value.type === 'LogicalExpression') {
62
+ const first = value.type === 'ConditionalExpression' ? value.consequent : value.left;
63
+ const second = value.type === 'ConditionalExpression' ? value.alternate : value.right;
64
+ markReturnedLocals(first, scopes, owner, values, out, seen);
65
+ markReturnedLocals(second, scopes, owner, values, out, seen);
66
+ }
67
+ else if (value.type === 'SequenceExpression')
68
+ markReturnedLocals(value.expressions[value.expressions.length - 1], scopes, owner, values, out, seen);
69
+ else if (value.type === 'AssignmentExpression' && value.operator === '=')
70
+ markReturnedLocals(value.right, scopes, owner, values, out, seen);
71
+ }
@@ -13,6 +13,7 @@ export declare function scriptsRunBy(scripts: Record<string, unknown>, name: str
13
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
+ cwd?: string;
16
17
  /** The config it names, as written; null when it names none. */
17
18
  config: string | null;
18
19
  /** The folder it takes as the project's root, as written: Vitest's `--root`, Cypress's `--project`; else null. */
@@ -21,6 +22,8 @@ export interface RunnerCommand {
21
22
  unreadable: boolean;
22
23
  /** A plain playwright test command collects its default files even without a config. */
23
24
  playwrightDefaults?: true;
25
+ /** Static positional file filters, when every selection argument is readable. */
26
+ filters?: string[];
24
27
  /** For Mocha, which takes its files and settings from them, the words after the program. */
25
28
  args?: string[];
26
29
  }
@@ -28,7 +31,7 @@ export interface RunnerCommand {
28
31
  * The commands of a package.json script that start a runner, with the config and root each names. Only a command whose
29
32
  * program is the runner counts, so `eslint --plugin jest -c .eslintrc.json` and `npm run jest` start none.
30
33
  */
31
- export declare function runnerCommands(script: string, runner: ScriptRunner): RunnerCommand[];
34
+ export declare function runnerCommands(script: string, runner: ScriptRunner, canEnter?: (cwd: string) => boolean | null): RunnerCommand[];
32
35
  /** What a Mocha command line gives: the specs, positional or `--spec`, and each option's values, aliases resolved. */
33
36
  export interface MochaArguments {
34
37
  positional: string[];
@@ -1,3 +1,4 @@
1
+ import path from 'node:path';
1
2
  import picomatch from 'picomatch';
2
3
  /** Node.js options that take their value as the next argument, so it is not a file to test. */
3
4
  const VALUE_OPTIONS = new Set([
@@ -60,7 +61,7 @@ const VALUE_OPTIONS = new Set([
60
61
  */
61
62
  export function nodeTestCommands(script, setups = false) {
62
63
  const commands = [];
63
- for (const words of commandsOf(script)) {
64
+ for (const { words } of commandsOf(script)) {
64
65
  const node = words.findIndex((word) => /(^|[/\\])node(\.exe)?$/.test(word));
65
66
  if (node === -1)
66
67
  continue;
@@ -95,9 +96,17 @@ export function nodeTestCommands(script, setups = false) {
95
96
  /** The commands of a script, each as its words, without quotes. */
96
97
  function commandsOf(script) {
97
98
  // A word is quoted in whole or in part, as `--server-args="-screen 0 1280x1024x24"`, and the shell drops the quotes.
98
- return script
99
- .split(/&&|\|\||[;|]/)
100
- .map((command) => [...command.matchAll(/(?:[^\s'"]+|'[^']*'|"[^"]*")+/g)].map(([word]) => word.replaceAll(/'([^']*)'|"([^"]*)"/g, '$1$2')));
99
+ const commands = [];
100
+ let words = [];
101
+ for (const [word, separator] of script.matchAll(/(&&|\|\||[;|])|(?:[^\s'"&;|]+|'[^']*'|"[^"]*"|&(?!&))+/g)) {
102
+ if (separator) {
103
+ commands.push({ words, next: separator });
104
+ words = [];
105
+ }
106
+ else
107
+ words.push(word.replaceAll(/'([^']*)'|"([^"]*)"/g, '$1$2'));
108
+ }
109
+ return [...commands, { words, next: '' }];
101
110
  }
102
111
  /**
103
112
  * A package.json script and those it runs in turn, each once: through `npm run`, `npm test`, `pnpm`, `yarn`,
@@ -110,7 +119,7 @@ export function scriptsRunBy(scripts, name) {
110
119
  if (run.includes(current) || !names.includes(current))
111
120
  return;
112
121
  run.push(current);
113
- for (const words of commandsOf(scripts[current])) {
122
+ for (const { words } of commandsOf(scripts[current])) {
114
123
  for (const called of calledScripts(words, names))
115
124
  visit(called);
116
125
  }
@@ -197,14 +206,61 @@ const RUNNER_PACKAGES = {
197
206
  '@wdio/cli': 'wdio',
198
207
  mocha: 'mocha',
199
208
  };
209
+ /** Only narrow discovery when every remaining argument has an unambiguous role. */
210
+ function fileFilters(program, args) {
211
+ let files;
212
+ if (program === 'jest' && args.includes('--runTestsByPath')) {
213
+ files = args.filter((arg) => !['--runTestsByPath', '--ci', '--runInBand'].includes(arg));
214
+ }
215
+ else if (program === 'vitest' && args[0] === 'run') {
216
+ files = args.slice(1).filter((arg) => arg !== '--coverage');
217
+ }
218
+ else if (program === 'playwright') {
219
+ files = args;
220
+ }
221
+ else
222
+ return [];
223
+ // Variables, shell globs, redirects and options with unmodeled values cannot safely narrow a command.
224
+ return files.every((file) => !/^[-~]/.test(file) && /^(?:[A-Za-z]:\/)?[\p{L}\p{N}_./ ~-]+$/u.test(file)) ? files : [];
225
+ }
200
226
  /**
201
227
  * The commands of a package.json script that start a runner, with the config and root each names. Only a command whose
202
228
  * program is the runner counts, so `eslint --plugin jest -c .eslintrc.json` and `npm run jest` start none.
203
229
  */
204
- export function runnerCommands(script, runner) {
230
+ export function runnerCommands(script, runner, canEnter = () => true) {
205
231
  const { programs, config, root } = RUNNERS[runner];
206
232
  const found = [];
207
- for (const words of commandsOf(script)) {
233
+ let cwd = '.';
234
+ let previous = '';
235
+ let success = null;
236
+ for (const { words, next } of commandsOf(script)) {
237
+ const before = previous;
238
+ previous = next;
239
+ if ((before === '&&' && success === false) || (before === '||' && success === true))
240
+ continue;
241
+ success = null;
242
+ if (words.length === 1 && ['true', 'false', ':'].includes(words[0])) {
243
+ success = words[0] !== 'false';
244
+ continue;
245
+ }
246
+ if (words[0] === 'cd' && before !== '|' && next !== '|') {
247
+ const args = words.slice(1);
248
+ if (args[0] === '-L')
249
+ args.shift();
250
+ if (args[0] === '--')
251
+ args.shift();
252
+ const [target] = args;
253
+ if (args.length !== 1 || !/^(?:[A-Za-z]:\/)?[\p{L}\p{N}_./ -]+$/u.test(target) || target.startsWith('-')) {
254
+ cwd = null;
255
+ }
256
+ else {
257
+ const dir = path.isAbsolute(target) ? target : cwd === null ? null : path.join(cwd, target);
258
+ success = dir === null ? null : canEnter(dir);
259
+ if (success !== false)
260
+ cwd = success ? dir : null;
261
+ }
262
+ continue;
263
+ }
208
264
  const started = programOf(words);
209
265
  if (!started || !Object.hasOwn(programs, started.program))
210
266
  continue;
@@ -215,7 +271,9 @@ export function runnerCommands(script, runner) {
215
271
  continue;
216
272
  args = args.slice(1);
217
273
  }
218
- const command = { config: null, root: null, unreadable: false };
274
+ const command = { config: null, root: null, unreadable: cwd === null };
275
+ if (cwd && cwd !== '.')
276
+ command.cwd = cwd;
219
277
  if (started.program === 'playwright' && args.length === 0)
220
278
  command.playwrightDefaults = true;
221
279
  if (runner === 'mocha')
@@ -225,11 +283,14 @@ export function runnerCommands(script, runner) {
225
283
  if (first !== undefined && !first.startsWith('-'))
226
284
  command.config = first;
227
285
  }
286
+ const remaining = [];
228
287
  for (let index = 0; index < args.length; index++) {
229
288
  const parts = args[index].split(/=(.*)/s);
230
289
  const key = config.includes(parts[0]) ? 'config' : root.includes(parts[0]) ? 'root' : null;
231
- if (key === null)
290
+ if (key === null) {
291
+ remaining.push(args[index]);
232
292
  continue;
293
+ }
233
294
  const value = parts.at(1) ?? args.at(++index);
234
295
  if (value === undefined)
235
296
  command.unreadable = true;
@@ -240,6 +301,9 @@ export function runnerCommands(script, runner) {
240
301
  const values = [command.config, command.root].filter((value) => value !== null);
241
302
  if (values.some((value) => /[$%]/.test(value) || value.startsWith('{')))
242
303
  command.unreadable = true;
304
+ const filters = fileFilters(started.program, remaining);
305
+ if (filters.length)
306
+ command.filters = filters;
243
307
  found.push(command);
244
308
  }
245
309
  return found;
@@ -379,8 +443,10 @@ export function mochaArguments(args) {
379
443
  const valued = MOCHA_VALUES[name];
380
444
  if (valued === undefined) {
381
445
  const flag = MOCHA_FLAGS[name];
382
- if (flag !== undefined)
383
- options.set(flag, []);
446
+ if (word === '--no-recursive')
447
+ options.set('recursive', ['false']);
448
+ else if (flag !== undefined)
449
+ options.set(flag, flag === 'recursive' && option[2] === 'false' ? ['false'] : []);
384
450
  continue;
385
451
  }
386
452
  const value = option.at(2) ?? args.at(++index);
package/dist/options.d.ts CHANGED
@@ -65,5 +65,7 @@ export declare function checkString(value: unknown, option: string): string;
65
65
  export declare function checkStrings(value: unknown, option: string, required: boolean): string[];
66
66
  /** `[major, minor]` of a checked version, or null. */
67
67
  export declare function majorMinor(version: string | null): [number, number] | null;
68
+ /** The patch component when the checked version specifies one. */
69
+ export declare function patchVersion(version: string | null): number | undefined;
68
70
  /** A path with `/` separators and without a leading `./`. */
69
71
  export declare function toPosixPath(path: string): string;
package/dist/options.js CHANGED
@@ -11,7 +11,7 @@ const FRAMEWORKS = [
11
11
  ];
12
12
  const COMMENTS = ['all', 'non-active', 'none'];
13
13
  // A prerelease and build metadata each appear once, so a long input can't make the match backtrack for long.
14
- const VERSION = /^v?(\d+)\.(\d+)(?:\.\d+)?(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
14
+ const VERSION = /^v?(\d+)\.(\d+)(?:\.(\d+))?(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
15
15
  /** An invalid option, told apart from other errors so that the command line can show it as a usage error. */
16
16
  export class OptionsError extends TypeError {
17
17
  }
@@ -78,6 +78,11 @@ export function majorMinor(version) {
78
78
  const match = version === null ? null : VERSION.exec(version);
79
79
  return match ? [Number(match[1]), Number(match[2])] : null;
80
80
  }
81
+ /** The patch component when the checked version specifies one. */
82
+ export function patchVersion(version) {
83
+ const patch = VERSION.exec(version ?? '')?.[3];
84
+ return patch === undefined ? undefined : Number(patch);
85
+ }
81
86
  /** A path with `/` separators and without a leading `./`. */
82
87
  export function toPosixPath(path) {
83
88
  return path.replaceAll('\\', '/').replace(/^(\.\/)+/, '');
package/dist/records.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { type Extraction, type PendingTest } from './extract.ts';
2
+ import { type ConcurrencyRules } from './vitest-concurrency.ts';
2
3
  import type { Dependencies } from './dependency-hash.ts';
3
4
  import type { RunSettings } from './model.ts';
4
5
  import type { ParsedFile } from './parse.ts';
@@ -22,7 +23,7 @@ export interface ConfigDefaults {
22
23
  retryText: string | null;
23
24
  repeatsText: string | null;
24
25
  /** Whether tests run in parallel unless the file says otherwise: Playwright's `fullyParallel`, Vitest's `sequence.concurrent`. */
25
- parallel: boolean;
26
+ parallel: boolean | null | undefined;
26
27
  }
27
28
  /** What a Vitest tag the config defines sets on the tests that carry it. */
28
29
  export interface TagOptions {
@@ -47,8 +48,6 @@ export interface VitestTags {
47
48
  isStrict: boolean;
48
49
  /** From Vitest 5 a tag's options win over the describe's around the test; before, the describe's win. */
49
50
  beatsDescribes: boolean;
50
- /** Vitest 4.1 passes the config's `sequence.concurrent`, when it sets one, to every test, over a tag's `concurrent`. */
51
- concurrentBeatsTags: boolean;
52
51
  }
53
52
  /** What the config the file uses gives it. */
54
53
  export interface FileConfig {
@@ -72,10 +71,13 @@ export interface FileConfig {
72
71
  configTags: string[];
73
72
  }
74
73
  interface RecordOptions {
74
+ vitestConcurrency: ConcurrencyRules | null;
75
75
  relativeFilePath: string;
76
76
  framework: Framework;
77
77
  /** Jasmine's focus rules apply: for Jasmine, and for WebdriverIO on Jasmine. */
78
78
  focusesLikeJasmine: boolean;
79
+ /** From 4.0.17, Vitest selects inner focused tests and suites over unmarked siblings in a focused suite. */
80
+ narrowsVitestFocus: boolean;
79
81
  comments: CommentsMode;
80
82
  isTypeTest: boolean;
81
83
  /** A Vitest 5 benchmark file, such as `*.bench.ts`. */
package/dist/records.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { LEVELS, REJECTS_FILE, toDiagnostic } from "./diagnostics.js";
2
2
  import { anySlow, eitherCondition, noHooks, } from "./extract.js";
3
3
  import { problem } from "./frameworks/common.js";
4
+ import { legacyVitestParallel, suiteConcurrency } from "./vitest-concurrency.js";
4
5
  import { hashNodes, shortHash } from "./hash.js";
5
6
  import { snippet } from "./source.js";
6
7
  /**
@@ -62,21 +63,43 @@ function undefinedTags(extraction, tags) {
62
63
  }
63
64
  const FLAG_ORDER = ['skip', 'todo', 'expectedToFail'];
64
65
  const ALWAYS = { condition: null, reason: null, hasDynamicReason: false };
66
+ /** Vitest checks allowOnly during collection, before a hook or a test body can skip the test. */
67
+ function skippedAtCollection(setting) {
68
+ return !setting.afterLoad && setting.condition === null && (setting.state === 'skip' || setting.state === 'todo');
69
+ }
65
70
  /**
66
71
  * The states of a test's declaration with those of its Vitest tags. Vitest merges the options and then takes `only`
67
72
  * over `skip` over `todo`, so a `.only` on either side drops the skip and todo of both.
68
73
  */
69
- function declaredStates(declared, options, { isOnly, skipPassedDown }) {
70
- const own = declared.map((setting) => ({ setting, source: 'test' }));
71
- if (options === null)
74
+ function declaredStates(declared, options, { isOnly, skipPassedDown, todoPassedDown, failsPassedDown, failsLine }, tagsFirst, focusedBySuite) {
75
+ const clearsSkip = tagsFirst && options?.skip === false;
76
+ const inheritedSkip = clearsSkip ? undefined : skipPassedDown;
77
+ const states = clearsSkip && skipPassedDown ? skipPassedDown.withoutSkip : declared;
78
+ const own = focusedBySuite || options?.only
79
+ ? failsLine === undefined
80
+ ? []
81
+ : [{ setting: { ...ALWAYS, state: 'expectedToFail', line: failsLine }, source: 'test' }]
82
+ : states.map((setting) => ({ setting, source: 'test' }));
83
+ const inherited = todoPassedDown !== undefined && !inheritedSkip && !(tagsFirst && options?.todo !== undefined)
84
+ ? [{ setting: { ...ALWAYS, state: 'todo', line: todoPassedDown }, source: 'suite' }]
85
+ : [];
86
+ if (failsPassedDown !== undefined && options?.fails === undefined) {
87
+ inherited.push({ setting: { ...ALWAYS, state: 'expectedToFail', line: failsPassedDown }, source: 'suite' });
88
+ }
89
+ if (options === null && !inherited.length)
72
90
  return own;
73
91
  // A describe's `skip` option is merged in too, where the scan otherwise leaves it to the describe's own state; the
74
92
  // test's own skip, when it has one, sorts first.
75
- const passed = skipPassedDown === undefined
93
+ const passed = options === null || inheritedSkip === undefined
76
94
  ? []
77
- : [{ setting: { ...ALWAYS, state: 'skip', line: skipPassedDown }, source: 'suite' }];
78
- const all = [...own, ...passed, ...tagStates(options).map((setting) => ({ setting, source: 'config' }))];
79
- const kept = isOnly || options.only ? all.filter(({ setting }) => setting.state === 'expectedToFail') : all;
95
+ : [{ setting: { ...ALWAYS, state: 'skip', line: inheritedSkip.line }, source: 'suite' }];
96
+ const all = [
97
+ ...own,
98
+ ...passed,
99
+ ...inherited,
100
+ ...(options ? tagStates(options).map((setting) => ({ setting, source: 'config' })) : []),
101
+ ];
102
+ const kept = isOnly || focusedBySuite || options?.only ? all.filter(({ setting }) => setting.state === 'expectedToFail') : all;
80
103
  return kept.sort((a, b) => FLAG_ORDER.indexOf(a.setting.state) - FLAG_ORDER.indexOf(b.setting.state));
81
104
  }
82
105
  /** The states the options of a test's Vitest tags set. */
@@ -211,6 +234,7 @@ class RecordBuilder {
211
234
  focused = new Set();
212
235
  /** Jasmine: scopes with a focused spec or describe below them, whose own focus Jasmine gives up for the inner one. */
213
236
  focusedBelow = new Set();
237
+ inheritedVitestFocus = new Map();
214
238
  constructor(parsed, options) {
215
239
  this.parsed = parsed;
216
240
  this.options = options;
@@ -244,6 +268,8 @@ class RecordBuilder {
244
268
  const lines = [...rejecting.filter((item) => !contained(item)), ...(firstTag ? [firstTag] : [])].map((item) => this.parsed.source.line(item.node.start));
245
269
  if (lines.length > 0)
246
270
  this.rejectedAt = Math.min(...lines);
271
+ if (extraction.registrationStoppedAt !== undefined)
272
+ this.rejectedAt = extraction.registrationStoppedAt;
247
273
  this.keepsEarlierTests = rejecting.length > 0 && rejecting.every((item) => item.keepsEarlierTests === true);
248
274
  this.focused = new Set(extraction.tests.filter((test) => test.declaration.isOnly).map((test) => test.scope));
249
275
  const focusedAt = [
@@ -264,6 +290,9 @@ class RecordBuilder {
264
290
  for (const [index, pending] of extraction.tests.entries()) {
265
291
  if (pending.parent)
266
292
  tests[index].parentTestId = this.testIds.get(pending.parent);
293
+ const focusedSuite = this.inheritedVitestFocus.get(pending);
294
+ if (focusedSuite && this.focusedBelow.has(focusedSuite))
295
+ tests[index].isOnly = false;
267
296
  }
268
297
  for (const item of problems) {
269
298
  const found = this.diagnostic(item);
@@ -332,8 +361,7 @@ class RecordBuilder {
332
361
  }
333
362
  suite(pending) {
334
363
  const { scope, declaration, call } = pending;
335
- const skipped = this.options.framework === 'vitest' &&
336
- outward(scope).some((parent) => parent.states.some((setting) => ['skip', 'todo'].includes(setting.state) && setting.condition === null));
364
+ const skipped = this.options.framework === 'vitest' && outward(scope).some((parent) => parent.states.some(skippedAtCollection));
337
365
  if (declaration.isOnly && !skipped)
338
366
  this.forbidOnly(pending.site ?? call, pending.site ? null : call);
339
367
  const parents = outward(scope).slice(1, -1).reverse();
@@ -363,7 +391,9 @@ class RecordBuilder {
363
391
  condition: chosen?.setting.condition ?? null,
364
392
  reason: chosen?.setting.reason ?? null,
365
393
  hasDynamicReason: chosen?.setting.hasDynamicReason ?? false,
366
- isParallel: scope.mode === 'parallel',
394
+ isParallel: declaration.vitestConcurrency && this.options.vitestConcurrency
395
+ ? suiteConcurrency({}, declaration.vitestConcurrency, this.options.vitestConcurrency).concurrent === true
396
+ : scope.mode === 'parallel',
367
397
  isSerial: scope.mode === 'serial',
368
398
  isShuffled: declaration.isShuffled,
369
399
  isParameterized: declaration.isParameterized,
@@ -468,11 +498,29 @@ class RecordBuilder {
468
498
  ...declaration.details.tags,
469
499
  ]);
470
500
  const fromTags = this.tagOptions(tags, declaration.ownStateOptions ?? []);
501
+ const focusedBySuite = declaration.inheritsOnly === true && fromTags?.only !== false;
502
+ const declaredOnly = declaration.isOnly || focusedBySuite || fromTags?.only === true;
503
+ if (this.options.narrowsVitestFocus) {
504
+ // Tag and inherited options can focus a sibling that appears later in the file.
505
+ if (declaredOnly) {
506
+ for (const scope of scopes)
507
+ this.focusedBelow.add(scope);
508
+ }
509
+ else {
510
+ const nearest = scopes.find((scope) => scope.isOnly);
511
+ if (nearest)
512
+ this.inheritedVitestFocus.set(pending, nearest);
513
+ }
514
+ }
471
515
  // In Vitest 5 the options of a test's tags win over those the describes pass down; before, the describes' win.
472
516
  const tagsFirst = this.options.config?.tags?.beatsDescribes ?? true;
473
517
  const tagged = (own, tag, around) => tagsFirst ? [...own, ...tag, ...around] : [...own, ...around, ...tag];
474
518
  const jest = this.options.framework === 'jest' ? this.jestState(pending, scopes) : null;
475
- const focus = this.options.focusesLikeJasmine ? this.jasmineFocus(pending, scopes) : undefined;
519
+ const focus = this.options.focusesLikeJasmine
520
+ ? pending.registrationStoppedAt === undefined
521
+ ? this.jasmineFocus(pending, scopes)
522
+ : null
523
+ : undefined;
476
524
  const mocha = !this.options.focusesLikeJasmine && ['mocha', 'cypress', 'webdriverio'].includes(this.options.framework);
477
525
  // A focus inside an `xdescribe` runs, as the describe's own skip doesn't reach it; `pending()` still does. An
478
526
  // `xdescribe` inside the focus stays skipped.
@@ -482,7 +530,8 @@ class RecordBuilder {
482
530
  suiteOf(scope).declaration.states.includes(setting);
483
531
  const overriding = OVERRIDING_DESCRIBES[this.options.framework];
484
532
  const around = scopes.flatMap((scope, index) => scope.states
485
- .filter((setting) => !declaredSkip(scope, index, setting))
533
+ .filter((setting) => !declaredSkip(scope, index, setting) &&
534
+ !(this.options.framework === 'vitest' && setting.state === 'expectedToFail'))
486
535
  .map((setting) => ({
487
536
  setting,
488
537
  source: scope.kind === 'file' ? 'file' : 'suite',
@@ -495,17 +544,18 @@ class RecordBuilder {
495
544
  : chooseState([
496
545
  // Outermost first, as the outermost of them decides.
497
546
  ...around.filter((candidate) => candidate.overrides).reverse(),
498
- ...declaredStates(pending.states.slice(0, declaration.states.length), fromTags, declaration),
547
+ ...declaredStates(pending.states.slice(0, declaration.states.length), fromTags, declaration, tagsFirst, focusedBySuite),
499
548
  ...pending.states.slice(declaration.states.length).map((setting) => ({ setting, source: 'test' })),
500
549
  // A test the declaration skips never runs its body, so its subtests never run; one its body skips still runs it.
501
550
  ...parents.flatMap((parent) => parent.declaration.states.map((setting) => ({ setting, source: 'suite' }))),
502
551
  ...around.filter((candidate) => !candidate.overrides),
503
552
  ]);
504
553
  // When the runner refuses the file, no test in it runs, whatever else is written, or none after the refused call.
505
- const scopeFailure = scopes
506
- .map((scope) => this.rejectedScopes.get(scope))
507
- .find((failure) => failure !== undefined && (this.options.framework === 'bun' || located.start >= failure.offset));
508
- const rejected = scopeFailure !== undefined ||
554
+ const scopeFailureLine = (this.rejectedAt === null ? pending.registrationStoppedAt : undefined) ??
555
+ scopes
556
+ .map((scope) => this.rejectedScopes.get(scope))
557
+ .find((failure) => failure !== undefined && (this.options.framework === 'bun' || located.start >= failure.offset))?.line;
558
+ const rejected = scopeFailureLine !== undefined ||
509
559
  (this.rejectedAt !== null &&
510
560
  !(this.keepsEarlierTests && this.parsed.source.line(located.start) < this.rejectedAt));
511
561
  const state = rejected ? 'notLoaded' : (chosen?.setting.state ?? 'active');
@@ -514,7 +564,7 @@ class RecordBuilder {
514
564
  ...describes.flatMap((scope) => suiteOf(scope).declaration.title?.text ?? []),
515
565
  ...parents.map((parent) => parent.declaration.title.text),
516
566
  ];
517
- const tagConcurrent = this.options.config?.tags?.concurrentBeatsTags ? undefined : fromTags?.concurrent;
567
+ const tagConcurrent = fromTags?.concurrent;
518
568
  const tagMode = tagConcurrent === undefined ? null : tagConcurrent ? 'parallel' : 'default';
519
569
  const [mode = null] = tagged([declaration.mode], [tagMode], [
520
570
  ...(this.options.framework === 'node' ? parents.map((parent) => parent.declaration.mode).reverse() : []),
@@ -530,7 +580,7 @@ class RecordBuilder {
530
580
  ? focus !== null
531
581
  : mocha
532
582
  ? this.mochaFocus(pending, scopes)
533
- : declaration.isOnly || scopes.some((scope) => scope.isOnly) || fromTags?.only === true;
583
+ : declaredOnly || scopes.some((scope) => scope.isOnly);
534
584
  const comments = this.options.comments === 'all' || (this.options.comments === 'non-active' && state !== 'active')
535
585
  ? pending.comments
536
586
  : [];
@@ -548,10 +598,7 @@ class RecordBuilder {
548
598
  if (pending.loops.includes(null)) {
549
599
  this.diagnostics.push(this.diagnostic(problem('test-in-loop', located, "The test is declared in a loop the scan can't count; it is listed once, while the runner creates one test per pass."), id));
550
600
  }
551
- if ((declaration.isOnly || fromTags?.only === true) &&
552
- chosen &&
553
- chosen.source !== 'test' &&
554
- chosen.setting.state === 'skip') {
601
+ if (declaredOnly && chosen && chosen.source !== 'test' && chosen.setting.state === 'skip') {
555
602
  this.diagnostics.push(this.diagnostic(problem('only-in-skipped-describe', located, 'The test uses .only, but a describe around it is skipped, so it is skipped too.'), id));
556
603
  }
557
604
  const record = {
@@ -586,8 +633,12 @@ class RecordBuilder {
586
633
  condition: setting?.condition ?? null,
587
634
  reason: setting?.reason ?? null,
588
635
  hasDynamicReason: setting?.hasDynamicReason ?? false,
589
- stateSource: scopeFailure ? 'suite' : rejected ? 'file' : (chosen?.source ?? null),
590
- stateLine: scopeFailure ? scopeFailure.line : rejected ? this.rejectedAt : (setting?.line ?? null),
636
+ stateSource: scopeFailureLine !== undefined && pending.scope.kind === 'describe'
637
+ ? 'suite'
638
+ : rejected
639
+ ? 'file'
640
+ : (chosen?.source ?? null),
641
+ stateLine: scopeFailureLine ?? (rejected ? this.rejectedAt : (setting?.line ?? null)),
591
642
  isParallel: mode === 'parallel',
592
643
  isSerial: mode === 'serial',
593
644
  tags,
@@ -627,13 +678,15 @@ class RecordBuilder {
627
678
  projects: null,
628
679
  defaults: null,
629
680
  };
630
- const skippedOnly = chosen && ['skip', 'todo'].includes(chosen.setting.state) && chosen.setting.condition === null;
631
- if (declaration.isOnly && this.options.framework === 'vitest' && !skippedOnly) {
681
+ const skippedOnly = chosen && skippedAtCollection(chosen.setting);
682
+ if (declaredOnly && this.options.framework === 'vitest' && !skippedOnly) {
632
683
  this.forbidOnly(located, pending.site ? null : pending.call, forbidOnly);
633
684
  }
634
685
  return {
635
686
  ...withConfig(record, defaults),
636
- isParallel: record.isParallel || (mode === null && defaults?.parallel === true),
687
+ isParallel: this.options.vitestConcurrency
688
+ ? legacyVitestParallel(this.options.vitestConcurrency, describes.map((scope) => suiteOf(scope).declaration.vitestConcurrency), declaration.vitestConcurrency, fromTags?.concurrent, defaults?.parallel)
689
+ : record.isParallel || (mode === null && defaults?.parallel === true),
637
690
  projects,
638
691
  };
639
692
  }
@@ -3,17 +3,20 @@ import { DependencyGraph, type SnapshotFiles } from './dependency-hash.ts';
3
3
  import { ExportedValues } from './imported-values.ts';
4
4
  import { type MochaInterface } from './frameworks/mocha.ts';
5
5
  import { type WebdriverIOFramework } from './frameworks/webdriverio.ts';
6
- import type { ModuleReader } from './model.ts';
6
+ import type { ModuleReader, ModuleSource } from './model.ts';
7
+ import { type ParsedFile } from './parse.ts';
7
8
  import { type CommentsMode, type FileConfig, type FileRecords } from './records.ts';
8
9
  import type { Framework } from './types.ts';
9
10
  export interface FileSettings {
10
11
  framework: Framework;
11
12
  /** `[major, minor]` of the framework version; null applies the newest rules. */
12
13
  version: [number, number] | null;
14
+ patch?: number;
13
15
  comments: CommentsMode;
14
16
  /** One test or describe per case of a table and per pass of a loop whose values the scan can work out. */
15
17
  expandCases?: boolean;
16
18
  readModule: ModuleReader | null;
19
+ initializeModule?: (file: string) => boolean;
17
20
  /** The project root, left out of error messages so that the output has no absolute paths. */
18
21
  root: string | null;
19
22
  /** Whether the config runs the file as a benchmark; null takes it from the file's name, as Vitest 5's default does. */
@@ -22,8 +25,8 @@ export interface FileSettings {
22
25
  config?: FileConfig | null;
23
26
  /** The interface Mocha's config sets for the tests: `describe` and `it`, or `suite` and `test`. */
24
27
  mochaInterface?: MochaInterface;
25
- /** The length Vitest's config shortens a value in a case title to; Vitest's default, 40, when unset. */
26
- titleTruncate?: number;
28
+ /** The distinct case-title truncation settings for this file's Vitest projects. */
29
+ titleThresholds?: (number | null)[];
27
30
  /** The framework a WebdriverIO config runs the specs with. */
28
31
  webdriverioFramework?: WebdriverIOFramework;
29
32
  /** Shared by the files of one scan, so that code many tests reach is read once. */
@@ -36,9 +39,20 @@ export interface FileSettings {
36
39
  snapshotFiles?: SnapshotFiles;
37
40
  }
38
41
  export interface FileResult extends FileRecords {
42
+ unknownRegistration?: boolean;
39
43
  usesGlobals: boolean;
40
44
  }
41
45
  /** The records of a file the scan read no tests from. */
42
46
  export declare function noRecords(relativeFilePath: string): Omit<FileRecords, 'diagnostics'>;
47
+ export interface PlaywrightSelection {
48
+ parsed: ParsedFile | null;
49
+ imports: Set<string>;
50
+ records: () => FileRecords | null;
51
+ }
52
+ /** Record module initialization in collection order. A spec that imports only Playwright needs its records only
53
+ * when script filters or project dependencies select among its tests. */
54
+ export declare function playwrightSelection(module: ModuleSource | {
55
+ reason: string;
56
+ }, version: FileSettings['version'], preloaded?: Set<string>): PlaywrightSelection;
43
57
  /** Reads one file: parse, extract, build records, and drop the AST. Never throws. */
44
- export declare function scanFile(code: string, relativeFilePath: string, settings: FileSettings): FileResult;
58
+ export declare function scanFile(code: string | ParsedFile, relativeFilePath: string, settings: FileSettings): FileResult;