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
@@ -10,6 +10,7 @@ import type { TrustProxy } from './security'
10
10
  import { createRequestConsent } from './consent'
11
11
  import { CookieStore } from './cookies'
12
12
  import { nodeEnv } from './env'
13
+ import { resolveFallbackRequestId } from './health'
13
14
  import { requestedRegion } from './region'
14
15
  import { getClientIp, isHttpsRequest } from './security'
15
16
 
@@ -31,21 +32,41 @@ export function isNotFound(value: unknown): value is NotFoundResult {
31
32
  return typeof value === 'object' && value !== null && (value as Record<symbol, unknown>)[NOT_FOUND_SYMBOL] === true
32
33
  }
33
34
 
34
- type SegmentParam<Seg extends string> =
35
- Seg extends `[...${infer Name}]`
36
- ? { [K in Name]: string }
37
- : Seg extends `[${infer Name}]`
38
- ? { [K in Name]: string }
39
- : Seg extends `*${infer Name}`
40
- ? { [K in Name extends '' ? 'rest' : Name]: string }
41
- : Seg extends `:${infer Name}`
42
- ? { [K in Name]: string }
43
- : unknown
44
-
45
- type MergeParams<A, B> = {
46
- [K in keyof A | keyof B]: K extends keyof B ? B[K] : K extends keyof A ? A[K] : never
35
+ /** Maps built-in (and augmented) route param matcher names to their TypeScript param value types. */
36
+ export interface ParamMatcherTypes {
37
+ integer: `${number}`
38
+ uuid: `${string}-${string}-${string}-${string}-${string}`
39
+ slug: string
47
40
  }
48
41
 
42
+ type MatcherValue<Name extends string> = Name extends keyof ParamMatcherTypes ? ParamMatcherTypes[Name] : string
43
+
44
+ type ParseParamSpec<Spec extends string> =
45
+ Spec extends `${infer Name}=${infer Matcher}`
46
+ ? [Name, MatcherValue<Matcher>]
47
+ : [Spec, string]
48
+
49
+ type SegmentParam<Seg extends string> =
50
+ Seg extends `(${string})`
51
+ ? unknown
52
+ : Seg extends `[[${infer Spec}]]`
53
+ ? { [K in ParseParamSpec<Spec>[0]]?: ParseParamSpec<Spec>[1] | undefined }
54
+ : Seg extends `[...${infer Spec}]`
55
+ ? { [K in ParseParamSpec<Spec>[0]]: string }
56
+ : Seg extends `[${infer Spec}]`
57
+ ? { [K in ParseParamSpec<Spec>[0]]: ParseParamSpec<Spec>[1] }
58
+ : Seg extends `*${infer Spec}`
59
+ ? { [K in ParseParamSpec<Spec>[0] extends '' ? 'rest' : ParseParamSpec<Spec>[0]]: string }
60
+ : Seg extends `:${infer Spec}?`
61
+ ? { [K in ParseParamSpec<Spec>[0]]?: ParseParamSpec<Spec>[1] | undefined }
62
+ : Seg extends `:${infer Spec}`
63
+ ? { [K in ParseParamSpec<Spec>[0]]: ParseParamSpec<Spec>[1] }
64
+ : unknown
65
+
66
+ type MergeParams<A, B> = unknown extends B
67
+ ? A
68
+ : { [K in keyof (Omit<A, keyof B> & B)]: (Omit<A, keyof B> & B)[K] }
69
+
49
70
  type ExtractRouteParamsRec<Path extends string, Acc = {}> =
50
71
  Path extends `${infer Seg}/${infer Rest}`
51
72
  ? ExtractRouteParamsRec<Rest, Seg extends '' ? Acc : MergeParams<Acc, SegmentParam<Seg>>>
@@ -53,7 +74,7 @@ type ExtractRouteParamsRec<Path extends string, Acc = {}> =
53
74
  ? Acc
54
75
  : MergeParams<Acc, SegmentParam<Path>>
55
76
 
56
- /** Extracts typed route params from a Prunelle route path (`'/notices/[id]'` -> `{ id: string }`, `'/docs/[...rest]'` -> `{ rest: string }`). */
77
+ /** Extracts typed route params from a Prunelle route path (`'/notices/[id=integer]'` -> `{ id: `${number}` }`, `'/[[lang]]/about'` -> `{ lang?: string | undefined }`, `'/docs/[...rest]'` -> `{ rest: string }`). */
57
78
  export type ExtractRouteParams<Path extends string> =
58
79
  string extends Path
59
80
  ? Record<string, string>
@@ -91,6 +112,15 @@ export interface LayoutProps<Path extends string = string> {
91
112
  url: URL
92
113
  }
93
114
 
115
+ /** Props passed to a Prunelle status page (`_401.tsx`, `_403.tsx`, `_404.tsx`, `_429.tsx`, `_503.tsx`). */
116
+ export interface StatusPageProps<Path extends string = string> {
117
+ status: number
118
+ message: string
119
+ params: ExtractRouteParams<Path>
120
+ locals: PrunelleLocals
121
+ url: URL
122
+ }
123
+
94
124
  export interface ServerOptions extends ServerRuntimeConfig {
95
125
  root: string
96
126
  outDir?: string | undefined
@@ -103,6 +133,8 @@ export interface ServerOptions extends ServerRuntimeConfig {
103
133
  errorSink?: ((info: ServerErrorInfo) => void) | undefined
104
134
  /** @internal The build's prerender server, which runs before the production environment exists, so plugin `requires` are not checked. */
105
135
  prerender?: boolean | undefined
136
+ /** @internal True during a `--static` export, which ships static HTML directly and must enforce plugin `requires` in production. */
137
+ static?: boolean | undefined
106
138
  }
107
139
 
108
140
  export interface RequestContext<Params = Record<string, string>> {
@@ -113,6 +145,8 @@ export interface RequestContext<Params = Record<string, string>> {
113
145
  consent: RequestConsent
114
146
  locals: PrunelleLocals
115
147
  ip?: string | undefined
148
+ /** Unique identifier for this request, echoed in the `x-request-id` response header and passed to `onError`. */
149
+ readonly requestId: string
116
150
  /** The region a `data-pru-target` link or form asked for alone (`x-pru-region`): `load()` can skip the data the others show. */
117
151
  readonly region?: string | undefined
118
152
  json: (data: unknown, init?: ResponseInit) => Response
@@ -129,7 +163,7 @@ export type Middleware = (ctx: RequestContext, next: () => Promise<Response>) =>
129
163
  export type PrunelleServer = ReturnType<typeof Bun.serve>
130
164
 
131
165
  export interface PrunelleApp {
132
- handle: (request: Request, remoteIp?: string) => Promise<Response>
166
+ handle: (request: Request, remoteIp?: string, disableTimeout?: () => void) => Promise<Response>
133
167
  serve: (port?: number, hostname?: string) => PrunelleServer
134
168
  /** @internal Swaps this app's handlers into a server another app started, with no dropped connection: `prunelle start` reloads a new build with it. */
135
169
  reloadInto?: (server: PrunelleServer) => void
@@ -158,6 +192,7 @@ export interface EmbeddedServerConfig extends ServerRuntimeConfig {
158
192
  nodeEnv?: string | undefined
159
193
  errorSink?: ((info: ServerErrorInfo) => void) | undefined
160
194
  prerender?: boolean | undefined
195
+ static?: boolean | undefined
161
196
  }
162
197
 
163
198
  export const MIME: Record<string, string> = {
@@ -210,6 +245,7 @@ export interface RequestContextOptions {
210
245
  /** The parsed `request.url`, when the caller already has it. */
211
246
  url?: URL | undefined
212
247
  consent?: NormalizedConsentConfig | undefined
248
+ requestId?: string | undefined
213
249
  }
214
250
 
215
251
  // None of these read the request, so every context shares them.
@@ -230,8 +266,25 @@ const text: RequestContext['text'] = (body, init) => {
230
266
  headers.set('content-length', String(Buffer.byteLength(body, 'utf8')))
231
267
  return new Response(body, { ...init, headers })
232
268
  }
269
+ export interface DeniedInfo {
270
+ status: number
271
+ message: string
272
+ fieldErrors?: Record<string, string> | undefined
273
+ }
274
+
275
+ const DENIED_RESPONSES = new WeakMap<Response, DeniedInfo>()
276
+
277
+ /** Metadata attached to a `Response` produced by `ctx.deny()`. */
278
+ export function getDeniedInfo(res: Response): DeniedInfo | undefined {
279
+ return DENIED_RESPONSES.get(res)
280
+ }
281
+
233
282
  const redirect: RequestContext['redirect'] = (location, status = 302) => new Response(null, { status, headers: { location } })
234
- const deny: RequestContext['deny'] = (status, message, fieldErrors) => Response.json({ ok: false, status, error: message, fieldErrors }, { status })
283
+ const deny: RequestContext['deny'] = (status, message, fieldErrors) => {
284
+ const res = Response.json({ ok: false, status, error: message, fieldErrors }, { status })
285
+ DENIED_RESPONSES.set(res, { status, message, fieldErrors })
286
+ return res
287
+ }
235
288
 
236
289
  /** RFC 9110 weak ETag comparison supporting `*`, comma-separated lists, and `W/` prefixes. */
237
290
  export function etagMatches(ifNoneMatch: string | null, etag: string): boolean {
@@ -258,15 +311,21 @@ export function makeRequestContext(
258
311
  const remoteIp = opts?.remoteIp
259
312
  const consentConfig = opts?.consent
260
313
  let cachedConsent: RequestConsent | undefined
314
+ let cachedConsentRaw: string | undefined
261
315
  const cookieStore = new CookieStore(
262
316
  request.headers.get('cookie'),
263
317
  isHttpsRequest(request, trustProxy),
264
318
  category => getConsent().has(category),
265
319
  )
266
320
  const getConsent = (): RequestConsent => {
267
- cachedConsent ??= createRequestConsent(consentConfig !== undefined ? cookieStore.get(consentConfig.cookieName) : undefined, consentConfig)
321
+ const raw = consentConfig !== undefined ? cookieStore.get(consentConfig.cookieName) : undefined
322
+ if (cachedConsent === undefined || raw !== cachedConsentRaw) {
323
+ cachedConsentRaw = raw
324
+ cachedConsent = createRequestConsent(raw, consentConfig)
325
+ }
268
326
  return cachedConsent
269
327
  }
328
+ const requestId = opts?.requestId ?? resolveFallbackRequestId(request, trustProxy)
270
329
  let cachedIp: string | undefined
271
330
  let ipComputed = false
272
331
  const ctx: RequestContext = {
@@ -278,6 +337,7 @@ export function makeRequestContext(
278
337
  return getConsent()
279
338
  },
280
339
  locals: {},
340
+ requestId,
281
341
  get ip() {
282
342
  if (!ipComputed) {
283
343
  ipComputed = true
@@ -302,15 +362,24 @@ export function makeRequestContext(
302
362
 
303
363
  /** True when the client sent or asked for JSON: such requests get JSON errors, not pages. */
304
364
  export function wantsJson(request: Request): boolean {
305
- return (request.headers.get('accept') ?? '').includes('application/json')
306
- || (request.headers.get('content-type') ?? '').includes('application/json')
365
+ return (request.headers.get('accept') ?? '').toLowerCase().includes('application/json')
366
+ || (request.headers.get('content-type') ?? '').toLowerCase().includes('application/json')
367
+ }
368
+
369
+ /** True when the client explicitly accepts HTML and does not ask for JSON (e.g. browser navigation). */
370
+ export function acceptsHtml(request: Request): boolean {
371
+ if (wantsJson(request))
372
+ return false
373
+ return (request.headers.get('accept') ?? '').toLowerCase().includes('text/html')
307
374
  }
308
375
 
376
+ const PUBLIC_CACHE_RE = /\bpublic\b/i
377
+
309
378
  /** Enforces `maxBytes` on incoming request bodies (both Content-Length and streaming body reads). */
310
379
  export async function enforceRequestBodyLimit(
311
380
  request: Request,
312
381
  maxBytes: number,
313
- ): Promise<{ ok: true, request: Request } | { ok: false }> {
382
+ ): Promise<{ ok: true, request: Request } | { ok: false, aborted?: true }> {
314
383
  if (request.method === 'GET' || request.method === 'HEAD' || !Number.isFinite(maxBytes) || maxBytes <= 0)
315
384
  return { ok: true, request }
316
385
 
@@ -332,9 +401,16 @@ export async function enforceRequestBodyLimit(
332
401
  let total = 0
333
402
  try {
334
403
  while (true) {
335
- const { done, value } = await reader.read()
336
- if (done)
404
+ let read: Awaited<ReturnType<typeof reader.read>>
405
+ try {
406
+ read = await reader.read()
407
+ }
408
+ catch {
409
+ return { ok: false, aborted: true }
410
+ }
411
+ if (read.done)
337
412
  break
413
+ const { value } = read
338
414
  total += value.byteLength
339
415
  if (total > maxBytes) {
340
416
  try {
@@ -350,12 +426,21 @@ export async function enforceRequestBodyLimit(
350
426
  reader.releaseLock()
351
427
  }
352
428
 
353
- const combined = new Uint8Array(total)
354
- let offset = 0
355
- for (let i = 0; i < chunks.length; i++) {
356
- const chunk = chunks[i]!
357
- combined.set(chunk, offset)
358
- offset += chunk.byteLength
429
+ let combined: Uint8Array<ArrayBuffer>
430
+ if (chunks.length === 1) {
431
+ const only = chunks[0]!
432
+ combined = only.buffer instanceof ArrayBuffer && only.byteOffset === 0 && only.byteLength === only.buffer.byteLength
433
+ ? only as Uint8Array<ArrayBuffer>
434
+ : new Uint8Array(only)
435
+ }
436
+ else {
437
+ combined = new Uint8Array(total)
438
+ let offset = 0
439
+ for (let i = 0; i < chunks.length; i++) {
440
+ const chunk = chunks[i]!
441
+ combined.set(chunk, offset)
442
+ offset += chunk.byteLength
443
+ }
359
444
  }
360
445
 
361
446
  headers.delete('transfer-encoding')
@@ -396,23 +481,35 @@ export function applyHstsHeader(
396
481
  }
397
482
  }
398
483
 
399
- /** Adds the pending cookies (when any) and the security headers the response does not set itself. */
484
+ /** Adds the pending cookies (when any), security headers, `x-request-id`, and dev `Server-Timing`. */
400
485
  export function finalizeResponse(
401
486
  res: Response,
402
487
  cookieStore: CookieStore | undefined,
403
488
  entries: readonly [string, string][],
489
+ requestId?: string,
490
+ serverTiming?: string,
404
491
  ): Response {
405
492
  const hasCookies = cookieStore?.hasChanges === true
406
- if (!hasCookies && entries.length === 0)
493
+ const hasRequestId = requestId !== undefined
494
+ const hasTiming = serverTiming !== undefined && serverTiming !== ''
495
+ if (!hasCookies && entries.length === 0 && !hasRequestId && !hasTiming)
407
496
  return res
408
497
 
409
498
  const apply = (h: Headers): void => {
410
- if (hasCookies)
499
+ if (hasCookies) {
411
500
  cookieStore!.applyTo(h)
501
+ const cc = h.get('cache-control')
502
+ if (cc !== null && PUBLIC_CACHE_RE.test(cc))
503
+ h.set('cache-control', 'private, no-store')
504
+ }
412
505
  for (const [k, v] of entries) {
413
506
  if (!h.has(k))
414
507
  h.set(k, v)
415
508
  }
509
+ if (hasRequestId && !h.has('x-request-id'))
510
+ h.set('x-request-id', requestId)
511
+ if (hasTiming)
512
+ h.set('server-timing', serverTiming)
416
513
  }
417
514
  // Mutate in place (no copy in Bun); a response with immutable headers (e.g. a proxied upstream fetch) is rebuilt.
418
515
  try {