prunelle 0.1.1 → 0.5.2

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 (105) 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 +80 -36
  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 +56 -6
  11. package/src/build/compile.ts +11 -9
  12. package/src/build/ecoindex.ts +229 -0
  13. package/src/build/index.ts +174 -108
  14. package/src/build/islands.ts +2 -2
  15. package/src/build/manifest.ts +66 -5
  16. package/src/build/output.ts +2 -2
  17. package/src/build/plugin-host.ts +91 -33
  18. package/src/build/precompress.ts +15 -2
  19. package/src/build/prerender.ts +128 -46
  20. package/src/build/report.ts +23 -2
  21. package/src/build/resolve.ts +8 -6
  22. package/src/build/routes.ts +175 -10
  23. package/src/build/static.ts +137 -39
  24. package/src/build/status-pages.ts +127 -0
  25. package/src/build/style-bundles.ts +526 -0
  26. package/src/cli/check-forms.ts +654 -0
  27. package/src/cli/check-links.ts +619 -0
  28. package/src/cli/check.ts +52 -5
  29. package/src/cli/commands.ts +86 -4
  30. package/src/cli/docs.ts +402 -0
  31. package/src/cli/inspect.ts +31 -2
  32. package/src/cli/mcp-tools.ts +480 -0
  33. package/src/cli/mcp.ts +205 -0
  34. package/src/cli/new.ts +2 -2
  35. package/src/cli/render.ts +261 -0
  36. package/src/cli/upgrade-names.ts +73 -13
  37. package/src/cli/upgrade.ts +137 -16
  38. package/src/compiler/analyze.ts +20 -6
  39. package/src/compiler/cacheability.ts +592 -0
  40. package/src/compiler/compliance-rgaa.ts +502 -0
  41. package/src/compiler/compliance.ts +120 -221
  42. package/src/compiler/dev-source.ts +87 -0
  43. package/src/compiler/dom-attrs.ts +138 -65
  44. package/src/compiler/dom.ts +12 -11
  45. package/src/compiler/expr-context.ts +167 -57
  46. package/src/compiler/props.ts +87 -36
  47. package/src/compiler/scope.ts +56 -17
  48. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  49. package/src/compiler/ssr.ts +216 -84
  50. package/src/dev/error-log.ts +151 -0
  51. package/src/dev/index.ts +84 -34
  52. package/src/dev/open-editor.ts +204 -0
  53. package/src/dev/protocol.ts +1 -0
  54. package/src/dev/reload.ts +5 -3
  55. package/src/dev/supervisor.ts +42 -25
  56. package/src/dev/watchers.ts +47 -11
  57. package/src/dom/action.ts +4 -1
  58. package/src/dom/attrs.ts +15 -3
  59. package/src/dom/extras.ts +2 -2
  60. package/src/dom/island.ts +11 -10
  61. package/src/plugins/config.ts +4 -4
  62. package/src/plugins/index.ts +2 -2
  63. package/src/plugins/public.ts +5 -2
  64. package/src/plugins/services.ts +62 -0
  65. package/src/plugins/types.ts +32 -0
  66. package/src/server/action-protect.ts +198 -0
  67. package/src/server/action-registry.ts +1 -1
  68. package/src/server/action.ts +82 -27
  69. package/src/server/assets.ts +34 -2
  70. package/src/server/compress.ts +91 -9
  71. package/src/server/errors.ts +303 -65
  72. package/src/server/form-schema.ts +343 -0
  73. package/src/server/health.ts +244 -0
  74. package/src/server/http.ts +128 -31
  75. package/src/server/index.ts +230 -260
  76. package/src/server/loader.ts +5 -0
  77. package/src/server/param-matchers.ts +112 -0
  78. package/src/server/plugin-host.ts +123 -88
  79. package/src/server/public.ts +3 -3
  80. package/src/server/rate-limit.ts +58 -35
  81. package/src/server/request-body.ts +1 -1
  82. package/src/server/route-cache.ts +423 -0
  83. package/src/server/route-table.ts +339 -8
  84. package/src/server/router.ts +125 -40
  85. package/src/server/routing.ts +196 -63
  86. package/src/server/security.ts +208 -32
  87. package/src/server/serve-handlers.ts +21 -7
  88. package/src/server/start.ts +60 -16
  89. package/src/server/static-dir.ts +61 -8
  90. package/src/server/stream.ts +41 -22
  91. package/src/ssr/context.ts +85 -3
  92. package/src/ssr/index.ts +120 -1
  93. package/src/ssr/region.ts +31 -19
  94. package/src/test/browser.ts +6 -0
  95. package/src/test/index.ts +17 -3
  96. package/src/ts-plugin/diagnostics.ts +378 -0
  97. package/src/ts-plugin/fixes.ts +364 -0
  98. package/src/ts-plugin/index.ts +194 -0
  99. package/templates/_shared/AGENTS.md +2 -2
  100. package/templates/_shared/mcp.json +11 -0
  101. package/templates/_shared/src/routes/legal.tsx +5 -0
  102. package/templates/_shared/tsconfig.json +5 -0
  103. package/templates/blog/prunelle.config.ts +1 -1
  104. package/templates/blog/src/routes/index.tsx +4 -0
  105. package/ts-plugin.cjs +4277 -0
@@ -0,0 +1,423 @@
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
+ /** Backoff cooldown in milliseconds after a failed SWR revalidation before retrying (default: 5000). */
23
+ failureCooldownMs?: number | undefined
24
+ }
25
+
26
+ export interface RouteCacheSingleflightResult {
27
+ entry: CachedRouteEntry | undefined
28
+ html: string
29
+ headers: Record<string, string>
30
+ }
31
+
32
+ export interface CachedRouteEntry {
33
+ html: string
34
+ bytes: number
35
+ headers: Record<string, string>
36
+ createdAt: number
37
+ freshUntil: number
38
+ staleUntil: number
39
+ spec: RouteCacheSpec
40
+ compressed: Partial<Record<CompressionEncoding, Uint8Array<ArrayBuffer> | null>>
41
+ }
42
+
43
+ export type RouteCacheLookup =
44
+ | { status: 'fresh', entry: CachedRouteEntry }
45
+ | { status: 'stale', entry: CachedRouteEntry }
46
+
47
+ const DEFAULT_MAX_ENTRIES = 500
48
+ const DEFAULT_MAX_BYTES = 32 * 1024 * 1024
49
+ const DEFAULT_FAILURE_COOLDOWN_MS = 5_000
50
+ const MIN_COMPRESS_BYTES = 256
51
+ const DURATION_RE = /^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/i
52
+
53
+ const UNIT_MS: Record<string, number> = {
54
+ ms: 1,
55
+ s: 1000,
56
+ m: 60_000,
57
+ h: 3_600_000,
58
+ d: 86_400_000,
59
+ }
60
+
61
+ /** Parses a duration string (`'500ms'`, `'30s'`, `'5m'`, `'1h'`, `'1d'`) or number of seconds into milliseconds. */
62
+ export function parseCacheDuration(value: unknown, allowZero = false): number | undefined {
63
+ if (typeof value === 'number') {
64
+ if (!Number.isFinite(value) || (allowZero ? value < 0 : value <= 0))
65
+ return undefined
66
+ return Math.round(value * 1000)
67
+ }
68
+ if (typeof value !== 'string')
69
+ return undefined
70
+ const match = DURATION_RE.exec(value.trim())
71
+ if (match === null)
72
+ return undefined
73
+ const amount = Number(match[1])
74
+ const unit = UNIT_MS[match[2]!.toLowerCase()]
75
+ if (!Number.isFinite(amount) || unit === undefined)
76
+ return undefined
77
+ const ms = Math.round(amount * unit)
78
+ if (!Number.isFinite(ms) || (allowZero ? ms < 0 : ms <= 0))
79
+ return undefined
80
+ return ms
81
+ }
82
+
83
+ /** Formats milliseconds into the cleanest short duration token (`1h`, `30s`, `500ms`). */
84
+ export function formatCacheDuration(ms: number): string {
85
+ if (ms === 0)
86
+ return '0s'
87
+ if (ms % 86_400_000 === 0)
88
+ return `${ms / 86_400_000}d`
89
+ if (ms % 3_600_000 === 0)
90
+ return `${ms / 3_600_000}h`
91
+ if (ms % 60_000 === 0)
92
+ return `${ms / 60_000}m`
93
+ if (ms % 1000 === 0)
94
+ return `${ms / 1000}s`
95
+ return `${ms}ms`
96
+ }
97
+
98
+ /** Builds a normalized `RouteCacheSpec` with its `Cache-Control` header value. */
99
+ export function buildRouteCacheSpec(maxAgeMs: number, swrMs: number = maxAgeMs): RouteCacheSpec {
100
+ const maxAgeSec = Math.max(1, Math.round(maxAgeMs / 1000))
101
+ const swrSec = swrMs === 0 ? 0 : Math.max(1, Math.round(swrMs / 1000))
102
+ return {
103
+ maxAgeMs,
104
+ swrMs,
105
+ cacheControl: `public, s-maxage=${maxAgeSec}, stale-while-revalidate=${swrSec}`,
106
+ }
107
+ }
108
+
109
+ /** Formats a `RouteCacheSpec` concisely for `prunelle inspect`. */
110
+ export function formatCacheSpec(spec: RouteCacheSpec): string {
111
+ const maxAge = formatCacheDuration(spec.maxAgeMs)
112
+ if (spec.swrMs === spec.maxAgeMs)
113
+ return maxAge
114
+ return `${maxAge},swr=${formatCacheDuration(spec.swrMs)}`
115
+ }
116
+
117
+ /** Returns a copy of `headers` with `cache-control` set to `cacheControl`. */
118
+ export function withCacheControl(headers: Record<string, string>, cacheControl: string): Record<string, string> {
119
+ return { ...headers, 'cache-control': cacheControl }
120
+ }
121
+
122
+ /** Builds a host-scoped cache key so multi-domain deployments never poison one host from another. */
123
+ export function routeCacheKey(url: URL): string {
124
+ return `${url.host}${url.pathname}${url.search}`
125
+ }
126
+
127
+ /** Whether a request is eligible to read from or populate the shared route cache. */
128
+ export function isCacheableRequest(request: Request): boolean {
129
+ if (request.method !== 'GET' && request.method !== 'HEAD')
130
+ return false
131
+ if (hasRegionHeader(request))
132
+ return false
133
+ const cookie = request.headers.get('cookie')
134
+ if (cookie !== null && cookie.includes(`${ACTION_ERROR_COOKIE}=`))
135
+ return false
136
+ return true
137
+ }
138
+
139
+ function compressCachedHtml(html: string, encoding: CompressionEncoding): Uint8Array<ArrayBuffer> | null {
140
+ const rawSize = Buffer.byteLength(html, 'utf8')
141
+ if (rawSize < MIN_COMPRESS_BYTES)
142
+ return null
143
+ const buf = (encoding === 'zstd' ? Bun.zstdCompressSync(html, { level: 3 }) : Bun.gzipSync(html, { level: 6 })) as Uint8Array<ArrayBuffer>
144
+ return buf.byteLength < rawSize ? buf : null
145
+ }
146
+
147
+ /** Bounded LRU cache for rendered HTML routes with stale-while-revalidate deduplication. */
148
+ export class RouteCache {
149
+ readonly #map = new Map<string, CachedRouteEntry>()
150
+ readonly #revalidating = new Set<string>()
151
+ readonly #inflight = new Map<string, Promise<RouteCacheSingleflightResult | undefined>>()
152
+ readonly #failedUntil = new Map<string, number>()
153
+ readonly #maxEntries: number
154
+ readonly #maxBytes: number
155
+ readonly #failureCooldownMs: number
156
+ #totalBytes = 0
157
+
158
+ constructor(options?: RouteCacheOptions) {
159
+ const entries = options?.maxEntries ?? DEFAULT_MAX_ENTRIES
160
+ const bytes = options?.maxBytes ?? DEFAULT_MAX_BYTES
161
+ const cooldown = options?.failureCooldownMs ?? DEFAULT_FAILURE_COOLDOWN_MS
162
+ this.#maxEntries = Number.isFinite(entries) && entries > 0 ? Math.floor(entries) : 0
163
+ this.#maxBytes = Number.isFinite(bytes) && bytes > 0 ? Math.floor(bytes) : 0
164
+ this.#failureCooldownMs = Number.isFinite(cooldown) && cooldown >= 0 ? Math.floor(cooldown) : DEFAULT_FAILURE_COOLDOWN_MS
165
+ }
166
+
167
+ get size(): number {
168
+ return this.#map.size
169
+ }
170
+
171
+ get bytes(): number {
172
+ return this.#totalBytes
173
+ }
174
+
175
+ hasInflight(key: string): boolean {
176
+ return this.#revalidating.has(key) || this.#inflight.has(key)
177
+ }
178
+
179
+ getInflight(key: string): Promise<RouteCacheSingleflightResult | undefined> | undefined {
180
+ return this.#inflight.get(key)
181
+ }
182
+
183
+ trackInflight(key: string, promise: Promise<RouteCacheSingleflightResult | undefined>): void {
184
+ this.#inflight.set(key, promise)
185
+ const cleanup = (): void => {
186
+ if (this.#inflight.get(key) === promise)
187
+ this.#inflight.delete(key)
188
+ }
189
+ void promise.then(cleanup, cleanup)
190
+ }
191
+
192
+ clear(): void {
193
+ this.#map.clear()
194
+ this.#failedUntil.clear()
195
+ this.#totalBytes = 0
196
+ }
197
+
198
+ delete(key: string): void {
199
+ const prev = this.#map.get(key)
200
+ if (prev === undefined)
201
+ return
202
+ this.#map.delete(key)
203
+ this.#totalBytes -= prev.bytes
204
+ }
205
+
206
+ /** Looks up `key`, refreshing LRU recency on fresh/stale hits and deleting expired entries. */
207
+ lookup(key: string, now = Date.now()): RouteCacheLookup | undefined {
208
+ const entry = this.#map.get(key)
209
+ if (entry === undefined)
210
+ return undefined
211
+ if (now >= entry.staleUntil) {
212
+ this.#map.delete(key)
213
+ this.#totalBytes -= entry.bytes
214
+ return undefined
215
+ }
216
+ this.#map.delete(key)
217
+ this.#map.set(key, entry)
218
+ return now < entry.freshUntil
219
+ ? { status: 'fresh', entry }
220
+ : { status: 'stale', entry }
221
+ }
222
+
223
+ /** Stores rendered HTML and headers under `key`, evicting LRU entries to enforce both caps. */
224
+ set(key: string, html: string, headers: Record<string, string>, spec: RouteCacheSpec, now = Date.now()): CachedRouteEntry | undefined {
225
+ const rawBytes = Buffer.byteLength(html, 'utf8')
226
+ if (this.#maxEntries <= 0 || this.#maxBytes <= 0 || rawBytes > this.#maxBytes)
227
+ return undefined
228
+ this.#failedUntil.delete(key)
229
+ const prev = this.#map.get(key)
230
+ if (prev !== undefined) {
231
+ this.#totalBytes -= prev.bytes
232
+ this.#map.delete(key)
233
+ }
234
+ const entry: CachedRouteEntry = {
235
+ html,
236
+ bytes: rawBytes,
237
+ headers,
238
+ createdAt: now,
239
+ freshUntil: now + spec.maxAgeMs,
240
+ staleUntil: now + spec.maxAgeMs + spec.swrMs,
241
+ spec,
242
+ compressed: {},
243
+ }
244
+ this.#map.set(key, entry)
245
+ this.#totalBytes += rawBytes
246
+ this.#evict(key)
247
+ return entry
248
+ }
249
+
250
+ /** Schedules a deduplicated background revalidation for `key`, backing off briefly on failure and reporting via `onError`. */
251
+ revalidate(key: string, task: () => Promise<void>, onError: (error: unknown) => void, now = Date.now()): boolean {
252
+ if (this.#revalidating.has(key))
253
+ return false
254
+ const cooldownUntil = this.#failedUntil.get(key)
255
+ if (cooldownUntil !== undefined) {
256
+ if (now < cooldownUntil)
257
+ return false
258
+ this.#failedUntil.delete(key)
259
+ }
260
+ this.#revalidating.add(key)
261
+ void Promise.resolve()
262
+ .then(task)
263
+ .then(() => {
264
+ this.#failedUntil.delete(key)
265
+ })
266
+ .catch((error: unknown) => {
267
+ if (this.#failureCooldownMs > 0) {
268
+ this.#failedUntil.set(key, Date.now() + this.#failureCooldownMs)
269
+ this.#pruneCooldowns()
270
+ }
271
+ onError(error)
272
+ })
273
+ .finally(() => {
274
+ this.#revalidating.delete(key)
275
+ })
276
+ return true
277
+ }
278
+
279
+ #pruneCooldowns(): void {
280
+ const cap = Math.max(this.#maxEntries * 2, 1000)
281
+ if (this.#failedUntil.size <= cap)
282
+ return
283
+ const now = Date.now()
284
+ for (const [k, until] of this.#failedUntil) {
285
+ if (now >= until)
286
+ this.#failedUntil.delete(k)
287
+ }
288
+ }
289
+
290
+ /** Builds a 200 HTML response for a cache hit (`age` included, precompressed variant reused). */
291
+ respondHit(
292
+ entry: CachedRouteEntry,
293
+ request: Request,
294
+ requestId: string,
295
+ compressCache: CompressionCache | undefined,
296
+ now = Date.now(),
297
+ ): Response {
298
+ const age = String(Math.max(0, Math.floor((now - entry.createdAt) / 1000)))
299
+ return this.#buildResponse(entry, entry.html, entry.headers, request, requestId, compressCache, age)
300
+ }
301
+
302
+ /** Builds a 200 HTML response for a freshly rendered miss (stored in cache when it fits). */
303
+ respondMiss(
304
+ entry: CachedRouteEntry | undefined,
305
+ html: string,
306
+ headers: Record<string, string>,
307
+ request: Request,
308
+ requestId: string,
309
+ compressCache: CompressionCache | undefined,
310
+ serverTiming?: string,
311
+ ): Response {
312
+ return this.#buildResponse(entry, html, headers, request, requestId, compressCache, undefined, serverTiming)
313
+ }
314
+
315
+ #buildResponse(
316
+ entry: CachedRouteEntry | undefined,
317
+ html: string,
318
+ baseHeaders: Record<string, string>,
319
+ request: Request,
320
+ requestId: string,
321
+ compressCache: CompressionCache | undefined,
322
+ age?: string,
323
+ serverTiming?: string,
324
+ ): Response {
325
+ const headers: Record<string, string> = { ...baseHeaders, 'x-request-id': requestId }
326
+ if (age !== undefined)
327
+ headers.age = age
328
+ if (serverTiming !== undefined)
329
+ headers['server-timing'] = serverTiming
330
+
331
+ if (compressCache !== undefined) {
332
+ headers.vary = mergeVaryValue(headers.vary, 'Accept-Encoding')
333
+ if (request.method !== 'HEAD') {
334
+ const enc = pickEncoding(request.headers.get('accept-encoding'))
335
+ if (enc !== undefined) {
336
+ const compressed = this.#getOrCompress(entry, html, enc)
337
+ if (compressed !== null) {
338
+ headers['content-encoding'] = enc
339
+ return markCompressionHandled(new Response(compressed, { status: 200, headers }))
340
+ }
341
+ }
342
+ }
343
+ }
344
+ return markCompressionHandled(new Response(request.method === 'HEAD' ? null : html, { status: 200, headers }))
345
+ }
346
+
347
+ #getOrCompress(entry: CachedRouteEntry | undefined, html: string, enc: CompressionEncoding): Uint8Array<ArrayBuffer> | null {
348
+ if (entry !== undefined) {
349
+ const existing = entry.compressed[enc]
350
+ if (existing !== undefined)
351
+ return existing
352
+ }
353
+ const buf = compressCachedHtml(html, enc)
354
+ if (entry !== undefined) {
355
+ if (buf === null) {
356
+ entry.compressed[enc] = null
357
+ }
358
+ else if (entry.bytes + buf.byteLength <= this.#maxBytes) {
359
+ entry.compressed[enc] = buf
360
+ entry.bytes += buf.byteLength
361
+ this.#totalBytes += buf.byteLength
362
+ this.#evictEntry(entry)
363
+ }
364
+ }
365
+ return buf
366
+ }
367
+
368
+ #evict(keepKey?: string): void {
369
+ while (this.#map.size > this.#maxEntries || this.#totalBytes > this.#maxBytes) {
370
+ const oldest = this.#map.keys().next()
371
+ if (oldest.done)
372
+ break
373
+ const key = oldest.value
374
+ if (key === keepKey && this.#map.size === 1)
375
+ break
376
+ const evicted = this.#map.get(key)!
377
+ this.#map.delete(key)
378
+ this.#totalBytes -= evicted.bytes
379
+ }
380
+ }
381
+
382
+ #evictEntry(keep: CachedRouteEntry): void {
383
+ while (this.#totalBytes > this.#maxBytes) {
384
+ let victimKey: string | undefined
385
+ for (const [k, v] of this.#map) {
386
+ if (v !== keep) {
387
+ victimKey = k
388
+ break
389
+ }
390
+ }
391
+ if (victimKey === undefined)
392
+ break
393
+ const evicted = this.#map.get(victimKey)!
394
+ this.#map.delete(victimKey)
395
+ this.#totalBytes -= evicted.bytes
396
+ }
397
+ }
398
+ }
399
+
400
+ /** Looks up a cached hit and schedules background revalidation when stale. */
401
+ export function serveCachedHit(
402
+ routeCache: RouteCache,
403
+ key: string,
404
+ request: Request,
405
+ requestId: string,
406
+ compressCache: CompressionCache | undefined,
407
+ revalidate: () => Promise<void>,
408
+ onError: (error: unknown) => void,
409
+ ): Response | undefined {
410
+ const hit = routeCache.lookup(key)
411
+ if (hit === undefined)
412
+ return undefined
413
+ if (hit.status === 'stale')
414
+ routeCache.revalidate(key, revalidate, onError)
415
+ return routeCache.respondHit(hit.entry, request, requestId, compressCache)
416
+ }
417
+
418
+ /** Creates a `RouteCache` unless disabled (`dev`, build prerendering, or `routeCache: false`). */
419
+ export function createRouteCache(option: RouteCacheOptions | false | undefined, disabled = false): RouteCache | undefined {
420
+ if (disabled || option === false)
421
+ return undefined
422
+ return new RouteCache(option)
423
+ }