1 import { SearchTypes } from "@medusajs/framework/types"
2 import {
3 MedusaError,
4 readDocumentPath,
5 setDocumentPath,
6 } from "@medusajs/framework/utils"
7 import type { AttributeSchema, AttributeSchemaConfig, Row } from "./api-types"
8 import type {
9 MedusaSearchFieldOptions,
10 MedusaSearchIndexOptions,
11 } from "./options"
12
13 export type PlannedField = {
14 path: string
15 type: string
16 is_array: boolean
17 is_date: boolean
18 field: SearchTypes.SearchFieldDefinition
19 dimensions?: number
20 embed?: boolean
21 }
22
23 export type TypoToleranceSettings = {
24 enabled: boolean
25 min_word_size_for_one_typo: number
26 min_word_size_for_two_typos: number
27 disabled_on_attributes: Set<string>
28 }
29
30 export type IndexPlan = {
31 fields: Map<string, PlannedField>
32 schema: Record<string, AttributeSchema>
33 searchable: string[]
34 primary_key: string
35 options: MedusaSearchIndexOptions
36 typo_tolerance: TypoToleranceSettings
37 vectors: string[]
38 }
39
40 function fail(message: string): never {
41 throw new MedusaError(MedusaError.Types.NOT_ALLOWED, message)
42 }
43
44 /**
45 * Cloud only matches a term fuzzily when the query is at least
46 * `3 * (distance + 1)` characters long, so the shortest word that can tolerate
47 * one typo is 6 characters and two typos is 9. Configuring anything lower is
48 * rejected at `upsertIndex` rather than silently raised.
49 */
50 export function minWordSizeForTypos(distance: number): number {
51 return 3 * (distance + 1)
52 }
53
54 const DEFAULT_MIN_WORD_SIZE_FOR_ONE_TYPO = minWordSizeForTypos(1)
55 const DEFAULT_MIN_WORD_SIZE_FOR_TWO_TYPOS = minWordSizeForTypos(2)
56
57 function resolveTypoTolerance(
58 settings: SearchTypes.SearchIndexSettings
59 ): TypoToleranceSettings {
60 const typo = settings.typo_tolerance
61 return {
62 enabled: typo?.enabled ?? true,
63 min_word_size_for_one_typo:
64 typo?.min_word_size_for_one_typo ?? DEFAULT_MIN_WORD_SIZE_FOR_ONE_TYPO,
65 min_word_size_for_two_typos:
66 typo?.min_word_size_for_two_typos ?? DEFAULT_MIN_WORD_SIZE_FOR_TWO_TYPOS,
67 disabled_on_attributes: new Set(typo?.disabled_on_attributes ?? []),
68 }
69 }
70
71 export function isSearchable(
72 field: SearchTypes.SearchFieldDefinition
73 ): boolean {
74 return field.searchable === true || typeof field.searchable === "object"
75 }
76
77 export function isFacetable(field: SearchTypes.SearchFieldDefinition): boolean {
78 return field.facetable === true || typeof field.facetable === "object"
79 }
80
81 function providerOptions<T>(value: {
82 provider_options?: Record<string, Record<string, unknown>>
83 }): T {
84 return (value.provider_options?.["search-medusa"] ?? {}) as T
85 }
86
87 function fieldType(
88 field: SearchTypes.SearchFieldDefinition,
89 isArray: boolean
90 ): string {
91 const array = isArray ? "[]" : ""
92
93 switch (field.type) {
94 case "keyword":
95 case "text":
96 return `${array}string`
97 case "integer":
98 return `${array}int`
99 case "float":
100 return `${array}float`
101 case "boolean":
102 return `${array}bool`
103 case "date":
104 return `${array}datetime`
105 case "vector":
106 if (isArray) {
107 fail("Medusa search vector fields cannot be arrays")
108 }
109 if (!field.dimensions || field.dimensions < 1) {
110 fail("Medusa search vector fields must declare positive dimensions")
111 }
112 return `[${field.dimensions}]f32`
113 case "geo":
114 return fail("The Medusa search provider does not support geo fields")
115 default:
116 return fail(
117 `The Medusa search provider does not support fields of type "${field.type}"`
118 )
119 }
120 }
121
122 function assertTypoToleranceSupported(
123 settings: SearchTypes.SearchIndexSettings,
124 paths: Set<string>
125 ): void {
126 const typo = settings.typo_tolerance
127 if (!typo) {
128 return
129 }
130
131 const thresholds = [
132 ["min_word_size_for_one_typo", typo.min_word_size_for_one_typo, 1],
133 ["min_word_size_for_two_typos", typo.min_word_size_for_two_typos, 2],
134 ] as const
135
136 for (const [name, value, distance] of thresholds) {
137 const minimum = minWordSizeForTypos(distance)
138 if (value !== undefined && value < minimum) {
139 fail(
140 `Medusa search requires settings.typo_tolerance.${name} to be at least ${minimum} to tolerate ${distance} ${
141 distance === 1 ? "typo" : "typos"
142 }, got ${value}`
143 )
144 }
145 }
146
147 const one = typo.min_word_size_for_one_typo
148 const two = typo.min_word_size_for_two_typos
149 if (one !== undefined && two !== undefined && two < one) {
150 fail(
151 `settings.typo_tolerance.min_word_size_for_two_typos (${two}) cannot be lower than min_word_size_for_one_typo (${one})`
152 )
153 }
154
155 for (const path of typo.disabled_on_attributes ?? []) {
156 if (!paths.has(path)) {
157 fail(
158 `settings.typo_tolerance.disabled_on_attributes references "${path}", which is not a field on this index`
159 )
160 }
161 }
162 }
163
164 export function assertIndexSupported(
165 definition: SearchTypes.ResolvedSearchIndexDefinition
166 ): void {
167 const paths = new Set<string>()
168
169 const walk = (
170 group: Record<string, SearchTypes.SearchFieldDefinition>,
171 prefix: string
172 ) => {
173 for (const [name, field] of Object.entries(group)) {
174 const path = prefix ? `${prefix}.${name}` : name
175
176 if (field.type === "object") {
177 if (field.fields) {
178 walk(field.fields, path)
179 }
180 continue
181 }
182
183 fieldType(field, !!field.array)
184 paths.add(path)
185 }
186 }
187
188 walk(definition.fields, "")
189 assertTypoToleranceSupported(definition.settings, paths)
190 }
191
192 export function buildIndexPlan(
193 definition: SearchTypes.ResolvedSearchIndexDefinition
194 ): IndexPlan {
195 assertIndexSupported(definition)
196
197 const fields = new Map<string, PlannedField>()
198 const schema: Record<string, AttributeSchema> = {}
199 const searchable: string[] = []
200 const typoTolerance = resolveTypoTolerance(definition.settings)
201
202 const walk = (
203 group: Record<string, SearchTypes.SearchFieldDefinition>,
204 prefix: string,
205 inArray: boolean
206 ) => {
207 for (const [name, field] of Object.entries(group)) {
208 const path = prefix ? `${prefix}.${name}` : name
209 const isArray = inArray || field.array === true
210
211 if (field.type === "object") {
212 if (field.fields) {
213 walk(field.fields, path, isArray)
214 }
215 continue
216 }
217
218 const configured = providerOptions<MedusaSearchFieldOptions>(field)
219 const type = fieldType(field, isArray)
220 const searchableField = isSearchable(field)
221 const indexed =
222 field.filterable ||
223 field.sortable ||
224 isFacetable(field) ||
225 path === definition.primary_key
226
227 const attribute: AttributeSchemaConfig = {
228 type,
229 filterable: !!indexed,
230 }
231
232 if (field.type === "vector") {
233 attribute.ann = configured.ann ?? true
234 if (field.embed) {
235 attribute.embed = {
236 ...(field.dimensions ? { dims: field.dimensions } : {}),
237 }
238 }
239 }
240
241 if (searchableField) {
242 attribute.full_text_search = configured.full_text_search ?? true
243 searchable.push(path)
244
245 // Typo tolerance needs a fuzzy index on the field it matches
246 // against — built by default alongside full-text search unless the
247 // index or the field opts out.
248 if (
249 typoTolerance.enabled &&
250 !typoTolerance.disabled_on_attributes.has(path)
251 ) {
252 attribute.fuzzy = true
253 }
254 }
255
256 // Glob is an exact-string wildcard index. Keywords that are
257 // filtered/sorted/faceted get it by default; text fields only if
258 // opted in. `id` is the Cloud document key and cannot carry one.
259 if (path !== "id") {
260 if (configured.glob !== undefined) {
261 attribute.glob = configured.glob
262 } else if (indexed && field.type === "keyword") {
263 attribute.glob = true
264 }
265 }
266 if (configured.regex !== undefined) {
267 attribute.regex = configured.regex
268 }
269
270 fields.set(path, {
271 path,
272 type,
273 is_array: isArray,
274 is_date: field.type === "date",
275 field,
276 dimensions: field.dimensions,
277 embed: field.embed,
278 })
279
280 schema[path] = attribute
281 }
282 }
283
284 walk(definition.fields, "", false)
285
286 const vectors: string[] = []
287 for (const planned of fields.values()) {
288 if (planned.field.type === "vector") {
289 vectors.push(planned.path)
290 }
291 }
292
293 return {
294 fields,
295 schema,
296 searchable,
297 primary_key: definition.primary_key,
298 options: providerOptions<MedusaSearchIndexOptions>(definition.settings),
299 typo_tolerance: typoTolerance,
300 vectors,
301 }
302 }
303
304 function coerce(value: unknown, planned: PlannedField): unknown {
305 if (value instanceof Date) {
306 return value.toISOString()
307 }
308 if (planned.is_date && typeof value === "string") {
309 return new Date(value).toISOString()
310 }
311 return value
312 }
313
314 function coerceVector(value: unknown, planned: PlannedField): number[] {
315 if (!Array.isArray(value) || !value.length) {
316 fail(
317 `Vector field "${planned.path}" must be a numeric array of length ${planned.dimensions}`
318 )
319 }
320
321 const nums = value.map((entry) => Number(entry))
322 if (nums.some((n) => Number.isNaN(n))) {
323 fail(`Vector field "${planned.path}" contains non-numeric components`)
324 }
325
326 if (planned.dimensions && nums.length !== planned.dimensions) {
327 fail(
328 `Vector field "${planned.path}" expected ${planned.dimensions} dimensions, got ${nums.length}`
329 )
330 }
331
332 return nums
333 }
334
335 export function toSearchDocument(
336 document: SearchTypes.SearchDocument,
337 plan: IndexPlan
338 ): Row {
339 const target: Record<string, unknown> = {}
340
341 for (const planned of plan.fields.values()) {
342 if (planned.field.type === "vector") {
343 // `readDocumentPath` flattens arrays; a vector is one value.
344 const raw = planned.path
345 .split(".")
346 .reduce<unknown>(
347 (value, segment) =>
348 value && typeof value === "object"
349 ? (value as Record<string, unknown>)[segment]
350 : undefined,
351 document
352 )
353 if (raw === undefined || raw === null) {
354 continue
355 }
356
357 // Engine-embedded fields accept the source text; the proxy embeds it
358 // into the `[N]f32` column before storage.
359 if (planned.embed) {
360 if (typeof raw !== "string") {
361 fail(`Vector field "${planned.path}" with embed must be a string`)
362 }
363 const text = raw.trim()
364 if (text) {
365 target[planned.path] = text
366 }
367 continue
368 }
369
370 target[planned.path] = coerceVector(raw, planned)
371 continue
372 }
373
374 const values = readDocumentPath(document, planned.path.split("."))
375 .map((value) => coerce(value, planned))
376 .filter((value) => value !== undefined)
377
378 if (!values.length) {
379 continue
380 }
381
382 target[planned.path] = planned.is_array ? values : values[0]
383 }
384
385 const primaryKey = document[plan.primary_key]
386 if (primaryKey === undefined || primaryKey === null || primaryKey === "") {
387 fail(
388 `A document written to Medusa search is missing primary key "${plan.primary_key}"`
389 )
390 }
391
392 const id = String(primaryKey)
393 if (Buffer.byteLength(id, "utf8") > 64) {
394 fail(`Medusa search document IDs cannot exceed 64 bytes ("${id}")`)
395 }
396
397 target.id = id
398 return target as Row
399 }
400
401 export function fromSearchDocument(
402 row: Row,
403 attributes: string[]
404 ): Record<string, unknown> {
405 const result: Record<string, unknown> = {}
406
407 for (const path of attributes) {
408 const value = row[path]
409 if (value !== undefined) {
410 setDocumentPath(result, path, value)
411 }
412 }
413
414 return result
415 }