refactor: add prefer-const to .eslintrc + fix errors (#14880)

This commit is contained in:
Milan Burda 2018-10-02 03:56:31 +02:00 committed by Samuel Attard
parent 07161a8452
commit 3ad3ade828
47 changed files with 239 additions and 238 deletions

View file

@ -4,6 +4,9 @@
"browser": true "browser": true
}, },
"rules": { "rules": {
"no-var": "error" "no-var": "error",
"prefer-const": ["error", {
"destructuring": "all"
}]
} }
} }

View file

@ -42,7 +42,7 @@ Object.assign(app, {
const nativeFn = app.getAppMetrics const nativeFn = app.getAppMetrics
app.getAppMetrics = () => { app.getAppMetrics = () => {
let metrics = nativeFn.call(app) const metrics = nativeFn.call(app)
for (const metric of metrics) { for (const metric of metrics) {
if ('memory' in metric) { if ('memory' in metric) {
deprecate.removeProperty(metric, 'memory') deprecate.removeProperty(metric, 'memory')
@ -96,7 +96,7 @@ app.allowNTLMCredentialsForAllDomains = function (allow) {
if (!process.noDeprecations) { if (!process.noDeprecations) {
deprecate.warn('app.allowNTLMCredentialsForAllDomains', 'session.allowNTLMCredentialsForDomains') deprecate.warn('app.allowNTLMCredentialsForAllDomains', 'session.allowNTLMCredentialsForDomains')
} }
let domains = allow ? '*' : '' const domains = allow ? '*' : ''
if (!this.isReady()) { if (!this.isReady()) {
this.commandLine.appendSwitch('auth-server-whitelist', domains) this.commandLine.appendSwitch('auth-server-whitelist', domains)
} else { } else {
@ -106,7 +106,7 @@ app.allowNTLMCredentialsForAllDomains = function (allow) {
// Routes the events to webContents. // Routes the events to webContents.
const events = ['login', 'certificate-error', 'select-client-certificate'] const events = ['login', 'certificate-error', 'select-client-certificate']
for (let name of events) { for (const name of events) {
app.on(name, (event, webContents, ...args) => { app.on(name, (event, webContents, ...args) => {
webContents.emit(name, event, ...args) webContents.emit(name, event, ...args)
}) })

View file

@ -17,7 +17,7 @@ const isSameArgs = (args) => args.length === spawnedArgs.length && args.every((e
// Spawn a command and invoke the callback when it completes with an error // Spawn a command and invoke the callback when it completes with an error
// and the output from standard out. // and the output from standard out.
let spawnUpdate = function (args, detached, callback) { const spawnUpdate = function (args, detached, callback) {
let error, errorEmitted, stderr, stdout let error, errorEmitted, stderr, stdout
try { try {

View file

@ -41,14 +41,14 @@ BrowserWindow.prototype._init = function () {
this.webContents.on('-add-new-contents', (event, webContents, disposition, this.webContents.on('-add-new-contents', (event, webContents, disposition,
userGesture, left, top, width, userGesture, left, top, width,
height) => { height) => {
let urlFrameName = v8Util.getHiddenValue(webContents, 'url-framename') const urlFrameName = v8Util.getHiddenValue(webContents, 'url-framename')
if ((disposition !== 'foreground-tab' && disposition !== 'new-window' && if ((disposition !== 'foreground-tab' && disposition !== 'new-window' &&
disposition !== 'background-tab') || !urlFrameName) { disposition !== 'background-tab') || !urlFrameName) {
event.preventDefault() event.preventDefault()
return return
} }
let { url, frameName } = urlFrameName const { url, frameName } = urlFrameName
v8Util.deleteHiddenValue(webContents, 'url-framename') v8Util.deleteHiddenValue(webContents, 'url-framename')
const options = { const options = {
show: true, show: true,
@ -115,7 +115,7 @@ BrowserWindow.prototype._init = function () {
} }
const visibilityEvents = ['show', 'hide', 'minimize', 'maximize', 'restore'] const visibilityEvents = ['show', 'hide', 'minimize', 'maximize', 'restore']
for (let event of visibilityEvents) { for (const event of visibilityEvents) {
this.on(event, visibilityChanged) this.on(event, visibilityChanged)
} }
@ -145,7 +145,7 @@ BrowserWindow.getAllWindows = () => {
} }
BrowserWindow.getFocusedWindow = () => { BrowserWindow.getFocusedWindow = () => {
for (let window of BrowserWindow.getAllWindows()) { for (const window of BrowserWindow.getAllWindows()) {
if (window.isFocused() || window.isDevToolsFocused()) return window if (window.isFocused() || window.isDevToolsFocused()) return window
} }
return null return null

View file

@ -284,7 +284,7 @@ module.exports = {
}, },
showCertificateTrustDialog: function (...args) { showCertificateTrustDialog: function (...args) {
let [window, options, callback] = parseArgs(...args) const [window, options, callback] = parseArgs(...args)
if (options == null || typeof options !== 'object') { if (options == null || typeof options !== 'object') {
throw new TypeError('options must be an object') throw new TypeError('options must be an object')

View file

@ -8,7 +8,7 @@ const MenuItem = function (options) {
const { Menu } = require('electron') const { Menu } = require('electron')
// Preserve extra fields specified by user // Preserve extra fields specified by user
for (let key in options) { for (const key in options) {
if (!(key in this)) this[key] = options[key] if (!(key in this)) this[key] = options[key]
} }
if (typeof this.role === 'string' || this.role instanceof String) { if (typeof this.role === 'string' || this.role instanceof String) {

View file

@ -180,7 +180,7 @@ function areValidTemplateItems (template) {
function sortTemplate (template) { function sortTemplate (template) {
const sorted = sortMenuItems(template) const sorted = sortMenuItems(template)
for (let id in sorted) { for (const id in sorted) {
const item = sorted[id] const item = sorted[id]
if (Array.isArray(item.submenu)) { if (Array.isArray(item.submenu)) {
item.submenu = sortTemplate(item.submenu) item.submenu = sortTemplate(item.submenu)

View file

@ -141,11 +141,10 @@ const NavigationController = (function () {
} }
NavigationController.prototype.goToOffset = function (offset) { NavigationController.prototype.goToOffset = function (offset) {
let pendingIndex
if (!this.canGoToOffset(offset)) { if (!this.canGoToOffset(offset)) {
return return
} }
pendingIndex = this.currentIndex + offset const pendingIndex = this.currentIndex + offset
if (this.inPageIndex > -1 && pendingIndex >= this.inPageIndex) { if (this.inPageIndex > -1 && pendingIndex >= this.inPageIndex) {
this.pendingIndex = pendingIndex this.pendingIndex = pendingIndex
return this.webContents._goToOffset(offset) return this.webContents._goToOffset(offset)

View file

@ -119,7 +119,7 @@ class ClientRequest extends EventEmitter {
let urlStr = options.url let urlStr = options.url
if (!urlStr) { if (!urlStr) {
let urlObj = {} const urlObj = {}
const protocol = options.protocol || 'http:' const protocol = options.protocol || 'http:'
if (!kSupportedProtocols.has(protocol)) { if (!kSupportedProtocols.has(protocol)) {
throw new Error('Protocol "' + protocol + '" not supported. ') throw new Error('Protocol "' + protocol + '" not supported. ')
@ -149,7 +149,7 @@ class ClientRequest extends EventEmitter {
// an invalid request. // an invalid request.
throw new TypeError('Request path contains unescaped characters.') throw new TypeError('Request path contains unescaped characters.')
} }
let pathObj = url.parse(options.path || '/') const pathObj = url.parse(options.path || '/')
urlObj.pathname = pathObj.pathname urlObj.pathname = pathObj.pathname
urlObj.search = pathObj.search urlObj.search = pathObj.search
urlObj.hash = pathObj.hash urlObj.hash = pathObj.hash
@ -161,7 +161,7 @@ class ClientRequest extends EventEmitter {
throw new Error('redirect mode should be one of follow, error or manual') throw new Error('redirect mode should be one of follow, error or manual')
} }
let urlRequestOptions = { const urlRequestOptions = {
method: method, method: method,
url: urlStr, url: urlStr,
redirect: redirectPolicy redirect: redirectPolicy
@ -180,7 +180,7 @@ class ClientRequest extends EventEmitter {
} }
} }
let urlRequest = new URLRequest(urlRequestOptions) const urlRequest = new URLRequest(urlRequestOptions)
// Set back and forward links. // Set back and forward links.
this.urlRequest = urlRequest this.urlRequest = urlRequest
@ -192,7 +192,7 @@ class ClientRequest extends EventEmitter {
this.extraHeaders = {} this.extraHeaders = {}
if (options.headers) { if (options.headers) {
for (let key in options.headers) { for (const key in options.headers) {
this.setHeader(key, options.headers[key]) this.setHeader(key, options.headers[key])
} }
} }
@ -286,8 +286,8 @@ class ClientRequest extends EventEmitter {
} }
_write (chunk, encoding, callback, isLast) { _write (chunk, encoding, callback, isLast) {
let chunkIsString = typeof chunk === 'string' const chunkIsString = typeof chunk === 'string'
let chunkIsBuffer = chunk instanceof Buffer const chunkIsBuffer = chunk instanceof Buffer
if (!chunkIsString && !chunkIsBuffer) { if (!chunkIsString && !chunkIsBuffer) {
throw new TypeError('First argument must be a string or Buffer.') throw new TypeError('First argument must be a string or Buffer.')
} }
@ -306,7 +306,7 @@ class ClientRequest extends EventEmitter {
// Headers are assumed to be sent on first call to _writeBuffer, // Headers are assumed to be sent on first call to _writeBuffer,
// i.e. after the first call to write or end. // i.e. after the first call to write or end.
let result = this.urlRequest.write(chunk, isLast) const result = this.urlRequest.write(chunk, isLast)
// The write callback is fired asynchronously to mimic Node.js. // The write callback is fired asynchronously to mimic Node.js.
if (callback) { if (callback) {
@ -318,7 +318,7 @@ class ClientRequest extends EventEmitter {
write (data, encoding, callback) { write (data, encoding, callback) {
if (this.urlRequest.finished) { if (this.urlRequest.finished) {
let error = new Error('Write after end.') const error = new Error('Write after end.')
process.nextTick(writeAfterEndNT, this, error, callback) process.nextTick(writeAfterEndNT, this, error, callback)
return true return true
} }

View file

@ -317,7 +317,7 @@ module.exports = {
getFocusedWebContents () { getFocusedWebContents () {
let focused = null let focused = null
for (let contents of binding.getAllWebContents()) { for (const contents of binding.getAllWebContents()) {
if (!contents.isFocused()) continue if (!contents.isFocused()) continue
if (focused == null) focused = contents if (focused == null) focused = contents
// Return webview web contents which may be embedded inside another // Return webview web contents which may be embedded inside another

View file

@ -51,7 +51,7 @@ class ObjectsRegistry {
// then garbage collected in old page). // then garbage collected in old page).
remove (webContents, contextId, id) { remove (webContents, contextId, id) {
const ownerKey = getOwnerKey(webContents, contextId) const ownerKey = getOwnerKey(webContents, contextId)
let owner = this.owners[ownerKey] const owner = this.owners[ownerKey]
if (owner) { if (owner) {
// Remove the reference in owner. // Remove the reference in owner.
owner.delete(id) owner.delete(id)
@ -63,10 +63,10 @@ class ObjectsRegistry {
// Clear all references to objects refrenced by the WebContents. // Clear all references to objects refrenced by the WebContents.
clear (webContents, contextId) { clear (webContents, contextId) {
const ownerKey = getOwnerKey(webContents, contextId) const ownerKey = getOwnerKey(webContents, contextId)
let owner = this.owners[ownerKey] const owner = this.owners[ownerKey]
if (!owner) return if (!owner) return
for (let id of owner) this.dereference(id) for (const id of owner) this.dereference(id)
delete this.owners[ownerKey] delete this.owners[ownerKey]
} }
@ -87,7 +87,7 @@ class ObjectsRegistry {
// Private: Dereference the object from store. // Private: Dereference the object from store.
dereference (id) { dereference (id) {
let pointer = this.storage[id] const pointer = this.storage[id]
if (pointer == null) { if (pointer == null) {
return return
} }

View file

@ -37,8 +37,8 @@ const getObjectMembers = function (object) {
} }
// Map properties to descriptors. // Map properties to descriptors.
return names.map((name) => { return names.map((name) => {
let descriptor = Object.getOwnPropertyDescriptor(object, name) const descriptor = Object.getOwnPropertyDescriptor(object, name)
let member = { name, enumerable: descriptor.enumerable, writable: false } const member = { name, enumerable: descriptor.enumerable, writable: false }
if (descriptor.get === undefined && typeof object[name] === 'function') { if (descriptor.get === undefined && typeof object[name] === 'function') {
member.type = 'method' member.type = 'method'
} else { } else {
@ -51,7 +51,7 @@ const getObjectMembers = function (object) {
// Return the description of object's prototype. // Return the description of object's prototype.
const getObjectPrototype = function (object) { const getObjectPrototype = function (object) {
let proto = Object.getPrototypeOf(object) const proto = Object.getPrototypeOf(object)
if (proto === null || proto === Object.prototype) return null if (proto === null || proto === Object.prototype) return null
return { return {
members: getObjectMembers(proto), members: getObjectMembers(proto),
@ -189,7 +189,7 @@ const unwrapArgs = function (sender, contextId, args) {
then: metaToValue(meta.then) then: metaToValue(meta.then)
}) })
case 'object': { case 'object': {
let ret = {} const ret = {}
Object.defineProperty(ret.constructor, 'name', { value: meta.name }) Object.defineProperty(ret.constructor, 'name', { value: meta.name })
for (const { name, value } of meta.members) { for (const { name, value } of meta.members) {
@ -213,7 +213,7 @@ const unwrapArgs = function (sender, contextId, args) {
} }
const processId = sender.getProcessId() const processId = sender.getProcessId()
let callIntoRenderer = function (...args) { const callIntoRenderer = function (...args) {
if (!sender.isDestroyed() && processId === sender.getProcessId()) { if (!sender.isDestroyed() && processId === sender.getProcessId()) {
sender.send('ELECTRON_RENDERER_CALLBACK', contextId, meta.id, valueToMeta(sender, contextId, args)) sender.send('ELECTRON_RENDERER_CALLBACK', contextId, meta.id, valueToMeta(sender, contextId, args))
} else { } else {
@ -295,7 +295,7 @@ handleRemoteCommand('ELECTRON_BROWSER_CURRENT_WEB_CONTENTS', function (event, co
handleRemoteCommand('ELECTRON_BROWSER_CONSTRUCTOR', function (event, contextId, id, args) { handleRemoteCommand('ELECTRON_BROWSER_CONSTRUCTOR', function (event, contextId, id, args) {
args = unwrapArgs(event.sender, contextId, args) args = unwrapArgs(event.sender, contextId, args)
let constructor = objectsRegistry.get(id) const constructor = objectsRegistry.get(id)
if (constructor == null) { if (constructor == null) {
throwRPCError(`Cannot call constructor on missing remote object ${id}`) throwRPCError(`Cannot call constructor on missing remote object ${id}`)
@ -306,7 +306,7 @@ handleRemoteCommand('ELECTRON_BROWSER_CONSTRUCTOR', function (event, contextId,
handleRemoteCommand('ELECTRON_BROWSER_FUNCTION_CALL', function (event, contextId, id, args) { handleRemoteCommand('ELECTRON_BROWSER_FUNCTION_CALL', function (event, contextId, id, args) {
args = unwrapArgs(event.sender, contextId, args) args = unwrapArgs(event.sender, contextId, args)
let func = objectsRegistry.get(id) const func = objectsRegistry.get(id)
if (func == null) { if (func == null) {
throwRPCError(`Cannot call function on missing remote object ${id}`) throwRPCError(`Cannot call function on missing remote object ${id}`)
@ -317,7 +317,7 @@ handleRemoteCommand('ELECTRON_BROWSER_FUNCTION_CALL', function (event, contextId
handleRemoteCommand('ELECTRON_BROWSER_MEMBER_CONSTRUCTOR', function (event, contextId, id, method, args) { handleRemoteCommand('ELECTRON_BROWSER_MEMBER_CONSTRUCTOR', function (event, contextId, id, method, args) {
args = unwrapArgs(event.sender, contextId, args) args = unwrapArgs(event.sender, contextId, args)
let object = objectsRegistry.get(id) const object = objectsRegistry.get(id)
if (object == null) { if (object == null) {
throwRPCError(`Cannot call constructor '${method}' on missing remote object ${id}`) throwRPCError(`Cannot call constructor '${method}' on missing remote object ${id}`)
@ -328,7 +328,7 @@ handleRemoteCommand('ELECTRON_BROWSER_MEMBER_CONSTRUCTOR', function (event, cont
handleRemoteCommand('ELECTRON_BROWSER_MEMBER_CALL', function (event, contextId, id, method, args) { handleRemoteCommand('ELECTRON_BROWSER_MEMBER_CALL', function (event, contextId, id, method, args) {
args = unwrapArgs(event.sender, contextId, args) args = unwrapArgs(event.sender, contextId, args)
let obj = objectsRegistry.get(id) const obj = objectsRegistry.get(id)
if (obj == null) { if (obj == null) {
throwRPCError(`Cannot call function '${method}' on missing remote object ${id}`) throwRPCError(`Cannot call function '${method}' on missing remote object ${id}`)
@ -339,7 +339,7 @@ handleRemoteCommand('ELECTRON_BROWSER_MEMBER_CALL', function (event, contextId,
handleRemoteCommand('ELECTRON_BROWSER_MEMBER_SET', function (event, contextId, id, name, args) { handleRemoteCommand('ELECTRON_BROWSER_MEMBER_SET', function (event, contextId, id, name, args) {
args = unwrapArgs(event.sender, contextId, args) args = unwrapArgs(event.sender, contextId, args)
let obj = objectsRegistry.get(id) const obj = objectsRegistry.get(id)
if (obj == null) { if (obj == null) {
throwRPCError(`Cannot set property '${name}' on missing remote object ${id}`) throwRPCError(`Cannot set property '${name}' on missing remote object ${id}`)
@ -350,7 +350,7 @@ handleRemoteCommand('ELECTRON_BROWSER_MEMBER_SET', function (event, contextId, i
}) })
handleRemoteCommand('ELECTRON_BROWSER_MEMBER_GET', function (event, contextId, id, name) { handleRemoteCommand('ELECTRON_BROWSER_MEMBER_GET', function (event, contextId, id, name) {
let obj = objectsRegistry.get(id) const obj = objectsRegistry.get(id)
if (obj == null) { if (obj == null) {
throwRPCError(`Cannot get property '${name}' on missing remote object ${id}`) throwRPCError(`Cannot get property '${name}' on missing remote object ${id}`)
@ -369,14 +369,14 @@ handleRemoteCommand('ELECTRON_BROWSER_CONTEXT_RELEASE', (event, contextId) => {
}) })
handleRemoteCommand('ELECTRON_BROWSER_GUEST_WEB_CONTENTS', function (event, contextId, guestInstanceId) { handleRemoteCommand('ELECTRON_BROWSER_GUEST_WEB_CONTENTS', function (event, contextId, guestInstanceId) {
let guestViewManager = require('@electron/internal/browser/guest-view-manager') const guestViewManager = require('@electron/internal/browser/guest-view-manager')
return valueToMeta(event.sender, contextId, guestViewManager.getGuest(guestInstanceId)) return valueToMeta(event.sender, contextId, guestViewManager.getGuest(guestInstanceId))
}) })
ipcMain.on('ELECTRON_BROWSER_ASYNC_CALL_TO_GUEST_VIEW', function (event, requestId, guestInstanceId, method, args, hasCallback) { ipcMain.on('ELECTRON_BROWSER_ASYNC_CALL_TO_GUEST_VIEW', function (event, requestId, guestInstanceId, method, args, hasCallback) {
new Promise(resolve => { new Promise(resolve => {
let guestViewManager = require('./guest-view-manager') const guestViewManager = require('./guest-view-manager')
let guest = guestViewManager.getGuest(guestInstanceId) const guest = guestViewManager.getGuest(guestInstanceId)
if (guest.hostWebContents !== event.sender) { if (guest.hostWebContents !== event.sender) {
throw new Error('Access denied') throw new Error('Access denied')
} }
@ -396,8 +396,8 @@ ipcMain.on('ELECTRON_BROWSER_ASYNC_CALL_TO_GUEST_VIEW', function (event, request
ipcMain.on('ELECTRON_BROWSER_SYNC_CALL_TO_GUEST_VIEW', function (event, guestInstanceId, method, args) { ipcMain.on('ELECTRON_BROWSER_SYNC_CALL_TO_GUEST_VIEW', function (event, guestInstanceId, method, args) {
try { try {
let guestViewManager = require('@electron/internal/browser/guest-view-manager') const guestViewManager = require('@electron/internal/browser/guest-view-manager')
let guest = guestViewManager.getGuest(guestInstanceId) const guest = guestViewManager.getGuest(guestInstanceId)
if (guest.hostWebContents !== event.sender) { if (guest.hostWebContents !== event.sender) {
throw new Error('Access denied') throw new Error('Access denied')
} }

View file

@ -5,7 +5,7 @@ const binding = process.atomBinding('crash_reporter')
const sendSync = function (channel, ...args) { const sendSync = function (channel, ...args) {
if (process.type === 'browser') { if (process.type === 'browser') {
let event = {} const event = {}
electron.ipcMain.emit(channel, event, ...args) electron.ipcMain.emit(channel, event, ...args)
return event.returnValue return event.returnValue
} else { } else {

View file

@ -36,7 +36,7 @@ function wrapArgs (args, visited = new Set()) {
if (Array.isArray(value)) { if (Array.isArray(value)) {
visited.add(value) visited.add(value)
let meta = { const meta = {
type: 'array', type: 'array',
value: wrapArgs(value, visited) value: wrapArgs(value, visited)
} }
@ -67,13 +67,13 @@ function wrapArgs (args, visited = new Set()) {
} }
} }
let meta = { const meta = {
type: 'object', type: 'object',
name: value.constructor ? value.constructor.name : '', name: value.constructor ? value.constructor.name : '',
members: [] members: []
} }
visited.add(value) visited.add(value)
for (let prop in value) { for (const prop in value) {
meta.members.push({ meta.members.push({
name: prop, name: prop,
value: valueToMeta(value[prop]) value: valueToMeta(value[prop])
@ -109,10 +109,10 @@ function wrapArgs (args, visited = new Set()) {
function setObjectMembers (ref, object, metaId, members) { function setObjectMembers (ref, object, metaId, members) {
if (!Array.isArray(members)) return if (!Array.isArray(members)) return
for (let member of members) { for (const member of members) {
if (object.hasOwnProperty(member.name)) continue if (object.hasOwnProperty(member.name)) continue
let descriptor = { enumerable: member.enumerable } const descriptor = { enumerable: member.enumerable }
if (member.type === 'method') { if (member.type === 'method') {
const remoteMemberFunction = function (...args) { const remoteMemberFunction = function (...args) {
let command let command
@ -163,7 +163,7 @@ function setObjectMembers (ref, object, metaId, members) {
// This matches |getObjectPrototype| in rpc-server. // This matches |getObjectPrototype| in rpc-server.
function setObjectPrototype (ref, object, metaId, descriptor) { function setObjectPrototype (ref, object, metaId, descriptor) {
if (descriptor === null) return if (descriptor === null) return
let proto = {} const proto = {}
setObjectMembers(ref, proto, metaId, descriptor.members) setObjectMembers(ref, proto, metaId, descriptor.members)
setObjectPrototype(ref, proto, metaId, descriptor.proto) setObjectPrototype(ref, proto, metaId, descriptor.proto)
Object.setPrototypeOf(object, proto) Object.setPrototypeOf(object, proto)
@ -201,7 +201,7 @@ function proxyFunctionProperties (remoteMemberFunction, metaId, name) {
return Object.getOwnPropertyNames(target) return Object.getOwnPropertyNames(target)
}, },
getOwnPropertyDescriptor: (target, property) => { getOwnPropertyDescriptor: (target, property) => {
let descriptor = Object.getOwnPropertyDescriptor(target, property) const descriptor = Object.getOwnPropertyDescriptor(target, property)
if (descriptor) return descriptor if (descriptor) return descriptor
loadRemoteProperties() loadRemoteProperties()
return Object.getOwnPropertyDescriptor(target, property) return Object.getOwnPropertyDescriptor(target, property)
@ -231,7 +231,7 @@ function metaToValue (meta) {
// A shadow class to represent the remote function object. // A shadow class to represent the remote function object.
if (meta.type === 'function') { if (meta.type === 'function') {
let remoteFunction = function (...args) { const remoteFunction = function (...args) {
let command let command
if (this && this.constructor === remoteFunction) { if (this && this.constructor === remoteFunction) {
command = 'ELECTRON_BROWSER_CONSTRUCTOR' command = 'ELECTRON_BROWSER_CONSTRUCTOR'
@ -262,7 +262,7 @@ function metaToValue (meta) {
function metaToPlainObject (meta) { function metaToPlainObject (meta) {
const obj = (() => meta.type === 'error' ? new Error() : {})() const obj = (() => meta.type === 'error' ? new Error() : {})()
for (let i = 0; i < meta.members.length; i++) { for (let i = 0; i < meta.members.length; i++) {
let { name, value } = meta.members[i] const { name, value } = meta.members[i]
obj[name] = value obj[name] = value
} }
return obj return obj

View file

@ -91,7 +91,7 @@ const getStorageManager = (storageType, extensionId) => {
// eslint-disable-next-line standard/no-callback-literal // eslint-disable-next-line standard/no-callback-literal
if (keys.length === 0) return callback({}) if (keys.length === 0) return callback({})
let items = {} const items = {}
keys.forEach(function (key) { keys.forEach(function (key) {
let value = storage[key] let value = storage[key]
if (value == null) value = defaults[key] if (value == null) value = defaults[key]

View file

@ -48,7 +48,7 @@ let preloadScript = null
let preloadScripts = [] let preloadScripts = []
let isBackgroundPage = false let isBackgroundPage = false
let appPath = null let appPath = null
for (let arg of process.argv) { for (const arg of process.argv) {
if (arg.indexOf('--guest-instance-id=') === 0) { if (arg.indexOf('--guest-instance-id=') === 0) {
// This is a guest web view. // This is a guest web view.
process.guestInstanceId = parseInt(arg.substr(arg.indexOf('=') + 1)) process.guestInstanceId = parseInt(arg.substr(arg.indexOf('=') + 1))

View file

@ -19,7 +19,7 @@ v8Util.setHiddenValue(global, 'Buffer', Buffer)
v8Util.setHiddenValue(global, 'ipc', new EventEmitter()) v8Util.setHiddenValue(global, 'ipc', new EventEmitter())
// The process object created by browserify is not an event emitter, fix it so // The process object created by browserify is not an event emitter, fix it so
// the API is more compatible with non-sandboxed renderers. // the API is more compatible with non-sandboxed renderers.
for (let prop of Object.keys(EventEmitter.prototype)) { for (const prop of Object.keys(EventEmitter.prototype)) {
if (process.hasOwnProperty(prop)) { if (process.hasOwnProperty(prop)) {
delete process[prop] delete process[prop]
} }

View file

@ -22,7 +22,7 @@ global.module = module
// Set the __filename to the path of html file if it is file: protocol. // Set the __filename to the path of html file if it is file: protocol.
if (self.location.protocol === 'file:') { if (self.location.protocol === 'file:') {
let pathname = process.platform === 'win32' && self.location.pathname[0] === '/' ? self.location.pathname.substr(1) : self.location.pathname const pathname = process.platform === 'win32' && self.location.pathname[0] === '/' ? self.location.pathname.substr(1) : self.location.pathname
global.__filename = path.normalize(decodeURIComponent(pathname)) global.__filename = path.normalize(decodeURIComponent(pathname))
global.__dirname = path.dirname(global.__filename) global.__dirname = path.dirname(global.__filename)

View file

@ -51,7 +51,7 @@ async function makeRequest (requestOptions, parseResponse) {
async function circleCIcall (buildUrl, targetBranch, job, options) { async function circleCIcall (buildUrl, targetBranch, job, options) {
console.log(`Triggering CircleCI to run build job: ${job} on branch: ${targetBranch} with release flag.`) console.log(`Triggering CircleCI to run build job: ${job} on branch: ${targetBranch} with release flag.`)
let buildRequest = { const buildRequest = {
'build_parameters': { 'build_parameters': {
'CIRCLE_JOB': job 'CIRCLE_JOB': job
} }
@ -67,7 +67,7 @@ async function circleCIcall (buildUrl, targetBranch, job, options) {
buildRequest.build_parameters.AUTO_RELEASE = 'true' buildRequest.build_parameters.AUTO_RELEASE = 'true'
} }
let circleResponse = await makeRequest({ const circleResponse = await makeRequest({
method: 'POST', method: 'POST',
url: buildUrl, url: buildUrl,
headers: { headers: {
@ -117,7 +117,7 @@ async function callAppVeyor (targetBranch, job, options) {
}), }),
method: 'POST' method: 'POST'
} }
let appVeyorResponse = await makeRequest(requestOpts, true).catch(err => { const appVeyorResponse = await makeRequest(requestOpts, true).catch(err => {
console.log('Error calling AppVeyor:', err) console.log('Error calling AppVeyor:', err)
}) })
const buildUrl = `https://windows-ci.electronjs.org/project/AppVeyor/${appVeyorJobs[job]}/build/${appVeyorResponse.version}` const buildUrl = `https://windows-ci.electronjs.org/project/AppVeyor/${appVeyorJobs[job]}/build/${appVeyorResponse.version}`
@ -147,7 +147,7 @@ async function buildVSTS (targetBranch, options) {
environmentVariables.UPLOAD_TO_S3 = 1 environmentVariables.UPLOAD_TO_S3 = 1
} }
let requestOpts = { const requestOpts = {
url: `${vstsURL}/definitions?api-version=4.1`, url: `${vstsURL}/definitions?api-version=4.1`,
auth: { auth: {
user: '', user: '',
@ -157,7 +157,7 @@ async function buildVSTS (targetBranch, options) {
'Content-Type': 'application/json' 'Content-Type': 'application/json'
} }
} }
let vstsResponse = await makeRequest(requestOpts, true).catch(err => { const vstsResponse = await makeRequest(requestOpts, true).catch(err => {
console.log('Error calling VSTS to get build definitions:', err) console.log('Error calling VSTS to get build definitions:', err)
}) })
let buildsToRun = [] let buildsToRun = []
@ -170,14 +170,14 @@ async function buildVSTS (targetBranch, options) {
} }
async function callVSTSBuild (build, targetBranch, environmentVariables) { async function callVSTSBuild (build, targetBranch, environmentVariables) {
let buildBody = { const buildBody = {
definition: build, definition: build,
sourceBranch: targetBranch sourceBranch: targetBranch
} }
if (Object.keys(environmentVariables).length !== 0) { if (Object.keys(environmentVariables).length !== 0) {
buildBody.parameters = JSON.stringify(environmentVariables) buildBody.parameters = JSON.stringify(environmentVariables)
} }
let requestOpts = { const requestOpts = {
url: `${vstsURL}/builds?api-version=4.1`, url: `${vstsURL}/builds?api-version=4.1`,
auth: { auth: {
user: '', user: '',
@ -189,7 +189,7 @@ async function callVSTSBuild (build, targetBranch, environmentVariables) {
body: JSON.stringify(buildBody), body: JSON.stringify(buildBody),
method: 'POST' method: 'POST'
} }
let vstsResponse = await makeRequest(requestOpts, true).catch(err => { const vstsResponse = await makeRequest(requestOpts, true).catch(err => {
console.log(`Error calling VSTS for job ${build.name}`, err) console.log(`Error calling VSTS for job ${build.name}`, err)
}) })
console.log(`VSTS release build request for ${build.name} successful. Check ${vstsResponse._links.web.href} for status.`) console.log(`VSTS release build request for ${build.name} successful. Check ${vstsResponse._links.web.href} for status.`)

View file

@ -12,11 +12,11 @@ const version = process.argv[2]
async function findRelease () { async function findRelease () {
github.authenticate({ type: 'token', token: process.env.ELECTRON_GITHUB_TOKEN }) github.authenticate({ type: 'token', token: process.env.ELECTRON_GITHUB_TOKEN })
let releases = await github.repos.getReleases({ const releases = await github.repos.getReleases({
owner: 'electron', owner: 'electron',
repo: version.indexOf('nightly') > 0 ? 'nightlies' : 'electron' repo: version.indexOf('nightly') > 0 ? 'nightlies' : 'electron'
}) })
let targetRelease = releases.data.find(release => { const targetRelease = releases.data.find(release => {
return release.tag_name === version return release.tag_name === version
}) })
let returnObject = {} let returnObject = {}

View file

@ -5,7 +5,7 @@ const gitDir = path.resolve(__dirname, '..')
async function determineNextMajorForMaster () { async function determineNextMajorForMaster () {
let branchNames let branchNames
let result = await GitProcess.exec(['branch', '-a', '--remote', '--list', 'origin/[0-9]-[0-9]-x'], gitDir) const result = await GitProcess.exec(['branch', '-a', '--remote', '--list', 'origin/[0-9]-[0-9]-x'], gitDir)
if (result.exitCode === 0) { if (result.exitCode === 0) {
branchNames = result.stdout.trim().split('\n') branchNames = result.stdout.trim().split('\n')
const filtered = branchNames.map(b => b.replace('origin/', '')) const filtered = branchNames.map(b => b.replace('origin/', ''))

View file

@ -34,15 +34,15 @@ async function getNewVersion (dryRun) {
if (!dryRun) { if (!dryRun) {
console.log(`Bumping for new "${versionType}" version.`) console.log(`Bumping for new "${versionType}" version.`)
} }
let bumpScript = path.join(__dirname, 'bump-version.py') const bumpScript = path.join(__dirname, 'bump-version.py')
let scriptArgs = [bumpScript, '--bump', versionType] const scriptArgs = [bumpScript, '--bump', versionType]
if (dryRun) { if (dryRun) {
scriptArgs.push('--dry-run') scriptArgs.push('--dry-run')
} }
try { try {
let bumpVersion = execSync(scriptArgs.join(' '), { encoding: 'UTF-8' }) let bumpVersion = execSync(scriptArgs.join(' '), { encoding: 'UTF-8' })
bumpVersion = bumpVersion.substr(bumpVersion.indexOf(':') + 1).trim() bumpVersion = bumpVersion.substr(bumpVersion.indexOf(':') + 1).trim()
let newVersion = `v${bumpVersion}` const newVersion = `v${bumpVersion}`
if (!dryRun) { if (!dryRun) {
console.log(`${pass} Successfully bumped version to ${newVersion}`) console.log(`${pass} Successfully bumped version to ${newVersion}`)
} }
@ -55,15 +55,15 @@ async function getNewVersion (dryRun) {
async function getCurrentBranch (gitDir) { async function getCurrentBranch (gitDir) {
console.log(`Determining current git branch`) console.log(`Determining current git branch`)
let gitArgs = ['rev-parse', '--abbrev-ref', 'HEAD'] const gitArgs = ['rev-parse', '--abbrev-ref', 'HEAD']
let branchDetails = await GitProcess.exec(gitArgs, gitDir) const branchDetails = await GitProcess.exec(gitArgs, gitDir)
if (branchDetails.exitCode === 0) { if (branchDetails.exitCode === 0) {
let currentBranch = branchDetails.stdout.trim() const currentBranch = branchDetails.stdout.trim()
console.log(`${pass} Successfully determined current git branch is ` + console.log(`${pass} Successfully determined current git branch is ` +
`${currentBranch}`) `${currentBranch}`)
return currentBranch return currentBranch
} else { } else {
let error = GitProcess.parseError(branchDetails.stderr) const error = GitProcess.parseError(branchDetails.stderr)
console.log(`${fail} Could not get details for the current branch, console.log(`${fail} Could not get details for the current branch,
error was ${branchDetails.stderr}`, error) error was ${branchDetails.stderr}`, error)
process.exit(1) process.exit(1)
@ -75,7 +75,7 @@ async function getReleaseNotes (currentBranch) {
return 'Nightlies do not get release notes, please compare tags for info' return 'Nightlies do not get release notes, please compare tags for info'
} }
console.log(`Generating release notes for ${currentBranch}.`) console.log(`Generating release notes for ${currentBranch}.`)
let githubOpts = { const githubOpts = {
owner: 'electron', owner: 'electron',
repo: targetRepo, repo: targetRepo,
base: `v${pkg.version}`, base: `v${pkg.version}`,
@ -88,7 +88,7 @@ async function getReleaseNotes (currentBranch) {
releaseNotes = '(placeholder)\n' releaseNotes = '(placeholder)\n'
} }
console.log(`Checking for commits from ${pkg.version} to ${currentBranch}`) console.log(`Checking for commits from ${pkg.version} to ${currentBranch}`)
let commitComparison = await github.repos.compareCommits(githubOpts) const commitComparison = await github.repos.compareCommits(githubOpts)
.catch(err => { .catch(err => {
console.log(`${fail} Error checking for commits from ${pkg.version} to ` + console.log(`${fail} Error checking for commits from ${pkg.version} to ` +
`${currentBranch}`, err) `${currentBranch}`, err)
@ -112,7 +112,7 @@ async function getReleaseNotes (currentBranch) {
let prNumber let prNumber
if (prMatch) { if (prMatch) {
commitMessage = commitMessage.replace(mergeRE, '').replace('\n', '') commitMessage = commitMessage.replace(mergeRE, '').replace('\n', '')
let newlineMatch = commitMessage.match(newlineRE) const newlineMatch = commitMessage.match(newlineRE)
if (newlineMatch) { if (newlineMatch) {
commitMessage = newlineMatch[1] commitMessage = newlineMatch[1]
} }
@ -138,19 +138,19 @@ async function getReleaseNotes (currentBranch) {
} }
async function createRelease (branchToTarget, isBeta) { async function createRelease (branchToTarget, isBeta) {
let releaseNotes = await getReleaseNotes(branchToTarget) const releaseNotes = await getReleaseNotes(branchToTarget)
let newVersion = await getNewVersion() const newVersion = await getNewVersion()
await tagRelease(newVersion) await tagRelease(newVersion)
const githubOpts = { const githubOpts = {
owner: 'electron', owner: 'electron',
repo: targetRepo repo: targetRepo
} }
console.log(`Checking for existing draft release.`) console.log(`Checking for existing draft release.`)
let releases = await github.repos.getReleases(githubOpts) const releases = await github.repos.getReleases(githubOpts)
.catch(err => { .catch(err => {
console.log('$fail} Could not get releases. Error was', err) console.log('$fail} Could not get releases. Error was', err)
}) })
let drafts = releases.data.filter(release => release.draft && const drafts = releases.data.filter(release => release.draft &&
release.tag_name === newVersion) release.tag_name === newVersion)
if (drafts.length > 0) { if (drafts.length > 0) {
console.log(`${fail} Aborting because draft release for console.log(`${fail} Aborting because draft release for
@ -188,7 +188,7 @@ async function createRelease (branchToTarget, isBeta) {
} }
async function pushRelease (branch) { async function pushRelease (branch) {
let pushDetails = await GitProcess.exec(['push', 'origin', `HEAD:${branch}`, '--follow-tags'], gitDir) const pushDetails = await GitProcess.exec(['push', 'origin', `HEAD:${branch}`, '--follow-tags'], gitDir)
if (pushDetails.exitCode === 0) { if (pushDetails.exitCode === 0) {
console.log(`${pass} Successfully pushed the release. Wait for ` + console.log(`${pass} Successfully pushed the release. Wait for ` +
`release builds to finish before running "npm run release".`) `release builds to finish before running "npm run release".`)
@ -208,7 +208,7 @@ async function runReleaseBuilds (branch) {
async function tagRelease (version) { async function tagRelease (version) {
console.log(`Tagging release ${version}.`) console.log(`Tagging release ${version}.`)
let checkoutDetails = await GitProcess.exec([ 'tag', '-a', '-m', version, version ], gitDir) const checkoutDetails = await GitProcess.exec([ 'tag', '-a', '-m', version, version ], gitDir)
if (checkoutDetails.exitCode === 0) { if (checkoutDetails.exitCode === 0) {
console.log(`${pass} Successfully tagged ${version}.`) console.log(`${pass} Successfully tagged ${version}.`)
} else { } else {
@ -219,7 +219,7 @@ async function tagRelease (version) {
} }
async function verifyNewVersion () { async function verifyNewVersion () {
let newVersion = await getNewVersion(true) const newVersion = await getNewVersion(true)
let response let response
if (args.automaticRelease) { if (args.automaticRelease) {
response = 'y' response = 'y'
@ -249,19 +249,19 @@ async function promptForVersion (version) {
// function to determine if there have been commits to master since the last release // function to determine if there have been commits to master since the last release
async function changesToRelease () { async function changesToRelease () {
let lastCommitWasRelease = new RegExp(`^Bump v[0-9.]*(-beta[0-9.]*)?(-nightly[0-9.]*)?$`, 'g') const lastCommitWasRelease = new RegExp(`^Bump v[0-9.]*(-beta[0-9.]*)?(-nightly[0-9.]*)?$`, 'g')
let lastCommit = await GitProcess.exec(['log', '-n', '1', `--pretty=format:'%s'`], gitDir) const lastCommit = await GitProcess.exec(['log', '-n', '1', `--pretty=format:'%s'`], gitDir)
return !lastCommitWasRelease.test(lastCommit.stdout) return !lastCommitWasRelease.test(lastCommit.stdout)
} }
async function prepareRelease (isBeta, notesOnly) { async function prepareRelease (isBeta, notesOnly) {
if (args.dryRun) { if (args.dryRun) {
let newVersion = await getNewVersion(true) const newVersion = await getNewVersion(true)
console.log(newVersion) console.log(newVersion)
} else { } else {
const currentBranch = (args.branch) ? args.branch : await getCurrentBranch(gitDir) const currentBranch = (args.branch) ? args.branch : await getCurrentBranch(gitDir)
if (notesOnly) { if (notesOnly) {
let releaseNotes = await getReleaseNotes(currentBranch) const releaseNotes = await getReleaseNotes(currentBranch)
console.log(`Draft release notes are: \n${releaseNotes}`) console.log(`Draft release notes are: \n${releaseNotes}`)
} else { } else {
const changes = await changesToRelease(currentBranch) const changes = await changesToRelease(currentBranch)

View file

@ -141,15 +141,15 @@ new Promise((resolve, reject) => {
async function getCurrentBranch () { async function getCurrentBranch () {
const gitDir = path.resolve(__dirname, '..') const gitDir = path.resolve(__dirname, '..')
console.log(`Determining current git branch`) console.log(`Determining current git branch`)
let gitArgs = ['rev-parse', '--abbrev-ref', 'HEAD'] const gitArgs = ['rev-parse', '--abbrev-ref', 'HEAD']
let branchDetails = await GitProcess.exec(gitArgs, gitDir) const branchDetails = await GitProcess.exec(gitArgs, gitDir)
if (branchDetails.exitCode === 0) { if (branchDetails.exitCode === 0) {
let currentBranch = branchDetails.stdout.trim() const currentBranch = branchDetails.stdout.trim()
console.log(`Successfully determined current git branch is ` + console.log(`Successfully determined current git branch is ` +
`${currentBranch}`) `${currentBranch}`)
return currentBranch return currentBranch
} else { } else {
let error = GitProcess.parseError(branchDetails.stderr) const error = GitProcess.parseError(branchDetails.stderr)
console.log(`Could not get details for the current branch, console.log(`Could not get details for the current branch,
error was ${branchDetails.stderr}`, error) error was ${branchDetails.stderr}`, error)
process.exit(1) process.exit(1)

View file

@ -24,15 +24,14 @@ const github = new GitHub({
github.authenticate({ type: 'token', token: process.env.ELECTRON_GITHUB_TOKEN }) github.authenticate({ type: 'token', token: process.env.ELECTRON_GITHUB_TOKEN })
async function getDraftRelease (version, skipValidation) { async function getDraftRelease (version, skipValidation) {
let releaseInfo = await github.repos.getReleases({ owner: 'electron', repo: targetRepo }) const releaseInfo = await github.repos.getReleases({ owner: 'electron', repo: targetRepo })
let drafts
let versionToCheck let versionToCheck
if (version) { if (version) {
versionToCheck = version versionToCheck = version
} else { } else {
versionToCheck = pkgVersion versionToCheck = pkgVersion
} }
drafts = releaseInfo.data const drafts = releaseInfo.data
.filter(release => release.tag_name === versionToCheck && .filter(release => release.tag_name === versionToCheck &&
release.draft === true) release.draft === true)
const draft = drafts[0] const draft = drafts[0]
@ -143,19 +142,19 @@ function checkVersion () {
if (args.skipVersionCheck) return if (args.skipVersionCheck) return
console.log(`Verifying that app version matches package version ${pkgVersion}.`) console.log(`Verifying that app version matches package version ${pkgVersion}.`)
let startScript = path.join(__dirname, 'start.py') const startScript = path.join(__dirname, 'start.py')
let scriptArgs = ['--version'] const scriptArgs = ['--version']
if (args.automaticRelease) { if (args.automaticRelease) {
scriptArgs.unshift('-R') scriptArgs.unshift('-R')
} }
let appVersion = runScript(startScript, scriptArgs).trim() const appVersion = runScript(startScript, scriptArgs).trim()
check((pkgVersion.indexOf(appVersion) === 0), `App version ${appVersion} matches ` + check((pkgVersion.indexOf(appVersion) === 0), `App version ${appVersion} matches ` +
`package version ${pkgVersion}.`, true) `package version ${pkgVersion}.`, true)
} }
function runScript (scriptName, scriptArgs, cwd) { function runScript (scriptName, scriptArgs, cwd) {
let scriptCommand = `${scriptName} ${scriptArgs.join(' ')}` const scriptCommand = `${scriptName} ${scriptArgs.join(' ')}`
let scriptOptions = { const scriptOptions = {
encoding: 'UTF-8' encoding: 'UTF-8'
} }
if (cwd) { if (cwd) {
@ -171,21 +170,21 @@ function runScript (scriptName, scriptArgs, cwd) {
function uploadNodeShasums () { function uploadNodeShasums () {
console.log('Uploading Node SHASUMS file to S3.') console.log('Uploading Node SHASUMS file to S3.')
let scriptPath = path.join(__dirname, 'upload-node-checksums.py') const scriptPath = path.join(__dirname, 'upload-node-checksums.py')
runScript(scriptPath, ['-v', pkgVersion]) runScript(scriptPath, ['-v', pkgVersion])
console.log(`${pass} Done uploading Node SHASUMS file to S3.`) console.log(`${pass} Done uploading Node SHASUMS file to S3.`)
} }
function uploadIndexJson () { function uploadIndexJson () {
console.log('Uploading index.json to S3.') console.log('Uploading index.json to S3.')
let scriptPath = path.join(__dirname, 'upload-index-json.py') const scriptPath = path.join(__dirname, 'upload-index-json.py')
runScript(scriptPath, [pkgVersion]) runScript(scriptPath, [pkgVersion])
console.log(`${pass} Done uploading index.json to S3.`) console.log(`${pass} Done uploading index.json to S3.`)
} }
async function createReleaseShasums (release) { async function createReleaseShasums (release) {
let fileName = 'SHASUMS256.txt' const fileName = 'SHASUMS256.txt'
let existingAssets = release.assets.filter(asset => asset.name === fileName) const existingAssets = release.assets.filter(asset => asset.name === fileName)
if (existingAssets.length > 0) { if (existingAssets.length > 0) {
console.log(`${fileName} already exists on GitHub; deleting before creating new file.`) console.log(`${fileName} already exists on GitHub; deleting before creating new file.`)
await github.repos.deleteAsset({ await github.repos.deleteAsset({
@ -197,17 +196,17 @@ async function createReleaseShasums (release) {
}) })
} }
console.log(`Creating and uploading the release ${fileName}.`) console.log(`Creating and uploading the release ${fileName}.`)
let scriptPath = path.join(__dirname, 'merge-electron-checksums.py') const scriptPath = path.join(__dirname, 'merge-electron-checksums.py')
let checksums = runScript(scriptPath, ['-v', pkgVersion]) const checksums = runScript(scriptPath, ['-v', pkgVersion])
console.log(`${pass} Generated release SHASUMS.`) console.log(`${pass} Generated release SHASUMS.`)
let filePath = await saveShaSumFile(checksums, fileName) const filePath = await saveShaSumFile(checksums, fileName)
console.log(`${pass} Created ${fileName} file.`) console.log(`${pass} Created ${fileName} file.`)
await uploadShasumFile(filePath, fileName, release) await uploadShasumFile(filePath, fileName, release)
console.log(`${pass} Successfully uploaded ${fileName} to GitHub.`) console.log(`${pass} Successfully uploaded ${fileName} to GitHub.`)
} }
async function uploadShasumFile (filePath, fileName, release) { async function uploadShasumFile (filePath, fileName, release) {
let githubOpts = { const githubOpts = {
owner: 'electron', owner: 'electron',
repo: targetRepo, repo: targetRepo,
id: release.id, id: release.id,
@ -242,7 +241,7 @@ function saveShaSumFile (checksums, fileName) {
} }
async function publishRelease (release) { async function publishRelease (release) {
let githubOpts = { const githubOpts = {
owner: 'electron', owner: 'electron',
repo: targetRepo, repo: targetRepo,
id: release.id, id: release.id,
@ -264,7 +263,7 @@ async function makeRelease (releaseToValidate) {
console.log('Release to validate !=== true') console.log('Release to validate !=== true')
} }
console.log(`Validating release ${releaseToValidate}`) console.log(`Validating release ${releaseToValidate}`)
let release = await getDraftRelease(releaseToValidate) const release = await getDraftRelease(releaseToValidate)
await validateReleaseAssets(release, true) await validateReleaseAssets(release, true)
} else { } else {
checkVersion() checkVersion()
@ -295,8 +294,8 @@ async function makeTempDir () {
} }
async function verifyAssets (release) { async function verifyAssets (release) {
let downloadDir = await makeTempDir() const downloadDir = await makeTempDir()
let githubOpts = { const githubOpts = {
owner: 'electron', owner: 'electron',
repo: targetRepo, repo: targetRepo,
headers: { headers: {
@ -304,10 +303,10 @@ async function verifyAssets (release) {
} }
} }
console.log(`Downloading files from GitHub to verify shasums`) console.log(`Downloading files from GitHub to verify shasums`)
let shaSumFile = 'SHASUMS256.txt' const shaSumFile = 'SHASUMS256.txt'
let filesToCheck = await Promise.all(release.assets.map(async (asset) => { let filesToCheck = await Promise.all(release.assets.map(async (asset) => {
githubOpts.id = asset.id githubOpts.id = asset.id
let assetDetails = await github.repos.getAsset(githubOpts) const assetDetails = await github.repos.getAsset(githubOpts)
await downloadFiles(assetDetails.meta.location, downloadDir, false, asset.name) await downloadFiles(assetDetails.meta.location, downloadDir, false, asset.name)
return asset.name return asset.name
})).catch(err => { })).catch(err => {
@ -328,7 +327,7 @@ async function verifyAssets (release) {
function downloadFiles (urls, directory, quiet, targetName) { function downloadFiles (urls, directory, quiet, targetName) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let nuggetOpts = { const nuggetOpts = {
dir: directory dir: directory
} }
if (quiet) { if (quiet) {
@ -348,32 +347,32 @@ function downloadFiles (urls, directory, quiet, targetName) {
} }
async function verifyShasums (urls, isS3) { async function verifyShasums (urls, isS3) {
let fileSource = isS3 ? 'S3' : 'GitHub' const fileSource = isS3 ? 'S3' : 'GitHub'
console.log(`Downloading files from ${fileSource} to verify shasums`) console.log(`Downloading files from ${fileSource} to verify shasums`)
let downloadDir = await makeTempDir() const downloadDir = await makeTempDir()
let filesToCheck = [] let filesToCheck = []
try { try {
if (!isS3) { if (!isS3) {
await downloadFiles(urls, downloadDir) await downloadFiles(urls, downloadDir)
filesToCheck = urls.map(url => { filesToCheck = urls.map(url => {
let currentUrl = new URL(url) const currentUrl = new URL(url)
return path.basename(currentUrl.pathname) return path.basename(currentUrl.pathname)
}).filter(file => file.indexOf('SHASUMS') === -1) }).filter(file => file.indexOf('SHASUMS') === -1)
} else { } else {
const s3VersionPath = `/atom-shell/dist/${pkgVersion}/` const s3VersionPath = `/atom-shell/dist/${pkgVersion}/`
await Promise.all(urls.map(async (url) => { await Promise.all(urls.map(async (url) => {
let currentUrl = new URL(url) const currentUrl = new URL(url)
let dirname = path.dirname(currentUrl.pathname) const dirname = path.dirname(currentUrl.pathname)
let filename = path.basename(currentUrl.pathname) const filename = path.basename(currentUrl.pathname)
let s3VersionPathIdx = dirname.indexOf(s3VersionPath) const s3VersionPathIdx = dirname.indexOf(s3VersionPath)
if (s3VersionPathIdx === -1 || dirname === s3VersionPath) { if (s3VersionPathIdx === -1 || dirname === s3VersionPath) {
if (s3VersionPathIdx !== -1 && filename.indexof('SHASUMS') === -1) { if (s3VersionPathIdx !== -1 && filename.indexof('SHASUMS') === -1) {
filesToCheck.push(filename) filesToCheck.push(filename)
} }
await downloadFiles(url, downloadDir, true) await downloadFiles(url, downloadDir, true)
} else { } else {
let subDirectory = dirname.substr(s3VersionPathIdx + s3VersionPath.length) const subDirectory = dirname.substr(s3VersionPathIdx + s3VersionPath.length)
let fileDirectory = path.join(downloadDir, subDirectory) const fileDirectory = path.join(downloadDir, subDirectory)
try { try {
fs.statSync(fileDirectory) fs.statSync(fileDirectory)
} catch (err) { } catch (err) {
@ -418,8 +417,8 @@ async function verifyShasums (urls, isS3) {
async function validateChecksums (validationArgs) { async function validateChecksums (validationArgs) {
console.log(`Validating checksums for files from ${validationArgs.fileSource} ` + console.log(`Validating checksums for files from ${validationArgs.fileSource} ` +
`against ${validationArgs.shaSumFile}.`) `against ${validationArgs.shaSumFile}.`)
let shaSumFilePath = path.join(validationArgs.fileDirectory, validationArgs.shaSumFile) const shaSumFilePath = path.join(validationArgs.fileDirectory, validationArgs.shaSumFile)
let checker = new sumchecker.ChecksumValidator(validationArgs.algorithm, const checker = new sumchecker.ChecksumValidator(validationArgs.algorithm,
shaSumFilePath, validationArgs.checkerOpts) shaSumFilePath, validationArgs.checkerOpts)
await checker.validate(validationArgs.fileDirectory, validationArgs.filesToCheck) await checker.validate(validationArgs.fileDirectory, validationArgs.filesToCheck)
.catch(err => { .catch(err => {

View file

@ -8,14 +8,14 @@ if (process.argv.length < 6) {
console.log('Usage: upload-to-github filePath fileName releaseId') console.log('Usage: upload-to-github filePath fileName releaseId')
process.exit(1) process.exit(1)
} }
let filePath = process.argv[2] const filePath = process.argv[2]
let fileName = process.argv[3] const fileName = process.argv[3]
let releaseId = process.argv[4] const releaseId = process.argv[4]
let releaseVersion = process.argv[5] const releaseVersion = process.argv[5]
const targetRepo = releaseVersion.indexOf('nightly') > 0 ? 'nightlies' : 'electron' const targetRepo = releaseVersion.indexOf('nightly') > 0 ? 'nightlies' : 'electron'
let githubOpts = { const githubOpts = {
owner: 'electron', owner: 'electron',
repo: targetRepo, repo: targetRepo,
id: releaseId, id: releaseId,
@ -34,7 +34,7 @@ function uploadToGitHub () {
console.log(`Error uploading ${fileName} to GitHub, will retry. Error was:`, err) console.log(`Error uploading ${fileName} to GitHub, will retry. Error was:`, err)
retry++ retry++
github.repos.getRelease(githubOpts).then(release => { github.repos.getRelease(githubOpts).then(release => {
let existingAssets = release.data.assets.filter(asset => asset.name === fileName) const existingAssets = release.data.assets.filter(asset => asset.name === fileName)
if (existingAssets.length > 0) { if (existingAssets.length > 0) {
console.log(`${fileName} already exists; will delete before retrying upload.`) console.log(`${fileName} already exists; will delete before retrying upload.`)
github.repos.deleteAsset({ github.repos.deleteAsset({

View file

@ -116,12 +116,12 @@ describe('BrowserView module', () => {
w.setBrowserView(view) w.setBrowserView(view)
expect(view.id).to.not.be.null() expect(view.id).to.not.be.null()
let view2 = w.getBrowserView() const view2 = w.getBrowserView()
expect(view2.webContents.id).to.equal(view.webContents.id) expect(view2.webContents.id).to.equal(view.webContents.id)
}) })
it('returns null if none is set', () => { it('returns null if none is set', () => {
let view = w.getBrowserView() const view = w.getBrowserView()
expect(view).to.be.null() expect(view).to.be.null()
}) })
}) })
@ -145,7 +145,7 @@ describe('BrowserView module', () => {
w.setBrowserView(view) w.setBrowserView(view)
expect(view.id).to.not.be.null() expect(view.id).to.not.be.null()
let view2 = BrowserView.fromId(view.id) const view2 = BrowserView.fromId(view.id)
expect(view2.webContents.id).to.equal(view.webContents.id) expect(view2.webContents.id).to.equal(view.webContents.id)
}) })
}) })
@ -156,7 +156,7 @@ describe('BrowserView module', () => {
w.setBrowserView(view) w.setBrowserView(view)
expect(view.id).to.not.be.null() expect(view.id).to.not.be.null()
let view2 = BrowserView.fromWebContents(view.webContents) const view2 = BrowserView.fromWebContents(view.webContents)
expect(view2.webContents.id).to.equal(view.webContents.id) expect(view2.webContents.id).to.equal(view.webContents.id)
}) })
}) })

View file

@ -129,7 +129,7 @@ describe('BrowserWindow with affinity module', () => {
nodeIntegration: false nodeIntegration: false
}) })
]).then(args => { ]).then(args => {
let w1 = args[1] const w1 = args[1]
return Promise.all([ return Promise.all([
testNodeIntegration(false), testNodeIntegration(false),
w1, w1,
@ -169,7 +169,7 @@ describe('BrowserWindow with affinity module', () => {
nodeIntegration: true nodeIntegration: true
}) })
]).then(args => { ]).then(args => {
let w1 = args[1] const w1 = args[1]
return Promise.all([ return Promise.all([
testNodeIntegration(true), testNodeIntegration(true),
w1, w1,

View file

@ -75,7 +75,7 @@ describe('BrowserWindow module', () => {
if (data) body += data if (data) body += data
}) })
req.on('end', () => { req.on('end', () => {
let parsedData = qs.parse(body) const parsedData = qs.parse(body)
fs.readFile(filePath, (err, data) => { fs.readFile(filePath, (err, data) => {
if (err) return if (err) return
if (parsedData.username === 'test' && if (parsedData.username === 'test' &&
@ -187,7 +187,7 @@ describe('BrowserWindow module', () => {
function * genNavigationEvent () { function * genNavigationEvent () {
let eventOptions = null let eventOptions = null
while ((eventOptions = events.shift()) && events.length) { while ((eventOptions = events.shift()) && events.length) {
let w = new BrowserWindow({ show: false }) const w = new BrowserWindow({ show: false })
eventOptions.id = w.id eventOptions.id = w.id
eventOptions.responseEvent = responseEvent eventOptions.responseEvent = responseEvent
ipcRenderer.send('test-webcontents-navigation-observer', eventOptions) ipcRenderer.send('test-webcontents-navigation-observer', eventOptions)
@ -195,7 +195,7 @@ describe('BrowserWindow module', () => {
} }
} }
let gen = genNavigationEvent() const gen = genNavigationEvent()
ipcRenderer.on(responseEvent, () => { ipcRenderer.on(responseEvent, () => {
if (!gen.next().value) done() if (!gen.next().value) done()
}) })
@ -1399,7 +1399,7 @@ describe('BrowserWindow module', () => {
describe('"sandbox" option', () => { describe('"sandbox" option', () => {
function waitForEvents (emitter, events, callback) { function waitForEvents (emitter, events, callback) {
let count = events.length let count = events.length
for (let event of events) { for (const event of events) {
emitter.once(event, () => { emitter.once(event, () => {
if (!--count) callback() if (!--count) callback()
}) })
@ -1473,7 +1473,7 @@ describe('BrowserWindow module', () => {
preload: preload preload: preload
} }
}) })
let htmlPath = path.join(fixtures, 'api', 'sandbox.html?exit-event') const htmlPath = path.join(fixtures, 'api', 'sandbox.html?exit-event')
const pageUrl = 'file://' + htmlPath const pageUrl = 'file://' + htmlPath
w.loadURL(pageUrl) w.loadURL(pageUrl)
ipcMain.once('answer', function (event, url) { ipcMain.once('answer', function (event, url) {
@ -1496,7 +1496,7 @@ describe('BrowserWindow module', () => {
} }
}) })
ipcRenderer.send('set-web-preferences-on-next-new-window', w.webContents.id, 'preload', preload) ipcRenderer.send('set-web-preferences-on-next-new-window', w.webContents.id, 'preload', preload)
let htmlPath = path.join(fixtures, 'api', 'sandbox.html?window-open') const htmlPath = path.join(fixtures, 'api', 'sandbox.html?window-open')
const pageUrl = 'file://' + htmlPath const pageUrl = 'file://' + htmlPath
w.loadURL(pageUrl) w.loadURL(pageUrl)
w.webContents.once('new-window', (e, url, frameName, disposition, options) => { w.webContents.once('new-window', (e, url, frameName, disposition, options) => {
@ -2763,7 +2763,7 @@ describe('BrowserWindow module', () => {
// dynamically. // dynamically.
it('can be changed with hasShadow option', () => { it('can be changed with hasShadow option', () => {
w.destroy() w.destroy()
let hasShadow = process.platform !== 'darwin' const hasShadow = process.platform !== 'darwin'
w = new BrowserWindow({ show: false, hasShadow: hasShadow }) w = new BrowserWindow({ show: false, hasShadow: hasShadow })
assert.strictEqual(w.hasShadow(), hasShadow) assert.strictEqual(w.hasShadow(), hasShadow)
}) })
@ -2964,7 +2964,7 @@ describe('BrowserWindow module', () => {
c.close() c.close()
}) })
it('disables parent window recursively', () => { it('disables parent window recursively', () => {
let c2 = new BrowserWindow({ show: false, parent: w, modal: true }) const c2 = new BrowserWindow({ show: false, parent: w, modal: true })
c.show() c.show()
assert.strictEqual(w.isEnabled(), false) assert.strictEqual(w.isEnabled(), false)
c2.show() c2.show()
@ -3435,7 +3435,7 @@ describe('BrowserWindow module', () => {
it('creates offscreen window with correct size', (done) => { it('creates offscreen window with correct size', (done) => {
w.webContents.once('paint', function (event, rect, data) { w.webContents.once('paint', function (event, rect, data) {
assert.notStrictEqual(data.length, 0) assert.notStrictEqual(data.length, 0)
let size = data.getSize() const size = data.getSize()
assertWithinDelta(size.width, 100, 2, 'width') assertWithinDelta(size.width, 100, 2, 'width')
assertWithinDelta(size.height, 100, 2, 'height') assertWithinDelta(size.height, 100, 2, 'height')
done() done()
@ -3450,7 +3450,7 @@ describe('BrowserWindow module', () => {
}) })
it('is false for regular window', () => { it('is false for regular window', () => {
let c = new BrowserWindow({ show: false }) const c = new BrowserWindow({ show: false })
assert.strictEqual(c.webContents.isOffscreen(), false) assert.strictEqual(c.webContents.isOffscreen(), false)
c.destroy() c.destroy()
}) })

View file

@ -412,7 +412,7 @@ const waitForCrashReport = () => {
const startServer = ({ callback, processType, done }) => { const startServer = ({ callback, processType, done }) => {
let called = false let called = false
let server = http.createServer((req, res) => { const server = http.createServer((req, res) => {
const form = new multiparty.Form() const form = new multiparty.Form()
form.parse(req, (error, fields) => { form.parse(req, (error, fields) => {
if (error) throw error if (error) throw error

View file

@ -71,7 +71,7 @@ describe('deprecations', () => {
deprecations.setHandler(m => { msg = m }) deprecations.setHandler(m => { msg = m })
const prop = 'itMustGo' const prop = 'itMustGo'
let o = { [prop]: 0 } const o = { [prop]: 0 }
deprecate.removeProperty(o, prop) deprecate.removeProperty(o, prop)
@ -88,7 +88,7 @@ describe('deprecations', () => {
const key = 'foo' const key = 'foo'
const val = 'bar' const val = 'bar'
let o = { [key]: val } const o = { [key]: val }
deprecate.removeProperty(o, key) deprecate.removeProperty(o, key)
for (let i = 0; i < 3; ++i) { for (let i = 0; i < 3; ++i) {
@ -104,7 +104,7 @@ describe('deprecations', () => {
const oldProp = 'dingyOldName' const oldProp = 'dingyOldName'
const newProp = 'shinyNewName' const newProp = 'shinyNewName'
let o = { [oldProp]: 0 } const o = { [oldProp]: 0 }
deprecate.renameProperty(o, oldProp, newProp) deprecate.renameProperty(o, oldProp, newProp)
expect(msg).to.be.a('string') expect(msg).to.be.a('string')

View file

@ -49,10 +49,10 @@ describe('MenuItems', () => {
}) })
describe('MenuItem group properties', () => { describe('MenuItem group properties', () => {
let template = [] const template = []
const findRadioGroups = (template) => { const findRadioGroups = (template) => {
let groups = [] const groups = []
let cur = null let cur = null
for (let i = 0; i <= template.length; i++) { for (let i = 0; i <= template.length; i++) {
if (cur && ((i === template.length) || (template[i].type !== 'radio'))) { if (cur && ((i === template.length) || (template[i].type !== 'radio'))) {
@ -68,7 +68,7 @@ describe('MenuItems', () => {
// returns array of checked menuitems in [begin,end) // returns array of checked menuitems in [begin,end)
const findChecked = (menuItems, begin, end) => { const findChecked = (menuItems, begin, end) => {
let checked = [] const checked = []
for (let i = begin; i < end; i++) { for (let i = begin; i < end; i++) {
if (menuItems[i].checked) checked.push(i) if (menuItems[i].checked) checked.push(i)
} }
@ -107,7 +107,7 @@ describe('MenuItems', () => {
it('should assign groupId automatically', () => { it('should assign groupId automatically', () => {
const menu = Menu.buildFromTemplate(template) const menu = Menu.buildFromTemplate(template)
let usedGroupIds = new Set() const usedGroupIds = new Set()
const groups = findRadioGroups(template) const groups = findRadioGroups(template)
groups.forEach(g => { groups.forEach(g => {
const groupId = menu.items[g.begin].groupId const groupId = menu.items[g.begin].groupId
@ -143,7 +143,7 @@ describe('MenuItems', () => {
describe('MenuItem role execution', () => { describe('MenuItem role execution', () => {
it('does not try to execute roles without a valid role property', () => { it('does not try to execute roles without a valid role property', () => {
let win = new BrowserWindow({ show: false, width: 200, height: 200 }) let win = new BrowserWindow({ show: false, width: 200, height: 200 })
let item = new MenuItem({ role: 'asdfghjkl' }) const item = new MenuItem({ role: 'asdfghjkl' })
const canExecute = roles.execute(item.role, win, win.webContents) const canExecute = roles.execute(item.role, win, win.webContents)
expect(canExecute).to.be.false() expect(canExecute).to.be.false()
@ -153,7 +153,7 @@ describe('MenuItems', () => {
it('executes roles with native role functions', () => { it('executes roles with native role functions', () => {
let win = new BrowserWindow({ show: false, width: 200, height: 200 }) let win = new BrowserWindow({ show: false, width: 200, height: 200 })
let item = new MenuItem({ role: 'reload' }) const item = new MenuItem({ role: 'reload' })
const canExecute = roles.execute(item.role, win, win.webContents) const canExecute = roles.execute(item.role, win, win.webContents)
expect(canExecute).to.be.true() expect(canExecute).to.be.true()
@ -163,7 +163,7 @@ describe('MenuItems', () => {
it('execute roles with non-native role functions', () => { it('execute roles with non-native role functions', () => {
let win = new BrowserWindow({ show: false, width: 200, height: 200 }) let win = new BrowserWindow({ show: false, width: 200, height: 200 })
let item = new MenuItem({ role: 'resetzoom' }) const item = new MenuItem({ role: 'resetzoom' })
const canExecute = roles.execute(item.role, win, win.webContents) const canExecute = roles.execute(item.role, win, win.webContents)
expect(canExecute).to.be.true() expect(canExecute).to.be.true()
@ -229,7 +229,7 @@ describe('MenuItems', () => {
'zoomout' 'zoomout'
] ]
for (let role in roleList) { for (const role in roleList) {
const item = new MenuItem({ role }) const item = new MenuItem({ role })
expect(item.getDefaultRoleAccelerator()).to.be.undefined() expect(item.getDefaultRoleAccelerator()).to.be.undefined()
} }
@ -258,7 +258,7 @@ describe('MenuItems', () => {
'zoomout': 'Zoom Out' 'zoomout': 'Zoom Out'
} }
for (let role in roleList) { for (const role in roleList) {
const item = new MenuItem({ role }) const item = new MenuItem({ role })
expect(item.label).to.equal(roleList[role]) expect(item.label).to.equal(roleList[role])
} }
@ -287,7 +287,7 @@ describe('MenuItems', () => {
'zoomout': 'CommandOrControl+-' 'zoomout': 'CommandOrControl+-'
} }
for (let role in roleList) { for (const role in roleList) {
const item = new MenuItem({ role }) const item = new MenuItem({ role })
expect(item.getDefaultRoleAccelerator()).to.equal(roleList[role]) expect(item.getDefaultRoleAccelerator()).to.equal(roleList[role])
} }

View file

@ -97,7 +97,7 @@ describe('netLog module', () => {
return return
} }
let appProcess = ChildProcess.spawn(remote.process.execPath, const appProcess = ChildProcess.spawn(remote.process.execPath,
[appPath, `--log-net-log=${dumpFile}`], { [appPath, `--log-net-log=${dumpFile}`], {
env: { env: {
TEST_REQUEST_URL: server.url TEST_REQUEST_URL: server.url
@ -116,7 +116,7 @@ describe('netLog module', () => {
return return
} }
let appProcess = ChildProcess.spawn(remote.process.execPath, const appProcess = ChildProcess.spawn(remote.process.execPath,
[appPath, `--log-net-log=${dumpFile}`], { [appPath, `--log-net-log=${dumpFile}`], {
env: { env: {
TEST_REQUEST_URL: server.url, TEST_REQUEST_URL: server.url,
@ -142,7 +142,7 @@ describe('netLog module', () => {
return return
} }
let appProcess = ChildProcess.spawn(remote.process.execPath, const appProcess = ChildProcess.spawn(remote.process.execPath,
[appPath], { [appPath], {
env: { env: {
TEST_REQUEST_URL: server.url, TEST_REQUEST_URL: server.url,

View file

@ -12,7 +12,7 @@ const { session } = remote
function randomBuffer (size, start, end) { function randomBuffer (size, start, end) {
start = start || 0 start = start || 0
end = end || 255 end = end || 255
let range = 1 + end - start const range = 1 + end - start
const buffer = Buffer.allocUnsafe(size) const buffer = Buffer.allocUnsafe(size)
for (let i = 0; i < size; ++i) { for (let i = 0; i < size; ++i) {
buffer[i] = start + Math.floor(Math.random() * range) buffer[i] = start + Math.floor(Math.random() * range)
@ -21,7 +21,7 @@ function randomBuffer (size, start, end) {
} }
function randomString (length) { function randomString (length) {
let buffer = randomBuffer(length, '0'.charCodeAt(0), 'z'.charCodeAt(0)) const buffer = randomBuffer(length, '0'.charCodeAt(0), 'z'.charCodeAt(0))
return buffer.toString() return buffer.toString()
} }
@ -209,8 +209,8 @@ describe('net module', () => {
let chunkIndex = 0 let chunkIndex = 0
const chunkCount = 100 const chunkCount = 100
let sentChunks = [] const sentChunks = []
let receivedChunks = [] const receivedChunks = []
urlRequest.on('response', (response) => { urlRequest.on('response', (response) => {
assert.strictEqual(response.statusCode, 200) assert.strictEqual(response.statusCode, 200)
response.pause() response.pause()
@ -218,8 +218,8 @@ describe('net module', () => {
receivedChunks.push(chunk) receivedChunks.push(chunk)
}) })
response.on('end', () => { response.on('end', () => {
let sentData = Buffer.concat(sentChunks) const sentData = Buffer.concat(sentChunks)
let receivedData = Buffer.concat(receivedChunks) const receivedData = Buffer.concat(receivedChunks)
assert.strictEqual(sentData.toString(), receivedData.toString()) assert.strictEqual(sentData.toString(), receivedData.toString())
assert.strictEqual(chunkIndex, chunkCount) assert.strictEqual(chunkIndex, chunkCount)
done() done()
@ -285,14 +285,14 @@ describe('net module', () => {
requestResponseEventEmitted = true requestResponseEventEmitted = true
const statusCode = response.statusCode const statusCode = response.statusCode
assert.strictEqual(statusCode, 200) assert.strictEqual(statusCode, 200)
let buffers = [] const buffers = []
response.pause() response.pause()
response.on('data', (chunk) => { response.on('data', (chunk) => {
buffers.push(chunk) buffers.push(chunk)
responseDataEventEmitted = true responseDataEventEmitted = true
}) })
response.on('end', () => { response.on('end', () => {
let receivedBodyData = Buffer.concat(buffers) const receivedBodyData = Buffer.concat(buffers)
assert(receivedBodyData.toString() === bodyData) assert(receivedBodyData.toString() === bodyData)
responseEndEventEmitted = true responseEndEventEmitted = true
maybeDone(done) maybeDone(done)
@ -907,7 +907,7 @@ describe('net module', () => {
assert.fail('Request should not be intercepted by the default session') assert.fail('Request should not be intercepted by the default session')
}) })
let customSession = session.fromPartition(customPartitionName, { cache: false }) const customSession = session.fromPartition(customPartitionName, { cache: false })
let requestIsIntercepted = false let requestIsIntercepted = false
customSession.webRequest.onBeforeRequest((details, callback) => { customSession.webRequest.onBeforeRequest((details, callback) => {
if (details.url === `${server.url}${requestUrl}`) { if (details.url === `${server.url}${requestUrl}`) {
@ -1189,7 +1189,7 @@ describe('net module', () => {
assert.fail('Request should not be intercepted by the default session') assert.fail('Request should not be intercepted by the default session')
}) })
let customSession = session.fromPartition(customPartitionName, { const customSession = session.fromPartition(customPartitionName, {
cache: false cache: false
}) })
let requestIsIntercepted = false let requestIsIntercepted = false
@ -1260,7 +1260,7 @@ describe('net module', () => {
}) })
const serverUrl = url.parse(server.url) const serverUrl = url.parse(server.url)
let options = { const options = {
port: serverUrl.port, port: serverUrl.port,
hostname: '127.0.0.1', hostname: '127.0.0.1',
headers: {} headers: {}
@ -1312,7 +1312,7 @@ describe('net module', () => {
} }
}) })
let nodeRequest = http.request(`${server.url}${nodeRequestUrl}`) const nodeRequest = http.request(`${server.url}${nodeRequestUrl}`)
nodeRequest.on('response', (nodeResponse) => { nodeRequest.on('response', (nodeResponse) => {
const netRequest = net.request(`${server.url}${netRequestUrl}`) const netRequest = net.request(`${server.url}${netRequestUrl}`)
netRequest.on('response', (netResponse) => { netRequest.on('response', (netResponse) => {
@ -1470,7 +1470,7 @@ describe('net module', () => {
it('should not emit any event after close', (done) => { it('should not emit any event after close', (done) => {
const requestUrl = '/requestUrl' const requestUrl = '/requestUrl'
let bodyData = randomString(kOneKiloByte) const bodyData = randomString(kOneKiloByte)
server.on('request', (request, response) => { server.on('request', (request, response) => {
switch (request.url) { switch (request.url) {
case requestUrl: case requestUrl:

View file

@ -62,10 +62,10 @@ const skip = process.platform !== 'linux' ||
} }
function unmarshalDBusNotifyHints (dbusHints) { function unmarshalDBusNotifyHints (dbusHints) {
let o = {} const o = {}
for (let hint of dbusHints) { for (const hint of dbusHints) {
let key = hint[0] const key = hint[0]
let value = hint[1][1][0] const value = hint[1][1][0]
o[key] = value o[key] = value
} }
return o return o
@ -102,11 +102,11 @@ const skip = process.platform !== 'linux' ||
const calls = await getCalls() const calls = await getCalls()
expect(calls).to.be.an('array').of.lengthOf.at.least(1) expect(calls).to.be.an('array').of.lengthOf.at.least(1)
let lastCall = calls[calls.length - 1] const lastCall = calls[calls.length - 1]
let methodName = lastCall[1] const methodName = lastCall[1]
expect(methodName).to.equal('Notify') expect(methodName).to.equal('Notify')
let args = unmarshalDBusNotifyArgs(lastCall[2]) const args = unmarshalDBusNotifyArgs(lastCall[2])
expect(args).to.deep.equal({ expect(args).to.deep.equal({
app_name: appName, app_name: appName,
replaces_id: 0, replaces_id: 0,

View file

@ -1036,7 +1036,7 @@ describe('protocol module', () => {
}) })
it('can access files through the FileSystem API', (done) => { it('can access files through the FileSystem API', (done) => {
let filePath = path.join(__dirname, 'fixtures', 'pages', 'filesystem.html') const filePath = path.join(__dirname, 'fixtures', 'pages', 'filesystem.html')
const handler = (request, callback) => callback({ path: filePath }) const handler = (request, callback) => callback({ path: filePath })
protocol.registerFileProtocol(standardScheme, handler, (error) => { protocol.registerFileProtocol(standardScheme, handler, (error) => {
if (error) return done(error) if (error) return done(error)
@ -1047,7 +1047,7 @@ describe('protocol module', () => {
}) })
it('registers secure, when {secure: true}', (done) => { it('registers secure, when {secure: true}', (done) => {
let filePath = path.join(__dirname, 'fixtures', 'pages', 'cache-storage.html') const filePath = path.join(__dirname, 'fixtures', 'pages', 'cache-storage.html')
const handler = (request, callback) => callback({ path: filePath }) const handler = (request, callback) => callback({ path: filePath })
ipcMain.once('success', () => done()) ipcMain.once('success', () => done())
ipcMain.once('failure', (event, err) => done(err)) ipcMain.once('failure', (event, err) => done(err))

View file

@ -228,7 +228,7 @@ describe('remote module', () => {
}) })
it('is referenced by its members', () => { it('is referenced by its members', () => {
let stringify = remote.getGlobal('JSON').stringify const stringify = remote.getGlobal('JSON').stringify
global.gc() global.gc()
stringify({}) stringify({})
}) })
@ -451,13 +451,13 @@ describe('remote module', () => {
assert.strictEqual(derived.method(), 'method') assert.strictEqual(derived.method(), 'method')
assert.strictEqual(derived.readonly, 'readonly') assert.strictEqual(derived.readonly, 'readonly')
assert(!derived.hasOwnProperty('method')) assert(!derived.hasOwnProperty('method'))
let proto = Object.getPrototypeOf(derived) const proto = Object.getPrototypeOf(derived)
assert(!proto.hasOwnProperty('method')) assert(!proto.hasOwnProperty('method'))
assert(Object.getPrototypeOf(proto).hasOwnProperty('method')) assert(Object.getPrototypeOf(proto).hasOwnProperty('method'))
}) })
it('is referenced by methods in prototype chain', () => { it('is referenced by methods in prototype chain', () => {
let method = derived.method const method = derived.method
derived = null derived = null
global.gc() global.gc()
assert.strictEqual(method(), 'method') assert.strictEqual(method(), 'method')
@ -474,7 +474,7 @@ describe('remote module', () => {
}) })
it('throws custom errors from the main process', () => { it('throws custom errors from the main process', () => {
let err = new Error('error') const err = new Error('error')
err.cause = new Error('cause') err.cause = new Error('cause')
err.prop = 'error prop' err.prop = 'error prop'
try { try {

View file

@ -537,7 +537,7 @@ describe('session module', () => {
if (request.method === 'GET') { if (request.method === 'GET') {
callback({ data: content, mimeType: 'text/html' }) callback({ data: content, mimeType: 'text/html' })
} else if (request.method === 'POST') { } else if (request.method === 'POST') {
let uuid = request.uploadData[1].blobUUID const uuid = request.uploadData[1].blobUUID
assert(uuid) assert(uuid)
session.defaultSession.getBlobData(uuid, (result) => { session.defaultSession.getBlobData(uuid, (result) => {
assert.strictEqual(result.toString(), postData) assert.strictEqual(result.toString(), postData)
@ -648,7 +648,7 @@ describe('session module', () => {
const fixtures = path.join(__dirname, 'fixtures') const fixtures = path.join(__dirname, 'fixtures')
const downloadFilePath = path.join(fixtures, 'logo.png') const downloadFilePath = path.join(fixtures, 'logo.png')
const rangeServer = http.createServer((req, res) => { const rangeServer = http.createServer((req, res) => {
let options = { root: fixtures } const options = { root: fixtures }
send(req, req.url, options) send(req, req.url, options)
.on('error', (error) => { done(error) }).pipe(res) .on('error', (error) => { done(error) }).pipe(res)
}) })

View file

@ -11,7 +11,7 @@ describe('systemPreferences module', () => {
}) })
it('should return a non-empty string', () => { it('should return a non-empty string', () => {
let accentColor = systemPreferences.getAccentColor() const accentColor = systemPreferences.getAccentColor()
assert.notStrictEqual(accentColor, null) assert.notStrictEqual(accentColor, null)
assert(accentColor.length > 0) assert(accentColor.length > 0)
}) })

View file

@ -103,7 +103,7 @@ describe('webContents module', () => {
describe('setDevToolsWebContents() API', () => { describe('setDevToolsWebContents() API', () => {
it('sets arbitry webContents as devtools', (done) => { it('sets arbitry webContents as devtools', (done) => {
let devtools = new BrowserWindow({ show: false }) const devtools = new BrowserWindow({ show: false })
devtools.webContents.once('dom-ready', () => { devtools.webContents.once('dom-ready', () => {
assert.ok(devtools.getURL().startsWith('chrome-devtools://devtools')) assert.ok(devtools.getURL().startsWith('chrome-devtools://devtools'))
devtools.webContents.executeJavaScript('InspectorFrontendHost.constructor.name', (name) => { devtools.webContents.executeJavaScript('InspectorFrontendHost.constructor.name', (name) => {
@ -756,7 +756,7 @@ describe('webContents module', () => {
} }
} }
let gen = genNavigationEvent() const gen = genNavigationEvent()
ipcRenderer.on(responseEvent, () => { ipcRenderer.on(responseEvent, () => {
if (!gen.next().value) done() if (!gen.next().value) done()
}) })

View file

@ -34,7 +34,7 @@ describe('chromium feature', () => {
const appPath = path.join(__dirname, 'fixtures', 'api', 'locale-check') const appPath = path.join(__dirname, 'fixtures', 'api', 'locale-check')
const electronPath = remote.getGlobal('process').execPath const electronPath = remote.getGlobal('process').execPath
let output = '' let output = ''
let appProcess = ChildProcess.spawn(electronPath, [appPath, `--lang=${locale}`]) const appProcess = ChildProcess.spawn(electronPath, [appPath, `--lang=${locale}`])
appProcess.stdout.on('data', (data) => { output += data }) appProcess.stdout.on('data', (data) => { output += data })
appProcess.stdout.on('end', () => { appProcess.stdout.on('end', () => {
@ -175,7 +175,7 @@ describe('chromium feature', () => {
describe('navigator.languages', (done) => { describe('navigator.languages', (done) => {
it('should return the system locale only', () => { it('should return the system locale only', () => {
let appLocale = app.getLocale() const appLocale = app.getLocale()
assert.strictEqual(navigator.languages.length, 1) assert.strictEqual(navigator.languages.length, 1)
assert.strictEqual(navigator.languages[0], appLocale) assert.strictEqual(navigator.languages[0], appLocale)
}) })
@ -294,7 +294,7 @@ describe('chromium feature', () => {
}) })
it('accepts "nodeIntegration" as feature', (done) => { it('accepts "nodeIntegration" as feature', (done) => {
let b let b = null
listener = (event) => { listener = (event) => {
assert.strictEqual(event.data.isProcessGlobalUndefined, true) assert.strictEqual(event.data.isProcessGlobalUndefined, true)
b.close() b.close()
@ -305,7 +305,7 @@ describe('chromium feature', () => {
}) })
it('inherit options of parent window', (done) => { it('inherit options of parent window', (done) => {
let b let b = null
listener = (event) => { listener = (event) => {
const ref1 = remote.getCurrentWindow().getSize() const ref1 = remote.getCurrentWindow().getSize()
const width = ref1[0] const width = ref1[0]
@ -339,7 +339,7 @@ describe('chromium feature', () => {
} }
it('disables node integration when it is disabled on the parent window', (done) => { it('disables node integration when it is disabled on the parent window', (done) => {
let b let b = null
listener = (event) => { listener = (event) => {
assert.strictEqual(event.data.isProcessGlobalUndefined, true) assert.strictEqual(event.data.isProcessGlobalUndefined, true)
b.close() b.close()
@ -359,7 +359,7 @@ describe('chromium feature', () => {
}) })
it('disables webviewTag when node integration is disabled on the parent window', (done) => { it('disables webviewTag when node integration is disabled on the parent window', (done) => {
let b let b = null
listener = (event) => { listener = (event) => {
assert.strictEqual(event.data.isWebViewUndefined, true) assert.strictEqual(event.data.isWebViewUndefined, true)
b.close() b.close()
@ -380,7 +380,7 @@ describe('chromium feature', () => {
// TODO(codebytere): re-enable this test // TODO(codebytere): re-enable this test
xit('disables node integration when it is disabled on the parent window for chrome devtools URLs', (done) => { xit('disables node integration when it is disabled on the parent window for chrome devtools URLs', (done) => {
let b let b = null
app.once('web-contents-created', (event, contents) => { app.once('web-contents-created', (event, contents) => {
contents.once('did-finish-load', () => { contents.once('did-finish-load', () => {
contents.executeJavaScript('typeof process').then((typeofProcessGlobal) => { contents.executeJavaScript('typeof process').then((typeofProcessGlobal) => {
@ -394,7 +394,7 @@ describe('chromium feature', () => {
}) })
it('disables JavaScript when it is disabled on the parent window', (done) => { it('disables JavaScript when it is disabled on the parent window', (done) => {
let b let b = null
app.once('web-contents-created', (event, contents) => { app.once('web-contents-created', (event, contents) => {
contents.once('did-finish-load', () => { contents.once('did-finish-load', () => {
app.once('browser-window-created', (event, window) => { app.once('browser-window-created', (event, window) => {
@ -419,7 +419,7 @@ describe('chromium feature', () => {
}) })
it('disables the <webview> tag when it is disabled on the parent window', (done) => { it('disables the <webview> tag when it is disabled on the parent window', (done) => {
let b let b = null
listener = (event) => { listener = (event) => {
assert.strictEqual(event.data.isWebViewGlobalUndefined, true) assert.strictEqual(event.data.isWebViewGlobalUndefined, true)
b.close() b.close()
@ -439,7 +439,7 @@ describe('chromium feature', () => {
}) })
it('does not override child options', (done) => { it('does not override child options', (done) => {
let b let b = null
const size = { const size = {
width: 350, width: 350,
height: 450 height: 450
@ -476,7 +476,7 @@ describe('chromium feature', () => {
}) })
it('defines a window.location getter', (done) => { it('defines a window.location getter', (done) => {
let b let b = null
let targetURL let targetURL
if (process.platform === 'win32') { if (process.platform === 'win32') {
targetURL = `file:///${fixtures.replace(/\\/g, '/')}/pages/base-page.html` targetURL = `file:///${fixtures.replace(/\\/g, '/')}/pages/base-page.html`
@ -494,7 +494,7 @@ describe('chromium feature', () => {
}) })
it('defines a window.location setter', (done) => { it('defines a window.location setter', (done) => {
let b let b = null
app.once('browser-window-created', (event, { webContents }) => { app.once('browser-window-created', (event, { webContents }) => {
webContents.once('did-finish-load', () => { webContents.once('did-finish-load', () => {
// When it loads, redirect // When it loads, redirect
@ -510,14 +510,14 @@ describe('chromium feature', () => {
}) })
it('open a blank page when no URL is specified', (done) => { it('open a blank page when no URL is specified', (done) => {
let b let b = null
app.once('browser-window-created', (event, { webContents }) => { app.once('browser-window-created', (event, { webContents }) => {
webContents.once('did-finish-load', () => { webContents.once('did-finish-load', () => {
const { location } = b const { location } = b
b.close() b.close()
assert.strictEqual(location, 'about:blank') assert.strictEqual(location, 'about:blank')
let c let c = null
app.once('browser-window-created', (event, { webContents }) => { app.once('browser-window-created', (event, { webContents }) => {
webContents.once('did-finish-load', () => { webContents.once('did-finish-load', () => {
const { location } = c const { location } = c
@ -543,7 +543,7 @@ describe('chromium feature', () => {
}) })
it('sets the window title to the specified frameName', (done) => { it('sets the window title to the specified frameName', (done) => {
let b let b = null
app.once('browser-window-created', (event, createdWindow) => { app.once('browser-window-created', (event, createdWindow) => {
assert.strictEqual(createdWindow.getTitle(), 'hello') assert.strictEqual(createdWindow.getTitle(), 'hello')
b.close() b.close()
@ -553,7 +553,7 @@ describe('chromium feature', () => {
}) })
it('does not throw an exception when the frameName is a built-in object property', (done) => { it('does not throw an exception when the frameName is a built-in object property', (done) => {
let b let b = null
app.once('browser-window-created', (event, createdWindow) => { app.once('browser-window-created', (event, createdWindow) => {
assert.strictEqual(createdWindow.getTitle(), '__proto__') assert.strictEqual(createdWindow.getTitle(), '__proto__')
b.close() b.close()
@ -563,7 +563,7 @@ describe('chromium feature', () => {
}) })
it('does not throw an exception when the features include webPreferences', () => { it('does not throw an exception when the features include webPreferences', () => {
let b let b = null
assert.doesNotThrow(() => { assert.doesNotThrow(() => {
b = window.open('', '', 'webPreferences=') b = window.open('', '', 'webPreferences=')
}) })
@ -572,7 +572,7 @@ describe('chromium feature', () => {
}) })
describe('window.opener', () => { describe('window.opener', () => {
let url = `file://${fixtures}/pages/window-opener.html` const url = `file://${fixtures}/pages/window-opener.html`
it('is null for main window', (done) => { it('is null for main window', (done) => {
w = new BrowserWindow({ show: false }) w = new BrowserWindow({ show: false })
w.webContents.once('ipc-message', (event, args) => { w.webContents.once('ipc-message', (event, args) => {
@ -583,7 +583,7 @@ describe('chromium feature', () => {
}) })
it('is not null for window opened by window.open', (done) => { it('is not null for window opened by window.open', (done) => {
let b let b = null
listener = (event) => { listener = (event) => {
assert.strictEqual(event.data, 'object') assert.strictEqual(event.data, 'object')
b.close() b.close()
@ -596,7 +596,7 @@ describe('chromium feature', () => {
describe('window.opener access from BrowserWindow', () => { describe('window.opener access from BrowserWindow', () => {
const scheme = 'other' const scheme = 'other'
let url = `${scheme}://${fixtures}/pages/window-opener-location.html` const url = `${scheme}://${fixtures}/pages/window-opener-location.html`
let w = null let w = null
before((done) => { before((done) => {
@ -720,7 +720,7 @@ describe('chromium feature', () => {
describe('window.postMessage', () => { describe('window.postMessage', () => {
it('sets the source and origin correctly', (done) => { it('sets the source and origin correctly', (done) => {
let b let b = null
listener = (event) => { listener = (event) => {
window.removeEventListener('message', listener) window.removeEventListener('message', listener)
b.close() b.close()
@ -751,7 +751,7 @@ describe('chromium feature', () => {
describe('window.opener.postMessage', () => { describe('window.opener.postMessage', () => {
it('sets source and origin correctly', (done) => { it('sets source and origin correctly', (done) => {
let b let b = null
listener = (event) => { listener = (event) => {
window.removeEventListener('message', listener) window.removeEventListener('message', listener)
b.close() b.close()
@ -803,7 +803,7 @@ describe('chromium feature', () => {
}) })
it('delivers messages that match the origin', (done) => { it('delivers messages that match the origin', (done) => {
let b let b = null
listener = (event) => { listener = (event) => {
window.removeEventListener('message', listener) window.removeEventListener('message', listener)
b.close() b.close()
@ -856,7 +856,7 @@ describe('chromium feature', () => {
}) })
it('Worker has no node integration by default', (done) => { it('Worker has no node integration by default', (done) => {
let worker = new Worker('../fixtures/workers/worker_node.js') const worker = new Worker('../fixtures/workers/worker_node.js')
worker.onmessage = (event) => { worker.onmessage = (event) => {
assert.strictEqual(event.data, 'undefined undefined undefined undefined') assert.strictEqual(event.data, 'undefined undefined undefined undefined')
worker.terminate() worker.terminate()
@ -865,7 +865,7 @@ describe('chromium feature', () => {
}) })
it('Worker has node integration with nodeIntegrationInWorker', (done) => { it('Worker has node integration with nodeIntegrationInWorker', (done) => {
let webview = new WebView() const webview = new WebView()
webview.addEventListener('ipc-message', (e) => { webview.addEventListener('ipc-message', (e) => {
assert.strictEqual(e.channel, 'object function object function') assert.strictEqual(e.channel, 'object function object function')
webview.remove() webview.remove()
@ -887,7 +887,7 @@ describe('chromium feature', () => {
}) })
it('SharedWorker has no node integration by default', (done) => { it('SharedWorker has no node integration by default', (done) => {
let worker = new SharedWorker('../fixtures/workers/shared_worker_node.js') const worker = new SharedWorker('../fixtures/workers/shared_worker_node.js')
worker.port.onmessage = (event) => { worker.port.onmessage = (event) => {
assert.strictEqual(event.data, 'undefined undefined undefined undefined') assert.strictEqual(event.data, 'undefined undefined undefined undefined')
done() done()
@ -895,7 +895,7 @@ describe('chromium feature', () => {
}) })
it('SharedWorker has node integration with nodeIntegrationInWorker', (done) => { it('SharedWorker has node integration with nodeIntegrationInWorker', (done) => {
let webview = new WebView() const webview = new WebView()
webview.addEventListener('console-message', (e) => { webview.addEventListener('console-message', (e) => {
console.log(e) console.log(e)
}) })
@ -944,7 +944,7 @@ describe('chromium feature', () => {
let contents = null let contents = null
before((done) => { before((done) => {
const handler = (request, callback) => { const handler = (request, callback) => {
let parsedUrl = url.parse(request.url) const parsedUrl = url.parse(request.url)
let filename let filename
switch (parsedUrl.pathname) { switch (parsedUrl.pathname) {
case '/localStorage' : filename = 'local_storage.html'; break case '/localStorage' : filename = 'local_storage.html'; break

View file

@ -15,7 +15,7 @@ let currentWindowSandboxed = false
app.once('ready', () => { app.once('ready', () => {
function testWindow (isSandboxed, callback) { function testWindow (isSandboxed, callback) {
currentWindowSandboxed = isSandboxed currentWindowSandboxed = isSandboxed
let currentWindow = new BrowserWindow({ const currentWindow = new BrowserWindow({
show: false, show: false,
webPreferences: { webPreferences: {
preload: path.join(__dirname, 'electron-app-mixed-sandbox-preload.js'), preload: path.join(__dirname, 'electron-app-mixed-sandbox-preload.js'),

View file

@ -8,7 +8,7 @@ process.on('uncaughtException', () => {
}) })
app.once('ready', () => { app.once('ready', () => {
let lastArg = process.argv[process.argv.length - 1] const lastArg = process.argv[process.argv.length - 1]
const client = net.connect(socketPath) const client = net.connect(socketPath)
client.once('connect', () => { client.once('connect', () => {
client.end(String(lastArg === '--second')) client.end(String(lastArg === '--second'))

View file

@ -1,5 +1,5 @@
self.onconnect = function (event) { self.onconnect = function (event) {
let port = event.ports[0] const port = event.ports[0]
port.start() port.start()
port.postMessage([typeof process, typeof setImmediate, typeof global, typeof Buffer].join(' ')) port.postMessage([typeof process, typeof setImmediate, typeof global, typeof Buffer].join(' '))
} }

View file

@ -131,7 +131,7 @@ describe('modules support', () => {
describe('when the path is outside the resources path', () => { describe('when the path is outside the resources path', () => {
it('includes paths outside of the resources path', () => { it('includes paths outside of the resources path', () => {
let modulePath = path.resolve('/foo') const modulePath = path.resolve('/foo')
assert.deepStrictEqual(Module._nodeModulePaths(modulePath), [ assert.deepStrictEqual(Module._nodeModulePaths(modulePath), [
path.join(modulePath, 'node_modules'), path.join(modulePath, 'node_modules'),
path.resolve('/node_modules') path.resolve('/node_modules')

View file

@ -331,10 +331,10 @@ describe('node feature', () => {
const key = 'q90K9yBqhWZnAMCMTOJfPQ==' const key = 'q90K9yBqhWZnAMCMTOJfPQ=='
const cipherText = '{"error_code":114,"error_message":"Tham số không hợp lệ","data":null}' const cipherText = '{"error_code":114,"error_message":"Tham số không hợp lệ","data":null}'
for (let i = 0; i < 10000; ++i) { for (let i = 0; i < 10000; ++i) {
let iv = Buffer.from('0'.repeat(32), 'hex') const iv = Buffer.from('0'.repeat(32), 'hex')
let input = Buffer.from(data, 'base64') const input = Buffer.from(data, 'base64')
let decipher = crypto.createDecipheriv('aes-128-cbc', Buffer.from(key, 'base64'), iv) const decipher = crypto.createDecipheriv('aes-128-cbc', Buffer.from(key, 'base64'), iv)
let result = Buffer.concat([decipher.update(input), decipher.final()]).toString('utf8') const result = Buffer.concat([decipher.update(input), decipher.final()]).toString('utf8')
assert.strictEqual(cipherText, result) assert.strictEqual(cipherText, result)
} }
}) })

View file

@ -56,7 +56,7 @@ if (process.platform !== 'darwin') {
// Write output to file if OUTPUT_TO_FILE is defined. // Write output to file if OUTPUT_TO_FILE is defined.
const outputToFile = process.env.OUTPUT_TO_FILE const outputToFile = process.env.OUTPUT_TO_FILE
const print = function (_, args) { const print = function (_, args) {
let output = util.format.apply(null, args) const output = util.format.apply(null, args)
if (outputToFile) { if (outputToFile) {
fs.appendFileSync(outputToFile, output + '\n') fs.appendFileSync(outputToFile, output + '\n')
} else { } else {
@ -398,7 +398,7 @@ ipcMain.on('test-webcontents-navigation-observer', (event, options) => {
}) })
ipcMain.on('test-browserwindow-destroy', (event, testOptions) => { ipcMain.on('test-browserwindow-destroy', (event, testOptions) => {
let focusListener = (event, win) => win.id const focusListener = (event, win) => win.id
app.on('browser-window-focus', focusListener) app.on('browser-window-focus', focusListener)
const windowCount = 3 const windowCount = 3
const windowOptions = { const windowOptions = {

View file

@ -987,7 +987,7 @@ describe('<webview> tag', function () {
describe('found-in-page event', () => { describe('found-in-page event', () => {
it('emits when a request is made', (done) => { it('emits when a request is made', (done) => {
let requestId = null let requestId = null
let activeMatchOrdinal = [] const activeMatchOrdinal = []
const listener = (e) => { const listener = (e) => {
assert.strictEqual(e.result.requestId, requestId) assert.strictEqual(e.result.requestId, requestId)
assert.strictEqual(e.result.matches, 3) assert.strictEqual(e.result.matches, 3)
@ -1157,7 +1157,7 @@ describe('<webview> tag', function () {
it('inherits the parent window visibility state and receives visibilitychange events', async () => { it('inherits the parent window visibility state and receives visibilitychange events', async () => {
const w = await openTheWindow({ show: false }) const w = await openTheWindow({ show: false })
w.loadFile(path.join(fixtures, 'pages', 'webview-visibilitychange.html')) w.loadFile(path.join(fixtures, 'pages', 'webview-visibilitychange.html'))
let [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong') const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong')
assert.strictEqual(visibilityState, 'hidden') assert.strictEqual(visibilityState, 'hidden')
assert.strictEqual(hidden, true) assert.strictEqual(hidden, true)