prunelle 0.7.3 → 0.7.5
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/llms.txt +11 -9
- package/package.json +1 -1
- package/src/a11y/index.ts +9 -2
- package/src/build/index.ts +29 -30
- package/src/build/prerender.ts +29 -13
- package/src/build/routes.ts +19 -1
- package/src/build/static.ts +24 -2
- package/src/cli/check-forms.ts +16 -6
- package/src/cli/check-links.ts +12 -9
- package/src/cli/check-security.ts +87 -12
- package/src/cli/check.ts +1 -1
- package/src/cli/commands.ts +3 -3
- package/src/cli/upgrade.ts +36 -3
- package/src/compiler/compliance.ts +2 -0
- package/src/compiler/dom.ts +41 -15
- package/src/compiler/ssr-helpers.ts +45 -21
- package/src/compiler/ssr.ts +32 -16
- package/src/context.ts +2 -0
- package/src/dev/error-log.ts +1 -1
- package/src/dev/index.ts +1 -1
- package/src/dev/supervisor.ts +2 -2
- package/src/dom/attrs.ts +1 -1
- package/src/dom/island.ts +30 -4
- package/src/jsx-runtime.ts +1 -1
- package/src/plugins/services.ts +1 -0
- package/src/reactivity/index.ts +14 -2
- package/src/server/action.ts +26 -18
- package/src/server/assets.ts +22 -4
- package/src/server/consent.ts +7 -2
- package/src/server/cookies.ts +8 -1
- package/src/server/errors.ts +57 -26
- package/src/server/http.ts +1 -1
- package/src/server/index.ts +7 -7
- package/src/server/page.ts +4 -0
- package/src/server/rate-limit.ts +36 -12
- package/src/server/route-cache.ts +9 -10
- package/src/server/route-table.ts +38 -13
- package/src/server/router.ts +4 -4
- package/src/server/sanitize-html.ts +21 -7
- package/src/server/security.ts +13 -3
- package/src/server/serve-handlers.ts +3 -3
- package/src/server/start.ts +2 -2
- package/src/server/static-dir.ts +3 -10
- package/src/server/stream.ts +4 -4
- package/src/ssr/consent-banner.ts +3 -1
- package/src/ssr/context.ts +85 -2
- package/src/ssr/index.ts +16 -4
- package/src/ssr/navigation.ts +1 -1
- package/src/style.ts +9 -7
- package/src/unrenderable.ts +15 -5
package/src/dev/supervisor.ts
CHANGED
|
@@ -162,6 +162,8 @@ export async function devSupervisor(options: DevSupervisorOptions): Promise<{ ur
|
|
|
162
162
|
const child = await ready
|
|
163
163
|
if (child === undefined)
|
|
164
164
|
return buildErrorResponse(request, crashed ?? 'prunelle dev: the app process is not running.', reloadAssets.script)
|
|
165
|
+
// The app process keeps its own idle timeout, which a stream or a route's `export const idleTimeout` sets, so this hop waits on it alone.
|
|
166
|
+
srv.timeout(request, 0)
|
|
165
167
|
const headers = new Headers(request.headers)
|
|
166
168
|
headers.set(DEV_CLIENT_IP_HEADER, srv.requestIP(request)?.address ?? '')
|
|
167
169
|
try {
|
|
@@ -173,8 +175,6 @@ export async function devSupervisor(options: DevSupervisorOptions): Promise<{ ur
|
|
|
173
175
|
redirect: 'manual',
|
|
174
176
|
signal: request.signal,
|
|
175
177
|
})
|
|
176
|
-
if (!res.headers.has('content-length'))
|
|
177
|
-
srv.timeout(request, 0)
|
|
178
178
|
return res
|
|
179
179
|
}
|
|
180
180
|
catch (err) {
|
package/src/dom/attrs.ts
CHANGED
|
@@ -64,7 +64,7 @@ export function setAttr(el: Element, name: string, value: unknown): void {
|
|
|
64
64
|
|
|
65
65
|
export function setProp(el: Element, name: string, value: unknown): void {
|
|
66
66
|
const next = name === 'value'
|
|
67
|
-
? (value == null ? '' : String(value))
|
|
67
|
+
? (value == null || typeof value === 'boolean' ? '' : String(value))
|
|
68
68
|
: Boolean(value)
|
|
69
69
|
const rec = el as unknown as Record<string, unknown>
|
|
70
70
|
if (rec[name] !== next)
|
package/src/dom/island.ts
CHANGED
|
@@ -71,7 +71,7 @@ function collectVisibleTargets(root: Element, out: Element[]): void {
|
|
|
71
71
|
function replayEvent(root: Element, ev: Event, target: EventTarget | null): void {
|
|
72
72
|
if (target === null || typeof target.dispatchEvent !== 'function')
|
|
73
73
|
return
|
|
74
|
-
if (typeof (target as Node).nodeType === 'number' && !root.contains(target as Node))
|
|
74
|
+
if (typeof (target as Node).nodeType === 'number' && target !== document && !root.contains(target as Node))
|
|
75
75
|
return
|
|
76
76
|
const init: EventInit = { bubbles: ev.bubbles, cancelable: ev.cancelable, composed: ev.composed }
|
|
77
77
|
let clone: Event
|
|
@@ -90,16 +90,31 @@ function replayEvent(root: Element, ev: Event, target: EventTarget | null): void
|
|
|
90
90
|
target.dispatchEvent(clone)
|
|
91
91
|
}
|
|
92
92
|
|
|
93
|
+
const MODIFIERS = ['Alt', 'Control', 'Meta', 'Shift']
|
|
94
|
+
|
|
95
|
+
// True when the key is one an element inside names with `aria-keyshortcuts="Control+K Meta+K"`, with exactly its modifiers held.
|
|
96
|
+
function isKeyShortcut(root: Element, e: KeyboardEvent): boolean {
|
|
97
|
+
for (const el of root.querySelectorAll('[aria-keyshortcuts]')) {
|
|
98
|
+
for (const combo of el.getAttribute('aria-keyshortcuts')!.split(' ')) {
|
|
99
|
+
const parts = combo.split('+')
|
|
100
|
+
if (parts.pop()!.toLowerCase() === e.key?.toLowerCase() && MODIFIERS.every(m => e.getModifierState(m) === parts.includes(m)))
|
|
101
|
+
return true
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return false
|
|
105
|
+
}
|
|
106
|
+
|
|
93
107
|
// A failed load keeps the listeners and drops the queued events: the next interaction loads the chunk again and is replayed once it is in.
|
|
108
|
+
// A shortcut the island declares is heard on the whole page, kept from the browser, and replayed on the document, where the component listens for it.
|
|
94
109
|
function watchInteraction(root: Element, onTrigger: (after: () => void) => Promise<boolean>): () => void {
|
|
95
110
|
const evs = ['pointerdown', 'click', 'focusin', 'keydown']
|
|
96
111
|
const queued: { ev: Event, target: EventTarget | null }[] = []
|
|
97
112
|
let loading = false
|
|
98
|
-
const go = (ev: Event) => {
|
|
113
|
+
const go = (ev: Event, target = ev.target) => {
|
|
99
114
|
// Prevent native toggle/submit/navigation before hydration so replaying the click triggers it once with handlers attached.
|
|
100
115
|
if (ev.type === 'click')
|
|
101
116
|
ev.preventDefault()
|
|
102
|
-
queued.push({ ev, target
|
|
117
|
+
queued.push({ ev, target })
|
|
103
118
|
if (!loading) {
|
|
104
119
|
loading = true
|
|
105
120
|
void onTrigger(() => {
|
|
@@ -113,9 +128,18 @@ function watchInteraction(root: Element, onTrigger: (after: () => void) => Promi
|
|
|
113
128
|
})
|
|
114
129
|
}
|
|
115
130
|
}
|
|
131
|
+
const onShortcut = (ev: Event) => {
|
|
132
|
+
if (!isKeyShortcut(root, ev as KeyboardEvent))
|
|
133
|
+
return
|
|
134
|
+
ev.preventDefault()
|
|
135
|
+
if (!root.contains(ev.target as Node))
|
|
136
|
+
go(ev, document)
|
|
137
|
+
}
|
|
116
138
|
for (const e of evs) root.addEventListener(e, go, true)
|
|
139
|
+
addEventListener('keydown', onShortcut, true)
|
|
117
140
|
return () => {
|
|
118
141
|
for (const e of evs) root.removeEventListener(e, go, true)
|
|
142
|
+
removeEventListener('keydown', onShortcut, true)
|
|
119
143
|
}
|
|
120
144
|
}
|
|
121
145
|
|
|
@@ -300,7 +324,9 @@ export function defineIslandElement(): void {
|
|
|
300
324
|
return true
|
|
301
325
|
}
|
|
302
326
|
this._d = dispose
|
|
303
|
-
|
|
327
|
+
// Queued behind the component's `onMount` callbacks, so a listener it binds there hears the replayed event.
|
|
328
|
+
if (after)
|
|
329
|
+
queueMicrotask(after)
|
|
304
330
|
return true
|
|
305
331
|
}
|
|
306
332
|
catch (err) {
|
package/src/jsx-runtime.ts
CHANGED
|
@@ -425,7 +425,7 @@ type VoidElementTagName =
|
|
|
425
425
|
| 'link' | 'meta' | 'param' | 'source' | 'track' | 'wbr'
|
|
426
426
|
|
|
427
427
|
type HtmlIntrinsicElements = {
|
|
428
|
-
[K in keyof HTMLElementTagNameMap]:
|
|
428
|
+
[K in Exclude<keyof HTMLElementTagNameMap, 'slot'>]:
|
|
429
429
|
(K extends keyof HtmlElementOverrides
|
|
430
430
|
? Omit<HTMLAttributes<HTMLElementTagNameMap[K]>, keyof HtmlElementOverrides[K] | (K extends VoidElementTagName ? 'children' : never)> & HtmlElementOverrides[K]
|
|
431
431
|
: Omit<HTMLAttributes<HTMLElementTagNameMap[K]>, K extends VoidElementTagName ? 'children' : never>)
|
package/src/plugins/services.ts
CHANGED
|
@@ -85,6 +85,7 @@ export const CMS_INLINE_ENABLED_SERVICE = serviceKey<boolean>('prunelle.cms.inli
|
|
|
85
85
|
export interface JobsQueueOptions {
|
|
86
86
|
attempts?: number | undefined
|
|
87
87
|
backoff?: 'exponential' | 'fixed' | number | undefined
|
|
88
|
+
timeout?: number | undefined
|
|
88
89
|
}
|
|
89
90
|
|
|
90
91
|
export interface JobsEnqueueOptions {
|
package/src/reactivity/index.ts
CHANGED
|
@@ -301,9 +301,17 @@ class EffectNode implements SubNode, Owner {
|
|
|
301
301
|
if (this.f & F.DISPOSED)
|
|
302
302
|
return
|
|
303
303
|
this.f &= ~(F.DIRTY | F.CHECK)
|
|
304
|
-
|
|
305
|
-
|
|
304
|
+
let errors: unknown[] | undefined
|
|
305
|
+
try {
|
|
306
|
+
releaseOwned(this)
|
|
307
|
+
}
|
|
308
|
+
catch (err) {
|
|
309
|
+
errors = [err]
|
|
310
|
+
}
|
|
311
|
+
if (this.f & F.DISPOSED) {
|
|
312
|
+
throwErrors(errors)
|
|
306
313
|
return
|
|
314
|
+
}
|
|
307
315
|
const prevSub = currentSub
|
|
308
316
|
const prevOwner = currentOwner
|
|
309
317
|
this.f |= F.RUNNING
|
|
@@ -320,12 +328,16 @@ class EffectNode implements SubNode, Owner {
|
|
|
320
328
|
;(this.cl ??= []).unshift(ret)
|
|
321
329
|
}
|
|
322
330
|
}
|
|
331
|
+
catch (err) {
|
|
332
|
+
;(errors ??= []).push(err)
|
|
333
|
+
}
|
|
323
334
|
finally {
|
|
324
335
|
unlinkRemaining(this)
|
|
325
336
|
this.f &= ~F.RUNNING
|
|
326
337
|
currentSub = prevSub
|
|
327
338
|
currentOwner = prevOwner
|
|
328
339
|
}
|
|
340
|
+
throwErrors(errors)
|
|
329
341
|
}
|
|
330
342
|
}
|
|
331
343
|
|
package/src/server/action.ts
CHANGED
|
@@ -157,54 +157,58 @@ function isPlainRecord(value: unknown): value is Record<string, unknown> {
|
|
|
157
157
|
return typeof value === 'object' && value !== null && !Array.isArray(value) && !(value instanceof Blob)
|
|
158
158
|
}
|
|
159
159
|
|
|
160
|
-
|
|
160
|
+
/** A form field whose name both holds a value and nests dotted fields (`a` and `a.b`): the body has no shape that keeps both. */
|
|
161
|
+
class FormFieldConflict extends Error {
|
|
162
|
+
constructor(readonly field: string) {
|
|
163
|
+
super(`form field "${field}" conflicts with another field`)
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function appendFormValue(target: Record<string, unknown>, key: string, value: FormDataEntryValue, forceArray: boolean, rawKey: string): void {
|
|
161
168
|
if (!Object.hasOwn(target, key)) {
|
|
162
169
|
setField(target, key, forceArray ? [value] : value)
|
|
163
170
|
return
|
|
164
171
|
}
|
|
165
172
|
const prev = target[key]
|
|
173
|
+
if (isPlainRecord(prev))
|
|
174
|
+
throw new FormFieldConflict(rawKey)
|
|
166
175
|
if (Array.isArray(prev))
|
|
167
176
|
prev.push(value)
|
|
168
177
|
else
|
|
169
178
|
setField(target, key, [prev, value])
|
|
170
179
|
}
|
|
171
180
|
|
|
172
|
-
/** Parses `FormData` into a plain record, mapping trailing `[]` names to arrays and dotted names (`a.b`, `a.b.c`) to nested objects safely. */
|
|
181
|
+
/** Parses `FormData` into a plain record, mapping trailing `[]` names to arrays and dotted names (`a.b`, `a.b.c`) to nested objects safely; throws `FormFieldConflict` when a name both holds a value and nests others. */
|
|
173
182
|
export function parseFormData(formData: FormData): Record<string, unknown> {
|
|
174
183
|
const out: Record<string, unknown> = {}
|
|
175
184
|
for (const [rawKey, val] of formData.entries()) {
|
|
176
185
|
const forceArray = rawKey.length > 2 && rawKey.endsWith('[]')
|
|
177
186
|
const key = forceArray ? rawKey.slice(0, -2) : rawKey
|
|
178
187
|
if (!key.includes('.')) {
|
|
179
|
-
appendFormValue(out, key, val, forceArray)
|
|
188
|
+
appendFormValue(out, key, val, forceArray, rawKey)
|
|
180
189
|
continue
|
|
181
190
|
}
|
|
182
191
|
const parts = key.split('.')
|
|
183
192
|
if (parts.some(p => UNSAFE_NESTED_KEYS.has(p)))
|
|
184
193
|
continue
|
|
185
194
|
if (parts.length > MAX_NESTED_DEPTH || parts.some(p => p.length === 0)) {
|
|
186
|
-
appendFormValue(out, key, val, forceArray)
|
|
195
|
+
appendFormValue(out, key, val, forceArray, rawKey)
|
|
187
196
|
continue
|
|
188
197
|
}
|
|
189
198
|
let cur = out
|
|
190
|
-
|
|
191
|
-
for (let i = 0; i < parts.length - 1; i++) {
|
|
192
|
-
const seg = parts[i]!
|
|
199
|
+
for (const seg of parts.slice(0, -1)) {
|
|
193
200
|
if (!Object.hasOwn(cur, seg)) {
|
|
194
201
|
const next: Record<string, unknown> = {}
|
|
195
202
|
setField(cur, seg, next)
|
|
196
203
|
cur = next
|
|
204
|
+
continue
|
|
197
205
|
}
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
blocked = true
|
|
203
|
-
break
|
|
204
|
-
}
|
|
206
|
+
const held = cur[seg]
|
|
207
|
+
if (!isPlainRecord(held))
|
|
208
|
+
throw new FormFieldConflict(rawKey)
|
|
209
|
+
cur = held
|
|
205
210
|
}
|
|
206
|
-
|
|
207
|
-
appendFormValue(cur, parts[parts.length - 1]!, val, forceArray)
|
|
211
|
+
appendFormValue(cur, parts[parts.length - 1]!, val, forceArray, rawKey)
|
|
208
212
|
}
|
|
209
213
|
return out
|
|
210
214
|
}
|
|
@@ -448,8 +452,12 @@ export async function executeAction(
|
|
|
448
452
|
try {
|
|
449
453
|
rawBody = await parseActionBody(request)
|
|
450
454
|
}
|
|
451
|
-
catch {
|
|
452
|
-
|
|
455
|
+
catch (error) {
|
|
456
|
+
if (!(error instanceof FormFieldConflict))
|
|
457
|
+
return Response.json({ ok: false, status: 400, error: 'Invalid request body' }, { status: 400 })
|
|
458
|
+
const fieldErrors = { [error.field]: 'This field conflicts with another field of the form' }
|
|
459
|
+
return flashAndRedirect('Invalid request body', fieldErrors, undefined)
|
|
460
|
+
?? Response.json({ ok: false, status: 400, error: 'Invalid request body', fieldErrors }, { status: 400 })
|
|
453
461
|
}
|
|
454
462
|
}
|
|
455
463
|
|
package/src/server/assets.ts
CHANGED
|
@@ -34,16 +34,34 @@ export interface PrerenderedSources {
|
|
|
34
34
|
isFast: (urlPath: string, route: RouteManifestEntry) => boolean
|
|
35
35
|
}
|
|
36
36
|
|
|
37
|
-
|
|
37
|
+
/** Shared MIME table for `public/`, hashed assets, prerendered files and `prunelle start --static`. */
|
|
38
|
+
export const STATIC_MIME: Readonly<Record<string, string>> = {
|
|
39
|
+
...MIME,
|
|
38
40
|
'.htm': 'text/html; charset=utf-8',
|
|
39
41
|
'.rss': 'application/rss+xml; charset=utf-8',
|
|
40
42
|
'.atom': 'application/atom+xml; charset=utf-8',
|
|
41
43
|
'.ics': 'text/calendar; charset=utf-8',
|
|
42
44
|
'.csv': 'text/csv; charset=utf-8',
|
|
45
|
+
'.vtt': 'text/vtt; charset=utf-8',
|
|
46
|
+
'.geojson': 'application/geo+json; charset=utf-8',
|
|
47
|
+
'.mp3': 'audio/mpeg',
|
|
48
|
+
'.ogg': 'audio/ogg',
|
|
49
|
+
'.oga': 'audio/ogg',
|
|
50
|
+
'.ogv': 'video/ogg',
|
|
51
|
+
'.m4a': 'audio/mp4',
|
|
52
|
+
'.wav': 'audio/wav',
|
|
53
|
+
'.flac': 'audio/flac',
|
|
54
|
+
'.opus': 'audio/opus',
|
|
55
|
+
'.zip': 'application/zip',
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** MIME type for a file extension, falling back to `application/octet-stream`. */
|
|
59
|
+
export function staticMime(ext: string): string {
|
|
60
|
+
return STATIC_MIME[ext.toLowerCase()] ?? 'application/octet-stream'
|
|
43
61
|
}
|
|
44
62
|
|
|
45
63
|
function prerenderedMime(ext: string, filePath: string | undefined): string {
|
|
46
|
-
const mapped =
|
|
64
|
+
const mapped = STATIC_MIME[ext.toLowerCase()]
|
|
47
65
|
if (mapped !== undefined)
|
|
48
66
|
return mapped
|
|
49
67
|
if (filePath !== undefined) {
|
|
@@ -74,7 +92,7 @@ export function createAssets(options: AssetsOptions) {
|
|
|
74
92
|
|
|
75
93
|
const registerPublic = (rel: string, body: EmbeddedBody, etag?: string, sidecars: ReturnType<typeof sidecarsOf> = { br: undefined, gz: undefined }): void => {
|
|
76
94
|
const cleanRel = rel.replace(/^\/+/, '')
|
|
77
|
-
const type =
|
|
95
|
+
const type = staticMime(extname(cleanRel))
|
|
78
96
|
publicMap.set(`/${cleanRel}`, servedFile({
|
|
79
97
|
key: `p:/${cleanRel}`,
|
|
80
98
|
source: embedded(body),
|
|
@@ -105,7 +123,7 @@ export function createAssets(options: AssetsOptions) {
|
|
|
105
123
|
for (const [rel, body] of Object.entries(assets)) {
|
|
106
124
|
if ((rel.endsWith('.br') || rel.endsWith('.gz')) && rel.slice(0, -3) in assets)
|
|
107
125
|
continue
|
|
108
|
-
const type =
|
|
126
|
+
const type = staticMime(extname(rel))
|
|
109
127
|
const sidecar = (ext: 'br' | 'gz'): FileSource | undefined => {
|
|
110
128
|
const source = assets[`${rel}.${ext}`] ?? (typeof body === 'string' && existsSync(`${body}.${ext}`) ? `${body}.${ext}` : undefined)
|
|
111
129
|
return source === undefined ? undefined : embedded(source)
|
package/src/server/consent.ts
CHANGED
|
@@ -75,6 +75,8 @@ export function normalizeConsentConfig(config: ConsentConfig | undefined): Norma
|
|
|
75
75
|
continue
|
|
76
76
|
if (name.includes(',') || name.includes(':'))
|
|
77
77
|
throw new Error(`prunelle: consent category "${name}" cannot contain "," or ":"`)
|
|
78
|
+
if (name === 'action' || name === 'redirect' || name === 'categories')
|
|
79
|
+
throw new Error(`prunelle: consent category "${name}" is reserved by the consent form; choose another category name.`)
|
|
78
80
|
categorySet.add(name)
|
|
79
81
|
categories.push(name)
|
|
80
82
|
labels[name] = given[item]?.trim() || name
|
|
@@ -116,7 +118,10 @@ export function parseConsentCookie(raw: string | undefined, declared: ReadonlySe
|
|
|
116
118
|
return version === '' ? { decided: true, decidedAt: undefined, granted: grantedOf(raw.slice(LEGACY_COOKIE_PREFIX.length), declared) } : none
|
|
117
119
|
if (!raw.startsWith(COOKIE_PREFIX))
|
|
118
120
|
return none
|
|
119
|
-
const
|
|
121
|
+
const parts = raw.slice(COOKIE_PREFIX.length).split(':')
|
|
122
|
+
if (parts.length !== 3)
|
|
123
|
+
return none
|
|
124
|
+
const [seconds, storedVersion, list] = parts
|
|
120
125
|
const at = Number(seconds)
|
|
121
126
|
if (list === undefined || storedVersion !== version || !Number.isSafeInteger(at) || at <= 0)
|
|
122
127
|
return none
|
|
@@ -243,7 +248,7 @@ async function parseConsentSubmission(
|
|
|
243
248
|
|
|
244
249
|
const listed = new Set(form.getAll('categories').filter((v): v is string => typeof v === 'string'))
|
|
245
250
|
for (const cat of config.categories) {
|
|
246
|
-
if (listed.has(cat) || isTruthyFormValue(form.get(cat)))
|
|
251
|
+
if (listed.has(cat) || (cat !== 'action' && cat !== 'redirect' && cat !== 'categories' && isTruthyFormValue(form.get(cat))))
|
|
247
252
|
granted.add(cat)
|
|
248
253
|
}
|
|
249
254
|
return { ok: true, granted, redirect }
|
package/src/server/cookies.ts
CHANGED
|
@@ -73,7 +73,14 @@ function serializeCookie(name: string, value: string, options: CookieOptions = {
|
|
|
73
73
|
if (sameSite === 'none' && !secure)
|
|
74
74
|
throw new Error(`prunelle: Cookie "${name}" with sameSite: "none" requires secure: true`)
|
|
75
75
|
|
|
76
|
-
let
|
|
76
|
+
let encoded: string
|
|
77
|
+
try {
|
|
78
|
+
encoded = encodeURIComponent(value)
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
throw new TypeError(`prunelle: invalid cookie value for "${name}": contains an unpaired UTF-16 surrogate; sanitize with value.toWellFormed() before setting the cookie.`)
|
|
82
|
+
}
|
|
83
|
+
let out = `${name}=${encoded}`
|
|
77
84
|
out += `; Path=${path}`
|
|
78
85
|
if (options.domain !== undefined)
|
|
79
86
|
out += `; Domain=${options.domain}`
|
package/src/server/errors.ts
CHANGED
|
@@ -20,10 +20,14 @@ import { styleHashesOf } from './security'
|
|
|
20
20
|
|
|
21
21
|
export type NotifyError = (error: unknown, request: Request, source: ServerErrorInfo['source'], requestId?: string) => void
|
|
22
22
|
|
|
23
|
+
const describeNonError = (error: unknown): string => error instanceof Response
|
|
24
|
+
? `prunelle: a Response (HTTP ${error.status}) was thrown instead of returned; return it from load() or the route handler instead.`
|
|
25
|
+
: String(error)
|
|
26
|
+
|
|
23
27
|
/** The text of an error a dev response shows: its stack, which starts with its message. */
|
|
24
|
-
export const errorDetail = (error: unknown): string => error instanceof Error ? error.stack ?? error.message :
|
|
28
|
+
export const errorDetail = (error: unknown): string => error instanceof Error ? error.stack ?? error.message : describeNonError(error)
|
|
25
29
|
|
|
26
|
-
const errorMessage = (error: unknown): string => error instanceof Error ? error.message :
|
|
30
|
+
const errorMessage = (error: unknown): string => error instanceof Error ? error.message : describeNonError(error)
|
|
27
31
|
|
|
28
32
|
const HTML_ESCAPE_RE = /[&<>"']/g
|
|
29
33
|
const HTML_ESCAPES: Record<string, string> = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }
|
|
@@ -57,11 +61,14 @@ export function createErrorNotifier(onError: ((info: ServerErrorInfo) => void) |
|
|
|
57
61
|
errorHooks.push({ owner: p.name, hook: p.onError })
|
|
58
62
|
}
|
|
59
63
|
return (error, request, source, requestId) => {
|
|
60
|
-
const
|
|
64
|
+
const normalized = error instanceof Response
|
|
65
|
+
? (void error.body?.cancel().catch(() => undefined), new Error(describeNonError(error)))
|
|
66
|
+
: error
|
|
67
|
+
const info: ServerErrorInfo = requestId !== undefined ? { error: normalized, request, source, requestId } : { error: normalized, request, source }
|
|
61
68
|
options.sink?.(info)
|
|
62
69
|
if (errorHooks.length === 0 && (options.dev === true || options.sink === undefined)) {
|
|
63
70
|
const idSuffix = requestId !== undefined ? ` [${requestId}]` : ''
|
|
64
|
-
console.error(`prunelle: unhandled error in ${source} ${request.method} ${new URL(request.url).pathname}${idSuffix}`,
|
|
71
|
+
console.error(`prunelle: unhandled error in ${source} ${request.method} ${new URL(request.url).pathname}${idSuffix}`, normalized)
|
|
65
72
|
}
|
|
66
73
|
for (const { owner, hook } of errorHooks) {
|
|
67
74
|
try {
|
|
@@ -89,8 +96,13 @@ interface CompiledStatusPage {
|
|
|
89
96
|
doc: DocumentOptions
|
|
90
97
|
}
|
|
91
98
|
|
|
99
|
+
interface StatusPageHit {
|
|
100
|
+
page: CompiledStatusPage
|
|
101
|
+
params?: Record<string, string>
|
|
102
|
+
}
|
|
103
|
+
|
|
92
104
|
interface StatusPageLookup {
|
|
93
|
-
|
|
105
|
+
findAll: (kind: StatusPageKind, url?: URL, routeFile?: string) => StatusPageHit[]
|
|
94
106
|
}
|
|
95
107
|
|
|
96
108
|
function dirnamePrefix(file: string): string {
|
|
@@ -184,7 +196,16 @@ function buildStatusPageLookup(
|
|
|
184
196
|
}
|
|
185
197
|
|
|
186
198
|
return {
|
|
187
|
-
|
|
199
|
+
findAll(kind, url, routeFile) {
|
|
200
|
+
const out: StatusPageHit[] = []
|
|
201
|
+
const seen = new Set<CompiledStatusPage>()
|
|
202
|
+
const push = (page: CompiledStatusPage, params?: Record<string, string>) => {
|
|
203
|
+
if (seen.has(page))
|
|
204
|
+
return
|
|
205
|
+
seen.add(page)
|
|
206
|
+
out.push(params !== undefined ? { page, params } : { page })
|
|
207
|
+
}
|
|
208
|
+
|
|
188
209
|
if (routeFile !== undefined) {
|
|
189
210
|
const dirMap = byDirPrefix.get(kind)
|
|
190
211
|
if (dirMap !== undefined) {
|
|
@@ -192,27 +213,27 @@ function buildStatusPageLookup(
|
|
|
192
213
|
while (dir !== undefined) {
|
|
193
214
|
const hit = dirMap.get(dir)
|
|
194
215
|
if (hit !== undefined)
|
|
195
|
-
|
|
216
|
+
push(hit)
|
|
196
217
|
if (dir === routesPrefix || !dir.startsWith(routesPrefix))
|
|
197
218
|
break
|
|
198
219
|
dir = parentDirPrefix(dir)
|
|
199
220
|
}
|
|
200
221
|
const rootHit = dirMap.get(routesPrefix)
|
|
201
222
|
if (rootHit !== undefined)
|
|
202
|
-
|
|
223
|
+
push(rootHit)
|
|
203
224
|
}
|
|
204
|
-
return
|
|
225
|
+
return out
|
|
205
226
|
}
|
|
206
227
|
|
|
207
228
|
const decoded = decodeRequestPath(url?.pathname ?? '/')
|
|
208
229
|
if (decoded === undefined)
|
|
209
|
-
return
|
|
230
|
+
return out
|
|
210
231
|
const urlRouter = byUrlRouter.get(kind)
|
|
211
232
|
if (urlRouter !== undefined) {
|
|
212
233
|
for (let i = decoded.segments.length; i >= 0; i--) {
|
|
213
234
|
const matched = urlRouter.match(pathPrefix(decoded, i))
|
|
214
235
|
if (matched !== undefined)
|
|
215
|
-
|
|
236
|
+
push(matched.data, matched.params)
|
|
216
237
|
}
|
|
217
238
|
}
|
|
218
239
|
const fallbackGroup = groupUrlRouter.get(kind)
|
|
@@ -220,10 +241,10 @@ function buildStatusPageLookup(
|
|
|
220
241
|
for (let i = decoded.segments.length; i >= 0; i--) {
|
|
221
242
|
const matched = fallbackGroup.match(pathPrefix(decoded, i))
|
|
222
243
|
if (matched !== undefined)
|
|
223
|
-
|
|
244
|
+
push(matched.data, matched.params)
|
|
224
245
|
}
|
|
225
246
|
}
|
|
226
|
-
return
|
|
247
|
+
return out
|
|
227
248
|
},
|
|
228
249
|
}
|
|
229
250
|
}
|
|
@@ -321,11 +342,11 @@ export function createFallbackPages(options: FallbackPagesOptions) {
|
|
|
321
342
|
|
|
322
343
|
async function buildErrorResponse(error: unknown, url?: URL, req?: Request, ctx?: RequestContext, routeFile?: string): Promise<Response> {
|
|
323
344
|
const effUrl = url ?? new URL('http://localhost/500')
|
|
324
|
-
const
|
|
325
|
-
|
|
345
|
+
const candidates = lookup.findAll('error', effUrl, routeFile)
|
|
346
|
+
// Outside dev the page gets a bare error: a thrown message can name a host, a table or a credential, and it lands in HTML anyone can load.
|
|
347
|
+
const shown = options.dev ? error : Object.assign(new Error('Internal Server Error'), { stack: 'Error: Internal Server Error' })
|
|
348
|
+
for (const found of candidates) {
|
|
326
349
|
const params = ctx !== undefined && Object.keys(ctx.params).length > 0 ? ctx.params : (found.params ?? {})
|
|
327
|
-
// Outside dev the page gets a bare error: a thrown message can name a host, a table or a credential, and it lands in HTML anyone can load.
|
|
328
|
-
const shown = options.dev ? error : Object.assign(new Error('Internal Server Error'), { stack: 'Error: Internal Server Error' })
|
|
329
350
|
const rendered = await renderCompiledStatusPage(
|
|
330
351
|
found.page,
|
|
331
352
|
500,
|
|
@@ -338,13 +359,19 @@ export function createFallbackPages(options: FallbackPagesOptions) {
|
|
|
338
359
|
if (rendered !== undefined)
|
|
339
360
|
return rendered
|
|
340
361
|
}
|
|
341
|
-
|
|
362
|
+
const text = options.dev ? errorDetail(error) : 'Internal Server Error'
|
|
363
|
+
if (candidates.length > 0) {
|
|
364
|
+
return new Response(req?.method === 'HEAD' ? null : minimalStatusHtml(500, text, options.lang), {
|
|
365
|
+
status: 500,
|
|
366
|
+
headers: htmlHeaders(false, false, true, fallbackHeadStyleHashes),
|
|
367
|
+
})
|
|
368
|
+
}
|
|
369
|
+
return new Response(req?.method === 'HEAD' ? null : text, { status: 500, headers: { 'content-type': 'text/plain; charset=utf-8' } })
|
|
342
370
|
}
|
|
343
371
|
|
|
344
372
|
async function buildNotFoundResponse(url?: URL, req?: Request, ctx?: RequestContext, routeFile?: string): Promise<Response> {
|
|
345
373
|
const effUrl = url ?? new URL('http://localhost/404')
|
|
346
|
-
const found
|
|
347
|
-
if (found !== undefined) {
|
|
374
|
+
for (const found of lookup.findAll('404', effUrl, routeFile)) {
|
|
348
375
|
const params = ctx !== undefined && Object.keys(ctx.params).length > 0 ? ctx.params : (found.params ?? {})
|
|
349
376
|
const rendered = await renderCompiledStatusPage(
|
|
350
377
|
found.page,
|
|
@@ -363,13 +390,17 @@ export function createFallbackPages(options: FallbackPagesOptions) {
|
|
|
363
390
|
|
|
364
391
|
async function renderDenied(denied: DeniedInfo, url: URL, req: Request, ctx?: RequestContext, routeFile?: string): Promise<Response> {
|
|
365
392
|
const statusKey = String(denied.status)
|
|
366
|
-
const
|
|
367
|
-
const found
|
|
368
|
-
|
|
393
|
+
const statusHits = STATUS_KINDS.has(statusKey) ? lookup.findAll(statusKey as StatusPageKind, url, routeFile) : []
|
|
394
|
+
for (const found of statusHits) {
|
|
395
|
+
const params = ctx !== undefined && Object.keys(ctx.params).length > 0 ? ctx.params : (found.params ?? {})
|
|
396
|
+
const props = { status: denied.status, message: denied.message, url, params, locals: ctx?.locals ?? {} }
|
|
397
|
+
const rendered = await renderCompiledStatusPage(found.page, denied.status, props, url, params, req, ctx)
|
|
398
|
+
if (rendered !== undefined)
|
|
399
|
+
return rendered
|
|
400
|
+
}
|
|
401
|
+
for (const found of lookup.findAll('error', url, routeFile)) {
|
|
369
402
|
const params = ctx !== undefined && Object.keys(ctx.params).length > 0 ? ctx.params : (found.params ?? {})
|
|
370
|
-
const props =
|
|
371
|
-
? { status: denied.status, message: denied.message, url, params, locals: ctx?.locals ?? {} }
|
|
372
|
-
: { error: new Error(denied.message), status: denied.status, message: denied.message, url, params, locals: ctx?.locals ?? {} }
|
|
403
|
+
const props = { error: new Error(denied.message), status: denied.status, message: denied.message, url, params, locals: ctx?.locals ?? {} }
|
|
373
404
|
const rendered = await renderCompiledStatusPage(found.page, denied.status, props, url, params, req, ctx)
|
|
374
405
|
if (rendered !== undefined)
|
|
375
406
|
return rendered
|
package/src/server/http.ts
CHANGED
|
@@ -167,7 +167,7 @@ export type Middleware = (ctx: RequestContext, next: () => Promise<Response>) =>
|
|
|
167
167
|
export type PrunelleServer = ReturnType<typeof Bun.serve>
|
|
168
168
|
|
|
169
169
|
export interface PrunelleApp {
|
|
170
|
-
handle: (request: Request, remoteIp?: string,
|
|
170
|
+
handle: (request: Request, remoteIp?: string, setIdleTimeout?: (seconds: number) => void) => Promise<Response>
|
|
171
171
|
serve: (port?: number, hostname?: string) => PrunelleServer
|
|
172
172
|
/** @internal Swaps this app's handlers into a server another app started, with no dropped connection: `prunelle start` reloads a new build with it. */
|
|
173
173
|
reloadInto?: (server: PrunelleServer) => void
|
package/src/server/index.ts
CHANGED
|
@@ -440,7 +440,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
440
440
|
}
|
|
441
441
|
|
|
442
442
|
// `bodyLimited` is set under `serve()`, where Bun.serve already enforces maxRequestBodySize on every body, chunked ones included.
|
|
443
|
-
async function handleInternal(request: Request, remoteIp?: string,
|
|
443
|
+
async function handleInternal(request: Request, remoteIp?: string, setIdleTimeout?: (seconds: number) => void, bodyLimited = false): Promise<Response> {
|
|
444
444
|
const requestId = resolveRequestId(request)
|
|
445
445
|
try {
|
|
446
446
|
const url = new URL(request.url)
|
|
@@ -522,7 +522,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
522
522
|
if (headFallbackPluginDef !== undefined)
|
|
523
523
|
res = stripHeadBody(res)
|
|
524
524
|
else if (isEventStream(res))
|
|
525
|
-
res = streams.track(res,
|
|
525
|
+
res = streams.track(res, setIdleTimeout)
|
|
526
526
|
return finish(await maybeCompressResponse(await withPluginHtmlCsp(res, htmlHeaders), ctx.request, compressCache), ctx.request, cookieStore, requestId, formatServerTiming(timing))
|
|
527
527
|
}
|
|
528
528
|
catch (error) {
|
|
@@ -577,9 +577,9 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
577
577
|
: route.middlewares
|
|
578
578
|
|
|
579
579
|
try {
|
|
580
|
-
const rawRes = await actions.run(ctx, () => runTimedChain(ctx, routeMiddlewares, () => renderCompiledRoute(route, ctx, cookieStore,
|
|
580
|
+
const rawRes = await actions.run(ctx, () => runTimedChain(ctx, routeMiddlewares, () => renderCompiledRoute(route, ctx, cookieStore, setIdleTimeout, staticPath, timing, routeMiddlewares), timing, runChain))
|
|
581
581
|
const handledRes = await maybeRenderDenied(rawRes, ctx.request, ctx.url, ctx, renderDenied, route.entry.file, isApiHandler(route.mod, method))
|
|
582
|
-
const res = isEventStream(handledRes) ? streams.track(handledRes,
|
|
582
|
+
const res = isEventStream(handledRes) ? streams.track(handledRes, setIdleTimeout) : handledRes
|
|
583
583
|
// Compress uncompressed API/middleware responses after the middleware chain unwinds.
|
|
584
584
|
const finalRes = res.headers.has('content-encoding') ? res : await maybeCompressResponse(res, ctx.request, compressCache)
|
|
585
585
|
return finish(finalRes, ctx.request, cookieStore, requestId, formatServerTiming(timing))
|
|
@@ -595,11 +595,11 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
|
|
|
595
595
|
}
|
|
596
596
|
}
|
|
597
597
|
|
|
598
|
-
function handle(request: Request, remoteIp?: string,
|
|
599
|
-
return runWithAppContext(serverAppCtx, () => handleInternal(request, remoteIp,
|
|
598
|
+
function handle(request: Request, remoteIp?: string, setIdleTimeout?: (seconds: number) => void): Promise<Response> {
|
|
599
|
+
return runWithAppContext(serverAppCtx, () => handleInternal(request, remoteIp, setIdleTimeout))
|
|
600
600
|
}
|
|
601
601
|
|
|
602
|
-
const runRequest = (req: Request, remoteIp: string | undefined,
|
|
602
|
+
const runRequest = (req: Request, remoteIp: string | undefined, setIdleTimeout: (seconds: number) => void): Promise<Response> => runWithAppContext(serverAppCtx, () => handleInternal(req, remoteIp, setIdleTimeout, true))
|
|
603
603
|
const runFast = (handler: FastHandler, req: Request, remoteIp: string | undefined): Response | Promise<Response> => runWithAppContext(serverAppCtx, () => handler(req, remoteIp))
|
|
604
604
|
const handlers = (server: () => PrunelleServer | undefined) => serveHandlers(server, { files, fastPrerenderedMap, fastStaticPages, pluginRouter, healthPath, healthHandler, resolveRequestId, runRequest, runFast, notifyError, serverError, fileGone })
|
|
605
605
|
|
package/src/server/page.ts
CHANGED
|
@@ -12,6 +12,10 @@ export interface LoadedPageModule {
|
|
|
12
12
|
load?: (ctx: RequestContext) => unknown | Promise<unknown>
|
|
13
13
|
clientData?: readonly string[] | ((data: unknown) => unknown) | undefined
|
|
14
14
|
csrf?: boolean | undefined
|
|
15
|
+
/** The language the page is written in, for its `<html lang>`, when it differs from `lang` in prunelle.config.ts. */
|
|
16
|
+
lang?: string | undefined
|
|
17
|
+
/** How long this route's request may stay silent before the connection closes, in seconds or a duration string (`'5m'`), `0` for no limit; the server's is 30 s. */
|
|
18
|
+
idleTimeout?: number | string | undefined
|
|
15
19
|
GET?: (ctx: RequestContext) => Response | Promise<Response>
|
|
16
20
|
POST?: (ctx: RequestContext) => Response | Promise<Response>
|
|
17
21
|
PUT?: (ctx: RequestContext) => Response | Promise<Response>
|