-
-
Notifications
You must be signed in to change notification settings - Fork 425
Expand file tree
/
Copy pathuseAlgoliaSearch.ts
More file actions
372 lines (329 loc) · 9.88 KB
/
useAlgoliaSearch.ts
File metadata and controls
372 lines (329 loc) · 9.88 KB
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
import {
liteClient as algoliasearch,
type LiteClient,
type SearchQuery,
type SearchResponse,
} from 'algoliasearch/lite'
let _searchClient: LiteClient | null = null
let _configuredAppId: string | null = null
function getOrCreateClient(appId: string, apiKey: string): LiteClient {
if (!_searchClient || _configuredAppId !== appId) {
_searchClient = algoliasearch(appId, apiKey)
_configuredAppId = appId
}
return _searchClient
}
interface AlgoliaOwner {
name: string
email?: string
avatar?: string
link?: string
}
interface AlgoliaRepo {
url: string
host: string
user: string
project: string
path: string
head?: string
branch?: string
}
/** Shape of a hit from the Algolia `npm-search` index. */
interface AlgoliaHit {
objectID: string
name: string
version: string
description: string | null
modified: number
homepage: string | null
repository: AlgoliaRepo | null
owners: AlgoliaOwner[] | null
downloadsLast30Days: number
downloadsRatio: number
popular: boolean
keywords: string[]
deprecated: boolean | string
isDeprecated: boolean
license: string | null
}
const ATTRIBUTES_TO_RETRIEVE = [
'name',
'version',
'description',
'modified',
'homepage',
'repository',
'owners',
'downloadsLast30Days',
'downloadsRatio',
'popular',
'keywords',
'deprecated',
'isDeprecated',
'license',
]
const EXISTENCE_CHECK_ATTRS = ['name']
function hitToSearchResult(hit: AlgoliaHit): NpmSearchResult {
return {
package: {
name: hit.name,
version: hit.version,
description: hit.description || '',
keywords: hit.keywords,
date: new Date(hit.modified).toISOString(),
links: {
npm: `https://www.npmjs.com/package/${hit.name}`,
homepage: hit.homepage || undefined,
repository: hit.repository?.url || undefined,
},
maintainers: hit.owners
? hit.owners.map(owner => ({
name: owner.name,
email: owner.email,
}))
: [],
},
searchScore: 0,
downloads: {
weekly: Math.round(hit.downloadsLast30Days / 4.3),
},
updated: new Date(hit.modified).toISOString(),
}
}
interface AlgoliaSearchOptions {
size?: number
from?: number
filters?: string
}
/** Extra checks bundled into a single multi-search request. */
export interface AlgoliaMultiSearchChecks {
name?: string
checkOrg?: boolean
checkUser?: boolean
checkPackage?: string
}
interface AlgoliaSearchWithSuggestionsResult {
search: NpmSearchResponse
orgExists: boolean
userExists: boolean
packageExists: boolean | null
}
/**
* Composable providing Algolia search for npm packages.
* Must be called during component setup.
*/
export function useAlgoliaSearch() {
const { algolia } = useRuntimeConfig().public
const client = getOrCreateClient(algolia.appId, algolia.apiKey)
const indexName = algolia.indexName
async function search(
query: string,
options: AlgoliaSearchOptions = {},
): Promise<NpmSearchResponse> {
const { results } = await client.search({
requests: [
{
indexName,
query,
offset: options.from,
length: options.size,
filters: options.filters || '',
analyticsTags: ['npmx.dev'],
attributesToRetrieve: ATTRIBUTES_TO_RETRIEVE,
attributesToHighlight: [],
} satisfies SearchQuery,
],
})
const response = results[0] as SearchResponse<AlgoliaHit> | undefined
if (!response) {
throw new Error('Algolia returned an empty response')
}
return {
isStale: false,
objects: response.hits.map(hitToSearchResult),
total: response.nbHits ?? 0,
time: new Date().toISOString(),
}
}
/** Fetch all packages for an owner using `owner.name` filter with pagination. */
async function searchByOwner(
ownerName: string,
options: { maxResults?: number } = {},
): Promise<NpmSearchResponse> {
const max = options.maxResults ?? 1000
const allHits: AlgoliaHit[] = []
let offset = 0
let serverTotal = 0
const batchSize = 200
while (offset < max) {
const remaining = serverTotal > 0 ? Math.min(max, serverTotal) - offset : max - offset
if (remaining <= 0) break
const length = Math.min(batchSize, remaining)
const { results } = await client.search({
requests: [
{
indexName,
query: '',
offset,
length,
filters: `owner.name:${ownerName}`,
analyticsTags: ['npmx.dev'],
attributesToRetrieve: ATTRIBUTES_TO_RETRIEVE,
attributesToHighlight: [],
} satisfies SearchQuery,
],
})
const response = results[0] as SearchResponse<AlgoliaHit> | undefined
if (!response) break
serverTotal = response.nbHits ?? 0
allHits.push(...response.hits)
if (response.hits.length < length || allHits.length >= serverTotal) {
break
}
offset += length
}
return {
isStale: false,
objects: allHits.map(hitToSearchResult),
total: serverTotal,
time: new Date().toISOString(),
}
}
/** Fetch metadata for a single batch of packages (max 1000) by exact name. */
async function getPackagesByNameSlice(names: string[]): Promise<NpmSearchResult[]> {
if (names.length === 0) return []
const response = await $fetch<{ results: (AlgoliaHit | null)[] }>(
`https://${algolia.appId}-dsn.algolia.net/1/indexes/*/objects`,
{
method: 'POST',
headers: {
'x-algolia-api-key': algolia.apiKey,
'x-algolia-application-id': algolia.appId,
},
body: {
requests: names.map(name => ({
indexName,
objectID: name,
attributesToRetrieve: ATTRIBUTES_TO_RETRIEVE,
})),
},
},
)
return response.results
.filter((r): r is AlgoliaHit => r !== null && 'name' in r)
.map(hitToSearchResult)
}
/** Fetch metadata for specific packages by exact name using Algolia's getObjects API. */
async function getPackagesByName(packageNames: string[]): Promise<NpmSearchResponse> {
if (packageNames.length === 0) {
return { isStale: false, objects: [], total: 0, time: new Date().toISOString() }
}
// Algolia getObjects has a limit of 1000 objects per request, so batch if needed
const BATCH_SIZE = 1000
const batches: string[][] = []
for (let i = 0; i < packageNames.length; i += BATCH_SIZE) {
batches.push(packageNames.slice(i, i + BATCH_SIZE))
}
const results = await Promise.all(batches.map(batch => getPackagesByNameSlice(batch)))
const allObjects = results.flat()
return {
isStale: false,
objects: allObjects,
total: allObjects.length,
time: new Date().toISOString(),
}
}
/**
* Combined search + org/user/package existence checks in a single
* Algolia multi-search request.
*/
async function searchWithSuggestions(
query: string,
options: AlgoliaSearchOptions = {},
checks?: AlgoliaMultiSearchChecks,
): Promise<AlgoliaSearchWithSuggestionsResult> {
const requests: SearchQuery[] = [
{
indexName,
query,
offset: options.from,
length: options.size,
filters: options.filters || '',
analyticsTags: ['npmx.dev'],
attributesToRetrieve: ATTRIBUTES_TO_RETRIEVE,
attributesToHighlight: [],
},
]
const orgQueryIndex = checks?.checkOrg && checks.name ? requests.length : -1
if (checks?.checkOrg && checks.name) {
requests.push({
indexName,
query: `"@${checks.name}"`,
length: 1,
analyticsTags: ['npmx.dev'],
attributesToRetrieve: EXISTENCE_CHECK_ATTRS,
attributesToHighlight: [],
})
}
const userQueryIndex = checks?.checkUser && checks.name ? requests.length : -1
if (checks?.checkUser && checks.name) {
requests.push({
indexName,
query: '',
filters: `owner.name:${checks.name}`,
length: 1,
analyticsTags: ['npmx.dev'],
attributesToRetrieve: EXISTENCE_CHECK_ATTRS,
attributesToHighlight: [],
})
}
const packageQueryIndex = checks?.checkPackage ? requests.length : -1
if (checks?.checkPackage) {
requests.push({
indexName,
query: '',
filters: `objectID:${checks.checkPackage}`,
length: 1,
analyticsTags: ['npmx.dev'],
attributesToRetrieve: EXISTENCE_CHECK_ATTRS,
attributesToHighlight: [],
})
}
const { results } = await client.search({ requests })
const mainResponse = results[0] as SearchResponse<AlgoliaHit> | undefined
if (!mainResponse) {
throw new Error('Algolia returned an empty response')
}
const searchResult: NpmSearchResponse = {
isStale: false,
objects: mainResponse.hits.map(hitToSearchResult),
total: mainResponse.nbHits ?? 0,
time: new Date().toISOString(),
}
let orgExists = false
if (orgQueryIndex >= 0 && checks?.name) {
const orgResponse = results[orgQueryIndex] as SearchResponse<AlgoliaHit> | undefined
const scopePrefix = `@${checks.name.toLowerCase()}/`
orgExists =
orgResponse?.hits?.some(h => h.name?.toLowerCase().startsWith(scopePrefix)) ?? false
}
let userExists = false
if (userQueryIndex >= 0) {
const userResponse = results[userQueryIndex] as SearchResponse<AlgoliaHit> | undefined
userExists = (userResponse?.nbHits ?? 0) > 0
}
let packageExists: boolean | null = null
if (packageQueryIndex >= 0) {
const pkgResponse = results[packageQueryIndex] as SearchResponse<AlgoliaHit> | undefined
packageExists = (pkgResponse?.nbHits ?? 0) > 0
}
return { search: searchResult, orgExists, userExists, packageExists }
}
return {
search,
searchWithSuggestions,
searchByOwner,
getPackagesByName,
getPackagesByNameSlice,
}
}