/
cli.js
executable file
·383 lines (342 loc) · 11.8 KB
/
cli.js
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
379
380
381
382
383
#!/usr/bin/env node
const { resolve, relative, dirname, sep } = require("path");
const glob = require("glob");
const shebangRegEx = require("./utils/shebang");
const rimraf = require("rimraf");
const crypto = require("crypto");
const { writeFileSync, unlink, existsSync, symlinkSync } = require("fs");
const { hasTypeModule } = require('./utils/has-type-module');
const mkdirp = require("mkdirp");
const { version: nccVersion } = require('../package.json');
// License and TypeScript plugins have Webpack deprecation warnings
// we don't want these on when running as a CLI utility
process.noDeprecation = true;
const usage = `Usage: ncc <cmd> <opts>
Commands:
build <input-file> [opts]
run <input-file> [opts]
cache clean|dir|size
help
version
Options:
-o, --out [file] Output directory for build (defaults to dist)
-m, --minify Minify output
-C, --no-cache Skip build cache population
-s, --source-map Generate source map
--no-source-map-register Skip source-map-register source map support
-e, --external [mod] Skip bundling 'mod'. Can be used many times
-q, --quiet Disable build summaries / non-error outputs
-w, --watch Start a watched build
-t, --transpile-only Use transpileOnly option with the ts-loader
--v8-cache Emit a build using the v8 compile cache
--license [file] Adds a file containing licensing information to the output
--stats-out [file] Emit webpack stats as json to the specified output file
--target [es] ECMAScript target to use for output (default: es2015)
Learn more: https://webpack.js.org/configuration/target
`;
// support an API mode for CLI testing
let api = false;
if (require.main === module) {
runCmd(process.argv.slice(2), process.stdout, process.stderr)
.then((watching) => {
if (!watching)
process.exit();
})
.catch(e => {
if (!e.silent)
console.error(e.nccError ? e.message : e);
process.exit(e.exitCode || 1);
});
}
else {
module.exports = runCmd;
api = true;
}
function renderSummary(code, map, assets, ext, outDir, buildTime) {
if (outDir && !outDir.endsWith(sep)) outDir += sep;
const codeSize = Math.round(Buffer.byteLength(code, "utf8") / 1024);
const mapSize = map ? Math.round(Buffer.byteLength(map, "utf8") / 1024) : 0;
const assetSizes = Object.create(null);
let totalSize = codeSize;
let maxAssetNameLength = 8 + (map ? 4 : 0); // length of index.js(.map)?
for (const asset of Object.keys(assets)) {
const assetSource = assets[asset].source;
const assetSize = Math.round(
(assetSource.byteLength || Buffer.byteLength(assetSource, "utf8")) / 1024
);
assetSizes[asset] = assetSize;
totalSize += assetSize;
if (asset.length > maxAssetNameLength) maxAssetNameLength = asset.length;
}
const orderedAssets = Object.keys(assets).sort((a, b) =>
assetSizes[a] > assetSizes[b] ? 1 : -1
);
const sizePadding = totalSize.toString().length;
let indexRender = `${codeSize
.toString()
.padStart(sizePadding, " ")}kB ${outDir}index${ext}`;
let indexMapRender = map ? `${mapSize
.toString()
.padStart(sizePadding, " ")}kB ${outDir}index${ext}.map` : '';
let output = "",
first = true;
for (const asset of orderedAssets) {
if (first) first = false;
else output += "\n";
if (codeSize < assetSizes[asset] && indexRender) {
output += indexRender + "\n";
indexRender = null;
}
if (mapSize && mapSize < assetSizes[asset] && indexMapRender) {
output += indexMapRender + "\n";
indexMapRender = null;
}
output += `${assetSizes[asset]
.toString()
.padStart(sizePadding, " ")}kB ${outDir}${asset}`;
}
if (indexRender) {
output += (first ? "" : "\n") + indexRender;
first = false;
}
if (indexMapRender) output += (first ? "" : "\n") + indexMapRender;
output += `\n${totalSize}kB [${buildTime}ms] - ncc ${nccVersion}`;
return output;
}
function nccError(msg, exitCode = 1) {
const err = new Error(msg);
err.nccError = true;
err.exitCode = exitCode;
throw err;
}
async function runCmd (argv, stdout, stderr) {
let args;
try {
args = require("arg")({
"--debug": Boolean,
"-d": "--debug",
"--external": [String],
"-e": "--external",
"--out": String,
"-o": "--out",
"--minify": Boolean,
"-m": "--minify",
"--source-map": Boolean,
"-s": "--source-map",
"--no-cache": Boolean,
"-C": "--no-cache",
"--no-asset-builds": Boolean,
"--no-source-map-register": Boolean,
"--quiet": Boolean,
"-q": "--quiet",
"--watch": Boolean,
"-w": "--watch",
"--v8-cache": Boolean,
"--transpile-only": Boolean,
"-t": "--transpile-only",
"--license": String,
"--stats-out": String,
"--target": String
}, {
permissive: false,
argv
});
} catch (e) {
if (e.message.indexOf("Unknown or unexpected option") === -1) throw e;
nccError(e.message + `\n${usage}`, 2);
}
if (args._.length === 0)
nccError(`Error: No command specified\n${usage}`, 2);
let run = false;
let outDir = args["--out"];
const quiet = args["--quiet"];
const statsOutFile = args["--stats-out"];
switch (args._[0]) {
case "cache":
if (args._.length > 2)
errTooManyArguments("cache");
const flags = Object.keys(args).filter(arg => arg.startsWith("--"));
if (flags.length)
errFlagNotCompatible(flags[0], "cache");
const cacheDir = require("./utils/ncc-cache-dir");
switch (args._[1]) {
case "clean":
rimraf.sync(cacheDir);
break;
case "dir":
stdout.write(cacheDir + '\n');
break;
case "size":
require("get-folder-size")(cacheDir, (err, size) => {
if (err) {
if (err.code === 'ENOENT') {
stdout.write("0MB\n");
return;
}
throw err;
}
stdout.write(`${(size / 1024 / 1024).toFixed(2)}MB\n`);
});
break;
default:
errInvalidCommand("cache " + args._[1]);
}
break;
case "run":
if (args._.length > 2)
errTooManyArguments("run");
if (args["--out"])
errFlagNotCompatible("--out", "run");
if (args["--watch"])
errFlagNotCompatible("--watch", "run");
outDir = resolve(
require("os").tmpdir(),
crypto.createHash('md5').update(resolve(args._[1] || ".")).digest('hex')
);
if (existsSync(outDir))
rimraf.sync(outDir);
mkdirp.sync(outDir);
run = true;
// fallthrough
case "build":
if (args._.length > 2)
errTooManyArguments("build");
let startTime = Date.now();
let ps;
const buildFile = eval("require.resolve")(resolve(args._[1] || "."));
const esm = buildFile.endsWith('.mjs') || !buildFile.endsWith('.cjs') && hasTypeModule(buildFile);
const ext = buildFile.endsWith('.cjs') ? '.cjs' : esm && (buildFile.endsWith('.mjs') || !hasTypeModule(buildFile)) ? '.mjs' : '.js';
const ncc = require("./index.js")(
buildFile,
{
debugLog: args["--debug"],
minify: args["--minify"],
externals: args["--external"],
sourceMap: args["--source-map"] || run,
sourceMapRegister: args["--no-source-map-register"] ? false : undefined,
noAssetBuilds: args["--no-asset-builds"] ? true : false,
cache: args["--no-cache"] ? false : undefined,
watch: args["--watch"],
v8cache: args["--v8-cache"],
transpileOnly: args["--transpile-only"],
license: args["--license"],
quiet,
target: args["--target"]
}
);
async function handler ({ err, code, map, assets, symlinks, stats }) {
// handle watch errors
if (err) {
stderr.write(err + '\n');
stdout.write('Watching for changes...\n');
return;
}
outDir = outDir || resolve(eval("'dist'"));
mkdirp.sync(outDir);
// remove all existing ".js" and ".cjs" files in the out directory
await Promise.all(
(await new Promise((resolve, reject) =>
glob(outDir + '/**/*.(js|cjs)', (err, files) => err ? reject(err) : resolve(files))
)).map(file =>
new Promise((resolve, reject) => unlink(file, err => err ? reject(err) : resolve())
))
);
writeFileSync(`${outDir}/index${ext}`, code, { mode: code.match(shebangRegEx) ? 0o777 : 0o666 });
if (map) writeFileSync(`${outDir}/index${ext}.map`, map);
for (const asset of Object.keys(assets)) {
const assetPath = outDir + "/" + asset;
mkdirp.sync(dirname(assetPath));
writeFileSync(assetPath, assets[asset].source, { mode: assets[asset].permissions });
}
for (const symlink of Object.keys(symlinks)) {
const symlinkPath = outDir + "/" + symlink;
symlinkSync(symlinks[symlink], symlinkPath);
}
if (!quiet) {
stdout.write(
renderSummary(
code,
map,
assets,
ext,
run ? "" : relative(process.cwd(), outDir),
Date.now() - startTime,
) + '\n'
);
if (args["--watch"])
stdout.write('Watching for changes...\n');
}
if (statsOutFile)
writeFileSync(statsOutFile, JSON.stringify(stats.toJson()));
if (run) {
// find node_modules
const root = resolve('/node_modules');
let nodeModulesDir = dirname(buildFile) + "/node_modules";
do {
if (nodeModulesDir === root) {
nodeModulesDir = undefined;
break;
}
if (existsSync(nodeModulesDir))
break;
} while (nodeModulesDir = resolve(nodeModulesDir, "../../node_modules"));
if (nodeModulesDir)
symlinkSync(nodeModulesDir, outDir + "/node_modules", "junction");
ps = require("child_process").fork(`${outDir}/index${ext}`, {
stdio: api ? 'pipe' : 'inherit'
});
if (api) {
ps.stdout.pipe(stdout);
ps.stderr.pipe(stderr);
}
return new Promise((resolve, reject) => {
function exit (code) {
require("rimraf").sync(outDir);
if (code === 0)
resolve();
else
reject({ silent: true, exitCode: code });
process.off("SIGTERM", exit);
process.off("SIGINT", exit);
}
ps.on("exit", exit);
process.on("SIGTERM", exit);
process.on("SIGINT", exit);
});
}
}
if (args["--watch"]) {
ncc.handler(handler);
ncc.rebuild(() => {
if (ps)
ps.kill();
startTime = Date.now();
stdout.write('File change, rebuilding...\n');
});
return true;
} else {
return ncc.then(handler);
}
break;
case "help":
nccError(usage, 2);
case "version":
stdout.write(require("../package.json").version + '\n');
break;
default:
errInvalidCommand(args._[0], 2);
}
function errTooManyArguments (cmd) {
nccError(`Error: Too many ${cmd} arguments provided\n${usage}`, 2);
}
function errFlagNotCompatible (flag, cmd) {
nccError(`Error: ${flag} flag is not compatible with ncc ${cmd}\n${usage}`, 2);
}
function errInvalidCommand (cmd) {
nccError(`Error: Invalid command "${cmd}"\n${usage}`, 2);
}
// remove me when node.js makes this the default behavior
process.on("unhandledRejection", e => {
throw e;
});
}