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
package/dist/extract.js CHANGED
@@ -1,8 +1,18 @@
1
- import { childNodes, isFunctionNode, isImportMetaVitest, propertyName, returnValues, unwrap, } from "./ast.js";
2
- import { commonJsExport, exportName } from "./frameworks/bindings.js";
1
+ import { isBuiltin } from 'node:module';
2
+ import { visitorKeys } from 'oxc-parser';
3
+ import { childNodes, isFunctionNode, isImportMetaVitest, isReference, propertyName, returnValues, unwrap, } from "./ast.js";
4
+ import { commonJsExport, exportName, requiredModule } from "./frameworks/bindings.js";
3
5
  import { problem, readCount } from "./frameworks/common.js";
6
+ import { omitted, stepGenerator } from "./generator-steps.js";
4
7
  import { snippet, splitLines } from "./source.js";
5
- import { bindingNames, isScopeNode } from "./values.js";
8
+ import { bindingNames, isScopeNode, nonIterable, usesRightOperand, } from "./values.js";
9
+ function possibleRegistration(registration) {
10
+ return (registration && {
11
+ ...registration,
12
+ iterators: new Map(registration.iterators),
13
+ asyncCall: registration.asyncCall && { ...registration.asyncCall },
14
+ });
15
+ }
6
16
  /** How many helpers deep a call is followed into the functions it calls, far more than real suites nest. */
7
17
  const MAX_DEPTH = 16;
8
18
  /**
@@ -77,17 +87,18 @@ function referencedNames(node) {
77
87
  * Whether a loop body can end a pass before its end or stop the loop, with `break`, `continue`, `return` or `throw`,
78
88
  * so that a test in it may not be registered on every pass. Functions inside run later, and don't count.
79
89
  */
80
- function leavesEarly(body) {
90
+ function leavesEarly(body, continueOnly = false) {
81
91
  if (body.type === 'FunctionDeclaration' || isFunctionNode(body))
82
92
  return false;
83
93
  switch (body.type) {
84
94
  case 'BreakStatement':
85
- case 'ContinueStatement':
86
95
  case 'ReturnStatement':
87
96
  case 'ThrowStatement':
97
+ return !continueOnly;
98
+ case 'ContinueStatement':
88
99
  return true;
89
100
  }
90
- return childNodes(body).some(leavesEarly);
101
+ return childNodes(body).some((child) => leavesEarly(child, continueOnly));
91
102
  }
92
103
  /**
93
104
  * What `test.describe.configure()` sets on the describe or file it is called in: the last mode, timeout and retries
@@ -147,12 +158,105 @@ function commentLines(comment) {
147
158
  : splitLines(comment.value).map((line) => line.replace(/^\s*\*?\s*/, '').trimEnd());
148
159
  return lines.filter((line) => line !== '' && !DIRECTIVE.test(line));
149
160
  }
161
+ /** A component or the object of a JSX member tag reads a binding. Intrinsic tags and attribute names are strings. */
162
+ function jsxReference(name, field, parent) {
163
+ if (parent?.type === 'JSXMemberExpression')
164
+ return field === 'object';
165
+ return ((parent?.type === 'JSXOpeningElement' || parent?.type === 'JSXClosingElement') &&
166
+ field === 'name' &&
167
+ !/^[a-z]/.test(name));
168
+ }
169
+ /** References that keep imported values in Playwright's emitted TypeScript. Look up the binding at the use
170
+ * so a local parameter or a property with the same name cannot keep an import alive. */
171
+ function runtimeReferences(frame) {
172
+ const used = new Set();
173
+ let hasJsx = false;
174
+ const scopes = [];
175
+ const program = frame.parsed.program;
176
+ const imports = new Map();
177
+ for (const statement of program.body) {
178
+ if (statement.type === 'ImportDeclaration')
179
+ for (const specifier of statement.specifiers)
180
+ imports.set(specifier.local.name, specifier);
181
+ }
182
+ const visit = (node, field, parent) => {
183
+ if (node.type === 'ImportDeclaration' ||
184
+ ('declare' in node && node.declare) ||
185
+ (node.type === 'ExportNamedDeclaration' && (node.source || node.exportKind === 'type')) ||
186
+ (node.type === 'ExportSpecifier' && node.exportKind === 'type'))
187
+ return;
188
+ if (node.type.startsWith('TS') && !TS_RUNTIME.has(node.type))
189
+ return;
190
+ const scoped = isScopeNode(node);
191
+ if (scoped)
192
+ scopes.push(node);
193
+ if (node.type === 'Identifier' || node.type === 'JSXIdentifier') {
194
+ const imported = imports.get(node.name);
195
+ const readsValue = node.type === 'Identifier' ? isReference(field, parent) : jsxReference(node.name, field, parent);
196
+ if (imported && readsValue && frame.values.declarationOf(node.name, scopes) === imported)
197
+ used.add(imported);
198
+ }
199
+ if (!hasJsx && (node.type === 'JSXElement' || node.type === 'JSXFragment')) {
200
+ hasJsx = true;
201
+ const factories = new Map([
202
+ ['jsx', 'React'],
203
+ ['jsxFrag', 'React'],
204
+ ]);
205
+ for (const comment of frame.parsed.comments) {
206
+ const pragma = /@(jsx(?:Frag)?)\s+([^\s.]+)/.exec(comment.value);
207
+ if (pragma)
208
+ factories.set(pragma[1], pragma[2]);
209
+ }
210
+ for (const name of factories.values()) {
211
+ const binding = frame.values.declarationOf(name, [program]);
212
+ if (binding)
213
+ used.add(binding);
214
+ }
215
+ }
216
+ const fields = node;
217
+ for (const key of visitorKeys[node.type]) {
218
+ const value = fields[key];
219
+ if (Array.isArray(value)) {
220
+ for (const child of value)
221
+ if (child)
222
+ visit(child, key, node);
223
+ }
224
+ else if (value)
225
+ visit(value, key, node);
226
+ }
227
+ if (scoped)
228
+ scopes.pop();
229
+ };
230
+ visit(program, null, null);
231
+ return used;
232
+ }
233
+ const TS_RUNTIME = new Set([
234
+ 'TSAsExpression',
235
+ 'TSSatisfiesExpression',
236
+ 'TSTypeAssertion',
237
+ 'TSNonNullExpression',
238
+ 'TSInstantiationExpression',
239
+ 'TSEnumDeclaration',
240
+ 'TSEnumBody',
241
+ 'TSEnumMember',
242
+ 'TSModuleDeclaration',
243
+ 'TSModuleBlock',
244
+ 'TSParameterProperty',
245
+ 'TSExportAssignment',
246
+ 'TSImportEqualsDeclaration',
247
+ 'TSExternalModuleReference',
248
+ ]);
249
+ export function initializesLocalModule(source) {
250
+ return source !== '@playwright/test' && source !== 'playwright/test' && !isBuiltin(source);
251
+ }
150
252
  class Walker {
151
253
  scopes = [];
152
254
  parents = [];
153
255
  fileScope;
154
256
  suites = [];
155
257
  tests = [];
258
+ iterators = new WeakMap();
259
+ argumentRevision = 0;
156
260
  problems = [];
157
261
  /** The scanned file. */
158
262
  main;
@@ -160,6 +264,10 @@ class Walker {
160
264
  frame;
161
265
  /** While an imported helper is walked, the call in the scanned file that walks it; records and problems point there. */
162
266
  site = null;
267
+ loaded = new Set();
268
+ valueImports = new WeakMap();
269
+ importDepth = 0;
270
+ unknownRegistration = false;
163
271
  openModule;
164
272
  frames = new Map();
165
273
  /** Problems of helper modules' own imports, reported once, at the first call that walks the module. */
@@ -181,6 +289,7 @@ class Walker {
181
289
  */
182
290
  declaredIn = new Map();
183
291
  deferred = [];
292
+ continuations = [];
184
293
  isDeferred = new Set();
185
294
  /**
186
295
  * Functions walked at one of their calls, or as a test or hook body passed by name, so that their tests are recorded
@@ -203,6 +312,7 @@ class Walker {
203
312
  constructor(main, openModule, options) {
204
313
  this.options = options;
205
314
  this.main = main;
315
+ this.loaded.add(main.relativeFilePath);
206
316
  this.frame = main;
207
317
  this.openModule = openModule;
208
318
  const { adapter } = main;
@@ -222,7 +332,11 @@ class Walker {
222
332
  };
223
333
  }
224
334
  run() {
335
+ const registration = this.main.adapter.catchesSuiteErrors
336
+ ? { iterators: new Map() }
337
+ : undefined;
225
338
  this.visit(this.main.parsed.program, {
339
+ registration,
226
340
  scope: this.fileScope,
227
341
  test: null,
228
342
  hookScope: null,
@@ -244,6 +358,14 @@ class Walker {
244
358
  quiet: false,
245
359
  registeredBy: null,
246
360
  });
361
+ if (registration) {
362
+ while (this.continuations.length) {
363
+ const batch = this.continuations;
364
+ this.continuations = [];
365
+ for (const resume of batch)
366
+ resume(registration);
367
+ }
368
+ }
247
369
  // Functions defined inside these are deferred in turn; the loop reaches them too, as they are added to the end.
248
370
  for (const entry of this.deferred)
249
371
  this.walkWhereWritten(entry);
@@ -255,22 +377,30 @@ class Walker {
255
377
  this.checkFunctionTests(exported);
256
378
  return {
257
379
  suites: this.suites,
380
+ registrationStoppedAt: registration?.failure?.line,
258
381
  tests: this.tests,
259
382
  problems: [...this.main.adapter.problems, ...this.problems],
260
383
  hooks: this.fileScope.hooks,
261
384
  usesGlobals: this.main.adapter.usesGlobals,
385
+ unknownRegistration: this.unknownRegistration,
262
386
  fileTags: this.main.adapter.fileTags.map((name, index) => ({
263
387
  name,
264
388
  span: this.main.adapter.fileTagSpans[index],
265
389
  })),
266
390
  };
267
391
  }
392
+ currentScope(context) {
393
+ const scope = context.registration?.scope;
394
+ return scope && scope !== context.scope ? { ...context, scope } : context;
395
+ }
268
396
  visit(node, context) {
397
+ if (this.frame.values.completedOperand(node, this.scopes))
398
+ return;
269
399
  const isScope = isScopeNode(node);
270
400
  if (isScope)
271
401
  this.scopes.push(node);
272
402
  this.parents.push(node);
273
- this.visitNode(node, context);
403
+ this.visitNode(node, this.currentScope(context));
274
404
  this.parents.pop();
275
405
  if (isScope)
276
406
  this.scopes.pop();
@@ -280,46 +410,143 @@ class Walker {
280
410
  this.visit(child, context);
281
411
  }
282
412
  visitNode(node, context) {
413
+ const task = context.registration?.asyncCall;
414
+ if (task &&
415
+ (context.skipImports ||
416
+ task.pending ||
417
+ context.registration?.returned ||
418
+ context.registration?.failure !== undefined))
419
+ return;
420
+ if (context.evaluatingArgument && context.registration) {
421
+ if (context.skipImports ||
422
+ context.registration.failure !== undefined ||
423
+ node.type === 'FunctionDeclaration' ||
424
+ isFunctionNode(node))
425
+ return;
426
+ const parameters = context.parameters;
427
+ if (parameters) {
428
+ const step = parameters.steps.get(node);
429
+ if (step === 'initialize') {
430
+ parameters.pending.delete(node.name);
431
+ return;
432
+ }
433
+ if (node.type.startsWith('TS') && !TS_RUNTIME.has(node.type))
434
+ return;
435
+ if (step === 'throw' || (node.type === 'Identifier' && this.readsUninitialized(node, parameters))) {
436
+ this.stopRegistration(node, context);
437
+ return;
438
+ }
439
+ if (node.type === 'AssignmentPattern' && step !== undefined) {
440
+ this.visitBranch(node.right, context, `${this.text(node.left)} === undefined`, step);
441
+ this.visit(node.left, context);
442
+ return;
443
+ }
444
+ }
445
+ if (node.type === 'ClassBody') {
446
+ // Class creation computes the keys first, then initializes static elements in declaration order.
447
+ for (const member of node.body)
448
+ if ('computed' in member && member.computed)
449
+ this.visit(member.key, context);
450
+ for (const member of node.body) {
451
+ if (member.type === 'StaticBlock')
452
+ this.visit(member, context);
453
+ else if ((member.type === 'PropertyDefinition' || member.type === 'AccessorProperty') &&
454
+ member.static &&
455
+ member.value)
456
+ this.visit(member.value, context);
457
+ }
458
+ return;
459
+ }
460
+ }
461
+ if (context.registration &&
462
+ !context.skipImports &&
463
+ context.registration.failure === undefined &&
464
+ node.type === 'SpreadElement' &&
465
+ this.parents.at(-2)?.type !== 'ObjectExpression') {
466
+ const operand = node.argument;
467
+ const use = {
468
+ ...context,
469
+ evaluatingArgument: true,
470
+ expandedAt: context.expandedAt ?? context.registeredBy?.start ?? node.start,
471
+ };
472
+ this.visit(operand, use);
473
+ const value = this.frame.values.iteratorOf(operand, this.scopes);
474
+ if (value) {
475
+ const spread = this.resumeIterator(value, use, context.registration, 'spread', omitted);
476
+ this.frame.values.iteratorSpreads.set(operand, spread);
477
+ this.argumentRevision++;
478
+ if (spread.outcome === 'throw')
479
+ this.stopRegistration(node, context, spread.result);
480
+ return;
481
+ }
482
+ if (this.frame.values.iteratorSpreads.delete(operand))
483
+ this.argumentRevision++;
484
+ const resolved = this.readArgument(operand, true);
485
+ if (resolved.ok ? nonIterable(resolved.value) : resolved.nonIterable)
486
+ this.stopRegistration(node, context);
487
+ return;
488
+ }
489
+ if (this.options.collectImports &&
490
+ !context.skipImports &&
491
+ !context.test &&
492
+ !context.hookScope &&
493
+ !context.helper &&
494
+ !context.quiet)
495
+ this.collectImport(node, context);
283
496
  switch (node.type) {
497
+ case 'AwaitExpression': {
498
+ this.visit(node.argument, context);
499
+ const registration = context.registration;
500
+ if (registration?.asyncCall && registration.failure === undefined) {
501
+ registration.asyncCall.atAwait ??= { scope: registration.scope };
502
+ const failure = this.awaitedFailure(node.argument);
503
+ if (failure === 'pending')
504
+ registration.asyncCall.pending = true;
505
+ if (failure === 'rejected')
506
+ this.stopRegistration(node, context);
507
+ }
508
+ return;
509
+ }
284
510
  case 'CallExpression': {
285
511
  if (context.test && !context.quiet)
286
512
  this.expectCall(node, context.test);
287
513
  const helper = this.helperCall(node, context);
288
514
  if (this.call(node, context) || this.loopCall(node, context))
289
515
  return;
290
- this.visitChildren(node, context);
291
- if (helper)
292
- this.walkAtCall(helper, node, context);
293
- return;
294
- }
295
- case 'IfStatement': {
296
- // In-source tests sit inside `if (import.meta.vitest)`, which is how they are written, not a condition.
297
- if (isImportMetaVitest(node.test))
298
- break;
299
- const condition = this.text(node.test);
300
- this.visit(node.test, context);
301
- const known = this.known(node.test, context);
302
- if (known) {
303
- const taken = known.value ? node.consequent : node.alternate;
304
- if (taken)
305
- this.visit(taken, context);
516
+ if (!helper) {
517
+ for (const child of childNodes(node)) {
518
+ this.visit(child, context);
519
+ if (child === node.callee &&
520
+ context.registration &&
521
+ this.advanceIterator(node, context, context.registration))
522
+ return;
523
+ }
306
524
  return;
307
525
  }
308
- this.visit(node.consequent, this.guarded(context, condition));
309
- if (node.alternate)
310
- this.visit(node.alternate, this.guarded(context, `!(${condition})`));
526
+ if (helper.fn !== unwrap(node.callee))
527
+ this.visit(node.callee, context);
528
+ const stopped = this.registrationArguments(node, context);
529
+ if (stopped)
530
+ this.walkedAtCall.add(helper.fn);
531
+ else {
532
+ if (stopped === null)
533
+ for (const arg of node.arguments)
534
+ this.visit(arg, context);
535
+ this.walkAtCall(helper, node, context, stopped !== null);
536
+ }
311
537
  return;
312
538
  }
539
+ case 'IfStatement':
313
540
  case 'ConditionalExpression': {
541
+ // In-source tests sit inside `if (import.meta.vitest)`, which is how they are written, not a condition.
542
+ if (node.type === 'IfStatement' && isImportMetaVitest(node.test))
543
+ break;
314
544
  const condition = this.text(node.test);
315
545
  this.visit(node.test, context);
316
546
  const known = this.known(node.test, context);
317
- if (known) {
318
- this.visit(known.value ? node.consequent : node.alternate, context);
319
- return;
320
- }
321
- this.visit(node.consequent, this.guarded(context, condition));
322
- this.visit(node.alternate, this.guarded(context, `!(${condition})`));
547
+ this.visitBranch(node.consequent, context, condition, known && Boolean(known.value));
548
+ if (node.alternate)
549
+ this.visitBranch(node.alternate, context, `!(${condition})`, known && !known.value);
323
550
  return;
324
551
  }
325
552
  case 'LogicalExpression': {
@@ -327,27 +554,67 @@ class Walker {
327
554
  const guard = node.operator === '&&' ? left : node.operator === '||' ? `!(${left})` : `(${left}) == null`;
328
555
  this.visit(node.left, context);
329
556
  const known = this.known(node.left, context);
330
- if (known) {
331
- const { value } = known;
332
- const right = node.operator === '&&'
333
- ? Boolean(value)
334
- : node.operator === '||'
335
- ? !value
336
- : value === null || value === undefined;
337
- if (right)
338
- this.visit(node.right, context);
339
- return;
340
- }
341
- this.visit(node.right, this.guarded(context, guard));
557
+ const right = known && usesRightOperand(node.operator, known.value);
558
+ this.visitBranch(node.right, context, guard, right);
342
559
  return;
343
560
  }
344
- case 'TryStatement':
345
- this.visit(node.block, context);
346
- // A `catch` block runs only when the `try` block throws, as when a test server can't start.
347
- if (node.handler)
348
- this.visit(node.handler, this.guarded(context, this.catchCondition(node.handler)));
349
- if (node.finalizer)
561
+ case 'TryStatement': {
562
+ const attempt = context.registration && { ...context.registration };
563
+ this.visit(node.block, { ...context, registration: attempt, handlesRegistrationError: !!attempt });
564
+ let failure = attempt?.failure;
565
+ let returned = attempt?.returned;
566
+ let scope = attempt?.recoveryScope ?? attempt?.scope;
567
+ const exit = node.handler && attempt && failure === undefined
568
+ ? this.frame.adapter.registrationExit?.(node.block, this.scopes)
569
+ : undefined;
570
+ if (node.handler && exit !== 'next' && exit !== 'return') {
571
+ const handler = this.guarded(context, this.catchCondition(node.handler));
572
+ if (handler.registration) {
573
+ handler.registration.scope = scope;
574
+ if (attempt && (failure !== undefined || exit === 'throw'))
575
+ handler.registration.iterators = attempt.iterators;
576
+ if (failure !== undefined)
577
+ handler.registration.asyncCall = attempt?.asyncCall;
578
+ }
579
+ this.visit(node.handler, handler);
580
+ if (failure !== undefined && handler.registration) {
581
+ failure = handler.registration.failure;
582
+ returned = handler.registration.returned;
583
+ scope = handler.registration.recoveryScope ?? handler.registration.scope;
584
+ }
585
+ else
586
+ returned = returned && handler.registration?.returned;
587
+ }
588
+ if (context.registration)
589
+ context.registration.scope = scope;
590
+ if (node.finalizer) {
350
591
  this.visit(node.finalizer, context);
592
+ if (failure !== undefined &&
593
+ (context.registration?.returned ||
594
+ this.frame.adapter.registrationExit?.(node.finalizer, this.scopes) === 'return'))
595
+ failure = undefined;
596
+ }
597
+ if (context.registration && failure !== undefined)
598
+ context.registration.failure ??= failure;
599
+ if (returned && context.registration)
600
+ context.registration.returned = true;
601
+ return;
602
+ }
603
+ case 'ReturnStatement':
604
+ if (node.argument) {
605
+ this.visit(node.argument, context);
606
+ const target = context.iteratorReturn;
607
+ if (target &&
608
+ this.scopes.findLast((n) => n.type === 'FunctionDeclaration' || isFunctionNode(n)) === target.fn) {
609
+ target.value = this.frame.values.iteratorOf(node.argument, this.scopes);
610
+ }
611
+ }
612
+ if (context.registration?.asyncCall && context.registration.failure === undefined)
613
+ context.registration.returned = true;
614
+ return;
615
+ case 'ThrowStatement':
616
+ this.visit(node.argument, context);
617
+ this.stopRegistration(node, context);
351
618
  return;
352
619
  case 'SwitchStatement': {
353
620
  const discriminant = this.text(node.discriminant);
@@ -355,19 +622,30 @@ class Walker {
355
622
  // The default case runs when no other case matches.
356
623
  const otherwise = values.map((value) => `${discriminant} !== ${value}`).join(' && ');
357
624
  this.visit(node.discriminant, context);
358
- for (const switchCase of node.cases) {
625
+ const start = this.switchStart(node, context);
626
+ let fallsThrough = false;
627
+ for (const [index, switchCase] of node.cases.entries()) {
359
628
  const guard = switchCase.test ? `${discriminant} === ${this.text(switchCase.test)}` : otherwise;
360
- this.visit(switchCase, this.guarded(context, guard === '' ? null : guard));
629
+ const guarded = this.guarded(context, guard === '' ? null : guard);
630
+ const executes = start === null || index === start || fallsThrough;
631
+ this.visit(switchCase, executes ? guarded : { ...guarded, skipImports: true });
632
+ fallsThrough = executes && !switchCase.consequent.some((statement) => alwaysLeaves(statement));
361
633
  }
362
634
  return;
363
635
  }
636
+ case 'SwitchCase':
637
+ if (node.test)
638
+ this.visit(node.test, context);
639
+ this.visitStatements(node.consequent, context);
640
+ return;
364
641
  case 'BlockStatement':
365
642
  this.visitStatements(node.body, context);
366
643
  return;
367
644
  case 'ForInStatement':
368
645
  case 'ForOfStatement': {
369
646
  const leaves = leavesEarly(node.body);
370
- const values = leaves ? null : this.loopValues(node);
647
+ const iterable = this.loopValues(node);
648
+ const values = leaves ? null : iterable;
371
649
  const expands = values ? this.expands(node, values, context) : 'no';
372
650
  if (values && expands === 'yes') {
373
651
  this.expandLoop(node, values, context);
@@ -377,15 +655,34 @@ class Walker {
377
655
  const listed = node.type === 'ForOfStatement' && !leaves ? node.right : null;
378
656
  const count = values?.length ?? (listed ? this.frame.values.lengthOf(listed, this.scopes.slice(0, -1)) : null);
379
657
  this.walkUnexpanded(node, expands === 'limit', () => {
380
- this.visitChildren(node, this.inLoop(context, count));
658
+ this.visit(node.right, context);
659
+ const loop = this.inLoop(context, count);
660
+ const body = iterable?.length === 0 ? { ...loop, skipImports: true } : loop;
661
+ this.visit(node.left, body);
662
+ this.visit(node.body, body);
381
663
  });
382
664
  return;
383
665
  }
384
666
  case 'ForStatement':
385
- case 'WhileStatement':
386
- case 'DoWhileStatement':
387
- this.visitChildren(node, this.inLoop(context, null));
667
+ case 'WhileStatement': {
668
+ const loop = this.inLoop(context, null);
669
+ if (node.type === 'ForStatement' && node.init)
670
+ this.visit(node.init, loop);
671
+ if (node.test)
672
+ this.visit(node.test, loop);
673
+ const condition = node.test && this.known(node.test, context);
674
+ const body = condition && !condition.value ? { ...loop, skipImports: true } : loop;
675
+ this.visit(node.body, body);
676
+ if (node.type === 'ForStatement' && node.update)
677
+ this.visit(node.update, this.loopTail(node.body, body));
678
+ return;
679
+ }
680
+ case 'DoWhileStatement': {
681
+ const loop = this.inLoop(context, null);
682
+ this.visit(node.body, loop);
683
+ this.visit(node.test, this.loopTail(node.body, loop));
388
684
  return;
685
+ }
389
686
  case 'FunctionDeclaration':
390
687
  case 'FunctionExpression':
391
688
  case 'ArrowFunctionExpression': {
@@ -393,7 +690,7 @@ class Walker {
393
690
  const helper = context.test || context.hookScope ? null : node;
394
691
  const named = helper !== null && this.isNamed(node);
395
692
  // In an imported helper's module, a function runs only when it is called, and is walked then.
396
- if (named && this.frame !== this.main)
693
+ if (this.frame !== this.main && (named || (this.importDepth > 0 && !context.test && !context.hookScope)))
397
694
  return;
398
695
  if (named && !this.isDeferred.has(node)) {
399
696
  // Its calls decide where its tests are registered, and a call may come after it, so it waits.
@@ -408,6 +705,7 @@ class Walker {
408
705
  ...context,
409
706
  isInFunction: true,
410
707
  helper: helper ?? context.helper,
708
+ registration: undefined,
411
709
  guards: helper ? [] : context.guards,
412
710
  });
413
711
  return;
@@ -415,6 +713,72 @@ class Walker {
415
713
  }
416
714
  this.visitChildren(node, context);
417
715
  }
716
+ /** Static module loads run once during collection. Keep the location of the import in the entry spec and
717
+ * the declaration's own location in the loaded module, just as for a helper invoked at a call site. */
718
+ collectImport(node, context) {
719
+ let source;
720
+ if (node.type === 'ImportDeclaration' && node.importKind !== 'type') {
721
+ source = node.source.value;
722
+ if (node.specifiers.length && /\.[cm]?tsx?$/.test(this.frame.relativeFilePath)) {
723
+ let used = this.valueImports.get(this.frame);
724
+ if (!used) {
725
+ used = runtimeReferences(this.frame);
726
+ this.valueImports.set(this.frame, used);
727
+ }
728
+ if (!node.specifiers.some((item) => (item.type !== 'ImportSpecifier' || item.importKind !== 'type') && used.has(item)))
729
+ return;
730
+ }
731
+ }
732
+ else if ((node.type === 'ExportAllDeclaration' || node.type === 'ExportNamedDeclaration') &&
733
+ node.source &&
734
+ node.exportKind !== 'type') {
735
+ if (node.type === 'ExportNamedDeclaration' &&
736
+ node.specifiers.length &&
737
+ node.specifiers.every((item) => item.exportKind === 'type'))
738
+ return;
739
+ source = node.source.value;
740
+ }
741
+ else if (node.type === 'CallExpression' &&
742
+ node.callee.type === 'Identifier' &&
743
+ node.callee.name === 'require' &&
744
+ !this.frame.values.declarationOf('require', this.scopes))
745
+ source = requiredModule(node);
746
+ else if (node.type === 'ImportExpression')
747
+ source = null;
748
+ else
749
+ return;
750
+ if (source !== null && !initializesLocalModule(source))
751
+ return;
752
+ const frame = source !== null ? this.openFrom(this.frame, source) : null;
753
+ if (!frame || this.importDepth >= MAX_DEPTH) {
754
+ this.unknownRegistration = true;
755
+ return;
756
+ }
757
+ if (this.loaded.has(frame.relativeFilePath))
758
+ return;
759
+ this.loaded.add(frame.relativeFilePath);
760
+ if (this.options.initializeModule?.(frame.relativeFilePath) === false)
761
+ return;
762
+ const caller = this.frame;
763
+ const site = this.site;
764
+ const scopes = this.scopes.splice(0);
765
+ const parents = this.parents.splice(0);
766
+ this.frame = frame;
767
+ this.site ??= node;
768
+ this.importDepth++;
769
+ this.visit(frame.parsed.program, { ...context, registeredBy: context.registeredBy ?? node });
770
+ this.importDepth--;
771
+ this.scopes.push(...scopes);
772
+ this.parents.push(...parents);
773
+ this.site = site;
774
+ this.frame = caller;
775
+ }
776
+ /** A continue reaches the update or trailing condition of its loop. A break, return or throw skips it. */
777
+ loopTail(body, context) {
778
+ return this.options.collectImports && alwaysLeaves(body) && !leavesEarly(body, true)
779
+ ? { ...context, skipImports: true }
780
+ : context;
781
+ }
418
782
  /** Whether a function has a name it can be called by: `function name() {}` or `const name = () => {}`. */
419
783
  isNamed(fn) {
420
784
  const parent = this.parents.at(-2);
@@ -426,7 +790,9 @@ class Walker {
426
790
  * the values of a case or pass; null otherwise, and then both branches are walked under the condition.
427
791
  */
428
792
  known(test, context) {
429
- if (!this.options.expandCases || context.test || context.hookScope)
793
+ if ((!this.options.expandCases && !this.options.collectImports && !context.registration) ||
794
+ context.test ||
795
+ context.hookScope)
430
796
  return null;
431
797
  // Only the values of the case, pass or helper call decide: a constant of the module may be changed in ways the scan
432
798
  // doesn't see, and taking a branch away would drop a test the runner registers.
@@ -442,11 +808,25 @@ class Walker {
442
808
  * condition; a branch taken for certain, or both branches leaving, ends the walk. A branch that leaves on only some
443
809
  * of its paths leaves what follows as it is.
444
810
  */
445
- visitStatements(statements, context) {
811
+ visitStatements(statements, context, start = 0) {
446
812
  let current = context;
447
- for (const statement of statements) {
813
+ for (let index = start; index < statements.length; index++) {
814
+ const task = current.registration?.asyncCall;
815
+ if (current.registration?.returned)
816
+ return;
817
+ if (task?.atAwait && task.body === this.parents.at(-1)) {
818
+ if (!current.skipImports && !task.pending && current.registration?.failure === undefined)
819
+ this.deferStatements(statements, index, current, task.body);
820
+ return;
821
+ }
822
+ const statement = statements[index];
448
823
  this.visit(statement, current);
449
- if (statement.type !== 'IfStatement' || isImportMetaVitest(statement.test))
824
+ if (statement.type !== 'IfStatement') {
825
+ if ((this.options.collectImports || context.registration) && alwaysLeaves(statement))
826
+ current = { ...current, skipImports: true };
827
+ continue;
828
+ }
829
+ if (isImportMetaVitest(statement.test))
450
830
  continue;
451
831
  const thenLeaves = alwaysLeaves(statement.consequent);
452
832
  const elseLeaves = statement.alternate !== null && alwaysLeaves(statement.alternate);
@@ -454,14 +834,78 @@ class Walker {
454
834
  continue;
455
835
  const known = this.known(statement.test, current);
456
836
  const taken = known && (known.value ? thenLeaves : elseLeaves);
457
- if (taken || (thenLeaves && elseLeaves))
837
+ if ((taken && this.options.expandCases) || (thenLeaves && elseLeaves))
458
838
  return;
459
- if (known)
839
+ if (known && (this.options.expandCases || (context.registration && !taken)))
460
840
  continue;
461
841
  const condition = this.text(statement.test);
462
842
  current = this.guarded(current, thenLeaves ? `!(${condition})` : condition);
843
+ if (taken)
844
+ current.skipImports = true;
463
845
  }
464
846
  }
847
+ /** Terminal outcomes of the built-in Promise constructor and its static methods that the scan can prove. */
848
+ awaitedFailure(expression) {
849
+ if (this.frame.values.declarationOf('Promise', this.scopes) ||
850
+ this.frame.values.assignedIn(this.frame.parsed.program).has('Promise'))
851
+ return null;
852
+ let node = unwrap(expression);
853
+ while (node.type === 'CallExpression') {
854
+ const method = unwrap(node.callee);
855
+ if (method.type !== 'MemberExpression' || method.object.type !== 'Identifier' || method.object.name !== 'Promise')
856
+ return null;
857
+ if (propertyName(method) === 'reject')
858
+ return 'rejected';
859
+ const value = node.arguments.at(0);
860
+ if (propertyName(method) !== 'resolve' || !value || value.type === 'SpreadElement')
861
+ return null;
862
+ node = unwrap(value);
863
+ }
864
+ if (node.type !== 'NewExpression' || node.callee.type !== 'Identifier' || node.callee.name !== 'Promise')
865
+ return null;
866
+ const executor = node.arguments[0];
867
+ if (!isFunctionNode(executor) ||
868
+ !executor.params.every((p) => p.type === 'Identifier') ||
869
+ executor.body?.type !== 'BlockStatement')
870
+ return null;
871
+ return executor.body.body.every((s) => s.type === 'VariableDeclaration' &&
872
+ ['var', 'let', 'const'].includes(s.kind) &&
873
+ s.declarations.every((d) => d.id.type === 'Identifier' && d.init?.type === 'Literal'))
874
+ ? 'pending'
875
+ : null;
876
+ }
877
+ /** Resume in the active file suite, retaining the lexical environment where the helper suspended. */
878
+ deferStatements(statements, index, context, body) {
879
+ const { frame, site, importDepth } = this;
880
+ const scopes = this.scopes.slice(), parents = this.parents.slice(), calls = this.callStack.slice();
881
+ this.continuations.push(frame.values.captureBindings((root) => {
882
+ this.frame = frame;
883
+ this.site = site;
884
+ this.importDepth = importDepth;
885
+ this.scopes.push(...scopes);
886
+ this.parents.push(...parents);
887
+ this.callStack.push(...calls);
888
+ this.asyncRegistration(root, body, (registration) => {
889
+ this.visitStatements(statements, {
890
+ ...context,
891
+ scope: root.scope ?? this.fileScope,
892
+ registration,
893
+ emptySuiteAt: undefined,
894
+ expandedAt: this.main.parsed.program.end + 1,
895
+ }, index);
896
+ });
897
+ this.callStack.length = this.parents.length = this.scopes.length = 0;
898
+ this.importDepth = 0;
899
+ this.site = null;
900
+ this.frame = this.main;
901
+ }));
902
+ }
903
+ asyncRegistration(caller, body, visit) {
904
+ const asyncCall = { body };
905
+ const registration = { ...caller, asyncCall };
906
+ visit(registration);
907
+ caller.scope = asyncCall.atAwait ? asyncCall.atAwait.scope : (registration.recoveryScope ?? registration.scope);
908
+ }
465
909
  placement(context) {
466
910
  return {
467
911
  scope: context.scope,
@@ -475,17 +919,118 @@ class Walker {
475
919
  catchCondition(handler) {
476
920
  return this.text({ start: handler.start, end: handler.body.start }).trim();
477
921
  }
478
- guarded(context, guard) {
479
- return { ...context, isInCondition: true, guards: guard === null ? context.guards : [...context.guards, guard] };
922
+ /** First case entered at collection, -1 for none, or null when a value cannot be determined. */
923
+ switchStart(node, context) {
924
+ if (!this.options.collectImports)
925
+ return null;
926
+ const key = this.known(node.discriminant, context);
927
+ if (!key || (key.value !== null && typeof key.value === 'object'))
928
+ return null;
929
+ let fallback = -1;
930
+ for (const [index, entry] of node.cases.entries()) {
931
+ if (entry.test === null)
932
+ fallback = index;
933
+ else {
934
+ const value = this.known(entry.test, context);
935
+ if (!value)
936
+ return null;
937
+ if (value.value === key.value)
938
+ return index;
939
+ }
940
+ }
941
+ return fallback;
942
+ }
943
+ visitBranch(node, context, guard, selected) {
944
+ if (selected !== null && (this.options.expandCases || context.evaluatingArgument)) {
945
+ if (selected)
946
+ this.visit(node, context);
947
+ return;
948
+ }
949
+ const guarded = this.guarded(context, guard, selected === true);
950
+ this.visit(node, selected === false ? { ...guarded, skipImports: true } : guarded);
951
+ }
952
+ guarded(context, guard, certain = false) {
953
+ return {
954
+ ...context,
955
+ isInCondition: true,
956
+ guards: guard === null ? context.guards : [...context.guards, guard],
957
+ registration: certain ? context.registration : possibleRegistration(context.registration),
958
+ };
959
+ }
960
+ advanceIterator(call, context, registration) {
961
+ const callee = unwrap(call.callee);
962
+ if (callee.type !== 'MemberExpression' || context.skipImports || registration.failure !== undefined)
963
+ return false;
964
+ const name = propertyName(callee);
965
+ if (name !== 'return' && name !== 'throw' && name !== 'next')
966
+ return false;
967
+ const values = this.frame.values;
968
+ values.iteratorMethods.delete(call);
969
+ const token = values.iteratorOf(callee.object, this.scopes);
970
+ if (!token)
971
+ return false;
972
+ this.argumentRevision++;
973
+ const unknownObject = { ok: false, importedFrom: null, defined: true, truthy: true, nonIterable: true };
974
+ if (this.registrationArguments(call, context)) {
975
+ values.iteratorMethods.set(call, { outcome: 'throw', result: unknownObject, registered: false });
976
+ return true;
977
+ }
978
+ const { args, complete } = values.callArguments(call, this.scopes, true, (operand) => this.readArgument(operand, true));
979
+ const first = args[0] ?? (complete ? omitted : { ok: false, importedFrom: null });
980
+ const use = {
981
+ ...context,
982
+ evaluatingArgument: true,
983
+ expandedAt: context.expandedAt ?? context.registeredBy?.start ?? call.start,
984
+ };
985
+ const step = this.resumeIterator(token, use, registration, name, first);
986
+ const result = step.outcome === 'next' && step.result.ok
987
+ ? { ok: true, value: { value: step.result.value, done: step.position === 'closed' } }
988
+ : unknownObject;
989
+ values.iteratorMethods.set(call, { outcome: step.outcome, registered: step.registered, result });
990
+ if (step.outcome === 'throw')
991
+ this.stopRegistration(call, context, step.result);
992
+ return true;
993
+ }
994
+ stopRegistration(node, context, value) {
995
+ if (context.registration && !context.skipImports)
996
+ context.registration.failure ??= {
997
+ line: this.lineOf(node),
998
+ value: node.type === 'ThrowStatement' ? this.readArgument(node.argument, true) : value,
999
+ };
1000
+ }
1001
+ readsUninitialized(node, parameters) {
1002
+ for (let entry = parameters; entry; entry = entry.outer) {
1003
+ if (!entry.pending.has(node.name) || this.frame.values.declarationOf(node.name, this.scopes) !== entry.fn)
1004
+ continue;
1005
+ const parent = this.parents[this.parents.length - 2];
1006
+ const key = Object.entries(parent).find(([, child]) => child === node)?.[0] ?? null;
1007
+ return isReference(key, parent);
1008
+ }
1009
+ return false;
480
1010
  }
481
1011
  /** Visits the body of a callback the framework or a loop calls, rather than a plain function. */
482
- visitCallback(fn, context) {
1012
+ visitCallback(fn, context, parameterSteps) {
483
1013
  this.scopes.push(fn);
484
1014
  this.parents.push(fn);
1015
+ const bindings = parameterSteps
1016
+ ? {
1017
+ ...context,
1018
+ evaluatingArgument: true,
1019
+ parameters: {
1020
+ fn,
1021
+ steps: parameterSteps,
1022
+ pending: new Set(fn.params.flatMap((param) => bindingNames(param))),
1023
+ outer: context.parameters,
1024
+ },
1025
+ }
1026
+ : context;
485
1027
  for (const parameter of fn.params)
486
- this.visit(parameter, context);
1028
+ this.visit(parameter, bindings);
487
1029
  // Function expressions and arrows always have a body; only declarations of overloads don't.
488
- this.visit(fn.body, context);
1030
+ if (!parameterSteps || (!fn.generator && bindings.registration?.failure === undefined))
1031
+ this.visit(fn.body, context);
1032
+ if (context.registration?.returned)
1033
+ context.registration.returned = false;
489
1034
  this.parents.pop();
490
1035
  this.scopes.pop();
491
1036
  }
@@ -497,6 +1042,7 @@ class Walker {
497
1042
  return {
498
1043
  ...context,
499
1044
  isInLoop: true,
1045
+ registration: passes ? context.registration : possibleRegistration(context.registration),
500
1046
  loops: [...context.loops, passes],
501
1047
  loopConditions: [...context.loopConditions, context.isInCondition || pass !== null],
502
1048
  caseIndex: pass?.index ?? context.caseIndex,
@@ -593,7 +1139,8 @@ class Walker {
593
1139
  else {
594
1140
  const count = values?.length ?? (leaves ? null : this.frame.values.lengthOf(callee.object, this.scopes));
595
1141
  this.walkUnexpanded(call, expands === 'limit', () => {
596
- this.visitCallback(arg, this.inLoop(context, count));
1142
+ const loop = this.inLoop(context, count);
1143
+ this.visitCallback(arg, list?.length === 0 ? { ...loop, skipImports: true } : loop);
597
1144
  });
598
1145
  }
599
1146
  }
@@ -604,17 +1151,36 @@ class Walker {
604
1151
  return true;
605
1152
  }
606
1153
  call(call, context) {
607
- const api = this.frame.adapter.classify(call, {
1154
+ const classify = () => this.frame.adapter.classify(call, {
608
1155
  scopes: this.scopes,
609
1156
  testContext: context.testContext,
610
1157
  inTest: context.test !== null,
611
1158
  inBody: context.test !== null || context.hookScope !== null,
612
1159
  passedDown: context.scope.suite?.declaration.passesDown ?? null,
1160
+ handlesRegistrationError: !!context.registration && context.handlesRegistrationError,
613
1161
  returnsOf: (name, scopes) => this.returnsOf(name, scopes),
614
1162
  });
1163
+ const api = classify();
615
1164
  if (!api)
616
1165
  return false;
617
- return this.handle(call, api, context);
1166
+ const revision = this.argumentRevision;
1167
+ if (this.registrationArguments(call, context))
1168
+ return true;
1169
+ // A spread or an explicit iterator step can supply a title during argument evaluation.
1170
+ return this.handle(call, revision === this.argumentRevision ? api : classify(), this.currentScope(context));
1171
+ }
1172
+ /** Whether argument evaluation stopped a call during collection, or null outside live Jasmine registration. */
1173
+ registrationArguments(call, context) {
1174
+ if (!context.registration || context.skipImports || context.registration.failure !== undefined)
1175
+ return null;
1176
+ const args = {
1177
+ ...context,
1178
+ evaluatingArgument: true,
1179
+ expandedAt: context.expandedAt ?? context.registeredBy?.start ?? call.start,
1180
+ };
1181
+ for (const arg of call.arguments)
1182
+ this.visit(arg, args);
1183
+ return args.registration?.failure !== undefined;
618
1184
  }
619
1185
  handle(call, api, context) {
620
1186
  switch (api.kind) {
@@ -675,6 +1241,8 @@ class Walker {
675
1241
  case 'hook':
676
1242
  if (context.test)
677
1243
  return false;
1244
+ if (context.registration?.failure !== undefined)
1245
+ return true;
678
1246
  // A function with a name registers its hooks where it is called, not where it is written.
679
1247
  if (!context.hookScope && context.declaredIn === null) {
680
1248
  context.scope.hooks[api.name] += 1;
@@ -689,6 +1257,7 @@ class Walker {
689
1257
  this.visitCallback(api.fn, {
690
1258
  ...context,
691
1259
  hookScope: context.scope,
1260
+ registration: undefined,
692
1261
  hookName: api.name,
693
1262
  testContext: api.testContext,
694
1263
  guards: [],
@@ -701,6 +1270,7 @@ class Walker {
701
1270
  context.test?.problems.push(...api.problems.map((item) => this.here(item)));
702
1271
  return true;
703
1272
  case 'invalid': {
1273
+ this.stopRegistration(call, context);
704
1274
  // Code that runs after the file loads, only when a condition holds, or in a function the scan can't place, which
705
1275
  // runs only if something calls it, can't be sure to stop it loading.
706
1276
  const afterLoad = context.test !== null ||
@@ -709,7 +1279,11 @@ class Walker {
709
1279
  context.declaredIn !== null ||
710
1280
  context.calledIn !== null ||
711
1281
  context.isInCondition;
712
- this.report({ ...api.problem, afterLoad: afterLoad || api.problem.afterLoad, scope: context.scope });
1282
+ this.report({
1283
+ ...api.problem,
1284
+ afterLoad: afterLoad || context.registration !== undefined || api.problem.afterLoad,
1285
+ scope: context.scope,
1286
+ });
713
1287
  // Under a condition, the call either never runs or fails the file, so it declares nothing either way.
714
1288
  return api.declaration && !context.isInCondition ? this.handle(call, api.declaration, context) : true;
715
1289
  }
@@ -737,12 +1311,25 @@ class Walker {
737
1311
  helperCall(call, context) {
738
1312
  const callee = unwrap(call.callee);
739
1313
  const runsHere = !context.test && !context.hookScope && !context.helper && this.callStack.length < MAX_DEPTH;
1314
+ if (runsHere &&
1315
+ (this.options.collectImports || context.registration) &&
1316
+ (callee.type === 'ArrowFunctionExpression' ||
1317
+ (callee.type === 'FunctionExpression' && (!callee.generator || context.registration))))
1318
+ return this.withinLimit({ fn: callee, frame: this.frame }, call);
740
1319
  if (callee.type === 'MemberExpression') {
741
1320
  const object = unwrap(callee.object);
742
1321
  const member = propertyName(callee);
743
- const imported = runsHere && object.type === 'Identifier' && member !== null
744
- ? this.importedFunction(object.name, this.scopes, this.frame, member)
745
- : null;
1322
+ if (!runsHere || member === null)
1323
+ return null;
1324
+ let imported = null;
1325
+ if (object.type === 'Identifier') {
1326
+ imported = this.importedFunction(object.name, this.scopes, this.frame, member);
1327
+ }
1328
+ else {
1329
+ const source = requiredModule(object);
1330
+ if (source !== null && !this.frame.values.declarationOf('require', this.scopes))
1331
+ imported = this.functionFrom(this.frame, source, member);
1332
+ }
746
1333
  return imported && !this.callStack.includes(imported.fn) ? this.withinLimit(imported, call) : null;
747
1334
  }
748
1335
  if (callee.type !== 'Identifier')
@@ -826,8 +1413,11 @@ class Walker {
826
1413
  const imported = from.values.importedName(name, scopes);
827
1414
  const whole = imported === null || from.values.declarationOf(name, scopes)?.type === 'VariableDeclarator';
828
1415
  const exported = member === null ? imported : whole ? member : null;
829
- const frame = exported === null ? null : this.openFrom(from, source);
830
- return frame ? this.exportedFunction(frame, exported, new Set(), 0) : null;
1416
+ return exported === null ? null : this.functionFrom(from, source, exported);
1417
+ }
1418
+ functionFrom(from, source, name) {
1419
+ const frame = this.openFrom(from, source);
1420
+ return frame ? this.exportedFunction(frame, name, new Set(), 0) : null;
831
1421
  }
832
1422
  /** A module a file imports, read as a frame once; null when it can't be read or parsed. */
833
1423
  openFrom(frame, source) {
@@ -896,16 +1486,129 @@ class Walker {
896
1486
  return local(value.name);
897
1487
  return isFunctionNode(value) ? { fn: value, frame } : null;
898
1488
  }
1489
+ readArgument(operand, atRegistration) {
1490
+ const { adapter, values } = this.frame;
1491
+ return atRegistration && adapter.registrationValue
1492
+ ? adapter.registrationValue(operand, this.scopes)
1493
+ : values.resolve(operand, this.scopes);
1494
+ }
1495
+ resumeIterator(token, context, registration, method, argument) {
1496
+ const position = registration.iterators.get(token);
1497
+ registration.iterators.set(token, 'running');
1498
+ const run = this.iterators.get(token);
1499
+ const step = run({ context, method, argument, position });
1500
+ registration.iterators.set(token, step.position);
1501
+ return step;
1502
+ }
1503
+ saveIterator({ fn, frame }, scopes, readSpread) {
1504
+ const token = { ok: false, importedFrom: null, defined: true, truthy: true, iterator: true };
1505
+ this.iterators.set(token, frame.values.captureBindings(({ context: use, method, position, argument }) => {
1506
+ const previousFrame = this.frame;
1507
+ const previousScopes = this.scopes.splice(0, this.scopes.length, ...scopes, fn);
1508
+ this.frame = frame;
1509
+ this.parents.push(fn);
1510
+ this.callStack.push(fn);
1511
+ try {
1512
+ const caller = use.registration;
1513
+ const registration = { ...caller };
1514
+ const context = { ...use, registration, isInFunction: true, declaredIn: null };
1515
+ const before = this.tests.length + this.suites.length;
1516
+ const evaluate = (node, around, readValue, handlesThrow, parameters) => {
1517
+ this.scopes.splice(0, this.scopes.length, ...scopes, fn, ...around);
1518
+ this.visit(node, {
1519
+ ...context,
1520
+ parameters: parameters ?? use.parameters,
1521
+ handlesRegistrationError: handlesThrow || use.handlesRegistrationError,
1522
+ });
1523
+ if (registration.failure !== undefined) {
1524
+ const thrown = registration.failure.value ?? { ok: false, importedFrom: null };
1525
+ registration.scope = registration.recoveryScope ?? registration.scope;
1526
+ delete registration.recoveryScope;
1527
+ delete registration.failure;
1528
+ return { thrown };
1529
+ }
1530
+ return readValue ? this.readArgument(node, true) : omitted;
1531
+ };
1532
+ const body = fn.body;
1533
+ const yielded = { values: [], complete: true };
1534
+ const previous = typeof position === 'object' ? position.locals : undefined;
1535
+ const locals = { operands: new Map(previous?.operands), catches: new Map(previous?.catches) };
1536
+ const enterCall = (name, around) => {
1537
+ // If an argument suspends or throws, the helper body cannot register at its declaration.
1538
+ const callee = this.functionNamed(name, [...scopes, fn, ...around]);
1539
+ if (callee)
1540
+ this.walkedAtCall.add(callee);
1541
+ };
1542
+ const collect = (spread) => {
1543
+ if (yielded.complete) {
1544
+ for (const item of spread.values)
1545
+ yielded.values.push(item);
1546
+ yielded.complete = spread.complete;
1547
+ }
1548
+ return spread.outcome;
1549
+ };
1550
+ const env = {
1551
+ locals,
1552
+ evaluate,
1553
+ bindCatch: (clause, around, value, handlesThrow) => {
1554
+ const steps = frame.values.bindCatch(clause, value, [...scopes, fn, ...around], locals);
1555
+ return evaluate(clause.param, around, false, handlesThrow, {
1556
+ fn: clause,
1557
+ steps,
1558
+ pending: new Set(bindingNames(clause.param)),
1559
+ outer: use.parameters,
1560
+ });
1561
+ },
1562
+ enterCall,
1563
+ iteratorOf: (operand, around) => frame.values.iteratorOf(operand, [...scopes, fn, ...around]),
1564
+ resumeDelegate: (iterator, next, value, handlesThrow) => {
1565
+ const step = this.resumeIterator(iterator, { ...context, handlesRegistrationError: handlesThrow || use.handlesRegistrationError }, registration, method === 'spread' ? 'spread' : next, value);
1566
+ if (method === 'spread')
1567
+ collect(step);
1568
+ return { position: step.position, outcome: step.outcome, value: step.result };
1569
+ },
1570
+ spreadDelegate: method === 'spread'
1571
+ ? (operand, around) => collect(readSpread(operand, [...scopes, fn, ...around]))
1572
+ : undefined,
1573
+ };
1574
+ const step = frame.values.withGeneratorLocals(locals, () => {
1575
+ let next = stepGenerator(body, position, method === 'spread' ? 'next' : method, argument, env);
1576
+ while (method === 'spread' && typeof next.position === 'object') {
1577
+ if (yielded.complete)
1578
+ yielded.values.push(next.value);
1579
+ next = stepGenerator(body, next.position, 'next', omitted, env);
1580
+ }
1581
+ return next;
1582
+ });
1583
+ caller.scope = registration.scope;
1584
+ return {
1585
+ values: yielded.values,
1586
+ complete: yielded.complete && step.outcome !== 'unknown',
1587
+ registered: this.tests.length + this.suites.length > before,
1588
+ outcome: step.outcome,
1589
+ position: step.position,
1590
+ result: step.value,
1591
+ };
1592
+ }
1593
+ finally {
1594
+ this.callStack.pop();
1595
+ this.parents.pop();
1596
+ this.frame = previousFrame;
1597
+ this.scopes.splice(0, this.scopes.length, ...previousScopes);
1598
+ }
1599
+ }));
1600
+ return token;
1601
+ }
899
1602
  /**
900
1603
  * Walks a function at one of its calls from the file or a describe, as the runner runs it there: with the scopes
901
1604
  * where it is written, and its parameters bound to the call's arguments so that titles built from them resolve. A
902
1605
  * function imported from another module is walked in that module, and what it registers points at this call.
903
1606
  */
904
- walkAtCall({ fn, frame }, call, context) {
1607
+ walkAtCall({ fn, frame }, call, context, registering) {
905
1608
  this.walkedAtCall.add(fn);
906
1609
  // Arguments are worked out where the call is, in the file and scopes of the caller.
907
- const spread = call.arguments.findIndex((item) => item.type === 'SpreadElement');
908
- const args = (spread === -1 ? call.arguments : call.arguments.slice(0, spread)).map((item) => this.frame.values.resolve(item, this.scopes));
1610
+ const { args, complete } = this.frame.values.callArguments(call, this.scopes, registering, (operand) => this.readArgument(operand, registering));
1611
+ const parameterSteps = registering ? new Map() : undefined;
909
1612
  const caller = this.frame;
910
1613
  const site = this.site;
911
1614
  if (frame !== caller) {
@@ -915,15 +1618,32 @@ class Walker {
915
1618
  const scopes = this.scopeChain(fn);
916
1619
  const saved = this.scopes.splice(0, this.scopes.length, ...scopes);
917
1620
  this.callStack.push(fn);
1621
+ const returned = { fn };
918
1622
  frame.values.withArguments(fn, args, scopes, () => {
919
- this.visitCallback(fn, {
920
- ...context,
921
- isInFunction: true,
922
- declaredIn: null,
923
- calledIn: context.declaredIn ? { fn: context.declaredIn, call } : context.calledIn,
924
- registeredBy: context.registeredBy ?? call,
925
- });
926
- }, spread === -1);
1623
+ const visitBody = (registration) => {
1624
+ this.visitCallback(fn, {
1625
+ ...context,
1626
+ registration,
1627
+ iteratorReturn: returned,
1628
+ isInFunction: true,
1629
+ declaredIn: null,
1630
+ calledIn: context.declaredIn ? { fn: context.declaredIn, call } : context.calledIn,
1631
+ registeredBy: context.registeredBy ?? call,
1632
+ }, parameterSteps);
1633
+ };
1634
+ if (registering && context.registration && fn.async && !fn.generator)
1635
+ this.asyncRegistration(context.registration, fn.body, visitBody);
1636
+ else
1637
+ visitBody(context.registration);
1638
+ if (registering && fn.generator && !fn.async && frame.adapter.registrationSpread) {
1639
+ returned.value = this.saveIterator({ fn, frame }, scopes, frame.adapter.registrationSpread.bind(frame.adapter));
1640
+ }
1641
+ else if (registering && fn.type === 'ArrowFunctionExpression' && fn.body.type !== 'BlockStatement') {
1642
+ returned.value = frame.values.iteratorOf(fn.body, [...scopes, fn]);
1643
+ }
1644
+ }, complete, parameterSteps);
1645
+ if (registering)
1646
+ caller.values.recordIterator(call, saved, returned.value);
927
1647
  this.callStack.pop();
928
1648
  this.scopes.splice(0, this.scopes.length, ...saved);
929
1649
  // What the module's own imports couldn't resolve is reported at the call, as it is why tests may be missing. Another
@@ -952,6 +1672,7 @@ class Walker {
952
1672
  helper: fn,
953
1673
  guards: [],
954
1674
  declaredIn: fn,
1675
+ registration: undefined,
955
1676
  quiet: this.walkedAtCall.has(fn),
956
1677
  });
957
1678
  this.scopes.splice(0, this.scopes.length, ...savedScopes);
@@ -1285,6 +2006,9 @@ class Walker {
1285
2006
  if (!title || title.isDynamic)
1286
2007
  return single("the scan can't work out the title");
1287
2008
  const titles = declaration.cases.map((item) => item.title);
2009
+ const problemTitle = titles.find((text) => text !== null && typeof text === 'object');
2010
+ if (problemTitle)
2011
+ return single(problemTitle.reason);
1288
2012
  if (titles.some((text) => text === null)) {
1289
2013
  return single("the title shows a value the scan doesn't format the way the runner does");
1290
2014
  }
@@ -1302,9 +2026,13 @@ class Walker {
1302
2026
  }));
1303
2027
  }
1304
2028
  declareCase(call, { declaration, index, args }, context) {
2029
+ const registrationStoppedAt = context.registration?.failure?.line ?? context.emptySuiteAt;
2030
+ if (registrationStoppedAt !== undefined && declaration.isOnly)
2031
+ declaration = { ...declaration, isOnly: false };
1305
2032
  const statement = this.statement(call);
1306
2033
  const empty = emptyTitle(declaration, call);
1307
2034
  const test = {
2035
+ registrationStoppedAt,
1308
2036
  scope: context.scope,
1309
2037
  parent: context.test,
1310
2038
  declaration,
@@ -1342,6 +2070,7 @@ class Walker {
1342
2070
  this.visitCallback(body, {
1343
2071
  ...context,
1344
2072
  test,
2073
+ registration: undefined,
1345
2074
  hookScope: null,
1346
2075
  hookName: null,
1347
2076
  stepDepth: 0,
@@ -1388,6 +2117,8 @@ class Walker {
1388
2117
  this.declareSuiteCase(call, item, context);
1389
2118
  }
1390
2119
  declareSuiteCase(call, { declaration, index, args }, context) {
2120
+ if ((context.registration?.failure !== undefined || context.emptySuiteAt !== undefined) && declaration.isOnly)
2121
+ declaration = { ...declaration, isOnly: false };
1391
2122
  for (const item of [...declaration.problems, ...emptyTitle(declaration, call)])
1392
2123
  this.report(item);
1393
2124
  const scope = {
@@ -1427,6 +2158,14 @@ class Walker {
1427
2158
  this.visitCallback(fn, {
1428
2159
  ...context,
1429
2160
  scope,
2161
+ registration: this.frame.adapter.catchesSuiteErrors
2162
+ ? {
2163
+ failure: context.registration?.failure,
2164
+ iterators: context.registration?.iterators ?? new Map(),
2165
+ }
2166
+ : undefined,
2167
+ emptySuiteAt: context.emptySuiteAt ?? (declaration.emptySuiteError ? this.lineOf(call) : undefined),
2168
+ handlesRegistrationError: false,
1430
2169
  test: null,
1431
2170
  hookScope: null,
1432
2171
  hookName: null,
@@ -1441,6 +2180,15 @@ class Walker {
1441
2180
  });
1442
2181
  });
1443
2182
  });
2183
+ const error = declaration.emptySuiteError;
2184
+ if (error) {
2185
+ this.report({ ...error.problem, afterLoad: true, scope: context.scope });
2186
+ if (context.registration && !context.skipImports && context.registration.failure === undefined) {
2187
+ context.registration.failure = { line: this.lineOf(call) };
2188
+ if (error.keepsScope)
2189
+ context.registration.recoveryScope = scope;
2190
+ }
2191
+ }
1444
2192
  }
1445
2193
  /** The statement a call forms, such as `test(...);`, or the call itself when it is part of a larger expression. */
1446
2194
  statement(call) {