@storybook/core-server 8.1.0-beta.0 → 8.1.0-beta.1

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/index.js CHANGED
@@ -16,12 +16,12 @@ Content-Type: ${v.type||"application/octet-stream"}\r
16
16
  `));return{staticDir,staticPath,targetDir,targetEndpoint}};async function copyAllStaticFilesRelativeToMain(staticDirs,outputDir,configDir){let workingDir=process.cwd();return staticDirs?.reduce(async(acc,dir)=>{await acc;let staticDirAndTarget=typeof dir=="string"?dir:`${dir.from}:${dir.to}`,{staticPath:from,targetEndpoint:to}=await parseStaticDir((0,import_core_common2.getDirectoryFromWorkingDir)({configDir,workingDir,directory:staticDirAndTarget})),targetPath=(0,import_path3.join)(outputDir,to),skipPaths=["index.html","iframe.html"].map(f3=>(0,import_path3.join)(targetPath,f3));from.includes("node_modules")||import_node_logger3.logger.info(import_chalk3.default`=> Copying static files: {cyan ${print(from)}} at {cyan ${print(targetPath)}}`),await import_fs_extra3.default.copy(from,targetPath,{dereference:!0,preserveTimestamps:!0,filter:(_,dest)=>!skipPaths.includes(dest)})},Promise.resolve())}function print(p){return(0,import_path3.relative)(process.cwd(),p)}var import_server_errors=require("@storybook/core-events/server-errors"),import_node_url=require("url");async function getManagerBuilder(){return import("@storybook/builder-manager")}async function getPreviewBuilder(builderName,configDir){let builderPackage=require.resolve(["webpack5"].includes(builderName)?`@storybook/builder-${builderName}`:builderName,{paths:[configDir]});return await import((0,import_node_url.pathToFileURL)(builderPackage).href)}async function getBuilders({presets,configDir}){let{builder}=await presets.apply("core",{});if(!builder)throw new import_server_errors.MissingBuilderError;let builderName=typeof builder=="string"?builder:builder.name;return Promise.all([getPreviewBuilder(builderName,configDir),getManagerBuilder()])}var import_path5=require("path"),import_fs_extra4=require("fs-extra"),import_debounce=__toESM(require("lodash/debounce.js")),import_core_events=require("@storybook/core-events");var import_watchpack=__toESM(require("watchpack"));function slash(path6){return path6.startsWith("\\\\?\\")?path6:path6.replace(/\\/g,"/")}var import_fs=__toESM(require("fs")),import_path4=__toESM(require("path")),import_uniq=__toESM(require("lodash/uniq.js")),import_core_common3=require("@storybook/core-common"),isDirectory=directory=>{try{return import_fs.default.lstatSync(directory).isDirectory()}catch{return!1}};function toImportPath(relativePath){return relativePath.startsWith(".")?relativePath:`./${relativePath}`}function watchStorySpecifiers(specifiers,options,onInvalidate){let wp=new import_watchpack.default({followSymlinks:!1,ignored:["**/.git","**/node_modules"]});wp.watch({directories:(0,import_uniq.default)(specifiers.map(ns=>ns.directory))});async function onChangeOrRemove(watchpackPath,removed){let importPath=slash(watchpackPath.startsWith(".")?watchpackPath:`./${watchpackPath}`),matchingSpecifier=specifiers.find(ns=>ns.importPathMatcher.exec(importPath));if(matchingSpecifier){onInvalidate(matchingSpecifier,importPath,removed);return}let absolutePath=import_path4.default.join(options.workingDir,importPath);!removed&&isDirectory(absolutePath)&&await Promise.all(specifiers.filter(specifier=>importPath.startsWith(specifier.directory)).map(async specifier=>{let dirGlob=import_path4.default.join(options.workingDir,importPath,"**",import_path4.default.basename(specifier.files)),{globby}=await import("globby");(await globby(slash(dirGlob),(0,import_core_common3.commonGlobOptions)(dirGlob))).forEach(filePath=>{let fileImportPath=toImportPath(import_path4.default.relative(options.workingDir,filePath).replace(/\\/g,"/"));specifier.importPathMatcher.exec(fileImportPath)&&onInvalidate(specifier,fileImportPath,removed)})}))}return wp.on("change",async(filePath,mtime,explanation)=>{await onChangeOrRemove(filePath,!mtime)}),wp.on("remove",async(filePath,explanation)=>{await onChangeOrRemove(filePath,!0)}),()=>wp.close()}var import_watchpack2=__toESM(require("watchpack"));function watchConfig(configDir,onInvalidate){let wp=new import_watchpack2.default({followSymlinks:!1,ignored:["**/.git","**/node_modules"]});return wp.watch({directories:[configDir]}),wp.on("change",async(filePath,mtime,explanation)=>{await onInvalidate(filePath,!mtime)}),wp.on("remove",async(filePath,explanation)=>{await onInvalidate(filePath,!0)}),()=>wp.close()}var DEBOUNCE=100;async function extractStoriesJson(outputFile,initializedStoryIndexGenerator,transform){let storyIndex=await(await initializedStoryIndexGenerator).getIndex();await(0,import_fs_extra4.writeJSON)(outputFile,transform?transform(storyIndex):storyIndex)}function useStoriesJson({router:router2,initializedStoryIndexGenerator,workingDir=process.cwd(),configDir,serverChannel,normalizedStories}){let maybeInvalidate=(0,import_debounce.default)(()=>serverChannel.emit(import_core_events.STORY_INDEX_INVALIDATED),DEBOUNCE,{leading:!0});watchStorySpecifiers(normalizedStories,{workingDir},async(specifier,path6,removed)=>{(await initializedStoryIndexGenerator).invalidate(specifier,path6,removed),maybeInvalidate()}),configDir&&watchConfig(configDir,async filePath=>{(0,import_path5.basename)(filePath).startsWith("preview")&&((await initializedStoryIndexGenerator).invalidateAll(),maybeInvalidate())}),router2.use("/index.json",async(req,res)=>{try{let index=await(await initializedStoryIndexGenerator).getIndex();res.header("Content-Type","application/json"),res.send(JSON.stringify(index))}catch(err){res.status(500),res.send(err instanceof Error?err.toString():String(err))}})}var import_fs_extra5=require("fs-extra"),import_telemetry=require("@storybook/telemetry");async function extractStorybookMetadata(outputFile,configDir){let storybookMetadata=await(0,import_telemetry.getStorybookMetadata)(configDir);await(0,import_fs_extra5.writeJSON)(outputFile,storybookMetadata)}function useStorybookMetadata(router2,configDir){router2.use("/project.json",async(req,res)=>{let storybookMetadata=await(0,import_telemetry.getStorybookMetadata)(configDir);res.header("Content-Type","application/json"),res.send(JSON.stringify(storybookMetadata))})}var import_path7=__toESM(require("path")),import_chalk4=__toESM(require("chalk")),import_fs_extra6=__toESM(require("fs-extra"));var import_tiny_invariant=__toESM(require("tiny-invariant")),import_preview_api=require("@storybook/preview-api"),import_core_common4=require("@storybook/core-common"),import_node_logger4=require("@storybook/node-logger"),import_csf_tools=require("@storybook/csf-tools"),import_csf=require("@storybook/csf"),import_docs_mdx=require("@storybook/docs-mdx"),import_ts_dedent2=__toESM(require("ts-dedent"));var import_path6=require("path");function autoName(mdxImportPath,csfImportPath,defaultName){let mdxBasename=(0,import_path6.basename)(mdxImportPath),csfBasename=(0,import_path6.basename)(csfImportPath),[mdxFilename]=mdxBasename.split("."),[csfFilename]=csfBasename.split(".");return mdxFilename===csfFilename?defaultName:mdxFilename}var IndexingError=class extends Error{constructor(message,importPaths,stack){super(),this.message=message,this.importPaths=importPaths,stack&&(this.stack=stack)}pathsString(){return this.importPaths.length===1?`${slash(this.importPaths[0])}`:`${this.importPaths.map(slash).join(",")}`}toString(){return`${this.pathsString()}: ${this.message}`}},MultipleIndexingError=class extends Error{constructor(indexingErrors){super();this.indexingErrors=indexingErrors;if(this.indexingErrors.length===0)throw new Error("Unexpected empty error list");if(this.indexingErrors.length===1){let[err]=this.indexingErrors;this.message=`Unable to index ${err.pathsString()}`}else this.message=`Unable to index files:
17
17
  ${this.indexingErrors.map(err=>`- ${err}`).join(`
18
18
  `)}`}toString(){return this.indexingErrors.length===1?`${this.message}:
19
- ${this.indexingErrors[0].stack}`:this.message}};var AUTODOCS_TAG="autodocs",STORIES_MDX_TAG="stories-mdx",UNATTACHED_MDX_TAG="unattached-mdx",ATTACHED_MDX_TAG="attached-mdx",PLAY_FN_TAG="play-fn";function isMdxEntry({tags}){return tags?.includes(UNATTACHED_MDX_TAG)||tags?.includes(ATTACHED_MDX_TAG)}var makeAbsolute=(otherImport,normalizedPath,workingDir)=>otherImport.startsWith(".")?slash(import_path7.default.resolve(workingDir,(0,import_core_common4.normalizeStoryPath)(import_path7.default.join(import_path7.default.dirname(normalizedPath),otherImport)))):otherImport,StoryIndexGenerator=class{constructor(specifiers,options){this.specifiers=specifiers;this.options=options;this.specifierToCache=new Map}async initialize(){(await Promise.all(this.specifiers.map(async specifier=>{let pathToSubIndex={},fullGlob=slash(import_path7.default.join(this.options.workingDir,specifier.directory,specifier.files)),{globby}=await import("globby"),files=await globby(fullGlob,(0,import_core_common4.commonGlobOptions)(fullGlob));return files.length===0&&import_node_logger4.once.warn(`No story files found for the specified pattern: ${import_chalk4.default.blue(import_path7.default.join(specifier.directory,specifier.files))}`),files.sort().forEach(absolutePath=>{let ext=import_path7.default.extname(absolutePath);if(ext===".storyshot"){let relativePath=import_path7.default.relative(this.options.workingDir,absolutePath);import_node_logger4.logger.info(`Skipping ${ext} file ${relativePath}`);return}pathToSubIndex[absolutePath]=!1}),[specifier,pathToSubIndex]}))).forEach(([specifier,cache3])=>this.specifierToCache.set(specifier,cache3));let previewCode=await this.getPreviewCode(),projectTags=previewCode?this.getProjectTags(previewCode):[];await this.ensureExtracted({projectTags})}async updateExtracted(updater,overwrite=!1){await Promise.all(this.specifiers.map(async specifier=>{let entry=this.specifierToCache.get(specifier);return(0,import_tiny_invariant.default)(entry,`specifier does not have a matching cache entry in specifierToCache: ${JSON.stringify(specifier)}`),Promise.all(Object.keys(entry).map(async absolutePath=>{if(!(entry[absolutePath]&&!overwrite))try{entry[absolutePath]=await updater(specifier,absolutePath,entry[absolutePath])}catch(err){let relativePath=`.${import_path7.default.sep}${import_path7.default.relative(this.options.workingDir,absolutePath)}`;entry[absolutePath]={type:"error",err:new IndexingError(err instanceof Error?err.message:String(err),[relativePath],err instanceof Error?err.stack:void 0)}}}))}))}isDocsMdx(absolutePath){return/(?<!\.stories)\.mdx$/i.test(absolutePath)}async ensureExtracted({projectTags}){return await this.updateExtracted(async(specifier,absolutePath)=>this.isDocsMdx(absolutePath)?!1:this.extractStories(specifier,absolutePath,projectTags)),await this.updateExtracted(async(specifier,absolutePath)=>this.extractDocs(specifier,absolutePath,projectTags)),this.specifiers.flatMap(specifier=>{let cache3=this.specifierToCache.get(specifier);return(0,import_tiny_invariant.default)(cache3,`specifier does not have a matching cache entry in specifierToCache: ${JSON.stringify(specifier)}`),Object.values(cache3).flatMap(entry=>entry?entry.type==="docs"?[entry]:entry.type==="error"?[entry]:entry.entries.map(item=>{if(item.type==="docs")return item;let{metaId,...existing}=item;return existing}):[])})}findDependencies(absoluteImports){return[...this.specifierToCache.values()].flatMap(cache3=>Object.entries(cache3).filter(([fileName,cacheEntry])=>!cacheEntry||cacheEntry.type!=="stories"?!1:!!absoluteImports.find(storyImport=>fileName.match(new RegExp(`^${storyImport}(\\.[^.]+)?$`)))).map(([_,cacheEntry])=>cacheEntry))}async extractStories(specifier,absolutePath,projectTags=[]){let relativePath=import_path7.default.relative(this.options.workingDir,absolutePath),importPath=slash((0,import_core_common4.normalizeStoryPath)(relativePath)),defaultMakeTitle=userTitle=>{let title=(0,import_preview_api.userOrAutoTitleFromSpecifier)(importPath,specifier,userTitle);return(0,import_tiny_invariant.default)(title,"makeTitle created an undefined title. This happens when the fileName doesn't match any specifier from main.js"),title},indexer=this.options.indexers.find(ind=>ind.test.exec(absolutePath));(0,import_tiny_invariant.default)(indexer,`No matching indexer found for ${absolutePath}`);let indexInputs=await indexer.createIndex(absolutePath,{makeTitle:defaultMakeTitle}),entries=indexInputs.map(input=>{let name=input.name??(0,import_csf.storyNameFromExport)(input.exportName),title=input.title??defaultMakeTitle(),id=input.__id??(0,import_csf.toId)(input.metaId??title,(0,import_csf.storyNameFromExport)(input.exportName)),tags=(0,import_csf.combineTags)(...projectTags,...input.tags??[]);return{type:"story",id,metaId:input.metaId,name,title,importPath,tags}}),hasAutodocsTag=entries.some(entry=>entry.tags.includes(AUTODOCS_TAG)),isStoriesMdx=entries.some(entry=>entry.tags.includes(STORIES_MDX_TAG));if((hasAutodocsTag&&this.options.docs.autodocs!==!1||isStoriesMdx)&&this.options.build?.test?.disableAutoDocs!==!0){let name=this.options.docs.defaultName??"Docs",{metaId}=indexInputs[0],{title}=entries[0],id=(0,import_csf.toId)(metaId??title,name),tags=(0,import_csf.combineTags)(...projectTags,...indexInputs[0].tags??[]);entries.unshift({id,title,name,importPath,type:"docs",tags,storiesImports:[]})}return{entries:entries.filter(entry=>!(entry.type==="story"&&entry.tags.includes("stories-mdx-docsOnly"))),dependents:[],type:"stories"}}async extractDocs(specifier,absolutePath,projectTags=[]){let relativePath=import_path7.default.relative(this.options.workingDir,absolutePath);try{let normalizedPath=(0,import_core_common4.normalizeStoryPath)(relativePath),importPath=slash(normalizedPath),content=await import_fs_extra6.default.readFile(absolutePath,"utf8"),result=(0,import_docs_mdx.analyze)(content);if(result.isTemplate)return!1;let absoluteImports=result.imports.map(p=>makeAbsolute(p,normalizedPath,this.options.workingDir)),dependencies=this.findDependencies(absoluteImports),sortedDependencies=dependencies,csfEntry;if(result.of){let absoluteOf=makeAbsolute(result.of,normalizedPath,this.options.workingDir);dependencies.forEach(dep=>{if(dep.entries.length>0){let first=dep.entries.find(e2=>e2.type!=="docs");import_path7.default.normalize(import_path7.default.resolve(this.options.workingDir,first.importPath)).startsWith(import_path7.default.normalize(absoluteOf))&&(csfEntry=first)}sortedDependencies=[dep,...dependencies.filter(d=>d!==dep)]}),(0,import_tiny_invariant.default)(csfEntry,import_ts_dedent2.default`Could not find or load CSF file at path "${result.of}" referenced by \`of={}\` in docs file "${relativePath}".
19
+ ${this.indexingErrors[0].stack}`:this.message}};var AUTODOCS_TAG="autodocs",STORIES_MDX_TAG="stories-mdx",UNATTACHED_MDX_TAG="unattached-mdx",ATTACHED_MDX_TAG="attached-mdx",PLAY_FN_TAG="play-fn";function isMdxEntry({tags}){return tags?.includes(UNATTACHED_MDX_TAG)||tags?.includes(ATTACHED_MDX_TAG)}var makeAbsolute=(otherImport,normalizedPath,workingDir)=>otherImport.startsWith(".")?slash(import_path7.default.resolve(workingDir,(0,import_core_common4.normalizeStoryPath)(import_path7.default.join(import_path7.default.dirname(normalizedPath),otherImport)))):otherImport,StoryIndexGenerator=class{constructor(specifiers,options){this.specifiers=specifiers;this.options=options;this.specifierToCache=new Map}async initialize(){(await Promise.all(this.specifiers.map(async specifier=>{let pathToSubIndex={},fullGlob=slash(import_path7.default.join(this.options.workingDir,specifier.directory,specifier.files)),{globby}=await import("globby"),files=await globby(fullGlob,(0,import_core_common4.commonGlobOptions)(fullGlob));return files.length===0&&import_node_logger4.once.warn(`No story files found for the specified pattern: ${import_chalk4.default.blue(import_path7.default.join(specifier.directory,specifier.files))}`),files.sort().forEach(absolutePath=>{let ext=import_path7.default.extname(absolutePath);if(ext===".storyshot"){let relativePath=import_path7.default.relative(this.options.workingDir,absolutePath);import_node_logger4.logger.info(`Skipping ${ext} file ${relativePath}`);return}pathToSubIndex[absolutePath]=!1}),[specifier,pathToSubIndex]}))).forEach(([specifier,cache3])=>this.specifierToCache.set(specifier,cache3));let previewCode=await this.getPreviewCode(),projectTags=this.getProjectTags(previewCode);await this.ensureExtracted({projectTags})}async updateExtracted(updater,overwrite=!1){await Promise.all(this.specifiers.map(async specifier=>{let entry=this.specifierToCache.get(specifier);return(0,import_tiny_invariant.default)(entry,`specifier does not have a matching cache entry in specifierToCache: ${JSON.stringify(specifier)}`),Promise.all(Object.keys(entry).map(async absolutePath=>{if(!(entry[absolutePath]&&!overwrite))try{entry[absolutePath]=await updater(specifier,absolutePath,entry[absolutePath])}catch(err){let relativePath=`.${import_path7.default.sep}${import_path7.default.relative(this.options.workingDir,absolutePath)}`;entry[absolutePath]={type:"error",err:new IndexingError(err instanceof Error?err.message:String(err),[relativePath],err instanceof Error?err.stack:void 0)}}}))}))}isDocsMdx(absolutePath){return/(?<!\.stories)\.mdx$/i.test(absolutePath)}async ensureExtracted({projectTags}){return await this.updateExtracted(async(specifier,absolutePath)=>this.isDocsMdx(absolutePath)?!1:this.extractStories(specifier,absolutePath,projectTags)),await this.updateExtracted(async(specifier,absolutePath)=>this.extractDocs(specifier,absolutePath,projectTags)),this.specifiers.flatMap(specifier=>{let cache3=this.specifierToCache.get(specifier);return(0,import_tiny_invariant.default)(cache3,`specifier does not have a matching cache entry in specifierToCache: ${JSON.stringify(specifier)}`),Object.values(cache3).flatMap(entry=>entry?entry.type==="docs"?[entry]:entry.type==="error"?[entry]:entry.entries.map(item=>{if(item.type==="docs")return item;let{metaId,...existing}=item;return existing}):[])})}findDependencies(absoluteImports){return[...this.specifierToCache.values()].flatMap(cache3=>Object.entries(cache3).filter(([fileName,cacheEntry])=>!cacheEntry||cacheEntry.type!=="stories"?!1:!!absoluteImports.find(storyImport=>fileName.match(new RegExp(`^${storyImport.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(\\.[^.]+)?$`)))).map(([_,cacheEntry])=>cacheEntry))}async extractStories(specifier,absolutePath,projectTags=[]){let relativePath=import_path7.default.relative(this.options.workingDir,absolutePath),importPath=slash((0,import_core_common4.normalizeStoryPath)(relativePath)),defaultMakeTitle=userTitle=>{let title=(0,import_preview_api.userOrAutoTitleFromSpecifier)(importPath,specifier,userTitle);return(0,import_tiny_invariant.default)(title,"makeTitle created an undefined title. This happens when the fileName doesn't match any specifier from main.js"),title},indexer=this.options.indexers.find(ind=>ind.test.exec(absolutePath));(0,import_tiny_invariant.default)(indexer,`No matching indexer found for ${absolutePath}`);let indexInputs=await indexer.createIndex(absolutePath,{makeTitle:defaultMakeTitle}),entries=indexInputs.map(input=>{let name=input.name??(0,import_csf.storyNameFromExport)(input.exportName),title=input.title??defaultMakeTitle(),id=input.__id??(0,import_csf.toId)(input.metaId??title,(0,import_csf.storyNameFromExport)(input.exportName)),tags=(0,import_csf.combineTags)(...projectTags,...input.tags??[]);return{type:"story",id,metaId:input.metaId,name,title,importPath,tags}}),hasAutodocsTag=entries.some(entry=>entry.tags.includes(AUTODOCS_TAG)),isStoriesMdx=entries.some(entry=>entry.tags.includes(STORIES_MDX_TAG));if((hasAutodocsTag&&this.options.docs.autodocs!==!1||isStoriesMdx)&&this.options.build?.test?.disableAutoDocs!==!0){let name=this.options.docs.defaultName??"Docs",{metaId}=indexInputs[0],{title}=entries[0],id=(0,import_csf.toId)(metaId??title,name),tags=(0,import_csf.combineTags)(...projectTags,...indexInputs[0].tags??[]);entries.unshift({id,title,name,importPath,type:"docs",tags,storiesImports:[]})}return{entries:entries.filter(entry=>!(entry.type==="story"&&entry.tags.includes("stories-mdx-docsOnly"))),dependents:[],type:"stories"}}async extractDocs(specifier,absolutePath,projectTags=[]){let relativePath=import_path7.default.relative(this.options.workingDir,absolutePath);try{let normalizedPath=(0,import_core_common4.normalizeStoryPath)(relativePath),importPath=slash(normalizedPath),content=await import_fs_extra6.default.readFile(absolutePath,"utf8"),result=(0,import_docs_mdx.analyze)(content);if(result.isTemplate)return!1;let absoluteImports=result.imports.map(p=>makeAbsolute(p,normalizedPath,this.options.workingDir)),dependencies=this.findDependencies(absoluteImports),sortedDependencies=dependencies,csfEntry;if(result.of){let absoluteOf=makeAbsolute(result.of,normalizedPath,this.options.workingDir);dependencies.forEach(dep=>{if(dep.entries.length>0){let first=dep.entries.find(e2=>e2.type!=="docs");import_path7.default.normalize(import_path7.default.resolve(this.options.workingDir,first.importPath)).startsWith(import_path7.default.normalize(absoluteOf))&&(csfEntry=first)}sortedDependencies=[dep,...dependencies.filter(d=>d!==dep)]}),(0,import_tiny_invariant.default)(csfEntry,import_ts_dedent2.default`Could not find or load CSF file at path "${result.of}" referenced by \`of={}\` in docs file "${relativePath}".
20
20
 
21
21
  - Does that file exist?
22
22
  - If so, is it a CSF file (\`.stories.*\`)?
23
23
  - If so, is it matched by the \`stories\` glob in \`main.js\`?
24
- - If so, has the file successfully loaded in Storybook and are its stories visible?`)}dependencies.forEach(dep=>{dep.dependents.push(absolutePath)});let title=csfEntry?.title||(0,import_preview_api.userOrAutoTitleFromSpecifier)(importPath,specifier,result.title);(0,import_tiny_invariant.default)(title,"makeTitle created an undefined title. This happens when a specifier's doesn't have any matches in its fileName");let defaultName=this.options.docs.defaultName??"Docs",name=result.name||(csfEntry?autoName(importPath,csfEntry.importPath,defaultName):defaultName),id=(0,import_csf.toId)(csfEntry?.metaId||title,name),tags=(0,import_csf.combineTags)(...projectTags,...csfEntry?.tags??[],...result.metaTags??[],csfEntry?"attached-mdx":"unattached-mdx");return{id,title,name,importPath,storiesImports:sortedDependencies.map(dep=>dep.entries[0].importPath),type:"docs",tags}}catch(err){throw err&&err.source?.match(/mdast-util-mdx-jsx/g)&&import_node_logger4.logger.warn(`\u{1F4A1} This seems to be an MDX2 syntax error. Please refer to the MDX section in the following resource for assistance on how to fix this: ${import_chalk4.default.yellow("https://storybook.js.org/migration-guides/7.0")}`),err}}chooseDuplicate(firstEntry,secondEntry){if(firstEntry.importPath===secondEntry.importPath)return firstEntry;let firstIsBetter=!0;(secondEntry.type==="story"||isMdxEntry(secondEntry)&&firstEntry.type==="docs"&&!isMdxEntry(firstEntry))&&(firstIsBetter=!1);let betterEntry=firstIsBetter?firstEntry:secondEntry,worseEntry=firstIsBetter?secondEntry:firstEntry,changeDocsName='Use `<Meta of={} name="Other Name">` to distinguish them.';if(worseEntry.type==="story")throw new IndexingError(`Duplicate stories with id: ${firstEntry.id}`,[firstEntry.importPath,secondEntry.importPath]);if(betterEntry.type==="story"){let worseDescriptor=isMdxEntry(worseEntry)?"component docs page":"automatically generated docs page";throw betterEntry.name===this.options.docs.defaultName?new IndexingError(`You have a story for ${betterEntry.title} with the same name as your default docs entry name (${betterEntry.name}), so the docs page is being dropped. Consider changing the story name.`,[firstEntry.importPath,secondEntry.importPath]):new IndexingError(`You have a story for ${betterEntry.title} with the same name as your ${worseDescriptor} (${worseEntry.name}), so the docs page is being dropped. ${changeDocsName}`,[firstEntry.importPath,secondEntry.importPath])}else if(isMdxEntry(betterEntry)){if(isMdxEntry(worseEntry))throw new IndexingError(`You have two component docs pages with the same name ${betterEntry.title}:${betterEntry.name}. ${changeDocsName}`,[firstEntry.importPath,secondEntry.importPath]);if(worseEntry.tags?.includes(AUTODOCS_TAG)&&this.options.docs.autodocs!==!0)throw new IndexingError(`You created a component docs page for '${worseEntry.title}', but also tagged the CSF file with '${AUTODOCS_TAG}'. This is probably a mistake.`,[betterEntry.importPath,worseEntry.importPath])}else return{...betterEntry,storiesImports:[...betterEntry.storiesImports,worseEntry.importPath,...worseEntry.storiesImports]};return betterEntry}async sortStories(entries,storySortParameter){let sortableStories=Object.values(entries),fileNameOrder=this.storyFileNames();return(0,import_preview_api.sortStoriesV7)(sortableStories,storySortParameter,fileNameOrder),sortableStories.reduce((acc,item)=>(acc[item.id]=item,acc),{})}async getIndex(){if(this.lastIndex)return this.lastIndex;if(this.lastError)throw this.lastError;let previewCode=await this.getPreviewCode(),projectTags=previewCode?this.getProjectTags(previewCode):[],storiesList=await this.ensureExtracted({projectTags});try{let errorEntries=storiesList.filter(entry=>entry.type==="error");if(errorEntries.length)throw new MultipleIndexingError(errorEntries.map(entry=>entry.err));let duplicateErrors=[],indexEntries={};if(storiesList.forEach(entry=>{try{let existing=indexEntries[entry.id];existing?indexEntries[entry.id]=this.chooseDuplicate(existing,entry):indexEntries[entry.id]=entry}catch(err){err instanceof IndexingError&&duplicateErrors.push(err)}}),duplicateErrors.length)throw new MultipleIndexingError(duplicateErrors);let sorted=await this.sortStories(indexEntries,previewCode&&(0,import_csf_tools.getStorySortParameter)(previewCode));return this.lastIndex={v:4,entries:sorted},this.lastIndex}catch(err){throw this.lastError=err==null||err instanceof Error?err:void 0,(0,import_tiny_invariant.default)(this.lastError),import_node_logger4.logger.warn(`\u{1F6A8} ${this.lastError.toString()}`),this.lastError}}invalidateAll(){this.specifierToCache.forEach(cache3=>{Object.keys(cache3).forEach(key=>{cache3[key]=!1})}),this.lastIndex=null,this.lastError=null}invalidate(specifier,importPath,removed){let absolutePath=slash(import_path7.default.resolve(this.options.workingDir,importPath)),cache3=this.specifierToCache.get(specifier);(0,import_tiny_invariant.default)(cache3,`specifier does not have a matching cache entry in specifierToCache: ${JSON.stringify(specifier)}`);let cacheEntry=cache3[absolutePath];if(cacheEntry&&cacheEntry.type==="stories"){let{dependents}=cacheEntry,invalidated=new Set;this.specifierToCache.forEach(otherCache=>{dependents.forEach(dep=>{otherCache[dep]&&(invalidated.add(dep),otherCache[dep]=!1)})})}if(removed){if(cacheEntry&&cacheEntry.type==="docs"){let absoluteImports=cacheEntry.storiesImports.map(p=>import_path7.default.resolve(this.options.workingDir,p));this.findDependencies(absoluteImports).forEach(dep=>dep.dependents.splice(dep.dependents.indexOf(absolutePath),1))}delete cache3[absolutePath]}else cache3[absolutePath]=!1;this.lastIndex=null,this.lastError=null}async getPreviewCode(){let previewFile=["js","jsx","ts","tsx","mjs","cjs","mts"].map(ext=>import_path7.default.join(this.options.configDir,`preview.${ext}`)).find(fname=>import_fs_extra6.default.existsSync(fname));return previewFile&&(await import_fs_extra6.default.readFile(previewFile,"utf-8")).toString()}getProjectTags(previewCode){let projectAnnotations=(0,import_csf_tools.loadConfig)(previewCode).parse(),defaultTags=["dev","test"],extraTags=this.options.docs.autodocs===!0?[AUTODOCS_TAG]:[],projectTags=projectAnnotations.getFieldValue(["tags"])??[];return[...defaultTags,...projectTags,...extraTags]}storyFileNames(){return Array.from(this.specifierToCache.values()).flatMap(r2=>Object.keys(r2))}};var PAGE_REGEX=/(page|screen)/i,isPageStory=storyId=>PAGE_REGEX.test(storyId),isCLIExampleEntry=entry=>["example-introduction--docs","configure-your-project--docs","example-button--docs","example-button--primary","example-button--secondary","example-button--large","example-button--small","example-header--docs","example-header--logged-in","example-header--logged-out","example-page--logged-in","example-page--logged-out"].includes(entry.id),isAnyExampleEntry=entry=>entry.id.startsWith("example-button--")||entry.id.startsWith("example-header--")||entry.id.startsWith("example-page--");function summarizeIndex(storyIndex){let storyCount=0,componentTitles=new Set,exampleStoryCount=0,onboardingStoryCount=0,onboardingDocsCount=0,exampleDocsCount=0,pageStoryCount=0,playStoryCount=0,autodocsCount=0,storiesMdxCount=0,mdxCount=0;Object.values(storyIndex.entries).forEach(entry=>{isCLIExampleEntry(entry)?(entry.type==="story"&&(exampleStoryCount+=1),entry.type==="docs"&&(exampleDocsCount+=1)):isAnyExampleEntry(entry)?(entry.type==="story"&&(onboardingStoryCount+=1),entry.type==="docs"&&(onboardingDocsCount+=1)):entry.type==="story"?(storyCount+=1,componentTitles.add(entry.title),isPageStory(entry.title)&&(pageStoryCount+=1),entry.tags?.includes(PLAY_FN_TAG)&&(playStoryCount+=1)):entry.type==="docs"&&(isMdxEntry(entry)?mdxCount+=1:entry.tags?.includes(STORIES_MDX_TAG)?storiesMdxCount+=1:entry.tags?.includes(AUTODOCS_TAG)&&(autodocsCount+=1))});let componentCount=componentTitles.size;return{storyCount,componentCount,pageStoryCount,playStoryCount,autodocsCount,storiesMdxCount,mdxCount,exampleStoryCount,exampleDocsCount,onboardingStoryCount,onboardingDocsCount,version:storyIndex.v}}var import_server_errors2=require("@storybook/core-events/server-errors");async function buildOrThrow(callback){try{return await callback()}catch(err){let builderErrors=err.errors;throw builderErrors&&builderErrors.find(er=>er.text?.includes("No matching export"))?new import_server_errors2.NoMatchingExportError(err):err}}async function buildStaticStandalone(options){if(options.configType="PRODUCTION",options.outputDir==="")throw new Error("Won't remove current directory. Check your outputDir!");if(options.outputDir=(0,import_path8.resolve)(options.outputDir),options.configDir=(0,import_path8.resolve)(options.configDir),import_node_logger5.logger.info(import_chalk5.default`=> Cleaning outputDir: {cyan ${(0,import_path8.relative)(process.cwd(),options.outputDir)}}`),options.outputDir==="/")throw new Error("Won't remove directory '/'. Check your outputDir!");await(0,import_fs_extra7.emptyDir)(options.outputDir),await(0,import_fs_extra7.ensureDir)(options.outputDir);let config=await(0,import_core_common5.loadMainConfig)(options),{framework}=config,corePresets=[],frameworkName=typeof framework=="string"?framework:framework?.name;frameworkName?corePresets.push((0,import_path8.join)(frameworkName,"preset")):options.ignorePreview||import_node_logger5.logger.warn(`you have not specified a framework in your ${options.configDir}/main.js`),import_node_logger5.logger.info("=> Loading presets");let presets=await(0,import_core_common5.loadAllPresets)({corePresets:[require.resolve("@storybook/core-server/dist/presets/common-preset"),...corePresets],overridePresets:[require.resolve("@storybook/core-server/dist/presets/common-override-preset")],isCritical:!0,...options}),{renderer}=await presets.apply("core",{}),build2=await presets.apply("build",{}),[previewBuilder,managerBuilder]=await getBuilders({...options,presets,build:build2}),resolvedRenderer=renderer?(0,import_core_common5.resolveAddonName)(options.configDir,renderer,options):void 0;presets=await(0,import_core_common5.loadAllPresets)({corePresets:[require.resolve("@storybook/core-server/dist/presets/common-preset"),...managerBuilder.corePresets||[],...previewBuilder.corePresets||[],...resolvedRenderer?[resolvedRenderer]:[],...corePresets],overridePresets:[...previewBuilder.overridePresets||[],require.resolve("@storybook/core-server/dist/presets/common-override-preset")],...options,build:build2});let[features,core,staticDirs,indexers,stories,docsOptions]=await Promise.all([presets.apply("features"),presets.apply("core"),presets.apply("staticDirs"),presets.apply("experimental_indexers",[]),presets.apply("stories"),presets.apply("docs",{})]),fullOptions={...options,presets,features,build:build2},effects=[];import_global.global.FEATURES=features,await buildOrThrow(async()=>managerBuilder.build({startTime:process.hrtime(),options:fullOptions})),staticDirs&&effects.push(copyAllStaticFilesRelativeToMain(staticDirs,options.outputDir,options.configDir));let coreServerPublicDir=(0,import_path8.join)((0,import_path8.dirname)(require.resolve("@storybook/core-server/package.json")),"public");effects.push((0,import_fs_extra7.copy)(coreServerPublicDir,options.outputDir));let initializedStoryIndexGenerator=Promise.resolve(void 0);if(!options.ignorePreview){let workingDir=process.cwd(),directories={configDir:options.configDir,workingDir},normalizedStories=(0,import_core_common5.normalizeStories)(stories,directories),generator=new StoryIndexGenerator(normalizedStories,{...directories,indexers,docs:docsOptions,build:build2});initializedStoryIndexGenerator=generator.initialize().then(()=>generator),effects.push(extractStoriesJson((0,import_path8.join)(options.outputDir,"index.json"),initializedStoryIndexGenerator))}core?.disableProjectJson||effects.push(extractStorybookMetadata((0,import_path8.join)(options.outputDir,"project.json"),options.configDir)),options.debugWebpack&&(0,import_core_common5.logConfig)("Preview webpack config",await previewBuilder.getConfig(fullOptions)),options.ignorePreview?import_node_logger5.logger.info("=> Not building preview"):import_node_logger5.logger.info("=> Building preview..");let startTime=process.hrtime();await Promise.all([...options.ignorePreview?[]:[previewBuilder.build({startTime,options:fullOptions}).then(async previewStats=>{import_node_logger5.logger.trace({message:"=> Preview built",time:process.hrtime(startTime)});let statsOption=options.webpackStatsJson||options.statsJson;if(statsOption){let target=statsOption===!0?options.outputDir:statsOption;await outputStats(target,previewStats)}}).catch(error=>{throw import_node_logger5.logger.error("=> Failed to build the preview"),process.exitCode=1,error})],...effects]),core?.disableTelemetry||effects.push(initializedStoryIndexGenerator.then(async generator=>{let storyIndex=await generator?.getIndex(),payload={precedingUpgrade:await(0,import_telemetry2.getPrecedingUpgrade)()};storyIndex&&Object.assign(payload,{storyIndex:summarizeIndex(storyIndex)}),await(0,import_telemetry2.telemetry)("build",payload,{configDir:options.configDir})})),import_node_logger5.logger.info(`=> Output directory: ${options.outputDir}`)}var import_core_common12=require("@storybook/core-common"),import_prompts2=__toESM(require("prompts")),import_tiny_invariant4=__toESM(require("tiny-invariant")),import_global2=require("@storybook/global"),import_telemetry5=require("@storybook/telemetry"),import_path10=require("path"),import_node_logger14=require("@storybook/node-logger"),import_ts_dedent7=require("ts-dedent"),import_fs_extra10=require("fs-extra"),import_server_errors4=require("@storybook/core-events/server-errors");var import_express3=__toESM(require("express")),import_compression=__toESM(require("compression")),import_tiny_invariant3=__toESM(require("tiny-invariant")),import_core_common8=require("@storybook/core-common"),import_node_logger10=require("@storybook/node-logger"),import_server_errors3=require("@storybook/core-events/server-errors");var import_path9=__toESM(require("path")),import_fs2=__toESM(require("fs")),fileExists=basename5=>[".js",".cjs"].reduce((found,ext)=>{let filename=`${basename5}${ext}`;return!found&&import_fs2.default.existsSync(filename)?filename:found},"");function getMiddleware(configDir){let middlewarePath=fileExists(import_path9.default.resolve(configDir,"middleware"));if(middlewarePath){let middlewareModule=require(middlewarePath);return middlewareModule.__esModule&&(middlewareModule=middlewareModule.default),middlewareModule}return()=>{}}var import_ip=__toESM(require("ip")),import_node_logger6=require("@storybook/node-logger"),import_detect_port=__toESM(require("detect-port"));function getServerAddresses(port,host,proto,initialPath){let address=new URL(`${proto}://localhost:${port}/`),networkAddress=new URL(`${proto}://${host||import_ip.default.address()}:${port}/`);if(initialPath){let searchParams=`?path=${decodeURIComponent(initialPath.startsWith("/")?initialPath:`/${initialPath}`)}`;address.search=searchParams,networkAddress.search=searchParams}return{address:address.href,networkAddress:networkAddress.href}}var getServerPort=(port,{exactPort}={})=>(0,import_detect_port.default)(port).then(freePort=>(freePort!==port&&exactPort&&process.exit(-1),freePort)).catch(error=>{import_node_logger6.logger.error(error),process.exit(-1)}),getServerChannelUrl=(port,{https:https3})=>`${https3?"wss":"ws"}://localhost:${port}/storybook-server-channel`;var import_node_logger7=require("@storybook/node-logger"),import_fs_extra8=require("fs-extra"),import_http=__toESM(require("http")),import_https=__toESM(require("https"));async function getServer(app,options){if(!options.https)return import_http.default.createServer(app);options.sslCert||(import_node_logger7.logger.error("Error: --ssl-cert is required with --https"),process.exit(-1)),options.sslKey||(import_node_logger7.logger.error("Error: --ssl-key is required with --https"),process.exit(-1));let sslOptions={ca:await Promise.all((options.sslCa||[]).map(ca=>(0,import_fs_extra8.readFile)(ca,"utf-8"))),cert:await(0,import_fs_extra8.readFile)(options.sslCert,"utf-8"),key:await(0,import_fs_extra8.readFile)(options.sslKey,"utf-8")};return import_https.default.createServer(sslOptions,app)}var import_ws=__toESM(require("ws")),import_telejson=require("telejson"),import_channels=require("@storybook/channels"),ServerChannelTransport=class{constructor(server){this.socket=new import_ws.WebSocketServer({noServer:!0}),server.on("upgrade",(request,socket,head)=>{request.url==="/storybook-server-channel"&&this.socket.handleUpgrade(request,socket,head,ws=>{this.socket.emit("connection",ws,request)})}),this.socket.on("connection",wss=>{wss.on("message",raw=>{let data=raw.toString(),event=typeof data=="string"&&(0,import_telejson.isJSON)(data)?(0,import_telejson.parse)(data,{allowFunction:!1,allowClass:!1}):data;this.handler?.(event)})})}setHandler(handler){this.handler=handler}send(event){let data=(0,import_telejson.stringify)(event,{maxDepth:15,allowFunction:!1,allowClass:!1});Array.from(this.socket.clients).filter(c=>c.readyState===import_ws.default.OPEN).forEach(client=>client.send(data))}};function getServerChannel(server){let transports=[new ServerChannelTransport(server)];return new import_channels.Channel({transports,async:!0})}var import_node_logger8=require("@storybook/node-logger"),import_better_opn=__toESM(require("better-opn")),import_open=__toESM(require("open")),import_x_default_browser=__toESM(require("@aw-web-design/x-default-browser")),import_ts_dedent3=require("ts-dedent");function openInBrowser(address){let browserEnvVar=process.env.BROWSER,userBrowserIsChrome=browserEnvVar==="chrome"||browserEnvVar==="chromium"||browserEnvVar==="brave"||browserEnvVar==="com.brave.browser",openOptions=browserEnvVar?{app:{name:browserEnvVar}}:{};(0,import_x_default_browser.default)(async(err,res)=>{try{res&&(res.isChrome||res.isChromium||res.identity==="com.brave.browser"||userBrowserIsChrome)?await(0,import_better_opn.default)(address):await(0,import_open.default)(address,openOptions)}catch{import_node_logger8.logger.error(import_ts_dedent3.dedent`
24
+ - If so, has the file successfully loaded in Storybook and are its stories visible?`)}dependencies.forEach(dep=>{dep.dependents.push(absolutePath)});let title=csfEntry?.title||(0,import_preview_api.userOrAutoTitleFromSpecifier)(importPath,specifier,result.title);(0,import_tiny_invariant.default)(title,"makeTitle created an undefined title. This happens when a specifier's doesn't have any matches in its fileName");let defaultName=this.options.docs.defaultName??"Docs",name=result.name||(csfEntry?autoName(importPath,csfEntry.importPath,defaultName):defaultName),id=(0,import_csf.toId)(csfEntry?.metaId||title,name),tags=(0,import_csf.combineTags)(...projectTags,...csfEntry?.tags??[],...result.metaTags??[],csfEntry?"attached-mdx":"unattached-mdx");return{id,title,name,importPath,storiesImports:sortedDependencies.map(dep=>dep.entries[0].importPath),type:"docs",tags}}catch(err){throw err&&err.source?.match(/mdast-util-mdx-jsx/g)&&import_node_logger4.logger.warn(`\u{1F4A1} This seems to be an MDX2 syntax error. Please refer to the MDX section in the following resource for assistance on how to fix this: ${import_chalk4.default.yellow("https://storybook.js.org/migration-guides/7.0")}`),err}}chooseDuplicate(firstEntry,secondEntry){if(firstEntry.importPath===secondEntry.importPath)return firstEntry;let firstIsBetter=!0;(secondEntry.type==="story"||isMdxEntry(secondEntry)&&firstEntry.type==="docs"&&!isMdxEntry(firstEntry))&&(firstIsBetter=!1);let betterEntry=firstIsBetter?firstEntry:secondEntry,worseEntry=firstIsBetter?secondEntry:firstEntry,changeDocsName='Use `<Meta of={} name="Other Name">` to distinguish them.';if(worseEntry.type==="story")throw new IndexingError(`Duplicate stories with id: ${firstEntry.id}`,[firstEntry.importPath,secondEntry.importPath]);if(betterEntry.type==="story"){let worseDescriptor=isMdxEntry(worseEntry)?"component docs page":"automatically generated docs page";throw betterEntry.name===this.options.docs.defaultName?new IndexingError(`You have a story for ${betterEntry.title} with the same name as your default docs entry name (${betterEntry.name}), so the docs page is being dropped. Consider changing the story name.`,[firstEntry.importPath,secondEntry.importPath]):new IndexingError(`You have a story for ${betterEntry.title} with the same name as your ${worseDescriptor} (${worseEntry.name}), so the docs page is being dropped. ${changeDocsName}`,[firstEntry.importPath,secondEntry.importPath])}else if(isMdxEntry(betterEntry)){if(isMdxEntry(worseEntry))throw new IndexingError(`You have two component docs pages with the same name ${betterEntry.title}:${betterEntry.name}. ${changeDocsName}`,[firstEntry.importPath,secondEntry.importPath]);if(worseEntry.tags?.includes(AUTODOCS_TAG)&&this.options.docs.autodocs!==!0)throw new IndexingError(`You created a component docs page for '${worseEntry.title}', but also tagged the CSF file with '${AUTODOCS_TAG}'. This is probably a mistake.`,[betterEntry.importPath,worseEntry.importPath])}else return{...betterEntry,storiesImports:[...betterEntry.storiesImports,worseEntry.importPath,...worseEntry.storiesImports]};return betterEntry}async sortStories(entries,storySortParameter){let sortableStories=Object.values(entries),fileNameOrder=this.storyFileNames();return(0,import_preview_api.sortStoriesV7)(sortableStories,storySortParameter,fileNameOrder),sortableStories.reduce((acc,item)=>(acc[item.id]=item,acc),{})}async getIndex(){if(this.lastIndex)return this.lastIndex;if(this.lastError)throw this.lastError;let previewCode=await this.getPreviewCode(),projectTags=this.getProjectTags(previewCode),storiesList=await this.ensureExtracted({projectTags});try{let errorEntries=storiesList.filter(entry=>entry.type==="error");if(errorEntries.length)throw new MultipleIndexingError(errorEntries.map(entry=>entry.err));let duplicateErrors=[],indexEntries={};if(storiesList.forEach(entry=>{try{let existing=indexEntries[entry.id];existing?indexEntries[entry.id]=this.chooseDuplicate(existing,entry):indexEntries[entry.id]=entry}catch(err){err instanceof IndexingError&&duplicateErrors.push(err)}}),duplicateErrors.length)throw new MultipleIndexingError(duplicateErrors);let sorted=await this.sortStories(indexEntries,previewCode&&(0,import_csf_tools.getStorySortParameter)(previewCode));return this.lastIndex={v:4,entries:sorted},this.lastIndex}catch(err){throw this.lastError=err==null||err instanceof Error?err:void 0,(0,import_tiny_invariant.default)(this.lastError),import_node_logger4.logger.warn(`\u{1F6A8} ${this.lastError.toString()}`),this.lastError}}invalidateAll(){this.specifierToCache.forEach(cache3=>{Object.keys(cache3).forEach(key=>{cache3[key]=!1})}),this.lastIndex=null,this.lastError=null}invalidate(specifier,importPath,removed){let absolutePath=slash(import_path7.default.resolve(this.options.workingDir,importPath)),cache3=this.specifierToCache.get(specifier);(0,import_tiny_invariant.default)(cache3,`specifier does not have a matching cache entry in specifierToCache: ${JSON.stringify(specifier)}`);let cacheEntry=cache3[absolutePath];if(cacheEntry&&cacheEntry.type==="stories"){let{dependents}=cacheEntry,invalidated=new Set;this.specifierToCache.forEach(otherCache=>{dependents.forEach(dep=>{otherCache[dep]&&(invalidated.add(dep),otherCache[dep]=!1)})})}if(removed){if(cacheEntry&&cacheEntry.type==="docs"){let absoluteImports=cacheEntry.storiesImports.map(p=>import_path7.default.resolve(this.options.workingDir,p));this.findDependencies(absoluteImports).forEach(dep=>dep.dependents.splice(dep.dependents.indexOf(absolutePath),1))}delete cache3[absolutePath]}else cache3[absolutePath]=!1;this.lastIndex=null,this.lastError=null}async getPreviewCode(){let previewFile=["js","jsx","ts","tsx","mjs","cjs","mts"].map(ext=>import_path7.default.join(this.options.configDir,`preview.${ext}`)).find(fname=>import_fs_extra6.default.existsSync(fname));return previewFile&&(await import_fs_extra6.default.readFile(previewFile,"utf-8")).toString()}getProjectTags(previewCode){let projectTags=[],defaultTags=["dev","test"],extraTags=this.options.docs.autodocs===!0?[AUTODOCS_TAG]:[];return previewCode&&(projectTags=(0,import_csf_tools.loadConfig)(previewCode).parse().getFieldValue(["tags"])??[]),[...defaultTags,...projectTags,...extraTags]}storyFileNames(){return Array.from(this.specifierToCache.values()).flatMap(r2=>Object.keys(r2))}};var PAGE_REGEX=/(page|screen)/i,isPageStory=storyId=>PAGE_REGEX.test(storyId),isCLIExampleEntry=entry=>["example-introduction--docs","configure-your-project--docs","example-button--docs","example-button--primary","example-button--secondary","example-button--large","example-button--small","example-header--docs","example-header--logged-in","example-header--logged-out","example-page--logged-in","example-page--logged-out"].includes(entry.id),isAnyExampleEntry=entry=>entry.id.startsWith("example-button--")||entry.id.startsWith("example-header--")||entry.id.startsWith("example-page--");function summarizeIndex(storyIndex){let storyCount=0,componentTitles=new Set,exampleStoryCount=0,onboardingStoryCount=0,onboardingDocsCount=0,exampleDocsCount=0,pageStoryCount=0,playStoryCount=0,autodocsCount=0,storiesMdxCount=0,mdxCount=0;Object.values(storyIndex.entries).forEach(entry=>{isCLIExampleEntry(entry)?(entry.type==="story"&&(exampleStoryCount+=1),entry.type==="docs"&&(exampleDocsCount+=1)):isAnyExampleEntry(entry)?(entry.type==="story"&&(onboardingStoryCount+=1),entry.type==="docs"&&(onboardingDocsCount+=1)):entry.type==="story"?(storyCount+=1,componentTitles.add(entry.title),isPageStory(entry.title)&&(pageStoryCount+=1),entry.tags?.includes(PLAY_FN_TAG)&&(playStoryCount+=1)):entry.type==="docs"&&(isMdxEntry(entry)?mdxCount+=1:entry.tags?.includes(STORIES_MDX_TAG)?storiesMdxCount+=1:entry.tags?.includes(AUTODOCS_TAG)&&(autodocsCount+=1))});let componentCount=componentTitles.size;return{storyCount,componentCount,pageStoryCount,playStoryCount,autodocsCount,storiesMdxCount,mdxCount,exampleStoryCount,exampleDocsCount,onboardingStoryCount,onboardingDocsCount,version:storyIndex.v}}var import_server_errors2=require("@storybook/core-events/server-errors");async function buildOrThrow(callback){try{return await callback()}catch(err){let builderErrors=err.errors;throw builderErrors&&builderErrors.find(er=>er.text?.includes("No matching export"))?new import_server_errors2.NoMatchingExportError(err):err}}async function buildStaticStandalone(options){if(options.configType="PRODUCTION",options.outputDir==="")throw new Error("Won't remove current directory. Check your outputDir!");if(options.outputDir=(0,import_path8.resolve)(options.outputDir),options.configDir=(0,import_path8.resolve)(options.configDir),import_node_logger5.logger.info(import_chalk5.default`=> Cleaning outputDir: {cyan ${(0,import_path8.relative)(process.cwd(),options.outputDir)}}`),options.outputDir==="/")throw new Error("Won't remove directory '/'. Check your outputDir!");await(0,import_fs_extra7.emptyDir)(options.outputDir),await(0,import_fs_extra7.ensureDir)(options.outputDir);let config=await(0,import_core_common5.loadMainConfig)(options),{framework}=config,corePresets=[],frameworkName=typeof framework=="string"?framework:framework?.name;frameworkName?corePresets.push((0,import_path8.join)(frameworkName,"preset")):options.ignorePreview||import_node_logger5.logger.warn(`you have not specified a framework in your ${options.configDir}/main.js`),import_node_logger5.logger.info("=> Loading presets");let presets=await(0,import_core_common5.loadAllPresets)({corePresets:[require.resolve("@storybook/core-server/dist/presets/common-preset"),...corePresets],overridePresets:[require.resolve("@storybook/core-server/dist/presets/common-override-preset")],isCritical:!0,...options}),{renderer}=await presets.apply("core",{}),build2=await presets.apply("build",{}),[previewBuilder,managerBuilder]=await getBuilders({...options,presets,build:build2}),resolvedRenderer=renderer?(0,import_core_common5.resolveAddonName)(options.configDir,renderer,options):void 0;presets=await(0,import_core_common5.loadAllPresets)({corePresets:[require.resolve("@storybook/core-server/dist/presets/common-preset"),...managerBuilder.corePresets||[],...previewBuilder.corePresets||[],...resolvedRenderer?[resolvedRenderer]:[],...corePresets],overridePresets:[...previewBuilder.overridePresets||[],require.resolve("@storybook/core-server/dist/presets/common-override-preset")],...options,build:build2});let[features,core,staticDirs,indexers,stories,docsOptions]=await Promise.all([presets.apply("features"),presets.apply("core"),presets.apply("staticDirs"),presets.apply("experimental_indexers",[]),presets.apply("stories"),presets.apply("docs",{})]),fullOptions={...options,presets,features,build:build2},effects=[];import_global.global.FEATURES=features,await buildOrThrow(async()=>managerBuilder.build({startTime:process.hrtime(),options:fullOptions})),staticDirs&&effects.push(copyAllStaticFilesRelativeToMain(staticDirs,options.outputDir,options.configDir));let coreServerPublicDir=(0,import_path8.join)((0,import_path8.dirname)(require.resolve("@storybook/core-server/package.json")),"public");effects.push((0,import_fs_extra7.copy)(coreServerPublicDir,options.outputDir));let initializedStoryIndexGenerator=Promise.resolve(void 0);if(!options.ignorePreview){let workingDir=process.cwd(),directories={configDir:options.configDir,workingDir},normalizedStories=(0,import_core_common5.normalizeStories)(stories,directories),generator=new StoryIndexGenerator(normalizedStories,{...directories,indexers,docs:docsOptions,build:build2});initializedStoryIndexGenerator=generator.initialize().then(()=>generator),effects.push(extractStoriesJson((0,import_path8.join)(options.outputDir,"index.json"),initializedStoryIndexGenerator))}core?.disableProjectJson||effects.push(extractStorybookMetadata((0,import_path8.join)(options.outputDir,"project.json"),options.configDir)),options.debugWebpack&&(0,import_core_common5.logConfig)("Preview webpack config",await previewBuilder.getConfig(fullOptions)),options.ignorePreview?import_node_logger5.logger.info("=> Not building preview"):import_node_logger5.logger.info("=> Building preview..");let startTime=process.hrtime();await Promise.all([...options.ignorePreview?[]:[previewBuilder.build({startTime,options:fullOptions}).then(async previewStats=>{import_node_logger5.logger.trace({message:"=> Preview built",time:process.hrtime(startTime)});let statsOption=options.webpackStatsJson||options.statsJson;if(statsOption){let target=statsOption===!0?options.outputDir:statsOption;await outputStats(target,previewStats)}}).catch(error=>{throw import_node_logger5.logger.error("=> Failed to build the preview"),process.exitCode=1,error})],...effects]),core?.disableTelemetry||effects.push(initializedStoryIndexGenerator.then(async generator=>{let storyIndex=await generator?.getIndex(),payload={precedingUpgrade:await(0,import_telemetry2.getPrecedingUpgrade)()};storyIndex&&Object.assign(payload,{storyIndex:summarizeIndex(storyIndex)}),await(0,import_telemetry2.telemetry)("build",payload,{configDir:options.configDir})})),import_node_logger5.logger.info(`=> Output directory: ${options.outputDir}`)}var import_core_common12=require("@storybook/core-common"),import_prompts2=__toESM(require("prompts")),import_tiny_invariant4=__toESM(require("tiny-invariant")),import_global2=require("@storybook/global"),import_telemetry5=require("@storybook/telemetry"),import_path10=require("path"),import_node_logger14=require("@storybook/node-logger"),import_ts_dedent7=require("ts-dedent"),import_fs_extra10=require("fs-extra"),import_server_errors4=require("@storybook/core-events/server-errors");var import_express3=__toESM(require("express")),import_compression=__toESM(require("compression")),import_tiny_invariant3=__toESM(require("tiny-invariant")),import_core_common8=require("@storybook/core-common"),import_node_logger10=require("@storybook/node-logger"),import_server_errors3=require("@storybook/core-events/server-errors");var import_path9=__toESM(require("path")),import_fs2=__toESM(require("fs")),fileExists=basename5=>[".js",".cjs"].reduce((found,ext)=>{let filename=`${basename5}${ext}`;return!found&&import_fs2.default.existsSync(filename)?filename:found},"");function getMiddleware(configDir){let middlewarePath=fileExists(import_path9.default.resolve(configDir,"middleware"));if(middlewarePath){let middlewareModule=require(middlewarePath);return middlewareModule.__esModule&&(middlewareModule=middlewareModule.default),middlewareModule}return()=>{}}var import_ip=__toESM(require("ip")),import_node_logger6=require("@storybook/node-logger"),import_detect_port=__toESM(require("detect-port"));function getServerAddresses(port,host,proto,initialPath){let address=new URL(`${proto}://localhost:${port}/`),networkAddress=new URL(`${proto}://${host||import_ip.default.address()}:${port}/`);if(initialPath){let searchParams=`?path=${decodeURIComponent(initialPath.startsWith("/")?initialPath:`/${initialPath}`)}`;address.search=searchParams,networkAddress.search=searchParams}return{address:address.href,networkAddress:networkAddress.href}}var getServerPort=(port,{exactPort}={})=>(0,import_detect_port.default)(port).then(freePort=>(freePort!==port&&exactPort&&process.exit(-1),freePort)).catch(error=>{import_node_logger6.logger.error(error),process.exit(-1)}),getServerChannelUrl=(port,{https:https3})=>`${https3?"wss":"ws"}://localhost:${port}/storybook-server-channel`;var import_node_logger7=require("@storybook/node-logger"),import_fs_extra8=require("fs-extra"),import_http=__toESM(require("http")),import_https=__toESM(require("https"));async function getServer(app,options){if(!options.https)return import_http.default.createServer(app);options.sslCert||(import_node_logger7.logger.error("Error: --ssl-cert is required with --https"),process.exit(-1)),options.sslKey||(import_node_logger7.logger.error("Error: --ssl-key is required with --https"),process.exit(-1));let sslOptions={ca:await Promise.all((options.sslCa||[]).map(ca=>(0,import_fs_extra8.readFile)(ca,"utf-8"))),cert:await(0,import_fs_extra8.readFile)(options.sslCert,"utf-8"),key:await(0,import_fs_extra8.readFile)(options.sslKey,"utf-8")};return import_https.default.createServer(sslOptions,app)}var import_ws=__toESM(require("ws")),import_telejson=require("telejson"),import_channels=require("@storybook/channels"),ServerChannelTransport=class{constructor(server){this.socket=new import_ws.WebSocketServer({noServer:!0}),server.on("upgrade",(request,socket,head)=>{request.url==="/storybook-server-channel"&&this.socket.handleUpgrade(request,socket,head,ws=>{this.socket.emit("connection",ws,request)})}),this.socket.on("connection",wss=>{wss.on("message",raw=>{let data=raw.toString(),event=typeof data=="string"&&(0,import_telejson.isJSON)(data)?(0,import_telejson.parse)(data,{allowFunction:!1,allowClass:!1}):data;this.handler?.(event)})})}setHandler(handler){this.handler=handler}send(event){let data=(0,import_telejson.stringify)(event,{maxDepth:15,allowFunction:!1,allowClass:!1});Array.from(this.socket.clients).filter(c=>c.readyState===import_ws.default.OPEN).forEach(client=>client.send(data))}};function getServerChannel(server){let transports=[new ServerChannelTransport(server)];return new import_channels.Channel({transports,async:!0})}var import_node_logger8=require("@storybook/node-logger"),import_better_opn=__toESM(require("better-opn")),import_open=__toESM(require("open")),import_x_default_browser=__toESM(require("@aw-web-design/x-default-browser")),import_ts_dedent3=require("ts-dedent");function openInBrowser(address){let browserEnvVar=process.env.BROWSER,userBrowserIsChrome=browserEnvVar==="chrome"||browserEnvVar==="chromium"||browserEnvVar==="brave"||browserEnvVar==="com.brave.browser",openOptions=browserEnvVar?{app:{name:browserEnvVar}}:{};(0,import_x_default_browser.default)(async(err,res)=>{try{res&&(res.isChrome||res.isChromium||res.identity==="com.brave.browser"||userBrowserIsChrome)?await(0,import_better_opn.default)(address):await(0,import_open.default)(address,openOptions)}catch{import_node_logger8.logger.error(import_ts_dedent3.dedent`
25
25
  Could not open ${address} inside a browser. If you're running this command inside a
26
26
  docker container or on a CI, you need to pass the '--ci' flag to prevent opening a
27
27
  browser by default.
package/dist/index.mjs CHANGED
@@ -53,12 +53,12 @@ var require_eastasianwidth=__commonJS({"../../node_modules/eastasianwidth/eastas
53
53
  `));return {staticDir,staticPath,targetDir,targetEndpoint}};async function copyAllStaticFilesRelativeToMain(staticDirs,outputDir,configDir){let workingDir=process.cwd();return staticDirs?.reduce(async(acc,dir)=>{await acc;let staticDirAndTarget=typeof dir=="string"?dir:`${dir.from}:${dir.to}`,{staticPath:from,targetEndpoint:to}=await parseStaticDir(getDirectoryFromWorkingDir({configDir,workingDir,directory:staticDirAndTarget})),targetPath=join(outputDir,to),skipPaths=["index.html","iframe.html"].map(f=>join(targetPath,f));from.includes("node_modules")||logger.info(chalk8`=> Copying static files: {cyan ${print(from)}} at {cyan ${print(targetPath)}}`),await fs4.copy(from,targetPath,{dereference:!0,preserveTimestamps:!0,filter:(_,dest)=>!skipPaths.includes(dest)});},Promise.resolve())}function print(p){return relative(process.cwd(),p)}async function getManagerBuilder(){return import('@storybook/builder-manager')}async function getPreviewBuilder(builderName,configDir){let builderPackage=__require.resolve(["webpack5"].includes(builderName)?`@storybook/builder-${builderName}`:builderName,{paths:[configDir]});return await import(pathToFileURL(builderPackage).href)}async function getBuilders({presets,configDir}){let{builder}=await presets.apply("core",{});if(!builder)throw new MissingBuilderError;let builderName=typeof builder=="string"?builder:builder.name;return Promise.all([getPreviewBuilder(builderName,configDir),getManagerBuilder()])}function slash(path6){return path6.startsWith("\\\\?\\")?path6:path6.replace(/\\/g,"/")}var isDirectory=directory=>{try{return fs3.lstatSync(directory).isDirectory()}catch{return !1}};function toImportPath(relativePath){return relativePath.startsWith(".")?relativePath:`./${relativePath}`}function watchStorySpecifiers(specifiers,options,onInvalidate){let wp=new Watchpack({followSymlinks:!1,ignored:["**/.git","**/node_modules"]});wp.watch({directories:uniq(specifiers.map(ns=>ns.directory))});async function onChangeOrRemove(watchpackPath,removed){let importPath=slash(watchpackPath.startsWith(".")?watchpackPath:`./${watchpackPath}`),matchingSpecifier=specifiers.find(ns=>ns.importPathMatcher.exec(importPath));if(matchingSpecifier){onInvalidate(matchingSpecifier,importPath,removed);return}let absolutePath=path4.join(options.workingDir,importPath);!removed&&isDirectory(absolutePath)&&await Promise.all(specifiers.filter(specifier=>importPath.startsWith(specifier.directory)).map(async specifier=>{let dirGlob=path4.join(options.workingDir,importPath,"**",path4.basename(specifier.files)),{globby}=await import('globby');(await globby(slash(dirGlob),commonGlobOptions(dirGlob))).forEach(filePath=>{let fileImportPath=toImportPath(path4.relative(options.workingDir,filePath).replace(/\\/g,"/"));specifier.importPathMatcher.exec(fileImportPath)&&onInvalidate(specifier,fileImportPath,removed);});}));}return wp.on("change",async(filePath,mtime,explanation)=>{await onChangeOrRemove(filePath,!mtime);}),wp.on("remove",async(filePath,explanation)=>{await onChangeOrRemove(filePath,!0);}),()=>wp.close()}function watchConfig(configDir,onInvalidate){let wp=new Watchpack({followSymlinks:!1,ignored:["**/.git","**/node_modules"]});return wp.watch({directories:[configDir]}),wp.on("change",async(filePath,mtime,explanation)=>{await onInvalidate(filePath,!mtime);}),wp.on("remove",async(filePath,explanation)=>{await onInvalidate(filePath,!0);}),()=>wp.close()}var DEBOUNCE=100;async function extractStoriesJson(outputFile,initializedStoryIndexGenerator,transform){let storyIndex=await(await initializedStoryIndexGenerator).getIndex();await writeJSON(outputFile,transform?transform(storyIndex):storyIndex);}function useStoriesJson({router:router2,initializedStoryIndexGenerator,workingDir=process.cwd(),configDir,serverChannel,normalizedStories}){let maybeInvalidate=debounce(()=>serverChannel.emit(STORY_INDEX_INVALIDATED),DEBOUNCE,{leading:!0});watchStorySpecifiers(normalizedStories,{workingDir},async(specifier,path6,removed)=>{(await initializedStoryIndexGenerator).invalidate(specifier,path6,removed),maybeInvalidate();}),configDir&&watchConfig(configDir,async filePath=>{basename(filePath).startsWith("preview")&&((await initializedStoryIndexGenerator).invalidateAll(),maybeInvalidate());}),router2.use("/index.json",async(req,res)=>{try{let index=await(await initializedStoryIndexGenerator).getIndex();res.header("Content-Type","application/json"),res.send(JSON.stringify(index));}catch(err){res.status(500),res.send(err instanceof Error?err.toString():String(err));}});}async function extractStorybookMetadata(outputFile,configDir){let storybookMetadata=await getStorybookMetadata(configDir);await writeJSON(outputFile,storybookMetadata);}function useStorybookMetadata(router2,configDir){router2.use("/project.json",async(req,res)=>{let storybookMetadata=await getStorybookMetadata(configDir);res.header("Content-Type","application/json"),res.send(JSON.stringify(storybookMetadata));});}function autoName(mdxImportPath,csfImportPath,defaultName){let mdxBasename=basename(mdxImportPath),csfBasename=basename(csfImportPath),[mdxFilename]=mdxBasename.split("."),[csfFilename]=csfBasename.split(".");return mdxFilename===csfFilename?defaultName:mdxFilename}var IndexingError=class extends Error{constructor(message,importPaths,stack){super(),this.message=message,this.importPaths=importPaths,stack&&(this.stack=stack);}pathsString(){return this.importPaths.length===1?`${slash(this.importPaths[0])}`:`${this.importPaths.map(slash).join(",")}`}toString(){return `${this.pathsString()}: ${this.message}`}},MultipleIndexingError=class extends Error{constructor(indexingErrors){super();this.indexingErrors=indexingErrors;if(this.indexingErrors.length===0)throw new Error("Unexpected empty error list");if(this.indexingErrors.length===1){let[err]=this.indexingErrors;this.message=`Unable to index ${err.pathsString()}`;}else this.message=`Unable to index files:
54
54
  ${this.indexingErrors.map(err=>`- ${err}`).join(`
55
55
  `)}`;}toString(){return this.indexingErrors.length===1?`${this.message}:
56
- ${this.indexingErrors[0].stack}`:this.message}};var AUTODOCS_TAG="autodocs",STORIES_MDX_TAG="stories-mdx",UNATTACHED_MDX_TAG="unattached-mdx",ATTACHED_MDX_TAG="attached-mdx",PLAY_FN_TAG="play-fn";function isMdxEntry({tags}){return tags?.includes(UNATTACHED_MDX_TAG)||tags?.includes(ATTACHED_MDX_TAG)}var makeAbsolute=(otherImport,normalizedPath,workingDir)=>otherImport.startsWith(".")?slash(path4.resolve(workingDir,normalizeStoryPath(path4.join(path4.dirname(normalizedPath),otherImport)))):otherImport,StoryIndexGenerator=class{constructor(specifiers,options){this.specifiers=specifiers;this.options=options;this.specifierToCache=new Map;}async initialize(){(await Promise.all(this.specifiers.map(async specifier=>{let pathToSubIndex={},fullGlob=slash(path4.join(this.options.workingDir,specifier.directory,specifier.files)),{globby}=await import('globby'),files=await globby(fullGlob,commonGlobOptions(fullGlob));return files.length===0&&once.warn(`No story files found for the specified pattern: ${chalk8.blue(path4.join(specifier.directory,specifier.files))}`),files.sort().forEach(absolutePath=>{let ext=path4.extname(absolutePath);if(ext===".storyshot"){let relativePath=path4.relative(this.options.workingDir,absolutePath);logger.info(`Skipping ${ext} file ${relativePath}`);return}pathToSubIndex[absolutePath]=!1;}),[specifier,pathToSubIndex]}))).forEach(([specifier,cache3])=>this.specifierToCache.set(specifier,cache3));let previewCode=await this.getPreviewCode(),projectTags=previewCode?this.getProjectTags(previewCode):[];await this.ensureExtracted({projectTags});}async updateExtracted(updater,overwrite=!1){await Promise.all(this.specifiers.map(async specifier=>{let entry=this.specifierToCache.get(specifier);return invariant(entry,`specifier does not have a matching cache entry in specifierToCache: ${JSON.stringify(specifier)}`),Promise.all(Object.keys(entry).map(async absolutePath=>{if(!(entry[absolutePath]&&!overwrite))try{entry[absolutePath]=await updater(specifier,absolutePath,entry[absolutePath]);}catch(err){let relativePath=`.${path4.sep}${path4.relative(this.options.workingDir,absolutePath)}`;entry[absolutePath]={type:"error",err:new IndexingError(err instanceof Error?err.message:String(err),[relativePath],err instanceof Error?err.stack:void 0)};}}))}));}isDocsMdx(absolutePath){return new RegExp("(?<!\\.stories)\\.mdx$","i").test(absolutePath)}async ensureExtracted({projectTags}){return await this.updateExtracted(async(specifier,absolutePath)=>this.isDocsMdx(absolutePath)?!1:this.extractStories(specifier,absolutePath,projectTags)),await this.updateExtracted(async(specifier,absolutePath)=>this.extractDocs(specifier,absolutePath,projectTags)),this.specifiers.flatMap(specifier=>{let cache3=this.specifierToCache.get(specifier);return invariant(cache3,`specifier does not have a matching cache entry in specifierToCache: ${JSON.stringify(specifier)}`),Object.values(cache3).flatMap(entry=>entry?entry.type==="docs"?[entry]:entry.type==="error"?[entry]:entry.entries.map(item=>{if(item.type==="docs")return item;let{metaId,...existing}=item;return existing}):[])})}findDependencies(absoluteImports){return [...this.specifierToCache.values()].flatMap(cache3=>Object.entries(cache3).filter(([fileName,cacheEntry])=>!cacheEntry||cacheEntry.type!=="stories"?!1:!!absoluteImports.find(storyImport=>fileName.match(new RegExp(`^${storyImport}(\\.[^.]+)?$`)))).map(([_,cacheEntry])=>cacheEntry))}async extractStories(specifier,absolutePath,projectTags=[]){let relativePath=path4.relative(this.options.workingDir,absolutePath),importPath=slash(normalizeStoryPath(relativePath)),defaultMakeTitle=userTitle=>{let title=userOrAutoTitleFromSpecifier(importPath,specifier,userTitle);return invariant(title,"makeTitle created an undefined title. This happens when the fileName doesn't match any specifier from main.js"),title},indexer=this.options.indexers.find(ind=>ind.test.exec(absolutePath));invariant(indexer,`No matching indexer found for ${absolutePath}`);let indexInputs=await indexer.createIndex(absolutePath,{makeTitle:defaultMakeTitle}),entries=indexInputs.map(input=>{let name=input.name??storyNameFromExport(input.exportName),title=input.title??defaultMakeTitle(),id=input.__id??toId(input.metaId??title,storyNameFromExport(input.exportName)),tags=combineTags(...projectTags,...input.tags??[]);return {type:"story",id,metaId:input.metaId,name,title,importPath,tags}}),hasAutodocsTag=entries.some(entry=>entry.tags.includes(AUTODOCS_TAG)),isStoriesMdx=entries.some(entry=>entry.tags.includes(STORIES_MDX_TAG));if((hasAutodocsTag&&this.options.docs.autodocs!==!1||isStoriesMdx)&&this.options.build?.test?.disableAutoDocs!==!0){let name=this.options.docs.defaultName??"Docs",{metaId}=indexInputs[0],{title}=entries[0],id=toId(metaId??title,name),tags=combineTags(...projectTags,...indexInputs[0].tags??[]);entries.unshift({id,title,name,importPath,type:"docs",tags,storiesImports:[]});}return {entries:entries.filter(entry=>!(entry.type==="story"&&entry.tags.includes("stories-mdx-docsOnly"))),dependents:[],type:"stories"}}async extractDocs(specifier,absolutePath,projectTags=[]){let relativePath=path4.relative(this.options.workingDir,absolutePath);try{let normalizedPath=normalizeStoryPath(relativePath),importPath=slash(normalizedPath),content=await fs4.readFile(absolutePath,"utf8"),result=analyze(content);if(result.isTemplate)return !1;let absoluteImports=result.imports.map(p=>makeAbsolute(p,normalizedPath,this.options.workingDir)),dependencies=this.findDependencies(absoluteImports),sortedDependencies=dependencies,csfEntry;if(result.of){let absoluteOf=makeAbsolute(result.of,normalizedPath,this.options.workingDir);dependencies.forEach(dep=>{if(dep.entries.length>0){let first=dep.entries.find(e=>e.type!=="docs");path4.normalize(path4.resolve(this.options.workingDir,first.importPath)).startsWith(path4.normalize(absoluteOf))&&(csfEntry=first);}sortedDependencies=[dep,...dependencies.filter(d=>d!==dep)];}),invariant(csfEntry,dedent2`Could not find or load CSF file at path "${result.of}" referenced by \`of={}\` in docs file "${relativePath}".
56
+ ${this.indexingErrors[0].stack}`:this.message}};var AUTODOCS_TAG="autodocs",STORIES_MDX_TAG="stories-mdx",UNATTACHED_MDX_TAG="unattached-mdx",ATTACHED_MDX_TAG="attached-mdx",PLAY_FN_TAG="play-fn";function isMdxEntry({tags}){return tags?.includes(UNATTACHED_MDX_TAG)||tags?.includes(ATTACHED_MDX_TAG)}var makeAbsolute=(otherImport,normalizedPath,workingDir)=>otherImport.startsWith(".")?slash(path4.resolve(workingDir,normalizeStoryPath(path4.join(path4.dirname(normalizedPath),otherImport)))):otherImport,StoryIndexGenerator=class{constructor(specifiers,options){this.specifiers=specifiers;this.options=options;this.specifierToCache=new Map;}async initialize(){(await Promise.all(this.specifiers.map(async specifier=>{let pathToSubIndex={},fullGlob=slash(path4.join(this.options.workingDir,specifier.directory,specifier.files)),{globby}=await import('globby'),files=await globby(fullGlob,commonGlobOptions(fullGlob));return files.length===0&&once.warn(`No story files found for the specified pattern: ${chalk8.blue(path4.join(specifier.directory,specifier.files))}`),files.sort().forEach(absolutePath=>{let ext=path4.extname(absolutePath);if(ext===".storyshot"){let relativePath=path4.relative(this.options.workingDir,absolutePath);logger.info(`Skipping ${ext} file ${relativePath}`);return}pathToSubIndex[absolutePath]=!1;}),[specifier,pathToSubIndex]}))).forEach(([specifier,cache3])=>this.specifierToCache.set(specifier,cache3));let previewCode=await this.getPreviewCode(),projectTags=this.getProjectTags(previewCode);await this.ensureExtracted({projectTags});}async updateExtracted(updater,overwrite=!1){await Promise.all(this.specifiers.map(async specifier=>{let entry=this.specifierToCache.get(specifier);return invariant(entry,`specifier does not have a matching cache entry in specifierToCache: ${JSON.stringify(specifier)}`),Promise.all(Object.keys(entry).map(async absolutePath=>{if(!(entry[absolutePath]&&!overwrite))try{entry[absolutePath]=await updater(specifier,absolutePath,entry[absolutePath]);}catch(err){let relativePath=`.${path4.sep}${path4.relative(this.options.workingDir,absolutePath)}`;entry[absolutePath]={type:"error",err:new IndexingError(err instanceof Error?err.message:String(err),[relativePath],err instanceof Error?err.stack:void 0)};}}))}));}isDocsMdx(absolutePath){return new RegExp("(?<!\\.stories)\\.mdx$","i").test(absolutePath)}async ensureExtracted({projectTags}){return await this.updateExtracted(async(specifier,absolutePath)=>this.isDocsMdx(absolutePath)?!1:this.extractStories(specifier,absolutePath,projectTags)),await this.updateExtracted(async(specifier,absolutePath)=>this.extractDocs(specifier,absolutePath,projectTags)),this.specifiers.flatMap(specifier=>{let cache3=this.specifierToCache.get(specifier);return invariant(cache3,`specifier does not have a matching cache entry in specifierToCache: ${JSON.stringify(specifier)}`),Object.values(cache3).flatMap(entry=>entry?entry.type==="docs"?[entry]:entry.type==="error"?[entry]:entry.entries.map(item=>{if(item.type==="docs")return item;let{metaId,...existing}=item;return existing}):[])})}findDependencies(absoluteImports){return [...this.specifierToCache.values()].flatMap(cache3=>Object.entries(cache3).filter(([fileName,cacheEntry])=>!cacheEntry||cacheEntry.type!=="stories"?!1:!!absoluteImports.find(storyImport=>fileName.match(new RegExp(`^${storyImport.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(\\.[^.]+)?$`)))).map(([_,cacheEntry])=>cacheEntry))}async extractStories(specifier,absolutePath,projectTags=[]){let relativePath=path4.relative(this.options.workingDir,absolutePath),importPath=slash(normalizeStoryPath(relativePath)),defaultMakeTitle=userTitle=>{let title=userOrAutoTitleFromSpecifier(importPath,specifier,userTitle);return invariant(title,"makeTitle created an undefined title. This happens when the fileName doesn't match any specifier from main.js"),title},indexer=this.options.indexers.find(ind=>ind.test.exec(absolutePath));invariant(indexer,`No matching indexer found for ${absolutePath}`);let indexInputs=await indexer.createIndex(absolutePath,{makeTitle:defaultMakeTitle}),entries=indexInputs.map(input=>{let name=input.name??storyNameFromExport(input.exportName),title=input.title??defaultMakeTitle(),id=input.__id??toId(input.metaId??title,storyNameFromExport(input.exportName)),tags=combineTags(...projectTags,...input.tags??[]);return {type:"story",id,metaId:input.metaId,name,title,importPath,tags}}),hasAutodocsTag=entries.some(entry=>entry.tags.includes(AUTODOCS_TAG)),isStoriesMdx=entries.some(entry=>entry.tags.includes(STORIES_MDX_TAG));if((hasAutodocsTag&&this.options.docs.autodocs!==!1||isStoriesMdx)&&this.options.build?.test?.disableAutoDocs!==!0){let name=this.options.docs.defaultName??"Docs",{metaId}=indexInputs[0],{title}=entries[0],id=toId(metaId??title,name),tags=combineTags(...projectTags,...indexInputs[0].tags??[]);entries.unshift({id,title,name,importPath,type:"docs",tags,storiesImports:[]});}return {entries:entries.filter(entry=>!(entry.type==="story"&&entry.tags.includes("stories-mdx-docsOnly"))),dependents:[],type:"stories"}}async extractDocs(specifier,absolutePath,projectTags=[]){let relativePath=path4.relative(this.options.workingDir,absolutePath);try{let normalizedPath=normalizeStoryPath(relativePath),importPath=slash(normalizedPath),content=await fs4.readFile(absolutePath,"utf8"),result=analyze(content);if(result.isTemplate)return !1;let absoluteImports=result.imports.map(p=>makeAbsolute(p,normalizedPath,this.options.workingDir)),dependencies=this.findDependencies(absoluteImports),sortedDependencies=dependencies,csfEntry;if(result.of){let absoluteOf=makeAbsolute(result.of,normalizedPath,this.options.workingDir);dependencies.forEach(dep=>{if(dep.entries.length>0){let first=dep.entries.find(e=>e.type!=="docs");path4.normalize(path4.resolve(this.options.workingDir,first.importPath)).startsWith(path4.normalize(absoluteOf))&&(csfEntry=first);}sortedDependencies=[dep,...dependencies.filter(d=>d!==dep)];}),invariant(csfEntry,dedent2`Could not find or load CSF file at path "${result.of}" referenced by \`of={}\` in docs file "${relativePath}".
57
57
 
58
58
  - Does that file exist?
59
59
  - If so, is it a CSF file (\`.stories.*\`)?
60
60
  - If so, is it matched by the \`stories\` glob in \`main.js\`?
61
- - If so, has the file successfully loaded in Storybook and are its stories visible?`);}dependencies.forEach(dep=>{dep.dependents.push(absolutePath);});let title=csfEntry?.title||userOrAutoTitleFromSpecifier(importPath,specifier,result.title);invariant(title,"makeTitle created an undefined title. This happens when a specifier's doesn't have any matches in its fileName");let defaultName=this.options.docs.defaultName??"Docs",name=result.name||(csfEntry?autoName(importPath,csfEntry.importPath,defaultName):defaultName),id=toId(csfEntry?.metaId||title,name),tags=combineTags(...projectTags,...csfEntry?.tags??[],...result.metaTags??[],csfEntry?"attached-mdx":"unattached-mdx");return {id,title,name,importPath,storiesImports:sortedDependencies.map(dep=>dep.entries[0].importPath),type:"docs",tags}}catch(err){throw err&&err.source?.match(/mdast-util-mdx-jsx/g)&&logger.warn(`\u{1F4A1} This seems to be an MDX2 syntax error. Please refer to the MDX section in the following resource for assistance on how to fix this: ${chalk8.yellow("https://storybook.js.org/migration-guides/7.0")}`),err}}chooseDuplicate(firstEntry,secondEntry){if(firstEntry.importPath===secondEntry.importPath)return firstEntry;let firstIsBetter=!0;(secondEntry.type==="story"||isMdxEntry(secondEntry)&&firstEntry.type==="docs"&&!isMdxEntry(firstEntry))&&(firstIsBetter=!1);let betterEntry=firstIsBetter?firstEntry:secondEntry,worseEntry=firstIsBetter?secondEntry:firstEntry,changeDocsName='Use `<Meta of={} name="Other Name">` to distinguish them.';if(worseEntry.type==="story")throw new IndexingError(`Duplicate stories with id: ${firstEntry.id}`,[firstEntry.importPath,secondEntry.importPath]);if(betterEntry.type==="story"){let worseDescriptor=isMdxEntry(worseEntry)?"component docs page":"automatically generated docs page";throw betterEntry.name===this.options.docs.defaultName?new IndexingError(`You have a story for ${betterEntry.title} with the same name as your default docs entry name (${betterEntry.name}), so the docs page is being dropped. Consider changing the story name.`,[firstEntry.importPath,secondEntry.importPath]):new IndexingError(`You have a story for ${betterEntry.title} with the same name as your ${worseDescriptor} (${worseEntry.name}), so the docs page is being dropped. ${changeDocsName}`,[firstEntry.importPath,secondEntry.importPath])}else if(isMdxEntry(betterEntry)){if(isMdxEntry(worseEntry))throw new IndexingError(`You have two component docs pages with the same name ${betterEntry.title}:${betterEntry.name}. ${changeDocsName}`,[firstEntry.importPath,secondEntry.importPath]);if(worseEntry.tags?.includes(AUTODOCS_TAG)&&this.options.docs.autodocs!==!0)throw new IndexingError(`You created a component docs page for '${worseEntry.title}', but also tagged the CSF file with '${AUTODOCS_TAG}'. This is probably a mistake.`,[betterEntry.importPath,worseEntry.importPath])}else return {...betterEntry,storiesImports:[...betterEntry.storiesImports,worseEntry.importPath,...worseEntry.storiesImports]};return betterEntry}async sortStories(entries,storySortParameter){let sortableStories=Object.values(entries),fileNameOrder=this.storyFileNames();return sortStoriesV7(sortableStories,storySortParameter,fileNameOrder),sortableStories.reduce((acc,item)=>(acc[item.id]=item,acc),{})}async getIndex(){if(this.lastIndex)return this.lastIndex;if(this.lastError)throw this.lastError;let previewCode=await this.getPreviewCode(),projectTags=previewCode?this.getProjectTags(previewCode):[],storiesList=await this.ensureExtracted({projectTags});try{let errorEntries=storiesList.filter(entry=>entry.type==="error");if(errorEntries.length)throw new MultipleIndexingError(errorEntries.map(entry=>entry.err));let duplicateErrors=[],indexEntries={};if(storiesList.forEach(entry=>{try{let existing=indexEntries[entry.id];existing?indexEntries[entry.id]=this.chooseDuplicate(existing,entry):indexEntries[entry.id]=entry;}catch(err){err instanceof IndexingError&&duplicateErrors.push(err);}}),duplicateErrors.length)throw new MultipleIndexingError(duplicateErrors);let sorted=await this.sortStories(indexEntries,previewCode&&getStorySortParameter(previewCode));return this.lastIndex={v:4,entries:sorted},this.lastIndex}catch(err){throw this.lastError=err==null||err instanceof Error?err:void 0,invariant(this.lastError),logger.warn(`\u{1F6A8} ${this.lastError.toString()}`),this.lastError}}invalidateAll(){this.specifierToCache.forEach(cache3=>{Object.keys(cache3).forEach(key=>{cache3[key]=!1;});}),this.lastIndex=null,this.lastError=null;}invalidate(specifier,importPath,removed){let absolutePath=slash(path4.resolve(this.options.workingDir,importPath)),cache3=this.specifierToCache.get(specifier);invariant(cache3,`specifier does not have a matching cache entry in specifierToCache: ${JSON.stringify(specifier)}`);let cacheEntry=cache3[absolutePath];if(cacheEntry&&cacheEntry.type==="stories"){let{dependents}=cacheEntry,invalidated=new Set;this.specifierToCache.forEach(otherCache=>{dependents.forEach(dep=>{otherCache[dep]&&(invalidated.add(dep),otherCache[dep]=!1);});});}if(removed){if(cacheEntry&&cacheEntry.type==="docs"){let absoluteImports=cacheEntry.storiesImports.map(p=>path4.resolve(this.options.workingDir,p));this.findDependencies(absoluteImports).forEach(dep=>dep.dependents.splice(dep.dependents.indexOf(absolutePath),1));}delete cache3[absolutePath];}else cache3[absolutePath]=!1;this.lastIndex=null,this.lastError=null;}async getPreviewCode(){let previewFile=["js","jsx","ts","tsx","mjs","cjs","mts"].map(ext=>path4.join(this.options.configDir,`preview.${ext}`)).find(fname=>fs4.existsSync(fname));return previewFile&&(await fs4.readFile(previewFile,"utf-8")).toString()}getProjectTags(previewCode){let projectAnnotations=loadConfig(previewCode).parse(),defaultTags=["dev","test"],extraTags=this.options.docs.autodocs===!0?[AUTODOCS_TAG]:[],projectTags=projectAnnotations.getFieldValue(["tags"])??[];return [...defaultTags,...projectTags,...extraTags]}storyFileNames(){return Array.from(this.specifierToCache.values()).flatMap(r=>Object.keys(r))}};var PAGE_REGEX=/(page|screen)/i,isPageStory=storyId=>PAGE_REGEX.test(storyId),isCLIExampleEntry=entry=>["example-introduction--docs","configure-your-project--docs","example-button--docs","example-button--primary","example-button--secondary","example-button--large","example-button--small","example-header--docs","example-header--logged-in","example-header--logged-out","example-page--logged-in","example-page--logged-out"].includes(entry.id),isAnyExampleEntry=entry=>entry.id.startsWith("example-button--")||entry.id.startsWith("example-header--")||entry.id.startsWith("example-page--");function summarizeIndex(storyIndex){let storyCount=0,componentTitles=new Set,exampleStoryCount=0,onboardingStoryCount=0,onboardingDocsCount=0,exampleDocsCount=0,pageStoryCount=0,playStoryCount=0,autodocsCount=0,storiesMdxCount=0,mdxCount=0;Object.values(storyIndex.entries).forEach(entry=>{isCLIExampleEntry(entry)?(entry.type==="story"&&(exampleStoryCount+=1),entry.type==="docs"&&(exampleDocsCount+=1)):isAnyExampleEntry(entry)?(entry.type==="story"&&(onboardingStoryCount+=1),entry.type==="docs"&&(onboardingDocsCount+=1)):entry.type==="story"?(storyCount+=1,componentTitles.add(entry.title),isPageStory(entry.title)&&(pageStoryCount+=1),entry.tags?.includes(PLAY_FN_TAG)&&(playStoryCount+=1)):entry.type==="docs"&&(isMdxEntry(entry)?mdxCount+=1:entry.tags?.includes(STORIES_MDX_TAG)?storiesMdxCount+=1:entry.tags?.includes(AUTODOCS_TAG)&&(autodocsCount+=1));});let componentCount=componentTitles.size;return {storyCount,componentCount,pageStoryCount,playStoryCount,autodocsCount,storiesMdxCount,mdxCount,exampleStoryCount,exampleDocsCount,onboardingStoryCount,onboardingDocsCount,version:storyIndex.v}}async function buildOrThrow(callback){try{return await callback()}catch(err){let builderErrors=err.errors;throw builderErrors&&builderErrors.find(er=>er.text?.includes("No matching export"))?new NoMatchingExportError(err):err}}async function buildStaticStandalone(options){if(options.configType="PRODUCTION",options.outputDir==="")throw new Error("Won't remove current directory. Check your outputDir!");if(options.outputDir=resolve(options.outputDir),options.configDir=resolve(options.configDir),logger.info(chalk8`=> Cleaning outputDir: {cyan ${relative(process.cwd(),options.outputDir)}}`),options.outputDir==="/")throw new Error("Won't remove directory '/'. Check your outputDir!");await emptyDir(options.outputDir),await ensureDir(options.outputDir);let config=await loadMainConfig(options),{framework}=config,corePresets=[],frameworkName=typeof framework=="string"?framework:framework?.name;frameworkName?corePresets.push(join(frameworkName,"preset")):options.ignorePreview||logger.warn(`you have not specified a framework in your ${options.configDir}/main.js`),logger.info("=> Loading presets");let presets=await loadAllPresets({corePresets:[__require.resolve("@storybook/core-server/dist/presets/common-preset"),...corePresets],overridePresets:[__require.resolve("@storybook/core-server/dist/presets/common-override-preset")],isCritical:!0,...options}),{renderer}=await presets.apply("core",{}),build2=await presets.apply("build",{}),[previewBuilder,managerBuilder]=await getBuilders({...options,presets,build:build2}),resolvedRenderer=renderer?resolveAddonName(options.configDir,renderer,options):void 0;presets=await loadAllPresets({corePresets:[__require.resolve("@storybook/core-server/dist/presets/common-preset"),...managerBuilder.corePresets||[],...previewBuilder.corePresets||[],...resolvedRenderer?[resolvedRenderer]:[],...corePresets],overridePresets:[...previewBuilder.overridePresets||[],__require.resolve("@storybook/core-server/dist/presets/common-override-preset")],...options,build:build2});let[features,core,staticDirs,indexers,stories,docsOptions]=await Promise.all([presets.apply("features"),presets.apply("core"),presets.apply("staticDirs"),presets.apply("experimental_indexers",[]),presets.apply("stories"),presets.apply("docs",{})]),fullOptions={...options,presets,features,build:build2},effects=[];global$1.FEATURES=features,await buildOrThrow(async()=>managerBuilder.build({startTime:process.hrtime(),options:fullOptions})),staticDirs&&effects.push(copyAllStaticFilesRelativeToMain(staticDirs,options.outputDir,options.configDir));let coreServerPublicDir=join(dirname(__require.resolve("@storybook/core-server/package.json")),"public");effects.push(copy(coreServerPublicDir,options.outputDir));let initializedStoryIndexGenerator=Promise.resolve(void 0);if(!options.ignorePreview){let workingDir=process.cwd(),directories={configDir:options.configDir,workingDir},normalizedStories=normalizeStories(stories,directories),generator=new StoryIndexGenerator(normalizedStories,{...directories,indexers,docs:docsOptions,build:build2});initializedStoryIndexGenerator=generator.initialize().then(()=>generator),effects.push(extractStoriesJson(join(options.outputDir,"index.json"),initializedStoryIndexGenerator));}core?.disableProjectJson||effects.push(extractStorybookMetadata(join(options.outputDir,"project.json"),options.configDir)),options.debugWebpack&&logConfig("Preview webpack config",await previewBuilder.getConfig(fullOptions)),options.ignorePreview?logger.info("=> Not building preview"):logger.info("=> Building preview..");let startTime=process.hrtime();await Promise.all([...options.ignorePreview?[]:[previewBuilder.build({startTime,options:fullOptions}).then(async previewStats=>{logger.trace({message:"=> Preview built",time:process.hrtime(startTime)});let statsOption=options.webpackStatsJson||options.statsJson;if(statsOption){let target=statsOption===!0?options.outputDir:statsOption;await outputStats(target,previewStats);}}).catch(error=>{throw logger.error("=> Failed to build the preview"),process.exitCode=1,error})],...effects]),core?.disableTelemetry||effects.push(initializedStoryIndexGenerator.then(async generator=>{let storyIndex=await generator?.getIndex(),payload={precedingUpgrade:await getPrecedingUpgrade()};storyIndex&&Object.assign(payload,{storyIndex:summarizeIndex(storyIndex)}),await telemetry("build",payload,{configDir:options.configDir});})),logger.info(`=> Output directory: ${options.outputDir}`);}var fileExists=basename4=>[".js",".cjs"].reduce((found,ext)=>{let filename=`${basename4}${ext}`;return !found&&fs3.existsSync(filename)?filename:found},"");function getMiddleware(configDir){let middlewarePath=fileExists(path4.resolve(configDir,"middleware"));if(middlewarePath){let middlewareModule=__require(middlewarePath);return middlewareModule.__esModule&&(middlewareModule=middlewareModule.default),middlewareModule}return ()=>{}}function getServerAddresses(port,host,proto,initialPath){let address=new URL(`${proto}://localhost:${port}/`),networkAddress=new URL(`${proto}://${host||ip.address()}:${port}/`);if(initialPath){let searchParams=`?path=${decodeURIComponent(initialPath.startsWith("/")?initialPath:`/${initialPath}`)}`;address.search=searchParams,networkAddress.search=searchParams;}return {address:address.href,networkAddress:networkAddress.href}}var getServerPort=(port,{exactPort}={})=>detectFreePort(port).then(freePort=>(freePort!==port&&exactPort&&process.exit(-1),freePort)).catch(error=>{logger.error(error),process.exit(-1);}),getServerChannelUrl=(port,{https:https3})=>`${https3?"wss":"ws"}://localhost:${port}/storybook-server-channel`;async function getServer(app,options){if(!options.https)return http2.createServer(app);options.sslCert||(logger.error("Error: --ssl-cert is required with --https"),process.exit(-1)),options.sslKey||(logger.error("Error: --ssl-key is required with --https"),process.exit(-1));let sslOptions={ca:await Promise.all((options.sslCa||[]).map(ca=>readFile(ca,"utf-8"))),cert:await readFile(options.sslCert,"utf-8"),key:await readFile(options.sslKey,"utf-8")};return https.createServer(sslOptions,app)}var ServerChannelTransport=class{constructor(server){this.socket=new WebSocketServer({noServer:!0}),server.on("upgrade",(request,socket,head)=>{request.url==="/storybook-server-channel"&&this.socket.handleUpgrade(request,socket,head,ws=>{this.socket.emit("connection",ws,request);});}),this.socket.on("connection",wss=>{wss.on("message",raw=>{let data=raw.toString(),event=typeof data=="string"&&isJSON(data)?parse(data,{allowFunction:!1,allowClass:!1}):data;this.handler?.(event);});});}setHandler(handler){this.handler=handler;}send(event){let data=stringify(event,{maxDepth:15,allowFunction:!1,allowClass:!1});Array.from(this.socket.clients).filter(c=>c.readyState===WebSocket.OPEN).forEach(client=>client.send(data));}};function getServerChannel(server){let transports=[new ServerChannelTransport(server)];return new Channel({transports,async:!0})}function openInBrowser(address){let browserEnvVar=process.env.BROWSER,userBrowserIsChrome=browserEnvVar==="chrome"||browserEnvVar==="chromium"||browserEnvVar==="brave"||browserEnvVar==="com.brave.browser",openOptions=browserEnvVar?{app:{name:browserEnvVar}}:{};getDefaultBrowser(async(err,res)=>{try{res&&(res.isChrome||res.isChromium||res.identity==="com.brave.browser"||userBrowserIsChrome)?await betterOpn(address):await open(address,openOptions);}catch{logger.error(dedent`
61
+ - If so, has the file successfully loaded in Storybook and are its stories visible?`);}dependencies.forEach(dep=>{dep.dependents.push(absolutePath);});let title=csfEntry?.title||userOrAutoTitleFromSpecifier(importPath,specifier,result.title);invariant(title,"makeTitle created an undefined title. This happens when a specifier's doesn't have any matches in its fileName");let defaultName=this.options.docs.defaultName??"Docs",name=result.name||(csfEntry?autoName(importPath,csfEntry.importPath,defaultName):defaultName),id=toId(csfEntry?.metaId||title,name),tags=combineTags(...projectTags,...csfEntry?.tags??[],...result.metaTags??[],csfEntry?"attached-mdx":"unattached-mdx");return {id,title,name,importPath,storiesImports:sortedDependencies.map(dep=>dep.entries[0].importPath),type:"docs",tags}}catch(err){throw err&&err.source?.match(/mdast-util-mdx-jsx/g)&&logger.warn(`\u{1F4A1} This seems to be an MDX2 syntax error. Please refer to the MDX section in the following resource for assistance on how to fix this: ${chalk8.yellow("https://storybook.js.org/migration-guides/7.0")}`),err}}chooseDuplicate(firstEntry,secondEntry){if(firstEntry.importPath===secondEntry.importPath)return firstEntry;let firstIsBetter=!0;(secondEntry.type==="story"||isMdxEntry(secondEntry)&&firstEntry.type==="docs"&&!isMdxEntry(firstEntry))&&(firstIsBetter=!1);let betterEntry=firstIsBetter?firstEntry:secondEntry,worseEntry=firstIsBetter?secondEntry:firstEntry,changeDocsName='Use `<Meta of={} name="Other Name">` to distinguish them.';if(worseEntry.type==="story")throw new IndexingError(`Duplicate stories with id: ${firstEntry.id}`,[firstEntry.importPath,secondEntry.importPath]);if(betterEntry.type==="story"){let worseDescriptor=isMdxEntry(worseEntry)?"component docs page":"automatically generated docs page";throw betterEntry.name===this.options.docs.defaultName?new IndexingError(`You have a story for ${betterEntry.title} with the same name as your default docs entry name (${betterEntry.name}), so the docs page is being dropped. Consider changing the story name.`,[firstEntry.importPath,secondEntry.importPath]):new IndexingError(`You have a story for ${betterEntry.title} with the same name as your ${worseDescriptor} (${worseEntry.name}), so the docs page is being dropped. ${changeDocsName}`,[firstEntry.importPath,secondEntry.importPath])}else if(isMdxEntry(betterEntry)){if(isMdxEntry(worseEntry))throw new IndexingError(`You have two component docs pages with the same name ${betterEntry.title}:${betterEntry.name}. ${changeDocsName}`,[firstEntry.importPath,secondEntry.importPath]);if(worseEntry.tags?.includes(AUTODOCS_TAG)&&this.options.docs.autodocs!==!0)throw new IndexingError(`You created a component docs page for '${worseEntry.title}', but also tagged the CSF file with '${AUTODOCS_TAG}'. This is probably a mistake.`,[betterEntry.importPath,worseEntry.importPath])}else return {...betterEntry,storiesImports:[...betterEntry.storiesImports,worseEntry.importPath,...worseEntry.storiesImports]};return betterEntry}async sortStories(entries,storySortParameter){let sortableStories=Object.values(entries),fileNameOrder=this.storyFileNames();return sortStoriesV7(sortableStories,storySortParameter,fileNameOrder),sortableStories.reduce((acc,item)=>(acc[item.id]=item,acc),{})}async getIndex(){if(this.lastIndex)return this.lastIndex;if(this.lastError)throw this.lastError;let previewCode=await this.getPreviewCode(),projectTags=this.getProjectTags(previewCode),storiesList=await this.ensureExtracted({projectTags});try{let errorEntries=storiesList.filter(entry=>entry.type==="error");if(errorEntries.length)throw new MultipleIndexingError(errorEntries.map(entry=>entry.err));let duplicateErrors=[],indexEntries={};if(storiesList.forEach(entry=>{try{let existing=indexEntries[entry.id];existing?indexEntries[entry.id]=this.chooseDuplicate(existing,entry):indexEntries[entry.id]=entry;}catch(err){err instanceof IndexingError&&duplicateErrors.push(err);}}),duplicateErrors.length)throw new MultipleIndexingError(duplicateErrors);let sorted=await this.sortStories(indexEntries,previewCode&&getStorySortParameter(previewCode));return this.lastIndex={v:4,entries:sorted},this.lastIndex}catch(err){throw this.lastError=err==null||err instanceof Error?err:void 0,invariant(this.lastError),logger.warn(`\u{1F6A8} ${this.lastError.toString()}`),this.lastError}}invalidateAll(){this.specifierToCache.forEach(cache3=>{Object.keys(cache3).forEach(key=>{cache3[key]=!1;});}),this.lastIndex=null,this.lastError=null;}invalidate(specifier,importPath,removed){let absolutePath=slash(path4.resolve(this.options.workingDir,importPath)),cache3=this.specifierToCache.get(specifier);invariant(cache3,`specifier does not have a matching cache entry in specifierToCache: ${JSON.stringify(specifier)}`);let cacheEntry=cache3[absolutePath];if(cacheEntry&&cacheEntry.type==="stories"){let{dependents}=cacheEntry,invalidated=new Set;this.specifierToCache.forEach(otherCache=>{dependents.forEach(dep=>{otherCache[dep]&&(invalidated.add(dep),otherCache[dep]=!1);});});}if(removed){if(cacheEntry&&cacheEntry.type==="docs"){let absoluteImports=cacheEntry.storiesImports.map(p=>path4.resolve(this.options.workingDir,p));this.findDependencies(absoluteImports).forEach(dep=>dep.dependents.splice(dep.dependents.indexOf(absolutePath),1));}delete cache3[absolutePath];}else cache3[absolutePath]=!1;this.lastIndex=null,this.lastError=null;}async getPreviewCode(){let previewFile=["js","jsx","ts","tsx","mjs","cjs","mts"].map(ext=>path4.join(this.options.configDir,`preview.${ext}`)).find(fname=>fs4.existsSync(fname));return previewFile&&(await fs4.readFile(previewFile,"utf-8")).toString()}getProjectTags(previewCode){let projectTags=[],defaultTags=["dev","test"],extraTags=this.options.docs.autodocs===!0?[AUTODOCS_TAG]:[];return previewCode&&(projectTags=loadConfig(previewCode).parse().getFieldValue(["tags"])??[]),[...defaultTags,...projectTags,...extraTags]}storyFileNames(){return Array.from(this.specifierToCache.values()).flatMap(r=>Object.keys(r))}};var PAGE_REGEX=/(page|screen)/i,isPageStory=storyId=>PAGE_REGEX.test(storyId),isCLIExampleEntry=entry=>["example-introduction--docs","configure-your-project--docs","example-button--docs","example-button--primary","example-button--secondary","example-button--large","example-button--small","example-header--docs","example-header--logged-in","example-header--logged-out","example-page--logged-in","example-page--logged-out"].includes(entry.id),isAnyExampleEntry=entry=>entry.id.startsWith("example-button--")||entry.id.startsWith("example-header--")||entry.id.startsWith("example-page--");function summarizeIndex(storyIndex){let storyCount=0,componentTitles=new Set,exampleStoryCount=0,onboardingStoryCount=0,onboardingDocsCount=0,exampleDocsCount=0,pageStoryCount=0,playStoryCount=0,autodocsCount=0,storiesMdxCount=0,mdxCount=0;Object.values(storyIndex.entries).forEach(entry=>{isCLIExampleEntry(entry)?(entry.type==="story"&&(exampleStoryCount+=1),entry.type==="docs"&&(exampleDocsCount+=1)):isAnyExampleEntry(entry)?(entry.type==="story"&&(onboardingStoryCount+=1),entry.type==="docs"&&(onboardingDocsCount+=1)):entry.type==="story"?(storyCount+=1,componentTitles.add(entry.title),isPageStory(entry.title)&&(pageStoryCount+=1),entry.tags?.includes(PLAY_FN_TAG)&&(playStoryCount+=1)):entry.type==="docs"&&(isMdxEntry(entry)?mdxCount+=1:entry.tags?.includes(STORIES_MDX_TAG)?storiesMdxCount+=1:entry.tags?.includes(AUTODOCS_TAG)&&(autodocsCount+=1));});let componentCount=componentTitles.size;return {storyCount,componentCount,pageStoryCount,playStoryCount,autodocsCount,storiesMdxCount,mdxCount,exampleStoryCount,exampleDocsCount,onboardingStoryCount,onboardingDocsCount,version:storyIndex.v}}async function buildOrThrow(callback){try{return await callback()}catch(err){let builderErrors=err.errors;throw builderErrors&&builderErrors.find(er=>er.text?.includes("No matching export"))?new NoMatchingExportError(err):err}}async function buildStaticStandalone(options){if(options.configType="PRODUCTION",options.outputDir==="")throw new Error("Won't remove current directory. Check your outputDir!");if(options.outputDir=resolve(options.outputDir),options.configDir=resolve(options.configDir),logger.info(chalk8`=> Cleaning outputDir: {cyan ${relative(process.cwd(),options.outputDir)}}`),options.outputDir==="/")throw new Error("Won't remove directory '/'. Check your outputDir!");await emptyDir(options.outputDir),await ensureDir(options.outputDir);let config=await loadMainConfig(options),{framework}=config,corePresets=[],frameworkName=typeof framework=="string"?framework:framework?.name;frameworkName?corePresets.push(join(frameworkName,"preset")):options.ignorePreview||logger.warn(`you have not specified a framework in your ${options.configDir}/main.js`),logger.info("=> Loading presets");let presets=await loadAllPresets({corePresets:[__require.resolve("@storybook/core-server/dist/presets/common-preset"),...corePresets],overridePresets:[__require.resolve("@storybook/core-server/dist/presets/common-override-preset")],isCritical:!0,...options}),{renderer}=await presets.apply("core",{}),build2=await presets.apply("build",{}),[previewBuilder,managerBuilder]=await getBuilders({...options,presets,build:build2}),resolvedRenderer=renderer?resolveAddonName(options.configDir,renderer,options):void 0;presets=await loadAllPresets({corePresets:[__require.resolve("@storybook/core-server/dist/presets/common-preset"),...managerBuilder.corePresets||[],...previewBuilder.corePresets||[],...resolvedRenderer?[resolvedRenderer]:[],...corePresets],overridePresets:[...previewBuilder.overridePresets||[],__require.resolve("@storybook/core-server/dist/presets/common-override-preset")],...options,build:build2});let[features,core,staticDirs,indexers,stories,docsOptions]=await Promise.all([presets.apply("features"),presets.apply("core"),presets.apply("staticDirs"),presets.apply("experimental_indexers",[]),presets.apply("stories"),presets.apply("docs",{})]),fullOptions={...options,presets,features,build:build2},effects=[];global$1.FEATURES=features,await buildOrThrow(async()=>managerBuilder.build({startTime:process.hrtime(),options:fullOptions})),staticDirs&&effects.push(copyAllStaticFilesRelativeToMain(staticDirs,options.outputDir,options.configDir));let coreServerPublicDir=join(dirname(__require.resolve("@storybook/core-server/package.json")),"public");effects.push(copy(coreServerPublicDir,options.outputDir));let initializedStoryIndexGenerator=Promise.resolve(void 0);if(!options.ignorePreview){let workingDir=process.cwd(),directories={configDir:options.configDir,workingDir},normalizedStories=normalizeStories(stories,directories),generator=new StoryIndexGenerator(normalizedStories,{...directories,indexers,docs:docsOptions,build:build2});initializedStoryIndexGenerator=generator.initialize().then(()=>generator),effects.push(extractStoriesJson(join(options.outputDir,"index.json"),initializedStoryIndexGenerator));}core?.disableProjectJson||effects.push(extractStorybookMetadata(join(options.outputDir,"project.json"),options.configDir)),options.debugWebpack&&logConfig("Preview webpack config",await previewBuilder.getConfig(fullOptions)),options.ignorePreview?logger.info("=> Not building preview"):logger.info("=> Building preview..");let startTime=process.hrtime();await Promise.all([...options.ignorePreview?[]:[previewBuilder.build({startTime,options:fullOptions}).then(async previewStats=>{logger.trace({message:"=> Preview built",time:process.hrtime(startTime)});let statsOption=options.webpackStatsJson||options.statsJson;if(statsOption){let target=statsOption===!0?options.outputDir:statsOption;await outputStats(target,previewStats);}}).catch(error=>{throw logger.error("=> Failed to build the preview"),process.exitCode=1,error})],...effects]),core?.disableTelemetry||effects.push(initializedStoryIndexGenerator.then(async generator=>{let storyIndex=await generator?.getIndex(),payload={precedingUpgrade:await getPrecedingUpgrade()};storyIndex&&Object.assign(payload,{storyIndex:summarizeIndex(storyIndex)}),await telemetry("build",payload,{configDir:options.configDir});})),logger.info(`=> Output directory: ${options.outputDir}`);}var fileExists=basename4=>[".js",".cjs"].reduce((found,ext)=>{let filename=`${basename4}${ext}`;return !found&&fs3.existsSync(filename)?filename:found},"");function getMiddleware(configDir){let middlewarePath=fileExists(path4.resolve(configDir,"middleware"));if(middlewarePath){let middlewareModule=__require(middlewarePath);return middlewareModule.__esModule&&(middlewareModule=middlewareModule.default),middlewareModule}return ()=>{}}function getServerAddresses(port,host,proto,initialPath){let address=new URL(`${proto}://localhost:${port}/`),networkAddress=new URL(`${proto}://${host||ip.address()}:${port}/`);if(initialPath){let searchParams=`?path=${decodeURIComponent(initialPath.startsWith("/")?initialPath:`/${initialPath}`)}`;address.search=searchParams,networkAddress.search=searchParams;}return {address:address.href,networkAddress:networkAddress.href}}var getServerPort=(port,{exactPort}={})=>detectFreePort(port).then(freePort=>(freePort!==port&&exactPort&&process.exit(-1),freePort)).catch(error=>{logger.error(error),process.exit(-1);}),getServerChannelUrl=(port,{https:https3})=>`${https3?"wss":"ws"}://localhost:${port}/storybook-server-channel`;async function getServer(app,options){if(!options.https)return http2.createServer(app);options.sslCert||(logger.error("Error: --ssl-cert is required with --https"),process.exit(-1)),options.sslKey||(logger.error("Error: --ssl-key is required with --https"),process.exit(-1));let sslOptions={ca:await Promise.all((options.sslCa||[]).map(ca=>readFile(ca,"utf-8"))),cert:await readFile(options.sslCert,"utf-8"),key:await readFile(options.sslKey,"utf-8")};return https.createServer(sslOptions,app)}var ServerChannelTransport=class{constructor(server){this.socket=new WebSocketServer({noServer:!0}),server.on("upgrade",(request,socket,head)=>{request.url==="/storybook-server-channel"&&this.socket.handleUpgrade(request,socket,head,ws=>{this.socket.emit("connection",ws,request);});}),this.socket.on("connection",wss=>{wss.on("message",raw=>{let data=raw.toString(),event=typeof data=="string"&&isJSON(data)?parse(data,{allowFunction:!1,allowClass:!1}):data;this.handler?.(event);});});}setHandler(handler){this.handler=handler;}send(event){let data=stringify(event,{maxDepth:15,allowFunction:!1,allowClass:!1});Array.from(this.socket.clients).filter(c=>c.readyState===WebSocket.OPEN).forEach(client=>client.send(data));}};function getServerChannel(server){let transports=[new ServerChannelTransport(server)];return new Channel({transports,async:!0})}function openInBrowser(address){let browserEnvVar=process.env.BROWSER,userBrowserIsChrome=browserEnvVar==="chrome"||browserEnvVar==="chromium"||browserEnvVar==="brave"||browserEnvVar==="com.brave.browser",openOptions=browserEnvVar?{app:{name:browserEnvVar}}:{};getDefaultBrowser(async(err,res)=>{try{res&&(res.isChrome||res.isChromium||res.identity==="com.brave.browser"||userBrowserIsChrome)?await betterOpn(address):await open(address,openOptions);}catch{logger.error(dedent`
62
62
  Could not open ${address} inside a browser. If you're running this command inside a
63
63
  docker container or on a CI, you need to pass the '--ci' flag to prevent opening a
64
64
  browser by default.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@storybook/core-server",
3
- "version": "8.1.0-beta.0",
3
+ "version": "8.1.0-beta.1",
4
4
  "description": "Storybook framework-agnostic API",
5
5
  "keywords": [
6
6
  "storybook"
@@ -59,20 +59,20 @@
59
59
  "@babel/core": "^7.24.4",
60
60
  "@babel/parser": "^7.24.4",
61
61
  "@discoveryjs/json-ext": "^0.5.3",
62
- "@storybook/builder-manager": "8.1.0-beta.0",
63
- "@storybook/channels": "8.1.0-beta.0",
64
- "@storybook/core-common": "8.1.0-beta.0",
65
- "@storybook/core-events": "8.1.0-beta.0",
62
+ "@storybook/builder-manager": "8.1.0-beta.1",
63
+ "@storybook/channels": "8.1.0-beta.1",
64
+ "@storybook/core-common": "8.1.0-beta.1",
65
+ "@storybook/core-events": "8.1.0-beta.1",
66
66
  "@storybook/csf": "^0.1.7",
67
- "@storybook/csf-tools": "8.1.0-beta.0",
67
+ "@storybook/csf-tools": "8.1.0-beta.1",
68
68
  "@storybook/docs-mdx": "3.1.0-next.0",
69
69
  "@storybook/global": "^5.0.0",
70
- "@storybook/manager": "8.1.0-beta.0",
71
- "@storybook/manager-api": "8.1.0-beta.0",
72
- "@storybook/node-logger": "8.1.0-beta.0",
73
- "@storybook/preview-api": "8.1.0-beta.0",
74
- "@storybook/telemetry": "8.1.0-beta.0",
75
- "@storybook/types": "8.1.0-beta.0",
70
+ "@storybook/manager": "8.1.0-beta.1",
71
+ "@storybook/manager-api": "8.1.0-beta.1",
72
+ "@storybook/node-logger": "8.1.0-beta.1",
73
+ "@storybook/preview-api": "8.1.0-beta.1",
74
+ "@storybook/telemetry": "8.1.0-beta.1",
75
+ "@storybook/types": "8.1.0-beta.1",
76
76
  "@types/detect-port": "^1.3.0",
77
77
  "@types/diff": "^5.0.9",
78
78
  "@types/node": "^18.0.0",
@@ -103,7 +103,7 @@
103
103
  "ws": "^8.2.3"
104
104
  },
105
105
  "devDependencies": {
106
- "@storybook/addon-docs": "8.1.0-beta.0",
106
+ "@storybook/addon-docs": "8.1.0-beta.1",
107
107
  "@types/compression": "^1.7.0",
108
108
  "@types/ip": "^1.1.0",
109
109
  "@types/node-fetch": "^2.5.7",