Commit 15b11fce authored by Robert Knight's avatar Robert Knight

Replace "var" with "const" or "let" everywhere

This is the result of using jscodeshift [1] to apply the "no-vars"
transform from js-codemod [2] on all code in scripts/ and to gulpfile.js

[1] https://github.com/facebook/jscodeshift
[2] https://github.com/cpojer/js-codemod
parent 920be1a3
......@@ -2,42 +2,42 @@
'use strict';
var path = require('path');
var batch = require('gulp-batch');
var changed = require('gulp-changed');
var commander = require('commander');
var debounce = require('lodash.debounce');
var endOfStream = require('end-of-stream');
var gulp = require('gulp');
var gulpIf = require('gulp-if');
var gulpUtil = require('gulp-util');
var postcss = require('gulp-postcss');
var postcssURL = require('postcss-url');
var replace = require('gulp-replace');
var rename = require('gulp-rename');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var through = require('through2');
var createBundle = require('./scripts/gulp/create-bundle');
var manifest = require('./scripts/gulp/manifest');
var servePackage = require('./scripts/gulp/serve-package');
var vendorBundles = require('./scripts/gulp/vendor-bundles');
var IS_PRODUCTION_BUILD = process.env.NODE_ENV === 'production';
var SCRIPT_DIR = 'build/scripts';
var STYLE_DIR = 'build/styles';
var FONTS_DIR = 'build/fonts';
var IMAGES_DIR = 'build/images';
var TEMPLATES_DIR = 'src/sidebar/templates';
const path = require('path');
const batch = require('gulp-batch');
const changed = require('gulp-changed');
const commander = require('commander');
const debounce = require('lodash.debounce');
const endOfStream = require('end-of-stream');
const gulp = require('gulp');
const gulpIf = require('gulp-if');
const gulpUtil = require('gulp-util');
const postcss = require('gulp-postcss');
const postcssURL = require('postcss-url');
const replace = require('gulp-replace');
const rename = require('gulp-rename');
const sass = require('gulp-sass');
const sourcemaps = require('gulp-sourcemaps');
const through = require('through2');
const createBundle = require('./scripts/gulp/create-bundle');
const manifest = require('./scripts/gulp/manifest');
const servePackage = require('./scripts/gulp/serve-package');
const vendorBundles = require('./scripts/gulp/vendor-bundles');
const IS_PRODUCTION_BUILD = process.env.NODE_ENV === 'production';
const SCRIPT_DIR = 'build/scripts';
const STYLE_DIR = 'build/styles';
const FONTS_DIR = 'build/fonts';
const IMAGES_DIR = 'build/images';
const TEMPLATES_DIR = 'src/sidebar/templates';
// LiveReloadServer instance for sending messages to connected
// development clients
var liveReloadServer;
let liveReloadServer;
// List of file paths that changed since the last live-reload
// notification was dispatched
var liveReloadChangedFiles = [];
let liveReloadChangedFiles = [];
function parseCommandLine() {
commander
......@@ -55,7 +55,7 @@ function parseCommandLine() {
};
}
var taskArgs = parseCommandLine();
const taskArgs = parseCommandLine();
function isSASSFile(file) {
return file.path.match(/\.scss$/);
......@@ -69,14 +69,14 @@ function getEnv(key) {
}
/** A list of all modules included in vendor bundles. */
var vendorModules = Object.keys(vendorBundles.bundles)
const vendorModules = Object.keys(vendorBundles.bundles)
.reduce(function (deps, key) {
return deps.concat(vendorBundles.bundles[key]);
}, []);
// Builds the bundles containing vendor JS code
gulp.task('build-vendor-js', function () {
var finished = [];
const finished = [];
Object.keys(vendorBundles.bundles).forEach(function (name) {
finished.push(createBundle({
name: name,
......@@ -89,14 +89,14 @@ gulp.task('build-vendor-js', function () {
return Promise.all(finished);
});
var appBundleBaseConfig = {
const appBundleBaseConfig = {
path: SCRIPT_DIR,
external: vendorModules,
minify: IS_PRODUCTION_BUILD,
noParse: vendorBundles.noParseModules,
};
var appBundles = [{
const appBundles = [{
// The entry point for both the Hypothesis client and the sidebar
// application. This is responsible for loading the rest of the assets needed
// by the client.
......@@ -116,7 +116,7 @@ var appBundles = [{
transforms: ['babel', 'coffee'],
}];
var appBundleConfigs = appBundles.map(function (config) {
const appBundleConfigs = appBundles.map(function (config) {
return Object.assign({}, appBundleBaseConfig, config);
});
......@@ -132,7 +132,7 @@ gulp.task('watch-js', ['build-vendor-js'], function () {
});
});
var styleFiles = [
const styleFiles = [
// H
'./src/styles/annotator/annotator.scss',
'./src/styles/annotator/pdfjs-overrides.scss',
......@@ -152,11 +152,11 @@ gulp.task('build-css', function () {
return url.replace(/^fonts\//, '../fonts/');
}
var sassOpts = {
const sassOpts = {
outputStyle: IS_PRODUCTION_BUILD ? 'compressed' : 'nested',
};
var cssURLRewriter = postcssURL({
const cssURLRewriter = postcssURL({
url: rewriteCSSURL,
});
......@@ -169,17 +169,17 @@ gulp.task('build-css', function () {
});
gulp.task('watch-css', ['build-css'], function () {
var vendorCSS = styleFiles.filter(function (path) {
const vendorCSS = styleFiles.filter(function (path) {
return path.endsWith('.css');
});
var styleFileGlobs = vendorCSS.concat('./src/styles/**/*.scss');
const styleFileGlobs = vendorCSS.concat('./src/styles/**/*.scss');
gulp.watch(styleFileGlobs, ['build-css']);
});
var fontFiles = ['src/styles/vendor/fonts/*.woff',
'node_modules/katex/dist/fonts/*.woff',
'node_modules/katex/dist/fonts/*.woff2'];
const fontFiles = ['src/styles/vendor/fonts/*.woff',
'node_modules/katex/dist/fonts/*.woff',
'node_modules/katex/dist/fonts/*.woff2'];
gulp.task('build-fonts', function () {
gulp.src(fontFiles)
......@@ -191,7 +191,7 @@ gulp.task('watch-fonts', ['build-fonts'], function () {
gulp.watch(fontFiles, ['build-fonts']);
});
var imageFiles = 'src/images/**/*';
const imageFiles = 'src/images/**/*';
gulp.task('build-images', function () {
gulp.src(imageFiles)
.pipe(changed(IMAGES_DIR))
......@@ -208,9 +208,9 @@ gulp.task('watch-templates', function () {
});
});
var MANIFEST_SOURCE_FILES = 'build/@(fonts|images|scripts|styles)/*.@(js|css|woff|jpg|png|svg)';
const MANIFEST_SOURCE_FILES = 'build/@(fonts|images|scripts|styles)/*.@(js|css|woff|jpg|png|svg)';
var prevManifest = {};
let prevManifest = {};
/**
* Return an array of asset paths that changed between
......@@ -222,7 +222,7 @@ function changedAssets(prevManifest, newManifest) {
});
}
var debouncedLiveReload = debounce(function () {
const debouncedLiveReload = debounce(function () {
// Notify dev clients about the changed assets. Note: This currently has an
// issue that if CSS, JS and templates are all changed in quick succession,
// some of the assets might be empty/incomplete files that are still being
......@@ -253,7 +253,7 @@ function packageServerHostname() {
return process.env.PACKAGE_SERVER_HOSTNAME || 'localhost';
}
var isFirstBuild = true;
let isFirstBuild = true;
/**
* Generates the `build/boot.js` script which serves as the entry point for
......@@ -262,12 +262,12 @@ var isFirstBuild = true;
* @param {Object} manifest - Manifest mapping asset paths to cache-busted URLs
*/
function generateBootScript(manifest) {
var { version } = require('./package.json');
const { version } = require('./package.json');
var defaultSidebarAppUrl = process.env.SIDEBAR_APP_URL ?
const defaultSidebarAppUrl = process.env.SIDEBAR_APP_URL ?
`${process.env.SIDEBAR_APP_URL}` : 'https://hypothes.is/app.html';
var defaultAssetRoot;
let defaultAssetRoot;
if (process.env.NODE_ENV === 'production') {
defaultAssetRoot = `https://cdn.hypothes.is/hypothesis/${version}/`;
......@@ -301,8 +301,8 @@ function generateManifest() {
.pipe(manifest({name: 'manifest.json'}))
.pipe(through.obj(function (file, enc, callback) {
// Trigger a reload of the client in the dev server at localhost:3000
var newManifest = JSON.parse(file.contents.toString());
var changed = changedAssets(prevManifest, newManifest);
const newManifest = JSON.parse(file.contents.toString());
const changed = changedAssets(prevManifest, newManifest);
prevManifest = newManifest;
triggerLiveReload(changed);
......@@ -324,7 +324,7 @@ gulp.task('watch-manifest', function () {
});
gulp.task('serve-live-reload', ['serve-package'], function () {
var LiveReloadServer = require('./scripts/gulp/live-reload-server');
const LiveReloadServer = require('./scripts/gulp/live-reload-server');
liveReloadServer = new LiveReloadServer(3000, {
clientUrl: `http://${packageServerHostname()}:3001/hypothesis`,
});
......@@ -351,7 +351,7 @@ gulp.task('watch', ['serve-package',
function runKarma(baseConfig, opts, done) {
// See https://github.com/karma-runner/karma-mocha#configuration
var cliOpts = {
const cliOpts = {
client: {
mocha: {
grep: taskArgs.grep,
......@@ -362,12 +362,12 @@ function runKarma(baseConfig, opts, done) {
// Work around a bug in Karma 1.10 which causes console log messages not to
// be displayed when using a non-default reporter.
// See https://github.com/karma-runner/karma/pull/2220
var BaseReporter = require('karma/lib/reporters/base');
const BaseReporter = require('karma/lib/reporters/base');
BaseReporter.decoratorFactory.$inject =
BaseReporter.decoratorFactory.$inject.map(dep =>
dep.replace('browserLogOptions', 'browserConsoleLogOptions'));
var karma = require('karma');
const karma = require('karma');
new karma.Server(Object.assign({}, {
configFile: path.resolve(__dirname, baseConfig),
}, cliOpts, opts), done).start();
......@@ -382,14 +382,14 @@ gulp.task('test-watch', function (callback) {
});
gulp.task('upload-sourcemaps', ['build-js'], function () {
var uploadToSentry = require('./scripts/gulp/upload-to-sentry');
const uploadToSentry = require('./scripts/gulp/upload-to-sentry');
var opts = {
const opts = {
key: getEnv('SENTRY_API_KEY'),
organization: getEnv('SENTRY_ORGANIZATION'),
};
var projects = getEnv('SENTRY_PROJECTS').split(',');
var release = getEnv('SENTRY_RELEASE_VERSION');
const projects = getEnv('SENTRY_PROJECTS').split(',');
const release = getEnv('SENTRY_RELEASE_VERSION');
return gulp.src(['build/scripts/*.js', 'build/scripts/*.map'])
.pipe(uploadToSentry(opts, projects, release));
......
......@@ -37,19 +37,19 @@
// the last expression in a function, so the generated
// JS source has to do the same.
var Checker = require('jscs');
var babylon = require('babylon');
var decaffeinate = require('decaffeinate');
var fs = require('fs');
var path = require('path');
var typescriptFormatter = require('typescript-formatter');
const Checker = require('jscs');
const babylon = require('babylon');
const decaffeinate = require('decaffeinate');
const fs = require('fs');
const path = require('path');
const typescriptFormatter = require('typescript-formatter');
var inFile = process.argv[2];
const inFile = process.argv[2];
var jscsConfigPath = require.resolve('../../.jscsrc');
var jscsConfig = JSON.parse(fs.readFileSync(jscsConfigPath, 'utf-8'));
const jscsConfigPath = require.resolve('../../.jscsrc');
const jscsConfig = JSON.parse(fs.readFileSync(jscsConfigPath, 'utf-8'));
var stripReturnPatterns = [
const stripReturnPatterns = [
// Unit test cases
/it\(/,
// Assignments in setters etc.
......@@ -75,10 +75,10 @@ function stripUnnecessaryReturns(js) {
// If we need something more sophisticated, we shouldn't modify the
// source as a string but should instead write a Babel code transformer.
return js.split('\n').map(line => {
var returnPrefix = 'return ';
const returnPrefix = 'return ';
if (line.trim().startsWith(returnPrefix)) {
var remainder = line.trim().slice(returnPrefix.length);
for (var i=0; i < stripReturnPatterns.length; i++) {
const remainder = line.trim().slice(returnPrefix.length);
for (let i=0; i < stripReturnPatterns.length; i++) {
if (remainder.match(stripReturnPatterns[i])) {
return remainder;
}
......@@ -101,9 +101,9 @@ function checkSyntax(js) {
try {
babylon.parse(js, {sourceType: 'module'});
} catch (err) {
var context = js.split('\n').reduce((context, line, index) => {
var lineNumber = index+1;
var linePrefix;
const context = js.split('\n').reduce((context, line, index) => {
const lineNumber = index+1;
let linePrefix;
if (lineNumber === err.loc.line) {
linePrefix = `**${lineNumber}`;
} else {
......@@ -147,7 +147,7 @@ function reformat(js) {
return result.dest;
})
.then(result => {
var checker = new Checker();
const checker = new Checker();
checker.configure(jscsConfig);
return checker.fixString(result).output;
});
......@@ -164,7 +164,7 @@ function toResultOrError(promise) {
function convertFile(inFile, outFile) {
console.log('Converting', inFile);
var js;
let js;
try {
js = decaffeinate.convert(
......@@ -179,10 +179,10 @@ function convertFile(inFile, outFile) {
});
}
var conversions = [];
const conversions = [];
process.argv.slice(2).forEach(filePath => {
var inFile = path.resolve(filePath);
var outFile = inFile.replace(/\.coffee$/, '.js');
const inFile = path.resolve(filePath);
const outFile = inFile.replace(/\.coffee$/, '.js');
conversions.push(toResultOrError(convertFile(inFile, outFile)).then(function (result) {
result.fileName = inFile;
return result;
......@@ -190,8 +190,8 @@ process.argv.slice(2).forEach(filePath => {
});
Promise.all(conversions).then(results => {
var ok = 0;
var failed = 0;
let ok = 0;
let failed = 0;
results.forEach(result => {
if (result.error) {
console.log('Error converting %s: \n\n%s', result.fileName, result.error.message);
......
......@@ -3,19 +3,19 @@
*/
'use strict';
var fs = require('fs');
var path = require('path');
const fs = require('fs');
const path = require('path');
var babelify = require('babelify');
var browserify = require('browserify');
var coffeeify = require('coffeeify');
var exorcist = require('exorcist');
var gulpUtil = require('gulp-util');
var mkdirp = require('mkdirp');
var uglifyify = require('uglifyify');
var watchify = require('watchify');
const babelify = require('babelify');
const browserify = require('browserify');
const coffeeify = require('coffeeify');
const exorcist = require('exorcist');
const gulpUtil = require('gulp-util');
const mkdirp = require('mkdirp');
const uglifyify = require('uglifyify');
const watchify = require('watchify');
var log = gulpUtil.log;
const log = gulpUtil.log;
function streamFinished(stream) {
return new Promise(function (resolve, reject) {
......@@ -65,7 +65,7 @@ module.exports = function createBundle(config, buildOpts) {
buildOpts = buildOpts || {watch: false};
var bundleOpts = {
const bundleOpts = {
debug: true,
extensions: ['.coffee'],
......@@ -115,7 +115,7 @@ module.exports = function createBundle(config, buildOpts) {
bundleOpts.noParse = (config.noParse || []).map(function (id) {
// If package.json specifies a custom entry point for the module for
// use in the browser, resolve that.
var packageConfig = require('../../package.json');
const packageConfig = require('../../package.json');
if (packageConfig.browser && packageConfig.browser[id]) {
return require.resolve('../../' + packageConfig.browser[id]);
} else {
......@@ -123,13 +123,13 @@ module.exports = function createBundle(config, buildOpts) {
}
});
var name = config.name;
const name = config.name;
var bundleFileName = name + '.bundle.js';
var bundlePath = config.path + '/' + bundleFileName;
var sourcemapPath = bundlePath + '.map';
const bundleFileName = name + '.bundle.js';
const bundlePath = config.path + '/' + bundleFileName;
const sourcemapPath = bundlePath + '.map';
var bundle = browserify([], bundleOpts);
const bundle = browserify([], bundleOpts);
(config.require || []).forEach(function (req) {
// When another bundle uses 'bundle.external(<module path>)',
......@@ -146,8 +146,8 @@ module.exports = function createBundle(config, buildOpts) {
// If the require path is absolute, the same rules as
// above apply but the path needs to be relative to
// the root of the repository
var repoRootPath = path.join(__dirname, '../../');
var relativePath = path.relative(path.resolve(repoRootPath),
const repoRootPath = path.join(__dirname, '../../');
const relativePath = path.relative(path.resolve(repoRootPath),
path.resolve(req));
bundle.require(req, {expose: '/' + relativePath});
} else {
......@@ -174,12 +174,12 @@ module.exports = function createBundle(config, buildOpts) {
}
function build() {
var output = fs.createWriteStream(bundlePath);
var b = bundle.bundle();
const output = fs.createWriteStream(bundlePath);
const b = bundle.bundle();
b.on('error', function (err) {
log('Build error', err.toString());
});
var stream = b.pipe(exorcist(sourcemapPath))
const stream = b.pipe(exorcist(sourcemapPath))
.pipe(output);
return streamFinished(stream);
}
......@@ -187,7 +187,7 @@ module.exports = function createBundle(config, buildOpts) {
if (buildOpts.watch) {
bundle.plugin(watchify);
bundle.on('update', function (ids) {
var start = Date.now();
const start = Date.now();
log('Source files changed', ids);
build().then(function () {
......
'use strict';
var fs = require('fs');
var gulpUtil = require('gulp-util');
var http = require('http');
var WebSocketServer = require('websocket').server;
var urlParser = require('url');
const fs = require('fs');
const gulpUtil = require('gulp-util');
const http = require('http');
const WebSocketServer = require('websocket').server;
const urlParser = require('url');
function readmeText() {
return fs.readFileSync('./README.md', 'utf-8');
......@@ -37,13 +37,13 @@ function changelogText() {
* @constructor
*/
function LiveReloadServer(port, config) {
var connections = [];
let connections = [];
function listen() {
var log = gulpUtil.log;
var server = http.createServer(function (req, response) {
var url = urlParser.parse(req.url);
var content;
const log = gulpUtil.log;
const server = http.createServer(function (req, response) {
const url = urlParser.parse(req.url);
let content;
if (url.pathname === '/document/license') {
content = `
......@@ -145,17 +145,17 @@ function LiveReloadServer(port, config) {
log(`Live reload server listening at http://localhost:${port}/`);
});
var ws = new WebSocketServer({
const ws = new WebSocketServer({
httpServer: server,
});
ws.on('request', function (req) {
log('Live reload client connected');
var conn = req.accept(null, req.origin);
const conn = req.accept(null, req.origin);
connections.push(conn);
conn.on('close', function () {
var closedConn = conn;
const closedConn = conn;
connections = connections.filter(function (conn) {
return conn !== closedConn;
});
......
'use strict';
var path = require('path');
var crypto = require('crypto');
const path = require('path');
const crypto = require('crypto');
var through = require('through2');
var VinylFile = require('vinyl');
const through = require('through2');
const VinylFile = require('vinyl');
/**
* Gulp plugin that generates a cache-busting manifest file.
......@@ -15,19 +15,19 @@ var VinylFile = require('vinyl');
* to URLs with cache-busting query parameters (eg. "scripts/foo.js?af95bd").
*/
module.exports = function (opts) {
var manifest = {};
const manifest = {};
return through.obj(function (file, enc, callback) {
var hash = crypto.createHash('sha1');
const hash = crypto.createHash('sha1');
hash.update(file.contents);
var hashSuffix = hash.digest('hex').slice(0, 6);
var relPath = path.relative('build/', file.path);
const hashSuffix = hash.digest('hex').slice(0, 6);
const relPath = path.relative('build/', file.path);
manifest[relPath] = relPath + '?' + hashSuffix;
callback();
}, function (callback) {
var manifestFile = new VinylFile({
const manifestFile = new VinylFile({
path: opts.name,
contents: Buffer.from(JSON.stringify(manifest, null, 2), 'utf-8'),
});
......
'use strict';
var { readFileSync } = require('fs');
const { readFileSync } = require('fs');
var express = require('express');
var { log } = require('gulp-util');
const express = require('express');
const { log } = require('gulp-util');
var { version } = require('../../package.json');
const { version } = require('../../package.json');
/**
* An express server which serves the contents of the package.
......@@ -19,7 +19,7 @@ var { version } = require('../../package.json');
* app.
*/
function servePackage(port, hostname) {
var app = express();
const app = express();
// Enable CORS for assets so that cross-origin font loading works.
app.use(function (req, res, next) {
......@@ -28,9 +28,9 @@ function servePackage(port, hostname) {
next();
});
var serveBootScript = function (req, res) {
var entryPath = require.resolve('../..');
var entryScript = readFileSync(entryPath).toString('utf-8');
const serveBootScript = function (req, res) {
const entryPath = require.resolve('../..');
const entryScript = readFileSync(entryPath).toString('utf-8');
res.send(entryScript);
};
......
'use strict';
var fs = require('fs');
var path = require('path');
var gulpUtil = require('gulp-util');
var request = require('request');
var through = require('through2');
const fs = require('fs');
const path = require('path');
const gulpUtil = require('gulp-util');
const request = require('request');
const through = require('through2');
var SENTRY_API_ROOT = 'https://app.getsentry.com/api/0';
const SENTRY_API_ROOT = 'https://app.getsentry.com/api/0';
/**
* interface SentryOptions {
......@@ -49,8 +49,8 @@ function createRelease(opts, project, release) {
},
json: true,
}).then(function (result) {
var success = (result.response.statusCode === 201);
var alreadyCreated = (result.response.statusCode === 400 &&
const success = (result.response.statusCode === 201);
const alreadyCreated = (result.response.statusCode === 400 &&
result.body.detail.match(/already exists/));
if (success || alreadyCreated) {
......@@ -99,7 +99,7 @@ function uploadReleaseFile(opts, project, release, file) {
*/
module.exports = function uploadToSentry(opts, projects, release) {
// Create releases in every project
var releases = projects.map(function (project) {
const releases = projects.map(function (project) {
gulpUtil.log(`Creating release '${release}' in project '${project}'`);
return createRelease(opts, project, release);
});
......@@ -108,7 +108,7 @@ module.exports = function uploadToSentry(opts, projects, release) {
Promise.all(releases)
.then(function () {
gulpUtil.log(`Uploading ${path.basename(file.path)}`);
var uploads = projects.map(function (project) {
const uploads = projects.map(function (project) {
return uploadReleaseFile(opts, project, release, file);
});
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment