@storybook/addon-vitest 0.0.0-pr-31239-sha-e8c4c278 → 0.0.0-pr-31282-sha-7c7b460a

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.
package/dist/manager.js CHANGED
@@ -5,4 +5,4 @@ import { Modal, ProgressSpinner, Button, IconButton, WithTooltip, TooltipNote, L
5
5
  import { StopAltIcon, SyncIcon, CloseIcon, EyeIcon, PlayHollowIcon, InfoIcon } from '@storybook/icons';
6
6
  import { styled } from 'storybook/theming';
7
7
 
8
- var ADDON_ID="storybook/interactions",PANEL_ID=`${ADDON_ID}/panel`;var ADDON_ID2="storybook/a11y",PANEL_ID2=`${ADDON_ID2}/panel`;var ADDON_ID3="storybook/test",TEST_PROVIDER_ID=`${ADDON_ID3}/test-provider`;var DOCUMENTATION_LINK3="writing-tests/test-addon",DOCUMENTATION_FATAL_ERROR_LINK=`${DOCUMENTATION_LINK3}#what-happens-if-vitest-itself-has-an-error`;var storeOptions={id:ADDON_ID3,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}}},FULL_RUN_TRIGGERS=["global","run-all"];var STATUS_TYPE_ID_COMPONENT_TEST="storybook/component-test",STATUS_TYPE_ID_A11Y="storybook/a11y";var store=experimental_UniversalStore.create({...storeOptions,leader:globalThis.CONFIG_TYPE==="PRODUCTION"}),componentTestStatusStore=experimental_getStatusStore(STATUS_TYPE_ID_COMPONENT_TEST),a11yStatusStore=experimental_getStatusStore(STATUS_TYPE_ID_A11Y),testProviderStore=experimental_getTestProviderStore(ADDON_ID3);var ModalBar=styled.div({display:"flex",justifyContent:"space-between",alignItems:"center",padding:"6px 6px 6px 20px"}),ModalActionBar=styled.div({display:"flex",justifyContent:"space-between",alignItems:"center"}),ModalTitle=styled(Modal.Title)(({theme:{typography}})=>({fontSize:typography.size.s2,fontWeight:typography.weight.bold})),ModalStackTrace=styled.pre(({theme})=>({whiteSpace:"pre-wrap",wordWrap:"break-word",overflow:"auto",maxHeight:"60vh",margin:0,padding:"20px",fontFamily:theme.typography.fonts.mono,fontSize:"12px",borderTop:`1px solid ${theme.appBorderColor}`,borderRadius:0})),TroubleshootLink=styled.a(({theme})=>({color:theme.color.defaultText})),GlobalErrorContext=React3.createContext({isModalOpen:!1,setModalOpen:void 0});function ErrorCause({error}){return error?React3.createElement("div",null,React3.createElement("h4",null,"Caused by: ",error.name||"Error",": ",error.message),error.stack&&React3.createElement("pre",null,error.stack),error.cause&&React3.createElement(ErrorCause,{error:error.cause})):null}function GlobalErrorModal({onRerun,storeState}){let api=useStorybookApi(),{isModalOpen,setModalOpen}=useContext(GlobalErrorContext),handleClose=()=>setModalOpen?.(!1),troubleshootURL=api.getDocsUrl({subpath:DOCUMENTATION_FATAL_ERROR_LINK,versioned:!0,renderer:!0}),{fatalError,currentRun:{unhandledErrors}}=storeState,content=fatalError?React3.createElement(React3.Fragment,null,React3.createElement("p",null,fatalError.error.name||"Error"),fatalError.message&&React3.createElement("p",null,fatalError.message),fatalError.error.message&&React3.createElement("p",null,fatalError.error.message),fatalError.error.stack&&React3.createElement("p",null,fatalError.error.stack),fatalError.error.cause&&React3.createElement(ErrorCause,{error:fatalError.error.cause})):unhandledErrors.length>0?React3.createElement("ol",null,unhandledErrors.map(error=>React3.createElement("li",{key:error.name+error.message},React3.createElement("p",null,error.name,": ",error.message),error.VITEST_TEST_PATH&&React3.createElement("p",null,'This error originated in "',React3.createElement("b",null,error.VITEST_TEST_PATH),`". It doesn't mean the error was thrown inside the file itself, but while it was running.`),error.VITEST_TEST_NAME&&React3.createElement(React3.Fragment,null,React3.createElement("p",null,`The latest test that might've caused the error is "`,React3.createElement("b",null,error.VITEST_TEST_NAME),'". It might mean one of the following:'),React3.createElement("ul",null,React3.createElement("li",null,"The error was thrown, while Vitest was running this test."),React3.createElement("li",null,"If the error occurred after the test had been completed, this was the last documented test before it was thrown."))),error.stacks&&React3.createElement(React3.Fragment,null,React3.createElement("p",null,React3.createElement("b",null,"Stacks:")),React3.createElement("ul",null,error.stacks.map(stack=>React3.createElement("li",{key:stack.file+stack.line+stack.column},stack.file,":",stack.line,":",stack.column," - ",stack.method||"unknown method")))),error.stack&&React3.createElement("p",null,error.stack),error.cause?React3.createElement(ErrorCause,{error:error.cause}):null))):null;return React3.createElement(Modal,{onEscapeKeyDown:handleClose,onInteractOutside:handleClose,open:isModalOpen},React3.createElement(ModalBar,null,React3.createElement(ModalTitle,null,"Storybook Tests error details"),React3.createElement(ModalActionBar,null,React3.createElement(Button,{onClick:onRerun,variant:"ghost"},React3.createElement(SyncIcon,null),"Rerun"),React3.createElement(Button,{variant:"ghost",asChild:!0},React3.createElement("a",{target:"_blank",href:troubleshootURL,rel:"noreferrer"},"Troubleshoot")),React3.createElement(IconButton,{onClick:handleClose,"aria-label":"Close modal"},React3.createElement(CloseIcon,null)))),React3.createElement(ModalStackTrace,null,content,React3.createElement("br",null),React3.createElement("br",null),"Troubleshoot:"," ",React3.createElement(TroubleshootLink,{target:"_blank",href:troubleshootURL},troubleshootURL)))}function isPlainObject(object){if(typeof object!="object"||object==null)return !1;if(Object.getPrototypeOf(object)===null)return !0;if(object.toString()!=="[object Object]")return !1;let proto=object;for(;Object.getPrototypeOf(proto)!==null;)proto=Object.getPrototypeOf(proto);return Object.getPrototypeOf(object)===proto}var regexpTag="[object RegExp]",stringTag="[object String]",numberTag="[object Number]",booleanTag="[object Boolean]",argumentsTag="[object Arguments]",symbolTag="[object Symbol]",dateTag="[object Date]",mapTag="[object Map]",setTag="[object Set]",arrayTag="[object Array]",functionTag="[object Function]",arrayBufferTag="[object ArrayBuffer]",objectTag="[object Object]",errorTag="[object Error]",dataViewTag="[object DataView]",uint8ArrayTag="[object Uint8Array]",uint8ClampedArrayTag="[object Uint8ClampedArray]",uint16ArrayTag="[object Uint16Array]",uint32ArrayTag="[object Uint32Array]",bigUint64ArrayTag="[object BigUint64Array]",int8ArrayTag="[object Int8Array]",int16ArrayTag="[object Int16Array]",int32ArrayTag="[object Int32Array]",bigInt64ArrayTag="[object BigInt64Array]",float32ArrayTag="[object Float32Array]",float64ArrayTag="[object Float64Array]";function getSymbols(object){return Object.getOwnPropertySymbols(object).filter(symbol=>Object.prototype.propertyIsEnumerable.call(object,symbol))}function getTag(value){return value==null?value===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(value)}function isEqual(a,b){if(typeof a==typeof b)switch(typeof a){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return a===b;case"number":return a===b||Object.is(a,b);case"function":return a===b;case"object":return areObjectsEqual(a,b)}return areObjectsEqual(a,b)}function areObjectsEqual(a,b,stack){if(Object.is(a,b))return !0;let aTag=getTag(a),bTag=getTag(b);if(aTag===argumentsTag&&(aTag=objectTag),bTag===argumentsTag&&(bTag=objectTag),aTag!==bTag)return !1;switch(aTag){case stringTag:return a.toString()===b.toString();case numberTag:{let x=a.valueOf(),y=b.valueOf();return x===y||Number.isNaN(x)&&Number.isNaN(y)}case booleanTag:case dateTag:case symbolTag:return Object.is(a.valueOf(),b.valueOf());case regexpTag:return a.source===b.source&&a.flags===b.flags;case functionTag:return a===b}stack=stack??new Map;let aStack=stack.get(a),bStack=stack.get(b);if(aStack!=null&&bStack!=null)return aStack===b;stack.set(a,b),stack.set(b,a);try{switch(aTag){case mapTag:{if(a.size!==b.size)return !1;for(let[key,value]of a.entries())if(!b.has(key)||!areObjectsEqual(value,b.get(key),stack))return !1;return !0}case setTag:{if(a.size!==b.size)return !1;let aValues=Array.from(a.values()),bValues=Array.from(b.values());for(let i=0;i<aValues.length;i++){let aValue=aValues[i],index=bValues.findIndex(bValue=>areObjectsEqual(aValue,bValue,stack));if(index===-1)return !1;bValues.splice(index,1);}return !0}case arrayTag:case uint8ArrayTag:case uint8ClampedArrayTag:case uint16ArrayTag:case uint32ArrayTag:case bigUint64ArrayTag:case int8ArrayTag:case int16ArrayTag:case int32ArrayTag:case bigInt64ArrayTag:case float32ArrayTag:case float64ArrayTag:{if(typeof Buffer<"u"&&Buffer.isBuffer(a)!==Buffer.isBuffer(b)||a.length!==b.length)return !1;for(let i=0;i<a.length;i++)if(!areObjectsEqual(a[i],b[i],stack))return !1;return !0}case arrayBufferTag:return a.byteLength!==b.byteLength?!1:areObjectsEqual(new Uint8Array(a),new Uint8Array(b),stack);case dataViewTag:return a.byteLength!==b.byteLength||a.byteOffset!==b.byteOffset?!1:areObjectsEqual(a.buffer,b.buffer,stack);case errorTag:return a.name===b.name&&a.message===b.message;case objectTag:{if(!(areObjectsEqual(a.constructor,b.constructor,stack)||isPlainObject(a)&&isPlainObject(b)))return !1;let aKeys=[...Object.keys(a),...getSymbols(a)],bKeys=[...Object.keys(b),...getSymbols(b)];if(aKeys.length!==bKeys.length)return !1;for(let i=0;i<aKeys.length;i++){let propKey=aKeys[i],aProp=a[propKey];if(!Object.prototype.hasOwnProperty.call(b,propKey))return !1;let bProp=b[propKey];if(!areObjectsEqual(aProp,bProp,stack))return !1}return !0}default:return !1}}finally{stack.delete(a),stack.delete(b);}}var statusValueToStoryIds=(allStatuses,typeId,storyIds)=>{let statusValueToStoryIdsMap={"status-value:pending":[],"status-value:success":[],"status-value:error":[],"status-value:warning":[],"status-value:unknown":[]};return (storyIds?storyIds.map(storyId=>allStatuses[storyId]).filter(Boolean):Object.values(allStatuses)).forEach(statusByTypeId=>{let status=statusByTypeId[typeId];status&&statusValueToStoryIdsMap[status.value].push(status.storyId);}),statusValueToStoryIdsMap},useTestProvider=(api,entryId)=>{let testProviderState=experimental_useTestProviderStore(s=>s[ADDON_ID3]),[storeState,setStoreState]=experimental_useUniversalStore(store),[isSettingsUpdated,setIsSettingsUpdated]=useState(!1),settingsUpdatedTimeoutRef=useRef();useEffect(()=>{let unsubscribe=store.onStateChange((state,previousState)=>{isEqual(state.config,previousState.config)||(testProviderStore.settingsChanged(),setIsSettingsUpdated(!0),clearTimeout(settingsUpdatedTimeoutRef.current),settingsUpdatedTimeoutRef.current=setTimeout(()=>{setIsSettingsUpdated(!1);},1e3));});return ()=>{unsubscribe(),clearTimeout(settingsUpdatedTimeoutRef.current);}},[]);let storyIds=useMemo(()=>entryId?api.findAllLeafStoryIds(entryId):void 0,[entryId,api]),componentTestStatusSelector=useCallback(allStatuses=>statusValueToStoryIds(allStatuses,STATUS_TYPE_ID_COMPONENT_TEST,storyIds),[storyIds]),componentTestStatusValueToStoryIds=experimental_useStatusStore(componentTestStatusSelector),a11yStatusValueToStoryIdsSelector=useCallback(allStatuses=>statusValueToStoryIds(allStatuses,STATUS_TYPE_ID_A11Y,storyIds),[storyIds]),a11yStatusValueToStoryIds=experimental_useStatusStore(a11yStatusValueToStoryIdsSelector);return {storeState,setStoreState,testProviderState,componentTestStatusValueToStoryIds,a11yStatusValueToStoryIds,isSettingsUpdated}};var RelativeTime=({timestamp})=>{let[timeAgo,setTimeAgo]=useState(null);if(useEffect(()=>{if(timestamp){setTimeAgo(Date.now()-timestamp);let interval=setInterval(()=>setTimeAgo(Date.now()-timestamp),1e4);return ()=>clearInterval(interval)}},[timestamp]),timeAgo===null)return null;let seconds=Math.round(timeAgo/1e3);if(seconds<60)return "just now";let minutes=Math.floor(seconds/60);if(minutes<60)return minutes===1?"a minute ago":`${minutes} minutes ago`;let hours=Math.floor(minutes/60);if(hours<24)return hours===1?"an hour ago":`${hours} hours ago`;let days=Math.floor(hours/24);return days===1?"yesterday":`${days} days ago`};var Wrapper=styled.div(({theme})=>({overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis",fontSize:theme.typography.size.s1,color:theme.textMutedColor})),PositiveText=styled.span(({theme})=>({color:theme.color.positiveText}));function Description({entryId,storeState,testProviderState,isSettingsUpdated,...props}){let{setModalOpen}=React3.useContext(GlobalErrorContext),{componentTestCount,totalTestCount,unhandledErrors,finishedAt}=storeState.currentRun,finishedTestCount=componentTestCount.success+componentTestCount.error,description="Not run";if(!entryId&&isSettingsUpdated)description=React3.createElement(PositiveText,null,"Settings updated");else if(testProviderState==="test-provider-state:running")description=(finishedTestCount??0)===0?"Starting...":`Testing... ${finishedTestCount}/${totalTestCount}`;else if(!entryId&&testProviderState==="test-provider-state:crashed")description=setModalOpen?React3.createElement(Link,{isButton:!0,onClick:()=>setModalOpen(!0)},"View full error"):"Crashed";else if(!entryId&&unhandledErrors.length>0){let unhandledErrorDescription=`View ${unhandledErrors.length} unhandled error${unhandledErrors?.length>1?"s":""}`;description=setModalOpen?React3.createElement(Link,{isButton:!0,onClick:()=>setModalOpen(!0)},unhandledErrorDescription):unhandledErrorDescription;}else entryId&&totalTestCount?description=`Ran ${totalTestCount} ${totalTestCount===1?"test":"tests"}`:finishedAt?description=React3.createElement(React3.Fragment,null,"Ran ",totalTestCount," ",totalTestCount===1?"test":"tests"," ",React3.createElement(RelativeTime,{timestamp:finishedAt})):storeState.watching&&(description="Watching for file changes");return React3.createElement(Wrapper,{...props},description)}var TestStatusIcon=styled.div(({percentage})=>({width:percentage?12:6,height:percentage?12:6,margin:percentage?1:4,background:percentage?`conic-gradient(var(--status-color) ${percentage}%, var(--status-background) ${percentage+1}%)`:"var(--status-color)",borderRadius:"50%"}),({isRunning,theme})=>isRunning&&{animation:`${theme.animation.glow} 1.5s ease-in-out infinite`},({status,theme})=>status==="positive"&&{"--status-color":theme.color.positive,"--status-background":`${theme.color.positive}66`},({status,theme})=>status==="warning"&&{"--status-color":theme.color.gold,"--status-background":`${theme.color.gold}66`},({status,theme})=>status==="negative"&&{"--status-color":theme.color.negative,"--status-background":`${theme.color.negative}66`},({status,theme})=>status==="critical"&&{"--status-color":theme.color.defaultText,"--status-background":`${theme.color.defaultText}66`},({status,theme})=>status==="unknown"&&{"--status-color":theme.color.mediumdark,"--status-background":`${theme.color.mediumdark}66`});var Container=styled.div({display:"flex",flexDirection:"column"}),Heading=styled.div({display:"flex",justifyContent:"space-between",padding:"8px 0",gap:12}),Info=styled.div({display:"flex",flexDirection:"column",marginLeft:8,minWidth:0}),Title=styled.div(({crashed,theme})=>({fontSize:theme.typography.size.s1,fontWeight:crashed?"bold":"normal",color:crashed?theme.color.negativeText:theme.color.defaultText})),Actions=styled.div({display:"flex",gap:4}),Extras=styled.div({marginBottom:2}),Muted=styled.span(({theme})=>({color:theme.textMutedColor})),Progress=styled(ProgressSpinner)({margin:4}),Row=styled.div({display:"flex",gap:4}),StopIcon=styled(StopAltIcon)({width:10}),openPanel=({api,panelId,entryId})=>{let story=entryId?api.findAllLeafStoryIds(entryId)[0]:void 0;story&&api.selectStory(story),api.setSelectedPanel(panelId),api.togglePanel(!0);},TestProviderRender=({api,entry,testProviderState,storeState,setStoreState,componentTestStatusValueToStoryIds,a11yStatusValueToStoryIds,isSettingsUpdated,...props})=>{let{config,watching,cancelling,currentRun,fatalError}=storeState,finishedTestCount=currentRun.componentTestCount.success+currentRun.componentTestCount.error,hasA11yAddon=addons.experimental_getRegisteredAddons().includes(ADDON_ID2),isRunning=testProviderState==="test-provider-state:running",isStarting=isRunning&&finishedTestCount===0,[componentTestStatusIcon,componentTestStatusLabel]=fatalError?["critical","Component tests crashed"]:componentTestStatusValueToStoryIds["status-value:error"].length>0?["negative","Component tests failed"]:isRunning?["unknown","Testing in progress"]:componentTestStatusValueToStoryIds["status-value:success"].length>0?["positive","Component tests passed"]:["unknown","Run tests to see results"],[a11yStatusIcon,a11yStatusLabel]=fatalError?["critical","Component tests crashed"]:a11yStatusValueToStoryIds["status-value:error"].length>0?["negative","Accessibility tests failed"]:a11yStatusValueToStoryIds["status-value:warning"].length>0?["warning","Accessibility tests failed"]:isRunning?["unknown","Testing in progress"]:a11yStatusValueToStoryIds["status-value:success"].length>0?["positive","Accessibility tests passed"]:["unknown","Run tests to see accessibility results"];return React3.createElement(Container,{...props},React3.createElement(Heading,null,React3.createElement(Info,null,entry?React3.createElement(Title,{id:"testing-module-title"},"Run component tests"):React3.createElement(Title,{id:"testing-module-title",crashed:testProviderState==="test-provider-state:crashed"||fatalError!==void 0||currentRun.unhandledErrors.length>0},currentRun.unhandledErrors.length===1?"Component tests completed with an error":currentRun.unhandledErrors.length>1?"Component tests completed with errors":fatalError?"Component tests didn\u2019t complete":"Run component tests"),React3.createElement(Description,{id:"testing-module-description",storeState,testProviderState,entryId:entry?.id,isSettingsUpdated})),React3.createElement(Actions,null,!entry&&React3.createElement(WithTooltip,{hasChrome:!1,trigger:"hover",tooltip:React3.createElement(TooltipNote,{note:`${watching?"Disable":"Enable"} watch mode`})},React3.createElement(IconButton,{"aria-label":`${watching?"Disable":"Enable"} watch mode`,size:"medium",active:watching,onClick:()=>store.send({type:"TOGGLE_WATCHING",payload:{to:!watching}}),disabled:isRunning},React3.createElement(EyeIcon,null))),isRunning?React3.createElement(WithTooltip,{hasChrome:!1,trigger:"hover",tooltip:React3.createElement(TooltipNote,{note:cancelling?"Stopping...":"Stop test run"})},React3.createElement(IconButton,{"aria-label":cancelling?"Stopping...":"Stop test run",padding:"none",size:"medium",onClick:()=>store.send({type:"CANCEL_RUN"}),disabled:cancelling||isStarting},React3.createElement(Progress,{percentage:finishedTestCount&&storeState.currentRun.totalTestCount?finishedTestCount/storeState.currentRun.totalTestCount*100:void 0},React3.createElement(StopIcon,null)))):React3.createElement(WithTooltip,{hasChrome:!1,trigger:"hover",tooltip:React3.createElement(TooltipNote,{note:"Start test run"})},React3.createElement(IconButton,{"aria-label":"Start test run",size:"medium",onClick:()=>store.send({type:"TRIGGER_RUN",payload:{storyIds:entry?api.findAllLeafStoryIds(entry.id):void 0,triggeredBy:entry?entry.type:"global"}})},React3.createElement(PlayHollowIcon,null))))),React3.createElement(Extras,null,React3.createElement(Row,null,React3.createElement(ListItem,{as:"label",title:"Interactions",icon:entry?null:React3.createElement(Checkbox,{checked:!0,disabled:!0})}),React3.createElement(WithTooltip,{hasChrome:!1,trigger:"hover",tooltip:React3.createElement(TooltipNote,{note:componentTestStatusLabel})},React3.createElement(IconButton,{size:"medium",disabled:componentTestStatusValueToStoryIds["status-value:error"].length===0&&componentTestStatusValueToStoryIds["status-value:warning"].length===0&&componentTestStatusValueToStoryIds["status-value:success"].length===0,onClick:()=>{openPanel({api,panelId:PANEL_ID,entryId:componentTestStatusValueToStoryIds["status-value:error"][0]??componentTestStatusValueToStoryIds["status-value:warning"][0]??componentTestStatusValueToStoryIds["status-value:success"][0]??entry?.id});}},React3.createElement(TestStatusIcon,{status:componentTestStatusIcon,"aria-label":componentTestStatusLabel,isRunning}),componentTestStatusValueToStoryIds["status-value:error"].length+componentTestStatusValueToStoryIds["status-value:warning"].length||null))),!entry&&React3.createElement(Row,null,React3.createElement(ListItem,{as:"label",title:watching?React3.createElement(Muted,null,"Coverage (unavailable)"):"Coverage",icon:React3.createElement(Checkbox,{checked:config.coverage,disabled:isRunning,onChange:()=>setStoreState(s=>({...s,config:{...s.config,coverage:!config.coverage}}))})}),React3.createElement(WithTooltip,{hasChrome:!1,trigger:"hover",tooltip:React3.createElement(TooltipNote,{note:watching?"Unavailable in watch mode":currentRun.triggeredBy&&!FULL_RUN_TRIGGERS.includes(currentRun.triggeredBy)?"Unavailable when running focused tests":isRunning?"Testing in progress":currentRun.coverageSummary?"View coverage report":fatalError?"Component tests crashed":"Run tests to calculate coverage"})},watching||currentRun.triggeredBy&&!FULL_RUN_TRIGGERS.includes(currentRun.triggeredBy)?React3.createElement(IconButton,{size:"medium",disabled:!0},React3.createElement(InfoIcon,{"aria-label":watching?"Coverage is unavailable in watch mode":"Coverage is unavailable when running focused tests"})):currentRun.coverageSummary?React3.createElement(IconButton,{asChild:!0,size:"medium"},React3.createElement("a",{href:"/coverage/index.html",target:"_blank","aria-label":"Open coverage report"},React3.createElement(TestStatusIcon,{isRunning,percentage:currentRun.coverageSummary.percentage,status:currentRun.coverageSummary.status,"aria-label":`Coverage status: ${currentRun.coverageSummary.status}`}),React3.createElement("span",{"aria-label":`${currentRun.coverageSummary.percentage} percent coverage`},currentRun.coverageSummary.percentage,"%"))):React3.createElement(IconButton,{size:"medium",disabled:!0},React3.createElement(TestStatusIcon,{isRunning,status:fatalError?"critical":"unknown","aria-label":"Coverage status: unknown"})))),hasA11yAddon&&React3.createElement(Row,null,React3.createElement(ListItem,{as:"label",title:"Accessibility",icon:entry?null:React3.createElement(Checkbox,{checked:config.a11y,disabled:isRunning,onChange:()=>setStoreState(s=>({...s,config:{...s.config,a11y:!config.a11y}}))})}),React3.createElement(WithTooltip,{hasChrome:!1,trigger:"hover",tooltip:React3.createElement(TooltipNote,{note:a11yStatusLabel})},React3.createElement(IconButton,{size:"medium",disabled:a11yStatusValueToStoryIds["status-value:error"].length===0&&a11yStatusValueToStoryIds["status-value:warning"].length===0&&a11yStatusValueToStoryIds["status-value:success"].length===0,onClick:()=>{openPanel({api,entryId:a11yStatusValueToStoryIds["status-value:error"][0]??a11yStatusValueToStoryIds["status-value:warning"][0]??a11yStatusValueToStoryIds["status-value:success"][0]??entry?.id,panelId:PANEL_ID2});}},React3.createElement(TestStatusIcon,{status:a11yStatusIcon,"aria-label":a11yStatusLabel,isRunning}),a11yStatusValueToStoryIds["status-value:error"].length+a11yStatusValueToStoryIds["status-value:warning"].length||null)))))};var SidebarContextMenu=({context,api})=>{let{testProviderState,componentTestStatusValueToStoryIds,a11yStatusValueToStoryIds,storeState,setStoreState}=useTestProvider(api,context.id);return React3.createElement(TestProviderRender,{api,entry:context,style:{minWidth:240},testProviderState,componentTestStatusValueToStoryIds,a11yStatusValueToStoryIds,storeState,setStoreState,isSettingsUpdated:!1})};addons.register(ADDON_ID3,api=>{if((globalThis.STORYBOOK_BUILDER||"").includes("vite")){let openPanel2=panelId=>{api.setSelectedPanel(panelId),api.togglePanel(!0);};componentTestStatusStore.onSelect(()=>{openPanel2(PANEL_ID);}),a11yStatusStore.onSelect(()=>{openPanel2(PANEL_ID2);}),testProviderStore.onRunAll(()=>{store.send({type:"TRIGGER_RUN",payload:{triggeredBy:"run-all"}});}),store.untilReady().then(()=>{store.setState(state=>({...state,indexUrl:new URL("index.json",window.location.href).toString()}));}),addons.add(TEST_PROVIDER_ID,{type:Addon_TypesEnum.experimental_TEST_PROVIDER,render:()=>{let[isModalOpen,setModalOpen]=useState(!1),{storeState,setStoreState,testProviderState,componentTestStatusValueToStoryIds,a11yStatusValueToStoryIds,isSettingsUpdated}=useTestProvider(api);return React3.createElement(GlobalErrorContext.Provider,{value:{isModalOpen,setModalOpen}},React3.createElement(TestProviderRender,{api,storeState,setStoreState,isSettingsUpdated,testProviderState,componentTestStatusValueToStoryIds,a11yStatusValueToStoryIds}),React3.createElement(GlobalErrorModal,{storeState,onRerun:()=>{setModalOpen(!1),store.send({type:"TRIGGER_RUN",payload:{triggeredBy:"global"}});}}))},sidebarContextMenu:({context})=>context.type==="docs"||context.type==="story"&&!context.tags.includes("test")?null:React3.createElement(SidebarContextMenu,{context,api})});}});
8
+ var ADDON_ID="storybook/interactions",PANEL_ID=`${ADDON_ID}/panel`;var ADDON_ID2="storybook/a11y",PANEL_ID2=`${ADDON_ID2}/panel`;var ADDON_ID3="storybook/test",TEST_PROVIDER_ID=`${ADDON_ID3}/test-provider`;var DOCUMENTATION_LINK3="writing-tests/test-addon",DOCUMENTATION_FATAL_ERROR_LINK=`${DOCUMENTATION_LINK3}#what-happens-if-vitest-itself-has-an-error`;var storeOptions={id:ADDON_ID3,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}}},FULL_RUN_TRIGGERS=["global","run-all"];var STATUS_TYPE_ID_COMPONENT_TEST="storybook/component-test",STATUS_TYPE_ID_A11Y="storybook/a11y";var store=experimental_UniversalStore.create({...storeOptions,leader:globalThis.CONFIG_TYPE==="PRODUCTION"}),componentTestStatusStore=experimental_getStatusStore(STATUS_TYPE_ID_COMPONENT_TEST),a11yStatusStore=experimental_getStatusStore(STATUS_TYPE_ID_A11Y),testProviderStore=experimental_getTestProviderStore(ADDON_ID3);var ModalBar=styled.div({display:"flex",justifyContent:"space-between",alignItems:"center",padding:"6px 6px 6px 20px"}),ModalActionBar=styled.div({display:"flex",justifyContent:"space-between",alignItems:"center"}),ModalTitle=styled(Modal.Title)(({theme:{typography}})=>({fontSize:typography.size.s2,fontWeight:typography.weight.bold})),ModalStackTrace=styled.pre(({theme})=>({whiteSpace:"pre-wrap",wordWrap:"break-word",overflow:"auto",maxHeight:"60vh",margin:0,padding:"20px",fontFamily:theme.typography.fonts.mono,fontSize:"12px",borderTop:`1px solid ${theme.appBorderColor}`,borderRadius:0})),TroubleshootLink=styled.a(({theme})=>({color:theme.color.defaultText})),GlobalErrorContext=React3.createContext({isModalOpen:!1,setModalOpen:void 0});function ErrorCause({error}){return error?React3.createElement("div",null,React3.createElement("h4",null,"Caused by: ",error.name||"Error",": ",error.message),error.stack&&React3.createElement("pre",null,error.stack),error.cause&&React3.createElement(ErrorCause,{error:error.cause})):null}function GlobalErrorModal({onRerun,storeState}){let api=useStorybookApi(),{isModalOpen,setModalOpen}=useContext(GlobalErrorContext),handleClose=()=>setModalOpen?.(!1),troubleshootURL=api.getDocsUrl({subpath:DOCUMENTATION_FATAL_ERROR_LINK,versioned:!0,renderer:!0}),{fatalError,currentRun:{unhandledErrors}}=storeState,content=fatalError?React3.createElement(React3.Fragment,null,React3.createElement("p",null,fatalError.error.name||"Error"),fatalError.message&&React3.createElement("p",null,fatalError.message),fatalError.error.message&&React3.createElement("p",null,fatalError.error.message),fatalError.error.stack&&React3.createElement("p",null,fatalError.error.stack),fatalError.error.cause&&React3.createElement(ErrorCause,{error:fatalError.error.cause})):unhandledErrors.length>0?React3.createElement("ol",null,unhandledErrors.map(error=>React3.createElement("li",{key:error.name+error.message},React3.createElement("p",null,error.name,": ",error.message),error.VITEST_TEST_PATH&&React3.createElement("p",null,'This error originated in "',React3.createElement("b",null,error.VITEST_TEST_PATH),`". It doesn't mean the error was thrown inside the file itself, but while it was running.`),error.VITEST_TEST_NAME&&React3.createElement(React3.Fragment,null,React3.createElement("p",null,`The latest test that might've caused the error is "`,React3.createElement("b",null,error.VITEST_TEST_NAME),'". It might mean one of the following:'),React3.createElement("ul",null,React3.createElement("li",null,"The error was thrown, while Vitest was running this test."),React3.createElement("li",null,"If the error occurred after the test had been completed, this was the last documented test before it was thrown."))),error.stacks&&React3.createElement(React3.Fragment,null,React3.createElement("p",null,React3.createElement("b",null,"Stacks:")),React3.createElement("ul",null,error.stacks.map(stack=>React3.createElement("li",{key:stack.file+stack.line+stack.column},stack.file,":",stack.line,":",stack.column," - ",stack.method||"unknown method")))),error.stack&&React3.createElement("p",null,error.stack),error.cause?React3.createElement(ErrorCause,{error:error.cause}):null))):null;return React3.createElement(Modal,{onEscapeKeyDown:handleClose,onInteractOutside:handleClose,open:isModalOpen},React3.createElement(ModalBar,null,React3.createElement(ModalTitle,null,"Storybook Tests error details"),React3.createElement(ModalActionBar,null,React3.createElement(Button,{onClick:onRerun,variant:"ghost"},React3.createElement(SyncIcon,null),"Rerun"),React3.createElement(Button,{variant:"ghost",asChild:!0},React3.createElement("a",{target:"_blank",href:troubleshootURL,rel:"noreferrer"},"Troubleshoot")),React3.createElement(IconButton,{onClick:handleClose,"aria-label":"Close modal"},React3.createElement(CloseIcon,null)))),React3.createElement(ModalStackTrace,null,content,React3.createElement("br",null),React3.createElement("br",null),"Troubleshoot:"," ",React3.createElement(TroubleshootLink,{target:"_blank",href:troubleshootURL},troubleshootURL)))}function noop(){}function getSymbols(object){return Object.getOwnPropertySymbols(object).filter(symbol=>Object.prototype.propertyIsEnumerable.call(object,symbol))}function getTag(value){return value==null?value===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(value)}var regexpTag="[object RegExp]",stringTag="[object String]",numberTag="[object Number]",booleanTag="[object Boolean]",argumentsTag="[object Arguments]",symbolTag="[object Symbol]",dateTag="[object Date]",mapTag="[object Map]",setTag="[object Set]",arrayTag="[object Array]",functionTag="[object Function]",arrayBufferTag="[object ArrayBuffer]",objectTag="[object Object]",errorTag="[object Error]",dataViewTag="[object DataView]",uint8ArrayTag="[object Uint8Array]",uint8ClampedArrayTag="[object Uint8ClampedArray]",uint16ArrayTag="[object Uint16Array]",uint32ArrayTag="[object Uint32Array]",bigUint64ArrayTag="[object BigUint64Array]",int8ArrayTag="[object Int8Array]",int16ArrayTag="[object Int16Array]",int32ArrayTag="[object Int32Array]",bigInt64ArrayTag="[object BigInt64Array]",float32ArrayTag="[object Float32Array]",float64ArrayTag="[object Float64Array]";function isPlainObject(value){if(!value||typeof value!="object")return !1;let proto=Object.getPrototypeOf(value);return proto===null||proto===Object.prototype||Object.getPrototypeOf(proto)===null?Object.prototype.toString.call(value)==="[object Object]":!1}function eq(value,other){return value===other||Number.isNaN(value)&&Number.isNaN(other)}function isEqualWith(a,b,areValuesEqual){return isEqualWithImpl(a,b,void 0,void 0,void 0,void 0,areValuesEqual)}function isEqualWithImpl(a,b,property,aParent,bParent,stack,areValuesEqual){let result=areValuesEqual(a,b,property,aParent,bParent,stack);if(result!==void 0)return result;if(typeof a==typeof b)switch(typeof a){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return a===b;case"number":return a===b||Object.is(a,b);case"function":return a===b;case"object":return areObjectsEqual(a,b,stack,areValuesEqual)}return areObjectsEqual(a,b,stack,areValuesEqual)}function areObjectsEqual(a,b,stack,areValuesEqual){if(Object.is(a,b))return !0;let aTag=getTag(a),bTag=getTag(b);if(aTag===argumentsTag&&(aTag=objectTag),bTag===argumentsTag&&(bTag=objectTag),aTag!==bTag)return !1;switch(aTag){case stringTag:return a.toString()===b.toString();case numberTag:{let x=a.valueOf(),y=b.valueOf();return eq(x,y)}case booleanTag:case dateTag:case symbolTag:return Object.is(a.valueOf(),b.valueOf());case regexpTag:return a.source===b.source&&a.flags===b.flags;case functionTag:return a===b}stack=stack??new Map;let aStack=stack.get(a),bStack=stack.get(b);if(aStack!=null&&bStack!=null)return aStack===b;stack.set(a,b),stack.set(b,a);try{switch(aTag){case mapTag:{if(a.size!==b.size)return !1;for(let[key,value]of a.entries())if(!b.has(key)||!isEqualWithImpl(value,b.get(key),key,a,b,stack,areValuesEqual))return !1;return !0}case setTag:{if(a.size!==b.size)return !1;let aValues=Array.from(a.values()),bValues=Array.from(b.values());for(let i=0;i<aValues.length;i++){let aValue=aValues[i],index=bValues.findIndex(bValue=>isEqualWithImpl(aValue,bValue,void 0,a,b,stack,areValuesEqual));if(index===-1)return !1;bValues.splice(index,1);}return !0}case arrayTag:case uint8ArrayTag:case uint8ClampedArrayTag:case uint16ArrayTag:case uint32ArrayTag:case bigUint64ArrayTag:case int8ArrayTag:case int16ArrayTag:case int32ArrayTag:case bigInt64ArrayTag:case float32ArrayTag:case float64ArrayTag:{if(typeof Buffer<"u"&&Buffer.isBuffer(a)!==Buffer.isBuffer(b)||a.length!==b.length)return !1;for(let i=0;i<a.length;i++)if(!isEqualWithImpl(a[i],b[i],i,a,b,stack,areValuesEqual))return !1;return !0}case arrayBufferTag:return a.byteLength!==b.byteLength?!1:areObjectsEqual(new Uint8Array(a),new Uint8Array(b),stack,areValuesEqual);case dataViewTag:return a.byteLength!==b.byteLength||a.byteOffset!==b.byteOffset?!1:areObjectsEqual(new Uint8Array(a),new Uint8Array(b),stack,areValuesEqual);case errorTag:return a.name===b.name&&a.message===b.message;case objectTag:{if(!(areObjectsEqual(a.constructor,b.constructor,stack,areValuesEqual)||isPlainObject(a)&&isPlainObject(b)))return !1;let aKeys=[...Object.keys(a),...getSymbols(a)],bKeys=[...Object.keys(b),...getSymbols(b)];if(aKeys.length!==bKeys.length)return !1;for(let i=0;i<aKeys.length;i++){let propKey=aKeys[i],aProp=a[propKey];if(!Object.hasOwn(b,propKey))return !1;let bProp=b[propKey];if(!isEqualWithImpl(aProp,bProp,propKey,a,b,stack,areValuesEqual))return !1}return !0}default:return !1}}finally{stack.delete(a),stack.delete(b);}}function isEqual(a,b){return isEqualWith(a,b,noop)}var statusValueToStoryIds=(allStatuses,typeId,storyIds)=>{let statusValueToStoryIdsMap={"status-value:pending":[],"status-value:success":[],"status-value:error":[],"status-value:warning":[],"status-value:unknown":[]};return (storyIds?storyIds.map(storyId=>allStatuses[storyId]).filter(Boolean):Object.values(allStatuses)).forEach(statusByTypeId=>{let status=statusByTypeId[typeId];status&&statusValueToStoryIdsMap[status.value].push(status.storyId);}),statusValueToStoryIdsMap},useTestProvider=(api,entryId)=>{let testProviderState=experimental_useTestProviderStore(s=>s[ADDON_ID3]),[storeState,setStoreState]=experimental_useUniversalStore(store),[isSettingsUpdated,setIsSettingsUpdated]=useState(!1),settingsUpdatedTimeoutRef=useRef();useEffect(()=>{let unsubscribe=store.onStateChange((state,previousState)=>{isEqual(state.config,previousState.config)||(testProviderStore.settingsChanged(),setIsSettingsUpdated(!0),clearTimeout(settingsUpdatedTimeoutRef.current),settingsUpdatedTimeoutRef.current=setTimeout(()=>{setIsSettingsUpdated(!1);},1e3));});return ()=>{unsubscribe(),clearTimeout(settingsUpdatedTimeoutRef.current);}},[]);let storyIds=useMemo(()=>entryId?api.findAllLeafStoryIds(entryId):void 0,[entryId,api]),componentTestStatusSelector=useCallback(allStatuses=>statusValueToStoryIds(allStatuses,STATUS_TYPE_ID_COMPONENT_TEST,storyIds),[storyIds]),componentTestStatusValueToStoryIds=experimental_useStatusStore(componentTestStatusSelector),a11yStatusValueToStoryIdsSelector=useCallback(allStatuses=>statusValueToStoryIds(allStatuses,STATUS_TYPE_ID_A11Y,storyIds),[storyIds]),a11yStatusValueToStoryIds=experimental_useStatusStore(a11yStatusValueToStoryIdsSelector);return {storeState,setStoreState,testProviderState,componentTestStatusValueToStoryIds,a11yStatusValueToStoryIds,isSettingsUpdated}};var RelativeTime=({timestamp})=>{let[timeAgo,setTimeAgo]=useState(null);if(useEffect(()=>{if(timestamp){setTimeAgo(Date.now()-timestamp);let interval=setInterval(()=>setTimeAgo(Date.now()-timestamp),1e4);return ()=>clearInterval(interval)}},[timestamp]),timeAgo===null)return null;let seconds=Math.round(timeAgo/1e3);if(seconds<60)return "just now";let minutes=Math.floor(seconds/60);if(minutes<60)return minutes===1?"a minute ago":`${minutes} minutes ago`;let hours=Math.floor(minutes/60);if(hours<24)return hours===1?"an hour ago":`${hours} hours ago`;let days=Math.floor(hours/24);return days===1?"yesterday":`${days} days ago`};var Wrapper=styled.div(({theme})=>({overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis",fontSize:theme.typography.size.s1,color:theme.textMutedColor})),PositiveText=styled.span(({theme})=>({color:theme.color.positiveText}));function Description({entryId,storeState,testProviderState,isSettingsUpdated,...props}){let{setModalOpen}=React3.useContext(GlobalErrorContext),{componentTestCount,totalTestCount,unhandledErrors,finishedAt}=storeState.currentRun,finishedTestCount=componentTestCount.success+componentTestCount.error,description="Not run";if(!entryId&&isSettingsUpdated)description=React3.createElement(PositiveText,null,"Settings updated");else if(testProviderState==="test-provider-state:running")description=(finishedTestCount??0)===0?"Starting...":`Testing... ${finishedTestCount}/${totalTestCount}`;else if(!entryId&&testProviderState==="test-provider-state:crashed")description=setModalOpen?React3.createElement(Link,{isButton:!0,onClick:()=>setModalOpen(!0)},"View full error"):"Crashed";else if(!entryId&&unhandledErrors.length>0){let unhandledErrorDescription=`View ${unhandledErrors.length} unhandled error${unhandledErrors?.length>1?"s":""}`;description=setModalOpen?React3.createElement(Link,{isButton:!0,onClick:()=>setModalOpen(!0)},unhandledErrorDescription):unhandledErrorDescription;}else entryId&&totalTestCount?description=`Ran ${totalTestCount} ${totalTestCount===1?"test":"tests"}`:finishedAt?description=React3.createElement(React3.Fragment,null,"Ran ",totalTestCount," ",totalTestCount===1?"test":"tests"," ",React3.createElement(RelativeTime,{timestamp:finishedAt})):storeState.watching&&(description="Watching for file changes");return React3.createElement(Wrapper,{...props},description)}var TestStatusIcon=styled.div(({percentage})=>({width:percentage?12:6,height:percentage?12:6,margin:percentage?1:4,background:percentage?`conic-gradient(var(--status-color) ${percentage}%, var(--status-background) ${percentage+1}%)`:"var(--status-color)",borderRadius:"50%"}),({isRunning,theme})=>isRunning&&{animation:`${theme.animation.glow} 1.5s ease-in-out infinite`},({status,theme})=>status==="positive"&&{"--status-color":theme.color.positive,"--status-background":`${theme.color.positive}66`},({status,theme})=>status==="warning"&&{"--status-color":theme.color.gold,"--status-background":`${theme.color.gold}66`},({status,theme})=>status==="negative"&&{"--status-color":theme.color.negative,"--status-background":`${theme.color.negative}66`},({status,theme})=>status==="critical"&&{"--status-color":theme.color.defaultText,"--status-background":`${theme.color.defaultText}66`},({status,theme})=>status==="unknown"&&{"--status-color":theme.color.mediumdark,"--status-background":`${theme.color.mediumdark}66`});var Container=styled.div({display:"flex",flexDirection:"column"}),Heading=styled.div({display:"flex",justifyContent:"space-between",padding:"8px 0",gap:12}),Info=styled.div({display:"flex",flexDirection:"column",marginLeft:8,minWidth:0}),Title=styled.div(({crashed,theme})=>({fontSize:theme.typography.size.s1,fontWeight:crashed?"bold":"normal",color:crashed?theme.color.negativeText:theme.color.defaultText})),Actions=styled.div({display:"flex",gap:4}),Extras=styled.div({marginBottom:2}),Muted=styled.span(({theme})=>({color:theme.textMutedColor})),Progress=styled(ProgressSpinner)({margin:4}),Row=styled.div({display:"flex",gap:4}),StopIcon=styled(StopAltIcon)({width:10}),openPanel=({api,panelId,entryId})=>{let story=entryId?api.findAllLeafStoryIds(entryId)[0]:void 0;story&&api.selectStory(story),api.setSelectedPanel(panelId),api.togglePanel(!0);},TestProviderRender=({api,entry,testProviderState,storeState,setStoreState,componentTestStatusValueToStoryIds,a11yStatusValueToStoryIds,isSettingsUpdated,...props})=>{let{config,watching,cancelling,currentRun,fatalError}=storeState,finishedTestCount=currentRun.componentTestCount.success+currentRun.componentTestCount.error,hasA11yAddon=addons.experimental_getRegisteredAddons().includes(ADDON_ID2),isRunning=testProviderState==="test-provider-state:running",isStarting=isRunning&&finishedTestCount===0,[componentTestStatusIcon,componentTestStatusLabel]=fatalError?["critical","Component tests crashed"]:componentTestStatusValueToStoryIds["status-value:error"].length>0?["negative","Component tests failed"]:isRunning?["unknown","Testing in progress"]:componentTestStatusValueToStoryIds["status-value:success"].length>0?["positive","Component tests passed"]:["unknown","Run tests to see results"],[a11yStatusIcon,a11yStatusLabel]=fatalError?["critical","Component tests crashed"]:a11yStatusValueToStoryIds["status-value:error"].length>0?["negative","Accessibility tests failed"]:a11yStatusValueToStoryIds["status-value:warning"].length>0?["warning","Accessibility tests failed"]:isRunning?["unknown","Testing in progress"]:a11yStatusValueToStoryIds["status-value:success"].length>0?["positive","Accessibility tests passed"]:["unknown","Run tests to see accessibility results"];return React3.createElement(Container,{...props},React3.createElement(Heading,null,React3.createElement(Info,null,entry?React3.createElement(Title,{id:"testing-module-title"},"Run component tests"):React3.createElement(Title,{id:"testing-module-title",crashed:testProviderState==="test-provider-state:crashed"||fatalError!==void 0||currentRun.unhandledErrors.length>0},currentRun.unhandledErrors.length===1?"Component tests completed with an error":currentRun.unhandledErrors.length>1?"Component tests completed with errors":fatalError?"Component tests didn\u2019t complete":"Run component tests"),React3.createElement(Description,{id:"testing-module-description",storeState,testProviderState,entryId:entry?.id,isSettingsUpdated})),React3.createElement(Actions,null,!entry&&React3.createElement(WithTooltip,{hasChrome:!1,trigger:"hover",tooltip:React3.createElement(TooltipNote,{note:`${watching?"Disable":"Enable"} watch mode`})},React3.createElement(IconButton,{"aria-label":`${watching?"Disable":"Enable"} watch mode`,size:"medium",active:watching,onClick:()=>store.send({type:"TOGGLE_WATCHING",payload:{to:!watching}}),disabled:isRunning},React3.createElement(EyeIcon,null))),isRunning?React3.createElement(WithTooltip,{hasChrome:!1,trigger:"hover",tooltip:React3.createElement(TooltipNote,{note:cancelling?"Stopping...":"Stop test run"})},React3.createElement(IconButton,{"aria-label":cancelling?"Stopping...":"Stop test run",padding:"none",size:"medium",onClick:()=>store.send({type:"CANCEL_RUN"}),disabled:cancelling||isStarting},React3.createElement(Progress,{percentage:finishedTestCount&&storeState.currentRun.totalTestCount?finishedTestCount/storeState.currentRun.totalTestCount*100:void 0},React3.createElement(StopIcon,null)))):React3.createElement(WithTooltip,{hasChrome:!1,trigger:"hover",tooltip:React3.createElement(TooltipNote,{note:"Start test run"})},React3.createElement(IconButton,{"aria-label":"Start test run",size:"medium",onClick:()=>store.send({type:"TRIGGER_RUN",payload:{storyIds:entry?api.findAllLeafStoryIds(entry.id):void 0,triggeredBy:entry?entry.type:"global"}})},React3.createElement(PlayHollowIcon,null))))),React3.createElement(Extras,null,React3.createElement(Row,null,React3.createElement(ListItem,{as:"label",title:"Interactions",icon:entry?null:React3.createElement(Checkbox,{checked:!0,disabled:!0})}),React3.createElement(WithTooltip,{hasChrome:!1,trigger:"hover",tooltip:React3.createElement(TooltipNote,{note:componentTestStatusLabel})},React3.createElement(IconButton,{size:"medium",disabled:componentTestStatusValueToStoryIds["status-value:error"].length===0&&componentTestStatusValueToStoryIds["status-value:warning"].length===0&&componentTestStatusValueToStoryIds["status-value:success"].length===0,onClick:()=>{openPanel({api,panelId:PANEL_ID,entryId:componentTestStatusValueToStoryIds["status-value:error"][0]??componentTestStatusValueToStoryIds["status-value:warning"][0]??componentTestStatusValueToStoryIds["status-value:success"][0]??entry?.id});}},React3.createElement(TestStatusIcon,{status:componentTestStatusIcon,"aria-label":componentTestStatusLabel,isRunning}),componentTestStatusValueToStoryIds["status-value:error"].length+componentTestStatusValueToStoryIds["status-value:warning"].length||null))),!entry&&React3.createElement(Row,null,React3.createElement(ListItem,{as:"label",title:watching?React3.createElement(Muted,null,"Coverage (unavailable)"):"Coverage",icon:React3.createElement(Checkbox,{checked:config.coverage,disabled:isRunning,onChange:()=>setStoreState(s=>({...s,config:{...s.config,coverage:!config.coverage}}))})}),React3.createElement(WithTooltip,{hasChrome:!1,trigger:"hover",tooltip:React3.createElement(TooltipNote,{note:watching?"Unavailable in watch mode":currentRun.triggeredBy&&!FULL_RUN_TRIGGERS.includes(currentRun.triggeredBy)?"Unavailable when running focused tests":isRunning?"Testing in progress":currentRun.coverageSummary?"View coverage report":fatalError?"Component tests crashed":"Run tests to calculate coverage"})},watching||currentRun.triggeredBy&&!FULL_RUN_TRIGGERS.includes(currentRun.triggeredBy)?React3.createElement(IconButton,{size:"medium",disabled:!0},React3.createElement(InfoIcon,{"aria-label":watching?"Coverage is unavailable in watch mode":"Coverage is unavailable when running focused tests"})):currentRun.coverageSummary?React3.createElement(IconButton,{asChild:!0,size:"medium"},React3.createElement("a",{href:"/coverage/index.html",target:"_blank","aria-label":"Open coverage report"},React3.createElement(TestStatusIcon,{isRunning,percentage:currentRun.coverageSummary.percentage,status:currentRun.coverageSummary.status,"aria-label":`Coverage status: ${currentRun.coverageSummary.status}`}),React3.createElement("span",{"aria-label":`${currentRun.coverageSummary.percentage} percent coverage`},currentRun.coverageSummary.percentage,"%"))):React3.createElement(IconButton,{size:"medium",disabled:!0},React3.createElement(TestStatusIcon,{isRunning,status:fatalError?"critical":"unknown","aria-label":"Coverage status: unknown"})))),hasA11yAddon&&React3.createElement(Row,null,React3.createElement(ListItem,{as:"label",title:"Accessibility",icon:entry?null:React3.createElement(Checkbox,{checked:config.a11y,disabled:isRunning,onChange:()=>setStoreState(s=>({...s,config:{...s.config,a11y:!config.a11y}}))})}),React3.createElement(WithTooltip,{hasChrome:!1,trigger:"hover",tooltip:React3.createElement(TooltipNote,{note:a11yStatusLabel})},React3.createElement(IconButton,{size:"medium",disabled:a11yStatusValueToStoryIds["status-value:error"].length===0&&a11yStatusValueToStoryIds["status-value:warning"].length===0&&a11yStatusValueToStoryIds["status-value:success"].length===0,onClick:()=>{openPanel({api,entryId:a11yStatusValueToStoryIds["status-value:error"][0]??a11yStatusValueToStoryIds["status-value:warning"][0]??a11yStatusValueToStoryIds["status-value:success"][0]??entry?.id,panelId:PANEL_ID2});}},React3.createElement(TestStatusIcon,{status:a11yStatusIcon,"aria-label":a11yStatusLabel,isRunning}),a11yStatusValueToStoryIds["status-value:error"].length+a11yStatusValueToStoryIds["status-value:warning"].length||null)))))};var SidebarContextMenu=({context,api})=>{let{testProviderState,componentTestStatusValueToStoryIds,a11yStatusValueToStoryIds,storeState,setStoreState}=useTestProvider(api,context.id);return React3.createElement(TestProviderRender,{api,entry:context,style:{minWidth:240},testProviderState,componentTestStatusValueToStoryIds,a11yStatusValueToStoryIds,storeState,setStoreState,isSettingsUpdated:!1})};addons.register(ADDON_ID3,api=>{if((globalThis.STORYBOOK_BUILDER||"").includes("vite")){let openPanel2=panelId=>{api.setSelectedPanel(panelId),api.togglePanel(!0);};componentTestStatusStore.onSelect(()=>{openPanel2(PANEL_ID);}),a11yStatusStore.onSelect(()=>{openPanel2(PANEL_ID2);}),testProviderStore.onRunAll(()=>{store.send({type:"TRIGGER_RUN",payload:{triggeredBy:"run-all"}});}),store.untilReady().then(()=>{store.setState(state=>({...state,indexUrl:new URL("index.json",window.location.href).toString()}));}),addons.add(TEST_PROVIDER_ID,{type:Addon_TypesEnum.experimental_TEST_PROVIDER,render:()=>{let[isModalOpen,setModalOpen]=useState(!1),{storeState,setStoreState,testProviderState,componentTestStatusValueToStoryIds,a11yStatusValueToStoryIds,isSettingsUpdated}=useTestProvider(api);return React3.createElement(GlobalErrorContext.Provider,{value:{isModalOpen,setModalOpen}},React3.createElement(TestProviderRender,{api,storeState,setStoreState,isSettingsUpdated,testProviderState,componentTestStatusValueToStoryIds,a11yStatusValueToStoryIds}),React3.createElement(GlobalErrorModal,{storeState,onRerun:()=>{setModalOpen(!1),store.send({type:"TRIGGER_RUN",payload:{triggeredBy:"global"}});}}))},sidebarContextMenu:({context})=>context.type==="docs"||context.type==="story"&&!context.tags.includes("test")?null:React3.createElement(SidebarContextMenu,{context,api})});}});
@@ -1,5 +1,6 @@
1
1
  import { Vitest, TestSpecification, TestProject, WorkspaceProject, ResolvedCoverageOptions } from 'vitest/node';
2
2
  import { ReportBase, Visitor, ReportNode } from 'istanbul-lib-report';
3
+ import { ThrottledFunction } from './function/throttle.js';
3
4
  import { TestResult } from 'vitest/dist/node.js';
4
5
  import { experimental_UniversalStore } from 'storybook/internal/core-server';
5
6
  import { API_HashEntry, PreviewAnnotation, StoryId, StatusStoreByTypeId, TestProviderStoreById } from 'storybook/internal/types';
@@ -158,10 +159,7 @@ declare class TestManager {
158
159
  * The throttling (500ms) is necessary as the channel would otherwise get overwhelmed with events,
159
160
  * eventually causing the manager and dev server to lose connection.
160
161
  */
161
- throttledFlushTestCaseResults: (() => void) & {
162
- cancel: () => void;
163
- flush: () => void;
164
- };
162
+ throttledFlushTestCaseResults: ThrottledFunction<() => void>;
165
163
  onTestRunEnd(endResult: {
166
164
  totalTestCount: number;
167
165
  unhandledErrors: VitestError[];
@@ -14,7 +14,7 @@ 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)),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;}};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,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+=`
18
18
 
19
19
  Please install the @vitest/${isIstanbul?"coverage-istanbul":"coverage-v8"} package to collect coverage
20
20
  `),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){let id=slash(changedFilePath);if(this.vitest?.logger.clearHighlightCache(id),this.updateLastChanged(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",this.runAffectedTestsAfterChange.bind(this)),this.vitest.vite.watcher.on("add",this.runAffectedTestsAfterChange.bind(this)),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(`
@@ -11,7 +11,7 @@ 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)),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;}};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}),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+=`
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}),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
15
 
16
16
  Please install the @vitest/${isIstanbul?"coverage-istanbul":"coverage-v8"} package to collect coverage
17
17
  `),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){let id=slash(changedFilePath);if(this.vitest?.logger.clearHighlightCache(id),this.updateLastChanged(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",this.runAffectedTestsAfterChange.bind(this)),this.vitest.vite.watcher.on("add",this.runAffectedTestsAfterChange.bind(this)),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(`