hono 2.3.1 → 2.4.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 (153) hide show
  1. package/dist/cjs/compose.js +82 -66
  2. package/dist/cjs/context.js +159 -144
  3. package/dist/cjs/hono.js +173 -150
  4. package/dist/cjs/index.js +31 -11
  5. package/dist/cjs/middleware/basic-auth/index.js +70 -39
  6. package/dist/cjs/middleware/bearer-auth/index.js +69 -51
  7. package/dist/cjs/middleware/cache/index.js +49 -28
  8. package/dist/cjs/middleware/compress/index.js +39 -16
  9. package/dist/cjs/middleware/cors/index.js +89 -71
  10. package/dist/cjs/middleware/etag/index.js +46 -24
  11. package/dist/cjs/middleware/html/index.js +50 -30
  12. package/dist/cjs/middleware/jsx/index.js +178 -166
  13. package/dist/cjs/middleware/jsx/jsx-dev-runtime.js +30 -7
  14. package/dist/cjs/middleware/jsx/jsx-runtime.js +30 -6
  15. package/dist/cjs/middleware/jwt/index.js +74 -54
  16. package/dist/cjs/middleware/logger/index.js +59 -38
  17. package/dist/cjs/middleware/powered-by/index.js +30 -7
  18. package/dist/cjs/middleware/pretty-json/index.js +31 -8
  19. package/dist/cjs/middleware/serve-static/bun.js +56 -38
  20. package/dist/cjs/middleware/serve-static/index.js +27 -4
  21. package/dist/cjs/middleware/serve-static/module.js +42 -0
  22. package/dist/cjs/middleware/serve-static/serve-static.js +58 -39
  23. package/dist/cjs/middleware/validator/index.js +27 -4
  24. package/dist/cjs/middleware/validator/middleware.js +125 -91
  25. package/dist/cjs/package.json +3 -0
  26. package/dist/cjs/request.js +129 -116
  27. package/dist/cjs/router/reg-exp-router/index.js +27 -4
  28. package/dist/cjs/router/reg-exp-router/node.js +108 -97
  29. package/dist/cjs/router/reg-exp-router/router.js +158 -141
  30. package/dist/cjs/router/reg-exp-router/trie.js +55 -39
  31. package/dist/cjs/router/smart-router/index.js +27 -4
  32. package/dist/cjs/router/smart-router/router.js +70 -49
  33. package/dist/cjs/router/static-router/index.js +27 -4
  34. package/dist/cjs/router/static-router/router.js +78 -64
  35. package/dist/cjs/router/trie-router/index.js +27 -4
  36. package/dist/cjs/router/trie-router/node.js +167 -159
  37. package/dist/cjs/router/trie-router/router.js +43 -20
  38. package/dist/cjs/router.js +35 -6
  39. package/dist/cjs/types.js +16 -0
  40. package/dist/cjs/utils/body.js +36 -15
  41. package/dist/cjs/utils/buffer.js +56 -31
  42. package/dist/cjs/utils/cloudflare.js +53 -34
  43. package/dist/cjs/utils/cookie.js +59 -35
  44. package/dist/cjs/utils/crypto.js +69 -43
  45. package/dist/cjs/utils/encode.js +92 -65
  46. package/dist/cjs/utils/filepath.js +39 -22
  47. package/dist/cjs/utils/html.js +54 -33
  48. package/dist/cjs/utils/http-status.js +68 -45
  49. package/dist/cjs/utils/json.js +91 -76
  50. package/dist/cjs/utils/jwt/index.js +32 -25
  51. package/dist/cjs/utils/jwt/jwt.js +124 -93
  52. package/dist/cjs/utils/jwt/types.js +65 -38
  53. package/dist/cjs/utils/mime.js +110 -87
  54. package/dist/cjs/utils/object.js +53 -35
  55. package/dist/cjs/utils/types.js +16 -0
  56. package/dist/cjs/utils/url.js +89 -78
  57. package/dist/cjs/validator/rule.js +80 -0
  58. package/dist/cjs/validator/sanitizer.js +30 -0
  59. package/dist/cjs/validator/schema.js +16 -0
  60. package/dist/cjs/validator/validator.js +439 -0
  61. package/dist/compose.d.ts +4 -3
  62. package/dist/compose.js +61 -64
  63. package/dist/context.d.ts +10 -9
  64. package/dist/context.js +139 -143
  65. package/dist/hono.d.ts +27 -42
  66. package/dist/hono.js +153 -149
  67. package/dist/index.d.ts +4 -1
  68. package/dist/index.js +9 -9
  69. package/dist/middleware/basic-auth/index.d.ts +1 -1
  70. package/dist/middleware/basic-auth/index.js +52 -40
  71. package/dist/middleware/bearer-auth/index.d.ts +1 -1
  72. package/dist/middleware/bearer-auth/index.js +48 -49
  73. package/dist/middleware/cache/index.d.ts +1 -1
  74. package/dist/middleware/cache/index.js +28 -26
  75. package/dist/middleware/compress/index.d.ts +1 -1
  76. package/dist/middleware/compress/index.js +18 -14
  77. package/dist/middleware/cors/index.d.ts +1 -1
  78. package/dist/middleware/cors/index.js +68 -69
  79. package/dist/middleware/etag/index.d.ts +1 -1
  80. package/dist/middleware/etag/index.js +25 -22
  81. package/dist/middleware/html/index.js +29 -28
  82. package/dist/middleware/jsx/index.js +164 -172
  83. package/dist/middleware/jsx/jsx-dev-runtime.js +9 -5
  84. package/dist/middleware/jsx/jsx-runtime.js +7 -2
  85. package/dist/middleware/jwt/index.d.ts +1 -1
  86. package/dist/middleware/jwt/index.js +53 -52
  87. package/dist/middleware/logger/index.d.ts +1 -1
  88. package/dist/middleware/logger/index.js +35 -39
  89. package/dist/middleware/powered-by/index.d.ts +1 -1
  90. package/dist/middleware/powered-by/index.js +9 -5
  91. package/dist/middleware/pretty-json/index.d.ts +1 -1
  92. package/dist/middleware/pretty-json/index.js +10 -6
  93. package/dist/middleware/serve-static/bun.d.ts +1 -1
  94. package/dist/middleware/serve-static/bun.js +35 -36
  95. package/dist/middleware/serve-static/index.js +5 -1
  96. package/dist/middleware/serve-static/module.d.ts +3 -0
  97. package/dist/middleware/serve-static/module.js +13 -0
  98. package/dist/middleware/serve-static/serve-static.d.ts +2 -3
  99. package/dist/middleware/serve-static/serve-static.js +36 -36
  100. package/dist/middleware/validator/index.js +5 -2
  101. package/dist/middleware/validator/middleware.d.ts +9 -15
  102. package/dist/middleware/validator/middleware.js +104 -89
  103. package/dist/request.d.ts +2 -2
  104. package/dist/request.js +108 -114
  105. package/dist/router/reg-exp-router/index.js +5 -1
  106. package/dist/router/reg-exp-router/node.js +87 -96
  107. package/dist/router/reg-exp-router/router.js +140 -142
  108. package/dist/router/reg-exp-router/trie.js +35 -38
  109. package/dist/router/smart-router/index.js +5 -1
  110. package/dist/router/smart-router/router.js +50 -48
  111. package/dist/router/static-router/index.js +5 -1
  112. package/dist/router/static-router/router.js +58 -63
  113. package/dist/router/trie-router/index.js +5 -1
  114. package/dist/router/trie-router/node.js +147 -158
  115. package/dist/router/trie-router/router.js +23 -19
  116. package/dist/router.js +12 -5
  117. package/dist/types.d.ts +22 -0
  118. package/dist/types.js +0 -0
  119. package/dist/utils/body.js +15 -13
  120. package/dist/utils/buffer.js +35 -29
  121. package/dist/utils/cloudflare.js +32 -32
  122. package/dist/utils/cookie.js +38 -33
  123. package/dist/utils/crypto.js +48 -41
  124. package/dist/utils/encode.js +70 -62
  125. package/dist/utils/filepath.js +18 -20
  126. package/dist/utils/html.js +34 -32
  127. package/dist/utils/http-status.js +48 -44
  128. package/dist/utils/json.js +71 -75
  129. package/dist/utils/jwt/index.js +5 -1
  130. package/dist/utils/jwt/jwt.js +95 -90
  131. package/dist/utils/jwt/types.js +47 -41
  132. package/dist/utils/mime.js +90 -86
  133. package/dist/utils/object.js +31 -32
  134. package/dist/utils/types.d.ts +3 -0
  135. package/dist/utils/types.js +0 -0
  136. package/dist/utils/url.js +69 -77
  137. package/dist/{middleware/validator → validator}/rule.d.ts +0 -0
  138. package/dist/validator/rule.js +57 -0
  139. package/dist/{middleware/validator → validator}/sanitizer.d.ts +0 -0
  140. package/dist/validator/sanitizer.js +7 -0
  141. package/dist/validator/schema.d.ts +7 -0
  142. package/dist/validator/schema.js +0 -0
  143. package/dist/{middleware/validator → validator}/validator.d.ts +10 -7
  144. package/dist/validator/validator.js +406 -0
  145. package/package.json +14 -8
  146. package/dist/cjs/middleware/validator/rule.js +0 -66
  147. package/dist/cjs/middleware/validator/sanitizer.js +0 -6
  148. package/dist/cjs/middleware/validator/validator.js +0 -417
  149. package/dist/middleware/serve-static/module.d.mts +0 -3
  150. package/dist/middleware/serve-static/module.mjs +0 -13
  151. package/dist/middleware/validator/rule.js +0 -63
  152. package/dist/middleware/validator/sanitizer.js +0 -3
  153. package/dist/middleware/validator/validator.js +0 -403
package/dist/hono.js CHANGED
@@ -1,161 +1,165 @@
1
- import { compose } from './compose';
2
- import { HonoContext } from './context';
3
- import { extendRequestPrototype } from './request';
4
- import { METHODS } from './router';
5
- import { METHOD_NAME_ALL, METHOD_NAME_ALL_LOWERCASE } from './router';
6
- import { RegExpRouter } from './router/reg-exp-router';
7
- import { SmartRouter } from './router/smart-router';
8
- import { StaticRouter } from './router/static-router';
9
- import { TrieRouter } from './router/trie-router';
10
- import { getPathFromURL, mergePath } from './utils/url';
1
+ // src/hono.ts
2
+ import { compose } from "./compose.js";
3
+ import { HonoContext } from "./context.js";
4
+ import { extendRequestPrototype } from "./request.js";
5
+ import { METHOD_NAME_ALL, METHOD_NAME_ALL_LOWERCASE, METHODS } from "./router.js";
6
+ import { RegExpRouter } from "./router/reg-exp-router/index.js";
7
+ import { SmartRouter } from "./router/smart-router/index.js";
8
+ import { StaticRouter } from "./router/static-router/index.js";
9
+ import { TrieRouter } from "./router/trie-router/index.js";
10
+ import { getPathFromURL, mergePath } from "./utils/url.js";
11
11
  function defineDynamicClass() {
12
- return class {
13
- };
12
+ return class {
13
+ };
14
14
  }
15
- export class Hono extends defineDynamicClass() {
16
- constructor(init = {}) {
17
- super();
18
- this.router = new SmartRouter({
19
- routers: [new StaticRouter(), new RegExpRouter(), new TrieRouter()],
20
- });
21
- this.strict = true; // strict routing - default is true
22
- this._tempPath = '';
23
- this.path = '/';
24
- this.routes = [];
25
- this.notFoundHandler = (c) => {
26
- return c.text('404 Not Found', 404);
27
- };
28
- this.errorHandler = (err, c) => {
29
- console.trace(err.message);
30
- const message = 'Internal Server Error';
31
- return c.text(message, 500);
32
- };
33
- this.handleEvent = (event) => {
34
- return this.dispatch(event.request, event);
35
- };
36
- this.fetch = (request, Environment, executionCtx) => {
37
- return this.dispatch(request, executionCtx, Environment);
38
- };
39
- this.request = async (input, requestInit) => {
40
- const req = input instanceof Request ? input : new Request(input, requestInit);
41
- return await this.fetch(req);
42
- };
43
- extendRequestPrototype();
44
- const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
45
- allMethods.map((method) => {
46
- this[method] = (args1, ...args) => {
47
- if (typeof args1 === 'string') {
48
- this.path = args1;
49
- }
50
- else {
51
- this.addRoute(method, this.path, args1);
52
- }
53
- args.map((handler) => {
54
- if (typeof handler !== 'string') {
55
- this.addRoute(method, this.path, handler);
56
- }
57
- });
58
- return this;
59
- };
60
- });
61
- Object.assign(this, init);
62
- }
63
- route(path, app) {
64
- this._tempPath = path;
65
- if (app) {
66
- app.routes.map((r) => {
67
- this.addRoute(r.method, r.path, r.handler);
68
- });
69
- this._tempPath = '';
70
- }
71
- return this;
72
- }
73
- use(arg1, ...handlers) {
74
- if (typeof arg1 === 'string') {
75
- this.path = arg1;
76
- }
77
- else {
78
- handlers.unshift(arg1);
15
+ var Hono = class extends defineDynamicClass() {
16
+ constructor(init = {}) {
17
+ super();
18
+ this.router = new SmartRouter({
19
+ routers: [new StaticRouter(), new RegExpRouter(), new TrieRouter()]
20
+ });
21
+ this.strict = true;
22
+ this._tempPath = "";
23
+ this.path = "/";
24
+ this.routes = [];
25
+ this.notFoundHandler = (c) => {
26
+ return c.text("404 Not Found", 404);
27
+ };
28
+ this.errorHandler = (err, c) => {
29
+ console.trace(err.message);
30
+ const message = "Internal Server Error";
31
+ return c.text(message, 500);
32
+ };
33
+ this.handleEvent = (event) => {
34
+ return this.dispatch(event.request, event);
35
+ };
36
+ this.fetch = (request, Environment, executionCtx) => {
37
+ return this.dispatch(request, executionCtx, Environment);
38
+ };
39
+ this.request = async (input, requestInit) => {
40
+ const req = input instanceof Request ? input : new Request(input, requestInit);
41
+ return await this.fetch(req);
42
+ };
43
+ extendRequestPrototype();
44
+ const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
45
+ allMethods.map((method) => {
46
+ this[method] = (args1, ...args) => {
47
+ if (typeof args1 === "string") {
48
+ this.path = args1;
49
+ } else {
50
+ this.addRoute(method, this.path, args1);
79
51
  }
80
- handlers.map((handler) => {
81
- this.addRoute(METHOD_NAME_ALL, this.path, handler);
52
+ args.map((handler) => {
53
+ if (typeof handler !== "string") {
54
+ this.addRoute(method, this.path, handler);
55
+ }
82
56
  });
83
57
  return this;
58
+ };
59
+ });
60
+ Object.assign(this, init);
61
+ }
62
+ route(path, app) {
63
+ this._tempPath = path;
64
+ if (app) {
65
+ app.routes.map((r) => {
66
+ this.addRoute(r.method, r.path, r.handler);
67
+ });
68
+ this._tempPath = "";
84
69
  }
85
- onError(handler) {
86
- this.errorHandler = handler;
87
- return this;
88
- }
89
- notFound(handler) {
90
- this.notFoundHandler = handler;
91
- return this;
70
+ return this;
71
+ }
72
+ use(arg1, ...handlers) {
73
+ if (typeof arg1 === "string") {
74
+ this.path = arg1;
75
+ } else {
76
+ handlers.unshift(arg1);
92
77
  }
93
- addRoute(method, path, handler) {
94
- method = method.toUpperCase();
95
- if (this._tempPath) {
96
- path = mergePath(this._tempPath, path);
97
- }
98
- this.router.add(method, path, handler);
99
- const r = { path: path, method: method, handler: handler };
100
- this.routes.push(r);
78
+ handlers.map((handler) => {
79
+ this.addRoute(METHOD_NAME_ALL, this.path, handler);
80
+ });
81
+ return this;
82
+ }
83
+ onError(handler) {
84
+ this.errorHandler = handler;
85
+ return this;
86
+ }
87
+ notFound(handler) {
88
+ this.notFoundHandler = handler;
89
+ return this;
90
+ }
91
+ addRoute(method, path, handler) {
92
+ method = method.toUpperCase();
93
+ if (this._tempPath) {
94
+ path = mergePath(this._tempPath, path);
101
95
  }
102
- matchRoute(method, path) {
103
- return this.router.match(method, path);
96
+ this.router.add(method, path, handler);
97
+ const r = { path, method, handler };
98
+ this.routes.push(r);
99
+ }
100
+ matchRoute(method, path) {
101
+ return this.router.match(method, path);
102
+ }
103
+ handleError(err, c) {
104
+ if (err instanceof Error) {
105
+ return this.errorHandler(err, c);
104
106
  }
105
- handleError(err, c) {
106
- if (err instanceof Error) {
107
- return this.errorHandler(err, c);
107
+ throw err;
108
+ }
109
+ dispatch(request, eventOrExecutionCtx, env) {
110
+ const path = getPathFromURL(request.url, this.strict);
111
+ const method = request.method;
112
+ const result = this.matchRoute(method, path);
113
+ request.paramData = result?.params;
114
+ const c = new HonoContext(request, env, eventOrExecutionCtx, this.notFoundHandler);
115
+ if (result && result.handlers.length === 1) {
116
+ const handler = result.handlers[0];
117
+ let res;
118
+ try {
119
+ res = handler(c, async () => {
120
+ });
121
+ if (!res)
122
+ return this.notFoundHandler(c);
123
+ } catch (err) {
124
+ return this.handleError(err, c);
125
+ }
126
+ if (res instanceof Response)
127
+ return res;
128
+ return (async () => {
129
+ let awaited;
130
+ try {
131
+ awaited = await res;
132
+ } catch (err) {
133
+ return this.handleError(err, c);
108
134
  }
109
- throw err;
110
- }
111
- dispatch(request, eventOrExecutionCtx, env) {
112
- const path = getPathFromURL(request.url, this.strict);
113
- const method = request.method;
114
- const result = this.matchRoute(method, path);
115
- request.paramData = result?.params;
116
- const c = new HonoContext(request, env, eventOrExecutionCtx, this.notFoundHandler);
117
- // Do not `compose` if it has only one handler
118
- if (result && result.handlers.length === 1) {
119
- const handler = result.handlers[0];
120
- let res;
121
- try {
122
- res = handler(c, async () => { });
123
- if (!res)
124
- return this.notFoundHandler(c);
125
- }
126
- catch (err) {
127
- return this.handleError(err, c);
128
- }
129
- if (res instanceof Response)
130
- return res;
131
- return (async () => {
132
- let awaited;
133
- try {
134
- awaited = await res;
135
- }
136
- catch (err) {
137
- return this.handleError(err, c);
138
- }
139
- if (!awaited) {
140
- return this.notFoundHandler(c);
141
- }
142
- return awaited;
143
- })();
135
+ if (!awaited) {
136
+ return this.notFoundHandler(c);
144
137
  }
145
- const handlers = result ? result.handlers : [this.notFoundHandler];
146
- const composed = compose(handlers, this.notFoundHandler, this.errorHandler);
147
- return (async () => {
148
- try {
149
- const tmp = composed(c);
150
- const context = tmp instanceof Promise ? await tmp : tmp;
151
- if (!context.finalized) {
152
- throw new Error('Context is not finalized. You may forget returning Response object or `await next()`');
153
- }
154
- return context.res;
155
- }
156
- catch (err) {
157
- return this.handleError(err, c);
158
- }
159
- })();
138
+ return awaited;
139
+ })();
160
140
  }
161
- }
141
+ const handlers = result ? result.handlers : [this.notFoundHandler];
142
+ const composed = compose(
143
+ handlers,
144
+ this.notFoundHandler,
145
+ this.errorHandler
146
+ );
147
+ return (async () => {
148
+ try {
149
+ const tmp = composed(c);
150
+ const context = tmp instanceof Promise ? await tmp : tmp;
151
+ if (!context.finalized) {
152
+ throw new Error(
153
+ "Context is not finalized. You may forget returning Response object or `await next()`"
154
+ );
155
+ }
156
+ return context.res;
157
+ } catch (err) {
158
+ return this.handleError(err, c);
159
+ }
160
+ })();
161
+ }
162
+ };
163
+ export {
164
+ Hono
165
+ };
package/dist/index.d.ts CHANGED
@@ -1,7 +1,10 @@
1
1
  /// <reference path="request.d.ts" />
2
2
  import { Hono } from './hono';
3
- export type { Handler, Next, ContextVariableMap } from './hono';
3
+ export type { Next, ContextVariableMap, MiddlewareHandler } from './types';
4
4
  export type { Context } from './context';
5
+ export type { Validator } from './validator/validator';
6
+ import type { CustomHandler } from './types';
7
+ export type { CustomHandler as Handler };
5
8
  declare module './hono' {
6
9
  interface Hono {
7
10
  fire(): void;
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
- // @denoify-ignore
2
- // eslint-disable-next-line @typescript-eslint/triple-slash-reference
3
- /// <reference path="./request.ts" /> Import "declare global" for the Request interface.
4
- import { Hono } from './hono';
5
- Hono.prototype.fire = function () {
6
- addEventListener('fetch', (event) => {
7
- void event.respondWith(this.handleEvent(event));
8
- });
1
+ // src/index.ts
2
+ import { Hono } from "./hono.js";
3
+ Hono.prototype.fire = function() {
4
+ addEventListener("fetch", (event) => {
5
+ void event.respondWith(this.handleEvent(event));
6
+ });
7
+ };
8
+ export {
9
+ Hono
9
10
  };
10
- export { Hono };
@@ -1,4 +1,4 @@
1
- import type { MiddlewareHandler } from '../../hono';
1
+ import type { MiddlewareHandler } from '../../types';
2
2
  export declare const basicAuth: (options: {
3
3
  username: string;
4
4
  password: string;
@@ -1,43 +1,55 @@
1
- import { timingSafeEqual } from '../../utils/buffer';
2
- import { decodeBase64 } from '../../utils/encode';
3
- const CREDENTIALS_REGEXP = /^ *(?:[Bb][Aa][Ss][Ii][Cc]) +([A-Za-z0-9._~+/-]+=*) *$/;
4
- const USER_PASS_REGEXP = /^([^:]*):(.*)$/;
5
- const auth = (req) => {
6
- const match = CREDENTIALS_REGEXP.exec(req.headers.get('Authorization') || '');
7
- if (!match) {
8
- return undefined;
9
- }
10
- const userPass = USER_PASS_REGEXP.exec(decodeBase64(match[1]));
11
- if (!userPass) {
12
- return undefined;
13
- }
14
- return { username: userPass[1], password: userPass[2] };
1
+ // src/middleware/basic-auth/index.ts
2
+ import { timingSafeEqual } from "../../utils/buffer.js";
3
+ import { decodeBase64 } from "../../utils/encode.js";
4
+ var CREDENTIALS_REGEXP = /^ *(?:[Bb][Aa][Ss][Ii][Cc]) +([A-Za-z0-9._~+/-]+=*) *$/;
5
+ var USER_PASS_REGEXP = /^([^:]*):(.*)$/;
6
+ var auth = (req) => {
7
+ const match = CREDENTIALS_REGEXP.exec(req.headers.get("Authorization") || "");
8
+ if (!match) {
9
+ return void 0;
10
+ }
11
+ const userPass = USER_PASS_REGEXP.exec(decodeBase64(match[1]));
12
+ if (!userPass) {
13
+ return void 0;
14
+ }
15
+ return { username: userPass[1], password: userPass[2] };
15
16
  };
16
- export const basicAuth = (options, ...users) => {
17
- if (!options) {
18
- throw new Error('basic auth middleware requires options for "username and password"');
19
- }
20
- if (!options.realm) {
21
- options.realm = 'Secure Area';
22
- }
23
- users.unshift({ username: options.username, password: options.password });
24
- return async (ctx, next) => {
25
- const requestUser = auth(ctx.req);
26
- if (requestUser) {
27
- for (const user of users) {
28
- const usernameEqual = await timingSafeEqual(user.username, requestUser.username, options.hashFunction);
29
- const passwordEqual = await timingSafeEqual(user.password, requestUser.password, options.hashFunction);
30
- if (usernameEqual && passwordEqual) {
31
- await next();
32
- return;
33
- }
34
- }
17
+ var basicAuth = (options, ...users) => {
18
+ if (!options) {
19
+ throw new Error('basic auth middleware requires options for "username and password"');
20
+ }
21
+ if (!options.realm) {
22
+ options.realm = "Secure Area";
23
+ }
24
+ users.unshift({ username: options.username, password: options.password });
25
+ return async (ctx, next) => {
26
+ const requestUser = auth(ctx.req);
27
+ if (requestUser) {
28
+ for (const user of users) {
29
+ const usernameEqual = await timingSafeEqual(
30
+ user.username,
31
+ requestUser.username,
32
+ options.hashFunction
33
+ );
34
+ const passwordEqual = await timingSafeEqual(
35
+ user.password,
36
+ requestUser.password,
37
+ options.hashFunction
38
+ );
39
+ if (usernameEqual && passwordEqual) {
40
+ await next();
41
+ return;
35
42
  }
36
- return new Response('Unauthorized', {
37
- status: 401,
38
- headers: {
39
- 'WWW-Authenticate': 'Basic realm="' + options.realm?.replace(/"/g, '\\"') + '"',
40
- },
41
- });
42
- };
43
+ }
44
+ }
45
+ return new Response("Unauthorized", {
46
+ status: 401,
47
+ headers: {
48
+ "WWW-Authenticate": 'Basic realm="' + options.realm?.replace(/"/g, '\\"') + '"'
49
+ }
50
+ });
51
+ };
52
+ };
53
+ export {
54
+ basicAuth
43
55
  };
@@ -1,4 +1,4 @@
1
- import type { MiddlewareHandler } from '../../hono';
1
+ import type { MiddlewareHandler } from '../../types';
2
2
  export declare const bearerAuth: (options: {
3
3
  token: string;
4
4
  realm?: string;
@@ -1,53 +1,52 @@
1
- import { timingSafeEqual } from '../../utils/buffer';
2
- const TOKEN_STRINGS = '[A-Za-z0-9._~+/-]+=*';
3
- const PREFIX = 'Bearer';
4
- export const bearerAuth = (options) => {
5
- if (!options.token) {
6
- throw new Error('bearer auth middleware requires options for "token"');
7
- }
8
- if (!options.realm) {
9
- options.realm = '';
10
- }
11
- if (!options.prefix) {
12
- options.prefix = PREFIX;
13
- }
14
- const realm = options.realm?.replace(/"/g, '\\"');
15
- return async (c, next) => {
16
- const headerToken = c.req.headers.get('Authorization');
17
- if (!headerToken) {
18
- // No Authorization header
19
- return new Response('Unauthorized', {
20
- status: 401,
21
- headers: {
22
- 'WWW-Authenticate': `${options.prefix} realm="` + realm + '"',
23
- },
24
- });
1
+ // src/middleware/bearer-auth/index.ts
2
+ import { timingSafeEqual } from "../../utils/buffer.js";
3
+ var TOKEN_STRINGS = "[A-Za-z0-9._~+/-]+=*";
4
+ var PREFIX = "Bearer";
5
+ var bearerAuth = (options) => {
6
+ if (!options.token) {
7
+ throw new Error('bearer auth middleware requires options for "token"');
8
+ }
9
+ if (!options.realm) {
10
+ options.realm = "";
11
+ }
12
+ if (!options.prefix) {
13
+ options.prefix = PREFIX;
14
+ }
15
+ const realm = options.realm?.replace(/"/g, '\\"');
16
+ return async (c, next) => {
17
+ const headerToken = c.req.headers.get("Authorization");
18
+ if (!headerToken) {
19
+ return new Response("Unauthorized", {
20
+ status: 401,
21
+ headers: {
22
+ "WWW-Authenticate": `${options.prefix} realm="` + realm + '"'
25
23
  }
26
- else {
27
- const regexp = new RegExp('^' + options.prefix + ' +(' + TOKEN_STRINGS + ') *$');
28
- const match = regexp.exec(headerToken);
29
- if (!match) {
30
- // Invalid Request
31
- return new Response('Bad Request', {
32
- status: 400,
33
- headers: {
34
- 'WWW-Authenticate': `${options.prefix} error="invalid_request"`,
35
- },
36
- });
37
- }
38
- else {
39
- const equal = await timingSafeEqual(options.token, match[1], options.hashFunction);
40
- if (!equal) {
41
- // Invalid Token
42
- return new Response('Unauthorized', {
43
- status: 401,
44
- headers: {
45
- 'WWW-Authenticate': `${options.prefix} error="invalid_token"`,
46
- },
47
- });
48
- }
24
+ });
25
+ } else {
26
+ const regexp = new RegExp("^" + options.prefix + " +(" + TOKEN_STRINGS + ") *$");
27
+ const match = regexp.exec(headerToken);
28
+ if (!match) {
29
+ return new Response("Bad Request", {
30
+ status: 400,
31
+ headers: {
32
+ "WWW-Authenticate": `${options.prefix} error="invalid_request"`
33
+ }
34
+ });
35
+ } else {
36
+ const equal = await timingSafeEqual(options.token, match[1], options.hashFunction);
37
+ if (!equal) {
38
+ return new Response("Unauthorized", {
39
+ status: 401,
40
+ headers: {
41
+ "WWW-Authenticate": `${options.prefix} error="invalid_token"`
49
42
  }
43
+ });
50
44
  }
51
- await next();
52
- };
45
+ }
46
+ }
47
+ await next();
48
+ };
49
+ };
50
+ export {
51
+ bearerAuth
53
52
  };
@@ -1,4 +1,4 @@
1
- import type { MiddlewareHandler } from '../../hono';
1
+ import type { MiddlewareHandler } from '../../types';
2
2
  export declare const cache: (options: {
3
3
  cacheName: string;
4
4
  wait?: boolean;
@@ -1,28 +1,30 @@
1
- export const cache = (options) => {
2
- if (options.wait === undefined) {
3
- options.wait = false;
1
+ // src/middleware/cache/index.ts
2
+ var cache = (options) => {
3
+ if (options.wait === void 0) {
4
+ options.wait = false;
5
+ }
6
+ const addHeader = (response) => {
7
+ if (options.cacheControl)
8
+ response.headers.append("Cache-Control", options.cacheControl);
9
+ };
10
+ return async (c, next) => {
11
+ const key = c.req;
12
+ const cache2 = await caches.open(options.cacheName);
13
+ const response = await cache2.match(key);
14
+ if (!response) {
15
+ await next();
16
+ addHeader(c.res);
17
+ const response2 = c.res.clone();
18
+ if (options.wait) {
19
+ await cache2.put(key, response2);
20
+ } else {
21
+ c.executionCtx.waitUntil(cache2.put(key, response2));
22
+ }
23
+ } else {
24
+ return response;
4
25
  }
5
- const addHeader = (response) => {
6
- if (options.cacheControl)
7
- response.headers.append('Cache-Control', options.cacheControl);
8
- };
9
- return async (c, next) => {
10
- const key = c.req;
11
- const cache = await caches.open(options.cacheName);
12
- const response = await cache.match(key);
13
- if (!response) {
14
- await next();
15
- addHeader(c.res);
16
- const response = c.res.clone();
17
- if (options.wait) {
18
- await cache.put(key, response);
19
- }
20
- else {
21
- c.executionCtx.waitUntil(cache.put(key, response));
22
- }
23
- }
24
- else {
25
- return response;
26
- }
27
- };
26
+ };
27
+ };
28
+ export {
29
+ cache
28
30
  };
@@ -1,4 +1,4 @@
1
- import type { MiddlewareHandler } from '../../hono';
1
+ import type { MiddlewareHandler } from '../../types';
2
2
  declare type EncodingType = 'gzip' | 'deflate';
3
3
  interface CompressionOptions {
4
4
  encoding?: EncodingType;