small refactorings

This commit is contained in:
zadam 2023-06-29 22:10:13 +02:00
parent f4ec4e58c7
commit 48029cea7c
37 changed files with 95 additions and 155 deletions

28
package-lock.json generated
View File

@ -94,12 +94,12 @@
"jasmine": "5.0.2",
"jsdoc": "4.0.2",
"jsonc-eslint-parser": "2.3.0",
"lint-staged": "13.2.2",
"lint-staged": "13.2.3",
"lorem-ipsum": "2.0.8",
"nodemon": "2.0.22",
"prettier": "2.8.8",
"rcedit": "3.0.1",
"webpack": "5.88.0",
"webpack": "5.88.1",
"webpack-cli": "5.1.4"
},
"optionalDependencies": {
@ -8259,9 +8259,9 @@
}
},
"node_modules/lint-staged": {
"version": "13.2.2",
"resolved": "https://registry.npmjs.org/lint-staged/-/lint-staged-13.2.2.tgz",
"integrity": "sha512-71gSwXKy649VrSU09s10uAT0rWCcY3aewhMaHyl2N84oBk4Xs9HgxvUp3AYu+bNsK4NrOYYxvSgg7FyGJ+jGcA==",
"version": "13.2.3",
"resolved": "https://registry.npmjs.org/lint-staged/-/lint-staged-13.2.3.tgz",
"integrity": "sha512-zVVEXLuQIhr1Y7R7YAWx4TZLdvuzk7DnmrsTNL0fax6Z3jrpFcas+vKbzxhhvp6TA55m1SQuWkpzI1qbfDZbAg==",
"dev": true,
"dependencies": {
"chalk": "5.2.0",
@ -12571,9 +12571,9 @@
}
},
"node_modules/webpack": {
"version": "5.88.0",
"resolved": "https://registry.npmjs.org/webpack/-/webpack-5.88.0.tgz",
"integrity": "sha512-O3jDhG5e44qIBSi/P6KpcCcH7HD+nYIHVBhdWFxcLOcIGN8zGo5nqF3BjyNCxIh4p1vFdNnreZv2h2KkoAw3lw==",
"version": "5.88.1",
"resolved": "https://registry.npmjs.org/webpack/-/webpack-5.88.1.tgz",
"integrity": "sha512-FROX3TxQnC/ox4N+3xQoWZzvGXSuscxR32rbzjpXgEzWudJFEJBpdlkkob2ylrv5yzzufD1zph1OoFsLtm6stQ==",
"dev": true,
"dependencies": {
"@types/eslint-scope": "^3.7.3",
@ -19282,9 +19282,9 @@
}
},
"lint-staged": {
"version": "13.2.2",
"resolved": "https://registry.npmjs.org/lint-staged/-/lint-staged-13.2.2.tgz",
"integrity": "sha512-71gSwXKy649VrSU09s10uAT0rWCcY3aewhMaHyl2N84oBk4Xs9HgxvUp3AYu+bNsK4NrOYYxvSgg7FyGJ+jGcA==",
"version": "13.2.3",
"resolved": "https://registry.npmjs.org/lint-staged/-/lint-staged-13.2.3.tgz",
"integrity": "sha512-zVVEXLuQIhr1Y7R7YAWx4TZLdvuzk7DnmrsTNL0fax6Z3jrpFcas+vKbzxhhvp6TA55m1SQuWkpzI1qbfDZbAg==",
"dev": true,
"requires": {
"chalk": "5.2.0",
@ -22542,9 +22542,9 @@
"integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g=="
},
"webpack": {
"version": "5.88.0",
"resolved": "https://registry.npmjs.org/webpack/-/webpack-5.88.0.tgz",
"integrity": "sha512-O3jDhG5e44qIBSi/P6KpcCcH7HD+nYIHVBhdWFxcLOcIGN8zGo5nqF3BjyNCxIh4p1vFdNnreZv2h2KkoAw3lw==",
"version": "5.88.1",
"resolved": "https://registry.npmjs.org/webpack/-/webpack-5.88.1.tgz",
"integrity": "sha512-FROX3TxQnC/ox4N+3xQoWZzvGXSuscxR32rbzjpXgEzWudJFEJBpdlkkob2ylrv5yzzufD1zph1OoFsLtm6stQ==",
"dev": true,
"requires": {
"@types/eslint-scope": "^3.7.3",

View File

@ -110,14 +110,14 @@
"esm": "3.2.25",
"husky": "8.0.3",
"jsonc-eslint-parser": "2.3.0",
"lint-staged": "13.2.2",
"lint-staged": "13.2.3",
"jasmine": "5.0.2",
"jsdoc": "4.0.2",
"lorem-ipsum": "2.0.8",
"prettier": "2.8.8",
"nodemon": "2.0.22",
"rcedit": "3.0.1",
"webpack": "5.88.0",
"webpack": "5.88.1",
"webpack-cli": "5.1.4"
},
"optionalDependencies": {

View File

@ -6,7 +6,7 @@ const BEtapiToken = require('./entities/betapi_token');
const BNote = require('./entities/bnote');
const BOption = require('./entities/boption');
const BRecentNote = require('./entities/brecent_note');
const BRevision = require('./entities/brevision.js');
const BRevision = require('./entities/brevision');
const ENTITY_NAME_TO_ENTITY = {
"attachments": BAttachment,

View File

@ -1,6 +1,6 @@
const becca = require("../becca/becca");
const eu = require("./etapi_utils");
const passwordEncryptionService = require("../services/password_encryption");
const passwordEncryptionService = require("../services/encryption/password_encryption");
const etapiTokenService = require("../services/etapi_tokens");
function register(router, loginMiddleware) {

View File

@ -9,7 +9,7 @@ function getFontCss(req, res) {
return;
}
const optionsMap = optionService.getOptionsMap();
const optionsMap = optionService.getOptionMap();
const mainFontFamilyOverridden = optionsMap.mainFontFamily !== 'theme';
const treeFontFamilyOverridden = optionsMap.treeFontFamily !== 'theme';

View File

@ -4,7 +4,7 @@ const options = require('../../services/options');
const utils = require('../../services/utils');
const dateUtils = require('../../services/date_utils');
const instanceId = require('../../services/member_id');
const passwordEncryptionService = require('../../services/password_encryption');
const passwordEncryptionService = require('../../services/encryption/password_encryption');
const protectedSessionService = require('../../services/protected_session');
const appInfo = require('../../services/app_info');
const eventService = require('../../services/events');

View File

@ -60,7 +60,7 @@ const ALLOWED_OPTIONS = new Set([
]);
function getOptions() {
const optionMap = optionService.getOptionsMap();
const optionMap = optionService.getOptionMap();
const resultMap = {};
for (const optionName in optionMap) {

View File

@ -1,6 +1,6 @@
"use strict";
const passwordService = require('../../services/password');
const passwordService = require('../../services/encryption/password');
const ValidationError = require("../../errors/validation_error");
function changePassword(req) {

View File

@ -1,7 +1,7 @@
"use strict";
const beccaService = require('../../becca/becca_service');
const revisionService = require('../../services/revisions.js');
const revisionService = require('../../services/revisions');
const utils = require('../../services/utils');
const sql = require('../../services/sql');
const cls = require('../../services/cls');

View File

@ -13,7 +13,7 @@ const assetPath = require("../services/asset_path");
const appPath = require("../services/app_path");
function index(req, res) {
const options = optionService.getOptionsMap();
const options = optionService.getOptionMap();
let view = (!utils.isElectron() && req.cookies['trilium-device'] === 'mobile')
? 'mobile'

View File

@ -2,9 +2,9 @@
const utils = require('../services/utils');
const optionService = require('../services/options');
const myScryptService = require('../services/my_scrypt');
const myScryptService = require('../services/encryption/my_scrypt');
const log = require('../services/log');
const passwordService = require("../services/password");
const passwordService = require("../services/encryption/password");
const assetPath = require("../services/asset_path");
const appPath = require("../services/app_path");
const ValidationError = require("../errors/validation_error");

View File

@ -28,7 +28,7 @@ const branchesApiRoute = require('./api/branches');
const attachmentsApiRoute = require('./api/attachments');
const autocompleteApiRoute = require('./api/autocomplete');
const cloningApiRoute = require('./api/cloning');
const revisionsApiRoute = require('./api/revisions.js');
const revisionsApiRoute = require('./api/revisions');
const recentChangesApiRoute = require('./api/recent_changes');
const optionsApiRoute = require('./api/options');
const passwordApiRoute = require('./api/password');

View File

@ -1,37 +0,0 @@
const protectedSession = require("./protected_session");
const log = require("./log");
/**
* @param {BNote} note
*/
function protectAttachments(note) {
for (const attachment of note.getAttachments()) {
if (note.isProtected !== attachment.isProtected) {
if (!protectedSession.isProtectedSessionAvailable()) {
log.error("Protected session is not available to fix attachments.");
return;
}
try {
const content = attachment.getContent();
attachment.isProtected = note.isProtected;
// this will force de/encryption
attachment.setContent(content);
attachment.save();
}
catch (e) {
log.error(`Could not un/protect attachment ID = ${attachment.attachmentId}`);
throw e;
}
}
}
}
module.exports = {
protectAttachments
}

View File

@ -39,24 +39,6 @@ function getNoteWithLabel(name, value = undefined) {
return null;
}
/**
* Does not take into account templates and inheritance
*/
function getNotesWithLabelFast(name, value) {
// optimized version (~20 times faster) without using normal search, useful for e.g. finding date notes
const attrs = becca.findAttributes('label', name);
if (value === undefined) {
return attrs.map(attr => attr.getNote());
}
value = value?.toLowerCase();
return attrs
.filter(attr => attr.value.toLowerCase() === value)
.map(attr => attr.getNote());
}
function createLabel(noteId, name, value = "") {
return createAttribute({
noteId: noteId,
@ -130,7 +112,6 @@ function isAttributeDangerous(type, name) {
module.exports = {
getNotesWithLabel,
getNotesWithLabelFast,
getNoteWithLabel,
createLabel,
createRelation,

View File

@ -4,9 +4,9 @@ const etapiTokenService = require("./etapi_tokens");
const log = require('./log');
const sqlInit = require('./sql_init');
const utils = require('./utils');
const passwordEncryptionService = require('./password_encryption');
const passwordEncryptionService = require('./encryption/password_encryption');
const config = require('./config');
const passwordService = require("./password");
const passwordService = require("./encryption/password");
const noAuthentication = config.General && config.General.noAuthentication === true;

View File

@ -5,7 +5,6 @@ const eventChangesService = require('./entity_changes');
const treeService = require('./tree');
const BBranch = require('../becca/entities/bbranch');
const becca = require("../becca/becca");
const beccaService = require("../becca/becca_service");
const log = require("./log");
function cloneNoteToParentNote(noteId, parentNoteId, prefix) {
@ -136,8 +135,10 @@ function cloneNoteAfter(noteId, afterBranchId) {
const afterNote = becca.getBranch(afterBranchId);
if (isNoteDeleted(noteId) || isNoteDeleted(afterNote.parentNoteId)) {
return { success: false, message: 'Note is deleted.' };
if (!(noteId in becca.notes)) {
return { success: false, message: `Note to be cloned '${noteId}' is deleted or does not exist.` };
} else if (!(afterNote.parentNoteId in becca.notes)) {
return { success: false, message: `After note '${afterNote.parentNoteId}' is deleted or does not exist.` };
}
const parentNote = becca.getNote(afterNote.parentNoteId);

View File

@ -9,7 +9,7 @@ const cls = require('./cls');
const entityChangesService = require('./entity_changes');
const optionsService = require('./options');
const BBranch = require('../becca/entities/bbranch');
const revisionService = require('./revisions.js');
const revisionService = require('./revisions');
const becca = require("../becca/becca");
const utils = require("../services/utils");
const {sanitizeAttributeName} = require("./sanitize_attribute_name");
@ -153,7 +153,7 @@ class ConsistencyChecks {
const noteId = oldBranch.noteId;
oldBranch.markAsDeleted("missing-parent");
let message = `Branch '${branchId}' was was missing parent note '${parentNoteId}', so it was deleted. `;
let message = `Branch '${branchId}' was missing parent note '${parentNoteId}', so it was deleted. `;
if (becca.getNote(noteId).getParentBranches().length === 0) {
const newBranch = new BBranch({
@ -258,9 +258,9 @@ class ConsistencyChecks {
this.reloadNeeded = true;
logFix(`Branch '${branchId}' has been deleted since associated note '${noteId}' is deleted.`);
logFix(`Branch '${branchId}' has been deleted since the associated note '${noteId}' is deleted.`);
} else {
logError(`Branch '${branchId}' is not deleted even though associated note '${noteId}' is deleted.`)
logError(`Branch '${branchId}' is not deleted even though the associated note '${noteId}' is deleted.`)
}
});
@ -278,9 +278,9 @@ class ConsistencyChecks {
this.reloadNeeded = true;
logFix(`Branch '${branchId}' has been deleted since associated parent note '${parentNoteId}' is deleted.`);
logFix(`Branch '${branchId}' has been deleted since the associated parent note '${parentNoteId}' is deleted.`);
} else {
logError(`Branch '${branchId}' is not deleted even though associated parent note '${parentNoteId}' is deleted.`)
logError(`Branch '${branchId}' is not deleted even though the associated parent note '${parentNoteId}' is deleted.`)
}
});
@ -357,9 +357,9 @@ class ConsistencyChecks {
this.reloadNeeded = false;
logFix(`Attachment '${attachmentId}' has been deleted since associated note '${noteId}' is deleted.`);
logFix(`Attachment '${attachmentId}' has been deleted since the associated note '${noteId}' is deleted.`);
} else {
logError(`Attachment '${attachmentId}' is not deleted even though associated note '${noteId}' is deleted.`)
logError(`Attachment '${attachmentId}' is not deleted even though the associated note '${noteId}' is deleted.`)
}
});
}

View File

@ -51,12 +51,6 @@ function parseDateTime(str) {
}
}
function parseDate(str) {
const datePart = str.substr(0, 10);
return parseDateTime(`${datePart}T12:00:00.000Z`);
}
function parseLocalDate(str) {
const datePart = str.substr(0, 10);
@ -74,7 +68,6 @@ module.exports = {
localNowDate,
utcDateStr,
utcDateTimeStr,
parseDate,
parseDateTime,
parseLocalDate,
getDateTimeForFile

View File

@ -1,7 +1,7 @@
"use strict";
const crypto = require('crypto');
const log = require('./log');
const log = require('../log');
function arraysIdentical(a, b) {
let i = a.length;

View File

@ -1,6 +1,6 @@
"use strict";
const optionService = require('./options');
const optionService = require('../options');
const crypto = require('crypto');
function getVerificationHash(password) {

View File

@ -1,9 +1,9 @@
"use strict";
const sql = require('./sql');
const optionService = require('./options');
const sql = require('../sql');
const optionService = require('../options');
const myScryptService = require('./my_scrypt');
const utils = require('./utils');
const utils = require('../utils');
const passwordEncryptionService = require('./password_encryption');
function isPasswordSet() {

View File

@ -1,6 +1,6 @@
const optionService = require('./options');
const optionService = require('../options');
const myScryptService = require('./my_scrypt');
const utils = require('./utils');
const utils = require('../utils');
const dataEncryptionService = require('./data_encryption');
function verifyPassword(password) {
@ -23,6 +23,7 @@ function setDataKey(password, plainTextDataKey) {
optionService.setOption('encryptedDataKey', newEncryptedDataKey);
}
/** @return {Buffer} */
function getDataKey(password) {
const passwordDerivedKey = myScryptService.getPasswordDerivedKey(password);

View File

@ -14,7 +14,7 @@ const NOTE_CONTENT_CHANGE = "NOTE_CONTENT_CHANGED";
const eventListeners = {};
/**
* @param eventTypes - can be either single event or an array of events
* @param {string|string[]}eventTypes - can be either single event or an array of events
* @param listener
*/
function subscribe(eventTypes, listener) {

View File

@ -2,9 +2,9 @@ const sanitizeHtml = require('sanitize-html');
const sanitizeUrl = require('@braintree/sanitize-url').sanitizeUrl;
// intended mainly as protection against XSS via import
// secondarily, it (partly) protects against "CSS takeover"
// sanitize also note titles, label values etc. - there are so many usages which make it difficult to guarantee all of them
// are properly handled
// secondarily, it (partly) protects against "CSS takeover"
// sanitize also note titles, label values etc. - there are so many usages which make it difficult
// to guarantee all of them are properly handled
function sanitize(dirtyHtml) {
if (!dirtyHtml) {
return dirtyHtml;

View File

@ -105,8 +105,7 @@ function importEnex(taskContext, file, parentNote) {
}
saxStream.on("error", e => {
// unhandled errors will throw, since this is a proper node
// event emitter.
// unhandled errors will throw, since this is a proper node event emitter.
log.error(`error when parsing ENEX file: ${e}`);
// clear the error
this._parser.error = null;
@ -322,7 +321,7 @@ function importEnex(taskContext, file, parentNote) {
content += imageLink;
}
} catch (e) {
log.error(`error when saving image from ENEX file: ${e}`);
log.error(`error when saving image from ENEX file: ${e.message}`);
createFileNote();
}
} else {

View File

@ -87,7 +87,7 @@ function executeMigration(mig) {
const migrationModule = require(`${resourceDir.MIGRATIONS_DIR}/${mig.file}`);
migrationModule();
} else {
throw new Error(`Unknown migration type ${mig.type}`);
throw new Error(`Unknown migration type '${mig.type}'`);
}
}
@ -111,7 +111,7 @@ async function migrateIfNecessary() {
const currentDbVersion = getDbVersion();
if (currentDbVersion > appInfo.dbVersion && process.env.TRILIUM_IGNORE_DB_VERSION !== 'true') {
log.error(`Current DB version ${currentDbVersion} is newer than app db version ${appInfo.dbVersion} which means that it was created by newer and incompatible version of Trilium. Upgrade to latest version of Trilium to resolve this issue.`);
log.error(`Current DB version ${currentDbVersion} is newer than the current DB version ${appInfo.dbVersion}, which means that it was created by a newer and incompatible version of Trilium. Upgrade to the latest version of Trilium to resolve this issue.`);
utils.crash();
}

View File

@ -27,7 +27,6 @@ function getDefaultMimeForNoteType(typeName) {
}
module.exports = {
getNoteTypes: () => noteTypes,
getNoteTypeNames: () => noteTypes.map(nt => nt.type),
getDefaultMimeForNoteType
};

View File

@ -8,7 +8,7 @@ const cls = require('../services/cls');
const protectedSessionService = require('../services/protected_session');
const log = require('../services/log');
const utils = require('../services/utils');
const revisionService = require('./revisions.js');
const revisionService = require('./revisions');
const request = require('./request');
const path = require('path');
const url = require('url');
@ -312,10 +312,17 @@ function protectNote(note, protect) {
for (const attachment of note.getAttachments()) {
if (protect !== attachment.isProtected) {
const content = attachment.getContent();
try {
const content = attachment.getContent();
attachment.isProtected = protect;
attachment.setContent(content, { forceSave: true });
attachment.isProtected = protect;
attachment.setContent(content, {forceSave: true});
}
catch (e) {
log.error(`Could not un/protect attachment '${attachment.attachmentId}'`);
throw e;
}
}
}
}

View File

@ -1,7 +1,7 @@
const scheduledExecutions = {};
/**
* Subsequent calls will not move the timer to future. The first caller determines the time of execution.
* Subsequent calls will not move the timer to the future. The first caller determines the time of execution.
*
* The good thing about synchronous better-sqlite3 is that this cannot interrupt transaction. The execution will be called
* only outside of a transaction.
@ -22,4 +22,4 @@ function scheduleExecution(name, milliseconds, cb) {
module.exports = {
scheduleExecution
};
};

View File

@ -26,9 +26,7 @@ function getOption(name) {
return val;
}
/**
* @returns {integer}
*/
/** @returns {integer} */
function getOptionInt(name, defaultValue = undefined) {
const val = getOption(name);
@ -45,9 +43,7 @@ function getOptionInt(name, defaultValue = undefined) {
return intVal;
}
/**
* @returns {boolean}
*/
/** @returns {boolean} */
function getOptionBool(name) {
const val = getOption(name);
@ -76,7 +72,7 @@ function setOption(name, value) {
}
function createOption(name, value, isSynced) {
// to avoid circular dependency, need to find better solution
// to avoid circular dependency, need to find a better solution
const BOption = require('../becca/entities/boption');
new BOption({
@ -90,7 +86,7 @@ function getOptions() {
return Object.values(becca.options);
}
function getOptionsMap() {
function getOptionMap() {
const map = {};
for (const option of Object.values(becca.options)) {
@ -107,6 +103,6 @@ module.exports = {
setOption,
createOption,
getOptions,
getOptionsMap,
getOptionMap,
getOptionOrNull
};

View File

@ -93,7 +93,7 @@ const defaultOptions = [
];
function initStartupOptions() {
const optionsMap = optionService.getOptionsMap();
const optionsMap = optionService.getOptionMap();
const allDefaultOptions = defaultOptions.concat(getKeyboardDefaultOptions());

View File

@ -1,7 +1,7 @@
"use strict";
const log = require('./log');
const dataEncryptionService = require('./data_encryption');
const dataEncryptionService = require('./encryption/data_encryption');
let dataKey = null;
@ -21,19 +21,6 @@ function isProtectedSessionAvailable() {
return !!dataKey;
}
function decryptNotes(notes) {
try {
for (const note of notes) {
if (note.isProtected) {
note.title = decryptString(note.title);
}
}
}
catch (e) {
log.error(`Could not decrypt protected notes: ${e.message} ${e.stack}`);
}
}
function encrypt(plainText) {
if (plainText === null) {
return null;
@ -84,7 +71,6 @@ module.exports = {
encrypt,
decrypt,
decryptString,
decryptNotes,
touchProtectedSession,
checkProtectedSessionExpiration
};

View File

@ -6,7 +6,7 @@ const url = require('url');
const syncOptions = require('./sync_options');
// this service provides abstraction over node's HTTP/HTTPS and electron net.client APIs
// this allows to support system proxy
// this allows supporting system proxy
function exec(opts) {
const client = getClient(opts);
@ -171,7 +171,7 @@ function getProxyAgent(opts) {
function getClient(opts) {
// it's not clear how to explicitly configure proxy (as opposed to system proxy)
// so in that case we always use node's modules
// so in that case, we always use node's modules
if (utils.isElectron() && !opts.proxy) {
return require('electron').net;
}

View File

@ -7,6 +7,10 @@ const attributeService = require("../services/attributes");
const protectedSessionService = require("../services/protected_session");
const hiddenSubtreeService = require("./hidden_subtree");
/**
* @param {BNote} note
* @return {int[]}
*/
function getRunAtHours(note) {
try {
return note.getLabelValues('runAtHour').map(hour => parseInt(hour));

View File

@ -94,6 +94,9 @@ function getParams(params) {
}).join(",");
}
/**
* @param {BNote} note
*/
function getScriptBundleForFrontend(note) {
const bundle = getScriptBundle(note);
@ -111,6 +114,13 @@ function getScriptBundleForFrontend(note) {
return bundle;
}
/**
* @param {BNote} note
* @param {boolean} [root=true]
* @param {string|null} [scriptEnv]
* @param {string[]} [includedNoteIds]
* @param {string|null} [backendOverrideContent]
*/
function getScriptBundle(note, root = true, scriptEnv = null, includedNoteIds = [], backendOverrideContent = null) {
if (!note.isContentAvailable()) {
return;

View File

@ -2,7 +2,7 @@
/**
* Search string is lower cased for case-insensitive comparison. But when retrieving properties
* we need case-sensitive form, so we have this translation object.
* we need a case-sensitive form, so we have this translation object.
*/
const PROP_MAPPING = {
"noteid": "noteId",

View File

@ -88,7 +88,7 @@ async function createInitialDatabase() {
optionsInitService.initDocumentOptions();
optionsInitService.initNotSyncedOptions(true, {});
optionsInitService.initStartupOptions();
require("./password").resetPassword();
require("./encryption/password").resetPassword();
});
log.info("Importing demo content ...");