@cslug/http 0.1.0 → 0.3.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.
- package/docs/api.md +8 -1
- package/package.json +3 -3
- package/src/commands.ts +21 -2
- package/src/errors.ts +1 -2
- package/src/responses.ts +1 -0
- package/src/session.ts +3 -0
package/docs/api.md
CHANGED
|
@@ -72,7 +72,7 @@ Config `http`: `port`, `host`, `shutdownTimeout`, `bodyLimit`, `trustedProxies`,
|
|
|
72
72
|
| | |
|
|
73
73
|
|---|---|
|
|
74
74
|
| `session(options?)` | Loads the session from its cookie (`config('session')`: `cookie` (`cslug_session`), `lifetime` (`14d`), `sameSite`, `domain`), saves what changed, sends an HttpOnly cookie (Secure in production). Errors are rendered inside it so flashes are saved |
|
|
75
|
-
| `ctx.session` | `get`, `put`, `has`, `forget`, `pull`, `flash`, `reflash`, `flashed()`, `errors()`, `old(key?)`, `token()`, `verifyToken()`, `regenerate()` (on login), `invalidate()` (on logout). Without the middleware, using it throws an explanation |
|
|
75
|
+
| `ctx.session` | `get`, `put`, `has`, `forget`, `pull`, `flash`, `reflash`, `flashed()`, `errors()`, `old(key?)`, `token()`, `verifyToken()`, `regenerate()` (on login), `invalidate()` (on logout). Without the middleware, using it throws an explanation; `ctx.session.available` is false then |
|
|
76
76
|
| `csrf({ except? })` | 419 for POST/PUT/PATCH/DELETE without the session token (`_token` form field or `X-CSRF-Token` header) |
|
|
77
77
|
| form errors | A `ValidationError` on a non-JSON, non-GET request with a session → **303 back** (Referer) with `_errors` (translated) and `_old` (input without passwords, tokens, files) flashed |
|
|
78
78
|
| method spoofing | A form POST with `_method=PUT/PATCH/DELETE` is routed as that method |
|
|
@@ -91,3 +91,10 @@ Config `http`: `port`, `host`, `shutdownTimeout`, `bodyLimit`, `trustedProxies`,
|
|
|
91
91
|
GET/HEAD requests that match no route are served from `public/` (`config('http.public')`: a folder name, or
|
|
92
92
|
`false`). Dotfiles and paths escaping the folder are refused. Hashed build files (`name-1a2b3c4d.js`) get
|
|
93
93
|
`Cache-Control: public, max-age=31536000, immutable`; others revalidate with `Last-Modified` / 304.
|
|
94
|
+
|
|
95
|
+
## Commands
|
|
96
|
+
|
|
97
|
+
| | |
|
|
98
|
+
|---|---|
|
|
99
|
+
| `cslug serve [--port] [--host] [--reuse-port] [--with-worker] [--with-scheduler]` | The HTTP server; SIGTERM drains in-flight requests. `--with-worker` / `--with-scheduler` also run `queue:work` / `schedule:work` in this process (one-process deployment, guide 21); they are found by signature, so http does not import the queue, and missing commands are an error |
|
|
100
|
+
| `cslug routes [filter] [--json]` | The routes, with names and middleware |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cslug/http",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Router, middleware, HttpContext, sessions, CSRF, error rendering on Bun.serve.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -29,7 +29,7 @@
|
|
|
29
29
|
"bun": ">=1.3.14"
|
|
30
30
|
},
|
|
31
31
|
"peerDependencies": {
|
|
32
|
-
"@cslug/core": "0.
|
|
33
|
-
"@cslug/validation": "0.
|
|
32
|
+
"@cslug/core": "0.3.0",
|
|
33
|
+
"@cslug/validation": "0.3.0"
|
|
34
34
|
}
|
|
35
35
|
}
|
package/src/commands.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { join } from 'node:path'
|
|
2
|
-
import { arg, Command, flag, names } from '@cslug/core'
|
|
2
|
+
import { arg, COMMANDS, Command, type CommandClass, flag, names, parseArgs } from '@cslug/core'
|
|
3
3
|
import { HttpKernel } from './kernel'
|
|
4
4
|
import { Router } from './router'
|
|
5
5
|
|
|
@@ -14,13 +14,32 @@ export class ServeCommand extends Command {
|
|
|
14
14
|
port: flag.number().optional().describe('Port (default: config http.port, PORT, or 3000)'),
|
|
15
15
|
host: flag.string().optional().describe('Interface to bind (default: all)'),
|
|
16
16
|
reusePort: flag.boolean().describe('Share the port between several processes (cslug start with web instances > 1)'),
|
|
17
|
+
withWorker: flag.boolean().describe('Also run queue:work in this process (needs @cslug/queue)'),
|
|
18
|
+
withScheduler: flag.boolean().describe('Also run schedule:work in this process (needs ScheduleProvider)'),
|
|
17
19
|
}
|
|
18
20
|
|
|
19
|
-
handle({ port, host, reusePort }: Command.Args<typeof ServeCommand>) {
|
|
21
|
+
async handle({ port, host, reusePort, withWorker, withScheduler }: Command.Args<typeof ServeCommand>) {
|
|
22
|
+
// http does not import the queue: the other roles run through their own commands, found by signature
|
|
23
|
+
const roles = [withWorker && 'queue:work', withScheduler && 'schedule:work'].filter((r): r is string => !!r)
|
|
24
|
+
const found = this.app.taggedTokens(COMMANDS) as CommandClass[]
|
|
25
|
+
for (const signature of roles) {
|
|
26
|
+
if (!found.some((c) => c.signature === signature)) {
|
|
27
|
+
this.error(
|
|
28
|
+
`--with-${signature === 'queue:work' ? 'worker' : 'scheduler'}: no ${signature} command (is its provider listed?)`,
|
|
29
|
+
)
|
|
30
|
+
return 1
|
|
31
|
+
}
|
|
32
|
+
}
|
|
20
33
|
const envPort = process.env.PORT ? Number(process.env.PORT) : undefined
|
|
21
34
|
const server = this.app.resolve(HttpKernel).listen({ port: port ?? envPort, hostname: host, reusePort })
|
|
22
35
|
this.log.info('http.listening', { url: server.url.toString() })
|
|
23
36
|
if (process.stdout.isTTY) this.info(`Listening on ${server.url}`)
|
|
37
|
+
for (const signature of roles) {
|
|
38
|
+
const cmd = found.find((c) => c.signature === signature) as CommandClass
|
|
39
|
+
const instance = this.app.createScope().build(cmd as never) as { handle(args: unknown): unknown }
|
|
40
|
+
await instance.handle(parseArgs(cmd.args ?? {}, []))
|
|
41
|
+
}
|
|
42
|
+
return 0
|
|
24
43
|
}
|
|
25
44
|
}
|
|
26
45
|
|
package/src/errors.ts
CHANGED
|
@@ -2,7 +2,6 @@ import { AppError, type Application, Logger, t, validationTranslator } from '@cs
|
|
|
2
2
|
import { ValidationError } from '@cslug/validation'
|
|
3
3
|
import type { HttpContext } from './context'
|
|
4
4
|
import { json } from './responses'
|
|
5
|
-
import { MissingSession } from './session'
|
|
6
5
|
|
|
7
6
|
/** A renderer may return a Response for an error, or undefined to let the next one try. */
|
|
8
7
|
export type ErrorRenderer = (error: unknown, ctx: HttpContext) => Response | undefined | Promise<Response | undefined>
|
|
@@ -68,7 +67,7 @@ export class ExceptionHandler {
|
|
|
68
67
|
*/
|
|
69
68
|
protected formRedirect(error: unknown, ctx: HttpContext): Response | undefined {
|
|
70
69
|
if (!(error instanceof ValidationError) || ctx.request.wantsJson() || ctx.request.method === 'GET') return undefined
|
|
71
|
-
if (ctx.session
|
|
70
|
+
if (!ctx.session.available) return undefined
|
|
72
71
|
ctx.session.flash('_errors', error.messages(validationTranslator(ctx.locale)))
|
|
73
72
|
ctx.session.flash('_old', this.oldInput(ctx))
|
|
74
73
|
return new Response(null, { status: 303, headers: { location: ctx.request.header('referer') ?? '/' } })
|
package/src/responses.ts
CHANGED
|
@@ -5,6 +5,7 @@ import { route, type UrlOptions } from './url'
|
|
|
5
5
|
export interface Responsable {
|
|
6
6
|
toResponse(ctx: HttpContext): Response | Promise<Response>
|
|
7
7
|
}
|
|
8
|
+
/** Duck-typed so responsables from other packages (vue views) need no shared base class. */
|
|
8
9
|
export const isResponsable = (v: unknown): v is Responsable =>
|
|
9
10
|
typeof v === 'object' && v !== null && typeof (v as Responsable).toResponse === 'function'
|
|
10
11
|
|
package/src/session.ts
CHANGED
|
@@ -8,6 +8,8 @@ const randomId = (bytes = 32) => Buffer.from(crypto.getRandomValues(new Uint8Arr
|
|
|
8
8
|
* Flash values live for the next request only.
|
|
9
9
|
*/
|
|
10
10
|
export class Session {
|
|
11
|
+
/** False on the placeholder a route without the `session()` middleware gets (`MissingSession`). */
|
|
12
|
+
readonly available: boolean = true
|
|
11
13
|
private data: SessionData
|
|
12
14
|
private dirty = false
|
|
13
15
|
private destroyed: string[] = []
|
|
@@ -130,6 +132,7 @@ export class Session {
|
|
|
130
132
|
|
|
131
133
|
/** Placeholder until the `session()` middleware runs: every use explains how to fix it. */
|
|
132
134
|
export class MissingSession extends Session {
|
|
135
|
+
override readonly available = false
|
|
133
136
|
constructor() {
|
|
134
137
|
super('', {}, true)
|
|
135
138
|
}
|