1 | const { globToRegexp, serverRequire } = require('@storybook/core/common');
|
2 | const path = require('path');
|
3 | const fs = require('fs');
|
4 |
|
5 | const cwd = process.cwd();
|
6 |
|
7 | const toRequireContext = (specifier) => {
|
8 | const { directory, files } = specifier;
|
9 |
|
10 |
|
11 |
|
12 | const match = globToRegexp(`./${files}`);
|
13 |
|
14 | return {
|
15 | path: directory,
|
16 | recursive: files.includes('**') || files.split('/').length > 1,
|
17 | match,
|
18 | };
|
19 | };
|
20 |
|
21 | function requireUncached(module) {
|
22 | delete require.cache[require.resolve(module)];
|
23 |
|
24 | return serverRequire(module);
|
25 | }
|
26 |
|
27 | const supportedExtensions = ['js', 'jsx', 'ts', 'tsx', 'cjs', 'mjs'];
|
28 |
|
29 | function getFilePathExtension({ configPath }, fileName) {
|
30 | for (const ext of supportedExtensions) {
|
31 | const filePath = path.resolve(cwd, configPath, `${fileName}.${ext}`);
|
32 |
|
33 | if (fs.existsSync(filePath)) {
|
34 | return ext;
|
35 | }
|
36 | }
|
37 |
|
38 | return null;
|
39 | }
|
40 |
|
41 | function getMain({ configPath }) {
|
42 | const fileExtension = getFilePathExtension({ configPath }, 'main');
|
43 |
|
44 | if (fileExtension === null) {
|
45 | throw new Error('main config file not found');
|
46 | }
|
47 |
|
48 | const mainPath = path.resolve(cwd, configPath, `main.${fileExtension}`);
|
49 |
|
50 | return requireUncached(mainPath);
|
51 | }
|
52 |
|
53 | function ensureRelativePathHasDot(relativePath) {
|
54 | return relativePath.startsWith('.') ? relativePath : `./${relativePath}`;
|
55 | }
|
56 |
|
57 | function getPreviewExists({ configPath }) {
|
58 | return !!getFilePathExtension({ configPath }, 'preview');
|
59 | }
|
60 |
|
61 | module.exports = {
|
62 | toRequireContext,
|
63 | requireUncached,
|
64 | getFilePathExtension,
|
65 | getMain,
|
66 | ensureRelativePathHasDot,
|
67 | getPreviewExists,
|
68 | };
|