Skip to content

A fully open source & end-to-end encrypted note taking alternative to Evernote.

core: port fixes for sync issues from typescript branch

Abdullah Atta9ab7e722e084
diff --git a/packages/core/__e2e__/sync.test.js b/packages/core/__e2e__/sync.test.js
new file mode 100644
index 000000000..e9eb8e4e8
--- /dev/null
+++ b/packages/core/__e2e__/sync.test.js
@@ -0,0 +1,466 @@
+/*
+This file is part of the Notesnook project (https://notesnook.com/)
+
+Copyright (C) 2023 Streetwriters (Private) Limited
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+import Database from "../src/api/index";
+import { NodeStorageInterface } from "../__mocks__/node-storage.mock";
+import { FS } from "../__mocks__/fs.mock";
+import Compressor from "../__mocks__/compressor.mock";
+import { CHECK_IDS, EV, EVENTS } from "../src/common";
+import { EventSource } from "event-source-polyfill";
+import { delay } from "../__tests__/utils";
+import { test, expect, vitest } from "vitest";
+import { login } from "./utils";
+
+const TEST_TIMEOUT = 60 * 1000;
+
+test(
+ "case 1: device A & B should only download the changes from device C (no uploading)",
+ async () => {
+ const types = [];
+ function onSyncProgress({ type }) {
+ types.push(type);
+ }
+
+ const [deviceA, deviceB, deviceC] = await Promise.all([
+ initializeDevice("deviceA"),
+ initializeDevice("deviceB"),
+ initializeDevice("deviceC")
+ ]);
+
+ deviceA.eventManager.subscribe(EVENTS.syncProgress, onSyncProgress);
+ deviceB.eventManager.subscribe(EVENTS.syncProgress, onSyncProgress);
+
+ await deviceC.notes.add({ title: "new note 1" });
+ await syncAndWait(deviceC, deviceC);
+
+ expect(types.every((t) => t === "download")).toBe(true);
+
+ await cleanup(deviceA, deviceB, deviceC);
+ },
+ TEST_TIMEOUT
+);
+
+test(
+ "case 3: Device A & B have unsynced changes but server has nothing",
+ async () => {
+ const [deviceA, deviceB] = await Promise.all([
+ initializeDevice("deviceA"),
+ initializeDevice("deviceB")
+ ]);
+
+ const note1Id = await deviceA.notes.add({
+ title: "Test note from device A"
+ });
+ const note2Id = await deviceB.notes.add({
+ title: "Test note from device B"
+ });
+
+ await syncAndWait(deviceA, deviceB);
+
+ expect(deviceA.notes.note(note2Id)).toBeTruthy();
+ expect(deviceB.notes.note(note1Id)).toBeTruthy();
+ expect(deviceA.notes.note(note1Id)).toBeTruthy();
+ expect(deviceB.notes.note(note2Id)).toBeTruthy();
+
+ await cleanup(deviceA, deviceA);
+ },
+ TEST_TIMEOUT
+);
+
+// test(
+// "case 4: Device A's sync is interrupted halfway and Device B makes some changes afterwards and syncs.",
+// async () => {
+// const deviceA = await initializeDevice("deviceA");
+// const deviceB = await initializeDevice("deviceB");
+
+// const unsyncedNoteIds = [];
+// for (let i = 0; i < 10; ++i) {
+// const id = await deviceA.notes.add({
+// title: `Test note ${i} from device A`,
+// });
+// unsyncedNoteIds.push(id);
+// }
+
+// const half = unsyncedNoteIds.length / 2 + 1;
+// deviceA.eventManager.subscribe(
+// EVENTS.syncProgress,
+// async ({ type, current }) => {
+// if (type === "upload" && current === half) {
+// await deviceA.syncer.stop();
+// }
+// }
+// );
+
+// await expect(deviceA.sync(true)).rejects.toThrow();
+
+// let syncedNoteIds = [];
+// for (let i = 0; i < unsyncedNoteIds.length; ++i) {
+// const expectedNoteId = unsyncedNoteIds[i];
+// if (deviceB.notes.note(expectedNoteId))
+// syncedNoteIds.push(expectedNoteId);
+// }
+// expect(
+// syncedNoteIds.length === half - 1 || syncedNoteIds.length === half
+// ).toBe(true);
+
+// const deviceBNoteId = await deviceB.notes.add({
+// title: "Test note of case 4 from device B",
+// });
+
+// await deviceB.sync(true);
+
+// await syncAndWait(deviceA, deviceB);
+
+// expect(deviceA.notes.note(deviceBNoteId)).toBeTruthy();
+// expect(
+// unsyncedNoteIds
+// .map((id) => !!deviceB.notes.note(id))
+// .every((res) => res === true)
+// ).toBe(true);
+
+// await cleanup(deviceA, deviceB);
+// },
+//
+// );
+
+// test.only(
+// "case 5: Device A's sync is interrupted halfway and Device B makes changes on the same note's content that didn't get synced on Device A due to interruption.",
+// async () => {
+// const deviceA = await initializeDevice("deviceA");
+// const deviceB = await initializeDevice("deviceB");
+
+// const noteIds = [];
+// for (let i = 0; i < 10; ++i) {
+// const id = await deviceA.notes.add({
+// content: {
+// type: "tiptap",
+// data: `<p>deviceA=true</p>`,
+// },
+// });
+// noteIds.push(id);
+// }
+
+// await deviceA.sync(true);
+// await deviceB.sync(true);
+
+// const unsyncedNoteIds = [];
+// for (let id of noteIds) {
+// const noteId = await deviceA.notes.add({
+// id,
+// content: {
+// type: "tiptap",
+// data: `<p>deviceA=true+changed=true</p>`,
+// },
+// });
+// unsyncedNoteIds.push(noteId);
+// }
+
+// deviceA.eventManager.subscribe(
+// EVENTS.syncProgress,
+// async ({ type, total, current }) => {
+// const half = total / 2 + 1;
+// if (type === "upload" && current === half) {
+// await deviceA.syncer.stop();
+// }
+// }
+// );
+
+// await expect(deviceA.sync(true)).rejects.toThrow();
+
+// await delay(10 * 1000);
+
+// for (let id of unsyncedNoteIds) {
+// await deviceB.notes.add({
+// id,
+// content: {
+// type: "tiptap",
+// data: "<p>changes from device B</p>",
+// },
+// });
+// }
+
+// const error = await withError(async () => {
+// await deviceB.sync(true);
+// await deviceA.sync(true);
+// });
+
+// expect(error).not.toBeInstanceOf(NoErrorThrownError);
+// expect(error.message.includes("Merge")).toBeTruthy();
+
+// await cleanup(deviceA, deviceB);
+// },
+//
+// );
+
+test(
+ "issue: running force sync from device A makes device B always download everything",
+ async () => {
+ const [deviceA, deviceB] = await Promise.all([
+ initializeDevice("deviceA"),
+ initializeDevice("deviceB")
+ ]);
+
+ await syncAndWait(deviceA, deviceB, true);
+
+ const handler = vitest.fn();
+ deviceB.eventManager.subscribe(EVENTS.syncProgress, handler);
+
+ await deviceB.sync(true);
+
+ expect(handler).not.toHaveBeenCalled();
+
+ await cleanup(deviceB);
+ },
+ TEST_TIMEOUT
+);
+
+test(
+ "issue: colors are not properly created if multiple notes are synced together",
+ async () => {
+ const [deviceA, deviceB] = await Promise.all([
+ initializeDevice("deviceA", [CHECK_IDS.noteColor]),
+ initializeDevice("deviceB", [CHECK_IDS.noteColor])
+ ]);
+
+ const noteIds = [];
+ for (let i = 0; i < 3; ++i) {
+ const id = await deviceA.notes.add({
+ content: {
+ type: "tiptap",
+ data: `<p>deviceA=true</p>`
+ }
+ });
+ noteIds.push(id);
+ }
+
+ await syncAndWait(deviceA, deviceB);
+
+ for (let noteId of noteIds) {
+ await deviceA.notes.note(noteId).color("purple");
+ expect(deviceB.notes.note(noteId)).toBeTruthy();
+ expect(deviceB.notes.note(noteId).data.color).toBeUndefined();
+ }
+
+ await syncAndWait(deviceA, deviceB);
+
+ const purpleColor = deviceB.colors.tag("purple");
+ expect(noteIds.every((id) => purpleColor.noteIds.indexOf(id) > -1)).toBe(
+ true
+ );
+
+ await cleanup(deviceA, deviceB);
+ },
+ TEST_TIMEOUT
+);
+
+test(
+ "issue: new topic on device A gets replaced by the new topic on device B",
+ async () => {
+ const [deviceA, deviceB] = await Promise.all([
+ initializeDevice("deviceA"),
+ initializeDevice("deviceB")
+ ]);
+ // const deviceA = await initializeDevice("deviceA");
+ // const deviceB = await initializeDevice("deviceB");
+
+ const id = await deviceA.notebooks.add({ title: "Notebook 1" });
+
+ await syncAndWait(deviceA, deviceB, false);
+
+ expect(deviceB.notebooks.notebook(id)).toBeDefined();
+
+ await deviceA.notebooks.notebook(id).topics.add("Topic 1");
+ // to create a conflict
+ await delay(1500);
+ await deviceB.notebooks.notebook(id).topics.add("Topic 2");
+
+ expect(deviceA.notebooks.notebook(id).topics.has("Topic 1")).toBeTruthy();
+ expect(deviceB.notebooks.notebook(id).topics.has("Topic 2")).toBeTruthy();
+
+ expect(
+ deviceB.notebooks.notebook(id).topics.topic("Topic 2")._topic.dateEdited
+ ).toBeGreaterThan(
+ deviceA.notebooks.notebook(id).topics.topic("Topic 1")._topic.dateEdited
+ );
+ expect(deviceB.notebooks.notebook(id).dateModified).toBeGreaterThan(
+ deviceA.notebooks.notebook(id).dateModified
+ );
+
+ await syncAndWait(deviceB, deviceA, false);
+
+ expect(deviceA.notebooks.notebook(id).topics.has("Topic 1")).toBeTruthy();
+ expect(deviceB.notebooks.notebook(id).topics.has("Topic 1")).toBeTruthy();
+
+ expect(deviceA.notebooks.notebook(id).topics.has("Topic 2")).toBeTruthy();
+ expect(deviceB.notebooks.notebook(id).topics.has("Topic 2")).toBeTruthy();
+
+ await cleanup(deviceA, deviceB);
+ },
+ TEST_TIMEOUT
+);
+
+test(
+ "issue: assigning 2 notes to the same topic should keep references of both notes in the topic",
+ async (ctx) => {
+ const [deviceA, deviceB] = await Promise.all([
+ initializeDevice("deviceA"),
+ initializeDevice("deviceB")
+ ]);
+
+ const id = await deviceA.notebooks.add({
+ title: "Notebook 1",
+ topics: ["Topic 1"]
+ });
+
+ const topic = deviceA.notebooks.notebook(id).topics.topic("Topic 1");
+
+ await syncAndWait(deviceA, deviceB, false);
+
+ expect(deviceB.notebooks.notebook(id)).toBeDefined();
+
+ const noteA = await deviceA.notes.add({ title: "Note 1" });
+ await deviceA.notes.addToNotebook({ id, topic: topic.id }, noteA);
+
+ expect(
+ deviceA.notebooks.notebook(id).topics.topic(topic.id).totalNotes
+ ).toBe(1);
+
+ await delay(2000);
+
+ const noteB = await deviceB.notes.add({ title: "Note 2" });
+ await deviceB.notes.addToNotebook({ id, topic: topic.id }, noteB);
+
+ expect(
+ deviceB.notebooks.notebook(id).topics.topic(topic.id).totalNotes
+ ).toBe(1);
+
+ ctx.onTestFailed(() => {
+ console.log(deviceA.notes.topicReferences.get(topic.id), noteA);
+ console.log(deviceB.notes.topicReferences.get(topic.id), noteB);
+
+ deviceB.notes.topicReferences.rebuild();
+ deviceA.notes.topicReferences.rebuild();
+
+ console.log(deviceA.notes.topicReferences.get(topic.id), noteA);
+ console.log(deviceB.notes.topicReferences.get(topic.id), noteB);
+ });
+ await syncAndWait(deviceB, deviceA, false);
+
+ expect(deviceA.notes.note(noteB)).toBeDefined();
+ expect(deviceB.notes.note(noteA)).toBeDefined();
+
+ expect(deviceA.notes.note(noteA).data.notebooks).toHaveLength(1);
+ expect(deviceA.notes.note(noteB).data.notebooks).toHaveLength(1);
+
+ expect(
+ deviceA.notebooks.notebook(id).topics.topic(topic.id).totalNotes
+ ).toBe(2);
+ expect(
+ deviceB.notebooks.notebook(id).topics.topic(topic.id).totalNotes
+ ).toBe(2);
+
+ await cleanup(deviceA, deviceB);
+ },
+ TEST_TIMEOUT
+);
+
+/**
+ *
+ * @param {string} id
+ * @returns {Promise<Database>}
+ */
+async function initializeDevice(id, capabilities = []) {
+ console.time(`Init ${id}`);
+ EV.subscribe(EVENTS.userCheckStatus, async (type) => {
+ return {
+ type,
+ result: capabilities.indexOf(type) > -1
+ };
+ });
+ EV.subscribe(EVENTS.syncCheckStatus, async (type) => {
+ return {
+ type,
+ result: true
+ };
+ });
+
+ const device = new Database();
+ device.setup(new NodeStorageInterface(), EventSource, FS, Compressor);
+
+ await device.init();
+
+ await login(device);
+
+ await device.user.resetUser(false);
+
+ await device.sync(true, false);
+
+ console.timeEnd(`Init ${id}`);
+ return device;
+}
+
+/**
+ *
+ * @param {...Database} devices
+ */
+async function cleanup(...devices) {
+ await Promise.all([
+ devices.map(async (device) => {
+ await device.syncer.stop();
+ await device.user.logout();
+ device.eventManager.unsubscribeAll();
+ })
+ ]);
+ EV.unsubscribeAll();
+}
+
+/**
+ *
+ * @param {Database} deviceA
+ * @param {Database} deviceB
+ * @returns
+ */
+function syncAndWait(deviceA, deviceB, force = false) {
+ return new Promise((resolve, reject) => {
+ const ref2 = deviceB.eventManager.subscribe(
+ EVENTS.databaseSyncRequested,
+ (full, force, lastSynced) => {
+ console.log("sync requested by device A", full, force, lastSynced);
+ ref2.unsubscribe();
+ deviceB.sync(full, force, lastSynced).catch(reject);
+ }
+ );
+
+ const ref = deviceB.eventManager.subscribe(EVENTS.syncCompleted, () => {
+ ref.unsubscribe();
+ console.log("sync completed.");
+ resolve();
+ });
+
+ console.log(
+ "waiting for sync...",
+ "Device A:",
+ deviceA.syncer.sync.syncing,
+ "Device B:",
+ deviceB.syncer.sync.syncing
+ );
+
+ deviceA.sync(true, force).catch(reject);
+ });
+}
diff --git a/packages/core/__mocks__/fs.mock.js b/packages/core/__mocks__/fs.mock.ts
similarity index 52%
rename from packages/core/__mocks__/fs.mock.js
rename to packages/core/__mocks__/fs.mock.ts
index 111999783..9c11e0050 100644
--- a/packages/core/__mocks__/fs.mock.js
+++ b/packages/core/__mocks__/fs.mock.ts
@@ -17,44 +17,55 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-var fs = {};
+import { DataFormat, SerializedKey } from "@notesnook/crypto";
+import { xxhash64 } from "hash-wasm";
+import { IDataType } from "hash-wasm/dist/lib/util";
+
+let fs = {};
function hasItem(key) {
return !!fs[key];
}
-/**
- * We perform 4 steps here:
- * 1. We convert base64 to Uint8Array (if we get base64, that is)
- * 2. We hash the Uint8Array.
- * 3. We encrypt the Uint8Array
- * 4. We save the encrypted Uint8Array
- */
-async function writeEncrypted(filename, { data }) {
- const { hash, type: hashType } = hashBuffer(data);
- if (!filename) filename = hash;
- if (hasItem(filename)) return { hash, hashType };
- fs[filename] = data;
+async function writeEncryptedBase64(
+ data: string,
+ key: SerializedKey,
+ _mimeType: string
+) {
+ const bytes = new Uint8Array(Buffer.from(data, "base64"));
+
+ const { hash, type: hashType } = await hashBuffer(bytes);
+
+ if (hasItem(hash)) delete fs[hash];
+
+ fs[hash] = data;
return {
chunkSize: 512,
alg: "xcha-stream",
hash,
hashType,
iv: "some iv",
- cipher: data,
- salt: "i am some salt",
+ salt: key.salt!,
length: data.length
};
}
-function hashBuffer(data) {
+function hashBase64(data: string) {
+ return hashBuffer(Buffer.from(data, "base64"));
+}
+
+export async function hashBuffer(data: IDataType) {
return {
- hash: hashCode(data).toString(16),
- type: "xxh3"
+ hash: await xxhash64(data),
+ type: "xxh64"
};
}
-async function readEncrypted(filename) {
+async function readEncrypted<TOutputFormat extends DataFormat>(
+ filename: string,
+ _key: SerializedKey,
+ _cipherData: any
+) {
const cipher = fs[filename];
if (!cipher) {
console.error(`File not found. Filename: ${filename}`);
@@ -63,23 +74,23 @@ async function readEncrypted(filename) {
return cipher.data;
}
-async function uploadFile(filename) {
- let cipher = fs[filename];
+async function uploadFile(filename: string, _requestOptions: any) {
+ const cipher = fs[filename];
if (!cipher) throw new Error(`File not found. Filename: ${filename}`);
return true;
}
-async function downloadFile(filename) {
+async function downloadFile(filename: string, _requestOptions: any) {
return hasItem(filename);
}
-async function deleteFile(filename) {
+async function deleteFile(filename: string, _requestOptions: any) {
if (!hasItem(filename)) return true;
delete fs[filename];
return true;
}
-function exists(filename) {
+async function exists(filename) {
return hasItem(filename);
}
@@ -87,34 +98,27 @@ async function clearFileStorage() {
fs = {};
}
-module.exports = {
- writeEncrypted,
+export const FS = {
+ writeEncryptedBase64,
readEncrypted,
uploadFile: cancellable(uploadFile),
downloadFile: cancellable(downloadFile),
deleteFile,
exists,
- clearFileStorage
+ clearFileStorage,
+ hashBase64
};
-function cancellable(operation) {
- return function (filename, requestOptions) {
+function cancellable<T>(
+ operation: (filename: string, requestOptions: any) => Promise<T>
+) {
+ return function (filename: string, requestOptions: any) {
+ const abortController = new AbortController();
return {
execute: () => operation(filename, requestOptions),
- cancel: () => {}
+ cancel: async (message: string) => {
+ abortController.abort(message);
+ }
};
};
}
-
-function hashCode(str) {
- var hash = 0,
- i,
- chr;
- if (str.length === 0) return hash;
- for (i = 0; i < str.length; i++) {
- chr = str.charCodeAt(i);
- hash = (hash << 5) - hash + chr;
- hash |= 0; // Convert to 32bit integer
- }
- return hash;
-}
diff --git a/packages/core/__mocks__/node-storage.mock.js b/packages/core/__mocks__/node-storage.mock.js
deleted file mode 100644
index 39d2de9c2..000000000
--- a/packages/core/__mocks__/node-storage.mock.js
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
-This file is part of the Notesnook project (https://notesnook.com/)
-
-Copyright (C) 2023 Streetwriters (Private) Limited
-
-This program is free software: you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation, either version 3 of the License, or
-(at your option) any later version.
-
-This program is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-GNU General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with this program. If not, see <http://www.gnu.org/licenses/>.
-*/
-
-import { NNCrypto } from "@notesnook/crypto";
-
-export class NodeStorageInterface {
- constructor() {
- this.storage = {};
- this.crypto = new NNCrypto();
- }
-
- async read(key) {
- return new Promise((resolve) => resolve(this.storage[key]));
- }
-
- async readMulti(keys) {
- return new Promise((resolve) => {
- const result = [];
- keys.forEach((key) => {
- result.push([key, this.storage[key]]);
- });
- resolve(result);
- });
- }
-
- async write(key, data) {
- this.storage[key] = data;
- }
-
- async writeMulti(entries) {
- for (const [key, value] of entries) {
- this.storage[key] = value;
- }
- }
-
- remove(key) {
- delete this.storage[key];
- }
- clear() {
- this.storage = {};
- }
- getAllKeys() {
- return Object.keys(this.storage);
- }
-
- async encrypt(password, data) {
- return await this.crypto.encrypt(password, data, "text", "base64");
- }
-
- async encryptMulti(password, items) {
- return await this.crypto.encryptMulti(password, items, "text", "base64");
- }
-
- async decrypt(key, cipherData) {
- cipherData.format = "base64";
- return await this.crypto.decrypt(key, cipherData, "text");
- }
-
- async deriveCryptoKey(name, { password, salt }) {
- const keyData = await this.crypto.exportKey(password, salt);
- await this.write(`${name}@_k`, keyData.key);
- }
-
- async getCryptoKey(name) {
- const key = await this.read(`${name}@_k`);
- if (!key) return;
- return key;
- }
-
- async hash(password, email) {
- const APP_SALT = "oVzKtazBo7d8sb7TBvY9jw";
- return await this.crypto.hash(password, `${APP_SALT}${email}`);
- }
-
- async generateCryptoKey(password, salt) {
- return { password, salt };
- }
-}
diff --git a/packages/core/__mocks__/node-storage.mock.ts b/packages/core/__mocks__/node-storage.mock.ts
new file mode 100644
index 000000000..53d5b957a
--- /dev/null
+++ b/packages/core/__mocks__/node-storage.mock.ts
@@ -0,0 +1,108 @@
+/*
+This file is part of the Notesnook project (https://notesnook.com/)
+
+Copyright (C) 2023 Streetwriters (Private) Limited
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+import { Cipher, NNCrypto, SerializedKey } from "@notesnook/crypto";
+
+export class NodeStorageInterface {
+ storage = {};
+ crypto = new NNCrypto();
+
+ async write<T>(key: string, data: T): Promise<void> {
+ this.storage[key] = data;
+ }
+
+ async writeMulti<T>(entries: [key: string, data: T][]) {
+ for (const [key, value] of entries) {
+ this.storage[key] = value;
+ }
+ }
+
+ async readMulti<T>(keys: string[]): Promise<[string, T][]> {
+ const result: [string, T][] = [];
+ keys.forEach((key) => {
+ result.push([key, this.storage[key]]);
+ });
+ return result;
+ }
+
+ async read<T>(
+ key: string,
+ isArray?: boolean | undefined
+ ): Promise<T | undefined> {
+ return this.storage[key];
+ }
+
+ async remove(key: string): Promise<void> {
+ delete this.storage[key];
+ }
+
+ async clear(): Promise<void> {
+ this.storage = {};
+ }
+
+ async getAllKeys(): Promise<string[]> {
+ return Object.keys(this.storage);
+ }
+
+ async encrypt(key: SerializedKey, plainText: string) {
+ return await this.crypto.encrypt(key, plainText, "text", "base64");
+ }
+
+ async encryptMulti(key: SerializedKey, items: string[]) {
+ return await this.crypto.encryptMulti(key, items, "text", "base64");
+ }
+
+ decrypt(key: SerializedKey, cipherData: Cipher<"base64">): Promise<string> {
+ cipherData.format = "base64";
+ return this.crypto.decrypt(key, cipherData, "text");
+ }
+
+ decryptMulti(key: SerializedKey, items: Cipher<"base64">[]) {
+ items.forEach((c) => (c.format = "base64"));
+ return this.crypto.decryptMulti(key, items, "text");
+ }
+
+ async deriveCryptoKey(
+ name: string,
+ credentials: SerializedKey
+ ): Promise<void> {
+ const { password, salt } = credentials;
+ if (!password || !salt) return;
+ const keyData = await this.crypto.exportKey(password, salt);
+ await this.write(`${name}@_k`, keyData.key);
+ }
+
+ async hash(password: string, email: string): Promise<string> {
+ const APP_SALT = "oVzKtazBo7d8sb7TBvY9jw";
+ return await this.crypto.hash(password, `${APP_SALT}${email}`);
+ }
+
+ async getCryptoKey(name: string): Promise<string | undefined> {
+ const key = await this.read<string>(`${name}@_k`);
+ if (!key) return;
+ return key;
+ }
+
+ async generateCryptoKey(
+ password: string,
+ salt?: string | undefined
+ ): Promise<SerializedKey> {
+ return { password, salt };
+ }
+}
diff --git a/packages/core/package-lock.json b/packages/core/package-lock.json
index 230bba9b8..c17a4556d 100644
--- a/packages/core/package-lock.json
+++ b/packages/core/package-lock.json
@@ -36,7 +36,9 @@
"abortcontroller-polyfill": "^1.7.3",
"cross-env": "^7.0.3",
"dotenv": "^16.0.1",
+ "event-source-polyfill": "^1.0.31",
"eventsource": "^2.0.2",
+ "hash-wasm": "^4.9.0",
"isomorphic-fetch": "^3.0.0",
"jsdom": "^22.1.0",
"mockdate": "^3.0.5",
@@ -1391,6 +1393,12 @@
"@esbuild/win32-x64": "0.18.20"
}
},
+ "node_modules/event-source-polyfill": {
+ "version": "1.0.31",
+ "resolved": "https://registry.npmjs.org/event-source-polyfill/-/event-source-polyfill-1.0.31.tgz",
+ "integrity": "sha512-4IJSItgS/41IxN5UVAVuAyczwZF7ZIEsM1XAoUzIHA6A+xzusEZUutdXz2Nr+MQPLxfTiCvqE79/C8HT8fKFvA==",
+ "dev": true
+ },
"node_modules/event-target-shim": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz",
@@ -1504,6 +1512,12 @@
"node": ">=8"
}
},
+ "node_modules/hash-wasm": {
+ "version": "4.9.0",
+ "resolved": "https://registry.npmjs.org/hash-wasm/-/hash-wasm-4.9.0.tgz",
+ "integrity": "sha512-7SW7ejyfnRxuOc7ptQHSf4LDoZaWOivfzqw+5rpcQku0nHfmicPKE51ra9BiRLAmT8+gGLestr1XroUkqdjL6w==",
+ "dev": true
+ },
"node_modules/hast-util-parse-selector": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/hast-util-parse-selector/-/hast-util-parse-selector-3.1.1.tgz",
@@ -3882,6 +3896,12 @@
"@esbuild/win32-x64": "0.18.20"
}
},
+ "event-source-polyfill": {
+ "version": "1.0.31",
+ "resolved": "https://registry.npmjs.org/event-source-polyfill/-/event-source-polyfill-1.0.31.tgz",
+ "integrity": "sha512-4IJSItgS/41IxN5UVAVuAyczwZF7ZIEsM1XAoUzIHA6A+xzusEZUutdXz2Nr+MQPLxfTiCvqE79/C8HT8fKFvA==",
+ "dev": true
+ },
"event-target-shim": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz",
@@ -3967,6 +3987,12 @@
"integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
"dev": true
},
+ "hash-wasm": {
+ "version": "4.9.0",
+ "resolved": "https://registry.npmjs.org/hash-wasm/-/hash-wasm-4.9.0.tgz",
+ "integrity": "sha512-7SW7ejyfnRxuOc7ptQHSf4LDoZaWOivfzqw+5rpcQku0nHfmicPKE51ra9BiRLAmT8+gGLestr1XroUkqdjL6w==",
+ "dev": true
+ },
"hast-util-parse-selector": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/hast-util-parse-selector/-/hast-util-parse-selector-3.1.1.tgz",
diff --git a/packages/core/package.json b/packages/core/package.json
index e41fbf05e..3bcf1f952 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -17,7 +17,9 @@
"abortcontroller-polyfill": "^1.7.3",
"cross-env": "^7.0.3",
"dotenv": "^16.0.1",
+ "event-source-polyfill": "^1.0.31",
"eventsource": "^2.0.2",
+ "hash-wasm": "^4.9.0",
"isomorphic-fetch": "^3.0.0",
"jsdom": "^22.1.0",
"mockdate": "^3.0.5",
diff --git a/packages/core/src/api/sync/__tests__/sync.test.skip.js b/packages/core/src/api/sync/__tests__/sync.test.skip.js
deleted file mode 100644
index 3260d568a..000000000
--- a/packages/core/src/api/sync/__tests__/sync.test.skip.js
+++ /dev/null
@@ -1,399 +0,0 @@
-/*
-This file is part of the Notesnook project (https://notesnook.com/)
-
-Copyright (C) 2023 Streetwriters (Private) Limited
-
-This program is free software: you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation, either version 3 of the License, or
-(at your option) any later version.
-
-This program is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-GNU General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with this program. If not, see <http://www.gnu.org/licenses/>.
-*/
-
-import Database from "../../index";
-import { NodeStorageInterface } from "../../../../__mocks__/node-storage.mock";
-import FS from "../../../../__mocks__/fs.mock";
-import Compressor from "../../../../__mocks__/compressor.mock";
-import { CHECK_IDS, EV, EVENTS } from "../../../common";
-import EventSource from "eventsource";
-import { delay } from "../../../../__tests__/utils";
-
-jest.setTimeout(100 * 1000);
-
-test("case 1: device A & B should only download the changes from device C (no uploading)", async () => {
- const types = [];
- function onSyncProgress({ type }) {
- types.push(type);
- }
-
- const deviceA = await initializeDevice("deviceA");
- const deviceB = await initializeDevice("deviceB");
-
- deviceA.eventManager.subscribe(EVENTS.syncProgress, onSyncProgress);
- deviceB.eventManager.subscribe(EVENTS.syncProgress, onSyncProgress);
-
- const deviceC = await initializeDevice("deviceC");
-
- await deviceC.notes.add({ title: "new note 1" });
- await syncAndWait(deviceC, deviceC);
-
- expect(types.every((t) => t === "download")).toBe(true);
-
- await cleanup(deviceA, deviceB, deviceC);
-});
-
-test("case 3: Device A & B have unsynced changes but server has nothing", async () => {
- const deviceA = await initializeDevice("deviceA");
- const deviceB = await initializeDevice("deviceB");
-
- const note1Id = await deviceA.notes.add({
- title: "Test note from device A"
- });
- const note2Id = await deviceB.notes.add({
- title: "Test note from device B"
- });
-
- await syncAndWait(deviceA, deviceB);
-
- expect(deviceA.notes.note(note2Id)).toBeTruthy();
- expect(deviceB.notes.note(note1Id)).toBeTruthy();
- expect(deviceA.notes.note(note1Id)).toBeTruthy();
- expect(deviceB.notes.note(note2Id)).toBeTruthy();
-
- await cleanup(deviceA, deviceA);
-});
-
-// test(
-// "case 4: Device A's sync is interrupted halfway and Device B makes some changes afterwards and syncs.",
-// async () => {
-// const deviceA = await initializeDevice("deviceA");
-// const deviceB = await initializeDevice("deviceB");
-
-// const unsyncedNoteIds = [];
-// for (let i = 0; i < 10; ++i) {
-// const id = await deviceA.notes.add({
-// title: `Test note ${i} from device A`,
-// });
-// unsyncedNoteIds.push(id);
-// }
-
-// const half = unsyncedNoteIds.length / 2 + 1;
-// deviceA.eventManager.subscribe(
-// EVENTS.syncProgress,
-// async ({ type, current }) => {
-// if (type === "upload" && current === half) {
-// await deviceA.syncer.stop();
-// }
-// }
-// );
-
-// await expect(deviceA.sync(true)).rejects.toThrow();
-
-// let syncedNoteIds = [];
-// for (let i = 0; i < unsyncedNoteIds.length; ++i) {
-// const expectedNoteId = unsyncedNoteIds[i];
-// if (deviceB.notes.note(expectedNoteId))
-// syncedNoteIds.push(expectedNoteId);
-// }
-// expect(
-// syncedNoteIds.length === half - 1 || syncedNoteIds.length === half
-// ).toBe(true);
-
-// const deviceBNoteId = await deviceB.notes.add({
-// title: "Test note of case 4 from device B",
-// });
-
-// await deviceB.sync(true);
-
-// await syncAndWait(deviceA, deviceB);
-
-// expect(deviceA.notes.note(deviceBNoteId)).toBeTruthy();
-// expect(
-// unsyncedNoteIds
-// .map((id) => !!deviceB.notes.note(id))
-// .every((res) => res === true)
-// ).toBe(true);
-
-// await cleanup(deviceA, deviceB);
-// },
-//
-// );
-
-// test.only(
-// "case 5: Device A's sync is interrupted halfway and Device B makes changes on the same note's content that didn't get synced on Device A due to interruption.",
-// async () => {
-// const deviceA = await initializeDevice("deviceA");
-// const deviceB = await initializeDevice("deviceB");
-
-// const noteIds = [];
-// for (let i = 0; i < 10; ++i) {
-// const id = await deviceA.notes.add({
-// content: {
-// type: "tiptap",
-// data: `<p>deviceA=true</p>`,
-// },
-// });
-// noteIds.push(id);
-// }
-
-// await deviceA.sync(true);
-// await deviceB.sync(true);
-
-// const unsyncedNoteIds = [];
-// for (let id of noteIds) {
-// const noteId = await deviceA.notes.add({
-// id,
-// content: {
-// type: "tiptap",
-// data: `<p>deviceA=true+changed=true</p>`,
-// },
-// });
-// unsyncedNoteIds.push(noteId);
-// }
-
-// deviceA.eventManager.subscribe(
-// EVENTS.syncProgress,
-// async ({ type, total, current }) => {
-// const half = total / 2 + 1;
-// if (type === "upload" && current === half) {
-// await deviceA.syncer.stop();
-// }
-// }
-// );
-
-// await expect(deviceA.sync(true)).rejects.toThrow();
-
-// await delay(10 * 1000);
-
-// for (let id of unsyncedNoteIds) {
-// await deviceB.notes.add({
-// id,
-// content: {
-// type: "tiptap",
-// data: "<p>changes from device B</p>",
-// },
-// });
-// }
-
-// const error = await withError(async () => {
-// await deviceB.sync(true);
-// await deviceA.sync(true);
-// });
-
-// expect(error).not.toBeInstanceOf(NoErrorThrownError);
-// expect(error.message.includes("Merge")).toBeTruthy();
-
-// await cleanup(deviceA, deviceB);
-// },
-//
-// );
-
-test("issue: running force sync from device A makes device B always download everything", async () => {
- const deviceA = await initializeDevice("deviceA");
- const deviceB = await initializeDevice("deviceB");
-
- await syncAndWait(deviceA, deviceB, true);
-
- const handler = jest.fn();
- deviceB.eventManager.subscribe(EVENTS.syncProgress, handler);
-
- await deviceB.sync(true);
-
- expect(handler).not.toHaveBeenCalled();
-
- await cleanup(deviceB);
-});
-
-test("issue: colors are not properly created if multiple notes are synced together", async () => {
- const deviceA = await initializeDevice("deviceA", [CHECK_IDS.noteColor]);
- const deviceB = await initializeDevice("deviceB", [CHECK_IDS.noteColor]);
-
- const noteIds = [];
- for (let i = 0; i < 3; ++i) {
- const id = await deviceA.notes.add({
- content: {
- type: "tiptap",
- data: `<p>deviceA=true</p>`
- }
- });
- noteIds.push(id);
- }
-
- await syncAndWait(deviceA, deviceB);
-
- for (let noteId of noteIds) {
- await deviceA.notes.note(noteId).color("purple");
- expect(deviceB.notes.note(noteId)).toBeTruthy();
- expect(deviceB.notes.note(noteId).data.color).toBeUndefined();
- }
-
- await syncAndWait(deviceA, deviceB);
-
- await delay(2000);
-
- const purpleColor = deviceB.colors.tag("purple");
- expect(noteIds.every((id) => purpleColor.noteIds.indexOf(id) > -1)).toBe(
- true
- );
-
- await cleanup(deviceA, deviceB);
-});
-
-test("issue: new topic on device A gets replaced by the new topic on device B", async () => {
- const deviceA = await initializeDevice("deviceA");
- const deviceB = await initializeDevice("deviceB");
-
- const id = await deviceA.notebooks.add({ title: "Notebook 1" });
-
- await syncAndWait(deviceA, deviceB, false);
-
- expect(deviceB.notebooks.notebook(id)).toBeDefined();
-
- await deviceA.notebooks.notebook(id).topics.add("Topic 1");
-
- // to create a conflict
- await delay(1500);
-
- await deviceB.notebooks.notebook(id).topics.add("Topic 2");
-
- expect(deviceA.notebooks.notebook(id).topics.has("Topic 1")).toBeTruthy();
-
- expect(deviceB.notebooks.notebook(id).topics.has("Topic 2")).toBeTruthy();
-
- await syncAndWait(deviceA, deviceB, false);
-
- await delay(1000);
-
- await syncAndWait(deviceB, deviceB, false);
-
- expect(deviceA.notebooks.notebook(id).topics.has("Topic 1")).toBeTruthy();
- expect(deviceB.notebooks.notebook(id).topics.has("Topic 1")).toBeTruthy();
-
- expect(deviceA.notebooks.notebook(id).topics.has("Topic 2")).toBeTruthy();
- expect(deviceB.notebooks.notebook(id).topics.has("Topic 2")).toBeTruthy();
-
- await cleanup(deviceA, deviceB);
-});
-
-test("issue: remove notebook reference from notes that are removed from topic during merge", async () => {
- const deviceA = await initializeDevice("deviceA");
- const deviceB = await initializeDevice("deviceB");
-
- const id = await deviceA.notebooks.add({
- title: "Notebook 1",
- topics: ["Topic 1"]
- });
-
- await syncAndWait(deviceA, deviceB, false);
-
- expect(deviceB.notebooks.notebook(id)).toBeDefined();
-
- const noteA = await deviceA.notes.add({ title: "Note 1" });
- await deviceA.notes.addToNotebook({ id, topic: "Topic 1" }, noteA);
-
- expect(
- deviceA.notebooks.notebook(id).topics.topic("Topic 1").totalNotes
- ).toBe(1);
-
- await delay(2000);
-
- const noteB = await deviceB.notes.add({ title: "Note 2" });
- await deviceB.notes.addToNotebook({ id, topic: "Topic 1" }, noteB);
-
- expect(
- deviceB.notebooks.notebook(id).topics.topic("Topic 1").totalNotes
- ).toBe(1);
-
- await syncAndWait(deviceB, deviceA, false);
-
- expect(
- deviceA.notebooks.notebook(id).topics.topic("Topic 1").totalNotes
- ).toBe(1);
- expect(
- deviceB.notebooks.notebook(id).topics.topic("Topic 1").totalNotes
- ).toBe(1);
-
- expect(deviceA.notes.note(noteA).data.notebooks).toHaveLength(0);
-
- await cleanup(deviceA, deviceB);
-});
-
-/**
- *
- * @param {string} id
- * @returns {Promise<Database>}
- */
-async function initializeDevice(id, capabilities = []) {
- console.time("Init device");
- EV.subscribe(EVENTS.userCheckStatus, async (type) => {
- return {
- type,
- result: capabilities.indexOf(type) > -1
- };
- });
-
- const device = new Database(
- new NodeStorageInterface(),
- EventSource,
- FS,
- Compressor
- );
- // device.host({
- // API_HOST: "http://192.168.10.29:5264",
- // AUTH_HOST: "http://192.168.10.29:8264",
- // SSE_HOST: "http://192.168.10.29:7264",
- // ISSUES_HOST: "http://192.168.10.29:2624",
- // SUBSCRIPTIONS_HOST: "http://192.168.10.29:9264",
- // });
-
- await device.init(id);
-
- await device.user.login(
- process.env.EMAIL,
- process.env.PASSWORD,
- process.env.HASHED_PASSWORD
- );
-
- await device.user.resetUser(false);
-
- device.eventManager.subscribe(
- EVENTS.databaseSyncRequested,
- async (full, force) => {
- await device.sync(full, force);
- }
- );
-
- console.timeEnd("Init device");
- return device;
-}
-
-async function cleanup(...devices) {
- for (let device of devices) {
- await device.user.logout();
- device.eventManager.unsubscribeAll();
- }
- EV.unsubscribeAll();
-}
-
-/**
- *
- * @param {Database} deviceA
- * @param {Database} deviceB
- * @returns
- */
-function syncAndWait(deviceA, deviceB, force = false) {
- return new Promise((resolve) => {
- const ref = deviceB.eventManager.subscribe(EVENTS.syncCompleted, () => {
- ref.unsubscribe();
- resolve();
- });
- deviceA.sync(true, force);
- });
-}
diff --git a/packages/core/src/api/sync/index.js b/packages/core/src/api/sync/index.js
index 07898cd64..ebc775fe9 100644
--- a/packages/core/src/api/sync/index.js
+++ b/packages/core/src/api/sync/index.js
@@ -315,16 +315,16 @@ class Sync {
}
async stop(lastSynced) {
+ // refresh topic references
+ this.db.notes.topicReferences.rebuild();
+ // refresh monographs on sync completed
+ await this.db.monographs.init();
+
this.logger.info("Stopping sync", { lastSynced });
const storedLastSynced = await this.db.lastSynced();
if (lastSynced > storedLastSynced)
await this.db.storage.write("lastSynced", lastSynced);
this.db.eventManager.publish(EVENTS.syncCompleted);
-
- // refresh monographs on sync completed
- await this.db.monographs.init();
- // refresh topic references
- this.db.notes.topicReferences.rebuild();
}
async cancel() {
@@ -361,13 +361,19 @@ class Sync {
/**
* @private
*/
- onPushCompleted(lastSynced) {
+ async onPushCompleted(lastSynced) {
+ // refresh topic references
+ this.db.notes.topicReferences.rebuild();
+
this.db.eventManager.publish(
EVENTS.databaseSyncRequested,
false,
false,
lastSynced
);
+
+ // refresh monographs on sync completed
+ await this.db.monographs.init();
}
async processChunk(chunk, key, dbLastSynced, notify = false) {
@@ -412,8 +418,9 @@ class Sync {
}
const collectionType = this.itemTypeToCollection[chunk.type];
- if (collectionType && this.db[collectionType])
+ if (collectionType && this.db[collectionType]) {
await this.db[collectionType]._collection.setItems(items);
+ }
}
/**
diff --git a/packages/core/src/api/sync/merger.js b/packages/core/src/api/sync/merger.js
index b7053c75f..7b5dd1cbd 100644
--- a/packages/core/src/api/sync/merger.js
+++ b/packages/core/src/api/sync/merger.js
@@ -182,6 +182,7 @@ class Merger {
remoteItem.noteIds,
noteIds
);
+ remoteItem.remote = false;
}
return this._db.attachments.merge(localItem, remoteItem);
}
diff --git a/packages/core/src/collections/attachments.js b/packages/core/src/collections/attachments.js
index f42a3db57..21d77da13 100644
--- a/packages/core/src/collections/attachments.js
+++ b/packages/core/src/collections/attachments.js
@@ -50,6 +50,7 @@ export default class Attachments extends Collection {
remoteAttachment.noteIds,
localAttachment.noteIds
);
+ remoteAttachment.remote = false;
}
return remoteAttachment;
diff --git a/packages/core/src/collections/notebooks.js b/packages/core/src/collections/notebooks.js
index 989ab31c3..b64ed3146 100644
--- a/packages/core/src/collections/notebooks.js
+++ b/packages/core/src/collections/notebooks.js
@@ -26,6 +26,15 @@ import qclone from "qclone";
export default class Notebooks extends Collection {
merge(localNotebook, remoteNotebook, lastSyncedTimestamp) {
if (remoteNotebook.deleted) return remoteNotebook;
+
+ if (
+ localNotebook &&
+ (localNotebook.type === "trash" || localNotebook.deleted)
+ ) {
+ if (localNotebook.dateModified > remoteNotebook.dateModified) return;
+ return remoteNotebook;
+ }
+
if (localNotebook && localNotebook.topics?.length) {
let isChanged = false;
// merge new and old topics
@@ -82,7 +91,8 @@ export default class Notebooks extends Collection {
let notebook = {
...oldNotebook,
- ...notebookArg
+ ...notebookArg,
+ topics: oldNotebook?.topics || []
};
if (!notebook.title) throw new Error("Notebook must contain a title.");
@@ -102,8 +112,8 @@ export default class Notebooks extends Collection {
await this._collection.addItem(notebook);
- if (!oldNotebook) {
- await this.notebook(notebook).topics.add(...notebook.topics);
+ if (!oldNotebook && notebookArg.topics) {
+ await this.notebook(id).topics.add(...notebookArg.topics);
}
return id;
}
diff --git a/packages/core/src/collections/topics.js b/packages/core/src/collections/topics.js
index c6651fedf..0067114f1 100644
--- a/packages/core/src/collections/topics.js
+++ b/packages/core/src/collections/topics.js
@@ -86,7 +86,7 @@ export default class Topics {
notebook.topics.push(topic);
}
}
- return this._db.notebooks.add(notebook);
+ return this._db.notebooks._collection.updateItem(notebook);
}
/**
@@ -110,7 +110,8 @@ export default class Topics {
}
async delete(...topicIds) {
- let allTopics = qclone(this.all);
+ const notebook = qclone(this._db.notebooks.notebook(this._notebookId).data);
+ let allTopics = notebook.topics;
for (let topicId of topicIds) {
const topic = this.topic(topicId);
@@ -125,7 +126,7 @@ export default class Topics {
allTopics.splice(topicIndex, 1);
}
- await this._db.notebooks.add({ id: this._notebookId, topics: allTopics });
+ await this._db.notebooks._collection.updateItem(notebook);
}
}
diff --git a/packages/core/src/database/indexed-collection.js b/packages/core/src/database/indexed-collection.js
index 2d68b9fa9..6501230a3 100644
--- a/packages/core/src/database/indexed-collection.js
+++ b/packages/core/src/database/indexed-collection.js
@@ -109,7 +109,19 @@ export default class IndexedCollection {
}
setItems(items) {
- return this.indexer.writeMulti(items);
+ const entries = items.reduce((array, item) => {
+ if (!item) return array;
+
+ if (!item.remote) {
+ item.dateModified = Date.now();
+ item.synced = false;
+ }
+ delete item.remote;
+
+ array.push([item.id, item]);
+ return array;
+ }, []);
+ return this.indexer.writeMulti(entries);
}
async getEncryptionKey() {
diff --git a/packages/core/src/database/indexer.js b/packages/core/src/database/indexer.js
index 802f3f96f..af6f701b6 100644
--- a/packages/core/src/database/indexer.js
+++ b/packages/core/src/database/indexer.js
@@ -84,14 +84,12 @@ export default class Indexer extends Storage {
* @returns
*/
async writeMulti(items) {
- const entries = items.reduce((array, item) => {
- if (!item) return array;
- if (!this.indices.includes(item.id)) this.indices.push(item.id);
- array.push([this.makeId(item.id), item]);
- return array;
- }, []);
+ const entries = items.map(([id, item]) => {
+ if (!this.indices.includes(id)) this.indices.push(id);
+ return [this.makeId(id), item];
+ });
+ entries.push([this.type, this.indices]);
await super.writeMulti(entries);
- await super.write(this.type, this.indices);
}
async migrateIndices() {