@hono/node-server 2.0.0-rc.1 → 2.0.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,6 +1,974 @@
1
- import { n as RequestError, t as getRequestListener } from "./listener-RIBxK9_x.mjs";
2
- import { createServer } from "node:http";
1
+ import { t as X_ALREADY_SENT } from "./constants-BLSFu_RU.mjs";
2
+ import { STATUS_CODES, createServer } from "node:http";
3
+ import { Http2ServerRequest, constants } from "node:http2";
4
+ import { Readable } from "node:stream";
5
+ import { defineWebSocketHelper } from "hono/ws";
3
6
 
7
+ //#region src/error.ts
8
+ var RequestError = class extends Error {
9
+ constructor(message, options) {
10
+ super(message, options);
11
+ this.name = "RequestError";
12
+ }
13
+ };
14
+
15
+ //#endregion
16
+ //#region src/url.ts
17
+ const reValidRequestUrl = /^\/[!#$&-;=?-\[\]_a-z~]*$/;
18
+ const reDotSegment = /\/\.\.?(?:[/?#]|$)/;
19
+ const reValidHost = /^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/;
20
+ const buildUrl = (scheme, host, incomingUrl) => {
21
+ const url = `${scheme}://${host}${incomingUrl}`;
22
+ if (!reValidHost.test(host)) {
23
+ const urlObj = new URL(url);
24
+ if (urlObj.hostname.length !== host.length && urlObj.hostname !== (host.includes(":") ? host.replace(/:\d+$/, "") : host).toLowerCase()) throw new RequestError("Invalid host header");
25
+ return urlObj.href;
26
+ } else if (incomingUrl.length === 0) return url + "/";
27
+ else {
28
+ if (incomingUrl.charCodeAt(0) !== 47) throw new RequestError("Invalid URL");
29
+ if (!reValidRequestUrl.test(incomingUrl) || reDotSegment.test(incomingUrl)) return new URL(url).href;
30
+ return url;
31
+ }
32
+ };
33
+
34
+ //#endregion
35
+ //#region src/request.ts
36
+ const toRequestError = (e) => {
37
+ if (e instanceof RequestError) return e;
38
+ return new RequestError(e.message, { cause: e });
39
+ };
40
+ const GlobalRequest = global.Request;
41
+ var Request$1 = class extends GlobalRequest {
42
+ constructor(input, options) {
43
+ if (typeof input === "object" && getRequestCache in input) {
44
+ const hasReplacementBody = options !== void 0 && "body" in options && options.body != null;
45
+ if (input[bodyConsumedDirectlyKey] && !hasReplacementBody) throw new TypeError("Cannot construct a Request with a Request object that has already been used.");
46
+ input = input[getRequestCache]();
47
+ }
48
+ if (typeof (options?.body)?.getReader !== "undefined") options.duplex ??= "half";
49
+ super(input, options);
50
+ }
51
+ };
52
+ const newHeadersFromIncoming = (incoming) => {
53
+ const headerRecord = [];
54
+ const rawHeaders = incoming.rawHeaders;
55
+ for (let i = 0, len = rawHeaders.length; i < len; i += 2) {
56
+ const key = rawHeaders[i];
57
+ if (key.charCodeAt(0) !== 58) headerRecord.push([key, rawHeaders[i + 1]]);
58
+ }
59
+ return new Headers(headerRecord);
60
+ };
61
+ const wrapBodyStream = Symbol("wrapBodyStream");
62
+ const newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
63
+ const init = {
64
+ method,
65
+ headers,
66
+ signal: abortController.signal
67
+ };
68
+ if (method === "TRACE") {
69
+ init.method = "GET";
70
+ const req = new Request$1(url, init);
71
+ Object.defineProperty(req, "method", { get() {
72
+ return "TRACE";
73
+ } });
74
+ return req;
75
+ }
76
+ if (!(method === "GET" || method === "HEAD")) if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) init.body = new ReadableStream({ start(controller) {
77
+ controller.enqueue(incoming.rawBody);
78
+ controller.close();
79
+ } });
80
+ else if (incoming[wrapBodyStream]) {
81
+ let reader;
82
+ init.body = new ReadableStream({ async pull(controller) {
83
+ try {
84
+ reader ||= Readable.toWeb(incoming).getReader();
85
+ const { done, value } = await reader.read();
86
+ if (done) controller.close();
87
+ else controller.enqueue(value);
88
+ } catch (error) {
89
+ controller.error(error);
90
+ }
91
+ } });
92
+ } else init.body = Readable.toWeb(incoming);
93
+ return new Request$1(url, init);
94
+ };
95
+ const getRequestCache = Symbol("getRequestCache");
96
+ const requestCache = Symbol("requestCache");
97
+ const incomingKey = Symbol("incomingKey");
98
+ const urlKey = Symbol("urlKey");
99
+ const methodKey = Symbol("methodKey");
100
+ const headersKey = Symbol("headersKey");
101
+ const abortControllerKey = Symbol("abortControllerKey");
102
+ const getAbortController = Symbol("getAbortController");
103
+ const abortRequest = Symbol("abortRequest");
104
+ const bodyBufferKey = Symbol("bodyBuffer");
105
+ const bodyReadPromiseKey = Symbol("bodyReadPromise");
106
+ const bodyConsumedDirectlyKey = Symbol("bodyConsumedDirectly");
107
+ const bodyLockReaderKey = Symbol("bodyLockReader");
108
+ const abortReasonKey = Symbol("abortReason");
109
+ const newBodyUnusableError = () => {
110
+ return /* @__PURE__ */ new TypeError("Body is unusable");
111
+ };
112
+ const rejectBodyUnusable = () => {
113
+ return Promise.reject(newBodyUnusableError());
114
+ };
115
+ const textDecoder = new TextDecoder();
116
+ const consumeBodyDirectOnce = (request) => {
117
+ if (request[bodyConsumedDirectlyKey]) return rejectBodyUnusable();
118
+ request[bodyConsumedDirectlyKey] = true;
119
+ };
120
+ const toArrayBuffer = (buf) => {
121
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
122
+ };
123
+ const contentType = (request) => {
124
+ return (request[headersKey] ||= newHeadersFromIncoming(request[incomingKey])).get("content-type") || "";
125
+ };
126
+ const methodTokenRegExp = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
127
+ const normalizeIncomingMethod = (method) => {
128
+ if (typeof method !== "string" || method.length === 0) return "GET";
129
+ switch (method) {
130
+ case "DELETE":
131
+ case "GET":
132
+ case "HEAD":
133
+ case "OPTIONS":
134
+ case "POST":
135
+ case "PUT": return method;
136
+ }
137
+ const upper = method.toUpperCase();
138
+ switch (upper) {
139
+ case "DELETE":
140
+ case "GET":
141
+ case "HEAD":
142
+ case "OPTIONS":
143
+ case "POST":
144
+ case "PUT": return upper;
145
+ default: return method;
146
+ }
147
+ };
148
+ const validateDirectReadMethod = (method) => {
149
+ if (!methodTokenRegExp.test(method)) return /* @__PURE__ */ new TypeError(`'${method}' is not a valid HTTP method.`);
150
+ const normalized = method.toUpperCase();
151
+ if (normalized === "CONNECT" || normalized === "TRACK" || normalized === "TRACE" && method !== "TRACE") return /* @__PURE__ */ new TypeError(`'${method}' HTTP method is unsupported.`);
152
+ };
153
+ const readBodyWithFastPath = (request, method, fromBuffer) => {
154
+ if (request[bodyConsumedDirectlyKey]) return rejectBodyUnusable();
155
+ const methodName = request.method;
156
+ if (methodName === "GET" || methodName === "HEAD") return request[getRequestCache]()[method]();
157
+ const methodValidationError = validateDirectReadMethod(methodName);
158
+ if (methodValidationError) return Promise.reject(methodValidationError);
159
+ if (request[requestCache]) {
160
+ if (methodName !== "TRACE") return request[requestCache][method]();
161
+ }
162
+ const alreadyUsedError = consumeBodyDirectOnce(request);
163
+ if (alreadyUsedError) return alreadyUsedError;
164
+ const raw = readRawBodyIfAvailable(request);
165
+ if (raw) {
166
+ const result = Promise.resolve(fromBuffer(raw, request));
167
+ request[bodyBufferKey] = void 0;
168
+ return result;
169
+ }
170
+ return readBodyDirect(request).then((buf) => {
171
+ const result = fromBuffer(buf, request);
172
+ request[bodyBufferKey] = void 0;
173
+ return result;
174
+ });
175
+ };
176
+ const readRawBodyIfAvailable = (request) => {
177
+ const incoming = request[incomingKey];
178
+ if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) return incoming.rawBody;
179
+ };
180
+ const readBodyDirect = (request) => {
181
+ if (request[bodyBufferKey]) return Promise.resolve(request[bodyBufferKey]);
182
+ if (request[bodyReadPromiseKey]) return request[bodyReadPromiseKey];
183
+ const incoming = request[incomingKey];
184
+ if (Readable.isDisturbed(incoming)) return rejectBodyUnusable();
185
+ const promise = new Promise((resolve, reject) => {
186
+ const chunks = [];
187
+ let settled = false;
188
+ const finish = (callback) => {
189
+ if (settled) return;
190
+ settled = true;
191
+ cleanup();
192
+ callback();
193
+ };
194
+ const onData = (chunk) => {
195
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
196
+ };
197
+ const onEnd = () => {
198
+ finish(() => {
199
+ const buffer = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks);
200
+ request[bodyBufferKey] = buffer;
201
+ resolve(buffer);
202
+ });
203
+ };
204
+ const onError = (error) => {
205
+ finish(() => {
206
+ reject(error);
207
+ });
208
+ };
209
+ const onClose = () => {
210
+ if (incoming.readableEnded) {
211
+ onEnd();
212
+ return;
213
+ }
214
+ finish(() => {
215
+ if (incoming.errored) {
216
+ reject(incoming.errored);
217
+ return;
218
+ }
219
+ const reason = request[abortReasonKey];
220
+ if (reason !== void 0) {
221
+ reject(reason instanceof Error ? reason : new Error(String(reason)));
222
+ return;
223
+ }
224
+ reject(/* @__PURE__ */ new Error("Client connection prematurely closed."));
225
+ });
226
+ };
227
+ const cleanup = () => {
228
+ incoming.off("data", onData);
229
+ incoming.off("end", onEnd);
230
+ incoming.off("error", onError);
231
+ incoming.off("close", onClose);
232
+ request[bodyReadPromiseKey] = void 0;
233
+ };
234
+ incoming.on("data", onData);
235
+ incoming.on("end", onEnd);
236
+ incoming.on("error", onError);
237
+ incoming.on("close", onClose);
238
+ queueMicrotask(() => {
239
+ if (settled) return;
240
+ if (incoming.readableEnded) onEnd();
241
+ else if (incoming.errored) onError(incoming.errored);
242
+ else if (incoming.destroyed) onClose();
243
+ });
244
+ });
245
+ request[bodyReadPromiseKey] = promise;
246
+ return promise;
247
+ };
248
+ const requestPrototype = {
249
+ get method() {
250
+ return this[methodKey];
251
+ },
252
+ get url() {
253
+ return this[urlKey];
254
+ },
255
+ get headers() {
256
+ return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
257
+ },
258
+ [abortRequest](reason) {
259
+ if (this[abortReasonKey] === void 0) this[abortReasonKey] = reason;
260
+ const abortController = this[abortControllerKey];
261
+ if (abortController && !abortController.signal.aborted) abortController.abort(reason);
262
+ },
263
+ [getAbortController]() {
264
+ this[abortControllerKey] ||= new AbortController();
265
+ if (this[abortReasonKey] !== void 0 && !this[abortControllerKey].signal.aborted) this[abortControllerKey].abort(this[abortReasonKey]);
266
+ return this[abortControllerKey];
267
+ },
268
+ [getRequestCache]() {
269
+ const abortController = this[getAbortController]();
270
+ if (this[requestCache]) return this[requestCache];
271
+ const method = this.method;
272
+ if (this[bodyConsumedDirectlyKey] && !(method === "GET" || method === "HEAD")) {
273
+ this[bodyBufferKey] = void 0;
274
+ const init = {
275
+ method: method === "TRACE" ? "GET" : method,
276
+ headers: this.headers,
277
+ signal: abortController.signal
278
+ };
279
+ if (method !== "TRACE") {
280
+ init.body = new ReadableStream({ start(c) {
281
+ c.close();
282
+ } });
283
+ init.duplex = "half";
284
+ }
285
+ const req = new Request$1(this[urlKey], init);
286
+ if (method === "TRACE") Object.defineProperty(req, "method", { get() {
287
+ return "TRACE";
288
+ } });
289
+ return this[requestCache] = req;
290
+ }
291
+ return this[requestCache] = newRequestFromIncoming(this.method, this[urlKey], this.headers, this[incomingKey], abortController);
292
+ },
293
+ get body() {
294
+ if (!this[bodyConsumedDirectlyKey]) return this[getRequestCache]().body;
295
+ const request = this[getRequestCache]();
296
+ if (!this[bodyLockReaderKey] && request.body) this[bodyLockReaderKey] = request.body.getReader();
297
+ return request.body;
298
+ },
299
+ get bodyUsed() {
300
+ if (this[bodyConsumedDirectlyKey]) return true;
301
+ if (this[requestCache]) return this[requestCache].bodyUsed;
302
+ return false;
303
+ }
304
+ };
305
+ Object.defineProperty(requestPrototype, "signal", { get() {
306
+ return this[getAbortController]().signal;
307
+ } });
308
+ [
309
+ "cache",
310
+ "credentials",
311
+ "destination",
312
+ "integrity",
313
+ "mode",
314
+ "redirect",
315
+ "referrer",
316
+ "referrerPolicy",
317
+ "keepalive"
318
+ ].forEach((k) => {
319
+ Object.defineProperty(requestPrototype, k, { get() {
320
+ return this[getRequestCache]()[k];
321
+ } });
322
+ });
323
+ ["clone", "formData"].forEach((k) => {
324
+ Object.defineProperty(requestPrototype, k, { value: function() {
325
+ if (this[bodyConsumedDirectlyKey]) {
326
+ if (k === "clone") throw newBodyUnusableError();
327
+ return rejectBodyUnusable();
328
+ }
329
+ return this[getRequestCache]()[k]();
330
+ } });
331
+ });
332
+ Object.defineProperty(requestPrototype, "text", { value: function() {
333
+ return readBodyWithFastPath(this, "text", (buf) => textDecoder.decode(buf));
334
+ } });
335
+ Object.defineProperty(requestPrototype, "arrayBuffer", { value: function() {
336
+ return readBodyWithFastPath(this, "arrayBuffer", (buf) => toArrayBuffer(buf));
337
+ } });
338
+ Object.defineProperty(requestPrototype, "blob", { value: function() {
339
+ return readBodyWithFastPath(this, "blob", (buf, request) => {
340
+ const type = contentType(request);
341
+ const init = type ? { headers: { "content-type": type } } : void 0;
342
+ return new Response(buf, init).blob();
343
+ });
344
+ } });
345
+ Object.defineProperty(requestPrototype, "json", { value: function() {
346
+ if (this[bodyConsumedDirectlyKey]) return rejectBodyUnusable();
347
+ return this.text().then(JSON.parse);
348
+ } });
349
+ Object.defineProperty(requestPrototype, Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) {
350
+ return `Request (lightweight) ${inspectFn({
351
+ method: this.method,
352
+ url: this.url,
353
+ headers: this.headers,
354
+ nativeRequest: this[requestCache]
355
+ }, {
356
+ ...options,
357
+ depth: depth == null ? null : depth - 1
358
+ })}`;
359
+ } });
360
+ Object.setPrototypeOf(requestPrototype, Request$1.prototype);
361
+ const newRequest = (incoming, defaultHostname) => {
362
+ const req = Object.create(requestPrototype);
363
+ req[incomingKey] = incoming;
364
+ req[methodKey] = normalizeIncomingMethod(incoming.method);
365
+ const incomingUrl = incoming.url || "";
366
+ if (incomingUrl[0] !== "/" && (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
367
+ if (incoming instanceof Http2ServerRequest) throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
368
+ try {
369
+ req[urlKey] = new URL(incomingUrl).href;
370
+ } catch (e) {
371
+ throw new RequestError("Invalid absolute URL", { cause: e });
372
+ }
373
+ return req;
374
+ }
375
+ const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
376
+ if (!host) throw new RequestError("Missing host header");
377
+ let scheme;
378
+ if (incoming instanceof Http2ServerRequest) {
379
+ scheme = incoming.scheme;
380
+ if (!(scheme === "http" || scheme === "https")) throw new RequestError("Unsupported scheme");
381
+ } else scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
382
+ try {
383
+ req[urlKey] = buildUrl(scheme, host, incomingUrl);
384
+ } catch (e) {
385
+ if (e instanceof RequestError) throw e;
386
+ else throw new RequestError("Invalid URL", { cause: e });
387
+ }
388
+ return req;
389
+ };
390
+
391
+ //#endregion
392
+ //#region src/response.ts
393
+ const defaultContentType = "text/plain; charset=UTF-8";
394
+ const responseCache = Symbol("responseCache");
395
+ const getResponseCache = Symbol("getResponseCache");
396
+ const cacheKey = Symbol("cache");
397
+ const GlobalResponse = global.Response;
398
+ var Response$1 = class Response$1 {
399
+ #body;
400
+ #init;
401
+ [getResponseCache]() {
402
+ delete this[cacheKey];
403
+ return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
404
+ }
405
+ constructor(body, init) {
406
+ let headers;
407
+ this.#body = body;
408
+ if (init instanceof Response$1) {
409
+ const cachedGlobalResponse = init[responseCache];
410
+ if (cachedGlobalResponse) {
411
+ this.#init = cachedGlobalResponse;
412
+ this[getResponseCache]();
413
+ return;
414
+ } else {
415
+ this.#init = init.#init;
416
+ headers = new Headers(init.#init.headers);
417
+ }
418
+ } else this.#init = init;
419
+ if (body == null || typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) this[cacheKey] = [
420
+ init?.status || 200,
421
+ body ?? null,
422
+ headers || init?.headers
423
+ ];
424
+ }
425
+ get headers() {
426
+ const cache = this[cacheKey];
427
+ if (cache) {
428
+ if (!(cache[2] instanceof Headers)) cache[2] = new Headers(cache[2] || (cache[1] === null ? void 0 : { "content-type": defaultContentType }));
429
+ return cache[2];
430
+ }
431
+ return this[getResponseCache]().headers;
432
+ }
433
+ get status() {
434
+ return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
435
+ }
436
+ get ok() {
437
+ const status = this.status;
438
+ return status >= 200 && status < 300;
439
+ }
440
+ };
441
+ [
442
+ "body",
443
+ "bodyUsed",
444
+ "redirected",
445
+ "statusText",
446
+ "trailers",
447
+ "type",
448
+ "url"
449
+ ].forEach((k) => {
450
+ Object.defineProperty(Response$1.prototype, k, { get() {
451
+ return this[getResponseCache]()[k];
452
+ } });
453
+ });
454
+ [
455
+ "arrayBuffer",
456
+ "blob",
457
+ "clone",
458
+ "formData",
459
+ "json",
460
+ "text"
461
+ ].forEach((k) => {
462
+ Object.defineProperty(Response$1.prototype, k, { value: function() {
463
+ return this[getResponseCache]()[k]();
464
+ } });
465
+ });
466
+ Object.defineProperty(Response$1.prototype, Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) {
467
+ return `Response (lightweight) ${inspectFn({
468
+ status: this.status,
469
+ headers: this.headers,
470
+ ok: this.ok,
471
+ nativeResponse: this[responseCache]
472
+ }, {
473
+ ...options,
474
+ depth: depth == null ? null : depth - 1
475
+ })}`;
476
+ } });
477
+ Object.setPrototypeOf(Response$1, GlobalResponse);
478
+ Object.setPrototypeOf(Response$1.prototype, GlobalResponse.prototype);
479
+ const validRedirectUrl = /^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/;
480
+ const parseRedirectUrl = (url) => {
481
+ if (url instanceof URL) return url.href;
482
+ if (validRedirectUrl.test(url)) return url;
483
+ return new URL(url).href;
484
+ };
485
+ const validRedirectStatuses = new Set([
486
+ 301,
487
+ 302,
488
+ 303,
489
+ 307,
490
+ 308
491
+ ]);
492
+ Object.defineProperty(Response$1, "redirect", {
493
+ value: function redirect(url, status = 302) {
494
+ if (!validRedirectStatuses.has(status)) throw new RangeError("Invalid status code");
495
+ return new Response$1(null, {
496
+ status,
497
+ headers: { location: parseRedirectUrl(url) }
498
+ });
499
+ },
500
+ writable: true,
501
+ configurable: true
502
+ });
503
+ Object.defineProperty(Response$1, "json", {
504
+ value: function json(data, init) {
505
+ const body = JSON.stringify(data);
506
+ if (body === void 0) throw new TypeError("The data is not JSON serializable");
507
+ const initHeaders = init?.headers;
508
+ let headers;
509
+ if (initHeaders) {
510
+ headers = new Headers(initHeaders);
511
+ if (!headers.has("content-type")) headers.set("content-type", "application/json");
512
+ } else headers = { "content-type": "application/json" };
513
+ return new Response$1(body, {
514
+ status: init?.status ?? 200,
515
+ statusText: init?.statusText,
516
+ headers
517
+ });
518
+ },
519
+ writable: true,
520
+ configurable: true
521
+ });
522
+
523
+ //#endregion
524
+ //#region src/utils.ts
525
+ async function readWithoutBlocking(readPromise) {
526
+ return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
527
+ }
528
+ function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
529
+ const cancel = (error) => {
530
+ reader.cancel(error).catch(() => {});
531
+ };
532
+ writable.on("close", cancel);
533
+ writable.on("error", cancel);
534
+ (currentReadPromise ?? reader.read()).then(flow, handleStreamError);
535
+ return reader.closed.finally(() => {
536
+ writable.off("close", cancel);
537
+ writable.off("error", cancel);
538
+ });
539
+ function handleStreamError(error) {
540
+ if (error) writable.destroy(error);
541
+ }
542
+ function onDrain() {
543
+ reader.read().then(flow, handleStreamError);
544
+ }
545
+ function flow({ done, value }) {
546
+ try {
547
+ if (done) writable.end();
548
+ else if (!writable.write(value)) writable.once("drain", onDrain);
549
+ else return reader.read().then(flow, handleStreamError);
550
+ } catch (e) {
551
+ handleStreamError(e);
552
+ }
553
+ }
554
+ }
555
+ function writeFromReadableStream(stream, writable) {
556
+ if (stream.locked) throw new TypeError("ReadableStream is locked.");
557
+ else if (writable.destroyed) return;
558
+ return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
559
+ }
560
+ const buildOutgoingHttpHeaders = (headers, defaultContentType) => {
561
+ const res = {};
562
+ if (!(headers instanceof Headers)) headers = new Headers(headers ?? void 0);
563
+ if (headers.has("set-cookie")) {
564
+ const cookies = [];
565
+ for (const [k, v] of headers) if (k === "set-cookie") cookies.push(v);
566
+ else res[k] = v;
567
+ if (cookies.length > 0) res["set-cookie"] = cookies;
568
+ } else for (const [k, v] of headers) res[k] = v;
569
+ if (defaultContentType) res["content-type"] ??= defaultContentType;
570
+ return res;
571
+ };
572
+
573
+ //#endregion
574
+ //#region src/listener.ts
575
+ const outgoingEnded = Symbol("outgoingEnded");
576
+ const incomingDraining = Symbol("incomingDraining");
577
+ const DRAIN_TIMEOUT_MS = 500;
578
+ const MAX_DRAIN_BYTES = 64 * 1024 * 1024;
579
+ const drainIncoming = (incoming) => {
580
+ const incomingWithDrainState = incoming;
581
+ if (incoming.destroyed || incomingWithDrainState[incomingDraining]) return;
582
+ incomingWithDrainState[incomingDraining] = true;
583
+ if (incoming instanceof Http2ServerRequest) {
584
+ try {
585
+ incoming.stream?.close?.(constants.NGHTTP2_NO_ERROR);
586
+ } catch {}
587
+ return;
588
+ }
589
+ let bytesRead = 0;
590
+ const cleanup = () => {
591
+ clearTimeout(timer);
592
+ incoming.off("data", onData);
593
+ incoming.off("end", cleanup);
594
+ incoming.off("error", cleanup);
595
+ };
596
+ const forceClose = () => {
597
+ cleanup();
598
+ const socket = incoming.socket;
599
+ if (socket && !socket.destroyed) socket.destroySoon();
600
+ };
601
+ const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);
602
+ timer.unref?.();
603
+ const onData = (chunk) => {
604
+ bytesRead += chunk.length;
605
+ if (bytesRead > MAX_DRAIN_BYTES) forceClose();
606
+ };
607
+ incoming.on("data", onData);
608
+ incoming.on("end", cleanup);
609
+ incoming.on("error", cleanup);
610
+ incoming.resume();
611
+ };
612
+ const makeCloseHandler = (req, incoming, outgoing, needsBodyCleanup) => () => {
613
+ if (incoming.errored) req[abortRequest](incoming.errored.toString());
614
+ else if (!outgoing.writableFinished) req[abortRequest]("Client connection prematurely closed.");
615
+ if (needsBodyCleanup && !incoming.readableEnded) setTimeout(() => {
616
+ if (!incoming.readableEnded) setTimeout(() => {
617
+ drainIncoming(incoming);
618
+ });
619
+ });
620
+ };
621
+ const isImmediateCacheableResponse = (res) => {
622
+ if (!(cacheKey in res)) return false;
623
+ const body = res[cacheKey][1];
624
+ return body === null || typeof body === "string" || body instanceof Uint8Array;
625
+ };
626
+ const handleRequestError = () => new Response(null, { status: 400 });
627
+ const handleFetchError = (e) => new Response(null, { status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500 });
628
+ const handleResponseError = (e, outgoing) => {
629
+ const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
630
+ if (err.code === "ERR_STREAM_PREMATURE_CLOSE") console.info("The user aborted a request.");
631
+ else {
632
+ console.error(e);
633
+ if (!outgoing.headersSent) outgoing.writeHead(500, { "Content-Type": "text/plain" });
634
+ outgoing.end(`Error: ${err.message}`);
635
+ outgoing.destroy(err);
636
+ }
637
+ };
638
+ const flushHeaders = (outgoing) => {
639
+ if ("flushHeaders" in outgoing && outgoing.writable) outgoing.flushHeaders();
640
+ };
641
+ const responseViaCache = async (res, outgoing) => {
642
+ let [status, body, header] = res[cacheKey];
643
+ if (!header) {
644
+ if (body === null) {
645
+ outgoing.writeHead(status);
646
+ outgoing.end();
647
+ } else if (typeof body === "string") {
648
+ outgoing.writeHead(status, {
649
+ "Content-Type": defaultContentType,
650
+ "Content-Length": Buffer.byteLength(body)
651
+ });
652
+ outgoing.end(body);
653
+ } else if (body instanceof Uint8Array) {
654
+ outgoing.writeHead(status, {
655
+ "Content-Type": defaultContentType,
656
+ "Content-Length": body.byteLength
657
+ });
658
+ outgoing.end(body);
659
+ } else if (body instanceof Blob) {
660
+ outgoing.writeHead(status, {
661
+ "Content-Type": defaultContentType,
662
+ "Content-Length": body.size
663
+ });
664
+ outgoing.end(new Uint8Array(await body.arrayBuffer()));
665
+ } else {
666
+ outgoing.writeHead(status, { "Content-Type": defaultContentType });
667
+ flushHeaders(outgoing);
668
+ await writeFromReadableStream(body, outgoing)?.catch((e) => handleResponseError(e, outgoing));
669
+ }
670
+ outgoing[outgoingEnded]?.();
671
+ return;
672
+ }
673
+ let hasContentLength = false;
674
+ if (header instanceof Headers) {
675
+ hasContentLength = header.has("content-length");
676
+ header = buildOutgoingHttpHeaders(header, body === null ? void 0 : defaultContentType);
677
+ } else if (Array.isArray(header)) {
678
+ const headerObj = new Headers(header);
679
+ hasContentLength = headerObj.has("content-length");
680
+ header = buildOutgoingHttpHeaders(headerObj, body === null ? void 0 : defaultContentType);
681
+ } else for (const key in header) if (key.length === 14 && key.toLowerCase() === "content-length") {
682
+ hasContentLength = true;
683
+ break;
684
+ }
685
+ if (!hasContentLength) {
686
+ if (typeof body === "string") header["Content-Length"] = Buffer.byteLength(body);
687
+ else if (body instanceof Uint8Array) header["Content-Length"] = body.byteLength;
688
+ else if (body instanceof Blob) header["Content-Length"] = body.size;
689
+ }
690
+ outgoing.writeHead(status, header);
691
+ if (body == null) outgoing.end();
692
+ else if (typeof body === "string" || body instanceof Uint8Array) outgoing.end(body);
693
+ else if (body instanceof Blob) outgoing.end(new Uint8Array(await body.arrayBuffer()));
694
+ else {
695
+ flushHeaders(outgoing);
696
+ await writeFromReadableStream(body, outgoing)?.catch((e) => handleResponseError(e, outgoing));
697
+ }
698
+ outgoing[outgoingEnded]?.();
699
+ };
700
+ const isPromise = (res) => typeof res.then === "function";
701
+ const responseViaResponseObject = async (res, outgoing, options = {}) => {
702
+ if (isPromise(res)) if (options.errorHandler) try {
703
+ res = await res;
704
+ } catch (err) {
705
+ const errRes = await options.errorHandler(err);
706
+ if (!errRes) return;
707
+ res = errRes;
708
+ }
709
+ else res = await res.catch(handleFetchError);
710
+ if (cacheKey in res) return responseViaCache(res, outgoing);
711
+ const resHeaderRecord = buildOutgoingHttpHeaders(res.headers, res.body === null ? void 0 : defaultContentType);
712
+ if (res.body) {
713
+ const reader = res.body.getReader();
714
+ const values = [];
715
+ let done = false;
716
+ let currentReadPromise = void 0;
717
+ if (resHeaderRecord["transfer-encoding"] !== "chunked") {
718
+ let maxReadCount = 2;
719
+ for (let i = 0; i < maxReadCount; i++) {
720
+ currentReadPromise ||= reader.read();
721
+ const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
722
+ console.error(e);
723
+ done = true;
724
+ });
725
+ if (!chunk) {
726
+ if (i === 1) {
727
+ await new Promise((resolve) => setTimeout(resolve));
728
+ maxReadCount = 3;
729
+ continue;
730
+ }
731
+ break;
732
+ }
733
+ currentReadPromise = void 0;
734
+ if (chunk.value) values.push(chunk.value);
735
+ if (chunk.done) {
736
+ done = true;
737
+ break;
738
+ }
739
+ }
740
+ if (done && !("content-length" in resHeaderRecord)) resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
741
+ }
742
+ outgoing.writeHead(res.status, resHeaderRecord);
743
+ values.forEach((value) => {
744
+ outgoing.write(value);
745
+ });
746
+ if (done) outgoing.end();
747
+ else {
748
+ if (values.length === 0) flushHeaders(outgoing);
749
+ await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
750
+ }
751
+ } else if (resHeaderRecord[X_ALREADY_SENT]) {} else {
752
+ outgoing.writeHead(res.status, resHeaderRecord);
753
+ outgoing.end();
754
+ }
755
+ outgoing[outgoingEnded]?.();
756
+ };
757
+ const getRequestListener = (fetchCallback, options = {}) => {
758
+ const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
759
+ if (options.overrideGlobalObjects !== false && global.Request !== Request$1) {
760
+ Object.defineProperty(global, "Request", { value: Request$1 });
761
+ Object.defineProperty(global, "Response", { value: Response$1 });
762
+ }
763
+ return async (incoming, outgoing) => {
764
+ let res, req;
765
+ let needsBodyCleanup = false;
766
+ let closeHandlerAttached = false;
767
+ const ensureCloseHandler = () => {
768
+ if (!req || closeHandlerAttached) return;
769
+ closeHandlerAttached = true;
770
+ outgoing.on("close", makeCloseHandler(req, incoming, outgoing, needsBodyCleanup));
771
+ };
772
+ try {
773
+ req = newRequest(incoming, options.hostname);
774
+ needsBodyCleanup = autoCleanupIncoming && !(incoming.method === "GET" || incoming.method === "HEAD");
775
+ if (needsBodyCleanup) {
776
+ incoming[wrapBodyStream] = true;
777
+ if (incoming instanceof Http2ServerRequest) outgoing[outgoingEnded] = () => {
778
+ if (!incoming.readableEnded) setTimeout(() => {
779
+ if (!incoming.readableEnded) setTimeout(() => {
780
+ incoming.destroy();
781
+ outgoing.destroy();
782
+ });
783
+ });
784
+ };
785
+ }
786
+ res = fetchCallback(req, {
787
+ incoming,
788
+ outgoing
789
+ });
790
+ if (!isPromise(res) && isImmediateCacheableResponse(res)) {
791
+ if (needsBodyCleanup && !incoming.readableEnded) outgoing.once("finish", () => {
792
+ if (!incoming.readableEnded) drainIncoming(incoming);
793
+ });
794
+ return responseViaCache(res, outgoing);
795
+ }
796
+ ensureCloseHandler();
797
+ } catch (e) {
798
+ if (!res) if (options.errorHandler) {
799
+ ensureCloseHandler();
800
+ res = await options.errorHandler(req ? e : toRequestError(e));
801
+ if (!res) return;
802
+ } else if (!req) res = handleRequestError();
803
+ else res = handleFetchError(e);
804
+ else return handleResponseError(e, outgoing);
805
+ }
806
+ try {
807
+ return await responseViaResponseObject(res, outgoing, options);
808
+ } catch (e) {
809
+ return handleResponseError(e, outgoing);
810
+ }
811
+ };
812
+ };
813
+
814
+ //#endregion
815
+ //#region src/websocket.ts
816
+ /**
817
+ * @link https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent
818
+ */
819
+ const CloseEvent = globalThis.CloseEvent ?? class extends Event {
820
+ #eventInitDict;
821
+ constructor(type, eventInitDict = {}) {
822
+ super(type, eventInitDict);
823
+ this.#eventInitDict = eventInitDict;
824
+ }
825
+ get wasClean() {
826
+ return this.#eventInitDict.wasClean ?? false;
827
+ }
828
+ get code() {
829
+ return this.#eventInitDict.code ?? 0;
830
+ }
831
+ get reason() {
832
+ return this.#eventInitDict.reason ?? "";
833
+ }
834
+ };
835
+ const generateConnectionSymbol = () => Symbol("connection");
836
+ const CONNECTION_SYMBOL_KEY = Symbol("CONNECTION_SYMBOL_KEY");
837
+ const WAIT_FOR_WEBSOCKET_SYMBOL = Symbol("WAIT_FOR_WEBSOCKET_SYMBOL");
838
+ const rejectUpgradeRequest = (socket, status) => {
839
+ socket.end(`HTTP/1.1 ${status.toString()} ${STATUS_CODES[status] ?? ""}\r\nConnection: close\r
840
+ Content-Length: 0\r
841
+ \r
842
+ `);
843
+ };
844
+ const createUpgradeRequest = (request) => {
845
+ const protocol = request.socket.encrypted ? "https" : "http";
846
+ const url = new URL(request.url ?? "/", `${protocol}://${request.headers.host ?? "localhost"}`);
847
+ const headers = new Headers();
848
+ for (const key in request.headers) {
849
+ const value = request.headers[key];
850
+ if (!value) continue;
851
+ headers.append(key, Array.isArray(value) ? value[0] : value);
852
+ }
853
+ return new Request(url, { headers });
854
+ };
855
+ const setupWebSocket = (options) => {
856
+ const { server, fetchCallback, wss } = options;
857
+ const waiterMap = /* @__PURE__ */ new Map();
858
+ wss.on("connection", (ws, request) => {
859
+ const waiter = waiterMap.get(request);
860
+ if (waiter) {
861
+ waiter.resolve(ws);
862
+ waiterMap.delete(request);
863
+ }
864
+ });
865
+ const waitForWebSocket = (request, connectionSymbol) => {
866
+ return new Promise((resolve) => {
867
+ waiterMap.set(request, {
868
+ resolve,
869
+ connectionSymbol
870
+ });
871
+ });
872
+ };
873
+ server.on("upgrade", async (request, socket, head) => {
874
+ if (request.headers.upgrade?.toLowerCase() !== "websocket") return;
875
+ const env = {
876
+ incoming: request,
877
+ outgoing: void 0,
878
+ wss,
879
+ [WAIT_FOR_WEBSOCKET_SYMBOL]: waitForWebSocket
880
+ };
881
+ let status = 400;
882
+ try {
883
+ const response = await fetchCallback(createUpgradeRequest(request), env);
884
+ if (response instanceof Response) status = response.status;
885
+ } catch {
886
+ if (server.listenerCount("upgrade") === 1) rejectUpgradeRequest(socket, 500);
887
+ return;
888
+ }
889
+ const waiter = waiterMap.get(request);
890
+ if (!waiter || waiter.connectionSymbol !== env[CONNECTION_SYMBOL_KEY]) {
891
+ waiterMap.delete(request);
892
+ if (server.listenerCount("upgrade") === 1) rejectUpgradeRequest(socket, status);
893
+ return;
894
+ }
895
+ wss.handleUpgrade(request, socket, head, (ws) => {
896
+ wss.emit("connection", ws, request);
897
+ });
898
+ });
899
+ server.on("close", () => {
900
+ wss.close();
901
+ });
902
+ };
903
+ const upgradeWebSocket = defineWebSocketHelper(async (c, events, options) => {
904
+ if (c.req.header("upgrade")?.toLowerCase() !== "websocket") return;
905
+ const env = c.env;
906
+ const waitForWebSocket = env[WAIT_FOR_WEBSOCKET_SYMBOL];
907
+ if (!waitForWebSocket || !env.incoming) return new Response(null, { status: 500 });
908
+ const connectionSymbol = generateConnectionSymbol();
909
+ env[CONNECTION_SYMBOL_KEY] = connectionSymbol;
910
+ (async () => {
911
+ const ws = await waitForWebSocket(env.incoming, connectionSymbol);
912
+ const messagesReceivedInStarting = [];
913
+ const bufferMessage = (data, isBinary) => {
914
+ messagesReceivedInStarting.push([data, isBinary]);
915
+ };
916
+ ws.on("message", bufferMessage);
917
+ const ctx = {
918
+ binaryType: "arraybuffer",
919
+ close(code, reason) {
920
+ ws.close(code, reason);
921
+ },
922
+ protocol: ws.protocol,
923
+ raw: ws,
924
+ get readyState() {
925
+ return ws.readyState;
926
+ },
927
+ send(source, opts) {
928
+ ws.send(source, { compress: opts?.compress });
929
+ },
930
+ url: new URL(c.req.url)
931
+ };
932
+ try {
933
+ events?.onOpen?.(new Event("open"), ctx);
934
+ } catch (e) {
935
+ (options?.onError ?? console.error)(e);
936
+ }
937
+ const handleMessage = (data, isBinary) => {
938
+ const datas = Array.isArray(data) ? data : [data];
939
+ for (const data of datas) try {
940
+ events?.onMessage?.(new MessageEvent("message", { data: isBinary ? data instanceof ArrayBuffer ? data : data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength) : data.toString("utf-8") }), ctx);
941
+ } catch (e) {
942
+ (options?.onError ?? console.error)(e);
943
+ }
944
+ };
945
+ ws.off("message", bufferMessage);
946
+ for (const message of messagesReceivedInStarting) handleMessage(...message);
947
+ ws.on("message", (data, isBinary) => {
948
+ handleMessage(data, isBinary);
949
+ });
950
+ ws.on("close", (code, reason) => {
951
+ try {
952
+ events?.onClose?.(new CloseEvent("close", {
953
+ code,
954
+ reason: reason.toString()
955
+ }), ctx);
956
+ } catch (e) {
957
+ (options?.onError ?? console.error)(e);
958
+ }
959
+ });
960
+ ws.on("error", (error) => {
961
+ try {
962
+ events?.onError?.(new ErrorEvent("error", { error }), ctx);
963
+ } catch (e) {
964
+ (options?.onError ?? console.error)(e);
965
+ }
966
+ });
967
+ })();
968
+ return new Response();
969
+ });
970
+
971
+ //#endregion
4
972
  //#region src/server.ts
5
973
  const createAdaptorServer = (options) => {
6
974
  const fetchCallback = options.fetch;
@@ -9,7 +977,16 @@ const createAdaptorServer = (options) => {
9
977
  overrideGlobalObjects: options.overrideGlobalObjects,
10
978
  autoCleanupIncoming: options.autoCleanupIncoming
11
979
  });
12
- return (options.createServer || createServer)(options.serverOptions || {}, requestListener);
980
+ const server = (options.createServer || createServer)(options.serverOptions || {}, requestListener);
981
+ if (options.websocket && options.websocket.server) {
982
+ if (options.websocket.server.options.noServer !== true) throw new Error("WebSocket server must be created with { noServer: true } option");
983
+ setupWebSocket({
984
+ server,
985
+ fetchCallback,
986
+ wss: options.websocket.server
987
+ });
988
+ }
989
+ return server;
13
990
  };
14
991
  const serve = (options, listeningListener) => {
15
992
  const server = createAdaptorServer(options);
@@ -21,4 +998,4 @@ const serve = (options, listeningListener) => {
21
998
  };
22
999
 
23
1000
  //#endregion
24
- export { RequestError, createAdaptorServer, getRequestListener, serve };
1001
+ export { RequestError, createAdaptorServer, getRequestListener, serve, upgradeWebSocket };