Convert var's to let's

This patch:
- converts all var's to let's throughout the codebase
- enforces the let's over var's via the eslint rule
This commit is contained in:
Andrey Lushnikov 2017-06-22 13:38:10 -07:00
parent 78e879925f
commit 819fa355f4
20 changed files with 344 additions and 345 deletions

View File

@ -49,6 +49,7 @@ module.exports = {
"arrow-parens": [2, "as-needed"], "arrow-parens": [2, "as-needed"],
// anti-patterns // anti-patterns
"no-var": 2,
"no-with": 2, "no-with": 2,
"no-multi-str": 2, "no-multi-str": 2,
"no-caller": 2, "no-caller": 2,
@ -99,13 +100,11 @@ module.exports = {
"no-mixed-spaces-and-tabs": 2, "no-mixed-spaces-and-tabs": 2,
"no-trailing-spaces": 2, "no-trailing-spaces": 2,
"linebreak-style": [ 2, "unix" ], "linebreak-style": [ 2, "unix" ],
"indent": [2, 2, { "SwitchCase": 1, "CallExpression": {"arguments": 2}, "MemberExpression": 2 }],
/** /**
* Disabled, aspirational rules * Disabled, aspirational rules
*/ */
"indent": [2, 2, { "SwitchCase": 1, "CallExpression": {"arguments": 2}, "MemberExpression": 2 }],
// brace-style is disabled, as eslint cannot enforce 1tbs as default, but allman for functions // brace-style is disabled, as eslint cannot enforce 1tbs as default, but allman for functions
"brace-style": [0, "allman", { "allowSingleLine": true }], "brace-style": [0, "allman", { "allowSingleLine": true }],

View File

@ -14,9 +14,9 @@
* limitations under the License. * limitations under the License.
*/ */
var Downloader = require('./utils/ChromiumDownloader'); let Downloader = require('./utils/ChromiumDownloader');
var revision = require('./package').puppeteer.chromium_revision; let revision = require('./package').puppeteer.chromium_revision;
var ProgressBar = require('progress'); let ProgressBar = require('progress');
// Do nothing if the revision is already downloaded. // Do nothing if the revision is already downloaded.
if (Downloader.revisionInfo(Downloader.currentPlatform(), revision)) if (Downloader.revisionInfo(Downloader.currentPlatform(), revision))
@ -27,7 +27,7 @@ Downloader.downloadRevision(Downloader.currentPlatform(), revision, onProgress)
console.error('Download failed: ' + error.message); console.error('Download failed: ' + error.message);
}); });
var progressBar = null; let progressBar = null;
function onProgress(bytesTotal, delta) { function onProgress(bytesTotal, delta) {
if (!progressBar) { if (!progressBar) {
progressBar = new ProgressBar(`Downloading Chromium - ${toMegabytes(bytesTotal)} [:bar] :percent :etas `, { progressBar = new ProgressBar(`Downloading Chromium - ${toMegabytes(bytesTotal)} [:bar] :percent :etas `, {
@ -41,7 +41,7 @@ function onProgress(bytesTotal, delta) {
} }
function toMegabytes(bytes) { function toMegabytes(bytes) {
var mb = bytes / 1024 / 1024; let mb = bytes / 1024 / 1024;
return (Math.round(mb * 10) / 10) + ' Mb'; return (Math.round(mb * 10) / 10) + ' Mb';
} }

View File

@ -14,18 +14,18 @@
* limitations under the License. * limitations under the License.
*/ */
var http = require('http'); let http = require('http');
var path = require('path'); let path = require('path');
var removeRecursive = require('rimraf').sync; let removeRecursive = require('rimraf').sync;
var Page = require('./Page'); let Page = require('./Page');
var childProcess = require('child_process'); let childProcess = require('child_process');
var Downloader = require('../utils/ChromiumDownloader'); let Downloader = require('../utils/ChromiumDownloader');
var Connection = require('./Connection'); let Connection = require('./Connection');
var CHROME_PROFILE_PATH = path.resolve(__dirname, '..', '.dev_profile'); let CHROME_PROFILE_PATH = path.resolve(__dirname, '..', '.dev_profile');
var browserId = 0; let browserId = 0;
var DEFAULT_ARGS = [ let DEFAULT_ARGS = [
'--disable-background-timer-throttling', '--disable-background-timer-throttling',
'--no-first-run', '--no-first-run',
]; ];
@ -54,8 +54,8 @@ class Browser {
if (typeof options.executablePath === 'string') { if (typeof options.executablePath === 'string') {
this._chromeExecutable = options.executablePath; this._chromeExecutable = options.executablePath;
} else { } else {
var chromiumRevision = require('../package.json').puppeteer.chromium_revision; let chromiumRevision = require('../package.json').puppeteer.chromium_revision;
var revisionInfo = Downloader.revisionInfo(Downloader.currentPlatform(), chromiumRevision); let revisionInfo = Downloader.revisionInfo(Downloader.currentPlatform(), chromiumRevision);
console.assert(revisionInfo, 'Chromium revision is not downloaded. Run npm install'); console.assert(revisionInfo, 'Chromium revision is not downloaded. Run npm install');
this._chromeExecutable = revisionInfo.executablePath; this._chromeExecutable = revisionInfo.executablePath;
} }
@ -72,8 +72,8 @@ class Browser {
await this._ensureChromeIsRunning(); await this._ensureChromeIsRunning();
if (!this._chromeProcess || this._terminated) if (!this._chromeProcess || this._terminated)
throw new Error('ERROR: this chrome instance is not alive any more!'); throw new Error('ERROR: this chrome instance is not alive any more!');
var client = await Connection.create(this._remoteDebuggingPort); let client = await Connection.create(this._remoteDebuggingPort);
var page = await Page.create(client); let page = await Page.create(client);
return page; return page;
} }
@ -91,7 +91,7 @@ class Browser {
*/ */
async version() { async version() {
await this._ensureChromeIsRunning(); await this._ensureChromeIsRunning();
var version = await Connection.version(this._remoteDebuggingPort); let version = await Connection.version(this._remoteDebuggingPort);
return version.Browser; return version.Browser;
} }
@ -99,7 +99,7 @@ class Browser {
if (this._chromeProcess) if (this._chromeProcess)
return; return;
this._chromeProcess = childProcess.spawn(this._chromeExecutable, this._chromeArguments, {}); this._chromeProcess = childProcess.spawn(this._chromeExecutable, this._chromeArguments, {});
var stderr = ''; let stderr = '';
this._chromeProcess.stderr.on('data', data => stderr += data.toString('utf8')); this._chromeProcess.stderr.on('data', data => stderr += data.toString('utf8'));
// Cleanup as processes exit. // Cleanup as processes exit.
process.on('exit', () => this._chromeProcess.kill()); process.on('exit', () => this._chromeProcess.kill());
@ -123,20 +123,20 @@ class Browser {
module.exports = Browser; module.exports = Browser;
function waitForChromeResponsive(remoteDebuggingPort, shouldWaitCallback) { function waitForChromeResponsive(remoteDebuggingPort, shouldWaitCallback) {
var fulfill; let fulfill;
var promise = new Promise(x => fulfill = x); let promise = new Promise(x => fulfill = x);
var options = { let options = {
method: 'GET', method: 'GET',
host: 'localhost', host: 'localhost',
port: remoteDebuggingPort, port: remoteDebuggingPort,
path: '/json/list' path: '/json/list'
}; };
var probeTimeout = 100; let probeTimeout = 100;
sendRequest(); sendRequest();
return promise; return promise;
function sendRequest() { function sendRequest() {
var req = http.request(options, res => { let req = http.request(options, res => {
fulfill(); fulfill();
}); });
req.on('error', e => { req.on('error', e => {

View File

@ -14,9 +14,9 @@
* limitations under the License. * limitations under the License.
*/ */
var EventEmitter = require('events'); let EventEmitter = require('events');
var WebSocket = require('ws'); let WebSocket = require('ws');
var http = require('http'); let http = require('http');
const COMMAND_TIMEOUT = 10000; const COMMAND_TIMEOUT = 10000;
class Connection extends EventEmitter { class Connection extends EventEmitter {
@ -44,8 +44,8 @@ class Connection extends EventEmitter {
* @return {!Promise<?Object>} * @return {!Promise<?Object>}
*/ */
send(method, params = {}) { send(method, params = {}) {
var id = ++this._lastId; let id = ++this._lastId;
var message = JSON.stringify({id, method, params}); let message = JSON.stringify({id, method, params});
this._ws.send(message); this._ws.send(message);
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this._callbacks.set(id, {resolve, reject, method}); this._callbacks.set(id, {resolve, reject, method});
@ -56,9 +56,9 @@ class Connection extends EventEmitter {
* @param {string} message * @param {string} message
*/ */
_onMessage(message) { _onMessage(message) {
var object = JSON.parse(message); let object = JSON.parse(message);
if (object.id && this._callbacks.has(object.id)) { if (object.id && this._callbacks.has(object.id)) {
var callback = this._callbacks.get(object.id); let callback = this._callbacks.get(object.id);
this._callbacks.delete(object.id); this._callbacks.delete(object.id);
if (object.error) if (object.error)
callback.reject(new Error(`Protocol error (${callback.method}): ${object.error.message}`)); callback.reject(new Error(`Protocol error (${callback.method}): ${object.error.message}`));
@ -87,11 +87,11 @@ class Connection extends EventEmitter {
* @return {!Promise<!Connection>} * @return {!Promise<!Connection>}
*/ */
static async create(port) { static async create(port) {
var newTab = await runJsonCommand(port, 'new'); let newTab = await runJsonCommand(port, 'new');
var url = newTab.webSocketDebuggerUrl; let url = newTab.webSocketDebuggerUrl;
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
var ws = new WebSocket(url, { perMessageDeflate: false }); let ws = new WebSocket(url, { perMessageDeflate: false });
ws.on('open', () => resolve(new Connection(port, newTab.id, ws))); ws.on('open', () => resolve(new Connection(port, newTab.id, ws)));
ws.on('error', reject); ws.on('error', reject);
}); });
@ -112,17 +112,17 @@ class Connection extends EventEmitter {
* @return {!Promise<!Object>} * @return {!Promise<!Object>}
*/ */
function runJsonCommand(port, command) { function runJsonCommand(port, command) {
var request = http.get({ let request = http.get({
hostname: 'localhost', hostname: 'localhost',
port: port, port: port,
path: '/json/' + command path: '/json/' + command
}, onResponse); }, onResponse);
request.setTimeout(COMMAND_TIMEOUT, onTimeout); request.setTimeout(COMMAND_TIMEOUT, onTimeout);
var resolve, reject; let resolve, reject;
return new Promise((res, rej) => { resolve = res; reject = rej; }); return new Promise((res, rej) => { resolve = res; reject = rej; });
function onResponse(response) { function onResponse(response) {
var data = ''; let data = '';
response.on('data', chunk => data += chunk); response.on('data', chunk => data += chunk);
response.on('end', () => { response.on('end', () => {
if (response.statusCode !== 200) { if (response.statusCode !== 200) {

View File

@ -14,7 +14,7 @@
* limitations under the License. * limitations under the License.
*/ */
var EventEmitter = require('events'); let EventEmitter = require('events');
class FrameManager extends EventEmitter { class FrameManager extends EventEmitter {
/** /**
@ -22,7 +22,7 @@ class FrameManager extends EventEmitter {
* @return {!FrameManager} * @return {!FrameManager}
*/ */
static async create(client) { static async create(client) {
var mainFramePayload = await client.send('Page.getResourceTree'); let mainFramePayload = await client.send('Page.getResourceTree');
return new FrameManager(client, mainFramePayload.frameTree); return new FrameManager(client, mainFramePayload.frameTree);
} }
@ -70,8 +70,8 @@ class FrameManager extends EventEmitter {
this._navigateFrame(this._mainFrame, frameId, null); this._navigateFrame(this._mainFrame, frameId, null);
return; return;
} }
var parentFrame = this._frames.get(parentFrameId); let parentFrame = this._frames.get(parentFrameId);
var frame = new Frame(parentFrame, frameId, null); let frame = new Frame(parentFrame, frameId, null);
this._frames.set(frame._id, frame); this._frames.set(frame._id, frame);
this.emit(FrameManager.Events.FrameAttached, frame); this.emit(FrameManager.Events.FrameAttached, frame);
} }
@ -80,7 +80,7 @@ class FrameManager extends EventEmitter {
* @param {!Object} framePayload * @param {!Object} framePayload
*/ */
_frameNavigated(framePayload) { _frameNavigated(framePayload) {
var frame = this._frames.get(framePayload.id); let frame = this._frames.get(framePayload.id);
if (!frame) { if (!frame) {
// Simulate missed "frameAttached" for a main frame navigation to the new backend process. // Simulate missed "frameAttached" for a main frame navigation to the new backend process.
console.assert(!framePayload.parentId, 'Main frame shouldn\'t have parent frame id.'); console.assert(!framePayload.parentId, 'Main frame shouldn\'t have parent frame id.');
@ -93,7 +93,7 @@ class FrameManager extends EventEmitter {
* @param {string} frameId * @param {string} frameId
*/ */
_frameDetached(frameId) { _frameDetached(frameId) {
var frame = this._frames.get(frameId); let frame = this._frames.get(frameId);
if (frame) if (frame)
this._removeFramesRecursively(frame); this._removeFramesRecursively(frame);
} }
@ -105,7 +105,7 @@ class FrameManager extends EventEmitter {
*/ */
_navigateFrame(frame, newFrameId, newFramePayload) { _navigateFrame(frame, newFrameId, newFramePayload) {
// Detach all child frames first. // Detach all child frames first.
for (var child of frame.childFrames()) for (let child of frame.childFrames())
this._removeFramesRecursively(child); this._removeFramesRecursively(child);
this._frames.delete(frame._id, frame); this._frames.delete(frame._id, frame);
frame._id = newFrameId; frame._id = newFrameId;
@ -120,11 +120,11 @@ class FrameManager extends EventEmitter {
* @return {!Frame} * @return {!Frame}
*/ */
_addFramesRecursively(parentFrame, frameTreePayload) { _addFramesRecursively(parentFrame, frameTreePayload) {
var framePayload = frameTreePayload.frame; let framePayload = frameTreePayload.frame;
var frame = new Frame(parentFrame, framePayload.id, framePayload); let frame = new Frame(parentFrame, framePayload.id, framePayload);
this._frames.set(frame._id, frame); this._frames.set(frame._id, frame);
for (var i = 0; frameTreePayload.childFrames && i < frameTreePayload.childFrames.length; ++i) for (let i = 0; frameTreePayload.childFrames && i < frameTreePayload.childFrames.length; ++i)
this._addFramesRecursively(frame, frameTreePayload.childFrames[i]); this._addFramesRecursively(frame, frameTreePayload.childFrames[i]);
return frame; return frame;
} }
@ -133,7 +133,7 @@ class FrameManager extends EventEmitter {
* @param {!Frame} frame * @param {!Frame} frame
*/ */
_removeFramesRecursively(frame) { _removeFramesRecursively(frame) {
for (var child of frame.childFrames()) for (let child of frame.childFrames())
this._removeFramesRecursively(child); this._removeFramesRecursively(child);
frame._detach(); frame._detach();
this._frames.delete(frame._id); this._frames.delete(frame._id);

View File

@ -39,7 +39,7 @@ class Navigator {
this._minimumTimer = setTimeout(this._completeNavigation.bind(this, false), this._minTime); this._minimumTimer = setTimeout(this._completeNavigation.bind(this, false), this._minTime);
let onload = new Promise(fulfill => this._client.once('Page.loadEventFired', fulfill)); let onload = new Promise(fulfill => this._client.once('Page.loadEventFired', fulfill));
let networkIdle = new Promise(fulfill => this._navigationLoadCallback = fulfill); let networkIdle = new Promise(fulfill => this._navigationLoadCallback = fulfill);
var interstitialPromise = new Promise(fulfill => this._client.once('Security.certificateError', fulfill)).then(() => false); let interstitialPromise = new Promise(fulfill => this._client.once('Security.certificateError', fulfill)).then(() => false);
this._inflightRequests = 0; this._inflightRequests = 0;
// Await for the command to throw exception in case of illegal arguments. // Await for the command to throw exception in case of illegal arguments.

View File

@ -14,13 +14,13 @@
* limitations under the License. * limitations under the License.
*/ */
var fs = require('fs'); let fs = require('fs');
var EventEmitter = require('events'); let EventEmitter = require('events');
var mime = require('mime'); let mime = require('mime');
var Request = require('./Request'); let Request = require('./Request');
var Navigator = require('./Navigator'); let Navigator = require('./Navigator');
var Dialog = require('./Dialog'); let Dialog = require('./Dialog');
var FrameManager = require('./FrameManager'); let FrameManager = require('./FrameManager');
class Page extends EventEmitter { class Page extends EventEmitter {
/** /**
@ -34,10 +34,10 @@ class Page extends EventEmitter {
client.send('Runtime.enable', {}), client.send('Runtime.enable', {}),
client.send('Security.enable', {}), client.send('Security.enable', {}),
]); ]);
var expression = Page._evaluationString(() => window.devicePixelRatio); let expression = Page._evaluationString(() => window.devicePixelRatio);
var {result:{value: screenDPI}} = await client.send('Runtime.evaluate', { expression, returnByValue: true }); let {result:{value: screenDPI}} = await client.send('Runtime.evaluate', { expression, returnByValue: true });
var frameManager = await FrameManager.create(client); let frameManager = await FrameManager.create(client);
var page = new Page(client, frameManager, screenDPI); let page = new Page(client, frameManager, screenDPI);
// Initialize default page size. // Initialize default page size.
await page.setViewportSize({width: 400, height: 300}); await page.setViewportSize({width: 400, height: 300});
return page; return page;
@ -100,7 +100,7 @@ class Page extends EventEmitter {
* @param {!Object} event * @param {!Object} event
*/ */
_onRequestIntercepted(event) { _onRequestIntercepted(event) {
var request = new Request(this._client, event.InterceptionId, event.request); let request = new Request(this._client, event.InterceptionId, event.request);
this._requestInterceptor(request); this._requestInterceptor(request);
} }
@ -115,9 +115,9 @@ class Page extends EventEmitter {
* @param {string} url * @param {string} url
*/ */
function addScriptTag(url) { function addScriptTag(url) {
var script = document.createElement('script'); let script = document.createElement('script');
script.src = url; script.src = url;
var promise = new Promise(x => script.onload = x); let promise = new Promise(x => script.onload = x);
document.head.appendChild(script); document.head.appendChild(script);
return promise; return promise;
} }
@ -128,9 +128,9 @@ class Page extends EventEmitter {
* @return {!Promise} * @return {!Promise}
*/ */
async injectFile(filePath) { async injectFile(filePath) {
var callback; let callback;
var promise = new Promise(fulfill => callback = fulfill); let promise = new Promise(fulfill => callback = fulfill);
var expression = fs.readFile(filePath, 'utf8', (err, data) => callback({err, data})); let expression = fs.readFile(filePath, 'utf8', (err, data) => callback({err, data}));
await promise; await promise;
return this._client.send('Runtime.evaluate', { expression, returnByValue: true }); return this._client.send('Runtime.evaluate', { expression, returnByValue: true });
} }
@ -144,7 +144,7 @@ class Page extends EventEmitter {
throw new Error(`Failed to set in-page callback with name ${name}: window['${name}'] already exists!`); throw new Error(`Failed to set in-page callback with name ${name}: window['${name}'] already exists!`);
this._inPageCallbacks[name] = callback; this._inPageCallbacks[name] = callback;
var expression = Page._evaluationString(inPageCallback, name); let expression = Page._evaluationString(inPageCallback, name);
await this._client.send('Page.addScriptToEvaluateOnLoad', { scriptSource: expression }); await this._client.send('Page.addScriptToEvaluateOnLoad', { scriptSource: expression });
await this._client.send('Runtime.evaluate', { expression, returnByValue: true }); await this._client.send('Runtime.evaluate', { expression, returnByValue: true });
@ -173,7 +173,7 @@ class Page extends EventEmitter {
async setExtraHTTPHeaders(headers) { async setExtraHTTPHeaders(headers) {
this._extraHeaders = {}; this._extraHeaders = {};
// Note: header names are case-insensitive. // Note: header names are case-insensitive.
for (var key of Object.keys(headers)) for (let key of Object.keys(headers))
this._extraHeaders[key.toLowerCase()] = headers[key]; this._extraHeaders[key.toLowerCase()] = headers[key];
return this._client.send('Network.setExtraHTTPHeaders', { headers }); return this._client.send('Network.setExtraHTTPHeaders', { headers });
} }
@ -205,15 +205,15 @@ class Page extends EventEmitter {
* @param {!Object} exceptionDetails * @param {!Object} exceptionDetails
*/ */
async _handleException(exceptionDetails) { async _handleException(exceptionDetails) {
var message = await this._getExceptionMessage(exceptionDetails); let message = await this._getExceptionMessage(exceptionDetails);
this.emit(Page.Events.Error, new Error(message)); this.emit(Page.Events.Error, new Error(message));
} }
async _onConsoleAPI(event) { async _onConsoleAPI(event) {
if (event.type === 'debug' && event.args.length && event.args[0].value === 'driver:InPageCallback') { if (event.type === 'debug' && event.args.length && event.args[0].value === 'driver:InPageCallback') {
var {name, seq, args} = JSON.parse(event.args[1].value); let {name, seq, args} = JSON.parse(event.args[1].value);
var result = await this._inPageCallbacks[name](...args); let result = await this._inPageCallbacks[name](...args);
var expression = Page._evaluationString(deliverResult, name, seq, result); let expression = Page._evaluationString(deliverResult, name, seq, result);
this._client.send('Runtime.evaluate', { expression }); this._client.send('Runtime.evaluate', { expression });
function deliverResult(name, seq, result) { function deliverResult(name, seq, result) {
@ -222,12 +222,12 @@ class Page extends EventEmitter {
} }
return; return;
} }
var values = event.args.map(arg => arg.value || arg.description || ''); let values = event.args.map(arg => arg.value || arg.description || '');
this.emit(Page.Events.ConsoleMessage, values.join(' ')); this.emit(Page.Events.ConsoleMessage, values.join(' '));
} }
_onDialog(event) { _onDialog(event) {
var dialogType = null; let dialogType = null;
if (event.type === 'alert') if (event.type === 'alert')
dialogType = Dialog.Type.Alert; dialogType = Dialog.Type.Alert;
else if (event.type === 'confirm') else if (event.type === 'confirm')
@ -237,7 +237,7 @@ class Page extends EventEmitter {
else if (event.type === 'beforeunload') else if (event.type === 'beforeunload')
dialogType = Dialog.Type.BeforeUnload; dialogType = Dialog.Type.BeforeUnload;
console.assert(dialogType, 'Unknown javascript dialog type: ' + event.type); console.assert(dialogType, 'Unknown javascript dialog type: ' + event.type);
var dialog = new Dialog(this._client, dialogType, event.message); let dialog = new Dialog(this._client, dialogType, event.message);
this.emit(Page.Events.Dialog, dialog); this.emit(Page.Events.Dialog, dialog);
} }
@ -275,9 +275,9 @@ class Page extends EventEmitter {
*/ */
async setViewportSize(size) { async setViewportSize(size) {
this._viewportSize = size; this._viewportSize = size;
var width = size.width; let width = size.width;
var height = size.height; let height = size.height;
var zoom = this._screenDPI; let zoom = this._screenDPI;
return Promise.all([ return Promise.all([
this._client.send('Emulation.setDeviceMetricsOverride', { this._client.send('Emulation.setDeviceMetricsOverride', {
width, width,
@ -307,11 +307,11 @@ class Page extends EventEmitter {
* @return {!Promise<(!Object|undefined)>} * @return {!Promise<(!Object|undefined)>}
*/ */
async evaluate(fun, ...args) { async evaluate(fun, ...args) {
var syncExpression = Page._evaluationString(fun, ...args); let syncExpression = Page._evaluationString(fun, ...args);
var expression = `Promise.resolve(${syncExpression})`; let expression = `Promise.resolve(${syncExpression})`;
var { exceptionDetails, result: remoteObject } = await this._client.send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true }); let { exceptionDetails, result: remoteObject } = await this._client.send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true });
if (exceptionDetails) { if (exceptionDetails) {
var message = await this._getExceptionMessage(exceptionDetails); let message = await this._getExceptionMessage(exceptionDetails);
throw new Error('Evaluation failed: ' + message); throw new Error('Evaluation failed: ' + message);
} }
return remoteObject.value; return remoteObject.value;
@ -322,10 +322,10 @@ class Page extends EventEmitter {
* @return {string} * @return {string}
*/ */
async _getExceptionMessage(exceptionDetails) { async _getExceptionMessage(exceptionDetails) {
var message = ''; let message = '';
var exception = exceptionDetails.exception; let exception = exceptionDetails.exception;
if (exception) { if (exception) {
var response = await this._client.send('Runtime.callFunctionOn', { let response = await this._client.send('Runtime.callFunctionOn', {
objectId: exception.objectId, objectId: exception.objectId,
functionDeclaration: 'function() { return this.message; }', functionDeclaration: 'function() { return this.message; }',
returnByValue: true, returnByValue: true,
@ -336,9 +336,9 @@ class Page extends EventEmitter {
} }
if (exceptionDetails.stackTrace) { if (exceptionDetails.stackTrace) {
for (var callframe of exceptionDetails.stackTrace.callFrames) { for (let callframe of exceptionDetails.stackTrace.callFrames) {
var location = callframe.url + ':' + callframe.lineNumber + ':' + callframe.columnNumber; let location = callframe.url + ':' + callframe.lineNumber + ':' + callframe.columnNumber;
var functionName = callframe.functionName || '<anonymous>'; let functionName = callframe.functionName || '<anonymous>';
message += `\n at ${functionName} (${location})`; message += `\n at ${functionName} (${location})`;
} }
} }
@ -351,7 +351,7 @@ class Page extends EventEmitter {
* @return {!Promise} * @return {!Promise}
*/ */
async evaluateOnInitialized(fun, ...args) { async evaluateOnInitialized(fun, ...args) {
var scriptSource = Page._evaluationString(fun, ...args); let scriptSource = Page._evaluationString(fun, ...args);
await this._client.send('Page.addScriptToEvaluateOnLoad', { scriptSource }); await this._client.send('Page.addScriptToEvaluateOnLoad', { scriptSource });
} }
@ -370,9 +370,9 @@ class Page extends EventEmitter {
*/ */
async screenshot(options) { async screenshot(options) {
options = options || {}; options = options || {};
var screenshotType = null; let screenshotType = null;
if (options.path) { if (options.path) {
var mimeType = mime.lookup(options.path); let mimeType = mime.lookup(options.path);
if (mimeType === 'image/png') if (mimeType === 'image/png')
screenshotType = 'png'; screenshotType = 'png';
else if (mimeType === 'image/jpeg') else if (mimeType === 'image/jpeg')
@ -423,7 +423,7 @@ class Page extends EventEmitter {
}) })
]); ]);
} else if (options.fullPage) { } else if (options.fullPage) {
var response = await this._client.send('Page.getLayoutMetrics'); let response = await this._client.send('Page.getLayoutMetrics');
await Promise.all([ await Promise.all([
this._client.send('Emulation.setVisibleSize', { this._client.send('Emulation.setVisibleSize', {
width: Math.ceil(response.contentSize.width / this._screenDPI), width: Math.ceil(response.contentSize.width / this._screenDPI),
@ -436,7 +436,7 @@ class Page extends EventEmitter {
}) })
]); ]);
} }
var result = await this._client.send('Page.captureScreenshot', { let result = await this._client.send('Page.captureScreenshot', {
fromSurface: true, fromSurface: true,
format: screenshotType, format: screenshotType,
quality: options.quality quality: options.quality
@ -447,7 +447,7 @@ class Page extends EventEmitter {
this._client.send('Emulation.resetViewport') this._client.send('Emulation.resetViewport')
]); ]);
} }
var buffer = new Buffer(result.data, 'base64'); let buffer = new Buffer(result.data, 'base64');
if (options.path) if (options.path)
fs.writeFileSync(options.path, buffer); fs.writeFileSync(options.path, buffer);
return buffer; return buffer;
@ -461,16 +461,16 @@ class Page extends EventEmitter {
async printToPDF(filePath, options) { async printToPDF(filePath, options) {
options = options || {}; options = options || {};
var scale = options.scale || 1; let scale = options.scale || 1;
var displayHeaderFooter = options.displayHeaderFooter || false; let displayHeaderFooter = options.displayHeaderFooter || false;
var printBackground = options.printBackground || true; let printBackground = options.printBackground || true;
var landscape = options.landscape || false; let landscape = options.landscape || false;
var pageRanges = options.pageRanges || ''; let pageRanges = options.pageRanges || '';
var paperWidth = 8.5; let paperWidth = 8.5;
var paperHeight = 11; let paperHeight = 11;
if (options.format) { if (options.format) {
var format = Page.PaperFormats[options.format]; let format = Page.PaperFormats[options.format];
console.assert(format, 'Unknown paper format: ' + options.format); console.assert(format, 'Unknown paper format: ' + options.format);
paperWidth = format.width; paperWidth = format.width;
paperHeight = format.height; paperHeight = format.height;
@ -479,13 +479,13 @@ class Page extends EventEmitter {
paperHeight = convertPrintParameterToInches(options.height) || paperHeight; paperHeight = convertPrintParameterToInches(options.height) || paperHeight;
} }
var marginOptions = options.margin || {}; let marginOptions = options.margin || {};
var marginTop = convertPrintParameterToInches(marginOptions.top) || 0; let marginTop = convertPrintParameterToInches(marginOptions.top) || 0;
var marginLeft = convertPrintParameterToInches(marginOptions.left) || 0; let marginLeft = convertPrintParameterToInches(marginOptions.left) || 0;
var marginBottom = convertPrintParameterToInches(marginOptions.bottom) || 0; let marginBottom = convertPrintParameterToInches(marginOptions.bottom) || 0;
var marginRight = convertPrintParameterToInches(marginOptions.right) || 0; let marginRight = convertPrintParameterToInches(marginOptions.right) || 0;
var result = await this._client.send('Page.printToPDF', { let result = await this._client.send('Page.printToPDF', {
landscape: landscape, landscape: landscape,
displayHeaderFooter: displayHeaderFooter, displayHeaderFooter: displayHeaderFooter,
printBackground: printBackground, printBackground: printBackground,
@ -498,7 +498,7 @@ class Page extends EventEmitter {
marginRight: marginRight, marginRight: marginRight,
pageRanges: pageRanges pageRanges: pageRanges
}); });
var buffer = new Buffer(result.data, 'base64'); let buffer = new Buffer(result.data, 'base64');
fs.writeFileSync(filePath, buffer); fs.writeFileSync(filePath, buffer);
} }
@ -538,7 +538,7 @@ Page.PaperFormats = {
A5: {width: 5.83, height: 8.27 }, A5: {width: 5.83, height: 8.27 },
}; };
var unitToPixels = { let unitToPixels = {
'px': 1, 'px': 1,
'in': 96, 'in': 96,
'cm': 37.8, 'cm': 37.8,
@ -552,14 +552,14 @@ var unitToPixels = {
function convertPrintParameterToInches(parameter) { function convertPrintParameterToInches(parameter) {
if (typeof parameter === 'undefined') if (typeof parameter === 'undefined')
return undefined; return undefined;
var pixels; let pixels;
if (typeof parameter === 'number') { if (typeof parameter === 'number') {
// Treat numbers as pixel values to be aligned with phantom's paperSize. // Treat numbers as pixel values to be aligned with phantom's paperSize.
pixels = /** @type {number} */ (parameter); pixels = /** @type {number} */ (parameter);
} else if (typeof parameter === 'string') { } else if (typeof parameter === 'string') {
var text = parameter; let text = parameter;
var unit = text.substring(text.length - 2).toLowerCase(); let unit = text.substring(text.length - 2).toLowerCase();
var valueText = ''; let valueText = '';
if (unitToPixels.hasOwnProperty(unit)) { if (unitToPixels.hasOwnProperty(unit)) {
valueText = text.substring(0, text.length - 2); valueText = text.substring(0, text.length - 2);
} else { } else {
@ -568,7 +568,7 @@ function convertPrintParameterToInches(parameter) {
unit = 'px'; unit = 'px';
valueText = text; valueText = text;
} }
var value = Number(valueText); let value = Number(valueText);
console.assert(!isNaN(value), 'Failed to parse parameter value: ' + text); console.assert(!isNaN(value), 'Failed to parse parameter value: ' + text);
pixels = value * unitToPixels[unit]; pixels = value * unitToPixels[unit];
} else { } else {

View File

@ -14,11 +14,11 @@
* limitations under the License. * limitations under the License.
*/ */
var path = require('path'); let path = require('path');
var fs = require('fs'); let fs = require('fs');
var deasync = require('deasync'); let deasync = require('deasync');
var removeRecursive = require('rimraf').sync; let removeRecursive = require('rimraf').sync;
var copyRecursive = deasync(require('ncp').ncp); let copyRecursive = deasync(require('ncp').ncp);
class FileSystem { class FileSystem {
constructor() { constructor() {
@ -68,7 +68,7 @@ class FileSystem {
* @param {string} toPath * @param {string} toPath
*/ */
copy(fromPath, toPath) { copy(fromPath, toPath) {
var content = fs.readFileSync(fromPath); let content = fs.readFileSync(fromPath);
fs.writeFileSync(toPath, content); fs.writeFileSync(toPath, content);
} }
@ -77,7 +77,7 @@ class FileSystem {
* @param {string} toPath * @param {string} toPath
*/ */
move(fromPath, toPath) { move(fromPath, toPath) {
var content = fs.readFileSync(fromPath); let content = fs.readFileSync(fromPath);
fs.writeFileSync(toPath, content); fs.writeFileSync(toPath, content);
fs.unlinkSync(fromPath); fs.unlinkSync(fromPath);
} }
@ -170,7 +170,7 @@ class FileSystem {
* @param {string} mode * @param {string} mode
*/ */
write(filePath, data, mode) { write(filePath, data, mode) {
var fd = new FileDescriptor(filePath, mode, 'utf8'); let fd = new FileDescriptor(filePath, mode, 'utf8');
fd.write(data); fd.write(data);
fd.close(); fd.close();
} }
@ -288,8 +288,8 @@ class FileSystem {
} }
} }
var fdwrite = deasync(fs.write); let fdwrite = deasync(fs.write);
var fdread = deasync(fs.read); let fdread = deasync(fs.read);
class FileDescriptor { class FileDescriptor {
/** /**
@ -318,8 +318,8 @@ class FileDescriptor {
* @param {string} data * @param {string} data
*/ */
write(data) { write(data) {
var buffer = Buffer.from(data, this._encoding); let buffer = Buffer.from(data, this._encoding);
var written = fdwrite(this._fd, buffer, 0, buffer.length, this._position); let written = fdwrite(this._fd, buffer, 0, buffer.length, this._position);
this._position += written; this._position += written;
} }
@ -339,13 +339,13 @@ class FileDescriptor {
* @return {string} * @return {string}
*/ */
read(size) { read(size) {
var position = this._position; let position = this._position;
if (!size) { if (!size) {
size = fs.fstatSync(this._fd).size; size = fs.fstatSync(this._fd).size;
position = 0; position = 0;
} }
var buffer = new Buffer(size); let buffer = new Buffer(size);
var bytesRead = fdread(this._fd, buffer, 0, size, position); let bytesRead = fdread(this._fd, buffer, 0, size, position);
this._position += bytesRead; this._position += bytesRead;
return buffer.toString(this._encoding); return buffer.toString(this._encoding);
} }

View File

@ -14,17 +14,17 @@
* limitations under the License. * limitations under the License.
*/ */
var fs = require('fs'); let fs = require('fs');
var path = require('path'); let path = require('path');
var vm = require('vm'); let vm = require('vm');
var url = require('url'); let url = require('url');
/** /**
* @param {!Object} context * @param {!Object} context
* @param {string} scriptPath * @param {string} scriptPath
*/ */
module.exports.create = function(context, scriptPath) { module.exports.create = function(context, scriptPath) {
var phantom = { const phantom = {
page: { page: {
onConsoleMessage: null, onConsoleMessage: null,
}, },
@ -82,7 +82,7 @@ module.exports.create = function(context, scriptPath) {
* @return {!{major: number, minor: number, patch: number}} * @return {!{major: number, minor: number, patch: number}}
*/ */
get version() { get version() {
var versionParts = require('../package.json').version.split('.'); let versionParts = require('../package.json').version.split('.');
return { return {
major: parseInt(versionParts[0], 10), major: parseInt(versionParts[0], 10),
minor: parseInt(versionParts[1], 10), minor: parseInt(versionParts[1], 10),
@ -105,7 +105,7 @@ module.exports.create = function(context, scriptPath) {
filePath = path.resolve(phantom.libraryPath, filePath); filePath = path.resolve(phantom.libraryPath, filePath);
if (!fs.existsSync(filePath)) if (!fs.existsSync(filePath))
return false; return false;
var code = fs.readFileSync(filePath, 'utf8'); let code = fs.readFileSync(filePath, 'utf8');
if (code.startsWith('#!')) if (code.startsWith('#!'))
code = code.substring(code.indexOf('\n')); code = code.substring(code.indexOf('\n'));
vm.runInContext(code, context, { vm.runInContext(code, context, {
@ -120,7 +120,7 @@ module.exports.create = function(context, scriptPath) {
* @param {string} filename * @param {string} filename
*/ */
loadModule: function(moduleSource, filename) { loadModule: function(moduleSource, filename) {
var code = [ let code = [
'(function(require, exports, module) {\n', '(function(require, exports, module) {\n',
moduleSource, moduleSource,
'\n}.call({},', '\n}.call({},',

View File

@ -14,9 +14,9 @@
* limitations under the License. * limitations under the License.
*/ */
var readline = require('readline'); let readline = require('readline');
var await = require('./utilities').await; let await = require('./utilities').await;
var os = require('os'); let os = require('os');
class System { class System {
/** /**
@ -61,7 +61,7 @@ class StandardInput {
if (this._closed && !this._lines.length) if (this._closed && !this._lines.length)
return ''; return '';
if (!this._lines.length) { if (!this._lines.length) {
var linePromise = new Promise(fulfill => this._readline.once('line', fulfill)); let linePromise = new Promise(fulfill => this._readline.once('line', fulfill));
await(linePromise); await(linePromise);
} }
return this._lines.shift(); return this._lines.shift();
@ -72,10 +72,10 @@ class StandardInput {
*/ */
read() { read() {
if (!this._closed) { if (!this._closed) {
var closePromise = new Promise(fulfill => this._readline.once('close', fulfill)); let closePromise = new Promise(fulfill => this._readline.once('close', fulfill));
await(closePromise); await(closePromise);
} }
var text = this._lines.join('\n'); let text = this._lines.join('\n');
this._lines = []; this._lines = [];
return text; return text;
} }

View File

@ -14,13 +14,13 @@
* limitations under the License. * limitations under the License.
*/ */
var await = require('./utilities').await; let await = require('./utilities').await;
var EventEmitter = require('events'); let EventEmitter = require('events');
var fs = require('fs'); let fs = require('fs');
var path = require('path'); let path = require('path');
var PageEvents = require('../lib/Page').Events; let PageEvents = require('../lib/Page').Events;
var noop = function() { }; let noop = function() { };
class WebPage { class WebPage {
/** /**
@ -82,7 +82,7 @@ class WebPage {
* @param {!Request} request * @param {!Request} request
*/ */
function resourceInterceptor(request) { function resourceInterceptor(request) {
var requestData = { let requestData = {
url: request.url(), url: request.url(),
headers: request.headers() headers: request.headers()
}; };
@ -95,8 +95,8 @@ class WebPage {
_onResponseReceived(response) { _onResponseReceived(response) {
if (!this.onResourceReceived) if (!this.onResourceReceived)
return; return;
var headers = []; let headers = [];
for (var key in response.headers) { for (let key in response.headers) {
headers.push({ headers.push({
name: key, name: key,
value: response.headers[key] value: response.headers[key]
@ -217,7 +217,7 @@ class WebPage {
this._onAlertCallback.call(null, dialog.message()); this._onAlertCallback.call(null, dialog.message());
await(dialog.accept()); await(dialog.accept());
} else if (dialog.type === 'confirm' && this._onConfirmCallback) { } else if (dialog.type === 'confirm' && this._onConfirmCallback) {
var result = this._onConfirmCallback.call(null, dialog.message()); let result = this._onConfirmCallback.call(null, dialog.message());
await(result ? dialog.accept() : dialog.dismiss()); await(result ? dialog.accept() : dialog.dismiss());
} }
} }
@ -247,7 +247,7 @@ class WebPage {
this.onInitialized(); this.onInitialized();
this._deferEvaluate = false; this._deferEvaluate = false;
this._page.navigate(url).then(result => { this._page.navigate(url).then(result => {
var status = result ? 'success' : 'fail'; let status = result ? 'success' : 'fail';
if (!result) { if (!result) {
this.onResourceError.call(null, { this.onResourceError.call(null, {
url, url,
@ -283,8 +283,8 @@ class WebPage {
*/ */
render(fileName) { render(fileName) {
if (fileName.endsWith('pdf')) { if (fileName.endsWith('pdf')) {
var options = {}; let options = {};
var paperSize = this.paperSize || {}; let paperSize = this.paperSize || {};
options.margin = paperSize.margin; options.margin = paperSize.margin;
options.format = paperSize.format; options.format = paperSize.format;
options.landscape = paperSize.orientation === 'landscape'; options.landscape = paperSize.orientation === 'landscape';
@ -292,7 +292,7 @@ class WebPage {
options.height = paperSize.height; options.height = paperSize.height;
await(this._page.printToPDF(fileName, options)); await(this._page.printToPDF(fileName, options));
} else { } else {
var options = {}; let options = {};
if (this.clipRect && (this.clipRect.left || this.clipRect.top || this.clipRect.width || this.clipRect.height)) { if (this.clipRect && (this.clipRect.left || this.clipRect.top || this.clipRect.width || this.clipRect.height)) {
options.clip = { options.clip = {
x: this.clipRect.left, x: this.clipRect.left,
@ -362,7 +362,7 @@ class AsyncEmitter extends EventEmitter {
_onListenerAdded(event, listener) { _onListenerAdded(event, listener) {
// Async listener calls original listener on next tick. // Async listener calls original listener on next tick.
var asyncListener = (...args) => { let asyncListener = (...args) => {
process.nextTick(() => listener.apply(null, args)); process.nextTick(() => listener.apply(null, args));
}; };
listener[this._symbol] = asyncListener; listener[this._symbol] = asyncListener;

View File

@ -14,8 +14,8 @@
* limitations under the License. * limitations under the License.
*/ */
var http = require('http'); let http = require('http');
var await = require('./utilities').await; let await = require('./utilities').await;
class WebServer { class WebServer {
constructor() { constructor() {
@ -47,17 +47,17 @@ class WebServer {
return false; return false;
this.newRequest = callback; this.newRequest = callback;
this._server.listen(port); this._server.listen(port);
var errorPromise = new Promise(x => this._server.once('error', x)); let errorPromise = new Promise(x => this._server.once('error', x));
var successPromise = new Promise(x => this._server.once('listening', x)); let successPromise = new Promise(x => this._server.once('listening', x));
await(Promise.race([errorPromise, successPromise])); await(Promise.race([errorPromise, successPromise]));
if (!this._server.listening) if (!this._server.listening)
return false; return false;
this._server.on('request', (req, res) => { this._server.on('request', (req, res) => {
res.close = res.end.bind(res); res.close = res.end.bind(res);
var headers = res.getHeaders(); let headers = res.getHeaders();
res.headers = []; res.headers = [];
for (var key in headers) { for (let key in headers) {
res.headers.push({ res.headers.push({
name: key, name: key,
value: headers[key] value: headers[key]
@ -65,7 +65,7 @@ class WebServer {
} }
res.header = res.getHeader; res.header = res.getHeader;
res.setHeaders = headers => { res.setHeaders = headers => {
for (var key in headers) for (let key in headers)
res.setHeader(key, headers[key]); res.setHeader(key, headers[key]);
}; };
Object.defineProperty(res, 'statusCode', { Object.defineProperty(res, 'statusCode', {

View File

@ -15,18 +15,18 @@
* limitations under the License. * limitations under the License.
*/ */
var vm = require('vm'); let vm = require('vm');
var path = require('path'); let path = require('path');
var fs = require('fs'); let fs = require('fs');
var Phantom = require('./Phantom'); let Phantom = require('./Phantom');
var FileSystem = require('./FileSystem'); let FileSystem = require('./FileSystem');
var System = require('./System'); let System = require('./System');
var WebPage = require('./WebPage'); let WebPage = require('./WebPage');
var WebServer = require('./WebServer'); let WebServer = require('./WebServer');
var child_process = require('child_process'); let child_process = require('child_process');
var Browser = require('..').Browser; let Browser = require('..').Browser;
var version = require('../package.json').version; let version = require('../package.json').version;
var argv = require('minimist')(process.argv.slice(2), { let argv = require('minimist')(process.argv.slice(2), {
alias: { v: 'version' }, alias: { v: 'version' },
boolean: ['headless'], boolean: ['headless'],
default: {'headless': true }, default: {'headless': true },
@ -43,27 +43,27 @@ if (argv['ssl-certificates-path']) {
return; return;
} }
var scriptArguments = argv._; let scriptArguments = argv._;
if (!scriptArguments.length) { if (!scriptArguments.length) {
console.log(__filename.split('/').pop() + ' [scriptfile]'); console.log(__filename.split('/').pop() + ' [scriptfile]');
return; return;
} }
var scriptPath = path.resolve(process.cwd(), scriptArguments[0]); let scriptPath = path.resolve(process.cwd(), scriptArguments[0]);
if (!fs.existsSync(scriptPath)) { if (!fs.existsSync(scriptPath)) {
console.error(`script not found: ${scriptPath}`); console.error(`script not found: ${scriptPath}`);
process.exit(1); process.exit(1);
return; return;
} }
var browser = new Browser({ let browser = new Browser({
remoteDebuggingPort: 9229, remoteDebuggingPort: 9229,
headless: argv.headless, headless: argv.headless,
args: ['--no-sandbox'] args: ['--no-sandbox']
}); });
var context = createPhantomContext(browser, scriptPath, argv); let context = createPhantomContext(browser, scriptPath, argv);
var scriptContent = fs.readFileSync(scriptPath, 'utf8'); let scriptContent = fs.readFileSync(scriptPath, 'utf8');
vm.runInContext(scriptContent, context); vm.runInContext(scriptContent, context);
/** /**
@ -73,7 +73,7 @@ vm.runInContext(scriptContent, context);
* @return {!Object} * @return {!Object}
*/ */
function createPhantomContext(browser, scriptPath, argv) { function createPhantomContext(browser, scriptPath, argv) {
var context = {}; let context = {};
context.setInterval = setInterval; context.setInterval = setInterval;
context.setTimeout = setTimeout; context.setTimeout = setTimeout;
context.clearInterval = clearInterval; context.clearInterval = clearInterval;
@ -86,7 +86,7 @@ function createPhantomContext(browser, scriptPath, argv) {
vm.createContext(context); vm.createContext(context);
var nativeExports = { let nativeExports = {
fs: new FileSystem(), fs: new FileSystem(),
system: new System(argv._), system: new System(argv._),
webpage: { webpage: {
@ -100,8 +100,8 @@ function createPhantomContext(browser, scriptPath, argv) {
}, },
child_process: child_process child_process: child_process
}; };
var bootstrapPath = path.join(__dirname, '..', 'third_party', 'phantomjs', 'bootstrap.js'); let bootstrapPath = path.join(__dirname, '..', 'third_party', 'phantomjs', 'bootstrap.js');
var bootstrapCode = fs.readFileSync(bootstrapPath, 'utf8'); let bootstrapCode = fs.readFileSync(bootstrapPath, 'utf8');
vm.runInContext(bootstrapCode, context, { vm.runInContext(bootstrapCode, context, {
filename: 'bootstrap.js' filename: 'bootstrap.js'
})(nativeExports); })(nativeExports);

View File

@ -14,13 +14,13 @@
* limitations under the License. * limitations under the License.
*/ */
var loopWhile = require('deasync').loopWhile; let loopWhile = require('deasync').loopWhile;
module.exports = { module.exports = {
await: function(promise) { await: function(promise) {
var error; let error;
var result; let result;
var done = false; let done = false;
promise.then(r => result = r) promise.then(r => result = r)
.catch(err => error = err) .catch(err => error = err)
.then(() => done = true); .then(() => done = true);

View File

@ -14,11 +14,11 @@
* limitations under the License. * limitations under the License.
*/ */
var http = require('http'); let http = require('http');
var url = require('url'); let url = require('url');
var fs = require('fs'); let fs = require('fs');
var path = require('path'); let path = require('path');
var mime = require('mime'); let mime = require('mime');
class StaticServer { class StaticServer {
/** /**
@ -36,7 +36,7 @@ class StaticServer {
} }
_onRequest(request, response) { _onRequest(request, response) {
var pathName = url.parse(request.url).path; let pathName = url.parse(request.url).path;
if (pathName === '/') if (pathName === '/')
pathName = '/index.html'; pathName = '/index.html';
pathName = path.join(this._dirPath, pathName.substring(1)); pathName = path.join(this._dirPath, pathName.substring(1));

View File

@ -1,4 +1,4 @@
var utils = module.exports = { const utils = module.exports = {
/** /**
* @param {!Page} page * @param {!Page} page
* @param {string} frameId * @param {string} frameId
@ -9,7 +9,7 @@ var utils = module.exports = {
await page.evaluate(attachFrame, frameId, url); await page.evaluate(attachFrame, frameId, url);
function attachFrame(frameId, url) { function attachFrame(frameId, url) {
var frame = document.createElement('iframe'); let frame = document.createElement('iframe');
frame.src = url; frame.src = url;
frame.id = frameId; frame.id = frameId;
document.body.appendChild(frame); document.body.appendChild(frame);
@ -26,7 +26,7 @@ var utils = module.exports = {
await page.evaluate(detachFrame, frameId); await page.evaluate(detachFrame, frameId);
function detachFrame(frameId) { function detachFrame(frameId) {
var frame = document.getElementById(frameId); let frame = document.getElementById(frameId);
frame.remove(); frame.remove();
} }
}, },
@ -41,7 +41,7 @@ var utils = module.exports = {
await page.evaluate(navigateFrame, frameId, url); await page.evaluate(navigateFrame, frameId, url);
function navigateFrame(frameId, url) { function navigateFrame(frameId, url) {
var frame = document.getElementById(frameId); let frame = document.getElementById(frameId);
frame.src = url; frame.src = url;
return new Promise(x => frame.onload = x); return new Promise(x => frame.onload = x);
} }
@ -54,8 +54,8 @@ var utils = module.exports = {
*/ */
dumpFrames: function(frame, indentation) { dumpFrames: function(frame, indentation) {
indentation = indentation || ''; indentation = indentation || '';
var result = indentation + frame.url(); let result = indentation + frame.url();
for (var child of frame.childFrames()) for (let child of frame.childFrames())
result += '\n' + utils.dumpFrames(child, ' ' + indentation); result += '\n' + utils.dumpFrames(child, ' ' + indentation);
return result; return result;
}, },

View File

@ -13,16 +13,16 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
var path = require('path'); let path = require('path');
var fs = require('fs'); let fs = require('fs');
var Diff = require('text-diff'); let Diff = require('text-diff');
var mime = require('mime'); let mime = require('mime');
var PNG = require('pngjs').PNG; let PNG = require('pngjs').PNG;
var pixelmatch = require('pixelmatch'); let pixelmatch = require('pixelmatch');
var rm = require('rimraf').sync; let rm = require('rimraf').sync;
var GOLDEN_DIR = path.join(__dirname, 'golden'); let GOLDEN_DIR = path.join(__dirname, 'golden');
var OUTPUT_DIR = path.join(__dirname, 'output'); let OUTPUT_DIR = path.join(__dirname, 'output');
module.exports = { module.exports = {
addMatchers: function(jasmine) { addMatchers: function(jasmine) {
@ -35,7 +35,7 @@ module.exports = {
}, },
}; };
var GoldenComparators = { let GoldenComparators = {
'image/png': compareImages, 'image/png': compareImages,
'text/plain': compareText 'text/plain': compareText
}; };
@ -49,15 +49,15 @@ function compareImages(actualBuffer, expectedBuffer) {
if (!actualBuffer || !(actualBuffer instanceof Buffer)) if (!actualBuffer || !(actualBuffer instanceof Buffer))
return { errorMessage: 'Actual result should be Buffer.' }; return { errorMessage: 'Actual result should be Buffer.' };
var actual = PNG.sync.read(actualBuffer); let actual = PNG.sync.read(actualBuffer);
var expected = PNG.sync.read(expectedBuffer); let expected = PNG.sync.read(expectedBuffer);
if (expected.width !== actual.width || expected.height !== actual.height) { if (expected.width !== actual.width || expected.height !== actual.height) {
return { return {
errorMessage: `Sizes differ: expected image ${expected.width}px X ${expected.height}px, but got ${actual.width}px X ${actual.height}px. ` errorMessage: `Sizes differ: expected image ${expected.width}px X ${expected.height}px, but got ${actual.width}px X ${actual.height}px. `
}; };
} }
var diff = new PNG({width: expected.width, height: expected.height}); let diff = new PNG({width: expected.width, height: expected.height});
var count = pixelmatch(expected.data, actual.data, diff.data, expected.width, expected.height, {threshold: 0.1}); let count = pixelmatch(expected.data, actual.data, diff.data, expected.width, expected.height, {threshold: 0.1});
return count > 0 ? { diff: PNG.sync.write(diff) } : null; return count > 0 ? { diff: PNG.sync.write(diff) } : null;
} }
@ -69,14 +69,14 @@ function compareImages(actualBuffer, expectedBuffer) {
function compareText(actual, expectedBuffer) { function compareText(actual, expectedBuffer) {
if (typeof actual !== 'string') if (typeof actual !== 'string')
return { errorMessage: 'Actual result should be string' }; return { errorMessage: 'Actual result should be string' };
var expected = expectedBuffer.toString('utf-8'); let expected = expectedBuffer.toString('utf-8');
if (expected === actual) if (expected === actual)
return null; return null;
var diff = new Diff(); let diff = new Diff();
var result = diff.main(expected, actual); let result = diff.main(expected, actual);
diff.cleanupSemantic(result); diff.cleanupSemantic(result);
var html = diff.prettyHtml(result); let html = diff.prettyHtml(result);
var diffStylePath = path.join(__dirname, 'diffstyle.css'); let diffStylePath = path.join(__dirname, 'diffstyle.css');
html = `<link rel="stylesheet" href="file://${diffStylePath}">` + html; html = `<link rel="stylesheet" href="file://${diffStylePath}">` + html;
return { return {
diff: html, diff: html,
@ -84,7 +84,7 @@ function compareText(actual, expectedBuffer) {
}; };
} }
var customMatchers = { let customMatchers = {
toBeGolden: function(util, customEqualityTesters) { toBeGolden: function(util, customEqualityTesters) {
return { return {
/** /**
@ -93,10 +93,10 @@ var customMatchers = {
* @return {!{pass: boolean, message: (undefined|string)}} * @return {!{pass: boolean, message: (undefined|string)}}
*/ */
compare: function(actual, goldenName) { compare: function(actual, goldenName) {
var expectedPath = path.join(GOLDEN_DIR, goldenName); let expectedPath = path.join(GOLDEN_DIR, goldenName);
var actualPath = path.join(OUTPUT_DIR, goldenName); let actualPath = path.join(OUTPUT_DIR, goldenName);
var messageSuffix = 'Output is saved in "' + path.basename(OUTPUT_DIR + '" directory'); let messageSuffix = 'Output is saved in "' + path.basename(OUTPUT_DIR + '" directory');
if (!fs.existsSync(expectedPath)) { if (!fs.existsSync(expectedPath)) {
ensureOutputDir(); ensureOutputDir();
@ -106,15 +106,15 @@ var customMatchers = {
message: goldenName + ' is missing in golden results. ' + messageSuffix message: goldenName + ' is missing in golden results. ' + messageSuffix
}; };
} }
var expected = fs.readFileSync(expectedPath); let expected = fs.readFileSync(expectedPath);
var comparator = GoldenComparators[mime.lookup(goldenName)]; let comparator = GoldenComparators[mime.lookup(goldenName)];
if (!comparator) { if (!comparator) {
return { return {
pass: false, pass: false,
message: 'Failed to find comparator with type ' + mime.lookup(goldenName) + ': ' + goldenName message: 'Failed to find comparator with type ' + mime.lookup(goldenName) + ': ' + goldenName
}; };
} }
var result = comparator(actual, expected); let result = comparator(actual, expected);
if (!result) if (!result)
return { pass: true }; return { pass: true };
ensureOutputDir(); ensureOutputDir();
@ -122,11 +122,11 @@ var customMatchers = {
// Copy expected to the output/ folder for convenience. // Copy expected to the output/ folder for convenience.
fs.writeFileSync(addSuffix(actualPath, '-expected'), expected); fs.writeFileSync(addSuffix(actualPath, '-expected'), expected);
if (result.diff) { if (result.diff) {
var diffPath = addSuffix(actualPath, '-diff', result.diffExtension); let diffPath = addSuffix(actualPath, '-diff', result.diffExtension);
fs.writeFileSync(diffPath, result.diff); fs.writeFileSync(diffPath, result.diff);
} }
var message = goldenName + ' mismatch!'; let message = goldenName + ' mismatch!';
if (result.errorMessage) if (result.errorMessage)
message += ' ' + result.errorMessage; message += ' ' + result.errorMessage;
return { return {
@ -150,8 +150,8 @@ var customMatchers = {
* @return {string} * @return {string}
*/ */
function addSuffix(filePath, suffix, customExtension) { function addSuffix(filePath, suffix, customExtension) {
var dirname = path.dirname(filePath); let dirname = path.dirname(filePath);
var ext = path.extname(filePath); let ext = path.extname(filePath);
var name = path.basename(filePath, ext); let name = path.basename(filePath, ext);
return path.join(dirname, name + suffix + (customExtension || ext)); return path.join(dirname, name + suffix + (customExtension || ext));
} }

View File

@ -14,21 +14,21 @@
* limitations under the License. * limitations under the License.
*/ */
var path = require('path'); let path = require('path');
var Browser = require('../lib/Browser'); let Browser = require('../lib/Browser');
var StaticServer = require('./StaticServer'); let StaticServer = require('./StaticServer');
var GoldenUtils = require('./golden-utils'); let GoldenUtils = require('./golden-utils');
var PORT = 8907; let PORT = 8907;
var STATIC_PREFIX = 'http://localhost:' + PORT; let STATIC_PREFIX = 'http://localhost:' + PORT;
var EMPTY_PAGE = STATIC_PREFIX + '/empty.html'; let EMPTY_PAGE = STATIC_PREFIX + '/empty.html';
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10 * 1000; jasmine.DEFAULT_TIMEOUT_INTERVAL = 10 * 1000;
describe('Puppeteer', function() { describe('Puppeteer', function() {
var browser; let browser;
var staticServer; let staticServer;
var page; let page;
beforeAll(function() { beforeAll(function() {
browser = new Browser({args: ['--no-sandbox']}); browser = new Browser({args: ['--no-sandbox']});
@ -52,11 +52,11 @@ describe('Puppeteer', function() {
describe('Page.evaluate', function() { describe('Page.evaluate', function() {
it('should work', SX(async function() { it('should work', SX(async function() {
var result = await page.evaluate(() => 7 * 3); let result = await page.evaluate(() => 7 * 3);
expect(result).toBe(21); expect(result).toBe(21);
})); }));
it('should await promise', SX(async function() { it('should await promise', SX(async function() {
var result = await page.evaluate(() => Promise.resolve(8 * 7)); let result = await page.evaluate(() => Promise.resolve(8 * 7));
expect(result).toBe(56); expect(result).toBe(56);
})); }));
it('should work from-inside inPageCallback', SX(async function() { it('should work from-inside inPageCallback', SX(async function() {
@ -64,13 +64,13 @@ describe('Puppeteer', function() {
await page.setInPageCallback('callController', async function(a, b) { await page.setInPageCallback('callController', async function(a, b) {
return await page.evaluate((a, b) => a * b, a, b); return await page.evaluate((a, b) => a * b, a, b);
}); });
var result = await page.evaluate(async function() { let result = await page.evaluate(async function() {
return await callController(9, 3); return await callController(9, 3);
}); });
expect(result).toBe(27); expect(result).toBe(27);
})); }));
it('should reject promise with exception', SX(async function() { it('should reject promise with exception', SX(async function() {
var error = null; let error = null;
try { try {
await page.evaluate(() => not.existing.object.property); await page.evaluate(() => not.existing.object.property);
} catch (e) { } catch (e) {
@ -82,7 +82,7 @@ describe('Puppeteer', function() {
}); });
it('Page Events: ConsoleMessage', SX(async function() { it('Page Events: ConsoleMessage', SX(async function() {
var msgs = []; let msgs = [];
page.on('consolemessage', msg => msgs.push(msg)); page.on('consolemessage', msg => msgs.push(msg));
await page.evaluate(() => console.log('Message!')); await page.evaluate(() => console.log('Message!'));
expect(msgs).toEqual(['Message!']); expect(msgs).toEqual(['Message!']);
@ -90,11 +90,11 @@ describe('Puppeteer', function() {
describe('Page.navigate', function() { describe('Page.navigate', function() {
it('should fail when navigating to bad url', SX(async function() { it('should fail when navigating to bad url', SX(async function() {
var success = await page.navigate('asdfasdf'); let success = await page.navigate('asdfasdf');
expect(success).toBe(false); expect(success).toBe(false);
})); }));
it('should succeed when navigating to good url', SX(async function() { it('should succeed when navigating to good url', SX(async function() {
var success = await page.navigate(EMPTY_PAGE); let success = await page.navigate(EMPTY_PAGE);
expect(success).toBe(true); expect(success).toBe(true);
})); }));
}); });
@ -104,7 +104,7 @@ describe('Puppeteer', function() {
await page.setInPageCallback('callController', function(a, b) { await page.setInPageCallback('callController', function(a, b) {
return a * b; return a * b;
}); });
var result = await page.evaluate(async function() { let result = await page.evaluate(async function() {
return await callController(9, 4); return await callController(9, 4);
}); });
expect(result).toBe(36); expect(result).toBe(36);
@ -115,7 +115,7 @@ describe('Puppeteer', function() {
}); });
await page.navigate(EMPTY_PAGE); await page.navigate(EMPTY_PAGE);
var result = await page.evaluate(async function() { let result = await page.evaluate(async function() {
return await callController(9, 4); return await callController(9, 4);
}); });
expect(result).toBe(36); expect(result).toBe(36);
@ -125,7 +125,7 @@ describe('Puppeteer', function() {
return Promise.resolve(a * b); return Promise.resolve(a * b);
}); });
var result = await page.evaluate(async function() { let result = await page.evaluate(async function() {
return await callController(3, 5); return await callController(3, 5);
}); });
expect(result).toBe(15); expect(result).toBe(15);
@ -141,7 +141,7 @@ describe('Puppeteer', function() {
expect(request.postData()).toBe(undefined); expect(request.postData()).toBe(undefined);
request.continue(); request.continue();
}); });
var success = await page.navigate(EMPTY_PAGE); let success = await page.navigate(EMPTY_PAGE);
expect(success).toBe(true); expect(success).toBe(true);
})); }));
it('should show extraHTTPHeaders', SX(async function() { it('should show extraHTTPHeaders', SX(async function() {
@ -152,7 +152,7 @@ describe('Puppeteer', function() {
expect(request.headers()['foo']).toBe('bar'); expect(request.headers()['foo']).toBe('bar');
request.continue(); request.continue();
}); });
var success = await page.navigate(EMPTY_PAGE); let success = await page.navigate(EMPTY_PAGE);
expect(success).toBe(true); expect(success).toBe(true);
})); }));
it('should be abortable', SX(async function() { it('should be abortable', SX(async function() {
@ -162,9 +162,9 @@ describe('Puppeteer', function() {
else else
request.continue(); request.continue();
}); });
var failedResources = 0; let failedResources = 0;
page.on('resourceloadingfailed', event => ++failedResources); page.on('resourceloadingfailed', event => ++failedResources);
var success = await page.navigate(STATIC_PREFIX + '/one-style.html'); let success = await page.navigate(STATIC_PREFIX + '/one-style.html');
expect(success).toBe(true); expect(success).toBe(true);
expect(failedResources).toBe(1); expect(failedResources).toBe(1);
})); }));
@ -186,7 +186,7 @@ describe('Puppeteer', function() {
expect(dialog.message()).toBe('question?'); expect(dialog.message()).toBe('question?');
dialog.accept('answer!'); dialog.accept('answer!');
}); });
var result = await page.evaluate(() => prompt('question?')); let result = await page.evaluate(() => prompt('question?'));
expect(result).toBe('answer!'); expect(result).toBe('answer!');
})); }));
}); });
@ -205,13 +205,13 @@ describe('Puppeteer', function() {
it('should work', SX(async function() { it('should work', SX(async function() {
await page.setViewportSize({width: 500, height: 500}); await page.setViewportSize({width: 500, height: 500});
await page.navigate(STATIC_PREFIX + '/grid.html'); await page.navigate(STATIC_PREFIX + '/grid.html');
var screenshot = await page.screenshot(); let screenshot = await page.screenshot();
expect(screenshot).toBeGolden('screenshot-sanity.png'); expect(screenshot).toBeGolden('screenshot-sanity.png');
})); }));
it('should clip rect', SX(async function() { it('should clip rect', SX(async function() {
await page.setViewportSize({width: 500, height: 500}); await page.setViewportSize({width: 500, height: 500});
await page.navigate(STATIC_PREFIX + '/grid.html'); await page.navigate(STATIC_PREFIX + '/grid.html');
var screenshot = await page.screenshot({ let screenshot = await page.screenshot({
clip: { clip: {
x: 50, x: 50,
y: 100, y: 100,
@ -224,7 +224,7 @@ describe('Puppeteer', function() {
it('should work for offscreen clip', SX(async function() { it('should work for offscreen clip', SX(async function() {
await page.setViewportSize({width: 500, height: 500}); await page.setViewportSize({width: 500, height: 500});
await page.navigate(STATIC_PREFIX + '/grid.html'); await page.navigate(STATIC_PREFIX + '/grid.html');
var screenshot = await page.screenshot({ let screenshot = await page.screenshot({
clip: { clip: {
x: 50, x: 50,
y: 600, y: 600,
@ -237,8 +237,8 @@ describe('Puppeteer', function() {
it('should run in parallel', SX(async function() { it('should run in parallel', SX(async function() {
await page.setViewportSize({width: 500, height: 500}); await page.setViewportSize({width: 500, height: 500});
await page.navigate(STATIC_PREFIX + '/grid.html'); await page.navigate(STATIC_PREFIX + '/grid.html');
var promises = []; let promises = [];
for (var i = 0; i < 3; ++i) { for (let i = 0; i < 3; ++i) {
promises.push(page.screenshot({ promises.push(page.screenshot({
clip: { clip: {
x: 50 * i, x: 50 * i,
@ -248,13 +248,13 @@ describe('Puppeteer', function() {
} }
})); }));
} }
var screenshot = await promises[1]; let screenshot = await promises[1];
expect(screenshot).toBeGolden('screenshot-parallel-calls.png'); expect(screenshot).toBeGolden('screenshot-parallel-calls.png');
})); }));
it('should take fullPage screenshots', SX(async function() { it('should take fullPage screenshots', SX(async function() {
await page.setViewportSize({width: 500, height: 500}); await page.setViewportSize({width: 500, height: 500});
await page.navigate(STATIC_PREFIX + '/grid.html'); await page.navigate(STATIC_PREFIX + '/grid.html');
var screenshot = await page.screenshot({ let screenshot = await page.screenshot({
fullPage: true fullPage: true
}); });
expect(screenshot).toBeGolden('screenshot-grid-fullpage.png'); expect(screenshot).toBeGolden('screenshot-grid-fullpage.png');
@ -262,7 +262,7 @@ describe('Puppeteer', function() {
}); });
describe('Frame Management', function() { describe('Frame Management', function() {
var FrameUtils = require('./frame-utils'); let FrameUtils = require('./frame-utils');
it('should handle nested frames', SX(async function() { it('should handle nested frames', SX(async function() {
await page.navigate(STATIC_PREFIX + '/frames/nested-frames.html'); await page.navigate(STATIC_PREFIX + '/frames/nested-frames.html');
expect(FrameUtils.dumpFrames(page.mainFrame())).toBeGolden('nested-frames.txt'); expect(FrameUtils.dumpFrames(page.mainFrame())).toBeGolden('nested-frames.txt');
@ -270,21 +270,21 @@ describe('Puppeteer', function() {
it('should send events when frames are manipulated dynamically', SX(async function() { it('should send events when frames are manipulated dynamically', SX(async function() {
await page.navigate(EMPTY_PAGE); await page.navigate(EMPTY_PAGE);
// validate frameattached events // validate frameattached events
var attachedFrames = []; let attachedFrames = [];
page.on('frameattached', frame => attachedFrames.push(frame)); page.on('frameattached', frame => attachedFrames.push(frame));
await FrameUtils.attachFrame(page, 'frame1', './assets/frame.html'); await FrameUtils.attachFrame(page, 'frame1', './assets/frame.html');
expect(attachedFrames.length).toBe(1); expect(attachedFrames.length).toBe(1);
expect(attachedFrames[0].url()).toContain('/assets/frame.html'); expect(attachedFrames[0].url()).toContain('/assets/frame.html');
// validate framenavigated events // validate framenavigated events
var navigatedFrames = []; let navigatedFrames = [];
page.on('framenavigated', frame => navigatedFrames.push(frame)); page.on('framenavigated', frame => navigatedFrames.push(frame));
await FrameUtils.navigateFrame(page, 'frame1', './empty.html'); await FrameUtils.navigateFrame(page, 'frame1', './empty.html');
expect(navigatedFrames.length).toBe(1); expect(navigatedFrames.length).toBe(1);
expect(navigatedFrames[0].url()).toContain('/empty.html'); expect(navigatedFrames[0].url()).toContain('/empty.html');
// validate framedetached events // validate framedetached events
var detachedFrames = []; let detachedFrames = [];
page.on('framedetached', frame => detachedFrames.push(frame)); page.on('framedetached', frame => detachedFrames.push(frame));
await FrameUtils.detachFrame(page, 'frame1'); await FrameUtils.detachFrame(page, 'frame1');
expect(detachedFrames.length).toBe(1); expect(detachedFrames.length).toBe(1);
@ -292,21 +292,21 @@ describe('Puppeteer', function() {
})); }));
it('should persist mainFrame on cross-process navigation', SX(async function() { it('should persist mainFrame on cross-process navigation', SX(async function() {
await page.navigate(EMPTY_PAGE); await page.navigate(EMPTY_PAGE);
var mainFrame = page.mainFrame(); let mainFrame = page.mainFrame();
await page.navigate('http://127.0.0.1:' + PORT + '/empty.html'); await page.navigate('http://127.0.0.1:' + PORT + '/empty.html');
expect(page.mainFrame() === mainFrame).toBeTruthy(); expect(page.mainFrame() === mainFrame).toBeTruthy();
})); }));
it('should not send attach/detach events for main frame', SX(async function() { it('should not send attach/detach events for main frame', SX(async function() {
var hasEvents = false; let hasEvents = false;
page.on('frameattached', frame => hasEvents = true); page.on('frameattached', frame => hasEvents = true);
page.on('framedetached', frame => hasEvents = true); page.on('framedetached', frame => hasEvents = true);
await page.navigate(EMPTY_PAGE); await page.navigate(EMPTY_PAGE);
expect(hasEvents).toBe(false); expect(hasEvents).toBe(false);
})); }));
it('should detach child frames on navigation', SX(async function() { it('should detach child frames on navigation', SX(async function() {
var attachedFrames = []; let attachedFrames = [];
var detachedFrames = []; let detachedFrames = [];
var navigatedFrames = []; let navigatedFrames = [];
page.on('frameattached', frame => attachedFrames.push(frame)); page.on('frameattached', frame => attachedFrames.push(frame));
page.on('framedetached', frame => detachedFrames.push(frame)); page.on('framedetached', frame => detachedFrames.push(frame));
page.on('framenavigated', frame => navigatedFrames.push(frame)); page.on('framenavigated', frame => navigatedFrames.push(frame));
@ -315,9 +315,9 @@ describe('Puppeteer', function() {
expect(detachedFrames.length).toBe(0); expect(detachedFrames.length).toBe(0);
expect(navigatedFrames.length).toBe(5); expect(navigatedFrames.length).toBe(5);
var attachedFrames = []; attachedFrames = [];
var detachedFrames = []; detachedFrames = [];
var navigatedFrames = []; navigatedFrames = [];
await page.navigate(EMPTY_PAGE); await page.navigate(EMPTY_PAGE);
expect(attachedFrames.length).toBe(0); expect(attachedFrames.length).toBe(0);
expect(detachedFrames.length).toBe(4); expect(detachedFrames.length).toBe(4);

View File

@ -14,17 +14,17 @@
* limitations under the License. * limitations under the License.
*/ */
var os = require('os'); let os = require('os');
var https = require('https'); let https = require('https');
var fs = require('fs'); let fs = require('fs');
var path = require('path'); let path = require('path');
var extract = require('extract-zip'); let extract = require('extract-zip');
var util = require('util'); let util = require('util');
var URL = require('url'); let URL = require('url');
var CHROMIUM_PATH = path.join(__dirname, '..', '.local-chromium'); let CHROMIUM_PATH = path.join(__dirname, '..', '.local-chromium');
var downloadURLs = { let downloadURLs = {
linux: 'https://storage.googleapis.com/chromium-browser-snapshots/Linux_x64/%d/chrome-linux.zip', linux: 'https://storage.googleapis.com/chromium-browser-snapshots/Linux_x64/%d/chrome-linux.zip',
mac: 'https://storage.googleapis.com/chromium-browser-snapshots/Mac/%d/chrome-mac.zip', mac: 'https://storage.googleapis.com/chromium-browser-snapshots/Mac/%d/chrome-mac.zip',
win32: 'https://storage.googleapis.com/chromium-browser-snapshots/Win/%d/chrome-win32.zip', win32: 'https://storage.googleapis.com/chromium-browser-snapshots/Win/%d/chrome-win32.zip',
@ -43,7 +43,7 @@ module.exports = {
* @return {string} * @return {string}
*/ */
currentPlatform: function() { currentPlatform: function() {
var platform = os.platform(); let platform = os.platform();
if (platform === 'darwin') if (platform === 'darwin')
return 'mac'; return 'mac';
if (platform === 'linux') if (platform === 'linux')
@ -60,15 +60,15 @@ module.exports = {
*/ */
canDownloadRevision: function(platform, revision) { canDownloadRevision: function(platform, revision) {
console.assert(downloadURLs[platform], 'Unknown platform: ' + platform); console.assert(downloadURLs[platform], 'Unknown platform: ' + platform);
var url = URL.parse(util.format(downloadURLs[platform], revision)); let url = URL.parse(util.format(downloadURLs[platform], revision));
var options = { let options = {
method: 'HEAD', method: 'HEAD',
host: url.host, host: url.host,
path: url.pathname, path: url.pathname,
}; };
var resolve; let resolve;
var promise = new Promise(x => resolve = x); let promise = new Promise(x => resolve = x);
var request = https.request(options, response => { let request = https.request(options, response => {
resolve(response.statusCode === 200); resolve(response.statusCode === 200);
}); });
request.on('error', error => { request.on('error', error => {
@ -86,11 +86,11 @@ module.exports = {
* @return {!Promise} * @return {!Promise}
*/ */
downloadRevision: async function(platform, revision, progressCallback) { downloadRevision: async function(platform, revision, progressCallback) {
var url = downloadURLs[platform]; let url = downloadURLs[platform];
console.assert(url, `Unsupported platform: ${platform}`); console.assert(url, `Unsupported platform: ${platform}`);
url = util.format(url, revision); url = util.format(url, revision);
var zipPath = path.join(CHROMIUM_PATH, `download-${platform}-${revision}.zip`); let zipPath = path.join(CHROMIUM_PATH, `download-${platform}-${revision}.zip`);
var folderPath = getFolderPath(platform, revision); let folderPath = getFolderPath(platform, revision);
if (fs.existsSync(folderPath)) if (fs.existsSync(folderPath))
return; return;
try { try {
@ -110,10 +110,10 @@ module.exports = {
* @return {?{executablePath: string}} * @return {?{executablePath: string}}
*/ */
revisionInfo: function(platform, revision) { revisionInfo: function(platform, revision) {
var folderPath = getFolderPath(platform, revision); let folderPath = getFolderPath(platform, revision);
if (!fs.existsSync(folderPath)) if (!fs.existsSync(folderPath))
return null; return null;
var executablePath = ''; let executablePath = '';
if (platform === 'mac') if (platform === 'mac')
executablePath = path.join(folderPath, 'chrome-mac', 'Chromium.app', 'Contents', 'MacOS', 'Chromium'); executablePath = path.join(folderPath, 'chrome-mac', 'Chromium.app', 'Contents', 'MacOS', 'Chromium');
else if (platform === 'linux') else if (platform === 'linux')
@ -144,21 +144,21 @@ function getFolderPath(platform, revision) {
* @return {!Promise} * @return {!Promise}
*/ */
function downloadFile(url, destinationPath, progressCallback) { function downloadFile(url, destinationPath, progressCallback) {
var fulfill, reject; let fulfill, reject;
var promise = new Promise((x, y) => { fulfill = x; reject = y; }); let promise = new Promise((x, y) => { fulfill = x; reject = y; });
var request = https.get(url, response => { let request = https.get(url, response => {
if (response.statusCode !== 200) { if (response.statusCode !== 200) {
var error = new Error(`Download failed: server returned code ${response.statusCode}. URL: ${url}`); let error = new Error(`Download failed: server returned code ${response.statusCode}. URL: ${url}`);
// consume response data to free up memory // consume response data to free up memory
response.resume(); response.resume();
reject(error); reject(error);
return; return;
} }
var file = fs.createWriteStream(destinationPath); let file = fs.createWriteStream(destinationPath);
file.on('finish', () => fulfill()); file.on('finish', () => fulfill());
file.on('error', error => reject(error)); file.on('error', error => reject(error));
response.pipe(file); response.pipe(file);
var totalBytes = parseInt(response.headers['content-length'], 10); let totalBytes = parseInt(response.headers['content-length'], 10);
if (progressCallback) if (progressCallback)
response.on('data', onData.bind(null, totalBytes)); response.on('data', onData.bind(null, totalBytes));
}); });

View File

@ -15,11 +15,11 @@
* limitations under the License. * limitations under the License.
*/ */
var Downloader = require('./ChromiumDownloader'); let Downloader = require('./ChromiumDownloader');
var https = require('https'); let https = require('https');
var OMAHA_PROXY = 'https://omahaproxy.appspot.com/all.json'; let OMAHA_PROXY = 'https://omahaproxy.appspot.com/all.json';
var colors = { let colors = {
reset: '\x1b[0m', reset: '\x1b[0m',
red: '\x1b[31m', red: '\x1b[31m',
green: '\x1b[32m', green: '\x1b[32m',
@ -39,8 +39,8 @@ class Table {
*/ */
drawRow(values) { drawRow(values) {
console.assert(values.length === this.widths.length); console.assert(values.length === this.widths.length);
var row = ''; let row = '';
for (var i = 0; i < values.length; ++i) for (let i = 0; i < values.length; ++i)
row += padCenter(values[i], this.widths[i]); row += padCenter(values[i], this.widths[i]);
console.log(row); console.log(row);
} }
@ -59,8 +59,8 @@ Running command without arguments will check against omahaproxy revisions.`);
return; return;
} }
var fromRevision = parseInt(process.argv[2], 10); let fromRevision = parseInt(process.argv[2], 10);
var toRevision = parseInt(process.argv[3], 10); let toRevision = parseInt(process.argv[3], 10);
checkRangeAvailability(fromRevision, toRevision); checkRangeAvailability(fromRevision, toRevision);
/** /**
@ -68,23 +68,23 @@ checkRangeAvailability(fromRevision, toRevision);
*/ */
async function checkOmahaProxyAvailability() { async function checkOmahaProxyAvailability() {
console.log('Fetching revisions from ' + OMAHA_PROXY); console.log('Fetching revisions from ' + OMAHA_PROXY);
var platforms = await loadJSON(OMAHA_PROXY); let platforms = await loadJSON(OMAHA_PROXY);
if (!platforms) { if (!platforms) {
console.error('ERROR: failed to fetch chromium revisions from omahaproxy.'); console.error('ERROR: failed to fetch chromium revisions from omahaproxy.');
return; return;
} }
var table = new Table([27, 7, 7, 7, 7]); let table = new Table([27, 7, 7, 7, 7]);
table.drawRow([''].concat(Downloader.supportedPlatforms())); table.drawRow([''].concat(Downloader.supportedPlatforms()));
for (var platform of platforms) { for (let platform of platforms) {
// Trust only to the main platforms. // Trust only to the main platforms.
if (platform.os !== 'mac' && platform.os !== 'win' && platform.os !== 'win64' && platform.os !== 'linux') if (platform.os !== 'mac' && platform.os !== 'win' && platform.os !== 'win64' && platform.os !== 'linux')
continue; continue;
var osName = platform.os === 'win' ? 'win32' : platform.os; let osName = platform.os === 'win' ? 'win32' : platform.os;
for (var version of platform.versions) { for (let version of platform.versions) {
if (version.channel !== 'dev' && version.channel !== 'beta' && version.channel !== 'canary' && version.channel !== 'stable') if (version.channel !== 'dev' && version.channel !== 'beta' && version.channel !== 'canary' && version.channel !== 'stable')
continue; continue;
var revisionName = padLeft('[' + osName + ' ' + version.channel + ']', 15); let revisionName = padLeft('[' + osName + ' ' + version.channel + ']', 15);
var revision = parseInt(version.branch_base_position, 10); let revision = parseInt(version.branch_base_position, 10);
await checkAndDrawRevisionAvailability(table, revisionName, revision); await checkAndDrawRevisionAvailability(table, revisionName, revision);
} }
} }
@ -96,10 +96,10 @@ async function checkOmahaProxyAvailability() {
* @return {!Promise} * @return {!Promise}
*/ */
async function checkRangeAvailability(fromRevision, toRevision) { async function checkRangeAvailability(fromRevision, toRevision) {
var table = new Table([10, 7, 7, 7, 7]); let table = new Table([10, 7, 7, 7, 7]);
table.drawRow([''].concat(Downloader.supportedPlatforms())); table.drawRow([''].concat(Downloader.supportedPlatforms()));
var inc = fromRevision < toRevision ? 1 : -1; let inc = fromRevision < toRevision ? 1 : -1;
for (var revision = fromRevision; revision !== toRevision; revision += inc) for (let revision = fromRevision; revision !== toRevision; revision += inc)
await checkAndDrawRevisionAvailability(table, '', revision); await checkAndDrawRevisionAvailability(table, '', revision);
} }
@ -110,15 +110,15 @@ async function checkRangeAvailability(fromRevision, toRevision) {
* @return {!Promise} * @return {!Promise}
*/ */
async function checkAndDrawRevisionAvailability(table, name, revision) { async function checkAndDrawRevisionAvailability(table, name, revision) {
var promises = []; let promises = [];
for (var platform of Downloader.supportedPlatforms()) for (let platform of Downloader.supportedPlatforms())
promises.push(Downloader.canDownloadRevision(platform, revision)); promises.push(Downloader.canDownloadRevision(platform, revision));
var availability = await Promise.all(promises); let availability = await Promise.all(promises);
var allAvailable = availability.every(e => !!e); let allAvailable = availability.every(e => !!e);
var values = [name + ' ' + (allAvailable ? colors.green + revision + colors.reset : revision)]; let values = [name + ' ' + (allAvailable ? colors.green + revision + colors.reset : revision)];
for (var i = 0; i < availability.length; ++i) { for (let i = 0; i < availability.length; ++i) {
var decoration = availability[i] ? '+' : '-'; let decoration = availability[i] ? '+' : '-';
var color = availability[i] ? colors.green : colors.red; let color = availability[i] ? colors.green : colors.red;
values.push(color + decoration + colors.reset); values.push(color + decoration + colors.reset);
} }
table.drawRow(values); table.drawRow(values);
@ -129,19 +129,19 @@ async function checkAndDrawRevisionAvailability(table, name, revision) {
* @return {!Promise<?Object>} * @return {!Promise<?Object>}
*/ */
function loadJSON(url) { function loadJSON(url) {
var resolve; let resolve;
var promise = new Promise(x => resolve = x); let promise = new Promise(x => resolve = x);
https.get(url, response => { https.get(url, response => {
if (response.statusCode !== 200) { if (response.statusCode !== 200) {
resolve(null); resolve(null);
return; return;
} }
var body = ''; let body = '';
response.on('data', function(chunk){ response.on('data', function(chunk){
body += chunk; body += chunk;
}); });
response.on('end', function(){ response.on('end', function(){
var json = JSON.parse(body); let json = JSON.parse(body);
resolve(json); resolve(json);
}); });
}).on('error', function(e){ }).on('error', function(e){
@ -164,8 +164,8 @@ function spaceString(size) {
* @return {string} * @return {string}
*/ */
function filterOutColors(text) { function filterOutColors(text) {
for (var colorName in colors) { for (let colorName in colors) {
var color = colors[colorName]; let color = colors[colorName];
text = text.replace(color, ''); text = text.replace(color, '');
} }
return text; return text;
@ -177,7 +177,7 @@ function filterOutColors(text) {
* @return {string} * @return {string}
*/ */
function padLeft(text, length) { function padLeft(text, length) {
var printableCharacters = filterOutColors(text); let printableCharacters = filterOutColors(text);
return printableCharacters.length >= length ? text : spaceString(length - text.length) + text; return printableCharacters.length >= length ? text : spaceString(length - text.length) + text;
} }
@ -187,10 +187,10 @@ function padLeft(text, length) {
* @return {string} * @return {string}
*/ */
function padCenter(text, length) { function padCenter(text, length) {
var printableCharacters = filterOutColors(text); let printableCharacters = filterOutColors(text);
if (printableCharacters.length >= length) if (printableCharacters.length >= length)
return text; return text;
var left = Math.floor((length - printableCharacters.length) / 2); let left = Math.floor((length - printableCharacters.length) / 2);
var right = Math.ceil((length - printableCharacters.length) / 2); let right = Math.ceil((length - printableCharacters.length) / 2);
return spaceString(left) + text + spaceString(right); return spaceString(left) + text + spaceString(right);
} }