This commit is contained in:
2022-09-30 05:39:11 +00:00
parent 41ee9463ae
commit 4687fa49bc
11418 changed files with 1312504 additions and 0 deletions

Binary file not shown.

View File

@ -0,0 +1,23 @@
Copyright (c) 2015-2016 Zhuo Lu, Jason Hinkle, et al.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
</dict>
</plist>

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
</dict>
</plist>

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.app-sandbox</key>
<true/>
<key>com.apple.security.inherit</key>
<true/>
</dict>
</plist>

View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.app-sandbox</key>
<true/>
</dict>
</plist>

View File

@ -0,0 +1,149 @@
/**
* @module flat
*/
'use strict'
const path = require('path')
const util = require('./util')
const debuglog = util.debuglog
const debugwarn = util.debugwarn
const execFileAsync = util.execFileAsync
const validateOptsAppAsync = util.validateOptsAppAsync
const validateOptsPlatformAsync = util.validateOptsPlatformAsync
const Identity = require('./util-identities').findIdentitiesAsync
const findIdentitiesAsync = require('./util-identities').findIdentitiesAsync
/**
* This function returns a promise validating all options passed in opts.
* @function
* @param {Object} opts - Options.
* @returns {Promise} Promise.
*/
function validateFlatOptsAsync (opts) {
if (opts.pkg) {
if (typeof opts.pkg !== 'string') return Promise.reject(new Error('`pkg` must be a string.'))
if (path.extname(opts.pkg) !== '.pkg') return Promise.reject(new Error('Extension of output package must be `.pkg`.'))
} else {
debugwarn('No `pkg` passed in arguments, will fallback to default inferred from the given application.')
opts.pkg = path.join(path.dirname(opts.app), path.basename(opts.app, '.app') + '.pkg')
}
if (opts.install) {
if (typeof opts.install !== 'string') return Promise.reject(new Error('`install` must be a string.'))
} else {
debugwarn('No `install` passed in arguments, will fallback to default `/Applications`.')
opts.install = '/Applications'
}
return Promise.all([
validateOptsAppAsync(opts),
validateOptsPlatformAsync(opts),
])
}
/**
* This function returns a promise flattening the application.
* @function
* @param {Object} opts - Options.
* @returns {Promise} Promise.
*/
function flatApplicationAsync (opts) {
const args = [
'--component', opts.app, opts.install,
'--sign', opts.identity.name,
opts.pkg
]
if (opts.keychain) {
args.unshift('--keychain', opts.keychain)
}
if (opts.scripts) {
args.unshift('--scripts', opts.scripts)
}
debuglog('Flattening... ' + opts.app)
return execFileAsync('productbuild', args)
.thenReturn(undefined)
}
/**
* This function is exported and returns a promise flattening the application.
* @function
* @param {Object} opts - Options.
* @returns {Promise} Promise.
*/
module.exports.flatAsync = function (opts) {
return validateFlatOptsAsync(opts)
.then(function () {
let promise
if (opts.identity) {
debuglog('`identity` passed in arguments.')
if (opts['identity-validation'] === false || opts.identity instanceof Identity) {
return Promise.resolve()
}
promise = findIdentitiesAsync(opts, opts.identity)
} else {
debugwarn('No `identity` passed in arguments...')
if (opts.platform === 'mas') {
debuglog('Finding `3rd Party Mac Developer Installer` certificate for flattening app distribution in the Mac App Store...')
promise = findIdentitiesAsync(opts, '3rd Party Mac Developer Installer:')
} else {
debuglog('Finding `Developer ID Application` certificate for distribution outside the Mac App Store...')
promise = findIdentitiesAsync(opts, 'Developer ID Installer:')
}
}
return promise
.then(function (identities) {
if (identities.length > 0) {
// Provisioning profile(s) found
if (identities.length > 1) {
debugwarn('Multiple identities found, will use the first discovered.')
} else {
debuglog('Found 1 identity.')
}
opts.identity = identities[0]
} else {
// No identity found
return Promise.reject(new Error('No identity found for signing.'))
}
})
})
.then(function () {
// Pre-flat operations
})
.then(function () {
debuglog('Flattening application...', '\n',
'> Application:', opts.app, '\n',
'> Package output:', opts.pkg, '\n',
'> Install path:', opts.install, '\n',
'> Identity:', opts.identity, '\n',
'> Scripts:', opts.scripts)
return flatApplicationAsync(opts)
})
.then(function () {
// Post-flat operations
debuglog('Application flattened.')
})
}
/**
* This function is exported with normal callback implementation.
* @function
* @param {Object} opts - Options.
* @param {RequestCallback} cb - Callback.
*/
module.exports.flat = function (opts, cb) {
module.exports.flatAsync(opts)
.then(function () {
debuglog('Application flattened, saved to: ' + opts.app)
if (cb) cb()
})
.catch(function (err) {
debuglog('Flat failed:')
if (err.message) debuglog(err.message)
else if (err.stack) debuglog(err.stack)
else debuglog(err)
if (cb) cb(err)
})
}

View File

@ -0,0 +1,39 @@
interface BaseSignOptions {
app: string;
identity?: string;
platform?: string;
keychain?: string;
}
interface SignOptions extends BaseSignOptions {
binaries?: string[];
entitlements?: string;
'entitlements-inherit'?: string;
'entitlements-loginhelper'?: string;
'gatekeeper-assess'?: boolean;
hardenedRuntime?: boolean;
'identity-validation'?: boolean;
ignore?: string;
'pre-auto-entitlements'?: boolean;
'pre-embed-provisioning-profile'?: boolean;
'provisioning-profile'?: string;
'requirements'?: string;
'signature-size'?: number;
type?: string;
version?: string;
}
export function sign(opts: SignOptions, callback: (error: Error) => void): void;
export function signAsync(opts: SignOptions): Promise<any>;
interface FlatOptions extends BaseSignOptions {
'identity-validation'?: boolean;
install?: string;
pkg?: string;
scripts?: string;
}
export function flat(opts: FlatOptions, callback: (error: Error) => void): void;
export function flatAsync(opts: FlatOptions): Promise<any>;

View File

@ -0,0 +1,47 @@
/**
* @module electron-osx-sign
*/
'use strict'
const sign = require('./sign')
const flat = require('./flat')
/**
* This function is a normal callback implementation.
* @param {Object} opts - Options.
* @param {RequestCallback} cb - Callback.
*/
module.exports = sign.sign // Aliasing
/**
* This function is a normal callback implementation.
* @function
* @param {Object} opts - Options.
* @param {RequestCallback} cb - Callback.
*/
module.exports.sign = sign.sign
/**
* This function returns a promise signing the application.
* @function
* @param {mixed} opts - Options.
* @returns {Promise} Promise.
*/
module.exports.signAsync = sign.signAsync
/**
* This function is exported with normal callback implementation.
* @function
* @param {Object} opts - Options.
* @param {RequestCallback} cb - Callback.
*/
module.exports.flat = flat.flat
/**
* This function is exported and returns a promise flattening the application.
* @function
* @param {Object} opts - Options.
* @returns {Promise} Promise.
*/
module.exports.flatAsync = flat.flatAsync

View File

@ -0,0 +1,413 @@
/**
* @module sign
*/
'use strict'
const path = require('path')
const semver = require('semver')
const util = require('./util')
const debuglog = util.debuglog
const debugwarn = util.debugwarn
const getAppContentsPath = util.getAppContentsPath
const execFileAsync = util.execFileAsync
const validateOptsAppAsync = util.validateOptsAppAsync
const validateOptsPlatformAsync = util.validateOptsPlatformAsync
const walkAsync = util.walkAsync
const Identity = require('./util-identities').Identity
const findIdentitiesAsync = require('./util-identities').findIdentitiesAsync
const ProvisioningProfile = require('./util-provisioning-profiles').ProvisioningProfile
const preEmbedProvisioningProfile = require('./util-provisioning-profiles').preEmbedProvisioningProfile
const preAutoEntitlements = require('./util-entitlements').preAutoEntitlements
const osRelease = require('os').release()
/**
* This function returns a promise validating opts.binaries, the additional binaries to be signed along with the discovered enclosed components.
* @function
* @param {Object} opts - Options.
* @returns {Promise} Promise.
*/
function validateOptsBinariesAsync (opts) {
return new Promise(function (resolve, reject) {
if (opts.binaries) {
if (!Array.isArray(opts.binaries)) {
reject(new Error('Additional binaries should be an Array.'))
return
}
// TODO: Presence check for binary files, reject if any does not exist
}
resolve()
})
}
/**
* This function returns a promise validating all options passed in opts.
* @function
* @param {Object} opts - Options.
* @returns {Promise} Promise.
*/
function validateSignOptsAsync (opts) {
if (opts.ignore && !(opts.ignore instanceof Array)) {
opts.ignore = [opts.ignore]
}
if (opts['provisioning-profile']) {
if (typeof opts['provisioning-profile'] !== 'string' && !(opts['provisioning-profile'] instanceof ProvisioningProfile)) return Promise.reject(new Error('Path to provisioning profile should be a string or a ProvisioningProfile object.'))
}
if (opts['type']) {
if (opts['type'] !== 'development' && opts['type'] !== 'distribution') return Promise.reject(new Error('Type must be either `development` or `distribution`.'))
} else {
opts['type'] = 'distribution'
}
return Promise.all([
validateOptsAppAsync(opts),
validateOptsPlatformAsync(opts),
validateOptsBinariesAsync(opts),
])
}
/**
* This function returns a promise verifying the code sign of application bundle.
* @function
* @param {Object} opts - Options.
* @returns {Promise} Promise resolving output.
*/
async function verifySignApplicationAsync (opts) {
// Verify with codesign
const semver = require('semver')
debuglog('Verifying application bundle with codesign...')
await execFileAsync('codesign', [
'--verify',
'--deep'
]
.concat(
opts['strict-verify'] !== false &&
semver.gte(osRelease, '15.0.0') >= 0 // Strict flag since darwin 15.0.0 --> OS X 10.11.0 El Capitan
? ['--strict' +
(opts['strict-verify']
? '=' + opts['strict-verify'] // Array should be converted to a comma separated string
: '')]
: [],
['--verbose=2', opts.app]))
// Additionally test Gatekeeper acceptance for darwin platform
if (opts.platform === 'darwin' && opts['gatekeeper-assess'] !== false) {
debuglog('Verifying Gatekeeper acceptance for darwin platform...')
await execFileAsync('spctl', [
'--assess',
'--type', 'execute',
'--verbose',
'--ignore-cache',
'--no-cache',
opts.app
])
}
}
/**
* This function returns a promise codesigning only.
* @function
* @param {Object} opts - Options.
* @returns {Promise} Promise.
*/
function signApplicationAsync (opts) {
return walkAsync(getAppContentsPath(opts))
.then(async function (childPaths) {
/**
* Sort the child paths by how deep they are in the file tree. Some arcane apple
* logic expects the deeper files to be signed first otherwise strange errors get
* thrown our way
*/
childPaths = childPaths.sort((a, b) => {
const aDepth = a.split(path.sep).length
const bDepth = b.split(path.sep).length
return bDepth - aDepth
})
function ignoreFilePath (opts, filePath) {
if (opts.ignore) {
return opts.ignore.some(function (ignore) {
if (typeof ignore === 'function') {
return ignore(filePath)
}
return filePath.match(ignore)
})
}
return false
}
if (opts.binaries) childPaths = childPaths.concat(opts.binaries)
const args = [
'--sign', opts.identity.hash || opts.identity.name,
'--force'
]
if (opts.keychain) {
args.push('--keychain', opts.keychain)
}
if (opts.requirements) {
args.push('--requirements', opts.requirements)
}
if (opts.timestamp) {
args.push('--timestamp=' + opts.timestamp)
} else {
args.push('--timestamp')
}
if (opts['signature-size']) {
if (Number.isInteger(opts['signature-size']) && opts['signature-size'] > 0) {
args.push('--signature-size', opts['signature-size'])
} else {
debugwarn(`Invalid value provided for --signature-size (${opts['signature-size']}). Must be a positive integer.`)
}
}
let optionsArguments = []
if (opts['signature-flags']) {
if (Array.isArray(opts['signature-flags'])) {
optionsArguments = [...opts['signature-flags']]
} else {
const flags = opts['signature-flags'].split(',').map(function (flag) { return flag.trim() })
optionsArguments = [...flags]
}
}
if (opts.hardenedRuntime || opts['hardened-runtime'] || optionsArguments.includes('runtime')) {
// Hardened runtime since darwin 17.7.0 --> macOS 10.13.6
if (semver.gte(osRelease, '17.7.0') >= 0) {
optionsArguments.push('runtime')
} else {
// Remove runtime if passed in with --signature-flags
debuglog('Not enabling hardened runtime, current macOS version too low, requires 10.13.6 and higher')
optionsArguments = optionsArguments.filter(function (element, index) { return element !== 'runtime' })
}
}
if (opts['restrict']) {
optionsArguments.push('restrict')
debugwarn('This flag is to be deprecated, consider using --signature-flags=restrict instead')
}
if (optionsArguments.length) {
args.push('--options', [...new Set(optionsArguments)].join(','))
}
if (opts.entitlements) {
// Sign with entitlements
for (const filePath of childPaths) {
if (ignoreFilePath(opts, filePath)) {
debuglog('Skipped... ' + filePath)
continue
}
debuglog('Signing... ' + filePath)
let entitlementsFile = opts['entitlements-inherit']
if (filePath.includes('Library/LoginItems')) {
entitlementsFile = opts['entitlements-loginhelper']
}
await execFileAsync('codesign', args.concat('--entitlements', entitlementsFile, filePath))
}
debuglog('Signing... ' + opts.app)
await execFileAsync('codesign', args.concat('--entitlements', opts.entitlements, opts.app))
} else {
for (const filePath of childPaths) {
if (ignoreFilePath(opts, filePath)) {
debuglog('Skipped... ' + filePath)
continue
}
debuglog('Signing... ' + filePath)
await execFileAsync('codesign', args.concat(filePath))
}
debuglog('Signing... ' + opts.app)
await execFileAsync('codesign', args.concat(opts.app))
}
// Verify code sign
debuglog('Verifying...')
await verifySignApplicationAsync(opts)
debuglog('Verified.')
// Check entitlements if applicable
if (opts.entitlements) {
debuglog('Displaying entitlements...')
const result = await execFileAsync('codesign', [
'--display',
'--entitlements', ':-', // Write to standard output and strip off the blob header
opts.app
])
debuglog('Entitlements:', '\n', result)
}
})
}
/**
* This function returns a promise signing the application.
* @function
* @param {mixed} opts - Options.
* @returns {Promise} Promise.
*/
const signAsync = module.exports.signAsync = function (opts) {
return validateSignOptsAsync(opts)
.then(function () {
// Determine identity for signing
let promise
if (opts.identity) {
debuglog('`identity` passed in arguments.')
if (opts['identity-validation'] === false) {
if (!(opts.identity instanceof Identity)) {
opts.identity = new Identity(opts.identity)
}
return Promise.resolve()
}
promise = findIdentitiesAsync(opts, opts.identity)
} else {
debugwarn('No `identity` passed in arguments...')
if (opts.platform === 'mas') {
if (opts.type === 'distribution') {
debuglog('Finding `3rd Party Mac Developer Application` certificate for signing app distribution in the Mac App Store...')
promise = findIdentitiesAsync(opts, '3rd Party Mac Developer Application:')
} else {
debuglog('Finding `Mac Developer` certificate for signing app in development for the Mac App Store signing...')
promise = findIdentitiesAsync(opts, 'Mac Developer:')
}
} else {
debuglog('Finding `Developer ID Application` certificate for distribution outside the Mac App Store...')
promise = findIdentitiesAsync(opts, 'Developer ID Application:')
}
}
return promise
.then(function (identities) {
if (identities.length > 0) {
// Identity(/ies) found
if (identities.length > 1) {
debugwarn('Multiple identities found, will use the first discovered.')
} else {
debuglog('Found 1 identity.')
}
opts.identity = identities[0]
} else {
// No identity found
return Promise.reject(new Error('No identity found for signing.'))
}
})
})
.then(function () {
// Determine entitlements for code signing
let filePath
if (opts.platform === 'mas') {
// To sign apps for Mac App Store, an entitlements file is required, especially for app sandboxing (as well some other services).
// Fallback entitlements for sandboxing by default: Note this may cause troubles while running an signed app due to missing keys special to the project.
// Further reading: https://developer.apple.com/library/mac/documentation/Miscellaneous/Reference/EntitlementKeyReference/Chapters/EnablingAppSandbox.html
if (!opts.entitlements) {
filePath = path.join(__dirname, 'default.entitlements.mas.plist')
debugwarn('No `entitlements` passed in arguments:', '\n',
'* Sandbox entitlements are required for Mac App Store distribution, your codesign entitlements file is default to:', filePath)
opts.entitlements = filePath
}
if (!opts['entitlements-inherit']) {
filePath = path.join(__dirname, 'default.entitlements.mas.inherit.plist')
debugwarn('No `entitlements-inherit` passed in arguments:', '\n',
'* Sandbox entitlements file for enclosing app files is default to:', filePath)
opts['entitlements-inherit'] = filePath
}
} else {
// Not necessary to have entitlements for non Mac App Store distribution
if (!opts.entitlements) {
debugwarn('No `entitlements` passed in arguments:', '\n',
'* Provide `entitlements` to specify entitlements file for codesign.')
} else {
// If entitlements is provided as a flag, fallback to default
if (opts.entitlements === true) {
filePath = path.join(__dirname, 'default.entitlements.darwin.plist')
debugwarn('`entitlements` not specified in arguments:', '\n',
'* Provide `entitlements` to specify entitlements file for codesign.', '\n',
'* Sandbox entitlements file for enclosing app files is default to:', filePath)
opts.entitlements = filePath
}
if (!opts['entitlements-inherit']) {
filePath = path.join(__dirname, 'default.entitlements.darwin.inherit.plist')
debugwarn('No `entitlements-inherit` passed in arguments:', '\n',
'* Sandbox entitlements file for enclosing app files is default to:', filePath)
opts['entitlements-inherit'] = filePath
}
}
}
if (!opts['entitlements-loginhelper']) {
filePath = opts.entitlements
debugwarn('No `entitlements-loginhelper` passed in arguments:', '\n',
'* Sandbox entitlements file for login helper is default to:', filePath)
opts['entitlements-loginhelper'] = filePath
}
})
.then(async function () {
// Pre-sign operations
const preSignOperations = []
if (opts['pre-embed-provisioning-profile'] === false) {
debugwarn('Pre-sign operation disabled for provisioning profile embedding:', '\n',
'* Enable by setting `pre-embed-provisioning-profile` to `true`.')
} else {
debuglog('Pre-sign operation enabled for provisioning profile:', '\n',
'* Disable by setting `pre-embed-provisioning-profile` to `false`.')
preSignOperations.push(preEmbedProvisioningProfile)
}
if (opts['pre-auto-entitlements'] === false) {
debugwarn('Pre-sign operation disabled for entitlements automation.')
} else {
debuglog('Pre-sign operation enabled for entitlements automation with versions >= `1.1.1`:', '\n',
'* Disable by setting `pre-auto-entitlements` to `false`.')
if (opts.entitlements && (!opts.version || semver.gte(opts.version, '1.1.1') >= 0)) {
// Enable Mac App Store sandboxing without using temporary-exception, introduced in Electron v1.1.1. Relates to electron#5601
preSignOperations.push(preAutoEntitlements)
}
}
for (const preSignOperation of preSignOperations) {
await preSignOperation(opts)
}
})
.then(function () {
debuglog('Signing application...', '\n',
'> Application:', opts.app, '\n',
'> Platform:', opts.platform, '\n',
'> Entitlements:', opts.entitlements, '\n',
'> Child entitlements:', opts['entitlements-inherit'], '\n',
'> Additional binaries:', opts.binaries, '\n',
'> Identity:', opts.identity)
return signApplicationAsync(opts)
})
.then(function () {
// Post-sign operations
debuglog('Application signed.')
})
}
/**
* This function is a normal callback implementation.
* @function
* @param {Object} opts - Options.
* @param {RequestCallback} cb - Callback.
*/
module.exports.sign = function (opts, cb) {
signAsync(opts)
.then(function () {
debuglog('Application signed: ' + opts.app)
if (cb) cb()
})
.catch(function (err) {
debuglog('Sign failed:')
if (err.message) debuglog(err.message)
else if (err.stack) debuglog(err.stack)
else debuglog(err)
if (cb) cb(err)
})
}

View File

@ -0,0 +1,91 @@
/**
* @module util-entitlements
*/
'use strict'
const { executeAppBuilderAsJson, executeAppBuilderAndWriteJson } = require("../out/util/appBuilder")
const os = require('os')
const path = require('path')
const util = require('./util')
const debuglog = util.debuglog
const getAppContentsPath = util.getAppContentsPath
let tmpFileCounter = 0
/**
* This function returns a promise completing the entitlements automation: The process includes checking in `Info.plist` for `ElectronTeamID` or setting parsed value from identity, and checking in entitlements file for `com.apple.security.application-groups` or inserting new into array. A temporary entitlements file may be created to replace the input for any changes introduced.
* @function
* @param {Object} opts - Options.
* @returns {Promise} Promise.
*/
async function preAutoEntitlements(opts) {
// If entitlements file not provided, default will be used. Fixes #41
const appInfoPath = path.join(getAppContentsPath(opts), 'Info.plist')
debuglog('Automating entitlement app group...', '\n',
'> Info.plist:', appInfoPath, '\n',
'> Entitlements:', opts.entitlements)
const plistContent = await executeAppBuilderAsJson(["decode-plist", "-f", opts.entitlements, "-f", appInfoPath])
let entitlements = plistContent[0]
if (!entitlements['com.apple.security.app-sandbox']) {
// Only automate when app sandbox enabled by user
return
}
const appInfo = plistContent[1]
// Use ElectronTeamID in Info.plist if already specified
if (appInfo.ElectronTeamID) {
debuglog('`ElectronTeamID` found in `Info.plist`: ' + appInfo.ElectronTeamID)
} else {
// The team identifier in signing identity should not be trusted
if (opts['provisioning-profile']) {
appInfo.ElectronTeamID = opts['provisioning-profile'].message.Entitlements['com.apple.developer.team-identifier']
debuglog('`ElectronTeamID` not found in `Info.plist`, use parsed from provisioning profile: ' + appInfo.ElectronTeamID)
} else {
appInfo.ElectronTeamID = opts.identity.name.substring(opts.identity.name.indexOf('(') + 1, opts.identity.name.lastIndexOf(')'))
debuglog('`ElectronTeamID` not found in `Info.plist`, use parsed from signing identity: ' + appInfo.ElectronTeamID)
}
await executeAppBuilderAndWriteJson(["encode-plist"], {[appInfoPath]: appInfo})
debuglog('`Info.plist` updated:', '\n', '> Info.plist:', appInfoPath)
}
const appIdentifier = appInfo.ElectronTeamID + '.' + appInfo.CFBundleIdentifier
// Insert application identifier if not exists
if (entitlements['com.apple.application-identifier']) {
debuglog('`com.apple.application-identifier` found in entitlements file: ' + entitlements['com.apple.application-identifier'])
} else {
debuglog('`com.apple.application-identifier` not found in entitlements file, new inserted: ' + appIdentifier)
entitlements['com.apple.application-identifier'] = appIdentifier
}
// Insert developer team identifier if not exists
if (entitlements['com.apple.developer.team-identifier']) {
debuglog('`com.apple.developer.team-identifier` found in entitlements file: ' + entitlements['com.apple.developer.team-identifier'])
} else {
debuglog('`com.apple.developer.team-identifier` not found in entitlements file, new inserted: ' + appInfo.ElectronTeamID)
entitlements['com.apple.developer.team-identifier'] = appInfo.ElectronTeamID
}
// Init entitlements app group key to array if not exists
if (!entitlements['com.apple.security.application-groups']) {
entitlements['com.apple.security.application-groups'] = []
}
// Insert app group if not exists
if (Array.isArray(entitlements['com.apple.security.application-groups']) && entitlements['com.apple.security.application-groups'].indexOf(appIdentifier) === -1) {
debuglog('`com.apple.security.application-groups` not found in entitlements file, new inserted: ' + appIdentifier)
entitlements['com.apple.security.application-groups'].push(appIdentifier)
} else {
debuglog('`com.apple.security.application-groups` found in entitlements file: ' + appIdentifier)
}
// Create temporary entitlements file
const entitlementsPath = path.join(os.tmpdir(), `tmp-entitlements-${process.pid.toString(16)}-${(tmpFileCounter++).toString(16)}.plist`)
opts.entitlements = entitlementsPath
await executeAppBuilderAndWriteJson(["encode-plist"], {[entitlementsPath]: entitlements})
debuglog('Entitlements file updated:', '\n', '> Entitlements:', entitlementsPath)
}
module.exports.preAutoEntitlements = preAutoEntitlements

View File

@ -0,0 +1,55 @@
/**
* @module util-identities
*/
'use strict'
const util = require('./util')
const debuglog = util.debuglog
const flatList = util.flatList
const execFileAsync = util.execFileAsync
/**
* @constructor
* @param {string} name - Name of the signing identity.
* @param {String} hash - SHA-1 hash of the identity.
*/
var Identity = module.exports.Identity = function (name, hash) {
this.name = name
this.hash = hash
}
/**
* This function returns a promise checking the indentity proposed and updates the identity option to a exact finding from results.
* @function
* @param {Object} opts - Options.
* @param {string} identity - The proposed identity.
* @returns {Promise} Promise.
*/
module.exports.findIdentitiesAsync = function (opts, identity) {
// Only to look for valid identities, excluding those flagged with
// CSSMERR_TP_CERT_EXPIRED or CSSMERR_TP_NOT_TRUSTED. Fixes #9
var args = [
'find-identity',
'-v'
]
if (opts.keychain) {
args.push(opts.keychain)
}
return execFileAsync('security', args)
.then(function (result) {
return result.split('\n').map(function (line) {
if (line.indexOf(identity) >= 0) {
var identityFound = line.substring(line.indexOf('"') + 1, line.lastIndexOf('"'))
var identityHashFound = line.substring(line.indexOf(')') + 2, line.indexOf('"') - 1)
debuglog('Identity:', '\n',
'> Name:', identityFound, '\n',
'> Hash:', identityHashFound)
return new Identity(identityFound, identityHashFound)
}
})
})
.then(flatList)
}

View File

@ -0,0 +1,178 @@
/**
* @module util-provisioning-profiles
*/
'use strict'
const path = require('path')
const fs = require("fs-extra")
const os = require('os')
const { executeAppBuilderAsJson } = require("../out/util/appBuilder")
const util = require('./util')
const debuglog = util.debuglog
const debugwarn = util.debugwarn
const getAppContentsPath = util.getAppContentsPath
const copyFileAsync = util.copyFileAsync
const execFileAsync = util.execFileAsync
/**
* @constructor
* @param {string} filePath - Path to provisioning profile.
* @param {Object} message - Decoded message in provisioning profile.
*/
let ProvisioningProfile = module.exports.ProvisioningProfile = function (filePath, message) {
this.filePath = filePath
this.message = message
}
Object.defineProperty(ProvisioningProfile.prototype, 'name', {
get: function () {
return this.message['Name']
}
})
Object.defineProperty(ProvisioningProfile.prototype, 'platforms', {
get: function () {
if ('ProvisionsAllDevices' in this.message) return ['darwin'] // Developer ID
else if (this.type === 'distribution') return ['mas'] // Mac App Store
else return ['darwin', 'mas'] // Mac App Development
}
})
Object.defineProperty(ProvisioningProfile.prototype, 'type', {
get: function () {
if ('ProvisionedDevices' in this.message) return 'development' // Mac App Development
else return 'distribution' // Developer ID or Mac App Store
}
})
/**
* Returns a promise resolving to a ProvisioningProfile instance based on file.
* @function
* @param {string} filePath - Path to provisioning profile.
* @param {string} keychain - Keychain to use when unlocking provisioning profile.
* @returns {Promise} Promise.
*/
function getProvisioningProfileAsync(filePath, keychain) {
const securityArgs = [
'cms',
'-D', // Decode a CMS message
'-i', filePath // Use infile as source of data
]
if (keychain != null) {
securityArgs.push('-k', keychain)
}
return util.execFileAsync('security', securityArgs)
.then(async function (result) {
// make filename unique so it doesn't create issues with parallel method calls
const timestamp = process.hrtime.bigint
? process.hrtime.bigint().toString()
: process.hrtime().join('')
// todo read directly
const tempFile = path.join(os.tmpdir(), `${require('crypto').createHash('sha1').update(filePath).update(timestamp).digest('hex')}.plist`)
await fs.outputFile(tempFile, result)
const plistContent = await executeAppBuilderAsJson(["decode-plist", "-f", tempFile])
await fs.unlink(tempFile)
const provisioningProfile = new ProvisioningProfile(filePath, plistContent[0])
debuglog('Provisioning profile:', '\n',
'> Name:', provisioningProfile.name, '\n',
'> Platforms:', provisioningProfile.platforms, '\n',
'> Type:', provisioningProfile.type, '\n',
'> Path:', provisioningProfile.filePath, '\n',
'> Message:', provisioningProfile.message)
return provisioningProfile
})
}
/**
* Returns a promise resolving to a list of suitable provisioning profile within the current working directory.
* @function
* @param {Object} opts - Options.
* @returns {Promise} Promise.
*/
async function findProvisioningProfilesAsync(opts) {
const dirPath = process.cwd()
const dirContent = await Promise.all((await fs.readdir(dirPath))
.filter(it => it.endsWith(".provisionprofile"))
.map(async function (name) {
const filePath = path.join(dirPath, name)
const stat = await fs.lstat(filePath)
return stat.isFile() ? filePath : undefined
}))
return util.flatList(await Promise.all(util.flatList(dirContent).map(filePath => {
return getProvisioningProfileAsync(filePath)
.then((provisioningProfile) => {
if (provisioningProfile.platforms.indexOf(opts.platform) >= 0 && provisioningProfile.type === opts.type) {
return provisioningProfile
}
debugwarn('Provisioning profile above ignored, not for ' + opts.platform + ' ' + opts.type + '.')
return undefined
})
})))
}
/**
* Returns a promise embedding the provisioning profile in the app Contents folder.
* @function
* @param {Object} opts - Options.
* @returns {Promise} Promise.
*/
module.exports.preEmbedProvisioningProfile = function (opts) {
async function embedProvisioningProfile () {
if (!opts['provisioning-profile']) {
return
}
debuglog('Looking for existing provisioning profile...')
let embeddedFilePath = path.join(getAppContentsPath(opts), 'embedded.provisionprofile')
try {
await fs.lstat(embeddedFilePath)
debuglog('Found embedded provisioning profile:', '\n',
'* Please manually remove the existing file if not wanted.', '\n',
'* Current file at:', embeddedFilePath)
} catch (err) {
if (err.code === 'ENOENT') {
// File does not exist
debuglog('Embedding provisioning profile...')
return copyFileAsync(opts['provisioning-profile'].filePath, embeddedFilePath)
} else throw err
}
}
if (opts['provisioning-profile']) {
// User input provisioning profile
debuglog('`provisioning-profile` passed in arguments.')
if (opts['provisioning-profile'] instanceof ProvisioningProfile) {
return embedProvisioningProfile()
} else {
return getProvisioningProfileAsync(opts['provisioning-profile'], opts['keychain'])
.then(function (provisioningProfile) {
opts['provisioning-profile'] = provisioningProfile
})
.then(embedProvisioningProfile)
}
} else {
// Discover provisioning profile
debuglog('No `provisioning-profile` passed in arguments, will find in current working directory and in user library...')
return findProvisioningProfilesAsync(opts)
.then(function (provisioningProfiles) {
if (provisioningProfiles.length > 0) {
// Provisioning profile(s) found
if (provisioningProfiles.length > 1) {
debuglog('Multiple provisioning profiles found, will use the first discovered.')
} else {
debuglog('Found 1 provisioning profile.')
}
opts['provisioning-profile'] = provisioningProfiles[0]
} else {
// No provisioning profile found
debuglog('No provisioning profile found, will not embed profile in app contents.')
}
})
.then(embedProvisioningProfile)
}
}

View File

@ -0,0 +1,236 @@
/**
* @module util
*/
'use strict'
const child = require('child_process')
const fs = require('fs-extra')
const path = require('path')
const debug = require('debug')
/**
* This callback is used across signing and flattening.
* @callback RequestCallback
* @param {?Error} err
*/
/** @function */
const debuglog = module.exports.debuglog = debug('electron-osx-sign')
debuglog.log = console.log.bind(console)
/** @function */
const debugwarn = module.exports.debugwarn = debug('electron-osx-sign:warn')
debugwarn.log = console.warn.bind(console)
/** @function */
const removePassword = function (input) {
return input.replace(/(-P |pass:|\/p|-pass )([^ ]+)/, function (match, p1, p2) {
return `${p1}***`
})
}
/** @function */
module.exports.execFileAsync = function (file, args, options) {
if (debuglog.enabled) {
debuglog('Executing...', file, args && Array.isArray(args) ? removePassword(args.join(' ')) : '')
}
return new Promise(function (resolve, reject) {
child.execFile(file, args, options, function (err, stdout, stderr) {
if (err) {
debuglog('Error executing file:', '\n',
'> Stdout:', stdout, '\n',
'> Stderr:', stderr)
reject(err)
return
}
resolve(stdout)
})
})
}
/**
* This function returns a flattened list of elements from an array of lists.
* @function
* @param {*} list - List.
* @returns Flattened list.
*/
module.exports.flatList = function (list) {
function populateResult(list) {
if (!Array.isArray(list)) {
result.push(list)
} else if (list.length > 0) {
for (let item of list) if (item) populateResult(item)
}
}
let result = []
populateResult(list)
return result
}
/**
* This function returns the path to app contents.
* @function
* @param {Object} opts - Options.
* @returns {string} App contents path.
*/
var getAppContentsPath = module.exports.getAppContentsPath = function (opts) {
return path.join(opts.app, 'Contents')
}
/**
* This function returns the path to app frameworks within contents.
* @function
* @param {Object} opts - Options.
* @returns {string} App frameworks path.
*/
var getAppFrameworksPath = module.exports.getAppFrameworksPath = function (opts) {
return path.join(getAppContentsPath(opts), 'Frameworks')
}
/**
* This function returns a promise copying a file from the source to the target.
* @function
* @param {string} source - Source path.
* @param {string} target - Target path.
* @returns {Promise} Promise.
*/
module.exports.copyFileAsync = function (source, target) {
debuglog('Copying file...', '\n',
'> Source:', source, '\n',
'> Target:', target)
return new Promise(function (resolve, reject) {
var readStream = fs.createReadStream(source)
readStream.on('error', reject)
var writeStream = fs.createWriteStream(target)
writeStream.on('error', reject)
writeStream.on('close', resolve)
readStream.pipe(writeStream)
})
}
/**
* This function returns a promise with platform resolved.
* @function
* @param {Object} opts - Options.
* @returns {Promise} Promise resolving platform.
*/
var detectElectronPlatformAsync = module.exports.detectElectronPlatformAsync = function (opts) {
return new Promise(function (resolve) {
var appFrameworksPath = getAppFrameworksPath(opts)
// The presence of Squirrel.framework identifies a Mac App Store build as used in https://github.com/atom/electron/blob/master/docs/tutorial/mac-app-store-submission-guide.md
return fs.lstat(path.join(appFrameworksPath, 'Squirrel.framework'))
.then(function () {
resolve('darwin')
})
.catch(function () {
resolve('mas')
})
})
}
const isBinaryFile = require("isbinaryfile").isBinaryFile;
/**
* This function returns a promise resolving the file path if file binary.
* @function
* @param {string} filePath - Path to file.
* @returns {Promise} Promise resolving file path or undefined.
*/
const getFilePathIfBinaryAsync = module.exports.getFilePathIfBinaryAsync = function (filePath) {
return isBinaryFile(filePath)
.then(function (isBinary) {
return isBinary ? filePath : undefined
})
}
/**
* This function returns a promise validating opts.app, the application to be signed or flattened.
* @function
* @param {Object} opts - Options.
* @returns {Promise} Promise.
*/
module.exports.validateOptsAppAsync = async function (opts) {
if (!opts.app) {
throw new Error('Path to aplication must be specified.')
}
if (path.extname(opts.app) !== '.app') {
throw new Error('Extension of application must be `.app`.')
}
await fs.lstat(opts.app)
}
/**
* This function returns a promise validating opts.platform, the platform of Electron build. It allows auto-discovery if no opts.platform is specified.
* @function
* @param {Object} opts - Options.
* @returns {Promise} Promise.
*/
module.exports.validateOptsPlatformAsync = function (opts) {
if (opts.platform) {
if (opts.platform === 'mas' || opts.platform === 'darwin') {
return Promise.resolve()
} else {
debugwarn('`platform` passed in arguments not supported, checking Electron platform...')
}
} else {
debugwarn('No `platform` passed in arguments, checking Electron platform...')
}
return detectElectronPlatformAsync(opts)
.then(function (platform) {
opts.platform = platform
})
}
/**
* This function returns a promise resolving all child paths within the directory specified.
* @function
* @param {string} dirPath - Path to directory.
* @returns {Promise} Promise resolving child paths needing signing in order.
*/
module.exports.walkAsync = async function (dirPath) {
debuglog('Walking... ' + dirPath)
async function _walkAsync(dirPath) {
const names = await fs.readdir(dirPath)
return await Promise.all(names.map(async (name) => {
let filePath = path.join(dirPath, name)
const stat = await fs.lstat(filePath)
if (stat.isFile()) {
switch (path.extname(filePath)) {
case '': // Binary
if (path.basename(filePath)[0] !== '.') {
return getFilePathIfBinaryAsync(filePath)
} // Else reject hidden file
break
case '.dylib': // Dynamic library
case '.node': // Native node addon
return filePath
case '.cstemp': // Temporary file generated from past codesign
debuglog('Removing... ' + filePath)
await fs.unlink(filePath)
return
default:
if (path.extname(filePath).indexOf(' ') >= 0) {
// Still consider the file as binary if extension seems invalid
return getFilePathIfBinaryAsync(filePath)
}
}
} else if (stat.isDirectory() && !stat.isSymbolicLink()) {
const result = await _walkAsync(filePath)
switch (path.extname(filePath)) {
case '.app': // Application
case '.framework': // Framework
result.push(filePath)
}
return result
}
}))
}
return module.exports.flatList(await _walkAsync(dirPath))
}

View File

@ -0,0 +1,896 @@
9.0.1 / 2020-06-03
------------------
- Fix issue with `ensureFile()` when used with Jest on Windows ([#804](https://github.com/jprichardson/node-fs-extra/issues/804), [#805](https://github.com/jprichardson/node-fs-extra/pull/805))
- Remove unneeded `process.umask()` call ([#791](https://github.com/jprichardson/node-fs-extra/pull/791))
- Docs improvements ([#753](https://github.com/jprichardson/node-fs-extra/pull/753), [#795](https://github.com/jprichardson/node-fs-extra/pull/795), [#797](https://github.com/jprichardson/node-fs-extra/pull/797))
9.0.0 / 2020-03-19
------------------
### Breaking changes
- Requires Node.js version 10 or greater ([#725](https://github.com/jprichardson/node-fs-extra/issues/725), [#751](https://github.com/jprichardson/node-fs-extra/pull/751))
- Switched `ensureDir*` to use a fork of https://github.com/sindresorhus/make-dir to make use of native recursive `fs.mkdir` where possible ([#619](https://github.com/jprichardson/node-fs-extra/issues/619), [#756](https://github.com/jprichardson/node-fs-extra/pull/756))
- Properly preserve `atime` for `copy*` with `preserveTimestamps` option ([#633](https://github.com/jprichardson/node-fs-extra/pull/633))
**The following changes, allthough technically breaking, will not affect the vast majority of users:**
- `outputJson` now outputs objects as they were when the function was called, even if they are mutated later ([#702](https://github.com/jprichardson/node-fs-extra/issues/702), [#768](https://github.com/jprichardson/node-fs-extra/pull/768))
- Cannot pass `null` as an options parameter to `*Json*` methods ([#745](https://github.com/jprichardson/node-fs-extra/issues/745), [#768](https://github.com/jprichardson/node-fs-extra/pull/768))
### Improvements
- Add promise shims for `fs.writev` & `fs.opendir` ([#747](https://github.com/jprichardson/node-fs-extra/pull/747))
- Better errors for `ensureFile` ([#696](https://github.com/jprichardson/node-fs-extra/issues/696), [#744](https://github.com/jprichardson/node-fs-extra/pull/744))
- Better file comparison for older Node versions ([#694](https://github.com/jprichardson/node-fs-extra/pull/694))
### Miscellaneous changes
- Peformance optimizations ([#762](https://github.com/jprichardson/node-fs-extra/issues/762), [#764](https://github.com/jprichardson/node-fs-extra/pull/764))
- Add missing documentation for aliases ([#758](https://github.com/jprichardson/node-fs-extra/issues/758), [#766](https://github.com/jprichardson/node-fs-extra/pull/766))
- Update `universalify` dependency ([#767](https://github.com/jprichardson/node-fs-extra/pull/767))
8.1.0 / 2019-06-28
------------------
- Add support for promisified `fs.realpath.native` in Node v9.2+ ([#650](https://github.com/jprichardson/node-fs-extra/issues/650), [#682](https://github.com/jprichardson/node-fs-extra/pull/682))
- Update `graceful-fs` dependency ([#700](https://github.com/jprichardson/node-fs-extra/pull/700))
- Use `graceful-fs` everywhere ([#700](https://github.com/jprichardson/node-fs-extra/pull/700))
8.0.1 / 2019-05-13
------------------
- Fix bug `Maximum call stack size exceeded` error in `util/stat` ([#679](https://github.com/jprichardson/node-fs-extra/pull/679))
8.0.0 / 2019-05-11
------------------
**NOTE:** Node.js v6 support is deprecated, and will be dropped in the next major release.
- Use `renameSync()` under the hood in `moveSync()`
- Fix bug with bind-mounted directories in `copy*()` ([#613](https://github.com/jprichardson/node-fs-extra/issues/613), [#618](https://github.com/jprichardson/node-fs-extra/pull/618))
- Fix bug in `move()` with case-insensitive file systems
- Use `fs.stat()`'s `bigint` option in `copy*()` & `move*()` where possible ([#657](https://github.com/jprichardson/node-fs-extra/issues/657))
7.0.1 / 2018-11-07
------------------
- Fix `removeSync()` on Windows, in some cases, it would error out with `ENOTEMPTY` ([#646](https://github.com/jprichardson/node-fs-extra/pull/646))
- Document `mode` option for `ensureDir*()` ([#587](https://github.com/jprichardson/node-fs-extra/pull/587))
- Don't include documentation files in npm package tarball ([#642](https://github.com/jprichardson/node-fs-extra/issues/642), [#643](https://github.com/jprichardson/node-fs-extra/pull/643))
7.0.0 / 2018-07-16
------------------
- **BREAKING:** Refine `copy*()` handling of symlinks to properly detect symlinks that point to the same file. ([#582](https://github.com/jprichardson/node-fs-extra/pull/582))
- Fix bug with copying write-protected directories ([#600](https://github.com/jprichardson/node-fs-extra/pull/600))
- Universalify `fs.lchmod()` ([#596](https://github.com/jprichardson/node-fs-extra/pull/596))
- Add `engines` field to `package.json` ([#580](https://github.com/jprichardson/node-fs-extra/pull/580))
6.0.1 / 2018-05-09
------------------
- Fix `fs.promises` `ExperimentalWarning` on Node v10.1.0 ([#578](https://github.com/jprichardson/node-fs-extra/pull/578))
6.0.0 / 2018-05-01
------------------
- Drop support for Node.js versions 4, 5, & 7 ([#564](https://github.com/jprichardson/node-fs-extra/pull/564))
- Rewrite `move` to use `fs.rename` where possible ([#549](https://github.com/jprichardson/node-fs-extra/pull/549))
- Don't convert relative paths to absolute paths for `filter` ([#554](https://github.com/jprichardson/node-fs-extra/pull/554))
- `copy*`'s behavior when `preserveTimestamps` is `false` has been OS-dependent since 5.0.0, but that's now explicitly noted in the docs ([#563](https://github.com/jprichardson/node-fs-extra/pull/563))
- Fix subdirectory detection for `copy*` & `move*` ([#541](https://github.com/jprichardson/node-fs-extra/pull/541))
- Handle case-insensitive paths correctly in `copy*` ([#568](https://github.com/jprichardson/node-fs-extra/pull/568))
5.0.0 / 2017-12-11
------------------
Significant refactor of `copy()` & `copySync()`, including breaking changes. No changes to other functions in this release.
Huge thanks to **[@manidlou](https://github.com/manidlou)** for doing most of the work on this release.
- The `filter` option can no longer be a RegExp (must be a function). This was deprecated since fs-extra v1.0.0. [#512](https://github.com/jprichardson/node-fs-extra/pull/512)
- `copy()`'s `filter` option can now be a function that returns a Promise. [#518](https://github.com/jprichardson/node-fs-extra/pull/518)
- `copy()` & `copySync()` now use `fs.copyFile()`/`fs.copyFileSync()` in environments that support it (currently Node 8.5.0+). Older Node versions still get the old implementation. [#505](https://github.com/jprichardson/node-fs-extra/pull/505)
- Don't allow copying a directory into itself. [#83](https://github.com/jprichardson/node-fs-extra/issues/83)
- Handle copying between identical files. [#198](https://github.com/jprichardson/node-fs-extra/issues/198)
- Error out when copying an empty folder to a path that already exists. [#464](https://github.com/jprichardson/node-fs-extra/issues/464)
- Don't create `dest`'s parent if the `filter` function aborts the `copy()` operation. [#517](https://github.com/jprichardson/node-fs-extra/pull/517)
- Fix `writeStream` not being closed if there was an error in `copy()`. [#516](https://github.com/jprichardson/node-fs-extra/pull/516)
4.0.3 / 2017-12-05
------------------
- Fix wrong `chmod` values in `fs.remove()` [#501](https://github.com/jprichardson/node-fs-extra/pull/501)
- Fix `TypeError` on systems that don't have some `fs` operations like `lchown` [#520](https://github.com/jprichardson/node-fs-extra/pull/520)
4.0.2 / 2017-09-12
------------------
- Added `EOL` option to `writeJson*` & `outputJson*` (via upgrade to jsonfile v4)
- Added promise support to [`fs.copyFile()`](https://nodejs.org/api/fs.html#fs_fs_copyfile_src_dest_flags_callback) in Node 8.5+
- Added `.js` extension to `main` field in `package.json` for better tooling compatibility. [#485](https://github.com/jprichardson/node-fs-extra/pull/485)
4.0.1 / 2017-07-31
------------------
### Fixed
- Previously, `ensureFile()` & `ensureFileSync()` would do nothing if the path was a directory. Now, they error out for consistency with `ensureDir()`. [#465](https://github.com/jprichardson/node-fs-extra/issues/465), [#466](https://github.com/jprichardson/node-fs-extra/pull/466), [#470](https://github.com/jprichardson/node-fs-extra/issues/470)
4.0.0 / 2017-07-14
------------------
### Changed
- **BREAKING:** The promisified versions of `fs.read()` & `fs.write()` now return objects. See [the docs](docs/fs-read-write.md) for details. [#436](https://github.com/jprichardson/node-fs-extra/issues/436), [#449](https://github.com/jprichardson/node-fs-extra/pull/449)
- `fs.move()` now errors out when destination is a subdirectory of source. [#458](https://github.com/jprichardson/node-fs-extra/pull/458)
- Applied upstream fixes from `rimraf` to `fs.remove()` & `fs.removeSync()`. [#459](https://github.com/jprichardson/node-fs-extra/pull/459)
### Fixed
- Got `fs.outputJSONSync()` working again; it was broken due to refactoring. [#428](https://github.com/jprichardson/node-fs-extra/pull/428)
Also clarified the docs in a few places.
3.0.1 / 2017-05-04
------------------
- Fix bug in `move()` & `moveSync()` when source and destination are the same, and source does not exist. [#415](https://github.com/jprichardson/node-fs-extra/pull/415)
3.0.0 / 2017-04-27
------------------
### Added
- **BREAKING:** Added Promise support. All asynchronous native fs methods and fs-extra methods now return a promise if the callback is not passed. [#403](https://github.com/jprichardson/node-fs-extra/pull/403)
- `pathExists()`, a replacement for the deprecated `fs.exists`. `pathExists` has a normal error-first callback signature. Also added `pathExistsSync`, an alias to `fs.existsSync`, for completeness. [#406](https://github.com/jprichardson/node-fs-extra/pull/406)
### Removed
- **BREAKING:** Removed support for setting the default spaces for `writeJson()`, `writeJsonSync()`, `outputJson()`, & `outputJsonSync()`. This was undocumented. [#402](https://github.com/jprichardson/node-fs-extra/pull/402)
### Changed
- Upgraded jsonfile dependency to v3.0.0:
- **BREAKING:** Changed behavior of `throws` option for `readJsonSync()`; now does not throw filesystem errors when `throws` is `false`.
- **BREAKING:** `writeJson()`, `writeJsonSync()`, `outputJson()`, & `outputJsonSync()` now output minified JSON by default for consistency with `JSON.stringify()`; set the `spaces` option to `2` to override this new behavior. [#402](https://github.com/jprichardson/node-fs-extra/pull/402)
- Use `Buffer.allocUnsafe()` instead of `new Buffer()` in environments that support it. [#394](https://github.com/jprichardson/node-fs-extra/pull/394)
### Fixed
- `removeSync()` silently failed on Windows in some cases. Now throws an `EBUSY` error. [#408](https://github.com/jprichardson/node-fs-extra/pull/408)
2.1.2 / 2017-03-16
------------------
### Fixed
- Weird windows bug that resulted in `ensureDir()`'s callback being called twice in some cases. This bug may have also affected `remove()`. See [#392](https://github.com/jprichardson/node-fs-extra/issues/392), [#393](https://github.com/jprichardson/node-fs-extra/pull/393)
2.1.1 / 2017-03-15
------------------
### Fixed
- Reverted [`5597bd`](https://github.com/jprichardson/node-fs-extra/commit/5597bd5b67f7d060f5f5bf26e9635be48330f5d7), this broke compatibility with Node.js versions v4+ but less than `v4.5.0`.
- Remove `Buffer.alloc()` usage in `moveSync()`.
2.1.0 / 2017-03-15
------------------
Thanks to [Mani Maghsoudlou (@manidlou)](https://github.com/manidlou) & [Jan Peer Stöcklmair (@JPeer264)](https://github.com/JPeer264) for their extraordinary help with this release!
### Added
- `moveSync()` See [#309], [#381](https://github.com/jprichardson/node-fs-extra/pull/381). ([@manidlou](https://github.com/manidlou))
- `copy()` and `copySync()`'s `filter` option now gets the destination path passed as the second parameter. [#366](https://github.com/jprichardson/node-fs-extra/pull/366) ([@manidlou](https://github.com/manidlou))
### Changed
- Use `Buffer.alloc()` instead of deprecated `new Buffer()` in `copySync()`. [#380](https://github.com/jprichardson/node-fs-extra/pull/380) ([@manidlou](https://github.com/manidlou))
- Refactored entire codebase to use ES6 features supported by Node.js v4+ [#355](https://github.com/jprichardson/node-fs-extra/issues/355). [(@JPeer264)](https://github.com/JPeer264)
- Refactored docs. ([@manidlou](https://github.com/manidlou))
### Fixed
- `move()` shouldn't error out when source and dest are the same. [#377](https://github.com/jprichardson/node-fs-extra/issues/377), [#378](https://github.com/jprichardson/node-fs-extra/pull/378) ([@jdalton](https://github.com/jdalton))
2.0.0 / 2017-01-16
------------------
### Removed
- **BREAKING:** Removed support for Node `v0.12`. The Node foundation stopped officially supporting it
on Jan 1st, 2017.
- **BREAKING:** Remove `walk()` and `walkSync()`. `walkSync()` was only part of `fs-extra` for a little
over two months. Use [klaw](https://github.com/jprichardson/node-klaw) instead of `walk()`, in fact, `walk()` was just
an alias to klaw. For `walkSync()` use [klaw-sync](https://github.com/mawni/node-klaw-sync). See: [#338], [#339]
### Changed
- **BREAKING:** Renamed `clobber` to `overwrite`. This affects `copy()`, `copySync()`, and `move()`. [#330], [#333]
- Moved docs, to `docs/`. [#340]
### Fixed
- Apply filters to directories in `copySync()` like in `copy()`. [#324]
- A specific condition when disk is under heavy use, `copy()` can fail. [#326]
1.0.0 / 2016-11-01
------------------
After five years of development, we finally have reach the 1.0.0 milestone! Big thanks goes
to [Ryan Zim](https://github.com/RyanZim) for leading the charge on this release!
### Added
- `walkSync()`
### Changed
- **BREAKING**: dropped Node v0.10 support.
- disabled `rimaf` globbing, wasn't used. [#280]
- deprecate `copy()/copySync()` option `filter` if it's a `RegExp`. `filter` should now be a function.
- inline `rimraf`. This is temporary and was done because `rimraf` depended upon the beefy `glob` which `fs-extra` does not use. [#300]
### Fixed
- bug fix proper closing of file handle on `utimesMillis()` [#271]
- proper escaping of files with dollar signs [#291]
- `copySync()` failed if user didn't own file. [#199], [#301]
0.30.0 / 2016-04-28
-------------------
- Brought back Node v0.10 support. I didn't realize there was still demand. Official support will end **2016-10-01**.
0.29.0 / 2016-04-27
-------------------
- **BREAKING**: removed support for Node v0.10. If you still want to use Node v0.10, everything should work except for `ensureLink()/ensureSymlink()`. Node v0.12 is still supported but will be dropped in the near future as well.
0.28.0 / 2016-04-17
-------------------
- **BREAKING**: removed `createOutputStream()`. Use https://www.npmjs.com/package/create-output-stream. See: [#192][#192]
- `mkdirs()/mkdirsSync()` check for invalid win32 path chars. See: [#209][#209], [#237][#237]
- `mkdirs()/mkdirsSync()` if drive not mounted, error. See: [#93][#93]
0.27.0 / 2016-04-15
-------------------
- add `dereference` option to `copySync()`. [#235][#235]
0.26.7 / 2016-03-16
-------------------
- fixed `copy()` if source and dest are the same. [#230][#230]
0.26.6 / 2016-03-15
-------------------
- fixed if `emptyDir()` does not have a callback: [#229][#229]
0.26.5 / 2016-01-27
-------------------
- `copy()` with two arguments (w/o callback) was broken. See: [#215][#215]
0.26.4 / 2016-01-05
-------------------
- `copySync()` made `preserveTimestamps` default consistent with `copy()` which is `false`. See: [#208][#208]
0.26.3 / 2015-12-17
-------------------
- fixed `copy()` hangup in copying blockDevice / characterDevice / `/dev/null`. See: [#193][#193]
0.26.2 / 2015-11-02
-------------------
- fixed `outputJson{Sync}()` spacing adherence to `fs.spaces`
0.26.1 / 2015-11-02
-------------------
- fixed `copySync()` when `clogger=true` and the destination is read only. See: [#190][#190]
0.26.0 / 2015-10-25
-------------------
- extracted the `walk()` function into its own module [`klaw`](https://github.com/jprichardson/node-klaw).
0.25.0 / 2015-10-24
-------------------
- now has a file walker `walk()`
0.24.0 / 2015-08-28
-------------------
- removed alias `delete()` and `deleteSync()`. See: [#171][#171]
0.23.1 / 2015-08-07
-------------------
- Better handling of errors for `move()` when moving across devices. [#170][#170]
- `ensureSymlink()` and `ensureLink()` should not throw errors if link exists. [#169][#169]
0.23.0 / 2015-08-06
-------------------
- added `ensureLink{Sync}()` and `ensureSymlink{Sync}()`. See: [#165][#165]
0.22.1 / 2015-07-09
-------------------
- Prevent calling `hasMillisResSync()` on module load. See: [#149][#149].
Fixes regression that was introduced in `0.21.0`.
0.22.0 / 2015-07-09
-------------------
- preserve permissions / ownership in `copy()`. See: [#54][#54]
0.21.0 / 2015-07-04
-------------------
- add option to preserve timestamps in `copy()` and `copySync()`. See: [#141][#141]
- updated `graceful-fs@3.x` to `4.x`. This brings in features from `amazing-graceful-fs` (much cleaner code / less hacks)
0.20.1 / 2015-06-23
-------------------
- fixed regression caused by latest jsonfile update: See: https://github.com/jprichardson/node-jsonfile/issues/26
0.20.0 / 2015-06-19
-------------------
- removed `jsonfile` aliases with `File` in the name, they weren't documented and probably weren't in use e.g.
this package had both `fs.readJsonFile` and `fs.readJson` that were aliases to each other, now use `fs.readJson`.
- preliminary walker created. Intentionally not documented. If you use it, it will almost certainly change and break your code.
- started moving tests inline
- upgraded to `jsonfile@2.1.0`, can now pass JSON revivers/replacers to `readJson()`, `writeJson()`, `outputJson()`
0.19.0 / 2015-06-08
-------------------
- `fs.copy()` had support for Node v0.8, dropped support
0.18.4 / 2015-05-22
-------------------
- fixed license field according to this: [#136][#136] and https://github.com/npm/npm/releases/tag/v2.10.0
0.18.3 / 2015-05-08
-------------------
- bugfix: handle `EEXIST` when clobbering on some Linux systems. [#134][#134]
0.18.2 / 2015-04-17
-------------------
- bugfix: allow `F_OK` ([#120][#120])
0.18.1 / 2015-04-15
-------------------
- improved windows support for `move()` a bit. https://github.com/jprichardson/node-fs-extra/commit/92838980f25dc2ee4ec46b43ee14d3c4a1d30c1b
- fixed a lot of tests for Windows (appveyor)
0.18.0 / 2015-03-31
-------------------
- added `emptyDir()` and `emptyDirSync()`
0.17.0 / 2015-03-28
-------------------
- `copySync` added `clobber` option (before always would clobber, now if `clobber` is `false` it throws an error if the destination exists).
**Only works with files at the moment.**
- `createOutputStream()` added. See: [#118][#118]
0.16.5 / 2015-03-08
-------------------
- fixed `fs.move` when `clobber` is `true` and destination is a directory, it should clobber. [#114][#114]
0.16.4 / 2015-03-01
-------------------
- `fs.mkdirs` fix infinite loop on Windows. See: See https://github.com/substack/node-mkdirp/pull/74 and https://github.com/substack/node-mkdirp/issues/66
0.16.3 / 2015-01-28
-------------------
- reverted https://github.com/jprichardson/node-fs-extra/commit/1ee77c8a805eba5b99382a2591ff99667847c9c9
0.16.2 / 2015-01-28
-------------------
- fixed `fs.copy` for Node v0.8 (support is temporary and will be removed in the near future)
0.16.1 / 2015-01-28
-------------------
- if `setImmediate` is not available, fall back to `process.nextTick`
0.16.0 / 2015-01-28
-------------------
- bugfix `fs.move()` into itself. Closes [#104]
- bugfix `fs.move()` moving directory across device. Closes [#108]
- added coveralls support
- bugfix: nasty multiple callback `fs.copy()` bug. Closes [#98]
- misc fs.copy code cleanups
0.15.0 / 2015-01-21
-------------------
- dropped `ncp`, imported code in
- because of previous, now supports `io.js`
- `graceful-fs` is now a dependency
0.14.0 / 2015-01-05
-------------------
- changed `copy`/`copySync` from `fs.copy(src, dest, [filters], callback)` to `fs.copy(src, dest, [options], callback)` [#100][#100]
- removed mockfs tests for mkdirp (this may be temporary, but was getting in the way of other tests)
0.13.0 / 2014-12-10
-------------------
- removed `touch` and `touchSync` methods (they didn't handle permissions like UNIX touch)
- updated `"ncp": "^0.6.0"` to `"ncp": "^1.0.1"`
- imported `mkdirp` => `minimist` and `mkdirp` are no longer dependences, should now appease people who wanted `mkdirp` to be `--use_strict` safe. See [#59]([#59][#59])
0.12.0 / 2014-09-22
-------------------
- copy symlinks in `copySync()` [#85][#85]
0.11.1 / 2014-09-02
-------------------
- bugfix `copySync()` preserve file permissions [#80][#80]
0.11.0 / 2014-08-11
-------------------
- upgraded `"ncp": "^0.5.1"` to `"ncp": "^0.6.0"`
- upgrade `jsonfile": "^1.2.0"` to `jsonfile": "^2.0.0"` => on write, json files now have `\n` at end. Also adds `options.throws` to `readJsonSync()`
see https://github.com/jprichardson/node-jsonfile#readfilesyncfilename-options for more details.
0.10.0 / 2014-06-29
------------------
* bugfix: upgaded `"jsonfile": "~1.1.0"` to `"jsonfile": "^1.2.0"`, bumped minor because of `jsonfile` dep change
from `~` to `^`. [#67]
0.9.1 / 2014-05-22
------------------
* removed Node.js `0.8.x` support, `0.9.0` was published moments ago and should have been done there
0.9.0 / 2014-05-22
------------------
* upgraded `ncp` from `~0.4.2` to `^0.5.1`, [#58]
* upgraded `rimraf` from `~2.2.6` to `^2.2.8`
* upgraded `mkdirp` from `0.3.x` to `^0.5.0`
* added methods `ensureFile()`, `ensureFileSync()`
* added methods `ensureDir()`, `ensureDirSync()` [#31]
* added `move()` method. From: https://github.com/andrewrk/node-mv
0.8.1 / 2013-10-24
------------------
* copy failed to return an error to the callback if a file doesn't exist (ulikoehler [#38], [#39])
0.8.0 / 2013-10-14
------------------
* `filter` implemented on `copy()` and `copySync()`. (Srirangan / [#36])
0.7.1 / 2013-10-12
------------------
* `copySync()` implemented (Srirangan / [#33])
* updated to the latest `jsonfile` version `1.1.0` which gives `options` params for the JSON methods. Closes [#32]
0.7.0 / 2013-10-07
------------------
* update readme conventions
* `copy()` now works if destination directory does not exist. Closes [#29]
0.6.4 / 2013-09-05
------------------
* changed `homepage` field in package.json to remove NPM warning
0.6.3 / 2013-06-28
------------------
* changed JSON spacing default from `4` to `2` to follow Node conventions
* updated `jsonfile` dep
* updated `rimraf` dep
0.6.2 / 2013-06-28
------------------
* added .npmignore, [#25]
0.6.1 / 2013-05-14
------------------
* modified for `strict` mode, closes [#24]
* added `outputJson()/outputJsonSync()`, closes [#23]
0.6.0 / 2013-03-18
------------------
* removed node 0.6 support
* added node 0.10 support
* upgraded to latest `ncp` and `rimraf`.
* optional `graceful-fs` support. Closes [#17]
0.5.0 / 2013-02-03
------------------
* Removed `readTextFile`.
* Renamed `readJSONFile` to `readJSON` and `readJson`, same with write.
* Restructured documentation a bit. Added roadmap.
0.4.0 / 2013-01-28
------------------
* Set default spaces in `jsonfile` from 4 to 2.
* Updated `testutil` deps for tests.
* Renamed `touch()` to `createFile()`
* Added `outputFile()` and `outputFileSync()`
* Changed creation of testing diretories so the /tmp dir is not littered.
* Added `readTextFile()` and `readTextFileSync()`.
0.3.2 / 2012-11-01
------------------
* Added `touch()` and `touchSync()` methods.
0.3.1 / 2012-10-11
------------------
* Fixed some stray globals.
0.3.0 / 2012-10-09
------------------
* Removed all CoffeeScript from tests.
* Renamed `mkdir` to `mkdirs`/`mkdirp`.
0.2.1 / 2012-09-11
------------------
* Updated `rimraf` dep.
0.2.0 / 2012-09-10
------------------
* Rewrote module into JavaScript. (Must still rewrite tests into JavaScript)
* Added all methods of [jsonfile](https://github.com/jprichardson/node-jsonfile)
* Added Travis-CI.
0.1.3 / 2012-08-13
------------------
* Added method `readJSONFile`.
0.1.2 / 2012-06-15
------------------
* Bug fix: `deleteSync()` didn't exist.
* Verified Node v0.8 compatibility.
0.1.1 / 2012-06-15
------------------
* Fixed bug in `remove()`/`delete()` that wouldn't execute the function if a callback wasn't passed.
0.1.0 / 2012-05-31
------------------
* Renamed `copyFile()` to `copy()`. `copy()` can now copy directories (recursively) too.
* Renamed `rmrf()` to `remove()`.
* `remove()` aliased with `delete()`.
* Added `mkdirp` capabilities. Named: `mkdir()`. Hides Node.js native `mkdir()`.
* Instead of exporting the native `fs` module with new functions, I now copy over the native methods to a new object and export that instead.
0.0.4 / 2012-03-14
------------------
* Removed CoffeeScript dependency
0.0.3 / 2012-01-11
------------------
* Added methods rmrf and rmrfSync
* Moved tests from Jasmine to Mocha
[#344]: https://github.com/jprichardson/node-fs-extra/issues/344 "Licence Year"
[#343]: https://github.com/jprichardson/node-fs-extra/pull/343 "Add klaw-sync link to readme"
[#342]: https://github.com/jprichardson/node-fs-extra/pull/342 "allow preserveTimestamps when use move"
[#341]: https://github.com/jprichardson/node-fs-extra/issues/341 "mkdirp(path.dirname(dest) in move() logic needs cleaning up [question]"
[#340]: https://github.com/jprichardson/node-fs-extra/pull/340 "Move docs to seperate docs folder [documentation]"
[#339]: https://github.com/jprichardson/node-fs-extra/pull/339 "Remove walk() & walkSync() [feature-walk]"
[#338]: https://github.com/jprichardson/node-fs-extra/issues/338 "Remove walk() and walkSync() [feature-walk]"
[#337]: https://github.com/jprichardson/node-fs-extra/issues/337 "copy doesn't return a yieldable value"
[#336]: https://github.com/jprichardson/node-fs-extra/pull/336 "Docs enhanced walk sync [documentation, feature-walk]"
[#335]: https://github.com/jprichardson/node-fs-extra/pull/335 "Refactor move() tests [feature-move]"
[#334]: https://github.com/jprichardson/node-fs-extra/pull/334 "Cleanup lib/move/index.js [feature-move]"
[#333]: https://github.com/jprichardson/node-fs-extra/pull/333 "Rename clobber to overwrite [feature-copy, feature-move]"
[#332]: https://github.com/jprichardson/node-fs-extra/pull/332 "BREAKING: Drop Node v0.12 & io.js support"
[#331]: https://github.com/jprichardson/node-fs-extra/issues/331 "Add support for chmodr [enhancement, future]"
[#330]: https://github.com/jprichardson/node-fs-extra/pull/330 "BREAKING: Do not error when copy destination exists & clobber: false [feature-copy]"
[#329]: https://github.com/jprichardson/node-fs-extra/issues/329 "Does .walk() scale to large directories? [question]"
[#328]: https://github.com/jprichardson/node-fs-extra/issues/328 "Copying files corrupts [feature-copy, needs-confirmed]"
[#327]: https://github.com/jprichardson/node-fs-extra/pull/327 "Use writeStream 'finish' event instead of 'close' [bug, feature-copy]"
[#326]: https://github.com/jprichardson/node-fs-extra/issues/326 "fs.copy fails with chmod error when disk under heavy use [bug, feature-copy]"
[#325]: https://github.com/jprichardson/node-fs-extra/issues/325 "ensureDir is difficult to promisify [enhancement]"
[#324]: https://github.com/jprichardson/node-fs-extra/pull/324 "copySync() should apply filter to directories like copy() [bug, feature-copy]"
[#323]: https://github.com/jprichardson/node-fs-extra/issues/323 "Support for `dest` being a directory when using `copy*()`?"
[#322]: https://github.com/jprichardson/node-fs-extra/pull/322 "Add fs-promise as fs-extra-promise alternative"
[#321]: https://github.com/jprichardson/node-fs-extra/issues/321 "fs.copy() with clobber set to false return EEXIST error [feature-copy]"
[#320]: https://github.com/jprichardson/node-fs-extra/issues/320 "fs.copySync: Error: EPERM: operation not permitted, unlink "
[#319]: https://github.com/jprichardson/node-fs-extra/issues/319 "Create directory if not exists"
[#318]: https://github.com/jprichardson/node-fs-extra/issues/318 "Support glob patterns [enhancement, future]"
[#317]: https://github.com/jprichardson/node-fs-extra/pull/317 "Adding copy sync test for src file without write perms"
[#316]: https://github.com/jprichardson/node-fs-extra/pull/316 "Remove move()'s broken limit option [feature-move]"
[#315]: https://github.com/jprichardson/node-fs-extra/pull/315 "Fix move clobber tests to work around graceful-fs bug."
[#314]: https://github.com/jprichardson/node-fs-extra/issues/314 "move() limit option [documentation, enhancement, feature-move]"
[#313]: https://github.com/jprichardson/node-fs-extra/pull/313 "Test that remove() ignores glob characters."
[#312]: https://github.com/jprichardson/node-fs-extra/pull/312 "Enhance walkSync() to return items with path and stats [feature-walk]"
[#311]: https://github.com/jprichardson/node-fs-extra/issues/311 "move() not work when dest name not provided [feature-move]"
[#310]: https://github.com/jprichardson/node-fs-extra/issues/310 "Edit walkSync to return items like what walk emits [documentation, enhancement, feature-walk]"
[#309]: https://github.com/jprichardson/node-fs-extra/issues/309 "moveSync support [enhancement, feature-move]"
[#308]: https://github.com/jprichardson/node-fs-extra/pull/308 "Fix incorrect anchor link"
[#307]: https://github.com/jprichardson/node-fs-extra/pull/307 "Fix coverage"
[#306]: https://github.com/jprichardson/node-fs-extra/pull/306 "Update devDeps, fix lint error"
[#305]: https://github.com/jprichardson/node-fs-extra/pull/305 "Re-add Coveralls"
[#304]: https://github.com/jprichardson/node-fs-extra/pull/304 "Remove path-is-absolute [enhancement]"
[#303]: https://github.com/jprichardson/node-fs-extra/pull/303 "Document copySync filter inconsistency [documentation, feature-copy]"
[#302]: https://github.com/jprichardson/node-fs-extra/pull/302 "fix(console): depreciated -> deprecated"
[#301]: https://github.com/jprichardson/node-fs-extra/pull/301 "Remove chmod call from copySync [feature-copy]"
[#300]: https://github.com/jprichardson/node-fs-extra/pull/300 "Inline Rimraf [enhancement, feature-move, feature-remove]"
[#299]: https://github.com/jprichardson/node-fs-extra/pull/299 "Warn when filter is a RegExp [feature-copy]"
[#298]: https://github.com/jprichardson/node-fs-extra/issues/298 "API Docs [documentation]"
[#297]: https://github.com/jprichardson/node-fs-extra/pull/297 "Warn about using preserveTimestamps on 32-bit node"
[#296]: https://github.com/jprichardson/node-fs-extra/pull/296 "Improve EEXIST error message for copySync [enhancement]"
[#295]: https://github.com/jprichardson/node-fs-extra/pull/295 "Depreciate using regular expressions for copy's filter option [documentation]"
[#294]: https://github.com/jprichardson/node-fs-extra/pull/294 "BREAKING: Refactor lib/copy/ncp.js [feature-copy]"
[#293]: https://github.com/jprichardson/node-fs-extra/pull/293 "Update CI configs"
[#292]: https://github.com/jprichardson/node-fs-extra/issues/292 "Rewrite lib/copy/ncp.js [enhancement, feature-copy]"
[#291]: https://github.com/jprichardson/node-fs-extra/pull/291 "Escape '$' in replacement string for async file copying"
[#290]: https://github.com/jprichardson/node-fs-extra/issues/290 "Exclude files pattern while copying using copy.config.js [question]"
[#289]: https://github.com/jprichardson/node-fs-extra/pull/289 "(Closes #271) lib/util/utimes: properly close file descriptors in the event of an error"
[#288]: https://github.com/jprichardson/node-fs-extra/pull/288 "(Closes #271) lib/util/utimes: properly close file descriptors in the event of an error"
[#287]: https://github.com/jprichardson/node-fs-extra/issues/287 "emptyDir() callback arguments are inconsistent [enhancement, feature-remove]"
[#286]: https://github.com/jprichardson/node-fs-extra/pull/286 "Added walkSync function"
[#285]: https://github.com/jprichardson/node-fs-extra/issues/285 "CITGM test failing on s390"
[#284]: https://github.com/jprichardson/node-fs-extra/issues/284 "outputFile method is missing a check to determine if existing item is a folder or not"
[#283]: https://github.com/jprichardson/node-fs-extra/pull/283 "Apply filter also on directories and symlinks for copySync()"
[#282]: https://github.com/jprichardson/node-fs-extra/pull/282 "Apply filter also on directories and symlinks for copySync()"
[#281]: https://github.com/jprichardson/node-fs-extra/issues/281 "remove function executes 'successfully' but doesn't do anything?"
[#280]: https://github.com/jprichardson/node-fs-extra/pull/280 "Disable rimraf globbing"
[#279]: https://github.com/jprichardson/node-fs-extra/issues/279 "Some code is vendored instead of included [awaiting-reply]"
[#278]: https://github.com/jprichardson/node-fs-extra/issues/278 "copy() does not preserve file/directory ownership"
[#277]: https://github.com/jprichardson/node-fs-extra/pull/277 "Mention defaults for clobber and dereference options"
[#276]: https://github.com/jprichardson/node-fs-extra/issues/276 "Cannot connect to Shared Folder [awaiting-reply]"
[#275]: https://github.com/jprichardson/node-fs-extra/issues/275 "EMFILE, too many open files on Mac OS with JSON API"
[#274]: https://github.com/jprichardson/node-fs-extra/issues/274 "Use with memory-fs? [enhancement, future]"
[#273]: https://github.com/jprichardson/node-fs-extra/pull/273 "tests: rename `remote.test.js` to `remove.test.js`"
[#272]: https://github.com/jprichardson/node-fs-extra/issues/272 "Copy clobber flag never err even when true [bug, feature-copy]"
[#271]: https://github.com/jprichardson/node-fs-extra/issues/271 "Unclosed file handle on futimes error"
[#270]: https://github.com/jprichardson/node-fs-extra/issues/270 "copy not working as desired on Windows [feature-copy, platform-windows]"
[#269]: https://github.com/jprichardson/node-fs-extra/issues/269 "Copying with preserveTimeStamps: true is inaccurate using 32bit node [feature-copy]"
[#268]: https://github.com/jprichardson/node-fs-extra/pull/268 "port fix for mkdirp issue #111"
[#267]: https://github.com/jprichardson/node-fs-extra/issues/267 "WARN deprecated wrench@1.5.9: wrench.js is deprecated!"
[#266]: https://github.com/jprichardson/node-fs-extra/issues/266 "fs-extra"
[#265]: https://github.com/jprichardson/node-fs-extra/issues/265 "Link the `fs.stat fs.exists` etc. methods for replace the `fs` module forever?"
[#264]: https://github.com/jprichardson/node-fs-extra/issues/264 "Renaming a file using move fails when a file inside is open (at least on windows) [wont-fix]"
[#263]: https://github.com/jprichardson/node-fs-extra/issues/263 "ENOSYS: function not implemented, link [needs-confirmed]"
[#262]: https://github.com/jprichardson/node-fs-extra/issues/262 "Add .exists() and .existsSync()"
[#261]: https://github.com/jprichardson/node-fs-extra/issues/261 "Cannot read property 'prototype' of undefined"
[#260]: https://github.com/jprichardson/node-fs-extra/pull/260 "use more specific path for method require"
[#259]: https://github.com/jprichardson/node-fs-extra/issues/259 "Feature Request: isEmpty"
[#258]: https://github.com/jprichardson/node-fs-extra/issues/258 "copy files does not preserve file timestamp"
[#257]: https://github.com/jprichardson/node-fs-extra/issues/257 "Copying a file on windows fails"
[#256]: https://github.com/jprichardson/node-fs-extra/pull/256 "Updated Readme "
[#255]: https://github.com/jprichardson/node-fs-extra/issues/255 "Update rimraf required version"
[#254]: https://github.com/jprichardson/node-fs-extra/issues/254 "request for readTree, readTreeSync, walkSync method"
[#253]: https://github.com/jprichardson/node-fs-extra/issues/253 "outputFile does not touch mtime when file exists"
[#252]: https://github.com/jprichardson/node-fs-extra/pull/252 "Fixing problem when copying file with no write permission"
[#251]: https://github.com/jprichardson/node-fs-extra/issues/251 "Just wanted to say thank you"
[#250]: https://github.com/jprichardson/node-fs-extra/issues/250 "`fs.remove()` not removing files (works with `rm -rf`)"
[#249]: https://github.com/jprichardson/node-fs-extra/issues/249 "Just a Question ... Remove Servers"
[#248]: https://github.com/jprichardson/node-fs-extra/issues/248 "Allow option to not preserve permissions for copy"
[#247]: https://github.com/jprichardson/node-fs-extra/issues/247 "Add TypeScript typing directly in the fs-extra package"
[#246]: https://github.com/jprichardson/node-fs-extra/issues/246 "fse.remove() && fse.removeSync() don't throw error on ENOENT file"
[#245]: https://github.com/jprichardson/node-fs-extra/issues/245 "filter for empty dir [enhancement]"
[#244]: https://github.com/jprichardson/node-fs-extra/issues/244 "copySync doesn't apply the filter to directories"
[#243]: https://github.com/jprichardson/node-fs-extra/issues/243 "Can I request fs.walk() to be synchronous?"
[#242]: https://github.com/jprichardson/node-fs-extra/issues/242 "Accidentally truncates file names ending with $$ [bug, feature-copy]"
[#241]: https://github.com/jprichardson/node-fs-extra/pull/241 "Remove link to createOutputStream"
[#240]: https://github.com/jprichardson/node-fs-extra/issues/240 "walkSync request"
[#239]: https://github.com/jprichardson/node-fs-extra/issues/239 "Depreciate regular expressions for copy's filter [documentation, feature-copy]"
[#238]: https://github.com/jprichardson/node-fs-extra/issues/238 "Can't write to files while in a worker thread."
[#237]: https://github.com/jprichardson/node-fs-extra/issues/237 ".ensureDir(..) fails silently when passed an invalid path..."
[#236]: https://github.com/jprichardson/node-fs-extra/issues/236 "[Removed] Filed under wrong repo"
[#235]: https://github.com/jprichardson/node-fs-extra/pull/235 "Adds symlink dereference option to `fse.copySync` (#191)"
[#234]: https://github.com/jprichardson/node-fs-extra/issues/234 "ensureDirSync fails silent when EACCES: permission denied on travis-ci"
[#233]: https://github.com/jprichardson/node-fs-extra/issues/233 "please make sure the first argument in callback is error object [feature-copy]"
[#232]: https://github.com/jprichardson/node-fs-extra/issues/232 "Copy a folder content to its child folder. "
[#231]: https://github.com/jprichardson/node-fs-extra/issues/231 "Adding read/write/output functions for YAML"
[#230]: https://github.com/jprichardson/node-fs-extra/pull/230 "throw error if src and dest are the same to avoid zeroing out + test"
[#229]: https://github.com/jprichardson/node-fs-extra/pull/229 "fix 'TypeError: callback is not a function' in emptyDir"
[#228]: https://github.com/jprichardson/node-fs-extra/pull/228 "Throw error when target is empty so file is not accidentally zeroed out"
[#227]: https://github.com/jprichardson/node-fs-extra/issues/227 "Uncatchable errors when there are invalid arguments [feature-move]"
[#226]: https://github.com/jprichardson/node-fs-extra/issues/226 "Moving to the current directory"
[#225]: https://github.com/jprichardson/node-fs-extra/issues/225 "EBUSY: resource busy or locked, unlink"
[#224]: https://github.com/jprichardson/node-fs-extra/issues/224 "fse.copy ENOENT error"
[#223]: https://github.com/jprichardson/node-fs-extra/issues/223 "Suspicious behavior of fs.existsSync"
[#222]: https://github.com/jprichardson/node-fs-extra/pull/222 "A clearer description of emtpyDir function"
[#221]: https://github.com/jprichardson/node-fs-extra/pull/221 "Update README.md"
[#220]: https://github.com/jprichardson/node-fs-extra/pull/220 "Non-breaking feature: add option 'passStats' to copy methods."
[#219]: https://github.com/jprichardson/node-fs-extra/pull/219 "Add closing parenthesis in copySync example"
[#218]: https://github.com/jprichardson/node-fs-extra/pull/218 "fix #187 #70 options.filter bug"
[#217]: https://github.com/jprichardson/node-fs-extra/pull/217 "fix #187 #70 options.filter bug"
[#216]: https://github.com/jprichardson/node-fs-extra/pull/216 "fix #187 #70 options.filter bug"
[#215]: https://github.com/jprichardson/node-fs-extra/pull/215 "fse.copy throws error when only src and dest provided [bug, documentation, feature-copy]"
[#214]: https://github.com/jprichardson/node-fs-extra/pull/214 "Fixing copySync anchor tag"
[#213]: https://github.com/jprichardson/node-fs-extra/issues/213 "Merge extfs with this repo"
[#212]: https://github.com/jprichardson/node-fs-extra/pull/212 "Update year to 2016 in README.md and LICENSE"
[#211]: https://github.com/jprichardson/node-fs-extra/issues/211 "Not copying all files"
[#210]: https://github.com/jprichardson/node-fs-extra/issues/210 "copy/copySync behave differently when copying a symbolic file [bug, documentation, feature-copy]"
[#209]: https://github.com/jprichardson/node-fs-extra/issues/209 "In Windows invalid directory name causes infinite loop in ensureDir(). [bug]"
[#208]: https://github.com/jprichardson/node-fs-extra/pull/208 "fix options.preserveTimestamps to false in copy-sync by default [feature-copy]"
[#207]: https://github.com/jprichardson/node-fs-extra/issues/207 "Add `compare` suite of functions"
[#206]: https://github.com/jprichardson/node-fs-extra/issues/206 "outputFileSync"
[#205]: https://github.com/jprichardson/node-fs-extra/issues/205 "fix documents about copy/copySync [documentation, feature-copy]"
[#204]: https://github.com/jprichardson/node-fs-extra/pull/204 "allow copy of block and character device files"
[#203]: https://github.com/jprichardson/node-fs-extra/issues/203 "copy method's argument options couldn't be undefined [bug, feature-copy]"
[#202]: https://github.com/jprichardson/node-fs-extra/issues/202 "why there is not a walkSync method?"
[#201]: https://github.com/jprichardson/node-fs-extra/issues/201 "clobber for directories [feature-copy, future]"
[#200]: https://github.com/jprichardson/node-fs-extra/issues/200 "'copySync' doesn't work in sync"
[#199]: https://github.com/jprichardson/node-fs-extra/issues/199 "fs.copySync fails if user does not own file [bug, feature-copy]"
[#198]: https://github.com/jprichardson/node-fs-extra/issues/198 "handle copying between identical files [feature-copy]"
[#197]: https://github.com/jprichardson/node-fs-extra/issues/197 "Missing documentation for `outputFile` `options` 3rd parameter [documentation]"
[#196]: https://github.com/jprichardson/node-fs-extra/issues/196 "copy filter: async function and/or function called with `fs.stat` result [future]"
[#195]: https://github.com/jprichardson/node-fs-extra/issues/195 "How to override with outputFile?"
[#194]: https://github.com/jprichardson/node-fs-extra/pull/194 "allow ensureFile(Sync) to provide data to be written to created file"
[#193]: https://github.com/jprichardson/node-fs-extra/issues/193 "`fs.copy` fails silently if source file is /dev/null [bug, feature-copy]"
[#192]: https://github.com/jprichardson/node-fs-extra/issues/192 "Remove fs.createOutputStream()"
[#191]: https://github.com/jprichardson/node-fs-extra/issues/191 "How to copy symlinks to target as normal folders [feature-copy]"
[#190]: https://github.com/jprichardson/node-fs-extra/pull/190 "copySync to overwrite destination file if readonly and clobber true"
[#189]: https://github.com/jprichardson/node-fs-extra/pull/189 "move.test fix to support CRLF on Windows"
[#188]: https://github.com/jprichardson/node-fs-extra/issues/188 "move.test failing on windows platform"
[#187]: https://github.com/jprichardson/node-fs-extra/issues/187 "Not filter each file, stops on first false [feature-copy]"
[#186]: https://github.com/jprichardson/node-fs-extra/issues/186 "Do you need a .size() function in this module? [future]"
[#185]: https://github.com/jprichardson/node-fs-extra/issues/185 "Doesn't work on NodeJS v4.x"
[#184]: https://github.com/jprichardson/node-fs-extra/issues/184 "CLI equivalent for fs-extra"
[#183]: https://github.com/jprichardson/node-fs-extra/issues/183 "with clobber true, copy and copySync behave differently if destination file is read only [bug, feature-copy]"
[#182]: https://github.com/jprichardson/node-fs-extra/issues/182 "ensureDir(dir, callback) second callback parameter not specified"
[#181]: https://github.com/jprichardson/node-fs-extra/issues/181 "Add ability to remove file securely [enhancement, wont-fix]"
[#180]: https://github.com/jprichardson/node-fs-extra/issues/180 "Filter option doesn't work the same way in copy and copySync [bug, feature-copy]"
[#179]: https://github.com/jprichardson/node-fs-extra/issues/179 "Include opendir"
[#178]: https://github.com/jprichardson/node-fs-extra/issues/178 "ENOTEMPTY is thrown on removeSync "
[#177]: https://github.com/jprichardson/node-fs-extra/issues/177 "fix `remove()` wildcards (introduced by rimraf) [feature-remove]"
[#176]: https://github.com/jprichardson/node-fs-extra/issues/176 "createOutputStream doesn't emit 'end' event"
[#175]: https://github.com/jprichardson/node-fs-extra/issues/175 "[Feature Request].moveSync support [feature-move, future]"
[#174]: https://github.com/jprichardson/node-fs-extra/pull/174 "Fix copy formatting and document options.filter"
[#173]: https://github.com/jprichardson/node-fs-extra/issues/173 "Feature Request: writeJson should mkdirs"
[#172]: https://github.com/jprichardson/node-fs-extra/issues/172 "rename `clobber` flags to `overwrite`"
[#171]: https://github.com/jprichardson/node-fs-extra/issues/171 "remove unnecessary aliases"
[#170]: https://github.com/jprichardson/node-fs-extra/pull/170 "More robust handling of errors moving across virtual drives"
[#169]: https://github.com/jprichardson/node-fs-extra/pull/169 "suppress ensureLink & ensureSymlink dest exists error"
[#168]: https://github.com/jprichardson/node-fs-extra/pull/168 "suppress ensurelink dest exists error"
[#167]: https://github.com/jprichardson/node-fs-extra/pull/167 "Adds basic (string, buffer) support for ensureFile content [future]"
[#166]: https://github.com/jprichardson/node-fs-extra/pull/166 "Adds basic (string, buffer) support for ensureFile content"
[#165]: https://github.com/jprichardson/node-fs-extra/pull/165 "ensure for link & symlink"
[#164]: https://github.com/jprichardson/node-fs-extra/issues/164 "Feature Request: ensureFile to take optional argument for file content"
[#163]: https://github.com/jprichardson/node-fs-extra/issues/163 "ouputJson not formatted out of the box [bug]"
[#162]: https://github.com/jprichardson/node-fs-extra/pull/162 "ensure symlink & link"
[#161]: https://github.com/jprichardson/node-fs-extra/pull/161 "ensure symlink & link"
[#160]: https://github.com/jprichardson/node-fs-extra/pull/160 "ensure symlink & link"
[#159]: https://github.com/jprichardson/node-fs-extra/pull/159 "ensure symlink & link"
[#158]: https://github.com/jprichardson/node-fs-extra/issues/158 "Feature Request: ensureLink and ensureSymlink methods"
[#157]: https://github.com/jprichardson/node-fs-extra/issues/157 "writeJson isn't formatted"
[#156]: https://github.com/jprichardson/node-fs-extra/issues/156 "Promise.promisifyAll doesn't work for some methods"
[#155]: https://github.com/jprichardson/node-fs-extra/issues/155 "Readme"
[#154]: https://github.com/jprichardson/node-fs-extra/issues/154 "/tmp/millis-test-sync"
[#153]: https://github.com/jprichardson/node-fs-extra/pull/153 "Make preserveTimes also work on read-only files. Closes #152"
[#152]: https://github.com/jprichardson/node-fs-extra/issues/152 "fs.copy fails for read-only files with preserveTimestamp=true [feature-copy]"
[#151]: https://github.com/jprichardson/node-fs-extra/issues/151 "TOC does not work correctly on npm [documentation]"
[#150]: https://github.com/jprichardson/node-fs-extra/issues/150 "Remove test file fixtures, create with code."
[#149]: https://github.com/jprichardson/node-fs-extra/issues/149 "/tmp/millis-test-sync"
[#148]: https://github.com/jprichardson/node-fs-extra/issues/148 "split out `Sync` methods in documentation"
[#147]: https://github.com/jprichardson/node-fs-extra/issues/147 "Adding rmdirIfEmpty"
[#146]: https://github.com/jprichardson/node-fs-extra/pull/146 "ensure test.js works"
[#145]: https://github.com/jprichardson/node-fs-extra/issues/145 "Add `fs.exists` and `fs.existsSync` if it doesn't exist."
[#144]: https://github.com/jprichardson/node-fs-extra/issues/144 "tests failing"
[#143]: https://github.com/jprichardson/node-fs-extra/issues/143 "update graceful-fs"
[#142]: https://github.com/jprichardson/node-fs-extra/issues/142 "PrependFile Feature"
[#141]: https://github.com/jprichardson/node-fs-extra/pull/141 "Add option to preserve timestamps"
[#140]: https://github.com/jprichardson/node-fs-extra/issues/140 "Json file reading fails with 'utf8'"
[#139]: https://github.com/jprichardson/node-fs-extra/pull/139 "Preserve file timestamp on copy. Closes #138"
[#138]: https://github.com/jprichardson/node-fs-extra/issues/138 "Preserve timestamps on copying files"
[#137]: https://github.com/jprichardson/node-fs-extra/issues/137 "outputFile/outputJson: Unexpected end of input"
[#136]: https://github.com/jprichardson/node-fs-extra/pull/136 "Update license attribute"
[#135]: https://github.com/jprichardson/node-fs-extra/issues/135 "emptyDir throws Error if no callback is provided"
[#134]: https://github.com/jprichardson/node-fs-extra/pull/134 "Handle EEXIST error when clobbering dir"
[#133]: https://github.com/jprichardson/node-fs-extra/pull/133 "Travis runs with `sudo: false`"
[#132]: https://github.com/jprichardson/node-fs-extra/pull/132 "isDirectory method"
[#131]: https://github.com/jprichardson/node-fs-extra/issues/131 "copySync is not working iojs 1.8.4 on linux [feature-copy]"
[#130]: https://github.com/jprichardson/node-fs-extra/pull/130 "Please review additional features."
[#129]: https://github.com/jprichardson/node-fs-extra/pull/129 "can you review this feature?"
[#128]: https://github.com/jprichardson/node-fs-extra/issues/128 "fsExtra.move(filepath, newPath) broken;"
[#127]: https://github.com/jprichardson/node-fs-extra/issues/127 "consider using fs.access to remove deprecated warnings for fs.exists"
[#126]: https://github.com/jprichardson/node-fs-extra/issues/126 " TypeError: Object #<Object> has no method 'access'"
[#125]: https://github.com/jprichardson/node-fs-extra/issues/125 "Question: What do the *Sync function do different from non-sync"
[#124]: https://github.com/jprichardson/node-fs-extra/issues/124 "move with clobber option 'ENOTEMPTY'"
[#123]: https://github.com/jprichardson/node-fs-extra/issues/123 "Only copy the content of a directory"
[#122]: https://github.com/jprichardson/node-fs-extra/pull/122 "Update section links in README to match current section ids."
[#121]: https://github.com/jprichardson/node-fs-extra/issues/121 "emptyDir is undefined"
[#120]: https://github.com/jprichardson/node-fs-extra/issues/120 "usage bug caused by shallow cloning methods of 'graceful-fs'"
[#119]: https://github.com/jprichardson/node-fs-extra/issues/119 "mkdirs and ensureDir never invoke callback and consume CPU indefinitely if provided a path with invalid characters on Windows"
[#118]: https://github.com/jprichardson/node-fs-extra/pull/118 "createOutputStream"
[#117]: https://github.com/jprichardson/node-fs-extra/pull/117 "Fixed issue with slash separated paths on windows"
[#116]: https://github.com/jprichardson/node-fs-extra/issues/116 "copySync can only copy directories not files [documentation, feature-copy]"
[#115]: https://github.com/jprichardson/node-fs-extra/issues/115 ".Copy & .CopySync [feature-copy]"
[#114]: https://github.com/jprichardson/node-fs-extra/issues/114 "Fails to move (rename) directory to non-empty directory even with clobber: true"
[#113]: https://github.com/jprichardson/node-fs-extra/issues/113 "fs.copy seems to callback early if the destination file already exists"
[#112]: https://github.com/jprichardson/node-fs-extra/pull/112 "Copying a file into an existing directory"
[#111]: https://github.com/jprichardson/node-fs-extra/pull/111 "Moving a file into an existing directory "
[#110]: https://github.com/jprichardson/node-fs-extra/pull/110 "Moving a file into an existing directory"
[#109]: https://github.com/jprichardson/node-fs-extra/issues/109 "fs.move across windows drives fails"
[#108]: https://github.com/jprichardson/node-fs-extra/issues/108 "fse.move directories across multiple devices doesn't work"
[#107]: https://github.com/jprichardson/node-fs-extra/pull/107 "Check if dest path is an existing dir and copy or move source in it"
[#106]: https://github.com/jprichardson/node-fs-extra/issues/106 "fse.copySync crashes while copying across devices D: [feature-copy]"
[#105]: https://github.com/jprichardson/node-fs-extra/issues/105 "fs.copy hangs on iojs"
[#104]: https://github.com/jprichardson/node-fs-extra/issues/104 "fse.move deletes folders [bug]"
[#103]: https://github.com/jprichardson/node-fs-extra/issues/103 "Error: EMFILE with copy"
[#102]: https://github.com/jprichardson/node-fs-extra/issues/102 "touch / touchSync was removed ?"
[#101]: https://github.com/jprichardson/node-fs-extra/issues/101 "fs-extra promisified"
[#100]: https://github.com/jprichardson/node-fs-extra/pull/100 "copy: options object or filter to pass to ncp"
[#99]: https://github.com/jprichardson/node-fs-extra/issues/99 "ensureDir() modes [future]"
[#98]: https://github.com/jprichardson/node-fs-extra/issues/98 "fs.copy() incorrect async behavior [bug]"
[#97]: https://github.com/jprichardson/node-fs-extra/pull/97 "use path.join; fix copySync bug"
[#96]: https://github.com/jprichardson/node-fs-extra/issues/96 "destFolderExists in copySync is always undefined."
[#95]: https://github.com/jprichardson/node-fs-extra/pull/95 "Using graceful-ncp instead of ncp"
[#94]: https://github.com/jprichardson/node-fs-extra/issues/94 "Error: EEXIST, file already exists '../mkdirp/bin/cmd.js' on fs.copySync() [enhancement, feature-copy]"
[#93]: https://github.com/jprichardson/node-fs-extra/issues/93 "Confusing error if drive not mounted [enhancement]"
[#92]: https://github.com/jprichardson/node-fs-extra/issues/92 "Problems with Bluebird"
[#91]: https://github.com/jprichardson/node-fs-extra/issues/91 "fs.copySync('/test', '/haha') is different with 'cp -r /test /haha' [enhancement]"
[#90]: https://github.com/jprichardson/node-fs-extra/issues/90 "Folder creation and file copy is Happening in 64 bit machine but not in 32 bit machine"
[#89]: https://github.com/jprichardson/node-fs-extra/issues/89 "Error: EEXIST using fs-extra's fs.copy to copy a directory on Windows"
[#88]: https://github.com/jprichardson/node-fs-extra/issues/88 "Stacking those libraries"
[#87]: https://github.com/jprichardson/node-fs-extra/issues/87 "createWriteStream + outputFile = ?"
[#86]: https://github.com/jprichardson/node-fs-extra/issues/86 "no moveSync?"
[#85]: https://github.com/jprichardson/node-fs-extra/pull/85 "Copy symlinks in copySync"
[#84]: https://github.com/jprichardson/node-fs-extra/issues/84 "Push latest version to npm ?"
[#83]: https://github.com/jprichardson/node-fs-extra/issues/83 "Prevent copying a directory into itself [feature-copy]"
[#82]: https://github.com/jprichardson/node-fs-extra/pull/82 "README updates for move"
[#81]: https://github.com/jprichardson/node-fs-extra/issues/81 "fd leak after fs.move"
[#80]: https://github.com/jprichardson/node-fs-extra/pull/80 "Preserve file mode in copySync"
[#79]: https://github.com/jprichardson/node-fs-extra/issues/79 "fs.copy only .html file empty"
[#78]: https://github.com/jprichardson/node-fs-extra/pull/78 "copySync was not applying filters to directories"
[#77]: https://github.com/jprichardson/node-fs-extra/issues/77 "Create README reference to bluebird"
[#76]: https://github.com/jprichardson/node-fs-extra/issues/76 "Create README reference to typescript"
[#75]: https://github.com/jprichardson/node-fs-extra/issues/75 "add glob as a dep? [question]"
[#74]: https://github.com/jprichardson/node-fs-extra/pull/74 "including new emptydir module"
[#73]: https://github.com/jprichardson/node-fs-extra/pull/73 "add dependency status in readme"
[#72]: https://github.com/jprichardson/node-fs-extra/pull/72 "Use svg instead of png to get better image quality"
[#71]: https://github.com/jprichardson/node-fs-extra/issues/71 "fse.copy not working on Windows 7 x64 OS, but, copySync does work"
[#70]: https://github.com/jprichardson/node-fs-extra/issues/70 "Not filter each file, stops on first false [bug]"
[#69]: https://github.com/jprichardson/node-fs-extra/issues/69 "How to check if folder exist and read the folder name"
[#68]: https://github.com/jprichardson/node-fs-extra/issues/68 "consider flag to readJsonSync (throw false) [enhancement]"
[#67]: https://github.com/jprichardson/node-fs-extra/issues/67 "docs for readJson incorrectly states that is accepts options"
[#66]: https://github.com/jprichardson/node-fs-extra/issues/66 "ENAMETOOLONG"
[#65]: https://github.com/jprichardson/node-fs-extra/issues/65 "exclude filter in fs.copy"
[#64]: https://github.com/jprichardson/node-fs-extra/issues/64 "Announce: mfs - monitor your fs-extra calls"
[#63]: https://github.com/jprichardson/node-fs-extra/issues/63 "Walk"
[#62]: https://github.com/jprichardson/node-fs-extra/issues/62 "npm install fs-extra doesn't work"
[#61]: https://github.com/jprichardson/node-fs-extra/issues/61 "No longer supports node 0.8 due to use of `^` in package.json dependencies"
[#60]: https://github.com/jprichardson/node-fs-extra/issues/60 "chmod & chown for mkdirs"
[#59]: https://github.com/jprichardson/node-fs-extra/issues/59 "Consider including mkdirp and making fs-extra '--use_strict' safe [question]"
[#58]: https://github.com/jprichardson/node-fs-extra/issues/58 "Stack trace not included in fs.copy error"
[#57]: https://github.com/jprichardson/node-fs-extra/issues/57 "Possible to include wildcards in delete?"
[#56]: https://github.com/jprichardson/node-fs-extra/issues/56 "Crash when have no access to write to destination file in copy "
[#55]: https://github.com/jprichardson/node-fs-extra/issues/55 "Is it possible to have any console output similar to Grunt copy module?"
[#54]: https://github.com/jprichardson/node-fs-extra/issues/54 "`copy` does not preserve file ownership and permissons"
[#53]: https://github.com/jprichardson/node-fs-extra/issues/53 "outputFile() - ability to write data in appending mode"
[#52]: https://github.com/jprichardson/node-fs-extra/pull/52 "This fixes (what I think) is a bug in copySync"
[#51]: https://github.com/jprichardson/node-fs-extra/pull/51 "Add a Bitdeli Badge to README"
[#50]: https://github.com/jprichardson/node-fs-extra/issues/50 "Replace mechanism in createFile"
[#49]: https://github.com/jprichardson/node-fs-extra/pull/49 "update rimraf to v2.2.6"
[#48]: https://github.com/jprichardson/node-fs-extra/issues/48 "fs.copy issue [bug]"
[#47]: https://github.com/jprichardson/node-fs-extra/issues/47 "Bug in copy - callback called on readStream 'close' - Fixed in ncp 0.5.0"
[#46]: https://github.com/jprichardson/node-fs-extra/pull/46 "update copyright year"
[#45]: https://github.com/jprichardson/node-fs-extra/pull/45 "Added note about fse.outputFile() being the one that overwrites"
[#44]: https://github.com/jprichardson/node-fs-extra/pull/44 "Proposal: Stream support"
[#43]: https://github.com/jprichardson/node-fs-extra/issues/43 "Better error reporting "
[#42]: https://github.com/jprichardson/node-fs-extra/issues/42 "Performance issue?"
[#41]: https://github.com/jprichardson/node-fs-extra/pull/41 "There does seem to be a synchronous version now"
[#40]: https://github.com/jprichardson/node-fs-extra/issues/40 "fs.copy throw unexplained error ENOENT, utime "
[#39]: https://github.com/jprichardson/node-fs-extra/pull/39 "Added regression test for copy() return callback on error"
[#38]: https://github.com/jprichardson/node-fs-extra/pull/38 "Return err in copy() fstat cb, because stat could be undefined or null"
[#37]: https://github.com/jprichardson/node-fs-extra/issues/37 "Maybe include a line reader? [enhancement, question]"
[#36]: https://github.com/jprichardson/node-fs-extra/pull/36 "`filter` parameter `fs.copy` and `fs.copySync`"
[#35]: https://github.com/jprichardson/node-fs-extra/pull/35 "`filter` parameter `fs.copy` and `fs.copySync` "
[#34]: https://github.com/jprichardson/node-fs-extra/issues/34 "update docs to include options for JSON methods [enhancement]"
[#33]: https://github.com/jprichardson/node-fs-extra/pull/33 "fs_extra.copySync"
[#32]: https://github.com/jprichardson/node-fs-extra/issues/32 "update to latest jsonfile [enhancement]"
[#31]: https://github.com/jprichardson/node-fs-extra/issues/31 "Add ensure methods [enhancement]"
[#30]: https://github.com/jprichardson/node-fs-extra/issues/30 "update package.json optional dep `graceful-fs`"
[#29]: https://github.com/jprichardson/node-fs-extra/issues/29 "Copy failing if dest directory doesn't exist. Is this intended?"
[#28]: https://github.com/jprichardson/node-fs-extra/issues/28 "homepage field must be a string url. Deleted."
[#27]: https://github.com/jprichardson/node-fs-extra/issues/27 "Update Readme"
[#26]: https://github.com/jprichardson/node-fs-extra/issues/26 "Add readdir recursive method. [enhancement]"
[#25]: https://github.com/jprichardson/node-fs-extra/pull/25 "adding an `.npmignore` file"
[#24]: https://github.com/jprichardson/node-fs-extra/issues/24 "[bug] cannot run in strict mode [bug]"
[#23]: https://github.com/jprichardson/node-fs-extra/issues/23 "`writeJSON()` should create parent directories"
[#22]: https://github.com/jprichardson/node-fs-extra/pull/22 "Add a limit option to mkdirs()"
[#21]: https://github.com/jprichardson/node-fs-extra/issues/21 "touch() in 0.10.0"
[#20]: https://github.com/jprichardson/node-fs-extra/issues/20 "fs.remove yields callback before directory is really deleted"
[#19]: https://github.com/jprichardson/node-fs-extra/issues/19 "fs.copy err is empty array"
[#18]: https://github.com/jprichardson/node-fs-extra/pull/18 "Exposed copyFile Function"
[#17]: https://github.com/jprichardson/node-fs-extra/issues/17 "Use `require('graceful-fs')` if found instead of `require('fs')`"
[#16]: https://github.com/jprichardson/node-fs-extra/pull/16 "Update README.md"
[#15]: https://github.com/jprichardson/node-fs-extra/issues/15 "Implement cp -r but sync aka copySync. [enhancement]"
[#14]: https://github.com/jprichardson/node-fs-extra/issues/14 "fs.mkdirSync is broken in 0.3.1"
[#13]: https://github.com/jprichardson/node-fs-extra/issues/13 "Thoughts on including a directory tree / file watcher? [enhancement, question]"
[#12]: https://github.com/jprichardson/node-fs-extra/issues/12 "copyFile & copyFileSync are global"
[#11]: https://github.com/jprichardson/node-fs-extra/issues/11 "Thoughts on including a file walker? [enhancement, question]"
[#10]: https://github.com/jprichardson/node-fs-extra/issues/10 "move / moveFile API [enhancement]"
[#9]: https://github.com/jprichardson/node-fs-extra/issues/9 "don't import normal fs stuff into fs-extra"
[#8]: https://github.com/jprichardson/node-fs-extra/pull/8 "Update rimraf to latest version"
[#6]: https://github.com/jprichardson/node-fs-extra/issues/6 "Remove CoffeeScript development dependency"
[#5]: https://github.com/jprichardson/node-fs-extra/issues/5 "comments on naming"
[#4]: https://github.com/jprichardson/node-fs-extra/issues/4 "version bump to 0.2"
[#3]: https://github.com/jprichardson/node-fs-extra/pull/3 "Hi! I fixed some code for you!"
[#2]: https://github.com/jprichardson/node-fs-extra/issues/2 "Merge with fs.extra and mkdirp"
[#1]: https://github.com/jprichardson/node-fs-extra/issues/1 "file-extra npm !exist"

View File

@ -0,0 +1,15 @@
(The MIT License)
Copyright (c) 2011-2017 JP Richardson
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
(the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -0,0 +1,261 @@
Node.js: fs-extra
=================
`fs-extra` adds file system methods that aren't included in the native `fs` module and adds promise support to the `fs` methods. It also uses [`graceful-fs`](https://github.com/isaacs/node-graceful-fs) to prevent `EMFILE` errors. It should be a drop in replacement for `fs`.
[![npm Package](https://img.shields.io/npm/v/fs-extra.svg)](https://www.npmjs.org/package/fs-extra)
[![License](https://img.shields.io/npm/l/express.svg)](https://github.com/jprichardson/node-fs-extra/blob/master/LICENSE)
[![build status](https://img.shields.io/travis/jprichardson/node-fs-extra/master.svg)](http://travis-ci.org/jprichardson/node-fs-extra)
[![windows Build status](https://img.shields.io/appveyor/ci/jprichardson/node-fs-extra/master.svg?label=windows%20build)](https://ci.appveyor.com/project/jprichardson/node-fs-extra/branch/master)
[![downloads per month](http://img.shields.io/npm/dm/fs-extra.svg)](https://www.npmjs.org/package/fs-extra)
[![Coverage Status](https://img.shields.io/coveralls/github/jprichardson/node-fs-extra/master.svg)](https://coveralls.io/github/jprichardson/node-fs-extra)
[![JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://standardjs.com)
Why?
----
I got tired of including `mkdirp`, `rimraf`, and `ncp` in most of my projects.
Installation
------------
npm install fs-extra
Usage
-----
`fs-extra` is a drop in replacement for native `fs`. All methods in `fs` are attached to `fs-extra`. All `fs` methods return promises if the callback isn't passed.
You don't ever need to include the original `fs` module again:
```js
const fs = require('fs') // this is no longer necessary
```
you can now do this:
```js
const fs = require('fs-extra')
```
or if you prefer to make it clear that you're using `fs-extra` and not `fs`, you may want
to name your `fs` variable `fse` like so:
```js
const fse = require('fs-extra')
```
you can also keep both, but it's redundant:
```js
const fs = require('fs')
const fse = require('fs-extra')
```
Sync vs Async vs Async/Await
-------------
Most methods are async by default. All async methods will return a promise if the callback isn't passed.
Sync methods on the other hand will throw if an error occurs.
Also Async/Await will throw an error if one occurs.
Example:
```js
const fs = require('fs-extra')
// Async with promises:
fs.copy('/tmp/myfile', '/tmp/mynewfile')
.then(() => console.log('success!'))
.catch(err => console.error(err))
// Async with callbacks:
fs.copy('/tmp/myfile', '/tmp/mynewfile', err => {
if (err) return console.error(err)
console.log('success!')
})
// Sync:
try {
fs.copySync('/tmp/myfile', '/tmp/mynewfile')
console.log('success!')
} catch (err) {
console.error(err)
}
// Async/Await:
async function copyFiles () {
try {
await fs.copy('/tmp/myfile', '/tmp/mynewfile')
console.log('success!')
} catch (err) {
console.error(err)
}
}
copyFiles()
```
Methods
-------
### Async
- [copy](docs/copy.md)
- [emptyDir](docs/emptyDir.md)
- [ensureFile](docs/ensureFile.md)
- [ensureDir](docs/ensureDir.md)
- [ensureLink](docs/ensureLink.md)
- [ensureSymlink](docs/ensureSymlink.md)
- [mkdirp](docs/ensureDir.md)
- [mkdirs](docs/ensureDir.md)
- [move](docs/move.md)
- [outputFile](docs/outputFile.md)
- [outputJson](docs/outputJson.md)
- [pathExists](docs/pathExists.md)
- [readJson](docs/readJson.md)
- [remove](docs/remove.md)
- [writeJson](docs/writeJson.md)
### Sync
- [copySync](docs/copy-sync.md)
- [emptyDirSync](docs/emptyDir-sync.md)
- [ensureFileSync](docs/ensureFile-sync.md)
- [ensureDirSync](docs/ensureDir-sync.md)
- [ensureLinkSync](docs/ensureLink-sync.md)
- [ensureSymlinkSync](docs/ensureSymlink-sync.md)
- [mkdirpSync](docs/ensureDir-sync.md)
- [mkdirsSync](docs/ensureDir-sync.md)
- [moveSync](docs/move-sync.md)
- [outputFileSync](docs/outputFile-sync.md)
- [outputJsonSync](docs/outputJson-sync.md)
- [pathExistsSync](docs/pathExists-sync.md)
- [readJsonSync](docs/readJson-sync.md)
- [removeSync](docs/remove-sync.md)
- [writeJsonSync](docs/writeJson-sync.md)
**NOTE:** You can still use the native Node.js methods. They are promisified and copied over to `fs-extra`. See [notes on `fs.read()`, `fs.write()`, & `fs.writev()`](docs/fs-read-write-writev.md)
### What happened to `walk()` and `walkSync()`?
They were removed from `fs-extra` in v2.0.0. If you need the functionality, `walk` and `walkSync` are available as separate packages, [`klaw`](https://github.com/jprichardson/node-klaw) and [`klaw-sync`](https://github.com/manidlou/node-klaw-sync).
Third Party
-----------
### TypeScript
If you like TypeScript, you can use `fs-extra` with it: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/fs-extra
### File / Directory Watching
If you want to watch for changes to files or directories, then you should use [chokidar](https://github.com/paulmillr/chokidar).
### Obtain Filesystem (Devices, Partitions) Information
[fs-filesystem](https://github.com/arthurintelligence/node-fs-filesystem) allows you to read the state of the filesystem of the host on which it is run. It returns information about both the devices and the partitions (volumes) of the system.
### Misc.
- [fs-extra-debug](https://github.com/jdxcode/fs-extra-debug) - Send your fs-extra calls to [debug](https://npmjs.org/package/debug).
- [mfs](https://github.com/cadorn/mfs) - Monitor your fs-extra calls.
Hacking on fs-extra
-------------------
Wanna hack on `fs-extra`? Great! Your help is needed! [fs-extra is one of the most depended upon Node.js packages](http://nodei.co/npm/fs-extra.png?downloads=true&downloadRank=true&stars=true). This project
uses [JavaScript Standard Style](https://github.com/feross/standard) - if the name or style choices bother you,
you're gonna have to get over it :) If `standard` is good enough for `npm`, it's good enough for `fs-extra`.
[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard)
What's needed?
- First, take a look at existing issues. Those are probably going to be where the priority lies.
- More tests for edge cases. Specifically on different platforms. There can never be enough tests.
- Improve test coverage. See coveralls output for more info.
Note: If you make any big changes, **you should definitely file an issue for discussion first.**
### Running the Test Suite
fs-extra contains hundreds of tests.
- `npm run lint`: runs the linter ([standard](http://standardjs.com/))
- `npm run unit`: runs the unit tests
- `npm test`: runs both the linter and the tests
### Windows
If you run the tests on the Windows and receive a lot of symbolic link `EPERM` permission errors, it's
because on Windows you need elevated privilege to create symbolic links. You can add this to your Windows's
account by following the instructions here: http://superuser.com/questions/104845/permission-to-make-symbolic-links-in-windows-7
However, I didn't have much luck doing this.
Since I develop on Mac OS X, I use VMWare Fusion for Windows testing. I create a shared folder that I map to a drive on Windows.
I open the `Node.js command prompt` and run as `Administrator`. I then map the network drive running the following command:
net use z: "\\vmware-host\Shared Folders"
I can then navigate to my `fs-extra` directory and run the tests.
Naming
------
I put a lot of thought into the naming of these functions. Inspired by @coolaj86's request. So he deserves much of the credit for raising the issue. See discussion(s) here:
* https://github.com/jprichardson/node-fs-extra/issues/2
* https://github.com/flatiron/utile/issues/11
* https://github.com/ryanmcgrath/wrench-js/issues/29
* https://github.com/substack/node-mkdirp/issues/17
First, I believe that in as many cases as possible, the [Node.js naming schemes](http://nodejs.org/api/fs.html) should be chosen. However, there are problems with the Node.js own naming schemes.
For example, `fs.readFile()` and `fs.readdir()`: the **F** is capitalized in *File* and the **d** is not capitalized in *dir*. Perhaps a bit pedantic, but they should still be consistent. Also, Node.js has chosen a lot of POSIX naming schemes, which I believe is great. See: `fs.mkdir()`, `fs.rmdir()`, `fs.chown()`, etc.
We have a dilemma though. How do you consistently name methods that perform the following POSIX commands: `cp`, `cp -r`, `mkdir -p`, and `rm -rf`?
My perspective: when in doubt, err on the side of simplicity. A directory is just a hierarchical grouping of directories and files. Consider that for a moment. So when you want to copy it or remove it, in most cases you'll want to copy or remove all of its contents. When you want to create a directory, if the directory that it's suppose to be contained in does not exist, then in most cases you'll want to create that too.
So, if you want to remove a file or a directory regardless of whether it has contents, just call `fs.remove(path)`. If you want to copy a file or a directory whether it has contents, just call `fs.copy(source, destination)`. If you want to create a directory regardless of whether its parent directories exist, just call `fs.mkdirs(path)` or `fs.mkdirp(path)`.
Credit
------
`fs-extra` wouldn't be possible without using the modules from the following authors:
- [Isaac Shlueter](https://github.com/isaacs)
- [Charlie McConnel](https://github.com/avianflu)
- [James Halliday](https://github.com/substack)
- [Andrew Kelley](https://github.com/andrewrk)
License
-------
Licensed under MIT
Copyright (c) 2011-2017 [JP Richardson](https://github.com/jprichardson)
[1]: http://nodejs.org/docs/latest/api/fs.html
[jsonfile]: https://github.com/jprichardson/node-jsonfile

View File

@ -0,0 +1,166 @@
'use strict'
const fs = require('graceful-fs')
const path = require('path')
const mkdirsSync = require('../mkdirs').mkdirsSync
const utimesMillisSync = require('../util/utimes').utimesMillisSync
const stat = require('../util/stat')
function copySync (src, dest, opts) {
if (typeof opts === 'function') {
opts = { filter: opts }
}
opts = opts || {}
opts.clobber = 'clobber' in opts ? !!opts.clobber : true // default to true for now
opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber // overwrite falls back to clobber
// Warn about using preserveTimestamps on 32-bit node
if (opts.preserveTimestamps && process.arch === 'ia32') {
console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended;\n
see https://github.com/jprichardson/node-fs-extra/issues/269`)
}
const { srcStat, destStat } = stat.checkPathsSync(src, dest, 'copy')
stat.checkParentPathsSync(src, srcStat, dest, 'copy')
return handleFilterAndCopy(destStat, src, dest, opts)
}
function handleFilterAndCopy (destStat, src, dest, opts) {
if (opts.filter && !opts.filter(src, dest)) return
const destParent = path.dirname(dest)
if (!fs.existsSync(destParent)) mkdirsSync(destParent)
return startCopy(destStat, src, dest, opts)
}
function startCopy (destStat, src, dest, opts) {
if (opts.filter && !opts.filter(src, dest)) return
return getStats(destStat, src, dest, opts)
}
function getStats (destStat, src, dest, opts) {
const statSync = opts.dereference ? fs.statSync : fs.lstatSync
const srcStat = statSync(src)
if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts)
else if (srcStat.isFile() ||
srcStat.isCharacterDevice() ||
srcStat.isBlockDevice()) return onFile(srcStat, destStat, src, dest, opts)
else if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts)
}
function onFile (srcStat, destStat, src, dest, opts) {
if (!destStat) return copyFile(srcStat, src, dest, opts)
return mayCopyFile(srcStat, src, dest, opts)
}
function mayCopyFile (srcStat, src, dest, opts) {
if (opts.overwrite) {
fs.unlinkSync(dest)
return copyFile(srcStat, src, dest, opts)
} else if (opts.errorOnExist) {
throw new Error(`'${dest}' already exists`)
}
}
function copyFile (srcStat, src, dest, opts) {
fs.copyFileSync(src, dest)
if (opts.preserveTimestamps) handleTimestamps(srcStat.mode, src, dest)
return setDestMode(dest, srcStat.mode)
}
function handleTimestamps (srcMode, src, dest) {
// Make sure the file is writable before setting the timestamp
// otherwise open fails with EPERM when invoked with 'r+'
// (through utimes call)
if (fileIsNotWritable(srcMode)) makeFileWritable(dest, srcMode)
return setDestTimestamps(src, dest)
}
function fileIsNotWritable (srcMode) {
return (srcMode & 0o200) === 0
}
function makeFileWritable (dest, srcMode) {
return setDestMode(dest, srcMode | 0o200)
}
function setDestMode (dest, srcMode) {
return fs.chmodSync(dest, srcMode)
}
function setDestTimestamps (src, dest) {
// The initial srcStat.atime cannot be trusted
// because it is modified by the read(2) system call
// (See https://nodejs.org/api/fs.html#fs_stat_time_values)
const updatedSrcStat = fs.statSync(src)
return utimesMillisSync(dest, updatedSrcStat.atime, updatedSrcStat.mtime)
}
function onDir (srcStat, destStat, src, dest, opts) {
if (!destStat) return mkDirAndCopy(srcStat.mode, src, dest, opts)
if (destStat && !destStat.isDirectory()) {
throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`)
}
return copyDir(src, dest, opts)
}
function mkDirAndCopy (srcMode, src, dest, opts) {
fs.mkdirSync(dest)
copyDir(src, dest, opts)
return setDestMode(dest, srcMode)
}
function copyDir (src, dest, opts) {
fs.readdirSync(src).forEach(item => copyDirItem(item, src, dest, opts))
}
function copyDirItem (item, src, dest, opts) {
const srcItem = path.join(src, item)
const destItem = path.join(dest, item)
const { destStat } = stat.checkPathsSync(srcItem, destItem, 'copy')
return startCopy(destStat, srcItem, destItem, opts)
}
function onLink (destStat, src, dest, opts) {
let resolvedSrc = fs.readlinkSync(src)
if (opts.dereference) {
resolvedSrc = path.resolve(process.cwd(), resolvedSrc)
}
if (!destStat) {
return fs.symlinkSync(resolvedSrc, dest)
} else {
let resolvedDest
try {
resolvedDest = fs.readlinkSync(dest)
} catch (err) {
// dest exists and is a regular file or directory,
// Windows may throw UNKNOWN error. If dest already exists,
// fs throws error anyway, so no need to guard against it here.
if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return fs.symlinkSync(resolvedSrc, dest)
throw err
}
if (opts.dereference) {
resolvedDest = path.resolve(process.cwd(), resolvedDest)
}
if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) {
throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`)
}
// prevent copy if src is a subdir of dest since unlinking
// dest in this case would result in removing src contents
// and therefore a broken symlink would be created.
if (fs.statSync(dest).isDirectory() && stat.isSrcSubdir(resolvedDest, resolvedSrc)) {
throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`)
}
return copyLink(resolvedSrc, dest)
}
}
function copyLink (resolvedSrc, dest) {
fs.unlinkSync(dest)
return fs.symlinkSync(resolvedSrc, dest)
}
module.exports = copySync

View File

@ -0,0 +1,5 @@
'use strict'
module.exports = {
copySync: require('./copy-sync')
}

View File

@ -0,0 +1,232 @@
'use strict'
const fs = require('graceful-fs')
const path = require('path')
const mkdirs = require('../mkdirs').mkdirs
const pathExists = require('../path-exists').pathExists
const utimesMillis = require('../util/utimes').utimesMillis
const stat = require('../util/stat')
function copy (src, dest, opts, cb) {
if (typeof opts === 'function' && !cb) {
cb = opts
opts = {}
} else if (typeof opts === 'function') {
opts = { filter: opts }
}
cb = cb || function () {}
opts = opts || {}
opts.clobber = 'clobber' in opts ? !!opts.clobber : true // default to true for now
opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber // overwrite falls back to clobber
// Warn about using preserveTimestamps on 32-bit node
if (opts.preserveTimestamps && process.arch === 'ia32') {
console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended;\n
see https://github.com/jprichardson/node-fs-extra/issues/269`)
}
stat.checkPaths(src, dest, 'copy', (err, stats) => {
if (err) return cb(err)
const { srcStat, destStat } = stats
stat.checkParentPaths(src, srcStat, dest, 'copy', err => {
if (err) return cb(err)
if (opts.filter) return handleFilter(checkParentDir, destStat, src, dest, opts, cb)
return checkParentDir(destStat, src, dest, opts, cb)
})
})
}
function checkParentDir (destStat, src, dest, opts, cb) {
const destParent = path.dirname(dest)
pathExists(destParent, (err, dirExists) => {
if (err) return cb(err)
if (dirExists) return startCopy(destStat, src, dest, opts, cb)
mkdirs(destParent, err => {
if (err) return cb(err)
return startCopy(destStat, src, dest, opts, cb)
})
})
}
function handleFilter (onInclude, destStat, src, dest, opts, cb) {
Promise.resolve(opts.filter(src, dest)).then(include => {
if (include) return onInclude(destStat, src, dest, opts, cb)
return cb()
}, error => cb(error))
}
function startCopy (destStat, src, dest, opts, cb) {
if (opts.filter) return handleFilter(getStats, destStat, src, dest, opts, cb)
return getStats(destStat, src, dest, opts, cb)
}
function getStats (destStat, src, dest, opts, cb) {
const stat = opts.dereference ? fs.stat : fs.lstat
stat(src, (err, srcStat) => {
if (err) return cb(err)
if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts, cb)
else if (srcStat.isFile() ||
srcStat.isCharacterDevice() ||
srcStat.isBlockDevice()) return onFile(srcStat, destStat, src, dest, opts, cb)
else if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts, cb)
})
}
function onFile (srcStat, destStat, src, dest, opts, cb) {
if (!destStat) return copyFile(srcStat, src, dest, opts, cb)
return mayCopyFile(srcStat, src, dest, opts, cb)
}
function mayCopyFile (srcStat, src, dest, opts, cb) {
if (opts.overwrite) {
fs.unlink(dest, err => {
if (err) return cb(err)
return copyFile(srcStat, src, dest, opts, cb)
})
} else if (opts.errorOnExist) {
return cb(new Error(`'${dest}' already exists`))
} else return cb()
}
function copyFile (srcStat, src, dest, opts, cb) {
fs.copyFile(src, dest, err => {
if (err) return cb(err)
if (opts.preserveTimestamps) return handleTimestampsAndMode(srcStat.mode, src, dest, cb)
return setDestMode(dest, srcStat.mode, cb)
})
}
function handleTimestampsAndMode (srcMode, src, dest, cb) {
// Make sure the file is writable before setting the timestamp
// otherwise open fails with EPERM when invoked with 'r+'
// (through utimes call)
if (fileIsNotWritable(srcMode)) {
return makeFileWritable(dest, srcMode, err => {
if (err) return cb(err)
return setDestTimestampsAndMode(srcMode, src, dest, cb)
})
}
return setDestTimestampsAndMode(srcMode, src, dest, cb)
}
function fileIsNotWritable (srcMode) {
return (srcMode & 0o200) === 0
}
function makeFileWritable (dest, srcMode, cb) {
return setDestMode(dest, srcMode | 0o200, cb)
}
function setDestTimestampsAndMode (srcMode, src, dest, cb) {
setDestTimestamps(src, dest, err => {
if (err) return cb(err)
return setDestMode(dest, srcMode, cb)
})
}
function setDestMode (dest, srcMode, cb) {
return fs.chmod(dest, srcMode, cb)
}
function setDestTimestamps (src, dest, cb) {
// The initial srcStat.atime cannot be trusted
// because it is modified by the read(2) system call
// (See https://nodejs.org/api/fs.html#fs_stat_time_values)
fs.stat(src, (err, updatedSrcStat) => {
if (err) return cb(err)
return utimesMillis(dest, updatedSrcStat.atime, updatedSrcStat.mtime, cb)
})
}
function onDir (srcStat, destStat, src, dest, opts, cb) {
if (!destStat) return mkDirAndCopy(srcStat.mode, src, dest, opts, cb)
if (destStat && !destStat.isDirectory()) {
return cb(new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`))
}
return copyDir(src, dest, opts, cb)
}
function mkDirAndCopy (srcMode, src, dest, opts, cb) {
fs.mkdir(dest, err => {
if (err) return cb(err)
copyDir(src, dest, opts, err => {
if (err) return cb(err)
return setDestMode(dest, srcMode, cb)
})
})
}
function copyDir (src, dest, opts, cb) {
fs.readdir(src, (err, items) => {
if (err) return cb(err)
return copyDirItems(items, src, dest, opts, cb)
})
}
function copyDirItems (items, src, dest, opts, cb) {
const item = items.pop()
if (!item) return cb()
return copyDirItem(items, item, src, dest, opts, cb)
}
function copyDirItem (items, item, src, dest, opts, cb) {
const srcItem = path.join(src, item)
const destItem = path.join(dest, item)
stat.checkPaths(srcItem, destItem, 'copy', (err, stats) => {
if (err) return cb(err)
const { destStat } = stats
startCopy(destStat, srcItem, destItem, opts, err => {
if (err) return cb(err)
return copyDirItems(items, src, dest, opts, cb)
})
})
}
function onLink (destStat, src, dest, opts, cb) {
fs.readlink(src, (err, resolvedSrc) => {
if (err) return cb(err)
if (opts.dereference) {
resolvedSrc = path.resolve(process.cwd(), resolvedSrc)
}
if (!destStat) {
return fs.symlink(resolvedSrc, dest, cb)
} else {
fs.readlink(dest, (err, resolvedDest) => {
if (err) {
// dest exists and is a regular file or directory,
// Windows may throw UNKNOWN error. If dest already exists,
// fs throws error anyway, so no need to guard against it here.
if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return fs.symlink(resolvedSrc, dest, cb)
return cb(err)
}
if (opts.dereference) {
resolvedDest = path.resolve(process.cwd(), resolvedDest)
}
if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) {
return cb(new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`))
}
// do not copy if src is a subdir of dest since unlinking
// dest in this case would result in removing src contents
// and therefore a broken symlink would be created.
if (destStat.isDirectory() && stat.isSrcSubdir(resolvedDest, resolvedSrc)) {
return cb(new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`))
}
return copyLink(resolvedSrc, dest, cb)
})
}
})
}
function copyLink (resolvedSrc, dest, cb) {
fs.unlink(dest, err => {
if (err) return cb(err)
return fs.symlink(resolvedSrc, dest, cb)
})
}
module.exports = copy

View File

@ -0,0 +1,6 @@
'use strict'
const u = require('universalify').fromCallback
module.exports = {
copy: u(require('./copy'))
}

View File

@ -0,0 +1,48 @@
'use strict'
const u = require('universalify').fromCallback
const fs = require('graceful-fs')
const path = require('path')
const mkdir = require('../mkdirs')
const remove = require('../remove')
const emptyDir = u(function emptyDir (dir, callback) {
callback = callback || function () {}
fs.readdir(dir, (err, items) => {
if (err) return mkdir.mkdirs(dir, callback)
items = items.map(item => path.join(dir, item))
deleteItem()
function deleteItem () {
const item = items.pop()
if (!item) return callback()
remove.remove(item, err => {
if (err) return callback(err)
deleteItem()
})
}
})
})
function emptyDirSync (dir) {
let items
try {
items = fs.readdirSync(dir)
} catch {
return mkdir.mkdirsSync(dir)
}
items.forEach(item => {
item = path.join(dir, item)
remove.removeSync(item)
})
}
module.exports = {
emptyDirSync,
emptydirSync: emptyDirSync,
emptyDir,
emptydir: emptyDir
}

View File

@ -0,0 +1,69 @@
'use strict'
const u = require('universalify').fromCallback
const path = require('path')
const fs = require('graceful-fs')
const mkdir = require('../mkdirs')
function createFile (file, callback) {
function makeFile () {
fs.writeFile(file, '', err => {
if (err) return callback(err)
callback()
})
}
fs.stat(file, (err, stats) => { // eslint-disable-line handle-callback-err
if (!err && stats.isFile()) return callback()
const dir = path.dirname(file)
fs.stat(dir, (err, stats) => {
if (err) {
// if the directory doesn't exist, make it
if (err.code === 'ENOENT') {
return mkdir.mkdirs(dir, err => {
if (err) return callback(err)
makeFile()
})
}
return callback(err)
}
if (stats.isDirectory()) makeFile()
else {
// parent is not a directory
// This is just to cause an internal ENOTDIR error to be thrown
fs.readdir(dir, err => {
if (err) return callback(err)
})
}
})
})
}
function createFileSync (file) {
let stats
try {
stats = fs.statSync(file)
} catch {}
if (stats && stats.isFile()) return
const dir = path.dirname(file)
try {
if (!fs.statSync(dir).isDirectory()) {
// parent is not a directory
// This is just to cause an internal ENOTDIR error to be thrown
fs.readdirSync(dir)
}
} catch (err) {
// If the stat call above failed because the directory doesn't exist, create it
if (err && err.code === 'ENOENT') mkdir.mkdirsSync(dir)
else throw err
}
fs.writeFileSync(file, '')
}
module.exports = {
createFile: u(createFile),
createFileSync
}

View File

@ -0,0 +1,23 @@
'use strict'
const file = require('./file')
const link = require('./link')
const symlink = require('./symlink')
module.exports = {
// file
createFile: file.createFile,
createFileSync: file.createFileSync,
ensureFile: file.createFile,
ensureFileSync: file.createFileSync,
// link
createLink: link.createLink,
createLinkSync: link.createLinkSync,
ensureLink: link.createLink,
ensureLinkSync: link.createLinkSync,
// symlink
createSymlink: symlink.createSymlink,
createSymlinkSync: symlink.createSymlinkSync,
ensureSymlink: symlink.createSymlink,
ensureSymlinkSync: symlink.createSymlinkSync
}

View File

@ -0,0 +1,61 @@
'use strict'
const u = require('universalify').fromCallback
const path = require('path')
const fs = require('graceful-fs')
const mkdir = require('../mkdirs')
const pathExists = require('../path-exists').pathExists
function createLink (srcpath, dstpath, callback) {
function makeLink (srcpath, dstpath) {
fs.link(srcpath, dstpath, err => {
if (err) return callback(err)
callback(null)
})
}
pathExists(dstpath, (err, destinationExists) => {
if (err) return callback(err)
if (destinationExists) return callback(null)
fs.lstat(srcpath, (err) => {
if (err) {
err.message = err.message.replace('lstat', 'ensureLink')
return callback(err)
}
const dir = path.dirname(dstpath)
pathExists(dir, (err, dirExists) => {
if (err) return callback(err)
if (dirExists) return makeLink(srcpath, dstpath)
mkdir.mkdirs(dir, err => {
if (err) return callback(err)
makeLink(srcpath, dstpath)
})
})
})
})
}
function createLinkSync (srcpath, dstpath) {
const destinationExists = fs.existsSync(dstpath)
if (destinationExists) return undefined
try {
fs.lstatSync(srcpath)
} catch (err) {
err.message = err.message.replace('lstat', 'ensureLink')
throw err
}
const dir = path.dirname(dstpath)
const dirExists = fs.existsSync(dir)
if (dirExists) return fs.linkSync(srcpath, dstpath)
mkdir.mkdirsSync(dir)
return fs.linkSync(srcpath, dstpath)
}
module.exports = {
createLink: u(createLink),
createLinkSync
}

View File

@ -0,0 +1,99 @@
'use strict'
const path = require('path')
const fs = require('graceful-fs')
const pathExists = require('../path-exists').pathExists
/**
* Function that returns two types of paths, one relative to symlink, and one
* relative to the current working directory. Checks if path is absolute or
* relative. If the path is relative, this function checks if the path is
* relative to symlink or relative to current working directory. This is an
* initiative to find a smarter `srcpath` to supply when building symlinks.
* This allows you to determine which path to use out of one of three possible
* types of source paths. The first is an absolute path. This is detected by
* `path.isAbsolute()`. When an absolute path is provided, it is checked to
* see if it exists. If it does it's used, if not an error is returned
* (callback)/ thrown (sync). The other two options for `srcpath` are a
* relative url. By default Node's `fs.symlink` works by creating a symlink
* using `dstpath` and expects the `srcpath` to be relative to the newly
* created symlink. If you provide a `srcpath` that does not exist on the file
* system it results in a broken symlink. To minimize this, the function
* checks to see if the 'relative to symlink' source file exists, and if it
* does it will use it. If it does not, it checks if there's a file that
* exists that is relative to the current working directory, if does its used.
* This preserves the expectations of the original fs.symlink spec and adds
* the ability to pass in `relative to current working direcotry` paths.
*/
function symlinkPaths (srcpath, dstpath, callback) {
if (path.isAbsolute(srcpath)) {
return fs.lstat(srcpath, (err) => {
if (err) {
err.message = err.message.replace('lstat', 'ensureSymlink')
return callback(err)
}
return callback(null, {
toCwd: srcpath,
toDst: srcpath
})
})
} else {
const dstdir = path.dirname(dstpath)
const relativeToDst = path.join(dstdir, srcpath)
return pathExists(relativeToDst, (err, exists) => {
if (err) return callback(err)
if (exists) {
return callback(null, {
toCwd: relativeToDst,
toDst: srcpath
})
} else {
return fs.lstat(srcpath, (err) => {
if (err) {
err.message = err.message.replace('lstat', 'ensureSymlink')
return callback(err)
}
return callback(null, {
toCwd: srcpath,
toDst: path.relative(dstdir, srcpath)
})
})
}
})
}
}
function symlinkPathsSync (srcpath, dstpath) {
let exists
if (path.isAbsolute(srcpath)) {
exists = fs.existsSync(srcpath)
if (!exists) throw new Error('absolute srcpath does not exist')
return {
toCwd: srcpath,
toDst: srcpath
}
} else {
const dstdir = path.dirname(dstpath)
const relativeToDst = path.join(dstdir, srcpath)
exists = fs.existsSync(relativeToDst)
if (exists) {
return {
toCwd: relativeToDst,
toDst: srcpath
}
} else {
exists = fs.existsSync(srcpath)
if (!exists) throw new Error('relative srcpath does not exist')
return {
toCwd: srcpath,
toDst: path.relative(dstdir, srcpath)
}
}
}
}
module.exports = {
symlinkPaths,
symlinkPathsSync
}

View File

@ -0,0 +1,31 @@
'use strict'
const fs = require('graceful-fs')
function symlinkType (srcpath, type, callback) {
callback = (typeof type === 'function') ? type : callback
type = (typeof type === 'function') ? false : type
if (type) return callback(null, type)
fs.lstat(srcpath, (err, stats) => {
if (err) return callback(null, 'file')
type = (stats && stats.isDirectory()) ? 'dir' : 'file'
callback(null, type)
})
}
function symlinkTypeSync (srcpath, type) {
let stats
if (type) return type
try {
stats = fs.lstatSync(srcpath)
} catch {
return 'file'
}
return (stats && stats.isDirectory()) ? 'dir' : 'file'
}
module.exports = {
symlinkType,
symlinkTypeSync
}

View File

@ -0,0 +1,63 @@
'use strict'
const u = require('universalify').fromCallback
const path = require('path')
const fs = require('graceful-fs')
const _mkdirs = require('../mkdirs')
const mkdirs = _mkdirs.mkdirs
const mkdirsSync = _mkdirs.mkdirsSync
const _symlinkPaths = require('./symlink-paths')
const symlinkPaths = _symlinkPaths.symlinkPaths
const symlinkPathsSync = _symlinkPaths.symlinkPathsSync
const _symlinkType = require('./symlink-type')
const symlinkType = _symlinkType.symlinkType
const symlinkTypeSync = _symlinkType.symlinkTypeSync
const pathExists = require('../path-exists').pathExists
function createSymlink (srcpath, dstpath, type, callback) {
callback = (typeof type === 'function') ? type : callback
type = (typeof type === 'function') ? false : type
pathExists(dstpath, (err, destinationExists) => {
if (err) return callback(err)
if (destinationExists) return callback(null)
symlinkPaths(srcpath, dstpath, (err, relative) => {
if (err) return callback(err)
srcpath = relative.toDst
symlinkType(relative.toCwd, type, (err, type) => {
if (err) return callback(err)
const dir = path.dirname(dstpath)
pathExists(dir, (err, dirExists) => {
if (err) return callback(err)
if (dirExists) return fs.symlink(srcpath, dstpath, type, callback)
mkdirs(dir, err => {
if (err) return callback(err)
fs.symlink(srcpath, dstpath, type, callback)
})
})
})
})
})
}
function createSymlinkSync (srcpath, dstpath, type) {
const destinationExists = fs.existsSync(dstpath)
if (destinationExists) return undefined
const relative = symlinkPathsSync(srcpath, dstpath)
srcpath = relative.toDst
type = symlinkTypeSync(relative.toCwd, type)
const dir = path.dirname(dstpath)
const exists = fs.existsSync(dir)
if (exists) return fs.symlinkSync(srcpath, dstpath, type)
mkdirsSync(dir)
return fs.symlinkSync(srcpath, dstpath, type)
}
module.exports = {
createSymlink: u(createSymlink),
createSymlinkSync
}

View File

@ -0,0 +1,128 @@
'use strict'
// This is adapted from https://github.com/normalize/mz
// Copyright (c) 2014-2016 Jonathan Ong me@jongleberry.com and Contributors
const u = require('universalify').fromCallback
const fs = require('graceful-fs')
const api = [
'access',
'appendFile',
'chmod',
'chown',
'close',
'copyFile',
'fchmod',
'fchown',
'fdatasync',
'fstat',
'fsync',
'ftruncate',
'futimes',
'lchmod',
'lchown',
'link',
'lstat',
'mkdir',
'mkdtemp',
'open',
'opendir',
'readdir',
'readFile',
'readlink',
'realpath',
'rename',
'rmdir',
'stat',
'symlink',
'truncate',
'unlink',
'utimes',
'writeFile'
].filter(key => {
// Some commands are not available on some systems. Ex:
// fs.opendir was added in Node.js v12.12.0
// fs.lchown is not available on at least some Linux
return typeof fs[key] === 'function'
})
// Export all keys:
Object.keys(fs).forEach(key => {
if (key === 'promises') {
// fs.promises is a getter property that triggers ExperimentalWarning
// Don't re-export it here, the getter is defined in "lib/index.js"
return
}
exports[key] = fs[key]
})
// Universalify async methods:
api.forEach(method => {
exports[method] = u(fs[method])
})
// We differ from mz/fs in that we still ship the old, broken, fs.exists()
// since we are a drop-in replacement for the native module
exports.exists = function (filename, callback) {
if (typeof callback === 'function') {
return fs.exists(filename, callback)
}
return new Promise(resolve => {
return fs.exists(filename, resolve)
})
}
// fs.read(), fs.write(), & fs.writev() need special treatment due to multiple callback args
exports.read = function (fd, buffer, offset, length, position, callback) {
if (typeof callback === 'function') {
return fs.read(fd, buffer, offset, length, position, callback)
}
return new Promise((resolve, reject) => {
fs.read(fd, buffer, offset, length, position, (err, bytesRead, buffer) => {
if (err) return reject(err)
resolve({ bytesRead, buffer })
})
})
}
// Function signature can be
// fs.write(fd, buffer[, offset[, length[, position]]], callback)
// OR
// fs.write(fd, string[, position[, encoding]], callback)
// We need to handle both cases, so we use ...args
exports.write = function (fd, buffer, ...args) {
if (typeof args[args.length - 1] === 'function') {
return fs.write(fd, buffer, ...args)
}
return new Promise((resolve, reject) => {
fs.write(fd, buffer, ...args, (err, bytesWritten, buffer) => {
if (err) return reject(err)
resolve({ bytesWritten, buffer })
})
})
}
// fs.writev only available in Node v12.9.0+
if (typeof fs.writev === 'function') {
// Function signature is
// s.writev(fd, buffers[, position], callback)
// We need to handle the optional arg, so we use ...args
exports.writev = function (fd, buffers, ...args) {
if (typeof args[args.length - 1] === 'function') {
return fs.writev(fd, buffers, ...args)
}
return new Promise((resolve, reject) => {
fs.writev(fd, buffers, ...args, (err, bytesWritten, buffers) => {
if (err) return reject(err)
resolve({ bytesWritten, buffers })
})
})
}
}
// fs.realpath.native only available in Node v9.2+
if (typeof fs.realpath.native === 'function') {
exports.realpath.native = u(fs.realpath.native)
}

View File

@ -0,0 +1,27 @@
'use strict'
module.exports = {
// Export promiseified graceful-fs:
...require('./fs'),
// Export extra methods:
...require('./copy-sync'),
...require('./copy'),
...require('./empty'),
...require('./ensure'),
...require('./json'),
...require('./mkdirs'),
...require('./move-sync'),
...require('./move'),
...require('./output'),
...require('./path-exists'),
...require('./remove')
}
// Export fs.promises as a getter property so that we don't trigger
// ExperimentalWarning before fs.promises is actually accessed.
const fs = require('fs')
if (Object.getOwnPropertyDescriptor(fs, 'promises')) {
Object.defineProperty(module.exports, 'promises', {
get () { return fs.promises }
})
}

View File

@ -0,0 +1,16 @@
'use strict'
const u = require('universalify').fromPromise
const jsonFile = require('./jsonfile')
jsonFile.outputJson = u(require('./output-json'))
jsonFile.outputJsonSync = require('./output-json-sync')
// aliases
jsonFile.outputJSON = jsonFile.outputJson
jsonFile.outputJSONSync = jsonFile.outputJsonSync
jsonFile.writeJSON = jsonFile.writeJson
jsonFile.writeJSONSync = jsonFile.writeJsonSync
jsonFile.readJSON = jsonFile.readJson
jsonFile.readJSONSync = jsonFile.readJsonSync
module.exports = jsonFile

View File

@ -0,0 +1,11 @@
'use strict'
const jsonFile = require('jsonfile')
module.exports = {
// jsonfile exports
readJson: jsonFile.readFile,
readJsonSync: jsonFile.readFileSync,
writeJson: jsonFile.writeFile,
writeJsonSync: jsonFile.writeFileSync
}

View File

@ -0,0 +1,12 @@
'use strict'
const { stringify } = require('jsonfile/utils')
const { outputFileSync } = require('../output')
function outputJsonSync (file, data, options) {
const str = stringify(data, options)
outputFileSync(file, str, options)
}
module.exports = outputJsonSync

View File

@ -0,0 +1,12 @@
'use strict'
const { stringify } = require('jsonfile/utils')
const { outputFile } = require('../output')
async function outputJson (file, data, options = {}) {
const str = stringify(data, options)
await outputFile(file, str, options)
}
module.exports = outputJson

View File

@ -0,0 +1,14 @@
'use strict'
const u = require('universalify').fromPromise
const { makeDir: _makeDir, makeDirSync } = require('./make-dir')
const makeDir = u(_makeDir)
module.exports = {
mkdirs: makeDir,
mkdirsSync: makeDirSync,
// alias
mkdirp: makeDir,
mkdirpSync: makeDirSync,
ensureDir: makeDir,
ensureDirSync: makeDirSync
}

View File

@ -0,0 +1,141 @@
// Adapted from https://github.com/sindresorhus/make-dir
// Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict'
const fs = require('../fs')
const path = require('path')
const atLeastNode = require('at-least-node')
const useNativeRecursiveOption = atLeastNode('10.12.0')
// https://github.com/nodejs/node/issues/8987
// https://github.com/libuv/libuv/pull/1088
const checkPath = pth => {
if (process.platform === 'win32') {
const pathHasInvalidWinCharacters = /[<>:"|?*]/.test(pth.replace(path.parse(pth).root, ''))
if (pathHasInvalidWinCharacters) {
const error = new Error(`Path contains invalid characters: ${pth}`)
error.code = 'EINVAL'
throw error
}
}
}
const processOptions = options => {
const defaults = { mode: 0o777 }
if (typeof options === 'number') options = { mode: options }
return { ...defaults, ...options }
}
const permissionError = pth => {
// This replicates the exception of `fs.mkdir` with native the
// `recusive` option when run on an invalid drive under Windows.
const error = new Error(`operation not permitted, mkdir '${pth}'`)
error.code = 'EPERM'
error.errno = -4048
error.path = pth
error.syscall = 'mkdir'
return error
}
module.exports.makeDir = async (input, options) => {
checkPath(input)
options = processOptions(options)
if (useNativeRecursiveOption) {
const pth = path.resolve(input)
return fs.mkdir(pth, {
mode: options.mode,
recursive: true
})
}
const make = async pth => {
try {
await fs.mkdir(pth, options.mode)
} catch (error) {
if (error.code === 'EPERM') {
throw error
}
if (error.code === 'ENOENT') {
if (path.dirname(pth) === pth) {
throw permissionError(pth)
}
if (error.message.includes('null bytes')) {
throw error
}
await make(path.dirname(pth))
return make(pth)
}
try {
const stats = await fs.stat(pth)
if (!stats.isDirectory()) {
// This error is never exposed to the user
// it is caught below, and the original error is thrown
throw new Error('The path is not a directory')
}
} catch {
throw error
}
}
}
return make(path.resolve(input))
}
module.exports.makeDirSync = (input, options) => {
checkPath(input)
options = processOptions(options)
if (useNativeRecursiveOption) {
const pth = path.resolve(input)
return fs.mkdirSync(pth, {
mode: options.mode,
recursive: true
})
}
const make = pth => {
try {
fs.mkdirSync(pth, options.mode)
} catch (error) {
if (error.code === 'EPERM') {
throw error
}
if (error.code === 'ENOENT') {
if (path.dirname(pth) === pth) {
throw permissionError(pth)
}
if (error.message.includes('null bytes')) {
throw error
}
make(path.dirname(pth))
return make(pth)
}
try {
if (!fs.statSync(pth).isDirectory()) {
// This error is never exposed to the user
// it is caught below, and the original error is thrown
throw new Error('The path is not a directory')
}
} catch {
throw error
}
}
}
return make(path.resolve(input))
}

View File

@ -0,0 +1,5 @@
'use strict'
module.exports = {
moveSync: require('./move-sync')
}

View File

@ -0,0 +1,47 @@
'use strict'
const fs = require('graceful-fs')
const path = require('path')
const copySync = require('../copy-sync').copySync
const removeSync = require('../remove').removeSync
const mkdirpSync = require('../mkdirs').mkdirpSync
const stat = require('../util/stat')
function moveSync (src, dest, opts) {
opts = opts || {}
const overwrite = opts.overwrite || opts.clobber || false
const { srcStat } = stat.checkPathsSync(src, dest, 'move')
stat.checkParentPathsSync(src, srcStat, dest, 'move')
mkdirpSync(path.dirname(dest))
return doRename(src, dest, overwrite)
}
function doRename (src, dest, overwrite) {
if (overwrite) {
removeSync(dest)
return rename(src, dest, overwrite)
}
if (fs.existsSync(dest)) throw new Error('dest already exists.')
return rename(src, dest, overwrite)
}
function rename (src, dest, overwrite) {
try {
fs.renameSync(src, dest)
} catch (err) {
if (err.code !== 'EXDEV') throw err
return moveAcrossDevice(src, dest, overwrite)
}
}
function moveAcrossDevice (src, dest, overwrite) {
const opts = {
overwrite,
errorOnExist: true
}
copySync(src, dest, opts)
return removeSync(src)
}
module.exports = moveSync

View File

@ -0,0 +1,6 @@
'use strict'
const u = require('universalify').fromCallback
module.exports = {
move: u(require('./move'))
}

View File

@ -0,0 +1,65 @@
'use strict'
const fs = require('graceful-fs')
const path = require('path')
const copy = require('../copy').copy
const remove = require('../remove').remove
const mkdirp = require('../mkdirs').mkdirp
const pathExists = require('../path-exists').pathExists
const stat = require('../util/stat')
function move (src, dest, opts, cb) {
if (typeof opts === 'function') {
cb = opts
opts = {}
}
const overwrite = opts.overwrite || opts.clobber || false
stat.checkPaths(src, dest, 'move', (err, stats) => {
if (err) return cb(err)
const { srcStat } = stats
stat.checkParentPaths(src, srcStat, dest, 'move', err => {
if (err) return cb(err)
mkdirp(path.dirname(dest), err => {
if (err) return cb(err)
return doRename(src, dest, overwrite, cb)
})
})
})
}
function doRename (src, dest, overwrite, cb) {
if (overwrite) {
return remove(dest, err => {
if (err) return cb(err)
return rename(src, dest, overwrite, cb)
})
}
pathExists(dest, (err, destExists) => {
if (err) return cb(err)
if (destExists) return cb(new Error('dest already exists.'))
return rename(src, dest, overwrite, cb)
})
}
function rename (src, dest, overwrite, cb) {
fs.rename(src, dest, err => {
if (!err) return cb()
if (err.code !== 'EXDEV') return cb(err)
return moveAcrossDevice(src, dest, overwrite, cb)
})
}
function moveAcrossDevice (src, dest, overwrite, cb) {
const opts = {
overwrite,
errorOnExist: true
}
copy(src, dest, opts, err => {
if (err) return cb(err)
return remove(src, cb)
})
}
module.exports = move

View File

@ -0,0 +1,40 @@
'use strict'
const u = require('universalify').fromCallback
const fs = require('graceful-fs')
const path = require('path')
const mkdir = require('../mkdirs')
const pathExists = require('../path-exists').pathExists
function outputFile (file, data, encoding, callback) {
if (typeof encoding === 'function') {
callback = encoding
encoding = 'utf8'
}
const dir = path.dirname(file)
pathExists(dir, (err, itDoes) => {
if (err) return callback(err)
if (itDoes) return fs.writeFile(file, data, encoding, callback)
mkdir.mkdirs(dir, err => {
if (err) return callback(err)
fs.writeFile(file, data, encoding, callback)
})
})
}
function outputFileSync (file, ...args) {
const dir = path.dirname(file)
if (fs.existsSync(dir)) {
return fs.writeFileSync(file, ...args)
}
mkdir.mkdirsSync(dir)
fs.writeFileSync(file, ...args)
}
module.exports = {
outputFile: u(outputFile),
outputFileSync
}

View File

@ -0,0 +1,12 @@
'use strict'
const u = require('universalify').fromPromise
const fs = require('../fs')
function pathExists (path) {
return fs.access(path).then(() => true).catch(() => false)
}
module.exports = {
pathExists: u(pathExists),
pathExistsSync: fs.existsSync
}

View File

@ -0,0 +1,9 @@
'use strict'
const u = require('universalify').fromCallback
const rimraf = require('./rimraf')
module.exports = {
remove: u(rimraf),
removeSync: rimraf.sync
}

View File

@ -0,0 +1,302 @@
'use strict'
const fs = require('graceful-fs')
const path = require('path')
const assert = require('assert')
const isWindows = (process.platform === 'win32')
function defaults (options) {
const methods = [
'unlink',
'chmod',
'stat',
'lstat',
'rmdir',
'readdir'
]
methods.forEach(m => {
options[m] = options[m] || fs[m]
m = m + 'Sync'
options[m] = options[m] || fs[m]
})
options.maxBusyTries = options.maxBusyTries || 3
}
function rimraf (p, options, cb) {
let busyTries = 0
if (typeof options === 'function') {
cb = options
options = {}
}
assert(p, 'rimraf: missing path')
assert.strictEqual(typeof p, 'string', 'rimraf: path should be a string')
assert.strictEqual(typeof cb, 'function', 'rimraf: callback function required')
assert(options, 'rimraf: invalid options argument provided')
assert.strictEqual(typeof options, 'object', 'rimraf: options should be object')
defaults(options)
rimraf_(p, options, function CB (er) {
if (er) {
if ((er.code === 'EBUSY' || er.code === 'ENOTEMPTY' || er.code === 'EPERM') &&
busyTries < options.maxBusyTries) {
busyTries++
const time = busyTries * 100
// try again, with the same exact callback as this one.
return setTimeout(() => rimraf_(p, options, CB), time)
}
// already gone
if (er.code === 'ENOENT') er = null
}
cb(er)
})
}
// Two possible strategies.
// 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR
// 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR
//
// Both result in an extra syscall when you guess wrong. However, there
// are likely far more normal files in the world than directories. This
// is based on the assumption that a the average number of files per
// directory is >= 1.
//
// If anyone ever complains about this, then I guess the strategy could
// be made configurable somehow. But until then, YAGNI.
function rimraf_ (p, options, cb) {
assert(p)
assert(options)
assert(typeof cb === 'function')
// sunos lets the root user unlink directories, which is... weird.
// so we have to lstat here and make sure it's not a dir.
options.lstat(p, (er, st) => {
if (er && er.code === 'ENOENT') {
return cb(null)
}
// Windows can EPERM on stat. Life is suffering.
if (er && er.code === 'EPERM' && isWindows) {
return fixWinEPERM(p, options, er, cb)
}
if (st && st.isDirectory()) {
return rmdir(p, options, er, cb)
}
options.unlink(p, er => {
if (er) {
if (er.code === 'ENOENT') {
return cb(null)
}
if (er.code === 'EPERM') {
return (isWindows)
? fixWinEPERM(p, options, er, cb)
: rmdir(p, options, er, cb)
}
if (er.code === 'EISDIR') {
return rmdir(p, options, er, cb)
}
}
return cb(er)
})
})
}
function fixWinEPERM (p, options, er, cb) {
assert(p)
assert(options)
assert(typeof cb === 'function')
options.chmod(p, 0o666, er2 => {
if (er2) {
cb(er2.code === 'ENOENT' ? null : er)
} else {
options.stat(p, (er3, stats) => {
if (er3) {
cb(er3.code === 'ENOENT' ? null : er)
} else if (stats.isDirectory()) {
rmdir(p, options, er, cb)
} else {
options.unlink(p, cb)
}
})
}
})
}
function fixWinEPERMSync (p, options, er) {
let stats
assert(p)
assert(options)
try {
options.chmodSync(p, 0o666)
} catch (er2) {
if (er2.code === 'ENOENT') {
return
} else {
throw er
}
}
try {
stats = options.statSync(p)
} catch (er3) {
if (er3.code === 'ENOENT') {
return
} else {
throw er
}
}
if (stats.isDirectory()) {
rmdirSync(p, options, er)
} else {
options.unlinkSync(p)
}
}
function rmdir (p, options, originalEr, cb) {
assert(p)
assert(options)
assert(typeof cb === 'function')
// try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS)
// if we guessed wrong, and it's not a directory, then
// raise the original error.
options.rmdir(p, er => {
if (er && (er.code === 'ENOTEMPTY' || er.code === 'EEXIST' || er.code === 'EPERM')) {
rmkids(p, options, cb)
} else if (er && er.code === 'ENOTDIR') {
cb(originalEr)
} else {
cb(er)
}
})
}
function rmkids (p, options, cb) {
assert(p)
assert(options)
assert(typeof cb === 'function')
options.readdir(p, (er, files) => {
if (er) return cb(er)
let n = files.length
let errState
if (n === 0) return options.rmdir(p, cb)
files.forEach(f => {
rimraf(path.join(p, f), options, er => {
if (errState) {
return
}
if (er) return cb(errState = er)
if (--n === 0) {
options.rmdir(p, cb)
}
})
})
})
}
// this looks simpler, and is strictly *faster*, but will
// tie up the JavaScript thread and fail on excessively
// deep directory trees.
function rimrafSync (p, options) {
let st
options = options || {}
defaults(options)
assert(p, 'rimraf: missing path')
assert.strictEqual(typeof p, 'string', 'rimraf: path should be a string')
assert(options, 'rimraf: missing options')
assert.strictEqual(typeof options, 'object', 'rimraf: options should be object')
try {
st = options.lstatSync(p)
} catch (er) {
if (er.code === 'ENOENT') {
return
}
// Windows can EPERM on stat. Life is suffering.
if (er.code === 'EPERM' && isWindows) {
fixWinEPERMSync(p, options, er)
}
}
try {
// sunos lets the root user unlink directories, which is... weird.
if (st && st.isDirectory()) {
rmdirSync(p, options, null)
} else {
options.unlinkSync(p)
}
} catch (er) {
if (er.code === 'ENOENT') {
return
} else if (er.code === 'EPERM') {
return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er)
} else if (er.code !== 'EISDIR') {
throw er
}
rmdirSync(p, options, er)
}
}
function rmdirSync (p, options, originalEr) {
assert(p)
assert(options)
try {
options.rmdirSync(p)
} catch (er) {
if (er.code === 'ENOTDIR') {
throw originalEr
} else if (er.code === 'ENOTEMPTY' || er.code === 'EEXIST' || er.code === 'EPERM') {
rmkidsSync(p, options)
} else if (er.code !== 'ENOENT') {
throw er
}
}
}
function rmkidsSync (p, options) {
assert(p)
assert(options)
options.readdirSync(p).forEach(f => rimrafSync(path.join(p, f), options))
if (isWindows) {
// We only end up here once we got ENOTEMPTY at least once, and
// at this point, we are guaranteed to have removed all the kids.
// So, we know that it won't be ENOENT or ENOTDIR or anything else.
// try really hard to delete stuff on windows, because it has a
// PROFOUNDLY annoying habit of not closing handles promptly when
// files are deleted, resulting in spurious ENOTEMPTY errors.
const startTime = Date.now()
do {
try {
const ret = options.rmdirSync(p, options)
return ret
} catch {}
} while (Date.now() - startTime < 500) // give up after 500ms
} else {
const ret = options.rmdirSync(p, options)
return ret
}
}
module.exports = rimraf
rimraf.sync = rimrafSync

View File

@ -0,0 +1,139 @@
'use strict'
const fs = require('../fs')
const path = require('path')
const util = require('util')
const atLeastNode = require('at-least-node')
const nodeSupportsBigInt = atLeastNode('10.5.0')
const stat = (file) => nodeSupportsBigInt ? fs.stat(file, { bigint: true }) : fs.stat(file)
const statSync = (file) => nodeSupportsBigInt ? fs.statSync(file, { bigint: true }) : fs.statSync(file)
function getStats (src, dest) {
return Promise.all([
stat(src),
stat(dest).catch(err => {
if (err.code === 'ENOENT') return null
throw err
})
]).then(([srcStat, destStat]) => ({ srcStat, destStat }))
}
function getStatsSync (src, dest) {
let destStat
const srcStat = statSync(src)
try {
destStat = statSync(dest)
} catch (err) {
if (err.code === 'ENOENT') return { srcStat, destStat: null }
throw err
}
return { srcStat, destStat }
}
function checkPaths (src, dest, funcName, cb) {
util.callbackify(getStats)(src, dest, (err, stats) => {
if (err) return cb(err)
const { srcStat, destStat } = stats
if (destStat && areIdentical(srcStat, destStat)) {
return cb(new Error('Source and destination must not be the same.'))
}
if (srcStat.isDirectory() && isSrcSubdir(src, dest)) {
return cb(new Error(errMsg(src, dest, funcName)))
}
return cb(null, { srcStat, destStat })
})
}
function checkPathsSync (src, dest, funcName) {
const { srcStat, destStat } = getStatsSync(src, dest)
if (destStat && areIdentical(srcStat, destStat)) {
throw new Error('Source and destination must not be the same.')
}
if (srcStat.isDirectory() && isSrcSubdir(src, dest)) {
throw new Error(errMsg(src, dest, funcName))
}
return { srcStat, destStat }
}
// recursively check if dest parent is a subdirectory of src.
// It works for all file types including symlinks since it
// checks the src and dest inodes. It starts from the deepest
// parent and stops once it reaches the src parent or the root path.
function checkParentPaths (src, srcStat, dest, funcName, cb) {
const srcParent = path.resolve(path.dirname(src))
const destParent = path.resolve(path.dirname(dest))
if (destParent === srcParent || destParent === path.parse(destParent).root) return cb()
const callback = (err, destStat) => {
if (err) {
if (err.code === 'ENOENT') return cb()
return cb(err)
}
if (areIdentical(srcStat, destStat)) {
return cb(new Error(errMsg(src, dest, funcName)))
}
return checkParentPaths(src, srcStat, destParent, funcName, cb)
}
if (nodeSupportsBigInt) fs.stat(destParent, { bigint: true }, callback)
else fs.stat(destParent, callback)
}
function checkParentPathsSync (src, srcStat, dest, funcName) {
const srcParent = path.resolve(path.dirname(src))
const destParent = path.resolve(path.dirname(dest))
if (destParent === srcParent || destParent === path.parse(destParent).root) return
let destStat
try {
destStat = statSync(destParent)
} catch (err) {
if (err.code === 'ENOENT') return
throw err
}
if (areIdentical(srcStat, destStat)) {
throw new Error(errMsg(src, dest, funcName))
}
return checkParentPathsSync(src, srcStat, destParent, funcName)
}
function areIdentical (srcStat, destStat) {
if (destStat.ino && destStat.dev && destStat.ino === srcStat.ino && destStat.dev === srcStat.dev) {
if (nodeSupportsBigInt || destStat.ino < Number.MAX_SAFE_INTEGER) {
// definitive answer
return true
}
// Use additional heuristics if we can't use 'bigint'.
// Different 'ino' could be represented the same if they are >= Number.MAX_SAFE_INTEGER
// See issue 657
if (destStat.size === srcStat.size &&
destStat.mode === srcStat.mode &&
destStat.nlink === srcStat.nlink &&
destStat.atimeMs === srcStat.atimeMs &&
destStat.mtimeMs === srcStat.mtimeMs &&
destStat.ctimeMs === srcStat.ctimeMs &&
destStat.birthtimeMs === srcStat.birthtimeMs) {
// heuristic answer
return true
}
}
return false
}
// return true if dest is a subdir of src, otherwise false.
// It only checks the path strings.
function isSrcSubdir (src, dest) {
const srcArr = path.resolve(src).split(path.sep).filter(i => i)
const destArr = path.resolve(dest).split(path.sep).filter(i => i)
return srcArr.reduce((acc, cur, i) => acc && destArr[i] === cur, true)
}
function errMsg (src, dest, funcName) {
return `Cannot ${funcName} '${src}' to a subdirectory of itself, '${dest}'.`
}
module.exports = {
checkPaths,
checkPathsSync,
checkParentPaths,
checkParentPathsSync,
isSrcSubdir
}

View File

@ -0,0 +1,26 @@
'use strict'
const fs = require('graceful-fs')
function utimesMillis (path, atime, mtime, callback) {
// if (!HAS_MILLIS_RES) return fs.utimes(path, atime, mtime, callback)
fs.open(path, 'r+', (err, fd) => {
if (err) return callback(err)
fs.futimes(fd, atime, mtime, futimesErr => {
fs.close(fd, closeErr => {
if (callback) callback(futimesErr || closeErr)
})
})
})
}
function utimesMillisSync (path, atime, mtime) {
const fd = fs.openSync(path, 'r+')
fs.futimesSync(fd, atime, mtime)
return fs.closeSync(fd)
}
module.exports = {
utimesMillis,
utimesMillisSync
}

View File

@ -0,0 +1,101 @@
{
"_from": "fs-extra@^9.0.1",
"_id": "fs-extra@9.0.1",
"_inBundle": false,
"_integrity": "sha512-h2iAoN838FqAFJY2/qVpzFXy+EBxfVE220PalAqQLDVsFOHLJrZvut5puAbCdNv6WJk+B8ihI+k0c7JK5erwqQ==",
"_location": "/app-builder-lib/fs-extra",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "fs-extra@^9.0.1",
"name": "fs-extra",
"escapedName": "fs-extra",
"rawSpec": "^9.0.1",
"saveSpec": null,
"fetchSpec": "^9.0.1"
},
"_requiredBy": [
"/app-builder-lib"
],
"_resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-9.0.1.tgz",
"_shasum": "910da0062437ba4c39fedd863f1675ccfefcb9fc",
"_spec": "fs-extra@^9.0.1",
"_where": "/home/shihaam/www/freezer.shihaam.me/node_modules/app-builder-lib",
"author": {
"name": "JP Richardson",
"email": "jprichardson@gmail.com"
},
"bugs": {
"url": "https://github.com/jprichardson/node-fs-extra/issues"
},
"bundleDependencies": false,
"dependencies": {
"at-least-node": "^1.0.0",
"graceful-fs": "^4.2.0",
"jsonfile": "^6.0.1",
"universalify": "^1.0.0"
},
"deprecated": false,
"description": "fs-extra contains methods that aren't included in the vanilla Node.js fs package. Such as recursive mkdir, copy, and remove.",
"devDependencies": {
"coveralls": "^3.0.0",
"klaw": "^2.1.1",
"klaw-sync": "^3.0.2",
"minimist": "^1.1.1",
"mocha": "^5.0.5",
"nyc": "^15.0.0",
"proxyquire": "^2.0.1",
"read-dir-files": "^0.1.1",
"standard": "^14.1.0"
},
"engines": {
"node": ">=10"
},
"files": [
"lib/",
"!lib/**/__tests__/"
],
"homepage": "https://github.com/jprichardson/node-fs-extra",
"keywords": [
"fs",
"file",
"file system",
"copy",
"directory",
"extra",
"mkdirp",
"mkdir",
"mkdirs",
"recursive",
"json",
"read",
"write",
"extra",
"delete",
"remove",
"touch",
"create",
"text",
"output",
"move",
"promise"
],
"license": "MIT",
"main": "./lib/index.js",
"name": "fs-extra",
"repository": {
"type": "git",
"url": "git+https://github.com/jprichardson/node-fs-extra.git"
},
"scripts": {
"coverage": "nyc -r lcovonly npm run unit",
"coveralls": "coveralls < coverage/lcov.info",
"full-ci": "npm run lint && npm run coverage",
"lint": "standard",
"test": "npm run lint && npm run unit",
"test-find": "find ./lib/**/__tests__ -name *.test.js | xargs mocha",
"unit": "node test.js"
},
"version": "9.0.1"
}

View File

@ -0,0 +1,171 @@
6.1.0 / 2020-10-31
------------------
- Add `finalEOL` option to disable writing final EOL ([#115](https://github.com/jprichardson/node-jsonfile/issues/115), [#137](https://github.com/jprichardson/node-jsonfile/pull/137))
- Update dependency ([#138](https://github.com/jprichardson/node-jsonfile/pull/138))
6.0.1 / 2020-03-07
------------------
- Update dependency ([#130](https://github.com/jprichardson/node-jsonfile/pull/130))
- Fix code style ([#129](https://github.com/jprichardson/node-jsonfile/pull/129))
6.0.0 / 2020-02-24
------------------
- **BREAKING:** Drop support for Node 6 & 8 ([#128](https://github.com/jprichardson/node-jsonfile/pull/128))
- **BREAKING:** Do not allow passing `null` as options to `readFile()` or `writeFile()` ([#128](https://github.com/jprichardson/node-jsonfile/pull/128))
- Refactor internals ([#128](https://github.com/jprichardson/node-jsonfile/pull/128))
5.0.0 / 2018-09-08
------------------
- **BREAKING:** Drop Node 4 support
- **BREAKING:** If no callback is passed to an asynchronous method, a promise is now returned ([#109](https://github.com/jprichardson/node-jsonfile/pull/109))
- Cleanup docs
4.0.0 / 2017-07-12
------------------
- **BREAKING:** Remove global `spaces` option.
- **BREAKING:** Drop support for Node 0.10, 0.12, and io.js.
- Remove undocumented `passParsingErrors` option.
- Added `EOL` override option to `writeFile` when using `spaces`. [#89]
3.0.1 / 2017-07-05
------------------
- Fixed bug in `writeFile` when there was a serialization error & no callback was passed. In previous versions, an empty file would be written; now no file is written.
3.0.0 / 2017-04-25
------------------
- Changed behavior of `throws` option for `readFileSync`; now does not throw filesystem errors when `throws` is `false`
2.4.0 / 2016-09-15
------------------
### Changed
- added optional support for `graceful-fs` [#62]
2.3.1 / 2016-05-13
------------------
- fix to support BOM. [#45][#45]
2.3.0 / 2016-04-16
------------------
- add `throws` to `readFile()`. See [#39][#39]
- add support for any arbitrary `fs` module. Useful with [mock-fs](https://www.npmjs.com/package/mock-fs)
2.2.3 / 2015-10-14
------------------
- include file name in parse error. See: https://github.com/jprichardson/node-jsonfile/pull/34
2.2.2 / 2015-09-16
------------------
- split out tests into separate files
- fixed `throws` when set to `true` in `readFileSync()`. See: https://github.com/jprichardson/node-jsonfile/pull/33
2.2.1 / 2015-06-25
------------------
- fixed regression when passing in string as encoding for options in `writeFile()` and `writeFileSync()`. See: https://github.com/jprichardson/node-jsonfile/issues/28
2.2.0 / 2015-06-25
------------------
- added `options.spaces` to `writeFile()` and `writeFileSync()`
2.1.2 / 2015-06-22
------------------
- fixed if passed `readFileSync(file, 'utf8')`. See: https://github.com/jprichardson/node-jsonfile/issues/25
2.1.1 / 2015-06-19
------------------
- fixed regressions if `null` is passed for options. See: https://github.com/jprichardson/node-jsonfile/issues/24
2.1.0 / 2015-06-19
------------------
- cleanup: JavaScript Standard Style, rename files, dropped terst for assert
- methods now support JSON revivers/replacers
2.0.1 / 2015-05-24
------------------
- update license attribute https://github.com/jprichardson/node-jsonfile/pull/21
2.0.0 / 2014-07-28
------------------
* added `\n` to end of file on write. [#14](https://github.com/jprichardson/node-jsonfile/pull/14)
* added `options.throws` to `readFileSync()`
* dropped support for Node v0.8
1.2.0 / 2014-06-29
------------------
* removed semicolons
* bugfix: passed `options` to `fs.readFile` and `fs.readFileSync`. This technically changes behavior, but
changes it according to docs. [#12][#12]
1.1.1 / 2013-11-11
------------------
* fixed catching of callback bug (ffissore / #5)
1.1.0 / 2013-10-11
------------------
* added `options` param to methods, (seanodell / #4)
1.0.1 / 2013-09-05
------------------
* removed `homepage` field from package.json to remove NPM warning
1.0.0 / 2013-06-28
------------------
* added `.npmignore`, #1
* changed spacing default from `4` to `2` to follow Node conventions
0.0.1 / 2012-09-10
------------------
* Initial release.
[#89]: https://github.com/jprichardson/node-jsonfile/pull/89
[#45]: https://github.com/jprichardson/node-jsonfile/issues/45 "Reading of UTF8-encoded (w/ BOM) files fails"
[#44]: https://github.com/jprichardson/node-jsonfile/issues/44 "Extra characters in written file"
[#43]: https://github.com/jprichardson/node-jsonfile/issues/43 "Prettyfy json when written to file"
[#42]: https://github.com/jprichardson/node-jsonfile/pull/42 "Moved fs.readFileSync within the try/catch"
[#41]: https://github.com/jprichardson/node-jsonfile/issues/41 "Linux: Hidden file not working"
[#40]: https://github.com/jprichardson/node-jsonfile/issues/40 "autocreate folder doesn't work from Path-value"
[#39]: https://github.com/jprichardson/node-jsonfile/pull/39 "Add `throws` option for readFile (async)"
[#38]: https://github.com/jprichardson/node-jsonfile/pull/38 "Update README.md writeFile[Sync] signature"
[#37]: https://github.com/jprichardson/node-jsonfile/pull/37 "support append file"
[#36]: https://github.com/jprichardson/node-jsonfile/pull/36 "Add typescript definition file."
[#35]: https://github.com/jprichardson/node-jsonfile/pull/35 "Add typescript definition file."
[#34]: https://github.com/jprichardson/node-jsonfile/pull/34 "readFile JSON parse error includes filename"
[#33]: https://github.com/jprichardson/node-jsonfile/pull/33 "fix throw->throws typo in readFileSync()"
[#32]: https://github.com/jprichardson/node-jsonfile/issues/32 "readFile & readFileSync can possible have strip-comments as an option?"
[#31]: https://github.com/jprichardson/node-jsonfile/pull/31 "[Modify] Support string include is unicode escape string"
[#30]: https://github.com/jprichardson/node-jsonfile/issues/30 "How to use Jsonfile package in Meteor.js App?"
[#29]: https://github.com/jprichardson/node-jsonfile/issues/29 "writefile callback if no error?"
[#28]: https://github.com/jprichardson/node-jsonfile/issues/28 "writeFile options argument broken "
[#27]: https://github.com/jprichardson/node-jsonfile/pull/27 "Use svg instead of png to get better image quality"
[#26]: https://github.com/jprichardson/node-jsonfile/issues/26 "Breaking change to fs-extra"
[#25]: https://github.com/jprichardson/node-jsonfile/issues/25 "support string encoding param for read methods"
[#24]: https://github.com/jprichardson/node-jsonfile/issues/24 "readFile: Passing in null options with a callback throws an error"
[#23]: https://github.com/jprichardson/node-jsonfile/pull/23 "Add appendFile and appendFileSync"
[#22]: https://github.com/jprichardson/node-jsonfile/issues/22 "Default value for spaces in readme.md is outdated"
[#21]: https://github.com/jprichardson/node-jsonfile/pull/21 "Update license attribute"
[#20]: https://github.com/jprichardson/node-jsonfile/issues/20 "Add simple caching functionallity"
[#19]: https://github.com/jprichardson/node-jsonfile/pull/19 "Add appendFileSync method"
[#18]: https://github.com/jprichardson/node-jsonfile/issues/18 "Add updateFile and updateFileSync methods"
[#17]: https://github.com/jprichardson/node-jsonfile/issues/17 "seem read & write sync has sequentially problem"
[#16]: https://github.com/jprichardson/node-jsonfile/pull/16 "export spaces defaulted to null"
[#15]: https://github.com/jprichardson/node-jsonfile/issues/15 "`jsonfile.spaces` should default to `null`"
[#14]: https://github.com/jprichardson/node-jsonfile/pull/14 "Add EOL at EOF"
[#13]: https://github.com/jprichardson/node-jsonfile/issues/13 "Add a final newline"
[#12]: https://github.com/jprichardson/node-jsonfile/issues/12 "readFile doesn't accept options"
[#11]: https://github.com/jprichardson/node-jsonfile/pull/11 "Added try,catch to readFileSync"
[#10]: https://github.com/jprichardson/node-jsonfile/issues/10 "No output or error from writeFile"
[#9]: https://github.com/jprichardson/node-jsonfile/pull/9 "Change 'js' to 'jf' in example."
[#8]: https://github.com/jprichardson/node-jsonfile/pull/8 "Updated forgotten module.exports to me."
[#7]: https://github.com/jprichardson/node-jsonfile/pull/7 "Add file name in error message"
[#6]: https://github.com/jprichardson/node-jsonfile/pull/6 "Use graceful-fs when possible"
[#5]: https://github.com/jprichardson/node-jsonfile/pull/5 "Jsonfile doesn't behave nicely when used inside a test suite."
[#4]: https://github.com/jprichardson/node-jsonfile/pull/4 "Added options parameter to writeFile and writeFileSync"
[#3]: https://github.com/jprichardson/node-jsonfile/issues/3 "test2"
[#2]: https://github.com/jprichardson/node-jsonfile/issues/2 "homepage field must be a string url. Deleted."
[#1]: https://github.com/jprichardson/node-jsonfile/pull/1 "adding an `.npmignore` file"

View File

@ -0,0 +1,15 @@
(The MIT License)
Copyright (c) 2012-2015, JP Richardson <jprichardson@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
(the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -0,0 +1,230 @@
Node.js - jsonfile
================
Easily read/write JSON files in Node.js. _Note: this module cannot be used in the browser._
[![npm Package](https://img.shields.io/npm/v/jsonfile.svg?style=flat-square)](https://www.npmjs.org/package/jsonfile)
[![build status](https://secure.travis-ci.org/jprichardson/node-jsonfile.svg)](http://travis-ci.org/jprichardson/node-jsonfile)
[![windows Build status](https://img.shields.io/appveyor/ci/jprichardson/node-jsonfile/master.svg?label=windows%20build)](https://ci.appveyor.com/project/jprichardson/node-jsonfile/branch/master)
<a href="https://github.com/feross/standard"><img src="https://cdn.rawgit.com/feross/standard/master/sticker.svg" alt="Standard JavaScript" width="100"></a>
Why?
----
Writing `JSON.stringify()` and then `fs.writeFile()` and `JSON.parse()` with `fs.readFile()` enclosed in `try/catch` blocks became annoying.
Installation
------------
npm install --save jsonfile
API
---
* [`readFile(filename, [options], callback)`](#readfilefilename-options-callback)
* [`readFileSync(filename, [options])`](#readfilesyncfilename-options)
* [`writeFile(filename, obj, [options], callback)`](#writefilefilename-obj-options-callback)
* [`writeFileSync(filename, obj, [options])`](#writefilesyncfilename-obj-options)
----
### readFile(filename, [options], callback)
`options` (`object`, default `undefined`): Pass in any [`fs.readFile`](https://nodejs.org/api/fs.html#fs_fs_readfile_path_options_callback) options or set `reviver` for a [JSON reviver](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse).
- `throws` (`boolean`, default: `true`). If `JSON.parse` throws an error, pass this error to the callback.
If `false`, returns `null` for the object.
```js
const jsonfile = require('jsonfile')
const file = '/tmp/data.json'
jsonfile.readFile(file, function (err, obj) {
if (err) console.error(err)
console.dir(obj)
})
```
You can also use this method with promises. The `readFile` method will return a promise if you do not pass a callback function.
```js
const jsonfile = require('jsonfile')
const file = '/tmp/data.json'
jsonfile.readFile(file)
.then(obj => console.dir(obj))
.catch(error => console.error(error))
```
----
### readFileSync(filename, [options])
`options` (`object`, default `undefined`): Pass in any [`fs.readFileSync`](https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options) options or set `reviver` for a [JSON reviver](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse).
- `throws` (`boolean`, default: `true`). If an error is encountered reading or parsing the file, throw the error. If `false`, returns `null` for the object.
```js
const jsonfile = require('jsonfile')
const file = '/tmp/data.json'
console.dir(jsonfile.readFileSync(file))
```
----
### writeFile(filename, obj, [options], callback)
`options`: Pass in any [`fs.writeFile`](https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback) options or set `replacer` for a [JSON replacer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). Can also pass in `spaces`, or override `EOL` string or set `finalEOL` flag as `false` to not save the file with `EOL` at the end.
```js
const jsonfile = require('jsonfile')
const file = '/tmp/data.json'
const obj = { name: 'JP' }
jsonfile.writeFile(file, obj, function (err) {
if (err) console.error(err)
})
```
Or use with promises as follows:
```js
const jsonfile = require('jsonfile')
const file = '/tmp/data.json'
const obj = { name: 'JP' }
jsonfile.writeFile(file, obj)
.then(res => {
console.log('Write complete')
})
.catch(error => console.error(error))
```
**formatting with spaces:**
```js
const jsonfile = require('jsonfile')
const file = '/tmp/data.json'
const obj = { name: 'JP' }
jsonfile.writeFile(file, obj, { spaces: 2 }, function (err) {
if (err) console.error(err)
})
```
**overriding EOL:**
```js
const jsonfile = require('jsonfile')
const file = '/tmp/data.json'
const obj = { name: 'JP' }
jsonfile.writeFile(file, obj, { spaces: 2, EOL: '\r\n' }, function (err) {
if (err) console.error(err)
})
```
**disabling the EOL at the end of file:**
```js
const jsonfile = require('jsonfile')
const file = '/tmp/data.json'
const obj = { name: 'JP' }
jsonfile.writeFile(file, obj, { spaces: 2, finalEOL: false }, function (err) {
if (err) console.log(err)
})
```
**appending to an existing JSON file:**
You can use `fs.writeFile` option `{ flag: 'a' }` to achieve this.
```js
const jsonfile = require('jsonfile')
const file = '/tmp/mayAlreadyExistedData.json'
const obj = { name: 'JP' }
jsonfile.writeFile(file, obj, { flag: 'a' }, function (err) {
if (err) console.error(err)
})
```
----
### writeFileSync(filename, obj, [options])
`options`: Pass in any [`fs.writeFileSync`](https://nodejs.org/api/fs.html#fs_fs_writefilesync_file_data_options) options or set `replacer` for a [JSON replacer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). Can also pass in `spaces`, or override `EOL` string or set `finalEOL` flag as `false` to not save the file with `EOL` at the end.
```js
const jsonfile = require('jsonfile')
const file = '/tmp/data.json'
const obj = { name: 'JP' }
jsonfile.writeFileSync(file, obj)
```
**formatting with spaces:**
```js
const jsonfile = require('jsonfile')
const file = '/tmp/data.json'
const obj = { name: 'JP' }
jsonfile.writeFileSync(file, obj, { spaces: 2 })
```
**overriding EOL:**
```js
const jsonfile = require('jsonfile')
const file = '/tmp/data.json'
const obj = { name: 'JP' }
jsonfile.writeFileSync(file, obj, { spaces: 2, EOL: '\r\n' })
```
**disabling the EOL at the end of file:**
```js
const jsonfile = require('jsonfile')
const file = '/tmp/data.json'
const obj = { name: 'JP' }
jsonfile.writeFileSync(file, obj, { spaces: 2, finalEOL: false })
```
**appending to an existing JSON file:**
You can use `fs.writeFileSync` option `{ flag: 'a' }` to achieve this.
```js
const jsonfile = require('jsonfile')
const file = '/tmp/mayAlreadyExistedData.json'
const obj = { name: 'JP' }
jsonfile.writeFileSync(file, obj, { flag: 'a' })
```
License
-------
(MIT License)
Copyright 2012-2016, JP Richardson <jprichardson@gmail.com>

View File

@ -0,0 +1,88 @@
let _fs
try {
_fs = require('graceful-fs')
} catch (_) {
_fs = require('fs')
}
const universalify = require('universalify')
const { stringify, stripBom } = require('./utils')
async function _readFile (file, options = {}) {
if (typeof options === 'string') {
options = { encoding: options }
}
const fs = options.fs || _fs
const shouldThrow = 'throws' in options ? options.throws : true
let data = await universalify.fromCallback(fs.readFile)(file, options)
data = stripBom(data)
let obj
try {
obj = JSON.parse(data, options ? options.reviver : null)
} catch (err) {
if (shouldThrow) {
err.message = `${file}: ${err.message}`
throw err
} else {
return null
}
}
return obj
}
const readFile = universalify.fromPromise(_readFile)
function readFileSync (file, options = {}) {
if (typeof options === 'string') {
options = { encoding: options }
}
const fs = options.fs || _fs
const shouldThrow = 'throws' in options ? options.throws : true
try {
let content = fs.readFileSync(file, options)
content = stripBom(content)
return JSON.parse(content, options.reviver)
} catch (err) {
if (shouldThrow) {
err.message = `${file}: ${err.message}`
throw err
} else {
return null
}
}
}
async function _writeFile (file, obj, options = {}) {
const fs = options.fs || _fs
const str = stringify(obj, options)
await universalify.fromCallback(fs.writeFile)(file, str, options)
}
const writeFile = universalify.fromPromise(_writeFile)
function writeFileSync (file, obj, options = {}) {
const fs = options.fs || _fs
const str = stringify(obj, options)
// not sure if fs.writeFileSync returns anything, but just in case
return fs.writeFileSync(file, str, options)
}
const jsonfile = {
readFile,
readFileSync,
writeFile,
writeFileSync
}
module.exports = jsonfile

View File

@ -0,0 +1,20 @@
(The MIT License)
Copyright (c) 2017, Ryan Zimmerman <opensrc@ryanzim.com>
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the 'Software'), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -0,0 +1,76 @@
# universalify
[![Travis branch](https://img.shields.io/travis/RyanZim/universalify/master.svg)](https://travis-ci.org/RyanZim/universalify)
![Coveralls github branch](https://img.shields.io/coveralls/github/RyanZim/universalify/master.svg)
![npm](https://img.shields.io/npm/dm/universalify.svg)
![npm](https://img.shields.io/npm/l/universalify.svg)
Make a callback- or promise-based function support both promises and callbacks.
Uses the native promise implementation.
## Installation
```bash
npm install universalify
```
## API
### `universalify.fromCallback(fn)`
Takes a callback-based function to universalify, and returns the universalified function.
Function must take a callback as the last parameter that will be called with the signature `(error, result)`. `universalify` does not support calling the callback with three or more arguments, and does not ensure that the callback is only called once.
```js
function callbackFn (n, cb) {
setTimeout(() => cb(null, n), 15)
}
const fn = universalify.fromCallback(callbackFn)
// Works with Promises:
fn('Hello World!')
.then(result => console.log(result)) // -> Hello World!
.catch(error => console.error(error))
// Works with Callbacks:
fn('Hi!', (error, result) => {
if (error) return console.error(error)
console.log(result)
// -> Hi!
})
```
### `universalify.fromPromise(fn)`
Takes a promise-based function to universalify, and returns the universalified function.
Function must return a valid JS promise. `universalify` does not ensure that a valid promise is returned.
```js
function promiseFn (n) {
return new Promise(resolve => {
setTimeout(() => resolve(n), 15)
})
}
const fn = universalify.fromPromise(promiseFn)
// Works with Promises:
fn('Hello World!')
.then(result => console.log(result)) // -> Hello World!
.catch(error => console.error(error))
// Works with Callbacks:
fn('Hi!', (error, result) => {
if (error) return console.error(error)
console.log(result)
// -> Hi!
})
```
## License
MIT

View File

@ -0,0 +1,24 @@
'use strict'
exports.fromCallback = function (fn) {
return Object.defineProperty(function (...args) {
if (typeof args[args.length - 1] === 'function') fn.apply(this, args)
else {
return new Promise((resolve, reject) => {
fn.call(
this,
...args,
(err, res) => (err != null) ? reject(err) : resolve(res)
)
})
}
}, 'name', { value: fn.name })
}
exports.fromPromise = function (fn) {
return Object.defineProperty(function (...args) {
const cb = args[args.length - 1]
if (typeof cb !== 'function') return fn.apply(this, args)
else fn.apply(this, args.slice(0, -1)).then(r => cb(null, r), cb)
}, 'name', { value: fn.name })
}

View File

@ -0,0 +1,64 @@
{
"_from": "universalify@^2.0.0",
"_id": "universalify@2.0.0",
"_inBundle": false,
"_integrity": "sha512-hAZsKq7Yy11Zu1DE0OzWjw7nnLZmJZYTDZZyEFHZdUhV8FkH5MCfoU1XMaxXovpyW5nq5scPqq0ZDP9Zyl04oQ==",
"_location": "/app-builder-lib/jsonfile/universalify",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "universalify@^2.0.0",
"name": "universalify",
"escapedName": "universalify",
"rawSpec": "^2.0.0",
"saveSpec": null,
"fetchSpec": "^2.0.0"
},
"_requiredBy": [
"/app-builder-lib/jsonfile"
],
"_resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.0.tgz",
"_shasum": "75a4984efedc4b08975c5aeb73f530d02df25717",
"_spec": "universalify@^2.0.0",
"_where": "/home/shihaam/www/freezer.shihaam.me/node_modules/app-builder-lib/node_modules/jsonfile",
"author": {
"name": "Ryan Zimmerman",
"email": "opensrc@ryanzim.com"
},
"bugs": {
"url": "https://github.com/RyanZim/universalify/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Make a callback- or promise-based function support both promises and callbacks.",
"devDependencies": {
"colortape": "^0.1.2",
"coveralls": "^3.0.1",
"nyc": "^15.0.0",
"standard": "^14.3.1",
"tape": "^5.0.1"
},
"engines": {
"node": ">= 10.0.0"
},
"files": [
"index.js"
],
"homepage": "https://github.com/RyanZim/universalify#readme",
"keywords": [
"callback",
"native",
"promise"
],
"license": "MIT",
"name": "universalify",
"repository": {
"type": "git",
"url": "git+https://github.com/RyanZim/universalify.git"
},
"scripts": {
"test": "standard && nyc tape test/*.js | colortape"
},
"version": "2.0.0"
}

View File

@ -0,0 +1,73 @@
{
"_from": "jsonfile@^6.0.1",
"_id": "jsonfile@6.1.0",
"_inBundle": false,
"_integrity": "sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==",
"_location": "/app-builder-lib/jsonfile",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "jsonfile@^6.0.1",
"name": "jsonfile",
"escapedName": "jsonfile",
"rawSpec": "^6.0.1",
"saveSpec": null,
"fetchSpec": "^6.0.1"
},
"_requiredBy": [
"/app-builder-lib/fs-extra"
],
"_resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz",
"_shasum": "bc55b2634793c679ec6403094eb13698a6ec0aae",
"_spec": "jsonfile@^6.0.1",
"_where": "/home/shihaam/www/freezer.shihaam.me/node_modules/app-builder-lib/node_modules/fs-extra",
"author": {
"name": "JP Richardson",
"email": "jprichardson@gmail.com"
},
"bugs": {
"url": "https://github.com/jprichardson/node-jsonfile/issues"
},
"bundleDependencies": false,
"dependencies": {
"graceful-fs": "^4.1.6",
"universalify": "^2.0.0"
},
"deprecated": false,
"description": "Easily read/write JSON files.",
"devDependencies": {
"mocha": "^8.2.0",
"rimraf": "^2.4.0",
"standard": "^16.0.1"
},
"files": [
"index.js",
"utils.js"
],
"homepage": "https://github.com/jprichardson/node-jsonfile#readme",
"keywords": [
"read",
"write",
"file",
"json",
"fs",
"fs-extra"
],
"license": "MIT",
"main": "index.js",
"name": "jsonfile",
"optionalDependencies": {
"graceful-fs": "^4.1.6"
},
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/jprichardson/node-jsonfile.git"
},
"scripts": {
"lint": "standard",
"test": "npm run lint && npm run unit",
"unit": "mocha"
},
"version": "6.1.0"
}

View File

@ -0,0 +1,14 @@
function stringify (obj, { EOL = '\n', finalEOL = true, replacer = null, spaces } = {}) {
const EOF = finalEOL ? EOL : ''
const str = JSON.stringify(obj, replacer, spaces)
return str.replace(/\n/g, EOL) + EOF
}
function stripBom (content) {
// we do this because JSON.parse would convert it to a utf8 string if encoding wasn't specified
if (Buffer.isBuffer(content)) content = content.toString('utf8')
return content.replace(/^\uFEFF/, '')
}
module.exports = { stringify, stripBom }

View File

@ -0,0 +1,20 @@
(The MIT License)
Copyright (c) 2017, Ryan Zimmerman <opensrc@ryanzim.com>
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the 'Software'), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -0,0 +1,76 @@
# universalify
[![Travis branch](https://img.shields.io/travis/RyanZim/universalify/master.svg)](https://travis-ci.org/RyanZim/universalify)
![Coveralls github branch](https://img.shields.io/coveralls/github/RyanZim/universalify/master.svg)
![npm](https://img.shields.io/npm/dm/universalify.svg)
![npm](https://img.shields.io/npm/l/universalify.svg)
Make a callback- or promise-based function support both promises and callbacks.
Uses the native promise implementation.
## Installation
```bash
npm install universalify
```
## API
### `universalify.fromCallback(fn)`
Takes a callback-based function to universalify, and returns the universalified function.
Function must take a callback as the last parameter that will be called with the signature `(error, result)`. `universalify` does not support calling the callback with three or more arguments, and does not ensure that the callback is only called once.
```js
function callbackFn (n, cb) {
setTimeout(() => cb(null, n), 15)
}
const fn = universalify.fromCallback(callbackFn)
// Works with Promises:
fn('Hello World!')
.then(result => console.log(result)) // -> Hello World!
.catch(error => console.error(error))
// Works with Callbacks:
fn('Hi!', (error, result) => {
if (error) return console.error(error)
console.log(result)
// -> Hi!
})
```
### `universalify.fromPromise(fn)`
Takes a promise-based function to universalify, and returns the universalified function.
Function must return a valid JS promise. `universalify` does not ensure that a valid promise is returned.
```js
function promiseFn (n) {
return new Promise(resolve => {
setTimeout(() => resolve(n), 15)
})
}
const fn = universalify.fromPromise(promiseFn)
// Works with Promises:
fn('Hello World!')
.then(result => console.log(result)) // -> Hello World!
.catch(error => console.error(error))
// Works with Callbacks:
fn('Hi!', (error, result) => {
if (error) return console.error(error)
console.log(result)
// -> Hi!
})
```
## License
MIT

View File

@ -0,0 +1,23 @@
'use strict'
exports.fromCallback = function (fn) {
return Object.defineProperty(function (...args) {
if (typeof args[args.length - 1] === 'function') fn.apply(this, args)
else {
return new Promise((resolve, reject) => {
fn.apply(
this,
args.concat([(err, res) => err ? reject(err) : resolve(res)])
)
})
}
}, 'name', { value: fn.name })
}
exports.fromPromise = function (fn) {
return Object.defineProperty(function (...args) {
const cb = args[args.length - 1]
if (typeof cb !== 'function') return fn.apply(this, args)
else fn.apply(this, args.slice(0, -1)).then(r => cb(null, r), cb)
}, 'name', { value: fn.name })
}

View File

@ -0,0 +1,64 @@
{
"_from": "universalify@^1.0.0",
"_id": "universalify@1.0.0",
"_inBundle": false,
"_integrity": "sha512-rb6X1W158d7pRQBg5gkR8uPaSfiids68LTJQYOtEUhoJUWBdaQHsuT/EUduxXYxcrt4r5PJ4fuHW1MHT6p0qug==",
"_location": "/app-builder-lib/universalify",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "universalify@^1.0.0",
"name": "universalify",
"escapedName": "universalify",
"rawSpec": "^1.0.0",
"saveSpec": null,
"fetchSpec": "^1.0.0"
},
"_requiredBy": [
"/app-builder-lib/fs-extra"
],
"_resolved": "https://registry.npmjs.org/universalify/-/universalify-1.0.0.tgz",
"_shasum": "b61a1da173e8435b2fe3c67d29b9adf8594bd16d",
"_spec": "universalify@^1.0.0",
"_where": "/home/shihaam/www/freezer.shihaam.me/node_modules/app-builder-lib/node_modules/fs-extra",
"author": {
"name": "Ryan Zimmerman",
"email": "opensrc@ryanzim.com"
},
"bugs": {
"url": "https://github.com/RyanZim/universalify/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Make a callback- or promise-based function support both promises and callbacks.",
"devDependencies": {
"colortape": "^0.1.2",
"coveralls": "^3.0.1",
"nyc": "^15.0.0",
"standard": "^14.3.1",
"tape": "^4.6.3"
},
"engines": {
"node": ">= 10.0.0"
},
"files": [
"index.js"
],
"homepage": "https://github.com/RyanZim/universalify#readme",
"keywords": [
"callback",
"native",
"promise"
],
"license": "MIT",
"name": "universalify",
"repository": {
"type": "git",
"url": "git+https://github.com/RyanZim/universalify.git"
},
"scripts": {
"test": "standard && nyc tape test/*.js | colortape"
},
"version": "1.0.0"
}

View File

@ -0,0 +1,36 @@
import { FileTransformer } from "builder-util/out/fs";
import { AsarIntegrity } from "./asar/integrity";
import { Platform, PlatformPackager, ElectronPlatformName, AfterPackContext } from "./index";
export interface Framework {
readonly name: string;
readonly version: string;
readonly distMacOsAppName: string;
readonly macOsDefaultTargets: Array<string>;
readonly defaultAppIdPrefix: string;
readonly isNpmRebuildRequired: boolean;
readonly isCopyElevateHelper: boolean;
getDefaultIcon?(platform: Platform): string | null;
getMainFile?(platform: Platform): string | null;
getExcludedDependencies?(platform: Platform): Array<string> | null;
prepareApplicationStageDirectory(options: PrepareApplicationStageDirectoryOptions): Promise<any>;
beforeCopyExtraFiles?(options: BeforeCopyExtraFilesOptions): Promise<any>;
afterPack?(context: AfterPackContext): Promise<any>;
createTransformer?(): FileTransformer | null;
}
export interface BeforeCopyExtraFilesOptions {
packager: PlatformPackager<any>;
appOutDir: string;
asarIntegrity: AsarIntegrity | null;
platformName: string;
}
export interface PrepareApplicationStageDirectoryOptions {
readonly packager: PlatformPackager<any>;
/**
* Platform doesn't process application output directory in any way. Unpack implementation must create or empty dir if need.
*/
readonly appOutDir: string;
readonly platformName: ElectronPlatformName;
readonly arch: string;
readonly version: string;
}
export declare function isElectronBased(framework: Framework): boolean;

View File

@ -0,0 +1,12 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.isElectronBased = isElectronBased;
function isElectronBased(framework) {
return framework.name === "electron";
}
// __ts-babel@6.0.4
//# sourceMappingURL=Framework.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../src/Framework.ts"],"names":[],"mappings":";;;;;;;AAmDM,SAAU,eAAV,CAA0B,SAA1B,EAA8C;AAClD,SAAO,SAAS,CAAC,IAAV,KAAmB,UAA1B;AACD,C","sourcesContent":["import { FileTransformer } from \"builder-util/out/fs\"\nimport { AsarIntegrity } from \"./asar/integrity\"\nimport { Platform, PlatformPackager, ElectronPlatformName, AfterPackContext } from \"./index\"\n\nexport interface Framework {\n readonly name: string\n readonly version: string\n readonly distMacOsAppName: string\n readonly macOsDefaultTargets: Array<string>\n readonly defaultAppIdPrefix: string\n\n readonly isNpmRebuildRequired: boolean\n\n readonly isCopyElevateHelper: boolean\n\n getDefaultIcon?(platform: Platform): string | null\n\n getMainFile?(platform: Platform): string | null\n\n getExcludedDependencies?(platform: Platform): Array<string> | null\n\n prepareApplicationStageDirectory(options: PrepareApplicationStageDirectoryOptions): Promise<any>\n\n beforeCopyExtraFiles?(options: BeforeCopyExtraFilesOptions): Promise<any>\n\n afterPack?(context: AfterPackContext): Promise<any>\n\n createTransformer?(): FileTransformer | null\n}\n\nexport interface BeforeCopyExtraFilesOptions {\n packager: PlatformPackager<any>\n appOutDir: string\n\n asarIntegrity: AsarIntegrity | null\n\n // ElectronPlatformName\n platformName: string\n}\n\nexport interface PrepareApplicationStageDirectoryOptions {\n readonly packager: PlatformPackager<any>\n /**\n * Platform doesn't process application output directory in any way. Unpack implementation must create or empty dir if need.\n */\n readonly appOutDir: string\n readonly platformName: ElectronPlatformName\n readonly arch: string\n readonly version: string\n}\n\nexport function isElectronBased(framework: Framework): boolean {\n return framework.name === \"electron\"\n}"],"sourceRoot":""}

View File

@ -0,0 +1,10 @@
import { FileTransformer } from "builder-util/out/fs";
import { Platform } from "./core";
import { LibUiFramework } from "./frameworks/LibUiFramework";
export declare class ProtonFramework extends LibUiFramework {
readonly name = "proton";
readonly defaultAppIdPrefix = "com.proton-native.";
constructor(version: string, distMacOsAppName: string, isUseLaunchUi: boolean);
getDefaultIcon(platform: Platform): string;
createTransformer(): FileTransformer | null;
}

View File

@ -0,0 +1,159 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ProtonFramework = void 0;
function _builderUtil() {
const data = require("builder-util");
_builderUtil = function () {
return data;
};
return data;
}
function _builderUtilRuntime() {
const data = require("builder-util-runtime");
_builderUtilRuntime = function () {
return data;
};
return data;
}
function _core() {
const data = require("./core");
_core = function () {
return data;
};
return data;
}
function _fileTransformer() {
const data = require("./fileTransformer");
_fileTransformer = function () {
return data;
};
return data;
}
function _LibUiFramework() {
const data = require("./frameworks/LibUiFramework");
_LibUiFramework = function () {
return data;
};
return data;
}
function _pathManager() {
const data = require("./util/pathManager");
_pathManager = function () {
return data;
};
return data;
}
class ProtonFramework extends _LibUiFramework().LibUiFramework {
constructor(version, distMacOsAppName, isUseLaunchUi) {
super(version, distMacOsAppName, isUseLaunchUi);
this.name = "proton"; // noinspection JSUnusedGlobalSymbols
this.defaultAppIdPrefix = "com.proton-native.";
}
getDefaultIcon(platform) {
if (platform === _core().Platform.WINDOWS) {
return (0, _pathManager().getTemplatePath)("icons/proton-native/proton-native.ico");
} else if (platform === _core().Platform.LINUX) {
return (0, _pathManager().getTemplatePath)("icons/proton-native/linux");
} else {
return (0, _pathManager().getTemplatePath)("icons/proton-native/proton-native.icns");
}
}
createTransformer() {
let babel;
const babelOptions = {
ast: false,
sourceMaps: "inline"
};
if (process.env.TEST_SET_BABEL_PRESET === "true") {
babel = require("@babel/core"); // eslint-disable-next-line @typescript-eslint/no-use-before-define
babel = testOnlyBabel(babel, babelOptions, this.version);
} else {
try {
babel = require("babel-core");
} catch (e) {
// babel isn't installed
_builderUtil().log.debug(null, "don't transpile source code using Babel");
return null;
}
}
_builderUtil().log.info({
options: (0, _builderUtilRuntime().safeStringifyJson)(babelOptions, new Set(["presets"]))
}, "transpile source code using Babel");
return file => {
if (!(file.endsWith(".js") || file.endsWith(".jsx")) || file.includes(_fileTransformer().NODE_MODULES_PATTERN)) {
return null;
}
return new Promise((resolve, reject) => {
return babel.transformFile(file, babelOptions, (error, result) => {
if (error == null) {
resolve(result.code);
} else {
reject(error);
}
});
});
};
}
}
exports.ProtonFramework = ProtonFramework;
function testOnlyBabel(babel, babelOptions, nodeVersion) {
// out test dir can be located outside of electron-builder node_modules and babel cannot resolve string names of preset
babelOptions.presets = [[require("@babel/preset-env").default, {
targets: {
node: nodeVersion
}
}], require("@babel/preset-react")];
babelOptions.plugins = [// stage 0
require("@babel/plugin-proposal-function-bind").default, // stage 1
require("@babel/plugin-proposal-export-default-from").default, require("@babel/plugin-proposal-logical-assignment-operators").default, [require("@babel/plugin-proposal-optional-chaining").default, {
loose: false
}], [require("@babel/plugin-proposal-pipeline-operator").default, {
proposal: "minimal"
}], [require("@babel/plugin-proposal-nullish-coalescing-operator").default, {
loose: false
}], require("@babel/plugin-proposal-do-expressions").default, // stage 2
[require("@babel/plugin-proposal-decorators").default, {
legacy: true
}], require("@babel/plugin-proposal-function-sent").default, require("@babel/plugin-proposal-export-namespace-from").default, require("@babel/plugin-proposal-numeric-separator").default, require("@babel/plugin-proposal-throw-expressions").default, // stage 3
require("@babel/plugin-syntax-dynamic-import").default, require("@babel/plugin-syntax-import-meta").default, [require("@babel/plugin-proposal-class-properties").default, {
loose: false
}], require("@babel/plugin-proposal-json-strings").default];
babelOptions.babelrc = false;
return babel;
}
// __ts-babel@6.0.4
//# sourceMappingURL=ProtonFramework.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,28 @@
import { PlatformSpecificBuildOptions } from "./options/PlatformSpecificBuildOptions";
import { Packager } from "./packager";
export declare function smarten(s: string): string;
export declare class AppInfo {
private readonly info;
private readonly platformSpecificOptions;
readonly description: string;
readonly version: string;
readonly shortVersion: string | undefined;
readonly shortVersionWindows: string | undefined;
readonly buildNumber: string | undefined;
readonly buildVersion: string;
readonly productName: string;
readonly productFilename: string;
constructor(info: Packager, buildVersion: string | null | undefined, platformSpecificOptions?: PlatformSpecificBuildOptions | null);
get channel(): string | null;
getVersionInWeirdWindowsForm(isSetBuildNumber?: boolean): string;
private get notNullDevMetadata();
get companyName(): string | null;
get id(): string;
get macBundleIdentifier(): string;
get name(): string;
get linuxPackageName(): string;
get sanitizedName(): string;
get updaterCacheDirName(): string;
get copyright(): string;
computePackageUrl(): Promise<string | null>;
}

211
buildfiles/node_modules/app-builder-lib/out/appInfo.js generated vendored Normal file
View File

@ -0,0 +1,211 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.smarten = smarten;
exports.filterCFBundleIdentifier = filterCFBundleIdentifier;
exports.AppInfo = void 0;
function _builderUtil() {
const data = require("builder-util");
_builderUtil = function () {
return data;
};
return data;
}
function _sanitizeFilename() {
const data = _interopRequireDefault(require("sanitize-filename"));
_sanitizeFilename = function () {
return data;
};
return data;
}
function _semver() {
const data = require("semver");
_semver = function () {
return data;
};
return data;
}
function _macroExpander() {
const data = require("./util/macroExpander");
_macroExpander = function () {
return data;
};
return data;
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// fpm bug - rpm build --description is not escaped, well... decided to replace quite to smart quote
// http://leancrew.com/all-this/2010/11/smart-quotes-in-javascript/
function smarten(s) {
// opening singles
s = s.replace(/(^|[-\u2014\s(["])'/g, "$1\u2018"); // closing singles & apostrophes
s = s.replace(/'/g, "\u2019"); // opening doubles
s = s.replace(/(^|[-\u2014/[(\u2018\s])"/g, "$1\u201c"); // closing doubles
s = s.replace(/"/g, "\u201d");
return s;
}
class AppInfo {
constructor(info, buildVersion, platformSpecificOptions = null) {
this.info = info;
this.platformSpecificOptions = platformSpecificOptions;
this.description = smarten(this.info.metadata.description || "");
this.version = info.metadata.version;
if (buildVersion == null) {
buildVersion = info.config.buildVersion;
}
this.buildNumber = process.env.BUILD_NUMBER || process.env.TRAVIS_BUILD_NUMBER || process.env.APPVEYOR_BUILD_NUMBER || process.env.CIRCLE_BUILD_NUM || process.env.BUILD_BUILDNUMBER || process.env.CI_PIPELINE_IID;
if (buildVersion == null) {
buildVersion = this.version;
if (!(0, _builderUtil().isEmptyOrSpaces)(this.buildNumber)) {
buildVersion += `.${this.buildNumber}`;
}
}
this.buildVersion = buildVersion;
if (info.metadata.shortVersion) {
this.shortVersion = info.metadata.shortVersion;
}
if (info.metadata.shortVersionWindows) {
this.shortVersionWindows = info.metadata.shortVersionWindows;
}
this.productName = info.config.productName || info.metadata.productName || info.metadata.name;
this.productFilename = (0, _sanitizeFilename().default)(this.productName);
}
get channel() {
const prereleaseInfo = (0, _semver().prerelease)(this.version);
if (prereleaseInfo != null && prereleaseInfo.length > 0) {
return prereleaseInfo[0];
}
return null;
}
getVersionInWeirdWindowsForm(isSetBuildNumber = true) {
const parsedVersion = new (_semver().SemVer)(this.version); // https://github.com/electron-userland/electron-builder/issues/2635#issuecomment-371792272
let buildNumber = isSetBuildNumber ? this.buildNumber : null;
if (buildNumber == null || !/^\d+$/.test(buildNumber)) {
buildNumber = "0";
}
return `${parsedVersion.major}.${parsedVersion.minor}.${parsedVersion.patch}.${buildNumber}`;
}
get notNullDevMetadata() {
return this.info.devMetadata || {};
}
get companyName() {
const author = this.info.metadata.author || this.notNullDevMetadata.author;
return author == null ? null : author.name;
}
get id() {
let appId = null;
for (const options of [this.platformSpecificOptions, this.info.config]) {
if (options != null && appId == null) {
appId = options.appId;
}
}
const generateDefaultAppId = () => {
const info = this.info;
return `${info.framework.defaultAppIdPrefix}${info.metadata.name.toLowerCase()}`;
};
if (appId != null && (appId === "your.id" || (0, _builderUtil().isEmptyOrSpaces)(appId))) {
const incorrectAppId = appId;
appId = generateDefaultAppId();
_builderUtil().log.warn(`do not use "${incorrectAppId}" as appId, "${appId}" will be used instead`);
}
return appId == null ? generateDefaultAppId() : appId;
}
get macBundleIdentifier() {
return filterCFBundleIdentifier(this.id);
}
get name() {
return this.info.metadata.name;
}
get linuxPackageName() {
const name = this.name; // https://github.com/electron-userland/electron-builder/issues/2963
return name.startsWith("@") ? this.productFilename : name;
}
get sanitizedName() {
return (0, _sanitizeFilename().default)(this.name);
}
get updaterCacheDirName() {
return this.sanitizedName.toLowerCase() + "-updater";
}
get copyright() {
const copyright = this.info.config.copyright;
if (copyright != null) {
return (0, _macroExpander().expandMacro)(copyright, null, this);
}
return `Copyright © ${new Date().getFullYear()} ${this.companyName || this.productName}`;
}
async computePackageUrl() {
const url = this.info.metadata.homepage || this.notNullDevMetadata.homepage;
if (url != null) {
return url;
}
const info = await this.info.repositoryInfo;
return info == null || info.type !== "github" ? null : `https://${info.domain}/${info.user}/${info.project}`;
}
}
/** @internal */
exports.AppInfo = AppInfo;
function filterCFBundleIdentifier(identifier) {
// Remove special characters and allow only alphanumeric (A-Z,a-z,0-9), hyphen (-), and period (.)
// Apple documentation: https://developer.apple.com/library/mac/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html#//apple_ref/doc/uid/20001431-102070
return identifier.replace(/ /g, "-").replace(/[^a-zA-Z0-9.-]/g, "");
}
// __ts-babel@6.0.4
//# sourceMappingURL=appInfo.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,2 @@
export declare function readAsar(archive: string): Promise<AsarFilesystem>;
export declare function readAsarJson(archive: string, file: string): Promise<any>;

View File

@ -0,0 +1,213 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.readAsar = readAsar;
exports.readAsarJson = readAsarJson;
exports.AsarFilesystem = exports.Node = void 0;
function _chromiumPickleJs() {
const data = require("chromium-pickle-js");
_chromiumPickleJs = function () {
return data;
};
return data;
}
function _fsExtra() {
const data = require("fs-extra");
_fsExtra = function () {
return data;
};
return data;
}
var path = _interopRequireWildcard(require("path"));
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
/** @internal */
class Node {}
/** @internal */
exports.Node = Node;
class AsarFilesystem {
constructor(src, header = new Node(), headerSize = -1) {
this.src = src;
this.header = header;
this.headerSize = headerSize;
this.offset = 0;
if (this.header.files == null) {
this.header.files = {};
}
}
searchNodeFromDirectory(p, isCreate) {
let node = this.header;
for (const dir of p.split(path.sep)) {
if (dir !== ".") {
let child = node.files[dir];
if (child == null) {
if (!isCreate) {
return null;
}
child = new Node();
child.files = {};
node.files[dir] = child;
}
node = child;
}
}
return node;
}
getOrCreateNode(p) {
if (p == null || p.length === 0) {
return this.header;
}
const name = path.basename(p);
const dirNode = this.searchNodeFromDirectory(path.dirname(p), true);
if (dirNode.files == null) {
dirNode.files = {};
}
let result = dirNode.files[name];
if (result == null) {
result = new Node();
dirNode.files[name] = result;
}
return result;
}
addFileNode(file, dirNode, size, unpacked, stat) {
if (size > 4294967295) {
throw new Error(`${file}: file size cannot be larger than 4.2GB`);
}
const node = new Node();
node.size = size;
if (unpacked) {
node.unpacked = true;
} else {
// electron expects string
node.offset = this.offset.toString();
if (process.platform !== "win32" && stat.mode & 0o100) {
node.executable = true;
}
this.offset += node.size;
}
let children = dirNode.files;
if (children == null) {
children = {};
dirNode.files = children;
}
children[path.basename(file)] = node;
return node;
}
getNode(p) {
const node = this.searchNodeFromDirectory(path.dirname(p), false);
return node.files[path.basename(p)];
}
getFile(p, followLinks = true) {
const info = this.getNode(p); // if followLinks is false we don't resolve symlinks
return followLinks && info.link != null ? this.getFile(info.link) : info;
}
async readJson(file) {
return JSON.parse((await this.readFile(file)).toString());
}
readFile(file) {
return readFileFromAsar(this, file, this.getFile(file));
}
}
exports.AsarFilesystem = AsarFilesystem;
async function readAsar(archive) {
const fd = await (0, _fsExtra().open)(archive, "r");
let size;
let headerBuf;
try {
const sizeBuf = Buffer.allocUnsafe(8);
if ((await (0, _fsExtra().read)(fd, sizeBuf, 0, 8, null)).bytesRead !== 8) {
throw new Error("Unable to read header size");
}
const sizePickle = (0, _chromiumPickleJs().createFromBuffer)(sizeBuf);
size = sizePickle.createIterator().readUInt32();
headerBuf = Buffer.allocUnsafe(size);
if ((await (0, _fsExtra().read)(fd, headerBuf, 0, size, null)).bytesRead !== size) {
throw new Error("Unable to read header");
}
} finally {
await (0, _fsExtra().close)(fd);
}
const headerPickle = (0, _chromiumPickleJs().createFromBuffer)(headerBuf);
const header = headerPickle.createIterator().readString();
return new AsarFilesystem(archive, JSON.parse(header), size);
}
async function readAsarJson(archive, file) {
const fs = await readAsar(archive);
return await fs.readJson(file);
}
async function readFileFromAsar(filesystem, filename, info) {
const size = info.size;
const buffer = Buffer.allocUnsafe(size);
if (size <= 0) {
return buffer;
}
if (info.unpacked) {
return await (0, _fsExtra().readFile)(path.join(`${filesystem.src}.unpacked`, filename));
}
const fd = await (0, _fsExtra().open)(filesystem.src, "r");
try {
const offset = 8 + filesystem.headerSize + parseInt(info.offset, 10);
await (0, _fsExtra().read)(fd, buffer, 0, size, offset);
} finally {
await (0, _fsExtra().close)(fd);
}
return buffer;
}
// __ts-babel@6.0.4
//# sourceMappingURL=asar.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1 @@
export {};

View File

@ -0,0 +1,66 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.checkFileInArchive = checkFileInArchive;
function _fs() {
const data = require("builder-util/out/fs");
_fs = function () {
return data;
};
return data;
}
function _asar() {
const data = require("./asar");
_asar = function () {
return data;
};
return data;
}
/** @internal */
async function checkFileInArchive(asarFile, relativeFile, messagePrefix) {
function error(text) {
return new Error(`${messagePrefix} "${relativeFile}" in the "${asarFile}" ${text}`);
}
let fs;
try {
fs = await (0, _asar().readAsar)(asarFile);
} catch (e) {
throw error(`is corrupted: ${e}`);
}
let stat;
try {
stat = fs.getFile(relativeFile);
} catch (e) {
const fileStat = await (0, _fs().statOrNull)(asarFile);
if (fileStat == null) {
throw error(`does not exist. Seems like a wrong configuration.`);
} // asar throws error on access to undefined object (info.link)
stat = null;
}
if (stat == null) {
throw error(`does not exist. Seems like a wrong configuration.`);
}
if (stat.size === 0) {
throw error(`is corrupted: size 0`);
}
}
// __ts-babel@6.0.4
//# sourceMappingURL=asarFileChecker.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../src/asar/asarFileChecker.ts"],"names":[],"mappings":";;;;;;;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAEA;AACO,eAAe,kBAAf,CAAkC,QAAlC,EAAoD,YAApD,EAA0E,aAA1E,EAA+F;AACpG,WAAS,KAAT,CAAe,IAAf,EAA2B;AACzB,WAAO,IAAI,KAAJ,CAAU,GAAG,aAAa,KAAK,YAAY,aAAa,QAAQ,KAAK,IAAI,EAAzE,CAAP;AACD;;AAED,MAAI,EAAJ;;AACA,MAAI;AACF,IAAA,EAAE,GAAG,MAAM,sBAAS,QAAT,CAAX;AACD,GAFD,CAGA,OAAO,CAAP,EAAU;AACR,UAAM,KAAK,CAAC,iBAAiB,CAAC,EAAnB,CAAX;AACD;;AAED,MAAI,IAAJ;;AACA,MAAI;AACF,IAAA,IAAI,GAAG,EAAE,CAAC,OAAH,CAAW,YAAX,CAAP;AACD,GAFD,CAGA,OAAO,CAAP,EAAU;AACR,UAAM,QAAQ,GAAG,MAAM,sBAAW,QAAX,CAAvB;;AACA,QAAI,QAAQ,IAAI,IAAhB,EAAsB;AACpB,YAAM,KAAK,CAAC,mDAAD,CAAX;AACD,KAJO,CAMR;;;AACA,IAAA,IAAI,GAAG,IAAP;AACD;;AAED,MAAI,IAAI,IAAI,IAAZ,EAAkB;AAChB,UAAM,KAAK,CAAC,mDAAD,CAAX;AACD;;AACD,MAAI,IAAI,CAAC,IAAL,KAAc,CAAlB,EAAqB;AACnB,UAAM,KAAK,CAAC,sBAAD,CAAX;AACD;AACF,C","sourcesContent":["import { statOrNull } from \"builder-util/out/fs\"\nimport { Node, readAsar } from \"./asar\"\n\n/** @internal */\nexport async function checkFileInArchive(asarFile: string, relativeFile: string, messagePrefix: string) {\n function error(text: string) {\n return new Error(`${messagePrefix} \"${relativeFile}\" in the \"${asarFile}\" ${text}`)\n }\n\n let fs\n try {\n fs = await readAsar(asarFile)\n }\n catch (e) {\n throw error(`is corrupted: ${e}`)\n }\n\n let stat: Node | null\n try {\n stat = fs.getFile(relativeFile)\n }\n catch (e) {\n const fileStat = await statOrNull(asarFile)\n if (fileStat == null) {\n throw error(`does not exist. Seems like a wrong configuration.`)\n }\n\n // asar throws error on access to undefined object (info.link)\n stat = null\n }\n\n if (stat == null) {\n throw error(`does not exist. Seems like a wrong configuration.`)\n }\n if (stat.size === 0) {\n throw error(`is corrupted: size 0`)\n }\n}\n"],"sourceRoot":""}

View File

@ -0,0 +1 @@
export {};

View File

@ -0,0 +1,347 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.AsarPackager = void 0;
function _builderUtil() {
const data = require("builder-util");
_builderUtil = function () {
return data;
};
return data;
}
function _fs() {
const data = require("builder-util/out/fs");
_fs = function () {
return data;
};
return data;
}
var _fs2 = require("fs");
function _fsExtra() {
const data = require("fs-extra");
_fsExtra = function () {
return data;
};
return data;
}
var path = _interopRequireWildcard(require("path"));
function _appFileCopier() {
const data = require("../util/appFileCopier");
_appFileCopier = function () {
return data;
};
return data;
}
function _asar() {
const data = require("./asar");
_asar = function () {
return data;
};
return data;
}
function _unpackDetector() {
const data = require("./unpackDetector");
_unpackDetector = function () {
return data;
};
return data;
}
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
// eslint-disable-next-line @typescript-eslint/no-var-requires
const pickle = require("chromium-pickle-js");
/** @internal */
class AsarPackager {
constructor(src, destination, options, unpackPattern) {
this.src = src;
this.destination = destination;
this.options = options;
this.unpackPattern = unpackPattern;
this.fs = new (_asar().AsarFilesystem)(this.src);
this.outFile = path.join(destination, "app.asar");
this.unpackedDest = `${this.outFile}.unpacked`;
} // sort files to minimize file change (i.e. asar file is not changed dramatically on small change)
async pack(fileSets, packager) {
if (this.options.ordering != null) {
// ordering doesn't support transformed files, but ordering is not used functionality - wait user report to fix it
await order(fileSets[0].files, this.options.ordering, fileSets[0].src);
}
await (0, _fsExtra().ensureDir)(path.dirname(this.outFile));
const unpackedFileIndexMap = new Map();
for (const fileSet of fileSets) {
unpackedFileIndexMap.set(fileSet, await this.createPackageFromFiles(fileSet, packager.info));
}
await this.writeAsarFile(fileSets, unpackedFileIndexMap);
}
async createPackageFromFiles(fileSet, packager) {
const metadata = fileSet.metadata; // search auto unpacked dir
const unpackedDirs = new Set();
const rootForAppFilesWithoutAsar = path.join(this.destination, "app");
if (this.options.smartUnpack !== false) {
await (0, _unpackDetector().detectUnpackedDirs)(fileSet, unpackedDirs, this.unpackedDest, rootForAppFilesWithoutAsar);
}
const dirToCreateForUnpackedFiles = new Set(unpackedDirs);
const correctDirNodeUnpackedFlag = async (filePathInArchive, dirNode) => {
for (const dir of unpackedDirs) {
if (filePathInArchive.length > dir.length + 2 && filePathInArchive[dir.length] === path.sep && filePathInArchive.startsWith(dir)) {
dirNode.unpacked = true;
unpackedDirs.add(filePathInArchive); // not all dirs marked as unpacked after first iteration - because node module dir can be marked as unpacked after processing node module dir content
// e.g. node-notifier/example/advanced.js processed, but only on process vendor/terminal-notifier.app module will be marked as unpacked
await (0, _fsExtra().ensureDir)(path.join(this.unpackedDest, filePathInArchive));
break;
}
}
};
const transformedFiles = fileSet.transformedFiles;
const taskManager = new (_builderUtil().AsyncTaskManager)(packager.cancellationToken);
const fileCopier = new (_fs().FileCopier)();
let currentDirNode = null;
let currentDirPath = null;
const unpackedFileIndexSet = new Set();
for (let i = 0, n = fileSet.files.length; i < n; i++) {
const file = fileSet.files[i];
const stat = metadata.get(file);
if (stat == null) {
continue;
}
const pathInArchive = path.relative(rootForAppFilesWithoutAsar, (0, _appFileCopier().getDestinationPath)(file, fileSet));
if (stat.isSymbolicLink()) {
const s = stat;
this.fs.getOrCreateNode(pathInArchive).link = s.relativeLink;
s.pathInArchive = pathInArchive;
unpackedFileIndexSet.add(i);
continue;
}
let fileParent = path.dirname(pathInArchive);
if (fileParent === ".") {
fileParent = "";
}
if (currentDirPath !== fileParent) {
if (fileParent.startsWith("..")) {
throw new Error(`Internal error: path must not start with "..": ${fileParent}`);
}
currentDirPath = fileParent;
currentDirNode = this.fs.getOrCreateNode(fileParent); // do not check for root
if (fileParent !== "" && !currentDirNode.unpacked) {
if (unpackedDirs.has(fileParent)) {
currentDirNode.unpacked = true;
} else {
await correctDirNodeUnpackedFlag(fileParent, currentDirNode);
}
}
}
const dirNode = currentDirNode;
const newData = transformedFiles == null ? null : transformedFiles.get(i);
const isUnpacked = dirNode.unpacked || this.unpackPattern != null && this.unpackPattern(file, stat);
this.fs.addFileNode(file, dirNode, newData == null ? stat.size : Buffer.byteLength(newData), isUnpacked, stat);
if (isUnpacked) {
if (!dirNode.unpacked && !dirToCreateForUnpackedFiles.has(fileParent)) {
dirToCreateForUnpackedFiles.add(fileParent);
await (0, _fsExtra().ensureDir)(path.join(this.unpackedDest, fileParent));
}
const unpackedFile = path.join(this.unpackedDest, pathInArchive);
taskManager.addTask(copyFileOrData(fileCopier, newData, file, unpackedFile, stat));
if (taskManager.tasks.length > _fs().MAX_FILE_REQUESTS) {
await taskManager.awaitTasks();
}
unpackedFileIndexSet.add(i);
}
}
if (taskManager.tasks.length > 0) {
await taskManager.awaitTasks();
}
return unpackedFileIndexSet;
}
writeAsarFile(fileSets, unpackedFileIndexMap) {
return new Promise((resolve, reject) => {
const headerPickle = pickle.createEmpty();
headerPickle.writeString(JSON.stringify(this.fs.header));
const headerBuf = headerPickle.toBuffer();
const sizePickle = pickle.createEmpty();
sizePickle.writeUInt32(headerBuf.length);
const sizeBuf = sizePickle.toBuffer();
const writeStream = (0, _fsExtra().createWriteStream)(this.outFile);
writeStream.on("error", reject);
writeStream.on("close", resolve);
writeStream.write(sizeBuf);
let fileSetIndex = 0;
let files = fileSets[0].files;
let metadata = fileSets[0].metadata;
let transformedFiles = fileSets[0].transformedFiles;
let unpackedFileIndexSet = unpackedFileIndexMap.get(fileSets[0]);
const w = index => {
while (true) {
if (index >= files.length) {
if (++fileSetIndex >= fileSets.length) {
writeStream.end();
return;
} else {
files = fileSets[fileSetIndex].files;
metadata = fileSets[fileSetIndex].metadata;
transformedFiles = fileSets[fileSetIndex].transformedFiles;
unpackedFileIndexSet = unpackedFileIndexMap.get(fileSets[fileSetIndex]);
index = 0;
}
}
if (!unpackedFileIndexSet.has(index)) {
break;
} else {
const stat = metadata.get(files[index]);
if (stat != null && stat.isSymbolicLink()) {
(0, _fs2.symlink)(stat.linkRelativeToFile, path.join(this.unpackedDest, stat.pathInArchive), () => w(index + 1));
return;
}
}
index++;
}
const data = transformedFiles == null ? null : transformedFiles.get(index);
const file = files[index];
if (data !== null && data !== undefined) {
writeStream.write(data, () => w(index + 1));
return;
} // https://github.com/yarnpkg/yarn/pull/3539
const stat = metadata.get(file);
if (stat != null && stat.size < 2 * 1024 * 1024) {
(0, _fsExtra().readFile)(file).then(it => {
writeStream.write(it, () => w(index + 1));
}).catch(e => reject(`Cannot read file ${file}: ${e.stack || e}`));
} else {
const readStream = (0, _fsExtra().createReadStream)(file);
readStream.on("error", reject);
readStream.once("end", () => w(index + 1));
readStream.pipe(writeStream, {
end: false
});
}
};
writeStream.write(headerBuf, () => w(0));
});
}
}
exports.AsarPackager = AsarPackager;
async function order(filenames, orderingFile, src) {
const orderingFiles = (await (0, _fsExtra().readFile)(orderingFile, "utf8")).split("\n").map(line => {
if (line.indexOf(":") !== -1) {
line = line.split(":").pop();
}
line = line.trim();
if (line[0] === "/") {
line = line.slice(1);
}
return line;
});
const ordering = [];
for (const file of orderingFiles) {
const pathComponents = file.split(path.sep);
for (const pathComponent of pathComponents) {
ordering.push(path.join(src, pathComponent));
}
}
const sortedFiles = [];
let missing = 0;
const total = filenames.length;
for (const file of ordering) {
if (!sortedFiles.includes(file) && filenames.includes(file)) {
sortedFiles.push(file);
}
}
for (const file of filenames) {
if (!sortedFiles.includes(file)) {
sortedFiles.push(file);
missing += 1;
}
}
_builderUtil().log.info({
coverage: (total - missing) / total * 100
}, "ordering files in ASAR archive");
return sortedFiles;
}
function copyFileOrData(fileCopier, data, source, destination, stats) {
if (data == null) {
return fileCopier.copy(source, destination, stats);
} else {
return (0, _fsExtra().writeFile)(destination, data);
}
}
// __ts-babel@6.0.4
//# sourceMappingURL=asarUtil.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,14 @@
export interface AsarIntegrityOptions {
/**
* Allows external asar files.
*
* @default false
*/
readonly externalAllowed?: boolean;
}
export interface AsarIntegrity extends AsarIntegrityOptions {
checksums: {
[key: string]: string;
};
}
export declare function computeData(resourcesPath: string, options?: AsarIntegrityOptions | null): Promise<AsarIntegrity>;

View File

@ -0,0 +1,77 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.computeData = computeData;
function _bluebirdLst() {
const data = _interopRequireDefault(require("bluebird-lst"));
_bluebirdLst = function () {
return data;
};
return data;
}
function _crypto() {
const data = require("crypto");
_crypto = function () {
return data;
};
return data;
}
var _fs = require("fs");
function _fsExtra() {
const data = require("fs-extra");
_fsExtra = function () {
return data;
};
return data;
}
var path = _interopRequireWildcard(require("path"));
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
async function computeData(resourcesPath, options) {
// sort to produce constant result
const names = (await (0, _fsExtra().readdir)(resourcesPath)).filter(it => it.endsWith(".asar")).sort();
const checksums = await _bluebirdLst().default.map(names, it => hashFile(path.join(resourcesPath, it)));
const result = {};
for (let i = 0; i < names.length; i++) {
result[names[i]] = checksums[i];
}
return {
checksums: result,
...options
};
}
function hashFile(file, algorithm = "sha512", encoding = "base64") {
return new Promise((resolve, reject) => {
const hash = (0, _crypto().createHash)(algorithm);
hash.on("error", reject).setEncoding(encoding);
(0, _fs.createReadStream)(file).on("error", reject).on("end", () => {
hash.end();
resolve(hash.read());
}).pipe(hash, {
end: false
});
});
}
// __ts-babel@6.0.4
//# sourceMappingURL=integrity.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../src/asar/integrity.ts"],"names":[],"mappings":";;;;;;;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;;;;;;;;AAeO,eAAe,WAAf,CAA2B,aAA3B,EAAkD,OAAlD,EAAuF;AAC5F;AACA,QAAM,KAAK,GAAG,CAAC,MAAM,wBAAQ,aAAR,CAAP,EAA+B,MAA/B,CAAsC,EAAE,IAAI,EAAE,CAAC,QAAH,CAAY,OAAZ,CAA5C,EAAkE,IAAlE,EAAd;AACA,QAAM,SAAS,GAAG,MAAM,uBAAgB,GAAhB,CAAoB,KAApB,EAA2B,EAAE,IAAI,QAAQ,CAAC,IAAI,CAAC,IAAL,CAAU,aAAV,EAAyB,EAAzB,CAAD,CAAzC,CAAxB;AAEA,QAAM,MAAM,GAA8B,EAA1C;;AACA,OAAK,IAAI,CAAC,GAAG,CAAb,EAAgB,CAAC,GAAG,KAAK,CAAC,MAA1B,EAAkC,CAAC,EAAnC,EAAuC;AACrC,IAAA,MAAM,CAAC,KAAK,CAAC,CAAD,CAAN,CAAN,GAAmB,SAAS,CAAC,CAAD,CAA5B;AACD;;AACD,SAAO;AAAC,IAAA,SAAS,EAAE,MAAZ;AAAoB,OAAG;AAAvB,GAAP;AACD;;AAED,SAAS,QAAT,CAAkB,IAAlB,EAAgC,SAAA,GAAoB,QAApD,EAA8D,QAAA,GAAwC,QAAtG,EAA8G;AAC5G,SAAO,IAAI,OAAJ,CAAoB,CAAC,OAAD,EAAU,MAAV,KAAoB;AAC7C,UAAM,IAAI,GAAG,0BAAW,SAAX,CAAb;AACA,IAAA,IAAI,CACD,EADH,CACM,OADN,EACe,MADf,EAEG,WAFH,CAEe,QAFf;AAIA,8BAAiB,IAAjB,EACG,EADH,CACM,OADN,EACe,MADf,EAEG,EAFH,CAEM,KAFN,EAEa,MAAK;AACd,MAAA,IAAI,CAAC,GAAL;AACA,MAAA,OAAO,CAAC,IAAI,CAAC,IAAL,EAAD,CAAP;AACD,KALH,EAMG,IANH,CAMQ,IANR,EAMc;AAAC,MAAA,GAAG,EAAE;AAAN,KANd;AAOD,GAbM,CAAP;AAcD,C","sourcesContent":["import BluebirdPromise from \"bluebird-lst\"\nimport { createHash } from \"crypto\"\nimport { createReadStream } from \"fs\"\nimport { readdir } from \"fs-extra\"\nimport * as path from \"path\"\n\nexport interface AsarIntegrityOptions {\n /**\n * Allows external asar files.\n *\n * @default false\n */\n readonly externalAllowed?: boolean\n}\n\nexport interface AsarIntegrity extends AsarIntegrityOptions {\n checksums: { [key: string]: string }\n}\n\nexport async function computeData(resourcesPath: string, options?: AsarIntegrityOptions | null): Promise<AsarIntegrity> {\n // sort to produce constant result\n const names = (await readdir(resourcesPath)).filter(it => it.endsWith(\".asar\")).sort()\n const checksums = await BluebirdPromise.map(names, it => hashFile(path.join(resourcesPath, it)))\n\n const result: { [key: string]: string } = {}\n for (let i = 0; i < names.length; i++) {\n result[names[i]] = checksums[i]\n }\n return {checksums: result, ...options}\n}\n\nfunction hashFile(file: string, algorithm: string = \"sha512\", encoding: \"hex\" | \"base64\" | \"latin1\" = \"base64\") {\n return new Promise<string>((resolve, reject) => {\n const hash = createHash(algorithm)\n hash\n .on(\"error\", reject)\n .setEncoding(encoding)\n\n createReadStream(file)\n .on(\"error\", reject)\n .on(\"end\", () => {\n hash.end()\n resolve(hash.read() as string)\n })\n .pipe(hash, {end: false})\n })\n}"],"sourceRoot":""}

View File

@ -0,0 +1 @@
export declare function isLibOrExe(file: string): boolean;

View File

@ -0,0 +1,206 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.isLibOrExe = isLibOrExe;
exports.detectUnpackedDirs = detectUnpackedDirs;
function _bluebirdLst() {
const data = _interopRequireDefault(require("bluebird-lst"));
_bluebirdLst = function () {
return data;
};
return data;
}
function _builderUtil() {
const data = require("builder-util");
_builderUtil = function () {
return data;
};
return data;
}
function _fs() {
const data = require("builder-util/out/fs");
_fs = function () {
return data;
};
return data;
}
function _fsExtra() {
const data = require("fs-extra");
_fsExtra = function () {
return data;
};
return data;
}
function _isbinaryfile() {
const data = require("isbinaryfile");
_isbinaryfile = function () {
return data;
};
return data;
}
var path = _interopRequireWildcard(require("path"));
function _fileTransformer() {
const data = require("../fileTransformer");
_fileTransformer = function () {
return data;
};
return data;
}
function _appFileCopier() {
const data = require("../util/appFileCopier");
_appFileCopier = function () {
return data;
};
return data;
}
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function addValue(map, key, value) {
let list = map.get(key);
if (list == null) {
list = [value];
map.set(key, list);
} else {
list.push(value);
}
}
function isLibOrExe(file) {
return file.endsWith(".dll") || file.endsWith(".exe") || file.endsWith(".dylib") || file.endsWith(".so");
}
/** @internal */
async function detectUnpackedDirs(fileSet, autoUnpackDirs, unpackedDest, rootForAppFilesWithoutAsar) {
const dirToCreate = new Map();
const metadata = fileSet.metadata;
function addParents(child, root) {
child = path.dirname(child);
if (autoUnpackDirs.has(child)) {
return;
}
do {
autoUnpackDirs.add(child);
const p = path.dirname(child); // create parent dir to be able to copy file later without directory existence check
addValue(dirToCreate, p, path.basename(child));
if (child === root || p === root || autoUnpackDirs.has(p)) {
break;
}
child = p;
} while (true);
autoUnpackDirs.add(root);
}
for (let i = 0, n = fileSet.files.length; i < n; i++) {
const file = fileSet.files[i];
const index = file.lastIndexOf(_fileTransformer().NODE_MODULES_PATTERN);
if (index < 0) {
continue;
}
let nextSlashIndex = file.indexOf(path.sep, index + _fileTransformer().NODE_MODULES_PATTERN.length + 1);
if (nextSlashIndex < 0) {
continue;
}
if (file[index + _fileTransformer().NODE_MODULES_PATTERN.length] === "@") {
nextSlashIndex = file.indexOf(path.sep, nextSlashIndex + 1);
}
if (!metadata.get(file).isFile()) {
continue;
}
const packageDir = file.substring(0, nextSlashIndex);
const packageDirPathInArchive = path.relative(rootForAppFilesWithoutAsar, (0, _appFileCopier().getDestinationPath)(packageDir, fileSet));
const pathInArchive = path.relative(rootForAppFilesWithoutAsar, (0, _appFileCopier().getDestinationPath)(file, fileSet));
if (autoUnpackDirs.has(packageDirPathInArchive)) {
// if package dir is unpacked, any file also unpacked
addParents(pathInArchive, packageDirPathInArchive);
continue;
} // https://github.com/electron-userland/electron-builder/issues/2679
let shouldUnpack = false; // ffprobe-static and ffmpeg-static are known packages to always unpack
const moduleName = path.basename(packageDir);
if (moduleName === "ffprobe-static" || moduleName === "ffmpeg-static" || isLibOrExe(file)) {
shouldUnpack = true;
} else if (!file.includes(".", nextSlashIndex) && path.extname(file) === "") {
shouldUnpack = await (0, _isbinaryfile().isBinaryFile)(file);
}
if (!shouldUnpack) {
continue;
}
if (_builderUtil().log.isDebugEnabled) {
_builderUtil().log.debug({
file: pathInArchive,
reason: "contains executable code"
}, "not packed into asar archive");
}
addParents(pathInArchive, packageDirPathInArchive);
}
if (dirToCreate.size > 0) {
await (0, _fsExtra().ensureDir)(unpackedDest + path.sep + "node_modules"); // child directories should be not created asynchronously - parent directories should be created first
await _bluebirdLst().default.map(dirToCreate.keys(), async parentDir => {
const base = unpackedDest + path.sep + parentDir;
await (0, _fsExtra().ensureDir)(base);
await _bluebirdLst().default.each(dirToCreate.get(parentDir), it => {
if (dirToCreate.has(parentDir + path.sep + it)) {
// already created
return null;
} else {
return (0, _fsExtra().ensureDir)(base + path.sep + it);
}
});
}, _fs().CONCURRENCY);
}
}
// __ts-babel@6.0.4
//# sourceMappingURL=unpackDetector.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,3 @@
export declare function download(url: string, output: string, checksum?: string | null): Promise<void>;
export declare function getBinFromUrl(name: string, version: string, checksum: string): Promise<string>;
export declare function getBin(name: string, url?: string | null, checksum?: string | null): Promise<string>;

View File

@ -0,0 +1,76 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.download = download;
exports.getBinFromUrl = getBinFromUrl;
exports.getBin = getBin;
function _builderUtil() {
const data = require("builder-util");
_builderUtil = function () {
return data;
};
return data;
}
const versionToPromise = new Map();
function download(url, output, checksum) {
const args = ["download", "--url", url, "--output", output];
if (checksum != null) {
args.push("--sha512", checksum);
}
return (0, _builderUtil().executeAppBuilder)(args);
}
function getBinFromUrl(name, version, checksum) {
const dirName = `${name}-${version}`;
let url;
if (process.env.ELECTRON_BUILDER_BINARIES_DOWNLOAD_OVERRIDE_URL) {
url = process.env.ELECTRON_BUILDER_BINARIES_DOWNLOAD_OVERRIDE_URL + "/" + dirName + ".7z";
} else {
const baseUrl = process.env.NPM_CONFIG_ELECTRON_BUILDER_BINARIES_MIRROR || process.env.npm_config_electron_builder_binaries_mirror || process.env.npm_package_config_electron_builder_binaries_mirror || process.env.ELECTRON_BUILDER_BINARIES_MIRROR || "https://github.com/electron-userland/electron-builder-binaries/releases/download/";
const middleUrl = process.env.NPM_CONFIG_ELECTRON_BUILDER_BINARIES_CUSTOM_DIR || process.env.npm_config_electron_builder_binaries_custom_dir || process.env.npm_package_config_electron_builder_binaries_custom_dir || process.env.ELECTRON_BUILDER_BINARIES_CUSTOM_DIR || dirName;
const urlSuffix = dirName + ".7z";
url = `${baseUrl}${middleUrl}/${urlSuffix}`;
}
return getBin(dirName, url, checksum);
}
function getBin(name, url, checksum) {
// Old cache is ignored if cache environment variable changes
const cacheName = process.env.ELECTRON_BUILDER_CACHE + name;
let promise = versionToPromise.get(cacheName); // if rejected, we will try to download again
if (promise != null) {
return promise;
}
promise = doGetBin(name, url, checksum);
versionToPromise.set(cacheName, promise);
return promise;
}
function doGetBin(name, url, checksum) {
const args = ["download-artifact", "--name", name];
if (url != null) {
args.push("--url", url);
}
if (checksum != null) {
args.push("--sha512", checksum);
}
return (0, _builderUtil().executeAppBuilder)(args);
}
// __ts-babel@6.0.4
//# sourceMappingURL=binDownload.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../src/binDownload.ts"],"names":[],"mappings":";;;;;;;;;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAEA,MAAM,gBAAgB,GAAG,IAAI,GAAJ,EAAzB;;AAEM,SAAU,QAAV,CAAmB,GAAnB,EAAgC,MAAhC,EAAgD,QAAhD,EAAwE;AAC5E,QAAM,IAAI,GAAG,CAAC,UAAD,EAAa,OAAb,EAAsB,GAAtB,EAA2B,UAA3B,EAAuC,MAAvC,CAAb;;AACA,MAAI,QAAQ,IAAI,IAAhB,EAAsB;AACpB,IAAA,IAAI,CAAC,IAAL,CAAU,UAAV,EAAsB,QAAtB;AACD;;AACD,SAAO,sCAAkB,IAAlB,CAAP;AACD;;AAEK,SAAU,aAAV,CAAwB,IAAxB,EAAsC,OAAtC,EAAuD,QAAvD,EAAuE;AAC3E,QAAM,OAAO,GAAG,GAAG,IAAI,IAAI,OAAO,EAAlC;AACA,MAAI,GAAJ;;AACA,MAAI,OAAO,CAAC,GAAR,CAAY,+CAAhB,EAAiE;AAC/D,IAAA,GAAG,GAAG,OAAO,CAAC,GAAR,CAAY,+CAAZ,GAA8D,GAA9D,GAAoE,OAApE,GAA8E,KAApF;AACD,GAFD,MAGK;AAEH,UAAM,OAAO,GAAG,OAAO,CAAC,GAAR,CAAY,2CAAZ,IACd,OAAO,CAAC,GAAR,CAAY,2CADE,IAEd,OAAO,CAAC,GAAR,CAAY,mDAFE,IAGd,OAAO,CAAC,GAAR,CAAY,gCAHE,IAId,mFAJF;AAKA,UAAM,SAAS,GAAG,OAAO,CAAC,GAAR,CAAY,+CAAZ,IAChB,OAAO,CAAC,GAAR,CAAY,+CADI,IAEhB,OAAO,CAAC,GAAR,CAAY,uDAFI,IAGhB,OAAO,CAAC,GAAR,CAAY,oCAHI,IAIhB,OAJF;AAKA,UAAM,SAAS,GAAG,OAAO,GAAG,KAA5B;AACA,IAAA,GAAG,GAAG,GAAG,OAAO,GAAG,SAAS,IAAI,SAAS,EAAzC;AACD;;AAED,SAAO,MAAM,CAAC,OAAD,EAAU,GAAV,EAAe,QAAf,CAAb;AACD;;AAEK,SAAU,MAAV,CAAiB,IAAjB,EAA+B,GAA/B,EAAoD,QAApD,EAA4E;AAChF;AACA,QAAM,SAAS,GAAG,OAAO,CAAC,GAAR,CAAY,sBAAZ,GAAqC,IAAvD;AACA,MAAI,OAAO,GAAG,gBAAgB,CAAC,GAAjB,CAAqB,SAArB,CAAd,CAHgF,CAGlC;;AAE9C,MAAI,OAAO,IAAI,IAAf,EAAqB;AACnB,WAAO,OAAP;AACD;;AAED,EAAA,OAAO,GAAG,QAAQ,CAAC,IAAD,EAAO,GAAP,EAAY,QAAZ,CAAlB;AACA,EAAA,gBAAgB,CAAC,GAAjB,CAAqB,SAArB,EAAgC,OAAhC;AACA,SAAO,OAAP;AACD;;AAED,SAAS,QAAT,CAAkB,IAAlB,EAAgC,GAAhC,EAAgE,QAAhE,EAAmG;AACjG,QAAM,IAAI,GAAG,CAAC,mBAAD,EAAsB,QAAtB,EAAgC,IAAhC,CAAb;;AACA,MAAI,GAAG,IAAI,IAAX,EAAiB;AACf,IAAA,IAAI,CAAC,IAAL,CAAU,OAAV,EAAmB,GAAnB;AACD;;AACD,MAAI,QAAQ,IAAI,IAAhB,EAAsB;AACpB,IAAA,IAAI,CAAC,IAAL,CAAU,UAAV,EAAsB,QAAtB;AACD;;AACD,SAAO,sCAAkB,IAAlB,CAAP;AACD,C","sourcesContent":["import { executeAppBuilder } from \"builder-util\"\n\nconst versionToPromise = new Map<string, Promise<string>>()\n\nexport function download(url: string, output: string, checksum?: string | null): Promise<void> {\n const args = [\"download\", \"--url\", url, \"--output\", output]\n if (checksum != null) {\n args.push(\"--sha512\", checksum)\n }\n return executeAppBuilder(args) as Promise<any>\n}\n\nexport function getBinFromUrl(name: string, version: string, checksum: string): Promise<string> {\n const dirName = `${name}-${version}`\n let url: string\n if (process.env.ELECTRON_BUILDER_BINARIES_DOWNLOAD_OVERRIDE_URL) {\n url = process.env.ELECTRON_BUILDER_BINARIES_DOWNLOAD_OVERRIDE_URL + \"/\" + dirName + \".7z\"\n }\n else {\n\n const baseUrl = process.env.NPM_CONFIG_ELECTRON_BUILDER_BINARIES_MIRROR ||\n process.env.npm_config_electron_builder_binaries_mirror ||\n process.env.npm_package_config_electron_builder_binaries_mirror ||\n process.env.ELECTRON_BUILDER_BINARIES_MIRROR ||\n \"https://github.com/electron-userland/electron-builder-binaries/releases/download/\"\n const middleUrl = process.env.NPM_CONFIG_ELECTRON_BUILDER_BINARIES_CUSTOM_DIR ||\n process.env.npm_config_electron_builder_binaries_custom_dir ||\n process.env.npm_package_config_electron_builder_binaries_custom_dir ||\n process.env.ELECTRON_BUILDER_BINARIES_CUSTOM_DIR ||\n dirName\n const urlSuffix = dirName + \".7z\"\n url = `${baseUrl}${middleUrl}/${urlSuffix}`\n }\n\n return getBin(dirName, url, checksum)\n}\n\nexport function getBin(name: string, url?: string | null, checksum?: string | null): Promise<string> {\n // Old cache is ignored if cache environment variable changes\n const cacheName = process.env.ELECTRON_BUILDER_CACHE + name;\n let promise = versionToPromise.get(cacheName);// if rejected, we will try to download again\n\n if (promise != null) {\n return promise\n }\n\n promise = doGetBin(name, url, checksum)\n versionToPromise.set(cacheName, promise)\n return promise\n}\n\nfunction doGetBin(name: string, url: string | undefined | null, checksum: string | null | undefined): Promise<string> {\n const args = [\"download-artifact\", \"--name\", name]\n if (url != null) {\n args.push(\"--url\", url)\n }\n if (checksum != null) {\n args.push(\"--sha512\", checksum)\n }\n return executeAppBuilder(args)\n}"],"sourceRoot":""}

View File

@ -0,0 +1,3 @@
import { TmpDir } from "temp-file";
/** @private */
export declare function downloadCertificate(urlOrBase64: string, tmpDir: TmpDir, currentDir: string): Promise<string>;

View File

@ -0,0 +1,107 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.downloadCertificate = downloadCertificate;
function _fsExtra() {
const data = require("fs-extra");
_fsExtra = function () {
return data;
};
return data;
}
function _os() {
const data = require("os");
_os = function () {
return data;
};
return data;
}
var path = _interopRequireWildcard(require("path"));
function _builderUtil() {
const data = require("builder-util");
_builderUtil = function () {
return data;
};
return data;
}
function _fs() {
const data = require("builder-util/out/fs");
_fs = function () {
return data;
};
return data;
}
function _binDownload() {
const data = require("../binDownload");
_binDownload = function () {
return data;
};
return data;
}
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
/** @private */
async function downloadCertificate(urlOrBase64, tmpDir, currentDir) {
urlOrBase64 = urlOrBase64.trim();
let file = null;
if (urlOrBase64.length > 3 && urlOrBase64[1] === ":" || urlOrBase64.startsWith("/") || urlOrBase64.startsWith(".")) {
file = urlOrBase64;
} else if (urlOrBase64.startsWith("file://")) {
file = urlOrBase64.substring("file://".length);
} else if (urlOrBase64.startsWith("~/")) {
file = path.join((0, _os().homedir)(), urlOrBase64.substring("~/".length));
} else {
const isUrl = urlOrBase64.startsWith("https://");
if (isUrl || urlOrBase64.length > 2048 || urlOrBase64.endsWith("=")) {
const tempFile = await tmpDir.getTempFile({
suffix: ".p12"
});
if (isUrl) {
await (0, _binDownload().download)(urlOrBase64, tempFile);
} else {
await (0, _fsExtra().outputFile)(tempFile, Buffer.from(urlOrBase64, "base64"));
}
return tempFile;
} else {
file = urlOrBase64;
}
}
file = path.resolve(currentDir, file);
const stat = await (0, _fs().statOrNull)(file);
if (stat == null) {
throw new (_builderUtil().InvalidConfigurationError)(`${file} doesn't exist`);
} else if (!stat.isFile()) {
throw new (_builderUtil().InvalidConfigurationError)(`${file} not a file`);
} else {
return file;
}
}
// __ts-babel@6.0.4
//# sourceMappingURL=codesign.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../src/codeSign/codesign.ts"],"names":[],"mappings":";;;;;;;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;;AAEA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;;;;;AAEA;AACO,eAAe,mBAAf,CAAmC,WAAnC,EAAwD,MAAxD,EAAwE,UAAxE,EAA0F;AAC/F,EAAA,WAAW,GAAG,WAAW,CAAC,IAAZ,EAAd;AAEA,MAAI,IAAI,GAAkB,IAA1B;;AACA,MAAK,WAAW,CAAC,MAAZ,GAAqB,CAArB,IAA0B,WAAW,CAAC,CAAD,CAAX,KAAmB,GAA9C,IAAsD,WAAW,CAAC,UAAZ,CAAuB,GAAvB,CAAtD,IAAqF,WAAW,CAAC,UAAZ,CAAuB,GAAvB,CAAzF,EAAsH;AACpH,IAAA,IAAI,GAAG,WAAP;AACD,GAFD,MAGK,IAAI,WAAW,CAAC,UAAZ,CAAuB,SAAvB,CAAJ,EAAuC;AAC1C,IAAA,IAAI,GAAG,WAAW,CAAC,SAAZ,CAAsB,UAAU,MAAhC,CAAP;AACD,GAFI,MAGA,IAAI,WAAW,CAAC,UAAZ,CAAuB,IAAvB,CAAJ,EAAkC;AACrC,IAAA,IAAI,GAAG,IAAI,CAAC,IAAL,CAAU,oBAAV,EAAqB,WAAW,CAAC,SAAZ,CAAsB,KAAK,MAA3B,CAArB,CAAP;AACD,GAFI,MAGA;AACH,UAAM,KAAK,GAAG,WAAW,CAAC,UAAZ,CAAuB,UAAvB,CAAd;;AACA,QAAI,KAAK,IAAI,WAAW,CAAC,MAAZ,GAAqB,IAA9B,IAAsC,WAAW,CAAC,QAAZ,CAAqB,GAArB,CAA1C,EAAqE;AACnE,YAAM,QAAQ,GAAG,MAAM,MAAM,CAAC,WAAP,CAAmB;AAAC,QAAA,MAAM,EAAE;AAAT,OAAnB,CAAvB;;AACA,UAAI,KAAJ,EAAW;AACT,cAAM,6BAAS,WAAT,EAAsB,QAAtB,CAAN;AACD,OAFD,MAGK;AACH,cAAM,2BAAW,QAAX,EAAqB,MAAM,CAAC,IAAP,CAAY,WAAZ,EAAyB,QAAzB,CAArB,CAAN;AACD;;AACD,aAAO,QAAP;AACD,KATD,MAUK;AACH,MAAA,IAAI,GAAG,WAAP;AACD;AACF;;AAED,EAAA,IAAI,GAAG,IAAI,CAAC,OAAL,CAAa,UAAb,EAAyB,IAAzB,CAAP;AACA,QAAM,IAAI,GAAG,MAAM,sBAAW,IAAX,CAAnB;;AACA,MAAI,IAAI,IAAI,IAAZ,EAAkB;AAChB,UAAM,KAAI,wCAAJ,EAA8B,GAAG,IAAI,gBAArC,CAAN;AACD,GAFD,MAGK,IAAI,CAAC,IAAI,CAAC,MAAL,EAAL,EAAoB;AACvB,UAAM,KAAI,wCAAJ,EAA8B,GAAG,IAAI,aAArC,CAAN;AACD,GAFI,MAGA;AACH,WAAO,IAAP;AACD;AACF,C","sourcesContent":["import { outputFile } from \"fs-extra\"\nimport { homedir } from \"os\"\nimport * as path from \"path\"\nimport { TmpDir } from \"temp-file\"\nimport { InvalidConfigurationError } from \"builder-util\"\nimport { statOrNull } from \"builder-util/out/fs\"\nimport { download } from \"../binDownload\"\n\n/** @private */\nexport async function downloadCertificate(urlOrBase64: string, tmpDir: TmpDir, currentDir: string): Promise<string> {\n urlOrBase64 = urlOrBase64.trim()\n\n let file: string | null = null\n if ((urlOrBase64.length > 3 && urlOrBase64[1] === \":\") || urlOrBase64.startsWith(\"/\") || urlOrBase64.startsWith(\".\")) {\n file = urlOrBase64\n }\n else if (urlOrBase64.startsWith(\"file://\")) {\n file = urlOrBase64.substring(\"file://\".length)\n }\n else if (urlOrBase64.startsWith(\"~/\")) {\n file = path.join(homedir(), urlOrBase64.substring(\"~/\".length))\n }\n else {\n const isUrl = urlOrBase64.startsWith(\"https://\")\n if (isUrl || urlOrBase64.length > 2048 || urlOrBase64.endsWith(\"=\")) {\n const tempFile = await tmpDir.getTempFile({suffix: \".p12\"})\n if (isUrl) {\n await download(urlOrBase64, tempFile)\n }\n else {\n await outputFile(tempFile, Buffer.from(urlOrBase64, \"base64\"))\n }\n return tempFile\n }\n else {\n file = urlOrBase64\n }\n }\n\n file = path.resolve(currentDir, file)\n const stat = await statOrNull(file)\n if (stat == null) {\n throw new InvalidConfigurationError(`${file} doesn't exist`)\n }\n else if (!stat.isFile()) {\n throw new InvalidConfigurationError(`${file} not a file`)\n }\n else {\n return file\n }\n}"],"sourceRoot":""}

View File

@ -0,0 +1,27 @@
import { TmpDir } from "builder-util/out/util";
export declare const appleCertificatePrefixes: string[];
export declare type CertType = "Developer ID Application" | "Developer ID Installer" | "3rd Party Mac Developer Application" | "3rd Party Mac Developer Installer" | "Mac Developer";
export interface CodeSigningInfo {
keychainFile?: string | null;
}
export declare function isSignAllowed(isPrintWarn?: boolean): boolean;
export declare function reportError(isMas: boolean, certificateType: CertType, qualifier: string | null | undefined, keychainFile: string | null | undefined, isForceCodeSigning: boolean): Promise<void>;
export interface CreateKeychainOptions {
tmpDir: TmpDir;
cscLink: string;
cscKeyPassword: string;
cscILink?: string | null;
cscIKeyPassword?: string | null;
currentDir: string;
}
export declare function removeKeychain(keychainFile: string, printWarn?: boolean): Promise<any>;
export declare function createKeychain({ tmpDir, cscLink, cscKeyPassword, cscILink, cscIKeyPassword, currentDir }: CreateKeychainOptions): Promise<CodeSigningInfo>;
/** @private */
export declare function sign(path: string, name: string, keychain: string): Promise<any>;
export declare let findIdentityRawResult: Promise<Array<string>> | null;
export declare class Identity {
readonly name: string;
readonly hash: string;
constructor(name: string, hash: string);
}
export declare function findIdentity(certType: CertType, qualifier?: string | null, keychain?: string | null): Promise<Identity | null>;

View File

@ -0,0 +1,427 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.isSignAllowed = isSignAllowed;
exports.reportError = reportError;
exports.removeKeychain = removeKeychain;
exports.createKeychain = createKeychain;
exports.sign = sign;
exports.findIdentity = findIdentity;
exports.findIdentityRawResult = exports.appleCertificatePrefixes = void 0;
function _bluebirdLst() {
const data = _interopRequireDefault(require("bluebird-lst"));
_bluebirdLst = function () {
return data;
};
return data;
}
function _util() {
const data = require("builder-util/out/util");
_util = function () {
return data;
};
return data;
}
function _fs() {
const data = require("builder-util/out/fs");
_fs = function () {
return data;
};
return data;
}
function _log() {
const data = require("builder-util/out/log");
_log = function () {
return data;
};
return data;
}
function _crypto() {
const data = require("crypto");
_crypto = function () {
return data;
};
return data;
}
function _fsExtra() {
const data = require("fs-extra");
_fsExtra = function () {
return data;
};
return data;
}
function _lazyVal() {
const data = require("lazy-val");
_lazyVal = function () {
return data;
};
return data;
}
function _os() {
const data = require("os");
_os = function () {
return data;
};
return data;
}
var path = _interopRequireWildcard(require("path"));
function _tempFile() {
const data = require("temp-file");
_tempFile = function () {
return data;
};
return data;
}
function _flags() {
const data = require("../util/flags");
_flags = function () {
return data;
};
return data;
}
function _codesign() {
const data = require("./codesign");
_codesign = function () {
return data;
};
return data;
}
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const appleCertificatePrefixes = ["Developer ID Application:", "Developer ID Installer:", "3rd Party Mac Developer Application:", "3rd Party Mac Developer Installer:"];
exports.appleCertificatePrefixes = appleCertificatePrefixes;
function isSignAllowed(isPrintWarn = true) {
if (process.platform !== "darwin") {
if (isPrintWarn) {
_util().log.warn({
reason: "supported only on macOS"
}, "skipped macOS application code signing");
}
return false;
}
const buildForPrWarning = "There are serious security concerns with CSC_FOR_PULL_REQUEST=true (see the CircleCI documentation (https://circleci.com/docs/1.0/fork-pr-builds/) for details)" + "\nIf you have SSH keys, sensitive env vars or AWS credentials stored in your project settings and untrusted forks can make pull requests against your repo, then this option isn't for you.";
if ((0, _util().isPullRequest)()) {
if ((0, _util().isEnvTrue)(process.env.CSC_FOR_PULL_REQUEST)) {
if (isPrintWarn) {
_util().log.warn(buildForPrWarning);
}
} else {
if (isPrintWarn) {
// https://github.com/electron-userland/electron-builder/issues/1524
_util().log.warn("Current build is a part of pull request, code signing will be skipped." + "\nSet env CSC_FOR_PULL_REQUEST to true to force code signing." + `\n${buildForPrWarning}`);
}
return false;
}
}
return true;
}
async function reportError(isMas, certificateType, qualifier, keychainFile, isForceCodeSigning) {
const logFields = {};
if (qualifier == null) {
logFields.reason = "";
if ((0, _flags().isAutoDiscoveryCodeSignIdentity)()) {
logFields.reason += `cannot find valid "${certificateType}" identity${isMas ? "" : ` or custom non-Apple code signing certificate`}`;
}
logFields.reason += ", see https://electron.build/code-signing";
if (!(0, _flags().isAutoDiscoveryCodeSignIdentity)()) {
logFields.CSC_IDENTITY_AUTO_DISCOVERY = false;
}
} else {
logFields.reason = "Identity name is specified, but no valid identity with this name in the keychain";
logFields.identity = qualifier;
}
const args = ["find-identity"];
if (keychainFile != null) {
args.push(keychainFile);
}
if (qualifier != null || (0, _flags().isAutoDiscoveryCodeSignIdentity)()) {
logFields.allIdentities = (await (0, _util().exec)("security", args)).trim().split("\n").filter(it => !(it.includes("Policy: X.509 Basic") || it.includes("Matching identities"))).join("\n");
}
if (isMas || isForceCodeSigning) {
throw new Error(_log().Logger.createMessage("skipped macOS application code signing", logFields, "error", it => it));
} else {
_util().log.warn(logFields, "skipped macOS application code signing");
}
} // "Note that filename will not be searched to resolve the signing identity's certificate chain unless it is also on the user's keychain search list."
// but "security list-keychains" doesn't support add - we should 1) get current list 2) set new list - it is very bad http://stackoverflow.com/questions/10538942/add-a-keychain-to-search-list
// "overly complicated and introduces a race condition."
// https://github.com/electron-userland/electron-builder/issues/398
const bundledCertKeychainAdded = new (_lazyVal().Lazy)(async () => {
// copy to temp and then atomic rename to final path
const cacheDir = getCacheDirectory();
const tmpKeychainPath = path.join(cacheDir, (0, _tempFile().getTempName)("electron-builder-root-certs"));
const keychainPath = path.join(cacheDir, "electron-builder-root-certs.keychain");
const results = await Promise.all([listUserKeychains(), (0, _fs().copyFile)(path.join(__dirname, "..", "..", "certs", "root_certs.keychain"), tmpKeychainPath).then(() => (0, _fsExtra().rename)(tmpKeychainPath, keychainPath))]);
const list = results[0];
if (!list.includes(keychainPath)) {
await (0, _util().exec)("security", ["list-keychains", "-d", "user", "-s", keychainPath].concat(list));
}
});
function getCacheDirectory() {
const env = process.env.ELECTRON_BUILDER_CACHE;
return (0, _util().isEmptyOrSpaces)(env) ? path.join((0, _os().homedir)(), "Library", "Caches", "electron-builder") : path.resolve(env);
}
function listUserKeychains() {
return (0, _util().exec)("security", ["list-keychains", "-d", "user"]).then(it => it.split("\n").map(it => {
const r = it.trim();
return r.substring(1, r.length - 1);
}).filter(it => it.length > 0));
}
function removeKeychain(keychainFile, printWarn = true) {
return (0, _util().exec)("security", ["delete-keychain", keychainFile]).catch(e => {
if (printWarn) {
_util().log.warn({
file: keychainFile,
error: e.stack || e
}, "cannot delete keychain");
}
return (0, _fs().unlinkIfExists)(keychainFile);
});
}
async function createKeychain({
tmpDir,
cscLink,
cscKeyPassword,
cscILink,
cscIKeyPassword,
currentDir
}) {
// travis has correct AppleWWDRCA cert
if (process.env.TRAVIS !== "true") {
await bundledCertKeychainAdded.value;
} // https://github.com/electron-userland/electron-builder/issues/3685
// use constant file
const keychainFile = path.join(process.env.APP_BUILDER_TMP_DIR || (0, _os().tmpdir)(), `${(0, _crypto().createHash)("sha256").update(currentDir).update("app-builder").digest("hex")}.keychain`); // noinspection JSUnusedLocalSymbols
// eslint-disable-next-line @typescript-eslint/no-unused-vars
await removeKeychain(keychainFile, false).catch(_ => {});
const certLinks = [cscLink];
if (cscILink != null) {
certLinks.push(cscILink);
}
const certPaths = new Array(certLinks.length);
const keychainPassword = (0, _crypto().randomBytes)(32).toString("base64");
const securityCommands = [["create-keychain", "-p", keychainPassword, keychainFile], ["unlock-keychain", "-p", keychainPassword, keychainFile], ["set-keychain-settings", keychainFile]]; // https://stackoverflow.com/questions/42484678/codesign-keychain-gets-ignored
// https://github.com/electron-userland/electron-builder/issues/1457
const list = await listUserKeychains();
if (!list.includes(keychainFile)) {
securityCommands.push(["list-keychains", "-d", "user", "-s", keychainFile].concat(list));
}
await Promise.all([// we do not clear downloaded files - will be removed on tmpDir cleanup automatically. not a security issue since in any case data is available as env variables and protected by password.
_bluebirdLst().default.map(certLinks, (link, i) => (0, _codesign().downloadCertificate)(link, tmpDir, currentDir).then(it => certPaths[i] = it)), _bluebirdLst().default.mapSeries(securityCommands, it => (0, _util().exec)("security", it))]);
return await importCerts(keychainFile, certPaths, [cscKeyPassword, cscIKeyPassword].filter(it => it != null));
}
async function importCerts(keychainFile, paths, keyPasswords) {
for (let i = 0; i < paths.length; i++) {
const password = keyPasswords[i];
await (0, _util().exec)("security", ["import", paths[i], "-k", keychainFile, "-T", "/usr/bin/codesign", "-T", "/usr/bin/productbuild", "-P", password]); // https://stackoverflow.com/questions/39868578/security-codesign-in-sierra-keychain-ignores-access-control-settings-and-ui-p
// https://github.com/electron-userland/electron-packager/issues/701#issuecomment-322315996
await (0, _util().exec)("security", ["set-key-partition-list", "-S", "apple-tool:,apple:", "-s", "-k", password, keychainFile]);
}
return {
keychainFile
};
}
/** @private */
function sign(path, name, keychain) {
const args = ["--deep", "--force", "--sign", name, path];
if (keychain != null) {
args.push("--keychain", keychain);
}
return (0, _util().exec)("codesign", args);
}
let findIdentityRawResult = null;
exports.findIdentityRawResult = findIdentityRawResult;
async function getValidIdentities(keychain) {
function addKeychain(args) {
if (keychain != null) {
args.push(keychain);
}
return args;
}
let result = findIdentityRawResult;
if (result == null || keychain != null) {
// https://github.com/electron-userland/electron-builder/issues/481
// https://github.com/electron-userland/electron-builder/issues/535
result = Promise.all([(0, _util().exec)("security", addKeychain(["find-identity", "-v"])).then(it => it.trim().split("\n").filter(it => {
for (const prefix of appleCertificatePrefixes) {
if (it.includes(prefix)) {
return true;
}
}
return false;
})), (0, _util().exec)("security", addKeychain(["find-identity", "-v", "-p", "codesigning"])).then(it => it.trim().split("\n"))]).then(it => {
const array = it[0].concat(it[1]).filter(it => !it.includes("(Missing required extension)") && !it.includes("valid identities found") && !it.includes("iPhone ") && !it.includes("com.apple.idms.appleid.prd.")) // remove 1)
.map(it => it.substring(it.indexOf(")") + 1).trim());
return Array.from(new Set(array));
});
if (keychain == null) {
exports.findIdentityRawResult = findIdentityRawResult = result;
}
}
return result;
}
async function _findIdentity(type, qualifier, keychain) {
// https://github.com/electron-userland/electron-builder/issues/484
//noinspection SpellCheckingInspection
const lines = await getValidIdentities(keychain);
const namePrefix = `${type}:`;
for (const line of lines) {
if (qualifier != null && !line.includes(qualifier)) {
continue;
}
if (line.includes(namePrefix)) {
return parseIdentity(line);
}
}
if (type === "Developer ID Application") {
// find non-Apple certificate
// https://github.com/electron-userland/electron-builder/issues/458
l: for (const line of lines) {
if (qualifier != null && !line.includes(qualifier)) {
continue;
}
if (line.includes("Mac Developer:")) {
continue;
}
for (const prefix of appleCertificatePrefixes) {
if (line.includes(prefix)) {
continue l;
}
}
return parseIdentity(line);
}
}
return null;
}
const _Identity = require("../../electron-osx-sign/util-identities").Identity;
function parseIdentity(line) {
const firstQuoteIndex = line.indexOf('"');
const name = line.substring(firstQuoteIndex + 1, line.lastIndexOf('"'));
const hash = line.substring(0, firstQuoteIndex - 1);
return new _Identity(name, hash);
}
function findIdentity(certType, qualifier, keychain) {
let identity = qualifier || process.env.CSC_NAME;
if ((0, _util().isEmptyOrSpaces)(identity)) {
if ((0, _flags().isAutoDiscoveryCodeSignIdentity)()) {
return _findIdentity(certType, null, keychain);
} else {
return Promise.resolve(null);
}
} else {
identity = identity.trim();
for (const prefix of appleCertificatePrefixes) {
checkPrefix(identity, prefix);
}
return _findIdentity(certType, identity, keychain);
}
}
function checkPrefix(name, prefix) {
if (name.startsWith(prefix)) {
throw new (_util().InvalidConfigurationError)(`Please remove prefix "${prefix}" from the specified name — appropriate certificate will be chosen automatically`);
}
}
// __ts-babel@6.0.4
//# sourceMappingURL=macCodeSign.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,38 @@
import { WindowsConfiguration } from "..";
import { VmManager } from "../vm/vm";
import { WinPackager } from "../winPackager";
export declare function getSignVendorPath(): Promise<string>;
export declare type CustomWindowsSign = (configuration: CustomWindowsSignTaskConfiguration, packager?: WinPackager) => Promise<any>;
export interface WindowsSignOptions {
readonly path: string;
readonly name?: string | null;
readonly cscInfo?: FileCodeSigningInfo | CertificateFromStoreInfo | null;
readonly site?: string | null;
readonly options: WindowsConfiguration;
}
export interface WindowsSignTaskConfiguration extends WindowsSignOptions {
resultOutputPath?: string;
hash: string;
isNest: boolean;
}
export interface CustomWindowsSignTaskConfiguration extends WindowsSignTaskConfiguration {
computeSignToolArgs(isWin: boolean): Array<string>;
}
export declare function sign(options: WindowsSignOptions, packager: WinPackager): Promise<void>;
export interface FileCodeSigningInfo {
readonly file: string;
readonly password: string | null;
}
export declare function getCertInfo(file: string, password: string): Promise<CertificateInfo>;
export interface CertificateInfo {
readonly commonName: string;
readonly bloodyMicrosoftSubjectDn: string;
}
export interface CertificateFromStoreInfo {
thumbprint: string;
subject: string;
store: string;
isLocalMachineStore: boolean;
}
export declare function getCertificateFromStoreInfo(options: WindowsConfiguration, vm: VmManager): Promise<CertificateFromStoreInfo>;
export declare function doSign(configuration: CustomWindowsSignTaskConfiguration, packager: WinPackager): Promise<void>;

View File

@ -0,0 +1,398 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getSignVendorPath = getSignVendorPath;
exports.sign = sign;
exports.getCertInfo = getCertInfo;
exports.getCertificateFromStoreInfo = getCertificateFromStoreInfo;
exports.doSign = doSign;
exports.isOldWin6 = isOldWin6;
function _util() {
const data = require("builder-util/out/util");
_util = function () {
return data;
};
return data;
}
function _binDownload() {
const data = require("../binDownload");
_binDownload = function () {
return data;
};
return data;
}
function _appBuilder() {
const data = require("../util/appBuilder");
_appBuilder = function () {
return data;
};
return data;
}
function _bundledTool() {
const data = require("../util/bundledTool");
_bundledTool = function () {
return data;
};
return data;
}
function _fsExtra() {
const data = require("fs-extra");
_fsExtra = function () {
return data;
};
return data;
}
function os() {
const data = _interopRequireWildcard(require("os"));
os = function () {
return data;
};
return data;
}
var path = _interopRequireWildcard(require("path"));
function _platformPackager() {
const data = require("../platformPackager");
_platformPackager = function () {
return data;
};
return data;
}
function _flags() {
const data = require("../util/flags");
_flags = function () {
return data;
};
return data;
}
function _vm() {
const data = require("../vm/vm");
_vm = function () {
return data;
};
return data;
}
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function getSignVendorPath() {
return (0, _binDownload().getBin)("winCodeSign");
}
async function sign(options, packager) {
let hashes = options.options.signingHashAlgorithms; // msi does not support dual-signing
if (options.path.endsWith(".msi")) {
hashes = [hashes != null && !hashes.includes("sha1") ? "sha256" : "sha1"];
} else if (options.path.endsWith(".appx")) {
hashes = ["sha256"];
} else if (hashes == null) {
hashes = ["sha1", "sha256"];
} else {
hashes = Array.isArray(hashes) ? hashes : [hashes];
}
const executor = (0, _platformPackager().resolveFunction)(options.options.sign, "sign") || doSign;
let isNest = false;
for (const hash of hashes) {
const taskConfiguration = { ...options,
hash,
isNest
};
await executor({ ...taskConfiguration,
computeSignToolArgs: isWin => computeSignToolArgs(taskConfiguration, isWin)
}, packager);
isNest = true;
if (taskConfiguration.resultOutputPath != null) {
await (0, _fsExtra().rename)(taskConfiguration.resultOutputPath, options.path);
}
}
}
async function getCertInfo(file, password) {
let result = null;
const errorMessagePrefix = "Cannot extract publisher name from code signing certificate. As workaround, set win.publisherName. Error: ";
try {
result = await (0, _appBuilder().executeAppBuilderAsJson)(["certificate-info", "--input", file, "--password", password]);
} catch (e) {
throw new Error(`${errorMessagePrefix}${e.stack || e}`);
}
if (result.error != null) {
// noinspection ExceptionCaughtLocallyJS
throw new (_util().InvalidConfigurationError)(`${errorMessagePrefix}${result.error}`);
}
return result;
}
async function getCertificateFromStoreInfo(options, vm) {
const certificateSubjectName = options.certificateSubjectName;
const certificateSha1 = options.certificateSha1 ? options.certificateSha1.toUpperCase() : options.certificateSha1; // ExcludeProperty doesn't work, so, we cannot exclude RawData, it is ok
// powershell can return object if the only item
const rawResult = await vm.exec("powershell.exe", ["Get-ChildItem -Recurse Cert: -CodeSigningCert | Select-Object -Property Subject,PSParentPath,Thumbprint | ConvertTo-Json -Compress"]);
const certList = rawResult.length === 0 ? [] : (0, _util().asArray)(JSON.parse(rawResult));
for (const certInfo of certList) {
if (certificateSubjectName != null && !certInfo.Subject.includes(certificateSubjectName) || certificateSha1 != null && certInfo.Thumbprint.toUpperCase() !== certificateSha1) {
continue;
}
const parentPath = certInfo.PSParentPath;
const store = parentPath.substring(parentPath.lastIndexOf("\\") + 1);
_util().log.debug({
store,
PSParentPath: parentPath
}, "auto-detect certificate store"); // https://github.com/electron-userland/electron-builder/issues/1717
const isLocalMachineStore = parentPath.includes("Certificate::LocalMachine");
_util().log.debug(null, "auto-detect using of LocalMachine store");
return {
thumbprint: certInfo.Thumbprint,
subject: certInfo.Subject,
store,
isLocalMachineStore
};
}
throw new Error(`Cannot find certificate ${certificateSubjectName || certificateSha1}, all certs: ${rawResult}`);
}
async function doSign(configuration, packager) {
// https://github.com/electron-userland/electron-builder/pull/1944
const timeout = parseInt(process.env.SIGNTOOL_TIMEOUT, 10) || 10 * 60 * 1000;
let tool;
let args;
let env = process.env;
let vm;
if (configuration.path.endsWith(".appx") || !("file" in configuration.cscInfo)
/* certificateSubjectName and other such options */
) {
vm = await packager.vm.value;
tool = getWinSignTool(await getSignVendorPath());
args = computeSignToolArgs(configuration, true, vm);
} else {
vm = new (_vm().VmManager)();
const toolInfo = await getToolPath();
tool = toolInfo.path;
args = configuration.computeSignToolArgs(process.platform === "win32");
if (toolInfo.env != null) {
env = toolInfo.env;
}
}
try {
await vm.exec(tool, args, {
timeout,
env
});
} catch (e) {
if (e.message.includes("The file is being used by another process") || e.message.includes("The specified timestamp server either could not be reached")) {
_util().log.warn(`First attempt to code sign failed, another attempt will be made in 15 seconds: ${e.message}`);
await new Promise((resolve, reject) => {
setTimeout(() => {
vm.exec(tool, args, {
timeout,
env
}).then(resolve).catch(reject);
}, 15000);
});
}
throw e;
}
} // on windows be aware of http://stackoverflow.com/a/32640183/1910191
function computeSignToolArgs(options, isWin, vm = new (_vm().VmManager)()) {
const inputFile = vm.toVmFile(options.path);
const outputPath = isWin ? inputFile : getOutputPath(inputFile, options.hash);
if (!isWin) {
options.resultOutputPath = outputPath;
}
const args = isWin ? ["sign"] : ["-in", inputFile, "-out", outputPath];
if (process.env.ELECTRON_BUILDER_OFFLINE !== "true") {
const timestampingServiceUrl = options.options.timeStampServer || "http://timestamp.digicert.com";
if (isWin) {
args.push(options.isNest || options.hash === "sha256" ? "/tr" : "/t", options.isNest || options.hash === "sha256" ? options.options.rfc3161TimeStampServer || "http://timestamp.digicert.com" : timestampingServiceUrl);
} else {
args.push("-t", timestampingServiceUrl);
}
}
const certificateFile = options.cscInfo.file;
if (certificateFile == null) {
const cscInfo = options.cscInfo;
const subjectName = cscInfo.thumbprint;
if (!isWin) {
throw new Error(`${subjectName == null ? "certificateSha1" : "certificateSubjectName"} supported only on Windows`);
}
args.push("/sha1", cscInfo.thumbprint);
args.push("/s", cscInfo.store);
if (cscInfo.isLocalMachineStore) {
args.push("/sm");
}
} else {
const certExtension = path.extname(certificateFile);
if (certExtension === ".p12" || certExtension === ".pfx") {
args.push(isWin ? "/f" : "-pkcs12", vm.toVmFile(certificateFile));
} else {
throw new Error(`Please specify pkcs12 (.p12/.pfx) file, ${certificateFile} is not correct`);
}
}
if (!isWin || options.hash !== "sha1") {
args.push(isWin ? "/fd" : "-h", options.hash);
if (isWin && process.env.ELECTRON_BUILDER_OFFLINE !== "true") {
args.push("/td", "sha256");
}
}
if (options.name) {
args.push(isWin ? "/d" : "-n", options.name);
}
if (options.site) {
args.push(isWin ? "/du" : "-i", options.site);
} // msi does not support dual-signing
if (options.isNest) {
args.push(isWin ? "/as" : "-nest");
}
const password = options.cscInfo == null ? null : options.cscInfo.password;
if (password) {
args.push(isWin ? "/p" : "-pass", password);
}
if (options.options.additionalCertificateFile) {
args.push(isWin ? "/ac" : "-ac", vm.toVmFile(options.options.additionalCertificateFile));
}
const httpsProxyFromEnv = process.env.HTTPS_PROXY;
if (!isWin && httpsProxyFromEnv != null && httpsProxyFromEnv.length) {
args.push("-p", httpsProxyFromEnv);
}
if (isWin) {
// https://github.com/electron-userland/electron-builder/issues/2875#issuecomment-387233610
args.push("/debug"); // must be last argument
args.push(inputFile);
}
return args;
}
function getOutputPath(inputPath, hash) {
const extension = path.extname(inputPath);
return path.join(path.dirname(inputPath), `${path.basename(inputPath, extension)}-signed-${hash}${extension}`);
}
/** @internal */
function isOldWin6() {
const winVersion = os().release();
return winVersion.startsWith("6.") && !winVersion.startsWith("6.3");
}
function getWinSignTool(vendorPath) {
// use modern signtool on Windows Server 2012 R2 to be able to sign AppX
if (isOldWin6()) {
return path.join(vendorPath, "windows-6", "signtool.exe");
} else {
return path.join(vendorPath, "windows-10", process.arch, "signtool.exe");
}
}
async function getToolPath() {
if ((0, _flags().isUseSystemSigncode)()) {
return {
path: "osslsigncode"
};
}
const result = process.env.SIGNTOOL_PATH;
if (result) {
return {
path: result
};
}
const vendorPath = await getSignVendorPath();
if (process.platform === "win32") {
// use modern signtool on Windows Server 2012 R2 to be able to sign AppX
return {
path: getWinSignTool(vendorPath)
};
} else if (process.platform === "darwin") {
const toolDirPath = path.join(vendorPath, process.platform, "10.12");
return {
path: path.join(toolDirPath, "osslsigncode"),
env: (0, _bundledTool().computeToolEnv)([path.join(toolDirPath, "lib")])
};
} else {
return {
path: path.join(vendorPath, process.platform, "osslsigncode")
};
}
}
// __ts-babel@6.0.4
//# sourceMappingURL=windowsCodeSign.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,235 @@
import { Arch } from "builder-util";
import { BeforeBuildContext, Target } from "./core";
import { ElectronDownloadOptions } from "./electron/ElectronFramework";
import { AppXOptions } from "./options/AppXOptions";
import { AppImageOptions, DebOptions, LinuxConfiguration, LinuxTargetSpecificOptions } from "./options/linuxOptions";
import { DmgOptions, MacConfiguration, MasConfiguration } from "./options/macOptions";
import { MsiOptions } from "./options/MsiOptions";
import { PkgOptions } from "./options/pkgOptions";
import { PlatformSpecificBuildOptions } from "./options/PlatformSpecificBuildOptions";
import { SnapOptions } from "./options/SnapOptions";
import { SquirrelWindowsOptions } from "./options/SquirrelWindowsOptions";
import { WindowsConfiguration } from "./options/winOptions";
import { BuildResult } from "./packager";
import { ArtifactBuildStarted, ArtifactCreated } from "./packagerApi";
import { PlatformPackager } from "./platformPackager";
import { NsisOptions, NsisWebOptions, PortableOptions } from "./targets/nsis/nsisOptions";
/**
* Configuration Options
*/
export interface Configuration extends PlatformSpecificBuildOptions {
/**
* The application id. Used as [CFBundleIdentifier](https://developer.apple.com/library/ios/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html#//apple_ref/doc/uid/20001431-102070) for MacOS and as
* [Application User Model ID](https://msdn.microsoft.com/en-us/library/windows/desktop/dd378459(v=vs.85).aspx) for Windows (NSIS target only, Squirrel.Windows not supported). It is strongly recommended that an explicit ID is set.
* @default com.electron.${name}
*/
readonly appId?: string | null;
/**
* As [name](#Metadata-name), but allows you to specify a product name for your executable which contains spaces and other special characters not allowed in the [name property](https://docs.npmjs.com/files/package.json#name).
*/
readonly productName?: string | null;
/**
* The human-readable copyright line for the app.
* @default Copyright © year ${author}
*/
readonly copyright?: string | null;
readonly directories?: MetadataDirectories | null;
/**
* Options related to how build macOS targets.
*/
readonly mac?: MacConfiguration | null;
/**
* MAS (Mac Application Store) options.
*/
readonly mas?: MasConfiguration | null;
/**
* MAS (Mac Application Store) development options (`mas-dev` target).
*/
readonly masDev?: MasConfiguration | null;
/**
* macOS DMG options.
*/
readonly dmg?: DmgOptions | null;
/**
* macOS PKG options.
*/
readonly pkg?: PkgOptions | null;
/**
* Options related to how build Windows targets.
*/
readonly win?: WindowsConfiguration | null;
readonly nsis?: NsisOptions | null;
readonly nsisWeb?: NsisWebOptions | null;
readonly portable?: PortableOptions | null;
readonly appx?: AppXOptions | null;
/** @private */
readonly msi?: MsiOptions | null;
readonly squirrelWindows?: SquirrelWindowsOptions | null;
/**
* Options related to how build Linux targets.
*/
readonly linux?: LinuxConfiguration | null;
/**
* Debian package options.
*/
readonly deb?: DebOptions | null;
/**
* Snap options.
*/
readonly snap?: SnapOptions | null;
/**
* AppImage options.
*/
readonly appImage?: AppImageOptions | null;
readonly pacman?: LinuxTargetSpecificOptions | null;
readonly rpm?: LinuxTargetSpecificOptions | null;
readonly freebsd?: LinuxTargetSpecificOptions | null;
readonly p5p?: LinuxTargetSpecificOptions | null;
readonly apk?: LinuxTargetSpecificOptions | null;
/**
* Whether to build the application native dependencies from source.
* @default false
*/
buildDependenciesFromSource?: boolean;
/**
* Whether to execute `node-gyp rebuild` before starting to package the app.
*
* Don't [use](https://github.com/electron-userland/electron-builder/issues/683#issuecomment-241214075) [npm](http://electron.atom.io/docs/tutorial/using-native-node-modules/#using-npm) (neither `.npmrc`) for configuring electron headers. Use `electron-builder node-gyp-rebuild` instead.
* @default false
*/
readonly nodeGypRebuild?: boolean;
/**
* Additional command line arguments to use when installing app native deps.
*/
readonly npmArgs?: Array<string> | string | null;
/**
* Whether to [rebuild](https://docs.npmjs.com/cli/rebuild) native dependencies before starting to package the app.
* @default true
*/
readonly npmRebuild?: boolean;
/**
* The build version. Maps to the `CFBundleVersion` on macOS, and `FileVersion` metadata property on Windows. Defaults to the `version`.
* If `TRAVIS_BUILD_NUMBER` or `APPVEYOR_BUILD_NUMBER` or `CIRCLE_BUILD_NUM` or `BUILD_NUMBER` or `bamboo.buildNumber` or `CI_PIPELINE_IID` env defined, it will be used as a build version (`version.build_number`).
*/
readonly buildVersion?: string | null;
/**
* Whether to use [electron-compile](http://github.com/electron/electron-compile) to compile app. Defaults to `true` if `electron-compile` in the dependencies. And `false` if in the `devDependencies` or doesn't specified.
*/
readonly electronCompile?: boolean;
/**
* The path to custom Electron build (e.g. `~/electron/out/R`).
*/
readonly electronDist?: string;
/**
* The [electron-download](https://github.com/electron-userland/electron-download#usage) options.
*/
readonly electronDownload?: ElectronDownloadOptions;
/**
* The version of electron you are packaging for. Defaults to version of `electron`, `electron-prebuilt` or `electron-prebuilt-compile` dependency.
*/
electronVersion?: string | null;
/**
* The name of a built-in configuration preset or path to config file (relative to project dir). Currently, only `react-cra` is supported.
*
* If `react-scripts` in the app dependencies, `react-cra` will be set automatically. Set to `null` to disable automatic detection.
*/
extends?: string | null;
/**
* Inject properties to `package.json`.
*/
readonly extraMetadata?: any;
/**
* Whether to fail if the application is not signed (to prevent unsigned app if code signing configuration is not correct).
* @default false
*/
readonly forceCodeSigning?: boolean;
/**
* *libui-based frameworks only* The version of NodeJS you are packaging for.
* You can set it to `current` to set the Node.js version that you use to run.
*/
readonly nodeVersion?: string | null;
/**
* *libui-based frameworks only* The version of LaunchUI you are packaging for. Applicable for Windows only. Defaults to version suitable for used framework version.
*/
readonly launchUiVersion?: boolean | string | null;
/**
* The framework name. One of `electron`, `proton`, `libui`. Defaults to `electron`.
*/
readonly framework?: string | null;
/**
* The function (or path to file or module id) to be [run after pack](#afterpack) (but before pack into distributable format and sign).
*/
readonly afterPack?: ((context: AfterPackContext) => Promise<any> | any) | string | null;
/**
* The function (or path to file or module id) to be [run after pack and sign](#aftersign) (but before pack into distributable format).
*/
readonly afterSign?: ((context: AfterPackContext) => Promise<any> | any) | string | null;
/**
* The function (or path to file or module id) to be run on artifact build start.
*/
readonly artifactBuildStarted?: ((context: ArtifactBuildStarted) => Promise<any> | any) | string | null;
/**
* The function (or path to file or module id) to be run on artifact build completed.
*/
readonly artifactBuildCompleted?: ((context: ArtifactCreated) => Promise<any> | any) | string | null;
/**
* The function (or path to file or module id) to be [run after all artifacts are build](#afterAllArtifactBuild).
*/
readonly afterAllArtifactBuild?: ((context: BuildResult) => Promise<Array<string>> | Array<string>) | string | null;
/**
* Appx manifest created on disk - not packed into .appx package yet.
*/
readonly appxManifestCreated?: ((path: string) => Promise<any> | any) | string | null;
/**
* The function (or path to file or module id) to be [run on each node module](#onnodemodulefile) file.
*/
readonly onNodeModuleFile?: ((file: string) => void) | string | null;
/**
* The function (or path to file or module id) to be run before dependencies are installed or rebuilt. Works when `npmRebuild` is set to `true`. Resolving to `false` will skip dependencies install or rebuild.
*
* If provided and `node_modules` are missing, it will not invoke production dependencies check.
*/
readonly beforeBuild?: ((context: BeforeBuildContext) => Promise<any>) | string | null;
/**
* Whether to build using Electron Build Service if target not supported on current OS.
* @default true
*/
readonly remoteBuild?: boolean;
/**
* Whether to include PDB files.
* @default false
*/
readonly includePdb?: boolean;
/**
* Whether to remove `scripts` field from `package.json` files.
*
* @default true
*/
readonly removePackageScripts?: boolean;
}
export interface AfterPackContext {
readonly outDir: string;
readonly appOutDir: string;
readonly packager: PlatformPackager<any>;
readonly electronPlatformName: string;
readonly arch: Arch;
readonly targets: Array<Target>;
}
export interface MetadataDirectories {
/**
* The path to build resources.
*
* Please note — build resources are not packed into the app. If you need to use some files, e.g. as tray icon, please include required files explicitly: `"files": ["**\/*", "build/icon.*"]`
* @default build
*/
readonly buildResources?: string | null;
/**
* The output directory. [File macros](/file-patterns#file-macros) are supported.
* @default dist
*/
readonly output?: string | null;
/**
* The application directory (containing the application package.json), defaults to `app`, `www` or working directory.
*/
readonly app?: string | null;
}

View File

@ -0,0 +1,7 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
// __ts-babel@6.0.4
//# sourceMappingURL=configuration.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":[],"names":[],"mappings":"","sourceRoot":""}

Some files were not shown because too many files have changed in this diff Show More