-
-
Notifications
You must be signed in to change notification settings - Fork 10k
Expand file tree
/
Copy pathpostinstall.ts
More file actions
601 lines (500 loc) · 20.3 KB
/
postinstall.ts
File metadata and controls
601 lines (500 loc) · 20.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
import { existsSync } from 'node:fs';
import * as fs from 'node:fs/promises';
import { writeFile } from 'node:fs/promises';
import { babelParse, generate, traverse } from 'storybook/internal/babel';
import {
JsPackageManagerFactory,
extractProperFrameworkName,
formatFileContent,
getProjectRoot,
loadAllPresets,
loadMainConfig,
scanAndTransformFiles,
serverResolve,
transformImportFiles,
validateFrameworkName,
} from 'storybook/internal/common';
import { readConfig, writeConfig } from 'storybook/internal/csf-tools';
import { logger } from 'storybook/internal/node-logger';
// eslint-disable-next-line depend/ban-dependencies
import { execa } from 'execa';
import { findUp } from 'find-up';
import { dirname, join, relative, resolve } from 'pathe';
import prompts from 'prompts';
import { coerce, satisfies } from 'semver';
import { dedent } from 'ts-dedent';
import { type PostinstallOptions } from '../../../lib/cli-storybook/src/add';
import { DOCUMENTATION_LINK, SUPPORTED_FRAMEWORKS } from './constants';
import { printError, printInfo, printSuccess, printWarning, step } from './postinstall-logger';
import { loadTemplate, updateConfigFile, updateWorkspaceFile } from './updateVitestFile';
import { getAddonNames } from './utils';
const ADDON_NAME = '@storybook/addon-vitest' as const;
const EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx', '.cts', '.mts', '.cjs', '.mjs'];
const addonA11yName = '@storybook/addon-a11y';
let hasErrors = false;
const logErrors = (...args: Parameters<typeof printError>) => {
hasErrors = true;
printError(...args);
};
const findFile = async (basename: string, extensions = EXTENSIONS) =>
findUp(
extensions.map((ext) => basename + ext),
{ stopAt: getProjectRoot() }
);
export default async function postInstall(options: PostinstallOptions) {
printSuccess(
'👋 Howdy!',
dedent`
I'm the installation helper for ${ADDON_NAME}
Hold on for a moment while I look at your project and get it set up...
`
);
const packageManager = JsPackageManagerFactory.getPackageManager({
force: options.packageManager,
});
const info = await getStorybookInfo(options);
const allDeps = packageManager.getAllDependencies();
// only install these dependencies if they are not already installed
const dependencies = ['vitest', '@vitest/browser', 'playwright'].filter((p) => !allDeps[p]);
const vitestVersionSpecifier = await packageManager.getInstalledVersion('vitest');
const coercedVitestVersion = vitestVersionSpecifier ? coerce(vitestVersionSpecifier) : null;
const isVitest3_2OrNewer = vitestVersionSpecifier
? satisfies(vitestVersionSpecifier, '>=3.2.0')
: true;
const mainJsPath = serverResolve(resolve(options.configDir, 'main')) as string;
const config = await readConfig(mainJsPath);
const hasCustomWebpackConfig = !!config.getFieldNode(['webpackFinal']);
const isInteractive = process.stdout.isTTY && !process.env.CI;
if (info.frameworkPackageName === '@storybook/nextjs' && !hasCustomWebpackConfig) {
const out =
options.yes || !isInteractive
? { migrateToNextjsVite: !!options.yes }
: await prompts({
type: 'confirm',
name: 'migrateToNextjsVite',
message: dedent`
The addon requires the use of @storybook/nextjs-vite to work with Next.js.
https://storybook.js.org/docs/next/${DOCUMENTATION_LINK}#install-and-set-up
Do you want to migrate?
`,
initial: true,
});
if (out.migrateToNextjsVite) {
await packageManager.addDependencies({ type: 'devDependencies', skipInstall: true }, [
'@storybook/nextjs-vite',
]);
await packageManager.removeDependencies(['@storybook/nextjs']);
traverse(config._ast, {
StringLiteral(path) {
if (path.node.value === '@storybook/nextjs') {
path.node.value = '@storybook/nextjs-vite';
}
},
});
await writeConfig(config, mainJsPath);
info.frameworkPackageName = '@storybook/nextjs-vite';
info.builderPackageName = '@storybook/builder-vite';
await scanAndTransformFiles({
promptMessage:
'Enter a glob to scan for all @storybook/nextjs imports to substitute with @storybook/nextjs-vite:',
force: options.yes,
dryRun: false,
transformFn: (files, options, dryRun) => transformImportFiles(files, options, dryRun),
transformOptions: {
'@storybook/nextjs': '@storybook/nextjs-vite',
},
});
}
}
const annotationsImport = SUPPORTED_FRAMEWORKS.includes(info.frameworkPackageName)
? info.frameworkPackageName === '@storybook/nextjs'
? '@storybook/nextjs-vite'
: info.frameworkPackageName
: null;
const isRendererSupported = !!annotationsImport;
const prerequisiteCheck = async () => {
const reasons = [];
if (hasCustomWebpackConfig) {
reasons.push('• The addon can not be used with a custom Webpack configuration.');
}
if (
info.frameworkPackageName !== '@storybook/nextjs' &&
info.builderPackageName !== '@storybook/builder-vite'
) {
reasons.push(
'• The addon can only be used with a Vite-based Storybook framework or Next.js.'
);
}
if (!isRendererSupported) {
reasons.push(dedent`
• The addon cannot yet be used with ${info.frameworkPackageName}
`);
}
if (coercedVitestVersion && !satisfies(coercedVitestVersion, '>=3.0.0')) {
reasons.push(dedent`
• The addon requires Vitest 3.0.0 or higher. You are currently using ${vitestVersionSpecifier}.
Please update all of your Vitest dependencies and try again.
`);
}
const mswVersionSpecifier = await packageManager.getInstalledVersion('msw');
const coercedMswVersion = mswVersionSpecifier ? coerce(mswVersionSpecifier) : null;
if (coercedMswVersion && !satisfies(coercedMswVersion, '>=2.0.0')) {
reasons.push(dedent`
• The addon uses Vitest behind the scenes, which supports only version 2 and above of MSW. However, we have detected version ${coercedMswVersion.version} in this project.
Please update the 'msw' package and try again.
`);
}
if (info.frameworkPackageName === '@storybook/nextjs') {
const nextVersion = await packageManager.getInstalledVersion('next');
if (!nextVersion) {
reasons.push(dedent`
• You are using @storybook/nextjs without having "next" installed.
Please install "next" or use a different Storybook framework integration and try again.
`);
}
}
if (reasons.length > 0) {
reasons.unshift(
`@storybook/addon-vitest's automated setup failed due to the following package incompatibilities:`
);
reasons.push('--------------------------------');
reasons.push(
dedent`
You can fix these issues and rerun the command to reinstall. If you wish to roll back the installation, remove ${ADDON_NAME} from the "addons" array
in your main Storybook config file and remove the dependency from your package.json file.
`
);
if (!isRendererSupported) {
reasons.push(
dedent`
Please check the documentation for more information about its requirements and installation:
https://storybook.js.org/docs/next/${DOCUMENTATION_LINK}
`
);
} else {
reasons.push(
dedent`
Fear not, however, you can follow the manual installation process instead at:
https://storybook.js.org/docs/next/${DOCUMENTATION_LINK}#manual-setup
`
);
}
return reasons.map((r) => r.trim()).join('\n\n');
}
return null;
};
const result = await prerequisiteCheck();
if (result) {
logErrors('⛔️ Sorry!', result);
logger.line(1);
return;
}
if (info.frameworkPackageName === '@storybook/nextjs') {
printInfo(
'🍿 Just so you know...',
dedent`
It looks like you're using Next.js.
Adding "@storybook/nextjs-vite/vite-plugin" so you can use it with Vitest.
More info about the plugin at https://github.com/storybookjs/vite-plugin-storybook-nextjs
`
);
try {
const storybookVersion = await packageManager.getInstalledVersion('storybook');
dependencies.push(`@storybook/nextjs-vite@^${storybookVersion}`);
} catch (e) {
console.error('Failed to install @storybook/nextjs-vite. Please install it manually');
}
}
const v8Version = await packageManager.getInstalledVersion('@vitest/coverage-v8');
const istanbulVersion = await packageManager.getInstalledVersion('@vitest/coverage-istanbul');
if (!v8Version && !istanbulVersion) {
printInfo(
'🙈 Let me cover this for you',
dedent`
You don't seem to have a coverage reporter installed. Vitest needs either V8 or Istanbul to generate coverage reports.
Adding "@vitest/coverage-v8" to enable coverage reporting.
Read more about Vitest coverage providers at https://vitest.dev/guide/coverage.html#coverage-providers
`
);
dependencies.push(`@vitest/coverage-v8`); // Version specifier is added below
}
const versionedDependencies = dependencies.map((p) => {
if (p.includes('vitest')) {
return vitestVersionSpecifier ? `${p}@${vitestVersionSpecifier}` : p;
}
return p;
});
if (versionedDependencies.length > 0) {
await packageManager.addDependencies(
{ type: 'devDependencies', skipInstall: true },
versionedDependencies
);
logger.line(1);
logger.plain(`${step} Installing dependencies:`);
logger.plain(' ' + versionedDependencies.join(', '));
}
await packageManager.installDependencies();
logger.line(1);
if (options.skipInstall) {
logger.plain('Skipping Playwright installation, please run this command manually:');
logger.plain(' npx playwright install chromium --with-deps');
} else {
logger.plain(`${step} Configuring Playwright with Chromium (this might take some time):`);
logger.plain(' npx playwright install chromium --with-deps');
await packageManager.executeCommand({
command: 'npx',
args: ['playwright', 'install', 'chromium', '--with-deps'],
});
}
const fileExtension =
allDeps.typescript || (await findFile('tsconfig', [...EXTENSIONS, '.json'])) ? 'ts' : 'js';
const vitestSetupFile = resolve(options.configDir, `vitest.setup.${fileExtension}`);
if (existsSync(vitestSetupFile)) {
logErrors(
'🚨 Oh no!',
dedent`
Found an existing Vitest setup file:
${vitestSetupFile}
Please refer to the documentation to complete the setup manually:
https://storybook.js.org/docs/next/${DOCUMENTATION_LINK}#manual-setup
`
);
logger.line(1);
return;
}
logger.line(1);
logger.plain(`${step} Creating a Vitest setup file for Storybook:`);
logger.plain(` ${vitestSetupFile}`);
const previewExists = EXTENSIONS.map((ext) => resolve(options.configDir, `preview${ext}`)).some(
existsSync
);
const imports = [`import { setProjectAnnotations } from '${annotationsImport}';`];
const projectAnnotations = [];
if (previewExists) {
imports.push(`import * as projectAnnotations from './preview';`);
projectAnnotations.push('projectAnnotations');
}
await writeFile(
vitestSetupFile,
dedent`
${imports.join('\n')}
// This is an important step to apply the right configuration when testing your stories.
// More info at: https://storybook.js.org/docs/api/portable-stories/portable-stories-vitest#setprojectannotations
setProjectAnnotations([${projectAnnotations.join(', ')}]);
`
);
const vitestWorkspaceFile =
(await findFile('vitest.workspace', ['.ts', '.js', '.json'])) ||
(await findFile('vitest.projects', ['.ts', '.js', '.json']));
const viteConfigFile = await findFile('vite.config');
const vitestConfigFile = await findFile('vitest.config');
const vitestShimFile = await findFile('vitest.shims.d');
const rootConfig = vitestConfigFile || viteConfigFile;
const browserConfig = `{
enabled: true,
headless: true,
provider: 'playwright',
instances: [{ browser: 'chromium' }]
}`;
if (fileExtension === 'ts' && !vitestShimFile) {
await writeFile(
'vitest.shims.d.ts',
'/// <reference types="@vitest/browser/providers/playwright" />'
);
}
// If there's an existing workspace file, we update that file to include the Storybook Addon Vitest plugin.
// We assume the existing workspaces include the Vite(st) config, so we won't add it.
if (vitestWorkspaceFile) {
const workspaceTemplate = await loadTemplate('vitest.workspace.template.ts', {
EXTENDS_WORKSPACE: viteConfigFile
? relative(dirname(vitestWorkspaceFile), viteConfigFile)
: '',
CONFIG_DIR: options.configDir,
BROWSER_CONFIG: browserConfig,
SETUP_FILE: relative(dirname(vitestWorkspaceFile), vitestSetupFile),
}).then((t) => t.replace(`\n 'ROOT_CONFIG',`, '').replace(/\s+extends: '',/, ''));
const workspaceFile = await fs.readFile(vitestWorkspaceFile, 'utf8');
const source = babelParse(workspaceTemplate);
const target = babelParse(workspaceFile);
const updated = updateWorkspaceFile(source, target);
if (updated) {
logger.line(1);
logger.plain(`${step} Updating your Vitest workspace file:`);
logger.plain(` ${vitestWorkspaceFile}`);
const formattedContent = await formatFileContent(vitestWorkspaceFile, generate(target).code);
await writeFile(vitestWorkspaceFile, formattedContent);
} else {
logErrors(
'🚨 Oh no!',
dedent`
Could not update existing Vitest workspace file:
${vitestWorkspaceFile}
I was able to configure most of the addon but could not safely extend
your existing workspace file automatically, you must do it yourself.
Please refer to the documentation to complete the setup manually:
https://storybook.js.org/docs/next/${DOCUMENTATION_LINK}#manual-setup
`
);
logger.line(1);
return;
}
}
// If there's an existing Vite/Vitest config with workspaces, we update it to include the Storybook Addon Vitest plugin.
else if (rootConfig) {
let target, updated;
const configFile = await fs.readFile(rootConfig, 'utf8');
const hasProjectsConfig = configFile.includes('projects:');
const configFileHasTypeReference = configFile.match(
/\/\/\/\s*<reference\s+types=["']vitest\/config["']\s*\/>/
);
const templateName =
hasProjectsConfig || isVitest3_2OrNewer
? 'vitest.config.3.2.template.ts'
: 'vitest.config.template.ts';
if (templateName) {
const configTemplate = await loadTemplate(templateName, {
CONFIG_DIR: options.configDir,
BROWSER_CONFIG: browserConfig,
SETUP_FILE: relative(dirname(rootConfig), vitestSetupFile),
});
const source = babelParse(configTemplate);
target = babelParse(configFile);
updated = updateConfigFile(source, target);
}
if (target && updated) {
logger.line(1);
logger.plain(`${step} Updating your ${vitestConfigFile ? 'Vitest' : 'Vite'} config file:`);
logger.plain(` ${rootConfig}`);
const formattedContent = await formatFileContent(rootConfig, generate(target).code);
await writeFile(
rootConfig,
configFileHasTypeReference
? formattedContent
: '/// <reference types="vitest/config" />\n' + formattedContent
);
} else {
logErrors(
'🚨 Oh no!',
dedent`
We were unable to update your existing ${vitestConfigFile ? 'Vitest' : 'Vite'} config file.
Please refer to the documentation to complete the setup manually:
https://storybook.js.org/docs/writing-tests/integrations/vitest-addon#manual-setup
`
);
}
}
// If there's no existing Vitest/Vite config, we create a new Vitest config file.
else {
const newConfigFile = resolve(`vitest.config.${fileExtension}`);
const configTemplate = await loadTemplate(
isVitest3_2OrNewer ? 'vitest.config.3.2.template.ts' : 'vitest.config.template.ts',
{
CONFIG_DIR: options.configDir,
BROWSER_CONFIG: browserConfig,
SETUP_FILE: relative(dirname(newConfigFile), vitestSetupFile),
}
);
logger.line(1);
logger.plain(`${step} Creating a Vitest config file:`);
logger.plain(` ${newConfigFile}`);
const formattedContent = await formatFileContent(newConfigFile, configTemplate);
await writeFile(newConfigFile, formattedContent);
}
const a11yAddon = info.addons.find((addon) => addon.includes(addonA11yName));
if (a11yAddon) {
try {
logger.plain(`${step} Setting up ${addonA11yName} for @storybook/addon-vitest:`);
const command = ['automigrate', 'addon-a11y-addon-test'];
command.push('--loglevel', 'silent');
command.push('--yes', '--skip-doctor');
if (options.packageManager) {
command.push('--package-manager', options.packageManager);
}
if (options.skipInstall) {
command.push('--skip-install');
}
if (options.configDir !== '.storybook') {
command.push('--config-dir', options.configDir);
}
await execa('storybook', command, {
stdio: 'inherit',
});
} catch (e: unknown) {
logErrors(
'🚨 Oh no!',
dedent`
We have detected that you have ${addonA11yName} installed but could not automatically set it up for @storybook/addon-vitest:
${e instanceof Error ? e.message : String(e)}
Please refer to the documentation to complete the setup manually:
https://storybook.js.org/docs/writing-tests/accessibility-testing#test-addon-integration
`
);
}
}
const runCommand = rootConfig ? `npx vitest --project=storybook` : `npx vitest`;
if (!hasErrors) {
printSuccess(
'🎉 All done!',
dedent`
@storybook/addon-vitest is now configured and you're ready to run your tests!
Here are a couple of tips to get you started:
• You can run tests with "${runCommand}"
• When using the Vitest extension in your editor, all of your stories will be shown as tests!
Check the documentation for more information about its features and options at:
https://storybook.js.org/docs/next/${DOCUMENTATION_LINK}
`
);
} else {
printWarning(
'⚠️ Done, but with errors!',
dedent`
@storybook/addon-vitest was installed successfully, but there were some errors during the setup process.
Please refer to the documentation to complete the setup manually and check the errors above:
https://storybook.js.org/docs/next/${DOCUMENTATION_LINK}#manual-setup
`
);
}
logger.line(1);
}
async function getStorybookInfo({ configDir, packageManager: pkgMgr }: PostinstallOptions) {
const packageManager = JsPackageManagerFactory.getPackageManager({ force: pkgMgr, configDir });
const { packageJson } = packageManager.primaryPackageJson;
const config = await loadMainConfig({ configDir, noCache: true });
const { framework } = config;
const frameworkName = typeof framework === 'string' ? framework : framework?.name;
validateFrameworkName(frameworkName);
const frameworkPackageName = extractProperFrameworkName(frameworkName);
const presets = await loadAllPresets({
corePresets: [join(frameworkName, 'preset')],
overridePresets: [
require.resolve('storybook/internal/core-server/presets/common-override-preset'),
],
packageJson,
configDir,
isCritical: true,
});
const core = await presets.apply('core', {});
const { builder, renderer } = core;
if (!builder) {
throw new Error('Could not detect your Storybook builder.');
}
const builderPackageJson = await fs.readFile(
require.resolve(join(typeof builder === 'string' ? builder : builder.name, 'package.json')),
'utf8'
);
const builderPackageName = JSON.parse(builderPackageJson).name;
let rendererPackageName: string | undefined;
if (renderer) {
const rendererPackageJson = await fs.readFile(
require.resolve(join(renderer, 'package.json')),
'utf8'
);
rendererPackageName = JSON.parse(rendererPackageJson).name;
}
return {
frameworkPackageName,
builderPackageName,
rendererPackageName,
addons: getAddonNames(config),
};
}