h3 0.6.0 → 0.7.2

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
@@ -75,7 +75,7 @@ const app = createApp()
75
75
 
76
76
  const router = createRouter()
77
77
  .get('/', () => 'Hello World!')
78
- .get('/hello/:name', req => `Hello ${req.params.name}!`)
78
+ .get('/hello/:name', req => `Hello ${req.context.params.name}!`)
79
79
 
80
80
  app.use(router)
81
81
  ```
package/dist/index.cjs CHANGED
@@ -346,10 +346,12 @@ function createEvent(req, res) {
346
346
  const event = {
347
347
  __is_event__: true,
348
348
  req,
349
- res
349
+ res,
350
+ context: {}
350
351
  };
351
352
  event.event = event;
352
353
  req.event = event;
354
+ req.context = event.context;
353
355
  req.req = req;
354
356
  req.res = res;
355
357
  res.event = event;
@@ -501,8 +503,9 @@ function createRouter() {
501
503
  statusMessage: `Method ${method} is not allowed on this route.`
502
504
  });
503
505
  }
504
- event.event.params = matched.params || {};
505
- event.req.params = event.event.params;
506
+ const params = matched.params || {};
507
+ event.event.context.params = params;
508
+ event.req.context.params = params;
506
509
  return handler(event);
507
510
  });
508
511
  return router;
package/dist/index.d.ts CHANGED
@@ -7,18 +7,18 @@ interface H3Event {
7
7
  event: H3Event;
8
8
  req: IncomingMessage;
9
9
  res: ServerResponse;
10
- /** Request params only filled with h3 Router handlers */
11
- params?: Record<string, any>;
10
+ context: Record<string, any>;
12
11
  }
13
12
  declare type CompatibilityEvent = H3Event | IncomingMessage;
14
13
  declare type _JSONValue<T = string | number | boolean> = T | T[] | Record<string, T>;
15
14
  declare type JSONValue = _JSONValue<_JSONValue>;
16
- declare type H3Response = void | JSONValue | Buffer;
17
- interface EventHandler {
15
+ declare type _H3Response = void | JSONValue | Buffer;
16
+ declare type H3Response = _H3Response | Promise<_H3Response>;
17
+ interface EventHandler<T extends H3Response = H3Response> {
18
18
  '__is_handler__'?: true;
19
- (event: CompatibilityEvent): H3Response | Promise<H3Response>;
19
+ (event: CompatibilityEvent): T;
20
20
  }
21
- declare function defineEventHandler(handler: EventHandler): EventHandler;
21
+ declare function defineEventHandler<T extends H3Response = H3Response>(handler: EventHandler<T>): EventHandler<T>;
22
22
  declare const eventHandler: typeof defineEventHandler;
23
23
  declare type LazyEventHandler = () => EventHandler | Promise<EventHandler>;
24
24
  declare function defineLazyEventHandler(factory: LazyEventHandler): EventHandler;
@@ -35,10 +35,9 @@ declare function isEvent(input: any): input is H3Event;
35
35
 
36
36
  interface CompatibilityRequestProps {
37
37
  event: H3Event;
38
+ context: Record<string, any>;
38
39
  /** Only available with connect and press */
39
40
  originalUrl?: string;
40
- /** Request params only filled with h3 Router handlers */
41
- params?: Record<string, any>;
42
41
  }
43
42
  interface IncomingMessage extends http.IncomingMessage, CompatibilityRequestProps {
44
43
  req: H3Event['req'];
@@ -54,7 +53,7 @@ declare type PromisifiedHandler = Handler<Promise<any>>;
54
53
  declare type Middleware = (req: IncomingMessage, res: ServerResponse, next: (err?: Error) => any) => any;
55
54
  declare type LazyHandler = () => Handler | Promise<Handler>;
56
55
  declare type Encoding = false | 'ascii' | 'utf8' | 'utf-8' | 'utf16le' | 'ucs2' | 'ucs-2' | 'base64' | 'latin1' | 'binary' | 'hex';
57
- declare type HTTPMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'CONNECT' | 'OPTIONS' | 'TRACE';
56
+ declare type HTTPMethod = 'GET' | 'HEAD' | 'PATCH' | 'POST' | 'PUT' | 'DELETE' | 'CONNECT' | 'OPTIONS' | 'TRACE';
58
57
 
59
58
  interface Layer {
60
59
  route: string;
@@ -92,7 +91,7 @@ interface AppOptions {
92
91
  }
93
92
  declare function createApp(options?: AppOptions): App;
94
93
  declare function use(app: App, arg1: string | Handler | InputLayer | InputLayer[], arg2?: Handler | Partial<InputLayer> | Handler[] | Middleware | Middleware[], arg3?: Partial<InputLayer>): App;
95
- declare function createAppEventHandler(stack: Stack, options: AppOptions): EventHandler;
94
+ declare function createAppEventHandler(stack: Stack, options: AppOptions): EventHandler<Promise<void>>;
96
95
 
97
96
  /**
98
97
  * H3 Runtime Error
@@ -244,4 +243,4 @@ interface Router extends AddRouteShortcuts {
244
243
  }
245
244
  declare function createRouter(): Router;
246
245
 
247
- export { AddRouteShortcuts, App, AppOptions, AppUse, CacheConditions, CompatibilityEvent, CompatibilityEventHandler, DynamicEventHandler, Encoding, EventHandler, H3Error, H3Event, H3Response, HTTPMethod, Handler, IncomingMessage, InputLayer, InputStack, JSONValue, Layer, LazyEventHandler, LazyHandler, MIMES, Matcher, Middleware, NodeHandler, PromisifiedHandler, Router, RouterMethod, RouterUse, ServerResponse, Stack, _JSONValue, appendHeader, assertMethod, callHandler, createApp, createAppEventHandler, createError, createEvent, createRouter, defaultContentType, defineEventHandler, defineHandle, defineHandler, defineLazyEventHandler, defineLazyHandler, defineMiddleware, deleteCookie, dynamicEventHandler, eventHandler, handleCacheHeaders, isError, isEvent, isEventHandler, isMethod, isStream, lazyEventHandler, lazyHandle, promisifyHandle, promisifyHandler, send, sendError, sendRedirect, sendStream, setCookie, toEventHandler, use, useBase, useBody, useCookie, useCookies, useMethod, useQuery, useRawBody };
246
+ export { AddRouteShortcuts, App, AppOptions, AppUse, CacheConditions, CompatibilityEvent, CompatibilityEventHandler, DynamicEventHandler, Encoding, EventHandler, H3Error, H3Event, H3Response, HTTPMethod, Handler, IncomingMessage, InputLayer, InputStack, JSONValue, Layer, LazyEventHandler, LazyHandler, MIMES, Matcher, Middleware, NodeHandler, PromisifiedHandler, Router, RouterMethod, RouterUse, ServerResponse, Stack, appendHeader, assertMethod, callHandler, createApp, createAppEventHandler, createError, createEvent, createRouter, defaultContentType, defineEventHandler, defineHandle, defineHandler, defineLazyEventHandler, defineLazyHandler, defineMiddleware, deleteCookie, dynamicEventHandler, eventHandler, handleCacheHeaders, isError, isEvent, isEventHandler, isMethod, isStream, lazyEventHandler, lazyHandle, promisifyHandle, promisifyHandler, send, sendError, sendRedirect, sendStream, setCookie, toEventHandler, use, useBase, useBody, useCookie, useCookies, useMethod, useQuery, useRawBody };
package/dist/index.mjs CHANGED
@@ -338,10 +338,12 @@ function createEvent(req, res) {
338
338
  const event = {
339
339
  __is_event__: true,
340
340
  req,
341
- res
341
+ res,
342
+ context: {}
342
343
  };
343
344
  event.event = event;
344
345
  req.event = event;
346
+ req.context = event.context;
345
347
  req.req = req;
346
348
  req.res = res;
347
349
  res.event = event;
@@ -493,8 +495,9 @@ function createRouter() {
493
495
  statusMessage: `Method ${method} is not allowed on this route.`
494
496
  });
495
497
  }
496
- event.event.params = matched.params || {};
497
- event.req.params = event.event.params;
498
+ const params = matched.params || {};
499
+ event.event.context.params = params;
500
+ event.req.context.params = params;
498
501
  return handler(event);
499
502
  });
500
503
  return router;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "h3",
3
- "version": "0.6.0",
3
+ "version": "0.7.2",
4
4
  "description": "Tiny JavaScript Server",
5
5
  "repository": "unjs/h3",
6
6
  "license": "MIT",
@@ -54,5 +54,5 @@
54
54
  "release": "pnpm lint && pnpm test && pnpm build && standard-version && pnpm publish && git push --follow-tags",
55
55
  "test": "vitest run"
56
56
  },
57
- "readme": "[![npm downloads](https://img.shields.io/npm/dm/h3.svg?style=flat-square)](https://npmjs.com/package/h3)\n[![version](https://img.shields.io/npm/v/h3/latest.svg?style=flat-square)](https://npmjs.com/package/h3)\n[![bundlephobia](https://img.shields.io/bundlephobia/min/h3/latest.svg?style=flat-square)](https://bundlephobia.com/result?p=h3)\n[![build status](https://img.shields.io/github/workflow/status/unjs/h3/ci/main?style=flat-square)](https://github.com/unjs/h3/actions)\n[![coverage](https://img.shields.io/codecov/c/gh/unjs/h3/main?style=flat-square)](https://codecov.io/gh/unjs/h3)\n[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue?style=flat-square)](https://www.jsdocs.io/package/h3)\n\n> H3 is a minimal h(ttp) framework built for high performance and portability\n\n<!-- ![h3 - Tiny JavaScript Server](.github/banner.svg) -->\n\n## Features\n\n✔️ &nbsp;**Portable:** Works perfectly in Serverless, Workers, and Node.js\n\n✔️ &nbsp;**Compatible:** Support connect/express middleware\n\n✔️ &nbsp;**Minimal:** Small, tree-shakable and zero-dependency\n\n✔️ &nbsp;**Modern:** Native promise support\n\n✔️ &nbsp;**Extendable:** Ships with a set of composable utilities but can be extended\n\n✔️ &nbsp;**Router:** Super fast route matching using [unjs/radix3](https://github.com/unjs/radix3)\n\n## Install\n\n```bash\n# Using npm\nnpm install h3\n\n# Using yarn\nyarn add h3\n\n# Using pnpm\npnpm add h3\n```\n\n## Usage\n\n```ts\nimport { createServer } from 'http'\nimport { createApp } from 'h3'\n\nconst app = createApp()\napp.use('/', () => 'Hello world!')\n\ncreateServer(app).listen(process.env.PORT || 3000)\n```\n\n<details>\n <summary>Example using <a href=\"https://github.com/unjs/listhen\">listhen</a> for an elegant listener.</summary>\n\n```ts\nimport { createApp } from 'h3'\nimport { listen } from 'listhen'\n\nconst app = createApp()\napp.use('/', () => 'Hello world!')\n\nlisten(app)\n```\n</details>\n\n## Router\n\nThe `app` instance created by `h3` uses a middleware stack (see [how it works](#how-it-works)) with the ability to match route prefix and apply matched middleware.\n\nTo opt-in using a more advanced and convenient routing system, we can create a router instance and register it to app instance.\n\n```ts\nimport { createApp, createRouter } from 'h3'\n\nconst app = createApp()\n\nconst router = createRouter()\n .get('/', () => 'Hello World!')\n .get('/hello/:name', req => `Hello ${req.params.name}!`)\n\napp.use(router)\n```\n\n**Tip:** We can register same route more than once with different methods.\n\nRoutes are internally stored in a [Radix Tree](https://en.wikipedia.org/wiki/Radix_tree) and matched using [unjs/radix3](https://github.com/unjs/radix3).\n\n## More usage examples\n\n```js\n// Handle can directly return object or Promise<object> for JSON response\napp.use('/api', (req) => ({ url: req.url }))\n\n// We can have better matching other than quick prefix match\napp.use('/odd', () => 'Is odd!', { match: url => url.substr(1) % 2 })\n\n// Handle can directly return string for HTML response\napp.use(() => '<h1>Hello world!</h1>')\n\n// We can chain calls to .use()\napp.use('/1', () => '<h1>Hello world!</h1>')\n .use('/2', () => '<h1>Goodbye!</h1>')\n\n// Legacy middleware with 3rd argument are automatically promisified\napp.use((req, res, next) => { req.setHeader('X-Foo', 'bar'); next() })\n\n// Force promisify a legacy middleware\n// app.use(someMiddleware, { promisify: true })\n\n// Lazy loaded routes using { lazy: true }\n// app.use('/big', () => import('./big'), { lazy: true })\n```\n\n## Utilities\n\nInstead of adding helpers to `req` and `res`, h3 exposes them as composable utilities.\n\n- `useRawBody(req, encoding?)`\n- `useBody(req)`\n- `useCookies(req)`\n- `useCookie(req, name)`\n- `setCookie(res, name, value, opts?)`\n- `deleteCookie(res, name, opts?)`\n- `useQuery(req)`\n- `send(res, data, type?)`\n- `sendRedirect(res, location, code=302)`\n- `appendHeader(res, name, value)`\n- `createError({ statusCode, statusMessage, data? })`\n- `sendError(res, error, debug?)`\n- `defineHandle(handle)`\n- `defineMiddleware(middlware)`\n- `useMethod(req, default?)`\n- `isMethod(req, expected, allowHead?)`\n- `assertMethod(req, expected, allowHead?)`\n\n👉 You can learn more about usage in [JSDocs Documentation](https://www.jsdocs.io/package/h3#package-functions).\n\n## How it works?\n\nUsing `createApp`, it returns a standard `(req, res)` handler function and internally an array called middleware stack. using`use()` method we can add an item to this internal stack.\n\nWhen a request comes, each stack item that matches the route will be called and resolved until [`res.writableEnded`](https://nodejs.org/api/http.html#http_response_writableended) flag is set, which means the response is sent. If `writableEnded` is not set after all middleware, a `404` error will be thrown. And if one of the stack items resolves to a value, it will be serialized and sent as response as a shorthand method to sending responses.\n\nFor maximum compatibility with connect/express middleware (`req, res, next?` signature), h3 converts classic middleware into a promisified version ready to use with stack runner:\n\n- If middleware has 3rd next/callback param, the promise will `resolve/reject` when called\n- If middleware returns a promise, it will be **chained** to the main promise\n- If calling middleware throws an immediate error, the promise will be rejected\n- On `close` and `error` events of res, the promise will `resolve/reject` (to ensure if middleware simply calls `res.end`)\n\n## License\n\nMIT\n"
57
+ "readme": "[![npm downloads](https://img.shields.io/npm/dm/h3.svg?style=flat-square)](https://npmjs.com/package/h3)\n[![version](https://img.shields.io/npm/v/h3/latest.svg?style=flat-square)](https://npmjs.com/package/h3)\n[![bundlephobia](https://img.shields.io/bundlephobia/min/h3/latest.svg?style=flat-square)](https://bundlephobia.com/result?p=h3)\n[![build status](https://img.shields.io/github/workflow/status/unjs/h3/ci/main?style=flat-square)](https://github.com/unjs/h3/actions)\n[![coverage](https://img.shields.io/codecov/c/gh/unjs/h3/main?style=flat-square)](https://codecov.io/gh/unjs/h3)\n[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue?style=flat-square)](https://www.jsdocs.io/package/h3)\n\n> H3 is a minimal h(ttp) framework built for high performance and portability\n\n<!-- ![h3 - Tiny JavaScript Server](.github/banner.svg) -->\n\n## Features\n\n✔️ &nbsp;**Portable:** Works perfectly in Serverless, Workers, and Node.js\n\n✔️ &nbsp;**Compatible:** Support connect/express middleware\n\n✔️ &nbsp;**Minimal:** Small, tree-shakable and zero-dependency\n\n✔️ &nbsp;**Modern:** Native promise support\n\n✔️ &nbsp;**Extendable:** Ships with a set of composable utilities but can be extended\n\n✔️ &nbsp;**Router:** Super fast route matching using [unjs/radix3](https://github.com/unjs/radix3)\n\n## Install\n\n```bash\n# Using npm\nnpm install h3\n\n# Using yarn\nyarn add h3\n\n# Using pnpm\npnpm add h3\n```\n\n## Usage\n\n```ts\nimport { createServer } from 'http'\nimport { createApp } from 'h3'\n\nconst app = createApp()\napp.use('/', () => 'Hello world!')\n\ncreateServer(app).listen(process.env.PORT || 3000)\n```\n\n<details>\n <summary>Example using <a href=\"https://github.com/unjs/listhen\">listhen</a> for an elegant listener.</summary>\n\n```ts\nimport { createApp } from 'h3'\nimport { listen } from 'listhen'\n\nconst app = createApp()\napp.use('/', () => 'Hello world!')\n\nlisten(app)\n```\n</details>\n\n## Router\n\nThe `app` instance created by `h3` uses a middleware stack (see [how it works](#how-it-works)) with the ability to match route prefix and apply matched middleware.\n\nTo opt-in using a more advanced and convenient routing system, we can create a router instance and register it to app instance.\n\n```ts\nimport { createApp, createRouter } from 'h3'\n\nconst app = createApp()\n\nconst router = createRouter()\n .get('/', () => 'Hello World!')\n .get('/hello/:name', req => `Hello ${req.context.params.name}!`)\n\napp.use(router)\n```\n\n**Tip:** We can register same route more than once with different methods.\n\nRoutes are internally stored in a [Radix Tree](https://en.wikipedia.org/wiki/Radix_tree) and matched using [unjs/radix3](https://github.com/unjs/radix3).\n\n## More usage examples\n\n```js\n// Handle can directly return object or Promise<object> for JSON response\napp.use('/api', (req) => ({ url: req.url }))\n\n// We can have better matching other than quick prefix match\napp.use('/odd', () => 'Is odd!', { match: url => url.substr(1) % 2 })\n\n// Handle can directly return string for HTML response\napp.use(() => '<h1>Hello world!</h1>')\n\n// We can chain calls to .use()\napp.use('/1', () => '<h1>Hello world!</h1>')\n .use('/2', () => '<h1>Goodbye!</h1>')\n\n// Legacy middleware with 3rd argument are automatically promisified\napp.use((req, res, next) => { req.setHeader('X-Foo', 'bar'); next() })\n\n// Force promisify a legacy middleware\n// app.use(someMiddleware, { promisify: true })\n\n// Lazy loaded routes using { lazy: true }\n// app.use('/big', () => import('./big'), { lazy: true })\n```\n\n## Utilities\n\nInstead of adding helpers to `req` and `res`, h3 exposes them as composable utilities.\n\n- `useRawBody(req, encoding?)`\n- `useBody(req)`\n- `useCookies(req)`\n- `useCookie(req, name)`\n- `setCookie(res, name, value, opts?)`\n- `deleteCookie(res, name, opts?)`\n- `useQuery(req)`\n- `send(res, data, type?)`\n- `sendRedirect(res, location, code=302)`\n- `appendHeader(res, name, value)`\n- `createError({ statusCode, statusMessage, data? })`\n- `sendError(res, error, debug?)`\n- `defineHandle(handle)`\n- `defineMiddleware(middlware)`\n- `useMethod(req, default?)`\n- `isMethod(req, expected, allowHead?)`\n- `assertMethod(req, expected, allowHead?)`\n\n👉 You can learn more about usage in [JSDocs Documentation](https://www.jsdocs.io/package/h3#package-functions).\n\n## How it works?\n\nUsing `createApp`, it returns a standard `(req, res)` handler function and internally an array called middleware stack. using`use()` method we can add an item to this internal stack.\n\nWhen a request comes, each stack item that matches the route will be called and resolved until [`res.writableEnded`](https://nodejs.org/api/http.html#http_response_writableended) flag is set, which means the response is sent. If `writableEnded` is not set after all middleware, a `404` error will be thrown. And if one of the stack items resolves to a value, it will be serialized and sent as response as a shorthand method to sending responses.\n\nFor maximum compatibility with connect/express middleware (`req, res, next?` signature), h3 converts classic middleware into a promisified version ready to use with stack runner:\n\n- If middleware has 3rd next/callback param, the promise will `resolve/reject` when called\n- If middleware returns a promise, it will be **chained** to the main promise\n- If calling middleware throws an immediate error, the promise will be rejected\n- On `close` and `error` events of res, the promise will `resolve/reject` (to ensure if middleware simply calls `res.end`)\n\n## License\n\nMIT\n"
58
58
  }