Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
common JS module system prototype
azivner7a865a90813e
diff --git a/src/public/javascripts/note_editor.js b/src/public/javascripts/note_editor.jsindex 98bc9aa84d..eca919fb7e 100644--- a/src/public/javascripts/note_editor.js+++ b/src/public/javascripts/note_editor.js@@ -217,7 +217,7 @@ const noteEditor = (function() {if (currentNote.detail.type === 'render') {$noteDetailRender.show();- const subTree = await server.get('script/subtree/' + getCurrentNoteId());+ const subTree = await server.get('script/render/' + getCurrentNoteId());$noteDetailRender.html(subTree);}diff --git a/src/routes/api/script.js b/src/routes/api/script.jsindex 3d88d2c700..4306e3626e 100644--- a/src/routes/api/script.js+++ b/src/routes/api/script.js@@ -44,4 +44,11 @@ router.get('/subtree/:noteId', auth.checkApiAuth, wrap(async (req, res, next) =>res.send(await script.getNoteScript(note, repository));}));+router.get('/render/:noteId', auth.checkApiAuth, wrap(async (req, res, next) => {+ const repository = new Repository(req);+ const note = await repository.getNote(req.params.noteId);++ res.send(await script.getRenderScript(note, repository));+}));+module.exports = router;\ No newline at end of filediff --git a/src/services/scheduler.js b/src/services/scheduler.jsindex 0485013071..b256615eb8 100644--- a/src/services/scheduler.js+++ b/src/services/scheduler.js@@ -19,7 +19,7 @@ async function runNotesWithAttribute(runAttrValue) {}}-setTimeout(() => runNotesWithAttribute('backend_startup'), 10 * 1000);+setTimeout(() => runNotesWithAttribute('backend_startup'), 1 * 1000);setInterval(() => runNotesWithAttribute('hourly'), 3600 * 1000);diff --git a/src/services/script.js b/src/services/script.jsindex 6bbb44263a..a403b0a8dc 100644--- a/src/services/script.js+++ b/src/services/script.js@@ -7,9 +7,20 @@ async function executeNote(note) {}const manualTransactionHandling = (await note.getAttributeMap()).manual_transaction_handling !== undefined;- const noteScript = await getNoteScript(note);- return await executeJob(noteScript, [], manualTransactionHandling);+ const modules = await getModules([note], []);++ // last \r\n is necessary if script contains line comment on its last line+ const script = "async function() {\r\n" + modules.script + "\r\n}";++ const ctx = new ScriptContext(null, note, module.allModules);++ if (manualTransactionHandling) {+ return await execute(ctx, script, '');+ }+ else {+ return await sql.doInTransaction(async () => execute(ctx, script, ''));+ }}async function executeScript(dataKey, script, params) {@@ -20,7 +31,9 @@ async function executeScript(dataKey, script, params) {}async function execute(ctx, script, paramsStr) {- return await (function() { return eval(`const api = this; (${script})(${paramsStr})`); }.call(ctx));+ console.log(`const api = this; (${script})(${paramsStr})`);++ return await (function() { return eval(`const api = this;\r\n(${script})(${paramsStr})`); }.call(ctx));}const timeouts = {};@@ -83,38 +96,64 @@ function getParams(params) {}).join(",");}-async function getNoteScript(note) {- const subTreeScripts = await getSubTreeScripts(note, [note.noteId]);+async function getRenderScript(note) {+ const subTreeScripts = await getModules(note, [note.noteId]);// last \r\n is necessary if script contains line comment on its last linereturn "async function() {" + subTreeScripts + note.content + "\r\n}";}+async function getNoteScript(note) {++}+/*** @param includedNoteIds - if multiple child note scripts reference same dependency (child note),* it will be included just once*/-async function getSubTreeScripts(parent, includedNoteIds) {- let script = "\r\n";+async function getModules(children, includedNoteIds) {+ const modules = [];+ let allModules = [];+ let script = '';++ for (const child of children) {+ if (!child.isJavaScript()) {+ continue;+ }++ modules.push(child);- for (const child of await parent.getChildren()) {- if (!child.isJavaScript() || includedNoteIds.includes(child.noteId)) {+ if (includedNoteIds.includes(child.noteId)) {continue;}includedNoteIds.push(child.noteId);- script += await getSubTreeScripts(child.noteId, includedNoteIds);+ const children = await getModules(await child.getChildren(), includedNoteIds);++ allModules = allModules.concat(children.allModules);- script += child.content + "\r\n";+ script += children.script;++ script += `+api.__modules['${child.noteId}'] = {};+await (async function(module, api, startNote, currentNote` + (children.modules.length > 0 ? ', ' : '') ++ children.modules.map(child => child.title).join(', ') + `) {+${child.content}+})(api.__modules['${child.noteId}'], api, api.__startNote, api.__notes['${child.noteId}']` + (children.modules.length > 0 ? ', ' : '') ++ children.modules.map(child => `api.__modules['${child.noteId}'].exports`).join(', ') + `);+`;}- return script;+ allModules = allModules.concat(modules);++ return { script, modules, allModules };}module.exports = {executeNote,executeScript,setJob,- getNoteScript+ getNoteScript,+ getRenderScript};\ No newline at end of filediff --git a/src/services/script_context.js b/src/services/script_context.jsindex 8a5ddcc071..5305c0e976 100644--- a/src/services/script_context.js+++ b/src/services/script_context.js@@ -9,12 +9,21 @@ const config = require('./config');const Repository = require('./repository');const axios = require('axios');-function ScriptContext(dataKey) {+function ScriptContext(dataKey, note, allNotes) {dataKey = protected_session.getDataKey(dataKey);const repository = new Repository(dataKey);this.axios = axios;+ this.__startNote = note;+ this.__notes = {};++ if (allNotes) {+ allNotes.forEach(note => this.__notes[note.noteId] = note);+ }++ this.__modules = {};+this.utils = {unescapeHtml: utils.unescapeHtml,isoDateTimeStr: utils.dateStr