@cimplify/sdk 0.83.0 → 0.85.0

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/dist/advanced.d.mts +3 -3
  2. package/dist/advanced.d.ts +3 -3
  3. package/dist/{chunk-ODEPW244.js → chunk-A6J7W6DH.js} +2 -2
  4. package/dist/{chunk-I6RE4BKH.mjs → chunk-DU4IX2I2.mjs} +1 -1
  5. package/dist/{chunk-PLTP6HWW.mjs → chunk-GIFVSWYJ.mjs} +18 -18
  6. package/dist/{chunk-FKBXZ2A6.js → chunk-NWTCBGJ2.js} +18 -18
  7. package/dist/{client-Cogz7C1t.d.mts → client-BEhIE0Dm.d.mts} +2 -2
  8. package/dist/{client-Cq3B-WXv.d.ts → client-BT5gaiGR.d.ts} +2 -2
  9. package/dist/{client-DnHP_2Jw.d.mts → client-DLtwQ-jI.d.mts} +2 -2
  10. package/dist/{client-xc2aQSB4.d.ts → client-WKKxIiF1.d.ts} +2 -2
  11. package/dist/{index-C4xE31-D.d.ts → index-BrC1x2kK.d.ts} +3 -3
  12. package/dist/{index-Dy8D3r9b.d.mts → index-DZz6hdrT.d.mts} +3 -3
  13. package/dist/index.d.mts +6 -6
  14. package/dist/index.d.ts +6 -6
  15. package/dist/mock/cli.mjs +657 -353
  16. package/dist/mock/library.js +18 -18
  17. package/dist/mock/library.mjs +18 -18
  18. package/dist/mock/msw.js +18 -18
  19. package/dist/mock/msw.mjs +18 -18
  20. package/dist/{payment-nH9OCUg2.d.ts → payment-D1f3ZQPC.d.ts} +1 -1
  21. package/dist/{payment-T_0MUE9o.d.mts → payment-Dh-6cRcV.d.mts} +1 -1
  22. package/dist/{price-Bg7hujK_.d.mts → price-4T7dlhxM.d.mts} +5 -1
  23. package/dist/{price-B8WMoldA.d.ts → price-CQdOJoX-.d.ts} +5 -1
  24. package/dist/{product-DXhjLQ_w.d.mts → product-RJMIdCAf.d.mts} +39 -2
  25. package/dist/{product-DXhjLQ_w.d.ts → product-RJMIdCAf.d.ts} +39 -2
  26. package/dist/react.d.mts +51 -5
  27. package/dist/react.d.ts +51 -5
  28. package/dist/react.js +137 -27
  29. package/dist/react.mjs +136 -28
  30. package/dist/{server-DaovvB9J.d.mts → server-DjK98UW-.d.mts} +1 -1
  31. package/dist/{server-ZGCyuz4V.d.ts → server-DvThXldo.d.ts} +1 -1
  32. package/dist/server.d.mts +4 -4
  33. package/dist/server.d.ts +4 -4
  34. package/dist/styles.css +1 -1
  35. package/dist/testing/msw.d.mts +2 -2
  36. package/dist/testing/msw.d.ts +2 -2
  37. package/dist/testing/msw.js +2 -2
  38. package/dist/testing/msw.mjs +1 -1
  39. package/dist/testing/suite.d.mts +6 -6
  40. package/dist/testing/suite.d.ts +6 -6
  41. package/dist/testing/suite.js +21 -21
  42. package/dist/testing/suite.mjs +2 -2
  43. package/dist/testing.d.mts +20 -20
  44. package/dist/testing.d.ts +20 -20
  45. package/dist/testing.js +77 -77
  46. package/dist/testing.mjs +3 -3
  47. package/dist/utils.d.mts +4 -4
  48. package/dist/utils.d.ts +4 -4
  49. package/package.json +21 -21
  50. package/registry/default-product-layout.json +1 -1
  51. package/registry/retail-product-card.json +1 -1
package/dist/mock/cli.mjs CHANGED
@@ -2,44 +2,59 @@
2
2
  import { writeFileSync, existsSync, readFileSync } from 'fs';
3
3
  import { basename, isAbsolute, resolve } from 'path';
4
4
  import { pathToFileURL } from 'url';
5
- import { createServer } from 'http';
5
+ import { createServer, STATUS_CODES } from 'http';
6
6
  import { Http2ServerRequest, constants } from 'http2';
7
7
  import { Readable } from 'stream';
8
- import crypto, { createHmac } from 'crypto';
8
+ import { createHmac } from 'crypto';
9
9
 
10
+ // ../node_modules/.bun/@hono+node-server@2.0.5+8bc17dcb8a4189a6/node_modules/@hono/node-server/dist/constants-BLSFu_RU.mjs
11
+ var X_ALREADY_SENT = "x-hono-already-sent";
12
+
13
+ // ../node_modules/.bun/@hono+node-server@2.0.5+8bc17dcb8a4189a6/node_modules/@hono/node-server/dist/index.mjs
10
14
  var RequestError = class extends Error {
11
15
  constructor(message, options) {
12
16
  super(message, options);
13
17
  this.name = "RequestError";
14
18
  }
15
19
  };
16
- var toRequestError = (e) => {
17
- if (e instanceof RequestError) {
18
- return e;
20
+ var reValidRequestUrl = /^\/[!#$&-;=?-\[\]_a-z~]*$/;
21
+ var reDotSegment = /\/\.\.?(?:[/?#]|$)/;
22
+ var reValidHost = /^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/;
23
+ var buildUrl = (scheme, host, incomingUrl) => {
24
+ const url = `${scheme}://${host}${incomingUrl}`;
25
+ if (!reValidHost.test(host)) {
26
+ const urlObj = new URL(url);
27
+ if (urlObj.hostname.length !== host.length && urlObj.hostname !== (host.includes(":") ? host.replace(/:\d+$/, "") : host).toLowerCase()) throw new RequestError("Invalid host header");
28
+ return urlObj.href;
29
+ } else if (incomingUrl.length === 0) return url + "/";
30
+ else {
31
+ if (incomingUrl.charCodeAt(0) !== 47) throw new RequestError("Invalid URL");
32
+ if (!reValidRequestUrl.test(incomingUrl) || reDotSegment.test(incomingUrl)) return new URL(url).href;
33
+ return url;
19
34
  }
35
+ };
36
+ var toRequestError = (e) => {
37
+ if (e instanceof RequestError) return e;
20
38
  return new RequestError(e.message, { cause: e });
21
39
  };
22
40
  var GlobalRequest = global.Request;
23
- var Request2 = class extends GlobalRequest {
41
+ var Request$1 = class extends GlobalRequest {
24
42
  constructor(input, options) {
25
43
  if (typeof input === "object" && getRequestCache in input) {
44
+ const hasReplacementBody = options !== void 0 && "body" in options && options.body != null;
45
+ if (input[bodyConsumedDirectlyKey] && !hasReplacementBody) throw new TypeError("Cannot construct a Request with a Request object that has already been used.");
26
46
  input = input[getRequestCache]();
27
47
  }
28
- if (typeof options?.body?.getReader !== "undefined") {
29
- options.duplex ??= "half";
30
- }
48
+ if (typeof options?.body?.getReader !== "undefined") options.duplex ??= "half";
31
49
  super(input, options);
32
50
  }
33
51
  };
34
52
  var newHeadersFromIncoming = (incoming) => {
35
53
  const headerRecord = [];
36
54
  const rawHeaders = incoming.rawHeaders;
37
- for (let i = 0; i < rawHeaders.length; i += 2) {
38
- const { [i]: key, [i + 1]: value } = rawHeaders;
39
- if (key.charCodeAt(0) !== /*:*/
40
- 58) {
41
- headerRecord.push([key, value]);
42
- }
55
+ for (let i = 0, len = rawHeaders.length; i < len; i += 2) {
56
+ const key = rawHeaders[i];
57
+ if (key.charCodeAt(0) !== 58) headerRecord.push([key, rawHeaders[i + 1]]);
43
58
  }
44
59
  return new Headers(headerRecord);
45
60
  };
@@ -52,55 +67,190 @@ var newRequestFromIncoming = (method, url, headers, incoming, abortController) =
52
67
  };
53
68
  if (method === "TRACE") {
54
69
  init.method = "GET";
55
- const req = new Request2(url, init);
56
- Object.defineProperty(req, "method", {
57
- get() {
58
- return "TRACE";
59
- }
60
- });
70
+ const req = new Request$1(url, init);
71
+ Object.defineProperty(req, "method", { get() {
72
+ return "TRACE";
73
+ } });
61
74
  return req;
62
75
  }
63
- if (!(method === "GET" || method === "HEAD")) {
64
- if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
65
- init.body = new ReadableStream({
66
- start(controller) {
67
- controller.enqueue(incoming.rawBody);
68
- controller.close();
69
- }
70
- });
71
- } else if (incoming[wrapBodyStream]) {
72
- let reader;
73
- init.body = new ReadableStream({
74
- async pull(controller) {
75
- try {
76
- reader ||= Readable.toWeb(incoming).getReader();
77
- const { done, value } = await reader.read();
78
- if (done) {
79
- controller.close();
80
- } else {
81
- controller.enqueue(value);
82
- }
83
- } catch (error) {
84
- controller.error(error);
85
- }
86
- }
87
- });
88
- } else {
89
- init.body = Readable.toWeb(incoming);
90
- }
91
- }
92
- return new Request2(url, init);
76
+ if (!(method === "GET" || method === "HEAD")) if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) init.body = new ReadableStream({ start(controller) {
77
+ controller.enqueue(incoming.rawBody);
78
+ controller.close();
79
+ } });
80
+ else if (incoming[wrapBodyStream]) {
81
+ let reader;
82
+ init.body = new ReadableStream({ async pull(controller) {
83
+ try {
84
+ reader ||= Readable.toWeb(incoming).getReader();
85
+ const { done, value } = await reader.read();
86
+ if (done) controller.close();
87
+ else controller.enqueue(value);
88
+ } catch (error) {
89
+ controller.error(error);
90
+ }
91
+ } });
92
+ } else init.body = Readable.toWeb(incoming);
93
+ return new Request$1(url, init);
93
94
  };
94
95
  var getRequestCache = /* @__PURE__ */ Symbol("getRequestCache");
95
96
  var requestCache = /* @__PURE__ */ Symbol("requestCache");
96
97
  var incomingKey = /* @__PURE__ */ Symbol("incomingKey");
97
98
  var urlKey = /* @__PURE__ */ Symbol("urlKey");
99
+ var methodKey = /* @__PURE__ */ Symbol("methodKey");
98
100
  var headersKey = /* @__PURE__ */ Symbol("headersKey");
99
101
  var abortControllerKey = /* @__PURE__ */ Symbol("abortControllerKey");
100
102
  var getAbortController = /* @__PURE__ */ Symbol("getAbortController");
103
+ var abortRequest = /* @__PURE__ */ Symbol("abortRequest");
104
+ var bodyBufferKey = /* @__PURE__ */ Symbol("bodyBuffer");
105
+ var bodyReadPromiseKey = /* @__PURE__ */ Symbol("bodyReadPromise");
106
+ var bodyConsumedDirectlyKey = /* @__PURE__ */ Symbol("bodyConsumedDirectly");
107
+ var bodyLockReaderKey = /* @__PURE__ */ Symbol("bodyLockReader");
108
+ var abortReasonKey = /* @__PURE__ */ Symbol("abortReason");
109
+ var newBodyUnusableError = () => {
110
+ return /* @__PURE__ */ new TypeError("Body is unusable");
111
+ };
112
+ var rejectBodyUnusable = () => {
113
+ return Promise.reject(newBodyUnusableError());
114
+ };
115
+ var textDecoder = new TextDecoder();
116
+ var consumeBodyDirectOnce = (request) => {
117
+ if (request[bodyConsumedDirectlyKey]) return rejectBodyUnusable();
118
+ request[bodyConsumedDirectlyKey] = true;
119
+ };
120
+ var toArrayBuffer = (buf) => {
121
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
122
+ };
123
+ var contentType = (request) => {
124
+ return (request[headersKey] ||= newHeadersFromIncoming(request[incomingKey])).get("content-type") || "";
125
+ };
126
+ var methodTokenRegExp = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
127
+ var normalizeIncomingMethod = (method) => {
128
+ if (typeof method !== "string" || method.length === 0) return "GET";
129
+ switch (method) {
130
+ case "DELETE":
131
+ case "GET":
132
+ case "HEAD":
133
+ case "OPTIONS":
134
+ case "POST":
135
+ case "PUT":
136
+ return method;
137
+ }
138
+ const upper = method.toUpperCase();
139
+ switch (upper) {
140
+ case "DELETE":
141
+ case "GET":
142
+ case "HEAD":
143
+ case "OPTIONS":
144
+ case "POST":
145
+ case "PUT":
146
+ return upper;
147
+ default:
148
+ return method;
149
+ }
150
+ };
151
+ var validateDirectReadMethod = (method) => {
152
+ if (!methodTokenRegExp.test(method)) return /* @__PURE__ */ new TypeError(`'${method}' is not a valid HTTP method.`);
153
+ const normalized = method.toUpperCase();
154
+ if (normalized === "CONNECT" || normalized === "TRACK" || normalized === "TRACE" && method !== "TRACE") return /* @__PURE__ */ new TypeError(`'${method}' HTTP method is unsupported.`);
155
+ };
156
+ var readBodyWithFastPath = (request, method, fromBuffer) => {
157
+ if (request[bodyConsumedDirectlyKey]) return rejectBodyUnusable();
158
+ const methodName = request.method;
159
+ if (methodName === "GET" || methodName === "HEAD") return request[getRequestCache]()[method]();
160
+ const methodValidationError = validateDirectReadMethod(methodName);
161
+ if (methodValidationError) return Promise.reject(methodValidationError);
162
+ if (request[requestCache]) {
163
+ if (methodName !== "TRACE") return request[requestCache][method]();
164
+ }
165
+ const alreadyUsedError = consumeBodyDirectOnce(request);
166
+ if (alreadyUsedError) return alreadyUsedError;
167
+ const raw2 = readRawBodyIfAvailable(request);
168
+ if (raw2) {
169
+ const result = Promise.resolve(fromBuffer(raw2, request));
170
+ request[bodyBufferKey] = void 0;
171
+ return result;
172
+ }
173
+ return readBodyDirect(request).then((buf) => {
174
+ const result = fromBuffer(buf, request);
175
+ request[bodyBufferKey] = void 0;
176
+ return result;
177
+ });
178
+ };
179
+ var readRawBodyIfAvailable = (request) => {
180
+ const incoming = request[incomingKey];
181
+ if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) return incoming.rawBody;
182
+ };
183
+ var readBodyDirect = (request) => {
184
+ if (request[bodyBufferKey]) return Promise.resolve(request[bodyBufferKey]);
185
+ if (request[bodyReadPromiseKey]) return request[bodyReadPromiseKey];
186
+ const incoming = request[incomingKey];
187
+ if (Readable.isDisturbed(incoming)) return rejectBodyUnusable();
188
+ const promise = new Promise((resolve2, reject) => {
189
+ const chunks = [];
190
+ let settled = false;
191
+ const finish = (callback) => {
192
+ if (settled) return;
193
+ settled = true;
194
+ cleanup();
195
+ callback();
196
+ };
197
+ const onData = (chunk) => {
198
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
199
+ };
200
+ const onEnd = () => {
201
+ finish(() => {
202
+ const buffer = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks);
203
+ request[bodyBufferKey] = buffer;
204
+ resolve2(buffer);
205
+ });
206
+ };
207
+ const onError = (error) => {
208
+ finish(() => {
209
+ reject(error);
210
+ });
211
+ };
212
+ const onClose = () => {
213
+ if (incoming.readableEnded) {
214
+ onEnd();
215
+ return;
216
+ }
217
+ finish(() => {
218
+ if (incoming.errored) {
219
+ reject(incoming.errored);
220
+ return;
221
+ }
222
+ const reason = request[abortReasonKey];
223
+ if (reason !== void 0) {
224
+ reject(reason instanceof Error ? reason : new Error(String(reason)));
225
+ return;
226
+ }
227
+ reject(/* @__PURE__ */ new Error("Client connection prematurely closed."));
228
+ });
229
+ };
230
+ const cleanup = () => {
231
+ incoming.off("data", onData);
232
+ incoming.off("end", onEnd);
233
+ incoming.off("error", onError);
234
+ incoming.off("close", onClose);
235
+ request[bodyReadPromiseKey] = void 0;
236
+ };
237
+ incoming.on("data", onData);
238
+ incoming.on("end", onEnd);
239
+ incoming.on("error", onError);
240
+ incoming.on("close", onClose);
241
+ queueMicrotask(() => {
242
+ if (settled) return;
243
+ if (incoming.readableEnded) onEnd();
244
+ else if (incoming.errored) onError(incoming.errored);
245
+ else if (incoming.destroyed) onClose();
246
+ });
247
+ });
248
+ request[bodyReadPromiseKey] = promise;
249
+ return promise;
250
+ };
101
251
  var requestPrototype = {
102
252
  get method() {
103
- return this[incomingKey].method || "GET";
253
+ return this[methodKey];
104
254
  },
105
255
  get url() {
106
256
  return this[urlKey];
@@ -108,24 +258,57 @@ var requestPrototype = {
108
258
  get headers() {
109
259
  return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
110
260
  },
261
+ [abortRequest](reason) {
262
+ if (this[abortReasonKey] === void 0) this[abortReasonKey] = reason;
263
+ const abortController = this[abortControllerKey];
264
+ if (abortController && !abortController.signal.aborted) abortController.abort(reason);
265
+ },
111
266
  [getAbortController]() {
112
- this[getRequestCache]();
267
+ this[abortControllerKey] ||= new AbortController();
268
+ if (this[abortReasonKey] !== void 0 && !this[abortControllerKey].signal.aborted) this[abortControllerKey].abort(this[abortReasonKey]);
113
269
  return this[abortControllerKey];
114
270
  },
115
271
  [getRequestCache]() {
116
- this[abortControllerKey] ||= new AbortController();
117
- return this[requestCache] ||= newRequestFromIncoming(
118
- this.method,
119
- this[urlKey],
120
- this.headers,
121
- this[incomingKey],
122
- this[abortControllerKey]
123
- );
272
+ const abortController = this[getAbortController]();
273
+ if (this[requestCache]) return this[requestCache];
274
+ const method = this.method;
275
+ if (this[bodyConsumedDirectlyKey] && !(method === "GET" || method === "HEAD")) {
276
+ this[bodyBufferKey] = void 0;
277
+ const init = {
278
+ method: method === "TRACE" ? "GET" : method,
279
+ headers: this.headers,
280
+ signal: abortController.signal
281
+ };
282
+ if (method !== "TRACE") {
283
+ init.body = new ReadableStream({ start(c) {
284
+ c.close();
285
+ } });
286
+ init.duplex = "half";
287
+ }
288
+ const req = new Request$1(this[urlKey], init);
289
+ if (method === "TRACE") Object.defineProperty(req, "method", { get() {
290
+ return "TRACE";
291
+ } });
292
+ return this[requestCache] = req;
293
+ }
294
+ return this[requestCache] = newRequestFromIncoming(this.method, this[urlKey], this.headers, this[incomingKey], abortController);
295
+ },
296
+ get body() {
297
+ if (!this[bodyConsumedDirectlyKey]) return this[getRequestCache]().body;
298
+ const request = this[getRequestCache]();
299
+ if (!this[bodyLockReaderKey] && request.body) this[bodyLockReaderKey] = request.body.getReader();
300
+ return request.body;
301
+ },
302
+ get bodyUsed() {
303
+ if (this[bodyConsumedDirectlyKey]) return true;
304
+ if (this[requestCache]) return this[requestCache].bodyUsed;
305
+ return false;
124
306
  }
125
307
  };
308
+ Object.defineProperty(requestPrototype, "signal", { get() {
309
+ return this[getAbortController]().signal;
310
+ } });
126
311
  [
127
- "body",
128
- "bodyUsed",
129
312
  "cache",
130
313
  "credentials",
131
314
  "destination",
@@ -134,86 +317,100 @@ var requestPrototype = {
134
317
  "redirect",
135
318
  "referrer",
136
319
  "referrerPolicy",
137
- "signal",
138
320
  "keepalive"
139
321
  ].forEach((k) => {
140
- Object.defineProperty(requestPrototype, k, {
141
- get() {
142
- return this[getRequestCache]()[k];
143
- }
144
- });
322
+ Object.defineProperty(requestPrototype, k, { get() {
323
+ return this[getRequestCache]()[k];
324
+ } });
145
325
  });
146
- ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
147
- Object.defineProperty(requestPrototype, k, {
148
- value: function() {
149
- return this[getRequestCache]()[k]();
150
- }
151
- });
326
+ ["clone", "formData"].forEach((k) => {
327
+ Object.defineProperty(requestPrototype, k, { value: function() {
328
+ if (this[bodyConsumedDirectlyKey]) {
329
+ if (k === "clone") throw newBodyUnusableError();
330
+ return rejectBodyUnusable();
331
+ }
332
+ return this[getRequestCache]()[k]();
333
+ } });
152
334
  });
153
- Object.defineProperty(requestPrototype, /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), {
154
- value: function(depth, options, inspectFn) {
155
- const props = {
156
- method: this.method,
157
- url: this.url,
158
- headers: this.headers,
159
- nativeRequest: this[requestCache]
160
- };
161
- return `Request (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
162
- }
163
- });
164
- Object.setPrototypeOf(requestPrototype, Request2.prototype);
335
+ Object.defineProperty(requestPrototype, "text", { value: function() {
336
+ return readBodyWithFastPath(this, "text", (buf) => textDecoder.decode(buf));
337
+ } });
338
+ Object.defineProperty(requestPrototype, "arrayBuffer", { value: function() {
339
+ return readBodyWithFastPath(this, "arrayBuffer", (buf) => toArrayBuffer(buf));
340
+ } });
341
+ Object.defineProperty(requestPrototype, "blob", { value: function() {
342
+ return readBodyWithFastPath(this, "blob", (buf, request) => {
343
+ const type = contentType(request);
344
+ const init = type ? { headers: { "content-type": type } } : void 0;
345
+ return new Response(buf, init).blob();
346
+ });
347
+ } });
348
+ Object.defineProperty(requestPrototype, "json", { value: function() {
349
+ if (this[bodyConsumedDirectlyKey]) return rejectBodyUnusable();
350
+ return this.text().then(JSON.parse);
351
+ } });
352
+ Object.defineProperty(requestPrototype, /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) {
353
+ return `Request (lightweight) ${inspectFn({
354
+ method: this.method,
355
+ url: this.url,
356
+ headers: this.headers,
357
+ nativeRequest: this[requestCache]
358
+ }, {
359
+ ...options,
360
+ depth: depth == null ? null : depth - 1
361
+ })}`;
362
+ } });
363
+ Object.setPrototypeOf(requestPrototype, Request$1.prototype);
165
364
  var newRequest = (incoming, defaultHostname) => {
166
365
  const req = Object.create(requestPrototype);
167
366
  req[incomingKey] = incoming;
367
+ req[methodKey] = normalizeIncomingMethod(incoming.method);
168
368
  const incomingUrl = incoming.url || "";
169
- if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL.
170
- (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
171
- if (incoming instanceof Http2ServerRequest) {
172
- throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
173
- }
369
+ if (incomingUrl[0] !== "/" && (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
370
+ if (incoming instanceof Http2ServerRequest) throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
174
371
  try {
175
- const url2 = new URL(incomingUrl);
176
- req[urlKey] = url2.href;
372
+ req[urlKey] = new URL(incomingUrl).href;
177
373
  } catch (e) {
178
374
  throw new RequestError("Invalid absolute URL", { cause: e });
179
375
  }
180
376
  return req;
181
377
  }
182
378
  const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
183
- if (!host) {
184
- throw new RequestError("Missing host header");
185
- }
379
+ if (!host) throw new RequestError("Missing host header");
186
380
  let scheme;
187
381
  if (incoming instanceof Http2ServerRequest) {
188
382
  scheme = incoming.scheme;
189
- if (!(scheme === "http" || scheme === "https")) {
190
- throw new RequestError("Unsupported scheme");
191
- }
192
- } else {
193
- scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
194
- }
195
- const url = new URL(`${scheme}://${host}${incomingUrl}`);
196
- if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
197
- throw new RequestError("Invalid host header");
383
+ if (!(scheme === "http" || scheme === "https")) throw new RequestError("Unsupported scheme");
384
+ } else scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
385
+ try {
386
+ req[urlKey] = buildUrl(scheme, host, incomingUrl);
387
+ } catch (e) {
388
+ if (e instanceof RequestError) throw e;
389
+ else throw new RequestError("Invalid URL", { cause: e });
198
390
  }
199
- req[urlKey] = url.href;
200
391
  return req;
201
392
  };
393
+ var defaultContentType = "text/plain; charset=UTF-8";
202
394
  var responseCache = /* @__PURE__ */ Symbol("responseCache");
203
395
  var getResponseCache = /* @__PURE__ */ Symbol("getResponseCache");
204
396
  var cacheKey = /* @__PURE__ */ Symbol("cache");
205
397
  var GlobalResponse = global.Response;
206
- var Response2 = class _Response {
398
+ var Response$1 = class Response$12 {
207
399
  #body;
208
400
  #init;
209
401
  [getResponseCache]() {
402
+ const cache = this[cacheKey];
403
+ const liveHeaders = cache && cache[2] instanceof Headers ? cache[2] : void 0;
210
404
  delete this[cacheKey];
211
- return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
405
+ return this[responseCache] ||= new GlobalResponse(this.#body, liveHeaders ? {
406
+ ...this.#init,
407
+ headers: liveHeaders
408
+ } : this.#init);
212
409
  }
213
410
  constructor(body, init) {
214
411
  let headers;
215
412
  this.#body = body;
216
- if (init instanceof _Response) {
413
+ if (init instanceof Response$12) {
217
414
  const cachedGlobalResponse = init[responseCache];
218
415
  if (cachedGlobalResponse) {
219
416
  this.#init = cachedGlobalResponse;
@@ -221,23 +418,19 @@ var Response2 = class _Response {
221
418
  return;
222
419
  } else {
223
420
  this.#init = init.#init;
224
- headers = new Headers(init.#init.headers);
421
+ headers = new Headers(init.headers);
225
422
  }
226
- } else {
227
- this.#init = init;
228
- }
229
- if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
230
- this[cacheKey] = [init?.status || 200, body, headers || init?.headers];
231
- }
423
+ } else this.#init = init;
424
+ if (body == null || typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) this[cacheKey] = [
425
+ init?.status || 200,
426
+ body ?? null,
427
+ headers || init?.headers
428
+ ];
232
429
  }
233
430
  get headers() {
234
431
  const cache = this[cacheKey];
235
432
  if (cache) {
236
- if (!(cache[2] instanceof Headers)) {
237
- cache[2] = new Headers(
238
- cache[2] || { "content-type": "text/plain; charset=UTF-8" }
239
- );
240
- }
433
+ if (!(cache[2] instanceof Headers)) cache[2] = new Headers(cache[2] || (cache[1] === null ? void 0 : { "content-type": defaultContentType }));
241
434
  return cache[2];
242
435
  }
243
436
  return this[getResponseCache]().headers;
@@ -250,33 +443,87 @@ var Response2 = class _Response {
250
443
  return status >= 200 && status < 300;
251
444
  }
252
445
  };
253
- ["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => {
254
- Object.defineProperty(Response2.prototype, k, {
255
- get() {
256
- return this[getResponseCache]()[k];
257
- }
258
- });
446
+ [
447
+ "body",
448
+ "bodyUsed",
449
+ "redirected",
450
+ "statusText",
451
+ "trailers",
452
+ "type",
453
+ "url"
454
+ ].forEach((k) => {
455
+ Object.defineProperty(Response$1.prototype, k, { get() {
456
+ return this[getResponseCache]()[k];
457
+ } });
259
458
  });
260
- ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
261
- Object.defineProperty(Response2.prototype, k, {
262
- value: function() {
263
- return this[getResponseCache]()[k]();
264
- }
265
- });
459
+ [
460
+ "arrayBuffer",
461
+ "blob",
462
+ "clone",
463
+ "formData",
464
+ "json",
465
+ "text"
466
+ ].forEach((k) => {
467
+ Object.defineProperty(Response$1.prototype, k, { value: function() {
468
+ return this[getResponseCache]()[k]();
469
+ } });
266
470
  });
267
- Object.defineProperty(Response2.prototype, /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), {
268
- value: function(depth, options, inspectFn) {
269
- const props = {
270
- status: this.status,
271
- headers: this.headers,
272
- ok: this.ok,
273
- nativeResponse: this[responseCache]
274
- };
275
- return `Response (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
276
- }
471
+ Object.defineProperty(Response$1.prototype, /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) {
472
+ return `Response (lightweight) ${inspectFn({
473
+ status: this.status,
474
+ headers: this.headers,
475
+ ok: this.ok,
476
+ nativeResponse: this[responseCache]
477
+ }, {
478
+ ...options,
479
+ depth: depth == null ? null : depth - 1
480
+ })}`;
481
+ } });
482
+ Object.setPrototypeOf(Response$1, GlobalResponse);
483
+ Object.setPrototypeOf(Response$1.prototype, GlobalResponse.prototype);
484
+ var validRedirectUrl = /^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/;
485
+ var parseRedirectUrl = (url) => {
486
+ if (url instanceof URL) return url.href;
487
+ if (validRedirectUrl.test(url)) return url;
488
+ return new URL(url).href;
489
+ };
490
+ var validRedirectStatuses = /* @__PURE__ */ new Set([
491
+ 301,
492
+ 302,
493
+ 303,
494
+ 307,
495
+ 308
496
+ ]);
497
+ Object.defineProperty(Response$1, "redirect", {
498
+ value: function redirect(url, status = 302) {
499
+ if (!validRedirectStatuses.has(status)) throw new RangeError("Invalid status code");
500
+ return new Response$1(null, {
501
+ status,
502
+ headers: { location: parseRedirectUrl(url) }
503
+ });
504
+ },
505
+ writable: true,
506
+ configurable: true
507
+ });
508
+ Object.defineProperty(Response$1, "json", {
509
+ value: function json(data, init) {
510
+ const body = JSON.stringify(data);
511
+ if (body === void 0) throw new TypeError("The data is not JSON serializable");
512
+ const initHeaders = init?.headers;
513
+ let headers;
514
+ if (initHeaders) {
515
+ headers = new Headers(initHeaders);
516
+ if (!headers.has("content-type")) headers.set("content-type", "application/json");
517
+ } else headers = { "content-type": "application/json" };
518
+ return new Response$1(body, {
519
+ status: init?.status ?? 200,
520
+ statusText: init?.statusText,
521
+ headers
522
+ });
523
+ },
524
+ writable: true,
525
+ configurable: true
277
526
  });
278
- Object.setPrototypeOf(Response2, GlobalResponse);
279
- Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
280
527
  async function readWithoutBlocking(readPromise) {
281
528
  return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
282
529
  }
@@ -293,71 +540,48 @@ function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromi
293
540
  writable.off("error", cancel);
294
541
  });
295
542
  function handleStreamError(error) {
296
- if (error) {
297
- writable.destroy(error);
298
- }
543
+ if (error) writable.destroy(error);
299
544
  }
300
545
  function onDrain() {
301
546
  reader.read().then(flow, handleStreamError);
302
547
  }
303
548
  function flow({ done, value }) {
304
549
  try {
305
- if (done) {
306
- writable.end();
307
- } else if (!writable.write(value)) {
308
- writable.once("drain", onDrain);
309
- } else {
310
- return reader.read().then(flow, handleStreamError);
311
- }
550
+ if (done) writable.end();
551
+ else if (!writable.write(value)) writable.once("drain", onDrain);
552
+ else return reader.read().then(flow, handleStreamError);
312
553
  } catch (e) {
313
554
  handleStreamError(e);
314
555
  }
315
556
  }
316
557
  }
317
558
  function writeFromReadableStream(stream, writable) {
318
- if (stream.locked) {
319
- throw new TypeError("ReadableStream is locked.");
320
- } else if (writable.destroyed) {
321
- return;
322
- }
559
+ if (stream.locked) throw new TypeError("ReadableStream is locked.");
560
+ else if (writable.destroyed) return;
323
561
  return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
324
562
  }
325
- var buildOutgoingHttpHeaders = (headers) => {
563
+ var buildOutgoingHttpHeaders = (headers, defaultContentType2) => {
326
564
  const res = {};
327
- if (!(headers instanceof Headers)) {
328
- headers = new Headers(headers ?? void 0);
329
- }
330
- const cookies = [];
331
- for (const [k, v] of headers) {
332
- if (k === "set-cookie") {
333
- cookies.push(v);
334
- } else {
335
- res[k] = v;
336
- }
337
- }
338
- if (cookies.length > 0) {
339
- res["set-cookie"] = cookies;
340
- }
341
- res["content-type"] ??= "text/plain; charset=UTF-8";
565
+ if (!(headers instanceof Headers)) headers = new Headers(headers ?? void 0);
566
+ if (headers.has("set-cookie")) {
567
+ const cookies = [];
568
+ for (const [k, v] of headers) if (k === "set-cookie") cookies.push(v);
569
+ else res[k] = v;
570
+ if (cookies.length > 0) res["set-cookie"] = cookies;
571
+ } else for (const [k, v] of headers) res[k] = v;
572
+ if (defaultContentType2) res["content-type"] ??= defaultContentType2;
342
573
  return res;
343
574
  };
344
- var X_ALREADY_SENT = "x-hono-already-sent";
345
- if (typeof global.crypto === "undefined") {
346
- global.crypto = crypto;
347
- }
348
575
  var outgoingEnded = /* @__PURE__ */ Symbol("outgoingEnded");
349
576
  var incomingDraining = /* @__PURE__ */ Symbol("incomingDraining");
350
577
  var DRAIN_TIMEOUT_MS = 500;
351
578
  var MAX_DRAIN_BYTES = 64 * 1024 * 1024;
352
579
  var drainIncoming = (incoming) => {
353
580
  const incomingWithDrainState = incoming;
354
- if (incoming.destroyed || incomingWithDrainState[incomingDraining]) {
355
- return;
356
- }
581
+ if (incoming.destroyed || incomingWithDrainState[incomingDraining]) return;
357
582
  incomingWithDrainState[incomingDraining] = true;
358
583
  if (incoming instanceof Http2ServerRequest) {
359
584
  try {
360
- ;
361
585
  incoming.stream?.close?.(constants.NGHTTP2_NO_ERROR);
362
586
  } catch {
363
587
  }
@@ -373,110 +597,119 @@ var drainIncoming = (incoming) => {
373
597
  const forceClose = () => {
374
598
  cleanup();
375
599
  const socket = incoming.socket;
376
- if (socket && !socket.destroyed) {
377
- socket.destroySoon();
378
- }
600
+ if (socket && !socket.destroyed) socket.destroySoon();
379
601
  };
380
602
  const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);
381
603
  timer.unref?.();
382
604
  const onData = (chunk) => {
383
605
  bytesRead += chunk.length;
384
- if (bytesRead > MAX_DRAIN_BYTES) {
385
- forceClose();
386
- }
606
+ if (bytesRead > MAX_DRAIN_BYTES) forceClose();
387
607
  };
388
608
  incoming.on("data", onData);
389
609
  incoming.on("end", cleanup);
390
610
  incoming.on("error", cleanup);
391
611
  incoming.resume();
392
612
  };
393
- var handleRequestError = () => new Response(null, {
394
- status: 400
395
- });
396
- var handleFetchError = (e) => new Response(null, {
397
- status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500
398
- });
613
+ var makeCloseHandler = (req, incoming, outgoing, needsBodyCleanup) => () => {
614
+ if (incoming.errored) req[abortRequest](incoming.errored.toString());
615
+ else if (!outgoing.writableFinished) req[abortRequest]("Client connection prematurely closed.");
616
+ if (needsBodyCleanup && !incoming.readableEnded) setTimeout(() => {
617
+ if (!incoming.readableEnded) setTimeout(() => {
618
+ drainIncoming(incoming);
619
+ });
620
+ });
621
+ };
622
+ var isImmediateCacheableResponse = (res) => {
623
+ if (!(cacheKey in res)) return false;
624
+ const body = res[cacheKey][1];
625
+ return body === null || typeof body === "string" || body instanceof Uint8Array;
626
+ };
627
+ var handleRequestError = () => new Response(null, { status: 400 });
628
+ var handleFetchError = (e) => new Response(null, { status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500 });
399
629
  var handleResponseError = (e, outgoing) => {
400
630
  const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
401
- if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
402
- console.info("The user aborted a request.");
403
- } else {
631
+ if (err.code === "ERR_STREAM_PREMATURE_CLOSE") console.info("The user aborted a request.");
632
+ else {
404
633
  console.error(e);
405
- if (!outgoing.headersSent) {
406
- outgoing.writeHead(500, { "Content-Type": "text/plain" });
407
- }
634
+ if (!outgoing.headersSent) outgoing.writeHead(500, { "Content-Type": "text/plain" });
408
635
  outgoing.end(`Error: ${err.message}`);
409
636
  outgoing.destroy(err);
410
637
  }
411
638
  };
412
639
  var flushHeaders = (outgoing) => {
413
- if ("flushHeaders" in outgoing && outgoing.writable) {
414
- outgoing.flushHeaders();
415
- }
640
+ if ("flushHeaders" in outgoing && outgoing.writable) outgoing.flushHeaders();
416
641
  };
417
642
  var responseViaCache = async (res, outgoing) => {
418
643
  let [status, body, header] = res[cacheKey];
419
- let hasContentLength = false;
420
644
  if (!header) {
421
- header = { "content-type": "text/plain; charset=UTF-8" };
422
- } else if (header instanceof Headers) {
645
+ if (body === null) {
646
+ outgoing.writeHead(status);
647
+ outgoing.end();
648
+ } else if (typeof body === "string") {
649
+ outgoing.writeHead(status, {
650
+ "Content-Type": defaultContentType,
651
+ "Content-Length": Buffer.byteLength(body)
652
+ });
653
+ outgoing.end(body);
654
+ } else if (body instanceof Uint8Array) {
655
+ outgoing.writeHead(status, {
656
+ "Content-Type": defaultContentType,
657
+ "Content-Length": body.byteLength
658
+ });
659
+ outgoing.end(body);
660
+ } else if (body instanceof Blob) {
661
+ outgoing.writeHead(status, {
662
+ "Content-Type": defaultContentType,
663
+ "Content-Length": body.size
664
+ });
665
+ outgoing.end(new Uint8Array(await body.arrayBuffer()));
666
+ } else {
667
+ outgoing.writeHead(status, { "Content-Type": defaultContentType });
668
+ flushHeaders(outgoing);
669
+ await writeFromReadableStream(body, outgoing)?.catch((e) => handleResponseError(e, outgoing));
670
+ }
671
+ outgoing[outgoingEnded]?.();
672
+ return;
673
+ }
674
+ let hasContentLength = false;
675
+ if (header instanceof Headers) {
423
676
  hasContentLength = header.has("content-length");
424
- header = buildOutgoingHttpHeaders(header);
677
+ header = buildOutgoingHttpHeaders(header, body === null ? void 0 : defaultContentType);
425
678
  } else if (Array.isArray(header)) {
426
679
  const headerObj = new Headers(header);
427
680
  hasContentLength = headerObj.has("content-length");
428
- header = buildOutgoingHttpHeaders(headerObj);
429
- } else {
430
- for (const key in header) {
431
- if (key.length === 14 && key.toLowerCase() === "content-length") {
432
- hasContentLength = true;
433
- break;
434
- }
435
- }
681
+ header = buildOutgoingHttpHeaders(headerObj, body === null ? void 0 : defaultContentType);
682
+ } else for (const key in header) if (key.length === 14 && key.toLowerCase() === "content-length") {
683
+ hasContentLength = true;
684
+ break;
436
685
  }
437
686
  if (!hasContentLength) {
438
- if (typeof body === "string") {
439
- header["Content-Length"] = Buffer.byteLength(body);
440
- } else if (body instanceof Uint8Array) {
441
- header["Content-Length"] = body.byteLength;
442
- } else if (body instanceof Blob) {
443
- header["Content-Length"] = body.size;
444
- }
687
+ if (typeof body === "string") header["Content-Length"] = Buffer.byteLength(body);
688
+ else if (body instanceof Uint8Array) header["Content-Length"] = body.byteLength;
689
+ else if (body instanceof Blob) header["Content-Length"] = body.size;
445
690
  }
446
691
  outgoing.writeHead(status, header);
447
- if (typeof body === "string" || body instanceof Uint8Array) {
448
- outgoing.end(body);
449
- } else if (body instanceof Blob) {
450
- outgoing.end(new Uint8Array(await body.arrayBuffer()));
451
- } else {
692
+ if (body == null) outgoing.end();
693
+ else if (typeof body === "string" || body instanceof Uint8Array) outgoing.end(body);
694
+ else if (body instanceof Blob) outgoing.end(new Uint8Array(await body.arrayBuffer()));
695
+ else {
452
696
  flushHeaders(outgoing);
453
- await writeFromReadableStream(body, outgoing)?.catch(
454
- (e) => handleResponseError(e, outgoing)
455
- );
697
+ await writeFromReadableStream(body, outgoing)?.catch((e) => handleResponseError(e, outgoing));
456
698
  }
457
699
  outgoing[outgoingEnded]?.();
458
700
  };
459
701
  var isPromise = (res) => typeof res.then === "function";
460
702
  var responseViaResponseObject = async (res, outgoing, options = {}) => {
461
- if (isPromise(res)) {
462
- if (options.errorHandler) {
463
- try {
464
- res = await res;
465
- } catch (err) {
466
- const errRes = await options.errorHandler(err);
467
- if (!errRes) {
468
- return;
469
- }
470
- res = errRes;
471
- }
472
- } else {
473
- res = await res.catch(handleFetchError);
474
- }
475
- }
476
- if (cacheKey in res) {
477
- return responseViaCache(res, outgoing);
703
+ if (isPromise(res)) if (options.errorHandler) try {
704
+ res = await res;
705
+ } catch (err) {
706
+ const errRes = await options.errorHandler(err);
707
+ if (!errRes) return;
708
+ res = errRes;
478
709
  }
479
- const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
710
+ else res = await res.catch(handleFetchError);
711
+ if (cacheKey in res) return responseViaCache(res, outgoing);
712
+ const resHeaderRecord = buildOutgoingHttpHeaders(res.headers, res.body === null ? void 0 : defaultContentType);
480
713
  if (res.body) {
481
714
  const reader = res.body.getReader();
482
715
  const values = [];
@@ -499,28 +732,21 @@ var responseViaResponseObject = async (res, outgoing, options = {}) => {
499
732
  break;
500
733
  }
501
734
  currentReadPromise = void 0;
502
- if (chunk.value) {
503
- values.push(chunk.value);
504
- }
735
+ if (chunk.value) values.push(chunk.value);
505
736
  if (chunk.done) {
506
737
  done = true;
507
738
  break;
508
739
  }
509
740
  }
510
- if (done && !("content-length" in resHeaderRecord)) {
511
- resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
512
- }
741
+ if (done && !("content-length" in resHeaderRecord)) resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
513
742
  }
514
743
  outgoing.writeHead(res.status, resHeaderRecord);
515
744
  values.forEach((value) => {
516
745
  outgoing.write(value);
517
746
  });
518
- if (done) {
519
- outgoing.end();
520
- } else {
521
- if (values.length === 0) {
522
- flushHeaders(outgoing);
523
- }
747
+ if (done) outgoing.end();
748
+ else {
749
+ if (values.length === 0) flushHeaders(outgoing);
524
750
  await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
525
751
  }
526
752
  } else if (resHeaderRecord[X_ALREADY_SENT]) ; else {
@@ -531,83 +757,52 @@ var responseViaResponseObject = async (res, outgoing, options = {}) => {
531
757
  };
532
758
  var getRequestListener = (fetchCallback, options = {}) => {
533
759
  const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
534
- if (options.overrideGlobalObjects !== false && global.Request !== Request2) {
535
- Object.defineProperty(global, "Request", {
536
- value: Request2
537
- });
538
- Object.defineProperty(global, "Response", {
539
- value: Response2
540
- });
760
+ if (options.overrideGlobalObjects !== false && global.Request !== Request$1) {
761
+ Object.defineProperty(global, "Request", { value: Request$1 });
762
+ Object.defineProperty(global, "Response", { value: Response$1 });
541
763
  }
542
764
  return async (incoming, outgoing) => {
543
765
  let res, req;
766
+ let needsBodyCleanup = false;
767
+ let closeHandlerAttached = false;
768
+ const ensureCloseHandler = () => {
769
+ if (!req || closeHandlerAttached) return;
770
+ closeHandlerAttached = true;
771
+ outgoing.on("close", makeCloseHandler(req, incoming, outgoing, needsBodyCleanup));
772
+ };
544
773
  try {
545
774
  req = newRequest(incoming, options.hostname);
546
- let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
547
- if (!incomingEnded) {
548
- ;
775
+ needsBodyCleanup = autoCleanupIncoming && !(incoming.method === "GET" || incoming.method === "HEAD");
776
+ if (needsBodyCleanup) {
549
777
  incoming[wrapBodyStream] = true;
550
- incoming.on("end", () => {
551
- incomingEnded = true;
552
- });
553
- if (incoming instanceof Http2ServerRequest) {
554
- ;
555
- outgoing[outgoingEnded] = () => {
556
- if (!incomingEnded) {
557
- setTimeout(() => {
558
- if (!incomingEnded) {
559
- setTimeout(() => {
560
- drainIncoming(incoming);
561
- });
562
- }
563
- });
564
- }
565
- };
566
- }
567
- outgoing.on("finish", () => {
568
- if (!incomingEnded) {
569
- drainIncoming(incoming);
570
- }
571
- });
572
- }
573
- outgoing.on("close", () => {
574
- const abortController = req[abortControllerKey];
575
- if (abortController) {
576
- if (incoming.errored) {
577
- req[abortControllerKey].abort(incoming.errored.toString());
578
- } else if (!outgoing.writableFinished) {
579
- req[abortControllerKey].abort("Client connection prematurely closed.");
580
- }
581
- }
582
- if (!incomingEnded) {
583
- setTimeout(() => {
584
- if (!incomingEnded) {
585
- setTimeout(() => {
586
- drainIncoming(incoming);
587
- });
588
- }
778
+ if (incoming instanceof Http2ServerRequest) outgoing[outgoingEnded] = () => {
779
+ if (!incoming.readableEnded) setTimeout(() => {
780
+ if (!incoming.readableEnded) setTimeout(() => {
781
+ incoming.destroy();
782
+ outgoing.destroy();
783
+ });
589
784
  });
590
- }
785
+ };
786
+ }
787
+ res = fetchCallback(req, {
788
+ incoming,
789
+ outgoing
591
790
  });
592
- res = fetchCallback(req, { incoming, outgoing });
593
- if (cacheKey in res) {
791
+ if (!isPromise(res) && isImmediateCacheableResponse(res)) {
792
+ if (needsBodyCleanup && !incoming.readableEnded) outgoing.once("finish", () => {
793
+ if (!incoming.readableEnded) drainIncoming(incoming);
794
+ });
594
795
  return responseViaCache(res, outgoing);
595
796
  }
797
+ ensureCloseHandler();
596
798
  } catch (e) {
597
- if (!res) {
598
- if (options.errorHandler) {
599
- res = await options.errorHandler(req ? e : toRequestError(e));
600
- if (!res) {
601
- return;
602
- }
603
- } else if (!req) {
604
- res = handleRequestError();
605
- } else {
606
- res = handleFetchError(e);
607
- }
608
- } else {
609
- return handleResponseError(e, outgoing);
610
- }
799
+ if (!res) if (options.errorHandler) {
800
+ ensureCloseHandler();
801
+ res = await options.errorHandler(req ? e : toRequestError(e));
802
+ if (!res) return;
803
+ } else if (!req) res = handleRequestError();
804
+ else res = handleFetchError(e);
805
+ else return handleResponseError(e, outgoing);
611
806
  }
612
807
  try {
613
808
  return await responseViaResponseObject(res, outgoing, options);
@@ -616,6 +811,108 @@ var getRequestListener = (fetchCallback, options = {}) => {
616
811
  }
617
812
  };
618
813
  };
814
+ var CONNECTION_SYMBOL_KEY = /* @__PURE__ */ Symbol("CONNECTION_SYMBOL_KEY");
815
+ var WAIT_FOR_WEBSOCKET_SYMBOL = /* @__PURE__ */ Symbol("WAIT_FOR_WEBSOCKET_SYMBOL");
816
+ var responseHeadersToSkip = /* @__PURE__ */ new Set([
817
+ "connection",
818
+ "content-length",
819
+ "keep-alive",
820
+ "proxy-authenticate",
821
+ "proxy-authorization",
822
+ "te",
823
+ "trailer",
824
+ "transfer-encoding",
825
+ "upgrade",
826
+ "sec-websocket-accept",
827
+ "sec-websocket-extensions",
828
+ "sec-websocket-protocol"
829
+ ]);
830
+ var appendResponseHeaders = (headers, responseHeaders) => {
831
+ if (!responseHeaders) return;
832
+ responseHeaders.forEach((value, key) => {
833
+ if (responseHeadersToSkip.has(key.toLowerCase())) return;
834
+ headers.push(`${key}: ${value}`);
835
+ });
836
+ };
837
+ var rejectUpgradeRequest = (socket, status, responseHeaders) => {
838
+ const responseLines = ["Connection: close", "Content-Length: 0"];
839
+ appendResponseHeaders(responseLines, responseHeaders);
840
+ socket.end(`HTTP/1.1 ${status.toString()} ${STATUS_CODES[status] ?? ""}\r
841
+ ${responseLines.join("\r\n")}\r
842
+ \r
843
+ `);
844
+ };
845
+ var createUpgradeRequest = (request) => {
846
+ const protocol = request.socket.encrypted ? "https" : "http";
847
+ const url = new URL(request.url ?? "/", `${protocol}://${request.headers.host ?? "localhost"}`);
848
+ const headers = new Headers();
849
+ for (const key in request.headers) {
850
+ const value = request.headers[key];
851
+ if (!value) continue;
852
+ headers.append(key, Array.isArray(value) ? value[0] : value);
853
+ }
854
+ return new Request(url, { headers });
855
+ };
856
+ var setupWebSocket = (options) => {
857
+ const { server, fetchCallback, wss } = options;
858
+ const waiterMap = /* @__PURE__ */ new Map();
859
+ wss.on("connection", (ws, request) => {
860
+ const waiter = waiterMap.get(request);
861
+ if (waiter) {
862
+ waiter.resolve(ws);
863
+ waiterMap.delete(request);
864
+ }
865
+ });
866
+ const waitForWebSocket = (request, connectionSymbol) => {
867
+ return new Promise((resolve2) => {
868
+ waiterMap.set(request, {
869
+ resolve: resolve2,
870
+ connectionSymbol
871
+ });
872
+ });
873
+ };
874
+ server.on("upgrade", async (request, socket, head) => {
875
+ if (request.headers.upgrade?.toLowerCase() !== "websocket") return;
876
+ const env = {
877
+ incoming: request,
878
+ outgoing: void 0,
879
+ wss,
880
+ [WAIT_FOR_WEBSOCKET_SYMBOL]: waitForWebSocket
881
+ };
882
+ let status = 400;
883
+ let responseHeaders;
884
+ try {
885
+ const response = await fetchCallback(createUpgradeRequest(request), env);
886
+ if (response instanceof Response) {
887
+ status = response.status;
888
+ responseHeaders = response.headers;
889
+ }
890
+ } catch {
891
+ if (server.listenerCount("upgrade") === 1) rejectUpgradeRequest(socket, 500);
892
+ return;
893
+ }
894
+ const waiter = waiterMap.get(request);
895
+ if (!waiter || waiter.connectionSymbol !== env[CONNECTION_SYMBOL_KEY]) {
896
+ waiterMap.delete(request);
897
+ if (server.listenerCount("upgrade") === 1) rejectUpgradeRequest(socket, status, responseHeaders);
898
+ return;
899
+ }
900
+ const addResponseHeaders = (headers) => {
901
+ appendResponseHeaders(headers, responseHeaders);
902
+ };
903
+ wss.on("headers", addResponseHeaders);
904
+ try {
905
+ wss.handleUpgrade(request, socket, head, (ws) => {
906
+ wss.emit("connection", ws, request);
907
+ });
908
+ } finally {
909
+ wss.off("headers", addResponseHeaders);
910
+ }
911
+ });
912
+ server.on("close", () => {
913
+ wss.close();
914
+ });
915
+ };
619
916
  var createAdaptorServer = (options) => {
620
917
  const fetchCallback = options.fetch;
621
918
  const requestListener = getRequestListener(fetchCallback, {
@@ -623,8 +920,15 @@ var createAdaptorServer = (options) => {
623
920
  overrideGlobalObjects: options.overrideGlobalObjects,
624
921
  autoCleanupIncoming: options.autoCleanupIncoming
625
922
  });
626
- const createServer$1 = options.createServer || createServer;
627
- const server = createServer$1(options.serverOptions || {}, requestListener);
923
+ const server = (options.createServer || createServer)(options.serverOptions || {}, requestListener);
924
+ if (options.websocket && options.websocket.server) {
925
+ if (options.websocket.server.options.noServer !== true) throw new Error("WebSocket server must be created with { noServer: true } option");
926
+ setupWebSocket({
927
+ server,
928
+ fetchCallback,
929
+ wss: options.websocket.server
930
+ });
931
+ }
628
932
  return server;
629
933
  };
630
934
  var serve = (options, listeningListener) => {
@@ -636,7 +940,7 @@ var serve = (options, listeningListener) => {
636
940
  return server;
637
941
  };
638
942
 
639
- // ../node_modules/.bun/hono@4.12.22/node_modules/hono/dist/compose.js
943
+ // ../node_modules/.bun/hono@4.12.25/node_modules/hono/dist/compose.js
640
944
  var compose = (middleware, onError, onNotFound) => {
641
945
  return (context, next) => {
642
946
  let index = -1;
@@ -680,15 +984,15 @@ var compose = (middleware, onError, onNotFound) => {
680
984
  };
681
985
  };
682
986
 
683
- // ../node_modules/.bun/hono@4.12.22/node_modules/hono/dist/request/constants.js
987
+ // ../node_modules/.bun/hono@4.12.25/node_modules/hono/dist/request/constants.js
684
988
  var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
685
989
 
686
- // ../node_modules/.bun/hono@4.12.22/node_modules/hono/dist/utils/body.js
990
+ // ../node_modules/.bun/hono@4.12.25/node_modules/hono/dist/utils/body.js
687
991
  var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
688
992
  const { all = false, dot = false } = options;
689
993
  const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;
690
- const contentType = headers.get("Content-Type");
691
- if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) {
994
+ const contentType2 = headers.get("Content-Type");
995
+ if (contentType2?.startsWith("multipart/form-data") || contentType2?.startsWith("application/x-www-form-urlencoded")) {
692
996
  return parseFormData(request, { all, dot });
693
997
  }
694
998
  return {};
@@ -754,7 +1058,7 @@ var handleParsingNestedValues = (form, key, value) => {
754
1058
  });
755
1059
  };
756
1060
 
757
- // ../node_modules/.bun/hono@4.12.22/node_modules/hono/dist/utils/url.js
1061
+ // ../node_modules/.bun/hono@4.12.25/node_modules/hono/dist/utils/url.js
758
1062
  var splitPath = (path) => {
759
1063
  const paths = path.split("/");
760
1064
  if (paths[0] === "") {
@@ -957,7 +1261,7 @@ var getQueryParams = (url, key) => {
957
1261
  };
958
1262
  var decodeURIComponent_ = decodeURIComponent;
959
1263
 
960
- // ../node_modules/.bun/hono@4.12.22/node_modules/hono/dist/request.js
1264
+ // ../node_modules/.bun/hono@4.12.25/node_modules/hono/dist/request.js
961
1265
  var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);
962
1266
  var HonoRequest = class {
963
1267
  /**
@@ -1240,7 +1544,7 @@ var HonoRequest = class {
1240
1544
  }
1241
1545
  };
1242
1546
 
1243
- // ../node_modules/.bun/hono@4.12.22/node_modules/hono/dist/utils/html.js
1547
+ // ../node_modules/.bun/hono@4.12.25/node_modules/hono/dist/utils/html.js
1244
1548
  var HtmlEscapedCallbackPhase = {
1245
1549
  Stringify: 1};
1246
1550
  var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
@@ -1271,11 +1575,11 @@ var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) =>
1271
1575
  }
1272
1576
  };
1273
1577
 
1274
- // ../node_modules/.bun/hono@4.12.22/node_modules/hono/dist/context.js
1578
+ // ../node_modules/.bun/hono@4.12.25/node_modules/hono/dist/context.js
1275
1579
  var TEXT_PLAIN = "text/plain; charset=UTF-8";
1276
- var setDefaultContentType = (contentType, headers) => {
1580
+ var setDefaultContentType = (contentType2, headers) => {
1277
1581
  return {
1278
- "Content-Type": contentType,
1582
+ "Content-Type": contentType2,
1279
1583
  ...headers
1280
1584
  };
1281
1585
  };
@@ -1678,7 +1982,7 @@ var Context = class {
1678
1982
  };
1679
1983
  };
1680
1984
 
1681
- // ../node_modules/.bun/hono@4.12.22/node_modules/hono/dist/router.js
1985
+ // ../node_modules/.bun/hono@4.12.25/node_modules/hono/dist/router.js
1682
1986
  var METHOD_NAME_ALL = "ALL";
1683
1987
  var METHOD_NAME_ALL_LOWERCASE = "all";
1684
1988
  var METHODS = ["get", "post", "put", "delete", "options", "patch"];
@@ -1686,10 +1990,10 @@ var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is
1686
1990
  var UnsupportedPathError = class extends Error {
1687
1991
  };
1688
1992
 
1689
- // ../node_modules/.bun/hono@4.12.22/node_modules/hono/dist/utils/constants.js
1993
+ // ../node_modules/.bun/hono@4.12.25/node_modules/hono/dist/utils/constants.js
1690
1994
  var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
1691
1995
 
1692
- // ../node_modules/.bun/hono@4.12.22/node_modules/hono/dist/hono-base.js
1996
+ // ../node_modules/.bun/hono@4.12.25/node_modules/hono/dist/hono-base.js
1693
1997
  var notFoundHandler = (c) => {
1694
1998
  return c.text("404 Not Found", 404);
1695
1999
  };
@@ -2065,7 +2369,7 @@ var Hono = class _Hono {
2065
2369
  };
2066
2370
  };
2067
2371
 
2068
- // ../node_modules/.bun/hono@4.12.22/node_modules/hono/dist/router/reg-exp-router/matcher.js
2372
+ // ../node_modules/.bun/hono@4.12.25/node_modules/hono/dist/router/reg-exp-router/matcher.js
2069
2373
  var emptyParam = [];
2070
2374
  function match(method, path) {
2071
2375
  const matchers = this.buildAllMatchers();
@@ -2086,7 +2390,7 @@ function match(method, path) {
2086
2390
  return match2(method, path);
2087
2391
  }
2088
2392
 
2089
- // ../node_modules/.bun/hono@4.12.22/node_modules/hono/dist/router/reg-exp-router/node.js
2393
+ // ../node_modules/.bun/hono@4.12.25/node_modules/hono/dist/router/reg-exp-router/node.js
2090
2394
  var LABEL_REG_EXP_STR = "[^/]+";
2091
2395
  var ONLY_WILDCARD_REG_EXP_STR = ".*";
2092
2396
  var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
@@ -2194,7 +2498,7 @@ var Node = class _Node {
2194
2498
  }
2195
2499
  };
2196
2500
 
2197
- // ../node_modules/.bun/hono@4.12.22/node_modules/hono/dist/router/reg-exp-router/trie.js
2501
+ // ../node_modules/.bun/hono@4.12.25/node_modules/hono/dist/router/reg-exp-router/trie.js
2198
2502
  var Trie = class {
2199
2503
  #context = { varIndex: 0 };
2200
2504
  #root = new Node();
@@ -2250,7 +2554,7 @@ var Trie = class {
2250
2554
  }
2251
2555
  };
2252
2556
 
2253
- // ../node_modules/.bun/hono@4.12.22/node_modules/hono/dist/router/reg-exp-router/router.js
2557
+ // ../node_modules/.bun/hono@4.12.25/node_modules/hono/dist/router/reg-exp-router/router.js
2254
2558
  var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
2255
2559
  var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
2256
2560
  function buildWildcardRegExp(path) {
@@ -2428,7 +2732,7 @@ var RegExpRouter = class {
2428
2732
  }
2429
2733
  };
2430
2734
 
2431
- // ../node_modules/.bun/hono@4.12.22/node_modules/hono/dist/router/smart-router/router.js
2735
+ // ../node_modules/.bun/hono@4.12.25/node_modules/hono/dist/router/smart-router/router.js
2432
2736
  var SmartRouter = class {
2433
2737
  name = "SmartRouter";
2434
2738
  #routers = [];
@@ -2483,7 +2787,7 @@ var SmartRouter = class {
2483
2787
  }
2484
2788
  };
2485
2789
 
2486
- // ../node_modules/.bun/hono@4.12.22/node_modules/hono/dist/router/trie-router/node.js
2790
+ // ../node_modules/.bun/hono@4.12.25/node_modules/hono/dist/router/trie-router/node.js
2487
2791
  var emptyParams = /* @__PURE__ */ Object.create(null);
2488
2792
  var hasChildren = (children) => {
2489
2793
  for (const _ in children) {
@@ -2658,7 +2962,7 @@ var Node2 = class _Node2 {
2658
2962
  }
2659
2963
  };
2660
2964
 
2661
- // ../node_modules/.bun/hono@4.12.22/node_modules/hono/dist/router/trie-router/router.js
2965
+ // ../node_modules/.bun/hono@4.12.25/node_modules/hono/dist/router/trie-router/router.js
2662
2966
  var TrieRouter = class {
2663
2967
  name = "TrieRouter";
2664
2968
  #node;
@@ -2680,7 +2984,7 @@ var TrieRouter = class {
2680
2984
  }
2681
2985
  };
2682
2986
 
2683
- // ../node_modules/.bun/hono@4.12.22/node_modules/hono/dist/hono.js
2987
+ // ../node_modules/.bun/hono@4.12.25/node_modules/hono/dist/hono.js
2684
2988
  var Hono2 = class extends Hono {
2685
2989
  /**
2686
2990
  * Creates an instance of the Hono class.