@atlaspack/cli 2.12.1-dev.3356

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/cli.js ADDED
@@ -0,0 +1,576 @@
1
+ // @flow
2
+
3
+ import type {InitialAtlaspackOptions} from '@atlaspack/types';
4
+ import {BuildError} from '@atlaspack/core';
5
+ import {NodeFS} from '@atlaspack/fs';
6
+ import ThrowableDiagnostic from '@atlaspack/diagnostic';
7
+ import {prettyDiagnostic, openInBrowser} from '@atlaspack/utils';
8
+ import {Disposable} from '@atlaspack/events';
9
+ import {INTERNAL_ORIGINAL_CONSOLE} from '@atlaspack/logger';
10
+ import chalk from 'chalk';
11
+ import commander from 'commander';
12
+ import path from 'path';
13
+ import getPort from 'get-port';
14
+ import {version} from '../package.json';
15
+ import {DEFAULT_FEATURE_FLAGS} from '@atlaspack/feature-flags';
16
+
17
+ const program = new commander.Command();
18
+
19
+ // Exit codes in response to signals are traditionally
20
+ // 128 + signal value
21
+ // https://tldp.org/LDP/abs/html/exitcodes.html
22
+ const SIGINT_EXIT_CODE = 130;
23
+
24
+ async function logUncaughtError(e: mixed) {
25
+ if (e instanceof ThrowableDiagnostic) {
26
+ for (let diagnostic of e.diagnostics) {
27
+ let {message, codeframe, stack, hints, documentation} =
28
+ await prettyDiagnostic(diagnostic);
29
+ INTERNAL_ORIGINAL_CONSOLE.error(chalk.red(message));
30
+ if (codeframe || stack) {
31
+ INTERNAL_ORIGINAL_CONSOLE.error('');
32
+ }
33
+ INTERNAL_ORIGINAL_CONSOLE.error(codeframe);
34
+ INTERNAL_ORIGINAL_CONSOLE.error(stack);
35
+ if ((stack || codeframe) && hints.length > 0) {
36
+ INTERNAL_ORIGINAL_CONSOLE.error('');
37
+ }
38
+ for (let h of hints) {
39
+ INTERNAL_ORIGINAL_CONSOLE.error(chalk.blue(h));
40
+ }
41
+ if (documentation) {
42
+ INTERNAL_ORIGINAL_CONSOLE.error(chalk.magenta.bold(documentation));
43
+ }
44
+ }
45
+ } else {
46
+ INTERNAL_ORIGINAL_CONSOLE.error(e);
47
+ }
48
+
49
+ // A hack to definitely ensure we logged the uncaught exception
50
+ await new Promise(resolve => setTimeout(resolve, 100));
51
+ }
52
+
53
+ const handleUncaughtException = async exception => {
54
+ try {
55
+ await logUncaughtError(exception);
56
+ } catch (err) {
57
+ console.error(exception);
58
+ console.error(err);
59
+ }
60
+
61
+ process.exit(1);
62
+ };
63
+
64
+ process.on('unhandledRejection', handleUncaughtException);
65
+
66
+ program.storeOptionsAsProperties();
67
+ program.version(version);
68
+
69
+ // Only display choices available to callers OS
70
+ let watcherBackendChoices = ['brute-force'];
71
+ switch (process.platform) {
72
+ case 'darwin': {
73
+ watcherBackendChoices.push('watchman', 'fs-events');
74
+ break;
75
+ }
76
+ case 'linux': {
77
+ watcherBackendChoices.push('watchman', 'inotify');
78
+ break;
79
+ }
80
+ case 'win32': {
81
+ watcherBackendChoices.push('watchman', 'windows');
82
+ break;
83
+ }
84
+ case 'freebsd' || 'openbsd': {
85
+ watcherBackendChoices.push('watchman');
86
+ break;
87
+ }
88
+ default:
89
+ break;
90
+ }
91
+
92
+ // --no-cache, --cache-dir, --no-source-maps, --no-autoinstall, --global?, --public-url, --log-level
93
+ // --no-content-hash, --experimental-scope-hoisting, --detailed-report
94
+ const commonOptions = {
95
+ '--no-cache': 'disable the filesystem cache',
96
+ '--config <path>':
97
+ 'specify which config to use. can be a path or a package name',
98
+ '--cache-dir <path>':
99
+ 'set the cache directory. defaults to ".atlaspack-cache"',
100
+ '--watch-dir <path>':
101
+ 'set the root watch directory. defaults to nearest lockfile or source control dir.',
102
+ '--watch-ignore [path]': [
103
+ `list of directories watcher should not be tracking for changes. defaults to ['.git', '.hg']`,
104
+ dirs => dirs.split(','),
105
+ ],
106
+ '--watch-backend': new commander.Option(
107
+ '--watch-backend <name>',
108
+ 'set watcher backend',
109
+ ).choices(watcherBackendChoices),
110
+ '--no-source-maps': 'disable sourcemaps',
111
+ '--target [name]': [
112
+ 'only build given target(s)',
113
+ (val, list) => list.concat([val]),
114
+ [],
115
+ ],
116
+ '--log-level <level>': new commander.Option(
117
+ '--log-level <level>',
118
+ 'set the log level',
119
+ ).choices(['none', 'error', 'warn', 'info', 'verbose']),
120
+ '--dist-dir <dir>':
121
+ 'output directory to write to when unspecified by targets',
122
+ '--no-autoinstall': 'disable autoinstall',
123
+ '--profile': 'enable sampling build profiling',
124
+ '--trace': 'enable build tracing',
125
+ '-V, --version': 'output the version number',
126
+ '--detailed-report [count]': [
127
+ 'print the asset timings and sizes in the build report',
128
+ parseOptionInt,
129
+ ],
130
+ '--reporter <name>': [
131
+ 'additional reporters to run',
132
+ (val, acc) => {
133
+ acc.push(val);
134
+ return acc;
135
+ },
136
+ [],
137
+ ],
138
+ '--feature-flag <name=value>': [
139
+ 'sets the value of a feature flag',
140
+ (value, previousValue) => {
141
+ let [name, val] = value.split('=');
142
+ if (name in DEFAULT_FEATURE_FLAGS) {
143
+ let featureFlagValue;
144
+ if (typeof DEFAULT_FEATURE_FLAGS[name] === 'boolean') {
145
+ if (val !== 'true' && val !== 'false') {
146
+ throw new Error(
147
+ `Feature flag ${name} must be set to true or false`,
148
+ );
149
+ }
150
+ featureFlagValue = val === 'true';
151
+ }
152
+ previousValue[name] = featureFlagValue ?? String(val);
153
+ } else {
154
+ INTERNAL_ORIGINAL_CONSOLE.warn(
155
+ `Unknown feature flag ${name} specified, it will be ignored`,
156
+ );
157
+ }
158
+ return previousValue;
159
+ },
160
+ {},
161
+ ],
162
+ };
163
+
164
+ var hmrOptions = {
165
+ '--no-hmr': 'disable hot module replacement',
166
+ '-p, --port <port>': [
167
+ 'set the port to serve on. defaults to $PORT or 1234',
168
+ process.env.PORT,
169
+ ],
170
+ '--host <host>':
171
+ 'set the host to listen on, defaults to listening on all interfaces',
172
+ '--https': 'serves files over HTTPS',
173
+ '--cert <path>': 'path to certificate to use with HTTPS',
174
+ '--key <path>': 'path to private key to use with HTTPS',
175
+ '--hmr-port <port>': ['hot module replacement port', process.env.HMR_PORT],
176
+ '--hmr-host <host>': ['hot module replacement host', process.env.HMR_HOST],
177
+ };
178
+
179
+ function applyOptions(cmd, options) {
180
+ for (let opt in options) {
181
+ const option = options[opt];
182
+ if (option instanceof commander.Option) {
183
+ cmd.addOption(option);
184
+ } else {
185
+ cmd.option(opt, ...(Array.isArray(option) ? option : [option]));
186
+ }
187
+ }
188
+ }
189
+
190
+ let serve = program
191
+ .command('serve [input...]')
192
+ .description('starts a development server')
193
+ .option('--public-url <url>', 'the path prefix for absolute urls')
194
+ .option(
195
+ '--open [browser]',
196
+ 'automatically open in specified browser, defaults to default browser',
197
+ )
198
+ .option('--watch-for-stdin', 'exit when stdin closes')
199
+ .option(
200
+ '--lazy [includes]',
201
+ 'Build async bundles on demand, when requested in the browser. Defaults to all async bundles, unless a comma separated list of source file globs is provided. Only async bundles whose entry points match these globs will be built lazily',
202
+ )
203
+ .option(
204
+ '--lazy-exclude <excludes>',
205
+ 'Can only be used in combination with --lazy. Comma separated list of source file globs, async bundles whose entry points match these globs will not be built lazily',
206
+ )
207
+ .action(runCommand);
208
+
209
+ applyOptions(serve, hmrOptions);
210
+ applyOptions(serve, commonOptions);
211
+
212
+ let watch = program
213
+ .command('watch [input...]')
214
+ .description('starts the bundler in watch mode')
215
+ .option('--public-url <url>', 'the path prefix for absolute urls')
216
+ .option('--no-content-hash', 'disable content hashing')
217
+ .option('--watch-for-stdin', 'exit when stdin closes')
218
+ .action(runCommand);
219
+
220
+ applyOptions(watch, hmrOptions);
221
+ applyOptions(watch, commonOptions);
222
+
223
+ let build = program
224
+ .command('build [input...]')
225
+ .description('bundles for production')
226
+ .option('--no-optimize', 'disable minification')
227
+ .option('--no-scope-hoist', 'disable scope-hoisting')
228
+ .option('--public-url <url>', 'the path prefix for absolute urls')
229
+ .option('--no-content-hash', 'disable content hashing')
230
+ .action(runCommand);
231
+
232
+ applyOptions(build, commonOptions);
233
+
234
+ program
235
+ .command('help [command]')
236
+ .description('display help information for a command')
237
+ .action(function (command) {
238
+ let cmd = program.commands.find(c => c.name() === command) || program;
239
+ cmd.help();
240
+ });
241
+
242
+ program.on('--help', function () {
243
+ INTERNAL_ORIGINAL_CONSOLE.log('');
244
+ INTERNAL_ORIGINAL_CONSOLE.log(
245
+ ' Run `' +
246
+ chalk.bold('atlaspack help <command>') +
247
+ '` for more information on specific commands',
248
+ );
249
+ INTERNAL_ORIGINAL_CONSOLE.log('');
250
+ });
251
+
252
+ // Override to output option description if argument was missing
253
+ // $FlowFixMe[prop-missing]
254
+ commander.Command.prototype.optionMissingArgument = function (option) {
255
+ INTERNAL_ORIGINAL_CONSOLE.error(
256
+ "error: option `%s' argument missing",
257
+ option.flags,
258
+ );
259
+ INTERNAL_ORIGINAL_CONSOLE.log(program.createHelp().optionDescription(option));
260
+ process.exit(1);
261
+ };
262
+
263
+ // Make serve the default command except for --help
264
+ var args = process.argv;
265
+ if (args[2] === '--help' || args[2] === '-h') args[2] = 'help';
266
+
267
+ if (!args[2] || !program.commands.some(c => c.name() === args[2])) {
268
+ args.splice(2, 0, 'serve');
269
+ }
270
+
271
+ program.parse(args);
272
+
273
+ function runCommand(...args) {
274
+ run(...args).catch(handleUncaughtException);
275
+ }
276
+
277
+ async function run(
278
+ entries: Array<string>,
279
+ _opts: any, // using pre v7 Commander options as properties
280
+ command: any,
281
+ ) {
282
+ if (entries.length === 0) {
283
+ entries = ['.'];
284
+ }
285
+
286
+ entries = entries.map(entry => path.resolve(entry));
287
+
288
+ let Atlaspack = require('@atlaspack/core').default;
289
+ let fs = new NodeFS();
290
+ let options = await normalizeOptions(command, fs);
291
+ let atlaspack = new Atlaspack({
292
+ entries,
293
+ defaultConfig: require.resolve('@atlaspack/config-default', {
294
+ paths: [fs.cwd(), __dirname],
295
+ }),
296
+ shouldPatchConsole: false,
297
+ ...options,
298
+ });
299
+
300
+ let disposable = new Disposable();
301
+ let unsubscribe: () => Promise<mixed>;
302
+ let isExiting;
303
+ async function exit(exitCode: number = 0) {
304
+ if (isExiting) {
305
+ return;
306
+ }
307
+
308
+ isExiting = true;
309
+ if (unsubscribe != null) {
310
+ await unsubscribe();
311
+ } else if (atlaspack.isProfiling) {
312
+ await atlaspack.stopProfiling();
313
+ }
314
+
315
+ if (process.stdin.isTTY && process.stdin.isRaw) {
316
+ // $FlowFixMe
317
+ process.stdin.setRawMode(false);
318
+ }
319
+
320
+ disposable.dispose();
321
+ process.exit(exitCode);
322
+ }
323
+
324
+ const isWatching = command.name() === 'watch' || command.name() === 'serve';
325
+ if (process.stdin.isTTY) {
326
+ // $FlowFixMe
327
+ process.stdin.setRawMode(true);
328
+ require('readline').emitKeypressEvents(process.stdin);
329
+
330
+ let stream = process.stdin.on('keypress', async (char, key) => {
331
+ if (!key.ctrl) {
332
+ return;
333
+ }
334
+
335
+ switch (key.name) {
336
+ case 'c':
337
+ // Detect the ctrl+c key, and gracefully exit after writing the asset graph to the cache.
338
+ // This is mostly for tools that wrap Atlaspack as a child process like yarn and npm.
339
+ //
340
+ // Setting raw mode prevents SIGINT from being sent in response to ctrl-c:
341
+ // https://nodejs.org/api/tty.html#tty_readstream_setrawmode_mode
342
+ //
343
+ // We don't use the SIGINT event for this because when run inside yarn, the parent
344
+ // yarn process ends before Atlaspack and it appears that Atlaspack has ended while it may still
345
+ // be cleaning up. Handling events from stdin prevents this impression.
346
+ //
347
+ // When watching, a 0 success code is acceptable when Atlaspack is interrupted with ctrl-c.
348
+ // When building, fail with a code as if we received a SIGINT.
349
+ await exit(isWatching ? 0 : SIGINT_EXIT_CODE);
350
+ break;
351
+ case 'e':
352
+ await (atlaspack.isProfiling
353
+ ? atlaspack.stopProfiling()
354
+ : atlaspack.startProfiling());
355
+ break;
356
+ case 'y':
357
+ await atlaspack.takeHeapSnapshot();
358
+ break;
359
+ }
360
+ });
361
+
362
+ disposable.add(() => {
363
+ stream.destroy();
364
+ });
365
+ }
366
+
367
+ if (isWatching) {
368
+ ({unsubscribe} = await atlaspack.watch(err => {
369
+ if (err) {
370
+ throw err;
371
+ }
372
+ }));
373
+
374
+ if (command.open && options.serveOptions) {
375
+ await openInBrowser(
376
+ `${options.serveOptions.https ? 'https' : 'http'}://${
377
+ options.serveOptions.host || 'localhost'
378
+ }:${options.serveOptions.port}`,
379
+ command.open,
380
+ );
381
+ }
382
+
383
+ if (command.watchForStdin) {
384
+ process.stdin.on('end', async () => {
385
+ INTERNAL_ORIGINAL_CONSOLE.log('STDIN closed, ending');
386
+
387
+ await exit();
388
+ });
389
+ process.stdin.resume();
390
+ }
391
+
392
+ // In non-tty cases, respond to SIGINT by cleaning up. Since we're watching,
393
+ // a 0 success code is acceptable.
394
+ process.on('SIGINT', () => exit());
395
+ process.on('SIGTERM', () => exit());
396
+ } else {
397
+ try {
398
+ await atlaspack.run();
399
+ } catch (err) {
400
+ // If an exception is thrown during Atlaspack.build, it is given to reporters in a
401
+ // buildFailure event, and has been shown to the user.
402
+ if (!(err instanceof BuildError)) {
403
+ await logUncaughtError(err);
404
+ }
405
+ await exit(1);
406
+ }
407
+
408
+ await exit();
409
+ }
410
+ }
411
+
412
+ function parsePort(portValue: string): number {
413
+ let parsedPort = Number(portValue);
414
+
415
+ // Throw an error if port value is invalid...
416
+ if (!Number.isInteger(parsedPort)) {
417
+ throw new Error(`Port ${portValue} is not a valid integer.`);
418
+ }
419
+
420
+ return parsedPort;
421
+ }
422
+
423
+ function parseOptionInt(value) {
424
+ const parsedValue = parseInt(value, 10);
425
+ if (isNaN(parsedValue)) {
426
+ throw new commander.InvalidOptionArgumentError('Must be an integer.');
427
+ }
428
+ return parsedValue;
429
+ }
430
+
431
+ async function normalizeOptions(
432
+ command,
433
+ inputFS,
434
+ ): Promise<InitialAtlaspackOptions> {
435
+ let nodeEnv;
436
+ if (command.name() === 'build') {
437
+ nodeEnv = process.env.NODE_ENV || 'production';
438
+ // Autoinstall unless explicitly disabled or we detect a CI environment.
439
+ command.autoinstall = !(command.autoinstall === false || process.env.CI);
440
+ } else {
441
+ nodeEnv = process.env.NODE_ENV || 'development';
442
+ }
443
+
444
+ // Set process.env.NODE_ENV to a default if undefined so that it is
445
+ // available in JS configs and plugins.
446
+ process.env.NODE_ENV = nodeEnv;
447
+
448
+ let https = !!command.https;
449
+ if (command.cert && command.key) {
450
+ https = {
451
+ cert: command.cert,
452
+ key: command.key,
453
+ };
454
+ }
455
+
456
+ let serveOptions = false;
457
+ let {host} = command;
458
+
459
+ // Ensure port is valid and available
460
+ let port = parsePort(command.port || '1234');
461
+ let originalPort = port;
462
+ if (command.name() === 'serve' || command.hmr) {
463
+ try {
464
+ port = await getPort({port, host});
465
+ } catch (err) {
466
+ throw new ThrowableDiagnostic({
467
+ diagnostic: {
468
+ message: `Could not get available port: ${err.message}`,
469
+ origin: 'atlaspack',
470
+ stack: err.stack,
471
+ },
472
+ });
473
+ }
474
+
475
+ if (port !== originalPort) {
476
+ let errorMessage = `Port "${originalPort}" could not be used`;
477
+ if (command.port != null) {
478
+ // Throw the error if the user defined a custom port
479
+ throw new Error(errorMessage);
480
+ } else {
481
+ // Atlaspack logger is not set up at this point, so just use native INTERNAL_ORIGINAL_CONSOLE
482
+ INTERNAL_ORIGINAL_CONSOLE.warn(errorMessage);
483
+ }
484
+ }
485
+ }
486
+
487
+ if (command.name() === 'serve') {
488
+ let {publicUrl} = command;
489
+
490
+ serveOptions = {
491
+ https,
492
+ port,
493
+ host,
494
+ publicUrl,
495
+ };
496
+ }
497
+
498
+ let hmrOptions = null;
499
+ if (command.name() !== 'build' && command.hmr !== false) {
500
+ let hmrport = command.hmrPort ? parsePort(command.hmrPort) : port;
501
+ let hmrhost = command.hmrHost ? command.hmrHost : host;
502
+
503
+ hmrOptions = {
504
+ port: hmrport,
505
+ host: hmrhost,
506
+ };
507
+ }
508
+
509
+ if (command.detailedReport === true) {
510
+ command.detailedReport = '10';
511
+ }
512
+
513
+ let additionalReporters = [
514
+ {packageName: '@atlaspack/reporter-cli', resolveFrom: __filename},
515
+ ...(command.reporter: Array<string>).map(packageName => ({
516
+ packageName,
517
+ resolveFrom: path.join(inputFS.cwd(), 'index'),
518
+ })),
519
+ ];
520
+
521
+ if (command.trace) {
522
+ additionalReporters.unshift({
523
+ packageName: '@atlaspack/reporter-tracer',
524
+ resolveFrom: __filename,
525
+ });
526
+ }
527
+
528
+ let mode = command.name() === 'build' ? 'production' : 'development';
529
+
530
+ const normalizeIncludeExcludeList = (input?: string): string[] => {
531
+ if (typeof input !== 'string') return [];
532
+ return input.split(',').map(value => value.trim());
533
+ };
534
+
535
+ return {
536
+ shouldDisableCache: command.cache === false,
537
+ cacheDir: command.cacheDir,
538
+ watchDir: command.watchDir,
539
+ watchBackend: command.watchBackend,
540
+ watchIgnore: command.watchIgnore,
541
+ config: command.config,
542
+ mode,
543
+ hmrOptions,
544
+ shouldContentHash: hmrOptions ? false : command.contentHash,
545
+ serveOptions,
546
+ targets: command.target.length > 0 ? command.target : null,
547
+ shouldAutoInstall: command.autoinstall ?? true,
548
+ logLevel: command.logLevel,
549
+ shouldProfile: command.profile,
550
+ shouldTrace: command.trace,
551
+ shouldBuildLazily: typeof command.lazy !== 'undefined',
552
+ lazyIncludes: normalizeIncludeExcludeList(command.lazy),
553
+ lazyExcludes: normalizeIncludeExcludeList(command.lazyExclude),
554
+ shouldBundleIncrementally:
555
+ process.env.ATLASPACK_INCREMENTAL_BUNDLING === 'false' ? false : true,
556
+ detailedReport:
557
+ command.detailedReport != null
558
+ ? {
559
+ assetsPerBundle: parseInt(command.detailedReport, 10),
560
+ }
561
+ : null,
562
+ env: {
563
+ NODE_ENV: nodeEnv,
564
+ },
565
+ additionalReporters,
566
+ defaultTargetOptions: {
567
+ shouldOptimize:
568
+ command.optimize != null ? command.optimize : mode === 'production',
569
+ sourceMaps: command.sourceMaps ?? true,
570
+ shouldScopeHoist: command.scopeHoist,
571
+ publicUrl: command.publicUrl,
572
+ distDir: command.distDir,
573
+ },
574
+ featureFlags: command.featureFlag,
575
+ };
576
+ }