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
@@ -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
@@ -324,10 +330,33 @@ export interface SecurityHeadersOptions {
324
330
 
325
331
  const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS'])
326
332
 
327
- /** How many reverse proxies sit in front of the app: `true` is one, a number is that many, `false` trusts no forwarded header. */
328
- export type TrustProxy = boolean | number
333
+ /** How many reverse proxies sit in front of the app: `true` is one, a number is that many, `false` trusts no forwarded header. The server hands plugins a `ProxyTrust` once `site` is known. */
334
+ export type TrustProxy = boolean | number | ProxyTrust
329
335
 
330
- function proxyHops(trustProxy: TrustProxy): number {
336
+ /** `trustProxy` as the server resolves it with `site`: the trusted hops, and the only hosts an `X-Forwarded-Host` may name, since a proxy that sets `Host` alone passes the client's one through. */
337
+ export interface ProxyTrust {
338
+ readonly hops: number
339
+ readonly hosts: ReadonlySet<string>
340
+ }
341
+
342
+ /** `trustProxy` bound to the hosts of `site` and `trustedOrigins`; unchanged with no proxy or no `site`, as then any forwarded host is the proxy's word. */
343
+ export function resolveTrustProxy(trustProxy: TrustProxy, site: string | undefined, trustedOrigins: Iterable<string> = []): TrustProxy {
344
+ const hops = proxyHops(trustProxy)
345
+ const siteHost = site === undefined ? undefined : URL.parse(site)?.host
346
+ if (hops === 0 || !siteHost)
347
+ return trustProxy
348
+ const hosts = new Set([siteHost])
349
+ for (const origin of trustedOrigins) {
350
+ const host = URL.parse(origin)?.host
351
+ if (host)
352
+ hosts.add(host)
353
+ }
354
+ return { hops, hosts }
355
+ }
356
+
357
+ export function proxyHops(trustProxy: TrustProxy): number {
358
+ if (typeof trustProxy === 'object')
359
+ return trustProxy.hops
331
360
  if (trustProxy === true)
332
361
  return 1
333
362
  if (trustProxy === false || !Number.isFinite(trustProxy))
@@ -370,16 +399,17 @@ function forwardedOrigin(request: Request, trustProxy: TrustProxy, requestUrl?:
370
399
  const proto = forwardedValue(request, 'x-forwarded-proto', trustProxy)?.toLowerCase()
371
400
  if (proto !== 'http' && proto !== 'https')
372
401
  return undefined
373
- const host = forwardedValue(request, 'x-forwarded-host', trustProxy) || request.headers.get('host')?.trim() || (requestUrl ?? new URL(request.url)).host
402
+ const forwarded = originOf(proto, forwardedValue(request, 'x-forwarded-host', trustProxy))
403
+ if (forwarded !== undefined && (typeof trustProxy !== 'object' || trustProxy.hosts.has(new URL(forwarded).host)))
404
+ return forwarded
405
+ return originOf(proto, request.headers.get('host')?.trim() || (requestUrl ?? new URL(request.url)).host)
406
+ }
407
+
408
+ function originOf(proto: string, host: string | undefined): string | undefined {
374
409
  if (!host)
375
410
  return undefined
376
- try {
377
- const origin = new URL(`${proto}://${host}`).origin
378
- return origin === 'null' ? undefined : origin
379
- }
380
- catch {
381
- return undefined
382
- }
411
+ const origin = URL.parse(`${proto}://${host}`)?.origin
412
+ return origin === undefined || origin === 'null' ? undefined : origin
383
413
  }
384
414
 
385
415
  /** Returns true when the request arrived over HTTPS (directly, or via X-Forwarded-Proto when `trustProxy` is true). */
@@ -508,8 +538,15 @@ export function verifyOrigin(
508
538
  const fetchSite = request.headers.get('sec-fetch-site')
509
539
  if (fetchSite !== null && fetchSite !== 'same-origin' && fetchSite !== 'none')
510
540
  return { ok: false, reason: `Cross-site request blocked: sec-fetch-site=${fetchSite}` }
541
+ if (fetchSite !== null || !request.headers.has('cookie'))
542
+ return { ok: true }
511
543
 
512
- return { ok: true }
544
+ // A browser too old to send Origin or Sec-Fetch-Site still sends the session cookie: only a same-site Referer vouches for it.
545
+ const referer = request.headers.get('referer')
546
+ const refererOrigin = referer === null ? undefined : URL.parse(referer)?.origin
547
+ if (refererOrigin !== undefined && isTrustedOrigin(refererOrigin, request, trustedOrigins, trustProxy, requestUrl))
548
+ return { ok: true }
549
+ return { ok: false, reason: referer === null ? 'Cross-site request blocked: a cookie came with no Origin, Sec-Fetch-Site or Referer' : `Cross-site request blocked: untrusted referer ${refererOrigin ?? referer}` }
513
550
  }
514
551
 
515
552
  /** The notice a production server prints when it listens on loopback only, which a container's published port or another machine cannot reach; undefined otherwise. */
@@ -520,12 +557,34 @@ export function loopbackBindNotice(hostname: string, fromHost: boolean): string
520
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.`
521
558
  }
522
559
 
523
- 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 {
524
562
  if (options === false || options?.csp === false)
525
563
  return undefined
526
- if (typeof options?.csp === 'object')
527
- return extendCsp(options.csp)
528
- 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 }
529
588
  }
530
589
 
531
590
  export function resolveHstsValue(options: SecurityHeadersOptions | false | undefined): string | undefined {
@@ -536,7 +595,7 @@ export function resolveHstsValue(options: SecurityHeadersOptions | false | undef
536
595
  return typeof options?.hsts === 'string' ? options.hsts : DEFAULT_HSTS
537
596
  }
538
597
 
539
- export function buildSecurityHeaderEntries(options: SecurityHeadersOptions | false | undefined): readonly [string, string][] {
598
+ export function buildSecurityHeaderEntries(options: SecurityHeadersOptions | false | undefined, overHttps = false): readonly [string, string][] {
540
599
  if (options === false)
541
600
  return []
542
601
  const opts = options ?? {}
@@ -553,8 +612,10 @@ export function buildSecurityHeaderEntries(options: SecurityHeadersOptions | fal
553
612
  entries.push(['cross-origin-opener-policy', opts.crossOriginOpenerPolicy ?? DEFAULT_COOP])
554
613
  if (opts.crossOriginResourcePolicy !== false)
555
614
  entries.push(['cross-origin-resource-policy', opts.crossOriginResourcePolicy ?? DEFAULT_CORP])
556
- const csp = resolveCspPolicy(opts)
615
+ const csp = resolveCspPolicy(opts, overHttps)
557
616
  if (csp !== undefined)
558
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}"`])
559
620
  return entries
560
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)}`)