dynamo-bao 0.4.2 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,419 @@
1
+ // Pure helpers for searchable models. Kept dependency-free so they can be
2
+ // unit-tested in isolation and reused for both write-side index population
3
+ // and read-side query normalization.
4
+
5
+ const NON_ALPHANUM_REGEX = /[^\p{L}\p{N}\s]/gu;
6
+ const WHITESPACE_REGEX = /\s+/g;
7
+
8
+ function normalize(text, { caseSensitive = false } = {}) {
9
+ let result = String(text).replace(NON_ALPHANUM_REGEX, " ");
10
+ if (!caseSensitive) result = result.toLowerCase();
11
+ result = result.replace(WHITESPACE_REGEX, " ").trim();
12
+ return result;
13
+ }
14
+
15
+ function buildSearchText(values, config) {
16
+ const {
17
+ fields = [],
18
+ caseSensitive = false,
19
+ minTermLength = 1,
20
+ dedupe = false,
21
+ } = config || {};
22
+
23
+ const parts = [];
24
+ for (const fieldName of fields) {
25
+ const value = values[fieldName];
26
+ if (value === null || value === undefined) continue;
27
+ parts.push(String(value));
28
+ }
29
+ if (parts.length === 0) return "";
30
+
31
+ let text = normalize(parts.join(" "), { caseSensitive });
32
+ if (text === "") return "";
33
+
34
+ const needsTokenize = dedupe || (minTermLength && minTermLength > 1);
35
+ if (!needsTokenize) return text;
36
+
37
+ const tokens = text.split(" ");
38
+ const filtered = [];
39
+ const seen = new Set();
40
+ for (const tok of tokens) {
41
+ if (!tok) continue;
42
+ if (minTermLength > 1 && [...tok].length < minTermLength) continue;
43
+ if (dedupe) {
44
+ if (seen.has(tok)) continue;
45
+ seen.add(tok);
46
+ }
47
+ filtered.push(tok);
48
+ }
49
+ return filtered.join(" ");
50
+ }
51
+
52
+ function normalizeSearchTerm(term, config = {}) {
53
+ return normalize(term, config);
54
+ }
55
+
56
+ function tokenizeSearchQuery(query) {
57
+ if (typeof query !== "string") return [];
58
+ const tokens = [];
59
+ let i = 0;
60
+ const n = query.length;
61
+ while (i < n) {
62
+ const ch = query[i];
63
+ if (/\s/.test(ch)) {
64
+ i++;
65
+ continue;
66
+ }
67
+ if (ch === '"') {
68
+ const close = query.indexOf('"', i + 1);
69
+ if (close === -1) {
70
+ const phrase = query.slice(i + 1).trim();
71
+ if (phrase) tokens.push(phrase);
72
+ break;
73
+ }
74
+ const phrase = query.slice(i + 1, close).trim();
75
+ if (phrase) tokens.push(phrase);
76
+ i = close + 1;
77
+ continue;
78
+ }
79
+ let j = i;
80
+ while (j < n && !/\s/.test(query[j]) && query[j] !== '"') j++;
81
+ const word = query.slice(i, j);
82
+ if (word) tokens.push(word);
83
+ i = j;
84
+ }
85
+ return tokens;
86
+ }
87
+
88
+ // Decide what `_searchText` should be on a save.
89
+ //
90
+ // Returns:
91
+ // undefined → do not include `_searchText` in the update payload (leave the
92
+ // row's existing value untouched, or skip on insert).
93
+ // null → include `_searchText: null` (caller emits REMOVE).
94
+ // string → include `_searchText: <value>` (caller emits SET).
95
+ //
96
+ // Inputs:
97
+ // searchConfig: the validated `static searchConfig` object, or null.
98
+ // dyUpdatesToSave: the diff being written to DynamoDB (in Dy format —
99
+ // string fields stay as strings, so this is the same
100
+ // representation that buildSearchText reads).
101
+ // currentItem: the loaded model instance whose `_dyData` holds current
102
+ // values. Required for non-isNew updates so untouched source
103
+ // fields can be backfilled. May be null for insert.
104
+ // isNew: true on create.
105
+ // forceReindex: true when the caller wants every index attribute
106
+ // recomputed from the merged state regardless of which
107
+ // fields were touched.
108
+ function computeSearchTextUpdate({
109
+ searchConfig,
110
+ dyUpdatesToSave,
111
+ currentItem,
112
+ isNew = false,
113
+ forceReindex = false,
114
+ }) {
115
+ if (!searchConfig) return undefined;
116
+
117
+ const fields = searchConfig.fields || [];
118
+ const sourceTouched = fields.some((f) =>
119
+ Object.prototype.hasOwnProperty.call(dyUpdatesToSave, f),
120
+ );
121
+
122
+ if (!isNew && !forceReindex && !sourceTouched) return undefined;
123
+
124
+ const merged = {};
125
+ if (currentItem && currentItem._dyData) {
126
+ for (const f of fields) {
127
+ if (f in currentItem._dyData) merged[f] = currentItem._dyData[f];
128
+ }
129
+ }
130
+ for (const f of fields) {
131
+ if (Object.prototype.hasOwnProperty.call(dyUpdatesToSave, f)) {
132
+ merged[f] = dyUpdatesToSave[f];
133
+ }
134
+ }
135
+
136
+ const result = buildSearchText(merged, searchConfig);
137
+
138
+ if (result === "") {
139
+ return isNew ? undefined : null;
140
+ }
141
+ return result;
142
+ }
143
+
144
+ // Build a DynamoDB FilterExpression predicate that matches rows whose
145
+ // `_searchText` contains the supplied terms. Terms are normalized with the
146
+ // same rules used to build `_searchText` so the values match what's stored.
147
+ //
148
+ // Returns null-safe `{ FilterExpression, ExpressionAttributeNames,
149
+ // ExpressionAttributeValues }`. The caller is responsible for AND'ing this
150
+ // into any user-supplied filter.
151
+ const VALID_OPERATORS = new Set(["$and", "$or"]);
152
+
153
+ function buildSearchPredicate(terms, searchConfig, options = {}) {
154
+ if (!Array.isArray(terms)) {
155
+ throw new Error("terms must be an array of strings.");
156
+ }
157
+ for (const t of terms) {
158
+ if (typeof t !== "string") {
159
+ throw new Error("terms must be strings.");
160
+ }
161
+ }
162
+ const { operator = "$and" } = options;
163
+ if (!VALID_OPERATORS.has(operator)) {
164
+ throw new Error(
165
+ `operator must be one of: ${Array.from(VALID_OPERATORS).join(", ")}.`,
166
+ );
167
+ }
168
+
169
+ // Mirror the write-side filter: terms shorter than minTermLength are
170
+ // dropped from the predicate so the user can't silently get zero matches
171
+ // by querying for a term the index doesn't store. Length is counted in
172
+ // Unicode code points to match buildSearchText's [...tok].length check.
173
+ const minTermLength =
174
+ (searchConfig && searchConfig.minTermLength) || 1;
175
+ const normalized = [];
176
+ for (const t of terms) {
177
+ const n = normalizeSearchTerm(t, searchConfig || {});
178
+ if (n && [...n].length >= minTermLength) normalized.push(n);
179
+ }
180
+ if (normalized.length === 0) {
181
+ throw new Error("searchAll requires at least one non-empty term.");
182
+ }
183
+
184
+ // `:stN` placeholders are deliberately a separate namespace from the
185
+ // FilterExpressionBuilder convention (`:vN`, see src/filter-expression.js)
186
+ // so the two can be merged into a single FilterExpression without colliding.
187
+ const join = operator === "$or" ? " OR " : " AND ";
188
+ const parts = [];
189
+ const values = {};
190
+ normalized.forEach((value, idx) => {
191
+ const key = `:st${idx}`;
192
+ parts.push(`contains(#st, ${key})`);
193
+ values[key] = value;
194
+ });
195
+
196
+ const expression =
197
+ parts.length === 1 ? parts[0] : parts.map((p) => `(${p})`).join(join);
198
+
199
+ return {
200
+ FilterExpression: expression,
201
+ ExpressionAttributeNames: { "#st": "_searchText" },
202
+ ExpressionAttributeValues: values,
203
+ };
204
+ }
205
+
206
+ // Validate a `limit` option value. Accepts positive integers and Infinity.
207
+ // Anything else throws — saves the caller from passing 0 or a float and
208
+ // silently getting weird behavior downstream.
209
+ function validateLimit(limit) {
210
+ if (limit === Infinity) return;
211
+ if (
212
+ typeof limit !== "number" ||
213
+ Number.isNaN(limit) ||
214
+ !Number.isInteger(limit) ||
215
+ limit < 1
216
+ ) {
217
+ throw new Error("limit must be a positive integer or Infinity.");
218
+ }
219
+ }
220
+
221
+ // Take an async iterable of arrays (batches) and re-yield them, capping the
222
+ // total flattened item count at `limit`. The last batch yielded is sliced to
223
+ // fit so the consumer never sees more than `limit` items in total. Stops
224
+ // pulling from the source once the cap is hit, so a generator-backed source
225
+ // is suspended (no further DynamoDB Query calls, no further bucket scans).
226
+ async function* applyLimit(asyncIterable, limit) {
227
+ if (limit === Infinity) {
228
+ yield* asyncIterable;
229
+ return;
230
+ }
231
+ let yielded = 0;
232
+ for await (const batch of asyncIterable) {
233
+ const room = limit - yielded;
234
+ if (room <= 0) return;
235
+ if (batch.length === 0) {
236
+ yield batch;
237
+ continue;
238
+ }
239
+ if (batch.length <= room) {
240
+ yield batch;
241
+ yielded += batch.length;
242
+ if (yielded >= limit) return;
243
+ } else {
244
+ yield batch.slice(0, room);
245
+ return;
246
+ }
247
+ }
248
+ }
249
+
250
+ // Stable, deterministic hash of a search predicate. Used to invalidate a
251
+ // cursor if the caller resumes with different terms / operator / config —
252
+ // otherwise a continuation key from the old query would silently splice
253
+ // rows from a different result set into the new one. Not cryptographic;
254
+ // just a reliable equality check.
255
+ function predicateHash(terms, operator, searchConfig) {
256
+ const cfg = searchConfig || {};
257
+ const normalized = (terms || []).map((t) =>
258
+ normalizeSearchTerm(String(t), cfg),
259
+ );
260
+ const payload = JSON.stringify({
261
+ terms: normalized,
262
+ operator: operator || "$and",
263
+ caseSensitive: !!cfg.caseSensitive,
264
+ minTermLength: cfg.minTermLength || 1,
265
+ dedupe: !!cfg.dedupe,
266
+ });
267
+ // Simple FNV-1a 32-bit. Collisions are astronomically rare for our
268
+ // input space and we don't need cryptographic strength.
269
+ let h = 0x811c9dc5;
270
+ for (let i = 0; i < payload.length; i++) {
271
+ h ^= payload.charCodeAt(i);
272
+ h = Math.imul(h, 0x01000193);
273
+ }
274
+ return (h >>> 0).toString(36);
275
+ }
276
+
277
+ const CURSOR_REQUIRED_FIELDS = [
278
+ "bucketCursors",
279
+ "predicateHash",
280
+ "modelPrefix",
281
+ "scope",
282
+ "tenantId",
283
+ ];
284
+
285
+ // URL-safe base64 with manual character replacement so we don't depend on
286
+ // Node's "base64url" encoding token (Node 16+ only — README still claims
287
+ // 12.17.0+ as the floor). Manual form works on every Node version that
288
+ // supports Buffer.
289
+ function _toBase64url(utf8) {
290
+ return Buffer.from(utf8, "utf8")
291
+ .toString("base64")
292
+ .replace(/\+/g, "-")
293
+ .replace(/\//g, "_")
294
+ .replace(/=+$/, "");
295
+ }
296
+
297
+ function _fromBase64url(s) {
298
+ let padded = s.replace(/-/g, "+").replace(/_/g, "/");
299
+ while (padded.length % 4) padded += "=";
300
+ // Validate the input contains only base64-alphabet characters; otherwise
301
+ // Node's Buffer is permissive and silently drops garbage characters.
302
+ if (!/^[A-Za-z0-9+/=]*$/.test(padded)) {
303
+ throw new Error("Invalid cursor: not valid base64url.");
304
+ }
305
+ return Buffer.from(padded, "base64").toString("utf8");
306
+ }
307
+
308
+ function encodeCursor(state) {
309
+ if (!state || typeof state !== "object") {
310
+ throw new Error("encodeCursor: invalid state.");
311
+ }
312
+ for (const f of CURSOR_REQUIRED_FIELDS) {
313
+ if (!(f in state)) {
314
+ throw new Error(`encodeCursor: missing required field "${f}".`);
315
+ }
316
+ }
317
+ const json = JSON.stringify({
318
+ bucketCursors: state.bucketCursors,
319
+ predicateHash: state.predicateHash,
320
+ modelPrefix: state.modelPrefix,
321
+ scope: state.scope,
322
+ tenantId: state.tenantId,
323
+ pendingItemKeys: state.pendingItemKeys || [],
324
+ });
325
+ return _toBase64url(json);
326
+ }
327
+
328
+ function decodeCursor(encoded) {
329
+ if (typeof encoded !== "string" || encoded.length === 0) {
330
+ throw new Error("Invalid cursor: must be a non-empty string.");
331
+ }
332
+ let json;
333
+ try {
334
+ json = _fromBase64url(encoded);
335
+ } catch (e) {
336
+ throw new Error(e.message || "Invalid cursor: not valid base64url.");
337
+ }
338
+ let parsed;
339
+ try {
340
+ parsed = JSON.parse(json);
341
+ } catch (e) {
342
+ throw new Error("Invalid cursor: payload is not valid JSON.");
343
+ }
344
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
345
+ throw new Error("Invalid cursor: payload is not an object.");
346
+ }
347
+ for (const f of CURSOR_REQUIRED_FIELDS) {
348
+ if (!(f in parsed)) {
349
+ throw new Error(`Invalid cursor: missing required field "${f}".`);
350
+ }
351
+ }
352
+ // Defense-in-depth: validate field types. Cursors round-trip through
353
+ // user-controlled storage, so a malformed payload that parses as JSON
354
+ // shouldn't crash deep in _searchPaged with an opaque TypeError —
355
+ // surface the shape problem at decode.
356
+ if (
357
+ !parsed.bucketCursors ||
358
+ typeof parsed.bucketCursors !== "object" ||
359
+ Array.isArray(parsed.bucketCursors)
360
+ ) {
361
+ throw new Error(
362
+ "Invalid cursor: bucketCursors must be an object map.",
363
+ );
364
+ }
365
+ if (typeof parsed.predicateHash !== "string") {
366
+ throw new Error("Invalid cursor: predicateHash must be a string.");
367
+ }
368
+ if (
369
+ parsed.modelPrefix !== null &&
370
+ typeof parsed.modelPrefix !== "string"
371
+ ) {
372
+ throw new Error("Invalid cursor: modelPrefix must be a string or null.");
373
+ }
374
+ if (!Array.isArray(parsed.scope)) {
375
+ throw new Error("Invalid cursor: scope must be an array.");
376
+ }
377
+ for (const s of parsed.scope) {
378
+ if (!Number.isInteger(s) || s < 0) {
379
+ throw new Error(
380
+ "Invalid cursor: scope must contain non-negative integers.",
381
+ );
382
+ }
383
+ }
384
+ if (
385
+ parsed.tenantId !== null &&
386
+ typeof parsed.tenantId !== "string"
387
+ ) {
388
+ throw new Error("Invalid cursor: tenantId must be a string or null.");
389
+ }
390
+ if (
391
+ parsed.pendingItemKeys !== undefined &&
392
+ !Array.isArray(parsed.pendingItemKeys)
393
+ ) {
394
+ throw new Error("Invalid cursor: pendingItemKeys must be an array.");
395
+ }
396
+ if (Array.isArray(parsed.pendingItemKeys)) {
397
+ for (const k of parsed.pendingItemKeys) {
398
+ if (typeof k !== "string") {
399
+ throw new Error(
400
+ "Invalid cursor: pendingItemKeys must contain strings.",
401
+ );
402
+ }
403
+ }
404
+ }
405
+ return parsed;
406
+ }
407
+
408
+ module.exports = {
409
+ buildSearchText,
410
+ normalizeSearchTerm,
411
+ tokenizeSearchQuery,
412
+ computeSearchTextUpdate,
413
+ buildSearchPredicate,
414
+ applyLimit,
415
+ validateLimit,
416
+ predicateHash,
417
+ encodeCursor,
418
+ decodeCursor,
419
+ };