@cslug/http 0.0.0-stage → 0.2.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/README.md +6 -2
- package/docs/README.md +24 -0
- package/docs/api.md +100 -0
- package/package.json +33 -4
- package/src/body.ts +72 -0
- package/src/commands.ts +132 -0
- package/src/context.ts +232 -0
- package/src/errors.ts +130 -0
- package/src/index.ts +41 -0
- package/src/kernel.ts +302 -0
- package/src/middleware/index.ts +121 -0
- package/src/middleware/web.ts +140 -0
- package/src/provider.ts +104 -0
- package/src/responses.ts +113 -0
- package/src/router.ts +202 -0
- package/src/session.ts +163 -0
- package/src/static.ts +34 -0
- package/src/url.ts +87 -0
- package/stubs/controller.resource.stub +37 -0
- package/stubs/controller.stub +9 -0
- package/stubs/middleware.stub +9 -0
- package/stubs/validator.stub +7 -0
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import {
|
|
2
|
+
CslugError,
|
|
3
|
+
currentContext,
|
|
4
|
+
parseDuration,
|
|
5
|
+
RateLimiter,
|
|
6
|
+
SessionStore,
|
|
7
|
+
TooManyRequestsError,
|
|
8
|
+
Translator,
|
|
9
|
+
} from '@cslug/core'
|
|
10
|
+
import type { HttpContext } from '../context'
|
|
11
|
+
import { ExceptionHandler } from '../errors'
|
|
12
|
+
import type { MiddlewareFn } from '../router'
|
|
13
|
+
import { Session } from '../session'
|
|
14
|
+
|
|
15
|
+
export type SessionOptions = {
|
|
16
|
+
cookie?: string
|
|
17
|
+
lifetime?: string
|
|
18
|
+
sameSite?: 'lax' | 'strict' | 'none'
|
|
19
|
+
/** Cookie domain, e.g. `.albastr.com` to share a login across subdomains. */
|
|
20
|
+
domain?: string
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Load the session from its cookie (or start one), run the request, save what changed, send the cookie.
|
|
25
|
+
* Config: `session` (`cookie`, `lifetime`, `sameSite`, `domain`); data lives in the bound `SessionStore`.
|
|
26
|
+
*/
|
|
27
|
+
export const session =
|
|
28
|
+
(options: SessionOptions = {}): MiddlewareFn =>
|
|
29
|
+
async (ctx, next) => {
|
|
30
|
+
const config = { ...ctx.app.config<SessionOptions | undefined>('session'), ...options }
|
|
31
|
+
const name = config.cookie ?? 'cslug_session'
|
|
32
|
+
const lifetime = config.lifetime ?? '14d'
|
|
33
|
+
const store = ctx.resolve(SessionStore)
|
|
34
|
+
const id = ctx.request.cookie(name)
|
|
35
|
+
const data = id ? await store.read(id) : undefined
|
|
36
|
+
const s = id && data ? new Session(id, data, false) : Session.create()
|
|
37
|
+
ctx.session = s
|
|
38
|
+
|
|
39
|
+
let res: Response
|
|
40
|
+
try {
|
|
41
|
+
res = await next()
|
|
42
|
+
} catch (error) {
|
|
43
|
+
// render here, inside the session, so what the handler flashes (form errors, old input) is saved
|
|
44
|
+
res = await ctx.resolve(ExceptionHandler).handle(error, ctx)
|
|
45
|
+
}
|
|
46
|
+
await s.save(store, lifetime)
|
|
47
|
+
if (s.needsCookie || s.id !== id) {
|
|
48
|
+
const seconds = Math.floor(parseDuration(lifetime) / 1000)
|
|
49
|
+
res = withCookie(res, ctx, name, s.id, seconds, config)
|
|
50
|
+
}
|
|
51
|
+
return res
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function withCookie(
|
|
55
|
+
res: Response,
|
|
56
|
+
ctx: HttpContext,
|
|
57
|
+
name: string,
|
|
58
|
+
value: string,
|
|
59
|
+
maxAge: number,
|
|
60
|
+
config: SessionOptions,
|
|
61
|
+
): Response {
|
|
62
|
+
const parts = [
|
|
63
|
+
`${name}=${value}`,
|
|
64
|
+
'Path=/',
|
|
65
|
+
'HttpOnly',
|
|
66
|
+
`SameSite=${capitalize(config.sameSite ?? 'lax')}`,
|
|
67
|
+
`Max-Age=${maxAge}`,
|
|
68
|
+
]
|
|
69
|
+
if (ctx.app.config('app.env') === 'production' || config.sameSite === 'none') parts.push('Secure')
|
|
70
|
+
if (config.domain) parts.push(`Domain=${config.domain}`)
|
|
71
|
+
const headers = new Headers(res.headers)
|
|
72
|
+
headers.append('set-cookie', parts.join('; '))
|
|
73
|
+
return new Response(res.body, { status: res.status, statusText: res.statusText, headers })
|
|
74
|
+
}
|
|
75
|
+
const capitalize = (s: string) => s.charAt(0).toUpperCase() + s.slice(1)
|
|
76
|
+
|
|
77
|
+
/** 419 for state-changing requests without the session's CSRF token (`_token` field or `X-CSRF-Token` header). */
|
|
78
|
+
export const csrf =
|
|
79
|
+
(options: { except?: (string | RegExp)[] } = {}): MiddlewareFn =>
|
|
80
|
+
async (ctx, next) => {
|
|
81
|
+
const safe = ['GET', 'HEAD', 'OPTIONS'].includes(ctx.request.method)
|
|
82
|
+
const excepted = options.except?.some((p) =>
|
|
83
|
+
typeof p === 'string' ? ctx.request.path === p : p.test(ctx.request.path),
|
|
84
|
+
)
|
|
85
|
+
ctx.session.token() // make sure a token exists for the forms of this page
|
|
86
|
+
if (!safe && !excepted) {
|
|
87
|
+
const body = ctx.request.isForm ? await ctx.request.body() : {}
|
|
88
|
+
const given = ctx.request.header('x-csrf-token') ?? (typeof body._token === 'string' ? body._token : undefined)
|
|
89
|
+
if (!ctx.session.verifyToken(given)) {
|
|
90
|
+
throw Object.assign(new CslugError('http.csrf_mismatch', 'The page expired. Reload it and try again.'), {
|
|
91
|
+
status: 419,
|
|
92
|
+
})
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return next()
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Rate limit a route: `throttle('5/min')`, keyed by the user (when known) or the IP; or pass a key function.
|
|
100
|
+
* Adds `X-RateLimit-Limit/Remaining`; over the limit → 429 with `Retry-After`.
|
|
101
|
+
*/
|
|
102
|
+
export const throttle =
|
|
103
|
+
(limit: string, key?: (ctx: HttpContext) => string | Promise<string>): MiddlewareFn =>
|
|
104
|
+
async (ctx, next) => {
|
|
105
|
+
const limiter = ctx.resolve(RateLimiter)
|
|
106
|
+
const who = key
|
|
107
|
+
? await key(ctx)
|
|
108
|
+
: `${(currentContext()?.userId as string | undefined) ?? ctx.request.ip() ?? 'unknown'}`
|
|
109
|
+
const result = await limiter.hit(`throttle:${ctx.routeName ?? ctx.request.path}:${who}`, limit)
|
|
110
|
+
if (!result.allowed) throw new TooManyRequestsError(result.retryAfter)
|
|
111
|
+
const res = await next()
|
|
112
|
+
res.headers.set('x-ratelimit-limit', limit.split('/')[0] ?? limit)
|
|
113
|
+
res.headers.set('x-ratelimit-remaining', String(result.remaining))
|
|
114
|
+
return res
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Pick the request's locale: the `:locale` route parameter, then the `locale` cookie, then `Accept-Language`,
|
|
119
|
+
* then the default. Only locales listed in `config('i18n.locales')` are accepted. Sets `ctx.locale` and the
|
|
120
|
+
* ambient locale used by `t()`.
|
|
121
|
+
*/
|
|
122
|
+
export const locale = (): MiddlewareFn => async (ctx, next) => {
|
|
123
|
+
const translator = ctx.resolve(Translator)
|
|
124
|
+
const supported = translator.locales
|
|
125
|
+
const pick = (l: string | undefined) => (l && supported.includes(l) ? l : undefined)
|
|
126
|
+
const fromHeader = (ctx.request.header('accept-language') ?? '')
|
|
127
|
+
.split(',')
|
|
128
|
+
.map((part) => {
|
|
129
|
+
const [tag, q] = part.trim().split(';q=')
|
|
130
|
+
return { tag: (tag ?? '').toLowerCase(), q: q ? Number(q) : 1 }
|
|
131
|
+
})
|
|
132
|
+
.sort((a, b) => b.q - a.q)
|
|
133
|
+
.map(({ tag }) => pick(tag) ?? pick(tag.split('-')[0]))
|
|
134
|
+
.find(Boolean)
|
|
135
|
+
const chosen = pick(ctx.params.locale) ?? pick(ctx.request.cookie('locale')) ?? fromHeader ?? translator.defaultLocale
|
|
136
|
+
ctx.locale = chosen
|
|
137
|
+
const store = currentContext()
|
|
138
|
+
if (store) store.locale = chosen
|
|
139
|
+
return next()
|
|
140
|
+
}
|
package/src/provider.ts
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
import { Logger, ServiceProvider } from '@cslug/core'
|
|
4
|
+
import { httpCommands } from './commands'
|
|
5
|
+
import { ExceptionHandler } from './errors'
|
|
6
|
+
import { HttpKernel } from './kernel'
|
|
7
|
+
import { bodyLimit, cors, csrf, securityHeaders, session } from './middleware'
|
|
8
|
+
import { type GroupOptions, type Middleware, type RouteRegistrar, Router } from './router'
|
|
9
|
+
|
|
10
|
+
export type HttpConfig = {
|
|
11
|
+
port?: number
|
|
12
|
+
host?: string
|
|
13
|
+
/** Time to let in-flight requests finish on shutdown. */
|
|
14
|
+
shutdownTimeout?: string | number
|
|
15
|
+
bodyLimit?: string | number
|
|
16
|
+
/** Folder served for GET/HEAD requests no route matches (default `public`); false turns it off. */
|
|
17
|
+
public?: boolean | string
|
|
18
|
+
trustedProxies?: string[]
|
|
19
|
+
cors?: { origins: string[]; credentials?: boolean }
|
|
20
|
+
/** Extra middleware for the `web` (routes/web.ts) and `api` (routes/api.ts) groups. */
|
|
21
|
+
groups?: { web?: Middleware[]; api?: Middleware[] }
|
|
22
|
+
/** Global middleware added after the defaults. */
|
|
23
|
+
middleware?: Middleware[]
|
|
24
|
+
/** Problem `type` URL base (default `${app.url}/errors`). */
|
|
25
|
+
problemBase?: string
|
|
26
|
+
/** Disable the /health endpoints. */
|
|
27
|
+
health?: boolean
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Tags for middleware that packages add to the `web` / `api` groups (`this.app.tag([token], WEB_MIDDLEWARE)`). */
|
|
31
|
+
export const WEB_MIDDLEWARE = 'http.middleware.web'
|
|
32
|
+
export const API_MIDDLEWARE = 'http.middleware.api'
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Binds Router, ExceptionHandler and HttpKernel; at boot loads `routes/web.ts` (web group) and `routes/api.ts`
|
|
36
|
+
* (api group) when they exist; on shutdown stops the server gracefully. `cslug serve` calls `kernel.listen()`.
|
|
37
|
+
*/
|
|
38
|
+
export class HttpProvider extends ServiceProvider {
|
|
39
|
+
register() {
|
|
40
|
+
this.commands(httpCommands)
|
|
41
|
+
this.app.singleton(Router, () => new Router())
|
|
42
|
+
this.app.singleton(ExceptionHandler, (c) => new ExceptionHandler(this.app, c.resolve(Logger)))
|
|
43
|
+
this.app.singleton(
|
|
44
|
+
HttpKernel,
|
|
45
|
+
(c) => new HttpKernel(this.app, c.resolve(Router), c.resolve(ExceptionHandler), c.resolve(Logger)),
|
|
46
|
+
)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async boot() {
|
|
50
|
+
const config = this.app.config<HttpConfig | undefined>('http') ?? {}
|
|
51
|
+
const kernel = this.app.resolve(HttpKernel)
|
|
52
|
+
const router = this.app.resolve(Router)
|
|
53
|
+
if (config.public !== false)
|
|
54
|
+
kernel.publicDir = join(this.app.rootDir, typeof config.public === 'string' ? config.public : 'public')
|
|
55
|
+
kernel.global.push(securityHeaders(), bodyLimit(config.bodyLimit ?? '1mb'), ...(config.middleware ?? []))
|
|
56
|
+
|
|
57
|
+
if (config.health !== false) {
|
|
58
|
+
router.load((r) => {
|
|
59
|
+
r.get('/health/live', () => kernel.health('live')).name('health.live')
|
|
60
|
+
r.get('/health/ready', () => kernel.health('ready')).name('health.ready')
|
|
61
|
+
})
|
|
62
|
+
}
|
|
63
|
+
const groups: [file: string, group: GroupOptions][] = [
|
|
64
|
+
[
|
|
65
|
+
'routes/web.ts',
|
|
66
|
+
{
|
|
67
|
+
middleware: [
|
|
68
|
+
session(),
|
|
69
|
+
csrf(),
|
|
70
|
+
...this.app.tagged<Middleware>(WEB_MIDDLEWARE),
|
|
71
|
+
...(config.groups?.web ?? []),
|
|
72
|
+
],
|
|
73
|
+
group: 'web',
|
|
74
|
+
},
|
|
75
|
+
],
|
|
76
|
+
[
|
|
77
|
+
'routes/api.ts',
|
|
78
|
+
{
|
|
79
|
+
middleware: [
|
|
80
|
+
...(config.cors ? [cors(config.cors)] : []),
|
|
81
|
+
...this.app.tagged<Middleware>(API_MIDDLEWARE),
|
|
82
|
+
...(config.groups?.api ?? []),
|
|
83
|
+
],
|
|
84
|
+
group: 'api',
|
|
85
|
+
},
|
|
86
|
+
],
|
|
87
|
+
]
|
|
88
|
+
for (const [file, group] of groups) {
|
|
89
|
+
const path = join(this.app.rootDir, file)
|
|
90
|
+
if (!existsSync(path)) continue
|
|
91
|
+
const mod = (await import(path)) as { default?: (r: RouteRegistrar) => void }
|
|
92
|
+
if (typeof mod.default !== 'function')
|
|
93
|
+
throw new Error(`${file} must \`export default defineRoutes((r) => { … })\``)
|
|
94
|
+
router.load(mod.default, group)
|
|
95
|
+
}
|
|
96
|
+
kernel.compile()
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
async shutdown() {
|
|
100
|
+
const timeout = this.app.config<string | number | undefined>('http.shutdownTimeout') ?? '10s'
|
|
101
|
+
const { parseDuration } = await import('@cslug/core')
|
|
102
|
+
await this.app.resolve(HttpKernel).stop(parseDuration(timeout))
|
|
103
|
+
}
|
|
104
|
+
}
|
package/src/responses.ts
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import type { HttpContext } from './context'
|
|
2
|
+
import { route, type UrlOptions } from './url'
|
|
3
|
+
|
|
4
|
+
/** Anything a handler returns that knows how to become a Response (views, redirects…). */
|
|
5
|
+
export interface Responsable {
|
|
6
|
+
toResponse(ctx: HttpContext): Response | Promise<Response>
|
|
7
|
+
}
|
|
8
|
+
/** Duck-typed so responsables from other packages (vue views) need no shared base class. */
|
|
9
|
+
export const isResponsable = (v: unknown): v is Responsable =>
|
|
10
|
+
typeof v === 'object' && v !== null && typeof (v as Responsable).toResponse === 'function'
|
|
11
|
+
|
|
12
|
+
/** JSON with bigint → string, Date → ISO, and `toJSON()` (Money) respected. */
|
|
13
|
+
export function json(data: unknown, init: ResponseInit = {}): Response {
|
|
14
|
+
const body = JSON.stringify(data, (_k, v) => (typeof v === 'bigint' ? v.toString() : v))
|
|
15
|
+
const headers = new Headers(init.headers)
|
|
16
|
+
if (!headers.has('content-type')) headers.set('content-type', 'application/json; charset=utf-8')
|
|
17
|
+
return new Response(body, { ...init, headers })
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export const created = (data?: unknown) => json(data ?? null, { status: 201 })
|
|
21
|
+
export const accepted = (data?: unknown) => json(data ?? null, { status: 202 })
|
|
22
|
+
export const noContent = () => new Response(null, { status: 204 })
|
|
23
|
+
|
|
24
|
+
/** A file download. `content` may be a Bun file, bytes or a string. */
|
|
25
|
+
export function download(content: Blob | Uint8Array<ArrayBuffer> | string, filename: string, type?: string): Response {
|
|
26
|
+
const blob = content instanceof Blob ? content : new Blob([content], { type: type ?? 'application/octet-stream' })
|
|
27
|
+
return new Response(blob, {
|
|
28
|
+
headers: {
|
|
29
|
+
'content-type': type ?? (blob.type || 'application/octet-stream'),
|
|
30
|
+
'content-disposition': `attachment; filename="${filename.replace(/"/g, '')}"; filename*=UTF-8''${encodeURIComponent(filename)}`,
|
|
31
|
+
},
|
|
32
|
+
})
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Stream text or bytes (CSV exports…). */
|
|
36
|
+
export function stream(source: AsyncIterable<string | Uint8Array>, type = 'text/plain; charset=utf-8'): Response {
|
|
37
|
+
const encoder = new TextEncoder()
|
|
38
|
+
const body = new ReadableStream<Uint8Array>({
|
|
39
|
+
async start(controller) {
|
|
40
|
+
for await (const chunk of source) controller.enqueue(typeof chunk === 'string' ? encoder.encode(chunk) : chunk)
|
|
41
|
+
controller.close()
|
|
42
|
+
},
|
|
43
|
+
})
|
|
44
|
+
return new Response(body, { headers: { 'content-type': type } })
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Server-sent events: each item becomes a `data:` event (objects as JSON). */
|
|
48
|
+
export function sse(source: AsyncIterable<unknown>): Response {
|
|
49
|
+
return stream(
|
|
50
|
+
(async function* () {
|
|
51
|
+
for await (const item of source) yield `data: ${typeof item === 'string' ? item : JSON.stringify(item)}\n\n`
|
|
52
|
+
})(),
|
|
53
|
+
'text/event-stream',
|
|
54
|
+
)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** `redirect().route(...)`, `.to(url)`, `.back()`, `.away(url)`, `.with(key, message)` (flash, with sessions). */
|
|
58
|
+
export class Redirect implements Responsable {
|
|
59
|
+
private target?: string
|
|
60
|
+
private toReferrer = false
|
|
61
|
+
private status = 302
|
|
62
|
+
readonly flashes: Record<string, unknown> = {}
|
|
63
|
+
|
|
64
|
+
to(url: string): this {
|
|
65
|
+
this.target = url
|
|
66
|
+
return this
|
|
67
|
+
}
|
|
68
|
+
route(name: string, params: Record<string, unknown> = {}, options: UrlOptions = {}): this {
|
|
69
|
+
this.target = route(name, params, options)
|
|
70
|
+
return this
|
|
71
|
+
}
|
|
72
|
+
/** To an external URL (payment checkout…). */
|
|
73
|
+
away(url: string): this {
|
|
74
|
+
this.target = url
|
|
75
|
+
return this
|
|
76
|
+
}
|
|
77
|
+
/** Back to the previous page (Referer), or `fallback`. */
|
|
78
|
+
back(fallback = '/'): this {
|
|
79
|
+
this.toReferrer = true
|
|
80
|
+
this.target = fallback
|
|
81
|
+
return this
|
|
82
|
+
}
|
|
83
|
+
/** After login: the page the user wanted, else `fallback` (needs sessions). */
|
|
84
|
+
private useIntended = false
|
|
85
|
+
/** After login: the page the user wanted before being sent to login, else `fallback`. */
|
|
86
|
+
intended(fallback: string): this {
|
|
87
|
+
this.target = fallback
|
|
88
|
+
this.useIntended = true
|
|
89
|
+
return this
|
|
90
|
+
}
|
|
91
|
+
/** Flash a value for the next request: `.with('success', t('saved'))` (needs the session middleware). */
|
|
92
|
+
with(key: string, value: unknown): this {
|
|
93
|
+
this.flashes[key] = value
|
|
94
|
+
return this
|
|
95
|
+
}
|
|
96
|
+
withStatus(status: 301 | 302 | 303 | 307 | 308): this {
|
|
97
|
+
this.status = status
|
|
98
|
+
return this
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
toResponse(ctx: HttpContext): Response {
|
|
102
|
+
const referrer = this.toReferrer ? ctx.request.header('referer') : undefined
|
|
103
|
+
let location = referrer ?? this.target ?? '/'
|
|
104
|
+
if (this.useIntended) location = ctx.session.pull<string>('url.intended') ?? location
|
|
105
|
+
for (const [k, v] of Object.entries(this.flashes)) ctx.session.flash(k, v)
|
|
106
|
+
// 303 after non-GET so the browser follows with GET
|
|
107
|
+
const status =
|
|
108
|
+
this.status === 302 && ctx.request.method && !['GET', 'HEAD'].includes(ctx.request.method) ? 303 : this.status
|
|
109
|
+
return new Response(null, { status, headers: { location } })
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export const redirect = () => new Redirect()
|
package/src/router.ts
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
import { type Class, CslugError } from '@cslug/core'
|
|
2
|
+
import type { HttpContext } from './context'
|
|
3
|
+
|
|
4
|
+
export type Method = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS'
|
|
5
|
+
export type Next = () => Promise<Response>
|
|
6
|
+
/** A middleware function, or a class with `handle(ctx, next)` built by the container. */
|
|
7
|
+
export type MiddlewareFn = (ctx: HttpContext, next: Next) => Response | Promise<Response>
|
|
8
|
+
export type MiddlewareClass = Class<{ handle(ctx: HttpContext, next: Next): Response | Promise<Response> }>
|
|
9
|
+
export type Middleware = MiddlewareFn | MiddlewareClass
|
|
10
|
+
|
|
11
|
+
type ActionClass = Class<object>
|
|
12
|
+
/** `[Controller, 'method']`, a single-action controller class (`handle`), or a closure. */
|
|
13
|
+
export type Action =
|
|
14
|
+
| readonly [ActionClass, string]
|
|
15
|
+
| Class<{ handle(ctx: HttpContext): unknown }>
|
|
16
|
+
| ((ctx: HttpContext) => unknown)
|
|
17
|
+
|
|
18
|
+
export type RouteDef = {
|
|
19
|
+
method: Method
|
|
20
|
+
path: string
|
|
21
|
+
name?: string
|
|
22
|
+
domain?: string
|
|
23
|
+
action: Action
|
|
24
|
+
middleware: Middleware[]
|
|
25
|
+
wheres: Record<string, RegExp>
|
|
26
|
+
meta: Record<string, unknown>
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export type GroupOptions = {
|
|
30
|
+
prefix?: string
|
|
31
|
+
/** Host to match, may contain parameters: `':operator.albastr.com'`. */
|
|
32
|
+
domain?: string
|
|
33
|
+
middleware?: Middleware[]
|
|
34
|
+
/** Route-name prefix: `as: 'admin'` + `.name('show')` → `admin.show`. */
|
|
35
|
+
as?: string
|
|
36
|
+
/** Free-form metadata for packages (e.g. `ssr: false` for @cslug/vue). */
|
|
37
|
+
[key: string]: unknown
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const join = (a: string, b: string) => {
|
|
41
|
+
const path = `${a.replace(/\/+$/, '')}/${b.replace(/^\/+/, '')}`.replace(/\/+$/, '')
|
|
42
|
+
return path === '' ? '/' : path.startsWith('/') ? path : `/${path}`
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** The fluent handle returned by `r.get(...)`. */
|
|
46
|
+
export class RouteBuilder {
|
|
47
|
+
constructor(
|
|
48
|
+
readonly def: RouteDef,
|
|
49
|
+
private readonly namePrefix: string,
|
|
50
|
+
) {}
|
|
51
|
+
name(name: string): this {
|
|
52
|
+
this.def.name = this.namePrefix ? `${this.namePrefix}.${name}` : name
|
|
53
|
+
return this
|
|
54
|
+
}
|
|
55
|
+
middleware(...middleware: Middleware[]): this {
|
|
56
|
+
this.def.middleware.push(...middleware)
|
|
57
|
+
return this
|
|
58
|
+
}
|
|
59
|
+
/** Constrain a path or domain parameter: `.where('operator', /^[a-z0-9-]{3,40}$/)`. */
|
|
60
|
+
where(param: string, pattern: RegExp): this {
|
|
61
|
+
this.def.wheres[param] = pattern
|
|
62
|
+
return this
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
type Resource = 'index' | 'create' | 'store' | 'show' | 'edit' | 'update' | 'destroy'
|
|
67
|
+
|
|
68
|
+
/** What `defineRoutes` callbacks receive. */
|
|
69
|
+
export class RouteRegistrar {
|
|
70
|
+
constructor(
|
|
71
|
+
readonly routes: RouteDef[],
|
|
72
|
+
private readonly scope: {
|
|
73
|
+
prefix: string
|
|
74
|
+
domain?: string
|
|
75
|
+
middleware: Middleware[]
|
|
76
|
+
as: string
|
|
77
|
+
meta: Record<string, unknown>
|
|
78
|
+
} = {
|
|
79
|
+
prefix: '',
|
|
80
|
+
middleware: [],
|
|
81
|
+
as: '',
|
|
82
|
+
meta: {},
|
|
83
|
+
},
|
|
84
|
+
) {}
|
|
85
|
+
|
|
86
|
+
private add(method: Method, path: string, action: Action): RouteBuilder {
|
|
87
|
+
const def: RouteDef = {
|
|
88
|
+
method,
|
|
89
|
+
path: join(this.scope.prefix, path),
|
|
90
|
+
domain: this.scope.domain,
|
|
91
|
+
action,
|
|
92
|
+
middleware: [...this.scope.middleware],
|
|
93
|
+
wheres: {},
|
|
94
|
+
meta: { ...this.scope.meta },
|
|
95
|
+
}
|
|
96
|
+
this.routes.push(def)
|
|
97
|
+
return new RouteBuilder(def, this.scope.as)
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
get(path: string, action: Action) {
|
|
101
|
+
return this.add('GET', path, action)
|
|
102
|
+
}
|
|
103
|
+
post(path: string, action: Action) {
|
|
104
|
+
return this.add('POST', path, action)
|
|
105
|
+
}
|
|
106
|
+
put(path: string, action: Action) {
|
|
107
|
+
return this.add('PUT', path, action)
|
|
108
|
+
}
|
|
109
|
+
patch(path: string, action: Action) {
|
|
110
|
+
return this.add('PATCH', path, action)
|
|
111
|
+
}
|
|
112
|
+
delete(path: string, action: Action) {
|
|
113
|
+
return this.add('DELETE', path, action)
|
|
114
|
+
}
|
|
115
|
+
options(path: string, action: Action) {
|
|
116
|
+
return this.add('OPTIONS', path, action)
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
group(options: GroupOptions, routes: (r: RouteRegistrar) => void): void {
|
|
120
|
+
const { prefix, domain, middleware, as, ...meta } = options
|
|
121
|
+
routes(
|
|
122
|
+
new RouteRegistrar(this.routes, {
|
|
123
|
+
prefix: join(this.scope.prefix, prefix ?? ''),
|
|
124
|
+
domain: domain ?? this.scope.domain,
|
|
125
|
+
middleware: [...this.scope.middleware, ...(middleware ?? [])],
|
|
126
|
+
as: [this.scope.as, as].filter(Boolean).join('.'),
|
|
127
|
+
meta: { ...this.scope.meta, ...meta },
|
|
128
|
+
}),
|
|
129
|
+
)
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* REST routes: `r.resource('operators', OperatorController)` → index, create, store, show, edit, update, destroy.
|
|
134
|
+
* Nested: `r.resource('operators.documents', Ctl)` → `/operators/:operator/documents/:document`.
|
|
135
|
+
*/
|
|
136
|
+
resource(name: string, controller: ActionClass) {
|
|
137
|
+
const parts = name.split('.')
|
|
138
|
+
const param = (p: string) =>
|
|
139
|
+
(p.endsWith('ies') ? `${p.slice(0, -3)}y` : p.endsWith('s') ? p.slice(0, -1) : p).replace(
|
|
140
|
+
/-([a-z])/g,
|
|
141
|
+
(_, c: string) => c.toUpperCase(),
|
|
142
|
+
)
|
|
143
|
+
const base = parts.map((p, i) => (i < parts.length - 1 ? `${p}/:${param(p)}` : p)).join('/')
|
|
144
|
+
const item = `${base}/:${param(parts.at(-1) as string)}`
|
|
145
|
+
const table: [Resource, Method, string][] = [
|
|
146
|
+
['index', 'GET', base],
|
|
147
|
+
['create', 'GET', `${base}/create`],
|
|
148
|
+
['store', 'POST', base],
|
|
149
|
+
['show', 'GET', item],
|
|
150
|
+
['edit', 'GET', `${item}/edit`],
|
|
151
|
+
['update', 'PATCH', item],
|
|
152
|
+
['destroy', 'DELETE', item],
|
|
153
|
+
]
|
|
154
|
+
const built = table.map(([action, method, path]) => {
|
|
155
|
+
const route = this.add(method, path, [controller, action] as const).name(`${name}.${action}`)
|
|
156
|
+
return { action, route }
|
|
157
|
+
})
|
|
158
|
+
return {
|
|
159
|
+
only: (actions: Resource[]) => {
|
|
160
|
+
for (const { action, route } of built)
|
|
161
|
+
if (!actions.includes(action)) this.routes.splice(this.routes.indexOf(route.def), 1)
|
|
162
|
+
},
|
|
163
|
+
except: (actions: Resource[]) => {
|
|
164
|
+
for (const { action, route } of built)
|
|
165
|
+
if (actions.includes(action)) this.routes.splice(this.routes.indexOf(route.def), 1)
|
|
166
|
+
},
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** A routes file: `export default defineRoutes((r) => { … })`. */
|
|
172
|
+
export const defineRoutes = (fn: (r: RouteRegistrar) => void) => fn
|
|
173
|
+
|
|
174
|
+
/** All routes of the app, with name lookup. */
|
|
175
|
+
export class Router {
|
|
176
|
+
readonly routes: RouteDef[] = []
|
|
177
|
+
|
|
178
|
+
/** Add routes (a `defineRoutes` function), optionally inside a group (the `web` / `api` groups). */
|
|
179
|
+
load(fn: (r: RouteRegistrar) => void, group: GroupOptions = {}): this {
|
|
180
|
+
new RouteRegistrar(this.routes).group(group, fn)
|
|
181
|
+
return this
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
byName(name: string): RouteDef | undefined {
|
|
185
|
+
return this.routes.find((r) => r.name === name)
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** Checks: duplicate names, and the same method+path+domain twice. Called when the kernel starts. */
|
|
189
|
+
validate(): void {
|
|
190
|
+
const names = new Set<string>()
|
|
191
|
+
const keys = new Set<string>()
|
|
192
|
+
for (const r of this.routes) {
|
|
193
|
+
if (r.name) {
|
|
194
|
+
if (names.has(r.name)) throw new CslugError('http.duplicate_route_name', `Two routes are named "${r.name}"`)
|
|
195
|
+
names.add(r.name)
|
|
196
|
+
}
|
|
197
|
+
const key = `${r.method} ${r.domain ?? '*'} ${r.path}`
|
|
198
|
+
if (keys.has(key)) throw new CslugError('http.duplicate_route', `Route defined twice: ${key}`)
|
|
199
|
+
keys.add(key)
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
}
|