-
-
Notifications
You must be signed in to change notification settings - Fork 116
Expand file tree
/
Copy pathworkspace-storage.js
More file actions
2942 lines (2817 loc) · 129 KB
/
Copy pathworkspace-storage.js
File metadata and controls
2942 lines (2817 loc) · 129 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
(function () {
'use strict';
const DATABASE_NAME = 'markdownViewerWorkspace';
const DATABASE_VERSION = 3;
const VAULT_FORMAT_VERSION = 1;
const VAULT_NAME = 'Markdown Viewer Vault';
const LEGACY_VAULT_LOCATOR_KEY = 'markdownViewerVaultLocator';
const LEGACY_PORTABLE_LOCATOR_FILE = '.markdown-viewer-vault-locator.json';
const LEGACY_TABS_KEY = 'markdownViewerTabs';
const LEGACY_SECRET_KEY = 'markdownViewerSecretWorkspace';
const INTERNAL_DIR = '.markdown-viewer';
const SECRET_FOLDER_RECORD_ID = '__folders__';
const SECRET_MANIFEST_BACKUP_RECORD_ID = '__manifest_backup__';
const TRASH_RETENTION_DAYS = 30;
const TRASH_RETENTION_MS = TRASH_RETENTION_DAYS * 24 * 60 * 60 * 1000;
function isDesktopRuntime() {
try {
return Boolean(
typeof Neutralino !== 'undefined' &&
typeof NL_PORT !== 'undefined' &&
Neutralino.filesystem &&
Neutralino.storage &&
Neutralino.os
);
} catch (_) {
return false;
}
}
function randomId(prefix) {
if (self.crypto && typeof self.crypto.randomUUID === 'function') {
return prefix + '_' + self.crypto.randomUUID();
}
return prefix + '_' + Date.now() + '_' + Math.random().toString(36).slice(2, 10);
}
function normalizePathSeparators(value) {
return String(value || '').replace(/\\/g, '/').replace(/\/+/g, '/');
}
function sanitizePathSegment(value, fallback) {
let segment = String(value || '')
.replace(/[<>:"/\\|?*\u0000-\u001f]/g, ' ')
.replace(/\s+/g, ' ')
.trim()
.replace(/[. ]+$/g, '');
if (!segment) segment = fallback || 'Untitled';
if (/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i.test(segment)) segment = '_' + segment;
return segment.slice(0, 120);
}
function metadataFromTab(tab) {
const metadata = {};
Object.keys(tab || {}).forEach(function (key) {
if (
key === 'content' ||
key === 'contentLoaded' ||
key === '_vaultRelativePath' ||
key === '_persistedContent' ||
key.indexOf('_storage') === 0
) return;
metadata[key] = tab[key];
});
metadata.id = String(metadata.id || '');
metadata.contentLoaded = false;
return metadata;
}
function cloneJson(value, fallback) {
try {
return JSON.parse(JSON.stringify(value));
} catch (_) {
return fallback;
}
}
function utf8ByteLength(value) {
return new TextEncoder().encode(String(value == null ? '' : value)).byteLength;
}
async function stableDocumentIdSuffix(value) {
const bytes = new TextEncoder().encode(String(value == null ? '' : value));
if (!self.crypto || !self.crypto.subtle) {
throw new Error('Cryptographic document path generation is unavailable.');
}
const digest = new Uint8Array(await self.crypto.subtle.digest('SHA-256', bytes));
return Array.from(digest.slice(0, 16)).map(function(byte) {
return byte.toString(16).padStart(2, '0');
}).join('');
}
function requestToPromise(request) {
return new Promise(function (resolve, reject) {
request.onsuccess = function () { resolve(request.result); };
request.onerror = function () { reject(request.error || new Error('IndexedDB request failed')); };
});
}
function transactionToPromise(transaction) {
return new Promise(function (resolve, reject) {
transaction.oncomplete = function () { resolve(); };
transaction.onabort = function () { reject(transaction.error || new Error('IndexedDB transaction aborted')); };
transaction.onerror = function () { reject(transaction.error || new Error('IndexedDB transaction failed')); };
});
}
function base64ByteLength(value) {
if (typeof value !== 'string' || !value || value.length % 4 !== 0 || !/^[A-Za-z0-9+/]+={0,2}$/.test(value)) {
return -1;
}
try {
return atob(value).length;
} catch (_) {
return -1;
}
}
function validateEncryptedEnvelope(envelope) {
return Boolean(
envelope && typeof envelope === 'object' &&
base64ByteLength(envelope.iv) === 12 &&
base64ByteLength(envelope.ciphertext) >= 16
);
}
function isSecretManifestStructurallyValid(manifest) {
return Boolean(
manifest && typeof manifest === 'object' &&
base64ByteLength(manifest.salt) >= 16 &&
Number.isSafeInteger(Number(manifest.iterations)) &&
Number(manifest.iterations) >= 100000
);
}
function isSecretRecordStructurallyValid(record) {
if (!record || typeof record !== 'object') return false;
try {
requireSecretRecordId(record.id);
} catch (_) {
return false;
}
return validateEncryptedEnvelope(record.envelope);
}
function isTrashRecordRestorable(record, desktop) {
if (!record || typeof record.trashId !== 'string' || !record.trashId) return false;
const kind = record.kind || 'normal-document';
if (kind === 'normal-document') {
return Boolean(
record.metadata && typeof record.metadata.id === 'string' && record.metadata.id &&
(desktop ? typeof record.contentPath === 'string' && record.contentPath : typeof record.content === 'string')
);
}
if (kind === 'secret-workspace-snapshot') {
if (!isSecretManifestStructurallyValid(record.secretManifest) || !Array.isArray(record.secretRecords)) return false;
const ids = new Set();
return record.secretRecords.every(function(secretRecord) {
if (!isSecretRecordStructurallyValid(secretRecord) || ids.has(secretRecord.id)) return false;
ids.add(secretRecord.id);
return true;
});
}
if (kind === 'secret-record') {
return Boolean(
isSecretManifestStructurallyValid(record.secretManifest) &&
isSecretRecordStructurallyValid(record.secretRecord) &&
record.documentId === record.secretRecord.id
);
}
return false;
}
function isTrashRecordEligibleForAutomaticPurge(record, cutoff) {
if (!record || typeof record.trashId !== 'string' || !record.trashId) return false;
const deletedAt = Number(record.deletedAt);
if (!Number.isSafeInteger(deletedAt) || deletedAt <= 0 || deletedAt > cutoff) return false;
return isTrashRecordRestorable(record, typeof record.contentPath === 'string');
}
function requireDocumentId(id) {
if (typeof id !== 'string' || !id.trim()) {
throw new TypeError('Document IDs must be non-empty strings.');
}
return id;
}
function requireSecretRecordId(id) {
if (typeof id !== 'string' || !id || id.length > 120 || sanitizePathSegment(id, '') !== id ||
id === SECRET_MANIFEST_BACKUP_RECORD_ID) {
throw new TypeError('Secret Workspace record IDs must be safe, non-empty strings of at most 120 characters.');
}
return id;
}
function normalizedStorageRevision(value) {
const revision = Number(value);
return Number.isSafeInteger(revision) && revision >= 0 ? revision : 0;
}
function jsonEqual(left, right) {
return JSON.stringify(left == null ? null : left) === JSON.stringify(right == null ? null : right);
}
function mergeObjectChanges(base, local, remote) {
const result = Object.assign({}, remote || {});
const keys = new Set(Object.keys(base || {}).concat(Object.keys(local || {}), Object.keys(remote || {})));
keys.forEach(function(key) {
if (key === '_storageRevision' || key === '_storageWriterId') return;
const baseValue = base && base[key];
const localValue = local && local[key];
const remoteValue = remote && remote[key];
if (jsonEqual(localValue, baseValue)) return;
if (jsonEqual(remoteValue, baseValue) || jsonEqual(localValue, remoteValue)) {
if (localValue === undefined) delete result[key];
else result[key] = cloneJson(localValue, localValue);
}
});
return result;
}
function mergeOrganizationChanges(baseValue, localValue, remoteValue) {
const base = baseValue && typeof baseValue === 'object' ? baseValue : {};
const local = localValue && typeof localValue === 'object' ? localValue : {};
const remote = remoteValue && typeof remoteValue === 'object' ? remoteValue : {};
const merged = Object.assign({}, remote);
merged.version = Math.max(Number(remote.version) || 1, Number(local.version) || 1);
const mergeCollection = function(key) {
const baseItems = Array.isArray(base[key]) ? base[key] : [];
const localItems = Array.isArray(local[key]) ? local[key] : [];
const remoteItems = Array.isArray(remote[key]) ? remote[key] : [];
const baseById = new Map(baseItems.filter(Boolean).map(function(item) { return [item.id, item]; }));
const localById = new Map(localItems.filter(Boolean).map(function(item) { return [item.id, item]; }));
const remoteById = new Map(remoteItems.filter(Boolean).map(function(item) { return [item.id, item]; }));
const output = remoteItems.filter(Boolean).map(function(item) { return cloneJson(item, item); });
const outputById = new Map(output.map(function(item) { return [item.id, item]; }));
localById.forEach(function(localItem, id) {
const baseItem = baseById.get(id);
const remoteItem = remoteById.get(id);
if (!baseItem) {
if (!remoteItem) {
const copy = cloneJson(localItem, localItem);
output.push(copy);
outputById.set(id, copy);
} else if (!jsonEqual(localItem, remoteItem)) {
const copy = cloneJson(localItem, localItem);
copy.id = randomId(key === 'folders' ? 'folder_conflict' : 'workspace_conflict');
if (copy.name) copy.name = String(copy.name) + ' (conflict copy)';
output.push(copy);
}
return;
}
if (jsonEqual(localItem, baseItem)) return;
if (!remoteItem) {
const copy = cloneJson(localItem, localItem);
copy.id = randomId(key === 'folders' ? 'folder_recovered' : 'workspace_recovered');
if (copy.name) copy.name = String(copy.name) + ' (recovered)';
output.push(copy);
return;
}
const combined = mergeObjectChanges(baseItem, localItem, remoteItem);
Object.assign(outputById.get(id), combined);
});
baseById.forEach(function(baseItem, id) {
if (localById.has(id)) return;
const remoteItem = remoteById.get(id);
if (remoteItem && jsonEqual(remoteItem, baseItem)) {
const index = output.findIndex(function(item) { return item.id === id; });
if (index >= 0) output.splice(index, 1);
}
});
merged[key] = output;
};
mergeCollection('workspaces');
mergeCollection('folders');
merged.ui = mergeObjectChanges(base.ui || {}, local.ui || {}, remote.ui || {});
return merged;
}
function tabFromStoredMetadata(item) {
const tab = Object.assign({}, item || {});
tab._storageRevision = normalizedStorageRevision(tab.storageRevision);
tab._storageWriterId = typeof tab.storageWriterId === 'string' ? tab.storageWriterId : '';
delete tab.storageRevision;
delete tab.storageWriterId;
tab.contentLoaded = false;
tab.content = undefined;
return tab;
}
class WorkspaceConflictError extends Error {
constructor(documentId, attemptedTab, storedMetadata, storedContent) {
super('This document changed in another tab before the current update could be saved.');
this.name = 'WorkspaceConflictError';
this.documentId = documentId;
this.attemptedTab = attemptedTab;
this.storedMetadata = tabFromStoredMetadata(storedMetadata);
this.storedContent = typeof storedContent === 'string' ? storedContent : '';
this.contentConflict = Boolean(
attemptedTab &&
attemptedTab.contentLoaded !== false &&
typeof attemptedTab.content === 'string' &&
attemptedTab.content !== this.storedContent
);
}
}
class WorkspaceCorruptionError extends Error {
constructor(documentId, message) {
super(message || 'The saved document body is missing from workspace storage.');
this.name = 'WorkspaceCorruptionError';
this.documentId = documentId;
}
}
class WorkspaceSecretConflictError extends Error {
constructor(recordId, attemptedRecord, storedRecord) {
super('This Secret Workspace record changed in another tab before the current update could be saved.');
this.name = 'WorkspaceSecretConflictError';
this.recordId = recordId;
this.attemptedRecord = cloneJson(attemptedRecord, null);
this.storedRecord = cloneJson(storedRecord, null);
}
}
class MarkdownWorkspaceStorage {
constructor() {
this.desktop = isDesktopRuntime();
this.db = null;
this.ready = false;
this.vaultPath = '';
this.vaultId = '';
this.vaultIndex = { version: VAULT_FORMAT_VERSION, documents: [], updatedAt: 0 };
this.vaultOrganization = null;
this.desktopSettings = {};
this._organizationSnapshot = '';
this._organizationRevision = 0;
this.lastError = null;
this._desktopIndexWrite = Promise.resolve();
this._normalContentCache = new Map();
this._maxContentCacheEntries = 20;
this.writerId = randomId('writer');
}
async init() {
if (this.ready) return this;
if (this.desktop) await this._initDesktop();
else await this._initBrowser();
await this._migrateLegacyNormalDocuments();
this.ready = true;
try {
await this.purgeExpiredTrash();
} catch (error) {
this.lastError = error;
console.warn('Expired Trash items could not be removed:', error);
}
return this;
}
async _initBrowser() {
if (!('indexedDB' in self)) throw new Error('IndexedDB is unavailable in this browser.');
this.db = await new Promise(function (resolve, reject) {
const request = indexedDB.open(DATABASE_NAME, DATABASE_VERSION);
request.onupgradeneeded = function () {
const db = request.result;
if (!db.objectStoreNames.contains('documents')) {
const documents = db.createObjectStore('documents', { keyPath: 'id' });
documents.createIndex('workspaceId', 'workspaceId', { unique: false });
documents.createIndex('folderId', 'folderId', { unique: false });
documents.createIndex('lastOpenedAt', 'lastOpenedAt', { unique: false });
}
if (!db.objectStoreNames.contains('contents')) {
db.createObjectStore('contents', { keyPath: 'id' });
}
if (!db.objectStoreNames.contains('metadata')) {
db.createObjectStore('metadata', { keyPath: 'key' });
}
if (!db.objectStoreNames.contains('secretRecords')) {
db.createObjectStore('secretRecords', { keyPath: 'id' });
}
if (!db.objectStoreNames.contains('trash')) {
const trash = db.createObjectStore('trash', { keyPath: 'trashId' });
trash.createIndex('documentId', 'documentId', { unique: false });
trash.createIndex('deletedAt', 'deletedAt', { unique: false });
}
if (!db.objectStoreNames.contains('journals')) {
db.createObjectStore('journals', { keyPath: 'journalId' });
}
};
request.onsuccess = function () { resolve(request.result); };
request.onerror = function () { reject(request.error || new Error('Unable to open workspace storage')); };
request.onblocked = function () { reject(new Error('Workspace storage upgrade is blocked by another tab.')); };
});
this.db.onversionchange = function() {
try { this.close(); } catch (_) {}
};
this.vaultId = await this.getMetadata('vaultId');
if (!this.vaultId) {
this.vaultId = randomId('vault');
await this.setMetadata('vaultId', this.vaultId);
}
// Persistence is an optional durability improvement. Some browsers keep
// this request pending indefinitely, so it must never gate workspace
// initialization or make otherwise healthy data inaccessible.
this.requestPersistentStorage();
}
async _pathJoin() {
const parts = Array.from(arguments).filter(Boolean);
if (this.desktop && Neutralino.filesystem.getJoinedPath) {
return Neutralino.filesystem.getJoinedPath.apply(Neutralino.filesystem, parts);
}
return normalizePathSeparators(parts.join('/'));
}
async _pathExists(path) {
try {
const stats = await Neutralino.filesystem.getStats(path);
return stats || null;
} catch (_) {
return null;
}
}
async _ensureDirectory(path) {
const stats = await this._pathExists(path);
if (stats && stats.isDirectory) return;
if (stats) throw new Error('Expected a folder but found a file: ' + path);
await Neutralino.filesystem.createDirectory(path);
}
async _readJsonFile(path, fallback) {
try {
const raw = await Neutralino.filesystem.readFile(path);
return JSON.parse(raw);
} catch (_) {
return fallback;
}
}
async _writeJsonFile(path, value) {
const serialized = JSON.stringify(value, null, 2);
await Neutralino.filesystem.writeFile(path, serialized);
const verified = await Neutralino.filesystem.readFile(path);
if (verified !== serialized) {
throw new Error('A desktop storage write could not be verified: ' + path);
}
}
async _writeJsonFileRecoverably(path, value) {
const temporaryPath = path + '.pending';
const backupPath = path + '.backup';
const serialized = JSON.stringify(value, null, 2);
await Neutralino.filesystem.writeFile(temporaryPath, serialized);
if (await this._pathExists(path)) {
await Neutralino.filesystem.copy(path, backupPath, { overwrite: true });
}
await Neutralino.filesystem.writeFile(path, serialized);
const verified = await Neutralino.filesystem.readFile(path);
if (verified !== serialized) {
throw new Error('A desktop storage write could not be verified: ' + path);
}
try { await Neutralino.filesystem.remove(temporaryPath); } catch (_) {}
try { await Neutralino.filesystem.remove(backupPath); } catch (_) {}
}
async _readJsonFileRecoverably(path, fallback) {
const primary = await this._readJsonFile(path, null);
const backupPath = path + '.backup';
const backup = await this._readJsonFile(backupPath, null);
const pendingPath = path + '.pending';
const pending = await this._readJsonFile(pendingPath, null);
const candidates = [
{ value: primary, priority: 3 },
{ value: pending, priority: 2 },
{ value: backup, priority: 1 }
].filter(function(item) { return item.value && typeof item.value === 'object'; });
if (!candidates.length) return fallback;
candidates.sort(function(left, right) {
const leftTime = Number(left.value.updatedAt || left.value.committedAt) || 0;
const rightTime = Number(right.value.updatedAt || right.value.committedAt) || 0;
return rightTime - leftTime || right.priority - left.priority;
});
const selected = candidates[0];
if (selected.value !== primary) await this._writeJsonFile(path, selected.value);
try { if (pending) await Neutralino.filesystem.remove(pendingPath); } catch (_) {}
try { if (backup) await Neutralino.filesystem.remove(backupPath); } catch (_) {}
return selected.value;
}
async _removeLegacyVaultLocator(documentsPath) {
try {
await Neutralino.storage.removeData(LEGACY_VAULT_LOCATOR_KEY);
} catch (_) {}
try {
const legacyLocatorPath = await this._pathJoin(documentsPath, LEGACY_PORTABLE_LOCATOR_FILE);
const stats = await this._pathExists(legacyLocatorPath);
if (stats && !stats.isDirectory) {
await Neutralino.filesystem.remove(legacyLocatorPath);
}
} catch (_) {}
}
async _initDesktop() {
const documentsPath = await Neutralino.os.getPath('documents');
// Cleanup from the preview locator design is non-blocking and never gates startup.
this._removeLegacyVaultLocator(documentsPath);
const vaultPath = await this._pathJoin(documentsPath, VAULT_NAME);
this.vaultPath = vaultPath;
const workspacePath = await this._pathJoin(vaultPath, 'Workspace');
const secretPath = await this._pathJoin(vaultPath, 'Secret Workspace', 'objects');
const internalPath = await this._pathJoin(vaultPath, INTERNAL_DIR);
const historyPath = await this._pathJoin(internalPath, 'history');
const trashPath = await this._pathJoin(internalPath, 'trash');
const journalPath = await this._pathJoin(internalPath, 'journal');
await this._ensureDirectory(vaultPath);
await this._ensureDirectory(workspacePath);
await this._ensureDirectory(await this._pathJoin(vaultPath, 'Secret Workspace'));
await this._ensureDirectory(secretPath);
await this._ensureDirectory(internalPath);
await this._ensureDirectory(historyPath);
await this._ensureDirectory(trashPath);
await this._ensureDirectory(journalPath);
await this._recoverDesktopJournal();
const manifestPath = await this._pathJoin(internalPath, 'vault.json');
let manifest = await this._readJsonFile(manifestPath, null);
if (!manifest) {
manifest = {
format: 'markdown-viewer-vault',
version: VAULT_FORMAT_VERSION,
id: randomId('vault'),
name: VAULT_NAME,
createdAt: Date.now(),
updatedAt: Date.now()
};
await this._writeJsonFile(manifestPath, manifest);
}
if (manifest.format !== 'markdown-viewer-vault') {
throw new Error('The selected folder is not a Markdown Viewer Vault.');
}
if (Number(manifest.version) > VAULT_FORMAT_VERSION) {
throw new Error('This vault was created by a newer version of Markdown Viewer.');
}
this.vaultId = manifest.id || randomId('vault');
const settingsPath = await this._pathJoin(internalPath, 'settings.json');
this.desktopSettings = await this._readJsonFile(settingsPath, {});
const organizationPath = await this._pathJoin(internalPath, 'organization.json');
this.vaultOrganization = await this._readJsonFileRecoverably(organizationPath, null);
const organizationSnapshot = cloneJson(this.vaultOrganization, null);
if (organizationSnapshot) {
delete organizationSnapshot._storageRevision;
delete organizationSnapshot._storageWriterId;
delete organizationSnapshot.updatedAt;
}
this._organizationRevision = normalizedStorageRevision(this.vaultOrganization && this.vaultOrganization._storageRevision);
this._organizationSnapshot = organizationSnapshot ? JSON.stringify(organizationSnapshot) : '';
const indexPath = await this._pathJoin(internalPath, 'index.json');
const loadedIndex = await this._readJsonFileRecoverably(indexPath, null);
if (loadedIndex && Array.isArray(loadedIndex.documents)) {
this.vaultIndex = loadedIndex;
} else {
this.vaultIndex = await this._rebuildDesktopIndex(workspacePath);
await this._writeJsonFileRecoverably(indexPath, this.vaultIndex);
if (this.vaultOrganization) {
await this._writeJsonFile(organizationPath, this.vaultOrganization);
this._organizationSnapshot = JSON.stringify(this.vaultOrganization);
}
}
}
async _rebuildDesktopIndex(workspacePath) {
const organization = this.vaultOrganization && typeof this.vaultOrganization === 'object'
? cloneJson(this.vaultOrganization, null)
: { version: 1, workspaces: [], folders: [], ui: {} };
if (!Array.isArray(organization.folders)) organization.folders = [];
const documents = [];
const seenIds = new Set();
const findOrCreateFolder = function(name, parentFolderId) {
let folder = organization.folders.find(function(item) {
return item &&
item.workspaceId !== 'workspace_secret' &&
(item.parentFolderId || null) === (parentFolderId || null) &&
String(item.name || '').toLowerCase() === String(name || '').toLowerCase();
});
if (!folder) {
folder = {
id: randomId('folder'),
workspaceId: 'workspace_default',
parentFolderId: parentFolderId || null,
name: sanitizePathSegment(name, 'Folder'),
expanded: true,
createdAt: Date.now()
};
organization.folders.push(folder);
}
return folder;
};
const walk = async (currentPath, relativeSegments, parentFolderId) => {
let entries = [];
try {
entries = await Neutralino.filesystem.readDirectory(currentPath);
} catch (_) {
return;
}
entries.sort(function(a, b) {
return String(a && a.entry || '').localeCompare(String(b && b.entry || ''));
});
for (const entry of entries) {
if (!entry || !entry.entry) continue;
const entryPath = await this._pathJoin(currentPath, entry.entry);
if (entry.type === 'DIRECTORY') {
const folder = findOrCreateFolder(entry.entry, parentFolderId);
await walk(entryPath, relativeSegments.concat(entry.entry), folder.id);
continue;
}
if (entry.type !== 'FILE' || !/\.md$/i.test(entry.entry)) continue;
const nameMatch = /^(.*?)(?:--([a-z0-9]{1,32}))?\.md$/i.exec(entry.entry);
const recoveredSuffix = nameMatch && nameMatch[2] ? nameMatch[2] : '';
let id = recoveredSuffix ? 'recovered_' + recoveredSuffix : randomId('recovered');
while (seenIds.has(id)) id = randomId('recovered');
seenIds.add(id);
let stats = null;
try { stats = await Neutralino.filesystem.getStats(entryPath); } catch (_) {}
const timestamp = Number(stats && (stats.modifiedAt || stats.createdAt)) || Date.now();
documents.push({
id: id,
title: sanitizePathSegment(nameMatch && nameMatch[1], 'Recovered document'),
workspaceId: 'workspace_default',
folderId: parentFolderId || null,
favorite: false,
isOpen: false,
viewMode: 'split',
reviewThreads: [],
createdAt: timestamp,
lastOpenedAt: timestamp,
lastEditedAt: timestamp,
contentSize: Number(stats && stats.size) || 0,
vaultRelativePath: normalizePathSeparators(['Workspace'].concat(relativeSegments, entry.entry).join('/')),
contentLoaded: false
});
}
};
await walk(workspacePath, [], null);
if (documents.length) documents[0].isOpen = true;
this.vaultOrganization = organization;
return {
version: VAULT_FORMAT_VERSION,
documents: documents,
rebuiltAt: Date.now(),
updatedAt: Date.now()
};
}
async _recoverDesktopJournal() {
const journalPath = await this._pathJoin(this.vaultPath, INTERNAL_DIR, 'journal');
let entries = [];
try {
entries = await Neutralino.filesystem.readDirectory(journalPath);
} catch (_) {}
const normalizedVault = normalizePathSeparators(this.vaultPath).toLowerCase().replace(/\/+$/, '') + '/';
const pendingRecords = [];
for (const entry of entries) {
if (!entry || entry.type !== 'FILE' || !/\.json$/i.test(entry.entry || '')) continue;
const recordPath = await this._pathJoin(journalPath, entry.entry);
const record = await this._readJsonFile(recordPath, null);
pendingRecords.push({ recordPath: recordPath, record: record });
}
// A committed index is authoritative for move recovery. Process it before
// move journals even when the filesystem returns directory entries in the
// opposite order.
pendingRecords.sort(function(left, right) {
const priority = function(item) {
if (item.record && item.record.operation === 'index-commit') return 0;
if (item.record && item.record.operation === 'move') return 1;
return 2;
};
return priority(left) - priority(right);
});
for (const pendingRecord of pendingRecords) {
const recordPath = pendingRecord.recordPath;
const record = pendingRecord.record;
if (record && record.operation === 'index-commit' && record.index && Array.isArray(record.index.documents)) {
const indexPath = await this._pathJoin(this.vaultPath, INTERNAL_DIR, 'index.json');
const currentIndex = await this._readJsonFileRecoverably(indexPath, null);
if (!currentIndex || Number(record.index.updatedAt) >= Number(currentIndex.updatedAt || 0)) {
await this._writeJsonFileRecoverably(indexPath, record.index);
}
try { await Neutralino.filesystem.remove(recordPath); } catch (_) {}
continue;
}
if (record && record.operation === 'move') {
const source = normalizePathSeparators(record.source);
const destination = normalizePathSeparators(record.destination);
const indexPath = await this._pathJoin(this.vaultPath, INTERNAL_DIR, 'index.json');
const index = await this._readJsonFileRecoverably(indexPath, null);
const indexedDocument = index && Array.isArray(index.documents)
? index.documents.find(function(item) { return item.id === record.documentId; })
: null;
const committed = Boolean(
indexedDocument &&
normalizePathSeparators(indexedDocument.vaultRelativePath) === normalizePathSeparators(record.destinationRelativePath)
);
if (!committed &&
source.toLowerCase().startsWith(normalizedVault) &&
destination.toLowerCase().startsWith(normalizedVault) &&
!source.split('/').includes('..') &&
!destination.split('/').includes('..') &&
await this._pathExists(destination) &&
!(await this._pathExists(source))) {
await Neutralino.filesystem.move(destination, source);
}
try { await Neutralino.filesystem.remove(recordPath); } catch (_) {}
continue;
}
if (!record || !record.destination || !record.temporary) {
try { await Neutralino.filesystem.remove(recordPath); } catch (_) {}
continue;
}
const destination = normalizePathSeparators(record.destination);
const temporary = normalizePathSeparators(record.temporary);
if (
destination.split('/').includes('..') ||
temporary.split('/').includes('..') ||
!destination.toLowerCase().startsWith(normalizedVault) ||
!temporary.toLowerCase().startsWith(normalizedVault)
) {
continue;
}
if (await this._pathExists(temporary)) {
const recoveredContent = await Neutralino.filesystem.readFile(temporary);
await Neutralino.filesystem.writeFile(destination, recoveredContent);
const verifiedContent = await Neutralino.filesystem.readFile(destination);
if (verifiedContent !== recoveredContent) {
throw new Error('A recovered desktop document write could not be verified.');
}
try { await Neutralino.filesystem.remove(temporary); } catch (_) {}
}
if (record.metadata && typeof record.metadata === 'object' && await this._pathExists(destination)) {
const indexPath = await this._pathJoin(this.vaultPath, INTERNAL_DIR, 'index.json');
const currentIndex = await this._readJsonFileRecoverably(indexPath, null) || {
version: VAULT_FORMAT_VERSION,
documents: [],
updatedAt: 0
};
if (!Array.isArray(currentIndex.documents)) currentIndex.documents = [];
const recoveredMetadata = cloneJson(record.metadata, {}) || {};
const existingIndex = currentIndex.documents.findIndex(function(item) {
return item.id === recoveredMetadata.id;
});
const existing = existingIndex >= 0 ? currentIndex.documents[existingIndex] : null;
if (!existing || normalizedStorageRevision(recoveredMetadata.storageRevision) > normalizedStorageRevision(existing.storageRevision)) {
if (existingIndex >= 0) currentIndex.documents.splice(existingIndex, 1, recoveredMetadata);
else currentIndex.documents.push(recoveredMetadata);
currentIndex.updatedAt = Math.max(Date.now(), Number(currentIndex.updatedAt) || 0);
await this._writeJsonFileRecoverably(indexPath, currentIndex);
}
}
try { await Neutralino.filesystem.remove(recordPath); } catch (_) {}
}
await this._recoverDesktopTrashTransactions();
}
async _completeDesktopTrashPurge(record, metadataPath) {
const trashPath = await this._pathJoin(this.vaultPath, INTERNAL_DIR, 'trash');
const normalizedTrashPath = normalizePathSeparators(trashPath).toLowerCase().replace(/\/+$/, '') + '/';
const isSafeTrashPath = function(path) {
const normalized = normalizePathSeparators(path);
return Boolean(
normalized &&
normalized.toLowerCase().startsWith(normalizedTrashPath) &&
!normalized.split('/').includes('..')
);
};
if (!isSafeTrashPath(metadataPath)) {
throw new Error('Trash metadata points outside the managed Trash folder.');
}
if ((record.kind || 'normal-document') === 'normal-document') {
if (!isSafeTrashPath(record.contentPath)) {
throw new Error('Trash content points outside the managed Trash folder.');
}
if (await this._pathExists(record.contentPath)) {
await Neutralino.filesystem.remove(record.contentPath);
}
}
if (await this._pathExists(metadataPath)) {
await Neutralino.filesystem.remove(metadataPath);
}
}
async _recoverDesktopTrashTransactions() {
const trashPath = await this._pathJoin(this.vaultPath, INTERNAL_DIR, 'trash');
let entries = [];
try { entries = await Neutralino.filesystem.readDirectory(trashPath); } catch (_) { return; }
const indexPath = await this._pathJoin(this.vaultPath, INTERNAL_DIR, 'index.json');
const currentIndex = await this._readJsonFileRecoverably(indexPath, null);
const hasCurrentIndex = Boolean(currentIndex && Array.isArray(currentIndex.documents));
const normalizedVault = normalizePathSeparators(this.vaultPath).toLowerCase().replace(/\/+$/, '') + '/';
for (const entry of entries) {
if (!entry || entry.type !== 'FILE' || !/(?:\.md\.json|\.secret\.json)$/i.test(entry.entry || '')) continue;
const metadataPath = await this._pathJoin(trashPath, entry.entry);
const record = await this._readJsonFileRecoverably(metadataPath, null);
if (!record) continue;
if (record.purgeInProgress) {
try {
await this._completeDesktopTrashPurge(record, metadataPath);
} catch (error) {
console.warn('An interrupted Trash purge could not be completed:', error);
}
continue;
}
if (record.kind !== 'normal-document' || !hasCurrentIndex) continue;
const source = normalizePathSeparators(record.originalPath || record.source);
const destination = normalizePathSeparators(record.contentPath || record.destination);
if (!source || !destination || !source.toLowerCase().startsWith(normalizedVault) ||
!destination.toLowerCase().startsWith(normalizedVault) || source.split('/').includes('..') ||
destination.split('/').includes('..')) continue;
if (record.restoreInProgress && typeof record.restoreInProgress === 'object') {
const restoreDestination = normalizePathSeparators(record.restoreInProgress.destination);
const restoreMetadata = record.restoreInProgress.metadata;
if (restoreDestination && restoreMetadata && typeof restoreMetadata.id === 'string' &&
restoreDestination.toLowerCase().startsWith(normalizedVault) &&
!restoreDestination.split('/').includes('..')) {
const indexedRestore = currentIndex.documents.some(function(item) {
return item.id === restoreMetadata.id &&
normalizePathSeparators(item.vaultRelativePath) === normalizePathSeparators(restoreMetadata.vaultRelativePath);
});
const restoreExists = await this._pathExists(restoreDestination);
const trashContentExists = await this._pathExists(destination);
if (indexedRestore && restoreExists) {
try { await Neutralino.filesystem.remove(metadataPath); } catch (_) {}
continue;
}
if (!indexedRestore && restoreExists && !trashContentExists) {
await Neutralino.filesystem.move(restoreDestination, destination);
}
if (!indexedRestore) {
const preservedTrashRecord = cloneJson(record, record);
delete preservedTrashRecord.restoreInProgress;
preservedTrashRecord.updatedAt = Date.now();
await this._writeJsonFileRecoverably(metadataPath, preservedTrashRecord);
continue;
}
}
}
const indexed = currentIndex.documents.find(function(item) {
return item.id === record.documentId && record.metadata &&
normalizePathSeparators(item.vaultRelativePath) === normalizePathSeparators(record.metadata.vaultRelativePath);
});
const sourceExists = await this._pathExists(source);
const destinationExists = await this._pathExists(destination);
if (indexed && !sourceExists && destinationExists) {
await Neutralino.filesystem.move(destination, source);
try { await Neutralino.filesystem.remove(metadataPath); } catch (_) {}
} else if (indexed && sourceExists && !destinationExists) {
try { await Neutralino.filesystem.remove(metadataPath); } catch (_) {}
}
}
}
async _desktopResolveVaultRelativePath(relativePath) {
const normalized = normalizePathSeparators(relativePath).replace(/^\/+/, '');
const segments = normalized.split('/').filter(Boolean);
if (!segments.length || segments.some(function(segment) {
return segment === '.' || segment === '..';
})) {
throw new Error('The vault index contains an invalid document path.');
}
return this._pathJoin.apply(this, [this.vaultPath].concat(segments));
}
async _migrateLegacyNormalDocuments() {
const existing = await this.listDocumentMetadata();
let legacy = [];
try {
legacy = JSON.parse(localStorage.getItem(LEGACY_TABS_KEY) || '[]');
} catch (_) {}
if (!Array.isArray(legacy) || !legacy.length) return;
const normal = legacy.filter(function (tab) {
return tab && tab.temporary !== true && tab.kind !== 'share-snapshot' && tab.workspaceId !== 'workspace_secret';
});
if (!normal.length) return;
const existingById = new Map(existing.map(function(item) { return [item.id, item]; }));
const pending = [];
const migratedLegacyIds = [];
for (const legacyTab of normal) {
const legacyContent = typeof legacyTab.content === 'string' ? legacyTab.content : '';
const legacyId = typeof legacyTab.id === 'string' && legacyTab.id.trim()
? legacyTab.id
: randomId('legacy_recovered');
const storedMetadata = existingById.get(legacyId);
if (!storedMetadata) {
const copy = Object.assign({}, legacyTab, {
id: legacyId,
content: legacyContent,
contentLoaded: true,
_storageRevision: 0
});
pending.push(copy);
existingById.set(legacyId, copy);
migratedLegacyIds.push(legacyId);
continue;
}
let storedContent = null;
try {
storedContent = await this.loadDocumentContent(legacyId);
} catch (error) {
if (!error || error.name !== 'WorkspaceCorruptionError') throw error;
}
if (storedContent === null) {
pending.push(Object.assign({}, storedMetadata, legacyTab, {
id: legacyId,
content: legacyContent,
contentLoaded: true,
_storageRevision: storedMetadata._storageRevision
}));
migratedLegacyIds.push(legacyId);
continue;
}
if (storedContent !== legacyContent) {
const recoveryId = randomId('legacy_recovered');
pending.push(Object.assign({}, legacyTab, {
id: recoveryId,
title: String(legacyTab.title || storedMetadata.title || 'Untitled') + ' (legacy recovery)',
content: legacyContent,
contentLoaded: true,
_storageRevision: 0
}));
migratedLegacyIds.push(recoveryId);
}
}
if (pending.length) await this.saveDocuments(pending, null, {
changedIds: pending.map(function(tab) { return tab.id; }),
forceContent: true
});
for (const id of migratedLegacyIds) await this.loadDocumentContent(id);
await this.setMetadata('legacyMigration', {
version: 3,
completedAt: Date.now(),
documentCount: pending.length,
existingDocumentCount: existing.length
});
try {
localStorage.removeItem(LEGACY_TABS_KEY);
} catch (_) {}
if (this.desktop && Neutralino.storage.removeData) {
try {
await Neutralino.storage.removeData(LEGACY_TABS_KEY);
} catch (_) {}
}
}
async listDocumentMetadata() {
if (this.desktop) {
return this.vaultIndex.documents.map(function (item) {
const tab = tabFromStoredMetadata(item);
tab._vaultRelativePath = item.vaultRelativePath || '';
return tab;
});
}
const transaction = this.db.transaction('documents', 'readonly');
const records = await requestToPromise(transaction.objectStore('documents').getAll());
await transactionToPromise(transaction);
return records.map(tabFromStoredMetadata);
}
async loadDocumentMetadata(id) {
requireDocumentId(id);
if (this.desktop) {
const item = this.vaultIndex.documents.find(function(record) { return record.id === id; });
return item ? tabFromStoredMetadata(item) : null;
}
const transaction = this.db.transaction('documents', 'readonly');
const record = await requestToPromise(transaction.objectStore('documents').get(id));
await transactionToPromise(transaction);
return record ? tabFromStoredMetadata(record) : null;
}
async auditAndRepairDocuments() {
if (this.desktop) return { recoveredOrphans: 0, missingContents: 0 };
const transaction = this.db.transaction(['documents', 'contents'], 'readwrite');
const completion = transactionToPromise(transaction);
const documents = transaction.objectStore('documents');
const contents = transaction.objectStore('contents');
const metadataRecords = await requestToPromise(documents.getAll());
const contentRecords = await requestToPromise(contents.getAll());
const metadataIds = new Set(metadataRecords.map(function(item) { return item.id; }));
const contentIds = new Set(contentRecords.map(function(item) { return item.id; }));
let recoveredOrphans = 0;