Open History to see the last commit
1// This file is auto-generated by @hey-api/openapi-ts
2
3import { getAuthToken } from '../core/auth.gen'
4import type { QuerySerializerOptions } from '../core/bodySerializer.gen'
5import { jsonBodySerializer } from '../core/bodySerializer.gen'
6import {
7 serializeArrayParam,
8 serializeObjectParam,
9 serializePrimitiveParam,
10} from '../core/pathSerializer.gen'
11import { getUrl } from '../core/utils.gen'
12import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'
13
14export const createQuerySerializer = <T = unknown>({
15 parameters = {},
16 ...args
17}: QuerySerializerOptions = {}): ((queryParams: T) => string) => {
18 const querySerializer = (queryParams: T): string => {
19 const search: string[] = []
20 if (queryParams && typeof queryParams === 'object') {
21 for (const name in queryParams) {
22 const value = queryParams[name]
23
24 if (value === undefined || value === null) {
25 continue
26 }
27
28 const options = parameters[name] || args
29
30 if (Array.isArray(value)) {
31 const serializedArray = serializeArrayParam({
32 allowReserved: options.allowReserved,
33 explode: true,
34 name,
35 style: 'form',
36 value,
37 ...options.array,
38 })
39 if (serializedArray) search.push(serializedArray)
40 } else if (typeof value === 'object') {
41 const serializedObject = serializeObjectParam({
42 allowReserved: options.allowReserved,
43 explode: true,
44 name,
45 style: 'deepObject',
46 value: value as Record<string, unknown>,
47 ...options.object,
48 })
49 if (serializedObject) search.push(serializedObject)
50 } else {
51 const serializedPrimitive = serializePrimitiveParam({
52 allowReserved: options.allowReserved,
53 name,
54 value: value as string,
55 })
56 if (serializedPrimitive) search.push(serializedPrimitive)
57 }
58 }
59 }
60 return search.join('&')
61 }
62 return querySerializer
63}
64
65/**
66 * Infers parseAs value from provided Content-Type header.
67 */
68export const getParseAs = (
69 contentType: string | null,
70): Exclude<Config['parseAs'], 'auto'> => {
71 if (!contentType) {
72 // If no Content-Type header is provided, the best we can do is return the raw response body,
73 // which is effectively the same as the 'stream' option.
74 return 'stream'
75 }
76
77 const cleanContent = contentType.split(';')[0]?.trim()
78
79 if (!cleanContent) {
80 return
81 }
82
83 if (
84 cleanContent.startsWith('application/json') ||
85 cleanContent.endsWith('+json')
86 ) {
87 return 'json'
88 }
89
90 if (cleanContent === 'multipart/form-data') {
91 return 'formData'
92 }
93
94 if (
95 ['application/', 'audio/', 'image/', 'video/'].some((type) =>
96 cleanContent.startsWith(type),
97 )
98 ) {
99 return 'blob'
100 }
101
102 if (cleanContent.startsWith('text/')) {
103 return 'text'
104 }
105
106 return
107}
108
109const checkForExistence = (
110 options: Pick<RequestOptions, 'auth' | 'query'> & {
111 headers: Headers
112 },
113 name?: string,
114): boolean => {
115 if (!name) {
116 return false
117 }
118 if (
119 options.headers.has(name) ||
120 options.query?.[name] ||
121 options.headers.get('Cookie')?.includes(`${name}=`)
122 ) {
123 return true
124 }
125 return false
126}
127
128export async function setAuthParams(
129 options: Pick<RequestOptions, 'auth' | 'query' | 'security'> & {
130 headers: Headers
131 },
132): Promise<void> {
133 for (const auth of options.security ?? []) {
134 if (checkForExistence(options, auth.name)) {
135 continue
136 }
137
138 const token = await getAuthToken(auth, options.auth)
139
140 if (!token) {
141 continue
142 }
143
144 const name = auth.name ?? 'Authorization'
145
146 switch (auth.in) {
147 case 'query':
148 if (!options.query) {
149 options.query = {}
150 }
151 options.query[name] = token
152 break
153 case 'cookie':
154 options.headers.append('Cookie', `${name}=${token}`)
155 break
156 case 'header':
157 default:
158 options.headers.set(name, token)
159 break
160 }
161 }
162}
163
164export const buildUrl: Client['buildUrl'] = (options) =>
165 getUrl({
166 baseUrl: options.baseUrl as string,
167 path: options.path,
168 query: options.query,
169 querySerializer:
170 typeof options.querySerializer === 'function'
171 ? options.querySerializer
172 : createQuerySerializer(options.querySerializer),
173 url: options.url,
174 })
175
176export const mergeConfigs = (a: Config, b: Config): Config => {
177 const config = { ...a, ...b }
178 if (config.baseUrl?.endsWith('/')) {
179 config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1)
180 }
181 config.headers = mergeHeaders(a.headers, b.headers)
182 return config
183}
184
185const headersEntries = (headers: Headers): Array<[string, string]> => {
186 const entries: Array<[string, string]> = []
187 headers.forEach((value, key) => {
188 entries.push([key, value])
189 })
190 return entries
191}
192
193export const mergeHeaders = (
194 ...headers: Array<Required<Config>['headers'] | undefined>
195): Headers => {
196 const mergedHeaders = new Headers()
197 for (const header of headers) {
198 if (!header) {
199 continue
200 }
201
202 const iterator =
203 header instanceof Headers
204 ? headersEntries(header)
205 : Object.entries(header)
206
207 for (const [key, value] of iterator) {
208 if (value === null) {
209 mergedHeaders.delete(key)
210 } else if (Array.isArray(value)) {
211 for (const v of value) {
212 mergedHeaders.append(key, v as string)
213 }
214 } else if (value !== undefined) {
215 // assume object headers are meant to be JSON stringified, i.e., their
216 // content value in OpenAPI specification is 'application/json'
217 mergedHeaders.set(
218 key,
219 typeof value === 'object' ? JSON.stringify(value) : (value as string),
220 )
221 }
222 }
223 }
224 return mergedHeaders
225}
226
227type ErrInterceptor<Err, Res, Req, Options> = (
228 error: Err,
229 /** response may be undefined due to a network error where no response object is produced */
230 response: Res | undefined,
231 /** request may be undefined, because error may be from building the request object itself */
232 request: Req | undefined,
233 options: Options,
234) => Err | Promise<Err>
235
236type ReqInterceptor<Req, Options> = (
237 request: Req,
238 options: Options,
239) => Req | Promise<Req>
240
241type ResInterceptor<Res, Req, Options> = (
242 response: Res,
243 request: Req,
244 options: Options,
245) => Res | Promise<Res>
246
247class Interceptors<Interceptor> {
248 fns: Array<Interceptor | null> = []
249
250 clear(): void {
251 this.fns = []
252 }
253
254 eject(id: number | Interceptor): void {
255 const index = this.getInterceptorIndex(id)
256 if (this.fns[index]) {
257 this.fns[index] = null
258 }
259 }
260
261 exists(id: number | Interceptor): boolean {
262 const index = this.getInterceptorIndex(id)
263 return Boolean(this.fns[index])
264 }
265
266 getInterceptorIndex(id: number | Interceptor): number {
267 if (typeof id === 'number') {
268 return this.fns[id] ? id : -1
269 }
270 return this.fns.indexOf(id)
271 }
272
273 update(
274 id: number | Interceptor,
275 fn: Interceptor,
276 ): number | Interceptor | false {
277 const index = this.getInterceptorIndex(id)
278 if (this.fns[index]) {
279 this.fns[index] = fn
280 return id
281 }
282 return false
283 }
284
285 use(fn: Interceptor): number {
286 this.fns.push(fn)
287 return this.fns.length - 1
288 }
289}
290
291export interface Middleware<Req, Res, Err, Options> {
292 error: Interceptors<ErrInterceptor<Err, Res, Req, Options>>
293 request: Interceptors<ReqInterceptor<Req, Options>>
294 response: Interceptors<ResInterceptor<Res, Req, Options>>
295}
296
297export const createInterceptors = <Req, Res, Err, Options>(): Middleware<
298 Req,
299 Res,
300 Err,
301 Options
302> => ({
303 error: new Interceptors<ErrInterceptor<Err, Res, Req, Options>>(),
304 request: new Interceptors<ReqInterceptor<Req, Options>>(),
305 response: new Interceptors<ResInterceptor<Res, Req, Options>>(),
306})
307
308const defaultQuerySerializer = createQuerySerializer({
309 allowReserved: false,
310 array: {
311 explode: true,
312 style: 'form',
313 },
314 object: {
315 explode: true,
316 style: 'deepObject',
317 },
318})
319
320const defaultHeaders = {
321 'Content-Type': 'application/json',
322}
323
324export const createConfig = <T extends ClientOptions = ClientOptions>(
325 override: Config<Omit<ClientOptions, keyof T> & T> = {},
326): Config<Omit<ClientOptions, keyof T> & T> => ({
327 ...jsonBodySerializer,
328 headers: defaultHeaders,
329 parseAs: 'auto',
330 querySerializer: defaultQuerySerializer,
331 ...override,
332})