hono 1.4.4 → 1.4.7

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.
package/README.md CHANGED
@@ -73,6 +73,8 @@ Built-in middleware make _"**Write Less, do more**"_ in reality. You can use a l
73
73
  - [CORS](https://github.com/honojs/hono/tree/master/src/middleware/cors/)
74
74
  - [ETag](https://github.com/honojs/hono/tree/master/src/middleware/etag/)
75
75
  - [GraphQL Server](https://github.com/honojs/hono/tree/master/src/middleware/graphql-server/)
76
+ - [html](https://github.com/honojs/hono/tree/master/src/middleware/html/)
77
+ - [JSX](https://github.com/honojs/hono/tree/master/src/middleware/jsx/)
76
78
  - [JWT Authentication](https://github.com/honojs/hono/tree/master/src/middleware/jwt/)
77
79
  - [Logger](https://github.com/honojs/hono/tree/master/src/middleware/logger/)
78
80
  - [Mustache template engine](https://github.com/honojs/hono/tree/master/src/middleware/mustache/) (Only for Cloudflare Workers)
@@ -495,6 +497,8 @@ app.get('/foo', async (c) => {
495
497
 
496
498
  ### c.env
497
499
 
500
+ Environment variables, secrets, and KV namespaces are known as bindings. Regardless of type, bindings are always available as global variables and can be accessed via the context `c.env.BINDING_KEY`.
501
+
498
502
  ```ts
499
503
  // Environment object for Cloudflare Workers
500
504
  app.get('*', async c => {
package/dist/compose.js CHANGED
@@ -17,7 +17,7 @@ const compose = (middleware, onError, onNotFound) => {
17
17
  handler = next;
18
18
  if (!handler) {
19
19
  if (context instanceof context_1.Context && context.finalized === false && onNotFound) {
20
- context.res = onNotFound(context);
20
+ context.res = await onNotFound(context);
21
21
  }
22
22
  return Promise.resolve(context);
23
23
  }
package/dist/context.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  /// <reference types="@cloudflare/workers-types" />
2
+ import type { NotFoundHandler } from './hono';
2
3
  import type { StatusCode } from './utils/http-status';
3
4
  declare type Headers = Record<string, string>;
4
5
  export declare type Data = string | ArrayBuffer | ReadableStream;
@@ -15,8 +16,8 @@ export declare class Context<RequestParamKeyType extends string = string, E = En
15
16
  private _headers;
16
17
  private _res;
17
18
  private notFoundHandler;
18
- render: (template: string, params?: object, options?: object) => Promise<Response>;
19
- constructor(req: Request<RequestParamKeyType>, env?: E | undefined, event?: FetchEvent | undefined, notFoundHandler?: (c: Context<string, E>) => Response);
19
+ render: (content: string, params?: object, options?: object) => Response | Promise<Response>;
20
+ constructor(req: Request<RequestParamKeyType>, env?: E | undefined, event?: FetchEvent | undefined, notFoundHandler?: NotFoundHandler);
20
21
  get res(): Response;
21
22
  set res(_res: Response);
22
23
  header(name: string, value: string): void;
package/dist/hono.d.ts CHANGED
@@ -3,7 +3,7 @@ import { Context } from './context';
3
3
  import type { Env } from './context';
4
4
  import type { Router } from './router';
5
5
  export declare type Handler<RequestParamKeyType extends string = string, E = Env> = (c: Context<RequestParamKeyType, E>, next: Next) => Response | Promise<Response> | Promise<void> | Promise<Response | undefined>;
6
- export declare type NotFoundHandler<E = Env> = (c: Context<string, E>) => Response;
6
+ export declare type NotFoundHandler<E = Env> = (c: Context<string, E>) => Response | Promise<Response>;
7
7
  export declare type ErrorHandler<E = Env> = (err: Error, c: Context<string, E>) => Response;
8
8
  export declare type Next = () => Promise<void>;
9
9
  declare type ParamKeyName<NameWithPattern> = NameWithPattern extends `${infer Name}{${infer _Pattern}` ? Name : NameWithPattern;
package/dist/hono.js CHANGED
@@ -102,6 +102,9 @@ class Hono extends defineDynamicClass() {
102
102
  let context;
103
103
  try {
104
104
  context = await composed(c);
105
+ if (!context.finalized) {
106
+ throw new Error('Context is not finalized. You may forget returning Response object or `await next()`');
107
+ }
105
108
  }
106
109
  catch (err) {
107
110
  if (err instanceof Error) {
@@ -0,0 +1,8 @@
1
+ import type { Context } from '../../context';
2
+ import type { Next } from '../../hono';
3
+ export declare const bearerAuth: (options: {
4
+ token: string;
5
+ realm?: string;
6
+ prefix?: string;
7
+ hashFunction?: Function;
8
+ }) => (c: Context, next: Next) => Promise<void>;
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.bearerAuth = void 0;
4
+ const buffer_1 = require("../../utils/buffer");
5
+ const TOKEN_STRINGS = '[A-Za-z0-9._~+/-]+=*';
6
+ const PREFIX = 'Bearer';
7
+ const bearerAuth = (options) => {
8
+ if (!options.token) {
9
+ throw new Error('bearer auth middleware requires options for "token"');
10
+ }
11
+ if (!options.realm) {
12
+ options.realm = '';
13
+ }
14
+ if (!options.prefix) {
15
+ options.prefix = PREFIX;
16
+ }
17
+ const realm = options.realm?.replace(/"/g, '\\"');
18
+ return async (c, next) => {
19
+ const headerToken = c.req.headers.get('Authorization');
20
+ if (!headerToken) {
21
+ // No Authorization header
22
+ c.res = new Response('Unauthorized', {
23
+ status: 401,
24
+ headers: {
25
+ 'WWW-Authenticate': `${options.prefix} realm="` + realm + '"',
26
+ },
27
+ });
28
+ }
29
+ else {
30
+ const regexp = new RegExp('^' + options.prefix + ' +(' + TOKEN_STRINGS + ') *$');
31
+ const match = regexp.exec(headerToken);
32
+ if (!match) {
33
+ // Invalid Request
34
+ c.res = new Response('Bad Request', {
35
+ status: 400,
36
+ headers: {
37
+ 'WWW-Authenticate': `${options.prefix} error="invalid_request"`,
38
+ },
39
+ });
40
+ }
41
+ else {
42
+ const equal = await (0, buffer_1.timingSafeEqual)(options.token, match[1], options.hashFunction);
43
+ if (!equal) {
44
+ // Invalid Token
45
+ c.res = new Response('Unauthorized', {
46
+ status: 401,
47
+ headers: {
48
+ 'WWW-Authenticate': `${options.prefix} error="invalid_token"`,
49
+ },
50
+ });
51
+ }
52
+ else {
53
+ // Authorize OK
54
+ await next();
55
+ return;
56
+ }
57
+ }
58
+ }
59
+ };
60
+ };
61
+ exports.bearerAuth = bearerAuth;
@@ -0,0 +1,5 @@
1
+ export declare type HtmlEscapedString = string & {
2
+ isEscaped: true;
3
+ };
4
+ export declare const raw: (value: any) => HtmlEscapedString;
5
+ export declare const html: (strings: TemplateStringsArray, ...values: any[]) => HtmlEscapedString;
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.html = exports.raw = void 0;
4
+ const html_1 = require("../../utils/html");
5
+ const raw = (value) => {
6
+ const escapedString = new String(value);
7
+ escapedString.isEscaped = true;
8
+ return escapedString;
9
+ };
10
+ exports.raw = raw;
11
+ const html = (strings, ...values) => {
12
+ let result = '';
13
+ for (let i = 0, len = strings.length - 1; i < len; i++) {
14
+ result += strings[i];
15
+ const children = values[i] instanceof Array ? values[i].flat(Infinity) : [values[i]];
16
+ for (let i = 0, len = children.length; i < len; i++) {
17
+ const child = children[i];
18
+ if (typeof child === 'boolean' || child === null || child === undefined) {
19
+ continue;
20
+ }
21
+ else if (typeof child === 'object' && child.isEscaped) {
22
+ result += child;
23
+ }
24
+ else {
25
+ result += (0, html_1.escape)(child.toString());
26
+ }
27
+ }
28
+ }
29
+ result += strings[strings.length - 1];
30
+ return (0, exports.raw)(result);
31
+ };
32
+ exports.html = html;
@@ -0,0 +1,16 @@
1
+ import type { HtmlEscapedString } from '../../utils/html';
2
+ declare global {
3
+ namespace jsx.JSX {
4
+ interface IntrinsicElements {
5
+ [tagName: string]: Record<string, any>;
6
+ }
7
+ }
8
+ }
9
+ export declare const jsx: (tag: string | Function, props: Record<string, any>, ...children: (string | HtmlEscapedString)[]) => HtmlEscapedString;
10
+ declare type FC<T = Record<string, any>> = (props: T) => HtmlEscapedString;
11
+ export declare const memo: <T>(component: FC<T>, propsAreEqual?: (prevProps: Readonly<T>, nextProps: Readonly<T>) => boolean) => FC<T>;
12
+ export declare const Fragment: (props: {
13
+ key?: string;
14
+ children?: any;
15
+ }) => HtmlEscapedString;
16
+ export {};
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Fragment = exports.memo = exports.jsx = void 0;
4
+ const html_1 = require("../../utils/html");
5
+ const jsx = (tag, props, ...children) => {
6
+ if (typeof tag === 'function') {
7
+ return tag.call(null, { ...props, children: children.length <= 1 ? children[0] : children });
8
+ }
9
+ let result = tag !== '' ? `<${tag}` : '';
10
+ const propsKeys = Object.keys(props || {});
11
+ for (let i = 0, len = propsKeys.length; i < len; i++) {
12
+ const v = props[propsKeys[i]];
13
+ if (propsKeys[i] === 'dangerouslySetInnerHTML') {
14
+ if (children.length > 0) {
15
+ throw 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.';
16
+ }
17
+ const escapedString = new String(v.__html);
18
+ escapedString.isEscaped = true;
19
+ children = [escapedString];
20
+ continue;
21
+ }
22
+ else if (v === null || v === undefined) {
23
+ continue;
24
+ }
25
+ result += ` ${propsKeys[i]}="${(0, html_1.escape)(v.toString())}"`;
26
+ }
27
+ if (tag !== '') {
28
+ result += '>';
29
+ }
30
+ const flattenChildren = children.flat(Infinity);
31
+ for (let i = 0, len = flattenChildren.length; i < len; i++) {
32
+ const child = flattenChildren[i];
33
+ if (typeof child === 'boolean' || child === null || child === undefined) {
34
+ continue;
35
+ }
36
+ else if (typeof child === 'object' && child.isEscaped) {
37
+ result += child;
38
+ }
39
+ else {
40
+ result += (0, html_1.escape)(child.toString());
41
+ }
42
+ }
43
+ if (tag !== '') {
44
+ result += `</${tag}>`;
45
+ }
46
+ const escapedString = new String(result);
47
+ escapedString.isEscaped = true;
48
+ return escapedString;
49
+ };
50
+ exports.jsx = jsx;
51
+ const shallowEqual = (a, b) => {
52
+ if (a === b) {
53
+ return true;
54
+ }
55
+ const aKeys = Object.keys(a);
56
+ const bKeys = Object.keys(b);
57
+ if (aKeys.length !== bKeys.length) {
58
+ return false;
59
+ }
60
+ for (let i = 0, len = aKeys.length; i < len; i++) {
61
+ if (a[aKeys[i]] !== b[aKeys[i]]) {
62
+ return false;
63
+ }
64
+ }
65
+ return true;
66
+ };
67
+ const memo = (component, propsAreEqual = shallowEqual) => {
68
+ let computed = undefined;
69
+ let prevProps = undefined;
70
+ return ((props) => {
71
+ if (prevProps && !propsAreEqual(prevProps, props)) {
72
+ computed = undefined;
73
+ }
74
+ prevProps = props;
75
+ return (computed || (computed = component(props)));
76
+ });
77
+ };
78
+ exports.memo = memo;
79
+ const Fragment = (props) => {
80
+ return (0, exports.jsx)('', {}, ...(props.children || []));
81
+ };
82
+ exports.Fragment = Fragment;
@@ -1,3 +1,3 @@
1
1
  import type { MustacheOptions } from './mustache';
2
- declare const module: (options?: MustacheOptions) => import("../../hono").Handler<string, import("../../context").Env>;
2
+ declare const module: (options?: MustacheOptions) => (c: import("../../context").Context<string, import("../../context").Env>, next: import("../../hono").Next) => Promise<void>;
3
3
  export { module as mustache };
@@ -1,8 +1,9 @@
1
1
  /// <reference types="@cloudflare/workers-types" />
2
- import type { Handler } from '../../hono';
2
+ import type { Context } from '../../context';
3
+ import type { Next } from '../../hono';
3
4
  export declare type MustacheOptions = {
4
5
  root: string;
5
6
  manifest?: object | string;
6
7
  namespace?: KVNamespace;
7
8
  };
8
- export declare const mustache: (init?: MustacheOptions) => Handler;
9
+ export declare const mustache: (init?: MustacheOptions) => (c: Context, next: Next) => Promise<void>;
@@ -5,5 +5,6 @@ declare type Algorithm = {
5
5
  declare type Data = string | object | boolean;
6
6
  export declare const sha256: (data: Data) => Promise<string | null>;
7
7
  export declare const sha1: (data: Data) => Promise<string | null>;
8
+ export declare const md5: (data: Data) => Promise<string | null>;
8
9
  export declare const createHash: (data: Data, algorithm: Algorithm) => Promise<string | null>;
9
10
  export {};
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createHash = exports.sha1 = exports.sha256 = void 0;
3
+ exports.createHash = exports.md5 = exports.sha1 = exports.sha256 = void 0;
4
4
  const sha256 = async (data) => {
5
5
  const algorithm = { name: 'SHA-256', alias: 'sha256' };
6
6
  const hash = await (0, exports.createHash)(data, algorithm);
@@ -13,6 +13,12 @@ const sha1 = async (data) => {
13
13
  return hash;
14
14
  };
15
15
  exports.sha1 = sha1;
16
+ const md5 = async (data) => {
17
+ const algorithm = { name: 'MD5', alias: 'md5' };
18
+ const hash = await (0, exports.createHash)(data, algorithm);
19
+ return hash;
20
+ };
21
+ exports.md5 = md5;
16
22
  const createHash = async (data, algorithm) => {
17
23
  if (crypto && crypto.subtle) {
18
24
  const buffer = await crypto.subtle.digest({
@@ -0,0 +1,4 @@
1
+ export declare type HtmlEscapedString = string & {
2
+ isEscaped: true;
3
+ };
4
+ export declare const escape: (str: string) => string;
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.escape = void 0;
4
+ const entityMap = {
5
+ '&': '&amp;',
6
+ '<': '&lt;',
7
+ '>': '&gt;',
8
+ '"': '&quot;',
9
+ };
10
+ const escapeRe = new RegExp(`[${Object.keys(entityMap).join('')}]`, 'g');
11
+ const replaceFn = (m) => entityMap[m];
12
+ const escape = (str) => {
13
+ return str.replace(escapeRe, replaceFn);
14
+ };
15
+ exports.escape = escape;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hono",
3
- "version": "1.4.4",
3
+ "version": "1.4.7",
4
4
  "description": "Ultrafast web framework for Cloudflare Workers.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -18,11 +18,14 @@
18
18
  "exports": {
19
19
  ".": "./dist/index.js",
20
20
  "./basic-auth": "./dist/middleware/basic-auth/index.js",
21
+ "./bearer-auth": "./dist/middleware/bearer-auth/index.js",
21
22
  "./body-parse": "./dist/middleware/body-parse/index.js",
22
23
  "./cookie": "./dist/middleware/cookie/index.js",
23
24
  "./cors": "./dist/middleware/cors/index.js",
24
25
  "./etag": "./dist/middleware/etag/index.js",
25
26
  "./graphql-server": "./dist/middleware/graphql-server/index.js",
27
+ "./html": "./dist/middleware/html/index.js",
28
+ "./jsx": "./dist/middleware/jsx/index.js",
26
29
  "./jwt": "./dist/middleware/jwt/index.js",
27
30
  "./logger": "./dist/middleware/logger/index.js",
28
31
  "./mustache": "./dist/middleware/mustache/index.js",
@@ -41,6 +44,9 @@
41
44
  "basic-auth": [
42
45
  "./dist/middleware/basic-auth"
43
46
  ],
47
+ "bearer-auth": [
48
+ "./dist/middleware/bearer-auth"
49
+ ],
44
50
  "body-parse": [
45
51
  "./dist/middleware/body-parse"
46
52
  ],
@@ -56,6 +62,12 @@
56
62
  "graphql-server": [
57
63
  "./dist/middleware/graphql-server"
58
64
  ],
65
+ "html": [
66
+ "./dist/middleware/html"
67
+ ],
68
+ "jsx": [
69
+ "./dist/middleware/jsx"
70
+ ],
59
71
  "jwt": [
60
72
  "./dist/middleware/jwt"
61
73
  ],