changes in access to startNote and currentNote

This commit is contained in:
azivner 2018-03-06 23:04:35 -05:00
parent 6d0218cb36
commit 766a567a32
8 changed files with 74 additions and 42 deletions

View File

@ -1,4 +1,12 @@
function Api(startNote, allNotes) { function ApiContext(startNote, allNotes) {
return {
modules: {},
notes: toObject(allNotes, note => [note.noteId, note]),
apis: toObject(allNotes, note => [note.noteId, Api(startNote, note)]),
};
}
function Api(startNote, currentNote) {
const $pluginButtons = $("#plugin-buttons"); const $pluginButtons = $("#plugin-buttons");
async function activateNote(notePath) { async function activateNote(notePath) {
@ -28,7 +36,7 @@ function Api(startNote, allNotes) {
}); });
} }
async function runOnServer(script, params) { async function runOnServer(script, params = []) {
if (typeof script === "function") { if (typeof script === "function") {
script = script.toString(); script = script.toString();
} }
@ -36,16 +44,16 @@ function Api(startNote, allNotes) {
const ret = await server.post('script/exec', { const ret = await server.post('script/exec', {
script: script, script: script,
params: prepareParams(params), params: prepareParams(params),
startNoteId: startNote.noteId startNoteId: startNote.noteId,
currentNoteId: currentNote.noteId
}); });
return ret.executionResult; return ret.executionResult;
} }
return { return {
__startNote: startNote, startNote: startNote,
__notes: toObject(allNotes, note => [note.noteId, note]), currentNote: currentNote,
__modules: {},
addButtonToToolbar, addButtonToToolbar,
activateNote, activateNote,
getInstanceName: noteTree.getInstanceName, getInstanceName: noteTree.getInstanceName,

View File

@ -201,9 +201,9 @@ window.onerror = function (msg, url, lineNo, columnNo, error) {
$("#logout-button").toggle(!isElectron()); $("#logout-button").toggle(!isElectron());
$(document).ready(() => { $(document).ready(() => {
server.get("script/startup").then(scripts => { server.get("script/startup").then(scriptBundles => {
for (const script of scripts) { for (const bundle of scriptBundles) {
executeBundle(script); executeBundle(bundle);
} }
}); });
}); });

View File

@ -299,7 +299,7 @@ const noteEditor = (function() {
await saveNoteIfChanged(); await saveNoteIfChanged();
if (currentNote.detail.mime.endsWith("env=frontend")) { if (currentNote.detail.mime.endsWith("env=frontend")) {
const bundle = await server.get('script/subtree/' + getCurrentNoteId()); const bundle = await server.get('script/bundle/' + getCurrentNoteId());
executeBundle(bundle); executeBundle(bundle);
} }

View File

@ -116,9 +116,11 @@ async function stopWatch(what, func) {
} }
async function executeBundle(bundle) { async function executeBundle(bundle) {
const api = Api(bundle.note, bundle.allNotes); const apiContext = ApiContext(bundle.note, bundle.allNotes);
return await (function() { return eval(`const api = this; (async function() { ${bundle.script}\r\n})()`); }.call(api)); console.log((`const apiContext = this; (async function() { ${bundle.script}\r\n})()`));
return await (function() { return eval(`const apiContext = this; (async function() { ${bundle.script}\r\n})()`); }.call(apiContext));
} }
function formatValueWithWhitespace(val) { function formatValueWithWhitespace(val) {

View File

@ -9,7 +9,7 @@ const script = require('../../services/script');
const Repository = require('../../services/repository'); const Repository = require('../../services/repository');
router.post('/exec', auth.checkApiAuth, wrap(async (req, res, next) => { router.post('/exec', auth.checkApiAuth, wrap(async (req, res, next) => {
const ret = await script.executeScript(req, req.body.script, req.body.params, req.body.startNoteId); const ret = await script.executeScript(req, req.body.script, req.body.params, req.body.startNoteId, req.body.currentNoteId);
res.send({ res.send({
executionResult: ret executionResult: ret
@ -20,7 +20,7 @@ router.post('/run/:noteId', auth.checkApiAuth, wrap(async (req, res, next) => {
const repository = new Repository(req); const repository = new Repository(req);
const note = await repository.getNote(req.params.noteId); const note = await repository.getNote(req.params.noteId);
const ret = await script.executeNote(note); const ret = await script.executeNote(req, note);
res.send({ res.send({
executionResult: ret executionResult: ret
@ -42,7 +42,7 @@ router.get('/startup', auth.checkApiAuth, wrap(async (req, res, next) => {
res.send(scripts); res.send(scripts);
})); }));
router.get('/subtree/:noteId', auth.checkApiAuth, wrap(async (req, res, next) => { router.get('/bundle/:noteId', auth.checkApiAuth, wrap(async (req, res, next) => {
const repository = new Repository(req); const repository = new Repository(req);
const note = await repository.getNote(req.params.noteId); const note = await repository.getNote(req.params.noteId);
const bundle = await script.getScriptBundle(note); const bundle = await script.getScriptBundle(note);

View File

@ -15,7 +15,7 @@ async function runNotesWithAttribute(runAttrValue) {
AND notes.isDeleted = 0`, [runAttrValue]); AND notes.isDeleted = 0`, [runAttrValue]);
for (const note of notes) { for (const note of notes) {
script.executeNote(note); script.executeNote(null, note);
} }
} }

View File

@ -2,21 +2,28 @@ const sql = require('./sql');
const ScriptContext = require('./script_context'); const ScriptContext = require('./script_context');
const Repository = require('./repository'); const Repository = require('./repository');
async function executeNote(note) { async function executeNote(dataKey, note) {
if (note.isProtected || !note.isJavaScript()) { if (!note.isJavaScript()) {
return; return;
} }
const manualTransactionHandling = (await note.getAttributeMap()).manual_transaction_handling !== undefined;
const bundle = await getScriptBundle(note); const bundle = await getScriptBundle(note);
await executeBundle(dataKey, bundle);
}
async function executeBundle(dataKey, bundle, startNote) {
if (!startNote) {
// this is the default case, the only exception is when we want to preserve frontend startNote
startNote = bundle.note;
}
// last \r\n is necessary if script contains line comment on its last line // last \r\n is necessary if script contains line comment on its last line
const script = "async function() {\r\n" + bundle.script + "\r\n}"; const script = "async function() {\r\n" + bundle.script + "\r\n}";
const ctx = new ScriptContext(null, note, bundle.allNotes); const ctx = new ScriptContext(dataKey, startNote, bundle.allNotes);
if (manualTransactionHandling) { if (await bundle.note.hasAttribute('manual_transaction_handling')) {
return await execute(ctx, script, ''); return await execute(ctx, script, '');
} }
else { else {
@ -24,18 +31,25 @@ async function executeNote(note) {
} }
} }
async function executeScript(dataKey, script, params, startNoteId) { /**
* This method preserves frontend startNode - that's why we start execution from currentNote and override
* bundle's startNote.
*/
async function executeScript(dataKey, script, params, startNoteId, currentNoteId) {
const repository = new Repository(dataKey); const repository = new Repository(dataKey);
const startNote = await repository.getNote(startNoteId); const startNote = await repository.getNote(startNoteId);
const currentNote = await repository.getNote(currentNoteId);
const ctx = new ScriptContext(dataKey, startNote, []); currentNote.content = `(${script}\r\n)(${getParams(params)})`;
const paramsStr = getParams(params); currentNote.mime = 'application/javascript;env=backend';
return await sql.doInTransaction(async () => execute(ctx, script, paramsStr)); const bundle = await getScriptBundle(currentNote);
return await executeBundle(dataKey, bundle, startNote);
} }
async function execute(ctx, script, paramsStr) { async function execute(ctx, script, paramsStr) {
return await (function() { return eval(`const api = this;const startNote = api.__startNote;\r\n(${script}\r\n)(${paramsStr})`); }.call(ctx)); return await (function() { return eval(`const apiContext = this;\r\n(${script}\r\n)(${paramsStr})`); }.call(ctx));
} }
function getParams(params) { function getParams(params) {
@ -73,6 +87,10 @@ async function getScriptBundle(note, scriptEnv, includedNoteIds = []) {
scriptEnv = note.getScriptEnv(); scriptEnv = note.getScriptEnv();
} }
if (note.type !== 'file' && scriptEnv !== note.getScriptEnv()) {
return;
}
const bundle = { const bundle = {
note: note, note: note,
script: '', script: '',
@ -86,12 +104,6 @@ async function getScriptBundle(note, scriptEnv, includedNoteIds = []) {
includedNoteIds.push(note.noteId); includedNoteIds.push(note.noteId);
bundle.script = `api.__modules['${note.noteId}'] = { __noteId: '${note.noteId}', __env: '${note.getScriptEnv()}'};`;
if (note.type !== 'file' && scriptEnv !== note.getScriptEnv()) {
return bundle;
}
const modules = []; const modules = [];
for (const child of await note.getChildren()) { for (const child of await note.getChildren()) {
@ -107,11 +119,12 @@ async function getScriptBundle(note, scriptEnv, includedNoteIds = []) {
if (note.isJavaScript()) { if (note.isJavaScript()) {
bundle.script += ` bundle.script += `
await (async function(exports, module, api, startNote, currentNote` + (modules.length > 0 ? ', ' : '') + apiContext.modules['${note.noteId}'] = {};
modules.map(child => child.title).join(', ') + `) { await (async function(exports, module, api` + (modules.length > 0 ? ', ' : '') +
modules.map(child => sanitizeVariableName(child.title)).join(', ') + `) {
${note.content} ${note.content}
})({}, api.__modules['${note.noteId}'], api, api.__startNote, api.__notes['${note.noteId}']` + (modules.length > 0 ? ', ' : '') + })({}, apiContext.modules['${note.noteId}'], apiContext.apis['${note.noteId}']` + (modules.length > 0 ? ', ' : '') +
modules.map(mod => `api.__modules['${mod.noteId}'].exports`).join(', ') + `); modules.map(mod => `apiContext.modules['${mod.noteId}'].exports`).join(', ') + `);
`; `;
} }
else if (note.isHtml()) { else if (note.isHtml()) {
@ -121,6 +134,10 @@ ${note.content}
return bundle; return bundle;
} }
function sanitizeVariableName(str) {
return str.replace(/[^a-z0-9_]/gim, "");
}
module.exports = { module.exports = {
executeNote, executeNote,
executeScript, executeScript,

View File

@ -11,11 +11,16 @@ const axios = require('axios');
function ScriptContext(dataKey, startNote, allNotes) { function ScriptContext(dataKey, startNote, allNotes) {
dataKey = protected_session.getDataKey(dataKey); dataKey = protected_session.getDataKey(dataKey);
const repository = new Repository(dataKey);
this.__startNote = startNote; this.modules = {};
this.__notes = utils.toObject(allNotes, note => [note.noteId, note]); this.notes = utils.toObject(allNotes, note => [note.noteId, note]);
this.__modules = {}; this.apis = utils.toObject(allNotes, note => [note.noteId, new ScriptApi(dataKey, startNote, note)]);
}
function ScriptApi(dataKey, startNote, currentNote) {
const repository = new Repository(dataKey);
this.startNote = startNote;
this.currentNote = currentNote;
this.axios = axios; this.axios = axios;
@ -50,7 +55,7 @@ function ScriptContext(dataKey, startNote, allNotes) {
this.updateEntity = repository.updateEntity; this.updateEntity = repository.updateEntity;
this.log = message => log.info(`Script: ${message}`); this.log = message => log.info(`Script ${currentNote.noteId}: ${message}`);
this.getRootCalendarNoteId = date_notes.getRootCalendarNoteId; this.getRootCalendarNoteId = date_notes.getRootCalendarNoteId;
this.getDateNoteId = date_notes.getDateNoteId; this.getDateNoteId = date_notes.getDateNoteId;