-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbrowser-fetch.ts
More file actions
183 lines (166 loc) · 5.11 KB
/
Copy pathbrowser-fetch.ts
File metadata and controls
183 lines (166 loc) · 5.11 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
import type { RequestInfo, RequestInit } from '../internal/builtin-types';
import { KernelError } from '../core/error';
import { buildHeaders } from '../internal/headers';
import type { FinalRequestOptions, RequestOptions } from '../internal/request-options';
import type { HTTPMethod } from '../internal/types';
import type { Kernel } from '../client';
export interface BrowserFetchInit extends RequestInit {
timeout_ms?: number;
}
export async function browserFetch(
client: Kernel,
sessionId: string,
input: RequestInfo | URL,
init?: BrowserFetchInit,
): Promise<Response> {
const route = client.browserRouteCache.get(sessionId);
if (!route) {
throw new KernelError(
`browser route cache does not contain session ${sessionId}; create, retrieve, or list the browser before calling browser.fetch`,
);
}
const { url: targetURL, method, headers, body, signal, duplex, timeout_ms } = splitFetchArgs(input, init);
assertHTTPURL(targetURL);
const query: Record<string, unknown> = { url: targetURL, jwt: route.jwt };
if (timeout_ms !== undefined) {
query['timeout_ms'] = timeout_ms;
}
const accept = headers.get('accept');
const requestOptions: FinalRequestOptions = {
method: normalizeMethod(method),
path: joinURL(route.baseURL, '/curl/raw'),
query,
body: body as RequestOptions['body'],
headers: buildHeaders([
{ Authorization: null },
accept ? { Accept: accept } : { Accept: '*/*' },
headersToRequestOptionsHeaders(headers),
]),
signal: signal ?? null,
__binaryResponse: true,
};
if (duplex) {
requestOptions.fetchOptions = { duplex } as NonNullable<RequestOptions['fetchOptions']>;
}
return client.request(requestOptions).asResponse();
}
function normalizeMethod(method: string): HTTPMethod {
const methodLower = method.toLowerCase();
const allowed = new Set(['get', 'post', 'put', 'patch', 'delete', 'head', 'options']);
if (!allowed.has(methodLower)) {
throw new KernelError(`browser.fetch unsupported HTTP method: ${method}`);
}
return methodLower as HTTPMethod;
}
function splitFetchArgs(
input: RequestInfo | URL,
init?: BrowserFetchInit,
): {
url: string;
method: string;
headers: Headers;
body?: RequestInit['body'];
signal?: AbortSignal | null;
duplex?: RequestInit['duplex'];
timeout_ms?: number;
} {
const timeoutFromInit = init && 'timeout_ms' in init ? init['timeout_ms'] : undefined;
if (input instanceof Request) {
const headers = new Headers(input.headers);
if (init?.headers) {
const extra = new Headers(init.headers);
extra.forEach((value, key) => {
headers.set(key, value);
});
}
const out: {
url: string;
method: string;
headers: Headers;
body?: RequestInit['body'];
signal?: AbortSignal | null;
duplex?: RequestInit['duplex'];
timeout_ms?: number;
} = {
url: input.url,
method: (init?.method ?? input.method)?.toUpperCase() || 'GET',
headers,
};
const body = init?.body ?? input.body;
if (body !== undefined && body !== null) {
out.body = body;
}
const signal = init?.signal ?? input.signal;
if (signal !== undefined) {
out.signal = signal;
}
if (init?.duplex !== undefined) {
out.duplex = init.duplex;
}
if (timeoutFromInit !== undefined) {
out.timeout_ms = timeoutFromInit;
}
return out;
}
const out: {
url: string;
method: string;
headers: Headers;
body?: RequestInit['body'];
signal?: AbortSignal | null;
duplex?: RequestInit['duplex'];
timeout_ms?: number;
} = {
url: input instanceof URL ? input.href : String(input),
method: (init?.method ?? 'GET').toUpperCase(),
headers: new Headers(init?.headers),
};
if (init?.body !== undefined) {
out.body = init.body;
}
if (init?.signal !== undefined) {
out.signal = init.signal;
}
if (init?.duplex !== undefined) {
out.duplex = init.duplex;
}
if (timeoutFromInit !== undefined) {
out.timeout_ms = timeoutFromInit;
}
return out;
}
function assertHTTPURL(url: string): void {
let parsed: URL;
try {
parsed = new URL(url);
} catch {
throw new KernelError(`browser.fetch target must be an absolute URL; received: ${url}`);
}
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
throw new KernelError(`browser.fetch only supports http(s) URLs; received: ${parsed.protocol}`);
}
}
function headersToRequestOptionsHeaders(headers: Headers): Record<string, string | null | undefined> {
const out: Record<string, string | null | undefined> = {};
headers.forEach((value, key) => {
switch (key.toLowerCase()) {
case 'accept':
case 'content-length':
case 'connection':
case 'keep-alive':
case 'proxy-authenticate':
case 'proxy-authorization':
case 'te':
case 'trailers':
case 'transfer-encoding':
case 'upgrade':
return;
default:
out[key] = value;
}
});
return out;
}
function joinURL(baseURL: string, path: string): string {
return `${baseURL.replace(/\/+$/, '')}${path.startsWith('/') ? path : `/${path}`}`;
}