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