@atlaspack/cli 2.12.1-dev.3478 → 2.12.1-dev.3520

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.
@@ -0,0 +1,220 @@
1
+ // @flow strict-local
2
+
3
+ import ThrowableDiagnostic from '@atlaspack/diagnostic';
4
+ import commander from 'commander';
5
+ import getPort from 'get-port';
6
+ import type {FileSystem} from '@atlaspack/fs';
7
+ import type {FeatureFlags} from '@atlaspack/feature-flags';
8
+ import type {InitialAtlaspackOptions, LogLevel} from '@atlaspack/types';
9
+ import {INTERNAL_ORIGINAL_CONSOLE} from '@atlaspack/logger';
10
+ import path from 'path';
11
+
12
+ function parsePort(portValue: string): number {
13
+ let parsedPort = Number(portValue);
14
+
15
+ // Throw an error if port value is invalid...
16
+ if (!Number.isInteger(parsedPort)) {
17
+ throw new Error(`Port ${portValue} is not a valid integer.`);
18
+ }
19
+
20
+ return parsedPort;
21
+ }
22
+
23
+ export interface Options {
24
+ production?: boolean;
25
+ autoinstall?: boolean;
26
+ https?: boolean;
27
+ cert?: string;
28
+ key?: string;
29
+ host: string;
30
+ port?: string;
31
+ hmr?: boolean;
32
+ hmrPort?: string;
33
+ hmrHost?: string;
34
+ publicUrl?: string;
35
+ detailedReport?: boolean | string;
36
+ reporter: string[];
37
+ trace?: boolean;
38
+ cache?: boolean;
39
+ cacheDir?: string;
40
+ watchDir?: string;
41
+ watchBackend?:
42
+ | 'watchman'
43
+ | 'fs-events'
44
+ | 'inotify'
45
+ | 'brute-force'
46
+ | 'windows';
47
+ watchIgnore?: string[];
48
+ config?: string;
49
+ logLevel?: LogLevel;
50
+ profile?: boolean;
51
+ contentHash?: boolean;
52
+ featureFlag?: $Partial<FeatureFlags>;
53
+ optimize?: boolean;
54
+ sourceMaps?: boolean;
55
+ scopeHoist?: boolean;
56
+ distDir?: string;
57
+ lazy?: string;
58
+ lazyExclude?: string;
59
+ target: string[];
60
+ }
61
+
62
+ // $FlowFixMe
63
+ export interface CommandExt extends commander.Command, Options {}
64
+
65
+ // $FlowFixMe
66
+ function shouldUseProductionDefaults(command: CommandExt) {
67
+ return command.name() === 'build' || command.production === true;
68
+ }
69
+
70
+ export async function normalizeOptions(
71
+ command: CommandExt,
72
+ inputFS: FileSystem,
73
+ ): Promise<InitialAtlaspackOptions> {
74
+ let nodeEnv;
75
+ if (shouldUseProductionDefaults(command)) {
76
+ nodeEnv = process.env.NODE_ENV ?? 'production';
77
+ // Autoinstall unless explicitly disabled or we detect a CI environment.
78
+ command.autoinstall = !(command.autoinstall === false || process.env.CI);
79
+ } else {
80
+ nodeEnv = process.env.NODE_ENV ?? 'development';
81
+ }
82
+
83
+ // Set process.env.NODE_ENV to a default if undefined so that it is
84
+ // available in JS configs and plugins.
85
+ process.env.NODE_ENV = nodeEnv;
86
+
87
+ let https = !!command.https;
88
+ if (command.cert != null && command.key != null) {
89
+ https = {
90
+ cert: command.cert,
91
+ key: command.key,
92
+ };
93
+ }
94
+
95
+ let serveOptions = false;
96
+ let {host} = command;
97
+
98
+ // Ensure port is valid and available
99
+ let port = parsePort(command.port != null ? String(command.port) : '1234');
100
+ let originalPort = port;
101
+ if (
102
+ !shouldUseProductionDefaults(command) &&
103
+ (command.name() === 'serve' || Boolean(command.hmr))
104
+ ) {
105
+ try {
106
+ port = await getPort({port, host});
107
+ } catch (err) {
108
+ throw new ThrowableDiagnostic({
109
+ diagnostic: {
110
+ message: `Could not get available port: ${err.message}`,
111
+ origin: 'atlaspack',
112
+ stack: err.stack,
113
+ },
114
+ });
115
+ }
116
+
117
+ if (port !== originalPort) {
118
+ let errorMessage = `Port "${originalPort}" could not be used`;
119
+ if (command.port != null) {
120
+ // Throw the error if the user defined a custom port
121
+ throw new Error(errorMessage);
122
+ } else {
123
+ // Atlaspack logger is not set up at this point, so just use native INTERNAL_ORIGINAL_CONSOLE
124
+ INTERNAL_ORIGINAL_CONSOLE.warn(errorMessage);
125
+ }
126
+ }
127
+ }
128
+
129
+ if (command.name() === 'serve') {
130
+ let {publicUrl} = command;
131
+
132
+ serveOptions = {
133
+ https,
134
+ port,
135
+ host,
136
+ publicUrl,
137
+ };
138
+ }
139
+
140
+ let hmrOptions = null;
141
+ if (!shouldUseProductionDefaults(command) && command.hmr !== false) {
142
+ let hmrport = command.hmrPort != null ? parsePort(command.hmrPort) : port;
143
+ let hmrhost = command.hmrHost != null ? String(command.hmrHost) : host;
144
+
145
+ hmrOptions = {
146
+ port: hmrport,
147
+ host: hmrhost,
148
+ };
149
+ }
150
+
151
+ if (command.detailedReport === true) {
152
+ command.detailedReport = '10';
153
+ }
154
+
155
+ let additionalReporters = [
156
+ {packageName: '@atlaspack/reporter-cli', resolveFrom: __filename},
157
+ ...(command.reporter: Array<string>).map((packageName) => ({
158
+ packageName,
159
+ resolveFrom: path.join(inputFS.cwd(), 'index'),
160
+ })),
161
+ ];
162
+
163
+ if (command.trace) {
164
+ additionalReporters.unshift({
165
+ packageName: '@atlaspack/reporter-tracer',
166
+ resolveFrom: __filename,
167
+ });
168
+ }
169
+
170
+ let mode = shouldUseProductionDefaults(command)
171
+ ? 'production'
172
+ : 'development';
173
+
174
+ const normalizeIncludeExcludeList = (input?: string): string[] => {
175
+ if (typeof input !== 'string') return [];
176
+ return input.split(',').map((value) => value.trim());
177
+ };
178
+
179
+ return {
180
+ shouldDisableCache: command.cache === false,
181
+ cacheDir: command.cacheDir,
182
+ watchDir: command.watchDir,
183
+ watchBackend: command.watchBackend,
184
+ watchIgnore: command.watchIgnore,
185
+ config: command.config,
186
+ mode,
187
+ hmrOptions,
188
+ shouldContentHash: hmrOptions ? false : command.contentHash,
189
+ serveOptions,
190
+ targets: command.target.length > 0 ? command.target : null,
191
+ shouldAutoInstall: command.autoinstall ?? true,
192
+ logLevel: command.logLevel,
193
+ shouldProfile: command.profile,
194
+ shouldTrace: command.trace,
195
+ shouldBuildLazily: typeof command.lazy !== 'undefined',
196
+ lazyIncludes: normalizeIncludeExcludeList(command.lazy),
197
+ lazyExcludes: normalizeIncludeExcludeList(command.lazyExclude),
198
+ shouldBundleIncrementally:
199
+ process.env.ATLASPACK_INCREMENTAL_BUNDLING === 'false' ? false : true,
200
+ detailedReport:
201
+ command.detailedReport != null
202
+ ? {
203
+ assetsPerBundle: parseInt(command.detailedReport, 10),
204
+ }
205
+ : null,
206
+ env: {
207
+ NODE_ENV: nodeEnv,
208
+ },
209
+ additionalReporters,
210
+ defaultTargetOptions: {
211
+ shouldOptimize:
212
+ command.optimize != null ? command.optimize : mode === 'production',
213
+ sourceMaps: command.sourceMaps ?? true,
214
+ shouldScopeHoist: command.scopeHoist,
215
+ publicUrl: command.publicUrl,
216
+ distDir: command.distDir,
217
+ },
218
+ featureFlags: command.featureFlag,
219
+ };
220
+ }
package/src/options.js ADDED
@@ -0,0 +1,123 @@
1
+ // @flow strict-local
2
+
3
+ import {INTERNAL_ORIGINAL_CONSOLE} from '@atlaspack/logger';
4
+ import commander from 'commander';
5
+ import {DEFAULT_FEATURE_FLAGS} from '@atlaspack/feature-flags';
6
+ import type {OptionsDefinition} from './applyOptions';
7
+
8
+ // Only display choices available to callers OS
9
+ export let watcherBackendChoices: string[] = ['brute-force'];
10
+ switch (process.platform) {
11
+ case 'darwin': {
12
+ watcherBackendChoices.push('watchman', 'fs-events');
13
+ break;
14
+ }
15
+ case 'linux': {
16
+ watcherBackendChoices.push('watchman', 'inotify');
17
+ break;
18
+ }
19
+ case 'win32': {
20
+ watcherBackendChoices.push('watchman', 'windows');
21
+ break;
22
+ }
23
+ case 'freebsd' || 'openbsd': {
24
+ watcherBackendChoices.push('watchman');
25
+ break;
26
+ }
27
+ default:
28
+ break;
29
+ }
30
+
31
+ // --no-cache, --cache-dir, --no-source-maps, --no-autoinstall, --global?, --public-url, --log-level
32
+ // --no-content-hash, --experimental-scope-hoisting, --detailed-report
33
+ export const commonOptions: OptionsDefinition = {
34
+ '--no-cache': 'disable the filesystem cache',
35
+ '--config <path>':
36
+ 'specify which config to use. can be a path or a package name',
37
+ '--cache-dir <path>': 'set the cache directory. defaults to ".parcel-cache"',
38
+ '--watch-dir <path>':
39
+ 'set the root watch directory. defaults to nearest lockfile or source control dir.',
40
+ '--watch-ignore [path]': [
41
+ `list of directories watcher should not be tracking for changes. defaults to ['.git', '.hg']`,
42
+ (dirs: string): string[] => dirs.split(','),
43
+ ],
44
+ '--watch-backend': new commander.Option(
45
+ '--watch-backend <name>',
46
+ 'set watcher backend',
47
+ ).choices(watcherBackendChoices),
48
+ '--no-source-maps': 'disable sourcemaps',
49
+ '--target [name]': [
50
+ 'only build given target(s)',
51
+ (val, list) => list.concat([val]),
52
+ [],
53
+ ],
54
+ '--log-level <level>': new commander.Option(
55
+ '--log-level <level>',
56
+ 'set the log level',
57
+ ).choices(['none', 'error', 'warn', 'info', 'verbose']),
58
+ '--dist-dir <dir>':
59
+ 'output directory to write to when unspecified by targets',
60
+ '--no-autoinstall': 'disable autoinstall',
61
+ '--profile': 'enable sampling build profiling',
62
+ '--trace': 'enable build tracing',
63
+ '-V, --version': 'output the version number',
64
+ '--detailed-report [count]': [
65
+ 'print the asset timings and sizes in the build report',
66
+ parseOptionInt,
67
+ ],
68
+ '--reporter <name>': [
69
+ 'additional reporters to run',
70
+ (val, acc) => {
71
+ acc.push(val);
72
+ return acc;
73
+ },
74
+ [],
75
+ ],
76
+ '--feature-flag <name=value>': [
77
+ 'sets the value of a feature flag',
78
+ (value, previousValue) => {
79
+ let [name, val] = value.split('=');
80
+ if (name in DEFAULT_FEATURE_FLAGS) {
81
+ let featureFlagValue;
82
+ if (typeof DEFAULT_FEATURE_FLAGS[name] === 'boolean') {
83
+ if (val !== 'true' && val !== 'false') {
84
+ throw new Error(
85
+ `Feature flag ${name} must be set to true or false`,
86
+ );
87
+ }
88
+ featureFlagValue = val === 'true';
89
+ }
90
+ previousValue[name] = featureFlagValue ?? String(val);
91
+ } else {
92
+ INTERNAL_ORIGINAL_CONSOLE.warn(
93
+ `Unknown feature flag ${name} specified, it will be ignored`,
94
+ );
95
+ }
96
+ return previousValue;
97
+ },
98
+ {},
99
+ ],
100
+ };
101
+
102
+ export const hmrOptions: OptionsDefinition = {
103
+ '--no-hmr': 'disable hot module replacement',
104
+ '-p, --port <port>': [
105
+ 'set the port to serve on. defaults to $PORT or 1234',
106
+ process.env.PORT,
107
+ ],
108
+ '--host <host>':
109
+ 'set the host to listen on, defaults to listening on all interfaces',
110
+ '--https': 'serves files over HTTPS',
111
+ '--cert <path>': 'path to certificate to use with HTTPS',
112
+ '--key <path>': 'path to private key to use with HTTPS',
113
+ '--hmr-port <port>': ['hot module replacement port', process.env.HMR_PORT],
114
+ '--hmr-host <host>': ['hot module replacement host', process.env.HMR_HOST],
115
+ };
116
+
117
+ function parseOptionInt(value: string): number {
118
+ const parsedValue = parseInt(value, 10);
119
+ if (isNaN(parsedValue)) {
120
+ throw new commander.InvalidOptionArgumentError('Must be an integer.');
121
+ }
122
+ return parsedValue;
123
+ }