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