hono 4.13.2 → 4.13.4

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 (50) hide show
  1. package/dist/cjs/client/client.js +25 -11
  2. package/dist/cjs/client/utils.js +4 -1
  3. package/dist/cjs/context.js +4 -0
  4. package/dist/cjs/helper/accepts/accepts.js +36 -2
  5. package/dist/cjs/jsx/dom/render.js +2 -0
  6. package/dist/cjs/middleware/cors/index.js +1 -1
  7. package/dist/cjs/middleware/csrf/index.js +1 -1
  8. package/dist/cjs/middleware/etag/digest.js +1 -1
  9. package/dist/cjs/middleware/etag/index.js +3 -3
  10. package/dist/cjs/middleware/pretty-json/index.js +3 -1
  11. package/dist/cjs/request.js +8 -4
  12. package/dist/cjs/router/linear-router/router.js +7 -2
  13. package/dist/cjs/router/pattern-router/router.js +3 -9
  14. package/dist/cjs/router/reg-exp-router/node.js +10 -3
  15. package/dist/cjs/router/reg-exp-router/router.js +47 -83
  16. package/dist/cjs/router/reg-exp-router/trie.js +2 -1
  17. package/dist/cjs/router/trie-router/node.js +46 -69
  18. package/dist/cjs/router/trie-router/router.js +3 -11
  19. package/dist/cjs/router/utils.js +27 -0
  20. package/dist/cjs/utils/cookie.js +1 -1
  21. package/dist/cjs/utils/ipaddr.js +5 -3
  22. package/dist/cjs/utils/stream.js +7 -1
  23. package/dist/client/client.js +25 -11
  24. package/dist/client/utils.js +4 -1
  25. package/dist/context.js +4 -0
  26. package/dist/helper/accepts/accepts.js +36 -2
  27. package/dist/jsx/dom/render.js +2 -0
  28. package/dist/middleware/cors/index.js +1 -1
  29. package/dist/middleware/csrf/index.js +1 -1
  30. package/dist/middleware/etag/digest.js +1 -1
  31. package/dist/middleware/etag/index.js +3 -3
  32. package/dist/middleware/pretty-json/index.js +3 -1
  33. package/dist/request.js +8 -4
  34. package/dist/router/linear-router/router.js +7 -2
  35. package/dist/router/pattern-router/router.js +3 -9
  36. package/dist/router/reg-exp-router/node.js +6 -2
  37. package/dist/router/reg-exp-router/router.js +53 -84
  38. package/dist/router/reg-exp-router/trie.js +2 -1
  39. package/dist/router/trie-router/node.js +46 -69
  40. package/dist/router/trie-router/router.js +3 -11
  41. package/dist/router/utils.js +5 -0
  42. package/dist/types/context.d.ts +4 -0
  43. package/dist/types/router/reg-exp-router/node.d.ts +3 -0
  44. package/dist/types/router/trie-router/node.d.ts +1 -2
  45. package/dist/types/router/trie-router/router.d.ts +0 -1
  46. package/dist/types/router/utils.d.ts +1 -0
  47. package/dist/utils/cookie.js +1 -1
  48. package/dist/utils/ipaddr.js +5 -3
  49. package/dist/utils/stream.js +7 -1
  50. package/package.json +1 -1
@@ -22,77 +22,53 @@ __export(node_exports, {
22
22
  module.exports = __toCommonJS(node_exports);
23
23
  var import_router = require("../../router");
24
24
  var import_url = require("../../utils/url");
25
- const emptyParams = /* @__PURE__ */ Object.create(null);
26
- const hasChildren = (children) => {
27
- for (const _ in children) {
28
- return true;
29
- }
30
- return false;
31
- };
25
+ var import_utils = require("../utils");
26
+ const emptyParams = (0, import_utils.createNullObject)();
27
+ let order = 0;
32
28
  class Node {
33
- #methods;
34
- #children;
35
- #patterns;
36
- #order = 0;
29
+ #methods = [];
30
+ #children = (0, import_utils.createNullObject)();
31
+ #patterns = [];
32
+ #pattern;
37
33
  #params = emptyParams;
38
- constructor(method, handler, children) {
39
- this.#children = children || /* @__PURE__ */ Object.create(null);
40
- this.#methods = [];
41
- if (method && handler) {
42
- const m = /* @__PURE__ */ Object.create(null);
43
- m[method] = { handler, possibleKeys: [], score: 0 };
44
- this.#methods = [m];
45
- }
46
- this.#patterns = [];
47
- }
48
34
  insert(method, path, handler) {
49
- this.#order = ++this.#order;
50
35
  let curNode = this;
51
36
  const parts = (0, import_url.splitRoutingPath)(path);
52
- const possibleKeys = [];
53
- for (let i = 0, len = parts.length; i < len; i++) {
54
- const p = parts[i];
55
- const nextP = parts[i + 1];
56
- const pattern = (0, import_url.getPattern)(p, nextP);
57
- const key = Array.isArray(pattern) ? pattern[0] : p;
58
- if (key in curNode.#children) {
59
- curNode = curNode.#children[key];
60
- if (pattern) {
61
- possibleKeys.push(pattern[1]);
62
- }
63
- continue;
37
+ const possibleKeys = /* @__PURE__ */ new Set();
38
+ let i = 0;
39
+ for (const p of parts) {
40
+ const nextP = parts[++i];
41
+ const pattern = (0, import_url.getPattern)(p, nextP) || (nextP === void 0 && p && p.indexOf("*") === p.length - 1 ? p : null);
42
+ const isParam = Array.isArray(pattern);
43
+ const key = isParam ? pattern[0] : pattern || p;
44
+ const child = curNode.#children[key] ||= new Node();
45
+ if (pattern && !child.#pattern) {
46
+ child.#pattern = pattern;
47
+ curNode.#patterns.push(child);
64
48
  }
65
- curNode.#children[key] = new Node();
66
- if (pattern) {
67
- curNode.#patterns.push(pattern);
68
- possibleKeys.push(pattern[1]);
49
+ curNode = child;
50
+ if (isParam) {
51
+ possibleKeys.add(pattern[1]);
69
52
  }
70
- curNode = curNode.#children[key];
71
53
  }
72
54
  curNode.#methods.push({
73
55
  [method]: {
74
56
  handler,
75
- possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
76
- score: this.#order
57
+ possibleKeys: [...possibleKeys],
58
+ score: ++order
77
59
  }
78
60
  });
79
- return curNode;
80
61
  }
81
62
  #pushHandlerSets(handlerSets, node, method, nodeParams, params) {
82
63
  for (let i = 0, len = node.#methods.length; i < len; i++) {
83
64
  const m = node.#methods[i];
84
65
  const handlerSet = m[method] || m[import_router.METHOD_NAME_ALL];
85
- const processedSet = {};
86
- if (handlerSet !== void 0) {
87
- handlerSet.params = /* @__PURE__ */ Object.create(null);
66
+ if (handlerSet) {
67
+ handlerSet.params = (0, import_utils.createNullObject)();
88
68
  handlerSets.push(handlerSet);
89
- if (nodeParams !== emptyParams || params && params !== emptyParams) {
90
- for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) {
91
- const key = handlerSet.possibleKeys[i2];
92
- const processed = processedSet[handlerSet.score];
93
- handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];
94
- processedSet[handlerSet.score] = true;
95
- }
69
+ for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) {
70
+ const key = handlerSet.possibleKeys[i2];
71
+ handlerSet.params[key] = params?.[key] && !i2 ? params[key] : nodeParams[key] ?? params?.[key];
96
72
  }
97
73
  }
98
74
  }
@@ -124,33 +100,33 @@ class Node {
124
100
  tempNodes.push(nextNode);
125
101
  }
126
102
  }
127
- for (let k = 0, len3 = node.#patterns.length; k < len3; k++) {
128
- const pattern = node.#patterns[k];
103
+ for (const child of node.#patterns) {
104
+ const pattern = child.#pattern;
129
105
  const params = node.#params === emptyParams ? {} : { ...node.#params };
130
- if (pattern === "*") {
131
- const astNode = node.#children["*"];
132
- if (astNode) {
133
- this.#pushHandlerSets(handlerSets, astNode, method, node.#params);
134
- astNode.#params = params;
135
- tempNodes.push(astNode);
106
+ if (typeof pattern === "string") {
107
+ if (pattern === "*" || part.startsWith(pattern.slice(0, -1))) {
108
+ this.#pushHandlerSets(handlerSets, child, method, node.#params);
109
+ if (pattern === "*") {
110
+ child.#params = params;
111
+ tempNodes.push(child);
112
+ }
136
113
  }
137
114
  continue;
138
115
  }
139
- const [key, name, matcher] = pattern;
140
- if (!part && !(matcher instanceof RegExp)) {
116
+ const [, name, matcher] = pattern;
117
+ if (!part && matcher === true) {
141
118
  continue;
142
119
  }
143
- const child = node.#children[key];
144
- if (matcher instanceof RegExp) {
145
- if (partOffsets === null) {
146
- partOffsets = new Array(len);
120
+ if (matcher !== true) {
121
+ if (!partOffsets) {
122
+ partOffsets = [];
147
123
  let offset = path[0] === "/" ? 1 : 0;
148
124
  for (let p = 0; p < len; p++) {
149
125
  partOffsets[p] = offset;
150
126
  offset += parts[p].length + 1;
151
127
  }
152
128
  }
153
- const restPathString = path.substring(partOffsets[i]);
129
+ const restPathString = path.slice(partOffsets[i]);
154
130
  const m = matcher.exec(restPathString);
155
131
  if (m) {
156
132
  params[name] = m[0];
@@ -164,11 +140,12 @@ class Node {
164
140
  params
165
141
  );
166
142
  }
167
- if (hasChildren(child.#children)) {
143
+ for (const _ in child.#children) {
168
144
  child.#params = params;
169
145
  const componentCount = m[0].match(/\//g)?.length ?? 0;
170
146
  const targetCurNodes = curNodesQueue[componentCount] ||= [];
171
147
  targetCurNodes.push(child);
148
+ break;
172
149
  }
173
150
  continue;
174
151
  }
@@ -196,7 +173,7 @@ class Node {
196
173
  const shifted = curNodesQueue.shift();
197
174
  curNodes = shifted ? tempNodes.concat(shifted) : tempNodes;
198
175
  }
199
- if (handlerSets.length > 1) {
176
+ if (handlerSets[1]) {
200
177
  handlerSets.sort((a, b) => {
201
178
  return a.score - b.score;
202
179
  });
@@ -24,19 +24,11 @@ var import_url = require("../../utils/url");
24
24
  var import_node = require("./node");
25
25
  class TrieRouter {
26
26
  name = "TrieRouter";
27
- #node;
28
- constructor() {
29
- this.#node = new import_node.Node();
30
- }
27
+ #node = new import_node.Node();
31
28
  add(method, path, handler) {
32
- const results = (0, import_url.checkOptionalParameter)(path);
33
- if (results) {
34
- for (let i = 0, len = results.length; i < len; i++) {
35
- this.#node.insert(method, results[i], handler);
36
- }
37
- return;
29
+ for (const result of (0, import_url.checkOptionalParameter)(path) || [path]) {
30
+ this.#node.insert(method, result, handler);
38
31
  }
39
- this.#node.insert(method, path, handler);
40
32
  }
41
33
  match(method, path) {
42
34
  return this.#node.search(method, path);
@@ -0,0 +1,27 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+ var utils_exports = {};
19
+ __export(utils_exports, {
20
+ createNullObject: () => createNullObject
21
+ });
22
+ module.exports = __toCommonJS(utils_exports);
23
+ const createNullObject = () => /* @__PURE__ */ Object.create(null);
24
+ // Annotate the CommonJS export names for ESM import in node:
25
+ 0 && (module.exports = {
26
+ createNullObject
27
+ });
@@ -101,7 +101,7 @@ const parseSigned = async (cookie, secret, name) => {
101
101
  const secretKey = await getCryptoKey(secret);
102
102
  for (const [key, value] of Object.entries(parse(cookie, name))) {
103
103
  const signatureStartPos = value.lastIndexOf(".");
104
- if (signatureStartPos < 1) {
104
+ if (signatureStartPos < 0) {
105
105
  continue;
106
106
  }
107
107
  const signedValue = value.substring(0, signatureStartPos);
@@ -30,12 +30,14 @@ __export(ipaddr_exports, {
30
30
  module.exports = __toCommonJS(ipaddr_exports);
31
31
  const expandIPv6 = (ipV6) => {
32
32
  const sections = ipV6.split(":");
33
- if (IPV4_REGEX.test(sections.at(-1))) {
33
+ const lastSection = sections.at(-1);
34
+ if (IPV4_REGEX.test(lastSection)) {
35
+ const octets = lastSection.split(".").map(Number);
34
36
  sections.splice(
35
37
  -1,
36
38
  1,
37
- ...convertIPv6BinaryToString(convertIPv4ToBinary(sections.at(-1))).substring(2).split(":")
38
- // => ['7f00', '0001']
39
+ (octets[0] << 8 | octets[1]).toString(16),
40
+ (octets[2] << 8 | octets[3]).toString(16)
39
41
  );
40
42
  }
41
43
  for (let i = 0; i < sections.length; i++) {
@@ -96,7 +96,13 @@ class StreamingApi {
96
96
  abort() {
97
97
  if (!this.aborted) {
98
98
  this.aborted = true;
99
- this.abortSubscribers.forEach((subscriber) => subscriber());
99
+ this.abortSubscribers.forEach((subscriber) => {
100
+ try {
101
+ void Promise.resolve(subscriber()).catch(() => {
102
+ });
103
+ } catch {
104
+ }
105
+ });
100
106
  }
101
107
  }
102
108
  }
@@ -26,6 +26,10 @@ var createProxy = (callback, path) => {
26
26
  });
27
27
  return proxy;
28
28
  };
29
+ var appendQueryParams = (url, searchParams) => {
30
+ const queryString = searchParams.toString();
31
+ return queryString ? `${url}?${queryString}` : url;
32
+ };
29
33
  var ClientRequestImpl = class {
30
34
  url;
31
35
  method;
@@ -52,6 +56,9 @@ var ClientRequestImpl = class {
52
56
  }
53
57
  if (Array.isArray(v)) {
54
58
  for (const v2 of v) {
59
+ if (v2 === void 0) {
60
+ continue;
61
+ }
55
62
  form.append(k, v2);
56
63
  }
57
64
  } else {
@@ -76,19 +83,29 @@ var ClientRequestImpl = class {
76
83
  if (args?.cookie) {
77
84
  const cookies = [];
78
85
  for (const [key, value] of Object.entries(args.cookie)) {
86
+ if (value === void 0) {
87
+ continue;
88
+ }
79
89
  cookies.push(serialize(key, value));
80
90
  }
81
- headerValues["Cookie"] = cookies.join("; ");
91
+ if (cookies.length > 0) {
92
+ headerValues["Cookie"] = cookies.join("; ");
93
+ }
82
94
  }
83
95
  if (this.cType) {
84
96
  headerValues["Content-Type"] = this.cType;
85
97
  }
86
- const headers = new Headers(headerValues ?? void 0);
98
+ const headers = new Headers();
99
+ for (const [key, value] of Object.entries(headerValues)) {
100
+ if (value !== void 0) {
101
+ headers.set(key, value);
102
+ }
103
+ }
87
104
  let url = this.url;
88
105
  url = removeIndexString(url);
89
106
  url = replaceUrlParam(url, this.pathParams);
90
107
  if (this.queryParams) {
91
- url = url + "?" + this.queryParams.toString();
108
+ url = appendQueryParams(url, this.queryParams);
92
109
  }
93
110
  methodUpperCase = this.method.toUpperCase();
94
111
  const setBody = !(methodUpperCase === "GET" || methodUpperCase === "HEAD");
@@ -132,7 +149,7 @@ var hc = (baseUrl, options) => createProxy(function proxyCallback(opts) {
132
149
  result = replaceUrlParam(url, opts.args[0].param);
133
150
  }
134
151
  if (opts.args[0].query) {
135
- result = result + "?" + buildSearchParamsOption(opts.args[0].query).toString();
152
+ result = appendQueryParams(result, buildSearchParamsOption(opts.args[0].query));
136
153
  }
137
154
  }
138
155
  result = removeIndexString(result);
@@ -143,18 +160,15 @@ var hc = (baseUrl, options) => createProxy(function proxyCallback(opts) {
143
160
  }
144
161
  if (method === "ws") {
145
162
  const webSocketUrl = replaceUrlProtocol(
146
- opts.args[0] && opts.args[0].param ? replaceUrlParam(url, opts.args[0].param) : url,
163
+ opts.args[0]?.param ? replaceUrlParam(url, opts.args[0].param) : url,
147
164
  "ws"
148
165
  );
149
166
  const targetUrl = new URL(webSocketUrl);
150
167
  const queryParams = opts.args[0]?.query;
151
168
  if (queryParams) {
152
- Object.entries(queryParams).forEach(([key, value]) => {
153
- if (Array.isArray(value)) {
154
- value.forEach((item) => targetUrl.searchParams.append(key, item));
155
- } else {
156
- targetUrl.searchParams.set(key, value);
157
- }
169
+ const searchParams = buildSearchParamsOption(queryParams);
170
+ searchParams.forEach((value, key) => {
171
+ targetUrl.searchParams.append(key, value);
158
172
  });
159
173
  }
160
174
  const establishWebSocket = (...args) => {
@@ -9,7 +9,7 @@ var mergePath = (base, path) => {
9
9
  var replaceUrlParam = (urlString, params) => {
10
10
  for (const [k, v] of Object.entries(params)) {
11
11
  const reg = new RegExp("/:" + k + "(?:{[^/]+})?\\??(?=/|$)");
12
- urlString = urlString.replace(reg, v ? `/${v}` : "");
12
+ urlString = urlString.replace(reg, () => v ? `/${v}` : "");
13
13
  }
14
14
  return urlString;
15
15
  };
@@ -21,6 +21,9 @@ var buildSearchParams = (query) => {
21
21
  }
22
22
  if (Array.isArray(v)) {
23
23
  for (const v2 of v) {
24
+ if (v2 === void 0) {
25
+ continue;
26
+ }
24
27
  searchParams.append(k, v2);
25
28
  }
26
29
  } else {
package/dist/context.js CHANGED
@@ -202,6 +202,10 @@ var Context = class {
202
202
  * c.header('X-Message', 'Hello!')
203
203
  * c.header('Content-Type', 'text/plain')
204
204
  *
205
+ * // Append multiple headers using the append option (e.g. Vary)
206
+ * c.header('Vary', 'Accept-Encoding', { append: true })
207
+ * c.header('Vary', 'User-Agent', { append: true })
208
+ *
205
209
  * return c.body('Thank you for coming')
206
210
  * })
207
211
  * ```
@@ -1,9 +1,43 @@
1
1
  // src/helper/accepts/accepts.ts
2
2
  import { parseAccept } from "../../utils/accept.js";
3
+ var matchType = (acceptType, supportedType) => {
4
+ if (acceptType === supportedType) {
5
+ return true;
6
+ }
7
+ if (acceptType === "*/*" || acceptType === "*") {
8
+ return false;
9
+ }
10
+ if (acceptType.endsWith("/*")) {
11
+ const [acceptMain] = acceptType.split("/");
12
+ const [supportedMain] = supportedType.split("/");
13
+ return acceptMain === supportedMain;
14
+ }
15
+ return false;
16
+ };
17
+ var getSpecificity = (type) => {
18
+ if (type === "*/*" || type === "*") {
19
+ return 1;
20
+ }
21
+ if (type.endsWith("/*")) {
22
+ return 2;
23
+ }
24
+ return 3;
25
+ };
3
26
  var defaultMatch = (accepts2, config) => {
4
27
  const { supports, default: defaultSupport } = config;
5
- const accept = accepts2.sort((a, b) => b.q - a.q).find((accept2) => supports.includes(accept2.type));
6
- return accept ? accept.type : defaultSupport;
28
+ const sortedAccepts = accepts2.slice().sort((a, b) => {
29
+ if (b.q !== a.q) {
30
+ return b.q - a.q;
31
+ }
32
+ return getSpecificity(b.type) - getSpecificity(a.type);
33
+ });
34
+ for (const accept of sortedAccepts) {
35
+ const matched = supports.find((supported) => matchType(accept.type, supported));
36
+ if (matched) {
37
+ return matched;
38
+ }
39
+ }
40
+ return defaultSupport;
7
41
  };
8
42
  var accepts = (c, options) => {
9
43
  const acceptHeader = c.req.header(options.header);
@@ -78,6 +78,7 @@ var applyProps = (container, attributes, oldAttributes) => {
78
78
  } else if (key === "dangerouslySetInnerHTML" && value) {
79
79
  container.innerHTML = value.__html;
80
80
  } else if (key === "ref") {
81
+ refCleanupMap.get(container)?.();
81
82
  let cleanup;
82
83
  if (typeof value === "function") {
83
84
  cleanup = value(container) || (() => value(null));
@@ -142,6 +143,7 @@ var applyProps = (container, attributes, oldAttributes) => {
142
143
  container.removeEventListener(eventSpec[0], value, eventSpec[1]);
143
144
  } else if (key === "ref") {
144
145
  refCleanupMap.get(container)?.();
146
+ refCleanupMap.delete(container);
145
147
  } else {
146
148
  try {
147
149
  container.removeAttribute(toAttributeName(container, key));
@@ -48,7 +48,7 @@ var cors = (options) => {
48
48
  }
49
49
  if (c.req.method === "OPTIONS") {
50
50
  if (opts.origin !== "*") {
51
- set("Vary", "Origin");
51
+ c.res.headers.append("Vary", "Origin");
52
52
  }
53
53
  if (opts.maxAge != null) {
54
54
  set("Access-Control-Max-Age", opts.maxAge.toString());
@@ -2,7 +2,7 @@
2
2
  import { HTTPException } from "../../http-exception.js";
3
3
  var secFetchSiteValues = ["same-origin", "same-site", "none", "cross-site"];
4
4
  var isSecFetchSite = (value) => secFetchSiteValues.includes(value);
5
- var isSafeMethodRe = /^(GET|HEAD)$/;
5
+ var isSafeMethodRe = /^(GET|HEAD|OPTIONS)$/;
6
6
  var isRequestedByFormElementRe = /^\b(application\/x-www-form-urlencoded|multipart\/form-data|text\/plain)\b/i;
7
7
  var csrf = (options) => {
8
8
  const originHandler = ((optsOrigin) => {
@@ -38,7 +38,7 @@ var generateDigest = async (stream, generator) => {
38
38
  const requiredLength = chunkLength + remaining;
39
39
  if (requiredLength < CHUNK_SIZE) {
40
40
  if (!chunk) {
41
- chunk = value.subarray(offset);
41
+ chunk = value.slice(offset);
42
42
  } else {
43
43
  if (chunk.byteLength < requiredLength) {
44
44
  const nextChunk = new Uint8Array(
@@ -10,7 +10,7 @@ var RETAINED_304_HEADERS = [
10
10
  ];
11
11
  var stripWeak = (tag) => tag.replace(/^W\//, "");
12
12
  function etagMatches(etag2, ifNoneMatch) {
13
- return ifNoneMatch != null && ifNoneMatch.split(/,\s*/).some((t) => stripWeak(t) === stripWeak(etag2));
13
+ return ifNoneMatch != null && ifNoneMatch.split(",").some((t) => stripWeak(t.trim()) === stripWeak(etag2));
14
14
  }
15
15
  function initializeGenerator(generator) {
16
16
  if (!generator) {
@@ -60,11 +60,11 @@ var etag = (options) => {
60
60
  ETag: etag3
61
61
  }
62
62
  });
63
- c.res.headers.forEach((_, key) => {
63
+ for (const key of Array.from(c.res.headers.keys())) {
64
64
  if (retainedHeaders.indexOf(key.toLowerCase()) === -1) {
65
65
  c.res.headers.delete(key);
66
66
  }
67
- });
67
+ }
68
68
  } else {
69
69
  c.res.headers.set("ETag", etag3);
70
70
  }
@@ -1,10 +1,12 @@
1
1
  // src/middleware/pretty-json/index.ts
2
+ var jsonContentTypeRegex = /^application\/(?:[a-z0-9._-]+\+)?json(?=$|[;\s])/i;
2
3
  var prettyJSON = (options) => {
3
4
  const targetQuery = options?.query ?? "pretty";
4
5
  return async function prettyJSON2(c, next) {
5
6
  const pretty = options?.force || c.req.query(targetQuery) || c.req.query(targetQuery) === "";
6
7
  await next();
7
- if (pretty && c.res.headers.get("Content-Type")?.startsWith("application/json")) {
8
+ const contentType = c.res.headers.get("Content-Type");
9
+ if (pretty && contentType && jsonContentTypeRegex.test(contentType)) {
8
10
  const obj = await c.res.json();
9
11
  c.res = new Response(JSON.stringify(obj, null, options?.space ?? 2), c.res);
10
12
  }
package/dist/request.js CHANGED
@@ -46,13 +46,13 @@ var HonoRequest = class {
46
46
  return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
47
47
  }
48
48
  #getDecodedParam(key) {
49
- const paramKey = this.#matchResult[0][this.routeIndex][1][key];
49
+ const paramKey = this.#matchResult[0][this.routeIndex]?.[1][key];
50
50
  const param = this.#getParamValue(paramKey);
51
51
  return param && tryDecodeURIComponent(param);
52
52
  }
53
53
  #getAllDecodedParams() {
54
54
  const decoded = {};
55
- const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
55
+ const keys = Object.keys(this.#matchResult[0][this.routeIndex]?.[1] ?? {});
56
56
  for (const key of keys) {
57
57
  const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
58
58
  if (value !== void 0) {
@@ -292,10 +292,14 @@ var cloneRawRequest = async (req) => {
292
292
  message: "Cannot clone request: body was already consumed and not cached. Please use HonoRequest methods (e.g., req.json(), req.text()) instead of consuming req.raw directly."
293
293
  });
294
294
  }
295
- const body = await req[cacheKey]();
295
+ let body = await req[cacheKey]();
296
296
  const headers = req.header();
297
- if (body instanceof FormData) {
297
+ if (cacheKey === "json") {
298
+ body = JSON.stringify(body);
299
+ delete headers["content-length"];
300
+ } else if (body instanceof FormData) {
298
301
  delete headers["content-type"];
302
+ delete headers["content-length"];
299
303
  }
300
304
  const requestInit = {
301
305
  body,
@@ -29,7 +29,8 @@ var LinearRouter = class {
29
29
  }
30
30
  } else if (hasStar && !hasLabel) {
31
31
  const endsWithStar = routePath.charCodeAt(routePath.length - 1) === 42;
32
- const parts = (endsWithStar ? routePath.slice(0, -2) : routePath).split(splitByStarRe);
32
+ const endsWithSlashStar = routePath.endsWith("/*");
33
+ const parts = (endsWithStar ? routePath.slice(0, endsWithSlashStar ? -2 : -1) : routePath).split(splitByStarRe);
33
34
  const lastIndex = parts.length - 1;
34
35
  for (let j = 0, pos = 0, len2 = parts.length; j < len2; j++) {
35
36
  const part = parts[j];
@@ -39,7 +40,11 @@ var LinearRouter = class {
39
40
  }
40
41
  pos += part.length;
41
42
  if (j === lastIndex) {
42
- if (!endsWithStar && pos !== path.length && !(pos === path.length - 1 && path.charCodeAt(pos) === 47)) {
43
+ if (endsWithSlashStar) {
44
+ if (pos !== path.length && path.charCodeAt(pos) !== 47) {
45
+ continue ROUTES_LOOP;
46
+ }
47
+ } else if (!endsWithStar && pos !== path.length && !(pos === path.length - 1 && path.charCodeAt(pos) === 47)) {
43
48
  continue ROUTES_LOOP;
44
49
  }
45
50
  } else {
@@ -5,10 +5,8 @@ var PatternRouter = class {
5
5
  name = "PatternRouter";
6
6
  #routes = [];
7
7
  add(method, path, handler) {
8
- const endsWithWildcard = path.at(-1) === "*";
9
- if (endsWithWildcard) {
10
- path = path.slice(0, -2);
11
- }
8
+ const suffix = path.endsWith("/*") ? "(?:$|/)" : path.endsWith("*") ? "" : "/?$";
9
+ path = path.replace(/\*$/, "");
12
10
  if (path.at(-1) === "?") {
13
11
  path = path.slice(0, -1);
14
12
  this.add(method, path.replace(/\/[^/]+$/, ""), handler);
@@ -20,11 +18,7 @@ var PatternRouter = class {
20
18
  }
21
19
  );
22
20
  try {
23
- this.#routes.push([
24
- new RegExp(`^${parts.join("")}${endsWithWildcard ? "" : "/?$"}`),
25
- method,
26
- handler
27
- ]);
21
+ this.#routes.push([new RegExp(`^${parts.join("")}${suffix}`), method, handler]);
28
22
  } catch {
29
23
  throw new UnsupportedPathError();
30
24
  }
@@ -1,4 +1,5 @@
1
1
  // src/router/reg-exp-router/node.ts
2
+ import { createNullObject } from "../utils.js";
2
3
  var LABEL_REG_EXP_STR = "[^/]+";
3
4
  var ONLY_WILDCARD_REG_EXP_STR = ".*";
4
5
  var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
@@ -27,7 +28,7 @@ var Node = class _Node {
27
28
  // handler index of a dynamic path, or -1 for a static path terminal
28
29
  #index;
29
30
  #varIndex;
30
- #children = /* @__PURE__ */ Object.create(null);
31
+ #children = createNullObject();
31
32
  insert(tokens, index, paramMap, context, isStatic) {
32
33
  let node = this;
33
34
  for (let i = 0, len = tokens.length; i < len; i++) {
@@ -105,6 +106,9 @@ var Node = class _Node {
105
106
  }
106
107
  };
107
108
  export {
109
+ LABEL_REG_EXP_STR,
108
110
  Node,
109
- PATH_ERROR
111
+ ONLY_WILDCARD_REG_EXP_STR,
112
+ PATH_ERROR,
113
+ TAIL_WILDCARD_REG_EXP_STR
110
114
  };