@quaesitor-textus/mongo 0.2.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.
Files changed (51) hide show
  1. package/LICENSE +180 -0
  2. package/README.md +417 -0
  3. package/dist/adapters/express.cjs +110 -0
  4. package/dist/adapters/express.d.cts +20 -0
  5. package/dist/adapters/express.d.ts +20 -0
  6. package/dist/adapters/express.js +7 -0
  7. package/dist/adapters/fastify.cjs +113 -0
  8. package/dist/adapters/fastify.d.cts +10 -0
  9. package/dist/adapters/fastify.d.ts +10 -0
  10. package/dist/adapters/fastify.js +16 -0
  11. package/dist/adapters/next-app.cjs +120 -0
  12. package/dist/adapters/next-app.d.cts +9 -0
  13. package/dist/adapters/next-app.d.ts +9 -0
  14. package/dist/adapters/next-app.js +23 -0
  15. package/dist/adapters/next-pages.cjs +110 -0
  16. package/dist/adapters/next-pages.d.cts +5 -0
  17. package/dist/adapters/next-pages.d.ts +5 -0
  18. package/dist/adapters/next-pages.js +7 -0
  19. package/dist/chunk-AUIK33V2.js +55 -0
  20. package/dist/chunk-RXTFVXXU.js +42 -0
  21. package/dist/index.cjs +288 -0
  22. package/dist/index.d.cts +51 -0
  23. package/dist/index.d.ts +51 -0
  24. package/dist/index.js +203 -0
  25. package/dist/startSearchSync-Bk7Na8Do.d.cts +39 -0
  26. package/dist/startSearchSync-Bk7Na8Do.d.ts +39 -0
  27. package/package.json +88 -0
  28. package/src/adapters/express.ts +8 -0
  29. package/src/adapters/fastify.ts +19 -0
  30. package/src/adapters/next-app.ts +27 -0
  31. package/src/adapters/next-pages.ts +11 -0
  32. package/src/adapters/shared.ts +61 -0
  33. package/src/buildTextSearchFilter.test.ts +30 -0
  34. package/src/buildTextSearchFilter.ts +34 -0
  35. package/src/computeSearchFields.test.ts +23 -0
  36. package/src/computeSearchFields.ts +31 -0
  37. package/src/config.ts +14 -0
  38. package/src/createLiveSearch.test.ts +48 -0
  39. package/src/createLiveSearch.ts +57 -0
  40. package/src/index.ts +12 -0
  41. package/src/modes.test.ts +20 -0
  42. package/src/modes.ts +24 -0
  43. package/src/parity.test.ts +60 -0
  44. package/src/searchIndexes.test.ts +12 -0
  45. package/src/searchIndexes.ts +22 -0
  46. package/src/sse.test.ts +11 -0
  47. package/src/sse.ts +7 -0
  48. package/src/startSearchSync.test.ts +42 -0
  49. package/src/startSearchSync.ts +91 -0
  50. package/src/version.test.ts +40 -0
  51. package/src/version.ts +41 -0
package/LICENSE ADDED
@@ -0,0 +1,180 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship made available under
36
+ the License, as indicated by a copyright notice that is included in
37
+ or attached to the work (an example is provided in the Appendix below).
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other transformations
42
+ represent, as a whole, an original work of authorship. For the purposes
43
+ of this License, Derivative Works shall not include works that remain
44
+ separable from, or merely link (or bind by name) to the interfaces of,
45
+ the Work and Derivative Works thereof.
46
+
47
+ "Contribution" shall mean, as submitted to the Licensor for inclusion
48
+ in the Work by the copyright owner or by an individual or Legal Entity
49
+ authorized to submit on behalf of the copyright owner. For the purposes
50
+ of this definition, "submitted" means any form of electronic, verbal,
51
+ or written communication sent to the Licensor or its representatives,
52
+ including but not limited to communication on electronic mailing lists,
53
+ source code control systems, and issue tracking systems that are managed
54
+ by, or on behalf of, the Licensor for the purpose of discussing and
55
+ improving the Work, but excluding communication that is conspicuously
56
+ marked or otherwise designated in writing by the copyright owner as
57
+ "Not a Contribution."
58
+
59
+ "Contributor" shall mean Licensor and any Legal Entity on behalf of
60
+ whom a Contribution has been received by the Licensor and included
61
+ within the Work.
62
+
63
+ 2. Grant of Copyright License. Subject to the terms and conditions of
64
+ this License, each Contributor hereby grants to You a perpetual,
65
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
66
+ copyright license to reproduce, prepare Derivative Works of,
67
+ publicly display, publicly perform, sublicense, and distribute the
68
+ Work and such Derivative Works in Source or Object form.
69
+
70
+ 3. Grant of Patent License. Subject to the terms and conditions of
71
+ this License, each Contributor hereby grants to You a perpetual,
72
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
73
+ (except as stated in this section) patent license to make, have made,
74
+ use, offer to sell, sell, import, and otherwise transfer the Work,
75
+ where such license applies only to those patent claims licensable
76
+ by such Contributor that are necessarily infringed by their
77
+ Contribution(s) alone or by the combination of their Contribution(s)
78
+ with the Work to which such Contribution(s) was submitted. If You
79
+ institute patent litigation against any entity (including a cross-claim
80
+ or counterclaim in a lawsuit) alleging that the Work or any
81
+ Contribution embodied within the Work constitutes direct or contributory
82
+ patent infringement, then any patent licenses granted to You under
83
+ this License for that Work shall terminate as of the date such
84
+ litigation is filed.
85
+
86
+ 4. Redistribution. You may reproduce and distribute copies of the
87
+ Work or Derivative Works thereof in any medium, with or without
88
+ modifications, and in Source or Object form, provided that You
89
+ meet the following conditions:
90
+
91
+ (a) You must give any other recipients of the Work or Derivative
92
+ Works a copy of this License; and
93
+
94
+ (b) You must cause any modified files to carry prominent notices
95
+ stating that You changed the files; and
96
+
97
+ (c) You must retain, in the Source form of any Derivative Works
98
+ that You distribute, all copyright, patent, trademark, and
99
+ attribution notices from the Source form of the Work,
100
+ excluding those notices that do not pertain to any part of
101
+ the Derivative Works; and
102
+
103
+ (d) If the Work includes a "NOTICE" text file as part of its
104
+ distribution, You must include a readable copy of the
105
+ attribution notices contained within such NOTICE file, in
106
+ at least one of the following places: within a NOTICE text
107
+ file distributed as part of the Derivative Works; within
108
+ the Source form or documentation, if provided along with the
109
+ Derivative Works; or, within a display generated by the
110
+ Derivative Works, if and wherever such third-party notices
111
+ normally appear. The contents of the NOTICE file are for
112
+ informational purposes only and do not modify the License.
113
+ You may add Your own attribution notices within Derivative
114
+ Works that You distribute, alongside or in addition to the
115
+ NOTICE text from the Work, provided that such additional
116
+ attribution notices cannot be construed as modifying the License.
117
+
118
+ You may add Your own license statement for Your modifications and
119
+ may provide additional grant of rights to use, copy, modify, merge,
120
+ publish, distribute, sublicense, and/or sell copies of the
121
+ Derivative Works, as You see fit.
122
+
123
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
124
+ any Contribution intentionally submitted for inclusion in the Work
125
+ by You to the Licensor shall be under the terms and conditions of
126
+ this License, without any additional terms or conditions.
127
+ Notwithstanding the above, nothing herein shall supersede or modify
128
+ the terms of any separate license agreement you may have executed
129
+ with Licensor regarding such Contributions.
130
+
131
+ 6. Trademarks. This License does not grant permission to use the trade
132
+ names, trademarks, service marks, or product names of the Licensor,
133
+ except as required for reasonable and customary use in describing the
134
+ origin of the Work and reproducing the content of the NOTICE file.
135
+
136
+ 7. Disclaimer of Warranty. Unless required by applicable law or
137
+ agreed to in writing, Licensor provides the Work (and each
138
+ Contributor provides its Contributions) on an "AS IS" BASIS,
139
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
140
+ implied, including, without limitation, any warranties or conditions
141
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
142
+ PARTICULAR PURPOSE. You are solely responsible for determining the
143
+ appropriateness of using or reproducing the Work and assume any
144
+ risks associated with Your exercise of permissions under this License.
145
+
146
+ 8. Limitation of Liability. In no event and under no legal theory,
147
+ whether in tort (including negligence), contract, or otherwise,
148
+ unless required by applicable law (such as deliberate and grossly
149
+ negligent acts) or agreed to in writing, shall any Contributor be
150
+ liable to You for damages, including any direct, indirect, special,
151
+ incidental, or exemplary damages of any character arising as a
152
+ result of this License or out of the use or inability to use the
153
+ Work (even if such Contributor has been advised of the possibility
154
+ of such damages).
155
+
156
+ 9. Accepting Warranty or Additional Liability. While redistributing
157
+ the Work or Derivative Works thereof, You may choose to offer,
158
+ and charge a fee for, acceptance of support, warranty, indemnity,
159
+ or other liability obligations and/or rights consistent with this
160
+ License. However, in accepting such obligations, You may offer such
161
+ obligations only on Your own behalf and on behalf of the sole
162
+ responsibility of those additional obligations, not on behalf of
163
+ any other Contributor. You are solely responsible for fulfilling
164
+ the obligations under such additional warranty or liability terms.
165
+
166
+ END OF TERMS AND CONDITIONS
167
+
168
+ Copyright 2026 Kristof Csillag
169
+
170
+ Licensed under the Apache License, Version 2.0 (the "License");
171
+ you may not use this file except in compliance with the License.
172
+ You may obtain a copy of the License at
173
+
174
+ http://www.apache.org/licenses/LICENSE-2.0
175
+
176
+ Unless required by applicable law or agreed to in writing, software
177
+ distributed under the License is distributed on an "AS IS" BASIS,
178
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
179
+ See the License for the specific language governing permissions and
180
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,417 @@
1
+ # @quaesitor-textus/mongo
2
+
3
+ Server-side MongoDB search that reproduces the exact matching behaviour of
4
+ [`@quaesitor-textus/core`](../core) — diacritic- and case-insensitive substring
5
+ matching — **index-backed** and with **zero server-side JavaScript**.
6
+
7
+ ## What it is / why
8
+
9
+ `@quaesitor-textus/core` does its matching in the browser: it folds text (Unicode
10
+ normalization, diacritic stripping, case folding) and runs substring matches over
11
+ an in-memory corpus. That is perfect for a few hundred items already on the client,
12
+ but it does not scale to a collection that lives in a database.
13
+
14
+ This package is the server-side companion. It moves the same matching semantics
15
+ into MongoDB while keeping two hard constraints:
16
+
17
+ - **Index-backed.** Queries use a multikey index over stored n-grams as a coarse
18
+ superset pre-filter, so Mongo never has to scan the whole collection for a
19
+ substring.
20
+ - **No server-side JavaScript.** MongoDB's query engine (and its `$where` / server
21
+ JS) does **not** implement `String.prototype.normalize`, so it cannot fold
22
+ Unicode the way the client does. Instead, **all normalization happens in Node at
23
+ ingest time**: each document gets derived fields holding fully-folded n-grams and
24
+ one pre-folded "verify" string per query mode. Queries then combine a `$all`
25
+ n-gram filter with a `$regex` substring check against the appropriate verify
26
+ string. The folding never runs inside Mongo — it was already baked into the
27
+ stored fields.
28
+
29
+ The result: a server query built by `buildTextSearchFilter` returns exactly what
30
+ the client's `matchItem` would have matched over the same corpus. (That guarantee
31
+ is exercised by the parity integration test in this package.)
32
+
33
+ ### How the derived fields are shaped
34
+
35
+ For namespace `ns` (default `_qt`) and a configured target `t`, each document gains:
36
+
37
+ ```
38
+ { [ns]: { [t]: { ngrams: string[], norm: string, /* + e.g. */ norm_cs: string } } }
39
+ ```
40
+
41
+ - `ngrams` — bigrams + trigrams of the **fully-folded** corpus
42
+ (`normalizeText(corpus, {})`). This is the coarsest fold, so the same n-gram index
43
+ is a valid superset filter for every query mode.
44
+ - one **verify string** per stored query mode, keyed by `modeKey(mode)`:
45
+ - `norm` — the base, fully-folded string (case- and diacritic-insensitive).
46
+ - `norm_cs` — case-sensitive (diacritics stripped, case preserved).
47
+ - `norm_ds` — diacritic-sensitive (lowercased, diacritics preserved).
48
+ - `norm_cs_ds` — both case- and diacritic-sensitive.
49
+
50
+ A query for a given mode `$all`s the fully-folded n-grams of its patterns against
51
+ `ngrams`, then `$regex`es each pattern (folded with that same mode) against the
52
+ mode's verify string.
53
+
54
+ ## Mongo setup
55
+
56
+ Change streams (used by the recommended watcher, below) require MongoDB to run as a
57
+ **replica set**. A single-node replica set is enough for development.
58
+
59
+ With a stock `mongo:7` server:
60
+
61
+ ```bash
62
+ mongod --replSet rs0 --bind_ip_all
63
+ # in another shell, once:
64
+ mongosh --eval 'rs.initiate()'
65
+ ```
66
+
67
+ (`packages/demo` ships a `docker-compose.yml` + `Makefile` that does exactly this on
68
+ port 27018 with an idempotent `rs.initiate()` healthcheck — see the runnable
69
+ companion below.)
70
+
71
+ Then create the search indexes once, against your collection:
72
+
73
+ ```ts
74
+ import { createSearchIndexes } from '@quaesitor-textus/mongo'
75
+
76
+ await createSearchIndexes(collection, config)
77
+ ```
78
+
79
+ This creates one multikey index per target over its `ngrams` array (named
80
+ `${namespace}_${target}_ngrams`). If you only want to inspect the specs without
81
+ creating them, call `searchIndexSpecs(config)`.
82
+
83
+ ## Server wiring
84
+
85
+ ### 1. Define a `MongoSearchConfig`
86
+
87
+ A target names the document fields whose text you want to search, plus the query
88
+ modes you intend to support at runtime.
89
+
90
+ ```ts
91
+ import type { MongoSearchConfig } from '@quaesitor-textus/mongo'
92
+
93
+ const config: MongoSearchConfig = {
94
+ namespace: '_qt', // optional; default '_qt'
95
+ ngramSizes: [2, 3], // optional; default [2, 3]
96
+ targets: {
97
+ author: { fields: ['author'], queryModes: [{ caseSensitive: true }] },
98
+ title: { fields: ['title'], queryModes: [{ caseSensitive: true }] },
99
+ },
100
+ }
101
+ ```
102
+
103
+ - `fields` — paths harvested into the corpus (same path semantics as the core
104
+ filter, e.g. nested objects/arrays and the `$` root).
105
+ - `options` — the base/default query mode for the target; defaults to `{}` (fully
106
+ folded).
107
+ - `queryModes` — additional runtime-selectable modes. The set of verify strings a
108
+ target stores is `[options ?? {}, ...queryModes]` deduped by `modeKey`.
109
+
110
+ ### 2. Keep derived fields in sync
111
+
112
+ You need each document's derived `[namespace]` block to stay current as documents
113
+ are written. There are two ways:
114
+
115
+ **(a) Compute inline on every write.** Merge the derived fields into the document
116
+ before you persist it:
117
+
118
+ ```ts
119
+ import { computeSearchFields } from '@quaesitor-textus/mongo'
120
+
121
+ const doc = { author: 'Gabriel García Márquez', title: 'One Hundred Years of Solitude' }
122
+ await collection.insertOne({ ...doc, ...computeSearchFields(doc, config) })
123
+ ```
124
+
125
+ This gives you read-your-writes: the document is searchable the instant the insert
126
+ acknowledges. The cost is that every write path in your app must remember to do it.
127
+
128
+ **(b) Run the change-stream watcher (recommended).** Start it once at boot and write
129
+ your documents **raw** — the watcher recomputes and `$set`s the derived block for
130
+ you:
131
+
132
+ ```ts
133
+ import { startSearchSync } from '@quaesitor-textus/mongo'
134
+
135
+ const sync = startSearchSync(collection, config)
136
+ // ... later, on shutdown:
137
+ await sync.stop()
138
+ ```
139
+
140
+ The watcher tails the collection's change stream (`insert` / `update` / `replace`),
141
+ recomputes `computeSearchFields`, and writes the derived block back. It includes a
142
+ loop guard: if the stored derived block already equals the freshly computed one, it
143
+ skips the write so its own update does not retrigger the handler.
144
+
145
+ `startSearchSync` returns a `SearchSync` **emitter**: register a listener with
146
+ `sync.on(listener)` (remove it with `sync.off(listener)`) to receive a stream of
147
+ events — `indexing-started`, `indexing-finished` (a debounced burst summary, handy
148
+ for logging), and a per-document `indexed` event fired **after** each derive write
149
+ resolves (so a filter on the derived fields will match). Switch on `event.type`:
150
+
151
+ ```ts
152
+ const sync = startSearchSync(collection, config)
153
+ sync.on((e) => {
154
+ if (e.type === 'indexing-started') console.log('indexing started')
155
+ else if (e.type === 'indexing-finished') console.log(`indexed ${e.count} doc(s) in ${e.durationMs}ms`)
156
+ })
157
+ ```
158
+
159
+ **Backfill for external writers / restart resilience.** Change streams are
160
+ forward-only: they only see writes that happen *after* the watcher opens the stream,
161
+ so documents written before the watcher ran (or during downtime) never get a derived
162
+ block. Pass `{ backfill: true }` to sweep, on start, any pre-existing documents that
163
+ are missing the namespace (`{ [namespace]: { $exists: false } }`) and derive them:
164
+
165
+ ```ts
166
+ const sync = startSearchSync(collection, config, { backfill: true })
167
+ ```
168
+
169
+ This is the heterogeneous-writer pattern: one process (e.g. a Python tool) writes raw
170
+ documents, while a separate Node app runs the watcher with `backfill: true` and serves
171
+ search. On boot the Node app catches up on everything written while it was down, then
172
+ keeps current via the change stream. Backfill also requires a replica set.
173
+
174
+ **Versioned re-indexing.** `computeSearchFields` stamps `_qt._v = \`${SEARCH_FIELDS_VERSION}:${fingerprint(config)}\`` on each derived block. `SEARCH_FIELDS_VERSION` (a code constant) is bumped on any change to the derived output (normalization, n-grams, corpus, shape); the fingerprint hashes the derivation-affecting config (namespace, n-gram sizes, targets). The `backfill` sweep re-derives documents whose stored `_v` differs from the current one, so **upgrading the library or changing your config automatically re-indexes the collection on the next start with `backfill: true`** — no manual migration. This is how a normalization change (e.g. the precomposed-letter folding in v2) invalidates and rebuilds existing data.
175
+
176
+ **Trade-offs of the watcher:**
177
+
178
+ - It **requires a replica set** (change streams are a replica-set feature).
179
+ - Sync is **asynchronous**: there is a small window between your raw write and the
180
+ watcher's `$set`. During that window the document exists but its text is not yet
181
+ searchable, so **read-your-writes on text search is not guaranteed**. If you need
182
+ the document searchable immediately, use approach (a) for that write (or do both —
183
+ inline compute on the critical path, watcher as a backstop).
184
+
185
+ ### 3. Translate a text-search node into a Mongo filter
186
+
187
+ ```ts
188
+ import { buildTextSearchFilter } from '@quaesitor-textus/mongo'
189
+
190
+ const filter = buildTextSearchFilter('author', ['garcia', 'marquez'], config)
191
+ const rows = await collection.find(filter).toArray()
192
+ ```
193
+
194
+ `buildTextSearchFilter(target, patterns, config, options?)` returns a
195
+ `Filter<Document>`:
196
+
197
+ - empty `patterns` → `{}` (match everything);
198
+ - otherwise `{ $and: [ { ngramField: { $all: <folded ngrams> } }, ...perPatternVerifyRegex ] }`.
199
+
200
+ Each pattern must be a substring of the mode-folded verify string (patterns are
201
+ AND-ed). Pass `options` to pick a non-default mode (e.g.
202
+ `{ caseSensitive: true }`); omit it to use the target's base mode.
203
+
204
+ ## Client usage
205
+
206
+ The browser builds a query *description* and POSTs it to your server, which calls
207
+ `buildTextSearchFilter`. Below are three escalating shapes. The client tokenizes raw
208
+ input into patterns with core's `parseInput`.
209
+
210
+ ### (a) Naive single field
211
+
212
+ ```ts
213
+ import { parseInput } from '@quaesitor-textus/core'
214
+
215
+ // client
216
+ const patterns = parseInput(userInput) // e.g. 'garcia marquez' → ['garcia','marquez']
217
+ await fetch('/api/search', {
218
+ method: 'POST',
219
+ headers: { 'content-type': 'application/json' },
220
+ body: JSON.stringify({ patterns }),
221
+ })
222
+
223
+ // server
224
+ app.post('/api/search', async (req) => {
225
+ const { patterns } = req.body as { patterns: string[] }
226
+ const filter = buildTextSearchFilter('author', patterns, config)
227
+ return collection.find(filter).toArray()
228
+ })
229
+ ```
230
+
231
+ ### (b) Two fields (author OR title)
232
+
233
+ Combine two per-target filters yourself with `$or`:
234
+
235
+ ```ts
236
+ // server
237
+ const { patterns } = req.body as { patterns: string[] }
238
+ const filter = {
239
+ $or: [
240
+ buildTextSearchFilter('author', patterns, config),
241
+ buildTextSearchFilter('title', patterns, config),
242
+ ],
243
+ }
244
+ return collection.find(filter).toArray()
245
+ ```
246
+
247
+ ### (c) Inside a predicate tree
248
+
249
+ For richer UIs you will want to compose text search with other conditions (boolean
250
+ logic, scalar leaves). Here is **one reasonable, generic** predicate shape:
251
+
252
+ ```ts
253
+ type Predicate =
254
+ | { AND: Predicate[] }
255
+ | { OR: Predicate[] }
256
+ | { TEXT: { target: string; patterns: string[]; options?: SearchOptions } }
257
+ | { YEAR: { gte?: number; lte?: number } } // example scalar leaf
258
+
259
+ function toMongo(p: Predicate, config: MongoSearchConfig): Filter<Document> {
260
+ if ('AND' in p) return p.AND.length ? { $and: p.AND.map(c => toMongo(c, config)) } : {}
261
+ if ('OR' in p) return p.OR.length ? { $or: p.OR.map(c => toMongo(c, config)) } : {}
262
+ if ('TEXT' in p) return buildTextSearchFilter(p.TEXT.target, p.TEXT.patterns, config, p.TEXT.options)
263
+ // ...scalar leaves like YEAR translate to ordinary Mongo range filters
264
+ return {}
265
+ }
266
+ ```
267
+
268
+ > **Note:** this package does **not** own or assume your filter syntax. The shape
269
+ > above is just one reasonable example — `buildTextSearchFilter` is the only piece
270
+ > you need from here; you decide how text-search nodes fit into your own query
271
+ > language. (`packages/demo` implements a concrete version of exactly this pattern.)
272
+
273
+ ## Maintenance alternatives
274
+
275
+ The shipped mechanism for keeping derived fields in sync is the change-stream
276
+ **watcher** (`startSearchSync`). Other approaches are possible but worse:
277
+
278
+ - **Mongoose plugin** (pre-save hook) or a **driver wrapper** that intercepts writes:
279
+ both can call `computeSearchFields` and merge the result before persisting. They
280
+ work for full-document writes, but partial updates (`$set` of a single field) force
281
+ a **racy read-modify-write**: you must re-read the current document, recompute the
282
+ whole corpus, and write back — and there is no way to recompute server-side (no
283
+ Unicode normalization in Mongo's engine), so two concurrent partial updates can
284
+ clobber each other's derived fields.
285
+
286
+ The watcher sidesteps this: it always recomputes from the post-write `fullDocument`,
287
+ so it is correct regardless of how the write was shaped. Its only requirements are a
288
+ replica set and tolerance for the brief async-staleness window (see the watcher
289
+ trade-offs above).
290
+
291
+ ## Live search (SSE)
292
+
293
+ The watcher's per-document `indexed` event is the foundation for a **live, push-based
294
+ search**: clients see the current matching set, then watch new matches arrive as
295
+ documents are indexed. This package ships a small, layered, transport-agnostic engine
296
+ plus thin adapters for Fastify, Express, and Next.js (App + Pages Router).
297
+
298
+ ### The engine: `createLiveSearch`
299
+
300
+ `createLiveSearch` is framework-agnostic — it knows nothing about HTTP. Give it a
301
+ `SearchSync` (from `startSearchSync`), the collection/config, a Mongo `filter`, and a
302
+ `sendEvent` callback; it emits:
303
+
304
+ - `snapshot` — the current matching set (capped), sent once on start;
305
+ - `match` — one per newly-`indexed` document that matches `filter`;
306
+ - `capped` — sent once the emitted count reaches `cap` (default `500`), after which
307
+ no further matches are pushed.
308
+
309
+ ```ts
310
+ import { createLiveSearch } from '@quaesitor-textus/mongo'
311
+
312
+ const live = createLiveSearch({
313
+ sync, // a SearchSync from startSearchSync
314
+ collection,
315
+ config,
316
+ filter, // a Filter<Document>, e.g. from buildTextSearchFilter
317
+ sort: { field: 'year', dir: 1 }, // optional; sorts the initial snapshot
318
+ cap: 500, // optional; default 500
319
+ sendEvent: (event) => { /* serialize + push to the client */ },
320
+ })
321
+ // ... when the client disconnects:
322
+ live.stop()
323
+ ```
324
+
325
+ Internally it sends the snapshot (a sorted, capped `find`), then for each `indexed`
326
+ event runs a `findOne` match-test (`_id` AND `filter`) and emits a `match` only for
327
+ newly-matching, not-yet-seen documents.
328
+
329
+ ### The wire helpers: `formatSse` / `sseComment`
330
+
331
+ These format the SSE wire bytes, independent of any framework:
332
+
333
+ ```ts
334
+ import { formatSse, sseComment } from '@quaesitor-textus/mongo'
335
+
336
+ formatSse({ type: 'match', item }) // => `data: {"type":"match","item":{...}}\n\n`
337
+ sseComment() // => `: ping\n\n` (a heartbeat comment)
338
+ ```
339
+
340
+ ### Fastify — `@quaesitor-textus/mongo/fastify`
341
+
342
+ `streamLiveSearch` is the transport glue for Fastify: it sets the SSE headers, hijacks
343
+ the reply socket, runs a heartbeat (`heartbeatMs`, default `25000`), wires
344
+ `createLiveSearch` to `reply.raw.write(formatSse(...))`, and tears everything down when
345
+ the request closes. It lives behind a subpath export; **fastify is an optional peer
346
+ dependency**, so you only pull it in if you use this adapter.
347
+
348
+ ```ts
349
+ import { streamLiveSearch } from '@quaesitor-textus/mongo/fastify'
350
+
351
+ app.get('/api/live', (request, reply) => {
352
+ const filter = buildTextSearchFilter('author', patterns, config)
353
+ streamLiveSearch(request, reply, {
354
+ sync, // a SearchSync shared across requests
355
+ collection,
356
+ config,
357
+ filter,
358
+ sort: { field: 'year', dir: 1 }, // optional
359
+ cap: 500, // optional
360
+ heartbeatMs: 25000, // optional
361
+ })
362
+ })
363
+ ```
364
+
365
+ ### Express — `@quaesitor-textus/mongo/express`
366
+
367
+ ```ts
368
+ import { streamLiveSearch } from '@quaesitor-textus/mongo/express'
369
+
370
+ app.get('/api/live', (req, res) => {
371
+ const filter = buildTextSearchFilter('author', patterns, config)
372
+ streamLiveSearch(req, res, { sync, collection, config, filter })
373
+ })
374
+ ```
375
+
376
+ ### Next.js Pages Router — `@quaesitor-textus/mongo/next/pages`
377
+
378
+ ```ts
379
+ import { streamLiveSearch } from '@quaesitor-textus/mongo/next/pages'
380
+
381
+ export default function handler(req, res) {
382
+ streamLiveSearch(req, res, { sync, collection, config, filter })
383
+ }
384
+ export const config = { api: { responseLimit: false } } // allow long-lived SSE
385
+ ```
386
+
387
+ ### Next.js App Router — `@quaesitor-textus/mongo/next/app`
388
+
389
+ ```ts
390
+ import { liveSearchResponse } from '@quaesitor-textus/mongo/next/app'
391
+
392
+ export async function GET(request: Request) {
393
+ // parse the filter from request.url, build the Mongo filter, then:
394
+ return liveSearchResponse({ sync, collection, config, filter })
395
+ }
396
+ ```
397
+
398
+ **Dependency-free by design.** The Express and Next Pages adapters are typed against
399
+ Node's `http` `IncomingMessage`/`ServerResponse` (those frameworks' request/response
400
+ objects are subtypes), and the Next App adapter uses only the Web `Response`/`ReadableStream`
401
+ APIs. So **none of them import — or require you to install — `express` or `next`**; you
402
+ only need the framework you already use. Only the Fastify adapter imports its framework
403
+ (for `reply.hijack()`), as an optional peer dependency.
404
+
405
+ ### Any other framework
406
+
407
+ `createLiveSearch` + `formatSse`/`sseComment` are the reusable core. Wiring them to any
408
+ runtime that exposes a writable response is a handful of lines (write the SSE headers,
409
+ push each `sendEvent` payload through `formatSse`, run a heartbeat with `sseComment`, call
410
+ `live.stop()` on disconnect) — exactly what the shared `runLiveSearch` helper does.
411
+
412
+ ## Runnable companion
413
+
414
+ See [`packages/demo`](../demo) for a full-stack, runnable example: a Fastify + Vite /
415
+ React / antd book-search UI over MongoDB with server-side pagination, a year-range
416
+ predicate composed with text search, and a live watcher showcase (the "truckload"
417
+ button inserts raw documents and you watch them become searchable a moment later).