@storybook/addon-vitest 0.0.0-pr-31764-sha-f043b02d → 0.0.0-pr-31715-sha-e505ceac

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.
@@ -49,11 +49,11 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
49
49
  ${fromBody}`,toStringDescriptor=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),toStringName=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),changeToString=(to,from,name)=>{let withName=name===""?"":`with ${name.trim()}() `,newToString=wrappedToString.bind(null,withName,from.toString());Object.defineProperty(newToString,"name",toStringName),Object.defineProperty(to,"toString",{...toStringDescriptor,value:newToString});};function mimicFunction(to,from,{ignoreNonConfigurable=!1}={}){let{name}=to;for(let property of Reflect.ownKeys(from))copyProperty(to,from,property,ignoreNonConfigurable);return changePrototype(to,from),changeToString(to,from,name),to}var calledFunctions=new WeakMap,onetime=(function_,options={})=>{if(typeof function_!="function")throw new TypeError("Expected a function");let returnValue,callCount=0,functionName=function_.displayName||function_.name||"<anonymous>",onetime2=function(...arguments_){if(calledFunctions.set(onetime2,++callCount),callCount===1)returnValue=function_.apply(this,arguments_),function_=null;else if(options.throw===!0)throw new Error(`Function \`${functionName}\` can only be called once`);return returnValue};return mimicFunction(onetime2,function_),calledFunctions.set(onetime2,callCount),onetime2};onetime.callCount=function_=>{if(!calledFunctions.has(function_))throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`);return calledFunctions.get(function_)};var onetime_default=onetime;var getRealtimeSignals=()=>{let length=SIGRTMAX-SIGRTMIN+1;return Array.from({length},getRealtimeSignal)},getRealtimeSignal=(value,index)=>({name:`SIGRT${index+1}`,number:SIGRTMIN+index,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),SIGRTMIN=34,SIGRTMAX=64;var SIGNALS=[{name:"SIGHUP",number:1,action:"terminate",description:"Terminal closed",standard:"posix"},{name:"SIGINT",number:2,action:"terminate",description:"User interruption with CTRL-C",standard:"ansi"},{name:"SIGQUIT",number:3,action:"core",description:"User interruption with CTRL-\\",standard:"posix"},{name:"SIGILL",number:4,action:"core",description:"Invalid machine instruction",standard:"ansi"},{name:"SIGTRAP",number:5,action:"core",description:"Debugger breakpoint",standard:"posix"},{name:"SIGABRT",number:6,action:"core",description:"Aborted",standard:"ansi"},{name:"SIGIOT",number:6,action:"core",description:"Aborted",standard:"bsd"},{name:"SIGBUS",number:7,action:"core",description:"Bus error due to misaligned, non-existing address or paging error",standard:"bsd"},{name:"SIGEMT",number:7,action:"terminate",description:"Command should be emulated but is not implemented",standard:"other"},{name:"SIGFPE",number:8,action:"core",description:"Floating point arithmetic error",standard:"ansi"},{name:"SIGKILL",number:9,action:"terminate",description:"Forced termination",standard:"posix",forced:!0},{name:"SIGUSR1",number:10,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGSEGV",number:11,action:"core",description:"Segmentation fault",standard:"ansi"},{name:"SIGUSR2",number:12,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGPIPE",number:13,action:"terminate",description:"Broken pipe or socket",standard:"posix"},{name:"SIGALRM",number:14,action:"terminate",description:"Timeout or timer",standard:"posix"},{name:"SIGTERM",number:15,action:"terminate",description:"Termination",standard:"ansi"},{name:"SIGSTKFLT",number:16,action:"terminate",description:"Stack is empty or overflowed",standard:"other"},{name:"SIGCHLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"posix"},{name:"SIGCLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"other"},{name:"SIGCONT",number:18,action:"unpause",description:"Unpaused",standard:"posix",forced:!0},{name:"SIGSTOP",number:19,action:"pause",description:"Paused",standard:"posix",forced:!0},{name:"SIGTSTP",number:20,action:"pause",description:'Paused using CTRL-Z or "suspend"',standard:"posix"},{name:"SIGTTIN",number:21,action:"pause",description:"Background process cannot read terminal input",standard:"posix"},{name:"SIGBREAK",number:21,action:"terminate",description:"User interruption with CTRL-BREAK",standard:"other"},{name:"SIGTTOU",number:22,action:"pause",description:"Background process cannot write to terminal output",standard:"posix"},{name:"SIGURG",number:23,action:"ignore",description:"Socket received out-of-band data",standard:"bsd"},{name:"SIGXCPU",number:24,action:"core",description:"Process timed out",standard:"bsd"},{name:"SIGXFSZ",number:25,action:"core",description:"File too big",standard:"bsd"},{name:"SIGVTALRM",number:26,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGPROF",number:27,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGWINCH",number:28,action:"ignore",description:"Terminal window size changed",standard:"bsd"},{name:"SIGIO",number:29,action:"terminate",description:"I/O is available",standard:"other"},{name:"SIGPOLL",number:29,action:"terminate",description:"Watched event",standard:"other"},{name:"SIGINFO",number:29,action:"ignore",description:"Request for process information",standard:"other"},{name:"SIGPWR",number:30,action:"terminate",description:"Device running out of power",standard:"systemv"},{name:"SIGSYS",number:31,action:"core",description:"Invalid system call",standard:"other"},{name:"SIGUNUSED",number:31,action:"terminate",description:"Invalid system call",standard:"other"}];var getSignals=()=>{let realtimeSignals=getRealtimeSignals();return [...SIGNALS,...realtimeSignals].map(normalizeSignal)},normalizeSignal=({name,number:defaultNumber,description,action,forced=!1,standard})=>{let{signals:{[name]:constantSignal}}=os.constants,supported=constantSignal!==void 0;return {name,number:supported?constantSignal:defaultNumber,description,supported,action,forced,standard}};var getSignalsByName=()=>{let signals2=getSignals();return Object.fromEntries(signals2.map(getSignalByName))},getSignalByName=({name,number,description,supported,action,forced,standard})=>[name,{name,number,description,supported,action,forced,standard}],signalsByName=getSignalsByName(),getSignalsByNumber=()=>{let signals2=getSignals(),length=65,signalsA=Array.from({length},(value,number)=>getSignalByNumber(number,signals2));return Object.assign({},...signalsA)},getSignalByNumber=(number,signals2)=>{let signal=findSignalByNumber(number,signals2);if(signal===void 0)return {};let{name,description,supported,action,forced,standard}=signal;return {[number]:{name,number,description,supported,action,forced,standard}}},findSignalByNumber=(number,signals2)=>{let signal=signals2.find(({name})=>os.constants.signals[name]===number);return signal!==void 0?signal:signals2.find(signalA=>signalA.number===number)};getSignalsByNumber();var getErrorPrefix=({timedOut,timeout,errorCode,signal,signalDescription,exitCode,isCanceled})=>timedOut?`timed out after ${timeout} milliseconds`:isCanceled?"was canceled":errorCode!==void 0?`failed with ${errorCode}`:signal!==void 0?`was killed with ${signal} (${signalDescription})`:exitCode!==void 0?`failed with exit code ${exitCode}`:"failed",makeError=({stdout,stderr,all,error:error2,signal,exitCode,command,escapedCommand,timedOut,isCanceled,killed,parsed:{options:{timeout,cwd:cwd2=process2__default.default.cwd()}}})=>{exitCode=exitCode===null?void 0:exitCode,signal=signal===null?void 0:signal;let signalDescription=signal===void 0?void 0:signalsByName[signal].description,errorCode=error2&&error2.code,execaMessage=`Command ${getErrorPrefix({timedOut,timeout,errorCode,signal,signalDescription,exitCode,isCanceled})}: ${command}`,isError=Object.prototype.toString.call(error2)==="[object Error]",shortMessage=isError?`${execaMessage}
50
50
  ${error2.message}`:execaMessage,message=[shortMessage,stderr,stdout].filter(Boolean).join(`
51
51
  `);return isError?(error2.originalMessage=error2.message,error2.message=message):error2=new Error(message),error2.shortMessage=shortMessage,error2.command=command,error2.escapedCommand=escapedCommand,error2.exitCode=exitCode,error2.signal=signal,error2.signalDescription=signalDescription,error2.stdout=stdout,error2.stderr=stderr,error2.cwd=cwd2,all!==void 0&&(error2.all=all),"bufferedData"in error2&&delete error2.bufferedData,error2.failed=!0,error2.timedOut=!!timedOut,error2.isCanceled=isCanceled,error2.killed=killed&&!timedOut,error2};var aliases=["stdin","stdout","stderr"],hasAlias=options=>aliases.some(alias=>options[alias]!==void 0),normalizeStdio=options=>{if(!options)return;let{stdio}=options;if(stdio===void 0)return aliases.map(alias=>options[alias]);if(hasAlias(options))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${aliases.map(alias=>`\`${alias}\``).join(", ")}`);if(typeof stdio=="string")return stdio;if(!Array.isArray(stdio))throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``);let length=Math.max(stdio.length,aliases.length);return Array.from({length},(value,index)=>stdio[index])};var signals=[];signals.push("SIGHUP","SIGINT","SIGTERM");process.platform!=="win32"&&signals.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&signals.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var processOk=process8=>!!process8&&typeof process8=="object"&&typeof process8.removeListener=="function"&&typeof process8.emit=="function"&&typeof process8.reallyExit=="function"&&typeof process8.listeners=="function"&&typeof process8.kill=="function"&&typeof process8.pid=="number"&&typeof process8.on=="function",kExitEmitter=Symbol.for("signal-exit emitter"),global2=globalThis,ObjectDefineProperty=Object.defineProperty.bind(Object),Emitter=class{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(global2[kExitEmitter])return global2[kExitEmitter];ObjectDefineProperty(global2,kExitEmitter,{value:this,writable:!1,enumerable:!1,configurable:!1});}on(ev,fn){this.listeners[ev].push(fn);}removeListener(ev,fn){let list=this.listeners[ev],i=list.indexOf(fn);i!==-1&&(i===0&&list.length===1?list.length=0:list.splice(i,1));}emit(ev,code,signal){if(this.emitted[ev])return !1;this.emitted[ev]=!0;let ret=!1;for(let fn of this.listeners[ev])ret=fn(code,signal)===!0||ret;return ev==="exit"&&(ret=this.emit("afterExit",code,signal)||ret),ret}},SignalExitBase=class{},signalExitWrap=handler=>({onExit(cb,opts){return handler.onExit(cb,opts)},load(){return handler.load()},unload(){return handler.unload()}}),SignalExitFallback=class extends SignalExitBase{onExit(){return ()=>{}}load(){}unload(){}},SignalExit=class extends SignalExitBase{#hupSig=process4.platform==="win32"?"SIGINT":"SIGHUP";#emitter=new Emitter;#process;#originalProcessEmit;#originalProcessReallyExit;#sigListeners={};#loaded=!1;constructor(process8){super(),this.#process=process8,this.#sigListeners={};for(let sig of signals)this.#sigListeners[sig]=()=>{let listeners=this.#process.listeners(sig),{count}=this.#emitter,p=process8;if(typeof p.__signal_exit_emitter__=="object"&&typeof p.__signal_exit_emitter__.count=="number"&&(count+=p.__signal_exit_emitter__.count),listeners.length===count){this.unload();let ret=this.#emitter.emit("exit",null,sig),s=sig==="SIGHUP"?this.#hupSig:sig;ret||process8.kill(process8.pid,s);}};this.#originalProcessReallyExit=process8.reallyExit,this.#originalProcessEmit=process8.emit;}onExit(cb,opts){if(!processOk(this.#process))return ()=>{};this.#loaded===!1&&this.load();let ev=opts?.alwaysLast?"afterExit":"exit";return this.#emitter.on(ev,cb),()=>{this.#emitter.removeListener(ev,cb),this.#emitter.listeners.exit.length===0&&this.#emitter.listeners.afterExit.length===0&&this.unload();}}load(){if(!this.#loaded){this.#loaded=!0,this.#emitter.count+=1;for(let sig of signals)try{let fn=this.#sigListeners[sig];fn&&this.#process.on(sig,fn);}catch{}this.#process.emit=(ev,...a)=>this.#processEmit(ev,...a),this.#process.reallyExit=code=>this.#processReallyExit(code);}}unload(){this.#loaded&&(this.#loaded=!1,signals.forEach(sig=>{let listener=this.#sigListeners[sig];if(!listener)throw new Error("Listener not defined for signal: "+sig);try{this.#process.removeListener(sig,listener);}catch{}}),this.#process.emit=this.#originalProcessEmit,this.#process.reallyExit=this.#originalProcessReallyExit,this.#emitter.count-=1);}#processReallyExit(code){return processOk(this.#process)?(this.#process.exitCode=code||0,this.#emitter.emit("exit",this.#process.exitCode,null),this.#originalProcessReallyExit.call(this.#process,this.#process.exitCode)):0}#processEmit(ev,...args){let og=this.#originalProcessEmit;if(ev==="exit"&&processOk(this.#process)){typeof args[0]=="number"&&(this.#process.exitCode=args[0]);let ret=og.call(this.#process,ev,...args);return this.#emitter.emit("exit",this.#process.exitCode,null),ret}else return og.call(this.#process,ev,...args)}},process4=globalThis.process,{onExit,load,unload}=signalExitWrap(processOk(process4)?new SignalExit(process4):new SignalExitFallback);var DEFAULT_FORCE_KILL_TIMEOUT=1e3*5,spawnedKill=(kill,signal="SIGTERM",options={})=>{let killResult=kill(signal);return setKillTimeout(kill,signal,options,killResult),killResult},setKillTimeout=(kill,signal,options,killResult)=>{if(!shouldForceKill(signal,options,killResult))return;let timeout=getForceKillAfterTimeout(options),t=setTimeout(()=>{kill("SIGKILL");},timeout);t.unref&&t.unref();},shouldForceKill=(signal,{forceKillAfterTimeout},killResult)=>isSigterm(signal)&&forceKillAfterTimeout!==!1&&killResult,isSigterm=signal=>signal===os__default.default.constants.signals.SIGTERM||typeof signal=="string"&&signal.toUpperCase()==="SIGTERM",getForceKillAfterTimeout=({forceKillAfterTimeout=!0})=>{if(forceKillAfterTimeout===!0)return DEFAULT_FORCE_KILL_TIMEOUT;if(!Number.isFinite(forceKillAfterTimeout)||forceKillAfterTimeout<0)throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${forceKillAfterTimeout}\` (${typeof forceKillAfterTimeout})`);return forceKillAfterTimeout},spawnedCancel=(spawned,context)=>{spawned.kill()&&(context.isCanceled=!0);},timeoutKill=(spawned,signal,reject)=>{spawned.kill(signal),reject(Object.assign(new Error("Timed out"),{timedOut:!0,signal}));},setupTimeout=(spawned,{timeout,killSignal="SIGTERM"},spawnedPromise)=>{if(timeout===0||timeout===void 0)return spawnedPromise;let timeoutId,timeoutPromise=new Promise((resolve2,reject)=>{timeoutId=setTimeout(()=>{timeoutKill(spawned,killSignal,reject);},timeout);}),safeSpawnedPromise=spawnedPromise.finally(()=>{clearTimeout(timeoutId);});return Promise.race([timeoutPromise,safeSpawnedPromise])},validateTimeout=({timeout})=>{if(timeout!==void 0&&(!Number.isFinite(timeout)||timeout<0))throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`)},setExitHandler=async(spawned,{cleanup,detached},timedPromise)=>{if(!cleanup||detached)return timedPromise;let removeExitHandler=onExit(()=>{spawned.kill();});return timedPromise.finally(()=>{removeExitHandler();})};function isStream(stream){return stream!==null&&typeof stream=="object"&&typeof stream.pipe=="function"}function isWritableStream(stream){return isStream(stream)&&stream.writable!==!1&&typeof stream._write=="function"&&typeof stream._writableState=="object"}var isExecaChildProcess=target=>target instanceof childProcess.ChildProcess&&typeof target.then=="function",pipeToTarget=(spawned,streamName,target)=>{if(typeof target=="string")return spawned[streamName].pipe(fs.createWriteStream(target)),spawned;if(isWritableStream(target))return spawned[streamName].pipe(target),spawned;if(!isExecaChildProcess(target))throw new TypeError("The second argument must be a string, a stream or an Execa child process.");if(!isWritableStream(target.stdin))throw new TypeError("The target child process's stdin must be available.");return spawned[streamName].pipe(target.stdin),target},addPipeMethods=spawned=>{spawned.stdout!==null&&(spawned.pipeStdout=pipeToTarget.bind(void 0,spawned,"stdout")),spawned.stderr!==null&&(spawned.pipeStderr=pipeToTarget.bind(void 0,spawned,"stderr")),spawned.all!==void 0&&(spawned.pipeAll=pipeToTarget.bind(void 0,spawned,"all"));};var getStreamContents=async(stream,{init,convertChunk,getSize,truncateChunk,addChunk,getFinalChunk,finalize},{maxBuffer=Number.POSITIVE_INFINITY}={})=>{if(!isAsyncIterable(stream))throw new Error("The first argument must be a Readable, a ReadableStream, or an async iterable.");let state=init();state.length=0;try{for await(let chunk of stream){let chunkType=getChunkType(chunk),convertedChunk=convertChunk[chunkType](chunk,state);appendChunk({convertedChunk,state,getSize,truncateChunk,addChunk,maxBuffer});}return appendFinalChunk({state,convertChunk,getSize,truncateChunk,addChunk,getFinalChunk,maxBuffer}),finalize(state)}catch(error2){throw error2.bufferedData=finalize(state),error2}},appendFinalChunk=({state,getSize,truncateChunk,addChunk,getFinalChunk,maxBuffer})=>{let convertedChunk=getFinalChunk(state);convertedChunk!==void 0&&appendChunk({convertedChunk,state,getSize,truncateChunk,addChunk,maxBuffer});},appendChunk=({convertedChunk,state,getSize,truncateChunk,addChunk,maxBuffer})=>{let chunkSize=getSize(convertedChunk),newLength=state.length+chunkSize;if(newLength<=maxBuffer){addNewChunk(convertedChunk,state,addChunk,newLength);return}let truncatedChunk=truncateChunk(convertedChunk,maxBuffer-state.length);throw truncatedChunk!==void 0&&addNewChunk(truncatedChunk,state,addChunk,maxBuffer),new MaxBufferError},addNewChunk=(convertedChunk,state,addChunk,newLength)=>{state.contents=addChunk(convertedChunk,state,newLength),state.length=newLength;},isAsyncIterable=stream=>typeof stream=="object"&&stream!==null&&typeof stream[Symbol.asyncIterator]=="function",getChunkType=chunk=>{let typeOfChunk=typeof chunk;if(typeOfChunk==="string")return "string";if(typeOfChunk!=="object"||chunk===null)return "others";if(globalThis.Buffer?.isBuffer(chunk))return "buffer";let prototypeName=objectToString.call(chunk);return prototypeName==="[object ArrayBuffer]"?"arrayBuffer":prototypeName==="[object DataView]"?"dataView":Number.isInteger(chunk.byteLength)&&Number.isInteger(chunk.byteOffset)&&objectToString.call(chunk.buffer)==="[object ArrayBuffer]"?"typedArray":"others"},{toString:objectToString}=Object.prototype,MaxBufferError=class extends Error{name="MaxBufferError";constructor(){super("maxBuffer exceeded");}};var identity=value=>value,noop=()=>{},getContentsProp=({contents})=>contents,throwObjectStream=chunk=>{throw new Error(`Streams in object mode are not supported: ${String(chunk)}`)},getLengthProp=convertedChunk=>convertedChunk.length;async function getStreamAsArrayBuffer(stream,options){return getStreamContents(stream,arrayBufferMethods,options)}var initArrayBuffer=()=>({contents:new ArrayBuffer(0)}),useTextEncoder=chunk=>textEncoder.encode(chunk),textEncoder=new TextEncoder,useUint8Array=chunk=>new Uint8Array(chunk),useUint8ArrayWithOffset=chunk=>new Uint8Array(chunk.buffer,chunk.byteOffset,chunk.byteLength),truncateArrayBufferChunk=(convertedChunk,chunkSize)=>convertedChunk.slice(0,chunkSize),addArrayBufferChunk=(convertedChunk,{contents,length:previousLength},length)=>{let newContents=hasArrayBufferResize()?resizeArrayBuffer(contents,length):resizeArrayBufferSlow(contents,length);return new Uint8Array(newContents).set(convertedChunk,previousLength),newContents},resizeArrayBufferSlow=(contents,length)=>{if(length<=contents.byteLength)return contents;let arrayBuffer=new ArrayBuffer(getNewContentsLength(length));return new Uint8Array(arrayBuffer).set(new Uint8Array(contents),0),arrayBuffer},resizeArrayBuffer=(contents,length)=>{if(length<=contents.maxByteLength)return contents.resize(length),contents;let arrayBuffer=new ArrayBuffer(length,{maxByteLength:getNewContentsLength(length)});return new Uint8Array(arrayBuffer).set(new Uint8Array(contents),0),arrayBuffer},getNewContentsLength=length=>SCALE_FACTOR**Math.ceil(Math.log(length)/Math.log(SCALE_FACTOR)),SCALE_FACTOR=2,finalizeArrayBuffer=({contents,length})=>hasArrayBufferResize()?contents:contents.slice(0,length),hasArrayBufferResize=()=>"resize"in ArrayBuffer.prototype,arrayBufferMethods={init:initArrayBuffer,convertChunk:{string:useTextEncoder,buffer:useUint8Array,arrayBuffer:useUint8Array,dataView:useUint8ArrayWithOffset,typedArray:useUint8ArrayWithOffset,others:throwObjectStream},getSize:getLengthProp,truncateChunk:truncateArrayBufferChunk,addChunk:addArrayBufferChunk,getFinalChunk:noop,finalize:finalizeArrayBuffer};async function getStreamAsBuffer(stream,options){if(!("Buffer"in globalThis))throw new Error("getStreamAsBuffer() is only supported in Node.js");try{return arrayBufferToNodeBuffer(await getStreamAsArrayBuffer(stream,options))}catch(error2){throw error2.bufferedData!==void 0&&(error2.bufferedData=arrayBufferToNodeBuffer(error2.bufferedData)),error2}}var arrayBufferToNodeBuffer=arrayBuffer=>globalThis.Buffer.from(arrayBuffer);async function getStreamAsString(stream,options){return getStreamContents(stream,stringMethods,options)}var initString=()=>({contents:"",textDecoder:new TextDecoder}),useTextDecoder=(chunk,{textDecoder})=>textDecoder.decode(chunk,{stream:!0}),addStringChunk=(convertedChunk,{contents})=>contents+convertedChunk,truncateStringChunk=(convertedChunk,chunkSize)=>convertedChunk.slice(0,chunkSize),getFinalStringChunk=({textDecoder})=>{let finalChunk=textDecoder.decode();return finalChunk===""?void 0:finalChunk},stringMethods={init:initString,convertChunk:{string:identity,buffer:useTextDecoder,arrayBuffer:useTextDecoder,dataView:useTextDecoder,typedArray:useTextDecoder,others:throwObjectStream},getSize:getLengthProp,truncateChunk:truncateStringChunk,addChunk:addStringChunk,getFinalChunk:getFinalStringChunk,finalize:getContentsProp};var import_merge_stream=__toESM(require_merge_stream(),1),validateInputOptions=input=>{if(input!==void 0)throw new TypeError("The `input` and `inputFile` options cannot be both set.")},getInput=({input,inputFile})=>typeof inputFile!="string"?input:(validateInputOptions(input),fs.createReadStream(inputFile)),handleInput=(spawned,options)=>{let input=getInput(options);input!==void 0&&(isStream(input)?input.pipe(spawned.stdin):spawned.stdin.end(input));},makeAllStream=(spawned,{all})=>{if(!all||!spawned.stdout&&!spawned.stderr)return;let mixed=(0, import_merge_stream.default)();return spawned.stdout&&mixed.add(spawned.stdout),spawned.stderr&&mixed.add(spawned.stderr),mixed},getBufferedData=async(stream,streamPromise)=>{if(!(!stream||streamPromise===void 0)){await promises.setTimeout(0),stream.destroy();try{return await streamPromise}catch(error2){return error2.bufferedData}}},getStreamPromise=(stream,{encoding,buffer,maxBuffer})=>{if(!(!stream||!buffer))return encoding==="utf8"||encoding==="utf-8"?getStreamAsString(stream,{maxBuffer}):encoding===null||encoding==="buffer"?getStreamAsBuffer(stream,{maxBuffer}):applyEncoding(stream,maxBuffer,encoding)},applyEncoding=async(stream,maxBuffer,encoding)=>(await getStreamAsBuffer(stream,{maxBuffer})).toString(encoding),getSpawnedResult=async({stdout,stderr,all},{encoding,buffer,maxBuffer},processDone)=>{let stdoutPromise=getStreamPromise(stdout,{encoding,buffer,maxBuffer}),stderrPromise=getStreamPromise(stderr,{encoding,buffer,maxBuffer}),allPromise=getStreamPromise(all,{encoding,buffer,maxBuffer:maxBuffer*2});try{return await Promise.all([processDone,stdoutPromise,stderrPromise,allPromise])}catch(error2){return Promise.all([{error:error2,signal:error2.signal,timedOut:error2.timedOut},getBufferedData(stdout,stdoutPromise),getBufferedData(stderr,stderrPromise),getBufferedData(all,allPromise)])}};var nativePromisePrototype=(async()=>{})().constructor.prototype,descriptors=["then","catch","finally"].map(property=>[property,Reflect.getOwnPropertyDescriptor(nativePromisePrototype,property)]),mergePromise=(spawned,promise)=>{for(let[property,descriptor]of descriptors){let value=typeof promise=="function"?(...args)=>Reflect.apply(descriptor.value,promise(),args):descriptor.value.bind(promise);Reflect.defineProperty(spawned,property,{...descriptor,value});}},getSpawnedPromise=spawned=>new Promise((resolve2,reject)=>{spawned.on("exit",(exitCode,signal)=>{resolve2({exitCode,signal});}),spawned.on("error",error2=>{reject(error2);}),spawned.stdin&&spawned.stdin.on("error",error2=>{reject(error2);});});var normalizeArgs=(file,args=[])=>Array.isArray(args)?[file,...args]:[file],NO_ESCAPE_REGEXP=/^[\w.-]+$/,escapeArg=arg=>typeof arg!="string"||NO_ESCAPE_REGEXP.test(arg)?arg:`"${arg.replaceAll('"','\\"')}"`,joinCommand=(file,args)=>normalizeArgs(file,args).join(" "),getEscapedCommand=(file,args)=>normalizeArgs(file,args).map(arg=>escapeArg(arg)).join(" ");var verboseDefault=util.debuglog("execa").enabled,padField=(field,padding)=>String(field).padStart(padding,"0"),getTimestamp=()=>{let date=new Date;return `${padField(date.getHours(),2)}:${padField(date.getMinutes(),2)}:${padField(date.getSeconds(),2)}.${padField(date.getMilliseconds(),3)}`},logCommand=(escapedCommand,{verbose})=>{verbose&&process2__default.default.stderr.write(`[${getTimestamp()}] ${escapedCommand}
52
- `);};var DEFAULT_MAX_BUFFER=1e3*1e3*100,getEnv=({env:envOption,extendEnv,preferLocal,localDir,execPath})=>{let env=extendEnv?{...process2__default.default.env,...envOption}:envOption;return preferLocal?npmRunPathEnv({env,cwd:localDir,execPath}):env},handleArguments=(file,args,options={})=>{let parsed=import_cross_spawn.default._parse(file,args,options);return file=parsed.command,args=parsed.args,options=parsed.options,options={maxBuffer:DEFAULT_MAX_BUFFER,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:options.cwd||process2__default.default.cwd(),execPath:process2__default.default.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:verboseDefault,...options},options.env=getEnv(options),options.stdio=normalizeStdio(options),process2__default.default.platform==="win32"&&path__default.default.basename(file,".exe")==="cmd"&&args.unshift("/q"),{file,args,options,parsed}},handleOutput=(options,value,error2)=>typeof value!="string"&&!buffer.Buffer.isBuffer(value)?error2===void 0?void 0:"":options.stripFinalNewline?stripFinalNewline(value):value;function execa(file,args,options){let parsed=handleArguments(file,args,options),command=joinCommand(file,args),escapedCommand=getEscapedCommand(file,args);logCommand(escapedCommand,parsed.options),validateTimeout(parsed.options);let spawned;try{spawned=childProcess__default.default.spawn(parsed.file,parsed.args,parsed.options);}catch(error2){let dummySpawned=new childProcess__default.default.ChildProcess,errorPromise=Promise.reject(makeError({error:error2,stdout:"",stderr:"",all:"",command,escapedCommand,parsed,timedOut:!1,isCanceled:!1,killed:!1}));return mergePromise(dummySpawned,errorPromise),dummySpawned}let spawnedPromise=getSpawnedPromise(spawned),timedPromise=setupTimeout(spawned,parsed.options,spawnedPromise),processDone=setExitHandler(spawned,parsed.options,timedPromise),context={isCanceled:!1};spawned.kill=spawnedKill.bind(null,spawned.kill.bind(spawned)),spawned.cancel=spawnedCancel.bind(null,spawned,context);let handlePromiseOnce=onetime_default(async()=>{let[{error:error2,exitCode,signal,timedOut},stdoutResult,stderrResult,allResult]=await getSpawnedResult(spawned,parsed.options,processDone),stdout=handleOutput(parsed.options,stdoutResult),stderr=handleOutput(parsed.options,stderrResult),all=handleOutput(parsed.options,allResult);if(error2||exitCode!==0||signal!==null){let returnedError=makeError({error:error2,exitCode,signal,stdout,stderr,all,command,escapedCommand,parsed,timedOut,isCanceled:(parsed.options.signal?parsed.options.signal.aborted:!1),killed:spawned.killed});if(!parsed.options.reject)return returnedError;throw returnedError}return {command,escapedCommand,exitCode:0,stdout,stderr,all,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}});return handleInput(spawned,parsed.options),spawned.all=makeAllStream(spawned,parsed.options),addPipeMethods(spawned),mergePromise(spawned,handlePromiseOnce),spawned}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(error2){if(error2 instanceof EndError)return error2.value;throw error2}}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=process2__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(path__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=path__default.default.resolve(toPath2(options.cwd)??""),{root}=path__default.default.parse(directory),stopAt=path__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(path__default.default.resolve(directory,foundPath)),directory===stopAt||matches.length>=limit))break;directory=path__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]:)?$/;var normalize=function(path6){if(path6.length===0)return ".";path6=normalizeWindowsPath(path6);let isUNCPath=path6.match(_UNC_REGEX),isPathAbsolute=isAbsolute(path6),trailingSeparator=path6[path6.length-1]==="/";return path6=normalizeString(path6,!isPathAbsolute),path6.length===0?isPathAbsolute?"/":trailingSeparator?"./":".":(trailingSeparator&&(path6+="/"),_DRIVE_LETTER_RE.test(path6)&&(path6+="/"),isUNCPath?isPathAbsolute?`//${path6}`:`//./${path6}`:isPathAbsolute&&!isAbsolute(path6)?`/${path6}`:path6)},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 path6=index>=0?arguments_[index]:cwd();!path6||path6.length===0||(resolvedPath=`${path6}/${resolvedPath}`,resolvedAbsolute=isAbsolute(path6));}return resolvedPath=normalizeString(resolvedPath,!resolvedAbsolute),resolvedAbsolute&&!isAbsolute(resolvedPath)?`/${resolvedPath}`:resolvedPath.length>0?resolvedPath:"."};function normalizeString(path6,allowAboveRoot){let res="",lastSegmentLength=0,lastSlash=-1,dots=0,char=null;for(let index=0;index<=path6.length;++index){if(index<path6.length)char=path6[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+=`/${path6.slice(lastSlash+1,index)}`:res=path6.slice(lastSlash+1,index),lastSegmentLength=index-lastSlash-1;lastSlash=index,dots=0;}else char==="."&&dots!==-1?++dots:dots=-1;}return res}var isAbsolute=function(p){return _IS_ABSOLUTE_RE.test(p)};var _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)?"/":".")};var import_picocolors=__toESM(require_picocolors()),import_semver=__toESM(require_semver2());var DOCUMENTATION_LINK2="writing-tests/integrations/vitest-addon";var SUPPORTED_FRAMEWORKS=["@storybook/nextjs","@storybook/nextjs-vite","@storybook/react-vite","@storybook/svelte-vite","@storybook/vue3-vite","@storybook/html-vite","@storybook/web-components-vite","@storybook/sveltekit","@storybook/react-native-web-vite"];var fancy=process.platform!=="win32"||process.env.CI||process.env.TERM==="xterm-256color",step=nodeLogger.colors.gray("\u203A");nodeLogger.colors.blue(fancy?"\u2139":"i");nodeLogger.colors.green(fancy?"\u2714":"\u221A");nodeLogger.colors.orange(fancy?"\u26A0":"\u203C");nodeLogger.colors.red(fancy?"\u2716":"\xD7");var baseOptions={borderStyle:"round",padding:1},print=(message,options)=>{nodeLogger.logger.line(1),nodeLogger.logger.logBox(message,{...baseOptions,...options});},printInfo=(title,message,options)=>print(message,{borderColor:"blue",title,...options}),printWarning=(title,message,options)=>print(message,{borderColor:"yellow",title,...options}),printError=(title,message,options)=>print(message,{borderColor:"red",title,...options}),printSuccess=(title,message,options)=>print(message,{borderColor:"green",title,...options});var loadTemplate=async(name,replacements)=>{let template=await fs4__namespace.readFile(join(dirname(__require.resolve("@storybook/addon-vitest/package.json")),"templates",name),"utf8");return Object.entries(replacements).forEach(([key,value])=>template=template.replace(key,value)),template},mergeProperties=(source,target)=>{for(let sourceProp of source)if(sourceProp.type==="ObjectProperty"){let targetProp=target.find(p=>sourceProp.key.type==="Identifier"&&p.type==="ObjectProperty"&&p.key.type==="Identifier"&&p.key.name===sourceProp.key.name);targetProp&&targetProp.type==="ObjectProperty"?sourceProp.value.type==="ObjectExpression"&&targetProp.value.type==="ObjectExpression"?mergeProperties(sourceProp.value.properties,targetProp.value.properties):sourceProp.value.type==="ArrayExpression"&&targetProp.value.type==="ArrayExpression"?targetProp.value.elements.push(...sourceProp.value.elements):targetProp.value=sourceProp.value:target.push(sourceProp);}},updateConfigFile=(source,target)=>{let updated=!1;for(let sourceNode of source.program.body)if(sourceNode.type==="ImportDeclaration"){if(!target.program.body.some(targetNode=>targetNode.type===sourceNode.type&&targetNode.specifiers.some(s=>s.local.name===sourceNode.specifiers[0].local.name))){let lastImport=target.program.body.findLastIndex(n=>n.type==="ImportDeclaration");target.program.body.splice(lastImport+1,0,sourceNode);}}else if(sourceNode.type==="VariableDeclaration"){if(!target.program.body.some(targetNode=>targetNode.type===sourceNode.type&&targetNode.declarations.some(d=>"name"in d.id&&"name"in sourceNode.declarations[0].id&&d.id.name===sourceNode.declarations[0].id.name))){let lastImport=target.program.body.findLastIndex(n=>n.type==="ImportDeclaration");target.program.body.splice(lastImport+1,0,sourceNode);}}else if(sourceNode.type==="ExportDefaultDeclaration"){let exportDefault=target.program.body.find(n=>n.type==="ExportDefaultDeclaration");if(exportDefault&&sourceNode.declaration.type==="CallExpression"&&sourceNode.declaration.arguments.length>0&&sourceNode.declaration.arguments[0].type==="ObjectExpression"){let{properties}=sourceNode.declaration.arguments[0];exportDefault.declaration.type==="ObjectExpression"?(mergeProperties(properties,exportDefault.declaration.properties),updated=!0):exportDefault.declaration.type==="CallExpression"&&exportDefault.declaration.callee.type==="Identifier"&&exportDefault.declaration.callee.name==="defineConfig"&&exportDefault.declaration.arguments[0]?.type==="ObjectExpression"&&(mergeProperties(properties,exportDefault.declaration.arguments[0].properties),updated=!0);}}return updated},updateWorkspaceFile=(source,target)=>{let updated=!1;for(let sourceNode of source.program.body)if(sourceNode.type==="ImportDeclaration"){if(!target.program.body.some(targetNode=>targetNode.type===sourceNode.type&&targetNode.source.value===sourceNode.source.value&&targetNode.specifiers.some(s=>s.local.name===sourceNode.specifiers[0].local.name))){let lastImport=target.program.body.findLastIndex(n=>n.type==="ImportDeclaration");target.program.body.splice(lastImport+1,0,sourceNode);}}else if(sourceNode.type==="VariableDeclaration"){if(!target.program.body.some(targetNode=>targetNode.type===sourceNode.type&&targetNode.declarations.some(d=>"name"in d.id&&"name"in sourceNode.declarations[0].id&&d.id.name===sourceNode.declarations[0].id.name))){let lastImport=target.program.body.findLastIndex(n=>n.type==="ImportDeclaration");target.program.body.splice(lastImport+1,0,sourceNode);}}else if(sourceNode.type==="ExportDefaultDeclaration"){let exportDefault=target.program.body.find(n=>n.type==="ExportDefaultDeclaration");if(exportDefault&&sourceNode.declaration.type==="CallExpression"&&sourceNode.declaration.arguments.length>0&&sourceNode.declaration.arguments[0].type==="ArrayExpression"&&sourceNode.declaration.arguments[0].elements.length>0){let{elements}=sourceNode.declaration.arguments[0];exportDefault.declaration.type==="ArrayExpression"?(exportDefault.declaration.elements.push(...elements),updated=!0):exportDefault.declaration.type==="CallExpression"&&exportDefault.declaration.callee.type==="Identifier"&&exportDefault.declaration.callee.name==="defineWorkspace"&&exportDefault.declaration.arguments[0]?.type==="ArrayExpression"&&(exportDefault.declaration.arguments[0].elements.push(...elements),updated=!0);}}return updated};function getAddonNames(mainConfig){return (mainConfig.addons||[]).map(addon=>{let name="";return typeof addon=="string"?name=addon:typeof addon=="object"&&(name=addon.name),name}).filter(item=>item!=null)}var ADDON_NAME="@storybook/addon-vitest",EXTENSIONS=[".ts",".tsx",".js",".jsx",".cts",".mts",".cjs",".mjs"],addonA11yName="@storybook/addon-a11y",findFile=async(basename2,extensions=EXTENSIONS)=>findUp(extensions.map(ext=>basename2+ext),{stopAt:common.getProjectRoot()});async function postInstall(options){printSuccess("\u{1F44B} Howdy!",tsDedent.dedent`
52
+ `);};var DEFAULT_MAX_BUFFER=1e3*1e3*100,getEnv=({env:envOption,extendEnv,preferLocal,localDir,execPath})=>{let env=extendEnv?{...process2__default.default.env,...envOption}:envOption;return preferLocal?npmRunPathEnv({env,cwd:localDir,execPath}):env},handleArguments=(file,args,options={})=>{let parsed=import_cross_spawn.default._parse(file,args,options);return file=parsed.command,args=parsed.args,options=parsed.options,options={maxBuffer:DEFAULT_MAX_BUFFER,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:options.cwd||process2__default.default.cwd(),execPath:process2__default.default.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:verboseDefault,...options},options.env=getEnv(options),options.stdio=normalizeStdio(options),process2__default.default.platform==="win32"&&path__default.default.basename(file,".exe")==="cmd"&&args.unshift("/q"),{file,args,options,parsed}},handleOutput=(options,value,error2)=>typeof value!="string"&&!buffer.Buffer.isBuffer(value)?error2===void 0?void 0:"":options.stripFinalNewline?stripFinalNewline(value):value;function execa(file,args,options){let parsed=handleArguments(file,args,options),command=joinCommand(file,args),escapedCommand=getEscapedCommand(file,args);logCommand(escapedCommand,parsed.options),validateTimeout(parsed.options);let spawned;try{spawned=childProcess__default.default.spawn(parsed.file,parsed.args,parsed.options);}catch(error2){let dummySpawned=new childProcess__default.default.ChildProcess,errorPromise=Promise.reject(makeError({error:error2,stdout:"",stderr:"",all:"",command,escapedCommand,parsed,timedOut:!1,isCanceled:!1,killed:!1}));return mergePromise(dummySpawned,errorPromise),dummySpawned}let spawnedPromise=getSpawnedPromise(spawned),timedPromise=setupTimeout(spawned,parsed.options,spawnedPromise),processDone=setExitHandler(spawned,parsed.options,timedPromise),context={isCanceled:!1};spawned.kill=spawnedKill.bind(null,spawned.kill.bind(spawned)),spawned.cancel=spawnedCancel.bind(null,spawned,context);let handlePromiseOnce=onetime_default(async()=>{let[{error:error2,exitCode,signal,timedOut},stdoutResult,stderrResult,allResult]=await getSpawnedResult(spawned,parsed.options,processDone),stdout=handleOutput(parsed.options,stdoutResult),stderr=handleOutput(parsed.options,stderrResult),all=handleOutput(parsed.options,allResult);if(error2||exitCode!==0||signal!==null){let returnedError=makeError({error:error2,exitCode,signal,stdout,stderr,all,command,escapedCommand,parsed,timedOut,isCanceled:(parsed.options.signal?parsed.options.signal.aborted:!1),killed:spawned.killed});if(!parsed.options.reject)return returnedError;throw returnedError}return {command,escapedCommand,exitCode:0,stdout,stderr,all,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}});return handleInput(spawned,parsed.options),spawned.all=makeAllStream(spawned,parsed.options),addPipeMethods(spawned),mergePromise(spawned,handlePromiseOnce),spawned}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(error2){if(error2 instanceof EndError)return error2.value;throw error2}}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=process2__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(path__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=path__default.default.resolve(toPath2(options.cwd)??""),{root}=path__default.default.parse(directory),stopAt=path__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(path__default.default.resolve(directory,foundPath)),directory===stopAt||matches.length>=limit))break;directory=path__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]:)?$/;var normalize=function(path6){if(path6.length===0)return ".";path6=normalizeWindowsPath(path6);let isUNCPath=path6.match(_UNC_REGEX),isPathAbsolute=isAbsolute(path6),trailingSeparator=path6[path6.length-1]==="/";return path6=normalizeString(path6,!isPathAbsolute),path6.length===0?isPathAbsolute?"/":trailingSeparator?"./":".":(trailingSeparator&&(path6+="/"),_DRIVE_LETTER_RE.test(path6)&&(path6+="/"),isUNCPath?isPathAbsolute?`//${path6}`:`//./${path6}`:isPathAbsolute&&!isAbsolute(path6)?`/${path6}`:path6)},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 path6=index>=0?arguments_[index]:cwd();!path6||path6.length===0||(resolvedPath=`${path6}/${resolvedPath}`,resolvedAbsolute=isAbsolute(path6));}return resolvedPath=normalizeString(resolvedPath,!resolvedAbsolute),resolvedAbsolute&&!isAbsolute(resolvedPath)?`/${resolvedPath}`:resolvedPath.length>0?resolvedPath:"."};function normalizeString(path6,allowAboveRoot){let res="",lastSegmentLength=0,lastSlash=-1,dots=0,char=null;for(let index=0;index<=path6.length;++index){if(index<path6.length)char=path6[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+=`/${path6.slice(lastSlash+1,index)}`:res=path6.slice(lastSlash+1,index),lastSegmentLength=index-lastSlash-1;lastSlash=index,dots=0;}else char==="."&&dots!==-1?++dots:dots=-1;}return res}var isAbsolute=function(p){return _IS_ABSOLUTE_RE.test(p)};var 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)?"/":".")};var import_picocolors=__toESM(require_picocolors()),import_semver=__toESM(require_semver2());var DOCUMENTATION_LINK2="writing-tests/integrations/vitest-addon";var SUPPORTED_FRAMEWORKS=["@storybook/nextjs","@storybook/nextjs-vite","@storybook/react-vite","@storybook/svelte-vite","@storybook/vue3-vite","@storybook/html-vite","@storybook/web-components-vite","@storybook/sveltekit","@storybook/react-native-web-vite"];var fancy=process.platform!=="win32"||process.env.CI||process.env.TERM==="xterm-256color",step=nodeLogger.colors.gray("\u203A");nodeLogger.colors.blue(fancy?"\u2139":"i");nodeLogger.colors.green(fancy?"\u2714":"\u221A");nodeLogger.colors.orange(fancy?"\u26A0":"\u203C");nodeLogger.colors.red(fancy?"\u2716":"\xD7");var baseOptions={borderStyle:"round",padding:1},print=(message,options)=>{nodeLogger.logger.line(1),nodeLogger.logger.logBox(message,{...baseOptions,...options});},printInfo=(title,message,options)=>print(message,{borderColor:"blue",title,...options});var printError=(title,message,options)=>print(message,{borderColor:"red",title,...options}),printSuccess=(title,message,options)=>print(message,{borderColor:"green",title,...options});var loadTemplate=async(name,replacements)=>{let template=await fs4__namespace.readFile(join(dirname(__require.resolve("@storybook/addon-vitest/package.json")),"templates",name),"utf8");return Object.entries(replacements).forEach(([key,value])=>template=template.replace(key,value)),template},mergeProperties=(source,target)=>{for(let sourceProp of source)if(sourceProp.type==="ObjectProperty"){let targetProp=target.find(p=>sourceProp.key.type==="Identifier"&&p.type==="ObjectProperty"&&p.key.type==="Identifier"&&p.key.name===sourceProp.key.name);targetProp&&targetProp.type==="ObjectProperty"?sourceProp.value.type==="ObjectExpression"&&targetProp.value.type==="ObjectExpression"?mergeProperties(sourceProp.value.properties,targetProp.value.properties):sourceProp.value.type==="ArrayExpression"&&targetProp.value.type==="ArrayExpression"?targetProp.value.elements.push(...sourceProp.value.elements):targetProp.value=sourceProp.value:target.push(sourceProp);}},updateConfigFile=(source,target)=>{let updated=!1;for(let sourceNode of source.program.body)if(sourceNode.type==="ImportDeclaration"){if(!target.program.body.some(targetNode=>targetNode.type===sourceNode.type&&targetNode.specifiers.some(s=>s.local.name===sourceNode.specifiers[0].local.name))){let lastImport=target.program.body.findLastIndex(n=>n.type==="ImportDeclaration");target.program.body.splice(lastImport+1,0,sourceNode);}}else if(sourceNode.type==="VariableDeclaration"){if(!target.program.body.some(targetNode=>targetNode.type===sourceNode.type&&targetNode.declarations.some(d=>"name"in d.id&&"name"in sourceNode.declarations[0].id&&d.id.name===sourceNode.declarations[0].id.name))){let lastImport=target.program.body.findLastIndex(n=>n.type==="ImportDeclaration");target.program.body.splice(lastImport+1,0,sourceNode);}}else if(sourceNode.type==="ExportDefaultDeclaration"){let exportDefault=target.program.body.find(n=>n.type==="ExportDefaultDeclaration");if(exportDefault&&sourceNode.declaration.type==="CallExpression"&&sourceNode.declaration.arguments.length>0&&sourceNode.declaration.arguments[0].type==="ObjectExpression"){let{properties}=sourceNode.declaration.arguments[0];exportDefault.declaration.type==="ObjectExpression"?(mergeProperties(properties,exportDefault.declaration.properties),updated=!0):exportDefault.declaration.type==="CallExpression"&&exportDefault.declaration.callee.type==="Identifier"&&exportDefault.declaration.callee.name==="defineConfig"&&exportDefault.declaration.arguments[0]?.type==="ObjectExpression"&&(mergeProperties(properties,exportDefault.declaration.arguments[0].properties),updated=!0);}}return updated},updateWorkspaceFile=(source,target)=>{let updated=!1;for(let sourceNode of source.program.body)if(sourceNode.type==="ImportDeclaration"){if(!target.program.body.some(targetNode=>targetNode.type===sourceNode.type&&targetNode.source.value===sourceNode.source.value&&targetNode.specifiers.some(s=>s.local.name===sourceNode.specifiers[0].local.name))){let lastImport=target.program.body.findLastIndex(n=>n.type==="ImportDeclaration");target.program.body.splice(lastImport+1,0,sourceNode);}}else if(sourceNode.type==="VariableDeclaration"){if(!target.program.body.some(targetNode=>targetNode.type===sourceNode.type&&targetNode.declarations.some(d=>"name"in d.id&&"name"in sourceNode.declarations[0].id&&d.id.name===sourceNode.declarations[0].id.name))){let lastImport=target.program.body.findLastIndex(n=>n.type==="ImportDeclaration");target.program.body.splice(lastImport+1,0,sourceNode);}}else if(sourceNode.type==="ExportDefaultDeclaration"){let exportDefault=target.program.body.find(n=>n.type==="ExportDefaultDeclaration");if(exportDefault&&sourceNode.declaration.type==="CallExpression"&&sourceNode.declaration.arguments.length>0&&sourceNode.declaration.arguments[0].type==="ArrayExpression"&&sourceNode.declaration.arguments[0].elements.length>0){let{elements}=sourceNode.declaration.arguments[0];exportDefault.declaration.type==="ArrayExpression"?(exportDefault.declaration.elements.push(...elements),updated=!0):exportDefault.declaration.type==="CallExpression"&&exportDefault.declaration.callee.type==="Identifier"&&exportDefault.declaration.callee.name==="defineWorkspace"&&exportDefault.declaration.arguments[0]?.type==="ArrayExpression"&&(exportDefault.declaration.arguments[0].elements.push(...elements),updated=!0);}}return updated};function getAddonNames(mainConfig){return (mainConfig.addons||[]).map(addon=>{let name="";return typeof addon=="string"?name=addon:typeof addon=="object"&&(name=addon.name),name}).filter(item=>item!=null)}var ADDON_NAME="@storybook/addon-vitest",EXTENSIONS=[".ts",".tsx",".js",".jsx",".cts",".mts",".cjs",".mjs"],addonA11yName="@storybook/addon-a11y",findFile=async(basename2,extensions=EXTENSIONS)=>findUp(extensions.map(ext=>basename2+ext),{stopAt:common.getProjectRoot()});async function postInstall(options){printSuccess("\u{1F44B} Howdy!",tsDedent.dedent`
53
53
  I'm the installation helper for ${nodeLogger.colors.pink(ADDON_NAME)}
54
54
 
55
55
  Hold on for a moment while I look at your project and get it set up...
56
- `);let packageManager=common.JsPackageManagerFactory.getPackageManager({force:options.packageManager}),info2=await getStorybookInfo(options),allDeps=packageManager.getAllDependencies(),dependencies=["vitest","@vitest/browser","playwright"].filter(p=>!allDeps[p]),vitestVersionSpecifier=await packageManager.getInstalledVersion("vitest"),coercedVitestVersion=vitestVersionSpecifier?(0, import_semver.coerce)(vitestVersionSpecifier):null,mainJsPath=common.serverResolve(resolve(options.configDir,"main")),config=await csfTools.readConfig(mainJsPath),hasCustomWebpackConfig=!!config.getFieldNode(["webpackFinal"]),isInteractive=process.stdout.isTTY&&!process.env.CI;info2.frameworkPackageName==="@storybook/nextjs"&&!hasCustomWebpackConfig&&(options.yes||!isInteractive?{migrateToNextjsVite:!!options.yes}:await prompts__default.default({type:"confirm",name:"migrateToNextjsVite",message:tsDedent.dedent`
56
+ `);let packageManager=common.JsPackageManagerFactory.getPackageManager({force:options.packageManager}),info2=await getStorybookInfo(options),allDeps=packageManager.getAllDependencies(),dependencies=["vitest","@vitest/browser","playwright"].filter(p=>!allDeps[p]),vitestVersionSpecifier=await packageManager.getInstalledVersion("vitest"),coercedVitestVersion=vitestVersionSpecifier?(0, import_semver.coerce)(vitestVersionSpecifier):null,isVitest3_2OrNewer=vitestVersionSpecifier?(0, import_semver.satisfies)(vitestVersionSpecifier,">=3.2.0"):!0,mainJsPath=common.serverResolve(resolve(options.configDir,"main")),config=await csfTools.readConfig(mainJsPath),hasCustomWebpackConfig=!!config.getFieldNode(["webpackFinal"]),isInteractive=process.stdout.isTTY&&!process.env.CI;info2.frameworkPackageName==="@storybook/nextjs"&&!hasCustomWebpackConfig&&(options.yes||!isInteractive?{migrateToNextjsVite:!!options.yes}:await prompts__default.default({type:"confirm",name:"migrateToNextjsVite",message:tsDedent.dedent`
57
57
  The addon requires the use of @storybook/nextjs-vite to work with Next.js.
58
58
  https://storybook.js.org/docs/next/${DOCUMENTATION_LINK2}#install-and-set-up
59
59
 
@@ -119,16 +119,13 @@ ${error2.message}`:execaMessage,message=[shortMessage,stderr,stdout].filter(Bool
119
119
 
120
120
  Please refer to the documentation to complete the setup manually:
121
121
  ${import_picocolors.default.cyan(`https://storybook.js.org/docs/next/${DOCUMENTATION_LINK2}#manual-setup`)}
122
- `),nodeLogger.logger.line(1);return}}else if(rootConfig){let target,updated,configFile=await fs4__namespace.readFile(rootConfig,"utf8");if(configFile.includes("workspace:")){let configTemplate=await loadTemplate("vitest.config.template.ts",{CONFIG_DIR:options.configDir,BROWSER_CONFIG:browserConfig,SETUP_FILE:relative(dirname(rootConfig),vitestSetupFile)}),source=babel.babelParse(configTemplate);target=babel.babelParse(configFile),updated=updateConfigFile(source,target);}if(target&&updated){nodeLogger.logger.line(1),nodeLogger.logger.plain(`${step} Updating your ${vitestConfigFile?"Vitest":"Vite"} config file:`),nodeLogger.logger.plain(nodeLogger.colors.gray(` ${rootConfig}`));let formattedContent=await common.formatFileContent(rootConfig,babel.generate(target).code);await fs4.writeFile(rootConfig,formattedContent);}else {printWarning("\u26A0\uFE0F Cannot update config file",tsDedent.dedent`
123
- Could not update your existing ${vitestConfigFile?"Vitest":"Vite"} config file:
124
- ${nodeLogger.colors.gray(rootConfig)}
122
+ `),nodeLogger.logger.line(1);return}}else if(rootConfig){let target,updated,configFile=await fs4__namespace.readFile(rootConfig,"utf8"),hasWorkspaceConfig=configFile.includes("workspace:"),hasProjectsConfig=configFile.includes("projects:"),configFileHasTypeReference=configFile.match(/\/\/\/\s*<reference\s+types=["']vitest\/config["']\s*\/>/),templateName=hasWorkspaceConfig?"vitest.config.template.ts":hasProjectsConfig||isVitest3_2OrNewer?"vitest.config.3.2.template.ts":null;if(templateName){let configTemplate=await loadTemplate(templateName,{CONFIG_DIR:options.configDir,BROWSER_CONFIG:browserConfig,SETUP_FILE:relative(dirname(rootConfig),vitestSetupFile)}),source=babel.babelParse(configFileHasTypeReference?configTemplate:`/// <reference types="vitest/config" />
123
+ `+configTemplate);target=babel.babelParse(configFile),updated=updateConfigFile(source,target);}if(target&&updated){nodeLogger.logger.line(1),nodeLogger.logger.plain(`${step} Updating your ${vitestConfigFile?"Vitest":"Vite"} config file:`),nodeLogger.logger.plain(nodeLogger.colors.gray(` ${rootConfig}`));let formattedContent=await common.formatFileContent(rootConfig,babel.generate(target).code);await fs4.writeFile(rootConfig,formattedContent);}else printError("\u{1F6A8} Oh no!",tsDedent.dedent`
124
+ We were unable to update your existing ${vitestConfigFile?"Vitest":"Vite"} config file
125
125
 
126
- Your existing config file cannot be safely updated, so instead a new Vitest
127
- workspace file will be created, extending from your config file.
128
-
129
- Please refer to the Vitest documentation to learn about the workspace file:
130
- ${import_picocolors.default.cyan("https://vitest.dev/guide/workspace.html")}
131
- `);let extension=extname(rootConfig).includes("ts")?".ts":".js",newWorkspaceFile=resolve(dirname(rootConfig),`vitest.workspace${extension}`),workspaceTemplate=await loadTemplate("vitest.workspace.template.ts",{ROOT_CONFIG:relative(dirname(newWorkspaceFile),rootConfig),EXTENDS_WORKSPACE:viteConfigFile?relative(dirname(newWorkspaceFile),viteConfigFile):"",CONFIG_DIR:options.configDir,BROWSER_CONFIG:browserConfig,SETUP_FILE:relative(dirname(newWorkspaceFile),vitestSetupFile)}).then(t=>t.replace(/\s+extends: '',/,""));nodeLogger.logger.line(1),nodeLogger.logger.plain(`${step} Creating a Vitest workspace file:`),nodeLogger.logger.plain(nodeLogger.colors.gray(` ${newWorkspaceFile}`));let formattedContent=await common.formatFileContent(newWorkspaceFile,workspaceTemplate);await fs4.writeFile(newWorkspaceFile,formattedContent);}}else {let newConfigFile=resolve(`vitest.config.${fileExtension}`),configTemplate=await loadTemplate("vitest.config.template.ts",{CONFIG_DIR:options.configDir,BROWSER_CONFIG:browserConfig,SETUP_FILE:relative(dirname(newConfigFile),vitestSetupFile)});nodeLogger.logger.line(1),nodeLogger.logger.plain(`${step} Creating a Vitest config file:`),nodeLogger.logger.plain(nodeLogger.colors.gray(` ${newConfigFile}`));let formattedContent=await common.formatFileContent(newConfigFile,configTemplate);await fs4.writeFile(newConfigFile,formattedContent);}if(info2.addons.find(addon=>addon.includes(addonA11yName)))try{nodeLogger.logger.plain(`${step} Setting up ${addonA11yName} for @storybook/addon-vitest:`);let command=["automigrate","addon-a11y-addon-test"];command.push("--loglevel","silent"),command.push("--yes","--skip-doctor"),options.packageManager&&command.push("--package-manager",options.packageManager),options.skipInstall&&command.push("--skip-install"),options.configDir!==".storybook"&&command.push("--config-dir",options.configDir),await execa("storybook",command,{stdio:"inherit"});}catch(e){printError("\u{1F6A8} Oh no!",tsDedent.dedent`
126
+ Please refer to the documentation to complete the setup manually:
127
+ ${import_picocolors.default.cyan("https://storybook.js.org/docs/writing-tests/integrations/vitest-addon#manual-setup")}
128
+ `);}else {let newConfigFile=resolve(`vitest.config.${fileExtension}`),configTemplate=await loadTemplate(isVitest3_2OrNewer?"vitest.config.3.2.template.ts":"vitest.config.template.ts",{CONFIG_DIR:options.configDir,BROWSER_CONFIG:browserConfig,SETUP_FILE:relative(dirname(newConfigFile),vitestSetupFile)});nodeLogger.logger.line(1),nodeLogger.logger.plain(`${step} Creating a Vitest config file:`),nodeLogger.logger.plain(nodeLogger.colors.gray(` ${newConfigFile}`));let formattedContent=await common.formatFileContent(newConfigFile,configTemplate);await fs4.writeFile(newConfigFile,formattedContent);}if(info2.addons.find(addon=>addon.includes(addonA11yName)))try{nodeLogger.logger.plain(`${step} Setting up ${addonA11yName} for @storybook/addon-vitest:`);let command=["automigrate","addon-a11y-addon-test"];command.push("--loglevel","silent"),command.push("--yes","--skip-doctor"),options.packageManager&&command.push("--package-manager",options.packageManager),options.skipInstall&&command.push("--skip-install"),options.configDir!==".storybook"&&command.push("--config-dir",options.configDir),await execa("storybook",command,{stdio:"inherit"});}catch(e){printError("\u{1F6A8} Oh no!",tsDedent.dedent`
132
129
  We have detected that you have ${addonA11yName} installed but could not automatically set it up for @storybook/addon-vitest:
133
130
 
134
131
  ${e instanceof Error?e.message:String(e)}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@storybook/addon-vitest",
3
- "version": "0.0.0-pr-31764-sha-f043b02d",
3
+ "version": "0.0.0-pr-31715-sha-e505ceac",
4
4
  "description": "Storybook addon for testing components",
5
5
  "keywords": [
6
6
  "storybook-addons",
@@ -124,7 +124,7 @@
124
124
  "peerDependencies": {
125
125
  "@vitest/browser": "^3.0.0",
126
126
  "@vitest/runner": "^3.0.0",
127
- "storybook": "^0.0.0-pr-31764-sha-f043b02d",
127
+ "storybook": "^0.0.0-pr-31715-sha-e505ceac",
128
128
  "vitest": "^3.0.0"
129
129
  },
130
130
  "peerDependenciesMeta": {
@@ -0,0 +1,30 @@
1
+ import path from 'node:path';
2
+ import { fileURLToPath } from 'node:url';
3
+
4
+ import { defineConfig } from 'vitest/config';
5
+
6
+ import { storybookTest } from '@storybook/addon-vitest/vitest-plugin';
7
+
8
+ const dirname =
9
+ typeof __dirname !== 'undefined' ? __dirname : path.dirname(fileURLToPath(import.meta.url));
10
+
11
+ // More info at: https://storybook.js.org/docs/next/writing-tests/integrations/vitest-addon
12
+ export default defineConfig({
13
+ test: {
14
+ projects: [
15
+ {
16
+ extends: true,
17
+ plugins: [
18
+ // The plugin will run tests for the stories defined in your Storybook config
19
+ // See options at: https://storybook.js.org/docs/next/writing-tests/integrations/vitest-addon#storybooktest
20
+ storybookTest({ configDir: path.join(dirname, 'CONFIG_DIR') }),
21
+ ],
22
+ test: {
23
+ name: 'storybook',
24
+ browser: BROWSER_CONFIG,
25
+ setupFiles: ['SETUP_FILE'],
26
+ },
27
+ },
28
+ ],
29
+ },
30
+ });