2020-07-11 08:02:43 -04:00
|
|
|
const fs = require('fs');
|
|
|
|
const https = require('https');
|
|
|
|
const path = require('path');
|
2020-07-12 02:17:43 -04:00
|
|
|
const zlib = require('zlib');
|
2020-07-11 08:02:43 -04:00
|
|
|
const pkg = require('./package.json');
|
|
|
|
|
|
|
|
const MAX_DOWNLOAD_ATTEMPTS = 4;
|
|
|
|
|
2020-07-24 02:08:14 -04:00
|
|
|
const binaryName = [process.platform, process.arch].join('__');
|
2020-07-22 07:52:54 -04:00
|
|
|
const binaryPath = path.join(__dirname, 'index.node');
|
2020-07-11 08:02:43 -04:00
|
|
|
|
|
|
|
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
|
|
|
|
|
|
class StatusError extends Error {
|
|
|
|
constructor (status) {
|
|
|
|
super(`Bad status of ${status}`);
|
|
|
|
this.status = status;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const fetch = url => new Promise((resolve, reject) => {
|
|
|
|
const stream = https.get(url, resp => {
|
|
|
|
if (!resp.statusCode || resp.statusCode < 200 || resp.statusCode > 299) {
|
|
|
|
return reject(new StatusError(resp.statusCode));
|
|
|
|
}
|
|
|
|
const parts = [];
|
|
|
|
resp.on('data', chunk => parts.push(chunk));
|
|
|
|
resp.on('end', () => resolve(Buffer.concat(parts)));
|
|
|
|
});
|
|
|
|
stream.on('error', reject);
|
|
|
|
});
|
|
|
|
|
|
|
|
const downloadNativeBinary = async () => {
|
|
|
|
for (let attempt = 0; ; attempt++) {
|
|
|
|
let binary;
|
|
|
|
try {
|
2020-07-12 02:17:43 -04:00
|
|
|
binary = await fetch(`https://wilsonl.in/minify-html/bin/nodejs/${pkg.version}/${binaryName}.node.gz`);
|
2020-07-11 08:02:43 -04:00
|
|
|
} catch (e) {
|
|
|
|
if (e instanceof StatusError && attempt < MAX_DOWNLOAD_ATTEMPTS) {
|
|
|
|
await wait(Math.random() * 2500 + 500);
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
throw e;
|
|
|
|
}
|
|
|
|
|
2020-07-12 02:17:43 -04:00
|
|
|
fs.writeFileSync(binaryPath, zlib.gunzipSync(binary));
|
2020-07-11 08:02:43 -04:00
|
|
|
break;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2020-07-11 09:33:44 -04:00
|
|
|
if (!fs.existsSync(path.join(__dirname, '.no-postinstall')) && !fs.existsSync(binaryPath)) {
|
2020-07-11 08:02:43 -04:00
|
|
|
downloadNativeBinary()
|
|
|
|
.then(
|
|
|
|
() => console.log(`Downloaded ${pkg.name}`),
|
|
|
|
err => {
|
|
|
|
console.error(`Failed to download ${pkg.name}: ${err}`);
|
|
|
|
process.exit(1);
|
|
|
|
},
|
|
|
|
);
|
|
|
|
}
|