1 import { SearchTypes } from "@medusajs/framework/types"
2 import {
3 extractPrimaryKeyFilter,
4 MedusaError,
5 projectDocument,
6 readDocumentPath,
7 searchValueToBoolean,
8 searchValueToNumber,
9 setDocumentPath,
10 } from "@medusajs/framework/utils"
11 import { IndexPlan, PlannedField, weightLabel } from "./plan"
12
13 // Path flattening, projection and primary-key extraction live in
14 // @medusajs/utils so every provider collapses documents identically.
15 export { extractPrimaryKeyFilter, projectDocument }
16
17 function fail(message: string): never {
18 throw new MedusaError(MedusaError.Types.NOT_ALLOWED, message)
19 }
20
21 function coerce(value: unknown, planned: PlannedField): unknown {
22 switch (planned.kind) {
23 case "number":
24 return searchValueToNumber(value, planned.is_date)
25 case "boolean":
26 return searchValueToBoolean(value)
27 case "text":
28 case "keyword":
29 return typeof value === "string" ? value : String(value)
30 case "vector":
31 return value
32 default:
33 return value
34 }
35 }
36
37 function coerceVector(
38 value: unknown,
39 planned: PlannedField
40 ): number[] | undefined {
41 if (!Array.isArray(value)) {
42 fail(
43 `Vector field "${planned.path}" must be a numeric array of length ${planned.dimensions}`
44 )
45 }
46
47 const nums = value.map((entry) => Number(entry))
48 if (nums.some((n) => Number.isNaN(n))) {
49 fail(`Vector field "${planned.path}" contains non-numeric components`)
50 }
51
52 if (planned.dimensions && nums.length !== planned.dimensions) {
53 fail(
54 `Vector field "${planned.path}" expected ${planned.dimensions} dimensions, got ${nums.length}`
55 )
56 }
57
58 return nums
59 }
60
61 /**
62 * Projects a source document onto the indexed shape used for filters and FTS,
63 * and returns the primary key plus the searchable plain-text blob and vectors.
64 */
65 export function projectIndexedDocument(
66 document: SearchTypes.SearchDocument,
67 plan: IndexPlan
68 ): {
69 id: string
70 indexed: Record<string, unknown>
71 search_text: string
72 weighted_parts: { text: string; weight: "A" | "B" | "C" | "D" }[]
73 vectors: Record<string, number[]>
74 } {
75 const indexed: Record<string, any> = {}
76 const textParts: string[] = []
77 const weighted_parts: { text: string; weight: "A" | "B" | "C" | "D" }[] = []
78 const vectors: Record<string, number[]> = {}
79
80 for (const planned of plan.fields.values()) {
81 const values = readDocumentPath(document, planned.path.split(".")).filter(
82 (value) => value !== undefined && value !== null
83 )
84
85 if (!values.length) {
86 continue
87 }
88
89 if (planned.kind === "vector") {
90 // Engine-embedded fields are produced from this field's text via
91 // the embedder — never store a client-supplied vector for them.
92 if (planned.field.embed) {
93 continue
94 }
95
96 const embedding = coerceVector(values[0], planned)
97 if (embedding) {
98 vectors[planned.path] = embedding
99 }
100 continue
101 }
102
103 const coerced = values
104 .map((value) => coerce(value, planned))
105 .filter((value) => value !== undefined)
106
107 if (!coerced.length) {
108 continue
109 }
110
111 const value = planned.is_array ? coerced : coerced[0]
112 setDocumentPath(indexed, planned.path, value)
113
114 if (
115 planned.kind === "text" ||
116 planned.kind === "keyword" ||
117 (planned.kind === "number" && !planned.is_date)
118 ) {
119 const asText = (Array.isArray(value) ? value : [value])
120 .map((entry) => String(entry))
121 .join(" ")
122
123 if (
124 planned.field.searchable === true ||
125 typeof planned.field.searchable === "object"
126 ) {
127 textParts.push(asText)
128 weighted_parts.push({
129 text: asText,
130 weight: weightLabel(planned.field.searchable),
131 })
132 }
133 }
134 }
135
136 const primaryKey = document[plan.primary_key]
137
138 if (primaryKey === undefined || primaryKey === null || primaryKey === "") {
139 fail(
140 `A document written to the postgres search provider is missing its primary key "${plan.primary_key}"`
141 )
142 }
143
144 return {
145 id: String(primaryKey),
146 indexed,
147 search_text: textParts.join(" "),
148 weighted_parts,
149 vectors,
150 }
151 }
152
153 /**
154 * Plain text the engine embedder should encode for an `embed: true` vector
155 * field. Missing/blank values return undefined so the vector column can stay
156 * null.
157 */
158 export function sourceTextForEmbed(
159 document: SearchTypes.SearchDocument,
160 path: string
161 ): string | undefined {
162 const values = readDocumentPath(document, path.split(".")).filter(
163 (value) => value !== undefined && value !== null
164 )
165
166 if (!values.length) {
167 return undefined
168 }
169
170 const value = values[0]
171 if (typeof value !== "string") {
172 fail(`Vector field "${path}" with embed must be a string`)
173 }
174
175 const text = value.trim()
176 return text || undefined
177 }