@storybook/addon-vitest 10.1.0-alpha.1 → 10.1.0-alpha.11

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.
@@ -1,38 +1,36 @@
1
- import CJS_COMPAT_NODE_URL_8w58nre1r1b from 'node:url';
2
- import CJS_COMPAT_NODE_PATH_8w58nre1r1b from 'node:path';
3
- import CJS_COMPAT_NODE_MODULE_8w58nre1r1b from "node:module";
1
+ import CJS_COMPAT_NODE_URL_zfiyucf8tb from 'node:url';
2
+ import CJS_COMPAT_NODE_PATH_zfiyucf8tb from 'node:path';
3
+ import CJS_COMPAT_NODE_MODULE_zfiyucf8tb from "node:module";
4
4
 
5
- var __filename = CJS_COMPAT_NODE_URL_8w58nre1r1b.fileURLToPath(import.meta.url);
6
- var __dirname = CJS_COMPAT_NODE_PATH_8w58nre1r1b.dirname(__filename);
7
- var require = CJS_COMPAT_NODE_MODULE_8w58nre1r1b.createRequire(import.meta.url);
5
+ var __filename = CJS_COMPAT_NODE_URL_zfiyucf8tb.fileURLToPath(import.meta.url);
6
+ var __dirname = CJS_COMPAT_NODE_PATH_zfiyucf8tb.dirname(__filename);
7
+ var require = CJS_COMPAT_NODE_MODULE_zfiyucf8tb.createRequire(import.meta.url);
8
8
 
9
9
  // ------------------------------------------------------------
10
10
  // end of CJS compatibility banner, injected by Storybook's esbuild configuration
11
11
  // ------------------------------------------------------------
12
12
  import {
13
13
  log
14
- } from "../_node-chunks/chunk-4EEN4T72.js";
14
+ } from "../_node-chunks/chunk-2WX72TIY.js";
15
15
  import {
16
16
  any,
17
17
  errorToErrorLike
18
- } from "../_node-chunks/chunk-5KVXKVT6.js";
18
+ } from "../_node-chunks/chunk-FD2MOKYY.js";
19
19
  import {
20
20
  ADDON_ID,
21
21
  COVERAGE_DIRECTORY,
22
22
  STATUS_TYPE_ID_A11Y,
23
23
  STATUS_TYPE_ID_COMPONENT_TEST,
24
24
  storeOptions
25
- } from "../_node-chunks/chunk-5D5GEQQR.js";
26
- import "../_node-chunks/chunk-RWZYDWYZ.js";
25
+ } from "../_node-chunks/chunk-TCQNKRGF.js";
26
+ import "../_node-chunks/chunk-XN666246.js";
27
27
  import {
28
28
  dirname,
29
29
  join,
30
30
  normalize,
31
31
  path
32
- } from "../_node-chunks/chunk-JLLEOCT6.js";
33
- import {
34
- __name
35
- } from "../_node-chunks/chunk-XYGEMTYA.js";
32
+ } from "../_node-chunks/chunk-L7WYCUSW.js";
33
+ import "../_node-chunks/chunk-FCFZB5YS.js";
36
34
 
37
35
  // src/node/vitest.ts
38
36
  import process2 from "node:process";
@@ -45,85 +43,41 @@ import {
45
43
 
46
44
  // ../../node_modules/es-toolkit/dist/function/debounce.mjs
47
45
  function debounce(func, debounceMs, { signal, edges } = {}) {
48
- let pendingThis = void 0;
49
- let pendingArgs = null;
50
- const leading = edges != null && edges.includes("leading");
51
- const trailing = edges == null || edges.includes("trailing");
52
- const invoke = /* @__PURE__ */ __name(() => {
53
- if (pendingArgs !== null) {
54
- func.apply(pendingThis, pendingArgs);
55
- pendingThis = void 0;
56
- pendingArgs = null;
57
- }
58
- }, "invoke");
59
- const onTimerEnd = /* @__PURE__ */ __name(() => {
60
- if (trailing) {
61
- invoke();
62
- }
63
- cancel();
64
- }, "onTimerEnd");
65
- let timeoutId = null;
66
- const schedule = /* @__PURE__ */ __name(() => {
67
- if (timeoutId != null) {
68
- clearTimeout(timeoutId);
69
- }
70
- timeoutId = setTimeout(() => {
71
- timeoutId = null;
72
- onTimerEnd();
46
+ let pendingThis, pendingArgs = null, leading = edges != null && edges.includes("leading"), trailing = edges == null || edges.includes("trailing"), invoke = () => {
47
+ pendingArgs !== null && (func.apply(pendingThis, pendingArgs), pendingThis = void 0, pendingArgs = null);
48
+ }, onTimerEnd = () => {
49
+ trailing && invoke(), cancel();
50
+ }, timeoutId = null, schedule = () => {
51
+ timeoutId != null && clearTimeout(timeoutId), timeoutId = setTimeout(() => {
52
+ timeoutId = null, onTimerEnd();
73
53
  }, debounceMs);
74
- }, "schedule");
75
- const cancelTimer = /* @__PURE__ */ __name(() => {
76
- if (timeoutId !== null) {
77
- clearTimeout(timeoutId);
78
- timeoutId = null;
79
- }
80
- }, "cancelTimer");
81
- const cancel = /* @__PURE__ */ __name(() => {
82
- cancelTimer();
83
- pendingThis = void 0;
84
- pendingArgs = null;
85
- }, "cancel");
86
- const flush = /* @__PURE__ */ __name(() => {
54
+ }, cancelTimer = () => {
55
+ timeoutId !== null && (clearTimeout(timeoutId), timeoutId = null);
56
+ }, cancel = () => {
57
+ cancelTimer(), pendingThis = void 0, pendingArgs = null;
58
+ }, flush = () => {
87
59
  invoke();
88
- }, "flush");
89
- const debounced = /* @__PURE__ */ __name(function(...args) {
90
- if (signal?.aborted) {
60
+ }, debounced = function(...args) {
61
+ if (signal?.aborted)
91
62
  return;
92
- }
93
- pendingThis = this;
94
- pendingArgs = args;
95
- const isFirstCall = timeoutId == null;
96
- schedule();
97
- if (leading && isFirstCall) {
98
- invoke();
99
- }
100
- }, "debounced");
101
- debounced.schedule = schedule;
102
- debounced.cancel = cancel;
103
- debounced.flush = flush;
104
- signal?.addEventListener("abort", cancel, { once: true });
105
- return debounced;
63
+ pendingThis = this, pendingArgs = args;
64
+ let isFirstCall = timeoutId == null;
65
+ schedule(), leading && isFirstCall && invoke();
66
+ };
67
+ return debounced.schedule = schedule, debounced.cancel = cancel, debounced.flush = flush, signal?.addEventListener("abort", cancel, { once: !0 }), debounced;
106
68
  }
107
- __name(debounce, "debounce");
108
69
 
109
70
  // ../../node_modules/es-toolkit/dist/function/partial.mjs
110
71
  function partial(func, ...partialArgs) {
111
72
  return partialImpl(func, placeholderSymbol, ...partialArgs);
112
73
  }
113
- __name(partial, "partial");
114
74
  function partialImpl(func, placeholder, ...partialArgs) {
115
- const partialed = /* @__PURE__ */ __name(function(...providedArgs) {
116
- let providedArgsIndex = 0;
117
- const substitutedArgs = partialArgs.slice().map((arg) => arg === placeholder ? providedArgs[providedArgsIndex++] : arg);
118
- const remainingArgs = providedArgs.slice(providedArgsIndex);
75
+ let partialed = function(...providedArgs) {
76
+ let providedArgsIndex = 0, substitutedArgs = partialArgs.slice().map((arg) => arg === placeholder ? providedArgs[providedArgsIndex++] : arg), remainingArgs = providedArgs.slice(providedArgsIndex);
119
77
  return func.apply(this, substitutedArgs.concat(remainingArgs));
120
- }, "partialed");
121
- if (func.prototype) {
122
- partialed.prototype = Object.create(func.prototype);
123
- }
124
- return partialed;
78
+ };
79
+ return func.prototype && (partialed.prototype = Object.create(func.prototype)), partialed;
125
80
  }
126
- __name(partialImpl, "partialImpl");
127
81
  var placeholderSymbol = Symbol("partial.placeholder");
128
82
  partial.placeholder = placeholderSymbol;
129
83
 
@@ -131,22 +85,13 @@ partial.placeholder = placeholderSymbol;
131
85
  function partialRight(func, ...partialArgs) {
132
86
  return partialRightImpl(func, placeholderSymbol2, ...partialArgs);
133
87
  }
134
- __name(partialRight, "partialRight");
135
88
  function partialRightImpl(func, placeholder, ...partialArgs) {
136
- const partialedRight = /* @__PURE__ */ __name(function(...providedArgs) {
137
- const placeholderLength = partialArgs.filter((arg) => arg === placeholder).length;
138
- const rangeLength = Math.max(providedArgs.length - placeholderLength, 0);
139
- const remainingArgs = providedArgs.slice(0, rangeLength);
140
- let providedArgsIndex = rangeLength;
141
- const substitutedArgs = partialArgs.slice().map((arg) => arg === placeholder ? providedArgs[providedArgsIndex++] : arg);
89
+ let partialedRight = function(...providedArgs) {
90
+ let placeholderLength = partialArgs.filter((arg) => arg === placeholder).length, rangeLength = Math.max(providedArgs.length - placeholderLength, 0), remainingArgs = providedArgs.slice(0, rangeLength), providedArgsIndex = rangeLength, substitutedArgs = partialArgs.slice().map((arg) => arg === placeholder ? providedArgs[providedArgsIndex++] : arg);
142
91
  return func.apply(this, remainingArgs.concat(substitutedArgs));
143
- }, "partialedRight");
144
- if (func.prototype) {
145
- partialedRight.prototype = Object.create(func.prototype);
146
- }
147
- return partialedRight;
92
+ };
93
+ return func.prototype && (partialedRight.prototype = Object.create(func.prototype)), partialedRight;
148
94
  }
149
- __name(partialRightImpl, "partialRightImpl");
150
95
  var placeholderSymbol2 = Symbol("partialRight.placeholder");
151
96
  partialRight.placeholder = placeholderSymbol2;
152
97
 
@@ -155,24 +100,11 @@ var DEFAULT_RETRIES = Number.POSITIVE_INFINITY;
155
100
 
156
101
  // ../../node_modules/es-toolkit/dist/function/throttle.mjs
157
102
  function throttle(func, throttleMs, { signal, edges = ["leading", "trailing"] } = {}) {
158
- let pendingAt = null;
159
- const debounced = debounce(func, throttleMs, { signal, edges });
160
- const throttled = /* @__PURE__ */ __name(function(...args) {
161
- if (pendingAt == null) {
162
- pendingAt = Date.now();
163
- } else {
164
- if (Date.now() - pendingAt >= throttleMs) {
165
- pendingAt = Date.now();
166
- debounced.cancel();
167
- }
168
- }
169
- debounced(...args);
170
- }, "throttled");
171
- throttled.cancel = debounced.cancel;
172
- throttled.flush = debounced.flush;
173
- return throttled;
103
+ let pendingAt = null, debounced = debounce(func, throttleMs, { signal, edges }), throttled = function(...args) {
104
+ pendingAt == null ? pendingAt = Date.now() : Date.now() - pendingAt >= throttleMs && (pendingAt = Date.now(), debounced.cancel()), debounced.apply(this, args);
105
+ };
106
+ return throttled.cancel = debounced.cancel, throttled.flush = debounced.flush, throttled;
174
107
  }
175
- __name(throttle, "throttle");
176
108
 
177
109
  // src/node/vitest-manager.ts
178
110
  import { existsSync } from "node:fs";
@@ -180,28 +112,19 @@ import { getProjectRoot, resolvePathInStorybookCache } from "storybook/internal/
180
112
 
181
113
  // ../../node_modules/slash/index.js
182
114
  function slash(path2) {
183
- const isExtendedLengthPath = path2.startsWith("\\\\?\\");
184
- if (isExtendedLengthPath) {
185
- return path2;
186
- }
187
- return path2.replace(/\\/g, "/");
115
+ return path2.startsWith("\\\\?\\") ? path2 : path2.replace(/\\/g, "/");
188
116
  }
189
- __name(slash, "slash");
190
117
 
191
118
  // src/node/reporter.ts
192
119
  var StorybookReporter = class {
193
120
  constructor(testManager) {
194
121
  this.testManager = testManager;
195
122
  }
196
- static {
197
- __name(this, "StorybookReporter");
198
- }
199
123
  onInit(ctx) {
200
124
  this.ctx = ctx;
201
125
  }
202
126
  onTestCaseResult(testCase) {
203
- const { storyId, reports } = testCase.meta();
204
- const testResult = testCase.result();
127
+ let { storyId, reports } = testCase.meta(), testResult = testCase.result();
205
128
  this.testManager.onTestCaseResult({
206
129
  storyId,
207
130
  testResult,
@@ -209,42 +132,30 @@ var StorybookReporter = class {
209
132
  });
210
133
  }
211
134
  async onTestRunEnd(testModules, unhandledErrors) {
212
- const totalTestCount = testModules.flatMap(
135
+ let totalTestCount = testModules.flatMap(
213
136
  (t) => Array.from(t.children.allTests("passed")).concat(Array.from(t.children.allTests("failed")))
214
- ).length;
215
- const testModulesErrors = testModules.flatMap((t) => t.errors());
216
- const serializedErrors = unhandledErrors.concat(testModulesErrors).map((e) => {
217
- return {
218
- ...e,
219
- name: e.name,
220
- message: e.message,
221
- stack: e.stack?.replace(e.message, ""),
222
- cause: e.cause
223
- };
224
- });
137
+ ).length, testModulesErrors = testModules.flatMap((t) => t.errors()), serializedErrors = unhandledErrors.concat(testModulesErrors).map((e) => ({
138
+ ...e,
139
+ name: e.name,
140
+ message: e.message,
141
+ stack: e.stack?.replace(e.message, ""),
142
+ cause: e.cause
143
+ }));
225
144
  this.testManager.onTestRunEnd({
226
145
  totalTestCount,
227
146
  unhandledErrors: serializedErrors
228
- });
229
- this.clearVitestState();
147
+ }), this.clearVitestState();
230
148
  }
231
149
  // TODO: Clearing the whole internal state of Vitest might be too aggressive
232
150
  async clearVitestState() {
233
- this.ctx.state.filesMap.clear();
234
- this.ctx.state.pathsSet.clear();
235
- this.ctx.state.idMap.clear();
236
- this.ctx.state.errorsSet.clear();
237
- this.ctx.state.processTimeoutCauses?.clear();
151
+ this.ctx.state.filesMap.clear(), this.ctx.state.pathsSet.clear(), this.ctx.state.idMap.clear(), this.ctx.state.errorsSet.clear(), this.ctx.state.processTimeoutCauses?.clear();
238
152
  }
239
153
  };
240
154
 
241
155
  // src/node/vitest-manager.ts
242
- var VITEST_CONFIG_FILE_EXTENSIONS = ["mts", "mjs", "cts", "cjs", "ts", "tsx", "js", "jsx"];
243
- var VITEST_WORKSPACE_FILE_EXTENSION = ["ts", "js", "json"];
156
+ var VITEST_CONFIG_FILE_EXTENSIONS = ["mts", "mjs", "cts", "cjs", "ts", "tsx", "js", "jsx"], VITEST_WORKSPACE_FILE_EXTENSION = ["ts", "js", "json"];
244
157
  process.env.VITEST_STORYBOOK = "true";
245
- var DOUBLE_SPACES = " ";
246
- var getTestName = /* @__PURE__ */ __name((name) => `${name}${DOUBLE_SPACES}`, "getTestName");
247
- var VitestManager = class {
158
+ var DOUBLE_SPACES = " ", getTestName = (name) => `${name}${DOUBLE_SPACES}`, VitestManager = class {
248
159
  constructor(testManager) {
249
160
  this.testManager = testManager;
250
161
  this.vitest = null;
@@ -252,39 +163,32 @@ var VitestManager = class {
252
163
  this.vitestRestartPromise = null;
253
164
  this.runningPromise = null;
254
165
  }
255
- static {
256
- __name(this, "VitestManager");
257
- }
258
166
  async startVitest({ coverage }) {
259
- const { createVitest } = await import("vitest/node");
260
- const storybookCoverageReporter = [
167
+ let { createVitest } = await import("vitest/node"), storybookCoverageReporter = [
261
168
  "@storybook/addon-vitest/internal/coverage-reporter",
262
169
  {
263
170
  testManager: this.testManager,
264
171
  coverageOptions: this.vitest?.config?.coverage
265
172
  }
266
- ];
267
- const coverageOptions = coverage ? {
268
- enabled: true,
269
- clean: true,
270
- cleanOnRerun: true,
271
- reportOnFailure: true,
173
+ ], coverageOptions = coverage ? {
174
+ enabled: !0,
175
+ clean: !0,
176
+ cleanOnRerun: !0,
177
+ reportOnFailure: !0,
272
178
  reporter: [["html", {}], storybookCoverageReporter],
273
179
  reportsDirectory: resolvePathInStorybookCache(COVERAGE_DIRECTORY)
274
- } : { enabled: false };
275
- const vitestWorkspaceConfig = any(
180
+ } : { enabled: !1 }, vitestWorkspaceConfig = any(
276
181
  [
277
182
  ...VITEST_WORKSPACE_FILE_EXTENSION.map((ext) => `vitest.workspace.${ext}`),
278
183
  ...VITEST_CONFIG_FILE_EXTENSIONS.map((ext) => `vitest.config.${ext}`)
279
184
  ],
280
185
  { last: getProjectRoot() }
281
- );
282
- const projectName = "storybook:" + process.env.STORYBOOK_CONFIG_DIR;
186
+ ), projectName = "storybook:" + process.env.STORYBOOK_CONFIG_DIR;
283
187
  try {
284
188
  this.vitest = await createVitest("test", {
285
189
  root: vitestWorkspaceConfig ? dirname(vitestWorkspaceConfig) : process.cwd(),
286
- watch: true,
287
- passWithNoTests: false,
190
+ watch: !0,
191
+ passWithNoTests: !1,
288
192
  project: [projectName],
289
193
  // TODO:
290
194
  // Do we want to enable Vite's default reporter?
@@ -295,176 +199,104 @@ var VitestManager = class {
295
199
  coverage: coverageOptions
296
200
  });
297
201
  } catch (err) {
298
- const originalMessage = String(err.message);
202
+ let originalMessage = String(err.message);
299
203
  if (originalMessage.includes("Found multiple projects")) {
300
- const custom = [
204
+ let custom = [
301
205
  "Storybook was unable to start the test run because you have multiple Vitest projects (or browsers) in headed mode.",
302
206
  "Please set `headless: true` in your Storybook vitest config.\n\n"
303
- ].join("\n");
304
- if (!originalMessage.startsWith(custom)) {
305
- err.message = `${custom}${originalMessage}`;
306
- }
207
+ ].join(`
208
+ `);
209
+ originalMessage.startsWith(custom) || (err.message = `${custom}${originalMessage}`);
307
210
  }
308
211
  throw err;
309
212
  }
310
- if (this.vitest) {
311
- this.vitest.onCancel(() => {
312
- });
313
- }
213
+ this.vitest && this.vitest.onCancel(() => {
214
+ });
314
215
  try {
315
216
  await this.vitest.init();
316
217
  } catch (e) {
317
- let message = "Failed to initialize Vitest";
318
- const isV8 = e.message?.includes("@vitest/coverage-v8");
319
- const isIstanbul = e.message?.includes("@vitest/coverage-istanbul");
320
- if (e.message?.includes("Failed to load url") && (isIstanbul || isV8) || // Vitest will sometimes not throw the correct missing-package-detection error, so we have to check for this as well
321
- e instanceof TypeError && e?.message === "Cannot read properties of undefined (reading 'name')") {
322
- const coveragePackage = isIstanbul ? "coverage-istanbul" : "coverage-v8";
323
- message += `
218
+ let message = "Failed to initialize Vitest", isV8 = e.message?.includes("@vitest/coverage-v8"), isIstanbul = e.message?.includes("@vitest/coverage-istanbul");
219
+ (e.message?.includes("Failed to load url") && (isIstanbul || isV8) || // Vitest will sometimes not throw the correct missing-package-detection error, so we have to check for this as well
220
+ e instanceof TypeError && e?.message === "Cannot read properties of undefined (reading 'name')") && (message += `
324
221
 
325
- Please install the @vitest/${coveragePackage} package to collect coverage
326
- `;
327
- }
328
- this.testManager.reportFatalError(message, e);
222
+ Please install the @vitest/${isIstanbul ? "coverage-istanbul" : "coverage-v8"} package to collect coverage
223
+ `), this.testManager.reportFatalError(message, e);
329
224
  return;
330
225
  }
331
226
  await this.setupWatchers();
332
227
  }
333
228
  async restartVitest({ coverage }) {
334
- await this.vitestRestartPromise;
335
- this.vitestRestartPromise = new Promise(async (resolve, reject) => {
229
+ return await this.vitestRestartPromise, this.vitestRestartPromise = new Promise(async (resolve, reject) => {
336
230
  try {
337
- await this.runningPromise;
338
- await this.vitest?.close();
339
- await this.startVitest({ coverage });
340
- resolve();
231
+ await this.runningPromise, await this.vitest?.close(), await this.startVitest({ coverage }), resolve();
341
232
  } catch (e) {
342
233
  reject(e);
343
234
  } finally {
344
235
  this.vitestRestartPromise = null;
345
236
  }
346
- });
347
- return this.vitestRestartPromise;
237
+ }), this.vitestRestartPromise;
348
238
  }
349
239
  resetGlobalTestNamePattern() {
350
240
  this.vitest?.setGlobalTestNamePattern("");
351
241
  }
352
242
  updateLastChanged(filepath) {
353
243
  this.vitest.projects.forEach(({ browser, vite, server }) => {
354
- if (server) {
355
- const serverMods = server.moduleGraph.getModulesByFile(filepath);
356
- serverMods?.forEach((mod) => server.moduleGraph.invalidateModule(mod));
357
- }
358
- if (vite) {
359
- const serverMods = vite.moduleGraph.getModulesByFile(filepath);
360
- serverMods?.forEach((mod) => vite.moduleGraph.invalidateModule(mod));
361
- }
362
- if (browser) {
363
- const browserMods = browser.vite.moduleGraph.getModulesByFile(filepath);
364
- browserMods?.forEach((mod) => browser.vite.moduleGraph.invalidateModule(mod));
365
- }
244
+ server && server.moduleGraph.getModulesByFile(filepath)?.forEach((mod) => server.moduleGraph.invalidateModule(mod)), vite && vite.moduleGraph.getModulesByFile(filepath)?.forEach((mod) => vite.moduleGraph.invalidateModule(mod)), browser && browser.vite.moduleGraph.getModulesByFile(filepath)?.forEach((mod) => browser.vite.moduleGraph.invalidateModule(mod));
366
245
  });
367
246
  }
368
247
  async fetchStories(requestStoryIds) {
369
- const indexUrl = this.testManager.store.getState().indexUrl;
370
- if (!indexUrl) {
248
+ let indexUrl = this.testManager.store.getState().indexUrl;
249
+ if (!indexUrl)
371
250
  throw new Error(
372
251
  "Tried to fetch stories to test, but the index URL was not set in the store yet."
373
252
  );
374
- }
375
253
  try {
376
- const index = await Promise.race([
254
+ let index = await Promise.race([
377
255
  fetch(indexUrl).then((res) => res.json()),
378
256
  new Promise((_, reject) => setTimeout(reject, 3e3, new Error("Request took too long")))
379
257
  ]);
380
- const storyIds = requestStoryIds || Object.keys(index.entries);
381
- return storyIds.map((id) => index.entries[id]).filter((story) => story.type === "story");
258
+ return (requestStoryIds || Object.keys(index.entries)).map((id) => index.entries[id]).filter((story) => story.type === "story");
382
259
  } catch (e) {
383
- log("Failed to fetch story index: " + e.message);
384
- return [];
260
+ return log("Failed to fetch story index: " + e.message), [];
385
261
  }
386
262
  }
387
263
  filterTestSpecifications(testSpecifications, stories) {
388
- const filteredTestSpecifications = [];
389
- const filteredStoryIds = [];
390
- const storiesByImportPath = {};
391
- for (const story of stories) {
392
- const absoluteImportPath = path.join(process.cwd(), story.importPath);
393
- if (!storiesByImportPath[absoluteImportPath]) {
394
- storiesByImportPath[absoluteImportPath] = [];
395
- }
396
- storiesByImportPath[absoluteImportPath].push(story);
264
+ let filteredTestSpecifications = [], filteredStoryIds = [], storiesByImportPath = {};
265
+ for (let story of stories) {
266
+ let absoluteImportPath = path.join(process.cwd(), story.importPath);
267
+ storiesByImportPath[absoluteImportPath] || (storiesByImportPath[absoluteImportPath] = []), storiesByImportPath[absoluteImportPath].push(story);
397
268
  }
398
- for (const testSpecification of testSpecifications) {
399
- const { env = {} } = testSpecification.project.config;
400
- const include = env.__VITEST_INCLUDE_TAGS__?.split(",").filter(Boolean) ?? ["test"];
401
- const exclude = env.__VITEST_EXCLUDE_TAGS__?.split(",").filter(Boolean) ?? [];
402
- const skip = env.__VITEST_SKIP_TAGS__?.split(",").filter(Boolean) ?? [];
403
- const storiesInTestSpecification = storiesByImportPath[testSpecification.moduleId] ?? [];
404
- const filteredStories = storiesInTestSpecification.filter((story) => {
405
- if (include.length && !include.some((tag) => story.tags?.includes(tag))) {
406
- return false;
407
- }
408
- if (exclude.some((tag) => story.tags?.includes(tag))) {
409
- return false;
410
- }
411
- return true;
412
- });
413
- if (!filteredStories.length) {
414
- continue;
415
- }
416
- if (!this.testManager.store.getState().watching) {
417
- this.updateLastChanged(testSpecification.moduleId);
418
- }
419
- filteredTestSpecifications.push(testSpecification);
420
- filteredStoryIds.push(
269
+ for (let testSpecification of testSpecifications) {
270
+ let { env = {} } = testSpecification.project.config, include = env.__VITEST_INCLUDE_TAGS__?.split(",").filter(Boolean) ?? ["test"], exclude = env.__VITEST_EXCLUDE_TAGS__?.split(",").filter(Boolean) ?? [], skip = env.__VITEST_SKIP_TAGS__?.split(",").filter(Boolean) ?? [], filteredStories = (storiesByImportPath[testSpecification.moduleId] ?? []).filter((story) => !(include.length && !include.some((tag) => story.tags?.includes(tag)) || exclude.some((tag) => story.tags?.includes(tag))));
271
+ filteredStories.length && (this.testManager.store.getState().watching || this.updateLastChanged(testSpecification.moduleId), filteredTestSpecifications.push(testSpecification), filteredStoryIds.push(
421
272
  ...filteredStories.filter((story) => !skip.some((tag) => story.tags?.includes(tag))).map((story) => story.id)
422
- );
273
+ ));
423
274
  }
424
275
  return { filteredTestSpecifications, filteredStoryIds };
425
276
  }
426
277
  async runTests(runPayload) {
427
- const { watching, config } = this.testManager.store.getState();
428
- const coverageShouldBeEnabled = config.coverage && !watching && (runPayload?.storyIds?.length ?? 0) === 0;
429
- const currentCoverage = this.vitest?.config.coverage?.enabled;
430
- if (!this.vitest) {
431
- await this.startVitest({ coverage: coverageShouldBeEnabled });
432
- } else if (currentCoverage !== coverageShouldBeEnabled) {
433
- await this.restartVitest({ coverage: coverageShouldBeEnabled });
434
- } else {
435
- await this.vitestRestartPromise;
436
- }
437
- this.resetGlobalTestNamePattern();
438
- await this.cancelCurrentRun();
439
- const testSpecifications = await this.getStorybookTestSpecifications();
440
- const allStories = await this.fetchStories();
441
- const filteredStories = runPayload.storyIds ? allStories.filter((story) => runPayload.storyIds?.includes(story.id)) : allStories;
442
- const isSingleStoryRun = runPayload.storyIds?.length === 1;
443
- if (isSingleStoryRun) {
444
- const selectedStory = filteredStories.find((story) => story.id === runPayload.storyIds?.[0]);
445
- if (!selectedStory) {
278
+ let { watching, config } = this.testManager.store.getState(), coverageShouldBeEnabled = config.coverage && !watching && (runPayload?.storyIds?.length ?? 0) === 0, currentCoverage = this.vitest?.config.coverage?.enabled;
279
+ this.vitest ? currentCoverage !== coverageShouldBeEnabled ? await this.restartVitest({ coverage: coverageShouldBeEnabled }) : await this.vitestRestartPromise : await this.startVitest({ coverage: coverageShouldBeEnabled }), this.resetGlobalTestNamePattern(), await this.cancelCurrentRun();
280
+ let testSpecifications = await this.getStorybookTestSpecifications(), allStories = await this.fetchStories(), filteredStories = runPayload.storyIds ? allStories.filter((story) => runPayload.storyIds?.includes(story.id)) : allStories;
281
+ if (runPayload.storyIds?.length === 1) {
282
+ let selectedStory = filteredStories.find((story) => story.id === runPayload.storyIds?.[0]);
283
+ if (!selectedStory)
446
284
  throw new Error(`Story ${runPayload.storyIds?.[0]} not found`);
447
- }
448
- const storyName = selectedStory.name;
449
- let regex;
450
- const isParentStory = allStories.some((story) => selectedStory.id === story.parent);
451
- const hasParentStory = allStories.some((story) => selectedStory.parent === story.id);
285
+ let storyName = selectedStory.name, regex, isParentStory = allStories.some((story) => selectedStory.id === story.parent), hasParentStory = allStories.some((story) => selectedStory.parent === story.id);
452
286
  if (isParentStory) {
453
- const parentName = getTestName(selectedStory.name);
287
+ let parentName = getTestName(selectedStory.name);
454
288
  regex = new RegExp(`^${parentName}`);
455
289
  } else if (hasParentStory) {
456
- const parentStory = allStories.find((story) => story.id === selectedStory.parent);
457
- if (!parentStory) {
290
+ let parentStory = allStories.find((story) => story.id === selectedStory.parent);
291
+ if (!parentStory)
458
292
  throw new Error(`Parent story not found for story ${selectedStory.id}`);
459
- }
460
- const parentName = getTestName(parentStory.name);
293
+ let parentName = getTestName(parentStory.name);
461
294
  regex = new RegExp(`^${parentName} ${storyName}$`);
462
- } else {
295
+ } else
463
296
  regex = new RegExp(`^${storyName}$`);
464
- }
465
297
  this.vitest.setGlobalTestNamePattern(regex);
466
298
  }
467
- const { filteredTestSpecifications, filteredStoryIds } = this.filterTestSpecifications(
299
+ let { filteredTestSpecifications, filteredStoryIds } = this.filterTestSpecifications(
468
300
  testSpecifications,
469
301
  filteredStories
470
302
  );
@@ -474,138 +306,92 @@ Please install the @vitest/${coveragePackage} package to collect coverage
474
306
  ...s.currentRun,
475
307
  totalTestCount: filteredStoryIds.length
476
308
  }
477
- }));
478
- await this.vitest.runTestSpecifications(filteredTestSpecifications, true);
479
- this.resetGlobalTestNamePattern();
309
+ })), await this.vitest.runTestSpecifications(filteredTestSpecifications, !0), this.resetGlobalTestNamePattern();
480
310
  }
481
311
  async cancelCurrentRun() {
482
- await this.vitest?.cancelCurrentRun("keyboard-input");
483
- await this.runningPromise;
312
+ await this.vitest?.cancelCurrentRun("keyboard-input"), await this.runningPromise;
484
313
  }
485
314
  async getStorybookTestSpecifications() {
486
- const globTestSpecifications = await this.vitest?.globTestSpecifications() ?? [];
487
- return globTestSpecifications.filter(
315
+ return (await this.vitest?.globTestSpecifications() ?? []).filter(
488
316
  (workspaceSpec) => this.isStorybookProject(workspaceSpec.project)
489
317
  ) ?? [];
490
318
  }
491
319
  async runAffectedTestsAfterChange(changedFilePath, event) {
492
- const id = slash(changedFilePath);
493
- this.vitest?.logger.clearHighlightCache(id);
494
- this.updateLastChanged(id);
495
- if (event === "add") {
496
- const project = this.vitest?.projects.find(this.isStorybookProject.bind(this));
497
- project?.matchesTestGlob(id);
498
- }
499
- if (!this.testManager.store.getState().watching) {
320
+ let id = slash(changedFilePath);
321
+ if (this.vitest?.logger.clearHighlightCache(id), this.updateLastChanged(id), event === "add" && this.vitest?.projects.find(this.isStorybookProject.bind(this))?.matchesTestGlob(id), !this.testManager.store.getState().watching || !this.vitest)
500
322
  return;
501
- }
502
- if (!this.vitest) {
503
- return;
504
- }
505
323
  this.resetGlobalTestNamePattern();
506
- const storybookProject = this.vitest.projects.find((p) => this.isStorybookProject(p));
507
- const previewAnnotationSpecifications = this.testManager.store.getState().previewAnnotations.map((previewAnnotation) => {
508
- return {
509
- project: storybookProject ?? this.vitest.projects[0],
510
- moduleId: typeof previewAnnotation === "string" ? previewAnnotation : previewAnnotation.absolute
511
- };
512
- });
513
- const setupFilesSpecifications = this.vitest.projects.flatMap(
324
+ let storybookProject = this.vitest.projects.find((p) => this.isStorybookProject(p)), previewAnnotationSpecifications = this.testManager.store.getState().previewAnnotations.map((previewAnnotation) => ({
325
+ project: storybookProject ?? this.vitest.projects[0],
326
+ moduleId: typeof previewAnnotation == "string" ? previewAnnotation : previewAnnotation.absolute
327
+ })), setupFilesSpecifications = this.vitest.projects.flatMap(
514
328
  (project) => project.config.setupFiles.map((setupFile) => ({
515
329
  project,
516
330
  moduleId: setupFile
517
331
  }))
518
- );
519
- const syntheticGlobalTestSpecifications = previewAnnotationSpecifications.concat(setupFilesSpecifications);
520
- const testSpecifications = await this.getStorybookTestSpecifications();
521
- const allStories = await this.fetchStories();
522
- let affectsGlobalFiles = false;
523
- const affectedTestSpecifications = (await Promise.all(
332
+ ), syntheticGlobalTestSpecifications = previewAnnotationSpecifications.concat(setupFilesSpecifications), testSpecifications = await this.getStorybookTestSpecifications(), allStories = await this.fetchStories(), affectsGlobalFiles = !1, affectedTestSpecifications = (await Promise.all(
524
333
  syntheticGlobalTestSpecifications.concat(testSpecifications).map(async (testSpecification) => {
525
- const dependencies = await this.getTestDependencies(testSpecification);
526
- if (changedFilePath === testSpecification.moduleId || dependencies.has(changedFilePath)) {
527
- if (syntheticGlobalTestSpecifications.includes(testSpecification)) {
528
- affectsGlobalFiles = true;
529
- }
530
- return testSpecification;
531
- }
334
+ let dependencies = await this.getTestDependencies(testSpecification);
335
+ if (changedFilePath === testSpecification.moduleId || dependencies.has(changedFilePath))
336
+ return syntheticGlobalTestSpecifications.includes(testSpecification) && (affectsGlobalFiles = !0), testSpecification;
532
337
  })
533
- )).filter(Boolean);
534
- const testSpecificationsToRun = affectsGlobalFiles ? testSpecifications : affectedTestSpecifications;
535
- if (!testSpecificationsToRun.length) {
338
+ )).filter(Boolean), testSpecificationsToRun = affectsGlobalFiles ? testSpecifications : affectedTestSpecifications;
339
+ if (!testSpecificationsToRun.length)
536
340
  return;
537
- }
538
- const { filteredTestSpecifications, filteredStoryIds } = this.filterTestSpecifications(
341
+ let { filteredTestSpecifications, filteredStoryIds } = this.filterTestSpecifications(
539
342
  testSpecificationsToRun,
540
343
  allStories
541
344
  );
542
345
  await this.testManager.runTestsWithState({
543
346
  storyIds: filteredStoryIds,
544
347
  triggeredBy: "watch",
545
- callback: /* @__PURE__ */ __name(async () => {
348
+ callback: async () => {
546
349
  this.testManager.store.setState((s) => ({
547
350
  ...s,
548
351
  currentRun: {
549
352
  ...s.currentRun,
550
353
  totalTestCount: filteredStoryIds.length
551
354
  }
552
- }));
553
- await this.vitest.cancelCurrentRun("keyboard-input");
554
- await this.runningPromise;
555
- await this.vitest.runTestSpecifications(filteredTestSpecifications, false);
556
- }, "callback")
355
+ })), await this.vitest.cancelCurrentRun("keyboard-input"), await this.runningPromise, await this.vitest.runTestSpecifications(filteredTestSpecifications, !1);
356
+ }
557
357
  });
558
358
  }
559
359
  // This is an adaptation of Vitest's own implementation
560
360
  // see https://github.com/vitest-dev/vitest/blob/14409088166152c920ce7fa4ad4c0ba57149b869/packages/vitest/src/node/specifications.ts#L171-L198
561
361
  async getTestDependencies(spec) {
562
- const deps = /* @__PURE__ */ new Set();
563
- const addImports = /* @__PURE__ */ __name(async (project, filepath) => {
564
- if (deps.has(filepath)) {
362
+ let deps = /* @__PURE__ */ new Set(), addImports = async (project, filepath) => {
363
+ if (deps.has(filepath))
565
364
  return;
566
- }
567
365
  deps.add(filepath);
568
- const mod = project.vite.moduleGraph.getModuleById(filepath);
569
- const transformed = mod?.ssrTransformResult || await project.vite.transformRequest(filepath, { ssr: true });
570
- if (!transformed) {
366
+ let transformed = project.vite.moduleGraph.getModuleById(filepath)?.ssrTransformResult || await project.vite.transformRequest(filepath, { ssr: !0 });
367
+ if (!transformed)
571
368
  return;
572
- }
573
- const dependencies = [...transformed.deps ?? [], ...transformed.dynamicDeps ?? []];
369
+ let dependencies = [...transformed.deps ?? [], ...transformed.dynamicDeps ?? []];
574
370
  await Promise.all(
575
371
  dependencies.map(async (dep) => {
576
- const fsPath = dep.startsWith("/@fs/") ? dep.slice(process.platform === "win32" ? 5 : 4) : join(project.config.root, dep);
577
- if (!fsPath.includes("node_modules") && !deps.has(fsPath) && existsSync(fsPath)) {
578
- await addImports(project, fsPath);
579
- }
372
+ let fsPath = dep.startsWith("/@fs/") ? dep.slice(process.platform === "win32" ? 5 : 4) : join(project.config.root, dep);
373
+ !fsPath.includes("node_modules") && !deps.has(fsPath) && existsSync(fsPath) && await addImports(project, fsPath);
580
374
  })
581
375
  );
582
- }, "addImports");
583
- await addImports(spec.project, spec.moduleId);
584
- deps.delete(spec.moduleId);
585
- return deps;
376
+ };
377
+ return await addImports(spec.project, spec.moduleId), deps.delete(spec.moduleId), deps;
586
378
  }
587
379
  async registerVitestConfigListener() {
588
380
  this.vitest.vite.watcher.on("change", async (file) => {
589
- const isConfig = normalize(file) === this.vitest?.vite?.config.configFile;
590
- if (isConfig) {
381
+ if (normalize(file) === this.vitest?.vite?.config.configFile) {
591
382
  log("Restarting Vitest due to config change");
592
- const { watching, config } = this.testManager.store.getState();
383
+ let { watching, config } = this.testManager.store.getState();
593
384
  await this.restartVitest({ coverage: config.coverage && !watching });
594
385
  }
595
386
  });
596
387
  }
597
388
  async setupWatchers() {
598
- this.resetGlobalTestNamePattern();
599
- this.vitest.vite.watcher.removeAllListeners("change");
600
- this.vitest.vite.watcher.removeAllListeners("add");
601
- this.vitest.vite.watcher.on(
389
+ this.resetGlobalTestNamePattern(), this.vitest.vite.watcher.removeAllListeners("change"), this.vitest.vite.watcher.removeAllListeners("add"), this.vitest.vite.watcher.on(
602
390
  "change",
603
391
  (file) => this.runAffectedTestsAfterChange(file, "change")
604
- );
605
- this.vitest.vite.watcher.on("add", (file) => {
392
+ ), this.vitest.vite.watcher.on("add", (file) => {
606
393
  this.runAffectedTestsAfterChange(file, "add");
607
- });
608
- this.registerVitestConfigListener();
394
+ }), this.registerVitestConfigListener();
609
395
  }
610
396
  isStorybookProject(project) {
611
397
  return !!project.config.env?.__STORYBOOK_URL__;
@@ -619,8 +405,7 @@ var testStateToStatusValueMap = {
619
405
  warning: "status-value:warning",
620
406
  failed: "status-value:error",
621
407
  skipped: "status-value:unknown"
622
- };
623
- var TestManager = class _TestManager {
408
+ }, TestManager = class _TestManager {
624
409
  constructor(options) {
625
410
  this.batchedTestCaseResults = [];
626
411
  /**
@@ -638,28 +423,15 @@ var TestManager = class _TestManager {
638
423
  * eventually causing the manager and dev server to lose connection.
639
424
  */
640
425
  this.throttledFlushTestCaseResults = throttle(() => {
641
- const testCaseResultsToFlush = this.batchedTestCaseResults;
642
- this.batchedTestCaseResults = [];
643
- this.store.setState((s) => {
644
- let { success: ctSuccess, error: ctError } = s.currentRun.componentTestCount;
645
- let { success: a11ySuccess, warning: a11yWarning, error: a11yError } = s.currentRun.a11yCount;
426
+ let testCaseResultsToFlush = this.batchedTestCaseResults;
427
+ this.batchedTestCaseResults = [], this.store.setState((s) => {
428
+ let { success: ctSuccess, error: ctError } = s.currentRun.componentTestCount, { success: a11ySuccess, warning: a11yWarning, error: a11yError } = s.currentRun.a11yCount;
646
429
  testCaseResultsToFlush.forEach(({ testResult, reports }) => {
647
- if (testResult.state === "passed") {
648
- ctSuccess++;
649
- } else if (testResult.state === "failed") {
650
- ctError++;
651
- }
652
- reports?.filter((r) => r.type === "a11y").forEach((report) => {
653
- if (report.status === "passed") {
654
- a11ySuccess++;
655
- } else if (report.status === "warning") {
656
- a11yWarning++;
657
- } else if (report.status === "failed") {
658
- a11yError++;
659
- }
430
+ testResult.state === "passed" ? ctSuccess++ : testResult.state === "failed" && ctError++, reports?.filter((r) => r.type === "a11y").forEach((report) => {
431
+ report.status === "passed" ? a11ySuccess++ : report.status === "warning" ? a11yWarning++ : report.status === "failed" && a11yError++;
660
432
  });
661
433
  });
662
- const finishedTestCount = ctSuccess + ctError;
434
+ let finishedTestCount = ctSuccess + ctError;
663
435
  return {
664
436
  ...s,
665
437
  currentRun: {
@@ -673,75 +445,57 @@ var TestManager = class _TestManager {
673
445
  }
674
446
  };
675
447
  });
676
- const componentTestStatuses = testCaseResultsToFlush.map(({ storyId, testResult }) => ({
448
+ let componentTestStatuses = testCaseResultsToFlush.map(({ storyId, testResult }) => ({
677
449
  storyId,
678
450
  typeId: STATUS_TYPE_ID_COMPONENT_TEST,
679
451
  value: testStateToStatusValueMap[testResult.state],
680
452
  title: "Component tests",
681
- description: testResult.errors?.map((error) => error.stack || error.message).join("\n") ?? "",
682
- sidebarContextMenu: false
453
+ description: testResult.errors?.map((error) => error.stack || error.message).join(`
454
+ `) ?? "",
455
+ sidebarContextMenu: !1
683
456
  }));
684
457
  this.componentTestStatusStore.set(componentTestStatuses);
685
- const a11yStatuses = testCaseResultsToFlush.flatMap(
458
+ let a11yStatuses = testCaseResultsToFlush.flatMap(
686
459
  ({ storyId, reports }) => reports?.filter((r) => r.type === "a11y").map((a11yReport) => ({
687
460
  storyId,
688
461
  typeId: STATUS_TYPE_ID_A11Y,
689
462
  value: testStateToStatusValueMap[a11yReport.status],
690
463
  title: "Accessibility tests",
691
464
  description: "",
692
- sidebarContextMenu: false
465
+ sidebarContextMenu: !1
693
466
  }))
694
467
  ).filter((a11yStatus) => a11yStatus !== void 0);
695
- if (a11yStatuses.length > 0) {
696
- this.a11yStatusStore.set(a11yStatuses);
697
- }
468
+ a11yStatuses.length > 0 && this.a11yStatusStore.set(a11yStatuses);
698
469
  }, 500);
699
- this.store = options.store;
700
- this.componentTestStatusStore = options.componentTestStatusStore;
701
- this.a11yStatusStore = options.a11yStatusStore;
702
- this.testProviderStore = options.testProviderStore;
703
- this.onReady = options.onReady;
704
- this.storybookOptions = options.storybookOptions;
705
- this.vitestManager = new VitestManager(this);
706
- this.store.subscribe("TRIGGER_RUN", this.handleTriggerRunEvent.bind(this));
707
- this.store.subscribe("CANCEL_RUN", this.handleCancelEvent.bind(this));
708
- this.store.untilReady().then(() => {
709
- return this.vitestManager.startVitest({ coverage: this.store.getState().config.coverage });
710
- }).then(() => this.onReady?.()).catch((e) => {
470
+ this.store = options.store, this.componentTestStatusStore = options.componentTestStatusStore, this.a11yStatusStore = options.a11yStatusStore, this.testProviderStore = options.testProviderStore, this.onReady = options.onReady, this.storybookOptions = options.storybookOptions, this.vitestManager = new VitestManager(this), this.store.subscribe("TRIGGER_RUN", this.handleTriggerRunEvent.bind(this)), this.store.subscribe("CANCEL_RUN", this.handleCancelEvent.bind(this)), this.store.untilReady().then(() => this.vitestManager.startVitest({ coverage: this.store.getState().config.coverage })).then(() => this.onReady?.()).catch((e) => {
711
471
  this.reportFatalError("Failed to start Vitest", e);
712
472
  });
713
473
  }
714
- static {
715
- __name(this, "TestManager");
716
- }
717
474
  async handleTriggerRunEvent(event) {
718
475
  await this.runTestsWithState({
719
476
  storyIds: event.payload.storyIds,
720
477
  triggeredBy: event.payload.triggeredBy,
721
- callback: /* @__PURE__ */ __name(async () => {
478
+ callback: async () => {
722
479
  try {
723
- await this.vitestManager.vitestRestartPromise;
724
- await this.vitestManager.runTests(event.payload);
480
+ await this.vitestManager.vitestRestartPromise, await this.vitestManager.runTests(event.payload);
725
481
  } catch (err) {
726
- this.reportFatalError("Failed to run tests", err);
727
- throw err;
482
+ throw this.reportFatalError("Failed to run tests", err), err;
728
483
  }
729
- }, "callback")
484
+ }
730
485
  });
731
486
  }
732
487
  async handleCancelEvent() {
733
488
  try {
734
489
  this.store.setState((s) => ({
735
490
  ...s,
736
- cancelling: true
737
- }));
738
- await this.vitestManager.cancelCurrentRun();
491
+ cancelling: !0
492
+ })), await this.vitestManager.cancelCurrentRun();
739
493
  } catch (err) {
740
494
  this.reportFatalError("Failed to cancel tests", err);
741
495
  } finally {
742
496
  this.store.setState((s) => ({
743
497
  ...s,
744
- cancelling: false
498
+ cancelling: !1
745
499
  }));
746
500
  }
747
501
  }
@@ -750,9 +504,7 @@ var TestManager = class _TestManager {
750
504
  triggeredBy,
751
505
  callback
752
506
  }) {
753
- this.componentTestStatusStore.unset(storyIds);
754
- this.a11yStatusStore.unset(storyIds);
755
- this.store.setState((s) => ({
507
+ this.componentTestStatusStore.unset(storyIds), this.a11yStatusStore.unset(storyIds), this.store.setState((s) => ({
756
508
  ...s,
757
509
  currentRun: {
758
510
  ...storeOptions.initialState.currentRun,
@@ -761,17 +513,12 @@ var TestManager = class _TestManager {
761
513
  storyIds,
762
514
  config: s.config
763
515
  }
764
- }));
765
- process.env.VITEST_STORYBOOK_CONFIG = JSON.stringify(this.store.getState().config);
766
- await this.testProviderStore.runWithState(async () => {
767
- await callback();
768
- this.store.send({
516
+ })), process.env.VITEST_STORYBOOK_CONFIG = JSON.stringify(this.store.getState().config), await this.testProviderStore.runWithState(async () => {
517
+ if (await callback(), this.store.send({
769
518
  type: "TEST_RUN_COMPLETED",
770
519
  payload: this.store.getState().currentRun
771
- });
772
- if (this.store.getState().currentRun.unhandledErrors.length > 0) {
520
+ }), this.store.getState().currentRun.unhandledErrors.length > 0)
773
521
  throw new Error("Tests completed but there are unhandled errors");
774
- }
775
522
  });
776
523
  }
777
524
  onTestModuleCollected(collectedTestCount) {
@@ -784,16 +531,11 @@ var TestManager = class _TestManager {
784
531
  }));
785
532
  }
786
533
  onTestCaseResult(result) {
787
- const { storyId, testResult, reports } = result;
788
- if (!storyId) {
789
- return;
790
- }
791
- this.batchedTestCaseResults.push({ storyId, testResult, reports });
792
- this.throttledFlushTestCaseResults();
534
+ let { storyId, testResult, reports } = result;
535
+ storyId && (this.batchedTestCaseResults.push({ storyId, testResult, reports }), this.throttledFlushTestCaseResults());
793
536
  }
794
537
  onTestRunEnd(endResult) {
795
- this.throttledFlushTestCaseResults.flush();
796
- this.store.setState((s) => ({
538
+ this.throttledFlushTestCaseResults.flush(), this.store.setState((s) => ({
797
539
  ...s,
798
540
  currentRun: {
799
541
  ...s.currentRun,
@@ -813,8 +555,7 @@ var TestManager = class _TestManager {
813
555
  }));
814
556
  }
815
557
  async reportFatalError(message, error) {
816
- await this.store.untilReady();
817
- this.store.send({
558
+ await this.store.untilReady(), this.store.send({
818
559
  type: "FATAL_ERROR",
819
560
  payload: {
820
561
  message,
@@ -824,30 +565,26 @@ var TestManager = class _TestManager {
824
565
  }
825
566
  static async start(options) {
826
567
  return new Promise((resolve) => {
827
- const testManager = new _TestManager({
568
+ let testManager = new _TestManager({
828
569
  ...options,
829
- onReady: /* @__PURE__ */ __name(() => {
830
- resolve(testManager);
831
- options.onReady?.();
832
- }, "onReady")
570
+ onReady: () => {
571
+ resolve(testManager), options.onReady?.();
572
+ }
833
573
  });
834
574
  });
835
575
  }
836
576
  };
837
577
 
838
578
  // src/node/vitest.ts
839
- var UniversalStore = experimental_UniversalStore;
840
- var getStatusStore = experimental_getStatusStore;
841
- var getTestProviderStore = experimental_getTestProviderStore;
842
- var channel = new Channel({
843
- async: true,
579
+ var UniversalStore = experimental_UniversalStore, getStatusStore = experimental_getStatusStore, getTestProviderStore = experimental_getTestProviderStore, channel = new Channel({
580
+ async: !0,
844
581
  transport: {
845
- send: /* @__PURE__ */ __name((event) => {
582
+ send: (event) => {
846
583
  process2.send?.(event);
847
- }, "send"),
848
- setHandler: /* @__PURE__ */ __name((handler) => {
584
+ },
585
+ setHandler: (handler) => {
849
586
  process2.on("message", handler);
850
- }, "setHandler")
587
+ }
851
588
  }
852
589
  });
853
590
  UniversalStore.__prepare(channel, UniversalStore.Environment.SERVER);
@@ -857,20 +594,18 @@ new TestManager({
857
594
  componentTestStatusStore: getStatusStore(STATUS_TYPE_ID_COMPONENT_TEST),
858
595
  a11yStatusStore: getStatusStore(STATUS_TYPE_ID_A11Y),
859
596
  testProviderStore: getTestProviderStore(ADDON_ID),
860
- onReady: /* @__PURE__ */ __name(() => {
597
+ onReady: () => {
861
598
  process2.send?.({ type: "ready" });
862
- }, "onReady"),
599
+ },
863
600
  storybookOptions: {
864
601
  configDir: process2.env.STORYBOOK_CONFIG_DIR || ""
865
602
  }
866
603
  });
867
- var exit = /* @__PURE__ */ __name((code = 0) => {
868
- channel?.removeAllListeners();
869
- process2.exit(code);
870
- }, "exit");
871
- var createUnhandledErrorHandler = /* @__PURE__ */ __name((message) => async (error) => {
604
+ var exit = (code = 0) => {
605
+ channel?.removeAllListeners(), process2.exit(code);
606
+ }, createUnhandledErrorHandler = (message) => async (error) => {
872
607
  try {
873
- const payload = {
608
+ let payload = {
874
609
  message,
875
610
  error: {
876
611
  message: error.message,
@@ -886,7 +621,7 @@ var createUnhandledErrorHandler = /* @__PURE__ */ __name((message) => async (err
886
621
  } finally {
887
622
  exit(1);
888
623
  }
889
- }, "createUnhandledErrorHandler");
624
+ };
890
625
  process2.on(
891
626
  "uncaughtException",
892
627
  createUnhandledErrorHandler("Uncaught exception in the test runner process")