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,9 +1,9 @@
1
1
  // Standalone `--static` directory server (used when `outDir` holds exported HTML without `manifest.json`): every file is listed once at startup, so a request is a map lookup.
2
2
 
3
3
  import type { FSWatcher } from 'node:fs'
4
- import type { PrunellePlugin, ServerErrorInfo } from '../plugins/index'
4
+ import type { LogConfig, PrunellePlugin, ServerErrorInfo } from '../plugins/index'
5
5
  import type { NavigationConfig } from '../ssr/navigation'
6
- import type { PrunelleApp, PrunelleServer } from './http'
6
+ import type { PrunelleApp, PrunelleServer, ServeOptions } from './http'
7
7
  import type { SecurityHeadersOptions, TrustProxy } from './security'
8
8
  import type { FileSource, ServedFile } from './served-file'
9
9
  import { readdirSync, readFileSync, realpathSync, statSync, watch } from 'node:fs'
@@ -15,8 +15,9 @@ import { staticMime } from './assets'
15
15
  import { CompressionCache, isCompressibleType } from './compress'
16
16
  import { createErrorNotifier } from './errors'
17
17
  import { applyHstsHeader } from './http'
18
+ import { createRequestObserver } from './request-log'
18
19
  import { decodeRequestPath } from './request-path'
19
- import { buildSecurityHeaderEntries, inlineStyleHashes, PRUNELLE_ISLAND_STYLE_HASH, resolveCspPolicy, resolveHstsValue, withCspHashes } from './security'
20
+ import { buildSecurityHeaderEntries, inlineStyleHashes, PRUNELLE_ISLAND_STYLE_HASH, resolveCspPolicy, resolveHstsValue, withCspHashes, withoutCspReports } from './security'
20
21
  import { createFileServer, servedFile } from './served-file'
21
22
 
22
23
  const isRead = (request: Request): boolean => request.method === 'GET' || request.method === 'HEAD'
@@ -29,6 +30,7 @@ export interface StaticDirExtraOptions {
29
30
  errorSink?: ((info: ServerErrorInfo) => void) | undefined
30
31
  httpsSite?: boolean | undefined
31
32
  nodeEnv?: string | undefined
33
+ log?: LogConfig | undefined
32
34
  }
33
35
 
34
36
  function findNotFound(rel: string | undefined, byDir: ReadonlyMap<string, ServedFile>): ServedFile | undefined {
@@ -99,10 +101,10 @@ export function createStaticDirServer(
99
101
  realRoot = absRoot // listed as empty below, which answers 404s
100
102
  }
101
103
  const compressCache = compressEnabled ? new CompressionCache() : undefined
102
- const securityEntries = buildSecurityHeaderEntries(security)
104
+ const securityEntries = buildSecurityHeaderEntries(withoutCspReports(security))
103
105
  const securityRecord = Object.fromEntries(securityEntries)
104
- const baseCsp = resolveCspPolicy(security)
105
- const nav = extra !== undefined ? createNavigation(extra.navigation) : undefined
106
+ const baseCsp = resolveCspPolicy(withoutCspReports(security))
107
+ const nav = extra !== undefined ? createNavigation(extra.navigation, assetPrefix) : undefined
106
108
  const plugins = extra?.plugins !== undefined ? resolvePlugins(extra.plugins) : []
107
109
  const extraStyleHashes = [PRUNELLE_ISLAND_STYLE_HASH, ...(nav?.styleHashes ?? [])]
108
110
  const extraScriptHashes = [
@@ -118,7 +120,7 @@ export function createStaticDirServer(
118
120
  ? (res: Response) => res
119
121
  : (res: Response, req: Request) => applyHstsHeader(res, req, hstsValue, trustProxy, isDev, extra?.nodeEnv, httpsSite)
120
122
  const serveFileUnguarded = createFileServer({ compressEnabled, compressCache, withHsts })
121
- const notifyError = createErrorNotifier(extra?.onError, plugins, { dev: isDev, sink: extra?.errorSink })
123
+ const notifyError = createErrorNotifier(extra?.onError, plugins, { dev: isDev, sink: extra?.errorSink, format: extra?.log?.format })
122
124
  // A file that fails to open answers here, where the request is known: gone since the listing is a 404, anything else is reported.
123
125
  const serveFile = async (req: Request, file: ServedFile, status?: number): Promise<Response> => {
124
126
  try {
@@ -199,7 +201,7 @@ export function createStaticDirServer(
199
201
  console.warn(`prunelle start: files changed in ${absRoot} will be served only after a restart: ${err instanceof Error ? err.message : String(err)}`)
200
202
  }
201
203
 
202
- const handle = async (req: Request): Promise<Response> => {
204
+ const answer = async (req: Request): Promise<Response> => {
203
205
  if (!isRead(req))
204
206
  return withHsts(new Response('Method Not Allowed', { status: 405, headers: { ...securityRecord, allow: 'GET, HEAD' } }), req)
205
207
  const rel = requestedRel(new URL(req.url).pathname)
@@ -211,6 +213,8 @@ export function createStaticDirServer(
211
213
  return serveFile(req, notFound, 404)
212
214
  return withHsts(new Response('Not Found', { status: 404, headers: securityRecord }), req)
213
215
  }
216
+ const observe = createRequestObserver(extra?.log, [], isDev)
217
+ const handle = observe?.(answer) ?? answer
214
218
 
215
219
  const error = (): Response => new Response('Internal Server Error', {
216
220
  status: 500,
@@ -225,8 +229,8 @@ export function createStaticDirServer(
225
229
  return {
226
230
  handle,
227
231
  securityHeaders: securityRecord,
228
- serve(port = 3000, hostname = '127.0.0.1') {
229
- return Bun.serve({ port, hostname, idleTimeout: 30, development: false, fetch: handle, error: lastResort })
232
+ serve(port = 3000, hostname = '127.0.0.1', options: ServeOptions = {}) {
233
+ return Bun.serve({ port, hostname, reusePort: options.reusePort === true, idleTimeout: 30, development: false, fetch: handle, error: lastResort })
230
234
  },
231
235
  reloadInto(server: PrunelleServer) {
232
236
  server.reload({ routes: {}, fetch: handle, error: lastResort })
@@ -3,6 +3,7 @@
3
3
  import type { PendingChunk, RenderContext, SettledChunk } from '../ssr/context'
4
4
  import { getAppContext, runWithAppContext } from '../plugins/index'
5
5
  import { streamChunkScript } from '../ssr/context'
6
+ import { cancelQuietly } from './discard'
6
7
  import { currentRequest, runInRequest } from './request-scope'
7
8
 
8
9
  const textEncoder = new TextEncoder()
@@ -165,7 +166,7 @@ function trackEventStream(res: Response, active: Set<() => void>, setIdleTimeout
165
166
  closed = true
166
167
  active.delete(closeStream!)
167
168
  safeClose(controller)
168
- void reader.cancel().catch(() => undefined)
169
+ void cancelQuietly(reader)
169
170
  }
170
171
  active.add(closeStream)
171
172
  },
@@ -0,0 +1,39 @@
1
+ // What outside clients can call: the app's server actions and API routes, each with the JSON Schema of its input.
2
+
3
+ import type { BuildManifest } from '../build/index'
4
+ import type { AppSurface, SurfaceInput } from '../plugins/types'
5
+ import { isServerAction } from './action'
6
+ import { extractFormSchema } from './form-schema'
7
+ import { isStandardSchema } from './route-input'
8
+ import { HTTP_METHOD_EXPORTS } from './route-table'
9
+
10
+ function inputOf(schema: unknown): SurfaceInput {
11
+ if (!isStandardSchema(schema))
12
+ return { kind: 'none' }
13
+ const extracted = extractFormSchema(schema)
14
+ return extracted.ok ? { kind: 'json', schema: extracted.jsonSchema } : { kind: 'unsupported', vendor: extracted.vendor, reason: extracted.reason }
15
+ }
16
+
17
+ /** A route is an API route when it answers methods and renders no page. */
18
+ function apiMethods(mod: Record<string, unknown>): string[] {
19
+ if (typeof mod.default === 'function')
20
+ return []
21
+ return [...HTTP_METHOD_EXPORTS].filter(method => typeof mod[method] === 'function')
22
+ }
23
+
24
+ export function appSurface(manifest: BuildManifest, modules: Record<string, unknown>): AppSurface {
25
+ const actions: AppSurface['actions'][number][] = []
26
+ for (const entry of manifest.actions) {
27
+ const act = (modules[entry.file] as Record<string, unknown> | undefined)?.[entry.exportName]
28
+ if (isServerAction(act))
29
+ actions.push({ name: entry.exportName, url: entry.url, input: inputOf(act.schema), rateLimited: act.rateLimit !== undefined })
30
+ }
31
+ const routes: AppSurface['routes'][number][] = []
32
+ for (const entry of manifest.routes) {
33
+ const mod = modules[entry.file] as Record<string, unknown> | undefined
34
+ const methods = mod === undefined ? [] : apiMethods(mod)
35
+ if (methods.length > 0)
36
+ routes.push({ path: entry.path, methods, input: inputOf(mod!.schema) })
37
+ }
38
+ return { actions, routes }
39
+ }
@@ -0,0 +1,48 @@
1
+ // Webhook signatures: a route that turns off the cross-site check (`export const csrf = false`) proves the sender with one of these instead.
2
+
3
+ import { hmac, safeEqual } from './app-secret'
4
+
5
+ /** `standard` is Standard Webhooks (Svix, Resend, Clerk and others), `stripe` Stripe's `Stripe-Signature`, `github` GitHub's `X-Hub-Signature-256`. */
6
+ export type WebhookScheme = 'standard' | 'stripe' | 'github'
7
+
8
+ export interface VerifyWebhookOptions {
9
+ /** How far the signed timestamp may be from now, for the schemes that sign one (5 minutes). GitHub signs none. */
10
+ toleranceSeconds?: number | undefined
11
+ }
12
+
13
+ const TOLERANCE_SECONDS = 300
14
+ const STANDARD_PREFIX = 'whsec_'
15
+
16
+ /** The request's body when it carries a valid signature for `scheme` under `secret`, signed within `toleranceSeconds` where the scheme signs a time; undefined otherwise. It reads the body, so the route parses the text this returns. */
17
+ export async function verifyWebhook(request: Request, scheme: WebhookScheme, secret: string | undefined, options: VerifyWebhookOptions = {}): Promise<string | undefined> {
18
+ if (!secret)
19
+ throw new Error(`prunelle: verifyWebhook('${scheme}') got no secret: pass the signing secret the sender shows, read from an environment variable`)
20
+ const body = await request.text()
21
+ const headers = request.headers
22
+ const tolerance = options.toleranceSeconds ?? TOLERANCE_SECONDS
23
+ if (scheme === 'github') {
24
+ const signature = headers.get('x-hub-signature-256') ?? ''
25
+ return safeEqual(signature, `sha256=${hmac(secret, body).toString('hex')}`) ? body : undefined
26
+ }
27
+ if (scheme === 'stripe') {
28
+ const fields = (headers.get('stripe-signature') ?? '').split(',').map(field => field.split('='))
29
+ const timestamp = fields.find(([key]) => key === 't')?.[1]
30
+ if (timestamp === undefined || !fresh(timestamp, tolerance))
31
+ return undefined
32
+ const expected = hmac(secret, `${timestamp}.${body}`).toString('hex')
33
+ return fields.some(([key, value]) => key === 'v1' && value !== undefined && safeEqual(value, expected)) ? body : undefined
34
+ }
35
+ const id = headers.get('webhook-id')
36
+ const timestamp = headers.get('webhook-timestamp')
37
+ if (id === null || timestamp === null || !fresh(timestamp, tolerance))
38
+ return undefined
39
+ const key = Buffer.from(secret.startsWith(STANDARD_PREFIX) ? secret.slice(STANDARD_PREFIX.length) : secret, 'base64')
40
+ const expected = hmac(key, `${id}.${timestamp}.${body}`).toString('base64')
41
+ const signatures = (headers.get('webhook-signature') ?? '').split(' ')
42
+ return signatures.some(entry => entry.startsWith('v1,') && safeEqual(entry.slice(3), expected)) ? body : undefined
43
+ }
44
+
45
+ function fresh(timestamp: string, toleranceSeconds: number): boolean {
46
+ const seconds = Number(timestamp)
47
+ return /^\d+$/.test(timestamp) && Math.abs(Date.now() / 1000 - seconds) <= toleranceSeconds
48
+ }
@@ -0,0 +1,168 @@
1
+ // `prunelle start --workers <n>`: n processes of `prunelle start` listening on one port with SO_REUSEPORT, the kernel spreading connections across them.
2
+ // The primary serves nothing: it gives the workers one signing secret, passes a stop signal on to them, and starts again one that dies after it listened.
3
+ // Each worker tells the primary it listens over the IPC channel Bun opens between them, and stops when that channel closes, as it does when the primary is killed.
4
+
5
+ import process from 'node:process'
6
+
7
+ /** `<index>/<count>` in a worker's environment; its absence means the process serves alone. */
8
+ export const WORKER_ENV = 'PRUNELLE_WORKER'
9
+ /** The secret every worker signs with when the app sets none, so a form one rendered is accepted by the others. */
10
+ export const WORKERS_SECRET_ENV = 'PRUNELLE_WORKERS_SECRET'
11
+
12
+ /** What a worker sends the primary once it listens. */
13
+ export const READY_MESSAGE = 'prunelle:ready'
14
+
15
+ const SIGNALS = ['SIGTERM', 'SIGINT', 'SIGHUP'] as const
16
+ const RESTART_DELAY_MS = 1000
17
+ const WORKER_RE = /^(\d+)\/(\d+)$/
18
+
19
+ /** This process's place among the workers of a `prunelle start --workers`, or undefined when it serves alone. */
20
+ export function workerOf(env: Record<string, string | undefined> = process.env): { index: number, count: number } | undefined {
21
+ const match = WORKER_RE.exec(env[WORKER_ENV] ?? '')
22
+ return match === null ? undefined : { index: Number(match[1]), count: Number(match[2]) }
23
+ }
24
+
25
+ /** In a worker: stops it the way SIGTERM does once the primary is gone, whose stop signal would never come, and SO_REUSEPORT would let a new primary's workers share the port with it. */
26
+ export function followPrimary(): void {
27
+ process.once('disconnect', () => process.kill(process.pid, 'SIGTERM'))
28
+ }
29
+
30
+ /** In a worker: tells the primary it listens, so a later exit is a crash to recover from rather than a failure to start. */
31
+ export function reportListening(): void {
32
+ process.send?.(READY_MESSAGE)
33
+ }
34
+
35
+ /** The count `--workers` asks for, a whole number from 1 or `auto` for one per CPU core; undefined when it is neither. */
36
+ export function parseWorkers(value: string, cores: number = navigator.hardwareConcurrency): number | undefined {
37
+ if (value === 'auto')
38
+ return Math.max(1, cores)
39
+ const count = Number(value)
40
+ return Number.isInteger(count) && count >= 1 ? count : undefined
41
+ }
42
+
43
+ const RATE_LIMIT_CLAUSE = 'each counts rate limits alone, so a client gets its limit once per process'
44
+
45
+ export interface PerProcessInput {
46
+ store: string | undefined
47
+ /** Limiters counting in the process's memory, with or without a `store`: the app's own `createRateLimitStore()` ones and the unnamed ones of plugins. */
48
+ limiters: number
49
+ actionsRateLimited: boolean
50
+ cachedRoutes: boolean
51
+ plugins: readonly { perProcess?: string | undefined }[]
52
+ }
53
+
54
+ /** What each process keeps alone when several serve the app with no `store`, one clause each. */
55
+ export function perProcessState(input: PerProcessInput): string[] {
56
+ // A `store` shares the named limiters; the ones counting in memory stay per process.
57
+ if (input.store !== undefined)
58
+ return input.limiters > 0 ? [RATE_LIMIT_CLAUSE] : []
59
+ const clauses: string[] = []
60
+ if (input.limiters > 0 || input.actionsRateLimited)
61
+ clauses.push(RATE_LIMIT_CLAUSE)
62
+ if (input.cachedRoutes)
63
+ clauses.push('invalidateCache() drops a cached page in the process that ran it only')
64
+ for (const plugin of input.plugins) {
65
+ if (plugin.perProcess !== undefined)
66
+ clauses.push(plugin.perProcess)
67
+ }
68
+ return clauses
69
+ }
70
+
71
+ export interface SuperviseOptions {
72
+ count: number
73
+ /** What each worker runs: this `prunelle start` again, which reads its place from `PRUNELLE_WORKER` and sends `READY_MESSAGE` once it listens. The others start once the first has. */
74
+ command: string[]
75
+ env?: Record<string, string | undefined> | undefined
76
+ log?: ((message: string) => void) | undefined
77
+ /** @internal How long a worker that died waits before it starts again (1 s). */
78
+ restartDelayMs?: number | undefined
79
+ }
80
+
81
+ export interface Supervisor {
82
+ /** Passes `signal` on to every worker and starts none again. */
83
+ stop: (signal?: typeof SIGNALS[number]) => void
84
+ /** The highest exit code of the workers, once the last has exited after a stop. */
85
+ exited: Promise<number>
86
+ }
87
+
88
+ /** Starts the first worker, the others once it listens, starts again one that dies after it listened, and stops them all on SIGTERM, SIGINT or SIGHUP, or when one exits before it listens. */
89
+ export function superviseWorkers(options: SuperviseOptions): Supervisor {
90
+ const env = options.env ?? process.env
91
+ // A worker starting workers would start more on each restart, until the machine runs out of memory.
92
+ if (workerOf(env) !== undefined)
93
+ throw new Error(`prunelle: a worker of prunelle start --workers cannot start workers of its own: unset ${WORKER_ENV} in the environment that runs prunelle start`)
94
+ const log = options.log ?? ((message: string) => console.error(message))
95
+ const secret = env.PRUNELLE_FORM_SECRET || env.AUTH_SECRET ? undefined : Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString('hex')
96
+ const workers = new Map<number, Bun.Subprocess>()
97
+ const timers = new Set<ReturnType<typeof setTimeout>>()
98
+ let stopping = false
99
+ let exitCode = 0
100
+ let resolveExited!: (code: number) => void
101
+ const exited = new Promise<number>(resolve => resolveExited = resolve)
102
+
103
+ const settle = (): void => {
104
+ if (stopping && workers.size === 0 && timers.size === 0) {
105
+ for (const [signal, listener] of listeners)
106
+ process.off(signal, listener)
107
+ resolveExited(exitCode)
108
+ }
109
+ }
110
+
111
+ const stop = (signal: typeof SIGNALS[number] = 'SIGTERM'): void => {
112
+ stopping = true
113
+ for (const timer of timers)
114
+ clearTimeout(timer)
115
+ timers.clear()
116
+ for (const worker of workers.values())
117
+ worker.kill(signal)
118
+ settle()
119
+ }
120
+
121
+ // The others wait for the first to listen: a config that fails to load is then reported by one worker, not by each.
122
+ let othersStarted = false
123
+ const start = (index: number): void => {
124
+ let listening = false
125
+ const worker = Bun.spawn(options.command, {
126
+ env: { ...env, [WORKER_ENV]: `${index}/${options.count}`, ...(secret === undefined ? {} : { [WORKERS_SECRET_ENV]: secret }) },
127
+ stdio: ['ignore', 'inherit', 'inherit'],
128
+ ipc: (message) => {
129
+ if (message !== READY_MESSAGE)
130
+ return
131
+ listening = true
132
+ if (othersStarted)
133
+ return
134
+ othersStarted = true
135
+ for (let other = 2; other <= options.count && !stopping; other++)
136
+ start(other)
137
+ },
138
+ })
139
+ workers.set(index, worker)
140
+ void worker.exited.then((code) => {
141
+ workers.delete(index)
142
+ if (stopping) {
143
+ exitCode = Math.max(exitCode, code)
144
+ return settle()
145
+ }
146
+ // Starting it again would fail the same way. Exit code 0 is a stop signal that reached the worker before the primary, as Ctrl-C does.
147
+ if (!listening) {
148
+ log(code === 0
149
+ ? `prunelle start: worker ${index} stopped before it listened, so every worker is stopped`
150
+ : `prunelle start: worker ${index} exited with code ${code} before it listened, so every worker is stopped: its error is above`)
151
+ exitCode = code
152
+ return stop()
153
+ }
154
+ log(`prunelle start: worker ${index} exited with code ${code}; starting it again`)
155
+ const timer = setTimeout(() => {
156
+ timers.delete(timer)
157
+ start(index)
158
+ }, options.restartDelayMs ?? RESTART_DELAY_MS)
159
+ timers.add(timer)
160
+ })
161
+ }
162
+
163
+ const listeners = SIGNALS.map(signal => [signal, () => stop(signal)] as const)
164
+ for (const [signal, listener] of listeners)
165
+ process.on(signal, listener)
166
+ start(1)
167
+ return { stop, exited }
168
+ }
@@ -2,6 +2,8 @@
2
2
 
3
3
  import type { ConsentBannerProps, ConsentTexts } from '../context'
4
4
  import type { RequestConsent } from '../server/consent'
5
+ import type { ConsentDefaults } from './consent-texts'
6
+ import { consentDefaults } from './consent-texts'
5
7
  import { esc, escAttr, ssrChild } from './index'
6
8
 
7
9
  function requireCategories(consent: RequestConsent, tag: string): void {
@@ -9,52 +11,54 @@ function requireCategories(consent: RequestConsent, tag: string): void {
9
11
  throw new Error(`prunelle: <${tag}> has no consent category to ask about: declare them in prunelle.config.ts, such as consent: { categories: { analytics: 'Audience measurement' } }.`)
10
12
  }
11
13
 
12
- function checkboxes(consent: RequestConsent, legend: string | undefined): string {
14
+ function checkboxes(consent: RequestConsent, legend: string): string {
13
15
  const boxes = consent.categories.map((category) => {
14
16
  const checked = consent.has(category) ? ' checked' : ''
15
17
  return `<label data-part="choice"><input type="checkbox" name="categories" value="${escAttr(category)}"${checked}> ${esc(consent.labels[category] ?? category)}</label>`
16
18
  })
17
- return `<fieldset data-part="choices"><legend>${esc(legend ?? 'Cookies by purpose')}</legend>${boxes.join('')}</fieldset>`
19
+ return `<fieldset data-part="choices"><legend>${esc(legend)}</legend>${boxes.join('')}</fieldset>`
18
20
  }
19
21
 
20
22
  // Refuse comes first and looks the same as Accept: the CNIL asks for a refusal as easy as a consent.
21
- function decisionButtons(texts: ConsentTexts): string {
22
- return `<button type="submit" name="action" value="reject-all" data-ui="button">${esc(texts.refuse ?? 'Refuse all')}</button>`
23
- + `<button type="submit" name="action" value="accept-all" data-ui="button">${esc(texts.accept ?? 'Accept all')}</button>`
23
+ function decisionButtons(texts: ConsentTexts, defaults: ConsentDefaults): string {
24
+ return `<button type="submit" name="action" value="reject-all" data-ui="button">${esc(texts.refuse ?? defaults.refuse)}</button>`
25
+ + `<button type="submit" name="action" value="accept-all" data-ui="button">${esc(texts.accept ?? defaults.accept)}</button>`
24
26
  }
25
27
 
26
- function saveButton(texts: ConsentTexts): string {
27
- return `<button type="submit" name="action" value="save" data-ui="button">${esc(texts.save ?? 'Save my choices')}</button>`
28
+ function saveButton(texts: ConsentTexts, defaults: ConsentDefaults): string {
29
+ return `<button type="submit" name="action" value="save" data-ui="button">${esc(texts.save ?? defaults.save)}</button>`
28
30
  }
29
31
 
30
- export function renderConsentBanner(consent: RequestConsent | undefined, props: ConsentBannerProps): string {
32
+ export function renderConsentBanner(consent: RequestConsent | undefined, props: ConsentBannerProps, lang?: string): string {
31
33
  if (consent === undefined)
32
34
  return ''
33
35
  requireCategories(consent, 'ConsentBanner')
34
36
  if (consent.decided)
35
37
  return ''
38
+ const defaults = consentDefaults(lang ?? consent.lang)
36
39
  const labels = consent.categories.map(category => consent.labels[category] ?? category).join(', ')
37
40
  const body = props.children !== undefined
38
41
  ? ssrChild(props.children)
39
- : `<p>This site would like to set cookies for: ${esc(labels)}. You can accept or refuse them, and change your mind at any time.</p>`
42
+ : `<p>${defaults.body(esc(labels))}</p>`
40
43
  const policy = props.policyHref !== undefined
41
- ? `<p><a href="${escAttr(props.policyHref)}">${esc(props.policyLabel ?? 'Cookie policy')}</a></p>`
44
+ ? `<p><a href="${escAttr(props.policyHref)}">${esc(props.policyLabel ?? defaults.policy)}</a></p>`
42
45
  : ''
43
46
  return `<section data-ui="consent" aria-labelledby="pru-consent-title">`
44
- + `<h2 id="pru-consent-title" data-part="title">${esc(props.title ?? 'Cookies')}</h2>`
47
+ + `<h2 id="pru-consent-title" data-part="title">${esc(props.title ?? defaults.title)}</h2>`
45
48
  + `<div data-part="body">${body}${policy}</div>`
46
49
  + `<form method="post" action="${escAttr(consent.endpoint)}" data-part="form">`
47
- + `<div data-part="actions">${decisionButtons(props)}</div>`
48
- + `<details data-part="details"><summary>${esc(props.choose ?? 'Choose')}</summary>${checkboxes(consent, props.legend)}${saveButton(props)}</details>`
50
+ + `<div data-part="actions">${decisionButtons(props, defaults)}</div>`
51
+ + `<details data-part="details"><summary>${esc(props.choose ?? defaults.choose)}</summary>${checkboxes(consent, props.legend ?? defaults.legend)}${saveButton(props, defaults)}</details>`
49
52
  + `</form></section>`
50
53
  }
51
54
 
52
- export function renderConsentPreferences(consent: RequestConsent | undefined, texts: ConsentTexts): string {
55
+ export function renderConsentPreferences(consent: RequestConsent | undefined, texts: ConsentTexts, lang?: string): string {
53
56
  if (consent === undefined)
54
57
  return ''
55
58
  requireCategories(consent, 'ConsentPreferences')
59
+ const defaults = consentDefaults(lang ?? consent.lang)
56
60
  return `<form method="post" action="${escAttr(consent.endpoint)}" data-ui="consent" data-part="preferences">`
57
- + `${checkboxes(consent, texts.legend)}`
58
- + `<div data-part="actions">${saveButton(texts)}${decisionButtons(texts)}</div>`
61
+ + `${checkboxes(consent, texts.legend ?? defaults.legend)}`
62
+ + `<div data-part="actions">${saveButton(texts, defaults)}${decisionButtons(texts, defaults)}</div>`
59
63
  + `</form>`
60
64
  }
@@ -0,0 +1,40 @@
1
+ // The default texts of <ConsentBanner> and <ConsentPreferences>, in the language of the app's `lang`.
2
+
3
+ export interface ConsentDefaults {
4
+ title: string
5
+ /** The sentence of the banner, given the labels of the categories it asks about. */
6
+ body: (labels: string) => string
7
+ policy: string
8
+ accept: string
9
+ refuse: string
10
+ save: string
11
+ choose: string
12
+ legend: string
13
+ }
14
+
15
+ const ENGLISH: ConsentDefaults = {
16
+ title: 'Cookies',
17
+ body: labels => `This site would like to set cookies for: ${labels}. You can accept or refuse them, and change your mind at any time.`,
18
+ policy: 'Cookie policy',
19
+ accept: 'Accept all',
20
+ refuse: 'Refuse all',
21
+ save: 'Save my choices',
22
+ choose: 'Choose',
23
+ legend: 'Cookies by purpose',
24
+ }
25
+
26
+ const FRENCH: ConsentDefaults = {
27
+ title: 'Cookies',
28
+ body: labels => `Ce site souhaite déposer des cookies pour : ${labels}. Vous pouvez les accepter ou les refuser, et changer d'avis à tout moment.`,
29
+ policy: 'Politique de cookies',
30
+ accept: 'Tout accepter',
31
+ refuse: 'Tout refuser',
32
+ save: 'Enregistrer mes choix',
33
+ choose: 'Choisir',
34
+ legend: 'Cookies par finalité',
35
+ }
36
+
37
+ /** French for `fr`, `fr-CA` and the like, English for any other language. */
38
+ export function consentDefaults(lang: string): ConsentDefaults {
39
+ return lang.split('-', 1)[0]!.toLowerCase() === 'fr' ? FRENCH : ENGLISH
40
+ }
@@ -1,13 +1,18 @@
1
1
  // Per-request SSR context for <Head> metadata, streaming <Suspense>, rendered island tracking,
2
2
  // universal createContext/useContext, and deterministic hydration-safe useId().
3
3
 
4
- import type { CatchProps, ConsentBannerProps, ConsentGateProps, ConsentTexts } from '../context'
4
+ import type { CatchProps, ConsentBannerProps, ConsentGateProps, ConsentTexts, CookieTableProps } from '../context'
5
5
  import type { Html, PrunelleChild } from '../jsx-runtime'
6
+ import type { RequestSeeds } from '../reactivity/index'
6
7
  import type { RequestConsent } from '../server/consent'
7
8
  import type { FieldConstraint } from '../server/form-schema'
8
9
  import { AsyncLocalStorage } from 'node:async_hooks'
9
10
  import { registerServerContextBridge } from '../context'
11
+ import { getAppContext } from '../plugins/context'
12
+ import { COOKIE_INVENTORY } from '../server/cookie-inventory'
13
+ import { currentRequest } from '../server/request-scope'
10
14
  import { renderConsentBanner, renderConsentPreferences } from './consent-banner'
15
+ import { renderCookieTable } from './cookie-table'
11
16
  import { raw, ssrChild } from './index'
12
17
  import { Region } from './region'
13
18
 
@@ -40,6 +45,8 @@ export interface RenderContext {
40
45
  outerContexts: Map<symbol, unknown> | undefined
41
46
  /** The island rendering, as its tag. */
42
47
  island: string | undefined
48
+ /** What the request's islands wrote to module state, which each island's server render starts from. */
49
+ seeds: RequestSeeds | undefined
43
50
  /** Maps island chunk URL -> eager (true if hydrate is undefined/'load'). */
44
51
  renderedIslands: Map<string, boolean>
45
52
  hasIslands: boolean
@@ -182,6 +189,9 @@ registerServerContextBridge({
182
189
  return undefined
183
190
  return `${ctx.idPrefix}${ctx.idSeq++}`
184
191
  },
192
+ requestLocale() {
193
+ return requestLocale()
194
+ },
185
195
  region(props) {
186
196
  return Region(props)
187
197
  },
@@ -194,6 +204,9 @@ registerServerContextBridge({
194
204
  consentPreferences(props) {
195
205
  return ConsentPreferences(props)
196
206
  },
207
+ cookieTable(props) {
208
+ return CookieTable(props)
209
+ },
197
210
  head(props) {
198
211
  return Head(props)
199
212
  },
@@ -224,6 +237,7 @@ export function createRenderContext(
224
237
  contexts: new Map(),
225
238
  outerContexts: undefined,
226
239
  island: undefined,
240
+ seeds: undefined,
227
241
  renderedIslands: new Map(),
228
242
  hasIslands: false,
229
243
  revives: false,
@@ -360,12 +374,21 @@ export function ConsentGate(props: ConsentGateProps): Html {
360
374
  return raw(ssrChild(granted ? props.children : props.fallback))
361
375
  }
362
376
 
377
+ function requestLocale(): string | undefined {
378
+ const locale = (currentRequest()?.ctx.locals as { locale?: unknown } | undefined)?.locale
379
+ return typeof locale === 'string' && locale !== '' ? locale : undefined
380
+ }
381
+
363
382
  export function ConsentBanner(props: ConsentBannerProps): Html {
364
- return raw(renderConsentBanner(renderStorage.getStore()?.consent, props))
383
+ return raw(renderConsentBanner(renderStorage.getStore()?.consent, props, requestLocale()))
365
384
  }
366
385
 
367
386
  export function ConsentPreferences(props: ConsentTexts): Html {
368
- return raw(renderConsentPreferences(renderStorage.getStore()?.consent, props))
387
+ return raw(renderConsentPreferences(renderStorage.getStore()?.consent, props, requestLocale()))
388
+ }
389
+
390
+ export function CookieTable(props: CookieTableProps): Html {
391
+ return raw(renderCookieTable(getAppContext()?.inject(COOKIE_INVENTORY), props, requestLocale()))
369
392
  }
370
393
 
371
394
  const STACK_FRAME_RE = /^\s*at\s+(?:async\s+)?([A-Za-z_$][\w$]*)\s+\(/
@@ -0,0 +1,75 @@
1
+ // The markup of <CookieTable>: one row per cookie the site sets, in the app's language, with no script.
2
+
3
+ import type { CookieTableProps } from '../context'
4
+ import type { CookieInventory, CookieRow } from '../server/cookie-inventory'
5
+ import { esc } from './index'
6
+
7
+ interface CookieTableTexts {
8
+ caption: string
9
+ name: string
10
+ purpose: string
11
+ category: string
12
+ lifetime: string
13
+ essential: string
14
+ session: string
15
+ /** A field the source does not give, such as `[to fill in: purpose]`. */
16
+ missing: (field: string) => string
17
+ }
18
+
19
+ const ENGLISH: CookieTableTexts = {
20
+ caption: 'Cookies this site sets',
21
+ name: 'Name',
22
+ purpose: 'Purpose',
23
+ category: 'Category',
24
+ lifetime: 'Lifetime',
25
+ essential: 'Essential',
26
+ session: 'Browser session',
27
+ missing: field => `[to fill in: ${field}]`,
28
+ }
29
+
30
+ const FRENCH: CookieTableTexts = {
31
+ caption: 'Cookies déposés par ce site',
32
+ name: 'Nom',
33
+ purpose: 'Finalité',
34
+ category: 'Catégorie',
35
+ lifetime: 'Durée de conservation',
36
+ essential: 'Nécessaire',
37
+ session: 'Session du navigateur',
38
+ missing: field => `[à compléter : ${field}]`,
39
+ }
40
+
41
+ const FRENCH_FIELDS: Readonly<Record<string, string>> = { name: 'nom', purpose: 'finalité', category: 'catégorie', lifetime: 'durée' }
42
+
43
+ // The largest unit the lifetime is a whole number of, a month counted as 30 days and a year as 365; 30 days stays 30 days rather than 1 month.
44
+ const UNITS = [['year', 31_536_000, 1], ['month', 2_592_000, 2], ['day', 86_400, 1], ['hour', 3600, 1], ['minute', 60, 1]] as const
45
+
46
+ function formatLifetime(seconds: number, lang: string): string {
47
+ const [unit, size] = UNITS.find(([, size, least]) => seconds >= size * least && seconds % size === 0) ?? ['second', 1]
48
+ return new Intl.NumberFormat(lang, { style: 'unit', unit, unitDisplay: 'long' }).format(seconds / size)
49
+ }
50
+
51
+ function purposeIn(purpose: CookieRow['purpose'], lang: string): string | undefined {
52
+ if (purpose === undefined || typeof purpose === 'string')
53
+ return purpose
54
+ return purpose[lang] ?? purpose[lang.split('-', 1)[0]!] ?? purpose.en ?? Object.values(purpose)[0]
55
+ }
56
+
57
+ export function renderCookieTable(inventory: CookieInventory | undefined, props: CookieTableProps, lang?: string): string {
58
+ if (inventory === undefined)
59
+ return ''
60
+ const activeLang = lang ?? inventory.lang
61
+ const french = activeLang.split('-', 1)[0]!.toLowerCase() === 'fr'
62
+ const texts = french ? FRENCH : ENGLISH
63
+ const missing = (field: string): string => esc(texts.missing(french ? FRENCH_FIELDS[field]! : field))
64
+ const rows = inventory.rows.map((row) => {
65
+ const purpose = purposeIn(row.purpose, activeLang)
66
+ const category = row.category === 'essential' ? texts.essential : row.category === undefined ? undefined : inventory.labels[row.category] ?? row.category
67
+ const lifetime = row.lifetime === 'session' ? texts.session : row.lifetime === undefined ? undefined : formatLifetime(row.lifetime, activeLang)
68
+ return `<tr><td>${row.name === undefined ? missing('name') : `<code>${esc(row.name)}</code>`}</td>`
69
+ + `<td>${purpose === undefined ? missing('purpose') : esc(purpose)}</td>`
70
+ + `<td>${category === undefined ? missing('category') : esc(category)}</td>`
71
+ + `<td>${lifetime === undefined ? missing('lifetime') : esc(lifetime)}</td></tr>`
72
+ })
73
+ const head = [texts.name, texts.purpose, texts.category, texts.lifetime].map(label => `<th scope="col">${esc(label)}</th>`).join('')
74
+ return `<table data-ui="table"><caption>${esc(props.caption ?? texts.caption)}</caption><thead><tr>${head}</tr></thead><tbody>${rows.join('')}</tbody></table>`
75
+ }