chore: eslint no-var, vars-on-top

v1.18.x
Peter Jaszkowiak 4 years ago committed by Julian Lam
parent b56d9e12b5
commit dab3b23575

@ -110,8 +110,6 @@
// WORKING ON
"prefer-rest-params": "off",
"prefer-spread": "off",
"no-var": "off",
"vars-on-top": "off",
// TODO
"consistent-return": "off",

@ -10,7 +10,7 @@ const winston = require('winston');
const fork = require('child_process').fork;
const env = process.env;
var worker;
let worker;
env.NODE_ENV = env.NODE_ENV || 'development';
@ -19,10 +19,10 @@ const prestart = require('./src/prestart');
prestart.loadConfig(configFile);
var db = require('./src/database');
const db = require('./src/database');
module.exports = function (grunt) {
var args = [];
const args = [];
if (!grunt.option('verbose')) {
args.push('--log-level=info');
@ -39,7 +39,7 @@ module.exports = function (grunt) {
grunt.registerTask('default', ['watch']);
grunt.registerTask('init', async function () {
var done = this.async();
const done = this.async();
let plugins = [];
if (!process.argv.includes('--core')) {
await db.init();
@ -165,7 +165,7 @@ module.exports = function (grunt) {
grunt.event.removeAllListeners('watch');
grunt.event.on('watch', (action, filepath, target) => {
var compiling;
let compiling;
if (target === 'styleUpdated_Client') {
compiling = 'clientCSS';
} else if (target === 'styleUpdated_Admin') {

@ -83,7 +83,7 @@ function saveDatabaseConfig(config, databaseConfig) {
}
const allQuestions = questions.redis.concat(questions.mongo).concat(questions.postgres);
for (var x = 0; x < allQuestions.length; x += 1) {
for (let x = 0; x < allQuestions.length; x += 1) {
delete config[allQuestions[x].name];
}

@ -27,7 +27,7 @@ const formats = [
];
const timestampFormat = winston.format((info) => {
var dateString = `${new Date().toISOString()} [${global.process.pid}]`;
const dateString = `${new Date().toISOString()} [${global.process.pid}]`;
info.level = `${dateString} - ${info.level}`;
return info;
});
@ -117,9 +117,9 @@ function ping(req, res) {
}
function welcome(req, res) {
var dbs = ['redis', 'mongo', 'postgres'];
var databases = dbs.map((databaseName) => {
var questions = require(`../src/database/${databaseName}`).questions.filter(question => question && !question.hideOnWebInstall);
const dbs = ['redis', 'mongo', 'postgres'];
const databases = dbs.map((databaseName) => {
const questions = require(`../src/database/${databaseName}`).questions.filter(question => question && !question.hideOnWebInstall);
return {
name: databaseName,
@ -127,7 +127,7 @@ function welcome(req, res) {
};
});
var defaults = require('./data/defaults');
const defaults = require('./data/defaults');
res.render('install/index', {
url: nconf.get('url') || (`${req.protocol}://${req.get('host')}`),
@ -150,8 +150,8 @@ function install(req, res) {
}
req.setTimeout(0);
installing = true;
var setupEnvVars = nconf.get();
for (var i in req.body) {
const setupEnvVars = nconf.get();
for (const i in req.body) {
if (req.body.hasOwnProperty(i) && !process.env.hasOwnProperty(i)) {
setupEnvVars[i.replace(':', '__')] = req.body[i];
}
@ -161,7 +161,7 @@ function install(req, res) {
const pushToRoot = function (parentKey, key) {
setupEnvVars[`${parentKey}__${key}`] = setupEnvVars[parentKey][key];
};
for (var j in setupEnvVars) {
for (const j in setupEnvVars) {
if (setupEnvVars.hasOwnProperty(j) && typeof setupEnvVars[j] === 'object' && setupEnvVars[j] !== null && !Array.isArray(setupEnvVars[j])) {
Object.keys(setupEnvVars[j]).forEach(pushToRoot.bind(null, j));
delete setupEnvVars[j];
@ -174,7 +174,7 @@ function install(req, res) {
winston.info(setupEnvVars);
launchUrl = setupEnvVars.url;
var child = require('child_process').fork('app', ['--setup'], {
const child = require('child_process').fork('app', ['--setup'], {
env: setupEnvVars,
});
@ -192,7 +192,7 @@ async function launch(req, res) {
res.json({});
server.close();
req.setTimeout(0);
var child;
let child;
if (!nconf.get('launchCmd')) {
child = childProcess.spawn('node', ['loader.js'], {

@ -1,45 +1,45 @@
'use strict';
var nconf = require('nconf');
var fs = require('fs');
var url = require('url');
var path = require('path');
var fork = require('child_process').fork;
var async = require('async');
var logrotate = require('logrotate-stream');
var mkdirp = require('mkdirp');
const nconf = require('nconf');
const fs = require('fs');
const url = require('url');
const path = require('path');
const fork = require('child_process').fork;
const async = require('async');
const logrotate = require('logrotate-stream');
const mkdirp = require('mkdirp');
var file = require('./src/file');
var pkg = require('./package.json');
const file = require('./src/file');
const pkg = require('./package.json');
var pathToConfig = path.resolve(__dirname, process.env.CONFIG || 'config.json');
const pathToConfig = path.resolve(__dirname, process.env.CONFIG || 'config.json');
nconf.argv().env().file({
file: pathToConfig,
});
var pidFilePath = path.join(__dirname, 'pidfile');
const pidFilePath = path.join(__dirname, 'pidfile');
var outputLogFilePath = path.join(__dirname, nconf.get('logFile') || 'logs/output.log');
const outputLogFilePath = path.join(__dirname, nconf.get('logFile') || 'logs/output.log');
var logDir = path.dirname(outputLogFilePath);
const logDir = path.dirname(outputLogFilePath);
if (!fs.existsSync(logDir)) {
mkdirp.sync(path.dirname(outputLogFilePath));
}
var output = logrotate({ file: outputLogFilePath, size: '1m', keep: 3, compress: true });
var silent = nconf.get('silent') === 'false' ? false : nconf.get('silent') !== false;
var numProcs;
var workers = [];
var Loader = {
const output = logrotate({ file: outputLogFilePath, size: '1m', keep: 3, compress: true });
const silent = nconf.get('silent') === 'false' ? false : nconf.get('silent') !== false;
let numProcs;
const workers = [];
const Loader = {
timesStarted: 0,
};
var appPath = path.join(__dirname, 'app.js');
const appPath = path.join(__dirname, 'app.js');
Loader.init = function (callback) {
if (silent) {
console.log = function () {
var args = Array.prototype.slice.call(arguments);
const args = Array.prototype.slice.call(arguments);
output.write(`${args.join(' ')}\n`);
};
}
@ -112,7 +112,7 @@ Loader.start = function (callback) {
numProcs = getPorts().length;
console.log(`Clustering enabled: Spinning up ${numProcs} process(es).\n`);
for (var x = 0; x < numProcs; x += 1) {
for (let x = 0; x < numProcs; x += 1) {
forkWorker(x, x === 0);
}
@ -122,8 +122,8 @@ Loader.start = function (callback) {
};
function forkWorker(index, isPrimary) {
var ports = getPorts();
var args = [];
const ports = getPorts();
const args = [];
if (!ports[index]) {
return console.log(`[cluster] invalid port for worker : ${index} ports: ${ports.length}`);
@ -133,7 +133,7 @@ function forkWorker(index, isPrimary) {
process.env.isCluster = nconf.get('isCluster') || ports.length > 1;
process.env.port = ports[index];
var worker = fork(appPath, args, {
const worker = fork(appPath, args, {
silent: silent,
env: process.env,
});
@ -146,20 +146,20 @@ function forkWorker(index, isPrimary) {
Loader.addWorkerEvents(worker);
if (silent) {
var output = logrotate({ file: outputLogFilePath, size: '1m', keep: 3, compress: true });
const output = logrotate({ file: outputLogFilePath, size: '1m', keep: 3, compress: true });
worker.stdout.pipe(output);
worker.stderr.pipe(output);
}
}
function getPorts() {
var _url = nconf.get('url');
const _url = nconf.get('url');
if (!_url) {
console.log('[cluster] url is undefined, please check your config.json');
process.exit();
}
var urlObject = url.parse(_url);
var port = nconf.get('PORT') || nconf.get('port') || urlObject.port || 4567;
const urlObject = url.parse(_url);
let port = nconf.get('PORT') || nconf.get('port') || urlObject.port || 4567;
if (!Array.isArray(port)) {
port = [port];
}
@ -178,7 +178,7 @@ Loader.restart = function () {
throw err;
}
var conf = JSON.parse(configFile);
const conf = JSON.parse(configFile);
nconf.stores.env.readOnly = false;
nconf.set('url', conf.url);
@ -217,7 +217,7 @@ fs.open(pathToConfig, 'r', (err) => {
if (nconf.get('daemon') !== 'false' && nconf.get('daemon') !== false) {
if (file.existsSync(pidFilePath)) {
try {
var pid = fs.readFileSync(pidFilePath, { encoding: 'utf-8' });
const pid = fs.readFileSync(pidFilePath, { encoding: 'utf-8' });
process.kill(pid, 0);
process.exit();
} catch (e) {

@ -61,8 +61,8 @@ const fallbackCache = {};
async function initFallback(namespace) {
const template = await fs.promises.readFile(path.resolve(nconf.get('views_dir'), `${namespace}.tpl`), 'utf8');
var title = nsToTitle(namespace);
var translations = sanitize(template);
const title = nsToTitle(namespace);
let translations = sanitize(template);
translations = Translator.removePatterns(translations);
translations = simplify(translations);
translations += `\n${title}`;

@ -65,7 +65,7 @@ exports.doTopicAction = async function (action, event, caller, { tids }) {
async function logTopicAction(action, req, tid, title) {
// Only log certain actions to system event log
var actionsToLog = ['delete', 'restore', 'purge'];
const actionsToLog = ['delete', 'restore', 'purge'];
if (!actionsToLog.includes(action)) {
return;
}

@ -58,7 +58,7 @@ topicsAPI.create = async function (caller, data) {
};
topicsAPI.reply = async function (caller, data) {
var payload = {
const payload = {
tid: data.tid,
uid: caller.uid,
req: apiHelpers.buildReqObject(caller), // For IP recording

@ -1,13 +1,13 @@
'use strict';
var async = require('async');
var db = require('../database');
var batch = require('../batch');
var plugins = require('../plugins');
var topics = require('../topics');
var groups = require('../groups');
var privileges = require('../privileges');
var cache = require('../cache');
const async = require('async');
const db = require('../database');
const batch = require('../batch');
const plugins = require('../plugins');
const topics = require('../topics');
const groups = require('../groups');
const privileges = require('../privileges');
const cache = require('../cache');
module.exports = function (Categories) {
Categories.purge = async function (cid, uid) {

@ -140,7 +140,6 @@ module.exports = function (Categories) {
if (category.posts.length) {
return;
}
const posts = [];
getPostsRecursive(category, posts);

@ -30,9 +30,9 @@ module.exports = function (Categories) {
const result = await plugins.hooks.fire('filter:category.update', { cid: cid, category: modifiedFields });
const category = result.category;
var fields = Object.keys(category);
const fields = Object.keys(category);
// move parent to front, so its updated first
var parentCidIndex = fields.indexOf('parentCid');
const parentCidIndex = fields.indexOf('parentCid');
if (parentCidIndex !== -1 && fields.length > 1) {
fields.splice(0, 0, fields.splice(parentCidIndex, 1)[0]);
}

@ -5,17 +5,17 @@
// to include color styling in the output
// so the CLI looks nice
var Command = require('commander').Command;
const Command = require('commander').Command;
var commandColor = 'yellow';
var optionColor = 'cyan';
var argColor = 'magenta';
var subCommandColor = 'green';
var subOptionColor = 'blue';
var subArgColor = 'red';
const commandColor = 'yellow';
const optionColor = 'cyan';
const argColor = 'magenta';
const subCommandColor = 'green';
const subOptionColor = 'blue';
const subArgColor = 'red';
Command.prototype.helpInformation = function () {
var desc = [];
let desc = [];
if (this._description) {
desc = [
` ${this._description}`,
@ -23,23 +23,23 @@ Command.prototype.helpInformation = function () {
];
}
var cmdName = this._name;
let cmdName = this._name;
if (this._alias) {
cmdName = `${cmdName} | ${this._alias}`;
}
var usage = [
const usage = [
'',
` Usage: ${cmdName[commandColor]}${' '.reset}${this.usage()}`,
'',
];
var cmds = [];
var commandHelp = this.commandHelp();
let cmds = [];
const commandHelp = this.commandHelp();
if (commandHelp) {
cmds = [commandHelp];
}
var options = [
const options = [
'',
' Options:',
'',
@ -55,15 +55,15 @@ Command.prototype.helpInformation = function () {
};
function humanReadableArgName(arg) {
var nameOutput = arg.name + (arg.variadic === true ? '...' : '');
const nameOutput = arg.name + (arg.variadic === true ? '...' : '');
return arg.required ? `<${nameOutput}>` : `[${nameOutput}]`;
}
Command.prototype.usage = function () {
var args = this._args.map(arg => humanReadableArgName(arg));
const args = this._args.map(arg => humanReadableArgName(arg));
var usage = '[options]'[optionColor] +
const usage = '[options]'[optionColor] +
(this.commands.length ? ' [command]' : '')[subCommandColor] +
(this._args.length ? ` ${args.join(' ')}` : '')[argColor];
@ -71,7 +71,7 @@ Command.prototype.usage = function () {
};
function pad(str, width) {
var len = Math.max(0, width - str.length);
const len = Math.max(0, width - str.length);
return str + Array(len + 1).join(' ');
}
@ -80,8 +80,8 @@ Command.prototype.commandHelp = function () {
return '';
}
var commands = this.commands.filter(cmd => !cmd._noHelp).map((cmd) => {
var args = cmd._args.map(arg => humanReadableArgName(arg)).join(' ');
const commands = this.commands.filter(cmd => !cmd._noHelp).map((cmd) => {
const args = cmd._args.map(arg => humanReadableArgName(arg)).join(' ');
return [
`${cmd._name[subCommandColor] +
@ -92,14 +92,14 @@ Command.prototype.commandHelp = function () {
];
});
var width = commands.reduce((max, command) => Math.max(max, command[0].length), 0);
const width = commands.reduce((max, command) => Math.max(max, command[0].length), 0);
return [
'',
' Commands:',
'',
commands.map((cmd) => {
var desc = cmd[1] ? ` ${cmd[1]}` : '';
const desc = cmd[1] ? ` ${cmd[1]}` : '';
return pad(cmd[0], width) + desc;
}).join('\n').replace(/^/gm, ' '),
'',
@ -107,7 +107,7 @@ Command.prototype.commandHelp = function () {
};
Command.prototype.optionHelp = function () {
var width = this.largestOptionLength();
const width = this.largestOptionLength();
// Append the help information
return this.options

@ -54,7 +54,7 @@ function start(options) {
}
// Spawn a new NodeBB process
var child = fork(paths.loader, process.argv.slice(3), {
const child = fork(paths.loader, process.argv.slice(3), {
env: process.env,
cwd,
});

@ -27,7 +27,7 @@ function setup(initConfig) {
return await install.setup();
},
function (next) {
var configFile = paths.config;
let configFile = paths.config;
if (nconf.get('config')) {
configFile = path.resolve(paths.baseDir, nconf.get('config'));
}
@ -44,9 +44,9 @@ function setup(initConfig) {
// Disregard build step data
data = data[0];
var separator = ' ';
let separator = ' ';
if (process.stdout.columns > 10) {
for (var x = 0, cols = process.stdout.columns - 10; x < cols; x += 1) {
for (let x = 0, cols = process.stdout.columns - 10; x < cols; x += 1) {
separator += '=';
}
}

@ -1,15 +1,15 @@
'use strict';
var async = require('async');
var nconf = require('nconf');
const async = require('async');
const nconf = require('nconf');
var packageInstall = require('./package-install');
var upgrade = require('../upgrade');
var build = require('../meta/build');
var db = require('../database');
var upgradePlugins = require('./upgrade-plugins').upgradePlugins;
const packageInstall = require('./package-install');
const upgrade = require('../upgrade');
const build = require('../meta/build');
const db = require('../database');
const upgradePlugins = require('./upgrade-plugins').upgradePlugins;
var steps = {
const steps = {
package: {
message: 'Updating package.json file with defaults...',
handler: function (next) {
@ -67,10 +67,10 @@ function runSteps(tasks) {
throw err;
}
var message = 'NodeBB Upgrade Complete!';
const message = 'NodeBB Upgrade Complete!';
// some consoles will return undefined/zero columns, so just use 2 spaces in upgrade script if we can't get our column count
var columns = process.stdout.columns;
var spaces = columns ? new Array(Math.floor(columns / 2) - (message.length / 2) + 1).join(' ') : ' ';
const columns = process.stdout.columns;
const spaces = columns ? new Array(Math.floor(columns / 2) - (message.length / 2) + 1).join(' ') : ' ';
console.log(`\n\n${spaces}${message.green.bold}${'\n'.reset}`);
@ -85,7 +85,7 @@ function runUpgrade(upgrades, options) {
nconf.set('mongo:options:socketTimeoutMS', 0);
if (upgrades === true) {
var tasks = Object.keys(steps);
let tasks = Object.keys(steps);
if (options.package || options.install ||
options.plugins || options.schema || options.build) {
tasks = tasks.filter(key => options[key]);

@ -1,6 +1,6 @@
'use strict';
var accountsController = {
const accountsController = {
profile: require('./accounts/profile'),
edit: require('./accounts/edit'),
info: require('./accounts/info'),

@ -241,7 +241,7 @@ function filterLinks(links, states) {
canViewInfo: true,
...link.visibility };
var permit = Object.keys(states).some(state => states[state] && link.visibility[state]);
const permit = Object.keys(states).some(state => states[state] && link.visibility[state]);
links[index].public = permit;
return permit;

@ -110,7 +110,7 @@ async function getPosts(callerUid, userData, setSuffix) {
}
function addMetaTags(res, userData) {
var plainAboutMe = userData.aboutme ? utils.stripHTMLTags(utils.decodeHTMLEntities(userData.aboutme)) : '';
const plainAboutMe = userData.aboutme ? utils.stripHTMLTags(utils.decodeHTMLEntities(userData.aboutme)) : '';
res.locals.metaTags = [
{
name: 'title',

@ -219,8 +219,8 @@ async function getHomePageRoutes(userData) {
let routes = await helpers.getHomePageRoutes(userData.uid);
// Set selected for each route
var customIdx;
var hasSelected = false;
let customIdx;
let hasSelected = false;
routes = routes.map((route, idx) => {
if (route.route === userData.settings.homePageRoute) {
route.selected = true;

@ -3,7 +3,7 @@
const privileges = require('../privileges');
const helpers = require('./helpers');
var adminController = {
const adminController = {
dashboard: require('./admin/dashboard'),
categories: require('./admin/categories'),
privileges: require('./admin/privileges'),

@ -26,8 +26,8 @@ uploadsController.get = async function (req, res, next) {
let files = await fs.promises.readdir(currentFolder);
files = files.filter(filename => filename !== '.gitignore');
const itemCount = files.length;
var start = Math.max(0, (page - 1) * itemsPerPage);
var stop = start + itemsPerPage;
const start = Math.max(0, (page - 1) * itemsPerPage);
const stop = start + itemsPerPage;
files = files.slice(start, stop);
files = await filesToData(currentFolder, files);
@ -65,11 +65,11 @@ uploadsController.get = async function (req, res, next) {
};
function buildBreadcrumbs(currentFolder) {
var crumbs = [];
var parts = currentFolder.replace(nconf.get('upload_path'), '').split(path.sep);
var currentPath = '';
const crumbs = [];
const parts = currentFolder.replace(nconf.get('upload_path'), '').split(path.sep);
let currentPath = '';
parts.forEach((part) => {
var dir = path.join(currentPath, part);
const dir = path.join(currentPath, part);
crumbs.push({
text: part || 'Uploads',
url: part ?

@ -191,7 +191,7 @@ usersController.registrationQueue = async function (req, res) {
customHeaders: plugins.hooks.fire('filter:admin.registrationQueue.customHeaders', { headers: [] }),
invites: getInvites(),
});
var pageCount = Math.max(1, Math.ceil(data.registrationQueueCount / itemsPerPage));
const pageCount = Math.max(1, Math.ceil(data.registrationQueueCount / itemsPerPage));
data.pagination = pagination.create(page, pageCount);
data.customHeaders = data.customHeaders.headers;
res.render('admin/manage/registration', data);

@ -142,7 +142,7 @@ authenticationController.registerComplete = function (req, res, next) {
return next(err);
}
var callbacks = data.interstitials.reduce((memo, cur) => {
const callbacks = data.interstitials.reduce((memo, cur) => {
if (cur.hasOwnProperty('callback') && typeof cur.callback === 'function') {
req.body.files = req.files;
memo.push(cur.callback && cur.callback.constructor && cur.callback.constructor.name === 'AsyncFunction' ? cur.callback : util.promisify(cur.callback));
@ -151,7 +151,7 @@ authenticationController.registerComplete = function (req, res, next) {
return memo;
}, []);
var done = function (err, data) {
const done = function (err, data) {
delete req.session.registration;
if (err) {
return res.redirect(`${nconf.get('relative_path')}/?register=${encodeURIComponent(err.message)}`);
@ -218,7 +218,7 @@ authenticationController.login = async (req, res, next) => {
return continueLogin(strategy, req, res, next);
}
var loginWith = meta.config.allowLoginWith || 'username-email';
const loginWith = meta.config.allowLoginWith || 'username-email';
req.body.username = req.body.username.trim();
plugins.hooks.fire('filter:login.check', { req: req, res: res, userData: req.body }, (err) => {
@ -262,7 +262,7 @@ function continueLogin(strategy, req, res, next) {
// Alter user cookie depending on passed-in option
if (req.body.remember === 'on') {
var duration = 1000 * 60 * 60 * 24 * meta.config.loginDays;
const duration = 1000 * 60 * 60 * 24 * meta.config.loginDays;
req.session.cookie.maxAge = duration;
req.session.cookie.expires = new Date(Date.now() + duration);
} else {
@ -283,7 +283,7 @@ function continueLogin(strategy, req, res, next) {
} else {
delete req.query.lang;
await authenticationController.doLogin(req, userData.uid);
var destination;
let destination;
if (req.session.returnTo) {
destination = req.session.returnTo.startsWith('http') ?
req.session.returnTo :

@ -1,17 +1,17 @@
'use strict';
var nconf = require('nconf');
var winston = require('winston');
var validator = require('validator');
var plugins = require('../plugins');
var middleware = require('../middleware');
const nconf = require('nconf');
const winston = require('winston');
const validator = require('validator');
const plugins = require('../plugins');
const middleware = require('../middleware');
exports.handleURIErrors = async function handleURIErrors(err, req, res, next) {
// Handle cases where malformed URIs are passed in
if (err instanceof URIError) {
const cleanPath = req.path.replace(new RegExp(`^${nconf.get('relative_path')}`), '');
var tidMatch = cleanPath.match(/^\/topic\/(\d+)\//);
var cidMatch = cleanPath.match(/^\/category\/(\d+)\//);
const tidMatch = cleanPath.match(/^\/topic\/(\d+)\//);
const cidMatch = cleanPath.match(/^\/category\/(\d+)\//);
if (tidMatch) {
res.redirect(nconf.get('relative_path') + tidMatch[0]);
@ -36,7 +36,7 @@ exports.handleURIErrors = async function handleURIErrors(err, req, res, next) {
// this needs to have four arguments or express treats it as `(req, res, next)`
// don't remove `next`!
exports.handleErrors = function handleErrors(err, req, res, next) { // eslint-disable-line no-unused-vars
var cases = {
const cases = {
EBADCSRFTOKEN: function () {
winston.error(`${req.path}\n${err.message}`);
res.sendStatus(403);
@ -45,9 +45,9 @@ exports.handleErrors = function handleErrors(err, req, res, next) { // eslint-di
res.status(403).type('text/plain').send(err.message);
},
};
var defaultHandler = async function () {
const defaultHandler = async function () {
// Display NodeBB error page
var status = parseInt(err.status, 10);
const status = parseInt(err.status, 10);
if ((status === 302 || status === 308) && err.path) {
return res.locals.isAPI ? res.set('X-Redirect', err.path).status(200).json(err.path) : res.redirect(nconf.get('relative_path') + err.path);
}
@ -56,7 +56,7 @@ exports.handleErrors = function handleErrors(err, req, res, next) { // eslint-di
res.status(status || 500);
var path = String(req.path || '');
const path = String(req.path || '');
if (res.locals.isAPI) {
res.json({ path: validator.escape(path), error: err.message });
} else {

@ -487,7 +487,7 @@ async function generateBannedResponse(res) {
}
helpers.generateError = (statusCode, message) => {
var payload = {
const payload = {
status: {
code: 'internal-server-error',
message: 'An unexpected error was encountered while attempting to service your request.',

@ -52,7 +52,7 @@ async function rewrite(req, res, next) {
exports.rewrite = rewrite;
function pluginHook(req, res, next) {
var hook = `action:homepage.get:${res.locals.homePageRoute}`;
const hook = `action:homepage.get:${res.locals.homePageRoute}`;
plugins.hooks.fire(hook, {
req: req,

@ -1,9 +1,9 @@
'use strict';
var nconf = require('nconf');
const nconf = require('nconf');
var databaseName = nconf.get('database');
var winston = require('winston');
const databaseName = nconf.get('database');
const winston = require('winston');
if (!databaseName) {
winston.error(new Error('Database type not set! Run ./nodebb setup'));

@ -9,8 +9,8 @@ const connection = module.exports;
connection.getConnectionString = function (mongo) {
mongo = mongo || nconf.get('mongo');
var usernamePassword = '';
var uri = mongo.uri || '';
let usernamePassword = '';
const uri = mongo.uri || '';
if (mongo.username && mongo.password) {
usernamePassword = `${nconf.get('mongo:username')}:${encodeURIComponent(nconf.get('mongo:password'))}@`;
} else if (!uri.includes('@') || !uri.slice(uri.indexOf('://') + 3, uri.indexOf('@'))) {
@ -30,11 +30,11 @@ connection.getConnectionString = function (mongo) {
mongo.database = 'nodebb';
}
var hosts = mongo.host.split(',');
var ports = mongo.port.toString().split(',');
var servers = [];
const hosts = mongo.host.split(',');
const ports = mongo.port.toString().split(',');
const servers = [];
for (var i = 0; i < hosts.length; i += 1) {
for (let i = 0; i < hosts.length; i += 1) {
servers.push(`${hosts[i]}:${ports[i]}`);
}
@ -43,7 +43,7 @@ connection.getConnectionString = function (mongo) {
connection.getConnectionOptions = function (mongo) {
mongo = mongo || nconf.get('mongo');
var connOptions = {
const connOptions = {
poolSize: 10,
connectTimeoutMS: 90000,
useNewUrlParser: true,

@ -56,7 +56,7 @@ module.exports = function (module) {
if (!field) {
return;
}
var data = {};
const data = {};
data[field] = value;
await module.setObject(key, data);
};
@ -177,7 +177,7 @@ module.exports = function (module) {
return;
}
var data = {};
const data = {};
fields.forEach((field) => {
field = helpers.fieldToString(field);
data[field] = '';
@ -205,12 +205,12 @@ module.exports = function (module) {
return null;
}
var increment = {};
const increment = {};
field = helpers.fieldToString(field);
increment[field] = value;
if (Array.isArray(key)) {
var bulk = module.client.collection('objects').initializeUnorderedBulkOp();
const bulk = module.client.collection('objects').initializeUnorderedBulkOp();
key.forEach((key) => {
bulk.find({ _key: key }).upsert().update({ $inc: increment });
});

@ -6,8 +6,8 @@ const utils = require('../../utils');
helpers.noop = function () {};
helpers.toMap = function (data) {
var map = {};
for (var i = 0; i < data.length; i += 1) {
const map = {};
for (let i = 0; i < data.length; i += 1) {
map[data[i]._key] = data[i];
delete data[i]._key;
}

@ -1,7 +1,7 @@
'use strict';
module.exports = function (module) {
var helpers = require('./helpers');
const helpers = require('./helpers');
module.listPrepend = async function (key, value) {
if (!key) {

@ -66,7 +66,7 @@ module.exports = function (module) {
const objectData = await module.client.collection('objects').findOne({ _key: key }, { projection: { _id: 0 } });
// fallback to old field name 'value' for backwards compatibility #6340
var value = null;
let value = null;
if (objectData) {
if (objectData.hasOwnProperty('data')) {
value = objectData.data;
@ -105,7 +105,7 @@ module.exports = function (module) {
return null;
}
delete data.expireAt;
var keys = Object.keys(data);
const keys = Object.keys(data);
if (keys.length === 4 && data.hasOwnProperty('_key') && data.hasOwnProperty('score') && data.hasOwnProperty('value')) {
return 'zset';
} else if (keys.length === 3 && data.hasOwnProperty('_key') && data.hasOwnProperty('members')) {

@ -1,7 +1,7 @@
'use strict';
module.exports = function (module) {
var helpers = require('./helpers');
const helpers = require('./helpers');
module.setAdd = async function (key, value) {
if (!Array.isArray(value)) {
@ -36,9 +36,9 @@ module.exports = function (module) {
value = value.map(v => helpers.valueToString(v));
var bulk = module.client.collection('objects').initializeUnorderedBulkOp();
const bulk = module.client.collection('objects').initializeUnorderedBulkOp();
for (var i = 0; i < keys.length; i += 1) {
for (let i = 0; i < keys.length; i += 1) {
bulk.find({ _key: keys[i] }).upsert().updateOne({ $addToSet: {
members: {
$each: value,
@ -103,7 +103,7 @@ module.exports = function (module) {
const result = await module.client.collection('objects').find({ _key: { $in: sets }, members: value }, { projection: { _id: 0, members: 0 } }).toArray();
var map = {};
const map = {};
result.forEach((item) => {
map[item._key] = true;
});
@ -126,7 +126,7 @@ module.exports = function (module) {
}
const data = await module.client.collection('objects').find({ _key: { $in: keys } }, { projection: { _id: 0 } }).toArray();
var sets = {};
const sets = {};
data.forEach((set) => {
sets[set._key] = set.members || [];
});
@ -144,7 +144,7 @@ module.exports = function (module) {
module.setsCount = async function (keys) {
const setsMembers = await module.getSetsMembers(keys);
var counts = setsMembers.map(members => (members && members.length) || 0);
const counts = setsMembers.map(members => (members && members.length) || 0);
return counts;
};
@ -154,8 +154,8 @@ module.exports = function (module) {
return;
}
var randomIndex = Math.floor(Math.random() * data.members.length);
var value = data.members[randomIndex];
const randomIndex = Math.floor(Math.random() * data.members.length);
const value = data.members[randomIndex];
await module.setRemove(data._key, value);
return value;
};

@ -143,7 +143,7 @@ module.exports = function (module) {
return;
}
var query = { _key: key };
const query = { _key: key };
if (min !== '-inf') {
query.score = { $gte: min };
}
@ -226,8 +226,8 @@ module.exports = function (module) {
if (!Array.isArray(keys) || !keys.length) {
return [];
}
var data = new Array(values.length);
for (var i = 0; i < values.length; i += 1) {
const data = new Array(values.length);
for (let i = 0; i < values.length; i += 1) {
data[i] = { key: keys[i], value: values[i] };
}
const promises = data.map(item => method(item.key, item.value));
@ -271,7 +271,7 @@ module.exports = function (module) {
}
value = helpers.valueToString(value);
const result = await module.client.collection('objects').find({ _key: { $in: keys }, value: value }, { projection: { _id: 0, value: 0 } }).toArray();
var map = {};
const map = {};
result.forEach((item) => {
if (item) {
map[item._key] = item;
@ -291,7 +291,7 @@ module.exports = function (module) {
values = values.map(helpers.valueToString);
const result = await module.client.collection('objects').find({ _key: key, value: { $in: values } }, { projection: { _id: 0, _key: 0 } }).toArray();
var valueToScore = {};
const valueToScore = {};
result.forEach((item) => {
if (item) {
valueToScore[item.value] = item.score;
@ -328,7 +328,7 @@ module.exports = function (module) {
projection: { _id: 0, value: 1 },
}).toArray();
var isMember = {};
const isMember = {};
results.forEach((item) => {
if (item) {
isMember[item.value] = true;
@ -349,7 +349,7 @@ module.exports = function (module) {
projection: { _id: 0, _key: 1, value: 1 },
}).toArray();
var isMember = {};
const isMember = {};
results.forEach((item) => {
if (item) {
isMember[item._key] = true;
@ -393,7 +393,7 @@ module.exports = function (module) {
if (!key) {
return;
}
var data = {};
const data = {};
value = helpers.valueToString(value);
data.score = parseFloat(increment);
@ -426,7 +426,7 @@ module.exports = function (module) {
};
async function sortedSetLex(key, min, max, sort, start, count) {
var query = { _key: key };
const query = { _key: key };
start = start !== undefined ? start : 0;
count = count !== undefined ? count : 0;
buildLexQuery(query, min, max);
@ -441,7 +441,7 @@ module.exports = function (module) {
}
module.sortedSetRemoveRangeByLex = async function (key, min, max) {
var query = { _key: key };
const query = { _key: key };
buildLexQuery(query, min, max);
await module.client.collection('objects').deleteMany(query);
@ -499,14 +499,14 @@ module.exports = function (module) {
};
module.processSortedSet = async function (setKey, processFn, options) {
var done = false;
var ids = [];
var project = { _id: 0, _key: 0 };
let done = false;
const ids = [];
const project = { _id: 0, _key: 0 };
if (!options.withScores) {
project.score = 0;
}
var cursor = await module.client.collection('objects').find({ _key: setKey }, { projection: project })
const cursor = await module.client.collection('objects').find({ _key: setKey }, { projection: project })
.sort({ score: 1 })
.batchSize(options.batch);

@ -1,8 +1,8 @@
'use strict';
module.exports = function (module) {
var helpers = require('../helpers');
var utils = require('../../../utils');
const helpers = require('../helpers');
const utils = require('../../../utils');
module.sortedSetAdd = async function (key, score, value) {
if (!key) {
@ -40,8 +40,8 @@ module.exports = function (module) {
}
values = values.map(helpers.valueToString);
var bulk = module.client.collection('objects').initializeUnorderedBulkOp();
for (var i = 0; i < scores.length; i += 1) {
const bulk = module.client.collection('objects').initializeUnorderedBulkOp();
for (let i = 0; i < scores.length; i += 1) {
bulk.find({ _key: key, value: values[i] }).upsert().updateOne({ $set: { score: parseFloat(scores[i]) } });
}
await bulk.execute();
@ -63,8 +63,8 @@ module.exports = function (module) {
value = helpers.valueToString(value);
var bulk = module.client.collection('objects').initializeUnorderedBulkOp();
for (var i = 0; i < keys.length; i += 1) {
const bulk = module.client.collection('objects').initializeUnorderedBulkOp();
for (let i = 0; i < keys.length; i += 1) {
bulk.find({ _key: keys[i], value: value }).upsert().updateOne({ $set: { score: parseFloat(isArrayOfScores ? scores[i] : scores) } });
}
await bulk.execute();
@ -74,7 +74,7 @@ module.exports = function (module) {
if (!Array.isArray(data) || !data.length) {
return;
}
var bulk = module.client.collection('objects').initializeUnorderedBulkOp();
const bulk = module.client.collection('objects').initializeUnorderedBulkOp();
data.forEach((item) => {
if (!utils.isNumber(item[1])) {
throw new Error(`[[error:invalid-score, ${item[1]}]]`);

@ -1,7 +1,7 @@
'use strict';
module.exports = function (module) {
var helpers = require('../helpers');
const helpers = require('../helpers');
module.sortedSetRemove = async function (key, value) {
if (!key) {
@ -37,7 +37,7 @@ module.exports = function (module) {
if (!Array.isArray(keys) || !keys.length) {
return;
}
var query = { _key: { $in: keys } };
const query = { _key: { $in: keys } };
if (keys.length === 1) {
query._key = keys[0];
}
@ -56,7 +56,7 @@ module.exports = function (module) {
if (!Array.isArray(data) || !data.length) {
return;
}
var bulk = module.client.collection('objects').initializeUnorderedBulkOp();
const bulk = module.client.collection('objects').initializeUnorderedBulkOp();
data.forEach(item => bulk.find({ _key: item[0], value: String(item[1]) }).remove());
await bulk.execute();
};

@ -28,19 +28,19 @@ module.exports = function (module) {
if (!Array.isArray(params.sets) || !params.sets.length) {
return;
}
var limit = params.stop - params.start + 1;
let limit = params.stop - params.start + 1;
if (limit <= 0) {
limit = 0;
}
var aggregate = {};
const aggregate = {};
if (params.aggregate) {
aggregate[`$${params.aggregate.toLowerCase()}`] = '$score';
} else {
aggregate.$sum = '$score';
}
var pipeline = [
const pipeline = [
{ $match: { _key: { $in: params.sets } } },
{ $group: { _id: { value: '$value' }, totalScore: aggregate } },
{ $sort: { totalScore: params.sort } },
@ -54,7 +54,7 @@ module.exports = function (module) {
pipeline.push({ $limit: limit });
}
var project = { _id: 0, value: '$_id.value' };
const project = { _id: 0, value: '$_id.value' };
if (params.withScores) {
project.score = '$totalScore';
}

@ -64,7 +64,7 @@ postgresModule.init = async function () {
async function checkUpgrade(client) {
var res = await client.query(`
const res = await client.query(`
SELECT EXISTS(SELECT *
FROM "information_schema"."columns"
WHERE "table_schema" = 'public'
@ -331,7 +331,7 @@ postgresModule.createIndices = function (callback) {
return callback();
}
var query = postgresModule.pool.query.bind(postgresModule.pool);
const query = postgresModule.pool.query.bind(postgresModule.pool);
winston.info('[database] Checking database indices.');
async.series([
@ -348,7 +348,7 @@ postgresModule.createIndices = function (callback) {
};
postgresModule.checkCompatibility = function (callback) {
var postgresPkg = require('pg/package.json');
const postgresPkg = require('pg/package.json');
postgresModule.checkCompatibilityVersion(postgresPkg.version, callback);
};

@ -21,7 +21,7 @@ connection.getConnectionOptions = function (postgres) {
postgres.database = 'nodebb';
}
var connOptions = {
const connOptions = {
host: postgres.host,
port: postgres.port,
user: postgres.username,

@ -1,7 +1,7 @@
'use strict';
module.exports = function (module) {
var helpers = require('./helpers');
const helpers = require('./helpers');
module.setObject = async function (key, data) {
if (!key || !data) {
@ -158,7 +158,7 @@ SELECT (SELECT jsonb_object_agg(f, d."value")
return res.rows[0].d;
}
var obj = {};
const obj = {};
fields.forEach((f) => {
obj[f] = null;
});

@ -1,17 +1,17 @@
'use strict';
var helpers = module.exports;
const helpers = module.exports;
helpers.valueToString = function (value) {
return String(value);
};
helpers.removeDuplicateValues = function (values) {
var others = Array.prototype.slice.call(arguments, 1);
for (var i = 0; i < values.length; i++) {
const others = Array.prototype.slice.call(arguments, 1);
for (let i = 0; i < values.length; i++) {
if (values.lastIndexOf(values[i]) !== i) {
values.splice(i, 1);
for (var j = 0; j < others.length; j++) {
for (let j = 0; j < others.length; j++) {
others[j].splice(i, 1);
}
i -= 1;
@ -81,14 +81,14 @@ SELECT "_key", "type"
values: [keys],
});
var invalid = res.rows.filter(r => r.type !== type);
const invalid = res.rows.filter(r => r.type !== type);
if (invalid.length) {
const parts = invalid.map(r => `${JSON.stringify(r._key)} is ${r.type}`);
throw new Error(`database: cannot insert multiple objects as ${type} because they already exist: ${parts.join(', ')}`);
}
var missing = keys.filter(k => !res.rows.some(r => r._key === k));
const missing = keys.filter(k => !res.rows.some(r => r._key === k));
if (missing.length) {
throw new Error(`database: failed to insert keys for objects: ${JSON.stringify(missing)}`);

@ -1,7 +1,7 @@
'use strict';
module.exports = function (module) {
var helpers = require('./helpers');
const helpers = require('./helpers');
module.listPrepend = async function (key, value) {
if (!key) {

@ -1,9 +1,9 @@
'use strict';
var _ = require('lodash');
const _ = require('lodash');
module.exports = function (module) {
var helpers = require('./helpers');
const helpers = require('./helpers');
module.setAdd = async function (key, value) {
if (!Array.isArray(value)) {

@ -1,9 +1,9 @@
'use strict';
module.exports = function (module) {
var helpers = require('./helpers');
const helpers = require('./helpers');
const util = require('util');
var Cursor = require('pg-cursor');
const Cursor = require('pg-cursor');
Cursor.prototype.readAsync = util.promisify(Cursor.prototype.read);
const sleep = util.promisify(setTimeout);
@ -41,19 +41,19 @@ module.exports = function (module) {
return [];
}
var reverse = false;
let reverse = false;
if (start === 0 && stop < -1) {
reverse = true;
sort *= -1;
start = Math.abs(stop + 1);
stop = -1;
} else if (start < 0 && stop > start) {
var tmp1 = Math.abs(stop + 1);
const tmp1 = Math.abs(stop + 1);
stop = Math.abs(start + 1);
start = tmp1;
}
var limit = stop - start + 1;
let limit = stop - start + 1;
if (limit <= 0) {
limit = null;
}
@ -346,7 +346,7 @@ SELECT o."_key" k,
});
return keys.map((k) => {
var s = res.rows.find(r => r.k === k);
const s = res.rows.find(r => r.k === k);
return s ? parseFloat(s.s) : null;
});
};
@ -375,7 +375,7 @@ SELECT z."value" v,
});
return values.map((v) => {
var s = res.rows.find(r => r.v === v);
const s = res.rows.find(r => r.v === v);
return s ? parseFloat(s.s) : null;
});
};
@ -507,7 +507,7 @@ RETURNING "score" s`,
};
module.sortedSetLexCount = async function (key, min, max) {
var q = buildLexQuery(key, min, max);
const q = buildLexQuery(key, min, max);
const res = await module.pool.query({
name: `sortedSetLexCount${q.suffix}`,
@ -528,7 +528,7 @@ SELECT COUNT(*) c
start = start !== undefined ? start : 0;
count = count !== undefined ? count : 0;
var q = buildLexQuery(key, min, max);
const q = buildLexQuery(key, min, max);
q.values.push(start);
q.values.push(count <= 0 ? null : count);
const res = await module.pool.query({
@ -550,7 +550,7 @@ OFFSET $${q.values.length - 1}::INTEGER`,
}
module.sortedSetRemoveRangeByLex = async function (key, min, max) {
var q = buildLexQuery(key, min, max);
const q = buildLexQuery(key, min, max);
await module.pool.query({
name: `sortedSetRemoveRangeByLex${q.suffix}`,
text: `
@ -564,7 +564,7 @@ DELETE FROM "legacy_zset" z
};
function buildLexQuery(key, min, max) {
var q = {
const q = {
suffix: '',
where: `o."_key" = $1::TEXT`,
values: [key],
@ -636,8 +636,8 @@ SELECT z."value",
module.processSortedSet = async function (setKey, process, options) {
const client = await module.pool.connect();
var batchSize = (options || {}).batch || 100;
var cursor = client.query(new Cursor(`
const batchSize = (options || {}).batch || 100;
const cursor = client.query(new Cursor(`
SELECT z."value", z."score"
FROM "legacy_object_live" o
INNER JOIN "legacy_zset" z

@ -1,8 +1,8 @@
'use strict';
module.exports = function (module) {
var helpers = require('../helpers');
var utils = require('../../../utils');
const helpers = require('../helpers');
const utils = require('../../../utils');
module.sortedSetAdd = async function (key, score, value) {
if (!key) {

@ -37,11 +37,11 @@ SELECT COUNT(*) c
};
async function getSortedSetIntersect(params) {
var sets = params.sets;
var start = params.hasOwnProperty('start') ? params.start : 0;
var stop = params.hasOwnProperty('stop') ? params.stop : -1;
var weights = params.weights || [];
var aggregate = params.aggregate || 'SUM';
const sets = params.sets;
const start = params.hasOwnProperty('start') ? params.start : 0;
const stop = params.hasOwnProperty('stop') ? params.stop : -1;
let weights = params.weights || [];
const aggregate = params.aggregate || 'SUM';
if (sets.length < weights.length) {
weights = weights.slice(0, sets.length);
@ -50,7 +50,7 @@ SELECT COUNT(*) c
weights.push(1);
}
var limit = stop - start + 1;
let limit = stop - start + 1;
if (limit <= 0) {
limit = null;
}

@ -1,7 +1,7 @@
'use strict';
module.exports = function (module) {
var helpers = require('../helpers');
const helpers = require('../helpers');
module.sortedSetRemove = async function (key, value) {
if (!key) {

@ -31,11 +31,11 @@ SELECT COUNT(DISTINCT z."value") c
};
async function getSortedSetUnion(params) {
var sets = params.sets;
var start = params.hasOwnProperty('start') ? params.start : 0;
var stop = params.hasOwnProperty('stop') ? params.stop : -1;
var weights = params.weights || [];
var aggregate = params.aggregate || 'SUM';
const sets = params.sets;
const start = params.hasOwnProperty('start') ? params.start : 0;
const stop = params.hasOwnProperty('stop') ? params.stop : -1;
let weights = params.weights || [];
const aggregate = params.aggregate || 'SUM';
if (sets.length < weights.length) {
weights = weights.slice(0, sets.length);
@ -44,7 +44,7 @@ SELECT COUNT(DISTINCT z."value") c
weights.push(1);
}
var limit = stop - start + 1;
let limit = stop - start + 1;
if (limit <= 0) {
limit = null;
}

@ -193,7 +193,7 @@ module.exports = function (module) {
}
let result;
if (Array.isArray(key)) {
var batch = module.client.batch();
const batch = module.client.batch();
key.forEach(k => batch.hincrby(k, field, value));
result = await helpers.execBatch(batch);
} else {

@ -2,7 +2,7 @@
const util = require('util');
var helpers = module.exports;
const helpers = module.exports;
helpers.noop = function () {};
@ -12,7 +12,7 @@ helpers.execBatch = async function (batch) {
};
helpers.resultsToBool = function (results) {
for (var i = 0; i < results.length; i += 1) {
for (let i = 0; i < results.length; i += 1) {
results[i] = results[i] === 1;
}
return results;

@ -1,7 +1,7 @@
'use strict';
module.exports = function (module) {
var helpers = require('./helpers');
const helpers = require('./helpers');
module.flushdb = async function () {
await module.client.async.send_command('flushdb', []);

@ -20,7 +20,7 @@ const PubSub = function () {
}
try {
var msg = JSON.parse(message);
const msg = JSON.parse(message);
self.emit(msg.event, msg.data);
} catch (err) {
winston.error(err.stack);

@ -1,7 +1,7 @@
'use strict';
module.exports = function (module) {
var helpers = require('./helpers');
const helpers = require('./helpers');
module.setAdd = async function (key, value) {
if (!Array.isArray(value)) {
@ -30,13 +30,13 @@ module.exports = function (module) {
key = [key];
}
var batch = module.client.batch();
const batch = module.client.batch();
key.forEach(k => batch.srem(String(k), value));
await helpers.execBatch(batch);
};
module.setsRemove = async function (keys, value) {
var batch = module.client.batch();
const batch = module.client.batch();
keys.forEach(k => batch.srem(String(k), value));
await helpers.execBatch(batch);
};

@ -111,7 +111,7 @@ module.exports = function (module) {
if (!Array.isArray(keys) || !keys.length) {
return [];
}
var batch = module.client.batch();
const batch = module.client.batch();
keys.forEach(k => batch.zcard(String(k)));
return await helpers.execBatch(batch);
};
@ -138,7 +138,7 @@ module.exports = function (module) {
module.sortedSetsRanks = async function (keys, values) {
const batch = module.client.batch();
for (var i = 0; i < values.length; i += 1) {
for (let i = 0; i < values.length; i += 1) {
batch.zrank(keys[i], String(values[i]));
}
return await helpers.execBatch(batch);
@ -146,7 +146,7 @@ module.exports = function (module) {
module.sortedSetsRevRanks = async function (keys, values) {
const batch = module.client.batch();
for (var i = 0; i < values.length; i += 1) {
for (let i = 0; i < values.length; i += 1) {
batch.zrevrank(keys[i], String(values[i]));
}
return await helpers.execBatch(batch);
@ -154,7 +154,7 @@ module.exports = function (module) {
module.sortedSetRanks = async function (key, values) {
const batch = module.client.batch();
for (var i = 0; i < values.length; i += 1) {
for (let i = 0; i < values.length; i += 1) {
batch.zrank(key, String(values[i]));
}
return await helpers.execBatch(batch);
@ -162,7 +162,7 @@ module.exports = function (module) {
module.sortedSetRevRanks = async function (key, values) {
const batch = module.client.batch();
for (var i = 0; i < values.length; i += 1) {
for (let i = 0; i < values.length; i += 1) {
batch.zrevrank(key, String(values[i]));
}
return await helpers.execBatch(batch);
@ -230,7 +230,7 @@ module.exports = function (module) {
if (!Array.isArray(keys) || !keys.length) {
return [];
}
var batch = module.client.batch();
const batch = module.client.batch();
keys.forEach(k => batch.zrange(k, 0, -1));
return await helpers.execBatch(batch);
};
@ -257,8 +257,8 @@ module.exports = function (module) {
};
async function sortedSetLex(method, reverse, key, min, max, start, count) {
var minmin;
var maxmax;
let minmin;
let maxmax;
if (reverse) {
minmin = '+';
maxmax = '-';

@ -30,8 +30,8 @@ module.exports = function (module) {
throw new Error(`[[error:invalid-score, ${scores[i]}]]`);
}
}
var args = [key];
for (var i = 0; i < scores.length; i += 1) {
const args = [key];
for (let i = 0; i < scores.length; i += 1) {
args.push(scores[i], String(values[i]));
}
await module.client.async.zadd(args);
@ -51,8 +51,8 @@ module.exports = function (module) {
throw new Error('[[error:invalid-data]]');
}
var batch = module.client.batch();
for (var i = 0; i < keys.length; i += 1) {
const batch = module.client.batch();
for (let i = 0; i < keys.length; i += 1) {
if (keys[i]) {
batch.zadd(keys[i], isArrayOfScores ? scores[i] : scores, String(value));
}
@ -64,7 +64,7 @@ module.exports = function (module) {
if (!Array.isArray(data) || !data.length) {
return;
}
var batch = module.client.batch();
const batch = module.client.batch();
data.forEach((item) => {
if (!utils.isNumber(item[1])) {
throw new Error(`[[error:invalid-score, ${item[1]}]]`);

@ -7,11 +7,11 @@ module.exports = function (module) {
if (!Array.isArray(keys) || !keys.length) {
return 0;
}
var tempSetName = `temp_${Date.now()}`;
const tempSetName = `temp_${Date.now()}`;
var interParams = [tempSetName, keys.length].concat(keys);
const interParams = [tempSetName, keys.length].concat(keys);
var multi = module.client.multi();
const multi = module.client.multi();
multi.zinterstore(interParams);
multi.zcard(tempSetName);
multi.del(tempSetName);
@ -30,14 +30,14 @@ module.exports = function (module) {
};
async function getSortedSetRevIntersect(params) {
var sets = params.sets;
var start = params.hasOwnProperty('start') ? params.start : 0;
var stop = params.hasOwnProperty('stop') ? params.stop : -1;
var weights = params.weights || [];
const sets = params.sets;
const start = params.hasOwnProperty('start') ? params.start : 0;
const stop = params.hasOwnProperty('stop') ? params.stop : -1;
const weights = params.weights || [];
var tempSetName = `temp_${Date.now()}`;
const tempSetName = `temp_${Date.now()}`;
var interParams = [tempSetName, sets.length].concat(sets);
let interParams = [tempSetName, sets.length].concat(sets);
if (weights.length) {
interParams = interParams.concat(['WEIGHTS'].concat(weights));
}
@ -46,12 +46,12 @@ module.exports = function (module) {
interParams = interParams.concat(['AGGREGATE', params.aggregate]);
}
var rangeParams = [tempSetName, start, stop];
const rangeParams = [tempSetName, start, stop];
if (params.withScores) {
rangeParams.push('WITHSCORES');
}
var multi = module.client.multi();
const multi = module.client.multi();
multi.zinterstore(interParams);
multi[params.method](rangeParams);
multi.del(tempSetName);

@ -2,7 +2,7 @@
'use strict';
module.exports = function (module) {
var helpers = require('../helpers');
const helpers = require('../helpers');
module.sortedSetRemove = async function (key, value) {
if (!key) {
@ -30,7 +30,7 @@ module.exports = function (module) {
};
module.sortedSetsRemoveRangeByScore = async function (keys, min, max) {
var batch = module.client.batch();
const batch = module.client.batch();
keys.forEach(k => batch.zremrangebyscore(k, min, max));
await helpers.execBatch(batch);
};

@ -4,11 +4,11 @@
module.exports = function (module) {
const helpers = require('../helpers');
module.sortedSetUnionCard = async function (keys) {
var tempSetName = `temp_${Date.now()}`;
const tempSetName = `temp_${Date.now()}`;
if (!keys.length) {
return 0;
}
var multi = module.client.multi();
const multi = module.client.multi();
multi.zunionstore([tempSetName, keys.length].concat(keys));
multi.zcard(tempSetName);
multi.del(tempSetName);
@ -31,14 +31,14 @@ module.exports = function (module) {
return [];
}
var tempSetName = `temp_${Date.now()}`;
const tempSetName = `temp_${Date.now()}`;
var rangeParams = [tempSetName, params.start, params.stop];
const rangeParams = [tempSetName, params.start, params.stop];
if (params.withScores) {
rangeParams.push('WITHSCORES');
}
var multi = module.client.multi();
const multi = module.client.multi();
multi.zunionstore([tempSetName, params.sets.length].concat(params.sets));
multi[params.method](rangeParams);
multi.del(tempSetName);

@ -135,7 +135,7 @@ Flags.getFlagIdsWithFilters = async function ({ filters, uid }) {
filters.page = filters.hasOwnProperty('page') ? Math.abs(parseInt(filters.page, 10) || 1) : 1;
filters.perPage = filters.hasOwnProperty('perPage') ? Math.abs(parseInt(filters.perPage, 10) || 20) : 20;
for (var type in filters) {
for (const type in filters) {
if (filters.hasOwnProperty(type)) {
if (Flags._filters.hasOwnProperty(type)) {
Flags._filters[type](sets, orSets, filters[type], uid);
@ -586,7 +586,7 @@ Flags.update = async function (flagId, uid, changeset) {
// Retrieve existing flag data to compare for history-saving/reference purposes
const tasks = [];
for (var prop in changeset) {
for (const prop in changeset) {
if (changeset.hasOwnProperty(prop)) {
if (current[prop] === changeset[prop]) {
delete changeset[prop];

@ -46,7 +46,7 @@ Groups.getEphemeralGroup = function (groupName) {
};
Groups.removeEphemeralGroups = function (groups) {
for (var x = groups.length; x >= 0; x -= 1) {
for (let x = groups.length; x >= 0; x -= 1) {
if (Groups.ephemeralGroups.includes(groups[x])) {
groups.splice(x, 1);
}
@ -55,7 +55,7 @@ Groups.removeEphemeralGroups = function (groups) {
return groups;
};
var isPrivilegeGroupRegex = /^cid:\d+:privileges:[\w\-:]+$/;
const isPrivilegeGroupRegex = /^cid:\d+:privileges:[\w\-:]+$/;
Groups.isPrivilegeGroup = function (groupName) {
return isPrivilegeGroupRegex.test(groupName);
};

@ -87,7 +87,7 @@ function checkSetupFlag() {
}
function checkCIFlag() {
var ciVals;
let ciVals;
try {
ciVals = JSON.parse(nconf.get('ci'));
} catch (e) {
@ -151,7 +151,7 @@ async function completeConfigSetup(config) {
// Add CI object
if (install.ciVals) {
config.test_database = {};
for (var prop in install.ciVals) {
for (const prop in install.ciVals) {
if (install.ciVals.hasOwnProperty(prop)) {
config.test_database[prop] = install.ciVals[prop];
}
@ -173,7 +173,7 @@ async function completeConfigSetup(config) {
if (!/^http(?:s)?:\/\//.test(config.url)) {
config.url = `http://${config.url}`;
}
var urlObj = url.parse(config.url);
const urlObj = url.parse(config.url);
if (urlObj.port) {
config.port = urlObj.port;
}

@ -4,17 +4,17 @@
* Logger module: ability to dynamically turn on/off logging for http requests & socket.io events
*/
var fs = require('fs');
var path = require('path');
var winston = require('winston');
var util = require('util');
var morgan = require('morgan');
const fs = require('fs');
const path = require('path');
const winston = require('winston');
const util = require('util');
const morgan = require('morgan');
var file = require('./file');
var meta = require('./meta');
const file = require('./file');
const meta = require('./meta');
var opts = {
const opts = {
/*
* state used by Logger
*/
@ -29,7 +29,7 @@ var opts = {
};
/* -- Logger -- */
var Logger = module.exports;
const Logger = module.exports;
Logger.init = function (app) {
opts.express.app = app;
@ -58,7 +58,7 @@ Logger.setup_one_log = function (value) {
* Otherwise, close the current stream
*/
if (meta.config.loggerStatus > 0 || meta.config.loggerIOStatus) {
var stream = Logger.open(value);
const stream = Logger.open(value);
if (stream) {
opts.streams.log.f = stream;
} else {
@ -71,10 +71,10 @@ Logger.setup_one_log = function (value) {
Logger.open = function (value) {
/* Open the streams to log to: either a path or stdout */
var stream;
let stream;
if (value) {
if (file.existsSync(value)) {
var stats = fs.statSync(value);
const stats = fs.statSync(value);
if (stats) {
if (stats.isDirectory()) {
stream = fs.createWriteStream(path.join(value, 'nodebb.log'), { flags: 'a' });
@ -207,11 +207,11 @@ Logger.io_one = function (socket, uid) {
if (socket && meta.config.loggerIOStatus > 0) {
// courtesy of: http://stackoverflow.com/a/9674248
socket.oEmit = socket.emit;
var emit = socket.emit;
const emit = socket.emit;
socket.emit = override(emit, 'emit', 'Logger.io_one: emit.apply: Failed');
socket.$onvent = socket.onevent;
var $onevent = socket.onevent;
const $onevent = socket.onevent;
socket.onevent = override($onevent, 'on', 'Logger.io_one: $emit.apply: Failed');
}
};

@ -64,7 +64,7 @@ module.exports = function (Messaging) {
message.fromUser.banned = !!message.fromUser.banned;
message.fromUser.deleted = message.fromuid !== message.fromUser.uid && message.fromUser.uid === 0;
var self = message.fromuid === parseInt(uid, 10);
const self = message.fromuid === parseInt(uid, 10);
message.self = self ? 1 : 0;
message.newSet = false;
@ -104,7 +104,7 @@ module.exports = function (Messaging) {
});
} else if (messages.length === 1) {
// For single messages, we don't know the context, so look up the previous message and compare
var key = `uid:${uid}:chat:room:${roomId}:mids`;
const key = `uid:${uid}:chat:room:${roomId}:mids`;
const index = await db.sortedSetRank(key, messages[0].messageId);
if (index > 0) {
const mid = await db.getSortedSetRange(key, index - 1, index - 1);

@ -258,8 +258,8 @@ Messaging.hasPrivateChat = async (uid, withUid) => {
return 0;
}
var index = 0;
var roomId = 0;
let index = 0;
let roomId = 0;
while (index < roomIds.length && !roomId) {
/* eslint-disable no-await-in-loop */
const count = await Messaging.getUserCountInRoom(roomIds[index]);

@ -1,12 +1,12 @@
'use strict';
var validator = require('validator');
const validator = require('validator');
var db = require('../database');
var user = require('../user');
var plugins = require('../plugins');
var privileges = require('../privileges');
var meta = require('../meta');
const db = require('../database');
const user = require('../user');
const plugins = require('../plugins');
const privileges = require('../privileges');
const meta = require('../meta');
module.exports = function (Messaging) {
Messaging.getRoomData = async (roomId) => {
@ -233,7 +233,7 @@ module.exports = function (Messaging) {
user.isAdminOrGlobalMod(uid),
]);
var room = roomData;
const room = roomData;
room.messages = messages;
room.isOwner = parseInt(room.owner, 10) === parseInt(uid, 10);
room.users = users.filter(user => user && parseInt(user.uid, 10) && parseInt(user.uid, 10) !== parseInt(uid, 10));

@ -1,7 +1,7 @@
'use strict';
var db = require('../database');
var sockets = require('../socket.io');
const db = require('../database');
const sockets = require('../socket.io');
module.exports = function (Messaging) {
Messaging.getUnreadCount = async (uid) => {

@ -22,9 +22,9 @@ const aliases = {
exports.aliases = aliases;
function buildTargets() {
var length = 0;
var output = Object.keys(aliases).map((name) => {
var arr = aliases[name];
let length = 0;
const output = Object.keys(aliases).map((name) => {
const arr = aliases[name];
if (name.length > length) {
length = name.length;
}

@ -53,7 +53,7 @@ Blacklist.test = async function (clientIp) {
}
clientIp = clientIp.split(':').length === 2 ? clientIp.split(':')[0] : clientIp;
var addr;
let addr;
try {
addr = ipaddr.parse(clientIp);
} catch (err) {
@ -65,7 +65,7 @@ Blacklist.test = async function (clientIp) {
!Blacklist._rules.ipv4.includes(clientIp) && // not explicitly specified in ipv4 list
!Blacklist._rules.ipv6.includes(clientIp) && // not explicitly specified in ipv6 list
!Blacklist._rules.cidr.some((subnet) => {
var cidr = ipaddr.parseCIDR(subnet);
const cidr = ipaddr.parseCIDR(subnet);
if (addr.kind() !== cidr[0].kind()) {
return false;
}
@ -80,7 +80,7 @@ Blacklist.test = async function (clientIp) {
throw err;
}
} else {
var err = new Error('[[error:blacklisted-ip]]');
const err = new Error('[[error:blacklisted-ip]]');
err.code = 'blacklisted-ip';
analytics.increment('blacklist');
@ -90,14 +90,14 @@ Blacklist.test = async function (clientIp) {
Blacklist.validate = function (rules) {
rules = (rules || '').split('\n');
var ipv4 = [];
var ipv6 = [];
var cidr = [];
var invalid = [];
var duplicateCount = 0;
const ipv4 = [];
const ipv6 = [];
const cidr = [];
const invalid = [];
let duplicateCount = 0;
var inlineCommentMatch = /#.*$/;
var whitelist = ['127.0.0.1', '::1', '::ffff:0:127.0.0.1'];
const inlineCommentMatch = /#.*$/;
const whitelist = ['127.0.0.1', '::1', '::ffff:0:127.0.0.1'];
// Filter out blank lines and lines starting with the hash character (comments)
// Also trim inputs and remove inline comments
@ -113,8 +113,8 @@ Blacklist.validate = function (rules) {
// Filter out invalid rules
rules = rules.filter((rule) => {
var addr;
var isRange = false;
let addr;
let isRange = false;
try {
addr = ipaddr.parse(rule);
} catch (e) {
@ -161,9 +161,7 @@ Blacklist.validate = function (rules) {
};
Blacklist.addRule = async function (rule) {
var valid;
const result = Blacklist.validate(rule);
valid = result.valid;
const { valid } = Blacklist.validate(rule);
if (!valid.length) {
throw new Error('[[error:invalid-rule]]');
}

@ -50,7 +50,7 @@ const targetHandlers = {
};
const aliasMap = Object.keys(aliases).reduce((prev, key) => {
var arr = aliases[key];
const arr = aliases[key];
arr.forEach((alias) => {
prev[alias] = key;
});

@ -201,7 +201,7 @@ Configs.cookie = {
cookie.secure = true;
}
var relativePath = nconf.get('relative_path');
const relativePath = nconf.get('relative_path');
if (relativePath !== '') {
cookie.path = relativePath;
}

@ -1,12 +1,12 @@
'use strict';
var fork = require('child_process').fork;
const fork = require('child_process').fork;
var debugArg = process.execArgv.find(arg => /^--(debug|inspect)/.test(arg));
var debugging = !!debugArg;
let debugArg = process.execArgv.find(arg => /^--(debug|inspect)/.test(arg));
const debugging = !!debugArg;
debugArg = debugArg ? debugArg.replace('-brk', '').split('=') : ['--debug', 5859];
var lastAddress = parseInt(debugArg[1], 10);
let lastAddress = parseInt(debugArg[1], 10);
/**
* child-process.fork, but safe for use in debuggers
@ -15,7 +15,7 @@ var lastAddress = parseInt(debugArg[1], 10);
* @param {any} [options]
*/
function debugFork(modulePath, args, options) {
var execArgv = [];
let execArgv = [];
if (global.v8debug || debugging) {
lastAddress += 1;

@ -61,9 +61,9 @@ function restart() {
}
Meta.getSessionTTLSeconds = function () {
var ttlDays = 60 * 60 * 24 * Meta.config.loginDays;
var ttlSeconds = Meta.config.loginSeconds;
var ttl = ttlSeconds || ttlDays || 1209600; // Default to 14 days
const ttlDays = 60 * 60 * 24 * Meta.config.loginDays;
const ttlSeconds = Meta.config.loginSeconds;
const ttl = ttlSeconds || ttlDays || 1209600; // Default to 14 days
return ttl;
};

@ -29,9 +29,9 @@ async function getTranslationMetadata() {
return;
}
var rel = path.relative(coreLanguagesPath, p).split(/[/\\]/);
var language = rel.shift().replace('_', '-').replace('@', '-x-');
var namespace = rel.join('/').replace(/\.json$/, '');
const rel = path.relative(coreLanguagesPath, p).split(/[/\\]/);
const language = rel.shift().replace('_', '-').replace('@', '-x-');
const namespace = rel.join('/').replace(/\.json$/, '');
if (!language || !namespace) {
return;

@ -50,7 +50,7 @@ function getChild() {
return free.shift();
}
var proc = fork(__filename, [], {
const proc = fork(__filename, [], {
cwd: __dirname,
env: {
minifier_child: true,
@ -67,14 +67,14 @@ function freeChild(proc) {
}
function removeChild(proc) {
var i = pool.indexOf(proc);
const i = pool.indexOf(proc);
if (i !== -1) {
pool.splice(i, 1);
}
}
function forkAction(action, callback) {
var proc = getChild();
const proc = getChild();
proc.on('message', (message) => {
freeChild(proc);
@ -99,12 +99,12 @@ function forkAction(action, callback) {
});
}
var actions = {};
const actions = {};
if (process.env.minifier_child) {
process.on('message', (message) => {
if (message.type === 'action') {
var action = message.action;
const action = message.action;
if (typeof actions[action.act] !== 'function') {
process.send({
type: 'error',
@ -157,7 +157,7 @@ function concat(data, callback) {
return callback(err);
}
var output = files.join('\n;');
const output = files.join('\n;');
fs.writeFile(data.destPath, output, callback);
});
@ -175,7 +175,7 @@ function minifyJS_batch(data, callback) {
return next(err);
}
var filesToMinify = [
const filesToMinify = [
{
srcPath: fileObj.srcPath,
filename: fileObj.filename,
@ -220,7 +220,7 @@ function minifyJS(data, callback) {
actions.minifyJS = minifyJS;
function minifyAndSave(data, callback) {
var scripts = {};
const scripts = {};
data.files.forEach((ref) => {
if (!ref) {
return;
@ -229,7 +229,7 @@ function minifyAndSave(data, callback) {
scripts[ref.filename] = ref.source;
});
var minified = uglify.minify(scripts, {
const minified = uglify.minify(scripts, {
sourceMap: {
filename: data.filename,
url: `${String(data.filename).split(/[/\\]/).pop()}.map`,

@ -56,7 +56,7 @@ Tags.parse = async (req, data, meta, link) => {
}
// Link Tags
var defaultLinks = [{
const defaultLinks = [{
rel: 'icon',
type: 'image/x-icon',
href: `${relative_path}/favicon.ico${Meta.config['cache-buster'] ? `?${Meta.config['cache-buster']}` : ''}`,
@ -160,7 +160,7 @@ Tags.parse = async (req, data, meta, link) => {
addSiteOGImage(meta);
addIfNotExists(meta, 'property', 'og:title', Meta.config.title || 'NodeBB');
var ogUrl = url + (req.originalUrl !== '/' ? stripRelativePath(req.originalUrl) : '');
const ogUrl = url + (req.originalUrl !== '/' ? stripRelativePath(req.originalUrl) : '');
addIfNotExists(meta, 'property', 'og:url', ogUrl);
addIfNotExists(meta, 'name', 'description', Meta.config.description);
addIfNotExists(meta, 'property', 'og:description', Meta.config.description);
@ -174,7 +174,7 @@ Tags.parse = async (req, data, meta, link) => {
};
function addIfNotExists(meta, keyName, tagName, value) {
var exists = false;
let exists = false;
meta.forEach((tag) => {
if (tag[keyName] === tagName) {
exists = true;
@ -182,7 +182,7 @@ function addIfNotExists(meta, keyName, tagName, value) {
});
if (!exists && value) {
var data = {
const data = {
content: utils.escapeHTML(String(value)),
};
data[keyName] = tagName;
@ -200,7 +200,7 @@ function stripRelativePath(url) {
function addSiteOGImage(meta) {
const key = Meta.config['og:image'] ? 'og:image' : 'brand:logo';
var ogImage = stripRelativePath(Meta.config[key] || '');
let ogImage = stripRelativePath(Meta.config[key] || '');
if (ogImage && !ogImage.startsWith('http')) {
ogImage = url + ogImage;
}

@ -23,15 +23,15 @@ const viewsPath = nconf.get('views_dir');
const Templates = module.exports;
async function processImports(paths, templatePath, source) {
var regex = /<!-- IMPORT (.+?) -->/;
const regex = /<!-- IMPORT (.+?) -->/;
var matches = source.match(regex);
const matches = source.match(regex);
if (!matches) {
return source;
}
var partial = matches[1];
const partial = matches[1];
if (paths[partial] && templatePath !== partial) {
const partialSource = await fs.promises.readFile(paths[partial], 'utf8');
source = source.replace(regex, partialSource);
@ -72,9 +72,9 @@ async function getTemplateDirs(activePlugins) {
themeTemplates.push(nconf.get('base_templates_path'));
themeTemplates = _.uniq(themeTemplates.reverse());
var coreTemplatesPath = nconf.get('core_templates_path');
const coreTemplatesPath = nconf.get('core_templates_path');
var templateDirs = _.uniq([coreTemplatesPath].concat(themeTemplates, pluginTemplates));
let templateDirs = _.uniq([coreTemplatesPath].concat(themeTemplates, pluginTemplates));
templateDirs = await Promise.all(templateDirs.map(async path => (await file.exists(path) ? path : false)));
return templateDirs.filter(Boolean);
@ -90,7 +90,7 @@ async function getTemplateFiles(dirs) {
return files;
}));
var dict = {};
const dict = {};
buckets.forEach((files) => {
files.forEach((file) => {
dict[file.name] = file.path;
@ -103,7 +103,7 @@ async function getTemplateFiles(dirs) {
async function compileTemplate(filename, source) {
let paths = await file.walk(viewsPath);
paths = _.fromPairs(paths.map((p) => {
var relative = path.relative(viewsPath, p).replace(/\\/g, '/');
const relative = path.relative(viewsPath, p).replace(/\\/g, '/');
return [relative, p];
}));

@ -139,13 +139,13 @@ Themes.setupPaths = async () => {
currentThemeId: Meta.configs.get('theme:id'),
});
var themeId = data.currentThemeId || 'nodebb-theme-persona';
const themeId = data.currentThemeId || 'nodebb-theme-persona';
if (process.env.NODE_ENV === 'development') {
winston.info(`[themes] Using theme ${themeId}`);
}
var themeObj = data.themesData.find(themeObj => themeObj.id === themeId);
const themeObj = data.themesData.find(themeObj => themeObj.id === themeId);
if (!themeObj) {
throw new Error('[[error:theme-not-found]]');
@ -156,8 +156,8 @@ Themes.setupPaths = async () => {
Themes.setPath = function (themeObj) {
// Theme's templates path
var themePath = nconf.get('base_templates_path');
var fallback = path.join(nconf.get('themes_path'), themeObj.id, 'templates');
let themePath = nconf.get('base_templates_path');
const fallback = path.join(nconf.get('themes_path'), themeObj.id, 'templates');
if (themeObj.templates) {
themePath = path.join(nconf.get('themes_path'), themeObj.id, themeObj.templates);

@ -1,19 +1,19 @@
'use strict';
var winston = require('winston');
var jsesc = require('jsesc');
var nconf = require('nconf');
var semver = require('semver');
var user = require('../user');
var meta = require('../meta');
var plugins = require('../plugins');
var privileges = require('../privileges');
var utils = require('../../public/src/utils');
var versions = require('../admin/versions');
var helpers = require('./helpers');
var controllers = {
const winston = require('winston');
const jsesc = require('jsesc');
const nconf = require('nconf');
const semver = require('semver');
const user = require('../user');
const meta = require('../meta');
const plugins = require('../plugins');
const privileges = require('../privileges');
const utils = require('../../public/src/utils');
const versions = require('../admin/versions');
const helpers = require('./helpers');
const controllers = {
api: require('../controllers/api'),
helpers: require('../controllers/helpers'),
};
@ -27,7 +27,7 @@ middleware.buildHeader = helpers.try(async (req, res, next) => {
});
middleware.renderHeader = async (req, res, data) => {
var custom_header = {
const custom_header = {
plugins: [],
authentication: [],
};
@ -42,21 +42,21 @@ middleware.renderHeader = async (req, res, data) => {
privileges: privileges.admin.get(req.uid),
});
var userData = results.userData;
const userData = results.userData;
userData.uid = req.uid;
userData['email:confirmed'] = userData['email:confirmed'] === 1;
userData.privileges = results.privileges;
var acpPath = req.path.slice(1).split('/');
let acpPath = req.path.slice(1).split('/');
acpPath.forEach((path, i) => {
acpPath[i] = path.charAt(0).toUpperCase() + path.slice(1);
});
acpPath = acpPath.join(' > ');
var version = nconf.get('version');
const version = nconf.get('version');
res.locals.config.userLang = res.locals.config.acpLang || res.locals.config.userLang;
var templateValues = {
let templateValues = {
config: res.locals.config,
configJSON: jsesc(JSON.stringify(res.locals.config), { isScriptContext: true }),
relative_path: res.locals.config.relative_path,

@ -1,33 +1,33 @@
'use strict';
var async = require('async');
var path = require('path');
var csrf = require('csurf');
var validator = require('validator');
var nconf = require('nconf');
var ensureLoggedIn = require('connect-ensure-login');
var toobusy = require('toobusy-js');
var LRU = require('lru-cache');
var util = require('util');
var plugins = require('../plugins');
var meta = require('../meta');
var user = require('../user');
var groups = require('../groups');
var analytics = require('../analytics');
var privileges = require('../privileges');
var helpers = require('./helpers');
var controllers = {
const async = require('async');
const path = require('path');
const csrf = require('csurf');
const validator = require('validator');
const nconf = require('nconf');
const ensureLoggedIn = require('connect-ensure-login');
const toobusy = require('toobusy-js');
const LRU = require('lru-cache');
const util = require('util');
const plugins = require('../plugins');
const meta = require('../meta');
const user = require('../user');
const groups = require('../groups');
const analytics = require('../analytics');
const privileges = require('../privileges');
const helpers = require('./helpers');
const controllers = {
api: require('../controllers/api'),
helpers: require('../controllers/helpers'),
};
var delayCache = new LRU({
const delayCache = new LRU({
maxAge: 1000 * 60,
});
var middleware = module.exports;
const middleware = module.exports;
const relative_path = nconf.get('relative_path');
@ -66,7 +66,7 @@ require('./expose')(middleware);
middleware.assert = require('./assert');
middleware.stripLeadingSlashes = function stripLeadingSlashes(req, res, next) {
var target = req.originalUrl.replace(relative_path, '');
const target = req.originalUrl.replace(relative_path, '');
if (target.startsWith('//')) {
return res.redirect(relative_path + target.replace(/^\/+/, '/'));
}
@ -118,7 +118,7 @@ middleware.routeTouchIcon = function routeTouchIcon(req, res) {
if (meta.config['brand:touchIcon'] && validator.isURL(meta.config['brand:touchIcon'])) {
return res.redirect(meta.config['brand:touchIcon']);
}
var iconPath = '';
let iconPath = '';
if (meta.config['brand:touchIcon']) {
iconPath = path.join(nconf.get('upload_path'), meta.config['brand:touchIcon'].replace(/assets\/uploads/, ''));
} else {
@ -160,8 +160,8 @@ middleware.privateUploads = function privateUploads(req, res, next) {
}
if (req.path.startsWith(`${nconf.get('relative_path')}/assets/uploads/files`)) {
var extensions = (meta.config.privateUploadsExtensions || '').split(',').filter(Boolean);
var ext = path.extname(req.path);
const extensions = (meta.config.privateUploadsExtensions || '').split(',').filter(Boolean);
let ext = path.extname(req.path);
ext = ext ? ext.replace(/^\./, '') : ext;
if (!extensions.length || extensions.includes(ext)) {
return res.status(403).json('not-allowed');
@ -192,7 +192,7 @@ middleware.delayLoading = function delayLoading(req, res, next) {
// Introduces an artificial delay during load so that brute force attacks are effectively mitigated
// Add IP to cache so if too many requests are made, subsequent requests are blocked for a minute
var timesSeen = delayCache.get(req.ip) || 0;
let timesSeen = delayCache.get(req.ip) || 0;
if (timesSeen > 10) {
return res.sendStatus(429);
}

@ -384,12 +384,12 @@ Notifications.merge = async function (notifications) {
case 'notifications:user_started_following_you':
case 'notifications:user_posted_to':
case 'notifications:user_flagged_post_in':
case 'notifications:user_flagged_user':
var usernames = _.uniq(set.map(notifObj => notifObj && notifObj.user && notifObj.user.username));
var numUsers = usernames.length;
case 'notifications:user_flagged_user': {
const usernames = _.uniq(set.map(notifObj => notifObj && notifObj.user && notifObj.user.username));
const numUsers = usernames.length;
var title = utils.decodeHTMLEntities(notifications[modifyIndex].topicTitle || '');
var titleEscaped = title.replace(/%/g, '&#37;').replace(/,/g, '&#44;');
const title = utils.decodeHTMLEntities(notifications[modifyIndex].topicTitle || '');
let titleEscaped = title.replace(/%/g, '&#37;').replace(/,/g, '&#44;');
titleEscaped = titleEscaped ? (`, ${titleEscaped}`) : '';
if (numUsers === 2) {
@ -399,7 +399,7 @@ Notifications.merge = async function (notifications) {
}
notifications[modifyIndex].path = set[set.length - 1].path;
break;
} break;
case 'new_register':
notifications[modifyIndex].bodyShort = `[[notifications:${mergeId}_multiple, ${set.length}]]`;

@ -1,9 +1,9 @@
'use strict';
var qs = require('querystring');
var _ = require('lodash');
const qs = require('querystring');
const _ = require('lodash');
var pagination = module.exports;
const pagination = module.exports;
pagination.create = function (currentPage, pageCount, queryObj) {
if (pageCount <= 1) {
@ -19,17 +19,17 @@ pagination.create = function (currentPage, pageCount, queryObj) {
};
}
pageCount = parseInt(pageCount, 10);
var pagesToShow = [1, 2, pageCount - 1, pageCount];
let pagesToShow = [1, 2, pageCount - 1, pageCount];
currentPage = parseInt(currentPage, 10) || 1;
var previous = Math.max(1, currentPage - 1);
var next = Math.min(pageCount, currentPage + 1);
const previous = Math.max(1, currentPage - 1);
const next = Math.min(pageCount, currentPage + 1);
var startPage = Math.max(1, currentPage - 2);
let startPage = Math.max(1, currentPage - 2);
if (startPage > pageCount - 5) {
startPage -= 2 - (pageCount - currentPage);
}
var i;
let i;
for (i = 0; i < 5; i += 1) {
pagesToShow.push(startPage + i);
}
@ -40,7 +40,7 @@ pagination.create = function (currentPage, pageCount, queryObj) {
delete queryObj._;
var pages = pagesToShow.map((page) => {
const pages = pagesToShow.map((page) => {
queryObj.page = page;
return { page: page, active: page === currentPage, qs: qs.stringify(queryObj) };
});
@ -53,7 +53,7 @@ pagination.create = function (currentPage, pageCount, queryObj) {
}
}
var data = { rel: [], pages: pages, currentPage: currentPage, pageCount: pageCount };
const data = { rel: [], pages: pages, currentPage: currentPage, pageCount: pageCount };
queryObj.page = previous;
data.prev = { page: previous, active: currentPage > 1, qs: qs.stringify(queryObj) };
queryObj.page = next;

@ -43,7 +43,7 @@ Data.loadPluginInfo = async function (pluginPath) {
pluginData.nbbpm = packageData.nbbpm;
pluginData.path = pluginPath;
} catch (err) {
var pluginDir = path.basename(pluginPath);
const pluginDir = path.basename(pluginPath);
winston.error(`[plugins/${pluginDir}] Error in plugin.json or package.json!${err.stack}`);
throw new Error('[[error:parse-error]]');
@ -71,7 +71,7 @@ Data.getActive = async function () {
Data.getStaticDirectories = async function (pluginData) {
var validMappedPath = /^[\w\-_]+$/;
const validMappedPath = /^[\w\-_]+$/;
if (!pluginData.staticDirs) {
return;
@ -187,10 +187,10 @@ Data.getModules = async function getModules(pluginData) {
let pluginModules = pluginData.modules;
if (Array.isArray(pluginModules)) {
var strip = parseInt(pluginData.modulesStrip, 10) || 0;
const strip = parseInt(pluginData.modulesStrip, 10) || 0;
pluginModules = pluginModules.reduce((prev, modulePath) => {
var key;
let key;
if (strip) {
key = modulePath.replace(new RegExp(`.?(/[^/]+){${strip}}/`), '');
} else {

@ -80,7 +80,7 @@ Hooks.register = function (id, data) {
};
Hooks.unregister = function (id, hook, method) {
var hooks = plugins.loadedHooks[hook] || [];
const hooks = plugins.loadedHooks[hook] || [];
plugins.loadedHooks[hook] = hooks.filter(hookData => hookData && hookData.id !== id && hookData.method !== method);
};

@ -15,8 +15,8 @@ const meta = require('../meta');
const { pluginNamePattern, themeNamePattern, paths } = require('../constants');
var app;
var middleware;
let app;
let middleware;
const Plugins = module.exports;
@ -136,7 +136,7 @@ Plugins.reload = async function () {
if (Plugins.versionWarning.length && nconf.get('isPrimary')) {
console.log('');
winston.warn('[plugins/load] The following plugins may not be compatible with your version of NodeBB. This may cause unintended behaviour or crashing. In the event of an unresponsive NodeBB caused by this plugin, run `./nodebb reset -p PLUGINNAME` to disable it.');
for (var x = 0, numPlugins = Plugins.versionWarning.length; x < numPlugins; x += 1) {
for (let x = 0, numPlugins = Plugins.versionWarning.length; x < numPlugins; x += 1) {
console.log(' * '.yellow + Plugins.versionWarning[x]);
}
console.log('');
@ -156,7 +156,7 @@ Plugins.reload = async function () {
};
Plugins.reloadRoutes = async function (params) {
var controllers = require('../controllers');
const controllers = require('../controllers');
await Plugins.hooks.fire('static:app.load', { app: app, router: params.router, middleware: middleware, controllers: controllers });
winston.verbose('[plugins] All plugins reloaded and rerouted');
};
@ -244,7 +244,7 @@ Plugins.normalise = async function (apiReturn) {
const pluginArray = [];
for (var key in pluginMap) {
for (const key in pluginMap) {
if (pluginMap.hasOwnProperty(key)) {
pluginArray.push(pluginMap[key]);
}
@ -291,7 +291,7 @@ Plugins.showInstalled = async function () {
async function findNodeBBModules(dirs) {
const pluginPaths = [];
await async.each(dirs, (dirname, next) => {
var dirPath = path.join(Plugins.nodeModulesPath, dirname);
const dirPath = path.join(Plugins.nodeModulesPath, dirname);
async.waterfall([
function (cb) {
@ -320,7 +320,7 @@ async function findNodeBBModules(dirs) {
return next();
}
var subdirPath = path.join(dirPath, subdir);
const subdirPath = path.join(dirPath, subdir);
fs.stat(subdirPath, (err, stats) => {
if (err && err.code !== 'ENOENT') {
return next(err);

@ -42,7 +42,7 @@ module.exports = function (Plugins) {
},
};
var methods = {};
let methods = {};
if (Array.isArray(fields)) {
fields.forEach((field) => {
methods[field] = handlers[field];

@ -1,15 +1,15 @@
'use strict';
var _ = require('lodash');
const _ = require('lodash');
var meta = require('../meta');
var db = require('../database');
var plugins = require('../plugins');
var user = require('../user');
var topics = require('../topics');
var categories = require('../categories');
var groups = require('../groups');
var utils = require('../utils');
const meta = require('../meta');
const db = require('../database');
const plugins = require('../plugins');
const user = require('../user');
const topics = require('../topics');
const categories = require('../categories');
const groups = require('../groups');
const utils = require('../utils');
module.exports = function (Posts) {
Posts.create = async function (data) {

@ -1,15 +1,15 @@
'use strict';
var nconf = require('nconf');
var url = require('url');
var winston = require('winston');
const nconf = require('nconf');
const url = require('url');
const winston = require('winston');
const sanitize = require('sanitize-html');
const _ = require('lodash');
var meta = require('../meta');
var plugins = require('../plugins');
var translator = require('../translator');
var utils = require('../utils');
const meta = require('../meta');
const plugins = require('../plugins');
const translator = require('../translator');
const utils = require('../utils');
let sanitizeConfig = {
allowedTags: sanitize.defaults.allowedTags.concat([
@ -78,9 +78,9 @@ module.exports = function (Posts) {
if (!content) {
return content;
}
var parsed;
var current = regex.regex.exec(content);
var absolute;
let parsed;
let current = regex.regex.exec(content);
let absolute;
while (current !== null) {
if (current[1]) {
try {
@ -154,7 +154,7 @@ module.exports = function (Posts) {
function sanitizeSignature(signature) {
signature = translator.escape(signature);
var tagsToStrip = [];
const tagsToStrip = [];
if (meta.config['signatures:disableLinks']) {
tagsToStrip.push('a');

@ -81,8 +81,8 @@ module.exports = function (Posts) {
}
function toObject(key, data) {
var obj = {};
for (var i = 0; i < data.length; i += 1) {
const obj = {};
for (let i = 0; i < data.length; i += 1) {
obj[data[i][key]] = data[i];
}
return obj;

@ -1,8 +1,8 @@
'use strict';
var topics = require('../topics');
var utils = require('../utils');
const topics = require('../topics');
const utils = require('../utils');
module.exports = function (Posts) {
Posts.getPostsFromSet = async function (set, start, stop, uid, reverse) {

@ -13,7 +13,7 @@ function setupWinston() {
return;
}
var formats = [];
const formats = [];
if (nconf.get('log-colorize') !== 'false') {
formats.push(winston.format.colorize());
}
@ -23,7 +23,7 @@ function setupWinston() {
formats.push(winston.format.json());
} else {
const timestampFormat = winston.format((info) => {
var dateString = `${new Date().toISOString()} [${nconf.get('port')}/${global.process.pid}]`;
const dateString = `${new Date().toISOString()} [${nconf.get('port')}/${global.process.pid}]`;
info.level = `${dateString} - ${info.level}`;
return info;
});
@ -60,10 +60,10 @@ function loadConfig(configFile) {
});
// Explicitly cast as Bool, loader.js passes in isCluster as string 'true'/'false'
var castAsBool = ['isCluster', 'isPrimary', 'jobsDisabled'];
const castAsBool = ['isCluster', 'isPrimary', 'jobsDisabled'];
nconf.stores.env.readOnly = false;
castAsBool.forEach((prop) => {
var value = nconf.get(prop);
const value = nconf.get(prop);
if (value !== undefined) {
nconf.set(prop, typeof value === 'boolean' ? value : String(value).toLowerCase() === 'true');
}
@ -104,10 +104,10 @@ function loadConfig(configFile) {
}
function versionCheck() {
var version = process.version.slice(1);
var range = pkg.engines.node;
var semver = require('semver');
var compatible = semver.satisfies(version, range);
const version = process.version.slice(1);
const range = pkg.engines.node;
const semver = require('semver');
const compatible = semver.satisfies(version, range);
if (!compatible) {
winston.warn('Your version of Node.js is too outdated for NodeBB. Please update your version of Node.js.');

@ -112,7 +112,7 @@ helpers.getUserPrivileges = async function (cid, userPrivileges) {
memberData.forEach((member) => {
member.privileges = {};
for (var x = 0, numPrivs = userPrivileges.length; x < numPrivs; x += 1) {
for (let x = 0, numPrivs = userPrivileges.length; x < numPrivs; x += 1) {
member.privileges[userPrivileges[x]] = memberSets[x].includes(parseInt(member.uid, 10));
}
});
@ -145,7 +145,7 @@ helpers.getGroupPrivileges = async function (cid, groupPrivileges) {
const memberData = groupNames.map((member, index) => {
const memberPrivs = {};
for (var x = 0, numPrivs = groupPrivileges.length; x < numPrivs; x += 1) {
for (let x = 0, numPrivs = groupPrivileges.length; x < numPrivs; x += 1) {
memberPrivs[groupPrivileges[x]] = memberSets[x].includes(member);
}
return {

@ -1,6 +1,6 @@
'use strict';
var privileges = module.exports;
const privileges = module.exports;
privileges.privilegeLabels = [
{ name: '[[admin/manage/privileges:find-category]]' },

@ -162,12 +162,12 @@ module.exports = function (privileges) {
return { flag: false, message: '[[error:topic-locked]]' };
}
var postDeleteDuration = meta.config.postDeleteDuration;
const postDeleteDuration = meta.config.postDeleteDuration;
if (!results.isMod && postDeleteDuration && (Date.now() - postData.timestamp > postDeleteDuration * 1000)) {
return { flag: false, message: `[[error:post-delete-duration-expired, ${meta.config.postDeleteDuration}]]` };
}
var deleterUid = postData.deleterUid;
var flag = results['posts:delete'] && ((results.isOwner && (deleterUid === 0 || deleterUid === postData.uid)) || results.isMod);
const deleterUid = postData.deleterUid;
const flag = results['posts:delete'] && ((results.isOwner && (deleterUid === 0 || deleterUid === postData.uid)) || results.isMod);
return { flag: flag, message: '[[error:no-privileges]]' };
};

@ -1,18 +1,18 @@
'use strict';
var EventEmitter = require('events');
var nconf = require('nconf');
const EventEmitter = require('events');
const nconf = require('nconf');
var real;
var noCluster;
var singleHost;
let real;
let noCluster;
let singleHost;
function get() {
if (real) {
return real;
}
var pubsub;
let pubsub;
if (!nconf.get('isCluster')) {
if (noCluster) {

@ -3,13 +3,13 @@
const winston = require('winston');
const nconf = require('nconf');
var helpers = require('./helpers');
const helpers = require('./helpers');
var setupPageRoute = helpers.setupPageRoute;
const setupPageRoute = helpers.setupPageRoute;
module.exports = function (app, middleware, controllers) {
var middlewares = [middleware.exposeUid, middleware.canViewUsers];
var accountMiddlewares = [middleware.exposeUid, middleware.canViewUsers, middleware.checkAccountPermissions];
const middlewares = [middleware.exposeUid, middleware.canViewUsers];
const accountMiddlewares = [middleware.exposeUid, middleware.canViewUsers, middleware.checkAccountPermissions];
setupPageRoute(app, '/me', middleware, [], middleware.redirectMeToUserslug);
setupPageRoute(app, '/me/*', middleware, [], middleware.redirectMeToUserslug);

@ -1,11 +1,11 @@
'use strict';
var express = require('express');
const express = require('express');
var uploadsController = require('../controllers/uploads');
const uploadsController = require('../controllers/uploads');
module.exports = function (app, middleware, controllers) {
var router = express.Router();
const router = express.Router();
app.use('/api', router);
router.get('/config', middleware.applyCSRF, middleware.authenticateOrGuest, controllers.api.getConfig);
@ -25,9 +25,9 @@ module.exports = function (app, middleware, controllers) {
router.get('/topic/teaser/:topic_id', controllers.topics.teaser);
router.get('/topic/pagination/:topic_id', controllers.topics.pagination);
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
var middlewares = [middleware.maintenanceMode, multipartMiddleware, middleware.validateFiles, middleware.applyCSRF];
const multipart = require('connect-multiparty');
const multipartMiddleware = multipart();
const middlewares = [middleware.maintenanceMode, multipartMiddleware, middleware.validateFiles, middleware.applyCSRF];
router.post('/post/upload', middlewares, uploadsController.uploadPost);
router.post('/user/:userslug/uploadpicture', middlewares.concat([middleware.exposeUid, middleware.authenticate, middleware.canViewUsers, middleware.checkAccountPermissions]), controllers.accounts.edit.uploadPicture);

@ -1,19 +1,19 @@
'use strict';
var async = require('async');
var passport = require('passport');
var passportLocal = require('passport-local').Strategy;
const async = require('async');
const passport = require('passport');
const passportLocal = require('passport-local').Strategy;
const BearerStrategy = require('passport-http-bearer').Strategy;
var winston = require('winston');
const winston = require('winston');
const meta = require('../meta');
var controllers = require('../controllers');
var helpers = require('../controllers/helpers');
var plugins = require('../plugins');
const controllers = require('../controllers');
const helpers = require('../controllers/helpers');
const plugins = require('../plugins');
var loginStrategies = [];
let loginStrategies = [];
var Auth = module.exports;
const Auth = module.exports;
Auth.initialize = function (app, middleware) {
const passportInitMiddleware = passport.initialize();
@ -161,9 +161,9 @@ Auth.reloadRoutes = async function (params) {
});
});
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
var middlewares = [multipartMiddleware, Auth.middleware.applyCSRF, Auth.middleware.applyBlacklist];
const multipart = require('connect-multiparty');
const multipartMiddleware = multipart();
const middlewares = [multipartMiddleware, Auth.middleware.applyCSRF, Auth.middleware.applyBlacklist];
router.post('/register', middlewares, controllers.authentication.register);
router.post('/register/complete', middlewares, controllers.authentication.registerComplete);

@ -1,13 +1,13 @@
'use strict';
var express = require('express');
var nconf = require('nconf');
const express = require('express');
const nconf = require('nconf');
const fs = require('fs').promises;
const path = require('path');
module.exports = function (app) {
var router = express.Router();
const router = express.Router();
router.get('/test', (req, res) => {
res.redirect(404);

@ -355,7 +355,7 @@ function generateForPostsFeed(feedOptions, posts) {
feedOptions.feed_url = nconf.get('url') + feedOptions.feed_url;
feedOptions.site_url = nconf.get('url') + feedOptions.site_url;
var feed = new rss(feedOptions);
const feed = new rss(feedOptions);
if (posts.length > 0) {
feed.pubDate = new Date(parseInt(posts[0].timestamp, 10)).toUTCString();

@ -1,27 +1,27 @@
'use strict';
var nconf = require('nconf');
var winston = require('winston');
var path = require('path');
var express = require('express');
var meta = require('../meta');
var controllers = require('../controllers');
var plugins = require('../plugins');
var accountRoutes = require('./accounts');
var metaRoutes = require('./meta');
var apiRoutes = require('./api');
var adminRoutes = require('./admin');
var feedRoutes = require('./feeds');
var authRoutes = require('./authentication');
const nconf = require('nconf');
const winston = require('winston');
const path = require('path');
const express = require('express');
const meta = require('../meta');
const controllers = require('../controllers');
const plugins = require('../plugins');
const accountRoutes = require('./accounts');
const metaRoutes = require('./meta');
const apiRoutes = require('./api');
const adminRoutes = require('./admin');
const feedRoutes = require('./feeds');
const authRoutes = require('./authentication');
const writeRoutes = require('./write');
var helpers = require('./helpers');
const helpers = require('./helpers');
var setupPageRoute = helpers.setupPageRoute;
const setupPageRoute = helpers.setupPageRoute;
function mainRoutes(app, middleware, controllers) {
var loginRegisterMiddleware = [middleware.redirectToAccountIfLoggedIn];
const loginRegisterMiddleware = [middleware.redirectToAccountIfLoggedIn];
setupPageRoute(app, '/login', middleware, loginRegisterMiddleware, controllers.login);
setupPageRoute(app, '/register', middleware, loginRegisterMiddleware, controllers.register);
@ -78,13 +78,13 @@ function categoryRoutes(app, middleware, controllers) {
}
function userRoutes(app, middleware, controllers) {
var middlewares = [middleware.canViewUsers];
const middlewares = [middleware.canViewUsers];
setupPageRoute(app, '/users', middleware, middlewares, controllers.users.index);
}
function groupRoutes(app, middleware, controllers) {
var middlewares = [middleware.canViewGroups];
const middlewares = [middleware.canViewGroups];
setupPageRoute(app, '/groups', middleware, middlewares, controllers.groups.list);
setupPageRoute(app, '/groups/:slug', middleware, middlewares, controllers.groups.details);
@ -96,7 +96,7 @@ module.exports = async function (app, middleware) {
router.render = function () {
app.render.apply(app, arguments);
};
var ensureLoggedIn = require('connect-ensure-login');
const ensureLoggedIn = require('connect-ensure-login');
router.all('(/+api|/+api/*?)', middleware.prepareAPI);
router.all('(/+api/admin|/+api/admin/*?)', middleware.authenticate, middleware.admin.checkPrivileges);
@ -135,7 +135,7 @@ function addCoreRoutes(app, router, middleware) {
userRoutes(router, middleware, controllers);
groupRoutes(router, middleware, controllers);
var relativePath = nconf.get('relative_path');
const relativePath = nconf.get('relative_path');
app.use(relativePath || '/', router);
if (process.env.NODE_ENV === 'development') {
@ -144,12 +144,12 @@ function addCoreRoutes(app, router, middleware) {
app.use(middleware.privateUploads);
var statics = [
const statics = [
{ route: '/assets', path: path.join(__dirname, '../../build/public') },
{ route: '/assets', path: path.join(__dirname, '../../public') },
{ route: '/plugins', path: path.join(__dirname, '../../build/public/plugins') },
];
var staticOptions = {
const staticOptions = {
maxAge: app.enabled('cache') ? 5184000000 : 0,
};

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

Loading…
Cancel
Save