hono 1.0.0 → 1.2.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 (43) hide show
  1. package/README.md +189 -125
  2. package/dist/compose.d.ts +2 -2
  3. package/dist/compose.js +20 -8
  4. package/dist/context.d.ts +4 -5
  5. package/dist/context.js +5 -17
  6. package/dist/hono.d.ts +51 -25
  7. package/dist/hono.js +106 -49
  8. package/dist/index.d.ts +2 -2
  9. package/dist/index.js +2 -1
  10. package/dist/middleware/basic-auth/index.js +11 -10
  11. package/dist/middleware/body-parse/index.d.ts +5 -0
  12. package/dist/middleware/cookie/index.d.ts +1 -3
  13. package/dist/middleware/graphql-server/parse-body.d.ts +1 -3
  14. package/dist/middleware/jwt/index.d.ts +6 -0
  15. package/dist/middleware/jwt/index.js +49 -0
  16. package/dist/middleware/logger/index.js +3 -5
  17. package/dist/middleware/mustache/index.js +3 -9
  18. package/dist/router/reg-exp-router/node.d.ts +3 -0
  19. package/dist/router/reg-exp-router/node.js +13 -7
  20. package/dist/router/reg-exp-router/router.d.ts +21 -2
  21. package/dist/router/reg-exp-router/router.js +300 -80
  22. package/dist/router/reg-exp-router/trie.d.ts +4 -0
  23. package/dist/router/reg-exp-router/trie.js +2 -2
  24. package/dist/router/trie-router/node.d.ts +4 -3
  25. package/dist/router/trie-router/node.js +123 -55
  26. package/dist/router/trie-router/router.d.ts +1 -1
  27. package/dist/router.d.ts +4 -3
  28. package/dist/router.js +5 -4
  29. package/dist/utils/body.js +2 -2
  30. package/dist/utils/buffer.d.ts +1 -0
  31. package/dist/utils/buffer.js +9 -1
  32. package/dist/utils/crypto.d.ts +0 -2
  33. package/dist/utils/crypto.js +1 -51
  34. package/dist/utils/encode.d.ts +7 -0
  35. package/dist/utils/encode.js +105 -0
  36. package/dist/utils/jwt/index.d.ts +1 -0
  37. package/dist/utils/jwt/index.js +27 -0
  38. package/dist/utils/jwt/jwt.d.ts +7 -0
  39. package/dist/utils/jwt/jwt.js +98 -0
  40. package/dist/utils/jwt/types.d.ts +20 -0
  41. package/dist/utils/jwt/types.js +44 -0
  42. package/dist/utils/url.js +4 -4
  43. package/package.json +29 -21
package/dist/context.js CHANGED
@@ -5,10 +5,14 @@ const http_status_1 = require("./utils/http-status");
5
5
  const url_1 = require("./utils/url");
6
6
  class Context {
7
7
  constructor(req, opts) {
8
+ this.res = undefined;
9
+ this._headers = {};
10
+ this._status = 200;
11
+ this._statusText = '';
12
+ this._pretty = false;
8
13
  this._prettySpace = 2;
9
14
  this.req = this.initRequest(req);
10
15
  Object.assign(this, opts);
11
- this._headers = {};
12
16
  }
13
17
  initRequest(req) {
14
18
  req.header = (name) => {
@@ -27,10 +31,6 @@ class Context {
27
31
  this._headers[name] = value;
28
32
  }
29
33
  status(status) {
30
- if (this.res) {
31
- console.warn('c.res.status is already set.');
32
- return;
33
- }
34
34
  this._status = status;
35
35
  this._statusText = (0, http_status_1.getStatusText)(status);
36
36
  }
@@ -43,18 +43,6 @@ class Context {
43
43
  init.statusText =
44
44
  init.statusText || this._statusText || (0, http_status_1.getStatusText)(init.status);
45
45
  init.headers = Object.assign(Object.assign({}, this._headers), init.headers);
46
- // Content-Length
47
- let length = 0;
48
- if (data) {
49
- if (data instanceof ArrayBuffer) {
50
- length = data.byteLength;
51
- }
52
- else if (typeof data == 'string') {
53
- const Encoder = new TextEncoder();
54
- length = Encoder.encode(data).byteLength || 0;
55
- }
56
- }
57
- init.headers = Object.assign(Object.assign({}, init.headers), { 'Content-Length': length.toString() });
58
46
  return new Response(data, init);
59
47
  }
60
48
  body(data, status = this._status, headers = this._headers) {
package/dist/hono.d.ts CHANGED
@@ -2,54 +2,80 @@
2
2
  import { Context } from './context';
3
3
  import type { Env } from './context';
4
4
  import type { Router } from './router';
5
+ import { METHOD_NAME_ALL_LOWERCASE } from './router';
5
6
  declare global {
6
7
  interface Request<ParamKeyType = string> {
7
8
  param: (key: ParamKeyType) => string;
8
9
  query: (key: string) => string;
9
10
  header: (name: string) => string;
10
- parsedBody: any;
11
11
  }
12
12
  }
13
- export declare type Handler<RequestParamKeyType = string> = (c: Context<RequestParamKeyType | string>, next?: Next) => Response | Promise<Response>;
14
- export declare type MiddlewareHandler = (c: Context, next: Next) => Promise<void>;
15
- export declare type NotFoundHandler = (c: Context) => Response | Promise<Response>;
16
- export declare type ErrorHandler = (err: Error, c: Context) => Response;
13
+ export declare type Handler<RequestParamKeyType = string, E = Env> = (c: Context<RequestParamKeyType, E>, next?: Next) => Response | Promise<Response> | void | Promise<void>;
14
+ export declare type NotFoundHandler<E = Env> = (c: Context<string, E>) => Response;
15
+ export declare type ErrorHandler<E = Env> = (err: Error, c: Context<string, E>) => Response;
17
16
  export declare type Next = () => Promise<void>;
18
17
  declare type ParamKeyName<NameWithPattern> = NameWithPattern extends `${infer Name}{${infer _Pattern}` ? Name : NameWithPattern;
19
18
  declare type ParamKey<Component> = Component extends `:${infer NameWithPattern}` ? ParamKeyName<NameWithPattern> : never;
20
19
  declare type ParamKeys<Path> = Path extends `${infer Component}/${infer Rest}` ? ParamKey<Component> | ParamKeys<Rest> : ParamKey<Path>;
21
- declare const Hono_base: new () => {
22
- delete: <Path extends string>(path: Path, handler: Handler<ParamKeys<Path>>) => Hono;
23
- get: <Path extends string>(path: Path, handler: Handler<ParamKeys<Path>>) => Hono;
24
- post: <Path extends string>(path: Path, handler: Handler<ParamKeys<Path>>) => Hono;
25
- put: <Path extends string>(path: Path, handler: Handler<ParamKeys<Path>>) => Hono;
26
- head: <Path extends string>(path: Path, handler: Handler<ParamKeys<Path>>) => Hono;
27
- options: <Path extends string>(path: Path, handler: Handler<ParamKeys<Path>>) => Hono;
28
- patch: <Path extends string>(path: Path, handler: Handler<ParamKeys<Path>>) => Hono;
29
- all: <Path extends string>(path: Path, handler: Handler<ParamKeys<Path>>) => Hono;
30
- } & {
31
- methods: ["get", "post", "put", "delete", "head", "options", "patch", "all"];
20
+ interface HandlerInterface<T extends string, E = Env, U = Hono<E, T>> {
21
+ <Path extends string>(path: Path, ...handlers: Handler<ParamKeys<Path> extends never ? string : ParamKeys<Path>, E>[]): U;
22
+ (path: string, ...handlers: Handler<string, E>[]): U;
23
+ <Path extends string>(...handlers: Handler<ParamKeys<Path> extends never ? string : ParamKeys<Path>, E>[]): U;
24
+ (...handlers: Handler<string, E>[]): U;
25
+ }
26
+ declare const methods: readonly ["get", "post", "put", "delete", "head", "options", "patch"];
27
+ declare type Methods = typeof methods[number] | typeof METHOD_NAME_ALL_LOWERCASE;
28
+ interface Routing<E extends Env> {
29
+ path: string;
30
+ method: Methods;
31
+ handler: Handler<string, E>;
32
+ }
33
+ declare const Route_base: new <E_1 extends Env, T extends string, U>() => {
34
+ delete: HandlerInterface<T, E_1, U>;
35
+ get: HandlerInterface<T, E_1, U>;
36
+ all: HandlerInterface<T, E_1, U>;
37
+ post: HandlerInterface<T, E_1, U>;
38
+ put: HandlerInterface<T, E_1, U>;
39
+ head: HandlerInterface<T, E_1, U>;
40
+ options: HandlerInterface<T, E_1, U>;
41
+ patch: HandlerInterface<T, E_1, U>;
42
+ };
43
+ export declare class Route<E = Env, P extends string = ''> extends Route_base<E, P, Route<E, P>> {
44
+ #private;
45
+ routes: Routing<E>[];
46
+ constructor();
47
+ private add;
48
+ }
49
+ declare const Hono_base: new <E_1 extends Env, T extends string, U>() => {
50
+ delete: HandlerInterface<T, E_1, U>;
51
+ get: HandlerInterface<T, E_1, U>;
52
+ all: HandlerInterface<T, E_1, U>;
53
+ post: HandlerInterface<T, E_1, U>;
54
+ put: HandlerInterface<T, E_1, U>;
55
+ head: HandlerInterface<T, E_1, U>;
56
+ options: HandlerInterface<T, E_1, U>;
57
+ patch: HandlerInterface<T, E_1, U>;
32
58
  };
33
- export declare class Hono extends Hono_base {
59
+ export declare class Hono<E = Env, P extends string = ''> extends Hono_base<E, P, Hono<E, P>> {
60
+ #private;
34
61
  readonly routerClass: {
35
62
  new (): Router<any>;
36
63
  };
37
64
  readonly strict: boolean;
38
- private router;
39
- private middlewareRouters;
40
- private tempPath;
65
+ private path;
41
66
  constructor(init?: Partial<Pick<Hono, 'routerClass' | 'strict'>>);
42
67
  private notFoundHandler;
43
68
  private errorHandler;
44
- route(path: string): Hono;
45
- use(path: string, middleware: MiddlewareHandler): void;
46
- onError(handler: ErrorHandler): Hono;
47
- notFound(handler: NotFoundHandler): Hono;
69
+ route(path: string, route?: Route): Hono<E, P>;
70
+ use(path: string, ...middleware: Handler<string, E>[]): Hono<E, P>;
71
+ use(...middleware: Handler<string, E>[]): Hono<E, P>;
72
+ onError(handler: ErrorHandler<E>): Hono<E, P>;
73
+ notFound(handler: NotFoundHandler<E>): Hono<E, P>;
48
74
  private addRoute;
49
75
  private matchRoute;
50
76
  private dispatch;
51
77
  handleEvent(event: FetchEvent): Promise<Response>;
52
- fetch(request: Request, env?: Env, event?: FetchEvent): Promise<Response>;
78
+ fetch(request: Request, env?: E, event?: FetchEvent): Promise<Response>;
53
79
  request(input: RequestInfo, requestInit?: RequestInit): Promise<Response>;
54
80
  fire(): void;
55
81
  }
package/dist/hono.js CHANGED
@@ -1,23 +1,67 @@
1
1
  "use strict";
2
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
3
+ if (kind === "m") throw new TypeError("Private method is not writable");
4
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
5
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
6
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
7
+ };
8
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
9
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
10
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
11
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
+ };
13
+ var _Route_path, _Hono_router, _Hono_tempPath;
2
14
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Hono = void 0;
15
+ exports.Hono = exports.Route = void 0;
4
16
  const compose_1 = require("./compose");
5
17
  const context_1 = require("./context");
6
18
  const router_1 = require("./router");
19
+ const router_2 = require("./router");
7
20
  const trie_router_1 = require("./router/trie-router"); // Default Router
8
21
  const url_1 = require("./utils/url");
9
- function defineDynamicClass(...methods) {
22
+ const methods = ['get', 'post', 'put', 'delete', 'head', 'options', 'patch'];
23
+ function defineDynamicClass() {
10
24
  return class {
11
- get methods() {
12
- return methods;
13
- }
14
25
  };
15
26
  }
16
- class Hono extends defineDynamicClass('get', 'post', 'put', 'delete', 'head', 'options', 'patch', 'all') {
27
+ class Route extends defineDynamicClass() {
28
+ constructor() {
29
+ super();
30
+ this.routes = [];
31
+ _Route_path.set(this, '');
32
+ const allMethods = [...methods, router_2.METHOD_NAME_ALL_LOWERCASE];
33
+ allMethods.map((method) => {
34
+ this[method] = (args1, ...args) => {
35
+ if (typeof args1 === 'string') {
36
+ __classPrivateFieldSet(this, _Route_path, args1, "f");
37
+ }
38
+ else {
39
+ this.add(method, __classPrivateFieldGet(this, _Route_path, "f"), args1);
40
+ }
41
+ args.map((handler) => {
42
+ if (typeof handler !== 'string') {
43
+ this.add(method, __classPrivateFieldGet(this, _Route_path, "f"), handler);
44
+ }
45
+ });
46
+ return this;
47
+ };
48
+ });
49
+ }
50
+ add(method, path, handler) {
51
+ const r = { path: path, method: method, handler: handler };
52
+ this.routes.push(r);
53
+ return this;
54
+ }
55
+ }
56
+ exports.Route = Route;
57
+ _Route_path = new WeakMap();
58
+ class Hono extends defineDynamicClass() {
17
59
  constructor(init = {}) {
18
60
  super();
19
61
  this.routerClass = trie_router_1.TrieRouter;
20
62
  this.strict = true; // strict routing - default is true
63
+ _Hono_router.set(this, void 0);
64
+ _Hono_tempPath.set(this, void 0);
21
65
  this.notFoundHandler = (c) => {
22
66
  const message = '404 Not Found';
23
67
  return c.text(message, 404);
@@ -27,29 +71,49 @@ class Hono extends defineDynamicClass('get', 'post', 'put', 'delete', 'head', 'o
27
71
  const message = 'Internal Server Error';
28
72
  return c.text(message, 500);
29
73
  };
30
- this.methods.map((method) => {
31
- this[method] = (path, handler) => {
32
- return this.addRoute(method, path, handler);
74
+ const allMethods = [...methods, router_2.METHOD_NAME_ALL_LOWERCASE];
75
+ allMethods.map((method) => {
76
+ this[method] = (args1, ...args) => {
77
+ if (typeof args1 === 'string') {
78
+ this.path = args1;
79
+ }
80
+ else {
81
+ this.addRoute(method, this.path, args1);
82
+ }
83
+ args.map((handler) => {
84
+ if (typeof handler !== 'string') {
85
+ this.addRoute(method, this.path, handler);
86
+ }
87
+ });
88
+ return this;
33
89
  };
34
90
  });
35
91
  Object.assign(this, init);
36
- this.router = new this.routerClass();
37
- this.middlewareRouters = [];
38
- this.tempPath = null;
92
+ __classPrivateFieldSet(this, _Hono_router, new this.routerClass(), "f");
93
+ __classPrivateFieldSet(this, _Hono_tempPath, null, "f");
39
94
  }
40
- route(path) {
95
+ route(path, route) {
41
96
  const newHono = new Hono();
42
- newHono.tempPath = path;
43
- newHono.router = this.router;
97
+ __classPrivateFieldSet(newHono, _Hono_tempPath, path, "f");
98
+ __classPrivateFieldSet(newHono, _Hono_router, __classPrivateFieldGet(this, _Hono_router, "f"), "f");
99
+ if (route) {
100
+ route.routes.map((r) => {
101
+ newHono.addRoute(r.method, r.path, r.handler);
102
+ });
103
+ }
44
104
  return newHono;
45
105
  }
46
- use(path, middleware) {
47
- if (middleware.constructor.name !== 'AsyncFunction') {
48
- throw new TypeError('middleware must be a async function!');
106
+ use(arg1, ...handlers) {
107
+ if (typeof arg1 === 'string') {
108
+ this.path = arg1;
49
109
  }
50
- const router = new this.routerClass();
51
- router.add(router_1.METHOD_NAME_OF_ALL, path, middleware);
52
- this.middlewareRouters.push(router);
110
+ else {
111
+ handlers.unshift(arg1);
112
+ }
113
+ handlers.map((handler) => {
114
+ this.addRoute(router_1.METHOD_NAME_ALL, this.path, handler);
115
+ });
116
+ return this;
53
117
  }
54
118
  onError(handler) {
55
119
  this.errorHandler = handler;
@@ -59,54 +123,46 @@ class Hono extends defineDynamicClass('get', 'post', 'put', 'delete', 'head', 'o
59
123
  this.notFoundHandler = handler;
60
124
  return this;
61
125
  }
62
- // addRoute('get', '/', handler)
63
126
  addRoute(method, path, handler) {
64
127
  method = method.toUpperCase();
65
- if (this.tempPath) {
66
- path = (0, url_1.mergePath)(this.tempPath, path);
128
+ if (__classPrivateFieldGet(this, _Hono_tempPath, "f")) {
129
+ path = (0, url_1.mergePath)(__classPrivateFieldGet(this, _Hono_tempPath, "f"), path);
67
130
  }
68
- this.router.add(method, path, handler);
69
- return this;
131
+ __classPrivateFieldGet(this, _Hono_router, "f").add(method, path, handler);
70
132
  }
71
133
  async matchRoute(method, path) {
72
- return this.router.match(method, path);
134
+ return __classPrivateFieldGet(this, _Hono_router, "f").match(method, path);
73
135
  }
74
- async dispatch(request, env, event) {
136
+ async dispatch(request, event, env) {
75
137
  const path = (0, url_1.getPathFromURL)(request.url, { strict: this.strict });
76
138
  const method = request.method;
77
139
  const result = await this.matchRoute(method, path);
78
- // Methods for Request object
79
140
  request.param = (key) => {
80
141
  if (result)
81
142
  return result.params[key];
82
143
  };
83
- const handler = result ? result.handler : this.notFoundHandler;
84
- const middleware = [];
85
- for (const mr of this.middlewareRouters) {
86
- const mwResult = mr.match(router_1.METHOD_NAME_OF_ALL, path);
87
- if (mwResult)
88
- middleware.push(mwResult.handler);
144
+ const handlers = result ? result.handlers : [this.notFoundHandler];
145
+ const c = new context_1.Context(request, { env: env, event: event, res: undefined });
146
+ c.notFound = () => this.notFoundHandler(c);
147
+ const composed = (0, compose_1.compose)(handlers, this.errorHandler, this.notFoundHandler);
148
+ let context;
149
+ try {
150
+ context = await composed(c);
89
151
  }
90
- const wrappedHandler = async (context, next) => {
91
- const res = await handler(context);
92
- if (!(res instanceof Response)) {
93
- throw new TypeError('response must be a instance of Response');
152
+ catch (err) {
153
+ if (err instanceof Error) {
154
+ return this.errorHandler(err, c);
94
155
  }
95
- context.res = res;
96
- await next();
97
- };
98
- middleware.push(wrappedHandler);
99
- const composed = (0, compose_1.compose)(middleware, this.errorHandler);
100
- const c = new context_1.Context(request, { env: env, event: event, res: null });
101
- c.notFound = () => this.notFoundHandler(c);
102
- const context = await composed(c);
156
+ }
157
+ if (!context.res)
158
+ return context.notFound();
103
159
  return context.res;
104
160
  }
105
161
  async handleEvent(event) {
106
- return this.dispatch(event.request, {}, event);
162
+ return this.dispatch(event.request, event);
107
163
  }
108
164
  async fetch(request, env, event) {
109
- return this.dispatch(request, env, event);
165
+ return this.dispatch(request, event, env);
110
166
  }
111
167
  request(input, requestInit) {
112
168
  const req = input instanceof Request ? input : new Request(input, requestInit);
@@ -119,3 +175,4 @@ class Hono extends defineDynamicClass('get', 'post', 'put', 'delete', 'head', 'o
119
175
  }
120
176
  }
121
177
  exports.Hono = Hono;
178
+ _Hono_router = new WeakMap(), _Hono_tempPath = new WeakMap();
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { Hono } from './hono';
2
- export type { Handler, MiddlewareHandler, Next } from './hono';
1
+ export { Hono, Route } from './hono';
2
+ export type { Handler, Next } from './hono';
3
3
  export { Context } from './context';
4
4
  export type { Env } from './context';
package/dist/index.js CHANGED
@@ -1,7 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Context = exports.Hono = void 0;
3
+ exports.Context = exports.Route = exports.Hono = void 0;
4
4
  var hono_1 = require("./hono");
5
5
  Object.defineProperty(exports, "Hono", { enumerable: true, get: function () { return hono_1.Hono; } });
6
+ Object.defineProperty(exports, "Route", { enumerable: true, get: function () { return hono_1.Route; } });
6
7
  var context_1 = require("./context");
7
8
  Object.defineProperty(exports, "Context", { enumerable: true, get: function () { return context_1.Context; } });
@@ -2,7 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.basicAuth = void 0;
4
4
  const buffer_1 = require("../../utils/buffer");
5
- const crypto_1 = require("../../utils/crypto");
5
+ const encode_1 = require("../../utils/encode");
6
6
  const CREDENTIALS_REGEXP = /^ *(?:[Bb][Aa][Ss][Ii][Cc]) +([A-Za-z0-9._~+/-]+=*) *$/;
7
7
  const USER_PASS_REGEXP = /^([^:]*):(.*)$/;
8
8
  const auth = (req) => {
@@ -19,7 +19,7 @@ const auth = (req) => {
19
19
  if (!match) {
20
20
  return undefined;
21
21
  }
22
- const userPass = USER_PASS_REGEXP.exec((0, crypto_1.decodeBase64)(match[1]));
22
+ const userPass = USER_PASS_REGEXP.exec((0, encode_1.decodeBase64)(match[1]));
23
23
  if (!userPass) {
24
24
  return undefined;
25
25
  }
@@ -41,17 +41,18 @@ const basicAuth = (options, ...users) => {
41
41
  const passwordEqual = await (0, buffer_1.timingSafeEqual)(user.password, requestUser.password, options.hashFunction);
42
42
  if (usernameEqual && passwordEqual) {
43
43
  // Authorized OK
44
- return next();
44
+ await next();
45
45
  }
46
46
  }
47
47
  }
48
- ctx.res = new Response('Unauthorized', {
49
- status: 401,
50
- headers: {
51
- 'WWW-Authenticate': 'Basic realm="' + options.realm.replace(/"/g, '\\"') + '"',
52
- },
53
- });
54
- return;
48
+ else {
49
+ ctx.res = new Response('Unauthorized', {
50
+ status: 401,
51
+ headers: {
52
+ 'WWW-Authenticate': 'Basic realm="' + options.realm.replace(/"/g, '\\"') + '"',
53
+ },
54
+ });
55
+ }
55
56
  };
56
57
  };
57
58
  exports.basicAuth = basicAuth;
@@ -1,3 +1,8 @@
1
1
  import type { Context } from '../../context';
2
2
  import type { Next } from '../../hono';
3
+ declare global {
4
+ interface Request {
5
+ parsedBody: any;
6
+ }
7
+ }
3
8
  export declare const bodyParse: () => (ctx: Context, next: Next) => Promise<void>;
@@ -10,9 +10,7 @@ declare module '@/context' {
10
10
  cookie: (name: string, value: string, options?: CookieOptions) => void;
11
11
  }
12
12
  }
13
- export declare type Cookie = {
14
- [key: string]: string;
15
- };
13
+ export declare type Cookie = Record<string, string>;
16
14
  export declare type CookieOptions = {
17
15
  domain?: string;
18
16
  expires?: Date;
@@ -1,3 +1 @@
1
- export declare function parseBody(req: Request): Promise<{
2
- [param: string]: unknown;
3
- }>;
1
+ export declare function parseBody(req: Request): Promise<Record<string, unknown>>;
@@ -0,0 +1,6 @@
1
+ import type { Context } from '../../context';
2
+ import type { Next } from '../../hono';
3
+ export declare const jwt: (options: {
4
+ secret: string;
5
+ alg?: string;
6
+ }) => (ctx: Context, next: Next) => Promise<void>;
@@ -0,0 +1,49 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.jwt = void 0;
4
+ const jwt_1 = require("../../utils/jwt");
5
+ const jwt = (options) => {
6
+ if (!options) {
7
+ throw new Error('JWT auth middleware requires options for "secret');
8
+ }
9
+ return async (ctx, next) => {
10
+ const credentials = ctx.req.headers.get('Authorization');
11
+ await next();
12
+ if (!credentials) {
13
+ ctx.res = new Response('Unauthorized', {
14
+ status: 401,
15
+ headers: {
16
+ 'WWW-Authenticate': 'Basic ${options.secret}',
17
+ },
18
+ });
19
+ return;
20
+ }
21
+ const parts = credentials.split(/\s+/);
22
+ if (parts.length !== 2) {
23
+ ctx.res = new Response('Unauthorized', {
24
+ status: 401,
25
+ headers: {
26
+ 'WWW-Authenticate': 'Basic ${options.secret}',
27
+ },
28
+ });
29
+ }
30
+ let authorized = false;
31
+ let msg = '';
32
+ try {
33
+ authorized = await jwt_1.Jwt.verify(parts[1], options.secret, options.alg);
34
+ }
35
+ catch (e) {
36
+ msg = `${e}`;
37
+ }
38
+ if (!authorized) {
39
+ ctx.res = new Response('Unauthorized', {
40
+ status: 401,
41
+ statusText: msg,
42
+ headers: {
43
+ 'WWW-Authenticate': 'Bearer ${options.secret}',
44
+ },
45
+ });
46
+ }
47
+ };
48
+ };
49
+ exports.jwt = jwt;
@@ -31,10 +31,10 @@ const colorStatus = (status = 0) => {
31
31
  };
32
32
  return out[(status / 100) | 0];
33
33
  };
34
- function log(fn, prefix, method, path, status, elapsed, contentLength) {
34
+ function log(fn, prefix, method, path, status, elapsed) {
35
35
  const out = prefix === LogPrefix.Incoming
36
36
  ? ` ${prefix} ${method} ${path}`
37
- : ` ${prefix} ${method} ${path} ${colorStatus(status)} ${elapsed} ${contentLength}`;
37
+ : ` ${prefix} ${method} ${path} ${colorStatus(status)} ${elapsed}`;
38
38
  fn(out);
39
39
  }
40
40
  const logger = (fn = console.log) => {
@@ -44,9 +44,7 @@ const logger = (fn = console.log) => {
44
44
  log(fn, LogPrefix.Incoming, method, path);
45
45
  const start = Date.now();
46
46
  await next();
47
- const len = parseFloat(c.res.headers.get('Content-Length'));
48
- const contentLength = isNaN(len) ? '0' : len < 1024 ? `${len}b` : `${len / 1024}kB`;
49
- log(fn, LogPrefix.Outgoing, method, path, c.res.status, time(start), contentLength);
47
+ log(fn, LogPrefix.Outgoing, method, path, c.res.status, time(start));
50
48
  };
51
49
  };
52
50
  exports.logger = logger;
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.mustache = void 0;
4
+ const buffer_1 = require("../../utils/buffer");
4
5
  const cloudflare_1 = require("../../utils/cloudflare");
5
6
  const EXTENSION = '.mustache';
6
7
  const DEFAULT_DOCUMENT = 'index.mustache';
@@ -24,7 +25,7 @@ const mustache = (init = { root: '' }) => {
24
25
  if (!buffer) {
25
26
  throw new Error(`Template "${path}" is not found or blank.`);
26
27
  }
27
- const content = bufferToString(buffer);
28
+ const content = (0, buffer_1.bufferToString)(buffer);
28
29
  const partialArgs = {};
29
30
  if (options) {
30
31
  const partials = options;
@@ -38,7 +39,7 @@ const mustache = (init = { root: '' }) => {
38
39
  if (!partialBuffer) {
39
40
  throw new Error(`Partial Template "${partialPath}" is not found or blank.`);
40
41
  }
41
- partialArgs[key] = bufferToString(partialBuffer);
42
+ partialArgs[key] = (0, buffer_1.bufferToString)(partialBuffer);
42
43
  }
43
44
  }
44
45
  const output = Mustache.render(content, params, partialArgs);
@@ -48,10 +49,3 @@ const mustache = (init = { root: '' }) => {
48
49
  };
49
50
  };
50
51
  exports.mustache = mustache;
51
- const bufferToString = (buffer) => {
52
- if (buffer instanceof ArrayBuffer) {
53
- const enc = new TextDecoder('utf-8');
54
- return enc.decode(buffer);
55
- }
56
- return buffer;
57
- };
@@ -6,6 +6,9 @@ export declare class Node {
6
6
  index?: number;
7
7
  varIndex?: number;
8
8
  children: Record<string, Node>;
9
+ reverse: boolean;
10
+ constructor({ reverse }?: Partial<Node>);
11
+ newChildNode(): Node;
9
12
  insert(tokens: readonly string[], index: number, paramMap: ParamMap, context: Context): void;
10
13
  buildRegExpStr(): string;
11
14
  }
@@ -35,8 +35,12 @@ function compareKey(a, b) {
35
35
  return a.length === b.length ? (a < b ? -1 : 1) : b.length - a.length;
36
36
  }
37
37
  class Node {
38
- constructor() {
38
+ constructor({ reverse } = { reverse: false }) {
39
39
  this.children = {};
40
+ this.reverse = reverse;
41
+ }
42
+ newChildNode() {
43
+ return new Node({ reverse: this.reverse });
40
44
  }
41
45
  insert(tokens, index, paramMap, context) {
42
46
  var _a;
@@ -58,7 +62,7 @@ class Node {
58
62
  const regexpStr = pattern[2] || LABEL_REG_EXP_STR;
59
63
  node = this.children[regexpStr];
60
64
  if (!node) {
61
- node = this.children[regexpStr] = new Node();
65
+ node = this.children[regexpStr] = this.newChildNode();
62
66
  if (name !== '') {
63
67
  node.varIndex = context.varIndex++;
64
68
  }
@@ -68,19 +72,21 @@ class Node {
68
72
  }
69
73
  }
70
74
  else {
71
- node = (_a = this.children)[token] || (_a[token] = new Node());
75
+ node = (_a = this.children)[token] || (_a[token] = this.newChildNode());
72
76
  }
73
77
  node.insert(restTokens, index, paramMap, context);
74
78
  }
75
79
  buildRegExpStr() {
76
- const strList = Object.keys(this.children)
77
- .sort(compareKey)
78
- .map((k) => {
80
+ let childKeys = Object.keys(this.children).sort(compareKey);
81
+ if (this.reverse) {
82
+ childKeys = childKeys.reverse();
83
+ }
84
+ const strList = childKeys.map((k) => {
79
85
  const c = this.children[k];
80
86
  return (typeof c.varIndex === 'number' ? `(${k})@${c.varIndex}` : k) + c.buildRegExpStr();
81
87
  });
82
88
  if (typeof this.index === 'number') {
83
- strList.push(`#${this.index}`);
89
+ strList.unshift(`#${this.index}`);
84
90
  }
85
91
  if (strList.length === 0) {
86
92
  return '';