-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathtest.js
More file actions
1893 lines (1581 loc) · 70.3 KB
/
test.js
File metadata and controls
1893 lines (1581 loc) · 70.3 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
const { describe, it, before, after, beforeEach } = require("node:test");
const assert = require("node:assert");
const fs = require("fs");
const path = require("path");
// Use test directory for all databases
const TEST_DATA_DIR = path.join(__dirname, "test-data");
process.env.DATA_DIR = TEST_DATA_DIR;
const TEST_USER_ID = "testuser";
// Clean up test directory before tests
function cleanTestDir() {
if (fs.existsSync(TEST_DATA_DIR)) {
fs.rmSync(TEST_DATA_DIR, { recursive: true });
}
}
cleanTestDir();
describe("Database Tests", () => {
let db;
beforeEach(() => {
// Fresh db module for each test
delete require.cache[require.resolve("./db")];
cleanTestDir();
db = require("./db");
});
after(() => {
if (db && db.closeAllConnections) {
db.closeAllConnections();
}
cleanTestDir();
});
describe("saveUrl", () => {
it("should save a URL without tags", () => {
const id = db.saveUrl(TEST_USER_ID, "https://example.com");
assert.ok(id, "should return an id");
assert.match(id, /^[0-9a-f-]{36}$/, "id should be a UUID");
});
it("should save a URL with tags", () => {
const id = db.saveUrl(TEST_USER_ID, "https://example.com", ["test", "demo"]);
assert.ok(id);
const urls = db.getSavedUrls(TEST_USER_ID);
assert.strictEqual(urls.length, 1);
assert.strictEqual(urls[0].url, "https://example.com");
assert.deepStrictEqual(urls[0].tags.sort(), ["demo", "test"]);
});
it("should update existing URL instead of duplicating", () => {
const id1 = db.saveUrl(TEST_USER_ID, "https://example.com", ["tag1"]);
const id2 = db.saveUrl(TEST_USER_ID, "https://example.com", ["tag2"]);
// Should reuse same ID
assert.strictEqual(id1, id2);
const urls = db.getSavedUrls(TEST_USER_ID);
assert.strictEqual(urls.length, 1);
// Tags should be replaced
assert.deepStrictEqual(urls[0].tags, ["tag2"]);
});
it("should save multiple different URLs", () => {
db.saveUrl(TEST_USER_ID, "https://example1.com");
db.saveUrl(TEST_USER_ID, "https://example2.com");
db.saveUrl(TEST_USER_ID, "https://example3.com");
const urls = db.getSavedUrls(TEST_USER_ID);
assert.strictEqual(urls.length, 3);
});
});
describe("getSavedUrls", () => {
it("should return empty array when no URLs", () => {
const urls = db.getSavedUrls(TEST_USER_ID);
assert.deepStrictEqual(urls, []);
});
it("should return all saved URLs", () => {
db.saveUrl(TEST_USER_ID, "https://first.com");
db.saveUrl(TEST_USER_ID, "https://second.com");
db.saveUrl(TEST_USER_ID, "https://third.com");
const urls = db.getSavedUrls(TEST_USER_ID);
assert.strictEqual(urls.length, 3);
const urlStrings = urls.map((u) => u.url).sort();
assert.deepStrictEqual(urlStrings, [
"https://first.com",
"https://second.com",
"https://third.com",
]);
});
it("should include savedAt timestamp", () => {
db.saveUrl(TEST_USER_ID, "https://example.com");
const urls = db.getSavedUrls(TEST_USER_ID);
assert.ok(urls[0].savedAt);
// Should be a number (Unix ms)
assert.strictEqual(typeof urls[0].savedAt, "number");
});
});
describe("deleteUrl", () => {
it("should delete a URL by id", () => {
const id = db.saveUrl(TEST_USER_ID, "https://example.com");
assert.strictEqual(db.getSavedUrls(TEST_USER_ID).length, 1);
db.deleteUrl(TEST_USER_ID, id);
assert.strictEqual(db.getSavedUrls(TEST_USER_ID).length, 0);
});
it("should cascade delete url_tags associations", () => {
const id = db.saveUrl(TEST_USER_ID, "https://example.com", ["tag1", "tag2"]);
db.deleteUrl(TEST_USER_ID, id);
// URL should be gone
assert.strictEqual(db.getSavedUrls(TEST_USER_ID).length, 0);
// Tags should still exist (not deleted with URL)
const tags = db.getTagsByFrecency(TEST_USER_ID);
assert.strictEqual(tags.length, 2);
});
it("should not error when deleting non-existent id", () => {
assert.doesNotThrow(() => {
db.deleteUrl(TEST_USER_ID, "non-existent-id");
});
});
});
describe("updateUrlTags", () => {
it("should update tags for existing URL", () => {
const id = db.saveUrl(TEST_USER_ID, "https://example.com", ["old-tag"]);
db.updateUrlTags(TEST_USER_ID, id, ["new-tag1", "new-tag2"]);
const urls = db.getSavedUrls(TEST_USER_ID);
assert.deepStrictEqual(urls[0].tags.sort(), ["new-tag1", "new-tag2"]);
});
it("should clear tags when given empty array", () => {
const id = db.saveUrl(TEST_USER_ID, "https://example.com", ["tag1", "tag2"]);
db.updateUrlTags(TEST_USER_ID, id, []);
const urls = db.getSavedUrls(TEST_USER_ID);
assert.deepStrictEqual(urls[0].tags, []);
});
});
describe("Tags and Frecency", () => {
it("should track tag frequency", () => {
db.saveUrl(TEST_USER_ID, "https://example1.com", ["common"]);
db.saveUrl(TEST_USER_ID, "https://example2.com", ["common"]);
db.saveUrl(TEST_USER_ID, "https://example3.com", ["common"]);
db.saveUrl(TEST_USER_ID, "https://example4.com", ["rare"]);
const tags = db.getTagsByFrecency(TEST_USER_ID);
const common = tags.find((t) => t.name === "common");
const rare = tags.find((t) => t.name === "rare");
assert.strictEqual(common.frequency, 3);
assert.strictEqual(rare.frequency, 1);
});
it("should sort tags by frecency score descending", () => {
db.saveUrl(TEST_USER_ID, "https://example1.com", ["rare"]);
db.saveUrl(TEST_USER_ID, "https://example2.com", ["common"]);
db.saveUrl(TEST_USER_ID, "https://example3.com", ["common"]);
db.saveUrl(TEST_USER_ID, "https://example4.com", ["common"]);
const tags = db.getTagsByFrecency(TEST_USER_ID);
assert.strictEqual(tags[0].name, "common");
assert.strictEqual(tags[1].name, "rare");
});
it("should have positive frecency score", () => {
db.saveUrl(TEST_USER_ID, "https://example.com", ["test"]);
const tags = db.getTagsByFrecency(TEST_USER_ID);
assert.ok(tags[0].frecencyScore > 0);
});
it("should return empty array when no tags", () => {
const tags = db.getTagsByFrecency(TEST_USER_ID);
assert.deepStrictEqual(tags, []);
});
});
describe("Settings", () => {
it("should save and retrieve settings", () => {
db.setSetting(TEST_USER_ID, "test_key", "test_value");
const value = db.getSetting(TEST_USER_ID, "test_key");
assert.strictEqual(value, "test_value");
});
it("should return null for non-existent setting", () => {
const value = db.getSetting(TEST_USER_ID, "non_existent");
assert.strictEqual(value, null);
});
it("should update existing setting", () => {
db.setSetting(TEST_USER_ID, "key", "value1");
db.setSetting(TEST_USER_ID, "key", "value2");
const value = db.getSetting(TEST_USER_ID, "key");
assert.strictEqual(value, "value2");
});
});
describe("saveText", () => {
it("should save a text without tags", () => {
const id = db.saveText(TEST_USER_ID, "My note content");
assert.ok(id, "should return an id");
assert.match(id, /^[0-9a-f-]{36}$/, "id should be a UUID");
});
it("should save a text with tags", () => {
const id = db.saveText(TEST_USER_ID, "My note", ["personal", "todo"]);
assert.ok(id);
const texts = db.getTexts(TEST_USER_ID);
assert.strictEqual(texts.length, 1);
assert.strictEqual(texts[0].content, "My note");
assert.deepStrictEqual(texts[0].tags.sort(), ["personal", "todo"]);
});
it("should update existing text with same content", () => {
const id1 = db.saveText(TEST_USER_ID, "Same content", ["tag1"]);
const id2 = db.saveText(TEST_USER_ID, "Same content", ["tag2"]);
assert.strictEqual(id1, id2);
const texts = db.getTexts(TEST_USER_ID);
assert.strictEqual(texts.length, 1);
assert.deepStrictEqual(texts[0].tags, ["tag2"]);
});
});
describe("saveTagset", () => {
it("should save a tagset", () => {
const id = db.saveTagset(TEST_USER_ID, ["pushups", "10"]);
assert.ok(id, "should return an id");
assert.match(id, /^[0-9a-f-]{36}$/, "id should be a UUID");
});
it("should deduplicate tagsets with same tags", () => {
const id1 = db.saveTagset(TEST_USER_ID, ["pushups", "10"]);
const id2 = db.saveTagset(TEST_USER_ID, ["pushups", "10"]);
// Tagsets with identical tag sets are deduplicated
assert.strictEqual(id1, id2);
const tagsets = db.getTagsets(TEST_USER_ID);
assert.strictEqual(tagsets.length, 1);
});
it("should retrieve tagsets with their tags", () => {
db.saveTagset(TEST_USER_ID, ["exercise", "pushups", "20"]);
const tagsets = db.getTagsets(TEST_USER_ID);
assert.strictEqual(tagsets.length, 1);
assert.deepStrictEqual(tagsets[0].tags.sort(), ["20", "exercise", "pushups"]);
});
});
describe("getItems (unified)", () => {
it("should return all items when no type filter", () => {
db.saveUrl(TEST_USER_ID, "https://example.com");
db.saveText(TEST_USER_ID, "A note");
db.saveTagset(TEST_USER_ID, ["tag1", "tag2"]);
const items = db.getItems(TEST_USER_ID);
assert.strictEqual(items.length, 3);
});
it("should filter items by type", () => {
db.saveUrl(TEST_USER_ID, "https://example.com");
db.saveText(TEST_USER_ID, "A note");
db.saveTagset(TEST_USER_ID, ["tag1"]);
const urls = db.getItems(TEST_USER_ID, "url");
assert.strictEqual(urls.length, 1);
assert.strictEqual(urls[0].type, "url");
const texts = db.getItems(TEST_USER_ID, "text");
assert.strictEqual(texts.length, 1);
assert.strictEqual(texts[0].type, "text");
const tagsets = db.getItems(TEST_USER_ID, "tagset");
assert.strictEqual(tagsets.length, 1);
assert.strictEqual(tagsets[0].type, "tagset");
});
});
describe("deleteItem", () => {
it("should soft-delete any item type", () => {
const urlId = db.saveUrl(TEST_USER_ID, "https://example.com");
const textId = db.saveText(TEST_USER_ID, "Note");
const tagsetId = db.saveTagset(TEST_USER_ID, ["tag"]);
assert.strictEqual(db.getItems(TEST_USER_ID).length, 3);
db.deleteItem(TEST_USER_ID, urlId);
assert.strictEqual(db.getItems(TEST_USER_ID).length, 2);
db.deleteItem(TEST_USER_ID, textId);
assert.strictEqual(db.getItems(TEST_USER_ID).length, 1);
db.deleteItem(TEST_USER_ID, tagsetId);
assert.strictEqual(db.getItems(TEST_USER_ID).length, 0);
});
it("should retain soft-deleted items in database with includeDeleted", () => {
const urlId = db.saveUrl(TEST_USER_ID, "https://example.com");
db.deleteItem(TEST_USER_ID, urlId);
// Default query excludes deleted items
assert.strictEqual(db.getItems(TEST_USER_ID).length, 0);
// includeDeleted should show them
const allItems = db.getItems(TEST_USER_ID, null, "default", true);
assert.strictEqual(allItems.length, 1);
assert.ok(allItems[0].deletedAt > 0, "deletedAt should be set");
});
});
describe("updateItemTags", () => {
it("should update tags for any item type", () => {
const textId = db.saveText(TEST_USER_ID, "Note", ["old"]);
db.updateItemTags(TEST_USER_ID, textId, ["new1", "new2"]);
const texts = db.getTexts(TEST_USER_ID);
assert.deepStrictEqual(texts[0].tags.sort(), ["new1", "new2"]);
});
});
describe("Multi-user isolation", () => {
it("should isolate data between users", () => {
const user1 = "user1";
const user2 = "user2";
db.saveUrl(user1, "https://user1.com", ["user1-tag"]);
db.saveUrl(user2, "https://user2.com", ["user2-tag"]);
const urls1 = db.getSavedUrls(user1);
const urls2 = db.getSavedUrls(user2);
assert.strictEqual(urls1.length, 1);
assert.strictEqual(urls1[0].url, "https://user1.com");
assert.strictEqual(urls2.length, 1);
assert.strictEqual(urls2[0].url, "https://user2.com");
});
});
describe("saveImage", () => {
// Create a simple 1x1 PNG image buffer for testing
const testPngBuffer = Buffer.from([
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d,
0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
0x08, 0x02, 0x00, 0x00, 0x00, 0x90, 0x77, 0x53, 0xde, 0x00, 0x00, 0x00,
0x0c, 0x49, 0x44, 0x41, 0x54, 0x08, 0xd7, 0x63, 0xf8, 0xff, 0xff, 0x3f,
0x00, 0x05, 0xfe, 0x02, 0xfe, 0xdc, 0xcc, 0x59, 0xe7, 0x00, 0x00, 0x00,
0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
]);
it("should save an image and return id", () => {
const id = db.saveImage(TEST_USER_ID, "test.png", testPngBuffer, "image/png");
assert.ok(id, "should return an id");
assert.match(id, /^[0-9a-f-]{36}$/, "id should be a UUID");
});
it("should save an image with tags", () => {
const id = db.saveImage(TEST_USER_ID, "photo.png", testPngBuffer, "image/png", ["photo", "test"]);
assert.ok(id);
const images = db.getImages(TEST_USER_ID);
assert.strictEqual(images.length, 1);
assert.strictEqual(images[0].filename, "photo.png");
assert.deepStrictEqual(images[0].tags.sort(), ["photo", "test"]);
});
it("should store file on disk", () => {
db.saveImage(TEST_USER_ID, "disk.png", testPngBuffer, "image/png");
const imagesDir = path.join(TEST_DATA_DIR, TEST_USER_ID, "profiles", "default", "images");
const files = fs.readdirSync(imagesDir);
assert.strictEqual(files.length, 1);
assert.ok(files[0].endsWith(".png"));
});
it("should deduplicate identical images", () => {
const id1 = db.saveImage(TEST_USER_ID, "first.png", testPngBuffer, "image/png");
const id2 = db.saveImage(TEST_USER_ID, "second.png", testPngBuffer, "image/png");
// Should create two different item records
assert.notStrictEqual(id1, id2);
// But only one file on disk
const imagesDir = path.join(TEST_DATA_DIR, TEST_USER_ID, "profiles", "default", "images");
const files = fs.readdirSync(imagesDir);
assert.strictEqual(files.length, 1);
});
it("should reject non-image MIME types", () => {
assert.throws(
() => db.saveImage(TEST_USER_ID, "file.txt", Buffer.from("text"), "text/plain"),
/must be an image/
);
});
it("should reject images over size limit", () => {
const largeBuffer = Buffer.alloc(db.MAX_IMAGE_SIZE + 1);
assert.throws(
() => db.saveImage(TEST_USER_ID, "large.png", largeBuffer, "image/png"),
/exceeds maximum size/
);
});
it("should store metadata correctly", () => {
db.saveImage(TEST_USER_ID, "meta.png", testPngBuffer, "image/png");
const images = db.getImages(TEST_USER_ID);
assert.strictEqual(images[0].mime, "image/png");
assert.strictEqual(images[0].size, testPngBuffer.length);
});
});
describe("getImages", () => {
const testPngBuffer = Buffer.from([
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d,
0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
0x08, 0x02, 0x00, 0x00, 0x00, 0x90, 0x77, 0x53, 0xde, 0x00, 0x00, 0x00,
0x0c, 0x49, 0x44, 0x41, 0x54, 0x08, 0xd7, 0x63, 0xf8, 0xff, 0xff, 0x3f,
0x00, 0x05, 0xfe, 0x02, 0xfe, 0xdc, 0xcc, 0x59, 0xe7, 0x00, 0x00, 0x00,
0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
]);
it("should return empty array when no images", () => {
const images = db.getImages(TEST_USER_ID);
assert.deepStrictEqual(images, []);
});
it("should return all images with metadata", () => {
db.saveImage(TEST_USER_ID, "img1.png", testPngBuffer, "image/png", ["tag1"]);
db.saveImage(TEST_USER_ID, "img2.png", Buffer.from(testPngBuffer), "image/png", ["tag2"]);
const images = db.getImages(TEST_USER_ID);
assert.strictEqual(images.length, 2);
assert.ok(images[0].id);
assert.ok(images[0].filename);
assert.ok(images[0].mime);
assert.ok(images[0].size);
assert.ok(images[0].createdAt);
assert.ok(Array.isArray(images[0].tags));
});
});
describe("getImageById", () => {
const testPngBuffer = Buffer.from([
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d,
0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
0x08, 0x02, 0x00, 0x00, 0x00, 0x90, 0x77, 0x53, 0xde, 0x00, 0x00, 0x00,
0x0c, 0x49, 0x44, 0x41, 0x54, 0x08, 0xd7, 0x63, 0xf8, 0xff, 0xff, 0x3f,
0x00, 0x05, 0xfe, 0x02, 0xfe, 0xdc, 0xcc, 0x59, 0xe7, 0x00, 0x00, 0x00,
0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
]);
it("should return image by id", () => {
const id = db.saveImage(TEST_USER_ID, "find.png", testPngBuffer, "image/png");
const image = db.getImageById(TEST_USER_ID, id);
assert.ok(image);
assert.strictEqual(image.id, id);
assert.strictEqual(image.filename, "find.png");
assert.ok(image.metadata.hash);
});
it("should return null for non-existent id", () => {
const image = db.getImageById(TEST_USER_ID, "non-existent");
assert.strictEqual(image, null);
});
});
describe("getImagePath", () => {
const testPngBuffer = Buffer.from([
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d,
0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
0x08, 0x02, 0x00, 0x00, 0x00, 0x90, 0x77, 0x53, 0xde, 0x00, 0x00, 0x00,
0x0c, 0x49, 0x44, 0x41, 0x54, 0x08, 0xd7, 0x63, 0xf8, 0xff, 0xff, 0x3f,
0x00, 0x05, 0xfe, 0x02, 0xfe, 0xdc, 0xcc, 0x59, 0xe7, 0x00, 0x00, 0x00,
0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
]);
it("should return valid file path", () => {
const id = db.saveImage(TEST_USER_ID, "path.png", testPngBuffer, "image/png");
const imagePath = db.getImagePath(TEST_USER_ID, id);
assert.ok(imagePath);
assert.ok(fs.existsSync(imagePath));
});
it("should return null for non-existent id", () => {
const imagePath = db.getImagePath(TEST_USER_ID, "non-existent");
assert.strictEqual(imagePath, null);
});
});
describe("deleteImage", () => {
const testPngBuffer = Buffer.from([
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d,
0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
0x08, 0x02, 0x00, 0x00, 0x00, 0x90, 0x77, 0x53, 0xde, 0x00, 0x00, 0x00,
0x0c, 0x49, 0x44, 0x41, 0x54, 0x08, 0xd7, 0x63, 0xf8, 0xff, 0xff, 0x3f,
0x00, 0x05, 0xfe, 0x02, 0xfe, 0xdc, 0xcc, 0x59, 0xe7, 0x00, 0x00, 0x00,
0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
]);
it("should soft-delete image record", () => {
const id = db.saveImage(TEST_USER_ID, "del.png", testPngBuffer, "image/png");
assert.strictEqual(db.getImages(TEST_USER_ID).length, 1);
db.deleteImage(TEST_USER_ID, id);
// Image should not appear in default query (soft-deleted)
assert.strictEqual(db.getImages(TEST_USER_ID).length, 0);
});
it("should keep file on disk after soft-delete (tombstone for sync)", () => {
const id = db.saveImage(TEST_USER_ID, "single.png", testPngBuffer, "image/png");
const imagePath = db.getImagePath(TEST_USER_ID, id);
assert.ok(fs.existsSync(imagePath));
db.deleteImage(TEST_USER_ID, id);
// File stays on disk — soft-delete preserves the row and file
assert.ok(fs.existsSync(imagePath), "file should remain after soft-delete");
});
it("should retain soft-deleted image in database", () => {
const id = db.saveImage(TEST_USER_ID, "retained.png", testPngBuffer, "image/png");
db.deleteImage(TEST_USER_ID, id);
// Should still exist with includeDeleted
const allItems = db.getItems(TEST_USER_ID, "image", "default", true);
assert.strictEqual(allItems.length, 1);
assert.ok(allItems[0].deletedAt > 0, "deletedAt should be set");
});
});
describe("getItems with images", () => {
const testPngBuffer = Buffer.from([
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d,
0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
0x08, 0x02, 0x00, 0x00, 0x00, 0x90, 0x77, 0x53, 0xde, 0x00, 0x00, 0x00,
0x0c, 0x49, 0x44, 0x41, 0x54, 0x08, 0xd7, 0x63, 0xf8, 0xff, 0xff, 0x3f,
0x00, 0x05, 0xfe, 0x02, 0xfe, 0xdc, 0xcc, 0x59, 0xe7, 0x00, 0x00, 0x00,
0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
]);
it("should include images in getItems", () => {
db.saveUrl(TEST_USER_ID, "https://example.com");
db.saveText(TEST_USER_ID, "Note");
db.saveImage(TEST_USER_ID, "pic.png", testPngBuffer, "image/png");
const items = db.getItems(TEST_USER_ID);
assert.strictEqual(items.length, 3);
const imageItem = items.find((i) => i.type === "image");
assert.ok(imageItem);
assert.ok(imageItem.metadata);
assert.strictEqual(imageItem.metadata.mime, "image/png");
});
it("should filter by image type", () => {
db.saveUrl(TEST_USER_ID, "https://example.com");
db.saveImage(TEST_USER_ID, "pic.png", testPngBuffer, "image/png");
const images = db.getItems(TEST_USER_ID, "image");
assert.strictEqual(images.length, 1);
assert.strictEqual(images[0].type, "image");
});
});
describe("Unified Item Types", () => {
it("should support url, text, tagset, image types", () => {
const urlId = db.saveUrl(TEST_USER_ID, "https://example.com");
const textId = db.saveText(TEST_USER_ID, "My note");
const tagsetId = db.saveTagset(TEST_USER_ID, ["tag1", "tag2"]);
const items = db.getItems(TEST_USER_ID);
const types = items.map((i) => i.type).sort();
assert.deepStrictEqual(types, ["tagset", "text", "url"]);
});
it("should save items with correct type values", () => {
const urlId = db.saveItem(TEST_USER_ID, "url", "https://test.com", ["web"]);
const textId = db.saveItem(TEST_USER_ID, "text", "Note content", ["note"]);
const tagsetId = db.saveItem(TEST_USER_ID, "tagset", null, ["exercise", "20"]);
const items = db.getItems(TEST_USER_ID);
const urlItem = items.find((i) => i.id === urlId);
const textItem = items.find((i) => i.id === textId);
const tagsetItem = items.find((i) => i.id === tagsetId);
assert.strictEqual(urlItem.type, "url");
assert.strictEqual(textItem.type, "text");
assert.strictEqual(tagsetItem.type, "tagset");
});
});
describe("Sync Columns Schema", () => {
it("should have sync columns in schema", () => {
const conn = db.getConnection(TEST_USER_ID);
const tableInfo = conn.all("PRAGMA table_info(items)");
const columnNames = tableInfo.map((col) => col.name);
assert.ok(columnNames.includes("syncId"), "should have syncId column");
assert.ok(columnNames.includes("syncedAt"), "should have syncedAt column");
});
it("should have sync_id index", () => {
const conn = db.getConnection(TEST_USER_ID);
const indexes = conn.all("SELECT name FROM sqlite_master WHERE type='index' AND tbl_name='items'");
const indexNames = indexes.map((idx) => idx.name);
assert.ok(indexNames.includes("idx_items_syncId"), "should have idx_items_syncId index");
});
});
describe("Snake-case Migration", () => {
it("should migrate snake_case item_tags columns to camelCase", () => {
// Simulate a legacy database with snake_case columns
const Database = require("better-sqlite3");
const legacyDir = path.join(TEST_DATA_DIR, "legacy-user", "profiles", "default");
fs.mkdirSync(legacyDir, { recursive: true });
const legacyDb = new Database(path.join(legacyDir, "datastore.sqlite"));
legacyDb.pragma("journal_mode = WAL");
// Create legacy schema with snake_case columns
legacyDb.exec(`
CREATE TABLE items (
id TEXT PRIMARY KEY,
type TEXT NOT NULL,
content TEXT,
metadata TEXT,
sync_id TEXT DEFAULT '',
sync_source TEXT DEFAULT '',
synced_at INTEGER DEFAULT 0,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
deleted_at INTEGER DEFAULT 0
);
CREATE TABLE tags (
id TEXT PRIMARY KEY,
name TEXT NOT NULL UNIQUE,
frequency INTEGER DEFAULT 1,
last_used_at INTEGER NOT NULL,
frecency_score REAL DEFAULT 0.0,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
CREATE TABLE item_tags (
item_id TEXT NOT NULL,
tag_id TEXT NOT NULL,
created_at INTEGER NOT NULL,
PRIMARY KEY (item_id, tag_id)
);
CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT);
`);
// Insert a legacy item
legacyDb.prepare(`
INSERT INTO items (id, type, content, sync_id, sync_source, synced_at, created_at, updated_at, deleted_at)
VALUES ('legacy-1', 'url', 'https://example.com', '', '', 0, 1000, 1000, 0)
`).run();
legacyDb.close();
// Now open via db module — initializeSchema should migrate columns
delete require.cache[require.resolve("./db")];
const freshDb = require("./db");
const conn = freshDb.getConnection("legacy-user");
// Verify columns were renamed
const itemCols = conn.all("PRAGMA table_info(items)").map(c => c.name);
assert.ok(itemCols.includes("syncId"), "items.sync_id should be renamed to syncId");
assert.ok(itemCols.includes("createdAt"), "items.created_at should be renamed to createdAt");
assert.ok(itemCols.includes("deletedAt"), "items.deleted_at should be renamed to deletedAt");
assert.ok(!itemCols.includes("sync_id"), "items should not have snake_case sync_id");
const tagCols = conn.all("PRAGMA table_info(tags)").map(c => c.name);
assert.ok(tagCols.includes("lastUsed"), "tags.last_used_at should be renamed to lastUsed");
assert.ok(tagCols.includes("frecencyScore"), "tags.frecency_score should be renamed to frecencyScore");
const itCols = conn.all("PRAGMA table_info(item_tags)").map(c => c.name);
assert.ok(itCols.includes("itemId"), "item_tags.item_id should be renamed to itemId");
assert.ok(itCols.includes("tagId"), "item_tags.tag_id should be renamed to tagId");
// Verify the legacy data is still accessible
const items = freshDb.getItems("legacy-user");
assert.strictEqual(items.length, 1);
assert.strictEqual(items[0].content, "https://example.com");
freshDb.closeAllConnections();
});
});
describe("Production Schema Migration", () => {
it("should migrate original production schema to canonical (INTEGER PK, last_used, TEXT timestamps)", () => {
// This tests the ACTUAL production database schema from commit 21c30add5839.
// Key differences from canonical:
// - tags.id: INTEGER PRIMARY KEY AUTOINCREMENT (not TEXT)
// - tags column: last_used (not last_used_at or lastUsed)
// - item_tags.tag_id: INTEGER (not TEXT)
// - All timestamps: TEXT (not INTEGER)
// - items.deleted_at: NULL means not deleted (not 0)
const Database = require("better-sqlite3");
const rbDir = path.join(TEST_DATA_DIR, "rebuild-user", "profiles", "default");
fs.mkdirSync(rbDir, { recursive: true });
const rbDb = new Database(path.join(rbDir, "datastore.sqlite"));
rbDb.pragma("journal_mode = WAL");
rbDb.exec(`
CREATE TABLE items (
id TEXT PRIMARY KEY,
type TEXT NOT NULL CHECK(type IN ('url', 'text', 'tagset', 'image')),
content TEXT,
metadata TEXT,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
deleted_at TEXT
);
CREATE TABLE tags (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE,
frequency INTEGER NOT NULL DEFAULT 0,
last_used TEXT NOT NULL,
frecency_score REAL NOT NULL DEFAULT 0.0,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE TABLE item_tags (
item_id TEXT NOT NULL,
tag_id INTEGER NOT NULL,
created_at TEXT NOT NULL,
PRIMARY KEY (item_id, tag_id),
FOREIGN KEY (item_id) REFERENCES items(id) ON DELETE CASCADE,
FOREIGN KEY (tag_id) REFERENCES tags(id) ON DELETE CASCADE
);
CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT NOT NULL);
CREATE INDEX IF NOT EXISTS idx_items_type ON items(type);
CREATE INDEX IF NOT EXISTS idx_tags_name ON tags(name);
CREATE INDEX IF NOT EXISTS idx_tags_frecency ON tags(frecency_score DESC);
`);
// Insert test data with original TEXT timestamps and NULL deleted_at
const ts = new Date("2026-01-15T10:00:00Z").toISOString();
rbDb.prepare(`
INSERT INTO items (id, type, content, created_at, updated_at, deleted_at)
VALUES ('rb-1', 'url', 'https://example.com', ?, ?, NULL)
`).run(ts, ts);
rbDb.prepare(`
INSERT INTO tags (name, frequency, last_used, frecency_score, created_at, updated_at)
VALUES ('test', 3, ?, 15.0, ?, ?)
`).run(ts, ts, ts);
rbDb.prepare(`
INSERT INTO item_tags (item_id, tag_id, created_at) VALUES ('rb-1', 1, ?)
`).run(ts);
rbDb.close();
// Open via db module — ALTER RENAME will fail, rebuild should kick in
delete require.cache[require.resolve("./db")];
const freshDb = require("./db");
const conn = freshDb.getConnection("rebuild-user");
// Verify all columns are camelCase after rebuild
const itemCols = new Set(conn.all("PRAGMA table_info(items)").map(c => c.name));
assert.ok(itemCols.has("createdAt"), "items should have createdAt");
assert.ok(itemCols.has("deletedAt"), "items should have deletedAt");
assert.ok(itemCols.has("syncId"), "items should have syncId");
const tagCols = new Set(conn.all("PRAGMA table_info(tags)").map(c => c.name));
assert.ok(tagCols.has("lastUsed"), "tags should have lastUsed (was last_used)");
assert.ok(tagCols.has("frecencyScore"), "tags should have frecencyScore");
assert.ok(tagCols.has("createdAt"), "tags should have createdAt");
// Verify tags.id is now TEXT (was INTEGER AUTOINCREMENT)
const tagIdCol = conn.all("PRAGMA table_info(tags)").find(c => c.name === "id");
assert.ok(tagIdCol, "tags should have id column");
assert.strictEqual(tagIdCol.type, "TEXT", "tags.id should be TEXT after rebuild");
const itCols = new Set(conn.all("PRAGMA table_info(item_tags)").map(c => c.name));
assert.ok(itCols.has("itemId"), "item_tags should have itemId");
assert.ok(itCols.has("tagId"), "item_tags should have tagId");
// Verify item_tags.tagId is now TEXT (was INTEGER)
const itTagIdCol = conn.all("PRAGMA table_info(item_tags)").find(c => c.name === "tagId");
assert.ok(itTagIdCol, "item_tags should have tagId column");
assert.strictEqual(itTagIdCol.type, "TEXT", "item_tags.tagId should be TEXT after rebuild");
// Verify data survived the rebuild
const items = freshDb.getItems("rebuild-user");
assert.strictEqual(items.length, 1);
assert.strictEqual(items[0].content, "https://example.com");
const tags = freshDb.getTagsByFrecency("rebuild-user");
assert.strictEqual(tags.length, 1);
assert.strictEqual(tags[0].name, "test");
assert.strictEqual(tags[0].frequency, 3, "tag frequency should be preserved");
// Verify new items can be saved
const newId = freshDb.saveUrl("rebuild-user", "https://new.com", ["newtag"]);
assert.ok(newId);
assert.strictEqual(freshDb.getItems("rebuild-user").length, 2);
freshDb.closeAllConnections();
});
});
describe("Missing Columns Safety Net", () => {
it("should add missing columns when tags table has incomplete schema", () => {
// Simulate a legacy DB where tags table was created without some columns
// (e.g., an older version of the code that didn't have frecencyScore or lastUsed)
const Database = require("better-sqlite3");
const mcDir = path.join(TEST_DATA_DIR, "missing-cols-user", "profiles", "default");
fs.mkdirSync(mcDir, { recursive: true });
const mcDb = new Database(path.join(mcDir, "datastore.sqlite"));
mcDb.pragma("journal_mode = WAL");
// Minimal tags table — missing lastUsed, frecencyScore, createdAt, updatedAt
mcDb.exec(`
CREATE TABLE items (
id TEXT PRIMARY KEY,
type TEXT NOT NULL,
content TEXT,
metadata TEXT,
syncId TEXT DEFAULT '',
syncSource TEXT DEFAULT '',
syncedAt INTEGER DEFAULT 0,
createdAt INTEGER NOT NULL,
updatedAt INTEGER NOT NULL,
deletedAt INTEGER DEFAULT 0
);
CREATE TABLE tags (
id TEXT PRIMARY KEY,
name TEXT NOT NULL UNIQUE,
frequency INTEGER DEFAULT 1
);
CREATE TABLE item_tags (
itemId TEXT NOT NULL,
tagId TEXT NOT NULL,
createdAt INTEGER NOT NULL,
PRIMARY KEY (itemId, tagId)
);
CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT);
`);
// Insert test data with minimal columns
mcDb.prepare("INSERT INTO tags (id, name, frequency) VALUES ('t1', 'testtag', 3)").run();
mcDb.close();
// Open via db module — should add missing columns without crashing
delete require.cache[require.resolve("./db")];
const freshDb = require("./db");
const conn = freshDb.getConnection("missing-cols-user");
// Verify all required columns exist
const tagCols = new Set(conn.all("PRAGMA table_info(tags)").map(c => c.name));
assert.ok(tagCols.has("lastUsed"), "tags should have lastUsed after safety net");
assert.ok(tagCols.has("frecencyScore"), "tags should have frecencyScore after safety net");
assert.ok(tagCols.has("createdAt"), "tags should have createdAt after safety net");
assert.ok(tagCols.has("updatedAt"), "tags should have updatedAt after safety net");
// Verify existing data survived
const tags = freshDb.getTagsByFrecency("missing-cols-user");
assert.strictEqual(tags.length, 1);
assert.strictEqual(tags[0].name, "testtag");
assert.strictEqual(tags[0].frequency, 3);
// Verify new operations work
freshDb.saveUrl("missing-cols-user", "https://example.com", ["newtag"]);
const items = freshDb.getItems("missing-cols-user");
assert.strictEqual(items.length, 1);
freshDb.closeAllConnections();
});
});
describe("TEXT Timestamp Migration", () => {
it("should convert ISO string and stringified number timestamps to integers", () => {
const Database = require("better-sqlite3");
const tsDir = path.join(TEST_DATA_DIR, "ts-user", "profiles", "default");
fs.mkdirSync(tsDir, { recursive: true });
const tsDb = new Database(path.join(tsDir, "datastore.sqlite"));
tsDb.pragma("journal_mode = WAL");
// Create schema with TEXT affinity columns (simulates production)
tsDb.exec(`
CREATE TABLE items (
id TEXT PRIMARY KEY,
type TEXT NOT NULL,
content TEXT,
metadata TEXT,
syncId TEXT DEFAULT '',
syncSource TEXT DEFAULT '',
syncedAt TEXT DEFAULT '0',
createdAt TEXT NOT NULL,
updatedAt TEXT NOT NULL,
deletedAt TEXT DEFAULT '0'
);
CREATE TABLE tags (
id TEXT PRIMARY KEY,
name TEXT NOT NULL UNIQUE,
frequency INTEGER DEFAULT 1,
lastUsed TEXT NOT NULL,
frecencyScore REAL DEFAULT 0.0,
createdAt TEXT NOT NULL,
updatedAt TEXT NOT NULL
);
CREATE TABLE item_tags (
itemId TEXT NOT NULL,
tagId TEXT NOT NULL,
createdAt TEXT NOT NULL,
PRIMARY KEY (itemId, tagId)
);
CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT);
`);
// Insert items with TEXT timestamps (ISO strings and stringified numbers)
tsDb.prepare(`
INSERT INTO items (id, type, content, syncId, syncSource, syncedAt, createdAt, updatedAt, deletedAt)
VALUES ('iso-1', 'text', 'hello', '', '', '0', '2026-01-27T21:12:47.876Z', '2026-01-27T21:12:47.876Z', '0')
`).run();
tsDb.prepare(`
INSERT INTO items (id, type, content, syncId, syncSource, syncedAt, createdAt, updatedAt, deletedAt)
VALUES ('num-1', 'url', 'https://example.com', '', '', '0', '1769559596558.0', '1769559596558.0', '1769509253170')
`).run();
tsDb.prepare(`
INSERT INTO tags (id, name, frequency, lastUsed, frecencyScore, createdAt, updatedAt)
VALUES ('tag-1', 'test', 1, '2026-01-27T12:00:00.000Z', 10.0, '2026-01-27T12:00:00.000Z', '2026-01-27T12:00:00.000Z')
`).run();
tsDb.prepare(`
INSERT INTO item_tags (itemId, tagId, createdAt) VALUES ('iso-1', 'tag-1', '2026-01-27T12:00:00.000Z')
`).run();
tsDb.close();
// Open via db module — initializeSchema should migrate timestamps
delete require.cache[require.resolve("./db")];
const freshDb = require("./db");
const conn = freshDb.getConnection("ts-user");
// DB values are numeric (ISO converted to Unix ms, float strings to integers)
// but may remain TEXT type due to column TEXT affinity from legacy schema.
// The toTimestamp() safety net in response code ensures API returns integers.
const row1 = conn.get("SELECT CAST(createdAt AS INTEGER) as v FROM items WHERE id = 'iso-1'");
assert.ok(row1.v > 1700000000000, `ISO timestamp should be Unix ms, got ${row1.v}`);
const row2 = conn.get("SELECT CAST(createdAt AS INTEGER) as v, CAST(deletedAt AS INTEGER) as dv FROM items WHERE id = 'num-1'");
assert.strictEqual(row2.v, 1769559596558, `Should preserve value: ${row2.v}`);
assert.strictEqual(row2.dv, 1769509253170);
// Verify API response returns JavaScript numbers (the critical fix for clients)
const items = freshDb.getItems("ts-user", null, "default", true);
assert.strictEqual(items.length, 2);
for (const item of items) {
assert.strictEqual(typeof item.createdAt, "number", `createdAt should be number, got ${typeof item.createdAt}: ${item.createdAt}`);
assert.strictEqual(typeof item.updatedAt, "number", `updatedAt should be number, got ${typeof item.updatedAt}: ${item.updatedAt}`);
assert.strictEqual(typeof item.deletedAt, "number", `deletedAt should be number, got ${typeof item.deletedAt}: ${item.deletedAt}`);
}
// Verify getItemsSince works correctly with TEXT-affinity timestamps
const sinceItems = freshDb.getItemsSince("ts-user", 0, null, "default");
assert.strictEqual(sinceItems.length, 2, `getItemsSince(0) should return all items`);
for (const item of sinceItems) {
assert.strictEqual(typeof item.createdAt, "number");
assert.strictEqual(typeof item.updatedAt, "number");
}
freshDb.closeAllConnections();
});
});
describe("Production State: snake_case + TEXT timestamps", () => {
it("should handle legacy DB with snake_case columns AND TEXT timestamps end-to-end", () => {
// This is the actual production state that caused the crash:
// snake_case columns with TEXT-affinity timestamps
const Database = require("better-sqlite3");
const prodDir = path.join(TEST_DATA_DIR, "prod-user", "profiles", "default");
fs.mkdirSync(prodDir, { recursive: true });
const prodDb = new Database(path.join(prodDir, "datastore.sqlite"));
prodDb.pragma("journal_mode = WAL");
// Create legacy schema: snake_case columns with TEXT affinity
prodDb.exec(`
CREATE TABLE items (
id TEXT PRIMARY KEY,
type TEXT NOT NULL,
content TEXT,
metadata TEXT,
sync_id TEXT DEFAULT '',
sync_source TEXT DEFAULT '',