prunelle 0.9.0 → 0.10.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 (96) hide show
  1. package/llms.txt +18 -18
  2. package/package.json +2 -2
  3. package/src/a11y/declaration.ts +4 -7
  4. package/src/build/bundle.ts +6 -2
  5. package/src/build/index.ts +3 -1
  6. package/src/build/island-promote.ts +42 -2
  7. package/src/build/islands.ts +59 -8
  8. package/src/build/manifest.ts +98 -0
  9. package/src/build/plugin-host.ts +11 -1
  10. package/src/build/prerender.ts +6 -1
  11. package/src/build/reach.ts +4 -3
  12. package/src/build/resolve.ts +5 -1
  13. package/src/build/routes.ts +18 -0
  14. package/src/cli/check-forms.ts +8 -0
  15. package/src/cli/check-links.ts +14 -5
  16. package/src/cli/check.ts +12 -6
  17. package/src/cli/commands.ts +5 -3
  18. package/src/cli/form-opaque-children.ts +40 -0
  19. package/src/compiler/analyze.ts +20 -14
  20. package/src/compiler/cacheability-private.ts +13 -3
  21. package/src/compiler/compliance-contrast.ts +48 -10
  22. package/src/compiler/compliance-rules.ts +72 -0
  23. package/src/compiler/compliance.ts +6 -66
  24. package/src/compiler/dom-attrs.ts +178 -22
  25. package/src/compiler/dom.ts +31 -44
  26. package/src/compiler/emit.ts +17 -6
  27. package/src/compiler/expr-context.ts +260 -207
  28. package/src/compiler/props-body.ts +263 -21
  29. package/src/compiler/props.ts +155 -5
  30. package/src/compiler/signal-reads.ts +142 -29
  31. package/src/compiler/spread-handlers.ts +25 -13
  32. package/src/compiler/ssr-emit.ts +3 -3
  33. package/src/compiler/ssr-helpers.ts +0 -5
  34. package/src/compiler/ssr.ts +4 -2
  35. package/src/dev/host-check.ts +2 -1
  36. package/src/dev/reload.ts +4 -1
  37. package/src/dom/attrs.ts +93 -25
  38. package/src/dom/extras.ts +89 -49
  39. package/src/dom/field-marks.ts +9 -1
  40. package/src/dom/index.ts +19 -13
  41. package/src/dom/loop.ts +259 -188
  42. package/src/dom/prefetch.ts +4 -1
  43. package/src/dom/regions.ts +25 -8
  44. package/src/dom/swap.ts +11 -10
  45. package/src/dom/trusted.ts +4 -4
  46. package/src/eco/declaration.ts +5 -1
  47. package/src/eco/index.ts +3 -0
  48. package/src/index.ts +3 -2
  49. package/src/plugins/config.ts +1 -1
  50. package/src/plugins/public.ts +4 -0
  51. package/src/plugins/types.ts +8 -1
  52. package/src/reactivity/graph.ts +244 -41
  53. package/src/reactivity/hmr.ts +14 -3
  54. package/src/reactivity/index.ts +219 -235
  55. package/src/reactivity/resource.ts +17 -3
  56. package/src/reactivity/seed.ts +118 -16
  57. package/src/reactivity/selector.ts +85 -47
  58. package/src/reactivity/server-seed.ts +31 -23
  59. package/src/reactivity/store.ts +316 -136
  60. package/src/server/action-protect.ts +3 -0
  61. package/src/server/action-registry.ts +5 -1
  62. package/src/server/cache-invalidation.ts +4 -3
  63. package/src/server/compress.ts +52 -17
  64. package/src/server/consent.ts +5 -3
  65. package/src/server/cookies.ts +27 -8
  66. package/src/server/cors.ts +98 -0
  67. package/src/server/csp-report.ts +8 -4
  68. package/src/server/health.ts +9 -0
  69. package/src/server/http.ts +3 -1
  70. package/src/server/index.ts +25 -13
  71. package/src/server/loader.ts +1 -0
  72. package/src/server/plugin-host.ts +41 -9
  73. package/src/server/plugin-route-shadow.ts +24 -0
  74. package/src/server/rate-limit.ts +13 -3
  75. package/src/server/region.ts +19 -2
  76. package/src/server/request-handler.ts +58 -22
  77. package/src/server/request-log.ts +1 -1
  78. package/src/server/route-cache.ts +14 -2
  79. package/src/server/route-table.ts +21 -11
  80. package/src/server/router.ts +2 -1
  81. package/src/server/routing.ts +100 -42
  82. package/src/server/sanitize-html.ts +3 -1
  83. package/src/server/serve-handlers.ts +10 -4
  84. package/src/server/served-file.ts +19 -14
  85. package/src/server/shared-store.ts +10 -1
  86. package/src/server/static-dir.ts +21 -3
  87. package/src/server/webhook.ts +6 -4
  88. package/src/ssr/context.ts +149 -51
  89. package/src/ssr/index.ts +41 -46
  90. package/src/ssr/region.ts +9 -3
  91. package/src/style.ts +12 -5
  92. package/src/test/browser.ts +3 -1
  93. package/src/test/build-reuse.ts +22 -7
  94. package/src/test/index.ts +7 -3
  95. package/src/ts-plugin/diagnostics.ts +56 -18
  96. package/ts-plugin.cjs +465 -131
package/llms.txt CHANGED
@@ -19,12 +19,12 @@
19
19
  - Refused: `client:*`/`use:*`/`class:list`/`set:html` directives, a hook or signal imported from `react`, `preact`, `solid-js`, `vue` or `svelte` (the fix names the prunelle form), an import that resolves to nothing (`prunelle check`), `<slot>` (take `children`), a leading `---` frontmatter block, `'use client'`/`'use server'`, Promises, functions, signals or plain objects in JSX text/attrs, and route exports other frameworks read (`getStaticProps`, `getStaticPaths`, `generateStaticParams`, `metadata`, `revalidate`, a lowercase `get`), each naming the prunelle export. The error for an Astro or Next habit ends with its guide, `docs/getting-started/coming-from-astro` or `coming-from-next`, which maps that framework's concepts to prunelle's.
20
20
  - Literal `javascript:`/`vbscript:`/non-image `data:` URLs warn and are stripped; a spread rendered on the server drops every `on*` attribute, and a spread in an island binds an `on*` prop only when it is a function (a string `on*` is dropped); both drop `innerHTML`, `srcdoc` and `javascript:`/`vbscript:` URLs, and `dangerouslySetInnerHTML` in a spread throws.
21
21
  - **Signals, Context & IDs (`prunelle`)**:
22
- - `const count = signal(0)` (`.value` read/write, `.peek()` untracked), `computed(() => ...)`, `effect(() => ...)` (return cleanup, never `async`; skipped while an island renders on the server, so derive values with `computed`), `batch(() => ...)`, `untrack(() => ...)`, `root(dispose => ...)`, `onMount(() => ...)` (runs after DOM attach; return cleanup), `onCleanup(() => ...)`, `getOwner()`, `selector(() => id.value)` (O(1) selection), `store(obj)` + `snapshot(s)`.
23
- - `const posts = resource(() => page.value, (page, { signal }) => fetch(`/api/posts?page=${page}`, { signal }).then(r => r.json()), { initial? })` loads async data in an island: `posts.value` (the last value, kept while the next run loads or fails), `posts.loading.value`, `posts.error.value` (an `Error`), `posts.refetch()`. It re-runs when the source changes, aborting the run it replaces and discarding its late answer; a source of `undefined` waits. An action as the fetcher (`resource(() => ({ page: page.value }), listPosts)`) gives its typed `data` to `value` and its failure to `error`. `resource(({ signal }) => ...)` alone runs once, tracking nothing it reads. It never fetches on the server: the island renders `loading`, or `initial` (from `load()`), which the browser keeps until the source changes. 0 B on pages that do not use it.
24
- - A local signal read without `.value` in JSX, an `if`/ternary/loop test or `!`, and `const { value } = count`, fail compile. To let a child mutate parent state, pass the signal itself (`<Modal open={isOpen} />`).
25
- - Context: `const Ctx = createContext(defaultValue)`, `<Ctx.Provider value={v}>` or `provideContext(Ctx, v, fn)`, `useContext(Ctx)`. `useId(prefix = 'k')` gives deterministic hydration-safe IDs, scoped per island or SSR request.
22
+ - `const count = signal(0, { equals? })` (`.value` read/write, `.peek()` untracked), `computed(() => ..., { equals? })`, `effect(() => ...)` (return cleanup, never `async`; skipped while an island renders on the server, so derive values with `computed`), `batch(() => ...)`, `untrack(() => ...)`, `root(dispose => ...)`, `onMount(() => ...)` (runs after DOM attach; return cleanup), `onCleanup(() => ...)`, `getOwner()` (`Owner | undefined`) + `runWithOwner(owner, fn)`, `selector(() => id.value, fn?)` (O(1) selection, or custom matcher `fn(key, value)`), `store(obj)` + `snapshot(s)` + `reconcile(target, next)` (structurally diffs plain objects/arrays into a store inside `batch()`).
23
+ - `const posts = resource(() => page.value, (page, { signal }) => fetch(`/api/posts?page=${page}`, { signal }).then(r => r.json()), { initial? })` loads async data in an island: `posts.value` (the last value, kept while the next run loads or fails), `posts.loading.value`, `posts.error.value` (an `Error`, cleared when a new fetch starts or the source is `undefined`), `posts.refetch()`, `posts.mutate(next)` (writes directly to `posts.value` and participates in `useAction({ optimistic })` rollback/rebase). It re-runs when the source changes, aborting the run it replaces and discarding its late answer; a source of `undefined` waits. An action as the fetcher (`resource(() => ({ page: page.value }), listPosts)`) gives its typed `data` to `value` and its failure to `error`. `resource(({ signal }) => ...)` alone runs once, tracking nothing it reads. It never fetches on the server: the island renders `loading`, or `initial` (from `load()`), which the browser keeps until the source changes. 0 B on pages that do not use it.
24
+ - A local signal, computed, `resource`, or signal-valued hook field (`resource.loading`/`error`, `useAction` `pending`/`error`/`fieldErrors`/`data`/`progress`, `useLive` `status`/`last`/`error`) read without `.value` in JSX, an `if`/ternary/loop test or `!`, and `const { value } = count`, fail compile. Destructuring a `store()`, snapshotting `const x = sig.value` at a component's top level and rendering `{x}` in JSX, and mutating a destructured prop warn in browser-reachable components. To let a child mutate parent state, pass the signal itself (`<Modal open={isOpen} />`).
25
+ - Context: `const Ctx = createContext(defaultValue)`, `<Ctx.Provider value={v}>` or `provideContext(Ctx, v, fn)`, `useContext(Ctx)`. `useId(prefix = 'k')` gives deterministic hydration-safe IDs, scoped per island or SSR request (a region answer adds its own prefix, so ids stay unique after a swap or an append).
26
26
  - **Reactive props**: Destructuring props (`function Badge({ count = 0, ...rest }: Props)`) stays reactive in client components (in the parameter list only: `const { a } = props` in the body reads once, and a browser component doing it is warned), and a default beyond a literal or a name (`items = []`, `id = useId()`) runs once per call; server-rendered children inside islands are preserved via `<pru-slot>`.
27
- - **Automatic islands**: a component using reactive primitives (`signal`, `computed`, `effect`, `onMount`, `store`, `selector`, `resource`), DOM `on*` handlers/`ref`, or imported reactive module state becomes an island, decided per component. Islands importing the same module share its signals and stores, whatever their `$hydrate` modes; the module gives the first value. To start it from the request (a cart count from `load()`), pass it as a prop and write it while the island renders (`items.value = count`): on the server the write lands in a per-request copy that the islands after it read, the page carries the paths it wrote in an `s` attribute on that island, and the browser sets them on the module's `const x = signal(…)` or `store(…)` when that module first runs, before any island hydrates (JSON values only, a BigInt, cycle, Date or `__proto__` key throws naming the signal; the page carries nothing when no island writes, and the build ships the helper, about 130 B gzip, only in an app where a module writes imported state outside an event handler, `onMount` or `effect`). An island writing a signal made elsewhere (in `load()` or a function) while it renders on the server throws.
27
+ - **Automatic islands**: a component using reactive primitives (`signal`, `computed`, `effect`, `onMount`, `onCleanup`, `store`, `selector`, `useAction`, `resource`), DOM `on*` handlers/`ref`, or imported reactive module state becomes an island, decided per component. Islands importing the same module share its signals, stores and resources, whatever their `$hydrate` modes; the module gives the first value. To start it from the request (a cart count from `load()`), pass it as a prop and write it while the island renders (`items.value = count`): on the server the write lands in a per-request copy that the islands after it read, the page carries the paths it wrote in an `s` attribute on that island, and the browser sets them on the module's `const x = signal(…)` or `store(…)` when that module first runs, before any island hydrates, and re-applies them when `@prunellejs/spa` or `<Region>` swaps new islands into the page (JSON values only, a BigInt, cycle, Date or `__proto__` key throws naming the signal; the page carries nothing when no island writes, and the build ships the helper only in an app where a module writes imported state outside an event handler, `onMount` or `effect`). An island writing a signal made elsewhere (in `load()` or a function) while it renders on the server throws.
28
28
  - A static export beside an island stays static. A component that needs the browser is an island of its own wherever server code renders it as a tag, same file included: the page around it stays static, and its chunk keeps only the code of the file it reaches, so an async page importing server code can render a local widget.
29
29
  - A same-file helper that needs the browser makes each component calling it an island; a primitive called at a file's top level makes every component of the file one.
30
30
  - `<Head>`/`<Suspense>` in an island fail compile (`<Catch>` works in both). An island reading a context provided outside it throws in SSR: pass the value as a prop. Server children handed to an island render before it, in the page's scope.
@@ -43,36 +43,36 @@
43
43
  - Special files: `_layout.tsx` (nested outer→inner, receives `{ children, params, locals, url }`, server-only), `_middleware.ts` (`(ctx, next) => Response`, outer→inner), `_error.tsx` (receives `{ error }`, server-only), `_404.tsx` (server-only; also emitted as `404.html`, and as `<folder>/404.html` for static non-group folders in `--static`), and status pages `_401.tsx`, `_403.tsx`, `_429.tsx`, `_503.tsx` (receive `{ status, message, url, params, locals }`). Each needs a default export; an unsupported `_NNN.tsx` (e.g. `_418.tsx`) fails `prunelle check` and `prunelle build`.
44
44
  - `_404.tsx`, `_error.tsx` and status pages may live in any subfolder (including `(group)/`) and win over the root one for routes under it, wrapped in that folder's layouts. `ctx.deny(status, message, fieldErrors?)` renders the nearest status page (else the nearest `_error.tsx`, else clean HTML) when the request accepts HTML (`Accept: text/html`), and JSON otherwise (actions keep JSON for JS and flash + 303 for zero-JS forms).
45
45
  - Any other file under `src/routes/` must export a page, a method handler or an action (guarded by its folder's `_middleware.ts`), else `prunelle build`/`prunelle check` fail: prefix helpers or their folder with `_`.
46
- - Params, groups & optionals: `(name)/` groups routes under its `_layout.tsx` and `_middleware.ts` without adding a URL segment; `[[lang]]/about.tsx` matches `/about` and `/fr/about` (`params.lang` typed `string | undefined`); `[slug].tsx` → `params.slug`; `[...path].tsx` → `params.path` (segments joined by `/`).
46
+ - Params, groups & optionals: `(name)/` groups routes under its `_layout.tsx` and `_middleware.ts` without adding a URL segment; `[[lang]]/about.tsx` matches `/about` and `/fr/about` (`params.lang` typed `string | undefined`); `[slug].tsx` → `params.slug`; `[...path].tsx` → `params.path` (segments joined by `/`). A whole file or folder name is one of these forms: `pre-[id].tsx` (text beside a parameter) and `[[...rest]].tsx` (optional catch-all) fail `prunelle build` and `prunelle check`; use `[id].tsx`, or `[...rest].tsx` plus an `index.tsx`.
47
47
  - Matchers: `[id=integer].tsx` and `[...path=slug].tsx` match only accepted values and fall through on mismatch (built-ins: `integer` → `` `${number}` ``, `uuid` → `` `${string}-${string}-${string}-${string}-${string}` ``, `slug` → `string`; custom matchers live in `src/params/<name>.ts` exporting `match` or `default`). Unknown matchers or conflicting route patterns fail build and check naming both files; precedence is `static > matched param > param > optional > catch-all`.
48
48
  - Params arrive percent-decoded; a segment holding an encoded `/`, `\` or NUL, or a `.`/`..` segment, matches no dynamic route (404) unless a plugin catch-all route sets `encodedSlashes`, so a param is safe to join into a path. Static pages, `public/` files and `prunelle start` serving a `--static` export decode by the same rule (`/a%2fb.txt` never serves `a/b.txt`).
49
49
  - API routes: `.ts` files exporting standard `HTTP_METHOD_EXPORTS` (`GET`, `HEAD`, `POST`, `PUT`, `PATCH`, `DELETE`, `OPTIONS`) receiving `RequestContext` (`request`, `url`, `params`, `cookies`, `locals`, `ip`, `requestId`, `region`, `json()`, `text()`, `redirect(location, status?, { external? })`, `deny()`). `redirect()` stays on this site: a target on another origin throws unless `{ external: true }`, so never pass one read from the request. CSRF checks run on every method outside the safe allowlist (`GET`, `HEAD`, `OPTIONS`), trusting only the forwarded origin when `trustProxy` resolves one (or `trustedOrigins`). `export const schema = <Standard Schema>` makes the route validate its JSON body (`POST`/`PUT`/`PATCH`/`DELETE`) or query (`GET`/`HEAD`) before the handler: a failure answers 400 `{ ok: false, status: 400, error, fieldErrors, issues }` like an action, and the handler reads the parsed value as `ctx.input` (typed `unknown`: cast it to the schema's output type). `export const csrf = false` opts out of origin checks (webhooks, bearer APIs), and `prunelle check` warns `security/csrf-off` unless the route calls `verifyWebhook()`; `prunelle check` warns on it (`security/csrf-off`) until `// prunelle-ignore security/csrf-off` above the export says the route verifies its own signature or token.
50
50
  - Prerendering: `export const prerender = true` (+ `export function paths() { return ['/posts/a'] }`, required for dynamic routes and for every dynamic page under `--static`, or `prunelle build` fails; unlisted params return `404`, and so does a listed URL that answered other than `200` at build, which the build warns about). Skipped in `prunelle dev`. Static pages that read nothing from the request or clock are reported `cacheable` by `prunelle inspect` and prerender automatically with `autoPrerender: true` or `prunelle build --auto-prerender`.
51
51
  - Page language: `export const lang = 'fr'` gives that route `<html lang="fr">` when it is written in another language than `lang` in `prunelle.config.ts` (a French accessibility statement on an English site). It wins over plugin head hooks such as `@prunellejs/i18n`'s; `@prunellejs/ui` labels keep the config's language. A value that is not a language tag literal (`'french'`, `''`, a variable) fails `prunelle check` and `prunelle build`.
52
52
  - Slow responses: the server closes a request silent for 30 s (streamed pages and SSE lift it themselves); `export const idleTimeout = '5m'` (seconds or a duration string, `0` for no limit) sets it for that route's requests alone, from when its handler or page starts. A value that is not such a literal fails `prunelle check` and `prunelle build`.
53
- - Route caching: `export const cache = '1h'` (or `{ maxAge: '1h', staleWhileRevalidate?: '1d', tags?: ['posts'] }`) serves a bounded in-memory LRU render (`routeCache: { maxEntries?, maxBytes? } | false`), re-renders in the background once stale, and sends `cache-control: public, s-maxage=..., stale-while-revalidate=...` (`private, no-cache` under an app `_middleware.ts`, which may gate it; the server cache still serves it behind the middleware), with a weak `ETag` that a matching `If-None-Match` turns into a `304`. Its key leaves out `utm_*`, `gclid`, `gbraid`, `wbraid`, `dclid`, `fbclid`, `msclkid`, `mc_cid` and `mc_eid`, so a campaign link reuses the entry (a page showing them reads them uncached). A cached route (or its layout `load()` or imported local modules) reading `ctx.cookies`, `ctx.locals`, `ctx.consent`, `ctx.ip`, `Cookie`/`Authorization` or dynamic/bulk headers, `getActionError()`, `<ConsentGate>`, or passing `ctx`/`props`/`request` to a helper that does (or cannot be followed) fails `prunelle check` and `prunelle build` naming the read; at runtime the route cache also refuses to store any render that reads private request data.
54
- - `await invalidateCache('/posts/hello', '/blog/*', { tag: 'posts' })` (`prunelle/server`) drops the cached renders of a path (every host and query string, with or without its trailing slash), of a path and every page under it (`'/*'`: all), or of every route whose `cache.tags` holds the tag, so their next request renders fresh; a render already running answers its request but is not stored. Call it from server code (an action, a route, `load()`, a job, a plugin's server hook): elsewhere it throws. It drops in this process at once and, with `store`, in every other once the promise settles; it never rejects, logging a store it cannot reach. A CDN keeps its copy until its `s-maxage` runs out. `prunelle check` warns `cache/unknown-tag` on a tag no route declares.
53
+ - Route caching: `export const cache = '1h'` (or `{ maxAge: '1h', staleWhileRevalidate?: '1d', tags?: ['posts'] }`) serves a bounded in-memory LRU render (`routeCache: { maxEntries?, maxBytes? } | false`), re-renders in the background once stale, and sends `cache-control: public, s-maxage=..., stale-while-revalidate=...` (`private, no-cache` under an app `_middleware.ts` or a plugin middleware scoped to a path (`api.use(mw, { scope: '/admin' })`), which may gate it; one scoped to a request kind, like sessions, locales or analytics, keeps the public header; the server cache still serves it behind the gate and, once stale, refreshes it on the request that passes the gate rather than in the background), with a weak `ETag` that a matching `If-None-Match` turns into a `304`. Its key leaves out `utm_*`, `gclid`, `gbraid`, `wbraid`, `dclid`, `fbclid`, `msclkid`, `mc_cid` and `mc_eid`, so a campaign link reuses the entry (a page showing them reads them uncached). A cached route (or its layout `load()` or imported local modules) reading `ctx.cookies`, `ctx.locals`, `ctx.consent`, `ctx.ip`, `Cookie`/`Authorization` or dynamic/bulk headers, `getActionError()`, `<ConsentGate>`, or passing `ctx`/`props`/`request` to a helper that does (or cannot be followed) fails `prunelle check` and `prunelle build` naming the read; at runtime the route cache also refuses to store any render that reads private request data, a plugin `head` or `transformHtml` hook's read included.
54
+ - `await invalidateCache('/posts/hello', '/blog/*', { tag: 'posts' })` (`prunelle/server`) drops the cached renders of a path (every host and query string, with or without its trailing slash; read as written, so a slug `100%`, `what?` or `a#b` names its page, and a path with a query such as `'/posts?page=2'` throws), of a path and every page under it (`'/*'`: all), or of every route whose `cache.tags` holds the tag, so their next request renders fresh; a render already running answers its request but is not stored. Call it from server code (an action, a route, `load()`, a job, a plugin's server hook): elsewhere it throws. It drops in this process at once and, with `store`, in every other once the promise settles; it never rejects, logging a store it cannot reach. A CDN keeps its copy until its `s-maxage` runs out. `prunelle check` warns `cache/unknown-tag` on a tag no route declares.
55
55
  - **Streaming & Head**: `<Head><title>...</title></Head>` (innermost `<title>` wins). A page with no `<link rel="icon">` and no `public/favicon.ico` gets `<link rel="icon" href="data:,">`, so no `/favicon.ico` 404.
56
56
  - `<Suspense fallback={<p>Loading</p>} error={<p>Failed</p>}><AsyncComp /></Suspense>` streams resolved HTML inline with 0 KB external JS. It takes exactly one child; an async component anywhere but as the only child of `<Suspense>` fails build and check, even inside an async page. Boundaries nest, time out after `streamTimeout` (default `30000` ms), and their errors also fire `onError`.
57
57
  - `<Catch fallback={<p>Failed</p> | (error, retry) => ...}>` renders its fallback in place of children that throw or an awaited child that rejects, on the server (firing `onError`; nothing streams) and in an island, where it also catches a child effect's later throw and `retry()` renders the children again (there it is written as a tag: calling `Catch()` as a function throws); errors thrown by event handlers are not caught.
58
- - **Regions** (`<Region>` & `refreshRegion` from `prunelle`): `<Region name="pane" as="section" ...attrs>children</Region>` is server-only like `Head` and renders `<section data-pru-region="pane">` (a `<div>` without `as`). Its client runtime loads automatically **only on routes rendering a `<Region>`** (0 B on pages without one, no plugin needed). `<a href data-pru-target="pane">` and `<form data-pru-target="pane">` swap that region in place with the server's answer (`x-pru-region`, `x-pru-title`, `x-pru-build`, `vary: x-pru-region`); without JS the link or form loads the whole page. Supports `data-pru-append` (Load more), `data-pru-live` (debounced live GET form), `data-pru-sync="q tag"`, `[data-pru-prefetch]`, nested regions (`outer/inner`), `<form method="post" data-pru-target="...">` (follows redirects and swaps 4xx validation HTML in place), `data-persist="<key>"` via `Element.moveBefore`, lazy island runtime loading when a swap delivers `<pru-island>` onto an initially island-less page, `pru:region` event, and `await refreshRegion(name)` from `prunelle`. `prunelle check` validates `data-pru-target` names against parsed `<Region>` JSX across `src/`.
58
+ - **Regions** (`<Region>` & `refreshRegion` from `prunelle`): `<Region name="pane" as="section" ...attrs>children</Region>` is server-only like `Head` and renders `<section data-pru-region="pane">` (a `<div>` without `as`). Its client runtime loads automatically **only on routes rendering a `<Region>`** (0 B on pages without one, no plugin needed). `<a href data-pru-target="pane">` and `<form data-pru-target="pane">` swap that region in place with the server's answer (`x-pru-region`, `x-pru-title`, `x-pru-icon`, `x-pru-attrs`, `x-pru-build`, `vary: x-pru-region`): the tab takes the new title and `<link rel="icon">`, and the region element follows the new page's own attributes (`class`, `data-*`, `aria-*`); without JS the link or form loads the whole page. Supports `data-pru-append` (Load more), `data-pru-live` (debounced live GET form), `data-pru-sync="q tag"`, `[data-pru-prefetch]`, nested regions (`outer/inner`), `<form method="post" data-pru-target="...">` (follows redirects and swaps 4xx validation HTML in place), `data-persist="<key>"` via `Element.moveBefore`, lazy island runtime loading when a swap delivers `<pru-island>` onto an initially island-less page, `pru:region` event, and `await refreshRegion(name)` from `prunelle`. `prunelle check` validates `data-pru-target` names against parsed `<Region>` JSX across `src/`.
59
59
  - **Actions (`prunelle/server` & `useAction` from `prunelle`)**: `export const fn = action(standardSchema, async (input, ctx) => ..., options?)` or `action(async (ctx) => ...)`, a top-level named export so Prunelle can assign it a URL. `ctx` provides `redirect()` and `deny(status, message, fieldErrors?)`.
60
60
  - Zero-JS form: `<form action={fn} method="post">`. Array fields are coerced from checkboxes/multi-selects (`name="tags"` or `name="tags[]"` always parses as an array `tags`, and dotted names like `name="address.city"` parse into nested objects `{ address: { city } }`; a name that both holds a value and nests others, `a` beside `a.b`, answers `400` with that field in `fieldErrors`). SSR adds `required`, `minlength`/`maxlength`, `min`/`max`/`step`, `pattern` and `type="email"|"url"|"number"` to `<input>`/`<select>`/`<textarea>` from the action's Standard Schema JSON Schema unless the app wrote that attribute (0 B client JS, no implicit `<option>` tags). A validation failure sets an `HttpOnly` flash cookie, read with `getActionError(ctx.locals)` (the flash is signed with `PRUNELLE_FORM_SECRET` or `AUTH_SECRET`; its `values` are the fields the action schema declares, minus secrets such as password, token, card or `format: "password"`, or exactly `flashFields`; a schema with no JSON Schema output declares none, so list `flashFields`), and redirects `303` to the trusted Referer. After a failed submit (the flash render, or `useAction`'s `onSubmit` in an island), each control `fieldErrors` names gets `aria-invalid="true"` and `aria-describedby` pointing at the element of its form whose whole text is the message (the first after it, else the last before; given an id `pru-err-<name>` if it has none), unless the app or `Field` set `aria-invalid`; the next submit removes them. So render the message as text inside the form, e.g. `<p role="alert">{err.fieldErrors.title}</p>`.
61
- - `protect: { rateLimit?: { max, windowMs, key? }, honeypot?: boolean | string, minTime?: number }` (or top-level `rateLimit`) enforces `rateLimit` (`429` + `Retry-After` / flash+303) before body parsing, then honeypot/`minTime`, then schema validation. It renders a hidden honeypot and an action-URL-bound HMAC-signed `_pru_ts` timestamp into `<form action={fn}>` automatically and refuses bots, fast submits and timestamps older than two hours with `400` and the one message `Submission rejected` before the handler runs. Set `PRUNELLE_FORM_SECRET` or `AUTH_SECRET` in production when using `minTime`, else Prunelle logs a warning when the action is defined (the key is derived from it with HKDF). A `minTime` form an island renders only in the browser has no timestamp and is refused (`prunelle dev` says so): render it on the first render, hidden until needed. The timestamp is signed per request, so a `minTime` form on a page exporting `prerender = true` or `cache` fails `prunelle check` and `prunelle build` (`action/min-time-frozen`), a `--static` export of one fails the build, and `autoPrerender` leaves such a page to render at request time.
61
+ - `protect: { rateLimit?: { max, windowMs, key? }, honeypot?: boolean | string, minTime?: number }` (or top-level `rateLimit`) enforces `rateLimit` (`429` + `Retry-After` / flash+303) before body parsing, then honeypot/`minTime`, then schema validation. A honeypot name holding `.` or `[` throws when the action is defined (the form parser nests such names). It renders a hidden honeypot and an action-URL-bound HMAC-signed `_pru_ts` timestamp into `<form action={fn}>` automatically and refuses bots, fast submits and timestamps older than two hours with `400` and the one message `Submission rejected` before the handler runs. Set `PRUNELLE_FORM_SECRET` or `AUTH_SECRET` in production when using `minTime`, else Prunelle logs a warning when the action is defined (the key is derived from it with HKDF). A `minTime` form an island renders only in the browser has no timestamp and is refused (`prunelle dev` says so): render it on the first render, hidden until needed. The timestamp is signed per request, so a `minTime` form on a page exporting `prerender = true` or `cache` fails `prunelle check` and `prunelle build` (`action/min-time-frozen`), a `--static` export of one fails the build, and `autoPrerender` leaves such a page to render at request time.
62
62
  - `prunelle check` and `prunelle build` report unknown form fields with the closest name (a schema taking extra keys through `additionalProperties` or `patternProperties` accepts those), missing required fields, invalid `<select>` enum options (a control counts for the form its `form="id"` names, as in the browser), unsupported schema libraries (once per vendor) and unguarded public form actions without `protect`.
63
63
  - Island RPC: `const res = await fn(data)` always resolves to `{ ok: true, data }` or `{ ok: false, status, error, fieldErrors?, issues? }`; it accepts `FormData` for files, and redirects navigate the page (to another site only for `ctx.redirect(url, status, { external: true })`; any other cross-site target fails with `Redirect to another site refused`).
64
64
  - In islands, `const form = useAction(fn, { reset?, onSuccess?, onError?, optimistic? })` returns `{ pending, error, fieldErrors, data, progress, action, onSubmit, submit, reset }` (`pending`/`error`/`fieldErrors`/`data`/`progress` are `ReadonlySignal`s; `progress` is the fraction uploaded, 0 to 1, of a submit whose `FormData` holds a `File`, sent through a module fetched only by a form whose `progress` is read, and 0 otherwise). Wire `<form action={form.action} method="post" onSubmit={form.onSubmit}>` for progressive enhancement; it keeps the SSR protection fields and HTML5 constraints.
65
65
  - `optimistic: (input) => { notes.value = [...notes.value, String((input as FormData).get('body'))] }` changes the page as the request leaves (`input` is the `FormData` from `onSubmit`, or what `submit()` got). Its signal and store writes are recorded and undone, before `onError`, when the result is `{ ok: false }` or the request fails; a failed change among several forms' in flight is undone alone, the later ones made again. It must be synchronous: returning a promise throws.
66
66
  - A route, `load()`, middleware or another action may also call it: it runs in that request, schema and folder `_middleware.ts` included, and resolves to the same result; called outside a request it throws.
67
67
  - Server code is stripped from client bundles. CSRF `Origin`/`Sec-Fetch-Site` is checked on every unsafe method before middleware and body parsing, unmatched paths and 405s included, and a request carrying a cookie with neither header must have a same-site `Referer`; the folder's `_middleware.ts` runs before the handler.
68
- - **Config (`prunelle.config.ts`)**: `defineConfig({ site, lang, port, routesDir, outDir, publicDir, assetPrefix, security, trustedOrigins, trustProxy, maxRequestBodySize, navigation, routeCache, store, autoPrerender, streamTimeout, consent, compliance, budget, compress, healthCheck, onError, log, plugins })`. `trustProxy: true | number` trusts that many right-most proxy hops for `X-Forwarded-*`; with `site` set, an `X-Forwarded-Host` naming neither the site's host nor a `trustedOrigins` one is ignored for the origin check and `ctx.redirect`, `Host` standing in, and `prunelle check` warns `[security/proxy-no-site]` on `trustProxy` without `site` (an https `site` makes cookies `Secure` and sends HSTS without it, also under `start --static`, but not in `prunelle dev`; production warns once on `X-Forwarded-Proto` while it is off, and once on the first POST refused as `untrusted origin`, naming the Origin, the origin the server computed, `trustProxy` and `trustedOrigins`); `prunelle start` in production notices when it binds loopback (the default; `HOST` or `--host 0.0.0.0` opens it for a container); `maxRequestBodySize` defaults to `1 MiB`. `lang` sets `<html lang>` and the language of `@prunellejs/ui`'s built-in labels (`'fr'` or `'fr-*'` gives French ones); with no `lang` and no `@prunellejs/i18n`, `prunelle check` warns `rgaa/document-lang`.
68
+ - **Config (`prunelle.config.ts`)**: `defineConfig({ site, lang, port, routesDir, outDir, publicDir, assetPrefix, security, trustedOrigins, cors, trustProxy, maxRequestBodySize, navigation, routeCache, store, autoPrerender, streamTimeout, consent, compliance, budget, compress, healthCheck, onError, log, plugins })`. `cors: { origins: ['https://front.example'], credentials?, exposeHeaders? }` answers those origins with `Access-Control-Allow-Origin` on every response (every response then sends `Vary: Origin`) and their preflight with a 204 before any middleware, also under `start --static`, and lets them through the CSRF check (plugins see them in `api.trustedOrigins`); `origins: '*'` lets any origin read (its preflight allows `GET` and `HEAD`) but keeps the CSRF check, and throws with `credentials: true`; unset, no other origin may call the app. `trustProxy: true | number` trusts that many right-most proxy hops for `X-Forwarded-*`; with `site` set, an `X-Forwarded-Host` naming neither the site's host nor a `trustedOrigins` one is ignored for the origin check and `ctx.redirect`, `Host` standing in, and `prunelle check` warns `[security/proxy-no-site]` on `trustProxy` without `site` (an https `site` makes cookies `Secure` and sends HSTS without it, also under `start --static`, but not in `prunelle dev`; production warns once on `X-Forwarded-Proto` while it is off, and once on the first POST refused as `untrusted origin`, naming the Origin, the origin the server computed, `trustProxy` and `trustedOrigins`); `prunelle start` in production notices when it binds loopback (the default; `HOST` or `--host 0.0.0.0` opens it for a container); `maxRequestBodySize` defaults to `1 MiB`. `lang` sets `<html lang>` and the language of `@prunellejs/ui`'s built-in labels (`'fr'` or `'fr-*'` gives French ones); with no `lang` and no `@prunellejs/i18n`, `prunelle check` warns `rgaa/document-lang`.
69
69
  - `store: 'data/app.db'` (a SQLite file, relative to the root) or `store: process.env.DATABASE_URL` (`postgres://`, read at start) is the database every process of the app shares: rate limits count there across processes, `invalidateCache()` drops the page in every process, and `@prunellejs/live` `publish()` reaches every process (Postgres `LISTEN`/`NOTIFY`, SQLite polled every 200 ms while a stream is open). prunelle creates `prunelle_rate_hits` (client keys, IP addresses by default, kept for each limiter's window: list it in the processing register) and `prunelle_messages` on first use. Each app needs its own database or file: channels, tables and rate-limit scopes carry no app name, so two apps on one database see each other's messages and counts. `@prunellejs/db` given no `url` queries the `store` itself, SQLite or Postgres. `@prunellejs/auth` and `@prunellejs/jobs` given no store of their own use a SQLite `store` file; with a Postgres one a production start refuses until they get their own. Unset, each process keeps them in memory and opens no database. Plugins reach it with `api.inject(SHARED_STORE)` (`prunelle/server`): `publish(channel, payload)` reaches the `subscribe(channel, fn)` of every other process; in `requires(ctx)`, `parseStoreSpec(ctx.store, ctx.root)` tells a SQLite `{ kind, file }` from a `{ kind: 'postgres', url }`.
70
70
  - **Security headers & CSP**: on by default (`security: false` disables them, or override `csp`, `hsts`, `frameOptions`, `referrerPolicy`, `contentTypeOptions`, `permissionsPolicy`, `crossOriginOpenerPolicy`, `crossOriginResourcePolicy`; the last two default to `same-origin`, and every header also goes on the build-swap `503`). `prunelle check` warns on `security: false`, `csp: false`, `'unsafe-inline'` in a script or style directive, `trustedTypes: false` and `export const csrf = false` (`security/headers-off`, `csp-off`, `unsafe-inline`, `trusted-types-off`, `csrf-off`). The strict `DEFAULT_CSP` (style attributes allowed) gets automatic SHA-256 hashes for island/Suspense styles, the app's own `<style>` blocks and stream scripts; `HSTS` is sent on HTTPS requests.
71
71
  - `DEFAULT_CSP` ends with `require-trusted-types-for 'script'; trusted-types prunelle 'allow-duplicates'`: the browser refuses `el.innerHTML = html`, `insertAdjacentHTML`, `DOMParser` and `document.write` from app code, while prunelle and its plugins write through their `prunelle` policy (`innerHTML={html}` on an element, region swaps, SPA navigations). Write HTML with `innerHTML={html}`, text with `textContent`, or through an app policy added with `csp: { 'trusted-types': ['my-policy'] }`; `security: { trustedTypes: false }` drops both directives. `prunelle check` warns `[security/html-sink]` at each such write in `src/`.
72
72
  - `security: { cspReports: true }` adds `report-uri /_pru/csp-report` (and, under `prunelle start` with an https `site`, `report-to` plus `Reporting-Endpoints`): each violation reaches `onError` as `source: 'csp'`, `error.message` `CSP violation: <directive> blocked <url> on <page>`, `error.cause` `{ directive, blockedUrl, page, sourceFile?, line? }` (stderr without a hook). 30 reports a minute per client, 16 KB each; extension-caused reports are dropped; a `--static` export leaves the directives out.
73
73
  - `security: { csp: { 'style-src': [...], 'font-src': [...] } }` (or `extendCsp()` / `DEFAULT_CSP` from `prunelle/server`) adds sources to single directives without copying the whole policy; a new `*-src` directive inherits `default-src`, and automatic hashes still land in the extended directives.
74
74
  - A `--static` export embeds each page's and `404.html`'s hashed CSP in `<meta http-equiv="Content-Security-Policy">` with `frame-ancestors`, `report-uri`, `report-to` and `sandbox` stripped (browsers ignore them in `<meta>`): the build writes the headers that cannot live there from `security` into `dist/_headers` (Netlify, Cloudflare Pages), `dist/prunelle.caddy` (`import` it in a site block) and `dist/prunelle.nginx.conf` (`include` it in a server block), with the exact-path rules of `dist/_redirects` (written by `@prunellejs/seo` `redirects`, or shipped in `public/`) as `redir` and `location =` lines; a file the app ships under those names is kept, and `security: false` skips `_headers` while keeping comment-only `prunelle.caddy` / `prunelle.nginx.conf` (plus any `_redirects` rules) so existing includes do not fail.
75
- - **Observability**: the Bun server (not a `--static` export served by `prunelle start`) answers `/_pru/health` (at `${assetPrefix}/health`): `200 { ok: true }`, or `503` when the app's `healthCheck` or a plugin's `api.healthCheck(name, fn)` fails or takes over 5 s (cached for 5 s; a failure reads `check failed`, the error goes to stderr, `prunelle dev` shows it); `./app --health` probes it for a container `HEALTHCHECK`. Every request gets `ctx.requestId` (honoring a safe incoming `x-request-id` when `trustProxy` is truthy), returned in `x-request-id` and passed to `onError` as `info.requestId`. `prunelle dev` sends `Server-Timing` (`middleware`, `load`, `render`, `stream`; zero overhead in production). `log: { format: 'json', access: true }` in `prunelle.config.ts` prints unhandled errors as one JSON line each (`time`, `level`, `msg`, `source`, `method`, `path`, `requestId`, `error`, `stack`) and one access line per request to stdout (`GET /posts 200 3.4ms [id]`, or JSON with `method`, `path`, `status`, `duration`, `requestId`; never the query or the IP; the health probe is skipped). A plugin hears each request with `api.onRequestEnd(record)`: `{ request, requestId, status, start, duration, phases: { name, start, duration }[] }`, times in epoch milliseconds, phases in the order they began; it runs before the response is sent, so queue the work.
75
+ - **Observability**: the Bun server (not a `--static` export served by `prunelle start`) answers `/_pru/health` (at `${assetPrefix}/health`): `200 { ok: true }`, or `503` when the app's `healthCheck` or a plugin's `api.healthCheck(name, fn)` fails or takes over 5 s (cached for 5 s; a failure reads `check failed`, the error goes to stderr, `prunelle dev` shows it); `./app --health` probes it for a container `HEALTHCHECK`. Every request gets `ctx.requestId` (honoring a safe incoming `x-request-id` when `trustProxy` is truthy), returned in `x-request-id` and passed to `onError` as `info.requestId`. `prunelle dev` sends `Server-Timing` (`middleware`, `load`, `render`, `stream`; zero overhead in production). `log: { format: 'json', access: true }` in `prunelle.config.ts` prints unhandled errors as one JSON line each (`time`, `level`, `msg`, `source`, `method`, `path`, `requestId`, `error`, `stack`) and one access line per request to stdout (`GET /posts 200 3.4ms [id]`, or JSON with `method`, `path`, `status`, `duration`, `requestId`; never the query or the IP; the health probe is skipped). A plugin hears each request with `api.onRequestEnd(record)`: `{ request, requestId, status, start, duration, phases: { name, start, duration }[], route? }`, times in epoch milliseconds, `route` the template that answered (`/blog/:slug`, a page's or a plugin route's; none for a file, a prerendered page or no match), phases in the order they began; it runs before the response is sent, so queue the work.
76
76
  - **Server helpers (`prunelle/server`)**:
77
77
  - `defineEnv(standardSchema)` validates env vars at startup. `nodeEnv()` is safe in `--compile`: server code reads it, never `process.env.NODE_ENV`, which `prunelle build` leaves unset for a prerendered page (build and `prunelle check` warn on such a read outside island code).
78
78
  - HTML escaping: `raw`, `esc`, `escAttr`, `escJson` (JSON text for a `<script>`), `escXml` (text for a feed or sitemap: also drops the control characters XML forbids).
@@ -88,8 +88,8 @@
88
88
  - RGESN: `rgesn/autoplay` (`<video>`/`<audio>` with `autoplay`), `rgesn/img-size` (`<img>` without both `width` and `height`, unless spread), `rgesn/img-sizes` (a `srcset` of `w` descriptors without `sizes`, unless spread), `rgesn/large-public-file` (a file in `publicDir` over 1 MB), `rgesn/declaration` (`/ecoconception` still holding a `[à compléter` placeholder), `rgesn/island-by-value` (an imported island read as a value, `const D = Counter`, `{ C: Counter }` or `c={Counter}`, which hydrates what holds it whole: render `<Counter />` itself; a production `prunelle build` reports it too, and an ignore covers one read only).
89
89
  - `lcen/legal-notice`: a page app missing `/mentions-legales`, `/legal`, or a localized variant (`/fr/mentions-legales`, `/[lang]/mentions-legales`), a legal notice page that renders no text, or one still holding a `[to fill in` placeholder.
90
90
  - `rgpd/privacy-notice`: a `.tsx` file in `src/` with an `<input>` collecting an email or a phone number (`type="email|tel"` or `name="email|phone|tel"`, read from the parsed JSX, so a commented-out one does not count) while the app has no `/privacy`, `/confidentialite`, `/politique-de-confidentialite` or localized variant, or a privacy notice still holding a `[to fill in` or `[à compléter` placeholder outside a comment (`prunelle-ignore` works on both, and on the placeholders of the legal notice, accessibility statement and eco declaration). The `app` template ships `/privacy` and links it under its sign-up form.
91
- - Silence per rule with `compliance: { ignore: [...], legalNotice?: string | false, privacyNotice?: string | false, publicBody?: boolean }`, or `// prunelle-ignore <rule>` / `/* prunelle-ignore <rule> */` / `// prunelle-ignore-file <rule>`. The form check's warnings (`action/unguarded-public-form`, `form/invalid-option`, `form/schema-unsupported`, `form/unchecked` for an action module that fails to import, an ignore silencing that form only) are silenced the same way, the comment going on the line above the `<form>` or `<option>`; its errors cannot be. So is `security/csrf-off`, the comment going above `export const csrf = false`, and `security/proxy-no-site` through `compliance.ignore`.
92
- - One-declaration consent: `consent: { categories: ['analytics', 'media'] | { analytics: 'Audience measurement' }, cookieName?: 'pru_consent', maxAge?: 15552000, endpoint?: '/_pru/consent', version?: '2026-11' }` wires a CSRF-protected `POST /_pru/consent` endpoint (a zero-JS `<form method="post" action="/_pru/consent">` with `action="accept-all"|"reject-all"` or category checkboxes, `name="categories" value="analytics"` or `name="analytics"`, gets a `303`, JSON a `200`), exposes `ctx.consent` (`decided`, `decidedAt`, `categories`, `labels`, `endpoint`, `lang`, `has(cat)`, `all()`), refuses `ctx.cookies.set(name, val, { category })` before consent is granted, expires on `POST /_pru/consent` the cookies of each refused category that this server process set and the request carries, and exports server-only `<ConsentGate category="media" fallback={...}>` (0 KB browser JS, refused inside islands). The cookie stores the time of the choice and `version`: changing `version` asks every visitor again. `prunelle check` warns (`rgpd/consent-retention`) when `maxAge` is past 180 days, and `prunelle dev` warns once per cookie set with no `category`, which counts as essential.
91
+ - Silence per rule with `compliance: { ignore: [...], legalNotice?: string | false, privacyNotice?: string | false, publicBody?: boolean }`, or `// prunelle-ignore <rule>` / `/* prunelle-ignore <rule> */` / `// prunelle-ignore-file <rule>`. The form check's warnings (`action/unguarded-public-form`, `form/invalid-option`, `form/schema-unsupported`, `form/unchecked` for an action module that fails to import, an ignore silencing that form only) are silenced the same way, the comment going on the line above the `<form>` or `<option>`; its errors cannot be. So is `security/csrf-off`, the comment going above `export const csrf = false`, and `security/proxy-no-site` through `compliance.ignore`. A plugin `check(ctx)` warning is silenced by its tag in `compliance.ignore` (`'pwa/manifest-missing'`, `'seo/missing-image'`), typed from the plugins the config imports; a plugin declares its tags with `declare module 'prunelle/config' { interface PrunellePluginRules { 'ns/rule': true } }`.
92
+ - One-declaration consent: `consent: { categories: ['analytics', 'media'] | { analytics: 'Audience measurement' }, cookieName?: 'pru_consent', maxAge?: 15552000, endpoint?: '/_pru/consent', version?: '2026-11' }` wires a CSRF-protected `POST /_pru/consent` endpoint (a zero-JS `<form method="post" action="/_pru/consent">` with `action="accept-all"|"reject-all"` or category checkboxes, `name="categories" value="analytics"` or `name="analytics"`, gets a `303`, JSON a `200`), exposes `ctx.consent` (`decided`, `decidedAt`, `categories`, `labels`, `endpoint`, `lang`, `has(cat)`, `all()`), refuses `ctx.cookies.set(name, val, { category })` before consent is granted, expires on `POST /_pru/consent` the cookies of each refused category that this server process set and the request carries, and exports server-only `<ConsentGate category="media" fallback={...}>` (0 KB browser JS, refused inside islands). The cookie stores the time of the choice and `version`: changing `version` asks every visitor again, and so does a choice older than `maxAge` (whatever the browser kept). `prunelle check` warns (`rgpd/consent-retention`) when `maxAge` is past 180 days, and `prunelle dev` warns once per cookie set with no `category`, which counts as essential.
93
93
  - `<ConsentBanner policyHref?="/cookies" policyLabel? title? accept? refuse? choose? save? legend?>{text?}</ConsentBanner>` renders, until the visitor decides, a form with Refuse all and Accept all side by side and the categories (by label) behind a `<details>`, its texts in French when `lang` is `fr` (English otherwise, each prop overrides); `<ConsentPreferences />` renders the choice in force, to change or withdraw it (put it on the cookie policy page). Both are server-only, private on a cached route, and throw `prunelle: <ConsentBanner> has no consent category to ask about` without `consent.categories`. Markup: `data-ui="consent"` with `data-part` `title`, `body`, `form`, `actions`, `details`, `choices`, `choice`, `preferences`; buttons carry `data-ui="button"`.
94
94
  - `<CookieTable caption? />` (server-only, 0 B of JS) renders a `<table data-ui="table">` of every cookie the site sets, with its name, purpose, category (`consent.categories` label, or Essential) and lifetime, in French when `lang` is `fr`: `pru_consent` when `consent` is set, `__pru_action_err` (60 s) when the app has an action, each plugin's `cookies` (auth: the session cookie, `__Host-` named when `site` is https, its `_2fa`, `_webauthn` and, with a provider, `_oauth` cookies; analytics: `pru_no_count`), then the app's, read by `prunelle build` from `ctx.cookies.set(name, value, { category, purpose: 'Keeps the chosen theme.', maxAge })` (`purpose` is only read, never sent).
95
95
  - **Page changes (plain multi-page navigation, 0 B of JS)**: every page carries inline, CSP-hashed `@view-transition { navigation: auto }` (inside `@media (prefers-reduced-motion: no-preference)`) and a `<script type="speculationrules">` prefetching same-origin links on press (`eagerness: conservative`); it never links to another origin, `/_pru/*` (actions included), `[download]`, `[rel~=nofollow]`, nor a link or ancestor with `data-pru-no-prefetch`. Name an element that stays still with CSS `view-transition-name`.
@@ -105,18 +105,18 @@
105
105
  - `prunelle inspect [dir] [--json]`: fast static report, without bundling, of routes (groups, optional params, matchers, `cache`, accurate `autoPrerender` `cacheable`), `statusPages`, `paramMatchers`, islands with their interactivity `reason` and `hydrate` mode, actions with URLs and guarding `_middleware.ts`, and active plugins in resolved order; `--json` prints `{ routes, statusPages, paramMatchers, islands, actions, plugins }`.
106
106
  - `prunelle build [dir] [--static] [--compile [out]] [--auto-prerender] [--analyze] [--json] [--max-js <size>]`: `--analyze` lists each route's eager JS, CSS, fonts, first load (brotli), EcoIndex grade/score/inputs for prerendered routes (a static estimate from the build's files, not a browser visit, computed as `cnumr/ecoindex_python` does, the grade from the unrounded score, every image and third-party request of the page counted), and its islands with why each is one (`--analyze --json` outputs `BundleReport` JSON); `firstLoadUrls`, `distLocator` and `measureFirstLoad` from `prunelle/config` give plugins the same figure, and `await brotliSize(html)` reads the brotli cache. `--max-js 40kb` fails on a route whose gzipped eager JS is over it; `budget: { js?: '40kb', firstLoad?: '500kb' }` in `prunelle.config.ts` (bytes or KB) does the same on every build, `firstLoad` capping the brotli first load, and `--max-js` overrides `budget.js` for one run.
107
107
  - `prunelle a11y [--draft [dest]] [--force] [--audit-date YYYY-MM-DD --rate <percent>] [--json] [--routes /a,/b] [--all-static] [--org <name>] [--contact <email>] [--no-fail]`: an axe-core scan whose results are mapped to RGAA criteria, covering what axe can detect, not an RGAA audit; axe-core tags `RGAAv4` + WCAG 2.1 A/AA, each result mapped to its RGAA criterion, axe's `incomplete` results reported as `toCheck`, to check by hand, counted with the page JS errors and `skipped` routes (not opened) in the report; `--draft` refuses to overwrite an existing statement unless `--force` is given; the draft's level comes from the manual audit only, "non conforme" without one, "totalement conforme" refused when the same run found axe violations, derogations and out-of-scope contents left as `[à compléter : ...]`, and `prunelle check` warns about `[à compléter : ...]` left in any published statement.
108
- - `prunelle eco [dir] [--declaration [path]] [--service <name>] [--org <name>] [--contact <email>]`: builds the app and reports what it saw of the RGESN 2024 criteria it can read (4.1 autoplay, 4.4 third parties, 6.1 weight cap from `budget.firstLoad`, 6.3 compression, 6.5 unused resources, 6.7 one domain), saying what each check cannot see and giving no verdict: a person writes every one; `--declaration` writes an editable French declaration page (default `src/routes/ecoconception.tsx`) with each prerendered page's EcoIndex (a static estimate, not a browser visit), that evidence and a `[à compléter` placeholder for every verdict and the rest.
108
+ - `prunelle eco [dir] [--declaration [path]] [--force] [--service <name>] [--org <name>] [--contact <email>]`: builds the app and reports what it saw of the RGESN 2024 criteria it can read (4.1 autoplay, 4.4 third parties, 6.1 weight cap from `budget.firstLoad`, 6.3 compression, 6.5 unused resources, 6.7 one domain), saying what each check cannot see and giving no verdict: a person writes every one; `--declaration` writes an editable French declaration page (default `src/routes/ecoconception.tsx`) with each prerendered page's EcoIndex (a static estimate, not a browser visit), that evidence and a `[à compléter` placeholder for every verdict and the rest; a page already there is refused (exit 1) unless `--force`.
109
109
  - `prunelle rgpd [dir] [--draft [path]] [--force] [--org <name>] [--contact <email>]`: lists the personal data each plugin's `processing` declares (auth: accounts and sessions, following `storeIp`, `storeUserAgent` and its lifetimes; analytics: what it sends the provider, with consent as the legal basis when counting waits for it; files) and the forms of each `.tsx` file holding an email or phone `<input>`, every named field of such a form listed (a form whose `action` is under a plugin's `formActions`, such as `/auth/`, is that plugin's). `--draft` writes a French privacy notice (default `src/routes/confidentialite.tsx`, prerendered, with `<CookieTable />`, the rights and the CNIL complaint) and `registre-des-traitements.md` (the RGPD art. 30 record, kept out of the site), each detail nobody declared left as a `[à compléter : ...]` that `rgpd/privacy-notice` reports; without `--force` it writes neither when one exists.
110
110
  - `prunelle start [dir] [--port 3000] [--host [addr]] [--workers <n|auto>]`; `--workers` (Linux) runs n processes on one port with `SO_REUSEPORT`, the primary serving nothing and starting the others once the first listens, restarting a worker that dies after it listened and stopping all when one exits before it listens (it reports listening over Bun's IPC channel, and stops when the primary dies); with neither `PRUNELLE_FORM_SECRET` nor `AUTH_SECRET` the workers share one random secret (`startSecret()` in `prunelle/server`), and with no `store` worker 1 warns what each process keeps alone (rate limits, `invalidateCache()`, and each plugin's `perProcess` clause). `prunelle upgrade [dir] [--no-install]` moves a kay v2 app or workspace onto prunelle (kay v1 left untouched, a folder on neither refused, symbolic links never followed; `sqliteAuthStore()` preserves accounts).
111
111
  - Plugin commands: `prunelle ui-eject <grammar> [dest]`, `prunelle mcp-footprint`, `prunelle i18n-check`, `prunelle icons-find <words> [--set <prefix>] [--limit <n>]`, `prunelle pwa-vapid [--json]`, `prunelle db migrate|status`. A command gets `(args, root, { store })`. They load from `prunelle.config.ts` only when the first word is no built-in, and take `--root <dir>` and `--help`.
112
112
  - **CLI (dev, editor & agent tooling)**:
113
- - `prunelle dev [dir] [--port 3000] [--host [addr]]`: binds loopback `127.0.0.1` by default; answers `421` to a `Host` other than `localhost`, `*.localhost`, an IP address, its `--host` and the hosts of `site` and `trustedOrigins` (against DNS rebinding: add a tunnel's origin to `trustedOrigins`); marks rendered elements with `data-pru-src="file:line:col"` in dev only (production output is byte-identical), and Alt-click opens `$PRUNELLE_EDITOR` or `$VISUAL` in VS Code, Cursor, Zed, JetBrains, Sublime, Helix or a `{file}:{line}:{col}` template (`/_pru/open-editor` answers `403` off loopback and honours `trustedOrigins`); records dev build, crash and runtime errors in `.prunelle-dev/last-errors.jsonl`; runs the app in a child process recycled on `prunelle.config.ts` edits or past 2 GB; edits in `public/` reload without rebuilding; saving an island's file swaps that island in the open page without a reload and keeps the values of the signals it made while rendering (same declaration, same place), while a file that is no island, a `load()` or a stylesheet change still reloads.
113
+ - `prunelle dev [dir] [--port 3000] [--host [addr]]`: binds loopback `127.0.0.1` by default; answers `421` to a `Host` other than `localhost`, `*.localhost`, an IP address, its `--host` and the hosts of `site` and `trustedOrigins` (against DNS rebinding: add a tunnel's origin to `trustedOrigins`); marks rendered elements with `data-pru-src="file:line:col"` in dev only (production output is byte-identical), and Alt-click opens `$PRUNELLE_EDITOR` or `$VISUAL` in VS Code, Cursor, Zed, JetBrains, Sublime, Helix or a `{file}:{line}:{col}` template (`/_pru/open-editor` answers `403` off loopback and honours `trustedOrigins`); records dev build, crash and runtime errors in `.prunelle-dev/last-errors.jsonl`; runs the app in a child process recycled on `prunelle.config.ts` edits or past 2 GB; edits in `public/` reload without rebuilding; saving an island's file swaps that island in the open page without a reload and keeps the values of the signals and stores it made while rendering (same declaration, same place), while a file that is no island, a `load()` or a stylesheet change still reloads.
114
114
  - `prunelle render <url> [--method|-X <m>] [--body|-d <data>] [--header|-H "K: V"] [--cookie|-b "k=v"] [-i|--include] [--fresh]`: built on `testApp()`, it builds or reuses `.prunelle-cache/render-build` with no port bound and without touching `dist/`, and prints the body (status, headers and body with `-i`); exit `0` for `2xx`/`3xx`, `1` otherwise.
115
115
  - `prunelle docs <words...> [--json] [--limit <n>]`: searches `llms.txt` of `prunelle`, every installed `@prunellejs/*` package and every dependency in the app's `package.json` that ships one, at the installed versions; `--json` prints `{ query, words, packages, matches }`.
116
116
  - `prunelle mcp [dir] [--allow-write]`: stdio MCP server for coding agents exposing `check`, `inspect`, `build_analyze`, `build` (requires `--allow-write`), `render` (a method other than GET, HEAD or OPTIONS requires `--allow-write`), `docs` and `dev_errors` tools, plus `prunelle://llms/<pkg>` resources; it reloads `prunelle.config.ts` fresh on every tool call, and paths stay inside the project.
117
117
  - `prunelle/ts-plugin`, added to `tsconfig.json` `compilerOptions.plugins` as `{ "name": "prunelle/ts-plugin", "site"?: "...", "compliance"?: {...} }`, surfaces compiler mistakes, compliance warnings and 18 mechanical quick fixes in `tsserver` editors (select the workspace TypeScript version in VS Code; `tsserver`-only until `tsgo` supports plugins).
118
118
  - **Testing (`prunelle/test`)**:
119
- - `const app = await testApp({ root, prebuilt?, outDir?, plugins? })` (`plugins` replaces those of the app's config, as a plugin's own tests mount it on a fixture app) builds into its own `.prunelle-cache/test-*` folder, removed at exit, never into `dist/`, and reuses the build of an earlier call on the same root in the process while the app's files, build options and `process.env` are unchanged (not with `outDir`, `plugins` or `analyze`; the app still loads afresh) (`prebuilt: true` reuses the latest testApp build of that root in the process, else `dist/`). In-process, with a persistent cookie jar and no port: `app.get()`, `app.post()`, `app.import(path)` (the app's bundled copy of a route, action file or `prunelle.config.ts`), `app.submit(action | url, fields)` (sends an empty honeypot and an aged signed timestamp for `protect`ed `ServerAction`s unless overridden), `app.fetch()`, `app.cookies`, `app.clearCookies()`, `app.clock.set(time)` / `app.clock.advance(ms)` (the `Date.now()` the app and the test read, until dispose), `app.stub(url | RegExp, Response | (request) => Response)` (answers an outgoing request by origin and path; one leaving the machine with no stub is refused with its URL and makes `dispose()` throw, loopback goes through, and a `fetch` mock the test set first answers everything instead), `app.dispose()` (`await using app = await testApp(...)`).
119
+ - `const app = await testApp({ root, prebuilt?, outDir?, plugins? })` (`plugins` replaces those of the app's config, as a plugin's own tests mount it on a fixture app) builds into its own `.prunelle-cache/test-*` folder, removed at exit, never into `dist/`, and reuses the build of an earlier call on the same root in the process while the app's files, the files outside its root the build read, build options and `process.env` are unchanged (not with `outDir`, `plugins` or `analyze`; the app still loads afresh) (`prebuilt: true` reuses the latest testApp build of that root in the process, else `dist/`). In-process, with a persistent cookie jar and no port: `app.get()`, `app.post()`, `app.import(path)` (the app's bundled copy of a route, action file or `prunelle.config.ts`), `app.submit(action | url, fields)` (sends an empty honeypot and an aged signed timestamp for `protect`ed `ServerAction`s unless overridden), `app.fetch()`, `app.cookies`, `app.clearCookies()`, `app.clock.set(time)` / `app.clock.advance(ms)` (the `Date.now()` the app and the test read, until dispose), `app.stub(url | RegExp, Response | (request) => Response)` (answers an outgoing request by origin and path; one leaving the machine with no stub is refused with its URL and makes `dispose()` throw, loopback goes through, and a `fetch` mock the test set first answers everything instead), `app.dispose()` (`await using app = await testApp(...)`).
120
120
  - Unhandled errors in routes, actions, plugin routes and streamed `<Suspense>` boundaries log their source, method, path and stack to stderr (`console.error`) under `prunelle start` and `prunelle dev` when no `onError` hook is configured (an `onError` handles them without doubling). `testApp()` captures them silently in `app.errors` (`route GET /p: message`); `testApp({ dev: true })` shows them in the 500 like `prunelle dev` does.
121
121
  - With `dev` (`prunelle dev`, `testApp({ dev: true })`), the 500 carries message and stack, each frame at its `src/` file and line (under `prunelle start` too, through the source maps `prunelle build` writes; a `--compile` binary names its own code), as JSON `{ ok: false, status: 500, error, stack }` when the request wants JSON, else text; `_error.tsx` still renders. Production stays `Internal Server Error`, and `_error.tsx` receives that message too, never the thrown one. `prunelle dev` build errors also answer JSON/text per `Accept`.
122
122
  - Islands: `const b = await testBrowser({ root, timeout?, browserPath? })` (needs `playwright-core` as a dev dependency and Chrome/Chromium; serves the production build on `b.origin`, a free 127.0.0.1 port), then `const page = await b.open(path)`, which resolves once the page has loaded and its `load`/`client` islands have hydrated (`visible`, `idle`, `interaction` and `media(...)` ones are the test's to trigger); `b.open(path, { reducedMotion: true })` asks for less motion; `b.mount('src/islands/Counter.tsx', { start: 2 }, { export?: 'Counter' })` opens that one component alone on an empty page, hydrated the same way, with no route to write (props are JSON, each component is built once per testBrowser).
@@ -124,7 +124,7 @@
124
124
  - **Plugins (`prunelle.config.ts`)**: `export default defineConfig({ plugins: [...] })` / `definePlugin(...)`. Order with `enforce: 'pre' | 'post'` and `after: ['@prunellejs/i18n']` (a name no plugin has is an optional dependency, unless it is one typo from one that is, which fails). Two plugins sharing a `name` fail, and so does an unknown config key, naming the closest one.
125
125
  - A stateful plugin's `createX()` returns the plugin and the app's handle in one object: `plugins: [auth, mail, rooms]`, with `auth.guard()`, `mail.send()`, `rooms.publish()` in routes. Stateless plugins are `x()`.
126
126
  - `server(api)`: `use(mw, { scope? })` (`'all'` default, prerendered pages included; `'rendered'` skips prerendered pages, for middleware that only feeds rendering such as a session; `'dynamic'` also skips pages with no `load`; or a path prefix), `rewrite` (also run once per prerendered page at start, on an anonymous GET: no side effects), `healthCheck(name, fn)` (feeds `/_pru/health`; returning `false` or throwing turns it `503`), `provide(key, value)`/`inject(key)` typed by `serviceKey<T>(name)` from `prunelle/config`, `getBuildData`. `api.dev` is true under `prunelle dev`, and `api.devExposed` when `prunelle dev --host` binds an address other machines reach: a dev-only route that writes or reveals data refuses to start unguarded then.
127
- - `api.route(method, path, handler, { csrf?, trustedOrigins?, trustProxy?, rateLimit?, encodedSlashes? })`: `rateLimit: { max, windowMs, key? }` answers `429` with `Retry-After` before the handler past `max` per window, per `ctx.ip` or `key(ctx)`; `encodedSlashes: true` lets a `*name` catch-all take a segment holding `%2F`, `%5C` or `%00`, left encoded in the param, for text such as a URL, never a file path (on a path with no catch-all it throws). Responses get the security headers; an HTML one without its own CSP gets the app's, its `<style>` blocks hashed.
127
+ - `api.route(method, path, handler, { csrf?, trustedOrigins?, trustProxy?, rateLimit?, encodedSlashes? })`: `rateLimit: { max, windowMs, key? }` answers `429` with `Retry-After` before the handler past `max` per window, per `ctx.ip` or `key(ctx)`; `encodedSlashes: true` lets a `*name` catch-all take a segment holding `%2F`, `%5C` or `%00`, left encoded in the param, for text such as a URL, never a file path (on a path with no catch-all it throws). A GET route at the path of an app page (plugin routes are matched first) stops the server at start and fails `prunelle check`, naming the plugin and the page. Responses get the security headers; an HTML one without its own CSP gets the app's, its `<style>` blocks hashed.
128
128
  - `api.rateLimiter({ max, windowMs }, name?)` returns a limiter in the server's store (each limiter keeps at most 10 000 keys and 1 000 000 hits, not the store as a whole; swept every minute, dropped with the server) for a limit a route option cannot key, such as per email: `await hit(key)` returns 0, or the whole seconds to wait; `await peek(key)` answers the same without counting, to check a limit that only some outcomes count. With `store` set it counts there under the plugin's name and `name` (default: its order among the plugin's limiters), so name a limiter created while serving requests.
129
129
  - Build hooks: `build(ctx)` (`routesDir`, `emitAsset`, `emitPublic`, `addStyle`, `addRouteStyle`, `addHead`, `addRouteHead`, `provide`, `inject`, `setData`, `routes`), `afterPrerender(ctx)` (`routes`, `publicFiles`, `assets`, `emitAsset`, `emitPublic`, `setData`), `transform`, `bunPlugins` (array or `({ root, assetPrefix, minify, target, lang, multiLocale }) => [...]`), `css`, `prerenderPaths`, `clientEntry`, `watchPaths`, `commands`.
130
130
  - `cookies`: the cookies the plugin sets, `{ name, purpose: string | { en, fr }, category, maxAge? }[]` (no `maxAge`: a session cookie) or `({ site }) => [...]`, listed by `<CookieTable>`; `CookieDeclaration` from `prunelle/config`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "prunelle",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "description": "Bun-native TSX web framework with zero-directive automatic islands, fine-grained signals, and single-binary deploys",
5
5
  "license": "MIT",
6
6
  "homepage": "https://prunelle.kaynooo.fr",
@@ -51,7 +51,7 @@
51
51
  "directory": "packages/prunelle"
52
52
  },
53
53
  "dependencies": {
54
- "@kaynooo/cli-kit": "^0.52.1",
54
+ "@kaynooo/cli-kit": "^0.55.0",
55
55
  "oxc-parser": "^0.155.0"
56
56
  },
57
57
  "peerDependencies": {
@@ -88,14 +88,11 @@ export function escapeAttr(value: string): string {
88
88
  .replaceAll('>', '&gt;')
89
89
  }
90
90
 
91
+ // The day in Paris: a draft written between midnight and 2 a.m. there is still dated by the UTC day before otherwise.
91
92
  export function formatFrenchDate(date: Date): { iso: string, human: string } {
92
- const iso = date.toISOString().slice(0, 10)
93
- const human = new Intl.DateTimeFormat('fr-FR', {
94
- day: 'numeric',
95
- month: 'long',
96
- year: 'numeric',
97
- timeZone: 'UTC',
98
- }).format(date)
93
+ const timeZone = 'Europe/Paris'
94
+ const iso = new Intl.DateTimeFormat('en-CA', { day: '2-digit', month: '2-digit', year: 'numeric', timeZone }).format(date)
95
+ const human = new Intl.DateTimeFormat('fr-FR', { day: 'numeric', month: 'long', year: 'numeric', timeZone }).format(date)
99
96
  return { iso, human }
100
97
  }
101
98
 
@@ -35,6 +35,8 @@ export interface BundleEnv {
35
35
  lang?: string | undefined
36
36
  minify: boolean
37
37
  isDev: boolean
38
+ /** Split the server bundle by route so `prunelle dev` can keep unchanged chunks loaded; single-entry builds isolate every reload/test cleanly. */
39
+ splitServer?: boolean | undefined
38
40
  nodeEnv?: string | undefined
39
41
  analyze?: boolean | undefined
40
42
  graph: ModuleGraph
@@ -461,6 +463,7 @@ function resolveServerImports(b: PluginBuilder, isDev: boolean, root: string, re
461
463
  /** `entry` is the generated `_entry.js`, an in-memory file bundled beside `entries` so it shares their chunks. */
462
464
  export async function buildServer(env: BundleEnv, entries: string[], serverRoot: string, islandChunks: Map<string, string>, entry: { file: string, source: string }): Promise<void> {
463
465
  const { root, outDir, serverDir, graph, cache, islands } = env
466
+ const splitServer = env.splitServer ?? env.isDev
464
467
  const transforms = pluginTransforms(env.plugins)
465
468
  const externalOutDir = !isInside(root, outDir, { orSame: true })
466
469
 
@@ -469,6 +472,7 @@ export async function buildServer(env: BundleEnv, entries: string[], serverRoot:
469
472
  serverRoot,
470
473
  assetPrefix: env.assetPrefix, lang: env.lang, multiLocale: pluginSetsLang(env.plugins),
471
474
  isDev: env.isDev,
475
+ splitServer,
472
476
  seeds: islands.seedsModuleState,
473
477
  transforms: transforms.key,
474
478
  entries: [...entries].sort(),
@@ -575,13 +579,13 @@ export async function buildServer(env: BundleEnv, entries: string[], serverRoot:
575
579
  if (transforms.failure !== undefined)
576
580
  throw transforms.failure
577
581
  }, {
578
- entrypoints: [...entries, entry.file],
582
+ entrypoints: splitServer ? [...entries, entry.file] : [entry.file],
579
583
  files: { [entry.file]: entry.source },
580
584
  outdir: serverDir,
581
585
  root: serverRoot,
582
586
  target: 'bun',
583
587
  format: 'esm',
584
- splitting: true,
588
+ splitting: splitServer,
585
589
  packages: 'external',
586
590
  minify: false,
587
591
  // A stack trace names the source file and line: Bun reads the map beside each chunk.
@@ -83,6 +83,8 @@ export interface BuildOptions {
83
83
  compile?: string | boolean | undefined
84
84
  /** Run in development mode (keeps NODE_ENV as development and skips production client asset precompression; auto-detected via PRUNELLE_DEV=1). */
85
85
  dev?: boolean | undefined
86
+ /** Split the server bundle across route chunks (defaults to `dev`; false yields one `_entry.js` for clean `?v=` reloads). */
87
+ splitServer?: boolean | undefined
86
88
  /** Explicit NODE_ENV threaded through AppRuntimeContext and client defines without mutating process.env. */
87
89
  nodeEnv?: string | undefined
88
90
  }
@@ -432,7 +434,7 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
432
434
  .map(c => resolve(root, c))
433
435
  .filter(c => existsSync(c))
434
436
  const wantsAnalyze = wantsBundleAnalysis(run)
435
- const env = { root, outDir, clientDir, serverDir, assetPrefix, lang: run.lang, minify: run.minify, isDev, nodeEnv: run.nodeEnv, analyze: wantsAnalyze, graph, cache: options.cache, plugins, actionsByFile, islands }
437
+ const env = { root, outDir, clientDir, serverDir, assetPrefix, lang: run.lang, minify: run.minify, isDev, splitServer: options.splitServer ?? isDev, nodeEnv: run.nodeEnv, analyze: wantsAnalyze, graph, cache: options.cache, plugins, actionsByFile, islands }
436
438
 
437
439
  const routeEntryFiles = new Set([...specialFiles, ...pageFiles])
438
440
  const standaloneActionFiles = [...actionsByFile.keys()].filter(f => !routeEntryFiles.has(f))
@@ -62,6 +62,31 @@ export function resolveExportTarget(
62
62
  return { file, exportName }
63
63
  }
64
64
 
65
+ /** The module a namespace stands for once exported by `file` as `name`: `export * as name from './m'`, or `import * as name from './m'` then `export { name }`, through any re-export chain. */
66
+ export function resolveNamespaceModule(graph: ModuleGraph, load: LoadModule, file: string, name: string, depth = 0): string | undefined {
67
+ if (depth > MAX_REEXPORT_DEPTH)
68
+ return undefined
69
+ const analysis = load(file)
70
+ if (analysis === undefined)
71
+ return undefined
72
+ const direct = analysis.reexports.find(r => r.exported === name)
73
+ if (direct !== undefined) {
74
+ const next = graph.resolve(file, direct.source)
75
+ if (next === undefined || !isTsFile(next))
76
+ return undefined
77
+ return direct.local === '*' ? next : resolveNamespaceModule(graph, load, next, direct.local, depth + 1)
78
+ }
79
+ for (const re of analysis.reexports) {
80
+ if (re.exported !== '*')
81
+ continue
82
+ const next = graph.resolve(file, re.source)
83
+ const found = next !== undefined && isTsFile(next) ? resolveNamespaceModule(graph, load, next, name, depth + 1) : undefined
84
+ if (found !== undefined)
85
+ return found
86
+ }
87
+ return undefined
88
+ }
89
+
65
90
  export function moduleHasInteractiveExport(graph: ModuleGraph, load: LoadModule, file: string, seen = new Set<string>()): boolean {
66
91
  if (seen.has(file))
67
92
  return false
@@ -75,7 +100,7 @@ export function moduleHasInteractiveExport(graph: ModuleGraph, load: LoadModule,
75
100
  const next = graph.resolve(file, re.source)
76
101
  if (next === undefined || !isTsFile(next))
77
102
  continue
78
- if (re.exported === '*') {
103
+ if (re.local === '*') {
79
104
  if (moduleHasInteractiveExport(graph, load, next, seen))
80
105
  return true
81
106
  }
@@ -135,6 +160,20 @@ const COMPONENT_NAME_RE = /^[A-Z]/
135
160
  const allValueReads = (analysis: ModuleAnalysis, local: string): number[] =>
136
161
  analysis.bindings.map(b => b.valueRefs.get(local)).filter((offset): offset is number => offset !== undefined)
137
162
 
163
+ // Where `local` is the whole initialiser of an exported `const`, which re-exports it under that name instead of reading it.
164
+ function exportAliasStarts(analysis: ModuleAnalysis, local: string): Set<number> {
165
+ const starts = new Set<number>()
166
+ for (const stmt of analysis.program.body) {
167
+ if (stmt.type !== 'ExportNamedDeclaration' || stmt.declaration?.type !== 'VariableDeclaration')
168
+ continue
169
+ for (const d of stmt.declaration.declarations) {
170
+ if (d.id.type === 'Identifier' && d.init?.type === 'Identifier' && d.init.name === local)
171
+ starts.add(d.init.start)
172
+ }
173
+ }
174
+ return starts
175
+ }
176
+
138
177
  // All unshadowed non-JSX value reads of `local` in `analysis.program`, used only when a line-ignore hides the first recorded offset.
139
178
  function allProgramValueReads(analysis: ModuleAnalysis, local: string): number[] {
140
179
  const offsets: number[] = []
@@ -234,7 +273,8 @@ export function createPromoter(
234
273
  const recordValueUses = (file: string, analysis: ModuleAnalysis): void => {
235
274
  for (const imp of analysis.imports) {
236
275
  for (const spec of imp.specifiers) {
237
- const offsets = spec.imported === '*' || !COMPONENT_NAME_RE.test(spec.local) ? [] : allValueReads(analysis, spec.local)
276
+ // `export const Y = B` is a re-export under another name, followed like `export { B as Y }`, not a value read.
277
+ const offsets = spec.imported === '*' || !COMPONENT_NAME_RE.test(spec.local) ? [] : allValueReads(analysis, spec.local).filter(o => !exportAliasStarts(analysis, spec.local).has(o))
238
278
  if (offsets.length === 0 || reportedValueUses.has(`${file}#${spec.local}`) || interactiveKind(file, imp.source, spec.imported) !== 'export')
239
279
  continue
240
280
  reportedValueUses.add(`${file}#${spec.local}`)
@@ -2,17 +2,19 @@
2
2
 
3
3
  import type { ModuleAnalysis } from '../compiler/analyze'
4
4
  import type { ServerOnlyInIsland } from '../compiler/interactivity'
5
+ import type { CompilerWarning } from '../compiler/mistakes'
5
6
  import type { ModuleGraph } from './graph'
6
7
  import type { IslandValueUse, LoadModule, PromotedWarning } from './island-promote'
7
8
  import { basename, extname } from 'node:path'
8
9
  import { asyncInteractiveError } from '../compiler/analyze'
9
10
  import { findCrossFileServerOnly } from '../compiler/interactivity'
10
11
  import { collectMistakes, serverOnlyTagError } from '../compiler/mistakes'
12
+ import { checkBodyPropsDestructure } from '../compiler/props-body'
11
13
  import { findPrivateEnv, isServerOnlyModule } from '../compiler/server-only'
12
14
  import { checkBareSignals } from '../compiler/signal-reads'
13
15
  import { clientNeeds, clientView } from './client-prune'
14
16
  import { isInNodeModules, isTsFile, relPosix } from './files'
15
- import { collectExportedSignals, createPromoter, resolveExportTarget } from './island-promote'
17
+ import { collectExportedSignals, createPromoter, resolveExportTarget, resolveNamespaceModule } from './island-promote'
16
18
  import { writesModuleState } from './seed-writes'
17
19
 
18
20
  /** A component that is not an island, as a module renders it. */
@@ -78,6 +80,7 @@ export interface AnalyzeIslandsOptions {
78
80
  }
79
81
 
80
82
  const EMPTY_SET = new Set<string>()
83
+ const UNSAFE_ID_CHARS_RE = /[^a-z0-9_.-]/g
81
84
 
82
85
  export function islandKey(target: { file: string, exportName: string }): string {
83
86
  return `${target.file}#${target.exportName}`
@@ -139,6 +142,19 @@ function checkCrossFileServerOnlyTags(graph: ModuleGraph, load: LoadModule, issu
139
142
  }
140
143
  }
141
144
 
145
+ /** The export a rendered tag stands for when `spec` imports it: `<Counter />`, `<UI.Counter />`, or a namespace exported on, as in `<inner.B />` and `<W.X.B />`. */
146
+ function tagTarget(graph: ModuleGraph, load: LoadModule, spec: { local: string, imported: string }, resolved: string, tag: string): { file: string, exportName: string } | undefined {
147
+ if (tag === spec.local)
148
+ return spec.imported === '*' ? undefined : resolveExportTarget(graph, load, resolved, spec.imported)
149
+ if (!tag.startsWith(`${spec.local}.`))
150
+ return undefined
151
+ const path = tag.slice(spec.local.length + 1).split('.')
152
+ let module: string | undefined = spec.imported === '*' ? resolved : resolveNamespaceModule(graph, load, resolved, spec.imported)
153
+ for (const segment of path.slice(0, -1))
154
+ module = module === undefined ? undefined : resolveNamespaceModule(graph, load, module, segment)
155
+ return module === undefined ? undefined : resolveExportTarget(graph, load, module, path.at(-1)!)
156
+ }
157
+
142
158
  function discoverBindings(
143
159
  graph: ModuleGraph,
144
160
  load: LoadModule,
@@ -168,11 +184,8 @@ function discoverBindings(
168
184
  if (resolved === undefined || !isTsFile(resolved))
169
185
  continue
170
186
  for (const spec of imp.specifiers) {
171
- const tags = spec.imported === '*'
172
- ? [...analysis.staticJsxTags].filter(tag => tag.startsWith(`${spec.local}.`) && !tag.slice(spec.local.length + 1).includes('.')).map(tag => [tag, tag.slice(spec.local.length + 1)] as const)
173
- : analysis.staticJsxTags.has(spec.local) ? [[spec.local, spec.imported] as const] : []
174
- for (const [tag, exportName] of tags) {
175
- const target = resolveExportTarget(graph, load, resolved, exportName)
187
+ for (const tag of analysis.staticJsxTags) {
188
+ const target = tagTarget(graph, load, spec, resolved, tag)
176
189
  const component = target?.file.endsWith('.tsx') === true ? loadPromoted(target.file) : undefined
177
190
  if (target === undefined || component === undefined)
178
191
  continue
@@ -332,6 +345,42 @@ function walkIslandReach(
332
345
  return { reach, clientFiles: visited, cssFiles }
333
346
  }
334
347
 
348
+ function checkCrossFileBrowserWarnings(
349
+ graph: ModuleGraph,
350
+ root: string,
351
+ reach: ReadonlySet<string>,
352
+ clientFiles: ReadonlySet<string>,
353
+ promotedWarnings: PromotedWarning[],
354
+ ): void {
355
+ const checked = new Set<string>(clientFiles)
356
+ for (const [file, analysis] of graph.analyses) {
357
+ if (analysis.browserSpans.length > 0)
358
+ checked.add(file)
359
+ }
360
+ for (const file of checked) {
361
+ if (isInNodeModules(file) || !file.endsWith('.tsx'))
362
+ continue
363
+ const analysis = graph.analyses.get(file)
364
+ if (analysis === undefined || !analysis.hasJsx)
365
+ continue
366
+ const code = graph.source(file)
367
+ const spans: readonly [number, number][] = reach.has(file) ? [[0, code.length]] : analysis.browserSpans
368
+ if (spans.length === 0)
369
+ continue
370
+ const rel = relPosix(root, file)
371
+ const existing = new Set(analysis.warnings.map(w => `${w.start}\0${w.message.replaceAll(file, rel)}`))
372
+ const extra: CompilerWarning[] = []
373
+ checkBodyPropsDestructure(analysis.program, code, spans, analysis.jsxNodes, analysis.filename, extra)
374
+ for (const warning of extra) {
375
+ const key = `${warning.start}\0${warning.message.replaceAll(file, rel)}`
376
+ if (!existing.has(key)) {
377
+ existing.add(key)
378
+ promotedWarnings.push({ file, warning })
379
+ }
380
+ }
381
+ }
382
+ }
383
+
335
384
  /** Shared island planning and reachability analyzer used by both `prunelle build` and `prunelle check`. */
336
385
  export function analyzeIslands(options: AnalyzeIslandsOptions): IslandPlan {
337
386
  const { graph, root, pageFiles, specialFiles } = options
@@ -347,8 +396,9 @@ export function analyzeIslands(options: AnalyzeIslandsOptions): IslandPlan {
347
396
  const existing = targets.get(key)
348
397
  if (existing !== undefined)
349
398
  return existing
350
- const baseName = basename(file, extname(file)).toLowerCase()
351
- const expLower = exportName.toLowerCase()
399
+ // The id lands in a chunk URL, so a name holding `%`, `#`, `?`, `&` or the like keeps only letters, digits, `_`, `.` and `-`.
400
+ const baseName = basename(file, extname(file)).toLowerCase().replace(UNSAFE_ID_CHARS_RE, '-')
401
+ const expLower = exportName.toLowerCase().replace(UNSAFE_ID_CHARS_RE, '-')
352
402
  let id = exportName === 'default' || expLower === baseName ? baseName : `${baseName}-${expLower}`
353
403
  // The id names the entry file and the chunk: two islands sharing a basename (or 'runtime') keep it readable and add a hash of their path.
354
404
  if (usedIds.has(id))
@@ -406,6 +456,7 @@ export function analyzeIslands(options: AnalyzeIslandsOptions): IslandPlan {
406
456
  }
407
457
 
408
458
  const { reach, clientFiles, cssFiles } = walkIslandReach(graph, load, [...rootFiles], clientKeep, options.checkLeaks === true, issues)
459
+ checkCrossFileBrowserWarnings(graph, root, reach, clientFiles, promotedWarnings)
409
460
  return { targets, pageBindings, staticTags, cssFiles, reach, clientFiles, clientKeep, issues, valueUses, promotedWarnings, seedsModuleState: writesModuleState(graph) }
410
461
  }
411
462