prunelle 0.8.0 → 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 (184) hide show
  1. package/llms.txt +61 -44
  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 +14 -6
  14. package/src/build/index.ts +20 -10
  15. package/src/build/islands.ts +4 -1
  16. package/src/build/key-types.ts +31 -0
  17. package/src/build/manifest.ts +19 -1
  18. package/src/build/plugin-host.ts +2 -0
  19. package/src/build/prerender.ts +2 -2
  20. package/src/build/reach.ts +14 -1
  21. package/src/build/report.ts +1 -1
  22. package/src/build/route-types.ts +16 -0
  23. package/src/build/routes.ts +24 -15
  24. package/src/build/seed-ids.ts +65 -0
  25. package/src/build/seed-writes.ts +111 -0
  26. package/src/build/static-headers.ts +2 -2
  27. package/src/build/static.ts +1 -1
  28. package/src/cli/check-cache.ts +51 -0
  29. package/src/cli/check-consent.ts +95 -0
  30. package/src/cli/check-forms.ts +2 -2
  31. package/src/cli/check-links-patterns.ts +101 -0
  32. package/src/cli/check-links.ts +16 -100
  33. package/src/cli/check-regions.ts +185 -0
  34. package/src/cli/check-security.ts +50 -6
  35. package/src/cli/check.ts +40 -18
  36. package/src/cli/commands.ts +134 -14
  37. package/src/cli/docs.ts +21 -2
  38. package/src/cli/index.ts +1 -1
  39. package/src/cli/inspect.ts +2 -0
  40. package/src/cli/mcp-tools.ts +2 -2
  41. package/src/cli/new.ts +9 -5
  42. package/src/cli/upgrade-names.ts +14 -2
  43. package/src/cli/upgrade.ts +3 -0
  44. package/src/compiler/analyze.ts +2 -2
  45. package/src/compiler/cacheability.ts +24 -2
  46. package/src/compiler/compliance-contrast.ts +284 -0
  47. package/src/compiler/compliance-empty.ts +24 -0
  48. package/src/compiler/compliance-rgaa-content.ts +95 -0
  49. package/src/compiler/compliance-rgaa-criteria.ts +45 -0
  50. package/src/compiler/compliance-rgaa-pages.ts +140 -0
  51. package/src/compiler/compliance-rgaa.ts +19 -0
  52. package/src/compiler/compliance-third-party.ts +59 -0
  53. package/src/compiler/compliance-urls.ts +52 -0
  54. package/src/compiler/compliance.ts +70 -42
  55. package/src/compiler/cookie-inventory.ts +119 -0
  56. package/src/compiler/foreign-imports.ts +5 -3
  57. package/src/compiler/mistakes.ts +18 -9
  58. package/src/compiler/props-pattern.ts +211 -0
  59. package/src/compiler/props.ts +177 -346
  60. package/src/compiler/ssr-emit.ts +510 -0
  61. package/src/compiler/ssr-helpers.ts +170 -121
  62. package/src/compiler/ssr.ts +25 -440
  63. package/src/context.ts +14 -1
  64. package/src/dev/child.ts +1 -1
  65. package/src/dev/hot-islands.ts +71 -0
  66. package/src/dev/index.ts +31 -18
  67. package/src/dev/protocol.ts +1 -1
  68. package/src/dev/queue.ts +3 -2
  69. package/src/dev/reload.ts +1 -1
  70. package/src/dev/supervisor.ts +3 -1
  71. package/src/dev/watchers.ts +6 -2
  72. package/src/dom/action.ts +97 -14
  73. package/src/dom/extras.ts +2 -1
  74. package/src/dom/field-marks.ts +24 -0
  75. package/src/dom/hot.ts +9 -0
  76. package/src/dom/index.ts +25 -5
  77. package/src/dom/island-hot.ts +29 -0
  78. package/src/dom/island.ts +13 -2
  79. package/src/dom/prefetch.ts +132 -0
  80. package/src/dom/regions.ts +498 -0
  81. package/src/dom/swap.ts +245 -0
  82. package/src/dom/trusted.ts +22 -0
  83. package/src/dom/upload.ts +44 -0
  84. package/src/eco/declaration.ts +39 -40
  85. package/src/eco/index.ts +5 -5
  86. package/src/href.ts +31 -0
  87. package/src/index.ts +9 -3
  88. package/src/plugins/config.ts +1 -1
  89. package/src/plugins/context.ts +7 -1
  90. package/src/plugins/daily.ts +27 -0
  91. package/src/plugins/index.ts +3 -3
  92. package/src/plugins/order.ts +1 -1
  93. package/src/plugins/public.ts +8 -5
  94. package/src/plugins/services.ts +88 -14
  95. package/src/plugins/types.ts +120 -9
  96. package/src/reactivity/hmr.ts +90 -0
  97. package/src/reactivity/index.ts +38 -18
  98. package/src/reactivity/resource.ts +115 -0
  99. package/src/reactivity/seed.ts +39 -0
  100. package/src/reactivity/server-seed.ts +194 -0
  101. package/src/reactivity/store.ts +55 -1
  102. package/src/rgpd/draft.ts +171 -0
  103. package/src/rgpd/forms.ts +85 -0
  104. package/src/rgpd/index.ts +57 -0
  105. package/src/server/action-flash.ts +1 -0
  106. package/src/server/action-registry.ts +6 -8
  107. package/src/server/action.ts +51 -19
  108. package/src/server/app-secret.ts +14 -8
  109. package/src/server/cache-invalidation.ts +96 -0
  110. package/src/server/compress.ts +3 -1
  111. package/src/server/consent.ts +16 -2
  112. package/src/server/cookie-inventory.ts +78 -0
  113. package/src/server/cookies.ts +50 -0
  114. package/src/server/csp-report.ts +86 -0
  115. package/src/server/discard.ts +13 -0
  116. package/src/server/document.ts +2 -2
  117. package/src/server/env.ts +1 -1
  118. package/src/server/errors.ts +9 -2
  119. package/src/server/field-errors.ts +91 -0
  120. package/src/server/form-schema.ts +16 -11
  121. package/src/server/health.ts +33 -12
  122. package/src/server/http.ts +25 -10
  123. package/src/server/index.ts +101 -298
  124. package/src/server/loader.ts +1 -0
  125. package/src/server/page.ts +3 -9
  126. package/src/server/plugin-host.ts +26 -8
  127. package/src/server/public.ts +14 -3
  128. package/src/server/rate-limit.ts +39 -10
  129. package/src/server/region.ts +3 -0
  130. package/src/server/request-handler.ts +370 -0
  131. package/src/server/request-log.ts +94 -0
  132. package/src/server/route-cache.ts +41 -6
  133. package/src/server/route-input.ts +54 -0
  134. package/src/server/route-table.ts +35 -19
  135. package/src/server/routing.ts +12 -11
  136. package/src/server/sanitize-html.ts +1 -1
  137. package/src/server/security.ts +38 -8
  138. package/src/server/serve-handlers.ts +9 -5
  139. package/src/server/shared-store.ts +314 -0
  140. package/src/server/start.ts +12 -5
  141. package/src/server/static-dir.ts +14 -10
  142. package/src/server/stream.ts +2 -1
  143. package/src/server/surface.ts +39 -0
  144. package/src/server/webhook.ts +48 -0
  145. package/src/server/workers.ts +168 -0
  146. package/src/ssr/consent-banner.ts +20 -16
  147. package/src/ssr/consent-texts.ts +40 -0
  148. package/src/ssr/context.ts +26 -3
  149. package/src/ssr/cookie-table.ts +75 -0
  150. package/src/ssr/index.ts +23 -13
  151. package/src/ssr/navigation.ts +161 -14
  152. package/src/test/browser.ts +50 -22
  153. package/src/test/build-reuse.ts +70 -0
  154. package/src/test/index.ts +45 -6
  155. package/src/test/mount.ts +53 -0
  156. package/src/test/outside.ts +94 -0
  157. package/templates/_shared/AGENTS.md +1 -1
  158. package/templates/_shared/Dockerfile +22 -0
  159. package/templates/_shared/dockerignore +9 -0
  160. package/templates/_shared/gitignore +2 -0
  161. package/templates/app/.env.example +3 -1
  162. package/templates/app/compose.yaml +32 -0
  163. package/templates/app/db/migrations/001_notes.sql +7 -0
  164. package/templates/app/db/schema.ts +11 -0
  165. package/templates/app/package.json +1 -0
  166. package/templates/app/prunelle.config.ts +6 -0
  167. package/templates/app/src/actions/notes.ts +26 -0
  168. package/templates/app/src/auth.ts +4 -2
  169. package/templates/app/src/db.ts +5 -0
  170. package/templates/app/src/routes/dashboard/index.tsx +26 -1
  171. package/templates/app/src/routes/privacy.tsx +6 -2
  172. package/templates/app/tests/app.test.ts +14 -3
  173. package/templates/plugin/AGENTS.md +11 -0
  174. package/templates/plugin/CLAUDE.md +1 -0
  175. package/templates/plugin/README.md +27 -0
  176. package/templates/plugin/gitignore +2 -0
  177. package/templates/plugin/llms.txt +19 -0
  178. package/templates/plugin/package.json +33 -0
  179. package/templates/plugin/src/index.ts +40 -0
  180. package/templates/plugin/tests/fixture/prunelle.config.ts +4 -0
  181. package/templates/plugin/tests/fixture/src/routes/index.tsx +11 -0
  182. package/templates/plugin/tests/plugin.test.ts +42 -0
  183. package/templates/plugin/tsconfig.json +19 -0
  184. package/ts-plugin.cjs +3674 -2196
@@ -169,7 +169,7 @@ export function withCspHashes(
169
169
  return serializeCsp(parsed)
170
170
  }
171
171
 
172
- export const DEFAULT_CSP = "default-src 'self'; script-src 'self'; style-src 'self'; style-src-attr 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'"
172
+ export const DEFAULT_CSP = "default-src 'self'; script-src 'self'; style-src 'self'; style-src-attr 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'; require-trusted-types-for 'script'; trusted-types prunelle 'allow-duplicates'"
173
173
  export const DEFAULT_HSTS = 'max-age=31536000; includeSubDomains'
174
174
  export const DEFAULT_PERMISSIONS_POLICY = 'camera=(), microphone=(), geolocation=(), payment=(), usb=(), accelerometer=(), gyroscope=(), magnetometer=(), browsing-topics=()'
175
175
  export const DEFAULT_COOP = 'same-origin'
@@ -201,6 +201,8 @@ export interface KnownCspDirectives {
201
201
  'report-to'?: CspDirectiveValue | undefined
202
202
  'report-uri'?: CspDirectiveValue | undefined
203
203
  'upgrade-insecure-requests'?: CspDirectiveValue | undefined
204
+ 'require-trusted-types-for'?: CspDirectiveValue | undefined
205
+ 'trusted-types'?: CspDirectiveValue | undefined
204
206
  }
205
207
 
206
208
  export type CspDirectives = Readonly<KnownCspDirectives & Record<string, CspDirectiveValue | undefined>>
@@ -274,7 +276,7 @@ export function extendCsp(extra: CspDirectives, base = DEFAULT_CSP): string {
274
276
  }
275
277
 
276
278
  // Directives browsers ignore (and log an error for) when delivered via <meta http-equiv="Content-Security-Policy"> (W3C CSP3 §4.2.1).
277
- const META_CSP_IGNORED = new Set(['frame-ancestors', 'report-uri', 'sandbox'])
279
+ const META_CSP_IGNORED = new Set(['frame-ancestors', 'report-uri', 'report-to', 'sandbox'])
278
280
  const EXISTING_META_CSP_RE = /<meta\b[^>]*\bhttp-equiv\s*=\s*(?:"content-security-policy"|'content-security-policy'|content-security-policy\b)/i
279
281
  const META_CHARSET_RE = /<meta\b[^>]*\bcharset\s*=\s*[^>]*>/i
280
282
  const HEAD_OPEN_RE = /<head\b[^>]*>/i
@@ -315,6 +317,10 @@ export interface SecurityHeadersOptions {
315
317
  contentTypeOptions?: boolean | undefined
316
318
  permissionsPolicy?: string | false | undefined
317
319
  csp?: string | CspDirectives | false | undefined
320
+ /** `false` drops Trusted Types from the default CSP, so the browser lets any script write an HTML string into the page (`el.innerHTML = html`), an injected one included. Prunelle's own writes go through its `prunelle` policy either way; add an app's policy with `csp: { 'trusted-types': ['my-policy'] }`. */
321
+ trustedTypes?: boolean | undefined
322
+ /** `true` adds `report-uri` and `report-to` to the CSP and answers the browser's reports at `/_pru/csp-report`, handing each to `onError` with `source: 'csp'` (the error log without one). A static export has no endpoint, so it leaves them out. */
323
+ cspReports?: boolean | undefined
318
324
  hsts?: string | boolean | undefined
319
325
  /** `Cross-Origin-Opener-Policy` (default `same-origin`): another site's window cannot keep a handle on this one. `'same-origin-allow-popups'` keeps a payment or sign-in popup working. */
320
326
  crossOriginOpenerPolicy?: string | false | undefined
@@ -551,12 +557,34 @@ export function loopbackBindNotice(hostname: string, fromHost: boolean): string
551
557
  return `prunelle: the server listens on ${hostname} (${source}), which only this machine reaches: in a container or behind another host, set HOST=0.0.0.0 or pass --host so the published port answers.`
552
558
  }
553
559
 
554
- export function resolveCspPolicy(options: SecurityHeadersOptions | false | undefined): string | undefined {
560
+ /** `overHttps`: the app is known to be served over https, where `security.cspReports` can add `report-to`. */
561
+ export function resolveCspPolicy(options: SecurityHeadersOptions | false | undefined, overHttps = false): string | undefined {
555
562
  if (options === false || options?.csp === false)
556
563
  return undefined
557
- if (typeof options?.csp === 'object')
558
- return extendCsp(options.csp)
559
- return options?.csp ?? DEFAULT_CSP
564
+ const csp = typeof options?.csp === 'string' ? options.csp : withoutTrustedTypes(typeof options?.csp === 'object' ? extendCsp(options.csp) : DEFAULT_CSP, options)
565
+ if (options?.cspReports !== true)
566
+ return csp
567
+ // Over plain http Chromium sends nothing to a `report-to` endpoint and then ignores `report-uri` as well.
568
+ return `${csp}; report-uri ${CSP_REPORT_PATH}${overHttps ? `; report-to ${CSP_REPORT_GROUP}` : ''}`
569
+ }
570
+
571
+ const TRUSTED_TYPES_DIRECTIVES = new Set(['require-trusted-types-for', 'trusted-types'])
572
+
573
+ function withoutTrustedTypes(csp: string, options: SecurityHeadersOptions | undefined): string {
574
+ if (options?.trustedTypes !== false)
575
+ return csp
576
+ const parsed = parseCsp(csp)
577
+ parsed.order = parsed.order.filter(name => !TRUSTED_TYPES_DIRECTIVES.has(name))
578
+ return serializeCsp(parsed)
579
+ }
580
+
581
+ /** Where `security.cspReports` has the browser send its CSP violation reports. */
582
+ export const CSP_REPORT_PATH = '/_pru/csp-report'
583
+ const CSP_REPORT_GROUP = 'prunelle-csp'
584
+
585
+ /** The options a static export serves under: no server answers `/_pru/csp-report` there. */
586
+ export function withoutCspReports(options: SecurityHeadersOptions | false | undefined): SecurityHeadersOptions | false | undefined {
587
+ return options === false || options?.cspReports !== true ? options : { ...options, cspReports: false }
560
588
  }
561
589
 
562
590
  export function resolveHstsValue(options: SecurityHeadersOptions | false | undefined): string | undefined {
@@ -567,7 +595,7 @@ export function resolveHstsValue(options: SecurityHeadersOptions | false | undef
567
595
  return typeof options?.hsts === 'string' ? options.hsts : DEFAULT_HSTS
568
596
  }
569
597
 
570
- export function buildSecurityHeaderEntries(options: SecurityHeadersOptions | false | undefined): readonly [string, string][] {
598
+ export function buildSecurityHeaderEntries(options: SecurityHeadersOptions | false | undefined, overHttps = false): readonly [string, string][] {
571
599
  if (options === false)
572
600
  return []
573
601
  const opts = options ?? {}
@@ -584,8 +612,10 @@ export function buildSecurityHeaderEntries(options: SecurityHeadersOptions | fal
584
612
  entries.push(['cross-origin-opener-policy', opts.crossOriginOpenerPolicy ?? DEFAULT_COOP])
585
613
  if (opts.crossOriginResourcePolicy !== false)
586
614
  entries.push(['cross-origin-resource-policy', opts.crossOriginResourcePolicy ?? DEFAULT_CORP])
587
- const csp = resolveCspPolicy(opts)
615
+ const csp = resolveCspPolicy(opts, overHttps)
588
616
  if (csp !== undefined)
589
617
  entries.push(['content-security-policy', csp])
618
+ if (csp !== undefined && opts.cspReports === true && overHttps)
619
+ entries.push(['reporting-endpoints', `${CSP_REPORT_GROUP}="${CSP_REPORT_PATH}"`])
590
620
  return entries
591
621
  }
@@ -4,6 +4,7 @@ import type { createAssets, ServedFile } from './assets'
4
4
  import type { NotifyError } from './errors'
5
5
  import type { RequestIdResolver } from './health'
6
6
  import type { PrunelleServer } from './http'
7
+ import type { ObserveHandler } from './request-log'
7
8
  import type { RequestPath } from './request-path'
8
9
  import type { FastHandler } from './routing'
9
10
  import { ACTION_ERROR_COOKIE } from './action'
@@ -26,6 +27,8 @@ export interface ServeHandlerSources {
26
27
  notifyError: NotifyError
27
28
  serverError: () => Response
28
29
  fileGone: () => Response
30
+ /** Wraps every handler but the health probe's, when the access log or an `onRequestEnd` hook listens. */
31
+ observe?: ObserveHandler | undefined
29
32
  }
30
33
 
31
34
  export const isRead = (request: Request): boolean => request.method === 'GET' || request.method === 'HEAD'
@@ -36,7 +39,7 @@ export const hasActionErrorCookie = (request: Request): boolean => (request.head
36
39
  export const isPlainRead = (request: Request): boolean => isRead(request) && !hasActionErrorCookie(request) && !hasRegionHeader(request)
37
40
 
38
41
  export function serveHandlers(server: () => PrunelleServer | undefined, sources: ServeHandlerSources) {
39
- const { files, fastPrerenderedMap, fastStaticPages, pluginRouter, healthPath, healthHandler, resolveRequestId, runRequest, runFast, notifyError, serverError, fileGone } = sources
42
+ const { files, fastPrerenderedMap, fastStaticPages, pluginRouter, healthPath, healthHandler, resolveRequestId, runRequest, runFast, notifyError, serverError, fileGone, observe } = sources
40
43
  const ipOf = (req: Request) => server()?.requestIP(req)?.address
41
44
  const fetchReq = (req: Request) => runRequest(req, ipOf(req), seconds => server()?.timeout(req, seconds))
42
45
  // A file that fails to open answers here, where the request is known: gone since the build is a 404, anything else is reported with it.
@@ -55,14 +58,15 @@ export function serveHandlers(server: () => PrunelleServer | undefined, sources:
55
58
  }
56
59
 
57
60
  const routes: Record<string, (req: Request) => Response | Promise<Response>> = {}
58
- const registerServeRoute = (path: string, handler: (req: Request) => Response | Promise<Response>): void => {
61
+ const registerServeRoute = (path: string, handler: (req: Request) => Response | Promise<Response>, observed = true): void => {
59
62
  const key = toBunRouteKey(path)
60
63
  if (key !== undefined && !(key in routes))
61
- routes[key] = handler
64
+ routes[key] = observed && observe !== undefined ? observe(handler) : handler
62
65
  }
63
66
 
67
+ // A container probes its health every few seconds: logging each probe would bury the requests.
64
68
  if (healthPath !== undefined && healthHandler !== undefined)
65
- registerServeRoute(healthPath, req => healthHandler(req))
69
+ registerServeRoute(healthPath, req => healthHandler(req), false)
66
70
 
67
71
  for (const [path, asset] of files.assetMap)
68
72
  registerServeRoute(path, req => isRead(req) ? serveFile(req, asset) : fetchReq(req))
@@ -80,7 +84,7 @@ export function serveHandlers(server: () => PrunelleServer | undefined, sources:
80
84
 
81
85
  return {
82
86
  routes,
83
- fetch: fetchReq,
87
+ fetch: observe?.(fetchReq) ?? fetchReq,
84
88
  error(err: Error) {
85
89
  const fallbackReq = new Request('http://localhost/')
86
90
  const reqId = resolveRequestId?.(fallbackReq)
@@ -0,0 +1,314 @@
1
+ // The store every process of one app shares, named once by `store` in prunelle.config.ts: rate limits, and messages from one process to the others.
2
+
3
+ import type { SQL } from 'bun'
4
+ import { mkdirSync } from 'node:fs'
5
+ import { dirname, resolve } from 'node:path'
6
+ import { serviceKey } from '../plugins/services'
7
+
8
+ export interface SharedStore {
9
+ readonly kind: 'sqlite' | 'postgres'
10
+ /** The SQLite file, for a plugin that opens it itself (auth, jobs); `undefined` on Postgres. */
11
+ readonly file: string | undefined
12
+ readonly sql: SQL
13
+ /** Counts a hit of `key` unless `max` hits already fall within the window; returns 0, or the whole seconds until a hit would pass. */
14
+ hit(scope: string, key: string, max: number, windowMs: number): Promise<number>
15
+ /** The seconds `hit` would answer, counting nothing. */
16
+ peek(scope: string, key: string, max: number, windowMs: number): Promise<number>
17
+ /** Hands `payload` to the subscribers of `channel` in every other process, as they read it: the caller acts on it in its own process itself. */
18
+ publish(channel: string, payload: string): Promise<void>
19
+ /** Returns the unsubscribe. */
20
+ subscribe(channel: string, onMessage: (payload: string) => void): () => void
21
+ close(): Promise<void>
22
+ }
23
+
24
+ export const SHARED_STORE = serviceKey<SharedStore>('prunelle.store')
25
+
26
+ /** How often a SQLite store looks for another process's messages, while something subscribes. */
27
+ export const SQLITE_POLL_MS = 200
28
+ // A message committed late (a slow transaction, a clock a little behind) is still read if it lands within this of the newest one read.
29
+ const LOOKBACK_MS = 2000
30
+ const MESSAGE_TTL_MS = 60_000
31
+ const SWEEP_MS = 60_000
32
+ const START_RETRY_BASE_MS = 200
33
+ const START_RETRY_MAX_MS = 30_000
34
+ const NOTIFY_CHANNEL = 'prunelle_store'
35
+ const POSTGRES_RE = /^postgres(?:ql)?:\/\//i
36
+
37
+ /** `'data/app.db'`, `'sqlite:data/app.db'` or `'postgres://...'`, a path resolved against the app root. */
38
+ export function parseStoreSpec(spec: string, root: string): { kind: 'sqlite', file: string } | { kind: 'postgres', url: string } {
39
+ if (POSTGRES_RE.test(spec))
40
+ return { kind: 'postgres', url: spec }
41
+ const path = spec.replace(/^sqlite:(?:\/\/)?/i, '')
42
+ if (path.trim() === '' || path === ':memory:')
43
+ throw new Error(`prunelle: store is "${spec}", which no other process can open: name a SQLite file such as 'data/app.db', or a postgres:// URL.`)
44
+ return { kind: 'sqlite', file: resolve(root, path) }
45
+ }
46
+
47
+ const SQLITE_SCHEMA = [
48
+ 'pragma journal_mode = wal',
49
+ 'pragma busy_timeout = 5000',
50
+ 'create table if not exists prunelle_rate_hits (scope text not null, key text not null, at integer not null, expires integer not null)',
51
+ 'create table if not exists prunelle_messages (id integer primary key autoincrement, channel text not null, payload text not null, origin text not null, at integer not null)',
52
+ ]
53
+ const POSTGRES_SCHEMA = [
54
+ 'create table if not exists prunelle_rate_hits (scope text not null, key text not null, at bigint not null, expires bigint not null)',
55
+ 'create table if not exists prunelle_messages (id bigserial primary key, channel text not null, payload text not null, origin text not null, at bigint not null default (extract(epoch from clock_timestamp()) * 1000)::bigint)',
56
+ ]
57
+ const INDEXES = [
58
+ 'create index if not exists prunelle_rate_hits_key on prunelle_rate_hits (scope, key, at)',
59
+ 'create index if not exists prunelle_rate_hits_expires on prunelle_rate_hits (expires)',
60
+ 'create index if not exists prunelle_messages_at on prunelle_messages (at)',
61
+ ]
62
+
63
+ type Kind = SharedStore['kind']
64
+
65
+ // Logs a background task's failure once, and again only after it worked in between, so a store that stays down does not log every 200 ms.
66
+ function backgroundTask(what: string): (task: () => Promise<unknown>) => void {
67
+ let failing = false
68
+ return (task) => {
69
+ task().then(() => {
70
+ failing = false
71
+ }, (error: unknown) => {
72
+ if (!failing)
73
+ console.error(`prunelle: the shared store could not ${what}; it tries again.`, error)
74
+ failing = true
75
+ })
76
+ }
77
+ }
78
+
79
+ interface MessageRow { id: number | string, channel: string, payload: string, origin: string, at: number | string }
80
+
81
+ function rateCounter(sql: SQL, kind: Kind, prepare: () => Promise<void>): Pick<SharedStore, 'hit' | 'peek'> {
82
+ async function secondsUntilFree(scope: string, key: string, max: number, windowMs: number, now: number): Promise<number> {
83
+ const rows: { at: number | string }[] = await sql`select at from prunelle_rate_hits where scope = ${scope} and key = ${key} and at > ${now - windowMs} order by at desc limit ${max}`
84
+ return rows.length < max ? 0 : Math.max(1, Math.ceil((Number(rows[max - 1]!.at) + windowMs - now) / 1000))
85
+ }
86
+
87
+ return {
88
+ async hit(scope, key, max, windowMs) {
89
+ await prepare()
90
+ const now = Date.now()
91
+ // One statement, which SQLite's single writer runs alone; Postgres runs them side by side, so a lock on the key makes the count and the insert one step there.
92
+ const counted = async (tx: SQL): Promise<number> => {
93
+ const inserted = await tx`insert into prunelle_rate_hits (scope, key, at, expires) select ${scope}, ${key}, ${now}, ${now + windowMs} where (select count(*) from prunelle_rate_hits where scope = ${scope} and key = ${key} and at > ${now - windowMs}) < ${max}`
94
+ return inserted.count
95
+ }
96
+ const count = kind === 'sqlite'
97
+ ? await counted(sql)
98
+ : await sql.begin(async (tx) => {
99
+ await tx`select pg_advisory_xact_lock(hashtext(${`${scope}\n${key}`}))`
100
+ return counted(tx)
101
+ })
102
+ return count > 0 ? 0 : secondsUntilFree(scope, key, max, windowMs, now)
103
+ },
104
+ async peek(scope, key, max, windowMs) {
105
+ await prepare()
106
+ return secondsUntilFree(scope, key, max, windowMs, Date.now())
107
+ },
108
+ }
109
+ }
110
+
111
+ // Each process reads the rows the others insert: on a NOTIFY on Postgres, on a change of `PRAGMA data_version` on SQLite, and only while something subscribes.
112
+ function messageChannel(sql: SQL, kind: Kind, prepare: () => Promise<void>): Pick<SharedStore, 'publish' | 'subscribe'> & { stop: () => Promise<void> } {
113
+ const origin = crypto.randomUUID()
114
+ const listeners = new Map<string, Set<(payload: string) => void>>()
115
+ const seen = new Map<number, number>()
116
+ let since = 0
117
+ let reading: { stop: () => void } | undefined
118
+ let starting: Promise<{ stop: () => void }> | undefined
119
+ let retryTimer: ReturnType<typeof setTimeout> | undefined
120
+ let retryAttempt = 0
121
+ let startFailing = false
122
+ let draining: Promise<void> | undefined
123
+ let again = false
124
+ let closed = false
125
+ const inBackground = backgroundTask('read the messages of the other processes')
126
+
127
+ function deliver(channel: string, payload: string): void {
128
+ for (const onMessage of [...listeners.get(channel) ?? []])
129
+ onMessage(payload)
130
+ }
131
+
132
+ async function readNew(): Promise<void> {
133
+ const rows: MessageRow[] = await sql`select id, channel, payload, origin, at from prunelle_messages where at >= ${since - LOOKBACK_MS} order by id`
134
+ for (const row of rows) {
135
+ const id = Number(row.id)
136
+ const at = Number(row.at)
137
+ if (seen.has(id))
138
+ continue
139
+ seen.set(id, at)
140
+ since = Math.max(since, at)
141
+ if (row.origin !== origin)
142
+ deliver(row.channel, row.payload)
143
+ }
144
+ for (const [id, at] of seen) {
145
+ if (at < since - LOOKBACK_MS)
146
+ seen.delete(id)
147
+ }
148
+ }
149
+
150
+ // One read at a time; a signal during a read runs one more after it.
151
+ function drain(): Promise<void> {
152
+ if (draining !== undefined) {
153
+ again = true
154
+ return draining
155
+ }
156
+ draining = (async () => {
157
+ do {
158
+ again = false
159
+ await readNew()
160
+ } while (again && !closed)
161
+ })().finally(() => {
162
+ draining = undefined
163
+ })
164
+ return draining
165
+ }
166
+
167
+ async function dataVersion(): Promise<number> {
168
+ const [row] = await sql`pragma data_version` as [{ data_version: number }]
169
+ return row.data_version
170
+ }
171
+
172
+ async function startReading(): Promise<{ stop: () => void }> {
173
+ await prepare()
174
+ // Read before the newest message, so a commit landing in between still changes the version the poll compares.
175
+ let version = kind === 'sqlite' ? await dataVersion() : 0
176
+ // The messages of the lookback window were published before this subscriber, so they count as read.
177
+ const recent: Pick<MessageRow, 'id' | 'at'>[] = await sql`select id, at from prunelle_messages where at >= (select coalesce(max(at), 0) from prunelle_messages) - ${LOOKBACK_MS}`
178
+ seen.clear()
179
+ since = 0
180
+ for (const row of recent) {
181
+ seen.set(Number(row.id), Number(row.at))
182
+ since = Math.max(since, Number(row.at))
183
+ }
184
+ if (kind === 'postgres') {
185
+ const registration = await sql.listen(NOTIFY_CHANNEL, () => inBackground(drain))
186
+ return { stop: () => inBackground(async () => registration.unlisten()) }
187
+ }
188
+ const timer = setInterval(() => inBackground(async () => {
189
+ const current = await dataVersion()
190
+ if (current === version)
191
+ return
192
+ await drain()
193
+ version = current
194
+ }), SQLITE_POLL_MS)
195
+ timer.unref()
196
+ return { stop: () => clearInterval(timer) }
197
+ }
198
+
199
+ function clearRetry(): void {
200
+ if (retryTimer !== undefined) {
201
+ clearTimeout(retryTimer)
202
+ retryTimer = undefined
203
+ }
204
+ retryAttempt = 0
205
+ }
206
+
207
+ function ensureReading(): void {
208
+ if (reading !== undefined || starting !== undefined || retryTimer !== undefined || closed || listeners.size === 0)
209
+ return
210
+ starting = startReading()
211
+ void starting.then((handle) => {
212
+ starting = undefined
213
+ retryAttempt = 0
214
+ startFailing = false
215
+ if (listeners.size === 0 || closed)
216
+ handle.stop()
217
+ else
218
+ reading = handle
219
+ }, (error: unknown) => {
220
+ starting = undefined
221
+ if (!startFailing)
222
+ console.error('prunelle: the shared store could not start reading messages from other processes; it tries again.', error)
223
+ startFailing = true
224
+ if (closed || listeners.size === 0)
225
+ return
226
+ const delay = Math.min(START_RETRY_MAX_MS, START_RETRY_BASE_MS * 2 ** Math.min(retryAttempt++, 8))
227
+ retryTimer = setTimeout(() => {
228
+ retryTimer = undefined
229
+ ensureReading()
230
+ }, delay)
231
+ retryTimer.unref()
232
+ })
233
+ }
234
+
235
+ return {
236
+ async publish(channel, payload) {
237
+ await prepare()
238
+ if (kind === 'sqlite') {
239
+ await sql`insert into prunelle_messages (channel, payload, origin, at) values (${channel}, ${payload}, ${origin}, ${Date.now()})`
240
+ return
241
+ }
242
+ await sql`insert into prunelle_messages (channel, payload, origin) values (${channel}, ${payload}, ${origin})`
243
+ await sql.notify(NOTIFY_CHANNEL, '')
244
+ },
245
+ subscribe(channel, onMessage) {
246
+ let set = listeners.get(channel)
247
+ if (set === undefined)
248
+ listeners.set(channel, set = new Set())
249
+ set.add(onMessage)
250
+ ensureReading()
251
+ return () => {
252
+ set.delete(onMessage)
253
+ if (set.size === 0)
254
+ listeners.delete(channel)
255
+ if (listeners.size === 0) {
256
+ clearRetry()
257
+ reading?.stop()
258
+ reading = undefined
259
+ }
260
+ }
261
+ },
262
+ async stop() {
263
+ closed = true
264
+ clearRetry()
265
+ reading?.stop()
266
+ reading = undefined
267
+ listeners.clear()
268
+ await starting?.then(handle => handle.stop(), () => undefined)
269
+ },
270
+ }
271
+ }
272
+
273
+ export function openSharedStore(spec: string, root: string): SharedStore {
274
+ const parsed = parseStoreSpec(spec, root)
275
+ if (parsed.kind === 'sqlite')
276
+ mkdirSync(dirname(parsed.file), { recursive: true })
277
+ // Through `Bun.SQL`, not an import of it: an import loads Bun's SQL client in every server, a store or not (0.8 MiB).
278
+ const sql = parsed.kind === 'sqlite' ? new Bun.SQL({ adapter: 'sqlite', filename: parsed.file }) : new Bun.SQL(parsed.url)
279
+ let ready: Promise<void> | undefined
280
+ let sweeper: ReturnType<typeof setInterval> | undefined
281
+
282
+ // Two processes creating the tables at once on Postgres can race on its catalog: the loser finds them made on its second try.
283
+ async function createSchema(): Promise<void> {
284
+ for (const statement of [...parsed.kind === 'sqlite' ? SQLITE_SCHEMA : POSTGRES_SCHEMA, ...INDEXES])
285
+ await sql.unsafe(statement).catch(async () => sql.unsafe(statement))
286
+ const sweep = backgroundTask('delete its expired rate hits and messages')
287
+ sweeper = setInterval(() => sweep(async () => {
288
+ const now = Date.now()
289
+ await sql`delete from prunelle_rate_hits where expires < ${now}`
290
+ await sql`delete from prunelle_messages where at < ${now - MESSAGE_TTL_MS}`
291
+ }), SWEEP_MS)
292
+ sweeper.unref()
293
+ }
294
+
295
+ // A failed creation (Postgres not up yet at boot) is forgotten, so the next call tries again.
296
+ const prepare = (): Promise<void> => ready ??= createSchema().catch((err: unknown) => {
297
+ ready = undefined
298
+ throw err
299
+ })
300
+ const messages = messageChannel(sql, parsed.kind, prepare)
301
+ return {
302
+ kind: parsed.kind,
303
+ file: parsed.kind === 'sqlite' ? parsed.file : undefined,
304
+ sql,
305
+ ...rateCounter(sql, parsed.kind, prepare),
306
+ publish: messages.publish,
307
+ subscribe: messages.subscribe,
308
+ async close() {
309
+ clearInterval(sweeper)
310
+ await messages.stop()
311
+ await sql.close()
312
+ },
313
+ }
314
+ }
@@ -3,6 +3,7 @@
3
3
  import type { PrunelleApp, PrunelleServer } from './http'
4
4
  import { existsSync, readdirSync, watch } from 'node:fs'
5
5
  import { basename, dirname, join, relative } from 'node:path'
6
+ import { markHandled } from './discard'
6
7
  import { startBuiltApp } from './loader'
7
8
 
8
9
  /** How long a swap may leave the outDir missing before the server goes back to the build it had. */
@@ -12,6 +13,10 @@ export interface StartOptions {
12
13
  root: string
13
14
  port: number
14
15
  hostname: string
16
+ /** Shares the port with the other workers of a `prunelle start --workers`. */
17
+ reusePort?: boolean | undefined
18
+ /** Says nothing when a new build loads, the first worker saying it for the others; a build that fails to load is still logged. */
19
+ quietReload?: boolean | undefined
15
20
  }
16
21
 
17
22
  async function disposeApp(app: PrunelleApp): Promise<void> {
@@ -28,10 +33,11 @@ async function disposeApp(app: PrunelleApp): Promise<void> {
28
33
  export async function startServer(options: StartOptions): Promise<{ app: PrunelleApp, server: PrunelleServer }> {
29
34
  const first = await startBuiltApp({ root: options.root })
30
35
  let current = first.app
31
- const server = current.serve(options.port, options.hostname)
36
+ const server = current.serve(options.port, options.hostname, { reusePort: options.reusePort })
32
37
  const app: PrunelleApp = {
33
38
  handle: async (request, remoteIp, setIdleTimeout) => current.handle(request, remoteIp, setIdleTimeout),
34
39
  serve: () => server,
40
+ perProcessState: () => current.perProcessState?.() ?? [],
35
41
  closeStreams: async () => current.closeStreams?.(),
36
42
  dispose: async () => {
37
43
  watcher?.stop()
@@ -39,13 +45,13 @@ export async function startServer(options: StartOptions): Promise<{ app: Prunell
39
45
  },
40
46
  }
41
47
  const watcher = current.reloadInto !== undefined
42
- ? watchSwaps(first.outDir, first.entry === undefined, () => current, next => current = next, options.root, server)
48
+ ? watchSwaps(first.outDir, first.entry === undefined, () => current, next => current = next, options.root, server, options.quietReload !== true)
43
49
  : undefined
44
50
  return { app, server }
45
51
  }
46
52
 
47
53
  /** Watches the folder holding `outDir` for the rename a build's swap makes, then loads the new build and swaps its handlers in. */
48
- function watchSwaps(outDir: string, isStatic: boolean, current: () => PrunelleApp, setCurrent: (app: PrunelleApp) => void, root: string, server: PrunelleServer): { stop: () => void } {
54
+ function watchSwaps(outDir: string, isStatic: boolean, current: () => PrunelleApp, setCurrent: (app: PrunelleApp) => void, root: string, server: PrunelleServer, announce: boolean): { stop: () => void } {
49
55
  const name = basename(outDir)
50
56
  const shown = relative(root, outDir) || '.'
51
57
  // A `--static` export has no manifest: the folder being back with files in it is the sign.
@@ -61,7 +67,7 @@ function watchSwaps(outDir: string, isStatic: boolean, current: () => PrunelleAp
61
67
  if (held !== undefined || disposed)
62
68
  return
63
69
  const { promise, resolve, reject } = Promise.withResolvers<PrunelleApp>()
64
- void promise.catch(() => undefined)
70
+ markHandled(promise)
65
71
  held = { promise, resolve, reject }
66
72
  server.reload({
67
73
  routes: {},
@@ -98,7 +104,8 @@ function watchSwaps(outDir: string, isStatic: boolean, current: () => PrunelleAp
98
104
  return
99
105
  }
100
106
  setCurrent(loaded)
101
- console.log(`prunelle start: serving the new build in ${shown}/`)
107
+ if (announce)
108
+ console.log(`prunelle start: serving the new build in ${shown}/`)
102
109
  }
103
110
  catch (err) {
104
111
  console.error(`prunelle start: the build in ${shown}/ failed to load, so the previous one keeps answering: ${err instanceof Error ? err.message : String(err)}`)
@@ -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
  },