@hawkeyexl/manni 4.11.0 → 4.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/{batch-UAULUMGH.js → batch-EFSFG6GC.js} +20 -19
- package/dist/build-NIO3UIWJ.js +36 -0
- package/dist/calibrate-6VO7URRV.js +41 -0
- package/dist/capture-NMBVJO3C.js +38 -0
- package/dist/check-SHOYX2B5.js +30 -0
- package/dist/check-XMJKH3KV.js +34 -0
- package/dist/{check-VELUQAUW.js → check-Y62BJNC4.js} +35 -34
- package/dist/{check-VELUQAUW.js.map → check-Y62BJNC4.js.map} +1 -1
- package/dist/{check-YEOYBFST.js → check-ZMO3ZLMW.js} +19 -18
- package/dist/{chunk-BKVHX6FU.js → chunk-24AJK2RG.js} +5 -10
- package/dist/chunk-24AJK2RG.js.map +1 -0
- package/dist/{chunk-M42DZCOU.js → chunk-2OZF2VUB.js} +2 -2
- package/dist/chunk-2UJZXVHR.js +1868 -0
- package/dist/chunk-2UJZXVHR.js.map +1 -0
- package/dist/{chunk-HQR2ZBHW.js → chunk-3BRJCQPY.js} +36 -7
- package/dist/chunk-3BRJCQPY.js.map +1 -0
- package/dist/{chunk-U7CTFN2J.js → chunk-42VFJOAF.js} +7 -7
- package/dist/{chunk-LBSCW232.js → chunk-4Q24OYI3.js} +7 -7
- package/dist/{chunk-OPXWPJDA.js → chunk-4WJTURRO.js} +14 -14
- package/dist/{chunk-GDVZ5VII.js → chunk-5SID2SVL.js} +4 -4
- package/dist/{chunk-FUCPZVRY.js → chunk-AANUY4BH.js} +2 -2
- package/dist/chunk-ANPIIYRH.js +2272 -0
- package/dist/chunk-ANPIIYRH.js.map +1 -0
- package/dist/{chunk-WDWXAYVH.js → chunk-AYVKN3PG.js} +4 -4
- package/dist/{chunk-FQXWVS6J.js → chunk-CH6IOGXV.js} +9 -9
- package/dist/{chunk-4CK6ZSOK.js → chunk-D5Z6B4M7.js} +3 -3
- package/dist/{chunk-HA6MQMOY.js → chunk-D6SELXQ2.js} +6 -6
- package/dist/{chunk-2DRHT73U.js → chunk-DDILEF5F.js} +890 -1399
- package/dist/chunk-DDILEF5F.js.map +1 -0
- package/dist/{chunk-PCS4VJBV.js → chunk-DGRLHDM4.js} +9 -9
- package/dist/{chunk-2MJ62AYQ.js → chunk-DHGB4JBG.js} +4 -3
- package/dist/chunk-DHGB4JBG.js.map +1 -0
- package/dist/{chunk-Y6DOMTQD.js → chunk-DLU5FCFT.js} +27 -27
- package/dist/chunk-DLU5FCFT.js.map +1 -0
- package/dist/chunk-DSWKBZWW.js +16 -0
- package/dist/chunk-DSWKBZWW.js.map +1 -0
- package/dist/{chunk-KGEQJ5CC.js → chunk-F564FHMQ.js} +8 -8
- package/dist/{chunk-J6IDQGJL.js → chunk-FKAZUZQU.js} +469 -85
- package/dist/chunk-FKAZUZQU.js.map +1 -0
- package/dist/{chunk-IGSHYP74.js → chunk-G3MBUL5M.js} +4 -4
- package/dist/{chunk-ADMEPUBT.js → chunk-GQ3KRY3B.js} +3 -3
- package/dist/{chunk-T7JAOYE5.js → chunk-HDPN46JP.js} +6 -6
- package/dist/{chunk-R4WXQIOZ.js → chunk-IQQAJROD.js} +3 -3
- package/dist/{chunk-2IR4T5PO.js → chunk-IZXN3WI6.js} +2 -2
- package/dist/{chunk-NCPWXHDO.js → chunk-JEUFYSFQ.js} +4 -4
- package/dist/{chunk-LKP7QDFN.js → chunk-JSSM7VVV.js} +4 -4
- package/dist/{chunk-2IAZEB45.js → chunk-KFGZPVFA.js} +229 -821
- package/dist/chunk-KFGZPVFA.js.map +1 -0
- package/dist/{chunk-EIFCP6CZ.js → chunk-KGFSPJLD.js} +2 -2
- package/dist/{chunk-RLT5SEML.js → chunk-KMORGMCW.js} +6 -6
- package/dist/{chunk-WQWKYAAK.js → chunk-NUQF5F5J.js} +2 -2
- package/dist/{chunk-54F74XR3.js → chunk-NZ6KSHFD.js} +19 -19
- package/dist/{chunk-4D5IZSXM.js → chunk-OHUDZRLK.js} +3 -3
- package/dist/{chunk-FBMZJEB3.js → chunk-OKMTUAWO.js} +4 -4
- package/dist/{chunk-QLWC7MKD.js → chunk-OTJOBZJ5.js} +135 -135
- package/dist/chunk-OTJOBZJ5.js.map +1 -0
- package/dist/{chunk-6HWBRZIN.js → chunk-PS257NIU.js} +252 -193
- package/dist/chunk-PS257NIU.js.map +1 -0
- package/dist/chunk-QDC7JPFG.js +685 -0
- package/dist/chunk-QDC7JPFG.js.map +1 -0
- package/dist/{chunk-PCQ7ELJH.js → chunk-QEAGL4V5.js} +109 -5
- package/dist/chunk-QEAGL4V5.js.map +1 -0
- package/dist/{chunk-BBT6AVUG.js → chunk-QMY57PVW.js} +2 -2
- package/dist/{chunk-LPIF5LIE.js → chunk-QNDDPXFR.js} +2 -2
- package/dist/{chunk-PWBH7DCQ.js → chunk-QSIXNTRV.js} +4 -4
- package/dist/{chunk-VSEBFHAY.js → chunk-RGLFV4KO.js} +11369 -10218
- package/dist/chunk-RGLFV4KO.js.map +1 -0
- package/dist/{chunk-D4N2V43Z.js → chunk-SGR7ZAVE.js} +13 -7
- package/dist/chunk-SGR7ZAVE.js.map +1 -0
- package/dist/{chunk-GV56WGL2.js → chunk-SMHAYK6I.js} +1036 -883
- package/dist/chunk-SMHAYK6I.js.map +1 -0
- package/dist/{chunk-JPQDNYXH.js → chunk-STPGIKPY.js} +8 -2
- package/dist/chunk-STPGIKPY.js.map +1 -0
- package/dist/{chunk-NSBXVPZL.js → chunk-U22TOL5Y.js} +17 -17
- package/dist/{chunk-NGTVREIH.js → chunk-U6IHLEWT.js} +2 -2
- package/dist/{chunk-ODRPL3WB.js → chunk-UUCCV3SI.js} +2 -2
- package/dist/{chunk-MSRU4D4P.js → chunk-UXMCHBOJ.js} +2 -2
- package/dist/{chunk-B7XYNRJQ.js → chunk-VFAKGIDG.js} +2 -2
- package/dist/{chunk-QCHVR4ZM.js → chunk-VM7VAFJW.js} +33 -7
- package/dist/chunk-VM7VAFJW.js.map +1 -0
- package/dist/{chunk-VQK4VHLF.js → chunk-YQV75FIL.js} +2 -2
- package/dist/chunk-YUTVAMWW.js +2 -0
- package/dist/{cli-4MF37HAQ.js → cli-4CR7QIOK.js} +26 -25
- package/dist/{cli-4MF37HAQ.js.map → cli-4CR7QIOK.js.map} +1 -1
- package/dist/{cli-6KZTHWGP.js → cli-6R4W3HAH.js} +37 -36
- package/dist/{cli-6KZTHWGP.js.map → cli-6R4W3HAH.js.map} +1 -1
- package/dist/{cli-I62SRH3R.js → cli-BOMA2FMP.js} +14 -13
- package/dist/{cli-DRMZBZLB.js → cli-EDQPQOCE.js} +43 -42
- package/dist/{cli-DRMZBZLB.js.map → cli-EDQPQOCE.js.map} +1 -1
- package/dist/{cli-VID7PJS3.js → cli-GBF76EXT.js} +23 -22
- package/dist/{cli-VID7PJS3.js.map → cli-GBF76EXT.js.map} +1 -1
- package/dist/{cli-3BTCK4AB.js → cli-MQYCF3SR.js} +27 -26
- package/dist/{cli-3BTCK4AB.js.map → cli-MQYCF3SR.js.map} +1 -1
- package/dist/{cli-ONTC5PKT.js → cli-OJKFXQOM.js} +9 -9
- package/dist/{cli-VUKMWSSF.js → cli-PHZAO4LZ.js} +4 -4
- package/dist/{cli-RORDPAPE.js → cli-PTKFFNOW.js} +59 -38
- package/dist/cli-PTKFFNOW.js.map +1 -0
- package/dist/{cli-O4ABTN4Z.js → cli-UW2K5Z5J.js} +31 -30
- package/dist/{cli-O4ABTN4Z.js.map → cli-UW2K5Z5J.js.map} +1 -1
- package/dist/{cli-JJMOVIKS.js → cli-XXTNPPKB.js} +14 -14
- package/dist/cli.js +19 -13
- package/dist/cli.js.map +1 -1
- package/dist/{config-XDA42RJL.js → config-JJW75SBX.js} +5 -5
- package/dist/docmeta.js +13 -12
- package/dist/docmeta.js.map +1 -1
- package/dist/github-6VQKSB67.js +35 -0
- package/dist/github-RBSEM7ZK.js +30 -0
- package/dist/graph/runtime.d.ts +4 -1
- package/dist/graph/runtime.js +20 -9
- package/dist/graph/runtime.js.map +1 -1
- package/dist/{host-6GURH5HE.js → host-YSTYO5DX.js} +3 -3
- package/dist/index.d.ts +192 -26
- package/dist/index.js +129 -124
- package/dist/index.js.map +1 -1
- package/dist/{json-BXY44ED7.js → json-PU2HLHDQ.js} +18 -17
- package/dist/labels-SJNSOPBI.js +73 -0
- package/dist/labels-SJNSOPBI.js.map +1 -0
- package/dist/lint-KIVTHLGU.js +34 -0
- package/dist/list-RDEJDDJF.js +32 -0
- package/dist/list-SUTDWL2J.js +35 -0
- package/dist/{page-EV7OUBAU.js → page-UMAA3NCM.js} +18 -16
- package/dist/{prepare-JHJDJB6I.js → prepare-3I3LOXXD.js} +22 -21
- package/dist/{prepare-JHJDJB6I.js.map → prepare-3I3LOXXD.js.map} +1 -1
- package/dist/{pretty-SCRK66M5.js → pretty-ANLRHU4O.js} +18 -17
- package/dist/{pretty-Q5Y2PA64.js → pretty-Q3ZFKOR7.js} +18 -17
- package/dist/{provider-527CO4DM.js → provider-LBX4IXGX.js} +3 -3
- package/dist/{release-3D5PK6M7.js → release-VV3UTKE5.js} +3 -3
- package/dist/{reporters-M6LJ2IYU.js → reporters-26H3N2KW.js} +3 -3
- package/dist/{reporters-RBYTASMI.js → reporters-ILT36CIH.js} +7 -7
- package/dist/{reporters-A5ADKDYR.js → reporters-PNDLWT6K.js} +16 -15
- package/dist/run-QXCK33Z4.js +37 -0
- package/dist/{term-CQAGNG3Q.js → term-D2N7UN4P.js} +981 -141
- package/dist/term-D2N7UN4P.js.map +1 -0
- package/dist/validate-BRUCOT2O.js +19 -0
- package/package.json +3 -2
- package/plugin/manni/.claude-plugin/plugin.json +1 -1
- package/shapes/graph/shapes-1.1.0.ttl +785 -0
- package/dist/build-QSPNK5AL.js +0 -35
- package/dist/calibrate-KXN4URPM.js +0 -40
- package/dist/capture-JHTSUPUC.js +0 -37
- package/dist/check-MDGXEUWL.js +0 -20
- package/dist/check-WOQRKNZK.js +0 -29
- package/dist/chunk-2DRHT73U.js.map +0 -1
- package/dist/chunk-2IAZEB45.js.map +0 -1
- package/dist/chunk-2MJ62AYQ.js.map +0 -1
- package/dist/chunk-4VBSTXN6.js +0 -392
- package/dist/chunk-4VBSTXN6.js.map +0 -1
- package/dist/chunk-6HWBRZIN.js.map +0 -1
- package/dist/chunk-BKVHX6FU.js.map +0 -1
- package/dist/chunk-D4N2V43Z.js.map +0 -1
- package/dist/chunk-EFW7CAG4.js +0 -387
- package/dist/chunk-EFW7CAG4.js.map +0 -1
- package/dist/chunk-GV56WGL2.js.map +0 -1
- package/dist/chunk-HQR2ZBHW.js.map +0 -1
- package/dist/chunk-J6IDQGJL.js.map +0 -1
- package/dist/chunk-JPQDNYXH.js.map +0 -1
- package/dist/chunk-JROBZ7JA.js +0 -818
- package/dist/chunk-JROBZ7JA.js.map +0 -1
- package/dist/chunk-PCQ7ELJH.js.map +0 -1
- package/dist/chunk-QCHVR4ZM.js.map +0 -1
- package/dist/chunk-QLWC7MKD.js.map +0 -1
- package/dist/chunk-TU2WUBVZ.js +0 -2
- package/dist/chunk-VSEBFHAY.js.map +0 -1
- package/dist/chunk-Y6DOMTQD.js.map +0 -1
- package/dist/cli-RORDPAPE.js.map +0 -1
- package/dist/github-RY3FRA6P.js +0 -29
- package/dist/github-YKQSH7FS.js +0 -34
- package/dist/lint-YJ2L22BW.js +0 -33
- package/dist/list-NSG24VVX.js +0 -31
- package/dist/list-V6EGCSHX.js +0 -34
- package/dist/run-BUE2DDXN.js +0 -36
- package/dist/term-CQAGNG3Q.js.map +0 -1
- package/dist/validate-ZBW44RHT.js +0 -18
- /package/dist/{batch-UAULUMGH.js.map → batch-EFSFG6GC.js.map} +0 -0
- /package/dist/{build-QSPNK5AL.js.map → build-NIO3UIWJ.js.map} +0 -0
- /package/dist/{calibrate-KXN4URPM.js.map → calibrate-6VO7URRV.js.map} +0 -0
- /package/dist/{capture-JHTSUPUC.js.map → capture-NMBVJO3C.js.map} +0 -0
- /package/dist/{check-MDGXEUWL.js.map → check-SHOYX2B5.js.map} +0 -0
- /package/dist/{check-WOQRKNZK.js.map → check-XMJKH3KV.js.map} +0 -0
- /package/dist/{check-YEOYBFST.js.map → check-ZMO3ZLMW.js.map} +0 -0
- /package/dist/{chunk-M42DZCOU.js.map → chunk-2OZF2VUB.js.map} +0 -0
- /package/dist/{chunk-U7CTFN2J.js.map → chunk-42VFJOAF.js.map} +0 -0
- /package/dist/{chunk-LBSCW232.js.map → chunk-4Q24OYI3.js.map} +0 -0
- /package/dist/{chunk-OPXWPJDA.js.map → chunk-4WJTURRO.js.map} +0 -0
- /package/dist/{chunk-GDVZ5VII.js.map → chunk-5SID2SVL.js.map} +0 -0
- /package/dist/{chunk-FUCPZVRY.js.map → chunk-AANUY4BH.js.map} +0 -0
- /package/dist/{chunk-WDWXAYVH.js.map → chunk-AYVKN3PG.js.map} +0 -0
- /package/dist/{chunk-FQXWVS6J.js.map → chunk-CH6IOGXV.js.map} +0 -0
- /package/dist/{chunk-4CK6ZSOK.js.map → chunk-D5Z6B4M7.js.map} +0 -0
- /package/dist/{chunk-HA6MQMOY.js.map → chunk-D6SELXQ2.js.map} +0 -0
- /package/dist/{chunk-PCS4VJBV.js.map → chunk-DGRLHDM4.js.map} +0 -0
- /package/dist/{chunk-KGEQJ5CC.js.map → chunk-F564FHMQ.js.map} +0 -0
- /package/dist/{chunk-IGSHYP74.js.map → chunk-G3MBUL5M.js.map} +0 -0
- /package/dist/{chunk-ADMEPUBT.js.map → chunk-GQ3KRY3B.js.map} +0 -0
- /package/dist/{chunk-T7JAOYE5.js.map → chunk-HDPN46JP.js.map} +0 -0
- /package/dist/{chunk-R4WXQIOZ.js.map → chunk-IQQAJROD.js.map} +0 -0
- /package/dist/{chunk-2IR4T5PO.js.map → chunk-IZXN3WI6.js.map} +0 -0
- /package/dist/{chunk-NCPWXHDO.js.map → chunk-JEUFYSFQ.js.map} +0 -0
- /package/dist/{chunk-LKP7QDFN.js.map → chunk-JSSM7VVV.js.map} +0 -0
- /package/dist/{chunk-EIFCP6CZ.js.map → chunk-KGFSPJLD.js.map} +0 -0
- /package/dist/{chunk-RLT5SEML.js.map → chunk-KMORGMCW.js.map} +0 -0
- /package/dist/{chunk-WQWKYAAK.js.map → chunk-NUQF5F5J.js.map} +0 -0
- /package/dist/{chunk-54F74XR3.js.map → chunk-NZ6KSHFD.js.map} +0 -0
- /package/dist/{chunk-4D5IZSXM.js.map → chunk-OHUDZRLK.js.map} +0 -0
- /package/dist/{chunk-FBMZJEB3.js.map → chunk-OKMTUAWO.js.map} +0 -0
- /package/dist/{chunk-BBT6AVUG.js.map → chunk-QMY57PVW.js.map} +0 -0
- /package/dist/{chunk-LPIF5LIE.js.map → chunk-QNDDPXFR.js.map} +0 -0
- /package/dist/{chunk-PWBH7DCQ.js.map → chunk-QSIXNTRV.js.map} +0 -0
- /package/dist/{chunk-NSBXVPZL.js.map → chunk-U22TOL5Y.js.map} +0 -0
- /package/dist/{chunk-NGTVREIH.js.map → chunk-U6IHLEWT.js.map} +0 -0
- /package/dist/{chunk-ODRPL3WB.js.map → chunk-UUCCV3SI.js.map} +0 -0
- /package/dist/{chunk-MSRU4D4P.js.map → chunk-UXMCHBOJ.js.map} +0 -0
- /package/dist/{chunk-B7XYNRJQ.js.map → chunk-VFAKGIDG.js.map} +0 -0
- /package/dist/{chunk-VQK4VHLF.js.map → chunk-YQV75FIL.js.map} +0 -0
- /package/dist/{chunk-TU2WUBVZ.js.map → chunk-YUTVAMWW.js.map} +0 -0
- /package/dist/{cli-I62SRH3R.js.map → cli-BOMA2FMP.js.map} +0 -0
- /package/dist/{cli-ONTC5PKT.js.map → cli-OJKFXQOM.js.map} +0 -0
- /package/dist/{cli-VUKMWSSF.js.map → cli-PHZAO4LZ.js.map} +0 -0
- /package/dist/{cli-JJMOVIKS.js.map → cli-XXTNPPKB.js.map} +0 -0
- /package/dist/{config-XDA42RJL.js.map → config-JJW75SBX.js.map} +0 -0
- /package/dist/{github-RY3FRA6P.js.map → github-6VQKSB67.js.map} +0 -0
- /package/dist/{github-YKQSH7FS.js.map → github-RBSEM7ZK.js.map} +0 -0
- /package/dist/{host-6GURH5HE.js.map → host-YSTYO5DX.js.map} +0 -0
- /package/dist/{json-BXY44ED7.js.map → json-PU2HLHDQ.js.map} +0 -0
- /package/dist/{lint-YJ2L22BW.js.map → lint-KIVTHLGU.js.map} +0 -0
- /package/dist/{list-NSG24VVX.js.map → list-RDEJDDJF.js.map} +0 -0
- /package/dist/{list-V6EGCSHX.js.map → list-SUTDWL2J.js.map} +0 -0
- /package/dist/{page-EV7OUBAU.js.map → page-UMAA3NCM.js.map} +0 -0
- /package/dist/{pretty-Q5Y2PA64.js.map → pretty-ANLRHU4O.js.map} +0 -0
- /package/dist/{pretty-SCRK66M5.js.map → pretty-Q3ZFKOR7.js.map} +0 -0
- /package/dist/{provider-527CO4DM.js.map → provider-LBX4IXGX.js.map} +0 -0
- /package/dist/{release-3D5PK6M7.js.map → release-VV3UTKE5.js.map} +0 -0
- /package/dist/{reporters-A5ADKDYR.js.map → reporters-26H3N2KW.js.map} +0 -0
- /package/dist/{reporters-M6LJ2IYU.js.map → reporters-ILT36CIH.js.map} +0 -0
- /package/dist/{reporters-RBYTASMI.js.map → reporters-PNDLWT6K.js.map} +0 -0
- /package/dist/{run-BUE2DDXN.js.map → run-QXCK33Z4.js.map} +0 -0
- /package/dist/{validate-ZBW44RHT.js.map → validate-BRUCOT2O.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/graph/core/sort.ts","../../src/graph/core/vocab.ts","../../src/graph/runtime/graph.ts","../../src/graph/runtime/trace.ts","../../src/graph/core/localizations.ts","../../src/graph/core/iirds.ts","../../src/graph/runtime/traverse.ts","../../src/graph/runtime/resolve.ts","../../src/graph/runtime/assemble.ts","../../src/graph/runtime/rdfjs.ts","../../node_modules/minisearch/src/SearchableMap/TreeIterator.ts","../../node_modules/minisearch/src/SearchableMap/fuzzySearch.ts","../../node_modules/minisearch/src/SearchableMap/SearchableMap.ts","../../node_modules/minisearch/src/MiniSearch.ts","../../src/graph/runtime/lexical.ts","../../src/graph/core/vector-index.ts","../../src/graph/runtime/vector.ts","../../src/graph/runtime/entry.ts"],"sourcesContent":["/**\n * The ordering primitive behind the determinism contract. Every sort that\n * reaches output — the file list, emitted subjects/predicates/objects, query\n * results — must go through this comparator so ordering never depends on\n * locale, ICU version, or platform, the way `String.prototype.localeCompare`\n * and `Array.prototype.sort`'s default string coercion do.\n */\n\n/** Locale-independent code-unit comparison for stable sorting. */\nexport function byCodeUnit(a: string, b: string): number {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n","/**\n * Namespace table. Standard vocabularies wherever a term exists; the custom\n * `graph:` namespace stays minimal, and the newest vocabulary document under\n * `ns/` defines every term it holds — a bidirectional drift guard in\n * test/graph/unit/vocabulary.test.ts enforces both directions. Neither the term\n * count nor the version is written here: both went stale the first time a term\n * was added, and the guard resolves the file rather than naming it. The prefix\n * set is fixed — every emitted graph carries the same header.\n *\n * The custom prefix is `graph:` and its namespace is the manni site's, which is\n * where it dereferences (proposal 0051 §7). Both were `dockg` until the tool\n * joined the family, and graph ADR 01030's rule — the namespace IRI must resolve\n * — is why they moved rather than staying: `hawkeyexl.github.io/dockg` never\n * served anything and never will.\n *\n * The block an author writes on a page is `graph:`, and the prefix is `graph:`\n * too. The spelling is shared but the things differ: the key names frontmatter,\n * the prefix abbreviates an IRI in emitted RDF, and the prefix carries the\n * tool's name because `…/manni/graph/ns#` is the tool's namespace. Nothing\n * collides: no other prefix in this table is `graph`, and a `graph:` CURIE typed\n * at `--predicates` or `--subject` expanded to nothing before.\n */\nexport const NS = {\n dcterms: \"http://purl.org/dc/terms/\",\n foaf: \"http://xmlns.com/foaf/0.1/\",\n graph: \"https://hawkeyexl.github.io/manni/graph/ns#\",\n iirds: \"http://iirds.tekom.de/iirds#\",\n iirdsSft: \"http://iirds.tekom.de/iirds/domain/software#\",\n prov: \"http://www.w3.org/ns/prov#\",\n rdf: \"http://www.w3.org/1999/02/22-rdf-syntax-ns#\",\n schema: \"https://schema.org/\",\n skos: \"http://www.w3.org/2004/02/skos/core#\",\n xsd: \"http://www.w3.org/2001/XMLSchema#\",\n} as const;\n\nexport type Prefix = keyof typeof NS;\n\n/** Prefixes in emission order (sorted by prefix name). */\nexport const PREFIXES: ReadonlyArray<[Prefix, string]> = (\n Object.entries(NS) as Array<[Prefix, string]>\n).sort(([a], [b]) => (a < b ? -1 : 1));\n\nexport const RDF_TYPE = `${NS.rdf}type`;\n\n/**\n * Role individuals for qualified provenance (prov:hadRole objects). Part of\n * the deliberately small graph vocabulary.\n */\nexport const ROLE = {\n author: `${NS.graph}authorRole`,\n generator: `${NS.graph}generatorRole`,\n tool: `${NS.graph}toolRole`,\n} as const;\n","/**\n * `GraphIndex` — the browser-native in-memory graph (ADR 01018).\n *\n * Built from `graph.jsonld` (the Phase 6 export) with **no RDF parser**: that\n * artifact is plain `JSON.parse`-able, deterministically sorted, and free of\n * blank nodes, so a `Map`-based adjacency index is all the runtime needs. Node\n * callers can also build from quads (`fromQuads`) so the CLI can read Turtle.\n *\n * Platform-neutral: no `node:` imports, no npm dependencies, no I/O — the\n * caller supplies the bytes. Type-only imports are erased at build time.\n *\n * Every accessor returns deterministically sorted results, so traversal order\n * (and therefore the trace) is byte-stable for a given graph.\n */\nimport type { Quad } from \"../core/derive.js\";\nimport { byCodeUnit } from \"../core/sort.js\";\nimport { RDF_TYPE } from \"../core/vocab.js\";\n\n/** An object value: an IRI reference or a literal. */\nexport type Value =\n | { kind: \"iri\"; value: string }\n | { kind: \"literal\"; value: string; datatype?: string };\n\nexport interface GraphNode {\n id: string;\n /** Full class IRIs, sorted. */\n types: string[];\n /** Full predicate IRI → values, in insertion-normalized sorted order. */\n props: Map<string, Value[]>;\n}\n\n/** The parsed shape of a `graph.jsonld` document. */\ninterface JsonLdDoc {\n \"@context\"?: Record<string, string>;\n \"@graph\"?: unknown[];\n}\n\nconst XSD_STRING = \"http://www.w3.org/2001/XMLSchema#string\";\n\nfunction compareValues(a: Value, b: Value): number {\n if (a.kind !== b.kind) return a.kind === \"iri\" ? -1 : 1;\n const v = byCodeUnit(a.value, b.value);\n if (v !== 0) return v;\n const da = a.kind === \"literal\" ? (a.datatype ?? \"\") : \"\";\n const db = b.kind === \"literal\" ? (b.datatype ?? \"\") : \"\";\n return byCodeUnit(da, db);\n}\n\nexport class GraphIndex {\n private readonly nodes = new Map<string, GraphNode>();\n /** subject → predicate → object IRIs (sorted). */\n private readonly outbound = new Map<string, Map<string, string[]>>();\n /** object → predicate → subject IRIs (sorted). */\n private readonly inbound = new Map<string, Map<string, string[]>>();\n /** class IRI → instance IRIs (sorted). */\n private readonly byType = new Map<string, string[]>();\n /** prefix → namespace, from the artifact's own `@context`. */\n readonly context: Record<string, string>;\n\n private constructor(context: Record<string, string>) {\n this.context = context;\n }\n\n /**\n * Build from a `graph.jsonld` document — a JSON string or the parsed object.\n * CURIE keys and `@type` values are expanded using the document's own\n * `@context`, so the index is self-describing.\n */\n static fromJsonLd(input: string | object): GraphIndex {\n const doc = (\n typeof input === \"string\" ? (JSON.parse(input) as JsonLdDoc) : input\n ) as JsonLdDoc;\n const context = doc[\"@context\"] ?? {};\n const index = new GraphIndex({ ...context });\n for (const raw of doc[\"@graph\"] ?? []) {\n index.addJsonLdNode(raw as Record<string, unknown>);\n }\n index.finalize();\n return index;\n }\n\n /** Build from dockg's internal quad shape (the Node/CLI path). */\n static fromQuads(quads: Quad[], context: Record<string, string> = {}) {\n const index = new GraphIndex({ ...context });\n for (const q of quads) {\n const o = q.o;\n const value: Value =\n o.kind === \"iri\"\n ? { kind: \"iri\", value: o.value }\n : o.datatype && o.datatype !== XSD_STRING\n ? { kind: \"literal\", value: o.value, datatype: o.datatype }\n : { kind: \"literal\", value: o.value };\n index.addTriple(q.s, q.p, value);\n }\n index.finalize();\n return index;\n }\n\n /** Expand a CURIE (`dcterms:title`) to a full IRI using `@context`. */\n expand(term: string): string {\n const colon = term.indexOf(\":\");\n if (colon <= 0) return term;\n const ns = this.context[term.slice(0, colon)];\n return ns ? `${ns}${term.slice(colon + 1)}` : term;\n }\n\n /** Compact a full IRI to a CURIE when a context namespace matches. */\n compact(iri: string): string {\n let best = iri;\n let bestNs = \"\";\n for (const [prefix, ns] of Object.entries(this.context)) {\n if (\n iri.startsWith(ns) &&\n iri.length > ns.length &&\n ns.length > bestNs.length\n ) {\n best = `${prefix}:${iri.slice(ns.length)}`;\n bestNs = ns;\n }\n }\n return best;\n }\n\n private addJsonLdNode(raw: Record<string, unknown>): void {\n const id = typeof raw[\"@id\"] === \"string\" ? this.expand(raw[\"@id\"]) : \"\";\n if (!id) return;\n this.ensureNode(id);\n\n const rawTypes = raw[\"@type\"];\n for (const t of toArray(rawTypes)) {\n if (typeof t === \"string\") {\n this.addTriple(id, RDF_TYPE, { kind: \"iri\", value: this.expand(t) });\n }\n }\n\n for (const [key, rawValue] of Object.entries(raw)) {\n if (key === \"@id\" || key === \"@type\") continue;\n const predicate = this.expand(key);\n for (const v of toArray(rawValue)) {\n const value = this.toValue(v);\n if (value) this.addTriple(id, predicate, value);\n }\n }\n }\n\n private toValue(v: unknown): Value | undefined {\n if (typeof v === \"string\") return { kind: \"literal\", value: v };\n if (typeof v === \"number\" || typeof v === \"boolean\") {\n return { kind: \"literal\", value: String(v) };\n }\n if (v && typeof v === \"object\") {\n const o = v as Record<string, unknown>;\n if (typeof o[\"@id\"] === \"string\") {\n return { kind: \"iri\", value: this.expand(o[\"@id\"]) };\n }\n if (o[\"@value\"] !== undefined) {\n const raw = o[\"@value\"];\n // JSON.stringify spells a number or boolean the way String() would,\n // and gives an object a lexical form instead of \"[object Object]\".\n const lexical = typeof raw === \"string\" ? raw : JSON.stringify(raw);\n const dt =\n typeof o[\"@type\"] === \"string\" ? this.expand(o[\"@type\"]) : undefined;\n return dt && dt !== XSD_STRING\n ? { kind: \"literal\", value: lexical, datatype: dt }\n : { kind: \"literal\", value: lexical };\n }\n }\n return undefined;\n }\n\n private ensureNode(id: string): GraphNode {\n let node = this.nodes.get(id);\n if (!node) {\n node = { id, types: [], props: new Map() };\n this.nodes.set(id, node);\n }\n return node;\n }\n\n private addTriple(s: string, p: string, o: Value): void {\n const node = this.ensureNode(s);\n let values = node.props.get(p);\n if (!values) {\n values = [];\n node.props.set(p, values);\n }\n values.push(o);\n\n if (p === RDF_TYPE && o.kind === \"iri\") {\n node.types.push(o.value);\n const instances = this.byType.get(o.value);\n if (instances) instances.push(s);\n else this.byType.set(o.value, [s]);\n }\n\n if (o.kind === \"iri\") {\n addEdge(this.outbound, s, p, o.value);\n addEdge(this.inbound, o.value, p, s);\n // Referenced-only IRIs still resolve as (empty) nodes.\n this.ensureNode(o.value);\n }\n }\n\n /** Sort every collection so traversal order is deterministic. */\n private finalize(): void {\n for (const node of this.nodes.values()) {\n node.types.sort(byCodeUnit);\n for (const values of node.props.values()) values.sort(compareValues);\n }\n for (const instances of this.byType.values()) instances.sort(byCodeUnit);\n for (const map of [this.outbound, this.inbound]) {\n for (const preds of map.values()) {\n for (const targets of preds.values()) targets.sort(byCodeUnit);\n }\n }\n }\n\n /** Every node IRI, sorted. */\n ids(): string[] {\n return [...this.nodes.keys()].sort(byCodeUnit);\n }\n\n size(): number {\n return this.nodes.size;\n }\n\n node(iri: string): GraphNode | undefined {\n return this.nodes.get(iri);\n }\n\n has(iri: string): boolean {\n return this.nodes.has(iri);\n }\n\n /** Class IRIs of a node, sorted. */\n types(iri: string): string[] {\n return this.nodes.get(iri)?.types ?? [];\n }\n\n /** Instances of a class, sorted. */\n instancesOf(classIri: string): string[] {\n return this.byType.get(classIri) ?? [];\n }\n\n /** All values for a predicate, sorted. */\n values(iri: string, predicate: string): Value[] {\n return this.nodes.get(iri)?.props.get(predicate) ?? [];\n }\n\n /** Literal lexical forms for a predicate, sorted. */\n literals(iri: string, predicate: string): string[] {\n return this.values(iri, predicate)\n .filter((v) => v.kind === \"literal\")\n .map((v) => v.value);\n }\n\n /** The first literal for a predicate, if any. */\n literal(iri: string, predicate: string): string | undefined {\n return this.literals(iri, predicate)[0];\n }\n\n /** Outbound IRI targets: all predicates, or one. Sorted. */\n out(\n iri: string,\n predicate?: string,\n ): Array<{ predicate: string; target: string }> {\n return edges(this.outbound, iri, predicate);\n }\n\n /** Inbound IRI sources (who points at this node). Sorted. */\n in(\n iri: string,\n predicate?: string,\n ): Array<{ predicate: string; target: string }> {\n return edges(this.inbound, iri, predicate);\n }\n}\n\nfunction addEdge(\n map: Map<string, Map<string, string[]>>,\n key: string,\n predicate: string,\n target: string,\n): void {\n let preds = map.get(key);\n if (!preds) {\n preds = new Map();\n map.set(key, preds);\n }\n const targets = preds.get(predicate);\n if (targets) targets.push(target);\n else preds.set(predicate, [target]);\n}\n\nfunction edges(\n map: Map<string, Map<string, string[]>>,\n iri: string,\n predicate?: string,\n): Array<{ predicate: string; target: string }> {\n const preds = map.get(iri);\n if (!preds) return [];\n const out: Array<{ predicate: string; target: string }> = [];\n const keys = predicate ? [predicate] : [...preds.keys()].sort(byCodeUnit);\n for (const p of keys) {\n for (const target of preds.get(p) ?? []) out.push({ predicate: p, target });\n }\n return out;\n}\n\nfunction toArray(v: unknown): unknown[] {\n if (v === undefined || v === null) return [];\n return Array.isArray(v) ? v : [v];\n}\n","/**\n * Query trace — the explainability contract (ADR 01018). Every runtime stage\n * appends to a trace, and no API returns results without one: retrieval\n * provenance is part of the contract exactly as PROV provenance is part of the\n * build. The trace answers \"how and why did this result come back\": which nodes\n * were seeded, every hop walked, every node scope excluded (and by which rule),\n * and every content resolution attempted.\n *\n * Events are appended in traversal order, which is itself deterministic, so the\n * trace is byte-stable for a given graph + query.\n */\n\n/** How a seed was found. `hybrid` means several legs agreed on it. */\nexport type EntryVia = \"explicit\" | \"lexical\" | \"vector\" | \"hybrid\";\n\n/** A starting node, with the score/reason that made it a seed. */\nexport interface EntryCandidate {\n iri: string;\n /**\n * Relevance score: 1 for an explicitly requested seed, otherwise the fused\n * `rrfMerge` score. Note that fusion is **rank**-based, so a searched seed's\n * score reflects its position (1/(60 + rank)), not the engine's relevance —\n * it orders candidates but is not a magnitude to threshold on.\n */\n score: number;\n via: EntryVia;\n}\n\n/** One edge walked, in either direction. */\nexport interface Hop {\n from: string;\n predicate: string;\n to: string;\n /** Hops from the nearest seed (seeds are depth 0; their neighbors are 1). */\n depth: number;\n direction: \"out\" | \"in\";\n}\n\n/** A node the scope filter removed, and why. */\nexport interface ScopeExclusion {\n node: string;\n /**\n * The predicate that disqualified the node: a `graph:not*` IRI when an\n * explicit negative named the target, or the positive predicate (e.g.\n * `iirds:relates-to-product-variant`) when the node declared a scope set that\n * omits the target.\n */\n rule: string;\n /**\n * The filter target being applied — the variant or subject IRI the query\n * asked for. Under a `graph:not*` rule the node named this explicitly; under\n * a positive rule this is what the node's declared set was missing.\n */\n value: string;\n}\n\n/** One content-resolution attempt. */\nexport interface Resolution {\n iri: string;\n sourceUrl: string;\n ok: boolean;\n /** Present when `ok` is false. */\n error?: string;\n}\n\nexport interface QueryTrace {\n entry: EntryCandidate[];\n hops: Hop[];\n exclusions: ScopeExclusion[];\n resolutions: Resolution[];\n}\n\nexport function createTrace(): QueryTrace {\n return { entry: [], hops: [], exclusions: [], resolutions: [] };\n}\n\n/**\n * Every node named anywhere in the trace as reached — seeds plus hop targets.\n * The trace-completeness contract: a traversal's results must be a subset of\n * this, so every returned node is explainable by recorded events.\n */\nexport function reachedNodes(trace: QueryTrace): Set<string> {\n const reached = new Set<string>();\n for (const e of trace.entry) reached.add(e.iri);\n for (const h of trace.hops) reached.add(h.to);\n return reached;\n}\n","/**\n * The localization manifest (ADR 01038) — `graph/localizations.json`, the index of\n * indexes.\n *\n * Retrieval artifacts fan out per language: one `search.<lang>.json` and one\n * `vectors.<lang>.bin` each, because a single flat index over every locale\n * ranks across the boundary it exists to respect, and because one embedding\n * model cannot serve every language. The manifest is what makes that navigable\n * — a browser fetches this one small file, learns which localizations exist and\n * what each costs, and downloads only the pair it needs.\n *\n * Written by `manni graph export search`; `manni graph embed` fills in the\n * `vectors` block as it produces each sidecar, so a manifest entry without one\n * means exactly \"this language has no vectors yet\".\n *\n * No `node:` imports: the CLI writes it and the browser runtime reads it.\n */\nimport { byCodeUnit } from \"./sort.js\";\n\n/** Conventional filename, written beside the graph. */\nexport const LOCALIZATIONS_FILENAME = \"localizations.json\";\n\n/**\n * BCP-47's tag for undetermined, used as the bucket for documents that declare\n * no language. A real tag rather than a dockg invention, so a consumer that\n * knows BCP-47 already knows what it means — and so the bucket sorts, filters,\n * and names a file like any other language.\n */\nexport const UNDETERMINED = \"und\";\n\n/**\n * BCP-47's common shape: language(2-3) + optional script(4) + optional\n * region(2 alpha or 3 digit) + variants. Accepts de, de-DE, zh-Hans,\n * zh-Hans-CN, pt-BR and und; rejects English and de_DE.\n *\n * The same grammar appears in `config-schema.json` (for `routes[].language` and\n * `embed.byLanguage`) and in `shapes/graph/shapes-1.0.0.ttl` (for `dcterms:language`).\n * This copy exists because a tag also becomes a **filename**, and the shapes\n * only run under `manni graph check` — an unvalidated literal from the graph would\n * otherwise reach `writeFileSync` as a path segment. `test/unit/schema-sync.test.ts`\n * pins all three to each other.\n */\nexport const LANGUAGE_TAG =\n /^[A-Za-z]{2,3}(-[A-Za-z]{4})?(-([A-Za-z]{2}|[0-9]{3}))?(-([A-Za-z0-9]{5,8}|[0-9][A-Za-z0-9]{3}))*$/;\n\n/** Whether a string is usable as a language tag — and so as a filename segment. */\nexport function isLanguageTag(value: string): boolean {\n return LANGUAGE_TAG.test(value);\n}\n\n/**\n * The canonical spelling of a BCP-47 tag: `en-us` and `EN-US` both become\n * `en-US`. Tags are case-insensitive, so without this one locale splits into\n * two indexes and a filter matches only the spelling its author happened to\n * type. A string `Intl` refuses comes back as written, so the tag check that\n * guards filenames still sees, and reports, what the author wrote.\n *\n * `Intl` exists in every browser, so the runtime calls this too.\n */\nexport function canonicalLanguageTag(tag: string): string {\n try {\n return Intl.getCanonicalLocales(tag)[0] ?? tag;\n } catch {\n return tag;\n }\n}\n\n/** Where one language's lexical index lives, and what it holds. */\nexport interface SearchArtifact {\n /** Filename, relative to the manifest. */\n path: string;\n /** Indexed nodes. */\n entries: number;\n /** `sha256:…` of the file, so a consumer can detect a stale pair. */\n digest: string;\n}\n\n/** Where one language's vector sidecar lives, and what produced it. */\nexport interface VectorArtifact {\n path: string;\n /** The embedding model this language was embedded with. */\n model: string;\n dtype: string;\n dims: number;\n count: number;\n}\n\nexport interface LocalizationEntry {\n /** BCP-47 tag, or `und` for the undeclared bucket. */\n language: string;\n /** Documents in this language (sections excluded). */\n documents: number;\n search: SearchArtifact;\n /** Absent until `manni graph embed` has run for this language. */\n vectors?: VectorArtifact;\n}\n\nexport interface LocalizationsDoc {\n version: 1;\n /** One entry per language present, sorted by tag. */\n languages: LocalizationEntry[];\n}\n\n/** `search.de.json` — the lexical index for one language. */\nexport function searchIndexFilename(language: string): string {\n return `search.${language}.json`;\n}\n\n/** `vectors.de.bin` — the vector sidecar for one language. */\nexport function vectorIndexFilename(language: string): string {\n return `vectors.${language}.bin`;\n}\n\n/**\n * Serialize the manifest: sorted by language, two-space indent, trailing\n * newline — byte-stable like every other dockg artifact.\n */\nexport function emitLocalizations(doc: LocalizationsDoc): string {\n const languages = [...doc.languages].sort((a, b) =>\n byCodeUnit(a.language, b.language),\n );\n return `${JSON.stringify({ version: doc.version, languages }, null, 2)}\\n`;\n}\n\n/**\n * Parse and shape-check a manifest. Returns undefined for anything else.\n *\n * Every entry is checked, not just the envelope: callers reach straight for\n * `entry.search.path`, and a truncated or hand-edited file would otherwise\n * dereference `undefined` and surface as a raw TypeError with exit 1 rather\n * than the operational error (exit 2) an unreadable artifact owes.\n */\n/** A plain JSON object — not `null`, not an array. */\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\nexport function parseLocalizations(text: string): LocalizationsDoc | undefined {\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return undefined;\n }\n // Checked as `unknown`. Casting to `LocalizationsDoc` first would hand the\n // compiler the answer to the question this function exists to ask, and every\n // guard below would then read as a test that cannot fail.\n if (!isRecord(parsed)) return undefined;\n if (parsed[\"version\"] !== 1 || !Array.isArray(parsed[\"languages\"])) {\n return undefined;\n }\n for (const entry of parsed[\"languages\"] as unknown[]) {\n if (!isRecord(entry)) return undefined;\n const language = entry[\"language\"];\n const search = entry[\"search\"];\n if (\n typeof language !== \"string\" ||\n !isLanguageTag(language) ||\n typeof entry[\"documents\"] !== \"number\" ||\n !isRecord(search) ||\n typeof search[\"path\"] !== \"string\" ||\n typeof search[\"entries\"] !== \"number\" ||\n typeof search[\"digest\"] !== \"string\" ||\n !ownsFilename(search[\"path\"], searchIndexFilename(language))\n ) {\n return undefined;\n }\n const v = entry[\"vectors\"];\n if (v !== undefined) {\n if (\n !isRecord(v) ||\n typeof v[\"path\"] !== \"string\" ||\n typeof v[\"model\"] !== \"string\" ||\n typeof v[\"dtype\"] !== \"string\" ||\n typeof v[\"dims\"] !== \"number\" ||\n typeof v[\"count\"] !== \"number\" ||\n // Same constraint `search.path` gets: the last segment must be the\n // filename this language's sidecar would be given. Without it,\n // `isSafeRelativePath` alone leaves `vectors.path` far more reachable\n // than `search.path` — and `search --mode vector` opens it.\n !ownsFilename(v[\"path\"], vectorIndexFilename(language))\n ) {\n return undefined;\n }\n }\n }\n return parsed as unknown as LocalizationsDoc;\n}\n\n/**\n * A path from the manifest is joined onto a directory and opened, so it is\n * checked like any other untrusted path segment.\n *\n * `export` refuses to *write* a filename it built from a bad language tag; this\n * is the same hole on the read side, reached through a manifest instead of\n * through frontmatter. A hand-edited `\"path\": \"../../etc/passwd\"` would\n * otherwise be joined and read by `embed` and `search`.\n *\n * Rejects an absolute path, a Windows drive letter, a backslash, and any `.`\n * or empty segment. `..` is allowed **only as a prefix**, so `a/../../x` — an\n * escape wearing a normal first segment — is refused while `../vecs/x.bin`,\n * the layout `embed -o` produces, is not.\n *\n * How far up a leading run may climb is deliberately *not* capped. It was,\n * briefly, and the cap rejected manifests `embed -o` itself writes: a sidecar\n * directory two levels from the index directory produced an artifact set dockg\n * could not read back. The bound that matters is `ownsFilename` — a crafted\n * manifest can only ever name a file already called `search.<lang>.json` or\n * `vectors.<lang>.bin`, which is a long way from arbitrary-file read, and no\n * number of `..` segments widens it.\n */\nexport function isSafeRelativePath(path: string): boolean {\n if (path === \"\" || path.startsWith(\"/\") || /^[A-Za-z]:/.test(path)) {\n return false;\n }\n if (path.includes(\"\\\\\")) return false;\n const segments = path.split(\"/\");\n let leading = true;\n for (const segment of segments) {\n if (segment === \"\" || segment === \".\") return false;\n if (segment === \"..\") {\n if (!leading) return false;\n continue;\n }\n leading = false;\n }\n return true;\n}\n\n/**\n * The path is relative-safe *and* its last segment is the filename this\n * language's artifact would be given.\n *\n * The filename check is the constraint that actually narrows what a crafted\n * manifest can reach: `isSafeRelativePath` bounds the directory it can point\n * into, this bounds the file.\n */\nfunction ownsFilename(path: string, expected: string): boolean {\n if (!isSafeRelativePath(path)) return false;\n return path.slice(path.lastIndexOf(\"/\") + 1) === expected;\n}\n","/**\n * iiRDS Core + Software-domain term IRIs and the frontmatter-value → IRI maps\n * (ADR 01012). Every IRI here is byte-verified against the published\n * `iirds-core.rdf` / `iirds-software.rdf` in iirds-consortium/models. dockg\n * references these IRIs; it never redefines or re-types them (iiRDS is\n * CC BY-ND). This is the single source of truth shared by the schema\n * (via the schema-sync drift guard), derive, and shapes.\n */\nimport { NS } from \"./vocab.js\";\n\n/** Predicates (Core). */\nexport const IIRDS_HAS_TOPIC_TYPE = `${NS.iirds}has-topic-type`;\nexport const IIRDS_RELATES_TO_PRODUCT_VARIANT = `${NS.iirds}relates-to-product-variant`;\nexport const IIRDS_RELATES_TO_LIFECYCLE_PHASE = `${NS.iirds}relates-to-product-lifecycle-phase`;\nexport const IIRDS_HAS_SUBJECT = `${NS.iirds}has-subject`;\n\n/** Class minted for `graph.applies-to` nodes. */\nexport const IIRDS_PRODUCT_VARIANT = `${NS.iirds}ProductVariant`;\n\n/**\n * Package-serialization terms (iiRDS package export, ADR 01017). Local names\n * byte-verified against the canonical RDF/XML example in the published spec\n * (`sections/structure/serialization.md`). Used only by the package projection —\n * never emitted into the built graph. IUs are typed `iirds:Topic` (the subclass\n * that carries `has-topic-type`/`has-subject`), one of the valid IU subclasses.\n */\nexport const IIRDS_PACKAGE = `${NS.iirds}Package`;\nexport const IIRDS_IIRDS_VERSION = `${NS.iirds}iiRDSVersion`;\nexport const IIRDS_TOPIC = `${NS.iirds}Topic`;\nexport const IIRDS_IS_PART_OF_PACKAGE = `${NS.iirds}is-part-of-package`;\nexport const IIRDS_HAS_RENDITION = `${NS.iirds}has-rendition`;\nexport const IIRDS_RENDITION = `${NS.iirds}Rendition`;\nexport const IIRDS_SOURCE = `${NS.iirds}source`;\nexport const IIRDS_FORMAT = `${NS.iirds}format`;\nexport const IIRDS_TITLE = `${NS.iirds}title`;\nexport const IIRDS_LANGUAGE = `${NS.iirds}language`;\nexport const IIRDS_PARTY = `${NS.iirds}Party`;\nexport const IIRDS_HAS_PARTY_ROLE = `${NS.iirds}has-party-role`;\nexport const IIRDS_CREATOR = `${NS.iirds}Creator`;\nexport const IIRDS_RELATES_TO_PARTY = `${NS.iirds}relates-to-party`;\nexport const IIRDS_RELATES_TO_VCARD = `${NS.iirds}relates-to-vcard`;\n\n/** vcard namespace — package-local (not in the global NS/PREFIXES table). */\nexport const VCARD_NS = \"http://www.w3.org/2006/vcard/ns#\";\nexport const VCARD_ORGANIZATION = `${VCARD_NS}Organization`;\nexport const VCARD_ORGANIZATION_NAME = `${VCARD_NS}organization-name`;\n\n/**\n * Negative-scope predicates (ADR 01014). Minted into `graph:` — no standard\n * term exists, and OWL negative property assertions require blank nodes. Each\n * mirrors, and is SHACL-disjoint from, its positive counterpart above.\n */\nexport const GRAPH_NOT_APPLICABLE_TO_VARIANT = `${NS.graph}notApplicableToVariant`;\nexport const GRAPH_NOT_SOFTWARE_SUBJECT = `${NS.graph}notSoftwareSubject`;\n\n/**\n * Page-level `type` → `graph.type` (ADR 01024). The page's `type` is an open\n * vocabulary (docmeta:core); `graph.type` is the closed iiRDS enum. When the block\n * is silent, the page's value derives one through this map — an unmapped page\n * type derives nothing rather than inventing a topic type. An explicit\n * `graph.type` always wins: deeper wins, the page level is the fallback.\n */\nexport const PAGE_TYPE_TO_TOPIC_TYPE: Readonly<Record<string, string>> = {\n \"how-to\": \"task\",\n tutorial: \"learning\",\n explanation: \"concept\",\n reference: \"reference\",\n troubleshooting: \"troubleshooting\",\n};\n\n/** `graph.type` value → `iirds:has-topic-type` object IRI. */\nexport const TOPIC_TYPE_IRIS: Readonly<Record<string, string>> = {\n task: `${NS.iirds}GenericTask`,\n concept: `${NS.iirds}GenericConcept`,\n reference: `${NS.iirds}GenericReference`,\n learning: `${NS.iirds}GenericLearning`,\n troubleshooting: `${NS.iirds}GenericTroubleshooting`,\n form: `${NS.iirds}GenericForm`,\n};\n\n/**\n * `graph.about-product-lifecycle` value → `iirds:relates-to-product-lifecycle-phase`\n * object IRI (Software domain: iirds:Use/PuttingToUse/AfterUse instances).\n */\nexport const SOFTWARE_LIFECYCLE_IRIS: Readonly<Record<string, string>> = {\n administration: `${NS.iirdsSft}Administration`,\n customization: `${NS.iirdsSft}Customization`,\n update: `${NS.iirdsSft}Update`,\n deployment: `${NS.iirdsSft}Deployment`,\n integration: `${NS.iirdsSft}Integration`,\n deinstallation: `${NS.iirdsSft}Deinstallation`,\n};\n\n/**\n * `graph.about-product-aspect` value → `iirds:has-subject` object IRI (Software domain:\n * iirds:TechnicalOverview/TechnicalData instances).\n */\nexport const SOFTWARE_SUBJECT_IRIS: Readonly<Record<string, string>> = {\n architecture: `${NS.iirdsSft}Architecture`,\n interface: `${NS.iirdsSft}Interface`,\n \"system-requirement\": `${NS.iirdsSft}SystemRequirement`,\n};\n","/**\n * The deterministic walker (ADR 01018) — breadth-first traversal over a\n * `GraphIndex` with scope filtering, recording every hop and every exclusion\n * into a `QueryTrace`. This is the engine: generic RDF engines return bindings\n * without the path that produced them, and dockg's scope rules (ADR 01014)\n * are domain semantics no general engine knows.\n *\n * Determinism: neighbors come back sorted from the index, the frontier is\n * processed in (depth, IRI) order, and results are emitted in discovery order —\n * so the same graph + query always yields the same nodes *and* the same trace.\n *\n * Platform-neutral: no `node:` imports, no npm dependencies.\n */\nimport { byCodeUnit } from \"../core/sort.js\";\nimport { NS, RDF_TYPE } from \"../core/vocab.js\";\nimport { canonicalLanguageTag } from \"../core/localizations.js\";\nimport {\n GRAPH_NOT_APPLICABLE_TO_VARIANT,\n GRAPH_NOT_SOFTWARE_SUBJECT,\n IIRDS_HAS_SUBJECT,\n IIRDS_RELATES_TO_PRODUCT_VARIANT,\n SOFTWARE_SUBJECT_IRIS,\n} from \"../core/iirds.js\";\nimport type { GraphIndex } from \"./graph.js\";\nimport { createTrace, type QueryTrace, type ScopeExclusion } from \"./trace.js\";\n\nconst DCTERMS_TITLE = `${NS.dcterms}title`;\nconst DCTERMS_REFERENCES = `${NS.dcterms}references`;\nconst DCTERMS_LANGUAGE = `${NS.dcterms}language`;\n\n/** A section IRI's document, or the IRI itself when it has no fragment. */\nfunction documentOf(iri: string): string {\n const hash = iri.indexOf(\"#\");\n return hash === -1 ? iri : iri.slice(0, hash);\n}\n\nexport type Direction = \"out\" | \"in\" | \"both\";\n\nexport interface ScopeFilter {\n /** Product variant: an IRI, a `dcterms:title` (e.g. \"SP-X100\"), or a slug. */\n variant?: string;\n /** Software subject: an IRI or a `graph.about-product-aspect` value (e.g. \"architecture\"). */\n subject?: string;\n /**\n * BCP-47 tag (ADR 01037). Matched against `dcterms:language` after both are\n * canonicalized, since tags are case-insensitive. There is no fallback:\n * `de-AT` is not `de`, because relatedness between locales is an inference\n * and this runtime does not infer.\n */\n language?: string;\n}\n\nexport interface TraverseOptions extends ScopeFilter {\n /** Starting nodes (IRIs). */\n seeds: string[];\n /** Maximum hops from a seed. Default 1. */\n depth?: number;\n /** Restrict to these predicates (full IRIs). Default: every predicate. */\n predicates?: string[];\n /** Which edge directions to follow. Default \"out\". */\n direction?: Direction;\n /** Stop after this many nodes (seeds included). */\n limit?: number;\n /**\n * Follow `rdf:type` edges into class nodes. Default false, deliberately:\n * class nodes are schema, not content, and every document shares them — so\n * traversing them makes every document reachable from every other in two\n * hops (`a → graph:Document → b`). That is exactly the edge contamination\n * graph-governed retrieval exists to avoid. A `predicates` list that names\n * `rdf:type` follows them too, because it asked for them by name.\n */\n includeTypeEdges?: boolean;\n /** Append to an existing trace instead of starting a new one. */\n trace?: QueryTrace;\n}\n\nexport interface TraversedNode {\n iri: string;\n /** Hops from the nearest seed; seeds are 0. */\n depth: number;\n}\n\nexport interface TraverseResult {\n nodes: TraversedNode[];\n trace: QueryTrace;\n}\n\n/**\n * Resolve a variant input to its IRI: an exact node IRI, a `dcterms:title`\n * match on an `iirds:ProductVariant`, or a trailing-segment slug match.\n */\nexport function resolveVariant(\n graph: GraphIndex,\n input: string,\n): string | undefined {\n if (graph.has(input)) return input;\n const wanted = input.toLowerCase();\n const variants = graph.instancesOf(`${NS.iirds}ProductVariant`);\n for (const v of variants) {\n if (graph.literal(v, DCTERMS_TITLE)?.toLowerCase() === wanted) return v;\n }\n for (const v of variants) {\n if (v.slice(v.lastIndexOf(\"/\") + 1).toLowerCase() === wanted) return v;\n }\n return undefined;\n}\n\n/** Resolve a software-subject input to its iiRDS IRI. */\nexport function resolveSubject(\n graph: GraphIndex,\n input: string,\n): string | undefined {\n const mapped = SOFTWARE_SUBJECT_IRIS[input.toLowerCase()];\n if (mapped) return mapped;\n const expanded = graph.expand(input);\n return expanded.startsWith(\"http\") ? expanded : undefined;\n}\n\n/**\n * Decide whether a node survives the scope filter, and if not, why.\n *\n * Rules, in the spirit of ADR 01014 (absence of a positive claim is not a\n * negative claim, so both polarities are explicit):\n * - An explicit negative (`graph:notApplicableToVariant` /\n * `graph:notSoftwareSubject`) naming the target **excludes** the node.\n * - A node that declares a positive set which omits the target is **excluded**\n * — it scoped itself elsewhere — recorded under the positive predicate so\n * the trace distinguishes this from an explicit negative.\n * - A node that makes no claim is **kept**: unscoped content applies broadly.\n */\nexport function scopeExclusion(\n graph: GraphIndex,\n iri: string,\n scope: { variantIri?: string; subjectIri?: string; language?: string },\n): ScopeExclusion | undefined {\n // [target, positive predicate, negative predicate, object kind]. Language\n // joins the same table with two differences, both deliberate: its objects are\n // literals, and it has **no negative predicate** — a document has one\n // language (`sh:maxCount 1`), so \"not in German\" is not a claim an author\n // makes and there is nothing for a `graph:not*` term to express (ADR 01037).\n const checks: Array<\n [string | undefined, string, string | undefined, \"iri\" | \"literal\"]\n > = [\n [\n scope.variantIri,\n IIRDS_RELATES_TO_PRODUCT_VARIANT,\n GRAPH_NOT_APPLICABLE_TO_VARIANT,\n \"iri\",\n ],\n [scope.subjectIri, IIRDS_HAS_SUBJECT, GRAPH_NOT_SOFTWARE_SUBJECT, \"iri\"],\n [scope.language, DCTERMS_LANGUAGE, undefined, \"literal\"],\n ];\n for (const [target, positive, negative, kind] of checks) {\n if (!target) continue;\n if (negative !== undefined) {\n const denied = graph\n .values(iri, negative)\n .some((v) => v.kind === kind && v.value === target);\n if (denied) return { node: iri, rule: negative, value: target };\n }\n\n // Language is the one dimension a section inherits. Applicability is\n // explicit-only by ADR 01013 — a section may legitimately scope itself\n // differently from its document — but a section's *text* is in its\n // document's language and cannot differ, and the per-locale indexes file it\n // that way (`partitionByLanguage`). Without this a link with an anchor\n // reaches a section directly (derive.ts mints section IRIs as\n // `dcterms:references` targets) and carries English prose past a `de`\n // filter that excluded the document it belongs to.\n const subject = positive === DCTERMS_LANGUAGE ? documentOf(iri) : iri;\n const claimed = graph.values(subject, positive);\n if (claimed.length > 0) {\n const matches = claimed.some(\n (v) => v.kind === kind && v.value === target,\n );\n if (!matches) return { node: iri, rule: positive, value: target };\n }\n }\n return undefined;\n}\n\n/** Breadth-first traversal with scope filtering and full trace recording. */\nexport function traverse(\n graph: GraphIndex,\n options: TraverseOptions,\n): TraverseResult {\n const trace = options.trace ?? createTrace();\n const maxDepth = options.depth ?? 1;\n const direction: Direction = options.direction ?? \"out\";\n const allowed =\n options.predicates && options.predicates.length > 0\n ? new Set(options.predicates.map((p) => graph.expand(p)))\n : undefined;\n\n const variantIri = options.variant\n ? resolveVariant(graph, options.variant)\n : undefined;\n const subjectIri = options.subject\n ? resolveSubject(graph, options.subject)\n : undefined;\n // Language needs no resolution step, only a spelling: the filter value and\n // the graph value are both BCP-47 tags, and `derive` writes the canonical one.\n const language =\n options.language === undefined\n ? undefined\n : canonicalLanguageTag(options.language);\n const scope = { variantIri, subjectIri, language };\n // A predicate list that names `rdf:type` asked for type edges. Dropping them\n // anyway answered a question nobody asked, with an empty result.\n const followTypes =\n options.includeTypeEdges === true || allowed?.has(RDF_TYPE) === true;\n\n const excluded = new Set<string>();\n const keep = (iri: string): boolean => {\n if (excluded.has(iri)) return false;\n const exclusion = scopeExclusion(graph, iri, scope);\n if (exclusion) {\n excluded.add(iri);\n trace.exclusions.push(exclusion);\n return false;\n }\n return true;\n };\n\n const nodes: TraversedNode[] = [];\n const seen = new Set<string>();\n let frontier: string[] = [];\n\n // A seed `findEntry` already recorded keeps its real provenance. Re-recording\n // it as `explicit`/1 would leave the trace answering \"why did retrieval start\n // here?\" twice, with the lexical/vector score contradicted by a flat 1.\n const alreadySeeded = new Set(trace.entry.map((e) => e.iri));\n\n for (const seed of [...options.seeds].sort(byCodeUnit)) {\n if (!graph.has(seed) || seen.has(seed)) continue;\n seen.add(seed);\n if (!alreadySeeded.has(seed)) {\n trace.entry.push({ iri: seed, score: 1, via: \"explicit\" });\n }\n // A seed always expands, even when the scope filter excludes it. The\n // filter governs what the walk *reaches*, not where the caller chose to\n // start — and the canonical query is exactly this shape: from an English\n // page, `--impact --lang de` asks what German content a change here\n // affects. Gating the seed made that return nothing at all, because the\n // seed excluded itself before the frontier was ever populated.\n //\n // It is still kept out of the results and recorded in the trace, so the\n // answer honors the filter even though the walk started outside it.\n if (keep(seed)) nodes.push({ iri: seed, depth: 0 });\n frontier.push(seed);\n }\n\n const limit = options.limit ?? Infinity;\n for (let depth = 1; depth <= maxDepth && frontier.length > 0; depth++) {\n const next: string[] = [];\n for (const from of frontier) {\n if (nodes.length >= limit) break;\n for (const { predicate, target, dir } of neighbors(\n graph,\n from,\n direction,\n )) {\n if (allowed && !allowed.has(predicate)) continue;\n if (!followTypes && predicate === RDF_TYPE) continue;\n // The hop is recorded before filtering: the trace shows the edge was\n // walked even when the target is then scope-excluded.\n trace.hops.push({ from, predicate, to: target, depth, direction: dir });\n if (seen.has(target)) continue;\n seen.add(target);\n if (!keep(target)) continue;\n if (nodes.length >= limit) break;\n nodes.push({ iri: target, depth });\n next.push(target);\n }\n }\n frontier = next;\n }\n\n return { nodes, trace };\n}\n\nfunction neighbors(\n graph: GraphIndex,\n iri: string,\n direction: Direction,\n): Array<{ predicate: string; target: string; dir: \"out\" | \"in\" }> {\n const out: Array<{ predicate: string; target: string; dir: \"out\" | \"in\" }> =\n [];\n if (direction === \"out\" || direction === \"both\") {\n for (const e of graph.out(iri)) out.push({ ...e, dir: \"out\" });\n }\n if (direction === \"in\" || direction === \"both\") {\n for (const e of graph.in(iri)) out.push({ ...e, dir: \"in\" });\n }\n return out;\n}\n\n/** Who links to this node (one hop inbound over `dcterms:references`). */\nexport function reverseReferences(\n graph: GraphIndex,\n iri: string,\n options: Omit<TraverseOptions, \"seeds\" | \"direction\" | \"predicates\"> = {},\n): TraverseResult {\n return traverse(graph, {\n ...options,\n seeds: [iri],\n direction: \"in\",\n predicates: [DCTERMS_REFERENCES],\n depth: options.depth ?? 1,\n });\n}\n\n/**\n * Transitive inbound reach — \"what is affected if this node changes\".\n * Excludes the node itself from the returned set. Defaults to depth 3 rather\n * than the walker's 1, because impact analysis is only useful transitively.\n */\nexport function impact(\n graph: GraphIndex,\n iri: string,\n options: Omit<TraverseOptions, \"seeds\" | \"direction\"> = {},\n): TraverseResult {\n const result = traverse(graph, {\n ...options,\n seeds: [iri],\n direction: \"in\",\n depth: options.depth ?? 3,\n // The seed *may* occupy a slot in the walker's limit, so ask for one more:\n // `limit` means \"this many *affected* nodes\". Whether it actually takes\n // one depends on the scope filter — a seed the filter excludes still\n // expands but is not in `nodes` — so the slack is trimmed below rather\n // than assumed spent.\n limit: options.limit === undefined ? undefined : options.limit + 1,\n });\n const affected = result.nodes.filter((n) => n.iri !== iri);\n return {\n nodes:\n options.limit === undefined ? affected : affected.slice(0, options.limit),\n trace: result.trace,\n };\n}\n","/**\n * Content resolution (ADR 01018): graph node → the text it stands for.\n *\n * The graph is an index over documents ([ADR 01008](../../adrs/01008-graph-as-index-not-corpus.md)),\n * so retrieval must go back to the source to get text. The seam is a\n * `ContentResolver`; the shipped implementation uses `fetch`, which works\n * unchanged in browsers and in Node ≥18, and is injectable for tests.\n *\n * Section nodes (`doc.md#slug`) resolve by fetching the parent document and\n * slicing it at the heading whose text matches the section's `dcterms:title`\n * — so no line-span predicates need to be added to the graph.\n *\n * Platform-neutral: no `node:` imports, no npm dependencies.\n */\nimport { NS } from \"../core/vocab.js\";\nimport type { GraphIndex } from \"./graph.js\";\nimport type { QueryTrace } from \"./trace.js\";\n\nconst GRAPH_PATH = `${NS.graph}path`;\nconst DCTERMS_TITLE = `${NS.dcterms}title`;\nconst DCTERMS_HAS_PART = `${NS.dcterms}hasPart`;\nconst GRAPH_LEVEL = `${NS.graph}level`;\nconst GRAPH_ORDER = `${NS.graph}order`;\n\nexport interface ResolvedContent {\n iri: string;\n text: string;\n sourceUrl: string;\n title?: string;\n}\n\nexport interface ContentResolver {\n /** Text for a node, or undefined when the node has no content. */\n resolve(iri: string): Promise<ResolvedContent | undefined>;\n}\n\ntype FetchLike = (\n url: string,\n) => Promise<{ ok: boolean; status: number; text(): Promise<string> }>;\n\nexport interface FetchResolverOptions {\n /** Prefix joined to each `graph:path`, e.g. \"https://site/raw/\". */\n baseUrl?: string;\n /** Full control over path → URL. Overrides `baseUrl`. */\n pathToUrl?: (path: string) => string;\n /** Injectable fetch (defaults to the global). */\n fetch?: FetchLike;\n /** Record resolutions here. */\n trace?: QueryTrace;\n}\n\n/** Split a section IRI into its document IRI and fragment. */\nexport function splitFragment(iri: string): { doc: string; fragment?: string } {\n const hash = iri.indexOf(\"#\");\n return hash < 0\n ? { doc: iri }\n : { doc: iri.slice(0, hash), fragment: iri.slice(hash + 1) };\n}\n\n/**\n * Mark every line that sits inside a fenced code block (including the fence\n * delimiters themselves). Without this, a shell comment in a code sample —\n * `# Set the API key` — reads as an h1 and truncates the surrounding section,\n * which silently drops most of the retrieved content.\n *\n * CommonMark rules, minus the ones a heading scan cannot observe: a fence opens\n * on 3+ backticks or tildes indented at most 3 spaces, a backtick fence's info\n * string may not contain a backtick, and it closes on a delimiter of the same\n * character that is at least as long and carries no info string. An unclosed\n * fence runs to end of document.\n */\nfunction fencedLines(lines: string[]): boolean[] {\n const mask = new Array<boolean>(lines.length).fill(false);\n let open: string | undefined;\n for (const [i, line] of lines.entries()) {\n const m = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line);\n // Both groups are mandatory in the pattern, so a match carries both.\n // Requiring them is the check that proves it, and it replaces the bare\n // `m &&` the branches already tested — no condition is added, only\n // sharpened.\n const delimiter = m?.[1];\n const info = m?.[2];\n const isFence = delimiter !== undefined && info !== undefined;\n if (open === undefined) {\n if (isFence && !(delimiter.startsWith(\"`\") && info.includes(\"`\"))) {\n open = delimiter;\n mask[i] = true;\n }\n continue;\n }\n mask[i] = true;\n if (\n isFence &&\n delimiter[0] === open[0] &&\n delimiter.length >= open.length &&\n info.trim() === \"\"\n ) {\n open = undefined;\n }\n }\n return mask;\n}\n\n/** One heading as the source spells it, located by the line it starts on. */\ninterface SourceHeading {\n /** First line: the `#` line, or a setext heading's first line of text. */\n start: number;\n level: number;\n /** The heading's raw inline text, markdown and all. */\n text: string;\n}\n\nconst ATX = /^ {0,3}(#{1,6})(?:[ \\t]+(.*?))?[ \\t]*$/;\nconst SETEXT_UNDERLINE = /^ {0,3}(=+|-+)[ \\t]*$/;\n\n/**\n * Whether a line can be paragraph text, which a setext underline turns into a\n * heading. A blank line, an ATX heading, a list item, a block quote, a\n * thematic break and indented code cannot.\n */\nfunction isParagraphLine(line: string): boolean {\n if (line.trim() === \"\") return false;\n if (ATX.test(line)) return false;\n if (/^ {0,3}([-+*]|\\d{1,9}[.)])([ \\t]|$)/.test(line)) return false;\n if (/^ {0,3}>/.test(line)) return false;\n if (/^ {0,3}([-*_])([ \\t]*\\1){2,}[ \\t]*$/.test(line)) return false;\n return !/^ {4}/.test(line);\n}\n\n/**\n * How many leading lines a YAML frontmatter block takes, delimiters included.\n * Its closing `---` follows a line of text, so without this the scan would\n * read the last frontmatter key as a setext heading.\n */\nfunction frontmatterLength(lines: string[]): number {\n if (lines[0]?.trim() !== \"---\") return 0;\n for (let i = 1; i < lines.length; i++) {\n const line = lines[i]?.trim();\n if (line === \"---\" || line === \"...\") return i + 1;\n }\n return 0;\n}\n\n/**\n * Every heading in a markdown source, in order. ATX headings may sit up to\n * three spaces in and lose any closing `#` run. Setext headings are\n * underlined with `=` or `-`. Fenced code and frontmatter hold none.\n *\n * Line-based, so a shape remark reads and this does not is possible. The\n * common ones are covered, and a miss leaves one section unindexed.\n */\nfunction sourceHeadings(lines: string[]): SourceHeading[] {\n const fenced = fencedLines(lines);\n const skip = frontmatterLength(lines);\n const headings: SourceHeading[] = [];\n /** First line of the paragraph the scan is inside, or -1. */\n let paragraph = -1;\n for (const [i, line] of lines.entries()) {\n if (i < skip || fenced[i]) {\n paragraph = -1;\n continue;\n }\n const atx = ATX.exec(line);\n const hashes = atx?.[1];\n if (hashes !== undefined) {\n // A closing run is `#`s after whitespace, or the whole content.\n const text = (atx?.[2] ?? \"\").replace(/(^|[ \\t]+)#+$/, \"\");\n headings.push({ start: i, level: hashes.length, text });\n paragraph = -1;\n continue;\n }\n const underline = SETEXT_UNDERLINE.exec(line)?.[1];\n if (underline !== undefined && paragraph >= 0) {\n headings.push({\n start: paragraph,\n level: underline.startsWith(\"=\") ? 1 : 2,\n text: lines.slice(paragraph, i).join(\"\\n\"),\n });\n paragraph = -1;\n continue;\n }\n if (isParagraphLine(line)) {\n if (paragraph < 0) paragraph = i;\n } else {\n paragraph = -1;\n }\n }\n return headings;\n}\n\nconst ENTITIES: Record<string, string> = {\n amp: \"&\",\n lt: \"<\",\n gt: \">\",\n quot: '\"',\n apos: \"'\",\n nbsp: \" \",\n};\n\n/** Decode the character references a heading is likely to carry. */\nfunction decodeEntities(text: string): string {\n return text.replace(\n /&(#x[0-9a-f]+|#[0-9]+|[a-z]+);/gi,\n (whole, name: string) => {\n if (name.startsWith(\"#\")) {\n const hex = name[1] === \"x\" || name[1] === \"X\";\n const code = Number.parseInt(name.slice(hex ? 2 : 1), hex ? 16 : 10);\n return Number.isNaN(code) || code > 0x10ffff\n ? whole\n : String.fromCodePoint(code);\n }\n return ENTITIES[name.toLowerCase()] ?? whole;\n },\n );\n}\n\n/**\n * The key a heading is matched by, from either side. One side is the\n * plain-text title the build recorded, the other the source text after\n * `stripInline`. Markup characters go, whitespace collapses, and case folds.\n * Both sides pass through it, so a character it drops cannot make them differ.\n */\nexport function headingKey(text: string): string {\n return text\n .replace(/[`*_~\\\\[\\]]/g, \"\")\n .replace(/\\s+/g, \" \")\n .trim()\n .toLowerCase();\n}\n\n/**\n * Raw heading source to the text remark reads from it. Links and images keep\n * their text, autolinks their target, and character references decode.\n */\nfunction stripInline(raw: string): string {\n return decodeEntities(\n raw\n .replace(/!?\\[([^\\]]*)\\]\\((?:[^()]|\\([^()]*\\))*\\)/g, \"$1\")\n .replace(/!?\\[([^\\]]*)\\]\\[[^\\]]*\\]/g, \"$1\")\n .replace(/<((?:https?|mailto):[^>\\s]+)>/gi, \"$1\"),\n );\n}\n\n/**\n * Sections of a document in true document order, reconstructed from the\n * `dcterms:hasPart` tree ordered by `graph:order` within each parent.\n *\n * Needed because heading text is not unique: a document with two `## Install`\n * headings produces two section nodes, and matching by title alone would give\n * both the *first* heading's text — wrong content under a confident citation.\n */\nexport function documentSectionOrder(\n graph: GraphIndex,\n docIri: string,\n): string[] {\n const ordered: string[] = [];\n const seen = new Set<string>();\n\n const childrenOf = (iri: string): string[] =>\n graph\n .out(iri, DCTERMS_HAS_PART)\n .map((e) => e.target)\n .sort((a, b) => {\n const oa = Number.parseInt(graph.literal(a, GRAPH_ORDER) ?? \"\", 10);\n const ob = Number.parseInt(graph.literal(b, GRAPH_ORDER) ?? \"\", 10);\n if (Number.isNaN(oa) || Number.isNaN(ob) || oa === ob) {\n return a < b ? -1 : a > b ? 1 : 0;\n }\n return oa - ob;\n });\n\n const walk = (iri: string): void => {\n for (const child of childrenOf(iri)) {\n if (seen.has(child)) continue;\n seen.add(child);\n ordered.push(child);\n walk(child);\n }\n };\n walk(docIri);\n return ordered;\n}\n\n/**\n * Occurrence number of every section of a document, in one walk: section IRI →\n * how many earlier sections share its heading text and level.\n *\n * Batched because the per-section form is quadratic — a document with N\n * sections would otherwise rebuild the whole `hasPart` order N times, once per\n * section indexed or resolved.\n */\nexport function sectionOccurrences(\n graph: GraphIndex,\n docIri: string,\n): Map<string, number> {\n const occurrences = new Map<string, number>();\n // title → level → how many carrying that pair have been seen so far. Nested\n // rather than a joined key, so no separator has to be safe in either field.\n const counts = new Map<string, Map<string, number>>();\n\n for (const section of documentSectionOrder(graph, docIri)) {\n const rawTitle = graph.literal(section, DCTERMS_TITLE);\n if (rawTitle === undefined) {\n occurrences.set(section, 0);\n continue;\n }\n // Keyed exactly the way `sliceSection` matches headings, by `headingKey`.\n // Keyed by the raw title instead, a document with `## Install`\n // and `## install` gives both sections occurrence 0, and the second one\n // then slices the first heading: wrong content under a confident citation.\n const title = headingKey(rawTitle);\n const level = graph.literal(section, GRAPH_LEVEL) ?? \"\";\n let byLevel = counts.get(title);\n if (!byLevel) {\n byLevel = new Map();\n counts.set(title, byLevel);\n }\n const seen = byLevel.get(level) ?? 0;\n occurrences.set(section, seen);\n byLevel.set(level, seen + 1);\n }\n return occurrences;\n}\n\n/**\n * Which occurrence of its heading text a section is (0-based) — the number of\n * earlier same-title, same-level sections in the same document. A section the\n * `hasPart` tree does not reach counts as the first (0).\n */\nexport function sectionOccurrence(\n graph: GraphIndex,\n sectionIri: string,\n): number {\n const { doc } = splitFragment(sectionIri);\n return sectionOccurrences(graph, doc).get(sectionIri) ?? 0;\n}\n\n/**\n * The prose before a document's first heading — the text that belongs to no\n * section, and so would otherwise be indexed nowhere in a document that has\n * sections.\n *\n * Fence-aware for the same reason `sliceSection` is: a `#` comment inside a\n * leading code block is not a heading, and treating it as one would cut the\n * preamble short. Frontmatter is *not* stripped here — the caller decides,\n * since only the search index cares about that.\n */\nexport function documentPreamble(markdown: string): string | undefined {\n const lines = markdown.split(/\\r?\\n/);\n const end = sourceHeadings(lines)[0]?.start ?? lines.length;\n const text = lines.slice(0, end).join(\"\\n\").trim();\n return text === \"\" ? undefined : text;\n}\n\n/**\n * Slice a markdown document at the heading whose text matches `title`,\n * returning that heading through to the next heading of the same or higher\n * rank. Returns undefined when no such heading exists. Handles CRLF, and\n * ignores `#` lines inside fenced code blocks.\n *\n * `occurrence` selects among repeated headings (0 = the first). Heading text is\n * not unique, so callers with a specific section node in hand should pass\n * `sectionOccurrence(graph, iri)` rather than defaulting to the first match.\n */\nexport function sliceSection(\n markdown: string,\n title: string,\n level?: number,\n occurrence = 0,\n): string | undefined {\n return slice(markdown, title, level, occurrence, false);\n}\n\n/**\n * The text a section *owns*: its heading down to the next heading of **any**\n * rank, so nested subsections are excluded.\n *\n * `sliceSection` keeps the subtree because that is what retrieval wants — ask\n * for \"Configuration\" and you should get its subsections too. Indexing wants\n * the opposite: with the subtree, a parent section matches everything its\n * children match and outranks them, so an H1 section shadows every heading\n * beneath it. Same granularity rule as Document vs Section, one level down.\n */\nexport function sectionOwnText(\n markdown: string,\n title: string,\n level?: number,\n occurrence = 0,\n): string | undefined {\n return slice(markdown, title, level, occurrence, true);\n}\n\nfunction slice(\n markdown: string,\n title: string,\n level: number | undefined,\n occurrence: number,\n ownTextOnly: boolean,\n): string | undefined {\n const lines = markdown.split(/\\r?\\n/);\n const headings = sourceHeadings(lines);\n const wanted = headingKey(title);\n let remaining = occurrence;\n let found = -1;\n\n for (const [n, heading] of headings.entries()) {\n if (level !== undefined && heading.level !== level) continue;\n if (headingKey(stripInline(heading.text)) !== wanted) continue;\n if (remaining > 0) {\n remaining -= 1;\n continue;\n }\n found = n;\n break;\n }\n const match = headings[found];\n if (match === undefined) return undefined;\n\n const next = headings\n .slice(found + 1)\n .find((h) => ownTextOnly || h.level <= match.level);\n const end = next?.start ?? lines.length;\n return lines.slice(match.start, end).join(\"\\n\").trimEnd();\n}\n\n/**\n * A resolver that fetches document sources over HTTP. Documents map through\n * `graph:path`; sections slice their parent document by heading.\n */\nexport function createFetchResolver(\n graph: GraphIndex,\n options: FetchResolverOptions = {},\n): ContentResolver {\n const doFetch: FetchLike =\n options.fetch ?? ((url: string) => globalThis.fetch(url));\n const toUrl =\n options.pathToUrl ?? ((path: string) => `${options.baseUrl ?? \"\"}${path}`);\n const cache = new Map<string, Promise<string | undefined>>();\n // `assemble` resolves many sections of the same document; the occurrence walk\n // is per-document, so compute it once and reuse it.\n const occurrenceCache = new Map<string, Map<string, number>>();\n\n const occurrenceOf = (docIri: string, sectionIri: string): number => {\n let map = occurrenceCache.get(docIri);\n if (!map) {\n map = sectionOccurrences(graph, docIri);\n occurrenceCache.set(docIri, map);\n }\n return map.get(sectionIri) ?? 0;\n };\n\n const fetchDoc = (url: string): Promise<string | undefined> => {\n let pending = cache.get(url);\n if (!pending) {\n pending = doFetch(url)\n .then((r) => (r.ok ? r.text() : undefined))\n .catch(() => undefined);\n cache.set(url, pending);\n }\n return pending;\n };\n\n return {\n async resolve(iri: string): Promise<ResolvedContent | undefined> {\n const { doc, fragment } = splitFragment(iri);\n const path = graph.literal(doc, GRAPH_PATH);\n if (!path) return undefined;\n\n const sourceUrl = toUrl(path);\n const body = await fetchDoc(sourceUrl);\n const title = graph.literal(iri, DCTERMS_TITLE);\n\n if (body === undefined) {\n options.trace?.resolutions.push({\n iri,\n sourceUrl,\n ok: false,\n error: \"fetch failed\",\n });\n return undefined;\n }\n\n let text = body;\n if (fragment) {\n const levelText = graph.literal(iri, GRAPH_LEVEL);\n const level = levelText ? Number.parseInt(levelText, 10) : undefined;\n const slice =\n title === undefined\n ? undefined\n : sliceSection(\n body,\n title,\n Number.isNaN(level) ? undefined : level,\n occurrenceOf(doc, iri),\n );\n if (slice === undefined) {\n options.trace?.resolutions.push({\n iri,\n sourceUrl,\n ok: false,\n error: \"section heading not found\",\n });\n return undefined;\n }\n text = slice;\n }\n\n options.trace?.resolutions.push({ iri, sourceUrl, ok: true });\n return { iri, text, sourceUrl, title };\n },\n };\n}\n","/**\n * Context assembly (ADR 01018) — the runtime's terminal stage.\n *\n * Turns traversed nodes into the bundle an inference engine consumes:\n * `{ context, citations, trace, refusal? }`. **dockg stops here**: it never\n * calls a model. A different tool (an agent over MCP, a site backend) takes the\n * bundle onward, which keeps this runtime fully deterministic and keeps API\n * keys and inference cost outside dockg entirely.\n *\n * When nothing survives retrieval the result is a *structured refusal*, never\n * empty context — a caller must be able to tell \"no route exists\" apart from\n * \"here is nothing, proceed anyway\" (the disciplined-silence contract).\n *\n * Platform-neutral: no `node:` imports, no npm dependencies.\n */\nimport type { ContentResolver } from \"./resolve.js\";\nimport type { EntryCandidate, QueryTrace } from \"./trace.js\";\nimport { createTrace } from \"./trace.js\";\nimport type { TraversedNode } from \"./traverse.js\";\n\nexport interface ContextBlock {\n iri: string;\n title?: string;\n text: string;\n sourceUrl: string;\n /** Hops from the nearest seed — the relevance signal, carried through. */\n depth: number;\n}\n\nexport interface Citation {\n iri: string;\n title?: string;\n sourceUrl: string;\n}\n\nexport type RefusalReason = \"no-route\" | \"no-content\";\n\nexport interface Refusal {\n reason: RefusalReason;\n detail: string;\n}\n\n/**\n * The rankings that produced the seeds, carried through to the caller.\n *\n * Retrieval answers two different questions — \"what matched the query?\" and\n * \"what is the graph connected to it?\" — and a consumer needs both. Returning\n * only the graph result would make the match rankings inferrable solely from the\n * trace, which is diagnostic rather than a result surface (ADR 01020).\n */\nexport interface EntryRankings {\n /** The lexical leg's own ranking. */\n lexical: EntryCandidate[];\n /** The vector leg's own ranking; empty when no embedder was in play. */\n vector: EntryCandidate[];\n /** The fused ranking that actually seeded traversal. */\n merged: EntryCandidate[];\n}\n\nexport interface RetrievalBundle {\n /** What matched the query, per leg. Absent when seeds were given explicitly. */\n entry?: EntryRankings;\n context: ContextBlock[];\n citations: Citation[];\n trace: QueryTrace;\n /** Present when retrieval found nothing usable. `context` is then empty. */\n refusal?: Refusal;\n /** True when the character budget dropped otherwise-eligible blocks. */\n truncated: boolean;\n}\n\nexport interface AssembleOptions {\n /** Character budget across all blocks. Default: unbounded. */\n maxChars?: number;\n /** Append to an existing trace (normally the traversal's). */\n trace?: QueryTrace;\n /**\n * The entry rankings that produced these nodes, passed through to the bundle\n * so callers see matches and graph results side by side.\n */\n entry?: EntryRankings;\n}\n\n/**\n * Resolve traversed nodes to text and assemble the retrieval bundle. Nodes are\n * kept in traversal order (nearest-first), which is deterministic, and every\n * block carries the IRI it came from so citations are structural, not inferred.\n */\nexport async function assemble(\n resolver: ContentResolver,\n nodes: TraversedNode[],\n options: AssembleOptions = {},\n): Promise<RetrievalBundle> {\n const trace = options.trace ?? createTrace();\n const budget = options.maxChars ?? Infinity;\n\n if (nodes.length === 0) {\n return {\n ...(options.entry ? { entry: options.entry } : {}),\n context: [],\n citations: [],\n trace,\n truncated: false,\n refusal: {\n reason: \"no-route\",\n detail:\n \"No node in the graph was reachable for this query under the active scope filter.\",\n },\n };\n }\n\n const context: ContextBlock[] = [];\n let used = 0;\n let truncated = false;\n let resolvedAny = false;\n\n for (const node of nodes) {\n const resolved = await resolver.resolve(node.iri);\n if (!resolved) continue;\n resolvedAny = true;\n if (used + resolved.text.length > budget) {\n truncated = true;\n continue;\n }\n used += resolved.text.length;\n context.push({\n iri: resolved.iri,\n title: resolved.title,\n text: resolved.text,\n sourceUrl: resolved.sourceUrl,\n depth: node.depth,\n });\n }\n\n if (context.length === 0) {\n return {\n ...(options.entry ? { entry: options.entry } : {}),\n context: [],\n citations: [],\n trace,\n truncated,\n refusal: {\n reason: \"no-content\",\n detail: resolvedAny\n ? \"Every matching node's content exceeded the character budget.\"\n : \"Matching nodes were found, but none of them resolved to readable content.\",\n },\n };\n }\n\n return {\n ...(options.entry ? { entry: options.entry } : {}),\n context,\n citations: context.map((b) => ({\n iri: b.iri,\n title: b.title,\n sourceUrl: b.sourceUrl,\n })),\n trace,\n truncated,\n };\n}\n","/**\n * RDF/JS interop — the custom-SPARQL escape hatch (ADR 01018).\n *\n * The runtime's own walker is deliberately not a SPARQL engine: it is 0 KB and\n * it records a trace. But arbitrary user-authored SPARQL is a legitimate need,\n * so the index can hand out its contents as standard **RDF/JS quads**. Feed\n * them to any RDF/JS store and query with any engine:\n *\n * ```js\n * import { Store } from \"n3\";\n * import { QueryEngine } from \"@comunica/query-sparql-rdfjs-lite\";\n * const store = new Store(rdfjsQuads(graph));\n * const bindings = await new QueryEngine().queryBindings(sparql, { sources: [store] });\n * ```\n *\n * Quads are plain data rather than a hand-rolled `Source` stream on purpose:\n * every engine already accepts a store, stores accept quad arrays, and faking\n * Node's stream contract in a browser-safe module is fragile for no gain. At\n * docs scale materializing is trivial (the reference corpus is 172 quads).\n *\n * Honest caveat: engine results are bindings, not walker traces —\n * explainability lives in the walker API.\n *\n * The term shapes are structural, so they are hand-rolled here rather than\n * pulled from `@rdfjs/data-model`, keeping the runtime dependency-free and\n * browser-safe.\n */\nimport { byCodeUnit } from \"../core/sort.js\";\nimport type { GraphIndex, Value } from \"./graph.js\";\n\nconst XSD_STRING = \"http://www.w3.org/2001/XMLSchema#string\";\n\nexport interface RdfTerm {\n termType: \"NamedNode\" | \"Literal\" | \"DefaultGraph\";\n value: string;\n language?: string;\n datatype?: RdfTerm;\n equals(other?: RdfTerm | null): boolean;\n}\n\nexport interface RdfQuad {\n termType: \"Quad\";\n subject: RdfTerm;\n predicate: RdfTerm;\n object: RdfTerm;\n graph: RdfTerm;\n equals(other?: RdfQuad | null): boolean;\n}\n\nexport function namedNode(value: string): RdfTerm {\n return {\n termType: \"NamedNode\",\n value,\n equals(other) {\n return !!other && other.termType === \"NamedNode\" && other.value === value;\n },\n };\n}\n\nexport function defaultGraph(): RdfTerm {\n return {\n termType: \"DefaultGraph\",\n value: \"\",\n equals(other) {\n return !!other && other.termType === \"DefaultGraph\";\n },\n };\n}\n\nexport function literal(value: string, datatype?: string): RdfTerm {\n const dt = namedNode(datatype ?? XSD_STRING);\n return {\n termType: \"Literal\",\n value,\n language: \"\",\n datatype: dt,\n equals(other) {\n return (\n !!other &&\n other.termType === \"Literal\" &&\n other.value === value &&\n !!other.datatype &&\n other.datatype.value === dt.value\n );\n },\n };\n}\n\nfunction toTerm(v: Value): RdfTerm {\n return v.kind === \"iri\" ? namedNode(v.value) : literal(v.value, v.datatype);\n}\n\nfunction makeQuad(s: string, p: string, o: Value): RdfQuad {\n const subject = namedNode(s);\n const predicate = namedNode(p);\n const object = toTerm(o);\n const graph = defaultGraph();\n return {\n termType: \"Quad\",\n subject,\n predicate,\n object,\n graph,\n equals(other) {\n return (\n !!other &&\n subject.equals(other.subject) &&\n predicate.equals(other.predicate) &&\n object.equals(other.object)\n );\n },\n };\n}\n\n/**\n * The whole index as RDF/JS quads, in the index's deterministic order. Feed to\n * any RDF/JS store (`new Store(rdfjsQuads(graph))`) to run SPARQL.\n */\nexport function rdfjsQuads(graph: GraphIndex): RdfQuad[] {\n const quads: RdfQuad[] = [];\n for (const s of graph.ids()) {\n const node = graph.node(s);\n if (!node) continue;\n for (const p of [...node.props.keys()].sort(byCodeUnit)) {\n for (const v of node.props.get(p) ?? []) quads.push(makeQuad(s, p, v));\n }\n }\n return quads;\n}\n\n/**\n * Triple-pattern match returning RDF/JS quads. A null/undefined position is a\n * wildcard. Convenience for callers who want RDF/JS terms without pulling in a\n * store; the walker API is the richer (and traced) way to query.\n */\nexport function matchQuads(\n graph: GraphIndex,\n subject?: string | null,\n predicate?: string | null,\n object?: string | null,\n): RdfQuad[] {\n const quads: RdfQuad[] = [];\n const subjects = subject ? [subject] : graph.ids();\n for (const s of subjects) {\n const node = graph.node(s);\n if (!node) continue;\n const predicates = predicate\n ? [predicate]\n : [...node.props.keys()].sort(byCodeUnit);\n for (const p of predicates) {\n for (const v of node.props.get(p) ?? []) {\n if (object !== undefined && object !== null && v.value !== object) {\n continue;\n }\n quads.push(makeQuad(s, p, v));\n }\n }\n }\n return quads;\n}\n","import type { RadixTree, Entry, LeafType } from './types'\n\n/** @ignore */\nconst ENTRIES = 'ENTRIES'\n\n/** @ignore */\nconst KEYS = 'KEYS'\n\n/** @ignore */\nconst VALUES = 'VALUES'\n\n/** @ignore */\nconst LEAF = '' as LeafType\n\ninterface Iterators<T> {\n ENTRIES: Entry<T>\n KEYS: string\n VALUES: T\n}\n\ntype Kind<T> = keyof Iterators<T>\ntype Result<T, K extends keyof Iterators<T>> = Iterators<T>[K]\n\ntype IteratorPath<T> = {\n node: RadixTree<T>,\n keys: string[]\n}[]\n\nexport type IterableSet<T> = {\n _tree: RadixTree<T>,\n _prefix: string\n}\n\n/**\n * @private\n */\nclass TreeIterator<T, K extends Kind<T>> implements Iterator<Result<T, K>> {\n set: IterableSet<T>\n _type: K\n _path: IteratorPath<T>\n\n constructor (set: IterableSet<T>, type: K) {\n const node = set._tree\n const keys = Array.from(node.keys())\n this.set = set\n this._type = type\n this._path = keys.length > 0 ? [{ node, keys }] : []\n }\n\n next (): IteratorResult<Result<T, K>> {\n const value = this.dive()\n this.backtrack()\n return value\n }\n\n dive (): IteratorResult<Result<T, K>> {\n if (this._path.length === 0) { return { done: true, value: undefined } }\n const { node, keys } = last(this._path)!\n if (last(keys) === LEAF) { return { done: false, value: this.result() } }\n\n const child = node.get(last(keys)!)!\n this._path.push({ node: child, keys: Array.from(child.keys()) })\n return this.dive()\n }\n\n backtrack (): void {\n if (this._path.length === 0) { return }\n const keys = last(this._path)!.keys\n keys.pop()\n if (keys.length > 0) { return }\n this._path.pop()\n this.backtrack()\n }\n\n key (): string {\n return this.set._prefix + this._path\n .map(({ keys }) => last(keys))\n .filter(key => key !== LEAF)\n .join('')\n }\n\n value (): T {\n return last(this._path)!.node.get(LEAF)!\n }\n\n result (): Result<T, K> {\n switch (this._type) {\n case VALUES: return this.value() as Result<T, K>\n case KEYS: return this.key() as Result<T, K>\n default: return [this.key(), this.value()] as Result<T, K>\n }\n }\n\n [Symbol.iterator] () {\n return this\n }\n}\n\nconst last = <T>(array: T[]): T | undefined => {\n return array[array.length - 1]\n}\n\nexport { TreeIterator, ENTRIES, KEYS, VALUES, LEAF }\n","/* eslint-disable no-labels */\nimport { LEAF } from './TreeIterator'\nimport type { RadixTree } from './types'\n\nexport type FuzzyResult<T> = [T, number]\n\nexport type FuzzyResults<T> = Map<string, FuzzyResult<T>>\n\n/**\n * @ignore\n */\nexport const fuzzySearch = <T = any>(node: RadixTree<T>, query: string, maxDistance: number): FuzzyResults<T> => {\n const results: FuzzyResults<T> = new Map()\n if (query === undefined) return results\n\n // Number of columns in the Levenshtein matrix.\n const n = query.length + 1\n\n // Matching terms can never be longer than N + maxDistance.\n const m = n + maxDistance\n\n // Fill first matrix row and column with numbers: 0 1 2 3 ...\n const matrix = new Uint8Array(m * n).fill(maxDistance + 1)\n for (let j = 0; j < n; ++j) matrix[j] = j\n for (let i = 1; i < m; ++i) matrix[i * n] = i\n\n recurse(\n node,\n query,\n maxDistance,\n results,\n matrix,\n 1,\n n,\n ''\n )\n\n return results\n}\n\n// Modified version of http://stevehanov.ca/blog/?id=114\n\n// This builds a Levenshtein matrix for a given query and continuously updates\n// it for nodes in the radix tree that fall within the given maximum edit\n// distance. Keeping the same matrix around is beneficial especially for larger\n// edit distances.\n//\n// k a t e <-- query\n// 0 1 2 3 4\n// c 1 1 2 3 4\n// a 2 2 1 2 3\n// t 3 3 2 1 [2] <-- edit distance\n// ^\n// ^ term in radix tree, rows are added and removed as needed\n\nconst recurse = <T = any>(\n node: RadixTree<T>,\n query: string,\n maxDistance: number,\n results: FuzzyResults<T>,\n matrix: Uint8Array,\n m: number,\n n: number,\n prefix: string\n): void => {\n const offset = m * n\n\n key: for (const key of node.keys()) {\n if (key === LEAF) {\n // We've reached a leaf node. Check if the edit distance acceptable and\n // store the result if it is.\n const distance = matrix[offset - 1]\n if (distance <= maxDistance) {\n results.set(prefix, [node.get(key)!, distance])\n }\n } else {\n // Iterate over all characters in the key. Update the Levenshtein matrix\n // and check if the minimum distance in the last row is still within the\n // maximum edit distance. If it is, we can recurse over all child nodes.\n let i = m\n for (let pos = 0; pos < key.length; ++pos, ++i) {\n const char = key[pos]\n const thisRowOffset = n * i\n const prevRowOffset = thisRowOffset - n\n\n // Set the first column based on the previous row, and initialize the\n // minimum distance in the current row.\n let minDistance = matrix[thisRowOffset]\n\n const jmin = Math.max(0, i - maxDistance - 1)\n const jmax = Math.min(n - 1, i + maxDistance)\n\n // Iterate over remaining columns (characters in the query).\n for (let j = jmin; j < jmax; ++j) {\n const different = char !== query[j]\n\n // It might make sense to only read the matrix positions used for\n // deletion/insertion if the characters are different. But we want to\n // avoid conditional reads for performance reasons.\n const rpl = matrix[prevRowOffset + j] + +different\n const del = matrix[prevRowOffset + j + 1] + 1\n const ins = matrix[thisRowOffset + j] + 1\n\n const dist = matrix[thisRowOffset + j + 1] = Math.min(rpl, del, ins)\n\n if (dist < minDistance) minDistance = dist\n }\n\n // Because distance will never decrease, we can stop. There will be no\n // matching child nodes.\n if (minDistance > maxDistance) {\n continue key\n }\n }\n\n recurse(\n node.get(key)!,\n query,\n maxDistance,\n results,\n matrix,\n i,\n n,\n prefix + key\n )\n }\n }\n}\n\nexport default fuzzySearch\n","/* eslint-disable no-labels */\nimport { TreeIterator, ENTRIES, KEYS, VALUES, LEAF } from './TreeIterator'\nimport fuzzySearch, { type FuzzyResults } from './fuzzySearch'\nimport type { RadixTree, Entry, Path } from './types'\n\n/**\n * A class implementing the same interface as a standard JavaScript\n * [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)\n * with string keys, but adding support for efficiently searching entries with\n * prefix or fuzzy search. This class is used internally by {@link MiniSearch}\n * as the inverted index data structure. The implementation is a radix tree\n * (compressed prefix tree).\n *\n * Since this class can be of general utility beyond _MiniSearch_, it is\n * exported by the `minisearch` package and can be imported (or required) as\n * `minisearch/SearchableMap`.\n *\n * @typeParam T The type of the values stored in the map.\n */\nexport default class SearchableMap<T = any> {\n /**\n * @internal\n */\n _tree: RadixTree<T>\n\n /**\n * @internal\n */\n _prefix: string\n\n private _size: number | undefined = undefined\n\n /**\n * The constructor is normally called without arguments, creating an empty\n * map. In order to create a {@link SearchableMap} from an iterable or from an\n * object, check {@link SearchableMap.from} and {@link\n * SearchableMap.fromObject}.\n *\n * The constructor arguments are for internal use, when creating derived\n * mutable views of a map at a prefix.\n */\n constructor (tree: RadixTree<T> = new Map(), prefix = '') {\n this._tree = tree\n this._prefix = prefix\n }\n\n /**\n * Creates and returns a mutable view of this {@link SearchableMap},\n * containing only entries that share the given prefix.\n *\n * ### Usage:\n *\n * ```javascript\n * let map = new SearchableMap()\n * map.set(\"unicorn\", 1)\n * map.set(\"universe\", 2)\n * map.set(\"university\", 3)\n * map.set(\"unique\", 4)\n * map.set(\"hello\", 5)\n *\n * let uni = map.atPrefix(\"uni\")\n * uni.get(\"unique\") // => 4\n * uni.get(\"unicorn\") // => 1\n * uni.get(\"hello\") // => undefined\n *\n * let univer = map.atPrefix(\"univer\")\n * univer.get(\"unique\") // => undefined\n * univer.get(\"universe\") // => 2\n * univer.get(\"university\") // => 3\n * ```\n *\n * @param prefix The prefix\n * @return A {@link SearchableMap} representing a mutable view of the original\n * Map at the given prefix\n */\n atPrefix (prefix: string): SearchableMap<T> {\n if (!prefix.startsWith(this._prefix)) { throw new Error('Mismatched prefix') }\n\n const [node, path] = trackDown(this._tree, prefix.slice(this._prefix.length))\n\n if (node === undefined) {\n const [parentNode, key] = last(path)\n\n for (const k of parentNode!.keys()) {\n if (k !== LEAF && k.startsWith(key)) {\n const node = new Map()\n node.set(k.slice(key.length), parentNode!.get(k)!)\n return new SearchableMap(node, prefix)\n }\n }\n }\n\n return new SearchableMap<T>(node, prefix)\n }\n\n /**\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/clear\n */\n clear (): void {\n this._size = undefined\n this._tree.clear()\n }\n\n /**\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/delete\n * @param key Key to delete\n */\n delete (key: string): void {\n this._size = undefined\n return remove(this._tree, key)\n }\n\n /**\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/entries\n * @return An iterator iterating through `[key, value]` entries.\n */\n entries () {\n return new TreeIterator(this, ENTRIES)\n }\n\n /**\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/forEach\n * @param fn Iteration function\n */\n forEach (fn: (key: string, value: T, map: SearchableMap) => void): void {\n for (const [key, value] of this) {\n fn(key, value, this)\n }\n }\n\n /**\n * Returns a Map of all the entries that have a key within the given edit\n * distance from the search key. The keys of the returned Map are the matching\n * keys, while the values are two-element arrays where the first element is\n * the value associated to the key, and the second is the edit distance of the\n * key to the search key.\n *\n * ### Usage:\n *\n * ```javascript\n * let map = new SearchableMap()\n * map.set('hello', 'world')\n * map.set('hell', 'yeah')\n * map.set('ciao', 'mondo')\n *\n * // Get all entries that match the key 'hallo' with a maximum edit distance of 2\n * map.fuzzyGet('hallo', 2)\n * // => Map(2) { 'hello' => ['world', 1], 'hell' => ['yeah', 2] }\n *\n * // In the example, the \"hello\" key has value \"world\" and edit distance of 1\n * // (change \"e\" to \"a\"), the key \"hell\" has value \"yeah\" and edit distance of 2\n * // (change \"e\" to \"a\", delete \"o\")\n * ```\n *\n * @param key The search key\n * @param maxEditDistance The maximum edit distance (Levenshtein)\n * @return A Map of the matching keys to their value and edit distance\n */\n fuzzyGet (key: string, maxEditDistance: number): FuzzyResults<T> {\n return fuzzySearch<T>(this._tree, key, maxEditDistance)\n }\n\n /**\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get\n * @param key Key to get\n * @return Value associated to the key, or `undefined` if the key is not\n * found.\n */\n get (key: string): T | undefined {\n const node = lookup<T>(this._tree, key)\n return node !== undefined ? node.get(LEAF) : undefined\n }\n\n /**\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/has\n * @param key Key\n * @return True if the key is in the map, false otherwise\n */\n has (key: string): boolean {\n const node = lookup(this._tree, key)\n return node !== undefined && node.has(LEAF)\n }\n\n /**\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/keys\n * @return An `Iterable` iterating through keys\n */\n keys () {\n return new TreeIterator(this, KEYS)\n }\n\n /**\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/set\n * @param key Key to set\n * @param value Value to associate to the key\n * @return The {@link SearchableMap} itself, to allow chaining\n */\n set (key: string, value: T): SearchableMap<T> {\n if (typeof key !== 'string') { throw new Error('key must be a string') }\n this._size = undefined\n const node = createPath(this._tree, key)\n node.set(LEAF, value)\n return this\n }\n\n /**\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/size\n */\n get size (): number {\n if (this._size) { return this._size }\n /** @ignore */\n this._size = 0\n\n const iter = this.entries()\n while (!iter.next().done) this._size! += 1\n\n return this._size\n }\n\n /**\n * Updates the value at the given key using the provided function. The function\n * is called with the current value at the key, and its return value is used as\n * the new value to be set.\n *\n * ### Example:\n *\n * ```javascript\n * // Increment the current value by one\n * searchableMap.update('somekey', (currentValue) => currentValue == null ? 0 : currentValue + 1)\n * ```\n *\n * If the value at the given key is or will be an object, it might not require\n * re-assignment. In that case it is better to use `fetch()`, because it is\n * faster.\n *\n * @param key The key to update\n * @param fn The function used to compute the new value from the current one\n * @return The {@link SearchableMap} itself, to allow chaining\n */\n update (key: string, fn: (value: T | undefined) => T): SearchableMap<T> {\n if (typeof key !== 'string') { throw new Error('key must be a string') }\n this._size = undefined\n const node = createPath(this._tree, key)\n node.set(LEAF, fn(node.get(LEAF)))\n return this\n }\n\n /**\n * Fetches the value of the given key. If the value does not exist, calls the\n * given function to create a new value, which is inserted at the given key\n * and subsequently returned.\n *\n * ### Example:\n *\n * ```javascript\n * const map = searchableMap.fetch('somekey', () => new Map())\n * map.set('foo', 'bar')\n * ```\n *\n * @param key The key to update\n * @param initial A function that creates a new value if the key does not exist\n * @return The existing or new value at the given key\n */\n fetch (key: string, initial: () => T): T {\n if (typeof key !== 'string') { throw new Error('key must be a string') }\n this._size = undefined\n const node = createPath(this._tree, key)\n\n let value = node.get(LEAF)\n if (value === undefined) {\n node.set(LEAF, value = initial())\n }\n\n return value\n }\n\n /**\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/values\n * @return An `Iterable` iterating through values.\n */\n values () {\n return new TreeIterator(this, VALUES)\n }\n\n /**\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/@@iterator\n */\n [Symbol.iterator] () {\n return this.entries()\n }\n\n /**\n * Creates a {@link SearchableMap} from an `Iterable` of entries\n *\n * @param entries Entries to be inserted in the {@link SearchableMap}\n * @return A new {@link SearchableMap} with the given entries\n */\n static from<T = any> (entries: Iterable<Entry<T>> | Entry<T>[]) {\n const tree = new SearchableMap()\n for (const [key, value] of entries) {\n tree.set(key, value)\n }\n return tree\n }\n\n /**\n * Creates a {@link SearchableMap} from the iterable properties of a JavaScript object\n *\n * @param object Object of entries for the {@link SearchableMap}\n * @return A new {@link SearchableMap} with the given entries\n */\n static fromObject<T = any> (object: { [key: string]: T }) {\n return SearchableMap.from<T>(Object.entries(object))\n }\n}\n\nconst trackDown = <T = any>(tree: RadixTree<T> | undefined, key: string, path: Path<T> = []): [RadixTree<T> | undefined, Path<T>] => {\n if (key.length === 0 || tree == null) { return [tree, path] }\n\n for (const k of tree.keys()) {\n if (k !== LEAF && key.startsWith(k)) {\n path.push([tree, k]) // performance: update in place\n return trackDown(tree.get(k)!, key.slice(k.length), path)\n }\n }\n\n path.push([tree, key]) // performance: update in place\n return trackDown(undefined, '', path)\n}\n\nconst lookup = <T = any>(tree: RadixTree<T>, key: string): RadixTree<T> | undefined => {\n if (key.length === 0 || tree == null) { return tree }\n\n for (const k of tree.keys()) {\n if (k !== LEAF && key.startsWith(k)) {\n return lookup(tree.get(k)!, key.slice(k.length))\n }\n }\n}\n\n// Create a path in the radix tree for the given key, and returns the deepest\n// node. This function is in the hot path for indexing. It avoids unnecessary\n// string operations and recursion for performance.\nconst createPath = <T = any>(node: RadixTree<T>, key: string): RadixTree<T> => {\n const keyLength = key.length\n\n outer: for (let pos = 0; node && pos < keyLength;) {\n for (const k of node.keys()) {\n // Check whether this key is a candidate: the first characters must match.\n if (k !== LEAF && key[pos] === k[0]) {\n const len = Math.min(keyLength - pos, k.length)\n\n // Advance offset to the point where key and k no longer match.\n let offset = 1\n while (offset < len && key[pos + offset] === k[offset]) ++offset\n\n const child = node.get(k)!\n if (offset === k.length) {\n // The existing key is shorter than the key we need to create.\n node = child\n } else {\n // Partial match: we need to insert an intermediate node to contain\n // both the existing subtree and the new node.\n const intermediate = new Map()\n intermediate.set(k.slice(offset), child)\n node.set(key.slice(pos, pos + offset), intermediate)\n node.delete(k)\n node = intermediate\n }\n\n pos += offset\n continue outer\n }\n }\n\n // Create a final child node to contain the final suffix of the key.\n const child = new Map()\n node.set(key.slice(pos), child)\n return child\n }\n\n return node\n}\n\nconst remove = <T = any>(tree: RadixTree<T>, key: string): void => {\n const [node, path] = trackDown(tree, key)\n if (node === undefined) { return }\n node.delete(LEAF)\n\n if (node.size === 0) {\n cleanup(path)\n } else if (node.size === 1) {\n const [key, value] = node.entries().next().value!\n merge(path, key as string, value as RadixTree<T>)\n }\n}\n\nconst cleanup = <T = any>(path: Path<T>): void => {\n if (path.length === 0) { return }\n\n const [node, key] = last(path)\n node!.delete(key)\n\n if (node!.size === 0) {\n cleanup(path.slice(0, -1))\n } else if (node!.size === 1) {\n const [key, value] = node!.entries().next().value!\n if (key !== LEAF) {\n merge(path.slice(0, -1), key as string, value as RadixTree<T>)\n }\n }\n}\n\nconst merge = <T = any>(path: Path<T>, key: string, value: RadixTree<T>): void => {\n if (path.length === 0) { return }\n\n const [node, nodeKey] = last(path)\n node!.set(nodeKey + key, value)\n node!.delete(nodeKey)\n}\n\nconst last = <T = any>(array: T[]): T => {\n return array[array.length - 1]\n}\n","import SearchableMap from './SearchableMap/SearchableMap'\n\nexport type LowercaseCombinationOperator = 'or' | 'and' | 'and_not'\nexport type CombinationOperator = LowercaseCombinationOperator | Uppercase<LowercaseCombinationOperator> | Capitalize<LowercaseCombinationOperator>\n\nconst OR: LowercaseCombinationOperator = 'or'\nconst AND: LowercaseCombinationOperator = 'and'\nconst AND_NOT: LowercaseCombinationOperator = 'and_not'\n\n/**\n * Search options to customize the search behavior.\n */\nexport type SearchOptions = {\n /**\n * Names of the fields to search in. If omitted, all fields are searched.\n */\n fields?: string[],\n\n /**\n * Function used to filter search results, for example on the basis of stored\n * fields. It takes as argument each search result and should return a boolean\n * to indicate if the result should be kept or not.\n */\n filter?: (result: SearchResult) => boolean,\n\n /**\n * Key-value object of field names to boosting values. By default, fields are\n * assigned a boosting factor of 1. If one assigns to a field a boosting value\n * of 2, a result that matches the query in that field is assigned a score\n * twice as high as a result matching the query in another field, all else\n * being equal.\n */\n boost?: { [fieldName: string]: number },\n\n /**\n * Function to calculate a boost factor for each term.\n *\n * This function, if provided, is called for each query term (as split by\n * `tokenize` and processed by `processTerm`). The arguments passed to the\n * function are the query term, the positional index of the term in the query,\n * and the array of all query terms. It is expected to return a numeric boost\n * factor for the term. A factor lower than 1 reduces the importance of the\n * term, a factor greater than 1 increases it. A factor of exactly 1 is\n * neutral, and does not affect the term's importance.\n */\n boostTerm?: (term: string, i: number, terms: string[]) => number,\n\n /**\n * Relative weights to assign to prefix search results and fuzzy search\n * results. Exact matches are assigned a weight of 1.\n */\n weights?: { fuzzy: number, prefix: number },\n\n /**\n * Function to calculate a boost factor for documents. It takes as arguments\n * the document ID, and a term that matches the search in that document, and\n * the value of the stored fields for the document (if any). It should return\n * a boosting factor: a number higher than 1 increases the computed score, a\n * number lower than 1 decreases the score, and a falsy value skips the search\n * result completely.\n */\n boostDocument?: (documentId: any, term: string, storedFields?: Record<string, unknown>) => number,\n\n /**\n * Controls whether to perform prefix search. It can be a simple boolean, or a\n * function.\n *\n * If a boolean is passed, prefix search is performed if true.\n *\n * If a function is passed, it is called upon search with a search term, the\n * positional index of that search term in the tokenized search query, and the\n * tokenized search query. The function should return a boolean to indicate\n * whether to perform prefix search for that search term.\n */\n prefix?: boolean | ((term: string, index: number, terms: string[]) => boolean),\n\n /**\n * Controls whether to perform fuzzy search. It can be a simple boolean, or a\n * number, or a function.\n *\n * If a boolean is given, fuzzy search with a default fuzziness parameter is\n * performed if true.\n *\n * If a number higher or equal to 1 is given, fuzzy search is performed, with\n * a maximum edit distance (Levenshtein) equal to the number.\n *\n * If a number between 0 and 1 is given, fuzzy search is performed within a\n * maximum edit distance corresponding to that fraction of the term length,\n * approximated to the nearest integer. For example, 0.2 would mean an edit\n * distance of 20% of the term length, so 1 character in a 5-characters term.\n * The calculated fuzziness value is limited by the `maxFuzzy` option, to\n * prevent slowdown for very long queries.\n *\n * If a function is passed, the function is called upon search with a search\n * term, a positional index of that term in the tokenized search query, and\n * the tokenized search query. It should return a boolean or a number, with\n * the meaning documented above.\n */\n fuzzy?: boolean | number | ((term: string, index: number, terms: string[]) => boolean | number),\n\n /**\n * Controls the maximum fuzziness when using a fractional fuzzy value. This is\n * set to 6 by default. Very high edit distances usually don't produce\n * meaningful results, but can excessively impact search performance.\n */\n maxFuzzy?: number,\n\n /**\n * The operand to combine partial results for each term. By default it is\n * \"OR\", so results matching _any_ of the search terms are returned by a\n * search. If \"AND\" is given, only results matching _all_ the search terms are\n * returned by a search.\n */\n combineWith?: CombinationOperator,\n\n /**\n * Function to tokenize the search query. By default, the same tokenizer used\n * for indexing is used also for search.\n *\n * @remarks This function is called after `extractField` extracts a truthy\n * value from a field. This function is then expected to split the extracted\n * `text` document into tokens (more commonly referred to as \"terms\" in this\n * context). The resulting split might be simple, like for example on word\n * boundaries, or it might be more complex, taking into account certain\n * encoding, or parsing needs, or even just special cases. Think about how one\n * might need to go about indexing the term \"short-term\". You would likely\n * want to treat this case specially, and return two terms instead, `[\n * \"short\", \"term\" ]`.\n *\n * Or, you could let such a case be handled by the `processTerm` function,\n * which is designed to turn each token/term into whole terms or sub-terms. In\n * any case, the purpose of this function is to split apart the provided\n * `text` document into parts that can be processed by the `processTerm`\n * function.\n */\n tokenize?: (text: string) => string[],\n\n /**\n * Function to process or normalize terms in the search query. By default, the\n * same term processor used for indexing is used also for search.\n *\n * @remarks\n * During the document indexing phase, the first step is to call the\n * `extractField` function to fetch the requested value/field from the\n * document. This is then passed off to the `tokenize` function, which will\n * break apart each value into \"terms\". These terms are then individually\n * passed through this function to compute each term individually. A term\n * might for example be something like \"lbs\", in which case one would likely\n * want to return `[ \"lbs\", \"lb\", \"pound\", \"pounds\" ]`. You may also return\n * just a single string, or a falsy value if you would like to skip indexing\n * entirely for a specific term.\n *\n * Truthy return value(s) are then fed to the indexer as positive matches for\n * this document. In our example above, all four of the `[ \"lbs\", \"lb\",\n * \"pound\", \"pounds\" ]` terms would be added to the indexing engine, matching\n * against the current document being computed.\n *\n * *Note: Whatever values are returned from this function will receive no\n * further processing before being indexed. This means for example, if you\n * include whitespace at the beginning or end of a word, it will also be\n * indexed that way, with the included whitespace.*\n */\n processTerm?: (term: string) => string | string[] | null | undefined | false\n\n /**\n * BM25+ algorithm parameters. Customizing these is almost never necessary,\n * and finetuning them requires an understanding of the BM25 scoring model. In\n * most cases, it is best to omit this option to use defaults, and instead use\n * boosting to tweak scoring for specific use cases.\n */\n bm25?: BM25Params\n}\n\ntype SearchOptionsWithDefaults = SearchOptions & {\n boost: { [fieldName: string]: number },\n\n weights: { fuzzy: number, prefix: number },\n\n prefix: boolean | ((term: string, index: number, terms: string[]) => boolean),\n\n fuzzy: boolean | number | ((term: string, index: number, terms: string[]) => boolean | number),\n\n maxFuzzy: number,\n\n combineWith: CombinationOperator\n\n bm25: BM25Params\n}\n\n/**\n * Configuration options passed to the {@link MiniSearch} constructor\n *\n * @typeParam T The type of documents being indexed.\n */\nexport type Options<T = any> = {\n /**\n * Names of the document fields to be indexed.\n */\n fields: string[],\n\n /**\n * Name of the ID field, uniquely identifying a document.\n */\n idField?: string,\n\n /**\n * Names of fields to store, so that search results would include them. By\n * default none, so results would only contain the id field.\n */\n storeFields?: string[],\n\n /**\n * Function used to extract the value of each field in documents. By default,\n * the documents are assumed to be plain objects with field names as keys,\n * but by specifying a custom `extractField` function one can completely\n * customize how the fields are extracted.\n *\n * The function takes as arguments the document, and the name of the field to\n * extract from it. It should return the field value as a string.\n *\n * @remarks\n * The returned string is fed into the `tokenize` function to split it up\n * into tokens.\n */\n extractField?: (document: T, fieldName: string) => any,\n\n /**\n * Function used to turn field values into strings for indexing\n *\n * The function takes as arguments the field value, and the name of the field\n * to stringify, so that its logic can be customized on specific fields. By\n * default, it simply calls `toString()` on the field value (which in many\n * cases is already a string).\n *\n * ### Example:\n *\n * ```javascript\n * // Custom stringifier that formats dates as \"Tuesday, September 16, 2025\"\n * const miniSearch = new MiniSearch({\n * fields: ['title', 'date'],\n * stringifyField: ((fieldValue, _fieldName) => {\n * if (fieldValue instanceof Date) {\n * return fieldValue.toLocaleDateString('en-US', {\n * weekday: 'long',\n * year: 'numeric',\n * month: 'long',\n * day: 'numeric'\n * })\n * } else {\n * return fieldValue.toString()\n * }\n * }\n * })\n * ```\n */\n stringifyField?: (fieldValue: any, fieldName: string) => string,\n\n /**\n * Function used to split a field value into individual terms to be indexed.\n * The default tokenizer separates terms by space or punctuation, but a\n * custom tokenizer can be provided for custom logic.\n *\n * The function takes as arguments string to tokenize, and the name of the\n * field it comes from. It should return the terms as an array of strings.\n * When used for tokenizing a search query instead of a document field, the\n * `fieldName` is undefined.\n *\n * @remarks\n * This function is called after `extractField` extracts a truthy value from a\n * field. This function is then expected to split the extracted `text` document\n * into tokens (more commonly referred to as \"terms\" in this context). The resulting\n * split might be simple, like for example on word boundaries, or it might be more\n * complex, taking into account certain encoding, or parsing needs, or even just\n * special cases. Think about how one might need to go about indexing the term\n * \"short-term\". You would likely want to treat this case specially, and return two\n * terms instead, `[ \"short\", \"term\" ]`.\n *\n * Or, you could let such a case be handled by the `processTerm` function,\n * which is designed to turn each token/term into whole terms or sub-terms. In any\n * case, the purpose of this function is to split apart the provided `text` document\n * into parts that can be processed by the `processTerm` function.\n */\n tokenize?: (text: string, fieldName?: string) => string[],\n\n /**\n * Function used to process a term before indexing or search. This can be\n * used for normalization (such as stemming). By default, terms are\n * downcased, and otherwise no other normalization is performed.\n *\n * The function takes as arguments a term to process, and the name of the\n * field it comes from. It should return the processed term as a string, or a\n * falsy value to reject the term entirely.\n *\n * It can also return an array of strings, in which case each string in the\n * returned array is indexed as a separate term.\n *\n * @remarks\n * During the document indexing phase, the first step is to call the `extractField`\n * function to fetch the requested value/field from the document. This is then\n * passed off to the `tokenizer`, which will break apart each value into \"terms\".\n * These terms are then individually passed through the `processTerm` function\n * to compute each term individually. A term might for example be something\n * like \"lbs\", in which case one would likely want to return\n * `[ \"lbs\", \"lb\", \"pound\", \"pounds\" ]`. You may also return a single string value,\n * or a falsy value if you would like to skip indexing entirely for a specific term.\n *\n * Truthy return value(s) are then fed to the indexer as positive matches for this\n * document. In our example above, all four of the `[ \"lbs\", \"lb\", \"pound\", \"pounds\" ]`\n * terms would be added to the indexing engine, matching against the current document\n * being computed.\n *\n * *Note: Whatever values are returned from this function will receive no further\n * processing before being indexed. This means for example, if you include whitespace\n * at the beginning or end of a word, it will also be indexed that way, with the\n * included whitespace.*\n */\n processTerm?: (term: string, fieldName?: string) => string | string[] | null | undefined | false,\n\n /**\n * Function called to log messages. Arguments are a log level ('debug',\n * 'info', 'warn', or 'error'), a log message, and an optional string code\n * that identifies the reason for the log.\n *\n * The default implementation uses `console`, if defined.\n */\n logger?: (level: LogLevel, message: string, code?: string) => void\n\n /**\n * If `true` (the default), vacuuming is performed automatically as soon as\n * {@link MiniSearch#discard} is called a certain number of times, cleaning up\n * obsolete references from the index. If `false`, no automatic vacuuming is\n * performed. Custom settings controlling auto vacuuming thresholds, as well\n * as batching behavior, can be passed as an object (see the {@link\n * AutoVacuumOptions} type).\n */\n autoVacuum?: boolean | AutoVacuumOptions\n\n /**\n * Default search options (see the {@link SearchOptions} type and the {@link\n * MiniSearch#search} method for details)\n */\n searchOptions?: SearchOptions,\n\n /**\n * Default auto suggest options (see the {@link SearchOptions} type and the\n * {@link MiniSearch#autoSuggest} method for details)\n */\n autoSuggestOptions?: SearchOptions\n}\n\ntype OptionsWithDefaults<T = any> = Options<T> & {\n storeFields: string[]\n\n idField: string\n\n extractField: (document: T, fieldName: string) => any\n\n stringifyField: (fieldValue: any, fieldName: string) => string\n\n tokenize: (text: string, fieldName: string) => string[]\n\n processTerm: (term: string, fieldName: string) => string | string[] | null | undefined | false\n\n logger: (level: LogLevel, message: string, code?: string) => void\n\n autoVacuum: false | AutoVacuumOptions\n\n searchOptions: SearchOptionsWithDefaults\n\n autoSuggestOptions: SearchOptions\n}\n\ntype LogLevel = 'debug' | 'info' | 'warn' | 'error'\n\n/**\n * The type of auto-suggestions\n */\nexport type Suggestion = {\n /**\n * The suggestion\n */\n suggestion: string,\n\n /**\n * Suggestion as an array of terms\n */\n terms: string[],\n\n /**\n * Score for the suggestion\n */\n score: number\n}\n\n/**\n * Match information for a search result. It is a key-value object where keys\n * are terms that matched, and values are the list of fields that the term was\n * found in.\n */\nexport type MatchInfo = {\n [term: string]: string[]\n}\n\n/**\n * Type of the search results. Each search result indicates the document ID, the\n * terms that matched, the match information, the score, and all the stored\n * fields.\n */\nexport type SearchResult = {\n /**\n * The document ID\n */\n id: any,\n\n /**\n * List of document terms that matched. For example, if a prefix search for\n * `\"moto\"` matches `\"motorcycle\"`, `terms` will contain `\"motorcycle\"`.\n */\n terms: string[],\n\n /**\n * List of query terms that matched. For example, if a prefix search for\n * `\"moto\"` matches `\"motorcycle\"`, `queryTerms` will contain `\"moto\"`.\n */\n queryTerms: string[],\n\n /**\n * Score of the search results\n */\n score: number,\n\n /**\n * Match information, see {@link MatchInfo}\n */\n match: MatchInfo,\n\n /**\n * Stored fields\n */\n [key: string]: any\n}\n\n/**\n * @ignore\n */\nexport type AsPlainObject = {\n documentCount: number,\n nextId: number,\n documentIds: { [shortId: string]: any }\n fieldIds: { [fieldName: string]: number }\n fieldLength: { [shortId: string]: number[] }\n averageFieldLength: number[],\n storedFields: { [shortId: string]: any }\n dirtCount?: number,\n index: [string, { [fieldId: string]: SerializedIndexEntry }][]\n serializationVersion: number\n}\n\nexport type QueryCombination = SearchOptions & { queries: Query[] }\n\n/**\n * Wildcard query, used to match all terms\n */\nexport type Wildcard = typeof MiniSearch.wildcard\n\n/**\n * Search query expression, either a query string or an expression tree\n * combining several queries with a combination of AND or OR.\n */\nexport type Query = QueryCombination | string | Wildcard\n\n/**\n * Options to control vacuuming behavior.\n *\n * Vacuuming cleans up document references made obsolete by {@link\n * MiniSearch.discard} from the index. On large indexes, vacuuming is\n * potentially costly, because it has to traverse the whole inverted index.\n * Therefore, in order to dilute this cost so it does not negatively affects the\n * application, vacuuming is performed in batches, with a delay between each\n * batch. These options are used to configure the batch size and the delay\n * between batches.\n */\nexport type VacuumOptions = {\n /**\n * Size of each vacuuming batch (the number of terms in the index that will be\n * traversed in each batch). Defaults to 1000.\n */\n batchSize?: number,\n\n /**\n * Wait time between each vacuuming batch in milliseconds. Defaults to 10.\n */\n batchWait?: number\n}\n\n/**\n * Sets minimum thresholds for `dirtCount` and `dirtFactor` that trigger an\n * automatic vacuuming.\n */\nexport type VacuumConditions = {\n /**\n * Minimum `dirtCount` (number of discarded documents since the last vacuuming)\n * under which auto vacuum is not triggered. It defaults to 20.\n */\n minDirtCount?: number\n\n /**\n * Minimum `dirtFactor` (proportion of discarded documents over the total)\n * under which auto vacuum is not triggered. It defaults to 0.1.\n */\n minDirtFactor?: number,\n}\n\n/**\n * Options to control auto vacuum behavior. When discarding a document with\n * {@link MiniSearch#discard}, a vacuuming operation is automatically started if\n * the `dirtCount` and `dirtFactor` are above the `minDirtCount` and\n * `minDirtFactor` thresholds defined by this configuration. See {@link\n * VacuumConditions} for details on these.\n *\n * Also, `batchSize` and `batchWait` can be specified, controlling batching\n * behavior (see {@link VacuumOptions}).\n */\nexport type AutoVacuumOptions = VacuumOptions & VacuumConditions\n\ntype QuerySpec = {\n prefix: boolean,\n fuzzy: number | boolean,\n term: string,\n termBoost: number\n}\n\ntype DocumentTermFreqs = Map<number, number>\ntype FieldTermData = Map<number, DocumentTermFreqs>\n\ninterface RawResultValue {\n // Intermediate score, before applying the final score based on number of\n // matched terms.\n score: number,\n\n // Set of all query terms that were matched. They may not be present in the\n // text exactly in the case of prefix/fuzzy matches. We must check for\n // uniqueness before adding a new term. This is much faster than using a set,\n // because the number of elements is relatively small.\n terms: string[],\n\n // All terms that were found in the content, including the fields in which\n // they were present. This object will be provided as part of the final search\n // results.\n match: MatchInfo,\n}\n\ntype RawResult = Map<number, RawResultValue>\n\n/**\n * {@link MiniSearch} is the main entrypoint class, implementing a full-text\n * search engine in memory.\n *\n * @typeParam T The type of the documents being indexed.\n *\n * ### Basic example:\n *\n * ```javascript\n * const documents = [\n * {\n * id: 1,\n * title: 'Moby Dick',\n * text: 'Call me Ishmael. Some years ago...',\n * category: 'fiction'\n * },\n * {\n * id: 2,\n * title: 'Zen and the Art of Motorcycle Maintenance',\n * text: 'I can see by my watch...',\n * category: 'fiction'\n * },\n * {\n * id: 3,\n * title: 'Neuromancer',\n * text: 'The sky above the port was...',\n * category: 'fiction'\n * },\n * {\n * id: 4,\n * title: 'Zen and the Art of Archery',\n * text: 'At first sight it must seem...',\n * category: 'non-fiction'\n * },\n * // ...and more\n * ]\n *\n * // Create a search engine that indexes the 'title' and 'text' fields for\n * // full-text search. Search results will include 'title' and 'category' (plus the\n * // id field, that is always stored and returned)\n * const miniSearch = new MiniSearch({\n * fields: ['title', 'text'],\n * storeFields: ['title', 'category']\n * })\n *\n * // Add documents to the index\n * miniSearch.addAll(documents)\n *\n * // Search for documents:\n * let results = miniSearch.search('zen art motorcycle')\n * // => [\n * // { id: 2, title: 'Zen and the Art of Motorcycle Maintenance', category: 'fiction', score: 2.77258 },\n * // { id: 4, title: 'Zen and the Art of Archery', category: 'non-fiction', score: 1.38629 }\n * // ]\n * ```\n */\nexport default class MiniSearch<T = any> {\n protected _options: OptionsWithDefaults<T>\n protected _index: SearchableMap<FieldTermData>\n protected _documentCount: number\n protected _documentIds: Map<number, any>\n protected _idToShortId: Map<any, number>\n protected _fieldIds: { [key: string]: number }\n protected _fieldLength: Map<number, number[]>\n protected _avgFieldLength: number[]\n protected _nextId: number\n protected _storedFields: Map<number, Record<string, unknown>>\n protected _dirtCount: number\n private _currentVacuum: Promise<void> | null\n private _enqueuedVacuum: Promise<void> | null\n private _enqueuedVacuumConditions: VacuumConditions | undefined\n\n /**\n * The special wildcard symbol that can be passed to {@link MiniSearch#search}\n * to match all documents\n */\n static readonly wildcard: unique symbol = Symbol('*')\n\n /**\n * @param options Configuration options\n *\n * ### Examples:\n *\n * ```javascript\n * // Create a search engine that indexes the 'title' and 'text' fields of your\n * // documents:\n * const miniSearch = new MiniSearch({ fields: ['title', 'text'] })\n * ```\n *\n * ### ID Field:\n *\n * ```javascript\n * // Your documents are assumed to include a unique 'id' field, but if you want\n * // to use a different field for document identification, you can set the\n * // 'idField' option:\n * const miniSearch = new MiniSearch({ idField: 'key', fields: ['title', 'text'] })\n * ```\n *\n * ### Options and defaults:\n *\n * ```javascript\n * // The full set of options (here with their default value) is:\n * const miniSearch = new MiniSearch({\n * // idField: field that uniquely identifies a document\n * idField: 'id',\n *\n * // extractField: function used to get the value of a field in a document.\n * // By default, it assumes the document is a flat object with field names as\n * // property keys and field values as string property values, but custom logic\n * // can be implemented by setting this option to a custom extractor function.\n * extractField: (document, fieldName) => document[fieldName],\n *\n * // tokenize: function used to split fields into individual terms. By\n * // default, it is also used to tokenize search queries, unless a specific\n * // `tokenize` search option is supplied. When tokenizing an indexed field,\n * // the field name is passed as the second argument.\n * tokenize: (string, _fieldName) => string.split(SPACE_OR_PUNCTUATION),\n *\n * // processTerm: function used to process each tokenized term before\n * // indexing. It can be used for stemming and normalization. Return a falsy\n * // value in order to discard a term. By default, it is also used to process\n * // search queries, unless a specific `processTerm` option is supplied as a\n * // search option. When processing a term from a indexed field, the field\n * // name is passed as the second argument.\n * processTerm: (term, _fieldName) => term.toLowerCase(),\n *\n * // searchOptions: default search options, see the `search` method for\n * // details\n * searchOptions: undefined,\n *\n * // fields: document fields to be indexed. Mandatory, but not set by default\n * fields: undefined\n *\n * // storeFields: document fields to be stored and returned as part of the\n * // search results.\n * storeFields: []\n * })\n * ```\n */\n constructor (options: Options<T>) {\n if (options?.fields == null) {\n throw new Error('MiniSearch: option \"fields\" must be provided')\n }\n\n const autoVacuum = (options.autoVacuum == null || options.autoVacuum === true) ? defaultAutoVacuumOptions : options.autoVacuum\n\n this._options = {\n ...defaultOptions,\n ...options,\n autoVacuum,\n searchOptions: { ...defaultSearchOptions, ...(options.searchOptions || {}) },\n autoSuggestOptions: { ...defaultAutoSuggestOptions, ...(options.autoSuggestOptions || {}) }\n }\n\n this._index = new SearchableMap()\n\n this._documentCount = 0\n\n this._documentIds = new Map()\n\n this._idToShortId = new Map()\n\n // Fields are defined during initialization, don't change, are few in\n // number, rarely need iterating over, and have string keys. Therefore in\n // this case an object is a better candidate than a Map to store the mapping\n // from field key to ID.\n this._fieldIds = {}\n\n this._fieldLength = new Map()\n\n this._avgFieldLength = []\n\n this._nextId = 0\n\n this._storedFields = new Map()\n\n this._dirtCount = 0\n\n this._currentVacuum = null\n\n this._enqueuedVacuum = null\n this._enqueuedVacuumConditions = defaultVacuumConditions\n\n this.addFields(this._options.fields)\n }\n\n /**\n * Adds a document to the index\n *\n * @param document The document to be indexed\n */\n add (document: T): void {\n const { extractField, stringifyField, tokenize, processTerm, fields, idField } = this._options\n const id = extractField(document, idField)\n if (id == null) {\n throw new Error(`MiniSearch: document does not have ID field \"${idField}\"`)\n }\n\n if (this._idToShortId.has(id)) {\n throw new Error(`MiniSearch: duplicate ID ${id}`)\n }\n\n const shortDocumentId = this.addDocumentId(id)\n this.saveStoredFields(shortDocumentId, document)\n\n for (const field of fields) {\n const fieldValue = extractField(document, field)\n if (fieldValue == null) continue\n\n const tokens = tokenize(stringifyField(fieldValue, field), field)\n const fieldId = this._fieldIds[field]\n\n const uniqueTerms = new Set(tokens).size\n this.addFieldLength(shortDocumentId, fieldId, this._documentCount - 1, uniqueTerms)\n\n for (const term of tokens) {\n const processedTerm = processTerm(term, field)\n if (Array.isArray(processedTerm)) {\n for (const t of processedTerm) {\n this.addTerm(fieldId, shortDocumentId, t)\n }\n } else if (processedTerm) {\n this.addTerm(fieldId, shortDocumentId, processedTerm)\n }\n }\n }\n }\n\n /**\n * Adds all the given documents to the index\n *\n * @param documents An array of documents to be indexed\n */\n addAll (documents: readonly T[]): void {\n for (const document of documents) this.add(document)\n }\n\n /**\n * Adds all the given documents to the index asynchronously.\n *\n * Returns a promise that resolves (to `undefined`) when the indexing is done.\n * This method is useful when index many documents, to avoid blocking the main\n * thread. The indexing is performed asynchronously and in chunks.\n *\n * @param documents An array of documents to be indexed\n * @param options Configuration options\n * @return A promise resolving to `undefined` when the indexing is done\n */\n addAllAsync (documents: readonly T[], options: { chunkSize?: number } = {}): Promise<void> {\n const { chunkSize = 10 } = options\n const acc: { chunk: T[], promise: Promise<void> } = { chunk: [], promise: Promise.resolve() }\n\n const { chunk, promise } = documents.reduce(({ chunk, promise }, document: T, i: number) => {\n chunk.push(document)\n if ((i + 1) % chunkSize === 0) {\n return {\n chunk: [],\n promise: promise\n .then(() => new Promise(resolve => setTimeout(resolve, 0)))\n .then(() => this.addAll(chunk))\n }\n } else {\n return { chunk, promise }\n }\n }, acc)\n\n return promise.then(() => this.addAll(chunk))\n }\n\n /**\n * Removes the given document from the index.\n *\n * The document to remove must NOT have changed between indexing and removal,\n * otherwise the index will be corrupted.\n *\n * This method requires passing the full document to be removed (not just the\n * ID), and immediately removes the document from the inverted index, allowing\n * memory to be released. A convenient alternative is {@link\n * MiniSearch#discard}, which needs only the document ID, and has the same\n * visible effect, but delays cleaning up the index until the next vacuuming.\n *\n * @param document The document to be removed\n */\n remove (document: T): void {\n const { tokenize, processTerm, extractField, stringifyField, fields, idField } = this._options\n const id = extractField(document, idField)\n\n if (id == null) {\n throw new Error(`MiniSearch: document does not have ID field \"${idField}\"`)\n }\n\n const shortId = this._idToShortId.get(id)\n\n if (shortId == null) {\n throw new Error(`MiniSearch: cannot remove document with ID ${id}: it is not in the index`)\n }\n\n for (const field of fields) {\n const fieldValue = extractField(document, field)\n if (fieldValue == null) continue\n\n const tokens = tokenize(stringifyField(fieldValue, field), field)\n const fieldId = this._fieldIds[field]\n\n const uniqueTerms = new Set(tokens).size\n this.removeFieldLength(shortId, fieldId, this._documentCount, uniqueTerms)\n\n for (const term of tokens) {\n const processedTerm = processTerm(term, field)\n if (Array.isArray(processedTerm)) {\n for (const t of processedTerm) {\n this.removeTerm(fieldId, shortId, t)\n }\n } else if (processedTerm) {\n this.removeTerm(fieldId, shortId, processedTerm)\n }\n }\n }\n\n this._storedFields.delete(shortId)\n this._documentIds.delete(shortId)\n this._idToShortId.delete(id)\n this._fieldLength.delete(shortId)\n this._documentCount -= 1\n }\n\n /**\n * Removes all the given documents from the index. If called with no arguments,\n * it removes _all_ documents from the index.\n *\n * @param documents The documents to be removed. If this argument is omitted,\n * all documents are removed. Note that, for removing all documents, it is\n * more efficient to call this method with no arguments than to pass all\n * documents.\n */\n removeAll (documents?: readonly T[]): void {\n if (documents) {\n for (const document of documents) this.remove(document)\n } else if (arguments.length > 0) {\n throw new Error('Expected documents to be present. Omit the argument to remove all documents.')\n } else {\n this._index = new SearchableMap()\n this._documentCount = 0\n this._documentIds = new Map()\n this._idToShortId = new Map()\n this._fieldLength = new Map()\n this._avgFieldLength = []\n this._storedFields = new Map()\n this._nextId = 0\n }\n }\n\n /**\n * Discards the document with the given ID, so it won't appear in search results\n *\n * It has the same visible effect of {@link MiniSearch.remove} (both cause the\n * document to stop appearing in searches), but a different effect on the\n * internal data structures:\n *\n * - {@link MiniSearch#remove} requires passing the full document to be\n * removed as argument, and removes it from the inverted index immediately.\n *\n * - {@link MiniSearch#discard} instead only needs the document ID, and\n * works by marking the current version of the document as discarded, so it\n * is immediately ignored by searches. This is faster and more convenient\n * than {@link MiniSearch#remove}, but the index is not immediately\n * modified. To take care of that, vacuuming is performed after a certain\n * number of documents are discarded, cleaning up the index and allowing\n * memory to be released.\n *\n * After discarding a document, it is possible to re-add a new version, and\n * only the new version will appear in searches. In other words, discarding\n * and re-adding a document works exactly like removing and re-adding it. The\n * {@link MiniSearch.replace} method can also be used to replace a document\n * with a new version.\n *\n * #### Details about vacuuming\n *\n * Repetite calls to this method would leave obsolete document references in\n * the index, invisible to searches. Two mechanisms take care of cleaning up:\n * clean up during search, and vacuuming.\n *\n * - Upon search, whenever a discarded ID is found (and ignored for the\n * results), references to the discarded document are removed from the\n * inverted index entries for the search terms. This ensures that subsequent\n * searches for the same terms do not need to skip these obsolete references\n * again.\n *\n * - In addition, vacuuming is performed automatically by default (see the\n * `autoVacuum` field in {@link Options}) after a certain number of\n * documents are discarded. Vacuuming traverses all terms in the index,\n * cleaning up all references to discarded documents. Vacuuming can also be\n * triggered manually by calling {@link MiniSearch#vacuum}.\n *\n * @param id The ID of the document to be discarded\n */\n discard (id: any): void {\n const shortId = this._idToShortId.get(id)\n\n if (shortId == null) {\n throw new Error(`MiniSearch: cannot discard document with ID ${id}: it is not in the index`)\n }\n\n this._idToShortId.delete(id)\n this._documentIds.delete(shortId)\n this._storedFields.delete(shortId)\n\n ;(this._fieldLength.get(shortId) || []).forEach((fieldLength, fieldId) => {\n this.removeFieldLength(shortId, fieldId, this._documentCount, fieldLength)\n })\n\n this._fieldLength.delete(shortId)\n\n this._documentCount -= 1\n this._dirtCount += 1\n\n this.maybeAutoVacuum()\n }\n\n private maybeAutoVacuum (): void {\n if (this._options.autoVacuum === false) { return }\n\n const { minDirtFactor, minDirtCount, batchSize, batchWait } = this._options.autoVacuum\n this.conditionalVacuum({ batchSize, batchWait }, { minDirtCount, minDirtFactor })\n }\n\n /**\n * Discards the documents with the given IDs, so they won't appear in search\n * results\n *\n * It is equivalent to calling {@link MiniSearch#discard} for all the given\n * IDs, but with the optimization of triggering at most one automatic\n * vacuuming at the end.\n *\n * Note: to remove all documents from the index, it is faster and more\n * convenient to call {@link MiniSearch.removeAll} with no argument, instead\n * of passing all IDs to this method.\n */\n discardAll (ids: readonly any[]): void {\n const autoVacuum = this._options.autoVacuum\n\n try {\n this._options.autoVacuum = false\n\n for (const id of ids) {\n this.discard(id)\n }\n } finally {\n this._options.autoVacuum = autoVacuum\n }\n\n this.maybeAutoVacuum()\n }\n\n /**\n * It replaces an existing document with the given updated version\n *\n * It works by discarding the current version and adding the updated one, so\n * it is functionally equivalent to calling {@link MiniSearch#discard}\n * followed by {@link MiniSearch#add}. The ID of the updated document should\n * be the same as the original one.\n *\n * Since it uses {@link MiniSearch#discard} internally, this method relies on\n * vacuuming to clean up obsolete document references from the index, allowing\n * memory to be released (see {@link MiniSearch#discard}).\n *\n * @param updatedDocument The updated document to replace the old version\n * with\n */\n replace (updatedDocument: T): void {\n const { idField, extractField } = this._options\n const id = extractField(updatedDocument, idField)\n\n this.discard(id)\n this.add(updatedDocument)\n }\n\n /**\n * Triggers a manual vacuuming, cleaning up references to discarded documents\n * from the inverted index\n *\n * Vacuuming is only useful for applications that use the {@link\n * MiniSearch#discard} or {@link MiniSearch#replace} methods.\n *\n * By default, vacuuming is performed automatically when needed (controlled by\n * the `autoVacuum` field in {@link Options}), so there is usually no need to\n * call this method, unless one wants to make sure to perform vacuuming at a\n * specific moment.\n *\n * Vacuuming traverses all terms in the inverted index in batches, and cleans\n * up references to discarded documents from the posting list, allowing memory\n * to be released.\n *\n * The method takes an optional object as argument with the following keys:\n *\n * - `batchSize`: the size of each batch (1000 by default)\n *\n * - `batchWait`: the number of milliseconds to wait between batches (10 by\n * default)\n *\n * On large indexes, vacuuming could have a non-negligible cost: batching\n * avoids blocking the thread for long, diluting this cost so that it is not\n * negatively affecting the application. Nonetheless, this method should only\n * be called when necessary, and relying on automatic vacuuming is usually\n * better.\n *\n * It returns a promise that resolves (to undefined) when the clean up is\n * completed. If vacuuming is already ongoing at the time this method is\n * called, a new one is enqueued immediately after the ongoing one, and a\n * corresponding promise is returned. However, no more than one vacuuming is\n * enqueued on top of the ongoing one, even if this method is called more\n * times (enqueuing multiple ones would be useless).\n *\n * @param options Configuration options for the batch size and delay. See\n * {@link VacuumOptions}.\n */\n vacuum (options: VacuumOptions = {}): Promise<void> {\n return this.conditionalVacuum(options)\n }\n\n private conditionalVacuum (options: VacuumOptions, conditions?: VacuumConditions): Promise<void> {\n // If a vacuum is already ongoing, schedule another as soon as it finishes,\n // unless there's already one enqueued. If one was already enqueued, do not\n // enqueue another on top, but make sure that the conditions are the\n // broadest.\n if (this._currentVacuum) {\n this._enqueuedVacuumConditions = this._enqueuedVacuumConditions && conditions\n if (this._enqueuedVacuum != null) { return this._enqueuedVacuum }\n\n this._enqueuedVacuum = this._currentVacuum.then(() => {\n const conditions = this._enqueuedVacuumConditions\n this._enqueuedVacuumConditions = defaultVacuumConditions\n return this.performVacuuming(options, conditions)\n })\n return this._enqueuedVacuum\n }\n\n if (this.vacuumConditionsMet(conditions) === false) { return Promise.resolve() }\n\n this._currentVacuum = this.performVacuuming(options)\n return this._currentVacuum\n }\n\n private async performVacuuming (options: VacuumOptions, conditions?: VacuumConditions): Promise<void> {\n const initialDirtCount = this._dirtCount\n\n if (this.vacuumConditionsMet(conditions)) {\n const batchSize = options.batchSize || defaultVacuumOptions.batchSize\n const batchWait = options.batchWait || defaultVacuumOptions.batchWait\n let i = 1\n\n for (const [term, fieldsData] of this._index) {\n for (const [fieldId, fieldIndex] of fieldsData) {\n for (const [shortId] of fieldIndex) {\n if (this._documentIds.has(shortId)) { continue }\n\n if (fieldIndex.size <= 1) {\n fieldsData.delete(fieldId)\n } else {\n fieldIndex.delete(shortId)\n }\n }\n }\n\n if (this._index.get(term)!.size === 0) {\n this._index.delete(term)\n }\n\n if (i % batchSize === 0) {\n await new Promise((resolve) => setTimeout(resolve, batchWait))\n }\n\n i += 1\n }\n\n this._dirtCount -= initialDirtCount\n }\n\n // Make the next lines always async, so they execute after this function returns\n await null\n\n this._currentVacuum = this._enqueuedVacuum\n this._enqueuedVacuum = null\n }\n\n private vacuumConditionsMet (conditions?: VacuumConditions) {\n if (conditions == null) { return true }\n\n let { minDirtCount, minDirtFactor } = conditions\n minDirtCount = minDirtCount || defaultAutoVacuumOptions.minDirtCount\n minDirtFactor = minDirtFactor || defaultAutoVacuumOptions.minDirtFactor\n\n return this.dirtCount >= minDirtCount && this.dirtFactor >= minDirtFactor\n }\n\n /**\n * Is `true` if a vacuuming operation is ongoing, `false` otherwise\n */\n get isVacuuming (): boolean {\n return this._currentVacuum != null\n }\n\n /**\n * The number of documents discarded since the most recent vacuuming\n */\n get dirtCount (): number {\n return this._dirtCount\n }\n\n /**\n * A number between 0 and 1 giving an indication about the proportion of\n * documents that are discarded, and can therefore be cleaned up by vacuuming.\n * A value close to 0 means that the index is relatively clean, while a higher\n * value means that the index is relatively dirty, and vacuuming could release\n * memory.\n */\n get dirtFactor (): number {\n return this._dirtCount / (1 + this._documentCount + this._dirtCount)\n }\n\n /**\n * Returns `true` if a document with the given ID is present in the index and\n * available for search, `false` otherwise\n *\n * @param id The document ID\n */\n has (id: any): boolean {\n return this._idToShortId.has(id)\n }\n\n /**\n * Returns the stored fields (as configured in the `storeFields` constructor\n * option) for the given document ID. Returns `undefined` if the document is\n * not present in the index.\n *\n * @param id The document ID\n */\n getStoredFields (id: any): Record<string, unknown> | undefined {\n const shortId = this._idToShortId.get(id)\n\n if (shortId == null) { return undefined }\n\n return this._storedFields.get(shortId)\n }\n\n /**\n * Search for documents matching the given search query.\n *\n * The result is a list of scored document IDs matching the query, sorted by\n * descending score, and each including data about which terms were matched and\n * in which fields.\n *\n * ### Basic usage:\n *\n * ```javascript\n * // Search for \"zen art motorcycle\" with default options: terms have to match\n * // exactly, and individual terms are joined with OR\n * miniSearch.search('zen art motorcycle')\n * // => [ { id: 2, score: 2.77258, match: { ... } }, { id: 4, score: 1.38629, match: { ... } } ]\n * ```\n *\n * ### Restrict search to specific fields:\n *\n * ```javascript\n * // Search only in the 'title' field\n * miniSearch.search('zen', { fields: ['title'] })\n * ```\n *\n * ### Field boosting:\n *\n * ```javascript\n * // Boost a field\n * miniSearch.search('zen', { boost: { title: 2 } })\n * ```\n *\n * ### Prefix search:\n *\n * ```javascript\n * // Search for \"moto\" with prefix search (it will match documents\n * // containing terms that start with \"moto\" or \"neuro\")\n * miniSearch.search('moto neuro', { prefix: true })\n * ```\n *\n * ### Fuzzy search:\n *\n * ```javascript\n * // Search for \"ismael\" with fuzzy search (it will match documents containing\n * // terms similar to \"ismael\", with a maximum edit distance of 0.2 term.length\n * // (rounded to nearest integer)\n * miniSearch.search('ismael', { fuzzy: 0.2 })\n * ```\n *\n * ### Combining strategies:\n *\n * ```javascript\n * // Mix of exact match, prefix search, and fuzzy search\n * miniSearch.search('ismael mob', {\n * prefix: true,\n * fuzzy: 0.2\n * })\n * ```\n *\n * ### Advanced prefix and fuzzy search:\n *\n * ```javascript\n * // Perform fuzzy and prefix search depending on the search term. Here\n * // performing prefix and fuzzy search only on terms longer than 3 characters\n * miniSearch.search('ismael mob', {\n * prefix: term => term.length > 3\n * fuzzy: term => term.length > 3 ? 0.2 : null\n * })\n * ```\n *\n * ### Combine with AND:\n *\n * ```javascript\n * // Combine search terms with AND (to match only documents that contain both\n * // \"motorcycle\" and \"art\")\n * miniSearch.search('motorcycle art', { combineWith: 'AND' })\n * ```\n *\n * ### Combine with AND_NOT:\n *\n * There is also an AND_NOT combinator, that finds documents that match the\n * first term, but do not match any of the other terms. This combinator is\n * rarely useful with simple queries, and is meant to be used with advanced\n * query combinations (see later for more details).\n *\n * ### Filtering results:\n *\n * ```javascript\n * // Filter only results in the 'fiction' category (assuming that 'category'\n * // is a stored field)\n * miniSearch.search('motorcycle art', {\n * filter: (result) => result.category === 'fiction'\n * })\n * ```\n *\n * ### Wildcard query\n *\n * Searching for an empty string (assuming the default tokenizer) returns no\n * results. Sometimes though, one needs to match all documents, like in a\n * \"wildcard\" search. This is possible by passing the special value\n * {@link MiniSearch.wildcard} as the query:\n *\n * ```javascript\n * // Return search results for all documents\n * miniSearch.search(MiniSearch.wildcard)\n * ```\n *\n * Note that search options such as `filter` and `boostDocument` are still\n * applied, influencing which results are returned, and their order:\n *\n * ```javascript\n * // Return search results for all documents in the 'fiction' category\n * miniSearch.search(MiniSearch.wildcard, {\n * filter: (result) => result.category === 'fiction'\n * })\n * ```\n *\n * ### Advanced combination of queries:\n *\n * It is possible to combine different subqueries with OR, AND, and AND_NOT,\n * and even with different search options, by passing a query expression\n * tree object as the first argument, instead of a string.\n *\n * ```javascript\n * // Search for documents that contain \"zen\" and (\"motorcycle\" or \"archery\")\n * miniSearch.search({\n * combineWith: 'AND',\n * queries: [\n * 'zen',\n * {\n * combineWith: 'OR',\n * queries: ['motorcycle', 'archery']\n * }\n * ]\n * })\n *\n * // Search for documents that contain (\"apple\" or \"pear\") but not \"juice\" and\n * // not \"tree\"\n * miniSearch.search({\n * combineWith: 'AND_NOT',\n * queries: [\n * {\n * combineWith: 'OR',\n * queries: ['apple', 'pear']\n * },\n * 'juice',\n * 'tree'\n * ]\n * })\n * ```\n *\n * Each node in the expression tree can be either a string, or an object that\n * supports all {@link SearchOptions} fields, plus a `queries` array field for\n * subqueries.\n *\n * Note that, while this can become complicated to do by hand for complex or\n * deeply nested queries, it provides a formalized expression tree API for\n * external libraries that implement a parser for custom query languages.\n *\n * @param query Search query\n * @param searchOptions Search options. Each option, if not given, defaults to the corresponding value of `searchOptions` given to the constructor, or to the library default.\n */\n search (query: Query, searchOptions: SearchOptions = {}): SearchResult[] {\n const { searchOptions: globalSearchOptions } = this._options\n const searchOptionsWithDefaults: SearchOptionsWithDefaults = { ...globalSearchOptions, ...searchOptions }\n\n const rawResults = this.executeQuery(query, searchOptions)\n const results = []\n\n for (const [docId, { score, terms, match }] of rawResults) {\n // terms are the matched query terms, which will be returned to the user\n // as queryTerms. The quality is calculated based on them, as opposed to\n // the matched terms in the document (which can be different due to\n // prefix and fuzzy match)\n const quality = terms.length || 1\n\n const result = {\n id: this._documentIds.get(docId),\n score: score * quality,\n terms: Object.keys(match),\n queryTerms: terms,\n match\n }\n\n Object.assign(result, this._storedFields.get(docId))\n if (searchOptionsWithDefaults.filter == null || searchOptionsWithDefaults.filter(result)) {\n results.push(result)\n }\n }\n\n // If it's a wildcard query, and no document boost is applied, skip sorting\n // the results, as all results have the same score of 1\n if (query === MiniSearch.wildcard && searchOptionsWithDefaults.boostDocument == null) {\n return results\n }\n\n results.sort(byScore)\n return results\n }\n\n /**\n * Provide suggestions for the given search query\n *\n * The result is a list of suggested modified search queries, derived from the\n * given search query, each with a relevance score, sorted by descending score.\n *\n * By default, it uses the same options used for search, except that by\n * default it performs prefix search on the last term of the query, and\n * combine terms with `'AND'` (requiring all query terms to match). Custom\n * options can be passed as a second argument. Defaults can be changed upon\n * calling the {@link MiniSearch} constructor, by passing a\n * `autoSuggestOptions` option.\n *\n * ### Basic usage:\n *\n * ```javascript\n * // Get suggestions for 'neuro':\n * miniSearch.autoSuggest('neuro')\n * // => [ { suggestion: 'neuromancer', terms: [ 'neuromancer' ], score: 0.46240 } ]\n * ```\n *\n * ### Multiple words:\n *\n * ```javascript\n * // Get suggestions for 'zen ar':\n * miniSearch.autoSuggest('zen ar')\n * // => [\n * // { suggestion: 'zen archery art', terms: [ 'zen', 'archery', 'art' ], score: 1.73332 },\n * // { suggestion: 'zen art', terms: [ 'zen', 'art' ], score: 1.21313 }\n * // ]\n * ```\n *\n * ### Fuzzy suggestions:\n *\n * ```javascript\n * // Correct spelling mistakes using fuzzy search:\n * miniSearch.autoSuggest('neromancer', { fuzzy: 0.2 })\n * // => [ { suggestion: 'neuromancer', terms: [ 'neuromancer' ], score: 1.03998 } ]\n * ```\n *\n * ### Filtering:\n *\n * ```javascript\n * // Get suggestions for 'zen ar', but only within the 'fiction' category\n * // (assuming that 'category' is a stored field):\n * miniSearch.autoSuggest('zen ar', {\n * filter: (result) => result.category === 'fiction'\n * })\n * // => [\n * // { suggestion: 'zen archery art', terms: [ 'zen', 'archery', 'art' ], score: 1.73332 },\n * // { suggestion: 'zen art', terms: [ 'zen', 'art' ], score: 1.21313 }\n * // ]\n * ```\n *\n * @param queryString Query string to be expanded into suggestions\n * @param options Search options. The supported options and default values\n * are the same as for the {@link MiniSearch#search} method, except that by\n * default prefix search is performed on the last term in the query, and terms\n * are combined with `'AND'`.\n * @return A sorted array of suggestions sorted by relevance score.\n */\n autoSuggest (queryString: string, options: SearchOptions = {}): Suggestion[] {\n options = { ...this._options.autoSuggestOptions, ...options }\n\n const suggestions: Map<string, Omit<Suggestion, 'suggestion'> & { count: number }> = new Map()\n\n for (const { score, terms } of this.search(queryString, options)) {\n const phrase = terms.join(' ')\n const suggestion = suggestions.get(phrase)\n if (suggestion != null) {\n suggestion.score += score\n suggestion.count += 1\n } else {\n suggestions.set(phrase, { score, terms, count: 1 })\n }\n }\n\n const results = []\n for (const [suggestion, { score, terms, count }] of suggestions) {\n results.push({ suggestion, terms, score: score / count })\n }\n\n results.sort(byScore)\n return results\n }\n\n /**\n * Total number of documents available to search\n */\n get documentCount (): number {\n return this._documentCount\n }\n\n /**\n * Number of terms in the index\n */\n get termCount (): number {\n return this._index.size\n }\n\n /**\n * Deserializes a JSON index (serialized with `JSON.stringify(miniSearch)`)\n * and instantiates a MiniSearch instance. It should be given the same options\n * originally used when serializing the index.\n *\n * ### Usage:\n *\n * ```javascript\n * // If the index was serialized with:\n * let miniSearch = new MiniSearch({ fields: ['title', 'text'] })\n * miniSearch.addAll(documents)\n *\n * const json = JSON.stringify(miniSearch)\n * // It can later be deserialized like this:\n * miniSearch = MiniSearch.loadJSON(json, { fields: ['title', 'text'] })\n * ```\n *\n * @param json JSON-serialized index\n * @param options configuration options, same as the constructor\n * @return An instance of MiniSearch deserialized from the given JSON.\n */\n static loadJSON<T = any> (json: string, options: Options<T>): MiniSearch<T> {\n if (options == null) {\n throw new Error('MiniSearch: loadJSON should be given the same options used when serializing the index')\n }\n return this.loadJS(JSON.parse(json), options)\n }\n\n /**\n * Async equivalent of {@link MiniSearch.loadJSON}\n *\n * This function is an alternative to {@link MiniSearch.loadJSON} that returns\n * a promise, and loads the index in batches, leaving pauses between them to avoid\n * blocking the main thread. It tends to be slower than the synchronous\n * version, but does not block the main thread, so it can be a better choice\n * when deserializing very large indexes.\n *\n * @param json JSON-serialized index\n * @param options configuration options, same as the constructor\n * @return A Promise that will resolve to an instance of MiniSearch deserialized from the given JSON.\n */\n static async loadJSONAsync<T = any> (json: string, options: Options<T>): Promise<MiniSearch<T>> {\n if (options == null) {\n throw new Error('MiniSearch: loadJSON should be given the same options used when serializing the index')\n }\n return this.loadJSAsync(JSON.parse(json), options)\n }\n\n /**\n * Returns the default value of an option. It will throw an error if no option\n * with the given name exists.\n *\n * @param optionName Name of the option\n * @return The default value of the given option\n *\n * ### Usage:\n *\n * ```javascript\n * // Get default tokenizer\n * MiniSearch.getDefault('tokenize')\n *\n * // Get default term processor\n * MiniSearch.getDefault('processTerm')\n *\n * // Unknown options will throw an error\n * MiniSearch.getDefault('notExisting')\n * // => throws 'MiniSearch: unknown option \"notExisting\"'\n * ```\n */\n static getDefault (optionName: string): any {\n if (defaultOptions.hasOwnProperty(optionName)) {\n return getOwnProperty(defaultOptions, optionName)\n } else {\n throw new Error(`MiniSearch: unknown option \"${optionName}\"`)\n }\n }\n\n /**\n * @ignore\n */\n static loadJS<T = any> (js: AsPlainObject, options: Options<T>): MiniSearch<T> {\n const {\n index,\n documentIds,\n fieldLength,\n storedFields,\n serializationVersion\n } = js\n\n const miniSearch = this.instantiateMiniSearch(js, options)\n\n miniSearch._documentIds = objectToNumericMap(documentIds)\n miniSearch._fieldLength = objectToNumericMap(fieldLength)\n miniSearch._storedFields = objectToNumericMap(storedFields)\n\n for (const [shortId, id] of miniSearch._documentIds) {\n miniSearch._idToShortId.set(id, shortId)\n }\n\n for (const [term, data] of index) {\n const dataMap = new Map() as FieldTermData\n\n for (const fieldId of Object.keys(data)) {\n let indexEntry = data[fieldId]\n\n // Version 1 used to nest the index entry inside a field called ds\n if (serializationVersion === 1) {\n indexEntry = indexEntry.ds as unknown as SerializedIndexEntry\n }\n\n dataMap.set(parseInt(fieldId, 10), objectToNumericMap(indexEntry) as DocumentTermFreqs)\n }\n\n miniSearch._index.set(term, dataMap)\n }\n\n return miniSearch\n }\n\n /**\n * @ignore\n */\n static async loadJSAsync<T = any> (js: AsPlainObject, options: Options<T>): Promise<MiniSearch<T>> {\n const {\n index,\n documentIds,\n fieldLength,\n storedFields,\n serializationVersion\n } = js\n\n const miniSearch = this.instantiateMiniSearch(js, options)\n\n miniSearch._documentIds = await objectToNumericMapAsync(documentIds)\n miniSearch._fieldLength = await objectToNumericMapAsync(fieldLength)\n miniSearch._storedFields = await objectToNumericMapAsync(storedFields)\n\n for (const [shortId, id] of miniSearch._documentIds) {\n miniSearch._idToShortId.set(id, shortId)\n }\n\n let count = 0\n for (const [term, data] of index) {\n const dataMap = new Map() as FieldTermData\n\n for (const fieldId of Object.keys(data)) {\n let indexEntry = data[fieldId]\n\n // Version 1 used to nest the index entry inside a field called ds\n if (serializationVersion === 1) {\n indexEntry = indexEntry.ds as unknown as SerializedIndexEntry\n }\n\n dataMap.set(parseInt(fieldId, 10), await objectToNumericMapAsync(indexEntry) as DocumentTermFreqs)\n }\n\n if (++count % 1000 === 0) await wait(0)\n miniSearch._index.set(term, dataMap)\n }\n\n return miniSearch\n }\n\n /**\n * @ignore\n */\n private static instantiateMiniSearch<T = any> (js: AsPlainObject, options: Options<T>): MiniSearch<T> {\n const {\n documentCount,\n nextId,\n fieldIds,\n averageFieldLength,\n dirtCount,\n serializationVersion\n } = js\n\n if (serializationVersion !== 1 && serializationVersion !== 2) {\n throw new Error('MiniSearch: cannot deserialize an index created with an incompatible version')\n }\n\n const miniSearch = new MiniSearch(options)\n\n miniSearch._documentCount = documentCount\n miniSearch._nextId = nextId\n miniSearch._idToShortId = new Map<any, number>()\n miniSearch._fieldIds = fieldIds\n miniSearch._avgFieldLength = averageFieldLength\n miniSearch._dirtCount = dirtCount || 0\n miniSearch._index = new SearchableMap()\n\n return miniSearch\n }\n\n /**\n * @ignore\n */\n private executeQuery (query: Query, searchOptions: SearchOptions = {}): RawResult {\n if (query === MiniSearch.wildcard) {\n return this.executeWildcardQuery(searchOptions)\n }\n\n if (typeof query !== 'string') {\n const options = { ...searchOptions, ...query, queries: undefined }\n const results = query.queries.map((subquery) => this.executeQuery(subquery, options))\n return this.combineResults(results, options.combineWith)\n }\n\n const { tokenize, processTerm, searchOptions: globalSearchOptions } = this._options\n const options = { tokenize, processTerm, ...globalSearchOptions, ...searchOptions }\n const { tokenize: searchTokenize, processTerm: searchProcessTerm } = options\n const terms = searchTokenize(query)\n .flatMap((term: string) => searchProcessTerm(term))\n .filter((term) => !!term) as string[]\n const queries: QuerySpec[] = terms.map(termToQuerySpec(options))\n const results = queries.map(query => this.executeQuerySpec(query, options))\n\n return this.combineResults(results, options.combineWith)\n }\n\n /**\n * @ignore\n */\n private executeQuerySpec (query: QuerySpec, searchOptions: SearchOptions): RawResult {\n const options: SearchOptionsWithDefaults = { ...this._options.searchOptions, ...searchOptions }\n\n const boosts = (options.fields || this._options.fields).reduce((boosts, field) =>\n ({ ...boosts, [field]: getOwnProperty(options.boost, field) || 1 }), {})\n\n const {\n boostDocument,\n weights,\n maxFuzzy,\n bm25: bm25params\n } = options\n\n const { fuzzy: fuzzyWeight, prefix: prefixWeight } = { ...defaultSearchOptions.weights, ...weights }\n\n const data = this._index.get(query.term)\n const results = this.termResults(query.term, query.term, 1, query.termBoost, data, boosts, boostDocument, bm25params)\n\n let prefixMatches\n let fuzzyMatches\n\n if (query.prefix) {\n prefixMatches = this._index.atPrefix(query.term)\n }\n\n if (query.fuzzy) {\n const fuzzy = (query.fuzzy === true) ? 0.2 : query.fuzzy\n const maxDistance = fuzzy < 1 ? Math.min(maxFuzzy, Math.round(query.term.length * fuzzy)) : fuzzy\n if (maxDistance) fuzzyMatches = this._index.fuzzyGet(query.term, maxDistance)\n }\n\n if (prefixMatches) {\n for (const [term, data] of prefixMatches) {\n const distance = term.length - query.term.length\n if (!distance) { continue } // Skip exact match.\n\n // Delete the term from fuzzy results (if present) if it is also a\n // prefix result. This entry will always be scored as a prefix result.\n fuzzyMatches?.delete(term)\n\n // Weight gradually approaches 0 as distance goes to infinity, with the\n // weight for the hypothetical distance 0 being equal to prefixWeight.\n // The rate of change is much lower than that of fuzzy matches to\n // account for the fact that prefix matches stay more relevant than\n // fuzzy matches for longer distances.\n const weight = prefixWeight * term.length / (term.length + 0.3 * distance)\n this.termResults(query.term, term, weight, query.termBoost, data, boosts, boostDocument, bm25params, results)\n }\n }\n\n if (fuzzyMatches) {\n for (const term of fuzzyMatches.keys()) {\n const [data, distance] = fuzzyMatches.get(term)!\n if (!distance) { continue } // Skip exact match.\n\n // Weight gradually approaches 0 as distance goes to infinity, with the\n // weight for the hypothetical distance 0 being equal to fuzzyWeight.\n const weight = fuzzyWeight * term.length / (term.length + distance)\n this.termResults(query.term, term, weight, query.termBoost, data, boosts, boostDocument, bm25params, results)\n }\n }\n\n return results\n }\n\n /**\n * @ignore\n */\n private executeWildcardQuery (searchOptions: SearchOptions): RawResult {\n const results = new Map() as RawResult\n const options: SearchOptionsWithDefaults = { ...this._options.searchOptions, ...searchOptions }\n\n for (const [shortId, id] of this._documentIds) {\n const score = options.boostDocument ? options.boostDocument(id, '', this._storedFields.get(shortId)) : 1\n results.set(shortId, {\n score,\n terms: [],\n match: {}\n })\n }\n\n return results\n }\n\n /**\n * @ignore\n */\n private combineResults (results: RawResult[], combineWith: CombinationOperator = OR): RawResult {\n if (results.length === 0) { return new Map() }\n const operator = combineWith.toLowerCase()\n const combinator = (combinators as Record<string, CombinatorFunction>)[operator]\n\n if (!combinator) {\n throw new Error(`Invalid combination operator: ${combineWith}`)\n }\n\n return results.reduce(combinator) || new Map()\n }\n\n /**\n * Allows serialization of the index to JSON, to possibly store it and later\n * deserialize it with {@link MiniSearch.loadJSON}.\n *\n * Normally one does not directly call this method, but rather call the\n * standard JavaScript `JSON.stringify()` passing the {@link MiniSearch}\n * instance, and JavaScript will internally call this method. Upon\n * deserialization, one must pass to {@link MiniSearch.loadJSON} the same\n * options used to create the original instance that was serialized.\n *\n * ### Usage:\n *\n * ```javascript\n * // Serialize the index:\n * let miniSearch = new MiniSearch({ fields: ['title', 'text'] })\n * miniSearch.addAll(documents)\n * const json = JSON.stringify(miniSearch)\n *\n * // Later, to deserialize it:\n * miniSearch = MiniSearch.loadJSON(json, { fields: ['title', 'text'] })\n * ```\n *\n * @return A plain-object serializable representation of the search index.\n */\n toJSON (): AsPlainObject {\n const index: [string, { [key: string]: SerializedIndexEntry }][] = []\n\n for (const [term, fieldIndex] of this._index) {\n const data: { [key: string]: SerializedIndexEntry } = {}\n\n for (const [fieldId, freqs] of fieldIndex) {\n data[fieldId] = Object.fromEntries(freqs)\n }\n\n index.push([term, data])\n }\n\n return {\n documentCount: this._documentCount,\n nextId: this._nextId,\n documentIds: Object.fromEntries(this._documentIds),\n fieldIds: this._fieldIds,\n fieldLength: Object.fromEntries(this._fieldLength),\n averageFieldLength: this._avgFieldLength,\n storedFields: Object.fromEntries(this._storedFields),\n dirtCount: this._dirtCount,\n index,\n serializationVersion: 2\n }\n }\n\n /**\n * @ignore\n */\n private termResults (\n sourceTerm: string,\n derivedTerm: string,\n termWeight: number,\n termBoost: number,\n fieldTermData: FieldTermData | undefined,\n fieldBoosts: { [field: string]: number },\n boostDocumentFn: ((id: any, term: string, storedFields?: Record<string, unknown>) => number) | undefined,\n bm25params: BM25Params,\n results: RawResult = new Map()\n ): RawResult {\n if (fieldTermData == null) return results\n\n for (const field of Object.keys(fieldBoosts)) {\n const fieldBoost = fieldBoosts[field]\n const fieldId = this._fieldIds[field]\n\n const fieldTermFreqs = fieldTermData.get(fieldId)\n if (fieldTermFreqs == null) continue\n\n let matchingFields = fieldTermFreqs.size\n const avgFieldLength = this._avgFieldLength[fieldId]\n\n for (const docId of fieldTermFreqs.keys()) {\n if (!this._documentIds.has(docId)) {\n this.removeTerm(fieldId, docId, derivedTerm)\n matchingFields -= 1\n continue\n }\n\n const docBoost = boostDocumentFn ? boostDocumentFn(this._documentIds.get(docId), derivedTerm, this._storedFields.get(docId)) : 1\n if (!docBoost) continue\n\n const termFreq = fieldTermFreqs.get(docId)!\n const fieldLength = this._fieldLength.get(docId)![fieldId]\n\n // NOTE: The total number of fields is set to the number of documents\n // `this._documentCount`. It could also make sense to use the number of\n // documents where the current field is non-blank as a normalization\n // factor. This will make a difference in scoring if the field is rarely\n // present. This is currently not supported, and may require further\n // analysis to see if it is a valid use case.\n const rawScore = calcBM25Score(termFreq, matchingFields, this._documentCount, fieldLength, avgFieldLength, bm25params)\n const weightedScore = termWeight * termBoost * fieldBoost * docBoost * rawScore\n\n const result = results.get(docId)\n if (result) {\n result.score += weightedScore\n assignUniqueTerm(result.terms, sourceTerm)\n const match = getOwnProperty(result.match, derivedTerm)\n if (match) {\n match.push(field)\n } else {\n result.match[derivedTerm] = [field]\n }\n } else {\n results.set(docId, {\n score: weightedScore,\n terms: [sourceTerm],\n match: { [derivedTerm]: [field] }\n })\n }\n }\n }\n\n return results\n }\n\n /**\n * @ignore\n */\n private addTerm (fieldId: number, documentId: number, term: string): void {\n const indexData = this._index.fetch(term, createMap)\n\n let fieldIndex = indexData.get(fieldId)\n if (fieldIndex == null) {\n fieldIndex = new Map()\n fieldIndex.set(documentId, 1)\n indexData.set(fieldId, fieldIndex)\n } else {\n const docs = fieldIndex.get(documentId)\n fieldIndex.set(documentId, (docs || 0) + 1)\n }\n }\n\n /**\n * @ignore\n */\n private removeTerm (fieldId: number, documentId: number, term: string): void {\n if (!this._index.has(term)) {\n this.warnDocumentChanged(documentId, fieldId, term)\n return\n }\n\n const indexData = this._index.fetch(term, createMap)\n\n const fieldIndex = indexData.get(fieldId)\n if (fieldIndex == null || fieldIndex.get(documentId) == null) {\n this.warnDocumentChanged(documentId, fieldId, term)\n } else if (fieldIndex.get(documentId)! <= 1) {\n if (fieldIndex.size <= 1) {\n indexData.delete(fieldId)\n } else {\n fieldIndex.delete(documentId)\n }\n } else {\n fieldIndex.set(documentId, fieldIndex.get(documentId)! - 1)\n }\n\n if (this._index.get(term)!.size === 0) {\n this._index.delete(term)\n }\n }\n\n /**\n * @ignore\n */\n private warnDocumentChanged (shortDocumentId: number, fieldId: number, term: string): void {\n for (const fieldName of Object.keys(this._fieldIds)) {\n if (this._fieldIds[fieldName] === fieldId) {\n this._options.logger('warn', `MiniSearch: document with ID ${this._documentIds.get(shortDocumentId)} has changed before removal: term \"${term}\" was not present in field \"${fieldName}\". Removing a document after it has changed can corrupt the index!`, 'version_conflict')\n return\n }\n }\n }\n\n /**\n * @ignore\n */\n private addDocumentId (documentId: any): number {\n const shortDocumentId = this._nextId\n this._idToShortId.set(documentId, shortDocumentId)\n this._documentIds.set(shortDocumentId, documentId)\n this._documentCount += 1\n this._nextId += 1\n return shortDocumentId\n }\n\n /**\n * @ignore\n */\n private addFields (fields: string[]): void {\n for (let i = 0; i < fields.length; i++) {\n this._fieldIds[fields[i]] = i\n }\n }\n\n /**\n * @ignore\n */\n private addFieldLength (documentId: number, fieldId: number, count: number, length: number): void {\n let fieldLengths = this._fieldLength.get(documentId)\n if (fieldLengths == null) this._fieldLength.set(documentId, fieldLengths = [])\n fieldLengths[fieldId] = length\n\n const averageFieldLength = this._avgFieldLength[fieldId] || 0\n const totalFieldLength = (averageFieldLength * count) + length\n this._avgFieldLength[fieldId] = totalFieldLength / (count + 1)\n }\n\n /**\n * @ignore\n */\n private removeFieldLength (documentId: number, fieldId: number, count: number, length: number): void {\n if (count === 1) {\n this._avgFieldLength[fieldId] = 0\n return\n }\n const totalFieldLength = (this._avgFieldLength[fieldId] * count) - length\n this._avgFieldLength[fieldId] = totalFieldLength / (count - 1)\n }\n\n /**\n * @ignore\n */\n private saveStoredFields (documentId: number, doc: T): void {\n const { storeFields, extractField } = this._options\n if (storeFields == null || storeFields.length === 0) { return }\n\n let documentFields = this._storedFields.get(documentId)\n if (documentFields == null) this._storedFields.set(documentId, documentFields = {})\n\n for (const fieldName of storeFields) {\n const fieldValue = extractField(doc, fieldName)\n if (fieldValue !== undefined) documentFields[fieldName] = fieldValue\n }\n }\n}\n\nconst getOwnProperty = (object: any, property: string) =>\n Object.prototype.hasOwnProperty.call(object, property) ? object[property] : undefined\n\ntype CombinatorFunction = (a: RawResult, b: RawResult) => RawResult\n\nconst combinators: Record<LowercaseCombinationOperator, CombinatorFunction> = {\n [OR]: (a: RawResult, b: RawResult) => {\n for (const docId of b.keys()) {\n const existing = a.get(docId)\n if (existing == null) {\n a.set(docId, b.get(docId)!)\n } else {\n const { score, terms, match } = b.get(docId)!\n existing.score = existing.score + score\n existing.match = Object.assign(existing.match, match)\n assignUniqueTerms(existing.terms, terms)\n }\n }\n\n return a\n },\n [AND]: (a: RawResult, b: RawResult) => {\n const combined = new Map()\n\n for (const docId of b.keys()) {\n const existing = a.get(docId)\n if (existing == null) continue\n\n const { score, terms, match } = b.get(docId)!\n assignUniqueTerms(existing.terms, terms)\n combined.set(docId, {\n score: existing.score + score,\n terms: existing.terms,\n match: Object.assign(existing.match, match)\n })\n }\n\n return combined\n },\n [AND_NOT]: (a: RawResult, b: RawResult) => {\n for (const docId of b.keys()) a.delete(docId)\n return a\n }\n}\n\n/**\n * Parameters of the BM25+ scoring algorithm. Customizing these is almost never\n * necessary, and finetuning them requires an understanding of the BM25 scoring\n * model.\n *\n * Some information about BM25 (and BM25+) can be found at these links:\n *\n * - https://en.wikipedia.org/wiki/Okapi_BM25\n * - https://opensourceconnections.com/blog/2015/10/16/bm25-the-next-generation-of-lucene-relevation/\n */\nexport type BM25Params = {\n /** Term frequency saturation point.\n *\n * Recommended values are between `1.2` and `2`. Higher values increase the\n * difference in score between documents with higher and lower term\n * frequencies. Setting this to `0` or a negative value is invalid. Defaults\n * to `1.2`\n */\n k: number,\n\n /**\n * Length normalization impact.\n *\n * Recommended values are around `0.75`. Higher values increase the weight\n * that field length has on scoring. Setting this to `0` (not recommended)\n * means that the field length has no effect on scoring. Negative values are\n * invalid. Defaults to `0.7`.\n */\n b: number,\n\n /**\n * BM25+ frequency normalization lower bound (usually called δ).\n *\n * Recommended values are between `0.5` and `1`. Increasing this parameter\n * increases the minimum relevance of one occurrence of a search term\n * regardless of its (possibly very long) field length. Negative values are\n * invalid. Defaults to `0.5`.\n */\n d: number\n}\n\nconst defaultBM25params: BM25Params = { k: 1.2, b: 0.7, d: 0.5 }\n\nconst calcBM25Score = (\n termFreq: number,\n matchingCount: number,\n totalCount: number,\n fieldLength: number,\n avgFieldLength: number,\n bm25params: BM25Params\n): number => {\n const { k, b, d } = bm25params\n const invDocFreq = Math.log(1 + (totalCount - matchingCount + 0.5) / (matchingCount + 0.5))\n return invDocFreq * (d + termFreq * (k + 1) / (termFreq + k * (1 - b + b * fieldLength / avgFieldLength)))\n}\n\nconst termToQuerySpec = (options: SearchOptions) => (term: string, i: number, terms: string[]): QuerySpec => {\n const fuzzy = (typeof options.fuzzy === 'function')\n ? options.fuzzy(term, i, terms)\n : (options.fuzzy || false)\n const prefix = (typeof options.prefix === 'function')\n ? options.prefix(term, i, terms)\n : (options.prefix === true)\n const termBoost = (typeof options.boostTerm === 'function')\n ? options.boostTerm(term, i, terms)\n : 1\n return { term, fuzzy, prefix, termBoost }\n}\n\nconst defaultOptions = {\n idField: 'id',\n extractField: (document: any, fieldName: string) => document[fieldName],\n stringifyField: (fieldValue: any, fieldName: string) => fieldValue.toString(),\n tokenize: (text: string) => text.split(SPACE_OR_PUNCTUATION),\n processTerm: (term: string) => term.toLowerCase(),\n fields: undefined,\n searchOptions: undefined,\n storeFields: [],\n logger: (level: LogLevel, message: string): void => {\n if (typeof console?.[level] === 'function') console[level](message)\n },\n autoVacuum: true\n}\n\nconst defaultSearchOptions = {\n combineWith: OR,\n prefix: false,\n fuzzy: false,\n maxFuzzy: 6,\n boost: {},\n weights: { fuzzy: 0.45, prefix: 0.375 },\n bm25: defaultBM25params\n}\n\nconst defaultAutoSuggestOptions = {\n combineWith: AND,\n prefix: (term: string, i: number, terms: string[]): boolean =>\n i === terms.length - 1\n}\n\nconst defaultVacuumOptions = { batchSize: 1000, batchWait: 10 }\nconst defaultVacuumConditions = { minDirtFactor: 0.1, minDirtCount: 20 }\n\nconst defaultAutoVacuumOptions = { ...defaultVacuumOptions, ...defaultVacuumConditions }\n\nconst assignUniqueTerm = (target: string[], term: string): void => {\n // Avoid adding duplicate terms.\n if (!target.includes(term)) target.push(term)\n}\n\nconst assignUniqueTerms = (target: string[], source: readonly string[]): void => {\n for (const term of source) {\n // Avoid adding duplicate terms.\n if (!target.includes(term)) target.push(term)\n }\n}\n\ntype Scored = { score: number }\nconst byScore = ({ score: a }: Scored, { score: b }: Scored) => b - a\n\nconst createMap = () => new Map()\n\ninterface SerializedIndexEntry {\n [key: string]: number\n}\n\nconst objectToNumericMap = <T>(object: { [key: string]: T }): Map<number, T> => {\n const map = new Map()\n\n for (const key of Object.keys(object)) {\n map.set(parseInt(key, 10), object[key])\n }\n\n return map\n}\n\nconst objectToNumericMapAsync = async <T>(object: { [key: string]: T }): Promise<Map<number, T>> => {\n const map = new Map()\n\n let count = 0\n for (const key of Object.keys(object)) {\n map.set(parseInt(key, 10), object[key])\n if (++count % 1000 === 0) {\n await wait(0)\n }\n }\n\n return map\n}\n\nconst wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))\n\n// This regular expression matches any Unicode space, newline, or punctuation\n// character\nconst SPACE_OR_PUNCTUATION = /[\\n\\r\\p{Z}\\p{P}]+/u\n","/**\n * Lexical entry (ADR 01019) — text query → ranked seed nodes.\n *\n * Loads the `search.json` artifact (produced by `manni graph export search`)\n * and scores it with MiniSearch. The artifact carries body text, which the graph\n * deliberately does not (ADR 01008), so a query can match what a document *says*\n * and not merely what it is titled.\n *\n * MiniSearch is this runtime's one production dependency; the bundle-purity gate\n * allow-lists exactly it. Two guards keep ranking a dockg contract rather than a\n * library's: ties are broken by IRI here (MiniSearch does not define tie order),\n * and the on-disk artifact format is ours, so upgrading MiniSearch can never\n * change a committed artifact.\n *\n * Platform-neutral: no `node:` imports.\n */\nimport MiniSearch from \"minisearch\";\nimport type { SearchEntry, SearchIndexDoc } from \"../core/search-index.js\";\nimport { byCodeUnit } from \"../core/sort.js\";\nimport type { EntryCandidate } from \"./trace.js\";\n\nexport interface LexicalSearchOptions {\n /** Maximum candidates to return. Default 10. */\n limit?: number;\n}\n\nexport interface LexicalIndex {\n /** Ranked candidates, best first, ties broken by IRI. */\n search(query: string, options?: LexicalSearchOptions): EntryCandidate[];\n /** Indexed entry count. */\n size(): number;\n /** The entry behind an IRI, for callers that want its title/type. */\n entry(iri: string): SearchEntry | undefined;\n}\n\n/**\n * Build a lexical index from the search artifact — a JSON string or the parsed\n * document.\n */\nexport function createLexicalIndex(\n input: string | SearchIndexDoc,\n): LexicalIndex {\n const doc = (\n typeof input === \"string\" ? (JSON.parse(input) as SearchIndexDoc) : input\n ) as SearchIndexDoc | null;\n // Shape-check rather than trust: handed something that is valid JSON but not\n // a search artifact, MiniSearch's `addAll` throws \"documents is not\n // iterable\" from inside the library. An empty index is the honest answer.\n const entries = Array.isArray(doc?.entries) ? doc.entries : [];\n\n const mini = new MiniSearch<SearchEntry>({\n fields: [\"title\", \"labels\", \"description\", \"text\"],\n storeFields: [\"id\"],\n idField: \"id\",\n // Titles and labels are the strongest signal that a node *is* the subject;\n // body text is evidence it merely mentions it.\n searchOptions: {\n boost: { title: 3, labels: 2, description: 1.5 },\n prefix: true,\n fuzzy: 0.2,\n },\n });\n mini.addAll(entries);\n\n const byIri = new Map(entries.map((e) => [e.id, e]));\n\n return {\n size: () => entries.length,\n entry: (iri) => byIri.get(iri),\n search(query, options = {}) {\n const trimmed = query.trim();\n if (trimmed === \"\") return [];\n const hits = mini.search(trimmed);\n // MiniSearch does not define an order for equal scores; sort explicitly so\n // the same query against the same artifact always ranks identically.\n hits.sort((a, b) =>\n a.score === b.score\n ? byCodeUnit(String(a.id), String(b.id))\n : b.score - a.score,\n );\n return hits\n .slice(0, options.limit ?? 10)\n .map((h) => ({ iri: String(h.id), score: h.score, via: \"lexical\" }));\n },\n };\n}\n","/**\n * The vector sidecar (ADR 01020) — `graph/vectors.<lang>.bin`, embeddings for the\n * same text that language's lexical index covers (ADR 01038).\n *\n * Layout, fixed. The magic is four ASCII bytes in file order; every number\n * after it is little-endian:\n *\n * ```\n * 0 magic \"MGRV\" 4 bytes\n * 4 format version (u32) 4 bytes\n * 8 header length (u32) 4 bytes\n * 12 header JSON (UTF-8) headerLength bytes\n * . float32 payload count * dims * 4 bytes\n * ```\n *\n * The header names the model, dtype, dimensions, the node IRIs in payload order\n * (sorted), and a digest of the `search.json` the vectors were built from — so\n * the runtime can refuse to rank against vectors from a different model or a\n * stale corpus rather than returning quietly wrong results.\n *\n * Vectors are **L2-normalized at build time and stored as float32**. Normalizing\n * makes cosine collapse to a dot product at query time; float32 rather than int8\n * because int8 retains only ~91% of retrieval quality at 384 dimensions — see\n * ADR 01020, where that correction is recorded.\n *\n * No `node:` imports: the encoder runs in the CLI, the decoder in the browser.\n */\nimport { byCodeUnit } from \"./sort.js\";\n\n/**\n * \"MGRV\", manni graph vectors, as the bytes a hex dump shows first. It read\n * \"DKGV\" while the tool was dockg and \"MKGV\" while it was manni kg. Nothing was\n * published under either name, so no sidecar in the wild carries the old bytes.\n * Raw bytes rather than a little-endian u32: a u32 lands on disk reversed.\n */\nconst MAGIC = new Uint8Array([0x4d, 0x47, 0x52, 0x56]);\n// 2 since ADR 01038: the header names the language its vectors cover, so a\n// consumer cannot pair a sidecar with the wrong locale's index. A version-1\n// file is refused by `decodeVectorIndex` rather than read as if it had one.\nconst FORMAT_VERSION = 2;\nconst HEADER_OFFSET = 12;\n\nexport interface VectorIndexHeader {\n /** Embedding model id, e.g. an HF repo path. */\n model: string;\n /** Model-weight quantization the vectors were produced under. */\n dtype: string;\n /** Vector dimensions. Never assumed — always read from here. */\n dims: number;\n /** Number of vectors; equals `ids.length`. */\n count: number;\n /** Node IRIs, sorted, in payload order. */\n ids: string[];\n /** Digest of the `search.<lang>.json` these were built from (staleness detection). */\n source: string;\n /**\n * BCP-47 tag of the index these cover, or `und` (ADR 01038). Recorded so a\n * host that fetched the wrong pair is refused rather than ranked against a\n * model that never saw the language.\n */\n language: string;\n}\n\nexport interface VectorIndexDoc {\n header: VectorIndexHeader;\n /** `count * dims` floats, L2-normalized, row-major in `ids` order. */\n vectors: Float32Array;\n}\n\n/** Thrown for malformed input so callers can map it to an exit code / refusal. */\nexport class VectorIndexError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"VectorIndexError\";\n }\n}\n\n/**\n * L2-normalize a vector in place and return it. A zero vector is left alone —\n * dividing by its norm would produce NaNs that silently poison every later dot\n * product.\n */\nexport function normalize(vector: Float32Array): Float32Array {\n let sum = 0;\n // Iterating rather than indexing: every element is an element, which is what\n // the assertions here used to say.\n for (const value of vector) sum += value * value;\n if (sum === 0) return vector;\n const inv = 1 / Math.sqrt(sum);\n // `set(map(…))` scales every element in place with the same per-element\n // float32 rounding the indexed loop had, and without an index to assert.\n vector.set(vector.map((value) => value * inv));\n return vector;\n}\n\n/**\n * Encode entries into the sidecar. Entries are sorted by IRI first, so the bytes\n * depend on the set of entries and not on the order they were produced in.\n */\nexport function encodeVectorIndex(\n entries: Array<{ id: string; vector: Float32Array }>,\n meta: { model: string; dtype: string; source: string; language: string },\n): Uint8Array {\n const sorted = [...entries].sort((a, b) => byCodeUnit(a.id, b.id));\n const dims = sorted[0]?.vector.length ?? 0;\n for (const entry of sorted) {\n if (entry.vector.length !== dims) {\n throw new VectorIndexError(\n `Inconsistent vector dimensions: ${entry.id} has ${entry.vector.length}, expected ${dims}.`,\n );\n }\n }\n\n const header: VectorIndexHeader = {\n model: meta.model,\n dtype: meta.dtype,\n dims,\n count: sorted.length,\n ids: sorted.map((e) => e.id),\n source: meta.source,\n language: meta.language,\n };\n const headerBytes = new TextEncoder().encode(JSON.stringify(header));\n\n const payloadBytes = sorted.length * dims * 4;\n const out = new Uint8Array(HEADER_OFFSET + headerBytes.length + payloadBytes);\n const view = new DataView(out.buffer);\n out.set(MAGIC, 0);\n view.setUint32(4, FORMAT_VERSION, true);\n view.setUint32(8, headerBytes.length, true);\n out.set(headerBytes, HEADER_OFFSET);\n\n let offset = HEADER_OFFSET + headerBytes.length;\n for (const entry of sorted) {\n // Normalize a copy: the caller's array is not ours to mutate.\n const vector = normalize(Float32Array.from(entry.vector));\n // Exactly `dims` elements: the loop above rejected any entry of another\n // length, so iterating the vector is the same walk without the index.\n for (const value of vector) {\n view.setFloat32(offset, value, true);\n offset += 4;\n }\n }\n return out;\n}\n\n/** Decode a sidecar, rejecting anything malformed rather than mis-reading it. */\nexport function decodeVectorIndex(bytes: Uint8Array): VectorIndexDoc {\n if (bytes.length < HEADER_OFFSET) {\n throw new VectorIndexError(\"Not a manni graph vector index: file is too short.\");\n }\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n if (!MAGIC.every((byte, i) => bytes[i] === byte)) {\n throw new VectorIndexError(\n \"Not a manni graph vector index: bad magic — is this the right file?\",\n );\n }\n const version = view.getUint32(4, true);\n if (version !== FORMAT_VERSION) {\n throw new VectorIndexError(\n `Unsupported vector index version ${version} (this build reads ${FORMAT_VERSION}) — re-run \\`manni graph embed\\`.`,\n );\n }\n\n const headerLength = view.getUint32(8, true);\n if (HEADER_OFFSET + headerLength > bytes.length) {\n throw new VectorIndexError(\"Vector index is truncated: header overruns.\");\n }\n\n let header: VectorIndexHeader;\n try {\n header = JSON.parse(\n new TextDecoder().decode(\n bytes.subarray(HEADER_OFFSET, HEADER_OFFSET + headerLength),\n ),\n ) as VectorIndexHeader;\n } catch {\n throw new VectorIndexError(\"Vector index header is not valid JSON.\");\n }\n if (\n !Array.isArray(header.ids) ||\n typeof header.dims !== \"number\" ||\n header.ids.length !== header.count\n ) {\n throw new VectorIndexError(\"Vector index header is malformed.\");\n }\n\n const start = HEADER_OFFSET + headerLength;\n const expected = header.count * header.dims * 4;\n if (bytes.length - start !== expected) {\n throw new VectorIndexError(\n `Vector index is truncated: expected ${expected} payload bytes, found ${bytes.length - start}.`,\n );\n }\n\n // Copy rather than aliasing: `bytes` may be a view into a larger buffer whose\n // byteOffset is not 4-aligned, which Float32Array construction rejects.\n const vectors = new Float32Array(header.count * header.dims);\n for (let i = 0; i < vectors.length; i++) {\n vectors[i] = view.getFloat32(start + i * 4, true);\n }\n return { header, vectors };\n}\n","/**\n * Vector search (ADR 01020) — semantic entry, and a standalone capability.\n *\n * `search()` is usable on its own: give it a query vector and it ranks nodes by\n * meaning, with no lexical index and no graph involved. `findEntry` composes it\n * with the lexical leg, but does not own it.\n *\n * Hand-written rather than taken from a library, on evidence: the dedicated\n * browser vector libraries are 3 years stale, no maintained micro-package does\n * cosine top-k over typed arrays (the popular one throws on `Float32Array`), and\n * the engines that do exist run this same brute-force loop internally. See ADR\n * 01020 for the full survey.\n *\n * Vectors are L2-normalized at build time, so cosine similarity **is** the dot\n * product — no norms, no division, at query time. The loop is indexed rather\n * than `.reduce()`, which measures ~13× slower on typed arrays.\n *\n * Platform-neutral: no `node:` imports, no dependencies.\n */\nimport { byCodeUnit } from \"../core/sort.js\";\nimport {\n decodeVectorIndex,\n normalize,\n type VectorIndexHeader,\n} from \"../core/vector-index.js\";\nimport type { EntryCandidate } from \"./trace.js\";\n\nexport interface VectorSearchOptions {\n /** Maximum candidates to return. Default 10. */\n limit?: number;\n /**\n * Drop candidates scoring below this. Default 0 — every model has its own\n * useful range, so dockg does not impose a threshold the user did not choose.\n */\n minScore?: number;\n}\n\n/** Why a vector index cannot be used with the embedder or corpus at hand. */\nexport interface VectorMismatch {\n reason: \"model\" | \"dtype\" | \"dims\" | \"stale-source\";\n detail: string;\n}\n\n/**\n * Thrown when a query would be ranked against vectors it cannot be compared to.\n *\n * A distinct type so hosts can catch exactly this — and so it cannot be mistaken\n * for \"no results\". Ranking on regardless is the silent-wrong-answer failure\n * ADR 01020 exists to prevent, so this is loud by design.\n */\nexport class VectorMismatchError extends Error {\n readonly reason: VectorMismatch[\"reason\"];\n constructor(mismatch: VectorMismatch) {\n super(mismatch.detail);\n this.name = \"VectorMismatchError\";\n this.reason = mismatch.reason;\n }\n}\n\n/**\n * The digest `manni graph embed` records as a sidecar's `source`, computed the same\n * way in a browser — SHA-256 over the **raw bytes of `search.json` exactly as\n * fetched**, hex, prefixed `sha256:`.\n *\n * Exists so a host can pass `source` to `findEntry` and get the staleness half\n * of the refusal (ADR 01020) without reconstructing the recipe. Re-serializing\n * the parsed JSON would change the bytes and so the digest — pass the response\n * text, not `JSON.stringify(doc)`.\n *\n * Uses Web Crypto, which is platform-neutral: browsers and Node 18+ both have\n * it on `globalThis`.\n */\nexport async function searchIndexDigest(raw: string): Promise<string> {\n // `lib.dom` and @types/node both declare `globalThis.crypto.subtle` as\n // always present. A page served over plain HTTP gets `crypto` without\n // `subtle`, which is the case this throw exists for: the declaration is the\n // optimistic one, and reading through `Partial` is how the guard gets to say\n // so instead of reading as a test that cannot fail.\n const webCrypto = globalThis.crypto as\n | Partial<typeof globalThis.crypto>\n | undefined;\n const subtle = webCrypto?.subtle;\n if (!subtle) {\n throw new Error(\n \"searchIndexDigest needs Web Crypto (globalThis.crypto.subtle), which is unavailable here — a page served over plain HTTP does not get it.\",\n );\n }\n const digest = await subtle.digest(\"SHA-256\", new TextEncoder().encode(raw));\n const hex = [...new Uint8Array(digest)]\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n return `sha256:${hex}`;\n}\n\nexport interface VectorIndex {\n /**\n * Rank nodes against a query vector. The vector is normalized here, so\n * callers need not — an unnormalized query would otherwise scale every score.\n */\n search(query: Float32Array, options?: VectorSearchOptions): EntryCandidate[];\n /**\n * Check this index against the embedder and corpus in play. Returns the\n * mismatch, or undefined when they agree. Ranking against vectors from a\n * different model compares outputs of two different functions (ADR 01020), so\n * callers should refuse rather than proceed.\n */\n check(expected: {\n model?: string;\n dtype?: string;\n dims?: number;\n source?: string;\n }): VectorMismatch | undefined;\n readonly model: string;\n /**\n * Weight quantization the corpus vectors were produced under. The query side\n * must embed at the *same* dtype — q8 and fp32 weights are different\n * functions, so mixing them compares incomparable vectors (ADR 01020).\n */\n readonly dtype: string;\n readonly dims: number;\n readonly source: string;\n size(): number;\n /** The IRI at a payload row, for callers walking the index directly. */\n idAt(row: number): string | undefined;\n}\n\n/** Build a vector index from encoded sidecar bytes. */\nexport function createVectorIndex(bytes: Uint8Array): VectorIndex {\n const { header, vectors } = decodeVectorIndex(bytes);\n const { dims, ids } = header;\n\n return {\n model: header.model,\n dtype: header.dtype,\n dims,\n source: header.source,\n size: () => ids.length,\n idAt: (row) => ids[row],\n\n check(expected) {\n if (expected.model !== undefined && expected.model !== header.model) {\n return {\n reason: \"model\",\n detail: `Vector index was built with ${header.model}, but the embedder is ${expected.model}. Re-run \\`manni graph embed\\`.`,\n };\n }\n if (expected.dtype !== undefined && expected.dtype !== header.dtype) {\n return {\n reason: \"dtype\",\n detail: `Vector index was built at dtype ${header.dtype}, but the embedder is at ${expected.dtype} — different weights are a different function. Re-run \\`manni graph embed\\`.`,\n };\n }\n if (expected.dims !== undefined && expected.dims !== dims) {\n return {\n reason: \"dims\",\n detail: `Vector index has ${dims} dimensions, but the embedder produces ${expected.dims}.`,\n };\n }\n if (expected.source !== undefined && expected.source !== header.source) {\n return {\n reason: \"stale-source\",\n detail:\n \"Vector index was built from a different search index — the corpus changed. Re-run `manni graph embed`.\",\n };\n }\n return undefined;\n },\n\n search(query, options = {}) {\n if (dims === 0 || ids.length === 0) return [];\n if (query.length !== dims) {\n // A silent zero-fill or truncate here would return confident nonsense.\n // Typed like every other mismatch so a caller (and the CLI's exit-code\n // mapping) handles it the same way rather than seeing a raw stack.\n throw new VectorMismatchError({\n reason: \"dims\",\n detail: `Query vector has ${query.length} dimensions, but the index has ${dims}.`,\n });\n }\n const limit = normalizeLimit(options.limit);\n if (limit === 0) return [];\n const minScore = options.minScore ?? 0;\n\n // Copy before normalizing: the caller's vector is not ours to mutate.\n const q = normalize(Float32Array.from(query));\n\n const scored: EntryCandidate[] = [];\n // `entries()` pairs each row with its IRI, so the id is proven present\n // by the iteration rather than asserted after an index.\n for (const [row, iri] of ids.entries()) {\n // The payload is `count × dims` floats, so this row is exactly these\n // `dims` of them — and `q` was checked to be `dims` long above. Both\n // walks are therefore in range; `?? 0` spells that a term outside the\n // row contributes nothing, which is what out of range means for a dot\n // product.\n const stored = vectors.subarray(row * dims, (row + 1) * dims);\n let score = 0;\n for (const [i, value] of q.entries()) score += value * (stored[i] ?? 0);\n if (score >= minScore) {\n scored.push({ iri, score, via: \"vector\" });\n }\n }\n\n scored.sort((a, b) =>\n a.score === b.score ? byCodeUnit(a.iri, b.iri) : b.score - a.score,\n );\n return scored.slice(0, limit);\n },\n };\n}\n\n/**\n * A limit that is not a non-negative integer falls back to the documented\n * default — `slice(0, NaN)` is empty, which would report a confident \"no\n * results\" for a query that does match.\n */\nfunction normalizeLimit(limit: number | undefined): number {\n return typeof limit === \"number\" && Number.isInteger(limit) && limit >= 0\n ? limit\n : 10;\n}\n\nexport type { VectorIndexHeader };\n","/**\n * Entry-point finding (ADR 01019, extended by ADR 01020) — the stage that turns\n * a question into seed nodes for the walker.\n *\n * Two rankings now: lexical (BM25 over the search artifact) and, when the host\n * supplies an embedder, vector (cosine over the sidecar). `rrfMerge` fuses them.\n *\n * **Each leg is returned separately as well as fused.** A caller rendering a\n * search UI wants to show \"text matches\" and \"semantic matches\" as distinct\n * things, and either leg is usable on its own — `lexical.search` and\n * `vectors.search` are public and independent of this function.\n *\n * Every candidate is appended to the trace, so \"why did retrieval start here?\"\n * is answerable alongside \"why did it walk there?\" (ADR 01018 invariant 2).\n *\n * Platform-neutral: no `node:` imports.\n */\nimport { byCodeUnit } from \"../core/sort.js\";\nimport type { LexicalIndex } from \"./lexical.js\";\nimport { VectorMismatchError, type VectorIndex } from \"./vector.js\";\nimport {\n createTrace,\n type EntryCandidate,\n type EntryVia,\n type QueryTrace,\n} from \"./trace.js\";\n\n/**\n * Enough of an embedder to verify it against a vector index. Structural rather\n * than the `Embedder` interface itself, so the runtime stays independent of\n * `@hawkeyexl/manni/graph/embed` — any object with these three fields works.\n */\nexport interface QueryEmbedder {\n readonly model: string;\n readonly dtype: string;\n embed(text: string): Promise<Float32Array> | Float32Array;\n}\n\nexport interface FindEntryOptions {\n /** The lexical index to query. */\n lexical: LexicalIndex;\n /** The vector index. Without it (and an embedder), entry is lexical-only. */\n vectors?: VectorIndex;\n /**\n * The embedder for the query side. **Prefer this over `embedQuery`**: it\n * carries the model and dtype, so `findEntry` can verify they match the\n * vector index and refuse rather than rank against incomparable vectors.\n */\n embedder?: QueryEmbedder;\n /**\n * Embed the query with a bare function. An escape hatch for hosts wiring\n * their own model — but it carries no identity, so **the model/dtype match\n * cannot be verified**; only the dimension check inside `search` applies.\n * Prefer `embedder`.\n */\n embedQuery?: (query: string) => Promise<Float32Array> | Float32Array;\n /**\n * Digest of the `search.json` this caller loaded, from `searchIndexDigest`.\n * Supplied, a sidecar built from a *different* corpus is refused rather than\n * ranked — its IRIs may no longer exist, and it misses everything added\n * since. Omitted, that half of the check simply does not run: the runtime\n * cannot derive the digest, since it never sees the raw bytes.\n */\n source?: string;\n /** Maximum seeds to return. Default 10. */\n limit?: number;\n /** Append candidates here instead of starting a new trace. */\n trace?: QueryTrace;\n}\n\nexport interface EntryResult {\n /** The fused ranking — what seeds traversal. */\n candidates: EntryCandidate[];\n /** The lexical leg's own ranking. */\n lexical: EntryCandidate[];\n /** The vector leg's own ranking; empty when no embedder was supplied. */\n vector: EntryCandidate[];\n trace: QueryTrace;\n}\n\n/**\n * Reciprocal rank fusion over N ranked lists: score = Σ 1/(k + rank).\n *\n * Rank-based rather than score-based on purpose — lexical BM25 scores and\n * cosine similarities are not on a comparable scale, so fusing raw scores would\n * let whichever leg happens to produce bigger numbers dominate. `k = 60` is the\n * standard damping constant.\n *\n * Deterministic: input list order does not affect the result, and ties break by\n * IRI.\n */\nexport function rrfMerge(\n rankings: EntryCandidate[][],\n k = 60,\n): EntryCandidate[] {\n const fused = new Map<string, { score: number; vias: Set<EntryVia> }>();\n for (const ranking of rankings) {\n ranking.forEach((candidate, i) => {\n const current = fused.get(candidate.iri) ?? {\n score: 0,\n vias: new Set<EntryVia>(),\n };\n current.score += 1 / (k + i + 1);\n current.vias.add(candidate.via);\n fused.set(candidate.iri, current);\n });\n }\n\n return [...fused.entries()]\n .map(([iri, { score, vias }]) => {\n // One leg keeps its own provenance; several means the seed was fused.\n // Destructuring rather than `[...vias][0]!` so the single-leg case needs\n // no non-null assertion — an empty set simply falls through to \"hybrid\",\n // which is unreachable anyway (a set only exists once a leg added to it).\n const [only] = vias;\n return {\n iri,\n score,\n via: vias.size === 1 && only !== undefined ? only : \"hybrid\",\n };\n })\n .sort((a, b) =>\n a.score === b.score ? byCodeUnit(a.iri, b.iri) : b.score - a.score,\n );\n}\n\n/**\n * Find seed nodes for a question, returning each ranking leg and their fusion.\n *\n * Async because embedding a query is: local models are a WASM forward pass.\n * Uniformly async rather than sync-when-lexical-only, so callers have one\n * contract to hold rather than a return type that changes with the options.\n *\n * The vector leg runs only when both a `vectors` index and an `embedQuery` are\n * supplied. Absent either, this is lexical entry exactly as Phase 8 shipped it —\n * additive, never a new failure mode (ADR 01009's degrade-don't-fail rule).\n */\nexport async function findEntry(\n query: string,\n options: FindEntryOptions,\n): Promise<EntryResult> {\n const trace = options.trace ?? createTrace();\n // `--limit abc` parses to NaN, and `slice(0, NaN)` is empty — a typo'd flag\n // would report a confident \"0 results\" for a query that does match. Anything\n // that is not a non-negative integer falls back to the documented default.\n const limit =\n typeof options.limit === \"number\" &&\n Number.isInteger(options.limit) &&\n options.limit >= 0\n ? options.limit\n : 10;\n\n const lexical = options.lexical.search(query, { limit });\n\n // Bound first: the closure then captures the embedder the test found, rather\n // than re-reading a property the type cannot know is still the same one.\n const embedder = options.embedder;\n const embed = embedder ? (q: string) => embedder.embed(q) : options.embedQuery;\n\n let vector: EntryCandidate[] = [];\n if (options.vectors && embed && query.trim() !== \"\") {\n // Verify *before* embedding. The refusal is enforced here, not only in the\n // CLI, because this is the browser-facing surface — and the whole reason\n // ADR 01020 exists is that the browser must embed with a function that\n // agrees with the one that embedded the corpus. Ranking a stale or\n // wrong-model index would be the silent wrong answer this design prevents.\n const mismatch = options.vectors.check({\n ...(options.embedder\n ? { model: options.embedder.model, dtype: options.embedder.dtype }\n : {}),\n // Staleness is checked whichever way the query is embedded — it is a\n // property of the corpus, not of the embedder, so even the unverified\n // `embedQuery` path gets it when the caller supplies a digest.\n ...(options.source === undefined ? {} : { source: options.source }),\n });\n if (mismatch) throw new VectorMismatchError(mismatch);\n const queryVector = await embed(query);\n vector = options.vectors.search(queryVector, { limit });\n }\n\n const rankings = vector.length > 0 ? [lexical, vector] : [lexical];\n const candidates = rrfMerge(rankings).slice(0, limit);\n\n for (const candidate of candidates) trace.entry.push(candidate);\n return { candidates, lexical, vector, trace };\n}\n"],"mappings":";AASO,SAAS,WAAW,GAAW,GAAmB;AACvD,SAAO,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI;AAClC;;;ACWO,IAAM,KAAK;AAAA,EAChB,SAAS;AAAA,EACT,MAAM;AAAA,EACN,OAAO;AAAA,EACP,OAAO;AAAA,EACP,UAAU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ITLE","slice","XSD_STRING","last","node","child","key","chunk","promise","conditions","options","results","query","boosts","data"]}
|
|
1
|
+
{"version":3,"sources":["../../src/graph/core/sort.ts","../../src/graph/core/vocab.ts","../../src/graph/runtime/graph.ts","../../src/graph/runtime/trace.ts","../../src/graph/core/localizations.ts","../../src/graph/core/iirds.ts","../../src/graph/runtime/traverse.ts","../../src/graph/runtime/resolve.ts","../../src/graph/runtime/assemble.ts","../../src/graph/runtime/rdfjs.ts","../../node_modules/minisearch/src/SearchableMap/TreeIterator.ts","../../node_modules/minisearch/src/SearchableMap/fuzzySearch.ts","../../node_modules/minisearch/src/SearchableMap/SearchableMap.ts","../../node_modules/minisearch/src/MiniSearch.ts","../../src/graph/runtime/lexical.ts","../../src/graph/core/vector-index.ts","../../src/graph/runtime/vector.ts","../../src/graph/runtime/entry.ts"],"sourcesContent":["/**\n * The ordering primitive behind the determinism contract. Every sort that\n * reaches output — the file list, emitted subjects/predicates/objects, query\n * results — must go through this comparator so ordering never depends on\n * locale, ICU version, or platform, the way `String.prototype.localeCompare`\n * and `Array.prototype.sort`'s default string coercion do.\n */\n\n/** Locale-independent code-unit comparison for stable sorting. */\nexport function byCodeUnit(a: string, b: string): number {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n","/**\n * Namespace table. Standard vocabularies wherever a term exists; the custom\n * `graph:` namespace stays minimal, and the newest vocabulary document under\n * `ns/` defines every term it holds — a bidirectional drift guard in\n * test/graph/unit/vocabulary.test.ts enforces both directions. Neither the term\n * count nor the version is written here: both went stale the first time a term\n * was added, and the guard resolves the file rather than naming it. The prefix\n * set is fixed — every emitted graph carries the same header.\n *\n * The custom prefix is `graph:` and its namespace is the manni site's, which is\n * where it dereferences (proposal 0051 §7). Both were `dockg` until the tool\n * joined the family, and graph ADR 01030's rule — the namespace IRI must resolve\n * — is why they moved rather than staying: `hawkeyexl.github.io/dockg` never\n * served anything and never will.\n *\n * The block an author writes on a page is `graph:`, and the prefix is `graph:`\n * too. The spelling is shared but the things differ: the key names frontmatter,\n * the prefix abbreviates an IRI in emitted RDF, and the prefix carries the\n * tool's name because `…/manni/graph/ns#` is the tool's namespace. Nothing\n * collides: no other prefix in this table is `graph`, and a `graph:` CURIE typed\n * at `--predicates` or `--subject` expanded to nothing before.\n */\nexport const NS = {\n dcterms: \"http://purl.org/dc/terms/\",\n foaf: \"http://xmlns.com/foaf/0.1/\",\n graph: \"https://hawkeyexl.github.io/manni/graph/ns#\",\n iirds: \"http://iirds.tekom.de/iirds#\",\n iirdsSft: \"http://iirds.tekom.de/iirds/domain/software#\",\n prov: \"http://www.w3.org/ns/prov#\",\n rdf: \"http://www.w3.org/1999/02/22-rdf-syntax-ns#\",\n schema: \"https://schema.org/\",\n skos: \"http://www.w3.org/2004/02/skos/core#\",\n xsd: \"http://www.w3.org/2001/XMLSchema#\",\n} as const;\n\nexport type Prefix = keyof typeof NS;\n\n/** Prefixes in emission order (sorted by prefix name). */\nexport const PREFIXES: ReadonlyArray<[Prefix, string]> = (\n Object.entries(NS) as Array<[Prefix, string]>\n).sort(([a], [b]) => (a < b ? -1 : 1));\n\nexport const RDF_TYPE = `${NS.rdf}type`;\n\n/**\n * Role individuals for qualified provenance (prov:hadRole objects). Part of\n * the deliberately small graph vocabulary.\n */\nexport const ROLE = {\n author: `${NS.graph}authorRole`,\n generator: `${NS.graph}generatorRole`,\n tool: `${NS.graph}toolRole`,\n} as const;\n","/**\n * `GraphIndex` — the browser-native in-memory graph (ADR 01018).\n *\n * Built from `graph.jsonld` (the Phase 6 export) with **no RDF parser**: that\n * artifact is plain `JSON.parse`-able, deterministically sorted, and free of\n * blank nodes, so a `Map`-based adjacency index is all the runtime needs. Node\n * callers can also build from quads (`fromQuads`) so the CLI can read Turtle.\n *\n * Platform-neutral: no `node:` imports, no npm dependencies, no I/O — the\n * caller supplies the bytes. Type-only imports are erased at build time.\n *\n * Every accessor returns deterministically sorted results, so traversal order\n * (and therefore the trace) is byte-stable for a given graph.\n */\nimport type { Quad } from \"../core/derive.js\";\nimport { byCodeUnit } from \"../core/sort.js\";\nimport { RDF_TYPE } from \"../core/vocab.js\";\n\n/** An object value: an IRI reference or a literal. */\nexport type Value =\n | { kind: \"iri\"; value: string }\n | { kind: \"literal\"; value: string; datatype?: string; language?: string };\n\nexport interface GraphNode {\n id: string;\n /** Full class IRIs, sorted. */\n types: string[];\n /** Full predicate IRI → values, in insertion-normalized sorted order. */\n props: Map<string, Value[]>;\n}\n\n/** The parsed shape of a `graph.jsonld` document. */\ninterface JsonLdDoc {\n \"@context\"?: Record<string, string>;\n \"@graph\"?: unknown[];\n}\n\nconst XSD_STRING = \"http://www.w3.org/2001/XMLSchema#string\";\n\nfunction compareValues(a: Value, b: Value): number {\n if (a.kind !== b.kind) return a.kind === \"iri\" ? -1 : 1;\n const v = byCodeUnit(a.value, b.value);\n if (v !== 0) return v;\n const da = a.kind === \"literal\" ? (a.datatype ?? \"\") : \"\";\n const db = b.kind === \"literal\" ? (b.datatype ?? \"\") : \"\";\n const la = a.kind === \"literal\" ? (a.language ?? \"\") : \"\";\n const lb = b.kind === \"literal\" ? (b.language ?? \"\") : \"\";\n return byCodeUnit(da, db) || byCodeUnit(la, lb);\n}\n\nexport class GraphIndex {\n private readonly nodes = new Map<string, GraphNode>();\n /** subject → predicate → object IRIs (sorted). */\n private readonly outbound = new Map<string, Map<string, string[]>>();\n /** object → predicate → subject IRIs (sorted). */\n private readonly inbound = new Map<string, Map<string, string[]>>();\n /** class IRI → instance IRIs (sorted). */\n private readonly byType = new Map<string, string[]>();\n /** prefix → namespace, from the artifact's own `@context`. */\n readonly context: Record<string, string>;\n\n private constructor(context: Record<string, string>) {\n this.context = context;\n }\n\n /**\n * Build from a `graph.jsonld` document — a JSON string or the parsed object.\n * CURIE keys and `@type` values are expanded using the document's own\n * `@context`, so the index is self-describing.\n */\n static fromJsonLd(input: string | object): GraphIndex {\n const doc = (\n typeof input === \"string\" ? (JSON.parse(input) as JsonLdDoc) : input\n ) as JsonLdDoc;\n const context = doc[\"@context\"] ?? {};\n const index = new GraphIndex({ ...context });\n for (const raw of doc[\"@graph\"] ?? []) {\n index.addJsonLdNode(raw as Record<string, unknown>);\n }\n index.finalize();\n return index;\n }\n\n /** Build from dockg's internal quad shape (the Node/CLI path). */\n static fromQuads(quads: Quad[], context: Record<string, string> = {}) {\n const index = new GraphIndex({ ...context });\n for (const q of quads) {\n const o = q.o;\n const value: Value =\n o.kind === \"iri\"\n ? { kind: \"iri\", value: o.value }\n : o.language\n ? { kind: \"literal\", value: o.value, language: o.language }\n : o.datatype && o.datatype !== XSD_STRING\n ? { kind: \"literal\", value: o.value, datatype: o.datatype }\n : { kind: \"literal\", value: o.value };\n index.addTriple(q.s, q.p, value);\n }\n index.finalize();\n return index;\n }\n\n /** Expand a CURIE (`dcterms:title`) to a full IRI using `@context`. */\n expand(term: string): string {\n const colon = term.indexOf(\":\");\n if (colon <= 0) return term;\n const ns = this.context[term.slice(0, colon)];\n return ns ? `${ns}${term.slice(colon + 1)}` : term;\n }\n\n /** Compact a full IRI to a CURIE when a context namespace matches. */\n compact(iri: string): string {\n let best = iri;\n let bestNs = \"\";\n for (const [prefix, ns] of Object.entries(this.context)) {\n if (\n iri.startsWith(ns) &&\n iri.length > ns.length &&\n ns.length > bestNs.length\n ) {\n best = `${prefix}:${iri.slice(ns.length)}`;\n bestNs = ns;\n }\n }\n return best;\n }\n\n private addJsonLdNode(raw: Record<string, unknown>): void {\n const id = typeof raw[\"@id\"] === \"string\" ? this.expand(raw[\"@id\"]) : \"\";\n if (!id) return;\n this.ensureNode(id);\n\n const rawTypes = raw[\"@type\"];\n for (const t of toArray(rawTypes)) {\n if (typeof t === \"string\") {\n this.addTriple(id, RDF_TYPE, { kind: \"iri\", value: this.expand(t) });\n }\n }\n\n for (const [key, rawValue] of Object.entries(raw)) {\n if (key === \"@id\" || key === \"@type\") continue;\n const predicate = this.expand(key);\n for (const v of toArray(rawValue)) {\n const value = this.toValue(v);\n if (value) this.addTriple(id, predicate, value);\n }\n }\n }\n\n private toValue(v: unknown): Value | undefined {\n if (typeof v === \"string\") return { kind: \"literal\", value: v };\n if (typeof v === \"number\" || typeof v === \"boolean\") {\n return { kind: \"literal\", value: String(v) };\n }\n if (v && typeof v === \"object\") {\n const o = v as Record<string, unknown>;\n if (typeof o[\"@id\"] === \"string\") {\n return { kind: \"iri\", value: this.expand(o[\"@id\"]) };\n }\n if (o[\"@value\"] !== undefined) {\n const raw = o[\"@value\"];\n // JSON.stringify spells a number or boolean the way String() would,\n // and gives an object a lexical form instead of \"[object Object]\".\n const lexical = typeof raw === \"string\" ? raw : JSON.stringify(raw);\n if (typeof o[\"@language\"] === \"string\") {\n return { kind: \"literal\", value: lexical, language: o[\"@language\"] };\n }\n const dt =\n typeof o[\"@type\"] === \"string\" ? this.expand(o[\"@type\"]) : undefined;\n return dt && dt !== XSD_STRING\n ? { kind: \"literal\", value: lexical, datatype: dt }\n : { kind: \"literal\", value: lexical };\n }\n }\n return undefined;\n }\n\n private ensureNode(id: string): GraphNode {\n let node = this.nodes.get(id);\n if (!node) {\n node = { id, types: [], props: new Map() };\n this.nodes.set(id, node);\n }\n return node;\n }\n\n private addTriple(s: string, p: string, o: Value): void {\n const node = this.ensureNode(s);\n let values = node.props.get(p);\n if (!values) {\n values = [];\n node.props.set(p, values);\n }\n values.push(o);\n\n if (p === RDF_TYPE && o.kind === \"iri\") {\n node.types.push(o.value);\n const instances = this.byType.get(o.value);\n if (instances) instances.push(s);\n else this.byType.set(o.value, [s]);\n }\n\n if (o.kind === \"iri\") {\n addEdge(this.outbound, s, p, o.value);\n addEdge(this.inbound, o.value, p, s);\n // Referenced-only IRIs still resolve as (empty) nodes.\n this.ensureNode(o.value);\n }\n }\n\n /** Sort every collection so traversal order is deterministic. */\n private finalize(): void {\n for (const node of this.nodes.values()) {\n node.types.sort(byCodeUnit);\n for (const values of node.props.values()) values.sort(compareValues);\n }\n for (const instances of this.byType.values()) instances.sort(byCodeUnit);\n for (const map of [this.outbound, this.inbound]) {\n for (const preds of map.values()) {\n for (const targets of preds.values()) targets.sort(byCodeUnit);\n }\n }\n }\n\n /** Every node IRI, sorted. */\n ids(): string[] {\n return [...this.nodes.keys()].sort(byCodeUnit);\n }\n\n size(): number {\n return this.nodes.size;\n }\n\n node(iri: string): GraphNode | undefined {\n return this.nodes.get(iri);\n }\n\n has(iri: string): boolean {\n return this.nodes.has(iri);\n }\n\n /** Class IRIs of a node, sorted. */\n types(iri: string): string[] {\n return this.nodes.get(iri)?.types ?? [];\n }\n\n /** Instances of a class, sorted. */\n instancesOf(classIri: string): string[] {\n return this.byType.get(classIri) ?? [];\n }\n\n /** All values for a predicate, sorted. */\n values(iri: string, predicate: string): Value[] {\n return this.nodes.get(iri)?.props.get(predicate) ?? [];\n }\n\n /** Literal lexical forms for a predicate, sorted. */\n literals(iri: string, predicate: string): string[] {\n return this.values(iri, predicate)\n .filter((v) => v.kind === \"literal\")\n .map((v) => v.value);\n }\n\n /** The first literal for a predicate, if any. */\n literal(iri: string, predicate: string): string | undefined {\n return this.literals(iri, predicate)[0];\n }\n\n /** Outbound IRI targets: all predicates, or one. Sorted. */\n out(\n iri: string,\n predicate?: string,\n ): Array<{ predicate: string; target: string }> {\n return edges(this.outbound, iri, predicate);\n }\n\n /** Inbound IRI sources (who points at this node). Sorted. */\n in(\n iri: string,\n predicate?: string,\n ): Array<{ predicate: string; target: string }> {\n return edges(this.inbound, iri, predicate);\n }\n}\n\nfunction addEdge(\n map: Map<string, Map<string, string[]>>,\n key: string,\n predicate: string,\n target: string,\n): void {\n let preds = map.get(key);\n if (!preds) {\n preds = new Map();\n map.set(key, preds);\n }\n const targets = preds.get(predicate);\n if (targets) targets.push(target);\n else preds.set(predicate, [target]);\n}\n\nfunction edges(\n map: Map<string, Map<string, string[]>>,\n iri: string,\n predicate?: string,\n): Array<{ predicate: string; target: string }> {\n const preds = map.get(iri);\n if (!preds) return [];\n const out: Array<{ predicate: string; target: string }> = [];\n const keys = predicate ? [predicate] : [...preds.keys()].sort(byCodeUnit);\n for (const p of keys) {\n for (const target of preds.get(p) ?? []) out.push({ predicate: p, target });\n }\n return out;\n}\n\nfunction toArray(v: unknown): unknown[] {\n if (v === undefined || v === null) return [];\n return Array.isArray(v) ? v : [v];\n}\n","/**\n * Query trace — the explainability contract (ADR 01018). Every runtime stage\n * appends to a trace, and no API returns results without one: retrieval\n * provenance is part of the contract exactly as PROV provenance is part of the\n * build. The trace answers \"how and why did this result come back\": which nodes\n * were seeded, every hop walked, every node scope excluded (and by which rule),\n * and every content resolution attempted.\n *\n * Events are appended in traversal order, which is itself deterministic, so the\n * trace is byte-stable for a given graph + query.\n */\n\n/** How a seed was found. `hybrid` means several legs agreed on it. */\nexport type EntryVia = \"explicit\" | \"lexical\" | \"vector\" | \"hybrid\";\n\n/** A starting node, with the score/reason that made it a seed. */\nexport interface EntryCandidate {\n iri: string;\n /**\n * Relevance score: 1 for an explicitly requested seed, otherwise the fused\n * `rrfMerge` score. Note that fusion is **rank**-based, so a searched seed's\n * score reflects its position (1/(60 + rank)), not the engine's relevance —\n * it orders candidates but is not a magnitude to threshold on.\n */\n score: number;\n via: EntryVia;\n}\n\n/** One edge walked, in either direction. */\nexport interface Hop {\n from: string;\n predicate: string;\n to: string;\n /** Hops from the nearest seed (seeds are depth 0; their neighbors are 1). */\n depth: number;\n direction: \"out\" | \"in\";\n}\n\n/** A node the scope filter removed, and why. */\nexport interface ScopeExclusion {\n node: string;\n /**\n * The predicate that disqualified the node: a `graph:not*` IRI when an\n * explicit negative named the target, or the positive predicate (e.g.\n * `iirds:relates-to-product-variant`) when the node declared a scope set that\n * omits the target.\n */\n rule: string;\n /**\n * The filter target being applied — the variant or subject IRI the query\n * asked for. Under a `graph:not*` rule the node named this explicitly; under\n * a positive rule this is what the node's declared set was missing.\n */\n value: string;\n}\n\n/** One content-resolution attempt. */\nexport interface Resolution {\n iri: string;\n sourceUrl: string;\n ok: boolean;\n /** Present when `ok` is false. */\n error?: string;\n}\n\nexport interface QueryTrace {\n entry: EntryCandidate[];\n hops: Hop[];\n exclusions: ScopeExclusion[];\n resolutions: Resolution[];\n}\n\nexport function createTrace(): QueryTrace {\n return { entry: [], hops: [], exclusions: [], resolutions: [] };\n}\n\n/**\n * Every node named anywhere in the trace as reached — seeds plus hop targets.\n * The trace-completeness contract: a traversal's results must be a subset of\n * this, so every returned node is explainable by recorded events.\n */\nexport function reachedNodes(trace: QueryTrace): Set<string> {\n const reached = new Set<string>();\n for (const e of trace.entry) reached.add(e.iri);\n for (const h of trace.hops) reached.add(h.to);\n return reached;\n}\n","/**\n * The localization manifest (ADR 01038) — `graph/localizations.json`, the index of\n * indexes.\n *\n * Retrieval artifacts fan out per language: one `search.<lang>.json` and one\n * `vectors.<lang>.bin` each, because a single flat index over every locale\n * ranks across the boundary it exists to respect, and because one embedding\n * model cannot serve every language. The manifest is what makes that navigable\n * — a browser fetches this one small file, learns which localizations exist and\n * what each costs, and downloads only the pair it needs.\n *\n * Written by `manni graph export search`; `manni graph embed` fills in the\n * `vectors` block as it produces each sidecar, so a manifest entry without one\n * means exactly \"this language has no vectors yet\".\n *\n * No `node:` imports: the CLI writes it and the browser runtime reads it.\n */\nimport { byCodeUnit } from \"./sort.js\";\n\n/** Conventional filename, written beside the graph. */\nexport const LOCALIZATIONS_FILENAME = \"localizations.json\";\n\n/**\n * BCP-47's tag for undetermined, used as the bucket for documents that declare\n * no language. A real tag rather than a dockg invention, so a consumer that\n * knows BCP-47 already knows what it means — and so the bucket sorts, filters,\n * and names a file like any other language.\n */\nexport const UNDETERMINED = \"und\";\n\n/**\n * BCP-47's common shape: language(2-3) + optional script(4) + optional\n * region(2 alpha or 3 digit) + variants. Accepts de, de-DE, zh-Hans,\n * zh-Hans-CN, pt-BR and und; rejects English and de_DE.\n *\n * The same grammar appears in `config-schema.json` (for `routes[].language` and\n * `embed.byLanguage`) and in `shapes/graph/shapes-1.1.0.ttl` (for `dcterms:language`).\n * This copy exists because a tag also becomes a **filename**, and the shapes\n * only run under `manni graph check` — an unvalidated literal from the graph would\n * otherwise reach `writeFileSync` as a path segment. `test/unit/schema-sync.test.ts`\n * pins all three to each other.\n */\nexport const LANGUAGE_TAG =\n /^[A-Za-z]{2,3}(-[A-Za-z]{4})?(-([A-Za-z]{2}|[0-9]{3}))?(-([A-Za-z0-9]{5,8}|[0-9][A-Za-z0-9]{3}))*$/;\n\n/** Whether a string is usable as a language tag — and so as a filename segment. */\nexport function isLanguageTag(value: string): boolean {\n return LANGUAGE_TAG.test(value);\n}\n\n/**\n * The canonical spelling of a BCP-47 tag: `en-us` and `EN-US` both become\n * `en-US`. Tags are case-insensitive, so without this one locale splits into\n * two indexes and a filter matches only the spelling its author happened to\n * type. A string `Intl` refuses comes back as written, so the tag check that\n * guards filenames still sees, and reports, what the author wrote.\n *\n * `Intl` exists in every browser, so the runtime calls this too.\n */\nexport function canonicalLanguageTag(tag: string): string {\n try {\n return Intl.getCanonicalLocales(tag)[0] ?? tag;\n } catch {\n return tag;\n }\n}\n\n/** Where one language's lexical index lives, and what it holds. */\nexport interface SearchArtifact {\n /** Filename, relative to the manifest. */\n path: string;\n /** Indexed nodes. */\n entries: number;\n /** `sha256:…` of the file, so a consumer can detect a stale pair. */\n digest: string;\n}\n\n/** Where one language's vector sidecar lives, and what produced it. */\nexport interface VectorArtifact {\n path: string;\n /** The embedding model this language was embedded with. */\n model: string;\n dtype: string;\n dims: number;\n count: number;\n}\n\nexport interface LocalizationEntry {\n /** BCP-47 tag, or `und` for the undeclared bucket. */\n language: string;\n /** Documents in this language (sections excluded). */\n documents: number;\n search: SearchArtifact;\n /** Absent until `manni graph embed` has run for this language. */\n vectors?: VectorArtifact;\n}\n\nexport interface LocalizationsDoc {\n version: 1;\n /** One entry per language present, sorted by tag. */\n languages: LocalizationEntry[];\n}\n\n/** `search.de.json` — the lexical index for one language. */\nexport function searchIndexFilename(language: string): string {\n return `search.${language}.json`;\n}\n\n/** `vectors.de.bin` — the vector sidecar for one language. */\nexport function vectorIndexFilename(language: string): string {\n return `vectors.${language}.bin`;\n}\n\n/**\n * Serialize the manifest: sorted by language, two-space indent, trailing\n * newline — byte-stable like every other dockg artifact.\n */\nexport function emitLocalizations(doc: LocalizationsDoc): string {\n const languages = [...doc.languages].sort((a, b) =>\n byCodeUnit(a.language, b.language),\n );\n return `${JSON.stringify({ version: doc.version, languages }, null, 2)}\\n`;\n}\n\n/**\n * Parse and shape-check a manifest. Returns undefined for anything else.\n *\n * Every entry is checked, not just the envelope: callers reach straight for\n * `entry.search.path`, and a truncated or hand-edited file would otherwise\n * dereference `undefined` and surface as a raw TypeError with exit 1 rather\n * than the operational error (exit 2) an unreadable artifact owes.\n */\n/** A plain JSON object — not `null`, not an array. */\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\nexport function parseLocalizations(text: string): LocalizationsDoc | undefined {\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return undefined;\n }\n // Checked as `unknown`. Casting to `LocalizationsDoc` first would hand the\n // compiler the answer to the question this function exists to ask, and every\n // guard below would then read as a test that cannot fail.\n if (!isRecord(parsed)) return undefined;\n if (parsed[\"version\"] !== 1 || !Array.isArray(parsed[\"languages\"])) {\n return undefined;\n }\n for (const entry of parsed[\"languages\"] as unknown[]) {\n if (!isRecord(entry)) return undefined;\n const language = entry[\"language\"];\n const search = entry[\"search\"];\n if (\n typeof language !== \"string\" ||\n !isLanguageTag(language) ||\n typeof entry[\"documents\"] !== \"number\" ||\n !isRecord(search) ||\n typeof search[\"path\"] !== \"string\" ||\n typeof search[\"entries\"] !== \"number\" ||\n typeof search[\"digest\"] !== \"string\" ||\n !ownsFilename(search[\"path\"], searchIndexFilename(language))\n ) {\n return undefined;\n }\n const v = entry[\"vectors\"];\n if (v !== undefined) {\n if (\n !isRecord(v) ||\n typeof v[\"path\"] !== \"string\" ||\n typeof v[\"model\"] !== \"string\" ||\n typeof v[\"dtype\"] !== \"string\" ||\n typeof v[\"dims\"] !== \"number\" ||\n typeof v[\"count\"] !== \"number\" ||\n // Same constraint `search.path` gets: the last segment must be the\n // filename this language's sidecar would be given. Without it,\n // `isSafeRelativePath` alone leaves `vectors.path` far more reachable\n // than `search.path` — and `search --mode vector` opens it.\n !ownsFilename(v[\"path\"], vectorIndexFilename(language))\n ) {\n return undefined;\n }\n }\n }\n return parsed as unknown as LocalizationsDoc;\n}\n\n/**\n * A path from the manifest is joined onto a directory and opened, so it is\n * checked like any other untrusted path segment.\n *\n * `export` refuses to *write* a filename it built from a bad language tag; this\n * is the same hole on the read side, reached through a manifest instead of\n * through frontmatter. A hand-edited `\"path\": \"../../etc/passwd\"` would\n * otherwise be joined and read by `embed` and `search`.\n *\n * Rejects an absolute path, a Windows drive letter, a backslash, and any `.`\n * or empty segment. `..` is allowed **only as a prefix**, so `a/../../x` — an\n * escape wearing a normal first segment — is refused while `../vecs/x.bin`,\n * the layout `embed -o` produces, is not.\n *\n * How far up a leading run may climb is deliberately *not* capped. It was,\n * briefly, and the cap rejected manifests `embed -o` itself writes: a sidecar\n * directory two levels from the index directory produced an artifact set dockg\n * could not read back. The bound that matters is `ownsFilename` — a crafted\n * manifest can only ever name a file already called `search.<lang>.json` or\n * `vectors.<lang>.bin`, which is a long way from arbitrary-file read, and no\n * number of `..` segments widens it.\n */\nexport function isSafeRelativePath(path: string): boolean {\n if (path === \"\" || path.startsWith(\"/\") || /^[A-Za-z]:/.test(path)) {\n return false;\n }\n if (path.includes(\"\\\\\")) return false;\n const segments = path.split(\"/\");\n let leading = true;\n for (const segment of segments) {\n if (segment === \"\" || segment === \".\") return false;\n if (segment === \"..\") {\n if (!leading) return false;\n continue;\n }\n leading = false;\n }\n return true;\n}\n\n/**\n * The path is relative-safe *and* its last segment is the filename this\n * language's artifact would be given.\n *\n * The filename check is the constraint that actually narrows what a crafted\n * manifest can reach: `isSafeRelativePath` bounds the directory it can point\n * into, this bounds the file.\n */\nfunction ownsFilename(path: string, expected: string): boolean {\n if (!isSafeRelativePath(path)) return false;\n return path.slice(path.lastIndexOf(\"/\") + 1) === expected;\n}\n","/**\n * iiRDS Core + Software-domain term IRIs and the frontmatter-value → IRI maps\n * (ADR 01012). Every IRI here is byte-verified against the published\n * `iirds-core.rdf` / `iirds-software.rdf` in iirds-consortium/models. dockg\n * references these IRIs; it never redefines or re-types them (iiRDS is\n * CC BY-ND). This is the single source of truth shared by the schema\n * (via the schema-sync drift guard), derive, and shapes.\n */\nimport { NS } from \"./vocab.js\";\n\n/** Predicates (Core). */\nexport const IIRDS_HAS_TOPIC_TYPE = `${NS.iirds}has-topic-type`;\nexport const IIRDS_RELATES_TO_PRODUCT_VARIANT = `${NS.iirds}relates-to-product-variant`;\nexport const IIRDS_RELATES_TO_LIFECYCLE_PHASE = `${NS.iirds}relates-to-product-lifecycle-phase`;\nexport const IIRDS_HAS_SUBJECT = `${NS.iirds}has-subject`;\n\n/** Class minted for `graph.applies-to` nodes. */\nexport const IIRDS_PRODUCT_VARIANT = `${NS.iirds}ProductVariant`;\n\n/**\n * Package-serialization terms (iiRDS package export, ADR 01017). Local names\n * byte-verified against the canonical RDF/XML example in the published spec\n * (`sections/structure/serialization.md`). Used only by the package projection —\n * never emitted into the built graph. IUs are typed `iirds:Topic` (the subclass\n * that carries `has-topic-type`/`has-subject`), one of the valid IU subclasses.\n */\nexport const IIRDS_PACKAGE = `${NS.iirds}Package`;\nexport const IIRDS_IIRDS_VERSION = `${NS.iirds}iiRDSVersion`;\nexport const IIRDS_TOPIC = `${NS.iirds}Topic`;\nexport const IIRDS_IS_PART_OF_PACKAGE = `${NS.iirds}is-part-of-package`;\nexport const IIRDS_HAS_RENDITION = `${NS.iirds}has-rendition`;\nexport const IIRDS_RENDITION = `${NS.iirds}Rendition`;\nexport const IIRDS_SOURCE = `${NS.iirds}source`;\nexport const IIRDS_FORMAT = `${NS.iirds}format`;\nexport const IIRDS_TITLE = `${NS.iirds}title`;\nexport const IIRDS_LANGUAGE = `${NS.iirds}language`;\nexport const IIRDS_PARTY = `${NS.iirds}Party`;\nexport const IIRDS_HAS_PARTY_ROLE = `${NS.iirds}has-party-role`;\nexport const IIRDS_CREATOR = `${NS.iirds}Creator`;\nexport const IIRDS_RELATES_TO_PARTY = `${NS.iirds}relates-to-party`;\nexport const IIRDS_RELATES_TO_VCARD = `${NS.iirds}relates-to-vcard`;\n\n/** vcard namespace — package-local (not in the global NS/PREFIXES table). */\nexport const VCARD_NS = \"http://www.w3.org/2006/vcard/ns#\";\nexport const VCARD_ORGANIZATION = `${VCARD_NS}Organization`;\nexport const VCARD_ORGANIZATION_NAME = `${VCARD_NS}organization-name`;\n\n/**\n * Negative-scope predicates (ADR 01014). Minted into `graph:` — no standard\n * term exists, and OWL negative property assertions require blank nodes. Each\n * mirrors, and is SHACL-disjoint from, its positive counterpart above.\n */\nexport const GRAPH_NOT_APPLICABLE_TO_VARIANT = `${NS.graph}notApplicableToVariant`;\nexport const GRAPH_NOT_SOFTWARE_SUBJECT = `${NS.graph}notSoftwareSubject`;\n\n/**\n * Page-level `type` → `graph.type` (ADR 01024). The page's `type` is an open\n * vocabulary (docmeta:core); `graph.type` is the closed iiRDS enum. When the block\n * is silent, the page's value derives one through this map — an unmapped page\n * type derives nothing rather than inventing a topic type. An explicit\n * `graph.type` always wins: deeper wins, the page level is the fallback.\n */\nexport const PAGE_TYPE_TO_TOPIC_TYPE: Readonly<Record<string, string>> = {\n \"how-to\": \"task\",\n tutorial: \"learning\",\n explanation: \"concept\",\n reference: \"reference\",\n troubleshooting: \"troubleshooting\",\n};\n\n/** `graph.type` value → `iirds:has-topic-type` object IRI. */\nexport const TOPIC_TYPE_IRIS: Readonly<Record<string, string>> = {\n task: `${NS.iirds}GenericTask`,\n concept: `${NS.iirds}GenericConcept`,\n reference: `${NS.iirds}GenericReference`,\n learning: `${NS.iirds}GenericLearning`,\n troubleshooting: `${NS.iirds}GenericTroubleshooting`,\n form: `${NS.iirds}GenericForm`,\n};\n\n/**\n * `graph.about-product-lifecycle` value → `iirds:relates-to-product-lifecycle-phase`\n * object IRI (Software domain: iirds:Use/PuttingToUse/AfterUse instances).\n */\nexport const SOFTWARE_LIFECYCLE_IRIS: Readonly<Record<string, string>> = {\n administration: `${NS.iirdsSft}Administration`,\n customization: `${NS.iirdsSft}Customization`,\n update: `${NS.iirdsSft}Update`,\n deployment: `${NS.iirdsSft}Deployment`,\n integration: `${NS.iirdsSft}Integration`,\n deinstallation: `${NS.iirdsSft}Deinstallation`,\n};\n\n/**\n * `graph.about-product-aspect` value → `iirds:has-subject` object IRI (Software domain:\n * iirds:TechnicalOverview/TechnicalData instances).\n */\nexport const SOFTWARE_SUBJECT_IRIS: Readonly<Record<string, string>> = {\n architecture: `${NS.iirdsSft}Architecture`,\n interface: `${NS.iirdsSft}Interface`,\n \"system-requirement\": `${NS.iirdsSft}SystemRequirement`,\n};\n","/**\n * The deterministic walker (ADR 01018) — breadth-first traversal over a\n * `GraphIndex` with scope filtering, recording every hop and every exclusion\n * into a `QueryTrace`. This is the engine: generic RDF engines return bindings\n * without the path that produced them, and dockg's scope rules (ADR 01014)\n * are domain semantics no general engine knows.\n *\n * Determinism: neighbors come back sorted from the index, the frontier is\n * processed in (depth, IRI) order, and results are emitted in discovery order —\n * so the same graph + query always yields the same nodes *and* the same trace.\n *\n * Platform-neutral: no `node:` imports, no npm dependencies.\n */\nimport { byCodeUnit } from \"../core/sort.js\";\nimport { NS, RDF_TYPE } from \"../core/vocab.js\";\nimport { canonicalLanguageTag } from \"../core/localizations.js\";\nimport {\n GRAPH_NOT_APPLICABLE_TO_VARIANT,\n GRAPH_NOT_SOFTWARE_SUBJECT,\n IIRDS_HAS_SUBJECT,\n IIRDS_RELATES_TO_PRODUCT_VARIANT,\n SOFTWARE_SUBJECT_IRIS,\n} from \"../core/iirds.js\";\nimport type { GraphIndex } from \"./graph.js\";\nimport { createTrace, type QueryTrace, type ScopeExclusion } from \"./trace.js\";\n\nconst DCTERMS_TITLE = `${NS.dcterms}title`;\nconst DCTERMS_REFERENCES = `${NS.dcterms}references`;\nconst DCTERMS_LANGUAGE = `${NS.dcterms}language`;\n\n/** A section IRI's document, or the IRI itself when it has no fragment. */\nfunction documentOf(iri: string): string {\n const hash = iri.indexOf(\"#\");\n return hash === -1 ? iri : iri.slice(0, hash);\n}\n\nexport type Direction = \"out\" | \"in\" | \"both\";\n\nexport interface ScopeFilter {\n /** Product variant: an IRI, a `dcterms:title` (e.g. \"SP-X100\"), or a slug. */\n variant?: string;\n /** Software subject: an IRI or a `graph.about-product-aspect` value (e.g. \"architecture\"). */\n subject?: string;\n /**\n * BCP-47 tag (ADR 01037). Matched against `dcterms:language` after both are\n * canonicalized, since tags are case-insensitive. There is no fallback:\n * `de-AT` is not `de`, because relatedness between locales is an inference\n * and this runtime does not infer.\n */\n language?: string;\n}\n\nexport interface TraverseOptions extends ScopeFilter {\n /** Starting nodes (IRIs). */\n seeds: string[];\n /** Maximum hops from a seed. Default 1. */\n depth?: number;\n /** Restrict to these predicates (full IRIs). Default: every predicate. */\n predicates?: string[];\n /** Which edge directions to follow. Default \"out\". */\n direction?: Direction;\n /** Stop after this many nodes (seeds included). */\n limit?: number;\n /**\n * Follow `rdf:type` edges into class nodes. Default false, deliberately:\n * class nodes are schema, not content, and every document shares them — so\n * traversing them makes every document reachable from every other in two\n * hops (`a → graph:Document → b`). That is exactly the edge contamination\n * graph-governed retrieval exists to avoid. A `predicates` list that names\n * `rdf:type` follows them too, because it asked for them by name.\n */\n includeTypeEdges?: boolean;\n /** Append to an existing trace instead of starting a new one. */\n trace?: QueryTrace;\n}\n\nexport interface TraversedNode {\n iri: string;\n /** Hops from the nearest seed; seeds are 0. */\n depth: number;\n}\n\nexport interface TraverseResult {\n nodes: TraversedNode[];\n trace: QueryTrace;\n}\n\n/**\n * Resolve a variant input to its IRI: an exact node IRI, a `dcterms:title`\n * match on an `iirds:ProductVariant`, or a trailing-segment slug match.\n */\nexport function resolveVariant(\n graph: GraphIndex,\n input: string,\n): string | undefined {\n if (graph.has(input)) return input;\n const wanted = input.toLowerCase();\n const variants = graph.instancesOf(`${NS.iirds}ProductVariant`);\n for (const v of variants) {\n if (graph.literal(v, DCTERMS_TITLE)?.toLowerCase() === wanted) return v;\n }\n for (const v of variants) {\n if (v.slice(v.lastIndexOf(\"/\") + 1).toLowerCase() === wanted) return v;\n }\n return undefined;\n}\n\n/** Resolve a software-subject input to its iiRDS IRI. */\nexport function resolveSubject(\n graph: GraphIndex,\n input: string,\n): string | undefined {\n const mapped = SOFTWARE_SUBJECT_IRIS[input.toLowerCase()];\n if (mapped) return mapped;\n const expanded = graph.expand(input);\n return expanded.startsWith(\"http\") ? expanded : undefined;\n}\n\n/**\n * Decide whether a node survives the scope filter, and if not, why.\n *\n * Rules, in the spirit of ADR 01014 (absence of a positive claim is not a\n * negative claim, so both polarities are explicit):\n * - An explicit negative (`graph:notApplicableToVariant` /\n * `graph:notSoftwareSubject`) naming the target **excludes** the node.\n * - A node that declares a positive set which omits the target is **excluded**\n * — it scoped itself elsewhere — recorded under the positive predicate so\n * the trace distinguishes this from an explicit negative.\n * - A node that makes no claim is **kept**: unscoped content applies broadly.\n */\nexport function scopeExclusion(\n graph: GraphIndex,\n iri: string,\n scope: { variantIri?: string; subjectIri?: string; language?: string },\n): ScopeExclusion | undefined {\n // [target, positive predicate, negative predicate, object kind]. Language\n // joins the same table with two differences, both deliberate: its objects are\n // literals, and it has **no negative predicate** — a document has one\n // language (`sh:maxCount 1`), so \"not in German\" is not a claim an author\n // makes and there is nothing for a `graph:not*` term to express (ADR 01037).\n const checks: Array<\n [string | undefined, string, string | undefined, \"iri\" | \"literal\"]\n > = [\n [\n scope.variantIri,\n IIRDS_RELATES_TO_PRODUCT_VARIANT,\n GRAPH_NOT_APPLICABLE_TO_VARIANT,\n \"iri\",\n ],\n [scope.subjectIri, IIRDS_HAS_SUBJECT, GRAPH_NOT_SOFTWARE_SUBJECT, \"iri\"],\n [scope.language, DCTERMS_LANGUAGE, undefined, \"literal\"],\n ];\n for (const [target, positive, negative, kind] of checks) {\n if (!target) continue;\n if (negative !== undefined) {\n const denied = graph\n .values(iri, negative)\n .some((v) => v.kind === kind && v.value === target);\n if (denied) return { node: iri, rule: negative, value: target };\n }\n\n // Language is the one dimension a section inherits. Applicability is\n // explicit-only by ADR 01013 — a section may legitimately scope itself\n // differently from its document — but a section's *text* is in its\n // document's language and cannot differ, and the per-locale indexes file it\n // that way (`partitionByLanguage`). Without this a link with an anchor\n // reaches a section directly (derive.ts mints section IRIs as\n // `dcterms:references` targets) and carries English prose past a `de`\n // filter that excluded the document it belongs to.\n const subject = positive === DCTERMS_LANGUAGE ? documentOf(iri) : iri;\n const claimed = graph.values(subject, positive);\n if (claimed.length > 0) {\n const matches = claimed.some(\n (v) => v.kind === kind && v.value === target,\n );\n if (!matches) return { node: iri, rule: positive, value: target };\n }\n }\n return undefined;\n}\n\n/** Breadth-first traversal with scope filtering and full trace recording. */\nexport function traverse(\n graph: GraphIndex,\n options: TraverseOptions,\n): TraverseResult {\n const trace = options.trace ?? createTrace();\n const maxDepth = options.depth ?? 1;\n const direction: Direction = options.direction ?? \"out\";\n const allowed =\n options.predicates && options.predicates.length > 0\n ? new Set(options.predicates.map((p) => graph.expand(p)))\n : undefined;\n\n const variantIri = options.variant\n ? resolveVariant(graph, options.variant)\n : undefined;\n const subjectIri = options.subject\n ? resolveSubject(graph, options.subject)\n : undefined;\n // Language needs no resolution step, only a spelling: the filter value and\n // the graph value are both BCP-47 tags, and `derive` writes the canonical one.\n const language =\n options.language === undefined\n ? undefined\n : canonicalLanguageTag(options.language);\n const scope = { variantIri, subjectIri, language };\n // A predicate list that names `rdf:type` asked for type edges. Dropping them\n // anyway answered a question nobody asked, with an empty result.\n const followTypes =\n options.includeTypeEdges === true || allowed?.has(RDF_TYPE) === true;\n\n const excluded = new Set<string>();\n const keep = (iri: string): boolean => {\n if (excluded.has(iri)) return false;\n const exclusion = scopeExclusion(graph, iri, scope);\n if (exclusion) {\n excluded.add(iri);\n trace.exclusions.push(exclusion);\n return false;\n }\n return true;\n };\n\n const nodes: TraversedNode[] = [];\n const seen = new Set<string>();\n let frontier: string[] = [];\n\n // A seed `findEntry` already recorded keeps its real provenance. Re-recording\n // it as `explicit`/1 would leave the trace answering \"why did retrieval start\n // here?\" twice, with the lexical/vector score contradicted by a flat 1.\n const alreadySeeded = new Set(trace.entry.map((e) => e.iri));\n\n for (const seed of [...options.seeds].sort(byCodeUnit)) {\n if (!graph.has(seed) || seen.has(seed)) continue;\n seen.add(seed);\n if (!alreadySeeded.has(seed)) {\n trace.entry.push({ iri: seed, score: 1, via: \"explicit\" });\n }\n // A seed always expands, even when the scope filter excludes it. The\n // filter governs what the walk *reaches*, not where the caller chose to\n // start — and the canonical query is exactly this shape: from an English\n // page, `--impact --lang de` asks what German content a change here\n // affects. Gating the seed made that return nothing at all, because the\n // seed excluded itself before the frontier was ever populated.\n //\n // It is still kept out of the results and recorded in the trace, so the\n // answer honors the filter even though the walk started outside it.\n if (keep(seed)) nodes.push({ iri: seed, depth: 0 });\n frontier.push(seed);\n }\n\n const limit = options.limit ?? Infinity;\n for (let depth = 1; depth <= maxDepth && frontier.length > 0; depth++) {\n const next: string[] = [];\n for (const from of frontier) {\n if (nodes.length >= limit) break;\n for (const { predicate, target, dir } of neighbors(\n graph,\n from,\n direction,\n )) {\n if (allowed && !allowed.has(predicate)) continue;\n if (!followTypes && predicate === RDF_TYPE) continue;\n // The hop is recorded before filtering: the trace shows the edge was\n // walked even when the target is then scope-excluded.\n trace.hops.push({ from, predicate, to: target, depth, direction: dir });\n if (seen.has(target)) continue;\n seen.add(target);\n if (!keep(target)) continue;\n if (nodes.length >= limit) break;\n nodes.push({ iri: target, depth });\n next.push(target);\n }\n }\n frontier = next;\n }\n\n return { nodes, trace };\n}\n\nfunction neighbors(\n graph: GraphIndex,\n iri: string,\n direction: Direction,\n): Array<{ predicate: string; target: string; dir: \"out\" | \"in\" }> {\n const out: Array<{ predicate: string; target: string; dir: \"out\" | \"in\" }> =\n [];\n if (direction === \"out\" || direction === \"both\") {\n for (const e of graph.out(iri)) out.push({ ...e, dir: \"out\" });\n }\n if (direction === \"in\" || direction === \"both\") {\n for (const e of graph.in(iri)) out.push({ ...e, dir: \"in\" });\n }\n return out;\n}\n\n/** Who links to this node (one hop inbound over `dcterms:references`). */\nexport function reverseReferences(\n graph: GraphIndex,\n iri: string,\n options: Omit<TraverseOptions, \"seeds\" | \"direction\" | \"predicates\"> = {},\n): TraverseResult {\n return traverse(graph, {\n ...options,\n seeds: [iri],\n direction: \"in\",\n predicates: [DCTERMS_REFERENCES],\n depth: options.depth ?? 1,\n });\n}\n\n/**\n * Transitive inbound reach — \"what is affected if this node changes\".\n * Excludes the node itself from the returned set. Defaults to depth 3 rather\n * than the walker's 1, because impact analysis is only useful transitively.\n */\nexport function impact(\n graph: GraphIndex,\n iri: string,\n options: Omit<TraverseOptions, \"seeds\" | \"direction\"> = {},\n): TraverseResult {\n const result = traverse(graph, {\n ...options,\n seeds: [iri],\n direction: \"in\",\n depth: options.depth ?? 3,\n // The seed *may* occupy a slot in the walker's limit, so ask for one more:\n // `limit` means \"this many *affected* nodes\". Whether it actually takes\n // one depends on the scope filter — a seed the filter excludes still\n // expands but is not in `nodes` — so the slack is trimmed below rather\n // than assumed spent.\n limit: options.limit === undefined ? undefined : options.limit + 1,\n });\n const affected = result.nodes.filter((n) => n.iri !== iri);\n return {\n nodes:\n options.limit === undefined ? affected : affected.slice(0, options.limit),\n trace: result.trace,\n };\n}\n","/**\n * Content resolution (ADR 01018): graph node → the text it stands for.\n *\n * The graph is an index over documents ([ADR 01008](../../adrs/01008-graph-as-index-not-corpus.md)),\n * so retrieval must go back to the source to get text. The seam is a\n * `ContentResolver`; the shipped implementation uses `fetch`, which works\n * unchanged in browsers and in Node ≥18, and is injectable for tests.\n *\n * Section nodes (`doc.md#slug`) resolve by fetching the parent document and\n * slicing it at the heading whose text matches the section's `dcterms:title`\n * — so no line-span predicates need to be added to the graph.\n *\n * Platform-neutral: no `node:` imports, no npm dependencies.\n */\nimport { NS } from \"../core/vocab.js\";\nimport type { GraphIndex } from \"./graph.js\";\nimport type { QueryTrace } from \"./trace.js\";\n\nconst GRAPH_PATH = `${NS.graph}path`;\nconst DCTERMS_TITLE = `${NS.dcterms}title`;\nconst DCTERMS_HAS_PART = `${NS.dcterms}hasPart`;\nconst GRAPH_LEVEL = `${NS.graph}level`;\nconst GRAPH_ORDER = `${NS.graph}order`;\n\nexport interface ResolvedContent {\n iri: string;\n text: string;\n sourceUrl: string;\n title?: string;\n}\n\nexport interface ContentResolver {\n /** Text for a node, or undefined when the node has no content. */\n resolve(iri: string): Promise<ResolvedContent | undefined>;\n}\n\ntype FetchLike = (\n url: string,\n) => Promise<{ ok: boolean; status: number; text(): Promise<string> }>;\n\nexport interface FetchResolverOptions {\n /** Prefix joined to each `graph:path`, e.g. \"https://site/raw/\". */\n baseUrl?: string;\n /** Full control over path → URL. Overrides `baseUrl`. */\n pathToUrl?: (path: string) => string;\n /** Injectable fetch (defaults to the global). */\n fetch?: FetchLike;\n /** Record resolutions here. */\n trace?: QueryTrace;\n}\n\n/** Split a section IRI into its document IRI and fragment. */\nexport function splitFragment(iri: string): { doc: string; fragment?: string } {\n const hash = iri.indexOf(\"#\");\n return hash < 0\n ? { doc: iri }\n : { doc: iri.slice(0, hash), fragment: iri.slice(hash + 1) };\n}\n\n/**\n * Mark every line that sits inside a fenced code block (including the fence\n * delimiters themselves). Without this, a shell comment in a code sample —\n * `# Set the API key` — reads as an h1 and truncates the surrounding section,\n * which silently drops most of the retrieved content.\n *\n * CommonMark rules, minus the ones a heading scan cannot observe: a fence opens\n * on 3+ backticks or tildes indented at most 3 spaces, a backtick fence's info\n * string may not contain a backtick, and it closes on a delimiter of the same\n * character that is at least as long and carries no info string. An unclosed\n * fence runs to end of document.\n */\nfunction fencedLines(lines: string[]): boolean[] {\n const mask = new Array<boolean>(lines.length).fill(false);\n let open: string | undefined;\n for (const [i, line] of lines.entries()) {\n const m = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line);\n // Both groups are mandatory in the pattern, so a match carries both.\n // Requiring them is the check that proves it, and it replaces the bare\n // `m &&` the branches already tested — no condition is added, only\n // sharpened.\n const delimiter = m?.[1];\n const info = m?.[2];\n const isFence = delimiter !== undefined && info !== undefined;\n if (open === undefined) {\n if (isFence && !(delimiter.startsWith(\"`\") && info.includes(\"`\"))) {\n open = delimiter;\n mask[i] = true;\n }\n continue;\n }\n mask[i] = true;\n if (\n isFence &&\n delimiter[0] === open[0] &&\n delimiter.length >= open.length &&\n info.trim() === \"\"\n ) {\n open = undefined;\n }\n }\n return mask;\n}\n\n/** One heading as the source spells it, located by the line it starts on. */\ninterface SourceHeading {\n /** First line: the `#` line, or a setext heading's first line of text. */\n start: number;\n level: number;\n /** The heading's raw inline text, markdown and all. */\n text: string;\n}\n\nconst ATX = /^ {0,3}(#{1,6})(?:[ \\t]+(.*?))?[ \\t]*$/;\nconst SETEXT_UNDERLINE = /^ {0,3}(=+|-+)[ \\t]*$/;\n\n/**\n * Whether a line can be paragraph text, which a setext underline turns into a\n * heading. A blank line, an ATX heading, a list item, a block quote, a\n * thematic break and indented code cannot.\n */\nfunction isParagraphLine(line: string): boolean {\n if (line.trim() === \"\") return false;\n if (ATX.test(line)) return false;\n if (/^ {0,3}([-+*]|\\d{1,9}[.)])([ \\t]|$)/.test(line)) return false;\n if (/^ {0,3}>/.test(line)) return false;\n if (/^ {0,3}([-*_])([ \\t]*\\1){2,}[ \\t]*$/.test(line)) return false;\n return !/^ {4}/.test(line);\n}\n\n/**\n * How many leading lines a YAML frontmatter block takes, delimiters included.\n * Its closing `---` follows a line of text, so without this the scan would\n * read the last frontmatter key as a setext heading.\n */\nfunction frontmatterLength(lines: string[]): number {\n if (lines[0]?.trim() !== \"---\") return 0;\n for (let i = 1; i < lines.length; i++) {\n const line = lines[i]?.trim();\n if (line === \"---\" || line === \"...\") return i + 1;\n }\n return 0;\n}\n\n/**\n * Every heading in a markdown source, in order. ATX headings may sit up to\n * three spaces in and lose any closing `#` run. Setext headings are\n * underlined with `=` or `-`. Fenced code and frontmatter hold none.\n *\n * Line-based, so a shape remark reads and this does not is possible. The\n * common ones are covered, and a miss leaves one section unindexed.\n */\nfunction sourceHeadings(lines: string[]): SourceHeading[] {\n const fenced = fencedLines(lines);\n const skip = frontmatterLength(lines);\n const headings: SourceHeading[] = [];\n /** First line of the paragraph the scan is inside, or -1. */\n let paragraph = -1;\n for (const [i, line] of lines.entries()) {\n if (i < skip || fenced[i]) {\n paragraph = -1;\n continue;\n }\n const atx = ATX.exec(line);\n const hashes = atx?.[1];\n if (hashes !== undefined) {\n // A closing run is `#`s after whitespace, or the whole content.\n const text = (atx?.[2] ?? \"\").replace(/(^|[ \\t]+)#+$/, \"\");\n headings.push({ start: i, level: hashes.length, text });\n paragraph = -1;\n continue;\n }\n const underline = SETEXT_UNDERLINE.exec(line)?.[1];\n if (underline !== undefined && paragraph >= 0) {\n headings.push({\n start: paragraph,\n level: underline.startsWith(\"=\") ? 1 : 2,\n text: lines.slice(paragraph, i).join(\"\\n\"),\n });\n paragraph = -1;\n continue;\n }\n if (isParagraphLine(line)) {\n if (paragraph < 0) paragraph = i;\n } else {\n paragraph = -1;\n }\n }\n return headings;\n}\n\nconst ENTITIES: Record<string, string> = {\n amp: \"&\",\n lt: \"<\",\n gt: \">\",\n quot: '\"',\n apos: \"'\",\n nbsp: \" \",\n};\n\n/** Decode the character references a heading is likely to carry. */\nfunction decodeEntities(text: string): string {\n return text.replace(\n /&(#x[0-9a-f]+|#[0-9]+|[a-z]+);/gi,\n (whole, name: string) => {\n if (name.startsWith(\"#\")) {\n const hex = name[1] === \"x\" || name[1] === \"X\";\n const code = Number.parseInt(name.slice(hex ? 2 : 1), hex ? 16 : 10);\n return Number.isNaN(code) || code > 0x10ffff\n ? whole\n : String.fromCodePoint(code);\n }\n return ENTITIES[name.toLowerCase()] ?? whole;\n },\n );\n}\n\n/**\n * The key a heading is matched by, from either side. One side is the\n * plain-text title the build recorded, the other the source text after\n * `stripInline`. Markup characters go, whitespace collapses, and case folds.\n * Both sides pass through it, so a character it drops cannot make them differ.\n */\nexport function headingKey(text: string): string {\n return text\n .replace(/[`*_~\\\\[\\]]/g, \"\")\n .replace(/\\s+/g, \" \")\n .trim()\n .toLowerCase();\n}\n\n/**\n * Raw heading source to the text remark reads from it. Links and images keep\n * their text, autolinks their target, and character references decode.\n */\nfunction stripInline(raw: string): string {\n return decodeEntities(\n raw\n .replace(/!?\\[([^\\]]*)\\]\\((?:[^()]|\\([^()]*\\))*\\)/g, \"$1\")\n .replace(/!?\\[([^\\]]*)\\]\\[[^\\]]*\\]/g, \"$1\")\n .replace(/<((?:https?|mailto):[^>\\s]+)>/gi, \"$1\"),\n );\n}\n\n/**\n * Sections of a document in true document order, reconstructed from the\n * `dcterms:hasPart` tree ordered by `graph:order` within each parent.\n *\n * Needed because heading text is not unique: a document with two `## Install`\n * headings produces two section nodes, and matching by title alone would give\n * both the *first* heading's text — wrong content under a confident citation.\n */\nexport function documentSectionOrder(\n graph: GraphIndex,\n docIri: string,\n): string[] {\n const ordered: string[] = [];\n const seen = new Set<string>();\n\n const childrenOf = (iri: string): string[] =>\n graph\n .out(iri, DCTERMS_HAS_PART)\n .map((e) => e.target)\n .sort((a, b) => {\n const oa = Number.parseInt(graph.literal(a, GRAPH_ORDER) ?? \"\", 10);\n const ob = Number.parseInt(graph.literal(b, GRAPH_ORDER) ?? \"\", 10);\n if (Number.isNaN(oa) || Number.isNaN(ob) || oa === ob) {\n return a < b ? -1 : a > b ? 1 : 0;\n }\n return oa - ob;\n });\n\n const walk = (iri: string): void => {\n for (const child of childrenOf(iri)) {\n if (seen.has(child)) continue;\n seen.add(child);\n ordered.push(child);\n walk(child);\n }\n };\n walk(docIri);\n return ordered;\n}\n\n/**\n * Occurrence number of every section of a document, in one walk: section IRI →\n * how many earlier sections share its heading text and level.\n *\n * Batched because the per-section form is quadratic — a document with N\n * sections would otherwise rebuild the whole `hasPart` order N times, once per\n * section indexed or resolved.\n */\nexport function sectionOccurrences(\n graph: GraphIndex,\n docIri: string,\n): Map<string, number> {\n const occurrences = new Map<string, number>();\n // title → level → how many carrying that pair have been seen so far. Nested\n // rather than a joined key, so no separator has to be safe in either field.\n const counts = new Map<string, Map<string, number>>();\n\n for (const section of documentSectionOrder(graph, docIri)) {\n const rawTitle = graph.literal(section, DCTERMS_TITLE);\n if (rawTitle === undefined) {\n occurrences.set(section, 0);\n continue;\n }\n // Keyed exactly the way `sliceSection` matches headings, by `headingKey`.\n // Keyed by the raw title instead, a document with `## Install`\n // and `## install` gives both sections occurrence 0, and the second one\n // then slices the first heading: wrong content under a confident citation.\n const title = headingKey(rawTitle);\n const level = graph.literal(section, GRAPH_LEVEL) ?? \"\";\n let byLevel = counts.get(title);\n if (!byLevel) {\n byLevel = new Map();\n counts.set(title, byLevel);\n }\n const seen = byLevel.get(level) ?? 0;\n occurrences.set(section, seen);\n byLevel.set(level, seen + 1);\n }\n return occurrences;\n}\n\n/**\n * Which occurrence of its heading text a section is (0-based) — the number of\n * earlier same-title, same-level sections in the same document. A section the\n * `hasPart` tree does not reach counts as the first (0).\n */\nexport function sectionOccurrence(\n graph: GraphIndex,\n sectionIri: string,\n): number {\n const { doc } = splitFragment(sectionIri);\n return sectionOccurrences(graph, doc).get(sectionIri) ?? 0;\n}\n\n/**\n * The prose before a document's first heading — the text that belongs to no\n * section, and so would otherwise be indexed nowhere in a document that has\n * sections.\n *\n * Fence-aware for the same reason `sliceSection` is: a `#` comment inside a\n * leading code block is not a heading, and treating it as one would cut the\n * preamble short. Frontmatter is *not* stripped here — the caller decides,\n * since only the search index cares about that.\n */\nexport function documentPreamble(markdown: string): string | undefined {\n const lines = markdown.split(/\\r?\\n/);\n const end = sourceHeadings(lines)[0]?.start ?? lines.length;\n const text = lines.slice(0, end).join(\"\\n\").trim();\n return text === \"\" ? undefined : text;\n}\n\n/**\n * Slice a markdown document at the heading whose text matches `title`,\n * returning that heading through to the next heading of the same or higher\n * rank. Returns undefined when no such heading exists. Handles CRLF, and\n * ignores `#` lines inside fenced code blocks.\n *\n * `occurrence` selects among repeated headings (0 = the first). Heading text is\n * not unique, so callers with a specific section node in hand should pass\n * `sectionOccurrence(graph, iri)` rather than defaulting to the first match.\n */\nexport function sliceSection(\n markdown: string,\n title: string,\n level?: number,\n occurrence = 0,\n): string | undefined {\n return slice(markdown, title, level, occurrence, false);\n}\n\n/**\n * The text a section *owns*: its heading down to the next heading of **any**\n * rank, so nested subsections are excluded.\n *\n * `sliceSection` keeps the subtree because that is what retrieval wants — ask\n * for \"Configuration\" and you should get its subsections too. Indexing wants\n * the opposite: with the subtree, a parent section matches everything its\n * children match and outranks them, so an H1 section shadows every heading\n * beneath it. Same granularity rule as Document vs Section, one level down.\n */\nexport function sectionOwnText(\n markdown: string,\n title: string,\n level?: number,\n occurrence = 0,\n): string | undefined {\n return slice(markdown, title, level, occurrence, true);\n}\n\n/**\n * The file lines `sectionOwnText` slices, 1-based and inclusive: the heading\n * down to the line before the next heading of any rank. `graph check` maps a\n * sample question's pinned answer onto the section that owns it with this.\n */\nexport function sectionOwnLines(\n markdown: string,\n title: string,\n level?: number,\n occurrence = 0,\n): { start: number; end: number } | undefined {\n const span = locate(markdown.split(/\\r?\\n/), title, level, occurrence, true);\n return span === undefined ? undefined : { start: span.start + 1, end: span.end };\n}\n\nfunction slice(\n markdown: string,\n title: string,\n level: number | undefined,\n occurrence: number,\n ownTextOnly: boolean,\n): string | undefined {\n const lines = markdown.split(/\\r?\\n/);\n const span = locate(lines, title, level, occurrence, ownTextOnly);\n if (span === undefined) return undefined;\n return lines.slice(span.start, span.end).join(\"\\n\").trimEnd();\n}\n\n/** The 0-based, end-exclusive line span of a section's slice. */\nfunction locate(\n lines: string[],\n title: string,\n level: number | undefined,\n occurrence: number,\n ownTextOnly: boolean,\n): { start: number; end: number } | undefined {\n const headings = sourceHeadings(lines);\n const wanted = headingKey(title);\n let remaining = occurrence;\n let found = -1;\n\n for (const [n, heading] of headings.entries()) {\n if (level !== undefined && heading.level !== level) continue;\n if (headingKey(stripInline(heading.text)) !== wanted) continue;\n if (remaining > 0) {\n remaining -= 1;\n continue;\n }\n found = n;\n break;\n }\n const match = headings[found];\n if (match === undefined) return undefined;\n\n const next = headings\n .slice(found + 1)\n .find((h) => ownTextOnly || h.level <= match.level);\n return { start: match.start, end: next?.start ?? lines.length };\n}\n\n/**\n * A resolver that fetches document sources over HTTP. Documents map through\n * `graph:path`; sections slice their parent document by heading.\n */\nexport function createFetchResolver(\n graph: GraphIndex,\n options: FetchResolverOptions = {},\n): ContentResolver {\n const doFetch: FetchLike =\n options.fetch ?? ((url: string) => globalThis.fetch(url));\n const toUrl =\n options.pathToUrl ?? ((path: string) => `${options.baseUrl ?? \"\"}${path}`);\n const cache = new Map<string, Promise<string | undefined>>();\n // `assemble` resolves many sections of the same document; the occurrence walk\n // is per-document, so compute it once and reuse it.\n const occurrenceCache = new Map<string, Map<string, number>>();\n\n const occurrenceOf = (docIri: string, sectionIri: string): number => {\n let map = occurrenceCache.get(docIri);\n if (!map) {\n map = sectionOccurrences(graph, docIri);\n occurrenceCache.set(docIri, map);\n }\n return map.get(sectionIri) ?? 0;\n };\n\n const fetchDoc = (url: string): Promise<string | undefined> => {\n let pending = cache.get(url);\n if (!pending) {\n pending = doFetch(url)\n .then((r) => (r.ok ? r.text() : undefined))\n .catch(() => undefined);\n cache.set(url, pending);\n }\n return pending;\n };\n\n return {\n async resolve(iri: string): Promise<ResolvedContent | undefined> {\n const { doc, fragment } = splitFragment(iri);\n const path = graph.literal(doc, GRAPH_PATH);\n if (!path) return undefined;\n\n const sourceUrl = toUrl(path);\n const body = await fetchDoc(sourceUrl);\n const title = graph.literal(iri, DCTERMS_TITLE);\n\n if (body === undefined) {\n options.trace?.resolutions.push({\n iri,\n sourceUrl,\n ok: false,\n error: \"fetch failed\",\n });\n return undefined;\n }\n\n let text = body;\n if (fragment) {\n const levelText = graph.literal(iri, GRAPH_LEVEL);\n const level = levelText ? Number.parseInt(levelText, 10) : undefined;\n const slice =\n title === undefined\n ? undefined\n : sliceSection(\n body,\n title,\n Number.isNaN(level) ? undefined : level,\n occurrenceOf(doc, iri),\n );\n if (slice === undefined) {\n options.trace?.resolutions.push({\n iri,\n sourceUrl,\n ok: false,\n error: \"section heading not found\",\n });\n return undefined;\n }\n text = slice;\n }\n\n options.trace?.resolutions.push({ iri, sourceUrl, ok: true });\n return { iri, text, sourceUrl, title };\n },\n };\n}\n","/**\n * Context assembly (ADR 01018) — the runtime's terminal stage.\n *\n * Turns traversed nodes into the bundle an inference engine consumes:\n * `{ context, citations, trace, refusal? }`. **dockg stops here**: it never\n * calls a model. A different tool (an agent over MCP, a site backend) takes the\n * bundle onward, which keeps this runtime fully deterministic and keeps API\n * keys and inference cost outside dockg entirely.\n *\n * When nothing survives retrieval the result is a *structured refusal*, never\n * empty context — a caller must be able to tell \"no route exists\" apart from\n * \"here is nothing, proceed anyway\" (the disciplined-silence contract).\n *\n * Platform-neutral: no `node:` imports, no npm dependencies.\n */\nimport type { ContentResolver } from \"./resolve.js\";\nimport type { EntryCandidate, QueryTrace } from \"./trace.js\";\nimport { createTrace } from \"./trace.js\";\nimport type { TraversedNode } from \"./traverse.js\";\n\nexport interface ContextBlock {\n iri: string;\n title?: string;\n text: string;\n sourceUrl: string;\n /** Hops from the nearest seed — the relevance signal, carried through. */\n depth: number;\n}\n\nexport interface Citation {\n iri: string;\n title?: string;\n sourceUrl: string;\n}\n\nexport type RefusalReason = \"no-route\" | \"no-content\";\n\nexport interface Refusal {\n reason: RefusalReason;\n detail: string;\n}\n\n/**\n * The rankings that produced the seeds, carried through to the caller.\n *\n * Retrieval answers two different questions — \"what matched the query?\" and\n * \"what is the graph connected to it?\" — and a consumer needs both. Returning\n * only the graph result would make the match rankings inferrable solely from the\n * trace, which is diagnostic rather than a result surface (ADR 01020).\n */\nexport interface EntryRankings {\n /** The lexical leg's own ranking. */\n lexical: EntryCandidate[];\n /** The vector leg's own ranking; empty when no embedder was in play. */\n vector: EntryCandidate[];\n /** The fused ranking that actually seeded traversal. */\n merged: EntryCandidate[];\n}\n\nexport interface RetrievalBundle {\n /** What matched the query, per leg. Absent when seeds were given explicitly. */\n entry?: EntryRankings;\n context: ContextBlock[];\n citations: Citation[];\n trace: QueryTrace;\n /** Present when retrieval found nothing usable. `context` is then empty. */\n refusal?: Refusal;\n /** True when the character budget dropped otherwise-eligible blocks. */\n truncated: boolean;\n}\n\nexport interface AssembleOptions {\n /** Character budget across all blocks. Default: unbounded. */\n maxChars?: number;\n /** Append to an existing trace (normally the traversal's). */\n trace?: QueryTrace;\n /**\n * The entry rankings that produced these nodes, passed through to the bundle\n * so callers see matches and graph results side by side.\n */\n entry?: EntryRankings;\n}\n\n/**\n * Resolve traversed nodes to text and assemble the retrieval bundle. Nodes are\n * kept in traversal order (nearest-first), which is deterministic, and every\n * block carries the IRI it came from so citations are structural, not inferred.\n */\nexport async function assemble(\n resolver: ContentResolver,\n nodes: TraversedNode[],\n options: AssembleOptions = {},\n): Promise<RetrievalBundle> {\n const trace = options.trace ?? createTrace();\n const budget = options.maxChars ?? Infinity;\n\n if (nodes.length === 0) {\n return {\n ...(options.entry ? { entry: options.entry } : {}),\n context: [],\n citations: [],\n trace,\n truncated: false,\n refusal: {\n reason: \"no-route\",\n detail:\n \"No node in the graph was reachable for this query under the active scope filter.\",\n },\n };\n }\n\n const context: ContextBlock[] = [];\n let used = 0;\n let truncated = false;\n let resolvedAny = false;\n\n for (const node of nodes) {\n const resolved = await resolver.resolve(node.iri);\n if (!resolved) continue;\n resolvedAny = true;\n if (used + resolved.text.length > budget) {\n truncated = true;\n continue;\n }\n used += resolved.text.length;\n context.push({\n iri: resolved.iri,\n title: resolved.title,\n text: resolved.text,\n sourceUrl: resolved.sourceUrl,\n depth: node.depth,\n });\n }\n\n if (context.length === 0) {\n return {\n ...(options.entry ? { entry: options.entry } : {}),\n context: [],\n citations: [],\n trace,\n truncated,\n refusal: {\n reason: \"no-content\",\n detail: resolvedAny\n ? \"Every matching node's content exceeded the character budget.\"\n : \"Matching nodes were found, but none of them resolved to readable content.\",\n },\n };\n }\n\n return {\n ...(options.entry ? { entry: options.entry } : {}),\n context,\n citations: context.map((b) => ({\n iri: b.iri,\n title: b.title,\n sourceUrl: b.sourceUrl,\n })),\n trace,\n truncated,\n };\n}\n","/**\n * RDF/JS interop — the custom-SPARQL escape hatch (ADR 01018).\n *\n * The runtime's own walker is deliberately not a SPARQL engine: it is 0 KB and\n * it records a trace. But arbitrary user-authored SPARQL is a legitimate need,\n * so the index can hand out its contents as standard **RDF/JS quads**. Feed\n * them to any RDF/JS store and query with any engine:\n *\n * ```js\n * import { Store } from \"n3\";\n * import { QueryEngine } from \"@comunica/query-sparql-rdfjs-lite\";\n * const store = new Store(rdfjsQuads(graph));\n * const bindings = await new QueryEngine().queryBindings(sparql, { sources: [store] });\n * ```\n *\n * Quads are plain data rather than a hand-rolled `Source` stream on purpose:\n * every engine already accepts a store, stores accept quad arrays, and faking\n * Node's stream contract in a browser-safe module is fragile for no gain. At\n * docs scale materializing is trivial (the reference corpus is 172 quads).\n *\n * Honest caveat: engine results are bindings, not walker traces —\n * explainability lives in the walker API.\n *\n * The term shapes are structural, so they are hand-rolled here rather than\n * pulled from `@rdfjs/data-model`, keeping the runtime dependency-free and\n * browser-safe.\n */\nimport { byCodeUnit } from \"../core/sort.js\";\nimport type { GraphIndex, Value } from \"./graph.js\";\n\nconst XSD_STRING = \"http://www.w3.org/2001/XMLSchema#string\";\nconst RDF_LANG_STRING = \"http://www.w3.org/1999/02/22-rdf-syntax-ns#langString\";\n\nexport interface RdfTerm {\n termType: \"NamedNode\" | \"Literal\" | \"DefaultGraph\";\n value: string;\n language?: string;\n datatype?: RdfTerm;\n equals(other?: RdfTerm | null): boolean;\n}\n\nexport interface RdfQuad {\n termType: \"Quad\";\n subject: RdfTerm;\n predicate: RdfTerm;\n object: RdfTerm;\n graph: RdfTerm;\n equals(other?: RdfQuad | null): boolean;\n}\n\nexport function namedNode(value: string): RdfTerm {\n return {\n termType: \"NamedNode\",\n value,\n equals(other) {\n return !!other && other.termType === \"NamedNode\" && other.value === value;\n },\n };\n}\n\nexport function defaultGraph(): RdfTerm {\n return {\n termType: \"DefaultGraph\",\n value: \"\",\n equals(other) {\n return !!other && other.termType === \"DefaultGraph\";\n },\n };\n}\n\nexport function literal(value: string, datatype?: string, language?: string): RdfTerm {\n const lang = language ?? \"\";\n const dt = namedNode(lang ? RDF_LANG_STRING : (datatype ?? XSD_STRING));\n return {\n termType: \"Literal\",\n value,\n language: lang,\n datatype: dt,\n equals(other) {\n return (\n !!other &&\n other.termType === \"Literal\" &&\n other.value === value &&\n (other.language ?? \"\") === lang &&\n !!other.datatype &&\n other.datatype.value === dt.value\n );\n },\n };\n}\n\nfunction toTerm(v: Value): RdfTerm {\n return v.kind === \"iri\" ? namedNode(v.value) : literal(v.value, v.datatype, v.language);\n}\n\nfunction makeQuad(s: string, p: string, o: Value): RdfQuad {\n const subject = namedNode(s);\n const predicate = namedNode(p);\n const object = toTerm(o);\n const graph = defaultGraph();\n return {\n termType: \"Quad\",\n subject,\n predicate,\n object,\n graph,\n equals(other) {\n return (\n !!other &&\n subject.equals(other.subject) &&\n predicate.equals(other.predicate) &&\n object.equals(other.object)\n );\n },\n };\n}\n\n/**\n * The whole index as RDF/JS quads, in the index's deterministic order. Feed to\n * any RDF/JS store (`new Store(rdfjsQuads(graph))`) to run SPARQL.\n */\nexport function rdfjsQuads(graph: GraphIndex): RdfQuad[] {\n const quads: RdfQuad[] = [];\n for (const s of graph.ids()) {\n const node = graph.node(s);\n if (!node) continue;\n for (const p of [...node.props.keys()].sort(byCodeUnit)) {\n for (const v of node.props.get(p) ?? []) quads.push(makeQuad(s, p, v));\n }\n }\n return quads;\n}\n\n/**\n * Triple-pattern match returning RDF/JS quads. A null/undefined position is a\n * wildcard. Convenience for callers who want RDF/JS terms without pulling in a\n * store; the walker API is the richer (and traced) way to query.\n */\nexport function matchQuads(\n graph: GraphIndex,\n subject?: string | null,\n predicate?: string | null,\n object?: string | null,\n): RdfQuad[] {\n const quads: RdfQuad[] = [];\n const subjects = subject ? [subject] : graph.ids();\n for (const s of subjects) {\n const node = graph.node(s);\n if (!node) continue;\n const predicates = predicate\n ? [predicate]\n : [...node.props.keys()].sort(byCodeUnit);\n for (const p of predicates) {\n for (const v of node.props.get(p) ?? []) {\n if (object !== undefined && object !== null && v.value !== object) {\n continue;\n }\n quads.push(makeQuad(s, p, v));\n }\n }\n }\n return quads;\n}\n","import type { RadixTree, Entry, LeafType } from './types'\n\n/** @ignore */\nconst ENTRIES = 'ENTRIES'\n\n/** @ignore */\nconst KEYS = 'KEYS'\n\n/** @ignore */\nconst VALUES = 'VALUES'\n\n/** @ignore */\nconst LEAF = '' as LeafType\n\ninterface Iterators<T> {\n ENTRIES: Entry<T>\n KEYS: string\n VALUES: T\n}\n\ntype Kind<T> = keyof Iterators<T>\ntype Result<T, K extends keyof Iterators<T>> = Iterators<T>[K]\n\ntype IteratorPath<T> = {\n node: RadixTree<T>,\n keys: string[]\n}[]\n\nexport type IterableSet<T> = {\n _tree: RadixTree<T>,\n _prefix: string\n}\n\n/**\n * @private\n */\nclass TreeIterator<T, K extends Kind<T>> implements Iterator<Result<T, K>> {\n set: IterableSet<T>\n _type: K\n _path: IteratorPath<T>\n\n constructor (set: IterableSet<T>, type: K) {\n const node = set._tree\n const keys = Array.from(node.keys())\n this.set = set\n this._type = type\n this._path = keys.length > 0 ? [{ node, keys }] : []\n }\n\n next (): IteratorResult<Result<T, K>> {\n const value = this.dive()\n this.backtrack()\n return value\n }\n\n dive (): IteratorResult<Result<T, K>> {\n if (this._path.length === 0) { return { done: true, value: undefined } }\n const { node, keys } = last(this._path)!\n if (last(keys) === LEAF) { return { done: false, value: this.result() } }\n\n const child = node.get(last(keys)!)!\n this._path.push({ node: child, keys: Array.from(child.keys()) })\n return this.dive()\n }\n\n backtrack (): void {\n if (this._path.length === 0) { return }\n const keys = last(this._path)!.keys\n keys.pop()\n if (keys.length > 0) { return }\n this._path.pop()\n this.backtrack()\n }\n\n key (): string {\n return this.set._prefix + this._path\n .map(({ keys }) => last(keys))\n .filter(key => key !== LEAF)\n .join('')\n }\n\n value (): T {\n return last(this._path)!.node.get(LEAF)!\n }\n\n result (): Result<T, K> {\n switch (this._type) {\n case VALUES: return this.value() as Result<T, K>\n case KEYS: return this.key() as Result<T, K>\n default: return [this.key(), this.value()] as Result<T, K>\n }\n }\n\n [Symbol.iterator] () {\n return this\n }\n}\n\nconst last = <T>(array: T[]): T | undefined => {\n return array[array.length - 1]\n}\n\nexport { TreeIterator, ENTRIES, KEYS, VALUES, LEAF }\n","/* eslint-disable no-labels */\nimport { LEAF } from './TreeIterator'\nimport type { RadixTree } from './types'\n\nexport type FuzzyResult<T> = [T, number]\n\nexport type FuzzyResults<T> = Map<string, FuzzyResult<T>>\n\n/**\n * @ignore\n */\nexport const fuzzySearch = <T = any>(node: RadixTree<T>, query: string, maxDistance: number): FuzzyResults<T> => {\n const results: FuzzyResults<T> = new Map()\n if (query === undefined) return results\n\n // Number of columns in the Levenshtein matrix.\n const n = query.length + 1\n\n // Matching terms can never be longer than N + maxDistance.\n const m = n + maxDistance\n\n // Fill first matrix row and column with numbers: 0 1 2 3 ...\n const matrix = new Uint8Array(m * n).fill(maxDistance + 1)\n for (let j = 0; j < n; ++j) matrix[j] = j\n for (let i = 1; i < m; ++i) matrix[i * n] = i\n\n recurse(\n node,\n query,\n maxDistance,\n results,\n matrix,\n 1,\n n,\n ''\n )\n\n return results\n}\n\n// Modified version of http://stevehanov.ca/blog/?id=114\n\n// This builds a Levenshtein matrix for a given query and continuously updates\n// it for nodes in the radix tree that fall within the given maximum edit\n// distance. Keeping the same matrix around is beneficial especially for larger\n// edit distances.\n//\n// k a t e <-- query\n// 0 1 2 3 4\n// c 1 1 2 3 4\n// a 2 2 1 2 3\n// t 3 3 2 1 [2] <-- edit distance\n// ^\n// ^ term in radix tree, rows are added and removed as needed\n\nconst recurse = <T = any>(\n node: RadixTree<T>,\n query: string,\n maxDistance: number,\n results: FuzzyResults<T>,\n matrix: Uint8Array,\n m: number,\n n: number,\n prefix: string\n): void => {\n const offset = m * n\n\n key: for (const key of node.keys()) {\n if (key === LEAF) {\n // We've reached a leaf node. Check if the edit distance acceptable and\n // store the result if it is.\n const distance = matrix[offset - 1]\n if (distance <= maxDistance) {\n results.set(prefix, [node.get(key)!, distance])\n }\n } else {\n // Iterate over all characters in the key. Update the Levenshtein matrix\n // and check if the minimum distance in the last row is still within the\n // maximum edit distance. If it is, we can recurse over all child nodes.\n let i = m\n for (let pos = 0; pos < key.length; ++pos, ++i) {\n const char = key[pos]\n const thisRowOffset = n * i\n const prevRowOffset = thisRowOffset - n\n\n // Set the first column based on the previous row, and initialize the\n // minimum distance in the current row.\n let minDistance = matrix[thisRowOffset]\n\n const jmin = Math.max(0, i - maxDistance - 1)\n const jmax = Math.min(n - 1, i + maxDistance)\n\n // Iterate over remaining columns (characters in the query).\n for (let j = jmin; j < jmax; ++j) {\n const different = char !== query[j]\n\n // It might make sense to only read the matrix positions used for\n // deletion/insertion if the characters are different. But we want to\n // avoid conditional reads for performance reasons.\n const rpl = matrix[prevRowOffset + j] + +different\n const del = matrix[prevRowOffset + j + 1] + 1\n const ins = matrix[thisRowOffset + j] + 1\n\n const dist = matrix[thisRowOffset + j + 1] = Math.min(rpl, del, ins)\n\n if (dist < minDistance) minDistance = dist\n }\n\n // Because distance will never decrease, we can stop. There will be no\n // matching child nodes.\n if (minDistance > maxDistance) {\n continue key\n }\n }\n\n recurse(\n node.get(key)!,\n query,\n maxDistance,\n results,\n matrix,\n i,\n n,\n prefix + key\n )\n }\n }\n}\n\nexport default fuzzySearch\n","/* eslint-disable no-labels */\nimport { TreeIterator, ENTRIES, KEYS, VALUES, LEAF } from './TreeIterator'\nimport fuzzySearch, { type FuzzyResults } from './fuzzySearch'\nimport type { RadixTree, Entry, Path } from './types'\n\n/**\n * A class implementing the same interface as a standard JavaScript\n * [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)\n * with string keys, but adding support for efficiently searching entries with\n * prefix or fuzzy search. This class is used internally by {@link MiniSearch}\n * as the inverted index data structure. The implementation is a radix tree\n * (compressed prefix tree).\n *\n * Since this class can be of general utility beyond _MiniSearch_, it is\n * exported by the `minisearch` package and can be imported (or required) as\n * `minisearch/SearchableMap`.\n *\n * @typeParam T The type of the values stored in the map.\n */\nexport default class SearchableMap<T = any> {\n /**\n * @internal\n */\n _tree: RadixTree<T>\n\n /**\n * @internal\n */\n _prefix: string\n\n private _size: number | undefined = undefined\n\n /**\n * The constructor is normally called without arguments, creating an empty\n * map. In order to create a {@link SearchableMap} from an iterable or from an\n * object, check {@link SearchableMap.from} and {@link\n * SearchableMap.fromObject}.\n *\n * The constructor arguments are for internal use, when creating derived\n * mutable views of a map at a prefix.\n */\n constructor (tree: RadixTree<T> = new Map(), prefix = '') {\n this._tree = tree\n this._prefix = prefix\n }\n\n /**\n * Creates and returns a mutable view of this {@link SearchableMap},\n * containing only entries that share the given prefix.\n *\n * ### Usage:\n *\n * ```javascript\n * let map = new SearchableMap()\n * map.set(\"unicorn\", 1)\n * map.set(\"universe\", 2)\n * map.set(\"university\", 3)\n * map.set(\"unique\", 4)\n * map.set(\"hello\", 5)\n *\n * let uni = map.atPrefix(\"uni\")\n * uni.get(\"unique\") // => 4\n * uni.get(\"unicorn\") // => 1\n * uni.get(\"hello\") // => undefined\n *\n * let univer = map.atPrefix(\"univer\")\n * univer.get(\"unique\") // => undefined\n * univer.get(\"universe\") // => 2\n * univer.get(\"university\") // => 3\n * ```\n *\n * @param prefix The prefix\n * @return A {@link SearchableMap} representing a mutable view of the original\n * Map at the given prefix\n */\n atPrefix (prefix: string): SearchableMap<T> {\n if (!prefix.startsWith(this._prefix)) { throw new Error('Mismatched prefix') }\n\n const [node, path] = trackDown(this._tree, prefix.slice(this._prefix.length))\n\n if (node === undefined) {\n const [parentNode, key] = last(path)\n\n for (const k of parentNode!.keys()) {\n if (k !== LEAF && k.startsWith(key)) {\n const node = new Map()\n node.set(k.slice(key.length), parentNode!.get(k)!)\n return new SearchableMap(node, prefix)\n }\n }\n }\n\n return new SearchableMap<T>(node, prefix)\n }\n\n /**\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/clear\n */\n clear (): void {\n this._size = undefined\n this._tree.clear()\n }\n\n /**\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/delete\n * @param key Key to delete\n */\n delete (key: string): void {\n this._size = undefined\n return remove(this._tree, key)\n }\n\n /**\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/entries\n * @return An iterator iterating through `[key, value]` entries.\n */\n entries () {\n return new TreeIterator(this, ENTRIES)\n }\n\n /**\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/forEach\n * @param fn Iteration function\n */\n forEach (fn: (key: string, value: T, map: SearchableMap) => void): void {\n for (const [key, value] of this) {\n fn(key, value, this)\n }\n }\n\n /**\n * Returns a Map of all the entries that have a key within the given edit\n * distance from the search key. The keys of the returned Map are the matching\n * keys, while the values are two-element arrays where the first element is\n * the value associated to the key, and the second is the edit distance of the\n * key to the search key.\n *\n * ### Usage:\n *\n * ```javascript\n * let map = new SearchableMap()\n * map.set('hello', 'world')\n * map.set('hell', 'yeah')\n * map.set('ciao', 'mondo')\n *\n * // Get all entries that match the key 'hallo' with a maximum edit distance of 2\n * map.fuzzyGet('hallo', 2)\n * // => Map(2) { 'hello' => ['world', 1], 'hell' => ['yeah', 2] }\n *\n * // In the example, the \"hello\" key has value \"world\" and edit distance of 1\n * // (change \"e\" to \"a\"), the key \"hell\" has value \"yeah\" and edit distance of 2\n * // (change \"e\" to \"a\", delete \"o\")\n * ```\n *\n * @param key The search key\n * @param maxEditDistance The maximum edit distance (Levenshtein)\n * @return A Map of the matching keys to their value and edit distance\n */\n fuzzyGet (key: string, maxEditDistance: number): FuzzyResults<T> {\n return fuzzySearch<T>(this._tree, key, maxEditDistance)\n }\n\n /**\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get\n * @param key Key to get\n * @return Value associated to the key, or `undefined` if the key is not\n * found.\n */\n get (key: string): T | undefined {\n const node = lookup<T>(this._tree, key)\n return node !== undefined ? node.get(LEAF) : undefined\n }\n\n /**\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/has\n * @param key Key\n * @return True if the key is in the map, false otherwise\n */\n has (key: string): boolean {\n const node = lookup(this._tree, key)\n return node !== undefined && node.has(LEAF)\n }\n\n /**\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/keys\n * @return An `Iterable` iterating through keys\n */\n keys () {\n return new TreeIterator(this, KEYS)\n }\n\n /**\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/set\n * @param key Key to set\n * @param value Value to associate to the key\n * @return The {@link SearchableMap} itself, to allow chaining\n */\n set (key: string, value: T): SearchableMap<T> {\n if (typeof key !== 'string') { throw new Error('key must be a string') }\n this._size = undefined\n const node = createPath(this._tree, key)\n node.set(LEAF, value)\n return this\n }\n\n /**\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/size\n */\n get size (): number {\n if (this._size) { return this._size }\n /** @ignore */\n this._size = 0\n\n const iter = this.entries()\n while (!iter.next().done) this._size! += 1\n\n return this._size\n }\n\n /**\n * Updates the value at the given key using the provided function. The function\n * is called with the current value at the key, and its return value is used as\n * the new value to be set.\n *\n * ### Example:\n *\n * ```javascript\n * // Increment the current value by one\n * searchableMap.update('somekey', (currentValue) => currentValue == null ? 0 : currentValue + 1)\n * ```\n *\n * If the value at the given key is or will be an object, it might not require\n * re-assignment. In that case it is better to use `fetch()`, because it is\n * faster.\n *\n * @param key The key to update\n * @param fn The function used to compute the new value from the current one\n * @return The {@link SearchableMap} itself, to allow chaining\n */\n update (key: string, fn: (value: T | undefined) => T): SearchableMap<T> {\n if (typeof key !== 'string') { throw new Error('key must be a string') }\n this._size = undefined\n const node = createPath(this._tree, key)\n node.set(LEAF, fn(node.get(LEAF)))\n return this\n }\n\n /**\n * Fetches the value of the given key. If the value does not exist, calls the\n * given function to create a new value, which is inserted at the given key\n * and subsequently returned.\n *\n * ### Example:\n *\n * ```javascript\n * const map = searchableMap.fetch('somekey', () => new Map())\n * map.set('foo', 'bar')\n * ```\n *\n * @param key The key to update\n * @param initial A function that creates a new value if the key does not exist\n * @return The existing or new value at the given key\n */\n fetch (key: string, initial: () => T): T {\n if (typeof key !== 'string') { throw new Error('key must be a string') }\n this._size = undefined\n const node = createPath(this._tree, key)\n\n let value = node.get(LEAF)\n if (value === undefined) {\n node.set(LEAF, value = initial())\n }\n\n return value\n }\n\n /**\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/values\n * @return An `Iterable` iterating through values.\n */\n values () {\n return new TreeIterator(this, VALUES)\n }\n\n /**\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/@@iterator\n */\n [Symbol.iterator] () {\n return this.entries()\n }\n\n /**\n * Creates a {@link SearchableMap} from an `Iterable` of entries\n *\n * @param entries Entries to be inserted in the {@link SearchableMap}\n * @return A new {@link SearchableMap} with the given entries\n */\n static from<T = any> (entries: Iterable<Entry<T>> | Entry<T>[]) {\n const tree = new SearchableMap()\n for (const [key, value] of entries) {\n tree.set(key, value)\n }\n return tree\n }\n\n /**\n * Creates a {@link SearchableMap} from the iterable properties of a JavaScript object\n *\n * @param object Object of entries for the {@link SearchableMap}\n * @return A new {@link SearchableMap} with the given entries\n */\n static fromObject<T = any> (object: { [key: string]: T }) {\n return SearchableMap.from<T>(Object.entries(object))\n }\n}\n\nconst trackDown = <T = any>(tree: RadixTree<T> | undefined, key: string, path: Path<T> = []): [RadixTree<T> | undefined, Path<T>] => {\n if (key.length === 0 || tree == null) { return [tree, path] }\n\n for (const k of tree.keys()) {\n if (k !== LEAF && key.startsWith(k)) {\n path.push([tree, k]) // performance: update in place\n return trackDown(tree.get(k)!, key.slice(k.length), path)\n }\n }\n\n path.push([tree, key]) // performance: update in place\n return trackDown(undefined, '', path)\n}\n\nconst lookup = <T = any>(tree: RadixTree<T>, key: string): RadixTree<T> | undefined => {\n if (key.length === 0 || tree == null) { return tree }\n\n for (const k of tree.keys()) {\n if (k !== LEAF && key.startsWith(k)) {\n return lookup(tree.get(k)!, key.slice(k.length))\n }\n }\n}\n\n// Create a path in the radix tree for the given key, and returns the deepest\n// node. This function is in the hot path for indexing. It avoids unnecessary\n// string operations and recursion for performance.\nconst createPath = <T = any>(node: RadixTree<T>, key: string): RadixTree<T> => {\n const keyLength = key.length\n\n outer: for (let pos = 0; node && pos < keyLength;) {\n for (const k of node.keys()) {\n // Check whether this key is a candidate: the first characters must match.\n if (k !== LEAF && key[pos] === k[0]) {\n const len = Math.min(keyLength - pos, k.length)\n\n // Advance offset to the point where key and k no longer match.\n let offset = 1\n while (offset < len && key[pos + offset] === k[offset]) ++offset\n\n const child = node.get(k)!\n if (offset === k.length) {\n // The existing key is shorter than the key we need to create.\n node = child\n } else {\n // Partial match: we need to insert an intermediate node to contain\n // both the existing subtree and the new node.\n const intermediate = new Map()\n intermediate.set(k.slice(offset), child)\n node.set(key.slice(pos, pos + offset), intermediate)\n node.delete(k)\n node = intermediate\n }\n\n pos += offset\n continue outer\n }\n }\n\n // Create a final child node to contain the final suffix of the key.\n const child = new Map()\n node.set(key.slice(pos), child)\n return child\n }\n\n return node\n}\n\nconst remove = <T = any>(tree: RadixTree<T>, key: string): void => {\n const [node, path] = trackDown(tree, key)\n if (node === undefined) { return }\n node.delete(LEAF)\n\n if (node.size === 0) {\n cleanup(path)\n } else if (node.size === 1) {\n const [key, value] = node.entries().next().value!\n merge(path, key as string, value as RadixTree<T>)\n }\n}\n\nconst cleanup = <T = any>(path: Path<T>): void => {\n if (path.length === 0) { return }\n\n const [node, key] = last(path)\n node!.delete(key)\n\n if (node!.size === 0) {\n cleanup(path.slice(0, -1))\n } else if (node!.size === 1) {\n const [key, value] = node!.entries().next().value!\n if (key !== LEAF) {\n merge(path.slice(0, -1), key as string, value as RadixTree<T>)\n }\n }\n}\n\nconst merge = <T = any>(path: Path<T>, key: string, value: RadixTree<T>): void => {\n if (path.length === 0) { return }\n\n const [node, nodeKey] = last(path)\n node!.set(nodeKey + key, value)\n node!.delete(nodeKey)\n}\n\nconst last = <T = any>(array: T[]): T => {\n return array[array.length - 1]\n}\n","import SearchableMap from './SearchableMap/SearchableMap'\n\nexport type LowercaseCombinationOperator = 'or' | 'and' | 'and_not'\nexport type CombinationOperator = LowercaseCombinationOperator | Uppercase<LowercaseCombinationOperator> | Capitalize<LowercaseCombinationOperator>\n\nconst OR: LowercaseCombinationOperator = 'or'\nconst AND: LowercaseCombinationOperator = 'and'\nconst AND_NOT: LowercaseCombinationOperator = 'and_not'\n\n/**\n * Search options to customize the search behavior.\n */\nexport type SearchOptions = {\n /**\n * Names of the fields to search in. If omitted, all fields are searched.\n */\n fields?: string[],\n\n /**\n * Function used to filter search results, for example on the basis of stored\n * fields. It takes as argument each search result and should return a boolean\n * to indicate if the result should be kept or not.\n */\n filter?: (result: SearchResult) => boolean,\n\n /**\n * Key-value object of field names to boosting values. By default, fields are\n * assigned a boosting factor of 1. If one assigns to a field a boosting value\n * of 2, a result that matches the query in that field is assigned a score\n * twice as high as a result matching the query in another field, all else\n * being equal.\n */\n boost?: { [fieldName: string]: number },\n\n /**\n * Function to calculate a boost factor for each term.\n *\n * This function, if provided, is called for each query term (as split by\n * `tokenize` and processed by `processTerm`). The arguments passed to the\n * function are the query term, the positional index of the term in the query,\n * and the array of all query terms. It is expected to return a numeric boost\n * factor for the term. A factor lower than 1 reduces the importance of the\n * term, a factor greater than 1 increases it. A factor of exactly 1 is\n * neutral, and does not affect the term's importance.\n */\n boostTerm?: (term: string, i: number, terms: string[]) => number,\n\n /**\n * Relative weights to assign to prefix search results and fuzzy search\n * results. Exact matches are assigned a weight of 1.\n */\n weights?: { fuzzy: number, prefix: number },\n\n /**\n * Function to calculate a boost factor for documents. It takes as arguments\n * the document ID, and a term that matches the search in that document, and\n * the value of the stored fields for the document (if any). It should return\n * a boosting factor: a number higher than 1 increases the computed score, a\n * number lower than 1 decreases the score, and a falsy value skips the search\n * result completely.\n */\n boostDocument?: (documentId: any, term: string, storedFields?: Record<string, unknown>) => number,\n\n /**\n * Controls whether to perform prefix search. It can be a simple boolean, or a\n * function.\n *\n * If a boolean is passed, prefix search is performed if true.\n *\n * If a function is passed, it is called upon search with a search term, the\n * positional index of that search term in the tokenized search query, and the\n * tokenized search query. The function should return a boolean to indicate\n * whether to perform prefix search for that search term.\n */\n prefix?: boolean | ((term: string, index: number, terms: string[]) => boolean),\n\n /**\n * Controls whether to perform fuzzy search. It can be a simple boolean, or a\n * number, or a function.\n *\n * If a boolean is given, fuzzy search with a default fuzziness parameter is\n * performed if true.\n *\n * If a number higher or equal to 1 is given, fuzzy search is performed, with\n * a maximum edit distance (Levenshtein) equal to the number.\n *\n * If a number between 0 and 1 is given, fuzzy search is performed within a\n * maximum edit distance corresponding to that fraction of the term length,\n * approximated to the nearest integer. For example, 0.2 would mean an edit\n * distance of 20% of the term length, so 1 character in a 5-characters term.\n * The calculated fuzziness value is limited by the `maxFuzzy` option, to\n * prevent slowdown for very long queries.\n *\n * If a function is passed, the function is called upon search with a search\n * term, a positional index of that term in the tokenized search query, and\n * the tokenized search query. It should return a boolean or a number, with\n * the meaning documented above.\n */\n fuzzy?: boolean | number | ((term: string, index: number, terms: string[]) => boolean | number),\n\n /**\n * Controls the maximum fuzziness when using a fractional fuzzy value. This is\n * set to 6 by default. Very high edit distances usually don't produce\n * meaningful results, but can excessively impact search performance.\n */\n maxFuzzy?: number,\n\n /**\n * The operand to combine partial results for each term. By default it is\n * \"OR\", so results matching _any_ of the search terms are returned by a\n * search. If \"AND\" is given, only results matching _all_ the search terms are\n * returned by a search.\n */\n combineWith?: CombinationOperator,\n\n /**\n * Function to tokenize the search query. By default, the same tokenizer used\n * for indexing is used also for search.\n *\n * @remarks This function is called after `extractField` extracts a truthy\n * value from a field. This function is then expected to split the extracted\n * `text` document into tokens (more commonly referred to as \"terms\" in this\n * context). The resulting split might be simple, like for example on word\n * boundaries, or it might be more complex, taking into account certain\n * encoding, or parsing needs, or even just special cases. Think about how one\n * might need to go about indexing the term \"short-term\". You would likely\n * want to treat this case specially, and return two terms instead, `[\n * \"short\", \"term\" ]`.\n *\n * Or, you could let such a case be handled by the `processTerm` function,\n * which is designed to turn each token/term into whole terms or sub-terms. In\n * any case, the purpose of this function is to split apart the provided\n * `text` document into parts that can be processed by the `processTerm`\n * function.\n */\n tokenize?: (text: string) => string[],\n\n /**\n * Function to process or normalize terms in the search query. By default, the\n * same term processor used for indexing is used also for search.\n *\n * @remarks\n * During the document indexing phase, the first step is to call the\n * `extractField` function to fetch the requested value/field from the\n * document. This is then passed off to the `tokenize` function, which will\n * break apart each value into \"terms\". These terms are then individually\n * passed through this function to compute each term individually. A term\n * might for example be something like \"lbs\", in which case one would likely\n * want to return `[ \"lbs\", \"lb\", \"pound\", \"pounds\" ]`. You may also return\n * just a single string, or a falsy value if you would like to skip indexing\n * entirely for a specific term.\n *\n * Truthy return value(s) are then fed to the indexer as positive matches for\n * this document. In our example above, all four of the `[ \"lbs\", \"lb\",\n * \"pound\", \"pounds\" ]` terms would be added to the indexing engine, matching\n * against the current document being computed.\n *\n * *Note: Whatever values are returned from this function will receive no\n * further processing before being indexed. This means for example, if you\n * include whitespace at the beginning or end of a word, it will also be\n * indexed that way, with the included whitespace.*\n */\n processTerm?: (term: string) => string | string[] | null | undefined | false\n\n /**\n * BM25+ algorithm parameters. Customizing these is almost never necessary,\n * and finetuning them requires an understanding of the BM25 scoring model. In\n * most cases, it is best to omit this option to use defaults, and instead use\n * boosting to tweak scoring for specific use cases.\n */\n bm25?: BM25Params\n}\n\ntype SearchOptionsWithDefaults = SearchOptions & {\n boost: { [fieldName: string]: number },\n\n weights: { fuzzy: number, prefix: number },\n\n prefix: boolean | ((term: string, index: number, terms: string[]) => boolean),\n\n fuzzy: boolean | number | ((term: string, index: number, terms: string[]) => boolean | number),\n\n maxFuzzy: number,\n\n combineWith: CombinationOperator\n\n bm25: BM25Params\n}\n\n/**\n * Configuration options passed to the {@link MiniSearch} constructor\n *\n * @typeParam T The type of documents being indexed.\n */\nexport type Options<T = any> = {\n /**\n * Names of the document fields to be indexed.\n */\n fields: string[],\n\n /**\n * Name of the ID field, uniquely identifying a document.\n */\n idField?: string,\n\n /**\n * Names of fields to store, so that search results would include them. By\n * default none, so results would only contain the id field.\n */\n storeFields?: string[],\n\n /**\n * Function used to extract the value of each field in documents. By default,\n * the documents are assumed to be plain objects with field names as keys,\n * but by specifying a custom `extractField` function one can completely\n * customize how the fields are extracted.\n *\n * The function takes as arguments the document, and the name of the field to\n * extract from it. It should return the field value as a string.\n *\n * @remarks\n * The returned string is fed into the `tokenize` function to split it up\n * into tokens.\n */\n extractField?: (document: T, fieldName: string) => any,\n\n /**\n * Function used to turn field values into strings for indexing\n *\n * The function takes as arguments the field value, and the name of the field\n * to stringify, so that its logic can be customized on specific fields. By\n * default, it simply calls `toString()` on the field value (which in many\n * cases is already a string).\n *\n * ### Example:\n *\n * ```javascript\n * // Custom stringifier that formats dates as \"Tuesday, September 16, 2025\"\n * const miniSearch = new MiniSearch({\n * fields: ['title', 'date'],\n * stringifyField: ((fieldValue, _fieldName) => {\n * if (fieldValue instanceof Date) {\n * return fieldValue.toLocaleDateString('en-US', {\n * weekday: 'long',\n * year: 'numeric',\n * month: 'long',\n * day: 'numeric'\n * })\n * } else {\n * return fieldValue.toString()\n * }\n * }\n * })\n * ```\n */\n stringifyField?: (fieldValue: any, fieldName: string) => string,\n\n /**\n * Function used to split a field value into individual terms to be indexed.\n * The default tokenizer separates terms by space or punctuation, but a\n * custom tokenizer can be provided for custom logic.\n *\n * The function takes as arguments string to tokenize, and the name of the\n * field it comes from. It should return the terms as an array of strings.\n * When used for tokenizing a search query instead of a document field, the\n * `fieldName` is undefined.\n *\n * @remarks\n * This function is called after `extractField` extracts a truthy value from a\n * field. This function is then expected to split the extracted `text` document\n * into tokens (more commonly referred to as \"terms\" in this context). The resulting\n * split might be simple, like for example on word boundaries, or it might be more\n * complex, taking into account certain encoding, or parsing needs, or even just\n * special cases. Think about how one might need to go about indexing the term\n * \"short-term\". You would likely want to treat this case specially, and return two\n * terms instead, `[ \"short\", \"term\" ]`.\n *\n * Or, you could let such a case be handled by the `processTerm` function,\n * which is designed to turn each token/term into whole terms or sub-terms. In any\n * case, the purpose of this function is to split apart the provided `text` document\n * into parts that can be processed by the `processTerm` function.\n */\n tokenize?: (text: string, fieldName?: string) => string[],\n\n /**\n * Function used to process a term before indexing or search. This can be\n * used for normalization (such as stemming). By default, terms are\n * downcased, and otherwise no other normalization is performed.\n *\n * The function takes as arguments a term to process, and the name of the\n * field it comes from. It should return the processed term as a string, or a\n * falsy value to reject the term entirely.\n *\n * It can also return an array of strings, in which case each string in the\n * returned array is indexed as a separate term.\n *\n * @remarks\n * During the document indexing phase, the first step is to call the `extractField`\n * function to fetch the requested value/field from the document. This is then\n * passed off to the `tokenizer`, which will break apart each value into \"terms\".\n * These terms are then individually passed through the `processTerm` function\n * to compute each term individually. A term might for example be something\n * like \"lbs\", in which case one would likely want to return\n * `[ \"lbs\", \"lb\", \"pound\", \"pounds\" ]`. You may also return a single string value,\n * or a falsy value if you would like to skip indexing entirely for a specific term.\n *\n * Truthy return value(s) are then fed to the indexer as positive matches for this\n * document. In our example above, all four of the `[ \"lbs\", \"lb\", \"pound\", \"pounds\" ]`\n * terms would be added to the indexing engine, matching against the current document\n * being computed.\n *\n * *Note: Whatever values are returned from this function will receive no further\n * processing before being indexed. This means for example, if you include whitespace\n * at the beginning or end of a word, it will also be indexed that way, with the\n * included whitespace.*\n */\n processTerm?: (term: string, fieldName?: string) => string | string[] | null | undefined | false,\n\n /**\n * Function called to log messages. Arguments are a log level ('debug',\n * 'info', 'warn', or 'error'), a log message, and an optional string code\n * that identifies the reason for the log.\n *\n * The default implementation uses `console`, if defined.\n */\n logger?: (level: LogLevel, message: string, code?: string) => void\n\n /**\n * If `true` (the default), vacuuming is performed automatically as soon as\n * {@link MiniSearch#discard} is called a certain number of times, cleaning up\n * obsolete references from the index. If `false`, no automatic vacuuming is\n * performed. Custom settings controlling auto vacuuming thresholds, as well\n * as batching behavior, can be passed as an object (see the {@link\n * AutoVacuumOptions} type).\n */\n autoVacuum?: boolean | AutoVacuumOptions\n\n /**\n * Default search options (see the {@link SearchOptions} type and the {@link\n * MiniSearch#search} method for details)\n */\n searchOptions?: SearchOptions,\n\n /**\n * Default auto suggest options (see the {@link SearchOptions} type and the\n * {@link MiniSearch#autoSuggest} method for details)\n */\n autoSuggestOptions?: SearchOptions\n}\n\ntype OptionsWithDefaults<T = any> = Options<T> & {\n storeFields: string[]\n\n idField: string\n\n extractField: (document: T, fieldName: string) => any\n\n stringifyField: (fieldValue: any, fieldName: string) => string\n\n tokenize: (text: string, fieldName: string) => string[]\n\n processTerm: (term: string, fieldName: string) => string | string[] | null | undefined | false\n\n logger: (level: LogLevel, message: string, code?: string) => void\n\n autoVacuum: false | AutoVacuumOptions\n\n searchOptions: SearchOptionsWithDefaults\n\n autoSuggestOptions: SearchOptions\n}\n\ntype LogLevel = 'debug' | 'info' | 'warn' | 'error'\n\n/**\n * The type of auto-suggestions\n */\nexport type Suggestion = {\n /**\n * The suggestion\n */\n suggestion: string,\n\n /**\n * Suggestion as an array of terms\n */\n terms: string[],\n\n /**\n * Score for the suggestion\n */\n score: number\n}\n\n/**\n * Match information for a search result. It is a key-value object where keys\n * are terms that matched, and values are the list of fields that the term was\n * found in.\n */\nexport type MatchInfo = {\n [term: string]: string[]\n}\n\n/**\n * Type of the search results. Each search result indicates the document ID, the\n * terms that matched, the match information, the score, and all the stored\n * fields.\n */\nexport type SearchResult = {\n /**\n * The document ID\n */\n id: any,\n\n /**\n * List of document terms that matched. For example, if a prefix search for\n * `\"moto\"` matches `\"motorcycle\"`, `terms` will contain `\"motorcycle\"`.\n */\n terms: string[],\n\n /**\n * List of query terms that matched. For example, if a prefix search for\n * `\"moto\"` matches `\"motorcycle\"`, `queryTerms` will contain `\"moto\"`.\n */\n queryTerms: string[],\n\n /**\n * Score of the search results\n */\n score: number,\n\n /**\n * Match information, see {@link MatchInfo}\n */\n match: MatchInfo,\n\n /**\n * Stored fields\n */\n [key: string]: any\n}\n\n/**\n * @ignore\n */\nexport type AsPlainObject = {\n documentCount: number,\n nextId: number,\n documentIds: { [shortId: string]: any }\n fieldIds: { [fieldName: string]: number }\n fieldLength: { [shortId: string]: number[] }\n averageFieldLength: number[],\n storedFields: { [shortId: string]: any }\n dirtCount?: number,\n index: [string, { [fieldId: string]: SerializedIndexEntry }][]\n serializationVersion: number\n}\n\nexport type QueryCombination = SearchOptions & { queries: Query[] }\n\n/**\n * Wildcard query, used to match all terms\n */\nexport type Wildcard = typeof MiniSearch.wildcard\n\n/**\n * Search query expression, either a query string or an expression tree\n * combining several queries with a combination of AND or OR.\n */\nexport type Query = QueryCombination | string | Wildcard\n\n/**\n * Options to control vacuuming behavior.\n *\n * Vacuuming cleans up document references made obsolete by {@link\n * MiniSearch.discard} from the index. On large indexes, vacuuming is\n * potentially costly, because it has to traverse the whole inverted index.\n * Therefore, in order to dilute this cost so it does not negatively affects the\n * application, vacuuming is performed in batches, with a delay between each\n * batch. These options are used to configure the batch size and the delay\n * between batches.\n */\nexport type VacuumOptions = {\n /**\n * Size of each vacuuming batch (the number of terms in the index that will be\n * traversed in each batch). Defaults to 1000.\n */\n batchSize?: number,\n\n /**\n * Wait time between each vacuuming batch in milliseconds. Defaults to 10.\n */\n batchWait?: number\n}\n\n/**\n * Sets minimum thresholds for `dirtCount` and `dirtFactor` that trigger an\n * automatic vacuuming.\n */\nexport type VacuumConditions = {\n /**\n * Minimum `dirtCount` (number of discarded documents since the last vacuuming)\n * under which auto vacuum is not triggered. It defaults to 20.\n */\n minDirtCount?: number\n\n /**\n * Minimum `dirtFactor` (proportion of discarded documents over the total)\n * under which auto vacuum is not triggered. It defaults to 0.1.\n */\n minDirtFactor?: number,\n}\n\n/**\n * Options to control auto vacuum behavior. When discarding a document with\n * {@link MiniSearch#discard}, a vacuuming operation is automatically started if\n * the `dirtCount` and `dirtFactor` are above the `minDirtCount` and\n * `minDirtFactor` thresholds defined by this configuration. See {@link\n * VacuumConditions} for details on these.\n *\n * Also, `batchSize` and `batchWait` can be specified, controlling batching\n * behavior (see {@link VacuumOptions}).\n */\nexport type AutoVacuumOptions = VacuumOptions & VacuumConditions\n\ntype QuerySpec = {\n prefix: boolean,\n fuzzy: number | boolean,\n term: string,\n termBoost: number\n}\n\ntype DocumentTermFreqs = Map<number, number>\ntype FieldTermData = Map<number, DocumentTermFreqs>\n\ninterface RawResultValue {\n // Intermediate score, before applying the final score based on number of\n // matched terms.\n score: number,\n\n // Set of all query terms that were matched. They may not be present in the\n // text exactly in the case of prefix/fuzzy matches. We must check for\n // uniqueness before adding a new term. This is much faster than using a set,\n // because the number of elements is relatively small.\n terms: string[],\n\n // All terms that were found in the content, including the fields in which\n // they were present. This object will be provided as part of the final search\n // results.\n match: MatchInfo,\n}\n\ntype RawResult = Map<number, RawResultValue>\n\n/**\n * {@link MiniSearch} is the main entrypoint class, implementing a full-text\n * search engine in memory.\n *\n * @typeParam T The type of the documents being indexed.\n *\n * ### Basic example:\n *\n * ```javascript\n * const documents = [\n * {\n * id: 1,\n * title: 'Moby Dick',\n * text: 'Call me Ishmael. Some years ago...',\n * category: 'fiction'\n * },\n * {\n * id: 2,\n * title: 'Zen and the Art of Motorcycle Maintenance',\n * text: 'I can see by my watch...',\n * category: 'fiction'\n * },\n * {\n * id: 3,\n * title: 'Neuromancer',\n * text: 'The sky above the port was...',\n * category: 'fiction'\n * },\n * {\n * id: 4,\n * title: 'Zen and the Art of Archery',\n * text: 'At first sight it must seem...',\n * category: 'non-fiction'\n * },\n * // ...and more\n * ]\n *\n * // Create a search engine that indexes the 'title' and 'text' fields for\n * // full-text search. Search results will include 'title' and 'category' (plus the\n * // id field, that is always stored and returned)\n * const miniSearch = new MiniSearch({\n * fields: ['title', 'text'],\n * storeFields: ['title', 'category']\n * })\n *\n * // Add documents to the index\n * miniSearch.addAll(documents)\n *\n * // Search for documents:\n * let results = miniSearch.search('zen art motorcycle')\n * // => [\n * // { id: 2, title: 'Zen and the Art of Motorcycle Maintenance', category: 'fiction', score: 2.77258 },\n * // { id: 4, title: 'Zen and the Art of Archery', category: 'non-fiction', score: 1.38629 }\n * // ]\n * ```\n */\nexport default class MiniSearch<T = any> {\n protected _options: OptionsWithDefaults<T>\n protected _index: SearchableMap<FieldTermData>\n protected _documentCount: number\n protected _documentIds: Map<number, any>\n protected _idToShortId: Map<any, number>\n protected _fieldIds: { [key: string]: number }\n protected _fieldLength: Map<number, number[]>\n protected _avgFieldLength: number[]\n protected _nextId: number\n protected _storedFields: Map<number, Record<string, unknown>>\n protected _dirtCount: number\n private _currentVacuum: Promise<void> | null\n private _enqueuedVacuum: Promise<void> | null\n private _enqueuedVacuumConditions: VacuumConditions | undefined\n\n /**\n * The special wildcard symbol that can be passed to {@link MiniSearch#search}\n * to match all documents\n */\n static readonly wildcard: unique symbol = Symbol('*')\n\n /**\n * @param options Configuration options\n *\n * ### Examples:\n *\n * ```javascript\n * // Create a search engine that indexes the 'title' and 'text' fields of your\n * // documents:\n * const miniSearch = new MiniSearch({ fields: ['title', 'text'] })\n * ```\n *\n * ### ID Field:\n *\n * ```javascript\n * // Your documents are assumed to include a unique 'id' field, but if you want\n * // to use a different field for document identification, you can set the\n * // 'idField' option:\n * const miniSearch = new MiniSearch({ idField: 'key', fields: ['title', 'text'] })\n * ```\n *\n * ### Options and defaults:\n *\n * ```javascript\n * // The full set of options (here with their default value) is:\n * const miniSearch = new MiniSearch({\n * // idField: field that uniquely identifies a document\n * idField: 'id',\n *\n * // extractField: function used to get the value of a field in a document.\n * // By default, it assumes the document is a flat object with field names as\n * // property keys and field values as string property values, but custom logic\n * // can be implemented by setting this option to a custom extractor function.\n * extractField: (document, fieldName) => document[fieldName],\n *\n * // tokenize: function used to split fields into individual terms. By\n * // default, it is also used to tokenize search queries, unless a specific\n * // `tokenize` search option is supplied. When tokenizing an indexed field,\n * // the field name is passed as the second argument.\n * tokenize: (string, _fieldName) => string.split(SPACE_OR_PUNCTUATION),\n *\n * // processTerm: function used to process each tokenized term before\n * // indexing. It can be used for stemming and normalization. Return a falsy\n * // value in order to discard a term. By default, it is also used to process\n * // search queries, unless a specific `processTerm` option is supplied as a\n * // search option. When processing a term from a indexed field, the field\n * // name is passed as the second argument.\n * processTerm: (term, _fieldName) => term.toLowerCase(),\n *\n * // searchOptions: default search options, see the `search` method for\n * // details\n * searchOptions: undefined,\n *\n * // fields: document fields to be indexed. Mandatory, but not set by default\n * fields: undefined\n *\n * // storeFields: document fields to be stored and returned as part of the\n * // search results.\n * storeFields: []\n * })\n * ```\n */\n constructor (options: Options<T>) {\n if (options?.fields == null) {\n throw new Error('MiniSearch: option \"fields\" must be provided')\n }\n\n const autoVacuum = (options.autoVacuum == null || options.autoVacuum === true) ? defaultAutoVacuumOptions : options.autoVacuum\n\n this._options = {\n ...defaultOptions,\n ...options,\n autoVacuum,\n searchOptions: { ...defaultSearchOptions, ...(options.searchOptions || {}) },\n autoSuggestOptions: { ...defaultAutoSuggestOptions, ...(options.autoSuggestOptions || {}) }\n }\n\n this._index = new SearchableMap()\n\n this._documentCount = 0\n\n this._documentIds = new Map()\n\n this._idToShortId = new Map()\n\n // Fields are defined during initialization, don't change, are few in\n // number, rarely need iterating over, and have string keys. Therefore in\n // this case an object is a better candidate than a Map to store the mapping\n // from field key to ID.\n this._fieldIds = {}\n\n this._fieldLength = new Map()\n\n this._avgFieldLength = []\n\n this._nextId = 0\n\n this._storedFields = new Map()\n\n this._dirtCount = 0\n\n this._currentVacuum = null\n\n this._enqueuedVacuum = null\n this._enqueuedVacuumConditions = defaultVacuumConditions\n\n this.addFields(this._options.fields)\n }\n\n /**\n * Adds a document to the index\n *\n * @param document The document to be indexed\n */\n add (document: T): void {\n const { extractField, stringifyField, tokenize, processTerm, fields, idField } = this._options\n const id = extractField(document, idField)\n if (id == null) {\n throw new Error(`MiniSearch: document does not have ID field \"${idField}\"`)\n }\n\n if (this._idToShortId.has(id)) {\n throw new Error(`MiniSearch: duplicate ID ${id}`)\n }\n\n const shortDocumentId = this.addDocumentId(id)\n this.saveStoredFields(shortDocumentId, document)\n\n for (const field of fields) {\n const fieldValue = extractField(document, field)\n if (fieldValue == null) continue\n\n const tokens = tokenize(stringifyField(fieldValue, field), field)\n const fieldId = this._fieldIds[field]\n\n const uniqueTerms = new Set(tokens).size\n this.addFieldLength(shortDocumentId, fieldId, this._documentCount - 1, uniqueTerms)\n\n for (const term of tokens) {\n const processedTerm = processTerm(term, field)\n if (Array.isArray(processedTerm)) {\n for (const t of processedTerm) {\n this.addTerm(fieldId, shortDocumentId, t)\n }\n } else if (processedTerm) {\n this.addTerm(fieldId, shortDocumentId, processedTerm)\n }\n }\n }\n }\n\n /**\n * Adds all the given documents to the index\n *\n * @param documents An array of documents to be indexed\n */\n addAll (documents: readonly T[]): void {\n for (const document of documents) this.add(document)\n }\n\n /**\n * Adds all the given documents to the index asynchronously.\n *\n * Returns a promise that resolves (to `undefined`) when the indexing is done.\n * This method is useful when index many documents, to avoid blocking the main\n * thread. The indexing is performed asynchronously and in chunks.\n *\n * @param documents An array of documents to be indexed\n * @param options Configuration options\n * @return A promise resolving to `undefined` when the indexing is done\n */\n addAllAsync (documents: readonly T[], options: { chunkSize?: number } = {}): Promise<void> {\n const { chunkSize = 10 } = options\n const acc: { chunk: T[], promise: Promise<void> } = { chunk: [], promise: Promise.resolve() }\n\n const { chunk, promise } = documents.reduce(({ chunk, promise }, document: T, i: number) => {\n chunk.push(document)\n if ((i + 1) % chunkSize === 0) {\n return {\n chunk: [],\n promise: promise\n .then(() => new Promise(resolve => setTimeout(resolve, 0)))\n .then(() => this.addAll(chunk))\n }\n } else {\n return { chunk, promise }\n }\n }, acc)\n\n return promise.then(() => this.addAll(chunk))\n }\n\n /**\n * Removes the given document from the index.\n *\n * The document to remove must NOT have changed between indexing and removal,\n * otherwise the index will be corrupted.\n *\n * This method requires passing the full document to be removed (not just the\n * ID), and immediately removes the document from the inverted index, allowing\n * memory to be released. A convenient alternative is {@link\n * MiniSearch#discard}, which needs only the document ID, and has the same\n * visible effect, but delays cleaning up the index until the next vacuuming.\n *\n * @param document The document to be removed\n */\n remove (document: T): void {\n const { tokenize, processTerm, extractField, stringifyField, fields, idField } = this._options\n const id = extractField(document, idField)\n\n if (id == null) {\n throw new Error(`MiniSearch: document does not have ID field \"${idField}\"`)\n }\n\n const shortId = this._idToShortId.get(id)\n\n if (shortId == null) {\n throw new Error(`MiniSearch: cannot remove document with ID ${id}: it is not in the index`)\n }\n\n for (const field of fields) {\n const fieldValue = extractField(document, field)\n if (fieldValue == null) continue\n\n const tokens = tokenize(stringifyField(fieldValue, field), field)\n const fieldId = this._fieldIds[field]\n\n const uniqueTerms = new Set(tokens).size\n this.removeFieldLength(shortId, fieldId, this._documentCount, uniqueTerms)\n\n for (const term of tokens) {\n const processedTerm = processTerm(term, field)\n if (Array.isArray(processedTerm)) {\n for (const t of processedTerm) {\n this.removeTerm(fieldId, shortId, t)\n }\n } else if (processedTerm) {\n this.removeTerm(fieldId, shortId, processedTerm)\n }\n }\n }\n\n this._storedFields.delete(shortId)\n this._documentIds.delete(shortId)\n this._idToShortId.delete(id)\n this._fieldLength.delete(shortId)\n this._documentCount -= 1\n }\n\n /**\n * Removes all the given documents from the index. If called with no arguments,\n * it removes _all_ documents from the index.\n *\n * @param documents The documents to be removed. If this argument is omitted,\n * all documents are removed. Note that, for removing all documents, it is\n * more efficient to call this method with no arguments than to pass all\n * documents.\n */\n removeAll (documents?: readonly T[]): void {\n if (documents) {\n for (const document of documents) this.remove(document)\n } else if (arguments.length > 0) {\n throw new Error('Expected documents to be present. Omit the argument to remove all documents.')\n } else {\n this._index = new SearchableMap()\n this._documentCount = 0\n this._documentIds = new Map()\n this._idToShortId = new Map()\n this._fieldLength = new Map()\n this._avgFieldLength = []\n this._storedFields = new Map()\n this._nextId = 0\n }\n }\n\n /**\n * Discards the document with the given ID, so it won't appear in search results\n *\n * It has the same visible effect of {@link MiniSearch.remove} (both cause the\n * document to stop appearing in searches), but a different effect on the\n * internal data structures:\n *\n * - {@link MiniSearch#remove} requires passing the full document to be\n * removed as argument, and removes it from the inverted index immediately.\n *\n * - {@link MiniSearch#discard} instead only needs the document ID, and\n * works by marking the current version of the document as discarded, so it\n * is immediately ignored by searches. This is faster and more convenient\n * than {@link MiniSearch#remove}, but the index is not immediately\n * modified. To take care of that, vacuuming is performed after a certain\n * number of documents are discarded, cleaning up the index and allowing\n * memory to be released.\n *\n * After discarding a document, it is possible to re-add a new version, and\n * only the new version will appear in searches. In other words, discarding\n * and re-adding a document works exactly like removing and re-adding it. The\n * {@link MiniSearch.replace} method can also be used to replace a document\n * with a new version.\n *\n * #### Details about vacuuming\n *\n * Repetite calls to this method would leave obsolete document references in\n * the index, invisible to searches. Two mechanisms take care of cleaning up:\n * clean up during search, and vacuuming.\n *\n * - Upon search, whenever a discarded ID is found (and ignored for the\n * results), references to the discarded document are removed from the\n * inverted index entries for the search terms. This ensures that subsequent\n * searches for the same terms do not need to skip these obsolete references\n * again.\n *\n * - In addition, vacuuming is performed automatically by default (see the\n * `autoVacuum` field in {@link Options}) after a certain number of\n * documents are discarded. Vacuuming traverses all terms in the index,\n * cleaning up all references to discarded documents. Vacuuming can also be\n * triggered manually by calling {@link MiniSearch#vacuum}.\n *\n * @param id The ID of the document to be discarded\n */\n discard (id: any): void {\n const shortId = this._idToShortId.get(id)\n\n if (shortId == null) {\n throw new Error(`MiniSearch: cannot discard document with ID ${id}: it is not in the index`)\n }\n\n this._idToShortId.delete(id)\n this._documentIds.delete(shortId)\n this._storedFields.delete(shortId)\n\n ;(this._fieldLength.get(shortId) || []).forEach((fieldLength, fieldId) => {\n this.removeFieldLength(shortId, fieldId, this._documentCount, fieldLength)\n })\n\n this._fieldLength.delete(shortId)\n\n this._documentCount -= 1\n this._dirtCount += 1\n\n this.maybeAutoVacuum()\n }\n\n private maybeAutoVacuum (): void {\n if (this._options.autoVacuum === false) { return }\n\n const { minDirtFactor, minDirtCount, batchSize, batchWait } = this._options.autoVacuum\n this.conditionalVacuum({ batchSize, batchWait }, { minDirtCount, minDirtFactor })\n }\n\n /**\n * Discards the documents with the given IDs, so they won't appear in search\n * results\n *\n * It is equivalent to calling {@link MiniSearch#discard} for all the given\n * IDs, but with the optimization of triggering at most one automatic\n * vacuuming at the end.\n *\n * Note: to remove all documents from the index, it is faster and more\n * convenient to call {@link MiniSearch.removeAll} with no argument, instead\n * of passing all IDs to this method.\n */\n discardAll (ids: readonly any[]): void {\n const autoVacuum = this._options.autoVacuum\n\n try {\n this._options.autoVacuum = false\n\n for (const id of ids) {\n this.discard(id)\n }\n } finally {\n this._options.autoVacuum = autoVacuum\n }\n\n this.maybeAutoVacuum()\n }\n\n /**\n * It replaces an existing document with the given updated version\n *\n * It works by discarding the current version and adding the updated one, so\n * it is functionally equivalent to calling {@link MiniSearch#discard}\n * followed by {@link MiniSearch#add}. The ID of the updated document should\n * be the same as the original one.\n *\n * Since it uses {@link MiniSearch#discard} internally, this method relies on\n * vacuuming to clean up obsolete document references from the index, allowing\n * memory to be released (see {@link MiniSearch#discard}).\n *\n * @param updatedDocument The updated document to replace the old version\n * with\n */\n replace (updatedDocument: T): void {\n const { idField, extractField } = this._options\n const id = extractField(updatedDocument, idField)\n\n this.discard(id)\n this.add(updatedDocument)\n }\n\n /**\n * Triggers a manual vacuuming, cleaning up references to discarded documents\n * from the inverted index\n *\n * Vacuuming is only useful for applications that use the {@link\n * MiniSearch#discard} or {@link MiniSearch#replace} methods.\n *\n * By default, vacuuming is performed automatically when needed (controlled by\n * the `autoVacuum` field in {@link Options}), so there is usually no need to\n * call this method, unless one wants to make sure to perform vacuuming at a\n * specific moment.\n *\n * Vacuuming traverses all terms in the inverted index in batches, and cleans\n * up references to discarded documents from the posting list, allowing memory\n * to be released.\n *\n * The method takes an optional object as argument with the following keys:\n *\n * - `batchSize`: the size of each batch (1000 by default)\n *\n * - `batchWait`: the number of milliseconds to wait between batches (10 by\n * default)\n *\n * On large indexes, vacuuming could have a non-negligible cost: batching\n * avoids blocking the thread for long, diluting this cost so that it is not\n * negatively affecting the application. Nonetheless, this method should only\n * be called when necessary, and relying on automatic vacuuming is usually\n * better.\n *\n * It returns a promise that resolves (to undefined) when the clean up is\n * completed. If vacuuming is already ongoing at the time this method is\n * called, a new one is enqueued immediately after the ongoing one, and a\n * corresponding promise is returned. However, no more than one vacuuming is\n * enqueued on top of the ongoing one, even if this method is called more\n * times (enqueuing multiple ones would be useless).\n *\n * @param options Configuration options for the batch size and delay. See\n * {@link VacuumOptions}.\n */\n vacuum (options: VacuumOptions = {}): Promise<void> {\n return this.conditionalVacuum(options)\n }\n\n private conditionalVacuum (options: VacuumOptions, conditions?: VacuumConditions): Promise<void> {\n // If a vacuum is already ongoing, schedule another as soon as it finishes,\n // unless there's already one enqueued. If one was already enqueued, do not\n // enqueue another on top, but make sure that the conditions are the\n // broadest.\n if (this._currentVacuum) {\n this._enqueuedVacuumConditions = this._enqueuedVacuumConditions && conditions\n if (this._enqueuedVacuum != null) { return this._enqueuedVacuum }\n\n this._enqueuedVacuum = this._currentVacuum.then(() => {\n const conditions = this._enqueuedVacuumConditions\n this._enqueuedVacuumConditions = defaultVacuumConditions\n return this.performVacuuming(options, conditions)\n })\n return this._enqueuedVacuum\n }\n\n if (this.vacuumConditionsMet(conditions) === false) { return Promise.resolve() }\n\n this._currentVacuum = this.performVacuuming(options)\n return this._currentVacuum\n }\n\n private async performVacuuming (options: VacuumOptions, conditions?: VacuumConditions): Promise<void> {\n const initialDirtCount = this._dirtCount\n\n if (this.vacuumConditionsMet(conditions)) {\n const batchSize = options.batchSize || defaultVacuumOptions.batchSize\n const batchWait = options.batchWait || defaultVacuumOptions.batchWait\n let i = 1\n\n for (const [term, fieldsData] of this._index) {\n for (const [fieldId, fieldIndex] of fieldsData) {\n for (const [shortId] of fieldIndex) {\n if (this._documentIds.has(shortId)) { continue }\n\n if (fieldIndex.size <= 1) {\n fieldsData.delete(fieldId)\n } else {\n fieldIndex.delete(shortId)\n }\n }\n }\n\n if (this._index.get(term)!.size === 0) {\n this._index.delete(term)\n }\n\n if (i % batchSize === 0) {\n await new Promise((resolve) => setTimeout(resolve, batchWait))\n }\n\n i += 1\n }\n\n this._dirtCount -= initialDirtCount\n }\n\n // Make the next lines always async, so they execute after this function returns\n await null\n\n this._currentVacuum = this._enqueuedVacuum\n this._enqueuedVacuum = null\n }\n\n private vacuumConditionsMet (conditions?: VacuumConditions) {\n if (conditions == null) { return true }\n\n let { minDirtCount, minDirtFactor } = conditions\n minDirtCount = minDirtCount || defaultAutoVacuumOptions.minDirtCount\n minDirtFactor = minDirtFactor || defaultAutoVacuumOptions.minDirtFactor\n\n return this.dirtCount >= minDirtCount && this.dirtFactor >= minDirtFactor\n }\n\n /**\n * Is `true` if a vacuuming operation is ongoing, `false` otherwise\n */\n get isVacuuming (): boolean {\n return this._currentVacuum != null\n }\n\n /**\n * The number of documents discarded since the most recent vacuuming\n */\n get dirtCount (): number {\n return this._dirtCount\n }\n\n /**\n * A number between 0 and 1 giving an indication about the proportion of\n * documents that are discarded, and can therefore be cleaned up by vacuuming.\n * A value close to 0 means that the index is relatively clean, while a higher\n * value means that the index is relatively dirty, and vacuuming could release\n * memory.\n */\n get dirtFactor (): number {\n return this._dirtCount / (1 + this._documentCount + this._dirtCount)\n }\n\n /**\n * Returns `true` if a document with the given ID is present in the index and\n * available for search, `false` otherwise\n *\n * @param id The document ID\n */\n has (id: any): boolean {\n return this._idToShortId.has(id)\n }\n\n /**\n * Returns the stored fields (as configured in the `storeFields` constructor\n * option) for the given document ID. Returns `undefined` if the document is\n * not present in the index.\n *\n * @param id The document ID\n */\n getStoredFields (id: any): Record<string, unknown> | undefined {\n const shortId = this._idToShortId.get(id)\n\n if (shortId == null) { return undefined }\n\n return this._storedFields.get(shortId)\n }\n\n /**\n * Search for documents matching the given search query.\n *\n * The result is a list of scored document IDs matching the query, sorted by\n * descending score, and each including data about which terms were matched and\n * in which fields.\n *\n * ### Basic usage:\n *\n * ```javascript\n * // Search for \"zen art motorcycle\" with default options: terms have to match\n * // exactly, and individual terms are joined with OR\n * miniSearch.search('zen art motorcycle')\n * // => [ { id: 2, score: 2.77258, match: { ... } }, { id: 4, score: 1.38629, match: { ... } } ]\n * ```\n *\n * ### Restrict search to specific fields:\n *\n * ```javascript\n * // Search only in the 'title' field\n * miniSearch.search('zen', { fields: ['title'] })\n * ```\n *\n * ### Field boosting:\n *\n * ```javascript\n * // Boost a field\n * miniSearch.search('zen', { boost: { title: 2 } })\n * ```\n *\n * ### Prefix search:\n *\n * ```javascript\n * // Search for \"moto\" with prefix search (it will match documents\n * // containing terms that start with \"moto\" or \"neuro\")\n * miniSearch.search('moto neuro', { prefix: true })\n * ```\n *\n * ### Fuzzy search:\n *\n * ```javascript\n * // Search for \"ismael\" with fuzzy search (it will match documents containing\n * // terms similar to \"ismael\", with a maximum edit distance of 0.2 term.length\n * // (rounded to nearest integer)\n * miniSearch.search('ismael', { fuzzy: 0.2 })\n * ```\n *\n * ### Combining strategies:\n *\n * ```javascript\n * // Mix of exact match, prefix search, and fuzzy search\n * miniSearch.search('ismael mob', {\n * prefix: true,\n * fuzzy: 0.2\n * })\n * ```\n *\n * ### Advanced prefix and fuzzy search:\n *\n * ```javascript\n * // Perform fuzzy and prefix search depending on the search term. Here\n * // performing prefix and fuzzy search only on terms longer than 3 characters\n * miniSearch.search('ismael mob', {\n * prefix: term => term.length > 3\n * fuzzy: term => term.length > 3 ? 0.2 : null\n * })\n * ```\n *\n * ### Combine with AND:\n *\n * ```javascript\n * // Combine search terms with AND (to match only documents that contain both\n * // \"motorcycle\" and \"art\")\n * miniSearch.search('motorcycle art', { combineWith: 'AND' })\n * ```\n *\n * ### Combine with AND_NOT:\n *\n * There is also an AND_NOT combinator, that finds documents that match the\n * first term, but do not match any of the other terms. This combinator is\n * rarely useful with simple queries, and is meant to be used with advanced\n * query combinations (see later for more details).\n *\n * ### Filtering results:\n *\n * ```javascript\n * // Filter only results in the 'fiction' category (assuming that 'category'\n * // is a stored field)\n * miniSearch.search('motorcycle art', {\n * filter: (result) => result.category === 'fiction'\n * })\n * ```\n *\n * ### Wildcard query\n *\n * Searching for an empty string (assuming the default tokenizer) returns no\n * results. Sometimes though, one needs to match all documents, like in a\n * \"wildcard\" search. This is possible by passing the special value\n * {@link MiniSearch.wildcard} as the query:\n *\n * ```javascript\n * // Return search results for all documents\n * miniSearch.search(MiniSearch.wildcard)\n * ```\n *\n * Note that search options such as `filter` and `boostDocument` are still\n * applied, influencing which results are returned, and their order:\n *\n * ```javascript\n * // Return search results for all documents in the 'fiction' category\n * miniSearch.search(MiniSearch.wildcard, {\n * filter: (result) => result.category === 'fiction'\n * })\n * ```\n *\n * ### Advanced combination of queries:\n *\n * It is possible to combine different subqueries with OR, AND, and AND_NOT,\n * and even with different search options, by passing a query expression\n * tree object as the first argument, instead of a string.\n *\n * ```javascript\n * // Search for documents that contain \"zen\" and (\"motorcycle\" or \"archery\")\n * miniSearch.search({\n * combineWith: 'AND',\n * queries: [\n * 'zen',\n * {\n * combineWith: 'OR',\n * queries: ['motorcycle', 'archery']\n * }\n * ]\n * })\n *\n * // Search for documents that contain (\"apple\" or \"pear\") but not \"juice\" and\n * // not \"tree\"\n * miniSearch.search({\n * combineWith: 'AND_NOT',\n * queries: [\n * {\n * combineWith: 'OR',\n * queries: ['apple', 'pear']\n * },\n * 'juice',\n * 'tree'\n * ]\n * })\n * ```\n *\n * Each node in the expression tree can be either a string, or an object that\n * supports all {@link SearchOptions} fields, plus a `queries` array field for\n * subqueries.\n *\n * Note that, while this can become complicated to do by hand for complex or\n * deeply nested queries, it provides a formalized expression tree API for\n * external libraries that implement a parser for custom query languages.\n *\n * @param query Search query\n * @param searchOptions Search options. Each option, if not given, defaults to the corresponding value of `searchOptions` given to the constructor, or to the library default.\n */\n search (query: Query, searchOptions: SearchOptions = {}): SearchResult[] {\n const { searchOptions: globalSearchOptions } = this._options\n const searchOptionsWithDefaults: SearchOptionsWithDefaults = { ...globalSearchOptions, ...searchOptions }\n\n const rawResults = this.executeQuery(query, searchOptions)\n const results = []\n\n for (const [docId, { score, terms, match }] of rawResults) {\n // terms are the matched query terms, which will be returned to the user\n // as queryTerms. The quality is calculated based on them, as opposed to\n // the matched terms in the document (which can be different due to\n // prefix and fuzzy match)\n const quality = terms.length || 1\n\n const result = {\n id: this._documentIds.get(docId),\n score: score * quality,\n terms: Object.keys(match),\n queryTerms: terms,\n match\n }\n\n Object.assign(result, this._storedFields.get(docId))\n if (searchOptionsWithDefaults.filter == null || searchOptionsWithDefaults.filter(result)) {\n results.push(result)\n }\n }\n\n // If it's a wildcard query, and no document boost is applied, skip sorting\n // the results, as all results have the same score of 1\n if (query === MiniSearch.wildcard && searchOptionsWithDefaults.boostDocument == null) {\n return results\n }\n\n results.sort(byScore)\n return results\n }\n\n /**\n * Provide suggestions for the given search query\n *\n * The result is a list of suggested modified search queries, derived from the\n * given search query, each with a relevance score, sorted by descending score.\n *\n * By default, it uses the same options used for search, except that by\n * default it performs prefix search on the last term of the query, and\n * combine terms with `'AND'` (requiring all query terms to match). Custom\n * options can be passed as a second argument. Defaults can be changed upon\n * calling the {@link MiniSearch} constructor, by passing a\n * `autoSuggestOptions` option.\n *\n * ### Basic usage:\n *\n * ```javascript\n * // Get suggestions for 'neuro':\n * miniSearch.autoSuggest('neuro')\n * // => [ { suggestion: 'neuromancer', terms: [ 'neuromancer' ], score: 0.46240 } ]\n * ```\n *\n * ### Multiple words:\n *\n * ```javascript\n * // Get suggestions for 'zen ar':\n * miniSearch.autoSuggest('zen ar')\n * // => [\n * // { suggestion: 'zen archery art', terms: [ 'zen', 'archery', 'art' ], score: 1.73332 },\n * // { suggestion: 'zen art', terms: [ 'zen', 'art' ], score: 1.21313 }\n * // ]\n * ```\n *\n * ### Fuzzy suggestions:\n *\n * ```javascript\n * // Correct spelling mistakes using fuzzy search:\n * miniSearch.autoSuggest('neromancer', { fuzzy: 0.2 })\n * // => [ { suggestion: 'neuromancer', terms: [ 'neuromancer' ], score: 1.03998 } ]\n * ```\n *\n * ### Filtering:\n *\n * ```javascript\n * // Get suggestions for 'zen ar', but only within the 'fiction' category\n * // (assuming that 'category' is a stored field):\n * miniSearch.autoSuggest('zen ar', {\n * filter: (result) => result.category === 'fiction'\n * })\n * // => [\n * // { suggestion: 'zen archery art', terms: [ 'zen', 'archery', 'art' ], score: 1.73332 },\n * // { suggestion: 'zen art', terms: [ 'zen', 'art' ], score: 1.21313 }\n * // ]\n * ```\n *\n * @param queryString Query string to be expanded into suggestions\n * @param options Search options. The supported options and default values\n * are the same as for the {@link MiniSearch#search} method, except that by\n * default prefix search is performed on the last term in the query, and terms\n * are combined with `'AND'`.\n * @return A sorted array of suggestions sorted by relevance score.\n */\n autoSuggest (queryString: string, options: SearchOptions = {}): Suggestion[] {\n options = { ...this._options.autoSuggestOptions, ...options }\n\n const suggestions: Map<string, Omit<Suggestion, 'suggestion'> & { count: number }> = new Map()\n\n for (const { score, terms } of this.search(queryString, options)) {\n const phrase = terms.join(' ')\n const suggestion = suggestions.get(phrase)\n if (suggestion != null) {\n suggestion.score += score\n suggestion.count += 1\n } else {\n suggestions.set(phrase, { score, terms, count: 1 })\n }\n }\n\n const results = []\n for (const [suggestion, { score, terms, count }] of suggestions) {\n results.push({ suggestion, terms, score: score / count })\n }\n\n results.sort(byScore)\n return results\n }\n\n /**\n * Total number of documents available to search\n */\n get documentCount (): number {\n return this._documentCount\n }\n\n /**\n * Number of terms in the index\n */\n get termCount (): number {\n return this._index.size\n }\n\n /**\n * Deserializes a JSON index (serialized with `JSON.stringify(miniSearch)`)\n * and instantiates a MiniSearch instance. It should be given the same options\n * originally used when serializing the index.\n *\n * ### Usage:\n *\n * ```javascript\n * // If the index was serialized with:\n * let miniSearch = new MiniSearch({ fields: ['title', 'text'] })\n * miniSearch.addAll(documents)\n *\n * const json = JSON.stringify(miniSearch)\n * // It can later be deserialized like this:\n * miniSearch = MiniSearch.loadJSON(json, { fields: ['title', 'text'] })\n * ```\n *\n * @param json JSON-serialized index\n * @param options configuration options, same as the constructor\n * @return An instance of MiniSearch deserialized from the given JSON.\n */\n static loadJSON<T = any> (json: string, options: Options<T>): MiniSearch<T> {\n if (options == null) {\n throw new Error('MiniSearch: loadJSON should be given the same options used when serializing the index')\n }\n return this.loadJS(JSON.parse(json), options)\n }\n\n /**\n * Async equivalent of {@link MiniSearch.loadJSON}\n *\n * This function is an alternative to {@link MiniSearch.loadJSON} that returns\n * a promise, and loads the index in batches, leaving pauses between them to avoid\n * blocking the main thread. It tends to be slower than the synchronous\n * version, but does not block the main thread, so it can be a better choice\n * when deserializing very large indexes.\n *\n * @param json JSON-serialized index\n * @param options configuration options, same as the constructor\n * @return A Promise that will resolve to an instance of MiniSearch deserialized from the given JSON.\n */\n static async loadJSONAsync<T = any> (json: string, options: Options<T>): Promise<MiniSearch<T>> {\n if (options == null) {\n throw new Error('MiniSearch: loadJSON should be given the same options used when serializing the index')\n }\n return this.loadJSAsync(JSON.parse(json), options)\n }\n\n /**\n * Returns the default value of an option. It will throw an error if no option\n * with the given name exists.\n *\n * @param optionName Name of the option\n * @return The default value of the given option\n *\n * ### Usage:\n *\n * ```javascript\n * // Get default tokenizer\n * MiniSearch.getDefault('tokenize')\n *\n * // Get default term processor\n * MiniSearch.getDefault('processTerm')\n *\n * // Unknown options will throw an error\n * MiniSearch.getDefault('notExisting')\n * // => throws 'MiniSearch: unknown option \"notExisting\"'\n * ```\n */\n static getDefault (optionName: string): any {\n if (defaultOptions.hasOwnProperty(optionName)) {\n return getOwnProperty(defaultOptions, optionName)\n } else {\n throw new Error(`MiniSearch: unknown option \"${optionName}\"`)\n }\n }\n\n /**\n * @ignore\n */\n static loadJS<T = any> (js: AsPlainObject, options: Options<T>): MiniSearch<T> {\n const {\n index,\n documentIds,\n fieldLength,\n storedFields,\n serializationVersion\n } = js\n\n const miniSearch = this.instantiateMiniSearch(js, options)\n\n miniSearch._documentIds = objectToNumericMap(documentIds)\n miniSearch._fieldLength = objectToNumericMap(fieldLength)\n miniSearch._storedFields = objectToNumericMap(storedFields)\n\n for (const [shortId, id] of miniSearch._documentIds) {\n miniSearch._idToShortId.set(id, shortId)\n }\n\n for (const [term, data] of index) {\n const dataMap = new Map() as FieldTermData\n\n for (const fieldId of Object.keys(data)) {\n let indexEntry = data[fieldId]\n\n // Version 1 used to nest the index entry inside a field called ds\n if (serializationVersion === 1) {\n indexEntry = indexEntry.ds as unknown as SerializedIndexEntry\n }\n\n dataMap.set(parseInt(fieldId, 10), objectToNumericMap(indexEntry) as DocumentTermFreqs)\n }\n\n miniSearch._index.set(term, dataMap)\n }\n\n return miniSearch\n }\n\n /**\n * @ignore\n */\n static async loadJSAsync<T = any> (js: AsPlainObject, options: Options<T>): Promise<MiniSearch<T>> {\n const {\n index,\n documentIds,\n fieldLength,\n storedFields,\n serializationVersion\n } = js\n\n const miniSearch = this.instantiateMiniSearch(js, options)\n\n miniSearch._documentIds = await objectToNumericMapAsync(documentIds)\n miniSearch._fieldLength = await objectToNumericMapAsync(fieldLength)\n miniSearch._storedFields = await objectToNumericMapAsync(storedFields)\n\n for (const [shortId, id] of miniSearch._documentIds) {\n miniSearch._idToShortId.set(id, shortId)\n }\n\n let count = 0\n for (const [term, data] of index) {\n const dataMap = new Map() as FieldTermData\n\n for (const fieldId of Object.keys(data)) {\n let indexEntry = data[fieldId]\n\n // Version 1 used to nest the index entry inside a field called ds\n if (serializationVersion === 1) {\n indexEntry = indexEntry.ds as unknown as SerializedIndexEntry\n }\n\n dataMap.set(parseInt(fieldId, 10), await objectToNumericMapAsync(indexEntry) as DocumentTermFreqs)\n }\n\n if (++count % 1000 === 0) await wait(0)\n miniSearch._index.set(term, dataMap)\n }\n\n return miniSearch\n }\n\n /**\n * @ignore\n */\n private static instantiateMiniSearch<T = any> (js: AsPlainObject, options: Options<T>): MiniSearch<T> {\n const {\n documentCount,\n nextId,\n fieldIds,\n averageFieldLength,\n dirtCount,\n serializationVersion\n } = js\n\n if (serializationVersion !== 1 && serializationVersion !== 2) {\n throw new Error('MiniSearch: cannot deserialize an index created with an incompatible version')\n }\n\n const miniSearch = new MiniSearch(options)\n\n miniSearch._documentCount = documentCount\n miniSearch._nextId = nextId\n miniSearch._idToShortId = new Map<any, number>()\n miniSearch._fieldIds = fieldIds\n miniSearch._avgFieldLength = averageFieldLength\n miniSearch._dirtCount = dirtCount || 0\n miniSearch._index = new SearchableMap()\n\n return miniSearch\n }\n\n /**\n * @ignore\n */\n private executeQuery (query: Query, searchOptions: SearchOptions = {}): RawResult {\n if (query === MiniSearch.wildcard) {\n return this.executeWildcardQuery(searchOptions)\n }\n\n if (typeof query !== 'string') {\n const options = { ...searchOptions, ...query, queries: undefined }\n const results = query.queries.map((subquery) => this.executeQuery(subquery, options))\n return this.combineResults(results, options.combineWith)\n }\n\n const { tokenize, processTerm, searchOptions: globalSearchOptions } = this._options\n const options = { tokenize, processTerm, ...globalSearchOptions, ...searchOptions }\n const { tokenize: searchTokenize, processTerm: searchProcessTerm } = options\n const terms = searchTokenize(query)\n .flatMap((term: string) => searchProcessTerm(term))\n .filter((term) => !!term) as string[]\n const queries: QuerySpec[] = terms.map(termToQuerySpec(options))\n const results = queries.map(query => this.executeQuerySpec(query, options))\n\n return this.combineResults(results, options.combineWith)\n }\n\n /**\n * @ignore\n */\n private executeQuerySpec (query: QuerySpec, searchOptions: SearchOptions): RawResult {\n const options: SearchOptionsWithDefaults = { ...this._options.searchOptions, ...searchOptions }\n\n const boosts = (options.fields || this._options.fields).reduce((boosts, field) =>\n ({ ...boosts, [field]: getOwnProperty(options.boost, field) || 1 }), {})\n\n const {\n boostDocument,\n weights,\n maxFuzzy,\n bm25: bm25params\n } = options\n\n const { fuzzy: fuzzyWeight, prefix: prefixWeight } = { ...defaultSearchOptions.weights, ...weights }\n\n const data = this._index.get(query.term)\n const results = this.termResults(query.term, query.term, 1, query.termBoost, data, boosts, boostDocument, bm25params)\n\n let prefixMatches\n let fuzzyMatches\n\n if (query.prefix) {\n prefixMatches = this._index.atPrefix(query.term)\n }\n\n if (query.fuzzy) {\n const fuzzy = (query.fuzzy === true) ? 0.2 : query.fuzzy\n const maxDistance = fuzzy < 1 ? Math.min(maxFuzzy, Math.round(query.term.length * fuzzy)) : fuzzy\n if (maxDistance) fuzzyMatches = this._index.fuzzyGet(query.term, maxDistance)\n }\n\n if (prefixMatches) {\n for (const [term, data] of prefixMatches) {\n const distance = term.length - query.term.length\n if (!distance) { continue } // Skip exact match.\n\n // Delete the term from fuzzy results (if present) if it is also a\n // prefix result. This entry will always be scored as a prefix result.\n fuzzyMatches?.delete(term)\n\n // Weight gradually approaches 0 as distance goes to infinity, with the\n // weight for the hypothetical distance 0 being equal to prefixWeight.\n // The rate of change is much lower than that of fuzzy matches to\n // account for the fact that prefix matches stay more relevant than\n // fuzzy matches for longer distances.\n const weight = prefixWeight * term.length / (term.length + 0.3 * distance)\n this.termResults(query.term, term, weight, query.termBoost, data, boosts, boostDocument, bm25params, results)\n }\n }\n\n if (fuzzyMatches) {\n for (const term of fuzzyMatches.keys()) {\n const [data, distance] = fuzzyMatches.get(term)!\n if (!distance) { continue } // Skip exact match.\n\n // Weight gradually approaches 0 as distance goes to infinity, with the\n // weight for the hypothetical distance 0 being equal to fuzzyWeight.\n const weight = fuzzyWeight * term.length / (term.length + distance)\n this.termResults(query.term, term, weight, query.termBoost, data, boosts, boostDocument, bm25params, results)\n }\n }\n\n return results\n }\n\n /**\n * @ignore\n */\n private executeWildcardQuery (searchOptions: SearchOptions): RawResult {\n const results = new Map() as RawResult\n const options: SearchOptionsWithDefaults = { ...this._options.searchOptions, ...searchOptions }\n\n for (const [shortId, id] of this._documentIds) {\n const score = options.boostDocument ? options.boostDocument(id, '', this._storedFields.get(shortId)) : 1\n results.set(shortId, {\n score,\n terms: [],\n match: {}\n })\n }\n\n return results\n }\n\n /**\n * @ignore\n */\n private combineResults (results: RawResult[], combineWith: CombinationOperator = OR): RawResult {\n if (results.length === 0) { return new Map() }\n const operator = combineWith.toLowerCase()\n const combinator = (combinators as Record<string, CombinatorFunction>)[operator]\n\n if (!combinator) {\n throw new Error(`Invalid combination operator: ${combineWith}`)\n }\n\n return results.reduce(combinator) || new Map()\n }\n\n /**\n * Allows serialization of the index to JSON, to possibly store it and later\n * deserialize it with {@link MiniSearch.loadJSON}.\n *\n * Normally one does not directly call this method, but rather call the\n * standard JavaScript `JSON.stringify()` passing the {@link MiniSearch}\n * instance, and JavaScript will internally call this method. Upon\n * deserialization, one must pass to {@link MiniSearch.loadJSON} the same\n * options used to create the original instance that was serialized.\n *\n * ### Usage:\n *\n * ```javascript\n * // Serialize the index:\n * let miniSearch = new MiniSearch({ fields: ['title', 'text'] })\n * miniSearch.addAll(documents)\n * const json = JSON.stringify(miniSearch)\n *\n * // Later, to deserialize it:\n * miniSearch = MiniSearch.loadJSON(json, { fields: ['title', 'text'] })\n * ```\n *\n * @return A plain-object serializable representation of the search index.\n */\n toJSON (): AsPlainObject {\n const index: [string, { [key: string]: SerializedIndexEntry }][] = []\n\n for (const [term, fieldIndex] of this._index) {\n const data: { [key: string]: SerializedIndexEntry } = {}\n\n for (const [fieldId, freqs] of fieldIndex) {\n data[fieldId] = Object.fromEntries(freqs)\n }\n\n index.push([term, data])\n }\n\n return {\n documentCount: this._documentCount,\n nextId: this._nextId,\n documentIds: Object.fromEntries(this._documentIds),\n fieldIds: this._fieldIds,\n fieldLength: Object.fromEntries(this._fieldLength),\n averageFieldLength: this._avgFieldLength,\n storedFields: Object.fromEntries(this._storedFields),\n dirtCount: this._dirtCount,\n index,\n serializationVersion: 2\n }\n }\n\n /**\n * @ignore\n */\n private termResults (\n sourceTerm: string,\n derivedTerm: string,\n termWeight: number,\n termBoost: number,\n fieldTermData: FieldTermData | undefined,\n fieldBoosts: { [field: string]: number },\n boostDocumentFn: ((id: any, term: string, storedFields?: Record<string, unknown>) => number) | undefined,\n bm25params: BM25Params,\n results: RawResult = new Map()\n ): RawResult {\n if (fieldTermData == null) return results\n\n for (const field of Object.keys(fieldBoosts)) {\n const fieldBoost = fieldBoosts[field]\n const fieldId = this._fieldIds[field]\n\n const fieldTermFreqs = fieldTermData.get(fieldId)\n if (fieldTermFreqs == null) continue\n\n let matchingFields = fieldTermFreqs.size\n const avgFieldLength = this._avgFieldLength[fieldId]\n\n for (const docId of fieldTermFreqs.keys()) {\n if (!this._documentIds.has(docId)) {\n this.removeTerm(fieldId, docId, derivedTerm)\n matchingFields -= 1\n continue\n }\n\n const docBoost = boostDocumentFn ? boostDocumentFn(this._documentIds.get(docId), derivedTerm, this._storedFields.get(docId)) : 1\n if (!docBoost) continue\n\n const termFreq = fieldTermFreqs.get(docId)!\n const fieldLength = this._fieldLength.get(docId)![fieldId]\n\n // NOTE: The total number of fields is set to the number of documents\n // `this._documentCount`. It could also make sense to use the number of\n // documents where the current field is non-blank as a normalization\n // factor. This will make a difference in scoring if the field is rarely\n // present. This is currently not supported, and may require further\n // analysis to see if it is a valid use case.\n const rawScore = calcBM25Score(termFreq, matchingFields, this._documentCount, fieldLength, avgFieldLength, bm25params)\n const weightedScore = termWeight * termBoost * fieldBoost * docBoost * rawScore\n\n const result = results.get(docId)\n if (result) {\n result.score += weightedScore\n assignUniqueTerm(result.terms, sourceTerm)\n const match = getOwnProperty(result.match, derivedTerm)\n if (match) {\n match.push(field)\n } else {\n result.match[derivedTerm] = [field]\n }\n } else {\n results.set(docId, {\n score: weightedScore,\n terms: [sourceTerm],\n match: { [derivedTerm]: [field] }\n })\n }\n }\n }\n\n return results\n }\n\n /**\n * @ignore\n */\n private addTerm (fieldId: number, documentId: number, term: string): void {\n const indexData = this._index.fetch(term, createMap)\n\n let fieldIndex = indexData.get(fieldId)\n if (fieldIndex == null) {\n fieldIndex = new Map()\n fieldIndex.set(documentId, 1)\n indexData.set(fieldId, fieldIndex)\n } else {\n const docs = fieldIndex.get(documentId)\n fieldIndex.set(documentId, (docs || 0) + 1)\n }\n }\n\n /**\n * @ignore\n */\n private removeTerm (fieldId: number, documentId: number, term: string): void {\n if (!this._index.has(term)) {\n this.warnDocumentChanged(documentId, fieldId, term)\n return\n }\n\n const indexData = this._index.fetch(term, createMap)\n\n const fieldIndex = indexData.get(fieldId)\n if (fieldIndex == null || fieldIndex.get(documentId) == null) {\n this.warnDocumentChanged(documentId, fieldId, term)\n } else if (fieldIndex.get(documentId)! <= 1) {\n if (fieldIndex.size <= 1) {\n indexData.delete(fieldId)\n } else {\n fieldIndex.delete(documentId)\n }\n } else {\n fieldIndex.set(documentId, fieldIndex.get(documentId)! - 1)\n }\n\n if (this._index.get(term)!.size === 0) {\n this._index.delete(term)\n }\n }\n\n /**\n * @ignore\n */\n private warnDocumentChanged (shortDocumentId: number, fieldId: number, term: string): void {\n for (const fieldName of Object.keys(this._fieldIds)) {\n if (this._fieldIds[fieldName] === fieldId) {\n this._options.logger('warn', `MiniSearch: document with ID ${this._documentIds.get(shortDocumentId)} has changed before removal: term \"${term}\" was not present in field \"${fieldName}\". Removing a document after it has changed can corrupt the index!`, 'version_conflict')\n return\n }\n }\n }\n\n /**\n * @ignore\n */\n private addDocumentId (documentId: any): number {\n const shortDocumentId = this._nextId\n this._idToShortId.set(documentId, shortDocumentId)\n this._documentIds.set(shortDocumentId, documentId)\n this._documentCount += 1\n this._nextId += 1\n return shortDocumentId\n }\n\n /**\n * @ignore\n */\n private addFields (fields: string[]): void {\n for (let i = 0; i < fields.length; i++) {\n this._fieldIds[fields[i]] = i\n }\n }\n\n /**\n * @ignore\n */\n private addFieldLength (documentId: number, fieldId: number, count: number, length: number): void {\n let fieldLengths = this._fieldLength.get(documentId)\n if (fieldLengths == null) this._fieldLength.set(documentId, fieldLengths = [])\n fieldLengths[fieldId] = length\n\n const averageFieldLength = this._avgFieldLength[fieldId] || 0\n const totalFieldLength = (averageFieldLength * count) + length\n this._avgFieldLength[fieldId] = totalFieldLength / (count + 1)\n }\n\n /**\n * @ignore\n */\n private removeFieldLength (documentId: number, fieldId: number, count: number, length: number): void {\n if (count === 1) {\n this._avgFieldLength[fieldId] = 0\n return\n }\n const totalFieldLength = (this._avgFieldLength[fieldId] * count) - length\n this._avgFieldLength[fieldId] = totalFieldLength / (count - 1)\n }\n\n /**\n * @ignore\n */\n private saveStoredFields (documentId: number, doc: T): void {\n const { storeFields, extractField } = this._options\n if (storeFields == null || storeFields.length === 0) { return }\n\n let documentFields = this._storedFields.get(documentId)\n if (documentFields == null) this._storedFields.set(documentId, documentFields = {})\n\n for (const fieldName of storeFields) {\n const fieldValue = extractField(doc, fieldName)\n if (fieldValue !== undefined) documentFields[fieldName] = fieldValue\n }\n }\n}\n\nconst getOwnProperty = (object: any, property: string) =>\n Object.prototype.hasOwnProperty.call(object, property) ? object[property] : undefined\n\ntype CombinatorFunction = (a: RawResult, b: RawResult) => RawResult\n\nconst combinators: Record<LowercaseCombinationOperator, CombinatorFunction> = {\n [OR]: (a: RawResult, b: RawResult) => {\n for (const docId of b.keys()) {\n const existing = a.get(docId)\n if (existing == null) {\n a.set(docId, b.get(docId)!)\n } else {\n const { score, terms, match } = b.get(docId)!\n existing.score = existing.score + score\n existing.match = Object.assign(existing.match, match)\n assignUniqueTerms(existing.terms, terms)\n }\n }\n\n return a\n },\n [AND]: (a: RawResult, b: RawResult) => {\n const combined = new Map()\n\n for (const docId of b.keys()) {\n const existing = a.get(docId)\n if (existing == null) continue\n\n const { score, terms, match } = b.get(docId)!\n assignUniqueTerms(existing.terms, terms)\n combined.set(docId, {\n score: existing.score + score,\n terms: existing.terms,\n match: Object.assign(existing.match, match)\n })\n }\n\n return combined\n },\n [AND_NOT]: (a: RawResult, b: RawResult) => {\n for (const docId of b.keys()) a.delete(docId)\n return a\n }\n}\n\n/**\n * Parameters of the BM25+ scoring algorithm. Customizing these is almost never\n * necessary, and finetuning them requires an understanding of the BM25 scoring\n * model.\n *\n * Some information about BM25 (and BM25+) can be found at these links:\n *\n * - https://en.wikipedia.org/wiki/Okapi_BM25\n * - https://opensourceconnections.com/blog/2015/10/16/bm25-the-next-generation-of-lucene-relevation/\n */\nexport type BM25Params = {\n /** Term frequency saturation point.\n *\n * Recommended values are between `1.2` and `2`. Higher values increase the\n * difference in score between documents with higher and lower term\n * frequencies. Setting this to `0` or a negative value is invalid. Defaults\n * to `1.2`\n */\n k: number,\n\n /**\n * Length normalization impact.\n *\n * Recommended values are around `0.75`. Higher values increase the weight\n * that field length has on scoring. Setting this to `0` (not recommended)\n * means that the field length has no effect on scoring. Negative values are\n * invalid. Defaults to `0.7`.\n */\n b: number,\n\n /**\n * BM25+ frequency normalization lower bound (usually called δ).\n *\n * Recommended values are between `0.5` and `1`. Increasing this parameter\n * increases the minimum relevance of one occurrence of a search term\n * regardless of its (possibly very long) field length. Negative values are\n * invalid. Defaults to `0.5`.\n */\n d: number\n}\n\nconst defaultBM25params: BM25Params = { k: 1.2, b: 0.7, d: 0.5 }\n\nconst calcBM25Score = (\n termFreq: number,\n matchingCount: number,\n totalCount: number,\n fieldLength: number,\n avgFieldLength: number,\n bm25params: BM25Params\n): number => {\n const { k, b, d } = bm25params\n const invDocFreq = Math.log(1 + (totalCount - matchingCount + 0.5) / (matchingCount + 0.5))\n return invDocFreq * (d + termFreq * (k + 1) / (termFreq + k * (1 - b + b * fieldLength / avgFieldLength)))\n}\n\nconst termToQuerySpec = (options: SearchOptions) => (term: string, i: number, terms: string[]): QuerySpec => {\n const fuzzy = (typeof options.fuzzy === 'function')\n ? options.fuzzy(term, i, terms)\n : (options.fuzzy || false)\n const prefix = (typeof options.prefix === 'function')\n ? options.prefix(term, i, terms)\n : (options.prefix === true)\n const termBoost = (typeof options.boostTerm === 'function')\n ? options.boostTerm(term, i, terms)\n : 1\n return { term, fuzzy, prefix, termBoost }\n}\n\nconst defaultOptions = {\n idField: 'id',\n extractField: (document: any, fieldName: string) => document[fieldName],\n stringifyField: (fieldValue: any, fieldName: string) => fieldValue.toString(),\n tokenize: (text: string) => text.split(SPACE_OR_PUNCTUATION),\n processTerm: (term: string) => term.toLowerCase(),\n fields: undefined,\n searchOptions: undefined,\n storeFields: [],\n logger: (level: LogLevel, message: string): void => {\n if (typeof console?.[level] === 'function') console[level](message)\n },\n autoVacuum: true\n}\n\nconst defaultSearchOptions = {\n combineWith: OR,\n prefix: false,\n fuzzy: false,\n maxFuzzy: 6,\n boost: {},\n weights: { fuzzy: 0.45, prefix: 0.375 },\n bm25: defaultBM25params\n}\n\nconst defaultAutoSuggestOptions = {\n combineWith: AND,\n prefix: (term: string, i: number, terms: string[]): boolean =>\n i === terms.length - 1\n}\n\nconst defaultVacuumOptions = { batchSize: 1000, batchWait: 10 }\nconst defaultVacuumConditions = { minDirtFactor: 0.1, minDirtCount: 20 }\n\nconst defaultAutoVacuumOptions = { ...defaultVacuumOptions, ...defaultVacuumConditions }\n\nconst assignUniqueTerm = (target: string[], term: string): void => {\n // Avoid adding duplicate terms.\n if (!target.includes(term)) target.push(term)\n}\n\nconst assignUniqueTerms = (target: string[], source: readonly string[]): void => {\n for (const term of source) {\n // Avoid adding duplicate terms.\n if (!target.includes(term)) target.push(term)\n }\n}\n\ntype Scored = { score: number }\nconst byScore = ({ score: a }: Scored, { score: b }: Scored) => b - a\n\nconst createMap = () => new Map()\n\ninterface SerializedIndexEntry {\n [key: string]: number\n}\n\nconst objectToNumericMap = <T>(object: { [key: string]: T }): Map<number, T> => {\n const map = new Map()\n\n for (const key of Object.keys(object)) {\n map.set(parseInt(key, 10), object[key])\n }\n\n return map\n}\n\nconst objectToNumericMapAsync = async <T>(object: { [key: string]: T }): Promise<Map<number, T>> => {\n const map = new Map()\n\n let count = 0\n for (const key of Object.keys(object)) {\n map.set(parseInt(key, 10), object[key])\n if (++count % 1000 === 0) {\n await wait(0)\n }\n }\n\n return map\n}\n\nconst wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))\n\n// This regular expression matches any Unicode space, newline, or punctuation\n// character\nconst SPACE_OR_PUNCTUATION = /[\\n\\r\\p{Z}\\p{P}]+/u\n","/**\n * Lexical entry (ADR 01019) — text query → ranked seed nodes.\n *\n * Loads the `search.json` artifact (produced by `manni graph export search`)\n * and scores it with MiniSearch. The artifact carries body text, which the graph\n * deliberately does not (ADR 01008), so a query can match what a document *says*\n * and not merely what it is titled.\n *\n * MiniSearch is this runtime's one production dependency; the bundle-purity gate\n * allow-lists exactly it. Two guards keep ranking a dockg contract rather than a\n * library's: ties are broken by IRI here (MiniSearch does not define tie order),\n * and the on-disk artifact format is ours, so upgrading MiniSearch can never\n * change a committed artifact.\n *\n * Platform-neutral: no `node:` imports.\n */\nimport MiniSearch from \"minisearch\";\nimport type { SearchEntry, SearchIndexDoc } from \"../core/search-index.js\";\nimport { byCodeUnit } from \"../core/sort.js\";\nimport type { EntryCandidate } from \"./trace.js\";\n\nexport interface LexicalSearchOptions {\n /** Maximum candidates to return. Default 10. */\n limit?: number;\n}\n\nexport interface LexicalIndex {\n /** Ranked candidates, best first, ties broken by IRI. */\n search(query: string, options?: LexicalSearchOptions): EntryCandidate[];\n /** Indexed entry count. */\n size(): number;\n /** The entry behind an IRI, for callers that want its title/type. */\n entry(iri: string): SearchEntry | undefined;\n}\n\n/**\n * Build a lexical index from the search artifact — a JSON string or the parsed\n * document.\n */\nexport function createLexicalIndex(\n input: string | SearchIndexDoc,\n): LexicalIndex {\n const doc = (\n typeof input === \"string\" ? (JSON.parse(input) as SearchIndexDoc) : input\n ) as SearchIndexDoc | null;\n // Shape-check rather than trust: handed something that is valid JSON but not\n // a search artifact, MiniSearch's `addAll` throws \"documents is not\n // iterable\" from inside the library. An empty index is the honest answer.\n const entries = Array.isArray(doc?.entries) ? doc.entries : [];\n\n const mini = new MiniSearch<SearchEntry>({\n fields: [\"title\", \"labels\", \"description\", \"text\"],\n storeFields: [\"id\"],\n idField: \"id\",\n // Titles and labels are the strongest signal that a node *is* the subject;\n // body text is evidence it merely mentions it.\n searchOptions: {\n boost: { title: 3, labels: 2, description: 1.5 },\n prefix: true,\n fuzzy: 0.2,\n },\n });\n mini.addAll(entries);\n\n const byIri = new Map(entries.map((e) => [e.id, e]));\n\n return {\n size: () => entries.length,\n entry: (iri) => byIri.get(iri),\n search(query, options = {}) {\n const trimmed = query.trim();\n if (trimmed === \"\") return [];\n const hits = mini.search(trimmed);\n // MiniSearch does not define an order for equal scores; sort explicitly so\n // the same query against the same artifact always ranks identically.\n hits.sort((a, b) =>\n a.score === b.score\n ? byCodeUnit(String(a.id), String(b.id))\n : b.score - a.score,\n );\n return hits\n .slice(0, options.limit ?? 10)\n .map((h) => ({ iri: String(h.id), score: h.score, via: \"lexical\" }));\n },\n };\n}\n","/**\n * The vector sidecar (ADR 01020) — `graph/vectors.<lang>.bin`, embeddings for the\n * same text that language's lexical index covers (ADR 01038).\n *\n * Layout, fixed. The magic is four ASCII bytes in file order; every number\n * after it is little-endian:\n *\n * ```\n * 0 magic \"MGRV\" 4 bytes\n * 4 format version (u32) 4 bytes\n * 8 header length (u32) 4 bytes\n * 12 header JSON (UTF-8) headerLength bytes\n * . float32 payload count * dims * 4 bytes\n * ```\n *\n * The header names the model, dtype, dimensions, the node IRIs in payload order\n * (sorted), and a digest of the `search.json` the vectors were built from — so\n * the runtime can refuse to rank against vectors from a different model or a\n * stale corpus rather than returning quietly wrong results.\n *\n * Vectors are **L2-normalized at build time and stored as float32**. Normalizing\n * makes cosine collapse to a dot product at query time; float32 rather than int8\n * because int8 retains only ~91% of retrieval quality at 384 dimensions — see\n * ADR 01020, where that correction is recorded.\n *\n * No `node:` imports: the encoder runs in the CLI, the decoder in the browser.\n */\nimport { byCodeUnit } from \"./sort.js\";\n\n/**\n * \"MGRV\", manni graph vectors, as the bytes a hex dump shows first. It read\n * \"DKGV\" while the tool was dockg and \"MKGV\" while it was manni kg. Nothing was\n * published under either name, so no sidecar in the wild carries the old bytes.\n * Raw bytes rather than a little-endian u32: a u32 lands on disk reversed.\n */\nconst MAGIC = new Uint8Array([0x4d, 0x47, 0x52, 0x56]);\n// 2 since ADR 01038: the header names the language its vectors cover, so a\n// consumer cannot pair a sidecar with the wrong locale's index. A version-1\n// file is refused by `decodeVectorIndex` rather than read as if it had one.\nconst FORMAT_VERSION = 2;\nconst HEADER_OFFSET = 12;\n\nexport interface VectorIndexHeader {\n /** Embedding model id, e.g. an HF repo path. */\n model: string;\n /** Model-weight quantization the vectors were produced under. */\n dtype: string;\n /** Vector dimensions. Never assumed — always read from here. */\n dims: number;\n /** Number of vectors; equals `ids.length`. */\n count: number;\n /** Node IRIs, sorted, in payload order. */\n ids: string[];\n /** Digest of the `search.<lang>.json` these were built from (staleness detection). */\n source: string;\n /**\n * BCP-47 tag of the index these cover, or `und` (ADR 01038). Recorded so a\n * host that fetched the wrong pair is refused rather than ranked against a\n * model that never saw the language.\n */\n language: string;\n}\n\nexport interface VectorIndexDoc {\n header: VectorIndexHeader;\n /** `count * dims` floats, L2-normalized, row-major in `ids` order. */\n vectors: Float32Array;\n}\n\n/** Thrown for malformed input so callers can map it to an exit code / refusal. */\nexport class VectorIndexError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"VectorIndexError\";\n }\n}\n\n/**\n * L2-normalize a vector in place and return it. A zero vector is left alone —\n * dividing by its norm would produce NaNs that silently poison every later dot\n * product.\n */\nexport function normalize(vector: Float32Array): Float32Array {\n let sum = 0;\n // Iterating rather than indexing: every element is an element, which is what\n // the assertions here used to say.\n for (const value of vector) sum += value * value;\n if (sum === 0) return vector;\n const inv = 1 / Math.sqrt(sum);\n // `set(map(…))` scales every element in place with the same per-element\n // float32 rounding the indexed loop had, and without an index to assert.\n vector.set(vector.map((value) => value * inv));\n return vector;\n}\n\n/**\n * Encode entries into the sidecar. Entries are sorted by IRI first, so the bytes\n * depend on the set of entries and not on the order they were produced in.\n */\nexport function encodeVectorIndex(\n entries: Array<{ id: string; vector: Float32Array }>,\n meta: { model: string; dtype: string; source: string; language: string },\n): Uint8Array {\n const sorted = [...entries].sort((a, b) => byCodeUnit(a.id, b.id));\n const dims = sorted[0]?.vector.length ?? 0;\n for (const entry of sorted) {\n if (entry.vector.length !== dims) {\n throw new VectorIndexError(\n `Inconsistent vector dimensions: ${entry.id} has ${entry.vector.length}, expected ${dims}.`,\n );\n }\n }\n\n const header: VectorIndexHeader = {\n model: meta.model,\n dtype: meta.dtype,\n dims,\n count: sorted.length,\n ids: sorted.map((e) => e.id),\n source: meta.source,\n language: meta.language,\n };\n const headerBytes = new TextEncoder().encode(JSON.stringify(header));\n\n const payloadBytes = sorted.length * dims * 4;\n const out = new Uint8Array(HEADER_OFFSET + headerBytes.length + payloadBytes);\n const view = new DataView(out.buffer);\n out.set(MAGIC, 0);\n view.setUint32(4, FORMAT_VERSION, true);\n view.setUint32(8, headerBytes.length, true);\n out.set(headerBytes, HEADER_OFFSET);\n\n let offset = HEADER_OFFSET + headerBytes.length;\n for (const entry of sorted) {\n // Normalize a copy: the caller's array is not ours to mutate.\n const vector = normalize(Float32Array.from(entry.vector));\n // Exactly `dims` elements: the loop above rejected any entry of another\n // length, so iterating the vector is the same walk without the index.\n for (const value of vector) {\n view.setFloat32(offset, value, true);\n offset += 4;\n }\n }\n return out;\n}\n\n/** Decode a sidecar, rejecting anything malformed rather than mis-reading it. */\nexport function decodeVectorIndex(bytes: Uint8Array): VectorIndexDoc {\n if (bytes.length < HEADER_OFFSET) {\n throw new VectorIndexError(\"Not a manni graph vector index: file is too short.\");\n }\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n if (!MAGIC.every((byte, i) => bytes[i] === byte)) {\n throw new VectorIndexError(\n \"Not a manni graph vector index: bad magic — is this the right file?\",\n );\n }\n const version = view.getUint32(4, true);\n if (version !== FORMAT_VERSION) {\n throw new VectorIndexError(\n `Unsupported vector index version ${version} (this build reads ${FORMAT_VERSION}) — re-run \\`manni graph embed\\`.`,\n );\n }\n\n const headerLength = view.getUint32(8, true);\n if (HEADER_OFFSET + headerLength > bytes.length) {\n throw new VectorIndexError(\"Vector index is truncated: header overruns.\");\n }\n\n let header: VectorIndexHeader;\n try {\n header = JSON.parse(\n new TextDecoder().decode(\n bytes.subarray(HEADER_OFFSET, HEADER_OFFSET + headerLength),\n ),\n ) as VectorIndexHeader;\n } catch {\n throw new VectorIndexError(\"Vector index header is not valid JSON.\");\n }\n if (\n !Array.isArray(header.ids) ||\n typeof header.dims !== \"number\" ||\n header.ids.length !== header.count\n ) {\n throw new VectorIndexError(\"Vector index header is malformed.\");\n }\n\n const start = HEADER_OFFSET + headerLength;\n const expected = header.count * header.dims * 4;\n if (bytes.length - start !== expected) {\n throw new VectorIndexError(\n `Vector index is truncated: expected ${expected} payload bytes, found ${bytes.length - start}.`,\n );\n }\n\n // Copy rather than aliasing: `bytes` may be a view into a larger buffer whose\n // byteOffset is not 4-aligned, which Float32Array construction rejects.\n const vectors = new Float32Array(header.count * header.dims);\n for (let i = 0; i < vectors.length; i++) {\n vectors[i] = view.getFloat32(start + i * 4, true);\n }\n return { header, vectors };\n}\n","/**\n * Vector search (ADR 01020) — semantic entry, and a standalone capability.\n *\n * `search()` is usable on its own: give it a query vector and it ranks nodes by\n * meaning, with no lexical index and no graph involved. `findEntry` composes it\n * with the lexical leg, but does not own it.\n *\n * Hand-written rather than taken from a library, on evidence: the dedicated\n * browser vector libraries are 3 years stale, no maintained micro-package does\n * cosine top-k over typed arrays (the popular one throws on `Float32Array`), and\n * the engines that do exist run this same brute-force loop internally. See ADR\n * 01020 for the full survey.\n *\n * Vectors are L2-normalized at build time, so cosine similarity **is** the dot\n * product — no norms, no division, at query time. The loop is indexed rather\n * than `.reduce()`, which measures ~13× slower on typed arrays.\n *\n * Platform-neutral: no `node:` imports, no dependencies.\n */\nimport { byCodeUnit } from \"../core/sort.js\";\nimport {\n decodeVectorIndex,\n normalize,\n type VectorIndexHeader,\n} from \"../core/vector-index.js\";\nimport type { EntryCandidate } from \"./trace.js\";\n\nexport interface VectorSearchOptions {\n /** Maximum candidates to return. Default 10. */\n limit?: number;\n /**\n * Drop candidates scoring below this. Default 0 — every model has its own\n * useful range, so dockg does not impose a threshold the user did not choose.\n */\n minScore?: number;\n}\n\n/** Why a vector index cannot be used with the embedder or corpus at hand. */\nexport interface VectorMismatch {\n reason: \"model\" | \"dtype\" | \"dims\" | \"stale-source\";\n detail: string;\n}\n\n/**\n * Thrown when a query would be ranked against vectors it cannot be compared to.\n *\n * A distinct type so hosts can catch exactly this — and so it cannot be mistaken\n * for \"no results\". Ranking on regardless is the silent-wrong-answer failure\n * ADR 01020 exists to prevent, so this is loud by design.\n */\nexport class VectorMismatchError extends Error {\n readonly reason: VectorMismatch[\"reason\"];\n constructor(mismatch: VectorMismatch) {\n super(mismatch.detail);\n this.name = \"VectorMismatchError\";\n this.reason = mismatch.reason;\n }\n}\n\n/**\n * The digest `manni graph embed` records as a sidecar's `source`, computed the same\n * way in a browser — SHA-256 over the **raw bytes of `search.json` exactly as\n * fetched**, hex, prefixed `sha256:`.\n *\n * Exists so a host can pass `source` to `findEntry` and get the staleness half\n * of the refusal (ADR 01020) without reconstructing the recipe. Re-serializing\n * the parsed JSON would change the bytes and so the digest — pass the response\n * text, not `JSON.stringify(doc)`.\n *\n * Uses Web Crypto, which is platform-neutral: browsers and Node 18+ both have\n * it on `globalThis`.\n */\nexport async function searchIndexDigest(raw: string): Promise<string> {\n // `lib.dom` and @types/node both declare `globalThis.crypto.subtle` as\n // always present. A page served over plain HTTP gets `crypto` without\n // `subtle`, which is the case this throw exists for: the declaration is the\n // optimistic one, and reading through `Partial` is how the guard gets to say\n // so instead of reading as a test that cannot fail.\n const webCrypto = globalThis.crypto as\n | Partial<typeof globalThis.crypto>\n | undefined;\n const subtle = webCrypto?.subtle;\n if (!subtle) {\n throw new Error(\n \"searchIndexDigest needs Web Crypto (globalThis.crypto.subtle), which is unavailable here — a page served over plain HTTP does not get it.\",\n );\n }\n const digest = await subtle.digest(\"SHA-256\", new TextEncoder().encode(raw));\n const hex = [...new Uint8Array(digest)]\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n return `sha256:${hex}`;\n}\n\nexport interface VectorIndex {\n /**\n * Rank nodes against a query vector. The vector is normalized here, so\n * callers need not — an unnormalized query would otherwise scale every score.\n */\n search(query: Float32Array, options?: VectorSearchOptions): EntryCandidate[];\n /**\n * Check this index against the embedder and corpus in play. Returns the\n * mismatch, or undefined when they agree. Ranking against vectors from a\n * different model compares outputs of two different functions (ADR 01020), so\n * callers should refuse rather than proceed.\n */\n check(expected: {\n model?: string;\n dtype?: string;\n dims?: number;\n source?: string;\n }): VectorMismatch | undefined;\n readonly model: string;\n /**\n * Weight quantization the corpus vectors were produced under. The query side\n * must embed at the *same* dtype — q8 and fp32 weights are different\n * functions, so mixing them compares incomparable vectors (ADR 01020).\n */\n readonly dtype: string;\n readonly dims: number;\n readonly source: string;\n size(): number;\n /** The IRI at a payload row, for callers walking the index directly. */\n idAt(row: number): string | undefined;\n}\n\n/** Build a vector index from encoded sidecar bytes. */\nexport function createVectorIndex(bytes: Uint8Array): VectorIndex {\n const { header, vectors } = decodeVectorIndex(bytes);\n const { dims, ids } = header;\n\n return {\n model: header.model,\n dtype: header.dtype,\n dims,\n source: header.source,\n size: () => ids.length,\n idAt: (row) => ids[row],\n\n check(expected) {\n if (expected.model !== undefined && expected.model !== header.model) {\n return {\n reason: \"model\",\n detail: `Vector index was built with ${header.model}, but the embedder is ${expected.model}. Re-run \\`manni graph embed\\`.`,\n };\n }\n if (expected.dtype !== undefined && expected.dtype !== header.dtype) {\n return {\n reason: \"dtype\",\n detail: `Vector index was built at dtype ${header.dtype}, but the embedder is at ${expected.dtype} — different weights are a different function. Re-run \\`manni graph embed\\`.`,\n };\n }\n if (expected.dims !== undefined && expected.dims !== dims) {\n return {\n reason: \"dims\",\n detail: `Vector index has ${dims} dimensions, but the embedder produces ${expected.dims}.`,\n };\n }\n if (expected.source !== undefined && expected.source !== header.source) {\n return {\n reason: \"stale-source\",\n detail:\n \"Vector index was built from a different search index — the corpus changed. Re-run `manni graph embed`.\",\n };\n }\n return undefined;\n },\n\n search(query, options = {}) {\n if (dims === 0 || ids.length === 0) return [];\n if (query.length !== dims) {\n // A silent zero-fill or truncate here would return confident nonsense.\n // Typed like every other mismatch so a caller (and the CLI's exit-code\n // mapping) handles it the same way rather than seeing a raw stack.\n throw new VectorMismatchError({\n reason: \"dims\",\n detail: `Query vector has ${query.length} dimensions, but the index has ${dims}.`,\n });\n }\n const limit = normalizeLimit(options.limit);\n if (limit === 0) return [];\n const minScore = options.minScore ?? 0;\n\n // Copy before normalizing: the caller's vector is not ours to mutate.\n const q = normalize(Float32Array.from(query));\n\n const scored: EntryCandidate[] = [];\n // `entries()` pairs each row with its IRI, so the id is proven present\n // by the iteration rather than asserted after an index.\n for (const [row, iri] of ids.entries()) {\n // The payload is `count × dims` floats, so this row is exactly these\n // `dims` of them — and `q` was checked to be `dims` long above. Both\n // walks are therefore in range; `?? 0` spells that a term outside the\n // row contributes nothing, which is what out of range means for a dot\n // product.\n const stored = vectors.subarray(row * dims, (row + 1) * dims);\n let score = 0;\n for (const [i, value] of q.entries()) score += value * (stored[i] ?? 0);\n if (score >= minScore) {\n scored.push({ iri, score, via: \"vector\" });\n }\n }\n\n scored.sort((a, b) =>\n a.score === b.score ? byCodeUnit(a.iri, b.iri) : b.score - a.score,\n );\n return scored.slice(0, limit);\n },\n };\n}\n\n/**\n * A limit that is not a non-negative integer falls back to the documented\n * default — `slice(0, NaN)` is empty, which would report a confident \"no\n * results\" for a query that does match.\n */\nfunction normalizeLimit(limit: number | undefined): number {\n return typeof limit === \"number\" && Number.isInteger(limit) && limit >= 0\n ? limit\n : 10;\n}\n\nexport type { VectorIndexHeader };\n","/**\n * Entry-point finding (ADR 01019, extended by ADR 01020) — the stage that turns\n * a question into seed nodes for the walker.\n *\n * Two rankings now: lexical (BM25 over the search artifact) and, when the host\n * supplies an embedder, vector (cosine over the sidecar). `rrfMerge` fuses them.\n *\n * **Each leg is returned separately as well as fused.** A caller rendering a\n * search UI wants to show \"text matches\" and \"semantic matches\" as distinct\n * things, and either leg is usable on its own — `lexical.search` and\n * `vectors.search` are public and independent of this function.\n *\n * Every candidate is appended to the trace, so \"why did retrieval start here?\"\n * is answerable alongside \"why did it walk there?\" (ADR 01018 invariant 2).\n *\n * Platform-neutral: no `node:` imports.\n */\nimport { byCodeUnit } from \"../core/sort.js\";\nimport type { LexicalIndex } from \"./lexical.js\";\nimport { VectorMismatchError, type VectorIndex } from \"./vector.js\";\nimport {\n createTrace,\n type EntryCandidate,\n type EntryVia,\n type QueryTrace,\n} from \"./trace.js\";\n\n/**\n * Enough of an embedder to verify it against a vector index. Structural rather\n * than the `Embedder` interface itself, so the runtime stays independent of\n * `@hawkeyexl/manni/graph/embed` — any object with these three fields works.\n */\nexport interface QueryEmbedder {\n readonly model: string;\n readonly dtype: string;\n embed(text: string): Promise<Float32Array> | Float32Array;\n}\n\nexport interface FindEntryOptions {\n /** The lexical index to query. */\n lexical: LexicalIndex;\n /** The vector index. Without it (and an embedder), entry is lexical-only. */\n vectors?: VectorIndex;\n /**\n * The embedder for the query side. **Prefer this over `embedQuery`**: it\n * carries the model and dtype, so `findEntry` can verify they match the\n * vector index and refuse rather than rank against incomparable vectors.\n */\n embedder?: QueryEmbedder;\n /**\n * Embed the query with a bare function. An escape hatch for hosts wiring\n * their own model — but it carries no identity, so **the model/dtype match\n * cannot be verified**; only the dimension check inside `search` applies.\n * Prefer `embedder`.\n */\n embedQuery?: (query: string) => Promise<Float32Array> | Float32Array;\n /**\n * Digest of the `search.json` this caller loaded, from `searchIndexDigest`.\n * Supplied, a sidecar built from a *different* corpus is refused rather than\n * ranked — its IRIs may no longer exist, and it misses everything added\n * since. Omitted, that half of the check simply does not run: the runtime\n * cannot derive the digest, since it never sees the raw bytes.\n */\n source?: string;\n /** Maximum seeds to return. Default 10. */\n limit?: number;\n /** Append candidates here instead of starting a new trace. */\n trace?: QueryTrace;\n}\n\nexport interface EntryResult {\n /** The fused ranking — what seeds traversal. */\n candidates: EntryCandidate[];\n /** The lexical leg's own ranking. */\n lexical: EntryCandidate[];\n /** The vector leg's own ranking; empty when no embedder was supplied. */\n vector: EntryCandidate[];\n trace: QueryTrace;\n}\n\n/**\n * Reciprocal rank fusion over N ranked lists: score = Σ 1/(k + rank).\n *\n * Rank-based rather than score-based on purpose — lexical BM25 scores and\n * cosine similarities are not on a comparable scale, so fusing raw scores would\n * let whichever leg happens to produce bigger numbers dominate. `k = 60` is the\n * standard damping constant.\n *\n * Deterministic: input list order does not affect the result, and ties break by\n * IRI.\n */\nexport function rrfMerge(\n rankings: EntryCandidate[][],\n k = 60,\n): EntryCandidate[] {\n const fused = new Map<string, { score: number; vias: Set<EntryVia> }>();\n for (const ranking of rankings) {\n ranking.forEach((candidate, i) => {\n const current = fused.get(candidate.iri) ?? {\n score: 0,\n vias: new Set<EntryVia>(),\n };\n current.score += 1 / (k + i + 1);\n current.vias.add(candidate.via);\n fused.set(candidate.iri, current);\n });\n }\n\n return [...fused.entries()]\n .map(([iri, { score, vias }]) => {\n // One leg keeps its own provenance; several means the seed was fused.\n // Destructuring rather than `[...vias][0]!` so the single-leg case needs\n // no non-null assertion — an empty set simply falls through to \"hybrid\",\n // which is unreachable anyway (a set only exists once a leg added to it).\n const [only] = vias;\n return {\n iri,\n score,\n via: vias.size === 1 && only !== undefined ? only : \"hybrid\",\n };\n })\n .sort((a, b) =>\n a.score === b.score ? byCodeUnit(a.iri, b.iri) : b.score - a.score,\n );\n}\n\n/**\n * Find seed nodes for a question, returning each ranking leg and their fusion.\n *\n * Async because embedding a query is: local models are a WASM forward pass.\n * Uniformly async rather than sync-when-lexical-only, so callers have one\n * contract to hold rather than a return type that changes with the options.\n *\n * The vector leg runs only when both a `vectors` index and an `embedQuery` are\n * supplied. Absent either, this is lexical entry exactly as Phase 8 shipped it —\n * additive, never a new failure mode (ADR 01009's degrade-don't-fail rule).\n */\nexport async function findEntry(\n query: string,\n options: FindEntryOptions,\n): Promise<EntryResult> {\n const trace = options.trace ?? createTrace();\n // `--limit abc` parses to NaN, and `slice(0, NaN)` is empty — a typo'd flag\n // would report a confident \"0 results\" for a query that does match. Anything\n // that is not a non-negative integer falls back to the documented default.\n const limit =\n typeof options.limit === \"number\" &&\n Number.isInteger(options.limit) &&\n options.limit >= 0\n ? options.limit\n : 10;\n\n const lexical = options.lexical.search(query, { limit });\n\n // Bound first: the closure then captures the embedder the test found, rather\n // than re-reading a property the type cannot know is still the same one.\n const embedder = options.embedder;\n const embed = embedder ? (q: string) => embedder.embed(q) : options.embedQuery;\n\n let vector: EntryCandidate[] = [];\n if (options.vectors && embed && query.trim() !== \"\") {\n // Verify *before* embedding. The refusal is enforced here, not only in the\n // CLI, because this is the browser-facing surface — and the whole reason\n // ADR 01020 exists is that the browser must embed with a function that\n // agrees with the one that embedded the corpus. Ranking a stale or\n // wrong-model index would be the silent wrong answer this design prevents.\n const mismatch = options.vectors.check({\n ...(options.embedder\n ? { model: options.embedder.model, dtype: options.embedder.dtype }\n : {}),\n // Staleness is checked whichever way the query is embedded — it is a\n // property of the corpus, not of the embedder, so even the unverified\n // `embedQuery` path gets it when the caller supplies a digest.\n ...(options.source === undefined ? {} : { source: options.source }),\n });\n if (mismatch) throw new VectorMismatchError(mismatch);\n const queryVector = await embed(query);\n vector = options.vectors.search(queryVector, { limit });\n }\n\n const rankings = vector.length > 0 ? [lexical, vector] : [lexical];\n const candidates = rrfMerge(rankings).slice(0, limit);\n\n for (const candidate of candidates) trace.entry.push(candidate);\n return { candidates, lexical, vector, trace };\n}\n"],"mappings":";AASO,SAAS,WAAW,GAAW,GAAmB;AACvD,SAAO,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI;AAClC;;;ACWO,IAAM,KAAK;AAAA,EAChB,SAAS;AAAA,EACT,MAAM;AAAA,EACN,OAAO;AAAA,EACP,OAAO;AAAA,EACP,UAAU;AAAA,EACV,MAAM;AAAA,EACN,KAAK;AAAA,EACL,QAAQ;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