prunelle 0.7.4 → 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 +17 -15
- package/package.json +1 -1
- package/src/build/graph.ts +1 -1
- package/src/build/index.ts +1 -1
- package/src/build/island-promote.ts +1 -1
- package/src/build/output.ts +1 -1
- package/src/build/routes.ts +19 -1
- package/src/cli/check-links.ts +1 -1
- package/src/cli/check-security.ts +19 -4
- package/src/cli/check.ts +3 -2
- 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/emit.ts +1 -1
- package/src/compiler/shared.ts +9 -16
- package/src/dev/index.ts +1 -1
- package/src/dev/supervisor.ts +2 -2
- package/src/dom/attrs.ts +8 -0
- package/src/dom/island.ts +30 -4
- package/src/plugins/context.ts +18 -1
- package/src/plugins/services.ts +1 -0
- package/src/plugins/types.ts +1 -1
- package/src/server/action.ts +26 -18
- package/src/server/app-secret.ts +8 -9
- package/src/server/document.ts +5 -2
- 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/route-table.ts +24 -11
- package/src/server/security.ts +43 -12
- package/src/server/serve-handlers.ts +3 -3
- package/src/server/start.ts +2 -2
- package/src/server/stream.ts +4 -4
- package/src/ssr/navigation.ts +1 -1
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,23 +42,25 @@
|
|
|
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
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.
|
|
@@ -66,22 +68,22 @@
|
|
|
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
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.
|
|
@@ -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/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
|
@@ -176,7 +176,7 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
176
176
|
const stageDir = stageDirFor(finalOutDir, stageSuffix)
|
|
177
177
|
const outDir = options.static ? join(cacheBaseDir, `${STATIC_STAGE_PREFIX}${stageSuffix}`) : stageDir
|
|
178
178
|
const assetPrefix = normalizeAssetPrefix(options.assetPrefix ?? fileConfig.assetPrefix ?? '/_pru')
|
|
179
|
-
assertOwnOutDir(root, finalOutDir
|
|
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
|
|
@@ -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/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/cli/check-links.ts
CHANGED
|
@@ -494,7 +494,7 @@ function discoverCollectionDirs(root: string, plugins: readonly PrunellePlugin[]
|
|
|
494
494
|
for (const plugin of plugins) {
|
|
495
495
|
if (plugin.name !== '@prunellejs/content' || plugin.watchPaths === undefined) continue
|
|
496
496
|
try { (typeof plugin.watchPaths === 'function' ? plugin.watchPaths(root) : plugin.watchPaths).forEach(addDir) }
|
|
497
|
-
catch
|
|
497
|
+
catch {}
|
|
498
498
|
}
|
|
499
499
|
for (const [file, analysis] of analyses) {
|
|
500
500
|
if (isInNodeModules(file) || !isInside(root, file)) continue
|
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
// `prunelle check` warnings about what weakens an app's defences: dotfiles under public/, and the security opt-outs in its config.
|
|
2
2
|
|
|
3
3
|
import type { Node } from 'oxc-parser'
|
|
4
|
+
import type { ComplianceConfig } from '../compiler/compliance'
|
|
4
5
|
import type { SecurityHeadersOptions } from '../server/security'
|
|
5
6
|
import { relative } from 'node:path'
|
|
6
7
|
import { parseSync } from 'oxc-parser'
|
|
7
8
|
import { isHiddenPublicPath, walkAllFiles } from '../build/files'
|
|
8
9
|
import { walk } from '../compiler/ast'
|
|
10
|
+
import { isIgnoredAt, isRuleIgnored, parsePrunelleIgnores } from '../compiler/compliance'
|
|
9
11
|
import { formatDiagnostic, unwrapTsExpr } from '../compiler/shared'
|
|
10
12
|
import { resolveCspPolicy } from '../server/security'
|
|
11
13
|
|
|
@@ -120,12 +122,25 @@ export function securityConfigWarnings(security: SecurityHeadersOptions | false
|
|
|
120
122
|
|
|
121
123
|
const CSRF_OFF_RE = /export\s+const\s+csrf\s*=\s*false\b/g
|
|
122
124
|
|
|
123
|
-
/** One warning per route file that exports `csrf = false`: it accepts a cross-site POST, so it must check a signature or a token itself. */
|
|
124
|
-
export function csrfOffWarnings(files: readonly string[], read: (file: string) => string, locate: (file: string, offset: number) => string): string[] {
|
|
125
|
+
/** One warning per route file that exports `csrf = false`: it accepts a cross-site POST, so it must check a signature or a token itself. A route that does says so with `// prunelle-ignore security/csrf-off` above the export. */
|
|
126
|
+
export function csrfOffWarnings(files: readonly string[], read: (file: string) => string, locate: (file: string, offset: number) => string, compliance?: ComplianceConfig | undefined): string[] {
|
|
127
|
+
if (isRuleIgnored('security/csrf-off', compliance))
|
|
128
|
+
return []
|
|
125
129
|
const warnings: string[] = []
|
|
126
130
|
for (const file of files) {
|
|
127
|
-
|
|
128
|
-
|
|
131
|
+
const code = read(file)
|
|
132
|
+
const ignores = parsePrunelleIgnores(code)
|
|
133
|
+
for (const match of code.matchAll(CSRF_OFF_RE)) {
|
|
134
|
+
if (!isIgnoredAt(ignores, 'security/csrf-off', match.index))
|
|
135
|
+
warnings.push(formatDiagnostic(locate(file, match.index), '[security/csrf-off] this route skips the cross-site request check, so any site can post to it: keep it only for a webhook or bearer-token API that verifies a signature or token itself, and say so with `// prunelle-ignore security/csrf-off` above the export; drop `export const csrf = false` for anything a browser form posts to.', 'warning'))
|
|
136
|
+
}
|
|
129
137
|
}
|
|
130
138
|
return warnings
|
|
131
139
|
}
|
|
140
|
+
|
|
141
|
+
/** A warning when `trustProxy` is on and `site` is not: any `X-Forwarded-Host` then counts as the app's host, though a proxy that sets `Host` alone passes the client's one through. */
|
|
142
|
+
export function proxyWithoutSiteWarnings(trustProxy: boolean | number | undefined, site: string | undefined, compliance?: ComplianceConfig | undefined): string[] {
|
|
143
|
+
if (trustProxy === undefined || trustProxy === false || trustProxy === 0 || site !== undefined || isRuleIgnored('security/proxy-no-site', compliance))
|
|
144
|
+
return []
|
|
145
|
+
return [formatDiagnostic('prunelle.config.ts:1:1', '[security/proxy-no-site] trustProxy is on but site is not set, so the origin check and ctx.redirect take any X-Forwarded-Host as this app\'s host, even one a client sent past a proxy that does not overwrite it: set site: \'https://your.domain\' in prunelle.config.ts, and list any other domain the app answers on in trustedOrigins.', 'warning')]
|
|
146
|
+
}
|
package/src/cli/check.ts
CHANGED
|
@@ -24,7 +24,7 @@ import { normalizeConsentConfig } from '../server/consent'
|
|
|
24
24
|
import { checkAppForms } from './check-forms'
|
|
25
25
|
import { unresolvedImport } from './check-imports'
|
|
26
26
|
import { checkAppLinks } from './check-links'
|
|
27
|
-
import { csrfOffWarnings, externalRedirectWarnings, publicDotfileWarnings, securityConfigWarnings } from './check-security'
|
|
27
|
+
import { csrfOffWarnings, externalRedirectWarnings, proxyWithoutSiteWarnings, publicDotfileWarnings, securityConfigWarnings } from './check-security'
|
|
28
28
|
|
|
29
29
|
/** Whether `prunelle check` typechecked the app, with which tool, or why it did not. */
|
|
30
30
|
export type TypecheckRun = { ran: true, tool: string } | { ran: false, reason: string }
|
|
@@ -394,7 +394,8 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
|
|
|
394
394
|
|
|
395
395
|
warnings.push(...publicDotfileWarnings(publicDir, root))
|
|
396
396
|
warnings.push(...securityConfigWarnings(loadedConfig.security))
|
|
397
|
-
warnings.push(...
|
|
397
|
+
warnings.push(...proxyWithoutSiteWarnings(loadedConfig.trustProxy, site, compliance))
|
|
398
|
+
warnings.push(...csrfOffWarnings(routeFiles, file => sourceOf(file, sources), (file, offset) => locOf(root, file, sources, offset), compliance))
|
|
398
399
|
warnings.push(...externalRedirectWarnings(files, file => sourceOf(file, sources), (file, offset) => locOf(root, file, sources, offset)))
|
|
399
400
|
|
|
400
401
|
// 3e. Broken internal link checks (#3)
|
package/src/compiler/analyze.ts
CHANGED
|
@@ -308,6 +308,16 @@ function scanDeclarations(program: Program, filename: string, imports: ImportSca
|
|
|
308
308
|
scan.localInits.set(d.id.name, d.init)
|
|
309
309
|
}
|
|
310
310
|
}
|
|
311
|
+
// `import X from './x'; export default X` (or `export { X }`) re-exports './x', so islands and state behind it are followed like `export { default } from './x'`.
|
|
312
|
+
const reexportImported = (exported: string, local: string, start: number): void => {
|
|
313
|
+
for (const imp of imports.imports) {
|
|
314
|
+
const spec = imp.specifiers.find(s => s.local === local && s.imported !== '*')
|
|
315
|
+
if (spec !== undefined) {
|
|
316
|
+
scan.reexports.push({ exported, local: spec.imported, source: imp.source, start })
|
|
317
|
+
return
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
}
|
|
311
321
|
const addExport = (exported: string, local: string | undefined): void => {
|
|
312
322
|
scan.exportedNames.push(exported)
|
|
313
323
|
if (local !== undefined)
|
|
@@ -335,8 +345,10 @@ function scanDeclarations(program: Program, filename: string, imports: ImportSca
|
|
|
335
345
|
addExport('default', decl.type === 'Identifier' ? decl.name : named ?? 'default')
|
|
336
346
|
if (isAsyncFunction(decl))
|
|
337
347
|
scan.hasAsyncDefault = true
|
|
338
|
-
else if (decl.type === 'Identifier')
|
|
348
|
+
else if (decl.type === 'Identifier') {
|
|
339
349
|
scan.defaultLocal = decl.name
|
|
350
|
+
reexportImported('default', decl.name, stmt.start)
|
|
351
|
+
}
|
|
340
352
|
else
|
|
341
353
|
scan.localInits.set('default', decl)
|
|
342
354
|
}
|
|
@@ -349,7 +361,9 @@ function scanDeclarations(program: Program, filename: string, imports: ImportSca
|
|
|
349
361
|
addExport(exported, stmt.source === null ? local : undefined)
|
|
350
362
|
if (stmt.source !== null)
|
|
351
363
|
scan.reexports.push({ exported, local, source: stmt.source.value, start: stmt.start })
|
|
352
|
-
else
|
|
364
|
+
else
|
|
365
|
+
reexportImported(exported, local, stmt.start)
|
|
366
|
+
if (stmt.source === null && exported === 'default')
|
|
353
367
|
scan.defaultLocal = local
|
|
354
368
|
}
|
|
355
369
|
if (stmt.declaration !== null)
|
|
@@ -41,6 +41,8 @@ export type ComplianceRule =
|
|
|
41
41
|
| 'lcen/legal-notice'
|
|
42
42
|
| 'rgaa/document-lang'
|
|
43
43
|
| 'rgaa/accessibility-statement'
|
|
44
|
+
| 'security/csrf-off'
|
|
45
|
+
| 'security/proxy-no-site'
|
|
44
46
|
| FormWarningRule
|
|
45
47
|
|
|
46
48
|
/** The warnings of the form-vs-action check (`cli/check-forms.ts`), silenced like the compliance rules. */
|
|
@@ -69,6 +71,8 @@ const COMPLIANCE_RULES = new Set<ComplianceRule>([
|
|
|
69
71
|
'lcen/legal-notice',
|
|
70
72
|
'rgaa/document-lang',
|
|
71
73
|
'rgaa/accessibility-statement',
|
|
74
|
+
'security/csrf-off',
|
|
75
|
+
'security/proxy-no-site',
|
|
72
76
|
'action/unguarded-public-form',
|
|
73
77
|
'form/invalid-option',
|
|
74
78
|
'form/schema-unsupported',
|
|
@@ -156,7 +156,10 @@ function emitDomExprAttr(
|
|
|
156
156
|
}
|
|
157
157
|
else if (DOM_PROPS.has(name)) {
|
|
158
158
|
const targetOps = isSelect && name === 'value' ? postChildOps : ops
|
|
159
|
-
|
|
159
|
+
// Only a <select multiple> pulls in setSelectValues, so other pages ship none of it.
|
|
160
|
+
const multiple = isSelect && name === 'value' && ctx.el.openingElement.attributes.some(a => a.type === 'JSXAttribute' && jsxTagName(a.name) === 'multiple')
|
|
161
|
+
const call = multiple ? `${use('setSelectValues')}(${elVar}, ${exprCode})` : `${use('setProp')}(${elVar}, ${JSON.stringify(name)}, ${exprCode})`
|
|
162
|
+
targetOps.push(wrapDomOp(call, isStatic, use))
|
|
160
163
|
}
|
|
161
164
|
else {
|
|
162
165
|
ops.push(wrapDomOp(`${use('setAttr')}(${elVar}, ${JSON.stringify(name)}, ${exprCode})`, isStatic, use))
|
package/src/compiler/emit.ts
CHANGED
|
@@ -20,7 +20,7 @@ export const DELEGATED_EVENTS = new Set([
|
|
|
20
20
|
])
|
|
21
21
|
|
|
22
22
|
// Helpers kept out of the dom core, which every island loads: a page pays for them only when one of its islands binds them.
|
|
23
|
-
const ATTR_HELPERS = ['setAttr', 'setClass', 'setProp', 'setStyle']
|
|
23
|
+
const ATTR_HELPERS = ['setAttr', 'setClass', 'setProp', 'setSelectValues', 'setStyle']
|
|
24
24
|
const CLAIM_HELPERS = ['eachStatic']
|
|
25
25
|
const EXTRA_HELPERS = ['catchBoundary', 'fragInsert', 'insert', 'mergeProps', 'omit', 'propDefault', 'setInnerHtml', 'show', 'spread']
|
|
26
26
|
|
package/src/compiler/shared.ts
CHANGED
|
@@ -367,28 +367,21 @@ type PrunelleTag = 'Head' | 'Region' | 'Suspense' | 'ConsentGate' | 'ConsentBann
|
|
|
367
367
|
|
|
368
368
|
const PRUNELLE_TAGS = new Set<string>(['Head', 'Region', 'Suspense', 'ConsentGate', 'ConsentBanner', 'ConsentPreferences', 'Catch'])
|
|
369
369
|
|
|
370
|
-
/** Resolves a JSX tag (direct, aliased, or namespaced via `prunelle`) to its canonical Prunelle tag. */
|
|
370
|
+
/** Resolves a JSX tag (direct, aliased, or namespaced via `prunelle`) to its canonical Prunelle tag; a tag not imported from `prunelle`, such as a component the file declares, is never one. */
|
|
371
371
|
export function resolvePrunelleTag(tag: string, imports: readonly PrunelleTagBinding[]): PrunelleTag | undefined {
|
|
372
|
-
let boundElsewhere = false
|
|
373
372
|
for (const imp of imports) {
|
|
374
|
-
|
|
373
|
+
if (imp.source !== 'prunelle')
|
|
374
|
+
continue
|
|
375
375
|
for (const spec of imp.specifiers) {
|
|
376
|
-
if (
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
return member as PrunelleTag
|
|
383
|
-
}
|
|
384
|
-
}
|
|
385
|
-
else if (spec.local === tag) {
|
|
386
|
-
boundElsewhere = true
|
|
376
|
+
if (spec.local === tag && PRUNELLE_TAGS.has(spec.imported))
|
|
377
|
+
return spec.imported as PrunelleTag
|
|
378
|
+
if (spec.imported === '*' && tag.startsWith(`${spec.local}.`)) {
|
|
379
|
+
const member = tag.slice(spec.local.length + 1)
|
|
380
|
+
if (PRUNELLE_TAGS.has(member))
|
|
381
|
+
return member as PrunelleTag
|
|
387
382
|
}
|
|
388
383
|
}
|
|
389
384
|
}
|
|
390
|
-
if (!boundElsewhere && PRUNELLE_TAGS.has(tag))
|
|
391
|
-
return tag as PrunelleTag
|
|
392
385
|
return undefined
|
|
393
386
|
}
|
|
394
387
|
|
package/src/dev/index.ts
CHANGED
|
@@ -98,7 +98,7 @@ async function handleAppFetch(
|
|
|
98
98
|
if (state.lastError !== undefined)
|
|
99
99
|
return buildErrorResponse(request, state.lastError, state.reloadAssets.script)
|
|
100
100
|
|
|
101
|
-
const res = await state.app!.handle(request, remoteIp)
|
|
101
|
+
const res = await state.app!.handle(request, remoteIp, seconds => srv.timeout(request, seconds))
|
|
102
102
|
const ct = res.headers.get('content-type') ?? ''
|
|
103
103
|
const isStreamedHtml = ct.includes('text/html') && request.method !== 'HEAD' && res.body !== null && !res.headers.has('content-length')
|
|
104
104
|
if (ct.includes('text/event-stream') || isStreamedHtml)
|
package/src/dev/supervisor.ts
CHANGED
|
@@ -162,6 +162,8 @@ export async function devSupervisor(options: DevSupervisorOptions): Promise<{ ur
|
|
|
162
162
|
const child = await ready
|
|
163
163
|
if (child === undefined)
|
|
164
164
|
return buildErrorResponse(request, crashed ?? 'prunelle dev: the app process is not running.', reloadAssets.script)
|
|
165
|
+
// The app process keeps its own idle timeout, which a stream or a route's `export const idleTimeout` sets, so this hop waits on it alone.
|
|
166
|
+
srv.timeout(request, 0)
|
|
165
167
|
const headers = new Headers(request.headers)
|
|
166
168
|
headers.set(DEV_CLIENT_IP_HEADER, srv.requestIP(request)?.address ?? '')
|
|
167
169
|
try {
|
|
@@ -173,8 +175,6 @@ export async function devSupervisor(options: DevSupervisorOptions): Promise<{ ur
|
|
|
173
175
|
redirect: 'manual',
|
|
174
176
|
signal: request.signal,
|
|
175
177
|
})
|
|
176
|
-
if (!res.headers.has('content-length'))
|
|
177
|
-
srv.timeout(request, 0)
|
|
178
178
|
return res
|
|
179
179
|
}
|
|
180
180
|
catch (err) {
|
package/src/dom/attrs.ts
CHANGED
|
@@ -71,6 +71,14 @@ export function setProp(el: Element, name: string, value: unknown): void {
|
|
|
71
71
|
rec[name] = next
|
|
72
72
|
}
|
|
73
73
|
|
|
74
|
+
/** The `value` of a `<select multiple>`: an array selects the options it lists, as SSR renders them; anything else is a plain value. */
|
|
75
|
+
export function setSelectValues(el: HTMLSelectElement, value: unknown): void {
|
|
76
|
+
if (!Array.isArray(value) || !el.multiple)
|
|
77
|
+
return setProp(el, 'value', value)
|
|
78
|
+
for (const option of el.options)
|
|
79
|
+
option.selected = value.some(v => String(v) === option.value)
|
|
80
|
+
}
|
|
81
|
+
|
|
74
82
|
export function setStyle(el: HTMLElement, value: unknown): void {
|
|
75
83
|
if (value == null || value === false) {
|
|
76
84
|
el.removeAttribute('style')
|
package/src/dom/island.ts
CHANGED
|
@@ -71,7 +71,7 @@ function collectVisibleTargets(root: Element, out: Element[]): void {
|
|
|
71
71
|
function replayEvent(root: Element, ev: Event, target: EventTarget | null): void {
|
|
72
72
|
if (target === null || typeof target.dispatchEvent !== 'function')
|
|
73
73
|
return
|
|
74
|
-
if (typeof (target as Node).nodeType === 'number' && !root.contains(target as Node))
|
|
74
|
+
if (typeof (target as Node).nodeType === 'number' && target !== document && !root.contains(target as Node))
|
|
75
75
|
return
|
|
76
76
|
const init: EventInit = { bubbles: ev.bubbles, cancelable: ev.cancelable, composed: ev.composed }
|
|
77
77
|
let clone: Event
|
|
@@ -90,16 +90,31 @@ function replayEvent(root: Element, ev: Event, target: EventTarget | null): void
|
|
|
90
90
|
target.dispatchEvent(clone)
|
|
91
91
|
}
|
|
92
92
|
|
|
93
|
+
const MODIFIERS = ['Alt', 'Control', 'Meta', 'Shift']
|
|
94
|
+
|
|
95
|
+
// True when the key is one an element inside names with `aria-keyshortcuts="Control+K Meta+K"`, with exactly its modifiers held.
|
|
96
|
+
function isKeyShortcut(root: Element, e: KeyboardEvent): boolean {
|
|
97
|
+
for (const el of root.querySelectorAll('[aria-keyshortcuts]')) {
|
|
98
|
+
for (const combo of el.getAttribute('aria-keyshortcuts')!.split(' ')) {
|
|
99
|
+
const parts = combo.split('+')
|
|
100
|
+
if (parts.pop()!.toLowerCase() === e.key?.toLowerCase() && MODIFIERS.every(m => e.getModifierState(m) === parts.includes(m)))
|
|
101
|
+
return true
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return false
|
|
105
|
+
}
|
|
106
|
+
|
|
93
107
|
// A failed load keeps the listeners and drops the queued events: the next interaction loads the chunk again and is replayed once it is in.
|
|
108
|
+
// A shortcut the island declares is heard on the whole page, kept from the browser, and replayed on the document, where the component listens for it.
|
|
94
109
|
function watchInteraction(root: Element, onTrigger: (after: () => void) => Promise<boolean>): () => void {
|
|
95
110
|
const evs = ['pointerdown', 'click', 'focusin', 'keydown']
|
|
96
111
|
const queued: { ev: Event, target: EventTarget | null }[] = []
|
|
97
112
|
let loading = false
|
|
98
|
-
const go = (ev: Event) => {
|
|
113
|
+
const go = (ev: Event, target = ev.target) => {
|
|
99
114
|
// Prevent native toggle/submit/navigation before hydration so replaying the click triggers it once with handlers attached.
|
|
100
115
|
if (ev.type === 'click')
|
|
101
116
|
ev.preventDefault()
|
|
102
|
-
queued.push({ ev, target
|
|
117
|
+
queued.push({ ev, target })
|
|
103
118
|
if (!loading) {
|
|
104
119
|
loading = true
|
|
105
120
|
void onTrigger(() => {
|
|
@@ -113,9 +128,18 @@ function watchInteraction(root: Element, onTrigger: (after: () => void) => Promi
|
|
|
113
128
|
})
|
|
114
129
|
}
|
|
115
130
|
}
|
|
131
|
+
const onShortcut = (ev: Event) => {
|
|
132
|
+
if (!isKeyShortcut(root, ev as KeyboardEvent))
|
|
133
|
+
return
|
|
134
|
+
ev.preventDefault()
|
|
135
|
+
if (!root.contains(ev.target as Node))
|
|
136
|
+
go(ev, document)
|
|
137
|
+
}
|
|
116
138
|
for (const e of evs) root.addEventListener(e, go, true)
|
|
139
|
+
addEventListener('keydown', onShortcut, true)
|
|
117
140
|
return () => {
|
|
118
141
|
for (const e of evs) root.removeEventListener(e, go, true)
|
|
142
|
+
removeEventListener('keydown', onShortcut, true)
|
|
119
143
|
}
|
|
120
144
|
}
|
|
121
145
|
|
|
@@ -300,7 +324,9 @@ export function defineIslandElement(): void {
|
|
|
300
324
|
return true
|
|
301
325
|
}
|
|
302
326
|
this._d = dispose
|
|
303
|
-
|
|
327
|
+
// Queued behind the component's `onMount` callbacks, so a listener it binds there hears the replayed event.
|
|
328
|
+
if (after)
|
|
329
|
+
queueMicrotask(after)
|
|
304
330
|
return true
|
|
305
331
|
}
|
|
306
332
|
catch (err) {
|
package/src/plugins/context.ts
CHANGED
|
@@ -86,9 +86,26 @@ async function runImporting<T>(ctx: AppRuntimeContext, load: () => Promise<T>):
|
|
|
86
86
|
}
|
|
87
87
|
}
|
|
88
88
|
|
|
89
|
+
// A frame of module top-level code prints with no function name and no parentheses: `at /app/prunelle.config.ts:3:1`.
|
|
90
|
+
const MODULE_FRAME_RE = /^\s*at [^\s(]+:\d+:\d+$/m
|
|
91
|
+
|
|
92
|
+
// Bun drops `inImport` too in a module's top-level code, so a call made there, while an import is running, is told apart by the module frame on its stack; queuing it would wait on the import that awaits it.
|
|
93
|
+
function calledFromImportedModule(): boolean {
|
|
94
|
+
if (importState.current === undefined)
|
|
95
|
+
return false
|
|
96
|
+
const limit = Error.stackTraceLimit
|
|
97
|
+
Error.stackTraceLimit = 50
|
|
98
|
+
try {
|
|
99
|
+
return MODULE_FRAME_RE.test(new Error('stack').stack ?? '')
|
|
100
|
+
}
|
|
101
|
+
finally {
|
|
102
|
+
Error.stackTraceLimit = limit
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
89
106
|
/** Imports with `ctx` as the app context, the imported modules' top-level code included. */
|
|
90
107
|
export async function importWithAppContext<T>(ctx: AppRuntimeContext, load: () => Promise<T>): Promise<T> {
|
|
91
|
-
if (importState.inImport.getStore() === true)
|
|
108
|
+
if (importState.inImport.getStore() === true || calledFromImportedModule())
|
|
92
109
|
return runImporting(ctx, load)
|
|
93
110
|
const prev = importState.tail
|
|
94
111
|
let release!: () => void
|