@mastra/deployer 1.57.0 → 1.58.0-alpha.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 (51) hide show
  1. package/CHANGELOG.md +75 -0
  2. package/dist/_types/@hono_node-server/dist/index.d.mts +101 -0
  3. package/dist/{analyze-mZfLnmw2.js → analyze-7xxwhB5F.js} +11 -4
  4. package/dist/{analyze-mZfLnmw2.js.map → analyze-7xxwhB5F.js.map} +1 -1
  5. package/dist/{analyze-C6SiypMS.cjs → analyze-D100622N.cjs} +11 -4
  6. package/dist/{analyze-C6SiypMS.cjs.map → analyze-D100622N.cjs.map} +1 -1
  7. package/dist/build/analyze.cjs +1 -1
  8. package/dist/build/analyze.d.ts.map +1 -1
  9. package/dist/build/analyze.js +1 -1
  10. package/dist/build/fs-routing/codegen.d.ts.map +1 -1
  11. package/dist/build/fs-routing/discover.d.ts +42 -0
  12. package/dist/build/fs-routing/discover.d.ts.map +1 -1
  13. package/dist/build/index.cjs +3 -3
  14. package/dist/build/index.js +3 -3
  15. package/dist/{build-C3NTU5IS.cjs → build-33wIyA35.cjs} +135 -7
  16. package/dist/build-33wIyA35.cjs.map +1 -0
  17. package/dist/{build-DCvdjuKW.js → build-xd6t8qiR.js} +131 -3
  18. package/dist/build-xd6t8qiR.js.map +1 -0
  19. package/dist/bundler/index.cjs +165 -4
  20. package/dist/bundler/index.cjs.map +1 -1
  21. package/dist/bundler/index.d.ts +51 -1
  22. package/dist/bundler/index.d.ts.map +1 -1
  23. package/dist/bundler/index.js +165 -7
  24. package/dist/bundler/index.js.map +1 -1
  25. package/dist/docs/SKILL.md +1 -1
  26. package/dist/docs/assets/SOURCE_MAP.json +1 -1
  27. package/dist/index.cjs +2 -2
  28. package/dist/index.js +2 -2
  29. package/dist/server/index.cjs +877 -164
  30. package/dist/server/index.cjs.map +1 -1
  31. package/dist/server/index.d.ts +1 -1
  32. package/dist/server/index.js +877 -163
  33. package/dist/server/index.js.map +1 -1
  34. package/dist/services/deps.d.ts +3 -1
  35. package/dist/services/deps.d.ts.map +1 -1
  36. package/dist/services/index.cjs +1 -1
  37. package/dist/services/index.js +1 -1
  38. package/dist/{services-CHz7RuZ1.js → services-BRF1RRXB.js} +39 -4
  39. package/dist/services-BRF1RRXB.js.map +1 -0
  40. package/dist/{services-Cw3Ho44Z.cjs → services-_ksvysL5.cjs} +39 -4
  41. package/dist/services-_ksvysL5.cjs.map +1 -0
  42. package/package.json +9 -8
  43. package/dist/_types/@hono_node-server/dist/index.d.ts +0 -8
  44. package/dist/_types/@hono_node-server/dist/listener.d.ts +0 -13
  45. package/dist/_types/@hono_node-server/dist/request.d.ts +0 -25
  46. package/dist/_types/@hono_node-server/dist/server.d.ts +0 -10
  47. package/dist/_types/@hono_node-server/dist/types.d.ts +0 -44
  48. package/dist/build-C3NTU5IS.cjs.map +0 -1
  49. package/dist/build-DCvdjuKW.js.map +0 -1
  50. package/dist/services-CHz7RuZ1.js.map +0 -1
  51. package/dist/services-Cw3Ho44Z.cjs.map +0 -1
@@ -6,11 +6,11 @@ import { dirname, join } from "path";
6
6
  import { fileURLToPath } from "url";
7
7
  import { Readable, Writable } from "stream";
8
8
  import * as https from "https";
9
- import { createServer } from "http";
9
+ import { STATUS_CODES, createServer } from "http";
10
10
  import { Http2ServerRequest, constants } from "http2";
11
- import crypto from "crypto";
12
- import { getMimeType } from "hono/utils/mime";
11
+ import { defineWebSocketHelper } from "hono/ws";
13
12
  import process$1, { versions } from "process";
13
+ import { getMimeType } from "hono/utils/mime";
14
14
  import { html } from "hono/html";
15
15
  import { Tool } from "@mastra/core/tools";
16
16
  import { MastraServer, checkRouteFGA, isZodError, normalizeQueryParams, redactStreamChunk, serializeStreamChunk } from "@mastra/server/server-adapter";
@@ -30,36 +30,105 @@ import { timeout } from "hono/timeout";
30
30
  import "hono/utils/handler";
31
31
  import "hono/validator";
32
32
  import { HTTPException } from "hono/http-exception";
33
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@hono/node-server/1.19.14/42c5178abe0ceb83054b3103dd081cbbfb29d6fb64d2c11700a4167fb620acdc/node_modules/@hono/node-server/dist/index.mjs
33
+ //#endregion
34
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@hono/node-server/2.0.10/a560c4fb751eda40b27a36d7ca69ad4a96169452a5efc0b1a386b85209fd1371/node_modules/@hono/node-server/dist/index.mjs
34
35
  var RequestError = class extends Error {
35
36
  constructor(message, options) {
36
37
  super(message, options);
37
38
  this.name = "RequestError";
38
39
  }
39
40
  };
40
- var toRequestError = (e) => {
41
+ const reValidRequestUrl = /^\/[!#$&-;=?-\[\]_a-z~]*$/;
42
+ const reDotSegment = /\/\.\.?(?:[/?#]|$)/;
43
+ const reValidHost = /^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/;
44
+ const buildUrl = (scheme, host, incomingUrl) => {
45
+ const url = `${scheme}://${host}${incomingUrl}`;
46
+ if (!reValidHost.test(host)) {
47
+ const urlObj = new URL(url);
48
+ if (urlObj.hostname.length !== host.length && urlObj.hostname !== (host.includes(":") ? host.replace(/:\d+$/, "") : host).toLowerCase()) throw new RequestError("Invalid host header");
49
+ return urlObj.href;
50
+ } else if (incomingUrl.length === 0) return url + "/";
51
+ else {
52
+ if (incomingUrl.charCodeAt(0) !== 47) throw new RequestError("Invalid URL");
53
+ if (!reValidRequestUrl.test(incomingUrl) || reDotSegment.test(incomingUrl)) return new URL(url).href;
54
+ return url;
55
+ }
56
+ };
57
+ const toRequestError = (e) => {
41
58
  if (e instanceof RequestError) return e;
42
59
  return new RequestError(e.message, { cause: e });
43
60
  };
44
- var GlobalRequest = global.Request;
45
- var Request = class extends GlobalRequest {
61
+ const GlobalRequest = global.Request;
62
+ var Request$1 = class extends GlobalRequest {
46
63
  constructor(input, options) {
47
- if (typeof input === "object" && getRequestCache in input) input = input[getRequestCache]();
48
- if (typeof options?.body?.getReader !== "undefined") options.duplex ??= "half";
64
+ if (typeof input === "object" && getRequestCache in input) {
65
+ const hasReplacementBody = options !== void 0 && "body" in options && options.body != null;
66
+ if (input[bodyConsumedDirectlyKey] && !hasReplacementBody) throw new TypeError("Cannot construct a Request with a Request object that has already been used.");
67
+ input = input[getRequestCache]();
68
+ }
69
+ if (typeof (options?.body)?.getReader !== "undefined") options.duplex ??= "half";
49
70
  super(input, options);
50
71
  }
51
72
  };
52
- var newHeadersFromIncoming = (incoming) => {
73
+ const newHeadersFromIncoming = (incoming) => {
53
74
  const headerRecord = [];
54
75
  const rawHeaders = incoming.rawHeaders;
55
- for (let i = 0; i < rawHeaders.length; i += 2) {
56
- const { [i]: key, [i + 1]: value } = rawHeaders;
57
- if (key.charCodeAt(0) !== 58) headerRecord.push([key, value]);
76
+ for (let i = 0, len = rawHeaders.length; i < len; i += 2) {
77
+ const key = rawHeaders[i];
78
+ if (key.charCodeAt(0) !== 58) headerRecord.push([key, rawHeaders[i + 1]]);
58
79
  }
59
80
  return new Headers(headerRecord);
60
81
  };
61
- var wrapBodyStream = Symbol("wrapBodyStream");
62
- var newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
82
+ const wrapBodyStream = Symbol("wrapBodyStream");
83
+ const byteExactEncodings = /* @__PURE__ */ new Set([
84
+ "latin1",
85
+ "binary",
86
+ "hex",
87
+ "base64",
88
+ "base64url"
89
+ ]);
90
+ const isByteExactEncoding = (encoding) => encoding === null || byteExactEncodings.has(encoding);
91
+ const bodyBufferedBeforeDisconnectKey = Symbol("bodyBufferedBeforeDisconnect");
92
+ const bodyBufferedLengthBeforeDisconnectKey = Symbol("bodyBufferedLengthBeforeDisconnect");
93
+ const toBufferChunk = (chunk, encoding) => Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding ?? "utf8");
94
+ const isRecoverableDisconnectedIncoming = (incoming) => !(incoming instanceof Http2ServerRequest) && !!incoming.complete && !!incoming.readableAborted && typeof incoming.read === "function" && isByteExactEncoding(incoming.readableEncoding);
95
+ const recordBodyBufferedBeforeDisconnect = (incoming) => {
96
+ if (incoming.readableDidRead || !isRecoverableDisconnectedIncoming(incoming)) return;
97
+ const incomingWithRecovery = incoming;
98
+ incomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey] ??= incoming.readableLength;
99
+ };
100
+ const readBodyBufferedBeforeDisconnect = (incoming, chunks) => {
101
+ if (incoming.readableDidRead && !chunks || !isRecoverableDisconnectedIncoming(incoming)) return;
102
+ const incomingWithRecovery = incoming;
103
+ if (incomingWithRecovery[bodyBufferedBeforeDisconnectKey] !== void 0) return incomingWithRecovery[bodyBufferedBeforeDisconnectKey];
104
+ let result;
105
+ const errored = incoming.errored;
106
+ if (errored && errored.code !== "ECONNRESET") result = errored;
107
+ else if (incomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey] !== void 0 && incoming.readableLength !== incomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey]) result = newBodyUnusableError();
108
+ else {
109
+ const bodyChunks = chunks ?? [];
110
+ const chunk = incoming.read();
111
+ if (chunk !== null) bodyChunks.push(toBufferChunk(chunk, incoming.readableEncoding));
112
+ const buffer = bodyChunks.length === 1 ? bodyChunks[0] : Buffer.concat(bodyChunks);
113
+ result = buffer;
114
+ const contentLength = incoming.headers["content-length"];
115
+ if (typeof contentLength === "string" && /^\d+$/.test(contentLength)) {
116
+ const expectedLength = Number(contentLength);
117
+ if (Number.isSafeInteger(expectedLength) && buffer.length !== expectedLength) result = newBodyUnusableError();
118
+ }
119
+ }
120
+ incomingWithRecovery[bodyBufferedBeforeDisconnectKey] = result;
121
+ return result;
122
+ };
123
+ const enqueueBufferedBody = (controller, buffered) => {
124
+ if (buffered instanceof Error) {
125
+ controller.error(buffered);
126
+ return;
127
+ }
128
+ if (buffered.length > 0) controller.enqueue(buffered);
129
+ controller.close();
130
+ };
131
+ const newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
63
132
  const init = {
64
133
  method,
65
134
  headers,
@@ -67,7 +136,7 @@ var newRequestFromIncoming = (method, url, headers, incoming, abortController) =
67
136
  };
68
137
  if (method === "TRACE") {
69
138
  init.method = "GET";
70
- const req = new Request(url, init);
139
+ const req = new Request$1(url, init);
71
140
  Object.defineProperty(req, "method", { get() {
72
141
  return "TRACE";
73
142
  } });
@@ -81,6 +150,13 @@ var newRequestFromIncoming = (method, url, headers, incoming, abortController) =
81
150
  let reader;
82
151
  init.body = new ReadableStream({ async pull(controller) {
83
152
  try {
153
+ if (!reader) {
154
+ const buffered = readBodyBufferedBeforeDisconnect(incoming);
155
+ if (buffered !== void 0) {
156
+ enqueueBufferedBody(controller, buffered);
157
+ return;
158
+ }
159
+ }
84
160
  reader ||= Readable.toWeb(incoming).getReader();
85
161
  const { done, value } = await reader.read();
86
162
  if (done) controller.close();
@@ -89,18 +165,190 @@ var newRequestFromIncoming = (method, url, headers, incoming, abortController) =
89
165
  controller.error(error);
90
166
  }
91
167
  } });
92
- } else init.body = Readable.toWeb(incoming);
93
- return new Request(url, init);
94
- };
95
- var getRequestCache = Symbol("getRequestCache");
96
- var requestCache = Symbol("requestCache");
97
- var incomingKey = Symbol("incomingKey");
98
- var urlKey = Symbol("urlKey");
99
- var headersKey = Symbol("headersKey");
100
- var abortControllerKey = Symbol("abortControllerKey");
101
- var requestPrototype = {
168
+ } else {
169
+ const buffered = readBodyBufferedBeforeDisconnect(incoming);
170
+ if (buffered !== void 0) init.body = new ReadableStream({ start(controller) {
171
+ enqueueBufferedBody(controller, buffered);
172
+ } });
173
+ else init.body = Readable.toWeb(incoming);
174
+ }
175
+ return new Request$1(url, init);
176
+ };
177
+ const getRequestCache = Symbol("getRequestCache");
178
+ const requestCache = Symbol("requestCache");
179
+ const incomingKey = Symbol("incomingKey");
180
+ const urlKey = Symbol("urlKey");
181
+ const methodKey = Symbol("methodKey");
182
+ const headersKey = Symbol("headersKey");
183
+ const abortControllerKey = Symbol("abortControllerKey");
184
+ const getAbortController = Symbol("getAbortController");
185
+ const abortRequest = Symbol("abortRequest");
186
+ const bodyBufferKey = Symbol("bodyBuffer");
187
+ const bodyReadPromiseKey = Symbol("bodyReadPromise");
188
+ const bodyConsumedDirectlyKey = Symbol("bodyConsumedDirectly");
189
+ const bodyLockReaderKey = Symbol("bodyLockReader");
190
+ const abortReasonKey = Symbol("abortReason");
191
+ const newBodyUnusableError = () => {
192
+ return /* @__PURE__ */ new TypeError("Body is unusable");
193
+ };
194
+ const rejectBodyUnusable = () => {
195
+ return Promise.reject(newBodyUnusableError());
196
+ };
197
+ const textDecoder = new TextDecoder();
198
+ const consumeBodyDirectOnce = (request) => {
199
+ if (request[bodyConsumedDirectlyKey]) return rejectBodyUnusable();
200
+ request[bodyConsumedDirectlyKey] = true;
201
+ };
202
+ const toArrayBuffer = (buf) => {
203
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
204
+ };
205
+ const contentType = (request) => {
206
+ return (request[headersKey] ||= newHeadersFromIncoming(request[incomingKey])).get("content-type") || "";
207
+ };
208
+ const methodTokenRegExp = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
209
+ const normalizeIncomingMethod = (method) => {
210
+ if (typeof method !== "string" || method.length === 0) return "GET";
211
+ switch (method) {
212
+ case "DELETE":
213
+ case "GET":
214
+ case "HEAD":
215
+ case "OPTIONS":
216
+ case "POST":
217
+ case "PUT": return method;
218
+ }
219
+ const upper = method.toUpperCase();
220
+ switch (upper) {
221
+ case "DELETE":
222
+ case "GET":
223
+ case "HEAD":
224
+ case "OPTIONS":
225
+ case "POST":
226
+ case "PUT": return upper;
227
+ default: return method;
228
+ }
229
+ };
230
+ const validateDirectReadMethod = (method) => {
231
+ if (!methodTokenRegExp.test(method)) return /* @__PURE__ */ new TypeError(`'${method}' is not a valid HTTP method.`);
232
+ const normalized = method.toUpperCase();
233
+ if (normalized === "CONNECT" || normalized === "TRACK" || normalized === "TRACE" && method !== "TRACE") return /* @__PURE__ */ new TypeError(`'${method}' HTTP method is unsupported.`);
234
+ };
235
+ const readBodyWithFastPath = (request, method, fromBuffer) => {
236
+ if (request[bodyConsumedDirectlyKey]) return rejectBodyUnusable();
237
+ const methodName = request.method;
238
+ if (methodName === "GET" || methodName === "HEAD") return request[getRequestCache]()[method]();
239
+ const methodValidationError = validateDirectReadMethod(methodName);
240
+ if (methodValidationError) return Promise.reject(methodValidationError);
241
+ if (request[requestCache]) {
242
+ if (methodName !== "TRACE") return request[requestCache][method]();
243
+ }
244
+ const alreadyUsedError = consumeBodyDirectOnce(request);
245
+ if (alreadyUsedError) return alreadyUsedError;
246
+ const raw = readRawBodyIfAvailable(request);
247
+ if (raw) {
248
+ const result = Promise.resolve(fromBuffer(raw, request));
249
+ request[bodyBufferKey] = void 0;
250
+ return result;
251
+ }
252
+ return readBodyDirect(request).then((buf) => {
253
+ const result = fromBuffer(buf, request);
254
+ request[bodyBufferKey] = void 0;
255
+ return result;
256
+ });
257
+ };
258
+ const readRawBodyIfAvailable = (request) => {
259
+ const incoming = request[incomingKey];
260
+ if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) return incoming.rawBody;
261
+ };
262
+ const normalizeAbortError = (request, incoming) => {
263
+ if (incoming.errored) return incoming.errored;
264
+ const reason = request[abortReasonKey];
265
+ if (reason !== void 0) return reason instanceof Error ? reason : new Error(String(reason));
266
+ return /* @__PURE__ */ new Error("Client connection prematurely closed.");
267
+ };
268
+ const readBodyDirect = (request) => {
269
+ if (request[bodyBufferKey]) return Promise.resolve(request[bodyBufferKey]);
270
+ if (request[bodyReadPromiseKey]) return request[bodyReadPromiseKey];
271
+ const incoming = request[incomingKey];
272
+ if (incoming.readableDidRead) return rejectBodyUnusable();
273
+ const buffered = readBodyBufferedBeforeDisconnect(incoming);
274
+ if (buffered !== void 0) {
275
+ if (buffered instanceof Error) return Promise.reject(buffered);
276
+ request[bodyBufferKey] = buffered;
277
+ return Promise.resolve(buffered);
278
+ }
279
+ const promise = new Promise((resolve, reject) => {
280
+ const chunks = [];
281
+ let settled = false;
282
+ const finish = (callback) => {
283
+ if (settled) return;
284
+ settled = true;
285
+ cleanup();
286
+ callback();
287
+ };
288
+ const recoverCompleteBodyAfterDisconnect = (error) => {
289
+ const streamError = incoming.errored ?? error;
290
+ if (!isRecoverableDisconnectedIncoming(incoming) || streamError && streamError.code !== "ECONNRESET") return false;
291
+ finish(() => {
292
+ const recovered = readBodyBufferedBeforeDisconnect(incoming, chunks);
293
+ if (recovered instanceof Error) reject(recovered);
294
+ else if (recovered === void 0) reject(error ?? normalizeAbortError(request, incoming));
295
+ else {
296
+ request[bodyBufferKey] = recovered;
297
+ resolve(recovered);
298
+ }
299
+ });
300
+ return true;
301
+ };
302
+ const onData = (chunk) => {
303
+ chunks.push(toBufferChunk(chunk, incoming.readableEncoding));
304
+ };
305
+ const onEnd = () => {
306
+ finish(() => {
307
+ const buffer = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks);
308
+ request[bodyBufferKey] = buffer;
309
+ resolve(buffer);
310
+ });
311
+ };
312
+ const onError = (error) => {
313
+ if (recoverCompleteBodyAfterDisconnect(error)) return;
314
+ finish(() => {
315
+ reject(error);
316
+ });
317
+ };
318
+ const onClose = () => {
319
+ if (incoming.readableEnded) {
320
+ onEnd();
321
+ return;
322
+ }
323
+ if (recoverCompleteBodyAfterDisconnect()) return;
324
+ finish(() => {
325
+ reject(normalizeAbortError(request, incoming));
326
+ });
327
+ };
328
+ const cleanup = () => {
329
+ incoming.off("data", onData);
330
+ incoming.off("end", onEnd);
331
+ incoming.off("error", onError);
332
+ incoming.off("close", onClose);
333
+ request[bodyReadPromiseKey] = void 0;
334
+ };
335
+ incoming.on("data", onData);
336
+ incoming.on("end", onEnd);
337
+ incoming.on("error", onError);
338
+ incoming.on("close", onClose);
339
+ queueMicrotask(() => {
340
+ if (settled) return;
341
+ if (incoming.readableEnded) onEnd();
342
+ else if (incoming.errored) onError(incoming.errored);
343
+ else if (incoming.destroyed) onClose();
344
+ });
345
+ });
346
+ request[bodyReadPromiseKey] = promise;
347
+ return promise;
348
+ };
349
+ const requestPrototype = {
102
350
  get method() {
103
- return this[incomingKey].method || "GET";
351
+ return this[methodKey];
104
352
  },
105
353
  get url() {
106
354
  return this[urlKey];
@@ -108,18 +356,57 @@ var requestPrototype = {
108
356
  get headers() {
109
357
  return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
110
358
  },
111
- [Symbol("getAbortController")]() {
112
- this[getRequestCache]();
359
+ [abortRequest](reason) {
360
+ if (this[abortReasonKey] === void 0) this[abortReasonKey] = reason;
361
+ const abortController = this[abortControllerKey];
362
+ if (abortController && !abortController.signal.aborted) abortController.abort(reason);
363
+ },
364
+ [getAbortController]() {
365
+ this[abortControllerKey] ||= new AbortController();
366
+ if (this[abortReasonKey] !== void 0 && !this[abortControllerKey].signal.aborted) this[abortControllerKey].abort(this[abortReasonKey]);
113
367
  return this[abortControllerKey];
114
368
  },
115
369
  [getRequestCache]() {
116
- this[abortControllerKey] ||= new AbortController();
117
- return this[requestCache] ||= newRequestFromIncoming(this.method, this[urlKey], this.headers, this[incomingKey], this[abortControllerKey]);
370
+ const abortController = this[getAbortController]();
371
+ if (this[requestCache]) return this[requestCache];
372
+ const method = this.method;
373
+ if (this[bodyConsumedDirectlyKey] && !(method === "GET" || method === "HEAD")) {
374
+ this[bodyBufferKey] = void 0;
375
+ const init = {
376
+ method: method === "TRACE" ? "GET" : method,
377
+ headers: this.headers,
378
+ signal: abortController.signal
379
+ };
380
+ if (method !== "TRACE") {
381
+ init.body = new ReadableStream({ start(c) {
382
+ c.close();
383
+ } });
384
+ init.duplex = "half";
385
+ }
386
+ const req = new Request$1(this[urlKey], init);
387
+ if (method === "TRACE") Object.defineProperty(req, "method", { get() {
388
+ return "TRACE";
389
+ } });
390
+ return this[requestCache] = req;
391
+ }
392
+ return this[requestCache] = newRequestFromIncoming(this.method, this[urlKey], this.headers, this[incomingKey], abortController);
393
+ },
394
+ get body() {
395
+ if (!this[bodyConsumedDirectlyKey]) return this[getRequestCache]().body;
396
+ const request = this[getRequestCache]();
397
+ if (!this[bodyLockReaderKey] && request.body) this[bodyLockReaderKey] = request.body.getReader();
398
+ return request.body;
399
+ },
400
+ get bodyUsed() {
401
+ if (this[bodyConsumedDirectlyKey]) return true;
402
+ if (this[requestCache]) return this[requestCache].bodyUsed;
403
+ return false;
118
404
  }
119
405
  };
406
+ Object.defineProperty(requestPrototype, "signal", { get() {
407
+ return this[getAbortController]().signal;
408
+ } });
120
409
  [
121
- "body",
122
- "bodyUsed",
123
410
  "cache",
124
411
  "credentials",
125
412
  "destination",
@@ -128,25 +415,37 @@ var requestPrototype = {
128
415
  "redirect",
129
416
  "referrer",
130
417
  "referrerPolicy",
131
- "signal",
132
418
  "keepalive"
133
419
  ].forEach((k) => {
134
420
  Object.defineProperty(requestPrototype, k, { get() {
135
421
  return this[getRequestCache]()[k];
136
422
  } });
137
423
  });
138
- [
139
- "arrayBuffer",
140
- "blob",
141
- "clone",
142
- "formData",
143
- "json",
144
- "text"
145
- ].forEach((k) => {
424
+ ["clone", "formData"].forEach((k) => {
146
425
  Object.defineProperty(requestPrototype, k, { value: function() {
426
+ if (this[bodyConsumedDirectlyKey]) {
427
+ if (k === "clone") throw newBodyUnusableError();
428
+ return rejectBodyUnusable();
429
+ }
147
430
  return this[getRequestCache]()[k]();
148
431
  } });
149
432
  });
433
+ Object.defineProperty(requestPrototype, "text", { value: function() {
434
+ return readBodyWithFastPath(this, "text", (buf) => textDecoder.decode(buf));
435
+ } });
436
+ Object.defineProperty(requestPrototype, "arrayBuffer", { value: function() {
437
+ return readBodyWithFastPath(this, "arrayBuffer", (buf) => toArrayBuffer(buf));
438
+ } });
439
+ Object.defineProperty(requestPrototype, "blob", { value: function() {
440
+ return readBodyWithFastPath(this, "blob", (buf, request) => {
441
+ const type = contentType(request);
442
+ return new Response(buf, type ? { headers: { "content-type": type } } : void 0).blob();
443
+ });
444
+ } });
445
+ Object.defineProperty(requestPrototype, "json", { value: function() {
446
+ if (this[bodyConsumedDirectlyKey]) return rejectBodyUnusable();
447
+ return this.text().then(JSON.parse);
448
+ } });
150
449
  Object.defineProperty(requestPrototype, Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) {
151
450
  return `Request (lightweight) ${inspectFn({
152
451
  method: this.method,
@@ -158,10 +457,11 @@ Object.defineProperty(requestPrototype, Symbol.for("nodejs.util.inspect.custom")
158
457
  depth: depth == null ? null : depth - 1
159
458
  })}`;
160
459
  } });
161
- Object.setPrototypeOf(requestPrototype, Request.prototype);
162
- var newRequest = (incoming, defaultHostname) => {
460
+ Object.setPrototypeOf(requestPrototype, Request$1.prototype);
461
+ const newRequest = (incoming, defaultHostname) => {
163
462
  const req = Object.create(requestPrototype);
164
463
  req[incomingKey] = incoming;
464
+ req[methodKey] = normalizeIncomingMethod(incoming.method);
165
465
  const incomingUrl = incoming.url || "";
166
466
  if (incomingUrl[0] !== "/" && (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
167
467
  if (incoming instanceof Http2ServerRequest) throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
@@ -179,26 +479,36 @@ var newRequest = (incoming, defaultHostname) => {
179
479
  scheme = incoming.scheme;
180
480
  if (!(scheme === "http" || scheme === "https")) throw new RequestError("Unsupported scheme");
181
481
  } else scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
182
- const url = new URL(`${scheme}://${host}${incomingUrl}`);
183
- if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) throw new RequestError("Invalid host header");
184
- req[urlKey] = url.href;
482
+ try {
483
+ req[urlKey] = buildUrl(scheme, host, incomingUrl);
484
+ } catch (e) {
485
+ if (e instanceof RequestError) throw e;
486
+ else throw new RequestError("Invalid URL", { cause: e });
487
+ }
185
488
  return req;
186
489
  };
187
- var responseCache = Symbol("responseCache");
188
- var getResponseCache = Symbol("getResponseCache");
189
- var cacheKey = Symbol("cache");
190
- var GlobalResponse = global.Response;
191
- var Response2 = class _Response {
490
+ const defaultContentType = "text/plain; charset=UTF-8";
491
+ const responseCache = Symbol("responseCache");
492
+ const getResponseCache = Symbol("getResponseCache");
493
+ const cacheKey = Symbol("cache");
494
+ const GlobalResponse = global.Response;
495
+ var Response$1 = class Response$1 {
192
496
  #body;
193
497
  #init;
194
498
  [getResponseCache]() {
499
+ const cache = this[cacheKey];
500
+ const liveHeaders = cache && cache[2] instanceof Headers ? cache[2] : void 0;
195
501
  delete this[cacheKey];
196
- return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
502
+ return this[responseCache] ||= new GlobalResponse(this.#body, liveHeaders ? {
503
+ status: this.#init?.status,
504
+ statusText: this.#init?.statusText,
505
+ headers: liveHeaders
506
+ } : this.#init);
197
507
  }
198
508
  constructor(body, init) {
199
509
  let headers;
200
510
  this.#body = body;
201
- if (init instanceof _Response) {
511
+ if (init instanceof Response$1) {
202
512
  const cachedGlobalResponse = init[responseCache];
203
513
  if (cachedGlobalResponse) {
204
514
  this.#init = cachedGlobalResponse;
@@ -206,19 +516,19 @@ var Response2 = class _Response {
206
516
  return;
207
517
  } else {
208
518
  this.#init = init.#init;
209
- headers = new Headers(init.#init.headers);
519
+ headers = new Headers(init.headers);
210
520
  }
211
521
  } else this.#init = init;
212
- if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) this[cacheKey] = [
522
+ if (body == null || typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) this[cacheKey] = [
213
523
  init?.status || 200,
214
- body,
524
+ body ?? null,
215
525
  headers || init?.headers
216
526
  ];
217
527
  }
218
528
  get headers() {
219
529
  const cache = this[cacheKey];
220
530
  if (cache) {
221
- if (!(cache[2] instanceof Headers)) cache[2] = new Headers(cache[2] || { "content-type": "text/plain; charset=UTF-8" });
531
+ if (!(cache[2] instanceof Headers)) cache[2] = new Headers(cache[2] || (cache[1] === null ? void 0 : { "content-type": defaultContentType }));
222
532
  return cache[2];
223
533
  }
224
534
  return this[getResponseCache]().headers;
@@ -240,7 +550,7 @@ var Response2 = class _Response {
240
550
  "type",
241
551
  "url"
242
552
  ].forEach((k) => {
243
- Object.defineProperty(Response2.prototype, k, { get() {
553
+ Object.defineProperty(Response$1.prototype, k, { get() {
244
554
  return this[getResponseCache]()[k];
245
555
  } });
246
556
  });
@@ -252,11 +562,11 @@ var Response2 = class _Response {
252
562
  "json",
253
563
  "text"
254
564
  ].forEach((k) => {
255
- Object.defineProperty(Response2.prototype, k, { value: function() {
565
+ Object.defineProperty(Response$1.prototype, k, { value: function() {
256
566
  return this[getResponseCache]()[k]();
257
567
  } });
258
568
  });
259
- Object.defineProperty(Response2.prototype, Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) {
569
+ Object.defineProperty(Response$1.prototype, Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) {
260
570
  return `Response (lightweight) ${inspectFn({
261
571
  status: this.status,
262
572
  headers: this.headers,
@@ -267,8 +577,51 @@ Object.defineProperty(Response2.prototype, Symbol.for("nodejs.util.inspect.custo
267
577
  depth: depth == null ? null : depth - 1
268
578
  })}`;
269
579
  } });
270
- Object.setPrototypeOf(Response2, GlobalResponse);
271
- Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
580
+ Object.setPrototypeOf(Response$1, GlobalResponse);
581
+ Object.setPrototypeOf(Response$1.prototype, GlobalResponse.prototype);
582
+ const validRedirectUrl = /^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/;
583
+ const parseRedirectUrl = (url) => {
584
+ if (url instanceof URL) return url.href;
585
+ if (validRedirectUrl.test(url)) return url;
586
+ return new URL(url).href;
587
+ };
588
+ const validRedirectStatuses = /* @__PURE__ */ new Set([
589
+ 301,
590
+ 302,
591
+ 303,
592
+ 307,
593
+ 308
594
+ ]);
595
+ Object.defineProperty(Response$1, "redirect", {
596
+ value: function redirect(url, status = 302) {
597
+ if (!validRedirectStatuses.has(status)) throw new RangeError("Invalid status code");
598
+ return new Response$1(null, {
599
+ status,
600
+ headers: { location: parseRedirectUrl(url) }
601
+ });
602
+ },
603
+ writable: true,
604
+ configurable: true
605
+ });
606
+ Object.defineProperty(Response$1, "json", {
607
+ value: function json(data, init) {
608
+ const body = JSON.stringify(data);
609
+ if (body === void 0) throw new TypeError("The data is not JSON serializable");
610
+ const initHeaders = init?.headers;
611
+ let headers;
612
+ if (initHeaders) {
613
+ headers = new Headers(initHeaders);
614
+ if (!headers.has("content-type")) headers.set("content-type", "application/json");
615
+ } else headers = { "content-type": "application/json" };
616
+ return new Response$1(body, {
617
+ status: init?.status ?? 200,
618
+ statusText: init?.statusText,
619
+ headers
620
+ });
621
+ },
622
+ writable: true,
623
+ configurable: true
624
+ });
272
625
  async function readWithoutBlocking(readPromise) {
273
626
  return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
274
627
  }
@@ -304,23 +657,23 @@ function writeFromReadableStream(stream, writable) {
304
657
  else if (writable.destroyed) return;
305
658
  return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
306
659
  }
307
- var buildOutgoingHttpHeaders = (headers) => {
660
+ const buildOutgoingHttpHeaders = (headers, defaultContentType) => {
308
661
  const res = {};
309
662
  if (!(headers instanceof Headers)) headers = new Headers(headers ?? void 0);
310
- const cookies = [];
311
- for (const [k, v] of headers) if (k === "set-cookie") cookies.push(v);
312
- else res[k] = v;
313
- if (cookies.length > 0) res["set-cookie"] = cookies;
314
- res["content-type"] ??= "text/plain; charset=UTF-8";
663
+ if (headers.has("set-cookie")) {
664
+ const cookies = [];
665
+ for (const [k, v] of headers) if (k === "set-cookie") cookies.push(v);
666
+ else res[k] = v;
667
+ if (cookies.length > 0) res["set-cookie"] = cookies;
668
+ } else for (const [k, v] of headers) res[k] = v;
669
+ if (defaultContentType) res["content-type"] ??= defaultContentType;
315
670
  return res;
316
671
  };
317
- var X_ALREADY_SENT = "x-hono-already-sent";
318
- if (typeof global.crypto === "undefined") global.crypto = crypto;
319
- var outgoingEnded = Symbol("outgoingEnded");
320
- var incomingDraining = Symbol("incomingDraining");
321
- var DRAIN_TIMEOUT_MS = 500;
322
- var MAX_DRAIN_BYTES = 64 * 1024 * 1024;
323
- var drainIncoming = (incoming) => {
672
+ const outgoingEnded = Symbol("outgoingEnded");
673
+ const incomingDraining = Symbol("incomingDraining");
674
+ const DRAIN_TIMEOUT_MS = 500;
675
+ const MAX_DRAIN_BYTES = 64 * 1024 * 1024;
676
+ const drainIncoming = (incoming) => {
324
677
  const incomingWithDrainState = incoming;
325
678
  if (incoming.destroyed || incomingWithDrainState[incomingDraining]) return;
326
679
  incomingWithDrainState[incomingDraining] = true;
@@ -353,9 +706,28 @@ var drainIncoming = (incoming) => {
353
706
  incoming.on("error", cleanup);
354
707
  incoming.resume();
355
708
  };
356
- var handleRequestError = () => new Response(null, { status: 400 });
357
- var handleFetchError = (e) => new Response(null, { status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500 });
358
- var handleResponseError = (e, outgoing) => {
709
+ const makeCloseHandler = (req, incoming, outgoing, needsBodyCleanup) => () => {
710
+ if (incoming.errored) {
711
+ recordBodyBufferedBeforeDisconnect(incoming);
712
+ req[abortRequest](incoming.errored.toString());
713
+ } else if (!outgoing.writableFinished) {
714
+ recordBodyBufferedBeforeDisconnect(incoming);
715
+ req[abortRequest]("Client connection prematurely closed.");
716
+ }
717
+ if (needsBodyCleanup && !incoming.readableEnded) setTimeout(() => {
718
+ if (!incoming.readableEnded) setTimeout(() => {
719
+ drainIncoming(incoming);
720
+ });
721
+ });
722
+ };
723
+ const isImmediateCacheableResponse = (res) => {
724
+ if (!(cacheKey in res)) return false;
725
+ const body = res[cacheKey][1];
726
+ return body === null || typeof body === "string" || body instanceof Uint8Array;
727
+ };
728
+ const handleRequestError = () => new Response(null, { status: 400 });
729
+ const handleFetchError = (e) => new Response(null, { status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500 });
730
+ const handleResponseError = (e, outgoing) => {
359
731
  const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
360
732
  if (err.code === "ERR_STREAM_PREMATURE_CLOSE") console.info("The user aborted a request.");
361
733
  else {
@@ -365,20 +737,49 @@ var handleResponseError = (e, outgoing) => {
365
737
  outgoing.destroy(err);
366
738
  }
367
739
  };
368
- var flushHeaders = (outgoing) => {
740
+ const flushHeaders = (outgoing) => {
369
741
  if ("flushHeaders" in outgoing && outgoing.writable) outgoing.flushHeaders();
370
742
  };
371
- var responseViaCache = async (res, outgoing) => {
743
+ const responseViaCache = async (res, outgoing) => {
372
744
  let [status, body, header] = res[cacheKey];
745
+ if (!header) {
746
+ if (body === null) {
747
+ outgoing.writeHead(status);
748
+ outgoing.end();
749
+ } else if (typeof body === "string") {
750
+ outgoing.writeHead(status, {
751
+ "Content-Type": defaultContentType,
752
+ "Content-Length": Buffer.byteLength(body)
753
+ });
754
+ outgoing.end(body);
755
+ } else if (body instanceof Uint8Array) {
756
+ outgoing.writeHead(status, {
757
+ "Content-Type": defaultContentType,
758
+ "Content-Length": body.byteLength
759
+ });
760
+ outgoing.end(body);
761
+ } else if (body instanceof Blob) {
762
+ outgoing.writeHead(status, {
763
+ "Content-Type": defaultContentType,
764
+ "Content-Length": body.size
765
+ });
766
+ outgoing.end(new Uint8Array(await body.arrayBuffer()));
767
+ } else {
768
+ outgoing.writeHead(status, { "Content-Type": defaultContentType });
769
+ flushHeaders(outgoing);
770
+ await writeFromReadableStream(body, outgoing)?.catch((e) => handleResponseError(e, outgoing));
771
+ }
772
+ outgoing[outgoingEnded]?.();
773
+ return;
774
+ }
373
775
  let hasContentLength = false;
374
- if (!header) header = { "content-type": "text/plain; charset=UTF-8" };
375
- else if (header instanceof Headers) {
776
+ if (header instanceof Headers) {
376
777
  hasContentLength = header.has("content-length");
377
- header = buildOutgoingHttpHeaders(header);
778
+ header = buildOutgoingHttpHeaders(header, body === null ? void 0 : defaultContentType);
378
779
  } else if (Array.isArray(header)) {
379
780
  const headerObj = new Headers(header);
380
781
  hasContentLength = headerObj.has("content-length");
381
- header = buildOutgoingHttpHeaders(headerObj);
782
+ header = buildOutgoingHttpHeaders(headerObj, body === null ? void 0 : defaultContentType);
382
783
  } else for (const key in header) if (key.length === 14 && key.toLowerCase() === "content-length") {
383
784
  hasContentLength = true;
384
785
  break;
@@ -389,7 +790,8 @@ var responseViaCache = async (res, outgoing) => {
389
790
  else if (body instanceof Blob) header["Content-Length"] = body.size;
390
791
  }
391
792
  outgoing.writeHead(status, header);
392
- if (typeof body === "string" || body instanceof Uint8Array) outgoing.end(body);
793
+ if (body == null) outgoing.end();
794
+ else if (typeof body === "string" || body instanceof Uint8Array) outgoing.end(body);
393
795
  else if (body instanceof Blob) outgoing.end(new Uint8Array(await body.arrayBuffer()));
394
796
  else {
395
797
  flushHeaders(outgoing);
@@ -397,8 +799,8 @@ var responseViaCache = async (res, outgoing) => {
397
799
  }
398
800
  outgoing[outgoingEnded]?.();
399
801
  };
400
- var isPromise = (res) => typeof res.then === "function";
401
- var responseViaResponseObject = async (res, outgoing, options = {}) => {
802
+ const isPromise = (res) => typeof res.then === "function";
803
+ const responseViaResponseObject = async (res, outgoing, options = {}) => {
402
804
  if (isPromise(res)) if (options.errorHandler) try {
403
805
  res = await res;
404
806
  } catch (err) {
@@ -408,7 +810,7 @@ var responseViaResponseObject = async (res, outgoing, options = {}) => {
408
810
  }
409
811
  else res = await res.catch(handleFetchError);
410
812
  if (cacheKey in res) return responseViaCache(res, outgoing);
411
- const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
813
+ const resHeaderRecord = buildOutgoingHttpHeaders(res.headers, res.body === null ? void 0 : defaultContentType);
412
814
  if (res.body) {
413
815
  const reader = res.body.getReader();
414
816
  const values = [];
@@ -448,57 +850,55 @@ var responseViaResponseObject = async (res, outgoing, options = {}) => {
448
850
  if (values.length === 0) flushHeaders(outgoing);
449
851
  await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
450
852
  }
451
- } else if (resHeaderRecord[X_ALREADY_SENT]) {} else {
853
+ } else if (resHeaderRecord["x-hono-already-sent"]) {} else {
452
854
  outgoing.writeHead(res.status, resHeaderRecord);
453
855
  outgoing.end();
454
856
  }
455
857
  outgoing[outgoingEnded]?.();
456
858
  };
457
- var getRequestListener = (fetchCallback, options = {}) => {
859
+ const getRequestListener = (fetchCallback, options = {}) => {
458
860
  const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
459
- if (options.overrideGlobalObjects !== false && global.Request !== Request) {
460
- Object.defineProperty(global, "Request", { value: Request });
461
- Object.defineProperty(global, "Response", { value: Response2 });
861
+ if (options.overrideGlobalObjects !== false && global.Request !== Request$1) {
862
+ Object.defineProperty(global, "Request", { value: Request$1 });
863
+ Object.defineProperty(global, "Response", { value: Response$1 });
462
864
  }
463
865
  return async (incoming, outgoing) => {
464
866
  let res, req;
867
+ let needsBodyCleanup = false;
868
+ let closeHandlerAttached = false;
869
+ const ensureCloseHandler = () => {
870
+ if (!req || closeHandlerAttached) return;
871
+ closeHandlerAttached = true;
872
+ outgoing.on("close", makeCloseHandler(req, incoming, outgoing, needsBodyCleanup));
873
+ };
465
874
  try {
466
875
  req = newRequest(incoming, options.hostname);
467
- let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
468
- if (!incomingEnded) {
876
+ needsBodyCleanup = autoCleanupIncoming && !(incoming.method === "GET" || incoming.method === "HEAD");
877
+ if (needsBodyCleanup) {
469
878
  incoming[wrapBodyStream] = true;
470
- incoming.on("end", () => {
471
- incomingEnded = true;
472
- });
473
879
  if (incoming instanceof Http2ServerRequest) outgoing[outgoingEnded] = () => {
474
- if (!incomingEnded) setTimeout(() => {
475
- if (!incomingEnded) setTimeout(() => {
476
- drainIncoming(incoming);
880
+ if (!incoming.readableEnded) setTimeout(() => {
881
+ if (!incoming.readableEnded) setTimeout(() => {
882
+ incoming.destroy();
883
+ outgoing.destroy();
477
884
  });
478
885
  });
479
886
  };
480
- outgoing.on("finish", () => {
481
- if (!incomingEnded) drainIncoming(incoming);
482
- });
483
887
  }
484
- outgoing.on("close", () => {
485
- if (req[abortControllerKey]) {
486
- if (incoming.errored) req[abortControllerKey].abort(incoming.errored.toString());
487
- else if (!outgoing.writableFinished) req[abortControllerKey].abort("Client connection prematurely closed.");
488
- }
489
- if (!incomingEnded) setTimeout(() => {
490
- if (!incomingEnded) setTimeout(() => {
491
- drainIncoming(incoming);
492
- });
493
- });
494
- });
495
888
  res = fetchCallback(req, {
496
889
  incoming,
497
890
  outgoing
498
891
  });
499
- if (cacheKey in res) return responseViaCache(res, outgoing);
892
+ if (!isPromise(res) && isImmediateCacheableResponse(res)) {
893
+ if (needsBodyCleanup && !incoming.readableEnded) outgoing.once("finish", () => {
894
+ if (!incoming.readableEnded) drainIncoming(incoming);
895
+ });
896
+ return responseViaCache(res, outgoing);
897
+ }
898
+ ensureCloseHandler();
500
899
  } catch (e) {
501
900
  if (!res) if (options.errorHandler) {
901
+ ensureCloseHandler();
502
902
  res = await options.errorHandler(req ? e : toRequestError(e));
503
903
  if (!res) return;
504
904
  } else if (!req) res = handleRequestError();
@@ -512,16 +912,254 @@ var getRequestListener = (fetchCallback, options = {}) => {
512
912
  }
513
913
  };
514
914
  };
515
- var createAdaptorServer = (options) => {
915
+ /**
916
+ * @link https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent
917
+ */
918
+ const CloseEvent = globalThis.CloseEvent ?? class extends Event {
919
+ #eventInitDict;
920
+ constructor(type, eventInitDict = {}) {
921
+ super(type, eventInitDict);
922
+ this.#eventInitDict = eventInitDict;
923
+ }
924
+ get wasClean() {
925
+ return this.#eventInitDict.wasClean ?? false;
926
+ }
927
+ get code() {
928
+ return this.#eventInitDict.code ?? 0;
929
+ }
930
+ get reason() {
931
+ return this.#eventInitDict.reason ?? "";
932
+ }
933
+ };
934
+ /**
935
+ * Node.js has no global `ErrorEvent`, unlike `Event`/`MessageEvent`/`CloseEvent`.
936
+ * @link https://developer.mozilla.org/en-US/docs/Web/API/ErrorEvent
937
+ */
938
+ const ErrorEvent = globalThis.ErrorEvent ?? class extends Event {
939
+ #eventInitDict;
940
+ constructor(type, eventInitDict = {}) {
941
+ super(type, eventInitDict);
942
+ this.#eventInitDict = eventInitDict;
943
+ }
944
+ get message() {
945
+ return this.#eventInitDict.message ?? "";
946
+ }
947
+ get filename() {
948
+ return this.#eventInitDict.filename ?? "";
949
+ }
950
+ get lineno() {
951
+ return this.#eventInitDict.lineno ?? 0;
952
+ }
953
+ get colno() {
954
+ return this.#eventInitDict.colno ?? 0;
955
+ }
956
+ get error() {
957
+ return this.#eventInitDict.error ?? null;
958
+ }
959
+ };
960
+ const generateConnectionSymbol = () => Symbol("connection");
961
+ const CONNECTION_SYMBOL_KEY = Symbol("CONNECTION_SYMBOL_KEY");
962
+ const WAIT_FOR_WEBSOCKET_SYMBOL = Symbol("WAIT_FOR_WEBSOCKET_SYMBOL");
963
+ const responseHeadersToSkip = /* @__PURE__ */ new Set([
964
+ "connection",
965
+ "content-length",
966
+ "keep-alive",
967
+ "proxy-authenticate",
968
+ "proxy-authorization",
969
+ "te",
970
+ "trailer",
971
+ "transfer-encoding",
972
+ "upgrade",
973
+ "sec-websocket-accept",
974
+ "sec-websocket-extensions",
975
+ "sec-websocket-protocol"
976
+ ]);
977
+ const appendResponseHeaders = (headers, responseHeaders) => {
978
+ if (!responseHeaders) return;
979
+ responseHeaders.forEach((value, key) => {
980
+ if (responseHeadersToSkip.has(key.toLowerCase())) return;
981
+ headers.push(`${key}: ${value}`);
982
+ });
983
+ };
984
+ const rejectUpgradeRequest = (socket, status, responseHeaders) => {
985
+ const responseLines = ["Connection: close", "Content-Length: 0"];
986
+ appendResponseHeaders(responseLines, responseHeaders);
987
+ socket.end(`HTTP/1.1 ${status.toString()} ${STATUS_CODES[status] ?? ""}\r\n${responseLines.join("\r\n")}\r\n\r
988
+ `);
989
+ };
990
+ const createUpgradeRequest = (request) => {
991
+ const protocol = request.socket.encrypted ? "https" : "http";
992
+ const url = new URL(request.url ?? "/", `${protocol}://${request.headers.host ?? "localhost"}`);
993
+ const headers = new Headers();
994
+ for (const key in request.headers) {
995
+ const value = request.headers[key];
996
+ if (!value) continue;
997
+ headers.append(key, Array.isArray(value) ? value[0] : value);
998
+ }
999
+ return new Request(url, { headers });
1000
+ };
1001
+ const setupWebSocket = (options) => {
1002
+ const { server, fetchCallback, wss } = options;
1003
+ const waiterMap = /* @__PURE__ */ new Map();
1004
+ wss.on("connection", (ws, request) => {
1005
+ const waiter = waiterMap.get(request);
1006
+ if (waiter) {
1007
+ waiter.resolve(ws);
1008
+ waiterMap.delete(request);
1009
+ }
1010
+ });
1011
+ const rejectWaiter = (request) => {
1012
+ const waiter = waiterMap.get(request);
1013
+ if (waiter) {
1014
+ waiterMap.delete(request);
1015
+ waiter.reject(/* @__PURE__ */ new Error("WebSocket handshake aborted"));
1016
+ }
1017
+ };
1018
+ const waitForWebSocket = (request, connectionSymbol) => {
1019
+ return new Promise((resolve, reject) => {
1020
+ waiterMap.set(request, {
1021
+ resolve,
1022
+ reject,
1023
+ connectionSymbol
1024
+ });
1025
+ });
1026
+ };
1027
+ server.on("upgrade", async (request, socket, head) => {
1028
+ if (request.headers.upgrade?.toLowerCase() !== "websocket") return;
1029
+ const env = {
1030
+ incoming: request,
1031
+ outgoing: void 0,
1032
+ wss,
1033
+ [WAIT_FOR_WEBSOCKET_SYMBOL]: waitForWebSocket
1034
+ };
1035
+ let status = 400;
1036
+ let responseHeaders;
1037
+ try {
1038
+ const response = await fetchCallback(createUpgradeRequest(request), env);
1039
+ if (response instanceof Response) {
1040
+ status = response.status;
1041
+ responseHeaders = response.headers;
1042
+ }
1043
+ } catch {
1044
+ if (server.listenerCount("upgrade") === 1) rejectUpgradeRequest(socket, 500);
1045
+ return;
1046
+ }
1047
+ const waiter = waiterMap.get(request);
1048
+ if (!waiter || waiter.connectionSymbol !== env[CONNECTION_SYMBOL_KEY]) {
1049
+ rejectWaiter(request);
1050
+ if (server.listenerCount("upgrade") === 1) rejectUpgradeRequest(socket, status, responseHeaders);
1051
+ return;
1052
+ }
1053
+ const addResponseHeaders = (headers) => {
1054
+ appendResponseHeaders(headers, responseHeaders);
1055
+ };
1056
+ const reclaimWaiterOnClose = () => rejectWaiter(request);
1057
+ socket.once("close", reclaimWaiterOnClose);
1058
+ wss.on("headers", addResponseHeaders);
1059
+ try {
1060
+ wss.handleUpgrade(request, socket, head, (ws) => {
1061
+ socket.off("close", reclaimWaiterOnClose);
1062
+ wss.emit("connection", ws, request);
1063
+ });
1064
+ } finally {
1065
+ wss.off("headers", addResponseHeaders);
1066
+ }
1067
+ });
1068
+ server.on("close", () => {
1069
+ wss.close();
1070
+ });
1071
+ };
1072
+ defineWebSocketHelper(async (c, events, options) => {
1073
+ if (c.req.header("upgrade")?.toLowerCase() !== "websocket") return;
1074
+ const env = c.env;
1075
+ const waitForWebSocket = env[WAIT_FOR_WEBSOCKET_SYMBOL];
1076
+ if (!waitForWebSocket || !env.incoming) return new Response(null, { status: 500 });
1077
+ const connectionSymbol = generateConnectionSymbol();
1078
+ env[CONNECTION_SYMBOL_KEY] = connectionSymbol;
1079
+ (async () => {
1080
+ let ws;
1081
+ try {
1082
+ ws = await waitForWebSocket(env.incoming, connectionSymbol);
1083
+ } catch {
1084
+ return;
1085
+ }
1086
+ const messagesReceivedInStarting = [];
1087
+ const bufferMessage = (data, isBinary) => {
1088
+ messagesReceivedInStarting.push([data, isBinary]);
1089
+ };
1090
+ ws.on("message", bufferMessage);
1091
+ const ctx = {
1092
+ binaryType: "arraybuffer",
1093
+ close(code, reason) {
1094
+ ws.close(code, reason);
1095
+ },
1096
+ protocol: ws.protocol,
1097
+ raw: ws,
1098
+ get readyState() {
1099
+ return ws.readyState;
1100
+ },
1101
+ send(source, opts) {
1102
+ ws.send(source, { compress: opts?.compress });
1103
+ },
1104
+ url: new URL(c.req.url)
1105
+ };
1106
+ try {
1107
+ events?.onOpen?.(new Event("open"), ctx);
1108
+ } catch (e) {
1109
+ (options?.onError ?? console.error)(e);
1110
+ }
1111
+ const handleMessage = (data, isBinary) => {
1112
+ const datas = Array.isArray(data) ? data : [data];
1113
+ for (const data of datas) try {
1114
+ events?.onMessage?.(new MessageEvent("message", { data: isBinary ? data instanceof ArrayBuffer ? data : data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength) : typeof data === "string" ? data : Buffer.from(data).toString("utf-8") }), ctx);
1115
+ } catch (e) {
1116
+ (options?.onError ?? console.error)(e);
1117
+ }
1118
+ };
1119
+ ws.off("message", bufferMessage);
1120
+ for (const message of messagesReceivedInStarting) handleMessage(...message);
1121
+ ws.on("message", (data, isBinary) => {
1122
+ handleMessage(data, isBinary);
1123
+ });
1124
+ ws.on("close", (code, reason) => {
1125
+ try {
1126
+ events?.onClose?.(new CloseEvent("close", {
1127
+ code,
1128
+ reason: reason.toString()
1129
+ }), ctx);
1130
+ } catch (e) {
1131
+ (options?.onError ?? console.error)(e);
1132
+ }
1133
+ });
1134
+ ws.on("error", (error) => {
1135
+ try {
1136
+ events?.onError?.(new ErrorEvent("error", { error }), ctx);
1137
+ } catch (e) {
1138
+ (options?.onError ?? console.error)(e);
1139
+ }
1140
+ });
1141
+ })();
1142
+ return new Response();
1143
+ });
1144
+ const createAdaptorServer = (options) => {
516
1145
  const fetchCallback = options.fetch;
517
1146
  const requestListener = getRequestListener(fetchCallback, {
518
1147
  hostname: options.hostname,
519
1148
  overrideGlobalObjects: options.overrideGlobalObjects,
520
1149
  autoCleanupIncoming: options.autoCleanupIncoming
521
1150
  });
522
- return (options.createServer || createServer)(options.serverOptions || {}, requestListener);
1151
+ const server = (options.createServer || createServer)(options.serverOptions || {}, requestListener);
1152
+ if (options.websocket && options.websocket.server) {
1153
+ if (options.websocket.server.options.noServer !== true) throw new Error("WebSocket server must be created with { noServer: true } option");
1154
+ setupWebSocket({
1155
+ server,
1156
+ fetchCallback,
1157
+ wss: options.websocket.server
1158
+ });
1159
+ }
1160
+ return server;
523
1161
  };
524
- var serve = (options, listeningListener) => {
1162
+ const serve = (options, listeningListener) => {
525
1163
  const server = createAdaptorServer(options);
526
1164
  server.listen(options?.port ?? 3e3, options.hostname, () => {
527
1165
  const serverInfo = server.address();
@@ -530,46 +1168,116 @@ var serve = (options, listeningListener) => {
530
1168
  return server;
531
1169
  };
532
1170
  //#endregion
533
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@hono/node-server/1.19.14/42c5178abe0ceb83054b3103dd081cbbfb29d6fb64d2c11700a4167fb620acdc/node_modules/@hono/node-server/dist/serve-static.mjs
534
- var COMPRESSIBLE_CONTENT_TYPE_REGEX = /^\s*(?:text\/[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i;
535
- var ENCODINGS = {
536
- br: ".br",
537
- zstd: ".zst",
538
- gzip: ".gz"
539
- };
540
- var ENCODINGS_ORDERED_KEYS = Object.keys(ENCODINGS);
541
- var pr54206Applied = () => {
1171
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@hono/node-server/2.0.10/a560c4fb751eda40b27a36d7ca69ad4a96169452a5efc0b1a386b85209fd1371/node_modules/@hono/node-server/dist/utils/stream.mjs
1172
+ const pr54206Applied = () => {
542
1173
  const [major, minor] = versions.node.split(".").map((component) => parseInt(component));
543
1174
  return major >= 23 || major === 22 && minor >= 7 || major === 20 && minor >= 18;
544
1175
  };
545
- var useReadableToWeb = pr54206Applied();
546
- var createStreamBody = (stream) => {
547
- if (useReadableToWeb) return Readable.toWeb(stream);
1176
+ const useReadableToWeb = pr54206Applied();
1177
+ const createStreamBody = (stream, useNativeReadableToWeb = useReadableToWeb) => {
1178
+ if (useNativeReadableToWeb) return Readable.toWeb(stream);
1179
+ let controller;
1180
+ let settled = false;
1181
+ const cleanup = () => {
1182
+ stream.off("data", onData);
1183
+ stream.off("error", onError);
1184
+ stream.off("end", onTerminate);
1185
+ stream.off("close", onTerminate);
1186
+ };
1187
+ const settle = (callback) => {
1188
+ if (settled) return;
1189
+ settled = true;
1190
+ cleanup();
1191
+ callback?.();
1192
+ };
1193
+ const onData = (chunk) => {
1194
+ if (settled || !controller) return;
1195
+ controller.enqueue(chunk);
1196
+ if ((controller.desiredSize ?? 0) <= 0) stream.pause();
1197
+ };
1198
+ const onError = (error) => {
1199
+ settle(() => {
1200
+ controller?.error(error);
1201
+ });
1202
+ };
1203
+ const onTerminate = () => {
1204
+ settle(() => {
1205
+ controller?.close();
1206
+ });
1207
+ };
548
1208
  return new ReadableStream({
549
- start(controller) {
550
- stream.on("data", (chunk) => {
551
- controller.enqueue(chunk);
552
- });
553
- stream.on("error", (err) => {
554
- controller.error(err);
555
- });
556
- stream.on("end", () => {
557
- controller.close();
558
- });
1209
+ start(streamController) {
1210
+ controller = streamController;
1211
+ stream.on("data", onData);
1212
+ stream.on("error", onError);
1213
+ stream.on("end", onTerminate);
1214
+ stream.on("close", onTerminate);
1215
+ stream.pause();
1216
+ },
1217
+ pull() {
1218
+ if (!settled) stream.resume();
559
1219
  },
560
1220
  cancel() {
1221
+ settle();
1222
+ const ignoreError = () => {};
1223
+ stream.on("error", ignoreError);
1224
+ stream.once("close", () => stream.off("error", ignoreError));
561
1225
  stream.destroy();
562
1226
  }
563
1227
  });
564
1228
  };
565
- var getStats = (path) => {
1229
+ //#endregion
1230
+ //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@hono/node-server/2.0.10/a560c4fb751eda40b27a36d7ca69ad4a96169452a5efc0b1a386b85209fd1371/node_modules/@hono/node-server/dist/serve-static.mjs
1231
+ const COMPRESSIBLE_CONTENT_TYPE_REGEX = /^\s*(?:text\/[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i;
1232
+ const ENCODINGS = {
1233
+ br: ".br",
1234
+ zstd: ".zst",
1235
+ gzip: ".gz"
1236
+ };
1237
+ const ENCODINGS_ORDERED_KEYS = Object.keys(ENCODINGS);
1238
+ const getStats = (path) => {
566
1239
  let stats;
567
1240
  try {
568
1241
  stats = statSync(path);
569
1242
  } catch {}
570
1243
  return stats;
571
1244
  };
572
- var tryDecode = (str, decoder) => {
1245
+ const BYTE_RANGE_PATTERN = /^(?:bytes=)?(?!-$)(\d*)-(\d*)$/;
1246
+ const parseByteRange = (range) => {
1247
+ const match = range.match(BYTE_RANGE_PATTERN);
1248
+ if (!match) return;
1249
+ const [, start, end] = match;
1250
+ if (start === "") return {
1251
+ type: "suffix",
1252
+ length: Number(end)
1253
+ };
1254
+ if (end === "") return {
1255
+ type: "open-ended",
1256
+ start: Number(start)
1257
+ };
1258
+ return {
1259
+ type: "bounded",
1260
+ start: Number(start),
1261
+ end: Number(end)
1262
+ };
1263
+ };
1264
+ const resolveByteRange = (spec, size) => {
1265
+ if (size === 0) return;
1266
+ if (spec.type === "suffix") {
1267
+ if (spec.length === 0) return;
1268
+ return {
1269
+ start: Math.max(size - spec.length, 0),
1270
+ end: size - 1
1271
+ };
1272
+ }
1273
+ const end = spec.type === "bounded" ? Math.min(spec.end, size - 1) : size - 1;
1274
+ if (spec.start >= size || spec.start > end) return;
1275
+ return {
1276
+ start: spec.start,
1277
+ end
1278
+ };
1279
+ };
1280
+ const tryDecode = (str, decoder) => {
573
1281
  try {
574
1282
  return decoder(str);
575
1283
  } catch {
@@ -582,8 +1290,8 @@ var tryDecode = (str, decoder) => {
582
1290
  });
583
1291
  }
584
1292
  };
585
- var tryDecodeURI = (str) => tryDecode(str, decodeURI);
586
- var serveStatic = (options = { root: "" }) => {
1293
+ const tryDecodeURI = (str) => tryDecode(str, decodeURI);
1294
+ const serveStatic = (options = { root: "" }) => {
587
1295
  const root = options.root || "";
588
1296
  const optionPath = options.path;
589
1297
  if (root !== "" && !existsSync(root)) console.error(`serveStatic: root path '${root}' is not found, are you sure it's correct?`);
@@ -593,7 +1301,7 @@ var serveStatic = (options = { root: "" }) => {
593
1301
  if (optionPath) filename = optionPath;
594
1302
  else try {
595
1303
  filename = tryDecodeURI(c.req.path);
596
- if (/(?:^|[\/\\])\.{1,2}(?:$|[\/\\])|[\/\\]{2,}/.test(filename)) throw new Error();
1304
+ if (/(?:^|[\/\\])\.{1,2}(?:$|[\/\\])|[\/\\]{2,}|\\/.test(filename)) throw new Error();
597
1305
  } catch {
598
1306
  await options.onNotFound?.(c.req.path, c);
599
1307
  return next();
@@ -611,7 +1319,7 @@ var serveStatic = (options = { root: "" }) => {
611
1319
  }
612
1320
  const mimeType = getMimeType(path);
613
1321
  c.header("Content-Type", mimeType || "application/octet-stream");
614
- if (options.precompressed && (!mimeType || COMPRESSIBLE_CONTENT_TYPE_REGEX.test(mimeType))) {
1322
+ if (options.precompressed && (!mimeType || mimeType === "application/octet-stream" || COMPRESSIBLE_CONTENT_TYPE_REGEX.test(mimeType))) {
615
1323
  const acceptEncodingSet = new Set(c.req.header("Accept-Encoding")?.split(",").map((encoding) => encoding.trim()));
616
1324
  for (const encoding of ENCODINGS_ORDERED_KEYS) {
617
1325
  if (!acceptEncodingSet.has(encoding)) continue;
@@ -628,6 +1336,7 @@ var serveStatic = (options = { root: "" }) => {
628
1336
  let result;
629
1337
  const size = stats.size;
630
1338
  const range = c.req.header("range") || "";
1339
+ c.header("Last-Modified", stats.mtime.toUTCString());
631
1340
  if (c.req.method == "HEAD" || c.req.method == "OPTIONS") {
632
1341
  c.header("Content-Length", size.toString());
633
1342
  c.status(200);
@@ -637,19 +1346,24 @@ var serveStatic = (options = { root: "" }) => {
637
1346
  result = c.body(createStreamBody(createReadStream(path)), 200);
638
1347
  } else {
639
1348
  c.header("Accept-Ranges", "bytes");
640
- c.header("Date", stats.birthtime.toUTCString());
641
- const parts = range.replace(/bytes=/, "").split("-", 2);
642
- const start = parseInt(parts[0], 10) || 0;
643
- let end = parseInt(parts[1], 10) || size - 1;
644
- if (size < end - start + 1) end = size - 1;
645
- const chunksize = end - start + 1;
646
- const stream = createReadStream(path, {
647
- start,
648
- end
649
- });
650
- c.header("Content-Length", chunksize.toString());
651
- c.header("Content-Range", `bytes ${start}-${end}/${stats.size}`);
652
- result = c.body(createStreamBody(stream), 206);
1349
+ const resolvedRange = resolveByteRange(parseByteRange(range) ?? {
1350
+ type: "open-ended",
1351
+ start: 0
1352
+ }, size);
1353
+ if (!resolvedRange) {
1354
+ c.header("Content-Range", `bytes */${size}`);
1355
+ result = c.body(null, 416);
1356
+ } else {
1357
+ const { start, end } = resolvedRange;
1358
+ const chunkSize = end - start + 1;
1359
+ const stream = createReadStream(path, {
1360
+ start,
1361
+ end
1362
+ });
1363
+ c.header("Content-Length", chunkSize.toString());
1364
+ c.header("Content-Range", `bytes ${start}-${end}/${size}`);
1365
+ result = c.body(createStreamBody(stream), 206);
1366
+ }
653
1367
  }
654
1368
  await options.onFound?.(path, c);
655
1369
  return result;
@@ -2002,7 +2716,7 @@ const headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/;
2002
2716
  function checkInvalidHeaderChar(val) {
2003
2717
  return headerCharRegex.test(val);
2004
2718
  }
2005
- const STATUS_CODES = {
2719
+ const STATUS_CODES$1 = {
2006
2720
  100: "Continue",
2007
2721
  101: "Switching Protocols",
2008
2722
  102: "Processing",
@@ -2171,7 +2885,7 @@ var FetchServerResponse = class FetchServerResponse extends FetchOutgoingMessage
2171
2885
  if (statusCode < 100 || statusCode > 999) throw new ERR_HTTP_INVALID_STATUS_CODE(originalStatusCode);
2172
2886
  if (typeof reason === "string") this.statusMessage = reason;
2173
2887
  else {
2174
- this.statusMessage ||= STATUS_CODES[statusCode] || "unknown";
2888
+ this.statusMessage ||= STATUS_CODES$1[statusCode] || "unknown";
2175
2889
  obj ??= reason;
2176
2890
  }
2177
2891
  this.statusCode = statusCode;