@storybook/addon-vitest 9.0.0-rc.3 → 9.0.0-rc.4
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.
|
@@ -3,7 +3,7 @@ import { ReportBase, Visitor, ReportNode } from 'istanbul-lib-report';
|
|
|
3
3
|
import { ThrottledFunction } from './function/throttle.js';
|
|
4
4
|
import { TestResult } from 'vitest/dist/node.js';
|
|
5
5
|
import { experimental_UniversalStore } from 'storybook/internal/core-server';
|
|
6
|
-
import { API_HashEntry, PreviewAnnotation, StoryId, StatusStoreByTypeId, TestProviderStoreById } from 'storybook/internal/types';
|
|
6
|
+
import { API_HashEntry, PreviewAnnotation, StoryId, Options, StatusStoreByTypeId, TestProviderStoreById } from 'storybook/internal/types';
|
|
7
7
|
import { Report } from 'storybook/preview-api';
|
|
8
8
|
|
|
9
9
|
interface VitestError extends Error {
|
|
@@ -116,6 +116,7 @@ declare class VitestManager {
|
|
|
116
116
|
}
|
|
117
117
|
|
|
118
118
|
type TestManagerOptions = {
|
|
119
|
+
storybookOptions: Options;
|
|
119
120
|
store: experimental_UniversalStore<StoreState, StoreEvent>;
|
|
120
121
|
componentTestStatusStore: StatusStoreByTypeId;
|
|
121
122
|
a11yStatusStore: StatusStoreByTypeId;
|
|
@@ -130,6 +131,7 @@ declare class TestManager {
|
|
|
130
131
|
private a11yStatusStore;
|
|
131
132
|
private testProviderStore;
|
|
132
133
|
private onReady?;
|
|
134
|
+
storybookOptions: Options;
|
|
133
135
|
private batchedTestCaseResults;
|
|
134
136
|
constructor(options: TestManagerOptions);
|
|
135
137
|
handleTriggerRunEvent(event: TriggerRunEvent): Promise<void>;
|
package/dist/node/vitest.js
CHANGED
|
@@ -14,8 +14,9 @@ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
|
14
14
|
var process3__default = /*#__PURE__*/_interopDefault(process3);
|
|
15
15
|
var path2__default = /*#__PURE__*/_interopDefault(path2);
|
|
16
16
|
|
|
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,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:!1,cleanOnRerun:!1,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}`)]);this.vitest=await createVitest("test",{root:vitestWorkspaceConfig?dirname(vitestWorkspaceConfig):process.cwd(),watch:!0,passWithNoTests:!1,reporters:["default",new StorybookReporter(this.testManager)],coverage:coverageOptions}),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+=`
|
|
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:!1,cleanOnRerun:!1,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}`)]),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+=`
|
|
18
19
|
|
|
19
20
|
Please install the @vitest/${isIstanbul?"coverage-istanbul":"coverage-v8"} package to collect coverage
|
|
20
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.getModuleProjects(filepath).forEach(({server,browser})=>{server&&server.moduleGraph.getModulesByFile(filepath)?.forEach(mod=>server.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(`
|
|
21
|
-
`)??"",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.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"});}});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));
|
|
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));
|
package/dist/node/vitest.mjs
CHANGED
|
@@ -11,8 +11,9 @@ import { resolvePathInStorybookCache } from 'storybook/internal/common';
|
|
|
11
11
|
const __filename = fileURLToPath(import.meta.url);
|
|
12
12
|
dirname(__filename);
|
|
13
13
|
ESM_COMPAT_Module.createRequire(import.meta.url);
|
|
14
|
-
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,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,resolve,args)=>{activeCount++;let result=(async()=>fn(...args))();resolve(result);try{await result;}catch{}next();},enqueue=(fn,resolve,args)=>{queue.enqueue(run.bind(void 0,fn,resolve,args)),(async()=>(await Promise.resolve(),activeCount<concurrency&&queue.size>0&&queue.dequeue()()))();},generator=(fn,...args)=>new Promise(resolve=>{enqueue(fn,resolve,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?fileURLToPath(urlOrPath):urlOrPath;async function locatePath(paths,{cwd=process3.cwd(),type="file",allowSymlinks=!0,concurrency,preserveOrder}={}){checkType(type),cwd=toPath(cwd);let statFunction=allowSymlinks?promises.stat:promises.lstat;return pLocate(paths,async path_=>{try{let stat=await statFunction(path3.resolve(cwd,path_));return matchType(type,stat)}catch{return !1}},{concurrency,preserveOrder})}function toPath2(urlOrPath){return urlOrPath instanceof URL?fileURLToPath(urlOrPath):urlOrPath}var findUpStop=Symbol("findUpStop");async function findUpMultiple(name,options={}){let directory=path3.resolve(toPath2(options.cwd)??""),{root}=path3.parse(directory),stopAt=path3.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(path3.resolve(directory,foundPath)),directory===stopAt||matches.length>=limit))break;directory=path3.dirname(directory);}return matches}async function findUp(name,options={}){return (await findUpMultiple(name,{...options,limit:1}))[0]}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$1(__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:!1,cleanOnRerun:!1,reportOnFailure:!0,reporter:[["html",{}],storybookCoverageReporter],reportsDirectory: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}`)]);this.vitest=await createVitest("test",{root:vitestWorkspaceConfig?dirname$1(vitestWorkspaceConfig):process.cwd(),watch:!0,passWithNoTests:!1,reporters:["default",new StorybookReporter(this.testManager)],coverage:coverageOptions})
|
|
14
|
+
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,resolve,args)=>{activeCount++;let result=(async()=>fn(...args))();resolve(result);try{await result;}catch{}next();},enqueue=(fn,resolve,args)=>{queue.enqueue(run.bind(void 0,fn,resolve,args)),(async()=>(await Promise.resolve(),activeCount<concurrency&&queue.size>0&&queue.dequeue()()))();},generator=(fn,...args)=>new Promise(resolve=>{enqueue(fn,resolve,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?fileURLToPath(urlOrPath):urlOrPath;async function locatePath(paths,{cwd=process3.cwd(),type="file",allowSymlinks=!0,concurrency,preserveOrder}={}){checkType(type),cwd=toPath(cwd);let statFunction=allowSymlinks?promises.stat:promises.lstat;return pLocate(paths,async path_=>{try{let stat=await statFunction(path3.resolve(cwd,path_));return matchType(type,stat)}catch{return !1}},{concurrency,preserveOrder})}function toPath2(urlOrPath){return urlOrPath instanceof URL?fileURLToPath(urlOrPath):urlOrPath}var findUpStop=Symbol("findUpStop");async function findUpMultiple(name,options={}){let directory=path3.resolve(toPath2(options.cwd)??""),{root}=path3.parse(directory),stopAt=path3.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(path3.resolve(directory,foundPath)),directory===stopAt||matches.length>=limit))break;directory=path3.dirname(directory);}return matches}async function findUp(name,options={}){return (await findUpMultiple(name,{...options,limit:1}))[0]}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$1(__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:!1,cleanOnRerun:!1,reportOnFailure:!0,reporter:[["html",{}],storybookCoverageReporter],reportsDirectory: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}`)]),projectName="storybook:"+process.env.STORYBOOK_CONFIG_DIR;try{this.vitest=await createVitest("test",{root:vitestWorkspaceConfig?dirname$1(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(`
|
|
15
|
+
`);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+=`
|
|
15
16
|
|
|
16
17
|
Please install the @vitest/${isIstanbul?"coverage-istanbul":"coverage-v8"} package to collect coverage
|
|
17
18
|
`),this.testManager.reportFatalError(message,e);return}await this.setupWatchers();}async restartVitest({coverage}){return await this.vitestRestartPromise,this.vitestRestartPromise=new Promise(async(resolve,reject)=>{try{await this.runningPromise,await this.vitest?.close(),await this.startVitest({coverage}),resolve();}catch(e){reject(e);}finally{this.vitestRestartPromise=null;}}),this.vitestRestartPromise}resetGlobalTestNamePattern(){this.vitest?.setGlobalTestNamePattern("");}updateLastChanged(filepath){this.vitest.getModuleProjects(filepath).forEach(({server,browser})=>{server&&server.moduleGraph.getModulesByFile(filepath)?.forEach(mod=>server.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=path.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)&&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(`
|
|
18
|
-
`)??"",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.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(resolve=>{let testManager=new _TestManager({...options,onReady:()=>{resolve(testManager),options.onReady?.();}});})}};var require2=createRequire(import.meta.url),{experimental_UniversalStore:UniversalStore,experimental_getStatusStore:getStatusStore,experimental_getTestProviderStore:getTestProviderStore}=require2("storybook/internal/core-server"),channel=new Channel({async:!0,transport:{send:event=>{process3.send?.(event);},setHandler:handler=>{process3.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.send?.({type:"ready"});}});var exit=(code=0)=>{channel?.removeAllListeners(),process3.exit(code);},createUnhandledErrorHandler=message=>async error=>{try{let payload={message,error:{message:error.message,name:error.name,stack:error.stack,cause:error.cause}};process3.send?.({type:"uncaught-error",payload});}finally{exit(1);}};process3.on("uncaughtException",createUnhandledErrorHandler("Uncaught exception in the test runner process"));process3.on("unhandledRejection",createUnhandledErrorHandler("Unhandled rejection in the test runner process"));process3.on("exit",exit);process3.on("SIGINT",()=>exit(0));process3.on("SIGTERM",()=>exit(0));
|
|
19
|
+
`)??"",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(resolve=>{let testManager=new _TestManager({...options,onReady:()=>{resolve(testManager),options.onReady?.();}});})}};var require2=createRequire(import.meta.url),{experimental_UniversalStore:UniversalStore,experimental_getStatusStore:getStatusStore,experimental_getTestProviderStore:getTestProviderStore}=require2("storybook/internal/core-server"),channel=new Channel({async:!0,transport:{send:event=>{process3.send?.(event);},setHandler:handler=>{process3.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.send?.({type:"ready"});},storybookOptions:{configDir:process3.env.STORYBOOK_CONFIG_DIR||""}});var exit=(code=0)=>{channel?.removeAllListeners(),process3.exit(code);},createUnhandledErrorHandler=message=>async error=>{try{let payload={message,error:{message:error.message,name:error.name,stack:error.stack,cause:error.cause}};process3.send?.({type:"uncaught-error",payload});}finally{exit(1);}};process3.on("uncaughtException",createUnhandledErrorHandler("Uncaught exception in the test runner process"));process3.on("unhandledRejection",createUnhandledErrorHandler("Unhandled rejection in the test runner process"));process3.on("exit",exit);process3.on("SIGINT",()=>exit(0));process3.on("SIGTERM",()=>exit(0));
|
package/dist/preset.js
CHANGED
|
@@ -27,11 +27,11 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
27
27
|
${fromBody}`,toStringDescriptor=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),toStringName=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),changeToString=(to,from,name)=>{let withName=name===""?"":`with ${name.trim()}() `,newToString=wrappedToString.bind(null,withName,from.toString());Object.defineProperty(newToString,"name",toStringName),Object.defineProperty(to,"toString",{...toStringDescriptor,value:newToString});};function mimicFunction(to,from,{ignoreNonConfigurable=!1}={}){let{name}=to;for(let property of Reflect.ownKeys(from))copyProperty(to,from,property,ignoreNonConfigurable);return changePrototype(to,from),changeToString(to,from,name),to}var calledFunctions=new WeakMap,onetime=(function_,options={})=>{if(typeof function_!="function")throw new TypeError("Expected a function");let returnValue,callCount=0,functionName=function_.displayName||function_.name||"<anonymous>",onetime2=function(...arguments_){if(calledFunctions.set(onetime2,++callCount),callCount===1)returnValue=function_.apply(this,arguments_),function_=null;else if(options.throw===!0)throw new Error(`Function \`${functionName}\` can only be called once`);return returnValue};return mimicFunction(onetime2,function_),calledFunctions.set(onetime2,callCount),onetime2};onetime.callCount=function_=>{if(!calledFunctions.has(function_))throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`);return calledFunctions.get(function_)};var onetime_default=onetime;var getRealtimeSignals=()=>{let length=SIGRTMAX-SIGRTMIN+1;return Array.from({length},getRealtimeSignal)},getRealtimeSignal=(value,index)=>({name:`SIGRT${index+1}`,number:SIGRTMIN+index,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),SIGRTMIN=34,SIGRTMAX=64;var SIGNALS=[{name:"SIGHUP",number:1,action:"terminate",description:"Terminal closed",standard:"posix"},{name:"SIGINT",number:2,action:"terminate",description:"User interruption with CTRL-C",standard:"ansi"},{name:"SIGQUIT",number:3,action:"core",description:"User interruption with CTRL-\\",standard:"posix"},{name:"SIGILL",number:4,action:"core",description:"Invalid machine instruction",standard:"ansi"},{name:"SIGTRAP",number:5,action:"core",description:"Debugger breakpoint",standard:"posix"},{name:"SIGABRT",number:6,action:"core",description:"Aborted",standard:"ansi"},{name:"SIGIOT",number:6,action:"core",description:"Aborted",standard:"bsd"},{name:"SIGBUS",number:7,action:"core",description:"Bus error due to misaligned, non-existing address or paging error",standard:"bsd"},{name:"SIGEMT",number:7,action:"terminate",description:"Command should be emulated but is not implemented",standard:"other"},{name:"SIGFPE",number:8,action:"core",description:"Floating point arithmetic error",standard:"ansi"},{name:"SIGKILL",number:9,action:"terminate",description:"Forced termination",standard:"posix",forced:!0},{name:"SIGUSR1",number:10,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGSEGV",number:11,action:"core",description:"Segmentation fault",standard:"ansi"},{name:"SIGUSR2",number:12,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGPIPE",number:13,action:"terminate",description:"Broken pipe or socket",standard:"posix"},{name:"SIGALRM",number:14,action:"terminate",description:"Timeout or timer",standard:"posix"},{name:"SIGTERM",number:15,action:"terminate",description:"Termination",standard:"ansi"},{name:"SIGSTKFLT",number:16,action:"terminate",description:"Stack is empty or overflowed",standard:"other"},{name:"SIGCHLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"posix"},{name:"SIGCLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"other"},{name:"SIGCONT",number:18,action:"unpause",description:"Unpaused",standard:"posix",forced:!0},{name:"SIGSTOP",number:19,action:"pause",description:"Paused",standard:"posix",forced:!0},{name:"SIGTSTP",number:20,action:"pause",description:'Paused using CTRL-Z or "suspend"',standard:"posix"},{name:"SIGTTIN",number:21,action:"pause",description:"Background process cannot read terminal input",standard:"posix"},{name:"SIGBREAK",number:21,action:"terminate",description:"User interruption with CTRL-BREAK",standard:"other"},{name:"SIGTTOU",number:22,action:"pause",description:"Background process cannot write to terminal output",standard:"posix"},{name:"SIGURG",number:23,action:"ignore",description:"Socket received out-of-band data",standard:"bsd"},{name:"SIGXCPU",number:24,action:"core",description:"Process timed out",standard:"bsd"},{name:"SIGXFSZ",number:25,action:"core",description:"File too big",standard:"bsd"},{name:"SIGVTALRM",number:26,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGPROF",number:27,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGWINCH",number:28,action:"ignore",description:"Terminal window size changed",standard:"bsd"},{name:"SIGIO",number:29,action:"terminate",description:"I/O is available",standard:"other"},{name:"SIGPOLL",number:29,action:"terminate",description:"Watched event",standard:"other"},{name:"SIGINFO",number:29,action:"ignore",description:"Request for process information",standard:"other"},{name:"SIGPWR",number:30,action:"terminate",description:"Device running out of power",standard:"systemv"},{name:"SIGSYS",number:31,action:"core",description:"Invalid system call",standard:"other"},{name:"SIGUNUSED",number:31,action:"terminate",description:"Invalid system call",standard:"other"}];var getSignals=()=>{let realtimeSignals=getRealtimeSignals();return [...SIGNALS,...realtimeSignals].map(normalizeSignal)},normalizeSignal=({name,number:defaultNumber,description,action,forced=!1,standard})=>{let{signals:{[name]:constantSignal}}=os.constants,supported=constantSignal!==void 0;return {name,number:supported?constantSignal:defaultNumber,description,supported,action,forced,standard}};var getSignalsByName=()=>{let signals2=getSignals();return Object.fromEntries(signals2.map(getSignalByName))},getSignalByName=({name,number,description,supported,action,forced,standard})=>[name,{name,number,description,supported,action,forced,standard}],signalsByName=getSignalsByName(),getSignalsByNumber=()=>{let signals2=getSignals(),length=65,signalsA=Array.from({length},(value,number)=>getSignalByNumber(number,signals2));return Object.assign({},...signalsA)},getSignalByNumber=(number,signals2)=>{let signal=findSignalByNumber(number,signals2);if(signal===void 0)return {};let{name,description,supported,action,forced,standard}=signal;return {[number]:{name,number,description,supported,action,forced,standard}}},findSignalByNumber=(number,signals2)=>{let signal=signals2.find(({name})=>os.constants.signals[name]===number);return signal!==void 0?signal:signals2.find(signalA=>signalA.number===number)};getSignalsByNumber();var getErrorPrefix=({timedOut,timeout,errorCode,signal,signalDescription,exitCode,isCanceled})=>timedOut?`timed out after ${timeout} milliseconds`:isCanceled?"was canceled":errorCode!==void 0?`failed with ${errorCode}`:signal!==void 0?`was killed with ${signal} (${signalDescription})`:exitCode!==void 0?`failed with exit code ${exitCode}`:"failed",makeError=({stdout,stderr,all,error,signal,exitCode,command,escapedCommand,timedOut,isCanceled,killed,parsed:{options:{timeout,cwd=process6__default.default.cwd()}}})=>{exitCode=exitCode===null?void 0:exitCode,signal=signal===null?void 0:signal;let signalDescription=signal===void 0?void 0:signalsByName[signal].description,errorCode=error&&error.code,execaMessage=`Command ${getErrorPrefix({timedOut,timeout,errorCode,signal,signalDescription,exitCode,isCanceled})}: ${command}`,isError=Object.prototype.toString.call(error)==="[object Error]",shortMessage=isError?`${execaMessage}
|
|
28
28
|
${error.message}`:execaMessage,message=[shortMessage,stderr,stdout].filter(Boolean).join(`
|
|
29
29
|
`);return isError?(error.originalMessage=error.message,error.message=message):error=new Error(message),error.shortMessage=shortMessage,error.command=command,error.escapedCommand=escapedCommand,error.exitCode=exitCode,error.signal=signal,error.signalDescription=signalDescription,error.stdout=stdout,error.stderr=stderr,error.cwd=cwd,all!==void 0&&(error.all=all),"bufferedData"in error&&delete error.bufferedData,error.failed=!0,error.timedOut=!!timedOut,error.isCanceled=isCanceled,error.killed=killed&&!timedOut,error};var aliases=["stdin","stdout","stderr"],hasAlias=options=>aliases.some(alias=>options[alias]!==void 0),normalizeStdio=options=>{if(!options)return;let{stdio}=options;if(stdio===void 0)return aliases.map(alias=>options[alias]);if(hasAlias(options))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${aliases.map(alias=>`\`${alias}\``).join(", ")}`);if(typeof stdio=="string")return stdio;if(!Array.isArray(stdio))throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``);let length=Math.max(stdio.length,aliases.length);return Array.from({length},(value,index)=>stdio[index])},normalizeStdioNode=options=>{let stdio=normalizeStdio(options);return stdio==="ipc"?"ipc":stdio===void 0||typeof stdio=="string"?[stdio,stdio,stdio,"ipc"]:stdio.includes("ipc")?stdio:[...stdio,"ipc"]};var signals=[];signals.push("SIGHUP","SIGINT","SIGTERM");process.platform!=="win32"&&signals.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&signals.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var processOk=process7=>!!process7&&typeof process7=="object"&&typeof process7.removeListener=="function"&&typeof process7.emit=="function"&&typeof process7.reallyExit=="function"&&typeof process7.listeners=="function"&&typeof process7.kill=="function"&&typeof process7.pid=="number"&&typeof process7.on=="function",kExitEmitter=Symbol.for("signal-exit emitter"),global2=globalThis,ObjectDefineProperty=Object.defineProperty.bind(Object),Emitter=class{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(global2[kExitEmitter])return global2[kExitEmitter];ObjectDefineProperty(global2,kExitEmitter,{value:this,writable:!1,enumerable:!1,configurable:!1});}on(ev,fn){this.listeners[ev].push(fn);}removeListener(ev,fn){let list=this.listeners[ev],i=list.indexOf(fn);i!==-1&&(i===0&&list.length===1?list.length=0:list.splice(i,1));}emit(ev,code,signal){if(this.emitted[ev])return !1;this.emitted[ev]=!0;let ret=!1;for(let fn of this.listeners[ev])ret=fn(code,signal)===!0||ret;return ev==="exit"&&(ret=this.emit("afterExit",code,signal)||ret),ret}},SignalExitBase=class{},signalExitWrap=handler=>({onExit(cb,opts){return handler.onExit(cb,opts)},load(){return handler.load()},unload(){return handler.unload()}}),SignalExitFallback=class extends SignalExitBase{onExit(){return ()=>{}}load(){}unload(){}},SignalExit=class extends SignalExitBase{#hupSig=process4.platform==="win32"?"SIGINT":"SIGHUP";#emitter=new Emitter;#process;#originalProcessEmit;#originalProcessReallyExit;#sigListeners={};#loaded=!1;constructor(process7){super(),this.#process=process7,this.#sigListeners={};for(let sig of signals)this.#sigListeners[sig]=()=>{let listeners=this.#process.listeners(sig),{count}=this.#emitter,p=process7;if(typeof p.__signal_exit_emitter__=="object"&&typeof p.__signal_exit_emitter__.count=="number"&&(count+=p.__signal_exit_emitter__.count),listeners.length===count){this.unload();let ret=this.#emitter.emit("exit",null,sig),s=sig==="SIGHUP"?this.#hupSig:sig;ret||process7.kill(process7.pid,s);}};this.#originalProcessReallyExit=process7.reallyExit,this.#originalProcessEmit=process7.emit;}onExit(cb,opts){if(!processOk(this.#process))return ()=>{};this.#loaded===!1&&this.load();let ev=opts?.alwaysLast?"afterExit":"exit";return this.#emitter.on(ev,cb),()=>{this.#emitter.removeListener(ev,cb),this.#emitter.listeners.exit.length===0&&this.#emitter.listeners.afterExit.length===0&&this.unload();}}load(){if(!this.#loaded){this.#loaded=!0,this.#emitter.count+=1;for(let sig of signals)try{let fn=this.#sigListeners[sig];fn&&this.#process.on(sig,fn);}catch{}this.#process.emit=(ev,...a)=>this.#processEmit(ev,...a),this.#process.reallyExit=code=>this.#processReallyExit(code);}}unload(){this.#loaded&&(this.#loaded=!1,signals.forEach(sig=>{let listener=this.#sigListeners[sig];if(!listener)throw new Error("Listener not defined for signal: "+sig);try{this.#process.removeListener(sig,listener);}catch{}}),this.#process.emit=this.#originalProcessEmit,this.#process.reallyExit=this.#originalProcessReallyExit,this.#emitter.count-=1);}#processReallyExit(code){return processOk(this.#process)?(this.#process.exitCode=code||0,this.#emitter.emit("exit",this.#process.exitCode,null),this.#originalProcessReallyExit.call(this.#process,this.#process.exitCode)):0}#processEmit(ev,...args){let og=this.#originalProcessEmit;if(ev==="exit"&&processOk(this.#process)){typeof args[0]=="number"&&(this.#process.exitCode=args[0]);let ret=og.call(this.#process,ev,...args);return this.#emitter.emit("exit",this.#process.exitCode,null),ret}else return og.call(this.#process,ev,...args)}},process4=globalThis.process,{onExit,load,unload}=signalExitWrap(processOk(process4)?new SignalExit(process4):new SignalExitFallback);var DEFAULT_FORCE_KILL_TIMEOUT=1e3*5,spawnedKill=(kill,signal="SIGTERM",options={})=>{let killResult=kill(signal);return setKillTimeout(kill,signal,options,killResult),killResult},setKillTimeout=(kill,signal,options,killResult)=>{if(!shouldForceKill(signal,options,killResult))return;let timeout=getForceKillAfterTimeout(options),t=setTimeout(()=>{kill("SIGKILL");},timeout);t.unref&&t.unref();},shouldForceKill=(signal,{forceKillAfterTimeout},killResult)=>isSigterm(signal)&&forceKillAfterTimeout!==!1&&killResult,isSigterm=signal=>signal===os__default.default.constants.signals.SIGTERM||typeof signal=="string"&&signal.toUpperCase()==="SIGTERM",getForceKillAfterTimeout=({forceKillAfterTimeout=!0})=>{if(forceKillAfterTimeout===!0)return DEFAULT_FORCE_KILL_TIMEOUT;if(!Number.isFinite(forceKillAfterTimeout)||forceKillAfterTimeout<0)throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${forceKillAfterTimeout}\` (${typeof forceKillAfterTimeout})`);return forceKillAfterTimeout},spawnedCancel=(spawned,context)=>{spawned.kill()&&(context.isCanceled=!0);},timeoutKill=(spawned,signal,reject)=>{spawned.kill(signal),reject(Object.assign(new Error("Timed out"),{timedOut:!0,signal}));},setupTimeout=(spawned,{timeout,killSignal="SIGTERM"},spawnedPromise)=>{if(timeout===0||timeout===void 0)return spawnedPromise;let timeoutId,timeoutPromise=new Promise((resolve2,reject)=>{timeoutId=setTimeout(()=>{timeoutKill(spawned,killSignal,reject);},timeout);}),safeSpawnedPromise=spawnedPromise.finally(()=>{clearTimeout(timeoutId);});return Promise.race([timeoutPromise,safeSpawnedPromise])},validateTimeout=({timeout})=>{if(timeout!==void 0&&(!Number.isFinite(timeout)||timeout<0))throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`)},setExitHandler=async(spawned,{cleanup,detached},timedPromise)=>{if(!cleanup||detached)return timedPromise;let removeExitHandler=onExit(()=>{spawned.kill();});return timedPromise.finally(()=>{removeExitHandler();})};function isStream(stream){return stream!==null&&typeof stream=="object"&&typeof stream.pipe=="function"}function isWritableStream(stream){return isStream(stream)&&stream.writable!==!1&&typeof stream._write=="function"&&typeof stream._writableState=="object"}var isExecaChildProcess=target=>target instanceof childProcess.ChildProcess&&typeof target.then=="function",pipeToTarget=(spawned,streamName,target)=>{if(typeof target=="string")return spawned[streamName].pipe(fs.createWriteStream(target)),spawned;if(isWritableStream(target))return spawned[streamName].pipe(target),spawned;if(!isExecaChildProcess(target))throw new TypeError("The second argument must be a string, a stream or an Execa child process.");if(!isWritableStream(target.stdin))throw new TypeError("The target child process's stdin must be available.");return spawned[streamName].pipe(target.stdin),target},addPipeMethods=spawned=>{spawned.stdout!==null&&(spawned.pipeStdout=pipeToTarget.bind(void 0,spawned,"stdout")),spawned.stderr!==null&&(spawned.pipeStderr=pipeToTarget.bind(void 0,spawned,"stderr")),spawned.all!==void 0&&(spawned.pipeAll=pipeToTarget.bind(void 0,spawned,"all"));};var getStreamContents=async(stream,{init,convertChunk,getSize,truncateChunk,addChunk,getFinalChunk,finalize},{maxBuffer=Number.POSITIVE_INFINITY}={})=>{if(!isAsyncIterable(stream))throw new Error("The first argument must be a Readable, a ReadableStream, or an async iterable.");let state=init();state.length=0;try{for await(let chunk of stream){let chunkType=getChunkType(chunk),convertedChunk=convertChunk[chunkType](chunk,state);appendChunk({convertedChunk,state,getSize,truncateChunk,addChunk,maxBuffer});}return appendFinalChunk({state,convertChunk,getSize,truncateChunk,addChunk,getFinalChunk,maxBuffer}),finalize(state)}catch(error){throw error.bufferedData=finalize(state),error}},appendFinalChunk=({state,getSize,truncateChunk,addChunk,getFinalChunk,maxBuffer})=>{let convertedChunk=getFinalChunk(state);convertedChunk!==void 0&&appendChunk({convertedChunk,state,getSize,truncateChunk,addChunk,maxBuffer});},appendChunk=({convertedChunk,state,getSize,truncateChunk,addChunk,maxBuffer})=>{let chunkSize=getSize(convertedChunk),newLength=state.length+chunkSize;if(newLength<=maxBuffer){addNewChunk(convertedChunk,state,addChunk,newLength);return}let truncatedChunk=truncateChunk(convertedChunk,maxBuffer-state.length);throw truncatedChunk!==void 0&&addNewChunk(truncatedChunk,state,addChunk,maxBuffer),new MaxBufferError},addNewChunk=(convertedChunk,state,addChunk,newLength)=>{state.contents=addChunk(convertedChunk,state,newLength),state.length=newLength;},isAsyncIterable=stream=>typeof stream=="object"&&stream!==null&&typeof stream[Symbol.asyncIterator]=="function",getChunkType=chunk=>{let typeOfChunk=typeof chunk;if(typeOfChunk==="string")return "string";if(typeOfChunk!=="object"||chunk===null)return "others";if(globalThis.Buffer?.isBuffer(chunk))return "buffer";let prototypeName=objectToString.call(chunk);return prototypeName==="[object ArrayBuffer]"?"arrayBuffer":prototypeName==="[object DataView]"?"dataView":Number.isInteger(chunk.byteLength)&&Number.isInteger(chunk.byteOffset)&&objectToString.call(chunk.buffer)==="[object ArrayBuffer]"?"typedArray":"others"},{toString:objectToString}=Object.prototype,MaxBufferError=class extends Error{name="MaxBufferError";constructor(){super("maxBuffer exceeded");}};var identity=value=>value,noop2=()=>{},getContentsProp=({contents})=>contents,throwObjectStream=chunk=>{throw new Error(`Streams in object mode are not supported: ${String(chunk)}`)},getLengthProp=convertedChunk=>convertedChunk.length;async function getStreamAsArrayBuffer(stream,options){return getStreamContents(stream,arrayBufferMethods,options)}var initArrayBuffer=()=>({contents:new ArrayBuffer(0)}),useTextEncoder=chunk=>textEncoder.encode(chunk),textEncoder=new TextEncoder,useUint8Array=chunk=>new Uint8Array(chunk),useUint8ArrayWithOffset=chunk=>new Uint8Array(chunk.buffer,chunk.byteOffset,chunk.byteLength),truncateArrayBufferChunk=(convertedChunk,chunkSize)=>convertedChunk.slice(0,chunkSize),addArrayBufferChunk=(convertedChunk,{contents,length:previousLength},length)=>{let newContents=hasArrayBufferResize()?resizeArrayBuffer(contents,length):resizeArrayBufferSlow(contents,length);return new Uint8Array(newContents).set(convertedChunk,previousLength),newContents},resizeArrayBufferSlow=(contents,length)=>{if(length<=contents.byteLength)return contents;let arrayBuffer=new ArrayBuffer(getNewContentsLength(length));return new Uint8Array(arrayBuffer).set(new Uint8Array(contents),0),arrayBuffer},resizeArrayBuffer=(contents,length)=>{if(length<=contents.maxByteLength)return contents.resize(length),contents;let arrayBuffer=new ArrayBuffer(length,{maxByteLength:getNewContentsLength(length)});return new Uint8Array(arrayBuffer).set(new Uint8Array(contents),0),arrayBuffer},getNewContentsLength=length=>SCALE_FACTOR**Math.ceil(Math.log(length)/Math.log(SCALE_FACTOR)),SCALE_FACTOR=2,finalizeArrayBuffer=({contents,length})=>hasArrayBufferResize()?contents:contents.slice(0,length),hasArrayBufferResize=()=>"resize"in ArrayBuffer.prototype,arrayBufferMethods={init:initArrayBuffer,convertChunk:{string:useTextEncoder,buffer:useUint8Array,arrayBuffer:useUint8Array,dataView:useUint8ArrayWithOffset,typedArray:useUint8ArrayWithOffset,others:throwObjectStream},getSize:getLengthProp,truncateChunk:truncateArrayBufferChunk,addChunk:addArrayBufferChunk,getFinalChunk:noop2,finalize:finalizeArrayBuffer};async function getStreamAsBuffer(stream,options){if(!("Buffer"in globalThis))throw new Error("getStreamAsBuffer() is only supported in Node.js");try{return arrayBufferToNodeBuffer(await getStreamAsArrayBuffer(stream,options))}catch(error){throw error.bufferedData!==void 0&&(error.bufferedData=arrayBufferToNodeBuffer(error.bufferedData)),error}}var arrayBufferToNodeBuffer=arrayBuffer=>globalThis.Buffer.from(arrayBuffer);async function getStreamAsString(stream,options){return getStreamContents(stream,stringMethods,options)}var initString=()=>({contents:"",textDecoder:new TextDecoder}),useTextDecoder=(chunk,{textDecoder})=>textDecoder.decode(chunk,{stream:!0}),addStringChunk=(convertedChunk,{contents})=>contents+convertedChunk,truncateStringChunk=(convertedChunk,chunkSize)=>convertedChunk.slice(0,chunkSize),getFinalStringChunk=({textDecoder})=>{let finalChunk=textDecoder.decode();return finalChunk===""?void 0:finalChunk},stringMethods={init:initString,convertChunk:{string:identity,buffer:useTextDecoder,arrayBuffer:useTextDecoder,dataView:useTextDecoder,typedArray:useTextDecoder,others:throwObjectStream},getSize:getLengthProp,truncateChunk:truncateStringChunk,addChunk:addStringChunk,getFinalChunk:getFinalStringChunk,finalize:getContentsProp};var import_merge_stream=__toESM(require_merge_stream(),1),validateInputOptions=input=>{if(input!==void 0)throw new TypeError("The `input` and `inputFile` options cannot be both set.")},getInput=({input,inputFile})=>typeof inputFile!="string"?input:(validateInputOptions(input),fs.createReadStream(inputFile)),handleInput=(spawned,options)=>{let input=getInput(options);input!==void 0&&(isStream(input)?input.pipe(spawned.stdin):spawned.stdin.end(input));},makeAllStream=(spawned,{all})=>{if(!all||!spawned.stdout&&!spawned.stderr)return;let mixed=(0, import_merge_stream.default)();return spawned.stdout&&mixed.add(spawned.stdout),spawned.stderr&&mixed.add(spawned.stderr),mixed},getBufferedData=async(stream,streamPromise)=>{if(!(!stream||streamPromise===void 0)){await promises$1.setTimeout(0),stream.destroy();try{return await streamPromise}catch(error){return error.bufferedData}}},getStreamPromise=(stream,{encoding,buffer,maxBuffer})=>{if(!(!stream||!buffer))return encoding==="utf8"||encoding==="utf-8"?getStreamAsString(stream,{maxBuffer}):encoding===null||encoding==="buffer"?getStreamAsBuffer(stream,{maxBuffer}):applyEncoding(stream,maxBuffer,encoding)},applyEncoding=async(stream,maxBuffer,encoding)=>(await getStreamAsBuffer(stream,{maxBuffer})).toString(encoding),getSpawnedResult=async({stdout,stderr,all},{encoding,buffer,maxBuffer},processDone)=>{let stdoutPromise=getStreamPromise(stdout,{encoding,buffer,maxBuffer}),stderrPromise=getStreamPromise(stderr,{encoding,buffer,maxBuffer}),allPromise=getStreamPromise(all,{encoding,buffer,maxBuffer:maxBuffer*2});try{return await Promise.all([processDone,stdoutPromise,stderrPromise,allPromise])}catch(error){return Promise.all([{error,signal:error.signal,timedOut:error.timedOut},getBufferedData(stdout,stdoutPromise),getBufferedData(stderr,stderrPromise),getBufferedData(all,allPromise)])}};var nativePromisePrototype=(async()=>{})().constructor.prototype,descriptors=["then","catch","finally"].map(property=>[property,Reflect.getOwnPropertyDescriptor(nativePromisePrototype,property)]),mergePromise=(spawned,promise)=>{for(let[property,descriptor]of descriptors){let value=typeof promise=="function"?(...args)=>Reflect.apply(descriptor.value,promise(),args):descriptor.value.bind(promise);Reflect.defineProperty(spawned,property,{...descriptor,value});}},getSpawnedPromise=spawned=>new Promise((resolve2,reject)=>{spawned.on("exit",(exitCode,signal)=>{resolve2({exitCode,signal});}),spawned.on("error",error=>{reject(error);}),spawned.stdin&&spawned.stdin.on("error",error=>{reject(error);});});var normalizeArgs=(file,args=[])=>Array.isArray(args)?[file,...args]:[file],NO_ESCAPE_REGEXP=/^[\w.-]+$/,escapeArg=arg=>typeof arg!="string"||NO_ESCAPE_REGEXP.test(arg)?arg:`"${arg.replaceAll('"','\\"')}"`,joinCommand=(file,args)=>normalizeArgs(file,args).join(" "),getEscapedCommand=(file,args)=>normalizeArgs(file,args).map(arg=>escapeArg(arg)).join(" ");var verboseDefault=util.debuglog("execa").enabled,padField=(field,padding)=>String(field).padStart(padding,"0"),getTimestamp=()=>{let date=new Date;return `${padField(date.getHours(),2)}:${padField(date.getMinutes(),2)}:${padField(date.getSeconds(),2)}.${padField(date.getMilliseconds(),3)}`},logCommand=(escapedCommand,{verbose})=>{verbose&&process6__default.default.stderr.write(`[${getTimestamp()}] ${escapedCommand}
|
|
30
|
-
`);};var DEFAULT_MAX_BUFFER=1e3*1e3*100,getEnv=({env:envOption,extendEnv,preferLocal,localDir,execPath})=>{let env=extendEnv?{...process6__default.default.env,...envOption}:envOption;return preferLocal?npmRunPathEnv({env,cwd:localDir,execPath}):env},handleArguments=(file,args,options={})=>{let parsed=import_cross_spawn.default._parse(file,args,options);return file=parsed.command,args=parsed.args,options=parsed.options,options={maxBuffer:DEFAULT_MAX_BUFFER,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:options.cwd||process6__default.default.cwd(),execPath:process6__default.default.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:verboseDefault,...options},options.env=getEnv(options),options.stdio=normalizeStdio(options),process6__default.default.platform==="win32"&&path__default.default.basename(file,".exe")==="cmd"&&args.unshift("/q"),{file,args,options,parsed}},handleOutput=(options,value,error)=>typeof value!="string"&&!buffer.Buffer.isBuffer(value)?error===void 0?void 0:"":options.stripFinalNewline?stripFinalNewline(value):value;function execa(file,args,options){let parsed=handleArguments(file,args,options),command=joinCommand(file,args),escapedCommand=getEscapedCommand(file,args);logCommand(escapedCommand,parsed.options),validateTimeout(parsed.options);let spawned;try{spawned=childProcess__default.default.spawn(parsed.file,parsed.args,parsed.options);}catch(error){let dummySpawned=new childProcess__default.default.ChildProcess,errorPromise=Promise.reject(makeError({error,stdout:"",stderr:"",all:"",command,escapedCommand,parsed,timedOut:!1,isCanceled:!1,killed:!1}));return mergePromise(dummySpawned,errorPromise),dummySpawned}let spawnedPromise=getSpawnedPromise(spawned),timedPromise=setupTimeout(spawned,parsed.options,spawnedPromise),processDone=setExitHandler(spawned,parsed.options,timedPromise),context={isCanceled:!1};spawned.kill=spawnedKill.bind(null,spawned.kill.bind(spawned)),spawned.cancel=spawnedCancel.bind(null,spawned,context);let handlePromiseOnce=onetime_default(async()=>{let[{error,exitCode,signal,timedOut},stdoutResult,stderrResult,allResult]=await getSpawnedResult(spawned,parsed.options,processDone),stdout=handleOutput(parsed.options,stdoutResult),stderr=handleOutput(parsed.options,stderrResult),all=handleOutput(parsed.options,allResult);if(error||exitCode!==0||signal!==null){let returnedError=makeError({error,exitCode,signal,stdout,stderr,all,command,escapedCommand,parsed,timedOut,isCanceled:(parsed.options.signal?parsed.options.signal.aborted:!1),killed:spawned.killed});if(!parsed.options.reject)return returnedError;throw returnedError}return {command,escapedCommand,exitCode:0,stdout,stderr,all,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}});return handleInput(spawned,parsed.options),spawned.all=makeAllStream(spawned,parsed.options),addPipeMethods(spawned),mergePromise(spawned,handlePromiseOnce),spawned}function execaNode(scriptPath,args,options={}){args&&!Array.isArray(args)&&typeof args=="object"&&(options=args,args=[]);let stdio=normalizeStdioNode(options),defaultExecArgv=process6__default.default.execArgv.filter(arg=>!arg.startsWith("--inspect")),{nodePath=process6__default.default.execPath,nodeOptions=defaultExecArgv}=options;return execa(nodePath,[...nodeOptions,scriptPath,...Array.isArray(args)?args:[]],{...options,stdin:void 0,stdout:void 0,stderr:void 0,stdio,shell:!1})}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]:$/;var 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 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)};var MAX_START_TIME=3e4,vitestModulePath=join(__dirname,"node","vitest.mjs"),eventQueue=[],child,ready=!1,unsubscribeStore,unsubscribeStatusStore,unsubscribeTestProviderStore,forwardUniversalStoreEvent=storeEventName=>(event,eventInfo)=>{child?.send({type:storeEventName,args:[{event,eventInfo}],from:"server"});},bootTestRunner=async(channel,store)=>{let stderr=[],killChild=()=>{unsubscribeStore?.(),unsubscribeStatusStore?.(),unsubscribeTestProviderStore?.(),child?.kill(),child=null;};store.subscribe("FATAL_ERROR",killChild);let exit=(code=0)=>{killChild(),eventQueue.length=0,process.exit(code);};process.on("exit",exit),process.on("SIGINT",()=>exit(0)),process.on("SIGTERM",()=>exit(0));let startChildProcess=()=>new Promise((resolve2,reject)=>{child=execaNode(vitestModulePath,{env:{VITEST:"true",TEST:"true",VITEST_CHILD_PROCESS:"true",NODE_ENV:process.env.NODE_ENV??"test"},extendEnv:!0}),stderr=[],child.stdout?.on("data",log),child.stderr?.on("data",data=>{data.toString().match(/^\u001B\[33m/)||(log(data),stderr.push(data.toString()));}),unsubscribeStore=store.subscribe(forwardUniversalStoreEvent(STORE_CHANNEL_EVENT_NAME)),unsubscribeStatusStore=coreServer.internal_universalStatusStore.subscribe(forwardUniversalStoreEvent(STATUS_STORE_CHANNEL_EVENT_NAME)),unsubscribeTestProviderStore=coreServer.internal_universalTestProviderStore.subscribe(forwardUniversalStoreEvent(TEST_PROVIDER_STORE_CHANNEL_EVENT_NAME)),child.on("message",event=>{if(event.type==="ready"){for(;eventQueue.length;){let{type,args}=eventQueue.shift();child?.send({type,args,from:"server"});}resolve2();}else event.type==="uncaught-error"?(store.send({type:"FATAL_ERROR",payload:event.payload}),reject()):channel.emit(event.type,...event.args);});}),timeout=new Promise((_,reject)=>setTimeout(reject,MAX_START_TIME,new Error(`Aborting test runner process because it took longer than ${MAX_START_TIME/1e3} seconds to start.`)));await Promise.race([startChildProcess(),timeout]).catch(error=>{throw store.send({type:"FATAL_ERROR",payload:{message:"Failed to start test runner process",error:{message:error.message,name:error.name,stack:error.stack,cause:error.cause}}}),eventQueue.length=0,error});},runTestRunner=async(channel,store,initEvent,initArgs)=>{!ready&&initEvent&&eventQueue.push({type:initEvent,args:initArgs}),child||(ready=!1,await bootTestRunner(channel,store),ready=!0);};var experimental_serverChannel=async(channel,options)=>{let core=await options.presets.apply("core"),previewPath=common.loadPreviewOrConfigFile({configDir:options.configDir}),previewAnnotations=await options.presets.apply("previewAnnotations",[],options),builderName=typeof core?.builder=="string"?core.builder:core?.builder?.name,framework=await common.getFrameworkName(options);if(!builderName?.includes("vite"))return framework.includes("nextjs")&&log(tsDedent.dedent`
|
|
30
|
+
`);};var DEFAULT_MAX_BUFFER=1e3*1e3*100,getEnv=({env:envOption,extendEnv,preferLocal,localDir,execPath})=>{let env=extendEnv?{...process6__default.default.env,...envOption}:envOption;return preferLocal?npmRunPathEnv({env,cwd:localDir,execPath}):env},handleArguments=(file,args,options={})=>{let parsed=import_cross_spawn.default._parse(file,args,options);return file=parsed.command,args=parsed.args,options=parsed.options,options={maxBuffer:DEFAULT_MAX_BUFFER,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:options.cwd||process6__default.default.cwd(),execPath:process6__default.default.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:verboseDefault,...options},options.env=getEnv(options),options.stdio=normalizeStdio(options),process6__default.default.platform==="win32"&&path__default.default.basename(file,".exe")==="cmd"&&args.unshift("/q"),{file,args,options,parsed}},handleOutput=(options,value,error)=>typeof value!="string"&&!buffer.Buffer.isBuffer(value)?error===void 0?void 0:"":options.stripFinalNewline?stripFinalNewline(value):value;function execa(file,args,options){let parsed=handleArguments(file,args,options),command=joinCommand(file,args),escapedCommand=getEscapedCommand(file,args);logCommand(escapedCommand,parsed.options),validateTimeout(parsed.options);let spawned;try{spawned=childProcess__default.default.spawn(parsed.file,parsed.args,parsed.options);}catch(error){let dummySpawned=new childProcess__default.default.ChildProcess,errorPromise=Promise.reject(makeError({error,stdout:"",stderr:"",all:"",command,escapedCommand,parsed,timedOut:!1,isCanceled:!1,killed:!1}));return mergePromise(dummySpawned,errorPromise),dummySpawned}let spawnedPromise=getSpawnedPromise(spawned),timedPromise=setupTimeout(spawned,parsed.options,spawnedPromise),processDone=setExitHandler(spawned,parsed.options,timedPromise),context={isCanceled:!1};spawned.kill=spawnedKill.bind(null,spawned.kill.bind(spawned)),spawned.cancel=spawnedCancel.bind(null,spawned,context);let handlePromiseOnce=onetime_default(async()=>{let[{error,exitCode,signal,timedOut},stdoutResult,stderrResult,allResult]=await getSpawnedResult(spawned,parsed.options,processDone),stdout=handleOutput(parsed.options,stdoutResult),stderr=handleOutput(parsed.options,stderrResult),all=handleOutput(parsed.options,allResult);if(error||exitCode!==0||signal!==null){let returnedError=makeError({error,exitCode,signal,stdout,stderr,all,command,escapedCommand,parsed,timedOut,isCanceled:(parsed.options.signal?parsed.options.signal.aborted:!1),killed:spawned.killed});if(!parsed.options.reject)return returnedError;throw returnedError}return {command,escapedCommand,exitCode:0,stdout,stderr,all,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}});return handleInput(spawned,parsed.options),spawned.all=makeAllStream(spawned,parsed.options),addPipeMethods(spawned),mergePromise(spawned,handlePromiseOnce),spawned}function execaNode(scriptPath,args,options={}){args&&!Array.isArray(args)&&typeof args=="object"&&(options=args,args=[]);let stdio=normalizeStdioNode(options),defaultExecArgv=process6__default.default.execArgv.filter(arg=>!arg.startsWith("--inspect")),{nodePath=process6__default.default.execPath,nodeOptions=defaultExecArgv}=options;return execa(nodePath,[...nodeOptions,scriptPath,...Array.isArray(args)?args:[]],{...options,stdin:void 0,stdout:void 0,stderr:void 0,stdio,shell:!1})}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]:$/;var 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 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)};var MAX_START_TIME=3e4,vitestModulePath=join(__dirname,"node","vitest.mjs"),eventQueue=[],child,ready=!1,unsubscribeStore,unsubscribeStatusStore,unsubscribeTestProviderStore,forwardUniversalStoreEvent=storeEventName=>(event,eventInfo)=>{child?.send({type:storeEventName,args:[{event,eventInfo}],from:"server"});},bootTestRunner=async({channel,store,options})=>{let stderr=[],killChild=()=>{unsubscribeStore?.(),unsubscribeStatusStore?.(),unsubscribeTestProviderStore?.(),child?.kill(),child=null;};store.subscribe("FATAL_ERROR",killChild);let exit=(code=0)=>{killChild(),eventQueue.length=0,process.exit(code);};process.on("exit",exit),process.on("SIGINT",()=>exit(0)),process.on("SIGTERM",()=>exit(0));let startChildProcess=()=>new Promise((resolve2,reject)=>{child=execaNode(vitestModulePath,{env:{VITEST:"true",TEST:"true",VITEST_CHILD_PROCESS:"true",NODE_ENV:process.env.NODE_ENV??"test",STORYBOOK_CONFIG_DIR:options.configDir},extendEnv:!0}),stderr=[],child.stdout?.on("data",log),child.stderr?.on("data",data=>{data.toString().match(/^\u001B\[33m/)||(log(data),stderr.push(data.toString()));}),unsubscribeStore=store.subscribe(forwardUniversalStoreEvent(STORE_CHANNEL_EVENT_NAME)),unsubscribeStatusStore=coreServer.internal_universalStatusStore.subscribe(forwardUniversalStoreEvent(STATUS_STORE_CHANNEL_EVENT_NAME)),unsubscribeTestProviderStore=coreServer.internal_universalTestProviderStore.subscribe(forwardUniversalStoreEvent(TEST_PROVIDER_STORE_CHANNEL_EVENT_NAME)),child.on("message",event=>{if(event.type==="ready"){for(;eventQueue.length;){let{type,args}=eventQueue.shift();child?.send({type,args,from:"server"});}resolve2();}else event.type==="uncaught-error"?(store.send({type:"FATAL_ERROR",payload:event.payload}),reject()):channel.emit(event.type,...event.args);});}),timeout=new Promise((_,reject)=>setTimeout(reject,MAX_START_TIME,new Error(`Aborting test runner process because it took longer than ${MAX_START_TIME/1e3} seconds to start.`)));await Promise.race([startChildProcess(),timeout]).catch(error=>{throw store.send({type:"FATAL_ERROR",payload:{message:"Failed to start test runner process",error:{message:error.message,name:error.name,stack:error.stack,cause:error.cause}}}),eventQueue.length=0,error});},runTestRunner=async({channel,store,initEvent,initArgs,options})=>{!ready&&initEvent&&eventQueue.push({type:initEvent,args:initArgs}),child||(ready=!1,await bootTestRunner({channel,store,options}),ready=!0);};var experimental_serverChannel=async(channel,options)=>{let core=await options.presets.apply("core"),previewPath=common.loadPreviewOrConfigFile({configDir:options.configDir}),previewAnnotations=await options.presets.apply("previewAnnotations",[],options),builderName=typeof core?.builder=="string"?core.builder:core?.builder?.name,framework=await common.getFrameworkName(options);if(!builderName?.includes("vite"))return framework.includes("nextjs")&&log(tsDedent.dedent`
|
|
31
31
|
You're using ${framework}, which is a Webpack-based builder. In order to use Storybook Test, with your project, you need to use '@storybook/nextjs-vite', a high performance Vite-based equivalent.
|
|
32
32
|
|
|
33
33
|
Information on how to upgrade here: ${import_picocolors2.default.yellow("https://storybook.js.org/docs/get-started/frameworks/nextjs#with-vite")}\n
|
|
34
|
-
`),channel;let fsCache=common.createFileSystemCache({basePath:common.resolvePathInStorybookCache(ADDON_ID2.replace("/","-")),ns:"storybook",ttl:14*24*60*60*1e3}),cachedState=await fsCache.get("state",{config:storeOptions.initialState.config}),selectCachedState=s=>({config:s.config}),store=coreServer.experimental_UniversalStore.create({...storeOptions,initialState:{...storeOptions.initialState,previewAnnotations:(previewAnnotations??[]).concat(previewPath??[]),...selectCachedState(cachedState)},leader:!0});store.onStateChange((state,previousState)=>{isEqual(selectCachedState(state),selectCachedState(previousState))||fsCache.set("state",selectCachedState(state));});let testProviderStore=coreServer.experimental_getTestProviderStore(ADDON_ID2);if(store.subscribe("TRIGGER_RUN",(event,eventInfo)=>{testProviderStore.setState("test-provider-state:running"),store.setState(s=>({...s,fatalError:void 0})),runTestRunner(channel,store,STORE_CHANNEL_EVENT_NAME,[{event,eventInfo}]);}),store.subscribe("TOGGLE_WATCHING",(event,eventInfo)=>{store.setState(s=>({...s,watching:event.payload.to,currentRun:{...s.currentRun,...event.payload.to&&{coverageSummary:void 0}}})),event.payload.to&&runTestRunner(channel,store,STORE_CHANNEL_EVENT_NAME,[{event,eventInfo}]);}),store.subscribe("FATAL_ERROR",event=>{let{message,error}=event.payload,name=error.name||"Error";log(`${name}: ${message}`),error.stack&&log(error.stack);function logErrorWithCauses(err){err&&(log(`Caused by: ${err.name??"Error"}: ${err.message}`),err.stack&&log(err.stack),err.cause&&logErrorWithCauses(err.cause));}error.cause&&logErrorWithCauses(error.cause),store.setState(s=>({...s,fatalError:{message,error}})),testProviderStore.setState("test-provider-state:crashed");}),testProviderStore.onClearAll(()=>{store.setState(s=>({...s,currentRun:{...s.currentRun,coverageSummary:void 0,unhandledErrors:[]}}));}),!core.disableTelemetry){let enableCrashReports=core.enableCrashReports||options.enableCrashReports,packageJsonPath=__require.resolve("@storybook/addon-vitest/package.json"),{version:addonVersion}=JSON.parse(fs.readFileSync(packageJsonPath,{encoding:"utf-8"}));channel.on(STORYBOOK_ADDON_TEST_CHANNEL,event=>{telemetry.telemetry("addon-test",{...event,payload:{...event.payload,storyId:telemetry.oneWayHash(event.payload.storyId)},addonVersion});}),store.subscribe("TOGGLE_WATCHING",async event=>{await telemetry.telemetry("addon-test",{watchMode:event.payload.to,addonVersion});}),store.subscribe("TEST_RUN_COMPLETED",async event=>{let{unhandledErrors,startedAt,finishedAt,...currentRun}=event.payload;await telemetry.telemetry("addon-test",{...currentRun,duration:(finishedAt??0)-(startedAt??0),unhandledErrorCount:unhandledErrors.length,...enableCrashReports&&unhandledErrors.length>0&&{unhandledErrors:unhandledErrors.map(error=>{let{stacks,...errorWithoutStacks}=error;return telemetry.sanitizeError(errorWithoutStacks)})},addonVersion});}),enableCrashReports&&store.subscribe("FATAL_ERROR",async event=>{await telemetry.telemetry("addon-test",{fatalError:telemetry.cleanPaths(event.payload.error.message),addonVersion});});}return channel},staticDirs=async(values=[],options)=>{if(options.configType==="PRODUCTION")return values;let coverageDirectory=common.resolvePathInStorybookCache(COVERAGE_DIRECTORY);return await promises.mkdir(coverageDirectory,{recursive:!0}),[{from:coverageDirectory,to:"/coverage"},...values]};
|
|
34
|
+
`),channel;let fsCache=common.createFileSystemCache({basePath:common.resolvePathInStorybookCache(ADDON_ID2.replace("/","-")),ns:"storybook",ttl:14*24*60*60*1e3}),cachedState=await fsCache.get("state",{config:storeOptions.initialState.config}),selectCachedState=s=>({config:s.config}),store=coreServer.experimental_UniversalStore.create({...storeOptions,initialState:{...storeOptions.initialState,previewAnnotations:(previewAnnotations??[]).concat(previewPath??[]),...selectCachedState(cachedState)},leader:!0});store.onStateChange((state,previousState)=>{isEqual(selectCachedState(state),selectCachedState(previousState))||fsCache.set("state",selectCachedState(state));});let testProviderStore=coreServer.experimental_getTestProviderStore(ADDON_ID2);if(store.subscribe("TRIGGER_RUN",(event,eventInfo)=>{testProviderStore.setState("test-provider-state:running"),store.setState(s=>({...s,fatalError:void 0})),runTestRunner({channel,store,initEvent:STORE_CHANNEL_EVENT_NAME,initArgs:[{event,eventInfo}],options});}),store.subscribe("TOGGLE_WATCHING",(event,eventInfo)=>{store.setState(s=>({...s,watching:event.payload.to,currentRun:{...s.currentRun,...event.payload.to&&{coverageSummary:void 0}}})),event.payload.to&&runTestRunner({channel,store,initEvent:STORE_CHANNEL_EVENT_NAME,initArgs:[{event,eventInfo}],options});}),store.subscribe("FATAL_ERROR",event=>{let{message,error}=event.payload,name=error.name||"Error";log(`${name}: ${message}`),error.stack&&log(error.stack);function logErrorWithCauses(err){err&&(log(`Caused by: ${err.name??"Error"}: ${err.message}`),err.stack&&log(err.stack),err.cause&&logErrorWithCauses(err.cause));}error.cause&&logErrorWithCauses(error.cause),store.setState(s=>({...s,fatalError:{message,error}})),testProviderStore.setState("test-provider-state:crashed");}),testProviderStore.onClearAll(()=>{store.setState(s=>({...s,currentRun:{...s.currentRun,coverageSummary:void 0,unhandledErrors:[]}}));}),!core.disableTelemetry){let enableCrashReports=core.enableCrashReports||options.enableCrashReports,packageJsonPath=__require.resolve("@storybook/addon-vitest/package.json"),{version:addonVersion}=JSON.parse(fs.readFileSync(packageJsonPath,{encoding:"utf-8"}));channel.on(STORYBOOK_ADDON_TEST_CHANNEL,event=>{telemetry.telemetry("addon-test",{...event,payload:{...event.payload,storyId:telemetry.oneWayHash(event.payload.storyId)},addonVersion});}),store.subscribe("TOGGLE_WATCHING",async event=>{await telemetry.telemetry("addon-test",{watchMode:event.payload.to,addonVersion});}),store.subscribe("TEST_RUN_COMPLETED",async event=>{let{unhandledErrors,startedAt,finishedAt,...currentRun}=event.payload;await telemetry.telemetry("addon-test",{...currentRun,duration:(finishedAt??0)-(startedAt??0),unhandledErrorCount:unhandledErrors.length,...enableCrashReports&&unhandledErrors.length>0&&{unhandledErrors:unhandledErrors.map(error=>{let{stacks,...errorWithoutStacks}=error;return telemetry.sanitizeError(errorWithoutStacks)})},addonVersion});}),enableCrashReports&&store.subscribe("FATAL_ERROR",async event=>{await telemetry.telemetry("addon-test",{fatalError:telemetry.cleanPaths(event.payload.error.message),addonVersion});});}return channel},staticDirs=async(values=[],options)=>{if(options.configType==="PRODUCTION")return values;let coverageDirectory=common.resolvePathInStorybookCache(COVERAGE_DIRECTORY);return await promises.mkdir(coverageDirectory,{recursive:!0}),[{from:coverageDirectory,to:"/coverage"},...values]};
|
|
35
35
|
|
|
36
36
|
exports.experimental_serverChannel = experimental_serverChannel;
|
|
37
37
|
exports.staticDirs = staticDirs;
|
|
@@ -42,7 +42,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
42
42
|
The values you passed to "test.include" will be ignored, please remove them from your Vitest configuration where the Storybook plugin is applied.
|
|
43
43
|
|
|
44
44
|
More info: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#addon-test-indexing-behavior-of-storybookaddon-test-is-changed
|
|
45
|
-
`))),config$1},configureVitest(context){context.vitest.config.coverage.exclude.push("storybook-static");},async configureServer(server){if(staticDirs)for(let staticDir of staticDirs)try{let{staticPath,targetEndpoint}=mapStaticDir(staticDir,directories.configDir);server.middlewares.use(targetEndpoint,build_default(staticPath,{dev:!0,etag:!0,extensions:[]}));}catch(e){console.warn(e);}},async transform(code,id){if(process.env.VITEST!=="true")return code;let relativeId=relative(finalOptions.vitestRoot,id);if((0, import_micromatch.match)([relativeId],finalOptions.includeStories).length>0)return csfTools.vitestTransform({code,fileName:id,configDir:finalOptions.configDir,tagsFilter:finalOptions.tags,stories:storiesGlobs,previewLevelTags})}};
|
|
45
|
+
`))),config$1},configureVitest(context){context.vitest.config.coverage.exclude.push("storybook-static");},async configureServer(server){if(staticDirs)for(let staticDir of staticDirs)try{let{staticPath,targetEndpoint}=mapStaticDir(staticDir,directories.configDir);server.middlewares.use(targetEndpoint,build_default(staticPath,{dev:!0,etag:!0,extensions:[]}));}catch(e){console.warn(e);}},async transform(code,id){if(process.env.VITEST!=="true")return code;let relativeId=relative(finalOptions.vitestRoot,id);if((0, import_micromatch.match)([relativeId],finalOptions.includeStories).length>0)return csfTools.vitestTransform({code,fileName:id,configDir:finalOptions.configDir,tagsFilter:finalOptions.tags,stories:storiesGlobs,previewLevelTags})}};if(plugins.push(storybookTestPlugin),process.env.VITEST_STORYBOOK){let projectName=join("storybook:",finalOptions.configDir);plugins.push({name:"storybook:workspace-name-override",config:{order:"pre",handler:config=>(config.test??={},config.test.name=projectName,config)}});}return plugins},vitest_plugin_default=storybookTest;
|
|
46
46
|
|
|
47
47
|
exports.default = vitest_plugin_default;
|
|
48
48
|
exports.storybookTest = storybookTest;
|
|
@@ -23,6 +23,6 @@ var require_utils=__commonJS({"../../node_modules/braces/lib/utils.js"(exports){
|
|
|
23
23
|
The values you passed to "test.include" will be ignored, please remove them from your Vitest configuration where the Storybook plugin is applied.
|
|
24
24
|
|
|
25
25
|
More info: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#addon-test-indexing-behavior-of-storybookaddon-test-is-changed
|
|
26
|
-
`))),config},configureVitest(context){context.vitest.config.coverage.exclude.push("storybook-static");},async configureServer(server){if(staticDirs)for(let staticDir of staticDirs)try{let{staticPath,targetEndpoint}=mapStaticDir(staticDir,directories.configDir);server.middlewares.use(targetEndpoint,(0,import_sirv.default)(staticPath,{dev:!0,etag:!0,extensions:[]}));}catch(e){console.warn(e);}},async transform(code,id){if(process.env.VITEST!=="true")return code;let relativeId=relative(finalOptions.vitestRoot,id);if((0, import_micromatch.match)([relativeId],finalOptions.includeStories).length>0)return vitestTransform({code,fileName:id,configDir:finalOptions.configDir,tagsFilter:finalOptions.tags,stories:storiesGlobs,previewLevelTags})}};
|
|
26
|
+
`))),config},configureVitest(context){context.vitest.config.coverage.exclude.push("storybook-static");},async configureServer(server){if(staticDirs)for(let staticDir of staticDirs)try{let{staticPath,targetEndpoint}=mapStaticDir(staticDir,directories.configDir);server.middlewares.use(targetEndpoint,(0,import_sirv.default)(staticPath,{dev:!0,etag:!0,extensions:[]}));}catch(e){console.warn(e);}},async transform(code,id){if(process.env.VITEST!=="true")return code;let relativeId=relative(finalOptions.vitestRoot,id);if((0, import_micromatch.match)([relativeId],finalOptions.includeStories).length>0)return vitestTransform({code,fileName:id,configDir:finalOptions.configDir,tagsFilter:finalOptions.tags,stories:storiesGlobs,previewLevelTags})}};if(plugins.push(storybookTestPlugin),process.env.VITEST_STORYBOOK){let projectName=join$1("storybook:",finalOptions.configDir);plugins.push({name:"storybook:workspace-name-override",config:{order:"pre",handler:config=>(config.test??={},config.test.name=projectName,config)}});}return plugins},vitest_plugin_default=storybookTest;
|
|
27
27
|
|
|
28
28
|
export { vitest_plugin_default as default, storybookTest };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@storybook/addon-vitest",
|
|
3
|
-
"version": "9.0.0-rc.
|
|
3
|
+
"version": "9.0.0-rc.4",
|
|
4
4
|
"description": "Storybook addon for testing components",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"storybook-addons",
|
|
@@ -124,7 +124,7 @@
|
|
|
124
124
|
"peerDependencies": {
|
|
125
125
|
"@vitest/browser": "^3.0.0",
|
|
126
126
|
"@vitest/runner": "^3.0.0",
|
|
127
|
-
"storybook": "^9.0.0-rc.
|
|
127
|
+
"storybook": "^9.0.0-rc.4",
|
|
128
128
|
"vitest": "^3.0.0"
|
|
129
129
|
},
|
|
130
130
|
"peerDependenciesMeta": {
|