Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor install script #114

Merged
merged 38 commits into from
Oct 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
ae2a3ed
build(node): bump latest to `v20.8.0`
ayushmanchhabra Sep 29, 2023
4e4a642
refactor: sort imports
ayushmanchhabra Sep 29, 2023
bec0756
docs: add license
ayushmanchhabra Sep 30, 2023
914c7b5
docs: remove duplicate license
ayushmanchhabra Sep 30, 2023
84b76cb
refactor: install script
ayushmanchhabra Sep 30, 2023
11ce6d5
build(dependabot): batch updates
ayushmanchhabra Sep 30, 2023
e423a77
build: convert to esm
ayushmanchhabra Sep 30, 2023
27334e7
chore: move under `/lib` dir
ayushmanchhabra Oct 3, 2023
a8de567
build(npm): remove `engines` property since we get the latest Node ve…
ayushmanchhabra Oct 3, 2023
dbf112e
Convert double quotes to single quotes
TheJaredWilcurt Oct 5, 2023
53e31b0
refactor: use optional chaining for prerelease check
ayushmanchhabra Oct 5, 2023
bf92233
fix: exit on incompatible version/(platform/arch)
ayushmanchhabra Oct 5, 2023
c8b4cab
chore: remove additional `console.log` function
ayushmanchhabra Oct 5, 2023
ed681cd
refactor: use `Array.prototype.join` instead of `$` operator
ayushmanchhabra Oct 5, 2023
72ae57a
refactor: use `Array.prototype.join` instead of `$` operator
ayushmanchhabra Oct 6, 2023
67d2e39
chore: revert out of scope change
ayushmanchhabra Oct 6, 2023
566d755
fix: decompress binary from file path
ayushmanchhabra Oct 6, 2023
cc467f8
fix(npm): update lock file
ayushmanchhabra Oct 6, 2023
f103f4a
fix: use `join()`
ayushmanchhabra Oct 6, 2023
6bdf09d
fix: fail if file path is invalid
ayushmanchhabra Oct 6, 2023
2c97298
build(npm): remove `packageManager` property
ayushmanchhabra Oct 6, 2023
e51cf7b
refactor: make impl DRY and improve naming
ayushmanchhabra Oct 6, 2023
f775d13
Merge branch 'refactor/install' of github.com:ayushmanchhabra/nw-npm …
ayushmanchhabra Oct 6, 2023
cdc38ee
fix: out of scope function
ayushmanchhabra Oct 6, 2023
cd38c64
fix: async await call
ayushmanchhabra Oct 6, 2023
e39dd23
fix: out of scope function
ayushmanchhabra Oct 6, 2023
35d15af
fix: await
ayushmanchhabra Oct 6, 2023
1ab0406
fix: use correct dirs
ayushmanchhabra Oct 6, 2023
d759d38
fix
ayushmanchhabra Oct 6, 2023
1f55f3f
refactor: use `String.prototype.endsWith`
ayushmanchhabra Oct 7, 2023
0e9505c
refactor: use `String.prototype.endsWith`
ayushmanchhabra Oct 7, 2023
93b7bbd
refactor: use `!` operator
ayushmanchhabra Oct 7, 2023
dcae229
docs: indent JSDoc comments
ayushmanchhabra Oct 7, 2023
20a0f22
refactor: use `String.prototype.endsWith`
ayushmanchhabra Oct 7, 2023
7c0213f
refactor: use `String.prototype.endsWith`
ayushmanchhabra Oct 7, 2023
b9a6794
fix: destructure and append prelease array to versionString
ayushmanchhabra Oct 7, 2023
bb2178d
refactor: decompression calls
ayushmanchhabra Oct 7, 2023
f033872
docs: improve function description
ayushmanchhabra Oct 7, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
204 changes: 204 additions & 0 deletions lib/install.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
import { createWriteStream, existsSync } from 'node:fs';
import { rename, rm } from 'node:fs/promises';
import { get } from 'node:https';
import { dirname, resolve } from 'node:path';
import { arch, env, platform, exit } from 'node:process';
import { fileURLToPath, URL } from 'node:url';

import compressing from 'compressing';
import progress from 'cli-progress';
import semver from 'semver';

import nodeManifest from '../package.json' assert { type: 'json' };

/**
* NW.js build flavor
*
* @type {'sdk' | 'normal'}
*/
let buildType = env.npm_config_nwjs_build_type || env.NWJS_BUILD_TYPE || 'normal';

/**
* Parsed string version to Semver version object
*/
let parsedVersion = semver.parse(nodeManifest.version);

/**
* Version string of the format `X.Y.Z-pre`.
* The prerelease segment `pre` is used to specify build flavor, or other tags.
*
* @type {string}
*/
let versionString = [
parsedVersion.major,
parsedVersion.minor,
parsedVersion.patch
].join('.');

// Check if version is a prelease.
if (typeof parsedVersion?.prerelease?.[0] === 'string') {
let prerelease = parsedVersion.prerelease[0].split('-');
if (prerelease.length > 1) {
prerelease = prerelease.slice(0, -1);
}
versionString = [versionString, ...prerelease].join('-');
}

// Check build flavor and slice that off the `versionString`.
if (versionString.endsWith('-sdk')) {
versionString = versionString.slice(0, -4);
buildType = 'sdk';
} else if (versionString.endsWith('sdk')) {
versionString = versionString.slice(0, -3);
buildType = 'sdk';
}

/**
* URL to download or get binaries from.
*
* @type {string}
*/
let url = '';

/**
* Host operating system
*
* @type {NodeJS.Platform | 'osx' | 'win'}
*/
let hostOs = env.npm_config_nwjs_platform || env.NWJS_PLATFORM || platform;

/**
* Host architecture
*
* @type {NodeJS.Architecture}
*/
let hostArch = env.npm_config_nwjs_process_arch || arch;

/**
* URL base prepended to `url`.
*
* @type {string}
*/
let urlBase = env.npm_config_nwjs_urlbase || env.NWJS_URLBASE || 'https://dl.nwjs.io/v';

const PLATFORM_KV = {
darwin: 'osx',
linux: 'linux',
win32: 'win',
};

const ARCH_KV = {
x64: 'x64',
ia32: 'ia32',
arm64: 'arm64',
};

url = [
urlBase,
versionString,
'/nwjs',
buildType === 'normal' ? '' : `-${buildType}`,
'-v',
versionString,
'-',
PLATFORM_KV[hostOs],
'-',
ARCH_KV[hostArch],
PLATFORM_KV[hostOs] === 'linux' ? '.tar.gz' : '.zip'
].join('');

if (!PLATFORM_KV[hostOs] || !ARCH_KV[hostArch]) {
console.error('[ ERROR ] Could not find a compatible version of nw.js to download for your platform.');
exit(1);
}

const __dirname = dirname(fileURLToPath(import.meta.url));

/**
* The folder where NW.js binaries are placed.
*
* @type {string}
*/
let nwDir = resolve(__dirname, '..', 'nwjs');

if (existsSync(nwDir) === true) {
exit(0);
}

let parsedUrl = new URL(url);

/**
* Path to the compressed binary.
*
* @type {string}
*/
let filePath = '';

/**
* Recursively delete the passed in directory.
* Rename the downloaded file.
* @param {string} dir - directory to remove
*/
const rmAndRename = async (dir) => {
await rm(dir, { recursive: true, force: true });
await rename(`nwjs-v${versionString}-${PLATFORM_KV[hostOs]}-${ARCH_KV[hostArch]}`, 'nwjs');
};

/**
* @param {'zip' | 'tgz'} zipOrTgz
* @param {string} filePath
* @return {Promise<void>}
*/
const decompress = function (zipOrTgz, filePath) {
return compressing[zipOrTgz].uncompress(filePath, '.')
.then(async () => await rmAndRename(filePath));
}

// If the url is linking to the file system,
// then it is assumed that a compressed binary exists in that location.
if (parsedUrl.protocol === 'file:') {
filePath = resolve(decodeURIComponent(url.slice('file://'.length)));

if (existsSync(filePath) === false) {
ayushmanchhabra marked this conversation as resolved.
Show resolved Hide resolved
console.error('[ ERROR ] Could not find ' + filePath);
}

// If the compressed file is of ZIP format:
if (filePath.endsWith('.zip')) {
decompress('zip', filePath);
// If the compressed file is of TGZ format:
} else if (filePath.endsWith('.tar.gz')) {
decompress('tgz', filePath);
} else {
console.error(`[ ERROR ] Expected .zip or .tar.gz file format. Got ${filePath}`);
exit(1);
}

} else {

const bar = new progress.SingleBar({}, progress.Presets.rect);

const stream = createWriteStream(nwDir);

get(url, (response) => {

let chunks = 0;
bar.start(Number(response.headers['content-length']), 0);
response.on('data', async (chunk) => {
chunks += chunk.length;
bar.increment();
bar.update(chunks);
});

response.on('error', async () => await rm(nwDir, { force: true }));

response.on('end', () => {
if (PLATFORM_KV[hostOs] === 'linux') {
decompress('tgz', nwDir);
} else {
decompress('zip', nwDir);
}
});
response.pipe(stream);
});
}
Loading