@delali/narsil 0.3.1-next.73 → 0.3.1-next.74

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 (46) hide show
  1. package/dist/{capabilities-CYeAWYxQ.d.ts → capabilities-CAMzmkAg.d.ts} +2 -2
  2. package/dist/{chunk-PU43WDY4.mjs → chunk-2E35UM3G.mjs} +1 -13
  3. package/dist/chunk-3DDUNI6N.mjs +48 -0
  4. package/dist/{chunk-THMSFOJO.mjs → chunk-BVBIQQKG.mjs} +576 -547
  5. package/dist/{chunk-ZULSEZCE.mjs → chunk-CTOSGRM7.mjs} +100 -19
  6. package/dist/{chunk-CVFAFZSN.mjs → chunk-CUZOX6CN.mjs} +23 -15
  7. package/dist/chunk-I23G3IZC.mjs +593 -0
  8. package/dist/chunk-KEHK2O6P.mjs +13 -0
  9. package/dist/{chunk-AFKH4ZK3.mjs → chunk-LX4JERXI.mjs} +1 -1
  10. package/dist/{chunk-LPBWCHBE.mjs → chunk-NOZUQM7J.mjs} +2 -2
  11. package/dist/{chunk-WVDFG45M.mjs → chunk-PO53FV4Q.mjs} +2 -1
  12. package/dist/chunk-T5ZWEWVD.mjs +658 -0
  13. package/dist/{chunk-2WLD2NFW.mjs → chunk-TVFLHM7M.mjs} +2 -2
  14. package/dist/{chunk-3YKWSO54.mjs → chunk-VKX2BPXD.mjs} +147 -647
  15. package/dist/{chunk-AK3BLGCI.mjs → chunk-Z3DQPOJQ.mjs} +15 -48
  16. package/dist/{client-D698E5ge.d.ts → client-C-I70ArH.d.ts} +3 -3
  17. package/dist/client.d.ts +8 -8
  18. package/dist/{config-Bv8etwUZ.d.ts → config-C6Iw5rCX.d.ts} +2 -2
  19. package/dist/{config-QXU3HMpq.d.ts → config-DJPH3IQB.d.ts} +2 -2
  20. package/dist/direct-executor-KFAGILJC.mjs +17 -0
  21. package/dist/distribution/coordinator/etcd.d.ts +2 -2
  22. package/dist/distribution/coordinator/in-memory.d.ts +2 -2
  23. package/dist/distribution.d.ts +8 -8
  24. package/dist/distribution.mjs +19 -9
  25. package/dist/{engine-D_OzKZ-6.d.ts → engine-B8eRPO7m.d.ts} +2 -2
  26. package/dist/index.browser.mjs +1200 -808
  27. package/dist/index.d.ts +27 -8
  28. package/dist/index.mjs +12 -8
  29. package/dist/{memory-B4jMmygw.d.ts → memory-DJEwWoCi.d.ts} +1205 -1180
  30. package/dist/partial-words-DTIHO8G4.d.ts +19 -0
  31. package/dist/partial-words.d.ts +22 -0
  32. package/dist/partial-words.mjs +11 -0
  33. package/dist/persistence/durability/checkpoint-worker.d.ts +33 -13
  34. package/dist/persistence/durability/checkpoint-worker.mjs +12 -8
  35. package/dist/react.d.ts +7 -7
  36. package/dist/{schema-BBOCdhND.d.ts → schema-DgyDijhf.d.ts} +6 -2
  37. package/dist/server.d.ts +10 -10
  38. package/dist/server.mjs +8 -6
  39. package/dist/{tasks-DpgCpW1x.d.ts → tasks-BVmAKYBh.d.ts} +1 -1
  40. package/dist/{thread-3LNVA43V.mjs → thread-W6DPKEF6.mjs} +8 -5
  41. package/dist/{types-BiUmaiWT.d.ts → types-ChrVy4lH.d.ts} +1 -1
  42. package/dist/vector/search-worker.d.ts +1 -1
  43. package/dist/vector/search-worker.mjs +3 -2
  44. package/dist/workers/entry.mjs +3 -3
  45. package/package.json +15 -7
  46. package/dist/direct-executor-5SRDFZAS.mjs +0 -13
@@ -1,1421 +1,1446 @@
1
- import { A as AnyDocument, S as SchemaDefinition, d as ScoringMode } from './schema-BBOCdhND.js';
1
+ import { A as AnyDocument, d as ScoringMode, S as SchemaDefinition } from './schema-DgyDijhf.js';
2
2
 
3
3
  /**
4
- * Every code a {@link NarsilError} carries, grouped by the part of the engine
5
- * that raises it.
6
- *
7
- * Match on the code rather than on the message, because a code is stable and a
8
- * message is not. The HTTP server maps each code to a status, so a code also
9
- * tells you whether the caller or the engine is at fault.
4
+ * Compares one field against a value. Setting several keys narrows the match,
5
+ * because a document has to satisfy all of them.
10
6
  *
11
7
  * @public
12
8
  */
13
- declare const ErrorCodes: {
14
- readonly SCHEMA_INVALID_TYPE: "SCHEMA_INVALID_TYPE";
15
- readonly SCHEMA_DEPTH_EXCEEDED: "SCHEMA_DEPTH_EXCEEDED";
16
- readonly SCHEMA_INVALID_VECTOR_DIMENSION: "SCHEMA_INVALID_VECTOR_DIMENSION";
17
- readonly SCHEMA_INVALID_GEOPOINT: "SCHEMA_INVALID_GEOPOINT";
18
- readonly DOC_NOT_FOUND: "DOC_NOT_FOUND";
19
- readonly DOC_ALREADY_EXISTS: "DOC_ALREADY_EXISTS";
20
- readonly DOC_VALIDATION_FAILED: "DOC_VALIDATION_FAILED";
21
- readonly INDEX_NOT_FOUND: "INDEX_NOT_FOUND";
22
- readonly INDEX_ALREADY_EXISTS: "INDEX_ALREADY_EXISTS";
23
- readonly INDEX_ORPHANED: "INDEX_ORPHANED";
24
- readonly INDEX_REOPEN_CAPACITY_EXHAUSTED: "INDEX_REOPEN_CAPACITY_EXHAUSTED";
25
- readonly INSTANCE_SHUT_DOWN: "INSTANCE_SHUT_DOWN";
26
- readonly PARTITION_CORRUPTED: "PARTITION_CORRUPTED";
27
- readonly PARTITION_REBALANCING_BACKPRESSURE: "PARTITION_REBALANCING_BACKPRESSURE";
28
- readonly WORKER_CRASHED: "WORKER_CRASHED";
29
- readonly WORKER_BUSY: "WORKER_BUSY";
30
- readonly WORKER_TIMEOUT: "WORKER_TIMEOUT";
31
- readonly WORKER_ACTION_FAILED: "WORKER_ACTION_FAILED";
32
- readonly PERSISTENCE_SAVE_FAILED: "PERSISTENCE_SAVE_FAILED";
33
- readonly PERSISTENCE_LOAD_FAILED: "PERSISTENCE_LOAD_FAILED";
34
- readonly PERSISTENCE_DELETE_FAILED: "PERSISTENCE_DELETE_FAILED";
35
- readonly PERSISTENCE_CRC_MISMATCH: "PERSISTENCE_CRC_MISMATCH";
36
- readonly PERSISTENCE_WAL_CORRUPT: "PERSISTENCE_WAL_CORRUPT";
37
- readonly PERSISTENCE_FSYNC_FAILED: "PERSISTENCE_FSYNC_FAILED";
38
- readonly SEARCH_INVALID_FIELD: "SEARCH_INVALID_FIELD";
39
- readonly VECTOR_DIMENSION_MISMATCH: "VECTOR_DIMENSION_MISMATCH";
40
- readonly SEARCH_INVALID_FILTER: "SEARCH_INVALID_FILTER";
41
- readonly SEARCH_INVALID_MODE: "SEARCH_INVALID_MODE";
42
- readonly SEARCH_INVALID_CURSOR: "SEARCH_INVALID_CURSOR";
43
- readonly SEARCH_RESULT_WINDOW_EXCEEDED: "SEARCH_RESULT_WINDOW_EXCEEDED";
44
- readonly SEARCH_WORK_CAP_EXCEEDED: "SEARCH_WORK_CAP_EXCEEDED";
45
- readonly LANGUAGE_NOT_SUPPORTED: "LANGUAGE_NOT_SUPPORTED";
46
- readonly ENVELOPE_VERSION_MISMATCH: "ENVELOPE_VERSION_MISMATCH";
47
- readonly ENVELOPE_INVALID_MAGIC: "ENVELOPE_INVALID_MAGIC";
48
- readonly PARTITION_CAPACITY_EXCEEDED: "PARTITION_CAPACITY_EXCEEDED";
49
- readonly EMBEDDING_FAILED: "EMBEDDING_FAILED";
50
- readonly EMBEDDING_DIMENSION_MISMATCH: "EMBEDDING_DIMENSION_MISMATCH";
51
- readonly EMBEDDING_NO_SOURCE: "EMBEDDING_NO_SOURCE";
52
- readonly EMBEDDING_CONFIG_INVALID: "EMBEDDING_CONFIG_INVALID";
53
- readonly DOC_MISSING_REQUIRED_FIELD: "DOC_MISSING_REQUIRED_FIELD";
54
- readonly CONFIG_INVALID: "CONFIG_INVALID";
55
- readonly QUERY_ROUTING_FAILED: "QUERY_ROUTING_FAILED";
56
- readonly QUERY_PARTIAL_FAILURE: "QUERY_PARTIAL_FAILURE";
57
- readonly QUERY_NODE_TIMEOUT: "QUERY_NODE_TIMEOUT";
58
- readonly QUERY_NO_ACTIVE_REPLICA: "QUERY_NO_ACTIVE_REPLICA";
59
- readonly CLUSTER_OPERATION_UNSUPPORTED: "CLUSTER_OPERATION_UNSUPPORTED";
60
- readonly ALLOCATION_NO_DATA_NODES: "ALLOCATION_NO_DATA_NODES";
61
- readonly ALLOCATION_INVALID_CONFIG: "ALLOCATION_INVALID_CONFIG";
62
- readonly ALLOCATION_FAILED: "ALLOCATION_FAILED";
63
- readonly CONTROLLER_METADATA_INVALID: "CONTROLLER_METADATA_INVALID";
64
- readonly NODE_BOOTSTRAP_FAILED: "NODE_BOOTSTRAP_FAILED";
65
- readonly NODE_ALREADY_JOINED: "NODE_ALREADY_JOINED";
66
- readonly NODE_NOT_JOINED: "NODE_NOT_JOINED";
67
- readonly NODE_NOT_READY: "NODE_NOT_READY";
68
- readonly NODE_NOT_CONTROLLER: "NODE_NOT_CONTROLLER";
69
- readonly COORDINATOR_DEPENDENCY_MISSING: "COORDINATOR_DEPENDENCY_MISSING";
70
- readonly TRANSPORT_DEPENDENCY_MISSING: "TRANSPORT_DEPENDENCY_MISSING";
71
- readonly REPLICATION_ENTRY_INVALID: "REPLICATION_ENTRY_INVALID";
72
- readonly REPLICATION_INSYNC_REMOVAL_FAILED: "REPLICATION_INSYNC_REMOVAL_FAILED";
73
- readonly REPLICATION_ROLLBACK_FAILED: "REPLICATION_ROLLBACK_FAILED";
74
- readonly REPLICATION_LOG_FULL: "REPLICATION_LOG_FULL";
75
- readonly REPLICATION_ENTRY_CORRUPT: "REPLICATION_ENTRY_CORRUPT";
76
- readonly REPLICATION_SNAPSHOT_CORRUPT: "REPLICATION_SNAPSHOT_CORRUPT";
77
- readonly REPLICATION_TERM_MISMATCH: "REPLICATION_TERM_MISMATCH";
78
- readonly REPLICATION_SYNC_FAILED: "REPLICATION_SYNC_FAILED";
79
- readonly PARTITION_NOT_PRIMARY: "PARTITION_NOT_PRIMARY";
80
- readonly PARTITION_UNASSIGNED: "PARTITION_UNASSIGNED";
81
- readonly INSUFFICIENT_REPLICAS: "INSUFFICIENT_REPLICAS";
82
- readonly SNAPSHOT_SYNC_UNAUTHORIZED: "SNAPSHOT_SYNC_UNAUTHORIZED";
83
- readonly SNAPSHOT_SYNC_REQUEST_INVALID: "SNAPSHOT_SYNC_REQUEST_INVALID";
84
- readonly SNAPSHOT_SYNC_INDEX_NOT_FOUND: "SNAPSHOT_SYNC_INDEX_NOT_FOUND";
85
- readonly SNAPSHOT_SYNC_CAPACITY_EXHAUSTED: "SNAPSHOT_SYNC_CAPACITY_EXHAUSTED";
86
- readonly SNAPSHOT_SYNC_SNAPSHOT_FAILED: "SNAPSHOT_SYNC_SNAPSHOT_FAILED";
87
- readonly SNAPSHOT_SYNC_DECODE_FAILED: "SNAPSHOT_SYNC_DECODE_FAILED";
88
- readonly SNAPSHOT_SYNC_FRAME_INVALID: "SNAPSHOT_SYNC_FRAME_INVALID";
89
- readonly SNAPSHOT_SYNC_HEADER_INVALID: "SNAPSHOT_SYNC_HEADER_INVALID";
90
- readonly SNAPSHOT_SYNC_HEADER_MISMATCH: "SNAPSHOT_SYNC_HEADER_MISMATCH";
91
- readonly SNAPSHOT_SYNC_CHUNK_OUT_OF_ORDER: "SNAPSHOT_SYNC_CHUNK_OUT_OF_ORDER";
92
- readonly SNAPSHOT_SYNC_CHUNK_OVERFLOW: "SNAPSHOT_SYNC_CHUNK_OVERFLOW";
93
- readonly SNAPSHOT_SYNC_CHUNK_SIZE_EXCEEDED: "SNAPSHOT_SYNC_CHUNK_SIZE_EXCEEDED";
94
- readonly SNAPSHOT_SYNC_CHUNK_MISSING: "SNAPSHOT_SYNC_CHUNK_MISSING";
95
- readonly SNAPSHOT_SYNC_END_MISSING: "SNAPSHOT_SYNC_END_MISSING";
96
- readonly SNAPSHOT_SYNC_CHECKSUM_MISMATCH: "SNAPSHOT_SYNC_CHECKSUM_MISMATCH";
97
- readonly SNAPSHOT_SYNC_PRIMARY_ERROR: "SNAPSHOT_SYNC_PRIMARY_ERROR";
98
- readonly SNAPSHOT_SYNC_NO_TARGETS: "SNAPSHOT_SYNC_NO_TARGETS";
99
- readonly SNAPSHOT_SYNC_TRANSPORT_FAILED: "SNAPSHOT_SYNC_TRANSPORT_FAILED";
100
- readonly SNAPSHOT_SYNC_SCHEMA_UNAVAILABLE: "SNAPSHOT_SYNC_SCHEMA_UNAVAILABLE";
101
- readonly SNAPSHOT_SYNC_RESTORE_FAILED: "SNAPSHOT_SYNC_RESTORE_FAILED";
102
- readonly SNAPSHOT_SYNC_RESTORE_CLEANUP_FAILED: "SNAPSHOT_SYNC_RESTORE_CLEANUP_FAILED";
103
- readonly SNAPSHOT_SYNC_TIMEOUT: "SNAPSHOT_SYNC_TIMEOUT";
104
- readonly SNAPSHOT_SYNC_ALLOCATION_UNAVAILABLE: "SNAPSHOT_SYNC_ALLOCATION_UNAVAILABLE";
105
- readonly SNAPSHOT_SYNC_NOT_ASSIGNED: "SNAPSHOT_SYNC_NOT_ASSIGNED";
106
- readonly SNAPSHOT_SYNC_ABORTED: "SNAPSHOT_SYNC_ABORTED";
9
+ type ComparisonFilter = {
10
+ /** This matches a field equal to the value, or a list field where one element equals it. */
11
+ eq?: number | string | boolean;
12
+ /**
13
+ * This matches a document that holds the field with a value other than this
14
+ * one, or a list field where every element differs from it, which an empty
15
+ * list does.
16
+ */
17
+ ne?: number | string | boolean;
18
+ /** This matches a field greater than the number. */
19
+ gt?: number;
20
+ /** This matches a field less than the number. */
21
+ lt?: number;
22
+ /** This matches a field greater than or equal to the number. */
23
+ gte?: number;
24
+ /** This matches a field less than or equal to the number. */
25
+ lte?: number;
26
+ /** This matches a field inside the inclusive range, given as `[low, high]`. */
27
+ between?: [number, number];
107
28
  };
108
29
  /**
109
- * Any one of the codes in {@link ErrorCodes}, which is the type to narrow on
110
- * when you branch on a failure the engine raised.
30
+ * The engine tests a text field against this filter for equality, for a text
31
+ * range, or with the set and prefix tests.
111
32
  *
112
- * @public
113
- */
114
- type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];
115
- /**
116
- * Every code the HTTP layer raises for a failure that arises before or around
117
- * the engine call, such as parsing the body, enforcing a limit, or routing.
33
+ * The engine compares each element of a `string[]`, `verbatim[]`, or `enum[]` field, so
34
+ * it matches a document with `eq`, `in`, `startsWith`, `endsWith`, or
35
+ * `contains` where one element passes the test, while it matches a document
36
+ * with `ne` or `nin` where every element differs from the values.
118
37
  *
119
- * The engine raises none of these, so a failure carrying one of them says the
120
- * request never reached the engine.
38
+ * The engine applies the range tests `gt`, `gte`, `lt`, `lte`, and `between`
39
+ * to a single `string` or `verbatim` field whose type includes `sortable`,
40
+ * while it throws `SEARCH_INVALID_FILTER` for a text range on any other field.
41
+ * It orders the values as a sort on the field does, comparing their case folds
42
+ * first and their raw code points only where the folds are equal.
121
43
  *
122
- * @public
123
- */
124
- declare const ServerErrorCodes: {
125
- readonly INVALID_REQUEST: "INVALID_REQUEST";
126
- readonly INVALID_JSON: "INVALID_JSON";
127
- readonly EMPTY_BODY: "EMPTY_BODY";
128
- readonly PAYLOAD_TOO_LARGE: "PAYLOAD_TOO_LARGE";
129
- readonly NOT_FOUND: "NOT_FOUND";
130
- readonly TASK_NOT_FOUND: "TASK_NOT_FOUND";
131
- readonly TASK_NOT_CANCELLABLE: "TASK_NOT_CANCELLABLE";
132
- readonly TASK_OWNED_BY_ANOTHER_INSTANCE: "TASK_OWNED_BY_ANOTHER_INSTANCE";
133
- readonly TASK_INTERRUPTED: "TASK_INTERRUPTED";
134
- readonly TOO_MANY_REQUESTS: "TOO_MANY_REQUESTS";
135
- readonly HOOK_ERROR: "HOOK_ERROR";
136
- readonly INTERNAL_ERROR: "INTERNAL_ERROR";
137
- };
138
- /**
139
- * Any one of the codes in {@link ServerErrorCodes}.
44
+ * A pattern field is a `verbatim` or `verbatim[]` field, or a `string` or
45
+ * `string[]` field whose type includes `pattern`. On such a field, the engine
46
+ * answers `eq`, `ne`, `in`, `nin`, `startsWith`, `endsWith`, and `contains`
47
+ * from the field's pattern index. `caseFold` applies to each of those tests.
48
+ * On an `enum` or `enum[]` field, the engine answers `eq`, `ne`, `in`, `nin`,
49
+ * `startsWith`, and `endsWith` from the field's index of values. It throws
50
+ * `SEARCH_INVALID_FILTER` for `eq`, `ne`, `in`, `nin`, `startsWith`, or
51
+ * `endsWith` on a `string` or `string[]` field whose type leaves out
52
+ * `pattern`, because such a field keeps no index of whole values.
53
+ * The engine compares the code points of each value as stored, with no
54
+ * Unicode normalisation. It throws `SEARCH_INVALID_FILTER` for `contains` or
55
+ * `caseFold` on any other field, for a test text longer than 1,024 code points
56
+ * on a pattern field, and for a `caseFold` test whose text has a case fold
57
+ * longer than 2,048 code points.
140
58
  *
141
59
  * @public
142
60
  */
143
- type ServerErrorCode = (typeof ServerErrorCodes)[keyof typeof ServerErrorCodes];
61
+ type StringFilter = Pick<ComparisonFilter, 'eq' | 'ne'> & {
62
+ /** This matches a value that comes after the text in sort order. */
63
+ gt?: string;
64
+ /** This matches a value that comes before the text in sort order. */
65
+ lt?: string;
66
+ /** This matches a value equal to the text or after it in sort order. */
67
+ gte?: string;
68
+ /** This matches a value equal to the text or before it in sort order. */
69
+ lte?: string;
70
+ /** This matches a value inside the inclusive range in sort order, given as `[low, high]`. */
71
+ between?: [string, string];
72
+ /** This matches a field equal to any value in the list, which holds at most 65,536 values. */
73
+ in?: string[];
74
+ /** This matches a field that differs from every value in the list, which holds at most 65,536 values. */
75
+ nin?: string[];
76
+ /** This matches a field starting with the text. */
77
+ startsWith?: string;
78
+ /** This matches a field ending with the text. */
79
+ endsWith?: string;
80
+ /** This matches a pattern field whose value holds the text anywhere in it. */
81
+ contains?: string;
82
+ /**
83
+ * When this is true, the engine compares the case fold of each value of a
84
+ * pattern field with the case fold of the text, so a test for `error` matches
85
+ * `ERROR`. It applies to `eq`, `ne`, `in`, `nin`, `startsWith`, `endsWith`,
86
+ * and `contains`.
87
+ */
88
+ caseFold?: boolean;
89
+ };
144
90
  /**
145
- * Every code that the caller's own side raises, where a request never reaches
146
- * a server, or where the caller cannot read the answer.
91
+ * Tests the contents of a list field, which is a `number[]`, `boolean[]`,
92
+ * `enum[]`, `verbatim[]`, or `string[]` field.
147
93
  *
148
- * The HTTP client raises the first five. The React bindings raise
149
- * `CLIENT_UNEXPECTED_ERROR` alone, which reports a fault inside a hook. No
150
- * server sends any of them, so a failure under one means the exchange broke
151
- * before the operation ran. `STATUS_BY_CODE` in `src/server/errors.ts`
152
- * therefore maps none of them, because no request can arrive under one and no
153
- * HTTP status belongs to one.
94
+ * The engine throws `SEARCH_INVALID_FILTER` for these tests on any other
95
+ * field, for a value whose type differs from the type of the list's elements,
96
+ * and for `containsAll` or `matchesAny` on a `string[]` field whose type leaves
97
+ * out `pattern`.
154
98
  *
155
99
  * @public
156
100
  */
157
- declare const ClientErrorCodes: {
158
- readonly CLIENT_CONNECTION_FAILED: "CLIENT_CONNECTION_FAILED";
159
- readonly CLIENT_REQUEST_TIMEOUT: "CLIENT_REQUEST_TIMEOUT";
160
- readonly CLIENT_REQUEST_ABORTED: "CLIENT_REQUEST_ABORTED";
161
- readonly CLIENT_INVALID_RESPONSE: "CLIENT_INVALID_RESPONSE";
162
- readonly CLIENT_TASK_TIMEOUT: "CLIENT_TASK_TIMEOUT";
163
- readonly CLIENT_UNEXPECTED_ERROR: "CLIENT_UNEXPECTED_ERROR";
101
+ type ArrayFilter = {
102
+ /** This matches a list holding every one of the values, at most 65,536 of them, so an empty set of values matches every list. */
103
+ containsAll?: (string | number | boolean)[];
104
+ /** This matches a list holding at least one of the values, at most 65,536 of them. */
105
+ matchesAny?: (string | number | boolean)[];
106
+ /** This compares the number of elements in the list. */
107
+ size?: ComparisonFilter;
164
108
  };
165
109
  /**
166
- * Any one of the codes in {@link ClientErrorCodes}.
110
+ * Tests whether a field carries a value at all, without looking at what it
111
+ * holds.
167
112
  *
168
113
  * @public
169
114
  */
170
- type ClientErrorCode = (typeof ClientErrorCodes)[keyof typeof ClientErrorCodes];
115
+ type PresenceFilter = {
116
+ /** This matches a document where the field holds a value other than null. */
117
+ exists?: boolean;
118
+ /** This matches a document where the field is absent or null. */
119
+ notExists?: boolean;
120
+ /** This matches a document where the field is absent, null, an empty string, or an empty list. */
121
+ isEmpty?: boolean;
122
+ /** This matches a document where the field holds a value other than an empty string or an empty list. */
123
+ isNotEmpty?: boolean;
124
+ };
171
125
  /**
172
- * Every code a {@link NarsilError} can carry: one the engine raised, one the
173
- * HTTP layer raised, one the client raised, or any other string.
174
- *
175
- * The last arm exists for a server's `onRequest` hook, which rejects a request
176
- * under a code of its own, such as `UNAUTHORIZED`, and the client then passes
177
- * that code through unchanged. An editor still completes every code Narsil
178
- * defines.
126
+ * Matches a `geopoint` field against a circle drawn on the earth.
179
127
  *
180
128
  * @public
181
129
  */
182
- type NarsilErrorCode = ErrorCode | ServerErrorCode | ClientErrorCode | (string & {});
183
- /**
184
- * The error every part of the engine throws.
130
+ type GeoRadiusFilter = {
131
+ /** The engine tests the field against this circle. */
132
+ radius: {
133
+ /** The centre has this latitude, in degrees from -90 to 90. For any other value, the engine throws `SEARCH_INVALID_FILTER`. */
134
+ lat: number;
135
+ /** The centre has this longitude, in degrees from -180 to 180. For any other value, the engine throws `SEARCH_INVALID_FILTER`. */
136
+ lon: number;
137
+ /** The circle has this radius, measured in `unit`. */
138
+ distance: number;
139
+ /**
140
+ * The engine measures `distance` in kilometres under `'km'`, in miles
141
+ * under `'mi'`, and in metres under `'m'`. For any other unit, it throws
142
+ * `SEARCH_INVALID_FILTER`.
143
+ */
144
+ unit: 'km' | 'mi' | 'm';
145
+ /** The engine matches the points inside the circle while this is true, which is the default, and the points outside it while this is false. */
146
+ inside?: boolean;
147
+ /**
148
+ * The engine measures each distance with the Haversine formula on a sphere
149
+ * by default, and with Vincenty's formula on the WGS-84 ellipsoid while
150
+ * this is true. Vincenty's formula iterates, so the engine takes longer
151
+ * to compute each distance. The two formulas differ by less than 0.3% under about
152
+ * 100 km, while across a continent they can differ by up to 0.5%.
153
+ */
154
+ highPrecision?: boolean;
155
+ };
156
+ };
157
+ /**
158
+ * Matches a `geopoint` field against a polygon drawn on the earth.
185
159
  *
186
- * Catch it, read {@link NarsilError.code} to decide what to do, and read
187
- * {@link NarsilError.details} for the values that caused it. The engine lets
188
- * this error propagate unchanged, so the code you catch is the code the
189
- * failing operation raised.
160
+ * @public
161
+ */
162
+ type GeoPolygonFilter = {
163
+ /** The engine tests the field against this polygon. */
164
+ polygon: {
165
+ /**
166
+ * The engine closes the ring through these corners in the order that you
167
+ * list them, so you can leave the first point off the end. It throws
168
+ * `SEARCH_INVALID_FILTER` for a ring of fewer than three corners, which
169
+ * encloses no area, and for a corner whose latitude is outside -90 to 90
170
+ * or whose longitude is outside -180 to 180. It also throws that error for
171
+ * a ring of more than 65,536 corners. List the corners counter-clockwise
172
+ * around the area, as in an exterior ring of GeoJSON. Where the corners
173
+ * span 180 degrees of longitude or more, the engine matches the area on
174
+ * the left of that path, so a ring listed that way can cross the
175
+ * antimeridian or span more than half the globe.
176
+ */
177
+ points: Array<{
178
+ lat: number;
179
+ lon: number;
180
+ }>;
181
+ /** The engine matches the points inside the polygon while this is true, which is the default, and the points outside it while this is false. */
182
+ inside?: boolean;
183
+ };
184
+ };
185
+ /**
186
+ * Either shape a `geopoint` field is matched against.
190
187
  *
191
188
  * @public
192
189
  */
193
- declare class NarsilError extends Error {
194
- /** This says which failure it is. */
195
- readonly code: NarsilErrorCode;
196
- /** This carries the values behind the failure, such as the field, index, or limit involved. It is empty when the code says everything. */
197
- readonly details: Record<string, unknown>;
198
- /**
199
- * Builds an error carrying a code the caller can branch on.
200
- *
201
- * @param code - The failure this error reports, from {@link ErrorCodes} for
202
- * an engine failure, {@link ServerErrorCodes} for one the HTTP layer raised,
203
- * or {@link ClientErrorCodes} for one that stopped a request from reaching a
204
- * server.
205
- * @param message - Plain description, for a log or a person.
206
- * @param details - Values behind the failure, which reach
207
- * {@link NarsilError.details}.
208
- */
209
- constructor(code: NarsilErrorCode, message: string, details?: Record<string, unknown>);
210
- }
190
+ type GeoFilter = GeoRadiusFilter | GeoPolygonFilter;
211
191
  /**
212
- * Reports whether a caught value is a {@link NarsilError}, including one that
213
- * another entry point of this package raises.
192
+ * The filter one field accepts. Which of these forms applies follows from the
193
+ * field's declared type.
214
194
  *
215
- * Each browser bundle holds its own copy of the class, so an `instanceof` test
216
- * inside the React bindings returns false for an error that the client raises,
217
- * although that error still holds its code. This function tests for the marker
218
- * that the constructor writes, so it returns true for an error from any entry
219
- * point.
195
+ * @public
196
+ */
197
+ type FieldFilter = ComparisonFilter | StringFilter | ArrayFilter | PresenceFilter | GeoFilter;
198
+ /**
199
+ * The filter that a query runs, built from per-field tests and the boolean
200
+ * operators that combine them.
220
201
  *
221
- * @param value - The value that a `catch` block receives.
222
- * @returns True where the value holds a code in {@link NarsilError.code}.
202
+ * The engine answers every test from an index that it keeps for the field. It
203
+ * applies the filter before scoring, so a narrow filter makes a search
204
+ * cheaper. A filter nests at most 30 levels deep and holds at most 1,024
205
+ * tests, counted across every field and nested expression. Past either limit,
206
+ * the engine throws `SEARCH_INVALID_FILTER`, while it throws
207
+ * `SEARCH_INVALID_FIELD` for a test on a field that the schema leaves out.
223
208
  *
224
209
  * @public
225
210
  */
226
- declare function isNarsilError(value: unknown): value is NarsilError;
211
+ type FilterExpression = {
212
+ /** These per-field tests are keyed by field name, and a document has to satisfy every entry. */
213
+ fields?: Record<string, FieldFilter>;
214
+ /** Every nested expression has to match. */
215
+ and?: FilterExpression[];
216
+ /** At least one nested expression has to match. */
217
+ or?: FilterExpression[];
218
+ /** The nested expression has to fail. */
219
+ not?: FilterExpression;
220
+ };
227
221
 
228
222
  /**
229
- * This map lists every event that the engine emits, with the payload of each
230
- * one.
223
+ * Everything {@link Narsil.suggest} accepts.
231
224
  *
232
- * {@link Narsil.on} registers a listener under a key from this map, so that the
233
- * engine can pass the matching payload to that listener. Most of these events
234
- * report work that the engine does in the background, away from the call that
235
- * started it, so a failure that such an event reports never rejects a promise
236
- * that you are holding.
225
+ * @public
226
+ */
227
+ interface SuggestParams {
228
+ /** The returned terms complete this text. */
229
+ prefix: string;
230
+ /** The lookup returns this many completions, most widely used first, and 10 by default. */
231
+ limit?: number;
232
+ }
233
+ /**
234
+ * Everything {@link Narsil.listDocuments} accepts.
235
+ *
236
+ * {@link Narsil.listDocuments} reads the stored documents without ranking them,
237
+ * which is how you page through a whole index. Leave `cursor` out to start at
238
+ * the first document, then pass back the cursor each result carries until it
239
+ * comes back null.
240
+ *
241
+ * A cursor belongs to the sort it was made under, so pass the same `sort` back
242
+ * with it. Changing `sort` invalidates the cursor, and the engine then throws
243
+ * `SEARCH_INVALID_CURSOR` rather than returning a page from the wrong order.
237
244
  *
238
245
  * @public
239
246
  */
240
- type NarsilEventMap = {
247
+ interface ListParams {
241
248
  /**
242
- * The engine emits this event after a call changes what a read returns from
243
- * an index. The calls are the inserts, updates, and removals, singly or in a
244
- * batch, together with `clear`, `restore`, `rebalance`, `rebuildAnalysis`,
245
- * `compactVectors`, `optimizeVectors`, `createIndex`, and `dropIndex`. The
246
- * engine emits the event after a call that throws as well, because a call can
247
- * change the index before it throws. It also emits the event after it reloads
248
- * an index, once a shared invalidation adapter reports that another instance
249
- * saved that index. The engine emits one event per batch, however many
250
- * documents the batch holds.
251
- *
252
- * The engine emits the event once a query can see the change, which means
253
- * after every worker copy applies the change and after any rebalance in
254
- * progress replays it. A query that a listener sends from its handler
255
- * therefore returns results that include the change. The engine waits for the
256
- * change to become visible only while a listener is registered for the event.
249
+ * This cursor comes from a previous result, and continues where it stopped.
250
+ * The engine ties a cursor to the sort that produced it, and it throws
251
+ * `SEARCH_INVALID_CURSOR` for a cursor sent back under a different sort.
257
252
  */
258
- write: {
259
- /** This is the name of the index that changed. */
260
- indexName: string;
261
- };
253
+ cursor?: string;
254
+ /** The page carries this many documents, and 10 by default. The engine raises a value below one to one. */
255
+ limit?: number;
256
+ /** This narrows the listing to the documents the filter accepts. */
257
+ filters?: FilterExpression;
262
258
  /**
263
- * A worker thread exited unexpectedly. The pool removes the thread and fails
264
- * the requests that the thread was serving with `WORKER_CRASHED`. The engine
265
- * then sends each of those queries again on the main thread, so the caller
266
- * receives a result with no error. The remaining workers keep serving
267
- * queries, because each of them holds a full worker copy of every promoted
268
- * index.
259
+ * This orders the listing by field value rather than by document id, and the
260
+ * engine applies the fields in the order they are listed. Pass an object
261
+ * keyed by field, or a list of fields in the order they apply. It breaks a
262
+ * tie on document id, and it sorts by at most eight fields. The engine uses
263
+ * document-id order when you leave this out.
269
264
  *
270
- * After a delay, the engine spawns a replacement and loads every copy onto
271
- * it before it sends queries to the replacement. Once no worker is left, the
272
- * main thread serves every query, because it holds every document. The first
273
- * request after the delay then starts a new pool. The delay starts at one
274
- * second and doubles up to a minute while replacements keep failing.
265
+ * The engine reads every document the listing covers to build a sorted page,
266
+ * so a sorted listing costs more than the default order on a large index.
275
267
  */
276
- workerCrash: {
277
- /** This is the id of the worker that exited. */
278
- workerId: number;
279
- /** These are the indexes that the worker held. */
280
- indexNames: string[];
281
- /** This is the error that ended the worker. */
282
- error: Error;
283
- };
284
- /** An index gained worker copies, either because it reached the copy
285
- * threshold or because a request loaded its copies again after an idle
286
- * spell. */
287
- workerPromote: {
288
- /** This is the number of workers in the pool. */
289
- workerCount: number;
290
- /** This is the reason that the index gained its copies, such as the copy
291
- * threshold that it reached. */
292
- reason: string;
293
- };
294
- /** An index could not gain worker copies, so the main thread keeps serving
295
- * its queries. */
296
- workerPromoteFailure: {
297
- /** This is the reason that the engine tried to load the copies. */
298
- reason: string;
299
- /** This is the error that stopped the load. */
300
- error: Error;
301
- /** This is true when the engine will try again at a later threshold. */
302
- retryable: boolean;
303
- };
304
- /** An index finished spreading its documents across a new number of
305
- * partitions. */
306
- partitionRebalance: {
307
- /** This is the name of the index that the engine rebalanced. */
308
- indexName: string;
309
- /** This is the number of partitions before the rebalance. */
310
- oldCount: number;
311
- /** This is the number of partitions after the rebalance. */
312
- newCount: number;
313
- };
268
+ sort?: SortSpec;
269
+ /** This chooses how much of each stored document comes back, and the whole document by default. */
270
+ document?: DocumentProjection;
271
+ }
272
+
273
+ /**
274
+ * Which engine answers a query: keyword matching, vector similarity, or both
275
+ * merged into one ranking.
276
+ *
277
+ * @public
278
+ */
279
+ type SearchMode = 'fulltext' | 'vector' | 'hybrid';
280
+ /**
281
+ * How many of a query's terms a document has to carry. `all` demands every
282
+ * term, `any` accepts one, and a number demands that many.
283
+ *
284
+ * @public
285
+ */
286
+ type TermMatchPolicy = 'all' | 'any' | number;
287
+ /**
288
+ * One field of a sort, and the direction that field orders by.
289
+ *
290
+ * @public
291
+ */
292
+ interface SortField {
293
+ /** The field the engine reads, which may name a nested field with dots. */
294
+ field: string;
295
+ /** Ascending or descending order for this field. */
296
+ direction: 'asc' | 'desc';
314
297
  /**
315
- * An index passed its watermark, so its partitions are close to their
316
- * capacity. On a cluster node, the engine reports the document count and the
317
- * capacity of the one partition that `partitionId` identifies, which this
318
- * node leads.
319
- */
320
- partitionWatermark: {
321
- /** This is the name of the index that crossed the mark. */
322
- indexName: string;
323
- /** This is the number of documents in the index, or in the partition on a
324
- * cluster node. */
325
- documentCount: number;
326
- /** This is the number of documents that the current partitions of the
327
- * index can hold, or that the partition can hold on a cluster node. */
328
- capacity: number;
329
- /** This is the number of partitions in the index. */
330
- partitionCount: number;
331
- /** On a cluster node, this is the partition that crossed the mark, while
332
- * outside a cluster the field is absent. */
333
- partitionId?: number;
334
- };
335
- /**
336
- * The process uses nine tenths of its heap, as measured during a write or a
337
- * load, so the next large index can end the process with an out-of-memory
338
- * error.
339
- *
340
- * Where `--max-old-space-size` or `--max-old-space-size-percentage` sets a
341
- * limit, on the command line or in `NODE_OPTIONS`, the engine measures the
342
- * used bytes against that limit, which `heapLimit` then reports. Where
343
- * neither flag sets a limit, the engine measures the share of the heap that
344
- * V8 reports as no longer available. V8 reports a limit about 192 MB above
345
- * the true ceiling, so a process on a default heap below about 2 GB can end before
346
- * this event fires.
347
- *
348
- * The engine emits the event once per crossing, then arms it again once the
349
- * free share of the heap recovers to two tenths. Raise the limit with
350
- * `--max-old-space-size-percentage` or `--max-old-space-size`, or close an
351
- * idle index; see {@link ProcessMemoryReport.heapLimit}.
298
+ * Where a document's field holds a list, the engine sorts that document by
299
+ * one value from the list: the smallest under `'min'`, the largest under
300
+ * `'max'`, and the mean or the median of the list's numbers under `'avg'`
301
+ * or `'median'`. Where you leave this out, the engine uses `'min'` for an
302
+ * ascending sort and `'max'` for a descending one. It sorts by a field that
303
+ * holds a single value as that value stands, under every mode. It throws
304
+ * `SEARCH_INVALID_FIELD` for `'avg'` or `'median'` on a field that the
305
+ * schema declares as anything other than `number` or `number[]`.
352
306
  */
353
- heapPressure: {
354
- /** This is the index that a write or a load was touching when the heap
355
- * reached that point. */
356
- indexName: string;
357
- /** This is the heap that the process uses, in bytes. */
358
- heapUsed: number;
359
- /** This is the size in bytes that the heap can grow to. */
360
- heapLimit: number;
361
- /** This is the estimate of the bytes that the index holds. */
362
- estimatedMemoryBytes: number;
363
- };
364
- /** The engine started, completed, or failed a rebuild that brings the terms
365
- * of an index up to the current analysis of its language module. */
366
- analysisRebuild: {
367
- /** This is the name of the index under rebuild. */
368
- indexName: string;
369
- /** This is the stage that the rebuild has reached. */
370
- status: 'started' | 'completed' | 'failed';
371
- /** This is the number of partitions that the rebuild has covered so far. */
372
- partitionsRebuilt: number;
373
- /** This is the number of partitions that the rebuild covers in total. */
374
- partitionCount: number;
375
- /** This is the error that stopped the rebuild, which only a `failed`
376
- * status includes. */
377
- error?: Error;
378
- };
379
- /** The engine started, completed, or failed the rewrite of an index that you
380
- * saved with an earlier release. The engine rewrites the index as it
381
- * recovers it, before it serves the index's first request. Because the
382
- * engine writes the new manifest last, the earlier files stay intact through
383
- * a failed rewrite. The engine then starts the rewrite again the next time
384
- * it recovers the index. Without index lifecycle settings, the engine
385
- * recovers every index before {@link createNarsil} returns, so pass the
386
- * listener in the `events` setting of {@link createNarsil}. */
387
- layoutUpgrade: {
388
- /** This is the name of the index under rewrite. */
389
- indexName: string;
390
- /** This is the stage that the rewrite has reached. */
391
- status: 'started' | 'completed' | 'failed';
392
- /** This is `manifest` where the earlier index is a segment manifest with
393
- * its files, and `bundle` where it is a single snapshot bundle. */
394
- layout: 'manifest' | 'bundle';
395
- /** This is the error that stopped the rewrite, which only a `failed`
396
- * status includes. */
397
- error?: Error;
398
- };
399
- /** A write to the write-ahead log or a checkpoint failed, so the writes since
400
- * the last checkpoint are at risk. */
401
- durabilityError: {
402
- /** This is the error that the durability layer threw. */
403
- error: Error;
404
- };
405
- /** The invalidation channel failed, so this instance can serve partitions
406
- * that another instance has since changed. */
407
- invalidationError: {
408
- /** This is the error that the adapter threw. */
409
- error: Error;
410
- };
411
- };
307
+ mode?: 'min' | 'max' | 'avg' | 'median';
308
+ }
412
309
  /**
413
- * This map holds a listener for any event of {@link NarsilEventMap}, so that
414
- * the engine can register each listener before it starts.
310
+ * A sort, either as an object keyed by field or as a list of fields in the
311
+ * order they apply.
312
+ *
313
+ * Both forms order by the first field, break a tie on the second, and carry on
314
+ * that way. Prefer the list where the order of the fields matters, because
315
+ * JavaScript moves an all-digit key such as `2024` to the front of an object
316
+ * and the list keeps the order you wrote.
415
317
  *
416
318
  * @public
417
319
  */
418
- type NarsilEventHandlers = {
419
- [K in keyof NarsilEventMap]?: (payload: NarsilEventMap[K]) => void;
420
- };
421
-
320
+ type SortSpec = Record<string, 'asc' | 'desc'> | readonly SortField[];
422
321
  /**
423
- * What {@link Narsil.query} returns: the ranked hits and everything the query
424
- * asked for alongside them.
322
+ * Everything {@link Narsil.query} accepts.
425
323
  *
426
- * @typeParam T - Shape of the stored documents, which flows through to each
427
- * hit's `document`.
324
+ * Set `term` for keyword search, `vector` for similarity search, and `mode`
325
+ * when you want both. The engine matches nothing for a query carrying neither
326
+ * of them, so page through an index with {@link Narsil.listDocuments}
327
+ * instead.
428
328
  *
429
329
  * @public
430
330
  */
431
- interface QueryResult<T = AnyDocument> {
432
- /** These documents match, cut to the query's `limit`, best score first or in the query's sort order. */
433
- hits: Array<Hit<T>>;
331
+ interface QueryParams {
332
+ /** The engine analyses this text with the index's language module and searches for the terms that result. */
333
+ term?: string;
334
+ /** The engine searches the term in these fields, and in every text field in the schema by default. */
335
+ fields?: string[];
434
336
  /**
435
- * This many documents match in total, before the engine applies `limit`
436
- * and `offset`. For a keyword search the engine counts every match. For a
437
- * vector search it counts every vector that passes the query's filter and
438
- * its `similarity` floor, which is every vector in the field where the query
439
- * sets neither of them. The engine also counts each pinned document that
440
- * the query does not match, since it places that document among the hits.
337
+ * The engine scores only the documents that pass this filter. It throws
338
+ * `SEARCH_INVALID_FILTER` for an operand of the wrong shape, and for an
339
+ * operator on a field of another type, such as `startsWith` on a number
340
+ * field.
441
341
  */
442
- count: number;
342
+ filters?: FilterExpression;
443
343
  /**
444
- * `count` holds the exact number of matches where this is true, and a
445
- * number at or below the true total where it is false. Where a query sets a
446
- * `similarity` floor on a vector field that holds a graph, the engine
447
- * counts only the vectors that it fetches, because it compares the query
448
- * with only a fraction of that field's vectors. For a hybrid query the
449
- * engine fuses two rankings, so the count is exact only where each of those
450
- * rankings contains every matching document. Where you pin a document from
451
- * outside the hits that the engine fetches, the engine reports true only
452
- * where it holds every match of the query, because only then can it test
453
- * whether the query matches that document.
344
+ * The engine multiplies the score from each named field by its weight. It
345
+ * throws `SEARCH_INVALID_FIELD` for any field other than a text field that
346
+ * the schema declares, and `CONFIG_INVALID` for a weight that is not a
347
+ * finite number.
454
348
  */
455
- countExact: boolean;
456
- /** The engine spent this many milliseconds on the search. */
457
- elapsed: number;
458
- /** This opaque cursor reaches the next page. Pass it back as `searchAfter`. */
459
- cursor?: string;
460
- /** These facet counts are keyed by the field each facet was asked for. */
461
- facets?: Record<string, FacetResult>;
462
- /** These groups arrive when the query asked for grouping. */
463
- groups?: GroupResult[];
464
- /** This turns true when the index's terms came from an older analysis than its language module produces now. */
465
- analysisStale?: boolean;
466
- /** The search read this much of the index, which is how you spot a degraded answer. */
467
- coverage: QueryCoverage;
349
+ boost?: Record<string, number>;
350
+ /** The engine gathers term statistics this way, and follows the index's `defaultScoring` where the query sets none. */
351
+ scoring?: ScoringMode;
352
+ /**
353
+ * The engine drops any hit scoring below this value. It ranks with BM25,
354
+ * which has no fixed upper bound, so a floor that suits one index and one
355
+ * query can reject every hit in another.
356
+ */
357
+ minScore?: number;
358
+ /**
359
+ * The engine keeps a document only where the document matches this many
360
+ * query terms, under the same `tolerance` and `prefixLength` that the search
361
+ * uses. One term is enough by default.
362
+ */
363
+ termMatch?: TermMatchPolicy;
364
+ /**
365
+ * The engine matches an indexed term within this edit distance of a query
366
+ * term, so it finds a document for a query with a typo. It counts each
367
+ * Unicode code point as one character. Set an integer from 0 to 10.
368
+ */
369
+ tolerance?: number;
370
+ /**
371
+ * The engine applies `tolerance` only to the indexed terms that share this
372
+ * many leading characters with the query term, or to the terms that start
373
+ * with the whole query term when the query term is shorter. Set an integer
374
+ * from 0 to 1,024; the default is 2.
375
+ */
376
+ prefixLength?: number;
377
+ /**
378
+ * With this set, the engine treats the last query term as an unfinished
379
+ * word, so `secur` matches `security`. The engine matches that last term by
380
+ * its stem or by completing it, while `tolerance` applies only to the earlier
381
+ * terms, which have to match whole. The engine scores completions against a
382
+ * shared document frequency. It also ranks them below whole-word matches.
383
+ * The engine ignores this setting where `exact` is true, and the setting is
384
+ * false by default.
385
+ */
386
+ prefix?: boolean;
387
+ /**
388
+ * With this set, the engine also matches each query word of three or more
389
+ * characters inside the longer words of every field whose type includes
390
+ * `partial`, so a search for `proof` matches a document with `waterproof`
391
+ * in such a field. The engine counts each Unicode code point as one
392
+ * character. It looks for the query word, before stemming, inside each word
393
+ * exactly as that word appears in a document.
394
+ *
395
+ * The engine adds at most 50 such words to a query, which it divides as
396
+ * evenly as it can among the query words. Within the share of each query
397
+ * word, it adds first the words that the most documents contain. It scores
398
+ * a match inside a longer word in proportion to the part of that word that
399
+ * the query word makes up, so it scores such a match below a whole-word
400
+ * match at the same frequency in a field of the same length. With
401
+ * `highlight`, it tags each whole word that contains a query word in a
402
+ * searched `partial` field.
403
+ *
404
+ * The engine applies no `tolerance` to these matches. It ignores this
405
+ * setting where `exact` is true or where the searched fields include no
406
+ * `partial` field. Where the setting is absent, the engine treats it as
407
+ * false, while it throws `CONFIG_INVALID` for any value other than `true`
408
+ * or `false`.
409
+ */
410
+ partialWords?: boolean;
411
+ /**
412
+ * With this set, the engine matches each query term only against an equal
413
+ * indexed term, so it turns off fuzzy matching, prefix completion, and
414
+ * partial-word matching. The engine still stems the query, because the
415
+ * index stores stemmed terms, so a search for `running` matches a document
416
+ * that contains `runs` through the stem that both words share.
417
+ */
418
+ exact?: boolean;
419
+ /**
420
+ * The engine counts the values of these fields across the matching
421
+ * documents, and each entry sets how it cuts and sorts that field's counts.
422
+ * For a field outside the schema, it counts the values that the documents
423
+ * store. It throws `SEARCH_INVALID_FIELD` for a `geopoint` or a vector
424
+ * field.
425
+ */
426
+ facets?: FacetConfig;
427
+ /**
428
+ * The engine sorts the hits by the values of these fields, in place of the
429
+ * relevance ranking. Pass an object keyed by field, or a list of fields in
430
+ * the order that the engine compares them. The engine sorts by a `number`,
431
+ * `boolean`, or `enum` field, by a text field whose type includes
432
+ * `sortable`, or by a list of any of these, which it reduces to one value by
433
+ * the entry's `mode`. It throws `SEARCH_INVALID_FIELD` for a sort on a
434
+ * `geopoint` or a vector field, because neither type has an order. It throws
435
+ * the same code for a sort on any other text field, since the engine keeps
436
+ * up to the first 512 code points of every document's value in memory to
437
+ * sort by a text field. The engine orders hybrid results by fusion, so it
438
+ * throws `SEARCH_INVALID_MODE` for a sort on a hybrid query. It also throws
439
+ * that code for a direction other than `asc` and `desc`.
440
+ */
441
+ sort?: SortSpec;
442
+ /** These settings collapse the hits into groups by field value. */
443
+ group?: GroupConfig;
444
+ /**
445
+ * The query returns this many hits, and 10 by default. Pass 0 to read the
446
+ * match count with no hits. The engine reads a value below 0 as 0. It falls
447
+ * back to the default for `NaN` and for an infinite value, so a page size
448
+ * that you compute from user input never fails the query.
449
+ */
450
+ limit?: number;
451
+ /** The query skips this many hits before returning. A deep offset costs more than a cursor. */
452
+ offset?: number;
453
+ /** This cursor comes from a previous result's `cursor`, and pages without an offset's cost. */
454
+ searchAfter?: string;
455
+ /** These settings name the fields that come back with highlighted snippets. */
456
+ highlight?: HighlightConfig;
457
+ /** These documents take fixed positions, ahead of the ranking. */
458
+ pinned?: Array<{
459
+ docId: string;
460
+ position: number;
461
+ }>;
462
+ /** This picks which engine answers the query. Keyword search runs by default. */
463
+ mode?: SearchMode;
464
+ /** These vector-search inputs are required in `vector` and `hybrid` mode. */
465
+ vector?: VectorQueryConfig;
466
+ /** These settings control how the keyword and vector rankings merge in `hybrid` mode. */
467
+ hybrid?: HybridConfig;
468
+ /**
469
+ * Setting this returns relevance scores on a sorted query. A query that
470
+ * names a sort ranks by sort values alone and computes no scores, so its
471
+ * hits carry none until this restores them. A query without a sort ignores
472
+ * this and always carries scores.
473
+ */
474
+ includeScores?: boolean;
475
+ /** Setting this returns the numbers behind each hit's score, which is what you read when a ranking surprises you. */
476
+ includeScoreComponents?: boolean;
477
+ /** This chooses how much of each stored document comes back, and the whole document by default. */
478
+ document?: DocumentProjection;
468
479
  }
469
480
  /**
470
- * How much of an index one search read, which is what you check before you
471
- * trust a count or a ranking.
472
- *
473
- * An embedded engine reads every partition it holds, so `queriedPartitions`
474
- * matches `totalPartitions` there and the other two stay zero. A search across
475
- * a cluster may find a node slow or unreachable, which it counts here while
476
- * still returning the hits the other nodes gave it.
481
+ * How much of a stored document each hit carries back.
477
482
  *
478
- * @public
479
- */
480
- interface QueryCoverage {
481
- /** The search should have read this many partitions. */
482
- totalPartitions: number;
483
- /** The search read this many of them. */
484
- queriedPartitions: number;
485
- /** The search counts a partition here when the node holding it took longer than the query allowed. */
486
- timedOutPartitions: number;
487
- /** The search counts a partition here when the node holding it returned an error, and when no active replica served it. */
488
- failedPartitions: number;
489
- }
490
- /**
491
- * One matching document, with the score that ranked it.
483
+ * Pass `false` when the ids and scores are all you need, and every hit's
484
+ * `document` is then an empty object. Pass `include` to keep named fields
485
+ * alone, or `exclude` to drop named fields and keep the rest; naming both
486
+ * keeps the included fields and then drops the excluded ones from those. Use
487
+ * dots to name a nested field, so `author.name` addresses the `name` inside
488
+ * `author`, and a name that matches no field changes nothing.
492
489
  *
493
- * @typeParam T - Shape of the stored document.
490
+ * Drop a vector field on a similarity search, because the engine otherwise
491
+ * reads every hit's vector back out of the index and writes it into the
492
+ * response.
494
493
  *
495
494
  * @public
496
495
  */
497
- interface Hit<T = AnyDocument> {
498
- /** The document is stored under this id. */
499
- id: string;
500
- /**
501
- * This score ranked the hit. Scores compare within one result set, never
502
- * across searches. A sorted query ranks by sort values instead and carries
503
- * no score unless it sets `includeScores`.
504
- */
505
- score?: number;
506
- /** This is the stored document. */
507
- document: T;
508
- /** These are the parts the score was built from, which arrive when the query asked for them. */
509
- scoreComponents?: ScoreComponents;
510
- /** These highlighted snippets are keyed by field, and arrive when the query asked for highlighting. */
511
- highlights?: Record<string, HighlightMatch>;
512
- }
496
+ type DocumentProjection = boolean | {
497
+ /** Names the fields to keep, so every field left out of this list is dropped. */
498
+ include?: string[];
499
+ /** Names the fields to drop, so every other field is kept. */
500
+ exclude?: string[];
501
+ };
513
502
  /**
514
- * The numbers BM25 combined into one hit's score, which is what you read when
515
- * a ranking surprises you.
503
+ * Vector-search inputs passed under `QueryParams.vector`.
504
+ *
505
+ * Supply either a raw `value` array or a `text` string for auto-embedding;
506
+ * passing both throws `EMBEDDING_CONFIG_INVALID`. Result count is governed
507
+ * by the outer query's `limit`, not by any field on this object.
516
508
  *
517
509
  * @public
518
510
  */
519
- interface ScoreComponents {
511
+ interface VectorQueryConfig {
520
512
  /**
521
- * Each query term appears in one field of this document this many times,
522
- * under a key of `field:term`. A term that appears in two fields therefore
523
- * has two entries here, while the keys of {@link ScoreComponents.idf} hold
524
- * the bare term.
513
+ * Name of the schema field that holds the vector to compare against.
514
+ * Must reference a field declared as `vector[N]` in the index schema.
525
515
  */
526
- termFrequencies: Record<string, number>;
527
- /** Each field the query searched holds this many tokens, keyed by field. */
528
- fieldLengths: Record<string, number>;
529
- /** Each query term carries this inverse document frequency, which is what makes a rare term count for more. */
530
- idf: Record<string, number>;
531
- }
532
- /**
533
- * A highlighted field, ready to render.
534
- *
535
- * @public
536
- */
537
- interface HighlightMatch {
538
- /** This is the field's text around the match, wrapped in the query's tags. */
539
- snippet: string;
516
+ field: string;
540
517
  /**
541
- * Each range gives the start and the end of one match in the original field,
542
- * so you can render the highlight yourself. Where the snippet covers part of
543
- * the field alone, the engine lists only the matches that the snippet
544
- * displays. Every offset is a character count from the start of the original
545
- * field, whatever the snippet contains.
518
+ * Raw query vector, given as a number array or a `Float32Array`. Length
519
+ * must match the indexed field's dimension or the search rejects the
520
+ * request with `VECTOR_DIMENSION_MISMATCH`.
546
521
  */
547
- positions: Array<{
548
- start: number;
549
- end: number;
550
- }>;
551
- }
552
- /**
553
- * Counts for one faceted field.
554
- *
555
- * @public
556
- */
557
- interface FacetResult {
558
- /** This many documents match per value, keyed by value. */
559
- values: Record<string, number>;
560
- /** This is the number of entries in `values`, which is at most the facet's `limit`. */
561
- count: number;
522
+ value?: number[] | Float32Array;
562
523
  /**
563
- * Every count in `values` is at most this far below its true count. A value
564
- * that the engine leaves out of `values` because of `limit` has a true
565
- * count of at most this figure too. Where the engine counts a field on one
566
- * thread, it counts every value exactly, so this figure is the largest
567
- * count that it leaves out. Where it splits the count across worker copies
568
- * or cluster nodes, each of them returns only its own top values, so the
569
- * merged count of a value that is common overall but rare on one of them
570
- * can lack the matches on that one. A bound of 0 means that `values` holds
571
- * every matching value, each with its exact count.
524
+ * Text to embed at query time using the index or instance embedding
525
+ * adapter. Mutually exclusive with `value`; requires a configured adapter.
572
526
  */
573
- errorBound: number;
574
- }
575
- /**
576
- * One group of hits, produced by a query that grouped its results.
577
- *
578
- * @public
579
- */
580
- interface GroupResult {
581
- /** Each grouping field holds this value for the group, keyed by field. */
582
- values: Record<string, unknown>;
583
- /** These hits fall in the group, cut to the query's `maxPerGroup`. */
584
- hits: Array<Hit>;
585
- /** The query's reducer produced this value for the group, and only a query that set `group.reduce` carries it. */
586
- reduced?: unknown;
587
- /** The reducer threw, and this holds its message, so the group carries its hits and no `reduced` value. */
588
- reducerError?: string;
527
+ text?: string;
528
+ /**
529
+ * Score floor applied during ranking. Hits scoring below this value
530
+ * are dropped before `limit` is enforced, so the returned hit count
531
+ * can be smaller than `limit` even when more documents exist. The
532
+ * floor is interpreted in score space for every metric; for
533
+ * `euclidean`, distance is mapped to a similarity score of
534
+ * `1 / (1 + distance)` first. Defaults to no floor.
535
+ */
536
+ similarity?: number;
537
+ /**
538
+ * Similarity metric used for ranking. Defaults to `cosine`. Choose
539
+ * `dotProduct` for raw inner-product scoring on already-normalised
540
+ * vectors and `euclidean` for distance-based ordering.
541
+ */
542
+ metric?: 'cosine' | 'dotProduct' | 'euclidean';
543
+ /**
544
+ * HNSW exploration factor for approximate search. Higher values raise
545
+ * recall at the cost of latency. Ignored while the field is still
546
+ * served by the brute-force backend. Defaults to the engine's built-in
547
+ * value when omitted.
548
+ */
549
+ efSearch?: number;
550
+ /**
551
+ * How many times `limit` a quantized field re-scores against its
552
+ * full-precision vectors before it returns the best `limit`. A value below
553
+ * 1 or one that is not a finite number fails with `CONFIG_INVALID`. The
554
+ * engine ignores this on a field whose quantization is `none`. When a query
555
+ * omits it, the engine takes 3 for `osq1` and `osq2`, 2 for `osq8`, and 2
556
+ * for `osq4` at 1,024 dimensions and above, but 5 for `osq4` below 1,024,
557
+ * where a four-bit code ranks the true neighbours less reliably.
558
+ */
559
+ oversample?: number;
589
560
  }
590
561
  /**
591
- * What {@link Narsil.preflight} returns: how many documents a query matches,
592
- * without building or ranking a single hit.
562
+ * How a hybrid query merges its keyword ranking with its vector ranking.
593
563
  *
594
- * @public
595
- */
596
- interface PreflightResult {
597
- /** The query matches this many documents. */
598
- count: number;
599
- /** `count` holds the exact number of matches where this is true, and a number at or below the true total where it is false, under the rule in {@link QueryResult.countExact}. */
600
- countExact: boolean;
601
- /** The count took this many milliseconds. */
602
- elapsed: number;
603
- /** This turns true when the index's terms came from an older analysis than its language module produces now. */
604
- analysisStale?: boolean;
605
- }
606
- /**
607
- * What a batch write returns. One bad document never abandons the rest, so
608
- * read both lists.
564
+ * `rrf` combines the two by rank alone, which needs no tuning and handles
565
+ * scores that live on different scales. `linear` blends the scores directly,
566
+ * which gives you control once you know what each side's scores look like.
609
567
  *
610
568
  * @public
611
569
  */
612
- interface BatchResult {
613
- /** The engine wrote the documents under these ids. */
614
- succeeded: string[];
615
- /** The engine rejected each of these documents, and each entry carries the error that rejected it. */
616
- failed: Array<{
617
- docId: string;
618
- error: NarsilError;
619
- }>;
570
+ interface HybridConfig {
571
+ /** The engine merges the rankings this way, and by rank fusion by default. It throws `CONFIG_INVALID` for any other value. */
572
+ strategy?: 'rrf' | 'linear';
573
+ /** The engine uses this rank-fusion constant under `rrf` alone, where a larger value reduces the lead of the top ranks. Set a whole number of at least 1, or leave it out for 60. The engine throws `CONFIG_INVALID` for any other value. */
574
+ k?: number;
575
+ /** The engine uses this weight of the vector score, from 0 to 1, under `linear` alone, and 0.5 where you leave it out. It throws `CONFIG_INVALID` for a value outside that range. */
576
+ alpha?: number;
620
577
  }
621
578
  /**
622
- * What {@link Narsil.importDocumentExport} returns. The engine continues past each
623
- * refused line, so read the refusals to learn which documents it skipped.
579
+ * Fields a query counts values for, keyed by field name.
624
580
  *
625
581
  * @public
626
582
  */
627
- interface DocumentImportResult {
628
- /** The engine wrote this many documents, counting each one that it replaced. */
629
- imported: number;
630
- /** The engine refused this many lines in total. */
631
- refusedCount: number;
632
- /** These are the 1,000 refusals with the lowest line numbers. Each entry contains the line number, where the header is line 1, along with the error code and a message. */
633
- refused: Array<{
634
- line: number;
635
- code: NarsilErrorCode;
636
- message: string;
637
- }>;
583
+ interface FacetConfig {
584
+ /** Each key names a field the query counts values for. */
585
+ [field: string]: {
586
+ /** The engine returns this many values for the field, in the order of `sort`. An engine returns every value where you leave this out, while a cluster returns 10, or every range of a field that sets `ranges`. */
587
+ limit?: number;
588
+ /** The engine orders the returned values by their count, putting the highest first under `'desc'`, which is the default, and the lowest first under `'asc'`. Under `'asc'`, each cluster node sends the count of up to 10,000 values of the field, so the lowest counts are exact wherever no node holds more values than that. */
589
+ sort?: 'asc' | 'desc';
590
+ /** The engine counts a numeric field's matches into these ranges, with one count for each range. A cluster search counts up to 1,000 ranges on a field and throws `CONFIG_INVALID` for more. */
591
+ ranges?: Array<{
592
+ from: number;
593
+ to: number;
594
+ }>;
595
+ };
638
596
  }
639
597
  /**
640
- * What {@link Narsil.getStats} returns about one index.
598
+ * How a query collapses its hits into groups.
641
599
  *
642
600
  * @public
643
601
  */
644
- interface IndexStats {
645
- /** The index holds this many documents. A closed index reports its count as of the last checkpoint. */
646
- documentCount: number;
647
- /** The index is spread across this many partitions. */
648
- partitionCount: number;
602
+ interface GroupConfig {
603
+ /** The values of these fields define a group, and several fields group by their combination. */
604
+ fields: string[];
605
+ /** The engine returns this many hits from each group, best first, and one hit where you leave this out. */
606
+ maxPerGroup?: number;
607
+ /** The engine returns this many groups, best first, and every group where you leave this out. */
608
+ limit?: number;
649
609
  /**
650
- * Formula-based estimate of the index's main-thread memory footprint, summed
651
- * across every partition and vector index for this index. Computed from
652
- * structural counters (document count, posting counts, field-index sizes),
653
- * not measured. Per-object V8 overhead (hidden classes, map transitions,
654
- * GC headers) is not captured here, so this number routinely undershoots
655
- * the real heap by a meaningful factor. Use {@link Narsil.getMemoryStats}
656
- * when sizing host memory.
657
- */
658
- estimatedMemoryBytes: number;
659
- /** The index analyses text with this language module. */
660
- language: string;
661
- /** The index was created with this field layout. */
662
- schema: SchemaDefinition;
663
- }
664
- /**
665
- * A summary of one index, as {@link Narsil.listIndexes} reports it.
666
- *
667
- * @public
668
- */
669
- interface IndexInfo {
670
- /** The index was created under this name. */
671
- name: string;
672
- /** The index holds this many documents. A closed index reports its count as of the last checkpoint. */
673
- documentCount: number;
674
- /** The index is spread across this many partitions. */
675
- partitionCount: number;
676
- /** The index analyses text with this language module. */
677
- language: string;
678
- /** This turns true when the index's terms came from an older analysis than its language module produces now. */
679
- analysisStale?: boolean;
680
- /** This is `open` in memory, `closed` after release, and `reopen-failed` after five recovery failures. */
681
- state: 'open' | 'closed' | 'reopen-failed';
682
- /** This counts successful loads since this engine started. */
683
- reopenCount: number;
610
+ * The engine folds every hit of each group into one value, such as a sum or
611
+ * an average, including the hits beyond `maxPerGroup`. In cluster mode the
612
+ * coordinator fetches up to 10,000 hits of each group to fold.
613
+ */
614
+ reduce?: GroupReducer;
684
615
  }
685
616
  /**
686
- * What {@link Narsil.getPartitionStats} reports for one partition, which is
687
- * where you look when an index grows unevenly.
617
+ * Folds the hits of one group into a single value.
688
618
  *
689
619
  * @public
690
620
  */
691
- interface PartitionStatsResult {
692
- /** This identifies the partition within its index. */
693
- partitionId: number;
694
- /** The partition holds this many documents. */
695
- documentCount: number;
621
+ type GroupReducer = {
696
622
  /**
697
- * Formula-based estimate of this partition's memory footprint. V8 has no
698
- * per-object heap accounting API, so this number is derived from structural
699
- * counters (document count, posting counts, field-index sizes) and does not
700
- * include per-object overhead. Treat as an estimate, not a measurement.
623
+ * Folds one hit into the running value.
624
+ *
625
+ * @param accumulator - What the previous call returned, or what
626
+ * `initialValue` produced for the first hit.
627
+ * @param doc - The hit's stored document.
628
+ * @param score - The hit's relevance score.
629
+ * @returns The new running value.
701
630
  */
702
- estimatedMemoryBytes: number;
703
- }
631
+ reducer: (accumulator: unknown, doc: AnyDocument, score: number) => unknown;
632
+ /** Produces the starting value for each group. The engine calls it once per group. */
633
+ initialValue: () => unknown;
634
+ };
704
635
  /**
705
- * What {@link Narsil.suggest} returns: the indexed terms that complete a
706
- * prefix, ready to offer as you-type suggestions.
636
+ * This configuration names the fields that receive highlighted snippets. It
637
+ * also sets how the engine marks those snippets up.
638
+ *
639
+ * The engine analyses the text of each returned field again to tag every word
640
+ * that it matched, so it tags the same words whatever the index's
641
+ * `trackPositions` setting is. It tags a word whose stem equals a query stem,
642
+ * and a word within the query's `tolerance` of a query stem. For a `prefix`
643
+ * query, it tags a word for the last query term only when that word completes
644
+ * the term or shares its stem.
707
645
  *
708
646
  * @public
709
647
  */
710
- interface SuggestResult {
711
- /** These completions run most widely used first. */
712
- terms: Array<{
713
- /** This is the completed term, as the index holds it. */
714
- term: string;
715
- /** The term appears in this many documents, which is what ordered the list. */
716
- documentFrequency: number;
717
- }>;
718
- /** The lookup took this many milliseconds. */
719
- elapsed: number;
720
- /** This turns true when the index's terms came from an older analysis than its language module produces now. */
721
- analysisStale?: boolean;
648
+ interface HighlightConfig {
649
+ /** The engine highlights these fields. */
650
+ fields: string[];
651
+ /** The engine writes this before each match, and writes `<mark>` by default. */
652
+ preTag?: string;
653
+ /** The engine writes this after each match, and writes `</mark>` by default. */
654
+ postTag?: string;
655
+ /**
656
+ * The engine takes this many characters of the field around the densest run
657
+ * of matches, 200 by default. It returns a snippet longer than that number,
658
+ * because it then adds the opening and closing tags, and an ellipsis at each
659
+ * end where it cuts the field.
660
+ */
661
+ maxSnippetLength?: number;
722
662
  }
663
+
723
664
  /**
724
- * The state of one vector field, and what maintenance would cost, as
725
- * {@link Narsil.vectorMaintenanceStatus} reports it.
665
+ * Every code a {@link NarsilError} carries, grouped by the part of the engine
666
+ * that raises it.
726
667
  *
727
- * Removing a vector leaves a tombstone in the graph, and enough of them slow a
728
- * search down. Read this to decide when compaction earns its cost.
668
+ * Match on the code rather than on the message, because a code is stable and a
669
+ * message is not. The HTTP server maps each code to a status, so a code also
670
+ * tells you whether the caller or the engine is at fault.
729
671
  *
730
672
  * @public
731
673
  */
732
- interface VectorMaintenanceResult {
733
- /** This describes the named vector field. */
734
- fieldName: string;
735
- /**
736
- * Tombstones make up this share of the graph's nodes, from 0 to 1. Before
737
- * the first build, where {@link VectorMaintenanceResult.graphCount} reads 0,
738
- * the engine divides by the number of stored vectors, because no graph
739
- * exists yet.
740
- */
741
- tombstoneRatio: number;
742
- /** The field holds this many HNSW graphs: 0 before the first build and 1 once a graph exists. */
743
- graphCount: number;
744
- /** This many vectors wait outside the graph, which a search scans one by one. */
745
- bufferSize: number;
746
- /** This stays true while a graph build runs. */
747
- building: boolean;
748
- /** {@link Narsil.compactVectors} would take about this many milliseconds. */
749
- estimatedCompactMs: number;
750
- /** {@link Narsil.optimizeVectors} would take about this many milliseconds. */
751
- estimatedOptimizeMs: number;
752
- }
674
+ declare const ErrorCodes: {
675
+ readonly SCHEMA_INVALID_TYPE: "SCHEMA_INVALID_TYPE";
676
+ readonly SCHEMA_DEPTH_EXCEEDED: "SCHEMA_DEPTH_EXCEEDED";
677
+ readonly SCHEMA_INVALID_VECTOR_DIMENSION: "SCHEMA_INVALID_VECTOR_DIMENSION";
678
+ readonly SCHEMA_INVALID_GEOPOINT: "SCHEMA_INVALID_GEOPOINT";
679
+ readonly DOC_NOT_FOUND: "DOC_NOT_FOUND";
680
+ readonly DOC_ALREADY_EXISTS: "DOC_ALREADY_EXISTS";
681
+ readonly DOC_VALIDATION_FAILED: "DOC_VALIDATION_FAILED";
682
+ readonly INDEX_NOT_FOUND: "INDEX_NOT_FOUND";
683
+ readonly INDEX_ALREADY_EXISTS: "INDEX_ALREADY_EXISTS";
684
+ readonly INDEX_ORPHANED: "INDEX_ORPHANED";
685
+ readonly INDEX_REOPEN_CAPACITY_EXHAUSTED: "INDEX_REOPEN_CAPACITY_EXHAUSTED";
686
+ readonly INSTANCE_SHUT_DOWN: "INSTANCE_SHUT_DOWN";
687
+ readonly PARTITION_CORRUPTED: "PARTITION_CORRUPTED";
688
+ readonly PARTITION_REBALANCING_BACKPRESSURE: "PARTITION_REBALANCING_BACKPRESSURE";
689
+ readonly WORKER_CRASHED: "WORKER_CRASHED";
690
+ readonly WORKER_BUSY: "WORKER_BUSY";
691
+ readonly WORKER_TIMEOUT: "WORKER_TIMEOUT";
692
+ readonly WORKER_ACTION_FAILED: "WORKER_ACTION_FAILED";
693
+ readonly PERSISTENCE_SAVE_FAILED: "PERSISTENCE_SAVE_FAILED";
694
+ readonly PERSISTENCE_LOAD_FAILED: "PERSISTENCE_LOAD_FAILED";
695
+ readonly PERSISTENCE_DELETE_FAILED: "PERSISTENCE_DELETE_FAILED";
696
+ readonly PERSISTENCE_CRC_MISMATCH: "PERSISTENCE_CRC_MISMATCH";
697
+ readonly PERSISTENCE_WAL_CORRUPT: "PERSISTENCE_WAL_CORRUPT";
698
+ readonly PERSISTENCE_FSYNC_FAILED: "PERSISTENCE_FSYNC_FAILED";
699
+ readonly SEARCH_INVALID_FIELD: "SEARCH_INVALID_FIELD";
700
+ readonly VECTOR_DIMENSION_MISMATCH: "VECTOR_DIMENSION_MISMATCH";
701
+ readonly SEARCH_INVALID_FILTER: "SEARCH_INVALID_FILTER";
702
+ readonly SEARCH_INVALID_MODE: "SEARCH_INVALID_MODE";
703
+ readonly SEARCH_INVALID_CURSOR: "SEARCH_INVALID_CURSOR";
704
+ readonly SEARCH_RESULT_WINDOW_EXCEEDED: "SEARCH_RESULT_WINDOW_EXCEEDED";
705
+ readonly SEARCH_WORK_CAP_EXCEEDED: "SEARCH_WORK_CAP_EXCEEDED";
706
+ readonly LANGUAGE_NOT_SUPPORTED: "LANGUAGE_NOT_SUPPORTED";
707
+ readonly ENVELOPE_VERSION_MISMATCH: "ENVELOPE_VERSION_MISMATCH";
708
+ readonly ENVELOPE_INVALID_MAGIC: "ENVELOPE_INVALID_MAGIC";
709
+ readonly PARTITION_CAPACITY_EXCEEDED: "PARTITION_CAPACITY_EXCEEDED";
710
+ readonly EMBEDDING_FAILED: "EMBEDDING_FAILED";
711
+ readonly EMBEDDING_DIMENSION_MISMATCH: "EMBEDDING_DIMENSION_MISMATCH";
712
+ readonly EMBEDDING_NO_SOURCE: "EMBEDDING_NO_SOURCE";
713
+ readonly EMBEDDING_CONFIG_INVALID: "EMBEDDING_CONFIG_INVALID";
714
+ readonly DOC_MISSING_REQUIRED_FIELD: "DOC_MISSING_REQUIRED_FIELD";
715
+ readonly CONFIG_INVALID: "CONFIG_INVALID";
716
+ readonly QUERY_ROUTING_FAILED: "QUERY_ROUTING_FAILED";
717
+ readonly QUERY_PARTIAL_FAILURE: "QUERY_PARTIAL_FAILURE";
718
+ readonly QUERY_NODE_TIMEOUT: "QUERY_NODE_TIMEOUT";
719
+ readonly QUERY_NO_ACTIVE_REPLICA: "QUERY_NO_ACTIVE_REPLICA";
720
+ readonly CLUSTER_OPERATION_UNSUPPORTED: "CLUSTER_OPERATION_UNSUPPORTED";
721
+ readonly ALLOCATION_NO_DATA_NODES: "ALLOCATION_NO_DATA_NODES";
722
+ readonly ALLOCATION_INVALID_CONFIG: "ALLOCATION_INVALID_CONFIG";
723
+ readonly ALLOCATION_FAILED: "ALLOCATION_FAILED";
724
+ readonly CONTROLLER_METADATA_INVALID: "CONTROLLER_METADATA_INVALID";
725
+ readonly NODE_BOOTSTRAP_FAILED: "NODE_BOOTSTRAP_FAILED";
726
+ readonly NODE_ALREADY_JOINED: "NODE_ALREADY_JOINED";
727
+ readonly NODE_NOT_JOINED: "NODE_NOT_JOINED";
728
+ readonly NODE_NOT_READY: "NODE_NOT_READY";
729
+ readonly NODE_NOT_CONTROLLER: "NODE_NOT_CONTROLLER";
730
+ readonly COORDINATOR_DEPENDENCY_MISSING: "COORDINATOR_DEPENDENCY_MISSING";
731
+ readonly TRANSPORT_DEPENDENCY_MISSING: "TRANSPORT_DEPENDENCY_MISSING";
732
+ readonly REPLICATION_ENTRY_INVALID: "REPLICATION_ENTRY_INVALID";
733
+ readonly REPLICATION_INSYNC_REMOVAL_FAILED: "REPLICATION_INSYNC_REMOVAL_FAILED";
734
+ readonly REPLICATION_ROLLBACK_FAILED: "REPLICATION_ROLLBACK_FAILED";
735
+ readonly REPLICATION_LOG_FULL: "REPLICATION_LOG_FULL";
736
+ readonly REPLICATION_ENTRY_CORRUPT: "REPLICATION_ENTRY_CORRUPT";
737
+ readonly REPLICATION_SNAPSHOT_CORRUPT: "REPLICATION_SNAPSHOT_CORRUPT";
738
+ readonly REPLICATION_TERM_MISMATCH: "REPLICATION_TERM_MISMATCH";
739
+ readonly REPLICATION_SYNC_FAILED: "REPLICATION_SYNC_FAILED";
740
+ readonly PARTITION_NOT_PRIMARY: "PARTITION_NOT_PRIMARY";
741
+ readonly PARTITION_UNASSIGNED: "PARTITION_UNASSIGNED";
742
+ readonly INSUFFICIENT_REPLICAS: "INSUFFICIENT_REPLICAS";
743
+ readonly SNAPSHOT_SYNC_UNAUTHORIZED: "SNAPSHOT_SYNC_UNAUTHORIZED";
744
+ readonly SNAPSHOT_SYNC_REQUEST_INVALID: "SNAPSHOT_SYNC_REQUEST_INVALID";
745
+ readonly SNAPSHOT_SYNC_INDEX_NOT_FOUND: "SNAPSHOT_SYNC_INDEX_NOT_FOUND";
746
+ readonly SNAPSHOT_SYNC_CAPACITY_EXHAUSTED: "SNAPSHOT_SYNC_CAPACITY_EXHAUSTED";
747
+ readonly SNAPSHOT_SYNC_SNAPSHOT_FAILED: "SNAPSHOT_SYNC_SNAPSHOT_FAILED";
748
+ readonly SNAPSHOT_SYNC_DECODE_FAILED: "SNAPSHOT_SYNC_DECODE_FAILED";
749
+ readonly SNAPSHOT_SYNC_FRAME_INVALID: "SNAPSHOT_SYNC_FRAME_INVALID";
750
+ readonly SNAPSHOT_SYNC_HEADER_INVALID: "SNAPSHOT_SYNC_HEADER_INVALID";
751
+ readonly SNAPSHOT_SYNC_HEADER_MISMATCH: "SNAPSHOT_SYNC_HEADER_MISMATCH";
752
+ readonly SNAPSHOT_SYNC_CHUNK_OUT_OF_ORDER: "SNAPSHOT_SYNC_CHUNK_OUT_OF_ORDER";
753
+ readonly SNAPSHOT_SYNC_CHUNK_OVERFLOW: "SNAPSHOT_SYNC_CHUNK_OVERFLOW";
754
+ readonly SNAPSHOT_SYNC_CHUNK_SIZE_EXCEEDED: "SNAPSHOT_SYNC_CHUNK_SIZE_EXCEEDED";
755
+ readonly SNAPSHOT_SYNC_CHUNK_MISSING: "SNAPSHOT_SYNC_CHUNK_MISSING";
756
+ readonly SNAPSHOT_SYNC_END_MISSING: "SNAPSHOT_SYNC_END_MISSING";
757
+ readonly SNAPSHOT_SYNC_CHECKSUM_MISMATCH: "SNAPSHOT_SYNC_CHECKSUM_MISMATCH";
758
+ readonly SNAPSHOT_SYNC_PRIMARY_ERROR: "SNAPSHOT_SYNC_PRIMARY_ERROR";
759
+ readonly SNAPSHOT_SYNC_NO_TARGETS: "SNAPSHOT_SYNC_NO_TARGETS";
760
+ readonly SNAPSHOT_SYNC_TRANSPORT_FAILED: "SNAPSHOT_SYNC_TRANSPORT_FAILED";
761
+ readonly SNAPSHOT_SYNC_SCHEMA_UNAVAILABLE: "SNAPSHOT_SYNC_SCHEMA_UNAVAILABLE";
762
+ readonly SNAPSHOT_SYNC_RESTORE_FAILED: "SNAPSHOT_SYNC_RESTORE_FAILED";
763
+ readonly SNAPSHOT_SYNC_RESTORE_CLEANUP_FAILED: "SNAPSHOT_SYNC_RESTORE_CLEANUP_FAILED";
764
+ readonly SNAPSHOT_SYNC_TIMEOUT: "SNAPSHOT_SYNC_TIMEOUT";
765
+ readonly SNAPSHOT_SYNC_ALLOCATION_UNAVAILABLE: "SNAPSHOT_SYNC_ALLOCATION_UNAVAILABLE";
766
+ readonly SNAPSHOT_SYNC_NOT_ASSIGNED: "SNAPSHOT_SYNC_NOT_ASSIGNED";
767
+ readonly SNAPSHOT_SYNC_ABORTED: "SNAPSHOT_SYNC_ABORTED";
768
+ };
753
769
  /**
754
- * One stored document, as {@link Narsil.listDocuments} returns it.
770
+ * Any one of the codes in {@link ErrorCodes}, which is the type to narrow on
771
+ * when you branch on a failure the engine raised.
755
772
  *
756
- * @typeParam T - Shape of the stored document.
773
+ * @public
774
+ */
775
+ type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];
776
+ /**
777
+ * Every code the HTTP layer raises for a failure that arises before or around
778
+ * the engine call, such as parsing the body, enforcing a limit, or routing.
779
+ *
780
+ * The engine raises none of these, so a failure carrying one of them says the
781
+ * request never reached the engine.
757
782
  *
758
783
  * @public
759
784
  */
760
- interface ListedDocument<T = AnyDocument> {
761
- /** The document is stored under this id. */
762
- id: string;
763
- /** This holds the stored document, cut down to what the projection kept. */
764
- document: T;
765
- }
785
+ declare const ServerErrorCodes: {
786
+ readonly INVALID_REQUEST: "INVALID_REQUEST";
787
+ readonly INVALID_JSON: "INVALID_JSON";
788
+ readonly EMPTY_BODY: "EMPTY_BODY";
789
+ readonly PAYLOAD_TOO_LARGE: "PAYLOAD_TOO_LARGE";
790
+ readonly NOT_FOUND: "NOT_FOUND";
791
+ readonly TASK_NOT_FOUND: "TASK_NOT_FOUND";
792
+ readonly TASK_NOT_CANCELLABLE: "TASK_NOT_CANCELLABLE";
793
+ readonly TASK_OWNED_BY_ANOTHER_INSTANCE: "TASK_OWNED_BY_ANOTHER_INSTANCE";
794
+ readonly TASK_INTERRUPTED: "TASK_INTERRUPTED";
795
+ readonly TOO_MANY_REQUESTS: "TOO_MANY_REQUESTS";
796
+ readonly HOOK_ERROR: "HOOK_ERROR";
797
+ readonly INTERNAL_ERROR: "INTERNAL_ERROR";
798
+ };
766
799
  /**
767
- * What {@link Narsil.listDocuments} returns: one page of stored documents and
768
- * the cursor that reaches the next one.
800
+ * Any one of the codes in {@link ServerErrorCodes}.
769
801
  *
770
- * @typeParam T - Shape of the stored documents.
802
+ * @public
803
+ */
804
+ type ServerErrorCode = (typeof ServerErrorCodes)[keyof typeof ServerErrorCodes];
805
+ /**
806
+ * Every code that the caller's own side raises, where a request never reaches
807
+ * a server, or where the caller cannot read the answer.
808
+ *
809
+ * The HTTP client raises the first five. The React bindings raise
810
+ * `CLIENT_UNEXPECTED_ERROR` alone, which reports a fault inside a hook. No
811
+ * server sends any of them, so a failure under one means the exchange broke
812
+ * before the operation ran. `STATUS_BY_CODE` in `src/server/errors.ts`
813
+ * therefore maps none of them, because no request can arrive under one and no
814
+ * HTTP status belongs to one.
771
815
  *
772
816
  * @public
773
817
  */
774
- interface ListResult<T = AnyDocument> {
775
- /** These documents make up the page, in ascending document-id order. */
776
- documents: Array<ListedDocument<T>>;
777
- /** This opaque cursor reaches the next page, and is null once the listing is finished. */
778
- cursor: string | null;
779
- /** The listing covers this many documents in total, and any filter narrows that count. */
780
- total: number;
781
- /** The engine spent this many milliseconds building the page. */
782
- elapsed: number;
783
- }
784
-
818
+ declare const ClientErrorCodes: {
819
+ readonly CLIENT_CONNECTION_FAILED: "CLIENT_CONNECTION_FAILED";
820
+ readonly CLIENT_REQUEST_TIMEOUT: "CLIENT_REQUEST_TIMEOUT";
821
+ readonly CLIENT_REQUEST_ABORTED: "CLIENT_REQUEST_ABORTED";
822
+ readonly CLIENT_INVALID_RESPONSE: "CLIENT_INVALID_RESPONSE";
823
+ readonly CLIENT_TASK_TIMEOUT: "CLIENT_TASK_TIMEOUT";
824
+ readonly CLIENT_UNEXPECTED_ERROR: "CLIENT_UNEXPECTED_ERROR";
825
+ };
785
826
  /**
786
- * Compares one field against a value. Setting several keys narrows the match,
787
- * because a document has to satisfy all of them.
827
+ * Any one of the codes in {@link ClientErrorCodes}.
788
828
  *
789
829
  * @public
790
830
  */
791
- type ComparisonFilter = {
792
- /** This matches a field equal to the value, or a list field where one element equals it. */
793
- eq?: number | string | boolean;
794
- /**
795
- * This matches a document that holds the field with a value other than this
796
- * one, or a list field where every element differs from it, which an empty
797
- * list does.
798
- */
799
- ne?: number | string | boolean;
800
- /** This matches a field greater than the number. */
801
- gt?: number;
802
- /** This matches a field less than the number. */
803
- lt?: number;
804
- /** This matches a field greater than or equal to the number. */
805
- gte?: number;
806
- /** This matches a field less than or equal to the number. */
807
- lte?: number;
808
- /** This matches a field inside the inclusive range, given as `[low, high]`. */
809
- between?: [number, number];
810
- };
831
+ type ClientErrorCode = (typeof ClientErrorCodes)[keyof typeof ClientErrorCodes];
811
832
  /**
812
- * The engine tests a text field against this filter for equality, for a text
813
- * range, or with the set and prefix tests.
833
+ * Every code a {@link NarsilError} can carry: one the engine raised, one the
834
+ * HTTP layer raised, one the client raised, or any other string.
814
835
  *
815
- * The engine compares each element of a `string[]`, `verbatim[]`, or `enum[]` field, so
816
- * it matches a document with `eq`, `in`, `startsWith`, `endsWith`, or
817
- * `contains` where one element passes the test, while it matches a document
818
- * with `ne` or `nin` where every element differs from the values.
836
+ * The last arm exists for a server's `onRequest` hook, which rejects a request
837
+ * under a code of its own, such as `UNAUTHORIZED`, and the client then passes
838
+ * that code through unchanged. An editor still completes every code Narsil
839
+ * defines.
819
840
  *
820
- * The engine applies the range tests `gt`, `gte`, `lt`, `lte`, and `between`
821
- * to a single `string` or `verbatim` field whose type includes `sortable`,
822
- * while it throws `SEARCH_INVALID_FILTER` for a text range on any other field.
823
- * It orders the values as a sort on the field does, comparing their case folds
824
- * first and their raw code points only where the folds are equal.
841
+ * @public
842
+ */
843
+ type NarsilErrorCode = ErrorCode | ServerErrorCode | ClientErrorCode | (string & {});
844
+ /**
845
+ * The error every part of the engine throws.
825
846
  *
826
- * A pattern field is a `verbatim` or `verbatim[]` field, or a `string` or
827
- * `string[]` field whose type includes `pattern`. On such a field, the engine
828
- * answers `eq`, `ne`, `in`, `nin`, `startsWith`, `endsWith`, and `contains`
829
- * from the field's pattern index. `caseFold` applies to each of those tests.
830
- * On an `enum` or `enum[]` field, the engine answers `eq`, `ne`, `in`, `nin`,
831
- * `startsWith`, and `endsWith` from the field's index of values. It throws
832
- * `SEARCH_INVALID_FILTER` for `eq`, `ne`, `in`, `nin`, `startsWith`, or
833
- * `endsWith` on a `string` or `string[]` field whose type leaves out
834
- * `pattern`, because such a field keeps no index of whole values.
835
- * The engine compares the code points of each value as stored, with no
836
- * Unicode normalisation. It throws `SEARCH_INVALID_FILTER` for `contains` or
837
- * `caseFold` on any other field, for a test text longer than 1,024 code points
838
- * on a pattern field, and for a `caseFold` test whose text has a case fold
839
- * longer than 2,048 code points.
847
+ * Catch it, read {@link NarsilError.code} to decide what to do, and read
848
+ * {@link NarsilError.details} for the values that caused it. The engine lets
849
+ * this error propagate unchanged, so the code you catch is the code the
850
+ * failing operation raised.
840
851
  *
841
852
  * @public
842
853
  */
843
- type StringFilter = Pick<ComparisonFilter, 'eq' | 'ne'> & {
844
- /** This matches a value that comes after the text in sort order. */
845
- gt?: string;
846
- /** This matches a value that comes before the text in sort order. */
847
- lt?: string;
848
- /** This matches a value equal to the text or after it in sort order. */
849
- gte?: string;
850
- /** This matches a value equal to the text or before it in sort order. */
851
- lte?: string;
852
- /** This matches a value inside the inclusive range in sort order, given as `[low, high]`. */
853
- between?: [string, string];
854
- /** This matches a field equal to any value in the list, which holds at most 65,536 values. */
855
- in?: string[];
856
- /** This matches a field that differs from every value in the list, which holds at most 65,536 values. */
857
- nin?: string[];
858
- /** This matches a field starting with the text. */
859
- startsWith?: string;
860
- /** This matches a field ending with the text. */
861
- endsWith?: string;
862
- /** This matches a pattern field whose value holds the text anywhere in it. */
863
- contains?: string;
854
+ declare class NarsilError extends Error {
855
+ /** This says which failure it is. */
856
+ readonly code: NarsilErrorCode;
857
+ /** This carries the values behind the failure, such as the field, index, or limit involved. It is empty when the code says everything. */
858
+ readonly details: Record<string, unknown>;
864
859
  /**
865
- * When this is true, the engine compares the case fold of each value of a
866
- * pattern field with the case fold of the text, so a test for `error` matches
867
- * `ERROR`. It applies to `eq`, `ne`, `in`, `nin`, `startsWith`, `endsWith`,
868
- * and `contains`.
860
+ * Builds an error carrying a code the caller can branch on.
861
+ *
862
+ * @param code - The failure this error reports, from {@link ErrorCodes} for
863
+ * an engine failure, {@link ServerErrorCodes} for one the HTTP layer raised,
864
+ * or {@link ClientErrorCodes} for one that stopped a request from reaching a
865
+ * server.
866
+ * @param message - Plain description, for a log or a person.
867
+ * @param details - Values behind the failure, which reach
868
+ * {@link NarsilError.details}.
869
869
  */
870
- caseFold?: boolean;
871
- };
870
+ constructor(code: NarsilErrorCode, message: string, details?: Record<string, unknown>);
871
+ }
872
872
  /**
873
- * Tests the contents of a list field, which is a `number[]`, `boolean[]`,
874
- * `enum[]`, `verbatim[]`, or `string[]` field.
873
+ * Reports whether a caught value is a {@link NarsilError}, including one that
874
+ * another entry point of this package raises.
875
875
  *
876
- * The engine throws `SEARCH_INVALID_FILTER` for these tests on any other
877
- * field, for a value whose type differs from the type of the list's elements,
878
- * and for `containsAll` or `matchesAny` on a `string[]` field whose type leaves
879
- * out `pattern`.
876
+ * Each browser bundle holds its own copy of the class, so an `instanceof` test
877
+ * inside the React bindings returns false for an error that the client raises,
878
+ * although that error still holds its code. This function tests for the marker
879
+ * that the constructor writes, so it returns true for an error from any entry
880
+ * point.
880
881
  *
881
- * @public
882
- */
883
- type ArrayFilter = {
884
- /** This matches a list holding every one of the values, at most 65,536 of them, so an empty set of values matches every list. */
885
- containsAll?: (string | number | boolean)[];
886
- /** This matches a list holding at least one of the values, at most 65,536 of them. */
887
- matchesAny?: (string | number | boolean)[];
888
- /** This compares the number of elements in the list. */
889
- size?: ComparisonFilter;
890
- };
891
- /**
892
- * Tests whether a field carries a value at all, without looking at what it
893
- * holds.
882
+ * @param value - The value that a `catch` block receives.
883
+ * @returns True where the value holds a code in {@link NarsilError.code}.
894
884
  *
895
885
  * @public
896
886
  */
897
- type PresenceFilter = {
898
- /** This matches a document where the field holds a value other than null. */
899
- exists?: boolean;
900
- /** This matches a document where the field is absent or null. */
901
- notExists?: boolean;
902
- /** This matches a document where the field is absent, null, an empty string, or an empty list. */
903
- isEmpty?: boolean;
904
- /** This matches a document where the field holds a value other than an empty string or an empty list. */
905
- isNotEmpty?: boolean;
906
- };
887
+ declare function isNarsilError(value: unknown): value is NarsilError;
888
+
907
889
  /**
908
- * Matches a `geopoint` field against a circle drawn on the earth.
890
+ * This map lists every event that the engine emits, with the payload of each
891
+ * one.
892
+ *
893
+ * {@link Narsil.on} registers a listener under a key from this map, so that the
894
+ * engine can pass the matching payload to that listener. Most of these events
895
+ * report work that the engine does in the background, away from the call that
896
+ * started it, so a failure that such an event reports never rejects a promise
897
+ * that you are holding.
909
898
  *
910
899
  * @public
911
900
  */
912
- type GeoRadiusFilter = {
913
- /** The engine tests the field against this circle. */
914
- radius: {
915
- /** The centre has this latitude, in degrees from -90 to 90. For any other value, the engine throws `SEARCH_INVALID_FILTER`. */
916
- lat: number;
917
- /** The centre has this longitude, in degrees from -180 to 180. For any other value, the engine throws `SEARCH_INVALID_FILTER`. */
918
- lon: number;
919
- /** The circle has this radius, measured in `unit`. */
920
- distance: number;
921
- /**
922
- * The engine measures `distance` in kilometres under `'km'`, in miles
923
- * under `'mi'`, and in metres under `'m'`. For any other unit, it throws
924
- * `SEARCH_INVALID_FILTER`.
925
- */
926
- unit: 'km' | 'mi' | 'm';
927
- /** The engine matches the points inside the circle while this is true, which is the default, and the points outside it while this is false. */
928
- inside?: boolean;
929
- /**
930
- * The engine measures each distance with the Haversine formula on a sphere
931
- * by default, and with Vincenty's formula on the WGS-84 ellipsoid while
932
- * this is true. Vincenty's formula iterates, so the engine takes longer
933
- * to compute each distance. The two formulas differ by less than 0.3% under about
934
- * 100 km, while across a continent they can differ by up to 0.5%.
935
- */
936
- highPrecision?: boolean;
901
+ type NarsilEventMap = {
902
+ /**
903
+ * The engine emits this event after a call changes what a read returns from
904
+ * an index. The calls are the inserts, updates, and removals, singly or in a
905
+ * batch, together with `clear`, `restore`, `rebalance`, `rebuildAnalysis`,
906
+ * `compactVectors`, `optimizeVectors`, `createIndex`, and `dropIndex`. The
907
+ * engine emits the event after a call that throws as well, because a call can
908
+ * change the index before it throws. It also emits the event after it reloads
909
+ * an index, once a shared invalidation adapter reports that another instance
910
+ * saved that index. The engine emits one event per batch, however many
911
+ * documents the batch holds.
912
+ *
913
+ * The engine emits the event once a query can see the change, which means
914
+ * after every worker copy applies the change and after any rebalance in
915
+ * progress replays it. A query that a listener sends from its handler
916
+ * therefore returns results that include the change. The engine waits for the
917
+ * change to become visible only while a listener is registered for the event.
918
+ */
919
+ write: {
920
+ /** This is the name of the index that changed. */
921
+ indexName: string;
922
+ };
923
+ /**
924
+ * A worker thread exited unexpectedly. The pool removes the thread and fails
925
+ * the requests that the thread was serving with `WORKER_CRASHED`. The engine
926
+ * then sends each of those queries again on the main thread, so the caller
927
+ * receives a result with no error. The remaining workers keep serving
928
+ * queries, because each of them holds a full worker copy of every promoted
929
+ * index.
930
+ *
931
+ * After a delay, the engine spawns a replacement and loads every copy onto
932
+ * it before it sends queries to the replacement. Once no worker is left, the
933
+ * main thread serves every query, because it holds every document. The first
934
+ * request after the delay then starts a new pool. The delay starts at one
935
+ * second and doubles up to a minute while replacements keep failing.
936
+ */
937
+ workerCrash: {
938
+ /** This is the id of the worker that exited. */
939
+ workerId: number;
940
+ /** These are the indexes that the worker held. */
941
+ indexNames: string[];
942
+ /** This is the error that ended the worker. */
943
+ error: Error;
944
+ };
945
+ /** An index gained worker copies, either because it reached the copy
946
+ * threshold or because a request loaded its copies again after an idle
947
+ * spell. */
948
+ workerPromote: {
949
+ /** This is the number of workers in the pool. */
950
+ workerCount: number;
951
+ /** This is the reason that the index gained its copies, such as the copy
952
+ * threshold that it reached. */
953
+ reason: string;
954
+ };
955
+ /** An index could not gain worker copies, so the main thread keeps serving
956
+ * its queries. */
957
+ workerPromoteFailure: {
958
+ /** This is the reason that the engine tried to load the copies. */
959
+ reason: string;
960
+ /** This is the error that stopped the load. */
961
+ error: Error;
962
+ /** This is true when the engine will try again at a later threshold. */
963
+ retryable: boolean;
964
+ };
965
+ /** An index finished spreading its documents across a new number of
966
+ * partitions. */
967
+ partitionRebalance: {
968
+ /** This is the name of the index that the engine rebalanced. */
969
+ indexName: string;
970
+ /** This is the number of partitions before the rebalance. */
971
+ oldCount: number;
972
+ /** This is the number of partitions after the rebalance. */
973
+ newCount: number;
974
+ };
975
+ /**
976
+ * An index passed its watermark, so its partitions are close to their
977
+ * capacity. On a cluster node, the engine reports the document count and the
978
+ * capacity of the one partition that `partitionId` identifies, which this
979
+ * node leads.
980
+ */
981
+ partitionWatermark: {
982
+ /** This is the name of the index that crossed the mark. */
983
+ indexName: string;
984
+ /** This is the number of documents in the index, or in the partition on a
985
+ * cluster node. */
986
+ documentCount: number;
987
+ /** This is the number of documents that the current partitions of the
988
+ * index can hold, or that the partition can hold on a cluster node. */
989
+ capacity: number;
990
+ /** This is the number of partitions in the index. */
991
+ partitionCount: number;
992
+ /** On a cluster node, this is the partition that crossed the mark, while
993
+ * outside a cluster the field is absent. */
994
+ partitionId?: number;
995
+ };
996
+ /**
997
+ * The process uses nine tenths of its heap, as measured during a write or a
998
+ * load, so the next large index can end the process with an out-of-memory
999
+ * error.
1000
+ *
1001
+ * Where `--max-old-space-size` or `--max-old-space-size-percentage` sets a
1002
+ * limit, on the command line or in `NODE_OPTIONS`, the engine measures the
1003
+ * used bytes against that limit, which `heapLimit` then reports. Where
1004
+ * neither flag sets a limit, the engine measures the share of the heap that
1005
+ * V8 reports as no longer available. V8 reports a limit about 192 MB above
1006
+ * the true ceiling, so a process on a default heap below about 2 GB can end before
1007
+ * this event fires.
1008
+ *
1009
+ * The engine emits the event once per crossing, then arms it again once the
1010
+ * free share of the heap recovers to two tenths. Raise the limit with
1011
+ * `--max-old-space-size-percentage` or `--max-old-space-size`, or close an
1012
+ * idle index; see {@link ProcessMemoryReport.heapLimit}.
1013
+ */
1014
+ heapPressure: {
1015
+ /** This is the index that a write or a load was touching when the heap
1016
+ * reached that point. */
1017
+ indexName: string;
1018
+ /** This is the heap that the process uses, in bytes. */
1019
+ heapUsed: number;
1020
+ /** This is the size in bytes that the heap can grow to. */
1021
+ heapLimit: number;
1022
+ /** This is the estimate of the bytes that the index holds. */
1023
+ estimatedMemoryBytes: number;
1024
+ };
1025
+ /** The engine started, completed, or failed a rebuild that brings the terms
1026
+ * of an index up to the current analysis of its language module. */
1027
+ analysisRebuild: {
1028
+ /** This is the name of the index under rebuild. */
1029
+ indexName: string;
1030
+ /** This is the stage that the rebuild has reached. */
1031
+ status: 'started' | 'completed' | 'failed';
1032
+ /** This is the number of partitions that the rebuild has covered so far. */
1033
+ partitionsRebuilt: number;
1034
+ /** This is the number of partitions that the rebuild covers in total. */
1035
+ partitionCount: number;
1036
+ /** This is the error that stopped the rebuild, which only a `failed`
1037
+ * status includes. */
1038
+ error?: Error;
1039
+ };
1040
+ /** The engine started, completed, or failed the rewrite of an index that you
1041
+ * saved with an earlier release. The engine rewrites the index as it
1042
+ * recovers it, before it serves the index's first request. Because the
1043
+ * engine writes the new manifest last, the earlier files stay intact through
1044
+ * a failed rewrite. The engine then starts the rewrite again the next time
1045
+ * it recovers the index. Without index lifecycle settings, the engine
1046
+ * recovers every index before {@link createNarsil} returns, so pass the
1047
+ * listener in the `events` setting of {@link createNarsil}. */
1048
+ layoutUpgrade: {
1049
+ /** This is the name of the index under rewrite. */
1050
+ indexName: string;
1051
+ /** This is the stage that the rewrite has reached. */
1052
+ status: 'started' | 'completed' | 'failed';
1053
+ /** This is `manifest` where the earlier index is a segment manifest with
1054
+ * its files, and `bundle` where it is a single snapshot bundle. */
1055
+ layout: 'manifest' | 'bundle';
1056
+ /** This is the error that stopped the rewrite, which only a `failed`
1057
+ * status includes. */
1058
+ error?: Error;
1059
+ };
1060
+ /** A write to the write-ahead log or a checkpoint failed, so the writes since
1061
+ * the last checkpoint are at risk. */
1062
+ durabilityError: {
1063
+ /** This is the error that the durability layer threw. */
1064
+ error: Error;
1065
+ };
1066
+ /** The invalidation channel failed, so this instance can serve partitions
1067
+ * that another instance has since changed. */
1068
+ invalidationError: {
1069
+ /** This is the error that the adapter threw. */
1070
+ error: Error;
937
1071
  };
938
1072
  };
939
1073
  /**
940
- * Matches a `geopoint` field against a polygon drawn on the earth.
1074
+ * This map holds a listener for any event of {@link NarsilEventMap}, so that
1075
+ * the engine can register each listener before it starts.
941
1076
  *
942
1077
  * @public
943
1078
  */
944
- type GeoPolygonFilter = {
945
- /** The engine tests the field against this polygon. */
946
- polygon: {
947
- /**
948
- * The engine closes the ring through these corners in the order that you
949
- * list them, so you can leave the first point off the end. It throws
950
- * `SEARCH_INVALID_FILTER` for a ring of fewer than three corners, which
951
- * encloses no area, and for a corner whose latitude is outside -90 to 90
952
- * or whose longitude is outside -180 to 180. It also throws that error for
953
- * a ring of more than 65,536 corners. List the corners counter-clockwise
954
- * around the area, as in an exterior ring of GeoJSON. Where the corners
955
- * span 180 degrees of longitude or more, the engine matches the area on
956
- * the left of that path, so a ring listed that way can cross the
957
- * antimeridian or span more than half the globe.
958
- */
959
- points: Array<{
960
- lat: number;
961
- lon: number;
962
- }>;
963
- /** The engine matches the points inside the polygon while this is true, which is the default, and the points outside it while this is false. */
964
- inside?: boolean;
965
- };
1079
+ type NarsilEventHandlers = {
1080
+ [K in keyof NarsilEventMap]?: (payload: NarsilEventMap[K]) => void;
966
1081
  };
1082
+
967
1083
  /**
968
- * Either shape a `geopoint` field is matched against.
1084
+ * What {@link Narsil.query} returns: the ranked hits and everything the query
1085
+ * asked for alongside them.
969
1086
  *
970
- * @public
971
- */
972
- type GeoFilter = GeoRadiusFilter | GeoPolygonFilter;
973
- /**
974
- * The filter one field accepts. Which of these forms applies follows from the
975
- * field's declared type.
1087
+ * @typeParam T - Shape of the stored documents, which flows through to each
1088
+ * hit's `document`.
976
1089
  *
977
1090
  * @public
978
1091
  */
979
- type FieldFilter = ComparisonFilter | StringFilter | ArrayFilter | PresenceFilter | GeoFilter;
1092
+ interface QueryResult<T = AnyDocument> {
1093
+ /** These documents match, cut to the query's `limit`, best score first or in the query's sort order. */
1094
+ hits: Array<Hit<T>>;
1095
+ /**
1096
+ * This many documents match in total, before the engine applies `limit`
1097
+ * and `offset`. For a keyword search the engine counts every match. For a
1098
+ * vector search it counts every vector that passes the query's filter and
1099
+ * its `similarity` floor, which is every vector in the field where the query
1100
+ * sets neither of them. The engine also counts each pinned document that
1101
+ * the query does not match, since it places that document among the hits.
1102
+ */
1103
+ count: number;
1104
+ /**
1105
+ * `count` holds the exact number of matches where this is true, and a
1106
+ * number at or below the true total where it is false. Where a query sets a
1107
+ * `similarity` floor on a vector field that holds a graph, the engine
1108
+ * counts only the vectors that it fetches, because it compares the query
1109
+ * with only a fraction of that field's vectors. For a hybrid query the
1110
+ * engine fuses two rankings, so the count is exact only where each of those
1111
+ * rankings contains every matching document. Where you pin a document from
1112
+ * outside the hits that the engine fetches, the engine reports true only
1113
+ * where it holds every match of the query, because only then can it test
1114
+ * whether the query matches that document.
1115
+ */
1116
+ countExact: boolean;
1117
+ /** The engine spent this many milliseconds on the search. */
1118
+ elapsed: number;
1119
+ /** This opaque cursor reaches the next page. Pass it back as `searchAfter`. */
1120
+ cursor?: string;
1121
+ /** These facet counts are keyed by the field each facet was asked for. */
1122
+ facets?: Record<string, FacetResult>;
1123
+ /** These groups arrive when the query asked for grouping. */
1124
+ groups?: GroupResult[];
1125
+ /** This turns true when the index's terms came from an older analysis than its language module produces now. */
1126
+ analysisStale?: boolean;
1127
+ /** The search read this much of the index, which is how you spot a degraded answer. */
1128
+ coverage: QueryCoverage;
1129
+ }
980
1130
  /**
981
- * The filter that a query runs, built from per-field tests and the boolean
982
- * operators that combine them.
983
- *
984
- * The engine answers every test from an index that it keeps for the field. It
985
- * applies the filter before scoring, so a narrow filter makes a search
986
- * cheaper. A filter nests at most 30 levels deep and holds at most 1,024
987
- * tests, counted across every field and nested expression. Past either limit,
988
- * the engine throws `SEARCH_INVALID_FILTER`, while it throws
989
- * `SEARCH_INVALID_FIELD` for a test on a field that the schema leaves out.
1131
+ * How much of an index one search read, which is what you check before you
1132
+ * trust a count or a ranking.
990
1133
  *
991
- * @public
992
- */
993
- type FilterExpression = {
994
- /** These per-field tests are keyed by field name, and a document has to satisfy every entry. */
995
- fields?: Record<string, FieldFilter>;
996
- /** Every nested expression has to match. */
997
- and?: FilterExpression[];
998
- /** At least one nested expression has to match. */
999
- or?: FilterExpression[];
1000
- /** The nested expression has to fail. */
1001
- not?: FilterExpression;
1002
- };
1003
-
1004
- /**
1005
- * Everything {@link Narsil.suggest} accepts.
1134
+ * An embedded engine reads every partition it holds, so `queriedPartitions`
1135
+ * matches `totalPartitions` there and the other two stay zero. A search across
1136
+ * a cluster may find a node slow or unreachable, which it counts here while
1137
+ * still returning the hits the other nodes gave it.
1006
1138
  *
1007
1139
  * @public
1008
1140
  */
1009
- interface SuggestParams {
1010
- /** The returned terms complete this text. */
1011
- prefix: string;
1012
- /** The lookup returns this many completions, most widely used first, and 10 by default. */
1013
- limit?: number;
1141
+ interface QueryCoverage {
1142
+ /** The search should have read this many partitions. */
1143
+ totalPartitions: number;
1144
+ /** The search read this many of them. */
1145
+ queriedPartitions: number;
1146
+ /** The search counts a partition here when the node holding it took longer than the query allowed. */
1147
+ timedOutPartitions: number;
1148
+ /** The search counts a partition here when the node holding it returned an error, and when no active replica served it. */
1149
+ failedPartitions: number;
1014
1150
  }
1015
1151
  /**
1016
- * Everything {@link Narsil.listDocuments} accepts.
1017
- *
1018
- * {@link Narsil.listDocuments} reads the stored documents without ranking them,
1019
- * which is how you page through a whole index. Leave `cursor` out to start at
1020
- * the first document, then pass back the cursor each result carries until it
1021
- * comes back null.
1152
+ * One matching document, with the score that ranked it.
1022
1153
  *
1023
- * A cursor belongs to the sort it was made under, so pass the same `sort` back
1024
- * with it. Changing `sort` invalidates the cursor, and the engine then throws
1025
- * `SEARCH_INVALID_CURSOR` rather than returning a page from the wrong order.
1154
+ * @typeParam T - Shape of the stored document.
1026
1155
  *
1027
1156
  * @public
1028
1157
  */
1029
- interface ListParams {
1030
- /**
1031
- * This cursor comes from a previous result, and continues where it stopped.
1032
- * The engine ties a cursor to the sort that produced it, and it throws
1033
- * `SEARCH_INVALID_CURSOR` for a cursor sent back under a different sort.
1034
- */
1035
- cursor?: string;
1036
- /** The page carries this many documents, and 10 by default. The engine raises a value below one to one. */
1037
- limit?: number;
1038
- /** This narrows the listing to the documents the filter accepts. */
1039
- filters?: FilterExpression;
1158
+ interface Hit<T = AnyDocument> {
1159
+ /** The document is stored under this id. */
1160
+ id: string;
1040
1161
  /**
1041
- * This orders the listing by field value rather than by document id, and the
1042
- * engine applies the fields in the order they are listed. Pass an object
1043
- * keyed by field, or a list of fields in the order they apply. It breaks a
1044
- * tie on document id, and it sorts by at most eight fields. The engine uses
1045
- * document-id order when you leave this out.
1046
- *
1047
- * The engine reads every document the listing covers to build a sorted page,
1048
- * so a sorted listing costs more than the default order on a large index.
1162
+ * This score ranked the hit. Scores compare within one result set, never
1163
+ * across searches. A sorted query ranks by sort values instead and carries
1164
+ * no score unless it sets `includeScores`.
1049
1165
  */
1050
- sort?: SortSpec;
1051
- /** This chooses how much of each stored document comes back, and the whole document by default. */
1052
- document?: DocumentProjection;
1166
+ score?: number;
1167
+ /** This is the stored document. */
1168
+ document: T;
1169
+ /** These are the parts the score was built from, which arrive when the query asked for them. */
1170
+ scoreComponents?: ScoreComponents;
1171
+ /** These highlighted snippets are keyed by field, and arrive when the query asked for highlighting. */
1172
+ highlights?: Record<string, HighlightMatch>;
1053
1173
  }
1054
-
1055
1174
  /**
1056
- * Which engine answers a query: keyword matching, vector similarity, or both
1057
- * merged into one ranking.
1175
+ * The numbers BM25 combined into one hit's score, which is what you read when
1176
+ * a ranking surprises you.
1058
1177
  *
1059
1178
  * @public
1060
1179
  */
1061
- type SearchMode = 'fulltext' | 'vector' | 'hybrid';
1180
+ interface ScoreComponents {
1181
+ /**
1182
+ * Each query term appears in one field of this document this many times,
1183
+ * under a key of `field:term`. A term that appears in two fields therefore
1184
+ * has two entries here, while the keys of {@link ScoreComponents.idf} hold
1185
+ * the bare term.
1186
+ */
1187
+ termFrequencies: Record<string, number>;
1188
+ /** Each field the query searched holds this many tokens, keyed by field. */
1189
+ fieldLengths: Record<string, number>;
1190
+ /** Each query term carries this inverse document frequency, which is what makes a rare term count for more. */
1191
+ idf: Record<string, number>;
1192
+ }
1062
1193
  /**
1063
- * How many of a query's terms a document has to carry. `all` demands every
1064
- * term, `any` accepts one, and a number demands that many.
1194
+ * A highlighted field, ready to render.
1065
1195
  *
1066
1196
  * @public
1067
1197
  */
1068
- type TermMatchPolicy = 'all' | 'any' | number;
1198
+ interface HighlightMatch {
1199
+ /** This is the field's text around the match, wrapped in the query's tags. */
1200
+ snippet: string;
1201
+ /**
1202
+ * Each range gives the start and the end of one match in the original field,
1203
+ * so you can render the highlight yourself. Where the snippet covers part of
1204
+ * the field alone, the engine lists only the matches that the snippet
1205
+ * displays. Every offset is a character count from the start of the original
1206
+ * field, whatever the snippet contains.
1207
+ */
1208
+ positions: Array<{
1209
+ start: number;
1210
+ end: number;
1211
+ }>;
1212
+ }
1069
1213
  /**
1070
- * One field of a sort, and the direction that field orders by.
1214
+ * Counts for one faceted field.
1071
1215
  *
1072
1216
  * @public
1073
1217
  */
1074
- interface SortField {
1075
- /** The field the engine reads, which may name a nested field with dots. */
1076
- field: string;
1077
- /** Ascending or descending order for this field. */
1078
- direction: 'asc' | 'desc';
1218
+ interface FacetResult {
1219
+ /** This many documents match per value, keyed by value. */
1220
+ values: Record<string, number>;
1221
+ /** This is the number of entries in `values`, which is at most the facet's `limit`. */
1222
+ count: number;
1079
1223
  /**
1080
- * Where a document's field holds a list, the engine sorts that document by
1081
- * one value from the list: the smallest under `'min'`, the largest under
1082
- * `'max'`, and the mean or the median of the list's numbers under `'avg'`
1083
- * or `'median'`. Where you leave this out, the engine uses `'min'` for an
1084
- * ascending sort and `'max'` for a descending one. It sorts by a field that
1085
- * holds a single value as that value stands, under every mode. It throws
1086
- * `SEARCH_INVALID_FIELD` for `'avg'` or `'median'` on a field that the
1087
- * schema declares as anything other than `number` or `number[]`.
1224
+ * Every count in `values` is at most this far below its true count. A value
1225
+ * that the engine leaves out of `values` because of `limit` has a true
1226
+ * count of at most this figure too. Where the engine counts a field on one
1227
+ * thread, it counts every value exactly, so this figure is the largest
1228
+ * count that it leaves out. Where it splits the count across worker copies
1229
+ * or cluster nodes, each of them returns only its own top values, so the
1230
+ * merged count of a value that is common overall but rare on one of them
1231
+ * can lack the matches on that one. A bound of 0 means that `values` holds
1232
+ * every matching value, each with its exact count.
1088
1233
  */
1089
- mode?: 'min' | 'max' | 'avg' | 'median';
1234
+ errorBound: number;
1090
1235
  }
1091
1236
  /**
1092
- * A sort, either as an object keyed by field or as a list of fields in the
1093
- * order they apply.
1094
- *
1095
- * Both forms order by the first field, break a tie on the second, and carry on
1096
- * that way. Prefer the list where the order of the fields matters, because
1097
- * JavaScript moves an all-digit key such as `2024` to the front of an object
1098
- * and the list keeps the order you wrote.
1237
+ * One group of hits, produced by a query that grouped its results.
1099
1238
  *
1100
1239
  * @public
1101
1240
  */
1102
- type SortSpec = Record<string, 'asc' | 'desc'> | readonly SortField[];
1241
+ interface GroupResult {
1242
+ /** Each grouping field holds this value for the group, keyed by field. */
1243
+ values: Record<string, unknown>;
1244
+ /** These hits fall in the group, cut to the query's `maxPerGroup`. */
1245
+ hits: Array<Hit>;
1246
+ /** The query's reducer produced this value for the group, and only a query that set `group.reduce` carries it. */
1247
+ reduced?: unknown;
1248
+ /** The reducer threw, and this holds its message, so the group carries its hits and no `reduced` value. */
1249
+ reducerError?: string;
1250
+ }
1103
1251
  /**
1104
- * Everything {@link Narsil.query} accepts.
1252
+ * What {@link Narsil.preflight} returns: how many documents a query matches,
1253
+ * without building or ranking a single hit.
1105
1254
  *
1106
- * Set `term` for keyword search, `vector` for similarity search, and `mode`
1107
- * when you want both. The engine matches nothing for a query carrying neither
1108
- * of them, so page through an index with {@link Narsil.listDocuments}
1109
- * instead.
1255
+ * @public
1256
+ */
1257
+ interface PreflightResult {
1258
+ /** The query matches this many documents. */
1259
+ count: number;
1260
+ /** `count` holds the exact number of matches where this is true, and a number at or below the true total where it is false, under the rule in {@link QueryResult.countExact}. */
1261
+ countExact: boolean;
1262
+ /** The count took this many milliseconds. */
1263
+ elapsed: number;
1264
+ /** This turns true when the index's terms came from an older analysis than its language module produces now. */
1265
+ analysisStale?: boolean;
1266
+ }
1267
+ /**
1268
+ * What a batch write returns. One bad document never abandons the rest, so
1269
+ * read both lists.
1110
1270
  *
1111
1271
  * @public
1112
1272
  */
1113
- interface QueryParams {
1114
- /** The engine analyses this text with the index's language module and searches for the terms that result. */
1115
- term?: string;
1116
- /** The engine searches the term in these fields, and in every text field in the schema by default. */
1117
- fields?: string[];
1118
- /**
1119
- * The engine scores only the documents that pass this filter. It throws
1120
- * `SEARCH_INVALID_FILTER` for an operand of the wrong shape, and for an
1121
- * operator on a field of another type, such as `startsWith` on a number
1122
- * field.
1123
- */
1124
- filters?: FilterExpression;
1125
- /**
1126
- * The engine multiplies the score from each named field by its weight. It
1127
- * throws `SEARCH_INVALID_FIELD` for any field other than a text field that
1128
- * the schema declares, and `CONFIG_INVALID` for a weight that is not a
1129
- * finite number.
1130
- */
1131
- boost?: Record<string, number>;
1132
- /** The engine gathers term statistics this way, and follows the index's `defaultScoring` where the query sets none. */
1133
- scoring?: ScoringMode;
1134
- /**
1135
- * The engine drops any hit scoring below this value. It ranks with BM25,
1136
- * which has no fixed upper bound, so a floor that suits one index and one
1137
- * query can reject every hit in another.
1138
- */
1139
- minScore?: number;
1140
- /**
1141
- * The engine keeps a document only where the document matches this many
1142
- * query terms, under the same `tolerance` and `prefixLength` that the search
1143
- * uses. One term is enough by default.
1144
- */
1145
- termMatch?: TermMatchPolicy;
1146
- /**
1147
- * The engine matches an indexed term within this edit distance of a query
1148
- * term, so it finds a document for a query with a typo. It counts each
1149
- * Unicode code point as one character. Set an integer from 0 to 10.
1150
- */
1151
- tolerance?: number;
1152
- /**
1153
- * The engine applies `tolerance` only to the indexed terms that share this
1154
- * many leading characters with the query term, or to the terms that start
1155
- * with the whole query term when the query term is shorter. Set an integer
1156
- * from 0 to 1,024; the default is 2.
1157
- */
1158
- prefixLength?: number;
1159
- /**
1160
- * With this set, the engine treats the last query term as an unfinished
1161
- * word, so `secur` matches `security`. The engine matches that last term by
1162
- * its stem or by completing it, while `tolerance` applies only to the earlier
1163
- * terms, which have to match whole. The engine scores completions against a
1164
- * shared document frequency. It also ranks them below whole-word matches.
1165
- * The engine ignores this setting where `exact` is true, and the setting is
1166
- * false by default.
1167
- */
1168
- prefix?: boolean;
1169
- /**
1170
- * Setting this makes the engine match each query term only against an equal
1171
- * indexed term, which turns off fuzzy matching and prefix completion. The
1172
- * engine still stems the query, because the index stores stemmed terms, so
1173
- * `running` matches a document that holds `runs` through their shared stem.
1174
- */
1175
- exact?: boolean;
1176
- /**
1177
- * The engine counts the values of these fields across the matching
1178
- * documents, and each entry sets how it cuts and sorts that field's counts.
1179
- * For a field outside the schema, it counts the values that the documents
1180
- * store. It throws `SEARCH_INVALID_FIELD` for a `geopoint` or a vector
1181
- * field.
1182
- */
1183
- facets?: FacetConfig;
1184
- /**
1185
- * The engine sorts the hits by the values of these fields, in place of the
1186
- * relevance ranking. Pass an object keyed by field, or a list of fields in
1187
- * the order that the engine compares them. The engine sorts by a `number`,
1188
- * `boolean`, or `enum` field, by a text field whose type includes
1189
- * `sortable`, or by a list of any of these, which it reduces to one value by
1190
- * the entry's `mode`. It throws `SEARCH_INVALID_FIELD` for a sort on a
1191
- * `geopoint` or a vector field, because neither type has an order. It throws
1192
- * the same code for a sort on any other text field, since the engine keeps
1193
- * up to the first 512 code points of every document's value in memory to
1194
- * sort by a text field. The engine orders hybrid results by fusion, so it
1195
- * throws `SEARCH_INVALID_MODE` for a sort on a hybrid query. It also throws
1196
- * that code for a direction other than `asc` and `desc`.
1197
- */
1198
- sort?: SortSpec;
1199
- /** These settings collapse the hits into groups by field value. */
1200
- group?: GroupConfig;
1201
- /**
1202
- * The query returns this many hits, and 10 by default. Pass 0 to read the
1203
- * match count with no hits. The engine reads a value below 0 as 0. It falls
1204
- * back to the default for `NaN` and for an infinite value, so a page size
1205
- * that you compute from user input never fails the query.
1206
- */
1207
- limit?: number;
1208
- /** The query skips this many hits before returning. A deep offset costs more than a cursor. */
1209
- offset?: number;
1210
- /** This cursor comes from a previous result's `cursor`, and pages without an offset's cost. */
1211
- searchAfter?: string;
1212
- /** These settings name the fields that come back with highlighted snippets. */
1213
- highlight?: HighlightConfig;
1214
- /** These documents take fixed positions, ahead of the ranking. */
1215
- pinned?: Array<{
1273
+ interface BatchResult {
1274
+ /** The engine wrote the documents under these ids. */
1275
+ succeeded: string[];
1276
+ /** The engine rejected each of these documents, and each entry carries the error that rejected it. */
1277
+ failed: Array<{
1216
1278
  docId: string;
1217
- position: number;
1279
+ error: NarsilError;
1218
1280
  }>;
1219
- /** This picks which engine answers the query. Keyword search runs by default. */
1220
- mode?: SearchMode;
1221
- /** These vector-search inputs are required in `vector` and `hybrid` mode. */
1222
- vector?: VectorQueryConfig;
1223
- /** These settings control how the keyword and vector rankings merge in `hybrid` mode. */
1224
- hybrid?: HybridConfig;
1225
- /**
1226
- * Setting this returns relevance scores on a sorted query. A query that
1227
- * names a sort ranks by sort values alone and computes no scores, so its
1228
- * hits carry none until this restores them. A query without a sort ignores
1229
- * this and always carries scores.
1230
- */
1231
- includeScores?: boolean;
1232
- /** Setting this returns the numbers behind each hit's score, which is what you read when a ranking surprises you. */
1233
- includeScoreComponents?: boolean;
1234
- /** This chooses how much of each stored document comes back, and the whole document by default. */
1235
- document?: DocumentProjection;
1236
1281
  }
1237
1282
  /**
1238
- * How much of a stored document each hit carries back.
1239
- *
1240
- * Pass `false` when the ids and scores are all you need, and every hit's
1241
- * `document` is then an empty object. Pass `include` to keep named fields
1242
- * alone, or `exclude` to drop named fields and keep the rest; naming both
1243
- * keeps the included fields and then drops the excluded ones from those. Use
1244
- * dots to name a nested field, so `author.name` addresses the `name` inside
1245
- * `author`, and a name that matches no field changes nothing.
1246
- *
1247
- * Drop a vector field on a similarity search, because the engine otherwise
1248
- * reads every hit's vector back out of the index and writes it into the
1249
- * response.
1283
+ * What {@link Narsil.importDocumentExport} returns. The engine continues past each
1284
+ * refused line, so read the refusals to learn which documents it skipped.
1250
1285
  *
1251
1286
  * @public
1252
1287
  */
1253
- type DocumentProjection = boolean | {
1254
- /** Names the fields to keep, so every field left out of this list is dropped. */
1255
- include?: string[];
1256
- /** Names the fields to drop, so every other field is kept. */
1257
- exclude?: string[];
1258
- };
1288
+ interface DocumentImportResult {
1289
+ /** The engine wrote this many documents, counting each one that it replaced. */
1290
+ imported: number;
1291
+ /** The engine refused this many lines in total. */
1292
+ refusedCount: number;
1293
+ /** These are the 1,000 refusals with the lowest line numbers. Each entry contains the line number, where the header is line 1, along with the error code and a message. */
1294
+ refused: Array<{
1295
+ line: number;
1296
+ code: NarsilErrorCode;
1297
+ message: string;
1298
+ }>;
1299
+ }
1259
1300
  /**
1260
- * Vector-search inputs passed under `QueryParams.vector`.
1261
- *
1262
- * Supply either a raw `value` array or a `text` string for auto-embedding;
1263
- * passing both throws `EMBEDDING_CONFIG_INVALID`. Result count is governed
1264
- * by the outer query's `limit`, not by any field on this object.
1301
+ * What {@link Narsil.getStats} returns about one index.
1265
1302
  *
1266
1303
  * @public
1267
1304
  */
1268
- interface VectorQueryConfig {
1269
- /**
1270
- * Name of the schema field that holds the vector to compare against.
1271
- * Must reference a field declared as `vector[N]` in the index schema.
1272
- */
1273
- field: string;
1274
- /**
1275
- * Raw query vector, given as a number array or a `Float32Array`. Length
1276
- * must match the indexed field's dimension or the search rejects the
1277
- * request with `VECTOR_DIMENSION_MISMATCH`.
1278
- */
1279
- value?: number[] | Float32Array;
1280
- /**
1281
- * Text to embed at query time using the index or instance embedding
1282
- * adapter. Mutually exclusive with `value`; requires a configured adapter.
1283
- */
1284
- text?: string;
1285
- /**
1286
- * Score floor applied during ranking. Hits scoring below this value
1287
- * are dropped before `limit` is enforced, so the returned hit count
1288
- * can be smaller than `limit` even when more documents exist. The
1289
- * floor is interpreted in score space for every metric; for
1290
- * `euclidean`, distance is mapped to a similarity score of
1291
- * `1 / (1 + distance)` first. Defaults to no floor.
1292
- */
1293
- similarity?: number;
1294
- /**
1295
- * Similarity metric used for ranking. Defaults to `cosine`. Choose
1296
- * `dotProduct` for raw inner-product scoring on already-normalised
1297
- * vectors and `euclidean` for distance-based ordering.
1298
- */
1299
- metric?: 'cosine' | 'dotProduct' | 'euclidean';
1300
- /**
1301
- * HNSW exploration factor for approximate search. Higher values raise
1302
- * recall at the cost of latency. Ignored while the field is still
1303
- * served by the brute-force backend. Defaults to the engine's built-in
1304
- * value when omitted.
1305
- */
1306
- efSearch?: number;
1305
+ interface IndexStats {
1306
+ /** The index holds this many documents. A closed index reports its count as of the last checkpoint. */
1307
+ documentCount: number;
1308
+ /** The index is spread across this many partitions. */
1309
+ partitionCount: number;
1307
1310
  /**
1308
- * How many times `limit` a quantized field re-scores against its
1309
- * full-precision vectors before it returns the best `limit`. A value below
1310
- * 1 or one that is not a finite number fails with `CONFIG_INVALID`. The
1311
- * engine ignores this on a field whose quantization is `none`. When a query
1312
- * omits it, the engine takes 3 for `osq1` and `osq2`, 2 for `osq8`, and 2
1313
- * for `osq4` at 1,024 dimensions and above, but 5 for `osq4` below 1,024,
1314
- * where a four-bit code ranks the true neighbours less reliably.
1311
+ * Formula-based estimate of the index's main-thread memory footprint, summed
1312
+ * across every partition and vector index for this index. Computed from
1313
+ * structural counters (document count, posting counts, field-index sizes),
1314
+ * not measured. Per-object V8 overhead (hidden classes, map transitions,
1315
+ * GC headers) is not captured here, so this number routinely undershoots
1316
+ * the real heap by a meaningful factor. Use {@link Narsil.getMemoryStats}
1317
+ * when sizing host memory.
1315
1318
  */
1316
- oversample?: number;
1319
+ estimatedMemoryBytes: number;
1320
+ /** The index analyses text with this language module. */
1321
+ language: string;
1322
+ /** The index was created with this field layout. */
1323
+ schema: SchemaDefinition;
1317
1324
  }
1318
1325
  /**
1319
- * How a hybrid query merges its keyword ranking with its vector ranking.
1326
+ * A summary of one index, as {@link Narsil.listIndexes} reports it.
1320
1327
  *
1321
- * `rrf` combines the two by rank alone, which needs no tuning and handles
1322
- * scores that live on different scales. `linear` blends the scores directly,
1323
- * which gives you control once you know what each side's scores look like.
1328
+ * @public
1329
+ */
1330
+ interface IndexInfo {
1331
+ /** The index was created under this name. */
1332
+ name: string;
1333
+ /** The index holds this many documents. A closed index reports its count as of the last checkpoint. */
1334
+ documentCount: number;
1335
+ /** The index is spread across this many partitions. */
1336
+ partitionCount: number;
1337
+ /** The index analyses text with this language module. */
1338
+ language: string;
1339
+ /** This turns true when the index's terms came from an older analysis than its language module produces now. */
1340
+ analysisStale?: boolean;
1341
+ /** This is `open` in memory, `closed` after release, and `reopen-failed` after five recovery failures. */
1342
+ state: 'open' | 'closed' | 'reopen-failed';
1343
+ /** This counts successful loads since this engine started. */
1344
+ reopenCount: number;
1345
+ }
1346
+ /**
1347
+ * What {@link Narsil.getPartitionStats} reports for one partition, which is
1348
+ * where you look when an index grows unevenly.
1324
1349
  *
1325
1350
  * @public
1326
1351
  */
1327
- interface HybridConfig {
1328
- /** The engine merges the rankings this way, and by rank fusion by default. It throws `CONFIG_INVALID` for any other value. */
1329
- strategy?: 'rrf' | 'linear';
1330
- /** The engine uses this rank-fusion constant under `rrf` alone, where a larger value reduces the lead of the top ranks. Set a whole number of at least 1, or leave it out for 60. The engine throws `CONFIG_INVALID` for any other value. */
1331
- k?: number;
1332
- /** The engine uses this weight of the vector score, from 0 to 1, under `linear` alone, and 0.5 where you leave it out. It throws `CONFIG_INVALID` for a value outside that range. */
1333
- alpha?: number;
1352
+ interface PartitionStatsResult {
1353
+ /** This identifies the partition within its index. */
1354
+ partitionId: number;
1355
+ /** The partition holds this many documents. */
1356
+ documentCount: number;
1357
+ /**
1358
+ * Formula-based estimate of this partition's memory footprint. V8 has no
1359
+ * per-object heap accounting API, so this number is derived from structural
1360
+ * counters (document count, posting counts, field-index sizes) and does not
1361
+ * include per-object overhead. Treat as an estimate, not a measurement.
1362
+ */
1363
+ estimatedMemoryBytes: number;
1334
1364
  }
1335
1365
  /**
1336
- * Fields a query counts values for, keyed by field name.
1366
+ * What {@link Narsil.suggest} returns: the indexed terms that complete a
1367
+ * prefix, ready to offer as you-type suggestions.
1337
1368
  *
1338
1369
  * @public
1339
1370
  */
1340
- interface FacetConfig {
1341
- /** Each key names a field the query counts values for. */
1342
- [field: string]: {
1343
- /** The engine returns this many values for the field, in the order of `sort`. An engine returns every value where you leave this out, while a cluster returns 10, or every range of a field that sets `ranges`. */
1344
- limit?: number;
1345
- /** The engine orders the returned values by their count, putting the highest first under `'desc'`, which is the default, and the lowest first under `'asc'`. Under `'asc'`, each cluster node sends the count of up to 10,000 values of the field, so the lowest counts are exact wherever no node holds more values than that. */
1346
- sort?: 'asc' | 'desc';
1347
- /** The engine counts a numeric field's matches into these ranges, with one count for each range. A cluster search counts up to 1,000 ranges on a field and throws `CONFIG_INVALID` for more. */
1348
- ranges?: Array<{
1349
- from: number;
1350
- to: number;
1351
- }>;
1352
- };
1371
+ interface SuggestResult {
1372
+ /** These completions run most widely used first. */
1373
+ terms: Array<{
1374
+ /** This is the completed term, as the index holds it. */
1375
+ term: string;
1376
+ /** The term appears in this many documents, which is what ordered the list. */
1377
+ documentFrequency: number;
1378
+ }>;
1379
+ /** The lookup took this many milliseconds. */
1380
+ elapsed: number;
1381
+ /** This turns true when the index's terms came from an older analysis than its language module produces now. */
1382
+ analysisStale?: boolean;
1353
1383
  }
1354
1384
  /**
1355
- * How a query collapses its hits into groups.
1385
+ * The state of one vector field, and what maintenance would cost, as
1386
+ * {@link Narsil.vectorMaintenanceStatus} reports it.
1387
+ *
1388
+ * Removing a vector leaves a tombstone in the graph, and enough of them slow a
1389
+ * search down. Read this to decide when compaction earns its cost.
1356
1390
  *
1357
1391
  * @public
1358
1392
  */
1359
- interface GroupConfig {
1360
- /** The values of these fields define a group, and several fields group by their combination. */
1361
- fields: string[];
1362
- /** The engine returns this many hits from each group, best first, and one hit where you leave this out. */
1363
- maxPerGroup?: number;
1364
- /** The engine returns this many groups, best first, and every group where you leave this out. */
1365
- limit?: number;
1393
+ interface VectorMaintenanceResult {
1394
+ /** This describes the named vector field. */
1395
+ fieldName: string;
1366
1396
  /**
1367
- * The engine folds every hit of each group into one value, such as a sum or
1368
- * an average, including the hits beyond `maxPerGroup`. In cluster mode the
1369
- * coordinator fetches up to 10,000 hits of each group to fold.
1397
+ * Tombstones make up this share of the graph's nodes, from 0 to 1. Before
1398
+ * the first build, where {@link VectorMaintenanceResult.graphCount} reads 0,
1399
+ * the engine divides by the number of stored vectors, because no graph
1400
+ * exists yet.
1370
1401
  */
1371
- reduce?: GroupReducer;
1402
+ tombstoneRatio: number;
1403
+ /** The field holds this many HNSW graphs: 0 before the first build and 1 once a graph exists. */
1404
+ graphCount: number;
1405
+ /** This many vectors wait outside the graph, which a search scans one by one. */
1406
+ bufferSize: number;
1407
+ /** This stays true while a graph build runs. */
1408
+ building: boolean;
1409
+ /** {@link Narsil.compactVectors} would take about this many milliseconds. */
1410
+ estimatedCompactMs: number;
1411
+ /** {@link Narsil.optimizeVectors} would take about this many milliseconds. */
1412
+ estimatedOptimizeMs: number;
1372
1413
  }
1373
1414
  /**
1374
- * Folds the hits of one group into a single value.
1415
+ * One stored document, as {@link Narsil.listDocuments} returns it.
1416
+ *
1417
+ * @typeParam T - Shape of the stored document.
1375
1418
  *
1376
1419
  * @public
1377
1420
  */
1378
- type GroupReducer = {
1379
- /**
1380
- * Folds one hit into the running value.
1381
- *
1382
- * @param accumulator - What the previous call returned, or what
1383
- * `initialValue` produced for the first hit.
1384
- * @param doc - The hit's stored document.
1385
- * @param score - The hit's relevance score.
1386
- * @returns The new running value.
1387
- */
1388
- reducer: (accumulator: unknown, doc: AnyDocument, score: number) => unknown;
1389
- /** Produces the starting value for each group. The engine calls it once per group. */
1390
- initialValue: () => unknown;
1391
- };
1421
+ interface ListedDocument<T = AnyDocument> {
1422
+ /** The document is stored under this id. */
1423
+ id: string;
1424
+ /** This holds the stored document, cut down to what the projection kept. */
1425
+ document: T;
1426
+ }
1392
1427
  /**
1393
- * This configuration names the fields that receive highlighted snippets. It
1394
- * also sets how the engine marks those snippets up.
1428
+ * What {@link Narsil.listDocuments} returns: one page of stored documents and
1429
+ * the cursor that reaches the next one.
1395
1430
  *
1396
- * The engine analyses the text of each returned field again to tag every word
1397
- * that it matched, so it tags the same words whatever the index's
1398
- * `trackPositions` setting is. It tags a word whose stem equals a query stem,
1399
- * and a word within the query's `tolerance` of a query stem. For a `prefix`
1400
- * query, it tags a word for the last query term only when that word completes
1401
- * the term or shares its stem.
1431
+ * @typeParam T - Shape of the stored documents.
1402
1432
  *
1403
1433
  * @public
1404
1434
  */
1405
- interface HighlightConfig {
1406
- /** The engine highlights these fields. */
1407
- fields: string[];
1408
- /** The engine writes this before each match, and writes `<mark>` by default. */
1409
- preTag?: string;
1410
- /** The engine writes this after each match, and writes `</mark>` by default. */
1411
- postTag?: string;
1412
- /**
1413
- * The engine takes this many characters of the field around the densest run
1414
- * of matches, 200 by default. It returns a snippet longer than that number,
1415
- * because it then adds the opening and closing tags, and an ellipsis at each
1416
- * end where it cuts the field.
1417
- */
1418
- maxSnippetLength?: number;
1435
+ interface ListResult<T = AnyDocument> {
1436
+ /** These documents make up the page, in ascending document-id order. */
1437
+ documents: Array<ListedDocument<T>>;
1438
+ /** This opaque cursor reaches the next page, and is null once the listing is finished. */
1439
+ cursor: string | null;
1440
+ /** The listing covers this many documents in total, and any filter narrows that count. */
1441
+ total: number;
1442
+ /** The engine spent this many milliseconds building the page. */
1443
+ elapsed: number;
1419
1444
  }
1420
1445
 
1421
1446
  /**