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,365 @@
1
+ // Bounded in-memory route response cache with stale-while-revalidate (SWR) and per-encoding compression reuse.
2
+
3
+ import type { CompressionCache, CompressionEncoding } from './compress'
4
+ import { ACTION_ERROR_COOKIE } from './action'
5
+ import { markCompressionHandled, mergeVaryValue, pickEncoding } from './compress'
6
+ import { hasRegionHeader } from './region'
7
+
8
+ export interface RouteCacheSpec {
9
+ /** Fresh lifetime in milliseconds. */
10
+ maxAgeMs: number
11
+ /** Stale-while-revalidate window in milliseconds (defaults to `maxAgeMs`). */
12
+ swrMs: number
13
+ /** Normalized `Cache-Control` header value (`public, s-maxage=..., stale-while-revalidate=...`). */
14
+ cacheControl: string
15
+ }
16
+
17
+ export interface RouteCacheOptions {
18
+ /** Maximum cached responses kept in memory (default: 500). */
19
+ maxEntries?: number | undefined
20
+ /** Maximum total bytes across cached responses and their compressed variants (default: 32 MiB). */
21
+ maxBytes?: number | undefined
22
+ }
23
+
24
+ export interface CachedRouteEntry {
25
+ html: string
26
+ bytes: number
27
+ headers: Record<string, string>
28
+ createdAt: number
29
+ freshUntil: number
30
+ staleUntil: number
31
+ spec: RouteCacheSpec
32
+ compressed: Partial<Record<CompressionEncoding, Uint8Array<ArrayBuffer> | null>>
33
+ }
34
+
35
+ export type RouteCacheLookup =
36
+ | { status: 'fresh', entry: CachedRouteEntry }
37
+ | { status: 'stale', entry: CachedRouteEntry }
38
+
39
+ const DEFAULT_MAX_ENTRIES = 500
40
+ const DEFAULT_MAX_BYTES = 32 * 1024 * 1024
41
+ const MIN_COMPRESS_BYTES = 256
42
+ const DURATION_RE = /^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/i
43
+
44
+ const UNIT_MS: Record<string, number> = {
45
+ ms: 1,
46
+ s: 1000,
47
+ m: 60_000,
48
+ h: 3_600_000,
49
+ d: 86_400_000,
50
+ }
51
+
52
+ /** Parses a duration string (`'500ms'`, `'30s'`, `'5m'`, `'1h'`, `'1d'`) or number of seconds into milliseconds. */
53
+ export function parseCacheDuration(value: unknown, allowZero = false): number | undefined {
54
+ if (typeof value === 'number') {
55
+ if (!Number.isFinite(value) || (allowZero ? value < 0 : value <= 0))
56
+ return undefined
57
+ return Math.round(value * 1000)
58
+ }
59
+ if (typeof value !== 'string')
60
+ return undefined
61
+ const match = DURATION_RE.exec(value.trim())
62
+ if (match === null)
63
+ return undefined
64
+ const amount = Number(match[1])
65
+ const unit = UNIT_MS[match[2]!.toLowerCase()]
66
+ if (!Number.isFinite(amount) || unit === undefined)
67
+ return undefined
68
+ const ms = Math.round(amount * unit)
69
+ if (!Number.isFinite(ms) || (allowZero ? ms < 0 : ms <= 0))
70
+ return undefined
71
+ return ms
72
+ }
73
+
74
+ /** Formats milliseconds into the cleanest short duration token (`1h`, `30s`, `500ms`). */
75
+ export function formatCacheDuration(ms: number): string {
76
+ if (ms === 0)
77
+ return '0s'
78
+ if (ms % 86_400_000 === 0)
79
+ return `${ms / 86_400_000}d`
80
+ if (ms % 3_600_000 === 0)
81
+ return `${ms / 3_600_000}h`
82
+ if (ms % 60_000 === 0)
83
+ return `${ms / 60_000}m`
84
+ if (ms % 1000 === 0)
85
+ return `${ms / 1000}s`
86
+ return `${ms}ms`
87
+ }
88
+
89
+ /** Builds a normalized `RouteCacheSpec` with its `Cache-Control` header value. */
90
+ export function buildRouteCacheSpec(maxAgeMs: number, swrMs: number = maxAgeMs): RouteCacheSpec {
91
+ const maxAgeSec = Math.max(1, Math.round(maxAgeMs / 1000))
92
+ const swrSec = swrMs === 0 ? 0 : Math.max(1, Math.round(swrMs / 1000))
93
+ return {
94
+ maxAgeMs,
95
+ swrMs,
96
+ cacheControl: `public, s-maxage=${maxAgeSec}, stale-while-revalidate=${swrSec}`,
97
+ }
98
+ }
99
+
100
+ /** Formats a `RouteCacheSpec` concisely for `prunelle inspect`. */
101
+ export function formatCacheSpec(spec: RouteCacheSpec): string {
102
+ const maxAge = formatCacheDuration(spec.maxAgeMs)
103
+ if (spec.swrMs === spec.maxAgeMs)
104
+ return maxAge
105
+ return `${maxAge},swr=${formatCacheDuration(spec.swrMs)}`
106
+ }
107
+
108
+ /** Returns a copy of `headers` with `cache-control` set to `cacheControl`. */
109
+ export function withCacheControl(headers: Record<string, string>, cacheControl: string): Record<string, string> {
110
+ return { ...headers, 'cache-control': cacheControl }
111
+ }
112
+
113
+ /** Whether a request is eligible to read from or populate the shared route cache. */
114
+ export function isCacheableRequest(request: Request): boolean {
115
+ if (request.method !== 'GET' && request.method !== 'HEAD')
116
+ return false
117
+ if (hasRegionHeader(request))
118
+ return false
119
+ const cookie = request.headers.get('cookie')
120
+ if (cookie !== null && cookie.includes(`${ACTION_ERROR_COOKIE}=`))
121
+ return false
122
+ return true
123
+ }
124
+
125
+ function compressCachedHtml(html: string, encoding: CompressionEncoding): Uint8Array<ArrayBuffer> | null {
126
+ const rawSize = Buffer.byteLength(html, 'utf8')
127
+ if (rawSize < MIN_COMPRESS_BYTES)
128
+ return null
129
+ const buf = (encoding === 'zstd' ? Bun.zstdCompressSync(html, { level: 3 }) : Bun.gzipSync(html, { level: 6 })) as Uint8Array<ArrayBuffer>
130
+ return buf.byteLength < rawSize ? buf : null
131
+ }
132
+
133
+ /** Bounded LRU cache for rendered HTML routes with stale-while-revalidate deduplication. */
134
+ export class RouteCache {
135
+ readonly #map = new Map<string, CachedRouteEntry>()
136
+ readonly #revalidating = new Set<string>()
137
+ readonly #maxEntries: number
138
+ readonly #maxBytes: number
139
+ #totalBytes = 0
140
+
141
+ constructor(options?: RouteCacheOptions) {
142
+ const entries = options?.maxEntries ?? DEFAULT_MAX_ENTRIES
143
+ const bytes = options?.maxBytes ?? DEFAULT_MAX_BYTES
144
+ this.#maxEntries = Number.isFinite(entries) && entries > 0 ? Math.floor(entries) : 0
145
+ this.#maxBytes = Number.isFinite(bytes) && bytes > 0 ? Math.floor(bytes) : 0
146
+ }
147
+
148
+ get size(): number {
149
+ return this.#map.size
150
+ }
151
+
152
+ get bytes(): number {
153
+ return this.#totalBytes
154
+ }
155
+
156
+ hasInflight(key: string): boolean {
157
+ return this.#revalidating.has(key)
158
+ }
159
+
160
+ clear(): void {
161
+ this.#map.clear()
162
+ this.#totalBytes = 0
163
+ }
164
+
165
+ delete(key: string): void {
166
+ const prev = this.#map.get(key)
167
+ if (prev === undefined)
168
+ return
169
+ this.#map.delete(key)
170
+ this.#totalBytes -= prev.bytes
171
+ }
172
+
173
+ /** Looks up `key`, refreshing LRU recency on fresh/stale hits and deleting expired entries. */
174
+ lookup(key: string, now = Date.now()): RouteCacheLookup | undefined {
175
+ const entry = this.#map.get(key)
176
+ if (entry === undefined)
177
+ return undefined
178
+ if (now >= entry.staleUntil) {
179
+ this.#map.delete(key)
180
+ this.#totalBytes -= entry.bytes
181
+ return undefined
182
+ }
183
+ this.#map.delete(key)
184
+ this.#map.set(key, entry)
185
+ return now < entry.freshUntil
186
+ ? { status: 'fresh', entry }
187
+ : { status: 'stale', entry }
188
+ }
189
+
190
+ /** Stores rendered HTML and headers under `key`, evicting LRU entries to enforce both caps. */
191
+ set(key: string, html: string, headers: Record<string, string>, spec: RouteCacheSpec, now = Date.now()): CachedRouteEntry | undefined {
192
+ const rawBytes = Buffer.byteLength(html, 'utf8')
193
+ if (this.#maxEntries <= 0 || this.#maxBytes <= 0 || rawBytes > this.#maxBytes)
194
+ return undefined
195
+ const prev = this.#map.get(key)
196
+ if (prev !== undefined) {
197
+ this.#totalBytes -= prev.bytes
198
+ this.#map.delete(key)
199
+ }
200
+ const entry: CachedRouteEntry = {
201
+ html,
202
+ bytes: rawBytes,
203
+ headers,
204
+ createdAt: now,
205
+ freshUntil: now + spec.maxAgeMs,
206
+ staleUntil: now + spec.maxAgeMs + spec.swrMs,
207
+ spec,
208
+ compressed: {},
209
+ }
210
+ this.#map.set(key, entry)
211
+ this.#totalBytes += rawBytes
212
+ this.#evict(key)
213
+ return entry
214
+ }
215
+
216
+ /** Schedules a deduplicated background revalidation for `key`, reporting failures via `onError`. */
217
+ revalidate(key: string, task: () => Promise<void>, onError: (error: unknown) => void): boolean {
218
+ if (this.#revalidating.has(key))
219
+ return false
220
+ this.#revalidating.add(key)
221
+ void Promise.resolve()
222
+ .then(task)
223
+ .catch((error: unknown) => {
224
+ onError(error)
225
+ })
226
+ .finally(() => {
227
+ this.#revalidating.delete(key)
228
+ })
229
+ return true
230
+ }
231
+
232
+ /** Builds a 200 HTML response for a cache hit (`age` included, precompressed variant reused). */
233
+ respondHit(
234
+ entry: CachedRouteEntry,
235
+ request: Request,
236
+ requestId: string,
237
+ compressCache: CompressionCache | undefined,
238
+ now = Date.now(),
239
+ ): Response {
240
+ const age = String(Math.max(0, Math.floor((now - entry.createdAt) / 1000)))
241
+ return this.#buildResponse(entry, entry.html, entry.headers, request, requestId, compressCache, age)
242
+ }
243
+
244
+ /** Builds a 200 HTML response for a freshly rendered miss (stored in cache when it fits). */
245
+ respondMiss(
246
+ entry: CachedRouteEntry | undefined,
247
+ html: string,
248
+ headers: Record<string, string>,
249
+ request: Request,
250
+ requestId: string,
251
+ compressCache: CompressionCache | undefined,
252
+ serverTiming?: string,
253
+ ): Response {
254
+ return this.#buildResponse(entry, html, headers, request, requestId, compressCache, undefined, serverTiming)
255
+ }
256
+
257
+ #buildResponse(
258
+ entry: CachedRouteEntry | undefined,
259
+ html: string,
260
+ baseHeaders: Record<string, string>,
261
+ request: Request,
262
+ requestId: string,
263
+ compressCache: CompressionCache | undefined,
264
+ age?: string,
265
+ serverTiming?: string,
266
+ ): Response {
267
+ const headers: Record<string, string> = { ...baseHeaders, 'x-request-id': requestId }
268
+ if (age !== undefined)
269
+ headers.age = age
270
+ if (serverTiming !== undefined)
271
+ headers['server-timing'] = serverTiming
272
+
273
+ if (compressCache !== undefined) {
274
+ headers.vary = mergeVaryValue(headers.vary, 'Accept-Encoding')
275
+ if (request.method !== 'HEAD') {
276
+ const enc = pickEncoding(request.headers.get('accept-encoding'))
277
+ if (enc !== undefined) {
278
+ const compressed = this.#getOrCompress(entry, html, enc)
279
+ if (compressed !== null) {
280
+ headers['content-encoding'] = enc
281
+ return markCompressionHandled(new Response(compressed, { status: 200, headers }))
282
+ }
283
+ }
284
+ }
285
+ }
286
+ return markCompressionHandled(new Response(request.method === 'HEAD' ? null : html, { status: 200, headers }))
287
+ }
288
+
289
+ #getOrCompress(entry: CachedRouteEntry | undefined, html: string, enc: CompressionEncoding): Uint8Array<ArrayBuffer> | null {
290
+ if (entry !== undefined) {
291
+ const existing = entry.compressed[enc]
292
+ if (existing !== undefined)
293
+ return existing
294
+ }
295
+ const buf = compressCachedHtml(html, enc)
296
+ if (entry !== undefined) {
297
+ if (buf === null) {
298
+ entry.compressed[enc] = null
299
+ }
300
+ else if (entry.bytes + buf.byteLength <= this.#maxBytes) {
301
+ entry.compressed[enc] = buf
302
+ entry.bytes += buf.byteLength
303
+ this.#totalBytes += buf.byteLength
304
+ this.#evictEntry(entry)
305
+ }
306
+ }
307
+ return buf
308
+ }
309
+
310
+ #evict(keepKey?: string): void {
311
+ while (this.#map.size > this.#maxEntries || this.#totalBytes > this.#maxBytes) {
312
+ const oldest = this.#map.keys().next()
313
+ if (oldest.done)
314
+ break
315
+ const key = oldest.value
316
+ if (key === keepKey && this.#map.size === 1)
317
+ break
318
+ const evicted = this.#map.get(key)!
319
+ this.#map.delete(key)
320
+ this.#totalBytes -= evicted.bytes
321
+ }
322
+ }
323
+
324
+ #evictEntry(keep: CachedRouteEntry): void {
325
+ while (this.#totalBytes > this.#maxBytes) {
326
+ let victimKey: string | undefined
327
+ for (const [k, v] of this.#map) {
328
+ if (v !== keep) {
329
+ victimKey = k
330
+ break
331
+ }
332
+ }
333
+ if (victimKey === undefined)
334
+ break
335
+ const evicted = this.#map.get(victimKey)!
336
+ this.#map.delete(victimKey)
337
+ this.#totalBytes -= evicted.bytes
338
+ }
339
+ }
340
+ }
341
+
342
+ /** Looks up a cached hit and schedules background revalidation when stale. */
343
+ export function serveCachedHit(
344
+ routeCache: RouteCache,
345
+ key: string,
346
+ request: Request,
347
+ requestId: string,
348
+ compressCache: CompressionCache | undefined,
349
+ revalidate: () => Promise<void>,
350
+ onError: (error: unknown) => void,
351
+ ): Response | undefined {
352
+ const hit = routeCache.lookup(key)
353
+ if (hit === undefined)
354
+ return undefined
355
+ if (hit.status === 'stale')
356
+ routeCache.revalidate(key, revalidate, onError)
357
+ return routeCache.respondHit(hit.entry, request, requestId, compressCache)
358
+ }
359
+
360
+ /** Creates a `RouteCache` unless disabled (`dev`, build prerendering, or `routeCache: false`). */
361
+ export function createRouteCache(option: RouteCacheOptions | false | undefined, disabled = false): RouteCache | undefined {
362
+ if (disabled || option === false)
363
+ return undefined
364
+ return new RouteCache(option)
365
+ }