1 import { parseSearchParams, stringifyParams } from "./request"
2 import {
3 HighlightResultNode,
4 InstantSearchFacetHit,
5 InstantSearchFacetSearchResponse,
6 InstantSearchHighlightResult,
7 InstantSearchHit,
8 InstantSearchRequest,
9 InstantSearchSearchResponse,
10 SearchFacetResult,
11 SearchHit,
12 SearchResult,
13 } from "./types"
14
15 const DEFAULT_PRE_TAG = "<mark>"
16 const DEFAULT_POST_TAG = "</mark>"
17
18 function setByPath(
19 target: Record<string, HighlightResultNode>,
20 path: string,
21 value: InstantSearchHighlightResult
22 ): void {
23 const parts = path.split(".")
24 let current: Record<string, HighlightResultNode> = target
25
26 for (let i = 0; i < parts.length - 1; i++) {
27 const part = parts[i]
28 const existing = current[part]
29 if (!existing || typeof existing !== "object" || "value" in existing) {
30 current[part] = {}
31 }
32 current = current[part] as Record<string, HighlightResultNode>
33 }
34
35 current[parts[parts.length - 1]] = value
36 }
37
38 function extractMatchedWords(
39 value: string,
40 preTag: string,
41 postTag: string
42 ): string[] {
43 const words: string[] = []
44 let remaining = value
45
46 while (remaining.length) {
47 const start = remaining.indexOf(preTag)
48 if (start === -1) {
49 break
50 }
51 const after = remaining.slice(start + preTag.length)
52 const end = after.indexOf(postTag)
53 if (end === -1) {
54 break
55 }
56 const word = after.slice(0, end)
57 if (word) {
58 words.push(word)
59 }
60 remaining = after.slice(end + postTag.length)
61 }
62
63 return words
64 }
65
66 function adaptHighlightValue(
67 value: string,
68 preTag: string,
69 postTag: string
70 ): string {
71 if (preTag === DEFAULT_PRE_TAG && postTag === DEFAULT_POST_TAG) {
72 return value
73 }
74 return value
75 .split(DEFAULT_PRE_TAG)
76 .join(preTag)
77 .split(DEFAULT_POST_TAG)
78 .join(postTag)
79 }
80
81 function toHighlightResult(
82 fragments: string[],
83 preTag: string,
84 postTag: string
85 ): InstantSearchHighlightResult {
86 const value = adaptHighlightValue(fragments.join(" … "), preTag, postTag)
87 const matchedWords = extractMatchedWords(value, preTag, postTag)
88
89 return {
90 value,
91 matchLevel: matchedWords.length ? "full" : "none",
92 matchedWords,
93 }
94 }
95
96 function adaptHighlights(
97 highlights: Record<string, string[]> | undefined,
98 preTag: string,
99 postTag: string
100 ): Record<string, HighlightResultNode> | undefined {
101 if (!highlights) {
102 return undefined
103 }
104
105 const result: Record<string, HighlightResultNode> = {}
106 for (const [path, fragments] of Object.entries(highlights)) {
107 if (!fragments?.length) {
108 continue
109 }
110 setByPath(result, path, toHighlightResult(fragments, preTag, postTag))
111 }
112
113 return Object.keys(result).length ? result : undefined
114 }
115
116 function asDocument(document: unknown): Record<string, unknown> {
117 if (document && typeof document === "object" && !Array.isArray(document)) {
118 return document as Record<string, unknown>
119 }
120 return {}
121 }
122
123 function adaptHit(
124 hit: SearchHit,
125 options: {
126 primaryKey: string
127 preTag: string
128 postTag: string
129 snippet: boolean
130 }
131 ): InstantSearchHit {
132 const document = asDocument(hit.document)
133 const objectID = String(
134 hit.id ?? document[options.primaryKey] ?? document.id ?? ""
135 )
136 const adapted: InstantSearchHit = {
137 ...document,
138 objectID,
139 }
140
141 const highlightResult = adaptHighlights(
142 hit.highlights,
143 options.preTag,
144 options.postTag
145 )
146 if (highlightResult) {
147 if (options.snippet) {
148 adapted._snippetResult = highlightResult
149 } else {
150 adapted._highlightResult = highlightResult
151 }
152 }
153
154 if (hit.score != null) {
155 adapted._score = hit.score
156 }
157
158 return adapted
159 }
160
161 function adaptFacets(facets: Record<string, SearchFacetResult> | undefined): {
162 facets?: Record<string, Record<string, number>>
163 facets_stats?: Record<
164 string,
165 { min: number; max: number; avg?: number; sum?: number }
166 >
167 } {
168 if (!facets) {
169 return {}
170 }
171
172 const values: Record<string, Record<string, number>> = {}
173 const stats: Record<
174 string,
175 { min: number; max: number; avg?: number; sum?: number }
176 > = {}
177
178 for (const [field, facet] of Object.entries(facets)) {
179 if (facet.type === "value") {
180 values[field] = Object.fromEntries(
181 facet.values.map((entry) => [entry.value, entry.count])
182 )
183 } else if (facet.type === "stats") {
184 stats[field] = {
185 min: facet.min,
186 max: facet.max,
187 ...(facet.avg != null ? { avg: facet.avg } : {}),
188 ...(facet.sum != null ? { sum: facet.sum } : {}),
189 }
190 // InstantSearch's helper only copies `facets_stats` onto keys present in
191 // `facets`. Range widgets then read `results.disjunctiveFacets[].stats`.
192 if (!values[field]) {
193 values[field] = {}
194 }
195 } else if (facet.type === "range") {
196 values[field] = Object.fromEntries(
197 facet.ranges.map((entry) => [entry.key, entry.count])
198 )
199 }
200 }
201
202 return {
203 ...(Object.keys(values).length ? { facets: values } : {}),
204 ...(Object.keys(stats).length ? { facets_stats: stats } : {}),
205 }
206 }
207
208 export function adaptSearchResponse(
209 result: SearchResult,
210 request: InstantSearchRequest,
211 options: { primaryKey?: string } = {}
212 ): InstantSearchSearchResponse {
213 const params = parseSearchParams(request.params)
214 const hitsPerPage = params.hitsPerPage ?? result.metadata.take
215 const skip = result.metadata.skip ?? 0
216 const page =
217 params.page ?? (hitsPerPage > 0 ? Math.floor(skip / hitsPerPage) : 0)
218 const hitCount = result.hits.length
219 // No total from the engine (`count: "none"`). A full page means there may
220 // be more hits — InstantSearch needs nbHits past this page to show "next".
221 const nbHits =
222 result.metadata.count ??
223 (hitsPerPage > 0 && hitCount >= hitsPerPage
224 ? skip + hitCount + 1
225 : skip + hitCount)
226 const nbPages =
227 hitsPerPage > 0 && nbHits > 0 ? Math.ceil(nbHits / hitsPerPage) : 0
228 const preTag = params.highlightPreTag ?? DEFAULT_PRE_TAG
229 const postTag = params.highlightPostTag ?? DEFAULT_POST_TAG
230 const snippet = Boolean(params.attributesToSnippet?.length)
231 const primaryKey = options.primaryKey ?? "id"
232 const { facets, facets_stats } = adaptFacets(result.facets)
233
234 return {
235 hits: (result.hits ?? []).map((hit) =>
236 adaptHit(hit, { primaryKey, preTag, postTag, snippet })
237 ),
238 nbHits,
239 page,
240 nbPages,
241 hitsPerPage,
242 processingTimeMS: result.metadata.processing_time_ms ?? 0,
243 query: result.metadata.query ?? params.query ?? "",
244 params: stringifyParams(params),
245 index: request.indexName,
246 exhaustiveNbHits: result.metadata.count != null,
247 exhaustiveFacetsCount: true,
248 ...(facets ? { facets } : {}),
249 ...(facets_stats ? { facets_stats } : {}),
250 }
251 }
252
253 export function createEmptySearchResponse(
254 request: InstantSearchRequest
255 ): InstantSearchSearchResponse {
256 const params = parseSearchParams(request.params)
257 const hitsPerPage = params.hitsPerPage ?? 0
258 const page = params.page ?? 0
259
260 return {
261 hits: [],
262 nbHits: 0,
263 page,
264 nbPages: 0,
265 hitsPerPage,
266 processingTimeMS: 0,
267 query: params.query ?? "",
268 params: stringifyParams(params),
269 index: request.indexName,
270 exhaustiveNbHits: true,
271 exhaustiveFacetsCount: true,
272 }
273 }
274
275 function highlightFacetValue(value: string, query: string | undefined): string {
276 if (!query) {
277 return value
278 }
279 const index = value.toLowerCase().indexOf(query.toLowerCase())
280 if (index === -1) {
281 return value
282 }
283 return (
284 value.slice(0, index) +
285 DEFAULT_PRE_TAG +
286 value.slice(index, index + query.length) +
287 DEFAULT_POST_TAG +
288 value.slice(index + query.length)
289 )
290 }
291
292 export function adaptFacetSearchResponse(
293 result: SearchResult,
294 request: InstantSearchRequest
295 ): InstantSearchFacetSearchResponse {
296 const params = parseSearchParams(request.params)
297 const facetName = params.facetName
298 const facet = facetName ? result.facets?.[facetName] : undefined
299 const facetHits: InstantSearchFacetHit[] =
300 facet?.type === "value"
301 ? facet.values.map((entry) => ({
302 value: entry.value,
303 highlighted: highlightFacetValue(entry.value, params.facetQuery),
304 count: entry.count,
305 }))
306 : []
307
308 return {
309 facetHits,
310 exhaustiveFacetsCount: true,
311 processingTimeMS: result.metadata.processing_time_ms ?? 0,
312 }
313 }
314
315 export function createEmptyFacetSearchResponse(): InstantSearchFacetSearchResponse {
316 return {
317 facetHits: [],
318 exhaustiveFacetsCount: true,
319 processingTimeMS: 0,
320 }
321 }