Repository navigation
Expand file tree
/
Copy pathstore.js
More file actions
2483 lines (2212 loc) · 111 KB
/
Copy pathstore.js
File metadata and controls
2483 lines (2212 loc) · 111 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { openDb, openTransaction, awaitTransactionComplete, requestToPromise } from './db.js';
import { LIMITS } from './constants.js';
import { createStamp, migrateNoteStamps, computeTextHash } from './sync-engine.js';
let conn = null;
let listeners = new Set();
let memoryFallback = null;
let persistRequested = false;
function emit(event) {
for (const handler of listeners) {
// A faulty subscriber must not be able to break a save: emit() is on
// saveDraft's synchronous path, which is required never to throw.
try {
handler(event);
} catch (error) {
console.error('heldnote: event subscriber threw', error);
}
}
}
export function __emitForTests(event) {
emit(event);
}
export function subscribe(handler) {
listeners.add(handler);
return () => listeners.delete(handler);
}
export async function open({ dbName } = {}) {
const result = await openDb({
name: dbName,
onVersionChange: handleVersionChange,
});
if (result.outcome === 'version-error') {
throw Object.assign(new Error('This browser holds newer data than this page. Reload to update.'), { code: 'version-mismatch' });
}
if (result.outcome !== 'ok') {
// Reused, not rebuilt: if some caller retries open() after a first failure,
// rebuilding would throw away everything typed into the memory session so
// far — which is the one thing this mode exists to hold on to.
memoryFallback = memoryFallback || newMemoryStore();
const reason = result.outcome === 'blocked' ? 'blocked' : result.outcome === 'corrupt' ? 'corrupt' : 'unavailable';
emit({ type: 'storage-unavailable', reason });
return { available: false, retention: 'unknown', schemaVersion: 1, reason };
}
conn = result.db;
// A previous open() may have failed and left a memory session holding text
// the user has already typed. Storage working now does not make that text
// less real, so it is written through to disk before memory mode is turned
// off — clearing the flag first would strand every one of those notes behind
// a guard nothing reads any more. A migration that fails leaves memory mode
// on rather than dropping the notes: honest degradation beats a silent loss.
if (memoryFallback) {
try {
await migrateMemorySessionToDisk();
memoryFallback = null;
} catch (error) {
console.error('heldnote: could not migrate the memory session to storage', error);
// Close before dropping the handle. Left open and unreachable, this
// connection would block another tab's upgrade and block deleteDatabase
// — able to cause the very `blocked` outcome that forces memory mode.
// close() cannot clean it up later either: it is guarded on `conn`.
result.db.close();
conn = null;
emit({ type: 'storage-unavailable', reason: 'migration-failed' });
return { available: false, retention: 'unknown', schemaVersion: 1, reason: 'migration-failed' };
}
}
// Fire-and-forget: store-api.md says maintenance is "called at startup", but
// it was previously only ever reached from a quota-failure retry, so pruning
// happened exclusively AFTER a write had already failed. open() must not wait
// for it (boot latency is the whole point of an app that opens instantly),
// and must not be able to fail because of it — a pruning pass that throws is
// logged and otherwise ignored, exactly as it is on the retry paths.
runMaintenance().catch((error) => {
console.error('heldnote: startup maintenance failed', error);
});
return { available: true, retention: 'unknown', schemaVersion: 1 };
}
// Runs when another tab's upgrade forces this connection closed. db.js has
// already called db.close() by the time this is reached, so the handle in
// `conn` is dead. Dropping it is what makes every subsequent call fail through
// activeConn()'s typed `storage-unavailable` error instead of a raw TypeError
// (null) or InvalidStateError (closed handle) from deep inside a transaction.
//
// This deliberately does NOT fail over to memoryFallback: the notes that exist
// are on disk, and an empty in-memory store would make the whole list appear to
// vanish — a far more alarming lie than an honest "storage is not available,
// reload". The event tells the UI to say exactly that.
function handleVersionChange() {
conn = null;
emit({ type: 'storage-unavailable', reason: 'version-change' });
}
// The browser fires versionchange only when a second connection requests a
// higher version, which a single-page test cannot stage portably. This calls
// the very handler db.js is wired to, so what the test exercises is the
// production path, not a re-implementation of it.
export function __simulateVersionChangeForTests() {
handleVersionChange();
}
// Every persisted-path transaction goes through this instead of touching `conn`
// directly. Before open(), and after the connection is force-closed by another
// tab's upgrade (see onVersionChange above), `conn` is null — and
// openTransaction(null, ...) throws a raw TypeError from db.js that no caller
// can branch on. This turns that into the documented StoreError code.
function activeConn() {
if (!conn) {
throw Object.assign(new Error('storage is not available'), { code: 'storage-unavailable' });
}
return conn;
}
export function isMemoryFallback() {
return Boolean(memoryFallback);
}
export function hasMemoryOnlyNotes() {
return memoryOnlyText.size > 0;
}
function metaValue(record) {
if (!record) return undefined;
return Object.prototype.hasOwnProperty.call(record, 'value') ? record.value : record;
}
export async function getMeta(key) {
if (memoryFallback) return metaValue(memoryFallback.meta.get(key));
const tx = openTransaction(activeConn(), ['meta'], 'readonly');
return metaValue(await requestToPromise(tx.objectStore('meta').get(key)));
}
export async function setMeta(key, value) {
if (memoryFallback) {
memoryFallback.meta.set(key, { key, value });
return;
}
const tx = openTransaction(activeConn(), ['meta'], 'readwrite', { durability: 'strict' });
tx.objectStore('meta').put({ key, value });
await awaitTransactionComplete(tx);
}
export async function batchSetMeta(entries) {
if (memoryFallback) {
for (const entry of entries) memoryFallback.meta.set(entry.key, { ...entry });
return;
}
const tx = openTransaction(activeConn(), ['meta'], 'readwrite', { durability: 'strict' });
for (const entry of entries) tx.objectStore('meta').put({ ...entry });
await awaitTransactionComplete(tx);
}
export async function deleteMeta(key) {
if (memoryFallback) {
memoryFallback.meta.delete(key);
return;
}
const tx = openTransaction(activeConn(), ['meta'], 'readwrite', { durability: 'strict' });
tx.objectStore('meta').delete(key);
await awaitTransactionComplete(tx);
}
async function ensureDeviceIdInStore(metaStore) {
const existing = await requestToPromise(metaStore.get('deviceId'));
const value = metaValue(existing);
if (typeof value === 'string' && value) return value;
const id = crypto && typeof crypto.randomUUID === 'function'
? crypto.randomUUID()
: synchronousFallbackDeviceId();
metaStore.put({ key: 'deviceId', value: id });
return id;
}
export async function getDeviceId() {
if (memoryFallback) {
const existing = metaValue(memoryFallback.meta.get('deviceId'));
if (existing) return existing;
const id = crypto && typeof crypto.randomUUID === 'function'
? crypto.randomUUID()
: synchronousFallbackDeviceId();
memoryFallback.meta.set('deviceId', { key: 'deviceId', value: id });
return id;
}
const tx = openTransaction(activeConn(), ['meta'], 'readwrite', { durability: 'strict' });
const id = await ensureDeviceIdInStore(tx.objectStore('meta'));
await awaitTransactionComplete(tx);
return id;
}
export async function getHLCState() {
const deviceId = await getDeviceId();
const existing = await getMeta('hlc');
if (existing && Number.isFinite(existing.w) && Number.isFinite(existing.c)) {
return { w: existing.w, c: existing.c, d: deviceId };
}
return { w: 0, c: 0, d: deviceId };
}
export async function absorbRemoteStamps(stamps) {
if (memoryFallback) return { clockWarning: false };
const tx = openTransaction(activeConn(), ['meta'], 'readwrite', { durability: 'strict' });
const metaStore = tx.objectStore('meta');
const deviceId = await ensureDeviceIdInStore(metaStore);
const stored = metaValue(await requestToPromise(metaStore.get('hlc')));
const state = stored && Number.isFinite(stored.w) && Number.isFinite(stored.c)
? { w: stored.w, c: stored.c, d: deviceId }
: { w: 0, c: 0, d: deviceId };
let clockWarning = false;
const now = Date.now();
for (const stamp of stamps) {
if (!stamp || !Number.isFinite(stamp.w) || !Number.isFinite(stamp.c)) continue;
if (stamp.w - now > 24 * 60 * 60 * 1000) clockWarning = true;
if (stamp.w > state.w) {
state.w = stamp.w;
state.c = stamp.c;
} else if (stamp.w === state.w) {
state.c = Math.max(state.c, stamp.c);
}
}
metaStore.put({ key: 'hlc', value: state });
await awaitTransactionComplete(tx);
return { clockWarning };
}
async function mutationStamp(metaStore) {
const deviceId = await ensureDeviceIdInStore(metaStore);
const storedHlc = metaValue(await requestToPromise(metaStore.get('hlc')));
const state = storedHlc && Number.isFinite(storedHlc.w) && Number.isFinite(storedHlc.c)
? { w: storedHlc.w, c: storedHlc.c, d: deviceId }
: { w: 0, c: 0, d: deviceId };
const stamp = createStamp(state);
metaStore.put({ key: 'hlc', value: state });
const storedDirty = metaValue(await requestToPromise(metaStore.get('dirtyGen')));
metaStore.put({ key: 'dirtyGen', value: (Number.isFinite(storedDirty) ? storedDirty : 0) + 1 });
return stamp;
}
function ensureNoteStamps(record, deviceId) {
if (!record.stamps) record.stamps = migrateNoteStamps(record.updatedAt, deviceId);
return record.stamps;
}
export async function close() {
if (conn) {
conn.close();
conn = null;
}
memoryFallback = null;
listeners = new Set();
// Revision bookkeeping describes the connection that is going away. Keeping
// it would let flush() answer "already durable" from a previous database
// after a delete/reopen or an import that reuses note ids.
draftQueues.clear();
revCounters.clear();
durableRevs.clear();
lastVersionText.clear();
memoryOnlyText.clear();
versionCommitsStopped = false;
persistRequested = false;
}
async function requestPersistenceOnce() {
if (persistRequested) return;
persistRequested = true;
if (!navigator.storage || !navigator.storage.persist) return;
const granted = await navigator.storage.persist().catch(() => false);
emit({ type: 'retention-changed', retention: granted ? 'persistent' : 'best-effort' });
}
let fallbackDeviceId = null;
function synchronousFallbackDeviceId() {
if (fallbackDeviceId) return fallbackDeviceId;
try {
fallbackDeviceId = localStorage.getItem('heldnote-device-id-fallback');
if (!fallbackDeviceId) {
fallbackDeviceId = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
localStorage.setItem('heldnote-device-id-fallback', fallbackDeviceId);
}
} catch (_e) {
fallbackDeviceId = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
}
return fallbackDeviceId;
}
function newId() {
if (crypto && typeof crypto.randomUUID === 'function') return crypto.randomUUID();
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}-${synchronousFallbackDeviceId()}`;
}
function toNoteSummary(record) {
return {
id: record.id,
title: record.title,
updatedAt: record.updatedAt,
pinned: record.pinKey === 1,
deletedAt: record.isDeleted === 1 ? record.deletedAt : null,
};
}
export async function createNote() {
if (memoryFallback) return memoryCreateNote();
const id = newId();
const now = Date.now();
const noteRecord = {
id, title: 'Untitled.txt', createdAt: now, updatedAt: now, localRev: 0, noteRev: 1,
pinned: false, pinKey: 0, isDeleted: 0,
};
const draftRecord = { noteId: id, text: '', localRev: 0, savedAt: now, byteLength: 0 };
const tx = openTransaction(activeConn(), ['notes', 'drafts', 'meta'], 'readwrite', { durability: 'strict' });
const stamp = await mutationStamp(tx.objectStore('meta'));
noteRecord.stamps = {
text: { ...stamp }, title: { ...stamp },
pinned: { ...stamp }, lifecycle: { ...stamp },
};
tx.objectStore('notes').put(noteRecord);
tx.objectStore('drafts').put(draftRecord);
await awaitTransactionComplete(tx);
emit({ type: 'sync-dirty', noteId: id });
return { id, title: 'Untitled.txt', text: '', createdAt: now, updatedAt: now, pinned: false, deletedAt: null, localRev: 0 };
}
export async function listNotes({ query, includeTrashed = false, limit, before } = {}) {
if (memoryFallback) return memoryListNotes({ query, includeTrashed, limit, before });
const tx = openTransaction(activeConn(), ['notes', 'drafts'], 'readonly');
const notesStore = tx.objectStore('notes');
const draftsStore = tx.objectStore('drafts');
const results = [];
const lowerQuery = query ? query.toLowerCase() : null;
await new Promise((resolve, reject) => {
const req = notesStore.openCursor();
req.onsuccess = async () => {
const cursor = req.result;
if (!cursor) { resolve(); return; }
const record = cursor.value;
const isTrashed = record.isDeleted === 1;
if (!includeTrashed && isTrashed) {
cursor.continue();
return;
}
// Matching covers title AND body text (PRD requirement). The title
// check is free (already in hand from the cursor); only fall through to
// a second store read of the draft's body when the title alone doesn't
// satisfy the query, so a title match never pays for a drafts lookup.
// `record.title || ''` is belt-and-braces against a record whose title is
// not a string. parseImportFile now rejects such a file outright, but a
// record written before that validation existed (or by any path not yet
// imagined) would otherwise throw here — inside an async cursor handler,
// where the throw becomes an unhandled rejection rather than reaching the
// surrounding reject(), leaving listNotes() pending forever. A hung note
// list is a far worse outcome than an untitled note failing to match.
let matchesQuery = !lowerQuery || String(record.title || '').toLowerCase().includes(lowerQuery);
if (!matchesQuery) {
// Explicit try/catch: this handler is async, so a rejection from the
// awaited request would otherwise become an unhandled rejection
// instead of reaching the surrounding Promise's reject() — leaving
// listNotes()'s own await pending forever instead of failing loudly.
try {
const draftRecord = await requestToPromise(draftsStore.get(record.id));
matchesQuery = !!draftRecord && String(draftRecord.text || '').toLowerCase().includes(lowerQuery);
} catch (error) {
reject(error);
return;
}
}
if (matchesQuery) {
results.push(toNoteSummary(record));
}
cursor.continue();
};
req.onerror = () => reject(req.error);
});
results.sort((a, b) => {
if (a.pinned !== b.pinned) return a.pinned ? -1 : 1;
return b.updatedAt - a.updatedAt;
});
const sliced = before ? results.filter((r) => r.updatedAt < before) : results;
return typeof limit === 'number' ? sliced.slice(0, limit) : sliced;
}
const revCounters = new Map();
const durableRevs = new Map();
export async function getNote(id) {
if (memoryFallback) return memoryGetNote(id);
const tx = openTransaction(activeConn(), ['notes', 'drafts'], 'readonly');
const noteRecord = await requestToPromise(tx.objectStore('notes').get(id));
const draftRecord = await requestToPromise(tx.objectStore('drafts').get(id));
if (!noteRecord || !draftRecord) {
throw Object.assign(new Error(`note ${id} not found`), { code: 'not-found' });
}
revCounters.set(id, Math.max(revCounters.get(id) || 0, draftRecord.localRev));
durableRevs.set(id, Math.max(durableRevs.get(id) || 0, draftRecord.localRev));
return {
id: noteRecord.id,
title: noteRecord.title,
text: draftRecord.text,
createdAt: noteRecord.createdAt,
updatedAt: noteRecord.updatedAt,
pinned: noteRecord.pinKey === 1,
deletedAt: noteRecord.isDeleted === 1 ? noteRecord.deletedAt : null,
localRev: draftRecord.localRev,
};
}
async function updateNoteFields(id, fields, stampField) {
if (memoryFallback) return memoryUpdateNoteFields(id, fields);
const tx = openTransaction(activeConn(), ['notes', 'meta'], 'readwrite', { durability: 'strict' });
const store = tx.objectStore('notes');
const record = await requestToPromise(store.get(id));
if (!record) throw Object.assign(new Error(`note ${id} not found`), { code: 'not-found' });
const stamp = await mutationStamp(tx.objectStore('meta'));
ensureNoteStamps(record, stamp.d)[stampField] = stamp;
Object.assign(record, fields);
record.noteRev = (record.noteRev || 0) + 1;
store.put(record);
await awaitTransactionComplete(tx);
emit({ type: 'note-changed', noteId: id });
emit({ type: 'sync-dirty', noteId: id });
}
export async function setPinned(id, on) {
await updateNoteFields(id, { pinned: on, pinKey: on ? 1 : 0 }, 'pinned');
}
export async function trashNote(id) {
await updateNoteFields(id, { isDeleted: 1, deletedAt: Date.now() }, 'lifecycle');
}
// The title is a user-set filename (e.g. "notes.md") — independent of the text,
// never derived from it (see docs/filename-plan.md). This is the ONLY writer of
// title after createNote; the draft and restore paths deliberately leave it
// alone. Sanitizing here (not just in the UI) makes the store the single choke
// point: path separators and control characters can never reach a record.
export async function renameNote(id, title) {
if (typeof title !== 'string') {
throw Object.assign(new Error('title must be a string'), { code: 'invalid-title' });
}
const clean = title.replace(/[/\\\u0000-\u001F]/g, '').trim().slice(0, 200);
if (!clean) {
throw Object.assign(new Error('title must not be empty'), { code: 'invalid-title' });
}
// updatedAt bumps on purpose: a rename is a deliberate modification, and the
// list sorts by updatedAt. localRev is NOT touched — it is the draft-revision
// counter, and moving it here would corrupt flush()'s durability answers.
await updateNoteFields(id, { title: clean, updatedAt: Date.now() }, 'title');
}
export async function restoreNote(id) {
if (memoryFallback) return memoryRestoreNote(id);
const tx = openTransaction(activeConn(), ['notes', 'meta'], 'readwrite', { durability: 'strict' });
const noteStore = tx.objectStore('notes');
const record = await requestToPromise(noteStore.get(id));
if (!record) throw Object.assign(new Error(`note ${id} not found`), { code: 'not-found' });
const stamp = await mutationStamp(tx.objectStore('meta'));
ensureNoteStamps(record, stamp.d).lifecycle = stamp;
record.isDeleted = 0;
delete record.deletedAt;
record.noteRev = (record.noteRev || 0) + 1;
noteStore.put(record);
await awaitTransactionComplete(tx);
emit({ type: 'note-changed', noteId: id });
emit({ type: 'sync-dirty', noteId: id });
}
// Purges every note currently in the trash. Deliberately a loop over
// purgeNote rather than one wide transaction: purgeNote is what writes a
// note's tombstone in the SAME transaction as its deletion, and that atomicity
// is the whole reason a purge propagates to other devices instead of the note
// resurrecting. One failure (a quota fault, a note purged from another tab
// mid-loop) must not abandon the rest, so failures are collected and the
// caller is told what actually went; a partial empty is still a correct state.
export async function emptyTrash() {
const all = await listNotes({ includeTrashed: true, limit: 100000 });
const trashed = all.filter((note) => note.deletedAt != null);
const purged = [];
const failed = [];
for (const note of trashed) {
try {
await purgeNote(note.id);
purged.push(note.id);
} catch (error) {
failed.push({ id: note.id, error });
}
}
return { purged, failed };
}
export async function purgeNote(id) {
if (memoryFallback) return memoryPurgeNote(id);
const tx = openTransaction(activeConn(), ['notes', 'drafts', 'versions', 'meta'], 'readwrite', { durability: 'strict' });
const stamp = await mutationStamp(tx.objectStore('meta'));
tx.objectStore('notes').delete(id);
tx.objectStore('drafts').delete(id);
tx.objectStore('meta').put({ key: `tombstone:${id}`, id, stamp });
const versionsStore = tx.objectStore('versions');
await new Promise((resolve, reject) => {
const range = IDBKeyRange.bound([id, -Infinity], [id, Infinity]);
const req = versionsStore.openCursor(range);
req.onsuccess = () => {
const cursor = req.result;
if (!cursor) { resolve(); return; }
cursor.delete();
cursor.continue();
};
req.onerror = () => reject(req.error);
});
await awaitTransactionComplete(tx);
emit({ type: 'note-changed', noteId: id });
emit({ type: 'sync-dirty', noteId: id });
}
// --- draft layer: serialized, coalescing writer -----------------------------
//
// At most one draft transaction per note is in flight at any time. While one is
// running, further keystrokes only replace the queued payload, so the writer
// always persists the newest text and never a stale intermediate one. Because
// an accepted revision is written on the very next turn (no debounce), the
// wall-clock budget of LIMITS.DRAFT_FLUSH_MAX_MS covers the whole path from
// saveDraft() to the transaction's `complete` event.
const draftQueues = new Map(); // noteId -> { pendingText, pendingRev, inFlight, waiters, lastFailure }
// --- quota exhaustion: prune-retry-once, then degrade -----------------------
//
// A quota-class error (QuotaExceededError, or the AbortError the fault-
// injection seam produces) gets exactly one prune-and-retry before this code
// gives up on the attempt in front of it. The two call sites degrade
// differently because the two failures mean different things:
//
// - the DRAFT path is the one that must never silently stop working, so a
// draft write that still fails after prune-and-retry goes memory-only for
// that note: the in-memory buffer (memoryOnlyText) keeps the text
// available for copy/export, ordinary 'saved' events stop, and a
// 'memory-only' event fires instead.
// - the VERSION-COMMIT path is expendable: drafts must keep saving even
// after history stops. A version write that still fails after retry sets
// versionCommitsStopped so no further commitVersion() call even attempts
// a write (it returns null immediately), and a 'quota-warning' fires once
// at the moment history commits stop.
//
// memoryOnlyText is connection-scoped like durableRevs etc. and is cleared in
// close(); versionCommitsStopped is a whole-connection latch (once history
// commits are known to be unsalvageable for the current storage pressure,
// there is no per-note distinction worth making) and is reset in close() too.
const memoryOnlyText = new Map(); // noteId -> last text that could not be made durable
let versionCommitsStopped = false;
export function getMemoryOnlyText(noteId) {
return memoryOnlyText.get(noteId);
}
function isQuotaError(error) {
return Boolean(error) && (error.name === 'QuotaExceededError' || error.name === 'AbortError');
}
// LIMITS.MAX_NOTE_SIZE_BYTES is the "tested maximum note size" the design
// adopted in place of the earlier "no size limit" position. It was defined but
// referenced nowhere, which is the worst of both worlds: a documented guarantee
// with no enforcement behind it. Enforced on the draft path only — that is the
// one path a user can drive past the cap by typing (or pasting), and it is the
// path where refusing early keeps a single oversized note from being the reason
// every other note stops saving.
function assertWithinSizeLimit(noteId, byteLength) {
if (byteLength <= LIMITS.MAX_NOTE_SIZE_BYTES) return;
throw Object.assign(
new Error(`note ${noteId} is ${byteLength} bytes, over the ${LIMITS.MAX_NOTE_SIZE_BYTES}-byte maximum`),
{ code: 'note-too-large', byteLength, limit: LIMITS.MAX_NOTE_SIZE_BYTES },
);
}
function queueFor(noteId) {
let q = draftQueues.get(noteId);
if (!q) {
q = { pendingText: null, pendingRev: null, inFlight: false, restoring: false, waiters: [], lastFailure: null };
draftQueues.set(noteId, q);
}
return q;
}
export function saveDraft(id, text) {
if (memoryFallback) return memorySaveDraft(id, text);
const nextRev = (revCounters.get(id) || 0) + 1;
revCounters.set(id, nextRev);
const q = queueFor(id);
q.pendingText = text;
q.pendingRev = nextRev;
// A newer payload is on its way, so an earlier failure no longer decides
// anything: the write about to run can still make this text durable.
q.lastFailure = null;
emit({ type: 'saving', noteId: id, requestedRev: nextRev });
// While a restore holds the lock, the payload is only queued: restoreVersion
// starts the write itself once its own transaction has committed, so this
// text lands on top of the restored text instead of racing it.
if (!q.inFlight && !q.restoring) {
runDraftWrite(id);
}
return nextRev;
}
function resolveWaiters(noteId, receipt) {
const q = queueFor(noteId);
q.lastFailure = receipt.error ? { rev: receipt.requestedRev, error: receipt.error } : null;
const remaining = [];
for (const waiter of q.waiters) {
if (receipt.durableRev >= waiter.rev) {
// The revision this caller asked about is durable, so the promise is
// kept even if some later revision in the same batch failed.
waiter.resolve(receipt);
} else if (receipt.error && receipt.requestedRev >= waiter.rev) {
// The write that failed already carried this waiter's text (coalescing
// means a newer payload supersedes the older one), so nothing still
// queued can make it durable. Reject rather than wait forever.
waiter.reject(receipt.error);
} else {
remaining.push(waiter);
}
}
q.waiters = remaining;
}
export function flush(noteId, throughRev) {
const q = queueFor(noteId);
const durableRev = durableRevs.get(noteId) || 0;
if (durableRev >= throughRev) {
// Already durable: no future transaction is left to wait on, and waiters
// are only ever settled by one completing.
return Promise.resolve({ noteId, requestedRev: throughRev, durableRev, completedAt: Date.now() });
}
if (q.lastFailure && q.lastFailure.rev >= throughRev) {
// The write carrying this revision already failed and no newer payload has
// been queued since, so waiting would never end.
return Promise.reject(q.lastFailure.error);
}
return new Promise((resolve, reject) => {
q.waiters.push({ rev: throughRev, resolve, reject });
});
}
async function runDraftWrite(noteId) {
const q = queueFor(noteId);
q.inFlight = true;
// Re-checked once per iteration: an iteration that started before a restore
// took the lock is safe (its transaction was created first, so it commits
// ahead of the restore and its text is what the restore's draft read sees),
// but a *new* iteration started under the lock would create its transaction
// after that draft read and before the restore's write, which is exactly the
// interleaving that loses text. Exiting here leaves the payload in
// pendingText with inFlight false, which is what restoreVersion's finally
// expects to find.
while (q.pendingText !== null && !q.restoring) {
const text = q.pendingText;
const rev = q.pendingRev;
// Read at dequeue, before any await, so it names the generation this write
// belongs to. restoreVersion() bumps the generation before opening its own
// transaction; the comparison below is what stops a write dequeued under
// the old generation from publishing itself over a restore.
const generationAtQueue = currentGeneration(noteId);
q.pendingText = null;
q.pendingRev = null;
const now = Date.now();
let receipt;
try {
// Kept inside the try: a throw here (a non-string payload reaching
// TextEncoder, say) would otherwise escape the loop, skipping both
// resolveWaiters and the inFlight reset, and wedge this note's queue.
const byteLength = new TextEncoder().encode(text).length;
if (currentGeneration(noteId) !== generationAtQueue) {
throw Object.assign(new Error('stale write superseded by a restore'), { code: 'stale-generation' });
}
// The size cap is enforced HERE — after coalescing, before any
// transaction is opened — so nothing partial is ever written and only
// the newest text is ever measured. Throwing (rather than returning)
// routes this through the one place that already owns receipt building,
// waiter settlement and the inFlight reset for every other failure.
//
// It sits BELOW the generation fence deliberately: a payload a restore
// has already superseded is not the user's current text, so stashing it
// in memoryOnlyText and announcing "not saved" would report a problem
// about text nobody is looking at any more.
assertWithinSizeLimit(noteId, byteLength);
const tx = openTransaction(activeConn(), ['notes', 'drafts', 'meta'], 'readwrite', { durability: 'strict' });
// The note record is read BEFORE the draft is written. Issued the other
// way round, a get() that fails (or a note deleted or replaced by an
// import out from under this writer) still leaves the drafts.put()
// issued, and nothing aborts the transaction — so it commits, stranding
// a draft record for a note that no longer exists, or overwriting
// freshly imported text with a stale pre-import draft. Throwing before
// the put is issued means the transaction carries no change at all.
const noteStore = tx.objectStore('notes');
const noteRecord = await requestToPromise(noteStore.get(noteId));
if (!noteRecord) {
throw Object.assign(new Error(`note ${noteId} not found`), { code: 'not-found' });
}
tx.objectStore('drafts').put({ noteId, text, localRev: rev, savedAt: now, byteLength });
// title is deliberately NOT touched: it is a user-set filename now
// (renameNote is its only writer). A draft write that rewrote it would
// silently revert a rename on the very next keystroke.
const stamp = await mutationStamp(tx.objectStore('meta'));
ensureNoteStamps(noteRecord, stamp.d).text = stamp;
noteRecord.updatedAt = now;
noteRecord.localRev = rev;
noteRecord.noteRev = (noteRecord.noteRev || 0) + 1;
noteStore.put(noteRecord);
await awaitTransactionComplete(tx);
// Monotonic: a restore may already have published a higher revision, and
// durableRevs is what flush() trusts to answer "already on disk".
const durableRev = Math.max(durableRevs.get(noteId) || 0, rev);
durableRevs.set(noteId, durableRev);
memoryOnlyText.delete(noteId);
receipt = { noteId, requestedRev: rev, durableRev, completedAt: Date.now() };
emit({ type: 'saved', ...receipt });
emit({ type: 'sync-dirty', noteId });
} catch (error) {
if (error && error.code === 'note-too-large') {
// Deliberately NOT truncated and NOT dropped: the text the user typed
// stays in the visible buffer (memoryOnlyText, the same channel the
// quota path uses, so copy/export still reach it) and the interface is
// told plainly that it is not being stored. Silently accepting it
// would be the dishonest option; silently cutting it would be worse.
memoryOnlyText.set(noteId, text);
receipt = { noteId, requestedRev: rev, durableRev: durableRevs.get(noteId) || 0, completedAt: Date.now(), error };
emit({ type: 'quota-warning', noteId, reason: 'note-too-large' });
emit({ type: 'memory-only', noteId, text });
} else if (isQuotaError(error)) {
// One prune-and-retry, then the note this text belongs to goes
// memory-only rather than looping forever against storage that is
// still full.
await runMaintenance().catch(() => {});
if (currentGeneration(noteId) !== generationAtQueue) {
// A restore won the note while maintenance ran. That is a
// supersession, not a quota failure: the restore's text is what is
// now current, so this stale payload must not overwrite it, and it
// must not be reported memory-only either (memory-only exists to
// preserve text that is otherwise about to be lost, and this text
// is not — the restore's checkpoint already preserved it). Falls
// through to the same save-failed reporting the generation fence
// uses on the first attempt.
receipt = { noteId, requestedRev: rev, durableRev: durableRevs.get(noteId) || 0, completedAt: Date.now(), error };
emit({ type: 'save-failed', ...receipt });
} else {
try {
// Recomputed rather than reused: byteLength above is scoped to
// the outer try block and is not visible here.
const retryByteLength = new TextEncoder().encode(text).length;
const retryTx = openTransaction(activeConn(), ['notes', 'drafts', 'meta'], 'readwrite', { durability: 'strict' });
// Same read-before-write ordering as the first attempt, for the
// same reason.
const retryNoteStore = retryTx.objectStore('notes');
const retryNoteRecord = await requestToPromise(retryNoteStore.get(noteId));
if (!retryNoteRecord) {
throw Object.assign(new Error(`note ${noteId} not found`), { code: 'not-found' });
}
retryTx.objectStore('drafts').put({ noteId, text, localRev: rev, savedAt: now, byteLength: retryByteLength });
// Same rule as the first attempt: the user-set title is not touched.
const retryStamp = await mutationStamp(retryTx.objectStore('meta'));
ensureNoteStamps(retryNoteRecord, retryStamp.d).text = retryStamp;
retryNoteRecord.updatedAt = now;
retryNoteRecord.localRev = rev;
retryNoteRecord.noteRev = (retryNoteRecord.noteRev || 0) + 1;
retryNoteStore.put(retryNoteRecord);
await awaitTransactionComplete(retryTx);
const durableRev = Math.max(durableRevs.get(noteId) || 0, rev);
durableRevs.set(noteId, durableRev);
memoryOnlyText.delete(noteId);
receipt = { noteId, requestedRev: rev, durableRev, completedAt: Date.now() };
emit({ type: 'saved', ...receipt });
emit({ type: 'sync-dirty', noteId });
} catch (retryError) {
memoryOnlyText.set(noteId, text);
receipt = { noteId, requestedRev: rev, durableRev: durableRevs.get(noteId) || 0, completedAt: Date.now(), error: retryError };
emit({ type: 'memory-only', noteId, text });
}
}
} else {
receipt = { noteId, requestedRev: rev, durableRev: durableRevs.get(noteId) || 0, completedAt: Date.now(), error };
emit({ type: 'save-failed', ...receipt });
}
}
resolveWaiters(noteId, receipt);
}
q.inFlight = false;
}
// --- version layer: snapshot the current draft into an immutable history ---
//
// commitVersion() flushes the draft to durability first (so sourceRev always
// names a durable revision), then snapshots the draft's current text into the
// versions store, deduping against the last-committed text so unchanged notes
// don't accumulate no-op versions. lastVersionText is connection-scoped (like
// revCounters/durableRevs) and is cleared in close().
const lastVersionText = new Map(); // noteId -> text of the newest committed version, for dedup
export async function commitVersion(id) {
if (memoryFallback) return memoryCommitVersion(id);
const q = queueFor(id);
// A restore already in progress will itself commit the next version (its
// own write, or whatever runs after it in the finally block), so there is
// nothing useful for a routine commit to do — skip rather than contend.
// This mirrors restoreVersion's own "restore-in-progress" check but returns
// null instead of throwing: commitVersion is polled routinely by an idle
// timer (Task 18) and null already means "nothing to commit right now".
if (q.restoring) return null;
// Once a version write has failed a prune-and-retry, history commits are
// considered permanently unsalvageable for this connection: draft writes
// must keep working, but there is no point contending for the lock or
// hitting storage again on every subsequent commitVersion() call.
if (versionCommitsStopped) return null;
const currentRev = revCounters.get(id) || 0;
if (currentRev > 0) {
await flush(id, currentRev).catch(() => {});
}
// Second check-and-set, synchronous (no await between them), exactly like
// restoreVersion's own lock acquisition: a restore (or another commit) may
// have started during the flush above, and this is the point that must not
// race it. nextSeq() + the write below are the vulnerable "allocate a seq,
// then write a version record in a later transaction" shape restoreVersion's
// lock exists to fence — commitVersion has the same shape and reuses the
// same q.restoring flag rather than a second one.
//
// The flush() above must stay OUTSIDE the lock (it needs the draft writer to
// keep running, which the lock suppresses), but the draft read must be INSIDE
// it. Read before the lock, a restore could start and finish in the gap, and
// this commit would then snapshot the pre-restore text — writing a spurious
// duplicate of a state the restore had already checkpointed.
if (q.restoring) return null;
q.restoring = true;
try {
const draftTx = openTransaction(activeConn(), ['drafts'], 'readonly');
const draft = await requestToPromise(draftTx.objectStore('drafts').get(id));
// No draft record means no note: say so with a code callers can branch on
// rather than letting draft.text raise a bare TypeError.
if (!draft) {
throw Object.assign(new Error(`note ${id} not found`), { code: 'not-found' });
}
if (lastVersionText.get(id) === draft.text) {
return null;
}
// nextSeq() also opens a transaction scoped to 'versions', so it is
// exposed to exactly the same fault (real quota pressure or the
// fault-injection seam) as the write below — a quota-class failure can
// surface there just as easily as on the put() itself. Both are folded
// into one prune-and-retry-once attempt: on failure, anything already
// computed (seq/at/byteLength) is stale relative to the post-prune state,
// so the retry recomputes them rather than reusing values from a
// transaction that never committed.
let seq;
let at;
let byteLength;
try {
seq = await nextSeq(id);
at = Date.now();
byteLength = new TextEncoder().encode(draft.text).length;
const writeTx = openTransaction(activeConn(), ['versions'], 'readwrite', { durability: 'strict' });
writeTx.objectStore('versions').put({ noteId: id, seq, at, sourceRev: draft.localRev, text: draft.text, byteLength });
await awaitTransactionComplete(writeTx);
} catch (error) {
if (!isQuotaError(error)) throw error;
await runMaintenance().catch(() => {});
try {
seq = await nextSeq(id);
at = Date.now();
byteLength = new TextEncoder().encode(draft.text).length;
const retryTx = openTransaction(activeConn(), ['versions'], 'readwrite', { durability: 'strict' });
retryTx.objectStore('versions').put({ noteId: id, seq, at, sourceRev: draft.localRev, text: draft.text, byteLength });
await awaitTransactionComplete(retryTx);
} catch (retryError) {
versionCommitsStopped = true;
emit({ type: 'quota-warning', noteId: id, reason: 'version-commits-stopped' });
return null;
}
}
lastVersionText.set(id, draft.text);
await requestPersistenceOnce();
return { seq, at, sourceRev: draft.localRev, size: byteLength };
} finally {
// Released whether the write succeeded or threw, same discipline as
// restoreVersion's finally: leaving it set would wedge the note's draft
// queue (saveDraft's launch guard checks q.restoring too) permanently.
q.restoring = false;
// Same shape as restoreVersion's finally, and for the same reason: text
// typed while the lock was held was accepted (coalesced into
// pendingText) but never started, because saveDraft's launch guard
// checks q.restoring. Left alone, it would sit stuck until some later,
// unrelated saveDraft() call happened to arrive and re-trigger that
// guard. This task's prune-and-retry can hold the lock across an extra
// runMaintenance() pass plus a retried write — meaningfully longer than
// a single write — which widens that window, so it is started here
// rather than left to chance.
if (q.pendingText !== null && !q.inFlight) {
runDraftWrite(id);
}
}
}
// Ordered by the versions store's OWN primary key ([noteId, seq]), never by the
// by_note_at index. The index is ordered by `at`, so its newest record is the
// highest `seq` only while Date.now() happens to be monotonic for this note.
// Two ordinary events break that coincidence, and both silently destroy data,
// because a reused seq means put() overwrites an existing version record:
// - a clock rollback (NTP correction, manual change) makes the next version's
// `at` smaller than the previous one's, so the previous record stays
// "newest" by index order and its seq is handed out again;
// - importing a backup whose newest version carries an `at` ahead of the
// local clock leaves that record permanently "newest" by index order, so
// every subsequent local commit computes the same seq.
// The primary key range below is the seq order itself, so neither matters.
async function nextSeq(noteId) {
const tx = openTransaction(activeConn(), ['versions'], 'readonly');
const range = IDBKeyRange.bound([noteId, -Infinity], [noteId, Infinity]);
let maxSeq = 0;
await new Promise((resolve, reject) => {
const req = tx.objectStore('versions').openCursor(range, 'prev');
req.onsuccess = () => {
const cursor = req.result;
if (cursor) { maxSeq = cursor.value.seq; }
resolve();
};
req.onerror = () => reject(req.error);
});
return maxSeq + 1;
}
export async function listVersions(id, { before, limit } = {}) {
if (memoryFallback) return memoryListVersions(id, { before, limit });
const tx = openTransaction(activeConn(), ['versions'], 'readonly');
const index = tx.objectStore('versions').index('by_note_at');
const upper = before ? [id, before.at, before.seq] : [id, Infinity, Infinity];
const range = IDBKeyRange.bound([id, -Infinity, -Infinity], upper, false, Boolean(before));
const results = [];
await new Promise((resolve, reject) => {
const req = index.openCursor(range, 'prev');
req.onsuccess = () => {
const cursor = req.result;
if (!cursor || (limit && results.length >= limit)) { resolve(); return; }
const { seq, at, sourceRev, byteLength, kind, protectedUntil, lostFields } = cursor.value;
results.push({ seq, at, sourceRev, size: byteLength, kind, protectedUntil, lostFields });
cursor.continue();
};
req.onerror = () => reject(req.error);
});