A fully open source & end-to-end encrypted note taking alternative to Evernote.
TypeScript asp-net-coredotnet-coreelectronfosshacktoberfestnote-managmentnote-takingnote-taking-appnotebooknotesnotes-appopen-sourceopensourceprivacyproductivityreactreact-nativereactjsself-hosted
feat: impl fully indexed & searchable data stores
thecodrr56297da18b30
diff --git a/packages/core/__tests__/notebooks.test.js b/packages/core/__tests__/notebooks.test.jsindex dc5b40914..d45dedd8f 100644--- a/packages/core/__tests__/notebooks.test.js+++ b/packages/core/__tests__/notebooks.test.js@@ -2,7 +2,7 @@ import {StorageInterface,notebookTest,TEST_NOTEBOOK,- TEST_NOTE+ TEST_NOTE,} from "./utils";beforeEach(async () => {@@ -26,7 +26,7 @@ test("search all notebooks", () =>notebookTest({...TEST_NOTEBOOK,title: "I will be searched.",- description: "searched description"+ description: "searched description",}).then(({ db }) => {let filtered = db.notebooks.filter("searhed");expect(filtered.length).toBeGreaterThan(0);@@ -54,16 +54,10 @@ test("unpin a notebook", () =>test("delete a notebook", () =>notebookTest().then(async ({ db, id }) => {let noteId = await db.notes.add(TEST_NOTE);- await db.notebooks- .notebook(id)- .topics.topic("General")- .add(noteId);- expect(- db.notebooks- .notebook(id)- .topics.topic("General")- .has(noteId)- ).toBe(true);+ await db.notebooks.notebook(id).topics.topic("General").add(noteId);+ expect(db.notebooks.notebook(id).topics.topic("General").has(noteId)).toBe(+ true+ );let note = db.notes.note(noteId);expect(note.notebook.id).toBe(id);await db.notebooks.delete(id);diff --git a/packages/core/__tests__/topics.test.js b/packages/core/__tests__/topics.test.jsindex cd80032c5..44f0f72ca 100644--- a/packages/core/__tests__/topics.test.js+++ b/packages/core/__tests__/topics.test.js@@ -79,13 +79,12 @@ test("delete a topic", () =>}));test("delete note from edited topic", () =>- notebookTest().then(async ({ id }) =>- noteTest().then(async ({ db, id: noteId }) => {- let topics = db.notebooks.notebook(id).topics;- await topics.add("Home");- let topic = topics.topic("Home");- await db.notes.move({ id, topic: topic._topic.title }, noteId);- await topics.add({ id: topic._topic.id, title: "Hello22" });- await db.notes.delete(noteId);- })- ));+ notebookTest().then(async ({ db, id }) => {+ const noteId = await db.notes.add(TEST_NOTE);+ let topics = db.notebooks.notebook(id).topics;+ await topics.add("Home");+ let topic = topics.topic("Home");+ await db.notes.move({ id, topic: topic._topic.title }, noteId);+ await topics.add({ id: topic._topic.id, title: "Hello22" });+ await db.notes.delete(noteId);+ }));diff --git a/packages/core/api/lookup.js b/packages/core/api/lookup.jsindex 3918439b7..08b8f2de9 100644--- a/packages/core/api/lookup.js+++ b/packages/core/api/lookup.js@@ -1,4 +1,5 @@import fuzzysearch from "fuzzysearch";+import sm from "../utils/set";var tfun = require("transfun/transfun.js").tfun;if (!tfun) {tfun = global.tfun;@@ -14,23 +15,22 @@ export default class Lookup {}notes(notes, query) {- let contentIds = this._db.content._collection.search.searchDocs(query);- let noteIds = this._db.notes._collection.search.searchDocs(query);- return notes.filter((note) => {- return (- contentIds.findIndex((content) => note.id === content.noteId) > -1 ||- noteIds.findIndex((n) => n.id === note.id) > -1- );- });+ return sm.union(+ this._db.content._collection.search.search(query, {+ map: (elem) => {+ return notes.find((note) => note.contentId === elem);+ },+ }),+ this._db.notes._collection.search.search(query)+ );}notebooks(array, query) {- const notebooksIds = this._db.notebooks._collection.search.searchDocs(- query- );- return tfun.filter(- (nb) => notebooksIds.findIndex((notebook) => notebook.id === nb.id) > -1- )(array);+ return this._db.notebooks._collection.search.search(query, {+ map: (elem) => {+ return array.find((nb) => nb.id === elem);+ },+ });}topics(array, query) {diff --git a/packages/core/collections/content.js b/packages/core/collections/content.jsindex cf840d11f..4efc9f895 100644--- a/packages/core/collections/content.js+++ b/packages/core/collections/content.js@@ -44,11 +44,7 @@ export default class Content extends Collection {return this._collection.removeItem(id);}- multi(ids) {- return this._collection.getItems(ids);- }-all() {- return this._collection.getItems(this._collection.indexer.indices);+ return this._collection.getItems();}}diff --git a/packages/core/collections/notebooks.js b/packages/core/collections/notebooks.jsindex fec001af9..66821821c 100644--- a/packages/core/collections/notebooks.js+++ b/packages/core/collections/notebooks.js@@ -35,7 +35,6 @@ export default class Notebooks extends Collection {description: notebook.description,dateCreated: notebook.dateCreated,pinned: !!notebook.pinned,- favorite: !!notebook.favorite,topics: notebook.topics || [],totalNotes: 0,};diff --git a/packages/core/database/backup.js b/packages/core/database/backup.jsindex 21b47b787..ce19bf6b8 100644--- a/packages/core/database/backup.js+++ b/packages/core/database/backup.js@@ -29,26 +29,23 @@ export default class Backup {(key) => !invalidKeys.some((t) => t === key));- const db = Object.fromEntries(await this._db.context.readMulti(keys));- db.h = md5.hex(JSON.stringify(db));- db.ht = "md5";+ let data = Object.fromEntries(await this._db.context.readMulti(keys));if (encrypt) {const key = await this._db.user.key();- return JSON.stringify({- type,- date: Date.now(),- data: await this._db.context.encrypt(key, JSON.stringify(db)),- });+ data = await this._db.context.encrypt(key, JSON.stringify(data));}// save backup timeawait this._db.context.write("lastBackupTime", Date.now());return JSON.stringify({+ version: 2,type,date: Date.now(),- data: db,+ data,+ hash: md5.hex(JSON.stringify(data)),+ hash_type: "md5",});}@@ -70,16 +67,26 @@ export default class Backup {db = JSON.parse(await this._db.context.decrypt(key, db));}- if (!this._verify(db))+ if (!this._verify(backup))throw new Error("Backup file has been tempered, aborting...");-- for (let key in db) {- let value = db[key];- if (value && value.dateEdited) {- value.dateEdited = Date.now();- }- await this._db.context.write(key, value);- }+ // TODO add a proper restoration system.+ // for (let key in db) {+ // let value = db[key];+ // if (value && value.dateEdited) {+ // value.dateEdited = Date.now();+ // }++ // const oldValue = await this._db.context.read(oldValue);++ // let finalValue = oldValue || value;+ // if (typeof value === "object") {+ // finalValue = Array.isArray(value)+ // ? [...value, ...oldValue]+ // : { ...value, ...oldValue };+ // }++ // await this._db.context.write(key, finalValue);+ // }}_validate(backup) {@@ -91,14 +98,11 @@ export default class Backup {);}- _verify(db) {- const hash = db.h;- const hash_type = db.ht;- delete db.h;- delete db.ht;+ _verify(backup) {+ const { hash, hash_type, data: db } = backup;switch (hash_type) {case "md5": {- return hash == md5.hex(JSON.stringify(db));+ return hash === md5.hex(JSON.stringify(db));}default: {return false;diff --git a/packages/core/database/cached-collection.js b/packages/core/database/cached-collection.jsindex 74d4ef854..93467595c 100644--- a/packages/core/database/cached-collection.js+++ b/packages/core/database/cached-collection.js@@ -1,45 +1,36 @@-import Indexer from "./indexer";+import Storage from "./storage";+import HyperSearch from "hypersearch";+import { getSchema } from "./schemas";+import PersistentCachedMap from "./persistentcachedmap";import sort from "fast-sort";-import { EV } from "../common";import IndexedCollection from "./indexed-collection";export default class CachedCollection extends IndexedCollection {- constructor(context, type) {- super(context, type);- }-async init() {- await super.init();- const data = await this.indexer.readMulti(this.indexer.indices);- this.map = new Map(data);- }-- async clear() {- await super.clear();- this.map.clear();- }-- async updateItem(item, index = true) {- await super.updateItem(item, index);- this.map.set(item.id, item);- EV.publish("db:write", item);+ const index = new PersistentCachedMap(`${this.type}Index`, this.storage);+ const store = new PersistentCachedMap(`${this.type}Store`, this.storage);+ await index.init();+ await store.init();+ this.search = new HyperSearch({+ schema: getSchema(this.type),+ tokenizer: "forward",+ index,+ store,+ });}exists(id) {- return this.map.has(id) && !this.map.get(id).deleted;- }-- getItem(id) {- return this.map.get(id);+ const item = this.getItem(id);+ return item && !item.deleted;}getRaw() {- return Array.from(this.map.values());+ return Array.from(this.search.getAllDocs());}getItems(sortFn = (u) => u.dateCreated) {let items = [];- this.map.forEach((value) => {+ this.search.options.store.forEach((value) => {if (!value || value.deleted) return;items[items.length] = value;});diff --git a/packages/core/database/indexed-collection.js b/packages/core/database/indexed-collection.jsindex 93d253993..25d769a20 100644--- a/packages/core/database/indexed-collection.js+++ b/packages/core/database/indexed-collection.js@@ -1,77 +1,78 @@-import Indexer from "./indexer";+import Storage from "./storage";import HyperSearch from "hypersearch";import { getSchema } from "./schemas";+import PersistentCachedMap from "./persistentcachedmap";+import PersistentMap from "./persistentmap";+import sort from "fast-sort";export default class IndexedCollection {- constructor(context, type) {- this.indexer = new Indexer(context, type);+ /**+ *+ * @param {Storage} storage+ * @param {string} type+ */+ constructor(storage, type) {this.type = type;- this.search = new HyperSearch({- schema: getSchema(type),- tokenizer: "forward",- });+ this.storage = storage;}clear() {- return this.indexer.clear();+ return this.search.clear();}async init() {- await this.indexer.init();- const index = await this.indexer.read(`${this.type}-index`);- if (index) this.search.import(index);+ const index = new PersistentCachedMap(`${this.type}Index`, this.storage);+ const store = new PersistentMap(`${this.type}Store`, this.storage);+ await index.init();+ await store.init();+ this.search = new HyperSearch({+ schema: getSchema(this.type),+ tokenizer: "forward",+ index,+ store,+ });}async addItem(item) {- const exists = await this.exists(item.id);+ const exists = this.exists(item.id);if (!exists) item.dateCreated = item.dateCreated || Date.now();- await this.updateItem(item);- if (!exists) {- await this.indexer.index(item.id);- }+ await this._upsertItem(item);}- async updateItem(item, index = true) {+ /**+ * @protected+ */+ async _upsertItem(item) {if (!item.id) throw new Error("The item must contain the id field.");// if item is newly synced, remote will be true.item.dateEdited = item.remote ? item.dateEdited : Date.now();// the item has become local now, so remove the flag.delete item.remote;- await this.indexer.write(item.id, item);-- if (index && (this.type === "notes" || this.type === "notebooks")) {- this.search.addDoc(item);- this.indexer.write(`${this.type}-index`, this.search.export());- }+ const exists = this.exists(item.id);+ if (!exists) await this.search.addDoc(item);+ else await this.search.updateDoc(item.id, item);}async removeItem(id) {- await this.updateItem(- {- id,- deleted: true,- dateCreated: Date.now(),- dateEdited: Date.now(),- },- false- );- if (this.type === "notes" || this.type === "notebooks")- this.search.remove(id);+ await this.search.remove(id);+ await this._upsertItem({+ id,+ deleted: true,+ dateCreated: Date.now(),+ dateEdited: Date.now(),+ });}- exists(id) {- return this.indexer.exists(id);+ async exists(id) {+ const item = await this.getItem(id);+ return item && !item.deleted;}getItem(id) {- return this.indexer.read(id);+ return this.search.getById(id);}- async getItems(indices) {- const data = await this.indexer.readMulti(indices);- return data.reduce((total, current) => {- total.push(current[1]);- return total;- }, []);+ async getItems() {+ return await this.search.getAllDocs();}}diff --git a/packages/core/database/indexer.js b/packages/core/database/indexer.jsindex 5623b4657..ed227e2a0 100644--- a/packages/core/database/indexer.js+++ b/packages/core/database/indexer.js@@ -11,7 +11,7 @@ export default class Indexer extends Storage {this.indices = (await this.read(this.type, true)) || [];}- async exists(key) {+ exists(key) {return this.indices.includes(key);}@@ -30,7 +30,10 @@ export default class Indexer extends Storage {}async clear() {+ for (var i = 0; i < this.indices.length; ++i) {+ let key = this.indices[i];+ await this.remove(key);+ }this.indices = [];- await super.clear();}}diff --git a/packages/core/database/persistentcachedmap.js b/packages/core/database/persistentcachedmap.jsnew file mode 100644index 000000000..cc2dc7593--- /dev/null+++ b/packages/core/database/persistentcachedmap.js@@ -0,0 +1,53 @@+import Storage from "./storage";+import Indexer from "./indexer";++export default class PersistentCachedMap {+ /**+ *+ * @param {string} key+ * @param {Storage} storage+ */+ constructor(key, storage) {+ this.key = key;+ this.indexer = new Indexer(storage, key);+ }++ async init() {+ await this.indexer.init();+ const data = await this.indexer.readMulti(this.indexer.indices);+ this.map = new Map(data);+ }++ async set(key, value) {+ this.map.set(key, value);+ await this.indexer.write(key, value);+ await this.indexer.index(key);+ }++ async delete(key) {+ await this.indexer.remove(key);+ await this.indexer.deindex(key);+ return this.map.delete(key);+ }++ get(key) {+ return this.map.get(key);+ }++ has(key) {+ return this.map.has(key);+ }++ async clear() {+ await this.indexer.clear();+ this.map.clear();+ }++ values() {+ return this.map.values();+ }++ forEach(callbackFn) {+ return this.map.forEach(callbackFn);+ }+}diff --git a/packages/core/database/persistentmap.js b/packages/core/database/persistentmap.jsnew file mode 100644index 000000000..a11e3bb5e--- /dev/null+++ b/packages/core/database/persistentmap.js@@ -0,0 +1,48 @@+import Indexer from "./indexer";+import Storage from "./storage";++export default class PersistentMap {+ /**+ *+ * @param {string} key+ * @param {Storage} storage+ */+ constructor(key, storage) {+ this.key = key;+ this.indexer = new Indexer(storage, key);+ }++ init() {+ return this.indexer.init();+ }++ async set(key, value) {+ await this.indexer.write(key, value);+ await this.indexer.index(key);+ }++ async delete(key) {+ await this.indexer.remove(key);+ await this.indexer.deindex(key);+ }++ get(key) {+ return this.indexer.read(key);+ }++ has(key) {+ return this.indexer.exists(key);+ }++ async clear() {+ await this.indexer.clear();+ }++ async values() {+ const data = await this.indexer.readMulti(this.indexer.indices);+ return data.reduce((total, current) => {+ total.push(current[1]);+ return total;+ }, []);+ }+}diff --git a/packages/core/database/schemas.js b/packages/core/database/schemas.jsindex 4a69617e5..a2b6161d8 100644--- a/packages/core/database/schemas.js+++ b/packages/core/database/schemas.js@@ -1,22 +1,46 @@const { getContentFromData } = require("../contenttypes");+const { qclone } = require("qclone");++const onlyStore = { store: true, index: false };+const indexAndStore = { store: true, index: true };+const asId = { asId: true };++const basicItem = {+ id: asId,+ deleted: onlyStore,+ dateCreated: onlyStore,+ dateEdited: onlyStore,+ type: onlyStore,+};const schemas = {content: {- id: { asId: true, store: false },- noteId: { store: true, index: false },+ ...basicItem,+ noteId: onlyStore,+ conflicted: onlyStore,+ resolved: onlyStore,data: {resolve: (doc) => {- if (doc.data.iv) return "";+ if (!doc.data || doc.data.iv) return "";const content = getContentFromData(doc.type, doc.data);return content._text;},- store: false,+ store: true,index: true,},},notes: {- id: { asId: true, store: false },- title: true,+ ...basicItem,+ locked: onlyStore,+ colors: onlyStore,+ tags: onlyStore,+ conflicted: onlyStore,+ contentId: onlyStore,+ pinned: onlyStore,+ favorite: onlyStore,+ title: indexAndStore,+ headline: onlyStore,+ notebook: onlyStore,// pinned: {// resolve: (doc) => (doc.pinned ? "pinned:true" : "pinned:false"),// index: true,@@ -25,18 +49,46 @@ const schemas = {// },},notebooks: {- id: { asId: true, store: false },- title: true,- description: true,+ ...basicItem,+ title: indexAndStore,+ description: indexAndStore,+ totalNotes: onlyStore,+ pinned: onlyStore,topics: {resolve: (doc) => {if (!doc.topics) return "";return doc.topics.map((v) => v.title || v).join(" ");},+ ...indexAndStore,},},+ colors: {+ ...basicItem,+ merge: ["tags"],+ },+ tags: {+ ...basicItem,+ noteIds: onlyStore,+ deletedIds: onlyStore,+ title: indexAndStore,+ },+ trash: {+ id: asId,+ dateDeleted: onlyStore,+ itemType: onlyStore,+ itemId: onlyStore,+ merge: ["notes", "notebooks"],+ },};export function getSchema(type) {- return schemas[type];+ let schema = qclone(schemas[type]);+ if (schema.merge) {+ const mergeSchemas = schema.merge;+ delete schema.merge;+ mergeSchemas.forEach((key) => {+ schema = { ...schema, ...schemas[key] };+ });+ }+ return schema;}