Moved settings.js to ts.

This commit is contained in:
SamTV12345 2024-02-21 21:48:51 +01:00
parent 71c74bc633
commit fbf8667019
44 changed files with 852 additions and 760 deletions

View file

@ -14,7 +14,7 @@ import fs from 'fs';
const hooks = require('../../static/js/pluginfw/hooks');
import log4js from 'log4js';
const SessionStore = require('../db/SessionStore');
import * as settings from '../utils/Settings';
import {getEpVersion, getGitCommit, settings} from '../utils/Settings';
const stats = require('../stats')
import util from 'util';
const webaccess = require('./express/webaccess');
@ -68,9 +68,9 @@ const closeServer = async () => {
exports.createServer = async () => {
console.log('Report bugs at https://github.com/ether/etherpad-lite/issues');
serverName = `Etherpad ${settings.getGitCommit()} (https://etherpad.org)`;
serverName = `Etherpad ${getGitCommit()} (https://etherpad.org)`;
console.log(`Your Etherpad version is ${settings.getEpVersion()} (${settings.getGitCommit()})`);
console.log(`Your Etherpad version is ${getEpVersion()} (${getGitCommit()})`);
await exports.restartServer();

View file

@ -7,7 +7,7 @@ import {QueryType} from "../../types/QueryType";
import {PluginType} from "../../types/Plugin";
const eejs = require('../../eejs');
import * as settings from '../../utils/Settings';
import {getEpVersion, getGitCommit} from '../../utils/Settings';
const installer = require('../../../static/js/pluginfw/installer');
const pluginDefs = require('../../../static/js/pluginfw/plugin_defs');
const plugins = require('../../../static/js/pluginfw/plugins');
@ -24,8 +24,8 @@ exports.expressCreateServer = (hookName:string, args: ArgsExpressType, cb:Functi
});
args.app.get('/admin/plugins/info', (req:any, res:any) => {
const gitCommit = settings.getGitCommit();
const epVersion = settings.getEpVersion();
const gitCommit = getGitCommit();
const epVersion = getEpVersion();
res.send(eejs.require('ep_etherpad-lite/templates/admin/plugins-info.html', {
gitCommit,

View file

@ -4,8 +4,7 @@ const eejs = require('../../eejs');
const fsp = require('fs').promises;
const hooks = require('../../../static/js/pluginfw/hooks');
const plugins = require('../../../static/js/pluginfw/plugins');
import {reloadSettings, settingsFilename, showSettingsInAdminPage} from '../../utils/Settings';
import * as settings from '../../utils/Settings';
import {reloadSettings, settings} from '../../utils/Settings';
exports.expressCreateServer = (hookName:string, {app}:any) => {
app.get('/admin/settings', (req:any, res:any) => {
@ -26,12 +25,12 @@ exports.socketio = (hookName:string, {io}:any) => {
socket.on('load', async (query:string):Promise<any> => {
let data;
try {
data = await fsp.readFile(settingsFilename, 'utf8');
data = await fsp.readFile(settings.settingsFilename, 'utf8');
} catch (err) {
return console.log(err);
}
// if showSettingsInAdminPage is set to false, then return NOT_ALLOWED in the result
if (!showSettingsInAdminPage) {
if (!settings.showSettingsInAdminPage) {
socket.emit('settings', {results: 'NOT_ALLOWED'});
} else {
socket.emit('settings', {results: data});
@ -39,7 +38,7 @@ exports.socketio = (hookName:string, {io}:any) => {
});
socket.on('saveSettings', async (newSettings:string) => {
await fsp.writeFile(settingsFilename, newSettings);
await fsp.writeFile(settings.settingsFilename, newSettings);
socket.emit('saveprogress', 'saved');
});

View file

@ -2,7 +2,7 @@
const log4js = require('log4js');
const clientLogger = log4js.getLogger('client');
const {Formidable} = require('formidable');
import {Formidable} from 'formidable';
const apiHandler = require('../../handler/APIHandler');
const util = require('util');
@ -25,6 +25,7 @@ exports.expressPreSession = async (hookName:string, {app}:any) => {
// The Etherpad client side sends information about client side javscript errors
app.post('/jserror', (req:any, res:any, next:Function) => {
(async () => {
// @ts-ignore
const data = JSON.parse(await parseJserrorForm(req));
clientLogger.warn(`${data.msg} --`, {
[util.inspect.custom]: (depth: number, options:any) => {

View file

@ -3,7 +3,7 @@
import {ArgsExpressType} from "../../types/ArgsExpressType";
const hasPadAccess = require('../../padaccess');
import {exportAvailable, importExportRateLimiting} from '../../utils/Settings';
import {exportAvailable, settings} from '../../utils/Settings';
const exportHandler = require('../../handler/ExportHandler');
const importHandler = require('../../handler/ImportHandler');
const padManager = require('../../db/PadManager');
@ -14,7 +14,7 @@ const webaccess = require('./webaccess');
exports.expressCreateServer = (hookName:string, args:ArgsExpressType, cb:Function) => {
const limiter = rateLimit({
...importExportRateLimiting,
...settings.importExportRateLimiting,
handler: (request:any) => {
if (request.rateLimit.current === request.rateLimit.limit + 1) {
// when the rate limiter triggers, write a warning in the logs

View file

@ -24,7 +24,7 @@ const cloneDeep = require('lodash.clonedeep');
const createHTTPError = require('http-errors');
const apiHandler = require('../../handler/APIHandler');
import {ssl} from '../../utils/Settings';
import {settings} from '../../utils/Settings';
const log4js = require('log4js');
const logger = log4js.getLogger('API');
@ -724,5 +724,5 @@ const getApiRootForVersion = (version:string, style:any = APIPathStyle.FLAT): st
const generateServerForApiVersion = (apiRoot:string, req:any): {
url:string
} => ({
url: `${ssl ? 'https' : 'http'}://${req.headers.host}${apiRoot}`,
url: `${settings.ssl ? 'https' : 'http'}://${req.headers.host}${apiRoot}`,
});

View file

@ -6,7 +6,7 @@ const events = require('events');
const express = require('../express');
const log4js = require('log4js');
const proxyaddr = require('proxy-addr');
import * as settings from '../../utils/Settings';
import {settings} from '../../utils/Settings';
import {Server} from 'socket.io'
const socketIORouter = require('../../handler/SocketIORouter');
const hooks = require('../../../static/js/pluginfw/hooks');

View file

@ -6,7 +6,7 @@ const fs = require('fs');
const fsp = fs.promises;
const toolbar = require('../../utils/toolbar');
const hooks = require('../../../static/js/pluginfw/hooks');
import * as settings from '../../utils/Settings';
import {getEpVersion, root, settings} from '../../utils/Settings';
const util = require('util');
const webaccess = require('./webaccess');
@ -17,7 +17,7 @@ exports.expressPreSession = async (hookName, {app}) => {
res.set('Content-Type', 'application/health+json');
res.json({
status: 'pass',
releaseId: settings.getEpVersion(),
releaseId: getEpVersion(),
});
});
@ -31,11 +31,11 @@ exports.expressPreSession = async (hookName, {app}) => {
app.get('/robots.txt', (req, res) => {
let filePath =
path.join(settings.root, 'src', 'static', 'skins', settings.skinName, 'robots.txt');
path.join(root, 'src', 'static', 'skins', settings.skinName, 'robots.txt');
res.sendFile(filePath, (err) => {
// there is no custom robots.txt, send the default robots.txt which dissallows all
if (err) {
filePath = path.join(settings.root, 'src', 'static', 'robots.txt');
filePath = path.join(root, 'src', 'static', 'robots.txt');
res.sendFile(filePath);
}
});
@ -54,9 +54,9 @@ exports.expressPreSession = async (hookName, {app}) => {
const fns = [
...(settings.favicon ? [path.resolve(settings.root, settings.favicon)] : []),
path.join(settings.root, 'src', 'static', 'skins', settings.skinName, 'favicon.ico'),
path.join(settings.root, 'src', 'static', 'favicon.ico'),
...(settings.favicon ? [path.resolve(root, settings.favicon)] : []),
path.join(root, 'src', 'static', 'skins', settings.skinName, 'favicon.ico'),
path.join(root, 'src', 'static', 'favicon.ico'),
];
for (const fn of fns) {
try {

View file

@ -1,34 +1,37 @@
'use strict';
const fs = require('fs').promises;
const minify = require('../../utils/Minify');
const path = require('path');
const plugins = require('../../../static/js/pluginfw/plugin_defs');
import * as settings from '../../utils/Settings';
import {root, settings} from '../../utils/Settings';
const CachingMiddleware = require('../../utils/caching_middleware');
const Yajsml = require('etherpad-yajsml');
// Rewrite tar to include modules with no extensions and proper rooted paths.
const getTar = async () => {
const prefixLocalLibraryPath = (path) => {
const prefixLocalLibraryPath = (path: string) => {
if (path.charAt(0) === '$') {
return path.slice(1);
} else {
return `ep_etherpad-lite/static/js/${path}`;
}
};
const tarJson = await fs.readFile(path.join(settings.root, 'src/node/utils/tar.json'), 'utf8');
const tarJson = await fs.readFile(path.join(root, 'src/node/utils/tar.json'), 'utf8');
const tar = {};
for (const [key, relativeFiles] of Object.entries(JSON.parse(tarJson))) {
// @ts-ignore
const files = relativeFiles.map(prefixLocalLibraryPath);
// @ts-ignore
tar[prefixLocalLibraryPath(key)] = files
.concat(files.map((p) => p.replace(/\.js$/, '')))
.concat(files.map((p) => `${p.replace(/\.js$/, '')}/index.js`));
.concat(files.map((p:string) => p.replace(/\.js$/, '')))
.concat(files.map((p:string) => `${p.replace(/\.js$/, '')}/index.js`));
}
return tar;
};
exports.expressPreSession = async (hookName, {app}) => {
exports.expressPreSession = async (hookName: string, {app}:any) => {
// Cache both minified and static.
const assetCache = new CachingMiddleware();
app.all(/\/javascripts\/(.*)/, assetCache.handle.bind(assetCache));
@ -58,11 +61,13 @@ exports.expressPreSession = async (hookName, {app}) => {
// serve plugin definitions
// not very static, but served here so that client can do
// require("pluginfw/static/js/plugin-definitions.js");
app.get('/pluginfw/plugin-definitions.json', (req, res, next) => {
const clientParts = plugins.parts.filter((part) => part.client_hooks != null);
app.get('/pluginfw/plugin-definitions.json', (req:any, res:any, next:Function) => {
const clientParts = plugins.parts.filter((part:any) => part.client_hooks != null);
const clientPlugins = {};
for (const name of new Set(clientParts.map((part) => part.plugin))) {
for (const name of new Set(clientParts.map((part:any) => part.plugin))) {
// @ts-ignore
clientPlugins[name] = {...plugins.plugins[name]};
// @ts-ignore
delete clientPlugins[name].package;
}
res.setHeader('Content-Type', 'application/json; charset=utf-8');

View file

@ -4,7 +4,7 @@ const path = require('path');
const fsp = require('fs').promises;
const plugins = require('../../../static/js/pluginfw/plugin_defs');
const sanitizePathname = require('../../utils/sanitizePathname');
import * as settings from '../../utils/Settings';
import {root, settings} from '../../utils/Settings';
// Returns all *.js files under specDir (recursively) as relative paths to specDir, using '/'
// instead of path.sep to separate pathname components.
@ -57,7 +57,7 @@ exports.expressPreSession = async (hookName, {app}) => {
})().catch((err) => next(err || new Error(err)));
});
const rootTestFolder = path.join(settings.root, 'src/tests/frontend/');
const rootTestFolder = path.join(root, 'src/tests/frontend/');
app.get('/tests/frontend/index.html', (req, res) => {
res.redirect(['./', ...req.url.split('?').slice(1)].join('?'));

View file

@ -3,7 +3,7 @@
const assert = require('assert').strict;
const log4js = require('log4js');
const httpLogger = log4js.getLogger('http');
import * as settings from '../../utils/Settings';
import {settings} from '../../utils/Settings';
const hooks = require('../../../static/js/pluginfw/hooks');
const readOnlyManager = require('../../db/ReadOnlyManager');

View file

@ -9,7 +9,7 @@ const path = require('path');
const _ = require('underscore');
const pluginDefs = require('../../static/js/pluginfw/plugin_defs.js');
const existsSync = require('../utils/path_exists');
import {customLocaleStrings, maxAge, root} from '../utils/Settings';
import {settings, root} from '../utils/Settings';
// returns all existing messages merged together and grouped by langcode
// {es: {"foo": "string"}, en:...}
@ -71,9 +71,9 @@ const getAllLocales = () => {
const wrongFormatErr = Error(
'customLocaleStrings in wrong format. See documentation ' +
'for Customization for Administrators, under Localization.');
if (customLocaleStrings) {
if (typeof customLocaleStrings !== 'object') throw wrongFormatErr;
_.each(customLocaleStrings, (overrides:MapArrayType<string> , langcode:string) => {
if (settings.customLocaleStrings) {
if (typeof settings.customLocaleStrings !== 'object') throw wrongFormatErr;
_.each(settings.customLocaleStrings, (overrides:MapArrayType<string> , langcode:string) => {
if (typeof overrides !== 'object') throw wrongFormatErr;
_.each(overrides, (localeString:string|object, key:string) => {
if (typeof localeString !== 'string') throw wrongFormatErr;
@ -133,7 +133,7 @@ exports.expressPreSession = async (hookName:string, {app}:any) => {
// works with /locale/en and /locale/en.json requests
const locale = req.params.locale.split('.')[0];
if (Object.prototype.hasOwnProperty.call(exports.availableLangs, locale)) {
res.setHeader('Cache-Control', `public, max-age=${maxAge}`);
res.setHeader('Cache-Control', `public, max-age=${settings.maxAge}`);
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.send(`{"${locale}":${JSON.stringify(locales[locale])}}`);
} else {
@ -142,7 +142,7 @@ exports.expressPreSession = async (hookName:string, {app}:any) => {
});
app.get('/locales.json', (req: any, res:any) => {
res.setHeader('Cache-Control', `public, max-age=${maxAge}`);
res.setHeader('Cache-Control', `public, max-age=${settings.maxAge}`);
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.send(localeIndex);
});