peisar 0.3.11

A practical Markdown parser written in Rust
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
//! In-memory + on-disk cache of Markdown and asset files.
//!
//! [`PeisarCache`] loads every markdown file under an entry directory
//! (plus optional assets) into memory, mirrors them to a `.peisar_cache`
//! directory on disk, and — once [`PeisarCache::start_watching`] is called —
//! keeps both in sync with recursive file-watching. It is the engine behind
//! the `peisar-ssg` dev server, but it works as a plain Rust dependency too.
//!
//! # Rust usage
//!
//! Construct a cache with [`PeisarCache::new`] or
//! [`PeisarCache::with_config`]. Construction walks the entry directory
//! once, snapshots every discovered file into memory, and persists the
//! snapshot to `.peisar_cache` before returning:
//!
//! ```no_run
//! use peisar::cache::{CachedContent, PeisarCache};
//!
//! # fn main() -> std::io::Result<()> {
//! // Markdown from "contents", assets from "public". Relative paths are
//! // resolved against the current working directory.
//! let mut cache = PeisarCache::with_config("contents", Some("public"))?;
//!
//! // Every cached markdown file, as absolute path -> raw text.
//! for (path, text) in cache.all() {
//!     println!("{} ({} bytes)", path.display(), text.len());
//! }
//!
//! // Single entries keep their variant: markdown is `Text`, binary assets
//! // are `Binary`. The cache is keyed by absolute paths, so keys from
//! // `all()` — or `current_dir()`-joined paths — can be passed to `get()`.
//! let index = std::env::current_dir()?.join("contents").join("index.md");
//! match cache.get(&index) {
//!     Some(CachedContent::Text(md)) => println!("{md}"),
//!     Some(CachedContent::Binary(bytes)) => println!("{} bytes", bytes.len()),
//!     None => println!("not cached"),
//! }
//!
//! // Keep memory and disk in sync with the filesystem until the cache is
//! // dropped (which stops the watcher and joins the worker thread).
//! cache.start_watching()?;
//! # Ok(())
//! # }
//! ```
//!
//! # Discovery rules
//!
//! - *Markdown*: files under the entry directory whose extension is `md`,
//!   `markdown`, `mdown`, `mkdn`, `mkd`, `mdwn`, `mkdown`, or `ron`; they are
//!   cached as UTF-8 text.
//! - *Assets*: files under the assets directory — the `public` directory of
//!   the current working directory when no assets directory is given — with
//!   a known image, script, style, font, or audio/video extension. Images,
//!   fonts, and audio/video files are cached as raw bytes; `js`, `css`,
//!   `map`, and `svg` are cached as UTF-8 text.
//!
//! # Disk format
//!
//! - Text (markdown) entries are stored as `.json` (default) or `.bin`
//!   (when `PEISAR_CACHE_FORMAT=bincode`) files that embed the raw content
//!   and the parsed front matter.
//! - Binary assets are mirrored verbatim under their original names.
//! - Writes are atomic (temp file + rename) and content-hashed (BLAKE3) so
//!   unchanged entries are not rewritten; files removed from the source
//!   tree are pruned from the cache directory.
//! - A `.peisar_cache` entry is appended to `.gitignore` automatically.
//!
//! # Threading and lifecycle
//!
//! Disk persistence runs on a background worker thread fed by a channel.
//! Watcher events update the in-memory cache first, then enqueue an
//! incremental update/remove/sync command so the watcher callback never
//! blocks on I/O. Dropping a [`PeisarCache`] stops the watcher, closes the
//! channel, and joins the worker thread — Rust consumers need no explicit
//! `dispose()`.
//!
//! # JavaScript surface
//!
//! `new PeisarCache(entryDir, assetsDir?)`, `PeisarCache.withConfigJs`,
//! `startWatchingJs()`, `getText`, `getBinary`, `listFiles`,
//! `markdownFiles()`, `assetFiles()`, `onChange(cb) → id`, `offChange(id)`,
//! `dispose()`.

mod file;
use file::{
    ASSET_BINARY_EXTENSIONS, ASSET_EXTENSIONS, MARKDOWN_EXTENSIONS, collect_asset_files,
    collect_markdown_files,
};
#[cfg(feature = "npm")]
use napi::bindgen_prelude::*;
#[cfg(feature = "npm")]
use napi_derive::napi;
use notify::{RecommendedWatcher, RecursiveMode, Watcher};
use serde::{Deserialize, Serialize};
use serde_yaml::Value as YamlValue;
use std::collections::{HashMap, HashSet};
use std::env;
use std::fs::{self, OpenOptions};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{Arc, RwLock, mpsc};
use std::thread;

/// A file-change event delivered to change callbacks
/// (see [`PeisarCache::on_change`]).
#[cfg_attr(feature = "npm", napi(object))]
#[derive(Debug, Clone)]
pub struct CacheChangeEvent {
    /// Absolute path of the changed file.
    pub path: String,
    /// `"create"`, `"modify"`, `"remove"`, or `"other"`.
    pub kind: String,
    /// `true` when the file is under the markdown entry directory.
    pub is_markdown: bool,
}

/// Serialized form of a cached text entry, embedded in every `.json` / `.bin`
/// cache file: the source path relative to the working directory, the raw
/// markdown, and its parsed front matter.
#[derive(Serialize, Deserialize, Debug, PartialEq)]
struct CacheEntry {
    file_path: String,
    markdown_raw_content: String,
    frontmatter_data: Option<YamlValue>,
    #[serde(default)]
    is_binary: bool,
}

/// Parse a leading `--- … ---` YAML front-matter block, returning `None`
/// when the content does not start with one.
fn parse_frontmatter(content: &str) -> Option<YamlValue> {
    let mut lines = content.lines();
    if let Some(first) = lines.next() {
        if first.trim() == "---" {
            let mut fm_lines: Vec<&str> = Vec::new();
            for line in lines {
                if line.trim() == "---" {
                    break;
                }
                fm_lines.push(line);
            }
            let fm_str = fm_lines.join("\n");
            match serde_yaml::from_str(&fm_str) {
                Ok(v) => Some(v),
                Err(_) => None,
            }
        } else {
            None
        }
    } else {
        None
    }
}

/// An entry stored in the cache: raw UTF-8 text (markdown and textual
/// assets) or raw bytes (binary assets). Exposed to JavaScript so JS
/// consumers can branch on the variant.
#[cfg_attr(feature = "npm", napi)]
#[derive(Debug, Clone)]
pub enum CachedContent {
    /// UTF-8 text content (markdown files and textual assets).
    Text(String),
    /// Raw bytes (binary assets like images or fonts).
    Binary(Vec<u8>),
}

/// Boxed change callback held in the subscription registry.
///
/// In npm builds, JavaScript callbacks are wrapped into a thread-safe
/// function before they are stored because watcher events fire off-thread.
pub type CacheChangeCallback = Box<dyn Fn(CacheChangeEvent) + Send + 'static>;

/// Backward-compatible name for callbacks used by the JavaScript binding.
pub type JsChangeCallback = CacheChangeCallback;

/// Shared registry of JS change callbacks, keyed by subscription id.
#[derive(Clone, Default)]
struct ChangeCallbacks {
    inner: Arc<std::sync::Mutex<HashMap<u32, CacheChangeCallback>>>,
    next_id: Arc<AtomicU32>,
}

impl ChangeCallbacks {
    fn add(&self, cb: CacheChangeCallback) -> u32 {
        let mut map = self.inner.lock().unwrap();
        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
        map.insert(id, cb);
        id
    }

    fn remove(&self, id: u32) {
        self.inner.lock().unwrap().remove(&id);
    }

    fn clear(&self) {
        self.inner.lock().unwrap().clear();
    }

    fn dispatch(&self, event: CacheChangeEvent) {
        let map = self.inner.lock().unwrap();
        for cb in map.values() {
            cb(event.clone());
        }
    }
}

/// Incremental command sent to the persistence worker by construction and
/// the file watcher.
#[derive(Debug)]
enum PersistCommand {
    Update(PathBuf, CachedContent),
    Remove(PathBuf),
    SyncAll(HashMap<PathBuf, CachedContent>),
}

/// Map a source path to its on-disk cache target and its path relative to
/// `cwd`. Text entries gain the cache-format extension (`.json` / `.bin`);
/// binary assets keep their original file name.
fn compute_target_for_source(src: &Path, cwd: &Path, is_binary: bool) -> (PathBuf, PathBuf) {
    // returns (target_path, rel_path)
    //
    // Paths outside `cwd` are mirrored by their normal path components
    // (e.g. `/elsewhere/b.png` → `elsewhere/b.png`).  Keeping the relative
    // path free of a leading root is important: `PathBuf::join` with an
    // absolute path *replaces* the buffer, which would otherwise make the
    // cache write its entry over the original source file.
    let rel_path = match src.strip_prefix(cwd) {
        Ok(rel) => rel.to_path_buf(),
        Err(_) => {
            let mut rel = PathBuf::new();
            rel.extend(src.components().filter_map(|c| match c {
                std::path::Component::Normal(p) => Some(p),
                _ => None,
            }));
            rel
        }
    };
    let parent = rel_path.parent().map(|p| p.to_path_buf());
    let fname = rel_path
        .file_name()
        .map(|f| f.to_string_lossy().to_string())
        .unwrap_or_default();
    let cache_dir = cwd.join(".peisar_cache");

    let target = if is_binary {
        // mirror original filename for binary assets
        match &parent {
            Some(p) => cache_dir.join(p).join(&fname),
            None => cache_dir.join(&fname),
        }
    } else {
        // text entries are stored in the configured cache format (default: JSON).
        // Set PEISAR_CACHE_FORMAT=bincode to store compact binary entries (.bin).
        let fmt = env::var("PEISAR_CACHE_FORMAT").unwrap_or_else(|_| "json".to_string());
        let ext = if fmt.eq_ignore_ascii_case("bincode") {
            ".bin"
        } else {
            ".json"
        };
        let cache_name = format!("{}{}", fname, ext);
        match &parent {
            Some(p) => cache_dir.join(p).join(&cache_name),
            None => cache_dir.join(&cache_name),
        }
    };

    (target, rel_path)
}

/// Synchronously persist `map` to `<cwd>/.peisar_cache`, prune stale cache
/// files, and make sure `.gitignore` contains a `.peisar_cache` entry.
fn persist_cache_map(map: &HashMap<PathBuf, CachedContent>) -> io::Result<()> {
    let cwd = env::current_dir()?;
    let cache_dir = cwd.join(".peisar_cache");
    fs::create_dir_all(&cache_dir)?;

    let mut expected_files: HashSet<PathBuf> = HashSet::new();

    for (path, content) in map {
        match content {
            CachedContent::Text(text) => {
                let (target, rel_path) = compute_target_for_source(path, &cwd, false);
                let target_dir = target
                    .parent()
                    .map(|p| p.to_path_buf())
                    .unwrap_or(cache_dir.clone());
                fs::create_dir_all(&target_dir)?;

                let file_path_str = rel_path.to_string_lossy().to_string();
                let fm = parse_frontmatter(text);
                let entry = CacheEntry {
                    file_path: file_path_str,
                    markdown_raw_content: text.clone(),
                    frontmatter_data: fm,
                    is_binary: false,
                };

                // Support configurable on-disk format via PEISAR_CACHE_FORMAT.
                let fmt = env::var("PEISAR_CACHE_FORMAT").unwrap_or_else(|_| "json".to_string());
                if fmt.eq_ignore_ascii_case("bincode") {
                    let bytes = bincode::serialize(&entry).map_err(|e| {
                        io::Error::new(io::ErrorKind::Other, format!("bincode error: {}", e))
                    })?;

                    // Write atomically to a temp file then rename
                    let fname = target
                        .file_name()
                        .map(|f| f.to_string_lossy().to_string())
                        .unwrap_or_default();
                    let tmp_name = format!("{}.tmp", fname);
                    let tmp_path = target_dir.join(&tmp_name);
                    fs::write(&tmp_path, &bytes)?;
                    fs::rename(&tmp_path, &target)?;
                } else {
                    let json = serde_json::to_string_pretty(&entry).map_err(|e| {
                        io::Error::new(io::ErrorKind::Other, format!("serde_json error: {}", e))
                    })?;

                    // Write atomically to a temp file then rename
                    let fname = target
                        .file_name()
                        .map(|f| f.to_string_lossy().to_string())
                        .unwrap_or_default();
                    let tmp_name = format!("{}.tmp", fname);
                    let tmp_path = target_dir.join(&tmp_name);
                    fs::write(&tmp_path, json.as_bytes())?;
                    fs::rename(&tmp_path, &target)?;
                }

                expected_files.insert(target);
            }
            CachedContent::Binary(bytes) => {
                let (target, _rel_path) = compute_target_for_source(path, &cwd, true);
                let target_dir = target
                    .parent()
                    .map(|p| p.to_path_buf())
                    .unwrap_or(cache_dir.clone());
                fs::create_dir_all(&target_dir)?;

                let fname = target
                    .file_name()
                    .map(|f| f.to_string_lossy().to_string())
                    .unwrap_or_default();
                let tmp_name = format!("{}.tmp", fname);
                let tmp_path = target_dir.join(&tmp_name);
                fs::write(&tmp_path, bytes)?;
                fs::rename(&tmp_path, &target)?;

                expected_files.insert(target);
            }
        }
    }

    // Remove stale files that are present in .peisar_cache but not expected
    fn collect_files(dir: &Path, out: &mut Vec<PathBuf>) -> io::Result<()> {
        for entry in fs::read_dir(dir)? {
            let entry = entry?;
            let p = entry.path();
            if p.is_dir() {
                collect_files(&p, out)?;
            } else if p.is_file() {
                out.push(p);
            }
        }
        Ok(())
    }

    if cache_dir.exists() {
        let mut existing_files: Vec<PathBuf> = Vec::new();
        collect_files(&cache_dir, &mut existing_files)?;
        for f in existing_files {
            if !expected_files.contains(&f) {
                let _ = fs::remove_file(&f);
            }
        }

        // Remove empty directories under .peisar_cache
        fn remove_empty(dir: &Path) -> io::Result<()> {
            for entry in fs::read_dir(dir)? {
                let entry = entry?;
                let p = entry.path();
                if p.is_dir() {
                    remove_empty(&p)?;
                    if fs::read_dir(&p)?.next().is_none() {
                        let _ = fs::remove_dir(&p);
                    }
                }
            }
            Ok(())
        }
        let _ = remove_empty(&cache_dir);
    }

    // Ensure .peisar_cache is in .gitignore
    let gitignore_path = cwd.join(".gitignore");
    if gitignore_path.exists() {
        let existing = fs::read_to_string(&gitignore_path)?;
        let mut has_entry = false;
        for line in existing.lines() {
            if line.trim() == ".peisar_cache" {
                has_entry = true;
                break;
            }
        }
        if !has_entry {
            let mut file = OpenOptions::new().append(true).open(&gitignore_path)?;
            if !existing.ends_with('\n') {
                file.write_all(b"\n")?;
            }
            file.write_all(b".peisar_cache\n")?;
        }
    } else {
        fs::write(gitignore_path, ".peisar_cache\n")?;
    }

    Ok(())
}

/// In-memory cache of the Markdown and asset files under a directory tree.
///
/// The cache maps absolute source paths to [`CachedContent`] entries, is
/// mirrored to a `.peisar_cache` directory on disk, and — after
/// [`PeisarCache::start_watching`] — tracks the source directories with a
/// recursive file watcher.
///
/// Rust consumers read the cache with [`PeisarCache::get`] and
/// [`PeisarCache::all`]; JavaScript consumers use the N-API methods below
/// (`getText`, `getBinary`, `listFiles`, `markdownFiles`, `assetFiles`, …).
#[cfg_attr(feature = "npm", napi)]
pub struct PeisarCache {
    // cache maps source path -> cached content (text or binary)
    cache: Arc<RwLock<HashMap<PathBuf, CachedContent>>>,
    watcher: Option<RecommendedWatcher>,
    entry_dir: PathBuf,
    assets_dir: Option<PathBuf>,
    // Sender for persistence commands — None until worker is started in new()
    persist_tx: Option<mpsc::Sender<PersistCommand>>,
    // Background worker handle to join on drop
    worker_handle: Option<thread::JoinHandle<()>>,
    // JS onChange subscriptions fed by the watcher
    change_callbacks: ChangeCallbacks,
}

#[cfg_attr(feature = "npm", napi)]
impl PeisarCache {
    /// Construct a new PeisarCache using the default discovery behavior.
    ///
    /// JS: `new PeisarCache(entryDir, assetsDir?)` — both plain strings.
    #[cfg(feature = "npm")]
    #[napi(constructor)]
    pub fn new_js(entry_dir: String, assets_dir: Option<String>) -> Result<Self> {
        Self::with_config_js(entry_dir, assets_dir)
    }

    /// JS: same as the constructor, for callers that prefer a factory shape.
    /// Kept non-generic so NAPI can export it.
    #[cfg(feature = "npm")]
    #[napi(factory)]
    pub fn with_config_js(entry_dir: String, assets_dir: Option<String>) -> Result<Self> {
        PeisarCache::with_config(entry_dir, assets_dir)
            .map_err(|e| napi::Error::new(napi::Status::GenericFailure, format!("{}", e)))
    }

    /// Construct a [`PeisarCache`] over `entry_dir` with the default
    /// discovery behavior — equivalent to `with_config(entry_dir, None)`.
    ///
    /// `entry_dir` may be absolute or relative (resolved against the
    /// current working directory); it is normalized to an absolute path so
    /// watcher events match the cache keys. Assets default to the `public`
    /// directory of the current working directory when present.
    /// Construction snapshots every discovered file into memory and
    /// persists the snapshot to `.peisar_cache` before returning; see the
    /// [module documentation](crate::cache) for a full example.
    ///
    /// Rust-only constructor kept for the crate's internal users and tests
    /// (generic signatures cannot cross the NAPI boundary).
    pub fn new<P: AsRef<Path>>(entry_dir: P) -> io::Result<Self> {
        PeisarCache::with_config(entry_dir, None::<&Path>)
    }

    /// Construct a [`PeisarCache`] with an optional custom assets directory.
    ///
    /// If `assets_dir` is `Some(path)`, that path (absolute or relative to
    /// the current working directory) is used to discover assets. If
    /// `assets_dir` is `None`, the default behavior is to use the `public`
    /// directory at project root when present.
    ///
    /// Construction loads all markdown files under `entry_dir` (and the
    /// assets) into the in-memory cache, persists the cache to the
    /// `.peisar_cache` directory, and ensures `.gitignore` contains an
    /// entry for `.peisar_cache`.
    ///
    /// Rust-only constructor (generic signatures cannot cross the NAPI
    /// boundary); JavaScript uses the `PeisarCache` constructor or the
    /// `withConfigJs` factory.
    pub fn with_config<P: AsRef<Path>, Q: AsRef<Path>>(
        entry_dir: P,
        assets_dir: Option<Q>,
    ) -> io::Result<Self> {
        // Resolve the entry dir to an absolute path: notify watcher events
        // carry absolute paths, so the `is_markdown` prefix check below needs
        // an absolute `entry_dir` even when JS passes a relative directory.
        let cwd = env::current_dir()?;
        let entry_dir = {
            let d = entry_dir.as_ref();
            if d.is_absolute() {
                d.to_path_buf()
            } else {
                cwd.join(d)
            }
        };

        // Build initial in-memory cache with markdown files (text) and
        // optionally assets under the provided assets_dir (binary/text
        // depending on extension).
        let mut cache_map: HashMap<PathBuf, CachedContent> = HashMap::new();

        let files = collect_markdown_files(&entry_dir)?;
        for f in files {
            if let Ok(text) = fs::read_to_string(&f) {
                cache_map.insert(f, CachedContent::Text(text));
            }
        }

        // Resolve assets_dir: use provided path when given; otherwise fall
        // back to "public" at project root if present.
        let resolved_assets: Option<PathBuf> = match assets_dir {
            Some(p) => {
                let pbuf = p.as_ref().to_path_buf();
                if pbuf.is_absolute() {
                    Some(pbuf)
                } else {
                    Some(cwd.join(pbuf))
                }
            }
            None => {
                let p = cwd.join("public");
                if p.exists() && p.is_dir() {
                    Some(p)
                } else {
                    None
                }
            }
        };

        if let Some(ref a_dir) = resolved_assets {
            if let Ok(asset_files) = collect_asset_files(a_dir) {
                for f in asset_files {
                    // determine if binary by extension
                    let is_binary = f
                        .extension()
                        .and_then(|e| e.to_str())
                        .map(|s| ASSET_BINARY_EXTENSIONS.contains(&s.to_lowercase().as_str()))
                        .unwrap_or(false);

                    if is_binary {
                        if let Ok(bytes) = fs::read(&f) {
                            cache_map.insert(f, CachedContent::Binary(bytes));
                        }
                    } else {
                        if let Ok(text) = fs::read_to_string(&f) {
                            cache_map.insert(f, CachedContent::Text(text));
                        }
                    }
                }
            }
        }

        // Persist the initial cache to disk synchronously so callers observe
        // cache files immediately after construction.
        persist_cache_map(&cache_map)?;

        // Prepare background persistence worker that accepts incremental
        // commands so the watcher callback can remain non-blocking for large
        // repositories. Seed the worker's hash map with the current contents
        // to enable content-hash-based de-duplication.
        let (tx, rx) = mpsc::channel::<PersistCommand>();

        let mut last_hashes: HashMap<PathBuf, String> = HashMap::new();
        for (src, content) in &cache_map {
            let (target, _rel) =
                compute_target_for_source(src, &cwd, matches!(content, CachedContent::Binary(_)));
            let hash = match content {
                CachedContent::Text(s) => blake3::hash(s.as_bytes()).to_hex().to_string(),
                CachedContent::Binary(b) => blake3::hash(b).to_hex().to_string(),
            };
            last_hashes.insert(target, hash);
        }

        let handle = thread::spawn(move || {
            let cache_dir = cwd.join(".peisar_cache");

            // helper to collect all files under cache_dir
            fn collect_files(dir: &Path, out: &mut Vec<PathBuf>) -> io::Result<()> {
                for entry in fs::read_dir(dir)? {
                    let entry = entry?;
                    let p = entry.path();
                    if p.is_dir() {
                        collect_files(&p, out)?;
                    } else if p.is_file() {
                        out.push(p);
                    }
                }
                Ok(())
            }

            let mut hashes = last_hashes;

            while let Ok(cmd) = rx.recv() {
                match cmd {
                    PersistCommand::Update(src, content) => {
                        let is_binary = matches!(content, CachedContent::Binary(_));
                        let (target, rel_path) = compute_target_for_source(&src, &cwd, is_binary);
                        let target_dir = target
                            .parent()
                            .map(|p| p.to_path_buf())
                            .unwrap_or(cache_dir.clone());
                        if let Err(e) = fs::create_dir_all(&target_dir) {
                            eprintln!("persist mkdir error: {:?}", e);
                            continue;
                        }

                        let hash = match &content {
                            CachedContent::Text(s) => {
                                blake3::hash(s.as_bytes()).to_hex().to_string()
                            }
                            CachedContent::Binary(b) => blake3::hash(b).to_hex().to_string(),
                        };
                        if let Some(prev) = hashes.get(&target) {
                            if prev == &hash {
                                // nothing to do
                                continue;
                            }
                        }

                        if is_binary {
                            if let CachedContent::Binary(bytes) = content {
                                let fname = target
                                    .file_name()
                                    .map(|f| f.to_string_lossy().to_string())
                                    .unwrap_or_default();
                                let tmp_name = format!("{}.tmp", fname);
                                let tmp_path = target_dir.join(&tmp_name);
                                if let Err(e) = fs::write(&tmp_path, &bytes) {
                                    eprintln!("persist write tmp error: {:?}", e);
                                    continue;
                                }
                                if let Err(e) = fs::rename(&tmp_path, &target) {
                                    eprintln!("persist rename error: {:?}", e);
                                    let _ = fs::remove_file(&tmp_path);
                                    continue;
                                }
                                hashes.insert(target, hash);
                            }
                        } else {
                            if let CachedContent::Text(text) = content {
                                let fm = parse_frontmatter(&text);
                                let entry = CacheEntry {
                                    file_path: rel_path.to_string_lossy().to_string(),
                                    markdown_raw_content: text.clone(),
                                    frontmatter_data: fm,
                                    is_binary: false,
                                };

                                let fmt = env::var("PEISAR_CACHE_FORMAT")
                                    .unwrap_or_else(|_| "json".to_string());
                                if fmt.eq_ignore_ascii_case("bincode") {
                                    match bincode::serialize(&entry) {
                                        Ok(bytes) => {
                                            let fname = target
                                                .file_name()
                                                .map(|f| f.to_string_lossy().to_string())
                                                .unwrap_or_default();
                                            let tmp_name = format!("{}.tmp", fname);
                                            let tmp_path = target_dir.join(&tmp_name);
                                            if let Err(e) = fs::write(&tmp_path, &bytes) {
                                                eprintln!("persist write tmp error: {:?}", e);
                                                continue;
                                            }
                                            if let Err(e) = fs::rename(&tmp_path, &target) {
                                                eprintln!("persist rename error: {:?}", e);
                                                let _ = fs::remove_file(&tmp_path);
                                                continue;
                                            }
                                            hashes.insert(target, hash);
                                        }
                                        Err(e) => eprintln!("bincode serialize error: {:?}", e),
                                    }
                                } else {
                                    match serde_json::to_string_pretty(&entry) {
                                        Ok(json) => {
                                            let fname = target
                                                .file_name()
                                                .map(|f| f.to_string_lossy().to_string())
                                                .unwrap_or_default();
                                            let tmp_name = format!("{}.tmp", fname);
                                            let tmp_path = target_dir.join(&tmp_name);
                                            if let Err(e) = fs::write(&tmp_path, json.as_bytes()) {
                                                eprintln!("persist write tmp error: {:?}", e);
                                                continue;
                                            }
                                            if let Err(e) = fs::rename(&tmp_path, &target) {
                                                eprintln!("persist rename error: {:?}", e);
                                                let _ = fs::remove_file(&tmp_path);
                                                continue;
                                            }
                                            hashes.insert(target, hash);
                                        }
                                        Err(e) => eprintln!("serde_json error: {:?}", e),
                                    }
                                }
                            }
                        }
                    }
                    PersistCommand::Remove(src) => {
                        // Try removing both possible targets (text .json and mirrored binary file)
                        let (target_text, _rel) = compute_target_for_source(&src, &cwd, false);
                        if target_text.exists() {
                            if let Err(e) = fs::remove_file(&target_text) {
                                eprintln!("persist remove error: {:?}", e);
                            }
                        }
                        hashes.remove(&target_text);

                        let (target_bin, _rel2) = compute_target_for_source(&src, &cwd, true);
                        if target_bin.exists() {
                            if let Err(e) = fs::remove_file(&target_bin) {
                                eprintln!("persist remove error: {:?}", e);
                            }
                        }
                        hashes.remove(&target_bin);

                        // clean up empty parent directories for both targets
                        for target in &[target_text, target_bin] {
                            if let Some(mut parent) = target.parent().map(|p| p.to_path_buf()) {
                                while parent.starts_with(&cache_dir)
                                    && fs::read_dir(&parent)
                                        .map(|mut it| it.next().is_none())
                                        .unwrap_or(false)
                                {
                                    let _ = fs::remove_dir(&parent);
                                    if let Some(p) = parent.parent() {
                                        parent = p.to_path_buf();
                                    } else {
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    PersistCommand::SyncAll(map) => {
                        let mut expected: HashSet<PathBuf> = HashSet::new();
                        for (src, content) in map {
                            let is_binary = matches!(content, CachedContent::Binary(_));
                            let (target, rel_path) =
                                compute_target_for_source(&src, &cwd, is_binary);
                            expected.insert(target.clone());

                            let target_dir = target
                                .parent()
                                .map(|p| p.to_path_buf())
                                .unwrap_or(cache_dir.clone());
                            if let Err(e) = fs::create_dir_all(&target_dir) {
                                eprintln!("persist mkdir error: {:?}", e);
                                continue;
                            }

                            let hash = match &content {
                                CachedContent::Text(s) => {
                                    blake3::hash(s.as_bytes()).to_hex().to_string()
                                }
                                CachedContent::Binary(b) => blake3::hash(b).to_hex().to_string(),
                            };
                            if let Some(prev) = hashes.get(&target) {
                                if prev == &hash {
                                    continue;
                                }
                            }

                            if is_binary {
                                if let CachedContent::Binary(bytes) = content {
                                    let fname = target
                                        .file_name()
                                        .map(|f| f.to_string_lossy().to_string())
                                        .unwrap_or_default();
                                    let tmp_name = format!("{}.tmp", fname);
                                    let tmp_path = target_dir.join(&tmp_name);
                                    if let Err(e) = fs::write(&tmp_path, &bytes) {
                                        eprintln!("persist write tmp error: {:?}", e);
                                        continue;
                                    }
                                    if let Err(e) = fs::rename(&tmp_path, &target) {
                                        eprintln!("persist rename error: {:?}", e);
                                        let _ = fs::remove_file(&tmp_path);
                                        continue;
                                    }
                                    hashes.insert(target, hash);
                                }
                            } else {
                                if let CachedContent::Text(text) = content {
                                    let fm = parse_frontmatter(&text);
                                    let entry = CacheEntry {
                                        file_path: rel_path.to_string_lossy().to_string(),
                                        markdown_raw_content: text.clone(),
                                        frontmatter_data: fm,
                                        is_binary: false,
                                    };

                                    let fmt = env::var("PEISAR_CACHE_FORMAT")
                                        .unwrap_or_else(|_| "json".to_string());
                                    if fmt.eq_ignore_ascii_case("bincode") {
                                        match bincode::serialize(&entry) {
                                            Ok(bytes) => {
                                                let fname = target
                                                    .file_name()
                                                    .map(|f| f.to_string_lossy().to_string())
                                                    .unwrap_or_default();
                                                let tmp_name = format!("{}.tmp", fname);
                                                let tmp_path = target_dir.join(&tmp_name);
                                                if let Err(e) = fs::write(&tmp_path, &bytes) {
                                                    eprintln!("persist write tmp error: {:?}", e);
                                                    continue;
                                                }
                                                if let Err(e) = fs::rename(&tmp_path, &target) {
                                                    eprintln!("persist rename error: {:?}", e);
                                                    let _ = fs::remove_file(&tmp_path);
                                                    continue;
                                                }
                                                hashes.insert(target, hash);
                                            }
                                            Err(e) => eprintln!("bincode serialize error: {:?}", e),
                                        }
                                    } else {
                                        match serde_json::to_string_pretty(&entry) {
                                            Ok(json) => {
                                                let fname = target
                                                    .file_name()
                                                    .map(|f| f.to_string_lossy().to_string())
                                                    .unwrap_or_default();
                                                let tmp_name = format!("{}.tmp", fname);
                                                let tmp_path = target_dir.join(&tmp_name);
                                                if let Err(e) =
                                                    fs::write(&tmp_path, json.as_bytes())
                                                {
                                                    eprintln!("persist write tmp error: {:?}", e);
                                                    continue;
                                                }
                                                if let Err(e) = fs::rename(&tmp_path, &target) {
                                                    eprintln!("persist rename error: {:?}", e);
                                                    let _ = fs::remove_file(&tmp_path);
                                                    continue;
                                                }
                                                hashes.insert(target, hash);
                                            }
                                            Err(e) => eprintln!("serde_json error: {:?}", e),
                                        }
                                    }
                                }
                            }
                        }

                        // remove stale
                        if cache_dir.exists() {
                            let mut existing: Vec<PathBuf> = Vec::new();
                            if let Err(e) = collect_files(&cache_dir, &mut existing) {
                                eprintln!("collect files error: {:?}", e);
                            } else {
                                for f in existing {
                                    if !expected.contains(&f) {
                                        let _ = fs::remove_file(&f);
                                        hashes.remove(&f);
                                    }
                                }
                            }

                            // remove empty dirs
                            fn remove_empty(dir: &Path) -> io::Result<()> {
                                for entry in fs::read_dir(dir)? {
                                    let entry = entry?;
                                    let p = entry.path();
                                    if p.is_dir() {
                                        remove_empty(&p)?;
                                        if fs::read_dir(&p)?.next().is_none() {
                                            let _ = fs::remove_dir(&p);
                                        }
                                    }
                                }
                                Ok(())
                            }
                            let _ = remove_empty(&cache_dir);
                        }
                    }
                }
            }
        });

        Ok(PeisarCache {
            cache: Arc::new(RwLock::new(cache_map)),
            watcher: None,
            entry_dir,
            assets_dir: resolved_assets,
            persist_tx: Some(tx),
            worker_handle: Some(handle),
            change_callbacks: ChangeCallbacks::default(),
        })
    }

    /// JS: `cache.startWatchingJs()` — start watching the entry (and
    /// assets) directories recursively; errors surface as JS exceptions.
    #[cfg(feature = "npm")]
    #[napi]
    pub fn start_watching_js(&mut self) -> Result<()> {
        self.start_watching()
            .map_err(|e| napi::Error::new(napi::Status::GenericFailure, format!("{}", e)))
    }

    /// Start watching the entry (and assets) directories recursively.
    ///
    /// From then on, create/modify/remove events for markdown files and
    /// assets update the in-memory cache and enqueue a matching persistence
    /// command; events on directories trigger a full rescan. Events are also
    /// forwarded to JavaScript `onChange` subscribers (see
    /// [`PeisarCache::on_change`]).
    ///
    /// The returned [`io::Result`] covers watcher setup errors only; runtime
    /// errors are printed to stderr by the watch callback.
    pub fn start_watching(&mut self) -> io::Result<()> {
        let cache = Arc::clone(&self.cache);
        let entry_dir = self.entry_dir.clone();
        let assets_dir = self.assets_dir.clone();
        // Shared with the watcher thread so JS onChange callbacks fire on
        // every detected create/modify/remove event.
        let change_callbacks = self.change_callbacks.clone();

        let tx = match &self.persist_tx {
            Some(t) => t.clone(),
            None => {
                return Err(io::Error::new(
                    io::ErrorKind::Other,
                    "persistence worker not started",
                ));
            }
        };

        // recommended_watcher takes a closure that's invoked on file events.
        let mut watcher: RecommendedWatcher =
            notify::recommended_watcher(move |res: notify::Result<notify::Event>| {
                match res {
                    Ok(event) => {
                        let kind = event.kind.clone();
                        for path in event.paths {
                            // Notify JS subscribers about this change first,
                            // then update the in-memory cache below.
                            let is_markdown = path.starts_with(&entry_dir);
                            let kind_str = if matches!(kind, notify::EventKind::Create(_)) {
                                "create"
                            } else if matches!(kind, notify::EventKind::Modify(_)) {
                                "modify"
                            } else if matches!(kind, notify::EventKind::Remove(_)) {
                                "remove"
                            } else {
                                "other"
                            };
                            change_callbacks.dispatch(CacheChangeEvent {
                                path: path.to_string_lossy().to_string(),
                                kind: kind_str.to_string(),
                                is_markdown,
                            });
                            // If the event targets a directory, rescan everything.
                            if path.is_dir() {
                                let mut new_map: HashMap<PathBuf, CachedContent> = HashMap::new();

                                if let Ok(files) = collect_markdown_files(&entry_dir) {
                                    for f in files {
                                        if let Ok(text) = fs::read_to_string(&f) {
                                            new_map.insert(f, CachedContent::Text(text));
                                        }
                                    }
                                }

                                if let Some(ref a_dir) = assets_dir {
                                    if let Ok(asset_files) = collect_asset_files(a_dir) {
                                        for f in asset_files {
                                            let ext_l = f
                                                .extension()
                                                .and_then(|e| e.to_str())
                                                .map(|s| s.to_lowercase())
                                                .unwrap_or_default();
                                            if ASSET_EXTENSIONS.contains(&ext_l.as_str()) {
                                                let is_binary = ASSET_BINARY_EXTENSIONS
                                                    .contains(&ext_l.as_str());
                                                if is_binary {
                                                    if let Ok(bytes) = fs::read(&f) {
                                                        new_map.insert(
                                                            f,
                                                            CachedContent::Binary(bytes),
                                                        );
                                                    }
                                                } else if let Ok(text) = fs::read_to_string(&f) {
                                                    new_map.insert(f, CachedContent::Text(text));
                                                }
                                            }
                                        }
                                    }
                                }

                                if let Ok(mut w) = cache.write() {
                                    *w = new_map.clone();
                                    if let Err(e) = tx.send(PersistCommand::SyncAll(new_map)) {
                                        eprintln!("persist send error: {:?}", e);
                                    }
                                }

                                continue;
                            }

                            if path.is_file() {
                                if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
                                    let ext_l = ext.to_lowercase();

                                    // Markdown file
                                    if MARKDOWN_EXTENSIONS.contains(&ext_l.as_str()) {
                                        match fs::read_to_string(&path) {
                                            Ok(text) => {
                                                if let Ok(mut w) = cache.write() {
                                                    w.insert(
                                                        path.clone(),
                                                        CachedContent::Text(text.clone()),
                                                    );
                                                    if let Err(e) = tx.send(PersistCommand::Update(
                                                        path.clone(),
                                                        CachedContent::Text(text),
                                                    )) {
                                                        eprintln!("persist send error: {:?}", e);
                                                    }
                                                }
                                            }
                                            Err(_) => {
                                                if let Ok(mut w) = cache.write() {
                                                    w.remove(&path);
                                                    if let Err(e) = tx
                                                        .send(PersistCommand::Remove(path.clone()))
                                                    {
                                                        eprintln!("persist send error: {:?}", e);
                                                    }
                                                }
                                            }
                                        }
                                    // Asset file
                                    } else if ASSET_EXTENSIONS.contains(&ext_l.as_str()) {
                                        let is_binary =
                                            ASSET_BINARY_EXTENSIONS.contains(&ext_l.as_str());
                                        if is_binary {
                                            match fs::read(&path) {
                                                Ok(bytes) => {
                                                    if let Ok(mut w) = cache.write() {
                                                        w.insert(
                                                            path.clone(),
                                                            CachedContent::Binary(bytes.clone()),
                                                        );
                                                        if let Err(e) =
                                                            tx.send(PersistCommand::Update(
                                                                path.clone(),
                                                                CachedContent::Binary(bytes),
                                                            ))
                                                        {
                                                            eprintln!(
                                                                "persist send error: {:?}",
                                                                e
                                                            );
                                                        }
                                                    }
                                                }
                                                Err(_) => {
                                                    if let Ok(mut w) = cache.write() {
                                                        w.remove(&path);
                                                        if let Err(e) = tx.send(
                                                            PersistCommand::Remove(path.clone()),
                                                        ) {
                                                            eprintln!(
                                                                "persist send error: {:?}",
                                                                e
                                                            );
                                                        }
                                                    }
                                                }
                                            }
                                        } else {
                                            match fs::read_to_string(&path) {
                                                Ok(text) => {
                                                    if let Ok(mut w) = cache.write() {
                                                        w.insert(
                                                            path.clone(),
                                                            CachedContent::Text(text.clone()),
                                                        );
                                                        if let Err(e) =
                                                            tx.send(PersistCommand::Update(
                                                                path.clone(),
                                                                CachedContent::Text(text),
                                                            ))
                                                        {
                                                            eprintln!(
                                                                "persist send error: {:?}",
                                                                e
                                                            );
                                                        }
                                                    }
                                                }
                                                Err(_) => {
                                                    if let Ok(mut w) = cache.write() {
                                                        w.remove(&path);
                                                        if let Err(e) = tx.send(
                                                            PersistCommand::Remove(path.clone()),
                                                        ) {
                                                            eprintln!(
                                                                "persist send error: {:?}",
                                                                e
                                                            );
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    Err(e) => eprintln!("watch error: {:?}", e),
                }
            })
            .map_err(|e| {
                io::Error::new(
                    io::ErrorKind::Other,
                    format!("notify::recommended_watcher error: {}", e),
                )
            })?;

        watcher
            .watch(&self.entry_dir, RecursiveMode::Recursive)
            .map_err(|e| {
                io::Error::new(io::ErrorKind::Other, format!("notify::watch error: {}", e))
            })?;

        if let Some(a) = &self.assets_dir {
            watcher.watch(a, RecursiveMode::Recursive).map_err(|e| {
                io::Error::new(io::ErrorKind::Other, format!("notify::watch error: {}", e))
            })?;
        }

        self.watcher = Some(watcher);
        Ok(())
    }

    /// Get a cached entry by source path, if present.
    ///
    /// The cache is keyed by absolute paths — the keys of [`PeisarCache::all`]
    /// — so relative paths never match. The returned [`CachedContent`]
    /// preserves the variant the file was cached as: `Text` for markdown and
    /// textual assets, `Binary` for binary assets.
    pub fn get(&self, path: &Path) -> Option<CachedContent> {
        match self.cache.read() {
            Ok(r) => r.get(path).cloned(),
            Err(_) => None,
        }
    }

    /// Return a clone of the entire cache map for textual entries only:
    /// absolute source path -> raw UTF-8 text. Binary assets are omitted;
    /// use [`PeisarCache::get`] to read them.
    pub fn all(&self) -> HashMap<PathBuf, String> {
        match self.cache.read() {
            Ok(r) => {
                let mut out = HashMap::new();
                for (k, v) in r.iter() {
                    if let CachedContent::Text(s) = v {
                        out.insert(k.clone(), s.clone());
                    }
                }
                out
            }
            Err(_) => HashMap::new(),
        }
    }

    /// ----------------------------------------------------------------
    /// JavaScript (NAPI) surface
    /// ----------------------------------------------------------------
    /// All JS methods take/return plain strings because `&Path`/`PathBuf`
    /// do not cross the NAPI boundary.

    /// JS: `cache.getText(absPath)` — cached text of a file, or null.
    #[cfg_attr(feature = "npm", napi)]
    pub fn get_text(&self, abs_path: String) -> Option<String> {
        match self.cache.read() {
            Ok(r) => match r.get(Path::new(&abs_path)) {
                Some(CachedContent::Text(s)) => Some(s.clone()),
                _ => None,
            },
            Err(_) => None,
        }
    }

    /// JS: `cache.getBinary(absPath)` — cached bytes of a binary asset, or null.
    #[cfg_attr(feature = "npm", napi)]
    pub fn get_binary(&self, abs_path: String) -> Option<Vec<u8>> {
        match self.cache.read() {
            Ok(r) => match r.get(Path::new(&abs_path)) {
                Some(CachedContent::Binary(b)) => Some(b.clone()),
                _ => None,
            },
            Err(_) => None,
        }
    }

    /// JS: `cache.listFiles()` — absolute paths of everything cached.
    #[cfg_attr(feature = "npm", napi)]
    pub fn list_files(&self) -> Vec<String> {
        match self.cache.read() {
            Ok(r) => r.keys().map(|p| p.to_string_lossy().to_string()).collect(),
            Err(_) => Vec::new(),
        }
    }

    /// JS: `cache.markdownFiles()` — absolute paths of cached markdown files.
    #[cfg_attr(feature = "npm", napi)]
    pub fn markdown_files(&self) -> Vec<String> {
        self.filter_cached_files(|ext| MARKDOWN_EXTENSIONS.contains(&ext))
    }

    /// JS: `cache.assetFiles()` — absolute paths of cached non-markdown files.
    #[cfg_attr(feature = "npm", napi)]
    pub fn asset_files(&self) -> Vec<String> {
        self.filter_cached_files(|ext| !MARKDOWN_EXTENSIONS.contains(&ext))
    }

    /// Filter cached keys by extension predicate (helper shared by
    /// `markdown_files` / `asset_files`).
    fn filter_cached_files(&self, keep: fn(&str) -> bool) -> Vec<String> {
        match self.cache.read() {
            Ok(r) => r
                .keys()
                .filter(|p| {
                    p.extension()
                        .and_then(|e| e.to_str())
                        .map(|e| keep(e))
                        .unwrap_or(false)
                })
                .map(|p| p.to_string_lossy().to_string())
                .collect(),
            Err(_) => Vec::new(),
        }
    }

    /// JS: `cache.onChange(cb)` — invoke `cb(event)` on every file change the
    /// watcher detects while watching is active. Returns a subscription id
    /// that can be passed to `offChange(id)`.
    ///
    /// The callback is wrapped in a `ThreadsafeFunction` because notify
    /// events fire on the watcher thread, not the JS main thread.
    #[cfg(feature = "npm")]
    #[napi]
    pub fn on_change(
        &self,
        #[napi(ts_arg_type = "(event: CacheChangeEvent) => void")] callback: Function<
            'static,
            CacheChangeEvent,
            Unknown<'static>,
        >,
    ) -> Result<u32> {
        // `ThreadsafeFunction` is required: notify events fire on the watcher
        // thread, not the JS main thread.
        use napi::threadsafe_function::ThreadsafeFunctionCallMode;

        // Weak TSFN: the subscription must not keep the Node event loop
        // alive on its own — long-running consumers (dev server) keep the
        // loop alive via their own handles (http listener), so an
        // onChange-only script should exit when its work is done.
        let tsfn = callback
            .build_threadsafe_function::<CacheChangeEvent>()
            .weak::<true>()
            .build()?;

        Ok(self
            .change_callbacks
            .add(Box::new(move |event: CacheChangeEvent| {
                tsfn.call(event, ThreadsafeFunctionCallMode::NonBlocking);
            })))
    }

    /// Register a Rust callback that receives every change detected while
    /// watching is active. Returns a subscription id that can be passed to
    /// [`PeisarCache::off_change`].
    #[cfg(not(feature = "npm"))]
    pub fn on_change<F>(&self, callback: F) -> u32
    where
        F: Fn(CacheChangeEvent) + Send + 'static,
    {
        self.change_callbacks.add(Box::new(callback))
    }

    /// JS: `cache.offChange(id)` — remove a previously registered callback.
    #[cfg_attr(feature = "npm", napi)]
    pub fn off_change(&self, id: u32) {
        self.change_callbacks.remove(id);
    }

    /// JS: `cache.dispose()` — stop the watcher and drop JS change callbacks.
    /// Safe to call more than once.
    ///
    /// Rust consumers do not need this: dropping the [`PeisarCache`] stops
    /// the watcher, closes the persistence channel, and joins the worker.
    #[cfg_attr(feature = "npm", napi)]
    pub fn dispose(&mut self) {
        self.watcher = None;
        self.change_callbacks.clear();
    }
}

// Dropping a `PeisarCache` is the Rust equivalent of the JS `dispose()`:
// the watcher is released with the struct, closing the channel exits the
// persistence worker, and joining it guarantees queued writes land before
// the value goes away.
impl Drop for PeisarCache {
    fn drop(&mut self) {
        // Closing the sender will cause the worker thread to exit.
        self.persist_tx.take();
        if let Some(handle) = self.worker_handle.take() {
            let _ = handle.join();
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs::{self, File};
    use std::io::Write;
    use std::sync::Mutex;

    static TEST_CWD_LOCK: Mutex<()> = Mutex::new(());

    #[cfg(not(feature = "npm"))]
    #[test]
    fn on_change_registers_a_rust_callback() -> io::Result<()> {
        let _guard = TEST_CWD_LOCK.lock().unwrap();
        let tmp = env::temp_dir().join(format!(
            "peisar_change_callback_test_{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map_err(|e| io::Error::other(format!("time error: {e}")))?
                .as_millis()
        ));
        fs::create_dir_all(&tmp)?;

        let cache = PeisarCache::new(&tmp)?;
        let received = Arc::new(std::sync::Mutex::new(Vec::new()));
        let received_callback = Arc::clone(&received);
        let subscription = cache.on_change(move |event| {
            received_callback.lock().unwrap().push(event);
        });

        cache.change_callbacks.dispatch(CacheChangeEvent {
            path: "/tmp/example.md".to_string(),
            kind: "modify".to_string(),
            is_markdown: true,
        });
        cache.off_change(subscription);

        assert_eq!(received.lock().unwrap().len(), 1);
        fs::remove_dir_all(&tmp)?;
        Ok(())
    }

    #[test]
    fn test_persist_cache_and_gitignore_created() -> io::Result<()> {
        let _guard = TEST_CWD_LOCK.lock().unwrap();
        let orig = env::current_dir()?;
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map_err(|e| io::Error::new(io::ErrorKind::Other, format!("time error: {}", e)))?
            .as_millis();
        let tmp = env::temp_dir().join(format!("peisar_test_{}", now));
        if tmp.exists() {
            fs::remove_dir_all(&tmp)?;
        }
        fs::create_dir_all(&tmp)?;
        env::set_current_dir(&tmp)?;

        fs::create_dir_all("docs")?;
        let md_path = tmp.join("docs").join("doc1.md");
        let mut f = File::create(&md_path)?;
        f.write_all(b"---\ntitle: Test\ntags:\n  - a\n  - b\n---\n# Hello\n")?;
        f.sync_all()?;

        let _cache = PeisarCache::new("docs")?;

        let cache_file = tmp.join(".peisar_cache").join("docs").join("doc1.md.json");
        assert!(cache_file.exists());
        let s = fs::read_to_string(&cache_file)?;
        let entry: CacheEntry = serde_json::from_str(&s).unwrap();
        assert!(
            entry.file_path.ends_with("docs/doc1.md") || entry.file_path.ends_with("docs\\doc1.md")
        );
        assert!(entry.frontmatter_data.is_some());

        let gitignore = tmp.join(".gitignore");
        assert!(gitignore.exists());
        let git = fs::read_to_string(&gitignore)?;
        assert!(git.lines().any(|l| l.trim() == ".peisar_cache"));

        env::set_current_dir(orig)?;
        fs::remove_dir_all(&tmp)?;
        Ok(())
    }

    #[test]
    fn test_gitignore_not_duplicated() -> io::Result<()> {
        let _guard = TEST_CWD_LOCK.lock().unwrap();
        let orig = env::current_dir()?;
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map_err(|e| io::Error::new(io::ErrorKind::Other, format!("time error: {}", e)))?
            .as_millis();
        let tmp = env::temp_dir().join(format!("peisar_test_{}", now));
        if tmp.exists() {
            fs::remove_dir_all(&tmp)?;
        }
        fs::create_dir_all(&tmp)?;
        env::set_current_dir(&tmp)?;

        // pre-create .gitignore with entry
        fs::write(".gitignore", ".peisar_cache\n")?;

        fs::create_dir_all("docs")?;
        let md_path = tmp.join("docs").join("doc2.md");
        let mut f = File::create(&md_path)?;
        f.write_all(b"# No frontmatter\nContent\n")?;
        f.sync_all()?;

        let _cache = PeisarCache::new("docs")?;

        let git = fs::read_to_string(".gitignore")?;
        let occurrences = git.lines().filter(|l| l.trim() == ".peisar_cache").count();
        assert_eq!(occurrences, 1);

        env::set_current_dir(orig)?;
        fs::remove_dir_all(&tmp)?;
        Ok(())
    }

    #[test]
    fn test_stale_cache_removal_on_remove_command() -> io::Result<()> {
        let _guard = TEST_CWD_LOCK.lock().unwrap();
        let orig = env::current_dir()?;
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map_err(|e| io::Error::new(io::ErrorKind::Other, format!("time error: {}", e)))?
            .as_millis();
        let tmp = env::temp_dir().join(format!("peisar_test_{}", now));
        if tmp.exists() {
            fs::remove_dir_all(&tmp)?;
        }
        fs::create_dir_all(&tmp)?;
        env::set_current_dir(&tmp)?;

        fs::create_dir_all("docs")?;
        let md1 = tmp.join("docs").join("a.md");
        let md2 = tmp.join("docs").join("b.md");
        {
            let mut f1 = File::create(&md1)?;
            f1.write_all(b"# A\n")?;
            f1.sync_all()?;
            let mut f2 = File::create(&md2)?;
            f2.write_all(b"# B\n")?;
            f2.sync_all()?;
        }

        let cache = PeisarCache::new("docs")?;

        let cache_a = tmp.join(".peisar_cache").join("docs").join("a.md.json");
        let cache_b = tmp.join(".peisar_cache").join("docs").join("b.md.json");
        assert!(cache_a.exists());
        assert!(cache_b.exists());

        // Remove source file and send Remove command to worker
        fs::remove_file(&md1)?;
        if let Some(tx) = &cache.persist_tx {
            tx.send(PersistCommand::Remove(md1.clone())).unwrap();
        }

        // Wait for worker to process
        let mut waited = 0u32;
        while cache_a.exists() && waited < 50 {
            std::thread::sleep(std::time::Duration::from_millis(20));
            waited += 1;
        }

        assert!(!cache_a.exists());

        env::set_current_dir(orig)?;
        fs::remove_dir_all(&tmp)?;
        Ok(())
    }

    #[test]
    fn test_hashing_avoids_rewrite() -> io::Result<()> {
        let _guard = TEST_CWD_LOCK.lock().unwrap();
        let orig = env::current_dir()?;
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map_err(|e| io::Error::new(io::ErrorKind::Other, format!("time error: {}", e)))?
            .as_millis();
        let tmp = env::temp_dir().join(format!("peisar_test_{}", now));
        if tmp.exists() {
            fs::remove_dir_all(&tmp)?;
        }
        fs::create_dir_all(&tmp)?;
        env::set_current_dir(&tmp)?;

        fs::create_dir_all("docs")?;
        let md = tmp.join("docs").join("doc.md");
        let content = b"# Title\nContent\n";
        {
            let mut f = File::create(&md)?;
            f.write_all(content)?;
            f.sync_all()?;
        }

        let cache = PeisarCache::new("docs")?;
        let cache_file = tmp.join(".peisar_cache").join("docs").join("doc.md.json");
        assert!(cache_file.exists());

        let meta1 = fs::metadata(&cache_file)?.modified()?;
        // send update with same content
        if let Some(tx) = &cache.persist_tx {
            tx.send(PersistCommand::Update(
                md.clone(),
                CachedContent::Text(String::from_utf8_lossy(content).to_string()),
            ))
            .unwrap();
        }

        // Wait briefly to let worker run
        std::thread::sleep(std::time::Duration::from_millis(200));
        let meta2 = fs::metadata(&cache_file)?.modified()?;

        assert_eq!(meta1, meta2, "file was rewritten despite identical content");

        env::set_current_dir(orig)?;
        fs::remove_dir_all(&tmp)?;
        Ok(())
    }
}