test-inventory 0.10.3 → 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 +114 -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 +58 -4
  6. package/dist/config-runs.js +340 -42
  7. package/dist/config.d.ts +14 -6
  8. package/dist/config.js +273 -28
  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 +30 -0
  35. package/dist/node-scripts.js +247 -1
  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 +24 -6
  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
@@ -1,7 +1,7 @@
1
1
  import { childNodes, isFunctionNode, isImportMetaVitest, propertyKey, propertyName, unwrap, } from "../ast.js";
2
2
  import { snippet } from "../source.js";
3
3
  import { vitestCaseTitle } from "../case-titles.js";
4
- import { atLeast, hookFunction, problem, readChain, readCondition, destructuredNames, takesWhole, readCount, readOptions, readStrings, isTitleLiteral, readReason, namedFunction, origin, unresolvedOption, unresolvedOptions, readTitle, refused, text, } from "./common.js";
4
+ import { atLeast, hookFunction, problem, readChain, readCondition, destructuredNames, takesWhole, readCount, readOptions, readStrings, isTitleLiteral, readReason, namedFunction, origin, unresolvedOption, unresolvedOptions, readTitle, refused, text, wrappedFunction, } from "./common.js";
5
5
  import { SuiteAdapter } from "./test-functions.js";
6
6
  const MODIFIERS = {
7
7
  test: new Set(['concurrent', 'sequential', 'only', 'skip', 'todo', 'fails']),
@@ -30,7 +30,7 @@ const TEST_MEMBERS = [...MODIFIERS.test, ...MODIFIERS.describe, ...TABLES, ...CO
30
30
  const VITEST = {
31
31
  name: 'Vitest',
32
32
  source: 'vitest',
33
- mismatched: new Set(['@playwright/test', 'playwright/test', '@jest/globals']),
33
+ mismatched: new Set(['@playwright/test', 'playwright/test', '@jest/globals', 'mocha', 'node:test', 'bun:test']),
34
34
  starts: new Map([
35
35
  ['test', { kind: 'test', links: [] }],
36
36
  ['it', { kind: 'test', links: [] }],
@@ -195,7 +195,7 @@ export class VitestAdapter extends SuiteAdapter {
195
195
  callee.type !== 'SequenceExpression') {
196
196
  return null;
197
197
  }
198
- const chosen = this.testFunction(callee, context.scopes, (name, scopes) => context.returnsOf(name, scopes));
198
+ const chosen = this.testFunction(callee, context.scopes, (name, scopes) => context.returnsOf(name, scopes), false);
199
199
  const member = chosen?.links.at(-1);
200
200
  if (!chosen || !member || member.args || member.template)
201
201
  return null;
@@ -221,11 +221,14 @@ export class VitestAdapter extends SuiteAdapter {
221
221
  }
222
222
  const callee = snippet(text(this.file, call.callee));
223
223
  const removed = (link) => link.name === 'sequential' && atLeast(this.file.version, 5, 0);
224
+ // `test.for` came in Vitest 2.0 and `describe.for` in 3.0; before, the member is missing and the call throws.
225
+ const added = (link) => (link.name !== 'for' ? 0 : kind === 'test' ? 2 : 3);
226
+ const isTooNew = (link) => !atLeast(this.file.version, added(link), 0);
224
227
  const valid = (link) => {
225
228
  const called = link.args !== null || link.template !== null;
226
229
  if (MODIFIERS[kind].has(link.name))
227
230
  return !called && !removed(link);
228
- return TABLES.has(link.name) ? called : CONDITIONS.has(link.name) && link.args !== null;
231
+ return TABLES.has(link.name) ? called && !isTooNew(link) : CONDITIONS.has(link.name) && link.args !== null;
229
232
  };
230
233
  const tableIndex = links.findIndex((link) => TABLES.has(link.name) && (link.args !== null || link.template !== null));
231
234
  const invalid = links.find((link, index) => !valid(link) || (tableIndex !== -1 && index > tableIndex));
@@ -233,7 +236,9 @@ export class VitestAdapter extends SuiteAdapter {
233
236
  return this.declaration(call, kind, links, context);
234
237
  const refusal = removed(invalid)
235
238
  ? problem('removed-api', call, `sequential was removed in Vitest 5; ${callee}(...) fails.`, callee)
236
- : problem('invalid-chain', call, `${callee} is not part of Vitest's API.`, callee);
239
+ : isTooNew(invalid)
240
+ ? problem('invalid-chain', call, `${callee} needs Vitest ${added(invalid)} or newer.`, callee)
241
+ : problem('invalid-chain', call, `${callee} is not part of Vitest's API.`, callee);
237
242
  if (NOT_DECLARING.has(links[0].name))
238
243
  return { kind: 'invalid', problem: refusal };
239
244
  // Which of its parts the chain means is not known, so it declares a plain test or describe.
@@ -411,7 +416,7 @@ export class VitestAdapter extends SuiteAdapter {
411
416
  ...(skips ? { skipPassedDown: passed.line } : {}),
412
417
  details: read.details,
413
418
  fn,
414
- hashed: fn ?? namedFunction(this.file, context.scopes, body),
419
+ hashed: fn ?? namedFunction(this.file, context.scopes, body) ?? wrappedFunction(body),
415
420
  isParameterized: table !== null,
416
421
  caseCount: table ? this.caseCount(call, table, context, problems) : null,
417
422
  cases: table ? this.tableCases(table, title, context) : null,
package/dist/index.d.ts CHANGED
@@ -5,5 +5,7 @@ export type { ChangeKind, CloneGroup, InventoryDiff, MatchMethod, TestChange } f
5
5
  export { scanSource } from './scan-source.ts';
6
6
  export { filterInventory, pickTestFields } from './filter.ts';
7
7
  export type { InventoryFilter, PickedInventory } from './filter.ts';
8
+ export { runCommands } from './run-commands.ts';
9
+ export type { RunCommand } from './run-commands.ts';
8
10
  export type { CommentsMode, ScanOptions, ScanSourceOptions } from './options.ts';
9
11
  export type { Annotation, ConfigRecord, DeclaredAt, Diagnostic, DiagnosticCode, DiagnosticLevel, FileRecord, Framework, HookCounts, Inventory, InventoryLine, MetaValue, StateSource, SuiteRecord, Summary, TestRecord, TestState, Tool, } from './types.ts';
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. */
@@ -9,3 +9,33 @@ export declare function nodeTestCommands(script: string, setups?: boolean): stri
9
9
  * `bun run`, or `npm-run-all`, `run-s` and `run-p`, whose names may be globs where `*` stops at a `:`.
10
10
  */
11
11
  export declare function scriptsRunBy(scripts: Record<string, unknown>, name: string): string[];
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' | 'mocha';
14
+ /** A command of a script that starts a test runner. */
15
+ export interface RunnerCommand {
16
+ /** The config it names, as written; null when it names none. */
17
+ config: string | null;
18
+ /** The folder it takes as the project's root, as written: Vitest's `--root`, Cypress's `--project`; else null. */
19
+ root: string | null;
20
+ /** Whether it names its config or root in a way the scan can't read: a variable, or Jest's inline JSON. */
21
+ unreadable: boolean;
22
+ /** For Mocha, which takes its files and settings from them, the words after the program. */
23
+ args?: string[];
24
+ }
25
+ /**
26
+ * The commands of a package.json script that start a runner, with the config and root each names. Only a command whose
27
+ * program is the runner counts, so `eslint --plugin jest -c .eslintrc.json` and `npm run jest` start none.
28
+ */
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,3 +144,248 @@ function calledScripts(words, names) {
143
144
  return first === 'run' ? [second] : [first];
144
145
  return [];
145
146
  }
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
+ */
152
+ const RUNNERS = {
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: [] },
156
+ cypress: {
157
+ programs: { cypress: ['run', 'open'], 'cypress-cloud': null },
158
+ config: ['--config-file', '-C'],
159
+ root: ['--project', '-P'],
160
+ },
161
+ // `wdio run <config>` and `wdio <config>` take the config as the first argument.
162
+ webdriverio: { programs: { wdio: null }, config: [], root: [] },
163
+ mocha: { programs: { mocha: null, _mocha: null, 'ts-mocha': null }, config: ['--config'], root: [] },
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
+ ]);
189
+ /** The program each package's files start when `node` runs them. */
190
+ const RUNNER_PACKAGES = {
191
+ vitest: 'vitest',
192
+ jest: 'jest',
193
+ 'jest-cli': 'jest',
194
+ '@playwright/test': 'playwright',
195
+ playwright: 'playwright',
196
+ cypress: 'cypress',
197
+ '@wdio/cli': 'wdio',
198
+ mocha: 'mocha',
199
+ };
200
+ /**
201
+ * The commands of a package.json script that start a runner, with the config and root each names. Only a command whose
202
+ * program is the runner counts, so `eslint --plugin jest -c .eslintrc.json` and `npm run jest` start none.
203
+ */
204
+ export function runnerCommands(script, runner) {
205
+ const { programs, config, root } = RUNNERS[runner];
206
+ const found = [];
207
+ for (const words of commandsOf(script)) {
208
+ const started = programOf(words);
209
+ if (!started || !Object.hasOwn(programs, started.program))
210
+ continue;
211
+ const subcommands = programs[started.program];
212
+ let args = started.args;
213
+ if (subcommands) {
214
+ if (!subcommands.includes(args[0]))
215
+ continue;
216
+ args = args.slice(1);
217
+ }
218
+ const command = { config: null, root: null, unreadable: false };
219
+ if (runner === 'mocha')
220
+ command.args = args;
221
+ if (runner === 'webdriverio') {
222
+ const first = args.at(0) === 'run' ? args.at(1) : args.at(0);
223
+ if (first !== undefined && !first.startsWith('-'))
224
+ command.config = first;
225
+ }
226
+ for (let index = 0; index < args.length; index++) {
227
+ const parts = args[index].split(/=(.*)/s);
228
+ const key = config.includes(parts[0]) ? 'config' : root.includes(parts[0]) ? 'root' : null;
229
+ if (key === null)
230
+ continue;
231
+ const value = parts.at(1) ?? args.at(++index);
232
+ if (value === undefined)
233
+ command.unreadable = true;
234
+ else
235
+ command[key] = value;
236
+ }
237
+ // The shell expands a variable, and Jest reads a config that starts with `{` as the config itself.
238
+ const values = [command.config, command.root].filter((value) => value !== null);
239
+ if (values.some((value) => /[$%]/.test(value) || value.startsWith('{')))
240
+ command.unreadable = true;
241
+ found.push(command);
242
+ }
243
+ return found;
244
+ }
245
+ /**
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.
249
+ */
250
+ function programOf(words) {
251
+ let index = 0;
252
+ const skip = (test) => {
253
+ while (index < words.length && test(words[index]))
254
+ index++;
255
+ };
256
+ const isAssignment = (word) => /^\w+=/.test(word);
257
+ skip(isAssignment);
258
+ for (;;) {
259
+ const [word, next] = [words.at(index), words.at(index + 1)];
260
+ if (word === 'cross-env' || word === 'env') {
261
+ index++;
262
+ skip(isAssignment);
263
+ }
264
+ else if (word === 'dotenv' || (word === 'npm' && next === 'exec')) {
265
+ const end = words.indexOf('--', index);
266
+ index = end === -1 ? index + 2 : end + 1;
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
+ }
284
+ else if (word === 'npx' || word === 'bunx') {
285
+ index++;
286
+ skip((item) => item.startsWith('-'));
287
+ }
288
+ else if ((word === 'pnpm' && (next === 'exec' || next === 'dlx')) ||
289
+ (word === 'yarn' && next === 'exec') ||
290
+ (word === 'bun' && next === 'x')) {
291
+ index += 2;
292
+ }
293
+ else if ((word === 'pnpm' || word === 'yarn') && next !== 'run') {
294
+ // `pnpm vitest` starts the binary when no script has its name, which the scan takes to be so.
295
+ index++;
296
+ }
297
+ else
298
+ break;
299
+ }
300
+ const word = words.at(index);
301
+ if (word === undefined)
302
+ return null;
303
+ if (/(^|[/\\])node(\.exe)?$/.test(word)) {
304
+ index++;
305
+ while (index < words.length && words[index].startsWith('-'))
306
+ index += VALUE_OPTIONS.has(words[index]) ? 2 : 1;
307
+ const file = /node_modules[/\\](?:\.bin[/\\]([^/\\]+)|(@[^/\\]+[/\\][^/\\]+|[^/\\]+)[/\\])/.exec(words.at(index) ?? '');
308
+ const program = file?.at(1) ?? RUNNER_PACKAGES[file?.at(2)?.replaceAll('\\', '/') ?? ''];
309
+ return program ? { program, args: words.slice(index + 1) } : null;
310
+ }
311
+ const name = word.split(/[/\\]/).at(-1);
312
+ return { program: name.replace(/\.(cmd|exe|[cm]?js)$/, ''), args: words.slice(index + 1) };
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;