@johnhenry/browsermesh-sync 0.0.1 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnhenry/browsermesh-sync",
3
- "version": "0.0.1",
3
+ "version": "0.1.0",
4
4
  "description": "CRDT sync engine, delta sync, file transfer, and collaboration for BrowserMesh",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
@@ -21,6 +21,9 @@
21
21
  "peerDependencies": {
22
22
  "@johnhenry/browsermesh-primitives": ">=0.0.1 <1.0.0"
23
23
  },
24
+ "devDependencies": {
25
+ "fake-indexeddb": "^6.2.5"
26
+ },
24
27
  "scripts": {
25
28
  "test": "node --import ./test/_setup-globals.mjs --test test/*.test.mjs"
26
29
  },
package/src/index.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  // browsermesh-sync — CRDT & sync
2
2
  export * from './sync.mjs';
3
+ export * from './storage-indexeddb.mjs';
3
4
  export * from './delta-sync.mjs';
4
5
  export * from './migration.mjs';
5
6
  export * from './files.mjs';
@@ -0,0 +1,159 @@
1
+ /**
2
+ * storage-indexeddb.mjs — IndexedDB-backed persistence adapter for
3
+ * `MeshSyncEngine`.
4
+ *
5
+ * Implements the same `save(docs)` / `load()` / `clear()` contract as
6
+ * `InMemorySyncStorage` (see `sync.mjs`), but persists documents to a real
7
+ * IndexedDB object store so a workspace's CRDT state survives a page
8
+ * reload.
9
+ *
10
+ * Modeled on `browsermesh-core`'s `IndexedDBIdentityStorage` (same
11
+ * "wrap IndexedDB's callback/event API in promises, one object store,
12
+ * open-or-create on first use" shape) but intentionally self-contained:
13
+ * `browsermesh-sync` does not depend on `browsermesh-core`.
14
+ *
15
+ * Usage:
16
+ * const storage = new IndexedDBSyncStorage({ dbName: 'my-app-mesh-sync' });
17
+ * const sync = new MeshSyncEngine({ storage });
18
+ * await sync.load(); // restore documents persisted in a prior session
19
+ * ...
20
+ * await sync.save(); // persist current documents
21
+ */
22
+
23
+ /**
24
+ * IndexedDB-backed storage adapter for `MeshSyncEngine`.
25
+ *
26
+ * Stores the full serialized document list under a single object store,
27
+ * keyed by each document's `id`. `save()` replaces the entire stored set
28
+ * (matching `InMemorySyncStorage`'s "last write wins, whole-set" semantics)
29
+ * so documents removed locally since the last save do not linger.
30
+ *
31
+ * Falls back gracefully (throws a clear error) when IndexedDB is
32
+ * unavailable, mirroring `IndexedDBIdentityStorage`.
33
+ */
34
+ export class IndexedDBSyncStorage {
35
+ /** @type {string} */
36
+ #dbName;
37
+
38
+ /** @type {string} */
39
+ #storeName;
40
+
41
+ /** @type {IDBDatabase|null} */
42
+ #db = null;
43
+
44
+ /**
45
+ * @param {object} [opts]
46
+ * @param {string} [opts.dbName='mesh-sync'] IndexedDB database name.
47
+ * Configurable so multiple `MeshSyncEngine`s in one page (e.g. distinct
48
+ * workspaces/tenants) can use separate databases without colliding.
49
+ * @param {string} [opts.storeName='documents'] Object store name within
50
+ * the database.
51
+ */
52
+ constructor(opts = {}) {
53
+ this.#dbName = opts.dbName || 'mesh-sync';
54
+ this.#storeName = opts.storeName || 'documents';
55
+ }
56
+
57
+ /**
58
+ * Open the IndexedDB database, creating the object store on first use.
59
+ * Safe to call multiple times — subsequent calls are no-ops once open.
60
+ * @returns {Promise<void>}
61
+ */
62
+ async open() {
63
+ if (this.#db) return;
64
+ if (typeof indexedDB === 'undefined') {
65
+ throw new Error('IndexedDB not available');
66
+ }
67
+
68
+ const storeName = this.#storeName;
69
+
70
+ return new Promise((resolve, reject) => {
71
+ const request = indexedDB.open(this.#dbName, 1);
72
+
73
+ request.onupgradeneeded = (event) => {
74
+ const db = event.target.result;
75
+ if (!db.objectStoreNames.contains(storeName)) {
76
+ db.createObjectStore(storeName, { keyPath: 'id' });
77
+ }
78
+ };
79
+
80
+ request.onsuccess = (event) => {
81
+ this.#db = event.target.result;
82
+ this.#db.onclose = () => { this.#db = null; };
83
+ resolve();
84
+ };
85
+
86
+ request.onerror = () => {
87
+ reject(new Error(`Failed to open IndexedDB "${this.#dbName}": ${request.error?.message}`));
88
+ };
89
+ });
90
+ }
91
+
92
+ /**
93
+ * Persist the full set of documents, replacing whatever was previously
94
+ * stored (matches `InMemorySyncStorage.save()`'s whole-set-replace
95
+ * semantics).
96
+ * @param {object[]} docs Serialized `SyncDocument`s (each with an `id`).
97
+ * @returns {Promise<void>}
98
+ */
99
+ async save(docs) {
100
+ if (!this.#db) await this.open();
101
+ // Deep-clone through JSON to decouple from live objects, and to
102
+ // guarantee only structured-cloneable data reaches IndexedDB.
103
+ const records = JSON.parse(JSON.stringify(docs));
104
+
105
+ return new Promise((resolve, reject) => {
106
+ const tx = this.#db.transaction(this.#storeName, 'readwrite');
107
+ const store = tx.objectStore(this.#storeName);
108
+ store.clear();
109
+ for (const record of records) {
110
+ store.put(record);
111
+ }
112
+ tx.oncomplete = () => resolve();
113
+ tx.onerror = () => reject(new Error(`Failed to save sync documents to "${this.#dbName}": ${tx.error?.message}`));
114
+ tx.onabort = () => reject(new Error(`Save transaction aborted for "${this.#dbName}": ${tx.error?.message}`));
115
+ });
116
+ }
117
+
118
+ /**
119
+ * Load all persisted documents.
120
+ * @returns {Promise<object[]|null>} The stored documents, or `null` when
121
+ * nothing has been saved (mirrors `InMemorySyncStorage.load()`).
122
+ */
123
+ async load() {
124
+ if (!this.#db) await this.open();
125
+ return new Promise((resolve, reject) => {
126
+ const tx = this.#db.transaction(this.#storeName, 'readonly');
127
+ const store = tx.objectStore(this.#storeName);
128
+ const req = store.getAll();
129
+ req.onsuccess = () => {
130
+ const result = req.result;
131
+ resolve(result && result.length > 0 ? result : null);
132
+ };
133
+ req.onerror = () => reject(new Error(`Failed to load sync documents from "${this.#dbName}": ${req.error?.message}`));
134
+ });
135
+ }
136
+
137
+ /**
138
+ * Empty the object store.
139
+ * @returns {Promise<void>}
140
+ */
141
+ async clear() {
142
+ if (!this.#db) await this.open();
143
+ return new Promise((resolve, reject) => {
144
+ const tx = this.#db.transaction(this.#storeName, 'readwrite');
145
+ const store = tx.objectStore(this.#storeName);
146
+ const req = store.clear();
147
+ req.onsuccess = () => resolve();
148
+ req.onerror = () => reject(new Error(`Failed to clear sync documents in "${this.#dbName}": ${req.error?.message}`));
149
+ });
150
+ }
151
+
152
+ /** Close the database connection, if open. */
153
+ close() {
154
+ if (this.#db) {
155
+ this.#db.close();
156
+ this.#db = null;
157
+ }
158
+ }
159
+ }