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

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 (58) hide show
  1. package/README.md +1 -7
  2. package/dist/conninfo.d.mts +4 -3
  3. package/dist/conninfo.d.ts +4 -3
  4. package/dist/conninfo.js +20 -40
  5. package/dist/conninfo.mjs +19 -16
  6. package/dist/constants-B7DBcQew.js +11 -0
  7. package/dist/constants-DEKKqoym.mjs +5 -0
  8. package/dist/index.d.mts +62 -8
  9. package/dist/index.d.ts +62 -8
  10. package/dist/index.js +28 -613
  11. package/dist/index.mjs +24 -573
  12. package/dist/listener-Brd4yZ5d.js +726 -0
  13. package/dist/listener-RIBxK9_x.mjs +715 -0
  14. package/dist/serve-static.d.mts +14 -13
  15. package/dist/serve-static.d.ts +14 -13
  16. package/dist/serve-static.js +128 -170
  17. package/dist/serve-static.mjs +127 -145
  18. package/dist/utils/response.d.mts +3 -2
  19. package/dist/utils/response.d.ts +3 -2
  20. package/dist/utils/response.js +6 -35
  21. package/dist/utils/response.mjs +6 -9
  22. package/dist/vercel.d.mts +6 -5
  23. package/dist/vercel.d.ts +6 -5
  24. package/dist/vercel.js +7 -585
  25. package/dist/vercel.mjs +6 -548
  26. package/package.json +11 -13
  27. package/dist/globals.d.mts +0 -2
  28. package/dist/globals.d.ts +0 -2
  29. package/dist/globals.js +0 -29
  30. package/dist/globals.mjs +0 -5
  31. package/dist/listener.d.mts +0 -13
  32. package/dist/listener.d.ts +0 -13
  33. package/dist/listener.js +0 -581
  34. package/dist/listener.mjs +0 -546
  35. package/dist/request.d.mts +0 -25
  36. package/dist/request.d.ts +0 -25
  37. package/dist/request.js +0 -227
  38. package/dist/request.mjs +0 -195
  39. package/dist/response.d.mts +0 -26
  40. package/dist/response.d.ts +0 -26
  41. package/dist/response.js +0 -99
  42. package/dist/response.mjs +0 -72
  43. package/dist/server.d.mts +0 -10
  44. package/dist/server.d.ts +0 -10
  45. package/dist/server.js +0 -607
  46. package/dist/server.mjs +0 -571
  47. package/dist/types.d.mts +0 -44
  48. package/dist/types.d.ts +0 -44
  49. package/dist/types.js +0 -18
  50. package/dist/types.mjs +0 -0
  51. package/dist/utils/response/constants.d.mts +0 -3
  52. package/dist/utils/response/constants.d.ts +0 -3
  53. package/dist/utils/response/constants.js +0 -30
  54. package/dist/utils/response/constants.mjs +0 -5
  55. package/dist/utils.d.mts +0 -9
  56. package/dist/utils.d.ts +0 -9
  57. package/dist/utils.js +0 -99
  58. package/dist/utils.mjs +0 -71
package/dist/listener.mjs DELETED
@@ -1,546 +0,0 @@
1
- // src/listener.ts
2
- import { Http2ServerRequest as Http2ServerRequest2 } from "http2";
3
-
4
- // src/request.ts
5
- import { Http2ServerRequest } from "http2";
6
- import { Readable } from "stream";
7
- var RequestError = class extends Error {
8
- constructor(message, options) {
9
- super(message, options);
10
- this.name = "RequestError";
11
- }
12
- };
13
- var toRequestError = (e) => {
14
- if (e instanceof RequestError) {
15
- return e;
16
- }
17
- return new RequestError(e.message, { cause: e });
18
- };
19
- var GlobalRequest = global.Request;
20
- var Request = class extends GlobalRequest {
21
- constructor(input, options) {
22
- if (typeof input === "object" && getRequestCache in input) {
23
- input = input[getRequestCache]();
24
- }
25
- if (typeof options?.body?.getReader !== "undefined") {
26
- ;
27
- options.duplex ??= "half";
28
- }
29
- super(input, options);
30
- }
31
- };
32
- var newHeadersFromIncoming = (incoming) => {
33
- const headerRecord = [];
34
- const rawHeaders = incoming.rawHeaders;
35
- for (let i = 0; i < rawHeaders.length; i += 2) {
36
- const { [i]: key, [i + 1]: value } = rawHeaders;
37
- if (key.charCodeAt(0) !== /*:*/
38
- 58) {
39
- headerRecord.push([key, value]);
40
- }
41
- }
42
- return new Headers(headerRecord);
43
- };
44
- var wrapBodyStream = Symbol("wrapBodyStream");
45
- var newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
46
- const init = {
47
- method,
48
- headers,
49
- signal: abortController.signal
50
- };
51
- if (method === "TRACE") {
52
- init.method = "GET";
53
- const req = new Request(url, init);
54
- Object.defineProperty(req, "method", {
55
- get() {
56
- return "TRACE";
57
- }
58
- });
59
- return req;
60
- }
61
- if (!(method === "GET" || method === "HEAD")) {
62
- if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
63
- init.body = new ReadableStream({
64
- start(controller) {
65
- controller.enqueue(incoming.rawBody);
66
- controller.close();
67
- }
68
- });
69
- } else if (incoming[wrapBodyStream]) {
70
- let reader;
71
- init.body = new ReadableStream({
72
- async pull(controller) {
73
- try {
74
- reader ||= Readable.toWeb(incoming).getReader();
75
- const { done, value } = await reader.read();
76
- if (done) {
77
- controller.close();
78
- } else {
79
- controller.enqueue(value);
80
- }
81
- } catch (error) {
82
- controller.error(error);
83
- }
84
- }
85
- });
86
- } else {
87
- init.body = Readable.toWeb(incoming);
88
- }
89
- }
90
- return new Request(url, init);
91
- };
92
- var getRequestCache = Symbol("getRequestCache");
93
- var requestCache = Symbol("requestCache");
94
- var incomingKey = Symbol("incomingKey");
95
- var urlKey = Symbol("urlKey");
96
- var headersKey = Symbol("headersKey");
97
- var abortControllerKey = Symbol("abortControllerKey");
98
- var getAbortController = Symbol("getAbortController");
99
- var requestPrototype = {
100
- get method() {
101
- return this[incomingKey].method || "GET";
102
- },
103
- get url() {
104
- return this[urlKey];
105
- },
106
- get headers() {
107
- return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
108
- },
109
- [getAbortController]() {
110
- this[getRequestCache]();
111
- return this[abortControllerKey];
112
- },
113
- [getRequestCache]() {
114
- this[abortControllerKey] ||= new AbortController();
115
- return this[requestCache] ||= newRequestFromIncoming(
116
- this.method,
117
- this[urlKey],
118
- this.headers,
119
- this[incomingKey],
120
- this[abortControllerKey]
121
- );
122
- }
123
- };
124
- [
125
- "body",
126
- "bodyUsed",
127
- "cache",
128
- "credentials",
129
- "destination",
130
- "integrity",
131
- "mode",
132
- "redirect",
133
- "referrer",
134
- "referrerPolicy",
135
- "signal",
136
- "keepalive"
137
- ].forEach((k) => {
138
- Object.defineProperty(requestPrototype, k, {
139
- get() {
140
- return this[getRequestCache]()[k];
141
- }
142
- });
143
- });
144
- ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
145
- Object.defineProperty(requestPrototype, k, {
146
- value: function() {
147
- return this[getRequestCache]()[k]();
148
- }
149
- });
150
- });
151
- Object.setPrototypeOf(requestPrototype, Request.prototype);
152
- var newRequest = (incoming, defaultHostname) => {
153
- const req = Object.create(requestPrototype);
154
- req[incomingKey] = incoming;
155
- const incomingUrl = incoming.url || "";
156
- if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL.
157
- (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
158
- if (incoming instanceof Http2ServerRequest) {
159
- throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
160
- }
161
- try {
162
- const url2 = new URL(incomingUrl);
163
- req[urlKey] = url2.href;
164
- } catch (e) {
165
- throw new RequestError("Invalid absolute URL", { cause: e });
166
- }
167
- return req;
168
- }
169
- const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
170
- if (!host) {
171
- throw new RequestError("Missing host header");
172
- }
173
- let scheme;
174
- if (incoming instanceof Http2ServerRequest) {
175
- scheme = incoming.scheme;
176
- if (!(scheme === "http" || scheme === "https")) {
177
- throw new RequestError("Unsupported scheme");
178
- }
179
- } else {
180
- scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
181
- }
182
- const url = new URL(`${scheme}://${host}${incomingUrl}`);
183
- if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
184
- throw new RequestError("Invalid host header");
185
- }
186
- req[urlKey] = url.href;
187
- return req;
188
- };
189
-
190
- // src/response.ts
191
- var responseCache = Symbol("responseCache");
192
- var getResponseCache = Symbol("getResponseCache");
193
- var cacheKey = Symbol("cache");
194
- var GlobalResponse = global.Response;
195
- var Response2 = class _Response {
196
- #body;
197
- #init;
198
- [getResponseCache]() {
199
- delete this[cacheKey];
200
- return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
201
- }
202
- constructor(body, init) {
203
- let headers;
204
- this.#body = body;
205
- if (init instanceof _Response) {
206
- const cachedGlobalResponse = init[responseCache];
207
- if (cachedGlobalResponse) {
208
- this.#init = cachedGlobalResponse;
209
- this[getResponseCache]();
210
- return;
211
- } else {
212
- this.#init = init.#init;
213
- headers = new Headers(init.#init.headers);
214
- }
215
- } else {
216
- this.#init = init;
217
- }
218
- if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
219
- headers ||= init?.headers || { "content-type": "text/plain; charset=UTF-8" };
220
- this[cacheKey] = [init?.status || 200, body, headers];
221
- }
222
- }
223
- get headers() {
224
- const cache = this[cacheKey];
225
- if (cache) {
226
- if (!(cache[2] instanceof Headers)) {
227
- cache[2] = new Headers(cache[2]);
228
- }
229
- return cache[2];
230
- }
231
- return this[getResponseCache]().headers;
232
- }
233
- get status() {
234
- return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
235
- }
236
- get ok() {
237
- const status = this.status;
238
- return status >= 200 && status < 300;
239
- }
240
- };
241
- ["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => {
242
- Object.defineProperty(Response2.prototype, k, {
243
- get() {
244
- return this[getResponseCache]()[k];
245
- }
246
- });
247
- });
248
- ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
249
- Object.defineProperty(Response2.prototype, k, {
250
- value: function() {
251
- return this[getResponseCache]()[k]();
252
- }
253
- });
254
- });
255
- Object.setPrototypeOf(Response2, GlobalResponse);
256
- Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
257
-
258
- // src/utils.ts
259
- async function readWithoutBlocking(readPromise) {
260
- return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
261
- }
262
- function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
263
- const cancel = (error) => {
264
- reader.cancel(error).catch(() => {
265
- });
266
- };
267
- writable.on("close", cancel);
268
- writable.on("error", cancel);
269
- (currentReadPromise ?? reader.read()).then(flow, handleStreamError);
270
- return reader.closed.finally(() => {
271
- writable.off("close", cancel);
272
- writable.off("error", cancel);
273
- });
274
- function handleStreamError(error) {
275
- if (error) {
276
- writable.destroy(error);
277
- }
278
- }
279
- function onDrain() {
280
- reader.read().then(flow, handleStreamError);
281
- }
282
- function flow({ done, value }) {
283
- try {
284
- if (done) {
285
- writable.end();
286
- } else if (!writable.write(value)) {
287
- writable.once("drain", onDrain);
288
- } else {
289
- return reader.read().then(flow, handleStreamError);
290
- }
291
- } catch (e) {
292
- handleStreamError(e);
293
- }
294
- }
295
- }
296
- function writeFromReadableStream(stream, writable) {
297
- if (stream.locked) {
298
- throw new TypeError("ReadableStream is locked.");
299
- } else if (writable.destroyed) {
300
- return;
301
- }
302
- return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
303
- }
304
- var buildOutgoingHttpHeaders = (headers) => {
305
- const res = {};
306
- if (!(headers instanceof Headers)) {
307
- headers = new Headers(headers ?? void 0);
308
- }
309
- const cookies = [];
310
- for (const [k, v] of headers) {
311
- if (k === "set-cookie") {
312
- cookies.push(v);
313
- } else {
314
- res[k] = v;
315
- }
316
- }
317
- if (cookies.length > 0) {
318
- res["set-cookie"] = cookies;
319
- }
320
- res["content-type"] ??= "text/plain; charset=UTF-8";
321
- return res;
322
- };
323
-
324
- // src/utils/response/constants.ts
325
- var X_ALREADY_SENT = "x-hono-already-sent";
326
-
327
- // src/globals.ts
328
- import crypto from "crypto";
329
- if (typeof global.crypto === "undefined") {
330
- global.crypto = crypto;
331
- }
332
-
333
- // src/listener.ts
334
- var outgoingEnded = Symbol("outgoingEnded");
335
- var handleRequestError = () => new Response(null, {
336
- status: 400
337
- });
338
- var handleFetchError = (e) => new Response(null, {
339
- status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500
340
- });
341
- var handleResponseError = (e, outgoing) => {
342
- const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
343
- if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
344
- console.info("The user aborted a request.");
345
- } else {
346
- console.error(e);
347
- if (!outgoing.headersSent) {
348
- outgoing.writeHead(500, { "Content-Type": "text/plain" });
349
- }
350
- outgoing.end(`Error: ${err.message}`);
351
- outgoing.destroy(err);
352
- }
353
- };
354
- var flushHeaders = (outgoing) => {
355
- if ("flushHeaders" in outgoing && outgoing.writable) {
356
- outgoing.flushHeaders();
357
- }
358
- };
359
- var responseViaCache = async (res, outgoing) => {
360
- let [status, body, header] = res[cacheKey];
361
- if (header instanceof Headers) {
362
- header = buildOutgoingHttpHeaders(header);
363
- }
364
- if (typeof body === "string") {
365
- header["Content-Length"] = Buffer.byteLength(body);
366
- } else if (body instanceof Uint8Array) {
367
- header["Content-Length"] = body.byteLength;
368
- } else if (body instanceof Blob) {
369
- header["Content-Length"] = body.size;
370
- }
371
- outgoing.writeHead(status, header);
372
- if (typeof body === "string" || body instanceof Uint8Array) {
373
- outgoing.end(body);
374
- } else if (body instanceof Blob) {
375
- outgoing.end(new Uint8Array(await body.arrayBuffer()));
376
- } else {
377
- flushHeaders(outgoing);
378
- await writeFromReadableStream(body, outgoing)?.catch(
379
- (e) => handleResponseError(e, outgoing)
380
- );
381
- }
382
- ;
383
- outgoing[outgoingEnded]?.();
384
- };
385
- var isPromise = (res) => typeof res.then === "function";
386
- var responseViaResponseObject = async (res, outgoing, options = {}) => {
387
- if (isPromise(res)) {
388
- if (options.errorHandler) {
389
- try {
390
- res = await res;
391
- } catch (err) {
392
- const errRes = await options.errorHandler(err);
393
- if (!errRes) {
394
- return;
395
- }
396
- res = errRes;
397
- }
398
- } else {
399
- res = await res.catch(handleFetchError);
400
- }
401
- }
402
- if (cacheKey in res) {
403
- return responseViaCache(res, outgoing);
404
- }
405
- const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
406
- if (res.body) {
407
- const reader = res.body.getReader();
408
- const values = [];
409
- let done = false;
410
- let currentReadPromise = void 0;
411
- if (resHeaderRecord["transfer-encoding"] !== "chunked") {
412
- let maxReadCount = 2;
413
- for (let i = 0; i < maxReadCount; i++) {
414
- currentReadPromise ||= reader.read();
415
- const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
416
- console.error(e);
417
- done = true;
418
- });
419
- if (!chunk) {
420
- if (i === 1) {
421
- await new Promise((resolve) => setTimeout(resolve));
422
- maxReadCount = 3;
423
- continue;
424
- }
425
- break;
426
- }
427
- currentReadPromise = void 0;
428
- if (chunk.value) {
429
- values.push(chunk.value);
430
- }
431
- if (chunk.done) {
432
- done = true;
433
- break;
434
- }
435
- }
436
- if (done && !("content-length" in resHeaderRecord)) {
437
- resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
438
- }
439
- }
440
- outgoing.writeHead(res.status, resHeaderRecord);
441
- values.forEach((value) => {
442
- ;
443
- outgoing.write(value);
444
- });
445
- if (done) {
446
- outgoing.end();
447
- } else {
448
- if (values.length === 0) {
449
- flushHeaders(outgoing);
450
- }
451
- await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
452
- }
453
- } else if (resHeaderRecord[X_ALREADY_SENT]) {
454
- } else {
455
- outgoing.writeHead(res.status, resHeaderRecord);
456
- outgoing.end();
457
- }
458
- ;
459
- outgoing[outgoingEnded]?.();
460
- };
461
- var getRequestListener = (fetchCallback, options = {}) => {
462
- const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
463
- if (options.overrideGlobalObjects !== false && global.Request !== Request) {
464
- Object.defineProperty(global, "Request", {
465
- value: Request
466
- });
467
- Object.defineProperty(global, "Response", {
468
- value: Response2
469
- });
470
- }
471
- return async (incoming, outgoing) => {
472
- let res, req;
473
- try {
474
- req = newRequest(incoming, options.hostname);
475
- let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
476
- if (!incomingEnded) {
477
- ;
478
- incoming[wrapBodyStream] = true;
479
- incoming.on("end", () => {
480
- incomingEnded = true;
481
- });
482
- if (incoming instanceof Http2ServerRequest2) {
483
- ;
484
- outgoing[outgoingEnded] = () => {
485
- if (!incomingEnded) {
486
- setTimeout(() => {
487
- if (!incomingEnded) {
488
- setTimeout(() => {
489
- incoming.destroy();
490
- outgoing.destroy();
491
- });
492
- }
493
- });
494
- }
495
- };
496
- }
497
- }
498
- outgoing.on("close", () => {
499
- const abortController = req[abortControllerKey];
500
- if (abortController) {
501
- if (incoming.errored) {
502
- req[abortControllerKey].abort(incoming.errored.toString());
503
- } else if (!outgoing.writableFinished) {
504
- req[abortControllerKey].abort("Client connection prematurely closed.");
505
- }
506
- }
507
- if (!incomingEnded) {
508
- setTimeout(() => {
509
- if (!incomingEnded) {
510
- setTimeout(() => {
511
- incoming.destroy();
512
- });
513
- }
514
- });
515
- }
516
- });
517
- res = fetchCallback(req, { incoming, outgoing });
518
- if (cacheKey in res) {
519
- return responseViaCache(res, outgoing);
520
- }
521
- } catch (e) {
522
- if (!res) {
523
- if (options.errorHandler) {
524
- res = await options.errorHandler(req ? e : toRequestError(e));
525
- if (!res) {
526
- return;
527
- }
528
- } else if (!req) {
529
- res = handleRequestError();
530
- } else {
531
- res = handleFetchError(e);
532
- }
533
- } else {
534
- return handleResponseError(e, outgoing);
535
- }
536
- }
537
- try {
538
- return await responseViaResponseObject(res, outgoing, options);
539
- } catch (e) {
540
- return handleResponseError(e, outgoing);
541
- }
542
- };
543
- };
544
- export {
545
- getRequestListener
546
- };
@@ -1,25 +0,0 @@
1
- import { IncomingMessage } from 'node:http';
2
- import { Http2ServerRequest } from 'node:http2';
3
-
4
- declare class RequestError extends Error {
5
- constructor(message: string, options?: {
6
- cause?: unknown;
7
- });
8
- }
9
- declare const toRequestError: (e: unknown) => RequestError;
10
- declare const GlobalRequest: {
11
- new (input: RequestInfo | URL, init?: RequestInit): globalThis.Request;
12
- prototype: globalThis.Request;
13
- };
14
- declare class Request extends GlobalRequest {
15
- constructor(input: string | Request, options?: RequestInit);
16
- }
17
- type IncomingMessageWithWrapBodyStream = IncomingMessage & {
18
- [wrapBodyStream]: boolean;
19
- };
20
- declare const wrapBodyStream: unique symbol;
21
- declare const abortControllerKey: unique symbol;
22
- declare const getAbortController: unique symbol;
23
- declare const newRequest: (incoming: IncomingMessage | Http2ServerRequest, defaultHostname?: string) => any;
24
-
25
- export { GlobalRequest, type IncomingMessageWithWrapBodyStream, Request, RequestError, abortControllerKey, getAbortController, newRequest, toRequestError, wrapBodyStream };
package/dist/request.d.ts DELETED
@@ -1,25 +0,0 @@
1
- import { IncomingMessage } from 'node:http';
2
- import { Http2ServerRequest } from 'node:http2';
3
-
4
- declare class RequestError extends Error {
5
- constructor(message: string, options?: {
6
- cause?: unknown;
7
- });
8
- }
9
- declare const toRequestError: (e: unknown) => RequestError;
10
- declare const GlobalRequest: {
11
- new (input: RequestInfo | URL, init?: RequestInit): globalThis.Request;
12
- prototype: globalThis.Request;
13
- };
14
- declare class Request extends GlobalRequest {
15
- constructor(input: string | Request, options?: RequestInit);
16
- }
17
- type IncomingMessageWithWrapBodyStream = IncomingMessage & {
18
- [wrapBodyStream]: boolean;
19
- };
20
- declare const wrapBodyStream: unique symbol;
21
- declare const abortControllerKey: unique symbol;
22
- declare const getAbortController: unique symbol;
23
- declare const newRequest: (incoming: IncomingMessage | Http2ServerRequest, defaultHostname?: string) => any;
24
-
25
- export { GlobalRequest, type IncomingMessageWithWrapBodyStream, Request, RequestError, abortControllerKey, getAbortController, newRequest, toRequestError, wrapBodyStream };