prunelle 0.7.7 → 0.9.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 (189) hide show
  1. package/llms.txt +63 -46
  2. package/package.json +7 -2
  3. package/src/a11y/declaration.ts +6 -10
  4. package/src/a11y/index.ts +69 -125
  5. package/src/animate.ts +127 -0
  6. package/src/build/asides.ts +51 -0
  7. package/src/build/bundle.ts +88 -134
  8. package/src/build/client-entries.ts +6 -6
  9. package/src/build/client-outputs.ts +75 -0
  10. package/src/build/client-plugin.ts +9 -4
  11. package/src/build/ecoindex.ts +4 -2
  12. package/src/build/files.ts +18 -0
  13. package/src/build/graph.ts +15 -7
  14. package/src/build/index.ts +20 -10
  15. package/src/build/island-promote.ts +1 -1
  16. package/src/build/islands.ts +4 -1
  17. package/src/build/key-types.ts +31 -0
  18. package/src/build/manifest.ts +19 -1
  19. package/src/build/plugin-host.ts +2 -0
  20. package/src/build/prerender.ts +2 -2
  21. package/src/build/reach.ts +14 -1
  22. package/src/build/report.ts +1 -1
  23. package/src/build/route-types.ts +16 -0
  24. package/src/build/routes.ts +24 -15
  25. package/src/build/seed-ids.ts +65 -0
  26. package/src/build/seed-writes.ts +111 -0
  27. package/src/build/static-headers.ts +2 -2
  28. package/src/build/static.ts +1 -1
  29. package/src/cli/check-cache.ts +51 -0
  30. package/src/cli/check-consent.ts +95 -0
  31. package/src/cli/check-forms.ts +2 -2
  32. package/src/cli/check-links-patterns.ts +101 -0
  33. package/src/cli/check-links.ts +16 -100
  34. package/src/cli/check-regions.ts +185 -0
  35. package/src/cli/check-security.ts +57 -6
  36. package/src/cli/check.ts +40 -17
  37. package/src/cli/commands.ts +134 -14
  38. package/src/cli/docs.ts +21 -2
  39. package/src/cli/index.ts +1 -1
  40. package/src/cli/inspect.ts +2 -0
  41. package/src/cli/mcp-tools.ts +2 -2
  42. package/src/cli/new.ts +9 -5
  43. package/src/cli/upgrade-names.ts +14 -2
  44. package/src/cli/upgrade.ts +3 -0
  45. package/src/compiler/analyze.ts +18 -4
  46. package/src/compiler/cacheability.ts +24 -2
  47. package/src/compiler/compliance-contrast.ts +284 -0
  48. package/src/compiler/compliance-empty.ts +24 -0
  49. package/src/compiler/compliance-rgaa-content.ts +95 -0
  50. package/src/compiler/compliance-rgaa-criteria.ts +45 -0
  51. package/src/compiler/compliance-rgaa-pages.ts +140 -0
  52. package/src/compiler/compliance-rgaa.ts +19 -0
  53. package/src/compiler/compliance-third-party.ts +59 -0
  54. package/src/compiler/compliance-urls.ts +52 -0
  55. package/src/compiler/compliance.ts +72 -42
  56. package/src/compiler/cookie-inventory.ts +119 -0
  57. package/src/compiler/dom-attrs.ts +4 -1
  58. package/src/compiler/emit.ts +1 -1
  59. package/src/compiler/foreign-imports.ts +5 -3
  60. package/src/compiler/mistakes.ts +18 -9
  61. package/src/compiler/props-pattern.ts +211 -0
  62. package/src/compiler/props.ts +177 -346
  63. package/src/compiler/shared.ts +9 -16
  64. package/src/compiler/ssr-emit.ts +510 -0
  65. package/src/compiler/ssr-helpers.ts +170 -121
  66. package/src/compiler/ssr.ts +25 -440
  67. package/src/context.ts +14 -1
  68. package/src/dev/child.ts +1 -1
  69. package/src/dev/hot-islands.ts +71 -0
  70. package/src/dev/index.ts +31 -18
  71. package/src/dev/protocol.ts +1 -1
  72. package/src/dev/queue.ts +3 -2
  73. package/src/dev/reload.ts +1 -1
  74. package/src/dev/supervisor.ts +3 -1
  75. package/src/dev/watchers.ts +6 -2
  76. package/src/dom/action.ts +97 -14
  77. package/src/dom/attrs.ts +8 -0
  78. package/src/dom/extras.ts +2 -1
  79. package/src/dom/field-marks.ts +24 -0
  80. package/src/dom/hot.ts +9 -0
  81. package/src/dom/index.ts +25 -5
  82. package/src/dom/island-hot.ts +29 -0
  83. package/src/dom/island.ts +13 -2
  84. package/src/dom/prefetch.ts +132 -0
  85. package/src/dom/regions.ts +498 -0
  86. package/src/dom/swap.ts +245 -0
  87. package/src/dom/trusted.ts +22 -0
  88. package/src/dom/upload.ts +44 -0
  89. package/src/eco/declaration.ts +39 -40
  90. package/src/eco/index.ts +5 -5
  91. package/src/href.ts +31 -0
  92. package/src/index.ts +9 -3
  93. package/src/plugins/config.ts +1 -1
  94. package/src/plugins/context.ts +7 -1
  95. package/src/plugins/daily.ts +27 -0
  96. package/src/plugins/index.ts +3 -3
  97. package/src/plugins/order.ts +1 -1
  98. package/src/plugins/public.ts +8 -5
  99. package/src/plugins/services.ts +88 -14
  100. package/src/plugins/types.ts +121 -10
  101. package/src/reactivity/hmr.ts +90 -0
  102. package/src/reactivity/index.ts +38 -18
  103. package/src/reactivity/resource.ts +115 -0
  104. package/src/reactivity/seed.ts +39 -0
  105. package/src/reactivity/server-seed.ts +194 -0
  106. package/src/reactivity/store.ts +55 -1
  107. package/src/rgpd/draft.ts +171 -0
  108. package/src/rgpd/forms.ts +85 -0
  109. package/src/rgpd/index.ts +57 -0
  110. package/src/server/action-flash.ts +1 -0
  111. package/src/server/action-registry.ts +6 -8
  112. package/src/server/action.ts +51 -19
  113. package/src/server/app-secret.ts +22 -17
  114. package/src/server/cache-invalidation.ts +96 -0
  115. package/src/server/compress.ts +3 -1
  116. package/src/server/consent.ts +16 -2
  117. package/src/server/cookie-inventory.ts +78 -0
  118. package/src/server/cookies.ts +50 -0
  119. package/src/server/csp-report.ts +86 -0
  120. package/src/server/discard.ts +13 -0
  121. package/src/server/document.ts +7 -4
  122. package/src/server/env.ts +1 -1
  123. package/src/server/errors.ts +9 -2
  124. package/src/server/field-errors.ts +91 -0
  125. package/src/server/form-schema.ts +16 -11
  126. package/src/server/health.ts +35 -14
  127. package/src/server/http.ts +25 -10
  128. package/src/server/index.ts +102 -299
  129. package/src/server/loader.ts +1 -0
  130. package/src/server/page.ts +11 -24
  131. package/src/server/plugin-host.ts +26 -8
  132. package/src/server/public.ts +14 -3
  133. package/src/server/rate-limit.ts +39 -10
  134. package/src/server/region.ts +3 -0
  135. package/src/server/request-handler.ts +370 -0
  136. package/src/server/request-log.ts +94 -0
  137. package/src/server/route-cache.ts +41 -6
  138. package/src/server/route-input.ts +54 -0
  139. package/src/server/route-table.ts +35 -19
  140. package/src/server/routing.ts +12 -11
  141. package/src/server/sanitize-html.ts +1 -1
  142. package/src/server/security.ts +81 -20
  143. package/src/server/serve-handlers.ts +9 -5
  144. package/src/server/shared-store.ts +314 -0
  145. package/src/server/start.ts +12 -5
  146. package/src/server/static-dir.ts +14 -10
  147. package/src/server/stream.ts +2 -1
  148. package/src/server/surface.ts +39 -0
  149. package/src/server/webhook.ts +48 -0
  150. package/src/server/workers.ts +168 -0
  151. package/src/ssr/consent-banner.ts +20 -16
  152. package/src/ssr/consent-texts.ts +40 -0
  153. package/src/ssr/context.ts +26 -3
  154. package/src/ssr/cookie-table.ts +75 -0
  155. package/src/ssr/index.ts +23 -13
  156. package/src/ssr/navigation.ts +161 -14
  157. package/src/test/browser.ts +50 -22
  158. package/src/test/build-reuse.ts +70 -0
  159. package/src/test/index.ts +45 -6
  160. package/src/test/mount.ts +53 -0
  161. package/src/test/outside.ts +94 -0
  162. package/templates/_shared/AGENTS.md +1 -1
  163. package/templates/_shared/Dockerfile +22 -0
  164. package/templates/_shared/dockerignore +9 -0
  165. package/templates/_shared/gitignore +2 -0
  166. package/templates/app/.env.example +3 -1
  167. package/templates/app/compose.yaml +32 -0
  168. package/templates/app/db/migrations/001_notes.sql +7 -0
  169. package/templates/app/db/schema.ts +11 -0
  170. package/templates/app/package.json +1 -0
  171. package/templates/app/prunelle.config.ts +6 -0
  172. package/templates/app/src/actions/notes.ts +26 -0
  173. package/templates/app/src/auth.ts +4 -2
  174. package/templates/app/src/db.ts +5 -0
  175. package/templates/app/src/routes/dashboard/index.tsx +26 -1
  176. package/templates/app/src/routes/privacy.tsx +6 -2
  177. package/templates/app/tests/app.test.ts +14 -3
  178. package/templates/plugin/AGENTS.md +11 -0
  179. package/templates/plugin/CLAUDE.md +1 -0
  180. package/templates/plugin/README.md +27 -0
  181. package/templates/plugin/gitignore +2 -0
  182. package/templates/plugin/llms.txt +19 -0
  183. package/templates/plugin/package.json +33 -0
  184. package/templates/plugin/src/index.ts +40 -0
  185. package/templates/plugin/tests/fixture/prunelle.config.ts +4 -0
  186. package/templates/plugin/tests/fixture/src/routes/index.tsx +11 -0
  187. package/templates/plugin/tests/plugin.test.ts +42 -0
  188. package/templates/plugin/tsconfig.json +19 -0
  189. package/ts-plugin.cjs +3674 -2196
@@ -1,6 +1,8 @@
1
1
  // Typed cookie jar for RequestContext (lazy Cookie header parsing, validated & deduplicated Set-Cookie serialization).
2
2
 
3
3
  import { getAppContext } from '../plugins/context'
4
+ import { serviceKey } from '../plugins/services'
5
+ import { COOKIE_INVENTORY } from './cookie-inventory'
4
6
 
5
7
  export interface CookieOptions {
6
8
  path?: string | undefined
@@ -12,6 +14,8 @@ export interface CookieOptions {
12
14
  sameSite?: 'strict' | 'lax' | 'none' | undefined
13
15
  /** Consent category required before setting this cookie, or `'essential'` for a cookie the site cannot work without; omitted, it counts as essential and `prunelle dev` warns. */
14
16
  category?: string | undefined
17
+ /** What the cookie is for, as `<CookieTable>` lists it: read from the source by `prunelle build`, so write it as a literal; ignored when setting the cookie. */
18
+ purpose?: string | undefined
15
19
  }
16
20
 
17
21
  const warnedUncategorized = new Set<string>()
@@ -24,6 +28,51 @@ function warnUncategorized(name: string): void {
24
28
  console.warn(`prunelle: cookie "${name}" was set without a category, so it counts as essential and is set without consent: pass { category: 'essential' } when the site cannot work without it, or its consent category (such as 'analytics') so it waits for the visitor's consent.`)
25
29
  }
26
30
 
31
+ // The cookies this server instance set under each consent category, kept on AppRuntimeContext so servers stay isolated,
32
+ // paired with COOKIE_INVENTORY so consent withdrawal also expires declared cookies across restarts and worker processes.
33
+ const MAX_REMEMBERED_PER_CATEGORY = 200
34
+ type CategoryCookieMap = Map<string, Map<string, Pick<CookieOptions, 'path' | 'domain'>>>
35
+ const SET_COOKIES_BY_CATEGORY = serviceKey<CategoryCookieMap>('prunelle.cookies.byCategory')
36
+
37
+ function rememberUnderCategory(category: string, name: string, options: CookieOptions): void {
38
+ const appCtx = getAppContext()
39
+ if (appCtx === undefined)
40
+ return
41
+ let byCategory = appCtx.inject(SET_COOKIES_BY_CATEGORY)
42
+ if (byCategory === undefined) {
43
+ byCategory = new Map()
44
+ appCtx.provide(SET_COOKIES_BY_CATEGORY, byCategory)
45
+ }
46
+ let names = byCategory.get(category)
47
+ if (names === undefined) {
48
+ names = new Map()
49
+ byCategory.set(category, names)
50
+ }
51
+ if (names.size < MAX_REMEMBERED_PER_CATEGORY || names.has(name))
52
+ names.set(name, { path: options.path, domain: options.domain })
53
+ }
54
+
55
+ /** Expires, on the visitor's browser, each cookie of these refused categories that the request still carries. */
56
+ export function expireCookiesOf(jar: Cookies, categories: Iterable<string>): void {
57
+ const appCtx = getAppContext()
58
+ const byCategory = appCtx?.inject(SET_COOKIES_BY_CATEGORY)
59
+ const inventory = appCtx?.inject(COOKIE_INVENTORY)
60
+ for (const category of categories) {
61
+ const expired = new Set<string>()
62
+ for (const [name, scope] of byCategory?.get(category) ?? []) {
63
+ expired.add(name)
64
+ if (jar.get(name) !== undefined)
65
+ jar.delete(name, scope)
66
+ }
67
+ for (const row of inventory?.rows ?? []) {
68
+ if (row.category === category && row.name !== undefined && !expired.has(row.name) && jar.get(row.name) !== undefined) {
69
+ expired.add(row.name)
70
+ jar.delete(row.name)
71
+ }
72
+ }
73
+ }
74
+ }
75
+
27
76
  export interface Cookies {
28
77
  get(name: string): string | undefined
29
78
  set(name: string, value: string, options?: CookieOptions): void
@@ -134,6 +183,7 @@ export class CookieStore implements Cookies {
134
183
  else if (options.category !== 'essential') {
135
184
  if (this.#isConsentGranted === undefined || !this.#isConsentGranted(options.category))
136
185
  return
186
+ rememberUnderCategory(options.category, name, options)
137
187
  }
138
188
  const serialized = serializeCookie(name, value, options, this.#isHttps)
139
189
  this.#ensureValues().set(name, value)
@@ -0,0 +1,86 @@
1
+ // The endpoint `security.cspReports` adds: each CSP violation report a browser sends reaches `onError` as a `csp` error.
2
+
3
+ import type { PluginRouteOptions } from '../plugins/types'
4
+ import type { NotifyError } from './errors'
5
+ import type { RequestContext } from './http'
6
+ import { enforceRequestBodyLimit } from './http'
7
+ import { CSP_REPORT_PATH } from './security'
8
+
9
+ /** One violation, read from either format a browser sends. */
10
+ export interface CspViolation {
11
+ directive: string
12
+ blockedUrl: string
13
+ page: string
14
+ sourceFile?: string
15
+ line?: number
16
+ }
17
+
18
+ type Register = (method: string, path: string, handler: (ctx: RequestContext) => Response | Promise<Response>, options?: PluginRouteOptions) => void
19
+
20
+ // A report holds one violation of a few hundred bytes; a `report-to` batch holds a handful.
21
+ const MAX_REPORT_BYTES = 16 * 1024
22
+ const REPORT_RATE_LIMIT = { max: 30, windowMs: 60_000 }
23
+ // An extension's own scripts and images trip the page's CSP on every visit, and nothing the app changes stops them.
24
+ const EXTENSION_URL_RE = /^(?:chrome|moz|safari(?:-web)?|ms-browser)-extension:/
25
+
26
+ const MAX_LOGGED_CHARS = 200
27
+
28
+ /** A report field fit for a log line: control characters become spaces, so a newline cannot forge a line, and a long value is cut. */
29
+ const loggable = (value: string): string => {
30
+ const flat = value.replace(/[\x00-\x1F\x7F]/g, ' ')
31
+ return flat.length > MAX_LOGGED_CHARS ? `${flat.slice(0, MAX_LOGGED_CHARS)}...` : flat
32
+ }
33
+
34
+ const text = (value: unknown): string | undefined => typeof value === 'string' && value !== '' ? value : undefined
35
+
36
+ function violation(directive: unknown, blockedUrl: unknown, page: unknown, sourceFile: unknown, line: unknown): CspViolation | undefined {
37
+ const fields = { directive: text(directive), blockedUrl: text(blockedUrl), page: text(page) }
38
+ if (fields.directive === undefined || fields.page === undefined)
39
+ return undefined
40
+ const found: CspViolation = { directive: fields.directive, blockedUrl: fields.blockedUrl ?? 'inline', page: fields.page }
41
+ const file = text(sourceFile)
42
+ if (file !== undefined)
43
+ found.sourceFile = file
44
+ if (typeof line === 'number' && line > 0)
45
+ found.line = line
46
+ return found
47
+ }
48
+
49
+ type Fields = Record<string, unknown>
50
+ const isObject = (value: unknown): value is Fields => typeof value === 'object' && value !== null
51
+
52
+ /** The violations in a report body: `report-uri`'s `{ "csp-report": {...} }` or `report-to`'s array, whose other report types are skipped. Undefined when the body is neither. */
53
+ export function parseCspReports(body: unknown): CspViolation[] | undefined {
54
+ if (Array.isArray(body)) {
55
+ return body.flatMap((report) => {
56
+ if (!isObject(report) || report.type !== 'csp-violation' || !isObject(report.body))
57
+ return []
58
+ const b = report.body
59
+ return violation(b.effectiveDirective, b.blockedURL, b.documentURL, b.sourceFile, b.lineNumber) ?? []
60
+ })
61
+ }
62
+ if (!isObject(body) || !isObject(body['csp-report']))
63
+ return undefined
64
+ const r = body['csp-report']
65
+ const found = violation(r['effective-directive'], r['blocked-uri'], r['document-uri'], r['source-file'], r['line-number'])
66
+ return found === undefined ? [] : [found]
67
+ }
68
+
69
+ const fromExtension = (v: CspViolation): boolean => EXTENSION_URL_RE.test(v.blockedUrl) || EXTENSION_URL_RE.test(v.sourceFile ?? '')
70
+
71
+ export function registerCspReportRoute(register: Register, notifyError: NotifyError): void {
72
+ // A report changes nothing on the server, so it skips the cross-site check, which a page with an opaque origin (a sandboxed frame) would fail with `Origin: null`.
73
+ register('POST', CSP_REPORT_PATH, async (ctx) => {
74
+ const limited = await enforceRequestBodyLimit(ctx.request, MAX_REPORT_BYTES)
75
+ if (!limited.ok)
76
+ return new Response(null, { status: limited.aborted === true ? 400 : 413 })
77
+ const violations = parseCspReports(await limited.request.json().catch(() => undefined))
78
+ if (violations === undefined)
79
+ return new Response(null, { status: 400 })
80
+ for (const v of violations) {
81
+ if (!fromExtension(v))
82
+ notifyError(new Error(`CSP violation: ${v.directive} blocked ${loggable(v.blockedUrl)} on ${loggable(v.page)}`, { cause: v }), ctx.request, 'csp', ctx.requestId)
83
+ }
84
+ return new Response(null, { status: 204 })
85
+ }, { csrf: false, rateLimit: REPORT_RATE_LIMIT })
86
+ }
@@ -0,0 +1,13 @@
1
+ // A promise or stream whose failure nobody can act on: a body cancelled after the answer is known, a read already raced out. Named here so the intent stays in code, not in an empty handler.
2
+
3
+ function ignoreRejection(): void {}
4
+
5
+ /** Marks a promise whose rejection nobody awaits as handled, so it never surfaces as an unhandled rejection. */
6
+ export function markHandled(promise: Promise<unknown>): void {
7
+ promise.then(undefined, ignoreRejection)
8
+ }
9
+
10
+ /** Cancels a body or reader and waits for it, whatever the outcome: the stream is already past use. */
11
+ export function cancelQuietly(source: { cancel: () => Promise<void> } | null): Promise<void> {
12
+ return (source?.cancel() ?? Promise.resolve()).then(undefined, ignoreRejection)
13
+ }
@@ -30,8 +30,8 @@ export type HtmlHeaders = (hasIslands: boolean, hasSuspense: boolean, isDynamic:
30
30
  const STYLED_HEADER_CACHE_SIZE = 256
31
31
 
32
32
  // HTML headers, one set per (dynamic, islands, suspense) combination: the CSP only gains the hashes a page needs.
33
- export function createHtmlHeaders(security: SecurityHeadersOptions | false | undefined, securityRecord: Record<string, string>, navigation?: Navigation, plugins: readonly PrunellePlugin[] = []): HtmlHeaders {
34
- const baseCsp = resolveCspPolicy(security)
33
+ export function createHtmlHeaders(security: SecurityHeadersOptions | false | undefined, securityRecord: Record<string, string>, navigation?: Navigation, plugins: readonly PrunellePlugin[] = [], overHttps = false): HtmlHeaders {
34
+ const baseCsp = resolveCspPolicy(security, overHttps)
35
35
  const navStyles = navigation?.styleHashes ?? []
36
36
  const navScripts = [...navigation?.scriptHashes ?? [], ...plugins.flatMap(plugin => plugin.inlineScripts ?? []).map(cspSha256)]
37
37
  const htmlHeaderSets: Record<string, string>[] = []
@@ -126,7 +126,9 @@ function withBaseCsp(res: Response, htmlHeaders: HtmlHeaders): Response {
126
126
  return new Response(res.body, { status: res.status, statusText: res.statusText, headers })
127
127
  }
128
128
 
129
- /** A plugin's HTML page without a CSP of its own gets the app's, its `<style>` blocks hashed like a rendered page's. */
129
+ const HEAD_END_RE = /<\/head\s*>|<body[\s>]/i
130
+
131
+ /** A plugin's HTML page without a CSP of its own gets the app's, with the `<style>` blocks of its `<head>` hashed: one in the body may be content the page echoes, so it stays blocked. */
130
132
  export async function withPluginHtmlCsp(res: Response, htmlHeaders: HtmlHeaders): Promise<Response> {
131
133
  if (res.body === null || res.headers.has('content-security-policy') || !(res.headers.get('content-type') ?? '').trim().toLowerCase().startsWith('text/html'))
132
134
  return res
@@ -138,7 +140,8 @@ export async function withPluginHtmlCsp(res: Response, htmlHeaders: HtmlHeaders)
138
140
  return withBaseCsp(probed.passthrough, htmlHeaders)
139
141
  const html = new TextDecoder().decode(probed.buffered)
140
142
  const headers = new Headers(res.headers)
141
- const csp = htmlHeaders(false, false, true, inlineStyleHashes(html))['content-security-policy']
143
+ const headEnd = HEAD_END_RE.exec(html)?.index ?? 0
144
+ const csp = htmlHeaders(false, false, true, inlineStyleHashes(html.slice(0, headEnd)))['content-security-policy']
142
145
  if (csp !== undefined)
143
146
  headers.set('content-security-policy', csp)
144
147
  return new Response(html, { status: res.status, statusText: res.statusText, headers })
package/src/server/env.ts CHANGED
@@ -21,7 +21,7 @@ export function devFromEnv(): boolean {
21
21
  return false
22
22
  const where = BINARY_MAIN_RE.test(Bun.main) ? 'inside a compiled binary' : nodeEnv() === 'production' ? 'with NODE_ENV=production' : undefined
23
23
  if (where !== undefined)
24
- throw new Error(`prunelle: PRUNELLE_DEV=1 is set ${where}, where dev mode would open the CMS write routes, the mail outbox and the other dev-only routes to visitors: unset PRUNELLE_DEV, or use prunelle dev.`)
24
+ throw new Error(`prunelle: PRUNELLE_DEV=1 is set ${where}, where dev mode would open the mail outbox and the other dev-only routes to visitors: unset PRUNELLE_DEV, or use prunelle dev.`)
25
25
  return true
26
26
  }
27
27
 
@@ -10,8 +10,10 @@ import type { DeniedInfo, RequestContext } from './http'
10
10
  import type { ParamMatcherMap } from './param-matchers'
11
11
  import { createRenderContext, runWithRenderContext } from '../ssr/context'
12
12
  import { raw, renderDocument, ssrChild } from '../ssr/index'
13
+ import { cancelQuietly } from './discard'
13
14
  import { addedInlineStyleHashes, headTagStyleHashes, mergeStyleHashes, resolveRenderedIslands, revivePreload } from './document'
14
15
  import { wantsJson } from './http'
16
+ import { errorJsonLine } from './request-log'
15
17
  import { hasPublicFavicon } from './page'
16
18
  import { BUILTIN_PARAM_MATCHERS } from './param-matchers'
17
19
  import { decodeRequestPath, pathPrefix } from './request-path'
@@ -50,6 +52,8 @@ export interface ErrorNotifierOptions {
50
52
  dev?: boolean | undefined
51
53
  /** Hears every unhandled error, hooks or not: how `testApp().errors` fills. */
52
54
  sink?: ((info: ServerErrorInfo) => void) | undefined
55
+ /** `log.format`: `'json'` prints that error as one JSON line. */
56
+ format?: 'text' | 'json' | undefined
53
57
  }
54
58
 
55
59
  export function createErrorNotifier(onError: ((info: ServerErrorInfo) => void) | undefined, plugins: readonly PrunellePlugin[], options: ErrorNotifierOptions = {}): NotifyError {
@@ -62,13 +66,16 @@ export function createErrorNotifier(onError: ((info: ServerErrorInfo) => void) |
62
66
  }
63
67
  return (error, request, source, requestId) => {
64
68
  const normalized = error instanceof Response
65
- ? (void error.body?.cancel().catch(() => undefined), new Error(describeNonError(error)))
69
+ ? (void cancelQuietly(error.body), new Error(describeNonError(error)))
66
70
  : error
67
71
  const info: ServerErrorInfo = requestId !== undefined ? { error: normalized, request, source, requestId } : { error: normalized, request, source }
68
72
  options.sink?.(info)
69
73
  if (errorHooks.length === 0 && (options.dev === true || options.sink === undefined)) {
70
74
  const idSuffix = requestId !== undefined ? ` [${requestId}]` : ''
71
- console.error(`prunelle: unhandled error in ${source} ${request.method} ${new URL(request.url).pathname}${idSuffix}`, normalized)
75
+ if (options.format === 'json')
76
+ console.error(errorJsonLine(normalized, request, source, requestId))
77
+ else
78
+ console.error(`prunelle: unhandled error in ${source} ${request.method} ${new URL(request.url).pathname}${idSuffix}`, normalized)
72
79
  }
73
80
  for (const { owner, hook } of errorHooks) {
74
81
  try {
@@ -0,0 +1,91 @@
1
+ // A page re-rendered after a failed zero-JS submit: each field the error names gets `aria-invalid` and is described by the element of its form showing its message (RGAA 11.10, 11.11), as `useAction` does in an island.
2
+
3
+ import type { ActionErrorFlash } from './action'
4
+
5
+ const CONTROLS = new Set(['input', 'select', 'textarea'])
6
+
7
+ interface Seen { index: number, text: string }
8
+
9
+ // Numbers the elements inside the forms posting to `action`, in document order, so both passes name an element the same way.
10
+ function inForms(rewriter: HTMLRewriter, action: string, visit: (el: HTMLRewriterTypes.Element, at: number) => void): HTMLRewriter {
11
+ const path = (url: string): string => new URL(url, 'http://x').pathname
12
+ let index = -1
13
+ let inside = false
14
+ return rewriter.on('*', {
15
+ element(el) {
16
+ if (el.tagName === 'form') {
17
+ const target = el.getAttribute('action')
18
+ inside = target !== null && path(target) === path(action)
19
+ el.onEndTag(() => void (inside = false))
20
+ }
21
+ else if (inside) {
22
+ visit(el, ++index)
23
+ }
24
+ },
25
+ })
26
+ }
27
+
28
+ // The element showing a field's message: the first one after the field whose whole text is the message, else the last one before it, so fields sharing "Required" each get their own.
29
+ function messageOf(seen: readonly Seen[], field: number, text: string): number | undefined {
30
+ const matches = seen.filter(s => s.text === text).map(s => s.index)
31
+ return matches.find(i => i > field) ?? matches.findLast(i => i < field)
32
+ }
33
+
34
+ /** `html` with the fields of the failed form tied to their messages; unchanged when the flash names no field or the page has no form posting to its action. */
35
+ export async function markFlashedFields(html: string, flash: ActionErrorFlash | undefined): Promise<string> {
36
+ const errors = flash?.fieldErrors
37
+ if (flash === undefined || errors === undefined || Object.keys(errors).length === 0)
38
+ return html
39
+ // The page escaped each message as it rendered it, and the rewriter hands text over as written.
40
+ const escaped = new Map(Object.entries(errors).map(([name, message]) => [name, Bun.escapeHTML(message)]))
41
+
42
+ const fields = new Map<number, string>()
43
+ const ids = new Map<number, string | null>()
44
+ const seen: Seen[] = []
45
+ const open: Seen[] = []
46
+ await inForms(new HTMLRewriter(), flash.action, (el, at) => {
47
+ const name = el.getAttribute('name')
48
+ if (CONTROLS.has(el.tagName) && name !== null && escaped.has(name) && !el.hasAttribute('aria-invalid'))
49
+ fields.set(at, name)
50
+ ids.set(at, el.getAttribute('id'))
51
+ if (!el.canHaveContent)
52
+ return
53
+ const entry = { index: at, text: '' }
54
+ open.push(entry)
55
+ el.onEndTag(() => {
56
+ open.pop()
57
+ seen.push({ index: at, text: entry.text.trim() })
58
+ })
59
+ }).onDocument({ text(chunk) {
60
+ for (const entry of open)
61
+ entry.text += chunk.text
62
+ } }).transform(new Response(html)).text()
63
+ if (fields.size === 0)
64
+ return html
65
+
66
+ const describedBy = new Map<number, string>()
67
+ const newIds = new Map<number, string>()
68
+ for (const [at, name] of fields) {
69
+ const shown = messageOf(seen, at, escaped.get(name)!)
70
+ if (shown === undefined)
71
+ continue
72
+ const id = ids.get(shown) ?? newIds.get(shown) ?? `pru-err-${name}`
73
+ newIds.set(shown, id)
74
+ describedBy.set(at, id)
75
+ }
76
+
77
+ return inForms(new HTMLRewriter(), flash.action, (el, at) => {
78
+ const id = newIds.get(at)
79
+ if (id !== undefined)
80
+ el.setAttribute('id', id)
81
+ if (!fields.has(at))
82
+ return
83
+ // `data-pru-err` keeps what `aria-describedby` was, so `useAction` undoes these marks at the next submit.
84
+ const before = el.getAttribute('aria-describedby') ?? ''
85
+ el.setAttribute('data-pru-err', before)
86
+ el.setAttribute('aria-invalid', 'true')
87
+ const describe = describedBy.get(at)
88
+ if (describe !== undefined)
89
+ el.setAttribute('aria-describedby', `${before} ${describe}`.trim())
90
+ }).transform(new Response(html)).text()
91
+ }
@@ -25,6 +25,8 @@ export type ExtractedFormSchema =
25
25
  | {
26
26
  ok: false
27
27
  vendor: string
28
+ /** The message of the error the library threw converting the schema, when its converter failed (such as Zod 4 on `z.date()`). */
29
+ reason?: string | undefined
28
30
  }
29
31
 
30
32
  interface LegacyJsonSchemaCapable {
@@ -40,17 +42,20 @@ export function isRecord(value: unknown): value is Record<string, unknown> {
40
42
  return value !== null && typeof value === 'object' && !Array.isArray(value)
41
43
  }
42
44
 
43
- function readRawJsonSchema(schema: StandardSchemaV1): Record<string, unknown> | undefined {
45
+ const messageOf = (error: unknown): string => error instanceof Error ? error.message : String(error)
46
+
47
+ function readRawJsonSchema(schema: StandardSchemaV1): { json?: Record<string, unknown>, reason?: string } {
48
+ let reason: string | undefined
44
49
  const stdJson = schema['~standard']?.jsonSchema
45
50
  if (stdJson !== undefined && typeof stdJson.input === 'function') {
46
51
  for (const target of ['draft-2020-12', 'draft-07'] as const) {
47
52
  try {
48
53
  const out = stdJson.input({ target })
49
54
  if (isRecord(out))
50
- return out
55
+ return { json: out }
51
56
  }
52
- catch {
53
- continue
57
+ catch (error) {
58
+ reason ??= messageOf(error)
54
59
  }
55
60
  }
56
61
  }
@@ -59,15 +64,15 @@ function readRawJsonSchema(schema: StandardSchemaV1): Record<string, unknown> |
59
64
  try {
60
65
  const out = candidate.toJSONSchema()
61
66
  if (isRecord(out))
62
- return out
67
+ return { json: out }
63
68
  }
64
- catch {
65
- return undefined
69
+ catch (error) {
70
+ return { reason: reason ?? messageOf(error) }
66
71
  }
67
72
  }
68
73
  if (isRecord(candidate.jsonSchema))
69
- return candidate.jsonSchema
70
- return undefined
74
+ return { json: candidate.jsonSchema }
75
+ return reason === undefined ? {} : { reason }
71
76
  }
72
77
 
73
78
  function resolveRef(node: Record<string, unknown>, root: Record<string, unknown>, seen: Set<string>): Record<string, unknown> {
@@ -318,11 +323,11 @@ export function extractFormSchema(schema: StandardSchemaV1): ExtractedFormSchema
318
323
  if (cached !== undefined)
319
324
  return cached
320
325
 
321
- const raw = readRawJsonSchema(schema)
326
+ const { json: raw, reason } = readRawJsonSchema(schema)
322
327
  if (raw === undefined) {
323
328
  const rawVendor: unknown = schema['~standard']?.vendor
324
329
  const vendor = typeof rawVendor === 'string' && rawVendor.trim() !== '' ? rawVendor : 'unknown'
325
- const result: ExtractedFormSchema = { ok: false, vendor }
330
+ const result: ExtractedFormSchema = { ok: false, vendor, ...(reason === undefined ? {} : { reason }) }
326
331
  schemaCache.set(schema, result)
327
332
  return result
328
333
  }
@@ -1,7 +1,8 @@
1
- // Server observability helpers: `/_pru/health` probes, fast request IDs (`x-request-id`), and dev-only `Server-Timing`.
1
+ // Server observability helpers: `/_pru/health` probes, fast request IDs (`x-request-id`), and the phases a request goes through (dev `Server-Timing`, the access log and `onRequestEnd` hooks).
2
2
 
3
3
  import type { Middleware, RequestContext } from './http'
4
4
  import type { TrustProxy } from './security'
5
+ import { proxyHops } from './security'
5
6
 
6
7
  export type HealthCheckResult = boolean | void | { ok: boolean, message?: string | undefined }
7
8
  export type HealthCheckFn = () => HealthCheckResult | Promise<HealthCheckResult>
@@ -18,11 +19,17 @@ export interface HealthCheckOutcome {
18
19
  error?: string | undefined
19
20
  }
20
21
 
21
- export interface DevTiming {
22
+ export type RequestPhaseName = 'middleware' | 'load' | 'render' | 'stream'
23
+
24
+ export interface PhaseTiming {
22
25
  middleware?: number | undefined
23
26
  load?: number | undefined
24
27
  render?: number | undefined
25
28
  stream?: number | undefined
29
+ /** When each phase began (`performance.now()`), kept for a request the access log or an `onRequestEnd` hook hears. */
30
+ starts?: Partial<Record<RequestPhaseName, number>> | undefined
31
+ /** Measured for those hooks in production, never sent as `Server-Timing`. */
32
+ headerless?: true | undefined
26
33
  }
27
34
 
28
35
  export type RequestIdResolver = (request: Request) => string
@@ -55,8 +62,7 @@ export function isSafeRequestId(id: string): boolean {
55
62
  return true
56
63
  }
57
64
 
58
- const trustsProxyHeader = (trustProxy: TrustProxy): boolean =>
59
- trustProxy === true || (typeof trustProxy === 'number' && trustProxy > 0)
65
+ const trustsProxyHeader = (trustProxy: TrustProxy): boolean => proxyHops(trustProxy) > 0
60
66
 
61
67
  /** Fast per-server request ID resolver: 8-char random boot prefix + base36 counter (zero `randomUUID` / regex per request). */
62
68
  export function createRequestIdResolver(trustProxy: TrustProxy): RequestIdResolver {
@@ -100,25 +106,38 @@ export function withRequestId(res: Response, requestId: string): Response {
100
106
  }
101
107
  }
102
108
 
103
- export const createTiming = (isDev: boolean): DevTiming | undefined => (isDev ? {} : undefined)
109
+ // The timings of the requests something listens to, set where the request enters the server and read wherever a phase runs.
110
+ const observedTimings = new WeakMap<Request, PhaseTiming>()
111
+
112
+ /** Starts measuring the phases of `request`, for the access log or an `onRequestEnd` hook. */
113
+ export function observeTiming(request: Request, isDev: boolean): PhaseTiming {
114
+ const timing: PhaseTiming = isDev ? { starts: {} } : { starts: {}, headerless: true }
115
+ observedTimings.set(request, timing)
116
+ return timing
117
+ }
118
+
119
+ export const createTiming = (isDev: boolean, request: Request): PhaseTiming | undefined => observedTimings.get(request) ?? (isDev ? {} : undefined)
104
120
 
105
- export const startTimer = (timing: DevTiming | undefined): number => (timing !== undefined ? performance.now() : 0)
121
+ export const startTimer = (timing: PhaseTiming | undefined): number => (timing !== undefined ? performance.now() : 0)
106
122
 
107
- export function endTimer(timing: DevTiming | undefined, phase: keyof DevTiming, start: number): void {
108
- if (timing !== undefined)
109
- timing[phase] = performance.now() - start
123
+ export function endTimer(timing: PhaseTiming | undefined, phase: RequestPhaseName, start: number): void {
124
+ if (timing === undefined)
125
+ return
126
+ timing[phase] = performance.now() - start
127
+ if (timing.starts !== undefined)
128
+ timing.starts[phase] = start
110
129
  }
111
130
 
112
131
  /** Completes an in-progress `timing.render` start timestamp and formats the `Server-Timing` header value. */
113
- export function finishRenderTiming(timing: DevTiming): string | undefined {
132
+ export function finishRenderTiming(timing: PhaseTiming): string | undefined {
114
133
  if (timing.render !== undefined)
115
- timing.render = performance.now() - timing.render
134
+ endTimer(timing, 'render', timing.render)
116
135
  return formatServerTiming(timing)
117
136
  }
118
137
 
119
138
  /** 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)
139
+ export function formatServerTiming(timing: PhaseTiming | undefined): string | undefined {
140
+ if (timing === undefined || timing.headerless === true)
122
141
  return undefined
123
142
  const parts: string[] = []
124
143
  if (timing.middleware !== undefined)
@@ -137,7 +156,7 @@ export async function runTimedChain(
137
156
  ctx: RequestContext,
138
157
  middlewares: readonly Middleware[],
139
158
  last: () => Response | Promise<Response>,
140
- timing: DevTiming | undefined,
159
+ timing: PhaseTiming | undefined,
141
160
  runChain: (ctx: RequestContext, middlewares: readonly Middleware[], last: () => Response | Promise<Response>) => Promise<Response>,
142
161
  ): Promise<Response> {
143
162
  if (timing === undefined || middlewares.length === 0)
@@ -154,6 +173,8 @@ export async function runTimedChain(
154
173
  }
155
174
  })
156
175
  timing.middleware = Math.max(0, performance.now() - chainStart - innerMs)
176
+ if (timing.starts !== undefined)
177
+ timing.starts.middleware = chainStart
157
178
  return res
158
179
  }
159
180
 
@@ -5,10 +5,11 @@ import type { PrunelleChild } from '../jsx-runtime'
5
5
  import type { ServerErrorInfo, ServerRuntimeConfig, ServiceKey } from '../plugins/index'
6
6
  import type { NormalizedConsentConfig, RequestConsent } from './consent'
7
7
  import type { Cookies } from './cookies'
8
- import type { PrunelleLocals } from './index'
8
+ import type { PrunelleLocals, PrunelleRoutes } from './public'
9
9
  import type { TrustProxy } from './security'
10
10
  import { createRequestConsent } from './consent'
11
11
  import { CookieStore } from './cookies'
12
+ import { cancelQuietly } from './discard'
12
13
  import { nodeEnv } from './env'
13
14
  import { resolveFallbackRequestId } from './health'
14
15
  import { requestedRegion } from './region'
@@ -81,6 +82,9 @@ export type ExtractRouteParams<Path extends string> =
81
82
  ? Record<string, string>
82
83
  : ExtractRouteParamsRec<Path>
83
84
 
85
+ /** A route pattern of the app (`'/posts/[slug]'`), or any string until prunelle has written the app's `prunelle-routes.d.ts`. */
86
+ export type RoutePattern = [keyof PrunelleRoutes] extends [never] ? string : Extract<keyof PrunelleRoutes, string>
87
+
84
88
  export type LoaderFn = (...args: never[]) => unknown
85
89
 
86
90
  /** Infers the resolved page `data` type returned by a route's `load()` function, excluding `Response` and `notFound()`. */
@@ -93,7 +97,7 @@ type InferLoaderParams<T extends LoaderFn> =
93
97
 
94
98
  /** Props passed to a Prunelle route page component. Pass `typeof load` to infer `data` (and `params` when `load` uses `RouteContext<Path>`), or a route path string when there is no `load`. */
95
99
  export type PageProps<
96
- TLoadOrPath extends LoaderFn | string | undefined = undefined,
100
+ TLoadOrPath extends LoaderFn | RoutePattern | undefined = undefined,
97
101
  TPath extends string = string,
98
102
  > = {
99
103
  params: TLoadOrPath extends string
@@ -147,6 +151,8 @@ export interface RequestContext<Params = Record<string, string>> {
147
151
  cookies: Cookies
148
152
  consent: RequestConsent
149
153
  locals: PrunelleLocals
154
+ /** The parsed value of the route's `export const schema` (its JSON body, or its query for `GET` and `HEAD`): set before the handler runs, `undefined` when the route exports none. */
155
+ input?: unknown
150
156
  ip?: string | undefined
151
157
  /** Unique identifier for this request, echoed in the `x-request-id` response header and passed to `onError`. */
152
158
  readonly requestId: string
@@ -160,15 +166,22 @@ export interface RequestContext<Params = Record<string, string>> {
160
166
  }
161
167
 
162
168
  /** `RequestContext` with `params` inferred from a Prunelle route pattern (e.g. `RouteContext<'/notices/[id]'>`). */
163
- export type RouteContext<Path extends string = string> = RequestContext<ExtractRouteParams<Path>>
169
+ export type RouteContext<Path extends RoutePattern = RoutePattern> = RequestContext<RoutePattern extends Path ? Record<string, string> : ExtractRouteParams<Path>>
164
170
 
165
171
  export type Middleware = (ctx: RequestContext, next: () => Promise<Response>) => Response | Promise<Response>
166
172
 
167
173
  export type PrunelleServer = ReturnType<typeof Bun.serve>
168
174
 
175
+ export interface ServeOptions {
176
+ /** Lets other processes listen on the same port (`SO_REUSEPORT`, Linux), the kernel spreading connections across them: `prunelle start --workers` sets it. */
177
+ reusePort?: boolean | undefined
178
+ }
179
+
169
180
  export interface PrunelleApp {
170
181
  handle: (request: Request, remoteIp?: string, setIdleTimeout?: (seconds: number) => void) => Promise<Response>
171
- serve: (port?: number, hostname?: string) => PrunelleServer
182
+ serve: (port?: number, hostname?: string, options?: ServeOptions) => PrunelleServer
183
+ /** @internal What each process of this app keeps alone, one clause each, when several serve it with no `store`: `prunelle start --workers` warns with them. */
184
+ perProcessState?: () => string[]
172
185
  /** @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
186
  reloadInto?: (server: PrunelleServer) => void
174
187
  /** Looks up a server-scoped plugin service registered during `server(api)` (e.g. `JOBS_SERVICE`). */
@@ -365,11 +378,16 @@ export function makeRequestContext(
365
378
  opts?.httpsSite === true || isHttpsRequest(request, trustProxy),
366
379
  category => getConsent().has(category),
367
380
  )
381
+ const locals: PrunelleLocals = {}
382
+ const resolveLocale = (): string | undefined => {
383
+ const locale = (locals as { locale?: unknown }).locale
384
+ return typeof locale === 'string' && locale !== '' ? locale : undefined
385
+ }
368
386
  const getConsent = (): RequestConsent => {
369
387
  const raw = consentConfig !== undefined ? cookieStore.get(consentConfig.cookieName) : undefined
370
388
  if (cachedConsent === undefined || raw !== cachedConsentRaw) {
371
389
  cachedConsentRaw = raw
372
- cachedConsent = createRequestConsent(raw, consentConfig)
390
+ cachedConsent = createRequestConsent(raw, consentConfig, resolveLocale)
373
391
  }
374
392
  return cachedConsent
375
393
  }
@@ -385,7 +403,7 @@ export function makeRequestContext(
385
403
  get consent() {
386
404
  return getConsent()
387
405
  },
388
- locals: {},
406
+ locals,
389
407
  requestId,
390
408
  get ip() {
391
409
  if (!ipComputed) {
@@ -462,10 +480,7 @@ export async function enforceRequestBodyLimit(
462
480
  const { value } = read
463
481
  total += value.byteLength
464
482
  if (total > maxBytes) {
465
- try {
466
- await reader.cancel()
467
- }
468
- catch {}
483
+ await cancelQuietly(reader)
469
484
  return { ok: false }
470
485
  }
471
486
  chunks.push(value)