-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.ts
365 lines (323 loc) · 10.7 KB
/
index.ts
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
import { Context, Service } from 'cordis'
import { Awaitable, defineProperty, Dict, trimSlash } from 'cosmokit'
import { ClientOptions } from 'ws'
import { WebSocket } from 'undios/adapter'
export type { WebSocket } from 'undios/adapter'
declare module 'cordis' {
interface Context {
http: HTTP
}
interface Intercept {
http: HTTP.Config
}
interface Events {
'http/config'(config: HTTP.Config): void
'http/fetch-init'(url: URL, init: RequestInit, config: HTTP.Config): void
'http/websocket-init'(url: URL, init: ClientOptions, config: HTTP.Config): void
}
}
const kHTTPError = Symbol.for('undios.error')
class HTTPError extends Error {
[kHTTPError] = true
response?: HTTP.Response
static is(error: any): error is HTTPError {
return !!error?.[kHTTPError]
}
constructor(message?: string, public code?: HTTP.Error.Code) {
super(message)
}
}
/**
* @see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
*/
function encodeRequest(data: any): [string | null, any] {
if (data instanceof URLSearchParams) return [null, data]
if (data instanceof ArrayBuffer) return [null, data]
if (ArrayBuffer.isView(data)) return [null, data]
if (data instanceof Blob) return [null, data]
if (data instanceof FormData) return [null, data]
return ['application/json', JSON.stringify(data)]
}
export namespace HTTP {
export type Method =
| 'get' | 'GET'
| 'delete' | 'DELETE'
| 'head' | 'HEAD'
| 'options' | 'OPTIONS'
| 'post' | 'POST'
| 'put' | 'PUT'
| 'patch' | 'PATCH'
| 'purge' | 'PURGE'
| 'link' | 'LINK'
| 'unlink' | 'UNLINK'
export interface ResponseTypes {
json: any
text: string
stream: ReadableStream<Uint8Array>
blob: Blob
formdata: FormData
arraybuffer: ArrayBuffer
}
export interface Request1 {
<K extends keyof ResponseTypes>(url: string, config: HTTP.RequestConfig & { responseType: K }): Promise<ResponseTypes[K]>
<T = any>(url: string, config?: HTTP.RequestConfig): Promise<T>
}
export interface Request2 {
<K extends keyof ResponseTypes>(url: string, data: any, config: HTTP.RequestConfig & { responseType: K }): Promise<ResponseTypes[K]>
<T = any>(url: string, data?: any, config?: HTTP.RequestConfig): Promise<T>
}
export interface Config {
baseURL?: string
/** @deprecated use `baseURL` instead */
endpoint?: string
headers?: Dict
timeout?: number
}
export interface RequestConfig extends Config {
method?: Method
params?: Dict
data?: any
keepAlive?: boolean
redirect?: RequestRedirect
signal?: AbortSignal
responseType?: keyof ResponseTypes
validateStatus?: (status: number) => boolean
}
export interface Response<T = any> {
url: string
data: T
status: number
statusText: string
headers: Headers
}
export type Error = HTTPError
export namespace Error {
export type Code = 'ETIMEDOUT'
}
}
export interface HTTP {
<K extends keyof HTTP.ResponseTypes>(url: string, config: HTTP.RequestConfig & { responseType: K }): Promise<HTTP.Response<HTTP.ResponseTypes[K]>>
<T = any>(url: string | URL, config?: HTTP.RequestConfig): Promise<HTTP.Response<T>>
<T = any>(method: HTTP.Method, url: string | URL, config?: HTTP.RequestConfig): Promise<HTTP.Response<T>>
config: HTTP.Config
get: HTTP.Request1
delete: HTTP.Request1
patch: HTTP.Request2
post: HTTP.Request2
put: HTTP.Request2
}
export class HTTP extends Service<HTTP.Config> {
static Error = HTTPError
/** @deprecated use `HTTP.Error.is()` instead */
static isAxiosError = HTTPError.is
static [Service.provide] = 'http'
static [Service.immediate] = true
static {
for (const method of ['get', 'delete'] as const) {
defineProperty(HTTP.prototype, method, async function (this: HTTP, url: string, config?: HTTP.Config) {
const response = await this(url, { method, ...config })
return response.data
})
}
for (const method of ['patch', 'post', 'put'] as const) {
defineProperty(HTTP.prototype, method, async function (this: HTTP, url: string, data?: any, config?: HTTP.Config) {
const response = await this(url, { method, data, ...config })
return response.data
})
}
}
private _decoders: Dict = Object.create(null)
constructor(config?: HTTP.Config)
constructor(ctx: Context, config?: HTTP.Config)
constructor(...args: any[]) {
super(args[0], args[1])
this.decoder('json', (raw) => raw.json())
this.decoder('text', (raw) => raw.text())
this.decoder('blob', (raw) => raw.blob())
this.decoder('arraybuffer', (raw) => raw.arrayBuffer())
this.decoder('formdata', (raw) => raw.formData())
this.decoder('stream', (raw) => raw.body!)
}
static mergeConfig = (target: HTTP.Config, source?: HTTP.Config) => ({
...target,
...source,
headers: {
...target?.headers,
...source?.headers,
},
})
decoder<K extends keyof HTTP.ResponseTypes>(type: K, decoder: (raw: Response) => Awaitable<HTTP.ResponseTypes[K]>) {
return this[Context.origin].effect(() => {
this._decoders[type] = decoder
return () => delete this._decoders[type]
})
}
extend(config: HTTP.Config = {}) {
return this[Service.extend]({
config: HTTP.mergeConfig(this.config, config),
})
}
resolveConfig(init?: HTTP.RequestConfig): HTTP.RequestConfig {
const caller = this[Context.origin]
let result = { headers: {}, ...this.config }
caller.emit('http/config', result)
let intercept = caller[Context.intercept]
while (intercept) {
result = HTTP.mergeConfig(result, intercept.http)
intercept = Object.getPrototypeOf(intercept)
}
result = HTTP.mergeConfig(result, init)
return result
}
resolveURL(url: string | URL, config: HTTP.RequestConfig) {
if (config.endpoint) {
// this[Context.origin].emit('internal/warning', 'endpoint is deprecated, please use baseURL instead')
try {
new URL(url)
} catch {
url = trimSlash(config.endpoint) + url
}
}
try {
url = new URL(url, config.baseURL)
} catch (error) {
// prettify the error message
throw new TypeError(`Invalid URL: ${url}`)
}
for (const [key, value] of Object.entries(config.params ?? {})) {
url.searchParams.append(key, value)
}
return url
}
defaultDecoder(response: Response) {
const type = response.headers.get('Content-Type')
if (type?.startsWith('application/json')) {
return response.json()
} else if (type?.startsWith('text/')) {
return response.text()
} else {
return response.arrayBuffer()
}
}
async [Service.invoke](...args: any[]) {
const caller = this[Context.origin]
let method: HTTP.Method | undefined
if (typeof args[1] === 'string' || args[1] instanceof URL) {
method = args.shift()
}
const config = this.resolveConfig(args[1])
const url = this.resolveURL(args[0], config)
method ??= config.method ?? 'GET'
const controller = new AbortController()
if (config.signal) {
if (config.signal.aborted) {
throw config.signal.reason
}
config.signal.addEventListener('abort', () => {
controller.abort(config.signal!.reason)
})
}
const dispose = caller.effect(() => {
const timer = config.timeout && setTimeout(() => {
controller.abort(new HTTPError('request timeout', 'ETIMEDOUT'))
}, config.timeout)
return () => {
clearTimeout(timer)
controller.abort(new HTTPError('context disposed', 'ETIMEDOUT'))
}
})
controller.signal.addEventListener('abort', dispose)
try {
const headers = new Headers(config.headers)
const init: RequestInit = {
method,
headers,
body: config.data,
keepalive: config.keepAlive,
redirect: config.redirect,
signal: controller.signal,
}
if (config.data && typeof config.data === 'object') {
const [type, body] = encodeRequest(config.data)
init.body = body
if (type && !headers.has('Content-Type')) {
headers.append('Content-Type', type)
}
}
caller.emit('http/fetch-init', url, init, config)
const raw = await fetch(url, init).catch((cause) => {
if (HTTP.Error.is(cause)) throw cause
const error = new HTTP.Error(`fetch ${url} failed`)
error.cause = cause
throw error
})
const response: HTTP.Response = {
data: null,
url: raw.url,
status: raw.status,
statusText: raw.statusText,
headers: raw.headers,
}
// we don't use `raw.ok` because it may be a 3xx redirect
const validateStatus = config.validateStatus ?? (status => status < 400)
if (!validateStatus(raw.status)) {
const error = new HTTP.Error(raw.statusText)
error.response = response
try {
response.data = await this.defaultDecoder(raw)
} catch {}
throw error
}
if (config.responseType) {
if (!(config.responseType in this._decoders)) {
throw new TypeError(`Unknown responseType: ${config.responseType}`)
}
const decoder = this._decoders[config.responseType]
response.data = await decoder(raw)
} else {
response.data = await this.defaultDecoder(raw)
}
return response
} finally {
controller.abort()
}
}
async head(url: string, config?: HTTP.Config) {
const response = await this(url, { method: 'HEAD', ...config })
return response.headers
}
/** @deprecated use `ctx.http()` instead */
axios<T = any>(config: { url: string } & HTTP.RequestConfig): Promise<HTTP.Response<T>>
axios<T = any>(url: string, config?: HTTP.RequestConfig): Promise<HTTP.Response<T>>
axios(...args: any[]) {
const caller = this[Context.origin]
caller.emit('internal/warning', 'ctx.http.axios() is deprecated, use ctx.http() instead')
if (typeof args[0] === 'string') {
return this(args[0], args[1])
} else {
return this(args[0].url, args[0])
}
}
ws(url: string | URL, init?: HTTP.Config) {
const caller = this[Context.origin]
const config = this.resolveConfig(init)
url = this.resolveURL(url, config)
let options: ClientOptions | undefined
if ('Server' in WebSocket) {
options = {
handshakeTimeout: config?.timeout,
headers: config?.headers,
}
caller.emit('http/websocket-init', url, options, config)
}
const socket = new WebSocket(url, options as never)
const dispose = caller.on('dispose', () => {
socket.close(1001, 'context disposed')
})
socket.addEventListener('close', () => {
dispose()
})
return socket
}
}
export default HTTP