chunk-DRU63UQR.mjs 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import deprecate from 'util-deprecate';
  2. import chalk from 'chalk';
  3. import semver, { satisfies, gt, validRange, minVersion } from 'semver';
  4. import { sync, command } from 'execa';
  5. import path2, { dirname, join } from 'path';
  6. import fs2, { existsSync, readFileSync as readFileSync$1 } from 'fs';
  7. import dedent from 'ts-dedent';
  8. import fse, { readFileSync, readFile, writeFile, createWriteStream, move, remove, pathExistsSync } from 'fs-extra';
  9. import 'strip-json-comments';
  10. import findUp, { sync as sync$1 } from 'find-up';
  11. import downloadTarball from '@ndelangen/get-tarball';
  12. import getNpmTarballUrl from 'get-npm-tarball-url';
  13. import * as tempy from 'tempy';
  14. import tempy__default from 'tempy';
  15. import { rendererPackages } from '@storybook/core-common';
  16. import { sync as sync$2 } from 'cross-spawn';
  17. import sort from 'semver/functions/sort';
  18. import { platform } from 'os';
  19. import { logger as logger$1 } from '@storybook/node-logger';
  20. import { ZipOpenFS, VirtualFS, PosixFS } from '@yarnpkg/fslib';
  21. import { getLibzipSync } from '@yarnpkg/libzip';
  22. var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty;var __require=(x=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(x,{get:(a,b)=>(typeof require<"u"?require:a)[b]}):x)(function(x){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});var __commonJS=(cb,mod)=>function(){return mod||(0, cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod));var versions_default={"@storybook/addon-a11y":"7.6.17","@storybook/addon-actions":"7.6.17","@storybook/addon-backgrounds":"7.6.17","@storybook/addon-controls":"7.6.17","@storybook/addon-docs":"7.6.17","@storybook/addon-essentials":"7.6.17","@storybook/addon-highlight":"7.6.17","@storybook/addon-interactions":"7.6.17","@storybook/addon-jest":"7.6.17","@storybook/addon-links":"7.6.17","@storybook/addon-mdx-gfm":"7.6.17","@storybook/addon-measure":"7.6.17","@storybook/addon-outline":"7.6.17","@storybook/addon-themes":"7.6.17","@storybook/addon-storyshots":"7.6.17","@storybook/addon-storyshots-puppeteer":"7.6.17","@storybook/addon-storysource":"7.6.17","@storybook/addon-toolbars":"7.6.17","@storybook/addon-viewport":"7.6.17","@storybook/addons":"7.6.17","@storybook/angular":"7.6.17","@storybook/api":"7.6.17","@storybook/blocks":"7.6.17","@storybook/builder-manager":"7.6.17","@storybook/builder-vite":"7.6.17","@storybook/builder-webpack5":"7.6.17","@storybook/channel-postmessage":"7.6.17","@storybook/channel-websocket":"7.6.17","@storybook/channels":"7.6.17","@storybook/cli":"7.6.17","@storybook/client-api":"7.6.17","@storybook/client-logger":"7.6.17","@storybook/codemod":"7.6.17","@storybook/components":"7.6.17","@storybook/core-client":"7.6.17","@storybook/core-common":"7.6.17","@storybook/core-events":"7.6.17","@storybook/core-server":"7.6.17","@storybook/core-webpack":"7.6.17","@storybook/csf-plugin":"7.6.17","@storybook/csf-tools":"7.6.17","@storybook/docs-tools":"7.6.17","@storybook/ember":"7.6.17","@storybook/html":"7.6.17","@storybook/html-vite":"7.6.17","@storybook/html-webpack5":"7.6.17","@storybook/instrumenter":"7.6.17","@storybook/manager":"7.6.17","@storybook/manager-api":"7.6.17","@storybook/nextjs":"7.6.17","@storybook/node-logger":"7.6.17","@storybook/postinstall":"7.6.17","@storybook/preact":"7.6.17","@storybook/preact-vite":"7.6.17","@storybook/preact-webpack5":"7.6.17","@storybook/preset-create-react-app":"7.6.17","@storybook/preset-html-webpack":"7.6.17","@storybook/preset-preact-webpack":"7.6.17","@storybook/preset-react-webpack":"7.6.17","@storybook/preset-server-webpack":"7.6.17","@storybook/preset-svelte-webpack":"7.6.17","@storybook/preset-vue-webpack":"7.6.17","@storybook/preset-vue3-webpack":"7.6.17","@storybook/preset-web-components-webpack":"7.6.17","@storybook/preview":"7.6.17","@storybook/preview-api":"7.6.17","@storybook/preview-web":"7.6.17","@storybook/react":"7.6.17","@storybook/react-dom-shim":"7.6.17","@storybook/react-vite":"7.6.17","@storybook/react-webpack5":"7.6.17","@storybook/router":"7.6.17","@storybook/server":"7.6.17","@storybook/server-webpack5":"7.6.17","@storybook/source-loader":"7.6.17","@storybook/store":"7.6.17","@storybook/svelte":"7.6.17","@storybook/svelte-vite":"7.6.17","@storybook/svelte-webpack5":"7.6.17","@storybook/sveltekit":"7.6.17","@storybook/telemetry":"7.6.17","@storybook/theming":"7.6.17","@storybook/types":"7.6.17","@storybook/test":"7.6.17","@storybook/vue":"7.6.17","@storybook/vue-vite":"7.6.17","@storybook/vue-webpack5":"7.6.17","@storybook/vue3":"7.6.17","@storybook/vue3-vite":"7.6.17","@storybook/vue3-webpack5":"7.6.17","@storybook/web-components":"7.6.17","@storybook/web-components-vite":"7.6.17","@storybook/web-components-webpack5":"7.6.17",sb:"7.6.17",storybook:"7.6.17"};var useNpmWarning=deprecate(()=>{},"`--use-npm` is deprecated and will be removed in Storybook 8.0. \nPlease use the `--package-manager=npm` option instead.\nRead more at https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#cli-option---use-npm-deprecated");function ltMajor(versionRange,major){return validRange(versionRange)&&minVersion(versionRange).major<major}function eqMajor(versionRange,major){return validRange(versionRange)&&minVersion(versionRange).major===major}var externalFrameworks=[{name:"qwik",packageName:"storybook-framework-qwik"},{name:"solid",frameworks:["storybook-solidjs-vite"],renderer:"storybook-solidjs"}];var ProjectType=(ProjectType2=>(ProjectType2.UNDETECTED="UNDETECTED",ProjectType2.UNSUPPORTED="UNSUPPORTED",ProjectType2.REACT="REACT",ProjectType2.REACT_SCRIPTS="REACT_SCRIPTS",ProjectType2.REACT_NATIVE="REACT_NATIVE",ProjectType2.REACT_PROJECT="REACT_PROJECT",ProjectType2.WEBPACK_REACT="WEBPACK_REACT",ProjectType2.NEXTJS="NEXTJS",ProjectType2.VUE="VUE",ProjectType2.VUE3="VUE3",ProjectType2.SFC_VUE="SFC_VUE",ProjectType2.ANGULAR="ANGULAR",ProjectType2.EMBER="EMBER",ProjectType2.WEB_COMPONENTS="WEB_COMPONENTS",ProjectType2.HTML="HTML",ProjectType2.QWIK="QWIK",ProjectType2.PREACT="PREACT",ProjectType2.SVELTE="SVELTE",ProjectType2.SVELTEKIT="SVELTEKIT",ProjectType2.SERVER="SERVER",ProjectType2.NX="NX",ProjectType2.SOLID="SOLID",ProjectType2))(ProjectType||{});var supportedTemplates=[{preset:"SFC_VUE",dependencies:{"vue-loader":versionRange=>ltMajor(versionRange,16),vuetify:versionRange=>ltMajor(versionRange,3)},matcherFunction:({dependencies})=>dependencies.some(Boolean)},{preset:"VUE",dependencies:{vue:versionRange=>ltMajor(versionRange,3),nuxt:versionRange=>ltMajor(versionRange,3)},matcherFunction:({dependencies})=>dependencies.some(Boolean)},{preset:"VUE3",dependencies:{vue:versionRange=>versionRange==="next"||eqMajor(versionRange,3)},matcherFunction:({dependencies})=>dependencies.some(Boolean)},{preset:"EMBER",dependencies:["ember-cli"],matcherFunction:({dependencies})=>dependencies.every(Boolean)},{preset:"NEXTJS",dependencies:["next"],matcherFunction:({dependencies})=>dependencies.every(Boolean)},{preset:"QWIK",dependencies:["@builder.io/qwik"],matcherFunction:({dependencies})=>dependencies.every(Boolean)},{preset:"REACT_PROJECT",peerDependencies:["react"],matcherFunction:({peerDependencies})=>peerDependencies.every(Boolean)},{preset:"REACT_NATIVE",dependencies:["react-native","react-native-scripts"],matcherFunction:({dependencies})=>dependencies.some(Boolean)},{preset:"REACT_SCRIPTS",files:["/node_modules/.bin/react-scripts"],dependencies:["react-scripts"],matcherFunction:({dependencies,files})=>dependencies.every(Boolean)||files.every(Boolean)},{preset:"ANGULAR",dependencies:["@angular/core"],matcherFunction:({dependencies})=>dependencies.every(Boolean)},{preset:"WEB_COMPONENTS",dependencies:["lit-element","lit-html","lit"],matcherFunction:({dependencies})=>dependencies.some(Boolean)},{preset:"PREACT",dependencies:["preact"],matcherFunction:({dependencies})=>dependencies.every(Boolean)},{preset:"SVELTEKIT",dependencies:["@sveltejs/kit"],matcherFunction:({dependencies})=>dependencies.every(Boolean)},{preset:"SVELTE",dependencies:["svelte"],matcherFunction:({dependencies})=>dependencies.every(Boolean)},{preset:"SOLID",dependencies:["solid-js"],matcherFunction:({dependencies})=>dependencies.every(Boolean)},{preset:"WEBPACK_REACT",dependencies:["react","webpack"],matcherFunction:({dependencies})=>dependencies.every(Boolean)},{preset:"REACT",dependencies:["react"],matcherFunction:({dependencies})=>dependencies.every(Boolean)}],unsupportedTemplate={preset:"UNSUPPORTED",dependencies:{nuxt:versionRange=>eqMajor(versionRange,3)},matcherFunction:({dependencies})=>dependencies.some(Boolean)},notInstallableProjectTypes=["UNDETECTED","UNSUPPORTED","NX"],installableProjectTypes=Object.values(ProjectType).filter(type=>!notInstallableProjectTypes.includes(type)).map(type=>type.toLowerCase());function getCliDir(){return dirname(__require.resolve("@storybook/cli/package.json"))}var resolveUsingBranchInstall=async(packageManager,request)=>{let tempDirectory=tempy.directory(),version=versions_default[request]||await packageManager.latestVersion(request),url=getNpmTarballUrl(request,version,{registry:await packageManager.getRegistryURL()});return await downloadTarball({url,dir:tempDirectory}),join(tempDirectory,"package")};async function getRendererDir(packageManager,renderer){let externalFramework=externalFrameworks.find(framework=>framework.name===renderer),frameworkPackageName=externalFramework?.renderer||externalFramework?.packageName||`@storybook/${renderer}`,packageJsonPath=join(frameworkPackageName,"package.json"),errors=[];try{return dirname(__require.resolve(packageJsonPath,{paths:[process.cwd()]}))}catch(e){errors.push(e);}try{return await resolveUsingBranchInstall(packageManager,frameworkPackageName)}catch(e){errors.push(e);}throw new Error(`Cannot find ${packageJsonPath}, ${errors.map(e=>e.stack).join(`
  23. `)}`)}var logger=console;var commandLog=message=>(process.stdout.write(chalk.cyan(" \u2022 ")+message),(errorMessage,errorInfo)=>{if(errorMessage){if(process.stdout.write(`. ${chalk.red("\u2716")}
  24. `),logger.error(`
  25. ${chalk.red(errorMessage)}`),!errorInfo)return;let newErrorInfo=errorInfo.split(`
  26. `).map(line=>` ${chalk.dim(line)}`).join(`
  27. `);logger.error(`${newErrorInfo}
  28. `);return}process.stdout.write(`. ${chalk.green("\u2713")}
  29. `);});function paddedLog(message){let newMessage=message.split(`
  30. `).map(line=>` ${line}`).join(`
  31. `);logger.log(newMessage);}async function getBabelDependencies(packageManager,packageJson){let dependenciesToAdd=[],babelLoaderVersion="^8.0.0-0",babelCoreVersion=packageJson.dependencies["babel-core"]||packageJson.devDependencies["babel-core"];if(babelCoreVersion){let latestCompatibleBabelVersion=await packageManager.latestVersion("babel-core",babelCoreVersion);satisfies(latestCompatibleBabelVersion,"^6.0.0")&&(babelLoaderVersion="^7.0.0");}else if(!packageJson.dependencies["@babel/core"]&&!packageJson.devDependencies["@babel/core"]){let babelCoreInstallVersion=await packageManager.getVersion("@babel/core");dependenciesToAdd.push(`@babel/core@${babelCoreInstallVersion}`);}if(!packageJson.dependencies["babel-loader"]&&!packageJson.devDependencies["babel-loader"]){let babelLoaderInstallVersion=await packageManager.getVersion("babel-loader",babelLoaderVersion);dependenciesToAdd.push(`babel-loader@${babelLoaderInstallVersion}`);}return dependenciesToAdd}function copyTemplate(templateRoot,destination="."){let templateDir=path2.resolve(templateRoot,"template-csf/");if(!fs2.existsSync(templateDir))throw new Error("Couldn't find template dir");fse.copySync(templateDir,destination,{overwrite:!0});}var frameworkToRenderer={angular:"angular",ember:"ember",html:"html",nextjs:"react",preact:"preact",qwik:"qwik",react:"react","react-native":"react",server:"react",solid:"solid",svelte:"svelte",sveltekit:"svelte",vue:"vue",vue3:"vue","web-components":"web-components"};async function copyTemplateFiles({packageManager,renderer,language,destination,includeCommonAssets=!0}){let languageFolderMapping={typescript:"ts",javascript:"js","typescript-3-8":"ts-3-8","typescript-4-9":"ts-4-9"},templatePath=async()=>{let baseDir=await getRendererDir(packageManager,renderer),assetsDir=join(baseDir,"template","cli"),assetsLanguage=join(assetsDir,languageFolderMapping[language]),assetsJS=join(assetsDir,languageFolderMapping.javascript),assetsTS=join(assetsDir,languageFolderMapping.typescript),assetsTS38=join(assetsDir,languageFolderMapping["typescript-3-8"]);if(await fse.pathExists(assetsLanguage))return assetsLanguage;if(language==="typescript-4-9"&&await fse.pathExists(assetsTS38))return assetsTS38;if(await fse.pathExists(assetsTS))return assetsTS;if(await fse.pathExists(assetsJS))return assetsJS;if(await fse.pathExists(assetsDir))return assetsDir;throw new Error(`Unsupported renderer: ${renderer} (${baseDir})`)},destinationPath=destination??await(async()=>await fse.pathExists("./src")?"./src/stories":"./stories")();if(includeCommonAssets&&await fse.copy(join(getCliDir(),"rendererAssets","common"),destinationPath,{overwrite:!0}),await fse.copy(await templatePath(),destinationPath,{overwrite:!0}),includeCommonAssets){let rendererType=frameworkToRenderer[renderer]||"react";await adjustTemplate(join(destinationPath,"Configure.mdx"),{renderer:rendererType});}}async function adjustTemplate(templatePath,templateData){let template=await fse.readFile(templatePath,"utf8");Object.keys(templateData).forEach(key=>{template=template.replaceAll(`{{${key}}}`,`${templateData[key]}`);}),await fse.writeFile(templatePath,template);}function getStorybookVersionSpecifier(packageJson){let allDeps={...packageJson.dependencies,...packageJson.devDependencies},storybookPackage=Object.keys(allDeps).find(name=>versions_default[name]);if(!storybookPackage)throw new Error("Couldn't find any official storybook packages in package.json");return allDeps[storybookPackage]}async function isNxProject(){return findUp.sync("nx.json")}var HandledError=class extends Error{constructor(messageOrError){super(typeof messageOrError=="string"?messageOrError:messageOrError.message);this.handled=!0;typeof messageOrError!="string"&&(this.cause=messageOrError);}};var logger2=console;function getPackageDetails(pkg){let idx=pkg.lastIndexOf("@");if(idx<=0)return [pkg,void 0];let packageName=pkg.slice(0,idx),packageVersion=pkg.slice(idx+1);return [packageName,packageVersion]}var JsPackageManager=class{async setRegistryURL(url){url?await this.executeCommand({command:"npm",args:["config","set","registry",url]}):await this.executeCommand({command:"npm",args:["config","delete","registry"]});}async getRegistryURL(){let url=(await this.executeCommand({command:"npm",args:["config","get","registry"]})).trim();return url==="undefined"?void 0:url}constructor(options){this.cwd=options?.cwd||process.cwd();}isStorybookInMonorepo(){let cwd=process.cwd();for(;;){try{let turboJsonPath=`${cwd}/turbo.json`,rushJsonPath=`${cwd}/rush.json`;if(fs2.existsSync(turboJsonPath)||fs2.existsSync(rushJsonPath))return !0;let packageJsonPath=__require.resolve(`${cwd}/package.json`),packageJsonFile=readFileSync(packageJsonPath,"utf8");if(JSON.parse(packageJsonFile).workspaces)return !0}catch{}let parentDir=path2.dirname(cwd);if(parentDir===cwd)break;cwd=parentDir;}return !1}async installDependencies(){let done=commandLog("Preparing to install dependencies");done(),logger2.log(),logger2.log(),done=commandLog("Installing dependencies"),logger2.log();try{await this.runInstall(),done();}catch(e){throw done("An error occurred while installing dependencies."),new HandledError(e)}}packageJsonPath(){return path2.resolve(this.cwd,"package.json")}async readPackageJson(){let packageJsonPath=this.packageJsonPath();if(!fs2.existsSync(packageJsonPath))throw new Error(`Could not read package.json file at ${packageJsonPath}`);let jsonContent=await readFile(packageJsonPath,"utf8");return JSON.parse(jsonContent)}async writePackageJson(packageJson){let packageJsonToWrite={...packageJson};packageJsonToWrite.dependencies&&Object.keys(packageJsonToWrite.dependencies).length===0&&delete packageJsonToWrite.dependencies,packageJsonToWrite.devDependencies&&Object.keys(packageJsonToWrite.devDependencies).length===0&&delete packageJsonToWrite.devDependencies,packageJsonToWrite.peerDependencies&&Object.keys(packageJsonToWrite.peerDependencies).length===0&&delete packageJsonToWrite.peerDependencies;let content=`${JSON.stringify(packageJsonToWrite,null,2)}
  32. `;await writeFile(this.packageJsonPath(),content,"utf8");}async retrievePackageJson(){let packageJson;try{packageJson=await this.readPackageJson();}catch(err){if(err.message.includes("Could not read package.json"))await this.initPackageJson(),packageJson=await this.readPackageJson();else throw new Error(dedent`
  33. There was an error while reading the package.json file at ${this.packageJsonPath()}: ${err.message}
  34. Please fix the error and try again.
  35. `)}return {...packageJson,dependencies:{...packageJson.dependencies},devDependencies:{...packageJson.devDependencies},peerDependencies:{...packageJson.peerDependencies}}}async getAllDependencies(){let{dependencies,devDependencies,peerDependencies}=await this.retrievePackageJson();return {...dependencies,...devDependencies,...peerDependencies}}async addDependencies(options,dependencies){let{skipInstall}=options;if(skipInstall){let{packageJson}=options,dependenciesMap=dependencies.reduce((acc,dep)=>{let[packageName,packageVersion]=getPackageDetails(dep);return {...acc,[packageName]:packageVersion}},{});options.installAsDevDependencies?packageJson.devDependencies={...packageJson.devDependencies,...dependenciesMap}:packageJson.dependencies={...packageJson.dependencies,...dependenciesMap},await this.writePackageJson(packageJson);}else try{await this.runAddDeps(dependencies,options.installAsDevDependencies);}catch(e){throw logger2.error(`
  36. An error occurred while installing dependencies:`),logger2.log(e.message),new HandledError(e)}}async removeDependencies(options,dependencies){let{skipInstall}=options;if(skipInstall){let{packageJson}=options;dependencies.forEach(dep=>{packageJson.devDependencies&&delete packageJson.devDependencies[dep],packageJson.dependencies&&delete packageJson.dependencies[dep];}),await this.writePackageJson(packageJson);}else try{await this.runRemoveDeps(dependencies);}catch(e){throw logger2.error("An error occurred while removing dependencies."),logger2.log(e.message),new HandledError(e)}}getVersionedPackages(packages){return Promise.all(packages.map(async pkg=>{let[packageName,packageVersion]=getPackageDetails(pkg),latestInRange=await this.latestVersion(packageName,packageVersion),currentVersion=versions_default[packageName];return currentVersion===latestInRange?`${packageName}`:currentVersion?`${packageName}@${currentVersion}`:`${packageName}@^${latestInRange}`}))}getVersions(...packageNames){return Promise.all(packageNames.map(packageName=>this.getVersion(packageName)))}async getVersion(packageName,constraint){let current;/(@storybook|^sb$|^storybook$)/.test(packageName)&&(current=versions_default[packageName]);let latest;try{latest=await this.latestVersion(packageName,constraint);}catch(e){if(current)return logger2.warn(`
  37. ${chalk.yellow(e.message)}`),current;throw logger2.error(`
  38. ${chalk.red(e.message)}`),new HandledError(e)}return `^${current&&(!constraint||satisfies(current,constraint))&&gt(current,latest)?current:latest}`}async latestVersion(packageName,constraint){return constraint?(await this.runGetVersions(packageName,!0)).reverse().find(version=>satisfies(version,constraint)):this.runGetVersions(packageName,!1)}async addStorybookCommandInScripts(options){let storybookCmd=`storybook dev -p ${options?.port??6006}`,buildStorybookCmd="storybook build",preCommand=options?.preCommand?this.getRunCommand(options.preCommand):void 0;await this.addScripts({storybook:[preCommand,storybookCmd].filter(Boolean).join(" && "),"build-storybook":[preCommand,buildStorybookCmd].filter(Boolean).join(" && ")});}async addScripts(scripts){let packageJson=await this.retrievePackageJson();await this.writePackageJson({...packageJson,scripts:{...packageJson.scripts,...scripts}});}async addPackageResolutions(versions){let packageJson=await this.retrievePackageJson(),resolutions=this.getResolutions(packageJson,versions);this.writePackageJson({...packageJson,...resolutions});}executeCommandSync({command,args=[],stdio,cwd,ignoreError=!1,env,...execaOptions}){try{return sync(command,args,{cwd:cwd??this.cwd,stdio:stdio??"pipe",encoding:"utf-8",shell:!0,cleanup:!0,env,...execaOptions}).stdout??""}catch(err){if(ignoreError!==!0)throw err;return ""}}async executeCommand({command: command$1,args=[],stdio,cwd,ignoreError=!1,env,...execaOptions}){try{return (await command([command$1,...args].join(" "),{cwd:cwd??this.cwd,stdio:stdio??"pipe",encoding:"utf-8",shell:!0,cleanup:!0,env,...execaOptions})).stdout??""}catch(err){if(ignoreError!==!0)throw err;return ""}}};function parseList(str){return str.split(",").map(item=>item.trim()).filter(item=>item.length>0)}async function getStorybookVersion(packageManager){return (await Promise.all(Object.keys(rendererPackages).map(async pkg=>({name:pkg,version:await packageManager.getPackageVersion(pkg)})))).filter(({version})=>!!version)[0]?.version}function getEnvConfig(program,configEnv){Object.keys(configEnv).forEach(fieldName=>{let envVarName=configEnv[fieldName],envVarValue=process.env[envVarName];envVarValue&&(program[fieldName]=envVarValue);});}var createLogStream=async(logFileName="storybook.log")=>{let finalLogPath=join(process.cwd(),logFileName),temporaryLogPath=tempy__default.file({name:logFileName}),logStream=createWriteStream(temporaryLogPath,{encoding:"utf8"});return new Promise((resolve,reject)=>{logStream.once("open",()=>{resolve({logStream,moveLogFile:async()=>move(temporaryLogPath,finalLogPath,{overwrite:!0}),clearLogFile:async()=>writeFile(temporaryLogPath,""),removeLogFile:async()=>remove(temporaryLogPath),readLogFile:async()=>readFile(temporaryLogPath,"utf8")});}),logStream.once("error",reject);})},PACKAGES_EXCLUDED_FROM_CORE=["@storybook/addon-bench","@storybook/addon-console","@storybook/addon-onboarding","@storybook/addon-postcss","@storybook/addon-designs","@storybook/addon-styling","@storybook/addon-styling-webpack","@storybook/babel-plugin-require-context-hook","@storybook/bench","@storybook/builder-vite","@storybook/csf","@storybook/design-system","@storybook/ember-cli-storybook","@storybook/eslint-config-storybook","@storybook/expect","@storybook/jest","@storybook/linter-config","@storybook/mdx1-csf","@storybook/mdx2-csf","@storybook/react-docgen-typescript-plugin","@storybook/storybook-deployer","@storybook/test-runner","@storybook/testing-library","@storybook/testing-react","@nrwl/storybook","@nx/storybook"],isCorePackage=pkg=>pkg.startsWith("@storybook/")&&!pkg.startsWith("@storybook/preset-")&&!PACKAGES_EXCLUDED_FROM_CORE.includes(pkg);var NPM_ERROR_REGEX=/npm ERR! code (\w+)/,NPM_ERROR_CODES={E401:"Authentication failed or is required.",E403:"Access to the resource is forbidden.",E404:"Requested resource not found.",EACCES:"Permission issue.",EAI_FAIL:"DNS lookup failed.",EBADENGINE:"Engine compatibility check failed.",EBADPLATFORM:"Platform not supported.",ECONNREFUSED:"Connection refused.",ECONNRESET:"Connection reset.",EEXIST:"File or directory already exists.",EINVALIDTYPE:"Invalid type encountered.",EISGIT:"Git operation failed or conflicts with an existing file.",EJSONPARSE:"Error parsing JSON data.",EMISSINGARG:"Required argument missing.",ENEEDAUTH:"Authentication needed.",ENOAUDIT:"No audit available.",ENOENT:"File or directory does not exist.",ENOGIT:"Git not found or failed to run.",ENOLOCK:"Lockfile missing.",ENOSPC:"Insufficient disk space.",ENOTFOUND:"Resource not found.",EOTP:"One-time password required.",EPERM:"Permission error.",EPUBLISHCONFLICT:"Conflict during package publishing.",ERESOLVE:"Dependency resolution error.",EROFS:"File system is read-only.",ERR_SOCKET_TIMEOUT:"Socket timed out.",ETARGET:"Package target not found.",ETIMEDOUT:"Operation timed out.",ETOOMANYARGS:"Too many arguments provided.",EUNKNOWNTYPE:"Unknown type encountered."},NPMProxy=class extends JsPackageManager{constructor(){super(...arguments);this.type="npm";}async initPackageJson(){await this.executeCommand({command:"npm",args:["init","-y"]});}getRunStorybookCommand(){return "npm run storybook"}getRunCommand(command){return `npm run ${command}`}async getNpmVersion(){return this.executeCommand({command:"npm",args:["--version"]})}async getPackageJSON(packageName,basePath=this.cwd){let packageJsonPath=await sync$1(dir=>{let possiblePath=path2.join(dir,"node_modules",packageName,"package.json");return existsSync(possiblePath)?possiblePath:void 0},{cwd:basePath});return packageJsonPath?JSON.parse(readFileSync$1(packageJsonPath,"utf-8")):null}async getPackageVersion(packageName,basePath=this.cwd){let packageJson=await this.getPackageJSON(packageName,basePath);return packageJson?semver.coerce(packageJson.version)?.version??null:null}getInstallArgs(){return this.installArgs||(this.installArgs=[]),this.installArgs}runPackageCommandSync(command,args,cwd,stdio){return this.executeCommandSync({command:"npm",args:["exec","--",command,...args],cwd,stdio})}async runPackageCommand(command,args,cwd){return this.executeCommand({command:"npm",args:["exec","--",command,...args],cwd})}async findInstallations(){let exec=async({depth})=>{let pipeToNull=platform()==="win32"?"2>NUL":"2>/dev/null";return this.executeCommand({command:"npm",args:["ls","--json",`--depth=${depth}`,pipeToNull],env:{FORCE_COLOR:"false"}})};try{let commandResult=await exec({depth:99}),parsedOutput=JSON.parse(commandResult);return this.mapDependencies(parsedOutput)}catch{try{let commandResult=await exec({depth:0}),parsedOutput=JSON.parse(commandResult);return this.mapDependencies(parsedOutput)}catch{logger$1.warn("An issue occurred while trying to find dependencies metadata using npm.");return}}}getResolutions(packageJson,versions){return {overrides:{...packageJson.overrides,...versions}}}async runInstall(){await this.executeCommand({command:"npm",args:["install",...this.getInstallArgs()],stdio:"inherit"});}async runAddDeps(dependencies,installAsDevDependencies){let{logStream,readLogFile,moveLogFile,removeLogFile}=await createLogStream(),args=[...dependencies];installAsDevDependencies&&(args=["-D",...args]);try{await this.executeCommand({command:"npm",args:["install",...args,...this.getInstallArgs()],stdio:process.env.CI?"inherit":["ignore",logStream,logStream]});}catch{let stdout=await readLogFile(),errorMessage=this.parseErrorFromLogs(stdout);throw await moveLogFile(),new Error(dedent`${errorMessage}
  39. Please check the logfile generated at ./storybook.log for troubleshooting and try again.`)}await removeLogFile();}async runRemoveDeps(dependencies){let args=[...dependencies];await this.executeCommand({command:"npm",args:["uninstall",...this.getInstallArgs(),...args],stdio:"inherit"});}async runGetVersions(packageName,fetchAllVersions){let args=[fetchAllVersions?"versions":"version","--json"],commandResult=await this.executeCommand({command:"npm",args:["info",packageName,...args]});try{let parsedOutput=JSON.parse(commandResult);if(parsedOutput.error)throw new Error(parsedOutput.error.summary);return parsedOutput}catch{throw new Error(`Unable to find versions of ${packageName} using npm`)}}mapDependencies(input){let acc={},existingVersions={},duplicatedDependencies={},recurse=([name,packageInfo])=>{if(!name||!name.includes("storybook"))return;let value={version:packageInfo.version,location:""};existingVersions[name]?.includes(value.version)||(acc[name]?acc[name].push(value):acc[name]=[value],existingVersions[name]=sort([...existingVersions[name]||[],value.version]),existingVersions[name].length>1&&(duplicatedDependencies[name]=existingVersions[name])),packageInfo.dependencies&&Object.entries(packageInfo.dependencies).forEach(recurse);};return Object.entries(input.dependencies).forEach(recurse),{dependencies:acc,duplicatedDependencies,infoCommand:"npm ls --depth=1",dedupeCommand:"npm dedupe"}}parseErrorFromLogs(logs){let finalMessage="NPM error",match=logs.match(NPM_ERROR_REGEX);if(match){let errorCode=match[1];errorCode&&(finalMessage=`${finalMessage} ${errorCode}`);let errorMessage=NPM_ERROR_CODES[errorCode];errorMessage&&(finalMessage=`${finalMessage} - ${errorMessage}`);}return finalMessage.trim()}};var PNPM_ERROR_REGEX=/(ELIFECYCLE|ERR_PNPM_[A-Z_]+)\s+(.*)/i,PNPMProxy=class extends JsPackageManager{constructor(){super(...arguments);this.type="pnpm";}detectWorkspaceRoot(){let pnpmWorkspaceYaml=`${process.cwd()}/pnpm-workspace.yaml`;return pathExistsSync(pnpmWorkspaceYaml)}async initPackageJson(){await this.executeCommand({command:"pnpm",args:["init"]});}getRunStorybookCommand(){return "pnpm run storybook"}getRunCommand(command){return `pnpm run ${command}`}async getPnpmVersion(){return this.executeCommand({command:"pnpm",args:["--version"]})}getInstallArgs(){return this.installArgs||(this.installArgs=[],this.detectWorkspaceRoot()&&this.installArgs.push("-w")),this.installArgs}runPackageCommandSync(command,args,cwd,stdio){return this.executeCommandSync({command:"pnpm",args:["exec",command,...args],cwd,stdio})}async runPackageCommand(command,args,cwd){return this.executeCommand({command:"pnpm",args:["exec",command,...args],cwd})}async findInstallations(pattern){let commandResult=await this.executeCommand({command:"pnpm",args:["list",pattern.map(p=>`"${p}"`).join(" "),"--json","--depth=99"],env:{FORCE_COLOR:"false"}});try{let parsedOutput=JSON.parse(commandResult);return this.mapDependencies(parsedOutput)}catch{return}}async getPackageJSON(packageName,basePath=this.cwd){let pnpapiPath=sync$1([".pnp.js",".pnp.cjs"],{cwd:basePath});if(pnpapiPath)try{let pnpApi=__require(pnpapiPath),resolvedPath=await pnpApi.resolveToUnqualified(packageName,basePath,{considerBuiltins:!1}),pkgLocator=pnpApi.findPackageLocator(resolvedPath),pkg=pnpApi.getPackageInformation(pkgLocator);return JSON.parse(fs2.readFileSync(path2.join(pkg.packageLocation,"package.json"),"utf-8"))}catch(error){return error.code!=="MODULE_NOT_FOUND"&&console.error("Error while fetching package version in PNPM PnP mode:",error),null}let packageJsonPath=await sync$1(dir=>{let possiblePath=path2.join(dir,"node_modules",packageName,"package.json");return fs2.existsSync(possiblePath)?possiblePath:void 0},{cwd:basePath});return packageJsonPath?JSON.parse(fs2.readFileSync(packageJsonPath,"utf-8")):null}async getPackageVersion(packageName,basePath=this.cwd){let packageJSON=await this.getPackageJSON(packageName,basePath);return packageJSON?semver.coerce(packageJSON.version)?.version??null:null}getResolutions(packageJson,versions){return {overrides:{...packageJson.overrides,...versions}}}async runInstall(){await this.executeCommand({command:"pnpm",args:["install",...this.getInstallArgs()],stdio:"inherit"});}async runAddDeps(dependencies,installAsDevDependencies){let args=[...dependencies];installAsDevDependencies&&(args=["-D",...args]);let{logStream,readLogFile,moveLogFile,removeLogFile}=await createLogStream();try{await this.executeCommand({command:"pnpm",args:["add",...args,...this.getInstallArgs()],stdio:process.env.CI?"inherit":["ignore",logStream,logStream]});}catch{let stdout=await readLogFile(),errorMessage=this.parseErrorFromLogs(stdout);throw await moveLogFile(),new Error(dedent`${errorMessage}
  40. Please check the logfile generated at ./storybook.log for troubleshooting and try again.`)}await removeLogFile();}async runRemoveDeps(dependencies){let args=[...dependencies];await this.executeCommand({command:"pnpm",args:["remove",...args,...this.getInstallArgs()],stdio:"inherit"});}async runGetVersions(packageName,fetchAllVersions){let args=[fetchAllVersions?"versions":"version","--json"],commandResult=await this.executeCommand({command:"pnpm",args:["info",packageName,...args]});try{let parsedOutput=JSON.parse(commandResult);if(parsedOutput.error)throw new Error(parsedOutput.error.summary);return parsedOutput}catch{throw new Error(`Unable to find versions of ${packageName} using pnpm`)}}mapDependencies(input){let acc={},existingVersions={},duplicatedDependencies={},items=input.reduce((curr,item)=>{let{devDependencies,dependencies,peerDependencies}=item,allDependencies={...devDependencies,...dependencies,...peerDependencies};return Object.assign(curr,allDependencies)},{}),recurse=([name,packageInfo])=>{if(!name||!name.includes("storybook"))return;let value={version:packageInfo.version,location:""};existingVersions[name]?.includes(value.version)||(acc[name]?acc[name].push(value):acc[name]=[value],existingVersions[name]=[...existingVersions[name]||[],value.version],existingVersions[name].length>1&&(duplicatedDependencies[name]=existingVersions[name])),packageInfo.dependencies&&Object.entries(packageInfo.dependencies).forEach(recurse);};return Object.entries(items).forEach(recurse),{dependencies:acc,duplicatedDependencies,infoCommand:"pnpm list --depth=1",dedupeCommand:"pnpm dedupe"}}parseErrorFromLogs(logs){let finalMessage="PNPM error",match=logs.match(PNPM_ERROR_REGEX);if(match){let[errorCode]=match;errorCode&&(finalMessage=`${finalMessage} ${errorCode}`);}return finalMessage.trim()}};var parsePackageData=(packageName="")=>{let[first,second,third]=packageName.replace(/[└─├]+/g,"").trim().split("@"),version=(third||second).replace("npm:","");return {name:third?`@${second}`:first,value:{version,location:""}}};var YARN2_ERROR_REGEX=/(YN\d{4}):.*?Error:\s+(.*)/i,YARN2_ERROR_CODES={YN0000:"UNNAMED",YN0001:"EXCEPTION",YN0002:"MISSING_PEER_DEPENDENCY",YN0003:"CYCLIC_DEPENDENCIES",YN0004:"DISABLED_BUILD_SCRIPTS",YN0005:"BUILD_DISABLED",YN0006:"SOFT_LINK_BUILD",YN0007:"MUST_BUILD",YN0008:"MUST_REBUILD",YN0009:"BUILD_FAILED",YN0010:"RESOLVER_NOT_FOUND",YN0011:"FETCHER_NOT_FOUND",YN0012:"LINKER_NOT_FOUND",YN0013:"FETCH_NOT_CACHED",YN0014:"YARN_IMPORT_FAILED",YN0015:"REMOTE_INVALID",YN0016:"REMOTE_NOT_FOUND",YN0017:"RESOLUTION_PACK",YN0018:"CACHE_CHECKSUM_MISMATCH",YN0019:"UNUSED_CACHE_ENTRY",YN0020:"MISSING_LOCKFILE_ENTRY",YN0021:"WORKSPACE_NOT_FOUND",YN0022:"TOO_MANY_MATCHING_WORKSPACES",YN0023:"CONSTRAINTS_MISSING_DEPENDENCY",YN0024:"CONSTRAINTS_INCOMPATIBLE_DEPENDENCY",YN0025:"CONSTRAINTS_EXTRANEOUS_DEPENDENCY",YN0026:"CONSTRAINTS_INVALID_DEPENDENCY",YN0027:"CANT_SUGGEST_RESOLUTIONS",YN0028:"FROZEN_LOCKFILE_EXCEPTION",YN0029:"CROSS_DRIVE_VIRTUAL_LOCAL",YN0030:"FETCH_FAILED",YN0031:"DANGEROUS_NODE_MODULES",YN0032:"NODE_GYP_INJECTED",YN0046:"AUTOMERGE_FAILED_TO_PARSE",YN0047:"AUTOMERGE_IMMUTABLE",YN0048:"AUTOMERGE_SUCCESS",YN0049:"AUTOMERGE_REQUIRED",YN0050:"DEPRECATED_CLI_SETTINGS",YN0059:"INVALID_RANGE_PEER_DEPENDENCY",YN0060:"INCOMPATIBLE_PEER_DEPENDENCY",YN0061:"DEPRECATED_PACKAGE",YN0062:"INCOMPATIBLE_OS",YN0063:"INCOMPATIBLE_CPU",YN0068:"UNUSED_PACKAGE_EXTENSION",YN0069:"REDUNDANT_PACKAGE_EXTENSION",YN0071:"NM_CANT_INSTALL_EXTERNAL_SOFT_LINK",YN0072:"NM_PRESERVE_SYMLINKS_REQUIRED",YN0074:"NM_HARDLINKS_MODE_DOWNGRADED",YN0075:"PROLOG_INSTANTIATION_ERROR",YN0076:"INCOMPATIBLE_ARCHITECTURE",YN0077:"GHOST_ARCHITECTURE"},Yarn2Proxy=class extends JsPackageManager{constructor(){super(...arguments);this.type="yarn2";}getInstallArgs(){return this.installArgs||(this.installArgs=[]),this.installArgs}async initPackageJson(){await this.executeCommand({command:"yarn",args:["init"]});}getRunStorybookCommand(){return "yarn storybook"}getRunCommand(command){return `yarn ${command}`}runPackageCommandSync(command,args,cwd,stdio){return this.executeCommandSync({command:"yarn",args:[command,...args],cwd,stdio})}async runPackageCommand(command,args,cwd){return this.executeCommand({command:"yarn",args:[command,...args],cwd})}async findInstallations(pattern){let commandResult=await this.executeCommand({command:"yarn",args:["info","--name-only","--recursive",pattern.map(p=>`"${p}"`).join(" "),`"${pattern}"`],env:{FORCE_COLOR:"false"}});try{return this.mapDependencies(commandResult)}catch{return}}async getPackageJSON(packageName,basePath=this.cwd){let pnpapiPath=sync$1([".pnp.js",".pnp.cjs"],{cwd:basePath});if(pnpapiPath)try{let pnpApi=__require(pnpapiPath),resolvedPath=await pnpApi.resolveToUnqualified(packageName,basePath,{considerBuiltins:!1}),pkgLocator=pnpApi.findPackageLocator(resolvedPath),pkg=pnpApi.getPackageInformation(pkgLocator),zipOpenFs=new ZipOpenFS({libzip:getLibzipSync()}),virtualFs=new VirtualFS({baseFs:zipOpenFs}),crossFs=new PosixFS(virtualFs),virtualPath=path2.join(pkg.packageLocation,"package.json");return crossFs.readJsonSync(virtualPath)}catch(error){return error.code!=="MODULE_NOT_FOUND"&&console.error("Error while fetching package version in Yarn PnP mode:",error),null}let packageJsonPath=await sync$1(dir=>{let possiblePath=path2.join(dir,"node_modules",packageName,"package.json");return existsSync(possiblePath)?possiblePath:void 0},{cwd:basePath});return packageJsonPath?JSON.parse(readFileSync$1(packageJsonPath,"utf-8")):null}async getPackageVersion(packageName,basePath=this.cwd){let packageJSON=await this.getPackageJSON(packageName,basePath);return packageJSON?semver.coerce(packageJSON.version)?.version??null:null}getResolutions(packageJson,versions){return {resolutions:{...packageJson.resolutions,...versions}}}async runInstall(){await this.executeCommand({command:"yarn",args:["install",...this.getInstallArgs()],stdio:"inherit"});}async runAddDeps(dependencies,installAsDevDependencies){let args=[...dependencies];installAsDevDependencies&&(args=["-D",...args]);let{logStream,readLogFile,moveLogFile,removeLogFile}=await createLogStream();try{await this.executeCommand({command:"yarn",args:["add",...this.getInstallArgs(),...args],stdio:process.env.CI?"inherit":["ignore",logStream,logStream]});}catch{let stdout=await readLogFile(),errorMessage=this.parseErrorFromLogs(stdout);throw await moveLogFile(),new Error(dedent`${errorMessage}
  41. Please check the logfile generated at ./storybook.log for troubleshooting and try again.`)}await removeLogFile();}async runRemoveDeps(dependencies){let args=[...dependencies];await this.executeCommand({command:"yarn",args:["remove",...this.getInstallArgs(),...args],stdio:"inherit"});}async runGetVersions(packageName,fetchAllVersions){let field=fetchAllVersions?"versions":"version",args=["--fields",field,"--json"],commandResult=await this.executeCommand({command:"yarn",args:["npm","info",packageName,...args]});try{return JSON.parse(commandResult)[field]}catch{throw new Error(`Unable to find versions of ${packageName} using yarn 2`)}}mapDependencies(input){let lines=input.split(`
  42. `),acc={},existingVersions={},duplicatedDependencies={};return lines.forEach(packageName=>{if(!packageName||!packageName.includes("storybook"))return;let{name,value}=parsePackageData(packageName.replaceAll('"',""));existingVersions[name]?.includes(value.version)||(acc[name]?acc[name].push(value):acc[name]=[value],existingVersions[name]=[...existingVersions[name]||[],value.version],existingVersions[name].length>1&&(duplicatedDependencies[name]=existingVersions[name]));}),{dependencies:acc,duplicatedDependencies,infoCommand:"yarn why",dedupeCommand:"yarn dedupe"}}parseErrorFromLogs(logs){let finalMessage="YARN2 error",match=logs.match(YARN2_ERROR_REGEX);if(match){let errorCode=match[1];errorCode&&(finalMessage=`${finalMessage} ${errorCode}`);let errorType=YARN2_ERROR_CODES[errorCode];errorType&&(finalMessage=`${finalMessage} - ${errorType}`);let errorMessage=match[2];errorMessage&&(finalMessage=`${finalMessage}: ${errorMessage}`);}return finalMessage.trim()}};var YARN1_ERROR_REGEX=/^error\s(.*)$/gm,Yarn1Proxy=class extends JsPackageManager{constructor(){super(...arguments);this.type="yarn1";}getInstallArgs(){return this.installArgs||(this.installArgs=["--ignore-workspace-root-check"]),this.installArgs}async initPackageJson(){await this.executeCommand({command:"yarn",args:["init","-y"]});}getRunStorybookCommand(){return "yarn storybook"}getRunCommand(command){return `yarn ${command}`}runPackageCommandSync(command,args,cwd,stdio){return this.executeCommandSync({command:"yarn",args:[command,...args],cwd,stdio})}async runPackageCommand(command,args,cwd){return this.executeCommand({command:"yarn",args:[command,...args],cwd})}async getPackageJSON(packageName,basePath=this.cwd){let packageJsonPath=await sync$1(dir=>{let possiblePath=path2.join(dir,"node_modules",packageName,"package.json");return existsSync(possiblePath)?possiblePath:void 0},{cwd:basePath});return packageJsonPath?JSON.parse(readFileSync$1(packageJsonPath,"utf-8")):null}async getPackageVersion(packageName,basePath=this.cwd){let packageJson=await this.getPackageJSON(packageName,basePath);return packageJson?semver.coerce(packageJson.version)?.version??null:null}async findInstallations(pattern){let commandResult=await this.executeCommand({command:"yarn",args:["list","--pattern",pattern.map(p=>`"${p}"`).join(" "),"--recursive","--json"],env:{FORCE_COLOR:"false"}});try{let parsedOutput=JSON.parse(commandResult);return this.mapDependencies(parsedOutput)}catch{return}}getResolutions(packageJson,versions){return {resolutions:{...packageJson.resolutions,...versions}}}async runInstall(){await this.executeCommand({command:"yarn",args:["install",...this.getInstallArgs()],stdio:"inherit"});}async runAddDeps(dependencies,installAsDevDependencies){let args=[...dependencies];installAsDevDependencies&&(args=["-D",...args]);let{logStream,readLogFile,moveLogFile,removeLogFile}=await createLogStream();try{await this.executeCommand({command:"yarn",args:["add",...this.getInstallArgs(),...args],stdio:process.env.CI?"inherit":["ignore",logStream,logStream]});}catch{let stdout=await readLogFile(),errorMessage=this.parseErrorFromLogs(stdout);throw await moveLogFile(),new Error(dedent`${errorMessage}
  43. Please check the logfile generated at ./storybook.log for troubleshooting and try again.`)}await removeLogFile();}async runRemoveDeps(dependencies){let args=[...dependencies];await this.executeCommand({command:"yarn",args:["remove",...this.getInstallArgs(),...args],stdio:"inherit"});}async runGetVersions(packageName,fetchAllVersions){let args=[fetchAllVersions?"versions":"version","--json"],commandResult=await this.executeCommand({command:"yarn",args:["info",packageName,...args]});try{let parsedOutput=JSON.parse(commandResult);if(parsedOutput.type==="inspect")return parsedOutput.data;throw new Error(`Unable to find versions of ${packageName} using yarn`)}catch{throw new Error(`Unable to find versions of ${packageName} using yarn`)}}mapDependencies(input){if(input.type==="tree"){let{trees}=input.data,acc={},existingVersions={},duplicatedDependencies={},recurse=tree=>{let{children}=tree,{name,value}=parsePackageData(tree.name);!name||!name.includes("storybook")||(existingVersions[name]?.includes(value.version)||(acc[name]?acc[name].push(value):acc[name]=[value],existingVersions[name]=[...existingVersions[name]||[],value.version],existingVersions[name].length>1&&(duplicatedDependencies[name]=existingVersions[name])),children.forEach(recurse));};return trees.forEach(recurse),{dependencies:acc,duplicatedDependencies,infoCommand:"yarn why",dedupeCommand:"yarn dedupe"}}throw new Error("Something went wrong while parsing yarn output")}parseErrorFromLogs(logs){let finalMessage="YARN1 error",match=logs.match(YARN1_ERROR_REGEX);if(match){let errorMessage=match[0]?.replace(/^error\s(.*)$/,"$1");errorMessage&&(finalMessage=`${finalMessage}: ${errorMessage}`);}return finalMessage.trim()}};var NPM_LOCKFILE="package-lock.json",PNPM_LOCKFILE="pnpm-lock.yaml",YARN_LOCKFILE="yarn.lock",JsPackageManagerFactory=class{static getPackageManager({force}={},cwd){if(force==="npm")return new NPMProxy({cwd});if(force==="pnpm")return new PNPMProxy({cwd});if(force==="yarn1")return new Yarn1Proxy({cwd});if(force==="yarn2")return new Yarn2Proxy({cwd});let yarnVersion=getYarnVersion(cwd),closestLockfilePath=sync$1([YARN_LOCKFILE,PNPM_LOCKFILE,NPM_LOCKFILE],{cwd}),closestLockfile=closestLockfilePath&&path2.basename(closestLockfilePath),hasNPMCommand=hasNPM(cwd),hasPNPMCommand=hasPNPM(cwd);if(yarnVersion&&(closestLockfile===YARN_LOCKFILE||!hasNPMCommand&&!hasPNPMCommand))return yarnVersion===1?new Yarn1Proxy({cwd}):new Yarn2Proxy({cwd});if(hasPNPMCommand&&closestLockfile===PNPM_LOCKFILE)return new PNPMProxy({cwd});if(hasNPMCommand)return new NPMProxy({cwd});throw new Error("Unable to find a usable package manager within NPM, PNPM, Yarn and Yarn 2")}};function hasNPM(cwd){return sync$2("npm",["--version"],{cwd,shell:!0}).status===0}function hasPNPM(cwd){return sync$2("pnpm",["--version"],{cwd,shell:!0}).status===0}function getYarnVersion(cwd){let yarnVersionCommand=sync$2("yarn",["--version"],{cwd,shell:!0});if(yarnVersionCommand.status!==0)return;let yarnVersion=yarnVersionCommand.output.toString().replace(/,/g,"").replace(/"/g,"");return /^1\.+/.test(yarnVersion)?1:2}
  44. export { HandledError, JsPackageManager, JsPackageManagerFactory, __commonJS, __require, __toESM, commandLog, copyTemplate, copyTemplateFiles, createLogStream, externalFrameworks, getBabelDependencies, getCliDir, getEnvConfig, getPackageDetails, getStorybookVersion, getStorybookVersionSpecifier, installableProjectTypes, isCorePackage, isNxProject, paddedLog, parseList, supportedTemplates, unsupportedTemplate, useNpmWarning, versions_default };