@plinthjs/http 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/README.md +157 -2
- package/dist/index.cjs +3082 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +1626 -0
- package/dist/index.d.ts +1626 -0
- package/dist/index.js +3052 -0
- package/dist/index.js.map +1 -0
- package/package.json +58 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 The Plinth contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,158 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @plinthjs/http
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Plinth's HTTP layer. `Request` and
|
|
4
|
+
`Response` value objects, an async middleware pipeline, a `Router` (parameters, constraints, groups,
|
|
5
|
+
named routes, resource routes, model binding, signed URLs, fallback), an HTTP exception hierarchy
|
|
6
|
+
with its `ExceptionHandler`, the `HttpKernel` that drives the request lifecycle over the
|
|
7
|
+
`@plinthjs/core` container, and a server adapter over Node's built-in `node:http`.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
npm install @plinthjs/http
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Usage
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
import { gracefulShutdown, HttpKernel, Response, Router, serve } from '@plinthjs/http'
|
|
19
|
+
|
|
20
|
+
const router = new Router()
|
|
21
|
+
|
|
22
|
+
router.get('/', () => 'Hello Plinth') // strings and objects are coerced to responses
|
|
23
|
+
router.get('/users/{id}', (req) => Response.json({ id: req.param('id') })).whereNumber('id')
|
|
24
|
+
router.get('/posts/{page?}', (req) => Response.json({ page: req.param('page', '1') }))
|
|
25
|
+
|
|
26
|
+
router.group({ prefix: '/api', middleware: 'auth' }, (r) => {
|
|
27
|
+
r.post('/posts', async (req) => Response.json(req.only(['title', 'body']), 201))
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
router.fallback(() => Response.json({ message: 'Not Found' }, 404))
|
|
31
|
+
|
|
32
|
+
const kernel = new HttpKernel(router)
|
|
33
|
+
const server = await serve(kernel, 3000) // rejects on listen errors such as EADDRINUSE
|
|
34
|
+
gracefulShutdown(server, { timeout: 10_000, onShutdown: () => db.close() })
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
`createServer(kernel, { maxBodyBytes })` returns the bare `node:http` server when you want to
|
|
38
|
+
listen yourself; oversized bodies are refused with a 413.
|
|
39
|
+
|
|
40
|
+
## Middleware
|
|
41
|
+
|
|
42
|
+
A middleware is `(req, next) => Promise<Response>`. Register global middleware on the kernel and
|
|
43
|
+
route middleware on routes or groups, by value or by alias / group name:
|
|
44
|
+
|
|
45
|
+
```ts
|
|
46
|
+
import { cors, securityHeaders, throttle, type Middleware } from '@plinthjs/http'
|
|
47
|
+
|
|
48
|
+
const timing: Middleware = async (req, next) => {
|
|
49
|
+
const started = Date.now()
|
|
50
|
+
const res = await next(req)
|
|
51
|
+
return res.header('X-Response-Time', `${Date.now() - started}ms`)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
router.aliasMiddleware('auth', requireUser)
|
|
55
|
+
router.middlewareGroup('api', [timing, 'auth'])
|
|
56
|
+
router.get('/me', showProfile).middleware('api')
|
|
57
|
+
|
|
58
|
+
const kernel = new HttpKernel(router, {
|
|
59
|
+
middleware: [securityHeaders({ hsts: true }), cors({ origin: ['https://app.example.com'] })],
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
// Rate limiting, with any limiter exposing hit / tooManyAttempts / availableIn.
|
|
63
|
+
router.post('/login', login).middleware(throttle({ limiter, max: 5, decaySeconds: 60 }))
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
A `TerminableMiddleware` (an object with `handle` and `terminate(req, res)`) also gets a callback
|
|
67
|
+
after the response is produced.
|
|
68
|
+
|
|
69
|
+
## Requests
|
|
70
|
+
|
|
71
|
+
```ts
|
|
72
|
+
req.method() // 'POST'
|
|
73
|
+
req.path() // '/api/posts'
|
|
74
|
+
req.query('sort', 'desc')
|
|
75
|
+
req.input<string>('title')
|
|
76
|
+
req.boolean('published') // also integer(), float(), string(), enum()
|
|
77
|
+
req.has('tags') && req.filled('title')
|
|
78
|
+
req.header('accept')
|
|
79
|
+
req.bearerToken()
|
|
80
|
+
req.cookie('plinth_session')
|
|
81
|
+
req.file('avatar') // UploadedFile (multipart bodies are parsed)
|
|
82
|
+
req.wantsJson()
|
|
83
|
+
req.withAttribute('user', user).attribute('user') // immutable, returns a new Request
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
Build a request directly for tests: `new Request({ method: 'GET', url: '/users/1', headers: {} })`.
|
|
87
|
+
|
|
88
|
+
## Responses
|
|
89
|
+
|
|
90
|
+
```ts
|
|
91
|
+
Response.json({ ok: true }, 201)
|
|
92
|
+
Response.text('pong')
|
|
93
|
+
Response.html('<h1>Hi</h1>')
|
|
94
|
+
Response.noContent()
|
|
95
|
+
Response.redirectTo('/dashboard').with('status', 'Saved!') // flash data
|
|
96
|
+
Response.back('/')
|
|
97
|
+
.withErrors({ email: ['Taken'] })
|
|
98
|
+
.withInput(req.all())
|
|
99
|
+
Response.file('/srv/report.pdf')
|
|
100
|
+
Response.download('/srv/report.pdf', 'report.pdf')
|
|
101
|
+
Response.streamJson(rowsAsyncIterable)
|
|
102
|
+
Response.make('ok').cookie('seen', '1', { httpOnly: true }).withHeaders({ 'X-App': 'plinth' })
|
|
103
|
+
|
|
104
|
+
Response.macro('created', () => Response.json({ created: true }, 201))
|
|
105
|
+
Response.callMacro('created')
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
## Controllers and binding
|
|
109
|
+
|
|
110
|
+
```ts
|
|
111
|
+
import { Container } from '@plinthjs/core'
|
|
112
|
+
|
|
113
|
+
class UserController {
|
|
114
|
+
show(req: Request) {
|
|
115
|
+
return Response.json(req.route('user'))
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
router.bind('user', (id) => users.find(id)) // a null result renders a 404
|
|
120
|
+
router.get('/users/{user}', [UserController, 'show']).name('users.show')
|
|
121
|
+
router.resource('photos', PhotoController).only(['index', 'show'])
|
|
122
|
+
|
|
123
|
+
router.url('users.show', { user: 1 }) // '/users/1'
|
|
124
|
+
|
|
125
|
+
const kernel = new HttpKernel(router, { container: new Container() })
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
A bare class (or `[Class]`) dispatches to its `__invoke` method.
|
|
129
|
+
|
|
130
|
+
## Signed URLs
|
|
131
|
+
|
|
132
|
+
```ts
|
|
133
|
+
const router = new Router({ key: appKey }) // or router.setSigningKey(appKey)
|
|
134
|
+
|
|
135
|
+
const url = router.temporarySignedUrl('unsubscribe', 3600, { user: 1 }) // expires in an hour
|
|
136
|
+
router.validateSignature(url) // 'valid' | 'missing' | 'invalid' | 'expired'
|
|
137
|
+
router
|
|
138
|
+
.get('/unsubscribe/{user}', unsubscribe)
|
|
139
|
+
.name('unsubscribe')
|
|
140
|
+
.middleware(router.signedMiddleware())
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
## Errors
|
|
144
|
+
|
|
145
|
+
Throw `HttpException(status, message, headers)`, `NotFoundHttpException` or
|
|
146
|
+
`MethodNotAllowedHttpException` anywhere in the pipeline; the kernel reports and renders them through
|
|
147
|
+
its `ExceptionHandler`:
|
|
148
|
+
|
|
149
|
+
```ts
|
|
150
|
+
import { ExceptionHandler, HttpException } from '@plinthjs/http'
|
|
151
|
+
|
|
152
|
+
const handler = new ExceptionHandler(/* debug */ false)
|
|
153
|
+
.reportUsing((error, context) => logger.error(error, context))
|
|
154
|
+
.dontReport(HttpException)
|
|
155
|
+
.renderable((error) => (error instanceof PaymentError ? Response.json({}, 402) : undefined))
|
|
156
|
+
|
|
157
|
+
new HttpKernel(router, { exceptionHandler: handler })
|
|
158
|
+
```
|