vitest 3.2.0-beta.1 → 3.2.0-beta.2

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 (46) hide show
  1. package/LICENSE.md +0 -232
  2. package/dist/browser.d.ts +2 -0
  3. package/dist/browser.js +3 -4
  4. package/dist/chunks/{base.SfTiRNZf.js → base.DwtwORaC.js} +2 -2
  5. package/dist/chunks/{cac.TfX2-DVH.js → cac.I9MLYfT-.js} +10 -8
  6. package/dist/chunks/{cli-api.2970Nj9J.js → cli-api.d6IK1pnk.js} +48 -16
  7. package/dist/chunks/{coverage.z0LVMxgb.js → coverage.OGU09Jbh.js} +126 -4215
  8. package/dist/chunks/{creator.CuL7xDWI.js → creator.DGAdZ4Hj.js} +18 -39
  9. package/dist/chunks/{execute.BpmIjFTD.js → execute.JlGHLJZT.js} +3 -5
  10. package/dist/chunks/{global.d.BCOHQEpR.d.ts → global.d.BPa1eL3O.d.ts} +10 -10
  11. package/dist/chunks/{globals.Cg4NtV4P.js → globals.CpxW8ccg.js} +1 -2
  12. package/dist/chunks/{index.Bw6JxgX8.js → index.CK1YOQaa.js} +7 -7
  13. package/dist/chunks/{index.CUacZlWG.js → index.CV36oG_L.js} +881 -948
  14. package/dist/chunks/{index.BPc7M5ni.js → index.CfXMNXHg.js} +1 -13
  15. package/dist/chunks/index.CmC5OK9L.js +275 -0
  16. package/dist/chunks/{index.DbWBPwtH.js → index.DswW_LEs.js} +1 -1
  17. package/dist/chunks/{index.DBIGubLC.js → index.X0nbfr6-.js} +7 -7
  18. package/dist/chunks/{reporters.d.DGm4k1Wx.d.ts → reporters.d.CLC9rhKy.d.ts} +17 -0
  19. package/dist/chunks/{runBaseTests.CguliJB5.js → runBaseTests.Dn2vyej_.js} +3 -4
  20. package/dist/chunks/{setup-common.BP6KrF_Z.js → setup-common.CYo3Y0dD.js} +1 -3
  21. package/dist/chunks/typechecker.DnTrplSJ.js +897 -0
  22. package/dist/chunks/{vite.d.DjP_ALCZ.d.ts → vite.d.CBZ3M_ru.d.ts} +1 -1
  23. package/dist/chunks/{vm.CuLHT1BG.js → vm.C1HHjtNS.js} +1 -1
  24. package/dist/cli.js +20 -1
  25. package/dist/config.d.ts +3 -3
  26. package/dist/coverage.d.ts +1 -1
  27. package/dist/coverage.js +4 -7
  28. package/dist/execute.js +1 -1
  29. package/dist/index.d.ts +5 -27
  30. package/dist/index.js +1 -2
  31. package/dist/node.d.ts +4 -4
  32. package/dist/node.js +16 -18
  33. package/dist/reporters.d.ts +1 -1
  34. package/dist/reporters.js +14 -14
  35. package/dist/workers/forks.js +2 -2
  36. package/dist/workers/runVmTests.js +3 -4
  37. package/dist/workers/threads.js +2 -2
  38. package/dist/workers/vmForks.js +2 -2
  39. package/dist/workers/vmThreads.js +2 -2
  40. package/dist/workers.js +3 -3
  41. package/package.json +15 -19
  42. package/dist/chunks/run-once.Dimr7O9f.js +0 -47
  43. package/dist/chunks/typechecker.DYQbn8uK.js +0 -956
  44. package/dist/chunks/utils.8gfOgtry.js +0 -207
  45. package/dist/utils.d.ts +0 -3
  46. package/dist/utils.js +0 -2
@@ -0,0 +1,897 @@
1
+ import nodeos__default from 'node:os';
2
+ import { performance } from 'node:perf_hooks';
3
+ import { TraceMap, generatedPositionFor, eachMapping } from '@vitest/utils/source-map';
4
+ import { relative, basename, resolve, join } from 'pathe';
5
+ import { x } from 'tinyexec';
6
+ import { distDir } from '../path.js';
7
+ import { getTests, generateHash, calculateSuiteHash, someTasksAreOnly, interpretTaskModes } from '@vitest/runner/utils';
8
+ import '@vitest/utils';
9
+ import { parseAstAsync } from 'vite';
10
+
11
+ function hasFailedSnapshot(suite) {
12
+ return getTests(suite).some((s) => {
13
+ return s.result?.errors?.some((e) => typeof e?.message === "string" && e.message.match(/Snapshot .* mismatched/));
14
+ });
15
+ }
16
+ function convertTasksToEvents(file, onTask) {
17
+ const packs = [];
18
+ const events = [];
19
+ function visit(suite) {
20
+ onTask?.(suite);
21
+ packs.push([
22
+ suite.id,
23
+ suite.result,
24
+ suite.meta
25
+ ]);
26
+ events.push([suite.id, "suite-prepare"]);
27
+ suite.tasks.forEach((task) => {
28
+ if (task.type === "suite") {
29
+ visit(task);
30
+ } else {
31
+ onTask?.(task);
32
+ if (suite.mode !== "skip" && suite.mode !== "todo") {
33
+ packs.push([
34
+ task.id,
35
+ task.result,
36
+ task.meta
37
+ ]);
38
+ events.push([task.id, "test-prepare"], [task.id, "test-finished"]);
39
+ }
40
+ }
41
+ });
42
+ events.push([suite.id, "suite-finished"]);
43
+ }
44
+ visit(file);
45
+ return {
46
+ packs,
47
+ events
48
+ };
49
+ }
50
+
51
+ const REGEXP_WRAP_PREFIX = "$$vitest:";
52
+ function getOutputFile(config, reporter) {
53
+ if (!config?.outputFile) {
54
+ return;
55
+ }
56
+ if (typeof config.outputFile === "string") {
57
+ return config.outputFile;
58
+ }
59
+ return config.outputFile[reporter];
60
+ }
61
+ /**
62
+ * Prepares `SerializedConfig` for serialization, e.g. `node:v8.serialize`
63
+ */
64
+ function wrapSerializableConfig(config) {
65
+ let testNamePattern = config.testNamePattern;
66
+ let defines = config.defines;
67
+ if (testNamePattern && typeof testNamePattern !== "string") {
68
+ testNamePattern = `${REGEXP_WRAP_PREFIX}${testNamePattern.toString()}`;
69
+ }
70
+ if (defines) {
71
+ defines = {
72
+ keys: Object.keys(defines),
73
+ original: defines
74
+ };
75
+ }
76
+ return {
77
+ ...config,
78
+ testNamePattern,
79
+ defines
80
+ };
81
+ }
82
+
83
+ // AST walker module for ESTree compatible trees
84
+
85
+
86
+ // An ancestor walk keeps an array of ancestor nodes (including the
87
+ // current node) and passes them to the callback as third parameter
88
+ // (and also as state parameter when no other state is present).
89
+ function ancestor(node, visitors, baseVisitor, state, override) {
90
+ var ancestors = [];
91
+ if (!baseVisitor) { baseVisitor = base
92
+ ; }(function c(node, st, override) {
93
+ var type = override || node.type;
94
+ var isNew = node !== ancestors[ancestors.length - 1];
95
+ if (isNew) { ancestors.push(node); }
96
+ baseVisitor[type](node, st, c);
97
+ if (visitors[type]) { visitors[type](node, st || ancestors, ancestors); }
98
+ if (isNew) { ancestors.pop(); }
99
+ })(node, state, override);
100
+ }
101
+
102
+ function skipThrough(node, st, c) { c(node, st); }
103
+ function ignore(_node, _st, _c) {}
104
+
105
+ // Node walkers.
106
+
107
+ var base = {};
108
+
109
+ base.Program = base.BlockStatement = base.StaticBlock = function (node, st, c) {
110
+ for (var i = 0, list = node.body; i < list.length; i += 1)
111
+ {
112
+ var stmt = list[i];
113
+
114
+ c(stmt, st, "Statement");
115
+ }
116
+ };
117
+ base.Statement = skipThrough;
118
+ base.EmptyStatement = ignore;
119
+ base.ExpressionStatement = base.ParenthesizedExpression = base.ChainExpression =
120
+ function (node, st, c) { return c(node.expression, st, "Expression"); };
121
+ base.IfStatement = function (node, st, c) {
122
+ c(node.test, st, "Expression");
123
+ c(node.consequent, st, "Statement");
124
+ if (node.alternate) { c(node.alternate, st, "Statement"); }
125
+ };
126
+ base.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
127
+ base.BreakStatement = base.ContinueStatement = ignore;
128
+ base.WithStatement = function (node, st, c) {
129
+ c(node.object, st, "Expression");
130
+ c(node.body, st, "Statement");
131
+ };
132
+ base.SwitchStatement = function (node, st, c) {
133
+ c(node.discriminant, st, "Expression");
134
+ for (var i = 0, list = node.cases; i < list.length; i += 1) {
135
+ var cs = list[i];
136
+
137
+ c(cs, st);
138
+ }
139
+ };
140
+ base.SwitchCase = function (node, st, c) {
141
+ if (node.test) { c(node.test, st, "Expression"); }
142
+ for (var i = 0, list = node.consequent; i < list.length; i += 1)
143
+ {
144
+ var cons = list[i];
145
+
146
+ c(cons, st, "Statement");
147
+ }
148
+ };
149
+ base.ReturnStatement = base.YieldExpression = base.AwaitExpression = function (node, st, c) {
150
+ if (node.argument) { c(node.argument, st, "Expression"); }
151
+ };
152
+ base.ThrowStatement = base.SpreadElement =
153
+ function (node, st, c) { return c(node.argument, st, "Expression"); };
154
+ base.TryStatement = function (node, st, c) {
155
+ c(node.block, st, "Statement");
156
+ if (node.handler) { c(node.handler, st); }
157
+ if (node.finalizer) { c(node.finalizer, st, "Statement"); }
158
+ };
159
+ base.CatchClause = function (node, st, c) {
160
+ if (node.param) { c(node.param, st, "Pattern"); }
161
+ c(node.body, st, "Statement");
162
+ };
163
+ base.WhileStatement = base.DoWhileStatement = function (node, st, c) {
164
+ c(node.test, st, "Expression");
165
+ c(node.body, st, "Statement");
166
+ };
167
+ base.ForStatement = function (node, st, c) {
168
+ if (node.init) { c(node.init, st, "ForInit"); }
169
+ if (node.test) { c(node.test, st, "Expression"); }
170
+ if (node.update) { c(node.update, st, "Expression"); }
171
+ c(node.body, st, "Statement");
172
+ };
173
+ base.ForInStatement = base.ForOfStatement = function (node, st, c) {
174
+ c(node.left, st, "ForInit");
175
+ c(node.right, st, "Expression");
176
+ c(node.body, st, "Statement");
177
+ };
178
+ base.ForInit = function (node, st, c) {
179
+ if (node.type === "VariableDeclaration") { c(node, st); }
180
+ else { c(node, st, "Expression"); }
181
+ };
182
+ base.DebuggerStatement = ignore;
183
+
184
+ base.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
185
+ base.VariableDeclaration = function (node, st, c) {
186
+ for (var i = 0, list = node.declarations; i < list.length; i += 1)
187
+ {
188
+ var decl = list[i];
189
+
190
+ c(decl, st);
191
+ }
192
+ };
193
+ base.VariableDeclarator = function (node, st, c) {
194
+ c(node.id, st, "Pattern");
195
+ if (node.init) { c(node.init, st, "Expression"); }
196
+ };
197
+
198
+ base.Function = function (node, st, c) {
199
+ if (node.id) { c(node.id, st, "Pattern"); }
200
+ for (var i = 0, list = node.params; i < list.length; i += 1)
201
+ {
202
+ var param = list[i];
203
+
204
+ c(param, st, "Pattern");
205
+ }
206
+ c(node.body, st, node.expression ? "Expression" : "Statement");
207
+ };
208
+
209
+ base.Pattern = function (node, st, c) {
210
+ if (node.type === "Identifier")
211
+ { c(node, st, "VariablePattern"); }
212
+ else if (node.type === "MemberExpression")
213
+ { c(node, st, "MemberPattern"); }
214
+ else
215
+ { c(node, st); }
216
+ };
217
+ base.VariablePattern = ignore;
218
+ base.MemberPattern = skipThrough;
219
+ base.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
220
+ base.ArrayPattern = function (node, st, c) {
221
+ for (var i = 0, list = node.elements; i < list.length; i += 1) {
222
+ var elt = list[i];
223
+
224
+ if (elt) { c(elt, st, "Pattern"); }
225
+ }
226
+ };
227
+ base.ObjectPattern = function (node, st, c) {
228
+ for (var i = 0, list = node.properties; i < list.length; i += 1) {
229
+ var prop = list[i];
230
+
231
+ if (prop.type === "Property") {
232
+ if (prop.computed) { c(prop.key, st, "Expression"); }
233
+ c(prop.value, st, "Pattern");
234
+ } else if (prop.type === "RestElement") {
235
+ c(prop.argument, st, "Pattern");
236
+ }
237
+ }
238
+ };
239
+
240
+ base.Expression = skipThrough;
241
+ base.ThisExpression = base.Super = base.MetaProperty = ignore;
242
+ base.ArrayExpression = function (node, st, c) {
243
+ for (var i = 0, list = node.elements; i < list.length; i += 1) {
244
+ var elt = list[i];
245
+
246
+ if (elt) { c(elt, st, "Expression"); }
247
+ }
248
+ };
249
+ base.ObjectExpression = function (node, st, c) {
250
+ for (var i = 0, list = node.properties; i < list.length; i += 1)
251
+ {
252
+ var prop = list[i];
253
+
254
+ c(prop, st);
255
+ }
256
+ };
257
+ base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration;
258
+ base.SequenceExpression = function (node, st, c) {
259
+ for (var i = 0, list = node.expressions; i < list.length; i += 1)
260
+ {
261
+ var expr = list[i];
262
+
263
+ c(expr, st, "Expression");
264
+ }
265
+ };
266
+ base.TemplateLiteral = function (node, st, c) {
267
+ for (var i = 0, list = node.quasis; i < list.length; i += 1)
268
+ {
269
+ var quasi = list[i];
270
+
271
+ c(quasi, st);
272
+ }
273
+
274
+ for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
275
+ {
276
+ var expr = list$1[i$1];
277
+
278
+ c(expr, st, "Expression");
279
+ }
280
+ };
281
+ base.TemplateElement = ignore;
282
+ base.UnaryExpression = base.UpdateExpression = function (node, st, c) {
283
+ c(node.argument, st, "Expression");
284
+ };
285
+ base.BinaryExpression = base.LogicalExpression = function (node, st, c) {
286
+ c(node.left, st, "Expression");
287
+ c(node.right, st, "Expression");
288
+ };
289
+ base.AssignmentExpression = base.AssignmentPattern = function (node, st, c) {
290
+ c(node.left, st, "Pattern");
291
+ c(node.right, st, "Expression");
292
+ };
293
+ base.ConditionalExpression = function (node, st, c) {
294
+ c(node.test, st, "Expression");
295
+ c(node.consequent, st, "Expression");
296
+ c(node.alternate, st, "Expression");
297
+ };
298
+ base.NewExpression = base.CallExpression = function (node, st, c) {
299
+ c(node.callee, st, "Expression");
300
+ if (node.arguments)
301
+ { for (var i = 0, list = node.arguments; i < list.length; i += 1)
302
+ {
303
+ var arg = list[i];
304
+
305
+ c(arg, st, "Expression");
306
+ } }
307
+ };
308
+ base.MemberExpression = function (node, st, c) {
309
+ c(node.object, st, "Expression");
310
+ if (node.computed) { c(node.property, st, "Expression"); }
311
+ };
312
+ base.ExportNamedDeclaration = base.ExportDefaultDeclaration = function (node, st, c) {
313
+ if (node.declaration)
314
+ { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
315
+ if (node.source) { c(node.source, st, "Expression"); }
316
+ };
317
+ base.ExportAllDeclaration = function (node, st, c) {
318
+ if (node.exported)
319
+ { c(node.exported, st); }
320
+ c(node.source, st, "Expression");
321
+ };
322
+ base.ImportDeclaration = function (node, st, c) {
323
+ for (var i = 0, list = node.specifiers; i < list.length; i += 1)
324
+ {
325
+ var spec = list[i];
326
+
327
+ c(spec, st);
328
+ }
329
+ c(node.source, st, "Expression");
330
+ };
331
+ base.ImportExpression = function (node, st, c) {
332
+ c(node.source, st, "Expression");
333
+ };
334
+ base.ImportSpecifier = base.ImportDefaultSpecifier = base.ImportNamespaceSpecifier = base.Identifier = base.PrivateIdentifier = base.Literal = ignore;
335
+
336
+ base.TaggedTemplateExpression = function (node, st, c) {
337
+ c(node.tag, st, "Expression");
338
+ c(node.quasi, st, "Expression");
339
+ };
340
+ base.ClassDeclaration = base.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
341
+ base.Class = function (node, st, c) {
342
+ if (node.id) { c(node.id, st, "Pattern"); }
343
+ if (node.superClass) { c(node.superClass, st, "Expression"); }
344
+ c(node.body, st);
345
+ };
346
+ base.ClassBody = function (node, st, c) {
347
+ for (var i = 0, list = node.body; i < list.length; i += 1)
348
+ {
349
+ var elt = list[i];
350
+
351
+ c(elt, st);
352
+ }
353
+ };
354
+ base.MethodDefinition = base.PropertyDefinition = base.Property = function (node, st, c) {
355
+ if (node.computed) { c(node.key, st, "Expression"); }
356
+ if (node.value) { c(node.value, st, "Expression"); }
357
+ };
358
+
359
+ async function collectTests(ctx, filepath) {
360
+ const request = await ctx.vitenode.transformRequest(filepath, filepath);
361
+ if (!request) {
362
+ return null;
363
+ }
364
+ const ast = await parseAstAsync(request.code);
365
+ const testFilepath = relative(ctx.config.root, filepath);
366
+ const projectName = ctx.name;
367
+ const typecheckSubprojectName = projectName ? `${projectName}:__typecheck__` : "__typecheck__";
368
+ const file = {
369
+ filepath,
370
+ type: "suite",
371
+ id: generateHash(`${testFilepath}${typecheckSubprojectName}`),
372
+ name: testFilepath,
373
+ mode: "run",
374
+ tasks: [],
375
+ start: ast.start,
376
+ end: ast.end,
377
+ projectName,
378
+ meta: { typecheck: true },
379
+ file: null
380
+ };
381
+ file.file = file;
382
+ const definitions = [];
383
+ const getName = (callee) => {
384
+ if (!callee) {
385
+ return null;
386
+ }
387
+ if (callee.type === "Identifier") {
388
+ return callee.name;
389
+ }
390
+ if (callee.type === "CallExpression") {
391
+ return getName(callee.callee);
392
+ }
393
+ if (callee.type === "TaggedTemplateExpression") {
394
+ return getName(callee.tag);
395
+ }
396
+ if (callee.type === "MemberExpression") {
397
+ if (callee.object?.type === "Identifier" && [
398
+ "it",
399
+ "test",
400
+ "describe",
401
+ "suite"
402
+ ].includes(callee.object.name)) {
403
+ return callee.object?.name;
404
+ }
405
+ if (callee.object?.name?.startsWith("__vite_ssr_")) {
406
+ return getName(callee.property);
407
+ }
408
+ return getName(callee.object?.property);
409
+ }
410
+ if (callee.type === "SequenceExpression" && callee.expressions.length === 2) {
411
+ const [e0, e1] = callee.expressions;
412
+ if (e0.type === "Literal" && e0.value === 0) {
413
+ return getName(e1);
414
+ }
415
+ }
416
+ return null;
417
+ };
418
+ ancestor(ast, { CallExpression(node) {
419
+ const { callee } = node;
420
+ const name = getName(callee);
421
+ if (!name) {
422
+ return;
423
+ }
424
+ if (![
425
+ "it",
426
+ "test",
427
+ "describe",
428
+ "suite"
429
+ ].includes(name)) {
430
+ return;
431
+ }
432
+ const property = callee?.property?.name;
433
+ let mode = !property || property === name ? "run" : property;
434
+ if ([
435
+ "each",
436
+ "for",
437
+ "skipIf",
438
+ "runIf"
439
+ ].includes(mode)) {
440
+ return;
441
+ }
442
+ let start;
443
+ const end = node.end;
444
+ if (callee.type === "CallExpression") {
445
+ start = callee.end;
446
+ } else if (callee.type === "TaggedTemplateExpression") {
447
+ start = callee.end + 1;
448
+ } else {
449
+ start = node.start;
450
+ }
451
+ const { arguments: [messageNode] } = node;
452
+ const isQuoted = messageNode?.type === "Literal" || messageNode?.type === "TemplateLiteral";
453
+ const message = isQuoted ? request.code.slice(messageNode.start + 1, messageNode.end - 1) : request.code.slice(messageNode.start, messageNode.end);
454
+ if (mode === "skipIf" || mode === "runIf") {
455
+ mode = "skip";
456
+ }
457
+ definitions.push({
458
+ start,
459
+ end,
460
+ name: message,
461
+ type: name === "it" || name === "test" ? "test" : "suite",
462
+ mode,
463
+ task: null
464
+ });
465
+ } });
466
+ let lastSuite = file;
467
+ const updateLatestSuite = (index) => {
468
+ while (lastSuite.suite && lastSuite.end < index) {
469
+ lastSuite = lastSuite.suite;
470
+ }
471
+ return lastSuite;
472
+ };
473
+ definitions.sort((a, b) => a.start - b.start).forEach((definition) => {
474
+ const latestSuite = updateLatestSuite(definition.start);
475
+ let mode = definition.mode;
476
+ if (latestSuite.mode !== "run") {
477
+ mode = latestSuite.mode;
478
+ }
479
+ if (definition.type === "suite") {
480
+ const task = {
481
+ type: definition.type,
482
+ id: "",
483
+ suite: latestSuite,
484
+ file,
485
+ tasks: [],
486
+ mode,
487
+ name: definition.name,
488
+ end: definition.end,
489
+ start: definition.start,
490
+ meta: { typecheck: true }
491
+ };
492
+ definition.task = task;
493
+ latestSuite.tasks.push(task);
494
+ lastSuite = task;
495
+ return;
496
+ }
497
+ const task = {
498
+ type: definition.type,
499
+ id: "",
500
+ suite: latestSuite,
501
+ file,
502
+ mode,
503
+ timeout: 0,
504
+ context: {},
505
+ name: definition.name,
506
+ end: definition.end,
507
+ start: definition.start,
508
+ meta: { typecheck: true }
509
+ };
510
+ definition.task = task;
511
+ latestSuite.tasks.push(task);
512
+ });
513
+ calculateSuiteHash(file);
514
+ const hasOnly = someTasksAreOnly(file);
515
+ interpretTaskModes(file, ctx.config.testNamePattern, undefined, hasOnly, false, ctx.config.allowOnly);
516
+ return {
517
+ file,
518
+ parsed: request.code,
519
+ filepath,
520
+ map: request.map,
521
+ definitions
522
+ };
523
+ }
524
+
525
+ const newLineRegExp = /\r?\n/;
526
+ const errCodeRegExp = /error TS(?<errCode>\d+)/;
527
+ async function makeTscErrorInfo(errInfo) {
528
+ const [errFilePathPos = "", ...errMsgRawArr] = errInfo.split(":");
529
+ if (!errFilePathPos || errMsgRawArr.length === 0 || errMsgRawArr.join("").length === 0) {
530
+ return ["unknown filepath", null];
531
+ }
532
+ const errMsgRaw = errMsgRawArr.join("").trim();
533
+ const [errFilePath, errPos] = errFilePathPos.slice(0, -1).split("(");
534
+ if (!errFilePath || !errPos) {
535
+ return ["unknown filepath", null];
536
+ }
537
+ const [errLine, errCol] = errPos.split(",");
538
+ if (!errLine || !errCol) {
539
+ return [errFilePath, null];
540
+ }
541
+ const execArr = errCodeRegExp.exec(errMsgRaw);
542
+ if (!execArr) {
543
+ return [errFilePath, null];
544
+ }
545
+ const errCodeStr = execArr.groups?.errCode ?? "";
546
+ if (!errCodeStr) {
547
+ return [errFilePath, null];
548
+ }
549
+ const line = Number(errLine);
550
+ const col = Number(errCol);
551
+ const errCode = Number(errCodeStr);
552
+ return [errFilePath, {
553
+ filePath: errFilePath,
554
+ errCode,
555
+ line,
556
+ column: col,
557
+ errMsg: errMsgRaw.slice(`error TS${errCode} `.length)
558
+ }];
559
+ }
560
+ async function getRawErrsMapFromTsCompile(tscErrorStdout) {
561
+ const rawErrsMap = new Map();
562
+ const infos = await Promise.all(tscErrorStdout.split(newLineRegExp).reduce((prev, next) => {
563
+ if (!next) {
564
+ return prev;
565
+ } else if (!next.startsWith(" ")) {
566
+ prev.push(next);
567
+ } else {
568
+ prev[prev.length - 1] += `\n${next}`;
569
+ }
570
+ return prev;
571
+ }, []).map((errInfoLine) => makeTscErrorInfo(errInfoLine)));
572
+ infos.forEach(([errFilePath, errInfo]) => {
573
+ if (!errInfo) {
574
+ return;
575
+ }
576
+ if (!rawErrsMap.has(errFilePath)) {
577
+ rawErrsMap.set(errFilePath, [errInfo]);
578
+ } else {
579
+ rawErrsMap.get(errFilePath)?.push(errInfo);
580
+ }
581
+ });
582
+ return rawErrsMap;
583
+ }
584
+
585
+ function createIndexMap(source) {
586
+ const map = new Map();
587
+ let index = 0;
588
+ let line = 1;
589
+ let column = 1;
590
+ for (const char of source) {
591
+ map.set(`${line}:${column}`, index++);
592
+ if (char === "\n" || char === "\r\n") {
593
+ line++;
594
+ column = 0;
595
+ } else {
596
+ column++;
597
+ }
598
+ }
599
+ return map;
600
+ }
601
+
602
+ class TypeCheckError extends Error {
603
+ name = "TypeCheckError";
604
+ constructor(message, stacks) {
605
+ super(message);
606
+ this.message = message;
607
+ this.stacks = stacks;
608
+ }
609
+ }
610
+ class Typechecker {
611
+ _onParseStart;
612
+ _onParseEnd;
613
+ _onWatcherRerun;
614
+ _result = {
615
+ files: [],
616
+ sourceErrors: [],
617
+ time: 0
618
+ };
619
+ _startTime = 0;
620
+ _output = "";
621
+ _tests = {};
622
+ process;
623
+ files = [];
624
+ constructor(project) {
625
+ this.project = project;
626
+ }
627
+ setFiles(files) {
628
+ this.files = files;
629
+ }
630
+ onParseStart(fn) {
631
+ this._onParseStart = fn;
632
+ }
633
+ onParseEnd(fn) {
634
+ this._onParseEnd = fn;
635
+ }
636
+ onWatcherRerun(fn) {
637
+ this._onWatcherRerun = fn;
638
+ }
639
+ async collectFileTests(filepath) {
640
+ return collectTests(this.project, filepath);
641
+ }
642
+ getFiles() {
643
+ return this.files;
644
+ }
645
+ async collectTests() {
646
+ const tests = (await Promise.all(this.getFiles().map((filepath) => this.collectFileTests(filepath)))).reduce((acc, data) => {
647
+ if (!data) {
648
+ return acc;
649
+ }
650
+ acc[data.filepath] = data;
651
+ return acc;
652
+ }, {});
653
+ this._tests = tests;
654
+ return tests;
655
+ }
656
+ markPassed(file) {
657
+ if (!file.result?.state) {
658
+ file.result = { state: "pass" };
659
+ }
660
+ const markTasks = (tasks) => {
661
+ for (const task of tasks) {
662
+ if ("tasks" in task) {
663
+ markTasks(task.tasks);
664
+ }
665
+ if (!task.result?.state && (task.mode === "run" || task.mode === "queued")) {
666
+ task.result = { state: "pass" };
667
+ }
668
+ }
669
+ };
670
+ markTasks(file.tasks);
671
+ }
672
+ async prepareResults(output) {
673
+ const typeErrors = await this.parseTscLikeOutput(output);
674
+ const testFiles = new Set(this.getFiles());
675
+ if (!this._tests) {
676
+ this._tests = await this.collectTests();
677
+ }
678
+ const sourceErrors = [];
679
+ const files = [];
680
+ testFiles.forEach((path) => {
681
+ const { file, definitions, map, parsed } = this._tests[path];
682
+ const errors = typeErrors.get(path);
683
+ files.push(file);
684
+ if (!errors) {
685
+ this.markPassed(file);
686
+ return;
687
+ }
688
+ const sortedDefinitions = [...definitions.sort((a, b) => b.start - a.start)];
689
+ const traceMap = map && new TraceMap(map);
690
+ const indexMap = createIndexMap(parsed);
691
+ const markState = (task, state) => {
692
+ task.result = { state: task.mode === "run" || task.mode === "only" ? state : task.mode };
693
+ if (task.suite) {
694
+ markState(task.suite, state);
695
+ } else if (task.file && task !== task.file) {
696
+ markState(task.file, state);
697
+ }
698
+ };
699
+ errors.forEach(({ error, originalError }) => {
700
+ const processedPos = traceMap ? findGeneratedPosition(traceMap, {
701
+ line: originalError.line,
702
+ column: originalError.column,
703
+ source: basename(path)
704
+ }) : originalError;
705
+ const line = processedPos.line ?? originalError.line;
706
+ const column = processedPos.column ?? originalError.column;
707
+ const index = indexMap.get(`${line}:${column}`);
708
+ const definition = index != null && sortedDefinitions.find((def) => def.start <= index && def.end >= index);
709
+ const suite = definition ? definition.task : file;
710
+ const state = suite.mode === "run" || suite.mode === "only" ? "fail" : suite.mode;
711
+ const errors = suite.result?.errors || [];
712
+ suite.result = {
713
+ state,
714
+ errors
715
+ };
716
+ errors.push(error);
717
+ if (state === "fail") {
718
+ if (suite.suite) {
719
+ markState(suite.suite, "fail");
720
+ } else if (suite.file && suite !== suite.file) {
721
+ markState(suite.file, "fail");
722
+ }
723
+ }
724
+ });
725
+ this.markPassed(file);
726
+ });
727
+ typeErrors.forEach((errors, path) => {
728
+ if (!testFiles.has(path)) {
729
+ sourceErrors.push(...errors.map(({ error }) => error));
730
+ }
731
+ });
732
+ return {
733
+ files,
734
+ sourceErrors,
735
+ time: performance.now() - this._startTime
736
+ };
737
+ }
738
+ async parseTscLikeOutput(output) {
739
+ const errorsMap = await getRawErrsMapFromTsCompile(output);
740
+ const typesErrors = new Map();
741
+ errorsMap.forEach((errors, path) => {
742
+ const filepath = resolve(this.project.config.root, path);
743
+ const suiteErrors = errors.map((info) => {
744
+ const limit = Error.stackTraceLimit;
745
+ Error.stackTraceLimit = 0;
746
+ const errMsg = info.errMsg.replace(/\r?\n\s*(Type .* has no call signatures)/g, " $1");
747
+ const error = new TypeCheckError(errMsg, [{
748
+ file: filepath,
749
+ line: info.line,
750
+ column: info.column,
751
+ method: ""
752
+ }]);
753
+ Error.stackTraceLimit = limit;
754
+ return {
755
+ originalError: info,
756
+ error: {
757
+ name: error.name,
758
+ nameStr: String(error.name),
759
+ message: errMsg,
760
+ stacks: error.stacks,
761
+ stack: "",
762
+ stackStr: ""
763
+ }
764
+ };
765
+ });
766
+ typesErrors.set(filepath, suiteErrors);
767
+ });
768
+ return typesErrors;
769
+ }
770
+ async stop() {
771
+ this.process?.kill();
772
+ this.process = undefined;
773
+ }
774
+ async ensurePackageInstalled(ctx, checker) {
775
+ if (checker !== "tsc" && checker !== "vue-tsc") {
776
+ return;
777
+ }
778
+ const packageName = checker === "tsc" ? "typescript" : "vue-tsc";
779
+ await ctx.packageInstaller.ensureInstalled(packageName, ctx.config.root);
780
+ }
781
+ getExitCode() {
782
+ return this.process?.exitCode != null && this.process.exitCode;
783
+ }
784
+ getOutput() {
785
+ return this._output;
786
+ }
787
+ async start() {
788
+ if (this.process) {
789
+ return;
790
+ }
791
+ const { root, watch, typecheck } = this.project.config;
792
+ const args = [
793
+ "--noEmit",
794
+ "--pretty",
795
+ "false",
796
+ "--incremental",
797
+ "--tsBuildInfoFile",
798
+ join(process.versions.pnp ? join(nodeos__default.tmpdir(), this.project.hash) : distDir, "tsconfig.tmp.tsbuildinfo")
799
+ ];
800
+ if (watch) {
801
+ args.push("--watch");
802
+ }
803
+ if (typecheck.allowJs) {
804
+ args.push("--allowJs", "--checkJs");
805
+ }
806
+ if (typecheck.tsconfig) {
807
+ args.push("-p", resolve(root, typecheck.tsconfig));
808
+ }
809
+ this._output = "";
810
+ this._startTime = performance.now();
811
+ const child = x(typecheck.checker, args, {
812
+ nodeOptions: {
813
+ cwd: root,
814
+ stdio: "pipe"
815
+ },
816
+ throwOnError: false
817
+ });
818
+ this.process = child.process;
819
+ await this._onParseStart?.();
820
+ let rerunTriggered = false;
821
+ child.process?.stdout?.on("data", (chunk) => {
822
+ this._output += chunk;
823
+ if (!watch) {
824
+ return;
825
+ }
826
+ if (this._output.includes("File change detected") && !rerunTriggered) {
827
+ this._onWatcherRerun?.();
828
+ this._startTime = performance.now();
829
+ this._result.sourceErrors = [];
830
+ this._result.files = [];
831
+ this._tests = null;
832
+ rerunTriggered = true;
833
+ }
834
+ if (/Found \w+ errors*. Watching for/.test(this._output)) {
835
+ rerunTriggered = false;
836
+ this.prepareResults(this._output).then((result) => {
837
+ this._result = result;
838
+ this._onParseEnd?.(result);
839
+ });
840
+ this._output = "";
841
+ }
842
+ });
843
+ if (!watch) {
844
+ await child;
845
+ this._result = await this.prepareResults(this._output);
846
+ await this._onParseEnd?.(this._result);
847
+ }
848
+ }
849
+ getResult() {
850
+ return this._result;
851
+ }
852
+ getTestFiles() {
853
+ return Object.values(this._tests || {}).map((i) => i.file);
854
+ }
855
+ getTestPacksAndEvents() {
856
+ const packs = [];
857
+ const events = [];
858
+ for (const { file } of Object.values(this._tests || {})) {
859
+ const result = convertTasksToEvents(file);
860
+ packs.push(...result.packs);
861
+ events.push(...result.events);
862
+ }
863
+ return {
864
+ packs,
865
+ events
866
+ };
867
+ }
868
+ }
869
+ function findGeneratedPosition(traceMap, { line, column, source }) {
870
+ const found = generatedPositionFor(traceMap, {
871
+ line,
872
+ column,
873
+ source
874
+ });
875
+ if (found.line !== null) {
876
+ return found;
877
+ }
878
+ const mappings = [];
879
+ eachMapping(traceMap, (m) => {
880
+ if (m.source === source && m.originalLine !== null && m.originalColumn !== null && (line === m.originalLine ? column < m.originalColumn : line < m.originalLine)) {
881
+ mappings.push(m);
882
+ }
883
+ });
884
+ const next = mappings.sort((a, b) => a.originalLine === b.originalLine ? a.originalColumn - b.originalColumn : a.originalLine - b.originalLine).at(0);
885
+ if (next) {
886
+ return {
887
+ line: next.generatedLine,
888
+ column: next.generatedColumn
889
+ };
890
+ }
891
+ return {
892
+ line: null,
893
+ column: null
894
+ };
895
+ }
896
+
897
+ export { TypeCheckError as T, Typechecker as a, convertTasksToEvents as c, getOutputFile as g, hasFailedSnapshot as h, wrapSerializableConfig as w };