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
@@ -4,13 +4,18 @@ import type { BuildManifest } from '../build/index'
4
4
  import type { AppRuntimeContext } from '../plugins/context'
5
5
  import type { PrunellePlugin, MiddlewareOptions, PluginRouteOptions, ServerPluginAPI } from '../plugins/index'
6
6
  import type { HealthCheckEntry } from './health'
7
+ import type { RequestHook } from './request-log'
8
+ import type { NotifyError } from './errors'
7
9
  import type { EmbeddedServerConfig, Middleware, RequestContext } from './http'
8
10
 
9
11
  import type { TrustProxy } from './security'
10
12
  import { runWithAppContext } from '../plugins/context'
11
13
  import { enforceRequirements } from '../plugins/requires'
12
14
  import { normalizeConsentConfig, registerConsentRoute } from './consent'
15
+ import { registerCspReportRoute } from './csp-report'
16
+ import { appSurface } from './surface'
13
17
  import { assertRateLimit, createRateLimitStore, hitFor, tooManyRequests } from './rate-limit'
18
+ import { openSharedStore, SHARED_STORE } from './shared-store'
14
19
  import type { RequestPath } from './request-path'
15
20
  import type { RouteMatch } from './router'
16
21
  import { Router } from './router'
@@ -49,6 +54,7 @@ export interface ServerPluginHostOptions {
49
54
  trustProxy: TrustProxy
50
55
  trustedOriginsList: readonly string[]
51
56
  trustedOrigins: Set<string> | undefined
57
+ notifyError: NotifyError
52
58
  }
53
59
 
54
60
  function middlewareAppliesToPath(scope: ScopedMiddleware['scope'], path: string, kind: RequestKind): boolean {
@@ -124,11 +130,15 @@ function createMiddlewareLookup(scopedMiddlewares: readonly ScopedMiddleware[])
124
130
 
125
131
  export async function createServerPluginHost(options: ServerPluginHostOptions) {
126
132
  const { plugins, config, manifest, appCtx, trustedOrigins, trustProxy } = options
133
+ const shared = config.store === undefined ? undefined : openSharedStore(config.store, options.root)
134
+ if (shared !== undefined)
135
+ appCtx.provide(SHARED_STORE, shared)
127
136
  // The counters of every limited route and action of this server, dropped with it.
128
- const rateLimits = createRateLimitStore()
137
+ const rateLimits = createRateLimitStore({ shared })
129
138
  const scopedMiddlewares: ScopedMiddleware[] = []
130
139
  const healthChecks: HealthCheckEntry[] = []
131
140
  const shutdownHooks: { plugin: string, hook: () => void | Promise<void> }[] = []
141
+ const requestHooks: RequestHook[] = []
132
142
  const rewrites: ((pathname: string, ctx: RequestContext) => string | undefined)[] = []
133
143
  const router = new Router<Map<string, PluginRouteDef>>()
134
144
  const routeEntries = new Map<string, Map<string, PluginRouteDef>>()
@@ -164,9 +174,9 @@ export async function createServerPluginHost(options: ServerPluginHostOptions) {
164
174
  let limited = handler
165
175
  if (limit !== undefined) {
166
176
  assertRateLimit(limit, `${upperMethod} ${normPath} from "${pluginName}"`)
167
- const limiter = rateLimits.limiter(limit)
168
- limited = (ctx) => {
169
- const retryAfter = hitFor(limiter, limit, ctx)
177
+ const limiter = rateLimits.limiter(limit, `route:${upperMethod} ${normPath}`)
178
+ limited = async (ctx) => {
179
+ const retryAfter = await hitFor(limiter, limit, ctx)
170
180
  return retryAfter > 0 ? tooManyRequests(retryAfter) : handler(ctx)
171
181
  }
172
182
  }
@@ -194,6 +204,7 @@ export async function createServerPluginHost(options: ServerPluginHostOptions) {
194
204
  console.error(`prunelle: the onShutdown hook of ${plugin} threw; the other hooks still run.`, error)
195
205
  }
196
206
  }
207
+ await shared?.close()
197
208
  }
198
209
 
199
210
  const {
@@ -212,12 +223,15 @@ export async function createServerPluginHost(options: ServerPluginHostOptions) {
212
223
  const consentConfig = normalizeConsentConfig(config.consent)
213
224
  if (consentConfig !== undefined)
214
225
  registerConsentRoute(registerRouteFor('pru:consent'), consentConfig, trustedOrigins, trustProxy)
226
+ if (config.security !== false && config.security?.cspReports === true)
227
+ registerCspReportRoute(registerRouteFor('pru:csp-report'), options.notifyError)
215
228
 
216
229
  if (config.prerender !== true || config.static === true) {
217
230
  const production = !options.dev && (appCtx.nodeEnv ?? process.env.NODE_ENV) === 'production'
218
- await runWithAppContext(appCtx, () => enforceRequirements(plugins, { root: options.root, site: options.site, consentCategories: consentConfig?.categories ?? [] }, production))
231
+ await runWithAppContext(appCtx, () => enforceRequirements(plugins, { root: options.root, site: options.site, consentCategories: consentConfig?.categories ?? [], store: config.store }, production))
219
232
  }
220
233
  for (const plugin of plugins) {
234
+ let limiters = 0
221
235
  if (plugin.server !== undefined) {
222
236
  const pluginApi: ServerPluginAPI = {
223
237
  root: options.root,
@@ -233,9 +247,9 @@ export async function createServerPluginHost(options: ServerPluginHostOptions) {
233
247
  scopedMiddlewares.push({ mw, scope: middlewareOptions?.scope ?? 'all' })
234
248
  },
235
249
  route: registerRouteFor(plugin.name),
236
- rateLimiter(limit) {
250
+ rateLimiter(limit, name) {
237
251
  assertRateLimit(limit, `the rateLimiter of "${plugin.name}"`)
238
- return rateLimits.limiter(limit)
252
+ return rateLimits.limiter(limit, `${plugin.name}:${name ?? `#${++limiters}`}`)
239
253
  },
240
254
  rewrite(fn) {
241
255
  rewrites.push(fn)
@@ -251,6 +265,10 @@ export async function createServerPluginHost(options: ServerPluginHostOptions) {
251
265
  onShutdown(fn) {
252
266
  shutdownHooks.push({ plugin: plugin.name, hook: fn })
253
267
  },
268
+ onRequestEnd(fn) {
269
+ requestHooks.push({ owner: plugin.name, hook: fn })
270
+ },
271
+ surface: () => appSurface(manifest, config.modules),
254
272
  }
255
273
  await runWithAppContext(appCtx, () => plugin.server!(pluginApi))
256
274
  }
@@ -261,7 +279,7 @@ export async function createServerPluginHost(options: ServerPluginHostOptions) {
261
279
  throw error
262
280
  }
263
281
 
264
- return { router, rewrites, healthChecks, ...createMiddlewareLookup(scopedMiddlewares), rateLimits, dispose }
282
+ return { router, rewrites, healthChecks, requestHooks, ...createMiddlewareLookup(scopedMiddlewares), rateLimits, dispose }
265
283
  }
266
284
 
267
285
  export type ServerPluginHost = Awaited<ReturnType<typeof createServerPluginHost>>
@@ -1,18 +1,29 @@
1
1
  // `prunelle/server`: what an app's routes, actions and middleware use, and `createServer` to run a built app inside another program. Anything not listed here stays internal.
2
2
 
3
3
  export { action, getActionError } from './action'
4
+ export { invalidateCache } from './cache-invalidation'
5
+ export type { CacheTarget } from './cache-invalidation'
4
6
  export type { ActionContext, ActionErrorFlash, ActionOptions, ActionProtectOptions, ActionResult, ServerAction } from './action'
5
- export { safeEqual } from './app-secret'
7
+ export { deriveKey, safeEqual, signPayload, startSecret, verifyPayload } from './app-secret'
8
+ export { verifyWebhook } from './webhook'
9
+ export type { VerifyWebhookOptions, WebhookScheme } from './webhook'
6
10
  export type { ConsentConfig, RequestConsent } from './consent'
7
11
  export type { CookieOptions, Cookies } from './cookies'
8
12
  export { defineEnv, nodeEnv } from './env'
9
13
  export { notFound, wantsJson } from './http'
10
- export type { ExtractRouteParams, PrunelleApp, LayoutProps, LoaderData, LoaderFn, Middleware, NotFoundResult, PageProps, RequestContext, RouteContext, ServerOptions } from './http'
11
- export type { PrunelleLocals } from './index'
14
+ export type { ExtractRouteParams, PrunelleApp, LayoutProps, LoaderData, LoaderFn, Middleware, NotFoundResult, PageProps, RequestContext, RouteContext, RoutePattern, ServerOptions } from './http'
15
+
16
+ // Both declared here, the file `prunelle/server` resolves to: an augmentation reaches an interface only where it is declared, not through a re-export.
17
+ /** Request-scoped locals shared across middlewares, plugins, actions, layouts and pages; augment it with `declare module 'prunelle/server' { interface PrunelleLocals { ... } }`. */
18
+ export interface PrunelleLocals {}
19
+ /** The app's route patterns, filled in by the `prunelle-routes.d.ts` that `prunelle dev`, `build` and `check` write beside the routes folder. */
20
+ export interface PrunelleRoutes {}
12
21
  export { createServer } from './loader'
13
22
  export { createRateLimitStore, rateLimitAddress } from './rate-limit'
14
23
  export type { RateLimit, RateLimiter, RateLimitStore, RateLimitStoreOptions } from './rate-limit'
15
24
  export { readStringFields } from './request-body'
25
+ export { parseStoreSpec, SHARED_STORE } from './shared-store'
26
+ export type { SharedStore } from './shared-store'
16
27
  export { DEFAULT_CSP, extendCsp, getClientIp, isHttpsRequest, isTrustedOrigin, safeRedirect, verifyOrigin } from './security'
17
28
  export type { CspDirectives, SecurityHeadersOptions, TrustProxy } from './security'
18
29
  export { formatIssuePath, formatSchemaIssues, validateSchema, validateSchemaSync } from './standard-schema'
@@ -1,5 +1,6 @@
1
- // How often a client may call a plugin route or an action: a sliding window per key, in one store per server bounded in keys and hits.
1
+ // How often a client may call a plugin route or an action: a sliding window per key, in one store per server bounded in keys and hits, or in the app's shared store.
2
2
 
3
+ import type { SharedStore } from './shared-store'
3
4
  import { nodeEnv } from './env'
4
5
 
5
6
  export interface RateLimit<Ctx extends { ip?: string | undefined } = { ip?: string | undefined }> {
@@ -12,27 +13,31 @@ export interface RateLimit<Ctx extends { ip?: string | undefined } = { ip?: stri
12
13
  }
13
14
 
14
15
  export interface RateLimiter {
15
- /** Counts a request from `key` and returns 0; past the limit, counts nothing and returns the whole seconds until the next request would pass. */
16
- hit(key: string): number
16
+ /** Counts a request from `key` and returns 0; past the limit, counts nothing and returns the whole seconds until the next request would pass. A promise when the app shares a `store`. */
17
+ hit(key: string): number | Promise<number>
17
18
  /** The seconds `hit(key)` would answer, counting nothing: 0 while `key` is under the limit. */
18
- peek(key: string): number
19
+ peek(key: string): number | Promise<number>
19
20
  }
20
21
 
21
22
  export interface RateLimitStore {
22
- /** A limiter counting in this store, apart from every other limiter's keys. */
23
- limiter(limit: Pick<RateLimit, 'max' | 'windowMs'>): RateLimiter
23
+ /** A limiter counting in this store, apart from every other limiter's keys; a `name` counts in the shared store, when there is one, with every process giving that name. */
24
+ limiter(limit: Pick<RateLimit, 'max' | 'windowMs'>, name?: string): RateLimiter
24
25
  /** Drops the hits older than their window, and the keys left with none; returns how many keys went. */
25
26
  sweep(now?: number): number
26
27
  readonly size: number
28
+ /** How many limiters count in this process's memory rather than in the shared store. */
29
+ readonly limiters: number
27
30
  /** Stops the sweep timer. */
28
31
  close(): void
29
32
  }
30
33
 
31
34
  export interface RateLimitStoreOptions {
32
- /** Keys kept before the least recently used go (default: 10 000). */
35
+ /** Keys each limiter keeps before its least recently used go (default: 10 000). */
33
36
  maxKeys?: number | undefined
34
- /** Hits kept across all keys before the least recently used keys go (default: 1 000 000, about 8 MB). */
37
+ /** Hits each limiter keeps across its keys before its least recently used keys go (default: 1 000 000, about 8 MB per limiter). */
35
38
  maxHits?: number | undefined
39
+ /** Where named limiters count, so every process of the app shares their windows. */
40
+ shared?: SharedStore | undefined
36
41
  }
37
42
 
38
43
  interface Bucket {
@@ -43,6 +48,17 @@ interface Bucket {
43
48
 
44
49
  const SWEEP_MS = 60_000
45
50
 
51
+ // Every store not closed yet, so `--workers` can tell whether a limiter counts in this process's memory wherever the app made it.
52
+ const openStores = new Set<{ readonly limiters: number }>()
53
+
54
+ /** How many limiters of every open store count in this process's memory. */
55
+ export function memoryLimiters(): number {
56
+ let total = 0
57
+ for (const store of openStores)
58
+ total += store.limiters
59
+ return total
60
+ }
61
+
46
62
  /** Throws when a `rateLimit` option cannot count anything, naming where it was set. */
47
63
  export function assertRateLimit(limit: Pick<RateLimit, 'max' | 'windowMs'>, where: string): void {
48
64
  if (!Number.isInteger(limit.max) || limit.max < 1)
@@ -58,6 +74,11 @@ export function createRateLimitStore(options: RateLimitStoreOptions = {}): RateL
58
74
  const buckets: Bucket[] = []
59
75
  let totalKeys = 0
60
76
  let timer: ReturnType<typeof setInterval> | undefined
77
+ const self = {
78
+ get limiters() {
79
+ return buckets.length
80
+ },
81
+ }
61
82
 
62
83
  function secondsUntilFree(hits: readonly number[], max: number, windowMs: number, now: number): number {
63
84
  return Math.max(1, Math.ceil((hits[hits.length - max]! + windowMs - now) / 1000))
@@ -99,10 +120,14 @@ export function createRateLimitStore(options: RateLimitStoreOptions = {}): RateL
99
120
  }
100
121
 
101
122
  return {
102
- limiter(limit) {
123
+ limiter(limit, name) {
103
124
  const { max, windowMs } = limit
125
+ const shared = options.shared
126
+ if (shared !== undefined && name !== undefined)
127
+ return { hit: async key => shared.hit(name, key, max, windowMs), peek: async key => shared.peek(name, key, max, windowMs) }
104
128
  const bucket: Bucket = { entries: new Map(), windowMs, hitCount: 0 }
105
129
  buckets.push(bucket)
130
+ openStores.add(self)
106
131
  if (timer === undefined) {
107
132
  timer = setInterval(sweep, SWEEP_MS)
108
133
  timer.unref()
@@ -141,8 +166,12 @@ export function createRateLimitStore(options: RateLimitStoreOptions = {}): RateL
141
166
  get size() {
142
167
  return totalKeys
143
168
  },
169
+ get limiters() {
170
+ return buckets.length
171
+ },
144
172
  close() {
145
173
  clearInterval(timer)
174
+ openStores.delete(self)
146
175
  timer = undefined
147
176
  },
148
177
  }
@@ -218,6 +247,6 @@ export function rateLimitKey<Ctx extends { ip?: string | undefined }>(limit: Rat
218
247
  }
219
248
 
220
249
  /** Counts `ctx` against `limiter` under `rateLimitKey`; returns 0 or the seconds to wait. */
221
- export function hitFor<Ctx extends { ip?: string | undefined }>(limiter: RateLimiter, limit: RateLimit<Ctx>, ctx: Ctx): number {
250
+ export async function hitFor<Ctx extends { ip?: string | undefined }>(limiter: RateLimiter, limit: RateLimit<Ctx>, ctx: Ctx): Promise<number> {
222
251
  return limiter.hit(rateLimitKey(limit, ctx))
223
252
  }
@@ -64,6 +64,7 @@ export async function respondRegion(
64
64
  streamTimeout?: number,
65
65
  onError?: (error: unknown) => void,
66
66
  transformHtml?: (html: string) => Promise<string>,
67
+ buildId?: string,
67
68
  ): Promise<Response> {
68
69
  const path = parseRegionPath(request.headers.get(REGION_HEADER))
69
70
  if (path === undefined || path.length === 0)
@@ -92,5 +93,7 @@ export async function respondRegion(
92
93
  const headers: Record<string, string> = { ...htmlHeaders(rctx.hasIslands, false, true), 'vary': REGION_HEADER, [REGION_HEADER]: path.join('/') }
93
94
  if (title !== undefined)
94
95
  headers['x-pru-title'] = encodeURIComponent(title)
96
+ if (buildId !== undefined)
97
+ headers['x-pru-build'] = buildId
95
98
  return new Response(outHtml, { status: 200, headers })
96
99
  }
@@ -0,0 +1,370 @@
1
+ // The request path of the native server: static files, actions, prerendered pages, then plugin routes and compiled routes behind their middleware chains.
2
+
3
+ import type { ActionRegistry, RegisteredAction } from './action-registry'
4
+ import type { createAssets, ServedFile } from './assets'
5
+ import type { CompressionCache } from './compress'
6
+ import type { NormalizedConsentConfig } from './consent'
7
+ import type { CookieStore } from './cookies'
8
+ import type { createHtmlHeaders } from './document'
9
+ import type { createFallbackPages, NotifyError } from './errors'
10
+ import type { createHealthHandler, createRequestIdResolver, PhaseTiming } from './health'
11
+ import type { DeniedInfo, Middleware, RequestContext } from './http'
12
+ import type { ServerPluginHost } from './plugin-host'
13
+ import type { RequestPath } from './request-path'
14
+ import type { CompiledRoute, compileRouteTable, createCompiledRouteRenderer } from './route-table'
15
+ import type { OriginRefusal, TrustProxy } from './security'
16
+ import type { createStreamTracker } from './stream'
17
+ import { maybeCompressResponse } from './compress'
18
+ import { withPluginHtmlCsp } from './document'
19
+ import { devErrorResponse } from './errors'
20
+ import { acceptsHtml, enforceRequestBodyLimit, getDeniedInfo, makeRequestContext, runChain, wantsJson } from './http'
21
+ import { createTiming, formatServerTiming, runTimedChain, withRequestId } from './health'
22
+ import { stripHeadBody } from './page'
23
+ import { allowedPluginMethodsHeader, takesEncoded } from './plugin-host'
24
+ import { decodeRequestPath } from './request-path'
25
+ import { routeMethodHandler } from './route-table'
26
+ import { methodNotAllowed } from './routing'
27
+ import { isPlainRead, isRead } from './serve-handlers'
28
+ import { logOriginHint, verifyOrigin } from './security'
29
+
30
+ type Finish = (res: Response, request: Request, cookieStore?: CookieStore, requestId?: string, serverTiming?: string) => Response
31
+ type SetIdleTimeout = ((seconds: number) => void) | undefined
32
+ type RenderDenied = ReturnType<typeof createFallbackPages>['renderDenied']
33
+ type RenderError = ReturnType<typeof createFallbackPages>['renderError']
34
+ type PluginMatch = NonNullable<ReturnType<typeof matchPluginRoute>>
35
+ type PluginRouteDef = NonNullable<ReturnType<PluginMatch['data']['get']>>
36
+ type Timing = ReturnType<typeof createTiming>
37
+
38
+ const isEventStream = (res: Response): boolean => (res.headers.get('content-type') ?? '').toLowerCase().includes('text/event-stream')
39
+ const isApiHandler = (mod: CompiledRoute['mod'], method: string): boolean => routeMethodHandler(mod, method) !== undefined || (method === 'HEAD' && typeof mod.GET === 'function')
40
+ const badRequest = (): Response => new Response('Bad Request', { status: 400, headers: { 'content-type': 'text/plain; charset=utf-8' } })
41
+
42
+ export function maybeRenderDenied(
43
+ res: Response,
44
+ request: Request,
45
+ url: URL,
46
+ ctx: RequestContext,
47
+ renderDenied: (denied: DeniedInfo, url: URL, req: Request, ctx?: RequestContext, routeFile?: string) => Promise<Response>,
48
+ routeFile?: string,
49
+ isApi = false,
50
+ ): Response | Promise<Response> {
51
+ if (isApi)
52
+ return res
53
+ const denied = getDeniedInfo(res)
54
+ if (denied === undefined || !acceptsHtml(request))
55
+ return res
56
+ return renderDenied(denied, url, request, ctx, routeFile)
57
+ }
58
+
59
+ function matchPluginRoute(pluginRouter: ServerPluginHost['router'], requestPath: RequestPath, effective: RequestPath) {
60
+ const rawMatch = effective !== requestPath ? takesEncoded(pluginRouter.match(requestPath), requestPath) : undefined
61
+ return rawMatch ?? takesEncoded(pluginRouter.match(effective), effective)
62
+ }
63
+
64
+ function matchStaticOrPublic(
65
+ request: Request,
66
+ requestPath: RequestPath,
67
+ assetMap: ReadonlyMap<string, ServedFile>,
68
+ publicMap: ReadonlyMap<string, ServedFile>,
69
+ pluginRouter: ServerPluginHost['router'],
70
+ ): ServedFile | undefined {
71
+ const { staticPath } = requestPath
72
+ if (staticPath === undefined)
73
+ return undefined
74
+ const asset = assetMap.get(staticPath)
75
+ if (asset !== undefined)
76
+ return asset
77
+ const pub = publicMap.get(staticPath)
78
+ if (pub === undefined)
79
+ return undefined
80
+ const matchedPlugin = pluginRouter.match(requestPath)
81
+ const reqMethod = request.method.toUpperCase()
82
+ const shadowedByPlugin = matchedPlugin !== undefined
83
+ && (matchedPlugin.data.has(reqMethod) || (reqMethod === 'HEAD' && matchedPlugin.data.has('GET')) || matchedPlugin.data.has('ALL'))
84
+ return shadowedByPlugin ? undefined : pub
85
+ }
86
+
87
+ export function createRequestGuards(maxRequestBodySize: number, finish: Finish) {
88
+ const refuseCrossSite = (request: Request, check: OriginRefusal, cookieStore?: CookieStore, requestId?: string): Response => {
89
+ logOriginHint(check.hint)
90
+ return finish(Response.json({ ok: false, status: 403, error: check.reason }, { status: 403 }), request, cookieStore, requestId)
91
+ }
92
+
93
+ const checkBodyLimit = async (request: Request, bodyLimited: boolean, cookieStore?: CookieStore, requestId?: string): Promise<Request | Response> => {
94
+ if (bodyLimited)
95
+ return request
96
+ const bounded = await enforceRequestBodyLimit(request, maxRequestBodySize)
97
+ if (bounded.ok)
98
+ return bounded.request
99
+ const status = bounded.aborted ? 400 : 413
100
+ const message = bounded.aborted ? 'Bad Request' : 'Payload Too Large'
101
+ return finish(wantsJson(request)
102
+ ? Response.json({ ok: false, status, error: message }, { status })
103
+ : new Response(message, { status, headers: { 'content-type': 'text/plain; charset=utf-8' } }), request, cookieStore, requestId)
104
+ }
105
+ return { refuseCrossSite, checkBodyLimit }
106
+ }
107
+
108
+ export interface RequestHandlerDeps {
109
+ isDev: boolean
110
+ healthPath: string
111
+ healthHandler: ReturnType<typeof createHealthHandler>
112
+ resolveRequestId: ReturnType<typeof createRequestIdResolver>
113
+ finish: Finish
114
+ withHsts: (res: Response, request: Request) => Response
115
+ serverError: () => Response
116
+ assetMap: ReadonlyMap<string, ServedFile>
117
+ publicMap: ReadonlyMap<string, ServedFile>
118
+ serveFile: ReturnType<typeof createAssets>['serveFile']
119
+ pluginHost: ServerPluginHost
120
+ pluginMiddlewaresFor: (effectiveScopedPath: string, rawScopedPath: string) => readonly Middleware[]
121
+ actions: ActionRegistry
122
+ dispatchAction: (
123
+ registeredAction: RegisteredAction,
124
+ request: Request,
125
+ url: URL,
126
+ rawPathname: string,
127
+ remoteIp: string | undefined,
128
+ bodyLimited: boolean,
129
+ requestId: string,
130
+ existing?: { ctx: RequestContext, cookieStore: CookieStore },
131
+ ) => Promise<Response>
132
+ fastPrerenderedMap: ReadonlyMap<string, ServedFile>
133
+ fastStaticPages: ReturnType<typeof compileRouteTable>['fastStaticPages']
134
+ router: ReturnType<typeof compileRouteTable>['router']
135
+ trustProxy: TrustProxy
136
+ httpsSite: boolean
137
+ consent: NormalizedConsentConfig | undefined
138
+ trustedOrigins: Set<string> | undefined
139
+ refuseCrossSite: ReturnType<typeof createRequestGuards>['refuseCrossSite']
140
+ checkBodyLimit: ReturnType<typeof createRequestGuards>['checkBodyLimit']
141
+ streams: ReturnType<typeof createStreamTracker>
142
+ htmlHeaders: ReturnType<typeof createHtmlHeaders>
143
+ compressCache: CompressionCache | undefined
144
+ notifyError: NotifyError
145
+ renderError: RenderError
146
+ renderDenied: RenderDenied
147
+ renderNotFound: (cookieStore: CookieStore, url: URL, request: Request, ctx: RequestContext, effective: RequestPath, rawScopedPath: string, timing?: PhaseTiming) => Promise<Response>
148
+ renderCompiledRoute: ReturnType<typeof createCompiledRouteRenderer>
149
+ }
150
+
151
+ // The three ways a request that is neither a file nor an action ends: a plugin route, a plugin route's 405, and a compiled route.
152
+ function createRouteServers(deps: RequestHandlerDeps) {
153
+ const {
154
+ finish, pluginHost, pluginMiddlewaresFor, actions, refuseCrossSite, checkBodyLimit, streams, htmlHeaders, compressCache, notifyError, renderError,
155
+ renderDenied, renderCompiledRoute,
156
+ } = deps
157
+
158
+ // Custom plugin routes run behind path-matched plugin middlewares so ctx.locals is available without cross-scope leaks.
159
+ async function servePluginRoute(
160
+ request: Request,
161
+ url: URL,
162
+ ctx: RequestContext,
163
+ cookieStore: CookieStore,
164
+ pluginMatch: PluginMatch,
165
+ routeDef: PluginRouteDef,
166
+ isHeadFallback: boolean,
167
+ effectiveScopedPath: string,
168
+ scopedPath: string,
169
+ bodyLimited: boolean,
170
+ setIdleTimeout: SetIdleTimeout,
171
+ requestId: string,
172
+ timing: Timing,
173
+ ): Promise<Response> {
174
+ if (routeDef.csrf) {
175
+ const originCheck = verifyOrigin(request, routeDef.trustedOrigins, routeDef.trustProxy, url)
176
+ if (!originCheck.ok)
177
+ return refuseCrossSite(request, originCheck, cookieStore, requestId)
178
+ }
179
+ const checked = await checkBodyLimit(request, bodyLimited, cookieStore, requestId)
180
+ if (checked instanceof Response)
181
+ return checked
182
+ ctx.request = checked
183
+ ctx.params = pluginMatch.params
184
+ const pluginMws = pluginMiddlewaresFor(effectiveScopedPath, scopedPath)
185
+ try {
186
+ let res = await actions.run(ctx, () => runTimedChain(ctx, pluginMws, () => routeDef.handler(ctx), timing, runChain))
187
+ if (isHeadFallback)
188
+ res = stripHeadBody(res)
189
+ else if (isEventStream(res))
190
+ res = streams.track(res, setIdleTimeout)
191
+ return finish(await maybeCompressResponse(await withPluginHtmlCsp(res, htmlHeaders), ctx.request, compressCache), ctx.request, cookieStore, requestId, formatServerTiming(timing))
192
+ }
193
+ catch (error) {
194
+ notifyError(error, ctx.request, 'plugin', requestId)
195
+ return renderError(error, cookieStore, ctx.url, ctx.request, ctx)
196
+ }
197
+ }
198
+
199
+ // A plugin route matched the path but none of its methods the request's: the 405 still runs the plugin middlewares.
200
+ async function pluginMethodNotAllowed(
201
+ request: Request,
202
+ ctx: RequestContext,
203
+ cookieStore: CookieStore,
204
+ pluginMatch: PluginMatch,
205
+ effectiveScopedPath: string,
206
+ scopedPath: string,
207
+ requestId: string,
208
+ timing: Timing,
209
+ ): Promise<Response> {
210
+ ctx.params = pluginMatch.params
211
+ const allow = allowedPluginMethodsHeader(pluginMatch.data)
212
+ const pluginMws = pluginMiddlewaresFor(effectiveScopedPath, scopedPath)
213
+ try {
214
+ const res = await actions.run(ctx, () => runTimedChain(ctx, pluginMws, () => methodNotAllowed(allow), timing, runChain))
215
+ return finish(res, request, cookieStore, requestId, formatServerTiming(timing))
216
+ }
217
+ catch (error) {
218
+ notifyError(error, request, 'plugin', requestId)
219
+ return renderError(error, cookieStore, ctx.url, request, ctx)
220
+ }
221
+ }
222
+
223
+ async function serveCompiledRoute(
224
+ ctx: RequestContext,
225
+ cookieStore: CookieStore,
226
+ route: CompiledRoute,
227
+ method: string,
228
+ effectiveScopedPath: string,
229
+ scopedPath: string,
230
+ staticPath: string | undefined,
231
+ setIdleTimeout: SetIdleTimeout,
232
+ requestId: string,
233
+ timing: Timing,
234
+ ): Promise<Response> {
235
+ const routeMiddlewares = pluginHost.hasPathScopedMiddlewares && (route.dynamic || effectiveScopedPath !== scopedPath)
236
+ ? [...pluginMiddlewaresFor(effectiveScopedPath, scopedPath), ...route.dirMiddlewares]
237
+ : route.middlewares
238
+
239
+ try {
240
+ const rawRes = await actions.run(ctx, () => runTimedChain(ctx, routeMiddlewares, () => renderCompiledRoute(route, ctx, cookieStore, setIdleTimeout, staticPath, timing, routeMiddlewares), timing, runChain))
241
+ const handledRes = await maybeRenderDenied(rawRes, ctx.request, ctx.url, ctx, renderDenied, route.entry.file, isApiHandler(route.mod, method))
242
+ const res = isEventStream(handledRes) ? streams.track(handledRes, setIdleTimeout) : handledRes
243
+ // Compress uncompressed API/middleware responses after the middleware chain unwinds.
244
+ const finalRes = res.headers.has('content-encoding') ? res : await maybeCompressResponse(res, ctx.request, compressCache)
245
+ return finish(finalRes, ctx.request, cookieStore, requestId, formatServerTiming(timing))
246
+ }
247
+ catch (error) {
248
+ notifyError(error, ctx.request, 'route', requestId)
249
+ return renderError(error, cookieStore, ctx.url, ctx.request, ctx, route.entry.file)
250
+ }
251
+ }
252
+
253
+ return { servePluginRoute, pluginMethodNotAllowed, serveCompiledRoute }
254
+ }
255
+
256
+ /** The function every request goes through. Everything it needs is read once from `deps`: a request allocates only what its own work needs. */
257
+ export function createRequestHandler(deps: RequestHandlerDeps) {
258
+ const {
259
+ isDev, healthPath, healthHandler, resolveRequestId, finish, withHsts, serverError, assetMap, publicMap, serveFile, pluginHost, actions, dispatchAction,
260
+ fastPrerenderedMap, fastStaticPages, router, trustProxy, httpsSite, consent, trustedOrigins, refuseCrossSite, checkBodyLimit, notifyError, renderNotFound,
261
+ } = deps
262
+ const pluginRouter = pluginHost.router
263
+ const { servePluginRoute, pluginMethodNotAllowed, serveCompiledRoute } = createRouteServers(deps)
264
+
265
+ // `bodyLimited` is set under `serve()`, where Bun.serve already enforces maxRequestBodySize on every body, chunked ones included.
266
+ return async function handleInternal(request: Request, remoteIp?: string, setIdleTimeout?: (seconds: number) => void, bodyLimited = false): Promise<Response> {
267
+ const requestId = resolveRequestId(request)
268
+ try {
269
+ const url = new URL(request.url)
270
+ const rawPathname = url.pathname
271
+ const requestPath = decodeRequestPath(rawPathname)
272
+ if (requestPath === undefined)
273
+ return finish(badRequest(), request, undefined, requestId)
274
+ const { staticPath, scopedPath } = requestPath
275
+ if (staticPath === healthPath)
276
+ return healthHandler(request, requestId)
277
+ const read = isRead(request)
278
+
279
+ // 1. Static client assets, then public/ files (explicit plugin routes take precedence over public/ files)
280
+ if (read) {
281
+ const staticFile = matchStaticOrPublic(request, requestPath, assetMap, publicMap, pluginRouter)
282
+ if (staticFile !== undefined)
283
+ return withRequestId(await serveFile(request, staticFile), requestId)
284
+ }
285
+
286
+ // 2. Server actions (POST /_pru/action/<id>; non-POST runs applicable middlewares before 405)
287
+ const registeredAction = staticPath !== undefined ? actions.byUrl(staticPath) : undefined
288
+ if (registeredAction !== undefined)
289
+ return dispatchAction(registeredAction, request, url, rawPathname, remoteIp, bodyLimited, requestId)
290
+
291
+ // 3. Prerendered static HTML, then 4. the zero-overhead static route path
292
+ const plainRead = isPlainRead(request)
293
+ if (plainRead && staticPath !== undefined) {
294
+ const pre = fastPrerenderedMap.get(staticPath)
295
+ if (pre !== undefined)
296
+ return withRequestId(await serveFile(request, pre), requestId)
297
+ const fast = fastStaticPages.get(staticPath)
298
+ if (fast !== undefined)
299
+ return fast(request, remoteIp, url, requestId)
300
+ }
301
+
302
+ // 5. Full Router + Plugin Rewrites + Plugin Routes + Middleware + Streaming/Head/Error pipeline
303
+ const { ctx, cookieStore } = makeRequestContext(request, {}, { trustProxy, httpsSite, remoteIp, url, consent, requestId })
304
+ const timing = createTiming(isDev, request)
305
+
306
+ // Apply plugin URL rewrites (e.g. @prunellejs/i18n stripping /fr prefix and setting ctx.locals.locale)
307
+ let effectivePath = rawPathname
308
+ for (const rewrite of pluginHost.rewrites) {
309
+ const nextPath = rewrite(effectivePath, ctx)
310
+ if (nextPath !== undefined)
311
+ effectivePath = nextPath
312
+ }
313
+ let effective = requestPath
314
+ if (effectivePath !== rawPathname) {
315
+ const rewritten = decodeRequestPath(effectivePath)
316
+ if (rewritten === undefined)
317
+ return finish(badRequest(), request, cookieStore, requestId)
318
+ effective = rewritten
319
+ const rewrittenAction = rewritten.staticPath !== undefined ? actions.byUrl(rewritten.staticPath) : undefined
320
+ if (rewrittenAction !== undefined)
321
+ return dispatchAction(rewrittenAction, request, url, effectivePath, remoteIp, bodyLimited, requestId, { ctx, cookieStore })
322
+ }
323
+ const { scopedPath: effectiveScopedPath, staticPath: effectiveStaticPath } = effective
324
+
325
+ const method = request.method.toUpperCase()
326
+ const pluginMatch = matchPluginRoute(pluginRouter, requestPath, effective)
327
+ const directPluginDef = pluginMatch?.data.get(method) ?? pluginMatch?.data.get('ALL')
328
+ const headFallbackPluginDef = directPluginDef === undefined && method === 'HEAD' ? pluginMatch?.data.get('GET') : undefined
329
+ const routeDef = directPluginDef ?? headFallbackPluginDef
330
+ if (pluginMatch !== undefined && routeDef !== undefined)
331
+ return await servePluginRoute(request, url, ctx, cookieStore, pluginMatch, routeDef, headFallbackPluginDef !== undefined, effectiveScopedPath, scopedPath, bodyLimited, setIdleTimeout, requestId, timing)
332
+
333
+ // Localized/rewritten public/ links (e.g. /fr/logo.png -> /logo.png)
334
+ if (read && effectivePath !== rawPathname && effectiveStaticPath !== undefined) {
335
+ const pub = publicMap.get(effectiveStaticPath)
336
+ if (pub !== undefined)
337
+ return withRequestId(await serveFile(request, pub), requestId)
338
+ }
339
+
340
+ const matched = router.match(effective)
341
+ // Before any middleware: an unmatched path, a 405 and a route without a handler for the method are checked too, unless the route opts out.
342
+ if (matched?.data.mod.csrf !== false) {
343
+ const originCheck = verifyOrigin(request, trustedOrigins, trustProxy, url)
344
+ if (!originCheck.ok)
345
+ return refuseCrossSite(request, originCheck, cookieStore, requestId)
346
+ }
347
+ if (matched === undefined) {
348
+ if (pluginMatch !== undefined)
349
+ return await pluginMethodNotAllowed(request, ctx, cookieStore, pluginMatch, effectiveScopedPath, scopedPath, requestId, timing)
350
+ return renderNotFound(cookieStore, ctx.url, request, ctx, effective, scopedPath, timing)
351
+ }
352
+
353
+ ctx.params = matched.params
354
+ const route = matched.data
355
+
356
+ // Body limit for file-based API routes; the origin was checked above.
357
+ if (routeMethodHandler(route.mod, method) !== undefined) {
358
+ const checked = await checkBodyLimit(request, bodyLimited, cookieStore, requestId)
359
+ if (checked instanceof Response)
360
+ return checked
361
+ ctx.request = checked
362
+ }
363
+ return await serveCompiledRoute(ctx, cookieStore, route, method, effectiveScopedPath, scopedPath, staticPath, setIdleTimeout, requestId, timing)
364
+ }
365
+ catch (error) {
366
+ notifyError(error, request, 'route', requestId)
367
+ return withHsts(withRequestId(isDev ? devErrorResponse(error, request) : serverError(), requestId), request)
368
+ }
369
+ }
370
+ }