/
scripts.ts
255 lines (226 loc) · 7.54 KB
/
scripts.ts
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
import path from 'path';
import { readJSON, writeJSON, outputFile } from 'fs-extra';
import shell, { ExecOptions } from 'shelljs';
import chalk from 'chalk';
import { cra, cra_typescript } from './configs';
import storybookVersions from '../versions';
const logger = console;
export interface Parameters {
/** E2E configuration name */
name: string;
/** framework version */
version: string;
/** CLI to bootstrap the project */
generator: string;
/** Use storybook framework detection */
autoDetect?: boolean;
/** Pre-build hook */
preBuildCommand?: string;
/** When cli complains when folder already exists */
ensureDir?: boolean;
/** Dependencies to add before building Storybook */
additionalDeps?: string[];
/** Files to add before installing Storybook */
additionalFiles?: {
path: string;
contents: string;
}[];
/** Add typescript dependency and creates a tsconfig.json file */
typescript?: boolean;
}
interface Configuration {
e2e: boolean;
pnp: boolean;
}
const useLocalSbCli = true;
export interface Options extends Parameters {
appName: string;
creationPath: string;
cwd?: string;
e2e: boolean;
pnp: boolean;
}
export const exec = async (
command: string,
options: ExecOptions = {},
{ startMessage, errorMessage }: { startMessage?: string; errorMessage?: string } = {}
) => {
if (startMessage) {
logger.info(startMessage);
}
logger.debug(command);
return new Promise((resolve, reject) => {
const defaultOptions: ExecOptions = {
silent: true,
};
const child = shell.exec(command, { ...defaultOptions, ...options, async: true });
child.stderr.pipe(process.stderr);
child.stdout.pipe(process.stdout);
child.on('exit', (code) => {
if (code === 0) {
resolve(undefined);
} else {
logger.error(chalk.red(`An error occurred while executing: \`${command}\``));
logger.log(errorMessage);
reject(new Error(`command exited with code: ${code}: `));
}
});
});
};
const addPackageResolutions = async ({ cwd }: Options) => {
logger.info(`🔢 Adding package resolutions:`);
const packageJsonPath = path.join(cwd, 'package.json');
const packageJson = await readJSON(packageJsonPath);
packageJson.resolutions = storybookVersions;
await writeJSON(packageJsonPath, packageJson, { spaces: 2 });
};
const installYarn2 = async ({ cwd, pnp, name }: Options) => {
const command = [
`yarn set version berry`,
`yarn config set enableGlobalCache true`,
`yarn config set nodeLinker ${pnp ? 'pnp' : 'node-modules'}`,
];
// FIXME: Some dependencies used by CRA aren't listed in its package.json
// Next line is a hack to remove as soon as CRA will have added these missing deps
// for details see https://github.com/facebook/create-react-app/pull/11751
if ([cra.name, cra_typescript.name].includes(name)) {
command.push(
`yarn config set packageExtensions --json '{ "babel-preset-react-app@10.0.x": { "dependencies": { "@babel/plugin-proposal-private-property-in-object": "^7.16.0" } } }'`
);
}
await exec(
command.join(' && '),
{ cwd },
{ startMessage: `🧶 Installing Yarn 2`, errorMessage: `🚨 Installing Yarn 2 failed` }
);
};
const configureYarn2ForE2E = async ({ cwd }: Options) => {
const command = [
// ⚠️ Need to set registry because Yarn 2 is not using the conf of Yarn 1 (URL is hardcoded in CircleCI config.yml)
`yarn config set npmScopes --json '{ "storybook": { "npmRegistryServer": "http://localhost:6000/" } }'`,
// Some required magic to be able to fetch deps from local registry
`yarn config set unsafeHttpWhitelist --json '["localhost"]'`,
// Disable fallback mode to make sure everything is required correctly
`yarn config set pnpFallbackMode none`,
// We need to be able to update lockfile when bootstrapping the examples
`yarn config set enableImmutableInstalls false`,
// Discard all YN0013 - FETCH_NOT_CACHED messages
`yarn config set logFilters --json '[ { "code": "YN0013", "level": "discard" } ]'`,
].join(' && ');
await exec(
command,
{ cwd },
{ startMessage: `🎛 Configuring Yarn 2`, errorMessage: `🚨 Configuring Yarn 2 failed` }
);
};
const generate = async ({ cwd, name, appName, version, generator }: Options) => {
const command = generator.replace(/{{appName}}/g, appName).replace(/{{version}}/g, version);
await exec(
command,
{ cwd },
{
startMessage: `🏗 Bootstrapping ${name} project (this might take a few minutes)`,
errorMessage: `🚨 Bootstrapping ${name} failed`,
}
);
};
const addAdditionalFiles = async ({ additionalFiles, cwd }: Options) => {
logger.info(`⤵️ Adding required files`);
await Promise.all(
additionalFiles.map(async (file) => {
await outputFile(path.resolve(cwd, file.path), file.contents, { encoding: 'UTF-8' });
})
);
};
const initStorybook = async ({ cwd, autoDetect = true, name, e2e }: Options) => {
const type = autoDetect ? '' : `--type ${name}`;
const linkable = e2e ? '' : '--linkable';
const sbCLICommand = useLocalSbCli
? `node ${path.join(__dirname, '../../esm/generate')}`
: `yarn dlx -p @storybook/cli sb`;
const command = `${sbCLICommand} init --yes ${type} ${linkable}`;
await exec(
command,
{ cwd },
{
startMessage: `🎨 Initializing Storybook with @storybook/cli`,
errorMessage: `🚨 Storybook initialization failed`,
}
);
};
const addRequiredDeps = async ({ cwd, additionalDeps }: Options) => {
// Remove any lockfile generated without Yarn 2
shell.rm('-f', path.join(cwd, 'package-lock.json'), path.join(cwd, 'yarn.lock'));
const command =
additionalDeps && additionalDeps.length > 0
? `yarn add -D ${additionalDeps.join(' ')}`
: `yarn install`;
await exec(
command,
{ cwd },
{
startMessage: `🌍 Adding needed deps & installing all deps`,
errorMessage: `🚨 Dependencies installation failed`,
}
);
};
const addTypescript = async ({ cwd }: Options) => {
logger.info(`👮 Adding typescript and tsconfig.json`);
try {
await exec(`yarn add -D typescript@latest`, { cwd });
const tsConfig = {
compilerOptions: {
baseUrl: '.',
esModuleInterop: true,
jsx: 'preserve',
skipLibCheck: true,
strict: true,
},
include: ['src/*'],
};
const tsConfigJsonPath = path.resolve(cwd, 'tsconfig.json');
await writeJSON(tsConfigJsonPath, tsConfig, { encoding: 'utf8', spaces: 2 });
} catch (e) {
logger.error(`🚨 Creating tsconfig.json failed`);
throw e;
}
};
const doTask = async (
task: (options: Options) => Promise<void>,
options: Options,
condition = true
) => {
if (condition) {
await task(options);
logger.log();
}
};
export const createAndInit = async (
cwd: string,
{ name, version, ...rest }: Parameters,
{ e2e, pnp }: Configuration
) => {
const options: Options = {
name,
version,
appName: path.basename(cwd),
creationPath: path.join(cwd, '..'),
cwd,
e2e,
pnp,
...rest,
};
logger.log();
logger.info(`🏃 Starting for ${name} ${version}`);
logger.log();
await doTask(generate, { ...options, cwd: options.creationPath });
await doTask(addAdditionalFiles, { ...options, cwd }, !!options.additionalFiles);
if (e2e) {
await doTask(addPackageResolutions, options);
}
await doTask(installYarn2, options);
await doTask(configureYarn2ForE2E, options, e2e);
await doTask(addTypescript, options, !!options.typescript);
await doTask(addRequiredDeps, options);
await doTask(initStorybook, options);
};