prunelle 0.1.1 → 0.5.1

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 (88) hide show
  1. package/llms.txt +23 -19
  2. package/package.json +8 -2
  3. package/src/a11y/declaration.ts +335 -0
  4. package/src/a11y/index.ts +446 -0
  5. package/src/a11y/rgaa-map.ts +184 -0
  6. package/src/attrs.ts +11 -3
  7. package/src/build/bundle.ts +3 -2
  8. package/src/build/client-entries.ts +3 -2
  9. package/src/build/client-plugin.ts +8 -4
  10. package/src/build/client-prune.ts +11 -2
  11. package/src/build/compile.ts +2 -1
  12. package/src/build/ecoindex.ts +229 -0
  13. package/src/build/index.ts +121 -44
  14. package/src/build/manifest.ts +66 -5
  15. package/src/build/output.ts +2 -2
  16. package/src/build/plugin-host.ts +91 -33
  17. package/src/build/precompress.ts +15 -2
  18. package/src/build/prerender.ts +2 -2
  19. package/src/build/report.ts +23 -2
  20. package/src/build/resolve.ts +4 -3
  21. package/src/build/routes.ts +175 -10
  22. package/src/build/static.ts +71 -17
  23. package/src/build/status-pages.ts +127 -0
  24. package/src/build/style-bundles.ts +338 -0
  25. package/src/cli/check-forms.ts +654 -0
  26. package/src/cli/check-links.ts +619 -0
  27. package/src/cli/check.ts +52 -5
  28. package/src/cli/commands.ts +86 -4
  29. package/src/cli/docs.ts +402 -0
  30. package/src/cli/inspect.ts +31 -2
  31. package/src/cli/mcp-tools.ts +480 -0
  32. package/src/cli/mcp.ts +205 -0
  33. package/src/cli/new.ts +2 -2
  34. package/src/cli/render.ts +261 -0
  35. package/src/cli/upgrade-names.ts +73 -13
  36. package/src/cli/upgrade.ts +137 -16
  37. package/src/compiler/analyze.ts +17 -3
  38. package/src/compiler/cacheability.ts +592 -0
  39. package/src/compiler/compliance-rgaa.ts +502 -0
  40. package/src/compiler/compliance.ts +120 -221
  41. package/src/compiler/dev-source.ts +87 -0
  42. package/src/compiler/dom.ts +7 -7
  43. package/src/compiler/ssr.ts +135 -37
  44. package/src/dev/error-log.ts +151 -0
  45. package/src/dev/index.ts +60 -29
  46. package/src/dev/open-editor.ts +204 -0
  47. package/src/dev/reload.ts +5 -3
  48. package/src/dev/supervisor.ts +3 -0
  49. package/src/dom/action.ts +4 -1
  50. package/src/dom/island.ts +11 -10
  51. package/src/plugins/config.ts +4 -4
  52. package/src/plugins/index.ts +2 -2
  53. package/src/plugins/public.ts +5 -2
  54. package/src/plugins/services.ts +62 -0
  55. package/src/plugins/types.ts +32 -0
  56. package/src/server/action-protect.ts +198 -0
  57. package/src/server/action-registry.ts +1 -1
  58. package/src/server/action.ts +82 -27
  59. package/src/server/errors.ts +291 -62
  60. package/src/server/form-schema.ts +343 -0
  61. package/src/server/health.ts +244 -0
  62. package/src/server/http.ts +86 -19
  63. package/src/server/index.ts +158 -219
  64. package/src/server/param-matchers.ts +112 -0
  65. package/src/server/plugin-host.ts +40 -14
  66. package/src/server/public.ts +3 -3
  67. package/src/server/rate-limit.ts +58 -35
  68. package/src/server/request-body.ts +1 -1
  69. package/src/server/route-cache.ts +365 -0
  70. package/src/server/route-table.ts +302 -6
  71. package/src/server/router.ts +125 -40
  72. package/src/server/routing.ts +187 -61
  73. package/src/server/security.ts +208 -32
  74. package/src/server/serve-handlers.ts +21 -7
  75. package/src/ssr/context.ts +49 -0
  76. package/src/ssr/index.ts +120 -1
  77. package/src/test/browser.ts +6 -0
  78. package/src/test/index.ts +17 -3
  79. package/src/ts-plugin/diagnostics.ts +378 -0
  80. package/src/ts-plugin/fixes.ts +364 -0
  81. package/src/ts-plugin/index.ts +194 -0
  82. package/templates/_shared/AGENTS.md +2 -2
  83. package/templates/_shared/mcp.json +11 -0
  84. package/templates/_shared/src/routes/legal.tsx +5 -0
  85. package/templates/_shared/tsconfig.json +5 -0
  86. package/templates/blog/prunelle.config.ts +1 -1
  87. package/templates/blog/src/routes/index.tsx +4 -0
  88. package/ts-plugin.cjs +4277 -0
@@ -0,0 +1,112 @@
1
+ // Route parameter matchers (built-in `integer`, `uuid`, `slug` and app-defined `src/params/<name>.ts`) and shared route-pattern segment parsing.
2
+
3
+ export type ParamMatcher = (value: string) => boolean
4
+ export type ParamMatcherMap = Readonly<Record<string, ParamMatcher>>
5
+
6
+ const INTEGER_RE = /^\d+$/
7
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
8
+ const SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
9
+
10
+ export const BUILTIN_PARAM_MATCHERS: ParamMatcherMap = {
11
+ integer: value => INTEGER_RE.test(value),
12
+ uuid: value => UUID_RE.test(value),
13
+ slug: value => SLUG_RE.test(value),
14
+ }
15
+
16
+ export const BUILTIN_PARAM_MATCHER_NAMES = ['integer', 'uuid', 'slug'] as const
17
+
18
+ export function isBuiltinMatcher(name: string): boolean {
19
+ return Object.hasOwn(BUILTIN_PARAM_MATCHERS, name)
20
+ }
21
+
22
+ /** Extracts a matcher function from an app param matcher module (`export function match` or `export default`). */
23
+ export function extractMatcherFn(mod: unknown): ParamMatcher | undefined {
24
+ if (typeof mod === 'function')
25
+ return mod as ParamMatcher
26
+ if (mod !== null && typeof mod === 'object') {
27
+ const rec = mod as Record<string, unknown>
28
+ if (typeof rec.match === 'function')
29
+ return rec.match as ParamMatcher
30
+ if (typeof rec.default === 'function')
31
+ return rec.default as ParamMatcher
32
+ }
33
+ return undefined
34
+ }
35
+
36
+ /** Merges built-in matchers with app matchers listed in the build manifest. */
37
+ export function resolveParamMatchers(
38
+ manifestMatchers: Readonly<Record<string, string>> | undefined,
39
+ modules: Readonly<Record<string, unknown>>,
40
+ ): ParamMatcherMap {
41
+ if (manifestMatchers === undefined)
42
+ return BUILTIN_PARAM_MATCHERS
43
+ const merged: Record<string, ParamMatcher> = { ...BUILTIN_PARAM_MATCHERS }
44
+ for (const [name, modKey] of Object.entries(manifestMatchers)) {
45
+ const fn = extractMatcherFn(modules[modKey])
46
+ if (fn !== undefined)
47
+ merged[name] = fn
48
+ }
49
+ return merged
50
+ }
51
+
52
+ export interface ParsedPatternSegment {
53
+ kind: 'static' | 'param' | 'optional' | 'catchall'
54
+ /** Exact literal for static, parameter name for param/optional/catchall. */
55
+ value: string
56
+ matcherName?: string | undefined
57
+ }
58
+
59
+ function splitNameAndMatcher(spec: string, fallbackName?: string): { name: string, matcherName?: string | undefined } {
60
+ const eq = spec.indexOf('=')
61
+ if (eq === -1)
62
+ return { name: spec || fallbackName || '' }
63
+ const name = spec.slice(0, eq) || fallbackName || ''
64
+ const matcherName = spec.slice(eq + 1)
65
+ return matcherName.length > 0 ? { name, matcherName } : { name }
66
+ }
67
+
68
+ /** Parses one segment of a compiled route pattern (`about`, `:id`, `:id=integer`, `:lang?`, `:page=integer?`, `*rest`, `*path=slug`). */
69
+ export function parsePatternSegment(seg: string): ParsedPatternSegment {
70
+ if (seg.startsWith('*')) {
71
+ const { name, matcherName } = splitNameAndMatcher(seg.slice(1), 'rest')
72
+ return { kind: 'catchall', value: name, matcherName }
73
+ }
74
+ if (seg.startsWith(':')) {
75
+ const body = seg.slice(1)
76
+ const optional = body.endsWith('?')
77
+ const spec = optional ? body.slice(0, -1) : body
78
+ const { name, matcherName } = splitNameAndMatcher(spec)
79
+ return { kind: optional ? 'optional' : 'param', value: name, matcherName }
80
+ }
81
+ return { kind: 'static', value: seg }
82
+ }
83
+
84
+ /** Lists every param matcher reference in a compiled route pattern (e.g. `'/users/:id=integer'` -> `[{ param: 'id', matcher: 'integer' }]`). */
85
+ export function extractPatternMatchers(routePath: string): { param: string, matcher: string }[] {
86
+ const result: { param: string, matcher: string }[] = []
87
+ if (!routePath.includes('='))
88
+ return result
89
+ for (const seg of routePath.split('/')) {
90
+ if (seg === '')
91
+ continue
92
+ const parsed = parsePatternSegment(seg)
93
+ if (parsed.matcherName !== undefined)
94
+ result.push({ param: parsed.value, matcher: parsed.matcherName })
95
+ }
96
+ return result
97
+ }
98
+
99
+ /** Lists optional parameter names in a compiled route pattern (e.g. `'/:lang?/about'` -> `['lang']`). */
100
+ export function extractOptionalParams(routePath: string): string[] {
101
+ const result: string[] = []
102
+ if (!routePath.includes('?'))
103
+ return result
104
+ for (const seg of routePath.split('/')) {
105
+ if (seg === '')
106
+ continue
107
+ const parsed = parsePatternSegment(seg)
108
+ if (parsed.kind === 'optional')
109
+ result.push(parsed.value)
110
+ }
111
+ return result
112
+ }
@@ -3,6 +3,7 @@
3
3
  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
+ import type { HealthCheckEntry } from './health'
6
7
  import type { EmbeddedServerConfig, Middleware, RequestContext } from './http'
7
8
 
8
9
  import type { TrustProxy } from './security'
@@ -10,6 +11,8 @@ import { runWithAppContext } from '../plugins/context'
10
11
  import { enforceRequirements } from '../plugins/requires'
11
12
  import { normalizeConsentConfig, registerConsentRoute } from './consent'
12
13
  import { assertRateLimit, createRateLimitStore, hitFor, tooManyRequests } from './rate-limit'
14
+ import type { RequestPath } from './request-path'
15
+ import type { RouteMatch } from './router'
13
16
  import { Router } from './router'
14
17
 
15
18
  export interface PluginRouteDef {
@@ -18,6 +21,8 @@ export interface PluginRouteDef {
18
21
  csrf: boolean
19
22
  trustedOrigins: Set<string> | undefined
20
23
  trustProxy: TrustProxy
24
+ /** The catch-all takes an encoded separator for this method (`PluginRouteOptions.encodedSlashes`). */
25
+ encodedSlashes: boolean
21
26
  }
22
27
 
23
28
  interface ScopedMiddleware {
@@ -59,6 +64,14 @@ function middlewareAppliesToPath(scope: ScopedMiddleware['scope'], path: string,
59
64
  return normPath === normScope || normPath.startsWith(`${normScope}/`)
60
65
  }
61
66
 
67
+ /** The methods of `match` that may answer `path`: for a path with an encoded separator, only those that set `encodedSlashes`; none left is no match. */
68
+ export function takesEncoded(match: RouteMatch<Map<string, PluginRouteDef>> | undefined, path: RequestPath): RouteMatch<Map<string, PluginRouteDef>> | undefined {
69
+ if (match === undefined || path.encoded === undefined || path.encoded.size === 0)
70
+ return match
71
+ const data = new Map([...match.data].filter(([, def]) => def.encodedSlashes))
72
+ return data.size === 0 ? undefined : { data, params: match.params }
73
+ }
74
+
62
75
  export function allowedPluginMethodsHeader(methods: ReadonlyMap<string, PluginRouteDef>): string {
63
76
  const allowed = new Set<string>()
64
77
  for (const m of methods.keys()) {
@@ -71,11 +84,25 @@ export function allowedPluginMethodsHeader(methods: ReadonlyMap<string, PluginRo
71
84
  return [...allowed].join(', ')
72
85
  }
73
86
 
87
+ function assertRouteFree(pluginName: string, upperMethod: string, normPath: string, byMethod: ReadonlyMap<string, PluginRouteDef>): void {
88
+ const directConflict = byMethod.get(upperMethod)
89
+ if (directConflict !== undefined)
90
+ throw new Error(`prunelle: plugin "${pluginName}" registered ${upperMethod} ${normPath}, which collides with "${directConflict.plugin}". Mount one of the plugins on a different path.`)
91
+ if (upperMethod === 'ALL' && byMethod.size > 0) {
92
+ const [existingMethod, existingDef] = byMethod.entries().next().value!
93
+ throw new Error(`prunelle: plugin "${pluginName}" registered ALL ${normPath}, which collides with ${existingMethod} ${normPath} from "${existingDef.plugin}". Mount one of the plugins on a different path.`)
94
+ }
95
+ const allConflict = byMethod.get('ALL')
96
+ if (allConflict !== undefined)
97
+ throw new Error(`prunelle: plugin "${pluginName}" registered ${upperMethod} ${normPath}, which collides with ALL ${normPath} from "${allConflict.plugin}". Mount one of the plugins on a different path.`)
98
+ }
99
+
74
100
  export async function createServerPluginHost(options: ServerPluginHostOptions) {
75
101
  const { plugins, config, manifest, appCtx, trustedOrigins, trustProxy } = options
76
102
  // The counters of every limited route and action of this server, dropped with it.
77
103
  const rateLimits = createRateLimitStore()
78
104
  const scopedMiddlewares: ScopedMiddleware[] = []
105
+ const healthChecks: HealthCheckEntry[] = []
79
106
  const shutdownHooks: { plugin: string, hook: () => void | Promise<void> }[] = []
80
107
  const rewrites: ((pathname: string, ctx: RequestContext) => string | undefined)[] = []
81
108
  const router = new Router<Map<string, PluginRouteDef>>()
@@ -89,25 +116,20 @@ export async function createServerPluginHost(options: ServerPluginHostOptions) {
89
116
  ): void => {
90
117
  const upperMethod = method.toUpperCase()
91
118
  const normPath = path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path
119
+ const encodedSlashes = routeOptions?.encodedSlashes === true
120
+ if (encodedSlashes && !normPath.split('/').some(seg => seg.startsWith('*')))
121
+ throw new Error(`prunelle: plugin "${pluginName}" set encodedSlashes on ${upperMethod} ${normPath}, which has no catch-all: only a \`*name\` segment takes an encoded /, so end the path with one, or drop the option.`)
92
122
  let byMethod = routeEntries.get(normPath)
93
123
  if (byMethod === undefined) {
94
124
  byMethod = new Map()
95
125
  routeEntries.set(normPath, byMethod)
96
- router.add(normPath, byMethod)
126
+ router.add(normPath, byMethod, { encodedSlashes })
97
127
  }
98
128
  else {
99
- const directConflict = byMethod.get(upperMethod)
100
- if (directConflict !== undefined) {
101
- throw new Error(`prunelle: plugin "${pluginName}" registered ${upperMethod} ${normPath}, which collides with "${directConflict.plugin}". Mount one of the plugins on a different path.`)
102
- }
103
- if (upperMethod === 'ALL' && byMethod.size > 0) {
104
- const [existingMethod, existingDef] = byMethod.entries().next().value!
105
- throw new Error(`prunelle: plugin "${pluginName}" registered ALL ${normPath}, which collides with ${existingMethod} ${normPath} from "${existingDef.plugin}". Mount one of the plugins on a different path.`)
106
- }
107
- const allConflict = byMethod.get('ALL')
108
- if (allConflict !== undefined) {
109
- throw new Error(`prunelle: plugin "${pluginName}" registered ${upperMethod} ${normPath}, which collides with ALL ${normPath} from "${allConflict.plugin}". Mount one of the plugins on a different path.`)
110
- }
129
+ assertRouteFree(pluginName, upperMethod, normPath, byMethod)
130
+ // The path matches encoded separators once any method takes them; takesEncoded still refuses them to the others.
131
+ if (encodedSlashes)
132
+ router.add(normPath, byMethod, { encodedSlashes })
111
133
  }
112
134
  let routeTrustedOrigins = trustedOrigins
113
135
  if (routeOptions?.trustedOrigins !== undefined && routeOptions.trustedOrigins.length > 0) {
@@ -129,6 +151,7 @@ export async function createServerPluginHost(options: ServerPluginHostOptions) {
129
151
  csrf: routeOptions?.csrf ?? true,
130
152
  trustedOrigins: routeTrustedOrigins,
131
153
  trustProxy: routeOptions?.trustProxy ?? trustProxy,
154
+ encodedSlashes,
132
155
  })
133
156
  }
134
157
 
@@ -179,6 +202,9 @@ export async function createServerPluginHost(options: ServerPluginHostOptions) {
179
202
  getBuildData<T = Record<string, unknown>>(pluginName?: string): T | undefined {
180
203
  return manifest.pluginData?.[pluginName ?? plugin.name] as T | undefined
181
204
  },
205
+ healthCheck(name, fn) {
206
+ healthChecks.push({ name, fn })
207
+ },
182
208
  onShutdown(fn) {
183
209
  shutdownHooks.push({ plugin: plugin.name, hook: fn })
184
210
  },
@@ -224,7 +250,7 @@ export async function createServerPluginHost(options: ServerPluginHostOptions) {
224
250
  }
225
251
  }
226
252
 
227
- return { router, rewrites, allMiddlewares, hasPathScopedMiddlewares, middlewaresFor, middlewaresForPaths, rateLimits, dispose }
253
+ return { router, rewrites, healthChecks, allMiddlewares, hasPathScopedMiddlewares, middlewaresFor, middlewaresForPaths, rateLimits, dispose }
228
254
  }
229
255
 
230
256
  export type ServerPluginHost = Awaited<ReturnType<typeof createServerPluginHost>>
@@ -1,7 +1,7 @@
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 type { ActionContext, ActionErrorFlash, ActionOptions, ActionResult, ServerAction } from './action'
4
+ export type { ActionContext, ActionErrorFlash, ActionOptions, ActionProtectOptions, ActionResult, ServerAction } from './action'
5
5
  export type { ConsentConfig, RequestConsent } from './consent'
6
6
  export type { CookieOptions, Cookies } from './cookies'
7
7
  export { defineEnv, nodeEnv } from './env'
@@ -12,8 +12,8 @@ export { createServer } from './loader'
12
12
  export { createRateLimitStore } from './rate-limit'
13
13
  export type { RateLimit, RateLimiter, RateLimitStore, RateLimitStoreOptions } from './rate-limit'
14
14
  export { readStringFields } from './request-body'
15
- export { getClientIp, isHttpsRequest, isTrustedOrigin, safeEqual, safeRedirect, verifyOrigin } from './security'
16
- export type { SecurityHeadersOptions, TrustProxy } from './security'
15
+ export { DEFAULT_CSP, extendCsp, getClientIp, isHttpsRequest, isTrustedOrigin, safeEqual, safeRedirect, verifyOrigin } from './security'
16
+ export type { CspDirectives, SecurityHeadersOptions, TrustProxy } from './security'
17
17
  export { formatIssuePath, formatSchemaIssues, validateSchema, validateSchemaSync } from './standard-schema'
18
18
  export type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1, ValidationFailure, ValidationResult, ValidationSuccess } from './standard-schema'
19
19
  export { esc, escAttr, escJson, raw } from '../ssr/index'
@@ -1,5 +1,7 @@
1
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.
2
2
 
3
+ import { nodeEnv } from './env'
4
+
3
5
  export interface RateLimit<Ctx extends { ip?: string | undefined } = { ip?: string | undefined }> {
4
6
  /** Requests a key may make per window. */
5
7
  max: number
@@ -31,9 +33,10 @@ export interface RateLimitStoreOptions {
31
33
  maxHits?: number | undefined
32
34
  }
33
35
 
34
- interface Entry {
35
- hits: number[]
36
- windowMs: number
36
+ interface Bucket {
37
+ readonly entries: Map<string, number[]>
38
+ readonly windowMs: number
39
+ hitCount: number
37
40
  }
38
41
 
39
42
  const SWEEP_MS = 60_000
@@ -49,47 +52,51 @@ export function assertRateLimit(limit: Pick<RateLimit, 'max' | 'windowMs'>, wher
49
52
  export function createRateLimitStore(options: RateLimitStoreOptions = {}): RateLimitStore {
50
53
  const maxKeys = Math.max(1, options.maxKeys ?? 10_000)
51
54
  const maxHits = Math.max(1, options.maxHits ?? 1_000_000)
52
- // Least recently used first: a key is moved to the end on each request.
53
- const entries = new Map<string, Entry>()
54
- let hitCount = 0
55
- let nextId = 0
55
+ // Each limiter owns a bounded LRU map so flooding one endpoint cannot evict keys from another.
56
+ const buckets: Bucket[] = []
57
+ let totalKeys = 0
56
58
  let timer: ReturnType<typeof setInterval> | undefined
57
59
 
58
- function trim(entry: Entry, now: number): void {
59
- const cutoff = now - entry.windowMs
60
+ function trim(bucket: Bucket, hits: number[], now: number): void {
61
+ const cutoff = now - bucket.windowMs
60
62
  let stale = 0
61
- while (stale < entry.hits.length && entry.hits[stale]! <= cutoff)
63
+ while (stale < hits.length && hits[stale]! <= cutoff)
62
64
  stale++
63
65
  if (stale > 0) {
64
- entry.hits.splice(0, stale)
65
- hitCount -= stale
66
+ hits.splice(0, stale)
67
+ bucket.hitCount -= stale
66
68
  }
67
69
  }
68
70
 
69
71
  function sweep(now = Date.now()): number {
70
72
  let removed = 0
71
- for (const [key, entry] of entries) {
72
- trim(entry, now)
73
- if (entry.hits.length === 0) {
74
- entries.delete(key)
75
- removed++
73
+ for (const bucket of buckets) {
74
+ for (const [key, hits] of bucket.entries) {
75
+ trim(bucket, hits, now)
76
+ if (hits.length === 0) {
77
+ bucket.entries.delete(key)
78
+ totalKeys--
79
+ removed++
80
+ }
76
81
  }
77
82
  }
78
83
  return removed
79
84
  }
80
85
 
81
- function evict(): void {
82
- while (entries.size > maxKeys || hitCount > maxHits) {
83
- const [key, entry] = entries.entries().next().value!
84
- entries.delete(key)
85
- hitCount -= entry.hits.length
86
+ function evict(bucket: Bucket): void {
87
+ while (bucket.entries.size > maxKeys || bucket.hitCount > maxHits) {
88
+ const [key, hits] = bucket.entries.entries().next().value!
89
+ bucket.entries.delete(key)
90
+ bucket.hitCount -= hits.length
91
+ totalKeys--
86
92
  }
87
93
  }
88
94
 
89
95
  return {
90
96
  limiter(limit) {
91
97
  const { max, windowMs } = limit
92
- const prefix = `${nextId++}\0`
98
+ const bucket: Bucket = { entries: new Map(), windowMs, hitCount: 0 }
99
+ buckets.push(bucket)
93
100
  if (timer === undefined) {
94
101
  timer = setInterval(sweep, SWEEP_MS)
95
102
  timer.unref()
@@ -97,23 +104,28 @@ export function createRateLimitStore(options: RateLimitStoreOptions = {}): RateL
97
104
  return {
98
105
  hit(key) {
99
106
  const now = Date.now()
100
- const id = prefix + key
101
- const entry = entries.get(id) ?? { hits: [], windowMs }
102
- trim(entry, now)
103
- entries.delete(id)
104
- entries.set(id, entry)
105
- if (entry.hits.length >= max)
106
- return Math.max(1, Math.ceil((entry.hits[entry.hits.length - max]! + windowMs - now) / 1000))
107
- entry.hits.push(now)
108
- hitCount++
109
- evict()
107
+ const existing = bucket.entries.get(key)
108
+ const hits = existing ?? []
109
+ if (existing !== undefined) {
110
+ trim(bucket, hits, now)
111
+ bucket.entries.delete(key)
112
+ }
113
+ else {
114
+ totalKeys++
115
+ }
116
+ bucket.entries.set(key, hits)
117
+ if (hits.length >= max)
118
+ return Math.max(1, Math.ceil((hits[hits.length - max]! + windowMs - now) / 1000))
119
+ hits.push(now)
120
+ bucket.hitCount++
121
+ evict(bucket)
110
122
  return 0
111
123
  },
112
124
  }
113
125
  },
114
126
  sweep,
115
127
  get size() {
116
- return entries.size
128
+ return totalKeys
117
129
  },
118
130
  close() {
119
131
  clearInterval(timer)
@@ -127,7 +139,18 @@ export function tooManyRequests(retryAfter: number): Response {
127
139
  return Response.json({ ok: false, status: 429, error: 'Too many requests' }, { status: 429, headers: { 'retry-after': String(retryAfter) } })
128
140
  }
129
141
 
142
+ let warnedMissingIp = false
143
+
130
144
  /** Counts `ctx` against `limiter` by the limit's key, else the client address; returns 0 or the seconds to wait. */
131
145
  export function hitFor<Ctx extends { ip?: string | undefined }>(limiter: RateLimiter, limit: RateLimit<Ctx>, ctx: Ctx): number {
132
- return limiter.hit(limit.key?.(ctx) ?? ctx.ip ?? '')
146
+ const custom = limit.key?.(ctx)
147
+ if (custom !== undefined)
148
+ return limiter.hit(`k:${custom}`)
149
+ if (ctx.ip !== undefined && ctx.ip !== '')
150
+ return limiter.hit(`ip:${ctx.ip}`)
151
+ if (!warnedMissingIp && nodeEnv() === 'production') {
152
+ warnedMissingIp = true
153
+ console.warn('prunelle: rateLimit ran with no client IP (ctx.ip is undefined); configure trustProxy in prunelle.config.ts or pass remoteIp to app.handle() so callers do not share one fallback bucket.')
154
+ }
155
+ return limiter.hit('ip:unknown')
133
156
  }
@@ -7,7 +7,7 @@
7
7
  */
8
8
  export async function readStringFields(request: Request): Promise<Record<string, string>> {
9
9
  const fields: Record<string, string> = Object.create(null)
10
- const contentType = request.headers.get('content-type') ?? ''
10
+ const contentType = (request.headers.get('content-type') ?? '').toLowerCase()
11
11
  if (contentType.includes('application/json')) {
12
12
  const raw: unknown = await request.json()
13
13
  if (raw === null || typeof raw !== 'object' || Array.isArray(raw))