wip conversion to ES modules

This commit is contained in:
zadam 2023-11-21 22:49:35 +01:00
parent 722299dd26
commit 5205800720
242 changed files with 1563 additions and 1495 deletions

View File

@ -643,7 +643,7 @@ the "copyright" line and a pointer to where the full notice is found.
GNU Affero General Public License for more details. GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. along with this program. If not, see <http://www.js.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail. Also add information on how to contact you by electronic and paper mail.
@ -658,4 +658,4 @@ specific requirements.
You should also get your employer (if you work as a programmer) or school, You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary. if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see For more information on this, and how to apply and follow the GNU AGPL, see
<http://www.gnu.org/licenses/>. <http://www.js.gnu.org/licenses/>.

View File

@ -1,17 +1,21 @@
'use strict'; 'use strict';
const {app, globalShortcut, BrowserWindow} = require('electron'); import { app, globalShortcut, BrowserWindow } from 'electron';
const sqlInit = require('./src/services/sql_init'); import sqlInit from './src/services/sql_init.js';
const appIconService = require('./src/services/app_icon'); import appIconService from './src/services/app_icon.js';
const windowService = require('./src/services/window'); import windowService from './src/services/window.js';
const tray = require('./src/services/tray'); import tray from './src/services/tray.js';
import electron_debug from "electron-debug";
import electron_dl from "electron-dl";
import './src/www.js';
// Adds debug features like hotkeys for triggering dev tools and reload // Adds debug features like hotkeys for triggering dev tools and reload
require('electron-debug')(); electron_debug();
appIconService.installLocalAppIcon(); appIconService.installLocalAppIcon();
require('electron-dl')({ saveAs: true }); electron_dl({ saveAs: true });
// needed for excalidraw export https://github.com/zadam/trilium/issues/4271 // needed for excalidraw export https://github.com/zadam/trilium/issues/4271
app.commandLine.appendSwitch("enable-experimental-web-platform-features"); app.commandLine.appendSwitch("enable-experimental-web-platform-features");
@ -58,5 +62,3 @@ app.on('will-quit', () => {
// this is to disable electron warning spam in the dev console (local development only) // this is to disable electron warning spam in the dev console (local development only)
process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true'; process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true';
require('./src/www');

38
package-lock.json generated
View File

@ -1,12 +1,12 @@
{ {
"name": "trilium", "name": "trilium",
"version": "0.62.1-beta", "version": "0.62.2",
"lockfileVersion": 2, "lockfileVersion": 2,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "trilium", "name": "trilium",
"version": "0.62.1-beta", "version": "0.62.2",
"hasInstallScript": true, "hasInstallScript": true,
"license": "AGPL-3.0-only", "license": "AGPL-3.0-only",
"dependencies": { "dependencies": {
@ -16,7 +16,7 @@
"archiver": "6.0.1", "archiver": "6.0.1",
"async-mutex": "0.4.0", "async-mutex": "0.4.0",
"axios": "1.6.2", "axios": "1.6.2",
"better-sqlite3": "8.4.0", "better-sqlite3": "9.1.1",
"chokidar": "3.5.3", "chokidar": "3.5.3",
"cls-hooked": "4.2.2", "cls-hooked": "4.2.2",
"compression": "1.7.4", "compression": "1.7.4",
@ -77,11 +77,11 @@
"yauzl": "2.10.0" "yauzl": "2.10.0"
}, },
"bin": { "bin": {
"trilium": "src/www" "trilium": "src/www.js"
}, },
"devDependencies": { "devDependencies": {
"cross-env": "7.0.3", "cross-env": "7.0.3",
"electron": "25.9.5", "electron": "28.0.0-beta.8",
"electron-builder": "24.6.4", "electron-builder": "24.6.4",
"electron-packager": "17.1.2", "electron-packager": "17.1.2",
"electron-rebuild": "3.2.9", "electron-rebuild": "3.2.9",
@ -2540,13 +2540,13 @@
} }
}, },
"node_modules/better-sqlite3": { "node_modules/better-sqlite3": {
"version": "8.4.0", "version": "9.1.1",
"resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-8.4.0.tgz", "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-9.1.1.tgz",
"integrity": "sha512-NmsNW1CQvqMszu/CFAJ3pLct6NEFlNfuGM6vw72KHkjOD1UDnL96XNN1BMQc1hiHo8vE2GbOWQYIpZ+YM5wrZw==", "integrity": "sha512-FhW7bS7cXwkB2SFnPJrSGPmQerVSCzwBgmQ1cIRcYKxLsyiKjljzCbyEqqhYXo5TTBqt5BISiBj2YE2Sy2ynaA==",
"hasInstallScript": true, "hasInstallScript": true,
"dependencies": { "dependencies": {
"bindings": "^1.5.0", "bindings": "^1.5.0",
"prebuild-install": "^7.1.0" "prebuild-install": "^7.1.1"
} }
}, },
"node_modules/big-integer": { "node_modules/big-integer": {
@ -4366,9 +4366,9 @@
} }
}, },
"node_modules/electron": { "node_modules/electron": {
"version": "25.9.5", "version": "28.0.0-beta.8",
"resolved": "https://registry.npmjs.org/electron/-/electron-25.9.5.tgz", "resolved": "https://registry.npmjs.org/electron/-/electron-28.0.0-beta.8.tgz",
"integrity": "sha512-gM7GXUSd3JVRcYbBnNOtZeNnE5MCJjtZTT8QyIxJvpQ0Dh9dz3hTuEL62dOwnMFW/l47ACQ6es/8qi01P4QGZA==", "integrity": "sha512-8SwL743EG3sIdwqvgq+fteYexRGb0qTg8MUSm77IRnw6tOxbCfgd8QztpYS7z8SNDcpAABXD4I1X9nqBVBLshQ==",
"hasInstallScript": true, "hasInstallScript": true,
"dependencies": { "dependencies": {
"@electron/get": "^2.0.0", "@electron/get": "^2.0.0",
@ -15572,12 +15572,12 @@
} }
}, },
"better-sqlite3": { "better-sqlite3": {
"version": "8.4.0", "version": "9.1.1",
"resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-8.4.0.tgz", "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-9.1.1.tgz",
"integrity": "sha512-NmsNW1CQvqMszu/CFAJ3pLct6NEFlNfuGM6vw72KHkjOD1UDnL96XNN1BMQc1hiHo8vE2GbOWQYIpZ+YM5wrZw==", "integrity": "sha512-FhW7bS7cXwkB2SFnPJrSGPmQerVSCzwBgmQ1cIRcYKxLsyiKjljzCbyEqqhYXo5TTBqt5BISiBj2YE2Sy2ynaA==",
"requires": { "requires": {
"bindings": "^1.5.0", "bindings": "^1.5.0",
"prebuild-install": "^7.1.0" "prebuild-install": "^7.1.1"
} }
}, },
"big-integer": { "big-integer": {
@ -16964,9 +16964,9 @@
} }
}, },
"electron": { "electron": {
"version": "25.9.5", "version": "28.0.0-beta.8",
"resolved": "https://registry.npmjs.org/electron/-/electron-25.9.5.tgz", "resolved": "https://registry.npmjs.org/electron/-/electron-28.0.0-beta.8.tgz",
"integrity": "sha512-gM7GXUSd3JVRcYbBnNOtZeNnE5MCJjtZTT8QyIxJvpQ0Dh9dz3hTuEL62dOwnMFW/l47ACQ6es/8qi01P4QGZA==", "integrity": "sha512-8SwL743EG3sIdwqvgq+fteYexRGb0qTg8MUSm77IRnw6tOxbCfgd8QztpYS7z8SNDcpAABXD4I1X9nqBVBLshQ==",
"requires": { "requires": {
"@electron/get": "^2.0.0", "@electron/get": "^2.0.0",
"@types/node": "^18.11.18", "@types/node": "^18.11.18",

View File

@ -5,21 +5,22 @@
"version": "0.62.2", "version": "0.62.2",
"license": "AGPL-3.0-only", "license": "AGPL-3.0-only",
"main": "electron.js", "main": "electron.js",
"type": "module",
"bin": { "bin": {
"trilium": "./src/www" "trilium": "src/www.js"
}, },
"repository": { "repository": {
"type": "git", "type": "git",
"url": "https://github.com/zadam/trilium.git" "url": "https://github.com/zadam/trilium.git"
}, },
"scripts": { "scripts": {
"start-server": "cross-env TRILIUM_SAFE_MODE=1 TRILIUM_DATA_DIR=./data TRILIUM_ENV=dev TRILIUM_SYNC_SERVER_HOST=http://tsyncserver:4000 nodemon ./src/www", "start-server": "cross-env TRILIUM_SAFE_MODE=1 TRILIUM_DATA_DIR=./data TRILIUM_ENV=dev TRILIUM_SYNC_SERVER_HOST=http://tsyncserver:4000 nodemon src/www.js",
"start-server-no-dir": "cross-env TRILIUM_SAFE_MODE=1 TRILIUM_ENV=dev TRILIUM_SYNC_SERVER_HOST=http://tsyncserver:4000 nodemon ./src/www", "start-server-no-dir": "cross-env TRILIUM_SAFE_MODE=1 TRILIUM_ENV=dev TRILIUM_SYNC_SERVER_HOST=http://tsyncserver:4000 nodemon src/www.js",
"qstart-server": "npm run qswitch-server && TRILIUM_SAFE_MODE=1 TRILIUM_DATA_DIR=./data TRILIUM_ENV=dev TRILIUM_SYNC_SERVER_HOST=http://tsyncserver:4000 nodemon ./src/www", "qstart-server": "npm run qswitch-server && TRILIUM_SAFE_MODE=1 TRILIUM_DATA_DIR=./data TRILIUM_ENV=dev TRILIUM_SYNC_SERVER_HOST=http://tsyncserver:4000 nodemon src/www.js",
"start-electron": "cross-env TRILIUM_SAFE_MODE=1 TRILIUM_DATA_DIR=./data TRILIUM_SYNC_SERVER_HOST=http://tsyncserver:4000 TRILIUM_ENV=dev electron --inspect=5858 .", "start-electron": "cross-env TRILIUM_SAFE_MODE=1 TRILIUM_DATA_DIR=./data TRILIUM_SYNC_SERVER_HOST=http://tsyncserver:4000 TRILIUM_ENV=dev electron --inspect=5858 .",
"start-electron-no-dir": "cross-env TRILIUM_SAFE_MODE=1 TRILIUM_ENV=dev TRILIUM_SYNC_SERVER_HOST=http://tsyncserver:4000 electron --inspect=5858 .", "start-electron-no-dir": "cross-env TRILIUM_SAFE_MODE=1 TRILIUM_ENV=dev TRILIUM_SYNC_SERVER_HOST=http://tsyncserver:4000 electron --inspect=5858 .",
"qstart-electron": "npm run qswitch-electron && TRILIUM_SAFE_MODE=1 TRILIUM_DATA_DIR=./data TRILIUM_SYNC_SERVER_HOST=http://tsyncserver:4000 TRILIUM_ENV=dev electron --inspect=5858 .", "qstart-electron": "npm run qswitch-electron && TRILIUM_SAFE_MODE=1 TRILIUM_DATA_DIR=./data TRILIUM_SYNC_SERVER_HOST=http://tsyncserver:4000 TRILIUM_ENV=dev electron --inspect=5858 .",
"start-test-server": "npm run qswitch-server; rm -rf ./data-test; cross-env TRILIUM_SAFE_MODE=1 TRILIUM_DATA_DIR=./data-test TRILIUM_SYNC_SERVER_HOST=http://tsyncserver:4000 TRILIUM_ENV=dev TRILIUM_PORT=9999 node ./src/www", "start-test-server": "npm run qswitch-server; rm -rf ./data-test; cross-env TRILIUM_SAFE_MODE=1 TRILIUM_DATA_DIR=./data-test TRILIUM_SYNC_SERVER_HOST=http://tsyncserver:4000 TRILIUM_ENV=dev TRILIUM_PORT=9999 node src/www.js",
"switch-server": "rm -rf ./node_modules/better-sqlite3 && npm install", "switch-server": "rm -rf ./node_modules/better-sqlite3 && npm install",
"switch-electron": "./node_modules/.bin/electron-rebuild", "switch-electron": "./node_modules/.bin/electron-rebuild",
"qswitch-server": "rm -rf ./node_modules/better-sqlite3/bin ; mkdir -p ./node_modules/better-sqlite3/build ; cp ./bin/better-sqlite3/linux-server-better_sqlite3.node ./node_modules/better-sqlite3/build/better_sqlite3.node", "qswitch-server": "rm -rf ./node_modules/better-sqlite3/bin ; mkdir -p ./node_modules/better-sqlite3/build ; cp ./bin/better-sqlite3/linux-server-better_sqlite3.node ./node_modules/better-sqlite3/build/better_sqlite3.node",
@ -42,7 +43,7 @@
"archiver": "6.0.1", "archiver": "6.0.1",
"async-mutex": "0.4.0", "async-mutex": "0.4.0",
"axios": "1.6.2", "axios": "1.6.2",
"better-sqlite3": "8.4.0", "better-sqlite3": "9.1.1",
"chokidar": "3.5.3", "chokidar": "3.5.3",
"cls-hooked": "4.2.2", "cls-hooked": "4.2.2",
"compression": "1.7.4", "compression": "1.7.4",
@ -104,7 +105,7 @@
}, },
"devDependencies": { "devDependencies": {
"cross-env": "7.0.3", "cross-env": "7.0.3",
"electron": "25.9.5", "electron": "28.0.0-beta.8",
"electron-builder": "24.6.4", "electron-builder": "24.6.4",
"electron-packager": "17.1.2", "electron-packager": "17.1.2",
"electron-rebuild": "3.2.9", "electron-rebuild": "3.2.9",

View File

@ -1,8 +1,6 @@
const { import {describeEtapi, postEtapi, putEtapiContent,getEtapi} from "../support/etapi";
describeEtapi, postEtapi,
putEtapiContent
} = require("../support/etapi");
const {getEtapi} = require("../support/etapi.js");
describeEtapi("app_info", () => { describeEtapi("app_info", () => {
it("get", async () => { it("get", async () => {

View File

@ -1,8 +1,4 @@
const { import {describeEtapi, getEtapi, postEtapi,putEtapiContent} from "../support/etapi";
describeEtapi, postEtapi,
getEtapi,
} = require("../support/etapi");
const {putEtapiContent} = require("../support/etapi.js");
describeEtapi("backup", () => { describeEtapi("backup", () => {
it("create", async () => { it("create", async () => {

View File

@ -1,10 +1,9 @@
const { import {describeEtapi, postEtapi, postEtapiContent,getEtapiContent} from "../support/etapi";
describeEtapi, postEtapi, import fs from "fs";
postEtapiContent, import path from "path";
} = require("../support/etapi"); import {fileURLToPath} from "node:url";
const fs = require("fs");
const path = require("path"); const __dirname = path.dirname(fileURLToPath(import.meta.url));
const {getEtapiContent} = require("../support/etapi.js");
describeEtapi("import", () => { describeEtapi("import", () => {
it("import", async () => { it("import", async () => {

View File

@ -1,13 +1,14 @@
const crypto = require('crypto'); import crypto from "crypto";
const {
import {
deleteEtapi, deleteEtapi,
getEtapiResponse, describeEtapi,
describeEtapi, postEtapi,
getEtapi, getEtapi,
getEtapiContent, getEtapiContent,
patchEtapi, putEtapi, getEtapiResponse,
putEtapiContent patchEtapi,
} = require("../support/etapi"); postEtapi, putEtapi, putEtapiContent
} from "../support/etapi";
describeEtapi("notes", () => { describeEtapi("notes", () => {
it("create", async () => { it("create", async () => {

View File

@ -1,6 +1,6 @@
const anonymizationService = require('./services/anonymization'); import anonymizationService from './services/anonymization.js'
const sqlInit = require('./services/sql_init'); import sqlInit from './services/sql_init.js'
require('./becca/entity_constructor'); import './becca/entity_constructor.js';
sqlInit.dbReady.then(async () => { sqlInit.dbReady.then(async () => {
try { try {

View File

@ -1,14 +1,37 @@
const express = require('express'); import express from 'express';
const path = require('path'); import path from 'path';
const favicon = require('serve-favicon'); import favicon from 'serve-favicon';
const cookieParser = require('cookie-parser'); import cookieParser from 'cookie-parser';
const helmet = require('helmet'); import helmet from 'helmet';
const compression = require('compression'); import compression from 'compression';
const sessionParser = require('./routes/session_parser'); import sessionParser from './routes/session_parser.js'
const utils = require('./services/utils'); import utils from './services/utils.js'
import './services/handlers.js';
import './becca/becca_loader.js';
require('./services/handlers'); // triggers sync timer
require('./becca/becca_loader'); import './services/sync.js';
// triggers backup timer
import './services/backup.js';
// trigger consistency checks timer
import './services/consistency_checks.js';
import './services/scheduler.js';
import assetRoutes from './routes/assets.js'
import routes from './routes/routes.js'
import customRoutes from './routes/custom.js'
import errorHandlerRoutes from './routes/error_handlers.js'
import {initialize} from "@electron/remote/main/index.js";
import {fileURLToPath} from "node:url";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const app = express(); const app = express();
@ -37,24 +60,13 @@ app.use(`/robots.txt`, express.static(path.join(__dirname, 'public/robots.txt'))
app.use(sessionParser); app.use(sessionParser);
app.use(favicon(`${__dirname}/../images/app-icons/win/icon.ico`)); app.use(favicon(`${__dirname}/../images/app-icons/win/icon.ico`));
require('./routes/assets').register(app); assetRoutes.register(app);
require('./routes/routes').register(app); routes.register(app);
require('./routes/custom').register(app); customRoutes.register(app);
require('./routes/error_handlers').register(app); errorHandlerRoutes.register(app);
// triggers sync timer
require('./services/sync');
// triggers backup timer
require('./services/backup');
// trigger consistency checks timer
require('./services/consistency_checks');
require('./services/scheduler');
if (utils.isElectron()) { if (utils.isElectron()) {
require('@electron/remote/main').initialize(); initialize();
} }
module.exports = app; export default app;

View File

@ -1,8 +1,16 @@
"use strict"; "use strict";
const sql = require("../services/sql"); import sql from '../services/sql.js'
const NoteSet = require("../services/search/note_set"); import NoteSet from '../services/search/note_set.js'
const NotFoundError = require("../errors/not_found_error"); import NotFoundError from '../errors/not_found_error.js'
import BRevision from './entities/brevision.js' // avoiding circular dependency problems
import BAttachment from './entities/battachment.js' // avoiding circular dependency problems
import BBlob from './entities/bblob.js' // avoiding circular dependency problems
import BRecentNote from './entities/brecent_note.js' // avoiding circular dependency problems
/** /**
* Becca is a backend cache of all notes, branches, and attributes. * Becca is a backend cache of all notes, branches, and attributes.
@ -147,8 +155,6 @@ class Becca {
/** @returns {BRevision|null} */ /** @returns {BRevision|null} */
getRevision(revisionId) { getRevision(revisionId) {
const row = sql.getRow("SELECT * FROM revisions WHERE revisionId = ?", [revisionId]); const row = sql.getRow("SELECT * FROM revisions WHERE revisionId = ?", [revisionId]);
const BRevision = require("./entities/brevision"); // avoiding circular dependency problems
return row ? new BRevision(row) : null; return row ? new BRevision(row) : null;
} }
@ -162,9 +168,6 @@ class Becca {
JOIN blobs USING (blobId) JOIN blobs USING (blobId)
WHERE attachmentId = ? AND isDeleted = 0` WHERE attachmentId = ? AND isDeleted = 0`
: `SELECT * FROM attachments WHERE attachmentId = ? AND isDeleted = 0`; : `SELECT * FROM attachments WHERE attachmentId = ? AND isDeleted = 0`;
const BAttachment = require("./entities/battachment"); // avoiding circular dependency problems
return sql.getRows(query, [attachmentId]) return sql.getRows(query, [attachmentId])
.map(row => new BAttachment(row))[0]; .map(row => new BAttachment(row))[0];
} }
@ -180,7 +183,7 @@ class Becca {
/** @returns {BAttachment[]} */ /** @returns {BAttachment[]} */
getAttachments(attachmentIds) { getAttachments(attachmentIds) {
const BAttachment = require("./entities/battachment"); // avoiding circular dependency problems // avoiding circular dependency problems
return sql.getManyRows("SELECT * FROM attachments WHERE attachmentId IN (???) AND isDeleted = 0", attachmentIds) return sql.getManyRows("SELECT * FROM attachments WHERE attachmentId IN (???) AND isDeleted = 0", attachmentIds)
.map(row => new BAttachment(row)); .map(row => new BAttachment(row));
} }
@ -188,8 +191,6 @@ class Becca {
/** @returns {BBlob|null} */ /** @returns {BBlob|null} */
getBlob(entity) { getBlob(entity) {
const row = sql.getRow("SELECT *, LENGTH(content) AS contentLength FROM blobs WHERE blobId = ?", [entity.blobId]); const row = sql.getRow("SELECT *, LENGTH(content) AS contentLength FROM blobs WHERE blobId = ?", [entity.blobId]);
const BBlob = require("./entities/bblob"); // avoiding circular dependency problems
return row ? new BBlob(row) : null; return row ? new BBlob(row) : null;
} }
@ -237,16 +238,12 @@ class Becca {
/** @returns {BRecentNote[]} */ /** @returns {BRecentNote[]} */
getRecentNotesFromQuery(query, params = []) { getRecentNotesFromQuery(query, params = []) {
const rows = sql.getRows(query, params); const rows = sql.getRows(query, params);
const BRecentNote = require("./entities/brecent_note"); // avoiding circular dependency problems
return rows.map(row => new BRecentNote(row)); return rows.map(row => new BRecentNote(row));
} }
/** @returns {BRevision[]} */ /** @returns {BRevision[]} */
getRevisionsFromQuery(query, params = []) { getRevisionsFromQuery(query, params = []) {
const rows = sql.getRows(query, params); const rows = sql.getRows(query, params);
const BRevision = require("./entities/brevision"); // avoiding circular dependency problems
return rows.map(row => new BRevision(row)); return rows.map(row => new BRevision(row));
} }
@ -279,4 +276,4 @@ class Becca {
const becca = new Becca(); const becca = new Becca();
module.exports = becca; export default becca;

View File

@ -1,24 +1,28 @@
"use strict"; "use strict";
const sql = require('../services/sql'); import sql from '../services/sql.js'
const eventService = require('../services/events'); import eventService from '../services/events.js'
const becca = require('./becca'); import becca from './becca.js'
const sqlInit = require('../services/sql_init'); import sqlInit from '../services/sql_init.js'
const log = require('../services/log'); import log from '../services/log.js'
const BNote = require('./entities/bnote'); import BNote from './entities/bnote.js'
const BBranch = require('./entities/bbranch'); import BBranch from './entities/bbranch.js'
const BAttribute = require('./entities/battribute'); import BAttribute from './entities/battribute.js'
const BOption = require('./entities/boption'); import BOption from './entities/boption.js'
const BEtapiToken = require("./entities/betapi_token"); import BEtapiToken from './entities/betapi_token.js'
const cls = require("../services/cls"); import cls from '../services/cls.js'
const entityConstructor = require("../becca/entity_constructor"); import entityConstructor from '../becca/entity_constructor.js'
import services from '../services/options_init.js'
import services0 from '../services/ws.js'
const beccaLoaded = new Promise((res, rej) => { const beccaLoaded = new Promise((res, rej) => {
sqlInit.dbReady.then(() => { sqlInit.dbReady.then(() => {
cls.init(() => { cls.init(() => {
load(); load();
require('../services/options_init').initStartupOptions(); services.initStartupOptions();
res(); res();
}); });
@ -71,7 +75,7 @@ function load() {
function reload(reason) { function reload(reason) {
load(); load();
require('../services/ws').reloadFrontend(reason || "becca reloaded"); services0.reloadFrontend(reason || "becca reloaded");
} }
eventService.subscribeBeccaLoader([eventService.ENTITY_CHANGE_SYNCED], ({entityName, entityRow}) => { eventService.subscribeBeccaLoader([eventService.ENTITY_CHANGE_SYNCED], ({entityName, entityRow}) => {
@ -282,7 +286,7 @@ eventService.subscribeBeccaLoader(eventService.ENTER_PROTECTED_SESSION, () => {
eventService.subscribeBeccaLoader(eventService.LEAVE_PROTECTED_SESSION, load); eventService.subscribeBeccaLoader(eventService.LEAVE_PROTECTED_SESSION, load);
module.exports = { export default {
load, load,
reload, reload,
beccaLoaded beccaLoaded

View File

@ -1,8 +1,8 @@
"use strict"; "use strict";
const becca = require('./becca'); import becca from './becca.js'
const cls = require('../services/cls'); import cls from '../services/cls.js'
const log = require('../services/log'); import log from '../services/log.js'
function isNotePathArchived(notePath) { function isNotePathArchived(notePath) {
const noteId = notePath[notePath.length - 1]; const noteId = notePath[notePath.length - 1];
@ -82,7 +82,7 @@ function getNoteTitleForPath(notePathArray) {
return titles.join(' / '); return titles.join(' / ');
} }
module.exports = { export default {
getNoteTitle, getNoteTitle,
getNoteTitleForPath, getNoteTitleForPath,
isNotePathArchived isNotePathArchived

View File

@ -1,14 +1,16 @@
"use strict"; "use strict";
const utils = require('../../services/utils'); import utils from '../../services/utils.js'
const sql = require('../../services/sql'); import sql from '../../services/sql.js'
const entityChangesService = require('../../services/entity_changes'); import entityChangesService from '../../services/entity_changes.js'
const eventService = require("../../services/events"); import eventService from '../../services/events.js'
const dateUtils = require("../../services/date_utils"); import dateUtils from '../../services/date_utils.js'
const cls = require("../../services/cls"); import cls from '../../services/cls.js'
const log = require("../../services/log"); import log from '../../services/log.js'
const protectedSessionService = require("../../services/protected_session"); import protectedSessionService from '../../services/protected_session.js'
const blobService = require("../../services/blob"); import blobService from '../../services/blob.js'
import becca0 from '../becca.js'
let becca = null; let becca = null;
@ -34,7 +36,7 @@ class AbstractBeccaEntity {
*/ */
get becca() { get becca() {
if (!becca) { if (!becca) {
becca = require('../becca'); becca = becca0;
} }
return becca; return becca;
@ -306,4 +308,4 @@ class AbstractBeccaEntity {
} }
} }
module.exports = AbstractBeccaEntity; export default AbstractBeccaEntity;

View File

@ -1,11 +1,13 @@
"use strict"; "use strict";
const utils = require('../../services/utils'); import utils from '../../services/utils.js'
const dateUtils = require('../../services/date_utils'); import dateUtils from '../../services/date_utils.js'
const AbstractBeccaEntity = require("./abstract_becca_entity"); import AbstractBeccaEntity from './abstract_becca_entity.js'
const sql = require("../../services/sql"); import sql from '../../services/sql.js'
const protectedSessionService = require("../../services/protected_session"); import protectedSessionService from '../../services/protected_session.js'
const log = require("../../services/log"); import log from '../../services/log.js'
import noteService from '../../services/notes.js'
const attachmentRoleToNoteTypeMapping = { const attachmentRoleToNoteTypeMapping = {
'image': 'image' 'image': 'image'
@ -152,9 +154,6 @@ class BAttachment extends AbstractBeccaEntity {
if (!this.isContentAvailable()) { // isProtected is the same for attachment if (!this.isContentAvailable()) { // isProtected is the same for attachment
throw new Error(`Cannot convert protected attachment outside of protected session`); throw new Error(`Cannot convert protected attachment outside of protected session`);
} }
const noteService = require('../../services/notes');
const { note, branch } = noteService.createNewNote({ const { note, branch } = noteService.createNewNote({
parentNoteId: this.ownerId, parentNoteId: this.ownerId,
title: this.title, title: this.title,
@ -240,4 +239,4 @@ class BAttachment extends AbstractBeccaEntity {
} }
} }
module.exports = BAttachment; export default BAttachment;

View File

@ -1,11 +1,11 @@
"use strict"; "use strict";
const BNote = require('./bnote'); import BNote from './bnote.js'
const AbstractBeccaEntity = require("./abstract_becca_entity"); import AbstractBeccaEntity from './abstract_becca_entity.js'
const sql = require("../../services/sql"); import sql from '../../services/sql.js'
const dateUtils = require("../../services/date_utils"); import dateUtils from '../../services/date_utils.js'
const promotedAttributeDefinitionParser = require("../../services/promoted_attribute_definition_parser"); import promotedAttributeDefinitionParser from '../../services/promoted_attribute_definition_parser.js'
const {sanitizeAttributeName} = require("../../services/sanitize_attribute_name"); import { sanitizeAttributeName } from '../../services/sanitize_attribute_name.js';
/** /**
@ -239,4 +239,4 @@ class BAttribute extends AbstractBeccaEntity {
} }
} }
module.exports = BAttribute; export default BAttribute;

View File

@ -27,4 +27,4 @@ class BBlob {
} }
} }
module.exports = BBlob; export default BBlob;

View File

@ -1,12 +1,16 @@
"use strict"; "use strict";
const BNote = require('./bnote'); import BNote from './bnote.js'
const AbstractBeccaEntity = require("./abstract_becca_entity"); import AbstractBeccaEntity from './abstract_becca_entity.js'
const dateUtils = require("../../services/date_utils"); import dateUtils from '../../services/date_utils.js'
const utils = require("../../services/utils"); import utils from '../../services/utils.js'
const TaskContext = require("../../services/task_context"); import TaskContext from '../../services/task_context.js'
const cls = require("../../services/cls"); import cls from '../../services/cls.js'
const log = require("../../services/log"); import log from '../../services/log.js'
// needs to be run before branches and attributes are deleted and thus attached relations disappear
import handlers from '../../services/handlers.js'
/** /**
* Branch represents a relationship between a child note and its parent note. Trilium allows a note to have multiple * Branch represents a relationship between a child note and its parent note. Trilium allows a note to have multiple
@ -160,8 +164,6 @@ class BBranch extends AbstractBeccaEntity {
const parentBranches = note.getParentBranches(); const parentBranches = note.getParentBranches();
if (parentBranches.length === 1 && parentBranches[0] === this) { if (parentBranches.length === 1 && parentBranches[0] === this) {
// needs to be run before branches and attributes are deleted and thus attached relations disappear
const handlers = require("../../services/handlers");
handlers.runAttachedRelations(note, 'runOnNoteDeletion', note); handlers.runAttachedRelations(note, 'runOnNoteDeletion', note);
} }
} }
@ -279,4 +281,4 @@ class BBranch extends AbstractBeccaEntity {
} }
} }
module.exports = BBranch; export default BBranch;

View File

@ -1,7 +1,7 @@
"use strict"; "use strict";
const dateUtils = require('../../services/date_utils'); import dateUtils from '../../services/date_utils.js'
const AbstractBeccaEntity = require("./abstract_becca_entity"); import AbstractBeccaEntity from './abstract_becca_entity.js'
/** /**
* EtapiToken is an entity representing token used to authenticate against Trilium REST API from client applications. * EtapiToken is an entity representing token used to authenticate against Trilium REST API from client applications.
@ -75,4 +75,4 @@ class BEtapiToken extends AbstractBeccaEntity {
} }
} }
module.exports = BEtapiToken; export default BEtapiToken;

View File

@ -1,17 +1,29 @@
"use strict"; "use strict";
const protectedSessionService = require('../../services/protected_session'); import protectedSessionService from '../../services/protected_session.js'
const log = require('../../services/log'); import log from '../../services/log.js'
const sql = require('../../services/sql'); import sql from '../../services/sql.js'
const utils = require('../../services/utils'); import utils from '../../services/utils.js'
const dateUtils = require('../../services/date_utils'); import dateUtils from '../../services/date_utils.js'
const AbstractBeccaEntity = require("./abstract_becca_entity"); import AbstractBeccaEntity from './abstract_becca_entity.js'
const BRevision = require("./brevision"); import BRevision from './brevision.js'
const BAttachment = require("./battachment"); import BAttachment from './battachment.js'
const TaskContext = require("../../services/task_context"); import TaskContext from '../../services/task_context.js'
const dayjs = require("dayjs"); import dayjs from "dayjs";
const utc = require('dayjs/plugin/utc'); import utc from "dayjs/plugin/utc.js";
const eventService = require("../../services/events"); import eventService from '../../services/events.js'
import searchService from '../../services/search/services/search.js'
import BAttribute from './battribute.js'
import cloningService from '../../services/cloning.js'
import noteService from '../../services/notes.js'
// needs to be run before branches and attributes are deleted and thus attached relations disappear
import handlers from '../../services/handlers.js'
dayjs.extend(utc); dayjs.extend(utc);
const LABEL = 'label'; const LABEL = 'label';
@ -903,7 +915,6 @@ class BNote extends AbstractBeccaEntity {
} }
try { try {
const searchService = require("../../services/search/services/search");
const {searchResultNoteIds} = searchService.searchFromNote(this); const {searchResultNoteIds} = searchService.searchFromNote(this);
const becca = this.becca; const becca = this.becca;
@ -1303,8 +1314,6 @@ class BNote extends AbstractBeccaEntity {
} }
} }
else { else {
const BAttribute = require("./battribute");
new BAttribute({ new BAttribute({
noteId: this.noteId, noteId: this.noteId,
type: type, type: type,
@ -1343,8 +1352,6 @@ class BNote extends AbstractBeccaEntity {
* @returns {BAttribute} * @returns {BAttribute}
*/ */
addAttribute(type, name, value = "", isInheritable = false, position = null) { addAttribute(type, name, value = "", isInheritable = false, position = null) {
const BAttribute = require("./battribute");
return new BAttribute({ return new BAttribute({
noteId: this.noteId, noteId: this.noteId,
type: type, type: type,
@ -1448,8 +1455,6 @@ class BNote extends AbstractBeccaEntity {
removeRelation(name, value) { return this.removeAttribute(RELATION, name, value); } removeRelation(name, value) { return this.removeAttribute(RELATION, name, value); }
searchNotesInSubtree(searchString) { searchNotesInSubtree(searchString) {
const searchService = require("../../services/search/services/search");
return searchService.searchNotes(searchString); return searchService.searchNotes(searchString);
} }
@ -1462,8 +1467,6 @@ class BNote extends AbstractBeccaEntity {
* @returns {{success: boolean, message: string, branchId: string, notePath: string}} * @returns {{success: boolean, message: string, branchId: string, notePath: string}}
*/ */
cloneTo(parentNoteId) { cloneTo(parentNoteId) {
const cloningService = require("../../services/cloning");
const branch = this.becca.getNote(parentNoteId).getParentBranches()[0]; const branch = this.becca.getNote(parentNoteId).getParentBranches()[0];
return cloningService.cloneNoteToBranch(this.noteId, branch.branchId); return cloningService.cloneNoteToBranch(this.noteId, branch.branchId);
@ -1536,8 +1539,6 @@ class BNote extends AbstractBeccaEntity {
const fixedContent = utils.replaceAll(parentContent, oldNoteUrl, newAttachmentUrl); const fixedContent = utils.replaceAll(parentContent, oldNoteUrl, newAttachmentUrl);
parentNote.setContent(fixedContent); parentNote.setContent(fixedContent);
const noteService = require("../../services/notes");
noteService.asyncPostProcessContent(parentNote, fixedContent); // to mark an unused attachment for deletion noteService.asyncPostProcessContent(parentNote, fixedContent); // to mark an unused attachment for deletion
this.deleteNote(); this.deleteNote();
@ -1563,9 +1564,6 @@ class BNote extends AbstractBeccaEntity {
if (!taskContext) { if (!taskContext) {
taskContext = new TaskContext('no-progress-reporting'); taskContext = new TaskContext('no-progress-reporting');
} }
// needs to be run before branches and attributes are deleted and thus attached relations disappear
const handlers = require("../../services/handlers");
handlers.runAttachedRelations(this, 'runOnNoteDeletion', this); handlers.runAttachedRelations(this, 'runOnNoteDeletion', this);
taskContext.noteDeletionHandlerTriggered = true; taskContext.noteDeletionHandlerTriggered = true;
@ -1725,4 +1723,4 @@ class BNote extends AbstractBeccaEntity {
} }
} }
module.exports = BNote; export default BNote;

View File

@ -1,7 +1,7 @@
"use strict"; "use strict";
const dateUtils = require('../../services/date_utils'); import dateUtils from '../../services/date_utils.js'
const AbstractBeccaEntity = require("./abstract_becca_entity"); import AbstractBeccaEntity from './abstract_becca_entity.js'
/** /**
* Option represents a name-value pair, either directly configurable by the user or some system property. * Option represents a name-value pair, either directly configurable by the user or some system property.
@ -47,4 +47,4 @@ class BOption extends AbstractBeccaEntity {
} }
} }
module.exports = BOption; export default BOption;

View File

@ -1,7 +1,7 @@
"use strict"; "use strict";
const dateUtils = require('../../services/date_utils'); import dateUtils from '../../services/date_utils.js'
const AbstractBeccaEntity = require("./abstract_becca_entity"); import AbstractBeccaEntity from './abstract_becca_entity.js'
/** /**
* RecentNote represents recently visited note. * RecentNote represents recently visited note.
@ -32,4 +32,4 @@ class BRecentNote extends AbstractBeccaEntity {
} }
} }
module.exports = BRecentNote; export default BRecentNote;

View File

@ -1,12 +1,12 @@
"use strict"; "use strict";
const protectedSessionService = require('../../services/protected_session'); import protectedSessionService from '../../services/protected_session.js'
const utils = require('../../services/utils'); import utils from '../../services/utils.js'
const dateUtils = require('../../services/date_utils'); import dateUtils from '../../services/date_utils.js'
const becca = require('../becca'); import becca from '../becca.js'
const AbstractBeccaEntity = require("./abstract_becca_entity"); import AbstractBeccaEntity from './abstract_becca_entity.js'
const sql = require("../../services/sql"); import sql from '../../services/sql.js'
const BAttachment = require("./battachment"); import BAttachment from './battachment.js'
/** /**
* Revision represents a snapshot of note's title and content at some point in the past. * Revision represents a snapshot of note's title and content at some point in the past.
@ -205,4 +205,4 @@ class BRevision extends AbstractBeccaEntity {
} }
} }
module.exports = BRevision; export default BRevision;

View File

@ -1,12 +1,12 @@
const BAttachment = require("./entities/battachment"); import BAttachment from './entities/battachment.js'
const BAttribute = require('./entities/battribute'); import BAttribute from './entities/battribute.js'
const BBlob = require("./entities/bblob"); import BBlob from './entities/bblob.js'
const BBranch = require('./entities/bbranch'); import BBranch from './entities/bbranch.js'
const BEtapiToken = require('./entities/betapi_token'); import BEtapiToken from './entities/betapi_token.js'
const BNote = require('./entities/bnote'); import BNote from './entities/bnote.js'
const BOption = require('./entities/boption'); import BOption from './entities/boption.js'
const BRecentNote = require('./entities/brecent_note'); import BRecentNote from './entities/brecent_note.js'
const BRevision = require('./entities/brevision'); import BRevision from './entities/brevision.js'
const ENTITY_NAME_TO_ENTITY = { const ENTITY_NAME_TO_ENTITY = {
"attachments": BAttachment, "attachments": BAttachment,
@ -28,6 +28,6 @@ function getEntityFromEntityName(entityName) {
return ENTITY_NAME_TO_ENTITY[entityName]; return ENTITY_NAME_TO_ENTITY[entityName];
} }
module.exports = { export default {
getEntityFromEntityName getEntityFromEntityName
}; };

View File

@ -1,8 +1,8 @@
const becca = require('./becca'); import becca from './becca.js'
const log = require('../services/log'); import log from '../services/log.js'
const beccaService = require('./becca_service'); import beccaService from './becca_service.js'
const dateUtils = require('../services/date_utils'); import dateUtils from '../services/date_utils.js'
const {JSDOM} = require("jsdom"); import { JSDOM } from 'jsdom';
const DEBUG = false; const DEBUG = false;
@ -35,7 +35,7 @@ const IGNORED_ATTR_NAMES = [
function filterUrlValue(value) { function filterUrlValue(value) {
return value return value
.replace(/https?:\/\//ig, "") .replace(/https?:\/\//ig, "")
.replace(/www\./ig, "") .replace(/www.js\./ig, "")
.replace(/(\.net|\.com|\.org|\.info|\.edu)/ig, ""); .replace(/(\.net|\.com|\.org|\.info|\.edu)/ig, "");
} }
@ -456,6 +456,6 @@ function setImmediatePromise() {
}); });
} }
module.exports = { export default {
findSimilarNotes findSimilarNotes
}; };

View File

@ -4,4 +4,4 @@ class NotFoundError {
} }
} }
module.exports = NotFoundError; export default NotFoundError;

View File

@ -4,4 +4,4 @@ class ValidationError {
} }
} }
module.exports = ValidationError; export default ValidationError;

View File

@ -1,5 +1,5 @@
const appInfo = require('../services/app_info'); import appInfo from '../services/app_info.js'
const eu = require("./etapi_utils"); import eu from './etapi_utils.js'
function register(router) { function register(router) {
eu.route(router, 'get', '/etapi/app-info', (req, res, next) => { eu.route(router, 'get', '/etapi/app-info', (req, res, next) => {
@ -7,6 +7,6 @@ function register(router) {
}); });
} }
module.exports = { export default {
register register
}; };

View File

@ -1,8 +1,8 @@
const becca = require("../becca/becca"); import becca from '../becca/becca.js'
const eu = require("./etapi_utils"); import eu from './etapi_utils.js'
const mappers = require("./mappers"); import mappers from './mappers.js'
const v = require("./validators"); import v from './validators.js'
const utils = require("../services/utils"); import utils from '../services/utils.js'
function register(router) { function register(router) {
const ALLOWED_PROPERTIES_FOR_CREATE_ATTACHMENT = { const ALLOWED_PROPERTIES_FOR_CREATE_ATTACHMENT = {
@ -98,6 +98,6 @@ function register(router) {
}); });
} }
module.exports = { export default {
register register
}; };

View File

@ -1,8 +1,8 @@
const becca = require("../becca/becca"); import becca from '../becca/becca.js'
const eu = require("./etapi_utils"); import eu from './etapi_utils.js'
const mappers = require("./mappers"); import mappers from './mappers.js'
const attributeService = require("../services/attributes"); import attributeService from '../services/attributes.js'
const v = require("./validators"); import v from './validators.js'
function register(router) { function register(router) {
eu.route(router, 'get', '/etapi/attributes/:attributeId', (req, res, next) => { eu.route(router, 'get', '/etapi/attributes/:attributeId', (req, res, next) => {
@ -78,6 +78,6 @@ function register(router) {
}); });
} }
module.exports = { export default {
register register
}; };

View File

@ -1,7 +1,7 @@
const becca = require("../becca/becca"); import becca from '../becca/becca.js'
const eu = require("./etapi_utils"); import eu from './etapi_utils.js'
const passwordEncryptionService = require("../services/encryption/password_encryption"); import passwordEncryptionService from '../services/encryption/password_encryption.js'
const etapiTokenService = require("../services/etapi_tokens"); import etapiTokenService from '../services/etapi_tokens.js'
function register(router, loginMiddleware) { function register(router, loginMiddleware) {
eu.NOT_AUTHENTICATED_ROUTE(router, 'post', '/etapi/auth/login', loginMiddleware, (req, res, next) => { eu.NOT_AUTHENTICATED_ROUTE(router, 'post', '/etapi/auth/login', loginMiddleware, (req, res, next) => {
@ -38,6 +38,6 @@ function register(router, loginMiddleware) {
}); });
} }
module.exports = { export default {
register register
} };

View File

@ -1,5 +1,5 @@
const eu = require("./etapi_utils"); import eu from './etapi_utils.js'
const backupService = require("../services/backup"); import backupService from '../services/backup.js'
function register(router) { function register(router) {
eu.route(router, 'put', '/etapi/backup/:backupName', async (req, res, next) => { eu.route(router, 'put', '/etapi/backup/:backupName', async (req, res, next) => {
@ -9,6 +9,6 @@ function register(router) {
}); });
} }
module.exports = { export default {
register register
}; };

View File

@ -1,9 +1,9 @@
const becca = require("../becca/becca"); import becca from '../becca/becca.js'
const eu = require("./etapi_utils"); import eu from './etapi_utils.js'
const mappers = require("./mappers"); import mappers from './mappers.js'
const BBranch = require("../becca/entities/bbranch"); import BBranch from '../becca/entities/bbranch.js'
const entityChangesService = require("../services/entity_changes"); import entityChangesService from '../services/entity_changes.js'
const v = require("./validators"); import v from './validators.js'
function register(router) { function register(router) {
eu.route(router, 'get', '/etapi/branches/:branchId', (req, res, next) => { eu.route(router, 'get', '/etapi/branches/:branchId', (req, res, next) => {
@ -81,6 +81,6 @@ function register(router) {
}); });
} }
module.exports = { export default {
register register
}; };

View File

@ -1,9 +1,9 @@
const cls = require("../services/cls"); import cls from '../services/cls.js'
const sql = require("../services/sql"); import sql from '../services/sql.js'
const log = require("../services/log"); import log from '../services/log.js'
const becca = require("../becca/becca"); import becca from '../becca/becca.js'
const etapiTokenService = require("../services/etapi_tokens"); import etapiTokenService from '../services/etapi_tokens.js'
const config = require("../services/config"); import config from '../services/config.js'
const GENERIC_CODE = "GENERIC"; const GENERIC_CODE = "GENERIC";
const noAuthentication = config.General && config.General.noAuthentication === true; const noAuthentication = config.General && config.General.noAuthentication === true;
@ -136,7 +136,7 @@ function validateAndPatch(target, source, allowedProperties) {
} }
} }
module.exports = { export default {
EtapiError, EtapiError,
sendError, sendError,
route, route,
@ -147,4 +147,4 @@ module.exports = {
getAndCheckBranch, getAndCheckBranch,
getAndCheckAttribute, getAndCheckAttribute,
getAndCheckAttachment getAndCheckAttachment
} };

View File

@ -63,7 +63,7 @@ function mapAttachmentToPojo(attachment) {
}; };
} }
module.exports = { export default {
mapNoteToPojo, mapNoteToPojo,
mapBranchToPojo, mapBranchToPojo,
mapAttributeToPojo, mapAttributeToPojo,

View File

@ -1,14 +1,14 @@
const becca = require("../becca/becca"); import becca from '../becca/becca.js'
const utils = require("../services/utils"); import utils from '../services/utils.js'
const eu = require("./etapi_utils"); import eu from './etapi_utils.js'
const mappers = require("./mappers"); import mappers from './mappers.js'
const noteService = require("../services/notes"); import noteService from '../services/notes.js'
const TaskContext = require("../services/task_context"); import TaskContext from '../services/task_context.js'
const v = require("./validators"); import v from './validators.js'
const searchService = require("../services/search/services/search"); import searchService from '../services/search/services/search.js'
const SearchContext = require("../services/search/search_context"); import SearchContext from '../services/search/search_context.js'
const zipExportService = require("../services/export/zip"); import zipExportService from '../services/export/zip.js'
const zipImportService = require("../services/import/zip"); import zipImportService from '../services/import/zip.js'
function register(router) { function register(router) {
eu.route(router, 'get', '/etapi/notes', (req, res, next) => { eu.route(router, 'get', '/etapi/notes', (req, res, next) => {
@ -251,6 +251,6 @@ function parseInteger(obj, name) {
return integer; return integer;
} }
module.exports = { export default {
register register
}; };

View File

@ -1,5 +1,8 @@
const fs = require('fs'); import fs from 'fs';
const path = require('path'); import path from 'path';
import {fileURLToPath} from "node:url";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const specPath = path.join(__dirname, 'etapi.openapi.yaml'); const specPath = path.join(__dirname, 'etapi.openapi.yaml');
let spec = null; let spec = null;
@ -15,6 +18,6 @@ function register(router) {
}); });
} }
module.exports = { export default {
register register
}; };

View File

@ -1,7 +1,7 @@
const specialNotesService = require("../services/special_notes"); import specialNotesService from '../services/special_notes.js'
const dateNotesService = require("../services/date_notes"); import dateNotesService from '../services/date_notes.js'
const eu = require("./etapi_utils"); import eu from './etapi_utils.js'
const mappers = require("./mappers"); import mappers from './mappers.js'
const getDateInvalidError = date => new eu.EtapiError(400, "DATE_INVALID", `Date "${date}" is not valid.`); const getDateInvalidError = date => new eu.EtapiError(400, "DATE_INVALID", `Date "${date}" is not valid.`);
const getMonthInvalidError = month => new eu.EtapiError(400, "MONTH_INVALID", `Month "${month}" is not valid.`); const getMonthInvalidError = month => new eu.EtapiError(400, "MONTH_INVALID", `Month "${month}" is not valid.`);
@ -72,6 +72,6 @@ function register(router) {
}); });
} }
module.exports = { export default {
register register
}; };

View File

@ -1,5 +1,7 @@
const noteTypeService = require("../services/note_types"); import noteTypeService from '../services/note_types.js'
const dateUtils = require("../services/date_utils"); import dateUtils from '../services/date_utils.js'
import becca from '../becca/becca.js'
function mandatory(obj) { function mandatory(obj) {
if (obj === undefined ) { if (obj === undefined ) {
@ -63,9 +65,6 @@ function isNoteId(obj) {
if (obj === undefined || obj === null) { if (obj === undefined || obj === null) {
return; return;
} }
const becca = require('../becca/becca');
if (typeof obj !== 'string') { if (typeof obj !== 'string') {
return `'${obj}' is not a valid noteId`; return `'${obj}' is not a valid noteId`;
} }
@ -107,7 +106,7 @@ function isValidEntityId(obj) {
} }
} }
module.exports = { export default {
mandatory, mandatory,
notNull, notNull,
isString, isString,

View File

@ -10,6 +10,10 @@ import bundleService from "../services/bundle.js";
import froca from "../services/froca.js"; import froca from "../services/froca.js";
import linkService from "../services/link.js"; import linkService from "../services/link.js";
import {getCurrentWebContents, getCurrentWindow} from "@electron/remote";
import {ipcRenderer} from "electron";
export default class Entrypoints extends Component { export default class Entrypoints extends Component {
constructor() { constructor() {
super(); super();
@ -24,7 +28,7 @@ export default class Entrypoints extends Component {
openDevToolsCommand() { openDevToolsCommand() {
if (utils.isElectron()) { if (utils.isElectron()) {
utils.dynamicRequire('@electron/remote').getCurrentWindow().toggleDevTools(); getCurrentWindow().toggleDevTools();
} }
} }
@ -78,7 +82,7 @@ export default class Entrypoints extends Component {
toggleFullscreenCommand() { toggleFullscreenCommand() {
if (utils.isElectron()) { if (utils.isElectron()) {
const win = utils.dynamicRequire('@electron/remote').getCurrentWindow(); const win = getCurrentWindow();
if (win.isFullScreenable()) { if (win.isFullScreenable()) {
win.setFullScreen(!win.isFullScreen()); win.setFullScreen(!win.isFullScreen());
@ -101,7 +105,7 @@ export default class Entrypoints extends Component {
backInNoteHistoryCommand() { backInNoteHistoryCommand() {
if (utils.isElectron()) { if (utils.isElectron()) {
// standard JS version does not work completely correctly in electron // standard JS version does not work completely correctly in electron
const webContents = utils.dynamicRequire('@electron/remote').getCurrentWebContents(); const webContents = getCurrentWebContents();
const activeIndex = parseInt(webContents.getActiveIndex()); const activeIndex = parseInt(webContents.getActiveIndex());
webContents.goToIndex(activeIndex - 1); webContents.goToIndex(activeIndex - 1);
@ -114,7 +118,7 @@ export default class Entrypoints extends Component {
forwardInNoteHistoryCommand() { forwardInNoteHistoryCommand() {
if (utils.isElectron()) { if (utils.isElectron()) {
// standard JS version does not work completely correctly in electron // standard JS version does not work completely correctly in electron
const webContents = utils.dynamicRequire('@electron/remote').getCurrentWebContents(); const webContents = getCurrentWebContents();
const activeIndex = parseInt(webContents.getActiveIndex()); const activeIndex = parseInt(webContents.getActiveIndex());
webContents.goToIndex(activeIndex + 1); webContents.goToIndex(activeIndex + 1);
@ -140,8 +144,6 @@ export default class Entrypoints extends Component {
const extraWindowHash = linkService.calculateHash({notePath, hoistedNoteId, viewScope}); const extraWindowHash = linkService.calculateHash({notePath, hoistedNoteId, viewScope});
if (utils.isElectron()) { if (utils.isElectron()) {
const {ipcRenderer} = utils.dynamicRequire('electron');
ipcRenderer.send('create-extra-window', { extraWindowHash }); ipcRenderer.send('create-extra-window', { extraWindowHash });
} }
else { else {

View File

@ -158,7 +158,7 @@ class NoteContext extends Component {
return; return;
} }
if (await hoistedNoteService.checkNoteAccess(resolvedNotePath, this) === false) { if ((await hoistedNoteService.checkNoteAccess(resolvedNotePath, this)) === false) {
return; // note is outside of hoisted subtree and user chose not to unhoist return; // note is outside of hoisted subtree and user chose not to unhoist
} }

View File

@ -8,6 +8,8 @@ import options from "../services/options.js";
import froca from "../services/froca.js"; import froca from "../services/froca.js";
import utils from "../services/utils.js"; import utils from "../services/utils.js";
import {BrowserWindow} from "@electron/remote";
export default class RootCommandExecutor extends Component { export default class RootCommandExecutor extends Component {
editReadOnlyNoteCommand() { editReadOnlyNoteCommand() {
const noteContext = appContext.tabManager.getActiveContext(); const noteContext = appContext.tabManager.getActiveContext();
@ -158,7 +160,6 @@ export default class RootCommandExecutor extends Component {
toggleTrayCommand() { toggleTrayCommand() {
if (!utils.isElectron()) return; if (!utils.isElectron()) return;
const {BrowserWindow} = utils.dynamicRequire('@electron/remote');
const windows = BrowserWindow.getAllWindows(); const windows = BrowserWindow.getAllWindows();
const isVisible = windows.every(w => w.isVisible()); const isVisible = windows.every(w => w.isVisible());
const action = isVisible ? "hide" : "show" const action = isVisible ? "hide" : "show"

View File

@ -248,7 +248,7 @@ export default class TabManager extends Component {
async switchToNoteContext(ntxId, notePath, viewScope = {}, hoistedNoteId = null) { async switchToNoteContext(ntxId, notePath, viewScope = {}, hoistedNoteId = null) {
const noteContext = this.noteContexts.find(nc => nc.ntxId === ntxId) const noteContext = this.noteContexts.find(nc => nc.ntxId === ntxId)
|| await this.openEmptyTab(); || (await this.openEmptyTab());
await this.activateNoteContext(noteContext.ntxId); await this.activateNoteContext(noteContext.ntxId);

View File

@ -2,6 +2,8 @@ import options from "../services/options.js";
import Component from "./component.js"; import Component from "./component.js";
import utils from "../services/utils.js"; import utils from "../services/utils.js";
import {webFrame} from "electron";
const MIN_ZOOM = 0.5; const MIN_ZOOM = 0.5;
const MAX_ZOOM = 2.0; const MAX_ZOOM = 2.0;
@ -24,8 +26,6 @@ class ZoomComponent extends Component {
setZoomFactor(zoomFactor) { setZoomFactor(zoomFactor) {
zoomFactor = parseFloat(zoomFactor); zoomFactor = parseFloat(zoomFactor);
const webFrame = utils.dynamicRequire('electron').webFrame;
webFrame.setZoomFactor(zoomFactor); webFrame.setZoomFactor(zoomFactor);
} }
@ -43,7 +43,7 @@ class ZoomComponent extends Component {
} }
getCurrentZoom() { getCurrentZoom() {
return utils.dynamicRequire('electron').webFrame.getZoomFactor(); return webFrame.getZoomFactor();
} }
zoomOutEvent() { zoomOutEvent() {

View File

@ -8,6 +8,8 @@ import electronContextMenu from "./menus/electron_context_menu.js";
import DesktopLayout from "./layouts/desktop_layout.js"; import DesktopLayout from "./layouts/desktop_layout.js";
import glob from "./services/glob.js"; import glob from "./services/glob.js";
import {ipcRenderer} from "electron";
bundleService.getWidgetBundlesByParent().then(widgetBundles => { bundleService.getWidgetBundlesByParent().then(widgetBundles => {
appContext.setLayout(new DesktopLayout(widgetBundles)); appContext.setLayout(new DesktopLayout(widgetBundles));
appContext.start(); appContext.start();
@ -16,7 +18,7 @@ bundleService.getWidgetBundlesByParent().then(widgetBundles => {
glob.setupGlobs(); glob.setupGlobs();
if (utils.isElectron()) { if (utils.isElectron()) {
utils.dynamicRequire('electron').ipcRenderer.on('globalShortcut', ipcRenderer.on('globalShortcut',
async (event, actionName) => appContext.triggerCommand(actionName)); async (event, actionName) => appContext.triggerCommand(actionName));
} }

View File

@ -3,10 +3,11 @@ import options from "../services/options.js";
import zoomService from "../components/zoom.js"; import zoomService from "../components/zoom.js";
import contextMenu from "./context_menu.js"; import contextMenu from "./context_menu.js";
function setupContextMenu() { import electron from "electron";
const electron = utils.dynamicRequire('electron');
const remote = utils.dynamicRequire('@electron/remote'); import remote from "@electron/remote";
function setupContextMenu() {
const {webContents} = remote.getCurrentWindow(); const {webContents} = remote.getCurrentWindow();
webContents.on('context-menu', (event, params) => { webContents.on('context-menu', (event, params) => {

View File

@ -134,7 +134,7 @@ export default class TreeContextMenu {
this.treeWidget.triggerCommand("openNewNoteSplit", {ntxId, notePath}); this.treeWidget.triggerCommand("openNewNoteSplit", {ntxId, notePath});
} }
else if (command === 'convertNoteToAttachment') { else if (command === 'convertNoteToAttachment') {
if (!await dialogService.confirm(`Are you sure you want to convert note selected notes into attachments of their parent notes?`)) { if (!(await dialogService.confirm(`Are you sure you want to convert note selected notes into attachments of their parent notes?`))) {
return; return;
} }

View File

@ -4,6 +4,10 @@ import froca from "./froca.js";
import linkService from "./link.js"; import linkService from "./link.js";
import utils from "./utils.js"; import utils from "./utils.js";
// https://github.com/zadam/trilium/issues/2401
import {clipboard} from "electron";
let clipboardBranchIds = []; let clipboardBranchIds = [];
let clipboardMode = null; let clipboardMode = null;
@ -66,8 +70,6 @@ async function copy(branchIds) {
clipboardMode = 'copy'; clipboardMode = 'copy';
if (utils.isElectron()) { if (utils.isElectron()) {
// https://github.com/zadam/trilium/issues/2401
const {clipboard} = require('electron');
const links = []; const links = [];
for (const branch of froca.getBranches(clipboardBranchIds)) { for (const branch of froca.getBranches(clipboardBranchIds)) {

View File

@ -53,7 +53,7 @@ async function checkNoteAccess(notePath, noteContext) {
const hoistedNote = await froca.getNote(hoistedNoteId); const hoistedNote = await froca.getNote(hoistedNoteId);
if (!hoistedNote.hasAncestor('_hidden') if (!hoistedNote.hasAncestor('_hidden')
&& !await dialogService.confirm(`Requested note '${requestedNote.title}' is outside of hoisted note '${hoistedNote.title}' subtree and you must unhoist to access the note. Do you want to proceed with unhoisting?`)) { && !(await dialogService.confirm(`Requested note '${requestedNote.title}' is outside of hoisted note '${hoistedNote.title}' subtree and you must unhoist to access the note. Do you want to proceed with unhoisting?`))) {
return false; return false;
} }

View File

@ -4,6 +4,8 @@ import appContext from "../components/app_context.js";
import froca from "./froca.js"; import froca from "./froca.js";
import utils from "./utils.js"; import utils from "./utils.js";
import electron from "electron";
function getNotePathFromUrl(url) { function getNotePathFromUrl(url) {
const notePathMatch = /#(root[A-Za-z0-9_/]*)$/.exec(url); const notePathMatch = /#(root[A-Za-z0-9_/]*)$/.exec(url);
@ -242,8 +244,6 @@ function goToLinkExt(evt, hrefLink, $link) {
if (hrefLink.toLowerCase().startsWith('http') || hrefLink.startsWith("api/")) { if (hrefLink.toLowerCase().startsWith('http') || hrefLink.startsWith("api/")) {
window.open(hrefLink, '_blank'); window.open(hrefLink, '_blank');
} else if (hrefLink.toLowerCase().startsWith('file:') && utils.isElectron()) { } else if (hrefLink.toLowerCase().startsWith('file:') && utils.isElectron()) {
const electron = utils.dynamicRequire('electron');
electron.shell.openPath(hrefLink); electron.shell.openPath(hrefLink);
} }
} }

View File

@ -1,6 +1,12 @@
import utils from "./utils.js"; import utils from "./utils.js";
import server from "./server.js"; import server from "./server.js";
import remote from "@electron/remote";
import {exec} from "child_process";
import electron from "electron";
function checkType(type) { function checkType(type) {
if (type !== 'notes' && type !== 'attachments') { if (type !== 'notes' && type !== 'attachments') {
throw new Error(`Unrecognized type '${type}', should be 'notes' or 'attachments'`); throw new Error(`Unrecognized type '${type}', should be 'notes' or 'attachments'`);
@ -21,8 +27,6 @@ function getOpenFileUrl(type, noteId) {
function download(url) { function download(url) {
if (utils.isElectron()) { if (utils.isElectron()) {
const remote = utils.dynamicRequire('@electron/remote');
remote.getCurrentWebContents().downloadURL(url); remote.getCurrentWebContents().downloadURL(url);
} else { } else {
window.location.href = url; window.location.href = url;
@ -49,7 +53,6 @@ async function openCustom(type, entityId, mime) {
const resp = await server.post(`${type}/${entityId}/save-to-tmp-dir`); const resp = await server.post(`${type}/${entityId}/save-to-tmp-dir`);
let filePath = resp.tmpFilePath; let filePath = resp.tmpFilePath;
const {exec} = utils.dynamicRequire('child_process');
const platform = process.platform; const platform = process.platform;
if (platform === 'linux') { if (platform === 'linux') {
@ -139,8 +142,6 @@ async function openExternally(type, entityId, mime) {
if (utils.isElectron()) { if (utils.isElectron()) {
const resp = await server.post(`${type}/${entityId}/save-to-tmp-dir`); const resp = await server.post(`${type}/${entityId}/save-to-tmp-dir`);
const electron = utils.dynamicRequire('electron');
const res = await electron.shell.openPath(resp.tmpFilePath); const res = await electron.shell.openPath(resp.tmpFilePath);
if (res) { if (res) {

View File

@ -1,6 +1,8 @@
import utils from './utils.js'; import utils from './utils.js';
import ValidationError from "./validation_error.js"; import ValidationError from "./validation_error.js";
import {ipcRenderer as ipc} from "electron";
async function getHeaders(headers) { async function getHeaders(headers) {
const appContext = (await import('../components/app_context.js')).default; const appContext = (await import('../components/app_context.js')).default;
const activeNoteContext = appContext.tabManager ? appContext.tabManager.getActiveContext() : null; const activeNoteContext = appContext.tabManager ? appContext.tabManager.getActiveContext() : null;
@ -81,7 +83,6 @@ async function call(method, url, componentId, options = {}) {
const {data} = options; const {data} = options;
if (utils.isElectron()) { if (utils.isElectron()) {
const ipc = utils.dynamicRequire('electron').ipcRenderer;
const requestId = idCounter++; const requestId = idCounter++;
resp = await new Promise((resolve, reject) => { resp = await new Promise((resolve, reject) => {
@ -159,8 +160,6 @@ function ajax(url, method, data, headers, silentNotFound) {
} }
if (utils.isElectron()) { if (utils.isElectron()) {
const ipc = utils.dynamicRequire('electron').ipcRenderer;
ipc.on('server-response', async (event, arg) => { ipc.on('server-response', async (event, arg) => {
if (arg.statusCode >= 200 && arg.statusCode < 300) { if (arg.statusCode >= 200 && arg.statusCode < 300) {
handleSuccessfulResponse(arg); handleSuccessfulResponse(arg);

View File

@ -4,6 +4,8 @@ import froca from './froca.js';
import hoistedNoteService from '../services/hoisted_note.js'; import hoistedNoteService from '../services/hoisted_note.js';
import appContext from "../components/app_context.js"; import appContext from "../components/app_context.js";
import {getCurrentWindow} from "@electron/remote";
/** /**
* @returns {string|null} * @returns {string|null}
*/ */
@ -121,7 +123,7 @@ ws.subscribeToMessages(message => {
appContext.tabManager.activateOrOpenNote(message.noteId); appContext.tabManager.activateOrOpenNote(message.noteId);
if (utils.isElectron()) { if (utils.isElectron()) {
const currentWindow = utils.dynamicRequire('@electron/remote').getCurrentWindow(); const currentWindow = getCurrentWindow();
currentWindow.show(); currentWindow.show();
} }

View File

@ -1,6 +1,8 @@
import utils from "./services/utils.js"; import utils from "./services/utils.js";
import macInit from './services/mac_init.js'; import macInit from './services/mac_init.js';
import remote from "@electron/remote";
macInit.init(); macInit.init();
function SetupModel() { function SetupModel() {
@ -84,7 +86,6 @@ async function checkOutstandingSyncs() {
if (initialized) { if (initialized) {
if (utils.isElectron()) { if (utils.isElectron()) {
const remote = utils.dynamicRequire('@electron/remote');
remote.app.relaunch(); remote.app.relaunch();
remote.app.exit(0); remote.app.exit(0);
} }

View File

@ -123,7 +123,7 @@ export default class AttachmentActionsWidget extends BasicWidget {
} }
async deleteAttachmentCommand() { async deleteAttachmentCommand() {
if (!await dialogService.confirm(`Are you sure you want to delete attachment '${this.attachment.title}'?`)) { if (!(await dialogService.confirm(`Are you sure you want to delete attachment '${this.attachment.title}'?`))) {
return; return;
} }
@ -132,7 +132,7 @@ export default class AttachmentActionsWidget extends BasicWidget {
} }
async convertAttachmentIntoNoteCommand() { async convertAttachmentIntoNoteCommand() {
if (!await dialogService.confirm(`Are you sure you want to convert attachment '${this.attachment.title}' into a separate note?`)) { if (!(await dialogService.confirm(`Are you sure you want to convert attachment '${this.attachment.title}' into a separate note?`))) {
return; return;
} }

View File

@ -3,6 +3,8 @@ import utils from "../../services/utils.js";
import UpdateAvailableWidget from "./update_available.js"; import UpdateAvailableWidget from "./update_available.js";
import options from "../../services/options.js"; import options from "../../services/options.js";
import {webFrame} from "electron";
const TPL = ` const TPL = `
<div class="dropdown global-menu dropright"> <div class="dropdown global-menu dropright">
<style> <style>
@ -281,7 +283,7 @@ export default class GlobalMenuWidget extends BasicWidget {
return; return;
} }
const zoomFactor = utils.dynamicRequire('electron').webFrame.getZoomFactor(); const zoomFactor = webFrame.getZoomFactor();
const zoomPercent = Math.round(zoomFactor * 100); const zoomPercent = Math.round(zoomFactor * 100);
this.$zoomState.text(`${zoomPercent}%`); this.$zoomState.text(`${zoomPercent}%`);

View File

@ -3,6 +3,8 @@ import contextMenu from "../../menus/context_menu.js";
import treeService from "../../services/tree.js"; import treeService from "../../services/tree.js";
import ButtonFromNoteWidget from "./button_from_note.js"; import ButtonFromNoteWidget from "./button_from_note.js";
import {getCurrentWebContents} from "@electron/remote";
export default class HistoryNavigationButton extends ButtonFromNoteWidget { export default class HistoryNavigationButton extends ButtonFromNoteWidget {
constructor(launcherNote, command) { constructor(launcherNote, command) {
super(); super();
@ -27,7 +29,7 @@ export default class HistoryNavigationButton extends ButtonFromNoteWidget {
return; return;
} }
this.webContents = utils.dynamicRequire('@electron/remote').getCurrentWebContents(); this.webContents = getCurrentWebContents();
// without this, the history is preserved across frontend reloads // without this, the history is preserved across frontend reloads
this.webContents.clearHistory(); this.webContents.clearHistory();

View File

@ -119,7 +119,7 @@ export default class NoteActionsWidget extends NoteContextAwareWidget {
} }
async convertNoteIntoAttachmentCommand() { async convertNoteIntoAttachmentCommand() {
if (!await dialogService.confirm(`Are you sure you want to convert note '${this.note.title}' into an attachment of the parent note?`)) { if (!(await dialogService.confirm(`Are you sure you want to convert note '${this.note.title}' into an attachment of the parent note?`))) {
return; return;
} }

View File

@ -5,6 +5,8 @@ import BasicWidget from "../basic_widget.js";
import shortcutService from "../../services/shortcuts.js"; import shortcutService from "../../services/shortcuts.js";
import server from "../../services/server.js"; import server from "../../services/server.js";
import {clipboard} from "electron";
const TPL = ` const TPL = `
<div class="markdown-import-dialog modal fade mx-auto" tabindex="-1" role="dialog"> <div class="markdown-import-dialog modal fade mx-auto" tabindex="-1" role="dialog">
<div class="modal-dialog modal-lg" role="document"> <div class="modal-dialog modal-lg" role="document">
@ -69,7 +71,6 @@ export default class MarkdownImportDialog extends BasicWidget {
} }
if (utils.isElectron()) { if (utils.isElectron()) {
const {clipboard} = utils.dynamicRequire('electron');
const text = clipboard.readText(); const text = clipboard.readText();
this.convertMarkdownToHtml(text); this.convertMarkdownToHtml(text);

View File

@ -173,9 +173,9 @@ export default class NoteDetailWidget extends NoteContextAwareWidget {
type = 'readOnlyCode'; type = 'readOnlyCode';
} else if (viewScope.viewMode === 'attachments') { } else if (viewScope.viewMode === 'attachments') {
type = viewScope.attachmentId ? 'attachmentDetail' : 'attachmentList'; type = viewScope.attachmentId ? 'attachmentDetail' : 'attachmentList';
} else if (type === 'text' && await this.noteContext.isReadOnly()) { } else if (type === 'text' && (await this.noteContext.isReadOnly())) {
type = 'readOnlyText'; type = 'readOnlyText';
} else if ((type === 'code' || type === 'mermaid') && await this.noteContext.isReadOnly()) { } else if ((type === 'code' || type === 'mermaid') && (await this.noteContext.isReadOnly())) {
type = 'readOnlyCode'; type = 'readOnlyCode';
} else if (type === 'text') { } else if (type === 'text') {
type = 'editableText'; type = 'editableText';
@ -303,7 +303,7 @@ export default class NoteDetailWidget extends NoteContextAwareWidget {
this.handleEvent('noteTypeMimeChanged', {noteId: this.noteId}); this.handleEvent('noteTypeMimeChanged', {noteId: this.noteId});
} }
else if (loadResults.isNoteReloaded(this.noteId, this.componentId) else if (loadResults.isNoteReloaded(this.noteId, this.componentId)
&& (this.type !== await this.getWidgetType() || this.mime !== this.note.mime)) { && (this.type !== (await this.getWidgetType()) || this.mime !== this.note.mime)) {
// this needs to have a triggerEvent so that e.g., note type (not in the component subtree) is updated // this needs to have a triggerEvent so that e.g., note type (not in the component subtree) is updated
this.triggerEvent('noteTypeMimeChanged', {noteId: this.noteId}); this.triggerEvent('noteTypeMimeChanged', {noteId: this.noteId});

View File

@ -998,8 +998,8 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {
const oldActiveNode = this.getActiveNode(); const oldActiveNode = this.getActiveNode();
const newActiveNode = this.noteContext?.notePath const newActiveNode = this.noteContext?.notePath
&& (!treeService.isNotePathInHiddenSubtree(this.noteContext.notePath) || await hoistedNoteService.isHoistedInHiddenSubtree()) && (!treeService.isNotePathInHiddenSubtree(this.noteContext.notePath) || (await hoistedNoteService.isHoistedInHiddenSubtree()))
&& await this.getNodeFromPath(this.noteContext.notePath); && (await this.getNodeFromPath(this.noteContext.notePath));
if (newActiveNode !== oldActiveNode) { if (newActiveNode !== oldActiveNode) {
let oldActiveNodeFocused = false; let oldActiveNodeFocused = false;

View File

@ -135,7 +135,7 @@ export default class NoteTypeWidget extends NoteContextAwareWidget {
return; return;
} }
if (type !== this.note.type && !await this.confirmChangeIfContent()) { if (type !== this.note.type && !(await this.confirmChangeIfContent())) {
return; return;
} }

View File

@ -40,7 +40,7 @@ export default class SharedSwitchWidget extends SwitchWidget {
if (this.note.getParentBranches().length === 1) { if (this.note.getParentBranches().length === 1) {
const text = "This note exists only as a shared note, unsharing would delete it. Do you want to continue and thus delete this note?"; const text = "This note exists only as a shared note, unsharing would delete it. Do you want to continue and thus delete this note?";
if (!await dialogService.confirm(text)) { if (!(await dialogService.confirm(text))) {
return; return;
} }
} }

View File

@ -2,6 +2,8 @@ import BasicWidget from "./basic_widget.js";
import options from "../services/options.js"; import options from "../services/options.js";
import utils from "../services/utils.js"; import utils from "../services/utils.js";
import remote from "@electron/remote";
const TPL = ` const TPL = `
<div class="title-bar-buttons"> <div class="title-bar-buttons">
<style> <style>
@ -59,7 +61,6 @@ export default class TitleBarButtonsWidget extends BasicWidget {
// When the window is restarted, the window will not be reset when it is set to the top, // When the window is restarted, the window will not be reset when it is set to the top,
// so get the window status and set the icon background // so get the window status and set the icon background
setTimeout(() => { setTimeout(() => {
const remote = utils.dynamicRequire('@electron/remote');
if (remote.BrowserWindow.getFocusedWindow()?.isAlwaysOnTop()) { if (remote.BrowserWindow.getFocusedWindow()?.isAlwaysOnTop()) {
$topBtn.addClass('active'); $topBtn.addClass('active');
} }
@ -67,7 +68,6 @@ export default class TitleBarButtonsWidget extends BasicWidget {
$topBtn.on('click', () => { $topBtn.on('click', () => {
$topBtn.trigger('blur'); $topBtn.trigger('blur');
const remote = utils.dynamicRequire('@electron/remote');
const focusedWindow = remote.BrowserWindow.getFocusedWindow(); const focusedWindow = remote.BrowserWindow.getFocusedWindow();
const isAlwaysOnTop = focusedWindow.isAlwaysOnTop() const isAlwaysOnTop = focusedWindow.isAlwaysOnTop()
if (isAlwaysOnTop) { if (isAlwaysOnTop) {
@ -81,13 +81,11 @@ export default class TitleBarButtonsWidget extends BasicWidget {
$minimizeBtn.on('click', () => { $minimizeBtn.on('click', () => {
$minimizeBtn.trigger('blur'); $minimizeBtn.trigger('blur');
const remote = utils.dynamicRequire('@electron/remote');
remote.BrowserWindow.getFocusedWindow().minimize(); remote.BrowserWindow.getFocusedWindow().minimize();
}); });
$maximizeBtn.on('click', () => { $maximizeBtn.on('click', () => {
$maximizeBtn.trigger('blur'); $maximizeBtn.trigger('blur');
const remote = utils.dynamicRequire('@electron/remote');
const focusedWindow = remote.BrowserWindow.getFocusedWindow(); const focusedWindow = remote.BrowserWindow.getFocusedWindow();
if (focusedWindow.isMaximized()) { if (focusedWindow.isMaximized()) {
@ -99,7 +97,6 @@ export default class TitleBarButtonsWidget extends BasicWidget {
$closeBtn.on('click', () => { $closeBtn.on('click', () => {
$closeBtn.trigger('blur'); $closeBtn.trigger('blur');
const remote = utils.dynamicRequire('@electron/remote');
remote.BrowserWindow.getFocusedWindow().close(); remote.BrowserWindow.getFocusedWindow().close();
}); });
} }

View File

@ -4,6 +4,10 @@ import libraryLoader from "../../services/library_loader.js";
import contextMenu from "../../menus/context_menu.js"; import contextMenu from "../../menus/context_menu.js";
import imageService from "../../services/image.js"; import imageService from "../../services/image.js";
import {getCurrentWebContents} from "@electron/remote";
import electron from "electron";
const TPL = ` const TPL = `
<div class="note-detail-image note-detail-printable"> <div class="note-detail-image note-detail-printable">
<style> <style>
@ -75,8 +79,7 @@ class ImageTypeWidget extends TypeWidget {
if (command === 'copyImageReferenceToClipboard') { if (command === 'copyImageReferenceToClipboard') {
imageService.copyImageReferenceToClipboard(this.$imageWrapper); imageService.copyImageReferenceToClipboard(this.$imageWrapper);
} else if (command === 'copyImageToClipboard') { } else if (command === 'copyImageToClipboard') {
const webContents = utils.dynamicRequire('@electron/remote').getCurrentWebContents(); const webContents = getCurrentWebContents();
utils.dynamicRequire('electron');
webContents.copyImageAt(e.pageX, e.pageY); webContents.copyImageAt(e.pageX, e.pageY);
} else { } else {
throw new Error(`Unrecognized command '${command}'`); throw new Error(`Unrecognized command '${command}'`);

View File

@ -120,7 +120,7 @@ export default class EtapiOptions extends OptionsWidget {
} }
async deleteToken(etapiTokenId, name) { async deleteToken(etapiTokenId, name) {
if (!await dialogService.confirm(`Are you sure you want to delete ETAPI token "${name}"?`)) { if (!(await dialogService.confirm(`Are you sure you want to delete ETAPI token "${name}"?`))) {
return; return;
} }

View File

@ -112,7 +112,7 @@ export default class KeyboardShortcutsOptions extends OptionsWidget {
}); });
this.$widget.find(".options-keyboard-shortcuts-set-all-to-default").on('click', async () => { this.$widget.find(".options-keyboard-shortcuts-set-all-to-default").on('click', async () => {
if (!await dialogService.confirm("Do you really want to reset all keyboard shortcuts to the default?")) { if (!(await dialogService.confirm("Do you really want to reset all keyboard shortcuts to the default?"))) {
return; return;
} }

View File

@ -1,6 +1,8 @@
import utils from "../../../services/utils.js"; import utils from "../../../services/utils.js";
import OptionsWidget from "./options_widget.js"; import OptionsWidget from "./options_widget.js";
import {getCurrentWindow} from "@electron/remote";
const TPL = ` const TPL = `
<div class="options-section"> <div class="options-section">
<h4>Spell Check</h4> <h4>Spell Check</h4>
@ -40,7 +42,7 @@ export default class SpellcheckOptions extends OptionsWidget {
this.$availableLanguageCodes = this.$widget.find(".available-language-codes"); this.$availableLanguageCodes = this.$widget.find(".available-language-codes");
if (utils.isElectron()) { if (utils.isElectron()) {
const { webContents } = utils.dynamicRequire('@electron/remote').getCurrentWindow(); const { webContents } = getCurrentWindow();
this.$availableLanguageCodes.text(webContents.session.availableSpellCheckerLanguages.join(', ')); this.$availableLanguageCodes.text(webContents.session.availableSpellCheckerLanguages.join(', '));
} }

View File

@ -395,7 +395,7 @@ export default class RelationMapTypeWidget extends TypeWidget {
items: [ {title: "Remove relation", command: "remove", uiIcon: "bx bx-trash"} ], items: [ {title: "Remove relation", command: "remove", uiIcon: "bx bx-trash"} ],
selectMenuItemHandler: async ({command}) => { selectMenuItemHandler: async ({command}) => {
if (command === 'remove') { if (command === 'remove') {
if (!await dialogService.confirm("Are you sure you want to remove the relation?")) { if (!(await dialogService.confirm("Are you sure you want to remove the relation?"))) {
return; return;
} }

View File

@ -1,11 +1,11 @@
"use strict"; "use strict";
const appInfo = require('../../services/app_info'); import appInfo from '../../services/app_info.js'
function getAppInfo() { function getAppInfo() {
return appInfo; return appInfo;
} }
module.exports = { export default {
getAppInfo getAppInfo
}; };

View File

@ -1,7 +1,7 @@
const becca = require("../../becca/becca"); import becca from '../../becca/becca.js'
const blobService = require("../../services/blob"); import blobService from '../../services/blob.js'
const ValidationError = require("../../errors/validation_error"); import ValidationError from '../../errors/validation_error.js'
const imageService = require("../../services/image.js"); import imageService from '../../services/image.js';
function getAttachmentBlob(req) { function getAttachmentBlob(req) {
const preview = req.query.preview === 'true'; const preview = req.query.preview === 'true';
@ -96,7 +96,7 @@ function convertAttachmentToNote(req) {
return attachment.convertToNote(); return attachment.convertToNote();
} }
module.exports = { export default {
getAttachmentBlob, getAttachmentBlob,
getAttachments, getAttachments,
getAttachment, getAttachment,

View File

@ -1,11 +1,11 @@
"use strict"; "use strict";
const sql = require('../../services/sql'); import sql from '../../services/sql.js'
const log = require('../../services/log'); import log from '../../services/log.js'
const attributeService = require('../../services/attributes'); import attributeService from '../../services/attributes.js'
const BAttribute = require('../../becca/entities/battribute'); import BAttribute from '../../becca/entities/battribute.js'
const becca = require("../../becca/becca"); import becca from '../../becca/becca.js'
const ValidationError = require("../../errors/validation_error"); import ValidationError from '../../errors/validation_error.js'
function getEffectiveNoteAttributes(req) { function getEffectiveNoteAttributes(req) {
const note = becca.getNote(req.params.noteId); const note = becca.getNote(req.params.noteId);
@ -225,7 +225,7 @@ function deleteRelation(req) {
} }
} }
module.exports = { export default {
updateNoteAttributes, updateNoteAttributes,
updateNoteAttribute, updateNoteAttribute,
setNoteAttribute, setNoteAttribute,

View File

@ -1,11 +1,11 @@
"use strict"; "use strict";
const beccaService = require('../../becca/becca_service'); import beccaService from '../../becca/becca_service.js'
const searchService = require('../../services/search/services/search'); import searchService from '../../services/search/services/search.js'
const log = require('../../services/log'); import log from '../../services/log.js'
const utils = require('../../services/utils'); import utils from '../../services/utils.js'
const cls = require('../../services/cls'); import cls from '../../services/cls.js'
const becca = require("../../becca/becca"); import becca from '../../becca/becca.js'
function getAutocomplete(req) { function getAutocomplete(req) {
const query = req.query.query.trim(); const query = req.query.query.trim();
@ -70,6 +70,6 @@ function getRecentNotes(activeNoteId) {
}); });
} }
module.exports = { export default {
getAutocomplete getAutocomplete
}; };

View File

@ -1,11 +1,11 @@
"use strict"; "use strict";
const fs = require('fs'); import fs from 'fs';
const dateUtils = require('../../services/date_utils'); import dateUtils from '../../services/date_utils.js'
const {LOG_DIR} = require('../../services/data_dir'); import dataDir from '../../services/data_dir.js';
function getBackendLog() { function getBackendLog() {
const file = `${LOG_DIR}/trilium-${dateUtils.localNowDate()}.log`; const file = `${dataDir.LOG_DIR}/trilium-${dateUtils.localNowDate()}.log`;
try { try {
return fs.readFileSync(file, 'utf8'); return fs.readFileSync(file, 'utf8');
@ -16,6 +16,6 @@ function getBackendLog() {
} }
} }
module.exports = { export default {
getBackendLog getBackendLog
}; };

View File

@ -1,16 +1,16 @@
"use strict"; "use strict";
const sql = require('../../services/sql'); import sql from '../../services/sql.js'
const utils = require('../../services/utils'); import utils from '../../services/utils.js'
const entityChangesService = require('../../services/entity_changes'); import entityChangesService from '../../services/entity_changes.js'
const treeService = require('../../services/tree'); import treeService from '../../services/tree.js'
const eraseService = require('../../services/erase'); import eraseService from '../../services/erase.js'
const becca = require('../../becca/becca'); import becca from '../../becca/becca.js'
const TaskContext = require('../../services/task_context'); import TaskContext from '../../services/task_context.js'
const branchService = require("../../services/branches"); import branchService from '../../services/branches.js'
const log = require("../../services/log"); import log from '../../services/log.js'
const ValidationError = require("../../errors/validation_error"); import ValidationError from '../../errors/validation_error.js'
const eventService = require("../../services/events.js"); import eventService from '../../services/events.js';
/** /**
* Code in this file deals with moving and cloning branches. The relationship between note and parent note is unique * Code in this file deals with moving and cloning branches. The relationship between note and parent note is unique
@ -223,7 +223,7 @@ function setPrefix(req) {
branch.save(); branch.save();
} }
module.exports = { export default {
moveBranchToParent, moveBranchToParent,
moveBranchBeforeNote, moveBranchBeforeNote,
moveBranchAfterNote, moveBranchAfterNote,

View File

@ -1,5 +1,5 @@
const becca = require("../../becca/becca"); import becca from '../../becca/becca.js'
const bulkActionService = require("../../services/bulk_actions"); import bulkActionService from '../../services/bulk_actions.js'
function execute(req) { function execute(req) {
const {noteIds, includeDescendants} = req.body; const {noteIds, includeDescendants} = req.body;
@ -42,7 +42,7 @@ function getAffectedNoteIds(noteIds, includeDescendants) {
return affectedNoteIds; return affectedNoteIds;
} }
module.exports = { export default {
execute, execute,
getAffectedNoteCount getAffectedNoteCount
}; };

View File

@ -1,19 +1,19 @@
"use strict"; "use strict";
const attributeService = require("../../services/attributes"); import attributeService from '../../services/attributes.js'
const cloneService = require("../../services/cloning"); import cloneService from '../../services/cloning.js'
const noteService = require('../../services/notes'); import noteService from '../../services/notes.js'
const dateNoteService = require('../../services/date_notes'); import dateNoteService from '../../services/date_notes.js'
const dateUtils = require('../../services/date_utils'); import dateUtils from '../../services/date_utils.js'
const imageService = require('../../services/image'); import imageService from '../../services/image.js'
const appInfo = require('../../services/app_info'); import appInfo from '../../services/app_info.js'
const ws = require('../../services/ws'); import ws from '../../services/ws.js'
const log = require('../../services/log'); import log from '../../services/log.js'
const utils = require('../../services/utils'); import utils from '../../services/utils.js'
const path = require('path'); import path from 'path';
const htmlSanitizer = require('../../services/html_sanitizer'); import htmlSanitizer from '../../services/html_sanitizer.js'
const {formatAttrForSearch} = require("../../services/attribute_formatter"); import { formatAttrForSearch } from '../../services/attribute_formatter.js';
const jsdom = require("jsdom"); import jsdom from 'jsdom';
const { JSDOM } = jsdom; const { JSDOM } = jsdom;
function addClipping(req) { function addClipping(req) {
@ -211,7 +211,7 @@ function findNotesByUrl(req){
} }
} }
module.exports = { export default {
createNote, createNote,
addClipping, addClipping,
openNote, openNote,

View File

@ -1,6 +1,6 @@
"use strict"; "use strict";
const cloningService = require('../../services/cloning'); import cloningService from '../../services/cloning.js'
function cloneNoteToBranch(req) { function cloneNoteToBranch(req) {
const {noteId, parentBranchId} = req.params; const {noteId, parentBranchId} = req.params;
@ -28,7 +28,7 @@ function toggleNoteInParent(req) {
return cloningService.toggleNoteInParent(present === 'true', noteId, parentNoteId); return cloningService.toggleNoteInParent(present === 'true', noteId, parentNoteId);
} }
module.exports = { export default {
cloneNoteToBranch, cloneNoteToBranch,
cloneNoteToParentNote, cloneNoteToParentNote,
cloneNoteAfter, cloneNoteAfter,

View File

@ -1,10 +1,10 @@
"use strict"; "use strict";
const sql = require('../../services/sql'); import sql from '../../services/sql.js'
const log = require('../../services/log'); import log from '../../services/log.js'
const backupService = require('../../services/backup'); import backupService from '../../services/backup.js'
const anonymizationService = require('../../services/anonymization'); import anonymizationService from '../../services/anonymization.js'
const consistencyChecksService = require('../../services/consistency_checks'); import consistencyChecksService from '../../services/consistency_checks.js'
function getExistingBackups() { function getExistingBackups() {
return backupService.getExistingBackups(); return backupService.getExistingBackups();
@ -44,7 +44,7 @@ function checkIntegrity() {
}; };
} }
module.exports = { export default {
getExistingBackups, getExistingBackups,
backupDatabase, backupDatabase,
vacuumDatabase, vacuumDatabase,

View File

@ -1,4 +1,4 @@
const etapiTokenService = require("../../services/etapi_tokens"); import etapiTokenService from '../../services/etapi_tokens.js'
function getTokens() { function getTokens() {
const tokens = etapiTokenService.getTokens(); const tokens = etapiTokenService.getTokens();
@ -20,7 +20,7 @@ function deleteToken(req) {
etapiTokenService.deleteToken(req.params.etapiTokenId); etapiTokenService.deleteToken(req.params.etapiTokenId);
} }
module.exports = { export default {
getTokens, getTokens,
createToken, createToken,
patchToken, patchToken,

View File

@ -1,12 +1,12 @@
"use strict"; "use strict";
const zipExportService = require('../../services/export/zip'); import zipExportService from '../../services/export/zip.js'
const singleExportService = require('../../services/export/single'); import singleExportService from '../../services/export/single.js'
const opmlExportService = require('../../services/export/opml'); import opmlExportService from '../../services/export/opml.js'
const becca = require('../../becca/becca'); import becca from '../../becca/becca.js'
const TaskContext = require("../../services/task_context"); import TaskContext from '../../services/task_context.js'
const log = require("../../services/log"); import log from '../../services/log.js'
const NotFoundError = require("../../errors/not_found_error"); import NotFoundError from '../../errors/not_found_error.js'
function exportBranch(req, res) { function exportBranch(req, res) {
const {branchId, type, format, version, taskId} = req.params; const {branchId, type, format, version, taskId} = req.params;
@ -50,6 +50,6 @@ function exportBranch(req, res) {
} }
} }
module.exports = { export default {
exportBranch exportBranch
}; };

View File

@ -1,16 +1,16 @@
"use strict"; "use strict";
const protectedSessionService = require('../../services/protected_session'); import protectedSessionService from '../../services/protected_session.js'
const utils = require('../../services/utils'); import utils from '../../services/utils.js'
const log = require('../../services/log'); import log from '../../services/log.js'
const noteService = require('../../services/notes'); import noteService from '../../services/notes.js'
const tmp = require('tmp'); import tmp from 'tmp';
const fs = require('fs'); import fs from 'fs';
const { Readable } = require('stream'); import { Readable } from 'stream';
const chokidar = require('chokidar'); import chokidar from 'chokidar';
const ws = require('../../services/ws'); import ws from '../../services/ws.js'
const becca = require("../../becca/becca"); import becca from '../../becca/becca.js'
const ValidationError = require("../../errors/validation_error"); import ValidationError from '../../errors/validation_error.js'
function updateFile(req) { function updateFile(req) {
const note = becca.getNoteOrThrow(req.params.noteId); const note = becca.getNoteOrThrow(req.params.noteId);
@ -217,7 +217,7 @@ function uploadModifiedFileToAttachment(req) {
attachment.setContent(fileContent); attachment.setContent(fileContent);
} }
module.exports = { export default {
updateFile, updateFile,
updateAttachment, updateAttachment,
openFile, openFile,

View File

@ -1,4 +1,4 @@
const optionService = require('../../services/options'); import optionService from '../../services/options.js'
function getFontCss(req, res) { function getFontCss(req, res) {
res.setHeader('Content-Type', 'text/css'); res.setHeader('Content-Type', 'text/css');
@ -34,6 +34,6 @@ function getFontCss(req, res) {
res.send(style); res.send(style);
} }
module.exports = { export default {
getFontCss getFontCss
}; };

View File

@ -1,9 +1,9 @@
"use strict"; "use strict";
const imageService = require('../../services/image'); import imageService from '../../services/image.js'
const becca = require('../../becca/becca'); import becca from '../../becca/becca.js'
const RESOURCE_DIR = require('../../services/resource_dir').RESOURCE_DIR; import resourceDir from '../../services/resource_dir.js';
const fs = require('fs'); import fs from 'fs';
function returnImageFromNote(req, res) { function returnImageFromNote(req, res) {
const image = becca.getNote(req.params.noteId); const image = becca.getNote(req.params.noteId);
@ -24,7 +24,7 @@ function returnImageFromRevision(req, res) {
function returnImageInt(image, res) { function returnImageInt(image, res) {
if (!image) { if (!image) {
res.set('Content-Type', 'image/png'); res.set('Content-Type', 'image/png');
return res.send(fs.readFileSync(`${RESOURCE_DIR}/db/image-deleted.png`)); return res.send(fs.readFileSync(`${resourceDir.RESOURCE_DIR}/db/image-deleted.png`));
} else if (!["image", "canvas", "mermaid"].includes(image.type)) { } else if (!["image", "canvas", "mermaid"].includes(image.type)) {
return res.sendStatus(400); return res.sendStatus(400);
} }
@ -67,7 +67,7 @@ function returnAttachedImage(req, res) {
if (!attachment) { if (!attachment) {
res.set('Content-Type', 'image/png'); res.set('Content-Type', 'image/png');
return res.send(fs.readFileSync(`${RESOURCE_DIR}/db/image-deleted.png`)); return res.send(fs.readFileSync(`${resourceDir.RESOURCE_DIR}/db/image-deleted.png`));
} }
if (!["image"].includes(attachment.role)) { if (!["image"].includes(attachment.role)) {
@ -99,7 +99,7 @@ function updateImage(req) {
return { uploaded: true }; return { uploaded: true };
} }
module.exports = { export default {
returnImageFromNote, returnImageFromNote,
returnImageFromRevision, returnImageFromRevision,
returnAttachedImage, returnAttachedImage,

View File

@ -1,16 +1,16 @@
"use strict"; "use strict";
const enexImportService = require('../../services/import/enex'); import enexImportService from '../../services/import/enex.js'
const opmlImportService = require('../../services/import/opml'); import opmlImportService from '../../services/import/opml.js'
const zipImportService = require('../../services/import/zip'); import zipImportService from '../../services/import/zip.js'
const singleImportService = require('../../services/import/single'); import singleImportService from '../../services/import/single.js'
const cls = require('../../services/cls'); import cls from '../../services/cls.js'
const path = require('path'); import path from 'path';
const becca = require('../../becca/becca'); import becca from '../../becca/becca.js'
const beccaLoader = require('../../becca/becca_loader'); import beccaLoader from '../../becca/becca_loader.js'
const log = require('../../services/log'); import log from '../../services/log.js'
const TaskContext = require('../../services/task_context'); import TaskContext from '../../services/task_context.js'
const ValidationError = require("../../errors/validation_error"); import ValidationError from '../../errors/validation_error.js'
async function importNotesToBranch(req) { async function importNotesToBranch(req) {
const {parentNoteId} = req.params; const {parentNoteId} = req.params;
@ -119,7 +119,7 @@ async function importAttachmentsToNote(req) {
} }
} }
module.exports = { export default {
importNotesToBranch, importNotesToBranch,
importAttachmentsToNote importAttachmentsToNote
}; };

View File

@ -1,7 +1,7 @@
"use strict"; "use strict";
const keyboardActions = require('../../services/keyboard_actions'); import keyboardActions from '../../services/keyboard_actions.js'
const becca = require('../../becca/becca'); import becca from '../../becca/becca.js'
function getKeyboardActions() { function getKeyboardActions() {
return keyboardActions.getKeyboardActions(); return keyboardActions.getKeyboardActions();
@ -14,7 +14,7 @@ function getShortcutsForNotes() {
return labels.filter(attr => becca.getNote(attr.noteId)?.type !== 'launcher'); return labels.filter(attr => becca.getNote(attr.noteId)?.type !== 'launcher');
} }
module.exports = { export default {
getKeyboardActions, getKeyboardActions,
getShortcutsForNotes getShortcutsForNotes
}; };

View File

@ -1,17 +1,17 @@
"use strict"; "use strict";
const options = require('../../services/options'); import options from '../../services/options.js'
const utils = require('../../services/utils'); import utils from '../../services/utils.js'
const dateUtils = require('../../services/date_utils'); import dateUtils from '../../services/date_utils.js'
const instanceId = require('../../services/instance_id'); import instanceId from '../../services/instance_id.js'
const passwordEncryptionService = require('../../services/encryption/password_encryption'); import passwordEncryptionService from '../../services/encryption/password_encryption.js'
const protectedSessionService = require('../../services/protected_session'); import protectedSessionService from '../../services/protected_session.js'
const appInfo = require('../../services/app_info'); import appInfo from '../../services/app_info.js'
const eventService = require('../../services/events'); import eventService from '../../services/events.js'
const sqlInit = require('../../services/sql_init'); import sqlInit from '../../services/sql_init.js'
const sql = require('../../services/sql'); import sql from '../../services/sql.js'
const ws = require("../../services/ws"); import ws from '../../services/ws.js'
const etapiTokenService = require("../../services/etapi_tokens"); import etapiTokenService from '../../services/etapi_tokens.js'
function loginSync(req) { function loginSync(req) {
if (!sqlInit.schemaExists()) { if (!sqlInit.schemaExists()) {
@ -102,7 +102,7 @@ function token(req) {
return { token: authToken }; return { token: authToken };
} }
module.exports = { export default {
loginSync, loginSync,
loginToProtectedSession, loginToProtectedSession,
logoutFromProtectedSession, logoutFromProtectedSession,

View File

@ -1,7 +1,7 @@
"use strict"; "use strict";
const becca = require("../../becca/becca"); import becca from '../../becca/becca.js'
const { JSDOM } = require("jsdom"); import { JSDOM } from 'jsdom';
function buildDescendantCountMap(noteIdsToCount) { function buildDescendantCountMap(noteIdsToCount) {
if (!Array.isArray(noteIdsToCount)) { if (!Array.isArray(noteIdsToCount)) {
@ -379,7 +379,7 @@ function getBacklinks(req) {
}); });
} }
module.exports = { export default {
getLinkMap, getLinkMap,
getTreeMap, getTreeMap,
getBacklinkCount, getBacklinkCount,

View File

@ -1,15 +1,15 @@
"use strict"; "use strict";
const noteService = require('../../services/notes'); import noteService from '../../services/notes.js'
const eraseService = require('../../services/erase'); import eraseService from '../../services/erase.js'
const treeService = require('../../services/tree'); import treeService from '../../services/tree.js'
const sql = require('../../services/sql'); import sql from '../../services/sql.js'
const utils = require('../../services/utils'); import utils from '../../services/utils.js'
const log = require('../../services/log'); import log from '../../services/log.js'
const TaskContext = require('../../services/task_context'); import TaskContext from '../../services/task_context.js'
const becca = require("../../becca/becca"); import becca from '../../becca/becca.js'
const ValidationError = require("../../errors/validation_error"); import ValidationError from '../../errors/validation_error.js'
const blobService = require("../../services/blob"); import blobService from '../../services/blob.js'
function getNote(req) { function getNote(req) {
return becca.getNoteOrThrow(req.params.noteId); return becca.getNoteOrThrow(req.params.noteId);
@ -236,7 +236,7 @@ function convertNoteToAttachment(req) {
}; };
} }
module.exports = { export default {
getNote, getNote,
getNoteBlob, getNoteBlob,
getNoteMetadata, getNoteMetadata,

View File

@ -1,9 +1,9 @@
"use strict"; "use strict";
const optionService = require('../../services/options'); import optionService from '../../services/options.js'
const log = require('../../services/log'); import log from '../../services/log.js'
const searchService = require('../../services/search/services/search'); import searchService from '../../services/search/services/search.js'
const ValidationError = require("../../errors/validation_error"); import ValidationError from '../../errors/validation_error.js'
// options allowed to be updated directly in the Options dialog // options allowed to be updated directly in the Options dialog
const ALLOWED_OPTIONS = new Set([ const ALLOWED_OPTIONS = new Set([
@ -135,7 +135,7 @@ function isAllowed(name) {
|| name.startsWith("hideArchivedNotes"); || name.startsWith("hideArchivedNotes");
} }
module.exports = { export default {
getOptions, getOptions,
updateOption, updateOption,
updateOptions, updateOptions,

View File

@ -1,5 +1,5 @@
const becca = require("../../becca/becca"); import becca from '../../becca/becca.js'
const markdownService = require("../../services/import/markdown"); import markdownService from '../../services/import/markdown.js'
function getIconUsage() { function getIconUsage() {
const iconClassToCountMap = {}; const iconClassToCountMap = {};
@ -33,7 +33,7 @@ function renderMarkdown(req) {
}; };
} }
module.exports = { export default {
getIconUsage, getIconUsage,
renderMarkdown renderMarkdown
}; };

View File

@ -1,7 +1,7 @@
"use strict"; "use strict";
const passwordService = require('../../services/encryption/password'); import passwordService from '../../services/encryption/password.js'
const ValidationError = require("../../errors/validation_error"); import ValidationError from '../../errors/validation_error.js'
function changePassword(req) { function changePassword(req) {
if (passwordService.isPasswordSet()) { if (passwordService.isPasswordSet()) {
@ -21,7 +21,7 @@ function resetPassword(req) {
return passwordService.resetPassword(); return passwordService.resetPassword();
} }
module.exports = { export default {
changePassword, changePassword,
resetPassword resetPassword
}; };

View File

@ -1,9 +1,9 @@
"use strict"; "use strict";
const sql = require('../../services/sql'); import sql from '../../services/sql.js'
const protectedSessionService = require('../../services/protected_session'); import protectedSessionService from '../../services/protected_session.js'
const noteService = require('../../services/notes'); import noteService from '../../services/notes.js'
const becca = require("../../becca/becca"); import becca from '../../becca/becca.js'
function getRecentChanges(req) { function getRecentChanges(req) {
const {ancestorNoteId} = req.params; const {ancestorNoteId} = req.params;
@ -97,6 +97,6 @@ function getRecentChanges(req) {
return recentChanges; return recentChanges;
} }
module.exports = { export default {
getRecentChanges getRecentChanges
}; };

View File

@ -1,8 +1,8 @@
"use strict"; "use strict";
const BRecentNote = require('../../becca/entities/brecent_note'); import BRecentNote from '../../becca/entities/brecent_note.js'
const sql = require('../../services/sql'); import sql from '../../services/sql.js'
const dateUtils = require('../../services/date_utils'); import dateUtils from '../../services/date_utils.js'
function addRecentNote(req) { function addRecentNote(req) {
new BRecentNote({ new BRecentNote({
@ -18,6 +18,6 @@ function addRecentNote(req) {
} }
} }
module.exports = { export default {
addRecentNote addRecentNote
}; };

View File

@ -1,5 +1,5 @@
const becca = require("../../becca/becca"); import becca from '../../becca/becca.js'
const sql = require("../../services/sql"); import sql from '../../services/sql.js'
function getRelationMap(req) { function getRelationMap(req) {
const {relationMapNoteId, noteIds} = req.body; const {relationMapNoteId, noteIds} = req.body;
@ -64,6 +64,6 @@ function getRelationMap(req) {
return resp; return resp;
} }
module.exports = { export default {
getRelationMap getRelationMap
}; };

View File

@ -1,13 +1,13 @@
"use strict"; "use strict";
const beccaService = require('../../becca/becca_service'); import beccaService from '../../becca/becca_service.js'
const revisionService = require('../../services/revisions'); import revisionService from '../../services/revisions.js'
const utils = require('../../services/utils'); import utils from '../../services/utils.js'
const sql = require('../../services/sql'); import sql from '../../services/sql.js'
const cls = require('../../services/cls'); import cls from '../../services/cls.js'
const path = require('path'); import path from 'path';
const becca = require("../../becca/becca"); import becca from '../../becca/becca.js'
const blobService = require("../../services/blob"); import blobService from '../../services/blob.js'
function getRevisionBlob(req) { function getRevisionBlob(req) {
const preview = req.query.preview === 'true'; const preview = req.query.preview === 'true';
@ -185,7 +185,7 @@ function getNotePathData(note) {
} }
} }
module.exports = { export default {
getRevisionBlob, getRevisionBlob,
getRevisions, getRevisions,
getRevision, getRevision,

View File

@ -1,10 +1,10 @@
"use strict"; "use strict";
const scriptService = require('../../services/script'); import scriptService from '../../services/script.js'
const attributeService = require('../../services/attributes'); import attributeService from '../../services/attributes.js'
const becca = require('../../becca/becca'); import becca from '../../becca/becca.js'
const syncService = require('../../services/sync'); import syncService from '../../services/sync.js'
const sql = require('../../services/sql'); import sql from '../../services/sql.js'
// The async/await here is very confusing, because the body.script may, but may not be async. If it is async, then we // The async/await here is very confusing, because the body.script may, but may not be async. If it is async, then we
// need to await it and make the complete response including metadata available in a Promise, so that the route detects // need to await it and make the complete response including metadata available in a Promise, so that the route detects
@ -120,7 +120,7 @@ function getBundle(req) {
return scriptService.getScriptBundleForFrontend(note, script, params); return scriptService.getScriptBundleForFrontend(note, script, params);
} }
module.exports = { export default {
exec, exec,
run, run,
getStartupBundles, getStartupBundles,

View File

@ -1,12 +1,12 @@
"use strict"; "use strict";
const becca = require('../../becca/becca'); import becca from '../../becca/becca.js'
const SearchContext = require('../../services/search/search_context'); import SearchContext from '../../services/search/search_context.js'
const searchService = require('../../services/search/services/search'); import searchService from '../../services/search/services/search.js'
const bulkActionService = require("../../services/bulk_actions"); import bulkActionService from '../../services/bulk_actions.js'
const cls = require("../../services/cls"); import cls from '../../services/cls.js'
const {formatAttrForSearch} = require("../../services/attribute_formatter"); import { formatAttrForSearch } from '../../services/attribute_formatter.js';
const ValidationError = require("../../errors/validation_error"); import ValidationError from '../../errors/validation_error.js'
function searchFromNote(req) { function searchFromNote(req) {
const note = becca.getNoteOrThrow(req.params.noteId); const note = becca.getNoteOrThrow(req.params.noteId);
@ -123,7 +123,7 @@ function searchTemplates() {
}).map(note => note.noteId); }).map(note => note.noteId);
} }
module.exports = { export default {
searchFromNote, searchFromNote,
searchAndExecute, searchAndExecute,
getRelatedNotes, getRelatedNotes,

View File

@ -1,10 +1,10 @@
"use strict"; "use strict";
const imageType = require('image-type'); import imageType from 'image-type';
const imageService = require('../../services/image'); import imageService from '../../services/image.js'
const noteService = require('../../services/notes'); import noteService from '../../services/notes.js'
const {sanitizeAttributeName} = require("../../services/sanitize_attribute_name"); import { sanitizeAttributeName } from '../../services/sanitize_attribute_name.js';
const specialNotesService = require("../../services/special_notes"); import specialNotesService from '../../services/special_notes.js'
function uploadImage(req) { function uploadImage(req) {
const file = req.file; const file = req.file;
@ -60,7 +60,7 @@ function saveNote(req) {
}; };
} }
module.exports = { export default {
uploadImage, uploadImage,
saveNote saveNote
}; };

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