services_backend_script_api.js.html 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <title>JSDoc: Source: services/backend_script_api.js</title>
  6. <script src="scripts/prettify/prettify.js"> </script>
  7. <script src="scripts/prettify/lang-css.js"> </script>
  8. <!--[if lt IE 9]>
  9. <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
  10. <![endif]-->
  11. <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
  12. <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">
  13. </head>
  14. <body>
  15. <div id="main">
  16. <h1 class="page-title">Source: services/backend_script_api.js</h1>
  17. <section>
  18. <article>
  19. <pre class="prettyprint source linenums"><code>const log = require('./log');
  20. const noteService = require('./notes');
  21. const sql = require('./sql');
  22. const utils = require('./utils');
  23. const attributeService = require('./attributes');
  24. const dateNoteService = require('./date_notes');
  25. const treeService = require('./tree');
  26. const config = require('./config');
  27. const axios = require('axios');
  28. const dayjs = require('dayjs');
  29. const xml2js = require('xml2js');
  30. const cloningService = require('./cloning');
  31. const appInfo = require('./app_info');
  32. const searchService = require('./search/services/search');
  33. const SearchContext = require("./search/search_context");
  34. const becca = require("../becca/becca");
  35. const ws = require("./ws");
  36. const SpacedUpdate = require("./spaced_update");
  37. const specialNotesService = require("./special_notes");
  38. const branchService = require("./branches");
  39. const exportService = require("./export/zip");
  40. const syncMutex = require("./sync_mutex");
  41. const backupService = require("./backup");
  42. const optionsService = require("./options");
  43. /**
  44. * A whole number
  45. * @typedef {number} int
  46. */
  47. /**
  48. * An instance of the frontend api available globally.
  49. * @global
  50. * @var {BackendScriptApi} api
  51. */
  52. /**
  53. * &lt;p>This is the main backend API interface for scripts. All the properties and methods are published in the "api" object
  54. * available in the JS backend notes. You can use e.g. &lt;code>api.log(api.startNote.title);&lt;/code>&lt;/p>
  55. *
  56. * @constructor
  57. */
  58. function BackendScriptApi(currentNote, apiParams) {
  59. /**
  60. * Note where the script started executing
  61. * @type {BNote}
  62. */
  63. this.startNote = apiParams.startNote;
  64. /**
  65. * Note where the script is currently executing. Don't mix this up with the concept of active note
  66. * @type {BNote}
  67. */
  68. this.currentNote = currentNote;
  69. /**
  70. * Entity whose event triggered this execution
  71. * @type {AbstractBeccaEntity}
  72. */
  73. this.originEntity = apiParams.originEntity;
  74. for (const key in apiParams) {
  75. this[key] = apiParams[key];
  76. }
  77. /**
  78. * Axios library for HTTP requests. See {@link https://axios-http.com} for documentation
  79. * @type {axios}
  80. * @deprecated use native (browser compatible) fetch() instead
  81. */
  82. this.axios = axios;
  83. /**
  84. * day.js library for date manipulation. See {@link https://day.js.org} for documentation
  85. * @type {dayjs}
  86. */
  87. this.dayjs = dayjs;
  88. /**
  89. * xml2js library for XML parsing. See {@link https://github.com/Leonidas-from-XIV/node-xml2js} for documentation
  90. * @type {xml2js}
  91. */
  92. this.xml2js = xml2js;
  93. /**
  94. * Instance name identifies particular Trilium instance. It can be useful for scripts
  95. * if some action needs to happen on only one specific instance.
  96. *
  97. * @returns {string|null}
  98. */
  99. this.getInstanceName = () => config.General ? config.General.instanceName : null;
  100. /**
  101. * @method
  102. * @param {string} noteId
  103. * @returns {BNote|null}
  104. */
  105. this.getNote = noteId => becca.getNote(noteId);
  106. /**
  107. * @method
  108. * @param {string} branchId
  109. * @returns {BBranch|null}
  110. */
  111. this.getBranch = branchId => becca.getBranch(branchId);
  112. /**
  113. * @method
  114. * @param {string} attributeId
  115. * @returns {BAttribute|null}
  116. */
  117. this.getAttribute = attributeId => becca.getAttribute(attributeId);
  118. /**
  119. * @method
  120. * @param {string} attachmentId
  121. * @returns {BAttachment|null}
  122. */
  123. this.getAttachment = attachmentId => becca.getAttachment(attachmentId);
  124. /**
  125. * @method
  126. * @param {string} revisionId
  127. * @returns {BRevision|null}
  128. */
  129. this.getRevision = revisionId => becca.getRevision(revisionId);
  130. /**
  131. * @method
  132. * @param {string} etapiTokenId
  133. * @returns {BEtapiToken|null}
  134. */
  135. this.getEtapiToken = etapiTokenId => becca.getEtapiToken(etapiTokenId);
  136. /**
  137. * @method
  138. * @returns {BEtapiToken[]}
  139. */
  140. this.getEtapiTokens = () => becca.getEtapiTokens();
  141. /**
  142. * @method
  143. * @param {string} optionName
  144. * @returns {BOption|null}
  145. */
  146. this.getOption = optionName => becca.getOption(optionName);
  147. /**
  148. * @method
  149. * @returns {BOption[]}
  150. */
  151. this.getOptions = () => optionsService.getOptions();
  152. /**
  153. * @method
  154. * @param {string} attributeId
  155. * @returns {BAttribute|null}
  156. */
  157. this.getAttribute = attributeId => becca.getAttribute(attributeId);
  158. /**
  159. * This is a powerful search method - you can search by attributes and their values, e.g.:
  160. * "#dateModified =* MONTH AND #log". See {@link https://github.com/zadam/trilium/wiki/Search} for full documentation for all options
  161. *
  162. * @method
  163. * @param {string} query
  164. * @param {Object} [searchParams]
  165. * @returns {BNote[]}
  166. */
  167. this.searchForNotes = (query, searchParams = {}) => {
  168. if (searchParams.includeArchivedNotes === undefined) {
  169. searchParams.includeArchivedNotes = true;
  170. }
  171. if (searchParams.ignoreHoistedNote === undefined) {
  172. searchParams.ignoreHoistedNote = true;
  173. }
  174. const noteIds = searchService.findResultsWithQuery(query, new SearchContext(searchParams))
  175. .map(sr => sr.noteId);
  176. return becca.getNotes(noteIds);
  177. };
  178. /**
  179. * This is a powerful search method - you can search by attributes and their values, e.g.:
  180. * "#dateModified =* MONTH AND #log". See {@link https://github.com/zadam/trilium/wiki/Search} for full documentation for all options
  181. *
  182. * @method
  183. * @param {string} query
  184. * @param {Object} [searchParams]
  185. * @returns {BNote|null}
  186. */
  187. this.searchForNote = (query, searchParams = {}) => {
  188. const notes = this.searchForNotes(query, searchParams);
  189. return notes.length > 0 ? notes[0] : null;
  190. };
  191. /**
  192. * Retrieves notes with given label name &amp; value
  193. *
  194. * @method
  195. * @param {string} name - attribute name
  196. * @param {string} [value] - attribute value
  197. * @returns {BNote[]}
  198. */
  199. this.getNotesWithLabel = attributeService.getNotesWithLabel;
  200. /**
  201. * Retrieves first note with given label name &amp; value
  202. *
  203. * @method
  204. * @param {string} name - attribute name
  205. * @param {string} [value] - attribute value
  206. * @returns {BNote|null}
  207. */
  208. this.getNoteWithLabel = attributeService.getNoteWithLabel;
  209. /**
  210. * If there's no branch between note and parent note, create one. Otherwise, do nothing. Returns the new or existing branch.
  211. *
  212. * @method
  213. * @param {string} noteId
  214. * @param {string} parentNoteId
  215. * @param {string} prefix - if branch is created between note and parent note, set this prefix
  216. * @returns {{branch: BBranch|null}}
  217. */
  218. this.ensureNoteIsPresentInParent = cloningService.ensureNoteIsPresentInParent;
  219. /**
  220. * If there's a branch between note and parent note, remove it. Otherwise, do nothing.
  221. *
  222. * @method
  223. * @param {string} noteId
  224. * @param {string} parentNoteId
  225. * @returns {void}
  226. */
  227. this.ensureNoteIsAbsentFromParent = cloningService.ensureNoteIsAbsentFromParent;
  228. /**
  229. * Based on the value, either create or remove branch between note and parent note.
  230. *
  231. * @method
  232. * @param {boolean} present - true if we want the branch to exist, false if we want it gone
  233. * @param {string} noteId
  234. * @param {string} parentNoteId
  235. * @param {string} prefix - if branch is created between note and parent note, set this prefix
  236. * @returns {void}
  237. */
  238. this.toggleNoteInParent = cloningService.toggleNoteInParent;
  239. /**
  240. * Create text note. See also createNewNote() for more options.
  241. *
  242. * @method
  243. * @param {string} parentNoteId
  244. * @param {string} title
  245. * @param {string} content
  246. * @returns {{note: BNote, branch: BBranch}} - object having "note" and "branch" keys representing respective objects
  247. */
  248. this.createTextNote = (parentNoteId, title, content = '') => noteService.createNewNote({
  249. parentNoteId,
  250. title,
  251. content,
  252. type: 'text'
  253. });
  254. /**
  255. * Create data note - data in this context means object serializable to JSON. Created note will be of type 'code' and
  256. * JSON MIME type. See also createNewNote() for more options.
  257. *
  258. * @method
  259. * @param {string} parentNoteId
  260. * @param {string} title
  261. * @param {object} content
  262. * @returns {{note: BNote, branch: BBranch}} object having "note" and "branch" keys representing respective objects
  263. */
  264. this.createDataNote = (parentNoteId, title, content = {}) => noteService.createNewNote({
  265. parentNoteId,
  266. title,
  267. content: JSON.stringify(content, null, '\t'),
  268. type: 'code',
  269. mime: 'application/json'
  270. });
  271. /**
  272. * @method
  273. *
  274. * @param {object} params
  275. * @param {string} params.parentNoteId
  276. * @param {string} params.title
  277. * @param {string|Buffer} params.content
  278. * @param {NoteType} params.type - text, code, file, image, search, book, relationMap, canvas
  279. * @param {string} [params.mime] - value is derived from default mimes for type
  280. * @param {boolean} [params.isProtected=false]
  281. * @param {boolean} [params.isExpanded=false]
  282. * @param {string} [params.prefix='']
  283. * @param {int} [params.notePosition] - default is last existing notePosition in a parent + 10
  284. * @returns {{note: BNote, branch: BBranch}} object contains newly created entities note and branch
  285. */
  286. this.createNewNote = noteService.createNewNote;
  287. /**
  288. * @method
  289. * @deprecated please use createTextNote() with similar API for simpler use cases or createNewNote() for more complex needs
  290. *
  291. * @param {string} parentNoteId - create new note under this parent
  292. * @param {string} title
  293. * @param {string} [content=""]
  294. * @param {object} [extraOptions={}]
  295. * @param {boolean} [extraOptions.json=false] - should the note be JSON
  296. * @param {boolean} [extraOptions.isProtected=false] - should the note be protected
  297. * @param {string} [extraOptions.type='text'] - note type
  298. * @param {string} [extraOptions.mime='text/html'] - MIME type of the note
  299. * @param {object[]} [extraOptions.attributes=[]] - attributes to be created for this note
  300. * @param {AttributeType} extraOptions.attributes.type - attribute type - label, relation etc.
  301. * @param {string} extraOptions.attributes.name - attribute name
  302. * @param {string} [extraOptions.attributes.value] - attribute value
  303. * @returns {{note: BNote, branch: BBranch}} object contains newly created entities note and branch
  304. */
  305. this.createNote = (parentNoteId, title, content = "", extraOptions= {}) => {
  306. extraOptions.parentNoteId = parentNoteId;
  307. extraOptions.title = title;
  308. const parentNote = becca.getNote(parentNoteId);
  309. // code note type can be inherited, otherwise "text" is the default
  310. extraOptions.type = parentNote.type === 'code' ? 'code' : 'text';
  311. extraOptions.mime = parentNote.type === 'code' ? parentNote.mime : 'text/html';
  312. if (extraOptions.json) {
  313. extraOptions.content = JSON.stringify(content || {}, null, '\t');
  314. extraOptions.type = 'code';
  315. extraOptions.mime = 'application/json';
  316. }
  317. else {
  318. extraOptions.content = content;
  319. }
  320. return sql.transactional(() => {
  321. const {note, branch} = noteService.createNewNote(extraOptions);
  322. for (const attr of extraOptions.attributes || []) {
  323. attributeService.createAttribute({
  324. noteId: note.noteId,
  325. type: attr.type,
  326. name: attr.name,
  327. value: attr.value,
  328. isInheritable: !!attr.isInheritable
  329. });
  330. }
  331. return {note, branch};
  332. });
  333. };
  334. this.logMessages = {};
  335. this.logSpacedUpdates = {};
  336. /**
  337. * Log given message to trilium logs and log pane in UI
  338. *
  339. * @method
  340. * @param message
  341. * @returns {void}
  342. */
  343. this.log = message => {
  344. log.info(message);
  345. const {noteId} = this.startNote;
  346. this.logMessages[noteId] = this.logMessages[noteId] || [];
  347. this.logSpacedUpdates[noteId] = this.logSpacedUpdates[noteId] || new SpacedUpdate(() => {
  348. const messages = this.logMessages[noteId];
  349. this.logMessages[noteId] = [];
  350. ws.sendMessageToAllClients({
  351. type: 'api-log-messages',
  352. noteId,
  353. messages
  354. });
  355. }, 100);
  356. this.logMessages[noteId].push(message);
  357. this.logSpacedUpdates[noteId].scheduleUpdate();
  358. };
  359. /**
  360. * Returns root note of the calendar.
  361. *
  362. * @method
  363. * @returns {BNote|null}
  364. */
  365. this.getRootCalendarNote = dateNoteService.getRootCalendarNote;
  366. /**
  367. * Returns day note for given date. If such note doesn't exist, it is created.
  368. *
  369. * @method
  370. * @param {string} date in YYYY-MM-DD format
  371. * @param {BNote} [rootNote] - specify calendar root note, normally leave empty to use the default calendar
  372. * @returns {BNote|null}
  373. */
  374. this.getDayNote = dateNoteService.getDayNote;
  375. /**
  376. * Returns today's day note. If such note doesn't exist, it is created.
  377. *
  378. * @method
  379. * @param {BNote} [rootNote] - specify calendar root note, normally leave empty to use the default calendar
  380. * @returns {BNote|null}
  381. */
  382. this.getTodayNote = dateNoteService.getTodayNote;
  383. /**
  384. * Returns note for the first date of the week of the given date.
  385. *
  386. * @method
  387. * @param {string} date in YYYY-MM-DD format
  388. * @param {object} [options]
  389. * @param {string} [options.startOfTheWeek=monday] - either "monday" (default) or "sunday"
  390. * @param {BNote} [rootNote] - specify calendar root note, normally leave empty to use the default calendar
  391. * @returns {BNote|null}
  392. */
  393. this.getWeekNote = dateNoteService.getWeekNote;
  394. /**
  395. * Returns month note for given date. If such a note doesn't exist, it is created.
  396. *
  397. * @method
  398. * @param {string} date in YYYY-MM format
  399. * @param {BNote} [rootNote] - specify calendar root note, normally leave empty to use the default calendar
  400. * @returns {BNote|null}
  401. */
  402. this.getMonthNote = dateNoteService.getMonthNote;
  403. /**
  404. * Returns year note for given year. If such a note doesn't exist, it is created.
  405. *
  406. * @method
  407. * @param {string} year in YYYY format
  408. * @param {BNote} [rootNote] - specify calendar root note, normally leave empty to use the default calendar
  409. * @returns {BNote|null}
  410. */
  411. this.getYearNote = dateNoteService.getYearNote;
  412. /**
  413. * Sort child notes of a given note.
  414. *
  415. * @method
  416. * @param {string} parentNoteId - this note's child notes will be sorted
  417. * @param {object} [sortConfig]
  418. * @param {string} [sortConfig.sortBy=title] - 'title', 'dateCreated', 'dateModified' or a label name
  419. * See {@link https://github.com/zadam/trilium/wiki/Sorting} for details.
  420. * @param {boolean} [sortConfig.reverse=false]
  421. * @param {boolean} [sortConfig.foldersFirst=false]
  422. * @returns {void}
  423. */
  424. this.sortNotes = (parentNoteId, sortConfig = {}) => treeService.sortNotes(
  425. parentNoteId,
  426. sortConfig.sortBy || "title",
  427. !!sortConfig.reverse,
  428. !!sortConfig.foldersFirst
  429. );
  430. /**
  431. * This method finds note by its noteId and prefix and either sets it to the given parentNoteId
  432. * or removes the branch (if parentNoteId is not given).
  433. *
  434. * This method looks similar to toggleNoteInParent() but differs because we're looking up branch by prefix.
  435. *
  436. * @method
  437. * @deprecated this method is pretty confusing and serves specialized purpose only
  438. * @param {string} noteId
  439. * @param {string} prefix
  440. * @param {string|null} parentNoteId
  441. * @returns {void}
  442. */
  443. this.setNoteToParent = treeService.setNoteToParent;
  444. /**
  445. * This functions wraps code which is supposed to be running in transaction. If transaction already
  446. * exists, then we'll use that transaction.
  447. *
  448. * @method
  449. * @param {function} func
  450. * @returns {any} result of func callback
  451. */
  452. this.transactional = sql.transactional;
  453. /**
  454. * Return randomly generated string of given length. This random string generation is NOT cryptographically secure.
  455. *
  456. * @method
  457. * @param {int} length of the string
  458. * @returns {string} random string
  459. */
  460. this.randomString = utils.randomString;
  461. /**
  462. * @method
  463. * @param {string} string to escape
  464. * @returns {string} escaped string
  465. */
  466. this.escapeHtml = utils.escapeHtml;
  467. /**
  468. * @method
  469. * @param {string} string to unescape
  470. * @returns {string} unescaped string
  471. */
  472. this.unescapeHtml = utils.unescapeHtml;
  473. /**
  474. * sql
  475. * @type {module:sql}
  476. */
  477. this.sql = sql;
  478. /**
  479. * @method
  480. * @returns {{syncVersion, appVersion, buildRevision, dbVersion, dataDirectory, buildDate}|*} - object representing basic info about running Trilium version
  481. */
  482. this.getAppInfo = () => appInfo;
  483. /**
  484. * Creates a new launcher to the launchbar. If the launcher (id) already exists, it will be updated.
  485. *
  486. * @method
  487. * @param {object} opts
  488. * @param {string} opts.id - id of the launcher, only alphanumeric at least 6 characters long
  489. * @param {"note" | "script" | "customWidget"} opts.type - one of
  490. * * "note" - activating the launcher will navigate to the target note (specified in targetNoteId param)
  491. * * "script" - activating the launcher will execute the script (specified in scriptNoteId param)
  492. * * "customWidget" - the launcher will be rendered with a custom widget (specified in widgetNoteId param)
  493. * @param {string} opts.title
  494. * @param {boolean} [opts.isVisible=false] - if true, will be created in the "Visible launchers", otherwise in "Available launchers"
  495. * @param {string} [opts.icon] - name of the boxicon to be used (e.g. "bx-time")
  496. * @param {string} [opts.keyboardShortcut] - will activate the target note/script upon pressing, e.g. "ctrl+e"
  497. * @param {string} [opts.targetNoteId] - for type "note"
  498. * @param {string} [opts.scriptNoteId] - for type "script"
  499. * @param {string} [opts.widgetNoteId] - for type "customWidget"
  500. * @returns {{note: BNote}}
  501. */
  502. this.createOrUpdateLauncher = opts => {
  503. if (!opts.id) { throw new Error("ID is a mandatory parameter for api.createOrUpdateLauncher(opts)"); }
  504. if (!opts.id.match(/[a-z0-9]{6,1000}/i)) { throw new Error(`ID must be an alphanumeric string at least 6 characters long.`); }
  505. if (!opts.type) { throw new Error("Launcher Type is a mandatory parameter for api.createOrUpdateLauncher(opts)"); }
  506. if (!["note", "script", "customWidget"].includes(opts.type)) { throw new Error(`Given launcher type '${opts.type}'`); }
  507. if (!opts.title?.trim()) { throw new Error("Title is a mandatory parameter for api.createOrUpdateLauncher(opts)"); }
  508. if (opts.type === 'note' &amp;&amp; !opts.targetNoteId) { throw new Error("targetNoteId is mandatory for launchers of type 'note'"); }
  509. if (opts.type === 'script' &amp;&amp; !opts.scriptNoteId) { throw new Error("scriptNoteId is mandatory for launchers of type 'script'"); }
  510. if (opts.type === 'customWidget' &amp;&amp; !opts.widgetNoteId) { throw new Error("widgetNoteId is mandatory for launchers of type 'customWidget'"); }
  511. const parentNoteId = opts.isVisible ? '_lbVisibleLaunchers' : '_lbAvailableLaunchers';
  512. const noteId = 'al_' + opts.id;
  513. const launcherNote =
  514. becca.getNote(noteId) ||
  515. specialNotesService.createLauncher({
  516. noteId: noteId,
  517. parentNoteId: parentNoteId,
  518. launcherType: opts.type,
  519. }).note;
  520. if (launcherNote.title !== opts.title) {
  521. launcherNote.title = opts.title;
  522. launcherNote.save();
  523. }
  524. if (launcherNote.getParentBranches().length === 1) {
  525. const branch = launcherNote.getParentBranches()[0];
  526. if (branch.parentNoteId !== parentNoteId) {
  527. branchService.moveBranchToNote(branch, parentNoteId);
  528. }
  529. }
  530. if (opts.type === 'note') {
  531. launcherNote.setRelation('target', opts.targetNoteId);
  532. } else if (opts.type === 'script') {
  533. launcherNote.setRelation('script', opts.scriptNoteId);
  534. } else if (opts.type === 'customWidget') {
  535. launcherNote.setRelation('widget', opts.widgetNoteId);
  536. } else {
  537. throw new Error(`Unrecognized launcher type '${opts.type}'`);
  538. }
  539. if (opts.keyboardShortcut) {
  540. launcherNote.setLabel('keyboardShortcut', opts.keyboardShortcut);
  541. } else {
  542. launcherNote.removeLabel('keyboardShortcut');
  543. }
  544. if (opts.icon) {
  545. launcherNote.setLabel('iconClass', `bx ${opts.icon}`);
  546. } else {
  547. launcherNote.removeLabel('iconClass');
  548. }
  549. return {note: launcherNote};
  550. };
  551. /**
  552. * @method
  553. * @param {string} noteId
  554. * @param {string} format - either 'html' or 'markdown'
  555. * @param {string} zipFilePath
  556. * @returns {Promise&lt;void>}
  557. */
  558. this.exportSubtreeToZipFile = async (noteId, format, zipFilePath) => await exportService.exportToZipFile(noteId, format, zipFilePath);
  559. /**
  560. * Executes given anonymous function on the frontend(s).
  561. * Internally, this serializes the anonymous function into string and sends it to frontend(s) via WebSocket.
  562. * Note that there can be multiple connected frontend instances (e.g. in different tabs). In such case, all
  563. * instances execute the given function.
  564. *
  565. * @method
  566. * @param {string} script - script to be executed on the frontend
  567. * @param {Array.&lt;?>} params - list of parameters to the anonymous function to be sent to frontend
  568. * @returns {undefined} - no return value is provided.
  569. */
  570. this.runOnFrontend = async (script, params = []) => {
  571. if (typeof script === "function") {
  572. script = script.toString();
  573. }
  574. ws.sendMessageToAllClients({
  575. type: 'execute-script',
  576. script: script,
  577. params: prepareParams(params),
  578. startNoteId: this.startNote.noteId,
  579. currentNoteId: this.currentNote.noteId,
  580. originEntityName: "notes", // currently there's no other entity on the frontend which can trigger event
  581. originEntityId: this.originEntity?.noteId || null
  582. });
  583. function prepareParams(params) {
  584. if (!params) {
  585. return params;
  586. }
  587. return params.map(p => {
  588. if (typeof p === "function") {
  589. return `!@#Function: ${p.toString()}`;
  590. }
  591. else {
  592. return p;
  593. }
  594. });
  595. }
  596. };
  597. /**
  598. * Sync process can make data intermittently inconsistent. Scripts which require strong data consistency
  599. * can use this function to wait for a possible sync process to finish and prevent new sync process from starting
  600. * while it is running.
  601. *
  602. * Because this is an async process, the inner callback doesn't have automatic transaction handling, so in case
  603. * you need to make some DB changes, you need to surround your call with api.transactional(...)
  604. *
  605. * @method
  606. * @param {function} callback - function to be executed while sync process is not running
  607. * @returns {Promise} - resolves once the callback is finished (callback is awaited)
  608. */
  609. this.runOutsideOfSync = syncMutex.doExclusively;
  610. /**
  611. * @method
  612. * @param {string} backupName - If the backupName is e.g. "now", then the backup will be written to "backup-now.db" file
  613. * @returns {Promise} - resolves once the backup is finished
  614. */
  615. this.backupNow = backupService.backupNow;
  616. /**
  617. * This object contains "at your risk" and "no BC guarantees" objects for advanced use cases.
  618. *
  619. * @property {Becca} becca - provides access to the backend in-memory object graph, see {@link https://github.com/zadam/trilium/blob/master/src/becca/becca.js}
  620. */
  621. this.__private = {
  622. becca
  623. }
  624. }
  625. module.exports = BackendScriptApi;
  626. </code></pre>
  627. </article>
  628. </section>
  629. </div>
  630. <nav>
  631. <h2><a href="index.html">Home</a></h2><h3>Modules</h3><ul><li><a href="module-sql.html">sql</a></li></ul><h3>Classes</h3><ul><li><a href="AbstractBeccaEntity.html">AbstractBeccaEntity</a></li><li><a href="BAttachment.html">BAttachment</a></li><li><a href="BAttribute.html">BAttribute</a></li><li><a href="BBranch.html">BBranch</a></li><li><a href="BEtapiToken.html">BEtapiToken</a></li><li><a href="BNote.html">BNote</a></li><li><a href="BOption.html">BOption</a></li><li><a href="BRecentNote.html">BRecentNote</a></li><li><a href="BRevision.html">BRevision</a></li><li><a href="BackendScriptApi.html">BackendScriptApi</a></li></ul><h3>Global</h3><ul><li><a href="global.html#api">api</a></li></ul>
  632. </nav>
  633. <br class="clear">
  634. <footer>
  635. Documentation generated by <a href="https://github.com/jsdoc/jsdoc">JSDoc 4.0.2</a>
  636. </footer>
  637. <script> prettyPrint(); </script>
  638. <script src="scripts/linenumber.js"> </script>
  639. </body>
  640. </html>