/
sandbox.ts
378 lines (341 loc) · 10.8 KB
/
sandbox.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
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
/* eslint-disable no-restricted-syntax, no-await-in-loop */
import path from 'path';
import {
remove,
pathExists,
readJSON,
writeJSON,
ensureSymlink,
ensureDir,
existsSync,
} from 'fs-extra';
import prompts from 'prompts';
import { createOptions, getOptionsOrPrompt } from './utils/options';
import { executeCLIStep } from './utils/cli-step';
import { installYarn2, configureYarn2ForVerdaccio, addPackageResolutions } from './utils/yarn';
import { exec } from './utils/exec';
import { getInterpretedFile } from '../code/lib/core-common';
import { ConfigFile, readConfig, writeConfig } from '../code/lib/csf-tools';
import { babelParse } from '../code/lib/csf-tools/src/babelParse';
import TEMPLATES from '../code/lib/cli/src/repro-templates';
type Template = keyof typeof TEMPLATES;
const templates: Template[] = Object.keys(TEMPLATES) as any;
const addons = ['a11y', 'storysource'];
const defaultAddons = [
'actions',
'backgrounds',
'controls',
'docs',
'highlight',
'links',
'interactions',
'measure',
'outline',
'toolbars',
'viewport',
];
const sandboxDir = path.resolve(__dirname, '../sandbox');
const codeDir = path.resolve(__dirname, '../code');
export const options = createOptions({
template: {
type: 'string',
description: 'Which template would you like to use?',
values: templates,
required: true as const,
},
addon: {
type: 'string[]',
description: 'Which extra addons (beyond the CLI defaults) would you like installed?',
values: addons,
},
includeStories: {
type: 'boolean',
description: "Include Storybook's own stories?",
promptType: (_, { template }) => template === 'react',
},
create: {
type: 'boolean',
description: 'Create the template from scratch (rather than degitting it)?',
},
forceDelete: {
type: 'boolean',
description: 'Always delete an existing sandbox, even if it has the same configuration?',
promptType: false,
},
forceReuse: {
type: 'boolean',
description: 'Always reuse an existing sandbox, even if it has a different configuration?',
promptType: false,
},
link: {
type: 'boolean',
description: 'Link the storybook to the local code?',
inverse: true,
},
publish: {
type: 'boolean',
description: 'Publish local code to verdaccio before installing?',
inverse: true,
promptType: (_, { link }) => !link,
},
start: {
type: 'boolean',
description: 'Start the Storybook?',
inverse: true,
},
build: {
type: 'boolean',
description: 'Build the Storybook?',
promptType: (_, { start }) => !start,
},
watch: {
type: 'boolean',
description: 'Start building used packages in watch mode as well as the Storybook?',
promptType: (_, { start }) => start,
},
dryRun: {
type: 'boolean',
description: "Don't execute commands, just list them (dry run)?",
promptType: false,
},
debug: {
type: 'boolean',
description: 'Print all the logs to the console',
promptType: false,
},
});
async function getOptions() {
return getOptionsOrPrompt('yarn sandbox', options);
}
const steps = {
repro: {
command: 'repro-next',
description: 'Bootstrapping Template',
icon: '👷',
hasArgument: true,
options: createOptions({
output: { type: 'string' },
// TODO allow default values for strings
branch: { type: 'string', values: ['next'] },
}),
},
add: {
command: 'add',
description: 'Adding addon',
icon: '+',
hasArgument: true,
options: createOptions({}),
},
link: {
command: 'link',
description: 'Linking packages',
icon: '🔗',
hasArgument: true,
options: createOptions({
local: { type: 'boolean' },
start: { type: 'boolean', inverse: true },
}),
},
build: {
command: 'build',
description: 'Building Storybook',
icon: '🔨',
options: createOptions({}),
},
dev: {
command: 'dev',
description: 'Starting Storybook',
icon: '🖥 ',
options: createOptions({}),
},
};
const logger = console;
async function findFirstPath(paths: string[], { cwd }: { cwd: string }) {
for (const filePath of paths) {
if (await pathExists(path.join(cwd, filePath))) return filePath;
}
return null;
}
async function addPackageScripts({
cwd,
scripts,
}: {
cwd: string;
scripts: Record<string, string>;
}) {
logger.info(`🔢 Adding package scripts:`);
const packageJsonPath = path.join(cwd, 'package.json');
const packageJson = await readJSON(packageJsonPath);
packageJson.scripts = {
...packageJson.scripts,
...scripts,
};
await writeJSON(packageJsonPath, packageJson, { spaces: 2 });
}
async function readMainConfig({ cwd }: { cwd: string }) {
const configDir = path.join(cwd, '.storybook');
if (!existsSync(configDir)) {
throw new Error(
`Unable to find the Storybook folder in "${configDir}". Are you sure it exists? Or maybe this folder uses a custom Storybook config directory?`
);
}
const mainConfigPath = getInterpretedFile(path.resolve(configDir, 'main'));
return readConfig(mainConfigPath);
}
// NOTE: the test regexp here will apply whether the path is symlink-preserved or otherwise
const loaderPath = require.resolve('../code/node_modules/esbuild-loader');
const webpackFinalCode = `
(config) => ({
...config,
module: {
...config.modules,
rules: [
{
test: [/\\/code\\/[^/]*\\/[^/]*\\/template\\/stories\\//],
loader: '${loaderPath}',
options: {
loader: 'tsx',
target: 'es2015',
},
},
...config.module.rules,
],
},
})`;
// paths are of the form 'renderers/react', 'addons/actions'
async function addStories(paths: string[], { mainConfig }: { mainConfig: ConfigFile }) {
const stories = mainConfig.getFieldValue(['stories']) as string[];
const extraStoryDirsAndExistence = await Promise.all(
paths
.map((p) => path.join(p, 'template', 'stories'))
.map(async (p) => [p, await pathExists(path.resolve(codeDir, p))] as const)
);
const relativeCodeDir = path.join('..', '..', '..', 'code');
const extraStories = extraStoryDirsAndExistence
.filter(([, exists]) => exists)
.map(([p]) => path.join(relativeCodeDir, p, '*.stories.@(js|jsx|ts|tsx)'));
mainConfig.setFieldValue(['stories'], [...stories, ...extraStories]);
mainConfig.setFieldNode(
['webpackFinal'],
// @ts-ignore (not sure why TS complains here, it does exist)
babelParse(webpackFinalCode).program.body[0].expression
);
}
async function main() {
const optionValues = await getOptions();
const { template, forceDelete, forceReuse, link, publish, dryRun, debug } = optionValues;
await ensureDir(sandboxDir);
const cwd = path.join(sandboxDir, template.replace('/', '-'));
const exists = await pathExists(cwd);
let shouldDelete = exists && !forceReuse;
if (exists && !forceDelete && !forceReuse) {
const relativePath = path.relative(process.cwd(), cwd);
({ shouldDelete } = await prompts({
type: 'toggle',
message: `${relativePath} already exists, should delete it and create a new one?`,
name: 'shouldDelete',
initial: false,
active: 'yes',
inactive: 'no',
}));
}
if (exists && shouldDelete && !dryRun) await remove(cwd);
if (!exists || shouldDelete) {
await executeCLIStep(steps.repro, {
argument: template,
optionValues: { output: cwd, branch: 'next' },
cwd: sandboxDir,
dryRun,
debug,
});
const mainConfig = await readMainConfig({ cwd });
const templateConfig = TEMPLATES[template as Template];
const storiesPath = await findFirstPath([path.join('src', 'stories'), 'stories'], { cwd });
// Link in the template/components/index.js from the renderer
const rendererName = templateConfig.expected.renderer.split('/')[1];
const rendererPath = path.join('renderers', rendererName);
await ensureSymlink(
path.join(codeDir, rendererPath, 'template', 'components'),
path.resolve(cwd, storiesPath, 'components')
);
mainConfig.setFieldValue(
['previewEntries'],
[`.${path.sep}${path.join(storiesPath, 'components')}`]
);
const storiesToAdd = [] as string[];
storiesToAdd.push(rendererPath);
// TODO -- sb add <addon> doesn't actually work properly:
// - installs in `deps` not `devDeps`
// - does a `workspace:^` install (what does that mean?)
// - doesn't add to `main.js`
for (const addon of optionValues.addon) {
const addonName = `@storybook/addon-${addon}`;
await executeCLIStep(steps.add, { argument: addonName, cwd, dryRun, debug });
}
for (const addon of [...defaultAddons, ...optionValues.addon]) {
storiesToAdd.push(path.join('addons', addon));
}
await addStories(storiesToAdd, { mainConfig });
await writeConfig(mainConfig);
await installYarn2({ cwd, dryRun, debug });
if (link) {
await executeCLIStep(steps.link, {
argument: cwd,
cwd: codeDir,
dryRun,
optionValues: { local: true, start: false },
debug,
});
} else {
if (publish) {
await exec('yarn local-registry --publish', { cwd: codeDir }, { dryRun, debug });
// NOTE: this is a background task and will run forever (TODO: sort out logging/exiting)
exec('CI=true yarn local-registry --open', { cwd: codeDir }, { dryRun, debug });
await exec('yarn wait-on http://localhost:6000', { cwd: codeDir }, { dryRun, debug });
}
// We need to add package resolutions to ensure that we only ever install the latest version
// of any storybook packages as verdaccio is not able to both proxy to npm and publish over
// the top. In theory this could mask issues where different versions cause problems.
await addPackageResolutions({ cwd, dryRun, debug });
await configureYarn2ForVerdaccio({ cwd, dryRun, debug });
await exec(
'yarn install',
{ cwd },
{
dryRun,
startMessage: `⬇️ Installing local dependencies`,
errorMessage: `🚨 Installing local dependencies failed`,
}
);
}
await addPackageScripts({
cwd,
scripts: {
storybook:
'NODE_OPTIONS="--preserve-symlinks --preserve-symlinks-main" storybook dev -p 6006',
'build-storybook':
'NODE_OPTIONS="--preserve-symlinks --preserve-symlinks-main" storybook build',
},
});
}
const { start, build } = optionValues;
if (start) {
await exec(
'yarn storybook',
{ cwd },
{
dryRun,
startMessage: `⬆️ Starting Storybook`,
errorMessage: `🚨 Starting Storybook failed`,
debug: true,
}
);
} else if (build) {
await executeCLIStep(steps.build, { cwd, dryRun, debug });
// TODO serve
}
// TODO start dev
}
if (require.main === module) {
main().catch((err) => console.error(err));
}