prunelle 0.1.1 → 0.6.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 (120) hide show
  1. package/llms.txt +130 -38
  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 +92 -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 +561 -0
  27. package/src/cli/check-links.ts +632 -0
  28. package/src/cli/check.ts +75 -20
  29. package/src/cli/commands.ts +85 -4
  30. package/src/cli/docs.ts +402 -0
  31. package/src/cli/inspect.ts +103 -14
  32. package/src/cli/mcp-tools.ts +490 -0
  33. package/src/cli/mcp.ts +205 -0
  34. package/src/cli/new.ts +2 -2
  35. package/src/cli/render.ts +421 -0
  36. package/src/cli/upgrade-names.ts +73 -13
  37. package/src/cli/upgrade.ts +137 -16
  38. package/src/compiler/analyze.ts +42 -9
  39. package/src/compiler/browser-globals.ts +140 -17
  40. package/src/compiler/cacheability.ts +636 -0
  41. package/src/compiler/compliance-rgaa.ts +508 -0
  42. package/src/compiler/compliance.ts +241 -289
  43. package/src/compiler/data-keys.ts +199 -192
  44. package/src/compiler/dev-source.ts +87 -0
  45. package/src/compiler/dom-attrs.ts +138 -65
  46. package/src/compiler/dom.ts +517 -442
  47. package/src/compiler/expr-context.ts +167 -57
  48. package/src/compiler/mistakes.ts +4 -1
  49. package/src/compiler/props.ts +87 -36
  50. package/src/compiler/scope.ts +400 -333
  51. package/src/compiler/server-only.ts +190 -151
  52. package/src/compiler/shared.ts +40 -12
  53. package/src/compiler/signal-reads.ts +6 -2
  54. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  55. package/src/compiler/ssr.ts +218 -87
  56. package/src/dev/error-log.ts +151 -0
  57. package/src/dev/index.ts +84 -34
  58. package/src/dev/open-editor.ts +204 -0
  59. package/src/dev/protocol.ts +1 -0
  60. package/src/dev/reload.ts +5 -3
  61. package/src/dev/supervisor.ts +42 -25
  62. package/src/dev/watchers.ts +47 -11
  63. package/src/dom/action.ts +43 -20
  64. package/src/dom/attrs.ts +15 -3
  65. package/src/dom/extras.ts +28 -12
  66. package/src/dom/index.ts +26 -8
  67. package/src/dom/island.ts +35 -28
  68. package/src/dom/loop.ts +10 -9
  69. package/src/plugins/config.ts +8 -7
  70. package/src/plugins/index.ts +2 -2
  71. package/src/plugins/load.ts +26 -7
  72. package/src/plugins/order.ts +38 -1
  73. package/src/plugins/public.ts +5 -2
  74. package/src/plugins/services.ts +81 -0
  75. package/src/plugins/types.ts +34 -0
  76. package/src/reactivity/graph.ts +10 -0
  77. package/src/reactivity/index.ts +24 -16
  78. package/src/reactivity/selector.ts +31 -4
  79. package/src/reactivity/store.ts +45 -13
  80. package/src/server/action-protect.ts +198 -0
  81. package/src/server/action-registry.ts +1 -1
  82. package/src/server/action.ts +82 -27
  83. package/src/server/assets.ts +34 -2
  84. package/src/server/compress.ts +91 -9
  85. package/src/server/document.ts +25 -10
  86. package/src/server/errors.ts +303 -65
  87. package/src/server/form-schema.ts +343 -0
  88. package/src/server/health.ts +244 -0
  89. package/src/server/http.ts +131 -32
  90. package/src/server/index.ts +231 -261
  91. package/src/server/loader.ts +5 -0
  92. package/src/server/param-matchers.ts +112 -0
  93. package/src/server/plugin-host.ts +123 -88
  94. package/src/server/public.ts +3 -3
  95. package/src/server/rate-limit.ts +58 -35
  96. package/src/server/request-body.ts +1 -1
  97. package/src/server/route-cache.ts +423 -0
  98. package/src/server/route-table.ts +339 -8
  99. package/src/server/router.ts +125 -40
  100. package/src/server/routing.ts +196 -63
  101. package/src/server/security.ts +208 -32
  102. package/src/server/serve-handlers.ts +21 -7
  103. package/src/server/start.ts +60 -16
  104. package/src/server/static-dir.ts +61 -8
  105. package/src/server/stream.ts +41 -22
  106. package/src/ssr/context.ts +85 -3
  107. package/src/ssr/index.ts +130 -3
  108. package/src/ssr/region.ts +31 -19
  109. package/src/test/browser.ts +28 -13
  110. package/src/test/index.ts +97 -12
  111. package/src/ts-plugin/diagnostics.ts +505 -0
  112. package/src/ts-plugin/fixes.ts +364 -0
  113. package/src/ts-plugin/index.ts +194 -0
  114. package/templates/_shared/AGENTS.md +2 -2
  115. package/templates/_shared/mcp.json +11 -0
  116. package/templates/_shared/src/routes/legal.tsx +5 -0
  117. package/templates/_shared/tsconfig.json +5 -0
  118. package/templates/blog/prunelle.config.ts +1 -1
  119. package/templates/blog/src/routes/index.tsx +4 -0
  120. package/ts-plugin.cjs +4277 -0
@@ -2,7 +2,7 @@
2
2
 
3
3
  import type { BuildManifest } from '../build/index'
4
4
  import type { PrunelleChild } from '../jsx-runtime'
5
- import type { ServerErrorInfo, ServerRuntimeConfig } from '../plugins/index'
5
+ import type { ServerErrorInfo, ServerRuntimeConfig, ServiceKey } from '../plugins/index'
6
6
  import type { NormalizedConsentConfig, RequestConsent } from './consent'
7
7
  import type { Cookies } from './cookies'
8
8
  import type { PrunelleLocals } from './index'
@@ -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,10 +163,12 @@ 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
170
+ /** Looks up a server-scoped plugin service registered during `server(api)` (e.g. `JOBS_SERVICE`). */
171
+ inject?: <T>(key: ServiceKey<T>) => T | undefined
136
172
  /** Closes active long-lived streams (such as SSE) before `server.stop()` drains normal in-flight HTTP requests. */
137
173
  closeStreams?: () => Promise<void>
138
174
  /** Runs plugin shutdown hooks and releases timers/resources (safe to call multiple times). */
@@ -158,6 +194,7 @@ export interface EmbeddedServerConfig extends ServerRuntimeConfig {
158
194
  nodeEnv?: string | undefined
159
195
  errorSink?: ((info: ServerErrorInfo) => void) | undefined
160
196
  prerender?: boolean | undefined
197
+ static?: boolean | undefined
161
198
  }
162
199
 
163
200
  export const MIME: Record<string, string> = {
@@ -210,6 +247,7 @@ export interface RequestContextOptions {
210
247
  /** The parsed `request.url`, when the caller already has it. */
211
248
  url?: URL | undefined
212
249
  consent?: NormalizedConsentConfig | undefined
250
+ requestId?: string | undefined
213
251
  }
214
252
 
215
253
  // None of these read the request, so every context shares them.
@@ -230,8 +268,25 @@ const text: RequestContext['text'] = (body, init) => {
230
268
  headers.set('content-length', String(Buffer.byteLength(body, 'utf8')))
231
269
  return new Response(body, { ...init, headers })
232
270
  }
271
+ export interface DeniedInfo {
272
+ status: number
273
+ message: string
274
+ fieldErrors?: Record<string, string> | undefined
275
+ }
276
+
277
+ const DENIED_RESPONSES = new WeakMap<Response, DeniedInfo>()
278
+
279
+ /** Metadata attached to a `Response` produced by `ctx.deny()`. */
280
+ export function getDeniedInfo(res: Response): DeniedInfo | undefined {
281
+ return DENIED_RESPONSES.get(res)
282
+ }
283
+
233
284
  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 })
285
+ const deny: RequestContext['deny'] = (status, message, fieldErrors) => {
286
+ const res = Response.json({ ok: false, status, error: message, fieldErrors }, { status })
287
+ DENIED_RESPONSES.set(res, { status, message, fieldErrors })
288
+ return res
289
+ }
235
290
 
236
291
  /** RFC 9110 weak ETag comparison supporting `*`, comma-separated lists, and `W/` prefixes. */
237
292
  export function etagMatches(ifNoneMatch: string | null, etag: string): boolean {
@@ -258,15 +313,21 @@ export function makeRequestContext(
258
313
  const remoteIp = opts?.remoteIp
259
314
  const consentConfig = opts?.consent
260
315
  let cachedConsent: RequestConsent | undefined
316
+ let cachedConsentRaw: string | undefined
261
317
  const cookieStore = new CookieStore(
262
318
  request.headers.get('cookie'),
263
319
  isHttpsRequest(request, trustProxy),
264
320
  category => getConsent().has(category),
265
321
  )
266
322
  const getConsent = (): RequestConsent => {
267
- cachedConsent ??= createRequestConsent(consentConfig !== undefined ? cookieStore.get(consentConfig.cookieName) : undefined, consentConfig)
323
+ const raw = consentConfig !== undefined ? cookieStore.get(consentConfig.cookieName) : undefined
324
+ if (cachedConsent === undefined || raw !== cachedConsentRaw) {
325
+ cachedConsentRaw = raw
326
+ cachedConsent = createRequestConsent(raw, consentConfig)
327
+ }
268
328
  return cachedConsent
269
329
  }
330
+ const requestId = opts?.requestId ?? resolveFallbackRequestId(request, trustProxy)
270
331
  let cachedIp: string | undefined
271
332
  let ipComputed = false
272
333
  const ctx: RequestContext = {
@@ -278,6 +339,7 @@ export function makeRequestContext(
278
339
  return getConsent()
279
340
  },
280
341
  locals: {},
342
+ requestId,
281
343
  get ip() {
282
344
  if (!ipComputed) {
283
345
  ipComputed = true
@@ -302,15 +364,24 @@ export function makeRequestContext(
302
364
 
303
365
  /** True when the client sent or asked for JSON: such requests get JSON errors, not pages. */
304
366
  export function wantsJson(request: Request): boolean {
305
- return (request.headers.get('accept') ?? '').includes('application/json')
306
- || (request.headers.get('content-type') ?? '').includes('application/json')
367
+ return (request.headers.get('accept') ?? '').toLowerCase().includes('application/json')
368
+ || (request.headers.get('content-type') ?? '').toLowerCase().includes('application/json')
369
+ }
370
+
371
+ /** True when the client explicitly accepts HTML and does not ask for JSON (e.g. browser navigation). */
372
+ export function acceptsHtml(request: Request): boolean {
373
+ if (wantsJson(request))
374
+ return false
375
+ return (request.headers.get('accept') ?? '').toLowerCase().includes('text/html')
307
376
  }
308
377
 
378
+ const PUBLIC_CACHE_RE = /\bpublic\b/i
379
+
309
380
  /** Enforces `maxBytes` on incoming request bodies (both Content-Length and streaming body reads). */
310
381
  export async function enforceRequestBodyLimit(
311
382
  request: Request,
312
383
  maxBytes: number,
313
- ): Promise<{ ok: true, request: Request } | { ok: false }> {
384
+ ): Promise<{ ok: true, request: Request } | { ok: false, aborted?: true }> {
314
385
  if (request.method === 'GET' || request.method === 'HEAD' || !Number.isFinite(maxBytes) || maxBytes <= 0)
315
386
  return { ok: true, request }
316
387
 
@@ -332,9 +403,16 @@ export async function enforceRequestBodyLimit(
332
403
  let total = 0
333
404
  try {
334
405
  while (true) {
335
- const { done, value } = await reader.read()
336
- if (done)
406
+ let read: Awaited<ReturnType<typeof reader.read>>
407
+ try {
408
+ read = await reader.read()
409
+ }
410
+ catch {
411
+ return { ok: false, aborted: true }
412
+ }
413
+ if (read.done)
337
414
  break
415
+ const { value } = read
338
416
  total += value.byteLength
339
417
  if (total > maxBytes) {
340
418
  try {
@@ -350,12 +428,21 @@ export async function enforceRequestBodyLimit(
350
428
  reader.releaseLock()
351
429
  }
352
430
 
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
431
+ let combined: Uint8Array<ArrayBuffer>
432
+ if (chunks.length === 1) {
433
+ const only = chunks[0]!
434
+ combined = only.buffer instanceof ArrayBuffer && only.byteOffset === 0 && only.byteLength === only.buffer.byteLength
435
+ ? only as Uint8Array<ArrayBuffer>
436
+ : new Uint8Array(only)
437
+ }
438
+ else {
439
+ combined = new Uint8Array(total)
440
+ let offset = 0
441
+ for (let i = 0; i < chunks.length; i++) {
442
+ const chunk = chunks[i]!
443
+ combined.set(chunk, offset)
444
+ offset += chunk.byteLength
445
+ }
359
446
  }
360
447
 
361
448
  headers.delete('transfer-encoding')
@@ -396,23 +483,35 @@ export function applyHstsHeader(
396
483
  }
397
484
  }
398
485
 
399
- /** Adds the pending cookies (when any) and the security headers the response does not set itself. */
486
+ /** Adds the pending cookies (when any), security headers, `x-request-id`, and dev `Server-Timing`. */
400
487
  export function finalizeResponse(
401
488
  res: Response,
402
489
  cookieStore: CookieStore | undefined,
403
490
  entries: readonly [string, string][],
491
+ requestId?: string,
492
+ serverTiming?: string,
404
493
  ): Response {
405
494
  const hasCookies = cookieStore?.hasChanges === true
406
- if (!hasCookies && entries.length === 0)
495
+ const hasRequestId = requestId !== undefined
496
+ const hasTiming = serverTiming !== undefined && serverTiming !== ''
497
+ if (!hasCookies && entries.length === 0 && !hasRequestId && !hasTiming)
407
498
  return res
408
499
 
409
500
  const apply = (h: Headers): void => {
410
- if (hasCookies)
501
+ if (hasCookies) {
411
502
  cookieStore!.applyTo(h)
503
+ const cc = h.get('cache-control')
504
+ if (cc !== null && PUBLIC_CACHE_RE.test(cc))
505
+ h.set('cache-control', 'private, no-store')
506
+ }
412
507
  for (const [k, v] of entries) {
413
508
  if (!h.has(k))
414
509
  h.set(k, v)
415
510
  }
511
+ if (hasRequestId && !h.has('x-request-id'))
512
+ h.set('x-request-id', requestId)
513
+ if (hasTiming)
514
+ h.set('server-timing', serverTiming)
416
515
  }
417
516
  // Mutate in place (no copy in Bun); a response with immutable headers (e.g. a proxied upstream fetch) is rebuilt.
418
517
  try {