Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 | 43x 43x 43x 43x 146x 43x 43x 43x 43x 907x 3x 304x 480x 33x 447x 447x 4228x 447x 364x 364x 333x 183x 183x 333x 333x 282x 282x 476x 4251x 4251x 1244x 1244x 333x 9x 37x 94x 61x 24x 8x 8x 5x 5x 5x 5x 5x 5x 7x 12x 7x 1x 1x 5x 4x 4x 4x 4x 4x 4x 8x 4x 6x 3x 4x 17x 17x 16x 4x 18x 16x 16x 18x 43x | const { BatchGetCommand } = require('@aws-sdk/lib-dynamodb')
const { PLAIN_VALUE_LANG } = require('./uniqueFieldValue')
const { queryIdsForExactPk, diffByKey } = require('./fieldValueIndexHelpers')
// Free-text-shaped field types get a trigram inverted index instead of a
// whole-value equality index (see utils/equalityIndexValue.js for the other
// types) — no gate other than type, ever: a field's type never changes once
// created, so this is a fixed, lifelong property.
const TEXT_SEARCH_TYPES = ['text', 'textarea', 'email']
function needsTextSearchIndex(field) {
return TEXT_SEARCH_TYPES.includes(field?.type)
}
const TRIGRAM_LENGTH = 3
const MIN_QUERY_LENGTH = 3
// NFD decomposition does NOT decompose these Latin ligatures (verified
// against the runtime: 'œuvre'.normalize('NFD') is unchanged) — without this
// expansion, a search for "oeuvre" (the common unaccented way to type it)
// would never match a stored "œuvre".
const LIGATURE_MAP = { œ: 'oe', æ: 'ae', Œ: 'OE', Æ: 'AE' }
const LIGATURE_REGEX = /[Ͼή]/g
/**
* Case-folds and strips diacritics so index-time and query-time tokens are
* comparable regardless of accents (this app is bilingual en/fr) — e.g.
* "catégorie" and "categorie" normalize to the same string.
*
* @param {string} value
* @returns {string}
*/
function normalizeForSearch(value) {
return value
.replace(LIGATURE_REGEX, (ch) => LIGATURE_MAP[ch])
.normalize('NFD')
.replace(/\p{M}/gu, '')
.toLowerCase()
}
/**
* Splits already-normalized text into words on any run of non-letter/
* non-digit characters (Unicode-aware), dropping empty results.
*
* @param {string} normalized
* @returns {string[]}
*/
function tokenizeWords(normalized) {
return normalized.split(/[^\p{L}\p{N}]+/u).filter(Boolean)
}
/**
* Generates the index tokens for one word: every overlapping 3-character
* window (kind 'trgm') for a word long enough to have any, or the whole word
* as its own literal token (kind 'stok') when it's too short to form a
* trigram — otherwise a 1-2 character word would simply vanish from the
* index with no way to ever surface it again.
*
* @param {string} word already-normalized
* @returns {Array<{ kind: 'trgm' | 'stok', token: string }>}
*/
function tokensForWord(word) {
if (word.length < TRIGRAM_LENGTH) {
return [{ kind: 'stok', token: word }]
}
const tokens = []
for (let i = 0; i <= word.length - TRIGRAM_LENGTH; i++) {
tokens.push({ kind: 'trgm', token: word.slice(i, i + TRIGRAM_LENGTH) })
}
return tokens
}
/**
* Canonicalizes a text-search-eligible field's value into the set of
* (language, kind, token) triples that need an index row — one per distinct
* token found across every word of the value, per non-empty language.
* Multilingual-map-shaped (like unique/equality text handling); a plain
* string is treated under the PLAIN_VALUE_LANG sentinel.
*
* @param {{ fieldId: string }} field
* @param {Record<string, unknown>} data
* @returns {Array<{ lang: string, kind: string, token: string }>}
*/
function getTextSearchTokens(field, data) {
const raw = data[field.fieldId]
if (raw === undefined || raw === null || raw === '') return []
const perLanguageValues =
typeof raw === 'string'
? [{ lang: PLAIN_VALUE_LANG, value: raw }]
: typeof raw === 'object' && !Array.isArray(raw)
? Object.entries(raw)
.filter(([, value]) => typeof value === 'string' && value !== '')
.map(([lang, value]) => ({ lang, value }))
: []
const results = []
for (const { lang, value } of perLanguageValues) {
const seen = new Set()
for (const word of tokenizeWords(normalizeForSearch(value))) {
for (const { kind, token } of tokensForWord(word)) {
const key = `${kind}:${token}`
if (seen.has(key)) continue
seen.add(key)
results.push({ lang, kind, token })
}
}
}
return results
}
/**
* Diffs a text-search field's value between an item's old and new state into
* the (language, kind, token) triples whose index row must be released
* and/or claimed. Same Map-diff shape as uniqueFieldValue.js's
* diffUniqueLanguageValues, keyed by the composite `lang#kind#token`.
*
* @param {{ fieldId: string }} field
* @param {Record<string, unknown>} oldData
* @param {Record<string, unknown>} newData
* @returns {{ toRelease: Array<{lang:string,kind:string,token:string}>, toClaim: Array<{lang:string,kind:string,token:string}> }}
*/
function diffTextSearchTokens(field, oldData, newData) {
return diffByKey(
getTextSearchTokens(field, oldData),
getTextSearchTokens(field, newData),
(t) => `${t.lang}#${t.kind}#${t.token}`
)
}
/**
* Builds the FieldValueIndexTable partition key for one text-search token.
* The explicit `#txt#kind:token` segment keeps this key shape structurally
* distinct from a reservation/equality key (`entityId#fieldId#lang#value`) —
* not strictly required for correctness (a hypothetical collision is a
* wasted-candidate problem, not a wrong-result problem, since every contains
* query is verified against real data — see resolveContainsCandidates), but
* cheap and keeps the raw table legible.
*/
function buildTextSearchKey(entityId, fieldId, lang, kind, token) {
return `${entityId}#${fieldId}#${lang}#txt#${kind}:${token}`
}
/** A BatchWriteItem `PutRequest` indexing `itemId` under one text-search token. */
function buildTextSearchPutRequest(entityId, fieldId, lang, kind, token, itemId) {
return {
PutRequest: {
Item: {
pk: buildTextSearchKey(entityId, fieldId, lang, kind, token),
sk: itemId,
entityId,
fieldId,
itemId
}
}
}
}
/** A BatchWriteItem `DeleteRequest` removing one text-search index row. */
function buildTextSearchDeleteRequest(entityId, fieldId, lang, kind, token, itemId) {
return {
DeleteRequest: {
Key: { pk: buildTextSearchKey(entityId, fieldId, lang, kind, token), sk: itemId }
}
}
}
/**
* Returns the set of item ids indexed under one exact token (paginated,
* bounded by `maxResults`) — the coarse candidate-generation step of a
* contains query, see resolveContainsCandidates for the full pipeline.
*/
async function queryItemIdsForTextSearchToken(
docClient,
tableName,
entityId,
fieldId,
lang,
kind,
token,
{ maxResults = Infinity } = {}
) {
const pk = buildTextSearchKey(entityId, fieldId, lang, kind, token)
return queryIdsForExactPk(docClient, tableName, pk, 'itemId', { maxResults })
}
/**
* Resolves a `contains` filter for the large-entity indexed path: for each
* search value (already validated elsewhere as a single word, >=
* MIN_QUERY_LENGTH normalized characters), queries one seed trigram (the
* value's first 3 normalized characters) per candidate language, unions the
* results across values/languages, then verifies every candidate against the
* item's *actual* stored value before returning it.
*
* Why a single seed trigram is provably sufficient (no false negatives):
* tokenization only splits on non-letter/digit runs, so a normalized query
* word that truly occurs inside a field's value must lie entirely within one
* tokenized word of that value (a run of letters/digits can't itself span a
* tokenizer boundary). That word is therefore at least as long as the query,
* so it went through the sliding-window branch at index time — meaning the
* query's own first 3 characters are necessarily one of that word's indexed
* windows. The candidate set is a superset though (trigram co-occurrence
* doesn't guarantee contiguity — "cat" doesn't mean "category"), so
* verification against the real value is mandatory, not optional, and must
* happen HERE rather than deferred to the caller's final page fetch —
* otherwise filteredTotal/hasMore in items/list.js would be computed against
* an inflated, unverified candidate set and pagination would silently break.
*
* @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
* @param {{ fieldValueIndexTableName: string, itemsTableName: string, entityId: string,
* field: { fieldId: string }, langs: string[], searchValues: string[], maxResults?: number }} params
* @returns {Promise<{ itemIds: Set<string>, truncated: boolean }>}
*/
async function resolveContainsCandidates(
docClient,
{
fieldValueIndexTableName,
itemsTableName,
entityId,
field,
langs,
searchValues,
maxResults = Infinity
}
) {
const coarseIds = new Set()
let truncated = false
for (const rawValue of searchValues) {
const normalized = normalizeForSearch(String(rawValue))
const seedTrigram = normalized.slice(0, TRIGRAM_LENGTH)
for (const lang of langs) {
const ids = await queryItemIdsForTextSearchToken(
docClient,
fieldValueIndexTableName,
entityId,
field.fieldId,
lang,
'trgm',
seedTrigram,
{ maxResults }
)
for (const id of ids) coarseIds.add(id)
if (coarseIds.size >= maxResults) {
truncated = true
break
}
}
}
if (coarseIds.size === 0) return { itemIds: new Set(), truncated }
const candidateIds = [...coarseIds]
const verifiedIds = new Set()
const BATCH_GET_SIZE = 100
for (let i = 0; i < candidateIds.length; i += BATCH_GET_SIZE) {
const batchIds = candidateIds.slice(i, i + BATCH_GET_SIZE)
const result = await docClient.send(
new BatchGetCommand({
RequestItems: {
[itemsTableName]: { Keys: batchIds.map((id) => ({ entityId, id })) }
}
})
)
for (const item of result.Responses?.[itemsTableName] || []) {
if (matchesContains(item, field, langs, searchValues)) {
verifiedIds.add(item.id)
}
}
}
return { itemIds: verifiedIds, truncated }
}
/**
* Small-entity in-memory equivalent: a direct normalized substring check
* against the item's real value, no index involved at all — every value
* present under any candidate language is checked (an item's `en` value
* containing the term is a match, independent of `fr`).
*
* @param {Record<string, unknown>} item
* @param {{ fieldId: string }} field
* @param {string[]} langs candidate languages (unused directly — kept for a
* consistent signature with resolveContainsCandidates; matching considers
* every language the value actually holds)
* @param {Array<string|number|boolean>} searchValues
* @returns {boolean}
*/
function matchesContains(item, field, langs, searchValues) {
const raw = item[field.fieldId]
if (raw === undefined || raw === null || raw === '') return false
const values =
typeof raw === 'string'
? [raw]
: typeof raw === 'object' && !Array.isArray(raw)
? Object.values(raw).filter((v) => typeof v === 'string')
: []
const normalizedValues = values.map((v) => normalizeForSearch(v))
return searchValues.some((searchValue) => {
const needle = normalizeForSearch(String(searchValue))
return normalizedValues.some((v) => v.includes(needle))
})
}
module.exports = {
TEXT_SEARCH_TYPES,
TRIGRAM_LENGTH,
MIN_QUERY_LENGTH,
needsTextSearchIndex,
normalizeForSearch,
tokenizeWords,
tokensForWord,
getTextSearchTokens,
diffTextSearchTokens,
buildTextSearchKey,
buildTextSearchPutRequest,
buildTextSearchDeleteRequest,
queryItemIdsForTextSearchToken,
resolveContainsCandidates,
matchesContains
}
|