-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbrowser.ts
More file actions
394 lines (377 loc) · 11.8 KB
/
browser.ts
File metadata and controls
394 lines (377 loc) · 11.8 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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
/// <reference lib="dom" />
import { doFetch } from './browser-fetch'
/**
* @file Browser-safe HTTP request layer — mirrors the public surface of
* `@socketsecurity/lib/http-request` (`httpJson`, `httpText`, `httpRequest`,
* `HttpResponseError`) but uses the browser's `fetch` API instead of Node's
* `node:https`. Designed for Chrome MV3 service workers, content scripts,
* popups, and any other browser context that doesn't have `node:http` /
* `node:https` / `node:stream`. Consumers import from
* `@socketsecurity/lib/http-request/browser` directly, OR from
* `@socketsecurity/lib/http-request` inside a bundler that resolves the
* `browser` package.json conditional (rolldown, vite, esbuild) — the bundler
* picks this entry automatically. API parity with the Node side is the goal —
* same function names, same option shapes (where browsers can support them),
* same error shape. Caveats:
*
* - `HttpResponse.body` is `Uint8Array` here, vs Node's `Buffer`. Most callers
* use `arrayBuffer()` / `text()` / `json()` and don't care.
* - `HttpResponse.headers` is `Record<string, string>` here, vs Node's
* `IncomingHttpHeaders` (which has array-valued headers like `set-cookie`).
* Browser `fetch()` flattens repeated headers per spec.
* - Hooks (`onRequest` / `onResponse`) are not yet supported in the browser
* path. Add when needed.
*/
/**
* Browser-side HTTP error. Mirrors the Node-side `HttpResponseError` shape
* (same `.name`, same `.response.status/statusText` access pattern, same
* `instanceof` semantics) but constructs from a `BrowserHttpResponse` instead
* of a Node `HttpResponse`.
*/
export class HttpResponseError extends Error {
response: BrowserHttpResponse
constructor(response: BrowserHttpResponse, message?: string | undefined) {
const statusCode = response.status ?? 'unknown'
const statusMessage = response.statusText || 'No status message'
super(message ?? `HTTP ${statusCode}: ${statusMessage}`)
this.name = 'HttpResponseError'
this.response = response
}
}
/**
* Combine an external `signal` with an internal `timeout`-driven
* AbortController so either can cancel the in-flight fetch.
*/
export function combineSignals(
external: AbortSignal | undefined,
timeoutMs: number | undefined,
): { signal: AbortSignal | undefined; cleanup: () => void } {
if (!timeoutMs) {
return { signal: external, cleanup: () => {} }
}
const controller = new AbortController()
const timer = setTimeout(() => controller.abort(), timeoutMs)
let externalListener: (() => void) | undefined
if (external) {
if (external.aborted) {
controller.abort()
} else {
externalListener = () => controller.abort()
external.addEventListener('abort', externalListener)
}
}
return {
signal: controller.signal,
cleanup: () => {
clearTimeout(timer)
if (external && externalListener) {
external.removeEventListener('abort', externalListener)
}
},
}
}
// oxlint-disable-next-line socket/sort-source-methods -- attempt() is called by combineSignals-using paths below; declared near its callers
export async function attempt(
url: string,
options: BrowserHttpRequestOptions,
): Promise<BrowserHttpResponse> {
const method = options.method ?? 'GET'
const init: RequestInit = { method }
if (options.headers) {
init.headers = options.headers
}
if (options.body !== undefined) {
;(init as { body?: BodyInit | null }).body = options.body as BodyInit
}
if (options.followRedirects === false) {
init.redirect = 'manual'
}
const { signal, cleanup } = combineSignals(options.signal, options.timeout)
if (signal) {
init.signal = signal
}
const startedAt = Date.now()
if (options.hooks?.onRequest) {
options.hooks.onRequest({
method,
url,
headers: options.headers,
timeout: options.timeout,
})
}
try {
const response = await doFetch(url, init)
const buffer = await response.arrayBuffer()
if (
options.maxResponseSize !== undefined &&
buffer.byteLength > options.maxResponseSize
) {
throw new Error(
`Response body (${buffer.byteLength} bytes) exceeds maxResponseSize (${options.maxResponseSize})`,
)
}
const body = new Uint8Array(buffer)
const headers = headersToRecord(response.headers)
if (options.hooks?.onResponse) {
options.hooks.onResponse({
method,
url,
duration: Date.now() - startedAt,
status: response.status,
statusText: response.statusText,
headers,
})
}
return {
body,
headers,
status: response.status,
statusText: response.statusText,
ok: response.ok,
url: response.url,
arrayBuffer(): ArrayBuffer {
return buffer
},
text(): string {
return decodeText(body)
},
json<T = unknown>(): T {
return JSON.parse(decodeText(body)) as T
},
}
} catch (err) {
if (options.hooks?.onResponse) {
options.hooks.onResponse({
method,
url,
duration: Date.now() - startedAt,
error: err instanceof Error ? err : new Error(String(err)),
})
}
throw err
} finally {
cleanup()
}
}
export function decodeText(bytes: Uint8Array): string {
return new TextDecoder('utf-8').decode(bytes)
}
/**
* Per-attempt request info passed to `hooks.onRequest`. Mirrors the Node-side
* `HttpHookRequestInfo` shape so callers can share hook implementations.
*/
export interface BrowserHttpHookRequestInfo {
method: string
url: string
headers?: Record<string, string> | undefined
timeout?: number | undefined
}
/**
* Per-attempt response info passed to `hooks.onResponse`. Either `status`
* (success) or `error` (network failure) is populated.
*/
export interface BrowserHttpHookResponseInfo {
method: string
url: string
duration: number
status?: number | undefined
statusText?: string | undefined
headers?: Record<string, string> | undefined
error?: Error | undefined
}
export interface BrowserHttpHooks {
onRequest?: ((info: BrowserHttpHookRequestInfo) => void) | undefined
onResponse?: ((info: BrowserHttpHookResponseInfo) => void) | undefined
}
export interface BrowserHttpRequestOptions {
/**
* Request body. Strings, Blobs, FormData, ArrayBuffer all pass through to
* fetch unchanged. Objects are NOT auto-stringified — the convenience wrapper
* `httpJson` handles JSON serialization.
*/
body?: string | Blob | FormData | ArrayBuffer | Uint8Array | undefined
/**
* Whether to follow redirects automatically. Defaults to true (browser fetch
* default). Setting `false` sets `redirect: 'manual'` so 3xx responses are
* returned to the caller instead of followed.
*/
followRedirects?: boolean | undefined
/**
* Request headers. Object form for ergonomics; passed through to fetch.
*/
headers?: Record<string, string> | undefined
/**
* Lifecycle hooks for observing request/response events. Mirrors the
* Node-side `hooks` field. Hooks fire per-attempt — retries trigger separate
* hook calls.
*/
hooks?: BrowserHttpHooks | undefined
/**
* Maximum response body size in bytes. Responses larger than this are
* truncated and treated as a network failure (so retries can fire). Defaults
* to no limit. Useful when calling untrusted endpoints.
*/
maxResponseSize?: number | undefined
/**
* HTTP method. Defaults to GET.
*/
method?: string | undefined
/**
* Number of retry attempts on 5xx / network failure. Defaults to 0 (no
* retries).
*/
retries?: number | undefined
/**
* Base delay (ms) between retries. Doubles per attempt (exponential).
* Defaults to 250ms.
*/
retryDelay?: number | undefined
/**
* Abort signal forwarded to fetch. Combined with `timeout` via
* AbortController when both are present.
*/
signal?: AbortSignal | undefined
/**
* Throw on non-2xx response. Defaults to false; `httpJson` / `httpText` set
* this to true so callers don't have to check `.ok`.
*/
throwOnError?: boolean | undefined
/**
* Per-attempt timeout in milliseconds. Implemented via AbortController;
* exceeds the timeout aborts the fetch and the attempt counts as a network
* failure (retryable). Defaults to no timeout (fetch defaults).
*/
timeout?: number | undefined
}
/**
* Browser-shaped HTTP response. Surface mirrors the Node-side `HttpResponse`
* but with browser-native body types.
*/
export interface BrowserHttpResponse {
/**
* Raw response body. `Uint8Array` instead of Node's `Buffer`.
*/
body: Uint8Array
/**
* Response headers, lowercased keys (matching Node side's lowercase
* convention). Repeated headers are joined with `, ` per fetch spec.
*/
headers: Record<string, string>
/**
* Convenience: true when status is 2xx.
*/
ok: boolean
/**
* HTTP status code.
*/
status: number
/**
* HTTP status text.
*/
statusText: string
/**
* Final URL after any redirects.
*/
url: string
/**
* Body as ArrayBuffer.
*/
arrayBuffer(): ArrayBuffer
/**
* Body parsed as JSON. Throws on invalid JSON.
*/
json<T = unknown>(): T
/**
* Body decoded as UTF-8 text.
*/
text(): string
}
export function headersToRecord(headers: Headers): Record<string, string> {
const out: Record<string, string> = {}
headers.forEach((value, key) => {
out[key.toLowerCase()] = value
})
return out
}
/**
* GET / POST a JSON endpoint. Automatically sets `Accept: application/json` and
* `Content-Type: application/json` (when a body is present). Throws
* `HttpResponseError` on non-2xx.
*/
export async function httpJson<T = unknown>(
url: string,
options?: BrowserHttpRequestOptions | undefined,
): Promise<T> {
const opts = options ?? {}
const headers: Record<string, string> = {
Accept: 'application/json',
...(opts.headers ?? {}),
}
if (opts.body !== undefined && !('Content-Type' in headers)) {
headers['Content-Type'] = 'application/json'
}
const response = await httpRequest(url, {
...opts,
headers,
throwOnError: true,
})
return response.json<T>()
}
/**
* Lower-level HTTP request. Use `httpJson` / `httpText` for the common cases.
* Returns the response unconditionally — callers inspect `.ok` or pass
* `throwOnError: true` to get a thrown `HttpResponseError` on non-2xx.
*/
export async function httpRequest(
url: string,
options?: BrowserHttpRequestOptions | undefined,
): Promise<BrowserHttpResponse> {
const opts = options ?? {}
const maxAttempts = (opts.retries ?? 0) + 1
const baseDelay = opts.retryDelay ?? 250
let lastError: unknown
for (let i = 0; i < maxAttempts; i++) {
try {
const response = await attempt(url, opts)
// 5xx → eligible for retry
if (response.status >= 500 && i + 1 < maxAttempts) {
await sleep(baseDelay * Math.pow(2, i))
continue
}
if (opts.throwOnError && !response.ok) {
throw new HttpResponseError(response)
}
return response
} catch (err) {
lastError = err
// Network errors are eligible for retry; HttpResponseError thrown
// by throwOnError is not (it's an explicit failure signal).
if (err instanceof HttpResponseError) {
throw err
}
if (i + 1 < maxAttempts) {
await sleep(baseDelay * Math.pow(2, i))
continue
}
}
}
throw lastError instanceof Error
? lastError
: new Error(`HTTP request to ${url} failed`)
}
/**
* GET / POST a text endpoint. Throws `HttpResponseError` on non-2xx.
*/
export async function httpText(
url: string,
options?: BrowserHttpRequestOptions | undefined,
): Promise<string> {
const response = await httpRequest(url, {
...(options ?? {}),
throwOnError: true,
})
return response.text()
}
export function sleep(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms))
}