@storybook/addon-vitest 0.0.0-pr-32813-sha-13a2dbef → 0.0.0-pr-32826-sha-83cda975

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 (41) hide show
  1. package/dist/chunk-55WZLVGN.mjs +11 -0
  2. package/dist/chunk-JKRQGT2U.mjs +10 -0
  3. package/dist/index.js +6 -9
  4. package/dist/index.mjs +5 -0
  5. package/dist/manager.js +8 -958
  6. package/dist/node/coverage-reporter.d.ts +184 -0
  7. package/dist/node/coverage-reporter.js +4 -1898
  8. package/dist/node/coverage-reporter.mjs +12 -0
  9. package/dist/node/vitest.d.ts +2 -0
  10. package/dist/node/vitest.js +17 -895
  11. package/dist/node/vitest.mjs +19 -0
  12. package/dist/postinstall.js +86 -2182
  13. package/dist/preset.js +35 -615
  14. package/dist/vitest-plugin/global-setup.d.ts +6 -0
  15. package/dist/vitest-plugin/global-setup.js +6 -200
  16. package/dist/vitest-plugin/global-setup.mjs +13 -0
  17. package/dist/vitest-plugin/index.js +43 -3827
  18. package/dist/vitest-plugin/index.mjs +28 -0
  19. package/dist/vitest-plugin/setup-file.d.ts +14 -0
  20. package/dist/vitest-plugin/setup-file.js +8 -30
  21. package/dist/vitest-plugin/setup-file.mjs +9 -0
  22. package/dist/vitest-plugin/test-utils.d.ts +20 -0
  23. package/dist/vitest-plugin/test-utils.js +8 -105
  24. package/dist/vitest-plugin/test-utils.mjs +8 -0
  25. package/manager.js +1 -1
  26. package/manager.mjs +1 -0
  27. package/package.json +91 -18
  28. package/postinstall.js +1 -0
  29. package/postinstall.mjs +1 -0
  30. package/preset.js +1 -1
  31. package/preset.mjs +1 -0
  32. package/dist/_browser-chunks/chunk-JK72E6FR.js +0 -6
  33. package/dist/_browser-chunks/chunk-PMYV6BH2.js +0 -76
  34. package/dist/_node-chunks/chunk-3HWZPHA7.js +0 -98
  35. package/dist/_node-chunks/chunk-AYHCYMTA.js +0 -103
  36. package/dist/_node-chunks/chunk-BV2IPKWM.js +0 -2574
  37. package/dist/_node-chunks/chunk-CL6PXGFC.js +0 -247
  38. package/dist/_node-chunks/chunk-JH5JWB2Y.js +0 -37
  39. package/dist/_node-chunks/chunk-O4DRP46F.js +0 -50
  40. package/dist/_node-chunks/chunk-SBEGZ5SF.js +0 -481
  41. package/dist/_node-chunks/chunk-U6VJX4LL.js +0 -91
@@ -1,900 +1,22 @@
1
- import CJS_COMPAT_NODE_URL_rkzy95h2tir from 'node:url';
2
- import CJS_COMPAT_NODE_PATH_rkzy95h2tir from 'node:path';
3
- import CJS_COMPAT_NODE_MODULE_rkzy95h2tir from "node:module";
1
+ 'use strict';
4
2
 
5
- var __filename = CJS_COMPAT_NODE_URL_rkzy95h2tir.fileURLToPath(import.meta.url);
6
- var __dirname = CJS_COMPAT_NODE_PATH_rkzy95h2tir.dirname(__filename);
7
- var require = CJS_COMPAT_NODE_MODULE_rkzy95h2tir.createRequire(import.meta.url);
3
+ var module$1 = require('module');
4
+ var process3 = require('process');
5
+ var channels = require('storybook/internal/channels');
6
+ var fs = require('fs');
7
+ var common = require('storybook/internal/common');
8
+ var path2 = require('path');
9
+ var url = require('url');
8
10
 
9
- // ------------------------------------------------------------
10
- // end of CJS compatibility banner, injected by Storybook's esbuild configuration
11
- // ------------------------------------------------------------
12
- import {
13
- log
14
- } from "../_node-chunks/chunk-JH5JWB2Y.js";
15
- import {
16
- any,
17
- errorToErrorLike
18
- } from "../_node-chunks/chunk-3HWZPHA7.js";
19
- import {
20
- ADDON_ID,
21
- COVERAGE_DIRECTORY,
22
- STATUS_TYPE_ID_A11Y,
23
- STATUS_TYPE_ID_COMPONENT_TEST,
24
- storeOptions
25
- } from "../_node-chunks/chunk-AYHCYMTA.js";
26
- import "../_node-chunks/chunk-U6VJX4LL.js";
27
- import {
28
- dirname,
29
- join,
30
- normalize,
31
- path
32
- } from "../_node-chunks/chunk-CL6PXGFC.js";
33
- import {
34
- __name
35
- } from "../_node-chunks/chunk-O4DRP46F.js";
11
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
12
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
36
13
 
37
- // src/node/vitest.ts
38
- import process2 from "node:process";
39
- import { Channel } from "storybook/internal/channels";
40
- import {
41
- experimental_UniversalStore,
42
- experimental_getStatusStore,
43
- experimental_getTestProviderStore
44
- } from "storybook/internal/core-server";
14
+ var process3__default = /*#__PURE__*/_interopDefault(process3);
15
+ var path2__default = /*#__PURE__*/_interopDefault(path2);
45
16
 
46
- // ../../node_modules/es-toolkit/dist/function/debounce.mjs
47
- 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();
73
- }, 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(() => {
87
- invoke();
88
- }, "flush");
89
- const debounced = /* @__PURE__ */ __name(function(...args) {
90
- if (signal?.aborted) {
91
- 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;
106
- }
107
- __name(debounce, "debounce");
17
+ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty;var __require=(x=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(x,{get:(a,b)=>(typeof require<"u"?require:a)[b]}):x)(function(x){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});var __commonJS=(cb,mod)=>function(){return mod||(0, cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod));var require_picocolors=__commonJS({"../../node_modules/picocolors/picocolors.js"(exports,module){var p=process||{},argv=p.argv||[],env=p.env||{},isColorSupported=!(env.NO_COLOR||argv.includes("--no-color"))&&(!!env.FORCE_COLOR||argv.includes("--color")||p.platform==="win32"||(p.stdout||{}).isTTY&&env.TERM!=="dumb"||!!env.CI),formatter=(open,close,replace=open)=>input=>{let string=""+input,index=string.indexOf(close,open.length);return ~index?open+replaceClose(string,close,replace,index)+close:open+string+close},replaceClose=(string,close,replace,index)=>{let result="",cursor=0;do result+=string.substring(cursor,index)+replace,cursor=index+close.length,index=string.indexOf(close,cursor);while(~index);return result+string.substring(cursor)},createColors=(enabled=isColorSupported)=>{let f=enabled?formatter:()=>String;return {isColorSupported:enabled,reset:f("\x1B[0m","\x1B[0m"),bold:f("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:f("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:f("\x1B[3m","\x1B[23m"),underline:f("\x1B[4m","\x1B[24m"),inverse:f("\x1B[7m","\x1B[27m"),hidden:f("\x1B[8m","\x1B[28m"),strikethrough:f("\x1B[9m","\x1B[29m"),black:f("\x1B[30m","\x1B[39m"),red:f("\x1B[31m","\x1B[39m"),green:f("\x1B[32m","\x1B[39m"),yellow:f("\x1B[33m","\x1B[39m"),blue:f("\x1B[34m","\x1B[39m"),magenta:f("\x1B[35m","\x1B[39m"),cyan:f("\x1B[36m","\x1B[39m"),white:f("\x1B[37m","\x1B[39m"),gray:f("\x1B[90m","\x1B[39m"),bgBlack:f("\x1B[40m","\x1B[49m"),bgRed:f("\x1B[41m","\x1B[49m"),bgGreen:f("\x1B[42m","\x1B[49m"),bgYellow:f("\x1B[43m","\x1B[49m"),bgBlue:f("\x1B[44m","\x1B[49m"),bgMagenta:f("\x1B[45m","\x1B[49m"),bgCyan:f("\x1B[46m","\x1B[49m"),bgWhite:f("\x1B[47m","\x1B[49m"),blackBright:f("\x1B[90m","\x1B[39m"),redBright:f("\x1B[91m","\x1B[39m"),greenBright:f("\x1B[92m","\x1B[39m"),yellowBright:f("\x1B[93m","\x1B[39m"),blueBright:f("\x1B[94m","\x1B[39m"),magentaBright:f("\x1B[95m","\x1B[39m"),cyanBright:f("\x1B[96m","\x1B[39m"),whiteBright:f("\x1B[97m","\x1B[39m"),bgBlackBright:f("\x1B[100m","\x1B[49m"),bgRedBright:f("\x1B[101m","\x1B[49m"),bgGreenBright:f("\x1B[102m","\x1B[49m"),bgYellowBright:f("\x1B[103m","\x1B[49m"),bgBlueBright:f("\x1B[104m","\x1B[49m"),bgMagentaBright:f("\x1B[105m","\x1B[49m"),bgCyanBright:f("\x1B[106m","\x1B[49m"),bgWhiteBright:f("\x1B[107m","\x1B[49m")}};module.exports=createColors();module.exports.createColors=createColors;}});var ADDON_ID2="storybook/test";var COVERAGE_DIRECTORY="coverage";var storeOptions={id:ADDON_ID2,initialState:{config:{coverage:!1,a11y:!1},watching:!1,cancelling:!1,fatalError:void 0,indexUrl:void 0,previewAnnotations:[],currentRun:{triggeredBy:void 0,config:{coverage:!1,a11y:!1},componentTestCount:{success:0,error:0},a11yCount:{success:0,warning:0,error:0},storyIds:void 0,totalTestCount:void 0,startedAt:void 0,finishedAt:void 0,unhandledErrors:[],coverageSummary:void 0}}};`UNIVERSAL_STORE:${storeOptions.id}`;var STATUS_TYPE_ID_COMPONENT_TEST="storybook/component-test",STATUS_TYPE_ID_A11Y="storybook/a11y";function debounce(func,debounceMs,{signal,edges}={}){let pendingThis,pendingArgs=null,leading=edges!=null&&edges.includes("leading"),trailing=edges==null||edges.includes("trailing"),invoke=()=>{pendingArgs!==null&&(func.apply(pendingThis,pendingArgs),pendingThis=void 0,pendingArgs=null);},onTimerEnd=()=>{trailing&&invoke(),cancel();},timeoutId=null,schedule=()=>{timeoutId!=null&&clearTimeout(timeoutId),timeoutId=setTimeout(()=>{timeoutId=null,onTimerEnd();},debounceMs);},cancelTimer=()=>{timeoutId!==null&&(clearTimeout(timeoutId),timeoutId=null);},cancel=()=>{cancelTimer(),pendingThis=void 0,pendingArgs=null;},flush=()=>{cancelTimer(),invoke();},debounced=function(...args){if(signal?.aborted)return;pendingThis=this,pendingArgs=args;let isFirstCall=timeoutId==null;schedule(),leading&&isFirstCall&&invoke();};return debounced.schedule=schedule,debounced.cancel=cancel,debounced.flush=flush,signal?.addEventListener("abort",cancel,{once:!0}),debounced}function throttle(func,throttleMs,{signal,edges=["leading","trailing"]}={}){let pendingAt=null,debounced=debounce(func,throttleMs,{signal,edges}),throttled=function(...args){pendingAt==null?pendingAt=Date.now():Date.now()-pendingAt>=throttleMs&&(pendingAt=Date.now(),debounced.cancel()),debounced(...args);};return throttled.cancel=debounced.cancel,throttled.flush=debounced.flush,throttled}function errorToErrorLike(error){return {message:error.message,name:error.name,stack:error.stack?.replace(error.message,""),cause:error.cause&&error.cause instanceof Error?errorToErrorLike(error.cause):void 0}}var Node=class{value;next;constructor(value){this.value=value;}},Queue=class{#head;#tail;#size;constructor(){this.clear();}enqueue(value){let node=new Node(value);this.#head?(this.#tail.next=node,this.#tail=node):(this.#head=node,this.#tail=node),this.#size++;}dequeue(){let current=this.#head;if(current)return this.#head=this.#head.next,this.#size--,current.value}peek(){if(this.#head)return this.#head.value}clear(){this.#head=void 0,this.#tail=void 0,this.#size=0;}get size(){return this.#size}*[Symbol.iterator](){let current=this.#head;for(;current;)yield current.value,current=current.next;}*drain(){for(;this.#head;)yield this.dequeue();}};function pLimit(concurrency){if(!((Number.isInteger(concurrency)||concurrency===Number.POSITIVE_INFINITY)&&concurrency>0))throw new TypeError("Expected `concurrency` to be a number from 1 and up");let queue=new Queue,activeCount=0,next=()=>{activeCount--,queue.size>0&&queue.dequeue()();},run=async(fn,resolve2,args)=>{activeCount++;let result=(async()=>fn(...args))();resolve2(result);try{await result;}catch{}next();},enqueue=(fn,resolve2,args)=>{queue.enqueue(run.bind(void 0,fn,resolve2,args)),(async()=>(await Promise.resolve(),activeCount<concurrency&&queue.size>0&&queue.dequeue()()))();},generator=(fn,...args)=>new Promise(resolve2=>{enqueue(fn,resolve2,args);});return Object.defineProperties(generator,{activeCount:{get:()=>activeCount},pendingCount:{get:()=>queue.size},clearQueue:{value:()=>{queue.clear();}}}),generator}var EndError=class extends Error{constructor(value){super(),this.value=value;}},testElement=async(element,tester)=>tester(await element),finder=async element=>{let values=await Promise.all(element);if(values[1]===!0)throw new EndError(values[0]);return !1};async function pLocate(iterable,tester,{concurrency=Number.POSITIVE_INFINITY,preserveOrder=!0}={}){let limit=pLimit(concurrency),items=[...iterable].map(element=>[element,limit(testElement,element,tester)]),checkLimit=pLimit(preserveOrder?1:Number.POSITIVE_INFINITY);try{await Promise.all(items.map(element=>checkLimit(finder,element)));}catch(error){if(error instanceof EndError)return error.value;throw error}}var typeMappings={directory:"isDirectory",file:"isFile"};function checkType(type){if(!Object.hasOwnProperty.call(typeMappings,type))throw new Error(`Invalid type specified: ${type}`)}var matchType=(type,stat)=>stat[typeMappings[type]](),toPath=urlOrPath=>urlOrPath instanceof URL?url.fileURLToPath(urlOrPath):urlOrPath;async function locatePath(paths,{cwd:cwd2=process3__default.default.cwd(),type="file",allowSymlinks=!0,concurrency,preserveOrder}={}){checkType(type),cwd2=toPath(cwd2);let statFunction=allowSymlinks?fs.promises.stat:fs.promises.lstat;return pLocate(paths,async path_=>{try{let stat=await statFunction(path2__default.default.resolve(cwd2,path_));return matchType(type,stat)}catch{return !1}},{concurrency,preserveOrder})}function toPath2(urlOrPath){return urlOrPath instanceof URL?url.fileURLToPath(urlOrPath):urlOrPath}var findUpStop=Symbol("findUpStop");async function findUpMultiple(name,options={}){let directory=path2__default.default.resolve(toPath2(options.cwd)??""),{root}=path2__default.default.parse(directory),stopAt=path2__default.default.resolve(directory,toPath2(options.stopAt??root)),limit=options.limit??Number.POSITIVE_INFINITY,paths=[name].flat(),runMatcher=async locateOptions=>{if(typeof name!="function")return locatePath(paths,locateOptions);let foundPath=await name(locateOptions.cwd);return typeof foundPath=="string"?locatePath([foundPath],locateOptions):foundPath},matches=[];for(;;){let foundPath=await runMatcher({...options,cwd:directory});if(foundPath===findUpStop||(foundPath&&matches.push(path2__default.default.resolve(directory,foundPath)),directory===stopAt||matches.length>=limit))break;directory=path2__default.default.dirname(directory);}return matches}async function findUp(name,options={}){return (await findUpMultiple(name,{...options,limit:1}))[0]}var _DRIVE_LETTER_START_RE=/^[A-Za-z]:\//;function normalizeWindowsPath(input=""){return input&&input.replace(/\\/g,"/").replace(_DRIVE_LETTER_START_RE,r=>r.toUpperCase())}var _UNC_REGEX=/^[/\\]{2}/,_IS_ABSOLUTE_RE=/^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/,_DRIVE_LETTER_RE=/^[A-Za-z]:$/,_ROOT_FOLDER_RE=/^\/([A-Za-z]:)?$/,sep="/",delimiter=":",normalize=function(path4){if(path4.length===0)return ".";path4=normalizeWindowsPath(path4);let isUNCPath=path4.match(_UNC_REGEX),isPathAbsolute=isAbsolute(path4),trailingSeparator=path4[path4.length-1]==="/";return path4=normalizeString(path4,!isPathAbsolute),path4.length===0?isPathAbsolute?"/":trailingSeparator?"./":".":(trailingSeparator&&(path4+="/"),_DRIVE_LETTER_RE.test(path4)&&(path4+="/"),isUNCPath?isPathAbsolute?`//${path4}`:`//./${path4}`:isPathAbsolute&&!isAbsolute(path4)?`/${path4}`:path4)},join=function(...arguments_){if(arguments_.length===0)return ".";let joined;for(let argument of arguments_)argument&&argument.length>0&&(joined===void 0?joined=argument:joined+=`/${argument}`);return joined===void 0?".":normalize(joined.replace(/\/\/+/g,"/"))};function cwd(){return typeof process<"u"&&typeof process.cwd=="function"?process.cwd().replace(/\\/g,"/"):"/"}var resolve=function(...arguments_){arguments_=arguments_.map(argument=>normalizeWindowsPath(argument));let resolvedPath="",resolvedAbsolute=!1;for(let index=arguments_.length-1;index>=-1&&!resolvedAbsolute;index--){let path4=index>=0?arguments_[index]:cwd();!path4||path4.length===0||(resolvedPath=`${path4}/${resolvedPath}`,resolvedAbsolute=isAbsolute(path4));}return resolvedPath=normalizeString(resolvedPath,!resolvedAbsolute),resolvedAbsolute&&!isAbsolute(resolvedPath)?`/${resolvedPath}`:resolvedPath.length>0?resolvedPath:"."};function normalizeString(path4,allowAboveRoot){let res="",lastSegmentLength=0,lastSlash=-1,dots=0,char=null;for(let index=0;index<=path4.length;++index){if(index<path4.length)char=path4[index];else {if(char==="/")break;char="/";}if(char==="/"){if(!(lastSlash===index-1||dots===1))if(dots===2){if(res.length<2||lastSegmentLength!==2||res[res.length-1]!=="."||res[res.length-2]!=="."){if(res.length>2){let lastSlashIndex=res.lastIndexOf("/");lastSlashIndex===-1?(res="",lastSegmentLength=0):(res=res.slice(0,lastSlashIndex),lastSegmentLength=res.length-1-res.lastIndexOf("/")),lastSlash=index,dots=0;continue}else if(res.length>0){res="",lastSegmentLength=0,lastSlash=index,dots=0;continue}}allowAboveRoot&&(res+=res.length>0?"/..":"..",lastSegmentLength=2);}else res.length>0?res+=`/${path4.slice(lastSlash+1,index)}`:res=path4.slice(lastSlash+1,index),lastSegmentLength=index-lastSlash-1;lastSlash=index,dots=0;}else char==="."&&dots!==-1?++dots:dots=-1;}return res}var isAbsolute=function(p){return _IS_ABSOLUTE_RE.test(p)},toNamespacedPath=function(p){return normalizeWindowsPath(p)},_EXTNAME_RE=/.(\.[^./]+)$/,extname=function(p){let match=_EXTNAME_RE.exec(normalizeWindowsPath(p));return match&&match[1]||""},relative=function(from,to){let _from=resolve(from).replace(_ROOT_FOLDER_RE,"$1").split("/"),_to=resolve(to).replace(_ROOT_FOLDER_RE,"$1").split("/");if(_to[0][1]===":"&&_from[0][1]===":"&&_from[0]!==_to[0])return _to.join("/");let _fromCopy=[..._from];for(let segment of _fromCopy){if(_to[0]!==segment)break;_from.shift(),_to.shift();}return [..._from.map(()=>".."),..._to].join("/")},dirname=function(p){let segments=normalizeWindowsPath(p).replace(/\/$/,"").split("/").slice(0,-1);return segments.length===1&&_DRIVE_LETTER_RE.test(segments[0])&&(segments[0]+="/"),segments.join("/")||(isAbsolute(p)?"/":".")},format=function(p){let segments=[p.root,p.dir,p.base??p.name+p.ext].filter(Boolean);return normalizeWindowsPath(p.root?resolve(...segments):segments.join("/"))},basename=function(p,extension){let lastSegment=normalizeWindowsPath(p).split("/").pop();return extension&&lastSegment.endsWith(extension)?lastSegment.slice(0,-extension.length):lastSegment},parse=function(p){let root=normalizeWindowsPath(p).split("/").shift()||"/",base=basename(p),extension=extname(base);return {root,dir:dirname(p),base,ext:extension,name:base.slice(0,base.length-extension.length)}},path3={__proto__:null,basename,delimiter,dirname,extname,format,isAbsolute,join,normalize,normalizeString,parse,relative,resolve,sep,toNamespacedPath};function slash(path4){return path4.startsWith("\\\\?\\")?path4:path4.replace(/\\/g,"/")}var import_picocolors=__toESM(require_picocolors());var log=message=>{console.log(`${import_picocolors.default.magenta(ADDON_ID2)}: ${message.toString().trim()}`);};var StorybookReporter=class{constructor(testManager){this.testManager=testManager;}onInit(ctx){this.ctx=ctx;}onTestCaseResult(testCase){let{storyId,reports}=testCase.meta(),testResult=testCase.result();this.testManager.onTestCaseResult({storyId,testResult,reports});}async onTestRunEnd(testModules,unhandledErrors){let totalTestCount=testModules.flatMap(t=>Array.from(t.children.allTests("passed")).concat(Array.from(t.children.allTests("failed")))).length,testModulesErrors=testModules.flatMap(t=>t.errors()),serializedErrors=unhandledErrors.concat(testModulesErrors).map(e=>({...e,name:e.name,message:e.message,stack:e.stack?.replace(e.message,""),cause:e.cause}));this.testManager.onTestRunEnd({totalTestCount,unhandledErrors:serializedErrors}),this.clearVitestState();}async clearVitestState(){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();}};var VITEST_CONFIG_FILE_EXTENSIONS=["mts","mjs","cts","cjs","ts","tsx","js","jsx"],VITEST_WORKSPACE_FILE_EXTENSION=["ts","js","json"],packageDir=dirname(__require.resolve("@storybook/addon-vitest/package.json"));process.env.VITEST_STORYBOOK="true";var VitestManager=class{constructor(testManager){this.testManager=testManager;this.vitest=null;this.vitestStartupCounter=0;this.vitestRestartPromise=null;this.runningPromise=null;}async startVitest({coverage}){let{createVitest}=await import('vitest/node'),storybookCoverageReporter=[join(packageDir,"dist/node/coverage-reporter.js"),{testManager:this.testManager,coverageOptions:this.vitest?.config?.coverage}],coverageOptions=coverage?{enabled:!0,clean:!0,cleanOnRerun:!0,reportOnFailure:!0,reporter:[["html",{}],storybookCoverageReporter],reportsDirectory:common.resolvePathInStorybookCache(COVERAGE_DIRECTORY)}:{enabled:!1},vitestWorkspaceConfig=await findUp([...VITEST_WORKSPACE_FILE_EXTENSION.map(ext=>`vitest.workspace.${ext}`),...VITEST_CONFIG_FILE_EXTENSIONS.map(ext=>`vitest.config.${ext}`)],{stopAt:common.getProjectRoot()}),projectName="storybook:"+process.env.STORYBOOK_CONFIG_DIR;try{this.vitest=await createVitest("test",{root:vitestWorkspaceConfig?dirname(vitestWorkspaceConfig):process.cwd(),watch:!0,passWithNoTests:!1,project:[projectName],reporters:["default",new StorybookReporter(this.testManager)],coverage:coverageOptions});}catch(err){let originalMessage=String(err.message);if(originalMessage.includes("Found multiple projects")){let custom=["Storybook was unable to start the test run because you have multiple Vitest projects (or browsers) in headed mode.","Please set `headless: true` in your Storybook vitest config.\n\n"].join(`
18
+ `);originalMessage.startsWith(custom)||(err.message=`${custom}${originalMessage}`);}throw err}this.vitest&&this.vitest.onCancel(()=>{});try{await this.vitest.init();}catch(e){let message="Failed to initialize Vitest",isV8=e.message?.includes("@vitest/coverage-v8"),isIstanbul=e.message?.includes("@vitest/coverage-istanbul");(e.message?.includes("Failed to load url")&&(isIstanbul||isV8)||e instanceof TypeError&&e?.message==="Cannot read properties of undefined (reading 'name')")&&(message+=`
108
19
 
109
- // ../../node_modules/es-toolkit/dist/function/partial.mjs
110
- function partial(func, ...partialArgs) {
111
- return partialImpl(func, placeholderSymbol, ...partialArgs);
112
- }
113
- __name(partial, "partial");
114
- 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);
119
- return func.apply(this, substitutedArgs.concat(remainingArgs));
120
- }, "partialed");
121
- if (func.prototype) {
122
- partialed.prototype = Object.create(func.prototype);
123
- }
124
- return partialed;
125
- }
126
- __name(partialImpl, "partialImpl");
127
- var placeholderSymbol = Symbol("partial.placeholder");
128
- partial.placeholder = placeholderSymbol;
129
-
130
- // ../../node_modules/es-toolkit/dist/function/partialRight.mjs
131
- function partialRight(func, ...partialArgs) {
132
- return partialRightImpl(func, placeholderSymbol2, ...partialArgs);
133
- }
134
- __name(partialRight, "partialRight");
135
- 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);
142
- return func.apply(this, remainingArgs.concat(substitutedArgs));
143
- }, "partialedRight");
144
- if (func.prototype) {
145
- partialedRight.prototype = Object.create(func.prototype);
146
- }
147
- return partialedRight;
148
- }
149
- __name(partialRightImpl, "partialRightImpl");
150
- var placeholderSymbol2 = Symbol("partialRight.placeholder");
151
- partialRight.placeholder = placeholderSymbol2;
152
-
153
- // ../../node_modules/es-toolkit/dist/function/retry.mjs
154
- var DEFAULT_RETRIES = Number.POSITIVE_INFINITY;
155
-
156
- // ../../node_modules/es-toolkit/dist/function/throttle.mjs
157
- 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;
174
- }
175
- __name(throttle, "throttle");
176
-
177
- // src/node/vitest-manager.ts
178
- import { existsSync } from "node:fs";
179
- import { getProjectRoot, resolvePathInStorybookCache } from "storybook/internal/common";
180
-
181
- // ../../node_modules/slash/index.js
182
- function slash(path2) {
183
- const isExtendedLengthPath = path2.startsWith("\\\\?\\");
184
- if (isExtendedLengthPath) {
185
- return path2;
186
- }
187
- return path2.replace(/\\/g, "/");
188
- }
189
- __name(slash, "slash");
190
-
191
- // src/node/reporter.ts
192
- var StorybookReporter = class {
193
- constructor(testManager) {
194
- this.testManager = testManager;
195
- }
196
- static {
197
- __name(this, "StorybookReporter");
198
- }
199
- onInit(ctx) {
200
- this.ctx = ctx;
201
- }
202
- onTestCaseResult(testCase) {
203
- const { storyId, reports } = testCase.meta();
204
- const testResult = testCase.result();
205
- this.testManager.onTestCaseResult({
206
- storyId,
207
- testResult,
208
- reports
209
- });
210
- }
211
- async onTestRunEnd(testModules, unhandledErrors) {
212
- const totalTestCount = testModules.flatMap(
213
- (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
- });
225
- this.testManager.onTestRunEnd({
226
- totalTestCount,
227
- unhandledErrors: serializedErrors
228
- });
229
- this.clearVitestState();
230
- }
231
- // TODO: Clearing the whole internal state of Vitest might be too aggressive
232
- 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();
238
- }
239
- };
240
-
241
- // 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"];
244
- process.env.VITEST_STORYBOOK = "true";
245
- var DOUBLE_SPACES = " ";
246
- var getTestName = /* @__PURE__ */ __name((name) => `${name}${DOUBLE_SPACES}`, "getTestName");
247
- var VitestManager = class {
248
- constructor(testManager) {
249
- this.testManager = testManager;
250
- this.vitest = null;
251
- this.vitestStartupCounter = 0;
252
- this.vitestRestartPromise = null;
253
- this.runningPromise = null;
254
- }
255
- static {
256
- __name(this, "VitestManager");
257
- }
258
- async startVitest({ coverage }) {
259
- const { createVitest } = await import("vitest/node");
260
- const storybookCoverageReporter = [
261
- "@storybook/addon-vitest/internal/coverage-reporter",
262
- {
263
- testManager: this.testManager,
264
- coverageOptions: this.vitest?.config?.coverage
265
- }
266
- ];
267
- const coverageOptions = coverage ? {
268
- enabled: true,
269
- clean: true,
270
- cleanOnRerun: true,
271
- reportOnFailure: true,
272
- reporter: [["html", {}], storybookCoverageReporter],
273
- reportsDirectory: resolvePathInStorybookCache(COVERAGE_DIRECTORY)
274
- } : { enabled: false };
275
- const vitestWorkspaceConfig = any(
276
- [
277
- ...VITEST_WORKSPACE_FILE_EXTENSION.map((ext) => `vitest.workspace.${ext}`),
278
- ...VITEST_CONFIG_FILE_EXTENSIONS.map((ext) => `vitest.config.${ext}`)
279
- ],
280
- { last: getProjectRoot() }
281
- );
282
- const projectName = "storybook:" + process.env.STORYBOOK_CONFIG_DIR;
283
- try {
284
- this.vitest = await createVitest("test", {
285
- root: vitestWorkspaceConfig ? dirname(vitestWorkspaceConfig) : process.cwd(),
286
- watch: true,
287
- passWithNoTests: false,
288
- project: [projectName],
289
- // TODO:
290
- // Do we want to enable Vite's default reporter?
291
- // The output in the terminal might be too spamy and it might be better to
292
- // find a way to just show errors and warnings for example
293
- // Otherwise it might be hard for the user to discover Storybook related logs
294
- reporters: ["default", new StorybookReporter(this.testManager)],
295
- coverage: coverageOptions
296
- });
297
- } catch (err) {
298
- const originalMessage = String(err.message);
299
- if (originalMessage.includes("Found multiple projects")) {
300
- const custom = [
301
- "Storybook was unable to start the test run because you have multiple Vitest projects (or browsers) in headed mode.",
302
- "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
- }
307
- }
308
- throw err;
309
- }
310
- if (this.vitest) {
311
- this.vitest.onCancel(() => {
312
- });
313
- }
314
- try {
315
- await this.vitest.init();
316
- } 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 += `
324
-
325
- Please install the @vitest/${coveragePackage} package to collect coverage
326
- `;
327
- }
328
- this.testManager.reportFatalError(message, e);
329
- return;
330
- }
331
- await this.setupWatchers();
332
- }
333
- async restartVitest({ coverage }) {
334
- await this.vitestRestartPromise;
335
- this.vitestRestartPromise = new Promise(async (resolve, reject) => {
336
- try {
337
- await this.runningPromise;
338
- await this.vitest?.close();
339
- await this.startVitest({ coverage });
340
- resolve();
341
- } catch (e) {
342
- reject(e);
343
- } finally {
344
- this.vitestRestartPromise = null;
345
- }
346
- });
347
- return this.vitestRestartPromise;
348
- }
349
- resetGlobalTestNamePattern() {
350
- this.vitest?.setGlobalTestNamePattern("");
351
- }
352
- updateLastChanged(filepath) {
353
- 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
- }
366
- });
367
- }
368
- async fetchStories(requestStoryIds) {
369
- const indexUrl = this.testManager.store.getState().indexUrl;
370
- if (!indexUrl) {
371
- throw new Error(
372
- "Tried to fetch stories to test, but the index URL was not set in the store yet."
373
- );
374
- }
375
- try {
376
- const index = await Promise.race([
377
- fetch(indexUrl).then((res) => res.json()),
378
- new Promise((_, reject) => setTimeout(reject, 3e3, new Error("Request took too long")))
379
- ]);
380
- const storyIds = requestStoryIds || Object.keys(index.entries);
381
- return storyIds.map((id) => index.entries[id]).filter((story) => story.type === "story");
382
- } catch (e) {
383
- log("Failed to fetch story index: " + e.message);
384
- return [];
385
- }
386
- }
387
- 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);
397
- }
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(
421
- ...filteredStories.filter((story) => !skip.some((tag) => story.tags?.includes(tag))).map((story) => story.id)
422
- );
423
- }
424
- return { filteredTestSpecifications, filteredStoryIds };
425
- }
426
- 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) {
446
- 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);
452
- if (isParentStory) {
453
- const parentName = getTestName(selectedStory.name);
454
- regex = new RegExp(`^${parentName}`);
455
- } else if (hasParentStory) {
456
- const parentStory = allStories.find((story) => story.id === selectedStory.parent);
457
- if (!parentStory) {
458
- throw new Error(`Parent story not found for story ${selectedStory.id}`);
459
- }
460
- const parentName = getTestName(parentStory.name);
461
- regex = new RegExp(`^${parentName} ${storyName}$`);
462
- } else {
463
- regex = new RegExp(`^${storyName}$`);
464
- }
465
- this.vitest.setGlobalTestNamePattern(regex);
466
- }
467
- const { filteredTestSpecifications, filteredStoryIds } = this.filterTestSpecifications(
468
- testSpecifications,
469
- filteredStories
470
- );
471
- this.testManager.store.setState((s) => ({
472
- ...s,
473
- currentRun: {
474
- ...s.currentRun,
475
- totalTestCount: filteredStoryIds.length
476
- }
477
- }));
478
- await this.vitest.runTestSpecifications(filteredTestSpecifications, true);
479
- this.resetGlobalTestNamePattern();
480
- }
481
- async cancelCurrentRun() {
482
- await this.vitest?.cancelCurrentRun("keyboard-input");
483
- await this.runningPromise;
484
- }
485
- async getStorybookTestSpecifications() {
486
- const globTestSpecifications = await this.vitest?.globTestSpecifications() ?? [];
487
- return globTestSpecifications.filter(
488
- (workspaceSpec) => this.isStorybookProject(workspaceSpec.project)
489
- ) ?? [];
490
- }
491
- 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) {
500
- return;
501
- }
502
- if (!this.vitest) {
503
- return;
504
- }
505
- 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(
514
- (project) => project.config.setupFiles.map((setupFile) => ({
515
- project,
516
- moduleId: setupFile
517
- }))
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(
524
- 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
- }
532
- })
533
- )).filter(Boolean);
534
- const testSpecificationsToRun = affectsGlobalFiles ? testSpecifications : affectedTestSpecifications;
535
- if (!testSpecificationsToRun.length) {
536
- return;
537
- }
538
- const { filteredTestSpecifications, filteredStoryIds } = this.filterTestSpecifications(
539
- testSpecificationsToRun,
540
- allStories
541
- );
542
- await this.testManager.runTestsWithState({
543
- storyIds: filteredStoryIds,
544
- triggeredBy: "watch",
545
- callback: /* @__PURE__ */ __name(async () => {
546
- this.testManager.store.setState((s) => ({
547
- ...s,
548
- currentRun: {
549
- ...s.currentRun,
550
- totalTestCount: filteredStoryIds.length
551
- }
552
- }));
553
- await this.vitest.cancelCurrentRun("keyboard-input");
554
- await this.runningPromise;
555
- await this.vitest.runTestSpecifications(filteredTestSpecifications, false);
556
- }, "callback")
557
- });
558
- }
559
- // This is an adaptation of Vitest's own implementation
560
- // see https://github.com/vitest-dev/vitest/blob/14409088166152c920ce7fa4ad4c0ba57149b869/packages/vitest/src/node/specifications.ts#L171-L198
561
- async getTestDependencies(spec) {
562
- const deps = /* @__PURE__ */ new Set();
563
- const addImports = /* @__PURE__ */ __name(async (project, filepath) => {
564
- if (deps.has(filepath)) {
565
- return;
566
- }
567
- 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) {
571
- return;
572
- }
573
- const dependencies = [...transformed.deps ?? [], ...transformed.dynamicDeps ?? []];
574
- await Promise.all(
575
- 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
- }
580
- })
581
- );
582
- }, "addImports");
583
- await addImports(spec.project, spec.moduleId);
584
- deps.delete(spec.moduleId);
585
- return deps;
586
- }
587
- async registerVitestConfigListener() {
588
- this.vitest.vite.watcher.on("change", async (file) => {
589
- const isConfig = normalize(file) === this.vitest?.vite?.config.configFile;
590
- if (isConfig) {
591
- log("Restarting Vitest due to config change");
592
- const { watching, config } = this.testManager.store.getState();
593
- await this.restartVitest({ coverage: config.coverage && !watching });
594
- }
595
- });
596
- }
597
- 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(
602
- "change",
603
- (file) => this.runAffectedTestsAfterChange(file, "change")
604
- );
605
- this.vitest.vite.watcher.on("add", (file) => {
606
- this.runAffectedTestsAfterChange(file, "add");
607
- });
608
- this.registerVitestConfigListener();
609
- }
610
- isStorybookProject(project) {
611
- return !!project.config.env?.__STORYBOOK_URL__;
612
- }
613
- };
614
-
615
- // src/node/test-manager.ts
616
- var testStateToStatusValueMap = {
617
- pending: "status-value:pending",
618
- passed: "status-value:success",
619
- warning: "status-value:warning",
620
- failed: "status-value:error",
621
- skipped: "status-value:unknown"
622
- };
623
- var TestManager = class _TestManager {
624
- constructor(options) {
625
- this.batchedTestCaseResults = [];
626
- /**
627
- * Throttled function to process batched test case results.
628
- *
629
- * This function:
630
- *
631
- * 1. Takes all batched test case results and clears the batch
632
- * 2. Updates the store state with new test counts (component tests and a11y tests)
633
- * 3. Adjusts the totalTestCount if more tests were run than initially anticipated
634
- * 4. Creates status objects for component tests and updates the component test status store
635
- * 5. Creates status objects for a11y tests (if any) and updates the a11y status store
636
- *
637
- * The throttling (500ms) is necessary as the channel would otherwise get overwhelmed with events,
638
- * eventually causing the manager and dev server to lose connection.
639
- */
640
- 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;
646
- 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
- }
660
- });
661
- });
662
- const finishedTestCount = ctSuccess + ctError;
663
- return {
664
- ...s,
665
- currentRun: {
666
- ...s.currentRun,
667
- componentTestCount: { success: ctSuccess, error: ctError },
668
- a11yCount: { success: a11ySuccess, warning: a11yWarning, error: a11yError },
669
- // in some cases successes and errors can exceed the anticipated totalTestCount
670
- // e.g. when testing more tests than the stories we know about upfront
671
- // in those cases, we set the totalTestCount to the sum of successes and errors
672
- totalTestCount: finishedTestCount > (s.currentRun.totalTestCount ?? 0) ? finishedTestCount : s.currentRun.totalTestCount
673
- }
674
- };
675
- });
676
- const componentTestStatuses = testCaseResultsToFlush.map(({ storyId, testResult }) => ({
677
- storyId,
678
- typeId: STATUS_TYPE_ID_COMPONENT_TEST,
679
- value: testStateToStatusValueMap[testResult.state],
680
- title: "Component tests",
681
- description: testResult.errors?.map((error) => error.stack || error.message).join("\n") ?? "",
682
- sidebarContextMenu: false
683
- }));
684
- this.componentTestStatusStore.set(componentTestStatuses);
685
- const a11yStatuses = testCaseResultsToFlush.flatMap(
686
- ({ storyId, reports }) => reports?.filter((r) => r.type === "a11y").map((a11yReport) => ({
687
- storyId,
688
- typeId: STATUS_TYPE_ID_A11Y,
689
- value: testStateToStatusValueMap[a11yReport.status],
690
- title: "Accessibility tests",
691
- description: "",
692
- sidebarContextMenu: false
693
- }))
694
- ).filter((a11yStatus) => a11yStatus !== void 0);
695
- if (a11yStatuses.length > 0) {
696
- this.a11yStatusStore.set(a11yStatuses);
697
- }
698
- }, 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) => {
711
- this.reportFatalError("Failed to start Vitest", e);
712
- });
713
- }
714
- static {
715
- __name(this, "TestManager");
716
- }
717
- async handleTriggerRunEvent(event) {
718
- await this.runTestsWithState({
719
- storyIds: event.payload.storyIds,
720
- triggeredBy: event.payload.triggeredBy,
721
- callback: /* @__PURE__ */ __name(async () => {
722
- try {
723
- await this.vitestManager.vitestRestartPromise;
724
- await this.vitestManager.runTests(event.payload);
725
- } catch (err) {
726
- this.reportFatalError("Failed to run tests", err);
727
- throw err;
728
- }
729
- }, "callback")
730
- });
731
- }
732
- async handleCancelEvent() {
733
- try {
734
- this.store.setState((s) => ({
735
- ...s,
736
- cancelling: true
737
- }));
738
- await this.vitestManager.cancelCurrentRun();
739
- } catch (err) {
740
- this.reportFatalError("Failed to cancel tests", err);
741
- } finally {
742
- this.store.setState((s) => ({
743
- ...s,
744
- cancelling: false
745
- }));
746
- }
747
- }
748
- async runTestsWithState({
749
- storyIds,
750
- triggeredBy,
751
- callback
752
- }) {
753
- this.componentTestStatusStore.unset(storyIds);
754
- this.a11yStatusStore.unset(storyIds);
755
- this.store.setState((s) => ({
756
- ...s,
757
- currentRun: {
758
- ...storeOptions.initialState.currentRun,
759
- triggeredBy,
760
- startedAt: Date.now(),
761
- storyIds,
762
- config: s.config
763
- }
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({
769
- type: "TEST_RUN_COMPLETED",
770
- payload: this.store.getState().currentRun
771
- });
772
- if (this.store.getState().currentRun.unhandledErrors.length > 0) {
773
- throw new Error("Tests completed but there are unhandled errors");
774
- }
775
- });
776
- }
777
- onTestModuleCollected(collectedTestCount) {
778
- this.store.setState((s) => ({
779
- ...s,
780
- currentRun: {
781
- ...s.currentRun,
782
- totalTestCount: (s.currentRun.totalTestCount ?? 0) + collectedTestCount
783
- }
784
- }));
785
- }
786
- onTestCaseResult(result) {
787
- const { storyId, testResult, reports } = result;
788
- if (!storyId) {
789
- return;
790
- }
791
- this.batchedTestCaseResults.push({ storyId, testResult, reports });
792
- this.throttledFlushTestCaseResults();
793
- }
794
- onTestRunEnd(endResult) {
795
- this.throttledFlushTestCaseResults.flush();
796
- this.store.setState((s) => ({
797
- ...s,
798
- currentRun: {
799
- ...s.currentRun,
800
- // when the test run is finished, we can set the totalTestCount to the actual number of tests run
801
- // this number can be lower than the total number of tests we anticipated upfront
802
- // e.g. when some tests where skipped without us knowing about it upfront
803
- totalTestCount: endResult.totalTestCount,
804
- unhandledErrors: endResult.unhandledErrors,
805
- finishedAt: Date.now()
806
- }
807
- }));
808
- }
809
- onCoverageCollected(coverageSummary) {
810
- this.store.setState((s) => ({
811
- ...s,
812
- currentRun: { ...s.currentRun, coverageSummary }
813
- }));
814
- }
815
- async reportFatalError(message, error) {
816
- await this.store.untilReady();
817
- this.store.send({
818
- type: "FATAL_ERROR",
819
- payload: {
820
- message,
821
- error: errorToErrorLike(error)
822
- }
823
- });
824
- }
825
- static async start(options) {
826
- return new Promise((resolve) => {
827
- const testManager = new _TestManager({
828
- ...options,
829
- onReady: /* @__PURE__ */ __name(() => {
830
- resolve(testManager);
831
- options.onReady?.();
832
- }, "onReady")
833
- });
834
- });
835
- }
836
- };
837
-
838
- // 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,
844
- transport: {
845
- send: /* @__PURE__ */ __name((event) => {
846
- process2.send?.(event);
847
- }, "send"),
848
- setHandler: /* @__PURE__ */ __name((handler) => {
849
- process2.on("message", handler);
850
- }, "setHandler")
851
- }
852
- });
853
- UniversalStore.__prepare(channel, UniversalStore.Environment.SERVER);
854
- var store = UniversalStore.create(storeOptions);
855
- new TestManager({
856
- store,
857
- componentTestStatusStore: getStatusStore(STATUS_TYPE_ID_COMPONENT_TEST),
858
- a11yStatusStore: getStatusStore(STATUS_TYPE_ID_A11Y),
859
- testProviderStore: getTestProviderStore(ADDON_ID),
860
- onReady: /* @__PURE__ */ __name(() => {
861
- process2.send?.({ type: "ready" });
862
- }, "onReady"),
863
- storybookOptions: {
864
- configDir: process2.env.STORYBOOK_CONFIG_DIR || ""
865
- }
866
- });
867
- var exit = /* @__PURE__ */ __name((code = 0) => {
868
- channel?.removeAllListeners();
869
- process2.exit(code);
870
- }, "exit");
871
- var createUnhandledErrorHandler = /* @__PURE__ */ __name((message) => async (error) => {
872
- try {
873
- const payload = {
874
- message,
875
- error: {
876
- message: error.message,
877
- name: error.name,
878
- stack: error.stack,
879
- cause: error.cause
880
- }
881
- };
882
- process2.send?.({
883
- type: "uncaught-error",
884
- payload
885
- });
886
- } finally {
887
- exit(1);
888
- }
889
- }, "createUnhandledErrorHandler");
890
- process2.on(
891
- "uncaughtException",
892
- createUnhandledErrorHandler("Uncaught exception in the test runner process")
893
- );
894
- process2.on(
895
- "unhandledRejection",
896
- createUnhandledErrorHandler("Unhandled rejection in the test runner process")
897
- );
898
- process2.on("exit", exit);
899
- process2.on("SIGINT", () => exit(0));
900
- process2.on("SIGTERM", () => exit(0));
20
+ Please install the @vitest/${isIstanbul?"coverage-istanbul":"coverage-v8"} package to collect coverage
21
+ `),this.testManager.reportFatalError(message,e);return}await this.setupWatchers();}async restartVitest({coverage}){return await this.vitestRestartPromise,this.vitestRestartPromise=new Promise(async(resolve2,reject)=>{try{await this.runningPromise,await this.vitest?.close(),await this.startVitest({coverage}),resolve2();}catch(e){reject(e);}finally{this.vitestRestartPromise=null;}}),this.vitestRestartPromise}resetGlobalTestNamePattern(){this.vitest?.setGlobalTestNamePattern("");}updateLastChanged(filepath){this.vitest.projects.forEach(({browser,vite,server})=>{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));});}async fetchStories(requestStoryIds){let indexUrl=this.testManager.store.getState().indexUrl;if(!indexUrl)throw new Error("Tried to fetch stories to test, but the index URL was not set in the store yet.");try{let index=await Promise.race([fetch(indexUrl).then(res=>res.json()),new Promise((_,reject)=>setTimeout(reject,3e3,new Error("Request took too long")))]);return (requestStoryIds||Object.keys(index.entries)).map(id=>index.entries[id]).filter(story=>story.type==="story")}catch(e){return log("Failed to fetch story index: "+e.message),[]}}filterTestSpecifications(testSpecifications,stories){let filteredTestSpecifications=[],filteredStoryIds=[],storiesByImportPath={};for(let story of stories){let absoluteImportPath=path3.join(process.cwd(),story.importPath);storiesByImportPath[absoluteImportPath]||(storiesByImportPath[absoluteImportPath]=[]),storiesByImportPath[absoluteImportPath].push(story);}for(let testSpecification of testSpecifications){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))));filteredStories.length&&(this.testManager.store.getState().watching||this.updateLastChanged(testSpecification.moduleId),filteredTestSpecifications.push(testSpecification),filteredStoryIds.push(...filteredStories.filter(story=>!skip.some(tag=>story.tags?.includes(tag))).map(story=>story.id)));}return {filteredTestSpecifications,filteredStoryIds}}async runTests(runPayload){let{watching,config}=this.testManager.store.getState(),coverageShouldBeEnabled=config.coverage&&!watching&&(runPayload?.storyIds?.length??0)===0,currentCoverage=this.vitest?.config.coverage?.enabled;this.vitest?currentCoverage!==coverageShouldBeEnabled?await this.restartVitest({coverage:coverageShouldBeEnabled}):await this.vitestRestartPromise:await this.startVitest({coverage:coverageShouldBeEnabled}),this.resetGlobalTestNamePattern(),await this.cancelCurrentRun();let testSpecifications=await this.getStorybookTestSpecifications(),stories=await this.fetchStories(runPayload?.storyIds);if(runPayload.storyIds?.length===1){let storyName=stories[0].name,regex=new RegExp(`^${storyName.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`);this.vitest.setGlobalTestNamePattern(regex);}let{filteredTestSpecifications,filteredStoryIds}=this.filterTestSpecifications(testSpecifications,stories);this.testManager.store.setState(s=>({...s,currentRun:{...s.currentRun,totalTestCount:filteredStoryIds.length}})),await this.vitest.runTestSpecifications(filteredTestSpecifications,!0),this.resetGlobalTestNamePattern();}async cancelCurrentRun(){await this.vitest?.cancelCurrentRun("keyboard-input"),await this.runningPromise;}async getStorybookTestSpecifications(){return (await this.vitest?.globTestSpecifications()??[]).filter(workspaceSpec=>this.isStorybookProject(workspaceSpec.project))??[]}async runAffectedTestsAfterChange(changedFilePath,event){let id=slash(changedFilePath);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)return;this.resetGlobalTestNamePattern();let storybookProject=this.vitest.projects.find(p=>this.isStorybookProject(p)),previewAnnotationSpecifications=this.testManager.store.getState().previewAnnotations.map(previewAnnotation=>({project:storybookProject??this.vitest.projects[0],moduleId:typeof previewAnnotation=="string"?previewAnnotation:previewAnnotation.absolute})),setupFilesSpecifications=this.vitest.projects.flatMap(project=>project.config.setupFiles.map(setupFile=>({project,moduleId:setupFile}))),syntheticGlobalTestSpecifications=previewAnnotationSpecifications.concat(setupFilesSpecifications),testSpecifications=await this.getStorybookTestSpecifications(),allStories=await this.fetchStories(),affectsGlobalFiles=!1,affectedTestSpecifications=(await Promise.all(syntheticGlobalTestSpecifications.concat(testSpecifications).map(async testSpecification=>{let dependencies=await this.getTestDependencies(testSpecification);if(changedFilePath===testSpecification.moduleId||dependencies.has(changedFilePath))return syntheticGlobalTestSpecifications.includes(testSpecification)&&(affectsGlobalFiles=!0),testSpecification}))).filter(Boolean),testSpecificationsToRun=affectsGlobalFiles?testSpecifications:affectedTestSpecifications;if(!testSpecificationsToRun.length)return;let{filteredTestSpecifications,filteredStoryIds}=this.filterTestSpecifications(testSpecificationsToRun,allStories);await this.testManager.runTestsWithState({storyIds:filteredStoryIds,triggeredBy:"watch",callback:async()=>{this.testManager.store.setState(s=>({...s,currentRun:{...s.currentRun,totalTestCount:filteredStoryIds.length}})),await this.vitest.cancelCurrentRun("keyboard-input"),await this.runningPromise,await this.vitest.runTestSpecifications(filteredTestSpecifications,!1);}});}async getTestDependencies(spec){let deps=new Set,addImports=async(project,filepath)=>{if(deps.has(filepath))return;deps.add(filepath);let transformed=project.vite.moduleGraph.getModuleById(filepath)?.ssrTransformResult||await project.vite.transformRequest(filepath,{ssr:!0});if(!transformed)return;let dependencies=[...transformed.deps??[],...transformed.dynamicDeps??[]];await Promise.all(dependencies.map(async dep=>{let fsPath=dep.startsWith("/@fs/")?dep.slice(process.platform==="win32"?5:4):join(project.config.root,dep);!fsPath.includes("node_modules")&&!deps.has(fsPath)&&fs.existsSync(fsPath)&&await addImports(project,fsPath);}));};return await addImports(spec.project,spec.moduleId),deps.delete(spec.moduleId),deps}async registerVitestConfigListener(){this.vitest.vite.watcher.on("change",async file=>{if(normalize(file)===this.vitest?.vite?.config.configFile){log("Restarting Vitest due to config change");let{watching,config}=this.testManager.store.getState();await this.restartVitest({coverage:config.coverage&&!watching});}});}async setupWatchers(){this.resetGlobalTestNamePattern(),this.vitest.vite.watcher.removeAllListeners("change"),this.vitest.vite.watcher.removeAllListeners("add"),this.vitest.vite.watcher.on("change",file=>this.runAffectedTestsAfterChange(file,"change")),this.vitest.vite.watcher.on("add",file=>{this.runAffectedTestsAfterChange(file,"add");}),this.registerVitestConfigListener();}isStorybookProject(project){return !!project.config.env?.__STORYBOOK_URL__}};var testStateToStatusValueMap={pending:"status-value:pending",passed:"status-value:success",warning:"status-value:warning",failed:"status-value:error",skipped:"status-value:unknown"},TestManager=class _TestManager{constructor(options){this.batchedTestCaseResults=[];this.throttledFlushTestCaseResults=throttle(()=>{let testCaseResultsToFlush=this.batchedTestCaseResults;this.batchedTestCaseResults=[],this.store.setState(s=>{let{success:ctSuccess,error:ctError}=s.currentRun.componentTestCount,{success:a11ySuccess,warning:a11yWarning,error:a11yError}=s.currentRun.a11yCount;testCaseResultsToFlush.forEach(({testResult,reports})=>{testResult.state==="passed"?ctSuccess++:testResult.state==="failed"&&ctError++,reports?.filter(r=>r.type==="a11y").forEach(report=>{report.status==="passed"?a11ySuccess++:report.status==="warning"?a11yWarning++:report.status==="failed"&&a11yError++;});});let finishedTestCount=ctSuccess+ctError;return {...s,currentRun:{...s.currentRun,componentTestCount:{success:ctSuccess,error:ctError},a11yCount:{success:a11ySuccess,warning:a11yWarning,error:a11yError},totalTestCount:finishedTestCount>(s.currentRun.totalTestCount??0)?finishedTestCount:s.currentRun.totalTestCount}}});let componentTestStatuses=testCaseResultsToFlush.map(({storyId,testResult})=>({storyId,typeId:STATUS_TYPE_ID_COMPONENT_TEST,value:testStateToStatusValueMap[testResult.state],title:"Component tests",description:testResult.errors?.map(error=>error.stack||error.message).join(`
22
+ `)??"",sidebarContextMenu:!1}));this.componentTestStatusStore.set(componentTestStatuses);let a11yStatuses=testCaseResultsToFlush.flatMap(({storyId,reports})=>reports?.filter(r=>r.type==="a11y").map(a11yReport=>({storyId,typeId:STATUS_TYPE_ID_A11Y,value:testStateToStatusValueMap[a11yReport.status],title:"Accessibility tests",description:"",sidebarContextMenu:!1}))).filter(a11yStatus=>a11yStatus!==void 0);a11yStatuses.length>0&&this.a11yStatusStore.set(a11yStatuses);},500);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=>{this.reportFatalError("Failed to start Vitest",e);});}async handleTriggerRunEvent(event){await this.runTestsWithState({storyIds:event.payload.storyIds,triggeredBy:event.payload.triggeredBy,callback:async()=>{try{await this.vitestManager.vitestRestartPromise,await this.vitestManager.runTests(event.payload);}catch(err){throw this.reportFatalError("Failed to run tests",err),err}}});}async handleCancelEvent(){try{this.store.setState(s=>({...s,cancelling:!0})),await this.vitestManager.cancelCurrentRun();}catch(err){this.reportFatalError("Failed to cancel tests",err);}finally{this.store.setState(s=>({...s,cancelling:!1}));}}async runTestsWithState({storyIds,triggeredBy,callback}){this.componentTestStatusStore.unset(storyIds),this.a11yStatusStore.unset(storyIds),this.store.setState(s=>({...s,currentRun:{...storeOptions.initialState.currentRun,triggeredBy,startedAt:Date.now(),storyIds,config:s.config}})),process.env.VITEST_STORYBOOK_CONFIG=JSON.stringify(this.store.getState().config),await this.testProviderStore.runWithState(async()=>{if(await callback(),this.store.send({type:"TEST_RUN_COMPLETED",payload:this.store.getState().currentRun}),this.store.getState().currentRun.unhandledErrors.length>0)throw new Error("Tests completed but there are unhandled errors")});}onTestModuleCollected(collectedTestCount){this.store.setState(s=>({...s,currentRun:{...s.currentRun,totalTestCount:(s.currentRun.totalTestCount??0)+collectedTestCount}}));}onTestCaseResult(result){let{storyId,testResult,reports}=result;storyId&&(this.batchedTestCaseResults.push({storyId,testResult,reports}),this.throttledFlushTestCaseResults());}onTestRunEnd(endResult){this.throttledFlushTestCaseResults.flush(),this.store.setState(s=>({...s,currentRun:{...s.currentRun,totalTestCount:endResult.totalTestCount,unhandledErrors:endResult.unhandledErrors,finishedAt:Date.now()}}));}onCoverageCollected(coverageSummary){this.store.setState(s=>({...s,currentRun:{...s.currentRun,coverageSummary}}));}async reportFatalError(message,error){await this.store.untilReady(),this.store.send({type:"FATAL_ERROR",payload:{message,error:errorToErrorLike(error)}});}static async start(options){return new Promise(resolve2=>{let testManager=new _TestManager({...options,onReady:()=>{resolve2(testManager),options.onReady?.();}});})}};var require2=module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('out.js', document.baseURI).href))),{experimental_UniversalStore:UniversalStore,experimental_getStatusStore:getStatusStore,experimental_getTestProviderStore:getTestProviderStore}=require2("storybook/internal/core-server"),channel=new channels.Channel({async:!0,transport:{send:event=>{process3__default.default.send?.(event);},setHandler:handler=>{process3__default.default.on("message",handler);}}});UniversalStore.__prepare(channel,UniversalStore.Environment.SERVER);var store=UniversalStore.create(storeOptions);new TestManager({store,componentTestStatusStore:getStatusStore(STATUS_TYPE_ID_COMPONENT_TEST),a11yStatusStore:getStatusStore(STATUS_TYPE_ID_A11Y),testProviderStore:getTestProviderStore(ADDON_ID2),onReady:()=>{process3__default.default.send?.({type:"ready"});},storybookOptions:{configDir:process3__default.default.env.STORYBOOK_CONFIG_DIR||""}});var exit=(code=0)=>{channel?.removeAllListeners(),process3__default.default.exit(code);},createUnhandledErrorHandler=message=>async error=>{try{let payload={message,error:{message:error.message,name:error.name,stack:error.stack,cause:error.cause}};process3__default.default.send?.({type:"uncaught-error",payload});}finally{exit(1);}};process3__default.default.on("uncaughtException",createUnhandledErrorHandler("Uncaught exception in the test runner process"));process3__default.default.on("unhandledRejection",createUnhandledErrorHandler("Unhandled rejection in the test runner process"));process3__default.default.on("exit",exit);process3__default.default.on("SIGINT",()=>exit(0));process3__default.default.on("SIGTERM",()=>exit(0));