This repository has been archived by the owner on Jan 13, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathproducer.ts
547 lines (483 loc) · 14.3 KB
/
producer.ts
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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
import { createBrotliCompress, createGzip } from 'zlib';
import Multistream from 'multistream';
import assert from 'assert';
import { execFileSync } from 'child_process';
import fs from 'fs-extra';
import intoStream from 'into-stream';
import path from 'path';
import streamMeter from 'stream-meter';
import { Readable } from 'stream';
import { STORE_BLOB, STORE_CONTENT, isDotNODE, snapshotify } from './common';
import { log, wasReported } from './log';
import { fabricateTwice } from './fabricator';
import { platform, SymLinks, Target } from './types';
import { Stripe } from './packer';
import { CompressType } from './compress_type';
interface NotFound {
notFound: true;
}
interface Placeholder {
position: number;
size: number;
padder: string;
}
type PlaceholderTypes =
| 'BAKERY'
| 'PAYLOAD_POSITION'
| 'PAYLOAD_SIZE'
| 'PRELUDE_POSITION'
| 'PRELUDE_SIZE';
type PlaceholderMap = Record<PlaceholderTypes, Placeholder | NotFound>;
function discoverPlaceholder(
binaryBuffer: Buffer,
searchString: string,
padder: string
): Placeholder | NotFound {
const placeholder = Buffer.from(searchString);
const position = binaryBuffer.indexOf(placeholder);
if (position === -1) {
return { notFound: true };
}
return { position, size: placeholder.length, padder };
}
function injectPlaceholder(
fd: number,
placeholder: Placeholder | NotFound,
value: string | number | Buffer,
cb: (
err: NodeJS.ErrnoException | null,
written: number,
buffer: Buffer
) => void
) {
if ('notFound' in placeholder) {
assert(false, 'Placeholder for not found');
}
const { position, size, padder } = placeholder;
let stringValue: Buffer = Buffer.from('');
if (typeof value === 'number') {
stringValue = Buffer.from(value.toString());
} else if (typeof value === 'string') {
stringValue = Buffer.from(value);
} else {
stringValue = value;
}
const padding = Buffer.from(padder.repeat(size - stringValue.length));
stringValue = Buffer.concat([stringValue, padding]);
fs.write(fd, stringValue, 0, stringValue.length, position, cb);
}
function discoverPlaceholders(binaryBuffer: Buffer) {
return {
BAKERY: discoverPlaceholder(
binaryBuffer,
`\0${'// BAKERY '.repeat(20)}`,
'\0'
),
PAYLOAD_POSITION: discoverPlaceholder(
binaryBuffer,
'// PAYLOAD_POSITION //',
' '
),
PAYLOAD_SIZE: discoverPlaceholder(binaryBuffer, '// PAYLOAD_SIZE //', ' '),
PRELUDE_POSITION: discoverPlaceholder(
binaryBuffer,
'// PRELUDE_POSITION //',
' '
),
PRELUDE_SIZE: discoverPlaceholder(binaryBuffer, '// PRELUDE_SIZE //', ' '),
};
}
function injectPlaceholders(
fd: number,
placeholders: PlaceholderMap,
values: Record<PlaceholderTypes, number | string | Buffer>,
cb: (error?: Error | null) => void
) {
injectPlaceholder(fd, placeholders.BAKERY, values.BAKERY, (error) => {
if (error) {
return cb(error);
}
injectPlaceholder(
fd,
placeholders.PAYLOAD_POSITION,
values.PAYLOAD_POSITION,
(error2) => {
if (error2) {
return cb(error2);
}
injectPlaceholder(
fd,
placeholders.PAYLOAD_SIZE,
values.PAYLOAD_SIZE,
(error3) => {
if (error3) {
return cb(error3);
}
injectPlaceholder(
fd,
placeholders.PRELUDE_POSITION,
values.PRELUDE_POSITION,
(error4) => {
if (error4) {
return cb(error4);
}
injectPlaceholder(
fd,
placeholders.PRELUDE_SIZE,
values.PRELUDE_SIZE,
cb
);
}
);
}
);
}
);
});
}
function makeBakeryValueFromBakes(bakes: string[]) {
const parts = [];
if (bakes.length) {
for (let i = 0; i < bakes.length; i += 1) {
parts.push(Buffer.from(bakes[i]));
parts.push(Buffer.alloc(1));
}
parts.push(Buffer.alloc(1));
}
return Buffer.concat(parts);
}
function replaceDollarWise(s: string, sf: string, st: string) {
return s.replace(sf, () => st);
}
function makePreludeBufferFromPrelude(prelude: string) {
return Buffer.from(
`(function(process, require, console, EXECPATH_FD, PAYLOAD_POSITION, PAYLOAD_SIZE) { ${prelude}\n})` // dont remove \n
);
}
function findPackageJson(nodeFile: string) {
let dir = nodeFile;
while (dir !== '/') {
dir = path.dirname(dir);
if (fs.existsSync(path.join(dir, 'package.json'))) {
break;
}
}
if (dir === '/') {
throw new Error(`package.json not found for "${nodeFile}"`);
}
return dir;
}
function nativePrebuildInstall(target: Target, nodeFile: string) {
const prebuildInstall = path.join(
__dirname,
'../node_modules/.bin/prebuild-install'
);
const dir = findPackageJson(nodeFile);
// parse the target node version from the binaryPath
const nodeVersion = path.basename(target.binaryPath).split('-')[1];
if (!/^v[0-9]+\.[0-9]+\.[0-9]+$/.test(nodeVersion)) {
throw new Error(`Couldn't find node version, instead got: ${nodeVersion}`);
}
const nativeFile = `${nodeFile}.${target.platform}.${nodeVersion}`;
if (fs.existsSync(nativeFile)) {
return nativeFile;
}
// prebuild-install will overwrite the target .node file, so take a backup
if (!fs.existsSync(`${nodeFile}.bak`)) {
fs.copyFileSync(nodeFile, `${nodeFile}.bak`);
}
// run prebuild
execFileSync(
prebuildInstall,
[
'--target',
nodeVersion,
'--platform',
platform[target.platform],
'--arch',
target.arch,
],
{ cwd: dir }
);
// move the prebuild to a new name with a platform/version extension
fs.copyFileSync(nodeFile, nativeFile);
// put the backed up file back
fs.moveSync(`${nodeFile}.bak`, nodeFile, { overwrite: true });
return nativeFile;
}
interface ProducerOptions {
backpack: { entrypoint: string; stripes: Stripe[]; prelude: string };
bakes: string[];
slash: string;
target: Target;
symLinks: SymLinks;
doCompress: CompressType;
nativeBuild: boolean;
}
/**
* instead of creating a vfs dicionnary with actual path as key
* we use a compression mechanism that can reduce significantly
* the memory footprint of the vfs in the code.
*
* without vfs compression:
*
* vfs = {
* "/folder1/folder2/file1.js": {};
* "/folder1/folder2/folder3/file2.js": {};
* "/folder1/folder2/folder3/file3.js": {};
* }
*
* with compression :
*
* fileDictionary = {
* "folder1": "1",
* "folder2": "2",
* "file1": "3",
* "folder3": "4",
* "file2": "5",
* "file3": "6",
* }
* vfs = {
* "/1/2/3": {};
* "/1/2/4/5": {};
* "/1/2/4/6": {};
* }
*
* note: the key is computed in base36 for further compression.
*/
const fileDictionary: { [key: string]: string } = {};
let counter = 0;
function getOrCreateHash(fileOrFolderName: string) {
let existingKey = fileDictionary[fileOrFolderName];
if (!existingKey) {
const newkey = counter;
counter += 1;
existingKey = newkey.toString(36);
fileDictionary[fileOrFolderName] = existingKey;
}
return existingKey;
}
const separator = '/';
function makeKey(
doCompression: CompressType,
fullpath: string,
slash: string
): string {
if (doCompression === CompressType.None) return fullpath;
return fullpath.split(slash).map(getOrCreateHash).join(separator);
}
export default function producer({
backpack,
bakes,
slash,
target,
symLinks,
doCompress,
nativeBuild,
}: ProducerOptions) {
return new Promise<void>((resolve, reject) => {
if (!Buffer.alloc) {
throw wasReported(
'Your node.js does not have Buffer.alloc. Please upgrade!'
);
}
const { prelude } = backpack;
let { entrypoint, stripes } = backpack;
entrypoint = snapshotify(entrypoint, slash);
stripes = stripes.slice();
const vfs: Record<string, Record<string, [number, number]>> = {};
for (const stripe of stripes) {
let { snap } = stripe;
snap = snapshotify(snap, slash);
const vfsKey = makeKey(doCompress, snap, slash);
if (!vfs[vfsKey]) vfs[vfsKey] = {};
}
const snapshotSymLinks: SymLinks = {};
for (const [key, value] of Object.entries(symLinks)) {
const k = snapshotify(key, slash);
const v = snapshotify(value, slash);
const vfsKey = makeKey(doCompress, k, slash);
snapshotSymLinks[vfsKey] = makeKey(doCompress, v, slash);
}
let meter: streamMeter.StreamMeter;
let count = 0;
function pipeToNewMeter(s: Readable) {
meter = streamMeter();
return s.pipe(meter);
}
function pipeMayCompressToNewMeter(s: Readable): streamMeter.StreamMeter {
if (doCompress === CompressType.GZip) {
return pipeToNewMeter(s.pipe(createGzip()));
}
if (doCompress === CompressType.Brotli) {
return pipeToNewMeter(s.pipe(createBrotliCompress()));
}
return pipeToNewMeter(s);
}
function next(s: Readable) {
count += 1;
return pipeToNewMeter(s);
}
const binaryBuffer = fs.readFileSync(target.binaryPath);
const placeholders = discoverPlaceholders(binaryBuffer);
let track = 0;
let prevStripe: Stripe;
let payloadPosition: number;
let payloadSize: number;
let preludePosition: number;
let preludeSize: number;
new Multistream((cb) => {
if (count === 0) {
return cb(null, next(intoStream(binaryBuffer)));
}
if (count === 1) {
payloadPosition = meter.bytes;
return cb(null, next(intoStream(Buffer.alloc(0))));
}
if (count === 2) {
if (prevStripe && !prevStripe.skip) {
const { store } = prevStripe;
let { snap } = prevStripe;
snap = snapshotify(snap, slash);
const vfsKey = makeKey(doCompress, snap, slash);
vfs[vfsKey][store] = [track, meter.bytes];
track += meter.bytes;
}
if (stripes.length) {
// clone to prevent 'skip' propagate
// to other targets, since same stripe
// is used for several targets
const stripe = { ...(stripes.shift() as Stripe) };
prevStripe = stripe;
if (stripe.buffer) {
if (stripe.store === STORE_BLOB) {
const snap = snapshotify(stripe.snap, slash);
return fabricateTwice(
bakes,
target.fabricator,
snap,
stripe.buffer,
(error, buffer) => {
if (error) {
log.warn(error.message);
stripe.skip = true;
return cb(null, intoStream(Buffer.alloc(0)));
}
cb(
null,
pipeMayCompressToNewMeter(
intoStream(buffer || Buffer.from(''))
)
);
}
);
}
return cb(
null,
pipeMayCompressToNewMeter(intoStream(stripe.buffer))
);
}
if (stripe.file) {
if (stripe.file === target.output) {
return cb(
wasReported(
'Trying to take executable into executable',
stripe.file
),
null
);
}
assert.strictEqual(stripe.store, STORE_CONTENT); // others must be buffers from walker
if (isDotNODE(stripe.file) && nativeBuild) {
try {
const platformFile = nativePrebuildInstall(target, stripe.file);
if (fs.existsSync(platformFile)) {
return cb(
null,
pipeMayCompressToNewMeter(fs.createReadStream(platformFile))
);
}
} catch (err) {
log.debug(
`prebuild-install failed[${stripe.file}]:`,
(err as Error).message
);
}
}
return cb(
null,
pipeMayCompressToNewMeter(fs.createReadStream(stripe.file))
);
}
assert(false, 'producer: bad stripe');
} else {
payloadSize = track;
preludePosition = payloadPosition + payloadSize;
return cb(
null,
next(
intoStream(
makePreludeBufferFromPrelude(
replaceDollarWise(
replaceDollarWise(
replaceDollarWise(
replaceDollarWise(
replaceDollarWise(
prelude,
'%VIRTUAL_FILESYSTEM%',
JSON.stringify(vfs)
),
'%DEFAULT_ENTRYPOINT%',
JSON.stringify(entrypoint)
),
'%SYMLINKS%',
JSON.stringify(snapshotSymLinks)
),
'%DICT%',
JSON.stringify(fileDictionary)
),
'%DOCOMPRESS%',
JSON.stringify(doCompress)
)
)
)
)
);
}
} else {
return cb(null, null);
}
})
.on('error', (error) => {
reject(error);
})
.pipe(fs.createWriteStream(target.output))
.on('error', (error) => {
reject(error);
})
.on('close', () => {
preludeSize = meter.bytes;
fs.open(target.output, 'r+', (error, fd) => {
if (error) return reject(error);
injectPlaceholders(
fd,
placeholders,
{
BAKERY: makeBakeryValueFromBakes(bakes),
PAYLOAD_POSITION: payloadPosition,
PAYLOAD_SIZE: payloadSize,
PRELUDE_POSITION: preludePosition,
PRELUDE_SIZE: preludeSize,
},
(error2) => {
if (error2) return reject(error2);
fs.close(fd, (error3) => {
if (error3) return reject(error3);
resolve();
});
}
);
});
});
});
}