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
|
// const { Object } = import.meta.primordials;
const { EventEmitter } = import.meta.require("events");
const {
Readable,
[Symbol.for("::bunternal::")]: { _ReadableFromWeb },
} = import.meta.require("node:stream");
const ObjectCreate = Object.create;
const kEmptyObject = ObjectCreate(null);
export var fetch = Bun.fetch;
export var Response = globalThis.Response;
export var Headers = globalThis.Headers;
export var Request = globalThis.Request;
export var URLSearchParams = globalThis.URLSearchParams;
export var URL = globalThis.URL;
export class File extends Blob {}
export class FileReader extends EventTarget {
constructor() {
throw new Error("Not implemented yet!");
}
}
export var FormData = globalThis.FormData;
function notImplemented() {
throw new Error("Not implemented in bun");
}
/**
* An object representing a URL.
* @typedef {Object} UrlObject
* @property {string | number} [port]
* @property {string} [path]
* @property {string} [pathname]
* @property {string} [hostname]
* @property {string} [origin]
* @property {string} [protocol]
* @property {string} [search]
*/
/**
* @typedef {import('http').IncomingHttpHeaders} IncomingHttpHeaders
* @typedef {'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'CONNECT' | 'OPTIONS' | 'TRACE' | 'PATCH'} HttpMethod
* @typedef {import('stream').Readable} Readable
* @typedef {import('events').EventEmitter} EventEmitter
*/
class BodyReadable extends _ReadableFromWeb {
#response;
#bodyUsed;
constructor(response, options = {}) {
var { body } = response;
if (!body) throw new Error("Response body is null");
super(options, body);
this.#response = response;
this.#bodyUsed = response.bodyUsed;
}
get bodyUsed() {
// return this.#response.bodyUsed;
return this.#bodyUsed;
}
#consume() {
if (this.#bodyUsed) throw new TypeError("unusable");
this.#bodyUsed = true;
}
async arrayBuffer() {
this.#consume();
return await this.#response.arrayBuffer();
}
async blob() {
this.#consume();
return await this.#response.blob();
}
async formData() {
this.#consume();
return await this.#response.formData();
}
async json() {
this.#consume();
return await this.#response.json();
}
async text() {
this.#consume();
return await this.#response.text();
}
}
// NOT IMPLEMENTED
// * idempotent?: boolean;
// * onInfo?: (info: { statusCode: number, headers: Object<string, string | string[]> }) => void;
// * opaque?: *;
// * responseHeader: 'raw' | null;
// * headersTimeout?: number | null;
// * bodyTimeout?: number | null;
// * upgrade?: boolean | string | null;
// * blocking?: boolean;
/**
* Performs an HTTP request.
* @param {string | URL | UrlObject} url
* @param {{
* dispatcher: Dispatcher;
* method: HttpMethod;
* signal?: AbortSignal | EventEmitter | null;
* maxRedirections?: number;
* body?: string | Buffer | Uint8Array | Readable | null | FormData;
* headers?: IncomingHttpHeaders | string[] | null;
* query?: Record<string, any>;
* reset?: boolean;
* throwOnError?: boolean;
* }} [options]
* @returns {{
* statusCode: number;
* headers: IncomingHttpHeaders;
* body: ResponseBody;
* trailers: Object<string, string>;
* opaque: *;
* context: Object<string, *>;
* }}
*/
export async function request(
url,
options = {
method: "GET",
signal: null,
headers: null,
query: null,
// idempotent: false, // GET and HEAD requests are idempotent by default
// blocking = false,
// upgrade = false,
// headersTimeout: 30000,
// bodyTimeout: 30000,
reset: false,
throwOnError: false,
body: null,
// dispatcher,
},
) {
let {
method = "GET",
headers: inputHeaders,
query,
signal,
// idempotent, // GET and HEAD requests are idempotent by default
// blocking = false,
// upgrade = false,
// headersTimeout = 30000,
// bodyTimeout = 30000,
reset = false,
throwOnError = false,
body: inputBody,
maxRedirections,
// dispatcher,
} = options;
// TODO: More validations
if (typeof url === "string") {
if (query) url = new URL(url);
} else if (typeof url === "object" && url !== null) {
if (!(url instanceof URL)) {
// TODO: Parse undici UrlObject
throw new Error("not implemented");
}
} else throw new TypeError("url must be a string, URL, or UrlObject");
if (typeof url === "string" && query) url = new URL(url);
if (typeof url === "object" && url !== null && query) if (query) url.search = new URLSearchParams(query).toString();
method = method && typeof method === "string" ? method.toUpperCase() : null;
// idempotent = idempotent === undefined ? method === "GET" || method === "HEAD" : idempotent;
if (inputBody && (method === "GET" || method === "HEAD")) {
throw new Error("Body not allowed for GET or HEAD requests");
}
if (inputBody && inputBody.read && inputBody instanceof Readable) {
// TODO: Streaming via ReadableStream?
let data = "";
inputBody.setEncoding("utf8");
for await (const chunk of stream) {
data += chunk;
}
inputBody = new TextEncoder().encode(data);
}
if (maxRedirections !== undefined && Number.isNaN(maxRedirections)) {
throw new Error("maxRedirections must be a number if defined");
}
if (signal && !(signal instanceof AbortSignal)) {
// TODO: Add support for event emitter signal
throw new Error("signal must be an instance of AbortSignal");
}
let resp;
/** @type {Response} */
const {
status: statusCode,
headers,
trailers,
} = (resp = await fetch(url, {
signal,
mode: "cors",
method,
headers: inputHeaders || kEmptyObject,
body: inputBody,
redirect: maxRedirections === "undefined" || maxRedirections > 0 ? "follow" : "manual",
keepalive: !reset,
}));
// Throw if received 4xx or 5xx response indicating HTTP error
if (throwOnError && statusCode >= 400 && statusCode < 600) {
throw new Error(`Request failed with status code ${statusCode}`);
}
const body = resp.body ? new BodyReadable(resp) : null;
return { statusCode, headers, body, trailers, opaque: kEmptyObject, context: kEmptyObject };
}
export function stream() {
throw new Error("Not implemented in bun");
}
export function pipeline() {
throw new Error("Not implemented in bun");
}
export function connect() {
throw new Error("Not implemented in bun");
}
export function upgrade() {
throw new Error("Not implemented in bun");
}
export class MockClient {
constructor() {
throw new Error("Not implemented in bun");
}
}
export class MockPool {
constructor() {
throw new Error("Not implemented in bun");
}
}
export class MockAgent {
constructor() {
throw new Error("Not implemented in bun");
}
}
export function mockErrors() {
throw new Error("Not implemented in bun");
}
export function Undici() {
throw new Error("Not implemented in bun");
}
class Dispatcher extends EventEmitter {}
class Agent extends Dispatcher {}
class Pool extends Dispatcher {
request() {
throw new Error("Not implemented in bun");
}
}
class BalancedPool extends Dispatcher {}
class Client extends Dispatcher {
request() {
throw new Error("Not implemented in bun");
}
}
Undici.Dispatcher = Dispatcher;
Undici.Pool = Pool;
Undici.BalancedPool = BalancedPool;
Undici.Client = Client;
Undici.Agent = Agent;
Undici.buildConnector =
Undici.errors =
Undici.setGlobalDispatcher =
Undici.getGlobalDispatcher =
Undici.request =
Undici.stream =
Undici.pipeline =
Undici.connect =
Undici.upgrade =
Undici.MockClient =
Undici.MockPool =
Undici.MockAgent =
Undici.mockErrors =
notImplemented;
Undici.fetch = fetch;
export default {
fetch,
Response,
Headers,
Request,
URLSearchParams,
URL,
File,
FileReader,
FormData,
request,
stream,
pipeline,
connect,
upgrade,
MockClient,
MockPool,
MockAgent,
mockErrors,
Dispatcher,
Pool,
BalancedPool,
Client,
Agent,
Undici,
[Symbol.for("CommonJS")]: 0,
};
|