prunelle 0.7.3 → 0.8.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.
- package/llms.txt +20 -18
- package/package.json +1 -1
- package/src/a11y/index.ts +9 -2
- package/src/build/graph.ts +1 -1
- package/src/build/index.ts +30 -31
- package/src/build/island-promote.ts +1 -1
- package/src/build/output.ts +1 -1
- package/src/build/prerender.ts +29 -13
- package/src/build/routes.ts +19 -1
- package/src/build/static.ts +24 -2
- package/src/cli/check-forms.ts +16 -6
- package/src/cli/check-links.ts +13 -10
- package/src/cli/check-security.ts +94 -12
- package/src/cli/check.ts +3 -2
- package/src/cli/commands.ts +3 -3
- package/src/cli/upgrade.ts +36 -3
- package/src/compiler/analyze.ts +16 -2
- package/src/compiler/compliance.ts +4 -0
- package/src/compiler/dom-attrs.ts +4 -1
- package/src/compiler/dom.ts +41 -15
- package/src/compiler/emit.ts +1 -1
- package/src/compiler/shared.ts +9 -16
- package/src/compiler/ssr-helpers.ts +45 -21
- package/src/compiler/ssr.ts +32 -16
- package/src/context.ts +2 -0
- package/src/dev/error-log.ts +1 -1
- package/src/dev/index.ts +1 -1
- package/src/dev/supervisor.ts +2 -2
- package/src/dom/attrs.ts +9 -1
- package/src/dom/island.ts +30 -4
- package/src/jsx-runtime.ts +1 -1
- package/src/plugins/context.ts +18 -1
- package/src/plugins/services.ts +1 -0
- package/src/plugins/types.ts +1 -1
- package/src/reactivity/index.ts +14 -2
- package/src/server/action.ts +26 -18
- package/src/server/app-secret.ts +8 -9
- package/src/server/assets.ts +22 -4
- package/src/server/consent.ts +7 -2
- package/src/server/cookies.ts +8 -1
- package/src/server/document.ts +5 -2
- package/src/server/errors.ts +57 -26
- package/src/server/health.ts +2 -2
- package/src/server/http.ts +1 -1
- package/src/server/index.ts +20 -18
- package/src/server/page.ts +12 -15
- package/src/server/public.ts +1 -1
- package/src/server/rate-limit.ts +36 -12
- package/src/server/route-cache.ts +9 -10
- package/src/server/route-table.ts +38 -13
- package/src/server/router.ts +4 -4
- package/src/server/sanitize-html.ts +21 -7
- package/src/server/security.ts +56 -15
- package/src/server/serve-handlers.ts +3 -3
- package/src/server/start.ts +2 -2
- package/src/server/static-dir.ts +3 -10
- package/src/server/stream.ts +4 -4
- package/src/ssr/consent-banner.ts +3 -1
- package/src/ssr/context.ts +85 -2
- package/src/ssr/index.ts +16 -4
- package/src/ssr/navigation.ts +1 -1
- package/src/style.ts +9 -7
- package/src/unrenderable.ts +15 -5
package/llms.txt
CHANGED
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
- 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.
|
|
28
28
|
- `<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.
|
|
29
29
|
- Hydration steps over a node an extension injected, redraws a part whose tag differs from the server's and removes the server nodes no list row claimed (mid-list or past the last row), in production too (dev also warns), and dispatches a bubbling `pru:hydration-mismatch` event (`detail: { removed, added }`) on the list's parent, which reaches the island.
|
|
30
|
-
- **Hydration**: `$hydrate="load" | "visible" | "idle" | "interaction" | "media(...)" | "client"` per call site, or the component file's default `export const hydrate = 'visible'`; unknown modes and `$hydrate` on a non-island fail compile. `idle` islands hydrate within 2 s; an `interaction` island whose chunk fails to load logs the error and retries on the next interaction, replaying it; a chunk URL off this origin is refused with a console error. A delegated handler that throws is reported with `reportError` and the other handlers still run; `onTouchStart` is delegated from the document, which browsers make passive so scrolling never waits on it: a handler that must `preventDefault` adds its own listener in `onMount` with `{ passive: false }`.
|
|
30
|
+
- **Hydration**: `$hydrate="load" | "visible" | "idle" | "interaction" | "media(...)" | "client"` per call site, or the component file's default `export const hydrate = 'visible'`; unknown modes and `$hydrate` on a non-island fail compile. `idle` islands hydrate within 2 s; an `interaction` island also hydrates on a shortcut an element inside it names with `aria-keyshortcuts` (`"Control+K Meta+K"`), pressed anywhere on the page and kept from the browser, and replays it to `document` after the component's `onMount` callbacks; one whose chunk fails to load logs the error and retries on the next interaction, replaying it; a chunk URL off this origin is refused with a console error. A delegated handler that throws is reported with `reportError` and the other handlers still run; `onTouchStart` is delegated from the document, which browsers make passive so scrolling never waits on it: a handler that must `preventDefault` adds its own listener in `onMount` with `{ passive: false }`.
|
|
31
31
|
- The loader carries only the strategies the app's islands can use. A page modulepreloads its eager islands with every chunk they import (a streamed page, its route's eager islands only); a page whose islands all hydrate later downloads the loader alone (about 1 KB gzip) until the first one does, each island bringing the DOM runtime.
|
|
32
32
|
- **Island boundary**: props crossing it must be serializable: JSON primitives plus `Date`, `Map`, `Set`, `URL`, `RegExp`. Functions, signals and JSX in a prop other than `children` are refused; only a page whose props hold one of those classes loads, and preloads, the small file that revives them.
|
|
33
33
|
- A page island receives only the `load()` keys it reads. When the compiler cannot tell which (`data` passed whole to a helper or a child), the whole result is sent and build and check warn: `export const clientData = ['key']` or `(data) => subset` picks what is sent.
|
|
@@ -42,46 +42,48 @@
|
|
|
42
42
|
- 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 `_`.
|
|
43
43
|
- 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 `/`).
|
|
44
44
|
- 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`.
|
|
45
|
-
- 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
|
|
46
|
-
- 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 csrf = false` opts out of origin checks (webhooks, bearer APIs).
|
|
45
|
+
- 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`).
|
|
46
|
+
- 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 csrf = false` opts out of origin checks (webhooks, bearer APIs); `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.
|
|
47
47
|
- 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`.
|
|
48
|
+
- 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`.
|
|
49
|
+
- 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`.
|
|
48
50
|
- Route caching: `export const cache = '1h'` (or `{ maxAge: '1h', staleWhileRevalidate?: '1d' }`) 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.
|
|
49
51
|
- **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.
|
|
50
52
|
- `<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`.
|
|
51
53
|
- `<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.
|
|
52
54
|
- **Regions** (`<Region>` from `prunelle`, swapped by `regions()` from `@prunellejs/spa`): `<Region name="pane" as="section" ...attrs>children</Region>` is server-only like `Head` and renders `<section data-pru-region="pane">`. `<a href data-pru-target="pane">` and `<form data-pru-target="pane">` swap that region in place with the server's answer; without JS the link or form loads the whole page. Load more, live search, nested regions, `refreshRegion()` and the mistakes it reports: `node_modules/@prunellejs/spa/llms.txt`.
|
|
53
55
|
- **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?)`.
|
|
54
|
-
- 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 } }`). 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.
|
|
56
|
+
- 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.
|
|
55
57
|
- `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.
|
|
56
|
-
- `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, unsupported schema libraries (once per vendor) and unguarded public form actions without `protect`.
|
|
58
|
+
- `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`.
|
|
57
59
|
- 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`).
|
|
58
60
|
- In islands, `const form = useAction(fn, { reset?, onSuccess?, onError? })` returns `{ pending, error, fieldErrors, data, action, onSubmit, submit, reset }` (`pending`/`error`/`fieldErrors`/`data` are `ReadonlySignal`s). Wire `<form action={form.action} method="post" onSubmit={form.onSubmit}>` for progressive enhancement; it keeps the SSR protection fields and HTML5 constraints.
|
|
59
61
|
- 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.
|
|
60
|
-
- Server code is stripped from client bundles. CSRF `Origin`/`Sec-Fetch-Site` is checked before middleware and body parsing
|
|
61
|
-
- **Config (`prunelle.config.ts`)**: `defineConfig({ site, lang, port, routesDir, outDir, publicDir, assetPrefix, security, trustedOrigins, trustProxy, maxRequestBodySize, navigation, routeCache, autoPrerender, streamTimeout, consent, compliance, budget, compress, healthCheck, onError, plugins })`. `trustProxy: true | number` trusts that many right-most proxy hops for `X-Forwarded
|
|
62
|
+
- 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.
|
|
63
|
+
- **Config (`prunelle.config.ts`)**: `defineConfig({ site, lang, port, routesDir, outDir, publicDir, assetPrefix, security, trustedOrigins, trustProxy, maxRequestBodySize, navigation, routeCache, autoPrerender, streamTimeout, consent, compliance, budget, compress, healthCheck, onError, 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`.
|
|
62
64
|
- **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 and `export const csrf = false` (`security/headers-off`, `csp-off`, `unsafe-inline`, `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.
|
|
63
65
|
- `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.
|
|
64
|
-
- 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` 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`
|
|
66
|
+
- 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` 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.
|
|
65
67
|
- **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).
|
|
66
68
|
- **Server helpers (`prunelle/server`)**:
|
|
67
69
|
- `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).
|
|
68
70
|
- 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).
|
|
69
|
-
- HTTP: `getClientIp`, `isHttpsRequest`, `isTrustedOrigin`, `verifyOrigin`, `wantsJson`, `safeEqual` (constant-time secret compare), `readStringFields` (a body's string fields, on a null-prototype record), and `safeRedirect(target, fallback = '/')`, which returns the trimmed target only when it is a path on this site, refusing absolute and protocol-relative URLs, backslashes and control characters (`@prunellejs/auth` and the consent endpoint use it).
|
|
71
|
+
- HTTP: `getClientIp`, `isHttpsRequest`, `isTrustedOrigin`, `verifyOrigin`, `wantsJson`, `safeEqual` (constant-time secret compare), `deriveKey(purpose, secret?)` (a 32-byte HKDF key for one purpose from the app secret, or from a plugin's own `secret`, so a token made for one use never verifies for another), `signPayload(purpose, payload, secret?)` / `verifyPayload(purpose, signed, secret?)` (`<hmac>.<payload>` under that key; verify returns the payload or `undefined`; not encrypted), `readStringFields` (a body's string fields, on a null-prototype record), and `safeRedirect(target, fallback = '/')`, which returns the trimmed target only when it is a path on this site, refusing absolute and protocol-relative URLs, backslashes and control characters (`@prunellejs/auth` and the consent endpoint use it).
|
|
70
72
|
- `createRateLimitStore({ maxKeys?, maxHits? })`: a standalone sliding-window store whose `.limiter({ max, windowMs }).hit(key)` returns 0 or the seconds to wait, and `.peek(key)` the same without counting; plugins use `api.rateLimiter()`. A `rateLimit` with no `key` counts the client's network: an IPv4 address without its port or `::ffff:` mapping, or an IPv6 address's /64; `rateLimitAddress(ip)` gives that key to a custom limiter.
|
|
71
73
|
- Standard Schema: `StandardSchemaV1` (including optional `'~standard'.jsonSchema: { input, output? }` Standard JSON Schema extension), `validateSchema`, `validateSchemaSync`, `formatSchemaIssues`, `formatIssuePath`.
|
|
72
74
|
- `declare module 'prunelle/server' { interface PrunelleLocals { ... } }` types `ctx.locals`; `createServer({ root })` runs a built app inside another program.
|
|
73
75
|
- **French web law & Consent (RGPD, CNIL, RGAA, RGESN, LCEN - 0 B client JS)**: `prunelle check` and production `prunelle build` emit actionable warnings (never hard errors):
|
|
74
76
|
- RGAA: `rgaa/img-alt` (`<img>` without `alt`, or `alt={undefined}`/`alt={false}`, unless `role="presentation"` or `aria-hidden`), `rgaa/form-label` (unlabelled `<input>`/`<select>`/`<textarea>`, or a ui `<Select>` with no `Field`, `<label for>` or `ariaLabel`; a `<Label>` component wraps like `<label>`, and `for={ids.name}` matches `id={ids.name}`), `rgaa/accessible-name` (empty or icon-only `<button>`/`<a>`, `<svg role="img">` without `aria-label` or `<title>`), `rgaa/duplicate-id` (duplicate literal `id` in one component, or a static `id` inside `.map()`), `rgaa/positive-tabindex` (`tabindex > 0`).
|
|
75
77
|
- RGAA structure: `rgaa/nested-control` (interactive element inside `<a>`/`<button>`/`<summary>`), `rgaa/link-as-button` (`<a>` without `href` with `onClick`, or `href="#"` / `javascript:`), `rgaa/unknown-role`, `rgaa/unknown-aria`, `rgaa/invalid-aria-value`, `rgaa/skipped-heading` (downward heading jump > 1 in one component), `rgaa/table-without-header` (`<table>` without `<th>`), `rgaa/fieldset-without-legend`, `rgaa/click-without-key` (`onClick` on a non-interactive element without a key handler), `rgaa/role-without-focus` (`role="button"` and other operable roles without `tabIndex`), `rgaa/mouse-only` (`onMouseEnter`/`onMouseOver` without `onFocus`/`onFocusIn`, `onMouseLeave`/`onMouseOut` without `onBlur`/`onFocusOut`), `rgaa/frame-title` (`<iframe>` without `title`), `rgaa/empty-heading`, `rgaa/autocomplete` (email, phone, name or address field without `autocomplete`), `rgaa/autofocus`, `rgaa/meta-refresh`, `rgaa/document-lang` (no `lang` in `prunelle.config.ts` and no `@prunellejs/i18n`, so pages say `<html lang="en">`), and `rgaa/accessibility-statement` (missing `/accessibilite` when `compliance: { publicBody: true }`; on any site, a statement still holding `[à compléter : ...]`).
|
|
76
|
-
- `rgpd/third-party-url`: a third-party `<script src>`, `<link rel="stylesheet|preload|preconnect|dns-prefetch|modulepreload|prefetch|prerender|icon|apple-touch-icon|manifest">`, `<iframe src>`, `<img src/srcset>`, `<video src/poster>`, `<audio>`, `<source>`, `<track>`, `<object data>`, `<embed>`, SVG `<image>`/`<use>`/`<feImage>` `href`, a `style` attribute's `url(...)`, or CSS `@import`/`url(...)` in `src/` or `
|
|
77
|
-
- 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
|
|
78
|
+
- `rgpd/third-party-url`: a third-party `<script src>`, `<link rel="stylesheet|preload|preconnect|dns-prefetch|modulepreload|prefetch|prerender|icon|apple-touch-icon|manifest">`, `<iframe src>`, `<img src/srcset>`, `<video src/poster>`, `<audio>`, `<source>`, `<track>`, `<object data>`, `<embed>`, SVG `<image>`/`<use>`/`<feImage>` `href`, a `style` attribute's `url(...)`, or CSS `@import`/`url(...)` in `src/` or the CSS of `publicDir`, outside `<ConsentGate>` or `site`. A string, template literal (its leading text; in `style`, every text segment), `a ? b : c` or `a ?? b` value is read; `<ConsentGate category="essential">` always renders, so it gates nothing.
|
|
79
|
+
- 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).
|
|
78
80
|
- `lcen/legal-notice`: a page app missing `/mentions-legales`, `/legal`, or a localized variant (`/fr/mentions-legales`, `/[lang]/mentions-legales`), or a legal notice still holding a `[to fill in` placeholder.
|
|
79
|
-
- `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"
|
|
80
|
-
- 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) are silenced the same way, the comment going on the line above the `<form>` or `<option>`; its errors cannot be.
|
|
81
|
+
- `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` 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.
|
|
82
|
+
- 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`.
|
|
81
83
|
- 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`, `has(cat)`, `all()`), refuses `ctx.cookies.set(name, val, { category })` before consent is granted, 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.
|
|
82
|
-
- `<ConsentBanner policyHref?="/cookies" 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>`; `<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"`.
|
|
84
|
+
- `<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>`; `<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"`.
|
|
83
85
|
- **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`.
|
|
84
|
-
- `defineConfig({ navigation: { viewTransitions?: boolean (true), prefetch?: 'conservative' | 'moderate' | 'eager' | false ('conservative'), prerender?: 'conservative' | 'moderate' | 'eager' | boolean (false; true is 'moderate'; it runs `load()` of pages nobody opens) } })`; a bad value throws `prunelle: navigation.<key> is ...`.
|
|
86
|
+
- `defineConfig({ navigation: { viewTransitions?: boolean (true; `false` also keeps `@prunellejs/spa` region and page swaps out of view transitions), prefetch?: 'conservative' | 'moderate' | 'eager' | false ('conservative'), prerender?: 'conservative' | 'moderate' | 'eager' | boolean (false; true is 'moderate'; it runs `load()` of pages nobody opens) } })`; a bad value throws `prunelle: navigation.<key> is ...`.
|
|
85
87
|
- `data-pru-keep-scroll="<key>"` on a scrolling element keeps its `scrollTop` across page loads (restored before first paint when the next page has the same key; per history entry on back/forward/reload; a no-op when `sessionStorage` is blocked), through one inline hashed script at the end of `<body>` on pages using the attribute. The key is a literal string without `"<>&` (compile error otherwise, also for a nested panel of the same key); the same key on two elements of one rendered page throws `prunelle: data-pru-keep-scroll="..." is on two elements of one page`. `@prunellejs/spa` keeps the same attribute across its swaps.
|
|
86
88
|
- **Static files & CSS**: Files in `public/` are served at `/` (dotfiles and dot folders stay out of the build except `.well-known/`; `prunelle check` warns `security/public-dotfile`; a plugin `emitAsset`/`emitPublic` path that leaves the output folder throws, naming the plugin) with ETag/`304` (`Cache-Control: no-cache` in `prunelle dev`; embedded in `--static` and `--compile`); prerendered pages (sent with `Cache-Control: no-cache`, so a revisit revalidates) and hashed assets answer an ETag, a `304` and a `HEAD` length too. Import `.css` or `*.module.css` directly from any component or layout.
|
|
87
89
|
- `prunelle build` consolidates local stylesheets into at most one site-wide hashed immutable sheet plus one per-route sheet when needed, preserving `@layer` and plugin-before-app cascade order.
|
|
@@ -96,7 +98,7 @@
|
|
|
96
98
|
- `prunelle start [dir] [--port 3000] [--host [addr]]`; `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).
|
|
97
99
|
- Plugin commands: `prunelle a11y [--draft [dest]] [--force] [--audit-date YYYY-MM-DD --rate <percent>] [--json] [--routes /a,/b]` (via `a11y()` from `prunelle/config`; 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; `--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, and `prunelle check` warns about `[à compléter : ...]` left in any published statement), `prunelle ui-eject <grammar> [dest]`, `prunelle mcp-footprint`, `prunelle i18n-check`, `prunelle icons-find <words> [--set <prefix>] [--limit <n>]`, `prunelle pwa-vapid [--json]`. They load from `prunelle.config.ts` only when the first word is no built-in, and take `--root <dir>` and `--help`.
|
|
98
100
|
- **CLI (dev, editor & agent tooling)**:
|
|
99
|
-
- `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; 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.
|
|
101
|
+
- `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.
|
|
100
102
|
- `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.
|
|
101
103
|
- `prunelle docs <words...> [--json] [--limit <n>]`: searches `llms.txt` of `prunelle` and every installed `@prunellejs/*` package at the installed versions; `--json` prints `{ query, words, packages, matches }`.
|
|
102
104
|
- `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.
|
|
@@ -114,7 +116,7 @@
|
|
|
114
116
|
- `api.rateLimiter({ max, windowMs })` returns a limiter in the server's store (bounded to 10 000 keys and 1 000 000 hits, swept every minute, dropped with the server) for a limit a route option cannot key, such as per email: `hit(key)` returns 0, or the whole seconds to wait; `peek(key)` answers the same without counting, to check a limit that only some outcomes count.
|
|
115
117
|
- Build hooks: `build(ctx)` (`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 }) => [...]`), `css`, `prerenderPaths`, `clientEntry`, `regionClientEntry`, `watchPaths`, `commands`.
|
|
116
118
|
- Page hooks: `head(head, ctx)`, `transformHtml`, `inlineScripts` (the inline scripts the plugin writes into pages, each as it stands between its tags: every page's CSP allows them by hash, since prunelle never hashes a script it finds in a page), `onError(info)` (`{ error, request, source, requestId }`), `check(ctx)`.
|
|
117
|
-
- `requires({ root, site, consentCategories })` returns one message per setting the plugin needs in production, naming it and its fix: a production start (`NODE_ENV=production`, not `prunelle dev`) refuses while any is unmet, listing them all; `prunelle dev`, tests and `prunelle check` warn once each; a throwing `requires` counts as unmet. First-party: auth refuses an in-memory store, jobs an in-memory DB, files `memoryFiles()` or a missing signing secret, mail a missing transport or `from`, mcp a missing `token`, seo and a content feed a missing `site`, analytics a consent category `consent.categories` does not declare.
|
|
119
|
+
- `requires({ root, site, consentCategories })` returns one message per setting the plugin needs in production, naming it and its fix: a production start (`NODE_ENV=production`, not `prunelle dev`) refuses while any is unmet, listing them all; `prunelle dev`, tests and `prunelle check` warn once each; a throwing `requires` counts as unmet. First-party: auth refuses an in-memory store, a missing or short `secret`, or a missing `mailer` when `requireEmailVerification` is on, jobs an in-memory DB, files `memoryFiles()` or a missing signing secret, mail a missing transport or `from`, mcp a missing `token`, seo and a content feed a missing `site`, analytics a consent category `consent.categories` does not declare.
|
|
118
120
|
- Runtime state (timers, connections, caches) is created in `server(api)` and released in `api.onShutdown()`, never in the plugin factory: `prunelle dev` starts the next server on the same instance before shutting the last one down, and a new process on a `prunelle.config.ts` edit. A throwing `onShutdown` or `onError` hook is logged with its plugin's name; the others still run.
|
|
119
121
|
- First-party packages (19 total with `prunelle`), each with its full reference:
|
|
120
122
|
- `@prunellejs/ui` (`node_modules/@prunellejs/ui/llms.txt`): zero-JS layout, form and overlay primitives, island widgets (`Tabs`, `Menu`, `Select`, `CommandPalette`, `DataTable`, `toast()`), `@layer kui` Style Grammars, `prunelle ui-eject`.
|
|
@@ -136,7 +138,7 @@
|
|
|
136
138
|
- `@prunellejs/tailwind` (`node_modules/@prunellejs/tailwind/llms.txt`): Tailwind v4 via `tailwind()`.
|
|
137
139
|
- `@prunellejs/spa` (`node_modules/@prunellejs/spa/llms.txt`): `regions()` for `<Region>` swaps and opt-in `spa()` full-page navigation with `[data-persist]` islands.
|
|
138
140
|
- **Server builds & `--compile`**:
|
|
139
|
-
- `prunelle build` writes a stage folder beside `outDir` and renames it in only once every step (bundles, plugin hooks, prerender, `--compile`) passed, so a failed build leaves the previous `outDir` byte-identical and a running `prunelle start` keeps serving it. Each build is marked with `.prunelle-output`; a folder holding files prunelle did not build is refused by name (an empty one or an unmarked older prunelle build is replaced).
|
|
141
|
+
- `prunelle build` writes a stage folder beside `outDir` and renames it in only once every step (bundles, plugin hooks, prerender, `--compile`) passed, so a failed build leaves the previous `outDir` byte-identical and a running `prunelle start` keeps serving it. Each build is marked with `.prunelle-output`; a folder holding files prunelle did not build is refused by name (an empty one or an unmarked older prunelle build is replaced; a folder holding only a subfolder named like a custom `assetPrefix` is not one). An `outDir` inside `publicDir` is refused.
|
|
140
142
|
- Once a build lands, `prunelle start` loads it in-process with no restart: requests arriving meanwhile wait for it, plugin `server()` runs again and the old build's `api.onShutdown()` hooks run, a build that fails to load is logged while the old one keeps answering, and a new port/host/`maxRequestBodySize` needs a restart. A file it can no longer read answers `404` `no-store`.
|
|
141
143
|
- The hashed client files the previous build made and this one dropped are hard-linked in (`manifest.carriedAssets`, never linked from a page) and served one more deploy, by `prunelle start`, a `--static` export and `--compile`, so a page loaded before the deploy still loads its deferred island chunks.
|
|
142
144
|
- Server `Bun.build` keeps npm dependencies external (`packages: 'external'`) while compiling `@prunellejs/*` TSX packages; `prunelle build --compile` bundles everything + `public/` assets (`with { type: "file" }`) into one standalone Bun executable (`NODE_ENV` defaults to `production`). The binary autoloads neither `.env` nor `bunfig.toml` from its cwd: the host passes the environment (systemd `EnvironmentFile=`, Compose `env_file:`). `PRUNELLE_DEV=1` throws at start inside a binary or with `NODE_ENV=production`.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "prunelle",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.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",
|
package/src/a11y/index.ts
CHANGED
|
@@ -410,9 +410,16 @@ async function runA11yCommand(args: string[], root: string, pluginOptions: A11yP
|
|
|
410
410
|
return badUsage('--status is gone: the compliance level follows the manual audit, so pass --audit-date YYYY-MM-DD and --rate <percent> (100 is totally, 50 or more partially compliant)')
|
|
411
411
|
if ((values['audit-date'] === undefined) !== (values.rate === undefined))
|
|
412
412
|
return badUsage('--audit-date and --rate go together: pass the day the manual RGAA audit ended and the percentage of criteria it found met')
|
|
413
|
-
const
|
|
414
|
-
|
|
413
|
+
const rawRate = values.rate?.trim()
|
|
414
|
+
const manualAudit = values['audit-date'] !== undefined && rawRate !== undefined
|
|
415
|
+
? { date: new Date(`${values['audit-date']}T00:00:00Z`), rate: rawRate === '' ? Number.NaN : Number(rawRate) }
|
|
415
416
|
: undefined
|
|
417
|
+
if (manualAudit !== undefined) {
|
|
418
|
+
if (Number.isNaN(manualAudit.date.getTime()))
|
|
419
|
+
return badUsage('--audit-date must be a valid YYYY-MM-DD date, e.g. --audit-date 2026-03-31')
|
|
420
|
+
if (!(manualAudit.rate >= 0 && manualAudit.rate <= 100))
|
|
421
|
+
return badUsage(`--rate must be a percentage from 0 to 100, got "${values.rate}"`)
|
|
422
|
+
}
|
|
416
423
|
|
|
417
424
|
const wantDraft = values.draft !== undefined
|
|
418
425
|
const force = values.force === true
|
package/src/build/graph.ts
CHANGED
|
@@ -133,7 +133,7 @@ export class ModuleGraph {
|
|
|
133
133
|
private readonly deps = new Map<string, string[]>()
|
|
134
134
|
|
|
135
135
|
/** `root` is the app's folder, for the root-relative paths in errors. */
|
|
136
|
-
constructor(
|
|
136
|
+
constructor(readonly root: string, private readonly cache?: BuildCache) {}
|
|
137
137
|
|
|
138
138
|
/** The file's mtime and size; only tracked when a cache is in use. */
|
|
139
139
|
stamp(file: string): FileStamp | undefined {
|
package/src/build/index.ts
CHANGED
|
@@ -38,7 +38,7 @@ import { parseByteSize } from './byte-size'
|
|
|
38
38
|
import { SERVER_ENTRY_FILE, serverEntrySource } from './server-entry'
|
|
39
39
|
import { PRUNELLE_SRC_ROOT, resolvePrunelleSpecifier } from './resolve'
|
|
40
40
|
import { ancestorFiles, assertNoRouteConflicts, discoverRouteMatchers, fileToRoutePath, hasRouteHandlerExport, missingPathsProblem, normalizeRoutePattern, routeExportProblem, routeFileProblem, SPECIAL_ROUTE_FILES } from './routes'
|
|
41
|
-
import { emitStaticNotFoundPages, exportStatic } from './static'
|
|
41
|
+
import { emitStaticNotFoundPages, exportStatic, normalizeAssetPrefix } from './static'
|
|
42
42
|
import { findUnknownStatusPages } from './status-pages'
|
|
43
43
|
import { consolidateStylesheets } from './style-bundles'
|
|
44
44
|
|
|
@@ -175,8 +175,8 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
175
175
|
const stageSuffix = processSuffix()
|
|
176
176
|
const stageDir = stageDirFor(finalOutDir, stageSuffix)
|
|
177
177
|
const outDir = options.static ? join(cacheBaseDir, `${STATIC_STAGE_PREFIX}${stageSuffix}`) : stageDir
|
|
178
|
-
const assetPrefix = (options.assetPrefix ?? fileConfig.assetPrefix ?? '/_pru')
|
|
179
|
-
assertOwnOutDir(root, finalOutDir
|
|
178
|
+
const assetPrefix = normalizeAssetPrefix(options.assetPrefix ?? fileConfig.assetPrefix ?? '/_pru')
|
|
179
|
+
assertOwnOutDir(root, finalOutDir)
|
|
180
180
|
removeStaleStages(finalOutDir)
|
|
181
181
|
removeDeadProcessDirs(cacheBaseDir, STATIC_STAGE_PREFIX)
|
|
182
182
|
const site = (options.site ?? fileConfig.site)?.replace(/\/$/, '') || undefined
|
|
@@ -194,28 +194,9 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
194
194
|
|
|
195
195
|
try {
|
|
196
196
|
return await runWithAppContext(appCtx, () => runBuild({
|
|
197
|
-
options,
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
routesDir,
|
|
201
|
-
publicDir,
|
|
202
|
-
finalOutDir,
|
|
203
|
-
stageDir,
|
|
204
|
-
outDir,
|
|
205
|
-
stageSuffix,
|
|
206
|
-
assetPrefix,
|
|
207
|
-
site,
|
|
208
|
-
lang: options.lang ?? fileConfig.lang,
|
|
209
|
-
budget: resolveBudget(options.maxJs, fileConfig.budget),
|
|
210
|
-
defaultPort: fileConfig.port,
|
|
211
|
-
compliance: fileConfig.compliance,
|
|
212
|
-
consentMaxAge: fileConfig.consent?.maxAge,
|
|
213
|
-
autoPrerender: options.autoPrerender ?? fileConfig.autoPrerender ?? false,
|
|
214
|
-
minify: options.minify ?? true,
|
|
215
|
-
isDev,
|
|
216
|
-
nodeEnv: effectiveNodeEnv,
|
|
217
|
-
appCtx,
|
|
218
|
-
publicFiles,
|
|
197
|
+
options, root, plugins: resolvePlugins(options.plugins ?? fileConfig.plugins), routesDir, publicDir, finalOutDir, stageDir, outDir, stageSuffix, assetPrefix, site,
|
|
198
|
+
lang: options.lang ?? fileConfig.lang, budget: resolveBudget(options.maxJs, fileConfig.budget), defaultPort: fileConfig.port, compliance: fileConfig.compliance,
|
|
199
|
+
consentMaxAge: fileConfig.consent?.maxAge, autoPrerender: options.autoPrerender ?? fileConfig.autoPrerender ?? false, minify: options.minify ?? true, isDev, nodeEnv: effectiveNodeEnv, appCtx, publicFiles,
|
|
219
200
|
}))
|
|
220
201
|
}
|
|
221
202
|
finally {
|
|
@@ -369,15 +350,33 @@ function copyPublicFiles(publicDir: string, outPublicDir: string, publicFiles: P
|
|
|
369
350
|
}
|
|
370
351
|
}
|
|
371
352
|
|
|
372
|
-
function collectNonEmptyClientAssets(
|
|
353
|
+
function collectNonEmptyClientAssets(
|
|
354
|
+
clientDir: string,
|
|
355
|
+
assetPrefix: string,
|
|
356
|
+
client: { assetFiles: readonly string[], srcCssToUrl: Map<string, string>, islandCssUrl: Map<string, string>, styleUrls: string[] },
|
|
357
|
+
): { assets: string[], builtClientAssets: Set<string> } {
|
|
373
358
|
const assets: string[] = []
|
|
374
|
-
|
|
359
|
+
const dropped = new Set<string>()
|
|
360
|
+
for (const rel of client.assetFiles) {
|
|
375
361
|
const abs = join(clientDir, rel)
|
|
376
362
|
const size = fileSize(abs)
|
|
377
|
-
if (size === 0)
|
|
378
|
-
|
|
379
|
-
|
|
363
|
+
if (size === 0 || size === undefined) {
|
|
364
|
+
if (size === 0)
|
|
365
|
+
rmSync(abs, { force: true })
|
|
366
|
+
dropped.add(`${assetPrefix}/${rel}`)
|
|
367
|
+
}
|
|
368
|
+
else {
|
|
380
369
|
assets.push(rel)
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
if (dropped.size > 0) {
|
|
373
|
+
for (const map of [client.srcCssToUrl, client.islandCssUrl]) {
|
|
374
|
+
for (const [k, url] of map) {
|
|
375
|
+
if (dropped.has(url))
|
|
376
|
+
map.delete(k)
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
client.styleUrls = client.styleUrls.filter(url => !dropped.has(url))
|
|
381
380
|
}
|
|
382
381
|
return { assets, builtClientAssets: new Set(assets) }
|
|
383
382
|
}
|
|
@@ -475,7 +474,7 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
|
|
|
475
474
|
if (options.cache !== undefined)
|
|
476
475
|
refreshCacheWatches(options.cache, graph, [...pluginCssFiles, ...(hasConfigFile ? [configSrc] : [])])
|
|
477
476
|
|
|
478
|
-
const { assets, builtClientAssets } = collectNonEmptyClientAssets(clientDir, client
|
|
477
|
+
const { assets, builtClientAssets } = collectNonEmptyClientAssets(clientDir, assetPrefix, client)
|
|
479
478
|
|
|
480
479
|
const { routes, statusPages, globalStyles, routeSourceFiles, globalSourceFiles } = buildRouteEntries({
|
|
481
480
|
graph, islands, islandChunks: client.islandChunks, srcCssToUrl: client.srcCssToUrl, islandCssUrl: client.islandCssUrl,
|
|
@@ -26,7 +26,7 @@ export function resolveExportTarget(
|
|
|
26
26
|
seen = new Set<string>(),
|
|
27
27
|
): { file: string, exportName: string } | undefined {
|
|
28
28
|
if (depth > MAX_REEXPORT_DEPTH)
|
|
29
|
-
|
|
29
|
+
throw new Error(`prunelle compiler: "${exportName}" is re-exported through more than ${MAX_REEXPORT_DEPTH} files in ${relPosix(graph.root, file)}: import it from a file fewer re-exports away from where it is declared.`)
|
|
30
30
|
const key = `${file}\0${exportName}`
|
|
31
31
|
if (seen.has(key))
|
|
32
32
|
return { file, exportName }
|
package/src/build/output.ts
CHANGED
|
@@ -8,7 +8,7 @@ import { relPosix } from './files'
|
|
|
8
8
|
export const OUTPUT_MARKER = '.prunelle-output'
|
|
9
9
|
|
|
10
10
|
/** Throws unless `outDir` is missing, empty, or a folder prunelle built: replacing it must never delete someone's files. */
|
|
11
|
-
export function assertOwnOutDir(root: string, outDir: string
|
|
11
|
+
export function assertOwnOutDir(root: string, outDir: string): void {
|
|
12
12
|
if (!existsSync(outDir))
|
|
13
13
|
return
|
|
14
14
|
const names = new Set(readdirSync(outDir))
|
package/src/build/prerender.ts
CHANGED
|
@@ -36,25 +36,27 @@ function extForContentType(contentType: string | null): string {
|
|
|
36
36
|
return CONTENT_TYPE_EXT[mime] ?? ''
|
|
37
37
|
}
|
|
38
38
|
|
|
39
|
-
function assertSafePrerenderPath(raw: string, original: string): string {
|
|
39
|
+
function assertSafePrerenderPath(raw: string, original: string, routeLabel: string): string {
|
|
40
40
|
const decoded = decodeRequestPath(raw)
|
|
41
41
|
if (decoded?.staticPath === undefined)
|
|
42
|
-
throw new Error(`prunelle build: unsafe or malformed prerender path "${original}".`)
|
|
42
|
+
throw new Error(`prunelle build: unsafe or malformed prerender path "${original}" from ${routeLabel}.`)
|
|
43
43
|
if (decoded.staticPath.split('/').some(seg => seg === '..' || seg.includes('\\') || seg.includes('\0')))
|
|
44
|
-
throw new Error(`prunelle build: prerender path "${original}" escapes output directory.`)
|
|
44
|
+
throw new Error(`prunelle build: prerender path "${original}" from ${routeLabel} escapes output directory.`)
|
|
45
45
|
return decoded.staticPath
|
|
46
46
|
}
|
|
47
47
|
|
|
48
|
-
function normalizePrerenderUrl(urlStr: string): string {
|
|
49
|
-
|
|
48
|
+
function normalizePrerenderUrl(urlStr: string, routeLabel: string): string {
|
|
49
|
+
if (urlStr.includes('?') || urlStr.includes('#'))
|
|
50
|
+
throw new Error(`prunelle build: prerender path "${urlStr}" from ${routeLabel} cannot contain "?" or "#": percent-encode it (e.g. %3F or %23) or remove the query/hash.`)
|
|
51
|
+
assertSafePrerenderPath(urlStr, urlStr, routeLabel)
|
|
50
52
|
let pathname: string
|
|
51
53
|
try {
|
|
52
54
|
pathname = new URL(urlStr, 'http://localhost').pathname
|
|
53
55
|
}
|
|
54
56
|
catch {
|
|
55
|
-
throw new Error(`prunelle build: invalid prerender path "${urlStr}".`)
|
|
57
|
+
throw new Error(`prunelle build: invalid prerender path "${urlStr}" from ${routeLabel}.`)
|
|
56
58
|
}
|
|
57
|
-
const staticPath = assertSafePrerenderPath(pathname, urlStr)
|
|
59
|
+
const staticPath = assertSafePrerenderPath(pathname, urlStr, routeLabel)
|
|
58
60
|
return staticPath.length > 1 && staticPath.endsWith('/') ? (staticPath.replace(TRAILING_SLASHES_RE, '') || '/') : staticPath
|
|
59
61
|
}
|
|
60
62
|
|
|
@@ -107,11 +109,15 @@ export interface PrerenderOptions {
|
|
|
107
109
|
|
|
108
110
|
const ROUTE_SOURCE_EXTENSIONS = ['.tsx', '.ts', '.jsx', '.js', '.mdx', '.md']
|
|
109
111
|
|
|
110
|
-
// The source file of a built route module (`server/posts/[slug].js` is `src/routes/posts/[slug].tsx`)
|
|
112
|
+
// The source file of a built route module (`server/posts/[slug].js` or `server/src/routes/posts/[slug].js` is `src/routes/posts/[slug].tsx`).
|
|
111
113
|
function routeSource(options: PrerenderOptions, route: RouteManifestEntry): string {
|
|
112
|
-
const
|
|
113
|
-
const
|
|
114
|
-
|
|
114
|
+
const stripped = route.file.replace(/^server\//, '').replace(/\.js$/, '')
|
|
115
|
+
for (const base of [options.routesDir, options.root]) {
|
|
116
|
+
const source = ROUTE_SOURCE_EXTENSIONS.map(ext => `${join(base, stripped)}${ext}`).find(file => existsSync(file))
|
|
117
|
+
if (source !== undefined)
|
|
118
|
+
return relPosix(options.root, source)
|
|
119
|
+
}
|
|
120
|
+
return route.file
|
|
115
121
|
}
|
|
116
122
|
|
|
117
123
|
// The build fails through the CLI, which prints only the message: the page's own error and its stack go in it.
|
|
@@ -175,7 +181,8 @@ async function planRoutes(options: PrerenderOptions, modules: Record<string, unk
|
|
|
175
181
|
urls = await runPluginHook(plugin, 'prerenderPaths', () => plugin.prerenderPaths!(urls, route))
|
|
176
182
|
}
|
|
177
183
|
|
|
178
|
-
|
|
184
|
+
const routeLabel = `"${route.path}" (${routeSource(options, route)})`
|
|
185
|
+
urls = [...new Set(urls.map(u => normalizePrerenderUrl(u, routeLabel)))]
|
|
179
186
|
|
|
180
187
|
if (urls.length === 0) {
|
|
181
188
|
if (hasPathsFn)
|
|
@@ -205,6 +212,7 @@ export async function prerender(options: PrerenderOptions) {
|
|
|
205
212
|
try {
|
|
206
213
|
const routePlans = await planRoutes(options, entry?.modules)
|
|
207
214
|
const allTasks = routePlans.flatMap(plan => plan.tasks)
|
|
215
|
+
const claimedFiles = new Map<string, { url: string, source: string }>()
|
|
208
216
|
let nextIdx = 0
|
|
209
217
|
let failed = false
|
|
210
218
|
const runWorker = async (): Promise<void> => {
|
|
@@ -231,6 +239,14 @@ export async function prerender(options: PrerenderOptions) {
|
|
|
231
239
|
}
|
|
232
240
|
const ct = res.headers.get('content-type')
|
|
233
241
|
const absOut = resolvePrerenderPath(prerenderDir, u, isStatic, ct)
|
|
242
|
+
const relOut = relPosix(isStatic ? prerenderDir : outDir, absOut)
|
|
243
|
+
const source = routeSource(options, task.route)
|
|
244
|
+
const prev = claimedFiles.get(absOut)
|
|
245
|
+
if (prev !== undefined) {
|
|
246
|
+
failed = true
|
|
247
|
+
throw new Error(`prunelle build: prerendered file "${relOut}" is written by both "${prev.url}" (${prev.source}) and "${u}" (${source}).`)
|
|
248
|
+
}
|
|
249
|
+
claimedFiles.set(absOut, { url: u, source })
|
|
234
250
|
mkdirSync(dirname(absOut), { recursive: true })
|
|
235
251
|
if ((ct ?? '').toLowerCase().includes('text/html')) {
|
|
236
252
|
const html = await res.text()
|
|
@@ -250,7 +266,7 @@ export async function prerender(options: PrerenderOptions) {
|
|
|
250
266
|
else {
|
|
251
267
|
writeFileSync(absOut, new Uint8Array(await res.arrayBuffer()))
|
|
252
268
|
}
|
|
253
|
-
task.relOut =
|
|
269
|
+
task.relOut = relOut
|
|
254
270
|
}
|
|
255
271
|
}
|
|
256
272
|
|
package/src/build/routes.ts
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
// Route files: their URL patterns, groups, param matchers, conflicts, and the `_layout`/`_middleware` chain that wraps them.
|
|
2
2
|
|
|
3
|
+
import type { Expression } from 'oxc-parser'
|
|
3
4
|
import type { ModuleAnalysis } from '../compiler/index'
|
|
4
5
|
import { existsSync } from 'node:fs'
|
|
5
6
|
import { basename, dirname, join, relative } from 'node:path'
|
|
6
7
|
import { parseCacheExport } from '../compiler/cacheability'
|
|
8
|
+
import { parseCacheDuration } from '../server/route-cache'
|
|
7
9
|
import { BUILTIN_PARAM_MATCHER_NAMES, extractPatternMatchers, isBuiltinMatcher, parsePatternSegment } from '../server/param-matchers'
|
|
8
10
|
import { relPosix } from './files'
|
|
9
11
|
|
|
@@ -144,6 +146,18 @@ function findExportOffset(analysis: ModuleAnalysis, exportName: string): number
|
|
|
144
146
|
return 0
|
|
145
147
|
}
|
|
146
148
|
|
|
149
|
+
// `idleTimeout = -1` as written: a negative number is a unary minus on a literal.
|
|
150
|
+
function idleTimeoutText(init: Expression | null | undefined): string | undefined {
|
|
151
|
+
if (init?.type === 'Literal')
|
|
152
|
+
return `idleTimeout = ${init.raw ?? String(init.value)}`
|
|
153
|
+
if (init?.type === 'UnaryExpression' && init.operator === '-' && init.argument.type === 'Literal')
|
|
154
|
+
return `idleTimeout = -${init.argument.raw ?? String(init.argument.value)}`
|
|
155
|
+
return undefined
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** A BCP 47 language tag as `<html lang>` takes it: `fr`, `en-GB`, `zh-Hant-TW`. */
|
|
159
|
+
const LANG_TAG_RE = /^[a-z]{2,3}(?:-[a-z\d]{2,8})*$/i
|
|
160
|
+
|
|
147
161
|
/** Returns the first route export problem together with its byte offset in the module source. */
|
|
148
162
|
export function routeExportProblemLocation(analysis: ModuleAnalysis, file: string): { message: string, offset: number } | undefined {
|
|
149
163
|
for (const name of analysis.exportedNames) {
|
|
@@ -159,6 +173,10 @@ export function routeExportProblemLocation(analysis: ModuleAnalysis, file: strin
|
|
|
159
173
|
const init = d.init
|
|
160
174
|
if (name === 'paths' && init !== null && init.type !== 'ArrowFunctionExpression' && init.type !== 'FunctionExpression')
|
|
161
175
|
return { message: `export const paths in ${file}: export function paths() returning the URLs, such as () => ['/posts/a'].`, offset: d.start }
|
|
176
|
+
if (name === 'lang' && !(init?.type === 'Literal' && typeof init.value === 'string' && LANG_TAG_RE.test(init.value)))
|
|
177
|
+
return { message: `${init?.type === 'Literal' ? `lang = ${init.raw ?? String(init.value)}` : 'lang set at runtime'} in ${file}: write the language the page is written in, such as lang = 'fr' or lang = 'en-GB'.`, offset: d.start }
|
|
178
|
+
if (name === 'idleTimeout' && !(init?.type === 'Literal' && parseCacheDuration(init.value, true) !== undefined))
|
|
179
|
+
return { message: `${idleTimeoutText(init) ?? 'idleTimeout set at runtime'} in ${file}: write the seconds a request may stay silent, such as idleTimeout = 120 or idleTimeout = '5m', or 0 for no limit.`, offset: d.start }
|
|
162
180
|
if (name === 'prerender' && !(init?.type === 'Literal' && typeof init.value === 'boolean'))
|
|
163
181
|
return { message: `${init?.type === 'Literal' ? `prerender = ${init.raw ?? String(init.value)}` : 'prerender set at runtime'} in ${file}: write prerender = true or prerender = false.`, offset: d.start }
|
|
164
182
|
}
|
|
@@ -169,7 +187,7 @@ export function routeExportProblemLocation(analysis: ModuleAnalysis, file: strin
|
|
|
169
187
|
return undefined
|
|
170
188
|
}
|
|
171
189
|
|
|
172
|
-
/** The first route export prunelle never reads (Next, Remix and Astro names), `paths` that is not a function,
|
|
190
|
+
/** The first route export prunelle never reads (Next, Remix and Astro names), `paths` that is not a function, `prerender` that is not literally `true` or `false`, or `lang` that is not a language tag literal, worded for `prunelle build` and `prunelle check` to prefix. */
|
|
173
191
|
export function routeExportProblem(analysis: ModuleAnalysis, file: string): string | undefined {
|
|
174
192
|
return routeExportProblemLocation(analysis, file)?.message
|
|
175
193
|
}
|
package/src/build/static.ts
CHANGED
|
@@ -22,6 +22,28 @@ import { pageFailure } from './prerender'
|
|
|
22
22
|
import { writeStaticHostFiles } from './static-headers'
|
|
23
23
|
|
|
24
24
|
const LEADING_SLASH_RE = /^\//
|
|
25
|
+
const REMOTE_ASSET_PREFIX_RE = /^(?:https?:)?\/\//i
|
|
26
|
+
|
|
27
|
+
/** Validates `assetPrefix`: must be a root-relative path (`/assets`) or an absolute URL (`https://cdn.example.com/_pru`). */
|
|
28
|
+
export function normalizeAssetPrefix(raw: string): string {
|
|
29
|
+
const hint = `prunelle: invalid assetPrefix ${JSON.stringify(raw)}: use a path starting with "/" (e.g. "/_pru") or an absolute URL (e.g. "https://cdn.example.com/_pru").`
|
|
30
|
+
if (raw === '' || /[\s?#]/.test(raw))
|
|
31
|
+
throw new Error(hint)
|
|
32
|
+
if (REMOTE_ASSET_PREFIX_RE.test(raw)) {
|
|
33
|
+
try {
|
|
34
|
+
const url = new URL(raw.startsWith('//') ? `https:${raw}` : raw)
|
|
35
|
+
if (url.hostname === '' || url.search !== '' || url.hash !== '')
|
|
36
|
+
throw new Error(hint)
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
throw new Error(hint)
|
|
40
|
+
}
|
|
41
|
+
return raw.replace(/\/+$/, '')
|
|
42
|
+
}
|
|
43
|
+
if (!raw.startsWith('/') || raw.split('/').some(seg => seg === '..' || seg.includes('\\')))
|
|
44
|
+
throw new Error(hint)
|
|
45
|
+
return raw.replace(/\/+$/, '')
|
|
46
|
+
}
|
|
25
47
|
|
|
26
48
|
export interface StaticExportOptions {
|
|
27
49
|
/** The app's folder, whose `.prunelle-cache/` keeps the brotli of what was compressed before. */
|
|
@@ -189,8 +211,8 @@ export async function exportStatic(options: StaticExportOptions): Promise<void>
|
|
|
189
211
|
if (options.notFoundEmitted !== true)
|
|
190
212
|
await emitStaticNotFoundPages(options)
|
|
191
213
|
|
|
192
|
-
//
|
|
193
|
-
const assetDir = join(stageDir, options.assetPrefix.replace(LEADING_SLASH_RE, ''))
|
|
214
|
+
// Root-relative prefixes mirror the URL path under <stage>/; absolute CDN prefixes land in <stage>/client/ like the server build.
|
|
215
|
+
const assetDir = join(stageDir, REMOTE_ASSET_PREFIX_RE.test(options.assetPrefix) ? 'client' : options.assetPrefix.replace(LEADING_SLASH_RE, ''))
|
|
194
216
|
for (const rel of options.assets)
|
|
195
217
|
copyInto(assetDir, rel, join(clientDir, rel))
|
|
196
218
|
// Also pick up files written directly into the public folder without registering them.
|
package/src/cli/check-forms.ts
CHANGED
|
@@ -499,17 +499,27 @@ function buildMiddlewareLookup(routesDir: string, routeFiles: readonly string[],
|
|
|
499
499
|
return { hasAncestorMiddleware, pagesRendering }
|
|
500
500
|
}
|
|
501
501
|
|
|
502
|
+
function compilePattern(source: string): RegExp | undefined {
|
|
503
|
+
try {
|
|
504
|
+
return new RegExp(source, 'u')
|
|
505
|
+
}
|
|
506
|
+
catch {
|
|
507
|
+
try {
|
|
508
|
+
return new RegExp(source)
|
|
509
|
+
}
|
|
510
|
+
catch {
|
|
511
|
+
return undefined
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
|
|
502
516
|
/** The `patternProperties` keys of a schema as regexes: a field name one matches is a key the schema accepts. */
|
|
503
517
|
function fieldPatterns(patternProperties: unknown): RegExp[] {
|
|
504
518
|
if (!isRecord(patternProperties))
|
|
505
519
|
return []
|
|
506
520
|
return Object.keys(patternProperties).flatMap((source) => {
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
}
|
|
510
|
-
catch {
|
|
511
|
-
return []
|
|
512
|
-
}
|
|
521
|
+
const pattern = compilePattern(source)
|
|
522
|
+
return pattern === undefined ? [] : [pattern]
|
|
513
523
|
})
|
|
514
524
|
}
|
|
515
525
|
|