forked from vercel/pkg
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
448 lines (368 loc) · 11 KB
/
index.js
File metadata and controls
448 lines (368 loc) · 11 KB
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
/* eslint-disable require-atomic-updates */
import { exists, mkdirp, readFile, remove, stat } from 'fs-extra';
import { log, wasReported } from './log.js';
import { need, system } from 'pkg-fetch';
import assert from 'assert';
import help from './help';
import { isPackageJson } from '../prelude/common.js';
import minimist from 'minimist';
import packer from './packer.js';
import path from 'path';
import { plusx } from './chmod.js';
import producer from './producer.js';
import refine from './refiner.js';
import { shutdown } from './fabricator.js';
import { version } from '../package.json';
import walk from './walker.js';
function isConfiguration (file) {
return isPackageJson(file) || file.endsWith('.config.json');
}
// http://www.openwall.com/lists/musl/2012/12/08/4
const { hostArch, hostPlatform, isValidNodeRange, knownArchs,
knownPlatforms, toFancyArch, toFancyPlatform } = system;
const hostNodeRange = 'node' + process.version.match(/^v(\d+)/)[1];
function parseTargets (items) {
// [ 'node6-macos-x64', 'node6-linux-x64' ]
const targets = [];
for (const item of items) {
const target = {
nodeRange: hostNodeRange,
platform: hostPlatform,
arch: hostArch
};
if (item !== 'host') {
for (const token of item.split('-')) {
if (!token) continue;
if (isValidNodeRange(token)) {
target.nodeRange = token;
continue;
}
const p = toFancyPlatform(token);
if (knownPlatforms.indexOf(p) >= 0) {
target.platform = p;
continue;
}
const a = toFancyArch(token);
if (knownArchs.indexOf(a) >= 0) {
target.arch = a;
continue;
}
throw wasReported(`Unknown token '${token}' in '${item}'`);
}
}
targets.push(target);
}
return targets;
}
function stringifyTarget (target) {
const { nodeRange, platform, arch } = target;
return `${nodeRange}-${platform}-${arch}`;
}
function differentParts (targets) {
const nodeRanges = {};
const platforms = {};
const archs = {};
for (const target of targets) {
nodeRanges[target.nodeRange] = true;
platforms[target.platform] = true;
archs[target.arch] = true;
}
const result = {};
if (Object.keys(nodeRanges).length > 1) {
result.nodeRange = true;
}
if (Object.keys(platforms).length > 1) {
result.platform = true;
}
if (Object.keys(archs).length > 1) {
result.arch = true;
}
return result;
}
function stringifyTargetForOutput (output, target, different) {
const a = [ output ];
if (different.nodeRange) a.push(target.nodeRange);
if (different.platform) a.push(target.platform);
if (different.arch) a.push(target.arch);
return a.join('-');
}
function fabricatorForTarget (target) {
const { nodeRange, arch } = target;
return { nodeRange, platform: hostPlatform, arch };
}
const dryRunResults = {};
async function needWithDryRun (target) {
const target2 = Object.assign({ dryRun: true }, target);
const result = await need(target2);
assert([ 'exists', 'fetched', 'built' ].indexOf(result) >= 0);
dryRunResults[result] = true;
}
const targetsCache = {};
async function needViaCache (target) {
const s = stringifyTarget(target);
let c = targetsCache[s];
if (c) return c;
c = await need(target);
targetsCache[s] = c;
return c;
}
export async function exec (argv2) { // eslint-disable-line complexity
const argv = minimist(argv2, {
boolean: [ 'b', 'build', 'bytecode', 'd', 'debug',
'h', 'help', 'public', 'v', 'version' ],
string: [ '_', 'c', 'config', 'o', 'options', 'output',
'outdir', 'out-dir', 'out-path', 'public-packages',
't', 'target', 'targets' ],
default: { bytecode: true }
});
if (argv.h || argv.help) {
help();
return;
}
// version
if (argv.v || argv.version) {
console.log(version);
return;
}
log.info(`pkg@${version}`);
// debug
log.debugMode = argv.d || argv.debug;
// forceBuild
const forceBuild = argv.b || argv.build;
// _
if (!argv._.length) {
throw wasReported('Entry file/directory is expected', [
'Pass --help to see usage information' ]);
}
if (argv._.length > 1) {
throw wasReported('Not more than one entry file/directory is expected');
}
// input
let input = path.resolve(argv._[0]);
if (!await exists(input)) {
throw wasReported('Input file does not exist', [ input ]);
}
if ((await stat(input)).isDirectory()) {
input = path.join(input, 'package.json');
if (!await exists(input)) {
throw wasReported('Input file does not exist', [ input ]);
}
}
// inputJson
let inputJson, inputJsonName;
if (isConfiguration(input)) {
inputJson = JSON.parse(await readFile(input));
inputJsonName = inputJson.name;
if (inputJsonName) {
inputJsonName = inputJsonName.split('/').pop(); // @org/foo
}
}
// inputBin
let inputBin;
if (inputJson) {
let bin = inputJson.bin;
if (bin) {
if (typeof bin === 'object') {
if (bin[inputJsonName]) {
bin = bin[inputJsonName];
} else {
bin = bin[Object.keys(bin)[0]]; // TODO multiple inputs to pkg them all?
}
}
inputBin = path.resolve(path.dirname(input), bin);
if (!await exists(inputBin)) {
throw wasReported('Bin file does not exist (taken from package.json ' +
'\'bin\' property)', [ inputBin ]);
}
}
}
if (inputJson && !inputBin) {
throw wasReported('Property \'bin\' does not exist in', [ input ]);
}
// inputFin
const inputFin = inputBin || input;
// config
let config = argv.c || argv.config;
if (inputJson && config) {
throw wasReported('Specify either \'package.json\' or config. Not both');
}
// configJson
let configJson;
if (config) {
config = path.resolve(config);
if (!await exists(config)) {
throw wasReported('Config file does not exist', [ config ]);
}
configJson = require(config); // may be either json or js
if (!configJson.name && !configJson.files &&
!configJson.dependencies && !configJson.pkg) { // package.json not detected
configJson = { pkg: configJson };
}
}
// output, outputPath
let output = argv.o || argv.output;
const outputPath = argv['out-path'] || argv.outdir || argv['out-dir'];
let autoOutput = false;
if (output && outputPath) {
throw wasReported('Specify either \'output\' or \'out-path\'. Not both');
}
if (!output) {
let name;
if (inputJson) {
name = inputJsonName;
if (!name) {
throw wasReported('Property \'name\' does not exist in', [ argv._[0] ]);
}
} else
if (configJson) {
name = configJson.name;
}
if (!name) {
name = path.basename(inputFin);
}
autoOutput = true;
const ext = path.extname(name);
output = name.slice(0, -ext.length || undefined);
output = path.resolve(outputPath || '', output);
} else {
output = path.resolve(output);
}
// targets
const sTargets = argv.t || argv.target || argv.targets || '';
if (typeof sTargets !== 'string') {
throw wasReported(`Something is wrong near ${JSON.stringify(sTargets)}`);
}
let targets = parseTargets(
sTargets.split(',').filter((t) => t)
);
if (!targets.length) {
let jsonTargets;
if (inputJson && inputJson.pkg) {
jsonTargets = inputJson.pkg.targets;
} else
if (configJson && configJson.pkg) {
jsonTargets = configJson.pkg.targets;
}
if (jsonTargets) {
targets = parseTargets(jsonTargets);
}
}
if (!targets.length) {
if (!autoOutput) {
targets = parseTargets([ 'host' ]);
assert(targets.length === 1);
} else {
targets = parseTargets([ 'linux', 'macos', 'win' ]);
}
log.info('Targets not specified. Assuming:',
`${targets.map(stringifyTarget).join(', ')}`);
}
// differentParts
const different = differentParts(targets);
// targets[].output
for (const target of targets) {
let file;
if (targets.length === 1) {
file = output;
} else {
file = stringifyTargetForOutput(output, target, different);
}
if (target.platform === 'win' &&
path.extname(file) !== '.exe') file += '.exe';
target.output = file;
}
// bakes
const bakes = (argv.options || '').split(',')
.filter((bake) => bake).map((bake) => '--' + bake);
// check if input is going
// to be overwritten by output
for (const target of targets) {
if (target.output === inputFin) {
if (autoOutput) {
target.output += '-' + target.platform;
} else {
throw wasReported('Refusing to overwrite input file', [ inputFin ]);
}
}
}
// fetch targets
const { bytecode } = argv;
for (const target of targets) {
target.forceBuild = forceBuild;
await needWithDryRun(target);
const f = target.fabricator = fabricatorForTarget(target);
f.forceBuild = forceBuild;
if (bytecode) {
await needWithDryRun(f);
}
}
if (dryRunResults.fetched && !dryRunResults.built) {
log.info('Fetching base Node.js binaries to PKG_CACHE_PATH');
}
for (const target of targets) {
target.binaryPath = await needViaCache(target);
const f = target.fabricator;
if (bytecode) {
f.binaryPath = await needViaCache(f);
if (f.platform !== 'win') {
await plusx(f.binaryPath);
}
}
}
// marker
let marker;
if (configJson) {
marker = {
config: configJson,
base: path.dirname(config),
configPath: config
};
} else {
marker = {
config: inputJson || {}, // not `inputBin` because only `input`
base: path.dirname(input), // is the place for `inputJson`
configPath: input
};
}
marker.toplevel = true;
// public
const params = {};
if (argv.public) {
params.publicToplevel = true;
}
if (argv['public-packages']) {
params.publicPackages = argv['public-packages'].split(',');
if (params.publicPackages.indexOf('*') !== -1) {
params.publicPackages = [ '*' ];
}
}
// records
let records;
let entrypoint = inputFin;
const addition = isConfiguration(input) ? input : undefined;
const walkResult = await walk(marker, entrypoint, addition, params);
entrypoint = walkResult.entrypoint;
records = walkResult.records;
const refineResult = refine(records, entrypoint);
entrypoint = refineResult.entrypoint;
records = refineResult.records;
const backpack = packer({ records, entrypoint, bytecode });
log.debug('Targets:', JSON.stringify(targets, null, 2));
for (const target of targets) {
if (await exists(target.output)) {
if ((await stat(target.output)).isFile()) {
await remove(target.output);
} else {
throw wasReported('Refusing to overwrite non-file output', [ target.output ]);
}
} else {
await mkdirp(path.dirname(target.output));
}
const slash = target.platform === 'win' ? '\\' : '/';
await producer({ backpack, bakes, slash, target });
if (target.platform !== 'win') {
await plusx(target.output);
}
}
shutdown();
}