Compare commits

...

23 Commits

Author SHA1 Message Date
calebboyd 9f22309949 feat: add asset flag for using cached artifact 2021-01-26 07:16:29 -06:00
calebboyd cf8e6ff393 fix: got upload searchParams 2021-01-05 12:47:29 -06:00
calebboyd 7275d4b848 fix: update dependencies 2021-01-03 17:00:24 -06:00
calebboyd 06a8242114 fix: resolve resources relative to passed cwd
closes #645
2021-01-03 16:25:52 -06:00
calebboyd 2935ee3f93 fix: add lstat patch 2021-01-03 15:29:55 -06:00
calebboyd 9f1f323b09 build: audit fix 2020-12-16 15:08:08 -06:00
bruce-one 0ba696e976 fix: support for 12.19.1. (#835) 2020-11-21 16:20:38 -06:00
bruce-one 0f0869b292 fix: internal module read json changes 12.18.3 (#803) 2020-09-24 10:13:22 -05:00
calebboyd c5dabbf9b4 build: audit fix 2020-07-21 08:59:59 -05:00
calebboyd e51b6b21a6 fix: set filesize for resource files 2020-07-10 07:12:14 -05:00
calebboyd 2b261728b4 feat: deterministic builds 2020-07-09 10:21:14 -05:00
Caleb Boyd 017abb94cc docs: add funding.yml 2020-07-01 10:33:33 -05:00
calebboyd 32033b6d15 fix: bring idepotent builds back 2020-06-27 06:46:13 -05:00
calebboyd bc1d579baa build: add more space for msbuild 2020-06-24 20:17:30 -05:00
calebboyd 6ffd47f1f1 chore: update macos build version 2020-06-24 09:55:56 -05:00
calebboyd c4e16fb6e0 chore: bump globby and fix ci node version 2020-06-24 09:52:27 -05:00
calebboyd ea6f1f0808 fix: update legacy v3 tag while v4 is beta 2020-06-22 14:59:44 -05:00
calebboyd c1055149ab chore: bump resolve dependnencies 2020-06-20 12:15:13 -05:00
calebboyd 79fffc358a chore: update resolve-dependencies 2020-06-20 08:39:39 -05:00
Bryce Gibson c8cf13a9dd Move nexe boot to support 12.18.0. 2020-06-04 07:43:26 -05:00
Aral Balkan 928b8134a7 fix: remove full stop from one line of help output for consistency 2020-05-08 17:42:03 -05:00
Aral Balkan 0a2e8dba00 fix: replace --asset option with --remote option (#760) 2020-05-08 17:42:03 -05:00
Aral Balkan 01c977bb3c feat: alternate nexe base binary remotes (--remote option) (#760) 2020-05-08 17:42:03 -05:00
20 changed files with 713 additions and 593 deletions
+1
View File
@@ -0,0 +1 @@
custom: https://www.paypal.me/calebsboyd
+6 -18
View File
@@ -49,7 +49,7 @@ Additional files or resources can be added to the binary by passing `-r "glob/pa
## Compiling Node
By default `nexe` will attempt to download a pre-built executable. These are listed on the [Nexe V3 releases page](https://github.com/nexe/nexe/releases/tag/v3.0.0). The exact version you want may be unavailable or you may want to customize what is built. See `nexe --help` for a list of options available when passing the [`--build`](#build-boolean) option. You will also need to ensure your environment is setup to [build node](https://github.com/nodejs/node/blob/master/BUILDING.md). Note: the `python` binary in your path should be an acceptable version of python 2. eg. Systems that have python2 will need to create a [symlink](https://github.com/nexe/nexe/issues/354#issuecomment-319874486).
By default `nexe` will attempt to download a pre-built executable. These are listed on the [Nexe V3 releases page](https://github.com/nexe/nexe/releases/tag/v3.3.3). The exact version you want may be unavailable or you may want to customize what is built. See `nexe --help` for a list of options available when passing the [`--build`](#build-boolean) option. You will also need to ensure your environment is setup to [build node](https://github.com/nodejs/node/blob/master/BUILDING.md). Note: the `python` binary in your path should be an acceptable version of python 2. eg. Systems that have python2 will need to create a [symlink](https://github.com/nexe/nexe/issues/354#issuecomment-319874486).
## Node.js API
@@ -116,8 +116,8 @@ compile({
- default: true
- #### `build: boolean`
- Build node from source, passing this flag tells nexe to download and build from source. Subsequently using this flag will cause nexe to use the previously built binary. To rebuild, first add [`--clean`](#clean-boolean)
- #### `asset: string`
- Provide a pre-built nexe binary asset, this can either be an http or https URL or a file path.
- #### `remote: string`
- Provide a custom remote location for fetching pre-built nexe binaries from. This can either be an HTTP or HTTPS URL or a file path.
- default: `null`
- #### `python: string`
- On Linux this is the path pointing to your python2 executable
@@ -202,7 +202,7 @@ For examples, see the built in patches: [src/patches](src/patches).
- Quickly perform a replace in a file within the downloaded Node.js source. The rest arguments are passed along to `String.prototype.replace`
- `readFileAsync(filename: string): Promise<NexeFile>`
- Access (or create) a file within the downloaded Node.js source.
- `addResource(filename: string, contents: Buffer): void`
- `addResource(filename: string, contents: Buffer): Promise<void>`
- Add a resource to the nexe bundle
- `files: NexeFile[]`
- The cache of the currently read, modified, or created files within the downloaded Node.js source.
@@ -216,9 +216,7 @@ Any modifications made to `NexeFile#contents` will be maintained in the cache _w
## Native Modules
TODO
- [ ] Implement support for `node-pre-gyp#find`.
In order to use native modules, the native binaries must be shipped alongside the binary generated by nexe.
## Contributing
@@ -226,20 +224,10 @@ Building
```
$ git clone git@github.com:nexe/nexe.git
$ cd nexe
$ yarn
$ npm i && npm run build
```
Testing
```
$ npm test
```
## Maintainers
[![Jared Allard](https://avatars.githubusercontent.com/u/2391349?s=130)](https://jaredallard.me/) | [![Caleb Boyd](https://avatars.githubusercontent.com/u/5818726?s=130)](https://github.com/calebboyd) | [![Dustin Greif](https://avatars.githubusercontent.com/u/3026298?s=130)](https://github.com/dgreif) |
---|---|---|
[Jared Allard](https://github.com/jaredallard) | [Caleb Boyd](http://github.com/calebboyd) | [Dustin Greif](https://github.com/dgreif) |
### Former
- [Craig Condon](http://crcn.codes/)
+3 -2
View File
@@ -25,7 +25,7 @@ jobs:
linux:
imageName: 'ubuntu-16.04'
mac:
imageName: 'macos-10.13'
imageName: 'macos-10.15'
windows_2017:
imageName: 'vs2017-win2016'
windows_2015:
@@ -43,7 +43,7 @@ jobs:
- task: NodeTool@0
displayName: Install Node
inputs:
versionSpec: '10.x'
versionSpec: '12.x'
- script: sudo apt-get update && sudo apt-get install -y libc6-dev-i386 gcc-multilib g++-multilib
condition: contains(variables['Agent.JobName'], 'linux')
displayName: Install Linux build dependencies
@@ -55,6 +55,7 @@ jobs:
env:
GITHUB_TOKEN: $(PersonalGithubToken)
NEXE_VERBOSE: $(NEXE_VERBOSE)
msbuild_args: /3G
condition: not(contains(variables['Agent.JobName'], 'windows'))
- powershell: |
iex (new-object net.webclient).downloadstring('https://get.scoop.sh')
+386 -400
View File
File diff suppressed because it is too large Load Diff
+21 -22
View File
@@ -2,7 +2,7 @@
"name": "nexe",
"description": "Create a single executable out of your Node.js application",
"license": "MIT",
"version": "4.0.0-beta.6",
"version": "4.0.0-beta.17",
"contributors": [
"Craig Condon <craig.j.condon@gmail.com> (http://crcn.io)",
"Jared Allard <jaredallard@outlook.com>",
@@ -30,7 +30,7 @@
"nexe": "index.js"
},
"engines": {
"node": ">=6"
"node": ">=10"
},
"dependencies": {
"@calebboyd/semaphore": "^1.3.1",
@@ -38,35 +38,34 @@
"caw": "^2.0.1",
"chalk": "^2.4.2",
"cherow": "1.6.9",
"download": "^7.1.0",
"globby": "^10.0.1",
"got": "^9.6.0",
"download": "^8.0.0",
"globby": "^11.0.1",
"got": "^11.8.1",
"minimist": "^1.2.5",
"mkdirp": "^1.0.4",
"multistream": "^4.0.0",
"multistream": "^4.0.1",
"ora": "^3.4.0",
"pify": "^4.0.1",
"resolve-dependencies": "^4.0.0",
"rimraf": "^3.0.0"
"pify": "^5.0.0",
"resolve-dependencies": "^6.0.4",
"rimraf": "^3.0.2"
},
"devDependencies": {
"@types/chai": "^4.2.11",
"@types/download": "^6.2.4",
"@types/execa": "^2.0.0",
"@types/globby": "^9.1.0",
"@types/got": "^9.6.10",
"@types/minimist": "^1.2.0",
"@types/mkdirp": "^1.0.0",
"@types/mocha": "^7.0.2",
"@types/chai": "^4",
"@types/download": "^6",
"@types/globby": "^9",
"@types/got": "^9.6.11",
"@types/minimist": "^1.2.1",
"@types/mkdirp": "^1.0.1",
"@types/mocha": "^7",
"@types/multistream": "^2.1.1",
"@types/ora": "^3.2.0",
"@types/pify": "3.0.2",
"@types/pify": "5.0.0",
"@types/rimraf": "3.0.0",
"@types/semver": "^7.1.0",
"@types/semver": "^7.3.4",
"chai": "^4.2.0",
"execa": "^4.0.0",
"mocha": "^7.1.1",
"prettier": "^2.0.5",
"execa": "^5.0.0",
"mocha": "^7",
"prettier": "^2.2.1",
"ts-node": "^8.9.0",
"tslint": "^6.1.1",
"tslint-config-prettier": "^1.18.0",
+21 -28
View File
@@ -12,11 +12,13 @@ import {
isWindows,
bound,
semverGt,
wrap,
} from './util'
import { NexeOptions, version } from './options'
import { NexeTarget } from './target'
import MultiStream = require('multistream')
import { Bundle, toStream } from './fs/bundle'
import { File } from 'resolve-dependencies'
const isBsd = Boolean(~process.platform.indexOf('bsd'))
const make = isWindows ? 'vcbuild.bat' : isBsd ? 'gmake' : 'make'
@@ -27,7 +29,7 @@ type StringReplacer = (match: string) => string
export interface NexeFile {
filename: string
absPath: string
contents: string
contents: string | Buffer
}
export { NexeOptions }
@@ -108,12 +110,12 @@ export class NexeCompiler {
//SOMEDAY iterate over multiple targets with `--outDir`
this.targets = options.targets as NexeTarget[]
this.target = this.targets[0]
if (options.asset && options.asset.startsWith('http')) {
this.remoteAsset = options.asset
} else {
this.remoteAsset =
'https://github.com/nexe/nexe/releases/download/v3.0.0/' + this.target.toString()
if (!/https?\:\/\//.test(options.remote)) {
throw new NexeError(
`Invalid remote URI scheme (must be http, https, or file): ${options.remote}`
)
}
this.remoteAsset = options.remote + this.target.toString()
this.src = join(this.options.temp, this.target.version)
this.configureScript = configure + (semverGt(this.target.version, '10.10.0') ? '.py' : '')
this.nodeSrcBinPath = isWindows
@@ -136,18 +138,10 @@ export class NexeCompiler {
}
@bound
addResource(absoluteFileName: string, content?: Buffer | string) {
addResource(absoluteFileName: string, content?: Buffer | string | File) {
return this.bundle.addResource(absoluteFileName, content)
}
get binaryConfiguration() {
return { resources: this.bundle.index }
}
get resourceSize() {
return this.bundle.blobSize
}
@bound
async readFileAsync(file: string) {
this.assertBuild()
@@ -176,11 +170,11 @@ export class NexeCompiler {
@bound
async replaceInFileAsync(file: string, replace: string | RegExp, value: string | StringReplacer) {
const entry = await this.readFileAsync(file)
entry.contents = entry.contents.replace(replace, value as any)
entry.contents = entry.contents.toString().replace(replace, value as any)
}
@bound
async setFileContentsAsync(file: string, contents: string) {
async setFileContentsAsync(file: string, contents: string | Buffer) {
const entry = await this.readFileAsync(file)
entry.contents = contents
}
@@ -198,7 +192,7 @@ export class NexeCompiler {
}
public getNodeExecutableLocation(target?: NexeTarget) {
if (this.options.asset && !this.options.asset.startsWith('http')) {
if (this.options.asset) {
return resolve(this.options.cwd, this.options.asset)
}
if (target) {
@@ -261,10 +255,7 @@ export class NexeCompiler {
return createReadStream(this.getNodeExecutableLocation())
}
private async _shouldCompileBinaryAsync(
binary: NodeJS.ReadableStream | null,
location: string | undefined
) {
private async _shouldCompileBinaryAsync(binary: NodeJS.ReadableStream | null, location: string) {
//SOMEDAY combine make/configure/vcBuild/and modified times of included files
const { snapshot, build } = this.options
@@ -298,20 +289,22 @@ export class NexeCompiler {
return [this.shims.join(''), this.startup].join(';')
}
private _assembleDeliverable(binary: NodeJS.ReadableStream) {
private async _assembleDeliverable(binary: NodeJS.ReadableStream) {
if (!this.options.mangle) {
return binary
}
const resources = this.bundle.renderIndex()
this.shims.unshift(wrap(`process.__nexe = ${JSON.stringify({ resources })};\n`))
const startup = this.code(),
codeSize = Buffer.byteLength(startup)
const code = this.code(),
codeSize = Buffer.byteLength(code),
lengths = Buffer.from(Array(16))
const lengths = Buffer.from(Array(16))
lengths.writeDoubleLE(codeSize, 0)
lengths.writeDoubleLE(this.bundle.blobSize, 8)
lengths.writeDoubleLE(this.bundle.size, 8)
return new (MultiStream as any)([
binary,
toStream(startup),
toStream(code),
this.bundle.toStream(),
toStream(Buffer.concat([Buffer.from('<nexe~~sentinel>'), lengths])),
])
+122 -39
View File
@@ -1,18 +1,26 @@
import { stat as getStat, Stats, createReadStream } from 'fs'
import * as fs from 'fs'
import { promisify } from 'util'
import { relative } from 'path'
import { Readable } from 'stream'
import { argv } from '../options'
import { File } from 'resolve-dependencies'
import MultiStream = require('multistream')
const stat = (file: string): Promise<Stats> => {
return new Promise((resolve, reject) => {
getStat(file, (err, stats) => (err ? reject(err) : resolve(stats)))
})
}
const lstat = promisify(fs.lstat),
realpath = promisify(fs.realpath),
createReadStream = fs.createReadStream,
stat = promisify(fs.stat)
export type MultiStreams = (Readable | (() => Readable))[]
function makeRelative(cwd: string, path: string) {
return './' + relative(cwd, path)
}
function sortEntry(a: [string, File], b: [string, File]) {
return a[0] > b[0] ? 1 : -1
}
export function toStream(content: Buffer | string) {
const readable = new Readable({
read() {
@@ -23,51 +31,126 @@ export function toStream(content: Buffer | string) {
return readable
}
export type File = { absPath: string; contents: string; deps: FileMap }
export type FileMap = { [absPath: string]: File | null }
export interface BundleOptions {
entries: string[]
cwd: string
expand: boolean
loadContent: boolean
files: FileMap
async function createFile(absoluteFileName: string) {
const stats = await lstat(absoluteFileName),
file: File = {
size: stats.size,
contents: '',
absPath: absoluteFileName,
deps: {},
}
if (stats.isSymbolicLink()) {
file.size = stats.size
const [realPath, realStat] = await Promise.all([
realpath(absoluteFileName),
stat(absoluteFileName),
])
file.realPath = realPath
file.realSize = realStat.size
}
return file
}
export class Bundle {
size = 0
cwd: string
rendered = false
private offset = 0
private index: { [key: string]: [number, number] } = {}
private files: { [key: string]: File } = {}
streams: MultiStreams = []
constructor({ cwd }: { cwd: string } = { cwd: process.cwd() }) {
this.cwd = cwd
}
cwd: string
blobSize: number = 0
index: { [relativeFilePath: string]: [number, number] } = {}
streams: (Readable | (() => Readable))[] = []
async addResource(absoluteFileName: string, content?: Buffer | string) {
let length = 0
if (content !== undefined) {
length = Buffer.byteLength(content)
} else {
const stats = await stat(absoluteFileName)
length = stats.size
}
const start = this.blobSize
this.blobSize += length
this.index[makeRelative(this.cwd, absoluteFileName)] = [start, length]
this.streams.push(() => (content ? toStream(content) : createReadStream(absoluteFileName)))
get list() {
return Object.keys(this.files)
}
concat() {
throw new Error('Not Implemented')
public async addResource(
absoluteFileName: string,
content?: File | Buffer | string
): Promise<number> {
if (this.files[absoluteFileName]) {
return this.size
}
if (typeof content === 'string' || Buffer.isBuffer(content)) {
this.files[absoluteFileName] = {
size: Buffer.byteLength(content),
contents: content as any, //todo type is wrong here... should allow buffer
deps: {},
absPath: absoluteFileName,
}
} else if (content) {
this.files[content.absPath] = content
} else {
this.files[absoluteFileName] = {
absPath: absoluteFileName,
contents: '',
deps: {},
size: 0,
}
this.files[absoluteFileName] = await createFile(absoluteFileName)
}
return (this.size += this.files[absoluteFileName].size)
}
/**
* De-dupe files by absolute path, partition by symlink/real
* Iterate over real, add entries
* Iterate over symlinks, add symlinks
*/
renderIndex() {
if (this.rendered) {
throw new Error('Bundle index already rendered')
}
const files = Object.entries(this.files),
realFiles: [string, File][] = [],
symLinks: [string, File][] = []
for (const entry of files) {
if (entry[1].realPath) {
symLinks.push(entry)
} else {
realFiles.push(entry)
}
}
realFiles.sort(sortEntry)
symLinks.sort(sortEntry)
for (const [absPath, file] of realFiles) {
this.addEntry(absPath, file)
}
for (const [absPath, file] of symLinks) {
this.addEntry(file.realPath as string, file)
this.addEntry(absPath, file, file.realPath)
}
this.rendered = true
return this.index
}
/**
* Add a stream if needed and an entry with the required offset and size
* Ensure the calling order of this method is idempotent (eg, while iterating a sorted set)
* @param entryPath
* @param file
* @param useEntry
*/
addEntry(entryPath: string, file: File, useEntry?: string) {
const existingName = useEntry && makeRelative(this.cwd, useEntry),
name = makeRelative(this.cwd, entryPath),
size = file.realSize ?? file.size,
existingEntry = this.index[existingName ?? name]
this.index[name] = existingEntry || [this.offset, size]
if (!existingEntry) {
this.streams.push(() =>
file.contents ? toStream(file.contents) : createReadStream(file.absPath)
)
this.offset += size
}
}
toStream() {
return new (MultiStream as any)(this.streams)
}
toJSON() {
return this.index
}
}
+52 -30
View File
@@ -1,4 +1,5 @@
import { Stats } from 'fs'
import { getLatestGitRelease } from '../releases'
export interface NexeBinary {
blobPath: string
@@ -115,6 +116,25 @@ function shimFs(binary: NexeBinary, fs: any = require('fs')) {
}
}
const getStat = function (fn: string) {
return function stat(filepath: string | Buffer, options: any, callback: any) {
let stat: any
if (typeof options === 'function') {
callback = options
stat = ownStat(filepath, null)
} else {
stat = ownStat(filepath, options)
}
if (stat) {
process.nextTick(() => {
callback(null, stat)
})
} else {
return originalFsMethods[fn].apply(fs, arguments)
}
}
}
function makeLong(filepath: string) {
return (path as any)._makeLong && (path as any)._makeLong(filepath)
}
@@ -220,23 +240,26 @@ function shimFs(binary: NexeBinary, fs: any = require('fs')) {
originalFsMethods.open(blobPath, 'r', function (err: Error, fd: number) {
if (err) return callback(err, null)
originalFsMethods.read(fd, Buffer.alloc(length), 0, length, resourceOffset, function (
error: Error,
bytesRead: number,
result: Buffer
) {
if (error) {
return originalFsMethods.close(fd, function () {
callback(error, null)
originalFsMethods.read(
fd,
Buffer.alloc(length),
0,
length,
resourceOffset,
function (error: Error, bytesRead: number, result: Buffer) {
if (error) {
return originalFsMethods.close(fd, function () {
callback(error, null)
})
}
originalFsMethods.close(fd, function (err: Error) {
if (err) {
return callback(err, result)
}
callback(err, encoding ? result.toString(encoding) : result)
})
}
originalFsMethods.close(fd, function (err: Error) {
if (err) {
return callback(err, result)
}
callback(err, encoding ? result.toString(encoding) : result)
})
})
)
})
},
createReadStream: function createReadStream(filepath: any, options: any) {
@@ -279,24 +302,16 @@ function shimFs(binary: NexeBinary, fs: any = require('fs')) {
}
return originalFsMethods.statSync.apply(fs, arguments)
},
stat: function stat(filepath: string | Buffer, options: any, callback: any) {
let stat: any
if (typeof options === 'function') {
callback = options
stat = ownStat(filepath, null)
} else {
stat = ownStat(filepath, options)
}
stat: getStat('stat'),
lstat: getStat('lstat'),
lstatSync: function statSync(filepath: string | Buffer, options: any) {
const stat = ownStat(filepath, options)
if (stat) {
process.nextTick(() => {
callback(null, stat)
})
} else {
return originalFsMethods.stat.apply(fs, arguments)
return stat
}
return originalFsMethods.lstatSync.apply(fs, arguments)
},
}
if (typeof fs.exists === 'function') {
nfs.exists = function (filepath: string, cb: Function) {
cb = cb || noop
@@ -317,7 +332,14 @@ function shimFs(binary: NexeBinary, fs: any = require('fs')) {
log('read (miss) ' + filepath)
return original.call(this, ...args)
}
patches.internalModuleReadJSON = patches.internalModuleReadFile
let returningArray: boolean
patches.internalModuleReadJSON = function (this: any, original: any, ...args: any[]) {
if (returningArray == null) returningArray = Array.isArray(original.call(this, ''))
const res = patches.internalModuleReadFile.call(this, original, ...args)
return returningArray && !Array.isArray(res)
? [res, /"(main|name|type|exports|imports)"/.test(res)]
: res
}
patches.internalModuleStat = function (this: any, original: any, ...args: any[]) {
setupManifest()
const filepath = getKey(args[0])
+9 -3
View File
@@ -21,6 +21,7 @@ export interface NexeOptions {
output: string
targets: (string | NexeTarget)[]
name: string
remote: string
asset: string
cwd: string
fs: boolean | string[]
@@ -71,16 +72,17 @@ const defaults = {
bundle: true,
patches: [],
plugins: [],
remote: 'https://github.com/nexe/nexe/releases/download/v3.3.3/',
}
const alias = {
i: 'input',
o: 'output',
v: 'version',
a: 'asset',
t: 'target',
b: 'build',
n: 'name',
r: 'resource',
a: 'asset',
p: 'python',
f: 'flag',
c: 'configure',
@@ -101,7 +103,7 @@ ${c.bold('nexe <entry-file> [options]')}
-t --target -- node version description
-n --name -- main app module name
-r --resource -- *embed files (glob) within the binary
-a --asset -- alternate asset path, file or url pointing to a base (nexe) binary
--remote -- alternate location (URL) to download pre-built base (nexe) binaries from
--plugin -- extend nexe runtime behavior
${c.underline.bold('Building from source:')}
@@ -112,7 +114,7 @@ ${c.bold('nexe <entry-file> [options]')}
-c --configure -- *arguments to the configure step
-m --make -- *arguments to the make/build step
--patch -- module with middleware default export for adding a build patch
--no-mangle -- used when generating base binaries, or when patching _third_party_main manually.
--no-mangle -- used when generating base binaries, or when patching _third_party_main manually
--snapshot -- path to a warmup snapshot
--ico -- file name for alternate icon file (windows)
--rc-* -- populate rc file options (windows)
@@ -249,6 +251,10 @@ function normalizeOptions(input?: Partial<NexeOptions>): NexeOptions {
options.configure = flatten(options.configure)
options.resources = flatten(opts.resource, options.resources)
if (!options.remote.endsWith('/')) {
options.remote += '/'
}
options.downloadOptions = options.downloadOptions || {}
options.downloadOptions.headers = options.downloadOptions.headers || {}
options.downloadOptions.headers['User-Agent'] = 'nexe (https://www.npmjs.com/package/nexe)'
+6 -5
View File
@@ -12,14 +12,15 @@ export default async function nodeRc(compiler: NexeCompiler, next: () => Promise
let value = options[key]
const isVar = /^[A-Z_]+$/.test(value)
value = isVar ? value : `"${value}"`
file.contents = file.contents.replace(
new RegExp(`VALUE "${key}",.*`),
`VALUE "${key}", ${value}`
)
file.contents = file.contents
.toString()
.replace(new RegExp(`VALUE "${key}",.*`), `VALUE "${key}", ${value}`)
})
;['PRODUCTVERSION', 'FILEVERSION'].forEach((x) => {
if (options[x]) {
file.contents = file.contents.replace(new RegExp(x + ' .*$', 'm'), `${x} ${options[x]}`)
file.contents = file.contents
.toString()
.replace(new RegExp(x + ' .*$', 'm'), `${x} ${options[x]}`)
}
})
+31 -13
View File
@@ -36,7 +36,7 @@ export default async function main(compiler: NexeCompiler, next: () => Promise<v
}
const file = await compiler.readFileAsync(bootFile),
ast = parse(file.contents, {
ast = parse(file.contents.toString(), {
loc: true,
tolerant: true,
next: true,
@@ -54,7 +54,7 @@ export default async function main(compiler: NexeCompiler, next: () => Promise<v
}
})
const fileLines = file.contents.split('\n')
const fileLines = file.contents.toString().split('\n')
fileLines.splice(
location.start.line,
0,
@@ -65,22 +65,40 @@ export default async function main(compiler: NexeCompiler, next: () => Promise<v
file.contents = fileLines.join('\n')
if (semverGt(version, '11.99')) {
await compiler.replaceInFileAsync(
bootFile,
'initializePolicy();',
'initializePolicy();\n' + wrap('{{replace:lib/patches/boot-nexe.js}}')
)
if (semverGt(version, '12.17.99')) {
await compiler.replaceInFileAsync(
bootFile,
'initializeFrozenIntrinsics();',
'initializeFrozenIntrinsics();\n' + wrap('{{replace:lib/patches/boot-nexe.js}}')
)
} else {
await compiler.replaceInFileAsync(
bootFile,
'initializePolicy();',
'initializePolicy();\n' + wrap('{{replace:lib/patches/boot-nexe.js}}')
)
}
await compiler.replaceInFileAsync(
bootFile,
'assert(!CJSLoader.hasLoadedAnyUserCJSModule)',
'/*assert(!CJSLoader.hasLoadedAnyUserCJSModule)*/'
)
await compiler.replaceInFileAsync(
'src/node.cc',
'MaybeLocal<Value> StartMainThreadExecution(Environment* env) {',
'MaybeLocal<Value> StartMainThreadExecution(Environment* env) {\n' +
' return StartExecution(env, "internal/main/run_main_module");\n'
)
const { contents: nodeccContents } = await compiler.readFileAsync('src/node.cc')
if (nodeccContents.includes('if (env->worker_context() != nullptr) {')) {
await compiler.replaceInFileAsync(
'src/node.cc',
'if (env->worker_context() != nullptr) {',
'if (env->worker_context() == nullptr) {\n' +
' return StartExecution(env, "internal/main/run_main_module"); } else {\n'
)
} else {
await compiler.replaceInFileAsync(
'src/node.cc',
'MaybeLocal<Value> StartMainThreadExecution(Environment* env) {',
'MaybeLocal<Value> StartMainThreadExecution(Environment* env) {\n' +
' return StartExecution(env, "internal/main/run_main_module");\n'
)
}
} else {
await compiler.setFileContentsAsync(
'lib/_third_party_main.js',
+4 -3
View File
@@ -1,11 +1,12 @@
import { join, dirname } from 'path'
import { promises } from 'fs'
import * as fs from 'fs'
import { promisify } from 'util'
import { readFileAsync, writeFileAsync, isDirectoryAsync } from '../util'
import mkdirpAsync = require('mkdirp')
import { NexeCompiler } from '../compiler'
const unlinkAsync = promises.unlink
const readdirAsync = promises.readdir
const unlinkAsync = promisify(fs.unlink),
readdirAsync = promisify(fs.readdir)
function readDirAsync(dir: string): Promise<string[]> {
return readdirAsync(dir).then((paths) => {
+15 -11
View File
@@ -1,8 +1,7 @@
import { NexeCompiler, NexeError } from '../compiler'
import { resolve, relative } from 'path'
import { each } from '@calebboyd/semaphore'
import resolveFiles, { resolveSync } from 'resolve-dependencies'
import { dequote, STDIN_FLAG, semverGt } from '../util'
import { dequote, STDIN_FLAG, semverGt, each } from '../util'
import { Readable } from 'stream'
function getStdIn(stdin: Readable): Promise<string> {
@@ -26,7 +25,7 @@ function getStdIn(stdin: Readable): Promise<string> {
}
export default async function bundle(compiler: NexeCompiler, next: any) {
const { bundle, cwd, input: inputPath } = compiler.options
const { bundle: doBundle, cwd, input: inputPath } = compiler.options
let input = inputPath
compiler.entrypoint = './' + relative(cwd, input)
@@ -36,14 +35,14 @@ export default async function bundle(compiler: NexeCompiler, next: any) {
compiler.startup = ';require("module").runMain();'
}
if (!bundle) {
if (!doBundle) {
await compiler.addResource(resolve(cwd, input))
return next()
}
let code = ''
if (typeof bundle === 'string') {
code = await require(bundle).createBundle(compiler.options)
if (typeof doBundle === 'string') {
code = await require(doBundle).createBundle(compiler.options)
}
if (input === STDIN_FLAG && (code = code || dequote(await getStdIn(process.stdin)))) {
@@ -62,9 +61,9 @@ export default async function bundle(compiler: NexeCompiler, next: any) {
compiler.entrypoint = './' + relative(cwd, input)
}
const { files, warnings } = await resolveFiles(
const { files, warnings } = resolveFiles(
input,
...Object.keys(compiler.bundle.index).filter((x) => x.endsWith('.js')),
...Object.keys(compiler.bundle.list).filter((x) => x.endsWith('.js')),
{ cwd, expand: 'variable', loadContent: false }
)
@@ -74,8 +73,13 @@ export default async function bundle(compiler: NexeCompiler, next: any) {
throw new NexeError('Parsing Error:\n' + warnings.join('\n'))
}
await each(Object.keys(files), (filename: string) => compiler.addResource(filename), {
concurrency: 10,
})
//TODO: warnings.forEach((x) => console.log(x))
await Promise.all(
Object.entries(files).map(([key, file]) => {
return compiler.addResource(key, file)
})
)
return next()
}
+5 -7
View File
@@ -1,5 +1,6 @@
import { isDirectoryAsync, each } from '../util'
import { each } from '../util'
import * as globs from 'globby'
import { resolve } from 'path'
import { NexeCompiler } from '../compiler'
export default async function resource(compiler: NexeCompiler, next: () => Promise<any>) {
@@ -14,14 +15,11 @@ export default async function resource(compiler: NexeCompiler, next: () => Promi
// and https://github.com/mrmlnc/fast-glob#pattern-syntax
const resourcesWithForwardSlashes = resources.map((r) => r.replace(/\\/g, '/'))
await each(globs(resourcesWithForwardSlashes, { cwd }), async (file) => {
if (await isDirectoryAsync(file)) {
return
}
await each(globs(resourcesWithForwardSlashes, { cwd, onlyFiles: true }), async (file) => {
count++
step.log(`Including file: ${file}`)
await compiler.addResource(file)
await compiler.addResource(resolve(cwd, file))
})
step.log(`Included ${count} file(s). ${(compiler.resourceSize / 1e6).toFixed(3)} MB`)
step.log(`Included ${count} file(s)`)
return next()
}
+1 -2
View File
@@ -3,10 +3,9 @@ import { wrap } from '../util'
export default async function (compiler: NexeCompiler, next: () => Promise<void>) {
await next()
compiler.shims.push(
wrap(
`process.__nexe = ${JSON.stringify(compiler.binaryConfiguration)};\n` +
'' +
'{{replace:lib/fs/patch.js}}' +
'\nshimFs(process.__nexe)' +
`\n${compiler.options.fs ? '' : 'restoreFs()'}`
+6 -6
View File
@@ -1,9 +1,9 @@
import { readFile, writeFile, stat } from 'fs'
import { execFile } from 'child_process'
import pify = require('pify')
import { promisify } from 'util'
import rimraf = require('rimraf')
const rimrafAsync = pify(rimraf)
const rimrafAsync = promisify(rimraf)
export const STDIN_FLAG = '[stdin]'
export async function each<T>(
@@ -64,10 +64,10 @@ export interface ReadFileAsync {
(path: string, encoding: string): Promise<string>
}
const readFileAsync = pify(readFile)
const writeFileAsync = pify(writeFile)
const statAsync = pify(stat)
const execFileAsync = pify(execFile)
const readFileAsync = promisify(readFile)
const writeFileAsync = promisify(writeFile)
const statAsync = promisify(stat)
const execFileAsync = promisify(execFile)
const isWindows = process.platform === 'win32'
function pathExistsAsync(path: string) {
+2 -2
View File
@@ -3,7 +3,7 @@ import { getUnBuiltReleases, getLatestGitRelease } from '../lib/releases'
import { runDockerBuild } from './docker'
import { getTarget, targetsEqual, NexeTarget } from '../lib/target'
import { pathExistsAsync, readFileAsync, execFileAsync, semverGt } from '../lib/util'
import got = require('got')
import got from 'got'
import { cpus } from 'os'
const env = process.env,
@@ -86,7 +86,7 @@ async function build() {
return
}
await got(gitRelease.upload_url.split('{')[0], {
query: { name: target.toString() },
searchParams: { name: target.toString() },
body: await readFileAsync(output),
headers: {
...headers,
+1 -1
View File
@@ -6,7 +6,7 @@ import { appendFileSync } from 'fs'
function alpine(target: NexeTarget) {
return `
FROM ${target.arch === 'x64' ? '' : 'i386/'}alpine:3.4
FROM ${target.arch === 'x64' ? '' : 'i386/'}alpine:3.12
RUN apk add --no-cache curl make gcc g++ binutils-gold python linux-headers paxctl libgcc libstdc++ git vim tar gzip wget
ENV NODE_VERSION=${target.version}
ENV NEXE_VERSION=latest
+20
View File
@@ -39,6 +39,26 @@ describe('options', () => {
expect(options.output).to.equal(path.resolve(cwd, `abc${ext}`))
})
})
describe('remote', () => {
it('should use default remote', () => {
const options = normalizeOptions({})
expect(options.remote).to.equal('https://github.com/nexe/nexe/releases/download/v3.3.3/')
})
it('should append trailing slash to third-party remote if necessary', () => {
const options = normalizeOptions({
remote: 'https://sitejs.org/nexe'
})
expect(options.remote).to.equal('https://sitejs.org/nexe/')
})
it('should not append trailing slash to third-party remote that already has one', () => {
const options = normalizeOptions({
remote: 'https://sitejs.org/nexe/'
})
expect(options.remote).to.equal('https://sitejs.org/nexe/')
})
})
describe('output', () => {
it('should work', () => {
const options = normalizeOptions({
+1 -1
View File
@@ -1,6 +1,6 @@
{
"compilerOptions": {
"target":"es5",
"target":"es2015",
"skipLibCheck": true,
"experimentalDecorators": true,
"lib": ["es2018"],