From f45a96392c22e9b772382f1bc8b99b0e30520681 Mon Sep 17 00:00:00 2001 From: SpookyJelly <74237436+SpookyJelly@users.noreply.github.com> Date: Fri, 19 May 2023 12:18:44 +0900 Subject: [PATCH 001/170] fix: error on using useStoryPrepared hook sometimes, `api.getData` returns undefined. which is used by isPrepared. I added a exception for this --- code/lib/manager-api/src/modules/stories.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/code/lib/manager-api/src/modules/stories.ts b/code/lib/manager-api/src/modules/stories.ts index 0d8b7b87659c..a3d0f9e922ed 100644 --- a/code/lib/manager-api/src/modules/stories.ts +++ b/code/lib/manager-api/src/modules/stories.ts @@ -141,6 +141,7 @@ export const init: ModuleFn = ({ }, isPrepared: (storyId, refId) => { const data = api.getData(storyId, refId); + if(!data) return false; return data.type === 'story' ? data.prepared : true; }, resolveStory: (storyId, refId) => { From c68aa57cc47b713413b4b4901ed942d945c39564 Mon Sep 17 00:00:00 2001 From: SpookyJelly <74237436+SpookyJelly@users.noreply.github.com> Date: Tue, 23 May 2023 12:56:41 +0900 Subject: [PATCH 002/170] Update stories.ts Fixed a wrong lint. --- code/lib/manager-api/src/modules/stories.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/code/lib/manager-api/src/modules/stories.ts b/code/lib/manager-api/src/modules/stories.ts index a3d0f9e922ed..b7dd4bdadc50 100644 --- a/code/lib/manager-api/src/modules/stories.ts +++ b/code/lib/manager-api/src/modules/stories.ts @@ -141,7 +141,9 @@ export const init: ModuleFn = ({ }, isPrepared: (storyId, refId) => { const data = api.getData(storyId, refId); - if(!data) return false; + if(!data) { + return false; + } return data.type === 'story' ? data.prepared : true; }, resolveStory: (storyId, refId) => { From e4fbacfb7d492eb4e8432614d67d43edf732cb1e Mon Sep 17 00:00:00 2001 From: Yann Braga Date: Wed, 19 Jul 2023 09:48:20 +0200 Subject: [PATCH 003/170] fix formatting --- code/lib/manager-api/src/modules/stories.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/code/lib/manager-api/src/modules/stories.ts b/code/lib/manager-api/src/modules/stories.ts index b7dd4bdadc50..a62bb7b3aef7 100644 --- a/code/lib/manager-api/src/modules/stories.ts +++ b/code/lib/manager-api/src/modules/stories.ts @@ -141,7 +141,7 @@ export const init: ModuleFn = ({ }, isPrepared: (storyId, refId) => { const data = api.getData(storyId, refId); - if(!data) { + if (!data) { return false; } return data.type === 'story' ? data.prepared : true; From fdba40fc4383006681a1001f32ce2aa897421e76 Mon Sep 17 00:00:00 2001 From: Jeppe Reinhold Date: Fri, 25 Aug 2023 13:31:43 +0200 Subject: [PATCH 004/170] add deprecation notice for cjs+vite --- MIGRATION.md | 21 ++++++++++++++++----- code/lib/core-server/src/build-dev.ts | 13 +++++++++++++ 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/MIGRATION.md b/MIGRATION.md index 5022eefb59bd..d612b131e630 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -1,5 +1,7 @@

Migration

+- [From version 7.3.0 to 7.4.0](#from-version-730-to-740) + - [CommonJS with Vite is deprecated](#commonjs-with-vite-is-deprecated) - [From version 7.0.0 to 7.2.0](#from-version-700-to-720) - [Addon API is more type-strict](#addon-api-is-more-type-strict) - [From version 6.5.x to 7.0.0](#from-version-65x-to-700) @@ -302,6 +304,14 @@ - [Packages renaming](#packages-renaming) - [Deprecated embedded addons](#deprecated-embedded-addons) +## From version 7.3.0 to 7.4.0 + +#### CommonJS with Vite is deprecated + +Using CommonJS in the `main` configuration with `main.cjs` or `main.cts` is deprecated, and will be removed in Storybook 8.0. This is a necessary change because Vite will remove support for CommonJS in the upcoming v5 release. + +Rename your `main` configuration file to `main.js` or `main.ts` and refactor any CommonJS syntax - like `require()` or `module.exports` - to ESM. + ## From version 7.0.0 to 7.2.0 #### Addon API is more type-strict @@ -311,6 +321,7 @@ When registering an addon using `@storybook/manager-api`, the addon API is now m The `type` property is now a required field, and the `id` property should not be set anymore. Here's a correct example: + ```tsx import { addons, types } from '@storybook/manager-api'; @@ -318,7 +329,7 @@ addons.register('my-addon', () => { addons.add('my-addon/panel', { type: types.PANEL, title: 'My Addon', - render: ({ active }) => active ?
Hello World
: null, + render: ({ active }) => (active ?
Hello World
: null), }); }); ``` @@ -869,16 +880,16 @@ Given the following `main.js`: ```js export default { - stories: ['../**/*.stories.*'] -} + stories: ['../**/*.stories.*'], +}; ``` If you want to restore the previous behavior to include `node_modules`, you can update it to: ```js export default { - stories: ['../**/*.stories.*', '../**/node_modules/**/*.stories.*'] -} + stories: ['../**/*.stories.*', '../**/node_modules/**/*.stories.*'], +}; ``` The first glob would have node_modules automatically excluded by Storybook, and the second glob would include all stories that are under a nested `node_modules` directory. diff --git a/code/lib/core-server/src/build-dev.ts b/code/lib/core-server/src/build-dev.ts index 7785afdee7b7..f557161703e2 100644 --- a/code/lib/core-server/src/build-dev.ts +++ b/code/lib/core-server/src/build-dev.ts @@ -11,6 +11,7 @@ import { loadMainConfig, resolveAddonName, resolvePathInStorybookCache, + serverResolve, validateFrameworkName, } from '@storybook/core-common'; import prompts from 'prompts'; @@ -19,6 +20,8 @@ import { global } from '@storybook/global'; import { telemetry } from '@storybook/telemetry'; import { join, resolve } from 'path'; +import { deprecate } from '@storybook/node-logger'; +import dedent from 'ts-dedent'; import { storybookDevServer } from './dev-server'; import { outputStats } from './utils/output-stats'; import { outputStartupInformation } from './utils/output-startup-information'; @@ -102,6 +105,16 @@ export async function buildDevStandalone( getManagerBuilder(), ]); + if (builderName.includes('builder-vite')) { + const mainJsPath = serverResolve(resolve(options.configDir || '.storybook', 'main')) as string; + if (/\.c[jt]s$/.test(mainJsPath)) { + deprecate( + dedent(`Using the .cjs or .cts extension for your main config file is deprecated with Vite. + - Refer to the migration guide at https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#commonjs-with-vite-is-deprecated`) + ); + } + } + const resolvedRenderer = renderer && resolveAddonName(options.configDir, renderer, options); // Load second pass: all presets are applied in order From 4cbcd333fe553dabec8d4cce267531c58b2104b6 Mon Sep 17 00:00:00 2001 From: Jeppe Reinhold Date: Fri, 25 Aug 2023 23:42:14 +0200 Subject: [PATCH 005/170] Improve CJS Vite migration notes Co-authored-by: Ben McCann <322311+benmccann@users.noreply.github.com> --- MIGRATION.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MIGRATION.md b/MIGRATION.md index d612b131e630..bd359a3da148 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -310,7 +310,7 @@ Using CommonJS in the `main` configuration with `main.cjs` or `main.cts` is deprecated, and will be removed in Storybook 8.0. This is a necessary change because Vite will remove support for CommonJS in the upcoming v5 release. -Rename your `main` configuration file to `main.js` or `main.ts` and refactor any CommonJS syntax - like `require()` or `module.exports` - to ESM. +You can address this by converting your `main` configuration file to ESM syntax and renaming it to `main.mjs` or `main.mts` if your project does not have `"type": "module"` in its `package.json`. To convert the config file to ESM you will need to replace any CommonJS syntax like `require()`, `module.exports`, or `__dirname`. If you haven't already, you may also consider adding `"type": "module"` to your package.json and converting your project to ESM. ## From version 7.0.0 to 7.2.0 From 30dd4baa1553ac6e71eb8c876151e15d0b188721 Mon Sep 17 00:00:00 2001 From: Jeppe Reinhold Date: Fri, 25 Aug 2023 23:44:11 +0200 Subject: [PATCH 006/170] link to vite discussion about ESM-only --- MIGRATION.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MIGRATION.md b/MIGRATION.md index bd359a3da148..8d865ca30581 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -308,7 +308,7 @@ #### CommonJS with Vite is deprecated -Using CommonJS in the `main` configuration with `main.cjs` or `main.cts` is deprecated, and will be removed in Storybook 8.0. This is a necessary change because Vite will remove support for CommonJS in the upcoming v5 release. +Using CommonJS in the `main` configuration with `main.cjs` or `main.cts` is deprecated, and will be removed in Storybook 8.0. This is a necessary change because [Vite will remove support for CommonJS in an upcoming release](https://github.com/vitejs/vite/discussions/13928). You can address this by converting your `main` configuration file to ESM syntax and renaming it to `main.mjs` or `main.mts` if your project does not have `"type": "module"` in its `package.json`. To convert the config file to ESM you will need to replace any CommonJS syntax like `require()`, `module.exports`, or `__dirname`. If you haven't already, you may also consider adding `"type": "module"` to your package.json and converting your project to ESM. From d80f62c8def8943db786630517c3735b93427247 Mon Sep 17 00:00:00 2001 From: Jeppe Reinhold Date: Tue, 29 Aug 2023 10:01:14 +0200 Subject: [PATCH 007/170] Improve VIte+CJS deprecation wording --- code/lib/core-server/src/build-dev.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/code/lib/core-server/src/build-dev.ts b/code/lib/core-server/src/build-dev.ts index f557161703e2..630c99a4d367 100644 --- a/code/lib/core-server/src/build-dev.ts +++ b/code/lib/core-server/src/build-dev.ts @@ -109,7 +109,7 @@ export async function buildDevStandalone( const mainJsPath = serverResolve(resolve(options.configDir || '.storybook', 'main')) as string; if (/\.c[jt]s$/.test(mainJsPath)) { deprecate( - dedent(`Using the .cjs or .cts extension for your main config file is deprecated with Vite. + dedent(`Using CommonJS in your main configuration file is deprecated with Vite." - Refer to the migration guide at https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#commonjs-with-vite-is-deprecated`) ); } From a0e1c7386203be952dfc0da324e12ed37fc2a4ce Mon Sep 17 00:00:00 2001 From: Jeppe Reinhold Date: Tue, 29 Aug 2023 13:13:22 +0200 Subject: [PATCH 008/170] show deprecation warning when main.js contains CommonJS syntax. --- code/lib/core-server/src/build-dev.ts | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/code/lib/core-server/src/build-dev.ts b/code/lib/core-server/src/build-dev.ts index 630c99a4d367..f40e66cce79c 100644 --- a/code/lib/core-server/src/build-dev.ts +++ b/code/lib/core-server/src/build-dev.ts @@ -22,6 +22,7 @@ import { telemetry } from '@storybook/telemetry'; import { join, resolve } from 'path'; import { deprecate } from '@storybook/node-logger'; import dedent from 'ts-dedent'; +import { readFile } from 'fs-extra'; import { storybookDevServer } from './dev-server'; import { outputStats } from './utils/output-stats'; import { outputStartupInformation } from './utils/output-startup-information'; @@ -106,12 +107,20 @@ export async function buildDevStandalone( ]); if (builderName.includes('builder-vite')) { + const deprecationMessage = + dedent(`Using CommonJS in your main configuration file is deprecated with Vite. + - Refer to the migration guide at https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#commonjs-with-vite-is-deprecated`); + const mainJsPath = serverResolve(resolve(options.configDir || '.storybook', 'main')) as string; if (/\.c[jt]s$/.test(mainJsPath)) { - deprecate( - dedent(`Using CommonJS in your main configuration file is deprecated with Vite." - - Refer to the migration guide at https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#commonjs-with-vite-is-deprecated`) - ); + deprecate(deprecationMessage); + } + const mainJsContent = await readFile(mainJsPath, 'utf-8'); + // Regex that matches any CommonJS-specific syntax, stolen from Vite: https://github.com/vitejs/vite/blob/91a18c2f7da796ff8217417a4bf189ddda719895/packages/vite/src/node/ssr/ssrExternal.ts#L87 + const CJS_CONTENT_REGEX = + /\bmodule\.exports\b|\bexports[.[]|\brequire\s*\(|\bObject\.(?:defineProperty|defineProperties|assign)\s*\(\s*exports\b/; + if (CJS_CONTENT_REGEX.test(mainJsContent)) { + deprecate(deprecationMessage); } } From f9b724c2983a36477390c410f2efea4e02cfa475 Mon Sep 17 00:00:00 2001 From: jonniebigodes Date: Tue, 31 Oct 2023 23:41:33 +0000 Subject: [PATCH 009/170] Docs: Test runner minor fixes --- .../snippets/common/test-runner-a11y-config.js.mdx | 2 +- .../snippets/common/test-runner-a11y-config.ts.mdx | 5 ++--- .../common/test-runner-a11y-configure.js.mdx | 2 +- .../common/test-runner-a11y-configure.ts.mdx | 7 +++---- .../common/test-runner-a11y-disable.js.mdx | 5 ++--- .../common/test-runner-a11y-disable.ts.mdx | 7 +++---- .../common/test-runner-helper-function.js.mdx | 5 ++++- .../common/test-runner-helper-function.ts.mdx | 6 ++++-- docs/writing-tests/accessibility-testing.md | 8 ++++---- docs/writing-tests/test-runner.md | 14 +++++++------- 10 files changed, 31 insertions(+), 30 deletions(-) diff --git a/docs/snippets/common/test-runner-a11y-config.js.mdx b/docs/snippets/common/test-runner-a11y-config.js.mdx index d7afb9b77456..bf5f2b954fb3 100644 --- a/docs/snippets/common/test-runner-a11y-config.js.mdx +++ b/docs/snippets/common/test-runner-a11y-config.js.mdx @@ -4,7 +4,7 @@ const { injectAxe, checkA11y } = require('axe-playwright'); /* - * See https://storybook.js.org/docs/react/writing-tests/test-runner#test-hook-api-experimental + * See https://storybook.js.org/docs/react/writing-tests/test-runner#test-hook-api * to learn more about the test-runner hooks API. */ module.exports = { diff --git a/docs/snippets/common/test-runner-a11y-config.ts.mdx b/docs/snippets/common/test-runner-a11y-config.ts.mdx index 9339eb7e2ae0..a317cb46ad18 100644 --- a/docs/snippets/common/test-runner-a11y-config.ts.mdx +++ b/docs/snippets/common/test-runner-a11y-config.ts.mdx @@ -1,12 +1,11 @@ ```ts // .storybook/test-runner.ts -import { injectAxe, checkA11y } from 'axe-playwright'; - import type { TestRunnerConfig } from '@storybook/test-runner'; +import { injectAxe, checkA11y } from 'axe-playwright'; /* - * See https://storybook.js.org/docs/react/writing-tests/test-runner#test-hook-api-experimental + * See https://storybook.js.org/docs/react/writing-tests/test-runner#test-hook-api * to learn more about the test-runner hooks API. */ const a11yConfig: TestRunnerConfig = { diff --git a/docs/snippets/common/test-runner-a11y-configure.js.mdx b/docs/snippets/common/test-runner-a11y-configure.js.mdx index e7ddb352d5ea..23333177d9a3 100644 --- a/docs/snippets/common/test-runner-a11y-configure.js.mdx +++ b/docs/snippets/common/test-runner-a11y-configure.js.mdx @@ -6,7 +6,7 @@ const { injectAxe, checkA11y, configureAxe } = require('axe-playwright'); const { getStoryContext } = require('@storybook/test-runner'); /* - * See https://storybook.js.org/docs/react/writing-tests/test-runner#test-hook-api-experimental + * See https://storybook.js.org/docs/react/writing-tests/test-runner#test-hook-api * to learn more about the test-runner hooks API. */ module.exports = { diff --git a/docs/snippets/common/test-runner-a11y-configure.ts.mdx b/docs/snippets/common/test-runner-a11y-configure.ts.mdx index 8b1f4d31037e..8828a71bba0d 100644 --- a/docs/snippets/common/test-runner-a11y-configure.ts.mdx +++ b/docs/snippets/common/test-runner-a11y-configure.ts.mdx @@ -1,14 +1,13 @@ ```ts // .storybook/test-runner.ts -import { injectAxe, checkA11y, configureAxe } from 'axe-playwright'; - +import type { TestRunnerConfig } from '@storybook/test-runner'; import { getStoryContext } from '@storybook/test-runner'; -import type { TestRunnerConfig } from '@storybook/test-runner'; +import { injectAxe, checkA11y, configureAxe } from 'axe-playwright'; /* - * See https://storybook.js.org/docs/react/writing-tests/test-runner#test-hook-api-experimental + * See https://storybook.js.org/docs/react/writing-tests/test-runner#test-hook-api * to learn more about the test-runner hooks API. */ const a11yConfig: TestRunnerConfig = { diff --git a/docs/snippets/common/test-runner-a11y-disable.js.mdx b/docs/snippets/common/test-runner-a11y-disable.js.mdx index edb12dab0bfa..02a13b3efca9 100644 --- a/docs/snippets/common/test-runner-a11y-disable.js.mdx +++ b/docs/snippets/common/test-runner-a11y-disable.js.mdx @@ -1,12 +1,11 @@ ```js // .storybook/test-runner.js -const { injectAxe, checkA11y } = require('axe-playwright'); - const { getStoryContext } = require('@storybook/test-runner'); +const { injectAxe, checkA11y } = require('axe-playwright'); /* - * See https://storybook.js.org/docs/react/writing-tests/test-runner#test-hook-api-experimental + * See https://storybook.js.org/docs/react/writing-tests/test-runner#test-hook-api * to learn more about the test-runner hooks API. */ module.exports = { diff --git a/docs/snippets/common/test-runner-a11y-disable.ts.mdx b/docs/snippets/common/test-runner-a11y-disable.ts.mdx index 3297e8ea0b7b..986b8c09eaff 100644 --- a/docs/snippets/common/test-runner-a11y-disable.ts.mdx +++ b/docs/snippets/common/test-runner-a11y-disable.ts.mdx @@ -1,14 +1,13 @@ ```ts // .storybook/test-runner.ts -import { injectAxe, checkA11y } from 'axe-playwright'; - +import type { TestRunnerConfig } from '@storybook/test-runner'; import { getStoryContext } from '@storybook/test-runner'; -import type { TestRunnerConfig } from '@storybook/test-runner'; +import { injectAxe, checkA11y } from 'axe-playwright'; /* - * See https://storybook.js.org/docs/react/writing-tests/test-runner#test-hook-api-experimental + * See https://storybook.js.org/docs/react/writing-tests/test-runner#test-hook-api * to learn more about the test-runner hooks API. */ const a11yConfig: TestRunnerConfig = { diff --git a/docs/snippets/common/test-runner-helper-function.js.mdx b/docs/snippets/common/test-runner-helper-function.js.mdx index 6ce0e1bf4123..739f0034b59e 100644 --- a/docs/snippets/common/test-runner-helper-function.js.mdx +++ b/docs/snippets/common/test-runner-helper-function.js.mdx @@ -1,7 +1,7 @@ ```js // .storybook/test-runner.js -const { getStoryContext } = require('@storybook/test-runner'); +const { getStoryContext, waitForPageReady } = require('@storybook/test-runner'); module.exports = { // Hook that is executed before the test runner starts running tests @@ -23,6 +23,9 @@ module.exports = { // Get the entire context of a story, including parameters, args, argTypes, etc. const storyContext = await getStoryContext(page, context); + // This utility function is designed for image snapshot testing. It will wait for the page to be fully loaded, including all the async items (e.g., images, fonts, etc.). + await waitForPageReady(page); + // Add your configuration here. }, }; diff --git a/docs/snippets/common/test-runner-helper-function.ts.mdx b/docs/snippets/common/test-runner-helper-function.ts.mdx index 94a9824a68a0..eea475d13f24 100644 --- a/docs/snippets/common/test-runner-helper-function.ts.mdx +++ b/docs/snippets/common/test-runner-helper-function.ts.mdx @@ -2,8 +2,7 @@ // .storybook/test-runner.ts import type { TestRunnerConfig } from '@storybook/test-runner'; - -import { getStoryContext } from '@storybook/test-runner'; +import { getStoryContext, waitForPageReady } from '@storybook/test-runner'; const config: TestRunnerConfig = { // Hook that is executed before the test runner starts running tests @@ -25,6 +24,9 @@ const config: TestRunnerConfig = { // Get the entire context of a story, including parameters, args, argTypes, etc. const storyContext = await getStoryContext(page, context); + // This utility function is designed for image snapshot testing. It will wait for the page to be fully loaded, including all the async items (e.g., images, fonts, etc.). + await waitForPageReady(page); + // Add your configuration here. }, }; diff --git a/docs/writing-tests/accessibility-testing.md b/docs/writing-tests/accessibility-testing.md index d6dbba00d27a..4773ec8594b0 100644 --- a/docs/writing-tests/accessibility-testing.md +++ b/docs/writing-tests/accessibility-testing.md @@ -89,7 +89,7 @@ Out of the box, Storybook's accessibility addon includes a set of accessibility #### Global a11y configuration -If you need to dismiss an accessibility rule or modify its settings across all stories, you can add the following to your [storybook/preview.js](../configure/overview.md#configure-story-rendering): +If you need to dismiss an accessibility rule or modify its settings across all stories, you can add the following to your [`storybook/preview.js|ts`](../configure/overview.md#configure-story-rendering): @@ -170,7 +170,7 @@ Disable accessibility testing for stories or components by adding the following The most accurate way to check accessibility is manually on real devices. However, you can use automated tools to catch common accessibility issues. For example, [Axe](https://www.deque.com/axe/), on average, catches upwards to [57% of WCAG issues](https://www.deque.com/blog/automated-testing-study-identifies-57-percent-of-digital-accessibility-issues/) automatically. -These tools work by auditing the rendered DOM against heuristics based on [WCAG](https://www.w3.org/WAI/standards-guidelines/wcag/) rules and other industry-accepted best practices. You can then integrate these tools into your test automation pipeline using the Storybook [test runner](./test-runner.md#test-hook-api-experimental) and [axe-playwright](https://github.com/abhinaba-ghosh/axe-playwright). +These tools work by auditing the rendered DOM against heuristics based on [WCAG](https://www.w3.org/WAI/standards-guidelines/wcag/) rules and other industry-accepted best practices. You can then integrate these tools into your test automation pipeline using the Storybook [test runner](./test-runner.md#test-hook-api) and [axe-playwright](https://github.com/abhinaba-ghosh/axe-playwright). ### Setup @@ -190,7 +190,7 @@ Run the following command to install the required dependencies. -Add a new [configuration file](./test-runner.md#test-hook-api-experimental) inside your Storybook directory with the following inside: +Add a new [configuration file](./test-runner.md#test-hook-api) inside your Storybook directory with the following inside: @@ -205,7 +205,7 @@ Add a new [configuration file](./test-runner.md#test-hook-api-experimental) insi
-šŸ’” `preRender` and `postRender` are convenient hooks that allow you to extend the test runner's default configuration. They are **experimental** and subject to changes. Read more about them [here](./test-runner.md#test-hook-api-experimental). +šŸ’” `preRender` and `postRender` are convenient hooks that allow you to extend the test runner's default configuration. Read more about them [here](./test-runner.md#test-hook-api).
diff --git a/docs/writing-tests/test-runner.md b/docs/writing-tests/test-runner.md index e75bee68c549..ebecf03198d3 100644 --- a/docs/writing-tests/test-runner.md +++ b/docs/writing-tests/test-runner.md @@ -190,19 +190,19 @@ However, you might want to pair the test runner and Chromatic in some cases. ## Advanced configuration -### Test hook API (experimental) +### Test hook API The test-runner renders a story and executes its [play function](../writing-stories/play-function.md) if one exists. However, certain behaviors are impossible to achieve via the play function, which executes in the browser. For example, if you want the test-runner to take visual snapshots for you, this is possible via Playwright/Jest but must be executed in Node. The test-runner exports test hooks that can be overridden globally to enable use cases like visual or DOM snapshots. These hooks give you access to the test lifecycle _before_ and _after_ the story is rendered. Listed below are the available hooks and an overview of how to use them. -| Hook | Description | -| ------------ | -------------------------------------------------------------------------------------------------- | -| `prepare` | Prepares the browser for tests
`async prepare({ page, browserContext, testRunnerConfig }) {}` | -| `setup` | Executes once before all the tests run
`setup() {}` | -| `preRender` | Executes before a story is rendered
`async preRender(page, context) {}` | -| `postRender` | Executes after the story is rendered
`async postRender(page, context) {}` | +| Hook | Description | +| ------------ | ------------------------------------------------------------------------------------------------- | +| `prepare` | Prepares the browser for tests
`async prepare({ page, browserContext, testRunnerConfig }) {}` | +| `setup` | Executes once before all the tests run
`setup() {}` | +| `preRender` | Executes before a story is rendered
`async preRender(page, context) {}` | +| `postRender` | Executes after the story is rendered
`async postRender(page, context) {}` |
From 8286a8dfcaf8d8700a8f0ee7c895bcc4ba9d0371 Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Fri, 3 Nov 2023 10:05:00 +0100 Subject: [PATCH 010/170] Convert build-package to Typescript --- code/package.json | 2 +- .../{build-package.js => build-package.ts} | 64 ++++++++++--------- 2 files changed, 35 insertions(+), 31 deletions(-) rename scripts/{build-package.js => build-package.ts} (74%) diff --git a/code/package.json b/code/package.json index 2b996643bff9..685378e820cf 100644 --- a/code/package.json +++ b/code/package.json @@ -26,7 +26,7 @@ }, "scripts": { "await-serve-storybooks": "wait-on http://localhost:8001", - "build": "NODE_ENV=production node ../scripts/build-package.js", + "build": "NODE_ENV=production ts-node --swc --esm ../scripts/build-package.ts", "changelog": "pr-log --sloppy --cherry-pick", "changelog:next": "pr-log --sloppy --since-prerelease", "check": "NODE_ENV=production node ../scripts/check-package.js", diff --git a/scripts/build-package.js b/scripts/build-package.ts similarity index 74% rename from scripts/build-package.js rename to scripts/build-package.ts index c76af11b8a09..ab7a4be048af 100644 --- a/scripts/build-package.js +++ b/scripts/build-package.ts @@ -1,39 +1,41 @@ #!/usr/bin/env node /* eslint-disable global-require */ -const { resolve, join, posix, sep } = require('path'); -const { readJSON } = require('fs-extra'); - -async function getWorkspaces(includePrivate = true) { - const { execaCommand } = await import('execa'); - const { stdout } = await execaCommand(`yarn workspaces list --json --no-private`, { - cwd: join(__dirname, '..', 'code'), - shell: true, - }); - return JSON.parse(`[${stdout.split('\n').join(',')}]`); -} +import { resolve, posix, sep } from 'path'; +import { readJSON } from 'fs-extra'; +import prompts from 'prompts'; +import program from 'commander'; +import chalk from 'chalk'; +import { getWorkspaces } from './utils/workspace'; +import { execaCommand } from './utils/exec'; async function run() { - const prompts = require('prompts'); - const program = require('commander'); - const chalk = require('chalk'); - const packages = await getWorkspaces(); const packageTasks = packages - .map((package) => { + .map((pkg) => { return { - ...package, - suffix: package.name.replace('@storybook/', ''), + ...pkg, + suffix: pkg.name.replace('@storybook/', ''), defaultValue: false, - helpText: `build only the ${package.name} package`, + helpText: `build only the ${pkg.name} package`, }; }) .reduce((acc, next) => { acc[next.name] = next; return acc; - }, {}); + }, {} as Record); - const tasks = { + const tasks: Record< + string, + { + name: string; + defaultValue: boolean; + suffix: string; + helpText: string; + value?: any; + location?: string; + } + > = { watch: { name: `watch`, defaultValue: false, @@ -92,6 +94,7 @@ async function run() { name: 'todo', min: 1, hint: 'You can also run directly with package name like `yarn build core`, or `yarn build --all` for all packages!', + // @ts-expect-error @types incomplete optionsPerPage: require('window-size').height - 3, // 3 lines for extra info choices: packages.map(({ name: key }) => ({ value: key, @@ -99,7 +102,7 @@ async function run() { selected: (tasks[key] && tasks[key].defaultValue) || false, })), }, - ]).then(({ watch, prod, todo }) => { + ]).then(({ watch, prod, todo }: { watch: boolean; prod: boolean; todo: Array }) => { watchMode = watch; prodMode = prod; return todo?.map((key) => tasks[key]); @@ -119,9 +122,8 @@ async function run() { .join(sep); const cwd = resolve(__dirname, '..', 'code', v.location); - const { execaCommand } = await import('execa'); const tsNode = require.resolve('ts-node/dist/bin'); - const sub = execaCommand( + const sub = await execaCommand( `node ${tsNode} ${commmand}${watchMode ? ' --watch' : ''}${prodMode ? ' --optimized' : ''}`, { cwd, @@ -134,16 +136,18 @@ async function run() { } ); - sub.stdout.on('data', (data) => { - process.stdout.write(`${chalk.cyan(v.name)}:\n${data}`); - }); - sub.stderr.on('data', (data) => { - process.stderr.write(`${chalk.red(v.name)}:\n${data}`); - }); + if (sub.stdout) { + process.stdout.write(`${chalk.cyan(v.name)}:\n${sub.stdout}`); + } + + if (sub.stderr) { + process.stderr.write(`${chalk.red(v.name)}:\n${sub.stderr}`); + } }); } run().catch((e) => { + // eslint-disable-next-line no-console console.log(e); process.exit(1); }); From b7ef8c560f5e45fce519fd9602ae3e5579495881 Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Fri, 3 Nov 2023 10:58:02 +0100 Subject: [PATCH 011/170] Use esbuild as esm loader for node --- code/.eslintrc.js | 2 +- code/addons/a11y/package.json | 4 +- code/addons/actions/package.json | 4 +- code/addons/backgrounds/package.json | 4 +- code/addons/controls/package.json | 4 +- code/addons/docs/package.json | 4 +- code/addons/essentials/package.json | 4 +- code/addons/gfm/package.json | 4 +- code/addons/highlight/package.json | 4 +- code/addons/interactions/package.json | 4 +- code/addons/jest/package.json | 4 +- code/addons/links/package.json | 4 +- code/addons/measure/package.json | 4 +- code/addons/outline/package.json | 4 +- code/addons/storyshots-core/package.json | 4 +- code/addons/storyshots-puppeteer/package.json | 4 +- code/addons/storysource/package.json | 4 +- code/addons/themes/package.json | 4 +- code/addons/toolbars/package.json | 4 +- code/addons/viewport/package.json | 4 +- code/builders/builder-manager/package.json | 4 +- code/builders/builder-vite/package.json | 4 +- code/builders/builder-webpack5/package.json | 4 +- code/deprecated/addons/package.json | 4 +- .../channel-postmessage/package.json | 4 +- .../deprecated/channel-websocket/package.json | 4 +- code/deprecated/client-api/package.json | 4 +- code/deprecated/core-client/package.json | 4 +- code/deprecated/manager-api-shim/package.json | 4 +- code/deprecated/preview-web/package.json | 4 +- code/deprecated/store/package.json | 4 +- code/frameworks/angular/package.json | 4 +- code/frameworks/ember/package.json | 4 +- code/frameworks/html-vite/package.json | 4 +- code/frameworks/html-webpack5/package.json | 4 +- code/frameworks/nextjs/package.json | 4 +- code/frameworks/preact-vite/package.json | 4 +- code/frameworks/preact-webpack5/package.json | 4 +- code/frameworks/react-vite/package.json | 4 +- code/frameworks/react-webpack5/package.json | 4 +- code/frameworks/server-webpack5/package.json | 4 +- code/frameworks/svelte-vite/package.json | 4 +- code/frameworks/svelte-webpack5/package.json | 4 +- code/frameworks/sveltekit/package.json | 4 +- code/frameworks/vue-vite/package.json | 4 +- code/frameworks/vue-webpack5/package.json | 4 +- code/frameworks/vue3-vite/package.json | 4 +- code/frameworks/vue3-webpack5/package.json | 4 +- .../web-components-vite/package.json | 4 +- .../web-components-webpack5/package.json | 4 +- code/lib/channels/package.json | 4 +- code/lib/cli/package.json | 4 +- code/lib/client-logger/package.json | 4 +- code/lib/codemod/package.json | 4 +- code/lib/core-common/package.json | 4 +- code/lib/core-events/package.json | 4 +- code/lib/core-server/package.json | 4 +- code/lib/core-webpack/package.json | 4 +- code/lib/csf-plugin/package.json | 4 +- code/lib/csf-tools/package.json | 4 +- code/lib/docs-tools/package.json | 4 +- code/lib/instrumenter/package.json | 4 +- code/lib/manager-api/package.json | 4 +- code/lib/node-logger/package.json | 4 +- code/lib/postinstall/package.json | 4 +- code/lib/preview-api/package.json | 4 +- code/lib/preview/package.json | 4 +- code/lib/react-dom-shim/package.json | 4 +- code/lib/router/package.json | 4 +- code/lib/source-loader/package.json | 4 +- code/lib/telemetry/package.json | 4 +- code/lib/test/package.json | 4 +- code/lib/theming/package.json | 4 +- code/lib/types/package.json | 4 +- code/package.json | 2 +- code/presets/create-react-app/package.json | 4 +- code/presets/html-webpack/package.json | 4 +- code/presets/preact-webpack/package.json | 4 +- code/presets/react-webpack/package.json | 4 +- code/presets/server-webpack/package.json | 4 +- code/presets/svelte-webpack/package.json | 4 +- code/presets/vue-webpack/package.json | 4 +- code/presets/vue3-webpack/package.json | 4 +- .../web-components-webpack/package.json | 4 +- code/prettier.config.js | 2 +- code/renderers/html/package.json | 4 +- code/renderers/preact/package.json | 4 +- code/renderers/react/package.json | 4 +- code/renderers/server/package.json | 4 +- code/renderers/svelte/package.json | 2 +- code/renderers/vue/package.json | 2 +- code/renderers/vue3/package.json | 2 +- code/renderers/web-components/package.json | 4 +- code/ui/blocks/package.json | 4 +- code/ui/components/package.json | 4 +- code/ui/manager/package.json | 4 +- scripts/.babelrc.js | 2 +- scripts/{.eslintrc.js => .eslintrc.cjs} | 0 scripts/build-package.ts | 11 ++--- ...dependencies.js => check-dependencies.cjs} | 0 .../{check-package.js => check-package.cjs} | 0 scripts/{jest.config.js => jest.config.cjs} | 0 scripts/package.json | 47 ++++++++++--------- scripts/prepare/bundle.ts | 2 - scripts/prepare/check-scripts.ts | 4 +- scripts/prepare/check.ts | 4 +- ...prettier.config.js => prettier.config.cjs} | 0 scripts/release/publish.ts | 10 +--- scripts/tasks/bench.ts | 8 ++-- scripts/tasks/dev.ts | 2 +- scripts/tasks/sandbox.ts | 12 +++-- scripts/tasks/serve.ts | 2 +- scripts/tsconfig.json | 8 ++-- scripts/utils/exec.ts | 15 ++---- scripts/yarn.lock | 28 +++++++---- 115 files changed, 259 insertions(+), 268 deletions(-) rename scripts/{.eslintrc.js => .eslintrc.cjs} (100%) rename scripts/{check-dependencies.js => check-dependencies.cjs} (100%) rename scripts/{check-package.js => check-package.cjs} (100%) rename scripts/{jest.config.js => jest.config.cjs} (100%) rename scripts/{prettier.config.js => prettier.config.cjs} (100%) diff --git a/code/.eslintrc.js b/code/.eslintrc.js index e967113bb8eb..efc6cd34e3c8 100644 --- a/code/.eslintrc.js +++ b/code/.eslintrc.js @@ -4,7 +4,7 @@ const scriptPath = path.join(__dirname, '..', 'scripts'); module.exports = { root: true, - extends: [path.join(scriptPath, '.eslintrc.js')], + extends: [path.join(scriptPath, '.eslintrc.cjs')], parserOptions: { tsconfigRootDir: __dirname, project: ['./tsconfig.json'], diff --git a/code/addons/a11y/package.json b/code/addons/a11y/package.json index 2b635b2abff9..fccfdda1b68a 100644 --- a/code/addons/a11y/package.json +++ b/code/addons/a11y/package.json @@ -60,8 +60,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/addon-highlight": "workspace:*", diff --git a/code/addons/actions/package.json b/code/addons/actions/package.json index adbd0ac5ad7d..448dcdb90afe 100644 --- a/code/addons/actions/package.json +++ b/code/addons/actions/package.json @@ -77,8 +77,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/addons/backgrounds/package.json b/code/addons/backgrounds/package.json index 1738199adcf7..38699d6a5aa2 100644 --- a/code/addons/backgrounds/package.json +++ b/code/addons/backgrounds/package.json @@ -73,8 +73,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/addons/controls/package.json b/code/addons/controls/package.json index b3992f0705a1..fc4d7665b532 100644 --- a/code/addons/controls/package.json +++ b/code/addons/controls/package.json @@ -65,8 +65,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/blocks": "workspace:*", diff --git a/code/addons/docs/package.json b/code/addons/docs/package.json index a75135fde197..dbf13c914474 100644 --- a/code/addons/docs/package.json +++ b/code/addons/docs/package.json @@ -94,8 +94,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@jest/transform": "^29.3.1", diff --git a/code/addons/essentials/package.json b/code/addons/essentials/package.json index ef565711cb10..a810921632a4 100644 --- a/code/addons/essentials/package.json +++ b/code/addons/essentials/package.json @@ -116,8 +116,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/addon-actions": "workspace:*", diff --git a/code/addons/gfm/package.json b/code/addons/gfm/package.json index d5fa5f53336f..750014b2a300 100644 --- a/code/addons/gfm/package.json +++ b/code/addons/gfm/package.json @@ -48,8 +48,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/node-logger": "workspace:*", diff --git a/code/addons/highlight/package.json b/code/addons/highlight/package.json index d6e8dd72260d..d5a3798a03cb 100644 --- a/code/addons/highlight/package.json +++ b/code/addons/highlight/package.json @@ -58,8 +58,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/core-events": "workspace:*", diff --git a/code/addons/interactions/package.json b/code/addons/interactions/package.json index 1006df6c8208..bcfe77ee9b39 100644 --- a/code/addons/interactions/package.json +++ b/code/addons/interactions/package.json @@ -69,8 +69,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/addons/jest/package.json b/code/addons/jest/package.json index d5437afd9088..7b5e909e34dc 100644 --- a/code/addons/jest/package.json +++ b/code/addons/jest/package.json @@ -67,8 +67,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/addons/links/package.json b/code/addons/links/package.json index ce5b0f9955d2..0ffc87920017 100644 --- a/code/addons/links/package.json +++ b/code/addons/links/package.json @@ -77,8 +77,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/addons/measure/package.json b/code/addons/measure/package.json index aab6e01731bb..9a2de4173286 100644 --- a/code/addons/measure/package.json +++ b/code/addons/measure/package.json @@ -72,8 +72,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/addons/outline/package.json b/code/addons/outline/package.json index 0dbe11877145..d520458bc6f5 100644 --- a/code/addons/outline/package.json +++ b/code/addons/outline/package.json @@ -75,8 +75,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/addons/storyshots-core/package.json b/code/addons/storyshots-core/package.json index d3b70029f54f..6db842c9754f 100644 --- a/code/addons/storyshots-core/package.json +++ b/code/addons/storyshots-core/package.json @@ -33,8 +33,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/tsc.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/tsc.ts" }, "dependencies": { "@jest/transform": "^29.3.1", diff --git a/code/addons/storyshots-puppeteer/package.json b/code/addons/storyshots-puppeteer/package.json index bd97205d275e..c19d88a6a9e6 100644 --- a/code/addons/storyshots-puppeteer/package.json +++ b/code/addons/storyshots-puppeteer/package.json @@ -32,8 +32,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/tsc.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/tsc.ts" }, "dependencies": { "@axe-core/puppeteer": "^4.2.0", diff --git a/code/addons/storysource/package.json b/code/addons/storysource/package.json index 02fb9f3e1a5a..53bff4fb96bb 100644 --- a/code/addons/storysource/package.json +++ b/code/addons/storysource/package.json @@ -50,8 +50,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/addons/themes/package.json b/code/addons/themes/package.json index 3e0f448d784f..dc4187502154 100644 --- a/code/addons/themes/package.json +++ b/code/addons/themes/package.json @@ -70,8 +70,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/addons/toolbars/package.json b/code/addons/toolbars/package.json index d9c00c78607e..86e88e18b6a6 100644 --- a/code/addons/toolbars/package.json +++ b/code/addons/toolbars/package.json @@ -65,8 +65,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/addons/viewport/package.json b/code/addons/viewport/package.json index 44da576cbd96..daec078a7bcb 100644 --- a/code/addons/viewport/package.json +++ b/code/addons/viewport/package.json @@ -70,8 +70,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/builders/builder-manager/package.json b/code/builders/builder-manager/package.json index 40ba65622445..1592368bd9f5 100644 --- a/code/builders/builder-manager/package.json +++ b/code/builders/builder-manager/package.json @@ -40,8 +40,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@fal-works/esbuild-plugin-global-externals": "^2.1.2", diff --git a/code/builders/builder-vite/package.json b/code/builders/builder-vite/package.json index e1e9203449fc..1fe79c77e95f 100644 --- a/code/builders/builder-vite/package.json +++ b/code/builders/builder-vite/package.json @@ -39,8 +39,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/channels": "workspace:*", diff --git a/code/builders/builder-webpack5/package.json b/code/builders/builder-webpack5/package.json index d0a5affdbb26..f7a6ae2a50ad 100644 --- a/code/builders/builder-webpack5/package.json +++ b/code/builders/builder-webpack5/package.json @@ -52,8 +52,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@babel/core": "^7.23.2", diff --git a/code/deprecated/addons/package.json b/code/deprecated/addons/package.json index a53096886a12..5c03086792bc 100644 --- a/code/deprecated/addons/package.json +++ b/code/deprecated/addons/package.json @@ -40,8 +40,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/manager-api": "workspace:*", diff --git a/code/deprecated/channel-postmessage/package.json b/code/deprecated/channel-postmessage/package.json index 5c7575c2ca9a..1d25d3d36dec 100644 --- a/code/deprecated/channel-postmessage/package.json +++ b/code/deprecated/channel-postmessage/package.json @@ -40,8 +40,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/channels": "workspace:*", diff --git a/code/deprecated/channel-websocket/package.json b/code/deprecated/channel-websocket/package.json index 867b016f8ecd..4915fca744cf 100644 --- a/code/deprecated/channel-websocket/package.json +++ b/code/deprecated/channel-websocket/package.json @@ -40,8 +40,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/facade.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/facade.ts" }, "dependencies": { "@storybook/channels": "workspace:*", diff --git a/code/deprecated/client-api/package.json b/code/deprecated/client-api/package.json index a03910376b14..e2039ae389d5 100644 --- a/code/deprecated/client-api/package.json +++ b/code/deprecated/client-api/package.json @@ -39,8 +39,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/facade.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/facade.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/deprecated/core-client/package.json b/code/deprecated/core-client/package.json index 00584a31ff5a..161a0d50f631 100644 --- a/code/deprecated/core-client/package.json +++ b/code/deprecated/core-client/package.json @@ -31,8 +31,8 @@ "module": "dist/entry.mjs", "types": "dist/entry.d.ts", "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/facade.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/facade.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/deprecated/manager-api-shim/package.json b/code/deprecated/manager-api-shim/package.json index 56401af1b7b4..2cd019ed8435 100644 --- a/code/deprecated/manager-api-shim/package.json +++ b/code/deprecated/manager-api-shim/package.json @@ -39,8 +39,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/facade.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/facade.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/deprecated/preview-web/package.json b/code/deprecated/preview-web/package.json index 24439508961a..61f82e70a08a 100644 --- a/code/deprecated/preview-web/package.json +++ b/code/deprecated/preview-web/package.json @@ -39,8 +39,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/facade.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/facade.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/deprecated/store/package.json b/code/deprecated/store/package.json index b04a829ae6fb..86c24e69b7aa 100644 --- a/code/deprecated/store/package.json +++ b/code/deprecated/store/package.json @@ -39,8 +39,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/facade.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/facade.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/frameworks/angular/package.json b/code/frameworks/angular/package.json index f53ac7a94f51..057073ce695f 100644 --- a/code/frameworks/angular/package.json +++ b/code/frameworks/angular/package.json @@ -33,8 +33,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/node_modules/.bin/tsc", - "prep": "../../../scripts/prepare/tsc.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/node_modules/.bin/tsc", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/tsc.ts" }, "dependencies": { "@storybook/builder-webpack5": "workspace:*", diff --git a/code/frameworks/ember/package.json b/code/frameworks/ember/package.json index 25d8f77bb1a9..6284c395a111 100644 --- a/code/frameworks/ember/package.json +++ b/code/frameworks/ember/package.json @@ -28,8 +28,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/tsc.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/tsc.ts" }, "dependencies": { "@storybook/builder-webpack5": "workspace:*", diff --git a/code/frameworks/html-vite/package.json b/code/frameworks/html-vite/package.json index cfb5d6869a79..06f2f179562f 100644 --- a/code/frameworks/html-vite/package.json +++ b/code/frameworks/html-vite/package.json @@ -43,8 +43,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/addons": "workspace:*", diff --git a/code/frameworks/html-webpack5/package.json b/code/frameworks/html-webpack5/package.json index dd6af1693421..32cff7f1610c 100644 --- a/code/frameworks/html-webpack5/package.json +++ b/code/frameworks/html-webpack5/package.json @@ -43,8 +43,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/builder-webpack5": "workspace:*", diff --git a/code/frameworks/nextjs/package.json b/code/frameworks/nextjs/package.json index 373f512b4efa..a69063b7b170 100644 --- a/code/frameworks/nextjs/package.json +++ b/code/frameworks/nextjs/package.json @@ -70,8 +70,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@babel/core": "^7.23.2", diff --git a/code/frameworks/preact-vite/package.json b/code/frameworks/preact-vite/package.json index d13d3bca0b54..50d16adb8310 100644 --- a/code/frameworks/preact-vite/package.json +++ b/code/frameworks/preact-vite/package.json @@ -43,8 +43,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@preact/preset-vite": "^2.0.0", diff --git a/code/frameworks/preact-webpack5/package.json b/code/frameworks/preact-webpack5/package.json index 134df1698462..6bef39303437 100644 --- a/code/frameworks/preact-webpack5/package.json +++ b/code/frameworks/preact-webpack5/package.json @@ -43,8 +43,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/builder-webpack5": "workspace:*", diff --git a/code/frameworks/react-vite/package.json b/code/frameworks/react-vite/package.json index c9e069cc4bcc..c8663a71e09c 100644 --- a/code/frameworks/react-vite/package.json +++ b/code/frameworks/react-vite/package.json @@ -43,8 +43,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@joshwooding/vite-plugin-react-docgen-typescript": "0.3.0", diff --git a/code/frameworks/react-webpack5/package.json b/code/frameworks/react-webpack5/package.json index e27ba5be6755..a56b5fd6d1c5 100644 --- a/code/frameworks/react-webpack5/package.json +++ b/code/frameworks/react-webpack5/package.json @@ -43,8 +43,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/builder-webpack5": "workspace:*", diff --git a/code/frameworks/server-webpack5/package.json b/code/frameworks/server-webpack5/package.json index 47f3fce958c0..f263c7b6b097 100644 --- a/code/frameworks/server-webpack5/package.json +++ b/code/frameworks/server-webpack5/package.json @@ -43,8 +43,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/builder-webpack5": "workspace:*", diff --git a/code/frameworks/svelte-vite/package.json b/code/frameworks/svelte-vite/package.json index 567fdd790508..8d447e1bb565 100644 --- a/code/frameworks/svelte-vite/package.json +++ b/code/frameworks/svelte-vite/package.json @@ -43,8 +43,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/builder-vite": "workspace:*", diff --git a/code/frameworks/svelte-webpack5/package.json b/code/frameworks/svelte-webpack5/package.json index d54a3393f846..9325d8342d99 100644 --- a/code/frameworks/svelte-webpack5/package.json +++ b/code/frameworks/svelte-webpack5/package.json @@ -43,8 +43,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/builder-webpack5": "workspace:*", diff --git a/code/frameworks/sveltekit/package.json b/code/frameworks/sveltekit/package.json index 1c0424652bce..3218d87b59b6 100644 --- a/code/frameworks/sveltekit/package.json +++ b/code/frameworks/sveltekit/package.json @@ -46,8 +46,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/builder-vite": "workspace:*", diff --git a/code/frameworks/vue-vite/package.json b/code/frameworks/vue-vite/package.json index f3d056f67188..2bc4ada4b5e0 100644 --- a/code/frameworks/vue-vite/package.json +++ b/code/frameworks/vue-vite/package.json @@ -43,8 +43,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/builder-vite": "workspace:*", diff --git a/code/frameworks/vue-webpack5/package.json b/code/frameworks/vue-webpack5/package.json index 95a29fae038a..6bffbe8a9fa0 100644 --- a/code/frameworks/vue-webpack5/package.json +++ b/code/frameworks/vue-webpack5/package.json @@ -43,8 +43,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/builder-webpack5": "workspace:*", diff --git a/code/frameworks/vue3-vite/package.json b/code/frameworks/vue3-vite/package.json index 1b39f568b920..145a44fef1cb 100644 --- a/code/frameworks/vue3-vite/package.json +++ b/code/frameworks/vue3-vite/package.json @@ -43,8 +43,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/builder-vite": "workspace:*", diff --git a/code/frameworks/vue3-webpack5/package.json b/code/frameworks/vue3-webpack5/package.json index f7f27f144a77..6809fff34e71 100644 --- a/code/frameworks/vue3-webpack5/package.json +++ b/code/frameworks/vue3-webpack5/package.json @@ -43,8 +43,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/builder-webpack5": "workspace:*", diff --git a/code/frameworks/web-components-vite/package.json b/code/frameworks/web-components-vite/package.json index 85000c5d71a5..e544462fcd26 100644 --- a/code/frameworks/web-components-vite/package.json +++ b/code/frameworks/web-components-vite/package.json @@ -43,8 +43,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/builder-vite": "workspace:*", diff --git a/code/frameworks/web-components-webpack5/package.json b/code/frameworks/web-components-webpack5/package.json index 21244cdbc78d..bf8be03c47c9 100644 --- a/code/frameworks/web-components-webpack5/package.json +++ b/code/frameworks/web-components-webpack5/package.json @@ -46,8 +46,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@babel/preset-env": "^7.23.2", diff --git a/code/lib/channels/package.json b/code/lib/channels/package.json index 220bc00dcc29..1f9b12dadd00 100644 --- a/code/lib/channels/package.json +++ b/code/lib/channels/package.json @@ -65,8 +65,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/lib/cli/package.json b/code/lib/cli/package.json index 9a74701a677e..91028341aa34 100644 --- a/code/lib/cli/package.json +++ b/code/lib/cli/package.json @@ -50,8 +50,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts", + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts", "test": "jest test/**/*.test.js" }, "dependencies": { diff --git a/code/lib/client-logger/package.json b/code/lib/client-logger/package.json index 5ad527fa292f..3384e0244b91 100644 --- a/code/lib/client-logger/package.json +++ b/code/lib/client-logger/package.json @@ -40,8 +40,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/global": "^5.0.0" diff --git a/code/lib/codemod/package.json b/code/lib/codemod/package.json index 096604690c64..f1802439a3cd 100644 --- a/code/lib/codemod/package.json +++ b/code/lib/codemod/package.json @@ -48,8 +48,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@babel/core": "^7.23.2", diff --git a/code/lib/core-common/package.json b/code/lib/core-common/package.json index a8c1af9f443f..bcb3fcb8d938 100644 --- a/code/lib/core-common/package.json +++ b/code/lib/core-common/package.json @@ -40,8 +40,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/core-events": "workspace:*", diff --git a/code/lib/core-events/package.json b/code/lib/core-events/package.json index d80846973c8e..c7fa8ec8d708 100644 --- a/code/lib/core-events/package.json +++ b/code/lib/core-events/package.json @@ -74,8 +74,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "ts-dedent": "^2.0.0" diff --git a/code/lib/core-server/package.json b/code/lib/core-server/package.json index e24ec0d82bf4..c785a5b83511 100644 --- a/code/lib/core-server/package.json +++ b/code/lib/core-server/package.json @@ -56,8 +56,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@aw-web-design/x-default-browser": "1.4.126", diff --git a/code/lib/core-webpack/package.json b/code/lib/core-webpack/package.json index 96bdfb086bb1..41bcb84edc34 100644 --- a/code/lib/core-webpack/package.json +++ b/code/lib/core-webpack/package.json @@ -40,8 +40,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/core-common": "workspace:*", diff --git a/code/lib/csf-plugin/package.json b/code/lib/csf-plugin/package.json index c5fa16545163..3f9f3fe2e3b3 100644 --- a/code/lib/csf-plugin/package.json +++ b/code/lib/csf-plugin/package.json @@ -40,8 +40,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/csf-tools": "workspace:*", diff --git a/code/lib/csf-tools/package.json b/code/lib/csf-tools/package.json index d6192a65472c..e0f9dbad3a03 100644 --- a/code/lib/csf-tools/package.json +++ b/code/lib/csf-tools/package.json @@ -38,8 +38,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@babel/generator": "^7.23.0", diff --git a/code/lib/docs-tools/package.json b/code/lib/docs-tools/package.json index b017a4651ce0..28192afce433 100644 --- a/code/lib/docs-tools/package.json +++ b/code/lib/docs-tools/package.json @@ -40,8 +40,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/core-common": "workspace:*", diff --git a/code/lib/instrumenter/package.json b/code/lib/instrumenter/package.json index 8c885530380f..175493fa5a4b 100644 --- a/code/lib/instrumenter/package.json +++ b/code/lib/instrumenter/package.json @@ -40,8 +40,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/channels": "workspace:*", diff --git a/code/lib/manager-api/package.json b/code/lib/manager-api/package.json index 801c9616d145..22a0f6167a12 100644 --- a/code/lib/manager-api/package.json +++ b/code/lib/manager-api/package.json @@ -39,8 +39,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/channels": "workspace:*", diff --git a/code/lib/node-logger/package.json b/code/lib/node-logger/package.json index de31ffedac48..92fd77b3688f 100644 --- a/code/lib/node-logger/package.json +++ b/code/lib/node-logger/package.json @@ -38,8 +38,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "devDependencies": { "@types/npmlog": "^4.1.2", diff --git a/code/lib/postinstall/package.json b/code/lib/postinstall/package.json index 1be31fad2e25..4fa15f7afccc 100644 --- a/code/lib/postinstall/package.json +++ b/code/lib/postinstall/package.json @@ -41,8 +41,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "devDependencies": { "jest": "^29.7.0", diff --git a/code/lib/preview-api/package.json b/code/lib/preview-api/package.json index 7cc8235a4742..965eeb0b0e18 100644 --- a/code/lib/preview-api/package.json +++ b/code/lib/preview-api/package.json @@ -64,8 +64,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/channels": "workspace:*", diff --git a/code/lib/preview/package.json b/code/lib/preview/package.json index cc2e06b83b5f..fe3ded7634f7 100644 --- a/code/lib/preview/package.json +++ b/code/lib/preview/package.json @@ -52,8 +52,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/esm-bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/esm-bundle.ts" }, "devDependencies": { "@storybook/channels": "workspace:*", diff --git a/code/lib/react-dom-shim/package.json b/code/lib/react-dom-shim/package.json index 0b9905b221e8..3f2b4241fa72 100644 --- a/code/lib/react-dom-shim/package.json +++ b/code/lib/react-dom-shim/package.json @@ -50,8 +50,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "devDependencies": { "@storybook/types": "workspace:*", diff --git a/code/lib/router/package.json b/code/lib/router/package.json index 70f3a92a95b6..8c15e8e98282 100644 --- a/code/lib/router/package.json +++ b/code/lib/router/package.json @@ -45,8 +45,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/lib/source-loader/package.json b/code/lib/source-loader/package.json index 4066cd709554..7c068ccec9a3 100644 --- a/code/lib/source-loader/package.json +++ b/code/lib/source-loader/package.json @@ -41,8 +41,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/csf": "^0.1.0", diff --git a/code/lib/telemetry/package.json b/code/lib/telemetry/package.json index f65f5d5c20eb..40d3997e6681 100644 --- a/code/lib/telemetry/package.json +++ b/code/lib/telemetry/package.json @@ -40,8 +40,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/lib/test/package.json b/code/lib/test/package.json index 1de2a016ba9d..042346075788 100644 --- a/code/lib/test/package.json +++ b/code/lib/test/package.json @@ -39,8 +39,8 @@ "*.d.ts" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/lib/theming/package.json b/code/lib/theming/package.json index 2d64c60cf941..16bafcbb62ae 100644 --- a/code/lib/theming/package.json +++ b/code/lib/theming/package.json @@ -45,8 +45,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@emotion/use-insertion-effect-with-fallbacks": "^1.0.0", diff --git a/code/lib/types/package.json b/code/lib/types/package.json index 808579cc9bde..ca2c2ef76dac 100644 --- a/code/lib/types/package.json +++ b/code/lib/types/package.json @@ -40,8 +40,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/channels": "workspace:*", diff --git a/code/package.json b/code/package.json index 685378e820cf..45e62b2406f9 100644 --- a/code/package.json +++ b/code/package.json @@ -26,7 +26,7 @@ }, "scripts": { "await-serve-storybooks": "wait-on http://localhost:8001", - "build": "NODE_ENV=production ts-node --swc --esm ../scripts/build-package.ts", + "build": "NODE_ENV=production yarn --cwd ../scripts build-package", "changelog": "pr-log --sloppy --cherry-pick", "changelog:next": "pr-log --sloppy --since-prerelease", "check": "NODE_ENV=production node ../scripts/check-package.js", diff --git a/code/presets/create-react-app/package.json b/code/presets/create-react-app/package.json index 6d223fe4b967..8732edf88e34 100644 --- a/code/presets/create-react-app/package.json +++ b/code/presets/create-react-app/package.json @@ -45,8 +45,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@pmmmwh/react-refresh-webpack-plugin": "^0.5.1", diff --git a/code/presets/html-webpack/package.json b/code/presets/html-webpack/package.json index f7eae3cde5a3..9edf6171d742 100644 --- a/code/presets/html-webpack/package.json +++ b/code/presets/html-webpack/package.json @@ -45,8 +45,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/core-webpack": "workspace:*", diff --git a/code/presets/preact-webpack/package.json b/code/presets/preact-webpack/package.json index 42619ff78004..9343e882fd8f 100644 --- a/code/presets/preact-webpack/package.json +++ b/code/presets/preact-webpack/package.json @@ -45,8 +45,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@babel/plugin-transform-react-jsx": "^7.22.15", diff --git a/code/presets/react-webpack/package.json b/code/presets/react-webpack/package.json index 2eb5e07a103a..2d584621d5c4 100644 --- a/code/presets/react-webpack/package.json +++ b/code/presets/react-webpack/package.json @@ -60,8 +60,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@babel/preset-flow": "^7.22.15", diff --git a/code/presets/server-webpack/package.json b/code/presets/server-webpack/package.json index fc97f71a8da7..34082bf790e2 100644 --- a/code/presets/server-webpack/package.json +++ b/code/presets/server-webpack/package.json @@ -50,8 +50,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/core-server": "workspace:*", diff --git a/code/presets/svelte-webpack/package.json b/code/presets/svelte-webpack/package.json index dddd9b9981c9..cde249ff6bb8 100644 --- a/code/presets/svelte-webpack/package.json +++ b/code/presets/svelte-webpack/package.json @@ -60,8 +60,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/core-webpack": "workspace:*", diff --git a/code/presets/vue-webpack/package.json b/code/presets/vue-webpack/package.json index fb9eb4538218..b1842cb352ae 100644 --- a/code/presets/vue-webpack/package.json +++ b/code/presets/vue-webpack/package.json @@ -55,8 +55,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/core-webpack": "workspace:*", diff --git a/code/presets/vue3-webpack/package.json b/code/presets/vue3-webpack/package.json index 5a9b3474c8f7..a1ba38ce467d 100644 --- a/code/presets/vue3-webpack/package.json +++ b/code/presets/vue3-webpack/package.json @@ -55,8 +55,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/core-webpack": "workspace:*", diff --git a/code/presets/web-components-webpack/package.json b/code/presets/web-components-webpack/package.json index 2b152f658feb..3ace8758cc22 100644 --- a/code/presets/web-components-webpack/package.json +++ b/code/presets/web-components-webpack/package.json @@ -48,8 +48,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@babel/plugin-syntax-dynamic-import": "^7.8.3", diff --git a/code/prettier.config.js b/code/prettier.config.js index 574656f01614..4c8f0237382a 100644 --- a/code/prettier.config.js +++ b/code/prettier.config.js @@ -1 +1 @@ -module.exports = require('../scripts/prettier.config'); +module.exports = require('../scripts/prettier.config.cjs'); diff --git a/code/renderers/html/package.json b/code/renderers/html/package.json index 9dec7bb0745e..7c27f74a9216 100644 --- a/code/renderers/html/package.json +++ b/code/renderers/html/package.json @@ -43,8 +43,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/core-client": "workspace:*", diff --git a/code/renderers/preact/package.json b/code/renderers/preact/package.json index 9d5330d468eb..a8373cb48d71 100644 --- a/code/renderers/preact/package.json +++ b/code/renderers/preact/package.json @@ -43,8 +43,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/core-client": "workspace:*", diff --git a/code/renderers/react/package.json b/code/renderers/react/package.json index 08c29dd01229..e0372f1fb22e 100644 --- a/code/renderers/react/package.json +++ b/code/renderers/react/package.json @@ -43,8 +43,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/renderers/server/package.json b/code/renderers/server/package.json index 47d9cced041e..c744c7c1a74e 100644 --- a/code/renderers/server/package.json +++ b/code/renderers/server/package.json @@ -42,8 +42,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/core-client": "workspace:*", diff --git a/code/renderers/svelte/package.json b/code/renderers/svelte/package.json index 99a84af9c552..e33d158cc63c 100644 --- a/code/renderers/svelte/package.json +++ b/code/renderers/svelte/package.json @@ -48,7 +48,7 @@ ], "scripts": { "check": "svelte-check", - "prep": "../../../scripts/prepare/bundle.ts" + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/renderers/vue/package.json b/code/renderers/vue/package.json index e9b16f82f4ae..d4a4df663f25 100644 --- a/code/renderers/vue/package.json +++ b/code/renderers/vue/package.json @@ -44,7 +44,7 @@ ], "scripts": { "check": "vue-tsc --noEmit", - "prep": "../../../scripts/prepare/bundle.ts" + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/renderers/vue3/package.json b/code/renderers/vue3/package.json index 3ea92f413b5f..1180bad9d65d 100644 --- a/code/renderers/vue3/package.json +++ b/code/renderers/vue3/package.json @@ -44,7 +44,7 @@ ], "scripts": { "check": "vue-tsc --noEmit", - "prep": "../../../scripts/prepare/bundle.ts" + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/core-client": "workspace:*", diff --git a/code/renderers/web-components/package.json b/code/renderers/web-components/package.json index 6ac0d96131dd..b3edd6f79b38 100644 --- a/code/renderers/web-components/package.json +++ b/code/renderers/web-components/package.json @@ -46,8 +46,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/ui/blocks/package.json b/code/ui/blocks/package.json index 91b854c8521c..eea82f3056e8 100644 --- a/code/ui/blocks/package.json +++ b/code/ui/blocks/package.json @@ -40,8 +40,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/channels": "workspace:*", diff --git a/code/ui/components/package.json b/code/ui/components/package.json index 92973bfacc56..98d9bf32701e 100644 --- a/code/ui/components/package.json +++ b/code/ui/components/package.json @@ -55,8 +55,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@radix-ui/react-select": "^1.2.2", diff --git a/code/ui/manager/package.json b/code/ui/manager/package.json index 6e46aecaee31..3b168cd74c99 100644 --- a/code/ui/manager/package.json +++ b/code/ui/manager/package.json @@ -47,8 +47,8 @@ "!src/**/*" ], "scripts": { - "check": "../../../scripts/prepare/check.ts", - "prep": "../../../scripts/prepare/esm-bundle.ts" + "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", + "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/esm-bundle.ts" }, "devDependencies": { "@fal-works/esbuild-plugin-global-externals": "^2.1.2", diff --git a/scripts/.babelrc.js b/scripts/.babelrc.js index 31016fd42625..c5d2be1935f6 100644 --- a/scripts/.babelrc.js +++ b/scripts/.babelrc.js @@ -1,4 +1,4 @@ -module.exports = { +export default { compact: false, presets: [ '@babel/preset-typescript', diff --git a/scripts/.eslintrc.js b/scripts/.eslintrc.cjs similarity index 100% rename from scripts/.eslintrc.js rename to scripts/.eslintrc.cjs diff --git a/scripts/build-package.ts b/scripts/build-package.ts index ab7a4be048af..b63195b188ae 100644 --- a/scripts/build-package.ts +++ b/scripts/build-package.ts @@ -1,11 +1,9 @@ -#!/usr/bin/env node - -/* eslint-disable global-require */ import { resolve, posix, sep } from 'path'; import { readJSON } from 'fs-extra'; import prompts from 'prompts'; import program from 'commander'; import chalk from 'chalk'; +import windowSize from 'window-size'; import { getWorkspaces } from './utils/workspace'; import { execaCommand } from './utils/exec'; @@ -95,7 +93,7 @@ async function run() { min: 1, hint: 'You can also run directly with package name like `yarn build core`, or `yarn build --all` for all packages!', // @ts-expect-error @types incomplete - optionsPerPage: require('window-size').height - 3, // 3 lines for extra info + optionsPerPage: windowSize.height - 3, // 3 lines for extra info choices: packages.map(({ name: key }) => ({ value: key, title: tasks[key].name || key, @@ -117,14 +115,13 @@ async function run() { } selection?.filter(Boolean).forEach(async (v) => { - const commmand = (await readJSON(resolve(v.location, 'package.json'))).scripts.prep + const commmand = (await readJSON(resolve('../code', v.location, 'package.json'))).scripts.prep .split(posix.sep) .join(sep); const cwd = resolve(__dirname, '..', 'code', v.location); - const tsNode = require.resolve('ts-node/dist/bin'); const sub = await execaCommand( - `node ${tsNode} ${commmand}${watchMode ? ' --watch' : ''}${prodMode ? ' --optimized' : ''}`, + `${commmand}${watchMode ? ' --watch' : ''}${prodMode ? ' --optimized' : ''}`, { cwd, buffer: false, diff --git a/scripts/check-dependencies.js b/scripts/check-dependencies.cjs similarity index 100% rename from scripts/check-dependencies.js rename to scripts/check-dependencies.cjs diff --git a/scripts/check-package.js b/scripts/check-package.cjs similarity index 100% rename from scripts/check-package.js rename to scripts/check-package.cjs diff --git a/scripts/jest.config.js b/scripts/jest.config.cjs similarity index 100% rename from scripts/jest.config.js rename to scripts/jest.config.cjs diff --git a/scripts/package.json b/scripts/package.json index b428f9b9f228..01a8ea31618c 100644 --- a/scripts/package.json +++ b/scripts/package.json @@ -2,35 +2,37 @@ "name": "@storybook/scripts", "version": "7.0.0-alpha.16", "private": true, + "type": "module", "scripts": { - "check": "./prepare/check-scripts.ts", + "build-package": "node --loader esbuild-register/loader -r esbuild-register ./build-package.ts", + "check": "node --loader esbuild-register/loader -r esbuild-register ./prepare/check-scripts.ts", "docs:prettier:check": "cd ../docs && prettier --check ./snippets", "docs:prettier:write": "cd ../docs && prettier --write ./snippets", - "get-report-message": "ts-node --swc ./get-report-message.ts", - "get-template": "ts-node --swc ./get-template.ts", + "get-report-message": "node --loader esbuild-register/loader -r esbuild-register ./get-report-message.ts", + "get-template": "node --loader esbuild-register/loader -r esbuild-register ./get-template.ts", "lint": "yarn lint:js && yarn lint:md", "lint:js": "yarn lint:js:cmd . --quiet", "lint:js:cmd": "cross-env NODE_ENV=production eslint --cache --cache-location=../.cache/eslint --ext .js,.jsx,.json,.html,.ts,.tsx,.mjs --report-unused-disable-directives", "lint:package": "sort-package-json", - "release:cancel-preparation-runs": "ts-node --swc ./release/cancel-preparation-runs.ts", - "release:ensure-next-ahead": "ts-node --swc ./release/ensure-next-ahead.ts", - "release:generate-pr-description": "ts-node --swc ./release/generate-pr-description.ts", - "release:get-changelog-from-file": "ts-node --swc ./release/get-changelog-from-file.ts", - "release:get-current-version": "ts-node --swc ./release/get-current-version.ts", - "release:get-version-changelog": "ts-node --swc ./release/get-version-changelog.ts", - "release:is-pr-frozen": "ts-node --swc ./release/is-pr-frozen.ts", - "release:is-prerelease": "ts-node --swc ./release/is-prerelease.ts", - "release:is-version-published": "ts-node --swc ./release/is-version-published.ts", - "release:label-patches": "ts-node --swc ./release/label-patches.ts", - "release:pick-patches": "ts-node --swc ./release/pick-patches.ts", - "release:publish": "ts-node --swc ./release/publish.ts", - "release:unreleased-changes-exists": "ts-node --swc ./release/unreleased-changes-exists.ts", - "release:version": "ts-node --swc ./release/version.ts", - "release:write-changelog": "ts-node --swc ./release/write-changelog.ts", - "strict-ts": "node --require esbuild-register ./strict-ts.ts", - "task": "ts-node --swc ./task.ts", + "release:cancel-preparation-runs": "node --loader esbuild-register/loader -r esbuild-register ./release/cancel-preparation-runs.ts", + "release:ensure-next-ahead": "node --loader esbuild-register/loader -r esbuild-register ./release/ensure-next-ahead.ts", + "release:generate-pr-description": "node --loader esbuild-register/loader -r esbuild-register ./release/generate-pr-description.ts", + "release:get-changelog-from-file": "node --loader esbuild-register/loader -r esbuild-register ./release/get-changelog-from-file.ts", + "release:get-current-version": "node --loader esbuild-register/loader -r esbuild-register ./release/get-current-version.ts", + "release:get-version-changelog": "node --loader esbuild-register/loader -r esbuild-register ./release/get-version-changelog.ts", + "release:is-pr-frozen": "node --loader esbuild-register/loader -r esbuild-register ./release/is-pr-frozen.ts", + "release:is-prerelease": "node --loader esbuild-register/loader -r esbuild-register ./release/is-prerelease.ts", + "release:is-version-published": "node --loader esbuild-register/loader -r esbuild-register ./release/is-version-published.ts", + "release:label-patches": "node --loader esbuild-register/loader -r esbuild-register ./release/label-patches.ts", + "release:pick-patches": "node --loader esbuild-register/loader -r esbuild-register ./release/pick-patches.ts", + "release:publish": "node --loader esbuild-register/loader -r esbuild-register ./release/publish.ts", + "release:unreleased-changes-exists": "node --loader esbuild-register/loader -r esbuild-register ./release/unreleased-changes-exists.ts", + "release:version": "node --loader esbuild-register/loader -r esbuild-register ./release/version.ts", + "release:write-changelog": "node --loader esbuild-register/loader -r esbuild-register ./release/write-changelog.ts", + "strict-ts": "node --loader esbuild-register/loader -r esbuild-register ./strict-ts.ts", + "task": "node --loader esbuild-register/loader -r esbuild-register ./task.ts", "test": "jest --config ./jest.config.js", - "upgrade": "ts-node --swc ./task.ts", + "upgrade": "node --loader esbuild-register/loader -r esbuild-register ./task.ts", "upload-bench": "ts-node ./upload-bench.ts" }, "husky": { @@ -104,6 +106,7 @@ "@types/serve-static": "^1.13.8", "@types/uuid": "^9.0.1", "@types/wait-on": "^5.3.1", + "@types/window-size": "^1.1.3", "@typescript-eslint/eslint-plugin": "^5.45.0", "@typescript-eslint/experimental-utils": "^5.45.0", "@typescript-eslint/parser": "^5.45.0", @@ -186,7 +189,7 @@ "ts-node": "^10.9.1", "tsup": "^6.7.0", "type-fest": "~2.19", - "typescript": "5.1.6", + "typescript": "5.2.2", "util": "^0.12.4", "uuid": "^9.0.0", "wait-on": "^7.0.1", diff --git a/scripts/prepare/bundle.ts b/scripts/prepare/bundle.ts index 1228e445a034..e71d2b1a2da6 100755 --- a/scripts/prepare/bundle.ts +++ b/scripts/prepare/bundle.ts @@ -1,5 +1,3 @@ -#!/usr/bin/env ../../node_modules/.bin/ts-node - import * as fs from 'fs-extra'; import path, { dirname, join, relative } from 'path'; import type { Options } from 'tsup'; diff --git a/scripts/prepare/check-scripts.ts b/scripts/prepare/check-scripts.ts index 86418acd93ba..261c070c1ca6 100755 --- a/scripts/prepare/check-scripts.ts +++ b/scripts/prepare/check-scripts.ts @@ -1,7 +1,5 @@ -#!/usr/bin/env ./node_modules/.bin/ts-node-script - import { join } from 'path'; -import * as ts from 'typescript'; +import ts from 'typescript'; const run = async ({ cwd }: { cwd: string }) => { const { options, fileNames } = getTSFilesAndConfig('tsconfig.json'); diff --git a/scripts/prepare/check.ts b/scripts/prepare/check.ts index d200e921ea0b..fe75515f95b1 100755 --- a/scripts/prepare/check.ts +++ b/scripts/prepare/check.ts @@ -1,8 +1,6 @@ -#!/usr/bin/env ../../node_modules/.bin/ts-node-script - import { join } from 'path'; import fs from 'fs-extra'; -import * as ts from 'typescript'; +import ts from 'typescript'; const run = async ({ cwd }: { cwd: string }) => { const { diff --git a/scripts/prettier.config.js b/scripts/prettier.config.cjs similarity index 100% rename from scripts/prettier.config.js rename to scripts/prettier.config.cjs diff --git a/scripts/release/publish.ts b/scripts/release/publish.ts index eeb8ab2f9349..52f72d5fc64d 100644 --- a/scripts/release/publish.ts +++ b/scripts/release/publish.ts @@ -7,6 +7,7 @@ import { z } from 'zod'; import { readJson } from 'fs-extra'; import fetch from 'node-fetch'; import dedent from 'ts-dedent'; +import pRetry from 'p-retry'; import { execaCommand } from '../utils/exec'; program @@ -134,15 +135,6 @@ const publishAllPackages = async ({ return; } - // Note this is to fool `ts-node` into not turning the `import()` into a `require()`. - // See: https://github.com/TypeStrong/ts-node/discussions/1290 - // prettier-ignore - const pRetry = ( - // eslint-disable-next-line @typescript-eslint/no-implied-eval - (await new Function('specifier', 'return import(specifier)')( - 'p-retry' - )) as typeof import('p-retry') - ).default; /** * 'yarn npm publish' will fail if just one package fails to publish. * But it will continue through with all the other packages, and --tolerate-republish makes it okay to publish the same version again. diff --git a/scripts/tasks/bench.ts b/scripts/tasks/bench.ts index 25325e1090e0..071bbd84ff4d 100644 --- a/scripts/tasks/bench.ts +++ b/scripts/tasks/bench.ts @@ -1,11 +1,11 @@ +import prettyBytes from 'pretty-bytes'; +import prettyTime from 'pretty-ms'; + import type { Task } from '../task'; import { PORT as devPort, dev } from './dev'; import { PORT as servePort, serve } from './serve'; -// eslint-disable-next-line @typescript-eslint/no-implied-eval -const dynamicImport = new Function('specifier', 'return import(specifier)'); - export const bench: Task = { description: 'Run benchmarks against a sandbox in dev mode', dependsOn: ['build'], @@ -19,8 +19,6 @@ export const bench: Task = { const { disableDocs } = options; const { browse } = await import('../bench/browse'); const { saveBench, loadBench } = await import('../bench/utils'); - const { default: prettyBytes } = await dynamicImport('pretty-bytes'); - const { default: prettyTime } = await dynamicImport('pretty-ms'); const devController = await dev.run(details, { ...options, debug: false }); if (!devController) { diff --git a/scripts/tasks/dev.ts b/scripts/tasks/dev.ts index 92e885f52078..138bb912cef8 100644 --- a/scripts/tasks/dev.ts +++ b/scripts/tasks/dev.ts @@ -1,4 +1,5 @@ import detectFreePort from 'detect-port'; +import waitOn from 'wait-on'; import type { Task } from '../task'; import { exec } from '../utils/exec'; @@ -18,7 +19,6 @@ export const dev: Task = { async run({ sandboxDir, selectedTask }, { dryRun, debug }) { const controller = new AbortController(); const devCommand = `yarn storybook --port ${PORT}${selectedTask === 'dev' ? '' : ' --ci'}`; - const { default: waitOn } = await import('wait-on'); const start = now(); exec( diff --git a/scripts/tasks/sandbox.ts b/scripts/tasks/sandbox.ts index 58e7d92fe421..bf3e0bbae07f 100644 --- a/scripts/tasks/sandbox.ts +++ b/scripts/tasks/sandbox.ts @@ -5,6 +5,14 @@ import { promisify } from 'util'; import dirSize from 'fast-folder-size'; import type { Task } from '../task'; import { now, saveBench } from '../bench/utils'; +import { + create, + install, + addStories, + extendMain, + init, + addExtraDependencies, +} from './sandbox-parts'; const logger = console; @@ -55,10 +63,6 @@ export const sandbox: Task = { await remove(details.sandboxDir); } - const { create, install, addStories, extendMain, init, addExtraDependencies } = await import( - './sandbox-parts' - ); - let startTime = now(); await create(details, options); const createTime = now() - startTime; diff --git a/scripts/tasks/serve.ts b/scripts/tasks/serve.ts index f5e637f33bb9..2b3a5cc8c4b9 100644 --- a/scripts/tasks/serve.ts +++ b/scripts/tasks/serve.ts @@ -1,4 +1,5 @@ import detectFreePort from 'detect-port'; +import waitOn from 'wait-on'; import type { Task } from '../task'; import { exec } from '../utils/exec'; @@ -26,7 +27,6 @@ export const serve: Task = { throw err; } }); - const { default: waitOn } = await import('wait-on'); await waitOn({ resources: [`http://localhost:${PORT}`], interval: 16 }); return controller; diff --git a/scripts/tsconfig.json b/scripts/tsconfig.json index c82e14a95108..0817a4342434 100644 --- a/scripts/tsconfig.json +++ b/scripts/tsconfig.json @@ -5,15 +5,15 @@ "incremental": false, "noImplicitAny": true, "jsx": "react", - "moduleResolution": "Node", - "target": "ES2020", - "module": "CommonJS", + "moduleResolution": "bundler", + "target": "es2022", + "module": "ES2022", "skipLibCheck": true, "allowSyntheticDefaultImports": true, "esModuleInterop": true, "isolatedModules": true, "strictBindCallApply": true, - "lib": ["dom", "esnext"], + "lib": ["dom", "es2023"], "types": ["node", "jest"], "strict": true, "strictNullChecks": false, diff --git a/scripts/utils/exec.ts b/scripts/utils/exec.ts index 74a886189420..4dec95e814fc 100644 --- a/scripts/utils/exec.ts +++ b/scripts/utils/exec.ts @@ -1,6 +1,7 @@ /* eslint-disable no-await-in-loop, no-restricted-syntax */ import type { ExecaChildProcess, Options } from 'execa'; import chalk from 'chalk'; +import { execa } from 'execa'; const logger = console; @@ -12,21 +13,14 @@ type StepOptions = { signal?: AbortSignal; }; -// Note this is to fool `ts-node` into not turning the `import()` into a `require()`. -// See: https://github.com/TypeStrong/ts-node/discussions/1290 -// eslint-disable-next-line @typescript-eslint/no-implied-eval -const dynamicImport = new Function('specifier', 'return import(specifier)'); -export const getExeca = async () => (await dynamicImport('execa')) as typeof import('execa'); - // Reimplementation of `execaCommand` to use `getExeca` export const execaCommand = async ( command: string, options: Options = {} ): Promise> => { - const execa = await getExeca(); // We await here because execaCommand returns a promise, but that's not what the user expects // eslint-disable-next-line @typescript-eslint/return-await - return await execa.execaCommand(command, { + return await execa(command, { cleanup: true, ...options, }); @@ -37,7 +31,6 @@ export const exec = async ( options: Options = {}, { startMessage, errorMessage, dryRun, debug, signal }: StepOptions = {} ): Promise => { - const execa = await getExeca(); logger.info(); if (startMessage) logger.info(startMessage); @@ -57,12 +50,12 @@ export const exec = async ( try { if (typeof command === 'string') { logger.debug(`> ${command}`); - currentChild = execa.execaCommand(command, { ...defaultOptions, ...options }); + currentChild = execa(command, { ...defaultOptions, ...options }); await currentChild; } else { for (const subcommand of command) { logger.debug(`> ${subcommand}`); - currentChild = execa.execaCommand(subcommand, { ...defaultOptions, ...options }); + currentChild = execa(subcommand, { ...defaultOptions, ...options }); await currentChild; } } diff --git a/scripts/yarn.lock b/scripts/yarn.lock index 411298c2d9b9..961917e09071 100644 --- a/scripts/yarn.lock +++ b/scripts/yarn.lock @@ -3138,6 +3138,7 @@ __metadata: "@types/serve-static": "npm:^1.13.8" "@types/uuid": "npm:^9.0.1" "@types/wait-on": "npm:^5.3.1" + "@types/window-size": "npm:^1.1.3" "@typescript-eslint/eslint-plugin": "npm:^5.45.0" "@typescript-eslint/experimental-utils": "npm:^5.45.0" "@typescript-eslint/parser": "npm:^5.45.0" @@ -3222,7 +3223,7 @@ __metadata: ts-node: "npm:^10.9.1" tsup: "npm:^6.7.0" type-fest: "npm:~2.19" - typescript: "npm:5.1.6" + typescript: "npm:5.2.2" util: "npm:^0.12.4" uuid: "npm:^9.0.0" verdaccio: "npm:^5.19.1" @@ -4089,6 +4090,15 @@ __metadata: languageName: node linkType: hard +"@types/window-size@npm:^1.1.3": + version: 1.1.3 + resolution: "@types/window-size@npm:1.1.3" + dependencies: + "@types/node": "npm:*" + checksum: 0ec54d81fd160a6ba50136a8fab4d682cf790723e7a6f758cfb1bc08fddc29e0443fbe1817894cc438cb1b4bf57e1edb7e768114221a0bd1682438e25aa7d8c8 + languageName: node + linkType: hard + "@types/yargs-parser@npm:*": version: 21.0.0 resolution: "@types/yargs-parser@npm:21.0.0" @@ -16521,23 +16531,23 @@ __metadata: languageName: node linkType: hard -"typescript@npm:5.1.6": - version: 5.1.6 - resolution: "typescript@npm:5.1.6" +"typescript@npm:5.2.2": + version: 5.2.2 + resolution: "typescript@npm:5.2.2" bin: tsc: bin/tsc tsserver: bin/tsserver - checksum: 45ac28e2df8365fd28dac42f5d62edfe69a7203d5ec646732cadc04065331f34f9078f81f150fde42ed9754eed6fa3b06a8f3523c40b821e557b727f1992e025 + checksum: 91ae3e6193d0ddb8656d4c418a033f0f75dec5e077ebbc2bd6d76439b93f35683936ee1bdc0e9cf94ec76863aa49f27159b5788219b50e1cd0cd6d110aa34b07 languageName: node linkType: hard -"typescript@patch:typescript@npm%3A5.1.6#optional!builtin": - version: 5.1.6 - resolution: "typescript@patch:typescript@npm%3A5.1.6#optional!builtin::version=5.1.6&hash=5da071" +"typescript@patch:typescript@npm%3A5.2.2#optional!builtin": + version: 5.2.2 + resolution: "typescript@patch:typescript@npm%3A5.2.2#optional!builtin::version=5.2.2&hash=f3b441" bin: tsc: bin/tsc tsserver: bin/tsserver - checksum: c2bded58ab897a8341fdbb0c1d92ea2362f498cfffebdc8a529d03e15ea2454142dfbf122dabbd9a5cb79b7123790d27def16e11844887d20636226773ed329a + checksum: 062c1cee1990e6b9419ce8a55162b8dc917eb87f807e4de0327dbc1c2fa4e5f61bc0dd4e034d38ff541d1ed0479b53bcee8e4de3a4075c51a1724eb6216cb6f5 languageName: node linkType: hard From c436354d4f965f6d5fc2fd21961059016084167f Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Fri, 3 Nov 2023 12:01:35 +0100 Subject: [PATCH 012/170] Convert require commonjs expressions to esm equivalents --- scripts/combine-compodoc.ts | 4 +++- scripts/dangerfile.ts | 11 ++++++----- scripts/event-log-checker.ts | 4 +++- scripts/get-report-message.ts | 4 +++- scripts/get-template.ts | 4 +++- scripts/release/cancel-preparation-runs.ts | 4 +++- scripts/release/ensure-next-ahead.ts | 4 +++- scripts/release/generate-pr-description.ts | 4 +++- scripts/release/get-changelog-from-file.ts | 4 +++- scripts/release/get-current-version.ts | 4 +++- scripts/release/get-version-changelog.ts | 4 +++- scripts/release/is-pr-frozen.ts | 4 +++- scripts/release/is-prerelease.ts | 4 +++- scripts/release/is-version-published.ts | 4 +++- scripts/release/label-patches.ts | 4 +++- scripts/release/pick-patches.ts | 4 +++- scripts/release/publish.ts | 4 +++- scripts/release/unreleased-changes-exists.ts | 4 +++- scripts/release/version.ts | 4 +++- scripts/release/write-changelog.ts | 4 +++- scripts/sandbox/generate.ts | 4 +++- scripts/sandbox/utils/git.ts | 2 +- scripts/tasks/install.ts | 4 ++-- scripts/tasks/sandbox-parts.ts | 4 +++- scripts/utils/cli-step.ts | 2 ++ scripts/utils/{cli-utils.js => cli-utils.ts} | 20 ++++++++------------ scripts/utils/concurrency.ts | 4 +--- 27 files changed, 83 insertions(+), 44 deletions(-) rename scripts/utils/{cli-utils.js => cli-utils.ts} (76%) diff --git a/scripts/combine-compodoc.ts b/scripts/combine-compodoc.ts index f09f85bb9870..0a4472edb7bc 100755 --- a/scripts/combine-compodoc.ts +++ b/scripts/combine-compodoc.ts @@ -6,6 +6,7 @@ import { join, resolve } from 'path'; import { realpath, readFile, writeFile, lstat } from 'fs-extra'; import { globSync } from 'glob'; import { directory } from 'tempy'; +import url from 'url'; import { execaCommand } from './utils/exec'; const logger = console; @@ -67,7 +68,8 @@ async function run(cwd: string) { await writeFile(join(cwd, 'documentation.json'), JSON.stringify(documentation)); } -if (require.main === module) { +const modulePath = url.fileURLToPath(import.meta.url); +if (process.argv[1] === modulePath) { run(resolve(process.argv[2])) .then(() => process.exit(0)) .catch((err) => { diff --git a/scripts/dangerfile.ts b/scripts/dangerfile.ts index 754686981c80..bd9bb6494602 100644 --- a/scripts/dangerfile.ts +++ b/scripts/dangerfile.ts @@ -2,13 +2,14 @@ import { fail, danger } from 'danger'; import { execSync } from 'child_process'; -execSync('npm install lodash'); +import flatten from 'lodash/flatten.js'; +import intersection from 'lodash/intersection.js'; +import isEmpty from 'lodash/isEmpty.js'; + +import pkg from '../code/package.json'; -const flatten = require('lodash/flatten.js'); -const intersection = require('lodash/intersection.js'); -const isEmpty = require('lodash/isEmpty.js'); +execSync('npm install lodash'); -const pkg = require('../code/package.json'); // eslint-disable-line import/newline-after-import const prLogConfig = pkg['pr-log']; const Versions = { diff --git a/scripts/event-log-checker.ts b/scripts/event-log-checker.ts index e1f6d82bd533..4f418bffde9e 100644 --- a/scripts/event-log-checker.ts +++ b/scripts/event-log-checker.ts @@ -2,6 +2,7 @@ import chalk from 'chalk'; import assert from 'assert'; import fetch from 'node-fetch'; +import url from 'url'; import { allTemplates } from '../code/lib/cli/src/sandbox-templates'; import versions from '../code/lib/cli/src/versions'; import { oneWayHash } from '../code/lib/telemetry/src/one-way-hash'; @@ -114,7 +115,8 @@ async function run() { export {}; -if (require.main === module) { +const modulePath = url.fileURLToPath(import.meta.url); +if (process.argv[1] === modulePath) { run() .then(() => process.exit(0)) .catch((err) => { diff --git a/scripts/get-report-message.ts b/scripts/get-report-message.ts index 47b24cfba47b..170938cbde0a 100644 --- a/scripts/get-report-message.ts +++ b/scripts/get-report-message.ts @@ -1,6 +1,7 @@ /* eslint-disable no-console */ import { readJson } from 'fs-extra'; import { join } from 'path'; +import url from 'url'; import { CODE_DIRECTORY } from './utils/constants'; import { execaCommand } from './utils/exec'; @@ -63,7 +64,8 @@ async function run() { console.log(`${title}${body}${footer}`.replace(/\n/g, '\\n')); } -if (require.main === module) { +const modulePath = url.fileURLToPath(import.meta.url); +if (process.argv[1] === modulePath) { run().catch((err) => { console.error(err); process.exit(1); diff --git a/scripts/get-template.ts b/scripts/get-template.ts index c56418f7a0b4..5c4b43ad0cb2 100644 --- a/scripts/get-template.ts +++ b/scripts/get-template.ts @@ -4,6 +4,7 @@ import { program } from 'commander'; import dedent from 'ts-dedent'; import chalk from 'chalk'; import yaml from 'yaml'; +import url from 'url'; import { allTemplates, templatesByCadence, @@ -179,7 +180,8 @@ async function run({ cadence, task, check }: RunOptions) { ); } -if (require.main === module) { +const modulePath = url.fileURLToPath(import.meta.url); +if (process.argv[1] === modulePath) { program .description('Retrieve the template to run for a given cadence and task') .option('--cadence ', 'Which cadence you want to run the script for') diff --git a/scripts/release/cancel-preparation-runs.ts b/scripts/release/cancel-preparation-runs.ts index 630bfb4847b3..9253f12041c5 100644 --- a/scripts/release/cancel-preparation-runs.ts +++ b/scripts/release/cancel-preparation-runs.ts @@ -6,6 +6,7 @@ import chalk from 'chalk'; import program from 'commander'; import dedent from 'ts-dedent'; +import url from 'url'; import { githubRestClient } from './utils/github-client'; program @@ -99,7 +100,8 @@ export const run = async () => { } }; -if (require.main === module) { +const modulePath = url.fileURLToPath(import.meta.url); +if (process.argv[1] === modulePath) { run().catch((err) => { console.error(err); // this is non-critical work, so we don't want to fail the CI build if this fails diff --git a/scripts/release/ensure-next-ahead.ts b/scripts/release/ensure-next-ahead.ts index 1aa32bfd932c..2deae1bee36e 100644 --- a/scripts/release/ensure-next-ahead.ts +++ b/scripts/release/ensure-next-ahead.ts @@ -14,6 +14,7 @@ import program from 'commander'; import semver from 'semver'; import { z } from 'zod'; import { readJson } from 'fs-extra'; +import url from 'url'; import { run as bumpVersion } from './version'; import { git } from './utils/git-client'; @@ -92,7 +93,8 @@ export const run = async (options: unknown) => { ); }; -if (require.main === module) { +const modulePath = url.fileURLToPath(import.meta.url); +if (process.argv[1] === modulePath) { const parsed = program.parse(); run(parsed.opts()).catch((err) => { console.error(err); diff --git a/scripts/release/generate-pr-description.ts b/scripts/release/generate-pr-description.ts index d437e8dc87bc..a62c586db867 100644 --- a/scripts/release/generate-pr-description.ts +++ b/scripts/release/generate-pr-description.ts @@ -5,6 +5,7 @@ import { z } from 'zod'; import dedent from 'ts-dedent'; import semver from 'semver'; import { setOutput } from '@actions/core'; +import url from 'url'; import type { Change } from './utils/get-changes'; import { getChanges, LABELS_BY_IMPORTANCE, RELEASED_LABELS } from './utils/get-changes'; import { getCurrentVersion } from './get-current-version'; @@ -295,7 +296,8 @@ export const run = async (rawOptions: unknown) => { } }; -if (require.main === module) { +const modulePath = url.fileURLToPath(import.meta.url); +if (process.argv[1] === modulePath) { const parsed = program.parse(); run(parsed.opts()).catch((err) => { console.error(err); diff --git a/scripts/release/get-changelog-from-file.ts b/scripts/release/get-changelog-from-file.ts index e01efe959032..7a5ea3ecaddd 100644 --- a/scripts/release/get-changelog-from-file.ts +++ b/scripts/release/get-changelog-from-file.ts @@ -6,6 +6,7 @@ import { readFile } from 'fs-extra'; import path from 'path'; import semver from 'semver'; import dedent from 'ts-dedent'; +import url from 'url'; import { getCurrentVersion } from './get-current-version'; program @@ -54,7 +55,8 @@ export const getChangelogFromFile = async (args: { return result; }; -if (require.main === module) { +const modulePath = url.fileURLToPath(import.meta.url); +if (process.argv[1] === modulePath) { const parsed = program.parse(); getChangelogFromFile({ version: parsed.args[0], diff --git a/scripts/release/get-current-version.ts b/scripts/release/get-current-version.ts index 413c101640b6..df91678f9c44 100644 --- a/scripts/release/get-current-version.ts +++ b/scripts/release/get-current-version.ts @@ -3,6 +3,7 @@ import chalk from 'chalk'; import { setOutput } from '@actions/core'; import path from 'path'; import { readJson } from 'fs-extra'; +import url from 'url'; const CODE_DIR_PATH = path.join(__dirname, '..', '..', 'code'); const CODE_PACKAGE_JSON_PATH = path.join(CODE_DIR_PATH, 'package.json'); @@ -17,7 +18,8 @@ export const getCurrentVersion = async () => { return version; }; -if (require.main === module) { +const modulePath = url.fileURLToPath(import.meta.url); +if (process.argv[1] === modulePath) { getCurrentVersion().catch((err) => { console.error(err); process.exit(1); diff --git a/scripts/release/get-version-changelog.ts b/scripts/release/get-version-changelog.ts index 3ece5480236d..c70ec902bb0d 100644 --- a/scripts/release/get-version-changelog.ts +++ b/scripts/release/get-version-changelog.ts @@ -2,6 +2,7 @@ import { setOutput } from '@actions/core'; import chalk from 'chalk'; import { program } from 'commander'; +import url from 'url'; import { getCurrentVersion } from './get-current-version'; import { getChanges } from './utils/get-changes'; @@ -26,7 +27,8 @@ export const getVersionChangelog = async (args: { version?: string; verbose?: bo return changelogText; }; -if (require.main === module) { +const modulePath = url.fileURLToPath(import.meta.url); +if (process.argv[1] === modulePath) { const parsed = program.parse(); getVersionChangelog({ version: parsed.args[0], verbose: parsed.opts().verbose }).catch((err) => { console.error(err); diff --git a/scripts/release/is-pr-frozen.ts b/scripts/release/is-pr-frozen.ts index e81610a451b9..d2e774b82cb7 100644 --- a/scripts/release/is-pr-frozen.ts +++ b/scripts/release/is-pr-frozen.ts @@ -4,6 +4,7 @@ import program from 'commander'; import { setOutput } from '@actions/core'; import path from 'path'; import { readJson } from 'fs-extra'; +import url from 'url'; import { getPullInfoFromCommit } from './utils/get-github-info'; import { git } from './utils/git-client'; @@ -98,7 +99,8 @@ export const run = async (options: unknown) => { return isFrozen; }; -if (require.main === module) { +const modulePath = url.fileURLToPath(import.meta.url); +if (process.argv[1] === modulePath) { const parsed = program.parse(); run(parsed.opts()).catch((err) => { console.error(err); diff --git a/scripts/release/is-prerelease.ts b/scripts/release/is-prerelease.ts index 25722c098cd6..ab9606073de6 100644 --- a/scripts/release/is-prerelease.ts +++ b/scripts/release/is-prerelease.ts @@ -3,6 +3,7 @@ import chalk from 'chalk'; import program from 'commander'; import { setOutput } from '@actions/core'; import semver from 'semver'; +import url from 'url'; import { getCurrentVersion } from './get-current-version'; program @@ -38,7 +39,8 @@ export const isPrerelease = async (args: { version?: string; verbose?: boolean } return result; }; -if (require.main === module) { +const modulePath = url.fileURLToPath(import.meta.url); +if (process.argv[1] === modulePath) { const parsed = program.parse(); isPrerelease({ version: parsed.args[0], diff --git a/scripts/release/is-version-published.ts b/scripts/release/is-version-published.ts index b5acd8c90ab7..a0b97d1a155c 100644 --- a/scripts/release/is-version-published.ts +++ b/scripts/release/is-version-published.ts @@ -3,6 +3,7 @@ import chalk from 'chalk'; import program from 'commander'; import { setOutput } from '@actions/core'; import fetch from 'node-fetch'; +import url from 'url'; import { getCurrentVersion } from './get-current-version'; program @@ -77,7 +78,8 @@ export const run = async (args: unknown[], options: unknown) => { return isAlreadyPublished; }; -if (require.main === module) { +const modulePath = url.fileURLToPath(import.meta.url); +if (process.argv[1] === modulePath) { const parsed = program.parse(); run(parsed.args, parsed.opts()).catch((err) => { console.error(err); diff --git a/scripts/release/label-patches.ts b/scripts/release/label-patches.ts index 1e9305b9806c..a23fbfe07a3e 100644 --- a/scripts/release/label-patches.ts +++ b/scripts/release/label-patches.ts @@ -1,6 +1,7 @@ import program from 'commander'; import { v4 as uuidv4 } from 'uuid'; import ora from 'ora'; +import url from 'url'; import { getLabelIds, githubGraphQlClient, getUnpickedPRs } from './utils/github-client'; import { getPullInfoFromCommits, getRepo } from './utils/get-changes'; import { getLatestTag, git } from './utils/git-client'; @@ -93,7 +94,8 @@ export const run = async (options: unknown) => { } }; -if (require.main === module) { +const modulePath = url.fileURLToPath(import.meta.url); +if (process.argv[1] === modulePath) { const options = program.parse().opts(); run(options).catch((err) => { console.error(err); diff --git a/scripts/release/pick-patches.ts b/scripts/release/pick-patches.ts index 9d3169d78c8a..cfaaf9693771 100644 --- a/scripts/release/pick-patches.ts +++ b/scripts/release/pick-patches.ts @@ -5,6 +5,7 @@ import chalk from 'chalk'; import ora from 'ora'; import { setOutput } from '@actions/core'; import invariant from 'tiny-invariant'; +import url from 'url'; import { git } from './utils/git-client'; import { getUnpickedPRs } from './utils/github-client'; @@ -85,7 +86,8 @@ export const run = async (_: unknown) => { } }; -if (require.main === module) { +const modulePath = url.fileURLToPath(import.meta.url); +if (process.argv[1] === modulePath) { const options = program.parse(process.argv); run(options).catch((err) => { console.error(err); diff --git a/scripts/release/publish.ts b/scripts/release/publish.ts index 52f72d5fc64d..82b01c552e9b 100644 --- a/scripts/release/publish.ts +++ b/scripts/release/publish.ts @@ -8,6 +8,7 @@ import { readJson } from 'fs-extra'; import fetch from 'node-fetch'; import dedent from 'ts-dedent'; import pRetry from 'p-retry'; +import url from 'url'; import { execaCommand } from '../utils/exec'; program @@ -189,7 +190,8 @@ export const run = async (options: unknown) => { ); }; -if (require.main === module) { +const modulePath = url.fileURLToPath(import.meta.url); +if (process.argv[1] === modulePath) { const parsed = program.parse(); run(parsed.opts()).catch((err) => { console.error(err); diff --git a/scripts/release/unreleased-changes-exists.ts b/scripts/release/unreleased-changes-exists.ts index 59adedbdbb0e..c0cd5260d59b 100644 --- a/scripts/release/unreleased-changes-exists.ts +++ b/scripts/release/unreleased-changes-exists.ts @@ -4,6 +4,7 @@ import program from 'commander'; import { z } from 'zod'; import { setOutput } from '@actions/core'; import { intersection } from 'lodash'; +import url from 'url'; import type { Change } from './utils/get-changes'; import { RELEASED_LABELS, getChanges } from './utils/get-changes'; import { getCurrentVersion } from './get-current-version'; @@ -77,7 +78,8 @@ ${chalk.blue(changesToRelease.map(({ title, pull }) => ` #${pull}: ${title}`).j return { changesToRelease, hasChangesToRelease }; }; -if (require.main === module) { +const modulePath = url.fileURLToPath(import.meta.url); +if (process.argv[1] === modulePath) { const parsed = program.parse(); run(parsed.opts()).catch((err) => { console.error(err); diff --git a/scripts/release/version.ts b/scripts/release/version.ts index 3b34d288a8c7..da9e7894d050 100644 --- a/scripts/release/version.ts +++ b/scripts/release/version.ts @@ -6,6 +6,7 @@ import path from 'path'; import program from 'commander'; import semver from 'semver'; import { z } from 'zod'; +import url from 'url'; import type { Workspace } from '../utils/workspace'; import { getWorkspaces } from '../utils/workspace'; import { execaCommand } from '../utils/exec'; @@ -293,7 +294,8 @@ export const run = async (options: unknown) => { } }; -if (require.main === module) { +const modulePath = url.fileURLToPath(import.meta.url); +if (process.argv[1] === modulePath) { const options = program.parse().opts(); run(options).catch((err) => { console.error(err); diff --git a/scripts/release/write-changelog.ts b/scripts/release/write-changelog.ts index 41bc9b72bd36..a353309b65af 100644 --- a/scripts/release/write-changelog.ts +++ b/scripts/release/write-changelog.ts @@ -5,6 +5,7 @@ import program from 'commander'; import semver from 'semver'; import { z } from 'zod'; import { readFile, writeFile, writeJson } from 'fs-extra'; +import url from 'url'; import { getChanges } from './utils/get-changes'; program @@ -132,7 +133,8 @@ export const run = async (args: unknown[], options: unknown) => { console.log(`āœ… Wrote Changelog to file`); }; -if (require.main === module) { +const modulePath = url.fileURLToPath(import.meta.url); +if (process.argv[1] === modulePath) { const parsed = program.parse(); run(parsed.args, parsed.opts()).catch((err) => { console.error(err); diff --git a/scripts/sandbox/generate.ts b/scripts/sandbox/generate.ts index 22a4eccf4d14..229df395bbb3 100755 --- a/scripts/sandbox/generate.ts +++ b/scripts/sandbox/generate.ts @@ -6,6 +6,7 @@ import prettyTime from 'pretty-hrtime'; import { copy, emptyDir, ensureDir, move, remove, rename, writeFile } from 'fs-extra'; import { program } from 'commander'; import { directory } from 'tempy'; +import url from 'url'; import { execaCommand } from '../utils/exec'; import type { OptionValues } from '../utils/options'; @@ -250,7 +251,8 @@ export const generate = async ({ await runGenerators(generatorConfigs, localRegistry, debug); }; -if (require.main === module) { +const modulePath = url.fileURLToPath(import.meta.url); +if (process.argv[1] === modulePath) { program .description('Generate sandboxes from a set of possible templates') .option('--templates [templates...]', 'Space-delimited list of templates to include') diff --git a/scripts/sandbox/utils/git.ts b/scripts/sandbox/utils/git.ts index 84fe02f25cdb..dea378eae921 100644 --- a/scripts/sandbox/utils/git.ts +++ b/scripts/sandbox/utils/git.ts @@ -5,7 +5,7 @@ import { execaCommand } from '../../utils/exec'; // eslint-disable-next-line import/no-cycle import { logger } from '../publish'; -const { version: storybookVersion } = require('../../../code/package.json'); +import { version as storybookVersion } from '../../../code/package.json'; const getTheLastCommitHashThatUpdatedTheSandboxRepo = async (branch: string) => { const owner = 'storybookjs'; diff --git a/scripts/tasks/install.ts b/scripts/tasks/install.ts index 653eda568381..e78130ab514f 100644 --- a/scripts/tasks/install.ts +++ b/scripts/tasks/install.ts @@ -1,6 +1,7 @@ import { pathExists, remove } from 'fs-extra'; import { join } from 'path'; import type { Task } from '../task'; +import { checkDependencies } from '../utils/cli-utils'; export const install: Task = { description: 'Install the dependencies of the monorepo', @@ -8,8 +9,7 @@ export const install: Task = { return pathExists(join(codeDir, 'node_modules')); }, async run({ codeDir }) { - // eslint-disable-next-line global-require - await require('../utils/cli-utils').checkDependencies(); + await checkDependencies(); // these are webpack4 types, we we should never use await remove(join(codeDir, 'node_modules', '@types', 'webpack')); diff --git a/scripts/tasks/sandbox-parts.ts b/scripts/tasks/sandbox-parts.ts index 393169b244f8..f64c13c61fbc 100644 --- a/scripts/tasks/sandbox-parts.ts +++ b/scripts/tasks/sandbox-parts.ts @@ -12,8 +12,9 @@ import { writeJson, } from 'fs-extra'; import { join, resolve, sep } from 'path'; - +import { createRequire } from 'module'; import slash from 'slash'; + import type { Task } from '../task'; import { executeCLIStep, steps } from '../utils/cli-step'; import { @@ -167,6 +168,7 @@ export const init: Task['run'] = async ( // loader for such files. NOTE this isn't necessary for Vite, as far as we know. function addEsbuildLoaderToStories(mainConfig: ConfigFile) { // NOTE: the test regexp here will apply whether the path is symlink-preserved or otherwise + const require = createRequire(import.meta.url); const esbuildLoaderPath = require.resolve('../../code/node_modules/esbuild-loader'); const storiesMdxLoaderPath = require.resolve( '../../code/node_modules/@storybook/mdx2-csf/loader' diff --git a/scripts/utils/cli-step.ts b/scripts/utils/cli-step.ts index d990597619f3..9e736f30b2a4 100644 --- a/scripts/utils/cli-step.ts +++ b/scripts/utils/cli-step.ts @@ -1,7 +1,9 @@ +import { createRequire } from 'module'; import type { OptionSpecifier, OptionValues } from './options'; import { createOptions, getCommand } from './options'; import { exec } from './exec'; +const require = createRequire(import.meta.url); const cliExecutable = require.resolve('../../code/lib/cli/bin/index.js'); export type CLIStep = { diff --git a/scripts/utils/cli-utils.js b/scripts/utils/cli-utils.ts similarity index 76% rename from scripts/utils/cli-utils.js rename to scripts/utils/cli-utils.ts index ba52d9338875..c37f2a950d74 100644 --- a/scripts/utils/cli-utils.js +++ b/scripts/utils/cli-utils.ts @@ -1,14 +1,14 @@ -const { spawn } = require('child_process'); -const { join } = require('path'); -const { existsSync } = require('fs'); +import { spawn } from 'child_process'; +import { join } from 'path'; +import { existsSync } from 'fs'; const logger = console; -const checkDependencies = async () => { +export const checkDependencies = async () => { const scriptsPath = join(__dirname, '..'); const codePath = join(__dirname, '..', '..', 'code'); - const tasks = []; + const tasks: Array = []; if (!existsSync(join(scriptsPath, 'node_modules'))) { tasks.push( @@ -35,8 +35,8 @@ const checkDependencies = async () => { await Promise.all( tasks.map( (t) => - new Promise((res, rej) => { - t.on('exit', (code) => { + new Promise((res, rej) => { + t.on('exit', (code: number) => { if (code !== 0) { rej(); } else { @@ -51,12 +51,8 @@ const checkDependencies = async () => { }); // give the filesystem some time - await new Promise((res, rej) => { + await new Promise((res) => { setTimeout(res, 1000); }); } }; - -module.exports = { - checkDependencies, -}; diff --git a/scripts/utils/concurrency.ts b/scripts/utils/concurrency.ts index ab49dc41e8f5..781c7c0d6787 100644 --- a/scripts/utils/concurrency.ts +++ b/scripts/utils/concurrency.ts @@ -1,9 +1,7 @@ -const os = require('os'); +import os from 'os'; /** * The maximum number of concurrent tasks we want to have on some CLI and CI tasks. * The amount of CPUS minus one, arbitrary limited to 15 to not overload CI executors. - * @type {number} */ export const maxConcurrentTasks = Math.min(Math.max(1, os.cpus().length - 1), 15); - From 946d8630ecce1579f8fafbd9af4ba9c77ce37d78 Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Fri, 3 Nov 2023 12:20:50 +0100 Subject: [PATCH 013/170] Fix babel and eslint --- scripts/{.babelrc.js => .babelrc.cjs} | 2 +- scripts/.eslintignore | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename scripts/{.babelrc.js => .babelrc.cjs} (93%) diff --git a/scripts/.babelrc.js b/scripts/.babelrc.cjs similarity index 93% rename from scripts/.babelrc.js rename to scripts/.babelrc.cjs index c5d2be1935f6..31016fd42625 100644 --- a/scripts/.babelrc.js +++ b/scripts/.babelrc.cjs @@ -1,4 +1,4 @@ -export default { +module.exports = { compact: false, presets: [ '@babel/preset-typescript', diff --git a/scripts/.eslintignore b/scripts/.eslintignore index db97fa57090f..9224e493860f 100644 --- a/scripts/.eslintignore +++ b/scripts/.eslintignore @@ -21,6 +21,6 @@ ember-output !.babelrc.js !.eslintrc.js !.eslintrc-markdown.js -!.jest.config.js +!.jest.config.cjs !.storybook From 3c806e093cf048ce339134859fa7771aaac29ec2 Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Fri, 3 Nov 2023 12:20:58 +0100 Subject: [PATCH 014/170] Fix tests --- scripts/jest.config.cjs | 22 ++++++- scripts/package.json | 6 +- scripts/yarn.lock | 143 ++++++++++++++++++++++++++-------------- 3 files changed, 117 insertions(+), 54 deletions(-) diff --git a/scripts/jest.config.cjs b/scripts/jest.config.cjs index f053ebf7976e..571d0ab11232 100644 --- a/scripts/jest.config.cjs +++ b/scripts/jest.config.cjs @@ -1 +1,21 @@ -module.exports = {}; +module.exports = { + transform: { + '^.+\\.(t|j)sx?$': [ + '@swc/jest', + { + jsc: { + parser: { + syntax: 'typescript', + tsx: false, + decorators: false, + dynamicImport: false, + }, + experimental: { + plugins: [['jest_workaround', {}]], + }, + }, + }, + ], + }, + transformIgnorePatterns: [], +}; diff --git a/scripts/package.json b/scripts/package.json index 01a8ea31618c..d1bd6e17fe99 100644 --- a/scripts/package.json +++ b/scripts/package.json @@ -31,7 +31,7 @@ "release:write-changelog": "node --loader esbuild-register/loader -r esbuild-register ./release/write-changelog.ts", "strict-ts": "node --loader esbuild-register/loader -r esbuild-register ./strict-ts.ts", "task": "node --loader esbuild-register/loader -r esbuild-register ./task.ts", - "test": "jest --config ./jest.config.js", + "test": "jest --config ./jest.config.cjs", "upgrade": "node --loader esbuild-register/loader -r esbuild-register ./task.ts", "upload-bench": "ts-node ./upload-bench.ts" }, @@ -81,7 +81,8 @@ "@storybook/jest": "next", "@storybook/linter-config": "^3.1.2", "@storybook/testing-library": "next", - "@swc/core": "1.3.82", + "@swc/core": "^1.3.95", + "@swc/jest": "^0.2.29", "@testing-library/dom": "^9.3.0", "@testing-library/jest-dom": "^5.11.9", "@testing-library/react": "^14.0.0", @@ -149,6 +150,7 @@ "jest-os-detection": "^1.3.1", "jest-serializer-html": "^7.1.0", "jest-watch-typeahead": "^2.2.1", + "jest_workaround": "^0.79.19", "json5": "^2.2.3", "junit-xml": "^1.2.0", "lint-staged": "^10.5.4", diff --git a/scripts/yarn.lock b/scripts/yarn.lock index 961917e09071..fc179744fad1 100644 --- a/scripts/yarn.lock +++ b/scripts/yarn.lock @@ -2170,6 +2170,15 @@ __metadata: languageName: node linkType: hard +"@jest/create-cache-key-function@npm:^27.4.2": + version: 27.5.1 + resolution: "@jest/create-cache-key-function@npm:27.5.1" + dependencies: + "@jest/types": "npm:^27.5.1" + checksum: 1890ac93fad852e0a98c31de1e5f2c548974aefd36e838d27b70834dda1654a153ed6a52258447ebacfd47463e9bdb83750631bee827797c7b9973c083998a96 + languageName: node + linkType: hard + "@jest/environment@npm:^29.7.0": version: 29.7.0 resolution: "@jest/environment@npm:29.7.0" @@ -3113,7 +3122,8 @@ __metadata: "@storybook/jest": "npm:next" "@storybook/linter-config": "npm:^3.1.2" "@storybook/testing-library": "npm:next" - "@swc/core": "npm:1.3.82" + "@swc/core": "npm:^1.3.95" + "@swc/jest": "npm:^0.2.29" "@testing-library/dom": "npm:^9.3.0" "@testing-library/jest-dom": "npm:^5.11.9" "@testing-library/react": "npm:^14.0.0" @@ -3182,6 +3192,7 @@ __metadata: jest-os-detection: "npm:^1.3.1" jest-serializer-html: "npm:^7.1.0" jest-watch-typeahead: "npm:^2.2.1" + jest_workaround: "npm:^0.79.19" json5: "npm:^2.2.3" junit-xml: "npm:^1.2.0" lint-staged: "npm:^10.5.4" @@ -3262,91 +3273,92 @@ __metadata: languageName: node linkType: hard -"@swc/core-darwin-arm64@npm:1.3.82": - version: 1.3.82 - resolution: "@swc/core-darwin-arm64@npm:1.3.82" +"@swc/core-darwin-arm64@npm:1.3.95": + version: 1.3.95 + resolution: "@swc/core-darwin-arm64@npm:1.3.95" conditions: os=darwin & cpu=arm64 languageName: node linkType: hard -"@swc/core-darwin-x64@npm:1.3.82": - version: 1.3.82 - resolution: "@swc/core-darwin-x64@npm:1.3.82" +"@swc/core-darwin-x64@npm:1.3.95": + version: 1.3.95 + resolution: "@swc/core-darwin-x64@npm:1.3.95" conditions: os=darwin & cpu=x64 languageName: node linkType: hard -"@swc/core-linux-arm-gnueabihf@npm:1.3.82": - version: 1.3.82 - resolution: "@swc/core-linux-arm-gnueabihf@npm:1.3.82" +"@swc/core-linux-arm-gnueabihf@npm:1.3.95": + version: 1.3.95 + resolution: "@swc/core-linux-arm-gnueabihf@npm:1.3.95" conditions: os=linux & cpu=arm languageName: node linkType: hard -"@swc/core-linux-arm64-gnu@npm:1.3.82": - version: 1.3.82 - resolution: "@swc/core-linux-arm64-gnu@npm:1.3.82" +"@swc/core-linux-arm64-gnu@npm:1.3.95": + version: 1.3.95 + resolution: "@swc/core-linux-arm64-gnu@npm:1.3.95" conditions: os=linux & cpu=arm64 & libc=glibc languageName: node linkType: hard -"@swc/core-linux-arm64-musl@npm:1.3.82": - version: 1.3.82 - resolution: "@swc/core-linux-arm64-musl@npm:1.3.82" +"@swc/core-linux-arm64-musl@npm:1.3.95": + version: 1.3.95 + resolution: "@swc/core-linux-arm64-musl@npm:1.3.95" conditions: os=linux & cpu=arm64 & libc=musl languageName: node linkType: hard -"@swc/core-linux-x64-gnu@npm:1.3.82": - version: 1.3.82 - resolution: "@swc/core-linux-x64-gnu@npm:1.3.82" +"@swc/core-linux-x64-gnu@npm:1.3.95": + version: 1.3.95 + resolution: "@swc/core-linux-x64-gnu@npm:1.3.95" conditions: os=linux & cpu=x64 & libc=glibc languageName: node linkType: hard -"@swc/core-linux-x64-musl@npm:1.3.82": - version: 1.3.82 - resolution: "@swc/core-linux-x64-musl@npm:1.3.82" +"@swc/core-linux-x64-musl@npm:1.3.95": + version: 1.3.95 + resolution: "@swc/core-linux-x64-musl@npm:1.3.95" conditions: os=linux & cpu=x64 & libc=musl languageName: node linkType: hard -"@swc/core-win32-arm64-msvc@npm:1.3.82": - version: 1.3.82 - resolution: "@swc/core-win32-arm64-msvc@npm:1.3.82" +"@swc/core-win32-arm64-msvc@npm:1.3.95": + version: 1.3.95 + resolution: "@swc/core-win32-arm64-msvc@npm:1.3.95" conditions: os=win32 & cpu=arm64 languageName: node linkType: hard -"@swc/core-win32-ia32-msvc@npm:1.3.82": - version: 1.3.82 - resolution: "@swc/core-win32-ia32-msvc@npm:1.3.82" +"@swc/core-win32-ia32-msvc@npm:1.3.95": + version: 1.3.95 + resolution: "@swc/core-win32-ia32-msvc@npm:1.3.95" conditions: os=win32 & cpu=ia32 languageName: node linkType: hard -"@swc/core-win32-x64-msvc@npm:1.3.82": - version: 1.3.82 - resolution: "@swc/core-win32-x64-msvc@npm:1.3.82" +"@swc/core-win32-x64-msvc@npm:1.3.95": + version: 1.3.95 + resolution: "@swc/core-win32-x64-msvc@npm:1.3.95" conditions: os=win32 & cpu=x64 languageName: node linkType: hard -"@swc/core@npm:1.3.82": - version: 1.3.82 - resolution: "@swc/core@npm:1.3.82" +"@swc/core@npm:^1.3.95": + version: 1.3.95 + resolution: "@swc/core@npm:1.3.95" dependencies: - "@swc/core-darwin-arm64": "npm:1.3.82" - "@swc/core-darwin-x64": "npm:1.3.82" - "@swc/core-linux-arm-gnueabihf": "npm:1.3.82" - "@swc/core-linux-arm64-gnu": "npm:1.3.82" - "@swc/core-linux-arm64-musl": "npm:1.3.82" - "@swc/core-linux-x64-gnu": "npm:1.3.82" - "@swc/core-linux-x64-musl": "npm:1.3.82" - "@swc/core-win32-arm64-msvc": "npm:1.3.82" - "@swc/core-win32-ia32-msvc": "npm:1.3.82" - "@swc/core-win32-x64-msvc": "npm:1.3.82" - "@swc/types": "npm:^0.1.4" + "@swc/core-darwin-arm64": "npm:1.3.95" + "@swc/core-darwin-x64": "npm:1.3.95" + "@swc/core-linux-arm-gnueabihf": "npm:1.3.95" + "@swc/core-linux-arm64-gnu": "npm:1.3.95" + "@swc/core-linux-arm64-musl": "npm:1.3.95" + "@swc/core-linux-x64-gnu": "npm:1.3.95" + "@swc/core-linux-x64-musl": "npm:1.3.95" + "@swc/core-win32-arm64-msvc": "npm:1.3.95" + "@swc/core-win32-ia32-msvc": "npm:1.3.95" + "@swc/core-win32-x64-msvc": "npm:1.3.95" + "@swc/counter": "npm:^0.1.1" + "@swc/types": "npm:^0.1.5" peerDependencies: "@swc/helpers": ^0.5.0 dependenciesMeta: @@ -3373,14 +3385,33 @@ __metadata: peerDependenciesMeta: "@swc/helpers": optional: true - checksum: cee1f56e969074fe9e23fe51348d7da0c921949f5845e57030824d0e32d09fcefc647371c982e82836cc72c27c5fc5370c6aaff4f8f1c527d1c39c5ab6203e17 + checksum: f0386b7cc1288d97ef3636fff06c1798914e453b574934778d6c90019acf6893bf566c805369ab74b7c7b559243de37e3fe8bb2bbe9b1ac3214a0575cc4f7335 languageName: node linkType: hard -"@swc/types@npm:^0.1.4": - version: 0.1.4 - resolution: "@swc/types@npm:0.1.4" - checksum: f506cb23a08c604c6343c51f47e399d2c59f2e4a7df0689849284915a9f726ca65ce86d5358b5ed88c6ba1fce135a25614b1adda1beedf570a24c230466d6a46 +"@swc/counter@npm:^0.1.1": + version: 0.1.2 + resolution: "@swc/counter@npm:0.1.2" + checksum: 18be012107d4ba1f79776c48d83391ca2159103d7d31a59ff52fcc8024db51b71c5f46714a9fb73981739bc8a38dc6f385a046b71cc08f6043f3c47f5c409eab + languageName: node + linkType: hard + +"@swc/jest@npm:^0.2.29": + version: 0.2.29 + resolution: "@swc/jest@npm:0.2.29" + dependencies: + "@jest/create-cache-key-function": "npm:^27.4.2" + jsonc-parser: "npm:^3.2.0" + peerDependencies: + "@swc/core": "*" + checksum: 10f34341f9bc8003cec44f91a88b531ba44094aad97b2f8410fb2f94db9eb3b8fc7f6d14ba867eb9c1dc6ba29cc46058244b8280d673a7c681062fe0dc73c3f0 + languageName: node + linkType: hard + +"@swc/types@npm:^0.1.5": + version: 0.1.5 + resolution: "@swc/types@npm:0.1.5" + checksum: b35f93fe896a2240f6f10544e408f9648c2bd4bcff9bd8d022d9a6942d31cf859f86119fb0bbb04a12eefa1f6a6745ffc7d18f3a490d76d7b6a074a7c9608144 languageName: node linkType: hard @@ -10799,6 +10830,16 @@ __metadata: languageName: node linkType: hard +"jest_workaround@npm:^0.79.19": + version: 0.79.19 + resolution: "jest_workaround@npm:0.79.19" + peerDependencies: + "@swc/core": ^1.3.68 + "@swc/jest": ^0.2.26 + checksum: 387ce514e7ef60129891a4647e5431f1e4179bde70de100d50fa4acc8a4f3c072db9cf65c8a7d971ab11437ace78aa77959c65cdb2e55e718c971905c55e62fd + languageName: node + linkType: hard + "jju@npm:^1.4.0": version: 1.4.0 resolution: "jju@npm:1.4.0" @@ -11005,7 +11046,7 @@ __metadata: languageName: node linkType: hard -"jsonc-parser@npm:3.2.0, jsonc-parser@npm:^3.0.0": +"jsonc-parser@npm:3.2.0, jsonc-parser@npm:^3.0.0, jsonc-parser@npm:^3.2.0": version: 3.2.0 resolution: "jsonc-parser@npm:3.2.0" checksum: 5a12d4d04dad381852476872a29dcee03a57439574e4181d91dca71904fcdcc5e8e4706c0a68a2c61ad9810e1e1c5806b5100d52d3e727b78f5cdc595401045b From e22f3b9cc31315d965d8372eedd2a6df63438886 Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Fri, 3 Nov 2023 12:28:03 +0100 Subject: [PATCH 015/170] Fix generate-sandbox script --- scripts/tasks/sandbox.ts | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/scripts/tasks/sandbox.ts b/scripts/tasks/sandbox.ts index bf3e0bbae07f..58e7d92fe421 100644 --- a/scripts/tasks/sandbox.ts +++ b/scripts/tasks/sandbox.ts @@ -5,14 +5,6 @@ import { promisify } from 'util'; import dirSize from 'fast-folder-size'; import type { Task } from '../task'; import { now, saveBench } from '../bench/utils'; -import { - create, - install, - addStories, - extendMain, - init, - addExtraDependencies, -} from './sandbox-parts'; const logger = console; @@ -63,6 +55,10 @@ export const sandbox: Task = { await remove(details.sandboxDir); } + const { create, install, addStories, extendMain, init, addExtraDependencies } = await import( + './sandbox-parts' + ); + let startTime = now(); await create(details, options); const createTime = now() - startTime; From baa57e0fb9beb5bcc0ee009fe7126bf5608dc275 Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Fri, 3 Nov 2023 12:38:36 +0100 Subject: [PATCH 016/170] Remove ts-node in scripts --- .circleci/config.yml | 5 +- scripts/package.json | 3 +- scripts/prepare/esm-bundle.ts | 2 - scripts/prepare/facade.ts | 5 +- scripts/prepare/tsc.ts | 2 - scripts/tasks/sandbox-parts.ts | 3 +- scripts/tsconfig.json | 9 +-- scripts/yarn.lock | 134 +-------------------------------- 8 files changed, 10 insertions(+), 153 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index b7266a42c698..77b6e334b250 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -322,7 +322,7 @@ jobs: at: . - run: name: Starting Event Collector - command: yarn ts-node ./event-log-collector.ts + command: node --loader esbuild-register/loader -r esbuild-register ./event-log-collector.ts working_directory: scripts background: true - run: @@ -330,7 +330,7 @@ jobs: command: yarn task --task build --template $(yarn get-template --cadence << pipeline.parameters.workflow >> --task build) --no-link --start-from=never --junit - run: name: Verifying Telemetry - command: yarn ts-node ./event-log-checker build $(yarn get-template --cadence << pipeline.parameters.workflow >> --task build) + command: node --loader esbuild-register/loader -r esbuild-register ./event-log-checker build $(yarn get-template --cadence << pipeline.parameters.workflow >> --task build) working_directory: scripts - report-workflow-on-failure: template: $(yarn get-template --cadence << pipeline.parameters.workflow >> --task build) @@ -640,4 +640,3 @@ workflows: # parallelism: 4 # requires: # - create-sandboxes - diff --git a/scripts/package.json b/scripts/package.json index d1bd6e17fe99..3d316aac3671 100644 --- a/scripts/package.json +++ b/scripts/package.json @@ -33,7 +33,7 @@ "task": "node --loader esbuild-register/loader -r esbuild-register ./task.ts", "test": "jest --config ./jest.config.cjs", "upgrade": "node --loader esbuild-register/loader -r esbuild-register ./task.ts", - "upload-bench": "ts-node ./upload-bench.ts" + "upload-bench": "node --loader esbuild-register/loader -r esbuild-register ./upload-bench.ts" }, "husky": { "hooks": { @@ -188,7 +188,6 @@ "tiny-invariant": "^1.3.1", "trash": "^7.0.0", "ts-dedent": "^2.0.0", - "ts-node": "^10.9.1", "tsup": "^6.7.0", "type-fest": "~2.19", "typescript": "5.2.2", diff --git a/scripts/prepare/esm-bundle.ts b/scripts/prepare/esm-bundle.ts index e75ddc75b679..6ec3e434e4e9 100755 --- a/scripts/prepare/esm-bundle.ts +++ b/scripts/prepare/esm-bundle.ts @@ -1,5 +1,3 @@ -#!/usr/bin/env ../../node_modules/.bin/ts-node - import * as fs from 'fs-extra'; import path, { dirname, join, relative } from 'path'; import type { Options } from 'tsup'; diff --git a/scripts/prepare/facade.ts b/scripts/prepare/facade.ts index d43d47ef89a1..c5d6b793ea68 100755 --- a/scripts/prepare/facade.ts +++ b/scripts/prepare/facade.ts @@ -1,5 +1,3 @@ -#!/usr/bin/env ../../node_modules/.bin/ts-node - import { join, parse } from 'path'; import fs from 'fs-extra'; import dedent from 'ts-dedent'; @@ -18,10 +16,9 @@ const run = async ({ cwd, flags }: { cwd: string; flags: string[] }) => { } = await fs.readJson(join(cwd, 'package.json')); const optimized = hasFlag(flags, 'optimized'); - const tsnodePath = join(__dirname, '..', 'node_modules', '.bin', 'ts-node'); if (pre) { - await exec(`${tsnodePath} ${pre}`, { cwd }); + await exec(`node --loader esbuild-register/loader -r esbuild-register ${pre}`, { cwd }); } await Promise.all([ diff --git a/scripts/prepare/tsc.ts b/scripts/prepare/tsc.ts index cc248979ef70..62179c5b29ec 100755 --- a/scripts/prepare/tsc.ts +++ b/scripts/prepare/tsc.ts @@ -1,5 +1,3 @@ -#!/usr/bin/env ../../node_modules/.bin/ts-node - import { join } from 'path'; import fs, { move } from 'fs-extra'; import * as ts from 'typescript'; diff --git a/scripts/tasks/sandbox-parts.ts b/scripts/tasks/sandbox-parts.ts index f64c13c61fbc..81c137200e8a 100644 --- a/scripts/tasks/sandbox-parts.ts +++ b/scripts/tasks/sandbox-parts.ts @@ -581,7 +581,8 @@ async function prepareAngularSandbox(cwd: string) { packageJson.scripts = { ...packageJson.scripts, - 'docs:json': 'DIR=$PWD; cd ../../scripts; yarn ts-node combine-compodoc $DIR', + 'docs:json': + 'DIR=$PWD; cd ../../scripts; node --loader esbuild-register/loader -r esbuild-register combine-compodoc $DIR', storybook: `yarn docs:json && ${packageJson.scripts.storybook}`, 'build-storybook': `yarn docs:json && ${packageJson.scripts['build-storybook']}`, }; diff --git a/scripts/tsconfig.json b/scripts/tsconfig.json index 0817a4342434..9f5821bab723 100644 --- a/scripts/tsconfig.json +++ b/scripts/tsconfig.json @@ -25,12 +25,5 @@ "resolveJsonModule": true }, "exclude": ["dist", "**/dist", "node_modules", "**/node_modules"], - "include": ["./**/*", "./.eslintrc.js"], - "ts-node": { - "transpileOnly": true, - "files": true, - "compilerOptions": { - "types": ["node"] - } - } + "include": ["./**/*", "./.eslintrc.js"] } diff --git a/scripts/yarn.lock b/scripts/yarn.lock index fc179744fad1..ccef5c76b802 100644 --- a/scripts/yarn.lock +++ b/scripts/yarn.lock @@ -1680,15 +1680,6 @@ __metadata: languageName: node linkType: hard -"@cspotcode/source-map-support@npm:^0.8.0": - version: 0.8.1 - resolution: "@cspotcode/source-map-support@npm:0.8.1" - dependencies: - "@jridgewell/trace-mapping": "npm:0.3.9" - checksum: 05c5368c13b662ee4c122c7bfbe5dc0b613416672a829f3e78bc49a357a197e0218d6e74e7c66cfcd04e15a179acab080bd3c69658c9fbefd0e1ccd950a07fc6 - languageName: node - linkType: hard - "@emotion/css-prettifier@npm:^1.1.3": version: 1.1.3 resolution: "@emotion/css-prettifier@npm:1.1.3" @@ -2387,7 +2378,7 @@ __metadata: languageName: node linkType: hard -"@jridgewell/resolve-uri@npm:^3.0.3, @jridgewell/resolve-uri@npm:^3.1.0": +"@jridgewell/resolve-uri@npm:^3.1.0": version: 3.1.1 resolution: "@jridgewell/resolve-uri@npm:3.1.1" checksum: 0dbc9e29bc640bbbdc5b9876d2859c69042bfcf1423c1e6421bcca53e826660bff4e41c7d4bcb8dbea696404231a6f902f76ba41835d049e20f2dd6cffb713bf @@ -2408,16 +2399,6 @@ __metadata: languageName: node linkType: hard -"@jridgewell/trace-mapping@npm:0.3.9": - version: 0.3.9 - resolution: "@jridgewell/trace-mapping@npm:0.3.9" - dependencies: - "@jridgewell/resolve-uri": "npm:^3.0.3" - "@jridgewell/sourcemap-codec": "npm:^1.4.10" - checksum: fa425b606d7c7ee5bfa6a31a7b050dd5814b4082f318e0e4190f991902181b4330f43f4805db1dd4f2433fd0ed9cc7a7b9c2683f1deeab1df1b0a98b1e24055b - languageName: node - linkType: hard - "@jridgewell/trace-mapping@npm:^0.3.12, @jridgewell/trace-mapping@npm:^0.3.17, @jridgewell/trace-mapping@npm:^0.3.18, @jridgewell/trace-mapping@npm:^0.3.9": version: 0.3.19 resolution: "@jridgewell/trace-mapping@npm:0.3.19" @@ -3231,7 +3212,6 @@ __metadata: trash: "npm:^7.0.0" ts-dedent: "npm:^2.0.0" ts-loader: "npm:^9.4.2" - ts-node: "npm:^10.9.1" tsup: "npm:^6.7.0" type-fest: "npm:~2.19" typescript: "npm:5.2.2" @@ -3494,34 +3474,6 @@ __metadata: languageName: node linkType: hard -"@tsconfig/node10@npm:^1.0.7": - version: 1.0.9 - resolution: "@tsconfig/node10@npm:1.0.9" - checksum: c176a2c1e1b16be120c328300ea910df15fb9a5277010116d26818272341a11483c5a80059389d04edacf6fd2d03d4687ad3660870fdd1cc0b7109e160adb220 - languageName: node - linkType: hard - -"@tsconfig/node12@npm:^1.0.7": - version: 1.0.11 - resolution: "@tsconfig/node12@npm:1.0.11" - checksum: dddca2b553e2bee1308a056705103fc8304e42bb2d2cbd797b84403a223b25c78f2c683ec3e24a095e82cd435387c877239bffcb15a590ba817cd3f6b9a99fd9 - languageName: node - linkType: hard - -"@tsconfig/node14@npm:^1.0.0": - version: 1.0.3 - resolution: "@tsconfig/node14@npm:1.0.3" - checksum: 67c1316d065fdaa32525bc9449ff82c197c4c19092b9663b23213c8cbbf8d88b6ed6a17898e0cbc2711950fbfaf40388938c1c748a2ee89f7234fc9e7fe2bf44 - languageName: node - linkType: hard - -"@tsconfig/node16@npm:^1.0.2": - version: 1.0.4 - resolution: "@tsconfig/node16@npm:1.0.4" - checksum: 05f8f2734e266fb1839eb1d57290df1664fe2aa3b0fdd685a9035806daa635f7519bf6d5d9b33f6e69dd545b8c46bd6e2b5c79acb2b1f146e885f7f11a42a5bb - languageName: node - linkType: hard - "@types/aria-query@npm:^5.0.1": version: 5.0.1 resolution: "@types/aria-query@npm:5.0.1" @@ -4606,7 +4558,7 @@ __metadata: languageName: node linkType: hard -"acorn-walk@npm:^8.0.2, acorn-walk@npm:^8.1.1": +"acorn-walk@npm:^8.0.2": version: 8.2.0 resolution: "acorn-walk@npm:8.2.0" checksum: dbe92f5b2452c93e960c5594e666dd1fae141b965ff2cb4a1e1d0381e3e4db4274c5ce4ffa3d681a86ca2a8d4e29d5efc0670a08e23fd2800051ea387df56ca2 @@ -4622,7 +4574,7 @@ __metadata: languageName: node linkType: hard -"acorn@npm:^8.1.0, acorn@npm:^8.4.1, acorn@npm:^8.8.1, acorn@npm:^8.9.0": +"acorn@npm:^8.1.0, acorn@npm:^8.8.1, acorn@npm:^8.9.0": version: 8.10.0 resolution: "acorn@npm:8.10.0" bin: @@ -4855,13 +4807,6 @@ __metadata: languageName: node linkType: hard -"arg@npm:^4.1.0": - version: 4.1.3 - resolution: "arg@npm:4.1.3" - checksum: 070ff801a9d236a6caa647507bdcc7034530604844d64408149a26b9e87c2f97650055c0f049abd1efc024b334635c01f29e0b632b371ac3f26130f4cf65997a - languageName: node - linkType: hard - "argparse@npm:^1.0.7": version: 1.0.10 resolution: "argparse@npm:1.0.10" @@ -6308,13 +6253,6 @@ __metadata: languageName: node linkType: hard -"create-require@npm:^1.1.0": - version: 1.1.1 - resolution: "create-require@npm:1.1.1" - checksum: 157cbc59b2430ae9a90034a5f3a1b398b6738bf510f713edc4d4e45e169bc514d3d99dd34d8d01ca7ae7830b5b8b537e46ae8f3c8f932371b0875c0151d7ec91 - languageName: node - linkType: hard - "cross-env@npm:^7.0.3": version: 7.0.3 resolution: "cross-env@npm:7.0.3" @@ -6830,13 +6768,6 @@ __metadata: languageName: node linkType: hard -"diff@npm:^4.0.1": - version: 4.0.2 - resolution: "diff@npm:4.0.2" - checksum: 81b91f9d39c4eaca068eb0c1eb0e4afbdc5bb2941d197f513dd596b820b956fef43485876226d65d497bebc15666aa2aa82c679e84f65d5f2bfbf14ee46e32c1 - languageName: node - linkType: hard - "diff@npm:^5.0.0": version: 5.1.0 resolution: "diff@npm:5.1.0" @@ -11697,13 +11628,6 @@ __metadata: languageName: node linkType: hard -"make-error@npm:^1.1.1": - version: 1.3.6 - resolution: "make-error@npm:1.3.6" - checksum: 171e458d86854c6b3fc46610cfacf0b45149ba043782558c6875d9f42f222124384ad0b468c92e996d815a8a2003817a710c0a160e49c1c394626f76fa45396f - languageName: node - linkType: hard - "make-fetch-happen@npm:^11.0.3": version: 11.1.1 resolution: "make-fetch-happen@npm:11.1.1" @@ -16326,44 +16250,6 @@ __metadata: languageName: node linkType: hard -"ts-node@npm:^10.9.1": - version: 10.9.1 - resolution: "ts-node@npm:10.9.1" - dependencies: - "@cspotcode/source-map-support": "npm:^0.8.0" - "@tsconfig/node10": "npm:^1.0.7" - "@tsconfig/node12": "npm:^1.0.7" - "@tsconfig/node14": "npm:^1.0.0" - "@tsconfig/node16": "npm:^1.0.2" - acorn: "npm:^8.4.1" - acorn-walk: "npm:^8.1.1" - arg: "npm:^4.1.0" - create-require: "npm:^1.1.0" - diff: "npm:^4.0.1" - make-error: "npm:^1.1.1" - v8-compile-cache-lib: "npm:^3.0.1" - yn: "npm:3.1.1" - peerDependencies: - "@swc/core": ">=1.2.50" - "@swc/wasm": ">=1.2.50" - "@types/node": "*" - typescript: ">=2.7" - peerDependenciesMeta: - "@swc/core": - optional: true - "@swc/wasm": - optional: true - bin: - ts-node: dist/bin.js - ts-node-cwd: dist/bin-cwd.js - ts-node-esm: dist/bin-esm.js - ts-node-script: dist/bin-script.js - ts-node-transpile-only: dist/bin-transpile.js - ts-script: dist/bin-script-deprecated.js - checksum: 95187932fb83f3901e22546bd2feeac7d2feb4f412f42ac3a595f049a23e8dcf70516dffb51866391228ea2dbcfaea039e250fb2bb334d48a86ab2b6aea0ae2d - languageName: node - linkType: hard - "tsconfig-paths@npm:^3.14.2": version: 3.14.2 resolution: "tsconfig-paths@npm:3.14.2" @@ -17179,13 +17065,6 @@ __metadata: languageName: node linkType: hard -"v8-compile-cache-lib@npm:^3.0.1": - version: 3.0.1 - resolution: "v8-compile-cache-lib@npm:3.0.1" - checksum: bdc36fb8095d3b41df197f5fb6f11e3a26adf4059df3213e3baa93810d8f0cc76f9a74aaefc18b73e91fe7e19154ed6f134eda6fded2e0f1c8d2272ed2d2d391 - languageName: node - linkType: hard - "v8-compile-cache@npm:2.3.0": version: 2.3.0 resolution: "v8-compile-cache@npm:2.3.0" @@ -17944,13 +17823,6 @@ __metadata: languageName: node linkType: hard -"yn@npm:3.1.1": - version: 3.1.1 - resolution: "yn@npm:3.1.1" - checksum: 0732468dd7622ed8a274f640f191f3eaf1f39d5349a1b72836df484998d7d9807fbea094e2f5486d6b0cd2414aad5775972df0e68f8604db89a239f0f4bf7443 - languageName: node - linkType: hard - "yocto-queue@npm:^0.1.0": version: 0.1.0 resolution: "yocto-queue@npm:0.1.0" From 50a7d47121cbecdf475944bac720b576dc9e0400 Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Fri, 3 Nov 2023 13:41:03 +0100 Subject: [PATCH 017/170] Fix check script --- code/package.json | 8 +-- .../{check-package.cjs => check-package.ts} | 57 ++++++++++--------- scripts/package.json | 4 ++ 3 files changed, 37 insertions(+), 32 deletions(-) rename scripts/{check-package.cjs => check-package.ts} (70%) diff --git a/code/package.json b/code/package.json index 45e62b2406f9..c20521acc1fa 100644 --- a/code/package.json +++ b/code/package.json @@ -29,10 +29,10 @@ "build": "NODE_ENV=production yarn --cwd ../scripts build-package", "changelog": "pr-log --sloppy --cherry-pick", "changelog:next": "pr-log --sloppy --since-prerelease", - "check": "NODE_ENV=production node ../scripts/check-package.js", + "check": "NODE_ENV=production yarn --cwd ../scripts check-package", "ci-tests": "yarn task --task check --no-link --start-from=install && yarn lint && yarn test && cd ../scripts && yarn test", "danger": "danger", - "generate-sandboxes": "ts-node --swc ../scripts/sandbox/generate.ts", + "generate-sandboxes": "yarn --cwd ../scripts generate-sandboxes", "github-release": "github-release-from-changelog", "lint": "yarn lint:js && yarn lint:md", "lint:ejs": "ejslint **/*.ejs", @@ -41,8 +41,8 @@ "lint:md": "../scripts/node_modules/.bin/remark -q .", "lint:other": "prettier --write '**/*.{css,html,json,md,yml}'", "lint:package": "sort-package-json", - "local-registry": "ts-node --swc --project=../scripts/tsconfig.json ../scripts/run-registry.ts", - "publish-sandboxes": "ts-node --swc ../scripts/sandbox/publish.ts", + "local-registry": "yarn --cwd ../scripts local-registry", + "publish-sandboxes": "yarn --cwd ../scripts publish", "storybook:blocks": "STORYBOOK_BLOCKS_ONLY=true yarn storybook:ui", "storybook:blocks:build": "STORYBOOK_BLOCKS_ONLY=true yarn storybook:ui:build", "storybook:blocks:chromatic": "STORYBOOK_BLOCKS_ONLY=true yarn storybook:ui:chromatic --project-token=${CHROMATIC_TOKEN_STORYBOOK_BLOCKS:-MISSING_PROJECT_TOKEN}", diff --git a/scripts/check-package.cjs b/scripts/check-package.ts similarity index 70% rename from scripts/check-package.cjs rename to scripts/check-package.ts index 7fc8bc88f198..6248ad54797a 100644 --- a/scripts/check-package.cjs +++ b/scripts/check-package.ts @@ -1,38 +1,39 @@ -#!/usr/bin/env node - -/* eslint-disable global-require */ -const { resolve } = require('path'); -const { readJSON } = require('fs-extra'); - -const getStorybookPackages = async () => { - const workspaceJSON = await readJSON(resolve(__dirname, '..', 'code', 'workspace.json')); - return Object.entries(workspaceJSON.projects).map(([k, v]) => ({ - location: v.root, - name: k, - })); -}; +import { resolve } from 'path'; +import { readJSON } from 'fs-extra'; +import prompts from 'prompts'; +import program from 'commander'; +import chalk from 'chalk'; +import windowSize from 'window-size'; +import { execaCommand } from 'execa'; +import { getWorkspaces } from './utils/workspace'; async function run() { - const prompts = require('prompts'); - const program = require('commander'); - const chalk = require('chalk'); - - const packages = await getStorybookPackages(); + const packages = await getWorkspaces(); const packageTasks = packages - .map((package) => { + .map((pkg) => { return { - ...package, - suffix: package.name.replace('@storybook/', ''), + ...pkg, + suffix: pkg.name.replace('@storybook/', ''), defaultValue: false, - helpText: `check only the ${package.name} package`, + helpText: `check only the ${pkg.name} package`, }; }) .reduce((acc, next) => { acc[next.name] = next; return acc; - }, {}); + }, {} as Record); - const tasks = { + const tasks: Record< + string, + { + name: string; + defaultValue: boolean; + suffix: string; + helpText: string; + value?: any; + location?: string; + } + > = { watch: { name: `watch`, defaultValue: false, @@ -76,14 +77,15 @@ async function run() { name: 'todo', min: 1, hint: 'You can also run directly with package name like `yarn check core`, or `yarn check --all` for all packages!', - optionsPerPage: require('window-size').height - 3, // 3 lines for extra info + // @ts-expect-error @types incomplete + optionsPerPage: windowSize.height - 3, // 3 lines for extra info choices: packages.map(({ name: key }) => ({ value: key, title: tasks[key].name || key, selected: (tasks[key] && tasks[key].defaultValue) || false, })), }, - ]).then(({ mode, todo }) => { + ]).then(({ mode, todo }: { mode: boolean; todo: Array }) => { watchMode = mode; return todo?.map((key) => tasks[key]); }); @@ -96,9 +98,8 @@ async function run() { } selection?.filter(Boolean).forEach(async (v) => { - const commmand = (await readJSON(resolve(v.location, 'package.json'))).scripts.check; + const commmand = (await readJSON(resolve('../code', v.location, 'package.json'))).scripts.check; const cwd = resolve(__dirname, '..', 'code', v.location); - const { execaCommand } = await import('execa'); const sub = execaCommand(`${commmand}${watchMode ? ' --watch' : ''}`, { cwd, buffer: false, diff --git a/scripts/package.json b/scripts/package.json index 3d316aac3671..390c3ef0b141 100644 --- a/scripts/package.json +++ b/scripts/package.json @@ -6,14 +6,18 @@ "scripts": { "build-package": "node --loader esbuild-register/loader -r esbuild-register ./build-package.ts", "check": "node --loader esbuild-register/loader -r esbuild-register ./prepare/check-scripts.ts", + "check-package": "node --loader esbuild-register/loader -r esbuild-register ./check-package.ts", "docs:prettier:check": "cd ../docs && prettier --check ./snippets", "docs:prettier:write": "cd ../docs && prettier --write ./snippets", + "generate-sandboxes": "node --loader esbuild-register/loader -r esbuild-register ./sandbox/generate.ts", "get-report-message": "node --loader esbuild-register/loader -r esbuild-register ./get-report-message.ts", "get-template": "node --loader esbuild-register/loader -r esbuild-register ./get-template.ts", "lint": "yarn lint:js && yarn lint:md", "lint:js": "yarn lint:js:cmd . --quiet", "lint:js:cmd": "cross-env NODE_ENV=production eslint --cache --cache-location=../.cache/eslint --ext .js,.jsx,.json,.html,.ts,.tsx,.mjs --report-unused-disable-directives", "lint:package": "sort-package-json", + "local-registry": "node --loader esbuild-register/loader -r esbuild-register ./run-registry.ts", + "publish": "node --loader esbuild-register/loader -r esbuild-register ./sandbox/publish.ts", "release:cancel-preparation-runs": "node --loader esbuild-register/loader -r esbuild-register ./release/cancel-preparation-runs.ts", "release:ensure-next-ahead": "node --loader esbuild-register/loader -r esbuild-register ./release/ensure-next-ahead.ts", "release:generate-pr-description": "node --loader esbuild-register/loader -r esbuild-register ./release/generate-pr-description.ts", From c74b562aed2ad105276b956f49ba5a77e14184fe Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Fri, 3 Nov 2023 13:43:10 +0100 Subject: [PATCH 018/170] Fix run-registry script --- scripts/run-registry.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/scripts/run-registry.ts b/scripts/run-registry.ts index 8a7017b34fa1..71ae3dd334de 100755 --- a/scripts/run-registry.ts +++ b/scripts/run-registry.ts @@ -89,7 +89,10 @@ const publish = async (packages: { name: string; location: string }[], url: stri ); const tarballFilename = `${name.replace('@', '').replace('/', '-')}.tgz`; - const command = `cd ${location} && yarn pack --out=${PACKS_DIRECTORY}/${tarballFilename} && cd ${PACKS_DIRECTORY} && npm publish ./${tarballFilename} --registry ${url} --force --access restricted --ignore-scripts`; + const command = `cd ${path.resolve( + '../code', + location + )} && yarn pack --out=${PACKS_DIRECTORY}/${tarballFilename} && cd ${PACKS_DIRECTORY} && npm publish ./${tarballFilename} --registry ${url} --force --access restricted --ignore-scripts`; exec(command, (e) => { if (e) { rej(e); From 50e524ebd6c40b4600bc7faacc6f8853e364d2b3 Mon Sep 17 00:00:00 2001 From: Joe Vaughan <122215197+joevaugh4n@users.noreply.github.com> Date: Fri, 3 Nov 2023 13:51:05 +0000 Subject: [PATCH 019/170] Create help.yml --- .github/DISCUSSION_TEMPLATE/help.yml | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 .github/DISCUSSION_TEMPLATE/help.yml diff --git a/.github/DISCUSSION_TEMPLATE/help.yml b/.github/DISCUSSION_TEMPLATE/help.yml new file mode 100644 index 000000000000..0e72d0d84835 --- /dev/null +++ b/.github/DISCUSSION_TEMPLATE/help.yml @@ -0,0 +1,25 @@ +--- +body: + - type: textarea + attributes: + label: Summary + description: How do you need help? + placeholder: I need help with... + validations: + required: true + - type: textarea + attributes: + label: Additional information + description: Share your Storybook configuration (`main.js or ts`), any error messages, or relevant dependencies + render: js + validations: + required: false + - type: input + attributes: + label: Share an example + description: Help us debug your issue by creating a minimal reproduction. You can do this with StackBlitz by heading to https://storybook.new! + validations: + required: false + - type: markdown + attributes: null + value: Before submitting, consider adding relevant labels to your thread (e.g. 'react', 'vue', 'vite'). That makes it easier for other users to spot your request. Thanks! From 122e94f4addea4d0917ee2c9ab6f9d47ac2c9bd3 Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Mon, 6 Nov 2023 14:58:47 +0100 Subject: [PATCH 020/170] Fix Typescript issues --- scripts/dangerfile.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/dangerfile.ts b/scripts/dangerfile.ts index bd9bb6494602..6e3100736021 100644 --- a/scripts/dangerfile.ts +++ b/scripts/dangerfile.ts @@ -32,7 +32,7 @@ const checkRequiredLabels = (labels: string[]) => { const requiredLabels = flatten([ prLogConfig.skipLabels || [], - (prLogConfig.validLabels || []).map((keyVal: string) => keyVal[0]), + (prLogConfig.validLabels || []).map((keyVal) => keyVal[0]), ]); const blockingLabels = intersection(forbiddenLabels, labels); From 103794e3bb1b0e56bdb2ac0ae1257c0276163e5b Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Mon, 6 Nov 2023 14:59:01 +0100 Subject: [PATCH 021/170] Replace tsup with esbuild --- scripts/prepare/facade.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/prepare/facade.ts b/scripts/prepare/facade.ts index c5d6b793ea68..2a1a62d73b52 100755 --- a/scripts/prepare/facade.ts +++ b/scripts/prepare/facade.ts @@ -70,7 +70,7 @@ const run = async ({ cwd, flags }: { cwd: string; flags: string[] }) => { ]); if (pre) { - await exec(`${tsnodePath} ${post}`, { cwd }); + await exec(`node --loader esbuild-register/loader -r esbuild-register ${post}`, { cwd }); } }; From b9f0e4eef5af9b8b7c8e821bd3197034f4a55dfb Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Mon, 6 Nov 2023 15:19:58 +0100 Subject: [PATCH 022/170] Use node directly to check angular framework --- code/frameworks/angular/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/code/frameworks/angular/package.json b/code/frameworks/angular/package.json index 057073ce695f..b7072dd55452 100644 --- a/code/frameworks/angular/package.json +++ b/code/frameworks/angular/package.json @@ -33,7 +33,7 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/node_modules/.bin/tsc", + "check": "node ../../../scripts/node_modules/.bin/tsc", "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/tsc.ts" }, "dependencies": { From 29f5388958746fa1363d545bcb4302777e49ecd9 Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Mon, 6 Nov 2023 15:20:13 +0100 Subject: [PATCH 023/170] Fix sandbox generation --- code/package.json | 2 +- package.json | 2 +- scripts/tasks/sandbox.ts | 7 ++++--- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/code/package.json b/code/package.json index c20521acc1fa..9241403005c9 100644 --- a/code/package.json +++ b/code/package.json @@ -49,7 +49,7 @@ "storybook:ui": "NODE_OPTIONS=\"--preserve-symlinks --preserve-symlinks-main\" ./lib/cli/bin/index.js dev --port 6006 --config-dir ./ui/.storybook", "storybook:ui:build": "NODE_OPTIONS=\"--preserve-symlinks --preserve-symlinks-main\" ./lib/cli/bin/index.js build --config-dir ./ui/.storybook", "storybook:ui:chromatic": "yarn chromatic --build-script-name storybook:ui:build --storybook-config-dir ./ui/.storybook --storybook-base-dir ./code --project-token=${CHROMATIC_TOKEN_STORYBOOK_UI:-MISSING_PROJECT_TOKEN} --only-changed --exit-zero-on-changes --exit-once-uploaded", - "task": "cd .. && yarn task", + "task": "yarn --cwd ../scripts task", "test": "NODE_OPTIONS=--max_old_space_size=4096 jest --config ./jest.config.js", "test:cli": "npm --prefix lib/cli run test" }, diff --git a/package.json b/package.json index 7564dbbfd79f..3e7e7cadb807 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,7 @@ "nx": "cd code; yarn nx", "pretty-docs": "cd scripts; yarn install >/dev/null; yarn docs:prettier:write", "start": "yarn task --task dev --template react-vite/default-ts --start-from=install", - "task": "echo 'Installing Script Dependencies...'; cd scripts; yarn install >/dev/null; yarn task", + "task": "echo 'Installing Script Dependencies...'; cd scripts; yarn install >/dev/null; cd ..; yarn --cwd=./scripts task", "test": "cd code; yarn test", "upload-bench": "cd scripts; yarn upload-bench" }, diff --git a/scripts/tasks/sandbox.ts b/scripts/tasks/sandbox.ts index 58e7d92fe421..5e3bade5d5d3 100644 --- a/scripts/tasks/sandbox.ts +++ b/scripts/tasks/sandbox.ts @@ -55,9 +55,10 @@ export const sandbox: Task = { await remove(details.sandboxDir); } - const { create, install, addStories, extendMain, init, addExtraDependencies } = await import( - './sandbox-parts' - ); + const { create, install, addStories, extendMain, init, addExtraDependencies } = + // @ts-expect-error esbuild for some reason exports a default object + // eslint-disable-next-line import/extensions + (await import('./sandbox-parts.ts')).default; let startTime = now(); await create(details, options); From 55dc4f21713ff708c20cacd6457b9b5129d82145 Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Tue, 7 Nov 2023 09:50:44 +0100 Subject: [PATCH 024/170] Use esMain helper to check for execution origin --- scripts/combine-compodoc.ts | 5 +-- scripts/event-log-checker.ts | 5 +-- scripts/get-report-message.ts | 5 +-- scripts/get-template.ts | 5 +-- scripts/release/cancel-preparation-runs.ts | 5 +-- scripts/release/ensure-next-ahead.ts | 5 +-- scripts/release/generate-pr-description.ts | 5 +-- scripts/release/get-changelog-from-file.ts | 5 +-- scripts/release/get-current-version.ts | 5 +-- scripts/release/get-version-changelog.ts | 5 +-- scripts/release/is-pr-frozen.ts | 5 +-- scripts/release/is-prerelease.ts | 5 +-- scripts/release/is-version-published.ts | 5 +-- scripts/release/label-patches.ts | 5 +-- scripts/release/pick-patches.ts | 5 +-- scripts/release/publish.ts | 5 +-- scripts/release/unreleased-changes-exists.ts | 5 +-- scripts/release/version.ts | 5 +-- scripts/release/write-changelog.ts | 5 +-- scripts/sandbox/generate.ts | 5 +-- scripts/utils/esmain.ts | 40 ++++++++++++++++++++ 21 files changed, 80 insertions(+), 60 deletions(-) create mode 100644 scripts/utils/esmain.ts diff --git a/scripts/combine-compodoc.ts b/scripts/combine-compodoc.ts index 0a4472edb7bc..251a5d88f50a 100755 --- a/scripts/combine-compodoc.ts +++ b/scripts/combine-compodoc.ts @@ -6,7 +6,7 @@ import { join, resolve } from 'path'; import { realpath, readFile, writeFile, lstat } from 'fs-extra'; import { globSync } from 'glob'; import { directory } from 'tempy'; -import url from 'url'; +import esMain from './utils/esmain'; import { execaCommand } from './utils/exec'; const logger = console; @@ -68,8 +68,7 @@ async function run(cwd: string) { await writeFile(join(cwd, 'documentation.json'), JSON.stringify(documentation)); } -const modulePath = url.fileURLToPath(import.meta.url); -if (process.argv[1] === modulePath) { +if (esMain(import.meta.url)) { run(resolve(process.argv[2])) .then(() => process.exit(0)) .catch((err) => { diff --git a/scripts/event-log-checker.ts b/scripts/event-log-checker.ts index 4f418bffde9e..2ffc395858e7 100644 --- a/scripts/event-log-checker.ts +++ b/scripts/event-log-checker.ts @@ -2,7 +2,7 @@ import chalk from 'chalk'; import assert from 'assert'; import fetch from 'node-fetch'; -import url from 'url'; +import esMain from './utils/esmain'; import { allTemplates } from '../code/lib/cli/src/sandbox-templates'; import versions from '../code/lib/cli/src/versions'; import { oneWayHash } from '../code/lib/telemetry/src/one-way-hash'; @@ -115,8 +115,7 @@ async function run() { export {}; -const modulePath = url.fileURLToPath(import.meta.url); -if (process.argv[1] === modulePath) { +if (esMain(import.meta)) { run() .then(() => process.exit(0)) .catch((err) => { diff --git a/scripts/get-report-message.ts b/scripts/get-report-message.ts index 170938cbde0a..ce67a50f29cf 100644 --- a/scripts/get-report-message.ts +++ b/scripts/get-report-message.ts @@ -1,7 +1,7 @@ /* eslint-disable no-console */ import { readJson } from 'fs-extra'; import { join } from 'path'; -import url from 'url'; +import esMain from './utils/esmain'; import { CODE_DIRECTORY } from './utils/constants'; import { execaCommand } from './utils/exec'; @@ -64,8 +64,7 @@ async function run() { console.log(`${title}${body}${footer}`.replace(/\n/g, '\\n')); } -const modulePath = url.fileURLToPath(import.meta.url); -if (process.argv[1] === modulePath) { +if (esMain(import.meta)) { run().catch((err) => { console.error(err); process.exit(1); diff --git a/scripts/get-template.ts b/scripts/get-template.ts index 5c4b43ad0cb2..7da650b41c90 100644 --- a/scripts/get-template.ts +++ b/scripts/get-template.ts @@ -4,7 +4,7 @@ import { program } from 'commander'; import dedent from 'ts-dedent'; import chalk from 'chalk'; import yaml from 'yaml'; -import url from 'url'; +import esMain from './utils/esmain'; import { allTemplates, templatesByCadence, @@ -180,8 +180,7 @@ async function run({ cadence, task, check }: RunOptions) { ); } -const modulePath = url.fileURLToPath(import.meta.url); -if (process.argv[1] === modulePath) { +if (esMain(import.meta)) { program .description('Retrieve the template to run for a given cadence and task') .option('--cadence ', 'Which cadence you want to run the script for') diff --git a/scripts/release/cancel-preparation-runs.ts b/scripts/release/cancel-preparation-runs.ts index 9253f12041c5..529f096fcbb0 100644 --- a/scripts/release/cancel-preparation-runs.ts +++ b/scripts/release/cancel-preparation-runs.ts @@ -6,7 +6,7 @@ import chalk from 'chalk'; import program from 'commander'; import dedent from 'ts-dedent'; -import url from 'url'; +import esMain from '../utils/esmain'; import { githubRestClient } from './utils/github-client'; program @@ -100,8 +100,7 @@ export const run = async () => { } }; -const modulePath = url.fileURLToPath(import.meta.url); -if (process.argv[1] === modulePath) { +if (esMain(import.meta)) { run().catch((err) => { console.error(err); // this is non-critical work, so we don't want to fail the CI build if this fails diff --git a/scripts/release/ensure-next-ahead.ts b/scripts/release/ensure-next-ahead.ts index 2deae1bee36e..bf861ce46163 100644 --- a/scripts/release/ensure-next-ahead.ts +++ b/scripts/release/ensure-next-ahead.ts @@ -14,7 +14,7 @@ import program from 'commander'; import semver from 'semver'; import { z } from 'zod'; import { readJson } from 'fs-extra'; -import url from 'url'; +import esMain from '../utils/esmain'; import { run as bumpVersion } from './version'; import { git } from './utils/git-client'; @@ -93,8 +93,7 @@ export const run = async (options: unknown) => { ); }; -const modulePath = url.fileURLToPath(import.meta.url); -if (process.argv[1] === modulePath) { +if (esMain(import.meta)) { const parsed = program.parse(); run(parsed.opts()).catch((err) => { console.error(err); diff --git a/scripts/release/generate-pr-description.ts b/scripts/release/generate-pr-description.ts index a62c586db867..065a3cf2adee 100644 --- a/scripts/release/generate-pr-description.ts +++ b/scripts/release/generate-pr-description.ts @@ -5,7 +5,7 @@ import { z } from 'zod'; import dedent from 'ts-dedent'; import semver from 'semver'; import { setOutput } from '@actions/core'; -import url from 'url'; +import esMain from '../utils/esmain'; import type { Change } from './utils/get-changes'; import { getChanges, LABELS_BY_IMPORTANCE, RELEASED_LABELS } from './utils/get-changes'; import { getCurrentVersion } from './get-current-version'; @@ -296,8 +296,7 @@ export const run = async (rawOptions: unknown) => { } }; -const modulePath = url.fileURLToPath(import.meta.url); -if (process.argv[1] === modulePath) { +if (esMain(import.meta)) { const parsed = program.parse(); run(parsed.opts()).catch((err) => { console.error(err); diff --git a/scripts/release/get-changelog-from-file.ts b/scripts/release/get-changelog-from-file.ts index 7a5ea3ecaddd..264e8d6ebec7 100644 --- a/scripts/release/get-changelog-from-file.ts +++ b/scripts/release/get-changelog-from-file.ts @@ -6,7 +6,7 @@ import { readFile } from 'fs-extra'; import path from 'path'; import semver from 'semver'; import dedent from 'ts-dedent'; -import url from 'url'; +import esMain from '../utils/esmain'; import { getCurrentVersion } from './get-current-version'; program @@ -55,8 +55,7 @@ export const getChangelogFromFile = async (args: { return result; }; -const modulePath = url.fileURLToPath(import.meta.url); -if (process.argv[1] === modulePath) { +if (esMain(import.meta)) { const parsed = program.parse(); getChangelogFromFile({ version: parsed.args[0], diff --git a/scripts/release/get-current-version.ts b/scripts/release/get-current-version.ts index df91678f9c44..6012b70eff19 100644 --- a/scripts/release/get-current-version.ts +++ b/scripts/release/get-current-version.ts @@ -3,7 +3,7 @@ import chalk from 'chalk'; import { setOutput } from '@actions/core'; import path from 'path'; import { readJson } from 'fs-extra'; -import url from 'url'; +import esMain from '../utils/esmain'; const CODE_DIR_PATH = path.join(__dirname, '..', '..', 'code'); const CODE_PACKAGE_JSON_PATH = path.join(CODE_DIR_PATH, 'package.json'); @@ -18,8 +18,7 @@ export const getCurrentVersion = async () => { return version; }; -const modulePath = url.fileURLToPath(import.meta.url); -if (process.argv[1] === modulePath) { +if (esMain(import.meta)) { getCurrentVersion().catch((err) => { console.error(err); process.exit(1); diff --git a/scripts/release/get-version-changelog.ts b/scripts/release/get-version-changelog.ts index c70ec902bb0d..93a927ff7579 100644 --- a/scripts/release/get-version-changelog.ts +++ b/scripts/release/get-version-changelog.ts @@ -2,7 +2,7 @@ import { setOutput } from '@actions/core'; import chalk from 'chalk'; import { program } from 'commander'; -import url from 'url'; +import esMain from '../utils/esmain'; import { getCurrentVersion } from './get-current-version'; import { getChanges } from './utils/get-changes'; @@ -27,8 +27,7 @@ export const getVersionChangelog = async (args: { version?: string; verbose?: bo return changelogText; }; -const modulePath = url.fileURLToPath(import.meta.url); -if (process.argv[1] === modulePath) { +if (esMain(import.meta)) { const parsed = program.parse(); getVersionChangelog({ version: parsed.args[0], verbose: parsed.opts().verbose }).catch((err) => { console.error(err); diff --git a/scripts/release/is-pr-frozen.ts b/scripts/release/is-pr-frozen.ts index d2e774b82cb7..2379bcd497be 100644 --- a/scripts/release/is-pr-frozen.ts +++ b/scripts/release/is-pr-frozen.ts @@ -4,7 +4,7 @@ import program from 'commander'; import { setOutput } from '@actions/core'; import path from 'path'; import { readJson } from 'fs-extra'; -import url from 'url'; +import esMain from '../utils/esmain'; import { getPullInfoFromCommit } from './utils/get-github-info'; import { git } from './utils/git-client'; @@ -99,8 +99,7 @@ export const run = async (options: unknown) => { return isFrozen; }; -const modulePath = url.fileURLToPath(import.meta.url); -if (process.argv[1] === modulePath) { +if (esMain(import.meta)) { const parsed = program.parse(); run(parsed.opts()).catch((err) => { console.error(err); diff --git a/scripts/release/is-prerelease.ts b/scripts/release/is-prerelease.ts index ab9606073de6..5a5424d5a8b0 100644 --- a/scripts/release/is-prerelease.ts +++ b/scripts/release/is-prerelease.ts @@ -3,7 +3,7 @@ import chalk from 'chalk'; import program from 'commander'; import { setOutput } from '@actions/core'; import semver from 'semver'; -import url from 'url'; +import esMain from '../utils/esmain'; import { getCurrentVersion } from './get-current-version'; program @@ -39,8 +39,7 @@ export const isPrerelease = async (args: { version?: string; verbose?: boolean } return result; }; -const modulePath = url.fileURLToPath(import.meta.url); -if (process.argv[1] === modulePath) { +if (esMain(import.meta)) { const parsed = program.parse(); isPrerelease({ version: parsed.args[0], diff --git a/scripts/release/is-version-published.ts b/scripts/release/is-version-published.ts index a0b97d1a155c..e24ca5594953 100644 --- a/scripts/release/is-version-published.ts +++ b/scripts/release/is-version-published.ts @@ -3,7 +3,7 @@ import chalk from 'chalk'; import program from 'commander'; import { setOutput } from '@actions/core'; import fetch from 'node-fetch'; -import url from 'url'; +import esMain from '../utils/esmain'; import { getCurrentVersion } from './get-current-version'; program @@ -78,8 +78,7 @@ export const run = async (args: unknown[], options: unknown) => { return isAlreadyPublished; }; -const modulePath = url.fileURLToPath(import.meta.url); -if (process.argv[1] === modulePath) { +if (esMain(import.meta)) { const parsed = program.parse(); run(parsed.args, parsed.opts()).catch((err) => { console.error(err); diff --git a/scripts/release/label-patches.ts b/scripts/release/label-patches.ts index a23fbfe07a3e..43d110d25612 100644 --- a/scripts/release/label-patches.ts +++ b/scripts/release/label-patches.ts @@ -1,7 +1,7 @@ import program from 'commander'; import { v4 as uuidv4 } from 'uuid'; import ora from 'ora'; -import url from 'url'; +import esMain from '../utils/esmain'; import { getLabelIds, githubGraphQlClient, getUnpickedPRs } from './utils/github-client'; import { getPullInfoFromCommits, getRepo } from './utils/get-changes'; import { getLatestTag, git } from './utils/git-client'; @@ -94,8 +94,7 @@ export const run = async (options: unknown) => { } }; -const modulePath = url.fileURLToPath(import.meta.url); -if (process.argv[1] === modulePath) { +if (esMain(import.meta)) { const options = program.parse().opts(); run(options).catch((err) => { console.error(err); diff --git a/scripts/release/pick-patches.ts b/scripts/release/pick-patches.ts index cfaaf9693771..595ab58f425f 100644 --- a/scripts/release/pick-patches.ts +++ b/scripts/release/pick-patches.ts @@ -5,7 +5,7 @@ import chalk from 'chalk'; import ora from 'ora'; import { setOutput } from '@actions/core'; import invariant from 'tiny-invariant'; -import url from 'url'; +import esMain from '../utils/esmain'; import { git } from './utils/git-client'; import { getUnpickedPRs } from './utils/github-client'; @@ -86,8 +86,7 @@ export const run = async (_: unknown) => { } }; -const modulePath = url.fileURLToPath(import.meta.url); -if (process.argv[1] === modulePath) { +if (esMain(import.meta)) { const options = program.parse(process.argv); run(options).catch((err) => { console.error(err); diff --git a/scripts/release/publish.ts b/scripts/release/publish.ts index 82b01c552e9b..8573e368f4e2 100644 --- a/scripts/release/publish.ts +++ b/scripts/release/publish.ts @@ -8,7 +8,7 @@ import { readJson } from 'fs-extra'; import fetch from 'node-fetch'; import dedent from 'ts-dedent'; import pRetry from 'p-retry'; -import url from 'url'; +import esMain from '../utils/esmain'; import { execaCommand } from '../utils/exec'; program @@ -190,8 +190,7 @@ export const run = async (options: unknown) => { ); }; -const modulePath = url.fileURLToPath(import.meta.url); -if (process.argv[1] === modulePath) { +if (esMain(import.meta)) { const parsed = program.parse(); run(parsed.opts()).catch((err) => { console.error(err); diff --git a/scripts/release/unreleased-changes-exists.ts b/scripts/release/unreleased-changes-exists.ts index c0cd5260d59b..5c8978f979a3 100644 --- a/scripts/release/unreleased-changes-exists.ts +++ b/scripts/release/unreleased-changes-exists.ts @@ -4,7 +4,7 @@ import program from 'commander'; import { z } from 'zod'; import { setOutput } from '@actions/core'; import { intersection } from 'lodash'; -import url from 'url'; +import esMain from '../utils/esmain'; import type { Change } from './utils/get-changes'; import { RELEASED_LABELS, getChanges } from './utils/get-changes'; import { getCurrentVersion } from './get-current-version'; @@ -78,8 +78,7 @@ ${chalk.blue(changesToRelease.map(({ title, pull }) => ` #${pull}: ${title}`).j return { changesToRelease, hasChangesToRelease }; }; -const modulePath = url.fileURLToPath(import.meta.url); -if (process.argv[1] === modulePath) { +if (esMain(import.meta)) { const parsed = program.parse(); run(parsed.opts()).catch((err) => { console.error(err); diff --git a/scripts/release/version.ts b/scripts/release/version.ts index da9e7894d050..592826104539 100644 --- a/scripts/release/version.ts +++ b/scripts/release/version.ts @@ -6,7 +6,7 @@ import path from 'path'; import program from 'commander'; import semver from 'semver'; import { z } from 'zod'; -import url from 'url'; +import esMain from '../utils/esmain'; import type { Workspace } from '../utils/workspace'; import { getWorkspaces } from '../utils/workspace'; import { execaCommand } from '../utils/exec'; @@ -294,8 +294,7 @@ export const run = async (options: unknown) => { } }; -const modulePath = url.fileURLToPath(import.meta.url); -if (process.argv[1] === modulePath) { +if (esMain(import.meta)) { const options = program.parse().opts(); run(options).catch((err) => { console.error(err); diff --git a/scripts/release/write-changelog.ts b/scripts/release/write-changelog.ts index a353309b65af..2f80d381ef49 100644 --- a/scripts/release/write-changelog.ts +++ b/scripts/release/write-changelog.ts @@ -5,7 +5,7 @@ import program from 'commander'; import semver from 'semver'; import { z } from 'zod'; import { readFile, writeFile, writeJson } from 'fs-extra'; -import url from 'url'; +import esMain from '../utils/esmain'; import { getChanges } from './utils/get-changes'; program @@ -133,8 +133,7 @@ export const run = async (args: unknown[], options: unknown) => { console.log(`āœ… Wrote Changelog to file`); }; -const modulePath = url.fileURLToPath(import.meta.url); -if (process.argv[1] === modulePath) { +if (esMain(import.meta)) { const parsed = program.parse(); run(parsed.args, parsed.opts()).catch((err) => { console.error(err); diff --git a/scripts/sandbox/generate.ts b/scripts/sandbox/generate.ts index 229df395bbb3..5c2ab47d0971 100755 --- a/scripts/sandbox/generate.ts +++ b/scripts/sandbox/generate.ts @@ -6,7 +6,7 @@ import prettyTime from 'pretty-hrtime'; import { copy, emptyDir, ensureDir, move, remove, rename, writeFile } from 'fs-extra'; import { program } from 'commander'; import { directory } from 'tempy'; -import url from 'url'; +import esMain from '../utils/esmain'; import { execaCommand } from '../utils/exec'; import type { OptionValues } from '../utils/options'; @@ -251,8 +251,7 @@ export const generate = async ({ await runGenerators(generatorConfigs, localRegistry, debug); }; -const modulePath = url.fileURLToPath(import.meta.url); -if (process.argv[1] === modulePath) { +if (esMain(import.meta)) { program .description('Generate sandboxes from a set of possible templates') .option('--templates [templates...]', 'Space-delimited list of templates to include') diff --git a/scripts/utils/esmain.ts b/scripts/utils/esmain.ts new file mode 100644 index 000000000000..286f8b250276 --- /dev/null +++ b/scripts/utils/esmain.ts @@ -0,0 +1,40 @@ +import path from 'path'; +import process from 'process'; +import { createRequire } from 'module'; +import { fileURLToPath } from 'url'; + +/** + * Strip the extension from a filename if it has one. + * @param {string} name A filename. + * @return {string} The filename without a path. + */ +export function stripExt(name: string) { + const extension = path.extname(name); + if (!extension) { + return name; + } + + return name.slice(0, -extension.length); +} + +/** + * Check if a module was run directly with node as opposed to being + * imported from another module. + */ +export default function esMain(url: string) { + if (!url || !process.argv[1]) { + return false; + } + + const require = createRequire(url); + const scriptPath = require.resolve(process.argv[1]); + + const modulePath = fileURLToPath(url); + + const extension = path.extname(scriptPath); + if (extension) { + return modulePath === scriptPath; + } + + return stripExt(modulePath) === scriptPath; +} From 40e627f8b461ea3865f1b91350c17c231affcb16 Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Tue, 7 Nov 2023 09:51:08 +0100 Subject: [PATCH 025/170] Add import for execa package in combine-compodoc.ts --- scripts/combine-compodoc.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/combine-compodoc.ts b/scripts/combine-compodoc.ts index 251a5d88f50a..3eaad97df6d0 100755 --- a/scripts/combine-compodoc.ts +++ b/scripts/combine-compodoc.ts @@ -6,8 +6,8 @@ import { join, resolve } from 'path'; import { realpath, readFile, writeFile, lstat } from 'fs-extra'; import { globSync } from 'glob'; import { directory } from 'tempy'; +import { execaCommand } from 'execa'; import esMain from './utils/esmain'; -import { execaCommand } from './utils/exec'; const logger = console; From 25b69072d225fd4383d116ddf4d4daa994db7bf4 Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Tue, 7 Nov 2023 14:30:03 +0100 Subject: [PATCH 026/170] Fix esMain helper usage --- scripts/event-log-checker.ts | 2 +- scripts/get-report-message.ts | 2 +- scripts/get-template.ts | 2 +- scripts/release/cancel-preparation-runs.ts | 2 +- scripts/release/ensure-next-ahead.ts | 2 +- scripts/release/generate-pr-description.ts | 2 +- scripts/release/get-changelog-from-file.ts | 2 +- scripts/release/get-current-version.ts | 2 +- scripts/release/get-version-changelog.ts | 2 +- scripts/release/is-pr-frozen.ts | 2 +- scripts/release/is-prerelease.ts | 2 +- scripts/release/is-version-published.ts | 2 +- scripts/release/label-patches.ts | 2 +- scripts/release/pick-patches.ts | 2 +- scripts/release/publish.ts | 2 +- scripts/release/unreleased-changes-exists.ts | 2 +- scripts/release/version.ts | 2 +- scripts/release/write-changelog.ts | 2 +- scripts/sandbox/generate.ts | 2 +- 19 files changed, 19 insertions(+), 19 deletions(-) diff --git a/scripts/event-log-checker.ts b/scripts/event-log-checker.ts index 2ffc395858e7..d480ccd1a0cd 100644 --- a/scripts/event-log-checker.ts +++ b/scripts/event-log-checker.ts @@ -115,7 +115,7 @@ async function run() { export {}; -if (esMain(import.meta)) { +if (esMain(import.meta.url)) { run() .then(() => process.exit(0)) .catch((err) => { diff --git a/scripts/get-report-message.ts b/scripts/get-report-message.ts index ce67a50f29cf..75df6ba066fc 100644 --- a/scripts/get-report-message.ts +++ b/scripts/get-report-message.ts @@ -64,7 +64,7 @@ async function run() { console.log(`${title}${body}${footer}`.replace(/\n/g, '\\n')); } -if (esMain(import.meta)) { +if (esMain(import.meta.url)) { run().catch((err) => { console.error(err); process.exit(1); diff --git a/scripts/get-template.ts b/scripts/get-template.ts index 7da650b41c90..0b54568b3143 100644 --- a/scripts/get-template.ts +++ b/scripts/get-template.ts @@ -180,7 +180,7 @@ async function run({ cadence, task, check }: RunOptions) { ); } -if (esMain(import.meta)) { +if (esMain(import.meta.url)) { program .description('Retrieve the template to run for a given cadence and task') .option('--cadence ', 'Which cadence you want to run the script for') diff --git a/scripts/release/cancel-preparation-runs.ts b/scripts/release/cancel-preparation-runs.ts index 529f096fcbb0..811de60bfa52 100644 --- a/scripts/release/cancel-preparation-runs.ts +++ b/scripts/release/cancel-preparation-runs.ts @@ -100,7 +100,7 @@ export const run = async () => { } }; -if (esMain(import.meta)) { +if (esMain(import.meta.url)) { run().catch((err) => { console.error(err); // this is non-critical work, so we don't want to fail the CI build if this fails diff --git a/scripts/release/ensure-next-ahead.ts b/scripts/release/ensure-next-ahead.ts index bf861ce46163..4bc4bfbab35b 100644 --- a/scripts/release/ensure-next-ahead.ts +++ b/scripts/release/ensure-next-ahead.ts @@ -93,7 +93,7 @@ export const run = async (options: unknown) => { ); }; -if (esMain(import.meta)) { +if (esMain(import.meta.url)) { const parsed = program.parse(); run(parsed.opts()).catch((err) => { console.error(err); diff --git a/scripts/release/generate-pr-description.ts b/scripts/release/generate-pr-description.ts index 065a3cf2adee..31bcc3c63c1a 100644 --- a/scripts/release/generate-pr-description.ts +++ b/scripts/release/generate-pr-description.ts @@ -296,7 +296,7 @@ export const run = async (rawOptions: unknown) => { } }; -if (esMain(import.meta)) { +if (esMain(import.meta.url)) { const parsed = program.parse(); run(parsed.opts()).catch((err) => { console.error(err); diff --git a/scripts/release/get-changelog-from-file.ts b/scripts/release/get-changelog-from-file.ts index 264e8d6ebec7..62a248f06d97 100644 --- a/scripts/release/get-changelog-from-file.ts +++ b/scripts/release/get-changelog-from-file.ts @@ -55,7 +55,7 @@ export const getChangelogFromFile = async (args: { return result; }; -if (esMain(import.meta)) { +if (esMain(import.meta.url)) { const parsed = program.parse(); getChangelogFromFile({ version: parsed.args[0], diff --git a/scripts/release/get-current-version.ts b/scripts/release/get-current-version.ts index 6012b70eff19..7fa283d4f08e 100644 --- a/scripts/release/get-current-version.ts +++ b/scripts/release/get-current-version.ts @@ -18,7 +18,7 @@ export const getCurrentVersion = async () => { return version; }; -if (esMain(import.meta)) { +if (esMain(import.meta.url)) { getCurrentVersion().catch((err) => { console.error(err); process.exit(1); diff --git a/scripts/release/get-version-changelog.ts b/scripts/release/get-version-changelog.ts index 93a927ff7579..a3c6e645f793 100644 --- a/scripts/release/get-version-changelog.ts +++ b/scripts/release/get-version-changelog.ts @@ -27,7 +27,7 @@ export const getVersionChangelog = async (args: { version?: string; verbose?: bo return changelogText; }; -if (esMain(import.meta)) { +if (esMain(import.meta.url)) { const parsed = program.parse(); getVersionChangelog({ version: parsed.args[0], verbose: parsed.opts().verbose }).catch((err) => { console.error(err); diff --git a/scripts/release/is-pr-frozen.ts b/scripts/release/is-pr-frozen.ts index 2379bcd497be..2eb52528dda7 100644 --- a/scripts/release/is-pr-frozen.ts +++ b/scripts/release/is-pr-frozen.ts @@ -99,7 +99,7 @@ export const run = async (options: unknown) => { return isFrozen; }; -if (esMain(import.meta)) { +if (esMain(import.meta.url)) { const parsed = program.parse(); run(parsed.opts()).catch((err) => { console.error(err); diff --git a/scripts/release/is-prerelease.ts b/scripts/release/is-prerelease.ts index 5a5424d5a8b0..ef15bf6c40b2 100644 --- a/scripts/release/is-prerelease.ts +++ b/scripts/release/is-prerelease.ts @@ -39,7 +39,7 @@ export const isPrerelease = async (args: { version?: string; verbose?: boolean } return result; }; -if (esMain(import.meta)) { +if (esMain(import.meta.url)) { const parsed = program.parse(); isPrerelease({ version: parsed.args[0], diff --git a/scripts/release/is-version-published.ts b/scripts/release/is-version-published.ts index e24ca5594953..6a57efa92d55 100644 --- a/scripts/release/is-version-published.ts +++ b/scripts/release/is-version-published.ts @@ -78,7 +78,7 @@ export const run = async (args: unknown[], options: unknown) => { return isAlreadyPublished; }; -if (esMain(import.meta)) { +if (esMain(import.meta.url)) { const parsed = program.parse(); run(parsed.args, parsed.opts()).catch((err) => { console.error(err); diff --git a/scripts/release/label-patches.ts b/scripts/release/label-patches.ts index 43d110d25612..68572d45c87c 100644 --- a/scripts/release/label-patches.ts +++ b/scripts/release/label-patches.ts @@ -94,7 +94,7 @@ export const run = async (options: unknown) => { } }; -if (esMain(import.meta)) { +if (esMain(import.meta.url)) { const options = program.parse().opts(); run(options).catch((err) => { console.error(err); diff --git a/scripts/release/pick-patches.ts b/scripts/release/pick-patches.ts index 595ab58f425f..9bdbf53977ec 100644 --- a/scripts/release/pick-patches.ts +++ b/scripts/release/pick-patches.ts @@ -86,7 +86,7 @@ export const run = async (_: unknown) => { } }; -if (esMain(import.meta)) { +if (esMain(import.meta.url)) { const options = program.parse(process.argv); run(options).catch((err) => { console.error(err); diff --git a/scripts/release/publish.ts b/scripts/release/publish.ts index 8573e368f4e2..32c1b57c5b26 100644 --- a/scripts/release/publish.ts +++ b/scripts/release/publish.ts @@ -190,7 +190,7 @@ export const run = async (options: unknown) => { ); }; -if (esMain(import.meta)) { +if (esMain(import.meta.url)) { const parsed = program.parse(); run(parsed.opts()).catch((err) => { console.error(err); diff --git a/scripts/release/unreleased-changes-exists.ts b/scripts/release/unreleased-changes-exists.ts index 5c8978f979a3..e076e640d302 100644 --- a/scripts/release/unreleased-changes-exists.ts +++ b/scripts/release/unreleased-changes-exists.ts @@ -78,7 +78,7 @@ ${chalk.blue(changesToRelease.map(({ title, pull }) => ` #${pull}: ${title}`).j return { changesToRelease, hasChangesToRelease }; }; -if (esMain(import.meta)) { +if (esMain(import.meta.url)) { const parsed = program.parse(); run(parsed.opts()).catch((err) => { console.error(err); diff --git a/scripts/release/version.ts b/scripts/release/version.ts index 592826104539..57c0973583cf 100644 --- a/scripts/release/version.ts +++ b/scripts/release/version.ts @@ -294,7 +294,7 @@ export const run = async (options: unknown) => { } }; -if (esMain(import.meta)) { +if (esMain(import.meta.url)) { const options = program.parse().opts(); run(options).catch((err) => { console.error(err); diff --git a/scripts/release/write-changelog.ts b/scripts/release/write-changelog.ts index 2f80d381ef49..30a64dd366ee 100644 --- a/scripts/release/write-changelog.ts +++ b/scripts/release/write-changelog.ts @@ -133,7 +133,7 @@ export const run = async (args: unknown[], options: unknown) => { console.log(`āœ… Wrote Changelog to file`); }; -if (esMain(import.meta)) { +if (esMain(import.meta.url)) { const parsed = program.parse(); run(parsed.args, parsed.opts()).catch((err) => { console.error(err); diff --git a/scripts/sandbox/generate.ts b/scripts/sandbox/generate.ts index 5c2ab47d0971..e625bd194baa 100755 --- a/scripts/sandbox/generate.ts +++ b/scripts/sandbox/generate.ts @@ -251,7 +251,7 @@ export const generate = async ({ await runGenerators(generatorConfigs, localRegistry, debug); }; -if (esMain(import.meta)) { +if (esMain(import.meta.url)) { program .description('Generate sandboxes from a set of possible templates') .option('--templates [templates...]', 'Space-delimited list of templates to include') From 4baa40ffb727330f2ac1b6ba5d9466c4a6c7301c Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Wed, 8 Nov 2023 08:41:12 +0100 Subject: [PATCH 027/170] Fix danger.js --- scripts/dangerfile.ts | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/scripts/dangerfile.ts b/scripts/dangerfile.ts index 6e3100736021..754686981c80 100644 --- a/scripts/dangerfile.ts +++ b/scripts/dangerfile.ts @@ -2,14 +2,13 @@ import { fail, danger } from 'danger'; import { execSync } from 'child_process'; -import flatten from 'lodash/flatten.js'; -import intersection from 'lodash/intersection.js'; -import isEmpty from 'lodash/isEmpty.js'; - -import pkg from '../code/package.json'; - execSync('npm install lodash'); +const flatten = require('lodash/flatten.js'); +const intersection = require('lodash/intersection.js'); +const isEmpty = require('lodash/isEmpty.js'); + +const pkg = require('../code/package.json'); // eslint-disable-line import/newline-after-import const prLogConfig = pkg['pr-log']; const Versions = { @@ -32,7 +31,7 @@ const checkRequiredLabels = (labels: string[]) => { const requiredLabels = flatten([ prLogConfig.skipLabels || [], - (prLogConfig.validLabels || []).map((keyVal) => keyVal[0]), + (prLogConfig.validLabels || []).map((keyVal: string) => keyVal[0]), ]); const blockingLabels = intersection(forbiddenLabels, labels); From 4d3188309328867b788776324dbadeb4bb3732cb Mon Sep 17 00:00:00 2001 From: Joe Vaughan <122215197+joevaugh4n@users.noreply.github.com> Date: Wed, 8 Nov 2023 09:35:26 +0100 Subject: [PATCH 028/170] Update .github/DISCUSSION_TEMPLATE/help.yml Co-authored-by: Kyle Gach --- .github/DISCUSSION_TEMPLATE/help.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/DISCUSSION_TEMPLATE/help.yml b/.github/DISCUSSION_TEMPLATE/help.yml index 0e72d0d84835..ddbaaca364ad 100644 --- a/.github/DISCUSSION_TEMPLATE/help.yml +++ b/.github/DISCUSSION_TEMPLATE/help.yml @@ -17,7 +17,7 @@ body: - type: input attributes: label: Share an example - description: Help us debug your issue by creating a minimal reproduction. You can do this with StackBlitz by heading to https://storybook.new! + description: Help us debug your issue by creating a minimal reproduction. You can do this with StackBlitz by heading to [https://storybook.new](https://storybook.new)! validations: required: false - type: markdown From 758c0de182ccf448bb206350b25ee3afd715ef80 Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Wed, 8 Nov 2023 09:59:43 +0100 Subject: [PATCH 029/170] Remove custom execa implementation --- scripts/get-report-message.ts | 4 ++-- scripts/release/publish.ts | 4 +++- scripts/release/version.ts | 3 ++- scripts/sandbox/generate.ts | 3 ++- scripts/sandbox/publish.ts | 6 +++--- scripts/sandbox/utils/git.ts | 10 ++++++---- scripts/upload-bench.ts | 9 ++++++--- scripts/utils/exec.ts | 13 ------------- scripts/utils/workspace.ts | 2 +- 9 files changed, 25 insertions(+), 29 deletions(-) diff --git a/scripts/get-report-message.ts b/scripts/get-report-message.ts index 75df6ba066fc..a10bbdd276e1 100644 --- a/scripts/get-report-message.ts +++ b/scripts/get-report-message.ts @@ -1,9 +1,9 @@ /* eslint-disable no-console */ import { readJson } from 'fs-extra'; import { join } from 'path'; +import { execaCommand } from 'execa'; import esMain from './utils/esmain'; import { CODE_DIRECTORY } from './utils/constants'; -import { execaCommand } from './utils/exec'; type Branch = 'main' | 'next' | 'alpha' | 'next-release' | 'latest-release'; type Workflow = 'merged' | 'daily'; @@ -28,7 +28,7 @@ const getFooter = async (branch: Branch, workflow: Workflow, job: string) => { : // show last 24h merges for daily workflow `git log --merges --since="24 hours ago" --pretty=format:"\`%h\` %<(12)%ar %s [%an]"`; - const result = await execaCommand(mergeCommits, { shell: true }); + const result = await execaCommand(mergeCommits, { shell: true, cleanup: true }); const formattedResult = result.stdout // discord needs escaped line breaks .replace(/\n/g, '\\n') diff --git a/scripts/release/publish.ts b/scripts/release/publish.ts index 32c1b57c5b26..c5f509ccd00a 100644 --- a/scripts/release/publish.ts +++ b/scripts/release/publish.ts @@ -8,8 +8,8 @@ import { readJson } from 'fs-extra'; import fetch from 'node-fetch'; import dedent from 'ts-dedent'; import pRetry from 'p-retry'; +import { execaCommand } from 'execa'; import esMain from '../utils/esmain'; -import { execaCommand } from '../utils/exec'; program .name('publish') @@ -111,6 +111,7 @@ const buildAllPackages = async () => { console.log(`šŸ—ļø Building all packages...`); await execaCommand('yarn task --task=compile --start-from=compile --no-link', { stdio: 'inherit', + cleanup: true, cwd: CODE_DIR_PATH, }); console.log(`šŸ—ļø Packages successfully built`); @@ -146,6 +147,7 @@ const publishAllPackages = async ({ () => execaCommand(command, { stdio: 'inherit', + cleanup: true, cwd: CODE_DIR_PATH, }), { diff --git a/scripts/release/version.ts b/scripts/release/version.ts index 57c0973583cf..db3f30fa8a80 100644 --- a/scripts/release/version.ts +++ b/scripts/release/version.ts @@ -6,10 +6,10 @@ import path from 'path'; import program from 'commander'; import semver from 'semver'; import { z } from 'zod'; +import { execaCommand } from 'execa'; import esMain from '../utils/esmain'; import type { Workspace } from '../utils/workspace'; import { getWorkspaces } from '../utils/workspace'; -import { execaCommand } from '../utils/exec'; program .name('version') @@ -284,6 +284,7 @@ export const run = async (options: unknown) => { await execaCommand(`yarn install --mode=update-lockfile`, { cwd: path.join(CODE_DIR_PATH), stdio: verbose ? 'inherit' : undefined, + cleanup: true, }); console.log(`āœ… Updated lock file with ${chalk.blue('yarn install --mode=update-lockfile')}`); } diff --git a/scripts/sandbox/generate.ts b/scripts/sandbox/generate.ts index e625bd194baa..e94459e4d915 100755 --- a/scripts/sandbox/generate.ts +++ b/scripts/sandbox/generate.ts @@ -6,8 +6,8 @@ import prettyTime from 'pretty-hrtime'; import { copy, emptyDir, ensureDir, move, remove, rename, writeFile } from 'fs-extra'; import { program } from 'commander'; import { directory } from 'tempy'; +import { execaCommand } from 'execa'; import esMain from '../utils/esmain'; -import { execaCommand } from '../utils/exec'; import type { OptionValues } from '../utils/options'; import { createOptions } from '../utils/options'; @@ -99,6 +99,7 @@ export const runCommand = async (script: string, options: ExecaOptions, debug = return execaCommand(script, { stdout: debug ? 'inherit' : 'ignore', shell: true, + cleanup: true, ...options, }); }; diff --git a/scripts/sandbox/publish.ts b/scripts/sandbox/publish.ts index a40fc2bd0540..e4307690efdd 100755 --- a/scripts/sandbox/publish.ts +++ b/scripts/sandbox/publish.ts @@ -3,7 +3,7 @@ import { join } from 'path'; import { existsSync } from 'fs'; import * as tempy from 'tempy'; import { copy, emptyDir, readdir, remove, stat, writeFile } from 'fs-extra'; -import { execaCommand } from '../utils/exec'; +import { execaCommand } from 'execa'; import { getTemplatesData, renderTemplate } from './utils/template'; // eslint-disable-next-line import/no-cycle @@ -26,8 +26,8 @@ const publish = async (options: PublishOptions & { tmpFolder: string }) => { const templatesData = await getTemplatesData(branch === 'main' ? 'main' : 'next'); logger.log(`šŸ‘Æā€ā™‚ļø Cloning the repository ${remote} in branch ${branch}`); - await execaCommand(`git clone ${remote} .`, { cwd: tmpFolder }); - await execaCommand(`git checkout ${branch}`, { cwd: tmpFolder }); + await execaCommand(`git clone ${remote} .`, { cwd: tmpFolder, cleanup: true }); + await execaCommand(`git checkout ${branch}`, { cwd: tmpFolder, cleanup: true }); // otherwise old files will stick around and result inconsistent states logger.log(`šŸ—‘ Delete existing template dirs from clone`); diff --git a/scripts/sandbox/utils/git.ts b/scripts/sandbox/utils/git.ts index dea378eae921..71de33aa38fe 100644 --- a/scripts/sandbox/utils/git.ts +++ b/scripts/sandbox/utils/git.ts @@ -1,7 +1,7 @@ import fetch from 'node-fetch'; import invariant from 'tiny-invariant'; -import { execaCommand } from '../../utils/exec'; +import { execaCommand } from 'execa'; // eslint-disable-next-line import/no-cycle import { logger } from '../publish'; @@ -50,9 +50,9 @@ export async function commitAllToGit({ cwd, branch }: { cwd: string; branch: str try { logger.log(`šŸ’Ŗ Committing everything to the repository`); - await execaCommand('git add .', { cwd }); + await execaCommand('git add .', { cwd, cleanup: true }); - const currentCommitHash = (await execaCommand('git rev-parse HEAD')).stdout + const currentCommitHash = (await execaCommand('git rev-parse HEAD', { cleanup: true })).stdout .toString() .slice(0, 12); @@ -63,7 +63,8 @@ export async function commitAllToGit({ cwd, branch }: { cwd: string; branch: str const previousCommitHash = await getTheLastCommitHashThatUpdatedTheSandboxRepo(branch); const mergeCommits = ( await execaCommand( - `git log ${previousCommitHash}..${currentCommitHash} --merges --pretty=%s` + `git log ${previousCommitHash}..${currentCommitHash} --merges --pretty=%s`, + { cleanup: true } ) ).stdout .toString() @@ -95,6 +96,7 @@ export async function commitAllToGit({ cwd, branch }: { cwd: string; branch: str await execaCommand(gitCommitCommand, { shell: true, + cleanup: true, cwd, }); } catch (e) { diff --git a/scripts/upload-bench.ts b/scripts/upload-bench.ts index e841ec363c33..250c6154ce25 100644 --- a/scripts/upload-bench.ts +++ b/scripts/upload-bench.ts @@ -1,10 +1,10 @@ import { join } from 'path'; import { BigQuery } from '@google-cloud/bigquery'; +import { execaCommand } from 'execa'; import type { BenchResults } from './bench/types'; import { loadBench } from './bench/utils'; import { SANDBOX_DIRECTORY } from './utils/constants'; -import { execaCommand } from './utils/exec'; const templateKey = process.argv[2]; @@ -64,8 +64,11 @@ const uploadBench = async () => { const row = { ...defaults, branch: - process.env.CIRCLE_BRANCH || (await execaCommand('git rev-parse --abbrev-ref HEAD')).stdout, - commit: process.env.CIRCLE_SHA1 || (await execaCommand('git rev-parse HEAD')).stdout, + process.env.CIRCLE_BRANCH || + (await execaCommand('git rev-parse --abbrev-ref HEAD', { cleanup: true })).stdout, + commit: + process.env.CIRCLE_SHA1 || + (await execaCommand('git rev-parse HEAD', { cleanup: true })).stdout, timestamp: new Date().toISOString(), label: templateKey, ...results, diff --git a/scripts/utils/exec.ts b/scripts/utils/exec.ts index 4dec95e814fc..536c36aecf14 100644 --- a/scripts/utils/exec.ts +++ b/scripts/utils/exec.ts @@ -13,19 +13,6 @@ type StepOptions = { signal?: AbortSignal; }; -// Reimplementation of `execaCommand` to use `getExeca` -export const execaCommand = async ( - command: string, - options: Options = {} -): Promise> => { - // We await here because execaCommand returns a promise, but that's not what the user expects - // eslint-disable-next-line @typescript-eslint/return-await - return await execa(command, { - cleanup: true, - ...options, - }); -}; - export const exec = async ( command: string | string[], options: Options = {}, diff --git a/scripts/utils/workspace.ts b/scripts/utils/workspace.ts index a9af2eb46fa2..7edef2d14f16 100644 --- a/scripts/utils/workspace.ts +++ b/scripts/utils/workspace.ts @@ -1,6 +1,6 @@ import memoize from 'memoizerific'; +import { execaCommand } from 'execa'; import { CODE_DIRECTORY } from './constants'; -import { execaCommand } from './exec'; export type Workspace = { name: string; location: string }; From 6d5080e0a16527231aeaab6e17ba484ec98d4d2a Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Wed, 8 Nov 2023 15:48:16 +0100 Subject: [PATCH 030/170] Fix tests --- scripts/release/__tests__/version.test.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/scripts/release/__tests__/version.test.ts b/scripts/release/__tests__/version.test.ts index 98069ffaba74..22a2cb7ca8a1 100644 --- a/scripts/release/__tests__/version.test.ts +++ b/scripts/release/__tests__/version.test.ts @@ -11,8 +11,8 @@ jest.mock('../../../code/lib/cli/src/versions', () => ({ '@storybook/addon-a11y': '7.1.0-alpha.29', })); -jest.mock('../../utils/exec'); -const { execaCommand } = require('../../utils/exec'); +jest.mock('execa'); +const { execaCommand } = require('execa'); jest.mock('../../utils/workspace', () => ({ getWorkspaces: jest.fn().mockResolvedValue([ @@ -288,6 +288,7 @@ describe('Version', () => { ); expect(execaCommand).toHaveBeenCalledWith('yarn install --mode=update-lockfile', { cwd: path.join(CODE_DIR_PATH), + cleanup: true, stdio: undefined, }); } From f7dba4ca7dca974d0e574ee8fe71b65aa13d549f Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Wed, 8 Nov 2023 17:12:06 +0100 Subject: [PATCH 031/170] Fix identation in Migration.md --- MIGRATION.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/MIGRATION.md b/MIGRATION.md index 7c195b604889..023a398d32a2 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -1,7 +1,7 @@

Migration

- [From version 7.5.0 to 7.6.0](#from-version-750-to-760) - - [Primary doc block accepts of prop](#primary-doc-block-accepts-of-prop) + - [Primary doc block accepts of prop](#primary-doc-block-accepts-of-prop) - [From version 7.4.0 to 7.5.0](#from-version-740-to-750) - [`storyStoreV6` and `storiesOf` is deprecated](#storystorev6-and-storiesof-is-deprecated) - [`storyIndexers` is replaced with `experimental_indexers`](#storyindexers-is-replaced-with-experimental_indexers) @@ -311,7 +311,7 @@ ## From version 7.5.0 to 7.6.0 -##### Primary doc block accepts of prop +#### Primary doc block accepts of prop The `Primary` doc block now also accepts an `of` prop as described in the [Doc Blocks](#doc-blocks) section. It still accepts being passed `name` or no props at all. From dca97a1f91b2577b0d1ddb1ff780e3837c12cc09 Mon Sep 17 00:00:00 2001 From: paoloricciuti Date: Fri, 10 Nov 2023 00:31:46 +0100 Subject: [PATCH 032/170] feat: tighter integration with sveltekit --- code/frameworks/sveltekit/package.json | 15 +++++- .../src/components/LinkListener.svelte | 43 ++++++++++++++++ .../sveltekit/src/mocks/app/forms.ts | 19 +++++++ .../sveltekit/src/mocks/app/navigation.ts | 49 +++++++++++++++++++ .../sveltekit/src/mocks/app/stores.ts | 20 ++++++++ .../sveltekit/src/plugins/config-overrides.ts | 31 +++++++++--- code/frameworks/sveltekit/src/preset.ts | 4 ++ code/frameworks/sveltekit/src/preview.ts | 19 +++++++ 8 files changed, 191 insertions(+), 9 deletions(-) create mode 100644 code/frameworks/sveltekit/src/components/LinkListener.svelte create mode 100644 code/frameworks/sveltekit/src/mocks/app/forms.ts create mode 100644 code/frameworks/sveltekit/src/mocks/app/navigation.ts create mode 100644 code/frameworks/sveltekit/src/mocks/app/stores.ts create mode 100644 code/frameworks/sveltekit/src/preview.ts diff --git a/code/frameworks/sveltekit/package.json b/code/frameworks/sveltekit/package.json index 632b552869f7..9eb5088313d5 100644 --- a/code/frameworks/sveltekit/package.json +++ b/code/frameworks/sveltekit/package.json @@ -29,6 +29,17 @@ "require": "./dist/index.js", "import": "./dist/index.mjs" }, + "./src/components/LinkListener.svelte": "./src/components/LinkListener.svelte", + "./preview": { + "types": "./dist/preview.d.ts", + "require": "./dist/preview.js", + "import": "./dist/preview.mjs" + }, + "./dist/preview.js": { + "types": "./dist/preview.d.ts", + "require": "./dist/preview.js", + "import": "./dist/preview.mjs" + }, "./preset": { "types": "./dist/preset.d.ts", "require": "./dist/preset.js" @@ -43,7 +54,8 @@ "README.md", "*.js", "*.d.ts", - "!src/**/*" + "!src/**/*", + "src/components/**/*" ], "scripts": { "check": "../../../scripts/prepare/check.ts", @@ -72,6 +84,7 @@ "bundler": { "entries": [ "./src/index.ts", + "./src/preview.ts", "./src/preset.ts" ], "platform": "node" diff --git a/code/frameworks/sveltekit/src/components/LinkListener.svelte b/code/frameworks/sveltekit/src/components/LinkListener.svelte new file mode 100644 index 000000000000..fafe78951db3 --- /dev/null +++ b/code/frameworks/sveltekit/src/components/LinkListener.svelte @@ -0,0 +1,43 @@ + + + diff --git a/code/frameworks/sveltekit/src/mocks/app/forms.ts b/code/frameworks/sveltekit/src/mocks/app/forms.ts new file mode 100644 index 000000000000..ed68853479ca --- /dev/null +++ b/code/frameworks/sveltekit/src/mocks/app/forms.ts @@ -0,0 +1,19 @@ +export function enhance(form: HTMLFormElement) { + // import('@storybook/addon-actions') + // .then(({ action }) => { + // action('sveltekit.enhance')(); + // }) + // .catch(console.log); +} + +export function applyAction() {} + +export function deserialize() { + return deserializeResponse; +} + +let deserializeResponse: any; + +export function setDeserializeResponse(answer: any) { + deserializeResponse = answer; +} diff --git a/code/frameworks/sveltekit/src/mocks/app/navigation.ts b/code/frameworks/sveltekit/src/mocks/app/navigation.ts new file mode 100644 index 000000000000..6d4af0ac87df --- /dev/null +++ b/code/frameworks/sveltekit/src/mocks/app/navigation.ts @@ -0,0 +1,49 @@ +import { getContext, onMount, setContext } from 'svelte'; + +export async function goto(...args: any[]) { + // try { + // const { action } = await import('@storybook/addon-actions'); + // action('sveltekit.goto')(...args); + // } catch (e) { + // console.log(e); + // } +} + +export function setAfterNavigateArgument(afterNavigateArgs: any) { + setContext('after-navigate-args', afterNavigateArgs); +} + +export function afterNavigate(cb: any) { + const argument = getContext('after-navigate-args'); + onMount(() => { + cb(argument); + }); +} + +export function onNavigate() {} + +export function beforeNavigate() {} + +export function disableScrollHandling() {} + +export async function invalidate(...args: any[]) { + // try { + // const { action } = await import('@storybook/addon-actions'); + // action('sveltekit.invalidate')(...args); + // } catch (e) { + // console.log(e); + // } +} + +export async function invalidateAll() { + // try { + // const { action } = await import('@storybook/addon-actions'); + // action('sveltekit.invalidateAll')(); + // } catch (e) { + // console.log(e); + // } +} + +export function preloadCode() {} + +export function preloadData() {} diff --git a/code/frameworks/sveltekit/src/mocks/app/stores.ts b/code/frameworks/sveltekit/src/mocks/app/stores.ts new file mode 100644 index 000000000000..bd7ce8e9120e --- /dev/null +++ b/code/frameworks/sveltekit/src/mocks/app/stores.ts @@ -0,0 +1,20 @@ +import { getContext, setContext } from 'svelte'; + +function createMockedStore(contextName: string) { + return [ + { + subscribe(runner: any) { + const page = getContext(contextName); + runner(page); + return () => {}; + }, + }, + (value: unknown) => { + setContext(contextName, value); + }, + ] as const; +} + +export const [page, setPage] = createMockedStore('page-ctx'); +export const [navigating, setNavigating] = createMockedStore('navigating-ctx'); +export const [updated, setUpdated] = createMockedStore('updated-ctx'); diff --git a/code/frameworks/sveltekit/src/plugins/config-overrides.ts b/code/frameworks/sveltekit/src/plugins/config-overrides.ts index db5294a13242..d1dfcc09919e 100644 --- a/code/frameworks/sveltekit/src/plugins/config-overrides.ts +++ b/code/frameworks/sveltekit/src/plugins/config-overrides.ts @@ -1,12 +1,27 @@ -import type { Plugin } from 'vite'; +import { resolve } from 'node:path'; +import { mergeConfig, type Plugin } from 'vite'; export function configOverrides() { - return { - // SvelteKit sets SSR, we need it to be false when building - name: 'storybook:sveltekit-overrides', - apply: 'build', - config: () => { - return { build: { ssr: false } }; + return [ + { + // SvelteKit sets SSR, we need it to be false when building + name: 'storybook:sveltekit-overrides', + apply: 'build', + config: () => { + return { build: { ssr: false } }; + }, }, - } satisfies Plugin; + { + name: 'storybook:sveltekit-mock-stores', + enforce: 'post', + config: (config) => + mergeConfig(config, { + resolve: { + alias: { + $app: resolve(__dirname, '../src/mocks/app/'), + }, + }, + }), + }, + ] satisfies Plugin[]; } diff --git a/code/frameworks/sveltekit/src/preset.ts b/code/frameworks/sveltekit/src/preset.ts index e92e45079f63..4e765d1631cc 100644 --- a/code/frameworks/sveltekit/src/preset.ts +++ b/code/frameworks/sveltekit/src/preset.ts @@ -13,6 +13,10 @@ export const core: PresetProperty<'core', StorybookConfig> = { builder: getAbsolutePath('@storybook/builder-vite'), renderer: getAbsolutePath('@storybook/svelte'), }; +export const previewAnnotations: StorybookConfig['previewAnnotations'] = (entry = []) => [ + ...entry, + require.resolve('@storybook/sveltekit/preview'), +]; export const viteFinal: NonNullable = async (config, options) => { const baseConfig = await svelteViteFinal(config, options); diff --git a/code/frameworks/sveltekit/src/preview.ts b/code/frameworks/sveltekit/src/preview.ts new file mode 100644 index 000000000000..dbb0786be689 --- /dev/null +++ b/code/frameworks/sveltekit/src/preview.ts @@ -0,0 +1,19 @@ +import type { Decorator } from '@storybook/svelte'; + +// eslint-disable-next-line import/no-extraneous-dependencies +import LinkListener from '@storybook/sveltekit/src/components/LinkListener.svelte'; +import { setDeserializeResponse } from './mocks/app/forms'; +import { setAfterNavigateArgument } from './mocks/app/navigation'; +import { setNavigating, setPage, setUpdated } from './mocks/app/stores'; + +export const decorators: Decorator[] = [ + (Story, ctx) => { + setPage(ctx.parameters?.sveltekit?.stores?.page); + setUpdated(ctx.parameters?.sveltekit?.stores?.updated); + setNavigating(ctx.parameters?.sveltekit?.stores?.navigating); + setDeserializeResponse(ctx.parameters?.sveltekit?.forms?.deserializeResponse); + setAfterNavigateArgument(ctx.parameters?.sveltekit?.navigation?.afterNavigate); + return Story(); + }, + (_, ctx) => ({ Component: LinkListener, props: { ctx } }), +]; From 0a103b1e237880aaad6005d52ee8c20af3934c1f Mon Sep 17 00:00:00 2001 From: paoloricciuti Date: Fri, 10 Nov 2023 11:20:39 +0100 Subject: [PATCH 033/170] fix callbacks for goto, enhance, invalidate, invalidateAll add getStores export --- code/frameworks/sveltekit/package.json | 2 +- .../src/components/LinkListener.svelte | 43 ------------- .../src/components/SvelteDecorator.svelte | 60 +++++++++++++++++++ .../sveltekit/src/mocks/app/forms.ts | 7 +-- .../sveltekit/src/mocks/app/navigation.ts | 28 ++++----- .../sveltekit/src/mocks/app/stores.ts | 8 +++ code/frameworks/sveltekit/src/preview.ts | 8 +-- 7 files changed, 85 insertions(+), 71 deletions(-) delete mode 100644 code/frameworks/sveltekit/src/components/LinkListener.svelte create mode 100644 code/frameworks/sveltekit/src/components/SvelteDecorator.svelte diff --git a/code/frameworks/sveltekit/package.json b/code/frameworks/sveltekit/package.json index 9eb5088313d5..afa20320e9b7 100644 --- a/code/frameworks/sveltekit/package.json +++ b/code/frameworks/sveltekit/package.json @@ -29,7 +29,7 @@ "require": "./dist/index.js", "import": "./dist/index.mjs" }, - "./src/components/LinkListener.svelte": "./src/components/LinkListener.svelte", + "./src/components/SvelteDecorator.svelte": "./src/components/SvelteDecorator.svelte", "./preview": { "types": "./dist/preview.d.ts", "require": "./dist/preview.js", diff --git a/code/frameworks/sveltekit/src/components/LinkListener.svelte b/code/frameworks/sveltekit/src/components/LinkListener.svelte deleted file mode 100644 index fafe78951db3..000000000000 --- a/code/frameworks/sveltekit/src/components/LinkListener.svelte +++ /dev/null @@ -1,43 +0,0 @@ - - - diff --git a/code/frameworks/sveltekit/src/components/SvelteDecorator.svelte b/code/frameworks/sveltekit/src/components/SvelteDecorator.svelte new file mode 100644 index 000000000000..fe337afe1815 --- /dev/null +++ b/code/frameworks/sveltekit/src/components/SvelteDecorator.svelte @@ -0,0 +1,60 @@ + + + diff --git a/code/frameworks/sveltekit/src/mocks/app/forms.ts b/code/frameworks/sveltekit/src/mocks/app/forms.ts index ed68853479ca..73a9eaefc044 100644 --- a/code/frameworks/sveltekit/src/mocks/app/forms.ts +++ b/code/frameworks/sveltekit/src/mocks/app/forms.ts @@ -1,9 +1,6 @@ export function enhance(form: HTMLFormElement) { - // import('@storybook/addon-actions') - // .then(({ action }) => { - // action('sveltekit.enhance')(); - // }) - // .catch(console.log); + const event = new CustomEvent('storybook:enhance'); + window.dispatchEvent(event); } export function applyAction() {} diff --git a/code/frameworks/sveltekit/src/mocks/app/navigation.ts b/code/frameworks/sveltekit/src/mocks/app/navigation.ts index 6d4af0ac87df..aeaf586ae0ca 100644 --- a/code/frameworks/sveltekit/src/mocks/app/navigation.ts +++ b/code/frameworks/sveltekit/src/mocks/app/navigation.ts @@ -1,12 +1,10 @@ import { getContext, onMount, setContext } from 'svelte'; export async function goto(...args: any[]) { - // try { - // const { action } = await import('@storybook/addon-actions'); - // action('sveltekit.goto')(...args); - // } catch (e) { - // console.log(e); - // } + const event = new CustomEvent('storybook:goto', { + detail: args, + }); + window.dispatchEvent(event); } export function setAfterNavigateArgument(afterNavigateArgs: any) { @@ -27,21 +25,15 @@ export function beforeNavigate() {} export function disableScrollHandling() {} export async function invalidate(...args: any[]) { - // try { - // const { action } = await import('@storybook/addon-actions'); - // action('sveltekit.invalidate')(...args); - // } catch (e) { - // console.log(e); - // } + const event = new CustomEvent('storybook:invalidate', { + detail: args, + }); + window.dispatchEvent(event); } export async function invalidateAll() { - // try { - // const { action } = await import('@storybook/addon-actions'); - // action('sveltekit.invalidateAll')(); - // } catch (e) { - // console.log(e); - // } + const event = new CustomEvent('storybook:invalidateAll'); + window.dispatchEvent(event); } export function preloadCode() {} diff --git a/code/frameworks/sveltekit/src/mocks/app/stores.ts b/code/frameworks/sveltekit/src/mocks/app/stores.ts index bd7ce8e9120e..e291f4d42ca1 100644 --- a/code/frameworks/sveltekit/src/mocks/app/stores.ts +++ b/code/frameworks/sveltekit/src/mocks/app/stores.ts @@ -18,3 +18,11 @@ function createMockedStore(contextName: string) { export const [page, setPage] = createMockedStore('page-ctx'); export const [navigating, setNavigating] = createMockedStore('navigating-ctx'); export const [updated, setUpdated] = createMockedStore('updated-ctx'); + +export function getStores() { + return { + page, + navigating, + updated, + }; +} diff --git a/code/frameworks/sveltekit/src/preview.ts b/code/frameworks/sveltekit/src/preview.ts index dbb0786be689..09c5578a6980 100644 --- a/code/frameworks/sveltekit/src/preview.ts +++ b/code/frameworks/sveltekit/src/preview.ts @@ -1,7 +1,7 @@ import type { Decorator } from '@storybook/svelte'; // eslint-disable-next-line import/no-extraneous-dependencies -import LinkListener from '@storybook/sveltekit/src/components/LinkListener.svelte'; +import SvelteDecorator from '@storybook/sveltekit/src/components/SvelteDecorator.svelte'; import { setDeserializeResponse } from './mocks/app/forms'; import { setAfterNavigateArgument } from './mocks/app/navigation'; import { setNavigating, setPage, setUpdated } from './mocks/app/stores'; @@ -11,9 +11,9 @@ export const decorators: Decorator[] = [ setPage(ctx.parameters?.sveltekit?.stores?.page); setUpdated(ctx.parameters?.sveltekit?.stores?.updated); setNavigating(ctx.parameters?.sveltekit?.stores?.navigating); - setDeserializeResponse(ctx.parameters?.sveltekit?.forms?.deserializeResponse); - setAfterNavigateArgument(ctx.parameters?.sveltekit?.navigation?.afterNavigate); + setDeserializeResponse(ctx.parameters?.sveltekit?.stores?.forms?.deserializeResponse); + setAfterNavigateArgument(ctx.parameters?.sveltekit?.stores?.navigation?.afterNavigate); return Story(); }, - (_, ctx) => ({ Component: LinkListener, props: { ctx } }), + (_, ctx) => ({ Component: SvelteDecorator, props: { ctx } }), ]; From a19c1e43f30cfa520f18b452c97ffb9cc0a41a81 Mon Sep 17 00:00:00 2001 From: paoloricciuti Date: Fri, 10 Nov 2023 16:26:46 +0100 Subject: [PATCH 034/170] add tests --- .../src/components/SvelteDecorator.svelte | 5 +- .../sveltekit/src/mocks/app/forms.ts | 23 ++-- code/frameworks/sveltekit/src/preview.ts | 4 +- .../Forms.svelte | 7 ++ .../Links.svelte | 1 + .../Navigation.svelte | 25 ++++ .../Stores.svelte | 15 +++ .../forms.stories.js | 26 ++++ .../links.stories.js | 26 ++++ .../navigation.stories.js | 83 +++++++++++++ .../stores.stories.js | 116 ++++++++++++++++++ .../Forms.svelte | 7 ++ .../Links.svelte | 1 + .../Navigation.svelte | 25 ++++ .../Stores.svelte | 15 +++ .../forms.stories.js | 26 ++++ .../links.stories.js | 26 ++++ .../navigation.stories.js | 83 +++++++++++++ .../stores.stories.js | 116 ++++++++++++++++++ 19 files changed, 614 insertions(+), 16 deletions(-) create mode 100644 code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/Forms.svelte create mode 100644 code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/Links.svelte create mode 100644 code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/Navigation.svelte create mode 100644 code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/Stores.svelte create mode 100644 code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/forms.stories.js create mode 100644 code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/links.stories.js create mode 100644 code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/navigation.stories.js create mode 100644 code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/stores.stories.js create mode 100644 code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/Forms.svelte create mode 100644 code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/Links.svelte create mode 100644 code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/Navigation.svelte create mode 100644 code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/Stores.svelte create mode 100644 code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/forms.stories.js create mode 100644 code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/links.stories.js create mode 100644 code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/navigation.stories.js create mode 100644 code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/stores.stories.js diff --git a/code/frameworks/sveltekit/src/components/SvelteDecorator.svelte b/code/frameworks/sveltekit/src/components/SvelteDecorator.svelte index fe337afe1815..025ec47e2074 100644 --- a/code/frameworks/sveltekit/src/components/SvelteDecorator.svelte +++ b/code/frameworks/sveltekit/src/components/SvelteDecorator.svelte @@ -30,8 +30,9 @@ for(let func of functions){ if(ctx?.parameters?.sveltekit?.[baseModule]?.[func] && ctx.parameters.sveltekit[baseModule][func] instanceof Function){ const listener = ({ detail = [] })=>{ - console.log("event", ctx); - ctx.parameters.sveltekit[baseModule][func](...detail); + console.log("event", func, ctx); + const args = Array.isArray(detail) ? detail : []; + ctx.parameters.sveltekit[baseModule][func](...args); } const eventType = `storybook:${func}`; toRemove.push({ eventType, listener }); diff --git a/code/frameworks/sveltekit/src/mocks/app/forms.ts b/code/frameworks/sveltekit/src/mocks/app/forms.ts index 73a9eaefc044..d1b26867c7d6 100644 --- a/code/frameworks/sveltekit/src/mocks/app/forms.ts +++ b/code/frameworks/sveltekit/src/mocks/app/forms.ts @@ -1,16 +1,17 @@ export function enhance(form: HTMLFormElement) { - const event = new CustomEvent('storybook:enhance'); - window.dispatchEvent(event); + const listener = (e: Event) => { + e.preventDefault(); + const event = new CustomEvent('storybook:enhance'); + window.dispatchEvent(event); + }; + form.addEventListener('submit', listener); + return { + destroy() { + form.removeEventListener('submit', listener); + }, + }; } export function applyAction() {} -export function deserialize() { - return deserializeResponse; -} - -let deserializeResponse: any; - -export function setDeserializeResponse(answer: any) { - deserializeResponse = answer; -} +export function deserialize() {} diff --git a/code/frameworks/sveltekit/src/preview.ts b/code/frameworks/sveltekit/src/preview.ts index 09c5578a6980..54914221f91c 100644 --- a/code/frameworks/sveltekit/src/preview.ts +++ b/code/frameworks/sveltekit/src/preview.ts @@ -2,7 +2,6 @@ import type { Decorator } from '@storybook/svelte'; // eslint-disable-next-line import/no-extraneous-dependencies import SvelteDecorator from '@storybook/sveltekit/src/components/SvelteDecorator.svelte'; -import { setDeserializeResponse } from './mocks/app/forms'; import { setAfterNavigateArgument } from './mocks/app/navigation'; import { setNavigating, setPage, setUpdated } from './mocks/app/stores'; @@ -11,8 +10,7 @@ export const decorators: Decorator[] = [ setPage(ctx.parameters?.sveltekit?.stores?.page); setUpdated(ctx.parameters?.sveltekit?.stores?.updated); setNavigating(ctx.parameters?.sveltekit?.stores?.navigating); - setDeserializeResponse(ctx.parameters?.sveltekit?.stores?.forms?.deserializeResponse); - setAfterNavigateArgument(ctx.parameters?.sveltekit?.stores?.navigation?.afterNavigate); + setAfterNavigateArgument(ctx.parameters?.sveltekit?.navigation?.afterNavigate); return Story(); }, (_, ctx) => ({ Component: SvelteDecorator, props: { ctx } }), diff --git a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/Forms.svelte b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/Forms.svelte new file mode 100644 index 000000000000..371a17656bea --- /dev/null +++ b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/Forms.svelte @@ -0,0 +1,7 @@ + + +
+ +
\ No newline at end of file diff --git a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/Links.svelte b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/Links.svelte new file mode 100644 index 000000000000..3470b6b0e6f8 --- /dev/null +++ b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/Links.svelte @@ -0,0 +1 @@ +Storybook \ No newline at end of file diff --git a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/Navigation.svelte b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/Navigation.svelte new file mode 100644 index 000000000000..d97b6fe8a2df --- /dev/null +++ b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/Navigation.svelte @@ -0,0 +1,25 @@ + + + + + + + diff --git a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/Stores.svelte b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/Stores.svelte new file mode 100644 index 000000000000..479239610a6b --- /dev/null +++ b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/Stores.svelte @@ -0,0 +1,15 @@ + + +

Directly importing

+
{JSON.stringify($page, null, 2)}
+
{JSON.stringify($navigating, null, 2)}
+
{JSON.stringify($updated, null, 2)}
+ +

With getStores

+
{JSON.stringify($pageStore, null, 2)}
+
{JSON.stringify($navigatingStore, null, 2)}
+
{JSON.stringify($updatedStore, null, 2)}
diff --git a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/forms.stories.js b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/forms.stories.js new file mode 100644 index 000000000000..fadda8554ac5 --- /dev/null +++ b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/forms.stories.js @@ -0,0 +1,26 @@ +import { expect, fn, within } from '@storybook/test'; +import Forms from './Forms.svelte'; + +export default { + title: 'stories/sveltekit/modules/Forms', + component: Forms, + tags: ['autodocs'], +}; + +const enhance = fn(); + +export const Enhance = { + async play({ canvasElement }) { + const canvas = within(canvasElement); + const button = canvas.getByText('enhance'); + button.click(); + expect(enhance).toHaveBeenCalled(); + }, + parameters: { + sveltekit: { + forms: { + enhance, + }, + }, + }, +}; diff --git a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/links.stories.js b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/links.stories.js new file mode 100644 index 000000000000..c293245fc698 --- /dev/null +++ b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/links.stories.js @@ -0,0 +1,26 @@ +import { expect, fn, within } from '@storybook/test'; +import Links from './Links.svelte'; + +export default { + title: 'stories/sveltekit/modules/Links', + component: Links, + tags: ['autodocs'], +}; + +const link = fn(); + +export const Link = { + async play({ canvasElement }) { + const canvas = within(canvasElement); + const button = canvas.getByText('Storybook'); + button.click(); + expect(link).toHaveBeenCalled(); + }, + parameters: { + sveltekit: { + linkOverrides: { + '/storybook': link, + }, + }, + }, +}; diff --git a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/navigation.stories.js b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/navigation.stories.js new file mode 100644 index 000000000000..14fe338749f4 --- /dev/null +++ b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/navigation.stories.js @@ -0,0 +1,83 @@ +import { expect, fn, within } from '@storybook/test'; +import Navigation from './Navigation.svelte'; + +export default { + title: 'stories/sveltekit/modules/Navigation', + component: Navigation, + tags: ['autodocs'], +}; + +const goto = fn(); + +export const Goto = { + async play({ canvasElement }) { + const canvas = within(canvasElement); + const button = canvas.getByText('goto'); + button.click(); + expect(goto).toHaveBeenCalledWith('/storybook'); + }, + parameters: { + sveltekit: { + navigation: { + goto, + }, + }, + }, +}; + +const invalidate = fn(); + +export const Invalidate = { + async play({ canvasElement }) { + const canvas = within(canvasElement); + const button = canvas.getByText('invalidate', { exact: true }); + button.click(); + expect(invalidate).toHaveBeenCalledWith('/storybook'); + }, + parameters: { + sveltekit: { + navigation: { + invalidate, + }, + }, + }, +}; + +const invalidateAll = fn(); + +export const InvalidateAll = { + async play({ canvasElement }) { + const canvas = within(canvasElement); + const button = canvas.getByText('invalidateAll'); + button.click(); + console.log({ button }); + expect(invalidateAll).toHaveBeenCalledWith(); + }, + parameters: { + sveltekit: { + navigation: { + invalidateAll, + }, + }, + }, +}; + +const afterNavigateFn = fn(); + +export const AfterNavigate = { + async play() { + expect(afterNavigateFn).toHaveBeenCalledWith({ test: 'passed' }); + }, + args: { + afterNavigateFn, + }, + parameters: { + sveltekit: { + navigation: { + afterNavigate: { + test: 'passed', + }, + }, + }, + }, +}; diff --git a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/stores.stories.js b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/stores.stories.js new file mode 100644 index 000000000000..9ad83fe1bd87 --- /dev/null +++ b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/stores.stories.js @@ -0,0 +1,116 @@ +import Stores from './Stores.svelte'; + +export default { + title: 'stories/sveltekit/modules/Stores', + component: Stores, + tags: ['autodocs'], +}; + +export const AllUndefined = {}; + +export const PageStore = { + parameters: { + sveltekit: { + stores: { + page: { + data: { + test: 'passed', + }, + }, + }, + }, + }, +}; + +export const NavigatingStore = { + parameters: { + sveltekit: { + stores: { + navigating: { + route: { + id: '/storybook', + }, + }, + }, + }, + }, +}; + +export const UpdatedStore = { + parameters: { + sveltekit: { + stores: { + updated: true, + }, + }, + }, +}; + +export const PageAndNavigatingStore = { + parameters: { + sveltekit: { + stores: { + page: { + data: { + test: 'passed', + }, + }, + navigating: { + route: { + id: '/storybook', + }, + }, + }, + }, + }, +}; + +export const PageAndUpdatedStore = { + parameters: { + sveltekit: { + stores: { + page: { + data: { + test: 'passed', + }, + }, + updated: true, + }, + }, + }, +}; + +export const NavigatingAndUpdatedStore = { + parameters: { + sveltekit: { + stores: { + navigating: { + route: { + id: '/storybook', + }, + }, + updated: true, + }, + }, + }, +}; + +export const AllThreeStores = { + parameters: { + sveltekit: { + stores: { + page: { + data: { + test: 'passed', + }, + }, + navigating: { + route: { + id: '/storybook', + }, + }, + updated: true, + }, + }, + }, +}; diff --git a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/Forms.svelte b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/Forms.svelte new file mode 100644 index 000000000000..371a17656bea --- /dev/null +++ b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/Forms.svelte @@ -0,0 +1,7 @@ + + +
+ +
\ No newline at end of file diff --git a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/Links.svelte b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/Links.svelte new file mode 100644 index 000000000000..3470b6b0e6f8 --- /dev/null +++ b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/Links.svelte @@ -0,0 +1 @@ +Storybook \ No newline at end of file diff --git a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/Navigation.svelte b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/Navigation.svelte new file mode 100644 index 000000000000..d97b6fe8a2df --- /dev/null +++ b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/Navigation.svelte @@ -0,0 +1,25 @@ + + + + + + + diff --git a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/Stores.svelte b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/Stores.svelte new file mode 100644 index 000000000000..479239610a6b --- /dev/null +++ b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/Stores.svelte @@ -0,0 +1,15 @@ + + +

Directly importing

+
{JSON.stringify($page, null, 2)}
+
{JSON.stringify($navigating, null, 2)}
+
{JSON.stringify($updated, null, 2)}
+ +

With getStores

+
{JSON.stringify($pageStore, null, 2)}
+
{JSON.stringify($navigatingStore, null, 2)}
+
{JSON.stringify($updatedStore, null, 2)}
diff --git a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/forms.stories.js b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/forms.stories.js new file mode 100644 index 000000000000..fadda8554ac5 --- /dev/null +++ b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/forms.stories.js @@ -0,0 +1,26 @@ +import { expect, fn, within } from '@storybook/test'; +import Forms from './Forms.svelte'; + +export default { + title: 'stories/sveltekit/modules/Forms', + component: Forms, + tags: ['autodocs'], +}; + +const enhance = fn(); + +export const Enhance = { + async play({ canvasElement }) { + const canvas = within(canvasElement); + const button = canvas.getByText('enhance'); + button.click(); + expect(enhance).toHaveBeenCalled(); + }, + parameters: { + sveltekit: { + forms: { + enhance, + }, + }, + }, +}; diff --git a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/links.stories.js b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/links.stories.js new file mode 100644 index 000000000000..c293245fc698 --- /dev/null +++ b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/links.stories.js @@ -0,0 +1,26 @@ +import { expect, fn, within } from '@storybook/test'; +import Links from './Links.svelte'; + +export default { + title: 'stories/sveltekit/modules/Links', + component: Links, + tags: ['autodocs'], +}; + +const link = fn(); + +export const Link = { + async play({ canvasElement }) { + const canvas = within(canvasElement); + const button = canvas.getByText('Storybook'); + button.click(); + expect(link).toHaveBeenCalled(); + }, + parameters: { + sveltekit: { + linkOverrides: { + '/storybook': link, + }, + }, + }, +}; diff --git a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/navigation.stories.js b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/navigation.stories.js new file mode 100644 index 000000000000..14fe338749f4 --- /dev/null +++ b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/navigation.stories.js @@ -0,0 +1,83 @@ +import { expect, fn, within } from '@storybook/test'; +import Navigation from './Navigation.svelte'; + +export default { + title: 'stories/sveltekit/modules/Navigation', + component: Navigation, + tags: ['autodocs'], +}; + +const goto = fn(); + +export const Goto = { + async play({ canvasElement }) { + const canvas = within(canvasElement); + const button = canvas.getByText('goto'); + button.click(); + expect(goto).toHaveBeenCalledWith('/storybook'); + }, + parameters: { + sveltekit: { + navigation: { + goto, + }, + }, + }, +}; + +const invalidate = fn(); + +export const Invalidate = { + async play({ canvasElement }) { + const canvas = within(canvasElement); + const button = canvas.getByText('invalidate', { exact: true }); + button.click(); + expect(invalidate).toHaveBeenCalledWith('/storybook'); + }, + parameters: { + sveltekit: { + navigation: { + invalidate, + }, + }, + }, +}; + +const invalidateAll = fn(); + +export const InvalidateAll = { + async play({ canvasElement }) { + const canvas = within(canvasElement); + const button = canvas.getByText('invalidateAll'); + button.click(); + console.log({ button }); + expect(invalidateAll).toHaveBeenCalledWith(); + }, + parameters: { + sveltekit: { + navigation: { + invalidateAll, + }, + }, + }, +}; + +const afterNavigateFn = fn(); + +export const AfterNavigate = { + async play() { + expect(afterNavigateFn).toHaveBeenCalledWith({ test: 'passed' }); + }, + args: { + afterNavigateFn, + }, + parameters: { + sveltekit: { + navigation: { + afterNavigate: { + test: 'passed', + }, + }, + }, + }, +}; diff --git a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/stores.stories.js b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/stores.stories.js new file mode 100644 index 000000000000..9ad83fe1bd87 --- /dev/null +++ b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/stores.stories.js @@ -0,0 +1,116 @@ +import Stores from './Stores.svelte'; + +export default { + title: 'stories/sveltekit/modules/Stores', + component: Stores, + tags: ['autodocs'], +}; + +export const AllUndefined = {}; + +export const PageStore = { + parameters: { + sveltekit: { + stores: { + page: { + data: { + test: 'passed', + }, + }, + }, + }, + }, +}; + +export const NavigatingStore = { + parameters: { + sveltekit: { + stores: { + navigating: { + route: { + id: '/storybook', + }, + }, + }, + }, + }, +}; + +export const UpdatedStore = { + parameters: { + sveltekit: { + stores: { + updated: true, + }, + }, + }, +}; + +export const PageAndNavigatingStore = { + parameters: { + sveltekit: { + stores: { + page: { + data: { + test: 'passed', + }, + }, + navigating: { + route: { + id: '/storybook', + }, + }, + }, + }, + }, +}; + +export const PageAndUpdatedStore = { + parameters: { + sveltekit: { + stores: { + page: { + data: { + test: 'passed', + }, + }, + updated: true, + }, + }, + }, +}; + +export const NavigatingAndUpdatedStore = { + parameters: { + sveltekit: { + stores: { + navigating: { + route: { + id: '/storybook', + }, + }, + updated: true, + }, + }, + }, +}; + +export const AllThreeStores = { + parameters: { + sveltekit: { + stores: { + page: { + data: { + test: 'passed', + }, + }, + navigating: { + route: { + id: '/storybook', + }, + }, + updated: true, + }, + }, + }, +}; From a42fc78297d4b7a65ab17d284a8a5134aad7b4af Mon Sep 17 00:00:00 2001 From: paoloricciuti Date: Fri, 10 Nov 2023 16:52:24 +0100 Subject: [PATCH 035/170] add check field to update store and write README --- code/frameworks/sveltekit/README.md | 49 +++++++++++++++++-- .../sveltekit/src/mocks/app/stores.ts | 8 ++- .../Stores.svelte | 2 + .../Stores.svelte | 2 + 4 files changed, 57 insertions(+), 4 deletions(-) diff --git a/code/frameworks/sveltekit/README.md b/code/frameworks/sveltekit/README.md index fd103c8764b1..45ba57592377 100644 --- a/code/frameworks/sveltekit/README.md +++ b/code/frameworks/sveltekit/README.md @@ -26,10 +26,10 @@ However SvelteKit has some [Kit-specific modules](https://kit.svelte.dev/docs/mo | **Module** | **Status** | **Note** | | ---------------------------------------------------------------------------------- | ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | [`$app/environment`](https://kit.svelte.dev/docs/modules#$app-environment) | āœ… Supported | `version` is always empty in Storybook. | -| [`$app/forms`](https://kit.svelte.dev/docs/modules#$app-forms) | ā³ Future | Will use mocks. Tracked in [#20999](https://github.com/storybookjs/storybook/issues/20999) | -| [`$app/navigation`](https://kit.svelte.dev/docs/modules#$app-navigation) | ā³ Future | Will use mocks. Tracked in [#20999](https://github.com/storybookjs/storybook/issues/20999) | +| [`$app/forms`](https://kit.svelte.dev/docs/modules#$app-forms) | āœ… Supported | See [How to mock](#how-to-mock) | +| [`$app/navigation`](https://kit.svelte.dev/docs/modules#$app-navigation) | āœ… Supported | See [How to mock](#how-to-mock) | | [`$app/paths`](https://kit.svelte.dev/docs/modules#$app-paths) | āœ… Supported | Requires SvelteKit 1.4.0 or newer | -| [`$app/stores`](https://kit.svelte.dev/docs/modules#$app-stores) | āœ… Supported | Mocks planned, so you can set different store values per story. | +| [`$app/stores`](https://kit.svelte.dev/docs/modules#$app-stores) | āœ… Supported | See [How to mock](#how-to-mock) | | [`$env/dynamic/private`](https://kit.svelte.dev/docs/modules#$env-dynamic-private) | ā›” Not supported | They are meant to only be available server-side, and Storybook renders all components on the client. | | [`$env/dynamic/public`](https://kit.svelte.dev/docs/modules#$env-dynamic-public) | šŸš§ Partially supported | Only supported in development mode. Storybook is built as a static app with no server-side API so cannot dynamically serve content. | | [`$env/static/private`](https://kit.svelte.dev/docs/modules#$env-static-private) | ā›” Not supported | They are meant to only be available server-side, and Storybook renders all components on the client. | @@ -125,3 +125,46 @@ You'll experience this if anything in your story is importing from `$app/forms` ## Acknowledgements Integrating with SvelteKit would not have been possible if it weren't for the fantastic efforts by the Svelte core team - especially [Ben McCann](https://twitter.com/benjaminmccann) - to make integrations with the wider ecosystem possible. + +## How to mock + +To mock a SvelteKit import you can make use of the `parameters.sveltekit` object either on the `Story`, on the `Template` or on the `Meta` + +```ts +export const MyStory = { + parameters: { + sveltekit: { + stores: { + page: { + data: { + test: 'passed', + }, + }, + navigating: { + route: { + id: '/storybook', + }, + }, + updated: true, + }, + }, + }, +}; +``` + +on this object you can add the name of the module you are mocking (in the example above we are mocking the `stores` module which correspond to `$app/stores`) and than pass the following kind of objects + +| Module | Path in parameters | Kind of objects | +| ----------------------------------------------- | ----------------------------------------------- | -------------------------------------------------------------------------------------------------- | +| import { page } from "$app/stores" | `parameters.sveltekit.stores.page` | A Partial of the page store | +| import { navigating } from "$app/stores" | `parameters.sveltekit.stores.navigating` | A Partial of the navigating store | +| import { updated } from "$app/stores" | `parameters.sveltekit.stores.updated` | A boolean representing the value of updated (you can also access `check()` which will be a noop) | +| import { goto } from "$app/navigation" | `parameters.sveltekit.navigation.goto` | A callback that will be called whenever goto is called | +| import { invalidate } from "$app/navigation" | `parameters.sveltekit.navigation.invalidate` | A callback that will be called whenever invalidate is called | +| import { invalidateAll } from "$app/navigation" | `parameters.sveltekit.navigation.invalidateAll` | A callback that will be called whenever invalidateAll is called | +| import { afterNavigate } from "$app/navigation" | `parameters.sveltekit.navigation.afterNavigate` | An object that will be passed to the afterNavigate function (which will be invoked onMount) called | +| import { enhance } from "$app/forms" | `parameters.sveltekit.forms.enhance` | A callback that will called when a form with `use:enhance` is submitted | + +All the other functions are still exported as `noop` from the mocked modules so that your application will still work. There was no way of make them work in a customizable way. + +Additionally you can pass an object to `parameter.sveltekit.linkOverrides` where the keys are regex representing a link and the values are functions. If you have an `` tag inside your code with the `href` attribute that matches one or more regex the corresponding function will be called. diff --git a/code/frameworks/sveltekit/src/mocks/app/stores.ts b/code/frameworks/sveltekit/src/mocks/app/stores.ts index e291f4d42ca1..56c9babaf93d 100644 --- a/code/frameworks/sveltekit/src/mocks/app/stores.ts +++ b/code/frameworks/sveltekit/src/mocks/app/stores.ts @@ -17,7 +17,13 @@ function createMockedStore(contextName: string) { export const [page, setPage] = createMockedStore('page-ctx'); export const [navigating, setNavigating] = createMockedStore('navigating-ctx'); -export const [updated, setUpdated] = createMockedStore('updated-ctx'); +const [updated, setUpdated] = createMockedStore('updated-ctx'); + +Object.defineProperty(updated, 'check', { + value: () => {}, +}); + +export { updated, setUpdated }; export function getStores() { return { diff --git a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/Stores.svelte b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/Stores.svelte index 479239610a6b..164b00f7fa8b 100644 --- a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/Stores.svelte +++ b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/Stores.svelte @@ -2,6 +2,8 @@ import { page, navigating, updated, getStores } from '$app/stores'; let { navigating: navigatingStore, page: pageStore, updated: updatedStore } = getStores(); + + updated.check();

Directly importing

diff --git a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/Stores.svelte b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/Stores.svelte index 479239610a6b..164b00f7fa8b 100644 --- a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/Stores.svelte +++ b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/Stores.svelte @@ -2,6 +2,8 @@ import { page, navigating, updated, getStores } from '$app/stores'; let { navigating: navigatingStore, page: pageStore, updated: updatedStore } = getStores(); + + updated.check();

Directly importing

From e184135475d78e3c00ebe718fd7510aa99d4dcb5 Mon Sep 17 00:00:00 2001 From: paoloricciuti Date: Fri, 10 Nov 2023 20:56:28 +0100 Subject: [PATCH 036/170] add components to files --- code/frameworks/sveltekit/package.json | 1 - 1 file changed, 1 deletion(-) diff --git a/code/frameworks/sveltekit/package.json b/code/frameworks/sveltekit/package.json index afa20320e9b7..5bcb60c7d5ed 100644 --- a/code/frameworks/sveltekit/package.json +++ b/code/frameworks/sveltekit/package.json @@ -54,7 +54,6 @@ "README.md", "*.js", "*.d.ts", - "!src/**/*", "src/components/**/*" ], "scripts": { From adc9704dfcb40bc1c04ad763ab6170d428400000 Mon Sep 17 00:00:00 2001 From: paoloricciuti Date: Fri, 10 Nov 2023 21:14:44 +0100 Subject: [PATCH 037/170] add mocks files to files --- code/frameworks/sveltekit/package.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/code/frameworks/sveltekit/package.json b/code/frameworks/sveltekit/package.json index 5bcb60c7d5ed..fe6bffb011fd 100644 --- a/code/frameworks/sveltekit/package.json +++ b/code/frameworks/sveltekit/package.json @@ -54,7 +54,8 @@ "README.md", "*.js", "*.d.ts", - "src/components/**/*" + "src/components/**/*", + "src/mocks/**/*" ], "scripts": { "check": "../../../scripts/prepare/check.ts", From dddc1c9363a0e2604b89d23b4cd9c8feca91aa08 Mon Sep 17 00:00:00 2001 From: paoloricciuti Date: Fri, 10 Nov 2023 21:48:40 +0100 Subject: [PATCH 038/170] remove logs + fix afternavigate tests --- .../sveltekit/src/components/SvelteDecorator.svelte | 1 - code/frameworks/sveltekit/src/mocks/app/navigation.ts | 4 +++- .../stories_svelte-kit-skeleton-js/Navigation.svelte | 5 +++-- .../stories_svelte-kit-skeleton-js/navigation.stories.js | 1 - .../stories_svelte-kit-skeleton-ts/navigation.stories.js | 1 - 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/code/frameworks/sveltekit/src/components/SvelteDecorator.svelte b/code/frameworks/sveltekit/src/components/SvelteDecorator.svelte index 025ec47e2074..04654a64e3a5 100644 --- a/code/frameworks/sveltekit/src/components/SvelteDecorator.svelte +++ b/code/frameworks/sveltekit/src/components/SvelteDecorator.svelte @@ -30,7 +30,6 @@ for(let func of functions){ if(ctx?.parameters?.sveltekit?.[baseModule]?.[func] && ctx.parameters.sveltekit[baseModule][func] instanceof Function){ const listener = ({ detail = [] })=>{ - console.log("event", func, ctx); const args = Array.isArray(detail) ? detail : []; ctx.parameters.sveltekit[baseModule][func](...args); } diff --git a/code/frameworks/sveltekit/src/mocks/app/navigation.ts b/code/frameworks/sveltekit/src/mocks/app/navigation.ts index aeaf586ae0ca..8d23ddbea46a 100644 --- a/code/frameworks/sveltekit/src/mocks/app/navigation.ts +++ b/code/frameworks/sveltekit/src/mocks/app/navigation.ts @@ -14,7 +14,9 @@ export function setAfterNavigateArgument(afterNavigateArgs: any) { export function afterNavigate(cb: any) { const argument = getContext('after-navigate-args'); onMount(() => { - cb(argument); + if (cb && cb instanceof Function) { + cb(argument); + } }); } diff --git a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/Navigation.svelte b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/Navigation.svelte index d97b6fe8a2df..f857ae36a843 100644 --- a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/Navigation.svelte +++ b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/Navigation.svelte @@ -2,8 +2,9 @@ import { goto, invalidate, invalidateAll, afterNavigate } from '$app/navigation'; export let afterNavigateFn; - - afterNavigate(afterNavigateFn); + if(afterNavigateFn){ + afterNavigate(afterNavigateFn); + } ); }; - -Button.propTypes = { - /** - * Is this the principal call to action on the page? - */ - primary: PropTypes.bool, - /** - * What background color to use - */ - backgroundColor: PropTypes.string, - /** - * How large should the button be? - */ - size: PropTypes.oneOf(['small', 'medium', 'large']), - /** - * Button contents - */ - label: PropTypes.string.isRequired, - /** - * Optional click handler - */ - onClick: PropTypes.func, -}; - -Button.defaultProps = { - backgroundColor: null, - primary: false, - size: 'medium', - onClick: undefined, -}; diff --git a/code/renderers/preact/template/cli/Header.jsx b/code/renderers/preact/template/cli/Header.jsx index 8a722e57d331..c87a04c4837e 100644 --- a/code/renderers/preact/template/cli/Header.jsx +++ b/code/renderers/preact/template/cli/Header.jsx @@ -1,9 +1,16 @@ -import PropTypes from 'prop-types'; - import { Button } from './Button'; import './header.css'; -export const Header = ({ user, onLogin, onLogout, onCreateAccount }) => ( +/** + * Header component + * @param {object} props + * @param {object} [props.user] + * @param {string} props.user.name + * @param {function} props.onLogin + * @param {function} props.onLogout + * @param {function} props.onCreateAccount + */ +export const Header = ({ user = null, onLogin, onLogout, onCreateAccount }) => (
@@ -43,16 +50,3 @@ export const Header = ({ user, onLogin, onLogout, onCreateAccount }) => (
); - -Header.propTypes = { - user: PropTypes.shape({ - name: PropTypes.string.isRequired, - }), - onLogin: PropTypes.func.isRequired, - onLogout: PropTypes.func.isRequired, - onCreateAccount: PropTypes.func.isRequired, -}; - -Header.defaultProps = { - user: null, -}; diff --git a/code/renderers/preact/template/cli/Page.jsx b/code/renderers/preact/template/cli/Page.jsx index 12ca119d0b04..a5bc82d9d105 100644 --- a/code/renderers/preact/template/cli/Page.jsx +++ b/code/renderers/preact/template/cli/Page.jsx @@ -2,6 +2,9 @@ import { useState } from 'preact/hooks'; import { Header } from './Header'; import './page.css'; +/** + * Simple page component + */ export const Page = () => { const [user, setUser] = useState(); diff --git a/code/renderers/preact/template/components/Button.jsx b/code/renderers/preact/template/components/Button.jsx index cd3c13987c32..e79f89f5d4b3 100644 --- a/code/renderers/preact/template/components/Button.jsx +++ b/code/renderers/preact/template/components/Button.jsx @@ -1,14 +1,11 @@ -/* eslint-disable react/react-in-jsx-scope */ -// eslint-disable-next-line import/no-extraneous-dependencies -import PropTypes from 'prop-types'; - +/** + * Button component + * @param {object} props + * @param {string} props.label + * @param {function} props.onClick + */ export const Button = ({ onClick, label }) => ( ); - -Button.propTypes = { - onClick: PropTypes.func.isRequired, - label: PropTypes.node.isRequired, -}; diff --git a/code/renderers/preact/template/components/Form.jsx b/code/renderers/preact/template/components/Form.jsx index fb58cbb10508..b2283d26ac10 100644 --- a/code/renderers/preact/template/components/Form.jsx +++ b/code/renderers/preact/template/components/Form.jsx @@ -1,8 +1,14 @@ -/* eslint-disable react/react-in-jsx-scope */ -// eslint-disable-next-line import/no-extraneous-dependencies -import PropTypes from 'prop-types'; import { useState } from 'preact/hooks'; +/** + * Header component + * @param {object} props + * @param {object} [props.user] + * @param {string} props.user.name + * @param {function} props.onLogin + * @param {function} props.onLogout + * @param {function} props.onCreateAccount + */ export const Form = ({ onSuccess }) => { const [value, setValue] = useState(''); const [complete, setComplete] = useState(false); @@ -32,7 +38,3 @@ export const Form = ({ onSuccess }) => { ); }; - -Form.propTypes = { - onSuccess: PropTypes.func.isRequired, -}; diff --git a/code/renderers/preact/template/components/Html.jsx b/code/renderers/preact/template/components/Html.jsx index 36cff8218890..b2c1f966f9e3 100644 --- a/code/renderers/preact/template/components/Html.jsx +++ b/code/renderers/preact/template/components/Html.jsx @@ -1,10 +1 @@ -/* eslint-disable react/react-in-jsx-scope */ -// eslint-disable-next-line import/no-extraneous-dependencies -import PropTypes from 'prop-types'; - -// eslint-disable-next-line react/no-danger export const Html = ({ content }) =>
; - -Html.propTypes = { - content: PropTypes.string.isRequired, -}; diff --git a/code/renderers/preact/template/components/Pre.jsx b/code/renderers/preact/template/components/Pre.jsx index 7efec93be9d6..3bf143581fac 100644 --- a/code/renderers/preact/template/components/Pre.jsx +++ b/code/renderers/preact/template/components/Pre.jsx @@ -1,21 +1,12 @@ -/* eslint-disable react/react-in-jsx-scope */ -// eslint-disable-next-line import/no-extraneous-dependencies -import PropTypes from 'prop-types'; - +/** + * Pre component + * @param {object} props + * @param {object} [props.style] + * @param {object} [props.object] + * @param {string} [props.text] + */ export const Pre = ({ style, object, text }) => (
     {object ? JSON.stringify(object, null, 2) : text}
   
); - -Pre.propTypes = { - style: PropTypes.shape({}), - object: PropTypes.shape({}), - text: PropTypes.string, -}; - -Pre.defaultProps = { - style: {}, - object: null, - text: '', -}; diff --git a/code/renderers/preact/template/stories/React.js b/code/renderers/preact/template/stories/React.js index 0c72668ebe74..1d1fa97c55d8 100644 --- a/code/renderers/preact/template/stories/React.js +++ b/code/renderers/preact/template/stories/React.js @@ -1,8 +1,11 @@ // eslint-disable-next-line import/no-extraneous-dependencies import React from 'react'; -// eslint-disable-next-line import/no-extraneous-dependencies -import PropTypes from 'prop-types'; +/** + * ReactFunctionalComponent component + * @param {object} props + * @param {string} props.label + */ export const ReactFunctionalComponent = ({ label }) => { const [clicks, setValue] = React.useState(0); return ( @@ -19,10 +22,11 @@ export const ReactFunctionalComponent = ({ label }) => { ); }; -ReactFunctionalComponent.propTypes = { - label: PropTypes.string.isRequired, -}; - +/** + * ReactClassComponent component + * @param {object} props + * @param {string} props.label + */ export class ReactClassComponent extends React.Component { state = { clicks: 0, @@ -45,7 +49,3 @@ export class ReactClassComponent extends React.Component { ); } } - -ReactClassComponent.propTypes = { - label: PropTypes.string.isRequired, -}; diff --git a/code/renderers/preact/template/stories/react-compat.stories.js b/code/renderers/preact/template/stories/react-compat.stories.js index b7895c1e8d0f..33f1078d3154 100644 --- a/code/renderers/preact/template/stories/react-compat.stories.js +++ b/code/renderers/preact/template/stories/react-compat.stories.js @@ -1,4 +1,3 @@ -/* eslint-disable react/react-in-jsx-scope */ import { ReactFunctionalComponent, ReactClassComponent } from './React'; export default { diff --git a/code/renderers/svelte/package.json b/code/renderers/svelte/package.json index ddd73d9a38e0..3d28936a3e6b 100644 --- a/code/renderers/svelte/package.json +++ b/code/renderers/svelte/package.json @@ -59,6 +59,7 @@ "@storybook/preview-api": "workspace:*", "@storybook/types": "workspace:*", "sveltedoc-parser": "^4.2.1", + "ts-dedent": "^2.0.0", "type-fest": "~2.19" }, "devDependencies": { diff --git a/code/ui/manager/package.json b/code/ui/manager/package.json index 0278119e1f00..7372f1f136f9 100644 --- a/code/ui/manager/package.json +++ b/code/ui/manager/package.json @@ -24,12 +24,17 @@ "types": "./dist/index.d.ts", "import": "./dist/index.js" }, - "./dist/runtime": { + "./runtime": { "types": "./dist/runtime.d.ts", "import": "./dist/runtime.js" }, - "./dist/globals": { + "./globals-module-info": { + "types": "./dist/globals-module-info.d.ts", + "require": "./dist/globals-module-info.js" + }, + "./globals": { "types": "./dist/globals.d.ts", + "import": "./dist/globals.js", "require": "./dist/globals.js" }, "./paths": "./paths.js", @@ -38,6 +43,22 @@ "main": "dist/index.js", "module": "dist/index.js", "types": "dist/index.d.ts", + "typesVersions": { + "*": { + "*": [ + "dist/index.d.ts" + ], + "runtime": [ + "dist/runtime.d.ts" + ], + "globals": [ + "dist/globals.d.ts" + ], + "globals-module-info": [ + "dist/globals-module-info.d.ts" + ] + } + }, "files": [ "dist/**/*", "static/**/*", @@ -97,7 +118,8 @@ "./src/runtime.ts" ], "nodeEntries": [ - "./src/globals.ts" + "./src/globals.ts", + "./src/globals-module-info.ts" ] }, "gitHead": "e6a7fd8a655c69780bc20b9749c2699e44beae17" diff --git a/code/ui/manager/scripts/generate-exports-file.ts b/code/ui/manager/scripts/generate-exports-file.ts index afdbea8ff6e6..ece5ac50391b 100644 --- a/code/ui/manager/scripts/generate-exports-file.ts +++ b/code/ui/manager/scripts/generate-exports-file.ts @@ -3,7 +3,7 @@ import fs from 'fs-extra'; import path from 'path'; import { dedent } from 'ts-dedent'; import { ESLint } from '../../../../scripts/node_modules/eslint'; -import { values } from '../src/globals/runtime'; +import { globalsNameValueMap } from '../src/globals/runtime'; const location = path.join(__dirname, '..', 'src', 'globals', 'exports.ts'); let attempts = 0; @@ -29,10 +29,13 @@ async function generate(text: string) { } const run = async () => { - const data = Object.entries(values).reduce>((acc, [key, value]) => { - acc[key] = Object.keys(value).filter(removeDefault); - return acc; - }, {}); + const data = Object.entries(globalsNameValueMap).reduce>( + (acc, [key, value]) => { + acc[key] = Object.keys(value).filter(removeDefault); + return acc; + }, + {} + ); console.log('Generating...'); diff --git a/code/ui/manager/src/globals-module-info.ts b/code/ui/manager/src/globals-module-info.ts new file mode 100644 index 000000000000..4bcbf259af79 --- /dev/null +++ b/code/ui/manager/src/globals-module-info.ts @@ -0,0 +1 @@ +export * from './globals/globals-module-info'; diff --git a/code/ui/manager/src/globals.ts b/code/ui/manager/src/globals.ts index d516acc55516..3b9b2321b6f0 100644 --- a/code/ui/manager/src/globals.ts +++ b/code/ui/manager/src/globals.ts @@ -1 +1 @@ -export * from './globals/definitions'; +export * from './globals/globals'; diff --git a/code/ui/manager/src/globals/exports.ts b/code/ui/manager/src/globals/exports.ts index ef2523f0e06a..f56ba153dd82 100644 --- a/code/ui/manager/src/globals/exports.ts +++ b/code/ui/manager/src/globals/exports.ts @@ -278,4 +278,5 @@ export default { ], '@storybook/addons': ['addons', 'types', 'mockChannel'], '@storybook/client-logger': ['deprecate', 'logger', 'once', 'pretty'], + '@storybook/types': ['Addon_TypesEnum'], } as const; diff --git a/code/ui/manager/src/globals/definitions.ts b/code/ui/manager/src/globals/globals-module-info.ts similarity index 65% rename from code/ui/manager/src/globals/definitions.ts rename to code/ui/manager/src/globals/globals-module-info.ts index 9122fca70262..616148e80ca4 100644 --- a/code/ui/manager/src/globals/definitions.ts +++ b/code/ui/manager/src/globals/globals-module-info.ts @@ -1,7 +1,6 @@ import type { ModuleInfo } from '@fal-works/esbuild-plugin-global-externals'; import Exports from './exports'; -import { Keys } from './types'; -import type { Definitions } from './types'; +import { globalPackages, globalsNameReferenceMap } from './globals'; /* * We create a map of a module's name to a ModuleInfo. @@ -18,18 +17,16 @@ import type { Definitions } from './types'; * * If you forget to do either, TypeScript will complain. * - * This `definitions.ts` file is consumed by the `builder-manager` package, + * This `globals-module-info.ts` file is consumed by the `builder-manager` package, * The `runtime.ts` file is used inside the manager's browser code runtime. */ -const createModuleInfo = (m: keyof typeof Keys): Required => ({ - type: 'esm', - varName: Keys[m], - namedExports: Exports[m], - defaultExport: true, -}); - -export const definitions = Object.keys(Keys).reduce((acc, key) => { - acc[key as keyof typeof Keys] = createModuleInfo(key as keyof typeof Keys); +export const globalsModuleInfoMap = globalPackages.reduce((acc, key) => { + acc[key] = { + type: 'esm', + varName: globalsNameReferenceMap[key], + namedExports: Exports[key], + defaultExport: true, + }; return acc; -}, {} as Definitions); +}, {} as Required>>); diff --git a/code/ui/manager/src/globals/globals.ts b/code/ui/manager/src/globals/globals.ts new file mode 100644 index 000000000000..1ef93c38bc94 --- /dev/null +++ b/code/ui/manager/src/globals/globals.ts @@ -0,0 +1,19 @@ +// Here we map the name of a module to their REFERENCE in the global scope. +export const globalsNameReferenceMap = { + react: '__REACT__', + 'react-dom': '__REACT_DOM__', + '@storybook/components': '__STORYBOOK_COMPONENTS__', + '@storybook/channels': '__STORYBOOK_CHANNELS__', + '@storybook/core-events': '__STORYBOOK_CORE_EVENTS__', + '@storybook/router': '__STORYBOOK_ROUTER__', + '@storybook/theming': '__STORYBOOK_THEMING__', + '@storybook/api': '__STORYBOOK_API__', // deprecated, remove in 8.0 + '@storybook/manager-api': '__STORYBOOK_API__', + '@storybook/addons': '__STORYBOOK_ADDONS__', + '@storybook/client-logger': '__STORYBOOK_CLIENT_LOGGER__', + '@storybook/types': '__STORYBOOK_TYPES__', +} as const; + +export const globalPackages = Object.keys(globalsNameReferenceMap) as Array< + keyof typeof globalsNameReferenceMap +>; diff --git a/code/ui/manager/src/globals/runtime.ts b/code/ui/manager/src/globals/runtime.ts index 5850699f171d..59f5f8fc1a09 100644 --- a/code/ui/manager/src/globals/runtime.ts +++ b/code/ui/manager/src/globals/runtime.ts @@ -1,32 +1,34 @@ import * as REACT from 'react'; -import * as REACTDOM from 'react-dom'; +import * as REACT_DOM from 'react-dom'; -import * as STORYBOOKCOMPONENTS from '@storybook/components'; -import * as STORYBOOKCHANNELS from '@storybook/channels'; -import * as STORYBOOKEVENTS from '@storybook/core-events'; -import * as STORYBOOKROUTER from '@storybook/router'; -import * as STORYBOOKTHEMING from '@storybook/theming'; -import * as STORYBOOKMANAGERAPI from '@storybook/manager-api'; -import * as STORYBOOKCLIENTLOGGER from '@storybook/client-logger'; +import * as COMPONENTS from '@storybook/components'; +import * as CHANNELS from '@storybook/channels'; +import * as EVENTS from '@storybook/core-events'; +import * as ROUTER from '@storybook/router'; +import * as THEMING from '@storybook/theming'; +import * as MANAGER_API from '@storybook/manager-api'; +import * as TYPES from '@storybook/types'; +import * as CLIENT_LOGGER from '@storybook/client-logger'; -import type { Keys } from './types'; +import type { globalsNameReferenceMap } from './globals'; // Here we map the name of a module to their VALUE in the global scope. -export const values: Required> = { - react: REACT as any, - 'react-dom': REACTDOM, - '@storybook/components': STORYBOOKCOMPONENTS, - '@storybook/channels': STORYBOOKCHANNELS, - '@storybook/core-events': STORYBOOKEVENTS, - '@storybook/router': STORYBOOKROUTER, - '@storybook/theming': STORYBOOKTHEMING, - '@storybook/api': STORYBOOKMANAGERAPI, // deprecated, remove in 8.0 - '@storybook/manager-api': STORYBOOKMANAGERAPI, +export const globalsNameValueMap: Required> = { + react: REACT, + 'react-dom': REACT_DOM, + '@storybook/components': COMPONENTS, + '@storybook/channels': CHANNELS, + '@storybook/core-events': EVENTS, + '@storybook/router': ROUTER, + '@storybook/theming': THEMING, + '@storybook/api': MANAGER_API, // deprecated, remove in 8.0 + '@storybook/manager-api': MANAGER_API, // backwards compatibility '@storybook/addons': { - addons: STORYBOOKMANAGERAPI.addons, - types: STORYBOOKMANAGERAPI.types, - mockChannel: STORYBOOKMANAGERAPI.mockChannel, + addons: MANAGER_API.addons, + types: MANAGER_API.types, + mockChannel: MANAGER_API.mockChannel, }, - '@storybook/client-logger': STORYBOOKCLIENTLOGGER, + '@storybook/client-logger': CLIENT_LOGGER, + '@storybook/types': TYPES, }; diff --git a/code/ui/manager/src/globals/types.ts b/code/ui/manager/src/globals/types.ts deleted file mode 100644 index 2861e45f632a..000000000000 --- a/code/ui/manager/src/globals/types.ts +++ /dev/null @@ -1,18 +0,0 @@ -import type { ModuleInfo } from '@fal-works/esbuild-plugin-global-externals'; - -// Here we map the name of a module to their NAME in the global scope. -export enum Keys { - 'react' = '__REACT__', - 'react-dom' = '__REACTDOM__', - '@storybook/components' = '__STORYBOOKCOMPONENTS__', - '@storybook/channels' = '__STORYBOOKCHANNELS__', - '@storybook/core-events' = '__STORYBOOKCOREEVENTS__', - '@storybook/router' = '__STORYBOOKROUTER__', - '@storybook/theming' = '__STORYBOOKTHEMING__', - '@storybook/api' = '__STORYBOOKAPI__', // deprecated, remove in 8.0 - '@storybook/manager-api' = '__STORYBOOKAPI__', - '@storybook/addons' = '__STORYBOOKADDONS__', - '@storybook/client-logger' = '__STORYBOOKCLIENTLOGGER__', -} - -export type Definitions = Required>>; diff --git a/code/ui/manager/src/runtime.ts b/code/ui/manager/src/runtime.ts index efa348ac47e0..f66bde4de3d3 100644 --- a/code/ui/manager/src/runtime.ts +++ b/code/ui/manager/src/runtime.ts @@ -9,8 +9,8 @@ import { CHANNEL_CREATED, TELEMETRY_ERROR } from '@storybook/core-events'; import Provider from './provider'; import { renderStorybookUI } from './index'; -import { values } from './globals/runtime'; -import { Keys } from './globals/types'; +import { globalsNameValueMap } from './globals/runtime'; +import { globalPackages, globalsNameReferenceMap } from './globals/globals'; import { prepareForTelemetry, shouldSkipError } from './utils/prepareForTelemetry'; const { FEATURES, CONFIG_TYPE } = global; @@ -58,8 +58,8 @@ class ReactProvider extends Provider { } // Apply all the globals -Object.keys(Keys).forEach((key: keyof typeof Keys) => { - global[Keys[key]] = values[key]; +globalPackages.forEach((key) => { + global[globalsNameReferenceMap[key]] = globalsNameValueMap[key]; }); global.sendTelemetryError = (error) => { diff --git a/code/ui/manager/src/typings.d.ts b/code/ui/manager/src/typings.d.ts index 2ff3df07e63e..bce29ea466a7 100644 --- a/code/ui/manager/src/typings.d.ts +++ b/code/ui/manager/src/typings.d.ts @@ -15,15 +15,15 @@ declare var VERSIONCHECK: any; declare var LOGLEVEL: 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'silent' | undefined; declare var __REACT__: any; -declare var __REACTDOM__: any; -declare var __STORYBOOKCOMPONENTS__: any; -declare var __STORYBOOKCOMPONENTSEXPERIMENTAL__: any; -declare var __STORYBOOKCHANNELS__: any; -declare var __STORYBOOKCOREEVENTS__: any; -declare var __STORYBOOKROUTER__: any; -declare var __STORYBOOKTHEMING__: any; -declare var __STORYBOOKAPI__: any; -declare var __STORYBOOKADDONS__: any; -declare var __STORYBOOKCLIENTLOGGER__: any; +declare var __REACT_DOM__: any; +declare var __STORYBOOK_COMPONENTS__: any; +declare var __STORYBOOK_CHANNELS__: any; +declare var __STORYBOOK_CORE_EVENTS__: any; +declare var __STORYBOOK_ROUTER__: any; +declare var __STORYBOOK_THEMING__: any; +declare var __STORYBOOK_API__: any; +declare var __STORYBOOK_ADDONS__: any; +declare var __STORYBOOK_CLIENT_LOGGER__: any; declare var __STORYBOOK_ADDONS_CHANNEL__: any; +declare var __STORYBOOK_TYPES__: any; declare var sendTelemetryError: (error: any) => void; diff --git a/code/yarn.lock b/code/yarn.lock index ce57e7431391..6cc2650da012 100644 --- a/code/yarn.lock +++ b/code/yarn.lock @@ -5345,7 +5345,6 @@ __metadata: "@storybook/channels": "workspace:*" "@storybook/client-logger": "workspace:*" "@storybook/components": "workspace:*" - "@storybook/core-events": "workspace:*" "@storybook/global": "npm:^5.0.0" "@storybook/manager-api": "workspace:*" "@storybook/preview-api": "workspace:*" @@ -5354,17 +5353,11 @@ __metadata: "@testing-library/react": "npm:^11.2.2" axe-core: "npm:^4.2.0" lodash: "npm:^4.17.21" + react: "npm:^16.8.0" + react-dom: "npm:^16.8.0" react-resize-detector: "npm:^7.1.2" resize-observer-polyfill: "npm:^1.5.1" typescript: "npm:~4.9.3" - peerDependencies: - react: ^16.8.0 || ^17.0.0 || ^18.0.0 - react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 - peerDependenciesMeta: - react: - optional: true - react-dom: - optional: true languageName: unknown linkType: soft @@ -5386,19 +5379,13 @@ __metadata: lodash: "npm:^4.17.21" polished: "npm:^4.2.2" prop-types: "npm:^15.7.2" + react: "npm:^16.8.0" + react-dom: "npm:^16.8.0" react-inspector: "npm:^6.0.0" telejson: "npm:^7.2.0" ts-dedent: "npm:^2.0.0" typescript: "npm:~4.9.3" uuid: "npm:^9.0.0" - peerDependencies: - react: ^16.8.0 || ^17.0.0 || ^18.0.0 - react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 - peerDependenciesMeta: - react: - optional: true - react-dom: - optional: true languageName: unknown linkType: soft @@ -5408,23 +5395,16 @@ __metadata: dependencies: "@storybook/client-logger": "workspace:*" "@storybook/components": "workspace:*" - "@storybook/core-events": "workspace:*" "@storybook/global": "npm:^5.0.0" "@storybook/manager-api": "workspace:*" "@storybook/preview-api": "workspace:*" "@storybook/theming": "workspace:*" "@storybook/types": "workspace:*" memoizerific: "npm:^1.11.3" + react: "npm:^16.8.0" + react-dom: "npm:^16.8.0" ts-dedent: "npm:^2.0.0" typescript: "npm:~4.9.3" - peerDependencies: - react: ^16.8.0 || ^17.0.0 || ^18.0.0 - react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 - peerDependenciesMeta: - react: - optional: true - react-dom: - optional: true languageName: unknown linkType: soft @@ -5436,22 +5416,15 @@ __metadata: "@storybook/client-logger": "workspace:*" "@storybook/components": "workspace:*" "@storybook/core-common": "workspace:*" - "@storybook/core-events": "workspace:*" "@storybook/manager-api": "workspace:*" "@storybook/node-logger": "workspace:*" "@storybook/preview-api": "workspace:*" "@storybook/theming": "workspace:*" "@storybook/types": "workspace:*" lodash: "npm:^4.17.21" + react: "npm:^16.8.0" + react-dom: "npm:^16.8.0" ts-dedent: "npm:^2.0.0" - peerDependencies: - react: ^16.8.0 || ^17.0.0 || ^18.0.0 - react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 - peerDependenciesMeta: - react: - optional: true - react-dom: - optional: true languageName: unknown linkType: soft @@ -5571,16 +5544,10 @@ __metadata: formik: "npm:^2.2.9" jest-mock: "npm:^27.0.6" polished: "npm:^4.2.2" + react: "npm:^16.8.0" + react-dom: "npm:^16.8.0" ts-dedent: "npm:^2.2.0" typescript: "npm:~4.9.3" - peerDependencies: - react: ^16.8.0 || ^17.0.0 || ^18.0.0 - react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 - peerDependenciesMeta: - react: - optional: true - react-dom: - optional: true languageName: unknown linkType: soft @@ -5595,18 +5562,13 @@ __metadata: "@storybook/manager-api": "workspace:*" "@storybook/preview-api": "workspace:*" "@storybook/theming": "workspace:*" + react: "npm:^16.8.0" + react-dom: "npm:^16.8.0" react-resize-detector: "npm:^7.1.2" tiny-invariant: "npm:^1.3.1" + ts-dedent: "npm:^2.0.0" typescript: "npm:~4.9.3" upath: "npm:^2.0.1" - peerDependencies: - react: ^16.8.0 || ^17.0.0 || ^18.0.0 - react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 - peerDependenciesMeta: - react: - optional: true - react-dom: - optional: true languageName: unknown linkType: soft @@ -5623,17 +5585,13 @@ __metadata: "@storybook/router": "workspace:*" "@storybook/types": "workspace:*" fs-extra: "npm:^11.1.0" - prop-types: "npm:^15.7.2" ts-dedent: "npm:^2.0.0" typescript: "npm:~4.9.3" peerDependencies: react: ^16.8.0 || ^17.0.0 || ^18.0.0 - react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 peerDependenciesMeta: react: optional: true - react-dom: - optional: true languageName: unknown linkType: soft @@ -5659,16 +5617,10 @@ __metadata: "@storybook/manager-api": "workspace:*" "@storybook/preview-api": "workspace:*" "@storybook/types": "workspace:*" + react: "npm:^16.8.0" + react-dom: "npm:^16.8.0" tiny-invariant: "npm:^1.3.1" typescript: "npm:~4.9.3" - peerDependencies: - react: ^16.8.0 || ^17.0.0 || ^18.0.0 - react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 - peerDependenciesMeta: - react: - optional: true - react-dom: - optional: true languageName: unknown linkType: soft @@ -5683,16 +5635,10 @@ __metadata: "@storybook/manager-api": "workspace:*" "@storybook/preview-api": "workspace:*" "@storybook/types": "workspace:*" + react: "npm:^16.8.0" + react-dom: "npm:^16.8.0" ts-dedent: "npm:^2.0.0" typescript: "npm:~4.9.3" - peerDependencies: - react: ^16.8.0 || ^17.0.0 || ^18.0.0 - react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 - peerDependenciesMeta: - react: - optional: true - react-dom: - optional: true languageName: unknown linkType: soft @@ -5820,18 +5766,11 @@ __metadata: "@types/react": "npm:^16.14.34" "@types/react-syntax-highlighter": "npm:11.0.5" estraverse: "npm:^5.2.0" - prop-types: "npm:^15.7.2" + react: "npm:^16.8.0" + react-dom: "npm:^16.8.0" react-syntax-highlighter: "npm:^15.5.0" tiny-invariant: "npm:^1.3.1" typescript: "npm:~4.9.3" - peerDependencies: - react: ^16.8.0 || ^17.0.0 || ^18.0.0 - react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 - peerDependenciesMeta: - react: - optional: true - react-dom: - optional: true languageName: unknown linkType: soft @@ -5848,14 +5787,6 @@ __metadata: "@storybook/types": "workspace:*" ts-dedent: "npm:^2.0.0" typescript: "npm:~4.9.3" - peerDependencies: - react: ^16.8.0 || ^17.0.0 || ^18.0.0 - react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 - peerDependenciesMeta: - react: - optional: true - react-dom: - optional: true languageName: unknown linkType: soft @@ -5868,15 +5799,9 @@ __metadata: "@storybook/manager-api": "workspace:*" "@storybook/preview-api": "workspace:*" "@storybook/theming": "workspace:*" + react: "npm:^16.8.0" + react-dom: "npm:^16.8.0" typescript: "npm:~4.9.3" - peerDependencies: - react: ^16.8.0 || ^17.0.0 || ^18.0.0 - react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 - peerDependenciesMeta: - react: - optional: true - react-dom: - optional: true languageName: unknown linkType: soft @@ -5892,16 +5817,9 @@ __metadata: "@storybook/preview-api": "workspace:*" "@storybook/theming": "workspace:*" memoizerific: "npm:^1.11.3" - prop-types: "npm:^15.7.2" + react: "npm:^16.8.0" + react-dom: "npm:^16.8.0" typescript: "npm:~4.9.3" - peerDependencies: - react: ^16.8.0 || ^17.0.0 || ^18.0.0 - react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 - peerDependenciesMeta: - react: - optional: true - react-dom: - optional: true languageName: unknown linkType: soft @@ -5912,9 +5830,6 @@ __metadata: "@storybook/manager-api": "workspace:*" "@storybook/preview-api": "workspace:*" "@storybook/types": "workspace:*" - peerDependencies: - react: ^16.8.0 || ^17.0.0 || ^18.0.0 - react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 languageName: unknown linkType: soft @@ -5943,7 +5858,6 @@ __metadata: "@storybook/core-webpack": "workspace:*" "@storybook/docs-tools": "workspace:*" "@storybook/global": "npm:^5.0.0" - "@storybook/manager-api": "workspace:*" "@storybook/node-logger": "workspace:*" "@storybook/preview-api": "workspace:*" "@storybook/telemetry": "workspace:*" @@ -5983,8 +5897,6 @@ __metadata: "@angular/platform-browser": ">=14.1.0 < 18.0.0" "@angular/platform-browser-dynamic": ">=14.1.0 < 18.0.0" "@babel/core": "*" - react: ^16.8.0 || ^17.0.0 || ^18.0.0 - react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 rxjs: ^6.0.0 || ^7.4.0 typescript: ^4.0.0 || ^5.0.0 zone.js: ">= 0.11.1 < 1.0.0" @@ -6000,14 +5912,6 @@ __metadata: dependencies: "@storybook/client-logger": "workspace:*" "@storybook/manager-api": "workspace:*" - peerDependencies: - react: ^16.8.0 || ^17.0.0 || ^18.0.0 - react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 - peerDependenciesMeta: - react: - optional: true - react-dom: - optional: true languageName: unknown linkType: soft @@ -6300,12 +6204,12 @@ __metadata: languageName: unknown linkType: soft -"@storybook/client-logger@npm:7.4.6": - version: 7.4.6 - resolution: "@storybook/client-logger@npm:7.4.6" +"@storybook/client-logger@npm:7.5.0": + version: 7.5.0 + resolution: "@storybook/client-logger@npm:7.5.0" dependencies: "@storybook/global": "npm:^5.0.0" - checksum: 170ad58c17e2608639533fe24aaa96ddd4d77d23b4b28f265b2cb67510fef966fc20b029e070fdc7216ba1cdb724d1210b2f8edc8aa538de32fd6e549f9010cf + checksum: 90326c49a224bf21680c04ffee94725bf75658086093ccb839a8aae39476929c4719eafb18e498a148cf0dd956d4e9a5d3b2a34d09ca4fd25e2af553458558ac languageName: node linkType: hard @@ -6635,8 +6539,6 @@ __metadata: babel-plugin-ember-modules-api-polyfill: ^2.12.0 babel-plugin-htmlbars-inline-precompile: 2 || 3 ember-source: ~3.28.1 - react: ^16.8.0 || ^17.0.0 || ^18.0.0 - react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 languageName: unknown linkType: soft @@ -6695,8 +6597,6 @@ __metadata: typescript: "npm:~4.9.3" peerDependencies: "@babel/core": "*" - react: ^16.8.0 || ^17.0.0 || ^18.0.0 - react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 languageName: unknown linkType: soft @@ -6800,14 +6700,13 @@ __metadata: lodash: "npm:^4.17.21" memoizerific: "npm:^1.11.3" qs: "npm:^6.10.0" + react: "npm:^16.8.0" + react-dom: "npm:^16.8.0" semver: "npm:^7.3.7" store2: "npm:^2.14.2" telejson: "npm:^7.2.0" ts-dedent: "npm:^2.0.0" typescript: "npm:~4.9.3" - peerDependencies: - react: ^16.8.0 || ^17.0.0 || ^18.0.0 - react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 languageName: unknown linkType: soft @@ -6984,8 +6883,6 @@ __metadata: peerDependencies: "@babel/core": "*" preact: ^8.0.0||^10.0.0 - react: ^16.8.0 || ^17.0.0 || ^18.0.0 - react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 languageName: unknown linkType: soft @@ -7209,7 +7106,6 @@ __metadata: lodash: "npm:^4.17.21" memoizerific: "npm:^1.11.3" qs: "npm:^6.10.0" - react: "npm:^16.14.0" slash: "npm:^5.0.0" synchronous-promise: "npm:^2.0.15" ts-dedent: "npm:^2.0.0" @@ -7236,6 +7132,8 @@ __metadata: "@storybook/global": "npm:^5.0.0" "@storybook/preview-api": "workspace:*" browser-dtector: "npm:^3.4.0" + fs-extra: "npm:^11.1.0" + ts-dedent: "npm:^2.0.0" typescript: "npm:~4.9.3" languageName: unknown linkType: soft @@ -7554,12 +7452,11 @@ __metadata: lodash: "npm:^4.17.21" memoizerific: "npm:^1.11.3" qs: "npm:^6.10.0" + react: "npm:^16.8.0" + react-dom: "npm:^16.8.0" react-router-dom: "npm:6.0.2" ts-dedent: "npm:^2.0.0" typescript: "npm:~4.9.3" - peerDependencies: - react: ^16.8.0 || ^17.0.0 || ^18.0.0 - react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 languageName: unknown linkType: soft @@ -7573,9 +7470,6 @@ __metadata: "@storybook/server": "workspace:*" "@types/node": "npm:^18.0.0" typescript: "npm:~4.9.3" - peerDependencies: - react: ^16.8.0 || ^17.0.0 || ^18.0.0 - react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 languageName: unknown linkType: soft @@ -7608,9 +7502,6 @@ __metadata: lodash: "npm:^4.17.21" prettier: "npm:^2.8.0" typescript: "npm:~4.9.3" - peerDependencies: - react: ^16.8.0 || ^17.0.0 || ^18.0.0 - react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 languageName: unknown linkType: soft @@ -7658,8 +7549,6 @@ __metadata: typescript: "npm:~4.9.3" peerDependencies: "@babel/core": "*" - react: ^16.8.0 || ^17.0.0 || ^18.0.0 - react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 svelte: ^3.48.0 || ^4.0.0 svelte-loader: "*" languageName: unknown @@ -7680,6 +7569,7 @@ __metadata: svelte: "npm:^4.0.0" svelte-check: "npm:3.4.6" sveltedoc-parser: "npm:^4.2.1" + ts-dedent: "npm:^2.0.0" type-fest: "npm:~2.19" typescript: "npm:^5.0.4" peerDependencies: @@ -7755,17 +7645,17 @@ __metadata: linkType: hard "@storybook/theming@npm:^7.0.2": - version: 7.4.6 - resolution: "@storybook/theming@npm:7.4.6" + version: 7.5.0 + resolution: "@storybook/theming@npm:7.5.0" dependencies: "@emotion/use-insertion-effect-with-fallbacks": "npm:^1.0.0" - "@storybook/client-logger": "npm:7.4.6" + "@storybook/client-logger": "npm:7.5.0" "@storybook/global": "npm:^5.0.0" memoizerific: "npm:^1.11.3" peerDependencies: react: ^16.8.0 || ^17.0.0 || ^18.0.0 react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 - checksum: 6250a413c346971792623bf5a907811fc009ff4a36b8f292d0f45c677269b2a50c29d84ab1e869ada7df3eb23d49614e1342bd2c88e71d4467702b92ebc42f2d + checksum: 57da8e27c748cbec4dc1661cdd2d449949d97476d8e97933696b31d07c7361cbbcca8d7225cc00ca078daa160023b8965ddec7c23519ce0a4ef2658246b062e7 languageName: node linkType: hard @@ -7823,8 +7713,6 @@ __metadata: vue: "npm:^2.7.10" vue-docgen-api: "npm:^4.40.0" peerDependencies: - react: ^16.8.0 || ^17.0.0 || ^18.0.0 - react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 vite: ^3.0.0 || ^4.0.0 || ^5.0.0 vue: ^2.7.0 languageName: unknown @@ -7847,8 +7735,6 @@ __metadata: "@babel/core": "*" babel-loader: ^7.0.0 || ^8.0.0 || ^9.0.0 css-loader: "*" - react: ^16.8.0 || ^17.0.0 || ^18.0.0 - react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 vue: ^2.6.8 vue-loader: ^15.7.0 vue-template-compiler: ^2.6.8 @@ -7869,8 +7755,6 @@ __metadata: vite: "npm:^4.0.0" vue-docgen-api: "npm:^4.40.0" peerDependencies: - react: ^16.8.0 || ^17.0.0 || ^18.0.0 - react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 vite: ^3.0.0 || ^4.0.0 || ^5.0.0 languageName: unknown linkType: soft @@ -7891,8 +7775,6 @@ __metadata: "@babel/core": "*" "@vue/compiler-sfc": ^3.0.0 babel-loader: ^7.0.0 || ^8.0.0 || ^9.0.0 - react: ^16.8.0 || ^17.0.0 || ^18.0.0 - react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 vue: ^3.0.0 languageName: unknown linkType: soft @@ -7961,9 +7843,6 @@ __metadata: "@types/node": "npm:^18.0.0" magic-string: "npm:^0.30.0" typescript: "npm:~4.9.3" - peerDependencies: - react: ^16.8.0 || ^17.0.0 || ^18.0.0 - react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 languageName: unknown linkType: soft @@ -7981,8 +7860,6 @@ __metadata: typescript: "npm:~4.9.3" peerDependencies: lit: ^2.0.0 || ^3.0.0 - react: ^16.8.0 || ^17.0.0 || ^18.0.0 - react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 languageName: unknown linkType: soft @@ -25779,7 +25656,7 @@ __metadata: languageName: node linkType: hard -"react@npm:^16.14.0": +"react@npm:^16.14.0, react@npm:^16.8.0": version: 16.14.0 resolution: "react@npm:16.14.0" dependencies: diff --git a/scripts/package.json b/scripts/package.json index b428f9b9f228..a93310ad8931 100644 --- a/scripts/package.json +++ b/scripts/package.json @@ -111,6 +111,7 @@ "babel-eslint": "^10.1.0", "babel-loader": "^9.1.2", "boxen": "^5.1.2", + "browser-assert": "^1.2.1", "chalk": "^4.1.0", "codecov": "^3.8.1", "commander": "^6.2.1", diff --git a/scripts/prepare/addon-bundle.ts b/scripts/prepare/addon-bundle.ts new file mode 100755 index 000000000000..757402c4600d --- /dev/null +++ b/scripts/prepare/addon-bundle.ts @@ -0,0 +1,285 @@ +#!/usr/bin/env ../../node_modules/.bin/ts-node + +import * as fs from 'fs-extra'; +import path, { dirname, join, relative } from 'path'; +import type { Options } from 'tsup'; +import type { PackageJson } from 'type-fest'; +import { build } from 'tsup'; +import aliasPlugin from 'esbuild-plugin-alias'; +import dedent from 'ts-dedent'; +import slash from 'slash'; +import { exec } from '../utils/exec'; + +import { globalPackages as globalPreviewPackages } from '../../code/lib/preview/src/globals/globals'; +import { globalPackages as globalManagerPackages } from '../../code/ui/manager/src/globals/globals'; + +/* TYPES */ + +type Formats = 'esm' | 'cjs'; +type BundlerConfig = { + previewEntries: string[]; + managerEntries: string[]; + nodeEntries: string[]; + exportEntries: string[]; + externals: string[]; + pre: string; + post: string; + formats: Formats[]; +}; +type PackageJsonWithBundlerConfig = PackageJson & { + bundler: BundlerConfig; +}; +type DtsConfigSection = Pick; + +/* MAIN */ + +const run = async ({ cwd, flags }: { cwd: string; flags: string[] }) => { + const { + name, + dependencies, + peerDependencies, + bundler: { + managerEntries = [], + previewEntries = [], + nodeEntries = [], + exportEntries = [], + externals: extraExternals = [], + pre, + post, + formats = ['esm', 'cjs'], + }, + } = (await fs.readJson(join(cwd, 'package.json'))) as PackageJsonWithBundlerConfig; + + if (pre) { + await exec(`node -r ${__dirname}/../node_modules/esbuild-register/register.js ${pre}`, { cwd }); + } + + const reset = hasFlag(flags, 'reset'); + const watch = hasFlag(flags, 'watch'); + const optimized = hasFlag(flags, 'optimized'); + + if (reset) { + await fs.emptyDir(join(process.cwd(), 'dist')); + } + + const tasks: Promise[] = []; + + const commonOptions: Options = { + outDir: join(process.cwd(), 'dist'), + silent: true, + treeshake: true, + shims: false, + watch, + clean: false, + esbuildPlugins: [ + aliasPlugin({ + process: require.resolve('../node_modules/process/browser.js'), + util: require.resolve('../node_modules/util/util.js'), + assert: require.resolve('browser-assert'), + }), + ], + }; + + const commonExternals = [ + name, + ...extraExternals, + ...Object.keys(dependencies || {}), + ...Object.keys(peerDependencies || {}), + ]; + + if (exportEntries.length > 0) { + const { dtsConfig, tsConfigExists } = await getDTSConfigs({ + formats, + entries: exportEntries, + optimized, + }); + + tasks.push( + build({ + ...commonOptions, + ...(optimized ? dtsConfig : {}), + entry: exportEntries, + format: ['esm'], + target: ['chrome100', 'safari15', 'firefox91'], + platform: 'browser', + external: [...commonExternals, ...globalManagerPackages, ...globalPreviewPackages], + esbuildOptions: (options) => { + /* eslint-disable no-param-reassign */ + options.conditions = ['module']; + options.platform = 'browser'; + Object.assign(options, getESBuildOptions(optimized)); + /* eslint-enable no-param-reassign */ + }, + }), + build({ + ...commonOptions, + ...(optimized ? dtsConfig : {}), + entry: exportEntries, + format: ['cjs'], + target: 'node16', + platform: 'node', + external: commonExternals, + esbuildOptions: (options) => { + /* eslint-disable no-param-reassign */ + options.conditions = ['module']; + options.platform = 'node'; + Object.assign(options, getESBuildOptions(optimized)); + /* eslint-enable no-param-reassign */ + }, + }) + ); + + if (tsConfigExists && !optimized) { + tasks.push(...exportEntries.map(generateDTSMapperFile)); + } + } + + if (managerEntries.length > 0) { + tasks.push( + build({ + ...commonOptions, + entry: managerEntries.map((e: string) => slash(join(cwd, e))), + outExtension: () => ({ + js: '.js', + }), + format: ['esm'], + target: ['chrome100', 'safari15', 'firefox91'], + platform: 'browser', + external: [...commonExternals, ...globalManagerPackages], + esbuildOptions: (options) => { + /* eslint-disable no-param-reassign */ + options.conditions = ['module']; + options.platform = 'browser'; + Object.assign(options, getESBuildOptions(optimized)); + /* eslint-enable no-param-reassign */ + }, + }) + ); + } + if (previewEntries.length > 0) { + tasks.push( + build({ + ...commonOptions, + entry: previewEntries.map((e: string) => slash(join(cwd, e))), + outExtension: () => ({ + js: '.js', + }), + format: ['esm'], + target: ['chrome100', 'safari15', 'firefox91'], + platform: 'browser', + external: [...commonExternals, ...globalPreviewPackages], + esbuildOptions: (c) => { + /* eslint-disable no-param-reassign */ + c.conditions = ['module']; + c.platform = 'browser'; + Object.assign(c, getESBuildOptions(optimized)); + /* eslint-enable no-param-reassign */ + }, + }) + ); + } + if (nodeEntries.length > 0) { + tasks.push( + build({ + ...commonOptions, + entry: nodeEntries.map((e: string) => slash(join(cwd, e))), + format: ['cjs'], + target: 'node16', + platform: 'node', + external: commonExternals, + esbuildOptions: (c) => { + /* eslint-disable no-param-reassign */ + c.platform = 'node'; + Object.assign(c, getESBuildOptions(optimized)); + /* eslint-enable no-param-reassign */ + }, + }) + ); + } + + await Promise.all(tasks); + + if (post) { + await exec( + `node -r ${__dirname}/../node_modules/esbuild-register/register.js ${post}`, + { cwd }, + { debug: true } + ); + } + + console.log('done'); +}; + +/* UTILS */ + +// keep in sync with code/lib/manager-api/src/index.ts + +async function getDTSConfigs({ + formats, + entries, + optimized, +}: { + formats: Formats[]; + entries: string[]; + optimized: boolean; +}) { + const tsConfigPath = join(cwd, 'tsconfig.json'); + const tsConfigExists = await fs.pathExists(tsConfigPath); + + const dtsBuild = optimized && formats[0] && tsConfigExists ? formats[0] : undefined; + + const dtsConfig: DtsConfigSection = { + tsconfig: tsConfigPath, + dts: { + entry: entries, + resolve: true, + }, + }; + + return { dtsBuild, dtsConfig, tsConfigExists }; +} + +function getESBuildOptions(optimized: boolean) { + return { + logLevel: 'error', + legalComments: 'none', + minifyWhitespace: optimized, + minifyIdentifiers: false, + minifySyntax: optimized, + }; +} + +async function generateDTSMapperFile(file: string) { + const { name: entryName, dir } = path.parse(file); + + const pathName = join(process.cwd(), dir.replace('./src', 'dist'), `${entryName}.d.ts`); + const srcName = join(process.cwd(), file); + const rel = relative(dirname(pathName), dirname(srcName)).split(path.sep).join(path.posix.sep); + + await fs.ensureFile(pathName); + await fs.writeFile( + pathName, + dedent` + // dev-mode + export * from '${rel}/${entryName}'; + `, + { encoding: 'utf-8' } + ); +} + +const hasFlag = (flags: string[], name: string) => !!flags.find((s) => s.startsWith(`--${name}`)); + +/* SELF EXECUTION */ + +const flags = process.argv.slice(2); +const cwd = process.cwd(); + +run({ cwd, flags }).catch((err: unknown) => { + // We can't let the stack try to print, it crashes in a way that sets the exit code to 0. + // Seems to have something to do with running JSON.parse() on binary / base64 encoded sourcemaps + // in @cspotcode/source-map-support + if (err instanceof Error) { + console.error(err.stack); + } + process.exit(1); +}); diff --git a/scripts/yarn.lock b/scripts/yarn.lock index 411298c2d9b9..a6d22a45a644 100644 --- a/scripts/yarn.lock +++ b/scripts/yarn.lock @@ -3146,6 +3146,7 @@ __metadata: babel-eslint: "npm:^10.1.0" babel-loader: "npm:^9.1.2" boxen: "npm:^5.1.2" + browser-assert: "npm:^1.2.1" chalk: "npm:^4.1.0" codecov: "npm:^3.8.1" commander: "npm:^6.2.1" @@ -5467,6 +5468,13 @@ __metadata: languageName: node linkType: hard +"browser-assert@npm:^1.2.1": + version: 1.2.1 + resolution: "browser-assert@npm:1.2.1" + checksum: 902abf999f92c9c951fdb6d7352c09eea9a84706258699655f7e7906e42daa06a1ae286398a755872740e05a6a71c43c5d1a0c0431d67a8cdb66e5d859a3fc0c + languageName: node + linkType: hard + "browserslist@npm:^4.21.10, browserslist@npm:^4.21.9": version: 4.21.10 resolution: "browserslist@npm:4.21.10" From e792e6fea90b8203d3a1d75cde85644bf7e63de4 Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Tue, 14 Nov 2023 15:27:14 +0100 Subject: [PATCH 040/170] Update package.json scripts to use esbuild-register from scripts/node_modules --- code/addons/a11y/package.json | 4 ++-- code/addons/actions/package.json | 4 ++-- code/addons/backgrounds/package.json | 4 ++-- code/addons/controls/package.json | 4 ++-- code/addons/docs/package.json | 4 ++-- code/addons/essentials/package.json | 4 ++-- code/addons/gfm/package.json | 4 ++-- code/addons/highlight/package.json | 4 ++-- code/addons/interactions/package.json | 4 ++-- code/addons/jest/package.json | 4 ++-- code/addons/links/package.json | 4 ++-- code/addons/measure/package.json | 4 ++-- code/addons/outline/package.json | 4 ++-- code/addons/storyshots-core/package.json | 4 ++-- code/addons/storyshots-puppeteer/package.json | 4 ++-- code/addons/storysource/package.json | 4 ++-- code/addons/themes/package.json | 4 ++-- code/addons/toolbars/package.json | 4 ++-- code/addons/viewport/package.json | 4 ++-- code/builders/builder-manager/package.json | 4 ++-- code/builders/builder-vite/package.json | 4 ++-- code/builders/builder-webpack5/package.json | 4 ++-- code/deprecated/addons/package.json | 4 ++-- code/deprecated/channel-postmessage/package.json | 4 ++-- code/deprecated/channel-websocket/package.json | 4 ++-- code/deprecated/client-api/package.json | 4 ++-- code/deprecated/core-client/package.json | 4 ++-- code/deprecated/manager-api-shim/package.json | 4 ++-- code/deprecated/preview-web/package.json | 4 ++-- code/deprecated/store/package.json | 4 ++-- code/frameworks/angular/package.json | 2 +- code/frameworks/ember/package.json | 4 ++-- code/frameworks/html-vite/package.json | 4 ++-- code/frameworks/html-webpack5/package.json | 4 ++-- code/frameworks/nextjs/package.json | 4 ++-- code/frameworks/preact-vite/package.json | 4 ++-- code/frameworks/preact-webpack5/package.json | 4 ++-- code/frameworks/react-vite/package.json | 4 ++-- code/frameworks/react-webpack5/package.json | 4 ++-- code/frameworks/server-webpack5/package.json | 4 ++-- code/frameworks/svelte-vite/package.json | 4 ++-- code/frameworks/svelte-webpack5/package.json | 4 ++-- code/frameworks/sveltekit/package.json | 4 ++-- code/frameworks/vue-vite/package.json | 4 ++-- code/frameworks/vue-webpack5/package.json | 4 ++-- code/frameworks/vue3-vite/package.json | 4 ++-- code/frameworks/vue3-webpack5/package.json | 4 ++-- code/frameworks/web-components-vite/package.json | 4 ++-- code/frameworks/web-components-webpack5/package.json | 4 ++-- code/lib/channels/package.json | 4 ++-- code/lib/cli/package.json | 4 ++-- code/lib/client-logger/package.json | 4 ++-- code/lib/codemod/package.json | 4 ++-- code/lib/core-common/package.json | 4 ++-- code/lib/core-events/package.json | 4 ++-- code/lib/core-server/package.json | 4 ++-- code/lib/core-webpack/package.json | 4 ++-- code/lib/csf-plugin/package.json | 4 ++-- code/lib/csf-tools/package.json | 4 ++-- code/lib/docs-tools/package.json | 4 ++-- code/lib/instrumenter/package.json | 4 ++-- code/lib/manager-api/package.json | 4 ++-- code/lib/node-logger/package.json | 4 ++-- code/lib/postinstall/package.json | 4 ++-- code/lib/preview-api/package.json | 4 ++-- code/lib/preview/package.json | 4 ++-- code/lib/react-dom-shim/package.json | 4 ++-- code/lib/router/package.json | 4 ++-- code/lib/source-loader/package.json | 4 ++-- code/lib/telemetry/package.json | 4 ++-- code/lib/test/package.json | 4 ++-- code/lib/theming/package.json | 4 ++-- code/lib/types/package.json | 4 ++-- code/presets/create-react-app/package.json | 4 ++-- code/presets/html-webpack/package.json | 4 ++-- code/presets/preact-webpack/package.json | 4 ++-- code/presets/react-webpack/package.json | 4 ++-- code/presets/server-webpack/package.json | 4 ++-- code/presets/svelte-webpack/package.json | 4 ++-- code/presets/vue-webpack/package.json | 4 ++-- code/presets/vue3-webpack/package.json | 4 ++-- code/presets/web-components-webpack/package.json | 4 ++-- code/renderers/html/package.json | 4 ++-- code/renderers/preact/package.json | 4 ++-- code/renderers/react/package.json | 4 ++-- code/renderers/server/package.json | 4 ++-- code/renderers/svelte/package.json | 2 +- code/renderers/vue/package.json | 2 +- code/renderers/vue3/package.json | 2 +- code/renderers/web-components/package.json | 4 ++-- code/ui/blocks/package.json | 4 ++-- code/ui/components/package.json | 4 ++-- code/ui/manager/package.json | 4 ++-- 93 files changed, 182 insertions(+), 182 deletions(-) diff --git a/code/addons/a11y/package.json b/code/addons/a11y/package.json index 982115b501f5..0f34cd9e527f 100644 --- a/code/addons/a11y/package.json +++ b/code/addons/a11y/package.json @@ -60,8 +60,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/addon-highlight": "workspace:*", diff --git a/code/addons/actions/package.json b/code/addons/actions/package.json index dae971d82905..40e68c4fff34 100644 --- a/code/addons/actions/package.json +++ b/code/addons/actions/package.json @@ -77,8 +77,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/addons/backgrounds/package.json b/code/addons/backgrounds/package.json index e698e3eba4b8..56b2bff935ae 100644 --- a/code/addons/backgrounds/package.json +++ b/code/addons/backgrounds/package.json @@ -73,8 +73,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/addons/controls/package.json b/code/addons/controls/package.json index d19e4a64617e..78f29f924270 100644 --- a/code/addons/controls/package.json +++ b/code/addons/controls/package.json @@ -65,8 +65,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/blocks": "workspace:*", diff --git a/code/addons/docs/package.json b/code/addons/docs/package.json index 268c69b97d86..20b24e94d52d 100644 --- a/code/addons/docs/package.json +++ b/code/addons/docs/package.json @@ -94,8 +94,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@jest/transform": "^29.3.1", diff --git a/code/addons/essentials/package.json b/code/addons/essentials/package.json index 7401de032c27..e25426ea9e31 100644 --- a/code/addons/essentials/package.json +++ b/code/addons/essentials/package.json @@ -116,8 +116,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/addon-actions": "workspace:*", diff --git a/code/addons/gfm/package.json b/code/addons/gfm/package.json index d83825748f7b..8ed921d17f37 100644 --- a/code/addons/gfm/package.json +++ b/code/addons/gfm/package.json @@ -48,8 +48,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/node-logger": "workspace:*", diff --git a/code/addons/highlight/package.json b/code/addons/highlight/package.json index 5450d894b52d..4a5b282644ee 100644 --- a/code/addons/highlight/package.json +++ b/code/addons/highlight/package.json @@ -58,8 +58,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/core-events": "workspace:*", diff --git a/code/addons/interactions/package.json b/code/addons/interactions/package.json index edb8a55e2a20..b7d115458cb6 100644 --- a/code/addons/interactions/package.json +++ b/code/addons/interactions/package.json @@ -69,8 +69,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/addons/jest/package.json b/code/addons/jest/package.json index 4f78b3f8aa4e..f9bd67e38501 100644 --- a/code/addons/jest/package.json +++ b/code/addons/jest/package.json @@ -67,8 +67,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/addons/links/package.json b/code/addons/links/package.json index f9f0592d43bc..8f9a7502df57 100644 --- a/code/addons/links/package.json +++ b/code/addons/links/package.json @@ -77,8 +77,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/addons/measure/package.json b/code/addons/measure/package.json index 9368eecad955..78c569318775 100644 --- a/code/addons/measure/package.json +++ b/code/addons/measure/package.json @@ -72,8 +72,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/addons/outline/package.json b/code/addons/outline/package.json index 6437a4f263eb..09eec0e02503 100644 --- a/code/addons/outline/package.json +++ b/code/addons/outline/package.json @@ -75,8 +75,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/addons/storyshots-core/package.json b/code/addons/storyshots-core/package.json index b9529e0d292d..a00ae2eec731 100644 --- a/code/addons/storyshots-core/package.json +++ b/code/addons/storyshots-core/package.json @@ -33,8 +33,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/tsc.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/tsc.ts" }, "dependencies": { "@jest/transform": "^29.3.1", diff --git a/code/addons/storyshots-puppeteer/package.json b/code/addons/storyshots-puppeteer/package.json index b69d36e8acde..392174a3d0ce 100644 --- a/code/addons/storyshots-puppeteer/package.json +++ b/code/addons/storyshots-puppeteer/package.json @@ -32,8 +32,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/tsc.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/tsc.ts" }, "dependencies": { "@axe-core/puppeteer": "^4.2.0", diff --git a/code/addons/storysource/package.json b/code/addons/storysource/package.json index 85b40d56664a..09e970e9f607 100644 --- a/code/addons/storysource/package.json +++ b/code/addons/storysource/package.json @@ -50,8 +50,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/addons/themes/package.json b/code/addons/themes/package.json index 595d64e9ef56..082775234046 100644 --- a/code/addons/themes/package.json +++ b/code/addons/themes/package.json @@ -70,8 +70,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/addons/toolbars/package.json b/code/addons/toolbars/package.json index 9a10b7efdbc3..903a674205be 100644 --- a/code/addons/toolbars/package.json +++ b/code/addons/toolbars/package.json @@ -65,8 +65,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/addons/viewport/package.json b/code/addons/viewport/package.json index 4b997880b5fa..d690529d0e68 100644 --- a/code/addons/viewport/package.json +++ b/code/addons/viewport/package.json @@ -70,8 +70,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/builders/builder-manager/package.json b/code/builders/builder-manager/package.json index d35b2c97a213..0c64ca32e651 100644 --- a/code/builders/builder-manager/package.json +++ b/code/builders/builder-manager/package.json @@ -40,8 +40,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@fal-works/esbuild-plugin-global-externals": "^2.1.2", diff --git a/code/builders/builder-vite/package.json b/code/builders/builder-vite/package.json index 2d5a24ce0d35..d4e02fa8c3c6 100644 --- a/code/builders/builder-vite/package.json +++ b/code/builders/builder-vite/package.json @@ -39,8 +39,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/channels": "workspace:*", diff --git a/code/builders/builder-webpack5/package.json b/code/builders/builder-webpack5/package.json index 990af8a140d3..d72f0de4a961 100644 --- a/code/builders/builder-webpack5/package.json +++ b/code/builders/builder-webpack5/package.json @@ -57,8 +57,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@babel/core": "^7.23.2", diff --git a/code/deprecated/addons/package.json b/code/deprecated/addons/package.json index 9d15fd59224f..89bbf3000895 100644 --- a/code/deprecated/addons/package.json +++ b/code/deprecated/addons/package.json @@ -40,8 +40,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/manager-api": "workspace:*", diff --git a/code/deprecated/channel-postmessage/package.json b/code/deprecated/channel-postmessage/package.json index bf22209c5f64..9723d53d21aa 100644 --- a/code/deprecated/channel-postmessage/package.json +++ b/code/deprecated/channel-postmessage/package.json @@ -40,8 +40,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/channels": "workspace:*", diff --git a/code/deprecated/channel-websocket/package.json b/code/deprecated/channel-websocket/package.json index 8e291a4ac852..cf9f8c2472bf 100644 --- a/code/deprecated/channel-websocket/package.json +++ b/code/deprecated/channel-websocket/package.json @@ -40,8 +40,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/facade.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/facade.ts" }, "dependencies": { "@storybook/channels": "workspace:*", diff --git a/code/deprecated/client-api/package.json b/code/deprecated/client-api/package.json index 25fa94650e05..ab9bd1a38dff 100644 --- a/code/deprecated/client-api/package.json +++ b/code/deprecated/client-api/package.json @@ -39,8 +39,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/facade.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/facade.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/deprecated/core-client/package.json b/code/deprecated/core-client/package.json index ff265bb1919d..8b8c0b1ea459 100644 --- a/code/deprecated/core-client/package.json +++ b/code/deprecated/core-client/package.json @@ -31,8 +31,8 @@ "module": "dist/entry.mjs", "types": "dist/entry.d.ts", "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/facade.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/facade.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/deprecated/manager-api-shim/package.json b/code/deprecated/manager-api-shim/package.json index 4c15fa4d619a..1924599d02f2 100644 --- a/code/deprecated/manager-api-shim/package.json +++ b/code/deprecated/manager-api-shim/package.json @@ -39,8 +39,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/facade.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/facade.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/deprecated/preview-web/package.json b/code/deprecated/preview-web/package.json index 08a093f37f55..cc75dde0e9f9 100644 --- a/code/deprecated/preview-web/package.json +++ b/code/deprecated/preview-web/package.json @@ -39,8 +39,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/facade.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/facade.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/deprecated/store/package.json b/code/deprecated/store/package.json index 5c948facc749..d63b568308d1 100644 --- a/code/deprecated/store/package.json +++ b/code/deprecated/store/package.json @@ -39,8 +39,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/facade.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/facade.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/frameworks/angular/package.json b/code/frameworks/angular/package.json index 25e790336a6e..9ad294cb298c 100644 --- a/code/frameworks/angular/package.json +++ b/code/frameworks/angular/package.json @@ -34,7 +34,7 @@ ], "scripts": { "check": "node ../../../scripts/node_modules/.bin/tsc", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/tsc.ts" + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/tsc.ts" }, "dependencies": { "@storybook/builder-webpack5": "workspace:*", diff --git a/code/frameworks/ember/package.json b/code/frameworks/ember/package.json index 94cdc922426e..6097d1b49c26 100644 --- a/code/frameworks/ember/package.json +++ b/code/frameworks/ember/package.json @@ -28,8 +28,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/tsc.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/tsc.ts" }, "dependencies": { "@storybook/builder-webpack5": "workspace:*", diff --git a/code/frameworks/html-vite/package.json b/code/frameworks/html-vite/package.json index 3618ec2a4b67..d9f204488b3d 100644 --- a/code/frameworks/html-vite/package.json +++ b/code/frameworks/html-vite/package.json @@ -43,8 +43,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/addons": "workspace:*", diff --git a/code/frameworks/html-webpack5/package.json b/code/frameworks/html-webpack5/package.json index d09ccceefb23..e22026b0f95c 100644 --- a/code/frameworks/html-webpack5/package.json +++ b/code/frameworks/html-webpack5/package.json @@ -43,8 +43,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/builder-webpack5": "workspace:*", diff --git a/code/frameworks/nextjs/package.json b/code/frameworks/nextjs/package.json index 11b092bc0ce0..695b57c1e738 100644 --- a/code/frameworks/nextjs/package.json +++ b/code/frameworks/nextjs/package.json @@ -70,8 +70,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@babel/core": "^7.23.2", diff --git a/code/frameworks/preact-vite/package.json b/code/frameworks/preact-vite/package.json index 0110bb9d8d92..d0e66e400b51 100644 --- a/code/frameworks/preact-vite/package.json +++ b/code/frameworks/preact-vite/package.json @@ -43,8 +43,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@preact/preset-vite": "^2.0.0", diff --git a/code/frameworks/preact-webpack5/package.json b/code/frameworks/preact-webpack5/package.json index 43065839e92f..8136f3948827 100644 --- a/code/frameworks/preact-webpack5/package.json +++ b/code/frameworks/preact-webpack5/package.json @@ -43,8 +43,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/builder-webpack5": "workspace:*", diff --git a/code/frameworks/react-vite/package.json b/code/frameworks/react-vite/package.json index 5a4d27903523..91584f7309b9 100644 --- a/code/frameworks/react-vite/package.json +++ b/code/frameworks/react-vite/package.json @@ -43,8 +43,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@joshwooding/vite-plugin-react-docgen-typescript": "0.3.0", diff --git a/code/frameworks/react-webpack5/package.json b/code/frameworks/react-webpack5/package.json index 4e021b06fd8b..5e8d43899ba6 100644 --- a/code/frameworks/react-webpack5/package.json +++ b/code/frameworks/react-webpack5/package.json @@ -43,8 +43,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/builder-webpack5": "workspace:*", diff --git a/code/frameworks/server-webpack5/package.json b/code/frameworks/server-webpack5/package.json index 2fed061b43bd..21f0e10fd88b 100644 --- a/code/frameworks/server-webpack5/package.json +++ b/code/frameworks/server-webpack5/package.json @@ -43,8 +43,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/builder-webpack5": "workspace:*", diff --git a/code/frameworks/svelte-vite/package.json b/code/frameworks/svelte-vite/package.json index 8dde98399e7f..da2dfba2ff89 100644 --- a/code/frameworks/svelte-vite/package.json +++ b/code/frameworks/svelte-vite/package.json @@ -43,8 +43,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/builder-vite": "workspace:*", diff --git a/code/frameworks/svelte-webpack5/package.json b/code/frameworks/svelte-webpack5/package.json index 36a873112a69..365d395a0165 100644 --- a/code/frameworks/svelte-webpack5/package.json +++ b/code/frameworks/svelte-webpack5/package.json @@ -43,8 +43,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/builder-webpack5": "workspace:*", diff --git a/code/frameworks/sveltekit/package.json b/code/frameworks/sveltekit/package.json index 04e02d1e80f2..8701a4bfcbc2 100644 --- a/code/frameworks/sveltekit/package.json +++ b/code/frameworks/sveltekit/package.json @@ -46,8 +46,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/builder-vite": "workspace:*", diff --git a/code/frameworks/vue-vite/package.json b/code/frameworks/vue-vite/package.json index 3cdc090a67f8..0a5b94b74d13 100644 --- a/code/frameworks/vue-vite/package.json +++ b/code/frameworks/vue-vite/package.json @@ -43,8 +43,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/builder-vite": "workspace:*", diff --git a/code/frameworks/vue-webpack5/package.json b/code/frameworks/vue-webpack5/package.json index e247fdc1519d..2258ba6eb848 100644 --- a/code/frameworks/vue-webpack5/package.json +++ b/code/frameworks/vue-webpack5/package.json @@ -43,8 +43,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/builder-webpack5": "workspace:*", diff --git a/code/frameworks/vue3-vite/package.json b/code/frameworks/vue3-vite/package.json index db006e4cb91e..1b2b62723b28 100644 --- a/code/frameworks/vue3-vite/package.json +++ b/code/frameworks/vue3-vite/package.json @@ -43,8 +43,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/builder-vite": "workspace:*", diff --git a/code/frameworks/vue3-webpack5/package.json b/code/frameworks/vue3-webpack5/package.json index a0b50a309047..d46d7162f347 100644 --- a/code/frameworks/vue3-webpack5/package.json +++ b/code/frameworks/vue3-webpack5/package.json @@ -43,8 +43,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/builder-webpack5": "workspace:*", diff --git a/code/frameworks/web-components-vite/package.json b/code/frameworks/web-components-vite/package.json index 2fe348aeee46..2c32f1352d13 100644 --- a/code/frameworks/web-components-vite/package.json +++ b/code/frameworks/web-components-vite/package.json @@ -43,8 +43,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/builder-vite": "workspace:*", diff --git a/code/frameworks/web-components-webpack5/package.json b/code/frameworks/web-components-webpack5/package.json index f77d6ff57e56..2f9d4153b9dc 100644 --- a/code/frameworks/web-components-webpack5/package.json +++ b/code/frameworks/web-components-webpack5/package.json @@ -46,8 +46,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@babel/preset-env": "^7.23.2", diff --git a/code/lib/channels/package.json b/code/lib/channels/package.json index 97041d0eb68c..ed8d4525fb22 100644 --- a/code/lib/channels/package.json +++ b/code/lib/channels/package.json @@ -65,8 +65,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/lib/cli/package.json b/code/lib/cli/package.json index f202d09551d8..5d5f33c23b0f 100644 --- a/code/lib/cli/package.json +++ b/code/lib/cli/package.json @@ -50,8 +50,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts", + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts", "test": "jest test/**/*.test.js" }, "dependencies": { diff --git a/code/lib/client-logger/package.json b/code/lib/client-logger/package.json index 01f6e4e61581..209d761a0c3b 100644 --- a/code/lib/client-logger/package.json +++ b/code/lib/client-logger/package.json @@ -40,8 +40,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/global": "^5.0.0" diff --git a/code/lib/codemod/package.json b/code/lib/codemod/package.json index 519ea66221be..4f91b18e2f85 100644 --- a/code/lib/codemod/package.json +++ b/code/lib/codemod/package.json @@ -48,8 +48,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@babel/core": "^7.23.2", diff --git a/code/lib/core-common/package.json b/code/lib/core-common/package.json index 6ff3e17086d7..80e74f7ef11b 100644 --- a/code/lib/core-common/package.json +++ b/code/lib/core-common/package.json @@ -40,8 +40,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/core-events": "workspace:*", diff --git a/code/lib/core-events/package.json b/code/lib/core-events/package.json index 1d81fd572edd..ada82cb59c26 100644 --- a/code/lib/core-events/package.json +++ b/code/lib/core-events/package.json @@ -74,8 +74,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "ts-dedent": "^2.0.0" diff --git a/code/lib/core-server/package.json b/code/lib/core-server/package.json index e8fa26863523..dd3add9d69b7 100644 --- a/code/lib/core-server/package.json +++ b/code/lib/core-server/package.json @@ -56,8 +56,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@aw-web-design/x-default-browser": "1.4.126", diff --git a/code/lib/core-webpack/package.json b/code/lib/core-webpack/package.json index 76228f4cf4b6..dacc6e45deb8 100644 --- a/code/lib/core-webpack/package.json +++ b/code/lib/core-webpack/package.json @@ -40,8 +40,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/core-common": "workspace:*", diff --git a/code/lib/csf-plugin/package.json b/code/lib/csf-plugin/package.json index 5bb7401fca86..f873a212f9d5 100644 --- a/code/lib/csf-plugin/package.json +++ b/code/lib/csf-plugin/package.json @@ -40,8 +40,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/csf-tools": "workspace:*", diff --git a/code/lib/csf-tools/package.json b/code/lib/csf-tools/package.json index 4fd7fc4fca05..63acbbeac118 100644 --- a/code/lib/csf-tools/package.json +++ b/code/lib/csf-tools/package.json @@ -38,8 +38,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@babel/generator": "^7.23.0", diff --git a/code/lib/docs-tools/package.json b/code/lib/docs-tools/package.json index a93540f256ae..f99cd0eb0ed6 100644 --- a/code/lib/docs-tools/package.json +++ b/code/lib/docs-tools/package.json @@ -40,8 +40,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/core-common": "workspace:*", diff --git a/code/lib/instrumenter/package.json b/code/lib/instrumenter/package.json index ff32f64c19f0..8994bae83cbd 100644 --- a/code/lib/instrumenter/package.json +++ b/code/lib/instrumenter/package.json @@ -40,8 +40,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/channels": "workspace:*", diff --git a/code/lib/manager-api/package.json b/code/lib/manager-api/package.json index a78be8748e84..aba346d66532 100644 --- a/code/lib/manager-api/package.json +++ b/code/lib/manager-api/package.json @@ -39,8 +39,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/channels": "workspace:*", diff --git a/code/lib/node-logger/package.json b/code/lib/node-logger/package.json index 742132de9201..3caebf579171 100644 --- a/code/lib/node-logger/package.json +++ b/code/lib/node-logger/package.json @@ -38,8 +38,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "devDependencies": { "@types/npmlog": "^4.1.2", diff --git a/code/lib/postinstall/package.json b/code/lib/postinstall/package.json index f23342659ea8..42b7332b2e69 100644 --- a/code/lib/postinstall/package.json +++ b/code/lib/postinstall/package.json @@ -41,8 +41,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "devDependencies": { "jest": "^29.7.0", diff --git a/code/lib/preview-api/package.json b/code/lib/preview-api/package.json index 6e11c55daa3b..5e577c588d15 100644 --- a/code/lib/preview-api/package.json +++ b/code/lib/preview-api/package.json @@ -64,8 +64,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/channels": "workspace:*", diff --git a/code/lib/preview/package.json b/code/lib/preview/package.json index 8fe5fbdcb4cb..5d1bd5d50296 100644 --- a/code/lib/preview/package.json +++ b/code/lib/preview/package.json @@ -52,8 +52,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/esm-bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/esm-bundle.ts" }, "devDependencies": { "@storybook/channels": "workspace:*", diff --git a/code/lib/react-dom-shim/package.json b/code/lib/react-dom-shim/package.json index 986c08dffa42..5adaf5afd744 100644 --- a/code/lib/react-dom-shim/package.json +++ b/code/lib/react-dom-shim/package.json @@ -50,8 +50,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "devDependencies": { "@storybook/types": "workspace:*", diff --git a/code/lib/router/package.json b/code/lib/router/package.json index 3e61b244e67f..63379996c90a 100644 --- a/code/lib/router/package.json +++ b/code/lib/router/package.json @@ -45,8 +45,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/lib/source-loader/package.json b/code/lib/source-loader/package.json index 86757b2f41c9..7115659af6d3 100644 --- a/code/lib/source-loader/package.json +++ b/code/lib/source-loader/package.json @@ -41,8 +41,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/csf": "^0.1.0", diff --git a/code/lib/telemetry/package.json b/code/lib/telemetry/package.json index d4db3291c362..4117e5882c2a 100644 --- a/code/lib/telemetry/package.json +++ b/code/lib/telemetry/package.json @@ -40,8 +40,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/lib/test/package.json b/code/lib/test/package.json index 4b082c255b90..94aeef099a96 100644 --- a/code/lib/test/package.json +++ b/code/lib/test/package.json @@ -39,8 +39,8 @@ "*.d.ts" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/lib/theming/package.json b/code/lib/theming/package.json index 8f8081cecaeb..5a1f26529adc 100644 --- a/code/lib/theming/package.json +++ b/code/lib/theming/package.json @@ -45,8 +45,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@emotion/use-insertion-effect-with-fallbacks": "^1.0.0", diff --git a/code/lib/types/package.json b/code/lib/types/package.json index 370d7950e78c..641f1cd585bd 100644 --- a/code/lib/types/package.json +++ b/code/lib/types/package.json @@ -40,8 +40,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/channels": "workspace:*", diff --git a/code/presets/create-react-app/package.json b/code/presets/create-react-app/package.json index fa30b9f6d93a..3336d73a402e 100644 --- a/code/presets/create-react-app/package.json +++ b/code/presets/create-react-app/package.json @@ -45,8 +45,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@pmmmwh/react-refresh-webpack-plugin": "^0.5.1", diff --git a/code/presets/html-webpack/package.json b/code/presets/html-webpack/package.json index 4c24a2a7f387..d84193c78be7 100644 --- a/code/presets/html-webpack/package.json +++ b/code/presets/html-webpack/package.json @@ -45,8 +45,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/core-webpack": "workspace:*", diff --git a/code/presets/preact-webpack/package.json b/code/presets/preact-webpack/package.json index 4d74b3f36ab1..cc2506d710c4 100644 --- a/code/presets/preact-webpack/package.json +++ b/code/presets/preact-webpack/package.json @@ -45,8 +45,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@babel/plugin-transform-react-jsx": "^7.22.15", diff --git a/code/presets/react-webpack/package.json b/code/presets/react-webpack/package.json index d34374359091..b8e179c279e0 100644 --- a/code/presets/react-webpack/package.json +++ b/code/presets/react-webpack/package.json @@ -65,8 +65,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@babel/preset-flow": "^7.22.15", diff --git a/code/presets/server-webpack/package.json b/code/presets/server-webpack/package.json index cb705b236e54..484b4d771bb1 100644 --- a/code/presets/server-webpack/package.json +++ b/code/presets/server-webpack/package.json @@ -50,8 +50,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/core-server": "workspace:*", diff --git a/code/presets/svelte-webpack/package.json b/code/presets/svelte-webpack/package.json index fce2d9ab8588..1eb33bf8a33f 100644 --- a/code/presets/svelte-webpack/package.json +++ b/code/presets/svelte-webpack/package.json @@ -60,8 +60,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/core-webpack": "workspace:*", diff --git a/code/presets/vue-webpack/package.json b/code/presets/vue-webpack/package.json index e2ba65efb9cd..ab9b647953b3 100644 --- a/code/presets/vue-webpack/package.json +++ b/code/presets/vue-webpack/package.json @@ -55,8 +55,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/core-webpack": "workspace:*", diff --git a/code/presets/vue3-webpack/package.json b/code/presets/vue3-webpack/package.json index c58a47380471..58b3b6607323 100644 --- a/code/presets/vue3-webpack/package.json +++ b/code/presets/vue3-webpack/package.json @@ -55,8 +55,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/core-webpack": "workspace:*", diff --git a/code/presets/web-components-webpack/package.json b/code/presets/web-components-webpack/package.json index c33ca8e1ed21..5f71e9c87657 100644 --- a/code/presets/web-components-webpack/package.json +++ b/code/presets/web-components-webpack/package.json @@ -48,8 +48,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@babel/plugin-syntax-dynamic-import": "^7.8.3", diff --git a/code/renderers/html/package.json b/code/renderers/html/package.json index 9ba0d6d7b0e9..ab3500dff9ef 100644 --- a/code/renderers/html/package.json +++ b/code/renderers/html/package.json @@ -43,8 +43,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/core-client": "workspace:*", diff --git a/code/renderers/preact/package.json b/code/renderers/preact/package.json index eac5aec6f576..9dee71b45fa9 100644 --- a/code/renderers/preact/package.json +++ b/code/renderers/preact/package.json @@ -43,8 +43,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/core-client": "workspace:*", diff --git a/code/renderers/react/package.json b/code/renderers/react/package.json index ce66b38cf818..daac2180662f 100644 --- a/code/renderers/react/package.json +++ b/code/renderers/react/package.json @@ -43,8 +43,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/renderers/server/package.json b/code/renderers/server/package.json index 42f81613162a..92f601988151 100644 --- a/code/renderers/server/package.json +++ b/code/renderers/server/package.json @@ -42,8 +42,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/core-client": "workspace:*", diff --git a/code/renderers/svelte/package.json b/code/renderers/svelte/package.json index bd7ff38d0b1a..09d93252fc65 100644 --- a/code/renderers/svelte/package.json +++ b/code/renderers/svelte/package.json @@ -48,7 +48,7 @@ ], "scripts": { "check": "svelte-check", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/renderers/vue/package.json b/code/renderers/vue/package.json index 4cead82af191..1f14d57e283b 100644 --- a/code/renderers/vue/package.json +++ b/code/renderers/vue/package.json @@ -44,7 +44,7 @@ ], "scripts": { "check": "vue-tsc --noEmit", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/renderers/vue3/package.json b/code/renderers/vue3/package.json index 76e24a10fd3e..cc6c71af5d3d 100644 --- a/code/renderers/vue3/package.json +++ b/code/renderers/vue3/package.json @@ -44,7 +44,7 @@ ], "scripts": { "check": "vue-tsc --noEmit", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/core-client": "workspace:*", diff --git a/code/renderers/web-components/package.json b/code/renderers/web-components/package.json index e765f82785ae..bd38fa466654 100644 --- a/code/renderers/web-components/package.json +++ b/code/renderers/web-components/package.json @@ -46,8 +46,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/client-logger": "workspace:*", diff --git a/code/ui/blocks/package.json b/code/ui/blocks/package.json index e8a52b797204..f0027b1c82ea 100644 --- a/code/ui/blocks/package.json +++ b/code/ui/blocks/package.json @@ -40,8 +40,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@storybook/channels": "workspace:*", diff --git a/code/ui/components/package.json b/code/ui/components/package.json index 4049f25e6960..937ab45eee27 100644 --- a/code/ui/components/package.json +++ b/code/ui/components/package.json @@ -55,8 +55,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { "@radix-ui/react-select": "^1.2.2", diff --git a/code/ui/manager/package.json b/code/ui/manager/package.json index df38b64c1079..c7ceca1bfdbb 100644 --- a/code/ui/manager/package.json +++ b/code/ui/manager/package.json @@ -47,8 +47,8 @@ "!src/**/*" ], "scripts": { - "check": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/check.ts", - "prep": "node --loader esbuild-register/loader -r esbuild-register ../../../scripts/prepare/esm-bundle.ts" + "check": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/check.ts", + "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/esm-bundle.ts" }, "devDependencies": { "@fal-works/esbuild-plugin-global-externals": "^2.1.2", From e8f8a65aee104fa384c0d7505fc470c1804267e6 Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Tue, 14 Nov 2023 17:15:47 +0100 Subject: [PATCH 041/170] Replace default export of esMain by named export --- scripts/combine-compodoc.ts | 2 +- scripts/event-log-checker.ts | 2 +- scripts/get-report-message.ts | 2 +- scripts/get-template.ts | 2 +- scripts/release/cancel-preparation-runs.ts | 2 +- scripts/release/ensure-next-ahead.ts | 2 +- scripts/release/generate-pr-description.ts | 2 +- scripts/release/get-changelog-from-file.ts | 2 +- scripts/release/get-current-version.ts | 2 +- scripts/release/get-version-changelog.ts | 2 +- scripts/release/is-pr-frozen.ts | 2 +- scripts/release/is-prerelease.ts | 2 +- scripts/release/is-version-published.ts | 2 +- scripts/release/label-patches.ts | 2 +- scripts/release/pick-patches.ts | 2 +- scripts/release/publish.ts | 2 +- scripts/release/unreleased-changes-exists.ts | 2 +- scripts/release/version.ts | 2 +- scripts/release/write-changelog.ts | 2 +- scripts/sandbox/generate.ts | 2 +- scripts/utils/esmain.ts | 2 +- 21 files changed, 21 insertions(+), 21 deletions(-) diff --git a/scripts/combine-compodoc.ts b/scripts/combine-compodoc.ts index 3eaad97df6d0..c355cc242831 100755 --- a/scripts/combine-compodoc.ts +++ b/scripts/combine-compodoc.ts @@ -7,7 +7,7 @@ import { realpath, readFile, writeFile, lstat } from 'fs-extra'; import { globSync } from 'glob'; import { directory } from 'tempy'; import { execaCommand } from 'execa'; -import esMain from './utils/esmain'; +import { esMain } from './utils/esmain'; const logger = console; diff --git a/scripts/event-log-checker.ts b/scripts/event-log-checker.ts index 2812dc089697..681e54f7dfe4 100644 --- a/scripts/event-log-checker.ts +++ b/scripts/event-log-checker.ts @@ -2,7 +2,7 @@ import chalk from 'chalk'; import assert from 'assert'; import fetch from 'node-fetch'; -import esMain from './utils/esmain'; +import { esMain } from './utils/esmain'; import { allTemplates } from '../code/lib/cli/src/sandbox-templates'; import versions from '../code/lib/cli/src/versions'; import { oneWayHash } from '../code/lib/telemetry/src/one-way-hash'; diff --git a/scripts/get-report-message.ts b/scripts/get-report-message.ts index a10bbdd276e1..d118bfed3b61 100644 --- a/scripts/get-report-message.ts +++ b/scripts/get-report-message.ts @@ -2,7 +2,7 @@ import { readJson } from 'fs-extra'; import { join } from 'path'; import { execaCommand } from 'execa'; -import esMain from './utils/esmain'; +import { esMain } from './utils/esmain'; import { CODE_DIRECTORY } from './utils/constants'; type Branch = 'main' | 'next' | 'alpha' | 'next-release' | 'latest-release'; diff --git a/scripts/get-template.ts b/scripts/get-template.ts index 0b54568b3143..ee3b81b13025 100644 --- a/scripts/get-template.ts +++ b/scripts/get-template.ts @@ -4,7 +4,7 @@ import { program } from 'commander'; import dedent from 'ts-dedent'; import chalk from 'chalk'; import yaml from 'yaml'; -import esMain from './utils/esmain'; +import { esMain } from './utils/esmain'; import { allTemplates, templatesByCadence, diff --git a/scripts/release/cancel-preparation-runs.ts b/scripts/release/cancel-preparation-runs.ts index 811de60bfa52..56cca697d1d9 100644 --- a/scripts/release/cancel-preparation-runs.ts +++ b/scripts/release/cancel-preparation-runs.ts @@ -6,7 +6,7 @@ import chalk from 'chalk'; import program from 'commander'; import dedent from 'ts-dedent'; -import esMain from '../utils/esmain'; +import { esMain } from '../utils/esmain'; import { githubRestClient } from './utils/github-client'; program diff --git a/scripts/release/ensure-next-ahead.ts b/scripts/release/ensure-next-ahead.ts index 4bc4bfbab35b..308004f031cf 100644 --- a/scripts/release/ensure-next-ahead.ts +++ b/scripts/release/ensure-next-ahead.ts @@ -14,7 +14,7 @@ import program from 'commander'; import semver from 'semver'; import { z } from 'zod'; import { readJson } from 'fs-extra'; -import esMain from '../utils/esmain'; +import { esMain } from '../utils/esmain'; import { run as bumpVersion } from './version'; import { git } from './utils/git-client'; diff --git a/scripts/release/generate-pr-description.ts b/scripts/release/generate-pr-description.ts index 31bcc3c63c1a..438c13fb4a91 100644 --- a/scripts/release/generate-pr-description.ts +++ b/scripts/release/generate-pr-description.ts @@ -5,7 +5,7 @@ import { z } from 'zod'; import dedent from 'ts-dedent'; import semver from 'semver'; import { setOutput } from '@actions/core'; -import esMain from '../utils/esmain'; +import { esMain } from '../utils/esmain'; import type { Change } from './utils/get-changes'; import { getChanges, LABELS_BY_IMPORTANCE, RELEASED_LABELS } from './utils/get-changes'; import { getCurrentVersion } from './get-current-version'; diff --git a/scripts/release/get-changelog-from-file.ts b/scripts/release/get-changelog-from-file.ts index 62a248f06d97..d400ad581507 100644 --- a/scripts/release/get-changelog-from-file.ts +++ b/scripts/release/get-changelog-from-file.ts @@ -6,7 +6,7 @@ import { readFile } from 'fs-extra'; import path from 'path'; import semver from 'semver'; import dedent from 'ts-dedent'; -import esMain from '../utils/esmain'; +import { esMain } from '../utils/esmain'; import { getCurrentVersion } from './get-current-version'; program diff --git a/scripts/release/get-current-version.ts b/scripts/release/get-current-version.ts index 7fa283d4f08e..fffa703ab088 100644 --- a/scripts/release/get-current-version.ts +++ b/scripts/release/get-current-version.ts @@ -3,7 +3,7 @@ import chalk from 'chalk'; import { setOutput } from '@actions/core'; import path from 'path'; import { readJson } from 'fs-extra'; -import esMain from '../utils/esmain'; +import { esMain } from '../utils/esmain'; const CODE_DIR_PATH = path.join(__dirname, '..', '..', 'code'); const CODE_PACKAGE_JSON_PATH = path.join(CODE_DIR_PATH, 'package.json'); diff --git a/scripts/release/get-version-changelog.ts b/scripts/release/get-version-changelog.ts index a3c6e645f793..ce0464d62517 100644 --- a/scripts/release/get-version-changelog.ts +++ b/scripts/release/get-version-changelog.ts @@ -2,7 +2,7 @@ import { setOutput } from '@actions/core'; import chalk from 'chalk'; import { program } from 'commander'; -import esMain from '../utils/esmain'; +import { esMain } from '../utils/esmain'; import { getCurrentVersion } from './get-current-version'; import { getChanges } from './utils/get-changes'; diff --git a/scripts/release/is-pr-frozen.ts b/scripts/release/is-pr-frozen.ts index 2eb52528dda7..70d04c9509f2 100644 --- a/scripts/release/is-pr-frozen.ts +++ b/scripts/release/is-pr-frozen.ts @@ -4,7 +4,7 @@ import program from 'commander'; import { setOutput } from '@actions/core'; import path from 'path'; import { readJson } from 'fs-extra'; -import esMain from '../utils/esmain'; +import { esMain } from '../utils/esmain'; import { getPullInfoFromCommit } from './utils/get-github-info'; import { git } from './utils/git-client'; diff --git a/scripts/release/is-prerelease.ts b/scripts/release/is-prerelease.ts index ef15bf6c40b2..b35f423820ea 100644 --- a/scripts/release/is-prerelease.ts +++ b/scripts/release/is-prerelease.ts @@ -3,7 +3,7 @@ import chalk from 'chalk'; import program from 'commander'; import { setOutput } from '@actions/core'; import semver from 'semver'; -import esMain from '../utils/esmain'; +import { esMain } from '../utils/esmain'; import { getCurrentVersion } from './get-current-version'; program diff --git a/scripts/release/is-version-published.ts b/scripts/release/is-version-published.ts index 6a57efa92d55..54c19a465eb7 100644 --- a/scripts/release/is-version-published.ts +++ b/scripts/release/is-version-published.ts @@ -3,7 +3,7 @@ import chalk from 'chalk'; import program from 'commander'; import { setOutput } from '@actions/core'; import fetch from 'node-fetch'; -import esMain from '../utils/esmain'; +import { esMain } from '../utils/esmain'; import { getCurrentVersion } from './get-current-version'; program diff --git a/scripts/release/label-patches.ts b/scripts/release/label-patches.ts index 68572d45c87c..453e64105abf 100644 --- a/scripts/release/label-patches.ts +++ b/scripts/release/label-patches.ts @@ -1,7 +1,7 @@ import program from 'commander'; import { v4 as uuidv4 } from 'uuid'; import ora from 'ora'; -import esMain from '../utils/esmain'; +import { esMain } from '../utils/esmain'; import { getLabelIds, githubGraphQlClient, getUnpickedPRs } from './utils/github-client'; import { getPullInfoFromCommits, getRepo } from './utils/get-changes'; import { getLatestTag, git } from './utils/git-client'; diff --git a/scripts/release/pick-patches.ts b/scripts/release/pick-patches.ts index 9bdbf53977ec..be713f5f5d51 100644 --- a/scripts/release/pick-patches.ts +++ b/scripts/release/pick-patches.ts @@ -5,7 +5,7 @@ import chalk from 'chalk'; import ora from 'ora'; import { setOutput } from '@actions/core'; import invariant from 'tiny-invariant'; -import esMain from '../utils/esmain'; +import { esMain } from '../utils/esmain'; import { git } from './utils/git-client'; import { getUnpickedPRs } from './utils/github-client'; diff --git a/scripts/release/publish.ts b/scripts/release/publish.ts index c5f509ccd00a..cd69f5260ce8 100644 --- a/scripts/release/publish.ts +++ b/scripts/release/publish.ts @@ -9,7 +9,7 @@ import fetch from 'node-fetch'; import dedent from 'ts-dedent'; import pRetry from 'p-retry'; import { execaCommand } from 'execa'; -import esMain from '../utils/esmain'; +import { esMain } from '../utils/esmain'; program .name('publish') diff --git a/scripts/release/unreleased-changes-exists.ts b/scripts/release/unreleased-changes-exists.ts index e076e640d302..7944edbac73f 100644 --- a/scripts/release/unreleased-changes-exists.ts +++ b/scripts/release/unreleased-changes-exists.ts @@ -4,7 +4,7 @@ import program from 'commander'; import { z } from 'zod'; import { setOutput } from '@actions/core'; import { intersection } from 'lodash'; -import esMain from '../utils/esmain'; +import { esMain } from '../utils/esmain'; import type { Change } from './utils/get-changes'; import { RELEASED_LABELS, getChanges } from './utils/get-changes'; import { getCurrentVersion } from './get-current-version'; diff --git a/scripts/release/version.ts b/scripts/release/version.ts index db3f30fa8a80..c56d7afa5b54 100644 --- a/scripts/release/version.ts +++ b/scripts/release/version.ts @@ -7,7 +7,7 @@ import program from 'commander'; import semver from 'semver'; import { z } from 'zod'; import { execaCommand } from 'execa'; -import esMain from '../utils/esmain'; +import { esMain } from '../utils/esmain'; import type { Workspace } from '../utils/workspace'; import { getWorkspaces } from '../utils/workspace'; diff --git a/scripts/release/write-changelog.ts b/scripts/release/write-changelog.ts index 30a64dd366ee..5af64eba3a8e 100644 --- a/scripts/release/write-changelog.ts +++ b/scripts/release/write-changelog.ts @@ -5,7 +5,7 @@ import program from 'commander'; import semver from 'semver'; import { z } from 'zod'; import { readFile, writeFile, writeJson } from 'fs-extra'; -import esMain from '../utils/esmain'; +import { esMain } from '../utils/esmain'; import { getChanges } from './utils/get-changes'; program diff --git a/scripts/sandbox/generate.ts b/scripts/sandbox/generate.ts index e94459e4d915..8f7ae78fb0d2 100755 --- a/scripts/sandbox/generate.ts +++ b/scripts/sandbox/generate.ts @@ -7,7 +7,7 @@ import { copy, emptyDir, ensureDir, move, remove, rename, writeFile } from 'fs-e import { program } from 'commander'; import { directory } from 'tempy'; import { execaCommand } from 'execa'; -import esMain from '../utils/esmain'; +import { esMain } from '../utils/esmain'; import type { OptionValues } from '../utils/options'; import { createOptions } from '../utils/options'; diff --git a/scripts/utils/esmain.ts b/scripts/utils/esmain.ts index 286f8b250276..edc9d07b4322 100644 --- a/scripts/utils/esmain.ts +++ b/scripts/utils/esmain.ts @@ -21,7 +21,7 @@ export function stripExt(name: string) { * Check if a module was run directly with node as opposed to being * imported from another module. */ -export default function esMain(url: string) { +export function esMain(url: string) { if (!url || !process.argv[1]) { return false; } From 737a3ed0070d5caebee7fac0df77d0d460736762 Mon Sep 17 00:00:00 2001 From: Jeppe Reinhold Date: Tue, 14 Nov 2023 17:29:45 +0100 Subject: [PATCH 042/170] cleanup addon-actions dependencies --- code/addons/actions/package.json | 6 +----- code/yarn.lock | 6 ------ 2 files changed, 1 insertion(+), 11 deletions(-) diff --git a/code/addons/actions/package.json b/code/addons/actions/package.json index 88b89cc58fb0..3df803987dac 100644 --- a/code/addons/actions/package.json +++ b/code/addons/actions/package.json @@ -64,13 +64,9 @@ }, "dependencies": { "@storybook/global": "^5.0.0", - "@types/lodash": "^4.14.167", "@types/uuid": "^9.0.1", "dequal": "^2.0.2", - "lodash": "^4.17.21", "polished": "^4.2.2", - "telejson": "^7.2.0", - "ts-dedent": "^2.0.0", "uuid": "^9.0.0" }, "devDependencies": { @@ -81,10 +77,10 @@ "@storybook/preview-api": "workspace:*", "@storybook/theming": "workspace:*", "@storybook/types": "workspace:*", - "prop-types": "^15.7.2", "react": "^16.8.0", "react-dom": "^16.8.0", "react-inspector": "^6.0.0", + "telejson": "^7.2.0", "typescript": "~4.9.3" }, "publishConfig": { diff --git a/code/yarn.lock b/code/yarn.lock index 6cc2650da012..bd945338259f 100644 --- a/code/yarn.lock +++ b/code/yarn.lock @@ -5373,17 +5373,13 @@ __metadata: "@storybook/preview-api": "workspace:*" "@storybook/theming": "workspace:*" "@storybook/types": "workspace:*" - "@types/lodash": "npm:^4.14.167" "@types/uuid": "npm:^9.0.1" dequal: "npm:^2.0.2" - lodash: "npm:^4.17.21" polished: "npm:^4.2.2" - prop-types: "npm:^15.7.2" react: "npm:^16.8.0" react-dom: "npm:^16.8.0" react-inspector: "npm:^6.0.0" telejson: "npm:^7.2.0" - ts-dedent: "npm:^2.0.0" typescript: "npm:~4.9.3" uuid: "npm:^9.0.0" languageName: unknown @@ -6820,8 +6816,6 @@ __metadata: peerDependenciesMeta: "@next/font": optional: true - "@storybook/addon-actions": - optional: true typescript: optional: true webpack: From 7e07d354d90ff279e885f0616c6c9011762617e2 Mon Sep 17 00:00:00 2001 From: Jeppe Reinhold Date: Tue, 14 Nov 2023 17:34:21 +0100 Subject: [PATCH 043/170] use ESM in nextjs framework, rework conditional importing of nextjs contexts --- code/frameworks/nextjs/package.json | 9 +--- .../nextjs/src/nextImport/webpack.ts | 3 +- code/frameworks/nextjs/src/preset.ts | 2 +- .../src/routing/app-router-provider.tsx | 54 +++++-------------- .../nextjs/src/routing/decorator.tsx | 32 ++++++----- .../src/routing/page-router-provider.tsx | 4 +- 6 files changed, 36 insertions(+), 68 deletions(-) diff --git a/code/frameworks/nextjs/package.json b/code/frameworks/nextjs/package.json index 99a3da9d8fb5..356b2eb48b0c 100644 --- a/code/frameworks/nextjs/package.json +++ b/code/frameworks/nextjs/package.json @@ -36,11 +36,7 @@ "types": "./dist/preset.d.ts", "require": "./dist/preset.js" }, - "./preview.js": { - "types": "./dist/preview.d.ts", - "require": "./dist/preview.js", - "import": "./dist/preview.mjs" - }, + "./dist/preview.mjs": "./dist/preview.mjs", "./next-image-loader-stub.js": { "types": "./dist/next-image-loader-stub.d.ts", "require": "./dist/next-image-loader-stub.js", @@ -136,9 +132,6 @@ "@next/font": { "optional": true }, - "@storybook/addon-actions": { - "optional": true - }, "typescript": { "optional": true }, diff --git a/code/frameworks/nextjs/src/nextImport/webpack.ts b/code/frameworks/nextjs/src/nextImport/webpack.ts index fc5d359ef8e2..35f39a7069ed 100644 --- a/code/frameworks/nextjs/src/nextImport/webpack.ts +++ b/code/frameworks/nextjs/src/nextImport/webpack.ts @@ -24,7 +24,8 @@ export function configureNextImport(baseConfig: WebpackConfig) { baseConfig.plugins.push( new IgnorePlugin({ // ignore next/dist/shared/lib/hooks-client-context and next/legacy/image imports - resourceRegExp: /(next\/dist\/shared\/lib\/hooks-client-context|next\/legacy\/image)$/, + resourceRegExp: + /(next\/dist\/shared\/lib\/hooks-client-context|next\/dist\/shared\/lib\/hooks-client-context\.shared-runtime|next\/legacy\/image)$/, }) ); } diff --git a/code/frameworks/nextjs/src/preset.ts b/code/frameworks/nextjs/src/preset.ts index fd726835293c..7b0e150f735a 100644 --- a/code/frameworks/nextjs/src/preset.ts +++ b/code/frameworks/nextjs/src/preset.ts @@ -69,7 +69,7 @@ export const core: PresetProperty<'core', StorybookConfig> = async (config, opti export const previewAnnotations: StorybookConfig['previewAnnotations'] = (entry = []) => [ ...entry, - require.resolve('@storybook/nextjs/preview.js'), + join(dirname(require.resolve('@storybook/nextjs/package.json')), 'dist/preview.mjs'), ]; // Not even sb init - automigrate - running dev diff --git a/code/frameworks/nextjs/src/routing/app-router-provider.tsx b/code/frameworks/nextjs/src/routing/app-router-provider.tsx index a7f0bd326f9b..c8b1c96c80a3 100644 --- a/code/frameworks/nextjs/src/routing/app-router-provider.tsx +++ b/code/frameworks/nextjs/src/routing/app-router-provider.tsx @@ -1,48 +1,16 @@ import React from 'react'; -import type { - LayoutRouterContext as TLayoutRouterContext, - AppRouterContext as TAppRouterContext, - GlobalLayoutRouterContext as TGlobalLayoutRouterContext, +import { + LayoutRouterContext, + AppRouterContext, + GlobalLayoutRouterContext, } from 'next/dist/shared/lib/app-router-context.shared-runtime'; -import type { - PathnameContext as TPathnameContext, - SearchParamsContext as TSearchParamsContext, +import { + PathnameContext, + SearchParamsContext, } from 'next/dist/shared/lib/hooks-client-context.shared-runtime'; import type { FlightRouterState } from 'next/dist/server/app-render/types'; import type { RouteParams } from './types'; -/** - * Normally dynamic imports are necessary because otherwise - * older versions of Next.js will throw an error - * because AppRouterProviders only exists in Next.js > v13 - * Using React.lazy though is currently not supported in SB decorators - * therefore using the try/catch workaround - */ -let AppRouterContext: typeof TAppRouterContext; -let LayoutRouterContext: typeof TLayoutRouterContext; -let PathnameContext: typeof TPathnameContext; -let SearchParamsContext: typeof TSearchParamsContext; -let GlobalLayoutRouterContext: typeof TGlobalLayoutRouterContext; - -try { - AppRouterContext = - require('next/dist/shared/lib/app-router-context.shared-runtime').AppRouterContext; - LayoutRouterContext = - require('next/dist/shared/lib/app-router-context.shared-runtime').LayoutRouterContext; - PathnameContext = - require('next/dist/shared/lib/hooks-client-context.shared-runtime').PathnameContext; - SearchParamsContext = - require('next/dist/shared/lib/hooks-client-context.shared-runtime').SearchParamsContext; - GlobalLayoutRouterContext = - require('next/dist/shared/lib/app-router-context.shared-runtime').GlobalLayoutRouterContext; -} catch { - AppRouterContext = React.Fragment as any; - LayoutRouterContext = React.Fragment as any; - PathnameContext = React.Fragment as any; - SearchParamsContext = React.Fragment as any; - GlobalLayoutRouterContext = React.Fragment as any; -} - type AppRouterProviderProps = { action: (name: string) => (...args: any[]) => void; routeParams: RouteParams; @@ -58,7 +26,11 @@ const getParallelRoutes = (segmentsList: Array): FlightRouterState => { return [] as any; }; -const AppRouterProvider: React.FC = ({ children, action, routeParams }) => { +export const AppRouterProvider: React.FC = ({ + children, + action, + routeParams, +}) => { const { pathname, query, segments = [], ...restRouteParams } = routeParams; const tree: FlightRouterState = [pathname, { children: getParallelRoutes([...segments]) }]; @@ -121,5 +93,3 @@ const AppRouterProvider: React.FC = ({ children, action, ); }; - -export default AppRouterProvider; diff --git a/code/frameworks/nextjs/src/routing/decorator.tsx b/code/frameworks/nextjs/src/routing/decorator.tsx index 8312b8e9d80c..059e378c2521 100644 --- a/code/frameworks/nextjs/src/routing/decorator.tsx +++ b/code/frameworks/nextjs/src/routing/decorator.tsx @@ -1,20 +1,10 @@ import * as React from 'react'; -// this will be aliased by webpack at runtime (this is just for typing) -import type { action as originalAction } from '@storybook/addon-actions'; import type { Addon_StoryContext } from '@storybook/types'; -import AppRouterProvider from './app-router-provider'; - -import PageRouterProvider from './page-router-provider'; +import { action } from '@storybook/addon-actions'; +import { PageRouterProvider } from './page-router-provider'; +import type { AppRouterProvider as TAppRouterProvider } from './app-router-provider'; import type { RouteParams, NextAppDirectory } from './types'; -let action: typeof originalAction; - -try { - action = require('@storybook/addon-actions').action; -} catch { - action = () => () => {}; -} - const defaultRouterParams: RouteParams = { pathname: '/', query: {}, @@ -27,7 +17,23 @@ export const RouterDecorator = ( const nextAppDirectory = (parameters.nextjs?.appDirectory as NextAppDirectory | undefined) ?? false; + const [AppRouterProvider, setAppRouterProvider] = React.useState< + typeof TAppRouterProvider | undefined + >(); + + React.useEffect(() => { + if (!nextAppDirectory) { + return; + } + import('./app-router-provider').then((exports) => + setAppRouterProvider(() => exports.AppRouterProvider) + ); + }, [nextAppDirectory]); + if (nextAppDirectory) { + if (!AppRouterProvider) { + return null; + } return ( = ({ +export const PageRouterProvider: React.FC = ({ children, action, routeParams, @@ -66,5 +66,3 @@ const PageRouterProvider: React.FC = ({ {children} ); - -export default PageRouterProvider; From 13c577994260f6097ae0fda55becf3b8da5caf19 Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Wed, 15 Nov 2023 10:31:11 +0100 Subject: [PATCH 044/170] Add skipCompiler option to TypeScript presets --- .../src/preview/iframe-webpack.config.ts | 3 ++- code/frameworks/angular/src/preset.ts | 1 + code/frameworks/vue-vite/src/preset.ts | 1 + code/frameworks/vue-webpack5/src/preset.ts | 1 + code/frameworks/vue3-webpack5/src/preset.ts | 1 + code/lib/types/src/modules/core-common.ts | 8 ++++++++ docs/api/main-config-typescript.md | 18 ++++++++++++++++++ ...main-config-typescript-skip-compiler.ts.mdx | 16 ++++++++++++++++ 8 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 docs/snippets/common/main-config-typescript-skip-compiler.ts.mdx diff --git a/code/builders/builder-webpack5/src/preview/iframe-webpack.config.ts b/code/builders/builder-webpack5/src/preview/iframe-webpack.config.ts index 13b02df7264f..70c212896501 100644 --- a/code/builders/builder-webpack5/src/preview/iframe-webpack.config.ts +++ b/code/builders/builder-webpack5/src/preview/iframe-webpack.config.ts @@ -200,7 +200,8 @@ export default async ( } } - const shouldCheckTs = typescriptOptions.check && !typescriptOptions.skipBabel; + const shouldCheckTs = + typescriptOptions.check && !typescriptOptions.skipBabel && !typescriptOptions.skipCompiler; const tsCheckOptions = typescriptOptions.checkOptions || {}; const cacheConfig = builderOptions.fsCache ? { cache: { type: 'filesystem' as const } } : {}; diff --git a/code/frameworks/angular/src/preset.ts b/code/frameworks/angular/src/preset.ts index ce5796d0c222..f093cb6cc8b8 100644 --- a/code/frameworks/angular/src/preset.ts +++ b/code/frameworks/angular/src/preset.ts @@ -41,5 +41,6 @@ export const typescript: PresetProperty<'typescript', StorybookConfig> = async ( return { ...config, skipBabel: true, + skipCompiler: true, }; }; diff --git a/code/frameworks/vue-vite/src/preset.ts b/code/frameworks/vue-vite/src/preset.ts index bf5b7d45ea5b..736e8860f906 100644 --- a/code/frameworks/vue-vite/src/preset.ts +++ b/code/frameworks/vue-vite/src/preset.ts @@ -23,6 +23,7 @@ export const core: PresetProperty<'core', StorybookConfig> = async (config, opti export const typescript: PresetProperty<'typescript', StorybookConfig> = async (config) => ({ ...config, skipBabel: true, + skipCompiler: true, }); export const viteFinal: StorybookConfig['viteFinal'] = async (config, { presets }) => { diff --git a/code/frameworks/vue-webpack5/src/preset.ts b/code/frameworks/vue-webpack5/src/preset.ts index 661053fddefb..1e493e9a7f99 100644 --- a/code/frameworks/vue-webpack5/src/preset.ts +++ b/code/frameworks/vue-webpack5/src/preset.ts @@ -25,4 +25,5 @@ export const core: PresetProperty<'core', StorybookConfig> = async (config, opti export const typescript: PresetProperty<'typescript', StorybookConfig> = async (config) => ({ ...config, skipBabel: true, + skipCompiler: true, }); diff --git a/code/frameworks/vue3-webpack5/src/preset.ts b/code/frameworks/vue3-webpack5/src/preset.ts index 0dd1e931ddd4..1714cc16075e 100644 --- a/code/frameworks/vue3-webpack5/src/preset.ts +++ b/code/frameworks/vue3-webpack5/src/preset.ts @@ -25,4 +25,5 @@ export const core: PresetProperty<'core', StorybookConfig> = async (config, opti export const typescript: PresetProperty<'typescript', StorybookConfig> = async (config) => ({ ...config, skipBabel: true, + skipCompiler: true, }); diff --git a/code/lib/types/src/modules/core-common.ts b/code/lib/types/src/modules/core-common.ts index f5043c362d7c..2aace3e79d40 100644 --- a/code/lib/types/src/modules/core-common.ts +++ b/code/lib/types/src/modules/core-common.ts @@ -223,8 +223,16 @@ export interface TypescriptOptions { * Disable parsing typescript files through babel. * * @default `false` + * @deprecated use `skipCompiler` instead */ skipBabel: boolean; + + /** + * Disable parsing typescript files through compiler. + * + * @default `false` + */ + skipCompiler: boolean; } export type Preset = diff --git a/docs/api/main-config-typescript.md b/docs/api/main-config-typescript.md index 425f8703777a..5ac80985eb9f 100644 --- a/docs/api/main-config-typescript.md +++ b/docs/api/main-config-typescript.md @@ -90,6 +90,8 @@ Only available for React Storybook projects. Options to pass to react-docgen-typ ## `skipBabel` +Deprecated: Will be removed in Storybook 8.0. Use `skipCompiler` instead + Type: `boolean` Disable parsing of TypeScript files through babel. @@ -103,3 +105,19 @@ Disable parsing of TypeScript files through babel. /> + +## `skipCompiler` + +Type: `boolean` + +Disable parsing of TypeScript files through the compiler, which is used for Webpack5. + + + + + + diff --git a/docs/snippets/common/main-config-typescript-skip-compiler.ts.mdx b/docs/snippets/common/main-config-typescript-skip-compiler.ts.mdx new file mode 100644 index 000000000000..aefe172fc6c1 --- /dev/null +++ b/docs/snippets/common/main-config-typescript-skip-compiler.ts.mdx @@ -0,0 +1,16 @@ +```ts +// .storybook/main.ts + +// Replace your-framework with the framework you are using (e.g., react-webpack5, vue3-vite) +import type { StorybookConfig } from '@storybook/your-framework'; + +const config: StorybookConfig = { + framework: '@storybook/your-framework', + stories: ['../src/**/*.mdx', '../src/**/*.stories.@(js|jsx|mjs|ts|tsx)'], + typescript: { + skipCompiler: true, + }, +}; + +export default config; +``` From b36a055c987269b7208461aa9ef80167de528287 Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Wed, 15 Nov 2023 12:59:06 +0100 Subject: [PATCH 045/170] Add file extension to CommonJS file import and remove dynamic imports --- .github/workflows/generate-sandboxes-main.yml | 2 +- .github/workflows/generate-sandboxes-next.yml | 2 +- scripts/tasks/bench.ts | 9 +++++++-- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/.github/workflows/generate-sandboxes-main.yml b/.github/workflows/generate-sandboxes-main.yml index 7d9328578493..ab3d72df342b 100644 --- a/.github/workflows/generate-sandboxes-main.yml +++ b/.github/workflows/generate-sandboxes-main.yml @@ -30,7 +30,7 @@ jobs: git config --global user.name "Storybook Bot" git config --global user.email "bot@storybook.js.org" - name: Install dependencies - run: node ./scripts/check-dependencies.js + run: node ./scripts/check-dependencies.cjs - name: Compile Storybook libraries run: yarn task --task compile --start-from=auto --no-link - name: Publishing to local registry diff --git a/.github/workflows/generate-sandboxes-next.yml b/.github/workflows/generate-sandboxes-next.yml index 8a28c4cbb23a..465fb44b7980 100644 --- a/.github/workflows/generate-sandboxes-next.yml +++ b/.github/workflows/generate-sandboxes-next.yml @@ -30,7 +30,7 @@ jobs: git config --global user.name "Storybook Bot" git config --global user.email "bot@storybook.js.org" - name: Install dependencies - run: node ./scripts/check-dependencies.js + run: node ./scripts/check-dependencies.cjs - name: Compile Storybook libraries run: yarn task --task compile --start-from=auto --no-link - name: Publishing to local registry diff --git a/scripts/tasks/bench.ts b/scripts/tasks/bench.ts index 349d79ea7fa9..cead08852edb 100644 --- a/scripts/tasks/bench.ts +++ b/scripts/tasks/bench.ts @@ -1,3 +1,4 @@ +/* eslint-disable import/extensions */ import prettyBytes from 'pretty-bytes'; import prettyTime from 'pretty-ms'; @@ -19,8 +20,10 @@ export const bench: Task = { const controllers: AbortController[] = []; try { const { disableDocs } = options; - const { browse } = await import('../bench/browse'); - const { saveBench, loadBench } = await import('../bench/utils'); + // @ts-expect-error Default import required for dynamic import processed by esbuild + const { browse } = (await import('../bench/browse.ts')).default; + // @ts-expect-error Default import required for dynamic import processed by esbuild + const { saveBench, loadBench } = (await import('../bench/utils.ts')).default; const devController = await dev.run(details, { ...options, debug: false }); if (!devController) { @@ -28,6 +31,7 @@ export const bench: Task = { } controllers.push(devController); const devBrowseResult = await browse(`http://localhost:${devPort}`, { disableDocs }); + devController.abort(); const serveController = await serve.run(details, { ...options, debug: false }); @@ -35,6 +39,7 @@ export const bench: Task = { throw new Error('serve: controller is null'); } controllers.push(serveController); + const buildBrowseResult = await browse(`http://localhost:${servePort}`, { disableDocs }); serveController.abort(); From b7e3e3736040846662d29505f9dfa43ac71a7d6f Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Wed, 15 Nov 2023 13:37:13 +0100 Subject: [PATCH 046/170] Convert check-dependencies script into Typescript --- .github/workflows/generate-sandboxes-main.yml | 5 ++++- .github/workflows/generate-sandboxes-next.yml | 5 ++++- scripts/check-dependencies.cjs | 7 ------- scripts/check-dependencies.ts | 7 +++++++ 4 files changed, 15 insertions(+), 9 deletions(-) delete mode 100755 scripts/check-dependencies.cjs create mode 100755 scripts/check-dependencies.ts diff --git a/.github/workflows/generate-sandboxes-main.yml b/.github/workflows/generate-sandboxes-main.yml index ab3d72df342b..adea48c1b2f6 100644 --- a/.github/workflows/generate-sandboxes-main.yml +++ b/.github/workflows/generate-sandboxes-main.yml @@ -30,7 +30,10 @@ jobs: git config --global user.name "Storybook Bot" git config --global user.email "bot@storybook.js.org" - name: Install dependencies - run: node ./scripts/check-dependencies.cjs + run: | + cd ./scripts + node --loader esbuild-register/loader -r esbuild-register ./check-dependencies.ts + cd .. - name: Compile Storybook libraries run: yarn task --task compile --start-from=auto --no-link - name: Publishing to local registry diff --git a/.github/workflows/generate-sandboxes-next.yml b/.github/workflows/generate-sandboxes-next.yml index 465fb44b7980..9a00f8b99cdc 100644 --- a/.github/workflows/generate-sandboxes-next.yml +++ b/.github/workflows/generate-sandboxes-next.yml @@ -30,7 +30,10 @@ jobs: git config --global user.name "Storybook Bot" git config --global user.email "bot@storybook.js.org" - name: Install dependencies - run: node ./scripts/check-dependencies.cjs + run: | + cd ./scripts + node --loader esbuild-register/loader -r esbuild-register ./check-dependencies.ts + cd .. - name: Compile Storybook libraries run: yarn task --task compile --start-from=auto --no-link - name: Publishing to local registry diff --git a/scripts/check-dependencies.cjs b/scripts/check-dependencies.cjs deleted file mode 100755 index c8bd9114faf9..000000000000 --- a/scripts/check-dependencies.cjs +++ /dev/null @@ -1,7 +0,0 @@ -#!/usr/bin/env node -const { checkDependencies } = require('./utils/cli-utils'); - -checkDependencies().catch((e) => { - console.error(e); - process.exit(1); -}); diff --git a/scripts/check-dependencies.ts b/scripts/check-dependencies.ts new file mode 100755 index 000000000000..babee83b82f6 --- /dev/null +++ b/scripts/check-dependencies.ts @@ -0,0 +1,7 @@ +import { checkDependencies } from './utils/cli-utils'; + +checkDependencies().catch((e) => { + // eslint-disable-next-line no-console + console.error(e); + process.exit(1); +}); From 3a24793dbc8aa54e61a4962d0b4e9253a0191ca9 Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Wed, 15 Nov 2023 15:10:12 +0100 Subject: [PATCH 047/170] Remove Typescript preset override for vue-vite --- code/frameworks/vue-vite/src/preset.ts | 6 ------ 1 file changed, 6 deletions(-) diff --git a/code/frameworks/vue-vite/src/preset.ts b/code/frameworks/vue-vite/src/preset.ts index 736e8860f906..3030587afaaa 100644 --- a/code/frameworks/vue-vite/src/preset.ts +++ b/code/frameworks/vue-vite/src/preset.ts @@ -20,12 +20,6 @@ export const core: PresetProperty<'core', StorybookConfig> = async (config, opti }; }; -export const typescript: PresetProperty<'typescript', StorybookConfig> = async (config) => ({ - ...config, - skipBabel: true, - skipCompiler: true, -}); - export const viteFinal: StorybookConfig['viteFinal'] = async (config, { presets }) => { return mergeConfig(config, { plugins: [vueDocgen()], From ec2d929e0f60ab939db46408b163cceef2002687 Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Wed, 15 Nov 2023 15:10:33 +0100 Subject: [PATCH 048/170] Clarify docs on skipCompiler option --- .../snippets/common/main-config-typescript-skip-compiler.ts.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/snippets/common/main-config-typescript-skip-compiler.ts.mdx b/docs/snippets/common/main-config-typescript-skip-compiler.ts.mdx index aefe172fc6c1..85c216504c27 100644 --- a/docs/snippets/common/main-config-typescript-skip-compiler.ts.mdx +++ b/docs/snippets/common/main-config-typescript-skip-compiler.ts.mdx @@ -1,7 +1,7 @@ ```ts // .storybook/main.ts -// Replace your-framework with the framework you are using (e.g., react-webpack5, vue3-vite) +// Replace your-framework with the framework you are using (e.g., react-webpack5) import type { StorybookConfig } from '@storybook/your-framework'; const config: StorybookConfig = { From 217b11ed389ee9c87f3eef132fe4fd81d2dea67b Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Wed, 15 Nov 2023 15:12:26 +0100 Subject: [PATCH 049/170] Add entry to Migration.md about skipCompiler --- MIGRATION.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/MIGRATION.md b/MIGRATION.md index ca14c266b621..385aeef95a56 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -1,6 +1,7 @@

Migration

- [From version 7.5.0 to 7.6.0](#from-version-750-to-760) + - [typescript.skipBabel deprecated](#typescriptskipbabel-deprecated) - [Primary doc block accepts of prop](#primary-doc-block-accepts-of-prop) - [Addons no longer need a peer dependency on React](#addons-no-longer-need-a-peer-dependency-on-react) - [From version 7.4.0 to 7.5.0](#from-version-740-to-750) @@ -310,6 +311,10 @@ ## From version 7.5.0 to 7.6.0 +#### typescript.skipBabel deprecated + +We will remove the `typescript.skipBabel` option in Storybook 8.0.0. Please use `typescirpt.skipCompiler` instead. + #### Primary doc block accepts of prop The `Primary` doc block now also accepts an `of` prop as described in the [Doc Blocks](#doc-blocks) section. It still accepts being passed `name` or no props at all. From 1eda85a97df5b3062fd228956a85c5c6e38ede1c Mon Sep 17 00:00:00 2001 From: Kasper Peulen Date: Wed, 15 Nov 2023 16:11:26 +0100 Subject: [PATCH 050/170] Warn on implicit actions --- MIGRATION.md | 50 ++++++++++++++++++ code/addons/actions/src/runtime/action.ts | 52 +++++++++++++------ .../core-events/src/errors/preview-errors.ts | 26 ++++++++++ .../core-server/src/presets/common-preset.ts | 1 + code/lib/types/src/modules/core-common.ts | 7 +++ 5 files changed, 120 insertions(+), 16 deletions(-) diff --git a/MIGRATION.md b/MIGRATION.md index ca14c266b621..77a3ae9613e4 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -1,6 +1,7 @@

Migration

- [From version 7.5.0 to 7.6.0](#from-version-750-to-760) + - [Using implicit actions during rendering is deprecated (for example in the play function)](#using-implicit-actions-during-rendering-is-deprecated-for-example-in-the-play-function) - [Primary doc block accepts of prop](#primary-doc-block-accepts-of-prop) - [Addons no longer need a peer dependency on React](#addons-no-longer-need-a-peer-dependency-on-react) - [From version 7.4.0 to 7.5.0](#from-version-740-to-750) @@ -310,6 +311,55 @@ ## From version 7.5.0 to 7.6.0 +#### Using implicit actions during rendering is deprecated (for example in the play function) + +In Storybook 7, we inferred if the component accepts any action props, +by checking if it starts with `onX` (for example `onClick`), or as configured by `actions.argTypesRegex`. +If that was the case, we would fill in jest spies for those args automatically. + +```ts +export default { + component: Button, +}; + +export const ButtonClick = { + play: async ({ args, canvasElement }) => { + await userEvent.click(within(canvasElement).getByRole('button')); + // args.onClick is a jest spy in 7.0 + await expect(args.onClick).toHaveBeenCalled(); + }, +}; +``` + +In Storybook 8 this feature will be removed, and spies have to added explicitly: + +```ts +import { fn } from '@storybook/test'; + +export default { + component: Button, + args: { + onClick: fn(), + }, +}; + +export const ButtonClick = { + play: async ({ args, canvasElement }) => { + await userEvent.click(within(canvasElement).getByRole('button')); + await expect(args.onClick).toHaveBeenCalled(); + }, +}; +``` + +For more context, see this RFC: +https://github.com/storybookjs/storybook/discussions/23649 + +To summarize: + +- This makes CSF files less magical and more portable, so that CSF files will render the same in a test environment where docgen is not available. +- This allows users and (test) integrators to run or build storybook without docgen, boosting the user performance and allows tools to give quicker feedback. +- This will make sure that we can one day lazy load docgen, without changing how stories are rendered. + #### Primary doc block accepts of prop The `Primary` doc block now also accepts an `of` prop as described in the [Doc Blocks](#doc-blocks) section. It still accepts being passed `name` or no props at all. diff --git a/code/addons/actions/src/runtime/action.ts b/code/addons/actions/src/runtime/action.ts index 9cb6055a5feb..365bb487621f 100644 --- a/code/addons/actions/src/runtime/action.ts +++ b/code/addons/actions/src/runtime/action.ts @@ -1,5 +1,10 @@ import { v4 as uuidv4 } from 'uuid'; +import type { PreviewWeb } from '@storybook/preview-api'; import { addons } from '@storybook/preview-api'; +import type { Renderer } from '@storybook/types'; +import { global } from '@storybook/global'; +import { ImplicitActionsDuringRendering } from '@storybook/core-events/preview-errors'; +import dedent from 'ts-dedent'; import { EVENT_ID } from '../constants'; import type { ActionDisplay, ActionOptions, HandlerFunction } from '../models'; import { config } from './configureActions'; @@ -54,22 +59,37 @@ export function action(name: string, options: ActionOptions = {}): HandlerFuncti }; const handler = function actionHandler(...args: any[]) { - // TODO: Enable once codemods are finished - // if (options.implicit) { - // const preview = - // '__STORYBOOK_PREVIEW__' in global - // ? (global.__STORYBOOK_PREVIEW__ as PreviewWeb) - // : undefined; - // if ( - // preview?.storyRenders.some( - // (render) => render.phase === 'playing' || render.phase === 'rendering' - // ) - // ) { - // console.warn( - // 'Can not use implicit actions during rendering or playing of a story.' - // ); - // } - // } + if (options.implicit) { + const preview = + '__STORYBOOK_PREVIEW__' in global + ? // eslint-disable-next-line no-underscore-dangle + (global.__STORYBOOK_PREVIEW__ as PreviewWeb) + : undefined; + const storyRenderer = preview?.storyRenders.find( + (render) => render.phase === 'playing' || render.phase === 'rendering' + ); + + if (storyRenderer) { + if (window?.FEATURES?.disallowImplicitActionsInRenderV8) { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + throw new ImplicitActionsDuringRendering({ phase: storyRenderer.phase!, name }); + } else { + console.warn(dedent` + We detected that you use an implicit action arg during ${storyRenderer.phase} of your story. + This is deprecated and won't work in Storybook 8 anymore. + + Please provide an explicit spy to your args like this: + import { fn } from '@storybook/test'; + ... + args: { + ${name}: fn() + } + + See: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#using-implicit-actions-during-rendering-is-deprecated-for-example-in-the-play-function + `); + } + } + } const channel = addons.getChannel(); // this makes sure that in js enviroments like react native you can still get an id diff --git a/code/lib/core-events/src/errors/preview-errors.ts b/code/lib/core-events/src/errors/preview-errors.ts index 84161db505b8..dda274d158d1 100644 --- a/code/lib/core-events/src/errors/preview-errors.ts +++ b/code/lib/core-events/src/errors/preview-errors.ts @@ -48,3 +48,29 @@ export class MissingStoryAfterHmrError extends StorybookError { - Also check the browser console and terminal for potential error messages.`; } } + +export class ImplicitActionsDuringRendering extends StorybookError { + readonly category = Category.PREVIEW_API; + + readonly code = 2; + + readonly documentation = + 'https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#using-implicit-actions-during-rendering-is-deprecated-for-example-in-the-play-function'; + + constructor(public data: { phase: string; name: string }) { + super(); + } + + template() { + return dedent` + We detected that you use an implicit action arg during ${this.data.phase} of your story. + + Please provide an explicit spy to your args like this: + import { fn } from '@storybook/test'; + ... + args: { + ${this.data.name}: fn() + } + `; + } +} diff --git a/code/lib/core-server/src/presets/common-preset.ts b/code/lib/core-server/src/presets/common-preset.ts index 6854a8f48682..9512038cc3cb 100644 --- a/code/lib/core-server/src/presets/common-preset.ts +++ b/code/lib/core-server/src/presets/common-preset.ts @@ -194,6 +194,7 @@ export const features = async ( storyStoreV7: true, argTypeTargetsV7: true, legacyDecoratorFileOrder: false, + disallowImplicitActionsInRenderV8: false, }); export const csfIndexer: Indexer = { diff --git a/code/lib/types/src/modules/core-common.ts b/code/lib/types/src/modules/core-common.ts index f5043c362d7c..839fa1cb4240 100644 --- a/code/lib/types/src/modules/core-common.ts +++ b/code/lib/types/src/modules/core-common.ts @@ -356,6 +356,13 @@ export interface StorybookConfig { * Apply decorators from preview.js before decorators from addons or frameworks */ legacyDecoratorFileOrder?: boolean; + + /** + * Disallow implicit actions during rendering. This will be the default in Storybook 8. + * + * This will make sure that your story renders the same no matter if docgen is enabled or not. + */ + disallowImplicitActionsInRenderV8?: boolean; }; build?: TestBuildConfig; From 23c89a103f536be1d225ec7d4cfae957edd5a642 Mon Sep 17 00:00:00 2001 From: Kasper Peulen Date: Wed, 15 Nov 2023 16:32:59 +0100 Subject: [PATCH 051/170] Fix dts build --- code/addons/actions/src/typings.d.ts | 1 + 1 file changed, 1 insertion(+) create mode 100644 code/addons/actions/src/typings.d.ts diff --git a/code/addons/actions/src/typings.d.ts b/code/addons/actions/src/typings.d.ts new file mode 100644 index 000000000000..fba51cec4ab6 --- /dev/null +++ b/code/addons/actions/src/typings.d.ts @@ -0,0 +1 @@ +declare var FEATURES: import('@storybook/types').StorybookConfig['features']; From 9115617281a209553d8ac05f8063aed7971a44b8 Mon Sep 17 00:00:00 2001 From: Yann Braga Date: Wed, 15 Nov 2023 17:52:43 +0100 Subject: [PATCH 052/170] gracefully handle ast parsing error in preview file --- code/lib/csf-tools/src/ConfigFile.ts | 49 ++++++++++++++++++-- code/lib/telemetry/src/storybook-metadata.ts | 18 ++++--- 2 files changed, 57 insertions(+), 10 deletions(-) diff --git a/code/lib/csf-tools/src/ConfigFile.ts b/code/lib/csf-tools/src/ConfigFile.ts index e31750a2fed6..eb2921b4e06d 100644 --- a/code/lib/csf-tools/src/ConfigFile.ts +++ b/code/lib/csf-tools/src/ConfigFile.ts @@ -1,5 +1,6 @@ /* eslint-disable no-underscore-dangle */ import fs from 'fs-extra'; +import dedent from 'ts-dedent'; import * as t from '@babel/types'; @@ -12,6 +13,30 @@ import { babelParse } from './babelParse'; const logger = console; +const getCsfParsingErrorMessage = ({ + expectedType, + foundType, + node, +}: { + expectedType: string; + foundType: string | undefined; + node: any | undefined; +}) => { + let nodeInfo = ''; + if (node) { + try { + nodeInfo = JSON.stringify(node); + } catch (e) { + // + } + } + + return dedent` + CSF Parsing error: Expected '${expectedType}' but found '${foundType}' instead in '${node?.type}'. + ${nodeInfo} + `; +}; + const propKey = (p: t.ObjectProperty) => { if (t.isIdentifier(p.key)) return p.key.name; if (t.isStringLiteral(p.key)) return p.key.value; @@ -163,7 +188,13 @@ export class ConfigFile { } }); } else { - logger.warn(`Unexpected ${JSON.stringify(node)}`); + logger.warn( + getCsfParsingErrorMessage({ + expectedType: 'ObjectExpression', + foundType: decl?.type, + node: decl || node.declaration, + }) + ); } }, }, @@ -183,7 +214,13 @@ export class ConfigFile { } }); } else { - logger.warn(`Unexpected ${JSON.stringify(node)}`); + logger.warn( + getCsfParsingErrorMessage({ + expectedType: 'VariableDeclaration', + foundType: node.declaration?.type, + node: node.declaration, + }) + ); } }, }, @@ -223,7 +260,13 @@ export class ConfigFile { } }); } else { - logger.warn(`Unexpected ${JSON.stringify(node)}`); + logger.warn( + getCsfParsingErrorMessage({ + expectedType: 'ObjectExpression', + foundType: exportObject?.type, + node: exportObject, + }) + ); } } } diff --git a/code/lib/telemetry/src/storybook-metadata.ts b/code/lib/telemetry/src/storybook-metadata.ts index 2c70b566f97d..782c4d4a4b78 100644 --- a/code/lib/telemetry/src/storybook-metadata.ts +++ b/code/lib/telemetry/src/storybook-metadata.ts @@ -164,13 +164,17 @@ export const computeStorybookMetadata = async ({ const storybookInfo = getStorybookInfo(packageJson); - const { previewConfig } = storybookInfo; - if (previewConfig) { - const config = await readConfig(previewConfig); - const usesGlobals = !!( - config.getFieldNode(['globals']) || config.getFieldNode(['globalTypes']) - ); - metadata.preview = { ...metadata.preview, usesGlobals }; + try { + const { previewConfig } = storybookInfo; + if (previewConfig) { + const config = await readConfig(previewConfig); + const usesGlobals = !!( + config.getFieldNode(['globals']) || config.getFieldNode(['globalTypes']) + ); + metadata.preview = { ...metadata.preview, usesGlobals }; + } + } catch (e) { + // gracefully handle error, as it's not critical information and AST parsing can cause trouble } const storybookVersion = storybookPackages[storybookInfo.frameworkPackage]?.version; From e33d18f2a78fd5fa3437e7dc5cc1b7465053a367 Mon Sep 17 00:00:00 2001 From: Joe Vaughan <122215197+joevaugh4n@users.noreply.github.com> Date: Wed, 15 Nov 2023 19:04:06 +0000 Subject: [PATCH 053/170] Update config.yml --- .github/ISSUE_TEMPLATE/config.yml | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index 95be4a49c705..75238b19d615 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -3,15 +3,18 @@ contact_links: - name: View documentation šŸ“š url: https://storybook.js.org/docs/ about: Check out the official docs for answers to common questions. - - name: Feature Requests šŸ’” + - name: Feature requests šŸ’” url: https://github.com/storybookjs/storybook/discussions/new?category=ideas about: Suggest a feature idea for this project. - name: Open an RFC šŸ¦„ url: https://github.com/storybookjs/storybook/discussions/new?category=rfc about: Do you want to propose a more involved change to Storybook? Open an RFC (Request for Comments) to start a discussion. - - name: Questions & discussions šŸ¤” + - name: Questions šŸ’­ + url: https://github.com/storybookjs/storybook/discussions/new?category=help + about: Need support with a Storybook problem? Open up a help request. + - name: Discussions šŸ™Œ url: https://github.com/storybookjs/storybook/discussions - about: Ask questions, show off your Storybook, etc. - - name: Community Discord šŸ’¬ + about: Show off your Storybook or discuss the project. + - name: Community Discord šŸŽ‰ url: https://discord.gg/storybook - about: Community discussions, interactive support, contributor help + about: Meet other community members and get contributor help. From 411202ff63a71f5c958c8f7bf815400b97761c0f Mon Sep 17 00:00:00 2001 From: Norbert de Langen Date: Thu, 16 Nov 2023 09:25:23 +0100 Subject: [PATCH 054/170] make CLI --test flag be true when `process.env.SB_TESTBUILD` === `true` --- code/lib/cli/src/generate.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/code/lib/cli/src/generate.ts b/code/lib/cli/src/generate.ts index 76c00eca2d2a..e5811888521b 100644 --- a/code/lib/cli/src/generate.ts +++ b/code/lib/cli/src/generate.ts @@ -273,7 +273,11 @@ command('build') configDir: 'SBCONFIG_CONFIG_DIR', }); - await build({ ...options, packageJson: pkg }).catch(() => process.exit(1)); + await build({ + ...options, + packageJson: pkg, + test: !!options.test || process.env.SB_TESTBUILD === 'true', + }).catch(() => process.exit(1)); }); program.on('command:*', ([invalidCmd]) => { From e3a59328539d65bff565852a5da73d0801d97966 Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Thu, 16 Nov 2023 09:27:36 +0100 Subject: [PATCH 055/170] Prettify docs --- docs/api/main-config-typescript.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/api/main-config-typescript.md b/docs/api/main-config-typescript.md index 5ac80985eb9f..89f11b1cbd5a 100644 --- a/docs/api/main-config-typescript.md +++ b/docs/api/main-config-typescript.md @@ -90,11 +90,11 @@ Only available for React Storybook projects. Options to pass to react-docgen-typ ## `skipBabel` -Deprecated: Will be removed in Storybook 8.0. Use `skipCompiler` instead +Deprecated: Will be removed in Storybook 8.0. Use `skipCompiler` instead. Type: `boolean` -Disable parsing of TypeScript files through babel. +Disable parsing of TypeScript files through Babel. From 41ab56ba6f8cbb8e125e871f1e3eb951d6050315 Mon Sep 17 00:00:00 2001 From: Norbert de Langen Date: Thu, 16 Nov 2023 11:32:49 +0100 Subject: [PATCH 056/170] fix issue where setting status without index, crashes storybook --- code/lib/manager-api/src/modules/stories.ts | 4 ++- .../lib/manager-api/src/tests/stories.test.ts | 28 +++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/code/lib/manager-api/src/modules/stories.ts b/code/lib/manager-api/src/modules/stories.ts index 795f9460b108..dc0af196679b 100644 --- a/code/lib/manager-api/src/modules/stories.ts +++ b/code/lib/manager-api/src/modules/stories.ts @@ -612,7 +612,9 @@ export const init: ModuleFn = ({ }); await store.setState({ status: newStatus }, { persistence: 'session' }); - await api.setIndex(index); + if (index) { + await api.setIndex(index); + } }, experimental_setFilter: async (id, filterFunction) => { const { internal_index: index } = store.getState(); diff --git a/code/lib/manager-api/src/tests/stories.test.ts b/code/lib/manager-api/src/tests/stories.test.ts index 76213e10be25..a115f64c79f5 100644 --- a/code/lib/manager-api/src/tests/stories.test.ts +++ b/code/lib/manager-api/src/tests/stories.test.ts @@ -1251,6 +1251,34 @@ describe('stories API', () => { } `); }); + it('skips updating index, if index is unset', async () => { + const moduleArgs = createMockModuleArgs({}); + const { api } = initStories(moduleArgs as unknown as ModuleArgs); + const { store } = moduleArgs; + + // await api.setIndex({ v: 4, entries: mockEntries }); + + await expect( + api.experimental_updateStatus('a-addon-id', { + 'a-story-id': { + status: 'pending', + title: 'an addon title', + description: 'an addon description', + }, + }) + ).resolves.not.toThrow(); + expect(store.getState().status).toMatchInlineSnapshot(` + Object { + "a-story-id": Object { + "a-addon-id": Object { + "description": "an addon description", + "status": "pending", + "title": "an addon title", + }, + }, + } + `); + }); it('updates multiple stories', async () => { const moduleArgs = createMockModuleArgs({}); const { api } = initStories(moduleArgs as unknown as ModuleArgs); From 962bf861a9981dd60df90b771ed59ff7406964d8 Mon Sep 17 00:00:00 2001 From: Norbert de Langen Date: Thu, 16 Nov 2023 12:00:21 +0100 Subject: [PATCH 057/170] cleanup --- code/lib/manager-api/src/tests/stories.test.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/code/lib/manager-api/src/tests/stories.test.ts b/code/lib/manager-api/src/tests/stories.test.ts index a115f64c79f5..7733f569e5c5 100644 --- a/code/lib/manager-api/src/tests/stories.test.ts +++ b/code/lib/manager-api/src/tests/stories.test.ts @@ -1256,8 +1256,6 @@ describe('stories API', () => { const { api } = initStories(moduleArgs as unknown as ModuleArgs); const { store } = moduleArgs; - // await api.setIndex({ v: 4, entries: mockEntries }); - await expect( api.experimental_updateStatus('a-addon-id', { 'a-story-id': { From d71bc5a4e5d7f83d3cf136080c6e38b7d7800143 Mon Sep 17 00:00:00 2001 From: Joe Vaughan <122215197+joevaugh4n@users.noreply.github.com> Date: Thu, 16 Nov 2023 11:15:11 +0000 Subject: [PATCH 058/170] Update help.yml --- .github/DISCUSSION_TEMPLATE/help.yml | 35 ++++++++++++++++++---------- 1 file changed, 23 insertions(+), 12 deletions(-) diff --git a/.github/DISCUSSION_TEMPLATE/help.yml b/.github/DISCUSSION_TEMPLATE/help.yml index ddbaaca364ad..fcdd32a46bcf 100644 --- a/.github/DISCUSSION_TEMPLATE/help.yml +++ b/.github/DISCUSSION_TEMPLATE/help.yml @@ -1,25 +1,36 @@ ---- body: - - type: textarea + - type: markdown + attributes: + value: | + Thanks for taking the time to start a new discussion! + + Before you post: + ā€¢ Check if someone has already asked/answered your question in a previous discussion. + + When you're ready to post: + ā€¢ Add tags to your thread (e.g. 'React', 'Vue', 'Vite') to make your issue clearer for other users. + + - type: textarea attributes: label: Summary - description: How do you need help? - placeholder: I need help with... - validations: + description: How can we help? + validations: required: true + - type: textarea attributes: label: Additional information - description: Share your Storybook configuration (`main.js or ts`), any error messages, or relevant dependencies + description: | + Share Your Storybook configuration (`main.js or main.ts`), your Storybook version number, any error messages, or any relevant dependencies. These help us get a clearer understanding of what might be going wrong. + + P.s. please share code as text rather than as a screenshot! It makes debugging much easier and faster. render: js - validations: + validations: required: false + - type: input attributes: - label: Share an example - description: Help us debug your issue by creating a minimal reproduction. You can do this with StackBlitz by heading to [https://storybook.new](https://storybook.new)! + label: Create a reproduction + description: Help us debug by creating a minimal reproduction with [https://storybook.new](https://storybook.new) validations: required: false - - type: markdown - attributes: null - value: Before submitting, consider adding relevant labels to your thread (e.g. 'react', 'vue', 'vite'). That makes it easier for other users to spot your request. Thanks! From eb3c8c9a9403a1dc0c9a88f66af38de151e73c21 Mon Sep 17 00:00:00 2001 From: Joe Vaughan <122215197+joevaugh4n@users.noreply.github.com> Date: Thu, 16 Nov 2023 12:22:53 +0000 Subject: [PATCH 059/170] Update help.yml --- .github/DISCUSSION_TEMPLATE/help.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/DISCUSSION_TEMPLATE/help.yml b/.github/DISCUSSION_TEMPLATE/help.yml index fcdd32a46bcf..2c588e76e6d2 100644 --- a/.github/DISCUSSION_TEMPLATE/help.yml +++ b/.github/DISCUSSION_TEMPLATE/help.yml @@ -8,7 +8,7 @@ body: ā€¢ Check if someone has already asked/answered your question in a previous discussion. When you're ready to post: - ā€¢ Add tags to your thread (e.g. 'React', 'Vue', 'Vite') to make your issue clearer for other users. + ā€¢ Add tags to your discussion (e.g. 'React', 'Vue', 'Vite') to make it clearer for other users. - type: textarea attributes: From 7aef3e4f76f445646ba2a2558193018c16f5aee7 Mon Sep 17 00:00:00 2001 From: Kasper Peulen Date: Thu, 16 Nov 2023 16:27:05 +0100 Subject: [PATCH 060/170] Address review comments --- MIGRATION.md | 4 +-- code/addons/actions/src/addArgsHelpers.ts | 3 ++- .../actions/src/models/ActionOptions.ts | 1 + code/addons/actions/src/runtime/action.ts | 25 +++++++------------ .../core-events/src/errors/preview-errors.ts | 4 +-- 5 files changed, 16 insertions(+), 21 deletions(-) diff --git a/MIGRATION.md b/MIGRATION.md index 77a3ae9613e4..8e401c599e75 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -1,7 +1,7 @@

Migration

- [From version 7.5.0 to 7.6.0](#from-version-750-to-760) - - [Using implicit actions during rendering is deprecated (for example in the play function)](#using-implicit-actions-during-rendering-is-deprecated-for-example-in-the-play-function) + - [Using implicit actions during rendering is deprecated](#using-implicit-actions-during-rendering-is-deprecated) - [Primary doc block accepts of prop](#primary-doc-block-accepts-of-prop) - [Addons no longer need a peer dependency on React](#addons-no-longer-need-a-peer-dependency-on-react) - [From version 7.4.0 to 7.5.0](#from-version-740-to-750) @@ -311,7 +311,7 @@ ## From version 7.5.0 to 7.6.0 -#### Using implicit actions during rendering is deprecated (for example in the play function) +#### Using implicit actions during rendering is deprecated In Storybook 7, we inferred if the component accepts any action props, by checking if it starts with `onX` (for example `onClick`), or as configured by `actions.argTypesRegex`. diff --git a/code/addons/actions/src/addArgsHelpers.ts b/code/addons/actions/src/addArgsHelpers.ts index 0dcb56c32f55..cd4f67897a53 100644 --- a/code/addons/actions/src/addArgsHelpers.ts +++ b/code/addons/actions/src/addArgsHelpers.ts @@ -19,6 +19,7 @@ export const inferActionsFromArgTypesRegex: ArgsEnhancer = (context) = const { initialArgs, argTypes, + id, parameters: { actions }, } = context; if (!actions || actions.disable || !actions.argTypesRegex || !argTypes) { @@ -32,7 +33,7 @@ export const inferActionsFromArgTypesRegex: ArgsEnhancer = (context) = return argTypesMatchingRegex.reduce((acc, [name, argType]) => { if (isInInitialArgs(name, initialArgs)) { - acc[name] = action(name, { implicit: true }); + acc[name] = action(name, { implicit: true, id }); } return acc; }, {} as Args); diff --git a/code/addons/actions/src/models/ActionOptions.ts b/code/addons/actions/src/models/ActionOptions.ts index b503df069d5c..ffd8d373b3fa 100644 --- a/code/addons/actions/src/models/ActionOptions.ts +++ b/code/addons/actions/src/models/ActionOptions.ts @@ -5,6 +5,7 @@ interface Options { clearOnStoryChange: boolean; limit: number; implicit: boolean; + id: string; } export type ActionOptions = Partial & Partial; diff --git a/code/addons/actions/src/runtime/action.ts b/code/addons/actions/src/runtime/action.ts index 365bb487621f..9955f27637dc 100644 --- a/code/addons/actions/src/runtime/action.ts +++ b/code/addons/actions/src/runtime/action.ts @@ -4,7 +4,6 @@ import { addons } from '@storybook/preview-api'; import type { Renderer } from '@storybook/types'; import { global } from '@storybook/global'; import { ImplicitActionsDuringRendering } from '@storybook/core-events/preview-errors'; -import dedent from 'ts-dedent'; import { EVENT_ID } from '../constants'; import type { ActionDisplay, ActionOptions, HandlerFunction } from '../models'; import { config } from './configureActions'; @@ -70,23 +69,17 @@ export function action(name: string, options: ActionOptions = {}): HandlerFuncti ); if (storyRenderer) { - if (window?.FEATURES?.disallowImplicitActionsInRenderV8) { + const deprecated = !window?.FEATURES?.disallowImplicitActionsInRenderV8; + const error = new ImplicitActionsDuringRendering({ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - throw new ImplicitActionsDuringRendering({ phase: storyRenderer.phase!, name }); + phase: storyRenderer.phase!, + name, + deprecated, + }); + if (deprecated) { + console.warn(error); } else { - console.warn(dedent` - We detected that you use an implicit action arg during ${storyRenderer.phase} of your story. - This is deprecated and won't work in Storybook 8 anymore. - - Please provide an explicit spy to your args like this: - import { fn } from '@storybook/test'; - ... - args: { - ${name}: fn() - } - - See: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#using-implicit-actions-during-rendering-is-deprecated-for-example-in-the-play-function - `); + throw error; } } } diff --git a/code/lib/core-events/src/errors/preview-errors.ts b/code/lib/core-events/src/errors/preview-errors.ts index dda274d158d1..50cb0609861a 100644 --- a/code/lib/core-events/src/errors/preview-errors.ts +++ b/code/lib/core-events/src/errors/preview-errors.ts @@ -57,14 +57,14 @@ export class ImplicitActionsDuringRendering extends StorybookError { readonly documentation = 'https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#using-implicit-actions-during-rendering-is-deprecated-for-example-in-the-play-function'; - constructor(public data: { phase: string; name: string }) { + constructor(public data: { phase: string; name: string; deprecated: boolean }) { super(); } template() { return dedent` We detected that you use an implicit action arg during ${this.data.phase} of your story. - + ${this.data.deprecated ? `\nThis is deprecated and won't work in Storybook 8 anymore.\n` : ``} Please provide an explicit spy to your args like this: import { fn } from '@storybook/test'; ... From 483943630be997236248aa10bf1717df2eff1a4a Mon Sep 17 00:00:00 2001 From: Joe Vaughan <122215197+joevaugh4n@users.noreply.github.com> Date: Thu, 16 Nov 2023 18:49:05 +0000 Subject: [PATCH 061/170] Update .github/DISCUSSION_TEMPLATE/help.yml Co-authored-by: Kyle Gach --- .github/DISCUSSION_TEMPLATE/help.yml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/DISCUSSION_TEMPLATE/help.yml b/.github/DISCUSSION_TEMPLATE/help.yml index 2c588e76e6d2..6b28e8111f50 100644 --- a/.github/DISCUSSION_TEMPLATE/help.yml +++ b/.github/DISCUSSION_TEMPLATE/help.yml @@ -2,13 +2,13 @@ body: - type: markdown attributes: value: | - Thanks for taking the time to start a new discussion! +Thanks for taking the time to start a new discussion! - Before you post: - ā€¢ Check if someone has already asked/answered your question in a previous discussion. +Before you post: +- Check if someone has already asked/answered your question in a previous discussion. - When you're ready to post: - ā€¢ Add tags to your discussion (e.g. 'React', 'Vue', 'Vite') to make it clearer for other users. +When you're ready to post: +- Add tags to your discussion (e.g. 'React', 'Vue', 'Vite') to make it clearer for other users. - type: textarea attributes: From 5112a32d436a0cb4b5ffa0d3895a183e422d3b56 Mon Sep 17 00:00:00 2001 From: Joe Vaughan <122215197+joevaugh4n@users.noreply.github.com> Date: Thu, 16 Nov 2023 18:49:25 +0000 Subject: [PATCH 062/170] Update .github/DISCUSSION_TEMPLATE/help.yml Co-authored-by: Kyle Gach --- .github/DISCUSSION_TEMPLATE/help.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/DISCUSSION_TEMPLATE/help.yml b/.github/DISCUSSION_TEMPLATE/help.yml index 6b28e8111f50..520805989d55 100644 --- a/.github/DISCUSSION_TEMPLATE/help.yml +++ b/.github/DISCUSSION_TEMPLATE/help.yml @@ -21,7 +21,7 @@ When you're ready to post: attributes: label: Additional information description: | - Share Your Storybook configuration (`main.js or main.ts`), your Storybook version number, any error messages, or any relevant dependencies. These help us get a clearer understanding of what might be going wrong. + Share Your Storybook configuration (`main.js` or `main.ts`), your Storybook version number, any error messages, and any relevant dependencies. These help us get a clearer understanding of what might be going wrong. P.s. please share code as text rather than as a screenshot! It makes debugging much easier and faster. render: js From f74414b52351498413d8976727120516c595bc5f Mon Sep 17 00:00:00 2001 From: Joe Vaughan <122215197+joevaugh4n@users.noreply.github.com> Date: Thu, 16 Nov 2023 18:49:40 +0000 Subject: [PATCH 063/170] Update .github/DISCUSSION_TEMPLATE/help.yml Co-authored-by: Kyle Gach --- .github/DISCUSSION_TEMPLATE/help.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/DISCUSSION_TEMPLATE/help.yml b/.github/DISCUSSION_TEMPLATE/help.yml index 520805989d55..970bb18d576f 100644 --- a/.github/DISCUSSION_TEMPLATE/help.yml +++ b/.github/DISCUSSION_TEMPLATE/help.yml @@ -23,7 +23,7 @@ When you're ready to post: description: | Share Your Storybook configuration (`main.js` or `main.ts`), your Storybook version number, any error messages, and any relevant dependencies. These help us get a clearer understanding of what might be going wrong. - P.s. please share code as text rather than as a screenshot! It makes debugging much easier and faster. + P.S. Please [share code as text](https://docs.github.com/en/get-started/writing-on-github/working-with-advanced-formatting/creating-and-highlighting-code-blocks) rather than as a screenshot! It makes debugging much easier and faster. render: js validations: required: false From 0d0a1da8edbc685434795f509631c74b5a68d99a Mon Sep 17 00:00:00 2001 From: Tao Zhou Date: Thu, 16 Nov 2023 11:44:42 -0800 Subject: [PATCH 064/170] Core: do not fail the build on warnOnIncompatibleAddons --- code/lib/core-server/src/build-dev.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/code/lib/core-server/src/build-dev.ts b/code/lib/core-server/src/build-dev.ts index 1e321a7d2933..7092b9341f4d 100644 --- a/code/lib/core-server/src/build-dev.ts +++ b/code/lib/core-server/src/build-dev.ts @@ -74,7 +74,11 @@ export async function buildDevStandalone( corePresets.push(join(frameworkName, 'preset')); - await warnOnIncompatibleAddons(config); + try { + await warnOnIncompatibleAddons(config); + } catch (e) { + console.warn("Failed to check for incompatible addons", e); + } // Load first pass: We need to determine the builder // We need to do this because builders might introduce 'overridePresets' which we need to take into account From b8ee9e95dd62f7ae5a826e956f4c1b200c7c71f8 Mon Sep 17 00:00:00 2001 From: Ed Preston Date: Fri, 17 Nov 2023 17:29:45 +1100 Subject: [PATCH 065/170] chore: remove warnings by updating to jscodeshift@0.15.1 --- code/lib/cli/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/code/lib/cli/package.json b/code/lib/cli/package.json index 1c05b073d394..8923fa6400ca 100644 --- a/code/lib/cli/package.json +++ b/code/lib/cli/package.json @@ -83,7 +83,7 @@ "get-port": "^5.1.1", "giget": "^1.0.0", "globby": "^11.0.2", - "jscodeshift": "^0.14.0", + "jscodeshift": "^0.15.1", "leven": "^3.1.0", "ora": "^5.4.1", "prettier": "^2.8.0", From 4b52a2809fbc4b084ebd29374cb5e5ebee422cdf Mon Sep 17 00:00:00 2001 From: Martin Nabhan <7613182+martinnabhan@users.noreply.github.com> Date: Fri, 17 Nov 2023 18:13:39 +0900 Subject: [PATCH 066/170] Add back image context CommonJS export --- code/frameworks/nextjs/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/code/frameworks/nextjs/package.json b/code/frameworks/nextjs/package.json index c1bee25f670f..fab731daf27d 100644 --- a/code/frameworks/nextjs/package.json +++ b/code/frameworks/nextjs/package.json @@ -29,7 +29,7 @@ }, "./dist/image-context": { "types": "./dist/image-context.d.ts", - "require": "./dist/image-context.mjs", + "require": "./dist/image-context.js", "import": "./dist/image-context.mjs" }, "./preset": { From 090b9be903c9609c3d85a3bb654bf5a83fa81302 Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Fri, 17 Nov 2023 10:16:36 +0100 Subject: [PATCH 067/170] Update yarn.lock --- code/yarn.lock | 120 +++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 117 insertions(+), 3 deletions(-) diff --git a/code/yarn.lock b/code/yarn.lock index ba6d74b8127a..3999f341dbe2 100644 --- a/code/yarn.lock +++ b/code/yarn.lock @@ -612,6 +612,21 @@ __metadata: languageName: node linkType: hard +"@babel/helper-module-transforms@npm:^7.23.3": + version: 7.23.3 + resolution: "@babel/helper-module-transforms@npm:7.23.3" + dependencies: + "@babel/helper-environment-visitor": "npm:^7.22.20" + "@babel/helper-module-imports": "npm:^7.22.15" + "@babel/helper-simple-access": "npm:^7.22.5" + "@babel/helper-split-export-declaration": "npm:^7.22.6" + "@babel/helper-validator-identifier": "npm:^7.22.20" + peerDependencies: + "@babel/core": ^7.0.0 + checksum: 211e1399d0c4993671e8e5c2b25383f08bee40004ace5404ed4065f0e9258cc85d99c1b82fd456c030ce5cfd4d8f310355b54ef35de9924eabfc3dff1331d946 + languageName: node + linkType: hard + "@babel/helper-optimise-call-expression@npm:^7.22.5": version: 7.22.5 resolution: "@babel/helper-optimise-call-expression@npm:7.22.5" @@ -1024,6 +1039,17 @@ __metadata: languageName: node linkType: hard +"@babel/plugin-syntax-jsx@npm:^7.23.3": + version: 7.23.3 + resolution: "@babel/plugin-syntax-jsx@npm:7.23.3" + dependencies: + "@babel/helper-plugin-utils": "npm:^7.22.5" + peerDependencies: + "@babel/core": ^7.0.0-0 + checksum: 563bb7599b868773f1c7c1d441ecc9bc53aeb7832775da36752c926fc402a1fa5421505b39e724f71eb217c13e4b93117e081cac39723b0e11dac4c897f33c3e + languageName: node + linkType: hard + "@babel/plugin-syntax-logical-assignment-operators@npm:^7.10.4, @babel/plugin-syntax-logical-assignment-operators@npm:^7.8.3": version: 7.10.4 resolution: "@babel/plugin-syntax-logical-assignment-operators@npm:7.10.4" @@ -1123,6 +1149,17 @@ __metadata: languageName: node linkType: hard +"@babel/plugin-syntax-typescript@npm:^7.23.3": + version: 7.23.3 + resolution: "@babel/plugin-syntax-typescript@npm:7.23.3" + dependencies: + "@babel/helper-plugin-utils": "npm:^7.22.5" + peerDependencies: + "@babel/core": ^7.0.0-0 + checksum: 4d6e9cdb9d0bfb9bd9b220fc951d937fce2ca69135ec121153572cebe81d86abc9a489208d6b69ee5f10cadcaeffa10d0425340a5029e40e14a6025021b90948 + languageName: node + linkType: hard + "@babel/plugin-syntax-unicode-sets-regex@npm:^7.18.6": version: 7.18.6 resolution: "@babel/plugin-syntax-unicode-sets-regex@npm:7.18.6" @@ -1442,6 +1479,19 @@ __metadata: languageName: node linkType: hard +"@babel/plugin-transform-modules-commonjs@npm:^7.23.3": + version: 7.23.3 + resolution: "@babel/plugin-transform-modules-commonjs@npm:7.23.3" + dependencies: + "@babel/helper-module-transforms": "npm:^7.23.3" + "@babel/helper-plugin-utils": "npm:^7.22.5" + "@babel/helper-simple-access": "npm:^7.22.5" + peerDependencies: + "@babel/core": ^7.0.0-0 + checksum: 5c8840c5c9ecba39367ae17c973ed13dbc43234147b77ae780eec65010e2a9993c5d717721b23e8179f7cf49decdd325c509b241d69cfbf92aa647a1d8d5a37d + languageName: node + linkType: hard + "@babel/plugin-transform-modules-systemjs@npm:^7.22.11, @babel/plugin-transform-modules-systemjs@npm:^7.22.5, @babel/plugin-transform-modules-systemjs@npm:^7.23.0": version: 7.23.0 resolution: "@babel/plugin-transform-modules-systemjs@npm:7.23.0" @@ -1838,6 +1888,20 @@ __metadata: languageName: node linkType: hard +"@babel/plugin-transform-typescript@npm:^7.23.3": + version: 7.23.3 + resolution: "@babel/plugin-transform-typescript@npm:7.23.3" + dependencies: + "@babel/helper-annotate-as-pure": "npm:^7.22.5" + "@babel/helper-create-class-features-plugin": "npm:^7.22.15" + "@babel/helper-plugin-utils": "npm:^7.22.5" + "@babel/plugin-syntax-typescript": "npm:^7.23.3" + peerDependencies: + "@babel/core": ^7.0.0-0 + checksum: a3c738efcf491ceb1eee646f57c44990ee0c80465527b88fcfa0b7602688c4ff8c165a4c5b62caf05d968b095212018fd30a02879c12d37c657081f57b31fb26 + languageName: node + linkType: hard + "@babel/plugin-transform-unicode-escapes@npm:^7.22.10, @babel/plugin-transform-unicode-escapes@npm:^7.22.5": version: 7.22.10 resolution: "@babel/plugin-transform-unicode-escapes@npm:7.22.10" @@ -2237,6 +2301,21 @@ __metadata: languageName: node linkType: hard +"@babel/preset-typescript@npm:^7.23.0": + version: 7.23.3 + resolution: "@babel/preset-typescript@npm:7.23.3" + dependencies: + "@babel/helper-plugin-utils": "npm:^7.22.5" + "@babel/helper-validator-option": "npm:^7.22.15" + "@babel/plugin-syntax-jsx": "npm:^7.23.3" + "@babel/plugin-transform-modules-commonjs": "npm:^7.23.3" + "@babel/plugin-transform-typescript": "npm:^7.23.3" + peerDependencies: + "@babel/core": ^7.0.0-0 + checksum: e72b654c7f0f08b35d7e1c0e3a59c0c13037f295c425760b8b148aa7dde01e6ddd982efc525710f997a1494fafdd55cb525738c016609e7e4d703d02014152b7 + languageName: node + linkType: hard + "@babel/preset-typescript@npm:^7.23.2": version: 7.23.2 resolution: "@babel/preset-typescript@npm:7.23.2" @@ -2252,7 +2331,7 @@ __metadata: languageName: node linkType: hard -"@babel/register@npm:^7.13.16": +"@babel/register@npm:^7.13.16, @babel/register@npm:^7.22.15": version: 7.22.15 resolution: "@babel/register@npm:7.22.15" dependencies: @@ -6172,7 +6251,7 @@ __metadata: get-port: "npm:^5.1.1" giget: "npm:^1.0.0" globby: "npm:^11.0.2" - jscodeshift: "npm:^0.14.0" + jscodeshift: "npm:^0.15.1" leven: "npm:^3.1.0" ora: "npm:^5.4.1" prettier: "npm:^2.8.0" @@ -20079,6 +20158,41 @@ __metadata: languageName: node linkType: hard +"jscodeshift@npm:^0.15.1": + version: 0.15.1 + resolution: "jscodeshift@npm:0.15.1" + dependencies: + "@babel/core": "npm:^7.23.0" + "@babel/parser": "npm:^7.23.0" + "@babel/plugin-transform-class-properties": "npm:^7.22.5" + "@babel/plugin-transform-modules-commonjs": "npm:^7.23.0" + "@babel/plugin-transform-nullish-coalescing-operator": "npm:^7.22.11" + "@babel/plugin-transform-optional-chaining": "npm:^7.23.0" + "@babel/plugin-transform-private-methods": "npm:^7.22.5" + "@babel/preset-flow": "npm:^7.22.15" + "@babel/preset-typescript": "npm:^7.23.0" + "@babel/register": "npm:^7.22.15" + babel-core: "npm:^7.0.0-bridge.0" + chalk: "npm:^4.1.2" + flow-parser: "npm:0.*" + graceful-fs: "npm:^4.2.4" + micromatch: "npm:^4.0.4" + neo-async: "npm:^2.5.0" + node-dir: "npm:^0.1.17" + recast: "npm:^0.23.3" + temp: "npm:^0.8.4" + write-file-atomic: "npm:^2.3.0" + peerDependencies: + "@babel/preset-env": ^7.1.6 + peerDependenciesMeta: + "@babel/preset-env": + optional: true + bin: + jscodeshift: bin/jscodeshift.js + checksum: 334de6ffa776a68b3f59f2f18a285ea977f3339d85e3517f3854761e65769ffa7e453c35cde320fc969106d573df39bd3fb08b23db54ae17c1b1516e5bf05742 + languageName: node + linkType: hard + "jsdom@npm:^16.4.0": version: 16.7.0 resolution: "jsdom@npm:16.7.0" @@ -25852,7 +25966,7 @@ __metadata: languageName: node linkType: hard -"recast@npm:^0.23.1": +"recast@npm:^0.23.1, recast@npm:^0.23.3": version: 0.23.4 resolution: "recast@npm:0.23.4" dependencies: From 8efaead946b95339681ddb6af9278f1635bc8e72 Mon Sep 17 00:00:00 2001 From: jonniebigodes Date: Fri, 17 Nov 2023 10:48:14 +0000 Subject: [PATCH 068/170] Minor polish and added filtering tests --- .../my-component-exclude-tags.story.js.mdx | 14 ++ .../my-component-exclude-tags.story.ts.mdx | 20 ++ .../my-component-include-tags.story.js.mdx | 14 ++ .../my-component-include-tags.story.ts.mdx | 20 ++ .../my-component-skip-tags.story.js.mdx | 14 ++ .../my-component-skip-tags.story.ts.mdx | 20 ++ .../common/test-runner-a11y-config.ts.mdx | 2 +- .../common/test-runner-a11y-configure.ts.mdx | 2 +- .../common/test-runner-a11y-disable.ts.mdx | 2 +- docs/snippets/common/test-runner-auth.js.mdx | 12 + docs/snippets/common/test-runner-auth.ts.mdx | 16 ++ .../test-runner-custom-page-viewport.js.mdx | 32 +++ .../test-runner-custom-page-viewport.ts.mdx | 36 +++ .../common/test-runner-helper-function.ts.mdx | 2 +- .../common/test-runner-hooks-example.ts.mdx | 2 +- .../common/test-runner-tags-config.js.mdx | 11 + .../common/test-runner-tags-config.ts.mdx | 15 ++ .../test-runner-tags-exclude.config.js.mdx | 9 + .../test-runner-tags-exclude.config.ts.mdx | 13 + .../test-runner-tags-include.config.js.mdx | 9 + .../test-runner-tags-include.config.ts.mdx | 13 + .../test-runner-tags-skip.config.js.mdx | 9 + .../test-runner-tags-skip.config.ts.mdx | 13 + .../common/test-runner-waitpageready.js.mdx | 25 ++ .../common/test-runner-waitpageready.ts.mdx | 29 +++ docs/writing-tests/accessibility-testing.md | 6 +- docs/writing-tests/test-runner.md | 222 ++++++++++++++---- 27 files changed, 529 insertions(+), 53 deletions(-) create mode 100644 docs/snippets/common/my-component-exclude-tags.story.js.mdx create mode 100644 docs/snippets/common/my-component-exclude-tags.story.ts.mdx create mode 100644 docs/snippets/common/my-component-include-tags.story.js.mdx create mode 100644 docs/snippets/common/my-component-include-tags.story.ts.mdx create mode 100644 docs/snippets/common/my-component-skip-tags.story.js.mdx create mode 100644 docs/snippets/common/my-component-skip-tags.story.ts.mdx create mode 100644 docs/snippets/common/test-runner-auth.js.mdx create mode 100644 docs/snippets/common/test-runner-auth.ts.mdx create mode 100644 docs/snippets/common/test-runner-custom-page-viewport.js.mdx create mode 100644 docs/snippets/common/test-runner-custom-page-viewport.ts.mdx create mode 100644 docs/snippets/common/test-runner-tags-config.js.mdx create mode 100644 docs/snippets/common/test-runner-tags-config.ts.mdx create mode 100644 docs/snippets/common/test-runner-tags-exclude.config.js.mdx create mode 100644 docs/snippets/common/test-runner-tags-exclude.config.ts.mdx create mode 100644 docs/snippets/common/test-runner-tags-include.config.js.mdx create mode 100644 docs/snippets/common/test-runner-tags-include.config.ts.mdx create mode 100644 docs/snippets/common/test-runner-tags-skip.config.js.mdx create mode 100644 docs/snippets/common/test-runner-tags-skip.config.ts.mdx create mode 100644 docs/snippets/common/test-runner-waitpageready.js.mdx create mode 100644 docs/snippets/common/test-runner-waitpageready.ts.mdx diff --git a/docs/snippets/common/my-component-exclude-tags.story.js.mdx b/docs/snippets/common/my-component-exclude-tags.story.js.mdx new file mode 100644 index 000000000000..e0b35b71986c --- /dev/null +++ b/docs/snippets/common/my-component-exclude-tags.story.js.mdx @@ -0,0 +1,14 @@ +```js +// MyComponent.stories.js|jsx + +import { MyComponent } from './MyComponent'; + +export default { + component: MyComponent, + tags: ['no-tests'], // šŸ‘ˆ Excludes all stories from being tested with the test-runner +}; + +export const ExcludeStory = { + tags: ['no-tests'], // šŸ‘ˆ Configures the story to be excluded from testing via the `no-tests` tag +}; +``` diff --git a/docs/snippets/common/my-component-exclude-tags.story.ts.mdx b/docs/snippets/common/my-component-exclude-tags.story.ts.mdx new file mode 100644 index 000000000000..6fee748fadc3 --- /dev/null +++ b/docs/snippets/common/my-component-exclude-tags.story.ts.mdx @@ -0,0 +1,20 @@ +```ts +// MyComponent.stories.ts|tsx + +// Replace your-framework with the name of your framework +import type { Meta, StoryObj } from '@storybook/your-framework'; + +import { MyComponent } from './MyComponent'; + +const meta: Meta = { + component: MyComponent, + tags: ['no-tests'], // šŸ‘ˆ Excludes all stories from being tested with the test-runner +}; + +export default meta; +type Story = StoryObj; + +export const ExcludeStory: Story = { + tags: ['no-tests'], // šŸ‘ˆ Configures the story to be excluded from testing via the `no-tests` tag +}; +``` diff --git a/docs/snippets/common/my-component-include-tags.story.js.mdx b/docs/snippets/common/my-component-include-tags.story.js.mdx new file mode 100644 index 000000000000..995f5285b1cc --- /dev/null +++ b/docs/snippets/common/my-component-include-tags.story.js.mdx @@ -0,0 +1,14 @@ +```js +// MyComponent.stories.js|jsx + +import { MyComponent } from './MyComponent'; + +export default { + component: MyComponent, + tags: ['test-only'], // šŸ‘ˆ Runs tests only for stories with this tag +}; + +export const IncludeStory = { + tags: ['test-only'], // šŸ‘ˆ Configures the story to be added to the test suite with the test-runner +}; +``` diff --git a/docs/snippets/common/my-component-include-tags.story.ts.mdx b/docs/snippets/common/my-component-include-tags.story.ts.mdx new file mode 100644 index 000000000000..5e47651618b6 --- /dev/null +++ b/docs/snippets/common/my-component-include-tags.story.ts.mdx @@ -0,0 +1,20 @@ +```ts +// MyComponent.stories.ts|tsx + +// Replace your-framework with the name of your framework +import type { Meta, StoryObj } from '@storybook/your-framework'; + +import { MyComponent } from './MyComponent'; + +const meta: Meta = { + component: MyComponent, + tags: ['test-only'], // šŸ‘ˆ Runs tests only for stories with this tag +}; + +export default meta; +type Story = StoryObj; + +export const IncludeStory: Story = { + tags: ['test-only'], // šŸ‘ˆ Configures the story to be added to the test suite with the test-runner +}; +``` diff --git a/docs/snippets/common/my-component-skip-tags.story.js.mdx b/docs/snippets/common/my-component-skip-tags.story.js.mdx new file mode 100644 index 000000000000..bf3737cb2ef6 --- /dev/null +++ b/docs/snippets/common/my-component-skip-tags.story.js.mdx @@ -0,0 +1,14 @@ +```js +// MyComponent.stories.js|jsx + +import { MyComponent } from './MyComponent'; + +export default { + component: MyComponent, + tags: ['skip-test'], // šŸ‘ˆ Skips running tests on this story +}; + +export const SkipStory = { + tags: ['skip-test'], // šŸ‘ˆ Configures the story to be skipped when running tests with the test-runner +}; +``` diff --git a/docs/snippets/common/my-component-skip-tags.story.ts.mdx b/docs/snippets/common/my-component-skip-tags.story.ts.mdx new file mode 100644 index 000000000000..62c0d1dfbabf --- /dev/null +++ b/docs/snippets/common/my-component-skip-tags.story.ts.mdx @@ -0,0 +1,20 @@ +```ts +// MyComponent.stories.ts|tsx + +// Replace your-framework with the name of your framework +import type { Meta, StoryObj } from '@storybook/your-framework'; + +import { MyComponent } from './MyComponent'; + +const meta: Meta = { + component: MyComponent, + tags: ['skip-test'], // šŸ‘ˆ Skips running tests on this story +}; + +export default meta; +type Story = StoryObj; + +export const SkipStory: Story = { + tags: ['skip-test'], // šŸ‘ˆ Configures the story to be skipped when running tests with the test-runner +}; +``` diff --git a/docs/snippets/common/test-runner-a11y-config.ts.mdx b/docs/snippets/common/test-runner-a11y-config.ts.mdx index a317cb46ad18..c007a62c1244 100644 --- a/docs/snippets/common/test-runner-a11y-config.ts.mdx +++ b/docs/snippets/common/test-runner-a11y-config.ts.mdx @@ -22,5 +22,5 @@ const a11yConfig: TestRunnerConfig = { }, }; -module.exports = a11yConfig; +export default a11yConfig; ``` diff --git a/docs/snippets/common/test-runner-a11y-configure.ts.mdx b/docs/snippets/common/test-runner-a11y-configure.ts.mdx index 8828a71bba0d..5a9adea12c86 100644 --- a/docs/snippets/common/test-runner-a11y-configure.ts.mdx +++ b/docs/snippets/common/test-runner-a11y-configure.ts.mdx @@ -32,5 +32,5 @@ const a11yConfig: TestRunnerConfig = { }, }; -module.exports = a11yConfig; +export default a11yConfig; ``` diff --git a/docs/snippets/common/test-runner-a11y-disable.ts.mdx b/docs/snippets/common/test-runner-a11y-disable.ts.mdx index 986b8c09eaff..97d8cd06f0fa 100644 --- a/docs/snippets/common/test-runner-a11y-disable.ts.mdx +++ b/docs/snippets/common/test-runner-a11y-disable.ts.mdx @@ -31,5 +31,5 @@ const a11yConfig: TestRunnerConfig = { }, }; -module.exports = a11yConfig; +export default a11yConfig; ``` diff --git a/docs/snippets/common/test-runner-auth.js.mdx b/docs/snippets/common/test-runner-auth.js.mdx new file mode 100644 index 000000000000..d4858de23165 --- /dev/null +++ b/docs/snippets/common/test-runner-auth.js.mdx @@ -0,0 +1,12 @@ +```js +// .storybook/test-runner.js + +module.exports = { + getHttpHeaders: async (url) => { + const token = url.includes('prod') ? 'XYZ' : 'ABC'; + return { + Authorization: `Bearer ${token}`, + }; + }, +}; +``` diff --git a/docs/snippets/common/test-runner-auth.ts.mdx b/docs/snippets/common/test-runner-auth.ts.mdx new file mode 100644 index 000000000000..c4fd82d8726e --- /dev/null +++ b/docs/snippets/common/test-runner-auth.ts.mdx @@ -0,0 +1,16 @@ +```ts +// .storybook/test-runner.ts + +import type { TestRunnerConfig } from '@storybook/test-runner'; + +const config: TestRunnerConfig = { + getHttpHeaders: async (url) => { + const token = url.includes('prod') ? 'prod-token' : 'dev-token'; + return { + Authorization: `Bearer ${token}`, + }; + }, +}; + +export default config; +``` diff --git a/docs/snippets/common/test-runner-custom-page-viewport.js.mdx b/docs/snippets/common/test-runner-custom-page-viewport.js.mdx new file mode 100644 index 000000000000..a4d5d0cc57f1 --- /dev/null +++ b/docs/snippets/common/test-runner-custom-page-viewport.js.mdx @@ -0,0 +1,32 @@ +```js +// .storybook/test-runner.js + +const { getStoryContext } = require('@storybook/test-runner'); +const { MINIMAL_VIEWPORTS } = require('@storybook/addon-viewport'); + +const DEFAULT_VIEWPORT_SIZE = { width: 1280, height: 720 }; + +module.exports = { + async preRender(page, story) { + // Accesses the story's parameters and retrieves the viewport used to render it + const context = await getStoryContext(page, story); + const viewportName = context.parameters?.viewport?.defaultViewport; + const viewportParameter = MINIMAL_VIEWPORTS[viewportName]; + + if (viewportParameter) { + const viewportSize = Object.entries(viewportParameter.styles).reduce( + (acc, [screen, size]) => ({ + ...acc, + // Converts the viewport size from percentages to numbers + [screen]: parseInt(size), + }), + {} + ); + // Configures the Playwright page to use the viewport size + page.setViewportSize(viewportSize); + } else { + page.setViewportSize(DEFAULT_VIEWPORT_SIZE); + } + }, +}; +``` diff --git a/docs/snippets/common/test-runner-custom-page-viewport.ts.mdx b/docs/snippets/common/test-runner-custom-page-viewport.ts.mdx new file mode 100644 index 000000000000..351b9e8bd0ec --- /dev/null +++ b/docs/snippets/common/test-runner-custom-page-viewport.ts.mdx @@ -0,0 +1,36 @@ +```ts +// .storybook/test-runner.js + +import type { TestRunnerConfig } from '@storybook/test-runner'; +import { getStoryContext } from '@storybook/test-runner'; + +const { MINIMAL_VIEWPORTS } = require('@storybook/addon-viewport'); + +const DEFAULT_VIEWPORT_SIZE = { width: 1280, height: 720 }; + +const config: TestRunnerConfig = { + async preRender(page, story) { + // Accesses the story's parameters and retrieves the viewport used to render it + const context = await getStoryContext(page, story); + const viewportName = context.parameters?.viewport?.defaultViewport; + const viewportParameter = MINIMAL_VIEWPORTS[viewportName]; + + if (viewportParameter) { + const viewportSize = Object.entries(viewportParameter.styles).reduce( + (acc, [screen, size]) => ({ + ...acc, + // Converts the viewport size from percentages to numbers + [screen]: parseInt(size), + }), + {} + ); + // Configures the Playwright page to use the viewport size + page.setViewportSize(viewportSize); + } else { + page.setViewportSize(DEFAULT_VIEWPORT_SIZE); + } + }, +}; + +export default config; +``` diff --git a/docs/snippets/common/test-runner-helper-function.ts.mdx b/docs/snippets/common/test-runner-helper-function.ts.mdx index eea475d13f24..57a04bd7c465 100644 --- a/docs/snippets/common/test-runner-helper-function.ts.mdx +++ b/docs/snippets/common/test-runner-helper-function.ts.mdx @@ -31,5 +31,5 @@ const config: TestRunnerConfig = { }, }; -module.exports = config; +export default config; ``` diff --git a/docs/snippets/common/test-runner-hooks-example.ts.mdx b/docs/snippets/common/test-runner-hooks-example.ts.mdx index d05ddb64801c..86398c9aeb45 100644 --- a/docs/snippets/common/test-runner-hooks-example.ts.mdx +++ b/docs/snippets/common/test-runner-hooks-example.ts.mdx @@ -24,5 +24,5 @@ const config: TestRunnerConfig = { }, }; -module.exports = config; +export default config; ``` diff --git a/docs/snippets/common/test-runner-tags-config.js.mdx b/docs/snippets/common/test-runner-tags-config.js.mdx new file mode 100644 index 000000000000..6ebfbb6c9fb4 --- /dev/null +++ b/docs/snippets/common/test-runner-tags-config.js.mdx @@ -0,0 +1,11 @@ +```js +// .storybook/test-runner.js + +module.exports = { + tags: { + include: ['test-only', 'pages'], + exclude: ['no-tests', 'tokens'], + skip: ['skip-test', 'layout'], + }, +}; +``` diff --git a/docs/snippets/common/test-runner-tags-config.ts.mdx b/docs/snippets/common/test-runner-tags-config.ts.mdx new file mode 100644 index 000000000000..023b13e77cc9 --- /dev/null +++ b/docs/snippets/common/test-runner-tags-config.ts.mdx @@ -0,0 +1,15 @@ +```ts +// .storybook/test-runner.ts + +import type { TestRunnerConfig } from '@storybook/test-runner'; + +const config: TestRunnerConfig = { + tags: { + include: ['test-only', 'pages'], + exclude: ['no-tests', 'tokens'], + skip: ['skip-test', 'layout'], + }, +}; + +export default config; +``` diff --git a/docs/snippets/common/test-runner-tags-exclude.config.js.mdx b/docs/snippets/common/test-runner-tags-exclude.config.js.mdx new file mode 100644 index 000000000000..5b73bb9bdf60 --- /dev/null +++ b/docs/snippets/common/test-runner-tags-exclude.config.js.mdx @@ -0,0 +1,9 @@ +```js +// .storybook/test-runner.js + +module.exports = { + tags: { + exclude: ['no-tests'], + }, +}; +``` diff --git a/docs/snippets/common/test-runner-tags-exclude.config.ts.mdx b/docs/snippets/common/test-runner-tags-exclude.config.ts.mdx new file mode 100644 index 000000000000..9712292fe33c --- /dev/null +++ b/docs/snippets/common/test-runner-tags-exclude.config.ts.mdx @@ -0,0 +1,13 @@ +```ts +// .storybook/test-runner.ts + +import type { TestRunnerConfig } from '@storybook/test-runner'; + +const config: TestRunnerConfig = { + tags: { + exclude: ['no-tests'], + }, +}; + +export default config; +``` diff --git a/docs/snippets/common/test-runner-tags-include.config.js.mdx b/docs/snippets/common/test-runner-tags-include.config.js.mdx new file mode 100644 index 000000000000..2b51222fed40 --- /dev/null +++ b/docs/snippets/common/test-runner-tags-include.config.js.mdx @@ -0,0 +1,9 @@ +```js +// .storybook/test-runner.js + +module.exports = { + tags: { + include: ['test-only'], + }, +}; +``` diff --git a/docs/snippets/common/test-runner-tags-include.config.ts.mdx b/docs/snippets/common/test-runner-tags-include.config.ts.mdx new file mode 100644 index 000000000000..b69e402aff92 --- /dev/null +++ b/docs/snippets/common/test-runner-tags-include.config.ts.mdx @@ -0,0 +1,13 @@ +```ts +// .storybook/test-runner.ts + +import type { TestRunnerConfig } from '@storybook/test-runner'; + +const config: TestRunnerConfig = { + tags: { + include: ['test-only'], + }, +}; + +export default config; +``` diff --git a/docs/snippets/common/test-runner-tags-skip.config.js.mdx b/docs/snippets/common/test-runner-tags-skip.config.js.mdx new file mode 100644 index 000000000000..bc82ef46d752 --- /dev/null +++ b/docs/snippets/common/test-runner-tags-skip.config.js.mdx @@ -0,0 +1,9 @@ +```js +// .storybook/test-runner.js + +module.exports = { + tags: { + skip: ['skip-test'], + }, +}; +``` diff --git a/docs/snippets/common/test-runner-tags-skip.config.ts.mdx b/docs/snippets/common/test-runner-tags-skip.config.ts.mdx new file mode 100644 index 000000000000..37a03bf7b1c4 --- /dev/null +++ b/docs/snippets/common/test-runner-tags-skip.config.ts.mdx @@ -0,0 +1,13 @@ +```ts +// .storybook/test-runner.ts + +import type { TestRunnerConfig } from '@storybook/test-runner'; + +const config: TestRunnerConfig = { + tags: { + skip: ['skip-test'], + }, +}; + +export default config; +``` diff --git a/docs/snippets/common/test-runner-waitpageready.js.mdx b/docs/snippets/common/test-runner-waitpageready.js.mdx new file mode 100644 index 000000000000..0dfb8aecb22a --- /dev/null +++ b/docs/snippets/common/test-runner-waitpageready.js.mdx @@ -0,0 +1,25 @@ +```js +// .storybook/test-runner.js + +const { waitForPageReady } = require('@storybook/test-runner'); +const { toMatchImageSnapshot } = require('jest-image-snapshot'); + +const customSnapshotsDir = `${process.cwd()}/__snapshots__`; + +module.exports = { + setup() { + expect.extend({ toMatchImageSnapshot }); + }, + async postRender(page, context) { + // Awaits for the page to be loaded and available including assets (e.g., fonts) + await waitForPageReady(page); + + // Generates a snapshot file based on the story identifier + const image = await page.screenshot(); + expect(image).toMatchImageSnapshot({ + customSnapshotsDir, + customSnapshotIdentifier: context.id, + }); + }, +}; +``` diff --git a/docs/snippets/common/test-runner-waitpageready.ts.mdx b/docs/snippets/common/test-runner-waitpageready.ts.mdx new file mode 100644 index 000000000000..7a3c1ae88d8e --- /dev/null +++ b/docs/snippets/common/test-runner-waitpageready.ts.mdx @@ -0,0 +1,29 @@ +```ts +// .storybook/test-runner.ts + +import type { TestRunnerConfig } from '@storybook/test-runner'; +import { waitForPageReady } from '@storybook/test-runner'; + +import { toMatchImageSnapshot } from 'jest-image-snapshot'; + +const customSnapshotsDir = `${process.cwd()}/__snapshots__`; + +const config: TestRunnerConfig = { + setup() { + expect.extend({ toMatchImageSnapshot }); + }, + async postRender(page, context) { + // Awaits for the page to be loaded and available including assets (e.g., fonts) + await waitForPageReady(page); + + // Generates a snapshot file based on the story identifier + const image = await page.screenshot(); + expect(image).toMatchImageSnapshot({ + customSnapshotsDir, + customSnapshotIdentifier: context.id, + }); + }, +}; + +export default config; +``` diff --git a/docs/writing-tests/accessibility-testing.md b/docs/writing-tests/accessibility-testing.md index 4773ec8594b0..cbc39f9cdf1c 100644 --- a/docs/writing-tests/accessibility-testing.md +++ b/docs/writing-tests/accessibility-testing.md @@ -203,11 +203,11 @@ Add a new [configuration file](./test-runner.md#test-hook-api) inside your Story -
+ -šŸ’” `preRender` and `postRender` are convenient hooks that allow you to extend the test runner's default configuration. Read more about them [here](./test-runner.md#test-hook-api). +`preRender` and `postRender` are convenient hooks that allow you to extend the test runner's default configuration. Read more about them [here](./test-runner.md#test-hook-api). -
+ When you execute the test runner (for example, with `yarn test-storybook`), it will run the accessibility audit and any [interaction tests](./interaction-testing.md) you might have configured for each component story. diff --git a/docs/writing-tests/test-runner.md b/docs/writing-tests/test-runner.md index ebecf03198d3..fc34bbd9caea 100644 --- a/docs/writing-tests/test-runner.md +++ b/docs/writing-tests/test-runner.md @@ -52,9 +52,11 @@ Start your Storybook with: -
-šŸ’” Storybook's test runner requires either a locally running Storybook instance or a published Storybook to run all the existing tests. -
+ + +Storybook's test runner requires either a locally running Storybook instance or a published Storybook to run all the existing tests. + + Finally, open a new terminal window and run the test-runner with: @@ -79,30 +81,33 @@ Test runner offers zero-config support for Storybook. However, you can run `test The test-runner is powered by [Jest](https://jestjs.io/) and accepts a subset of its [CLI options](https://jestjs.io/docs/cli) (for example, `--watch`, `--maxWorkers`). If you're already using any of those flags in your project, you should be able to migrate them into Storybook's test-runner without any issues. Listed below are all the available flags and examples of using them. -| Options | Description | -| ------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `--help` | Output usage information
`test-storybook --help` | -| `-s`, `--index-json` | Run in index json mode. Automatically detected (requires a compatible Storybook)
`test-storybook --index-json` | -| `--no-index-json` | Disables index json mode
`test-storybook --no-index-json` | -| `-c`, `--config-dir [dir-name]` | Directory where to load Storybook configurations from
`test-storybook -c .storybook` | -| `--watch` | Run in watch mode
`test-storybook --watch` | -| `--watchAll` | Watch files for changes and rerun all tests when something changes.
`test-storybook --watchAll` | -| `--coverage` | Runs [coverage tests](./test-coverage.md) on your stories and components
`test-storybook --coverage` | -| `--coverageDirectory` | Directory where to write coverage report output
`test-storybook --coverage --coverageDirectory coverage/ui/storybook` | -| `--url` | Define the URL to run tests in. Useful for custom Storybook URLs
`test-storybook --url http://the-storybook-url-here.com` | -| `--browsers` | Define browsers to run tests in. One or multiple of: chromium, firefox, webkit
`test-storybook --browsers firefox chromium` | -| `--maxWorkers [amount]` | Specifies the maximum number of workers the worker-pool will spawn for running tests
`test-storybook --maxWorkers=2` | -| `--no-cache` | Disable the cache
`test-storybook --no-cache` | -| `--clearCache` | Deletes the Jest cache directory and then exits without running tests
`test-storybook --clearCache` | -| `--verbose` | Display individual test results with the test suite hierarchy
`test-storybook --verbose` | -| `-u`, `--updateSnapshot` | Use this flag to re-record every snapshot that fails during this test run
`test-storybook -u` | -| `--eject` | Creates a local configuration file to override defaults of the test-runner
`test-storybook --eject` | -| `--json` | Prints the test results in JSON. This mode will send all other test output and user messages to stderr.
`test-storybook --json` | -| `--outputFile` | Write test results to a file when the --json option is also specified.
`test-storybook --json --outputFile results.json` | -| `--junit` | Indicates that test information should be reported in a junit file.
`test-storybook --**junit**` | -| `--ci` | Instead of the regular behavior of storing a new snapshot automatically, it will fail the test and require Jest to be run with `--updateSnapshot`.
`test-storybook --ci` | -| `--shard [index/count]` | Requires CI. Splits the test suite execution into multiple machines
`test-storybook --shard=1/8` | -| `--failOnConsole` | Makes tests fail on browser console errors
`test-storybook --failOnConsole` | +| Options | Description | +| ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `--help` | Output usage information
`test-storybook --help` | +| `-s`, `--index-json` | Run in index json mode. Automatically detected (requires a compatible Storybook)
`test-storybook --index-json` | +| `--no-index-json` | Disables index json mode
`test-storybook --no-index-json` | +| `-c`, `--config-dir [dir-name]` | Directory where to load Storybook configurations from
`test-storybook -c .storybook` | +| `--watch` | Run in watch mode
`test-storybook --watch` | +| `--watchAll` | Watch files for changes and rerun all tests when something changes.
`test-storybook --watchAll` | +| `--coverage` | Runs [coverage tests](./test-coverage.md) on your stories and components
`test-storybook --coverage` | +| `--coverageDirectory` | Directory where to write coverage report output
`test-storybook --coverage --coverageDirectory coverage/ui/storybook` | +| `--url` | Define the URL to run tests in. Useful for custom Storybook URLs
`test-storybook --url http://the-storybook-url-here.com` | +| `--browsers` | Define browsers to run tests in. One or multiple of: chromium, firefox, webkit
`test-storybook --browsers firefox chromium` | +| `--maxWorkers [amount]` | Specifies the maximum number of workers the worker-pool will spawn for running tests
`test-storybook --maxWorkers=2` | +| `--no-cache` | Disable the cache
`test-storybook --no-cache` | +| `--clearCache` | Deletes the Jest cache directory and then exits without running tests
`test-storybook --clearCache` | +| `--verbose` | Display individual test results with the test suite hierarchy
`test-storybook --verbose` | +| `-u`, `--updateSnapshot` | Use this flag to re-record every snapshot that fails during this test run
`test-storybook -u` | +| `--eject` | Creates a local configuration file to override defaults of the test-runner
`test-storybook --eject` | +| `--json` | Prints the test results in JSON. This mode will send all other test output and user messages to stderr.
`test-storybook --json` | +| `--outputFile` | Write test results to a file when the --json option is also specified.
`test-storybook --json --outputFile results.json` | +| `--junit` | Indicates that test information should be reported in a junit file.
`test-storybook --**junit**` | +| `--ci` | Instead of the regular behavior of storing a new snapshot automatically, it will fail the test and require Jest to be run with `--updateSnapshot`.
`test-storybook --ci` | +| `--shard [index/count]` | Requires CI. Splits the test suite execution into multiple machines
`test-storybook --shard=1/8` | +| `--failOnConsole` | Makes tests fail on browser console errors
`test-storybook --failOnConsole` | +| `--includeTags` | Experimental feature
Defines a subset of stories to be tested if they match the enabled [tags](#experimental-filter-tests).
`test-storybook --includeTags="test-only, pages"` | +| `--excludeTags` | Experimental feature
Prevents stories from being tested if they match the provided [tags](#experimental-filter-tests).
`test-storybook --skipTags="no-tests, tokens"` | +| `--skipTags` | Experimental feature
Configures the test runner to skip running tests for stories that match the provided [tags](#experimental-filter-tests).
`test-storybook --skipTags="skip-test, layout"` | @@ -151,11 +156,11 @@ If you're publishing your Storybook with services such as [Vercel](https://verce -
+ -šŸ’” The published Storybook must be publicly available for this example to work. We recommend running the test server using the recipe [below](#run-against-non-deployed-storybooks) if it requires authentication. +The published Storybook must be publicly available for this example to work. We recommend running the test server using the recipe [below](#run-against-non-deployed-storybooks) if it requires authentication. -
+ ### Run against non-deployed Storybooks @@ -171,11 +176,11 @@ You can use your CI provider (for example, [GitHub Actions](https://github.com/f -
+ -šŸ’” By default Storybook outputs the [build](../sharing/publish-storybook.md#build-storybook-as-a-static-web-application) to the `storybook-static` directory. If you're using a different build directory, you'll need to adjust the recipe accordingly. +By default, Storybook outputs the [build](../sharing/publish-storybook.md#build-storybook-as-a-static-web-application) to the `storybook-static` directory. If you're using a different build directory, you'll need to adjust the recipe accordingly. -
+ ### What's the difference between Chromatic and Test runner? @@ -204,12 +209,6 @@ Listed below are the available hooks and an overview of how to use them. | `preRender` | Executes before a story is rendered
`async preRender(page, context) {}` | | `postRender` | Executes after the story is rendered
`async postRender(page, context) {}` | -
- -šŸ’” These test hooks are experimental and may be subject to breaking changes. We encourage you to test as much as possible within the story's [play function](../writing-stories/play-function.md). - -
- To enable the hooks API, you'll need to add a new configuration file inside your Storybook directory and set them up as follows: @@ -223,11 +222,11 @@ To enable the hooks API, you'll need to add a new configuration file inside your -
+ -šŸ’” Except for the `setup` function, all other functions run asynchronously. Both `preRender` and `postRender` functions include two additional arguments, a [Playwright page](https://playwright.dev/docs/pages) and a context object which contains the `id`, `title`, and the `name` of the story. +Except for the `setup` function, all other functions run asynchronously. Both `preRender` and `postRender` functions include two additional arguments, a [Playwright page](https://playwright.dev/docs/pages) and a context object which contains the `id`, `title`, and the `name` of the story. -
+ When the test-runner executes, your existing tests will go through the following lifecycle: @@ -238,6 +237,105 @@ When the test-runner executes, your existing tests will go through the following - The story is rendered, and any existing `play` functions are executed. - The `postRender` function is executed. +### (Experimental) Filter tests + +When you run the test-runner on Storybook, it tests every story by default. However, if you want to filter the tests, you can use the `tags` configuration option. Storybook originally introduced this feature to generate [automatic documentation](../writing-docs/autodocs.md) for stories. But it can be further extended to configure the test-runner to run tests according to the provided tags using a similar configuration option or via CLI flags (e.g., `--includeTags`, `--excludeTags`, `--skipTags`). Listed below are the available options and an overview of how to use them. + +| Option | Description | +| --------- | ----------------------------------------------------------------------------- | +| `exclude` | Prevents stories if they match the provided tags from being tested. | +| `include` | Defines a subset of stories only to be tested if they match the enabled tags. | +| `skip` | Skips testing on stories if they match the provided tags. | + + + + + + + + + +Running tests with the CLI flags takes precedence over the options provided in the configuration file and will override the available options in the configuration file. + + + +#### Disabling tests + +If you want to prevent specific stories from being tested by the test-runner, you can configure your story with a custom tag, enable it to the test-runner configuration file or run the test-runner with the `--excludeTags` [CLI](#cli-options) flag and exclude them from testing. This is helpful when you want to exclude stories that are not yet ready for testing or are irrelevant to your tests. For example: + + + + + + + +#### Run tests for a subset of stories + +To allow the test-runner only to run tests on a specific story or subset of stories, you can configure the story with a custom tag, enable it in the test-runner configuration file or run the test-runner with the `--includeTags` [CLI](#cli-options) flag and include them in your tests. For example, if you wanted to run tests based on the `test-only` tag, you can adjust your configuration as follows: + + + + + + + + + +Applying tags for the component's stories should either be done at the component level (using `meta`) or at the story level. Importing tags across stories is not supported in Storybook and won't work as intended. + + + +#### Skip tests + +If you want to skip running tests on a particular story or subset of stories, you can configure your story with a custom tag, enable it in the test-runner configuration file, or run the test-runner with the `--skipTags` [CLI](#cli-options) flag. Running tests with this option will cause the test-runner to skip over the story and flag them accordingly in the test results. For example: + + + + + + + +### Authentication for deployed Storybooks + +If you use a secure hosting provider that requires authentication to host your Storybook, you may need to set HTTP headers. This is mainly because of how the test runner checks the status of the instance and the index of its stories through fetch requests and Playwright. To do this, you can modify the test-runner configuration file to include the `getHttpHeaders` function. This function takes the URL of the fetch calls and page visits as input and returns an object containing the headers that need to be set. + + + + + + + ### Helpers The test-runner exports a few helpers that can be used to make your tests more readable and maintainable by accessing Storybook's internals (e.g., `args`, `parameters`). Listed below are the available helpers and an overview of how to use them. @@ -253,6 +351,36 @@ The test-runner exports a few helpers that can be used to make your tests more r +#### Accessing story information with the test-runner + +If you need to access information about the story, such as its parameters, the test-runner includes a helper function named `getStoryContext` that you can use to retrieve it. You can then use it to customize your tests further as needed. For example, if you need to configure Playwright's page [viewport size](https://playwright.dev/docs/api/class-page#page-set-viewport-size) to use the viewport size defined in the story's parameters, you can do so as follows: + + + + + + + +#### Working with assets + +If you're running a specific set of tests (e.g., image snapshot testing), the test-runner provides a helper function named `waitForPageReady` that you can use to ensure the page is fully loaded and ready before running the test. For example: + + + + + + + ### Index.json mode The test-runner transforms your story files into tests when testing a local Storybook. For a remote Storybook, it uses the Storybook's [index.json](../configure/overview.md#feature-flags) (formerly `stories.json`) file (a static index of all the stories) to run the tests. @@ -273,11 +401,11 @@ Suppose you run into a situation where the local and remote Storybooks appear ou -
+ -šŸ’” The `index.json` mode is not compatible with watch mode. +The `index.json` mode is not compatible with the watch mode. -
+ If you need to disable it, use the `--no-index-json` flag: @@ -327,6 +455,10 @@ By default, the test runner truncates error outputs at 1000 characters, and you As the test runner is based on Playwright, you might need to use specific docker images or other configurations depending on your CI setup. In that case, you can refer to the [Playwright CI docs](https://playwright.dev/docs/ci) for more information. +### Tests filtered by tags are incorrectly executed + +If you've enabled filtering tests with tags and provided similar tags to the `include` and `exclude` lists, the test-runner will execute the tests based on the `exclude` list and ignore the `include` list. To avoid this, make sure the tags provided to the `include` and `exclude` lists differ. + #### Learn about other UI tests - Test runner to automate test execution From 8a377f876d0883161f2df3c9f4d9358d4e7a4b49 Mon Sep 17 00:00:00 2001 From: Norbert de Langen Date: Fri, 17 Nov 2023 14:30:38 +0100 Subject: [PATCH 069/170] make it work with --test --- .../src/presets/common-override-preset.ts | 56 +++++-- code/package.json | 2 +- code/ui/.storybook/main.ts | 6 + .../typography/DocumentFormattingSample.mdx | 143 ------------------ .../typography/DocumentWrapper.stories.tsx | 7 - 5 files changed, 49 insertions(+), 165 deletions(-) delete mode 100644 code/ui/components/src/components/typography/DocumentFormattingSample.mdx diff --git a/code/lib/core-server/src/presets/common-override-preset.ts b/code/lib/core-server/src/presets/common-override-preset.ts index 5696701a88cd..35913f2265ce 100644 --- a/code/lib/core-server/src/presets/common-override-preset.ts +++ b/code/lib/core-server/src/presets/common-override-preset.ts @@ -1,6 +1,13 @@ -import type { Options, PresetProperty, StorybookConfig, TestBuildFlags } from '@storybook/types'; +import type { + NormalizedStoriesSpecifier, + Options, + PresetProperty, + StoriesEntry, + StorybookConfig, + TestBuildFlags, +} from '@storybook/types'; import { normalizeStories, commonGlobOptions } from '@storybook/core-common'; -import { isAbsolute, join } from 'path'; +import { isAbsolute, join, relative } from 'path'; import slash from 'slash'; import { glob } from 'glob'; @@ -19,30 +26,51 @@ export const framework: PresetProperty<'framework', StorybookConfig> = async (co export const stories: PresetProperty<'stories', StorybookConfig> = async (entries, options) => { if (options?.build?.test?.disableMDXEntries) { - return ( + const result = ( await Promise.all( normalizeStories(entries, { configDir: options.configDir, workingDir: options.configDir, - }).map(({ directory, files }) => { + }).map(async ({ directory, files, titlePrefix }) => { const pattern = join(directory, files); const absolutePattern = isAbsolute(pattern) ? pattern : join(options.configDir, pattern); + const absoluteDirectory = isAbsolute(directory) + ? directory + : join(options.configDir, directory); - return glob(slash(absolutePattern), { - ...commonGlobOptions(absolutePattern), - follow: true, - }); + return { + files: ( + await glob(slash(absolutePattern), { + ...commonGlobOptions(absolutePattern), + follow: true, + }) + ).map((f) => relative(absoluteDirectory, f)), + directory, + titlePrefix, + }; }) ) - ).flatMap((expanded, i) => { - const filteredEntries = expanded.filter((s) => !s.endsWith('.mdx')); + ).reduce((acc, expanded, i) => { + const filteredEntries = expanded.files.filter((s) => !s.endsWith('.mdx')); // only return the filtered entries when there is something to filter // as webpack is faster with unexpanded globs - if (filteredEntries.length < expanded.length) { - return filteredEntries; + let items = []; + if (filteredEntries.length < expanded.files.length) { + items = filteredEntries.map((k) => ({ + ...expanded, + files: `**/${k}`, + })); + console.log({ a: filteredEntries.length, b: expanded.files.length }); + acc.push(...items); + } else { + items = [entries[i]]; } - return entries[i]; - }); + console.log({ items }); + acc.push(...items); + + return acc; + }, []); + return result; } return entries; }; diff --git a/code/package.json b/code/package.json index 9c486f75ab69..d796c99a0741 100644 --- a/code/package.json +++ b/code/package.json @@ -47,7 +47,7 @@ "storybook:blocks:build": "STORYBOOK_BLOCKS_ONLY=true yarn storybook:ui:build", "storybook:blocks:chromatic": "STORYBOOK_BLOCKS_ONLY=true yarn storybook:ui:chromatic --project-token=${CHROMATIC_TOKEN_STORYBOOK_BLOCKS:-MISSING_PROJECT_TOKEN}", "storybook:ui": "NODE_OPTIONS=\"--preserve-symlinks --preserve-symlinks-main\" ./lib/cli/bin/index.js dev --port 6006 --config-dir ./ui/.storybook", - "storybook:ui:build": "NODE_OPTIONS=\"--preserve-symlinks --preserve-symlinks-main\" ./lib/cli/bin/index.js build --config-dir ./ui/.storybook", + "storybook:ui:build": "NODE_OPTIONS=\"--preserve-symlinks --preserve-symlinks-main\" ./lib/cli/bin/index.js build --config-dir ./ui/.storybook --test", "storybook:ui:chromatic": "yarn chromatic --build-script-name storybook:ui:build --storybook-config-dir ./ui/.storybook --storybook-base-dir ./code --project-token=${CHROMATIC_TOKEN_STORYBOOK_UI:-MISSING_PROJECT_TOKEN} --only-changed --exit-zero-on-changes --exit-once-uploaded", "task": "yarn --cwd ../scripts task", "test": "NODE_OPTIONS=--max_old_space_size=4096 jest --config ./jest.config.js", diff --git a/code/ui/.storybook/main.ts b/code/ui/.storybook/main.ts index 347f21929530..4800dda1e181 100644 --- a/code/ui/.storybook/main.ts +++ b/code/ui/.storybook/main.ts @@ -8,6 +8,7 @@ const isBlocksOnly = process.env.STORYBOOK_BLOCKS_ONLY === 'true'; const allStories = [ { directory: '../manager/src', + files: '**/*.stories.@(js|jsx|mjs|ts|tsx|mdx)', titlePrefix: '@manager', }, { @@ -53,6 +54,11 @@ const config: StorybookConfig = { '@storybook/addon-designs', '@chromaui/addon-visual-tests', ], + build: { + test: { + disableBlocks: false, + }, + }, framework: { name: '@storybook/react-vite', options: {}, diff --git a/code/ui/components/src/components/typography/DocumentFormattingSample.mdx b/code/ui/components/src/components/typography/DocumentFormattingSample.mdx deleted file mode 100644 index 65b5e6fbe2ce..000000000000 --- a/code/ui/components/src/components/typography/DocumentFormattingSample.mdx +++ /dev/null @@ -1,143 +0,0 @@ -# h1 Heading - -## h2 Heading - -### h3 Heading - -#### h4 Heading - -##### h5 Heading - -###### h6 Heading - -## Typographic replacements - -Enable typographer option to see result. - -(c) (C) (r) (R) (tm) (TM) (p) (P) +- - -test.. test... test..... test?..... test!.... - -!!!!!! ???? ,, -- --- - -"Smartypants, double quotes" and 'single quotes' - -## Emphasis - -**This is bold text** - -**This is bold text** - -_This is italic text_ - -_This is italic text_ - -_**This is bold italic text**_ - -~~Strikethrough~~ - -## Blockquotes - -> Blockquotes can also be nested... -> -> > ...by using additional greater-than signs right next to each other... -> > -> > > ...or with spaces between arrows. - -## Lists - -Unordered - -- Create a list by starting a line with `+`, `-`, or `*` -- Sub-lists are made by indenting 2 spaces: - - Marker character change forces new list start: - - Ac tristique libero volutpat at - * Facilisis in pretium nisl aliquet - - Nulla volutpat aliquam velit -- Hooray! - -Ordered - -1. Lorem ipsum dolor sit amet -2. Consectetur adipiscing elit -3. Integer molestie lorem at massa - -1) You can use sequential numbers... -1) ...or keep all the numbers as `1.` - -Start numbering with offset: - -57. foo -1. bar - -## Code - -Inline `code` - -Indented code - - // Some comments - line 1 of code - line 2 of code - line 3 of code - -Block code "fences" - -``` -Sample text here... -``` - -Syntax highlighting - -```js -var foo = function (bar) { - return bar++; -}; - -console.log(foo(5)); -``` - -## Horizontal Rule - ---- - -## Tables - -| Option | Description | -| ------ | ------------------------------------------------------------------------- | -| data | path to data files to supply the data that will be passed into templates. | -| engine | engine to be used for processing templates. Handlebars is the default. | -| ext | extension to be used for dest files. | - -Right aligned columns - -| Option | Description | -| -----: | ------------------------------------------------------------------------: | -| data | path to data files to supply the data that will be passed into templates. | -| engine | engine to be used for processing templates. Handlebars is the default. | -| ext | extension to be used for dest files. | - -## Links - -[link text](http://dev.nodeca.com) - -[link with title](http://nodeca.github.io/pica/demo/ 'title text!') - -Autoconverted link https://github.com/nodeca/pica (enable linkify to see) - -# [Link](https://storybook.js.org/) in heading - -## [Link](https://storybook.js.org/) in heading - -### [Link](https://storybook.js.org/) in heading - -#### [Link](https://storybook.js.org/) in heading - -##### [Link](https://storybook.js.org/) in heading - -###### [Link](https://storybook.js.org/) in heading - -## Images - -![Minion](https://octodex.github.com/images/minion.png) -![Stormtroopocat](https://octodex.github.com/images/stormtroopocat.jpg 'The Stormtroopocat') diff --git a/code/ui/components/src/components/typography/DocumentWrapper.stories.tsx b/code/ui/components/src/components/typography/DocumentWrapper.stories.tsx index f11de8ede5f5..4a886c31bc40 100644 --- a/code/ui/components/src/components/typography/DocumentWrapper.stories.tsx +++ b/code/ui/components/src/components/typography/DocumentWrapper.stories.tsx @@ -1,19 +1,12 @@ import React from 'react'; import { DocumentWrapper } from './DocumentWrapper'; -import MarkdownSample from './DocumentFormattingSample.mdx'; export default { component: DocumentWrapper, decorators: [(storyFn: any) =>
{storyFn()}
], }; -export const WithMarkdown = () => ( - - - -); - export const WithDOM = () => (

h1 Heading

From dc4786c7df9077d21fe82592e0db1bb26d54ed2c Mon Sep 17 00:00:00 2001 From: Norbert de Langen Date: Fri, 17 Nov 2023 14:44:20 +0100 Subject: [PATCH 070/170] modify the default_files_pattern for normalizeStories to exclude mdx when --test flag is set --- code/lib/core-common/src/utils/normalize-stories.ts | 9 +++++---- .../core-server/src/presets/common-override-preset.ts | 1 + 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/code/lib/core-common/src/utils/normalize-stories.ts b/code/lib/core-common/src/utils/normalize-stories.ts index 9801fbeae307..3beabeae4c8c 100644 --- a/code/lib/core-common/src/utils/normalize-stories.ts +++ b/code/lib/core-common/src/utils/normalize-stories.ts @@ -9,7 +9,7 @@ import { normalizeStoryPath } from './paths'; import { globToRegexp } from './glob-to-regexp'; const DEFAULT_TITLE_PREFIX = ''; -const DEFAULT_FILES = '**/*.@(mdx|stories.@(js|jsx|mjs|ts|tsx))'; +const DEFAULT_FILES_PATTERN = '**/*.@(mdx|stories.@(js|jsx|mjs|ts|tsx))'; const isDirectory = (configDir: string, entry: string) => { try { @@ -34,7 +34,7 @@ export const getDirectoryFromWorkingDir = ({ export const normalizeStoriesEntry = ( entry: StoriesEntry, - { configDir, workingDir }: NormalizeOptions + { configDir, workingDir, default_files_pattern = DEFAULT_FILES_PATTERN }: NormalizeOptions ): NormalizedStoriesSpecifier => { let specifierWithoutMatcher: Omit; @@ -53,7 +53,7 @@ export const normalizeStoriesEntry = ( specifierWithoutMatcher = { titlePrefix: DEFAULT_TITLE_PREFIX, directory: entry, - files: DEFAULT_FILES, + files: default_files_pattern, }; } else { specifierWithoutMatcher = { @@ -65,7 +65,7 @@ export const normalizeStoriesEntry = ( } else { specifierWithoutMatcher = { titlePrefix: DEFAULT_TITLE_PREFIX, - files: DEFAULT_FILES, + files: default_files_pattern, ...entry, }; } @@ -99,6 +99,7 @@ export const normalizeStoriesEntry = ( interface NormalizeOptions { configDir: string; workingDir: string; + default_files_pattern?: string; } export const normalizeStories = (entries: StoriesEntry[], options: NormalizeOptions) => { diff --git a/code/lib/core-server/src/presets/common-override-preset.ts b/code/lib/core-server/src/presets/common-override-preset.ts index 35913f2265ce..46da6037e3dd 100644 --- a/code/lib/core-server/src/presets/common-override-preset.ts +++ b/code/lib/core-server/src/presets/common-override-preset.ts @@ -31,6 +31,7 @@ export const stories: PresetProperty<'stories', StorybookConfig> = async (entrie normalizeStories(entries, { configDir: options.configDir, workingDir: options.configDir, + default_files_pattern: '**/*.@(stories.@(js|jsx|mjs|ts|tsx))', }).map(async ({ directory, files, titlePrefix }) => { const pattern = join(directory, files); const absolutePattern = isAbsolute(pattern) ? pattern : join(options.configDir, pattern); From d37817e900afe433f9c287f99154408a8cda0dc6 Mon Sep 17 00:00:00 2001 From: Joe Vaughan <122215197+joevaugh4n@users.noreply.github.com> Date: Fri, 17 Nov 2023 13:44:58 +0000 Subject: [PATCH 071/170] Update .github/DISCUSSION_TEMPLATE/help.yml Co-authored-by: Vanessa Yuen <6842965+vanessayuenn@users.noreply.github.com> --- .github/DISCUSSION_TEMPLATE/help.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/DISCUSSION_TEMPLATE/help.yml b/.github/DISCUSSION_TEMPLATE/help.yml index 970bb18d576f..8a6d64c431f3 100644 --- a/.github/DISCUSSION_TEMPLATE/help.yml +++ b/.github/DISCUSSION_TEMPLATE/help.yml @@ -8,7 +8,7 @@ Before you post: - Check if someone has already asked/answered your question in a previous discussion. When you're ready to post: -- Add tags to your discussion (e.g. 'React', 'Vue', 'Vite') to make it clearer for other users. +- Add labels to your discussion (e.g. 'React', 'Vue', 'Vite') to make it clearer for other users. - type: textarea attributes: From 6f37cc1c272a19f8cc514dc90b47a5ad17cb1d28 Mon Sep 17 00:00:00 2001 From: Joe Vaughan <122215197+joevaugh4n@users.noreply.github.com> Date: Fri, 17 Nov 2023 13:48:03 +0000 Subject: [PATCH 072/170] Update help.yml --- .github/DISCUSSION_TEMPLATE/help.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/DISCUSSION_TEMPLATE/help.yml b/.github/DISCUSSION_TEMPLATE/help.yml index 8a6d64c431f3..47a9ba004d88 100644 --- a/.github/DISCUSSION_TEMPLATE/help.yml +++ b/.github/DISCUSSION_TEMPLATE/help.yml @@ -31,6 +31,7 @@ When you're ready to post: - type: input attributes: label: Create a reproduction - description: Help us debug by creating a minimal reproduction with [https://storybook.new](https://storybook.new) + description: | + Help us debug by creating a minimal reproduction with [https://storybook.new](https://storybook.new). [Learn more about creating a reproduction](ttps://storybook.js.org/docs/react/contribute/how-to-reproduce). validations: required: false From 57768746a0524eb9cf2c390132c90cc5cd5ce730 Mon Sep 17 00:00:00 2001 From: Joe Vaughan <122215197+joevaugh4n@users.noreply.github.com> Date: Fri, 17 Nov 2023 13:48:49 +0000 Subject: [PATCH 073/170] Update help.yml --- .github/DISCUSSION_TEMPLATE/help.yml | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/DISCUSSION_TEMPLATE/help.yml b/.github/DISCUSSION_TEMPLATE/help.yml index 47a9ba004d88..64fe57ca65d2 100644 --- a/.github/DISCUSSION_TEMPLATE/help.yml +++ b/.github/DISCUSSION_TEMPLATE/help.yml @@ -2,14 +2,14 @@ body: - type: markdown attributes: value: | -Thanks for taking the time to start a new discussion! + Thanks for taking the time to start a new discussion! -Before you post: -- Check if someone has already asked/answered your question in a previous discussion. - -When you're ready to post: -- Add labels to your discussion (e.g. 'React', 'Vue', 'Vite') to make it clearer for other users. + Before you post: + - Check if someone has already asked/answered your question in a previous discussion. + When you're ready to post: + - Add labels to your discussion (e.g. 'React', 'Vue', 'Vite') to make it clearer for other users. + - type: textarea attributes: label: Summary From 861170e5391dca89cf8abb353eb9e45d7cafbbd0 Mon Sep 17 00:00:00 2001 From: Norbert de Langen Date: Fri, 17 Nov 2023 14:50:49 +0100 Subject: [PATCH 074/170] cleanup --- code/lib/core-server/src/presets/common-override-preset.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/code/lib/core-server/src/presets/common-override-preset.ts b/code/lib/core-server/src/presets/common-override-preset.ts index 46da6037e3dd..5e907deca646 100644 --- a/code/lib/core-server/src/presets/common-override-preset.ts +++ b/code/lib/core-server/src/presets/common-override-preset.ts @@ -61,12 +61,10 @@ export const stories: PresetProperty<'stories', StorybookConfig> = async (entrie ...expanded, files: `**/${k}`, })); - console.log({ a: filteredEntries.length, b: expanded.files.length }); acc.push(...items); } else { items = [entries[i]]; } - console.log({ items }); acc.push(...items); return acc; From c643d59abfad4ef43d65d8a082ef7880bb761794 Mon Sep 17 00:00:00 2001 From: Norbert de Langen Date: Fri, 17 Nov 2023 15:00:08 +0100 Subject: [PATCH 075/170] fix --- code/lib/core-server/src/presets/common-override-preset.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/code/lib/core-server/src/presets/common-override-preset.ts b/code/lib/core-server/src/presets/common-override-preset.ts index 5e907deca646..0566797e7cf7 100644 --- a/code/lib/core-server/src/presets/common-override-preset.ts +++ b/code/lib/core-server/src/presets/common-override-preset.ts @@ -1,5 +1,4 @@ import type { - NormalizedStoriesSpecifier, Options, PresetProperty, StoriesEntry, From 00d021aaad0f1fb2f9d5ca43d9820e1239f4045d Mon Sep 17 00:00:00 2001 From: Joe Vaughan <122215197+joevaugh4n@users.noreply.github.com> Date: Fri, 17 Nov 2023 14:01:52 +0000 Subject: [PATCH 076/170] Update help.yml --- .github/DISCUSSION_TEMPLATE/help.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.github/DISCUSSION_TEMPLATE/help.yml b/.github/DISCUSSION_TEMPLATE/help.yml index 64fe57ca65d2..a633472ba87c 100644 --- a/.github/DISCUSSION_TEMPLATE/help.yml +++ b/.github/DISCUSSION_TEMPLATE/help.yml @@ -1,7 +1,6 @@ body: - type: markdown - attributes: - value: | + value: | Thanks for taking the time to start a new discussion! Before you post: From 9a4061578af25704fb0737bf2b4d1f28d422b02f Mon Sep 17 00:00:00 2001 From: Joe Vaughan <122215197+joevaugh4n@users.noreply.github.com> Date: Fri, 17 Nov 2023 14:02:07 +0000 Subject: [PATCH 077/170] Update help.yml --- .github/DISCUSSION_TEMPLATE/help.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/DISCUSSION_TEMPLATE/help.yml b/.github/DISCUSSION_TEMPLATE/help.yml index a633472ba87c..844e09e0c226 100644 --- a/.github/DISCUSSION_TEMPLATE/help.yml +++ b/.github/DISCUSSION_TEMPLATE/help.yml @@ -1,6 +1,6 @@ body: - type: markdown - value: | + value: | Thanks for taking the time to start a new discussion! Before you post: From 913d3dc0466625e454d45ba71358ccfe1537ea1c Mon Sep 17 00:00:00 2001 From: Joe Vaughan <122215197+joevaugh4n@users.noreply.github.com> Date: Fri, 17 Nov 2023 14:02:44 +0000 Subject: [PATCH 078/170] Update help.yml --- .github/DISCUSSION_TEMPLATE/help.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/DISCUSSION_TEMPLATE/help.yml b/.github/DISCUSSION_TEMPLATE/help.yml index 844e09e0c226..64fe57ca65d2 100644 --- a/.github/DISCUSSION_TEMPLATE/help.yml +++ b/.github/DISCUSSION_TEMPLATE/help.yml @@ -1,6 +1,7 @@ body: - type: markdown - value: | + attributes: + value: | Thanks for taking the time to start a new discussion! Before you post: From 9c3ffc8ff3b61458505b88d1856984f3c088defb Mon Sep 17 00:00:00 2001 From: Joe Vaughan <122215197+joevaugh4n@users.noreply.github.com> Date: Fri, 17 Nov 2023 14:03:11 +0000 Subject: [PATCH 079/170] Update help.yml --- .github/DISCUSSION_TEMPLATE/help.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/DISCUSSION_TEMPLATE/help.yml b/.github/DISCUSSION_TEMPLATE/help.yml index 64fe57ca65d2..34d9a112ea73 100644 --- a/.github/DISCUSSION_TEMPLATE/help.yml +++ b/.github/DISCUSSION_TEMPLATE/help.yml @@ -2,13 +2,13 @@ body: - type: markdown attributes: value: | - Thanks for taking the time to start a new discussion! + "Thanks for taking the time to start a new discussion! Before you post: - Check if someone has already asked/answered your question in a previous discussion. When you're ready to post: - - Add labels to your discussion (e.g. 'React', 'Vue', 'Vite') to make it clearer for other users. + - Add labels to your discussion (e.g. 'React', 'Vue', 'Vite') to make it clearer for other users." - type: textarea attributes: From a11fd310563daf82572d5a4436997d2f8187542c Mon Sep 17 00:00:00 2001 From: Joe Vaughan <122215197+joevaugh4n@users.noreply.github.com> Date: Fri, 17 Nov 2023 14:03:28 +0000 Subject: [PATCH 080/170] Update help.yml --- .github/DISCUSSION_TEMPLATE/help.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/DISCUSSION_TEMPLATE/help.yml b/.github/DISCUSSION_TEMPLATE/help.yml index 34d9a112ea73..bbd782b4ec85 100644 --- a/.github/DISCUSSION_TEMPLATE/help.yml +++ b/.github/DISCUSSION_TEMPLATE/help.yml @@ -8,7 +8,7 @@ body: - Check if someone has already asked/answered your question in a previous discussion. When you're ready to post: - - Add labels to your discussion (e.g. 'React', 'Vue', 'Vite') to make it clearer for other users." + - Add labels to your discussion (e.g. React, Vue, Vite) to make it clearer for other users." - type: textarea attributes: From c9bcdc77c897e4644659183200e020397622058f Mon Sep 17 00:00:00 2001 From: Joe Vaughan <122215197+joevaugh4n@users.noreply.github.com> Date: Fri, 17 Nov 2023 14:05:12 +0000 Subject: [PATCH 081/170] Update help.yml From f2be784092e5d66807c82d05ea3c1cfa81fbb2a8 Mon Sep 17 00:00:00 2001 From: Joe Vaughan <122215197+joevaugh4n@users.noreply.github.com> Date: Fri, 17 Nov 2023 14:06:03 +0000 Subject: [PATCH 082/170] Update help.yml --- .github/DISCUSSION_TEMPLATE/help.yml | 26 -------------------------- 1 file changed, 26 deletions(-) diff --git a/.github/DISCUSSION_TEMPLATE/help.yml b/.github/DISCUSSION_TEMPLATE/help.yml index bbd782b4ec85..d99ac06410e8 100644 --- a/.github/DISCUSSION_TEMPLATE/help.yml +++ b/.github/DISCUSSION_TEMPLATE/help.yml @@ -9,29 +9,3 @@ body: When you're ready to post: - Add labels to your discussion (e.g. React, Vue, Vite) to make it clearer for other users." - - - type: textarea - attributes: - label: Summary - description: How can we help? - validations: - required: true - - - type: textarea - attributes: - label: Additional information - description: | - Share Your Storybook configuration (`main.js` or `main.ts`), your Storybook version number, any error messages, and any relevant dependencies. These help us get a clearer understanding of what might be going wrong. - - P.S. Please [share code as text](https://docs.github.com/en/get-started/writing-on-github/working-with-advanced-formatting/creating-and-highlighting-code-blocks) rather than as a screenshot! It makes debugging much easier and faster. - render: js - validations: - required: false - - - type: input - attributes: - label: Create a reproduction - description: | - Help us debug by creating a minimal reproduction with [https://storybook.new](https://storybook.new). [Learn more about creating a reproduction](ttps://storybook.js.org/docs/react/contribute/how-to-reproduce). - validations: - required: false From 42170ade21c52d3ba805fdc40d78db63042c728a Mon Sep 17 00:00:00 2001 From: Joe Vaughan <122215197+joevaugh4n@users.noreply.github.com> Date: Fri, 17 Nov 2023 14:06:39 +0000 Subject: [PATCH 083/170] Update help.yml --- .github/DISCUSSION_TEMPLATE/help.yml | 30 ++++++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/.github/DISCUSSION_TEMPLATE/help.yml b/.github/DISCUSSION_TEMPLATE/help.yml index d99ac06410e8..d1052e8ed24e 100644 --- a/.github/DISCUSSION_TEMPLATE/help.yml +++ b/.github/DISCUSSION_TEMPLATE/help.yml @@ -2,10 +2,36 @@ body: - type: markdown attributes: value: | - "Thanks for taking the time to start a new discussion! + Thanks for taking the time to start a new discussion! Before you post: - Check if someone has already asked/answered your question in a previous discussion. When you're ready to post: - - Add labels to your discussion (e.g. React, Vue, Vite) to make it clearer for other users." + - Add labels to your discussion (e.g. React, Vue, Vite) to make it clearer for other users. + + - type: textarea + attributes: + label: Summary + description: How can we help? + validations: + required: true + + - type: textarea + attributes: + label: Additional information + description: | + Share Your Storybook configuration (`main.js` or `main.ts`), your Storybook version number, any error messages, and any relevant dependencies. These help us get a clearer understanding of what might be going wrong. + + P.S. Please [share code as text](https://docs.github.com/en/get-started/writing-on-github/working-with-advanced-formatting/creating-and-highlighting-code-blocks) rather than as a screenshot! It makes debugging much easier and faster. + render: js + validations: + required: false + + - type: input + attributes: + label: Create a reproduction + description: | + Help us debug by creating a minimal reproduction with [https://storybook.new](https://storybook.new). [Learn more about creating a reproduction](ttps://storybook.js.org/docs/react/contribute/how-to-reproduce). + validations: + required: false From bcdf02390dfc00facdce5689ededadc9722a93de Mon Sep 17 00:00:00 2001 From: Joe Vaughan <122215197+joevaugh4n@users.noreply.github.com> Date: Fri, 17 Nov 2023 14:08:57 +0000 Subject: [PATCH 084/170] Update help.yml --- .github/DISCUSSION_TEMPLATE/help.yml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/DISCUSSION_TEMPLATE/help.yml b/.github/DISCUSSION_TEMPLATE/help.yml index d1052e8ed24e..5664b2b8fdbb 100644 --- a/.github/DISCUSSION_TEMPLATE/help.yml +++ b/.github/DISCUSSION_TEMPLATE/help.yml @@ -4,11 +4,11 @@ body: value: | Thanks for taking the time to start a new discussion! - Before you post: - - Check if someone has already asked/answered your question in a previous discussion. + ### Before you post + Check if someone has already asked/answered your question in a previous discussion. - When you're ready to post: - - Add labels to your discussion (e.g. React, Vue, Vite) to make it clearer for other users. + ### When you're ready to post + Add labels to your discussion (e.g. React, Vue, Vite) to make it clearer for other users. - type: textarea attributes: @@ -32,6 +32,6 @@ body: attributes: label: Create a reproduction description: | - Help us debug by creating a minimal reproduction with [https://storybook.new](https://storybook.new). [Learn more about creating a reproduction](ttps://storybook.js.org/docs/react/contribute/how-to-reproduce). + Help us debug by creating a minimal reproduction with [https://storybook.new](https://storybook.new). Learn more about creating a reproduction [here](https://storybook.js.org/docs/react/contribute/how-to-reproduce). validations: required: false From 36d0747f4a6951651ad0f828d2327d657e968cd4 Mon Sep 17 00:00:00 2001 From: Norbert de Langen Date: Fri, 17 Nov 2023 15:22:07 +0100 Subject: [PATCH 085/170] ensure the changed default_files_pattern is applied to entries that didn't need filtering --- .../src/presets/common-override-preset.ts | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/code/lib/core-server/src/presets/common-override-preset.ts b/code/lib/core-server/src/presets/common-override-preset.ts index 0566797e7cf7..345dfa106850 100644 --- a/code/lib/core-server/src/presets/common-override-preset.ts +++ b/code/lib/core-server/src/presets/common-override-preset.ts @@ -25,13 +25,14 @@ export const framework: PresetProperty<'framework', StorybookConfig> = async (co export const stories: PresetProperty<'stories', StorybookConfig> = async (entries, options) => { if (options?.build?.test?.disableMDXEntries) { + const list = normalizeStories(entries, { + configDir: options.configDir, + workingDir: options.configDir, + default_files_pattern: '**/*.@(stories.@(js|jsx|mjs|ts|tsx))', + }); const result = ( await Promise.all( - normalizeStories(entries, { - configDir: options.configDir, - workingDir: options.configDir, - default_files_pattern: '**/*.@(stories.@(js|jsx|mjs|ts|tsx))', - }).map(async ({ directory, files, titlePrefix }) => { + list.map(async ({ directory, files, titlePrefix }) => { const pattern = join(directory, files); const absolutePattern = isAbsolute(pattern) ? pattern : join(options.configDir, pattern); const absoluteDirectory = isAbsolute(directory) @@ -62,7 +63,7 @@ export const stories: PresetProperty<'stories', StorybookConfig> = async (entrie })); acc.push(...items); } else { - items = [entries[i]]; + items = [list[i]]; } acc.push(...items); From 07374ccefdc8187b390e371c9983ca49f23415b8 Mon Sep 17 00:00:00 2001 From: Norbert de Langen Date: Fri, 17 Nov 2023 15:46:55 +0100 Subject: [PATCH 086/170] disable locally --- code/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/code/package.json b/code/package.json index d796c99a0741..9c486f75ab69 100644 --- a/code/package.json +++ b/code/package.json @@ -47,7 +47,7 @@ "storybook:blocks:build": "STORYBOOK_BLOCKS_ONLY=true yarn storybook:ui:build", "storybook:blocks:chromatic": "STORYBOOK_BLOCKS_ONLY=true yarn storybook:ui:chromatic --project-token=${CHROMATIC_TOKEN_STORYBOOK_BLOCKS:-MISSING_PROJECT_TOKEN}", "storybook:ui": "NODE_OPTIONS=\"--preserve-symlinks --preserve-symlinks-main\" ./lib/cli/bin/index.js dev --port 6006 --config-dir ./ui/.storybook", - "storybook:ui:build": "NODE_OPTIONS=\"--preserve-symlinks --preserve-symlinks-main\" ./lib/cli/bin/index.js build --config-dir ./ui/.storybook --test", + "storybook:ui:build": "NODE_OPTIONS=\"--preserve-symlinks --preserve-symlinks-main\" ./lib/cli/bin/index.js build --config-dir ./ui/.storybook", "storybook:ui:chromatic": "yarn chromatic --build-script-name storybook:ui:build --storybook-config-dir ./ui/.storybook --storybook-base-dir ./code --project-token=${CHROMATIC_TOKEN_STORYBOOK_UI:-MISSING_PROJECT_TOKEN} --only-changed --exit-zero-on-changes --exit-once-uploaded", "task": "yarn --cwd ../scripts task", "test": "NODE_OPTIONS=--max_old_space_size=4096 jest --config ./jest.config.js", From ddbb446dec65fa92ba836360a4708a01da412cc1 Mon Sep 17 00:00:00 2001 From: Norbert de Langen Date: Fri, 17 Nov 2023 16:28:23 +0100 Subject: [PATCH 087/170] simpler code --- .../lib/core-server/src/presets/common-override-preset.ts | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/code/lib/core-server/src/presets/common-override-preset.ts b/code/lib/core-server/src/presets/common-override-preset.ts index 345dfa106850..d92dead5d8f4 100644 --- a/code/lib/core-server/src/presets/common-override-preset.ts +++ b/code/lib/core-server/src/presets/common-override-preset.ts @@ -51,7 +51,7 @@ export const stories: PresetProperty<'stories', StorybookConfig> = async (entrie }; }) ) - ).reduce((acc, expanded, i) => { + ).flatMap((expanded, i) => { const filteredEntries = expanded.files.filter((s) => !s.endsWith('.mdx')); // only return the filtered entries when there is something to filter // as webpack is faster with unexpanded globs @@ -61,14 +61,12 @@ export const stories: PresetProperty<'stories', StorybookConfig> = async (entrie ...expanded, files: `**/${k}`, })); - acc.push(...items); } else { items = [list[i]]; } - acc.push(...items); - return acc; - }, []); + return items; + }); return result; } return entries; From b3854495ee87d4ddd23d073b34bf929aa69f1aac Mon Sep 17 00:00:00 2001 From: Tao Zhou Date: Fri, 17 Nov 2023 10:58:42 -0800 Subject: [PATCH 088/170] fix lint --- code/lib/core-server/src/build-dev.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/code/lib/core-server/src/build-dev.ts b/code/lib/core-server/src/build-dev.ts index 7092b9341f4d..459c576113b6 100644 --- a/code/lib/core-server/src/build-dev.ts +++ b/code/lib/core-server/src/build-dev.ts @@ -77,7 +77,7 @@ export async function buildDevStandalone( try { await warnOnIncompatibleAddons(config); } catch (e) { - console.warn("Failed to check for incompatible addons", e); + console.warn('Failed to check for incompatible addons', e); } // Load first pass: We need to determine the builder From 42ce9647f1b1cb8e9bc0fbc17b2126f2013828e3 Mon Sep 17 00:00:00 2001 From: jonniebigodes Date: Fri, 17 Nov 2023 22:07:44 +0000 Subject: [PATCH 089/170] Hooks updates --- .../my-component-exclude-tags.story.js.mdx | 5 +++-- .../my-component-exclude-tags.story.ts.mdx | 5 +++-- .../my-component-include-tags.story.js.mdx | 5 +++-- .../my-component-include-tags.story.ts.mdx | 5 +++-- .../my-component-skip-tags.story.js.mdx | 5 +++-- .../my-component-skip-tags.story.ts.mdx | 5 +++-- .../common/test-runner-a11y-config.js.mdx | 4 ++-- .../common/test-runner-a11y-config.ts.mdx | 8 ++++---- .../common/test-runner-a11y-configure.js.mdx | 4 ++-- .../common/test-runner-a11y-configure.ts.mdx | 8 ++++---- .../common/test-runner-a11y-disable.js.mdx | 4 ++-- .../common/test-runner-a11y-disable.ts.mdx | 8 ++++---- .../test-runner-custom-page-viewport.js.mdx | 2 +- .../test-runner-custom-page-viewport.ts.mdx | 2 +- .../common/test-runner-helper-function.js.mdx | 8 ++++---- .../common/test-runner-helper-function.ts.mdx | 8 ++++---- .../common/test-runner-hooks-example.js.mdx | 8 ++++---- .../common/test-runner-hooks-example.ts.mdx | 8 ++++---- .../common/test-runner-waitpageready.js.mdx | 2 +- .../common/test-runner-waitpageready.ts.mdx | 2 +- docs/writing-tests/accessibility-testing.md | 2 +- docs/writing-tests/test-runner.md | 20 +++++++++---------- 22 files changed, 67 insertions(+), 61 deletions(-) diff --git a/docs/snippets/common/my-component-exclude-tags.story.js.mdx b/docs/snippets/common/my-component-exclude-tags.story.js.mdx index e0b35b71986c..32eebb42518d 100644 --- a/docs/snippets/common/my-component-exclude-tags.story.js.mdx +++ b/docs/snippets/common/my-component-exclude-tags.story.js.mdx @@ -5,10 +5,11 @@ import { MyComponent } from './MyComponent'; export default { component: MyComponent, - tags: ['no-tests'], // šŸ‘ˆ Excludes all stories from being tested with the test-runner + tags: ['no-tests'], // šŸ‘ˆ Provides the `no-tests` tag to all stories in this file }; export const ExcludeStory = { - tags: ['no-tests'], // šŸ‘ˆ Configures the story to be excluded from testing via the `no-tests` tag + //šŸ‘‡ Adds the `no-tests` tag to this story to exclude it from the tests when enabled in the test-runner configuration + tags: ['no-tests'], }; ``` diff --git a/docs/snippets/common/my-component-exclude-tags.story.ts.mdx b/docs/snippets/common/my-component-exclude-tags.story.ts.mdx index 6fee748fadc3..79a62510ad3b 100644 --- a/docs/snippets/common/my-component-exclude-tags.story.ts.mdx +++ b/docs/snippets/common/my-component-exclude-tags.story.ts.mdx @@ -8,13 +8,14 @@ import { MyComponent } from './MyComponent'; const meta: Meta = { component: MyComponent, - tags: ['no-tests'], // šŸ‘ˆ Excludes all stories from being tested with the test-runner + tags: ['no-tests'], // šŸ‘ˆ Provides the `no-tests` tag to all stories in this file }; export default meta; type Story = StoryObj; export const ExcludeStory: Story = { - tags: ['no-tests'], // šŸ‘ˆ Configures the story to be excluded from testing via the `no-tests` tag + //šŸ‘‡ Adds the `no-tests` tag to this story to exclude it from the tests when enabled in the test-runner configuration + tags: ['no-tests'], }; ``` diff --git a/docs/snippets/common/my-component-include-tags.story.js.mdx b/docs/snippets/common/my-component-include-tags.story.js.mdx index 995f5285b1cc..1e667e43c716 100644 --- a/docs/snippets/common/my-component-include-tags.story.js.mdx +++ b/docs/snippets/common/my-component-include-tags.story.js.mdx @@ -5,10 +5,11 @@ import { MyComponent } from './MyComponent'; export default { component: MyComponent, - tags: ['test-only'], // šŸ‘ˆ Runs tests only for stories with this tag + tags: ['test-only'], // šŸ‘ˆ Provides the `test-only` tag to all stories in this file }; export const IncludeStory = { - tags: ['test-only'], // šŸ‘ˆ Configures the story to be added to the test suite with the test-runner + //šŸ‘‡ Adds the `test-only` tag to this story to be included in the tests when enabled in the test-runner configuration + tags: ['test-only'], }; ``` diff --git a/docs/snippets/common/my-component-include-tags.story.ts.mdx b/docs/snippets/common/my-component-include-tags.story.ts.mdx index 5e47651618b6..6b3f71446d8f 100644 --- a/docs/snippets/common/my-component-include-tags.story.ts.mdx +++ b/docs/snippets/common/my-component-include-tags.story.ts.mdx @@ -8,13 +8,14 @@ import { MyComponent } from './MyComponent'; const meta: Meta = { component: MyComponent, - tags: ['test-only'], // šŸ‘ˆ Runs tests only for stories with this tag + tags: ['test-only'], // šŸ‘ˆ Provides the `test-only` tag to all stories in this file }; export default meta; type Story = StoryObj; export const IncludeStory: Story = { - tags: ['test-only'], // šŸ‘ˆ Configures the story to be added to the test suite with the test-runner + //šŸ‘‡ Adds the `test-only` tag to this story to be included in the tests when enabled in the test-runner configuration + tags: ['test-only'], }; ``` diff --git a/docs/snippets/common/my-component-skip-tags.story.js.mdx b/docs/snippets/common/my-component-skip-tags.story.js.mdx index bf3737cb2ef6..c59991aace99 100644 --- a/docs/snippets/common/my-component-skip-tags.story.js.mdx +++ b/docs/snippets/common/my-component-skip-tags.story.js.mdx @@ -5,10 +5,11 @@ import { MyComponent } from './MyComponent'; export default { component: MyComponent, - tags: ['skip-test'], // šŸ‘ˆ Skips running tests on this story + tags: ['skip-test'], // šŸ‘ˆ Provides the `skip-test` tag to all stories in this file }; export const SkipStory = { - tags: ['skip-test'], // šŸ‘ˆ Configures the story to be skipped when running tests with the test-runner + //šŸ‘‡ Adds the `skip-test` tag to this story to allow it to be skipped in the tests when enabled in the test-runner configuration + tags: ['skip-test'], }; ``` diff --git a/docs/snippets/common/my-component-skip-tags.story.ts.mdx b/docs/snippets/common/my-component-skip-tags.story.ts.mdx index 62c0d1dfbabf..3513e3d33c43 100644 --- a/docs/snippets/common/my-component-skip-tags.story.ts.mdx +++ b/docs/snippets/common/my-component-skip-tags.story.ts.mdx @@ -8,13 +8,14 @@ import { MyComponent } from './MyComponent'; const meta: Meta = { component: MyComponent, - tags: ['skip-test'], // šŸ‘ˆ Skips running tests on this story + tags: ['skip-test'], // šŸ‘ˆ Provides the `skip-test` tag to all stories in this file }; export default meta; type Story = StoryObj; export const SkipStory: Story = { - tags: ['skip-test'], // šŸ‘ˆ Configures the story to be skipped when running tests with the test-runner + //šŸ‘‡ Adds the `skip-test` tag to this story to allow it to be skipped in the tests when enabled in the test-runner configuration + tags: ['skip-test'], }; ``` diff --git a/docs/snippets/common/test-runner-a11y-config.js.mdx b/docs/snippets/common/test-runner-a11y-config.js.mdx index bf5f2b954fb3..9ce64c1e3f09 100644 --- a/docs/snippets/common/test-runner-a11y-config.js.mdx +++ b/docs/snippets/common/test-runner-a11y-config.js.mdx @@ -8,10 +8,10 @@ const { injectAxe, checkA11y } = require('axe-playwright'); * to learn more about the test-runner hooks API. */ module.exports = { - async preRender(page) { + async preVisit(page) { await injectAxe(page); }, - async postRender(page) { + async postVisit(page) { await checkA11y(page, '#storybook-root', { detailedReport: true, detailedReportOptions: { diff --git a/docs/snippets/common/test-runner-a11y-config.ts.mdx b/docs/snippets/common/test-runner-a11y-config.ts.mdx index c007a62c1244..4bc91082506f 100644 --- a/docs/snippets/common/test-runner-a11y-config.ts.mdx +++ b/docs/snippets/common/test-runner-a11y-config.ts.mdx @@ -8,11 +8,11 @@ import { injectAxe, checkA11y } from 'axe-playwright'; * See https://storybook.js.org/docs/react/writing-tests/test-runner#test-hook-api * to learn more about the test-runner hooks API. */ -const a11yConfig: TestRunnerConfig = { - async preRender(page) { +const config: TestRunnerConfig = { + async preVisit(page) { await injectAxe(page); }, - async postRender(page) { + async postVisit(page) { await checkA11y(page, '#storybook-root', { detailedReport: true, detailedReportOptions: { @@ -22,5 +22,5 @@ const a11yConfig: TestRunnerConfig = { }, }; -export default a11yConfig; +export default config; ``` diff --git a/docs/snippets/common/test-runner-a11y-configure.js.mdx b/docs/snippets/common/test-runner-a11y-configure.js.mdx index 23333177d9a3..abd0a20b4089 100644 --- a/docs/snippets/common/test-runner-a11y-configure.js.mdx +++ b/docs/snippets/common/test-runner-a11y-configure.js.mdx @@ -10,10 +10,10 @@ const { getStoryContext } = require('@storybook/test-runner'); * to learn more about the test-runner hooks API. */ module.exports = { - async preRender(page) { + async preVisit(page) { await injectAxe(page); }, - async postRender(page, context) { + async postVisit(page, context) { // Get the entire context of a story, including parameters, args, argTypes, etc. const storyContext = await getStoryContext(page, context); diff --git a/docs/snippets/common/test-runner-a11y-configure.ts.mdx b/docs/snippets/common/test-runner-a11y-configure.ts.mdx index 5a9adea12c86..5af07ea7d760 100644 --- a/docs/snippets/common/test-runner-a11y-configure.ts.mdx +++ b/docs/snippets/common/test-runner-a11y-configure.ts.mdx @@ -10,11 +10,11 @@ import { injectAxe, checkA11y, configureAxe } from 'axe-playwright'; * See https://storybook.js.org/docs/react/writing-tests/test-runner#test-hook-api * to learn more about the test-runner hooks API. */ -const a11yConfig: TestRunnerConfig = { - async preRender(page) { +const config: TestRunnerConfig = { + async preVisit(page) { await injectAxe(page); }, - async postRender(page, context) { + async postVisit(page, context) { // Get the entire context of a story, including parameters, args, argTypes, etc. const storyContext = await getStoryContext(page, context); @@ -32,5 +32,5 @@ const a11yConfig: TestRunnerConfig = { }, }; -export default a11yConfig; +export default config; ``` diff --git a/docs/snippets/common/test-runner-a11y-disable.js.mdx b/docs/snippets/common/test-runner-a11y-disable.js.mdx index 02a13b3efca9..d6177c9ce38f 100644 --- a/docs/snippets/common/test-runner-a11y-disable.js.mdx +++ b/docs/snippets/common/test-runner-a11y-disable.js.mdx @@ -9,10 +9,10 @@ const { injectAxe, checkA11y } = require('axe-playwright'); * to learn more about the test-runner hooks API. */ module.exports = { - async preRender(page) { + async preVisit(page) { await injectAxe(page); }, - async postRender(page, context) { + async postVisit(page, context) { // Get the entire context of a story, including parameters, args, argTypes, etc. const storyContext = await getStoryContext(page, context); diff --git a/docs/snippets/common/test-runner-a11y-disable.ts.mdx b/docs/snippets/common/test-runner-a11y-disable.ts.mdx index 97d8cd06f0fa..1be273fee210 100644 --- a/docs/snippets/common/test-runner-a11y-disable.ts.mdx +++ b/docs/snippets/common/test-runner-a11y-disable.ts.mdx @@ -10,11 +10,11 @@ import { injectAxe, checkA11y } from 'axe-playwright'; * See https://storybook.js.org/docs/react/writing-tests/test-runner#test-hook-api * to learn more about the test-runner hooks API. */ -const a11yConfig: TestRunnerConfig = { - async preRender(page) { +const config: TestRunnerConfig = { + async preVisit(page) { await injectAxe(page); }, - async postRender(page, context) { + async postVisit(page, context) { // Get the entire context of a story, including parameters, args, argTypes, etc. const storyContext = await getStoryContext(page, context); @@ -31,5 +31,5 @@ const a11yConfig: TestRunnerConfig = { }, }; -export default a11yConfig; +export default config; ``` diff --git a/docs/snippets/common/test-runner-custom-page-viewport.js.mdx b/docs/snippets/common/test-runner-custom-page-viewport.js.mdx index a4d5d0cc57f1..b334755d1f74 100644 --- a/docs/snippets/common/test-runner-custom-page-viewport.js.mdx +++ b/docs/snippets/common/test-runner-custom-page-viewport.js.mdx @@ -7,7 +7,7 @@ const { MINIMAL_VIEWPORTS } = require('@storybook/addon-viewport'); const DEFAULT_VIEWPORT_SIZE = { width: 1280, height: 720 }; module.exports = { - async preRender(page, story) { + async preVisit(page, story) { // Accesses the story's parameters and retrieves the viewport used to render it const context = await getStoryContext(page, story); const viewportName = context.parameters?.viewport?.defaultViewport; diff --git a/docs/snippets/common/test-runner-custom-page-viewport.ts.mdx b/docs/snippets/common/test-runner-custom-page-viewport.ts.mdx index 351b9e8bd0ec..5db491a51335 100644 --- a/docs/snippets/common/test-runner-custom-page-viewport.ts.mdx +++ b/docs/snippets/common/test-runner-custom-page-viewport.ts.mdx @@ -9,7 +9,7 @@ const { MINIMAL_VIEWPORTS } = require('@storybook/addon-viewport'); const DEFAULT_VIEWPORT_SIZE = { width: 1280, height: 720 }; const config: TestRunnerConfig = { - async preRender(page, story) { + async preVisit(page, story) { // Accesses the story's parameters and retrieves the viewport used to render it const context = await getStoryContext(page, story); const viewportName = context.parameters?.viewport?.defaultViewport; diff --git a/docs/snippets/common/test-runner-helper-function.js.mdx b/docs/snippets/common/test-runner-helper-function.js.mdx index 739f0034b59e..9e7827f029ab 100644 --- a/docs/snippets/common/test-runner-helper-function.js.mdx +++ b/docs/snippets/common/test-runner-helper-function.js.mdx @@ -8,18 +8,18 @@ module.exports = { setup() { // Add your configuration here. }, - /* Hook to execute before a story is rendered. + /* Hook to execute before a story is initially visited before being rendered in the browser. * The page argument is the Playwright's page object for the story. * The context argument is a Storybook object containing the story's id, title, and name. */ - async preRender(page, context) { + async preVisit(page, context) { // Add your configuration here. }, - /* Hook to execute after a story is rendered. + /* Hook to execute after a story is visited and fully rendered. * The page argument is the Playwright's page object for the story * The context argument is a Storybook object containing the story's id, title, and name. */ - async postRender(page, context) { + async postVisit(page, context) { // Get the entire context of a story, including parameters, args, argTypes, etc. const storyContext = await getStoryContext(page, context); diff --git a/docs/snippets/common/test-runner-helper-function.ts.mdx b/docs/snippets/common/test-runner-helper-function.ts.mdx index 57a04bd7c465..af40e58b2dee 100644 --- a/docs/snippets/common/test-runner-helper-function.ts.mdx +++ b/docs/snippets/common/test-runner-helper-function.ts.mdx @@ -9,18 +9,18 @@ const config: TestRunnerConfig = { setup() { // Add your configuration here. }, - /* Hook to execute before a story is rendered. + /* Hook to execute before a story is initially visited before being rendered in the browser. * The page argument is the Playwright's page object for the story. * The context argument is a Storybook object containing the story's id, title, and name. */ - async preRender(page, context) { + async preVisit(page, context) { // Add your configuration here. }, - /* Hook to execute after a story is rendered. + /* Hook to execute after a story is visited and fully rendered. * The page argument is the Playwright's page object for the story * The context argument is a Storybook object containing the story's id, title, and name. */ - async postRender(page, context) { + async postVisit(page, context) { // Get the entire context of a story, including parameters, args, argTypes, etc. const storyContext = await getStoryContext(page, context); diff --git a/docs/snippets/common/test-runner-hooks-example.js.mdx b/docs/snippets/common/test-runner-hooks-example.js.mdx index e3d52b738645..18876266bf31 100644 --- a/docs/snippets/common/test-runner-hooks-example.js.mdx +++ b/docs/snippets/common/test-runner-hooks-example.js.mdx @@ -6,18 +6,18 @@ module.exports = { setup() { // Add your configuration here. }, - /* Hook to execute before a story is rendered. + /* Hook to execute before a story is initially visited before being rendered in the browser. * The page argument is the Playwright's page object for the story. * The context argument is a Storybook object containing the story's id, title, and name. */ - async preRender(page, context) { + async preVisit(page, context) { // Add your configuration here. }, - /* Hook to execute after a story is rendered. + /* Hook to execute after a story is visited and fully rendered. * The page argument is the Playwright's page object for the story * The context argument is a Storybook object containing the story's id, title, and name. */ - async postRender(page, context) { + async postVisit(page, context) { // Add your configuration here. }, }; diff --git a/docs/snippets/common/test-runner-hooks-example.ts.mdx b/docs/snippets/common/test-runner-hooks-example.ts.mdx index 86398c9aeb45..f06d4c71b063 100644 --- a/docs/snippets/common/test-runner-hooks-example.ts.mdx +++ b/docs/snippets/common/test-runner-hooks-example.ts.mdx @@ -8,18 +8,18 @@ const config: TestRunnerConfig = { setup() { // Add your configuration here. }, - /* Hook to execute before a story is rendered. + /* Hook to execute before a story is initially visited before being rendered in the browser. * The page argument is the Playwright's page object for the story. * The context argument is a Storybook object containing the story's id, title, and name. */ - async preRender(page, context) { + async preVisit(page, context) { // Add your configuration here. }, - /* Hook to execute after a story is rendered. + /* Hook to execute after a story is visited and fully rendered. * The page argument is the Playwright's page object for the story * The context argument is a Storybook object containing the story's id, title, and name. */ - async postRender(page, context) { + async postVisit(page, context) { // Add your configuration here. }, }; diff --git a/docs/snippets/common/test-runner-waitpageready.js.mdx b/docs/snippets/common/test-runner-waitpageready.js.mdx index 0dfb8aecb22a..1bb3df563c00 100644 --- a/docs/snippets/common/test-runner-waitpageready.js.mdx +++ b/docs/snippets/common/test-runner-waitpageready.js.mdx @@ -10,7 +10,7 @@ module.exports = { setup() { expect.extend({ toMatchImageSnapshot }); }, - async postRender(page, context) { + async postVisit(page, context) { // Awaits for the page to be loaded and available including assets (e.g., fonts) await waitForPageReady(page); diff --git a/docs/snippets/common/test-runner-waitpageready.ts.mdx b/docs/snippets/common/test-runner-waitpageready.ts.mdx index 7a3c1ae88d8e..2da14b2c7185 100644 --- a/docs/snippets/common/test-runner-waitpageready.ts.mdx +++ b/docs/snippets/common/test-runner-waitpageready.ts.mdx @@ -12,7 +12,7 @@ const config: TestRunnerConfig = { setup() { expect.extend({ toMatchImageSnapshot }); }, - async postRender(page, context) { + async postVisit(page, context) { // Awaits for the page to be loaded and available including assets (e.g., fonts) await waitForPageReady(page); diff --git a/docs/writing-tests/accessibility-testing.md b/docs/writing-tests/accessibility-testing.md index cbc39f9cdf1c..36c17f89860c 100644 --- a/docs/writing-tests/accessibility-testing.md +++ b/docs/writing-tests/accessibility-testing.md @@ -205,7 +205,7 @@ Add a new [configuration file](./test-runner.md#test-hook-api) inside your Story -`preRender` and `postRender` are convenient hooks that allow you to extend the test runner's default configuration. Read more about them [here](./test-runner.md#test-hook-api). +`preVisit` and `postVisit` are convenient hooks that allow you to extend the test runner's default configuration. Read more about them [here](./test-runner.md#test-hook-api). diff --git a/docs/writing-tests/test-runner.md b/docs/writing-tests/test-runner.md index fc34bbd9caea..90eef2dcaa89 100644 --- a/docs/writing-tests/test-runner.md +++ b/docs/writing-tests/test-runner.md @@ -202,12 +202,12 @@ The test-runner renders a story and executes its [play function](../writing-stor The test-runner exports test hooks that can be overridden globally to enable use cases like visual or DOM snapshots. These hooks give you access to the test lifecycle _before_ and _after_ the story is rendered. Listed below are the available hooks and an overview of how to use them. -| Hook | Description | -| ------------ | ------------------------------------------------------------------------------------------------- | -| `prepare` | Prepares the browser for tests
`async prepare({ page, browserContext, testRunnerConfig }) {}` | -| `setup` | Executes once before all the tests run
`setup() {}` | -| `preRender` | Executes before a story is rendered
`async preRender(page, context) {}` | -| `postRender` | Executes after the story is rendered
`async postRender(page, context) {}` | +| Hook | Description | +| ----------- | --------------------------------------------------------------------------------------------------------------- | +| `prepare` | Prepares the browser for tests
`async prepare({ page, browserContext, testRunnerConfig }) {}` | +| `setup` | Executes once before all the tests run
`setup() {}` | +| `preVisit` | Executes before a story is initially visited and rendered in the browser
`async preVisit(page, context) {}` | +| `postVisit` | Executes after the story is is visited and fully rendered
`async postVisit(page, context) {}` | To enable the hooks API, you'll need to add a new configuration file inside your Storybook directory and set them up as follows: @@ -224,7 +224,7 @@ To enable the hooks API, you'll need to add a new configuration file inside your -Except for the `setup` function, all other functions run asynchronously. Both `preRender` and `postRender` functions include two additional arguments, a [Playwright page](https://playwright.dev/docs/pages) and a context object which contains the `id`, `title`, and the `name` of the story. +Except for the `setup` function, all other functions run asynchronously. Both `preVisit` and `postVisit` functions include two additional arguments, a [Playwright page](https://playwright.dev/docs/pages) and a context object which contains the `id`, `title`, and the `name` of the story. @@ -233,9 +233,9 @@ When the test-runner executes, your existing tests will go through the following - The `setup` function is executed before all the tests run. - The context object is generated containing the required information. - Playwright navigates to the story's page. -- The `preRender` function is executed. +- The `preVisit` function is executed. - The story is rendered, and any existing `play` functions are executed. -- The `postRender` function is executed. +- The `postVisit` function is executed. ### (Experimental) Filter tests @@ -306,7 +306,7 @@ Applying tags for the component's stories should either be done at the component #### Skip tests -If you want to skip running tests on a particular story or subset of stories, you can configure your story with a custom tag, enable it in the test-runner configuration file, or run the test-runner with the `--skipTags` [CLI](#cli-options) flag. Running tests with this option will cause the test-runner to skip over the story and flag them accordingly in the test results. For example: +If you want to skip running tests on a particular story or subset of stories, you can configure your story with a custom tag, enable it in the test-runner configuration file, or run the test-runner with the `--skipTags` [CLI](#cli-options) flag. Running tests with this option will cause the test-runner to ignore and flag them accordingly in the test results, indicating that the tests are temporarily disabled. For example: From 6ead60de0f341019176ca0ed3576434fbaac1692 Mon Sep 17 00:00:00 2001 From: jonniebigodes Date: Sat, 18 Nov 2023 20:27:17 +0000 Subject: [PATCH 090/170] Small tweaks --- docs/api/cli-options.md | 1 + docs/api/main-config-build.md | 5 +++++ docs/api/main-config.md | 1 + docs/configure/overview.md | 31 ++++++++++++++++--------------- docs/sharing/publish-storybook.md | 12 ++++++++++-- docs/toc.js | 5 +++++ 6 files changed, 38 insertions(+), 17 deletions(-) create mode 100644 docs/api/main-config-build.md diff --git a/docs/api/cli-options.md b/docs/api/cli-options.md index a89d55a94d14..2a2fcf3dfdd7 100644 --- a/docs/api/cli-options.md +++ b/docs/api/cli-options.md @@ -74,6 +74,7 @@ Options include: | `--webpack-stats-json` | Write Webpack Stats JSON to disk
`storybook build --webpack-stats-json /my-storybook/webpack-stats` | | `--docs` | Builds Storybook in documentation mode. Learn more about it in [here](../writing-docs/build-documentation.md#publish-storybooks-documentation)
`storybook build --docs` | | `--disable-telemetry` | Disables Storybook's telemetry. Learn more about it [here](../configure/telemetry.md).
`storybook build --disable-telemetry` | +| `--test` | Optimize Storybook's production build for performance and tests by removing unnecessary features with the `test` option. Learn more [here](../api/main-config-build.md). | diff --git a/docs/api/main-config-build.md b/docs/api/main-config-build.md new file mode 100644 index 000000000000..6ccbe01a5df2 --- /dev/null +++ b/docs/api/main-config-build.md @@ -0,0 +1,5 @@ +--- +title: 'build' +--- + +Parent: [main.js|ts configuration](./main-config.md) diff --git a/docs/api/main-config.md b/docs/api/main-config.md index 69372067bdf8..e0988eec381f 100644 --- a/docs/api/main-config.md +++ b/docs/api/main-config.md @@ -30,6 +30,7 @@ An object to configure Storybook containing the following properties: - [`addons`](./main-config-addons.md) - [`babel`](./main-config-babel.md) - [`babelDefault`](./main-config-babel-default.md) +- [`build`](./main-config-build.md) - [`core`](./main-config-core.md) - [`docs`](./main-config-docs.md) - [`env`](./main-config-env.md) diff --git a/docs/configure/overview.md b/docs/configure/overview.md index 4e11a8f5c440..965515186fed 100644 --- a/docs/configure/overview.md +++ b/docs/configure/overview.md @@ -31,21 +31,22 @@ This configuration file is a [preset](../addons/addon-types.md) and, as such, ha -| Configuration element | Description | -| --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `stories` | The array of globs that indicates the [location of your story files](#configure-story-loading), relative to `main.js` | -| `staticDirs` | Sets a list of directories of [static files](./images-and-assets.md#serving-static-files-via-storybook-configuration) to be loaded by Storybook
`staticDirs: ['../public']` | -| `addons` | Sets the list of [addons](https://storybook.js.org/integrations) loaded by Storybook
`addons: ['@storybook/addon-essentials']` | -| `typescript` | Configures how Storybook handles [TypeScript files](./typescript.md)
`typescript: { check: false, checkOptions: {} }` | -| `framework` | Configures Storybook based on a set of [framework-specific](./frameworks.md) settings
`framework: { name: '@storybook/svelte-vite', options:{} }` | -| `core` | Configures Storybook's [internal features](../api/main-config-core.md)
`core: { disableTelemetry: true, }` | -| `docs` | Configures Storybook's [auto-generated documentation](../writing-docs/autodocs.md)
`docs: { autodocs: 'tag' }` | -| `features` | Enables Storybook's [additional features](../api/main-config-features.md)
See table below for a list of available features `features: { storyStoreV7: true }` | -| `refs` | Configures [Storybook composition](../sharing/storybook-composition.md)
`refs:{ example: { title: 'ExampleStorybook', url:'https://your-url.com' } }` | -| `logLevel` | Configures Storybook's logs in the browser terminal. Useful for debugging
`logLevel: 'debug'` | -| `webpackFinal` | Customize Storybook's [Webpack](../builders/webpack.md) setup
`webpackFinal: async (config:any) => { return config; }` | -| `viteFinal` | Customize Storybook's Vite setup when using the [vite builder](https://github.com/storybookjs/builder-vite)
`viteFinal: async (config: Vite.InlineConfig, options: Options) => { return config; }` | -| `env` | Defines custom Storybook [environment variables](./environment-variables.md#using-storybook-configuration).
`env: (config) => ({...config, EXAMPLE_VAR: 'Example var' }),` | +| Configuration element | Description | +| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `stories` | The array of globs that indicates the [location of your story files](#configure-story-loading), relative to `main.js` | +| `staticDirs` | Sets a list of directories of [static files](./images-and-assets.md#serving-static-files-via-storybook-configuration) to be loaded by Storybook
`staticDirs: ['../public']` | +| `addons` | Sets the list of [addons](https://storybook.js.org/integrations) loaded by Storybook
`addons: ['@storybook/addon-essentials']` | +| `typescript` | Configures how Storybook handles [TypeScript files](./typescript.md)
`typescript: { check: false, checkOptions: {} }` | +| `framework` | Configures Storybook based on a set of [framework-specific](./frameworks.md) settings
`framework: { name: '@storybook/svelte-vite', options:{} }` | +| `core` | Configures Storybook's [internal features](../api/main-config-core.md)
`core: { disableTelemetry: true, }` | +| `docs` | Configures Storybook's [auto-generated documentation](../writing-docs/autodocs.md)
`docs: { autodocs: 'tag' }` | +| `features` | Enables Storybook's [additional features](../api/main-config-features.md)
See table below for a list of available features `features: { storyStoreV7: true }` | +| `refs` | Configures [Storybook composition](../sharing/storybook-composition.md)
`refs:{ example: { title: 'ExampleStorybook', url:'https://your-url.com' } }` | +| `logLevel` | Configures Storybook's logs in the browser terminal. Useful for debugging
`logLevel: 'debug'` | +| `webpackFinal` | Customize Storybook's [Webpack](../builders/webpack.md) setup
`webpackFinal: async (config:any) => { return config; }` | +| `viteFinal` | Customize Storybook's Vite setup when using the [vite builder](https://github.com/storybookjs/builder-vite)
`viteFinal: async (config: Vite.InlineConfig, options: Options) => { return config; }` | +| `env` | Defines custom Storybook [environment variables](./environment-variables.md#using-storybook-configuration).
`env: (config) => ({...config, EXAMPLE_VAR: 'Example var' }),` | +| `build` | Optimizes Storybook's production [build](../api/main-config-test.md) for performance by excluding specific features from the bundle. Useful when decreased build times are a priority.
`build:Ā { test: {} }` | ### Feature flags diff --git a/docs/sharing/publish-storybook.md b/docs/sharing/publish-storybook.md index ca98bb2d8264..a4c214128205 100644 --- a/docs/sharing/publish-storybook.md +++ b/docs/sharing/publish-storybook.md @@ -50,6 +50,16 @@ Storybook will create a static web application capable of being served by any we +### Customizing the build for for performance + +By default, Storybook's production build will encapsulate all stories and documentation into the published bundle. This is great for small projects, but can cause performance issues for larger projects or when decreased build times are a priority. If you + + + + + +. To optimize Storybook's production build for performance and tests, you can remove unnecessary features with the `test` option. Learn more [here](../api/main-config-test.md). + ## Publish Storybook with Chromatic Once you've built your Storybook as a static web application, you can publish it to your web host. We recommend [Chromatic](https://www.chromatic.com/?utm_source=storybook_website&utm_medium=link&utm_campaign=storybook), a free publishing service made for Storybook that documents, versions, and indexes your UI components securely in the cloud. @@ -137,7 +147,6 @@ Since Storybook is built as a static web application, you can also publish it to To deploy Storybook on GitHub Pages, use the community-built [Deploy Storybook to GitHub Pages](https://github.com/bitovi/github-actions-storybook-to-github-pages) Action. To enable it, create a new workflow file inside your `.github/workflows` directory with the following content: - -

Component Publishing Protocol (CPP)

diff --git a/docs/toc.js b/docs/toc.js index 9c773a493244..13d66fee3bab 100644 --- a/docs/toc.js +++ b/docs/toc.js @@ -506,6 +506,11 @@ module.exports = { title: 'babelDefault', pathSegment: 'main-config-babel-default', type: 'link', + }, + { + title: 'build', + pathSegment: 'main-config-build', + type: 'link', }, { title: 'core', From e2c41a8b834d8ed189d962f9b12179ddf5e5ea76 Mon Sep 17 00:00:00 2001 From: jonniebigodes Date: Sat, 18 Nov 2023 21:01:46 +0000 Subject: [PATCH 091/170] tag fix and minor polish to the intro --- docs/writing-tests/test-runner.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/writing-tests/test-runner.md b/docs/writing-tests/test-runner.md index 90eef2dcaa89..fc4daeb130f1 100644 --- a/docs/writing-tests/test-runner.md +++ b/docs/writing-tests/test-runner.md @@ -106,7 +106,7 @@ If you're already using any of those flags in your project, you should be able t | `--shard [index/count]` | Requires CI. Splits the test suite execution into multiple machines
`test-storybook --shard=1/8` | | `--failOnConsole` | Makes tests fail on browser console errors
`test-storybook --failOnConsole` | | `--includeTags` | Experimental feature
Defines a subset of stories to be tested if they match the enabled [tags](#experimental-filter-tests).
`test-storybook --includeTags="test-only, pages"` | -| `--excludeTags` | Experimental feature
Prevents stories from being tested if they match the provided [tags](#experimental-filter-tests).
`test-storybook --skipTags="no-tests, tokens"` | +| `--excludeTags` | Experimental feature
Prevents stories from being tested if they match the provided [tags](#experimental-filter-tests).
`test-storybook --excludeTags="no-tests, tokens"` | | `--skipTags` | Experimental feature
Configures the test runner to skip running tests for stories that match the provided [tags](#experimental-filter-tests).
`test-storybook --skipTags="skip-test, layout"` | @@ -239,7 +239,7 @@ When the test-runner executes, your existing tests will go through the following ### (Experimental) Filter tests -When you run the test-runner on Storybook, it tests every story by default. However, if you want to filter the tests, you can use the `tags` configuration option. Storybook originally introduced this feature to generate [automatic documentation](../writing-docs/autodocs.md) for stories. But it can be further extended to configure the test-runner to run tests according to the provided tags using a similar configuration option or via CLI flags (e.g., `--includeTags`, `--excludeTags`, `--skipTags`). Listed below are the available options and an overview of how to use them. +When you run the test-runner on Storybook, it tests every story by default. However, if you want to filter the tests, you can use the `tags` configuration option. Storybook originally introduced this feature to generate [automatic documentation](../writing-docs/autodocs.md) for stories. But it can be further extended to configure the test-runner to run tests according to the provided tags using a similar configuration option or via CLI flags (e.g., `--includeTags`, `--excludeTags`, `--skipTags`), only available with the latest stable release (`0.15` or higher). Listed below are the available options and an overview of how to use them. | Option | Description | | --------- | ----------------------------------------------------------------------------- | From 51d5ea788662f753f53d25522c5fbf67363cf5d7 Mon Sep 17 00:00:00 2001 From: jonniebigodes Date: Sun, 19 Nov 2023 19:40:12 +0000 Subject: [PATCH 092/170] Examples added. Docs cleanup --- docs/api/cli-options.md | 28 ++-- docs/api/main-config-build.md | 148 ++++++++++++++++++ docs/configure/overview.md | 32 ++-- docs/faq.md | 24 +++ docs/sharing/publish-storybook.md | 14 +- .../main-config-test-disable-autodocs.js.mdx | 14 ++ .../main-config-test-disable-autodocs.ts.mdx | 18 +++ .../main-config-test-disable-blocks.js.mdx | 14 ++ .../main-config-test-disable-blocks.ts.mdx | 18 +++ ...n-config-test-disable-disableaddons.js.mdx | 20 +++ ...n-config-test-disable-disableaddons.ts.mdx | 24 +++ .../main-config-test-disable-docgen.js.mdx | 14 ++ .../main-config-test-disable-docgen.ts.mdx | 18 +++ .../main-config-test-disable-mdx.js.mdx | 14 ++ .../main-config-test-disable-mdx.ts.mdx | 18 +++ ...main-config-test-disable-sourcemaps.js.mdx | 14 ++ ...main-config-test-disable-sourcemaps.ts.mdx | 18 +++ ...ain-config-test-disable-treeshaking.js.mdx | 14 ++ ...ain-config-test-disable-treeshaking.ts.mdx | 18 +++ .../storybook-build-test-flag.npm.js.mdx | 3 + .../storybook-build-test-flag.pnpm.js.mdx | 3 + .../storybook-build-test-flag.yarn.js.mdx | 3 + 22 files changed, 457 insertions(+), 34 deletions(-) create mode 100644 docs/snippets/common/main-config-test-disable-autodocs.js.mdx create mode 100644 docs/snippets/common/main-config-test-disable-autodocs.ts.mdx create mode 100644 docs/snippets/common/main-config-test-disable-blocks.js.mdx create mode 100644 docs/snippets/common/main-config-test-disable-blocks.ts.mdx create mode 100644 docs/snippets/common/main-config-test-disable-disableaddons.js.mdx create mode 100644 docs/snippets/common/main-config-test-disable-disableaddons.ts.mdx create mode 100644 docs/snippets/common/main-config-test-disable-docgen.js.mdx create mode 100644 docs/snippets/common/main-config-test-disable-docgen.ts.mdx create mode 100644 docs/snippets/common/main-config-test-disable-mdx.js.mdx create mode 100644 docs/snippets/common/main-config-test-disable-mdx.ts.mdx create mode 100644 docs/snippets/common/main-config-test-disable-sourcemaps.js.mdx create mode 100644 docs/snippets/common/main-config-test-disable-sourcemaps.ts.mdx create mode 100644 docs/snippets/common/main-config-test-disable-treeshaking.js.mdx create mode 100644 docs/snippets/common/main-config-test-disable-treeshaking.ts.mdx create mode 100644 docs/snippets/common/storybook-build-test-flag.npm.js.mdx create mode 100644 docs/snippets/common/storybook-build-test-flag.pnpm.js.mdx create mode 100644 docs/snippets/common/storybook-build-test-flag.yarn.js.mdx diff --git a/docs/api/cli-options.md b/docs/api/cli-options.md index 2a2fcf3dfdd7..1ccbb4d1f124 100644 --- a/docs/api/cli-options.md +++ b/docs/api/cli-options.md @@ -61,20 +61,20 @@ storybook build [options] Options include: -| Option | Description | -| ------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `-h`, `--help` | Output usage information
`storybook build --help` | -| `-V`, `--version` | Output the version number
`storybook build -V` | -| `-s`, `--static-dir` | **Deprecated** [see note](#static-dir-deprecation).
Directory where to load static files from, comma-separated list
`storybook build -s public` | -| `-o`, `--output-dir [dir-name]` | Directory where to store built files
`storybook build -o /my-deployed-storybook` | -| `-c`, `--config-dir [dir-name]` | Directory where to load Storybook configurations from
`storybook build -c .storybook` | -| `--loglevel [level]` | Controls level of logging during build.
Available options: `silly`, `verbose`, `info` (default), `warn`, `error`, `silent`
`storybook build --loglevel warn` | -| `--quiet` | Suppress verbose build output
`storybook build --quiet` | -| `--debug-webpack` | Display final webpack configurations for debugging purposes
`storybook build --debug-webpack` | -| `--webpack-stats-json` | Write Webpack Stats JSON to disk
`storybook build --webpack-stats-json /my-storybook/webpack-stats` | -| `--docs` | Builds Storybook in documentation mode. Learn more about it in [here](../writing-docs/build-documentation.md#publish-storybooks-documentation)
`storybook build --docs` | -| `--disable-telemetry` | Disables Storybook's telemetry. Learn more about it [here](../configure/telemetry.md).
`storybook build --disable-telemetry` | -| `--test` | Optimize Storybook's production build for performance and tests by removing unnecessary features with the `test` option. Learn more [here](../api/main-config-build.md). | +| Option | Description | +| ------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `-h`, `--help` | Output usage information
`storybook build --help` | +| `-V`, `--version` | Output the version number
`storybook build -V` | +| `-s`, `--static-dir` | **Deprecated** [see note](#static-dir-deprecation).
Directory where to load static files from, comma-separated list
`storybook build -s public` | +| `-o`, `--output-dir [dir-name]` | Directory where to store built files
`storybook build -o /my-deployed-storybook` | +| `-c`, `--config-dir [dir-name]` | Directory where to load Storybook configurations from
`storybook build -c .storybook` | +| `--loglevel [level]` | Controls level of logging during build.
Available options: `silly`, `verbose`, `info` (default), `warn`, `error`, `silent`
`storybook build --loglevel warn` | +| `--quiet` | Suppress verbose build output
`storybook build --quiet` | +| `--debug-webpack` | Display final webpack configurations for debugging purposes
`storybook build --debug-webpack` | +| `--webpack-stats-json` | Write Webpack Stats JSON to disk
`storybook build --webpack-stats-json /my-storybook/webpack-stats` | +| `--docs` | Builds Storybook in documentation mode. Learn more about it in [here](../writing-docs/build-documentation.md#publish-storybooks-documentation)
`storybook build --docs` | +| `--disable-telemetry` | Disables Storybook's telemetry. Learn more about it [here](../configure/telemetry.md).
`storybook build --disable-telemetry` | +| `--test` | Optimize Storybook's production build for performance and tests by removing unnecessary features with the `test` option. Learn more [here](../api/main-config-build.md).
`storybook build --test` | diff --git a/docs/api/main-config-build.md b/docs/api/main-config-build.md index 6ccbe01a5df2..a206662bae4a 100644 --- a/docs/api/main-config-build.md +++ b/docs/api/main-config-build.md @@ -3,3 +3,151 @@ title: 'build' --- Parent: [main.js|ts configuration](./main-config.md) + +Type: `TestBuildConfig` + +Provides configuration options to optimize Storybook's production build output. + +## `test` + +Type: `TestBuildFlags` + +```ts +{ + disableBlocks?: boolean; + disabledAddons?: string[]; + disableMDXEntries?: boolean; + disableAutoDocs?: boolean; + disableDocgen?: boolean; + disableSourcemaps?: boolean; + disableTreeShaking?: boolean; + +} +``` + +Configures Storybook's production builds for performance testing purposes by disabling certain features from the build. When running ' build-storybook ', this feature is enabled by setting the `--test` [flag](./cli-options.md#build). + + + +Enabling these features can cause build or runtime errors with Storybook. We recommend enabling only the features you need for your project. + + + +### `test.disableBlocks` + +Type: `boolean` + +Excludes the `@storybook/blocks` package from the build, which generates automatic documentation with [Docs Blocks](../writing-docs/doc-blocks.md). + + + + + + + +### `test.disabledAddons` + +Type: `string[]` + +Sets the list of addons that will disabled in the build output. + + + + + + + +### `test.disableMDXEntries` + +Type: `boolean` + +Enabling this option removes user-written documentation entries in MDX format from the build. + + + + + + + +### `test.disableAutoDocs` + +Type: `boolean` + +Prevents automatic documentation generated with the [autodocs](../writing-docs/autodocs.md) feature from being included in the build. + + + + + + + +### `test.disableDocgen` + +Type: `boolean` + +Disables [automatic argType](./arg-types.md#automatic-argtype-inference) and component property inference with any of the supported static analysis tools based on the framework you are using. + + + + + + + +### `test.disableSourcemaps` + +Type: `boolean` + +Overrides the default behavior of generating source maps for the build. + + + + + + + +### `test.disableTreeShaking` + +Type: `boolean` + +Disables [tree shaking](https://developer.mozilla.org/en-US/docs/Glossary/Tree_shaking) in the build. + + + + + + diff --git a/docs/configure/overview.md b/docs/configure/overview.md index 965515186fed..ee38fd9a4569 100644 --- a/docs/configure/overview.md +++ b/docs/configure/overview.md @@ -31,22 +31,22 @@ This configuration file is a [preset](../addons/addon-types.md) and, as such, ha -| Configuration element | Description | -| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `stories` | The array of globs that indicates the [location of your story files](#configure-story-loading), relative to `main.js` | -| `staticDirs` | Sets a list of directories of [static files](./images-and-assets.md#serving-static-files-via-storybook-configuration) to be loaded by Storybook
`staticDirs: ['../public']` | -| `addons` | Sets the list of [addons](https://storybook.js.org/integrations) loaded by Storybook
`addons: ['@storybook/addon-essentials']` | -| `typescript` | Configures how Storybook handles [TypeScript files](./typescript.md)
`typescript: { check: false, checkOptions: {} }` | -| `framework` | Configures Storybook based on a set of [framework-specific](./frameworks.md) settings
`framework: { name: '@storybook/svelte-vite', options:{} }` | -| `core` | Configures Storybook's [internal features](../api/main-config-core.md)
`core: { disableTelemetry: true, }` | -| `docs` | Configures Storybook's [auto-generated documentation](../writing-docs/autodocs.md)
`docs: { autodocs: 'tag' }` | -| `features` | Enables Storybook's [additional features](../api/main-config-features.md)
See table below for a list of available features `features: { storyStoreV7: true }` | -| `refs` | Configures [Storybook composition](../sharing/storybook-composition.md)
`refs:{ example: { title: 'ExampleStorybook', url:'https://your-url.com' } }` | -| `logLevel` | Configures Storybook's logs in the browser terminal. Useful for debugging
`logLevel: 'debug'` | -| `webpackFinal` | Customize Storybook's [Webpack](../builders/webpack.md) setup
`webpackFinal: async (config:any) => { return config; }` | -| `viteFinal` | Customize Storybook's Vite setup when using the [vite builder](https://github.com/storybookjs/builder-vite)
`viteFinal: async (config: Vite.InlineConfig, options: Options) => { return config; }` | -| `env` | Defines custom Storybook [environment variables](./environment-variables.md#using-storybook-configuration).
`env: (config) => ({...config, EXAMPLE_VAR: 'Example var' }),` | -| `build` | Optimizes Storybook's production [build](../api/main-config-test.md) for performance by excluding specific features from the bundle. Useful when decreased build times are a priority.
`build:Ā { test: {} }` | +| Configuration element | Description | +| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `stories` | The array of globs that indicates the [location of your story files](#configure-story-loading), relative to `main.js` | +| `staticDirs` | Sets a list of directories of [static files](./images-and-assets.md#serving-static-files-via-storybook-configuration) to be loaded by Storybook
`staticDirs: ['../public']` | +| `addons` | Sets the list of [addons](https://storybook.js.org/integrations) loaded by Storybook
`addons: ['@storybook/addon-essentials']` | +| `typescript` | Configures how Storybook handles [TypeScript files](./typescript.md)
`typescript: { check: false, checkOptions: {} }` | +| `framework` | Configures Storybook based on a set of [framework-specific](./frameworks.md) settings
`framework: { name: '@storybook/svelte-vite', options:{} }` | +| `core` | Configures Storybook's [internal features](../api/main-config-core.md)
`core: { disableTelemetry: true, }` | +| `docs` | Configures Storybook's [auto-generated documentation](../writing-docs/autodocs.md)
`docs: { autodocs: 'tag' }` | +| `features` | Enables Storybook's [additional features](../api/main-config-features.md)
See table below for a list of available features `features: { storyStoreV7: true }` | +| `refs` | Configures [Storybook composition](../sharing/storybook-composition.md)
`refs:{ example: { title: 'ExampleStorybook', url:'https://your-url.com' } }` | +| `logLevel` | Configures Storybook's logs in the browser terminal. Useful for debugging
`logLevel: 'debug'` | +| `webpackFinal` | Customize Storybook's [Webpack](../builders/webpack.md) setup
`webpackFinal: async (config:any) => { return config; }` | +| `viteFinal` | Customize Storybook's Vite setup when using the [vite builder](https://github.com/storybookjs/builder-vite)
`viteFinal: async (config: Vite.InlineConfig, options: Options) => { return config; }` | +| `env` | Defines custom Storybook [environment variables](./environment-variables.md#using-storybook-configuration).
`env: (config) => ({...config, EXAMPLE_VAR: 'Example var' }),` | +| `build` | Optimizes Storybook's production [build](../api/main-config-build.md) for performance by excluding specific features from the bundle. Useful when decreased build times are a priority.
`build:Ā { test: {} }` | ### Feature flags diff --git a/docs/faq.md b/docs/faq.md index 6539f6a3431f..387986d9cfbc 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -344,6 +344,30 @@ We're only covering versions 5.3 and 5.0 as they were important milestones for S | | @storybook/blocks/useOf | [See current documentation](./api/doc-block-useof.md) | Non existing feature or undocumented | Non existing feature or undocumented | | | Stories/Component Story Format | [See current documentation](./api/csf.md) | [See versioned documentation](https://github.com/storybookjs/storybook/tree/release/5.3/docs/src/pages/formats/component-story-format) | Non existing feature or undocumented | | | Stories/StoriesOF format (see note below) | [See current documentation](https://github.com/storybookjs/storybook/blob/main/code/lib/preview-api/docs/storiesOf.md) | [See versioned documentation](https://github.com/storybookjs/storybook/tree/release/5.3/docs/src/pages/formats/storiesof-api) | Non existing feature or undocumented | +| | ArgTypes | [See current documentation](./api/arg-types.md) | Non existing feature or undocumented | Non existing feature or undocumented | +| | `main.js` configuration/Overview | [See current documentation](./api/main-config.md) | Non existing feature or undocumented | Non existing feature or undocumented | +| | `main.js` configuration/framework | [See current documentation](./api/main-config-framework.md) | Non existing feature or undocumented | Non existing feature or undocumented | +| | `main.js` configuration/stories | [See current documentation](./api/main-config-stories.md) | Non existing feature or undocumented | Non existing feature or undocumented | +| | `main.js` configuration/addons | [See current documentation](./api/main-config-addons.md) | Non existing feature or undocumented | Non existing feature or undocumented | +| | `main.js` configuration/babel | [See current documentation](./api/main-config-babel.md) | Non existing feature or undocumented | Non existing feature or undocumented | +| | `main.js` configuration/babelDefault | [See current documentation](./api/main-config-babel-default.md) | Non existing feature or undocumented | Non existing feature or undocumented | +| | `main.js` configuration/build | [See current documentation](./api/main-config-build.md) | Non existing feature or undocumented | Non existing feature or undocumented | +| | `main.js` configuration/core | [See current documentation](./api/main-config-core.md) | Non existing feature or undocumented | Non existing feature or undocumented | +| | `main.js` configuration/docs | [See current documentation](./api/main-config-docs.md) | Non existing feature or undocumented | Non existing feature or undocumented | +| | `main.js` configuration/env | [See current documentation](./api/main-config-env.md) | Non existing feature or undocumented | Non existing feature or undocumented | +| | `main.js` configuration/features | [See current documentation](./api/main-config-features.md) | Non existing feature or undocumented | Non existing feature or undocumented | +| | `main.js` configuration/indexers | [See current documentation](./api/main-config-indexers.md) | Non existing feature or undocumented | Non existing feature or undocumented | +| | `main.js` configuration/logLevel | [See current documentation](./api/main-config-log-level.md) | Non existing feature or undocumented | Non existing feature or undocumented | +| | `main.js` configuration/managerHead | [See current documentation](./api/main-config-manager-head.md) | Non existing feature or undocumented | Non existing feature or undocumented | +| | `main.js` configuration/previewAnnotations | [See current documentation](./api/main-config-preview-annotations.md) | Non existing feature or undocumented | Non existing feature or undocumented | +| | `main.js` configuration/previewBody | [See current documentation](./api/main-config-preview-body.md) | Non existing feature or undocumented | Non existing feature or undocumented | +| | `main.js` configuration/previewHead | [See current documentation](./api/main-config-preview-head.md) | Non existing feature or undocumented | Non existing feature or undocumented | +| | `main.js` configuration/refs | [See current documentation](./api/main-config-refs.md) | Non existing feature or undocumented | Non existing feature or undocumented | +| | `main.js` configuration/staticDirs | [See current documentation](./api/main-config-static-dirs.md) | Non existing feature or undocumented | Non existing feature or undocumented | +| | `main.js` configuration/typescript | [See current documentation](./api/main-config-typescript.md) | Non existing feature or undocumented | Non existing feature or undocumented | +| | `main.js` configuration/viteFinal | [See current documentation](./api/main-config-vite-final.md) | Non existing feature or undocumented | Non existing feature or undocumented | +| | `main.js` configuration/webpackFinal | [See current documentation](./api/main-config-webpack-final.md) | Non existing feature or undocumented | Non existing feature or undocumented | +| | `main.js` configuration/config | [See current documentation](./api/main-config-config.md) | Non existing feature or undocumented | Non existing feature or undocumented | | | Frameworks | [See current documentation](./api/new-frameworks.md) | Non existing feature or undocumented | Non existing feature or undocumented | | | CLI options | [See current documentation](./api/cli-options.md) | [See versioned documentation](https://github.com/storybookjs/storybook/tree/release/5.3/docs/src/pages/configurations/cli-options) | [See versioned documentation](https://github.com/storybookjs/storybook/tree/release/5.0/docs/src/pages/configurations/cli-options) | diff --git a/docs/sharing/publish-storybook.md b/docs/sharing/publish-storybook.md index a4c214128205..cf6b20b2e1bf 100644 --- a/docs/sharing/publish-storybook.md +++ b/docs/sharing/publish-storybook.md @@ -50,15 +50,21 @@ Storybook will create a static web application capable of being served by any we -### Customizing the build for for performance +### Customizing the build for performance -By default, Storybook's production build will encapsulate all stories and documentation into the published bundle. This is great for small projects, but can cause performance issues for larger projects or when decreased build times are a priority. If you +By default, Storybook's production build will encapsulate all stories and documentation into the production bundle. This is ideal for small projects but can cause performance issues for larger projects or when decreased build times are a priority (e.g., testing, CI/CD). If you need, you can customize the production build with the [`test` option](../api/main-config-build.md#test) in your `main.js|ts` configuration file and adjust your build script to enable the optimizations with the `--test` [flag](../api/cli-options.md#build). - + -. To optimize Storybook's production build for performance and tests, you can remove unnecessary features with the `test` option. Learn more [here](../api/main-config-test.md). + ## Publish Storybook with Chromatic diff --git a/docs/snippets/common/main-config-test-disable-autodocs.js.mdx b/docs/snippets/common/main-config-test-disable-autodocs.js.mdx new file mode 100644 index 000000000000..86b7de8fb7b3 --- /dev/null +++ b/docs/snippets/common/main-config-test-disable-autodocs.js.mdx @@ -0,0 +1,14 @@ +```js +// .storybook/main.js + +export default { + // Replace your-framework with the framework you are using (e.g., react-webpack5, vue3-vite) + framework: '@storybook/your-framework', + stories: ['../src/**/*.mdx', '../src/**/*.stories.@(js|jsx|mjs|ts|tsx)'], + build: { + test: { + disableAutoDocs: true, + }, + }, +}; +``` diff --git a/docs/snippets/common/main-config-test-disable-autodocs.ts.mdx b/docs/snippets/common/main-config-test-disable-autodocs.ts.mdx new file mode 100644 index 000000000000..1eb9e7218197 --- /dev/null +++ b/docs/snippets/common/main-config-test-disable-autodocs.ts.mdx @@ -0,0 +1,18 @@ +```ts +// .storybook/main.ts + +// Replace your-framework with the framework you are using (e.g., react-webpack5, vue3-vite) +import type { StorybookConfig } from '@storybook/your-framework'; + +const config: StorybookConfig = { + framework: '@storybook/your-framework', + stories: ['../src/**/*.mdx', '../src/**/*.stories.@(js|jsx|mjs|ts|tsx)'], + build: { + test: { + disableAutoDocs: true, + }, + }, +}; + +export default config; +``` diff --git a/docs/snippets/common/main-config-test-disable-blocks.js.mdx b/docs/snippets/common/main-config-test-disable-blocks.js.mdx new file mode 100644 index 000000000000..9b4aa8c9a478 --- /dev/null +++ b/docs/snippets/common/main-config-test-disable-blocks.js.mdx @@ -0,0 +1,14 @@ +```js +// .storybook/main.js + +export default { + // Replace your-framework with the framework you are using (e.g., react-webpack5, vue3-vite) + framework: '@storybook/your-framework', + stories: ['../src/**/*.mdx', '../src/**/*.stories.@(js|jsx|mjs|ts|tsx)'], + build: { + test: { + disableBlocks: true, + }, + }, +}; +``` diff --git a/docs/snippets/common/main-config-test-disable-blocks.ts.mdx b/docs/snippets/common/main-config-test-disable-blocks.ts.mdx new file mode 100644 index 000000000000..0cb4b4235bba --- /dev/null +++ b/docs/snippets/common/main-config-test-disable-blocks.ts.mdx @@ -0,0 +1,18 @@ +```ts +// .storybook/main.ts + +// Replace your-framework with the framework you are using (e.g., react-webpack5, vue3-vite) +import type { StorybookConfig } from '@storybook/your-framework'; + +const config: StorybookConfig = { + framework: '@storybook/your-framework', + stories: ['../src/**/*.mdx', '../src/**/*.stories.@(js|jsx|mjs|ts|tsx)'], + build: { + test: { + disableBlocks: true, + }, + }, +}; + +export default config; +``` diff --git a/docs/snippets/common/main-config-test-disable-disableaddons.js.mdx b/docs/snippets/common/main-config-test-disable-disableaddons.js.mdx new file mode 100644 index 000000000000..62edb30799b6 --- /dev/null +++ b/docs/snippets/common/main-config-test-disable-disableaddons.js.mdx @@ -0,0 +1,20 @@ +```js +// .storybook/main.js + +export default { + // Replace your-framework with the framework you are using (e.g., react-webpack5, vue3-vite) + framework: '@storybook/your-framework', + stories: ['../src/**/*.mdx', '../src/**/*.stories.@(js|jsx|mjs|ts|tsx)'], + addons: [ + '@storybook/addon-links', + '@storybook/addon-essentials', + '@storybook/addon-interactions', + '@storybook/addon-a11y', + ], + build: { + test: { + disabledAddons: ['@storybook/addon-a11y'], + }, + }, +}; +``` diff --git a/docs/snippets/common/main-config-test-disable-disableaddons.ts.mdx b/docs/snippets/common/main-config-test-disable-disableaddons.ts.mdx new file mode 100644 index 000000000000..eb05b42ec95c --- /dev/null +++ b/docs/snippets/common/main-config-test-disable-disableaddons.ts.mdx @@ -0,0 +1,24 @@ +```ts +// .storybook/main.ts + +// Replace your-framework with the framework you are using (e.g., react-webpack5, vue3-vite) +import type { StorybookConfig } from '@storybook/your-framework'; + +const config: StorybookConfig = { + framework: '@storybook/your-framework', + stories: ['../src/**/*.mdx', '../src/**/*.stories.@(js|jsx|mjs|ts|tsx)'], + addons: [ + '@storybook/addon-links', + '@storybook/addon-essentials', + '@storybook/addon-interactions', + '@storybook/addon-a11y', + ], + build: { + test: { + disabledAddons: ['@storybook/addon-a11y'], + }, + }, +}; + +export default config; +``` diff --git a/docs/snippets/common/main-config-test-disable-docgen.js.mdx b/docs/snippets/common/main-config-test-disable-docgen.js.mdx new file mode 100644 index 000000000000..ffe4bdc2f866 --- /dev/null +++ b/docs/snippets/common/main-config-test-disable-docgen.js.mdx @@ -0,0 +1,14 @@ +```js +// .storybook/main.js + +export default { + // Replace your-framework with the framework you are using (e.g., react-webpack5, vue3-vite) + framework: '@storybook/your-framework', + stories: ['../src/**/*.mdx', '../src/**/*.stories.@(js|jsx|mjs|ts|tsx)'], + build: { + test: { + disableDocgen: true, + }, + }, +}; +``` diff --git a/docs/snippets/common/main-config-test-disable-docgen.ts.mdx b/docs/snippets/common/main-config-test-disable-docgen.ts.mdx new file mode 100644 index 000000000000..1d0eb3c10d9d --- /dev/null +++ b/docs/snippets/common/main-config-test-disable-docgen.ts.mdx @@ -0,0 +1,18 @@ +```ts +// .storybook/main.ts + +// Replace your-framework with the framework you are using (e.g., react-webpack5, vue3-vite) +import type { StorybookConfig } from '@storybook/your-framework'; + +const config: StorybookConfig = { + framework: '@storybook/your-framework', + stories: ['../src/**/*.mdx', '../src/**/*.stories.@(js|jsx|mjs|ts|tsx)'], + build: { + test: { + disableDocgen: true, + }, + }, +}; + +export default config; +``` diff --git a/docs/snippets/common/main-config-test-disable-mdx.js.mdx b/docs/snippets/common/main-config-test-disable-mdx.js.mdx new file mode 100644 index 000000000000..f6204594c1ef --- /dev/null +++ b/docs/snippets/common/main-config-test-disable-mdx.js.mdx @@ -0,0 +1,14 @@ +```js +// .storybook/main.js + +export default { + // Replace your-framework with the framework you are using (e.g., react-webpack5, vue3-vite) + framework: '@storybook/your-framework', + stories: ['../src/**/*.mdx', '../src/**/*.stories.@(js|jsx|mjs|ts|tsx)'], + build: { + test: { + disableMDXEntries: true, + }, + }, +}; +``` diff --git a/docs/snippets/common/main-config-test-disable-mdx.ts.mdx b/docs/snippets/common/main-config-test-disable-mdx.ts.mdx new file mode 100644 index 000000000000..e5327602aed8 --- /dev/null +++ b/docs/snippets/common/main-config-test-disable-mdx.ts.mdx @@ -0,0 +1,18 @@ +```ts +// .storybook/main.ts + +// Replace your-framework with the framework you are using (e.g., react-webpack5, vue3-vite) +import type { StorybookConfig } from '@storybook/your-framework'; + +const config: StorybookConfig = { + framework: '@storybook/your-framework', + stories: ['../src/**/*.mdx', '../src/**/*.stories.@(js|jsx|mjs|ts|tsx)'], + build: { + test: { + disableMDXEntries: true, + }, + }, +}; + +export default config; +``` diff --git a/docs/snippets/common/main-config-test-disable-sourcemaps.js.mdx b/docs/snippets/common/main-config-test-disable-sourcemaps.js.mdx new file mode 100644 index 000000000000..9207b9317099 --- /dev/null +++ b/docs/snippets/common/main-config-test-disable-sourcemaps.js.mdx @@ -0,0 +1,14 @@ +```js +// .storybook/main.js + +export default { + // Replace your-framework with the framework you are using (e.g., react-webpack5, vue3-vite) + framework: '@storybook/your-framework', + stories: ['../src/**/*.mdx', '../src/**/*.stories.@(js|jsx|mjs|ts|tsx)'], + build: { + test: { + disableSourcemaps: true, + }, + }, +}; +``` diff --git a/docs/snippets/common/main-config-test-disable-sourcemaps.ts.mdx b/docs/snippets/common/main-config-test-disable-sourcemaps.ts.mdx new file mode 100644 index 000000000000..79b0abab693d --- /dev/null +++ b/docs/snippets/common/main-config-test-disable-sourcemaps.ts.mdx @@ -0,0 +1,18 @@ +```ts +// .storybook/main.ts + +// Replace your-framework with the framework you are using (e.g., react-webpack5, vue3-vite) +import type { StorybookConfig } from '@storybook/your-framework'; + +const config: StorybookConfig = { + framework: '@storybook/your-framework', + stories: ['../src/**/*.mdx', '../src/**/*.stories.@(js|jsx|mjs|ts|tsx)'], + build: { + test: { + disableSourcemaps: true, + }, + }, +}; + +export default config; +``` diff --git a/docs/snippets/common/main-config-test-disable-treeshaking.js.mdx b/docs/snippets/common/main-config-test-disable-treeshaking.js.mdx new file mode 100644 index 000000000000..f0957f7e5536 --- /dev/null +++ b/docs/snippets/common/main-config-test-disable-treeshaking.js.mdx @@ -0,0 +1,14 @@ +```js +// .storybook/main.js + +export default { + // Replace your-framework with the framework you are using (e.g., react-webpack5, vue3-vite) + framework: '@storybook/your-framework', + stories: ['../src/**/*.mdx', '../src/**/*.stories.@(js|jsx|mjs|ts|tsx)'], + build: { + test: { + disableTreeShaking: true, + }, + }, +}; +``` diff --git a/docs/snippets/common/main-config-test-disable-treeshaking.ts.mdx b/docs/snippets/common/main-config-test-disable-treeshaking.ts.mdx new file mode 100644 index 000000000000..b053cfa03435 --- /dev/null +++ b/docs/snippets/common/main-config-test-disable-treeshaking.ts.mdx @@ -0,0 +1,18 @@ +```ts +// .storybook/main.ts + +// Replace your-framework with the framework you are using (e.g., react-webpack5, vue3-vite) +import type { StorybookConfig } from '@storybook/your-framework'; + +const config: StorybookConfig = { + framework: '@storybook/your-framework', + stories: ['../src/**/*.mdx', '../src/**/*.stories.@(js|jsx|mjs|ts|tsx)'], + build: { + test: { + disableTreeShaking: true, + }, + }, +}; + +export default config; +``` diff --git a/docs/snippets/common/storybook-build-test-flag.npm.js.mdx b/docs/snippets/common/storybook-build-test-flag.npm.js.mdx new file mode 100644 index 000000000000..202b2cdb3188 --- /dev/null +++ b/docs/snippets/common/storybook-build-test-flag.npm.js.mdx @@ -0,0 +1,3 @@ +```shell +npm run build-storybook -- --test +``` diff --git a/docs/snippets/common/storybook-build-test-flag.pnpm.js.mdx b/docs/snippets/common/storybook-build-test-flag.pnpm.js.mdx new file mode 100644 index 000000000000..ae1a481577d1 --- /dev/null +++ b/docs/snippets/common/storybook-build-test-flag.pnpm.js.mdx @@ -0,0 +1,3 @@ +```shell +pnpm run build-storybook --test +``` diff --git a/docs/snippets/common/storybook-build-test-flag.yarn.js.mdx b/docs/snippets/common/storybook-build-test-flag.yarn.js.mdx new file mode 100644 index 000000000000..cb2007d3e8b8 --- /dev/null +++ b/docs/snippets/common/storybook-build-test-flag.yarn.js.mdx @@ -0,0 +1,3 @@ +```shell +yarn build-storybook --test +``` From 8aad2aae9efa0cb52971d5fa5cb7fca23aa80ff5 Mon Sep 17 00:00:00 2001 From: Kyrylo Shmidt <119138536+kshmidt-digma@users.noreply.github.com> Date: Mon, 20 Nov 2023 04:20:33 +0100 Subject: [PATCH 093/170] Update design-integrations.md Update link to the actual version of addon --- docs/sharing/design-integrations.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/sharing/design-integrations.md b/docs/sharing/design-integrations.md index d2211a7b52d9..ca0842f18b10 100644 --- a/docs/sharing/design-integrations.md +++ b/docs/sharing/design-integrations.md @@ -57,7 +57,7 @@ Once they're connected, you'll be able to view the story by clicking the link in ### Embed Figma in Storybook with the addon -[Design addon](https://storybook.js.org/addons/storybook-addon-designs) allows you to embed Figma files and prototypes in Storybook. +[Designs addon](https://storybook.js.org/addons/@storybook/addon-designs) allows you to embed Figma files and prototypes in Storybook. ![Storybook addon figma](./storybook-figma-addon.png) From 0dbb047163aece968ebedb034d81f7f458e9f0aa Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Wed, 15 Nov 2023 12:58:04 +0100 Subject: [PATCH 094/170] Next.js: Add experimental SWC support --- .../src/preview/iframe-webpack.config.ts | 107 ++-------- code/frameworks/nextjs/package.json | 12 +- code/frameworks/nextjs/src/css/webpack.ts | 3 + .../src/font/webpack/configureNextFont.ts | 30 +-- .../local/get-font-face-declarations.ts | 5 +- .../loader/storybook-nextjs-font-loader.ts | 22 ++- code/frameworks/nextjs/src/preset.ts | 14 +- code/frameworks/nextjs/src/swc/loader.ts | 77 ++++++++ .../nextjs/src/swc/next-swc-loader-patch.ts | 184 ++++++++++++++++++ code/lib/core-webpack/package.json | 1 + code/lib/core-webpack/src/index.ts | 1 + code/lib/core-webpack/src/types.ts | 6 + .../src/virtual-module-mapping.ts | 111 +++++++++++ code/yarn.lock | 97 ++++----- 14 files changed, 507 insertions(+), 163 deletions(-) create mode 100644 code/frameworks/nextjs/src/swc/loader.ts create mode 100644 code/frameworks/nextjs/src/swc/next-swc-loader-patch.ts create mode 100644 code/lib/core-webpack/src/virtual-module-mapping.ts diff --git a/code/builders/builder-webpack5/src/preview/iframe-webpack.config.ts b/code/builders/builder-webpack5/src/preview/iframe-webpack.config.ts index 3cea0d84fc7a..ad8fe95f4b39 100644 --- a/code/builders/builder-webpack5/src/preview/iframe-webpack.config.ts +++ b/code/builders/builder-webpack5/src/preview/iframe-webpack.config.ts @@ -1,4 +1,4 @@ -import { dirname, isAbsolute, join, resolve } from 'path'; +import { dirname, join, resolve } from 'path'; import { DefinePlugin, HotModuleReplacementPlugin, ProgressPlugin, ProvidePlugin } from 'webpack'; import type { Configuration } from 'webpack'; import HtmlWebpackPlugin from 'html-webpack-plugin'; @@ -7,25 +7,20 @@ import CaseSensitivePathsPlugin from 'case-sensitive-paths-webpack-plugin'; import TerserWebpackPlugin from 'terser-webpack-plugin'; import VirtualModulePlugin from 'webpack-virtual-modules'; import ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin'; -import slash from 'slash'; import type { TransformOptions as EsbuildOptions } from 'esbuild'; import type { JsMinifyOptions as SwcOptions } from '@swc/core'; -import type { Options, CoreConfig, DocsOptions, PreviewAnnotation } from '@storybook/types'; +import type { Options, CoreConfig, DocsOptions } from '@storybook/types'; import { globalsNameReferenceMap } from '@storybook/preview/globals'; import { getBuilderOptions, - getRendererName, stringifyProcessEnvs, - handlebars, - interpolate, normalizeStories, - readTemplate, - loadPreviewOrConfigFile, isPreservingSymlinks, } from '@storybook/core-common'; -import { toRequireContextString, toImportFn } from '@storybook/core-webpack'; +import type { BuilderOptions } from '@storybook/core-webpack'; +import { getVirtualModuleMapping } from '@storybook/core-webpack'; import { dedent } from 'ts-dedent'; -import type { BuilderOptions, TypescriptOptions } from '../types'; +import type { TypescriptOptions } from '../types'; import { createBabelLoader, createSWCLoader } from './loaders'; const getAbsolutePath = (input: I): I => @@ -114,92 +109,6 @@ export default async ( const builderOptions = await getBuilderOptions(options); - const previewAnnotations = [ - ...(await presets.apply('previewAnnotations', [], options)).map( - (entry) => { - // If entry is an object, use the absolute import specifier. - // This is to maintain back-compat with community addons that bundle other addons - // and package managers that "hide" sub dependencies (e.g. pnpm / yarn pnp) - // The vite builder uses the bare import specifier. - if (typeof entry === 'object') { - return entry.absolute; - } - - // TODO: Remove as soon as we drop support for disabled StoryStoreV7 - if (isAbsolute(entry)) { - return entry; - } - - return slash(entry); - } - ), - loadPreviewOrConfigFile(options), - ].filter(Boolean); - - const virtualModuleMapping: Record = {}; - if (features?.storyStoreV7) { - const storiesFilename = 'storybook-stories.js'; - const storiesPath = resolve(join(workingDir, storiesFilename)); - - const needPipelinedImport = !!builderOptions.lazyCompilation && !isProd; - virtualModuleMapping[storiesPath] = toImportFn(stories, { needPipelinedImport }); - const configEntryPath = resolve(join(workingDir, 'storybook-config-entry.js')); - virtualModuleMapping[configEntryPath] = handlebars( - await readTemplate( - require.resolve( - '@storybook/builder-webpack5/templates/virtualModuleModernEntry.js.handlebars' - ) - ), - { - storiesFilename, - previewAnnotations, - } - // We need to double escape `\` for webpack. We may have some in windows paths - ).replace(/\\/g, '\\\\'); - entries.push(configEntryPath); - } else { - const rendererName = await getRendererName(options); - - const rendererInitEntry = resolve(join(workingDir, 'storybook-init-renderer-entry.js')); - virtualModuleMapping[rendererInitEntry] = `import '${slash(rendererName)}';`; - entries.push(rendererInitEntry); - - const entryTemplate = await readTemplate( - join(__dirname, '..', '..', 'templates', 'virtualModuleEntry.template.js') - ); - - previewAnnotations.forEach((previewAnnotationFilename: string | undefined) => { - if (!previewAnnotationFilename) return; - - // Ensure that relative paths end up mapped to a filename in the cwd, so a later import - // of the `previewAnnotationFilename` in the template works. - const entryFilename = previewAnnotationFilename.startsWith('.') - ? `${previewAnnotationFilename.replace(/(\w)(\/|\\)/g, '$1-')}-generated-config-entry.js` - : `${previewAnnotationFilename}-generated-config-entry.js`; - // NOTE: although this file is also from the `dist/cjs` directory, it is actually a ESM - // file, see https://github.com/storybookjs/storybook/pull/16727#issuecomment-986485173 - virtualModuleMapping[entryFilename] = interpolate(entryTemplate, { - previewAnnotationFilename, - }); - entries.push(entryFilename); - }); - if (stories.length > 0) { - const storyTemplate = await readTemplate( - join(__dirname, '..', '..', 'templates', 'virtualModuleStory.template.js') - ); - // NOTE: this file has a `.cjs` extension as it is a CJS file (from `dist/cjs`) and runs - // in the user's webpack mode, which may be strict about the use of require/import. - // See https://github.com/storybookjs/storybook/issues/14877 - const storiesFilename = resolve(join(workingDir, `generated-stories-entry.cjs`)); - virtualModuleMapping[storiesFilename] = interpolate(storyTemplate, { - rendererName, - }) - // Make sure we also replace quotes for this one - .replace("'{{stories}}'", stories.map(toRequireContextString).join(',')); - entries.push(storiesFilename); - } - } - const shouldCheckTs = typescriptOptions.check && !typescriptOptions.skipBabel && !typescriptOptions.skipCompiler; const tsCheckOptions = typescriptOptions.checkOptions || {}; @@ -226,6 +135,12 @@ export default async ( externals['@storybook/blocks'] = '__STORYBOOK_BLOCKS_EMPTY_MODULE__'; } + const virtualModuleMapping = await getVirtualModuleMapping(options); + + Object.keys(virtualModuleMapping).forEach((key) => { + entries.push(key); + }); + return { name: 'preview', mode: isProd ? 'production' : 'development', diff --git a/code/frameworks/nextjs/package.json b/code/frameworks/nextjs/package.json index fab731daf27d..ba32244e8c5d 100644 --- a/code/frameworks/nextjs/package.json +++ b/code/frameworks/nextjs/package.json @@ -36,6 +36,11 @@ "types": "./dist/preset.d.ts", "require": "./dist/preset.js" }, + "./font/webpack/loader/storybook-nextjs-font-loader": { + "types": "./dist/font/webpack/loader/storybook-nextjs-font-loader.d.ts", + "require": "./dist/font/webpack/loader/storybook-nextjs-font-loader.js", + "import": "./dist/font/webpack/loader/storybook-nextjs-font-loader.mjs" + }, "./dist/preview.mjs": "./dist/preview.mjs", "./next-image-loader-stub.js": { "types": "./dist/next-image-loader-stub.d.ts", @@ -83,10 +88,12 @@ "@babel/preset-react": "^7.22.15", "@babel/preset-typescript": "^7.23.2", "@babel/runtime": "^7.23.2", + "@pmmmwh/react-refresh-webpack-plugin": "^0.5.11", "@storybook/addon-actions": "workspace:*", "@storybook/builder-webpack5": "workspace:*", "@storybook/core-common": "workspace:*", "@storybook/core-events": "workspace:*", + "@storybook/core-webpack": "workspace:*", "@storybook/node-logger": "workspace:*", "@storybook/preset-react-webpack": "workspace:*", "@storybook/preview-api": "workspace:*", @@ -117,7 +124,7 @@ "@types/babel__plugin-transform-runtime": "^7", "@types/babel__preset-env": "^7", "@types/loader-utils": "^2.0.5", - "next": "^14.0.0", + "next": "^14.0.2", "typescript": "^4.9.3", "webpack": "^5.65.0" }, @@ -156,7 +163,8 @@ "./src/images/next-future-image.tsx", "./src/images/next-legacy-image.tsx", "./src/images/next-image.tsx", - "./src/font/webpack/loader/storybook-nextjs-font-loader.ts" + "./src/font/webpack/loader/storybook-nextjs-font-loader.ts", + "./src/swc/next-swc-loader-patch.ts" ], "externals": [ "sb-original/next/image", diff --git a/code/frameworks/nextjs/src/css/webpack.ts b/code/frameworks/nextjs/src/css/webpack.ts index 8f5ed1bfcae3..75718527e7dd 100644 --- a/code/frameworks/nextjs/src/css/webpack.ts +++ b/code/frameworks/nextjs/src/css/webpack.ts @@ -34,6 +34,9 @@ export const configureCss = (baseConfig: WebpackConfig, nextConfig: NextConfig): }, require.resolve('postcss-loader'), ], + // We transform the "target.css" files from next.js into Javascript + // for Next.js to support fonts, so it should be ignored by the css-loader. + exclude: /next\/.*\/target.css$/, }; } }); diff --git a/code/frameworks/nextjs/src/font/webpack/configureNextFont.ts b/code/frameworks/nextjs/src/font/webpack/configureNextFont.ts index 47723fed4034..b1e3851611d6 100644 --- a/code/frameworks/nextjs/src/font/webpack/configureNextFont.ts +++ b/code/frameworks/nextjs/src/font/webpack/configureNextFont.ts @@ -1,14 +1,22 @@ import type { Configuration } from 'webpack'; -export function configureNextFont(baseConfig: Configuration) { - baseConfig.plugins = [...(baseConfig.plugins || [])]; - baseConfig.resolveLoader = { - ...baseConfig.resolveLoader, - alias: { - ...baseConfig.resolveLoader?.alias, - 'storybook-nextjs-font-loader': require.resolve( - './font/webpack/loader/storybook-nextjs-font-loader' - ), - }, - }; +export function configureNextFont(baseConfig: Configuration, isSWC?: boolean) { + const fontLoaderPath = require.resolve( + '@storybook/nextjs/font/webpack/loader/storybook-nextjs-font-loader' + ); + + if (isSWC) { + baseConfig.module?.rules?.push({ + test: /next\/.*\/target.css$/, + loader: fontLoaderPath, + }); + } else { + baseConfig.resolveLoader = { + ...baseConfig.resolveLoader, + alias: { + ...baseConfig.resolveLoader?.alias, + 'storybook-nextjs-font-loader': fontLoaderPath, + }, + }; + } } diff --git a/code/frameworks/nextjs/src/font/webpack/loader/local/get-font-face-declarations.ts b/code/frameworks/nextjs/src/font/webpack/loader/local/get-font-face-declarations.ts index 006c7f126f5b..d7d26ae55a37 100644 --- a/code/frameworks/nextjs/src/font/webpack/loader/local/get-font-face-declarations.ts +++ b/code/frameworks/nextjs/src/font/webpack/loader/local/get-font-face-declarations.ts @@ -1,6 +1,7 @@ // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-expect-error import loaderUtils from 'next/dist/compiled/loader-utils3'; +import { getProjectRoot } from '@storybook/core-common'; import path from 'path'; import type { LoaderOptions } from '../types'; @@ -11,7 +12,9 @@ export async function getFontFaceDeclarations(options: LoaderOptions, rootContex const localFontSrc = options.props.src as LocalFontSrc; // Parent folder relative to the root context - const parentFolder = path.dirname(options.filename).replace(rootContext, ''); + const parentFolder = path + .dirname(path.join(getProjectRoot(), options.filename)) + .replace(rootContext, ''); const { validateData } = require('../utils/local-font-utils'); const { weight, style, variable } = validateData('', options.props); diff --git a/code/frameworks/nextjs/src/font/webpack/loader/storybook-nextjs-font-loader.ts b/code/frameworks/nextjs/src/font/webpack/loader/storybook-nextjs-font-loader.ts index 85076ecd7201..8b7c08894f72 100644 --- a/code/frameworks/nextjs/src/font/webpack/loader/storybook-nextjs-font-loader.ts +++ b/code/frameworks/nextjs/src/font/webpack/loader/storybook-nextjs-font-loader.ts @@ -14,18 +14,34 @@ type FontFaceDeclaration = { }; export default async function storybookNextjsFontLoader(this: any) { - const options = this.getOptions() as LoaderOptions; + const loaderOptions = this.getOptions() as LoaderOptions; + let options; + + if (Object.keys(loaderOptions).length > 0) { + // handles Babel mode + options = loaderOptions; + } else { + // handles SWC mode + const importQuery = JSON.parse(this.resourceQuery.slice(1)); + + options = { + filename: importQuery.path, + fontFamily: importQuery.import, + props: importQuery.arguments[0], + source: this.context.replace(this.rootContext, ''), + }; + } // get execution context const rootCtx = this.rootContext; let fontFaceDeclaration: FontFaceDeclaration | undefined; - if (options.source === 'next/font/google' || options.source === '@next/font/google') { + if (options.source.endsWith('next/font/google') || options.source.endsWith('@next/font/google')) { fontFaceDeclaration = await getGoogleFontFaceDeclarations(options); } - if (options.source === 'next/font/local' || options.source === '@next/font/local') { + if (options.source.endsWith('next/font/local') || options.source.endsWith('@next/font/local')) { fontFaceDeclaration = await getLocalFontFaceDeclarations(options, rootCtx); } diff --git a/code/frameworks/nextjs/src/preset.ts b/code/frameworks/nextjs/src/preset.ts index 7b0e150f735a..e4fdd7936fb9 100644 --- a/code/frameworks/nextjs/src/preset.ts +++ b/code/frameworks/nextjs/src/preset.ts @@ -17,6 +17,7 @@ import { configureNextFont } from './font/webpack/configureNextFont'; import nextBabelPreset from './babel/preset'; import { configureNodePolyfills } from './nodePolyfills/webpack'; import { configureAliasing } from './dependency-map'; +import { configureSWCLoader } from './swc/loader'; export const addons: PresetProperty<'addons', StorybookConfig> = [ dirname(require.resolve(join('@storybook/preset-react-webpack', 'package.json'))), @@ -61,7 +62,9 @@ export const core: PresetProperty<'core', StorybookConfig> = async (config, opti name: dirname( require.resolve(join('@storybook/builder-webpack5', 'package.json')) ) as '@storybook/builder-webpack5', - options: typeof framework === 'string' ? {} : framework.options.builder || {}, + options: { + ...(typeof framework === 'string' ? {} : framework.options.builder || {}), + }, }, renderer: dirname(require.resolve(join('@storybook/react', 'package.json'))), }; @@ -135,7 +138,7 @@ export const webpackFinal: StorybookConfig['webpackFinal'] = async (baseConfig, const frameworkOptions = await options.presets.apply<{ options: FrameworkOptions }>( 'frameworkOptions' ); - const { options: { nextConfigPath } = {} } = frameworkOptions; + const { options: { nextConfigPath, builder } = {} } = frameworkOptions; const nextConfig = await configureConfig({ baseConfig, nextConfigPath, @@ -143,7 +146,7 @@ export const webpackFinal: StorybookConfig['webpackFinal'] = async (baseConfig, }); configureAliasing(baseConfig); - configureNextFont(baseConfig); + configureNextFont(baseConfig, builder?.useSWC); configureNextImport(baseConfig); configureRuntimeNextjsVersionResolution(baseConfig); configureImports({ baseConfig, configDir: options.configDir }); @@ -152,5 +155,10 @@ export const webpackFinal: StorybookConfig['webpackFinal'] = async (baseConfig, configureStyledJsx(baseConfig); configureNodePolyfills(baseConfig); + // TODO: In Storybook 8.0, we have to check whether the babel-compiler addon is used. Otherwise, swc should be used. + if (builder?.useSWC) { + await configureSWCLoader(baseConfig, options, nextConfig); + } + return baseConfig; }; diff --git a/code/frameworks/nextjs/src/swc/loader.ts b/code/frameworks/nextjs/src/swc/loader.ts new file mode 100644 index 000000000000..3c235c343f74 --- /dev/null +++ b/code/frameworks/nextjs/src/swc/loader.ts @@ -0,0 +1,77 @@ +import { getProjectRoot } from '@storybook/core-common'; +import { getVirtualModuleMapping } from '@storybook/core-webpack'; +import type { Options } from '@storybook/types'; +import ReactRefreshWebpackPlugin from '@pmmmwh/react-refresh-webpack-plugin'; +import type { NextConfig } from 'next'; +import path from 'path'; +import type { RuleSetRule } from 'webpack'; +import semver from 'semver'; +import { dedent } from 'ts-dedent'; +import { logger } from '@storybook/node-logger'; +import { getNextjsVersion } from '../utils'; + +export const configureSWCLoader = async ( + baseConfig: any, + options: Options, + nextConfig: NextConfig +) => { + const isDevelopment = options.configType !== 'PRODUCTION'; + const version = getNextjsVersion(); + + if (semver.lt(version, '14.0.0')) { + logger.warn( + dedent`You have activated the SWC mode for Next.js, but you are not using Next.js 14.0.0 or higher. + SWC is only supported in Next.js 14.0.0 and higher. + Skipping SWC and using Babel instead. + ` + ); + return; + } + + const dir = getProjectRoot(); + + baseConfig.plugins = [ + ...baseConfig.plugins, + new ReactRefreshWebpackPlugin({ + overlay: { + sockIntegration: 'whm', + }, + }), + ]; + + const virtualModules = await getVirtualModuleMapping(options); + + baseConfig.module.rules = [ + // TODO: Remove filtering in Storybook 8.0 + ...baseConfig.module.rules.filter( + (r: RuleSetRule) => + !(typeof r.use === 'object' && 'loader' in r.use && r.use.loader?.includes('swc-loader')) + ), + { + test: /\.(m?(j|t)sx?)$/, + include: [getProjectRoot()], + exclude: [/(node_modules)/, ...Object.keys(virtualModules)], + use: { + // we use our own patch because we need to remove tracing from the original code + // which is not possible otherwise + loader: require.resolve('./swc/next-swc-loader-patch.js'), + options: { + isServer: false, + rootDir: dir, + pagesDir: `${dir}/pages`, + appDir: `${dir}/apps`, + hasReactRefresh: isDevelopment, + hasServerComponents: true, + nextConfig, + supportedBrowsers: require('next/dist/build/utils').getSupportedBrowsers( + dir, + isDevelopment + ), + swcCacheDir: path.join(dir, nextConfig?.distDir ?? '.next', 'cache', 'swc'), + isServerLayer: false, + bundleTarget: 'default', + }, + }, + }, + ]; +}; diff --git a/code/frameworks/nextjs/src/swc/next-swc-loader-patch.ts b/code/frameworks/nextjs/src/swc/next-swc-loader-patch.ts new file mode 100644 index 000000000000..9fd155951fcd --- /dev/null +++ b/code/frameworks/nextjs/src/swc/next-swc-loader-patch.ts @@ -0,0 +1,184 @@ +// THIS IS A PATCH over the original code from Next 14.0.0 +// we use our own patch because we need to remove tracing from the original code +// which is not possible otherwise + +/* eslint-disable no-restricted-syntax */ +/* +Copyright (c) 2017 The swc Project Developers +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. +*/ + +import type { NextConfig } from 'next'; +import { isWasm, transform } from 'next/dist/build/swc'; +import { getLoaderSWCOptions } from 'next/dist/build/swc/options'; +import path, { isAbsolute } from 'path'; + +export interface SWCLoaderOptions { + rootDir: string; + isServer: boolean; + pagesDir?: string; + appDir?: string; + hasReactRefresh: boolean; + optimizeServerReact?: boolean; + nextConfig: NextConfig; + jsConfig: any; + supportedBrowsers: string[] | undefined; + swcCacheDir: string; + serverComponents?: boolean; + isReactServerLayer?: boolean; +} + +const mockCurrentTraceSpan = { + traceChild: (name: string) => mockCurrentTraceSpan, + traceAsyncFn: async (fn: any) => fn(), +}; + +async function loaderTransform(this: any, parentTrace: any, source?: string, inputSourceMap?: any) { + // Make the loader async + const filename = this.resourcePath; + + const loaderOptions: SWCLoaderOptions = this.getOptions() || {}; + + const { + isServer, + rootDir, + pagesDir, + appDir, + hasReactRefresh, + nextConfig, + jsConfig, + supportedBrowsers, + swcCacheDir, + serverComponents, + isReactServerLayer, + } = loaderOptions; + const isPageFile = filename.startsWith(pagesDir); + const relativeFilePathFromRoot = path.relative(rootDir, filename); + + const swcOptions = getLoaderSWCOptions({ + pagesDir, + appDir, + filename, + isServer, + isPageFile, + development: this.mode === 'development', + hasReactRefresh, + modularizeImports: nextConfig?.modularizeImports, + optimizePackageImports: nextConfig?.experimental?.optimizePackageImports, + swcPlugins: nextConfig?.experimental?.swcPlugins, + compilerOptions: nextConfig?.compiler, + optimizeServerReact: nextConfig?.experimental?.optimizeServerReact, + jsConfig, + supportedBrowsers, + swcCacheDir, + relativeFilePathFromRoot, + serverComponents, + isReactServerLayer, + }); + + const programmaticOptions = { + ...swcOptions, + filename, + inputSourceMap: inputSourceMap ? JSON.stringify(inputSourceMap) : undefined, + + // Set the default sourcemap behavior based on Webpack's mapping flag, + sourceMaps: this.sourceMap, + inlineSourcesContent: this.sourceMap, + + // Ensure that Webpack will get a full absolute path in the sourcemap + // so that it can properly map the module back to its internal cached + // modules. + sourceFileName: filename, + }; + + if (!programmaticOptions.inputSourceMap) { + delete programmaticOptions.inputSourceMap; + } + + // auto detect development mode + if ( + this.mode && + programmaticOptions.jsc && + programmaticOptions.jsc.transform && + programmaticOptions.jsc.transform.react && + !Object.prototype.hasOwnProperty.call(programmaticOptions.jsc.transform.react, 'development') + ) { + programmaticOptions.jsc.transform.react.development = this.mode === 'development'; + } + + const swcSpan = parentTrace.traceChild('next-swc-transform'); + return swcSpan.traceAsyncFn(() => + transform(source as any, programmaticOptions).then((output) => { + if (output.eliminatedPackages && this.eliminatedPackages) { + for (const pkg of JSON.parse(output.eliminatedPackages)) { + this.eliminatedPackages.add(pkg); + } + } + return [output.code, output.map ? JSON.parse(output.map) : undefined]; + }) + ); +} + +const EXCLUDED_PATHS = /[\\/](cache[\\/][^\\/]+\.zip[\\/]node_modules|__virtual__)[\\/]/g; + +export function pitch(this: any) { + const callback = this.async(); + (async () => { + if ( + // TODO: investigate swc file reading in PnP mode? + !process.versions.pnp && + !EXCLUDED_PATHS.test(this.resourcePath) && + this.loaders.length - 1 === this.loaderIndex && + isAbsolute(this.resourcePath) && + !(await isWasm()) + ) { + const loaderSpan = mockCurrentTraceSpan.traceChild('next-swc-loader'); + this.addDependency(this.resourcePath); + return loaderSpan.traceAsyncFn(() => loaderTransform.call(this, loaderSpan)); + } + + return null; + })().then((r) => { + if (r) return callback(null, ...r); + callback(); + return null; + }, callback); +} + +export default function swcLoader(this: any, inputSource: string, inputSourceMap: any) { + const loaderSpan = mockCurrentTraceSpan.traceChild('next-swc-loader'); + const callback = this.async(); + loaderSpan + .traceAsyncFn(() => loaderTransform.call(this, loaderSpan, inputSource, inputSourceMap)) + .then( + ([transformedSource, outputSourceMap]: any) => { + callback(null, transformedSource, outputSourceMap || inputSourceMap); + }, + (err: Error) => { + callback(err); + } + ); +} + +// accept Buffers instead of strings +export const raw = true; diff --git a/code/lib/core-webpack/package.json b/code/lib/core-webpack/package.json index 0b9a988df5d4..fd69a427abbd 100644 --- a/code/lib/core-webpack/package.json +++ b/code/lib/core-webpack/package.json @@ -51,6 +51,7 @@ "ts-dedent": "^2.0.0" }, "devDependencies": { + "slash": "^5.1.0", "typescript": "~4.9.3", "webpack": "5" }, diff --git a/code/lib/core-webpack/src/index.ts b/code/lib/core-webpack/src/index.ts index 370187367538..562860cbe1a6 100644 --- a/code/lib/core-webpack/src/index.ts +++ b/code/lib/core-webpack/src/index.ts @@ -4,3 +4,4 @@ export * from './check-webpack-version'; export * from './merge-webpack-config'; export * from './to-importFn'; export * from './to-require-context'; +export * from './virtual-module-mapping'; diff --git a/code/lib/core-webpack/src/types.ts b/code/lib/core-webpack/src/types.ts index 012b95f41cf6..1028c08a0a4d 100644 --- a/code/lib/core-webpack/src/types.ts +++ b/code/lib/core-webpack/src/types.ts @@ -22,6 +22,12 @@ export interface WebpackConfiguration { devtool?: false | string; } +export type BuilderOptions = { + fsCache?: boolean; + useSWC?: boolean; + lazyCompilation?: boolean; +}; + export type StorybookConfig = StorybookConfigBase & { /** * Modify or return a custom Webpack config after the Storybook's default configuration diff --git a/code/lib/core-webpack/src/virtual-module-mapping.ts b/code/lib/core-webpack/src/virtual-module-mapping.ts new file mode 100644 index 000000000000..ca3b30cd0e6a --- /dev/null +++ b/code/lib/core-webpack/src/virtual-module-mapping.ts @@ -0,0 +1,111 @@ +import type { Options, PreviewAnnotation } from '@storybook/types'; +import { isAbsolute, join, resolve } from 'path'; +import { + getBuilderOptions, + getRendererName, + handlebars, + interpolate, + loadPreviewOrConfigFile, + normalizeStories, + readTemplate, +} from '@storybook/core-common'; +import slash from 'slash'; +import type { BuilderOptions } from './types'; +import { toImportFn } from './to-importFn'; +import { toRequireContextString } from './to-require-context'; + +export const getVirtualModuleMapping = async (options: Options) => { + const virtualModuleMapping: Record = {}; + const builderOptions = await getBuilderOptions(options); + const workingDir = process.cwd(); + const isProd = options.configType === 'PRODUCTION'; + const nonNormalizedStories = await options.presets.apply('stories', []); + + const stories = normalizeStories(nonNormalizedStories, { + configDir: options.configDir, + workingDir, + }); + + const previewAnnotations = [ + ...(await options.presets.apply('previewAnnotations', [], options)).map( + (entry) => { + // If entry is an object, use the absolute import specifier. + // This is to maintain back-compat with community addons that bundle other addons + // and package managers that "hide" sub dependencies (e.g. pnpm / yarn pnp) + // The vite builder uses the bare import specifier. + if (typeof entry === 'object') { + return entry.absolute; + } + + // TODO: Remove as soon as we drop support for disabled StoryStoreV7 + if (isAbsolute(entry)) { + return entry; + } + + return slash(entry); + } + ), + loadPreviewOrConfigFile(options), + ].filter(Boolean); + + if (options.features?.storyStoreV7) { + const storiesFilename = 'storybook-stories.js'; + const storiesPath = resolve(join(workingDir, storiesFilename)); + + const needPipelinedImport = !!builderOptions.lazyCompilation && !isProd; + virtualModuleMapping[storiesPath] = toImportFn(stories, { needPipelinedImport }); + const configEntryPath = resolve(join(workingDir, 'storybook-config-entry.js')); + virtualModuleMapping[configEntryPath] = handlebars( + await readTemplate( + require.resolve( + '@storybook/builder-webpack5/templates/virtualModuleModernEntry.js.handlebars' + ) + ), + { + storiesFilename, + previewAnnotations, + } + // We need to double escape `\` for webpack. We may have some in windows paths + ).replace(/\\/g, '\\\\'); + } else { + const rendererName = await getRendererName(options); + + const rendererInitEntry = resolve(join(workingDir, 'storybook-init-renderer-entry.js')); + virtualModuleMapping[rendererInitEntry] = `import '${slash(rendererName)}';`; + + const entryTemplate = await readTemplate( + join(__dirname, '..', '..', 'templates', 'virtualModuleEntry.template.js') + ); + + previewAnnotations.forEach((previewAnnotationFilename: string | undefined) => { + if (!previewAnnotationFilename) return; + + // Ensure that relative paths end up mapped to a filename in the cwd, so a later import + // of the `previewAnnotationFilename` in the template works. + const entryFilename = previewAnnotationFilename.startsWith('.') + ? `${previewAnnotationFilename.replace(/(\w)(\/|\\)/g, '$1-')}-generated-config-entry.js` + : `${previewAnnotationFilename}-generated-config-entry.js`; + // NOTE: although this file is also from the `dist/cjs` directory, it is actually a ESM + // file, see https://github.com/storybookjs/storybook/pull/16727#issuecomment-986485173 + virtualModuleMapping[entryFilename] = interpolate(entryTemplate, { + previewAnnotationFilename, + }); + }); + if (stories.length > 0) { + const storyTemplate = await readTemplate( + join(__dirname, '..', '..', 'templates', 'virtualModuleStory.template.js') + ); + // NOTE: this file has a `.cjs` extension as it is a CJS file (from `dist/cjs`) and runs + // in the user's webpack mode, which may be strict about the use of require/import. + // See https://github.com/storybookjs/storybook/issues/14877 + const storiesFilename = resolve(join(workingDir, `generated-stories-entry.cjs`)); + virtualModuleMapping[storiesFilename] = interpolate(storyTemplate, { + rendererName, + }) + // Make sure we also replace quotes for this one + .replace("'{{stories}}'", stories.map(toRequireContextString).join(',')); + } + } + + return virtualModuleMapping; +}; diff --git a/code/yarn.lock b/code/yarn.lock index 3999f341dbe2..26430758888f 100644 --- a/code/yarn.lock +++ b/code/yarn.lock @@ -4031,72 +4031,72 @@ __metadata: languageName: node linkType: hard -"@next/env@npm:14.0.0": - version: 14.0.0 - resolution: "@next/env@npm:14.0.0" - checksum: c43e81dbd162a29a4b380342e416209d69d731e8ced7688d09668ec8196f543e358ed65adad81a26e943c63a293d7a018552f8389b6b1ac95cd0f63f4ef257c0 +"@next/env@npm:14.0.2": + version: 14.0.2 + resolution: "@next/env@npm:14.0.2" + checksum: 9fad703ce13b7b7fecf898d3c239f8976f2ec7f3c7c461c06da70898a0221775c48e1a2e2c76740216c4093c2db9bd7adaacd196586cd4283e09eb89de4c1db6 languageName: node linkType: hard -"@next/swc-darwin-arm64@npm:14.0.0": - version: 14.0.0 - resolution: "@next/swc-darwin-arm64@npm:14.0.0" +"@next/swc-darwin-arm64@npm:14.0.2": + version: 14.0.2 + resolution: "@next/swc-darwin-arm64@npm:14.0.2" conditions: os=darwin & cpu=arm64 languageName: node linkType: hard -"@next/swc-darwin-x64@npm:14.0.0": - version: 14.0.0 - resolution: "@next/swc-darwin-x64@npm:14.0.0" +"@next/swc-darwin-x64@npm:14.0.2": + version: 14.0.2 + resolution: "@next/swc-darwin-x64@npm:14.0.2" conditions: os=darwin & cpu=x64 languageName: node linkType: hard -"@next/swc-linux-arm64-gnu@npm:14.0.0": - version: 14.0.0 - resolution: "@next/swc-linux-arm64-gnu@npm:14.0.0" +"@next/swc-linux-arm64-gnu@npm:14.0.2": + version: 14.0.2 + resolution: "@next/swc-linux-arm64-gnu@npm:14.0.2" conditions: os=linux & cpu=arm64 & libc=glibc languageName: node linkType: hard -"@next/swc-linux-arm64-musl@npm:14.0.0": - version: 14.0.0 - resolution: "@next/swc-linux-arm64-musl@npm:14.0.0" +"@next/swc-linux-arm64-musl@npm:14.0.2": + version: 14.0.2 + resolution: "@next/swc-linux-arm64-musl@npm:14.0.2" conditions: os=linux & cpu=arm64 & libc=musl languageName: node linkType: hard -"@next/swc-linux-x64-gnu@npm:14.0.0": - version: 14.0.0 - resolution: "@next/swc-linux-x64-gnu@npm:14.0.0" +"@next/swc-linux-x64-gnu@npm:14.0.2": + version: 14.0.2 + resolution: "@next/swc-linux-x64-gnu@npm:14.0.2" conditions: os=linux & cpu=x64 & libc=glibc languageName: node linkType: hard -"@next/swc-linux-x64-musl@npm:14.0.0": - version: 14.0.0 - resolution: "@next/swc-linux-x64-musl@npm:14.0.0" +"@next/swc-linux-x64-musl@npm:14.0.2": + version: 14.0.2 + resolution: "@next/swc-linux-x64-musl@npm:14.0.2" conditions: os=linux & cpu=x64 & libc=musl languageName: node linkType: hard -"@next/swc-win32-arm64-msvc@npm:14.0.0": - version: 14.0.0 - resolution: "@next/swc-win32-arm64-msvc@npm:14.0.0" +"@next/swc-win32-arm64-msvc@npm:14.0.2": + version: 14.0.2 + resolution: "@next/swc-win32-arm64-msvc@npm:14.0.2" conditions: os=win32 & cpu=arm64 languageName: node linkType: hard -"@next/swc-win32-ia32-msvc@npm:14.0.0": - version: 14.0.0 - resolution: "@next/swc-win32-ia32-msvc@npm:14.0.0" +"@next/swc-win32-ia32-msvc@npm:14.0.2": + version: 14.0.2 + resolution: "@next/swc-win32-ia32-msvc@npm:14.0.2" conditions: os=win32 & cpu=ia32 languageName: node linkType: hard -"@next/swc-win32-x64-msvc@npm:14.0.0": - version: 14.0.0 - resolution: "@next/swc-win32-x64-msvc@npm:14.0.0" +"@next/swc-win32-x64-msvc@npm:14.0.2": + version: 14.0.2 + resolution: "@next/swc-win32-x64-msvc@npm:14.0.2" conditions: os=win32 & cpu=x64 languageName: node linkType: hard @@ -6490,6 +6490,7 @@ __metadata: "@storybook/node-logger": "workspace:*" "@storybook/types": "workspace:*" "@types/node": "npm:^18.0.0" + slash: "npm:^5.1.0" ts-dedent: "npm:^2.0.0" typescript: "npm:~4.9.3" webpack: "npm:5" @@ -6853,10 +6854,12 @@ __metadata: "@babel/preset-typescript": "npm:^7.23.2" "@babel/runtime": "npm:^7.23.2" "@babel/types": "npm:^7.23.0" + "@pmmmwh/react-refresh-webpack-plugin": "npm:^0.5.11" "@storybook/addon-actions": "workspace:*" "@storybook/builder-webpack5": "workspace:*" "@storybook/core-common": "workspace:*" "@storybook/core-events": "workspace:*" + "@storybook/core-webpack": "workspace:*" "@storybook/node-logger": "workspace:*" "@storybook/preset-react-webpack": "workspace:*" "@storybook/preview-api": "workspace:*" @@ -6871,7 +6874,7 @@ __metadata: fs-extra: "npm:^11.1.0" image-size: "npm:^1.0.0" loader-utils: "npm:^3.2.1" - next: "npm:^14.0.0" + next: "npm:^14.0.2" node-polyfill-webpack-plugin: "npm:^2.0.1" pnp-webpack-plugin: "npm:^1.7.0" postcss: "npm:^8.4.21" @@ -22777,20 +22780,20 @@ __metadata: languageName: node linkType: hard -"next@npm:^14.0.0": - version: 14.0.0 - resolution: "next@npm:14.0.0" +"next@npm:^14.0.2": + version: 14.0.2 + resolution: "next@npm:14.0.2" dependencies: - "@next/env": "npm:14.0.0" - "@next/swc-darwin-arm64": "npm:14.0.0" - "@next/swc-darwin-x64": "npm:14.0.0" - "@next/swc-linux-arm64-gnu": "npm:14.0.0" - "@next/swc-linux-arm64-musl": "npm:14.0.0" - "@next/swc-linux-x64-gnu": "npm:14.0.0" - "@next/swc-linux-x64-musl": "npm:14.0.0" - "@next/swc-win32-arm64-msvc": "npm:14.0.0" - "@next/swc-win32-ia32-msvc": "npm:14.0.0" - "@next/swc-win32-x64-msvc": "npm:14.0.0" + "@next/env": "npm:14.0.2" + "@next/swc-darwin-arm64": "npm:14.0.2" + "@next/swc-darwin-x64": "npm:14.0.2" + "@next/swc-linux-arm64-gnu": "npm:14.0.2" + "@next/swc-linux-arm64-musl": "npm:14.0.2" + "@next/swc-linux-x64-gnu": "npm:14.0.2" + "@next/swc-linux-x64-musl": "npm:14.0.2" + "@next/swc-win32-arm64-msvc": "npm:14.0.2" + "@next/swc-win32-ia32-msvc": "npm:14.0.2" + "@next/swc-win32-x64-msvc": "npm:14.0.2" "@swc/helpers": "npm:0.5.2" busboy: "npm:1.6.0" caniuse-lite: "npm:^1.0.30001406" @@ -22828,7 +22831,7 @@ __metadata: optional: true bin: next: dist/bin/next - checksum: cfb18a72d6e1d875efb1bb3806f9a06551f482c5cb87231e77e179a71d26f3d43700290988ad27e739302bfa7ff8ac8081aafd5456c39a2819fdd315617e5acf + checksum: 65ae7a09f1643bc3deafdbdae9ce0c02326346c4a60a7c739f8f6b154b2226b8fcc5efb984cdcb4ef100116910d4c1013089135800d30c7a50cf98c9d22e5a26 languageName: node linkType: hard @@ -27519,7 +27522,7 @@ __metadata: languageName: node linkType: hard -"slash@npm:^5.0.0": +"slash@npm:^5.0.0, slash@npm:^5.1.0": version: 5.1.0 resolution: "slash@npm:5.1.0" checksum: eb48b815caf0bdc390d0519d41b9e0556a14380f6799c72ba35caf03544d501d18befdeeef074bc9c052acf69654bc9e0d79d7f1de0866284137a40805299eb3 From eaa373f5894168ba5603c4b69051f9e7b8af5fed Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Wed, 15 Nov 2023 16:12:10 +0100 Subject: [PATCH 095/170] Add documentation to Next.js doc --- code/frameworks/nextjs/README.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/code/frameworks/nextjs/README.md b/code/frameworks/nextjs/README.md index 03cc1cbebc62..2a834fb7ee4a 100644 --- a/code/frameworks/nextjs/README.md +++ b/code/frameworks/nextjs/README.md @@ -122,7 +122,12 @@ export default { framework: { // name: '@storybook/react-webpack5', // Remove this name: '@storybook/nextjs', // Add this - options: {}, + options: { + builder: { + // Set useSWC to true if you want to try out the experimental SWC compiler in Next.js >= 14.0.0 + useSWC: true, + }, + }, }, }; ``` From c546fd516723afecbc9d97b4f318bf0497056e1f Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Thu, 16 Nov 2023 09:49:55 +0100 Subject: [PATCH 096/170] Retrigger pipeline From 5021bf4bbbebcfebd5363de6553788d77d06f48f Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Thu, 16 Nov 2023 11:15:36 +0100 Subject: [PATCH 097/170] Move virtualModule files into @storybook/core-webpack --- code/lib/core-webpack/src/virtual-module-mapping.ts | 4 ++-- .../core-webpack}/templates/virtualModuleEntry.template.js | 0 .../core-webpack}/templates/virtualModuleStory.template.js | 0 3 files changed, 2 insertions(+), 2 deletions(-) rename code/{builders/builder-webpack5 => lib/core-webpack}/templates/virtualModuleEntry.template.js (100%) rename code/{builders/builder-webpack5 => lib/core-webpack}/templates/virtualModuleStory.template.js (100%) diff --git a/code/lib/core-webpack/src/virtual-module-mapping.ts b/code/lib/core-webpack/src/virtual-module-mapping.ts index ca3b30cd0e6a..09941ba859a3 100644 --- a/code/lib/core-webpack/src/virtual-module-mapping.ts +++ b/code/lib/core-webpack/src/virtual-module-mapping.ts @@ -74,7 +74,7 @@ export const getVirtualModuleMapping = async (options: Options) => { virtualModuleMapping[rendererInitEntry] = `import '${slash(rendererName)}';`; const entryTemplate = await readTemplate( - join(__dirname, '..', '..', 'templates', 'virtualModuleEntry.template.js') + join(__dirname, '..', 'templates', 'virtualModuleEntry.template.js') ); previewAnnotations.forEach((previewAnnotationFilename: string | undefined) => { @@ -93,7 +93,7 @@ export const getVirtualModuleMapping = async (options: Options) => { }); if (stories.length > 0) { const storyTemplate = await readTemplate( - join(__dirname, '..', '..', 'templates', 'virtualModuleStory.template.js') + join(__dirname, '..', 'templates', 'virtualModuleStory.template.js') ); // NOTE: this file has a `.cjs` extension as it is a CJS file (from `dist/cjs`) and runs // in the user's webpack mode, which may be strict about the use of require/import. diff --git a/code/builders/builder-webpack5/templates/virtualModuleEntry.template.js b/code/lib/core-webpack/templates/virtualModuleEntry.template.js similarity index 100% rename from code/builders/builder-webpack5/templates/virtualModuleEntry.template.js rename to code/lib/core-webpack/templates/virtualModuleEntry.template.js diff --git a/code/builders/builder-webpack5/templates/virtualModuleStory.template.js b/code/lib/core-webpack/templates/virtualModuleStory.template.js similarity index 100% rename from code/builders/builder-webpack5/templates/virtualModuleStory.template.js rename to code/lib/core-webpack/templates/virtualModuleStory.template.js From 115cb7b55bcf10af2322b6f8587197edb52c6d96 Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Thu, 16 Nov 2023 09:49:55 +0100 Subject: [PATCH 098/170] Retrigger pipeline From 19b6bdc16ff1351346f710af73fedfb5260a7739 Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Thu, 16 Nov 2023 09:49:55 +0100 Subject: [PATCH 099/170] Retrigger pipeline From a6a32510a9263fb8ad9ebfd03619121e75f0f8b8 Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Thu, 16 Nov 2023 14:29:55 +0100 Subject: [PATCH 100/170] Use SWC for new Webpack5-based projects (except for Angular and Next.js) --- code/lib/cli/src/generators/baseGenerator.ts | 65 +++++++++++++++----- 1 file changed, 48 insertions(+), 17 deletions(-) diff --git a/code/lib/cli/src/generators/baseGenerator.ts b/code/lib/cli/src/generators/baseGenerator.ts index a7bdb1764668..ddbad146529f 100644 --- a/code/lib/cli/src/generators/baseGenerator.ts +++ b/code/lib/cli/src/generators/baseGenerator.ts @@ -4,7 +4,7 @@ import { dedent } from 'ts-dedent'; import ora from 'ora'; import type { NpmOptions } from '../NpmOptions'; import type { SupportedRenderers, SupportedFrameworks, Builder } from '../project_types'; -import { SupportedLanguage, externalFrameworks, CoreBuilder } from '../project_types'; +import { SupportedLanguage, externalFrameworks, CoreBuilder, ProjectType } from '../project_types'; import { copyTemplateFiles } from '../helpers'; import { configureMain, configurePreview } from './configure'; import type { JsPackageManager } from '../js-package-manager'; @@ -171,6 +171,15 @@ const hasInteractiveStories = (rendererId: SupportedRenderers) => const hasFrameworkTemplates = (framework?: SupportedFrameworks) => ['angular', 'nextjs'].includes(framework); +function shouldUseSWCCompiler(builder: Builder, projectType: ProjectType) { + return ( + builder === CoreBuilder.Webpack5 && + projectType !== ProjectType.ANGULAR && + // TODO: Remove in Storybook 8.0 + projectType !== ProjectType.NEXTJS + ); +} + export async function baseGenerator( packageManager: JsPackageManager, npmOptions: NpmOptions, @@ -194,6 +203,23 @@ export async function baseGenerator( builder = await detectBuilder(packageManager, projectType); } + const useSWC = shouldUseSWCCompiler(builder, projectType); + + const { + packages: frameworkPackages, + type, + rendererId, + framework: frameworkInclude, + builder: builderInclude, + } = getFrameworkDetails( + renderer, + builder, + pnp, + language, + framework, + shouldApplyRequireWrapperOnPackageNames + ); + const { extraAddons: extraAddonPackages, extraPackages, @@ -201,7 +227,6 @@ export async function baseGenerator( addScripts, addMainFile, addComponents, - skipBabel, extraMain, extensions, storybookConfigFolder, @@ -211,20 +236,14 @@ export async function baseGenerator( ...options, }; - const { - packages: frameworkPackages, - type, - rendererId, - framework: frameworkInclude, - builder: builderInclude, - } = getFrameworkDetails( - renderer, - builder, - pnp, - language, - framework, - shouldApplyRequireWrapperOnPackageNames - ); + let { skipBabel } = { + ...defaultOptions, + ...options, + }; + + if (useSWC) { + skipBabel = true; + } const extraAddonsToInstall = typeof extraAddonPackages === 'function' @@ -401,7 +420,19 @@ export async function baseGenerator( : []; await configureMain({ - framework: { name: frameworkInclude, options: options.framework || {} }, + framework: { + name: frameworkInclude, + options: useSWC + ? { + ...(options.framework ?? {}), + builder: { + ...(options.framework?.builder ?? {}), + useSWC: true, + }, + } + : options.framework || {}, + }, + useSWC, prefixes, storybookConfigFolder, docs: { autodocs: 'tag' }, From 3b9fab04d131222031bd8c24cdf99c366eb4a23a Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Thu, 16 Nov 2023 15:31:37 +0100 Subject: [PATCH 101/170] Fix Init for Angular projects --- code/lib/cli/src/generators/ANGULAR/index.ts | 11 ++++------- code/lib/cli/src/generators/baseGenerator.ts | 3 ++- 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/code/lib/cli/src/generators/ANGULAR/index.ts b/code/lib/cli/src/generators/ANGULAR/index.ts index 3c4d9a1f0ca9..03214d299848 100644 --- a/code/lib/cli/src/generators/ANGULAR/index.ts +++ b/code/lib/cli/src/generators/ANGULAR/index.ts @@ -1,8 +1,7 @@ import { join } from 'path'; -import semver from 'semver'; import { baseGenerator } from '../baseGenerator'; import type { Generator } from '../types'; -import { CoreBuilder } from '../../project_types'; +import { CoreBuilder, ProjectType } from '../../project_types'; import { AngularJSON, compoDocPreviewPrefix, promptForCompoDocs } from './helpers'; import { getCliDir } from '../../dirs'; import { paddedLog, copyTemplate } from '../../helpers'; @@ -13,10 +12,6 @@ const generator: Generator<{ projectName: string }> = async ( options, commandOptions ) => { - const angularVersion = await packageManager.getPackageVersion('@angular/core'); - const isWebpack5 = angularVersion && semver.gte(angularVersion, '12.0.0'); - const updatedOptions = isWebpack5 ? { ...options, builder: CoreBuilder.Webpack5 } : options; - const angularJSON = new AngularJSON(); if ( @@ -62,7 +57,9 @@ const generator: Generator<{ projectName: string }> = async ( packageManager, npmOptions, { - ...updatedOptions, + ...options, + builder: CoreBuilder.Webpack5, + projectType: ProjectType.ANGULAR, ...(useCompodoc && { frameworkPreviewParts: { prefix: compoDocPreviewPrefix, diff --git a/code/lib/cli/src/generators/baseGenerator.ts b/code/lib/cli/src/generators/baseGenerator.ts index ddbad146529f..4f94e24a8fb4 100644 --- a/code/lib/cli/src/generators/baseGenerator.ts +++ b/code/lib/cli/src/generators/baseGenerator.ts @@ -172,6 +172,8 @@ const hasFrameworkTemplates = (framework?: SupportedFrameworks) => ['angular', 'nextjs'].includes(framework); function shouldUseSWCCompiler(builder: Builder, projectType: ProjectType) { + console.log({ builder, projectType }); + return ( builder === CoreBuilder.Webpack5 && projectType !== ProjectType.ANGULAR && @@ -432,7 +434,6 @@ export async function baseGenerator( } : options.framework || {}, }, - useSWC, prefixes, storybookConfigFolder, docs: { autodocs: 'tag' }, From d00398821538e10f3b0e2851006889f33d958c11 Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Fri, 17 Nov 2023 10:18:33 +0100 Subject: [PATCH 102/170] Remove console.log --- code/lib/cli/src/generators/baseGenerator.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/code/lib/cli/src/generators/baseGenerator.ts b/code/lib/cli/src/generators/baseGenerator.ts index 4f94e24a8fb4..7a808b103fb8 100644 --- a/code/lib/cli/src/generators/baseGenerator.ts +++ b/code/lib/cli/src/generators/baseGenerator.ts @@ -172,8 +172,6 @@ const hasFrameworkTemplates = (framework?: SupportedFrameworks) => ['angular', 'nextjs'].includes(framework); function shouldUseSWCCompiler(builder: Builder, projectType: ProjectType) { - console.log({ builder, projectType }); - return ( builder === CoreBuilder.Webpack5 && projectType !== ProjectType.ANGULAR && From 5305ee9158413bfa9e6342ff2342d6b4e8de2fa1 Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Fri, 17 Nov 2023 11:45:07 +0100 Subject: [PATCH 103/170] Reposition swc loader order --- code/frameworks/nextjs/src/swc/loader.ts | 1 + .../nextjs/src/swc/next-swc-loader-patch.ts | 11 ++++++++++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/code/frameworks/nextjs/src/swc/loader.ts b/code/frameworks/nextjs/src/swc/loader.ts index 3c235c343f74..615e3ce92b5a 100644 --- a/code/frameworks/nextjs/src/swc/loader.ts +++ b/code/frameworks/nextjs/src/swc/loader.ts @@ -51,6 +51,7 @@ export const configureSWCLoader = async ( test: /\.(m?(j|t)sx?)$/, include: [getProjectRoot()], exclude: [/(node_modules)/, ...Object.keys(virtualModules)], + enforce: 'post', use: { // we use our own patch because we need to remove tracing from the original code // which is not possible otherwise diff --git a/code/frameworks/nextjs/src/swc/next-swc-loader-patch.ts b/code/frameworks/nextjs/src/swc/next-swc-loader-patch.ts index 9fd155951fcd..114daaddc293 100644 --- a/code/frameworks/nextjs/src/swc/next-swc-loader-patch.ts +++ b/code/frameworks/nextjs/src/swc/next-swc-loader-patch.ts @@ -165,11 +165,20 @@ export function pitch(this: any) { }, callback); } +function sanitizeSourceMap(rawSourceMap: any): any { + const { sourcesContent, ...sourceMap } = rawSourceMap ?? {}; + + // JSON parse/stringify trick required for swc to accept the SourceMap + return JSON.parse(JSON.stringify(sourceMap)); +} + export default function swcLoader(this: any, inputSource: string, inputSourceMap: any) { const loaderSpan = mockCurrentTraceSpan.traceChild('next-swc-loader'); const callback = this.async(); loaderSpan - .traceAsyncFn(() => loaderTransform.call(this, loaderSpan, inputSource, inputSourceMap)) + .traceAsyncFn(() => + loaderTransform.call(this, loaderSpan, inputSource, sanitizeSourceMap(inputSourceMap)) + ) .then( ([transformedSource, outputSourceMap]: any) => { callback(null, transformedSource, outputSourceMap || inputSourceMap); From df06528765104f88b69d0b43f031e27920fb31e4 Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Fri, 17 Nov 2023 11:45:26 +0100 Subject: [PATCH 104/170] Fix E2E test --- code/e2e-tests/addon-controls.spec.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/code/e2e-tests/addon-controls.spec.ts b/code/e2e-tests/addon-controls.spec.ts index df376782aae8..bef89cfb39b2 100644 --- a/code/e2e-tests/addon-controls.spec.ts +++ b/code/e2e-tests/addon-controls.spec.ts @@ -31,10 +31,12 @@ test.describe('addon-controls', () => { ); const toggle = sbPage.panelContent().locator('input[name=primary]'); await toggle.click(); - await expect(sbPage.previewRoot().locator('button')).toHaveCSS( - 'background-color', - 'rgba(0, 0, 0, 0)' - ); + await expect(async () => { + await expect(sbPage.previewRoot().locator('button')).toHaveCSS( + 'background-color', + 'rgba(0, 0, 0, 0)' + ); + }).toPass(); // Color picker: Background color const color = sbPage.panelContent().locator('input[placeholder="Choose color..."]'); From e047dfa8ac7935a171e08e8c5691a9ab5cd12f1f Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Fri, 17 Nov 2023 15:28:25 +0100 Subject: [PATCH 105/170] Exclude existing swc-loader --- code/builders/builder-webpack5/src/preview/loaders.ts | 8 ++------ code/frameworks/nextjs/src/swc/loader.ts | 9 +++------ 2 files changed, 5 insertions(+), 12 deletions(-) diff --git a/code/builders/builder-webpack5/src/preview/loaders.ts b/code/builders/builder-webpack5/src/preview/loaders.ts index 26943cd90e06..333d2a4268f7 100644 --- a/code/builders/builder-webpack5/src/preview/loaders.ts +++ b/code/builders/builder-webpack5/src/preview/loaders.ts @@ -49,12 +49,8 @@ export const createSWCLoader = async (excludes: string[] = [], options: Options) }; return { test: typescriptOptions.skipCompiler ? /\.(mjs|cjs|jsx?)$/ : /\.(mjs|cjs|tsx?|jsx?)$/, - use: [ - { - loader: require.resolve('swc-loader'), - options: config, - }, - ], + loader: require.resolve('swc-loader'), + options: config, include: [getProjectRoot()], exclude: [/node_modules/, ...excludes], }; diff --git a/code/frameworks/nextjs/src/swc/loader.ts b/code/frameworks/nextjs/src/swc/loader.ts index 615e3ce92b5a..661eabc625df 100644 --- a/code/frameworks/nextjs/src/swc/loader.ts +++ b/code/frameworks/nextjs/src/swc/loader.ts @@ -43,10 +43,9 @@ export const configureSWCLoader = async ( baseConfig.module.rules = [ // TODO: Remove filtering in Storybook 8.0 - ...baseConfig.module.rules.filter( - (r: RuleSetRule) => - !(typeof r.use === 'object' && 'loader' in r.use && r.use.loader?.includes('swc-loader')) - ), + ...baseConfig.module.rules.filter((r: RuleSetRule) => { + return !r.loader?.includes('swc-loader'); + }), { test: /\.(m?(j|t)sx?)$/, include: [getProjectRoot()], @@ -62,14 +61,12 @@ export const configureSWCLoader = async ( pagesDir: `${dir}/pages`, appDir: `${dir}/apps`, hasReactRefresh: isDevelopment, - hasServerComponents: true, nextConfig, supportedBrowsers: require('next/dist/build/utils').getSupportedBrowsers( dir, isDevelopment ), swcCacheDir: path.join(dir, nextConfig?.distDir ?? '.next', 'cache', 'swc'), - isServerLayer: false, bundleTarget: 'default', }, }, From f7a0756dc620792ea9f2930ab37ca7dd446e3d29 Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Mon, 20 Nov 2023 08:58:26 +0100 Subject: [PATCH 106/170] Add error message for Next.js if swc is not supported --- code/frameworks/nextjs/src/swc/loader.ts | 11 ++--------- .../lib/core-events/src/errors/server-errors.ts | 17 +++++++++++++++++ 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/code/frameworks/nextjs/src/swc/loader.ts b/code/frameworks/nextjs/src/swc/loader.ts index 661eabc625df..201bdc52e0d8 100644 --- a/code/frameworks/nextjs/src/swc/loader.ts +++ b/code/frameworks/nextjs/src/swc/loader.ts @@ -6,8 +6,7 @@ import type { NextConfig } from 'next'; import path from 'path'; import type { RuleSetRule } from 'webpack'; import semver from 'semver'; -import { dedent } from 'ts-dedent'; -import { logger } from '@storybook/node-logger'; +import { NextjsSWCNotSupportedError } from 'lib/core-events/src/errors/server-errors'; import { getNextjsVersion } from '../utils'; export const configureSWCLoader = async ( @@ -19,13 +18,7 @@ export const configureSWCLoader = async ( const version = getNextjsVersion(); if (semver.lt(version, '14.0.0')) { - logger.warn( - dedent`You have activated the SWC mode for Next.js, but you are not using Next.js 14.0.0 or higher. - SWC is only supported in Next.js 14.0.0 and higher. - Skipping SWC and using Babel instead. - ` - ); - return; + throw new NextjsSWCNotSupportedError(); } const dir = getProjectRoot(); diff --git a/code/lib/core-events/src/errors/server-errors.ts b/code/lib/core-events/src/errors/server-errors.ts index 951a482e9570..6ca430ae1966 100644 --- a/code/lib/core-events/src/errors/server-errors.ts +++ b/code/lib/core-events/src/errors/server-errors.ts @@ -368,3 +368,20 @@ export class GoogleFontsLoadingError extends StorybookError { `; } } + +export class NextjsSWCNotSupportedError extends StorybookError { + readonly category = Category.FRAMEWORK_NEXTJS; + + readonly code = 3; + + public readonly documentation = + 'https://github.com/storybookjs/storybook/blob/next/code/frameworks/nextjs/README.md#manual-migration'; + + template() { + return dedent` + You have activated the SWC mode for Next.js, but you are not using Next.js 14.0.0 or higher. + SWC is only supported in Next.js 14.0.0 and higher. Please go to your .storybook/main. file + and remove the { framework: { options: { builder: { useSWC: true } } } } option or upgrade to Next.js v14 or later. + `; + } +} From b54be152f12423cd2f9ac4589effa42ec7a0479e Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Mon, 20 Nov 2023 09:01:42 +0100 Subject: [PATCH 107/170] Pass proper projectType to generators --- code/lib/cli/src/generators/ANGULAR/index.ts | 3 +-- code/lib/cli/src/initiate.ts | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/code/lib/cli/src/generators/ANGULAR/index.ts b/code/lib/cli/src/generators/ANGULAR/index.ts index 03214d299848..c8c7f3f288b3 100644 --- a/code/lib/cli/src/generators/ANGULAR/index.ts +++ b/code/lib/cli/src/generators/ANGULAR/index.ts @@ -1,7 +1,7 @@ import { join } from 'path'; import { baseGenerator } from '../baseGenerator'; import type { Generator } from '../types'; -import { CoreBuilder, ProjectType } from '../../project_types'; +import { CoreBuilder } from '../../project_types'; import { AngularJSON, compoDocPreviewPrefix, promptForCompoDocs } from './helpers'; import { getCliDir } from '../../dirs'; import { paddedLog, copyTemplate } from '../../helpers'; @@ -59,7 +59,6 @@ const generator: Generator<{ projectName: string }> = async ( { ...options, builder: CoreBuilder.Webpack5, - projectType: ProjectType.ANGULAR, ...(useCompodoc && { frameworkPreviewParts: { prefix: compoDocPreviewPrefix, diff --git a/code/lib/cli/src/initiate.ts b/code/lib/cli/src/initiate.ts index e2966a0c1798..3afd703a1e08 100644 --- a/code/lib/cli/src/initiate.ts +++ b/code/lib/cli/src/initiate.ts @@ -57,7 +57,7 @@ const installStorybook = async ( linkable: !!options.linkable, pnp: pnp || options.usePnp, yes: options.yes, - projectType: options.type, + projectType, }; const runGenerator: () => Promise = async () => { From 39a2b469d91acb0cbfa5d52a1ca71a7d98c84a6b Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Mon, 20 Nov 2023 09:02:56 +0100 Subject: [PATCH 108/170] Fix e2e tests --- code/e2e-tests/addon-controls.spec.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/code/e2e-tests/addon-controls.spec.ts b/code/e2e-tests/addon-controls.spec.ts index bef89cfb39b2..2c388d7ef598 100644 --- a/code/e2e-tests/addon-controls.spec.ts +++ b/code/e2e-tests/addon-controls.spec.ts @@ -41,10 +41,12 @@ test.describe('addon-controls', () => { // Color picker: Background color const color = sbPage.panelContent().locator('input[placeholder="Choose color..."]'); await color.fill('red'); - await expect(sbPage.previewRoot().locator('button')).toHaveCSS( - 'background-color', - 'rgb(255, 0, 0)' - ); + await expect(async () => { + await expect(sbPage.previewRoot().locator('button')).toHaveCSS( + 'background-color', + 'rgb(255, 0, 0)' + ); + }).toPass(); // TODO: enable this once the controls for size are aligned in all CLI templates. // Radio buttons: Size From defbd62a4e9c3d7037b40511ad45c277f973273d Mon Sep 17 00:00:00 2001 From: Yann Braga Date: Mon, 20 Nov 2023 10:35:16 +0100 Subject: [PATCH 109/170] Update code/lib/core-server/src/build-dev.ts --- code/lib/core-server/src/build-dev.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/code/lib/core-server/src/build-dev.ts b/code/lib/core-server/src/build-dev.ts index 459c576113b6..ab8495907efa 100644 --- a/code/lib/core-server/src/build-dev.ts +++ b/code/lib/core-server/src/build-dev.ts @@ -77,7 +77,7 @@ export async function buildDevStandalone( try { await warnOnIncompatibleAddons(config); } catch (e) { - console.warn('Failed to check for incompatible addons', e); + console.warn('Storybook failed to check addon compatibility', e); } // Load first pass: We need to determine the builder From a7e5430049a5063ea49b3e31e1484d50b4e36803 Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Mon, 20 Nov 2023 10:53:01 +0100 Subject: [PATCH 110/170] Move swc logic to custom generators --- code/lib/cli/src/generators/HTML/index.ts | 5 ++++- code/lib/cli/src/generators/PREACT/index.ts | 5 ++++- code/lib/cli/src/generators/REACT/index.ts | 1 + .../cli/src/generators/REACT_SCRIPTS/index.ts | 1 + code/lib/cli/src/generators/SERVER/index.ts | 1 + code/lib/cli/src/generators/SFC_VUE/index.ts | 5 ++++- code/lib/cli/src/generators/VUE/index.ts | 1 + code/lib/cli/src/generators/VUE3/index.ts | 1 + .../src/generators/WEB-COMPONENTS/index.ts | 2 ++ .../cli/src/generators/WEBPACK_REACT/index.ts | 2 ++ code/lib/cli/src/generators/baseGenerator.ts | 19 ++++++------------- code/lib/cli/src/generators/types.ts | 3 ++- 12 files changed, 29 insertions(+), 17 deletions(-) diff --git a/code/lib/cli/src/generators/HTML/index.ts b/code/lib/cli/src/generators/HTML/index.ts index 781d580d2067..c4e0af830fbd 100755 --- a/code/lib/cli/src/generators/HTML/index.ts +++ b/code/lib/cli/src/generators/HTML/index.ts @@ -1,8 +1,11 @@ +import { CoreBuilder } from '../../project_types'; import { baseGenerator } from '../baseGenerator'; import type { Generator } from '../types'; const generator: Generator = async (packageManager, npmOptions, options) => { - await baseGenerator(packageManager, npmOptions, options, 'html'); + await baseGenerator(packageManager, npmOptions, options, 'html', { + useSWC: ({ builder }) => builder === CoreBuilder.Webpack5, + }); }; export default generator; diff --git a/code/lib/cli/src/generators/PREACT/index.ts b/code/lib/cli/src/generators/PREACT/index.ts index e5bf286467a6..6bbab88e16a3 100644 --- a/code/lib/cli/src/generators/PREACT/index.ts +++ b/code/lib/cli/src/generators/PREACT/index.ts @@ -1,8 +1,11 @@ +import { CoreBuilder } from '../../project_types'; import { baseGenerator } from '../baseGenerator'; import type { Generator } from '../types'; const generator: Generator = async (packageManager, npmOptions, options) => { - await baseGenerator(packageManager, npmOptions, options, 'preact'); + await baseGenerator(packageManager, npmOptions, options, 'preact', { + useSWC: ({ builder }) => builder === CoreBuilder.Webpack5, + }); }; export default generator; diff --git a/code/lib/cli/src/generators/REACT/index.ts b/code/lib/cli/src/generators/REACT/index.ts index 208c62bf25d4..3479c1fbc4c1 100644 --- a/code/lib/cli/src/generators/REACT/index.ts +++ b/code/lib/cli/src/generators/REACT/index.ts @@ -10,6 +10,7 @@ const generator: Generator = async (packageManager, npmOptions, options) => { await baseGenerator(packageManager, npmOptions, options, 'react', { extraPackages, + useSWC: ({ builder }) => builder === CoreBuilder.Webpack5, extraAddons: ['@storybook/addon-onboarding'], }); }; diff --git a/code/lib/cli/src/generators/REACT_SCRIPTS/index.ts b/code/lib/cli/src/generators/REACT_SCRIPTS/index.ts index 866b2210664a..2177a9d5090e 100644 --- a/code/lib/cli/src/generators/REACT_SCRIPTS/index.ts +++ b/code/lib/cli/src/generators/REACT_SCRIPTS/index.ts @@ -59,6 +59,7 @@ const generator: Generator = async (packageManager, npmOptions, options) => { { ...options, builder: CoreBuilder.Webpack5 }, 'react', { + useSWC: () => true, extraAddons, extraPackages, staticDir: fs.existsSync(path.resolve('./public')) ? 'public' : undefined, diff --git a/code/lib/cli/src/generators/SERVER/index.ts b/code/lib/cli/src/generators/SERVER/index.ts index c99b69e4902d..7ced80f7441c 100755 --- a/code/lib/cli/src/generators/SERVER/index.ts +++ b/code/lib/cli/src/generators/SERVER/index.ts @@ -9,6 +9,7 @@ const generator: Generator = async (packageManager, npmOptions, options) => { { ...options, builder: CoreBuilder.Webpack5 }, 'server', { + useSWC: () => true, extensions: ['json', 'yaml', 'yml'], } ); diff --git a/code/lib/cli/src/generators/SFC_VUE/index.ts b/code/lib/cli/src/generators/SFC_VUE/index.ts index e2849a352d90..a3e2f15ea604 100644 --- a/code/lib/cli/src/generators/SFC_VUE/index.ts +++ b/code/lib/cli/src/generators/SFC_VUE/index.ts @@ -1,8 +1,11 @@ +import { CoreBuilder } from '../../project_types'; import { baseGenerator } from '../baseGenerator'; import type { Generator } from '../types'; const generator: Generator = async (packageManager, npmOptions, options) => { - await baseGenerator(packageManager, npmOptions, options, 'vue'); + await baseGenerator(packageManager, npmOptions, options, 'vue', { + useSWC: ({ builder }) => builder === CoreBuilder.Webpack5, + }); }; export default generator; diff --git a/code/lib/cli/src/generators/VUE/index.ts b/code/lib/cli/src/generators/VUE/index.ts index c1869a539695..6b771973a283 100644 --- a/code/lib/cli/src/generators/VUE/index.ts +++ b/code/lib/cli/src/generators/VUE/index.ts @@ -7,6 +7,7 @@ const generator: Generator = async (packageManager, npmOptions, options) => { extraPackages: async ({ builder }) => { return builder === CoreBuilder.Webpack5 ? ['vue-loader@^15.7.0'] : []; }, + useSWC: ({ builder }) => builder === CoreBuilder.Webpack5, }); }; diff --git a/code/lib/cli/src/generators/VUE3/index.ts b/code/lib/cli/src/generators/VUE3/index.ts index 63dbddede7b5..ec20a5b946a1 100644 --- a/code/lib/cli/src/generators/VUE3/index.ts +++ b/code/lib/cli/src/generators/VUE3/index.ts @@ -9,6 +9,7 @@ const generator: Generator = async (packageManager, npmOptions, options) => { ? ['vue-loader@^17.0.0', '@vue/compiler-sfc@^3.2.0'] : []; }, + useSWC: ({ builder }) => builder === CoreBuilder.Webpack5, }); }; diff --git a/code/lib/cli/src/generators/WEB-COMPONENTS/index.ts b/code/lib/cli/src/generators/WEB-COMPONENTS/index.ts index 667395096743..bf5ceee43c15 100755 --- a/code/lib/cli/src/generators/WEB-COMPONENTS/index.ts +++ b/code/lib/cli/src/generators/WEB-COMPONENTS/index.ts @@ -1,9 +1,11 @@ +import { CoreBuilder } from '../../project_types'; import { baseGenerator } from '../baseGenerator'; import type { Generator } from '../types'; const generator: Generator = async (packageManager, npmOptions, options) => { return baseGenerator(packageManager, npmOptions, options, 'web-components', { extraPackages: ['lit'], + useSWC: ({ builder }) => builder === CoreBuilder.Webpack5, }); }; diff --git a/code/lib/cli/src/generators/WEBPACK_REACT/index.ts b/code/lib/cli/src/generators/WEBPACK_REACT/index.ts index 867bd82b80c2..94e8babee466 100644 --- a/code/lib/cli/src/generators/WEBPACK_REACT/index.ts +++ b/code/lib/cli/src/generators/WEBPACK_REACT/index.ts @@ -1,9 +1,11 @@ +import { CoreBuilder } from '../../project_types'; import { baseGenerator } from '../baseGenerator'; import type { Generator } from '../types'; const generator: Generator = async (packageManager, npmOptions, options) => { await baseGenerator(packageManager, npmOptions, options, 'react', { extraAddons: ['@storybook/addon-onboarding'], + useSWC: ({ builder }) => builder === CoreBuilder.Webpack5, }); }; diff --git a/code/lib/cli/src/generators/baseGenerator.ts b/code/lib/cli/src/generators/baseGenerator.ts index 7a808b103fb8..ae90bf3d3036 100644 --- a/code/lib/cli/src/generators/baseGenerator.ts +++ b/code/lib/cli/src/generators/baseGenerator.ts @@ -29,6 +29,7 @@ const defaultOptions: FrameworkOptions = { addMainFile: true, addComponents: true, skipBabel: false, + useSWC: () => false, extraMain: undefined, framework: undefined, extensions: undefined, @@ -171,15 +172,6 @@ const hasInteractiveStories = (rendererId: SupportedRenderers) => const hasFrameworkTemplates = (framework?: SupportedFrameworks) => ['angular', 'nextjs'].includes(framework); -function shouldUseSWCCompiler(builder: Builder, projectType: ProjectType) { - return ( - builder === CoreBuilder.Webpack5 && - projectType !== ProjectType.ANGULAR && - // TODO: Remove in Storybook 8.0 - projectType !== ProjectType.NEXTJS - ); -} - export async function baseGenerator( packageManager: JsPackageManager, npmOptions: NpmOptions, @@ -203,8 +195,6 @@ export async function baseGenerator( builder = await detectBuilder(packageManager, projectType); } - const useSWC = shouldUseSWCCompiler(builder, projectType); - const { packages: frameworkPackages, type, @@ -231,6 +221,7 @@ export async function baseGenerator( extensions, storybookConfigFolder, componentsDestinationPath, + useSWC, } = { ...defaultOptions, ...options, @@ -241,7 +232,9 @@ export async function baseGenerator( ...options, }; - if (useSWC) { + const swc = useSWC({ builder }); + + if (swc) { skipBabel = true; } @@ -422,7 +415,7 @@ export async function baseGenerator( await configureMain({ framework: { name: frameworkInclude, - options: useSWC + options: swc ? { ...(options.framework ?? {}), builder: { diff --git a/code/lib/cli/src/generators/types.ts b/code/lib/cli/src/generators/types.ts index 1711505e0bdc..e86e6876eda3 100644 --- a/code/lib/cli/src/generators/types.ts +++ b/code/lib/cli/src/generators/types.ts @@ -1,5 +1,5 @@ import type { NpmOptions } from '../NpmOptions'; -import type { SupportedLanguage, Builder, ProjectType } from '../project_types'; +import type { SupportedLanguage, Builder, ProjectType, CoreBuilder } from '../project_types'; import type { JsPackageManager, PackageManagerName } from '../js-package-manager/JsPackageManager'; import type { FrameworkPreviewParts } from './configure'; @@ -24,6 +24,7 @@ export interface FrameworkOptions { addMainFile?: boolean; addComponents?: boolean; skipBabel?: boolean; + useSWC?: ({ builder }: { builder: Builder }) => boolean; extraMain?: any; extensions?: string[]; framework?: Record; From 39ddc2593683d5e401bcf726a84033837c18fb47 Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Mon, 20 Nov 2023 10:53:27 +0100 Subject: [PATCH 111/170] Change selected compiler message --- code/builders/builder-webpack5/src/preview/loaders.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/code/builders/builder-webpack5/src/preview/loaders.ts b/code/builders/builder-webpack5/src/preview/loaders.ts index 333d2a4268f7..f10bd93a5ebc 100644 --- a/code/builders/builder-webpack5/src/preview/loaders.ts +++ b/code/builders/builder-webpack5/src/preview/loaders.ts @@ -10,6 +10,7 @@ export const createBabelLoader = ( typescriptOptions: TypescriptOptions, excludes: string[] = [] ) => { + logger.info(dedent`Using Babel compiler`); return { test: typescriptOptions.skipBabel ? /\.(mjs|jsx?)$/ : /\.(mjs|tsx?|jsx?)$/, use: [ @@ -24,9 +25,7 @@ export const createBabelLoader = ( }; export const createSWCLoader = async (excludes: string[] = [], options: Options) => { - logger.warn(dedent` - The SWC loader is an experimental feature and may change or even be removed at any time. - `); + logger.info(dedent`Using SWC compiler`); const swc = await options.presets.apply('swc', {}, options); const typescriptOptions = await options.presets.apply<{ skipCompiler?: boolean }>( From dff960f425533721704aaa9739eb2b65984aa044 Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Mon, 20 Nov 2023 10:53:50 +0100 Subject: [PATCH 112/170] Update jscodeshift to fix local sandbox creation --- code/lib/codemod/package.json | 4 +- code/lib/postinstall/package.json | 2 +- code/yarn.lock | 66 ++++--------------------------- 3 files changed, 10 insertions(+), 62 deletions(-) diff --git a/code/lib/codemod/package.json b/code/lib/codemod/package.json index c805f990a8de..ac98a974c4b3 100644 --- a/code/lib/codemod/package.json +++ b/code/lib/codemod/package.json @@ -62,13 +62,13 @@ "@types/cross-spawn": "^6.0.2", "cross-spawn": "^7.0.3", "globby": "^11.0.2", - "jscodeshift": "^0.14.0", + "jscodeshift": "^0.15.1", "lodash": "^4.17.21", "prettier": "^2.8.0", "recast": "^0.23.1" }, "devDependencies": { - "@types/jscodeshift": "^0.11.6", + "@types/jscodeshift": "^0.11.10", "ansi-regex": "^5.0.1", "jest": "^29.7.0", "jest-specific-snapshot": "^8.0.0", diff --git a/code/lib/postinstall/package.json b/code/lib/postinstall/package.json index a9779b34bd82..9e2a19920e07 100644 --- a/code/lib/postinstall/package.json +++ b/code/lib/postinstall/package.json @@ -47,7 +47,7 @@ "devDependencies": { "jest": "^29.7.0", "jest-specific-snapshot": "^8.0.0", - "jscodeshift": "^0.14.0", + "jscodeshift": "^0.15.1", "typescript": "~4.9.3" }, "publishConfig": { diff --git a/code/yarn.lock b/code/yarn.lock index 26430758888f..df84273184ce 100644 --- a/code/yarn.lock +++ b/code/yarn.lock @@ -6311,13 +6311,13 @@ __metadata: "@storybook/node-logger": "workspace:*" "@storybook/types": "workspace:*" "@types/cross-spawn": "npm:^6.0.2" - "@types/jscodeshift": "npm:^0.11.6" + "@types/jscodeshift": "npm:^0.11.10" ansi-regex: "npm:^5.0.1" cross-spawn: "npm:^7.0.3" globby: "npm:^11.0.2" jest: "npm:^29.7.0" jest-specific-snapshot: "npm:^8.0.0" - jscodeshift: "npm:^0.14.0" + jscodeshift: "npm:^0.15.1" lodash: "npm:^4.17.21" mdast-util-mdx-jsx: "npm:^2.1.2" mdast-util-mdxjs-esm: "npm:^1.3.1" @@ -6925,7 +6925,7 @@ __metadata: dependencies: jest: "npm:^29.7.0" jest-specific-snapshot: "npm:^8.0.0" - jscodeshift: "npm:^0.14.0" + jscodeshift: "npm:^0.15.1" typescript: "npm:~4.9.3" languageName: unknown linkType: soft @@ -8939,13 +8939,13 @@ __metadata: languageName: node linkType: hard -"@types/jscodeshift@npm:^0.11.6": - version: 0.11.7 - resolution: "@types/jscodeshift@npm:0.11.7" +"@types/jscodeshift@npm:^0.11.10": + version: 0.11.10 + resolution: "@types/jscodeshift@npm:0.11.10" dependencies: ast-types: "npm:^0.14.1" recast: "npm:^0.20.3" - checksum: a2c26f8e64950296bae6176c52e832e1f5c5eb3672adad3c1cdc63e23b8bd3de47890ac8eaae7eb0788feea7628ce540513ff5189379f79e882ddcfa1c855cfc + checksum: 1d477ea1addd62a5949f028ef16bac3226341d65052e4f51d61e51789c6c7aa17e953dac34eb6d1e5a2b761fc4c7920df875e20e85cdf4122fc08836e7da547a languageName: node linkType: hard @@ -11157,15 +11157,6 @@ __metadata: languageName: node linkType: hard -"ast-types@npm:0.15.2": - version: 0.15.2 - resolution: "ast-types@npm:0.15.2" - dependencies: - tslib: "npm:^2.0.1" - checksum: 5b26e3656e9e8d1db8c8d14971d0cb88ca0138aacce72171cb4cd4555fc8dc53c07e821c568e57fe147366931708fefd25cb9d7e880d42ce9cb569947844c962 - languageName: node - linkType: hard - "ast-types@npm:^0.16.1": version: 0.16.1 resolution: "ast-types@npm:0.16.1" @@ -20130,37 +20121,6 @@ __metadata: languageName: node linkType: hard -"jscodeshift@npm:^0.14.0": - version: 0.14.0 - resolution: "jscodeshift@npm:0.14.0" - dependencies: - "@babel/core": "npm:^7.13.16" - "@babel/parser": "npm:^7.13.16" - "@babel/plugin-proposal-class-properties": "npm:^7.13.0" - "@babel/plugin-proposal-nullish-coalescing-operator": "npm:^7.13.8" - "@babel/plugin-proposal-optional-chaining": "npm:^7.13.12" - "@babel/plugin-transform-modules-commonjs": "npm:^7.13.8" - "@babel/preset-flow": "npm:^7.13.13" - "@babel/preset-typescript": "npm:^7.13.0" - "@babel/register": "npm:^7.13.16" - babel-core: "npm:^7.0.0-bridge.0" - chalk: "npm:^4.1.2" - flow-parser: "npm:0.*" - graceful-fs: "npm:^4.2.4" - micromatch: "npm:^4.0.4" - neo-async: "npm:^2.5.0" - node-dir: "npm:^0.1.17" - recast: "npm:^0.21.0" - temp: "npm:^0.8.4" - write-file-atomic: "npm:^2.3.0" - peerDependencies: - "@babel/preset-env": ^7.1.6 - bin: - jscodeshift: bin/jscodeshift.js - checksum: dab63bdb4b7e67d79634fcd3f5dc8b227146e9f68aa88700bc49c5a45b6339d05bd934a98aa53d29abd04f81237d010e7e037799471b2aab66ec7b9a7d752786 - languageName: node - linkType: hard - "jscodeshift@npm:^0.15.1": version: 0.15.1 resolution: "jscodeshift@npm:0.15.1" @@ -25957,18 +25917,6 @@ __metadata: languageName: node linkType: hard -"recast@npm:^0.21.0": - version: 0.21.5 - resolution: "recast@npm:0.21.5" - dependencies: - ast-types: "npm:0.15.2" - esprima: "npm:~4.0.0" - source-map: "npm:~0.6.1" - tslib: "npm:^2.0.1" - checksum: a45168c82195f24fa2c70293a624fece0069a2e8e8adb637f9963777735f81cb3bb62e55172db677ec3573b08b2daaf1eddd85b74da6fe0bd37c9b15eeaf94b4 - languageName: node - linkType: hard - "recast@npm:^0.23.1, recast@npm:^0.23.3": version: 0.23.4 resolution: "recast@npm:0.23.4" From 5f1f16d4865a63493bf50f9d5bfac7e08bddd272 Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Mon, 20 Nov 2023 09:50:51 +0100 Subject: [PATCH 113/170] Change check-dependencies script to js WIP WIP WIP WIP --- .github/workflows/generate-sandboxes-main.yml | 2 +- .github/workflows/generate-sandboxes-next.yml | 2 +- scripts/check-dependencies.js | 72 +++++++++++++++++++ scripts/check-dependencies.ts | 7 -- 4 files changed, 74 insertions(+), 9 deletions(-) create mode 100644 scripts/check-dependencies.js delete mode 100755 scripts/check-dependencies.ts diff --git a/.github/workflows/generate-sandboxes-main.yml b/.github/workflows/generate-sandboxes-main.yml index adea48c1b2f6..53814040f610 100644 --- a/.github/workflows/generate-sandboxes-main.yml +++ b/.github/workflows/generate-sandboxes-main.yml @@ -32,7 +32,7 @@ jobs: - name: Install dependencies run: | cd ./scripts - node --loader esbuild-register/loader -r esbuild-register ./check-dependencies.ts + node --experimental-modules ./check-dependencies.js cd .. - name: Compile Storybook libraries run: yarn task --task compile --start-from=auto --no-link diff --git a/.github/workflows/generate-sandboxes-next.yml b/.github/workflows/generate-sandboxes-next.yml index 9a00f8b99cdc..d9355f593dc8 100644 --- a/.github/workflows/generate-sandboxes-next.yml +++ b/.github/workflows/generate-sandboxes-next.yml @@ -32,7 +32,7 @@ jobs: - name: Install dependencies run: | cd ./scripts - node --loader esbuild-register/loader -r esbuild-register ./check-dependencies.ts + node --experimental-modules ./check-dependencies.js cd .. - name: Compile Storybook libraries run: yarn task --task compile --start-from=auto --no-link diff --git a/scripts/check-dependencies.js b/scripts/check-dependencies.js new file mode 100644 index 000000000000..0bad76f507cc --- /dev/null +++ b/scripts/check-dependencies.js @@ -0,0 +1,72 @@ +/** + * This file needs to be run before any other script to ensure dependencies are installed + * Therefore, we cannot transform this file to Typescript, because it would require esbuild to be installed + */ +import { spawn } from 'child_process'; +import { join } from 'path'; +import { existsSync } from 'fs'; +import * as url from 'url'; + +const logger = console; + +const filename = url.fileURLToPath(import.meta.url); +const dirname = url.fileURLToPath(new URL('.', import.meta.url)); + +const checkDependencies = async () => { + const scriptsPath = join(dirname); + const codePath = join(dirname, '..', 'code'); + + const tasks = []; + + if (!existsSync(join(scriptsPath, 'node_modules'))) { + tasks.push( + spawn('yarn', ['install'], { + cwd: scriptsPath, + shell: true, + stdio: ['inherit', 'inherit', 'inherit'], + }) + ); + } + if (!existsSync(join(codePath, 'node_modules'))) { + tasks.push( + spawn('yarn', ['install'], { + cwd: codePath, + shell: true, + stdio: ['inherit', 'inherit', 'inherit'], + }) + ); + } + + if (tasks.length > 0) { + logger.log('installing dependencies'); + + await Promise.all( + tasks.map( + (t) => + new Promise((res, rej) => { + t.on('exit', (code) => { + if (code !== 0) { + rej(); + } else { + res(); + } + }); + }) + ) + ).catch(() => { + tasks.forEach((t) => t.kill()); + throw new Error('Failed to install dependencies'); + }); + + // give the filesystem some time + await new Promise((res) => { + setTimeout(res, 1000); + }); + } +}; + +checkDependencies().catch((e) => { + // eslint-disable-next-line no-console + console.error(e); + process.exit(1); +}); diff --git a/scripts/check-dependencies.ts b/scripts/check-dependencies.ts deleted file mode 100755 index babee83b82f6..000000000000 --- a/scripts/check-dependencies.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { checkDependencies } from './utils/cli-utils'; - -checkDependencies().catch((e) => { - // eslint-disable-next-line no-console - console.error(e); - process.exit(1); -}); From 95a2add386e291aff46f097874d015d684ed22a5 Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Mon, 20 Nov 2023 11:36:47 +0100 Subject: [PATCH 114/170] Cleanup imports --- code/lib/cli/src/generators/REACT/index.ts | 2 +- code/lib/cli/src/generators/baseGenerator.ts | 2 +- code/lib/cli/src/generators/types.ts | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/code/lib/cli/src/generators/REACT/index.ts b/code/lib/cli/src/generators/REACT/index.ts index 3479c1fbc4c1..046860356c56 100644 --- a/code/lib/cli/src/generators/REACT/index.ts +++ b/code/lib/cli/src/generators/REACT/index.ts @@ -1,5 +1,5 @@ import { detectLanguage } from '../../detect'; -import { SupportedLanguage } from '../../project_types'; +import { CoreBuilder, SupportedLanguage } from '../../project_types'; import { baseGenerator } from '../baseGenerator'; import type { Generator } from '../types'; diff --git a/code/lib/cli/src/generators/baseGenerator.ts b/code/lib/cli/src/generators/baseGenerator.ts index ae90bf3d3036..6083fae9e873 100644 --- a/code/lib/cli/src/generators/baseGenerator.ts +++ b/code/lib/cli/src/generators/baseGenerator.ts @@ -4,7 +4,7 @@ import { dedent } from 'ts-dedent'; import ora from 'ora'; import type { NpmOptions } from '../NpmOptions'; import type { SupportedRenderers, SupportedFrameworks, Builder } from '../project_types'; -import { SupportedLanguage, externalFrameworks, CoreBuilder, ProjectType } from '../project_types'; +import { SupportedLanguage, externalFrameworks, CoreBuilder } from '../project_types'; import { copyTemplateFiles } from '../helpers'; import { configureMain, configurePreview } from './configure'; import type { JsPackageManager } from '../js-package-manager'; diff --git a/code/lib/cli/src/generators/types.ts b/code/lib/cli/src/generators/types.ts index e86e6876eda3..2f97a34df126 100644 --- a/code/lib/cli/src/generators/types.ts +++ b/code/lib/cli/src/generators/types.ts @@ -1,5 +1,5 @@ import type { NpmOptions } from '../NpmOptions'; -import type { SupportedLanguage, Builder, ProjectType, CoreBuilder } from '../project_types'; +import type { SupportedLanguage, Builder, ProjectType } from '../project_types'; import type { JsPackageManager, PackageManagerName } from '../js-package-manager/JsPackageManager'; import type { FrameworkPreviewParts } from './configure'; From c825bd6560cd717455784ac8c479a2f111ff7e75 Mon Sep 17 00:00:00 2001 From: Norbert de Langen Date: Mon, 20 Nov 2023 13:09:08 +0100 Subject: [PATCH 115/170] rename property & add tests --- .../src/utils/normalize-stories.ts | 8 +- .../src/presets/common-override-preset.ts | 57 +--- .../__tests__/remove-mdx-stories.test.ts | 274 ++++++++++++++++++ .../src/utils/remove-mdx-entries.ts | 54 ++++ 4 files changed, 335 insertions(+), 58 deletions(-) create mode 100644 code/lib/core-server/src/utils/__tests__/remove-mdx-stories.test.ts create mode 100644 code/lib/core-server/src/utils/remove-mdx-entries.ts diff --git a/code/lib/core-common/src/utils/normalize-stories.ts b/code/lib/core-common/src/utils/normalize-stories.ts index 3beabeae4c8c..1a69fb1ce689 100644 --- a/code/lib/core-common/src/utils/normalize-stories.ts +++ b/code/lib/core-common/src/utils/normalize-stories.ts @@ -34,7 +34,7 @@ export const getDirectoryFromWorkingDir = ({ export const normalizeStoriesEntry = ( entry: StoriesEntry, - { configDir, workingDir, default_files_pattern = DEFAULT_FILES_PATTERN }: NormalizeOptions + { configDir, workingDir, defaultFilesPattern = DEFAULT_FILES_PATTERN }: NormalizeOptions ): NormalizedStoriesSpecifier => { let specifierWithoutMatcher: Omit; @@ -53,7 +53,7 @@ export const normalizeStoriesEntry = ( specifierWithoutMatcher = { titlePrefix: DEFAULT_TITLE_PREFIX, directory: entry, - files: default_files_pattern, + files: defaultFilesPattern, }; } else { specifierWithoutMatcher = { @@ -65,7 +65,7 @@ export const normalizeStoriesEntry = ( } else { specifierWithoutMatcher = { titlePrefix: DEFAULT_TITLE_PREFIX, - files: default_files_pattern, + files: defaultFilesPattern, ...entry, }; } @@ -99,7 +99,7 @@ export const normalizeStoriesEntry = ( interface NormalizeOptions { configDir: string; workingDir: string; - default_files_pattern?: string; + defaultFilesPattern?: string; } export const normalizeStories = (entries: StoriesEntry[], options: NormalizeOptions) => { diff --git a/code/lib/core-server/src/presets/common-override-preset.ts b/code/lib/core-server/src/presets/common-override-preset.ts index d92dead5d8f4..8cc740aea7d7 100644 --- a/code/lib/core-server/src/presets/common-override-preset.ts +++ b/code/lib/core-server/src/presets/common-override-preset.ts @@ -1,14 +1,5 @@ -import type { - Options, - PresetProperty, - StoriesEntry, - StorybookConfig, - TestBuildFlags, -} from '@storybook/types'; -import { normalizeStories, commonGlobOptions } from '@storybook/core-common'; -import { isAbsolute, join, relative } from 'path'; -import slash from 'slash'; -import { glob } from 'glob'; +import type { Options, PresetProperty, StorybookConfig, TestBuildFlags } from '@storybook/types'; +import { removeMDXEntries } from '../utils/remove-mdx-entries'; export const framework: PresetProperty<'framework', StorybookConfig> = async (config) => { // This will get called with the values from the user's main config, but before @@ -25,49 +16,7 @@ export const framework: PresetProperty<'framework', StorybookConfig> = async (co export const stories: PresetProperty<'stories', StorybookConfig> = async (entries, options) => { if (options?.build?.test?.disableMDXEntries) { - const list = normalizeStories(entries, { - configDir: options.configDir, - workingDir: options.configDir, - default_files_pattern: '**/*.@(stories.@(js|jsx|mjs|ts|tsx))', - }); - const result = ( - await Promise.all( - list.map(async ({ directory, files, titlePrefix }) => { - const pattern = join(directory, files); - const absolutePattern = isAbsolute(pattern) ? pattern : join(options.configDir, pattern); - const absoluteDirectory = isAbsolute(directory) - ? directory - : join(options.configDir, directory); - - return { - files: ( - await glob(slash(absolutePattern), { - ...commonGlobOptions(absolutePattern), - follow: true, - }) - ).map((f) => relative(absoluteDirectory, f)), - directory, - titlePrefix, - }; - }) - ) - ).flatMap((expanded, i) => { - const filteredEntries = expanded.files.filter((s) => !s.endsWith('.mdx')); - // only return the filtered entries when there is something to filter - // as webpack is faster with unexpanded globs - let items = []; - if (filteredEntries.length < expanded.files.length) { - items = filteredEntries.map((k) => ({ - ...expanded, - files: `**/${k}`, - })); - } else { - items = [list[i]]; - } - - return items; - }); - return result; + return removeMDXEntries(entries, options); } return entries; }; diff --git a/code/lib/core-server/src/utils/__tests__/remove-mdx-stories.test.ts b/code/lib/core-server/src/utils/__tests__/remove-mdx-stories.test.ts new file mode 100644 index 000000000000..9c40041c0dc1 --- /dev/null +++ b/code/lib/core-server/src/utils/__tests__/remove-mdx-stories.test.ts @@ -0,0 +1,274 @@ +import { glob as globlOriginal } from 'glob'; +import { type StoriesEntry } from '@storybook/types'; +import { normalizeStoriesEntry } from '@storybook/core-common'; +import { join } from 'path'; +import { removeMDXEntries } from '../remove-mdx-entries'; + +const glob = globlOriginal as jest.MockedFunction; + +jest.mock('glob', () => ({ glob: jest.fn() })); + +const createList = (list: { entry: StoriesEntry; result: string[] }[], configDir: string) => { + return list.reduce>( + (acc, { entry, result }) => { + const { directory, files } = normalizeStoriesEntry(entry, { + configDir, + workingDir: '/', + }); + acc[join('/', directory, files)] = { result, entry }; + return acc; + }, + {} + ); +}; + +const createGlobMock = (input: ReturnType) => { + return async (k: string | string[]) => { + if (Array.isArray(k)) { + throw new Error('do not pass an array to glob during tests'); + } + const result = input[k].result || []; + return result; + }; +}; + +test('empty', async () => { + const configDir = '/configDir/'; + const list = createList([], configDir); + glob.mockImplementation(createGlobMock(list)); + + await expect(() => removeMDXEntries(Object.keys(list), { configDir })).rejects + .toThrowErrorMatchingInlineSnapshot(` + "Storybook could not index your stories. + Your main configuration somehow does not contain a 'stories' field, or it resolved to an empty array. + + Please check your main configuration file and make sure it exports a 'stories' field that is not an empty array. + + More info: https://storybook.js.org/docs/react/faq#can-i-have-a-storybook-with-no-local-stories + " + `); +}); + +test('minimal', async () => { + const configDir = '/configDir/'; + const list = createList([{ entry: '*.js', result: [] }], configDir); + glob.mockImplementation(createGlobMock(list)); + + await expect( + removeMDXEntries( + Object.values(list).map((e) => e.entry), + { configDir } + ) + ).resolves.toMatchInlineSnapshot(` + Array [ + Object { + "directory": ".", + "files": "*.js", + "importPathMatcher": /\\^\\\\\\.\\[\\\\\\\\/\\]\\(\\?:\\(\\?!\\\\\\.\\)\\(\\?=\\.\\)\\[\\^/\\]\\*\\?\\\\\\.js\\)\\$/, + "titlePrefix": "", + }, + ] + `); +}); + +test('multiple', async () => { + const configDir = '/configDir/'; + const list = createList( + [ + { entry: '*.ts', result: [] }, + { entry: '*.js', result: [] }, + ], + configDir + ); + glob.mockImplementation(createGlobMock(list)); + + await expect( + removeMDXEntries( + Object.values(list).map((e) => e.entry), + { configDir } + ) + ).resolves.toMatchInlineSnapshot(` + Array [ + Object { + "directory": ".", + "files": "*.ts", + "importPathMatcher": /\\^\\\\\\.\\[\\\\\\\\/\\]\\(\\?:\\(\\?!\\\\\\.\\)\\(\\?=\\.\\)\\[\\^/\\]\\*\\?\\\\\\.ts\\)\\$/, + "titlePrefix": "", + }, + Object { + "directory": ".", + "files": "*.js", + "importPathMatcher": /\\^\\\\\\.\\[\\\\\\\\/\\]\\(\\?:\\(\\?!\\\\\\.\\)\\(\\?=\\.\\)\\[\\^/\\]\\*\\?\\\\\\.js\\)\\$/, + "titlePrefix": "", + }, + ] + `); +}); + +test('mdx but not matching any files', async () => { + const configDir = '/configDir/'; + const list = createList( + [ + { entry: '*.mdx', result: [] }, + { entry: '*.js', result: [] }, + ], + configDir + ); + glob.mockImplementation(createGlobMock(list)); + + await expect( + removeMDXEntries( + Object.values(list).map((e) => e.entry), + { configDir } + ) + ).resolves.toMatchInlineSnapshot(` + Array [ + Object { + "directory": ".", + "files": "*.mdx", + "importPathMatcher": /\\^\\\\\\.\\[\\\\\\\\/\\]\\(\\?:\\(\\?!\\\\\\.\\)\\(\\?=\\.\\)\\[\\^/\\]\\*\\?\\\\\\.mdx\\)\\$/, + "titlePrefix": "", + }, + Object { + "directory": ".", + "files": "*.js", + "importPathMatcher": /\\^\\\\\\.\\[\\\\\\\\/\\]\\(\\?:\\(\\?!\\\\\\.\\)\\(\\?=\\.\\)\\[\\^/\\]\\*\\?\\\\\\.js\\)\\$/, + "titlePrefix": "", + }, + ] + `); +}); + +test('removes entries that only yield mdx files', async () => { + const configDir = '/configDir/'; + const list = createList( + [ + { entry: '*.mdx', result: ['/configDir/my-file.mdx'] }, + { entry: '*.js', result: [] }, + ], + configDir + ); + glob.mockImplementation(createGlobMock(list)); + + await expect( + removeMDXEntries( + Object.values(list).map((e) => e.entry), + { configDir } + ) + ).resolves.toMatchInlineSnapshot(` + Array [ + Object { + "directory": ".", + "files": "*.js", + "importPathMatcher": /\\^\\\\\\.\\[\\\\\\\\/\\]\\(\\?:\\(\\?!\\\\\\.\\)\\(\\?=\\.\\)\\[\\^/\\]\\*\\?\\\\\\.js\\)\\$/, + "titlePrefix": "", + }, + ] + `); +}); + +test('expands entries that only yield mixed files', async () => { + const configDir = '/configDir/'; + const list = createList( + [ + { entry: '*.@(mdx|ts)', result: ['/configDir/my-file.mdx', '/configDir/my-file.ts'] }, + { entry: '*.js', result: [] }, + ], + configDir + ); + glob.mockImplementation(createGlobMock(list)); + + await expect( + removeMDXEntries( + Object.values(list).map((e) => e.entry), + { configDir } + ) + ).resolves.toMatchInlineSnapshot(` + Array [ + Object { + "directory": ".", + "files": "**/my-file.ts", + "titlePrefix": "", + }, + Object { + "directory": ".", + "files": "*.js", + "importPathMatcher": /\\^\\\\\\.\\[\\\\\\\\/\\]\\(\\?:\\(\\?!\\\\\\.\\)\\(\\?=\\.\\)\\[\\^/\\]\\*\\?\\\\\\.js\\)\\$/, + "titlePrefix": "", + }, + ] + `); +}); + +test('passes titlePrefix', async () => { + const configDir = '/configDir/'; + const list = createList( + [ + { + entry: { files: '*.@(mdx|ts)', directory: '.', titlePrefix: 'foo' }, + result: ['/configDir/my-file.mdx', '/configDir/my-file.ts'], + }, + ], + configDir + ); + glob.mockImplementation(createGlobMock(list)); + + await expect( + removeMDXEntries( + Object.values(list).map((e) => e.entry), + { configDir } + ) + ).resolves.toMatchInlineSnapshot(` + Array [ + Object { + "directory": ".", + "files": "**/my-file.ts", + "titlePrefix": "foo", + }, + ] + `); +}); + +test('expands to multiple entries', async () => { + const configDir = '/configDir/'; + const list = createList( + [ + { + entry: { files: '*.@(mdx|ts)', directory: '.', titlePrefix: 'foo' }, + result: [ + '/configDir/my-file.mdx', + '/configDir/my-file1.ts', + '/configDir/my-file2.ts', + '/configDir/my-file3.ts', + ], + }, + ], + configDir + ); + glob.mockImplementation(createGlobMock(list)); + + await expect( + removeMDXEntries( + Object.values(list).map((e) => e.entry), + { configDir } + ) + ).resolves.toMatchInlineSnapshot(` + Array [ + Object { + "directory": ".", + "files": "**/my-file1.ts", + "titlePrefix": "foo", + }, + Object { + "directory": ".", + "files": "**/my-file2.ts", + "titlePrefix": "foo", + }, + Object { + "directory": ".", + "files": "**/my-file3.ts", + "titlePrefix": "foo", + }, + ] + `); +}); diff --git a/code/lib/core-server/src/utils/remove-mdx-entries.ts b/code/lib/core-server/src/utils/remove-mdx-entries.ts new file mode 100644 index 000000000000..0efc7923baad --- /dev/null +++ b/code/lib/core-server/src/utils/remove-mdx-entries.ts @@ -0,0 +1,54 @@ +import type { Options, StoriesEntry } from '@storybook/types'; +import { normalizeStories, commonGlobOptions } from '@storybook/core-common'; +import { isAbsolute, join, relative } from 'path'; +import slash from 'slash'; +import { glob } from 'glob'; + +export async function removeMDXEntries( + entries: StoriesEntry[], + options: Pick +) { + const list = normalizeStories(entries, { + configDir: options.configDir, + workingDir: options.configDir, + defaultFilesPattern: '**/*.@(stories.@(js|jsx|mjs|ts|tsx))', + }); + const result = ( + await Promise.all( + list.map(async ({ directory, files, titlePrefix }) => { + const pattern = join(directory, files); + const absolutePattern = isAbsolute(pattern) ? pattern : join(options.configDir, pattern); + const absoluteDirectory = isAbsolute(directory) + ? directory + : join(options.configDir, directory); + + return { + files: ( + await glob(slash(absolutePattern), { + ...commonGlobOptions(absolutePattern), + follow: true, + }) + ).map((f) => relative(absoluteDirectory, f)), + directory, + titlePrefix, + }; + }) + ) + ).flatMap((expanded, i) => { + const filteredEntries = expanded.files.filter((s) => !s.endsWith('.mdx')); + // only return the filtered entries when there is something to filter + // as webpack is faster with unexpanded globs + let items = []; + if (filteredEntries.length < expanded.files.length) { + items = filteredEntries.map((k) => ({ + ...expanded, + files: `**/${k}`, + })); + } else { + items = [list[i]]; + } + + return items; + }); + return result; +} From b20a4830585a648a1e9ab622df90b9688507878d Mon Sep 17 00:00:00 2001 From: Norbert de Langen Date: Mon, 20 Nov 2023 13:42:15 +0100 Subject: [PATCH 116/170] maybe fix for windows --- .../src/utils/__tests__/remove-mdx-stories.test.ts | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/code/lib/core-server/src/utils/__tests__/remove-mdx-stories.test.ts b/code/lib/core-server/src/utils/__tests__/remove-mdx-stories.test.ts index 9c40041c0dc1..5438e48edfe9 100644 --- a/code/lib/core-server/src/utils/__tests__/remove-mdx-stories.test.ts +++ b/code/lib/core-server/src/utils/__tests__/remove-mdx-stories.test.ts @@ -2,6 +2,7 @@ import { glob as globlOriginal } from 'glob'; import { type StoriesEntry } from '@storybook/types'; import { normalizeStoriesEntry } from '@storybook/core-common'; import { join } from 'path'; +import slash from 'slash'; import { removeMDXEntries } from '../remove-mdx-entries'; const glob = globlOriginal as jest.MockedFunction; @@ -27,13 +28,14 @@ const createGlobMock = (input: ReturnType) => { if (Array.isArray(k)) { throw new Error('do not pass an array to glob during tests'); } - const result = input[k].result || []; + const result = input[slash(k)].result || []; return result; }; }; +const configDir = '/configDir/'; + test('empty', async () => { - const configDir = '/configDir/'; const list = createList([], configDir); glob.mockImplementation(createGlobMock(list)); @@ -50,7 +52,6 @@ test('empty', async () => { }); test('minimal', async () => { - const configDir = '/configDir/'; const list = createList([{ entry: '*.js', result: [] }], configDir); glob.mockImplementation(createGlobMock(list)); @@ -72,7 +73,6 @@ test('minimal', async () => { }); test('multiple', async () => { - const configDir = '/configDir/'; const list = createList( [ { entry: '*.ts', result: [] }, @@ -106,7 +106,6 @@ test('multiple', async () => { }); test('mdx but not matching any files', async () => { - const configDir = '/configDir/'; const list = createList( [ { entry: '*.mdx', result: [] }, @@ -140,7 +139,6 @@ test('mdx but not matching any files', async () => { }); test('removes entries that only yield mdx files', async () => { - const configDir = '/configDir/'; const list = createList( [ { entry: '*.mdx', result: ['/configDir/my-file.mdx'] }, @@ -168,7 +166,6 @@ test('removes entries that only yield mdx files', async () => { }); test('expands entries that only yield mixed files', async () => { - const configDir = '/configDir/'; const list = createList( [ { entry: '*.@(mdx|ts)', result: ['/configDir/my-file.mdx', '/configDir/my-file.ts'] }, @@ -201,7 +198,6 @@ test('expands entries that only yield mixed files', async () => { }); test('passes titlePrefix', async () => { - const configDir = '/configDir/'; const list = createList( [ { @@ -230,7 +226,6 @@ test('passes titlePrefix', async () => { }); test('expands to multiple entries', async () => { - const configDir = '/configDir/'; const list = createList( [ { From d840521d78c3102f3fca5244c051886bdcaedc7d Mon Sep 17 00:00:00 2001 From: Sam Vervaeck Date: Mon, 20 Nov 2023 13:47:27 +0100 Subject: [PATCH 117/170] Fix Yarn 4 failing to install due to jscodeshift dependency issue --- code/lib/codemod/package.json | 2 +- code/lib/postinstall/package.json | 2 +- code/yarn.lock | 56 ++----------------------------- 3 files changed, 4 insertions(+), 56 deletions(-) diff --git a/code/lib/codemod/package.json b/code/lib/codemod/package.json index c805f990a8de..9f8c8af0dbf9 100644 --- a/code/lib/codemod/package.json +++ b/code/lib/codemod/package.json @@ -62,7 +62,7 @@ "@types/cross-spawn": "^6.0.2", "cross-spawn": "^7.0.3", "globby": "^11.0.2", - "jscodeshift": "^0.14.0", + "jscodeshift": "^0.15.1", "lodash": "^4.17.21", "prettier": "^2.8.0", "recast": "^0.23.1" diff --git a/code/lib/postinstall/package.json b/code/lib/postinstall/package.json index a9779b34bd82..9e2a19920e07 100644 --- a/code/lib/postinstall/package.json +++ b/code/lib/postinstall/package.json @@ -47,7 +47,7 @@ "devDependencies": { "jest": "^29.7.0", "jest-specific-snapshot": "^8.0.0", - "jscodeshift": "^0.14.0", + "jscodeshift": "^0.15.1", "typescript": "~4.9.3" }, "publishConfig": { diff --git a/code/yarn.lock b/code/yarn.lock index 3999f341dbe2..90e5ab5564a5 100644 --- a/code/yarn.lock +++ b/code/yarn.lock @@ -6317,7 +6317,7 @@ __metadata: globby: "npm:^11.0.2" jest: "npm:^29.7.0" jest-specific-snapshot: "npm:^8.0.0" - jscodeshift: "npm:^0.14.0" + jscodeshift: "npm:^0.15.1" lodash: "npm:^4.17.21" mdast-util-mdx-jsx: "npm:^2.1.2" mdast-util-mdxjs-esm: "npm:^1.3.1" @@ -6922,7 +6922,7 @@ __metadata: dependencies: jest: "npm:^29.7.0" jest-specific-snapshot: "npm:^8.0.0" - jscodeshift: "npm:^0.14.0" + jscodeshift: "npm:^0.15.1" typescript: "npm:~4.9.3" languageName: unknown linkType: soft @@ -11154,15 +11154,6 @@ __metadata: languageName: node linkType: hard -"ast-types@npm:0.15.2": - version: 0.15.2 - resolution: "ast-types@npm:0.15.2" - dependencies: - tslib: "npm:^2.0.1" - checksum: 5b26e3656e9e8d1db8c8d14971d0cb88ca0138aacce72171cb4cd4555fc8dc53c07e821c568e57fe147366931708fefd25cb9d7e880d42ce9cb569947844c962 - languageName: node - linkType: hard - "ast-types@npm:^0.16.1": version: 0.16.1 resolution: "ast-types@npm:0.16.1" @@ -20127,37 +20118,6 @@ __metadata: languageName: node linkType: hard -"jscodeshift@npm:^0.14.0": - version: 0.14.0 - resolution: "jscodeshift@npm:0.14.0" - dependencies: - "@babel/core": "npm:^7.13.16" - "@babel/parser": "npm:^7.13.16" - "@babel/plugin-proposal-class-properties": "npm:^7.13.0" - "@babel/plugin-proposal-nullish-coalescing-operator": "npm:^7.13.8" - "@babel/plugin-proposal-optional-chaining": "npm:^7.13.12" - "@babel/plugin-transform-modules-commonjs": "npm:^7.13.8" - "@babel/preset-flow": "npm:^7.13.13" - "@babel/preset-typescript": "npm:^7.13.0" - "@babel/register": "npm:^7.13.16" - babel-core: "npm:^7.0.0-bridge.0" - chalk: "npm:^4.1.2" - flow-parser: "npm:0.*" - graceful-fs: "npm:^4.2.4" - micromatch: "npm:^4.0.4" - neo-async: "npm:^2.5.0" - node-dir: "npm:^0.1.17" - recast: "npm:^0.21.0" - temp: "npm:^0.8.4" - write-file-atomic: "npm:^2.3.0" - peerDependencies: - "@babel/preset-env": ^7.1.6 - bin: - jscodeshift: bin/jscodeshift.js - checksum: dab63bdb4b7e67d79634fcd3f5dc8b227146e9f68aa88700bc49c5a45b6339d05bd934a98aa53d29abd04f81237d010e7e037799471b2aab66ec7b9a7d752786 - languageName: node - linkType: hard - "jscodeshift@npm:^0.15.1": version: 0.15.1 resolution: "jscodeshift@npm:0.15.1" @@ -25954,18 +25914,6 @@ __metadata: languageName: node linkType: hard -"recast@npm:^0.21.0": - version: 0.21.5 - resolution: "recast@npm:0.21.5" - dependencies: - ast-types: "npm:0.15.2" - esprima: "npm:~4.0.0" - source-map: "npm:~0.6.1" - tslib: "npm:^2.0.1" - checksum: a45168c82195f24fa2c70293a624fece0069a2e8e8adb637f9963777735f81cb3bb62e55172db677ec3573b08b2daaf1eddd85b74da6fe0bd37c9b15eeaf94b4 - languageName: node - linkType: hard - "recast@npm:^0.23.1, recast@npm:^0.23.3": version: 0.23.4 resolution: "recast@npm:0.23.4" From f1d57e9a928eeb6afe29d32010148640227fcd74 Mon Sep 17 00:00:00 2001 From: Norbert de Langen Date: Mon, 20 Nov 2023 14:09:44 +0100 Subject: [PATCH 118/170] arg windows --- .../__tests__/remove-mdx-stories.test.ts | 107 ++++++++---------- 1 file changed, 47 insertions(+), 60 deletions(-) diff --git a/code/lib/core-server/src/utils/__tests__/remove-mdx-stories.test.ts b/code/lib/core-server/src/utils/__tests__/remove-mdx-stories.test.ts index 5438e48edfe9..18223c63c38a 100644 --- a/code/lib/core-server/src/utils/__tests__/remove-mdx-stories.test.ts +++ b/code/lib/core-server/src/utils/__tests__/remove-mdx-stories.test.ts @@ -7,16 +7,19 @@ import { removeMDXEntries } from '../remove-mdx-entries'; const glob = globlOriginal as jest.MockedFunction; +const configDir = '/configDir/'; +const workingDir = '/'; + jest.mock('glob', () => ({ glob: jest.fn() })); -const createList = (list: { entry: StoriesEntry; result: string[] }[], configDir: string) => { +const createList = (list: { entry: StoriesEntry; result: string[] }[]) => { return list.reduce>( (acc, { entry, result }) => { const { directory, files } = normalizeStoriesEntry(entry, { configDir, - workingDir: '/', + workingDir, }); - acc[join('/', directory, files)] = { result, entry }; + acc[slash(join('/', directory, files))] = { result, entry }; return acc; }, {} @@ -28,15 +31,17 @@ const createGlobMock = (input: ReturnType) => { if (Array.isArray(k)) { throw new Error('do not pass an array to glob during tests'); } - const result = input[slash(k)].result || []; - return result; + if (input[slash(k)]) { + return input[slash(k)]?.result; + } + + console.log({ k, input }); + throw new Error('can not find key in input'); }; }; -const configDir = '/configDir/'; - test('empty', async () => { - const list = createList([], configDir); + const list = createList([]); glob.mockImplementation(createGlobMock(list)); await expect(() => removeMDXEntries(Object.keys(list), { configDir })).rejects @@ -52,7 +57,7 @@ test('empty', async () => { }); test('minimal', async () => { - const list = createList([{ entry: '*.js', result: [] }], configDir); + const list = createList([{ entry: '*.js', result: [] }]); glob.mockImplementation(createGlobMock(list)); await expect( @@ -73,13 +78,10 @@ test('minimal', async () => { }); test('multiple', async () => { - const list = createList( - [ - { entry: '*.ts', result: [] }, - { entry: '*.js', result: [] }, - ], - configDir - ); + const list = createList([ + { entry: '*.ts', result: [] }, + { entry: '*.js', result: [] }, + ]); glob.mockImplementation(createGlobMock(list)); await expect( @@ -106,13 +108,10 @@ test('multiple', async () => { }); test('mdx but not matching any files', async () => { - const list = createList( - [ - { entry: '*.mdx', result: [] }, - { entry: '*.js', result: [] }, - ], - configDir - ); + const list = createList([ + { entry: '*.mdx', result: [] }, + { entry: '*.js', result: [] }, + ]); glob.mockImplementation(createGlobMock(list)); await expect( @@ -139,13 +138,10 @@ test('mdx but not matching any files', async () => { }); test('removes entries that only yield mdx files', async () => { - const list = createList( - [ - { entry: '*.mdx', result: ['/configDir/my-file.mdx'] }, - { entry: '*.js', result: [] }, - ], - configDir - ); + const list = createList([ + { entry: '*.mdx', result: ['/configDir/my-file.mdx'] }, + { entry: '*.js', result: [] }, + ]); glob.mockImplementation(createGlobMock(list)); await expect( @@ -166,13 +162,10 @@ test('removes entries that only yield mdx files', async () => { }); test('expands entries that only yield mixed files', async () => { - const list = createList( - [ - { entry: '*.@(mdx|ts)', result: ['/configDir/my-file.mdx', '/configDir/my-file.ts'] }, - { entry: '*.js', result: [] }, - ], - configDir - ); + const list = createList([ + { entry: '*.@(mdx|ts)', result: ['/configDir/my-file.mdx', '/configDir/my-file.ts'] }, + { entry: '*.js', result: [] }, + ]); glob.mockImplementation(createGlobMock(list)); await expect( @@ -198,15 +191,12 @@ test('expands entries that only yield mixed files', async () => { }); test('passes titlePrefix', async () => { - const list = createList( - [ - { - entry: { files: '*.@(mdx|ts)', directory: '.', titlePrefix: 'foo' }, - result: ['/configDir/my-file.mdx', '/configDir/my-file.ts'], - }, - ], - configDir - ); + const list = createList([ + { + entry: { files: '*.@(mdx|ts)', directory: '.', titlePrefix: 'foo' }, + result: ['/configDir/my-file.mdx', '/configDir/my-file.ts'], + }, + ]); glob.mockImplementation(createGlobMock(list)); await expect( @@ -226,20 +216,17 @@ test('passes titlePrefix', async () => { }); test('expands to multiple entries', async () => { - const list = createList( - [ - { - entry: { files: '*.@(mdx|ts)', directory: '.', titlePrefix: 'foo' }, - result: [ - '/configDir/my-file.mdx', - '/configDir/my-file1.ts', - '/configDir/my-file2.ts', - '/configDir/my-file3.ts', - ], - }, - ], - configDir - ); + const list = createList([ + { + entry: { files: '*.@(mdx|ts)', directory: '.', titlePrefix: 'foo' }, + result: [ + '/configDir/my-file.mdx', + '/configDir/my-file1.ts', + '/configDir/my-file2.ts', + '/configDir/my-file3.ts', + ], + }, + ]); glob.mockImplementation(createGlobMock(list)); await expect( From 27fd45d13b7ac7b3dd6effdf97e6965b9f4e6e64 Mon Sep 17 00:00:00 2001 From: Norbert de Langen Date: Mon, 20 Nov 2023 14:30:59 +0100 Subject: [PATCH 119/170] imprvoe, fix tests for windows --- .../__tests__/remove-mdx-stories.test.ts | 92 +++++++++---------- .../src/utils/remove-mdx-entries.ts | 2 +- 2 files changed, 43 insertions(+), 51 deletions(-) diff --git a/code/lib/core-server/src/utils/__tests__/remove-mdx-stories.test.ts b/code/lib/core-server/src/utils/__tests__/remove-mdx-stories.test.ts index 18223c63c38a..3ad458b287ab 100644 --- a/code/lib/core-server/src/utils/__tests__/remove-mdx-stories.test.ts +++ b/code/lib/core-server/src/utils/__tests__/remove-mdx-stories.test.ts @@ -35,7 +35,6 @@ const createGlobMock = (input: ReturnType) => { return input[slash(k)]?.result; } - console.log({ k, input }); throw new Error('can not find key in input'); }; }; @@ -60,17 +59,16 @@ test('minimal', async () => { const list = createList([{ entry: '*.js', result: [] }]); glob.mockImplementation(createGlobMock(list)); - await expect( - removeMDXEntries( - Object.values(list).map((e) => e.entry), - { configDir } - ) - ).resolves.toMatchInlineSnapshot(` + const result = await removeMDXEntries( + Object.values(list).map((e) => e.entry), + { configDir } + ); + + expect(result.map(({ importPathMatcher, ...v }) => v)).toMatchInlineSnapshot(` Array [ Object { "directory": ".", "files": "*.js", - "importPathMatcher": /\\^\\\\\\.\\[\\\\\\\\/\\]\\(\\?:\\(\\?!\\\\\\.\\)\\(\\?=\\.\\)\\[\\^/\\]\\*\\?\\\\\\.js\\)\\$/, "titlePrefix": "", }, ] @@ -84,23 +82,21 @@ test('multiple', async () => { ]); glob.mockImplementation(createGlobMock(list)); - await expect( - removeMDXEntries( - Object.values(list).map((e) => e.entry), - { configDir } - ) - ).resolves.toMatchInlineSnapshot(` + const result = await removeMDXEntries( + Object.values(list).map((e) => e.entry), + { configDir } + ); + + expect(result.map(({ importPathMatcher, ...v }) => v)).toMatchInlineSnapshot(` Array [ Object { "directory": ".", "files": "*.ts", - "importPathMatcher": /\\^\\\\\\.\\[\\\\\\\\/\\]\\(\\?:\\(\\?!\\\\\\.\\)\\(\\?=\\.\\)\\[\\^/\\]\\*\\?\\\\\\.ts\\)\\$/, "titlePrefix": "", }, Object { "directory": ".", "files": "*.js", - "importPathMatcher": /\\^\\\\\\.\\[\\\\\\\\/\\]\\(\\?:\\(\\?!\\\\\\.\\)\\(\\?=\\.\\)\\[\\^/\\]\\*\\?\\\\\\.js\\)\\$/, "titlePrefix": "", }, ] @@ -114,23 +110,21 @@ test('mdx but not matching any files', async () => { ]); glob.mockImplementation(createGlobMock(list)); - await expect( - removeMDXEntries( - Object.values(list).map((e) => e.entry), - { configDir } - ) - ).resolves.toMatchInlineSnapshot(` + const result = await removeMDXEntries( + Object.values(list).map((e) => e.entry), + { configDir } + ); + + expect(result.map(({ importPathMatcher, ...v }) => v)).toMatchInlineSnapshot(` Array [ Object { "directory": ".", "files": "*.mdx", - "importPathMatcher": /\\^\\\\\\.\\[\\\\\\\\/\\]\\(\\?:\\(\\?!\\\\\\.\\)\\(\\?=\\.\\)\\[\\^/\\]\\*\\?\\\\\\.mdx\\)\\$/, "titlePrefix": "", }, Object { "directory": ".", "files": "*.js", - "importPathMatcher": /\\^\\\\\\.\\[\\\\\\\\/\\]\\(\\?:\\(\\?!\\\\\\.\\)\\(\\?=\\.\\)\\[\\^/\\]\\*\\?\\\\\\.js\\)\\$/, "titlePrefix": "", }, ] @@ -144,17 +138,16 @@ test('removes entries that only yield mdx files', async () => { ]); glob.mockImplementation(createGlobMock(list)); - await expect( - removeMDXEntries( - Object.values(list).map((e) => e.entry), - { configDir } - ) - ).resolves.toMatchInlineSnapshot(` + const result = await removeMDXEntries( + Object.values(list).map((e) => e.entry), + { configDir } + ); + + expect(result.map(({ importPathMatcher, ...v }) => v)).toMatchInlineSnapshot(` Array [ Object { "directory": ".", "files": "*.js", - "importPathMatcher": /\\^\\\\\\.\\[\\\\\\\\/\\]\\(\\?:\\(\\?!\\\\\\.\\)\\(\\?=\\.\\)\\[\\^/\\]\\*\\?\\\\\\.js\\)\\$/, "titlePrefix": "", }, ] @@ -168,12 +161,12 @@ test('expands entries that only yield mixed files', async () => { ]); glob.mockImplementation(createGlobMock(list)); - await expect( - removeMDXEntries( - Object.values(list).map((e) => e.entry), - { configDir } - ) - ).resolves.toMatchInlineSnapshot(` + const result = await removeMDXEntries( + Object.values(list).map((e) => e.entry), + { configDir } + ); + + expect(result.map(({ importPathMatcher, ...v }) => v)).toMatchInlineSnapshot(` Array [ Object { "directory": ".", @@ -183,7 +176,6 @@ test('expands entries that only yield mixed files', async () => { Object { "directory": ".", "files": "*.js", - "importPathMatcher": /\\^\\\\\\.\\[\\\\\\\\/\\]\\(\\?:\\(\\?!\\\\\\.\\)\\(\\?=\\.\\)\\[\\^/\\]\\*\\?\\\\\\.js\\)\\$/, "titlePrefix": "", }, ] @@ -199,12 +191,12 @@ test('passes titlePrefix', async () => { ]); glob.mockImplementation(createGlobMock(list)); - await expect( - removeMDXEntries( - Object.values(list).map((e) => e.entry), - { configDir } - ) - ).resolves.toMatchInlineSnapshot(` + const result = await removeMDXEntries( + Object.values(list).map((e) => e.entry), + { configDir } + ); + + expect(result.map(({ importPathMatcher, ...v }) => v)).toMatchInlineSnapshot(` Array [ Object { "directory": ".", @@ -229,12 +221,12 @@ test('expands to multiple entries', async () => { ]); glob.mockImplementation(createGlobMock(list)); - await expect( - removeMDXEntries( - Object.values(list).map((e) => e.entry), - { configDir } - ) - ).resolves.toMatchInlineSnapshot(` + const result = await removeMDXEntries( + Object.values(list).map((e) => e.entry), + { configDir } + ); + + expect(result.map(({ importPathMatcher, ...v }) => v)).toMatchInlineSnapshot(` Array [ Object { "directory": ".", diff --git a/code/lib/core-server/src/utils/remove-mdx-entries.ts b/code/lib/core-server/src/utils/remove-mdx-entries.ts index 0efc7923baad..e53c4420e203 100644 --- a/code/lib/core-server/src/utils/remove-mdx-entries.ts +++ b/code/lib/core-server/src/utils/remove-mdx-entries.ts @@ -7,7 +7,7 @@ import { glob } from 'glob'; export async function removeMDXEntries( entries: StoriesEntry[], options: Pick -) { +): Promise[]> { const list = normalizeStories(entries, { configDir: options.configDir, workingDir: options.configDir, From 5cdee70c1a20edef996ff02161e824ef53d36783 Mon Sep 17 00:00:00 2001 From: Norbert de Langen Date: Mon, 20 Nov 2023 14:35:04 +0100 Subject: [PATCH 120/170] oops --- code/lib/core-server/src/utils/remove-mdx-entries.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/code/lib/core-server/src/utils/remove-mdx-entries.ts b/code/lib/core-server/src/utils/remove-mdx-entries.ts index e53c4420e203..e1e763ca6043 100644 --- a/code/lib/core-server/src/utils/remove-mdx-entries.ts +++ b/code/lib/core-server/src/utils/remove-mdx-entries.ts @@ -7,7 +7,7 @@ import { glob } from 'glob'; export async function removeMDXEntries( entries: StoriesEntry[], options: Pick -): Promise[]> { +): Promise> { const list = normalizeStories(entries, { configDir: options.configDir, workingDir: options.configDir, From 1e82d194d050647e7a6d43460503fbb137fffd39 Mon Sep 17 00:00:00 2001 From: Norbert de Langen Date: Mon, 20 Nov 2023 14:57:01 +0100 Subject: [PATCH 121/170] aaaa --- .../utils/__tests__/remove-mdx-stories.test.ts | 14 +++++++------- .../core-server/src/utils/remove-mdx-entries.ts | 15 +++++++++------ 2 files changed, 16 insertions(+), 13 deletions(-) diff --git a/code/lib/core-server/src/utils/__tests__/remove-mdx-stories.test.ts b/code/lib/core-server/src/utils/__tests__/remove-mdx-stories.test.ts index 3ad458b287ab..93280240e74e 100644 --- a/code/lib/core-server/src/utils/__tests__/remove-mdx-stories.test.ts +++ b/code/lib/core-server/src/utils/__tests__/remove-mdx-stories.test.ts @@ -64,7 +64,7 @@ test('minimal', async () => { { configDir } ); - expect(result.map(({ importPathMatcher, ...v }) => v)).toMatchInlineSnapshot(` + expect(result).toMatchInlineSnapshot(` Array [ Object { "directory": ".", @@ -87,7 +87,7 @@ test('multiple', async () => { { configDir } ); - expect(result.map(({ importPathMatcher, ...v }) => v)).toMatchInlineSnapshot(` + expect(result).toMatchInlineSnapshot(` Array [ Object { "directory": ".", @@ -115,7 +115,7 @@ test('mdx but not matching any files', async () => { { configDir } ); - expect(result.map(({ importPathMatcher, ...v }) => v)).toMatchInlineSnapshot(` + expect(result).toMatchInlineSnapshot(` Array [ Object { "directory": ".", @@ -143,7 +143,7 @@ test('removes entries that only yield mdx files', async () => { { configDir } ); - expect(result.map(({ importPathMatcher, ...v }) => v)).toMatchInlineSnapshot(` + expect(result).toMatchInlineSnapshot(` Array [ Object { "directory": ".", @@ -166,7 +166,7 @@ test('expands entries that only yield mixed files', async () => { { configDir } ); - expect(result.map(({ importPathMatcher, ...v }) => v)).toMatchInlineSnapshot(` + expect(result).toMatchInlineSnapshot(` Array [ Object { "directory": ".", @@ -196,7 +196,7 @@ test('passes titlePrefix', async () => { { configDir } ); - expect(result.map(({ importPathMatcher, ...v }) => v)).toMatchInlineSnapshot(` + expect(result).toMatchInlineSnapshot(` Array [ Object { "directory": ".", @@ -226,7 +226,7 @@ test('expands to multiple entries', async () => { { configDir } ); - expect(result.map(({ importPathMatcher, ...v }) => v)).toMatchInlineSnapshot(` + expect(result).toMatchInlineSnapshot(` Array [ Object { "directory": ".", diff --git a/code/lib/core-server/src/utils/remove-mdx-entries.ts b/code/lib/core-server/src/utils/remove-mdx-entries.ts index e1e763ca6043..ed93c1bc8d64 100644 --- a/code/lib/core-server/src/utils/remove-mdx-entries.ts +++ b/code/lib/core-server/src/utils/remove-mdx-entries.ts @@ -7,7 +7,7 @@ import { glob } from 'glob'; export async function removeMDXEntries( entries: StoriesEntry[], options: Pick -): Promise> { +): Promise { const list = normalizeStories(entries, { configDir: options.configDir, workingDir: options.configDir, @@ -34,18 +34,21 @@ export async function removeMDXEntries( }; }) ) - ).flatMap((expanded, i) => { - const filteredEntries = expanded.files.filter((s) => !s.endsWith('.mdx')); + ).flatMap(({ directory, files, titlePrefix }, i) => { + const filteredEntries = files.filter((s) => !s.endsWith('.mdx')); // only return the filtered entries when there is something to filter // as webpack is faster with unexpanded globs let items = []; - if (filteredEntries.length < expanded.files.length) { + if (filteredEntries.length < files.length) { items = filteredEntries.map((k) => ({ - ...expanded, + directory, + titlePrefix, files: `**/${k}`, })); } else { - items = [list[i]]; + items = [ + { directory: list[i].directory, titlePrefix: list[i].titlePrefix, files: list[i].files }, + ]; } return items; From 9e3c955fec7d7b1b7edfb2478dd6fa76ac9af510 Mon Sep 17 00:00:00 2001 From: jonniebigodes Date: Mon, 20 Nov 2023 14:10:16 +0000 Subject: [PATCH 122/170] Docs: Minor changes for code contribution docs --- docs/contribute/code.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/contribute/code.md b/docs/contribute/code.md index 7ce0068157bb..323737cfb621 100644 --- a/docs/contribute/code.md +++ b/docs/contribute/code.md @@ -6,7 +6,7 @@ Contribute a new feature or bug fix to [Storybook's monorepo](https://github.com ## Prerequisites -- Ensure you have node version 16 installed (suggestion: v16.17.1). +- Ensure you have node version 18 installed (suggestion: v18.16.0). - Ensure if you are using Windows to use the Windows Subsystem for Linux (WSL). ## Initial setup @@ -18,7 +18,7 @@ git clone https://github.com/your-username/storybook.git cd storybook ``` -Storybook uses the [yarn](https://v3.yarnpkg.com/) package manager. Use [Corepack](https://github.com/nodejs/corepack) to set up the correct version for use with Storybook. +Storybook uses the [Yarn](https://yarnpkg.com/) package manager. Use [Corepack](https://github.com/nodejs/corepack) to set up the correct version for use with Storybook. ```shell corepack enable @@ -201,7 +201,7 @@ npx storybook@next link --local /path/to/local-repro-directory -The `storybook link` command relies on [Yarn 2 linking](https://yarnpkg.com/cli/link/) under the hood. It requires your local reproduction to be using [Yarn 2](https://yarnpkg.com/) as well, which is the case if you're already enabled it with the [`storybook sandbox`](./how-to-reproduce.md) command per our contribution guidelines. The process will fail if you're trying to link a non-Yarn 2 project. +The `storybook link` command relies on [Yarn linking](https://yarnpkg.com/cli/link/) under the hood. It requires your local reproduction to be using [Yarn 2 or higher](https://yarnpkg.com/) as well, which is the case if you've already enabled it with the [`storybook sandbox`](./how-to-reproduce.md) command per our contribution guidelines. The process will fail if you're trying to link a non-Yarn 2 project. From d859e391a03d14f10ffb6a277ace48c9e6125b81 Mon Sep 17 00:00:00 2001 From: jonniebigodes Date: Mon, 20 Nov 2023 14:48:36 +0000 Subject: [PATCH 123/170] Capitalize Node --- docs/contribute/code.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/contribute/code.md b/docs/contribute/code.md index 323737cfb621..1ce7726caf3e 100644 --- a/docs/contribute/code.md +++ b/docs/contribute/code.md @@ -6,7 +6,7 @@ Contribute a new feature or bug fix to [Storybook's monorepo](https://github.com ## Prerequisites -- Ensure you have node version 18 installed (suggestion: v18.16.0). +- Ensure you have Node version 18 installed (suggestion: v18.16.0). - Ensure if you are using Windows to use the Windows Subsystem for Linux (WSL). ## Initial setup From a55ac767b2027eccfb68d80d945c3d7904819922 Mon Sep 17 00:00:00 2001 From: paoloricciuti Date: Mon, 20 Nov 2023 18:38:59 +0100 Subject: [PATCH 124/170] fix: svelte renderer run decorators twice --- .../svelte/templates/PreviewRender.svelte | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/code/renderers/svelte/templates/PreviewRender.svelte b/code/renderers/svelte/templates/PreviewRender.svelte index 7747cd8fcaba..581aa4d78e05 100644 --- a/code/renderers/svelte/templates/PreviewRender.svelte +++ b/code/renderers/svelte/templates/PreviewRender.svelte @@ -17,8 +17,25 @@ on, } = storyFn(); + let firstTime = true; + + // the first time we don't want to call storyFn two times so we just return the values + // we already have from the previous call. If storyFn changes this function will run + // again but this time firstTime will be false + function getStoryFnValue(storyFn){ + if(firstTime){ + firstTime = false; + return { + Component, + props, + on, + } + } + return storyFn(); + } + // reactive, re-render on storyFn change - $: ({ Component, props = {}, on } = storyFn()); + $: ({ Component, props = {}, on } = getStoryFnValue(storyFn)); const eventsFromArgTypes = Object.fromEntries( Object.entries(storyContext.argTypes) From 96e093fc0f993e45fc7f29f9b6eff63cbe1e25cb Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Mon, 20 Nov 2023 19:23:18 +0100 Subject: [PATCH 125/170] Next.js: Fix import path in swc loader --- code/frameworks/nextjs/src/swc/loader.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/code/frameworks/nextjs/src/swc/loader.ts b/code/frameworks/nextjs/src/swc/loader.ts index 201bdc52e0d8..687f60d8aefe 100644 --- a/code/frameworks/nextjs/src/swc/loader.ts +++ b/code/frameworks/nextjs/src/swc/loader.ts @@ -6,7 +6,7 @@ import type { NextConfig } from 'next'; import path from 'path'; import type { RuleSetRule } from 'webpack'; import semver from 'semver'; -import { NextjsSWCNotSupportedError } from 'lib/core-events/src/errors/server-errors'; +import { NextjsSWCNotSupportedError } from '@storybook/core-events/server-errors'; import { getNextjsVersion } from '../utils'; export const configureSWCLoader = async ( From 4a7b7e0a98f7d3c1440a6de90b3f4f7f8032c76e Mon Sep 17 00:00:00 2001 From: paoloricciuti Date: Mon, 20 Nov 2023 20:43:18 +0100 Subject: [PATCH 126/170] add test for decorators run once --- code/e2e-tests/framework-svelte.spec.ts | 11 +++++++++++ .../stories/decorators-runs-once.stories.js | 16 ++++++++++++++++ 2 files changed, 27 insertions(+) create mode 100644 code/renderers/svelte/template/stories/decorators-runs-once.stories.js diff --git a/code/e2e-tests/framework-svelte.spec.ts b/code/e2e-tests/framework-svelte.spec.ts index a208aa982d9c..2b6e447dd232 100644 --- a/code/e2e-tests/framework-svelte.spec.ts +++ b/code/e2e-tests/framework-svelte.spec.ts @@ -50,4 +50,15 @@ test.describe('Svelte', () => { const expectedSource = ''; await expect(sourceCode.textContent()).resolves.toContain(expectedSource); }); + + test('Decorators runs only once', async ({ page }) => { + const sbPage = new SbPage(page); + const lines: string[] = []; + page.on('console', (msg) => { + lines.push(msg.text()); + }); + + await sbPage.navigateToStory('stories/renderers/svelte/decorators-runs-once', 'default'); + expect(lines).toHaveLength(1); + }); }); diff --git a/code/renderers/svelte/template/stories/decorators-runs-once.stories.js b/code/renderers/svelte/template/stories/decorators-runs-once.stories.js new file mode 100644 index 000000000000..649d9f8a18bb --- /dev/null +++ b/code/renderers/svelte/template/stories/decorators-runs-once.stories.js @@ -0,0 +1,16 @@ +import ButtonJavaScript from './views/ButtonJavaScript.svelte'; + +export default { + component: ButtonJavaScript, + args: { + primary: true, + }, + decorators: [ + (Story) => { + console.log('decorator'); + return Story(); + }, + ], +}; + +export const Default = {}; From 00113197e573b7c0e66786124af2165f6067d136 Mon Sep 17 00:00:00 2001 From: Ian VanSchooten Date: Mon, 20 Nov 2023 16:29:08 -0500 Subject: [PATCH 127/170] FastBuild: Fix disabledAddons filter --- code/lib/core-common/src/presets.test.ts | 64 ++++++++++++++++++++++++ code/lib/core-common/src/presets.ts | 2 +- 2 files changed, 65 insertions(+), 1 deletion(-) diff --git a/code/lib/core-common/src/presets.test.ts b/code/lib/core-common/src/presets.test.ts index 667f1d01781e..6a283f566b8c 100644 --- a/code/lib/core-common/src/presets.test.ts +++ b/code/lib/core-common/src/presets.test.ts @@ -655,4 +655,68 @@ describe('loadPreset', () => { ] `); }); + + it('should filter out disabledAddons', async () => { + const loaded = await loadPreset( + { + name: '', + type: 'virtual', + framework: '@storybook/react', + presets: ['@storybook/preset-typescript'], + addons: ['@storybook/addon-docs', 'addon-bar'], + }, + 0, + { + build: { + test: { + disabledAddons: ['@storybook/addon-docs'], + }, + }, + } + ); + + // addon-docs should not be at the top level, but addon-bar and others should be. + expect(loaded).toMatchInlineSnapshot(` + Array [ + Object { + "name": "@storybook/preset-typescript", + "options": Object {}, + "preset": Object {}, + }, + Object { + "name": "@storybook/addon-interactions/preset", + "options": Object {}, + "preset": Object {}, + }, + Object { + "name": "@storybook/addon-cool", + "options": Object {}, + "preset": Object {}, + }, + Object { + "name": "addon-bar", + "options": Object {}, + "preset": Object {}, + }, + Object { + "name": Object { + "addons": Array [ + "@storybook/addon-docs", + "addon-bar", + ], + "framework": "@storybook/react", + "name": "", + "presets": Array [ + "@storybook/preset-typescript", + ], + "type": "virtual", + }, + "options": Object {}, + "preset": Object { + "framework": "@storybook/react", + }, + }, + ] + `); + }); }); diff --git a/code/lib/core-common/src/presets.ts b/code/lib/core-common/src/presets.ts index 8cc613a33b3f..407ff1775d3c 100644 --- a/code/lib/core-common/src/presets.ts +++ b/code/lib/core-common/src/presets.ts @@ -261,7 +261,7 @@ export async function loadPreset( // @ts-expect-error (Converted from ts-ignore) const name = i.name ? i.name : i; - return !!storybookOptions.build?.test?.disabledAddons?.find((n) => name.includes(n)); + return !storybookOptions.build?.test?.disabledAddons?.find((n) => name.includes(n)); }; } From 445b8d434c7a933dbf4cc6a5cf2d615cc9d8c940 Mon Sep 17 00:00:00 2001 From: paoloricciuti Date: Mon, 20 Nov 2023 23:10:30 +0100 Subject: [PATCH 128/170] move logic to preview.ts from SvelteDecorator --- code/frameworks/sveltekit/package.json | 2 - .../src/components/SvelteDecorator.svelte | 60 ---------------- code/frameworks/sveltekit/src/preview.ts | 68 ++++++++++++++++++- 3 files changed, 65 insertions(+), 65 deletions(-) delete mode 100644 code/frameworks/sveltekit/src/components/SvelteDecorator.svelte diff --git a/code/frameworks/sveltekit/package.json b/code/frameworks/sveltekit/package.json index 21821fb00181..96dd7f81edaa 100644 --- a/code/frameworks/sveltekit/package.json +++ b/code/frameworks/sveltekit/package.json @@ -29,7 +29,6 @@ "require": "./dist/index.js", "import": "./dist/index.mjs" }, - "./src/components/SvelteDecorator.svelte": "./src/components/SvelteDecorator.svelte", "./preview": { "types": "./dist/preview.d.ts", "require": "./dist/preview.js", @@ -54,7 +53,6 @@ "README.md", "*.js", "*.d.ts", - "src/components/**/*", "src/mocks/**/*" ], "scripts": { diff --git a/code/frameworks/sveltekit/src/components/SvelteDecorator.svelte b/code/frameworks/sveltekit/src/components/SvelteDecorator.svelte deleted file mode 100644 index 04654a64e3a5..000000000000 --- a/code/frameworks/sveltekit/src/components/SvelteDecorator.svelte +++ /dev/null @@ -1,60 +0,0 @@ - - - diff --git a/code/frameworks/sveltekit/src/preview.ts b/code/frameworks/sveltekit/src/preview.ts index 54914221f91c..50ac18b9e4d6 100644 --- a/code/frameworks/sveltekit/src/preview.ts +++ b/code/frameworks/sveltekit/src/preview.ts @@ -1,7 +1,6 @@ import type { Decorator } from '@storybook/svelte'; -// eslint-disable-next-line import/no-extraneous-dependencies -import SvelteDecorator from '@storybook/sveltekit/src/components/SvelteDecorator.svelte'; +import { onMount } from 'svelte'; import { setAfterNavigateArgument } from './mocks/app/navigation'; import { setNavigating, setPage, setUpdated } from './mocks/app/stores'; @@ -11,7 +10,70 @@ export const decorators: Decorator[] = [ setUpdated(ctx.parameters?.sveltekit?.stores?.updated); setNavigating(ctx.parameters?.sveltekit?.stores?.navigating); setAfterNavigateArgument(ctx.parameters?.sveltekit?.navigation?.afterNavigate); + + onMount(() => { + const globalClickListener = (e: MouseEvent) => { + const path = e.composedPath(); + const hasLink = path.findLast((el) => el instanceof HTMLElement && el.tagName === 'A'); + if (hasLink && hasLink instanceof HTMLAnchorElement) { + const to = hasLink.getAttribute('href'); + if (ctx?.parameters?.sveltekit?.linkOverrides && to) { + Object.entries(ctx.parameters.sveltekit.linkOverrides).forEach(([link, override]) => { + if (override instanceof Function) { + const regex = new RegExp(link); + if (regex.test(to)) { + override(); + } + } + }); + } + e.preventDefault(); + } + }; + + function createListeners(baseModule: string, functions: string[]) { + const toRemove: Array<{ + eventType: string; + listener: (event: { detail: any[] }) => void; + }> = []; + functions.forEach((func) => { + if ( + ctx?.parameters?.sveltekit?.[baseModule]?.[func] && + ctx.parameters.sveltekit[baseModule][func] instanceof Function + ) { + const listener = ({ detail = [] as any[] }) => { + const args = Array.isArray(detail) ? detail : []; + ctx.parameters.sveltekit[baseModule][func](...args); + }; + const eventType = `storybook:${func}`; + toRemove.push({ eventType, listener }); + // @ts-expect-error apparently you can't add a custom listener to the window with TS + window.addEventListener(eventType, listener); + } + }); + return () => { + toRemove.forEach(({ eventType, listener }) => { + // @ts-expect-error apparently you can't remove a custom listener to the window with TS + window.removeEventListener(eventType, listener); + }); + }; + } + + const removeNavigationListeners = createListeners('navigation', [ + 'goto', + 'invalidate', + 'invalidateAll', + ]); + const removeFormsListeners = createListeners('forms', ['enhance']); + window.addEventListener('click', globalClickListener); + + return () => { + window.removeEventListener('click', globalClickListener); + removeNavigationListeners(); + removeFormsListeners(); + }; + }); + return Story(); }, - (_, ctx) => ({ Component: SvelteDecorator, props: { ctx } }), ]; From c686a26f440d44da875e9dc0e75721a65ce27f3c Mon Sep 17 00:00:00 2001 From: paoloricciuti Date: Mon, 20 Nov 2023 23:33:06 +0100 Subject: [PATCH 129/170] fix CJS to ESM --- code/frameworks/sveltekit/package.json | 5 ++++- code/frameworks/sveltekit/src/preset.ts | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/code/frameworks/sveltekit/package.json b/code/frameworks/sveltekit/package.json index 96dd7f81edaa..7d76f10e7bdc 100644 --- a/code/frameworks/sveltekit/package.json +++ b/code/frameworks/sveltekit/package.json @@ -36,7 +36,10 @@ }, "./dist/preview.js": { "types": "./dist/preview.d.ts", - "require": "./dist/preview.js", + "require": "./dist/preview.js" + }, + "./dist/preview.mjs": { + "types": "./dist/preview.d.ts", "import": "./dist/preview.mjs" }, "./preset": { diff --git a/code/frameworks/sveltekit/src/preset.ts b/code/frameworks/sveltekit/src/preset.ts index 4e765d1631cc..835379149a25 100644 --- a/code/frameworks/sveltekit/src/preset.ts +++ b/code/frameworks/sveltekit/src/preset.ts @@ -15,7 +15,7 @@ export const core: PresetProperty<'core', StorybookConfig> = { }; export const previewAnnotations: StorybookConfig['previewAnnotations'] = (entry = []) => [ ...entry, - require.resolve('@storybook/sveltekit/preview'), + join(dirname(require.resolve('@storybook/sveltekit/package.json')), 'dist/preview.mjs'), ]; export const viteFinal: NonNullable = async (config, options) => { From de04701f13b4f7538373267cc05ca3bfc7ee4411 Mon Sep 17 00:00:00 2001 From: Kyle Gach Date: Mon, 20 Nov 2023 21:16:52 -0700 Subject: [PATCH 130/170] Update help.yml - Remove `render` attribute from Additional information textarea - That property will force input into a code block, but we're asking for information that would best fit in multiple code blocks - Add `id` for debugging purposes - Attempt to fix formatting issues --- .github/DISCUSSION_TEMPLATE/help.yml | 71 +++++++++++++++------------- 1 file changed, 37 insertions(+), 34 deletions(-) diff --git a/.github/DISCUSSION_TEMPLATE/help.yml b/.github/DISCUSSION_TEMPLATE/help.yml index 5664b2b8fdbb..2b74e6d0dcf8 100644 --- a/.github/DISCUSSION_TEMPLATE/help.yml +++ b/.github/DISCUSSION_TEMPLATE/help.yml @@ -1,37 +1,40 @@ body: - - type: markdown - attributes: - value: | - Thanks for taking the time to start a new discussion! - - ### Before you post - Check if someone has already asked/answered your question in a previous discussion. - - ### When you're ready to post - Add labels to your discussion (e.g. React, Vue, Vite) to make it clearer for other users. +- type: markdown + id: intro + attributes: + value: | + Thanks for taking the time to start a new discussion! + + ### Before you post + Check if someone has already asked/answered your question in a previous discussion. + + ### When you're ready to post + Add labels to your discussion (e.g. React, Vue, Vite) to make it clearer for other users. - - type: textarea - attributes: - label: Summary - description: How can we help? - validations: - required: true - - - type: textarea - attributes: - label: Additional information - description: | - Share Your Storybook configuration (`main.js` or `main.ts`), your Storybook version number, any error messages, and any relevant dependencies. These help us get a clearer understanding of what might be going wrong. +- type: textarea + id: summary + attributes: + label: Summary + description: How can we help? + validations: + required: true + +- type: textarea + id: additional-info + attributes: + label: Additional information + description: | + Share Your Storybook configuration (`main.js` or `main.ts`), your Storybook version number, any error messages, and any relevant dependencies. These help us get a clearer understanding of what might be going wrong. - P.S. Please [share code as text](https://docs.github.com/en/get-started/writing-on-github/working-with-advanced-formatting/creating-and-highlighting-code-blocks) rather than as a screenshot! It makes debugging much easier and faster. - render: js - validations: - required: false - - - type: input - attributes: - label: Create a reproduction - description: | - Help us debug by creating a minimal reproduction with [https://storybook.new](https://storybook.new). Learn more about creating a reproduction [here](https://storybook.js.org/docs/react/contribute/how-to-reproduce). - validations: - required: false + P.S. Please [share code as text](https://docs.github.com/en/get-started/writing-on-github/working-with-advanced-formatting/creating-and-highlighting-code-blocks) rather than as a screenshot! It makes debugging much easier and faster. + validations: + required: false + +- type: input + id: reproduction + attributes: + label: Create a reproduction + description: | + Help us debug by creating a minimal reproduction with [https://storybook.new](https://storybook.new). Learn more about creating a reproduction [here](https://storybook.js.org/docs/react/contribute/how-to-reproduce). + validations: + required: false From a6ad3528c9dc0377c8770486e7fbafff8f286763 Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Mon, 20 Nov 2023 13:04:42 +0100 Subject: [PATCH 131/170] Use temp dir to init Storybook for sandbox generation --- scripts/sandbox/generate.ts | 32 ++++++++++++++++++++------------ 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/scripts/sandbox/generate.ts b/scripts/sandbox/generate.ts index 8f7ae78fb0d2..ebdf88ac2048 100755 --- a/scripts/sandbox/generate.ts +++ b/scripts/sandbox/generate.ts @@ -71,23 +71,31 @@ const addStorybook = async ({ }) => { const beforeDir = join(baseDir, BEFORE_DIR_NAME); const afterDir = join(baseDir, AFTER_DIR_NAME); - const tmpDir = join(baseDir, 'tmp'); - await ensureDir(tmpDir); - await emptyDir(tmpDir); + const tmpDir = directory(); - await copy(beforeDir, tmpDir); - - const packageManager = JsPackageManagerFactory.getPackageManager({}, tmpDir); - if (localRegistry) { - await withLocalRegistry(packageManager, async () => { - await packageManager.addPackageResolutions(storybookVersions); + try { + await copy(beforeDir, tmpDir); + + const packageManager = JsPackageManagerFactory.getPackageManager({}, tmpDir); + if (localRegistry) { + await withLocalRegistry(packageManager, async () => { + await packageManager.addPackageResolutions({ + ...storybookVersions, + // Yarn1 Issue: https://github.com/storybookjs/storybook/issues/22431 + jackspeak: '2.1.1', + }); + await sbInit(tmpDir, flags, debug); + }); + } else { await sbInit(tmpDir, flags, debug); - }); - } else { - await sbInit(tmpDir, flags, debug); + } + } catch (e) { + await remove(tmpDir); + throw e; } + await rename(tmpDir, afterDir); }; From 40d85f0e44f1bd3f3ee0e7fa5ba112bb4a4a1f1a Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Mon, 20 Nov 2023 13:29:15 +0100 Subject: [PATCH 132/170] Fix Next.js generation --- code/lib/cli/src/sandbox-templates.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/code/lib/cli/src/sandbox-templates.ts b/code/lib/cli/src/sandbox-templates.ts index 7047dc138e16..e8be78844b83 100644 --- a/code/lib/cli/src/sandbox-templates.ts +++ b/code/lib/cli/src/sandbox-templates.ts @@ -120,7 +120,8 @@ const baseTemplates = { }, 'nextjs/default-js': { name: 'Next.js Latest (Webpack | JavaScript)', - script: 'yarn create next-app {{beforeDir}} --javascript --eslint', + script: + 'yarn create next-app {{beforeDir}} --javascript --eslint --tailwind --app --import-alias="@/*" --src-dir', expected: { framework: '@storybook/nextjs', renderer: '@storybook/react', @@ -130,7 +131,8 @@ const baseTemplates = { }, 'nextjs/default-ts': { name: 'Next.js Latest (Webpack | TypeScript)', - script: 'yarn create next-app {{beforeDir}} --typescript --eslint', + script: + 'yarn create next-app {{beforeDir}} --typescript --eslint --tailwind --app --import-alias="@/*" --src-dir', expected: { framework: '@storybook/nextjs', renderer: '@storybook/react', From 8b48f8d9de7f906e9202f2bb9084706e17f5daf1 Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Mon, 20 Nov 2023 13:58:37 +0100 Subject: [PATCH 133/170] Fix Angular sandbox generation --- code/lib/cli/src/sandbox-templates.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/code/lib/cli/src/sandbox-templates.ts b/code/lib/cli/src/sandbox-templates.ts index e8be78844b83..600a01044e56 100644 --- a/code/lib/cli/src/sandbox-templates.ts +++ b/code/lib/cli/src/sandbox-templates.ts @@ -303,7 +303,7 @@ const baseTemplates = { 'angular-cli/prerelease': { name: 'Angular CLI Prerelease (Webpack | TypeScript)', script: - 'npx -p @angular/cli@next ng new angular-v16 --directory {{beforeDir}} --routing=true --minimal=true --style=scss --strict --skip-git --skip-install --package-manager=yarn', + 'npx -p @angular/cli@next ng new angular-v16 --directory {{beforeDir}} --routing=true --minimal=true --style=scss --strict --skip-git --skip-install --package-manager=yarn --ssr', expected: { framework: '@storybook/angular', renderer: '@storybook/angular', @@ -314,7 +314,7 @@ const baseTemplates = { 'angular-cli/default-ts': { name: 'Angular CLI Latest (Webpack | TypeScript)', script: - 'npx -p @angular/cli ng new angular-latest --directory {{beforeDir}} --routing=true --minimal=true --style=scss --strict --skip-git --skip-install --package-manager=yarn', + 'npx -p @angular/cli ng new angular-latest --directory {{beforeDir}} --routing=true --minimal=true --style=scss --strict --skip-git --skip-install --package-manager=yarn --ssr', expected: { framework: '@storybook/angular', renderer: '@storybook/angular', From 8be2ce86531fe109ccff759c55f37a138829fe7f Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Mon, 20 Nov 2023 15:13:18 +0100 Subject: [PATCH 134/170] Set parallelism to one for sandbox generation --- scripts/sandbox/generate.ts | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/scripts/sandbox/generate.ts b/scripts/sandbox/generate.ts index ebdf88ac2048..e14b8bac5f04 100755 --- a/scripts/sandbox/generate.ts +++ b/scripts/sandbox/generate.ts @@ -15,8 +15,6 @@ import { allTemplates as sandboxTemplates } from '../../code/lib/cli/src/sandbox import storybookVersions from '../../code/lib/cli/src/versions'; import { JsPackageManagerFactory } from '../../code/lib/cli/src/js-package-manager/JsPackageManagerFactory'; -import { maxConcurrentTasks } from '../utils/maxConcurrentTasks'; - // eslint-disable-next-line import/no-cycle import { localizeYarnConfigFiles, setupYarn } from './utils/yarn'; import type { GeneratorConfig } from './utils/types'; @@ -139,9 +137,9 @@ const runGenerators = async ( console.log('Debug mode enabled. Verbose logs will be printed to the console.'); } - console.log(`šŸ¤¹ā€ā™‚ļø Generating sandboxes with a concurrency of ${maxConcurrentTasks}`); + console.log(`šŸ¤¹ā€ā™‚ļø Generating sandboxes with a concurrency of ${1}`); - const limit = pLimit(maxConcurrentTasks); + const limit = pLimit(1); await Promise.all( generators.map(({ dirName, name, script, expected }) => From 2d21b392f15177933acd4e35db1b0f5acfa2725d Mon Sep 17 00:00:00 2001 From: Paolo Ricciuti Date: Tue, 21 Nov 2023 10:36:47 +0100 Subject: [PATCH 135/170] Update code/frameworks/sveltekit/README.md Co-authored-by: Jeppe Reinhold --- code/frameworks/sveltekit/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/code/frameworks/sveltekit/README.md b/code/frameworks/sveltekit/README.md index 45ba57592377..7732078170b5 100644 --- a/code/frameworks/sveltekit/README.md +++ b/code/frameworks/sveltekit/README.md @@ -128,7 +128,7 @@ Integrating with SvelteKit would not have been possible if it weren't for the fa ## How to mock -To mock a SvelteKit import you can make use of the `parameters.sveltekit` object either on the `Story`, on the `Template` or on the `Meta` +To mock a SvelteKit import you can set it on `parameters.sveltekit`: ```ts export const MyStory = { From 63b1b0ea4f3f09988e77b26ee3569cf8ed119e11 Mon Sep 17 00:00:00 2001 From: Paolo Ricciuti Date: Tue, 21 Nov 2023 10:37:03 +0100 Subject: [PATCH 136/170] Update code/frameworks/sveltekit/README.md Co-authored-by: Jeppe Reinhold --- code/frameworks/sveltekit/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/code/frameworks/sveltekit/README.md b/code/frameworks/sveltekit/README.md index 7732078170b5..b5cfe70efbf0 100644 --- a/code/frameworks/sveltekit/README.md +++ b/code/frameworks/sveltekit/README.md @@ -152,7 +152,7 @@ export const MyStory = { }; ``` -on this object you can add the name of the module you are mocking (in the example above we are mocking the `stores` module which correspond to `$app/stores`) and than pass the following kind of objects +You can add the name of the module you want to mock to `parameters.sveltekit` (in the example above we are mocking the `stores` module which correspond to `$app/stores`) and then pass the following kind of objects: | Module | Path in parameters | Kind of objects | | ----------------------------------------------- | ----------------------------------------------- | -------------------------------------------------------------------------------------------------- | From 230089a431440c61834f11a3394952a206c5e865 Mon Sep 17 00:00:00 2001 From: paoloricciuti Date: Tue, 21 Nov 2023 10:58:19 +0100 Subject: [PATCH 137/170] fix PR comments --- code/frameworks/sveltekit/README.md | 54 +++++++++---------- .../sveltekit/src/plugins/config-overrides.ts | 31 +++-------- .../src/plugins/mock-sveltekit-stores.ts | 17 ++++++ code/frameworks/sveltekit/src/preset.ts | 5 +- code/frameworks/sveltekit/src/preview.ts | 29 +++++++++- .../links.stories.js | 2 +- .../links.stories.js | 2 +- 7 files changed, 85 insertions(+), 55 deletions(-) create mode 100644 code/frameworks/sveltekit/src/plugins/mock-sveltekit-stores.ts diff --git a/code/frameworks/sveltekit/README.md b/code/frameworks/sveltekit/README.md index b5cfe70efbf0..4bc106cbc445 100644 --- a/code/frameworks/sveltekit/README.md +++ b/code/frameworks/sveltekit/README.md @@ -100,32 +100,6 @@ yarn remove storybook-builder-vite yarn remove @storybook/builder-vite ``` -## Troubleshooting - -### Error: `ERR! SyntaxError: Identifier '__esbuild_register_import_meta_url__' has already been declared` when starting Storybook - -> When starting Storybook after upgrading to v7.0, it breaks with the following error: -> -> ``` -> ERR! SyntaxError: Identifier '__esbuild_register_import_meta_url__' has already been declared -> ``` - -You'll get this error when manually upgrading from 6.5 to 7.0. You need to remove the `svelteOptions` property in `.storybook/main.js`, as that is not supported by Storybook 7.0 + SvelteKit. The property is also not necessary anymore because the Vite and Svelte configurations are loaded automatically in Storybook 7.0. - -### Error: `Cannot read properties of undefined (reading 'disable_scroll_handling')` in preview - -> Some stories don't load, instead they show the following error in the preview: -> -> ``` -> Cannot read properties of undefined (reading 'disable_scroll_handling') -> ``` - -You'll experience this if anything in your story is importing from `$app/forms` or `$app/navigation`, which is currently not supported. To get around this, separate your component into a shallow parent component that imports what's needed and passes it to a child component via props. This way you can write stories for your child component and mock any of the necessary modules by passing props in. - -## Acknowledgements - -Integrating with SvelteKit would not have been possible if it weren't for the fantastic efforts by the Svelte core team - especially [Ben McCann](https://twitter.com/benjaminmccann) - to make integrations with the wider ecosystem possible. - ## How to mock To mock a SvelteKit import you can set it on `parameters.sveltekit`: @@ -167,4 +141,30 @@ You can add the name of the module you want to mock to `parameters.sveltekit` (i All the other functions are still exported as `noop` from the mocked modules so that your application will still work. There was no way of make them work in a customizable way. -Additionally you can pass an object to `parameter.sveltekit.linkOverrides` where the keys are regex representing a link and the values are functions. If you have an `
` tag inside your code with the `href` attribute that matches one or more regex the corresponding function will be called. +Additionally you can pass an object to `parameter.sveltekit.hrefs` where the keys are regex representing a link and the values are functions. If you have an `` tag inside your code with the `href` attribute that matches one or more regex the corresponding function will be called. + +## Troubleshooting + +### Error: `ERR! SyntaxError: Identifier '__esbuild_register_import_meta_url__' has already been declared` when starting Storybook + +> When starting Storybook after upgrading to v7.0, it breaks with the following error: +> +> ``` +> ERR! SyntaxError: Identifier '__esbuild_register_import_meta_url__' has already been declared +> ``` + +You'll get this error when manually upgrading from 6.5 to 7.0. You need to remove the `svelteOptions` property in `.storybook/main.js`, as that is not supported by Storybook 7.0 + SvelteKit. The property is also not necessary anymore because the Vite and Svelte configurations are loaded automatically in Storybook 7.0. + +### Error: `Cannot read properties of undefined (reading 'disable_scroll_handling')` in preview + +> Some stories don't load, instead they show the following error in the preview: +> +> ``` +> Cannot read properties of undefined (reading 'disable_scroll_handling') +> ``` + +You'll experience this if anything in your story is importing from `$app/forms` or `$app/navigation`, which is currently not supported. To get around this, separate your component into a shallow parent component that imports what's needed and passes it to a child component via props. This way you can write stories for your child component and mock any of the necessary modules by passing props in. + +## Acknowledgements + +Integrating with SvelteKit would not have been possible if it weren't for the fantastic efforts by the Svelte core team - especially [Ben McCann](https://twitter.com/benjaminmccann) - to make integrations with the wider ecosystem possible. diff --git a/code/frameworks/sveltekit/src/plugins/config-overrides.ts b/code/frameworks/sveltekit/src/plugins/config-overrides.ts index d1dfcc09919e..d132764d6e5c 100644 --- a/code/frameworks/sveltekit/src/plugins/config-overrides.ts +++ b/code/frameworks/sveltekit/src/plugins/config-overrides.ts @@ -1,27 +1,12 @@ -import { resolve } from 'node:path'; -import { mergeConfig, type Plugin } from 'vite'; +import { type Plugin } from 'vite'; export function configOverrides() { - return [ - { - // SvelteKit sets SSR, we need it to be false when building - name: 'storybook:sveltekit-overrides', - apply: 'build', - config: () => { - return { build: { ssr: false } }; - }, + return { + // SvelteKit sets SSR, we need it to be false when building + name: 'storybook:sveltekit-overrides', + apply: 'build', + config: () => { + return { build: { ssr: false } }; }, - { - name: 'storybook:sveltekit-mock-stores', - enforce: 'post', - config: (config) => - mergeConfig(config, { - resolve: { - alias: { - $app: resolve(__dirname, '../src/mocks/app/'), - }, - }, - }), - }, - ] satisfies Plugin[]; + } satisfies Plugin; } diff --git a/code/frameworks/sveltekit/src/plugins/mock-sveltekit-stores.ts b/code/frameworks/sveltekit/src/plugins/mock-sveltekit-stores.ts new file mode 100644 index 000000000000..873ce8bf3517 --- /dev/null +++ b/code/frameworks/sveltekit/src/plugins/mock-sveltekit-stores.ts @@ -0,0 +1,17 @@ +import { resolve } from 'node:path'; +import { mergeConfig, type Plugin } from 'vite'; + +export function mockSveltekitStores() { + return { + name: 'storybook:sveltekit-mock-stores', + enforce: 'post', + config: (config) => + mergeConfig(config, { + resolve: { + alias: { + $app: resolve(__dirname, '../src/mocks/app/'), + }, + }, + }), + } satisfies Plugin; +} diff --git a/code/frameworks/sveltekit/src/preset.ts b/code/frameworks/sveltekit/src/preset.ts index 835379149a25..45cfe7d0a6dd 100644 --- a/code/frameworks/sveltekit/src/preset.ts +++ b/code/frameworks/sveltekit/src/preset.ts @@ -4,6 +4,7 @@ import type { PresetProperty } from '@storybook/types'; import { withoutVitePlugins } from '@storybook/builder-vite'; import { dirname, join } from 'path'; import { configOverrides } from './plugins/config-overrides'; +import { mockSveltekitStores } from './plugins/mock-sveltekit-stores'; import { type StorybookConfig } from './types'; const getAbsolutePath = (input: I): I => @@ -29,7 +30,9 @@ export const viteFinal: NonNullable = async (confi 'vite-plugin-sveltekit-compile', 'vite-plugin-sveltekit-guard', ]) - ).concat(configOverrides()); + ) + .concat(configOverrides()) + .concat(mockSveltekitStores()); return { ...baseConfig, plugins }; }; diff --git a/code/frameworks/sveltekit/src/preview.ts b/code/frameworks/sveltekit/src/preview.ts index 50ac18b9e4d6..959d5cf41259 100644 --- a/code/frameworks/sveltekit/src/preview.ts +++ b/code/frameworks/sveltekit/src/preview.ts @@ -13,15 +13,19 @@ export const decorators: Decorator[] = [ onMount(() => { const globalClickListener = (e: MouseEvent) => { + // we add a global click event listener and we check if there's a link in the composedPath const path = e.composedPath(); const hasLink = path.findLast((el) => el instanceof HTMLElement && el.tagName === 'A'); if (hasLink && hasLink instanceof HTMLAnchorElement) { + // if it has a link we get the href of the link and we check over every provided href using the + // key as a regex const to = hasLink.getAttribute('href'); - if (ctx?.parameters?.sveltekit?.linkOverrides && to) { - Object.entries(ctx.parameters.sveltekit.linkOverrides).forEach(([link, override]) => { + if (ctx?.parameters?.sveltekit?.hrefs && to) { + Object.entries(ctx.parameters.sveltekit.hrefs).forEach(([link, override]) => { if (override instanceof Function) { const regex = new RegExp(link); if (regex.test(to)) { + // if the regex pass we call the function the user provided override(); } } @@ -31,27 +35,48 @@ export const decorators: Decorator[] = [ } }; + /** + * Function that create and add listeners for the event that are emitted by + * the mocked functions. The event name is based on the function name + * + * eg. storybook:goto, storybook:invalidateAll + * @param baseModule the base module where the function lives (navigation|forms) + * @param functions the list of functions in that module that emit events + * @returns a function to remove all the listener added + */ function createListeners(baseModule: string, functions: string[]) { + // the array of every added listener, we can use this in the return function + // to clean them const toRemove: Array<{ eventType: string; listener: (event: { detail: any[] }) => void; }> = []; functions.forEach((func) => { + // we loop over every function and check if the user actually passed + // a function in sveltekit[baseModule][func] eg. sveltekit.navigation.goto if ( ctx?.parameters?.sveltekit?.[baseModule]?.[func] && ctx.parameters.sveltekit[baseModule][func] instanceof Function ) { + // we create the listener that will just get the detail array from the custom element + // and call the user provided function spreading this args in...this will basically call + // the function that the user provide with the same arguments the function is invoked to + + // eg. if it calls goto("/my-route") inside the component the function sveltekit.navigation.goto + // it provided to storybook will be called with "/my-route" const listener = ({ detail = [] as any[] }) => { const args = Array.isArray(detail) ? detail : []; ctx.parameters.sveltekit[baseModule][func](...args); }; const eventType = `storybook:${func}`; toRemove.push({ eventType, listener }); + // add the listener to window // @ts-expect-error apparently you can't add a custom listener to the window with TS window.addEventListener(eventType, listener); } }); return () => { + // loop over every listener added and remove them toRemove.forEach(({ eventType, listener }) => { // @ts-expect-error apparently you can't remove a custom listener to the window with TS window.removeEventListener(eventType, listener); diff --git a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/links.stories.js b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/links.stories.js index c293245fc698..e0fe18674d72 100644 --- a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/links.stories.js +++ b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/links.stories.js @@ -18,7 +18,7 @@ export const Link = { }, parameters: { sveltekit: { - linkOverrides: { + hrefs: { '/storybook': link, }, }, diff --git a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/links.stories.js b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/links.stories.js index c293245fc698..e0fe18674d72 100644 --- a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/links.stories.js +++ b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/links.stories.js @@ -18,7 +18,7 @@ export const Link = { }, parameters: { sveltekit: { - linkOverrides: { + hrefs: { '/storybook': link, }, }, From 1a5bcd7c5791da456c205cd7b9e924aa56adee84 Mon Sep 17 00:00:00 2001 From: jonniebigodes Date: Tue, 21 Nov 2023 15:04:26 +0000 Subject: [PATCH 138/170] Docs: Minor cleanup --- code/presets/create-react-app/README.md | 2 +- docs/snippets/common/storybook-preview-sort-function.ts.mdx | 1 + docs/writing-tests/test-runner.md | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/code/presets/create-react-app/README.md b/code/presets/create-react-app/README.md index c20a9d2e7672..de48890d4c8a 100644 --- a/code/presets/create-react-app/README.md +++ b/code/presets/create-react-app/README.md @@ -6,7 +6,7 @@ This preset is designed to use alongside [`@storybook/react`](https://github.com ## Compatibility -This version (4.x) of `@storybook/preset-create-react-app` is compatibly with Create React App version 5 and above. Earlier versions are compatible with earlier version of the preset. +From version 4.0.0 onwards, the `@storybook/preset-create-react-app` is compatible with Create React App version 5 and later. If you're using an earlier version of Create React App, you can still utilize the preset's previous versions. ## Basic usage diff --git a/docs/snippets/common/storybook-preview-sort-function.ts.mdx b/docs/snippets/common/storybook-preview-sort-function.ts.mdx index 3deb961445be..a0054ba7b8cd 100644 --- a/docs/snippets/common/storybook-preview-sort-function.ts.mdx +++ b/docs/snippets/common/storybook-preview-sort-function.ts.mdx @@ -7,6 +7,7 @@ import { Preview } from '@storybook/your-framework'; const preview: Preview = { parameters: { options: { + // The `a` and `b` arguments in this function have a type of `import('@storybook/types').IndexEntry`. Remember that the function is executed in a JavaScript environment, so use JSDoc for IntelliSense to introspect it. storySort: (a, b) => a.id === b.id ? 0 : a.id.localeCompare(b.id, undefined, { numeric: true }), }, diff --git a/docs/writing-tests/test-runner.md b/docs/writing-tests/test-runner.md index cf9c7d3b851e..531fa1d789c8 100644 --- a/docs/writing-tests/test-runner.md +++ b/docs/writing-tests/test-runner.md @@ -144,7 +144,7 @@ You can also configure the test-runner to run tests on a CI environment. Documen ### Run against deployed Storybooks via Github Actions deployment -If you're publishing your Storybook with services such as [Vercel](https://vercel.com/) or [Netlify](https://www.netlify.com/), they emit a `deployment_status` event in GitHub Actions. You can use it and set the `deployment_status.target_url` as the `TARGET_URL` environment variable. Here's how: +If you're publishing your Storybook with services such as [Vercel](https://vercel.com/) or [Netlify](https://docs.netlify.com/site-deploys/notifications/#github-commit-statuses), they emit a `deployment_status` event in GitHub Actions. You can use it and set the `deployment_status.target_url` as the `TARGET_URL` environment variable. Here's how: From b542502225ea72f3447679012e73c08cffe53bdc Mon Sep 17 00:00:00 2001 From: Paolo Ricciuti Date: Tue, 21 Nov 2023 16:39:20 +0100 Subject: [PATCH 139/170] Update code/frameworks/sveltekit/src/mocks/app/stores.ts Co-authored-by: Jeppe Reinhold --- code/frameworks/sveltekit/src/mocks/app/stores.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/code/frameworks/sveltekit/src/mocks/app/stores.ts b/code/frameworks/sveltekit/src/mocks/app/stores.ts index 56c9babaf93d..5444455ec027 100644 --- a/code/frameworks/sveltekit/src/mocks/app/stores.ts +++ b/code/frameworks/sveltekit/src/mocks/app/stores.ts @@ -19,9 +19,7 @@ export const [page, setPage] = createMockedStore('page-ctx'); export const [navigating, setNavigating] = createMockedStore('navigating-ctx'); const [updated, setUpdated] = createMockedStore('updated-ctx'); -Object.defineProperty(updated, 'check', { - value: () => {}, -}); +updated.check = () => {}; export { updated, setUpdated }; From 9de928d0b343f001528d5c268ff737276e5dde2a Mon Sep 17 00:00:00 2001 From: paoloricciuti Date: Tue, 21 Nov 2023 17:21:17 +0100 Subject: [PATCH 140/170] better regex handling of links + add experiemental --- code/frameworks/sveltekit/README.md | 28 +++++------ .../sveltekit/src/mocks/app/stores.ts | 2 +- code/frameworks/sveltekit/src/preview.ts | 50 ++++++++++++------- .../forms.stories.js | 2 +- .../links.stories.js | 12 +++-- .../navigation.stories.js | 8 +-- .../stores.stories.js | 14 +++--- .../forms.stories.js | 2 +- .../links.stories.js | 12 +++-- .../navigation.stories.js | 8 +-- .../stores.stories.js | 14 +++--- 11 files changed, 90 insertions(+), 62 deletions(-) diff --git a/code/frameworks/sveltekit/README.md b/code/frameworks/sveltekit/README.md index 4bc106cbc445..edfad87b57b8 100644 --- a/code/frameworks/sveltekit/README.md +++ b/code/frameworks/sveltekit/README.md @@ -102,12 +102,12 @@ yarn remove @storybook/builder-vite ## How to mock -To mock a SvelteKit import you can set it on `parameters.sveltekit`: +To mock a SvelteKit import you can set it on `parameters.sveltekit_experimental`: ```ts export const MyStory = { parameters: { - sveltekit: { + sveltekit_experimental: { stores: { page: { data: { @@ -126,22 +126,22 @@ export const MyStory = { }; ``` -You can add the name of the module you want to mock to `parameters.sveltekit` (in the example above we are mocking the `stores` module which correspond to `$app/stores`) and then pass the following kind of objects: +You can add the name of the module you want to mock to `parameters.sveltekit_experimental` (in the example above we are mocking the `stores` module which correspond to `$app/stores`) and then pass the following kind of objects: -| Module | Path in parameters | Kind of objects | -| ----------------------------------------------- | ----------------------------------------------- | -------------------------------------------------------------------------------------------------- | -| import { page } from "$app/stores" | `parameters.sveltekit.stores.page` | A Partial of the page store | -| import { navigating } from "$app/stores" | `parameters.sveltekit.stores.navigating` | A Partial of the navigating store | -| import { updated } from "$app/stores" | `parameters.sveltekit.stores.updated` | A boolean representing the value of updated (you can also access `check()` which will be a noop) | -| import { goto } from "$app/navigation" | `parameters.sveltekit.navigation.goto` | A callback that will be called whenever goto is called | -| import { invalidate } from "$app/navigation" | `parameters.sveltekit.navigation.invalidate` | A callback that will be called whenever invalidate is called | -| import { invalidateAll } from "$app/navigation" | `parameters.sveltekit.navigation.invalidateAll` | A callback that will be called whenever invalidateAll is called | -| import { afterNavigate } from "$app/navigation" | `parameters.sveltekit.navigation.afterNavigate` | An object that will be passed to the afterNavigate function (which will be invoked onMount) called | -| import { enhance } from "$app/forms" | `parameters.sveltekit.forms.enhance` | A callback that will called when a form with `use:enhance` is submitted | +| Module | Path in parameters | Kind of objects | +| ----------------------------------------------- | ------------------------------------------------------------ | -------------------------------------------------------------------------------------------------- | +| import { page } from "$app/stores" | `parameters.sveltekit_experimental.stores.page` | A Partial of the page store | +| import { navigating } from "$app/stores" | `parameters.sveltekit_experimental.stores.navigating` | A Partial of the navigating store | +| import { updated } from "$app/stores" | `parameters.sveltekit_experimental.stores.updated` | A boolean representing the value of updated (you can also access `check()` which will be a noop) | +| import { goto } from "$app/navigation" | `parameters.sveltekit_experimental.navigation.goto` | A callback that will be called whenever goto is called | +| import { invalidate } from "$app/navigation" | `parameters.sveltekit_experimental.navigation.invalidate` | A callback that will be called whenever invalidate is called | +| import { invalidateAll } from "$app/navigation" | `parameters.sveltekit_experimental.navigation.invalidateAll` | A callback that will be called whenever invalidateAll is called | +| import { afterNavigate } from "$app/navigation" | `parameters.sveltekit_experimental.navigation.afterNavigate` | An object that will be passed to the afterNavigate function (which will be invoked onMount) called | +| import { enhance } from "$app/forms" | `parameters.sveltekit_experimental.forms.enhance` | A callback that will called when a form with `use:enhance` is submitted | All the other functions are still exported as `noop` from the mocked modules so that your application will still work. There was no way of make them work in a customizable way. -Additionally you can pass an object to `parameter.sveltekit.hrefs` where the keys are regex representing a link and the values are functions. If you have an `` tag inside your code with the `href` attribute that matches one or more regex the corresponding function will be called. +Additionally you can pass an object to `parameter.sveltekit_experimental.hrefs` where the keys are strings representing a link and the values are objects typed as `{ callback: () => void, asRegex?: boolean }`. If you have an `` tag inside your code with the `href` attribute that matches one or more links (treaded as regex based on the `asRegex` property) the corresponding `callback` will be called. ## Troubleshooting diff --git a/code/frameworks/sveltekit/src/mocks/app/stores.ts b/code/frameworks/sveltekit/src/mocks/app/stores.ts index 5444455ec027..5f47acb1df6c 100644 --- a/code/frameworks/sveltekit/src/mocks/app/stores.ts +++ b/code/frameworks/sveltekit/src/mocks/app/stores.ts @@ -19,7 +19,7 @@ export const [page, setPage] = createMockedStore('page-ctx'); export const [navigating, setNavigating] = createMockedStore('navigating-ctx'); const [updated, setUpdated] = createMockedStore('updated-ctx'); -updated.check = () => {}; +(updated as any).check = () => {}; export { updated, setUpdated }; diff --git a/code/frameworks/sveltekit/src/preview.ts b/code/frameworks/sveltekit/src/preview.ts index 959d5cf41259..b277822470b1 100644 --- a/code/frameworks/sveltekit/src/preview.ts +++ b/code/frameworks/sveltekit/src/preview.ts @@ -6,10 +6,10 @@ import { setNavigating, setPage, setUpdated } from './mocks/app/stores'; export const decorators: Decorator[] = [ (Story, ctx) => { - setPage(ctx.parameters?.sveltekit?.stores?.page); - setUpdated(ctx.parameters?.sveltekit?.stores?.updated); - setNavigating(ctx.parameters?.sveltekit?.stores?.navigating); - setAfterNavigateArgument(ctx.parameters?.sveltekit?.navigation?.afterNavigate); + setPage(ctx.parameters?.sveltekit_experimental?.stores?.page); + setUpdated(ctx.parameters?.sveltekit_experimental?.stores?.updated); + setNavigating(ctx.parameters?.sveltekit_experimental?.stores?.navigating); + setAfterNavigateArgument(ctx.parameters?.sveltekit_experimental?.navigation?.afterNavigate); onMount(() => { const globalClickListener = (e: MouseEvent) => { @@ -20,16 +20,32 @@ export const decorators: Decorator[] = [ // if it has a link we get the href of the link and we check over every provided href using the // key as a regex const to = hasLink.getAttribute('href'); - if (ctx?.parameters?.sveltekit?.hrefs && to) { - Object.entries(ctx.parameters.sveltekit.hrefs).forEach(([link, override]) => { - if (override instanceof Function) { - const regex = new RegExp(link); - if (regex.test(to)) { - // if the regex pass we call the function the user provided - override(); + if (ctx?.parameters?.sveltekit_experimental?.hrefs && to) { + Object.entries(ctx.parameters.sveltekit_experimental.hrefs).forEach( + ([link, override]) => { + if ( + override && + typeof override === 'object' && + 'callback' in override && + override.callback instanceof Function + ) { + const isRegex = + 'asRegex' in override && + typeof override.asRegex === 'boolean' && + override.asRegex; + let shoudlRunCallback = false; + if (isRegex) { + const regex = new RegExp(link); + shoudlRunCallback = regex.test(to); + } else { + shoudlRunCallback = to === link; + } + if (shoudlRunCallback) { + override.callback(); + } } } - }); + ); } e.preventDefault(); } @@ -53,20 +69,20 @@ export const decorators: Decorator[] = [ }> = []; functions.forEach((func) => { // we loop over every function and check if the user actually passed - // a function in sveltekit[baseModule][func] eg. sveltekit.navigation.goto + // a function in sveltekit_experimental[baseModule][func] eg. sveltekit_experimental.navigation.goto if ( - ctx?.parameters?.sveltekit?.[baseModule]?.[func] && - ctx.parameters.sveltekit[baseModule][func] instanceof Function + ctx?.parameters?.sveltekit_experimental?.[baseModule]?.[func] && + ctx.parameters.sveltekit_experimental[baseModule][func] instanceof Function ) { // we create the listener that will just get the detail array from the custom element // and call the user provided function spreading this args in...this will basically call // the function that the user provide with the same arguments the function is invoked to - // eg. if it calls goto("/my-route") inside the component the function sveltekit.navigation.goto + // eg. if it calls goto("/my-route") inside the component the function sveltekit_experimental.navigation.goto // it provided to storybook will be called with "/my-route" const listener = ({ detail = [] as any[] }) => { const args = Array.isArray(detail) ? detail : []; - ctx.parameters.sveltekit[baseModule][func](...args); + ctx.parameters.sveltekit_experimental[baseModule][func](...args); }; const eventType = `storybook:${func}`; toRemove.push({ eventType, listener }); diff --git a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/forms.stories.js b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/forms.stories.js index fadda8554ac5..f56d644e52bd 100644 --- a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/forms.stories.js +++ b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/forms.stories.js @@ -17,7 +17,7 @@ export const Enhance = { expect(enhance).toHaveBeenCalled(); }, parameters: { - sveltekit: { + sveltekit_experimental: { forms: { enhance, }, diff --git a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/links.stories.js b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/links.stories.js index e0fe18674d72..c2f651617ae8 100644 --- a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/links.stories.js +++ b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/links.stories.js @@ -12,12 +12,18 @@ const link = fn(); export const Link = { async play({ canvasElement }) { const canvas = within(canvasElement); - const button = canvas.getByText('Storybook'); - button.click(); + const a = canvas.getByText('Storybook'); + // eslint-disable-next-line no-undef + const oldUrl = window.location.toString(); + a.click(); + // eslint-disable-next-line no-undef + const newUrl = window.location.toString(); + expect(newUrl).toBe(oldUrl); + console.log({ newUrl, oldUrl }); expect(link).toHaveBeenCalled(); }, parameters: { - sveltekit: { + sveltekit_experimental: { hrefs: { '/storybook': link, }, diff --git a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/navigation.stories.js b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/navigation.stories.js index 30fc67fda1b4..4033123cc5d1 100644 --- a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/navigation.stories.js +++ b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/navigation.stories.js @@ -17,7 +17,7 @@ export const Goto = { expect(goto).toHaveBeenCalledWith('/storybook'); }, parameters: { - sveltekit: { + sveltekit_experimental: { navigation: { goto, }, @@ -35,7 +35,7 @@ export const Invalidate = { expect(invalidate).toHaveBeenCalledWith('/storybook'); }, parameters: { - sveltekit: { + sveltekit_experimental: { navigation: { invalidate, }, @@ -53,7 +53,7 @@ export const InvalidateAll = { expect(invalidateAll).toHaveBeenCalledWith(); }, parameters: { - sveltekit: { + sveltekit_experimental: { navigation: { invalidateAll, }, @@ -71,7 +71,7 @@ export const AfterNavigate = { afterNavigateFn, }, parameters: { - sveltekit: { + sveltekit_experimental: { navigation: { afterNavigate: { test: 'passed', diff --git a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/stores.stories.js b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/stores.stories.js index 9ad83fe1bd87..633295b9ed04 100644 --- a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/stores.stories.js +++ b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/stores.stories.js @@ -10,7 +10,7 @@ export const AllUndefined = {}; export const PageStore = { parameters: { - sveltekit: { + sveltekit_experimental: { stores: { page: { data: { @@ -24,7 +24,7 @@ export const PageStore = { export const NavigatingStore = { parameters: { - sveltekit: { + sveltekit_experimental: { stores: { navigating: { route: { @@ -38,7 +38,7 @@ export const NavigatingStore = { export const UpdatedStore = { parameters: { - sveltekit: { + sveltekit_experimental: { stores: { updated: true, }, @@ -48,7 +48,7 @@ export const UpdatedStore = { export const PageAndNavigatingStore = { parameters: { - sveltekit: { + sveltekit_experimental: { stores: { page: { data: { @@ -67,7 +67,7 @@ export const PageAndNavigatingStore = { export const PageAndUpdatedStore = { parameters: { - sveltekit: { + sveltekit_experimental: { stores: { page: { data: { @@ -82,7 +82,7 @@ export const PageAndUpdatedStore = { export const NavigatingAndUpdatedStore = { parameters: { - sveltekit: { + sveltekit_experimental: { stores: { navigating: { route: { @@ -97,7 +97,7 @@ export const NavigatingAndUpdatedStore = { export const AllThreeStores = { parameters: { - sveltekit: { + sveltekit_experimental: { stores: { page: { data: { diff --git a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/forms.stories.js b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/forms.stories.js index fadda8554ac5..f56d644e52bd 100644 --- a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/forms.stories.js +++ b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/forms.stories.js @@ -17,7 +17,7 @@ export const Enhance = { expect(enhance).toHaveBeenCalled(); }, parameters: { - sveltekit: { + sveltekit_experimental: { forms: { enhance, }, diff --git a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/links.stories.js b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/links.stories.js index e0fe18674d72..c2f651617ae8 100644 --- a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/links.stories.js +++ b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/links.stories.js @@ -12,12 +12,18 @@ const link = fn(); export const Link = { async play({ canvasElement }) { const canvas = within(canvasElement); - const button = canvas.getByText('Storybook'); - button.click(); + const a = canvas.getByText('Storybook'); + // eslint-disable-next-line no-undef + const oldUrl = window.location.toString(); + a.click(); + // eslint-disable-next-line no-undef + const newUrl = window.location.toString(); + expect(newUrl).toBe(oldUrl); + console.log({ newUrl, oldUrl }); expect(link).toHaveBeenCalled(); }, parameters: { - sveltekit: { + sveltekit_experimental: { hrefs: { '/storybook': link, }, diff --git a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/navigation.stories.js b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/navigation.stories.js index 30fc67fda1b4..4033123cc5d1 100644 --- a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/navigation.stories.js +++ b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/navigation.stories.js @@ -17,7 +17,7 @@ export const Goto = { expect(goto).toHaveBeenCalledWith('/storybook'); }, parameters: { - sveltekit: { + sveltekit_experimental: { navigation: { goto, }, @@ -35,7 +35,7 @@ export const Invalidate = { expect(invalidate).toHaveBeenCalledWith('/storybook'); }, parameters: { - sveltekit: { + sveltekit_experimental: { navigation: { invalidate, }, @@ -53,7 +53,7 @@ export const InvalidateAll = { expect(invalidateAll).toHaveBeenCalledWith(); }, parameters: { - sveltekit: { + sveltekit_experimental: { navigation: { invalidateAll, }, @@ -71,7 +71,7 @@ export const AfterNavigate = { afterNavigateFn, }, parameters: { - sveltekit: { + sveltekit_experimental: { navigation: { afterNavigate: { test: 'passed', diff --git a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/stores.stories.js b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/stores.stories.js index 9ad83fe1bd87..633295b9ed04 100644 --- a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/stores.stories.js +++ b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/stores.stories.js @@ -10,7 +10,7 @@ export const AllUndefined = {}; export const PageStore = { parameters: { - sveltekit: { + sveltekit_experimental: { stores: { page: { data: { @@ -24,7 +24,7 @@ export const PageStore = { export const NavigatingStore = { parameters: { - sveltekit: { + sveltekit_experimental: { stores: { navigating: { route: { @@ -38,7 +38,7 @@ export const NavigatingStore = { export const UpdatedStore = { parameters: { - sveltekit: { + sveltekit_experimental: { stores: { updated: true, }, @@ -48,7 +48,7 @@ export const UpdatedStore = { export const PageAndNavigatingStore = { parameters: { - sveltekit: { + sveltekit_experimental: { stores: { page: { data: { @@ -67,7 +67,7 @@ export const PageAndNavigatingStore = { export const PageAndUpdatedStore = { parameters: { - sveltekit: { + sveltekit_experimental: { stores: { page: { data: { @@ -82,7 +82,7 @@ export const PageAndUpdatedStore = { export const NavigatingAndUpdatedStore = { parameters: { - sveltekit: { + sveltekit_experimental: { stores: { navigating: { route: { @@ -97,7 +97,7 @@ export const NavigatingAndUpdatedStore = { export const AllThreeStores = { parameters: { - sveltekit: { + sveltekit_experimental: { stores: { page: { data: { From 25e92049d833720ac7d0c1f4ec4696c642c47e65 Mon Sep 17 00:00:00 2001 From: Ian VanSchooten Date: Tue, 21 Nov 2023 15:29:09 -0500 Subject: [PATCH 141/170] Fix @vitejs/plugin-react version in top-level package.json --- code/package.json | 2 +- code/yarn.lock | 32 +++----------------------------- 2 files changed, 4 insertions(+), 30 deletions(-) diff --git a/code/package.json b/code/package.json index 9c486f75ab69..a98045536f60 100644 --- a/code/package.json +++ b/code/package.json @@ -212,7 +212,7 @@ "@typescript-eslint/eslint-plugin": "^5.45.0", "@typescript-eslint/experimental-utils": "^5.45.0", "@typescript-eslint/parser": "^5.45.0", - "@vitejs/plugin-react": "^2.1.0", + "@vitejs/plugin-react": "^3.0.1", "babel-eslint": "^10.1.0", "babel-loader": "^9.1.2", "chromatic": "7.1.0", diff --git a/code/yarn.lock b/code/yarn.lock index df84273184ce..d2928cb17c0e 100644 --- a/code/yarn.lock +++ b/code/yarn.lock @@ -1687,7 +1687,7 @@ __metadata: languageName: node linkType: hard -"@babel/plugin-transform-react-jsx-development@npm:^7.16.7, @babel/plugin-transform-react-jsx-development@npm:^7.18.6, @babel/plugin-transform-react-jsx-development@npm:^7.22.5": +"@babel/plugin-transform-react-jsx-development@npm:^7.16.7, @babel/plugin-transform-react-jsx-development@npm:^7.22.5": version: 7.22.5 resolution: "@babel/plugin-transform-react-jsx-development@npm:7.22.5" dependencies: @@ -1720,7 +1720,7 @@ __metadata: languageName: node linkType: hard -"@babel/plugin-transform-react-jsx@npm:^7.14.9, @babel/plugin-transform-react-jsx@npm:^7.19.0, @babel/plugin-transform-react-jsx@npm:^7.22.15, @babel/plugin-transform-react-jsx@npm:^7.22.5": +"@babel/plugin-transform-react-jsx@npm:^7.14.9, @babel/plugin-transform-react-jsx@npm:^7.22.15, @babel/plugin-transform-react-jsx@npm:^7.22.5": version: 7.22.15 resolution: "@babel/plugin-transform-react-jsx@npm:7.22.15" dependencies: @@ -7455,7 +7455,7 @@ __metadata: "@typescript-eslint/eslint-plugin": "npm:^5.45.0" "@typescript-eslint/experimental-utils": "npm:^5.45.0" "@typescript-eslint/parser": "npm:^5.45.0" - "@vitejs/plugin-react": "npm:^2.1.0" + "@vitejs/plugin-react": "npm:^3.0.1" babel-eslint: "npm:^10.1.0" babel-loader: "npm:^9.1.2" chromatic: "npm:7.1.0" @@ -9758,23 +9758,6 @@ __metadata: languageName: node linkType: hard -"@vitejs/plugin-react@npm:^2.1.0": - version: 2.2.0 - resolution: "@vitejs/plugin-react@npm:2.2.0" - dependencies: - "@babel/core": "npm:^7.19.6" - "@babel/plugin-transform-react-jsx": "npm:^7.19.0" - "@babel/plugin-transform-react-jsx-development": "npm:^7.18.6" - "@babel/plugin-transform-react-jsx-self": "npm:^7.18.6" - "@babel/plugin-transform-react-jsx-source": "npm:^7.19.6" - magic-string: "npm:^0.26.7" - react-refresh: "npm:^0.14.0" - peerDependencies: - vite: ^3.0.0 - checksum: 85fe5c740fbe8aa5dd4c3516a02a937dff0e2b0858cfa7cf8a69b998b7d05e08c296a087fde66f9171367f5c9d10d6e4bc026df1fa1e2ec528f49e7eaabeeae1 - languageName: node - linkType: hard - "@vitejs/plugin-react@npm:^3.0.1": version: 3.1.0 resolution: "@vitejs/plugin-react@npm:3.1.0" @@ -21226,15 +21209,6 @@ __metadata: languageName: node linkType: hard -"magic-string@npm:^0.26.7": - version: 0.26.7 - resolution: "magic-string@npm:0.26.7" - dependencies: - sourcemap-codec: "npm:^1.4.8" - checksum: 950035b344fe2a8163668980bc4a215a0b225086e6e22100fd947e7647053c6ba6b4f11a04de83a97a276526ccb602ef53b173725dbb1971fb146cff5a5e14f6 - languageName: node - linkType: hard - "magic-string@npm:^0.27.0": version: 0.27.0 resolution: "magic-string@npm:0.27.0" From e66f93afe3438a3674ab7fecf5da1c39b581da0f Mon Sep 17 00:00:00 2001 From: Ian VanSchooten Date: Tue, 21 Nov 2023 15:31:22 -0500 Subject: [PATCH 142/170] Update @vitejs/plugin-react resolution workaround --- scripts/utils/yarn.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/utils/yarn.ts b/scripts/utils/yarn.ts index fcefed46ade1..66459b2a9389 100644 --- a/scripts/utils/yarn.ts +++ b/scripts/utils/yarn.ts @@ -67,7 +67,7 @@ export const addWorkaroundResolutions = async ({ cwd, dryRun }: YarnOptions) => const packageJson = await readJSON(packageJsonPath); packageJson.resolutions = { ...packageJson.resolutions, - '@vitejs/plugin-react': '^4.0.0', // due to conflicting version in @storybook/vite-react + '@vitejs/plugin-react': '4.2.0', // due to conflicting version in @storybook/vite-react }; await writeJSON(packageJsonPath, packageJson, { spaces: 2 }); }; From 60f20ce5ea76f95a7a9488c04d7bbdc63e1edb07 Mon Sep 17 00:00:00 2001 From: Norbert de Langen Date: Tue, 21 Nov 2023 10:00:25 +0100 Subject: [PATCH 143/170] debug CI failure by not writing into logfile --- code/lib/cli/src/js-package-manager/NPMProxy.ts | 2 +- code/lib/cli/src/js-package-manager/PNPMProxy.ts | 2 +- code/lib/cli/src/js-package-manager/Yarn1Proxy.ts | 2 +- code/lib/cli/src/js-package-manager/Yarn2Proxy.ts | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/code/lib/cli/src/js-package-manager/NPMProxy.ts b/code/lib/cli/src/js-package-manager/NPMProxy.ts index 1613bac9bb5d..da6a83acec8b 100644 --- a/code/lib/cli/src/js-package-manager/NPMProxy.ts +++ b/code/lib/cli/src/js-package-manager/NPMProxy.ts @@ -184,7 +184,7 @@ export class NPMProxy extends JsPackageManager { await this.executeCommand({ command: 'npm', args: ['install', ...args, ...this.getInstallArgs()], - stdio: ['ignore', logStream, logStream], + stdio: process.env.CI ? 'inherit' : ['ignore', logStream, logStream], }); } catch (err) { const stdout = await readLogFile(); diff --git a/code/lib/cli/src/js-package-manager/PNPMProxy.ts b/code/lib/cli/src/js-package-manager/PNPMProxy.ts index 57fb2ae9b075..33571c0e4dda 100644 --- a/code/lib/cli/src/js-package-manager/PNPMProxy.ts +++ b/code/lib/cli/src/js-package-manager/PNPMProxy.ts @@ -195,7 +195,7 @@ export class PNPMProxy extends JsPackageManager { await this.executeCommand({ command: 'pnpm', args: ['add', ...args, ...this.getInstallArgs()], - stdio: ['ignore', logStream, logStream], + stdio: process.env.CI ? 'inherit' : ['ignore', logStream, logStream], }); } catch (err) { const stdout = await readLogFile(); diff --git a/code/lib/cli/src/js-package-manager/Yarn1Proxy.ts b/code/lib/cli/src/js-package-manager/Yarn1Proxy.ts index 8d24e3676f4b..2dd3251ead61 100644 --- a/code/lib/cli/src/js-package-manager/Yarn1Proxy.ts +++ b/code/lib/cli/src/js-package-manager/Yarn1Proxy.ts @@ -134,7 +134,7 @@ export class Yarn1Proxy extends JsPackageManager { await this.executeCommand({ command: 'yarn', args: ['add', ...this.getInstallArgs(), ...args], - stdio: ['ignore', logStream, logStream], + stdio: process.env.CI ? 'inherit' : ['ignore', logStream, logStream], }); } catch (err) { const stdout = await readLogFile(); diff --git a/code/lib/cli/src/js-package-manager/Yarn2Proxy.ts b/code/lib/cli/src/js-package-manager/Yarn2Proxy.ts index ebf7928d8aea..b1780c474404 100644 --- a/code/lib/cli/src/js-package-manager/Yarn2Proxy.ts +++ b/code/lib/cli/src/js-package-manager/Yarn2Proxy.ts @@ -210,7 +210,7 @@ export class Yarn2Proxy extends JsPackageManager { await this.executeCommand({ command: 'yarn', args: ['add', ...this.getInstallArgs(), ...args], - stdio: ['ignore', logStream, logStream], + stdio: process.env.CI ? 'inherit' : ['ignore', logStream, logStream], }); } catch (err) { const stdout = await readLogFile(); From 73e7bc55a76d6aebe9bd0619b736b6c71669560d Mon Sep 17 00:00:00 2001 From: Ian VanSchooten Date: Tue, 21 Nov 2023 16:13:54 -0500 Subject: [PATCH 144/170] Add resolutions for fallback vite plugins in "no-link" mode --- scripts/utils/yarn.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/scripts/utils/yarn.ts b/scripts/utils/yarn.ts index 66459b2a9389..c807708b7a55 100644 --- a/scripts/utils/yarn.ts +++ b/scripts/utils/yarn.ts @@ -27,6 +27,11 @@ export const addPackageResolutions = async ({ cwd, dryRun }: YarnOptions) => { playwright: '1.36.0', 'playwright-core': '1.36.0', '@playwright/test': '1.36.0', + + // Due to support of older vite versions + '@vitejs/plugin-react': '4.2.0', + '@sveltejs/vite-plugin-svelte': '3.0.1', + '@vitejs/plugin-vue': '4.5.0', }; await writeJSON(packageJsonPath, packageJson, { spaces: 2 }); }; From 34a449dc88427c2c668067218dd7622f6a85e561 Mon Sep 17 00:00:00 2001 From: Ian VanSchooten Date: Tue, 21 Nov 2023 17:21:58 -0500 Subject: [PATCH 145/170] Only apply workarounds for sandboxes that need it --- scripts/tasks/sandbox-parts.ts | 19 +++++++++++++++++++ scripts/utils/yarn.ts | 10 ++++------ 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/scripts/tasks/sandbox-parts.ts b/scripts/tasks/sandbox-parts.ts index 81c137200e8a..45cc2039ef0c 100644 --- a/scripts/tasks/sandbox-parts.ts +++ b/scripts/tasks/sandbox-parts.ts @@ -93,6 +93,25 @@ export const install: Task['run'] = async ({ sandboxDir }, { link, dryRun, debug await addPackageResolutions({ cwd, dryRun, debug }); await configureYarn2ForVerdaccio({ cwd, dryRun, debug }); + // Add vite plugin workarounds for frameworks that need it + // (to support vite 5 without peer dep errors) + if ( + [ + 'bench-react-vite-default-ts', + 'bench-react-vite-default-ts-nodocs', + 'bench-react-vite-default-ts-test-build', + 'internal-ssv6-vite', + 'react-vite-default-js', + 'react-vite-default-ts', + 'svelte-vite-default-js', + 'svelte-vite-default-ts', + 'vue3-vite-default-js', + 'vue3-vite-default-ts', + ].includes(sandboxDir.split(sep).at(-1)) + ) { + await addWorkaroundResolutions({ cwd, dryRun, debug }); + } + await exec( 'yarn install', { cwd }, diff --git a/scripts/utils/yarn.ts b/scripts/utils/yarn.ts index c807708b7a55..19f87d1c0182 100644 --- a/scripts/utils/yarn.ts +++ b/scripts/utils/yarn.ts @@ -27,11 +27,6 @@ export const addPackageResolutions = async ({ cwd, dryRun }: YarnOptions) => { playwright: '1.36.0', 'playwright-core': '1.36.0', '@playwright/test': '1.36.0', - - // Due to support of older vite versions - '@vitejs/plugin-react': '4.2.0', - '@sveltejs/vite-plugin-svelte': '3.0.1', - '@vitejs/plugin-vue': '4.5.0', }; await writeJSON(packageJsonPath, packageJson, { spaces: 2 }); }; @@ -72,7 +67,10 @@ export const addWorkaroundResolutions = async ({ cwd, dryRun }: YarnOptions) => const packageJson = await readJSON(packageJsonPath); packageJson.resolutions = { ...packageJson.resolutions, - '@vitejs/plugin-react': '4.2.0', // due to conflicting version in @storybook/vite-react + // Due to our support of older vite versions + '@vitejs/plugin-react': '4.2.0', + '@sveltejs/vite-plugin-svelte': '3.0.1', + '@vitejs/plugin-vue': '4.5.0', }; await writeJSON(packageJsonPath, packageJson, { spaces: 2 }); }; From f57a6b857896c1e0d7b08e6f5a2ad9200b2f057b Mon Sep 17 00:00:00 2001 From: Jeppe Reinhold Date: Wed, 22 Nov 2023 00:31:09 +0100 Subject: [PATCH 146/170] add actions as default behavior, cleanup decorator --- code/frameworks/sveltekit/README.md | 55 +++++++-- code/frameworks/sveltekit/package.json | 11 +- code/frameworks/sveltekit/src/preview.ts | 114 +++++++++++------- .../Hrefs.svelte | 8 ++ .../Links.svelte | 1 - .../forms.stories.js | 2 +- .../hrefs.stories.js | 53 ++++++++ .../links.stories.js | 32 ----- .../navigation.stories.js | 2 +- .../stores.stories.js | 2 +- .../Hrefs.svelte | 8 ++ .../Links.svelte | 1 - .../forms.stories.js | 2 +- .../hrefs.stories.js | 53 ++++++++ .../links.stories.js | 32 ----- .../navigation.stories.js | 2 +- .../stores.stories.js | 2 +- code/yarn.lock | 1 + 18 files changed, 245 insertions(+), 136 deletions(-) create mode 100644 code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/Hrefs.svelte delete mode 100644 code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/Links.svelte create mode 100644 code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/hrefs.stories.js delete mode 100644 code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/links.stories.js create mode 100644 code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/Hrefs.svelte delete mode 100644 code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/Links.svelte create mode 100644 code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/hrefs.stories.js delete mode 100644 code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/links.stories.js diff --git a/code/frameworks/sveltekit/README.md b/code/frameworks/sveltekit/README.md index edfad87b57b8..d9242efcdbf1 100644 --- a/code/frameworks/sveltekit/README.md +++ b/code/frameworks/sveltekit/README.md @@ -13,6 +13,8 @@ Check out our [Frameworks API](https://storybook.js.org/blog/framework-api/) ann - [In a project with Storybook](#in-a-project-with-storybook) - [Automatic migration](#automatic-migration) - [Manual migration](#manual-migration) +- [How to mock](#how-to-mock) + - [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) @@ -128,20 +130,48 @@ export const MyStory = { You can add the name of the module you want to mock to `parameters.sveltekit_experimental` (in the example above we are mocking the `stores` module which correspond to `$app/stores`) and then pass the following kind of objects: -| Module | Path in parameters | Kind of objects | -| ----------------------------------------------- | ------------------------------------------------------------ | -------------------------------------------------------------------------------------------------- | -| import { page } from "$app/stores" | `parameters.sveltekit_experimental.stores.page` | A Partial of the page store | -| import { navigating } from "$app/stores" | `parameters.sveltekit_experimental.stores.navigating` | A Partial of the navigating store | -| import { updated } from "$app/stores" | `parameters.sveltekit_experimental.stores.updated` | A boolean representing the value of updated (you can also access `check()` which will be a noop) | -| import { goto } from "$app/navigation" | `parameters.sveltekit_experimental.navigation.goto` | A callback that will be called whenever goto is called | -| import { invalidate } from "$app/navigation" | `parameters.sveltekit_experimental.navigation.invalidate` | A callback that will be called whenever invalidate is called | -| import { invalidateAll } from "$app/navigation" | `parameters.sveltekit_experimental.navigation.invalidateAll` | A callback that will be called whenever invalidateAll is called | -| import { afterNavigate } from "$app/navigation" | `parameters.sveltekit_experimental.navigation.afterNavigate` | An object that will be passed to the afterNavigate function (which will be invoked onMount) called | -| import { enhance } from "$app/forms" | `parameters.sveltekit_experimental.forms.enhance` | A callback that will called when a form with `use:enhance` is submitted | +| Module | Path in parameters | Kind of objects | +| ------------------------------------------------- | ------------------------------------------------------------ | -------------------------------------------------------------------------------------------------- | +| `import { page } from "$app/stores"` | `parameters.sveltekit_experimental.stores.page` | A Partial of the page store | +| `import { navigating } from "$app/stores"` | `parameters.sveltekit_experimental.stores.navigating` | A Partial of the navigating store | +| `import { updated } from "$app/stores"` | `parameters.sveltekit_experimental.stores.updated` | A boolean representing the value of updated (you can also access `check()` which will be a noop) | +| `import { goto } from "$app/navigation"` | `parameters.sveltekit_experimental.navigation.goto` | A callback that will be called whenever goto is called | +| `import { invalidate } from "$app/navigation"` | `parameters.sveltekit_experimental.navigation.invalidate` | A callback that will be called whenever invalidate is called | +| `import { invalidateAll } from "$app/navigation"` | `parameters.sveltekit_experimental.navigation.invalidateAll` | A callback that will be called whenever invalidateAll is called | +| `import { afterNavigate } from "$app/navigation"` | `parameters.sveltekit_experimental.navigation.afterNavigate` | An object that will be passed to the afterNavigate function (which will be invoked onMount) called | +| `import { enhance } from "$app/forms"` | `parameters.sveltekit_experimental.forms.enhance` | A callback that will called when a form with `use:enhance` is submitted | -All the other functions are still exported as `noop` from the mocked modules so that your application will still work. There was no way of make them work in a customizable way. +All the other functions are still exported as `noop` from the mocked modules so that your application will still work. -Additionally you can pass an object to `parameter.sveltekit_experimental.hrefs` where the keys are strings representing a link and the values are objects typed as `{ callback: () => void, asRegex?: boolean }`. If you have an `` tag inside your code with the `href` attribute that matches one or more links (treaded as regex based on the `asRegex` property) the corresponding `callback` will be called. +### Mocking links + +The default link-handling behavior (ie. clicking an `` tag with an `href` attribute) is to log an action to the Actions panel. + +You can override this by setting an object on `parameter.sveltekit_experimental.hrefs`, where the keys are strings representing an href and the values are objects typed as `{ callback: (href, event) => void, asRegex?: boolean }`. + +If you have an `` tag inside your code with the `href` attribute that matches one or more of the links defined (treated as regex based on the `asRegex` property) the corresponding `callback` will be called. + +Example: + +```ts +export const MyStory = { + parameters: { + sveltekit_experimental: { + hrefs: { + '/basic-href': (to, event) => { + console.log(to, event); + }, + '/root.*': { + callback: (to, event) => { + console.log(to, event); + }, + asRegex: true, + }, + }, + }, + }, +}; +``` ## Troubleshooting @@ -168,3 +198,4 @@ You'll experience this if anything in your story is importing from `$app/forms` ## Acknowledgements Integrating with SvelteKit would not have been possible if it weren't for the fantastic efforts by the Svelte core team - especially [Ben McCann](https://twitter.com/benjaminmccann) - to make integrations with the wider ecosystem possible. +A big thank you also goes out to [Paolo Ricciuti](https://twitter.com/PaoloRicciuti) for improving the mocking capabilities. diff --git a/code/frameworks/sveltekit/package.json b/code/frameworks/sveltekit/package.json index 7d76f10e7bdc..a6550677ab25 100644 --- a/code/frameworks/sveltekit/package.json +++ b/code/frameworks/sveltekit/package.json @@ -29,17 +29,7 @@ "require": "./dist/index.js", "import": "./dist/index.mjs" }, - "./preview": { - "types": "./dist/preview.d.ts", - "require": "./dist/preview.js", - "import": "./dist/preview.mjs" - }, - "./dist/preview.js": { - "types": "./dist/preview.d.ts", - "require": "./dist/preview.js" - }, "./dist/preview.mjs": { - "types": "./dist/preview.d.ts", "import": "./dist/preview.mjs" }, "./preset": { @@ -63,6 +53,7 @@ "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { + "@storybook/addon-actions": "workspace:*", "@storybook/builder-vite": "workspace:*", "@storybook/svelte": "workspace:*", "@storybook/svelte-vite": "workspace:*" diff --git a/code/frameworks/sveltekit/src/preview.ts b/code/frameworks/sveltekit/src/preview.ts index b277822470b1..23512ace57d8 100644 --- a/code/frameworks/sveltekit/src/preview.ts +++ b/code/frameworks/sveltekit/src/preview.ts @@ -1,53 +1,84 @@ import type { Decorator } from '@storybook/svelte'; - +import { action } from '@storybook/addon-actions'; import { onMount } from 'svelte'; +import type { enhance } from './mocks/app/forms'; +import type { goto, invalidate, invalidateAll, afterNavigate } from './mocks/app/navigation'; import { setAfterNavigateArgument } from './mocks/app/navigation'; import { setNavigating, setPage, setUpdated } from './mocks/app/stores'; +type NormalizedHrefConfig = { + callback: (to: string, event: Event) => void; + asRegex?: boolean; +}; + +type HrefConfig = NormalizedHrefConfig | NormalizedHrefConfig['callback']; + +type SvelteKitParameters = Partial<{ + hrefs: Record; + stores: { + page: Record; + navigating: boolean; + updated: boolean; + }; + navigation: { + goto: typeof goto; + invalidate: typeof invalidate; + invalidateAll: typeof invalidateAll; + afterNavigate: typeof afterNavigate; + }; + forms: { + enhance: typeof enhance; + }; +}>; + +const normalizeHrefConfig = (hrefConfig: HrefConfig): NormalizedHrefConfig => { + if (typeof hrefConfig === 'function') { + return { callback: hrefConfig, asRegex: false }; + } + return hrefConfig; +}; + export const decorators: Decorator[] = [ (Story, ctx) => { - setPage(ctx.parameters?.sveltekit_experimental?.stores?.page); - setUpdated(ctx.parameters?.sveltekit_experimental?.stores?.updated); - setNavigating(ctx.parameters?.sveltekit_experimental?.stores?.navigating); - setAfterNavigateArgument(ctx.parameters?.sveltekit_experimental?.navigation?.afterNavigate); + const svelteKitParameters: SvelteKitParameters = ctx.parameters?.sveltekit_experimental ?? {}; + setPage(svelteKitParameters?.stores?.page); + setNavigating(svelteKitParameters?.stores?.navigating); + setUpdated(svelteKitParameters?.stores?.updated); + setAfterNavigateArgument(svelteKitParameters?.navigation?.afterNavigate); onMount(() => { const globalClickListener = (e: MouseEvent) => { // we add a global click event listener and we check if there's a link in the composedPath const path = e.composedPath(); - const hasLink = path.findLast((el) => el instanceof HTMLElement && el.tagName === 'A'); - if (hasLink && hasLink instanceof HTMLAnchorElement) { - // if it has a link we get the href of the link and we check over every provided href using the - // key as a regex - const to = hasLink.getAttribute('href'); - if (ctx?.parameters?.sveltekit_experimental?.hrefs && to) { - Object.entries(ctx.parameters.sveltekit_experimental.hrefs).forEach( - ([link, override]) => { - if ( - override && - typeof override === 'object' && - 'callback' in override && - override.callback instanceof Function - ) { - const isRegex = - 'asRegex' in override && - typeof override.asRegex === 'boolean' && - override.asRegex; - let shoudlRunCallback = false; - if (isRegex) { - const regex = new RegExp(link); - shoudlRunCallback = regex.test(to); - } else { - shoudlRunCallback = to === link; - } - if (shoudlRunCallback) { - override.callback(); - } - } - } - ); + const element = path.findLast((el) => el instanceof HTMLElement && el.tagName === 'A'); + if (element && element instanceof HTMLAnchorElement) { + // if the element is an a-tag we get the href of the element + // and compare it to the hrefs-parameter set by the user + const to = element.getAttribute('href'); + if (!to) { + return; } e.preventDefault(); + const defaultActionCallback = () => action('navigate')(to, e); + if (!svelteKitParameters.hrefs) { + defaultActionCallback(); + return; + } + + let callDefaultCallback = true; + // we loop over every href set by the user and check if the href matches + // if it does we call the callback provided by the user and disable the default callback + Object.entries(svelteKitParameters.hrefs).forEach(([href, hrefConfig]) => { + const { callback, asRegex } = normalizeHrefConfig(hrefConfig); + const isMatch = asRegex ? new RegExp(href).test(to) : to === href; + if (isMatch) { + callDefaultCallback = false; + callback?.(to, e); + } + }); + if (callDefaultCallback) { + defaultActionCallback(); + } } }; @@ -60,7 +91,7 @@ export const decorators: Decorator[] = [ * @param functions the list of functions in that module that emit events * @returns a function to remove all the listener added */ - function createListeners(baseModule: string, functions: string[]) { + function createListeners(baseModule: keyof SvelteKitParameters, functions: string[]) { // the array of every added listener, we can use this in the return function // to clean them const toRemove: Array<{ @@ -71,8 +102,8 @@ export const decorators: Decorator[] = [ // we loop over every function and check if the user actually passed // a function in sveltekit_experimental[baseModule][func] eg. sveltekit_experimental.navigation.goto if ( - ctx?.parameters?.sveltekit_experimental?.[baseModule]?.[func] && - ctx.parameters.sveltekit_experimental[baseModule][func] instanceof Function + (svelteKitParameters as any)[baseModule]?.[func] && + (svelteKitParameters as any)[baseModule][func] instanceof Function ) { // we create the listener that will just get the detail array from the custom element // and call the user provided function spreading this args in...this will basically call @@ -82,13 +113,12 @@ export const decorators: Decorator[] = [ // it provided to storybook will be called with "/my-route" const listener = ({ detail = [] as any[] }) => { const args = Array.isArray(detail) ? detail : []; - ctx.parameters.sveltekit_experimental[baseModule][func](...args); + (svelteKitParameters as any)[baseModule][func](...args); }; const eventType = `storybook:${func}`; toRemove.push({ eventType, listener }); // add the listener to window - // @ts-expect-error apparently you can't add a custom listener to the window with TS - window.addEventListener(eventType, listener); + (window.addEventListener as any)(eventType, listener); } }); return () => { diff --git a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/Hrefs.svelte b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/Hrefs.svelte new file mode 100644 index 000000000000..4e7d69e0e051 --- /dev/null +++ b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/Hrefs.svelte @@ -0,0 +1,8 @@ + diff --git a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/Links.svelte b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/Links.svelte deleted file mode 100644 index 3470b6b0e6f8..000000000000 --- a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/Links.svelte +++ /dev/null @@ -1 +0,0 @@ -Storybook \ No newline at end of file diff --git a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/forms.stories.js b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/forms.stories.js index f56d644e52bd..72b584baef76 100644 --- a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/forms.stories.js +++ b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/forms.stories.js @@ -2,7 +2,7 @@ import { expect, fn, within } from '@storybook/test'; import Forms from './Forms.svelte'; export default { - title: 'stories/sveltekit/modules/Forms', + title: 'stories/sveltekit/modules/forms', component: Forms, tags: ['autodocs'], }; diff --git a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/hrefs.stories.js b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/hrefs.stories.js new file mode 100644 index 000000000000..f1cbf4973534 --- /dev/null +++ b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/hrefs.stories.js @@ -0,0 +1,53 @@ +import { expect, fn, within } from '@storybook/test'; +import Hrefs from './Hrefs.svelte'; + +export default { + title: 'stories/sveltekit/modules/hrefs', + component: Hrefs, + tags: ['autodocs'], +}; + +export const DefaultActions = { + async play({ canvasElement }) { + const canvas = within(canvasElement); + // eslint-disable-next-line no-undef + const initialUrl = window.location.toString(); + + const basicHref = canvas.getByText('/basic-href'); + basicHref.click(); + + const complexHref = canvas.getByText( + '/deep/nested/link?with=true&multiple-params=200#and-an-id' + ); + complexHref.click(); + + // eslint-disable-next-line no-undef + const finalUrl = window.location.toString(); + expect(finalUrl).toBe(initialUrl); + }, +}; + +const basicStringMatch = fn(); +const noMatch = fn(); +const exactStringMatch = fn(); +const regexMatch = fn(); + +export const Callbacks = { + parameters: { + sveltekit_experimental: { + hrefs: { + '/basic-href': basicStringMatch, + '/basic': noMatch, + '/deep/nested/link?with=true&multiple-params=200#and-an-id': exactStringMatch, + 'nested/link\\?with': { callback: regexMatch, asRegex: true }, + }, + }, + }, + play: async (ctx) => { + await DefaultActions.play(ctx); + expect(basicStringMatch).toHaveBeenCalledTimes(1); + expect(noMatch).not.toHaveBeenCalled(); + expect(exactStringMatch).toHaveBeenCalledTimes(1); + expect(regexMatch).toHaveBeenCalledTimes(1); + }, +}; diff --git a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/links.stories.js b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/links.stories.js deleted file mode 100644 index c2f651617ae8..000000000000 --- a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/links.stories.js +++ /dev/null @@ -1,32 +0,0 @@ -import { expect, fn, within } from '@storybook/test'; -import Links from './Links.svelte'; - -export default { - title: 'stories/sveltekit/modules/Links', - component: Links, - tags: ['autodocs'], -}; - -const link = fn(); - -export const Link = { - async play({ canvasElement }) { - const canvas = within(canvasElement); - const a = canvas.getByText('Storybook'); - // eslint-disable-next-line no-undef - const oldUrl = window.location.toString(); - a.click(); - // eslint-disable-next-line no-undef - const newUrl = window.location.toString(); - expect(newUrl).toBe(oldUrl); - console.log({ newUrl, oldUrl }); - expect(link).toHaveBeenCalled(); - }, - parameters: { - sveltekit_experimental: { - hrefs: { - '/storybook': link, - }, - }, - }, -}; diff --git a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/navigation.stories.js b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/navigation.stories.js index 4033123cc5d1..529997126f7c 100644 --- a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/navigation.stories.js +++ b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/navigation.stories.js @@ -2,7 +2,7 @@ import { expect, fn, within } from '@storybook/test'; import Navigation from './Navigation.svelte'; export default { - title: 'stories/sveltekit/modules/Navigation', + title: 'stories/sveltekit/modules/navigation', component: Navigation, tags: ['autodocs'], }; diff --git a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/stores.stories.js b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/stores.stories.js index 633295b9ed04..7f7401cf8bee 100644 --- a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/stores.stories.js +++ b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-js/stores.stories.js @@ -1,7 +1,7 @@ import Stores from './Stores.svelte'; export default { - title: 'stories/sveltekit/modules/Stores', + title: 'stories/sveltekit/modules/stores', component: Stores, tags: ['autodocs'], }; diff --git a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/Hrefs.svelte b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/Hrefs.svelte new file mode 100644 index 000000000000..4e7d69e0e051 --- /dev/null +++ b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/Hrefs.svelte @@ -0,0 +1,8 @@ + diff --git a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/Links.svelte b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/Links.svelte deleted file mode 100644 index 3470b6b0e6f8..000000000000 --- a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/Links.svelte +++ /dev/null @@ -1 +0,0 @@ -Storybook \ No newline at end of file diff --git a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/forms.stories.js b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/forms.stories.js index f56d644e52bd..72b584baef76 100644 --- a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/forms.stories.js +++ b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/forms.stories.js @@ -2,7 +2,7 @@ import { expect, fn, within } from '@storybook/test'; import Forms from './Forms.svelte'; export default { - title: 'stories/sveltekit/modules/Forms', + title: 'stories/sveltekit/modules/forms', component: Forms, tags: ['autodocs'], }; diff --git a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/hrefs.stories.js b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/hrefs.stories.js new file mode 100644 index 000000000000..f1cbf4973534 --- /dev/null +++ b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/hrefs.stories.js @@ -0,0 +1,53 @@ +import { expect, fn, within } from '@storybook/test'; +import Hrefs from './Hrefs.svelte'; + +export default { + title: 'stories/sveltekit/modules/hrefs', + component: Hrefs, + tags: ['autodocs'], +}; + +export const DefaultActions = { + async play({ canvasElement }) { + const canvas = within(canvasElement); + // eslint-disable-next-line no-undef + const initialUrl = window.location.toString(); + + const basicHref = canvas.getByText('/basic-href'); + basicHref.click(); + + const complexHref = canvas.getByText( + '/deep/nested/link?with=true&multiple-params=200#and-an-id' + ); + complexHref.click(); + + // eslint-disable-next-line no-undef + const finalUrl = window.location.toString(); + expect(finalUrl).toBe(initialUrl); + }, +}; + +const basicStringMatch = fn(); +const noMatch = fn(); +const exactStringMatch = fn(); +const regexMatch = fn(); + +export const Callbacks = { + parameters: { + sveltekit_experimental: { + hrefs: { + '/basic-href': basicStringMatch, + '/basic': noMatch, + '/deep/nested/link?with=true&multiple-params=200#and-an-id': exactStringMatch, + 'nested/link\\?with': { callback: regexMatch, asRegex: true }, + }, + }, + }, + play: async (ctx) => { + await DefaultActions.play(ctx); + expect(basicStringMatch).toHaveBeenCalledTimes(1); + expect(noMatch).not.toHaveBeenCalled(); + expect(exactStringMatch).toHaveBeenCalledTimes(1); + expect(regexMatch).toHaveBeenCalledTimes(1); + }, +}; diff --git a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/links.stories.js b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/links.stories.js deleted file mode 100644 index c2f651617ae8..000000000000 --- a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/links.stories.js +++ /dev/null @@ -1,32 +0,0 @@ -import { expect, fn, within } from '@storybook/test'; -import Links from './Links.svelte'; - -export default { - title: 'stories/sveltekit/modules/Links', - component: Links, - tags: ['autodocs'], -}; - -const link = fn(); - -export const Link = { - async play({ canvasElement }) { - const canvas = within(canvasElement); - const a = canvas.getByText('Storybook'); - // eslint-disable-next-line no-undef - const oldUrl = window.location.toString(); - a.click(); - // eslint-disable-next-line no-undef - const newUrl = window.location.toString(); - expect(newUrl).toBe(oldUrl); - console.log({ newUrl, oldUrl }); - expect(link).toHaveBeenCalled(); - }, - parameters: { - sveltekit_experimental: { - hrefs: { - '/storybook': link, - }, - }, - }, -}; diff --git a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/navigation.stories.js b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/navigation.stories.js index 4033123cc5d1..529997126f7c 100644 --- a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/navigation.stories.js +++ b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/navigation.stories.js @@ -2,7 +2,7 @@ import { expect, fn, within } from '@storybook/test'; import Navigation from './Navigation.svelte'; export default { - title: 'stories/sveltekit/modules/Navigation', + title: 'stories/sveltekit/modules/navigation', component: Navigation, tags: ['autodocs'], }; diff --git a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/stores.stories.js b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/stores.stories.js index 633295b9ed04..7f7401cf8bee 100644 --- a/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/stores.stories.js +++ b/code/frameworks/sveltekit/template/stories_svelte-kit-skeleton-ts/stores.stories.js @@ -1,7 +1,7 @@ import Stores from './Stores.svelte'; export default { - title: 'stories/sveltekit/modules/Stores', + title: 'stories/sveltekit/modules/stores', component: Stores, tags: ['autodocs'], }; diff --git a/code/yarn.lock b/code/yarn.lock index df84273184ce..15310ab55bfb 100644 --- a/code/yarn.lock +++ b/code/yarn.lock @@ -7659,6 +7659,7 @@ __metadata: version: 0.0.0-use.local resolution: "@storybook/sveltekit@workspace:frameworks/sveltekit" dependencies: + "@storybook/addon-actions": "workspace:*" "@storybook/builder-vite": "workspace:*" "@storybook/svelte": "workspace:*" "@storybook/svelte-vite": "workspace:*" From da7725614166ab033ff3d4b4edc6ca433807c3b7 Mon Sep 17 00:00:00 2001 From: Jeppe Reinhold Date: Wed, 22 Nov 2023 00:48:23 +0100 Subject: [PATCH 147/170] e2e test for default sveltekit actions --- code/e2e-tests/framework-svelte.spec.ts | 39 +++++++++++++++++++++---- 1 file changed, 33 insertions(+), 6 deletions(-) diff --git a/code/e2e-tests/framework-svelte.spec.ts b/code/e2e-tests/framework-svelte.spec.ts index a208aa982d9c..bd6c833b609b 100644 --- a/code/e2e-tests/framework-svelte.spec.ts +++ b/code/e2e-tests/framework-svelte.spec.ts @@ -1,12 +1,16 @@ /* eslint-disable jest/no-disabled-tests */ import { test, expect } from '@playwright/test'; import process from 'process'; -import dedent from 'ts-dedent'; import { SbPage } from './util'; const storybookUrl = process.env.STORYBOOK_URL || 'http://localhost:6006'; const templateName = process.env.STORYBOOK_TEMPLATE_NAME; +test.beforeEach(async ({ page }) => { + await page.goto(storybookUrl); + await new SbPage(page).waitUntilLoaded(); +}); + test.describe('Svelte', () => { test.skip( // eslint-disable-next-line jest/valid-title @@ -14,11 +18,6 @@ test.describe('Svelte', () => { 'Only run this test on Svelte' ); - test.beforeEach(async ({ page }) => { - await page.goto(storybookUrl); - await new SbPage(page).waitUntilLoaded(); - }); - test('JS story has auto-generated args table', async ({ page }) => { const sbPage = new SbPage(page); @@ -51,3 +50,31 @@ test.describe('Svelte', () => { await expect(sourceCode.textContent()).resolves.toContain(expectedSource); }); }); + +test.describe('SvelteKit', () => { + test.skip( + // eslint-disable-next-line jest/valid-title + !templateName?.includes('svelte-kit'), + 'Only run this test on SvelteKit' + ); + + test('Links are logged in Actions panel', async ({ page }) => { + const sbPage = new SbPage(page); + + await sbPage.navigateToStory('stories/sveltekit/modules/hrefs', 'default-actions'); + const root = sbPage.previewRoot(); + const link = root.locator('a', { hasText: 'Link to /basic-href' }); + await link.click(); + + await sbPage.viewAddonPanel('Actions'); + const basicLogItem = await page.locator('#storybook-panel-root #panel-tab-content', { + hasText: `/basic-href`, + }); + + await expect(basicLogItem).toBeVisible(); + const complexLogItem = await page.locator('#storybook-panel-root #panel-tab-content', { + hasText: `/deep/nested`, + }); + await expect(complexLogItem).toBeVisible(); + }); +}); From 47842083780e70c98f8431c4395ebb1b5d37b5bc Mon Sep 17 00:00:00 2001 From: Jeppe Reinhold Date: Wed, 22 Nov 2023 00:56:05 +0100 Subject: [PATCH 148/170] fix decorator e2e test in dev --- code/e2e-tests/framework-svelte.spec.ts | 5 ++++- .../svelte/template/stories/decorators-runs-once.stories.js | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/code/e2e-tests/framework-svelte.spec.ts b/code/e2e-tests/framework-svelte.spec.ts index 321a18406315..ceffacc525d7 100644 --- a/code/e2e-tests/framework-svelte.spec.ts +++ b/code/e2e-tests/framework-svelte.spec.ts @@ -54,7 +54,10 @@ test.describe('Svelte', () => { const sbPage = new SbPage(page); const lines: string[] = []; page.on('console', (msg) => { - lines.push(msg.text()); + const text = msg.text(); + if (text === 'decorator called') { + lines.push(text); + } }); await sbPage.navigateToStory('stories/renderers/svelte/decorators-runs-once', 'default'); diff --git a/code/renderers/svelte/template/stories/decorators-runs-once.stories.js b/code/renderers/svelte/template/stories/decorators-runs-once.stories.js index 649d9f8a18bb..5186ccb14d88 100644 --- a/code/renderers/svelte/template/stories/decorators-runs-once.stories.js +++ b/code/renderers/svelte/template/stories/decorators-runs-once.stories.js @@ -7,7 +7,7 @@ export default { }, decorators: [ (Story) => { - console.log('decorator'); + console.log('decorator called'); return Story(); }, ], From aef74d6f21858c67fe3382d64e73425d93732701 Mon Sep 17 00:00:00 2001 From: Yann Braga Date: Thu, 16 Nov 2023 17:18:44 +0100 Subject: [PATCH 149/170] Detect no matching export error in storybook start and build --- .../core-events/src/errors/server-errors.ts | 25 +++++++++++++++++++ code/lib/core-server/src/build-dev.ts | 5 ++-- code/lib/core-server/src/build-static.ts | 5 +++- .../core-server/src/utils/build-or-throw.ts | 20 +++++++++++++++ 4 files changed, 52 insertions(+), 3 deletions(-) create mode 100644 code/lib/core-server/src/utils/build-or-throw.ts diff --git a/code/lib/core-events/src/errors/server-errors.ts b/code/lib/core-events/src/errors/server-errors.ts index 6ca430ae1966..188c299f4a66 100644 --- a/code/lib/core-events/src/errors/server-errors.ts +++ b/code/lib/core-events/src/errors/server-errors.ts @@ -385,3 +385,28 @@ export class NextjsSWCNotSupportedError extends StorybookError { `; } } + +export class NoMatchingExportError extends StorybookError { + readonly category = Category.CORE_SERVER; + + readonly code = 4; + + constructor(public data: { error: unknown | Error }) { + super(); + } + + template() { + return dedent` + There was an exports mismatch error when trying to build Storybook. + Please check whether the versions of your Storybook packages match whenever possible, as this might be the cause. + + Problematic example: + { "@storybook/react": "7.5.3", "@storybook/react-vite": "7.4.5", "storybook": "7.3.0" } + + Correct example: + { "@storybook/react": "7.5.3", "@storybook/react-vite": "7.5.3", "storybook": "7.5.3" } + + Clearing your lock file and reinstalling your dependencies might help as well. + `; + } +} diff --git a/code/lib/core-server/src/build-dev.ts b/code/lib/core-server/src/build-dev.ts index 1e321a7d2933..2811d93905f9 100644 --- a/code/lib/core-server/src/build-dev.ts +++ b/code/lib/core-server/src/build-dev.ts @@ -27,6 +27,7 @@ import { updateCheck } from './utils/update-check'; import { getServerPort, getServerChannelUrl } from './utils/server-address'; import { getManagerBuilder, getPreviewBuilder } from './utils/get-builders'; import { warnOnIncompatibleAddons } from './utils/warnOnIncompatibleAddons'; +import { buildOrThrow } from './utils/build-or-throw'; export async function buildDevStandalone( options: CLIOptions & LoadOptions & BuilderOptions @@ -134,8 +135,8 @@ export async function buildDevStandalone( features, }; - const { address, networkAddress, managerResult, previewResult } = await storybookDevServer( - fullOptions + const { address, networkAddress, managerResult, previewResult } = await buildOrThrow(async () => + storybookDevServer(fullOptions) ); const previewTotalTime = previewResult?.totalTime; diff --git a/code/lib/core-server/src/build-static.ts b/code/lib/core-server/src/build-static.ts index e6775f519829..cde136c47413 100644 --- a/code/lib/core-server/src/build-static.ts +++ b/code/lib/core-server/src/build-static.ts @@ -35,6 +35,7 @@ import { extractStorybookMetadata } from './utils/metadata'; import { StoryIndexGenerator } from './utils/StoryIndexGenerator'; import { summarizeIndex } from './utils/summarizeIndex'; import { defaultStaticDirs } from './utils/constants'; +import { buildOrThrow } from './utils/build-or-throw'; export type BuildStaticStandaloneOptions = CLIOptions & LoadOptions & @@ -146,7 +147,9 @@ export async function buildStaticStandalone(options: BuildStaticStandaloneOption global.FEATURES = features; - await managerBuilder.build({ startTime: process.hrtime(), options: fullOptions }); + await buildOrThrow(async () => + managerBuilder.build({ startTime: process.hrtime(), options: fullOptions }) + ); if (staticDirs) { effects.push( diff --git a/code/lib/core-server/src/utils/build-or-throw.ts b/code/lib/core-server/src/utils/build-or-throw.ts new file mode 100644 index 000000000000..9370446f1fa0 --- /dev/null +++ b/code/lib/core-server/src/utils/build-or-throw.ts @@ -0,0 +1,20 @@ +import { NoMatchingExportError } from '@storybook/core-events/server-errors'; + +export async function buildOrThrow(callback: () => Promise): Promise { + try { + return await callback(); + } catch (err: any) { + const builderErrors = err.errors as { text: string }[]; + if (builderErrors) { + const inconsistentVersionsError = builderErrors.find((er) => + er.text.includes('No matching export') + ); + + if (inconsistentVersionsError) { + throw new NoMatchingExportError(err); + } + } + + throw err; + } +} From 2c1dcf3a4d90b7e03fee080cd5155229e37ea5aa Mon Sep 17 00:00:00 2001 From: Yann Braga Date: Fri, 17 Nov 2023 14:42:50 +0100 Subject: [PATCH 150/170] Update code/lib/core-server/src/utils/build-or-throw.ts --- code/lib/core-server/src/utils/build-or-throw.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/code/lib/core-server/src/utils/build-or-throw.ts b/code/lib/core-server/src/utils/build-or-throw.ts index 9370446f1fa0..5c1746a0be2a 100644 --- a/code/lib/core-server/src/utils/build-or-throw.ts +++ b/code/lib/core-server/src/utils/build-or-throw.ts @@ -7,7 +7,7 @@ export async function buildOrThrow(callback: () => Promise): Promise { const builderErrors = err.errors as { text: string }[]; if (builderErrors) { const inconsistentVersionsError = builderErrors.find((er) => - er.text.includes('No matching export') + er.text?.includes('No matching export') ); if (inconsistentVersionsError) { From f0fd10b1ab2945ce16e02346ed0c3c12af2848e4 Mon Sep 17 00:00:00 2001 From: Yann Braga Date: Mon, 20 Nov 2023 15:48:52 +0100 Subject: [PATCH 151/170] Update code/lib/core-events/src/errors/server-errors.ts --- code/lib/core-events/src/errors/server-errors.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/code/lib/core-events/src/errors/server-errors.ts b/code/lib/core-events/src/errors/server-errors.ts index 188c299f4a66..964bbbb64a92 100644 --- a/code/lib/core-events/src/errors/server-errors.ts +++ b/code/lib/core-events/src/errors/server-errors.ts @@ -406,7 +406,7 @@ export class NoMatchingExportError extends StorybookError { Correct example: { "@storybook/react": "7.5.3", "@storybook/react-vite": "7.5.3", "storybook": "7.5.3" } - Clearing your lock file and reinstalling your dependencies might help as well. + Clearing your lock file and reinstalling your dependencies might help as well, as sometimes the version you see in your package.json might not be the one defined in your lock file, leading to version inconsistency issues. `; } } From 967f685f774daf8cafe4eae219942440753819ff Mon Sep 17 00:00:00 2001 From: Jeppe Reinhold Date: Wed, 22 Nov 2023 09:29:59 +0100 Subject: [PATCH 152/170] make parameter types public --- code/frameworks/sveltekit/src/preview.ts | 28 +--------------------- code/frameworks/sveltekit/src/types.ts | 30 +++++++++++++++++++++--- 2 files changed, 28 insertions(+), 30 deletions(-) diff --git a/code/frameworks/sveltekit/src/preview.ts b/code/frameworks/sveltekit/src/preview.ts index 23512ace57d8..a43431b5103d 100644 --- a/code/frameworks/sveltekit/src/preview.ts +++ b/code/frameworks/sveltekit/src/preview.ts @@ -1,35 +1,9 @@ import type { Decorator } from '@storybook/svelte'; import { action } from '@storybook/addon-actions'; import { onMount } from 'svelte'; -import type { enhance } from './mocks/app/forms'; -import type { goto, invalidate, invalidateAll, afterNavigate } from './mocks/app/navigation'; import { setAfterNavigateArgument } from './mocks/app/navigation'; import { setNavigating, setPage, setUpdated } from './mocks/app/stores'; - -type NormalizedHrefConfig = { - callback: (to: string, event: Event) => void; - asRegex?: boolean; -}; - -type HrefConfig = NormalizedHrefConfig | NormalizedHrefConfig['callback']; - -type SvelteKitParameters = Partial<{ - hrefs: Record; - stores: { - page: Record; - navigating: boolean; - updated: boolean; - }; - navigation: { - goto: typeof goto; - invalidate: typeof invalidate; - invalidateAll: typeof invalidateAll; - afterNavigate: typeof afterNavigate; - }; - forms: { - enhance: typeof enhance; - }; -}>; +import type { HrefConfig, NormalizedHrefConfig, SvelteKitParameters } from './types'; const normalizeHrefConfig = (hrefConfig: HrefConfig): NormalizedHrefConfig => { if (typeof hrefConfig === 'function') { diff --git a/code/frameworks/sveltekit/src/types.ts b/code/frameworks/sveltekit/src/types.ts index 647ea6fb5653..41fc01e844d5 100644 --- a/code/frameworks/sveltekit/src/types.ts +++ b/code/frameworks/sveltekit/src/types.ts @@ -1,5 +1,7 @@ import type { StorybookConfig as StorybookConfigBase } from '@storybook/types'; import type { StorybookConfigVite, BuilderOptions } from '@storybook/builder-vite'; +import type { afterNavigate, goto, invalidate, invalidateAll } from './mocks/app/navigation'; +import type { enhance } from './mocks/app/forms'; type FrameworkName = '@storybook/sveltekit'; type BuilderName = '@storybook/builder-vite'; @@ -25,12 +27,34 @@ type StorybookConfigFramework = { }; }; -/** - * The interface for Storybook configuration in `main.ts` files. - */ export type StorybookConfig = Omit< StorybookConfigBase, keyof StorybookConfigVite | keyof StorybookConfigFramework > & StorybookConfigVite & StorybookConfigFramework; + +export type NormalizedHrefConfig = { + callback: (to: string, event: Event) => void; + asRegex?: boolean; +}; + +export type HrefConfig = NormalizedHrefConfig | NormalizedHrefConfig['callback']; + +export type SvelteKitParameters = Partial<{ + hrefs: Record; + stores: { + page: Record; + navigating: boolean; + updated: boolean; + }; + navigation: { + goto: typeof goto; + invalidate: typeof invalidate; + invalidateAll: typeof invalidateAll; + afterNavigate: typeof afterNavigate; + }; + forms: { + enhance: typeof enhance; + }; +}>; From 9593addfa2004a2978c5179cd0d80975ef3496c8 Mon Sep 17 00:00:00 2001 From: paoloricciuti Date: Wed, 22 Nov 2023 09:33:22 +0100 Subject: [PATCH 153/170] fix types for SveltekitParameters --- code/frameworks/sveltekit/src/types.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/code/frameworks/sveltekit/src/types.ts b/code/frameworks/sveltekit/src/types.ts index 41fc01e844d5..0a726dab7678 100644 --- a/code/frameworks/sveltekit/src/types.ts +++ b/code/frameworks/sveltekit/src/types.ts @@ -45,14 +45,14 @@ export type SvelteKitParameters = Partial<{ hrefs: Record; stores: { page: Record; - navigating: boolean; + navigating: Record; updated: boolean; }; navigation: { goto: typeof goto; invalidate: typeof invalidate; invalidateAll: typeof invalidateAll; - afterNavigate: typeof afterNavigate; + afterNavigate: Record; }; forms: { enhance: typeof enhance; From 9e1bad022702ac33cdb7f2ae8b7e988494b3b153 Mon Sep 17 00:00:00 2001 From: paoloricciuti Date: Wed, 22 Nov 2023 09:42:16 +0100 Subject: [PATCH 154/170] remove afterNavigate import --- code/frameworks/sveltekit/src/types.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/code/frameworks/sveltekit/src/types.ts b/code/frameworks/sveltekit/src/types.ts index 0a726dab7678..c3f04a22bc82 100644 --- a/code/frameworks/sveltekit/src/types.ts +++ b/code/frameworks/sveltekit/src/types.ts @@ -1,7 +1,7 @@ +import type { BuilderOptions, StorybookConfigVite } from '@storybook/builder-vite'; import type { StorybookConfig as StorybookConfigBase } from '@storybook/types'; -import type { StorybookConfigVite, BuilderOptions } from '@storybook/builder-vite'; -import type { afterNavigate, goto, invalidate, invalidateAll } from './mocks/app/navigation'; import type { enhance } from './mocks/app/forms'; +import type { goto, invalidate, invalidateAll } from './mocks/app/navigation'; type FrameworkName = '@storybook/sveltekit'; type BuilderName = '@storybook/builder-vite'; From 8d612f3c245ee9fb4810d7ae07636690e2e43c65 Mon Sep 17 00:00:00 2001 From: Kasper Peulen Date: Wed, 22 Nov 2023 12:33:53 +0100 Subject: [PATCH 155/170] Model loaders as before each and restore mocks properly --- code/addons/links/package.json | 2 +- code/addons/storyshots-puppeteer/package.json | 2 +- code/lib/codemod/package.json | 2 +- code/lib/core-server/package.json | 2 +- code/lib/csf-tools/package.json | 2 +- code/lib/manager-api/package.json | 2 +- code/lib/preview-api/package.json | 2 +- .../src/modules/client-api/ClientApi.ts | 8 ++- .../preview-web/docs-context/DocsContext.ts | 2 +- .../preview-web/render/CsfDocsRender.ts | 4 +- .../preview-web/render/MdxDocsRender.ts | 4 +- .../src/modules/store/csf/normalizeArrays.ts | 4 ++ .../store/csf/normalizeProjectAnnotations.ts | 5 ++ .../src/modules/store/csf/normalizeStory.ts | 9 ++- .../src/modules/store/csf/prepareStory.ts | 49 ++++++++------ .../src/modules/store/sortStories.ts | 5 +- code/lib/source-loader/package.json | 2 +- code/lib/test/package.json | 2 +- code/lib/test/src/index.ts | 28 ++++---- code/lib/test/src/spy.ts | 66 +++++++++++++++++++ code/lib/types/package.json | 2 +- code/lib/types/src/modules/story.ts | 43 ++++++++---- code/package.json | 2 +- code/renderers/server/package.json | 2 +- code/ui/blocks/package.json | 2 +- code/ui/components/package.json | 2 +- code/yarn.lock | 44 ++++++------- 27 files changed, 206 insertions(+), 93 deletions(-) create mode 100644 code/lib/preview-api/src/modules/store/csf/normalizeArrays.ts create mode 100644 code/lib/test/src/spy.ts diff --git a/code/addons/links/package.json b/code/addons/links/package.json index 91039a15cdf4..c83dda4ab515 100644 --- a/code/addons/links/package.json +++ b/code/addons/links/package.json @@ -63,7 +63,7 @@ "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/addon-bundle.ts" }, "dependencies": { - "@storybook/csf": "^0.1.0", + "@storybook/csf": "0.1.2--canary.71.cad875c.0", "@storybook/global": "^5.0.0", "ts-dedent": "^2.0.0" }, diff --git a/code/addons/storyshots-puppeteer/package.json b/code/addons/storyshots-puppeteer/package.json index 6ffb44476d17..009f4ac4d346 100644 --- a/code/addons/storyshots-puppeteer/package.json +++ b/code/addons/storyshots-puppeteer/package.json @@ -37,7 +37,7 @@ }, "dependencies": { "@axe-core/puppeteer": "^4.2.0", - "@storybook/csf": "^0.1.0", + "@storybook/csf": "0.1.2--canary.71.cad875c.0", "@storybook/node-logger": "workspace:*", "@storybook/types": "workspace:*", "@types/jest-image-snapshot": "^6.0.0", diff --git a/code/lib/codemod/package.json b/code/lib/codemod/package.json index ac98a974c4b3..3b49d8bc6280 100644 --- a/code/lib/codemod/package.json +++ b/code/lib/codemod/package.json @@ -55,7 +55,7 @@ "@babel/core": "^7.23.2", "@babel/preset-env": "^7.23.2", "@babel/types": "^7.23.0", - "@storybook/csf": "^0.1.0", + "@storybook/csf": "0.1.2--canary.71.cad875c.0", "@storybook/csf-tools": "workspace:*", "@storybook/node-logger": "workspace:*", "@storybook/types": "workspace:*", diff --git a/code/lib/core-server/package.json b/code/lib/core-server/package.json index 830a25f85e89..12c6ba983de9 100644 --- a/code/lib/core-server/package.json +++ b/code/lib/core-server/package.json @@ -66,7 +66,7 @@ "@storybook/channels": "workspace:*", "@storybook/core-common": "workspace:*", "@storybook/core-events": "workspace:*", - "@storybook/csf": "^0.1.0", + "@storybook/csf": "0.1.2--canary.71.cad875c.0", "@storybook/csf-tools": "workspace:*", "@storybook/docs-mdx": "^0.1.0", "@storybook/global": "^5.0.0", diff --git a/code/lib/csf-tools/package.json b/code/lib/csf-tools/package.json index 252055c7957e..6b5f1ebac76b 100644 --- a/code/lib/csf-tools/package.json +++ b/code/lib/csf-tools/package.json @@ -46,7 +46,7 @@ "@babel/parser": "^7.23.0", "@babel/traverse": "^7.23.2", "@babel/types": "^7.23.0", - "@storybook/csf": "^0.1.0", + "@storybook/csf": "0.1.2--canary.71.cad875c.0", "@storybook/types": "workspace:*", "fs-extra": "^11.1.0", "recast": "^0.23.1", diff --git a/code/lib/manager-api/package.json b/code/lib/manager-api/package.json index f8f760e004cb..16d9821cdfb2 100644 --- a/code/lib/manager-api/package.json +++ b/code/lib/manager-api/package.json @@ -46,7 +46,7 @@ "@storybook/channels": "workspace:*", "@storybook/client-logger": "workspace:*", "@storybook/core-events": "workspace:*", - "@storybook/csf": "^0.1.0", + "@storybook/csf": "0.1.2--canary.71.cad875c.0", "@storybook/global": "^5.0.0", "@storybook/router": "workspace:*", "@storybook/theming": "workspace:*", diff --git a/code/lib/preview-api/package.json b/code/lib/preview-api/package.json index 5884953f4496..46b1d163d580 100644 --- a/code/lib/preview-api/package.json +++ b/code/lib/preview-api/package.json @@ -71,7 +71,7 @@ "@storybook/channels": "workspace:*", "@storybook/client-logger": "workspace:*", "@storybook/core-events": "workspace:*", - "@storybook/csf": "^0.1.0", + "@storybook/csf": "0.1.2--canary.71.cad875c.0", "@storybook/global": "^5.0.0", "@storybook/types": "workspace:*", "@types/qs": "^6.9.5", diff --git a/code/lib/preview-api/src/modules/client-api/ClientApi.ts b/code/lib/preview-api/src/modules/client-api/ClientApi.ts index 83a2ba0cd6b0..d68bf30b47cd 100644 --- a/code/lib/preview-api/src/modules/client-api/ClientApi.ts +++ b/code/lib/preview-api/src/modules/client-api/ClientApi.ts @@ -168,9 +168,11 @@ export class ClientApi { } }; - addStepRunner = (stepRunner: StepRunner) => { + addStepRunner = (stepRunner: StepRunner) => { this.facade.projectAnnotations.runStep = composeStepRunners( - [this.facade.projectAnnotations.runStep, stepRunner].filter(Boolean) as StepRunner[] + [this.facade.projectAnnotations.runStep, stepRunner].filter( + Boolean + ) as StepRunner[] ); }; @@ -297,7 +299,7 @@ export class ClientApi { this._addedExports[fileName] = { default: meta }; let counter = 0; - api.add = (storyName: string, storyFn: StoryFn, parameters: Parameters = {}) => { + api.add = (storyName: string, storyFn: StoryFn, parameters: Parameters = {}) => { hasAdded = true; if (typeof storyName !== 'string') { diff --git a/code/lib/preview-api/src/modules/preview-web/docs-context/DocsContext.ts b/code/lib/preview-api/src/modules/preview-web/docs-context/DocsContext.ts index 6796913596bd..40ea0ccbaa03 100644 --- a/code/lib/preview-api/src/modules/preview-web/docs-context/DocsContext.ts +++ b/code/lib/preview-api/src/modules/preview-web/docs-context/DocsContext.ts @@ -34,7 +34,7 @@ export class DocsContext implements DocsContextProps constructor( public channel: Channel, protected store: StoryStore, - public renderStoryToElement: DocsContextProps['renderStoryToElement'], + public renderStoryToElement: DocsContextProps['renderStoryToElement'], /** The CSF files known (via the index) to be refererenced by this docs file */ csfFiles: CSFFile[] ) { diff --git a/code/lib/preview-api/src/modules/preview-web/render/CsfDocsRender.ts b/code/lib/preview-api/src/modules/preview-web/render/CsfDocsRender.ts index a4fbb47b9e01..019d43d97893 100644 --- a/code/lib/preview-api/src/modules/preview-web/render/CsfDocsRender.ts +++ b/code/lib/preview-api/src/modules/preview-web/render/CsfDocsRender.ts @@ -95,7 +95,7 @@ export class CsfDocsRender implements Render['renderStoryToElement']) { if (!this.csfFiles) throw new Error('Cannot render docs before preparing'); const docsContext = new DocsContext( this.channel, @@ -112,7 +112,7 @@ export class CsfDocsRender implements Render['renderStoryToElement'] ) { if (!this.story || !this.csfFiles) throw new Error('Cannot render docs before preparing'); diff --git a/code/lib/preview-api/src/modules/preview-web/render/MdxDocsRender.ts b/code/lib/preview-api/src/modules/preview-web/render/MdxDocsRender.ts index ca81e01d438a..987dc7680192 100644 --- a/code/lib/preview-api/src/modules/preview-web/render/MdxDocsRender.ts +++ b/code/lib/preview-api/src/modules/preview-web/render/MdxDocsRender.ts @@ -79,7 +79,7 @@ export class MdxDocsRender implements Render['renderStoryToElement']) { if (!this.csfFiles) throw new Error('Cannot render docs before preparing'); // NOTE we do *not* attach any CSF file yet. We wait for `referenceMeta(..., true)` @@ -94,7 +94,7 @@ export class MdxDocsRender implements Render['renderStoryToElement'] ) { if (!this.exports || !this.csfFiles || !this.store.projectAnnotations) throw new Error('Cannot render docs before preparing'); diff --git a/code/lib/preview-api/src/modules/store/csf/normalizeArrays.ts b/code/lib/preview-api/src/modules/store/csf/normalizeArrays.ts new file mode 100644 index 000000000000..7253f120e24f --- /dev/null +++ b/code/lib/preview-api/src/modules/store/csf/normalizeArrays.ts @@ -0,0 +1,4 @@ +export const normalizeArrays = (array: T[] | T | undefined): T[] => { + if (Array.isArray(array)) return array; + return typeof array === 'function' ? [array] : []; +}; diff --git a/code/lib/preview-api/src/modules/store/csf/normalizeProjectAnnotations.ts b/code/lib/preview-api/src/modules/store/csf/normalizeProjectAnnotations.ts index a93bf3584395..e2e6a88db31e 100644 --- a/code/lib/preview-api/src/modules/store/csf/normalizeProjectAnnotations.ts +++ b/code/lib/preview-api/src/modules/store/csf/normalizeProjectAnnotations.ts @@ -8,16 +8,21 @@ import type { import { inferArgTypes } from '../inferArgTypes'; import { inferControls } from '../inferControls'; import { normalizeInputTypes } from './normalizeInputTypes'; +import { normalizeArrays } from './normalizeArrays'; export function normalizeProjectAnnotations({ argTypes, globalTypes, argTypesEnhancers, + decorators, + loaders, ...annotations }: ProjectAnnotations): NormalizedProjectAnnotations { return { ...(argTypes && { argTypes: normalizeInputTypes(argTypes as ArgTypes) }), ...(globalTypes && { globalTypes: normalizeInputTypes(globalTypes) }), + decorators: normalizeArrays(decorators), + loaders: normalizeArrays(loaders), argTypesEnhancers: [ ...(argTypesEnhancers || []), inferArgTypes, diff --git a/code/lib/preview-api/src/modules/store/csf/normalizeStory.ts b/code/lib/preview-api/src/modules/store/csf/normalizeStory.ts index 6666a95217b5..9a96bc4a332e 100644 --- a/code/lib/preview-api/src/modules/store/csf/normalizeStory.ts +++ b/code/lib/preview-api/src/modules/store/csf/normalizeStory.ts @@ -13,6 +13,7 @@ import { dedent } from 'ts-dedent'; import { logger } from '@storybook/client-logger'; import deprecate from 'util-deprecate'; import { normalizeInputTypes } from './normalizeInputTypes'; +import { normalizeArrays } from './normalizeArrays'; const deprecatedStoryAnnotation = dedent` CSF .story annotations deprecated; annotate story functions directly: @@ -44,11 +45,15 @@ export function normalizeStory( storyObject.storyName || story?.name || exportName; - const decorators = [...(storyObject.decorators || []), ...(story?.decorators || [])]; + + const decorators = [ + ...normalizeArrays(storyObject.decorators), + ...normalizeArrays(story?.decorators), + ]; const parameters = { ...story?.parameters, ...storyObject.parameters }; const args = { ...story?.args, ...storyObject.args }; const argTypes = { ...(story?.argTypes as ArgTypes), ...(storyObject.argTypes as ArgTypes) }; - const loaders = [...(storyObject.loaders || []), ...(story?.loaders || [])]; + const loaders = [...normalizeArrays(storyObject.loaders), ...normalizeArrays(story?.loaders)]; const { render, play, tags = [] } = storyObject; // eslint-disable-next-line no-underscore-dangle diff --git a/code/lib/preview-api/src/modules/store/csf/prepareStory.ts b/code/lib/preview-api/src/modules/store/csf/prepareStory.ts index e4bfb1937114..64306fedb327 100644 --- a/code/lib/preview-api/src/modules/store/csf/prepareStory.ts +++ b/code/lib/preview-api/src/modules/store/csf/prepareStory.ts @@ -1,24 +1,25 @@ +/* eslint-disable no-restricted-syntax,no-await-in-loop,@typescript-eslint/no-loop-func */ import { global } from '@storybook/global'; import type { - Renderer, Args, ArgsStoryFn, LegacyStoryFn, - Parameters, - PlayFunction, - PlayFunctionContext, - StepLabel, + ModuleExport, NormalizedComponentAnnotations, NormalizedProjectAnnotations, NormalizedStoryAnnotations, + Parameters, + PlayFunction, + PlayFunctionContext, + PreparedMeta, PreparedStory, + Renderer, + StepLabel, StoryContext, StoryContextForEnhancers, StoryContextForLoaders, StrictArgTypes, - PreparedMeta, - ModuleExport, } from '@storybook/types'; import { includeConditionalArg } from '@storybook/csf'; @@ -26,6 +27,7 @@ import { applyHooks } from '../../addons'; import { combineParameters } from '../parameters'; import { defaultDecorateStory } from '../decorators'; import { groupArgsByTarget, UNTARGETED } from '../args'; +import { normalizeArrays } from './normalizeArrays'; // Combine all the metadata about a story (both direct and inherited from the component/global scope) // into a "renderable" story function, with all decorators applied, parameters passed as context etc @@ -48,15 +50,23 @@ export function prepareStory( projectAnnotations ); - const loaders = [ - ...(projectAnnotations.loaders || []), - ...(componentAnnotations.loaders || []), - ...(storyAnnotations?.loaders || []), - ]; - const applyLoaders = async (context: StoryContextForLoaders) => { - const loadResults = await Promise.all(loaders.map((loader) => loader(context))); - const loaded = Object.assign({}, ...loadResults); - return { ...context, loaded }; + const applyLoaders = async ( + context: StoryContextForLoaders + ): Promise & { loaded: StoryContext['loaded'] }> => { + let updatedContext = { ...context, loaded: {} }; + for (const loaders of [ + ...('testPackageLoaders' in global && Array.isArray(global.testPackageLoaders) + ? [global.testPackageLoaders] + : []), + normalizeArrays(projectAnnotations.loaders), + normalizeArrays(componentAnnotations.loaders), + normalizeArrays(storyAnnotations.loaders), + ]) { + const loadResults = await Promise.all(loaders.map((loader) => loader(updatedContext))); + const loaded: Record = Object.assign({}, ...loadResults); + updatedContext = { ...updatedContext, loaded: { ...updatedContext.loaded, ...loaded } }; + } + return updatedContext; }; const undecoratedStoryFn: LegacyStoryFn = (context: StoryContext) => { @@ -70,9 +80,9 @@ export function prepareStory( const { applyDecorators = defaultDecorateStory, runStep } = projectAnnotations; const decorators = [ - ...(storyAnnotations?.decorators || []), - ...(componentAnnotations.decorators || []), - ...(projectAnnotations.decorators || []), + ...normalizeArrays(storyAnnotations?.decorators), + ...normalizeArrays(componentAnnotations?.decorators), + ...normalizeArrays(projectAnnotations?.decorators), ]; // The render function on annotations *has* to be an `ArgsStoryFn`, so when we normalize @@ -115,7 +125,6 @@ export function prepareStory( playFunction, }; } - export function prepareMeta( componentAnnotations: NormalizedComponentAnnotations, projectAnnotations: NormalizedProjectAnnotations, diff --git a/code/lib/preview-api/src/modules/store/sortStories.ts b/code/lib/preview-api/src/modules/store/sortStories.ts index 4335b6f72103..8fc6950fbd40 100644 --- a/code/lib/preview-api/src/modules/store/sortStories.ts +++ b/code/lib/preview-api/src/modules/store/sortStories.ts @@ -9,6 +9,7 @@ import type { Parameters, Path, PreparedStory, + Renderer, } from '@storybook/types'; import { storySort } from './storySort'; @@ -58,8 +59,8 @@ const toIndexEntry = (story: any): StoryIndexEntry => { return { id, title, name, importPath: parameters.fileName, type }; }; -export const sortStoriesV6 = ( - stories: [string, PreparedStory, Parameters, Parameters][], +export const sortStoriesV6 = ( + stories: [string, PreparedStory, Parameters, Parameters][], storySortParameter: Addon_StorySortParameter, fileNameOrder: Path[] ) => { diff --git a/code/lib/source-loader/package.json b/code/lib/source-loader/package.json index 98b44a0f9d62..b4310b61f1bd 100644 --- a/code/lib/source-loader/package.json +++ b/code/lib/source-loader/package.json @@ -45,7 +45,7 @@ "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { - "@storybook/csf": "^0.1.0", + "@storybook/csf": "0.1.2--canary.71.cad875c.0", "@storybook/types": "workspace:*", "estraverse": "^5.2.0", "lodash": "^4.17.21", diff --git a/code/lib/test/package.json b/code/lib/test/package.json index d75491d9cbb1..41c3d658bad1 100644 --- a/code/lib/test/package.json +++ b/code/lib/test/package.json @@ -19,7 +19,7 @@ "url": "https://opencollective.com/storybook" }, "license": "MIT", - "sideEffects": false, + "sideEffects": true, "exports": { ".": { "types": "./dist/index.d.ts", diff --git a/code/lib/test/src/index.ts b/code/lib/test/src/index.ts index 34d59391676e..57612fc8a6c3 100644 --- a/code/lib/test/src/index.ts +++ b/code/lib/test/src/index.ts @@ -1,18 +1,11 @@ import { instrument } from '@storybook/instrumenter'; -import * as spy from '@vitest/spy'; +import { type LoaderFunction } from '@storybook/csf'; import chai from 'chai'; -import { FORCE_REMOUNT, STORY_RENDER_PHASE_CHANGED } from '@storybook/core-events'; -import { addons } from '@storybook/preview-api'; +import { global } from '@storybook/global'; import { expect as rawExpect } from './expect'; +import { clearAllMocks, resetAllMocks, restoreAllMocks } from './spy'; -export * from '@vitest/spy'; - -const channel = addons.getChannel(); - -channel.on(FORCE_REMOUNT, () => spy.spies.forEach((mock) => mock.mockClear())); -channel.on(STORY_RENDER_PHASE_CHANGED, ({ newPhase }) => { - if (newPhase === 'loading') spy.spies.forEach((mock) => mock.mockClear()); -}); +export * from './spy'; export const { expect } = instrument( { expect: rawExpect }, @@ -32,3 +25,16 @@ export const { expect } = instrument( ); export * from './testing-library'; + +const resetAllMocksLoader: LoaderFunction = ({ parameters }) => { + if (parameters?.test?.mockReset === true) { + resetAllMocks(); + } else if (parameters?.test?.clearMocks === true) { + clearAllMocks(); + } else if (parameters?.test?.restoreMocks !== false) { + restoreAllMocks(); + } +}; + +// @ts-expect-error Wwe are using this as a default loader, if the test package is used. But we don't want to get into optional peer dep shenanigans. +global.testPackageLoaders = [resetAllMocksLoader]; diff --git a/code/lib/test/src/spy.ts b/code/lib/test/src/spy.ts new file mode 100644 index 000000000000..8b0ce5f38e56 --- /dev/null +++ b/code/lib/test/src/spy.ts @@ -0,0 +1,66 @@ +import { + spyOn, + isMockFunction, + fn, + spies as mocks, + type MaybeMocked, + type MaybeMockedDeep, + type MaybePartiallyMocked, + type MaybePartiallyMockedDeep, +} from '@vitest/spy'; + +export type * from '@vitest/spy'; + +export { spyOn, isMockFunction, fn, mocks }; + +/** + * Calls [`.mockClear()`](https://vitest.dev/api/mock#mockclear) on every mocked function. This will only empty `.mock` state, it will not reset implementation. + * + * It is useful if you need to clean up mock between different assertions. + */ +export function clearAllMocks() { + mocks.forEach((spy) => spy.mockClear()); +} + +/** + * Calls [`.mockReset()`](https://vitest.dev/api/mock#mockreset) on every mocked function. This will empty `.mock` state, reset "once" implementations and force the base implementation to return `undefined` when invoked. + * + * This is useful when you want to completely reset a mock to the default state. + */ +export function resetAllMocks() { + mocks.forEach((spy) => spy.mockReset()); +} + +/** + * Calls [`.mockRestore()`](https://vitest.dev/api/mock#mockrestore) on every mocked function. This will restore all original implementations. + */ +export function restoreAllMocks() { + mocks.forEach((spy) => spy.mockRestore()); +} + +/** + * Type helper for TypeScript. Just returns the object that was passed. + * + * When `partial` is `true` it will expect a `Partial` as a return value. By default, this will only make TypeScript believe that + * the first level values are mocked. You can pass down `{ deep: true }` as a second argument to tell TypeScript that the whole object is mocked, if it actually is. + * + * @param item Anything that can be mocked + * @param deep If the object is deeply mocked + * @param options If the object is partially or deeply mocked + */ +export function mocked(item: T, deep?: false): MaybeMocked; +export function mocked(item: T, deep: true): MaybeMockedDeep; +export function mocked(item: T, options: { partial?: false; deep?: false }): MaybeMocked; +export function mocked(item: T, options: { partial?: false; deep: true }): MaybeMockedDeep; +export function mocked( + item: T, + options: { partial: true; deep?: false } +): MaybePartiallyMocked; +export function mocked( + item: T, + options: { partial: true; deep: true } +): MaybePartiallyMockedDeep; +export function mocked(item: T): MaybeMocked; +export function mocked(item: T, _options = {}): MaybeMocked { + return item as any; +} diff --git a/code/lib/types/package.json b/code/lib/types/package.json index 078a827837a5..53bb317a2e1c 100644 --- a/code/lib/types/package.json +++ b/code/lib/types/package.json @@ -50,7 +50,7 @@ "file-system-cache": "2.3.0" }, "devDependencies": { - "@storybook/csf": "^0.1.0", + "@storybook/csf": "0.1.2--canary.71.cad875c.0", "@types/fs-extra": "^11.0.1", "@types/node": "^18.0.0", "typescript": "~4.9.3" diff --git a/code/lib/types/src/modules/story.ts b/code/lib/types/src/modules/story.ts index c1a5b9d6ffdd..cc88807ade87 100644 --- a/code/lib/types/src/modules/story.ts +++ b/code/lib/types/src/modules/story.ts @@ -1,4 +1,9 @@ -import type { Renderer, ProjectAnnotations as CsfProjectAnnotations } from '@storybook/csf'; +import type { + Renderer, + ProjectAnnotations as CsfProjectAnnotations, + DecoratorFunction, + LoaderFunction, +} from '@storybook/csf'; import type { ComponentAnnotations, @@ -42,23 +47,31 @@ export type ProjectAnnotations = CsfProjectAnnotatio renderToDOM?: RenderToCanvas; }; -export type NormalizedProjectAnnotations = - ProjectAnnotations & { - argTypes?: StrictArgTypes; - globalTypes?: StrictGlobalTypes; - }; +export type NormalizedProjectAnnotations = Omit< + ProjectAnnotations, + 'decorators' | 'loaders' +> & { + argTypes?: StrictArgTypes; + globalTypes?: StrictGlobalTypes; + decorators?: DecoratorFunction[]; + loaders?: LoaderFunction[]; +}; -export type NormalizedComponentAnnotations = - ComponentAnnotations & { - // Useful to guarantee that id & title exists - id: ComponentId; - title: ComponentTitle; - argTypes?: StrictArgTypes; - }; +export type NormalizedComponentAnnotations = Omit< + ComponentAnnotations, + 'decorators' | 'loaders' +> & { + // Useful to guarantee that id & title exists + id: ComponentId; + title: ComponentTitle; + argTypes?: StrictArgTypes; + decorators: DecoratorFunction[]; + loaders: LoaderFunction[]; +}; export type NormalizedStoryAnnotations = Omit< StoryAnnotations, - 'storyName' | 'story' + 'storyName' | 'story' | 'decorators' | 'loaders' > & { moduleExport: ModuleExport; // You cannot actually set id on story annotations, but we normalize it to be there for convience @@ -66,6 +79,8 @@ export type NormalizedStoryAnnotations = argTypes?: StrictArgTypes; name: StoryName; userStoryFn?: StoryFn; + decorators?: DecoratorFunction[]; + loaders?: LoaderFunction[]; }; export type CSFFile = { diff --git a/code/package.json b/code/package.json index a98045536f60..f371794f23be 100644 --- a/code/package.json +++ b/code/package.json @@ -140,7 +140,7 @@ "@storybook/core-events": "workspace:*", "@storybook/core-server": "workspace:*", "@storybook/core-webpack": "workspace:*", - "@storybook/csf": "^0.1.0", + "@storybook/csf": "0.1.2--canary.71.cad875c.0", "@storybook/csf-plugin": "workspace:*", "@storybook/csf-tools": "workspace:*", "@storybook/docs-tools": "workspace:*", diff --git a/code/renderers/server/package.json b/code/renderers/server/package.json index ae2f96fe428f..6d62894c70e0 100644 --- a/code/renderers/server/package.json +++ b/code/renderers/server/package.json @@ -47,7 +47,7 @@ }, "dependencies": { "@storybook/core-client": "workspace:*", - "@storybook/csf": "^0.1.0", + "@storybook/csf": "0.1.2--canary.71.cad875c.0", "@storybook/csf-tools": "workspace:*", "@storybook/global": "^5.0.0", "@storybook/preview-api": "workspace:*", diff --git a/code/ui/blocks/package.json b/code/ui/blocks/package.json index b42af01f67db..d8e1d6eb0fe5 100644 --- a/code/ui/blocks/package.json +++ b/code/ui/blocks/package.json @@ -48,7 +48,7 @@ "@storybook/client-logger": "workspace:*", "@storybook/components": "workspace:*", "@storybook/core-events": "workspace:*", - "@storybook/csf": "^0.1.0", + "@storybook/csf": "0.1.2--canary.71.cad875c.0", "@storybook/docs-tools": "workspace:*", "@storybook/global": "^5.0.0", "@storybook/manager-api": "workspace:*", diff --git a/code/ui/components/package.json b/code/ui/components/package.json index 13e69c16ff8b..c31988d7c1d6 100644 --- a/code/ui/components/package.json +++ b/code/ui/components/package.json @@ -62,7 +62,7 @@ "@radix-ui/react-select": "^1.2.2", "@radix-ui/react-toolbar": "^1.0.4", "@storybook/client-logger": "workspace:*", - "@storybook/csf": "^0.1.0", + "@storybook/csf": "0.1.2--canary.71.cad875c.0", "@storybook/global": "^5.0.0", "@storybook/theming": "workspace:*", "@storybook/types": "workspace:*", diff --git a/code/yarn.lock b/code/yarn.lock index d2928cb17c0e..0008e9657efa 100644 --- a/code/yarn.lock +++ b/code/yarn.lock @@ -5655,7 +5655,7 @@ __metadata: dependencies: "@storybook/client-logger": "workspace:*" "@storybook/core-events": "workspace:*" - "@storybook/csf": "npm:^0.1.0" + "@storybook/csf": "npm:0.1.2--canary.71.cad875c.0" "@storybook/global": "npm:^5.0.0" "@storybook/manager-api": "workspace:*" "@storybook/preview-api": "workspace:*" @@ -5724,7 +5724,7 @@ __metadata: resolution: "@storybook/addon-storyshots-puppeteer@workspace:addons/storyshots-puppeteer" dependencies: "@axe-core/puppeteer": "npm:^4.2.0" - "@storybook/csf": "npm:^0.1.0" + "@storybook/csf": "npm:0.1.2--canary.71.cad875c.0" "@storybook/node-logger": "workspace:*" "@storybook/types": "workspace:*" "@types/jest-image-snapshot": "npm:^6.0.0" @@ -6033,7 +6033,7 @@ __metadata: "@storybook/client-logger": "workspace:*" "@storybook/components": "workspace:*" "@storybook/core-events": "workspace:*" - "@storybook/csf": "npm:^0.1.0" + "@storybook/csf": "npm:0.1.2--canary.71.cad875c.0" "@storybook/docs-tools": "workspace:*" "@storybook/global": "npm:^5.0.0" "@storybook/manager-api": "workspace:*" @@ -6306,7 +6306,7 @@ __metadata: "@babel/core": "npm:^7.23.2" "@babel/preset-env": "npm:^7.23.2" "@babel/types": "npm:^7.23.0" - "@storybook/csf": "npm:^0.1.0" + "@storybook/csf": "npm:0.1.2--canary.71.cad875c.0" "@storybook/csf-tools": "workspace:*" "@storybook/node-logger": "workspace:*" "@storybook/types": "workspace:*" @@ -6344,7 +6344,7 @@ __metadata: "@radix-ui/react-select": "npm:^1.2.2" "@radix-ui/react-toolbar": "npm:^1.0.4" "@storybook/client-logger": "workspace:*" - "@storybook/csf": "npm:^0.1.0" + "@storybook/csf": "npm:0.1.2--canary.71.cad875c.0" "@storybook/global": "npm:^5.0.0" "@storybook/icons": "npm:^1.1.6" "@storybook/theming": "workspace:*" @@ -6434,7 +6434,7 @@ __metadata: "@storybook/channels": "workspace:*" "@storybook/core-common": "workspace:*" "@storybook/core-events": "workspace:*" - "@storybook/csf": "npm:^0.1.0" + "@storybook/csf": "npm:0.1.2--canary.71.cad875c.0" "@storybook/csf-tools": "workspace:*" "@storybook/docs-mdx": "npm:^0.1.0" "@storybook/global": "npm:^5.0.0" @@ -6515,7 +6515,7 @@ __metadata: "@babel/parser": "npm:^7.23.0" "@babel/traverse": "npm:^7.23.2" "@babel/types": "npm:^7.23.0" - "@storybook/csf": "npm:^0.1.0" + "@storybook/csf": "npm:0.1.2--canary.71.cad875c.0" "@storybook/types": "workspace:*" "@types/fs-extra": "npm:^11.0.1" "@types/js-yaml": "npm:^4.0.5" @@ -6527,6 +6527,15 @@ __metadata: languageName: unknown linkType: soft +"@storybook/csf@npm:0.1.2--canary.71.cad875c.0": + version: 0.1.2--canary.71.cad875c.0 + resolution: "@storybook/csf@npm:0.1.2--canary.71.cad875c.0" + dependencies: + type-fest: "npm:^2.19.0" + checksum: 6a26cbcc41a5a73374fff6329b47479dacf1af46112c4d1e11bce2e3f6e9992c61765dcd99cf0de18a209d4a21a824c2162cec0758f83d0a977b0cd90c5191eb + languageName: node + linkType: hard + "@storybook/csf@npm:^0.0.1": version: 0.0.1 resolution: "@storybook/csf@npm:0.0.1" @@ -6536,15 +6545,6 @@ __metadata: languageName: node linkType: hard -"@storybook/csf@npm:^0.1.0": - version: 0.1.1 - resolution: "@storybook/csf@npm:0.1.1" - dependencies: - type-fest: "npm:^2.19.0" - checksum: 999bb87fbbe047a559bbaa5baf2ed84872fcd5cdcae3c1169f8e4c641eefe8759d09a09034a78ed114032c0e5cf6301b7fa89e5e3ce60d75cf0bd5e33ec0a6e7 - languageName: node - linkType: hard - "@storybook/design-system@npm:^7.15.15": version: 7.15.15 resolution: "@storybook/design-system@npm:7.15.15" @@ -6765,7 +6765,7 @@ __metadata: "@storybook/channels": "workspace:*" "@storybook/client-logger": "workspace:*" "@storybook/core-events": "workspace:*" - "@storybook/csf": "npm:^0.1.0" + "@storybook/csf": "npm:0.1.2--canary.71.cad875c.0" "@storybook/global": "npm:^5.0.0" "@storybook/router": "workspace:*" "@storybook/theming": "workspace:*" @@ -7174,7 +7174,7 @@ __metadata: "@storybook/client-logger": "workspace:*" "@storybook/core-common": "workspace:*" "@storybook/core-events": "workspace:*" - "@storybook/csf": "npm:^0.1.0" + "@storybook/csf": "npm:0.1.2--canary.71.cad875c.0" "@storybook/global": "npm:^5.0.0" "@storybook/types": "workspace:*" "@types/qs": "npm:^6.9.5" @@ -7383,7 +7383,7 @@ __metadata: "@storybook/core-events": "workspace:*" "@storybook/core-server": "workspace:*" "@storybook/core-webpack": "workspace:*" - "@storybook/csf": "npm:^0.1.0" + "@storybook/csf": "npm:0.1.2--canary.71.cad875c.0" "@storybook/csf-plugin": "workspace:*" "@storybook/csf-tools": "workspace:*" "@storybook/docs-tools": "workspace:*" @@ -7556,7 +7556,7 @@ __metadata: resolution: "@storybook/server@workspace:renderers/server" dependencies: "@storybook/core-client": "workspace:*" - "@storybook/csf": "npm:^0.1.0" + "@storybook/csf": "npm:0.1.2--canary.71.cad875c.0" "@storybook/csf-tools": "workspace:*" "@storybook/global": "npm:^5.0.0" "@storybook/preview-api": "workspace:*" @@ -7573,7 +7573,7 @@ __metadata: version: 0.0.0-use.local resolution: "@storybook/source-loader@workspace:lib/source-loader" dependencies: - "@storybook/csf": "npm:^0.1.0" + "@storybook/csf": "npm:0.1.2--canary.71.cad875c.0" "@storybook/types": "workspace:*" estraverse: "npm:^5.2.0" jest-specific-snapshot: "npm:^8.0.0" @@ -7767,7 +7767,7 @@ __metadata: resolution: "@storybook/types@workspace:lib/types" dependencies: "@storybook/channels": "workspace:*" - "@storybook/csf": "npm:^0.1.0" + "@storybook/csf": "npm:0.1.2--canary.71.cad875c.0" "@types/babel__core": "npm:^7.0.0" "@types/express": "npm:^4.7.0" "@types/fs-extra": "npm:^11.0.1" From 0130a0acc9d41a84516266ba4ae5a1450e4671a9 Mon Sep 17 00:00:00 2001 From: Kasper Peulen Date: Wed, 22 Nov 2023 12:40:02 +0100 Subject: [PATCH 156/170] Pin new csf version --- code/addons/links/package.json | 2 +- code/addons/storyshots-puppeteer/package.json | 2 +- code/lib/codemod/package.json | 2 +- code/lib/core-server/package.json | 2 +- code/lib/csf-tools/package.json | 2 +- code/lib/manager-api/package.json | 2 +- code/lib/preview-api/package.json | 2 +- .../modules/store/csf/testing-utils/index.ts | 2 +- code/lib/source-loader/package.json | 2 +- code/lib/types/package.json | 2 +- code/package.json | 2 +- code/renderers/server/package.json | 2 +- code/ui/blocks/package.json | 2 +- code/ui/components/package.json | 2 +- code/yarn.lock | 34 +++++++++---------- 15 files changed, 31 insertions(+), 31 deletions(-) diff --git a/code/addons/links/package.json b/code/addons/links/package.json index c83dda4ab515..54e7bbca7105 100644 --- a/code/addons/links/package.json +++ b/code/addons/links/package.json @@ -63,7 +63,7 @@ "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/addon-bundle.ts" }, "dependencies": { - "@storybook/csf": "0.1.2--canary.71.cad875c.0", + "@storybook/csf": "0.1.2-next.0", "@storybook/global": "^5.0.0", "ts-dedent": "^2.0.0" }, diff --git a/code/addons/storyshots-puppeteer/package.json b/code/addons/storyshots-puppeteer/package.json index 009f4ac4d346..5949d89338b4 100644 --- a/code/addons/storyshots-puppeteer/package.json +++ b/code/addons/storyshots-puppeteer/package.json @@ -37,7 +37,7 @@ }, "dependencies": { "@axe-core/puppeteer": "^4.2.0", - "@storybook/csf": "0.1.2--canary.71.cad875c.0", + "@storybook/csf": "0.1.2-next.0", "@storybook/node-logger": "workspace:*", "@storybook/types": "workspace:*", "@types/jest-image-snapshot": "^6.0.0", diff --git a/code/lib/codemod/package.json b/code/lib/codemod/package.json index 3b49d8bc6280..e8f0a213dfb4 100644 --- a/code/lib/codemod/package.json +++ b/code/lib/codemod/package.json @@ -55,7 +55,7 @@ "@babel/core": "^7.23.2", "@babel/preset-env": "^7.23.2", "@babel/types": "^7.23.0", - "@storybook/csf": "0.1.2--canary.71.cad875c.0", + "@storybook/csf": "0.1.2-next.0", "@storybook/csf-tools": "workspace:*", "@storybook/node-logger": "workspace:*", "@storybook/types": "workspace:*", diff --git a/code/lib/core-server/package.json b/code/lib/core-server/package.json index 12c6ba983de9..557651a48e43 100644 --- a/code/lib/core-server/package.json +++ b/code/lib/core-server/package.json @@ -66,7 +66,7 @@ "@storybook/channels": "workspace:*", "@storybook/core-common": "workspace:*", "@storybook/core-events": "workspace:*", - "@storybook/csf": "0.1.2--canary.71.cad875c.0", + "@storybook/csf": "0.1.2-next.0", "@storybook/csf-tools": "workspace:*", "@storybook/docs-mdx": "^0.1.0", "@storybook/global": "^5.0.0", diff --git a/code/lib/csf-tools/package.json b/code/lib/csf-tools/package.json index 6b5f1ebac76b..c5e4e5de536f 100644 --- a/code/lib/csf-tools/package.json +++ b/code/lib/csf-tools/package.json @@ -46,7 +46,7 @@ "@babel/parser": "^7.23.0", "@babel/traverse": "^7.23.2", "@babel/types": "^7.23.0", - "@storybook/csf": "0.1.2--canary.71.cad875c.0", + "@storybook/csf": "0.1.2-next.0", "@storybook/types": "workspace:*", "fs-extra": "^11.1.0", "recast": "^0.23.1", diff --git a/code/lib/manager-api/package.json b/code/lib/manager-api/package.json index 16d9821cdfb2..0e5e2e755952 100644 --- a/code/lib/manager-api/package.json +++ b/code/lib/manager-api/package.json @@ -46,7 +46,7 @@ "@storybook/channels": "workspace:*", "@storybook/client-logger": "workspace:*", "@storybook/core-events": "workspace:*", - "@storybook/csf": "0.1.2--canary.71.cad875c.0", + "@storybook/csf": "0.1.2-next.0", "@storybook/global": "^5.0.0", "@storybook/router": "workspace:*", "@storybook/theming": "workspace:*", diff --git a/code/lib/preview-api/package.json b/code/lib/preview-api/package.json index 46b1d163d580..39b9b4682d25 100644 --- a/code/lib/preview-api/package.json +++ b/code/lib/preview-api/package.json @@ -71,7 +71,7 @@ "@storybook/channels": "workspace:*", "@storybook/client-logger": "workspace:*", "@storybook/core-events": "workspace:*", - "@storybook/csf": "0.1.2--canary.71.cad875c.0", + "@storybook/csf": "0.1.2-next.0", "@storybook/global": "^5.0.0", "@storybook/types": "workspace:*", "@types/qs": "^6.9.5", diff --git a/code/lib/preview-api/src/modules/store/csf/testing-utils/index.ts b/code/lib/preview-api/src/modules/store/csf/testing-utils/index.ts index 10468737e6dc..c9a3731f4bd6 100644 --- a/code/lib/preview-api/src/modules/store/csf/testing-utils/index.ts +++ b/code/lib/preview-api/src/modules/store/csf/testing-utils/index.ts @@ -82,7 +82,7 @@ export function composeStory)); }, { storyName, diff --git a/code/lib/source-loader/package.json b/code/lib/source-loader/package.json index b4310b61f1bd..de7fa088395d 100644 --- a/code/lib/source-loader/package.json +++ b/code/lib/source-loader/package.json @@ -45,7 +45,7 @@ "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { - "@storybook/csf": "0.1.2--canary.71.cad875c.0", + "@storybook/csf": "0.1.2-next.0", "@storybook/types": "workspace:*", "estraverse": "^5.2.0", "lodash": "^4.17.21", diff --git a/code/lib/types/package.json b/code/lib/types/package.json index 53bb317a2e1c..30cb9f4c26f2 100644 --- a/code/lib/types/package.json +++ b/code/lib/types/package.json @@ -50,7 +50,7 @@ "file-system-cache": "2.3.0" }, "devDependencies": { - "@storybook/csf": "0.1.2--canary.71.cad875c.0", + "@storybook/csf": "0.1.2-next.0", "@types/fs-extra": "^11.0.1", "@types/node": "^18.0.0", "typescript": "~4.9.3" diff --git a/code/package.json b/code/package.json index f371794f23be..31ccd621bcd3 100644 --- a/code/package.json +++ b/code/package.json @@ -140,7 +140,7 @@ "@storybook/core-events": "workspace:*", "@storybook/core-server": "workspace:*", "@storybook/core-webpack": "workspace:*", - "@storybook/csf": "0.1.2--canary.71.cad875c.0", + "@storybook/csf": "0.1.2-next.0", "@storybook/csf-plugin": "workspace:*", "@storybook/csf-tools": "workspace:*", "@storybook/docs-tools": "workspace:*", diff --git a/code/renderers/server/package.json b/code/renderers/server/package.json index 6d62894c70e0..e0c3cabd0f67 100644 --- a/code/renderers/server/package.json +++ b/code/renderers/server/package.json @@ -47,7 +47,7 @@ }, "dependencies": { "@storybook/core-client": "workspace:*", - "@storybook/csf": "0.1.2--canary.71.cad875c.0", + "@storybook/csf": "0.1.2-next.0", "@storybook/csf-tools": "workspace:*", "@storybook/global": "^5.0.0", "@storybook/preview-api": "workspace:*", diff --git a/code/ui/blocks/package.json b/code/ui/blocks/package.json index d8e1d6eb0fe5..0f4385cb96cb 100644 --- a/code/ui/blocks/package.json +++ b/code/ui/blocks/package.json @@ -48,7 +48,7 @@ "@storybook/client-logger": "workspace:*", "@storybook/components": "workspace:*", "@storybook/core-events": "workspace:*", - "@storybook/csf": "0.1.2--canary.71.cad875c.0", + "@storybook/csf": "0.1.2-next.0", "@storybook/docs-tools": "workspace:*", "@storybook/global": "^5.0.0", "@storybook/manager-api": "workspace:*", diff --git a/code/ui/components/package.json b/code/ui/components/package.json index c31988d7c1d6..eb28b1280f12 100644 --- a/code/ui/components/package.json +++ b/code/ui/components/package.json @@ -62,7 +62,7 @@ "@radix-ui/react-select": "^1.2.2", "@radix-ui/react-toolbar": "^1.0.4", "@storybook/client-logger": "workspace:*", - "@storybook/csf": "0.1.2--canary.71.cad875c.0", + "@storybook/csf": "0.1.2-next.0", "@storybook/global": "^5.0.0", "@storybook/theming": "workspace:*", "@storybook/types": "workspace:*", diff --git a/code/yarn.lock b/code/yarn.lock index 0008e9657efa..ad6a2779f617 100644 --- a/code/yarn.lock +++ b/code/yarn.lock @@ -5655,7 +5655,7 @@ __metadata: dependencies: "@storybook/client-logger": "workspace:*" "@storybook/core-events": "workspace:*" - "@storybook/csf": "npm:0.1.2--canary.71.cad875c.0" + "@storybook/csf": "npm:0.1.2-next.0" "@storybook/global": "npm:^5.0.0" "@storybook/manager-api": "workspace:*" "@storybook/preview-api": "workspace:*" @@ -5724,7 +5724,7 @@ __metadata: resolution: "@storybook/addon-storyshots-puppeteer@workspace:addons/storyshots-puppeteer" dependencies: "@axe-core/puppeteer": "npm:^4.2.0" - "@storybook/csf": "npm:0.1.2--canary.71.cad875c.0" + "@storybook/csf": "npm:0.1.2-next.0" "@storybook/node-logger": "workspace:*" "@storybook/types": "workspace:*" "@types/jest-image-snapshot": "npm:^6.0.0" @@ -6033,7 +6033,7 @@ __metadata: "@storybook/client-logger": "workspace:*" "@storybook/components": "workspace:*" "@storybook/core-events": "workspace:*" - "@storybook/csf": "npm:0.1.2--canary.71.cad875c.0" + "@storybook/csf": "npm:0.1.2-next.0" "@storybook/docs-tools": "workspace:*" "@storybook/global": "npm:^5.0.0" "@storybook/manager-api": "workspace:*" @@ -6306,7 +6306,7 @@ __metadata: "@babel/core": "npm:^7.23.2" "@babel/preset-env": "npm:^7.23.2" "@babel/types": "npm:^7.23.0" - "@storybook/csf": "npm:0.1.2--canary.71.cad875c.0" + "@storybook/csf": "npm:0.1.2-next.0" "@storybook/csf-tools": "workspace:*" "@storybook/node-logger": "workspace:*" "@storybook/types": "workspace:*" @@ -6344,7 +6344,7 @@ __metadata: "@radix-ui/react-select": "npm:^1.2.2" "@radix-ui/react-toolbar": "npm:^1.0.4" "@storybook/client-logger": "workspace:*" - "@storybook/csf": "npm:0.1.2--canary.71.cad875c.0" + "@storybook/csf": "npm:0.1.2-next.0" "@storybook/global": "npm:^5.0.0" "@storybook/icons": "npm:^1.1.6" "@storybook/theming": "workspace:*" @@ -6434,7 +6434,7 @@ __metadata: "@storybook/channels": "workspace:*" "@storybook/core-common": "workspace:*" "@storybook/core-events": "workspace:*" - "@storybook/csf": "npm:0.1.2--canary.71.cad875c.0" + "@storybook/csf": "npm:0.1.2-next.0" "@storybook/csf-tools": "workspace:*" "@storybook/docs-mdx": "npm:^0.1.0" "@storybook/global": "npm:^5.0.0" @@ -6515,7 +6515,7 @@ __metadata: "@babel/parser": "npm:^7.23.0" "@babel/traverse": "npm:^7.23.2" "@babel/types": "npm:^7.23.0" - "@storybook/csf": "npm:0.1.2--canary.71.cad875c.0" + "@storybook/csf": "npm:0.1.2-next.0" "@storybook/types": "workspace:*" "@types/fs-extra": "npm:^11.0.1" "@types/js-yaml": "npm:^4.0.5" @@ -6527,12 +6527,12 @@ __metadata: languageName: unknown linkType: soft -"@storybook/csf@npm:0.1.2--canary.71.cad875c.0": - version: 0.1.2--canary.71.cad875c.0 - resolution: "@storybook/csf@npm:0.1.2--canary.71.cad875c.0" +"@storybook/csf@npm:0.1.2-next.0": + version: 0.1.2-next.0 + resolution: "@storybook/csf@npm:0.1.2-next.0" dependencies: type-fest: "npm:^2.19.0" - checksum: 6a26cbcc41a5a73374fff6329b47479dacf1af46112c4d1e11bce2e3f6e9992c61765dcd99cf0de18a209d4a21a824c2162cec0758f83d0a977b0cd90c5191eb + checksum: 9f9fd8ef2b15d06252d3d6e0abad642093ab09ded51391d426d0671ed8b9584acbd464ed8ba5c68a94a245f005af117afe74e20af0dd475b9f704b9a5c806648 languageName: node linkType: hard @@ -6765,7 +6765,7 @@ __metadata: "@storybook/channels": "workspace:*" "@storybook/client-logger": "workspace:*" "@storybook/core-events": "workspace:*" - "@storybook/csf": "npm:0.1.2--canary.71.cad875c.0" + "@storybook/csf": "npm:0.1.2-next.0" "@storybook/global": "npm:^5.0.0" "@storybook/router": "workspace:*" "@storybook/theming": "workspace:*" @@ -7174,7 +7174,7 @@ __metadata: "@storybook/client-logger": "workspace:*" "@storybook/core-common": "workspace:*" "@storybook/core-events": "workspace:*" - "@storybook/csf": "npm:0.1.2--canary.71.cad875c.0" + "@storybook/csf": "npm:0.1.2-next.0" "@storybook/global": "npm:^5.0.0" "@storybook/types": "workspace:*" "@types/qs": "npm:^6.9.5" @@ -7383,7 +7383,7 @@ __metadata: "@storybook/core-events": "workspace:*" "@storybook/core-server": "workspace:*" "@storybook/core-webpack": "workspace:*" - "@storybook/csf": "npm:0.1.2--canary.71.cad875c.0" + "@storybook/csf": "npm:0.1.2-next.0" "@storybook/csf-plugin": "workspace:*" "@storybook/csf-tools": "workspace:*" "@storybook/docs-tools": "workspace:*" @@ -7556,7 +7556,7 @@ __metadata: resolution: "@storybook/server@workspace:renderers/server" dependencies: "@storybook/core-client": "workspace:*" - "@storybook/csf": "npm:0.1.2--canary.71.cad875c.0" + "@storybook/csf": "npm:0.1.2-next.0" "@storybook/csf-tools": "workspace:*" "@storybook/global": "npm:^5.0.0" "@storybook/preview-api": "workspace:*" @@ -7573,7 +7573,7 @@ __metadata: version: 0.0.0-use.local resolution: "@storybook/source-loader@workspace:lib/source-loader" dependencies: - "@storybook/csf": "npm:0.1.2--canary.71.cad875c.0" + "@storybook/csf": "npm:0.1.2-next.0" "@storybook/types": "workspace:*" estraverse: "npm:^5.2.0" jest-specific-snapshot: "npm:^8.0.0" @@ -7767,7 +7767,7 @@ __metadata: resolution: "@storybook/types@workspace:lib/types" dependencies: "@storybook/channels": "workspace:*" - "@storybook/csf": "npm:0.1.2--canary.71.cad875c.0" + "@storybook/csf": "npm:0.1.2-next.0" "@types/babel__core": "npm:^7.0.0" "@types/express": "npm:^4.7.0" "@types/fs-extra": "npm:^11.0.1" From e3725f88c88e4ec371add1181fc10e4a8e9d4b14 Mon Sep 17 00:00:00 2001 From: Jeppe Reinhold Date: Wed, 22 Nov 2023 14:07:11 +0100 Subject: [PATCH 157/170] rename nextjs story target --- code/e2e-tests/framework-nextjs.spec.ts | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/code/e2e-tests/framework-nextjs.spec.ts b/code/e2e-tests/framework-nextjs.spec.ts index 440c079d1704..4ca67544db74 100644 --- a/code/e2e-tests/framework-nextjs.spec.ts +++ b/code/e2e-tests/framework-nextjs.spec.ts @@ -30,7 +30,7 @@ test.describe('Next.js', () => { // TODO: Test is flaky, investigate why test.skip('should lazy load images by default', async () => { - await sbPage.navigateToStory('frameworks/nextjs/Image', 'lazy'); + await sbPage.navigateToStory('stories/frameworks/nextjs/Image', 'lazy'); const img = sbPage.previewRoot().locator('img'); @@ -39,7 +39,7 @@ test.describe('Next.js', () => { // TODO: Test is flaky, investigate why test.skip('should eager load images when loading parameter is set to eager', async () => { - await sbPage.navigateToStory('frameworks/nextjs/Image', 'eager'); + await sbPage.navigateToStory('stories/frameworks/nextjs/Image', 'eager'); const img = sbPage.previewRoot().locator('img'); @@ -67,7 +67,10 @@ test.describe('Next.js', () => { test.beforeEach(async ({ page }) => { sbPage = new SbPage(page); - await sbPage.navigateToStory('frameworks/nextjs-nextjs-default-js/Navigation', 'default'); + await sbPage.navigateToStory( + 'stories/frameworks/nextjs-nextjs-default-js/Navigation', + 'default' + ); root = sbPage.previewRoot(); }); @@ -99,7 +102,7 @@ test.describe('Next.js', () => { test.beforeEach(async ({ page }) => { sbPage = new SbPage(page); - await sbPage.navigateToStory('frameworks/nextjs-nextjs-default-js/Router', 'default'); + await sbPage.navigateToStory('stories/frameworks/nextjs-nextjs-default-js/Router', 'default'); root = sbPage.previewRoot(); }); From 704feaa76d6db218375abdcbd63a514eab7d1357 Mon Sep 17 00:00:00 2001 From: Kasper Peulen Date: Wed, 22 Nov 2023 14:46:31 +0100 Subject: [PATCH 158/170] Fix type issues --- code/lib/types/src/modules/story.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/code/lib/types/src/modules/story.ts b/code/lib/types/src/modules/story.ts index cc88807ade87..cd4e9f1c9d16 100644 --- a/code/lib/types/src/modules/story.ts +++ b/code/lib/types/src/modules/story.ts @@ -65,8 +65,8 @@ export type NormalizedComponentAnnotations[]; - loaders: LoaderFunction[]; + decorators?: DecoratorFunction[]; + loaders?: LoaderFunction[]; }; export type NormalizedStoryAnnotations = Omit< From b319f2dd420b0630f55e95c0bf6f08080277efef Mon Sep 17 00:00:00 2001 From: Kasper Peulen Date: Wed, 22 Nov 2023 15:40:18 +0100 Subject: [PATCH 159/170] Update test --- .../preview-api/src/modules/store/csf/prepareStory.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/code/lib/preview-api/src/modules/store/csf/prepareStory.test.ts b/code/lib/preview-api/src/modules/store/csf/prepareStory.test.ts index a7cb1d971e6d..b15c3a955659 100644 --- a/code/lib/preview-api/src/modules/store/csf/prepareStory.test.ts +++ b/code/lib/preview-api/src/modules/store/csf/prepareStory.test.ts @@ -343,9 +343,9 @@ describe('prepareStory', () => { ); const storyContext = { context: 'value' } as any; - const loadedContext = await applyLoaders(storyContext); + const loadedContext = await applyLoaders({ ...storyContext }); - expect(loader).toHaveBeenCalledWith(storyContext); + expect(loader).toHaveBeenCalledWith({ ...storyContext, loaded: {} }); expect(loadedContext).toEqual({ context: 'value', loaded: { foo: 7 }, From 980ca21a9d61bd112fa2f1637aec1039d1666e90 Mon Sep 17 00:00:00 2001 From: Kasper Peulen Date: Wed, 22 Nov 2023 15:40:18 +0100 Subject: [PATCH 160/170] Update test --- code/lib/preview-api/src/modules/store/csf/prepareStory.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/code/lib/preview-api/src/modules/store/csf/prepareStory.test.ts b/code/lib/preview-api/src/modules/store/csf/prepareStory.test.ts index a7cb1d971e6d..ef697a5c0c10 100644 --- a/code/lib/preview-api/src/modules/store/csf/prepareStory.test.ts +++ b/code/lib/preview-api/src/modules/store/csf/prepareStory.test.ts @@ -345,7 +345,7 @@ describe('prepareStory', () => { const storyContext = { context: 'value' } as any; const loadedContext = await applyLoaders(storyContext); - expect(loader).toHaveBeenCalledWith(storyContext); + expect(loader).toHaveBeenCalledWith({ ...storyContext, loaded: {} }); expect(loadedContext).toEqual({ context: 'value', loaded: { foo: 7 }, From 3c0b8cdaf646241c38a4e0165092b244737f1464 Mon Sep 17 00:00:00 2001 From: Yann Braga Date: Tue, 12 Sep 2023 19:32:43 +0100 Subject: [PATCH 161/170] add sb doctor command --- .../helpers/getDuplicatedDepsWarnings.ts | 104 +++++++++++++++ .../helpers/getMigrationSummary.ts | 104 +-------------- code/lib/cli/src/doctor/index.ts | 123 ++++++++++++++++++ code/lib/cli/src/generate.ts | 14 +- 4 files changed, 246 insertions(+), 99 deletions(-) create mode 100644 code/lib/cli/src/automigrate/helpers/getDuplicatedDepsWarnings.ts create mode 100644 code/lib/cli/src/doctor/index.ts diff --git a/code/lib/cli/src/automigrate/helpers/getDuplicatedDepsWarnings.ts b/code/lib/cli/src/automigrate/helpers/getDuplicatedDepsWarnings.ts new file mode 100644 index 000000000000..6c668e47c0ac --- /dev/null +++ b/code/lib/cli/src/automigrate/helpers/getDuplicatedDepsWarnings.ts @@ -0,0 +1,104 @@ +import chalk from 'chalk'; +import { frameworkPackages, rendererPackages } from '@storybook/core-common'; +import { hasMultipleVersions } from './hasMultipleVersions'; +import type { InstallationMetadata } from '../../js-package-manager/types'; + +export const messageDivider = '\n\n'; + +// These packages are aliased by Storybook, so it doesn't matter if they're duplicated +export const allowList = [ + '@storybook/csf', + // see this file for more info: code/lib/preview/src/globals/types.ts + '@storybook/addons', + '@storybook/channel-postmessage', + '@storybook/channel-websocket', + '@storybook/channels', + '@storybook/client-api', + '@storybook/client-logger', + '@storybook/core-client', + '@storybook/core-events', + '@storybook/preview-web', + '@storybook/preview-api', + '@storybook/store', + + // see this file for more info: code/ui/manager/src/globals/types.ts + '@storybook/components', + '@storybook/router', + '@storybook/theming', + '@storybook/api', + '@storybook/manager-api', +]; + +// These packages definitely will cause issues if they're duplicated +export const disallowList = [ + Object.keys(rendererPackages), + Object.keys(frameworkPackages), + '@storybook/instrumenter', +]; + +export function getDuplicatedDepsWarnings( + installationMetadata?: InstallationMetadata +): string[] | undefined { + if ( + !installationMetadata?.duplicatedDependencies || + Object.keys(installationMetadata.duplicatedDependencies).length === 0 + ) { + return undefined; + } + + const messages: string[] = []; + + const { critical, trivial } = Object.entries( + installationMetadata?.duplicatedDependencies + ).reduce<{ + critical: string[]; + trivial: string[]; + }>( + (acc, [dep, versions]) => { + if (allowList.includes(dep)) { + return acc; + } + + const hasMultipleMajorVersions = hasMultipleVersions(versions); + + if (disallowList.includes(dep) && hasMultipleMajorVersions) { + acc.critical.push(`${chalk.redBright(dep)}:\n${versions.join(', ')}`); + } else { + acc.trivial.push(`${chalk.hex('#ff9800')(dep)}:\n${versions.join(', ')}`); + } + + return acc; + }, + { critical: [], trivial: [] } + ); + + if (critical.length === 0 && trivial.length === 0) { + return messages; + } + + if (critical.length > 0) { + messages.push( + `${chalk.bold( + 'Critical:' + )} The following dependencies are duplicated and WILL cause unexpected behavior:` + ); + messages.push(critical.join(messageDivider)); + } + + if (trivial.length > 0) { + messages.push( + `${chalk.bold( + 'Attention:' + )} The following dependencies are duplicated which might cause unexpected behavior:` + ); + messages.push(trivial.join(messageDivider)); + } + + messages.push( + `You can find more information for a given dependency by running ${chalk.cyan( + `${installationMetadata.infoCommand} ` + )}` + ); + + return messages; +} diff --git a/code/lib/cli/src/automigrate/helpers/getMigrationSummary.ts b/code/lib/cli/src/automigrate/helpers/getMigrationSummary.ts index 6a16e2ae3291..c727f8d49f4d 100644 --- a/code/lib/cli/src/automigrate/helpers/getMigrationSummary.ts +++ b/code/lib/cli/src/automigrate/helpers/getMigrationSummary.ts @@ -1,13 +1,12 @@ import chalk from 'chalk'; import boxen from 'boxen'; -import { frameworkPackages, rendererPackages } from '@storybook/core-common'; import dedent from 'ts-dedent'; import type { FixSummary } from '../types'; import { FixStatus } from '../types'; -import { hasMultipleVersions } from './hasMultipleVersions'; import type { InstallationMetadata } from '../../js-package-manager/types'; +import { getDuplicatedDepsWarnings } from './getDuplicatedDepsWarnings'; -const messageDivider = '\n\n'; +export const messageDivider = '\n\n'; const segmentDivider = '\n\nā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€\n\n'; function getGlossaryMessages( @@ -76,11 +75,10 @@ export function getMigrationSummary({ And reach out on Discord if you need help: ${chalk.yellow('https://discord.gg/storybook')} `); - if ( - installationMetadata?.duplicatedDependencies && - Object.keys(installationMetadata.duplicatedDependencies).length > 0 - ) { - messages.push(getWarnings(installationMetadata).join(messageDivider)); + const duplicatedDepsMessage = getDuplicatedDepsWarnings(installationMetadata); + + if (duplicatedDepsMessage) { + messages.push(duplicatedDepsMessage.join(messageDivider)); } const hasNoFixes = Object.values(fixResults).every((r) => r === FixStatus.UNNECESSARY); @@ -102,93 +100,3 @@ export function getMigrationSummary({ borderColor: hasFailures ? 'red' : 'green', }); } - -// These packages are aliased by Storybook, so it doesn't matter if they're duplicated -const allowList = [ - '@storybook/csf', - // see this file for more info: code/lib/preview/src/globals/types.ts - '@storybook/addons', - '@storybook/channel-postmessage', // @deprecated: remove in 8.0 - '@storybook/channel-websocket', // @deprecated: remove in 8.0 - '@storybook/channels', - '@storybook/client-api', - '@storybook/client-logger', - '@storybook/core-client', - '@storybook/core-events', - '@storybook/preview-web', - '@storybook/preview-api', - '@storybook/store', - - // see this file for more info: code/ui/manager/src/globals/types.ts - '@storybook/components', - '@storybook/router', - '@storybook/theming', - '@storybook/api', // @deprecated: remove in 8.0 - '@storybook/manager-api', -]; - -// These packages definitely will cause issues if they're duplicated -const disallowList = [ - Object.keys(rendererPackages), - Object.keys(frameworkPackages), - '@storybook/instrumenter', -]; - -function getWarnings(installationMetadata: InstallationMetadata) { - const messages = []; - - const { critical, trivial } = Object.entries( - installationMetadata?.duplicatedDependencies - ).reduce<{ - critical: string[]; - trivial: string[]; - }>( - (acc, [dep, versions]) => { - if (allowList.includes(dep)) { - return acc; - } - - const hasMultipleMajorVersions = hasMultipleVersions(versions); - - if (disallowList.includes(dep) && hasMultipleMajorVersions) { - acc.critical.push(`${chalk.redBright(dep)}:\n${versions.join(', ')}`); - } else { - acc.trivial.push(`${chalk.hex('#ff9800')(dep)}:\n${versions.join(', ')}`); - } - - return acc; - }, - { critical: [], trivial: [] } - ); - - if (critical.length > 0) { - messages.push( - `${chalk.bold( - 'Critical:' - )} The following dependencies are duplicated and WILL cause unexpected behavior:` - ); - messages.push(critical.join(messageDivider)); - } - - if (trivial.length > 0) { - messages.push( - `${chalk.bold( - 'Attention:' - )} The following dependencies are duplicated which might cause unexpected behavior:` - ); - messages.push(trivial.join(messageDivider)); - } - - messages.push( - `You can find more information for a given dependency by running ${chalk.cyan( - `${installationMetadata.infoCommand} ` - )}` - ); - messages.push( - `Please try de-duplicating these dependencies by running ${chalk.cyan( - `${installationMetadata.dedupeCommand}` - )}` - ); - - return messages; -} diff --git a/code/lib/cli/src/doctor/index.ts b/code/lib/cli/src/doctor/index.ts new file mode 100644 index 000000000000..94dfac234aa3 --- /dev/null +++ b/code/lib/cli/src/doctor/index.ts @@ -0,0 +1,123 @@ +import chalk from 'chalk'; +import boxen from 'boxen'; +import { createWriteStream, move, remove } from 'fs-extra'; +import tempy from 'tempy'; +import dedent from 'ts-dedent'; + +import { join } from 'path'; +import { JsPackageManagerFactory } from '../js-package-manager'; +import type { PackageManagerName } from '../js-package-manager'; + +import { getStorybookData } from '../automigrate/helpers/mainConfigFile'; +import { getDuplicatedDepsWarnings } from '../automigrate/helpers/getDuplicatedDepsWarnings'; +import { cleanLog } from '../automigrate/helpers/cleanLog'; +import { getIncompatibleAddons } from '../automigrate/helpers/getIncompatibleAddons'; +import { incompatibleAddons } from '../automigrate/fixes/incompatible-addons'; + +const logger = console; +const LOG_FILE_NAME = 'doctor-storybook.log'; +const LOG_FILE_PATH = join(process.cwd(), LOG_FILE_NAME); +let TEMP_LOG_FILE_PATH = ''; + +const originalStdOutWrite = process.stdout.write.bind(process.stdout); +const originalStdErrWrite = process.stderr.write.bind(process.stdout); + +const augmentLogsToFile = () => { + TEMP_LOG_FILE_PATH = tempy.file({ name: LOG_FILE_NAME }); + const logStream = createWriteStream(TEMP_LOG_FILE_PATH); + + process.stdout.write = (d: string) => { + originalStdOutWrite(d); + return logStream.write(cleanLog(d)); + }; + process.stderr.write = (d: string) => { + return logStream.write(cleanLog(d)); + }; +}; + +const cleanup = () => { + process.stdout.write = originalStdOutWrite; + process.stderr.write = originalStdErrWrite; +}; + +type DoctorOptions = { + configDir?: string; + packageManager?: PackageManagerName; +}; + +export const doctor = async ({ + configDir: userSpecifiedConfigDir, + packageManager: pkgMgr, +}: DoctorOptions = {}) => { + augmentLogsToFile(); + const diagnosticMessages: string[] = []; + + logger.info('šŸ©ŗ checking the health of your Storybook..'); + + const packageManager = JsPackageManagerFactory.getPackageManager({ force: pkgMgr }); + let storybookVersion; + let mainConfig; + + try { + const storybookData = await getStorybookData({ + configDir: userSpecifiedConfigDir, + packageManager, + }); + storybookVersion = storybookData.storybookVersion; + mainConfig = storybookData.mainConfig; + } catch (err) { + if (err.message.includes('No configuration files have been found')) { + logger.info( + dedent`[Storybook doctor] Could not find or evaluate your Storybook main.js config directory at ${chalk.blue( + userSpecifiedConfigDir || '.storybook' + )} so the doctor command cannot proceed. You might be running this command in a monorepo or a non-standard project structure. If that is the case, please rerun this command by specifying the path to your Storybook config directory via the --config-dir option.` + ); + } + logger.info(dedent`[Storybook doctor] āŒ ${err.message}`); + logger.info('Please fix the error and try again.'); + } + + if (!storybookVersion) { + logger.info(dedent` + [Storybook doctor] āŒ Unable to determine Storybook version so the command will not proceed. + šŸ¤” Are you running storybook doctor from your project directory? Please specify your Storybook config directory with the --config-dir flag. + `); + process.exit(1); + } + + const installationMetadata = await packageManager.findInstallations([ + '@storybook/*', + 'storybook', + ]); + + diagnosticMessages.push(getDuplicatedDepsWarnings(installationMetadata)?.join('\n')); + + const incompatibleAddonList = await getIncompatibleAddons(mainConfig); + if (incompatibleAddonList.length > 0) { + diagnosticMessages.push(incompatibleAddons.prompt({ incompatibleAddonList })); + } + + logger.info(); + + const finalMessages = diagnosticMessages.filter(Boolean); + + if (finalMessages.length > 0) { + finalMessages.push(`You can find the full logs in ${chalk.cyan(LOG_FILE_PATH)}`); + + logger.info( + boxen(finalMessages.join('\n\n-------\n\n'), { + borderStyle: 'round', + padding: 1, + title: 'Diagnostics', + borderColor: 'red', + }) + ); + await move(TEMP_LOG_FILE_PATH, join(process.cwd(), LOG_FILE_NAME), { overwrite: true }); + } else { + logger.info('šŸ„³ Your Storybook project looks good!'); + await remove(TEMP_LOG_FILE_PATH); + } + logger.info(); + + cleanup(); +}; diff --git a/code/lib/cli/src/generate.ts b/code/lib/cli/src/generate.ts index e5811888521b..8f37de772933 100644 --- a/code/lib/cli/src/generate.ts +++ b/code/lib/cli/src/generate.ts @@ -23,6 +23,7 @@ import { build } from './build'; import { parseList, getEnvConfig } from './utils'; import versions from './versions'; import { JsPackageManagerFactory } from './js-package-manager'; +import { doctor } from './doctor'; addToGlobalContext('cliVersion', versions.storybook); @@ -170,7 +171,7 @@ command('link ') ); command('automigrate [fixId]') - .description('Check storybook for known problems or migrations and apply fixes') + .description('Check storybook for incompatibilities or migrations and apply fixes') .option('-y --yes', 'Skip prompting the user') .option('-n --dry-run', 'Only check for fixes, do not actually run them') .option('--package-manager ', 'Force package manager') @@ -189,6 +190,17 @@ command('automigrate [fixId]') }); }); +command('doctor') + .description('Check Storybook for known problems and provide suggestions or fixes') + .option('--package-manager ', 'Force package manager') + .option('-c, --config-dir ', 'Directory of Storybook configuration') + .action(async (options) => { + await doctor(options).catch((e) => { + logger.error(e); + process.exit(1); + }); + }); + command('dev') .option('-p, --port ', 'Port to run Storybook', (str) => parseInt(str, 10)) .option('-h, --host ', 'Host to run Storybook') From 1cfce18cd60a42ff21e85ceac42726cd426dd889 Mon Sep 17 00:00:00 2001 From: Yann Braga Date: Wed, 22 Nov 2023 15:34:55 +0100 Subject: [PATCH 162/170] move utilities to doctor directory, add mismatching version checks --- .../automigrate/fixes/incompatible-addons.ts | 4 +- .../helpers/getDuplicatedDepsWarnings.ts | 104 --------------- .../helpers/getMigrationSummary.ts | 2 +- .../src/doctor/getDuplicatedDepsWarnings.ts | 119 ++++++++++++++++++ .../getIncompatibleAddons.ts | 17 ++- .../doctor/getMismatchingVersionsWarning.ts | 95 ++++++++++++++ .../helpers => doctor}/hasMultipleVersions.ts | 0 code/lib/cli/src/doctor/index.ts | 29 +++-- .../src/utils/warnOnIncompatibleAddons.ts | 2 +- 9 files changed, 248 insertions(+), 124 deletions(-) delete mode 100644 code/lib/cli/src/automigrate/helpers/getDuplicatedDepsWarnings.ts create mode 100644 code/lib/cli/src/doctor/getDuplicatedDepsWarnings.ts rename code/lib/cli/src/{automigrate/helpers => doctor}/getIncompatibleAddons.ts (84%) create mode 100644 code/lib/cli/src/doctor/getMismatchingVersionsWarning.ts rename code/lib/cli/src/{automigrate/helpers => doctor}/hasMultipleVersions.ts (100%) diff --git a/code/lib/cli/src/automigrate/fixes/incompatible-addons.ts b/code/lib/cli/src/automigrate/fixes/incompatible-addons.ts index 3455408f279d..ce9d01ccd96a 100644 --- a/code/lib/cli/src/automigrate/fixes/incompatible-addons.ts +++ b/code/lib/cli/src/automigrate/fixes/incompatible-addons.ts @@ -1,7 +1,7 @@ import chalk from 'chalk'; import dedent from 'ts-dedent'; import type { Fix } from '../types'; -import { getIncompatibleAddons } from '../helpers/getIncompatibleAddons'; +import { getIncompatibleAddons } from '../../doctor/getIncompatibleAddons'; interface IncompatibleAddonsOptions { incompatibleAddonList: { name: string; version: string }[]; @@ -19,7 +19,7 @@ export const incompatibleAddons: Fix = { prompt({ incompatibleAddonList }) { return dedent` ${chalk.bold( - chalk.red('Attention') + 'Attention' )}: We've detected that you're using the following addons in versions which are known to be incompatible with Storybook 7: ${incompatibleAddonList diff --git a/code/lib/cli/src/automigrate/helpers/getDuplicatedDepsWarnings.ts b/code/lib/cli/src/automigrate/helpers/getDuplicatedDepsWarnings.ts deleted file mode 100644 index 6c668e47c0ac..000000000000 --- a/code/lib/cli/src/automigrate/helpers/getDuplicatedDepsWarnings.ts +++ /dev/null @@ -1,104 +0,0 @@ -import chalk from 'chalk'; -import { frameworkPackages, rendererPackages } from '@storybook/core-common'; -import { hasMultipleVersions } from './hasMultipleVersions'; -import type { InstallationMetadata } from '../../js-package-manager/types'; - -export const messageDivider = '\n\n'; - -// These packages are aliased by Storybook, so it doesn't matter if they're duplicated -export const allowList = [ - '@storybook/csf', - // see this file for more info: code/lib/preview/src/globals/types.ts - '@storybook/addons', - '@storybook/channel-postmessage', - '@storybook/channel-websocket', - '@storybook/channels', - '@storybook/client-api', - '@storybook/client-logger', - '@storybook/core-client', - '@storybook/core-events', - '@storybook/preview-web', - '@storybook/preview-api', - '@storybook/store', - - // see this file for more info: code/ui/manager/src/globals/types.ts - '@storybook/components', - '@storybook/router', - '@storybook/theming', - '@storybook/api', - '@storybook/manager-api', -]; - -// These packages definitely will cause issues if they're duplicated -export const disallowList = [ - Object.keys(rendererPackages), - Object.keys(frameworkPackages), - '@storybook/instrumenter', -]; - -export function getDuplicatedDepsWarnings( - installationMetadata?: InstallationMetadata -): string[] | undefined { - if ( - !installationMetadata?.duplicatedDependencies || - Object.keys(installationMetadata.duplicatedDependencies).length === 0 - ) { - return undefined; - } - - const messages: string[] = []; - - const { critical, trivial } = Object.entries( - installationMetadata?.duplicatedDependencies - ).reduce<{ - critical: string[]; - trivial: string[]; - }>( - (acc, [dep, versions]) => { - if (allowList.includes(dep)) { - return acc; - } - - const hasMultipleMajorVersions = hasMultipleVersions(versions); - - if (disallowList.includes(dep) && hasMultipleMajorVersions) { - acc.critical.push(`${chalk.redBright(dep)}:\n${versions.join(', ')}`); - } else { - acc.trivial.push(`${chalk.hex('#ff9800')(dep)}:\n${versions.join(', ')}`); - } - - return acc; - }, - { critical: [], trivial: [] } - ); - - if (critical.length === 0 && trivial.length === 0) { - return messages; - } - - if (critical.length > 0) { - messages.push( - `${chalk.bold( - 'Critical:' - )} The following dependencies are duplicated and WILL cause unexpected behavior:` - ); - messages.push(critical.join(messageDivider)); - } - - if (trivial.length > 0) { - messages.push( - `${chalk.bold( - 'Attention:' - )} The following dependencies are duplicated which might cause unexpected behavior:` - ); - messages.push(trivial.join(messageDivider)); - } - - messages.push( - `You can find more information for a given dependency by running ${chalk.cyan( - `${installationMetadata.infoCommand} ` - )}` - ); - - return messages; -} diff --git a/code/lib/cli/src/automigrate/helpers/getMigrationSummary.ts b/code/lib/cli/src/automigrate/helpers/getMigrationSummary.ts index c727f8d49f4d..583d1b9170ee 100644 --- a/code/lib/cli/src/automigrate/helpers/getMigrationSummary.ts +++ b/code/lib/cli/src/automigrate/helpers/getMigrationSummary.ts @@ -4,7 +4,7 @@ import dedent from 'ts-dedent'; import type { FixSummary } from '../types'; import { FixStatus } from '../types'; import type { InstallationMetadata } from '../../js-package-manager/types'; -import { getDuplicatedDepsWarnings } from './getDuplicatedDepsWarnings'; +import { getDuplicatedDepsWarnings } from '../../doctor/getDuplicatedDepsWarnings'; export const messageDivider = '\n\n'; const segmentDivider = '\n\nā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€\n\n'; diff --git a/code/lib/cli/src/doctor/getDuplicatedDepsWarnings.ts b/code/lib/cli/src/doctor/getDuplicatedDepsWarnings.ts new file mode 100644 index 000000000000..0015798988de --- /dev/null +++ b/code/lib/cli/src/doctor/getDuplicatedDepsWarnings.ts @@ -0,0 +1,119 @@ +import chalk from 'chalk'; +import { frameworkPackages, rendererPackages } from '@storybook/core-common'; +import { hasMultipleVersions } from './hasMultipleVersions'; +import type { InstallationMetadata } from '../js-package-manager/types'; + +export const messageDivider = '\n\n'; + +// These packages are aliased by Storybook, so it doesn't matter if they're duplicated +export const allowList = [ + '@storybook/csf', + // see this file for more info: code/lib/preview/src/globals/types.ts + '@storybook/addons', + '@storybook/channel-postmessage', + '@storybook/channel-websocket', + '@storybook/client-api', + '@storybook/client-logger', + '@storybook/core-client', + '@storybook/preview-web', + '@storybook/preview-api', + '@storybook/store', + + // see this file for more info: code/ui/manager/src/globals/types.ts + '@storybook/components', + '@storybook/router', + '@storybook/theming', + '@storybook/api', + '@storybook/manager-api', +]; + +// These packages definitely will cause issues if they're duplicated +export const disallowList = [ + Object.keys(rendererPackages), + Object.keys(frameworkPackages), + '@storybook/core-events', + '@storybook/instrumenter', + '@storybook/core-common', + '@storybook/core-server', + '@storybook/manager', + '@storybook/preview', +]; + +export function getDuplicatedDepsWarnings( + installationMetadata?: InstallationMetadata +): string[] | undefined { + try { + if ( + !installationMetadata?.duplicatedDependencies || + Object.keys(installationMetadata.duplicatedDependencies).length === 0 + ) { + return undefined; + } + + const messages: string[] = []; + + const { critical, trivial } = Object.entries( + installationMetadata?.duplicatedDependencies + ).reduce<{ + critical: string[]; + trivial: string[]; + }>( + (acc, [dep, packageVersions]) => { + if (allowList.includes(dep)) { + return acc; + } + + const hasMultipleMajorVersions = hasMultipleVersions(packageVersions); + + if (disallowList.includes(dep) && hasMultipleMajorVersions) { + acc.critical.push(`${chalk.redBright(dep)}:\n${packageVersions.join(', ')}`); + } else { + acc.trivial.push(`${chalk.hex('#ff9800')(dep)}:\n${packageVersions.join(', ')}`); + } + + return acc; + }, + { critical: [], trivial: [] } + ); + + if (critical.length === 0 && trivial.length === 0) { + return messages; + } + + if (critical.length > 0) { + messages.push( + `${chalk.bold( + 'Critical:' + )} The following dependencies are duplicated and WILL cause unexpected behavior:` + ); + messages.push(critical.join(messageDivider), '\n'); + } + + if (trivial.length > 0) { + messages.push( + `${chalk.bold( + 'Attention:' + )} The following dependencies are duplicated which might cause unexpected behavior:` + ); + messages.push(trivial.join(messageDivider)); + } + + messages.push( + '\n', + `You can find more information for a given dependency by running ${chalk.cyan( + `${installationMetadata.infoCommand} ` + )}` + ); + + messages.push( + '\n', + `Please try de-duplicating these dependencies by running ${chalk.cyan( + `${installationMetadata.dedupeCommand}` + )}` + ); + + return messages; + } catch (err) { + return undefined; + } +} diff --git a/code/lib/cli/src/automigrate/helpers/getIncompatibleAddons.ts b/code/lib/cli/src/doctor/getIncompatibleAddons.ts similarity index 84% rename from code/lib/cli/src/automigrate/helpers/getIncompatibleAddons.ts rename to code/lib/cli/src/doctor/getIncompatibleAddons.ts index d6fc28ed776b..135865f949c7 100644 --- a/code/lib/cli/src/automigrate/helpers/getIncompatibleAddons.ts +++ b/code/lib/cli/src/doctor/getIncompatibleAddons.ts @@ -1,7 +1,7 @@ import type { StorybookConfig } from '@storybook/types'; import semver from 'semver'; -import { getAddonNames } from './mainConfigFile'; -import { JsPackageManagerFactory } from '../../js-package-manager'; +import { getAddonNames } from '../automigrate/helpers/mainConfigFile'; +import { JsPackageManagerFactory } from '../js-package-manager'; export const getIncompatibleAddons = async ( mainConfig: StorybookConfig, @@ -38,12 +38,13 @@ export const getIncompatibleAddons = async ( const addons = getAddonNames(mainConfig).filter((addon) => addon in incompatibleList); - if (addons.length === 0) { - return []; - } + const dependencies = await packageManager.getAllDependencies(); + const storybookPackages = Object.keys(dependencies).filter((dep) => dep.includes('storybook')); + + const packagesToCheck = [...new Set([...addons, ...storybookPackages])]; const addonVersions = await Promise.all( - addons.map( + packagesToCheck.map( async (addon) => ({ name: addon, @@ -52,6 +53,10 @@ export const getIncompatibleAddons = async ( ) ); + if (addonVersions.length === 0) { + return []; + } + const incompatibleAddons: { name: string; version: string }[] = []; addonVersions.forEach(({ name, version: installedVersion }) => { if (installedVersion === null) return; diff --git a/code/lib/cli/src/doctor/getMismatchingVersionsWarning.ts b/code/lib/cli/src/doctor/getMismatchingVersionsWarning.ts new file mode 100644 index 000000000000..9aa0d424e01d --- /dev/null +++ b/code/lib/cli/src/doctor/getMismatchingVersionsWarning.ts @@ -0,0 +1,95 @@ +import chalk from 'chalk'; +import semver from 'semver'; +import { frameworkPackages } from '@storybook/core-common'; +import type { InstallationMetadata } from '../js-package-manager/types'; +import storybookCorePackages from '../versions'; + +function getPrimaryVersion(name: string, installationMetadata?: InstallationMetadata) { + const packageMetadata = installationMetadata?.dependencies[name]; + if (!packageMetadata) { + return undefined; + } + + return packageMetadata[0]?.version; +} + +export function getMismatchingVersionsWarnings( + installationMetadata?: InstallationMetadata, + allDependencies?: Record +): string | undefined { + const messages: string[] = []; + try { + const frameworkPackageName = Object.keys(installationMetadata?.dependencies).find( + (packageName) => { + return Object.keys(frameworkPackages).includes(packageName); + } + ); + const cliVersion = getPrimaryVersion('@storybook/cli', installationMetadata); + const frameworkVersion = getPrimaryVersion(frameworkPackageName, installationMetadata); + + if (!cliVersion || !frameworkVersion || semver.eq(cliVersion, frameworkVersion)) { + return undefined; + } + + messages.push( + `${chalk.bold( + 'Attention:' + )} There seems to be a mismatch between your Storybook package versions. This can result in a broken Storybook installation.` + ); + + let versionToCompare: string; + let packageToDisplay: string; + if (semver.lt(cliVersion, frameworkVersion)) { + versionToCompare = frameworkVersion; + packageToDisplay = frameworkPackageName; + } else { + versionToCompare = cliVersion; + packageToDisplay = 'storybook'; + } + + messages.push( + `The version of your storybook core packages should align with ${chalk.yellow( + versionToCompare + )} (from the ${chalk.cyan(packageToDisplay)} package) or higher.` + ); + + const filteredDependencies = Object.entries(installationMetadata?.dependencies).filter( + ([name, packages]) => { + if (Object.keys(storybookCorePackages).includes(name)) { + const packageVersion = packages[0].version; + return packageVersion !== versionToCompare; + } + + return false; + } + ); + + if (filteredDependencies.length > 0) { + messages.push( + `Based on your lockfile, these dependencies should be upgraded:`, + filteredDependencies + .map( + ([name, dep]) => + `${chalk.hex('#ff9800')(name)}: ${dep[0].version} ${ + allDependencies[name] ? '(in your package.json)' : '' + }` + ) + .join('\n') + ); + } + + messages.push( + `You can run ${chalk.cyan( + 'npx storybook@latest upgrade' + )} to upgrade all of your Storybook packages to the latest version. + + Alternatively you can try manually changing the versions to match in your package.json. We also recommend regenerating your lockfile, or running the following command to possibly deduplicate your Storybook package versions: ${chalk.cyan( + installationMetadata.dedupeCommand + )}` + ); + + return messages.join('\n\n'); + } catch (err) { + return undefined; + } +} diff --git a/code/lib/cli/src/automigrate/helpers/hasMultipleVersions.ts b/code/lib/cli/src/doctor/hasMultipleVersions.ts similarity index 100% rename from code/lib/cli/src/automigrate/helpers/hasMultipleVersions.ts rename to code/lib/cli/src/doctor/hasMultipleVersions.ts diff --git a/code/lib/cli/src/doctor/index.ts b/code/lib/cli/src/doctor/index.ts index 94dfac234aa3..bb7bcc6c3e14 100644 --- a/code/lib/cli/src/doctor/index.ts +++ b/code/lib/cli/src/doctor/index.ts @@ -3,16 +3,16 @@ import boxen from 'boxen'; import { createWriteStream, move, remove } from 'fs-extra'; import tempy from 'tempy'; import dedent from 'ts-dedent'; - import { join } from 'path'; + import { JsPackageManagerFactory } from '../js-package-manager'; import type { PackageManagerName } from '../js-package-manager'; - import { getStorybookData } from '../automigrate/helpers/mainConfigFile'; -import { getDuplicatedDepsWarnings } from '../automigrate/helpers/getDuplicatedDepsWarnings'; import { cleanLog } from '../automigrate/helpers/cleanLog'; -import { getIncompatibleAddons } from '../automigrate/helpers/getIncompatibleAddons'; import { incompatibleAddons } from '../automigrate/fixes/incompatible-addons'; +import { getDuplicatedDepsWarnings } from './getDuplicatedDepsWarnings'; +import { getIncompatibleAddons } from './getIncompatibleAddons'; +import { getMismatchingVersionsWarnings } from './getMismatchingVersionsWarning'; const logger = console; const LOG_FILE_NAME = 'doctor-storybook.log'; @@ -85,18 +85,27 @@ export const doctor = async ({ process.exit(1); } + const incompatibleAddonList = await getIncompatibleAddons(mainConfig); + console.log({ incompatibleAddonList }); + if (incompatibleAddonList.length > 0) { + diagnosticMessages.push(incompatibleAddons.prompt({ incompatibleAddonList })); + } + const installationMetadata = await packageManager.findInstallations([ '@storybook/*', 'storybook', ]); - diagnosticMessages.push(getDuplicatedDepsWarnings(installationMetadata)?.join('\n')); - - const incompatibleAddonList = await getIncompatibleAddons(mainConfig); - if (incompatibleAddonList.length > 0) { - diagnosticMessages.push(incompatibleAddons.prompt({ incompatibleAddonList })); + const allDependencies = await packageManager.getAllDependencies(); + const mismatchingVersionMessage = getMismatchingVersionsWarnings( + installationMetadata, + allDependencies + ); + if (mismatchingVersionMessage) { + diagnosticMessages.push(mismatchingVersionMessage); + } else { + diagnosticMessages.push(getDuplicatedDepsWarnings(installationMetadata)?.join('\n')); } - logger.info(); const finalMessages = diagnosticMessages.filter(Boolean); diff --git a/code/lib/core-server/src/utils/warnOnIncompatibleAddons.ts b/code/lib/core-server/src/utils/warnOnIncompatibleAddons.ts index 23e17c77bc56..fd4aaac39286 100644 --- a/code/lib/core-server/src/utils/warnOnIncompatibleAddons.ts +++ b/code/lib/core-server/src/utils/warnOnIncompatibleAddons.ts @@ -3,7 +3,7 @@ import { logger } from '@storybook/node-logger'; import chalk from 'chalk'; import dedent from 'ts-dedent'; -import { getIncompatibleAddons } from '../../../cli/src/automigrate/helpers/getIncompatibleAddons'; +import { getIncompatibleAddons } from '../../../cli/src/doctor/getIncompatibleAddons'; export const warnOnIncompatibleAddons = async (config: StorybookConfig) => { const incompatibleAddons = await getIncompatibleAddons(config); From daf70838635eef0d550a74cd3c2df275e550b681 Mon Sep 17 00:00:00 2001 From: Yann Braga Date: Wed, 22 Nov 2023 15:41:33 +0100 Subject: [PATCH 163/170] fix tests --- .../fixes/incompatible-addons.test.ts | 35 ++++++++++++++++++- .../helpers/getMigrationSummary.test.ts | 13 +++++-- 2 files changed, 45 insertions(+), 3 deletions(-) diff --git a/code/lib/cli/src/automigrate/fixes/incompatible-addons.test.ts b/code/lib/cli/src/automigrate/fixes/incompatible-addons.test.ts index 46978eba8396..fd4705acf879 100644 --- a/code/lib/cli/src/automigrate/fixes/incompatible-addons.test.ts +++ b/code/lib/cli/src/automigrate/fixes/incompatible-addons.test.ts @@ -24,7 +24,7 @@ const check = async ({ describe('incompatible-addons fix', () => { afterEach(jest.restoreAllMocks); - it('should show incompatible addons', async () => { + it('should show incompatible addons registered in main.js', async () => { await expect( check({ packageManager: { @@ -38,6 +38,7 @@ describe('incompatible-addons fix', () => { return Promise.resolve(null); } }, + getAllDependencies: async () => ({}), }, main: { addons: ['@storybook/essentials', '@storybook/addon-info'] }, }) @@ -51,6 +52,37 @@ describe('incompatible-addons fix', () => { }); }); + it('should show incompatible addons from package.json', async () => { + await expect( + check({ + packageManager: { + getPackageVersion(packageName, basePath) { + switch (packageName) { + case '@storybook/addon-essentials': + return Promise.resolve('7.0.0'); + case '@storybook/addon-info': + return Promise.resolve('5.3.21'); + default: + return Promise.resolve(null); + } + }, + getAllDependencies: async () => ({ + '@storybook/addon-essentials': '7.0.0', + '@storybook/addon-info': '5.3.21', + }), + }, + main: { addons: [] }, + }) + ).resolves.toEqual({ + incompatibleAddonList: [ + { + name: '@storybook/addon-info', + version: '5.3.21', + }, + ], + }); + }); + it('no-op when there are no incompatible addons', async () => { await expect( check({ @@ -63,6 +95,7 @@ describe('incompatible-addons fix', () => { return Promise.resolve(null); } }, + getAllDependencies: async () => ({}), }, main: { addons: ['@storybook/essentials'] }, }) diff --git a/code/lib/cli/src/automigrate/helpers/getMigrationSummary.test.ts b/code/lib/cli/src/automigrate/helpers/getMigrationSummary.test.ts index f5569ae2f49d..8a28a6c4fe23 100644 --- a/code/lib/cli/src/automigrate/helpers/getMigrationSummary.test.ts +++ b/code/lib/cli/src/automigrate/helpers/getMigrationSummary.test.ts @@ -139,16 +139,25 @@ describe('getMigrationSummary', () => { @storybook/instrumenter: 6.0.0, 7.1.0 - Attention: The following dependencies are duplicated which might cause unexpected behavior: - @storybook/core-common: 6.0.0, 7.1.0 + + + + Attention: The following dependencies are duplicated which might cause unexpected behavior: + @storybook/addon-essentials: 7.0.0, 7.1.0 + + + You can find more information for a given dependency by running yarn why + + + Please try de-duplicating these dependencies by running yarn dedupe" `); }); From 107ce09c1bde579aeefa6199766bf2245a4244f8 Mon Sep 17 00:00:00 2001 From: Yann Braga Date: Wed, 22 Nov 2023 15:43:19 +0100 Subject: [PATCH 164/170] add doctor command in error message --- code/lib/core-events/src/errors/server-errors.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/code/lib/core-events/src/errors/server-errors.ts b/code/lib/core-events/src/errors/server-errors.ts index 964bbbb64a92..f4ecab544773 100644 --- a/code/lib/core-events/src/errors/server-errors.ts +++ b/code/lib/core-events/src/errors/server-errors.ts @@ -406,7 +406,7 @@ export class NoMatchingExportError extends StorybookError { Correct example: { "@storybook/react": "7.5.3", "@storybook/react-vite": "7.5.3", "storybook": "7.5.3" } - Clearing your lock file and reinstalling your dependencies might help as well, as sometimes the version you see in your package.json might not be the one defined in your lock file, leading to version inconsistency issues. + Please run \`npx storybook@latest doctor\` for guidance on how to fix this issue. `; } } From 9609e12e19416b581b4d2c3b810533477a671c09 Mon Sep 17 00:00:00 2001 From: Kasper Peulen Date: Wed, 22 Nov 2023 15:45:31 +0100 Subject: [PATCH 165/170] Address review --- .../preview-api/src/modules/store/csf/normalizeArrays.ts | 2 +- code/lib/preview-api/src/modules/store/csf/prepareStory.ts | 7 +++---- code/lib/test/src/index.ts | 5 +++-- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/code/lib/preview-api/src/modules/store/csf/normalizeArrays.ts b/code/lib/preview-api/src/modules/store/csf/normalizeArrays.ts index 7253f120e24f..96344e6fac1d 100644 --- a/code/lib/preview-api/src/modules/store/csf/normalizeArrays.ts +++ b/code/lib/preview-api/src/modules/store/csf/normalizeArrays.ts @@ -1,4 +1,4 @@ export const normalizeArrays = (array: T[] | T | undefined): T[] => { if (Array.isArray(array)) return array; - return typeof array === 'function' ? [array] : []; + return array ? [array] : []; }; diff --git a/code/lib/preview-api/src/modules/store/csf/prepareStory.ts b/code/lib/preview-api/src/modules/store/csf/prepareStory.ts index 64306fedb327..311a4467c789 100644 --- a/code/lib/preview-api/src/modules/store/csf/prepareStory.ts +++ b/code/lib/preview-api/src/modules/store/csf/prepareStory.ts @@ -1,4 +1,4 @@ -/* eslint-disable no-restricted-syntax,no-await-in-loop,@typescript-eslint/no-loop-func */ +/* eslint-disable no-restricted-syntax,no-await-in-loop,@typescript-eslint/no-loop-func,no-underscore-dangle */ import { global } from '@storybook/global'; import type { @@ -55,8 +55,8 @@ export function prepareStory( ): Promise & { loaded: StoryContext['loaded'] }> => { let updatedContext = { ...context, loaded: {} }; for (const loaders of [ - ...('testPackageLoaders' in global && Array.isArray(global.testPackageLoaders) - ? [global.testPackageLoaders] + ...('__STORYBOOK_TEST_LOADERS__' in global && Array.isArray(global.__STORYBOOK_TEST_LOADERS__) + ? [global.__STORYBOOK_TEST_LOADERS__] : []), normalizeArrays(projectAnnotations.loaders), normalizeArrays(componentAnnotations.loaders), @@ -173,7 +173,6 @@ function preparePartialAnnotations( const { passArgsFirst = true } = parameters; - // eslint-disable-next-line no-underscore-dangle parameters.__isArgsStory = passArgsFirst && render && render.length > 0; } diff --git a/code/lib/test/src/index.ts b/code/lib/test/src/index.ts index 57612fc8a6c3..600c68f1d3b4 100644 --- a/code/lib/test/src/index.ts +++ b/code/lib/test/src/index.ts @@ -36,5 +36,6 @@ const resetAllMocksLoader: LoaderFunction = ({ parameters }) => { } }; -// @ts-expect-error Wwe are using this as a default loader, if the test package is used. But we don't want to get into optional peer dep shenanigans. -global.testPackageLoaders = [resetAllMocksLoader]; +// @ts-expect-error We are using this as a default Storybook loader, when the test package is used. This avoids the need for optional peer dependency workarounds. +// eslint-disable-next-line no-underscore-dangle +global.__STORYBOOK_TEST_LOADERS__ = [resetAllMocksLoader]; From 359c8954a184138ee9c826a5c5b1ec1fd3b61189 Mon Sep 17 00:00:00 2001 From: Kasper Peulen Date: Wed, 22 Nov 2023 16:06:54 +0100 Subject: [PATCH 166/170] Update csf version --- code/addons/links/package.json | 2 +- code/addons/storyshots-puppeteer/package.json | 2 +- code/lib/codemod/package.json | 2 +- code/lib/core-server/package.json | 2 +- code/lib/csf-tools/package.json | 2 +- code/lib/manager-api/package.json | 2 +- code/lib/preview-api/package.json | 2 +- code/lib/source-loader/package.json | 2 +- code/lib/types/package.json | 2 +- code/package.json | 2 +- code/renderers/server/package.json | 2 +- code/ui/blocks/package.json | 2 +- code/ui/components/package.json | 2 +- 13 files changed, 13 insertions(+), 13 deletions(-) diff --git a/code/addons/links/package.json b/code/addons/links/package.json index 54e7bbca7105..a2b252eee6c2 100644 --- a/code/addons/links/package.json +++ b/code/addons/links/package.json @@ -63,7 +63,7 @@ "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/addon-bundle.ts" }, "dependencies": { - "@storybook/csf": "0.1.2-next.0", + "@storybook/csf": "^0.1.2", "@storybook/global": "^5.0.0", "ts-dedent": "^2.0.0" }, diff --git a/code/addons/storyshots-puppeteer/package.json b/code/addons/storyshots-puppeteer/package.json index 5949d89338b4..4685d9a82237 100644 --- a/code/addons/storyshots-puppeteer/package.json +++ b/code/addons/storyshots-puppeteer/package.json @@ -37,7 +37,7 @@ }, "dependencies": { "@axe-core/puppeteer": "^4.2.0", - "@storybook/csf": "0.1.2-next.0", + "@storybook/csf": "^0.1.2", "@storybook/node-logger": "workspace:*", "@storybook/types": "workspace:*", "@types/jest-image-snapshot": "^6.0.0", diff --git a/code/lib/codemod/package.json b/code/lib/codemod/package.json index e8f0a213dfb4..f1914cd9d17e 100644 --- a/code/lib/codemod/package.json +++ b/code/lib/codemod/package.json @@ -55,7 +55,7 @@ "@babel/core": "^7.23.2", "@babel/preset-env": "^7.23.2", "@babel/types": "^7.23.0", - "@storybook/csf": "0.1.2-next.0", + "@storybook/csf": "^0.1.2", "@storybook/csf-tools": "workspace:*", "@storybook/node-logger": "workspace:*", "@storybook/types": "workspace:*", diff --git a/code/lib/core-server/package.json b/code/lib/core-server/package.json index 557651a48e43..a56640e1de4f 100644 --- a/code/lib/core-server/package.json +++ b/code/lib/core-server/package.json @@ -66,7 +66,7 @@ "@storybook/channels": "workspace:*", "@storybook/core-common": "workspace:*", "@storybook/core-events": "workspace:*", - "@storybook/csf": "0.1.2-next.0", + "@storybook/csf": "^0.1.2", "@storybook/csf-tools": "workspace:*", "@storybook/docs-mdx": "^0.1.0", "@storybook/global": "^5.0.0", diff --git a/code/lib/csf-tools/package.json b/code/lib/csf-tools/package.json index c5e4e5de536f..9620c543e085 100644 --- a/code/lib/csf-tools/package.json +++ b/code/lib/csf-tools/package.json @@ -46,7 +46,7 @@ "@babel/parser": "^7.23.0", "@babel/traverse": "^7.23.2", "@babel/types": "^7.23.0", - "@storybook/csf": "0.1.2-next.0", + "@storybook/csf": "^0.1.2", "@storybook/types": "workspace:*", "fs-extra": "^11.1.0", "recast": "^0.23.1", diff --git a/code/lib/manager-api/package.json b/code/lib/manager-api/package.json index 0e5e2e755952..02a7cac6d7ad 100644 --- a/code/lib/manager-api/package.json +++ b/code/lib/manager-api/package.json @@ -46,7 +46,7 @@ "@storybook/channels": "workspace:*", "@storybook/client-logger": "workspace:*", "@storybook/core-events": "workspace:*", - "@storybook/csf": "0.1.2-next.0", + "@storybook/csf": "^0.1.2", "@storybook/global": "^5.0.0", "@storybook/router": "workspace:*", "@storybook/theming": "workspace:*", diff --git a/code/lib/preview-api/package.json b/code/lib/preview-api/package.json index 39b9b4682d25..a43fecb7a446 100644 --- a/code/lib/preview-api/package.json +++ b/code/lib/preview-api/package.json @@ -71,7 +71,7 @@ "@storybook/channels": "workspace:*", "@storybook/client-logger": "workspace:*", "@storybook/core-events": "workspace:*", - "@storybook/csf": "0.1.2-next.0", + "@storybook/csf": "^0.1.2", "@storybook/global": "^5.0.0", "@storybook/types": "workspace:*", "@types/qs": "^6.9.5", diff --git a/code/lib/source-loader/package.json b/code/lib/source-loader/package.json index de7fa088395d..9c93afba521f 100644 --- a/code/lib/source-loader/package.json +++ b/code/lib/source-loader/package.json @@ -45,7 +45,7 @@ "prep": "node --loader ../../../scripts/node_modules/esbuild-register/loader.js -r ../../../scripts/node_modules/esbuild-register/register.js ../../../scripts/prepare/bundle.ts" }, "dependencies": { - "@storybook/csf": "0.1.2-next.0", + "@storybook/csf": "^0.1.2", "@storybook/types": "workspace:*", "estraverse": "^5.2.0", "lodash": "^4.17.21", diff --git a/code/lib/types/package.json b/code/lib/types/package.json index 30cb9f4c26f2..e14551c1822c 100644 --- a/code/lib/types/package.json +++ b/code/lib/types/package.json @@ -50,7 +50,7 @@ "file-system-cache": "2.3.0" }, "devDependencies": { - "@storybook/csf": "0.1.2-next.0", + "@storybook/csf": "^0.1.2", "@types/fs-extra": "^11.0.1", "@types/node": "^18.0.0", "typescript": "~4.9.3" diff --git a/code/package.json b/code/package.json index 31ccd621bcd3..6998a74be8d6 100644 --- a/code/package.json +++ b/code/package.json @@ -140,7 +140,7 @@ "@storybook/core-events": "workspace:*", "@storybook/core-server": "workspace:*", "@storybook/core-webpack": "workspace:*", - "@storybook/csf": "0.1.2-next.0", + "@storybook/csf": "^0.1.2", "@storybook/csf-plugin": "workspace:*", "@storybook/csf-tools": "workspace:*", "@storybook/docs-tools": "workspace:*", diff --git a/code/renderers/server/package.json b/code/renderers/server/package.json index e0c3cabd0f67..c20511b1feff 100644 --- a/code/renderers/server/package.json +++ b/code/renderers/server/package.json @@ -47,7 +47,7 @@ }, "dependencies": { "@storybook/core-client": "workspace:*", - "@storybook/csf": "0.1.2-next.0", + "@storybook/csf": "^0.1.2", "@storybook/csf-tools": "workspace:*", "@storybook/global": "^5.0.0", "@storybook/preview-api": "workspace:*", diff --git a/code/ui/blocks/package.json b/code/ui/blocks/package.json index 0f4385cb96cb..b2dbcfb882f7 100644 --- a/code/ui/blocks/package.json +++ b/code/ui/blocks/package.json @@ -48,7 +48,7 @@ "@storybook/client-logger": "workspace:*", "@storybook/components": "workspace:*", "@storybook/core-events": "workspace:*", - "@storybook/csf": "0.1.2-next.0", + "@storybook/csf": "^0.1.2", "@storybook/docs-tools": "workspace:*", "@storybook/global": "^5.0.0", "@storybook/manager-api": "workspace:*", diff --git a/code/ui/components/package.json b/code/ui/components/package.json index eb28b1280f12..9954c55392ef 100644 --- a/code/ui/components/package.json +++ b/code/ui/components/package.json @@ -62,7 +62,7 @@ "@radix-ui/react-select": "^1.2.2", "@radix-ui/react-toolbar": "^1.0.4", "@storybook/client-logger": "workspace:*", - "@storybook/csf": "0.1.2-next.0", + "@storybook/csf": "^0.1.2", "@storybook/global": "^5.0.0", "@storybook/theming": "workspace:*", "@storybook/types": "workspace:*", From 3606e3c4d20f84b86e962b4692071b1d27764aaa Mon Sep 17 00:00:00 2001 From: Kasper Peulen Date: Wed, 22 Nov 2023 16:07:04 +0100 Subject: [PATCH 167/170] Update csf version --- code/yarn.lock | 44 ++++++++++++++++++++++---------------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/code/yarn.lock b/code/yarn.lock index ad6a2779f617..e132a544a447 100644 --- a/code/yarn.lock +++ b/code/yarn.lock @@ -5655,7 +5655,7 @@ __metadata: dependencies: "@storybook/client-logger": "workspace:*" "@storybook/core-events": "workspace:*" - "@storybook/csf": "npm:0.1.2-next.0" + "@storybook/csf": "npm:^0.1.2" "@storybook/global": "npm:^5.0.0" "@storybook/manager-api": "workspace:*" "@storybook/preview-api": "workspace:*" @@ -5724,7 +5724,7 @@ __metadata: resolution: "@storybook/addon-storyshots-puppeteer@workspace:addons/storyshots-puppeteer" dependencies: "@axe-core/puppeteer": "npm:^4.2.0" - "@storybook/csf": "npm:0.1.2-next.0" + "@storybook/csf": "npm:^0.1.2" "@storybook/node-logger": "workspace:*" "@storybook/types": "workspace:*" "@types/jest-image-snapshot": "npm:^6.0.0" @@ -6033,7 +6033,7 @@ __metadata: "@storybook/client-logger": "workspace:*" "@storybook/components": "workspace:*" "@storybook/core-events": "workspace:*" - "@storybook/csf": "npm:0.1.2-next.0" + "@storybook/csf": "npm:^0.1.2" "@storybook/docs-tools": "workspace:*" "@storybook/global": "npm:^5.0.0" "@storybook/manager-api": "workspace:*" @@ -6306,7 +6306,7 @@ __metadata: "@babel/core": "npm:^7.23.2" "@babel/preset-env": "npm:^7.23.2" "@babel/types": "npm:^7.23.0" - "@storybook/csf": "npm:0.1.2-next.0" + "@storybook/csf": "npm:^0.1.2" "@storybook/csf-tools": "workspace:*" "@storybook/node-logger": "workspace:*" "@storybook/types": "workspace:*" @@ -6344,7 +6344,7 @@ __metadata: "@radix-ui/react-select": "npm:^1.2.2" "@radix-ui/react-toolbar": "npm:^1.0.4" "@storybook/client-logger": "workspace:*" - "@storybook/csf": "npm:0.1.2-next.0" + "@storybook/csf": "npm:^0.1.2" "@storybook/global": "npm:^5.0.0" "@storybook/icons": "npm:^1.1.6" "@storybook/theming": "workspace:*" @@ -6434,7 +6434,7 @@ __metadata: "@storybook/channels": "workspace:*" "@storybook/core-common": "workspace:*" "@storybook/core-events": "workspace:*" - "@storybook/csf": "npm:0.1.2-next.0" + "@storybook/csf": "npm:^0.1.2" "@storybook/csf-tools": "workspace:*" "@storybook/docs-mdx": "npm:^0.1.0" "@storybook/global": "npm:^5.0.0" @@ -6515,7 +6515,7 @@ __metadata: "@babel/parser": "npm:^7.23.0" "@babel/traverse": "npm:^7.23.2" "@babel/types": "npm:^7.23.0" - "@storybook/csf": "npm:0.1.2-next.0" + "@storybook/csf": "npm:^0.1.2" "@storybook/types": "workspace:*" "@types/fs-extra": "npm:^11.0.1" "@types/js-yaml": "npm:^4.0.5" @@ -6527,15 +6527,6 @@ __metadata: languageName: unknown linkType: soft -"@storybook/csf@npm:0.1.2-next.0": - version: 0.1.2-next.0 - resolution: "@storybook/csf@npm:0.1.2-next.0" - dependencies: - type-fest: "npm:^2.19.0" - checksum: 9f9fd8ef2b15d06252d3d6e0abad642093ab09ded51391d426d0671ed8b9584acbd464ed8ba5c68a94a245f005af117afe74e20af0dd475b9f704b9a5c806648 - languageName: node - linkType: hard - "@storybook/csf@npm:^0.0.1": version: 0.0.1 resolution: "@storybook/csf@npm:0.0.1" @@ -6545,6 +6536,15 @@ __metadata: languageName: node linkType: hard +"@storybook/csf@npm:^0.1.2": + version: 0.1.2 + resolution: "@storybook/csf@npm:0.1.2" + dependencies: + type-fest: "npm:^2.19.0" + checksum: b51a55292e5d2af8b1d135a28ecaa94f8860ddfedcb393adfa2cca1ee23853156066f737d8be1cb5412f572781aa525dc0b2f6e4a6f6ce805489f0149efe837c + languageName: node + linkType: hard + "@storybook/design-system@npm:^7.15.15": version: 7.15.15 resolution: "@storybook/design-system@npm:7.15.15" @@ -6765,7 +6765,7 @@ __metadata: "@storybook/channels": "workspace:*" "@storybook/client-logger": "workspace:*" "@storybook/core-events": "workspace:*" - "@storybook/csf": "npm:0.1.2-next.0" + "@storybook/csf": "npm:^0.1.2" "@storybook/global": "npm:^5.0.0" "@storybook/router": "workspace:*" "@storybook/theming": "workspace:*" @@ -7174,7 +7174,7 @@ __metadata: "@storybook/client-logger": "workspace:*" "@storybook/core-common": "workspace:*" "@storybook/core-events": "workspace:*" - "@storybook/csf": "npm:0.1.2-next.0" + "@storybook/csf": "npm:^0.1.2" "@storybook/global": "npm:^5.0.0" "@storybook/types": "workspace:*" "@types/qs": "npm:^6.9.5" @@ -7383,7 +7383,7 @@ __metadata: "@storybook/core-events": "workspace:*" "@storybook/core-server": "workspace:*" "@storybook/core-webpack": "workspace:*" - "@storybook/csf": "npm:0.1.2-next.0" + "@storybook/csf": "npm:^0.1.2" "@storybook/csf-plugin": "workspace:*" "@storybook/csf-tools": "workspace:*" "@storybook/docs-tools": "workspace:*" @@ -7556,7 +7556,7 @@ __metadata: resolution: "@storybook/server@workspace:renderers/server" dependencies: "@storybook/core-client": "workspace:*" - "@storybook/csf": "npm:0.1.2-next.0" + "@storybook/csf": "npm:^0.1.2" "@storybook/csf-tools": "workspace:*" "@storybook/global": "npm:^5.0.0" "@storybook/preview-api": "workspace:*" @@ -7573,7 +7573,7 @@ __metadata: version: 0.0.0-use.local resolution: "@storybook/source-loader@workspace:lib/source-loader" dependencies: - "@storybook/csf": "npm:0.1.2-next.0" + "@storybook/csf": "npm:^0.1.2" "@storybook/types": "workspace:*" estraverse: "npm:^5.2.0" jest-specific-snapshot: "npm:^8.0.0" @@ -7767,7 +7767,7 @@ __metadata: resolution: "@storybook/types@workspace:lib/types" dependencies: "@storybook/channels": "workspace:*" - "@storybook/csf": "npm:0.1.2-next.0" + "@storybook/csf": "npm:^0.1.2" "@types/babel__core": "npm:^7.0.0" "@types/express": "npm:^4.7.0" "@types/fs-extra": "npm:^11.0.1" From 23dcb6b8c46b0e2d796317920b95647814c9ef6a Mon Sep 17 00:00:00 2001 From: Yann Braga Date: Wed, 22 Nov 2023 16:28:58 +0100 Subject: [PATCH 168/170] remove log --- code/lib/cli/src/doctor/index.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/code/lib/cli/src/doctor/index.ts b/code/lib/cli/src/doctor/index.ts index bb7bcc6c3e14..cfafb899f3a4 100644 --- a/code/lib/cli/src/doctor/index.ts +++ b/code/lib/cli/src/doctor/index.ts @@ -86,7 +86,6 @@ export const doctor = async ({ } const incompatibleAddonList = await getIncompatibleAddons(mainConfig); - console.log({ incompatibleAddonList }); if (incompatibleAddonList.length > 0) { diagnosticMessages.push(incompatibleAddons.prompt({ incompatibleAddonList })); } From 12960c76f2aaa56b01c1e9c3c13114e5c5b5542d Mon Sep 17 00:00:00 2001 From: Kasper Peulen Date: Wed, 22 Nov 2023 17:04:18 +0100 Subject: [PATCH 169/170] Move args enhancer to be a loader --- code/addons/actions/src/addArgs.ts | 7 +---- code/addons/actions/src/addArgsHelpers.ts | 31 ----------------------- code/addons/actions/src/loaders.ts | 30 ++++++++++++++++++++++ code/addons/actions/src/preview.ts | 1 + 4 files changed, 32 insertions(+), 37 deletions(-) create mode 100644 code/addons/actions/src/loaders.ts diff --git a/code/addons/actions/src/addArgs.ts b/code/addons/actions/src/addArgs.ts index db14aee0ce3d..5742bd8627c0 100644 --- a/code/addons/actions/src/addArgs.ts +++ b/code/addons/actions/src/addArgs.ts @@ -1,12 +1,7 @@ import type { ArgsEnhancer } from '@storybook/types'; -import { - addActionsFromArgTypes, - attachActionsToFunctionMocks, - inferActionsFromArgTypesRegex, -} from './addArgsHelpers'; +import { addActionsFromArgTypes, inferActionsFromArgTypesRegex } from './addArgsHelpers'; export const argsEnhancers: ArgsEnhancer[] = [ addActionsFromArgTypes, inferActionsFromArgTypesRegex, - attachActionsToFunctionMocks, ]; diff --git a/code/addons/actions/src/addArgsHelpers.ts b/code/addons/actions/src/addArgsHelpers.ts index cd4f67897a53..ab8fd3b36a0b 100644 --- a/code/addons/actions/src/addArgsHelpers.ts +++ b/code/addons/actions/src/addArgsHelpers.ts @@ -1,4 +1,3 @@ -/* eslint-disable no-underscore-dangle,no-param-reassign */ import type { Args, Renderer, ArgsEnhancer } from '@storybook/types'; import { action } from './runtime/action'; @@ -63,33 +62,3 @@ export const addActionsFromArgTypes: ArgsEnhancer = (context) => { return acc; }, {} as Args); }; - -export const attachActionsToFunctionMocks: ArgsEnhancer = (context) => { - const { - initialArgs, - argTypes, - parameters: { actions }, - } = context; - if (actions?.disable || !argTypes) { - return {}; - } - - const argTypesWithAction = Object.entries(initialArgs).filter( - ([, value]) => - typeof value === 'function' && - '_isMockFunction' in value && - value._isMockFunction && - !value._actionAttached - ); - - return argTypesWithAction.reduce((acc, [key, value]) => { - const previous = value.getMockImplementation(); - value.mockImplementation((...args: unknown[]) => { - action(key)(...args); - return previous?.(...args); - }); - // this enhancer is being called multiple times - value._actionAttached = true; - return acc; - }, {} as Args); -}; diff --git a/code/addons/actions/src/loaders.ts b/code/addons/actions/src/loaders.ts new file mode 100644 index 000000000000..99e51287a893 --- /dev/null +++ b/code/addons/actions/src/loaders.ts @@ -0,0 +1,30 @@ +/* eslint-disable no-underscore-dangle */ +import type { LoaderFunction } from '@storybook/types'; +import { action } from './runtime'; + +const attachActionsToFunctionMocks: LoaderFunction = (context) => { + const { + args, + parameters: { actions }, + } = context; + if (actions?.disable) return; + + Object.entries(args) + .filter( + ([, value]) => + typeof value === 'function' && '_isMockFunction' in value && value._isMockFunction + ) + .forEach(([key, value]) => { + const previous = value.getMockImplementation(); + if (previous?._actionAttached !== true) { + const implementation = (...params: unknown[]) => { + action(key)(...params); + return previous?.(...params); + }; + implementation._actionAttached = true; + value.mockImplementation(implementation); + } + }); +}; + +export const loaders: LoaderFunction[] = [attachActionsToFunctionMocks]; diff --git a/code/addons/actions/src/preview.ts b/code/addons/actions/src/preview.ts index 7a06751b46dd..bfafaa7faf4e 100644 --- a/code/addons/actions/src/preview.ts +++ b/code/addons/actions/src/preview.ts @@ -1 +1,2 @@ export * from './addArgs'; +export * from './loaders'; From 3e17abebbb26edb35cd777e383e3659cbf0bd394 Mon Sep 17 00:00:00 2001 From: storybook-bot <32066757+storybook-bot@users.noreply.github.com> Date: Wed, 22 Nov 2023 17:02:35 +0000 Subject: [PATCH 170/170] Write changelog for 7.6.0-alpha.7 [skip ci] --- CHANGELOG.prerelease.md | 25 +++++++++++++++++++++++++ code/package.json | 3 ++- docs/versions/next.json | 2 +- 3 files changed, 28 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.prerelease.md b/CHANGELOG.prerelease.md index ead15edae9d9..c09c035b151c 100644 --- a/CHANGELOG.prerelease.md +++ b/CHANGELOG.prerelease.md @@ -1,3 +1,28 @@ +## 7.6.0-alpha.7 + +- Actions: Warn on implicit actions - [#24856](https://github.com/storybookjs/storybook/pull/24856), thanks [@kasperpeulen](https://github.com/kasperpeulen)! +- Addons, core: Make `react` and Storybook packages `devDependencies` where possible - ATTEMPT 2 - [#24834](https://github.com/storybookjs/storybook/pull/24834), thanks [@JReinhold](https://github.com/JReinhold)! +- CLI: Add "doctor" command - [#22236](https://github.com/storybookjs/storybook/pull/22236), thanks [@yannbf](https://github.com/yannbf)! +- Core: Add deprecation notice for Vite + CommonJS - [#23950](https://github.com/storybookjs/storybook/pull/23950), thanks [@JReinhold](https://github.com/JReinhold)! +- Core: Detect no matching export error in storybook start and build - [#24877](https://github.com/storybookjs/storybook/pull/24877), thanks [@yannbf](https://github.com/yannbf)! +- Core: Fix `useStoryPrepared` hook failing with `undefined` data - [#22631](https://github.com/storybookjs/storybook/pull/22631), thanks [@SpookyJelly](https://github.com/SpookyJelly)! +- Core: Gracefully handle error when parsing preview.js file - [#24858](https://github.com/storybookjs/storybook/pull/24858), thanks [@yannbf](https://github.com/yannbf)! +- Core: Make warnOnIncompatibleAddons fault-tolerant - [#24880](https://github.com/storybookjs/storybook/pull/24880), thanks [@taozhou-glean](https://github.com/taozhou-glean)! +- Dependency: Fix Yarn 4 failing to install due to jscodeshift dependency issue - [#24914](https://github.com/storybookjs/storybook/pull/24914), thanks [@samvv](https://github.com/samvv)! +- Dependency: Update jscodeshift to v0.15.1 - [#24882](https://github.com/storybookjs/storybook/pull/24882), thanks [@epreston](https://github.com/epreston)! +- FastBuild: Fix disabledAddons filter - [#24924](https://github.com/storybookjs/storybook/pull/24924), thanks [@IanVS](https://github.com/IanVS)! +- ManagerAPI: Fix setting status without index, crashes storybook - [#24866](https://github.com/storybookjs/storybook/pull/24866), thanks [@ndelangen](https://github.com/ndelangen)! +- Next.js: Add back image context CommonJS export - [#24885](https://github.com/storybookjs/storybook/pull/24885), thanks [@martinnabhan](https://github.com/martinnabhan)! +- Next.js: Add experimental SWC support - [#24852](https://github.com/storybookjs/storybook/pull/24852), thanks [@valentinpalkovic](https://github.com/valentinpalkovic)! +- Next.js: Fix import path in swc loader - [#24922](https://github.com/storybookjs/storybook/pull/24922), thanks [@valentinpalkovic](https://github.com/valentinpalkovic)! +- Svelte: Fix decorators always running twice - [#24921](https://github.com/storybookjs/storybook/pull/24921), thanks [@paoloricciuti](https://github.com/paoloricciuti)! +- SvelteKit: Add experimental page and navigation mocking - [#24795](https://github.com/storybookjs/storybook/pull/24795), thanks [@paoloricciuti](https://github.com/paoloricciuti)! +- Test: Model loaders as before each and restore mocks properly - [#24948](https://github.com/storybookjs/storybook/pull/24948), thanks [@kasperpeulen](https://github.com/kasperpeulen)! +- TestBuild: Add env-variable support to `--test` CLI-flag - [#24862](https://github.com/storybookjs/storybook/pull/24862), thanks [@ndelangen](https://github.com/ndelangen)! +- TestBuild: Add tests and rename to camelCase - [#24911](https://github.com/storybookjs/storybook/pull/24911), thanks [@ndelangen](https://github.com/ndelangen)! +- TestBuild: Fix indexer bug - [#24890](https://github.com/storybookjs/storybook/pull/24890), thanks [@ndelangen](https://github.com/ndelangen)! +- Typescript: Add 'skipCompiler' option to TypeScript presets - [#24847](https://github.com/storybookjs/storybook/pull/24847), thanks [@valentinpalkovic](https://github.com/valentinpalkovic)! + ## 7.6.0-alpha.6 - Addon: Move Visual Test addon to the code directory - [#24771](https://github.com/storybookjs/storybook/pull/24771), thanks [@cdedreuille](https://github.com/cdedreuille)! diff --git a/code/package.json b/code/package.json index 6998a74be8d6..f9be9959024a 100644 --- a/code/package.json +++ b/code/package.json @@ -328,5 +328,6 @@ "Dependency Upgrades" ] ] - } + }, + "deferredNextVersion": "7.6.0-alpha.7" } diff --git a/docs/versions/next.json b/docs/versions/next.json index 3b203dc04f4a..2c346435e0e0 100644 --- a/docs/versions/next.json +++ b/docs/versions/next.json @@ -1 +1 @@ -{"version":"7.6.0-alpha.6","info":{"plain":"- Addon: Move Visual Test addon to the code directory - [#24771](https://github.com/storybookjs/storybook/pull/24771), thanks [@cdedreuille](https://github.com/cdedreuille)!\n- FastBuild: Improve config loading & naming - [#24837](https://github.com/storybookjs/storybook/pull/24837), thanks [@ndelangen](https://github.com/ndelangen)!\n- TestBuild: Revert defaulting to SWC in test build, but keep using esbuild for minification - [#24843](https://github.com/storybookjs/storybook/pull/24843), thanks [@kasperpeulen](https://github.com/kasperpeulen)!\n- Viewport: Add newer device viewports - [#24777](https://github.com/storybookjs/storybook/pull/24777), thanks [@Tomo5524](https://github.com/Tomo5524)!\n- Vite: Prevent non-deterministic build output - [#24833](https://github.com/storybookjs/storybook/pull/24833), thanks [@henkerik](https://github.com/henkerik)!"}} +{"version":"7.6.0-alpha.7","info":{"plain":"- Actions: Warn on implicit actions - [#24856](https://github.com/storybookjs/storybook/pull/24856), thanks [@kasperpeulen](https://github.com/kasperpeulen)!\n- Addons, core: Make `react` and Storybook packages `devDependencies` where possible - ATTEMPT 2 - [#24834](https://github.com/storybookjs/storybook/pull/24834), thanks [@JReinhold](https://github.com/JReinhold)!\n- CLI: Add \\\"doctor\\\" command - [#22236](https://github.com/storybookjs/storybook/pull/22236), thanks [@yannbf](https://github.com/yannbf)!\n- Core: Add deprecation notice for Vite + CommonJS - [#23950](https://github.com/storybookjs/storybook/pull/23950), thanks [@JReinhold](https://github.com/JReinhold)!\n- Core: Detect no matching export error in storybook start and build - [#24877](https://github.com/storybookjs/storybook/pull/24877), thanks [@yannbf](https://github.com/yannbf)!\n- Core: Fix `useStoryPrepared` hook failing with `undefined` data - [#22631](https://github.com/storybookjs/storybook/pull/22631), thanks [@SpookyJelly](https://github.com/SpookyJelly)!\n- Core: Gracefully handle error when parsing preview.js file - [#24858](https://github.com/storybookjs/storybook/pull/24858), thanks [@yannbf](https://github.com/yannbf)!\n- Core: Make warnOnIncompatibleAddons fault-tolerant - [#24880](https://github.com/storybookjs/storybook/pull/24880), thanks [@taozhou-glean](https://github.com/taozhou-glean)!\n- Dependency: Fix Yarn 4 failing to install due to jscodeshift dependency issue - [#24914](https://github.com/storybookjs/storybook/pull/24914), thanks [@samvv](https://github.com/samvv)!\n- Dependency: Update jscodeshift to v0.15.1 - [#24882](https://github.com/storybookjs/storybook/pull/24882), thanks [@epreston](https://github.com/epreston)!\n- FastBuild: Fix disabledAddons filter - [#24924](https://github.com/storybookjs/storybook/pull/24924), thanks [@IanVS](https://github.com/IanVS)!\n- ManagerAPI: Fix setting status without index, crashes storybook - [#24866](https://github.com/storybookjs/storybook/pull/24866), thanks [@ndelangen](https://github.com/ndelangen)!\n- Next.js: Add back image context CommonJS export - [#24885](https://github.com/storybookjs/storybook/pull/24885), thanks [@martinnabhan](https://github.com/martinnabhan)!\n- Next.js: Add experimental SWC support - [#24852](https://github.com/storybookjs/storybook/pull/24852), thanks [@valentinpalkovic](https://github.com/valentinpalkovic)!\n- Next.js: Fix import path in swc loader - [#24922](https://github.com/storybookjs/storybook/pull/24922), thanks [@valentinpalkovic](https://github.com/valentinpalkovic)!\n- Svelte: Fix decorators always running twice - [#24921](https://github.com/storybookjs/storybook/pull/24921), thanks [@paoloricciuti](https://github.com/paoloricciuti)!\n- SvelteKit: Add experimental page and navigation mocking - [#24795](https://github.com/storybookjs/storybook/pull/24795), thanks [@paoloricciuti](https://github.com/paoloricciuti)!\n- Test: Model loaders as before each and restore mocks properly - [#24948](https://github.com/storybookjs/storybook/pull/24948), thanks [@kasperpeulen](https://github.com/kasperpeulen)!\n- TestBuild: Add env-variable support to `--test` CLI-flag - [#24862](https://github.com/storybookjs/storybook/pull/24862), thanks [@ndelangen](https://github.com/ndelangen)!\n- TestBuild: Add tests and rename to camelCase - [#24911](https://github.com/storybookjs/storybook/pull/24911), thanks [@ndelangen](https://github.com/ndelangen)!\n- TestBuild: Fix indexer bug - [#24890](https://github.com/storybookjs/storybook/pull/24890), thanks [@ndelangen](https://github.com/ndelangen)!\n- Typescript: Add 'skipCompiler' option to TypeScript presets - [#24847](https://github.com/storybookjs/storybook/pull/24847), thanks [@valentinpalkovic](https://github.com/valentinpalkovic)!"}}