From 6f6ed73158f011dab8b342b636a6f41c3270ec9f Mon Sep 17 00:00:00 2001 From: Jeppe Reinhold Date: Thu, 11 Jan 2024 23:13:48 +0100 Subject: [PATCH 1/7] new upgrade workflow based on https://github.com/storybookjs/storybook/pull/25553 --- code/lib/cli/src/generate.ts | 4 +- .../js-package-manager/JsPackageManager.ts | 2 + code/lib/cli/src/upgrade.test.ts | 87 +++------ code/lib/cli/src/upgrade.ts | 178 +++++++++--------- .../core-events/src/errors/server-errors.ts | 47 +++++ 5 files changed, 161 insertions(+), 157 deletions(-) diff --git a/code/lib/cli/src/generate.ts b/code/lib/cli/src/generate.ts index 8f37de772933..be3c4da1175e 100644 --- a/code/lib/cli/src/generate.ts +++ b/code/lib/cli/src/generate.ts @@ -73,7 +73,7 @@ command('babelrc') .action(() => generateStorybookBabelConfigInCWD()); command('upgrade') - .description('Upgrade your Storybook packages to the latest') + .description(`Upgrade your Storybook packages to v${versions.storybook}`) .option( '--package-manager ', 'Force package manager for installing dependencies' @@ -81,8 +81,6 @@ command('upgrade') .option('-N --use-npm', 'Use NPM to install dependencies (deprecated)') .option('-y --yes', 'Skip prompting the user') .option('-n --dry-run', 'Only check for upgrades, do not install') - .option('-t --tag ', 'Upgrade to a certain npm dist-tag (e.g. next, prerelease)') - .option('-p --prerelease', 'Upgrade to the pre-release packages') .option('-s --skip-check', 'Skip postinstall version and automigration checks') .option('-c, --config-dir ', 'Directory where to load Storybook configurations from') .action(async (options: UpgradeOptions) => upgrade(options).catch(() => process.exit(1))); diff --git a/code/lib/cli/src/js-package-manager/JsPackageManager.ts b/code/lib/cli/src/js-package-manager/JsPackageManager.ts index 52c0e53d1455..fca583935c84 100644 --- a/code/lib/cli/src/js-package-manager/JsPackageManager.ts +++ b/code/lib/cli/src/js-package-manager/JsPackageManager.ts @@ -133,6 +133,8 @@ export abstract class JsPackageManager { done = commandLog('Installing dependencies'); + logger.log(); + try { await this.runInstall(); done(); diff --git a/code/lib/cli/src/upgrade.test.ts b/code/lib/cli/src/upgrade.test.ts index 1110946e0b2b..d9445b66fcfb 100644 --- a/code/lib/cli/src/upgrade.test.ts +++ b/code/lib/cli/src/upgrade.test.ts @@ -1,4 +1,20 @@ -import { addExtraFlags, addNxPackagesToReject, getStorybookVersion } from './upgrade'; +import { getStorybookCoreVersion } from '@storybook/telemetry'; +import { + UpgradeStorybookToLowerVersionError, + UpgradeStorybookToSameVersionError, +} from '@storybook/core-events/server-errors'; +import { doUpgrade, getStorybookVersion } from './upgrade'; + +jest.mock('@storybook/telemetry'); +jest.mock('./versions', () => { + const originalVersions = jest.requireActual('./versions').default; + return { + default: Object.keys(originalVersions).reduce((acc, key) => { + acc[key] = '8.0.0'; + return acc; + }, {} as Record), + }; +}); describe.each([ ['│ │ │ ├── @babel/code-frame@7.10.3 deduped', null], @@ -21,68 +37,15 @@ describe.each([ }); }); -describe('extra flags', () => { - const extraFlags = { - 'react-scripts@<5': ['--foo'], - }; - const devDependencies = {}; - it('package matches constraints', () => { - expect( - addExtraFlags(extraFlags, [], { dependencies: { 'react-scripts': '4' }, devDependencies }) - ).toEqual(['--foo']); - }); - it('package prerelease matches constraints', () => { - expect( - addExtraFlags(extraFlags, [], { - dependencies: { 'react-scripts': '4.0.0-alpha.0' }, - devDependencies, - }) - ).toEqual(['--foo']); - }); - it('package not matches constraints', () => { - expect( - addExtraFlags(extraFlags, [], { - dependencies: { 'react-scripts': '5.0.0-alpha.0' }, - devDependencies, - }) - ).toEqual([]); - }); - it('no package not matches constraints', () => { - expect( - addExtraFlags(extraFlags, [], { - dependencies: {}, - devDependencies, - }) - ).toEqual([]); - }); -}); +describe('Upgrade errors', () => { + it('should throw an error when upgrading to a lower version number', async () => { + jest.mocked(getStorybookCoreVersion).mockResolvedValue('8.1.0'); -describe('addNxPackagesToReject', () => { - it('reject exists and is in regex pattern', () => { - const flags = ['--reject', '/preset-create-react-app/', '--some-flag', 'hello']; - expect(addNxPackagesToReject(flags)).toMatchObject([ - '--reject', - '/(preset-create-react-app|@nrwl/storybook|@nx/storybook)/', - '--some-flag', - 'hello', - ]); + await expect(doUpgrade({} as any)).rejects.toThrowError(UpgradeStorybookToLowerVersionError); }); - it('reject exists and is in unknown pattern', () => { - const flags = ['--some-flag', 'hello', '--reject', '@storybook/preset-create-react-app']; - expect(addNxPackagesToReject(flags)).toMatchObject([ - '--some-flag', - 'hello', - '--reject', - '@storybook/preset-create-react-app,@nrwl/storybook,@nx/storybook', - ]); - }); - it('reject does not exist', () => { - const flags = ['--some-flag', 'hello']; - expect(addNxPackagesToReject(flags)).toMatchObject([ - '--some-flag', - 'hello', - '--reject', - '@nrwl/storybook,@nx/storybook', - ]); + it('should throw an error when upgrading to the same version number', async () => { + jest.mocked(getStorybookCoreVersion).mockResolvedValue('8.0.0'); + + await expect(doUpgrade({} as any)).rejects.toThrowError(UpgradeStorybookToSameVersionError); }); }); diff --git a/code/lib/cli/src/upgrade.ts b/code/lib/cli/src/upgrade.ts index dd31f177df53..787998fce0a8 100644 --- a/code/lib/cli/src/upgrade.ts +++ b/code/lib/cli/src/upgrade.ts @@ -1,14 +1,22 @@ import { sync as spawnSync } from 'cross-spawn'; import { telemetry, getStorybookCoreVersion } from '@storybook/telemetry'; -import semver from 'semver'; +import semver, { coerce, eq, lt, prerelease } from 'semver'; import { logger } from '@storybook/node-logger'; import { withTelemetry } from '@storybook/core-server'; - -import type { PackageJsonWithMaybeDeps, PackageManagerName } from './js-package-manager'; -import { getPackageDetails, JsPackageManagerFactory, useNpmWarning } from './js-package-manager'; +import { + UpgradeStorybookToLowerVersionError, + UpgradeStorybookToSameVersionError, +} from '@storybook/core-events/server-errors'; + +import chalk from 'chalk'; +import dedent from 'ts-dedent'; +import boxen from 'boxen'; +import type { PackageManagerName } from './js-package-manager'; +import { JsPackageManagerFactory, useNpmWarning } from './js-package-manager'; import { commandLog } from './helpers'; import { automigrate } from './automigrate'; import { isCorePackage } from './utils'; +import versions from './versions'; type Package = { package: string; @@ -83,57 +91,7 @@ export const checkVersionConsistency = () => { }); }; -type ExtraFlags = Record; -const EXTRA_FLAGS: ExtraFlags = { - 'react-scripts@<5': ['--reject', '/preset-create-react-app/'], -}; - -export const addExtraFlags = ( - extraFlags: ExtraFlags, - flags: string[], - { dependencies, devDependencies }: PackageJsonWithMaybeDeps -) => { - return Object.entries(extraFlags).reduce( - (acc, entry) => { - const [pattern, extra] = entry; - const [pkg, specifier] = getPackageDetails(pattern); - const pkgVersion = dependencies[pkg] || devDependencies[pkg]; - - if (pkgVersion && semver.satisfies(semver.coerce(pkgVersion), specifier)) { - return [...acc, ...extra]; - } - - return acc; - }, - [...flags] - ); -}; - -export const addNxPackagesToReject = (flags: string[]) => { - const newFlags = [...flags]; - const index = flags.indexOf('--reject'); - if (index > -1) { - // Try to understand if it's in the format of a regex pattern - if (newFlags[index + 1].endsWith('/') && newFlags[index + 1].startsWith('/')) { - // Remove last and first slash so that I can add the parentheses - newFlags[index + 1] = newFlags[index + 1].substring(1, newFlags[index + 1].length - 1); - newFlags[index + 1] = `/(${newFlags[index + 1]}|@nrwl/storybook|@nx/storybook)/`; - } else { - // Adding the two packages as comma-separated values - // If the existing rejects are in regex format, they will be ignored. - // Maybe we need to find a more robust way to treat rejects? - newFlags[index + 1] = `${newFlags[index + 1]},@nrwl/storybook,@nx/storybook`; - } - } else { - newFlags.push('--reject'); - newFlags.push('@nrwl/storybook,@nx/storybook'); - } - return newFlags; -}; - export interface UpgradeOptions { - tag: string; - prerelease: boolean; skipCheck: boolean; useNpm: boolean; packageManager: PackageManagerName; @@ -144,8 +102,6 @@ export interface UpgradeOptions { } export const doUpgrade = async ({ - tag, - prerelease, skipCheck, useNpm, packageManager: pkgMgr, @@ -161,48 +117,88 @@ export const doUpgrade = async ({ } const packageManager = JsPackageManagerFactory.getPackageManager({ force: pkgMgr }); + const currentVersion = versions['@storybook/cli']; const beforeVersion = await getStorybookCoreVersion(); - commandLog(`Checking for latest versions of '@storybook/*' packages`); - - if (tag && prerelease) { - throw new Error( - `Cannot set both --tag and --prerelease. Use --tag next to get the latest prereleae` - ); + if (lt(currentVersion, beforeVersion)) { + throw new UpgradeStorybookToLowerVersionError({ beforeVersion, currentVersion }); } - - let target = 'latest'; - if (prerelease) { - // '@next' is storybook's convention for the latest prerelease tag. - // This used to be 'greatest', but that was not reliable and could pick canaries, etc. - // and random releases of other packages with storybook in their name. - target = '@next'; - } else if (tag) { - target = `@${tag}`; + if (eq(currentVersion, beforeVersion)) { + throw new UpgradeStorybookToSameVersionError({ beforeVersion }); } - let flags = []; - if (!dryRun) flags.push('--upgrade'); - flags.push('--target'); - flags.push(target); - flags = addExtraFlags(EXTRA_FLAGS, flags, await packageManager.retrievePackageJson()); - flags = addNxPackagesToReject(flags); - const check = spawnSync('npx', ['npm-check-updates@latest', '/storybook/', ...flags], { - stdio: 'pipe', - shell: true, - }); - logger.info(check.stdout.toString()); - logger.info(check.stderr.toString()); + const latestVersion = await packageManager.latestVersion('@storybook/cli'); + const isOutdated = lt(currentVersion, latestVersion); + const isPrerelease = prerelease(currentVersion) !== null; + + const borderColor = isOutdated ? '#FC521F' : '#F1618C'; + + const messages = { + welcome: `Upgrading Storybook from version ${chalk.bold(beforeVersion)} to version ${chalk.bold( + currentVersion + )}..`, + notLatest: chalk.red(dedent` + This version is behind the latest release, which is: ${chalk.bold(latestVersion)}! + You likely ran the upgrade command through npx, which can use a locally cached version, to upgrade to the latest version please run: + ${chalk.bold('npx storybook@latest upgrade')} + + You may want to CTRL+C to stop, and run with the latest version instead. + `), + prelease: chalk.yellow('This is a pre-release version.'), + }; - const checkSb = spawnSync('npx', ['npm-check-updates@latest', 'sb', ...flags], { - stdio: 'pipe', - shell: true, - }); - logger.info(checkSb.stdout.toString()); - logger.info(checkSb.stderr.toString()); + logger.plain( + boxen( + [messages.welcome] + .concat(isOutdated && !isPrerelease ? [messages.notLatest] : []) + .concat(isPrerelease ? [messages.prelease] : []) + .join('\n'), + { borderStyle: 'round', padding: 1, borderColor } + ) + ); + + const packageJson = await packageManager.retrievePackageJson(); + + const toUpgradedDependencies = (deps: Record) => { + const monorepoDependencies = Object.keys(deps || {}).filter((dependency) => { + // don't upgrade @storybook/preset-create-react-app if react-scripts is < v5 + if (dependency === '@storybook/preset-create-react-app') { + const reactScriptsVersion = + packageJson.dependencies['react-scripts'] ?? packageJson.devDependencies['react-scripts']; + if (reactScriptsVersion && lt(coerce(reactScriptsVersion), '5.0.0')) { + return false; + } + } + + // only upgrade packages that are in the monorepo + return dependency in versions; + }) as Array; + return monorepoDependencies.map( + (dependency) => + // add ^ modifier to the version if this is the latest and stable version + // example output: @storybook/react@^8.0.0 + `${dependency}@${!isOutdated || isPrerelease ? '^' : ''}${versions[dependency]}` + ); + }; + + const upgradedDependencies = toUpgradedDependencies(packageJson.dependencies); + const upgradedDevDependencies = toUpgradedDependencies(packageJson.devDependencies); if (!dryRun) { - commandLog(`Installing upgrades`); + commandLog(`Updating dependencies in ${chalk.cyan('package.json')}..`); + logger.plain(''); + if (upgradedDependencies.length > 0) { + await packageManager.addDependencies( + { installAsDevDependencies: false, skipInstall: true, packageJson }, + upgradedDependencies + ); + } + if (upgradedDevDependencies.length > 0) { + await packageManager.addDependencies( + { installAsDevDependencies: true, skipInstall: true, packageJson }, + upgradedDevDependencies + ); + } await packageManager.installDependencies(); } @@ -219,8 +215,6 @@ export const doUpgrade = async ({ automigrationPreCheckFailure: preCheckFailure || null, }; telemetry('upgrade', { - prerelease, - tag, beforeVersion, afterVersion, ...automigrationTelemetry, diff --git a/code/lib/core-events/src/errors/server-errors.ts b/code/lib/core-events/src/errors/server-errors.ts index f4ecab544773..49a774006540 100644 --- a/code/lib/core-events/src/errors/server-errors.ts +++ b/code/lib/core-events/src/errors/server-errors.ts @@ -410,3 +410,50 @@ export class NoMatchingExportError extends StorybookError { `; } } + +export class UpgradeStorybookToLowerVersionError extends StorybookError { + readonly category = Category.CLI_UPGRADE; + + readonly code = 3; + + constructor(public data: { beforeVersion: string; currentVersion: string }) { + super(); + } + + template() { + return dedent` + You are trying to upgrade Storybook to a lower version than the version currently installed. This is not supported. + Storybook version ${this.data.beforeVersion} was detected in your project, but you are trying to "upgrade" to version ${this.data.currentVersion}. + + This usually happens when running the upgrade command without a version specifier, e.g. "npx storybook upgrade". + This will cause npm to run the globally cached storybook binary, which might be an older version. + Instead you should always run the Storybook CLI with a version specifier to force npm to download the latest version: + + "npx storybook@latest upgrade" + `; + } +} + +export class UpgradeStorybookToSameVersionError extends StorybookError { + readonly category = Category.CLI_UPGRADE; + + readonly code = 4; + + constructor(public data: { beforeVersion: string }) { + super(); + } + + template() { + return dedent` + You are trying to upgrade Storybook to the same version that is currently installed in the project, version ${this.data.beforeVersion}. This is not supported. + + This usually happens when running the upgrade command without a version specifier, e.g. "npx storybook upgrade". + This will cause npm to run the globally cached storybook binary, which might be the same version that you already have. + This also happens if you're running the Storybook CLI that is locally installed in your project. + If you intended to upgrade to the latest version, you should always run the Storybook CLI with a version specifier to force npm to download the latest version: + "npx storybook@latest upgrade" + If you intended to re-run automigrations, you should run the "automigrate" command directly instead: + "npx storybook@${this.data.beforeVersion} automigrate" + `; + } +} From 3f48968ab8728f229b99d338b891fc281d4a310b Mon Sep 17 00:00:00 2001 From: Norbert de Langen Date: Fri, 12 Jan 2024 09:15:58 +0100 Subject: [PATCH 2/7] use current version for sandbox cli command --- code/lib/cli/src/generate.ts | 2 +- code/lib/cli/src/initiate.ts | 2 +- code/lib/cli/src/sandbox.ts | 106 ++++++++++++++++++++++++++------- scripts/tasks/sandbox-parts.ts | 2 +- 4 files changed, 86 insertions(+), 26 deletions(-) diff --git a/code/lib/cli/src/generate.ts b/code/lib/cli/src/generate.ts index be3c4da1175e..aff6dde48acb 100644 --- a/code/lib/cli/src/generate.ts +++ b/code/lib/cli/src/generate.ts @@ -151,7 +151,7 @@ command('sandbox [filterValue]') .option('-b --branch ', 'Define the branch to download from', 'next') .option('--no-init', 'Whether to download a template without an initialized Storybook', false) .action((filterValue, options) => - sandbox({ filterValue, ...options }).catch((e) => { + sandbox({ filterValue, ...options }, pkg).catch((e) => { logger.error(e); process.exit(1); }) diff --git a/code/lib/cli/src/initiate.ts b/code/lib/cli/src/initiate.ts index 2adbe8c5bc03..2ab4fb561890 100644 --- a/code/lib/cli/src/initiate.ts +++ b/code/lib/cli/src/initiate.ts @@ -274,7 +274,7 @@ const getEmptyDirMessage = (packageManagerType: PackageManagerName) => { `; }; -async function doInitiate( +export async function doInitiate( options: CommandOptions, pkg: PackageJson ): Promise< diff --git a/code/lib/cli/src/sandbox.ts b/code/lib/cli/src/sandbox.ts index 2938414adbfa..0d8003e07bac 100644 --- a/code/lib/cli/src/sandbox.ts +++ b/code/lib/cli/src/sandbox.ts @@ -6,31 +6,75 @@ import { dedent } from 'ts-dedent'; import { downloadTemplate } from 'giget'; import { existsSync, readdir } from 'fs-extra'; +import { lt, prerelease } from 'semver'; import type { Template, TemplateKey } from './sandbox-templates'; import { allTemplates as TEMPLATES } from './sandbox-templates'; +import type { PackageJson, PackageManagerName } from './js-package-manager'; +import { JsPackageManagerFactory } from './js-package-manager'; +import versions from './versions'; +import { doInitiate } from './initiate'; + const logger = console; interface SandboxOptions { filterValue?: string; output?: string; - branch?: string; init?: boolean; + packageManager: PackageManagerName; } type Choice = keyof typeof TEMPLATES; const toChoices = (c: Choice): prompts.Choice => ({ title: TEMPLATES[c].name, value: c }); -export const sandbox = async ({ - output: outputDirectory, - filterValue, - branch, - init, -}: SandboxOptions) => { +export const sandbox = async ( + { output: outputDirectory, filterValue, init, ...options }: SandboxOptions, + pkg: PackageJson +) => { // Either get a direct match when users pass a template id, or filter through all templates let selectedConfig: Template | undefined = TEMPLATES[filterValue as TemplateKey]; - let selectedTemplate: Choice | null = selectedConfig ? (filterValue as TemplateKey) : null; - + let templateId: Choice | null = selectedConfig ? (filterValue as TemplateKey) : null; + + const { packageManager: pkgMgr } = options; + + const packageManager = JsPackageManagerFactory.getPackageManager({ + force: pkgMgr, + }); + const latestVersion = await packageManager.latestVersion('@storybook/cli'); + const nextVersion = await packageManager.latestVersion('@storybook/cli@next'); + const currentVersion = versions['@storybook/cli']; + const isPrerelease = prerelease(currentVersion); + const isOutdated = lt(currentVersion, isPrerelease ? nextVersion : latestVersion); + const borderColor = isOutdated ? '#FC521F' : '#F1618C'; + + const downloadType = !isOutdated && init ? 'after-storybook' : 'before-storybook'; + const branch = isPrerelease ? 'next' : 'main'; + + const messages = { + welcome: `Creating a Storybook ${chalk.bold(currentVersion)} sandbox..`, + notLatest: chalk.red(dedent` + This version is behind the latest release, which is: ${chalk.bold(latestVersion)}! + You likely ran the init command through npx, which can use a locally cached version, to get the latest please run: + ${chalk.bold('npx storybook@latest sandbox')} + + You may want to CTRL+C to stop, and run with the latest version instead. + `), + longInitTime: chalk.yellow( + 'The creation of the sandbox will take longer, because we will need to run init.' + ), + prerelease: chalk.yellow('This is a pre-release version.'), + }; + + logger.log( + boxen( + [messages.welcome] + .concat(isOutdated && !isPrerelease ? [messages.notLatest] : []) + .concat(init && (isOutdated || isPrerelease) ? [messages.longInitTime] : []) + .concat(isPrerelease ? [messages.prerelease] : []) + .join('\n'), + { borderStyle: 'round', padding: 1, borderColor } + ) + ); if (!selectedConfig) { const filterRegex = new RegExp(`^${filterValue || ''}`, 'i'); @@ -78,7 +122,7 @@ export const sandbox = async ({ } if (choices.length === 1) { - [selectedTemplate] = choices; + [templateId] = choices; } else { logger.info( boxen( @@ -96,16 +140,16 @@ export const sandbox = async ({ ) ); - selectedTemplate = await promptSelectedTemplate(choices); + templateId = await promptSelectedTemplate(choices); } - const hasSelectedTemplate = !!(selectedTemplate ?? null); + const hasSelectedTemplate = !!(templateId ?? null); if (!hasSelectedTemplate) { logger.error('Somehow we got no templates. Please rerun this command!'); return; } - selectedConfig = TEMPLATES[selectedTemplate]; + selectedConfig = TEMPLATES[templateId]; if (!selectedConfig) { throw new Error('🚨 Sandbox: please specify a valid template type'); @@ -113,7 +157,7 @@ export const sandbox = async ({ } let selectedDirectory = outputDirectory; - const outputDirectoryName = outputDirectory || selectedTemplate; + const outputDirectoryName = outputDirectory || templateId; if (selectedDirectory && existsSync(`${selectedDirectory}`)) { logger.info(`⚠️ ${selectedDirectory} already exists! Overwriting...`); } @@ -146,23 +190,36 @@ export const sandbox = async ({ : path.join(process.cwd(), selectedDirectory); logger.info(`🏃 Adding ${selectedConfig.name} into ${templateDestination}`); + logger.log(`📦 Downloading sandbox template (${chalk.bold(downloadType)})...`); - logger.log('📦 Downloading sandbox template...'); try { - const templateType = init ? 'after-storybook' : 'before-storybook'; // Download the sandbox based on subfolder "after-storybook" and selected branch - const gitPath = `github:storybookjs/sandboxes/${selectedTemplate}/${templateType}#${branch}`; + const gitPath = `github:storybookjs/sandboxes/${templateId}/${downloadType}#${branch}`; await downloadTemplate(gitPath, { force: true, dir: templateDestination, }); // throw an error if templateDestination is an empty directory using fs-extra if ((await readdir(templateDestination)).length === 0) { - throw new Error( - dedent`Template downloaded from ${chalk.blue(gitPath)} is empty. - Are you use it exists? Or did you want to set ${chalk.yellow( - selectedTemplate - )} to inDevelopment first?` + const selected = chalk.yellow(templateId); + throw new Error(dedent` + Template downloaded from ${chalk.blue(gitPath)} is empty. + Are you use it exists? Or did you want to set ${selected} to inDevelopment first? + `); + } + + // when user wanted an sandbox that has been initiated, but force-downloaded the before-storybook directory + // then we need to initiate the sandbox + // this is to ensure we DO get the latest version of the template (output of the generator), but we initialize using the version of storybook that the CLI is. + // we warned the user about the fact they are running an old version of storybook + // we warned the user the sandbox step would take longer + if ((isOutdated || isPrerelease) && init) { + // we run doInitiate, instead of initiate, to avoid sending this init event to telemetry, because it's not a real world project + await doInitiate( + { + ...options, + }, + pkg ); } } catch (err) { @@ -171,7 +228,10 @@ export const sandbox = async ({ } const initMessage = init - ? chalk.yellow(`yarn install\nyarn storybook`) + ? chalk.yellow(dedent` + yarn install + yarn storybook + `) : `Recreate your setup, then ${chalk.yellow(`npx storybook@latest init`)}`; logger.info( diff --git a/scripts/tasks/sandbox-parts.ts b/scripts/tasks/sandbox-parts.ts index 7c890c5ac8b4..564647ab319b 100644 --- a/scripts/tasks/sandbox-parts.ts +++ b/scripts/tasks/sandbox-parts.ts @@ -65,7 +65,7 @@ export const create: Task['run'] = async ({ key, template, sandboxDir }, { dryRu } else { await executeCLIStep(steps.repro, { argument: key, - optionValues: { output: sandboxDir, branch: 'next', init: false, debug }, + optionValues: { output: sandboxDir, init: false, debug }, cwd: parentDir, dryRun, debug, From a89b141982d91310e1af6395149c9132b7a0d886 Mon Sep 17 00:00:00 2001 From: Jeppe Reinhold Date: Fri, 12 Jan 2024 09:36:03 +0100 Subject: [PATCH 3/7] add back deprecated flags --- code/lib/cli/src/generate.ts | 5 + code/lib/cli/src/upgrade.ts | 185 ++++++++++++++++++++++++++++++++++- code/lib/cli/src/versions.ts | 1 + 3 files changed, 186 insertions(+), 5 deletions(-) diff --git a/code/lib/cli/src/generate.ts b/code/lib/cli/src/generate.ts index be3c4da1175e..4693a065eed5 100644 --- a/code/lib/cli/src/generate.ts +++ b/code/lib/cli/src/generate.ts @@ -81,6 +81,11 @@ command('upgrade') .option('-N --use-npm', 'Use NPM to install dependencies (deprecated)') .option('-y --yes', 'Skip prompting the user') .option('-n --dry-run', 'Only check for upgrades, do not install') + .option( + '-t --tag ', + 'Upgrade to a certain npm dist-tag (e.g. next, prerelease) (deprecated)' + ) + .option('-p --prerelease', 'Upgrade to the pre-release packages (deprecated)') .option('-s --skip-check', 'Skip postinstall version and automigration checks') .option('-c, --config-dir ', 'Directory where to load Storybook configurations from') .action(async (options: UpgradeOptions) => upgrade(options).catch(() => process.exit(1))); diff --git a/code/lib/cli/src/upgrade.ts b/code/lib/cli/src/upgrade.ts index 787998fce0a8..315290b30d00 100644 --- a/code/lib/cli/src/upgrade.ts +++ b/code/lib/cli/src/upgrade.ts @@ -1,7 +1,7 @@ import { sync as spawnSync } from 'cross-spawn'; import { telemetry, getStorybookCoreVersion } from '@storybook/telemetry'; -import semver, { coerce, eq, lt, prerelease } from 'semver'; -import { logger } from '@storybook/node-logger'; +import semver, { coerce, eq, lt } from 'semver'; +import { deprecate, logger } from '@storybook/node-logger'; import { withTelemetry } from '@storybook/core-server'; import { UpgradeStorybookToLowerVersionError, @@ -11,8 +11,8 @@ import { import chalk from 'chalk'; import dedent from 'ts-dedent'; import boxen from 'boxen'; -import type { PackageManagerName } from './js-package-manager'; -import { JsPackageManagerFactory, useNpmWarning } from './js-package-manager'; +import type { PackageJsonWithMaybeDeps, PackageManagerName } from './js-package-manager'; +import { JsPackageManagerFactory, getPackageDetails, useNpmWarning } from './js-package-manager'; import { commandLog } from './helpers'; import { automigrate } from './automigrate'; import { isCorePackage } from './utils'; @@ -91,7 +91,165 @@ export const checkVersionConsistency = () => { }); }; +/** + * DEPRECATED BEHAVIOR SECTION + */ + +type ExtraFlags = Record; +const EXTRA_FLAGS: ExtraFlags = { + 'react-scripts@<5': ['--reject', '/preset-create-react-app/'], +}; + +export const addExtraFlags = ( + extraFlags: ExtraFlags, + flags: string[], + { dependencies, devDependencies }: PackageJsonWithMaybeDeps +) => { + return Object.entries(extraFlags).reduce( + (acc, entry) => { + const [pattern, extra] = entry; + const [pkg, specifier] = getPackageDetails(pattern); + const pkgVersion = dependencies[pkg] || devDependencies[pkg]; + + if (pkgVersion && semver.satisfies(semver.coerce(pkgVersion), specifier)) { + return [...acc, ...extra]; + } + + return acc; + }, + [...flags] + ); +}; + +export const addNxPackagesToReject = (flags: string[]) => { + const newFlags = [...flags]; + const index = flags.indexOf('--reject'); + if (index > -1) { + // Try to understand if it's in the format of a regex pattern + if (newFlags[index + 1].endsWith('/') && newFlags[index + 1].startsWith('/')) { + // Remove last and first slash so that I can add the parentheses + newFlags[index + 1] = newFlags[index + 1].substring(1, newFlags[index + 1].length - 1); + newFlags[index + 1] = `/(${newFlags[index + 1]}|@nrwl/storybook|@nx/storybook)/`; + } else { + // Adding the two packages as comma-separated values + // If the existing rejects are in regex format, they will be ignored. + // Maybe we need to find a more robust way to treat rejects? + newFlags[index + 1] = `${newFlags[index + 1]},@nrwl/storybook,@nx/storybook`; + } + } else { + newFlags.push('--reject'); + newFlags.push('@nrwl/storybook,@nx/storybook'); + } + return newFlags; +}; + +export const deprecatedUpgrade = async ({ + tag, + prerelease, + skipCheck, + useNpm, + packageManager: pkgMgr, + dryRun, + configDir, + yes, + ...options +}: UpgradeOptions) => { + if (useNpm) { + useNpmWarning(); + // eslint-disable-next-line no-param-reassign + pkgMgr = 'npm'; + } + if (tag) { + deprecate( + 'The --tag flag is deprecated. Specify the version you want to upgrade to with `npx storybook@ upgrade` instead' + ); + } else if (prerelease) { + deprecate( + 'The --prerelease flag is deprecated. Specify the version you want to upgrade to with `npx storybook@ upgrade` instead' + ); + } + const packageManager = JsPackageManagerFactory.getPackageManager({ force: pkgMgr }); + + const beforeVersion = await getStorybookCoreVersion(); + + commandLog(`Checking for latest versions of '@storybook/*' packages`); + + if (tag && prerelease) { + throw new Error( + `Cannot set both --tag and --prerelease. Use --tag next to get the latest prereleae` + ); + } + + let target = 'latest'; + if (prerelease) { + // '@next' is storybook's convention for the latest prerelease tag. + // This used to be 'greatest', but that was not reliable and could pick canaries, etc. + // and random releases of other packages with storybook in their name. + target = '@next'; + } else if (tag) { + target = `@${tag}`; + } + + let flags = []; + if (!dryRun) flags.push('--upgrade'); + flags.push('--target'); + flags.push(target); + flags = addExtraFlags(EXTRA_FLAGS, flags, await packageManager.retrievePackageJson()); + flags = addNxPackagesToReject(flags); + const check = spawnSync('npx', ['npm-check-updates@latest', '/storybook/', ...flags], { + stdio: 'pipe', + shell: true, + }); + logger.info(check.stdout.toString()); + logger.info(check.stderr.toString()); + + const checkSb = spawnSync('npx', ['npm-check-updates@latest', 'sb', ...flags], { + stdio: 'pipe', + shell: true, + }); + logger.info(checkSb.stdout.toString()); + logger.info(checkSb.stderr.toString()); + + if (!dryRun) { + commandLog(`Installing upgrades`); + await packageManager.installDependencies(); + } + + let automigrationResults; + if (!skipCheck) { + checkVersionConsistency(); + automigrationResults = await automigrate({ dryRun, yes, packageManager: pkgMgr, configDir }); + } + if (!options.disableTelemetry) { + const afterVersion = await getStorybookCoreVersion(); + const { preCheckFailure, fixResults } = automigrationResults || {}; + const automigrationTelemetry = { + automigrationResults: preCheckFailure ? null : fixResults, + automigrationPreCheckFailure: preCheckFailure || null, + }; + telemetry('upgrade', { + prerelease, + tag, + beforeVersion, + afterVersion, + ...automigrationTelemetry, + }); + } +}; + +/** + * DEPRECATED BEHAVIOR SECTION END + */ + export interface UpgradeOptions { + /** + * @deprecated + */ + tag: string; + /** + * @deprecated + */ + prerelease: boolean; skipCheck: boolean; useNpm: boolean; packageManager: PackageManagerName; @@ -102,6 +260,8 @@ export interface UpgradeOptions { } export const doUpgrade = async ({ + tag, + prerelease, skipCheck, useNpm, packageManager: pkgMgr, @@ -115,6 +275,21 @@ export const doUpgrade = async ({ // eslint-disable-next-line no-param-reassign pkgMgr = 'npm'; } + if (tag || prerelease) { + await deprecatedUpgrade({ + tag, + prerelease, + skipCheck, + useNpm, + packageManager: pkgMgr, + dryRun, + configDir, + yes, + ...options, + }); + return; + } + const packageManager = JsPackageManagerFactory.getPackageManager({ force: pkgMgr }); const currentVersion = versions['@storybook/cli']; @@ -129,7 +304,7 @@ export const doUpgrade = async ({ const latestVersion = await packageManager.latestVersion('@storybook/cli'); const isOutdated = lt(currentVersion, latestVersion); - const isPrerelease = prerelease(currentVersion) !== null; + const isPrerelease = semver.prerelease(currentVersion) !== null; const borderColor = isOutdated ? '#FC521F' : '#F1618C'; diff --git a/code/lib/cli/src/versions.ts b/code/lib/cli/src/versions.ts index c60d37df1f4f..2d44ce1d69ba 100644 --- a/code/lib/cli/src/versions.ts +++ b/code/lib/cli/src/versions.ts @@ -81,6 +81,7 @@ export default { '@storybook/svelte-webpack5': '7.6.7', '@storybook/sveltekit': '7.6.7', '@storybook/telemetry': '7.6.7', + '@storybook/test': '7.6.7', '@storybook/theming': '7.6.7', '@storybook/types': '7.6.7', '@storybook/vue': '7.6.7', From 2ac5b32b642ca993cce1d07a9c4c7bd8f8f8a9f3 Mon Sep 17 00:00:00 2001 From: Jeppe Reinhold Date: Fri, 12 Jan 2024 10:02:22 +0100 Subject: [PATCH 4/7] fix automigrations and readmes --- code/frameworks/nextjs/README.md | 2 +- code/frameworks/preact-vite/README.md | 2 +- code/frameworks/sveltekit/README.md | 3 +-- code/lib/cli/src/automigrate/fixes/builder-vite.ts | 6 +++++- .../lib/cli/src/automigrate/helpers/checkWebpack5Builder.ts | 6 ++++-- 5 files changed, 12 insertions(+), 7 deletions(-) diff --git a/code/frameworks/nextjs/README.md b/code/frameworks/nextjs/README.md index 252fb329167d..b1333b8cf315 100644 --- a/code/frameworks/nextjs/README.md +++ b/code/frameworks/nextjs/README.md @@ -98,7 +98,7 @@ npx storybook@latest init This framework is designed to work with Storybook 7. If you’re not already using v7, upgrade with this command: ```bash -npx storybook@latest upgrade --prerelease +npx storybook@latest upgrade ``` #### Automatic migration diff --git a/code/frameworks/preact-vite/README.md b/code/frameworks/preact-vite/README.md index e418166a3b54..1e7d742e1674 100644 --- a/code/frameworks/preact-vite/README.md +++ b/code/frameworks/preact-vite/README.md @@ -22,7 +22,7 @@ npx storybook@latest init This framework is designed to work with Storybook 7. If you’re not already using v7, upgrade with this command: ```bash -npx storybook@latest upgrade --prerelease +npx storybook@latest upgrade ``` #### Manual migration diff --git a/code/frameworks/sveltekit/README.md b/code/frameworks/sveltekit/README.md index 3e4b96f8f83b..78d6f61eab5b 100644 --- a/code/frameworks/sveltekit/README.md +++ b/code/frameworks/sveltekit/README.md @@ -17,7 +17,6 @@ Check out our [Frameworks API](https://storybook.js.org/blog/framework-api/) ann - [Mocking links](#mocking-links) - [Troubleshooting](#troubleshooting) - [Error: `ERR! SyntaxError: Identifier '__esbuild_register_import_meta_url__' has already been declared` when starting Storybook](#error-err-syntaxerror-identifier-__esbuild_register_import_meta_url__-has-already-been-declared-when-starting-storybook) - - [Error: `Cannot read properties of undefined (reading 'disable_scroll_handling')` in preview](#error-cannot-read-properties-of-undefined-reading-disable_scroll_handling-in-preview) - [Acknowledgements](#acknowledgements) ## Supported features @@ -64,7 +63,7 @@ npx storybook@latest init This framework is designed to work with Storybook 7. If you’re not already using v7, upgrade with this command: ```bash -npx storybook@latest upgrade --prerelease +npx storybook@latest upgrade ``` #### Automatic migration diff --git a/code/lib/cli/src/automigrate/fixes/builder-vite.ts b/code/lib/cli/src/automigrate/fixes/builder-vite.ts index b7ee1317957c..b81102d20d2c 100644 --- a/code/lib/cli/src/automigrate/fixes/builder-vite.ts +++ b/code/lib/cli/src/automigrate/fixes/builder-vite.ts @@ -6,6 +6,7 @@ import { writeConfig } from '@storybook/csf-tools'; import type { Fix } from '../types'; import type { PackageJson } from '../../js-package-manager'; import { updateMainConfig } from '../helpers/mainConfigFile'; +import { getStorybookVersionSpecifier } from '../../helpers'; const logger = console; @@ -68,8 +69,11 @@ export const builderVite: Fix = { logger.info(`✅ Adding '@storybook/builder-vite' as dev dependency`); if (!dryRun) { + const versionToInstall = getStorybookVersionSpecifier( + await packageManager.retrievePackageJson() + ); await packageManager.addDependencies({ installAsDevDependencies: true }, [ - '@storybook/builder-vite', + `@storybook/builder-vite@${versionToInstall}`, ]); } diff --git a/code/lib/cli/src/automigrate/helpers/checkWebpack5Builder.ts b/code/lib/cli/src/automigrate/helpers/checkWebpack5Builder.ts index 8d59d62d0bcc..10186ac40430 100644 --- a/code/lib/cli/src/automigrate/helpers/checkWebpack5Builder.ts +++ b/code/lib/cli/src/automigrate/helpers/checkWebpack5Builder.ts @@ -20,9 +20,11 @@ export const checkWebpack5Builder = async ({ To upgrade to the latest stable release, run this from your project directory: - ${chalk.cyan('npx storybook upgrade')} + ${chalk.cyan('npx storybook@latest upgrade')} - Add the ${chalk.cyan('--prerelease')} flag to get the latest prerelease. + To upgrade to the latest pre-release, run this from your project directory: + + ${chalk.cyan('npx storybook@next upgrade')} `.trim() ); return null; From 9cb3fe601077afdb497b06a38de0ffd72fe262b2 Mon Sep 17 00:00:00 2001 From: Jeppe Reinhold Date: Fri, 12 Jan 2024 10:33:58 +0100 Subject: [PATCH 5/7] update message matches new upgrade API --- code/lib/core-server/src/utils/update-check.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/code/lib/core-server/src/utils/update-check.ts b/code/lib/core-server/src/utils/update-check.ts index 2012921921a0..1ddb4cf85223 100644 --- a/code/lib/core-server/src/utils/update-check.ts +++ b/code/lib/core-server/src/utils/update-check.ts @@ -38,8 +38,7 @@ export function createUpdateMessage(updateInfo: VersionCheck, version: string): try { const isPrerelease = semver.prerelease(updateInfo.data.latest.version); - const suffix = isPrerelease ? '@next upgrade --prerelease' : '@latest upgrade'; - const upgradeCommand = `npx storybook${suffix}`; + const upgradeCommand = `npx storybook@${isPrerelease ? 'next' : 'latest'} upgrade`; updateMessage = updateInfo.success && semver.lt(version, updateInfo.data.latest.version) ? dedent` From 9f449a5bce2b6bc7ef564b657f706a1089775d45 Mon Sep 17 00:00:00 2001 From: Norbert de Langen Date: Fri, 12 Jan 2024 17:58:42 +0100 Subject: [PATCH 6/7] fix tests --- code/lib/cli/src/upgrade.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/code/lib/cli/src/upgrade.test.ts b/code/lib/cli/src/upgrade.test.ts index d9445b66fcfb..56827546b548 100644 --- a/code/lib/cli/src/upgrade.test.ts +++ b/code/lib/cli/src/upgrade.test.ts @@ -9,7 +9,7 @@ jest.mock('@storybook/telemetry'); jest.mock('./versions', () => { const originalVersions = jest.requireActual('./versions').default; return { - default: Object.keys(originalVersions).reduce((acc, key) => { + ...Object.keys(originalVersions).reduce((acc, key) => { acc[key] = '8.0.0'; return acc; }, {} as Record), From 24f72ed993a66f857ca0f2f568a50bffd61511bb Mon Sep 17 00:00:00 2001 From: Norbert de Langen Date: Mon, 15 Jan 2024 12:56:09 +0100 Subject: [PATCH 7/7] fix the call to init in the cwd & ignore if next tag is missing --- code/lib/cli/src/sandbox.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/code/lib/cli/src/sandbox.ts b/code/lib/cli/src/sandbox.ts index 0d8003e07bac..2f0a8859a646 100644 --- a/code/lib/cli/src/sandbox.ts +++ b/code/lib/cli/src/sandbox.ts @@ -41,7 +41,10 @@ export const sandbox = async ( force: pkgMgr, }); const latestVersion = await packageManager.latestVersion('@storybook/cli'); - const nextVersion = await packageManager.latestVersion('@storybook/cli@next'); + // In verdaccio we often only have the latest tag, so this will fail. + const nextVersion = await packageManager + .latestVersion('@storybook/cli@next') + .catch((e) => '0.0.0'); const currentVersion = versions['@storybook/cli']; const isPrerelease = prerelease(currentVersion); const isOutdated = lt(currentVersion, isPrerelease ? nextVersion : latestVersion); @@ -215,12 +218,15 @@ export const sandbox = async ( // we warned the user the sandbox step would take longer if ((isOutdated || isPrerelease) && init) { // we run doInitiate, instead of initiate, to avoid sending this init event to telemetry, because it's not a real world project + const before = process.cwd(); + process.chdir(templateDestination); await doInitiate( { ...options, }, pkg ); + process.chdir(before); } } catch (err) { logger.error(`🚨 Failed to download sandbox template: ${err.message}`);