prunelle 0.1.1 → 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.
Files changed (48) hide show
  1. package/llms.txt +12 -12
  2. package/package.json +1 -1
  3. package/src/build/client-entries.ts +3 -2
  4. package/src/build/compile.ts +2 -1
  5. package/src/build/index.ts +68 -29
  6. package/src/build/manifest.ts +18 -1
  7. package/src/build/output.ts +2 -2
  8. package/src/build/precompress.ts +15 -2
  9. package/src/build/prerender.ts +2 -2
  10. package/src/build/routes.ts +171 -10
  11. package/src/build/static.ts +71 -17
  12. package/src/build/status-pages.ts +127 -0
  13. package/src/cli/check-forms.ts +654 -0
  14. package/src/cli/check-links.ts +619 -0
  15. package/src/cli/check.ts +37 -4
  16. package/src/cli/commands.ts +5 -3
  17. package/src/cli/inspect.ts +21 -2
  18. package/src/cli/upgrade-names.ts +73 -13
  19. package/src/cli/upgrade.ts +137 -16
  20. package/src/compiler/compliance-rgaa.ts +502 -0
  21. package/src/compiler/compliance.ts +119 -220
  22. package/src/compiler/ssr.ts +121 -24
  23. package/src/dom/action.ts +4 -1
  24. package/src/dom/island.ts +5 -5
  25. package/src/plugins/config.ts +1 -1
  26. package/src/plugins/types.ts +13 -0
  27. package/src/server/action-protect.ts +186 -0
  28. package/src/server/action.ts +33 -10
  29. package/src/server/errors.ts +291 -62
  30. package/src/server/form-schema.ts +343 -0
  31. package/src/server/health.ts +244 -0
  32. package/src/server/http.ts +84 -17
  33. package/src/server/index.ts +162 -91
  34. package/src/server/param-matchers.ts +112 -0
  35. package/src/server/plugin-host.ts +40 -14
  36. package/src/server/public.ts +3 -3
  37. package/src/server/route-table.ts +5 -2
  38. package/src/server/router.ts +125 -40
  39. package/src/server/routing.ts +95 -57
  40. package/src/server/security.ts +171 -22
  41. package/src/server/serve-handlers.ts +21 -7
  42. package/src/ssr/context.ts +49 -0
  43. package/src/ssr/index.ts +120 -1
  44. package/src/test/browser.ts +6 -0
  45. package/src/test/index.ts +17 -3
  46. package/templates/_shared/src/routes/legal.tsx +5 -0
  47. package/templates/blog/prunelle.config.ts +1 -1
  48. package/templates/blog/src/routes/index.tsx +4 -0
@@ -0,0 +1,343 @@
1
+ // Extracts per-field HTML5 constraints and known field names from Standard Schema JSON Schema output.
2
+
3
+ import type { StandardSchemaV1 } from './standard-schema'
4
+
5
+ export interface FieldConstraint {
6
+ required?: boolean | undefined
7
+ type?: 'email' | 'url' | 'number' | undefined
8
+ minLength?: number | undefined
9
+ maxLength?: number | undefined
10
+ min?: number | undefined
11
+ max?: number | undefined
12
+ step?: number | 'any' | undefined
13
+ pattern?: string | undefined
14
+ enumValues?: readonly string[] | undefined
15
+ isArray?: boolean | undefined
16
+ }
17
+
18
+ export type ExtractedFormSchema =
19
+ | {
20
+ ok: true
21
+ fields: ReadonlyMap<string, FieldConstraint>
22
+ required: ReadonlySet<string>
23
+ jsonSchema: Record<string, unknown>
24
+ }
25
+ | {
26
+ ok: false
27
+ vendor: string
28
+ }
29
+
30
+ interface JsonSchemaCapable {
31
+ '~standard'?: {
32
+ vendor?: unknown
33
+ jsonSchema?: {
34
+ input?: (opts: { target: string }) => Record<string, unknown>
35
+ } | undefined
36
+ } | undefined
37
+ toJSONSchema?: (() => Record<string, unknown>) | undefined
38
+ jsonSchema?: Record<string, unknown> | undefined
39
+ }
40
+
41
+ const SAFE_INT_MIN = Number.MIN_SAFE_INTEGER
42
+ const SAFE_INT_MAX = Number.MAX_SAFE_INTEGER
43
+ const schemaCache = new WeakMap<StandardSchemaV1, ExtractedFormSchema>()
44
+
45
+ function isRecord(value: unknown): value is Record<string, unknown> {
46
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
47
+ }
48
+
49
+ function readRawJsonSchema(schema: StandardSchemaV1): Record<string, unknown> | undefined {
50
+ const candidate = schema as unknown as JsonSchemaCapable
51
+ const stdJson = candidate['~standard']?.jsonSchema
52
+ if (stdJson !== undefined && typeof stdJson.input === 'function') {
53
+ for (const target of ['draft-2020-12', 'draft-07']) {
54
+ try {
55
+ const out = stdJson.input({ target })
56
+ if (isRecord(out))
57
+ return out
58
+ }
59
+ catch {
60
+ continue
61
+ }
62
+ }
63
+ }
64
+ if (typeof candidate.toJSONSchema === 'function') {
65
+ try {
66
+ const out = candidate.toJSONSchema()
67
+ if (isRecord(out))
68
+ return out
69
+ }
70
+ catch {
71
+ return undefined
72
+ }
73
+ }
74
+ if (isRecord(candidate.jsonSchema))
75
+ return candidate.jsonSchema
76
+ return undefined
77
+ }
78
+
79
+ function resolveRef(node: Record<string, unknown>, root: Record<string, unknown>, seen: Set<string>): Record<string, unknown> {
80
+ const ref = node.$ref
81
+ if (typeof ref !== 'string' || !ref.startsWith('#/') || seen.has(ref))
82
+ return node
83
+ seen.add(ref)
84
+ const segments = ref.slice(2).split('/').map(s => s.replaceAll('~1', '/').replaceAll('~0', '~'))
85
+ let cur: unknown = root
86
+ for (const seg of segments) {
87
+ if (!isRecord(cur) || !Object.hasOwn(cur, seg))
88
+ return node
89
+ cur = cur[seg]
90
+ }
91
+ return isRecord(cur) ? resolveRef(cur, root, seen) : node
92
+ }
93
+
94
+ function isNullSchema(node: Record<string, unknown>): boolean {
95
+ return node.type === 'null' || (Array.isArray(node.enum) && node.enum.length === 1 && node.enum[0] === null)
96
+ }
97
+
98
+ function collectEnumValues(node: Record<string, unknown>): string[] | undefined {
99
+ if (Array.isArray(node.enum)) {
100
+ const vals = node.enum.filter((v): v is string | number => typeof v === 'string' || typeof v === 'number').map(String)
101
+ return vals.length > 0 ? vals : undefined
102
+ }
103
+ if (typeof node.const === 'string' || typeof node.const === 'number')
104
+ return [String(node.const)]
105
+ return undefined
106
+ }
107
+
108
+ function branchSpecificity(branch: Record<string, unknown>): number {
109
+ if (branch.type === 'number' || branch.type === 'integer')
110
+ return 4
111
+ if (branch.format === 'email' || branch.format === 'idn-email' || branch.format === 'uri' || branch.format === 'url')
112
+ return 3
113
+ if (branch.enum !== undefined || branch.const !== undefined)
114
+ return 2
115
+ if (branch.type === 'string' && (branch.minLength !== undefined || branch.maxLength !== undefined || branch.pattern !== undefined))
116
+ return 2
117
+ if (branch.type === 'array' || branch.type === 'object')
118
+ return 2
119
+ return 1
120
+ }
121
+
122
+ function unwrapUnion(node: Record<string, unknown>, root: Record<string, unknown>): { primary: Record<string, unknown>, unionEnums?: string[] | undefined } {
123
+ const rawList = Array.isArray(node.anyOf) ? node.anyOf : Array.isArray(node.oneOf) ? node.oneOf : undefined
124
+ if (rawList === undefined || rawList.length === 0)
125
+ return { primary: node }
126
+
127
+ const branches = rawList
128
+ .filter(isRecord)
129
+ .map(b => resolveRef(b, root, new Set()))
130
+ .filter(b => !isNullSchema(b))
131
+
132
+ if (branches.length === 0)
133
+ return { primary: node }
134
+
135
+ // Literal unions like `anyOf: [{ const: 'a' }, { const: 'b' }]`
136
+ const literalVals: string[] = []
137
+ let allLiterals = true
138
+ for (const b of branches) {
139
+ const vals = collectEnumValues(b)
140
+ if (vals === undefined) {
141
+ allLiterals = false
142
+ break
143
+ }
144
+ literalVals.push(...vals)
145
+ }
146
+ if (allLiterals && literalVals.length > 0)
147
+ return { primary: node, unionEnums: literalVals }
148
+
149
+ let best = branches[0]!
150
+ let bestScore = branchSpecificity(best)
151
+ for (let i = 1; i < branches.length; i++) {
152
+ const score = branchSpecificity(branches[i]!)
153
+ if (score > bestScore) {
154
+ best = branches[i]!
155
+ bestScore = score
156
+ }
157
+ }
158
+ return { primary: best }
159
+ }
160
+
161
+ function mergeAllOf(node: Record<string, unknown>, root: Record<string, unknown>): Record<string, unknown> {
162
+ const resolved = resolveRef(node, root, new Set())
163
+ if (!Array.isArray(resolved.allOf))
164
+ return resolved
165
+ const merged: Record<string, unknown> = { ...resolved }
166
+ delete merged.allOf
167
+ const props: Record<string, unknown> = isRecord(merged.properties) ? { ...merged.properties } : {}
168
+ const req = new Set<string>(Array.isArray(merged.required) ? merged.required.filter((r): r is string => typeof r === 'string') : [])
169
+ for (const entry of resolved.allOf) {
170
+ if (!isRecord(entry))
171
+ continue
172
+ const sub = mergeAllOf(entry, root)
173
+ if (isRecord(sub.properties)) {
174
+ for (const [k, v] of Object.entries(sub.properties))
175
+ props[k] = v
176
+ }
177
+ if (Array.isArray(sub.required)) {
178
+ for (const r of sub.required) {
179
+ if (typeof r === 'string')
180
+ req.add(r)
181
+ }
182
+ }
183
+ for (const [k, v] of Object.entries(sub)) {
184
+ if (k !== 'properties' && k !== 'required' && merged[k] === undefined)
185
+ merged[k] = v
186
+ }
187
+ }
188
+ if (Object.keys(props).length > 0)
189
+ merged.properties = props
190
+ if (req.size > 0)
191
+ merged.required = [...req]
192
+ return merged
193
+ }
194
+
195
+ function applyNumericConstraints(node: Record<string, unknown>, isInteger: boolean, out: FieldConstraint): void {
196
+ out.type = 'number'
197
+ if (typeof node.multipleOf === 'number' && Number.isFinite(node.multipleOf) && node.multipleOf > 0)
198
+ out.step = node.multipleOf
199
+ else
200
+ out.step = isInteger ? 1 : 'any'
201
+ if (typeof node.minimum === 'number' && Number.isFinite(node.minimum) && node.minimum > SAFE_INT_MIN)
202
+ out.min = node.minimum
203
+ else if (typeof node.exclusiveMinimum === 'number' && Number.isFinite(node.exclusiveMinimum))
204
+ out.min = isInteger ? node.exclusiveMinimum + 1 : node.exclusiveMinimum
205
+ if (typeof node.maximum === 'number' && Number.isFinite(node.maximum) && node.maximum < SAFE_INT_MAX)
206
+ out.max = node.maximum
207
+ else if (typeof node.exclusiveMaximum === 'number' && Number.isFinite(node.exclusiveMaximum))
208
+ out.max = isInteger ? node.exclusiveMaximum - 1 : node.exclusiveMaximum
209
+ }
210
+
211
+ function extractLeafConstraint(rawNode: Record<string, unknown>, root: Record<string, unknown>, required: boolean): FieldConstraint {
212
+ const merged = mergeAllOf(rawNode, root)
213
+ const { primary, unionEnums } = unwrapUnion(merged, root)
214
+ const out: FieldConstraint = required ? { required: true } : {}
215
+
216
+ const type = Array.isArray(primary.type)
217
+ ? primary.type.find(t => t !== 'null')
218
+ : primary.type
219
+
220
+ if (type === 'array') {
221
+ out.isArray = true
222
+ if (isRecord(primary.items)) {
223
+ const itemConstraint = extractLeafConstraint(primary.items, root, false)
224
+ if (itemConstraint.type !== undefined)
225
+ out.type = itemConstraint.type
226
+ if (itemConstraint.minLength !== undefined)
227
+ out.minLength = itemConstraint.minLength
228
+ if (itemConstraint.maxLength !== undefined)
229
+ out.maxLength = itemConstraint.maxLength
230
+ if (itemConstraint.min !== undefined)
231
+ out.min = itemConstraint.min
232
+ if (itemConstraint.max !== undefined)
233
+ out.max = itemConstraint.max
234
+ if (itemConstraint.step !== undefined)
235
+ out.step = itemConstraint.step
236
+ if (itemConstraint.pattern !== undefined)
237
+ out.pattern = itemConstraint.pattern
238
+ if (itemConstraint.enumValues !== undefined)
239
+ out.enumValues = itemConstraint.enumValues
240
+ }
241
+ return out
242
+ }
243
+
244
+ const format = typeof primary.format === 'string' ? primary.format.toLowerCase() : undefined
245
+ if (format === 'email' || format === 'idn-email')
246
+ out.type = 'email'
247
+ else if (format === 'uri' || format === 'url' || format === 'iri')
248
+ out.type = 'url'
249
+ else if (type === 'integer' || type === 'number')
250
+ applyNumericConstraints(primary, type === 'integer', out)
251
+
252
+ if (typeof primary.minLength === 'number' && Number.isFinite(primary.minLength) && primary.minLength > 0)
253
+ out.minLength = Math.trunc(primary.minLength)
254
+ if (typeof primary.maxLength === 'number' && Number.isFinite(primary.maxLength) && primary.maxLength >= 0 && primary.maxLength < SAFE_INT_MAX)
255
+ out.maxLength = Math.trunc(primary.maxLength)
256
+ if (typeof primary.pattern === 'string' && primary.pattern.length > 0)
257
+ out.pattern = primary.pattern
258
+
259
+ const enums = unionEnums ?? collectEnumValues(primary)
260
+ if (enums !== undefined)
261
+ out.enumValues = enums
262
+
263
+ return out
264
+ }
265
+
266
+ function walkObjectSchema(
267
+ node: Record<string, unknown>,
268
+ root: Record<string, unknown>,
269
+ prefix: string,
270
+ parentRequired: boolean,
271
+ fields: Map<string, FieldConstraint>,
272
+ requiredSet: Set<string>,
273
+ depth = 0,
274
+ ): void {
275
+ if (depth > 8)
276
+ return
277
+ const merged = mergeAllOf(node, root)
278
+ const { primary } = unwrapUnion(merged, root)
279
+ if (!isRecord(primary.properties))
280
+ return
281
+
282
+ const ownRequired = new Set<string>(
283
+ Array.isArray(primary.required) ? primary.required.filter((r): r is string => typeof r === 'string') : [],
284
+ )
285
+
286
+ for (const [key, propSchema] of Object.entries(primary.properties)) {
287
+ const path = prefix !== '' ? `${prefix}.${key}` : key
288
+ const isReq = parentRequired && ownRequired.has(key)
289
+ if (!isRecord(propSchema)) {
290
+ fields.set(path, isReq ? { required: true } : {})
291
+ if (isReq)
292
+ requiredSet.add(path)
293
+ continue
294
+ }
295
+ const resolved = mergeAllOf(propSchema, root)
296
+ const { primary: propPrimary } = unwrapUnion(resolved, root)
297
+ if (isRecord(propPrimary.properties) && Object.keys(propPrimary.properties).length > 0) {
298
+ walkObjectSchema(propPrimary, root, path, isReq, fields, requiredSet, depth + 1)
299
+ continue
300
+ }
301
+ const constraint = extractLeafConstraint(propSchema, root, isReq)
302
+ fields.set(path, constraint)
303
+ if (isReq)
304
+ requiredSet.add(path)
305
+ }
306
+ }
307
+
308
+ /** Looks up a form field constraint by HTML `name`, normalizing `name[]` array notation. */
309
+ export function lookupFieldConstraint(
310
+ fields: ReadonlyMap<string, FieldConstraint>,
311
+ name: string,
312
+ ): FieldConstraint | undefined {
313
+ const direct = fields.get(name)
314
+ if (direct !== undefined)
315
+ return direct
316
+ if (name.endsWith('[]'))
317
+ return fields.get(name.slice(0, -2))
318
+ return undefined
319
+ }
320
+
321
+ /** Extracts HTML5 form constraints and required field names from a Standard Schema (cached per schema instance). */
322
+ export function extractFormSchema(schema: StandardSchemaV1): ExtractedFormSchema {
323
+ const cached = schemaCache.get(schema)
324
+ if (cached !== undefined)
325
+ return cached
326
+
327
+ const raw = readRawJsonSchema(schema)
328
+ if (raw === undefined) {
329
+ const rawVendor = (schema as unknown as JsonSchemaCapable)['~standard']?.vendor
330
+ const vendor = typeof rawVendor === 'string' && rawVendor.trim() !== '' ? rawVendor : 'unknown'
331
+ const result: ExtractedFormSchema = { ok: false, vendor }
332
+ schemaCache.set(schema, result)
333
+ return result
334
+ }
335
+
336
+ const fields = new Map<string, FieldConstraint>()
337
+ const required = new Set<string>()
338
+ walkObjectSchema(raw, raw, '', true, fields, required)
339
+
340
+ const result: ExtractedFormSchema = { ok: true, fields, required, jsonSchema: raw }
341
+ schemaCache.set(schema, result)
342
+ return result
343
+ }
@@ -0,0 +1,244 @@
1
+ // Server observability helpers: `/_pru/health` probes, fast request IDs (`x-request-id`), and dev-only `Server-Timing`.
2
+
3
+ import type { Middleware, RequestContext } from './http'
4
+ import type { TrustProxy } from './security'
5
+
6
+ export type HealthCheckResult = boolean | void | { ok: boolean, message?: string | undefined }
7
+ export type HealthCheckFn = () => HealthCheckResult | Promise<HealthCheckResult>
8
+ export type HealthCheckConfig = HealthCheckFn | Record<string, HealthCheckFn>
9
+
10
+ export interface HealthCheckEntry {
11
+ name: string
12
+ fn: HealthCheckFn
13
+ }
14
+
15
+ export interface HealthCheckOutcome {
16
+ ok: boolean
17
+ message?: string | undefined
18
+ error?: string | undefined
19
+ }
20
+
21
+ export interface DevTiming {
22
+ middleware?: number | undefined
23
+ load?: number | undefined
24
+ render?: number | undefined
25
+ stream?: number | undefined
26
+ }
27
+
28
+ export type RequestIdResolver = (request: Request) => string
29
+
30
+ const MAX_REQUEST_ID_LEN = 128
31
+
32
+ function randomBootPrefix(): string {
33
+ const bytes = new Uint8Array(4)
34
+ crypto.getRandomValues(bytes)
35
+ let hex = ''
36
+ for (let i = 0; i < 4; i++)
37
+ hex += bytes[i]!.toString(16).padStart(2, '0')
38
+ return hex
39
+ }
40
+
41
+ /** Validates an incoming proxy `x-request-id`: non-empty, <= 128 chars, restricted to `[A-Za-z0-9._:/-]`. */
42
+ export function isSafeRequestId(id: string): boolean {
43
+ const len = id.length
44
+ if (len === 0 || len > MAX_REQUEST_ID_LEN)
45
+ return false
46
+ for (let i = 0; i < len; i++) {
47
+ const c = id.charCodeAt(i)
48
+ const ok = (c >= 48 && c <= 57)
49
+ || (c >= 65 && c <= 90)
50
+ || (c >= 97 && c <= 122)
51
+ || c === 45 || c === 46 || c === 47 || c === 58 || c === 95
52
+ if (!ok)
53
+ return false
54
+ }
55
+ return true
56
+ }
57
+
58
+ const trustsProxyHeader = (trustProxy: TrustProxy): boolean =>
59
+ trustProxy === true || (typeof trustProxy === 'number' && trustProxy > 0)
60
+
61
+ /** Fast per-server request ID resolver: 8-char random boot prefix + base36 counter (zero `randomUUID` / regex per request). */
62
+ export function createRequestIdResolver(trustProxy: TrustProxy): RequestIdResolver {
63
+ const bootId = randomBootPrefix()
64
+ let seq = 0
65
+ if (!trustsProxyHeader(trustProxy))
66
+ return () => `${bootId}-${(++seq).toString(36)}`
67
+ return (request: Request): string => {
68
+ const incoming = request.headers.get('x-request-id')
69
+ if (incoming !== null && isSafeRequestId(incoming))
70
+ return incoming
71
+ return `${bootId}-${(++seq).toString(36)}`
72
+ }
73
+ }
74
+
75
+ const fallbackBootId = randomBootPrefix()
76
+ let fallbackSeq = 0
77
+
78
+ /** Fallback request ID for direct `makeRequestContext()` calls outside a running server. */
79
+ export function resolveFallbackRequestId(request: Request, trustProxy: TrustProxy): string {
80
+ if (trustsProxyHeader(trustProxy)) {
81
+ const incoming = request.headers.get('x-request-id')
82
+ if (incoming !== null && isSafeRequestId(incoming))
83
+ return incoming
84
+ }
85
+ return `${fallbackBootId}-${(++fallbackSeq).toString(36)}`
86
+ }
87
+
88
+ /** Attaches `x-request-id` in place when mutable, rebuilding only for immutable responses. */
89
+ export function withRequestId(res: Response, requestId: string): Response {
90
+ if (res.headers.has('x-request-id'))
91
+ return res
92
+ try {
93
+ res.headers.set('x-request-id', requestId)
94
+ return res
95
+ }
96
+ catch {
97
+ const headers = new Headers(res.headers)
98
+ headers.set('x-request-id', requestId)
99
+ return new Response(res.body, { status: res.status, statusText: res.statusText, headers })
100
+ }
101
+ }
102
+
103
+ export const createTiming = (isDev: boolean): DevTiming | undefined => (isDev ? {} : undefined)
104
+
105
+ export const startTimer = (timing: DevTiming | undefined): number => (timing !== undefined ? performance.now() : 0)
106
+
107
+ export function endTimer(timing: DevTiming | undefined, phase: keyof DevTiming, start: number): void {
108
+ if (timing !== undefined)
109
+ timing[phase] = performance.now() - start
110
+ }
111
+
112
+ /** Completes an in-progress `timing.render` start timestamp and formats the `Server-Timing` header value. */
113
+ export function finishRenderTiming(timing: DevTiming): string | undefined {
114
+ if (timing.render !== undefined)
115
+ timing.render = performance.now() - timing.render
116
+ return formatServerTiming(timing)
117
+ }
118
+
119
+ /** Formats dev-only `Server-Timing` phases (returns `undefined` in production or when no phases ran). */
120
+ export function formatServerTiming(timing: DevTiming | undefined): string | undefined {
121
+ if (timing === undefined)
122
+ return undefined
123
+ const parts: string[] = []
124
+ if (timing.middleware !== undefined)
125
+ parts.push(`middleware;dur=${timing.middleware.toFixed(2)}`)
126
+ if (timing.load !== undefined)
127
+ parts.push(`load;dur=${timing.load.toFixed(2)}`)
128
+ if (timing.render !== undefined)
129
+ parts.push(`render;dur=${timing.render.toFixed(2)}`)
130
+ if (timing.stream !== undefined)
131
+ parts.push(`stream;dur=${timing.stream.toFixed(2)}`)
132
+ return parts.length > 0 ? parts.join(', ') : undefined
133
+ }
134
+
135
+ /** Runs a middleware chain, measuring only middleware time (excluding `last()`) when dev timing is active. */
136
+ export async function runTimedChain(
137
+ ctx: RequestContext,
138
+ middlewares: readonly Middleware[],
139
+ last: () => Response | Promise<Response>,
140
+ timing: DevTiming | undefined,
141
+ runChain: (ctx: RequestContext, middlewares: readonly Middleware[], last: () => Response | Promise<Response>) => Promise<Response>,
142
+ ): Promise<Response> {
143
+ if (timing === undefined || middlewares.length === 0)
144
+ return runChain(ctx, middlewares, last)
145
+ let innerMs = 0
146
+ const chainStart = performance.now()
147
+ const res = await runChain(ctx, middlewares, async () => {
148
+ const innerStart = performance.now()
149
+ try {
150
+ return await last()
151
+ }
152
+ finally {
153
+ innerMs += performance.now() - innerStart
154
+ }
155
+ })
156
+ timing.middleware = Math.max(0, performance.now() - chainStart - innerMs)
157
+ return res
158
+ }
159
+
160
+ /** Merges app-configured and plugin-registered health checks into a flat ordered list. */
161
+ export function collectHealthChecks(
162
+ appCheck: HealthCheckConfig | undefined,
163
+ pluginChecks: readonly HealthCheckEntry[],
164
+ ): HealthCheckEntry[] {
165
+ const entries: HealthCheckEntry[] = []
166
+ if (typeof appCheck === 'function') {
167
+ entries.push({ name: 'app', fn: appCheck })
168
+ }
169
+ else if (typeof appCheck === 'object' && appCheck !== null) {
170
+ for (const [name, fn] of Object.entries(appCheck)) {
171
+ if (typeof fn === 'function')
172
+ entries.push({ name, fn })
173
+ }
174
+ }
175
+ for (const entry of pluginChecks)
176
+ entries.push(entry)
177
+ return entries
178
+ }
179
+
180
+ async function runSingleHealthCheck(entry: HealthCheckEntry): Promise<[string, HealthCheckOutcome]> {
181
+ try {
182
+ const result = await entry.fn()
183
+ if (result === true || result === undefined)
184
+ return [entry.name, { ok: true }]
185
+ if (result === false)
186
+ return [entry.name, { ok: false }]
187
+ if (result.ok)
188
+ return [entry.name, result.message !== undefined ? { ok: true, message: result.message } : { ok: true }]
189
+ return [entry.name, result.message !== undefined ? { ok: false, error: result.message } : { ok: false }]
190
+ }
191
+ catch (err) {
192
+ return [entry.name, { ok: false, error: err instanceof Error ? err.message : String(err) }]
193
+ }
194
+ }
195
+
196
+ export interface HealthHandlerOptions {
197
+ checks: readonly HealthCheckEntry[]
198
+ securityRecord: Record<string, string>
199
+ withHsts: (res: Response, request: Request) => Response
200
+ resolveRequestId: RequestIdResolver
201
+ }
202
+
203
+ /** Handles `GET`/`HEAD` requests to `${assetPrefix}/health`, returning 200 when healthy and 503 if any check fails. */
204
+ export function createHealthHandler(options: HealthHandlerOptions): (request: Request, requestId?: string) => Response | Promise<Response> {
205
+ const { checks, securityRecord, withHsts, resolveRequestId } = options
206
+ const baseHeaders: Record<string, string> = {
207
+ 'content-type': 'application/json; charset=utf-8',
208
+ 'cache-control': 'no-store',
209
+ ...securityRecord,
210
+ }
211
+ const okPayload = '{"ok":true}'
212
+ const okLength = String(okPayload.length)
213
+
214
+ const jsonReply = (request: Request, status: number, payload: string, length: string, reqId: string): Response => {
215
+ const body = request.method === 'HEAD' ? null : payload
216
+ const res = new Response(body, { status, headers: { ...baseHeaders, 'content-length': length, 'x-request-id': reqId } })
217
+ return withHsts(res, request)
218
+ }
219
+
220
+ return (request: Request, requestId?: string): Response | Promise<Response> => {
221
+ const reqId = requestId ?? resolveRequestId(request)
222
+ if (request.method !== 'GET' && request.method !== 'HEAD') {
223
+ const res = new Response('Method Not Allowed', {
224
+ status: 405,
225
+ headers: { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store', 'allow': 'GET, HEAD', ...securityRecord, 'x-request-id': reqId },
226
+ })
227
+ return withHsts(res, request)
228
+ }
229
+ if (checks.length === 0)
230
+ return jsonReply(request, 200, okPayload, okLength, reqId)
231
+
232
+ return Promise.all(checks.map(runSingleHealthCheck)).then((results) => {
233
+ const checkMap: Record<string, HealthCheckOutcome> = {}
234
+ let allOk = true
235
+ for (const [name, outcome] of results) {
236
+ checkMap[name] = outcome
237
+ if (!outcome.ok)
238
+ allOk = false
239
+ }
240
+ const payload = JSON.stringify({ ok: allOk, checks: checkMap })
241
+ return jsonReply(request, allOk ? 200 : 503, payload, String(Buffer.byteLength(payload, 'utf8')), reqId)
242
+ })
243
+ }
244
+ }