h3 0.4.1 → 0.4.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
@@ -29,8 +29,11 @@
29
29
  # Using npm
30
30
  npm install h3
31
31
 
32
- # Using yarn
33
- yarn add h3
32
+ # Using pnpm
33
+ pnpm add h3
34
+
35
+ # Using pnpm
36
+ pnpm add h3
34
37
  ```
35
38
 
36
39
  ## Usage
package/dist/index.cjs CHANGED
@@ -159,6 +159,16 @@ function appendHeader(res, name, value) {
159
159
  }
160
160
  res.setHeader(name, current.concat(value));
161
161
  }
162
+ function isStream(data) {
163
+ return typeof data === "object" && typeof data.pipe === "function" && typeof data.on === "function";
164
+ }
165
+ function sendStream(res, data) {
166
+ return new Promise((resolve, reject) => {
167
+ data.pipe(res);
168
+ data.on("end", () => resolve(void 0));
169
+ data.on("error", (error) => reject(createError(error)));
170
+ });
171
+ }
162
172
 
163
173
  function useCookies(req) {
164
174
  return cookieEs.parse(req.headers.cookie || "");
@@ -280,6 +290,8 @@ function createHandle(stack, options) {
280
290
  const type = typeof val;
281
291
  if (type === "string") {
282
292
  return send(res, val, MIMES.html);
293
+ } else if (isStream(val)) {
294
+ return sendStream(res, val);
283
295
  } else if (type === "object" || type === "boolean" || type === "number") {
284
296
  if (val && val.buffer) {
285
297
  return send(res, val);
@@ -361,11 +373,13 @@ exports.defineHandle = defineHandle;
361
373
  exports.defineMiddleware = defineMiddleware;
362
374
  exports.deleteCookie = deleteCookie;
363
375
  exports.isMethod = isMethod;
376
+ exports.isStream = isStream;
364
377
  exports.lazyHandle = lazyHandle;
365
378
  exports.promisifyHandle = promisifyHandle;
366
379
  exports.send = send;
367
380
  exports.sendError = sendError;
368
381
  exports.sendRedirect = sendRedirect;
382
+ exports.sendStream = sendStream;
369
383
  exports.setCookie = setCookie;
370
384
  exports.use = use;
371
385
  exports.useBase = useBase;
package/dist/index.d.ts CHANGED
@@ -250,10 +250,12 @@ declare function useMethod(req: IncomingMessage, defaultMethod?: HTTPMethod): HT
250
250
  declare function isMethod(req: IncomingMessage, expected: HTTPMethod | HTTPMethod[], allowHead?: boolean): boolean;
251
251
  declare function assertMethod(req: IncomingMessage, expected: HTTPMethod | HTTPMethod[], allowHead?: boolean): void;
252
252
 
253
- declare function send(res: ServerResponse, data: any, type?: string): Promise<unknown>;
253
+ declare function send(res: ServerResponse, data: any, type?: string): Promise<void>;
254
254
  declare function defaultContentType(res: ServerResponse, type?: string): void;
255
- declare function sendRedirect(res: ServerResponse, location: string, code?: number): Promise<unknown>;
255
+ declare function sendRedirect(res: ServerResponse, location: string, code?: number): Promise<void>;
256
256
  declare function appendHeader(res: ServerResponse, name: string, value: string): void;
257
+ declare function isStream(data: any): boolean;
258
+ declare function sendStream(res: ServerResponse, data: any): Promise<unknown>;
257
259
 
258
260
  declare type RouterMethod = Lowercase<HTTPMethod>;
259
261
  declare type HandleWithParams = Handle<any, {
@@ -267,4 +269,4 @@ interface Router extends AddRouteShortcuts {
267
269
  }
268
270
  declare function createRouter(): Router;
269
271
 
270
- export { AddRouteShortcuts, AddWithMethod, App, AppOptions, AppUse, H3Error, Handle, HandleWithParams, InputLayer, InputStack, Layer, LazyHandle, MIMES, Matcher, Middleware, PHandle, Router, RouterMethod, Stack, appendHeader, assertMethod, callHandle, createApp, createError, createHandle, createRouter, defaultContentType, defineHandle, defineMiddleware, deleteCookie, isMethod, lazyHandle, promisifyHandle, send, sendError, sendRedirect, setCookie, use, useBase, useBody, useCookie, useCookies, useMethod, useQuery, useRawBody };
272
+ export { AddRouteShortcuts, AddWithMethod, App, AppOptions, AppUse, H3Error, Handle, HandleWithParams, InputLayer, InputStack, Layer, LazyHandle, MIMES, Matcher, Middleware, PHandle, Router, RouterMethod, Stack, appendHeader, assertMethod, callHandle, createApp, createError, createHandle, createRouter, defaultContentType, defineHandle, defineMiddleware, deleteCookie, isMethod, isStream, lazyHandle, promisifyHandle, send, sendError, sendRedirect, sendStream, setCookie, use, useBase, useBody, useCookie, useCookies, useMethod, useQuery, useRawBody };
package/dist/index.mjs CHANGED
@@ -151,6 +151,16 @@ function appendHeader(res, name, value) {
151
151
  }
152
152
  res.setHeader(name, current.concat(value));
153
153
  }
154
+ function isStream(data) {
155
+ return typeof data === "object" && typeof data.pipe === "function" && typeof data.on === "function";
156
+ }
157
+ function sendStream(res, data) {
158
+ return new Promise((resolve, reject) => {
159
+ data.pipe(res);
160
+ data.on("end", () => resolve(void 0));
161
+ data.on("error", (error) => reject(createError(error)));
162
+ });
163
+ }
154
164
 
155
165
  function useCookies(req) {
156
166
  return parse(req.headers.cookie || "");
@@ -272,6 +282,8 @@ function createHandle(stack, options) {
272
282
  const type = typeof val;
273
283
  if (type === "string") {
274
284
  return send(res, val, MIMES.html);
285
+ } else if (isStream(val)) {
286
+ return sendStream(res, val);
275
287
  } else if (type === "object" || type === "boolean" || type === "number") {
276
288
  if (val && val.buffer) {
277
289
  return send(res, val);
@@ -339,4 +351,4 @@ function createRouter() {
339
351
  return router;
340
352
  }
341
353
 
342
- export { H3Error, MIMES, appendHeader, assertMethod, callHandle, createApp, createError, createHandle, createRouter, defaultContentType, defineHandle, defineMiddleware, deleteCookie, isMethod, lazyHandle, promisifyHandle, send, sendError, sendRedirect, setCookie, use, useBase, useBody, useCookie, useCookies, useMethod, useQuery, useRawBody };
354
+ export { H3Error, MIMES, appendHeader, assertMethod, callHandle, createApp, createError, createHandle, createRouter, defaultContentType, defineHandle, defineMiddleware, deleteCookie, isMethod, isStream, lazyHandle, promisifyHandle, send, sendError, sendRedirect, sendStream, setCookie, use, useBase, useBody, useCookie, useCookies, useMethod, useQuery, useRawBody };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "h3",
3
- "version": "0.4.1",
3
+ "version": "0.4.2",
4
4
  "description": "Tiny JavaScript Server",
5
5
  "repository": "unjs/h3",
6
6
  "license": "MIT",
@@ -17,14 +17,6 @@
17
17
  "files": [
18
18
  "dist"
19
19
  ],
20
- "scripts": {
21
- "build": "unbuild",
22
- "dev": "jiti ./playground/index.ts",
23
- "lint": "eslint --ext ts,mjs,cjs .",
24
- "profile": "0x -o -D .profile -P 'autocannon -c 100 -p 10 -d 40 http://localhost:$PORT' ./playground/server.cjs",
25
- "release": "yarn lint && yarn test && yarn build && standard-version && npm publish && git push --follow-tags",
26
- "test": "vitest run"
27
- },
28
20
  "dependencies": {
29
21
  "cookie-es": "^0.5.0",
30
22
  "destr": "^1.1.0",
@@ -51,5 +43,15 @@
51
43
  "typescript": "latest",
52
44
  "unbuild": "latest",
53
45
  "vitest": "latest"
54
- }
55
- }
46
+ },
47
+ "packageManager": "pnpm@6.32.3",
48
+ "scripts": {
49
+ "build": "unbuild",
50
+ "dev": "jiti ./playground/index.ts",
51
+ "lint": "eslint --ext ts,mjs,cjs .",
52
+ "profile": "0x -o -D .profile -P 'autocannon -c 100 -p 10 -d 40 http://localhost:$PORT' ./playground/server.cjs",
53
+ "release": "pnpm lint && pnpm test && pnpm build && standard-version && pnpm publish && git push --follow-tags",
54
+ "test": "vitest run"
55
+ },
56
+ "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 pnpm\npnpm 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
+ }