1 import { MedusaError } from "@medusajs/framework/utils"
2 import { parseRetryAfter } from "../../../utils/rate-limit"
3 import type {
4 IndexCreateParams,
5 IndexMetadata,
6 IndexMultiQueryParams,
7 IndexMultiQueryResponse,
8 IndexQuery,
9 IndexQueryResult,
10 IndexSummary,
11 IndexWriteParams,
12 IndexWriteResponse,
13 AttributeSchema,
14 } from "./api-types"
15 import type {
16 MedusaSearchProviderOptions,
17 ResolvedMedusaSearchProviderOptions,
18 } from "./options"
19
20 /**
21 * Cloud proxy error envelope — same shape as Medusa payments.
22 */
23 export class CloudServiceError extends Error {
24 type: string
25 originalType: string
26 data: any
27 message: string
28 status?: number
29 /** How long Cloud asked the caller to wait, in milliseconds. */
30 retry_after?: number
31
32 constructor(
33 type: string,
34 originalType: string,
35 data: any,
36 message: string,
37 status?: number,
38 retryAfter?: number
39 ) {
40 super(message)
41 this.name = "CloudServiceError"
42 this.type = type
43 this.originalType = originalType
44 this.data = data
45 this.message = message
46 this.status = status
47 this.retry_after = retryAfter
48 }
49
50 get isNotFound(): boolean {
51 return this.status === 404
52 }
53 }
54
55 type RequestInitWithBody = Omit<RequestInit, "body"> & { body?: object }
56
57 /**
58 * Thin HTTP client for the Medusa Cloud search proxy. The provider passes
59 * Medusa index names; Cloud maps them to upstream storage for the environment.
60 */
61 export class MedusaSearchClient {
62 protected readonly options_: ResolvedMedusaSearchProviderOptions
63 protected readonly fetch_: typeof fetch
64
65 constructor(
66 options: ResolvedMedusaSearchProviderOptions,
67 { fetchImpl }: { fetchImpl?: typeof fetch } = {}
68 ) {
69 this.options_ = options
70 this.fetch_ = fetchImpl ?? ((input, init) => globalThis.fetch(input, init))
71 }
72
73 index(name: string): MedusaSearchIndex {
74 return new MedusaSearchIndex(this, name)
75 }
76
77 createIndex(body: IndexCreateParams): Promise<unknown> {
78 return this.request("POST", "/indexes", { body })
79 }
80
81 async *indexes(): AsyncGenerator<IndexSummary> {
82 let cursor: string | undefined
83
84 do {
85 const query = new URLSearchParams()
86 if (cursor) {
87 query.set("cursor", cursor)
88 }
89
90 const suffix = query.toString() ? `?${query.toString()}` : ""
91 const page = await this.request<{
92 indexes: IndexSummary[]
93 next_cursor?: string
94 }>("GET", `/indexes${suffix}`)
95
96 for (const entry of page.indexes ?? []) {
97 yield entry
98 }
99
100 cursor = page.next_cursor || undefined
101 } while (cursor)
102 }
103
104 async request<T>(
105 method: string,
106 path: string,
107 options: RequestInitWithBody = {}
108 ): Promise<T> {
109 const headers: Record<string, string> = {
110 "Content-Type": "application/json",
111 Authorization: `Basic ${this.options_.api_key}`,
112 "x-medusa-environment-handle": this.options_.environment_handle,
113 }
114
115 const response = await this.fetch_(`${this.options_.endpoint}${path}`, {
116 method,
117 headers: {
118 ...options.headers,
119 ...headers,
120 },
121 body: options.body ? JSON.stringify(options.body) : undefined,
122 })
123
124 const body = await response.json().catch(() => ({}))
125
126 if (!response.ok) {
127 throw new CloudServiceError(
128 body.type,
129 body.originalType,
130 body.data,
131 body.message,
132 response.status,
133 parseRetryAfter(response.headers.get("retry-after"))
134 )
135 }
136
137 return body as T
138 }
139 }
140
141 export class MedusaSearchIndex {
142 constructor(
143 protected readonly client_: MedusaSearchClient,
144 protected readonly name_: string
145 ) {}
146
147 protected path(suffix = ""): string {
148 return `/indexes/${encodeURIComponent(this.name_)}${suffix}`
149 }
150
151 schema(): Promise<Record<string, AttributeSchema>> {
152 return this.client_.request("GET", this.path("/schema"))
153 }
154
155 metadata(): Promise<IndexMetadata> {
156 return this.client_.request("GET", this.path("/metadata"))
157 }
158
159 updateSchema(body: {
160 schema: Record<string, AttributeSchema>
161 }): Promise<unknown> {
162 return this.client_.request("POST", this.path("/schema"), {
163 body: body.schema,
164 })
165 }
166
167 write(body: IndexWriteParams): Promise<IndexWriteResponse> {
168 return this.client_.request("POST", this.path(), { body })
169 }
170
171 async deleteAll(): Promise<void> {
172 await this.client_.request("DELETE", this.path())
173 }
174
175 query(body: IndexQuery): Promise<IndexQueryResult> {
176 return this.client_.request("POST", this.path("/query"), { body })
177 }
178
179 multiQuery(body: IndexMultiQueryParams): Promise<IndexMultiQueryResponse> {
180 return this.client_.request("POST", this.path("/query/multi"), { body })
181 }
182 }
183
184 export function resolveMedusaSearchOptions(
185 options: MedusaSearchProviderOptions
186 ): ResolvedMedusaSearchProviderOptions {
187 if (!options?.endpoint) {
188 throw new MedusaError(
189 MedusaError.Types.INVALID_ARGUMENT,
190 'Medusa search requires an explicit "endpoint" provider option'
191 )
192 }
193
194 const endpoint = parseEndpoint(options.endpoint)
195
196 if (endpoint.credentials && options.api_key) {
197 throw new MedusaError(
198 MedusaError.Types.INVALID_ARGUMENT,
199 'Medusa search received credentials both in the "endpoint" provider option and in the "api_key" provider option. Pass only one of them'
200 )
201 }
202
203 if (endpoint.credentials && options.environment_handle) {
204 throw new MedusaError(
205 MedusaError.Types.INVALID_ARGUMENT,
206 'Medusa search received an environment handle both in the "endpoint" provider option and in the "environment_handle" provider option. Pass only one of them'
207 )
208 }
209
210 const apiKey = endpoint.credentials?.api_key || options.api_key
211 const environmentHandle =
212 endpoint.credentials?.environment_handle || options.environment_handle
213
214 if (!apiKey) {
215 throw new MedusaError(
216 MedusaError.Types.INVALID_ARGUMENT,
217 'Medusa search requires an explicit "api_key" provider option, or basic auth credentials on the "endpoint" provider option'
218 )
219 }
220
221 if (!environmentHandle) {
222 throw new MedusaError(
223 MedusaError.Types.INVALID_ARGUMENT,
224 'Medusa search requires an explicit "environment_handle" provider option, or basic auth credentials on the "endpoint" provider option'
225 )
226 }
227
228 return {
229 ...options,
230 api_key: apiKey,
231 environment_handle: environmentHandle,
232 endpoint: endpoint.endpoint,
233 }
234 }
235
236 /**
237 * Whether the options carry credentials at all, so the module can skip
238 * registering Cloud search for an app that is not configured for it.
239 */
240 export function hasMedusaSearchCredentials(
241 options: Partial<MedusaSearchProviderOptions> = {}
242 ): boolean {
243 if (!options.endpoint) {
244 return false
245 }
246
247 if (options.api_key && options.environment_handle) {
248 return true
249 }
250
251 try {
252 return !!parseEndpoint(options.endpoint).credentials
253 } catch {
254 return false
255 }
256 }
257
258 function parseEndpoint(endpoint: string): {
259 endpoint: string
260 credentials?: { api_key: string; environment_handle: string }
261 } {
262 let url: URL
263 try {
264 url = new URL(endpoint)
265 } catch {
266 throw new MedusaError(
267 MedusaError.Types.INVALID_ARGUMENT,
268 `Medusa search could not parse the "endpoint" provider option: ${endpoint}`
269 )
270 }
271
272 if (!url.username && !url.password) {
273 return { endpoint }
274 }
275
276 // Cloud hands out an endpoint carrying the environment handle as the basic
277 // auth user and the key as the password, so a local setup only has to copy
278 // a single value. Requests keep them apart: the key is the auth header, the
279 // handle its own header.
280 const environmentHandle = decodeURIComponent(url.username)
281 const token = decodeURIComponent(url.password)
282
283 if (!environmentHandle || !token) {
284 throw new MedusaError(
285 MedusaError.Types.INVALID_ARGUMENT,
286 'Medusa search expects the "endpoint" provider option to carry both the environment handle and the token as basic auth credentials'
287 )
288 }
289
290 url.username = ""
291 url.password = ""
292
293 return {
294 credentials: {
295 api_key: token,
296 environment_handle: environmentHandle,
297 },
298 // The client appends paths that already start with a slash.
299 endpoint: url.toString().replace(/\/+$/, ""),
300 }
301 }