parcel 2.16.4 → 3.0.0-alpha.2

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