hono 4.7.11 → 4.8.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 (65) hide show
  1. package/dist/adapter/cloudflare-pages/handler.js +2 -1
  2. package/dist/adapter/service-worker/index.js +6 -0
  3. package/dist/cjs/adapter/cloudflare-pages/handler.js +2 -1
  4. package/dist/cjs/adapter/service-worker/index.js +7 -0
  5. package/dist/cjs/context.js +48 -116
  6. package/dist/cjs/helper/route/index.js +69 -0
  7. package/dist/cjs/helper/ssg/ssg.js +47 -8
  8. package/dist/cjs/helper/testing/index.js +2 -2
  9. package/dist/cjs/hono-base.js +1 -1
  10. package/dist/cjs/jsx/components.js +4 -1
  11. package/dist/cjs/jsx/streaming.js +6 -1
  12. package/dist/cjs/middleware/cache/index.js +5 -1
  13. package/dist/cjs/middleware/cors/index.js +12 -2
  14. package/dist/cjs/middleware/jwk/jwk.js +6 -1
  15. package/dist/cjs/middleware/jwt/jwt.js +2 -1
  16. package/dist/cjs/middleware/logger/index.js +6 -6
  17. package/dist/cjs/request/constants.js +28 -0
  18. package/dist/cjs/request.js +4 -0
  19. package/dist/cjs/router/trie-router/node.js +11 -13
  20. package/dist/cjs/utils/body.js +5 -1
  21. package/dist/cjs/utils/color.js +15 -2
  22. package/dist/cjs/utils/jwt/jwt.js +5 -6
  23. package/dist/cjs/utils/mime.js +1 -0
  24. package/dist/cjs/utils/url.js +5 -2
  25. package/dist/context.js +48 -116
  26. package/dist/helper/route/index.js +43 -0
  27. package/dist/helper/ssg/ssg.js +46 -8
  28. package/dist/helper/testing/index.js +2 -2
  29. package/dist/hono-base.js +1 -1
  30. package/dist/jsx/components.js +4 -1
  31. package/dist/jsx/streaming.js +5 -1
  32. package/dist/middleware/cache/index.js +5 -1
  33. package/dist/middleware/cors/index.js +12 -2
  34. package/dist/middleware/jwk/jwk.js +6 -1
  35. package/dist/middleware/jwt/jwt.js +2 -1
  36. package/dist/middleware/logger/index.js +7 -7
  37. package/dist/request/constants.js +5 -0
  38. package/dist/request.js +4 -0
  39. package/dist/router/trie-router/node.js +11 -13
  40. package/dist/types/adapter/cloudflare-pages/handler.d.ts +1 -0
  41. package/dist/types/adapter/service-worker/handler.d.ts +4 -3
  42. package/dist/types/adapter/service-worker/index.d.ts +23 -1
  43. package/dist/types/context.d.ts +5 -1
  44. package/dist/types/helper/route/index.d.ts +67 -0
  45. package/dist/types/helper/ssg/ssg.d.ts +9 -2
  46. package/dist/types/helper/testing/index.d.ts +2 -2
  47. package/dist/types/hono-base.d.ts +10 -0
  48. package/dist/types/jsx/streaming.d.ts +16 -1
  49. package/dist/types/middleware/cache/index.d.ts +3 -0
  50. package/dist/types/middleware/cors/index.d.ts +2 -2
  51. package/dist/types/middleware/jwk/jwk.d.ts +10 -7
  52. package/dist/types/middleware/jwt/jwt.d.ts +3 -0
  53. package/dist/types/request/constants.d.ts +1 -0
  54. package/dist/types/request.d.ts +8 -0
  55. package/dist/types/types.d.ts +1 -0
  56. package/dist/types/utils/color.d.ts +9 -0
  57. package/dist/types/utils/jwt/index.d.ts +1 -1
  58. package/dist/types/utils/jwt/jwt.d.ts +1 -1
  59. package/dist/types/utils/mime.d.ts +1 -0
  60. package/dist/utils/body.js +5 -1
  61. package/dist/utils/color.js +7 -1
  62. package/dist/utils/jwt/jwt.js +5 -6
  63. package/dist/utils/mime.js +1 -0
  64. package/dist/utils/url.js +5 -2
  65. package/package.json +9 -1
@@ -7,7 +7,8 @@ var handle = (app) => (eventContext) => {
7
7
  { ...eventContext.env, eventContext },
8
8
  {
9
9
  waitUntil: eventContext.waitUntil,
10
- passThroughOnException: eventContext.passThroughOnException
10
+ passThroughOnException: eventContext.passThroughOnException,
11
+ props: {}
11
12
  }
12
13
  );
13
14
  };
@@ -1,5 +1,11 @@
1
1
  // src/adapter/service-worker/index.ts
2
2
  import { handle } from "./handler.js";
3
+ var fire = (app, options = {
4
+ fetch: void 0
5
+ }) => {
6
+ addEventListener("fetch", handle(app, options));
7
+ };
3
8
  export {
9
+ fire,
4
10
  handle
5
11
  };
@@ -31,7 +31,8 @@ const handle = (app) => (eventContext) => {
31
31
  { ...eventContext.env, eventContext },
32
32
  {
33
33
  waitUntil: eventContext.waitUntil,
34
- passThroughOnException: eventContext.passThroughOnException
34
+ passThroughOnException: eventContext.passThroughOnException,
35
+ props: {}
35
36
  }
36
37
  );
37
38
  };
@@ -18,11 +18,18 @@ var __copyProps = (to, from, except, desc) => {
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
19
  var service_worker_exports = {};
20
20
  __export(service_worker_exports, {
21
+ fire: () => fire,
21
22
  handle: () => import_handler.handle
22
23
  });
23
24
  module.exports = __toCommonJS(service_worker_exports);
24
25
  var import_handler = require("./handler");
26
+ const fire = (app, options = {
27
+ fetch: void 0
28
+ }) => {
29
+ addEventListener("fetch", (0, import_handler.handle)(app, options));
30
+ };
25
31
  // Annotate the CommonJS export names for ESM import in node:
26
32
  0 && (module.exports = {
33
+ fire,
27
34
  handle
28
35
  });
@@ -25,11 +25,11 @@ module.exports = __toCommonJS(context_exports);
25
25
  var import_request = require("./request");
26
26
  var import_html = require("./utils/html");
27
27
  const TEXT_PLAIN = "text/plain; charset=UTF-8";
28
- const setHeaders = (headers, map = {}) => {
29
- for (const key of Object.keys(map)) {
30
- headers.set(key, map[key]);
31
- }
32
- return headers;
28
+ const setDefaultContentType = (contentType, headers) => {
29
+ return {
30
+ "Content-Type": contentType,
31
+ ...headers
32
+ };
33
33
  };
34
34
  class Context {
35
35
  #rawRequest;
@@ -38,15 +38,13 @@ class Context {
38
38
  #var;
39
39
  finalized = false;
40
40
  error;
41
- #status = 200;
41
+ #status;
42
42
  #executionCtx;
43
- #headers;
44
- #preparedHeaders;
45
43
  #res;
46
- #isFresh = true;
47
44
  #layout;
48
45
  #renderer;
49
46
  #notFoundHandler;
47
+ #preparedHeaders;
50
48
  #matchResult;
51
49
  #path;
52
50
  constructor(req, options) {
@@ -78,11 +76,11 @@ class Context {
78
76
  }
79
77
  }
80
78
  get res() {
81
- this.#isFresh = false;
82
- return this.#res ||= new Response("404 Not Found", { status: 404 });
79
+ return this.#res ||= new Response(null, {
80
+ headers: this.#preparedHeaders ??= new Headers()
81
+ });
83
82
  }
84
83
  set res(_res) {
85
- this.#isFresh = false;
86
84
  if (this.#res && _res) {
87
85
  _res = new Response(_res.body, _res);
88
86
  for (const [k, v] of this.#res.headers.entries()) {
@@ -116,42 +114,16 @@ class Context {
116
114
  if (this.finalized) {
117
115
  this.#res = new Response(this.#res.body, this.#res);
118
116
  }
117
+ const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers();
119
118
  if (value === void 0) {
120
- if (this.#headers) {
121
- this.#headers.delete(name);
122
- } else if (this.#preparedHeaders) {
123
- delete this.#preparedHeaders[name.toLocaleLowerCase()];
124
- }
125
- if (this.finalized) {
126
- this.res.headers.delete(name);
127
- }
128
- return;
129
- }
130
- if (options?.append) {
131
- if (!this.#headers) {
132
- this.#isFresh = false;
133
- this.#headers = new Headers(this.#preparedHeaders);
134
- this.#preparedHeaders = {};
135
- }
136
- this.#headers.append(name, value);
119
+ headers.delete(name);
120
+ } else if (options?.append) {
121
+ headers.append(name, value);
137
122
  } else {
138
- if (this.#headers) {
139
- this.#headers.set(name, value);
140
- } else {
141
- this.#preparedHeaders ??= {};
142
- this.#preparedHeaders[name.toLowerCase()] = value;
143
- }
144
- }
145
- if (this.finalized) {
146
- if (options?.append) {
147
- this.res.headers.append(name, value);
148
- } else {
149
- this.res.headers.set(name, value);
150
- }
123
+ headers.set(name, value);
151
124
  }
152
125
  };
153
126
  status = (status) => {
154
- this.#isFresh = false;
155
127
  this.#status = status;
156
128
  };
157
129
  set = (key, value) => {
@@ -168,94 +140,54 @@ class Context {
168
140
  return Object.fromEntries(this.#var);
169
141
  }
170
142
  #newResponse(data, arg, headers) {
171
- if (this.#isFresh && !headers && !arg && this.#status === 200) {
172
- return new Response(data, {
173
- headers: this.#preparedHeaders
174
- });
175
- }
176
- if (arg && typeof arg !== "number") {
177
- const header = new Headers(arg.headers);
178
- if (this.#headers) {
179
- this.#headers.forEach((v, k) => {
180
- if (k === "set-cookie") {
181
- header.append(k, v);
182
- } else {
183
- header.set(k, v);
184
- }
185
- });
186
- }
187
- const headers2 = setHeaders(header, this.#preparedHeaders);
188
- return new Response(data, {
189
- headers: headers2,
190
- status: arg.status ?? this.#status
191
- });
192
- }
193
- const status = typeof arg === "number" ? arg : this.#status;
194
- this.#preparedHeaders ??= {};
195
- this.#headers ??= new Headers();
196
- setHeaders(this.#headers, this.#preparedHeaders);
197
- if (this.#res) {
198
- this.#res.headers.forEach((v, k) => {
199
- if (k === "set-cookie") {
200
- this.#headers?.append(k, v);
143
+ const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers();
144
+ if (typeof arg === "object" && "headers" in arg) {
145
+ const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);
146
+ for (const [key, value] of argHeaders) {
147
+ if (key.toLowerCase() === "set-cookie") {
148
+ responseHeaders.append(key, value);
201
149
  } else {
202
- this.#headers?.set(k, v);
150
+ responseHeaders.set(key, value);
203
151
  }
204
- });
205
- setHeaders(this.#headers, this.#preparedHeaders);
152
+ }
206
153
  }
207
- headers ??= {};
208
- for (const [k, v] of Object.entries(headers)) {
209
- if (typeof v === "string") {
210
- this.#headers.set(k, v);
211
- } else {
212
- this.#headers.delete(k);
213
- for (const v2 of v) {
214
- this.#headers.append(k, v2);
154
+ if (headers) {
155
+ for (const [k, v] of Object.entries(headers)) {
156
+ if (typeof v === "string") {
157
+ responseHeaders.set(k, v);
158
+ } else {
159
+ responseHeaders.delete(k);
160
+ for (const v2 of v) {
161
+ responseHeaders.append(k, v2);
162
+ }
215
163
  }
216
164
  }
217
165
  }
218
- return new Response(data, {
219
- status,
220
- headers: this.#headers
221
- });
166
+ const status = typeof arg === "number" ? arg : arg?.status ?? this.#status;
167
+ return new Response(data, { status, headers: responseHeaders });
222
168
  }
223
169
  newResponse = (...args) => this.#newResponse(...args);
224
- body = (data, arg, headers) => {
225
- return typeof arg === "number" ? this.#newResponse(data, arg, headers) : this.#newResponse(data, arg);
226
- };
170
+ body = (data, arg, headers) => this.#newResponse(data, arg, headers);
227
171
  text = (text, arg, headers) => {
228
- if (!this.#preparedHeaders) {
229
- if (this.#isFresh && !headers && !arg) {
230
- return new Response(text);
231
- }
232
- this.#preparedHeaders = {};
233
- }
234
- this.#preparedHeaders["content-type"] = TEXT_PLAIN;
235
- if (typeof arg === "number") {
236
- return this.#newResponse(text, arg, headers);
237
- }
238
- return this.#newResponse(text, arg);
172
+ return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(
173
+ text,
174
+ arg,
175
+ setDefaultContentType(TEXT_PLAIN, headers)
176
+ );
239
177
  };
240
178
  json = (object, arg, headers) => {
241
- const body = JSON.stringify(object);
242
- this.#preparedHeaders ??= {};
243
- this.#preparedHeaders["content-type"] = "application/json";
244
- return typeof arg === "number" ? this.#newResponse(body, arg, headers) : this.#newResponse(body, arg);
179
+ return this.#newResponse(
180
+ JSON.stringify(object),
181
+ arg,
182
+ setDefaultContentType("application/json", headers)
183
+ );
245
184
  };
246
185
  html = (html, arg, headers) => {
247
- this.#preparedHeaders ??= {};
248
- this.#preparedHeaders["content-type"] = "text/html; charset=UTF-8";
249
- if (typeof html === "object") {
250
- return (0, import_html.resolveCallback)(html, import_html.HtmlEscapedCallbackPhase.Stringify, false, {}).then((html2) => {
251
- return typeof arg === "number" ? this.#newResponse(html2, arg, headers) : this.#newResponse(html2, arg);
252
- });
253
- }
254
- return typeof arg === "number" ? this.#newResponse(html, arg, headers) : this.#newResponse(html, arg);
186
+ const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType("text/html; charset=UTF-8", headers));
187
+ return typeof html === "object" ? (0, import_html.resolveCallback)(html, import_html.HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);
255
188
  };
256
189
  redirect = (location, status) => {
257
- this.#headers ??= new Headers();
258
- this.#headers.set("Location", String(location));
190
+ this.header("Location", String(location));
259
191
  return this.newResponse(null, status ?? 302);
260
192
  };
261
193
  notFound = () => {
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var route_exports = {};
20
+ __export(route_exports, {
21
+ basePath: () => basePath,
22
+ baseRoutePath: () => baseRoutePath,
23
+ matchedRoutes: () => matchedRoutes,
24
+ routePath: () => routePath
25
+ });
26
+ module.exports = __toCommonJS(route_exports);
27
+ var import_constants = require("../../request/constants");
28
+ var import_url = require("../../utils/url");
29
+ const matchedRoutes = (c) => c.req[import_constants.GET_MATCH_RESULT][0].map(([[, route]]) => route);
30
+ const routePath = (c) => matchedRoutes(c)[c.req.routeIndex].path;
31
+ const baseRoutePath = (c) => matchedRoutes(c)[c.req.routeIndex].basePath;
32
+ const basePathCacheMap = /* @__PURE__ */ new WeakMap();
33
+ const basePath = (c) => {
34
+ const routeIndex = c.req.routeIndex;
35
+ const cache = basePathCacheMap.get(c) || [];
36
+ if (typeof cache[routeIndex] === "string") {
37
+ return cache[routeIndex];
38
+ }
39
+ let result;
40
+ const rp = baseRoutePath(c);
41
+ if (!/[:*]/.test(rp)) {
42
+ result = rp;
43
+ } else {
44
+ const paths = (0, import_url.splitRoutingPath)(rp);
45
+ const reqPath = c.req.path;
46
+ let basePathLength = 0;
47
+ for (let i = 0, len = paths.length; i < len; i++) {
48
+ const pattern = (0, import_url.getPattern)(paths[i], paths[i + 1]);
49
+ if (pattern) {
50
+ const re = pattern[2] === true || pattern === "*" ? /[^\/]+/ : pattern[2];
51
+ basePathLength += reqPath.substring(basePathLength + 1).match(re)?.[0].length || 0;
52
+ } else {
53
+ basePathLength += paths[i].length;
54
+ }
55
+ basePathLength += 1;
56
+ }
57
+ result = reqPath.substring(0, basePathLength);
58
+ }
59
+ cache[routeIndex] = result;
60
+ basePathCacheMap.set(c, cache);
61
+ return result;
62
+ };
63
+ // Annotate the CommonJS export names for ESM import in node:
64
+ 0 && (module.exports = {
65
+ basePath,
66
+ baseRoutePath,
67
+ matchedRoutes,
68
+ routePath
69
+ });
@@ -18,6 +18,7 @@ var __copyProps = (to, from, except, desc) => {
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
19
  var ssg_exports = {};
20
20
  __export(ssg_exports, {
21
+ DEFAULT_OUTPUT_DIR: () => DEFAULT_OUTPUT_DIR,
21
22
  combineAfterGenerateHooks: () => combineAfterGenerateHooks,
22
23
  combineAfterResponseHooks: () => combineAfterResponseHooks,
23
24
  combineBeforeRequestHooks: () => combineBeforeRequestHooks,
@@ -34,6 +35,7 @@ var import_middleware = require("./middleware");
34
35
  var import_utils2 = require("./utils");
35
36
  const DEFAULT_CONCURRENCY = 2;
36
37
  const DEFAULT_CONTENT_TYPE = "text/plain";
38
+ const DEFAULT_OUTPUT_DIR = "./static";
37
39
  const generateFilePath = (routePath, outDir, mimeType, extensionMap) => {
38
40
  const extension = determineExtension(mimeType, extensionMap);
39
41
  if (routePath.endsWith(`.${extension}`)) {
@@ -110,13 +112,13 @@ const combineAfterResponseHooks = (hooks) => {
110
112
  return currentRes;
111
113
  };
112
114
  };
113
- const combineAfterGenerateHooks = (hooks) => {
115
+ const combineAfterGenerateHooks = (hooks, fsModule, options) => {
114
116
  if (!Array.isArray(hooks)) {
115
117
  return hooks;
116
118
  }
117
119
  return async (result) => {
118
120
  for (const hook of hooks) {
119
- await hook(result);
121
+ await hook(result, fsModule, options);
120
122
  }
121
123
  };
122
124
  };
@@ -218,14 +220,50 @@ const toSSG = async (app, fs, options) => {
218
220
  let result;
219
221
  const getInfoPromises = [];
220
222
  const savePromises = [];
223
+ const plugins = options?.plugins || [];
224
+ const beforeRequestHooks = [];
225
+ const afterResponseHooks = [];
226
+ const afterGenerateHooks = [];
227
+ if (options?.beforeRequestHook) {
228
+ beforeRequestHooks.push(
229
+ ...Array.isArray(options.beforeRequestHook) ? options.beforeRequestHook : [options.beforeRequestHook]
230
+ );
231
+ }
232
+ if (options?.afterResponseHook) {
233
+ afterResponseHooks.push(
234
+ ...Array.isArray(options.afterResponseHook) ? options.afterResponseHook : [options.afterResponseHook]
235
+ );
236
+ }
237
+ if (options?.afterGenerateHook) {
238
+ afterGenerateHooks.push(
239
+ ...Array.isArray(options.afterGenerateHook) ? options.afterGenerateHook : [options.afterGenerateHook]
240
+ );
241
+ }
242
+ for (const plugin of plugins) {
243
+ if (plugin.beforeRequestHook) {
244
+ beforeRequestHooks.push(
245
+ ...Array.isArray(plugin.beforeRequestHook) ? plugin.beforeRequestHook : [plugin.beforeRequestHook]
246
+ );
247
+ }
248
+ if (plugin.afterResponseHook) {
249
+ afterResponseHooks.push(
250
+ ...Array.isArray(plugin.afterResponseHook) ? plugin.afterResponseHook : [plugin.afterResponseHook]
251
+ );
252
+ }
253
+ if (plugin.afterGenerateHook) {
254
+ afterGenerateHooks.push(
255
+ ...Array.isArray(plugin.afterGenerateHook) ? plugin.afterGenerateHook : [plugin.afterGenerateHook]
256
+ );
257
+ }
258
+ }
221
259
  try {
222
- const outputDir = options?.dir ?? "./static";
260
+ const outputDir = options?.dir ?? DEFAULT_OUTPUT_DIR;
223
261
  const concurrency = options?.concurrency ?? DEFAULT_CONCURRENCY;
224
262
  const combinedBeforeRequestHook = combineBeforeRequestHooks(
225
- options?.beforeRequestHook || ((req) => req)
263
+ beforeRequestHooks.length > 0 ? beforeRequestHooks : [(req) => req]
226
264
  );
227
265
  const combinedAfterResponseHook = combineAfterResponseHooks(
228
- options?.afterResponseHook || ((req) => req)
266
+ afterResponseHooks.length > 0 ? afterResponseHooks : [(req) => req]
229
267
  );
230
268
  const getInfoGen = fetchRoutesContent(
231
269
  app,
@@ -262,14 +300,15 @@ const toSSG = async (app, fs, options) => {
262
300
  const errorObj = error instanceof Error ? error : new Error(String(error));
263
301
  result = { success: false, files: [], error: errorObj };
264
302
  }
265
- if (options?.afterGenerateHook) {
266
- const combinedAfterGenerateHooks = combineAfterGenerateHooks(options?.afterGenerateHook);
267
- await combinedAfterGenerateHooks(result);
303
+ if (afterGenerateHooks.length > 0) {
304
+ const combinedAfterGenerateHooks = combineAfterGenerateHooks(afterGenerateHooks, fs, options);
305
+ await combinedAfterGenerateHooks(result, fs, options);
268
306
  }
269
307
  return result;
270
308
  };
271
309
  // Annotate the CommonJS export names for ESM import in node:
272
310
  0 && (module.exports = {
311
+ DEFAULT_OUTPUT_DIR,
273
312
  combineAfterGenerateHooks,
274
313
  combineAfterResponseHooks,
275
314
  combineBeforeRequestHooks,
@@ -22,11 +22,11 @@ __export(testing_exports, {
22
22
  });
23
23
  module.exports = __toCommonJS(testing_exports);
24
24
  var import_client = require("../../client");
25
- const testClient = (app, Env, executionCtx) => {
25
+ const testClient = (app, Env, executionCtx, options) => {
26
26
  const customFetch = (input, init) => {
27
27
  return app.request(input, init, Env, executionCtx);
28
28
  };
29
- return (0, import_client.hc)("http://localhost", { fetch: customFetch });
29
+ return (0, import_client.hc)("http://localhost", { ...options, fetch: customFetch });
30
30
  };
31
31
  // Annotate the CommonJS export names for ESM import in node:
32
32
  0 && (module.exports = {
@@ -181,7 +181,7 @@ class Hono {
181
181
  #addRoute(method, path, handler) {
182
182
  method = method.toUpperCase();
183
183
  path = (0, import_url.mergePath)(this._basePath, path);
184
- const r = { path, method, handler };
184
+ const r = { basePath: this._basePath, path, method, handler };
185
185
  this.router.add(method, path, [handler, r]);
186
186
  this.routes.push(r);
187
187
  }
@@ -25,7 +25,9 @@ module.exports = __toCommonJS(components_exports);
25
25
  var import_html = require("../helper/html");
26
26
  var import_html2 = require("../utils/html");
27
27
  var import_constants = require("./constants");
28
+ var import_context = require("./context");
28
29
  var import_components = require("./dom/components");
30
+ var import_streaming = require("./streaming");
29
31
  let errorBoundaryCounter = 0;
30
32
  const childrenToString = async (children) => {
31
33
  try {
@@ -46,6 +48,7 @@ const ErrorBoundary = async ({ children, fallback, fallbackRender, onError }) =>
46
48
  if (!Array.isArray(children)) {
47
49
  children = [children];
48
50
  }
51
+ const nonce = (0, import_context.useContext)(import_streaming.StreamingContext)?.scriptNonce;
49
52
  let fallbackStr;
50
53
  const fallbackRes = (error) => {
51
54
  onError?.(error);
@@ -102,7 +105,7 @@ d.replaceWith(c.content)
102
105
  }
103
106
  htmlArray = htmlArray.flat();
104
107
  const content = htmlArray.join("");
105
- let html = buffer ? "" : `<template data-hono-target="E:${index}">${content}</template><script>
108
+ let html = buffer ? "" : `<template data-hono-target="E:${index}">${content}</template><script${nonce ? ` nonce="${nonce}"` : ""}>
106
109
  ((d,c) => {
107
110
  c=d.currentScript.previousSibling
108
111
  d=d.getElementById('E:${index}')
@@ -18,6 +18,7 @@ var __copyProps = (to, from, except, desc) => {
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
19
  var streaming_exports = {};
20
20
  __export(streaming_exports, {
21
+ StreamingContext: () => StreamingContext,
21
22
  Suspense: () => Suspense,
22
23
  renderToReadableStream: () => renderToReadableStream
23
24
  });
@@ -27,8 +28,10 @@ var import_html2 = require("../utils/html");
27
28
  var import_base = require("./base");
28
29
  var import_components = require("./components");
29
30
  var import_constants = require("./constants");
31
+ var import_context = require("./context");
30
32
  var import_components2 = require("./dom/components");
31
33
  var import_render = require("./dom/render");
34
+ const StreamingContext = (0, import_context.createContext)(null);
32
35
  let suspenseCounter = 0;
33
36
  const Suspense = async ({
34
37
  children,
@@ -40,6 +43,7 @@ const Suspense = async ({
40
43
  if (!Array.isArray(children)) {
41
44
  children = [children];
42
45
  }
46
+ const nonce = (0, import_context.useContext)(StreamingContext)?.scriptNonce;
43
47
  let resArray = [];
44
48
  const stackNode = { [import_constants.DOM_STASH]: [0, []] };
45
49
  const popNodeStack = (value) => {
@@ -85,7 +89,7 @@ const Suspense = async ({
85
89
  content
86
90
  );
87
91
  }
88
- let html = buffer ? "" : `<template data-hono-target="H:${index}">${content}</template><script>
92
+ let html = buffer ? "" : `<template data-hono-target="H:${index}">${content}</template><script${nonce ? ` nonce="${nonce}"` : ""}>
89
93
  ((d,c,n) => {
90
94
  c=d.currentScript.previousSibling
91
95
  d=d.getElementById('H:${index}')
@@ -161,6 +165,7 @@ const renderToReadableStream = (content, onError = console.trace) => {
161
165
  };
162
166
  // Annotate the CommonJS export names for ESM import in node:
163
167
  0 && (module.exports = {
168
+ StreamingContext,
164
169
  Suspense,
165
170
  renderToReadableStream
166
171
  });
@@ -21,6 +21,7 @@ __export(cache_exports, {
21
21
  cache: () => cache
22
22
  });
23
23
  module.exports = __toCommonJS(cache_exports);
24
+ const defaultCacheableStatusCodes = [200];
24
25
  const cache = (options) => {
25
26
  if (!globalThis.caches) {
26
27
  console.log("Cache Middleware is not enabled because caches is not defined.");
@@ -36,6 +37,9 @@ const cache = (options) => {
36
37
  'Middleware vary configuration cannot include "*", as it disallows effective caching.'
37
38
  );
38
39
  }
40
+ const cacheableStatusCodes = new Set(
41
+ options.cacheableStatusCodes ?? defaultCacheableStatusCodes
42
+ );
39
43
  const addHeader = (c) => {
40
44
  if (cacheControlDirectives) {
41
45
  const existingDirectives = c.res.headers.get("Cache-Control")?.split(",").map((d) => d.trim().split("=", 1)[0]) ?? [];
@@ -73,7 +77,7 @@ const cache = (options) => {
73
77
  return new Response(response.body, response);
74
78
  }
75
79
  await next();
76
- if (!c.res.ok) {
80
+ if (!cacheableStatusCodes.has(c.res.status)) {
77
81
  return;
78
82
  }
79
83
  addHeader(c);
@@ -45,6 +45,15 @@ const cors = (options) => {
45
45
  return (origin) => optsOrigin.includes(origin) ? origin : null;
46
46
  }
47
47
  })(opts.origin);
48
+ const findAllowMethods = ((optsAllowMethods) => {
49
+ if (typeof optsAllowMethods === "function") {
50
+ return optsAllowMethods;
51
+ } else if (Array.isArray(optsAllowMethods)) {
52
+ return () => optsAllowMethods;
53
+ } else {
54
+ return () => [];
55
+ }
56
+ })(opts.allowMethods);
48
57
  return async function cors2(c, next) {
49
58
  function set(key, value) {
50
59
  c.res.headers.set(key, value);
@@ -71,8 +80,9 @@ const cors = (options) => {
71
80
  if (opts.maxAge != null) {
72
81
  set("Access-Control-Max-Age", opts.maxAge.toString());
73
82
  }
74
- if (opts.allowMethods?.length) {
75
- set("Access-Control-Allow-Methods", opts.allowMethods.join(","));
83
+ const allowMethods = findAllowMethods(c.req.header("origin") || "", c);
84
+ if (allowMethods.length) {
85
+ set("Access-Control-Allow-Methods", allowMethods.join(","));
76
86
  }
77
87
  let headers = opts.allowHeaders;
78
88
  if (!headers?.length) {
@@ -73,6 +73,9 @@ const jwk = (options, init) => {
73
73
  }
74
74
  }
75
75
  if (!token) {
76
+ if (options.allow_anon) {
77
+ return next();
78
+ }
76
79
  const errDescription = "no authorization included in request";
77
80
  throw new import_http_exception.HTTPException(401, {
78
81
  message: errDescription,
@@ -86,7 +89,9 @@ const jwk = (options, init) => {
86
89
  let payload;
87
90
  let cause;
88
91
  try {
89
- payload = await import_jwt.Jwt.verifyFromJwks(token, options, init);
92
+ const keys = typeof options.keys === "function" ? await options.keys(ctx) : options.keys;
93
+ const jwks_uri = typeof options.jwks_uri === "function" ? await options.jwks_uri(ctx) : options.jwks_uri;
94
+ payload = await import_jwt.Jwt.verifyFromJwks(token, { keys, jwks_uri }, init);
90
95
  } catch (e) {
91
96
  cause = e;
92
97
  }
@@ -36,7 +36,8 @@ const jwt = (options) => {
36
36
  throw new Error("`crypto.subtle.importKey` is undefined. JWT auth middleware requires it.");
37
37
  }
38
38
  return async function jwt2(ctx, next) {
39
- const credentials = ctx.req.raw.headers.get("Authorization");
39
+ const headerName = options.headerName || "Authorization";
40
+ const credentials = ctx.req.raw.headers.get(headerName);
40
41
  let token;
41
42
  if (credentials) {
42
43
  const parts = credentials.split(/\s+/);
@@ -37,8 +37,8 @@ const time = (start) => {
37
37
  const delta = Date.now() - start;
38
38
  return humanize([delta < 1e3 ? delta + "ms" : Math.round(delta / 1e3) + "s"]);
39
39
  };
40
- const colorStatus = (status) => {
41
- const colorEnabled = (0, import_color.getColorEnabled)();
40
+ const colorStatus = async (status) => {
41
+ const colorEnabled = await (0, import_color.getColorEnabledAsync)();
42
42
  if (colorEnabled) {
43
43
  switch (status / 100 | 0) {
44
44
  case 5:
@@ -53,18 +53,18 @@ const colorStatus = (status) => {
53
53
  }
54
54
  return `${status}`;
55
55
  };
56
- function log(fn, prefix, method, path, status = 0, elapsed) {
57
- const out = prefix === "<--" /* Incoming */ ? `${prefix} ${method} ${path}` : `${prefix} ${method} ${path} ${colorStatus(status)} ${elapsed}`;
56
+ async function log(fn, prefix, method, path, status = 0, elapsed) {
57
+ const out = prefix === "<--" /* Incoming */ ? `${prefix} ${method} ${path}` : `${prefix} ${method} ${path} ${await colorStatus(status)} ${elapsed}`;
58
58
  fn(out);
59
59
  }
60
60
  const logger = (fn = console.log) => {
61
61
  return async function logger2(c, next) {
62
62
  const { method, url } = c.req;
63
63
  const path = url.slice(url.indexOf("/", 8));
64
- log(fn, "<--" /* Incoming */, method, path);
64
+ await log(fn, "<--" /* Incoming */, method, path);
65
65
  const start = Date.now();
66
66
  await next();
67
- log(fn, "-->" /* Outgoing */, method, path, c.res.status, time(start));
67
+ await log(fn, "-->" /* Outgoing */, method, path, c.res.status, time(start));
68
68
  };
69
69
  };
70
70
  // Annotate the CommonJS export names for ESM import in node: